From 6fde935916578d01201fd8b8276808c3d7cacc08 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 14:12:36 -0800 Subject: [PATCH 01/17] Add an MDP2 reset event over the shared reset-state API Add isaaclab_experimental.mdp2.mdp.reset_from_bank, which composes a ResetStateBuffer (states), a ResetStateSampler (choice) and a gather into the event outputs (restore). Fills are callables: FillFromCandidates rolls a candidates task, rejects with its terminations and spreads with its descriptor group; FillFromStates takes given states. Banks are per world by default or shared, with poses relative to env origins. Let ResetStateSampler.reset take caller-owned per-world seeds, so MDP2's random streams drive the draws, and give MDP2 init hooks the use's cache so the bank is built once at startup. Port Isaac-Lift-KukaAllegro-MDP2 to the library term with the core Lift sampler settings, and remove its task-local reset bank. --- .../isaaclab_experimental.mdp2.mdp.rst | 6 + docs/source/how-to/reset_state_buffers.rst | 42 +++ .../changelog.d/mdp2-resets.added.rst | 2 + source/isaaclab/changelog.d/mdp2-resets.minor | 0 .../envs/reset/reset_state_sampler.py | 21 +- .../test/envs/test_reset_state_sampler.py | 19 ++ .../changelog.d/mdp2-resets.added.rst | 5 + .../changelog.d/mdp2-resets.minor | 0 .../isaaclab_experimental/mdp2/eager.py | 5 +- .../mdp2/mdp/__init__.pyi | 5 + .../mdp2/mdp/reset_states.py | 249 +++++++++++++++++ .../test/mdp2/test_mdp2_reset_states.py | 216 +++++++++++++++ .../changelog.d/mdp2-resets.changed.rst | 2 + .../mdp2/lift_kuka_allegro/lift_env_cfg.py | 18 +- .../mdp2/lift_kuka_allegro/reset_bank.py | 250 ------------------ .../test/mdp2/test_lift_kuka_allegro.py | 30 ++- 16 files changed, 600 insertions(+), 270 deletions(-) create mode 100644 source/isaaclab/changelog.d/mdp2-resets.added.rst create mode 100644 source/isaaclab/changelog.d/mdp2-resets.minor create mode 100644 source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst create mode 100644 source/isaaclab_experimental/changelog.d/mdp2-resets.minor create mode 100644 source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py create mode 100644 source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py create mode 100644 source/isaaclab_tasks/changelog.d/mdp2-resets.changed.rst delete mode 100644 source/isaaclab_tasks/isaaclab_tasks/mdp2/lift_kuka_allegro/reset_bank.py diff --git a/docs/source/api/lab_experimental/isaaclab_experimental.mdp2.mdp.rst b/docs/source/api/lab_experimental/isaaclab_experimental.mdp2.mdp.rst index e9c26d8e323e..78bfd3c65e3b 100644 --- a/docs/source/api/lab_experimental/isaaclab_experimental.mdp2.mdp.rst +++ b/docs/source/api/lab_experimental/isaaclab_experimental.mdp2.mdp.rst @@ -21,6 +21,12 @@ Events .. automodule:: isaaclab_experimental.mdp2.mdp.events :members: +Reset states +------------ + +.. automodule:: isaaclab_experimental.mdp2.mdp.reset_states + :members: + Rewards ------- diff --git a/docs/source/how-to/reset_state_buffers.rst b/docs/source/how-to/reset_state_buffers.rst index 42546d35d257..d2ca887c73e7 100644 --- a/docs/source/how-to/reset_state_buffers.rst +++ b/docs/source/how-to/reset_state_buffers.rst @@ -124,6 +124,10 @@ Set ``ResetStateSamplerCfg.seed`` to initialize the sampler's per-environment ra Use ``sampler.reseed(seed)`` between rollouts to restart those streams while retaining history and assignments. A captured graph observes the new streams. +A framework that owns its random streams passes them instead: ``sampler.reset(mask, rng=seeds)`` +takes one int32 seed per environment, draws ``wp.randf(wp.rand_init(seeds[env], 0))``, and leaves +the internal streams untouched. The caller advances its seeds between resets, as MDP2 does. + Configure useful practice -------------------------- @@ -204,6 +208,44 @@ that took at least one step. The event credits the existing success reward's sti flag before the reward manager clears it and restores root-link poses, COM velocities, joints, and controller targets through public mask writers. +Use the MDP2 reset event +------------------------ + +MDP2 tasks use ``isaaclab_experimental.mdp2.mdp.reset_from_bank``. It composes the same three parts: +a fill builds a :class:`~isaaclab.envs.reset.ResetStateBuffer` once at startup, a +:class:`~isaaclab.envs.reset.ResetStateSampler` credits each ended episode and draws the next start +from the use's random stream, and the event gathers the drawn states into its ``outputs``, which +MDP2 commits. The outputs are the state: any writable scene fields. + +.. code-block:: python + + from isaaclab_experimental import mdp2 + from isaaclab_experimental.mdp2 import mdp + + "reset": mdp2.Event( + mdp.reset_from_bank, + inputs={"succeeded": mdp2.quantities.success}, + outputs={"joint_pos": robot.joint_pos, "object_pose_w": target.root_link_pose_w}, + params={ + "fill": mdp.FillFromCandidates(CANDIDATES, bank_size=16), + "sampler": ResetStateSamplerCfg(scores=[BetaSamplingScoreCfg(target=0.5)]), + }, + ) + +* ``fill`` returns the states. :class:`~isaaclab_experimental.mdp2.mdp.reset_states.FillFromCandidates` rolls the reset events of a + ``candidates`` task, keeps the states its terminations accept, and, given a ``descriptor`` + observation group, keeps the most spread of an oversampled harvest. :class:`~isaaclab_experimental.mdp2.mdp.reset_states.FillFromStates` + takes given states, such as states saved from an earlier fill or demonstrations. +* ``sampler`` weighs states by recent success; ``None`` draws uniformly. Binding ``succeeded`` + credits each ended episode to the state it started from. +* ``shared`` selects one bank for every world instead of one bank per world. Bind + ``env_origins`` so poses are stored relative to each world's origin. Share a bank only between + worlds whose states fit each other, such as worlds that spawn the same object. + +Place the event after the other reset events: it overwrites the outputs they wrote. The init +hook warms every kernel, so the event is captured with the rest of the step. +``Isaac-Lift-KukaAllegro-MDP2`` uses a bank per world with the core Lift sampler settings. + Migrating existing reset configurations --------------------------------------- diff --git a/source/isaaclab/changelog.d/mdp2-resets.added.rst b/source/isaaclab/changelog.d/mdp2-resets.added.rst new file mode 100644 index 000000000000..a65bf391c462 --- /dev/null +++ b/source/isaaclab/changelog.d/mdp2-resets.added.rst @@ -0,0 +1,2 @@ +* Added an optional ``rng`` argument to :meth:`~isaaclab.envs.reset.ResetStateSampler.reset` so that callers' + per-environment int32 seeds, such as MDP2's random streams, drive the draws. diff --git a/source/isaaclab/changelog.d/mdp2-resets.minor b/source/isaaclab/changelog.d/mdp2-resets.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab/isaaclab/envs/reset/reset_state_sampler.py b/source/isaaclab/isaaclab/envs/reset/reset_state_sampler.py index 891241206dec..95dc07fa240f 100644 --- a/source/isaaclab/isaaclab/envs/reset/reset_state_sampler.py +++ b/source/isaaclab/isaaclab/envs/reset/reset_state_sampler.py @@ -166,6 +166,7 @@ def reset( success: wp.array | ProxyArray | torch.Tensor | None = None, valid: wp.array | ProxyArray | torch.Tensor | None = None, state_ids: wp.array | ProxyArray | torch.Tensor | None = None, + rng: wp.array | ProxyArray | torch.Tensor | None = None, ) -> ProxyArray: """Record previous outcomes and assign starts for selected environments. @@ -183,6 +184,9 @@ def reset( success: Previous episode success flags, shape [num_envs]. Omit at startup. valid: Completed-episode mask, shape [num_envs]. Exclude unfinished manual resets. state_ids: Explicit catalog labels, shape [num_envs]. Omit to sample from scores. + rng: Caller-owned int32 seeds, shape [num_envs]. Each draw is then + ``wp.randf(wp.rand_init(rng[env], 0))`` and the internal streams are untouched; + the caller advances its seeds between resets. Omit to use the internal streams. Returns: Borrowed persistent full-environment ID assignments. Initially unassigned environments contain -1. @@ -196,6 +200,11 @@ def reset( else: self._resolve_requested_indices(selection, state_ids) # Credit the old assignments, then score and select their replacements. + seeds = None + if rng is not None: + seeds = self._input(rng, self.num_envs) + if seeds.dtype != wp.int32: + raise TypeError("rng must use the int32 dtype.") if success is not None: self._record_completed_outcomes(selection, success, valid) if self._scores: @@ -213,6 +222,7 @@ def reset( self._cdf, self._catalog_ids, self._rng, + seeds, self._assigned_indices, self.state_ids.warp, ], @@ -528,6 +538,7 @@ def _assign_reset_states( cumulative: wp.array(dtype=wp.float64), catalog_ids: wp.array(dtype=wp.int64), rng: wp.array(dtype=wp.uint32), + seeds: wp.array(dtype=wp.int32), assigned_indices: wp.array(dtype=wp.int32), state_ids: wp.array(dtype=wp.int64), ): @@ -538,9 +549,13 @@ def _assign_reset_states( index = requested[env] else: start = env_group_ids[env] * group_size - rng_state = rng[env] - uniform = wp.randf(rng_state) - rng[env] = rng_state + uniform = float(0.0) + if seeds: + uniform = wp.randf(wp.rand_init(seeds[env], 0)) + else: + rng_state = rng[env] + uniform = wp.randf(rng_state) + rng[env] = rng_state index = sample_cdf(cumulative, start, group_size, uniform) assigned_indices[env] = index state_ids[env] = catalog_ids[index] diff --git a/source/isaaclab/test/envs/test_reset_state_sampler.py b/source/isaaclab/test/envs/test_reset_state_sampler.py index 5f2ef73722dd..cf0be2427c8a 100644 --- a/source/isaaclab/test/envs/test_reset_state_sampler.py +++ b/source/isaaclab/test/envs/test_reset_state_sampler.py @@ -228,3 +228,22 @@ def reset_cycle(instance): np.testing.assert_array_equal(sampler.episode_counts.warp.numpy(), counts) np.testing.assert_array_equal(sampler.probabilities.warp.numpy(), probabilities) assert sampler.cfg.seed == 27 + + +def test_caller_seeds_decide_draws_and_leave_internal_streams_untouched(): + device = "cpu" + num_envs, num_states = 64, 8 + sampler = ResetStateSampler(ResetStateSamplerCfg(scores=[]), num_envs, num_states, device) + reference = ResetStateSampler(ResetStateSamplerCfg(scores=[]), num_envs, num_states, device) + seeds = wp.array(np.arange(num_envs, dtype=np.int32) * 7919, dtype=wp.int32, device=device) + + first = sampler.reset(rng=seeds).warp.numpy().copy() + assert not np.array_equal(sampler.reset().warp.numpy(), first) # internal stream still advances alone + np.testing.assert_array_equal(sampler.reset(rng=seeds).warp.numpy(), first) # same seeds, same draws + assert len(set(first.tolist())) > 1 + + # The internal streams were consumed once, as by one unseeded reset of the reference. + reference.reset() + np.testing.assert_array_equal(sampler.reset().warp.numpy(), reference.reset().warp.numpy()) + with pytest.raises(TypeError): + sampler.reset(rng=wp.zeros(num_envs, dtype=wp.int64, device=device)) diff --git a/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst b/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst new file mode 100644 index 000000000000..05b37df96af0 --- /dev/null +++ b/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst @@ -0,0 +1,5 @@ +* Added ``isaaclab_experimental.mdp2.mdp.reset_from_bank``, an MDP2 reset event that restores start states from a + :class:`~isaaclab.envs.reset.ResetStateBuffer` drawn by a :class:`~isaaclab.envs.reset.ResetStateSampler`, with + ``FillFromCandidates`` and ``FillFromStates`` to fill the bank per world or shared across worlds. +* Added ``cache`` to :class:`~isaaclab_experimental.mdp2.TermContext`, so init hooks can build host objects that the + use's Python hooks reuse. diff --git a/source/isaaclab_experimental/changelog.d/mdp2-resets.minor b/source/isaaclab_experimental/changelog.d/mdp2-resets.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/eager.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/eager.py index 398191cfbb1f..7771e3babd3c 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/eager.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/eager.py @@ -13,7 +13,7 @@ from __future__ import annotations from collections.abc import Callable, Mapping -from dataclasses import dataclass +from dataclasses import dataclass, field from typing import Any import torch @@ -37,6 +37,8 @@ class TermContext: # The selectors bound to the inputs, by argument name selectors: Mapping[str, FieldSelector | SubsetSelector | Entity] scene_data: SceneData # The scene, whose entity objects the hook may read + # Host objects that the use's Python hooks get as ``cache``, such as a buffer the init hook builds once + cache: dict[str, Any] = field(default_factory=dict) def entity(self, argument: str) -> Any: """Return the scene object, such as an articulation, of an entity input or of the entity an input selects.""" @@ -61,5 +63,6 @@ def call_init(mdp: MDP, op: TermOp, state: MDPState, hook: Callable) -> None: rng=state.rng.torch[op.stream] if op.random else None, selectors=op.inputs, scene_data=state.scene_data, + cache=state.caches.setdefault(op.name, {}), ) hook(context, **op.params) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi index 28b43c3dd68a..1786c05e6dc4 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi @@ -18,6 +18,10 @@ __all__ = [ "reset_joints_by_offset", "reset_joints_by_scale", "reset_root_state_uniform", + "FillFromCandidates", + "FillFromStates", + "farthest_points", + "reset_from_bank", "base_ang_vel", "base_lin_vel", "generated_commands", @@ -72,6 +76,7 @@ from .events import ( reset_joints_by_scale, reset_root_state_uniform, ) +from .reset_states import FillFromCandidates, FillFromStates, farthest_points, reset_from_bank from .observations import ( base_ang_vel, base_lin_vel, diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py new file mode 100644 index 000000000000..efbc5155b50b --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py @@ -0,0 +1,249 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Reset from a bank of start states: the MDP2 term over :mod:`isaaclab.envs.reset`. + +The term composes three parts that are chosen independently: + +- the states, a :class:`~isaaclab.envs.reset.ResetStateBuffer` that a fill builds once at startup; +- the choice, a :class:`~isaaclab.envs.reset.ResetStateSampler` that credits each ended episode to the state it + started from and draws the next one, from the use's random stream; +- the restore, which gathers the drawn states into the event's ``outputs``. + +The outputs are the state: any writable fields, such as ``robot.joint_pos`` and ``object.root_link_pose_w``. A fill is +a callable ``fill(ctx, shared) -> {output: tensor}`` that returns, per output, ``(num_worlds, bank_size, ...)`` states +for a bank per world, or ``(bank_size, ...)`` for one bank that every world shares. +""" + +from __future__ import annotations + +import functools +from collections.abc import Callable, Mapping +from dataclasses import dataclass +from typing import Any + +import torch +import warp as wp + +from isaaclab.envs.reset import ResetStateBuffer, ResetStateSampler, ResetStateSamplerCfg +from isaaclab.utils.warp import ProxyArray + +from ..builder import MDPBuilder +from ..config import TaskCfg +from ..eager import TermContext +from ..runtime import evaluate, reset, startup +from ..terms import Term + + +@dataclass(frozen=True) +class FillFromStates: + """Fill the bank with given states, such as states saved from an earlier fill or demonstrations. + + ``states`` maps each output to ``(num_worlds, bank_size, ...)`` states, or ``(bank_size, ...)`` for a shared bank, + in the frame the event restores: poses relative to the environment origins when the use binds ``env_origins``. + """ + + states: Mapping[str, torch.Tensor] + + def __call__(self, ctx: TermContext, shared: bool) -> dict[str, torch.Tensor]: + return {name: value.to(ctx.rng.device) for name, value in self.states.items()} + + +@dataclass(frozen=True) +class FillFromCandidates: + """Fill the bank by rejection sampling the reset events of a ``candidates`` task. + + The candidates' reset events draw a state in every world, and the states that none of its terminations reject are + kept. If the task has a ``descriptor`` observation group, ``oversample_factor`` times as many states are harvested + and the ones most spread over the descriptor are kept. + """ + + candidates: TaskCfg + bank_size: int + oversample_factor: float = 2.0 + max_rolls: int = 2000 + + def __call__(self, ctx: TermContext, shared: bool) -> dict[str, torch.Tensor]: + num_worlds, device = ctx.num_worlds, ctx.rng.device + builder = MDPBuilder(ctx.scene_data.schema) + builder.add_task(self.candidates) + mdp = builder.finalize(device=str(device), backend="warp") + state, transition = mdp.state(ctx.scene_data, seed=int(ctx.rng[0])), mdp.transition() + startup(mdp, state) + + descriptor = transition.observations.get("descriptor") + size = self.bank_size if descriptor is None else round(self.bank_size * self.oversample_factor) + if self.bank_size < 1 or size < self.bank_size: + raise ValueError("The bank must harvest at least as many states as it keeps, and keep at least one.") + fields = dict(ctx.outputs) + if descriptor is not None: + fields["descriptor"] = descriptor.torch + # Root poses are kept relative to the environment origins when the use binds them. + origins = ctx.inputs.get("env_origins") + poses = {name for name in ctx.outputs if origins is not None and _warp_view(ctx, name).dtype == wp.transformf} + + rows = (num_worlds, size) if not shared else (size,) + harvest = {name: value.new_zeros(*rows, *value.shape[1:]) for name, value in fields.items()} + filled = torch.zeros(num_worlds if not shared else 1, dtype=torch.long, device=device) + worlds = torch.arange(num_worlds, device=device) + mask = ProxyArray(wp.ones(num_worlds, dtype=wp.bool, device=str(device))) + commit = functools.partial(ctx.scene_data.commit, mask.warp, mdp.reset_writes) + for _ in range(self.max_rolls): + reset(mdp, state, mask, commit) + commit() + evaluate(mdp, state, transition) + accepted = ~transition.terminated.torch + values = {name: _minus_origin(value, origins) if name in poses else value for name, value in fields.items()} + if shared: + take = worlds[accepted][: size - int(filled)] + for name, value in values.items(): + harvest[name][int(filled) : int(filled) + len(take)] = value[take] + filled += len(take) + else: + take = accepted & (filled < size) + slot = filled.clamp(max=size - 1) + for name, value in values.items(): + harvest[name][worlds, slot] = torch.where(_rows(take, value), value, harvest[name][worlds, slot]) + filled += take + if (filled == size).all(): + break + else: + raise RuntimeError( + f"The reset bank harvested fewer than {size} valid start states after {self.max_rolls} rolls of the" + f" candidates ({filled.min().item()} in the worst {'bank' if shared else 'world'})." + ) + + if descriptor is not None: + # Keep the most spread states, each descriptor axis rescaled to unit span so that all axes count. + points = harvest.pop("descriptor") + points = points if not shared else points[None] + span = (points.amax(dim=(0, 1)) - points.amin(dim=(0, 1))).clamp(min=1e-6) + kept = farthest_points(points / span, self.bank_size) + if shared: + harvest = {name: value[kept[0]] for name, value in harvest.items()} + else: + harvest = {name: value[worlds[:, None], kept] for name, value in harvest.items()} + return harvest + + +def farthest_points(points: torch.Tensor, count: int) -> torch.Tensor: + """Return, for each batch of ``points`` of shape ``(batch, n, dim)``, the indices of ``count`` points spread as far + apart as possible.""" + batch = torch.arange(len(points), device=points.device) + chosen = torch.zeros(len(points), count, dtype=torch.long, device=points.device) + nearest = torch.full(points.shape[:2], float("inf"), device=points.device) + farthest = torch.zeros(len(points), dtype=torch.long, device=points.device) + for k in range(count): + chosen[:, k] = farthest + nearest = torch.minimum(nearest, (points - points[batch, farthest][:, None]).norm(dim=-1)) + farthest = nearest.argmax(dim=-1) + return chosen + + +def _init( + ctx: TermContext, + *, + fill: Callable[[TermContext, bool], dict[str, torch.Tensor]], + sampler: ResetStateSamplerCfg | None = None, + shared: bool = False, +) -> None: + """Fill the bank once, then build the sampler over it and bind the outputs it restores.""" + outputs = {name: _warp_view(ctx, name) for name in ctx.outputs} + if shared and "env_origins" not in ctx.inputs and any(value.dtype == wp.transformf for value in outputs.values()): + raise ValueError("A shared bank of poses needs the env_origins input, so that poses transfer across worlds.") + states = fill(ctx, shared) + if states.keys() != outputs.keys(): + raise ValueError(f"The fill returned states for {sorted(states)}, but the event writes {sorted(outputs)}.") + + num_worlds = ctx.num_worlds + leading = 1 if shared else 2 + bank_sizes = {value.shape[leading - 1] for value in states.values()} + if len(bank_sizes) != 1 or (not shared and any(value.shape[0] != num_worlds for value in states.values())): + raise ValueError("Every output needs the same number of states, per world unless the bank is shared.") + bank_size = bank_sizes.pop() + rows = { + name: wp.from_torch(value.reshape(-1, *value.shape[leading:]).contiguous(), dtype=outputs[name].dtype) + for name, value in states.items() + } + num_groups = 1 if shared else num_worlds + sampler_cfg = sampler if sampler is not None else ResetStateSamplerCfg(history_length=1, scores=[]) + device = outputs[next(iter(outputs))].device + groups = None if shared else wp.array(range(num_worlds), dtype=wp.int32, device=device) + origins = ctx.inputs.get("env_origins") + + ctx.cache.update( + bank=ResetStateBuffer(rows), + sampler=ResetStateSampler( + sampler_cfg, num_worlds, bank_size * num_groups, device, group_ids=groups, num_groups=num_groups + ), + outputs=outputs, + poses=[value for value in outputs.values() if value.dtype == wp.transformf] if origins is not None else [], + origins=None if origins is None else wp.from_torch(origins.contiguous(), dtype=wp.vec3f), + ) + # Load every kernel and the sampler's sort and scan scratch before a graph captures the hook: a reset of no worlds. + _reset_from_bank( + wp.zeros(num_worlds, dtype=wp.bool, device=device), ctx.cache, ctx.rng, ctx.inputs.get("succeeded") + ) + + +def _reset_from_bank(mask: Any, cache: dict, rng: Any, succeeded: Any = None, **_: Any) -> None: + """Credit the ended episodes, draw the next states, and write them to the masked worlds' outputs.""" + mask, rng = _as_warp(mask), _as_warp(rng) + sampler: ResetStateSampler = cache["sampler"] + success = None if succeeded is None else _as_warp(succeeded) + sampler.reset(mask, success=success, rng=rng) + cache["bank"].get_state(sampler.indices, out=cache["outputs"], mask=mask) + for pose in cache["poses"]: + wp.launch(_add_origin, mask.shape, [mask, cache["origins"], pose], device=pose.device) + + +reset_from_bank = Term(torch=_reset_from_bank, warp=_reset_from_bank, random=True, init=_init) +"""Restart the reset worlds from start states drawn from a bank, the MDP2 counterpart of MDP1's lift +``conditional_reset``. + +Params: ``fill``, a callable that returns the states, such as :class:`FillFromCandidates`; ``sampler``, a +:class:`~isaaclab.envs.reset.ResetStateSamplerCfg` that weighs the states by their recent success, or None to draw +uniformly; and ``shared``, whether every world draws from one bank rather than its own. Share a bank only between +worlds whose states fit each other: a state banked with one object spawned does not fit a world with another. + +Inputs: ``succeeded``, the ended episode's success, credited to the state it started from when bound; and +``env_origins``, which stores the poses relative to the environment origins so that a shared bank transfers across +worlds. + +Place it after the other reset events: it overwrites the outputs they wrote. The bank and the sampler's history persist +across episodes. +""" + + +@wp.kernel +def _add_origin(mask: wp.array(dtype=wp.bool), origins: wp.array(dtype=wp.vec3f), pose: wp.array(dtype=wp.transformf)): + world = wp.tid() + if mask[world]: + pose[world] = wp.transformf( + wp.transform_get_translation(pose[world]) + origins[world], wp.transform_get_rotation(pose[world]) + ) + + +def _warp_view(ctx: TermContext, name: str) -> wp.array: + """Return a Warp view of an output, keeping the element type of scene fields such as ``wp.transformf``.""" + selector = ctx.selectors[name] + if getattr(selector, "scene", False): + return ctx.scene_data.data(selector.entity, selector.field).warp + return wp.from_torch(ctx.outputs[name]) + + +def _minus_origin(pose: torch.Tensor, origins: torch.Tensor) -> torch.Tensor: + """Return root poses of shape ``(num_worlds, 7)`` relative to the environment origins.""" + relative = pose.clone() + relative[:, :3] -= origins + return relative + + +def _rows(take: torch.Tensor, value: torch.Tensor) -> torch.Tensor: + return take.view(-1, *[1] * (value.ndim - 1)) + + +def _as_warp(value: Any) -> wp.array: + return wp.from_torch(value) if isinstance(value, torch.Tensor) else value diff --git a/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py b/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py new file mode 100644 index 000000000000..35dc9be1e90a --- /dev/null +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py @@ -0,0 +1,216 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Tests for resetting MDP2 tasks from a bank of start states, on an analytic scene.""" + +from collections.abc import Collection + +import numpy as np +import pytest +import torch +import warp as wp +from isaaclab_experimental import mdp2 +from isaaclab_experimental.mdp2 import mdp + +from isaaclab.envs.reset import BetaSamplingScoreCfg, ResetStateSamplerCfg +from isaaclab.utils.warp import ProxyArray + +DEVICE = "cuda:0" if torch.cuda.is_available() else "cpu" + +pytestmark = pytest.mark.kitless + +robot, target, scene_entity = mdp2.Entity("robot"), mdp2.Entity("object"), mdp2.Entity("scene") +outputs = {"joint_pos": robot.joint_pos, "object_pose_w": target.root_link_pose_w} + + +class Scene: + """A robot with one joint, an object pose, and environment origins one meter apart along x.""" + + def __init__(self, num_worlds: int): + joints = mdp2.FieldSchema(("joints",), writable=True) + self.schema = mdp2.SceneSchema( + num_worlds=num_worlds, + step_dt=0.02, + entities={ + "robot": mdp2.EntitySchema(names={"joints": ("x",)}, fields={"joint_pos": joints}), + "object": mdp2.EntitySchema( + names={}, fields={"root_link_pose_w": mdp2.FieldSchema((), wp.transformf, writable=True)} + ), + "scene": mdp2.EntitySchema(names={}, fields={"env_origins": mdp2.FieldSchema((), wp.vec3f)}), + }, + ) + origins = np.zeros((num_worlds, 3), dtype=np.float32) + origins[:, 0] = np.arange(num_worlds) + identity = np.tile(np.array([0, 0, 0, 0, 0, 0, 1], dtype=np.float32), (num_worlds, 1)) + self._data = { + ("robot", "joint_pos"): ProxyArray(wp.zeros((num_worlds, 1), dtype=wp.float32, device=DEVICE)), + ("object", "root_link_pose_w"): ProxyArray(wp.array(identity, dtype=wp.transformf, device=DEVICE)), + ("scene", "env_origins"): ProxyArray(wp.array(origins, dtype=wp.vec3f, device=DEVICE)), + } + + def data(self, entity: str, field: str) -> ProxyArray: + return self._data[entity, field] + + def entity(self, name: str): + return self + + def commit(self, mask: wp.array, fields: Collection[mdp2.FieldSelector]) -> None: + """Nothing to commit: the fields are the simulation state.""" + + +@wp.func +def _draw(world: int, joint_pos: wp.array2d(dtype=float), object_pose_w: wp.array(dtype=wp.transformf), rng: wp.int32): + joint_pos[world, 0] = wp.randf(wp.rand_init(rng, 0), -1.0, 1.0) + position = wp.vec3(wp.randf(wp.rand_init(rng, 1), -1.0, 1.0), 0.0, 0.0) + object_pose_w[world] = wp.transformf(position, wp.quat_identity()) + + +def _draw_torch(mask, joint_pos, object_pose_w, rng): + samples = mdp2.uniform(rng, -1.0, 1.0, (2,)) + joint_pos[:, 0] = torch.where(mask, samples[:, 0], joint_pos[:, 0]) + object_pose_w[:, 0] = torch.where(mask, samples[:, 1], object_pose_w[:, 0]) + + +draw = mdp2.Term(torch=_draw_torch, warp=_draw, random=True) + + +@wp.func +def _outside(world: int, joint_pos: wp.array2d(dtype=float)) -> bool: + return wp.abs(joint_pos[world, 0]) > 0.5 + + +outside = mdp2.Term(torch=lambda joint_pos: joint_pos[:, 0].abs() > 0.5, warp=_outside) + + +@wp.func +def _positive(world: int, joint_pos: wp.array2d(dtype=float)) -> float: + return wp.where(joint_pos[world, 0] > 0.0, 1.0, 0.0) + + +positive = mdp2.Term(torch=lambda joint_pos: (joint_pos[:, 0] > 0.0).float(), warp=_positive) + +CANDIDATES = mdp2.TaskCfg( + events={"draw": mdp2.Event(draw, outputs=outputs)}, + terminations={"outside": mdp2.Termination(outside, inputs={"joint_pos": robot.joint_pos})}, +) + + +def build(scene: Scene, backend: str = "warp", **params) -> tuple[mdp2.MDP, mdp2.MDPState]: + """Build a task whose only reset event restores from a bank, credited by whether the joint ended positive.""" + inputs = params.pop("inputs", {"succeeded": mdp2.quantities.success}) + task = mdp2.TaskCfg( + quantities={"success": mdp2.Quantity(positive, inputs={"joint_pos": robot.joint_pos})}, + events={"reset": mdp2.Event(mdp.reset_from_bank, inputs=inputs, outputs=outputs, params=params)}, + ) + builder = mdp2.MDPBuilder(scene.schema) + builder.add_task(task) + task_mdp = builder.finalize(device=DEVICE, backend=backend) + state = task_mdp.state(scene, seed=3) + mdp2.startup(task_mdp, state) + return task_mdp, state + + +def reset(task_mdp, state, mask) -> None: + mdp2.reset(task_mdp, state, ProxyArray(wp.from_torch(torch.tensor(mask, device=DEVICE)))) + + +def bank_rows(state) -> dict[str, np.ndarray]: + return {name: value.warp.numpy() for name, value in state.caches["events.reset"]["bank"].states.items()} + + +def test_candidates_fill_each_world_with_valid_states_and_restore_only_reset_worlds(): + scene = Scene(num_worlds=8) + task_mdp, state = build(scene, fill=mdp.FillFromCandidates(CANDIDATES, bank_size=4)) + + banked = bank_rows(state)["joint_pos"].reshape(8, 4) + assert np.all(np.abs(banked) <= 0.5) and len(np.unique(banked)) == 32 + + reset(task_mdp, state, [True] * 8) + joint_pos = scene.data("robot", "joint_pos").torch[:, 0].cpu().numpy() + assert all(joint_pos[world] in banked[world] for world in range(8)) # each world draws from its own bank + + before = scene.data("robot", "joint_pos").torch.clone() + for _ in range(8): + reset(task_mdp, state, [True] + [False] * 7) + after = scene.data("robot", "joint_pos").torch + assert torch.equal(after[1:], before[1:]) + + +def test_shared_bank_restores_poses_relative_to_each_world_origin(): + scene = Scene(num_worlds=4) + poses = torch.tensor([[0.1, 0.2, 0.3, 0, 0, 0, 1], [-0.1, 0.0, 0.5, 0, 0, 0, 1]], device=DEVICE) + states = {"joint_pos": torch.tensor([[0.25], [-0.25]], device=DEVICE), "object_pose_w": poses} + task_mdp, state = build( + scene, + fill=mdp.FillFromStates(states), + shared=True, + inputs={"succeeded": mdp2.quantities.success, "env_origins": scene_entity.env_origins}, + ) + reset(task_mdp, state, [True] * 4) + + pose = scene.data("object", "root_link_pose_w").torch + slot = state.caches["events.reset"]["sampler"].indices.torch.long() + origins = scene.data("scene", "env_origins").torch + torch.testing.assert_close(pose[:, :3], poses[slot, :3] + origins) + torch.testing.assert_close(scene.data("robot", "joint_pos").torch, states["joint_pos"][slot]) + + +def test_outcomes_are_credited_to_the_state_each_episode_started_from(): + scene = Scene(num_worlds=16) + states = { + "joint_pos": torch.tensor([[0.5], [-0.5]], device=DEVICE), + "object_pose_w": torch.tensor([[0, 0, 0, 0, 0, 0, 1]] * 2, dtype=torch.float32, device=DEVICE), + } + sampler = ResetStateSamplerCfg(history_length=8, scores=[BetaSamplingScoreCfg(target=1.0)]) + inputs = {"succeeded": mdp2.quantities.success, "env_origins": scene_entity.env_origins} + task_mdp, state = build(scene, fill=mdp.FillFromStates(states), shared=True, sampler=sampler, inputs=inputs) + transition = task_mdp.transition() + for _ in range(6): + reset(task_mdp, state, [True] * 16) + mdp2.evaluate(task_mdp, state, transition) # success: the restored joint position is positive + + record = state.caches["events.reset"]["sampler"] + np.testing.assert_allclose(record.success_rate.warp.numpy(), [1.0, 0.0]) + assert record.episode_counts.warp.numpy().sum() == 5 * 16 # the first reset has no episode to credit + + +def test_backends_and_graph_replay_restore_the_same_states(): + runs = [] + for backend, capture in (("torch", False), ("warp", False), ("warp", True)): + if capture and not DEVICE.startswith("cuda"): + continue + scene = Scene(num_worlds=32) + task_mdp, state = build(scene, backend, fill=mdp.FillFromCandidates(CANDIDATES, bank_size=8)) + mask = ProxyArray(wp.zeros(32, dtype=wp.bool, device=DEVICE)) + transition = task_mdp.transition() + actions = ProxyArray(wp.zeros((32, 0), dtype=wp.float32, device=DEVICE)) + captured = mdp2.CapturedMDP(task_mdp, state, transition, actions, mask) if capture else None + generator = torch.Generator(device=DEVICE).manual_seed(0) + history = [] + for _ in range(10): + mask.torch.copy_(torch.rand(32, device=DEVICE, generator=generator) < 0.5) + if captured is None: + mdp2.reset(task_mdp, state, mask) + mdp2.evaluate(task_mdp, state, transition) + else: + captured.reset() + captured.evaluate() + history.append(scene.data("robot", "joint_pos").torch.clone()) + runs.append(torch.stack(history)) + for run in runs[1:]: + assert torch.equal(run, runs[0]) + + +@pytest.mark.parametrize( + ("params", "message"), + [ + ({"fill": mdp.FillFromStates({"joint_pos": torch.zeros(2, 1, 1)})}, "but the event writes"), + ({"fill": mdp.FillFromCandidates(CANDIDATES, bank_size=2), "shared": True}, "needs the env_origins input"), + ], + ids=["fill_misses_an_output", "shared_poses_without_origins"], +) +def test_invalid_banks_are_rejected_at_startup(params, message): + with pytest.raises(ValueError, match=message): + build(Scene(num_worlds=2), **params) diff --git a/source/isaaclab_tasks/changelog.d/mdp2-resets.changed.rst b/source/isaaclab_tasks/changelog.d/mdp2-resets.changed.rst new file mode 100644 index 000000000000..127595f35aa6 --- /dev/null +++ b/source/isaaclab_tasks/changelog.d/mdp2-resets.changed.rst @@ -0,0 +1,2 @@ +* Changed ``Isaac-Lift-KukaAllegro-MDP2`` to reset through ``isaaclab_experimental.mdp2.mdp.reset_from_bank`` with the + MDP1 lift sampler settings, replacing its task-local reset bank. diff --git a/source/isaaclab_tasks/isaaclab_tasks/mdp2/lift_kuka_allegro/lift_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/mdp2/lift_kuka_allegro/lift_env_cfg.py index f0e7035eeb44..fa8f88b00876 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/mdp2/lift_kuka_allegro/lift_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/mdp2/lift_kuka_allegro/lift_env_cfg.py @@ -13,6 +13,7 @@ import isaaclab.sim as sim_utils from isaaclab.assets import ArticulationCfg, AssetBaseCfg, RigidObjectCfg +from isaaclab.envs.reset import BetaSamplingScoreCfg, ResetStateSamplerCfg from isaaclab.scene import InteractiveSceneCfg from isaaclab.sensors import ContactSensorCfg from isaaclab.sim import MeshCapsuleCfg, MeshConeCfg, MeshCuboidCfg, MeshSphereCfg, RigidBodyMaterialBaseCfg @@ -24,7 +25,6 @@ from . import mdp as lift from .clearance import mesh_clearance, slab_clearance -from .reset_bank import reset_from_bank SIM_DT = 1 / 120 DECIMATION = 4 # 30 Hz control @@ -453,17 +453,19 @@ class KukaAllegroLiftPhysicsCfg(PresetCfg): outputs={"gravity_w": scene.gravity_w}, params={"initial_gravity": (0.0, 0.0, 0.0), "final_gravity": (0.0, 0.0, -9.81)}, ), - # Restart from the valid start states that the policy solves about half the time. + # Restart from the valid start states that the policy solves about half the time. Each world banks its own + # states, so that they fit the object it spawned. "reset": mdp2.Event( - reset_from_bank, + mdp.reset_from_bank, inputs={"succeeded": mdp2.quantities.success}, outputs={**robot_state, **object_state}, params={ - "candidates": CANDIDATES, - "bank_size": 16, - "history_length": 10, - "target_success_rate": 0.5, - "kappa": 1.0, + "fill": mdp.FillFromCandidates(CANDIDATES, bank_size=16), + "sampler": ResetStateSamplerCfg( + history_length=10, + scores=[BetaSamplingScoreCfg(target=0.5, kappa=1.0, weight=0.5)], + uniform_weight=1e-2, + ), }, ), }, diff --git a/source/isaaclab_tasks/isaaclab_tasks/mdp2/lift_kuka_allegro/reset_bank.py b/source/isaaclab_tasks/isaaclab_tasks/mdp2/lift_kuka_allegro/reset_bank.py deleted file mode 100644 index f9d087f2d9d5..000000000000 --- a/source/isaaclab_tasks/isaaclab_tasks/mdp2/lift_kuka_allegro/reset_bank.py +++ /dev/null @@ -1,250 +0,0 @@ -# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). -# All rights reserved. -# -# SPDX-License-Identifier: BSD-3-Clause - -"""The reset of the lift task: every world keeps a bank of valid start states, drawn by how often the policy solves -them. - -The bank is filled once, before training, from a task of candidate start states: its reset events draw a state, its -terminations reject it, and its ``descriptor`` observation group, if it has one, measures it. Restoring a state is an -ordinary reset event that runs inside the step's CUDA graph. -""" - -from __future__ import annotations - -import functools - -import torch -import warp as wp -from isaaclab_experimental import mdp2 - -from isaaclab.utils.warp import ProxyArray - -MIN_WEIGHT = wp.constant(1.0e-4) -"""Smallest weight of a start state, which keeps the states the policy never or always solves in the draw.""" - - -@wp.func -def _weight( - world: int, - slot: int, - outcomes: wp.array3d(dtype=float), - episodes: wp.array2d(dtype=float), - target_success_rate: float, - kappa: float, -) -> float: - """Return the weight of a start state, which peaks where its success rate is the target.""" - history = outcomes.shape[2] - successes = float(0.0) - for h in range(history): - successes += outcomes[world, slot, h] - rate = successes / wp.clamp(episodes[world, slot], 1.0, float(history)) - - weight = wp.pow(rate + MIN_WEIGHT, kappa * target_success_rate) - weight *= wp.pow(1.0 - rate + MIN_WEIGHT, kappa * (1.0 - target_success_rate)) - return wp.max(weight, MIN_WEIGHT) - - -@wp.func -def _reset_from_bank( - world: int, - joint_pos: wp.array2d(dtype=float), - joint_vel: wp.array2d(dtype=float), - object_pose_w: wp.array(dtype=wp.transformf), - object_vel_w: wp.array(dtype=wp.spatial_vectorf), - succeeded: wp.array(dtype=float), - bank_joint_pos: wp.array3d(dtype=float), - bank_joint_vel: wp.array3d(dtype=float), - bank_object_pose_w: wp.array3d(dtype=float), - bank_object_vel_w: wp.array3d(dtype=float), - outcomes: wp.array3d(dtype=float), - episodes: wp.array2d(dtype=float), - playing: wp.array(dtype=float), - target_success_rate: float, - kappa: float, - rng: wp.int32, -): - # Credit the episode that ended to the state it started from. - played = int(playing[world]) - if played >= 0: - position = int(episodes[world, played]) % outcomes.shape[2] - outcomes[world, played, position] = wp.where(succeeded[world] > 0.5, 1.0, 0.0) - episodes[world, played] = episodes[world, played] + 1.0 - - # Draw a state by its weight. - num_slots = episodes.shape[1] - total = float(0.0) - for s in range(num_slots): - total += _weight(world, s, outcomes, episodes, target_success_rate, kappa) - draw = wp.randf(wp.rand_init(rng, 0), 0.0, 1.0) * total - - slot = int(0) - cumulative = _weight(world, 0, outcomes, episodes, target_success_rate, kappa) - while slot < num_slots - 1 and cumulative <= draw: - slot += 1 - cumulative += _weight(world, slot, outcomes, episodes, target_success_rate, kappa) - playing[world] = float(slot) - - for j in range(joint_pos.shape[1]): - joint_pos[world, j] = bank_joint_pos[world, slot, j] - joint_vel[world, j] = bank_joint_vel[world, slot, j] - pose = wp.transformf() - for k in range(7): - pose[k] = bank_object_pose_w[world, slot, k] - velocity = wp.spatial_vectorf() - for k in range(6): - velocity[k] = bank_object_vel_w[world, slot, k] - object_pose_w[world] = pose - object_vel_w[world] = velocity - - -def _reset_from_bank_torch( - mask: torch.Tensor, - joint_pos: torch.Tensor, - joint_vel: torch.Tensor, - object_pose_w: torch.Tensor, - object_vel_w: torch.Tensor, - succeeded: torch.Tensor, - bank_joint_pos: torch.Tensor, - bank_joint_vel: torch.Tensor, - bank_object_pose_w: torch.Tensor, - bank_object_vel_w: torch.Tensor, - outcomes: torch.Tensor, - episodes: torch.Tensor, - playing: torch.Tensor, - rng: torch.Tensor, - *, - target_success_rate: float, - kappa: float, -) -> None: - worlds = torch.arange(len(mask), device=mask.device) - history = outcomes.shape[2] - - # Credit the episode that ended to the state it started from. - credited = mask & (playing >= 0.0) - played = playing.long().clamp(min=0) - position = episodes[worlds, played].long() % history - outcome = torch.where(credited, (succeeded > 0.5).float(), outcomes[worlds, played, position]) - outcomes[worlds, played, position] = outcome - episodes[worlds, played] += credited.float() - - # Draw a state by its weight. - rate = outcomes.sum(-1) / episodes.clamp(1.0, history) - weights = (rate + MIN_WEIGHT) ** (kappa * target_success_rate) - weights = (weights * (1.0 - rate + MIN_WEIGHT) ** (kappa * (1.0 - target_success_rate))).clamp_min(MIN_WEIGHT) - cumulative = weights.cumsum(-1) - draw = mdp2.uniform(rng, 0.0, 1.0) * cumulative[:, -1] - slot = (cumulative <= draw[:, None]).sum(-1).clamp(max=weights.shape[1] - 1) - playing.copy_(torch.where(mask, slot.float(), playing)) - - fields = ( - (joint_pos, bank_joint_pos), - (joint_vel, bank_joint_vel), - (object_pose_w, bank_object_pose_w), - (object_vel_w, bank_object_vel_w), - ) - for field, bank in fields: - field.copy_(torch.where(mask[:, None], bank[worlds, slot], field)) - - -def _farthest_points(points: torch.Tensor, count: int) -> torch.Tensor: - """Return, for each world, the indices of ``count`` of its points spread as far apart as possible.""" - worlds = torch.arange(len(points), device=points.device) - chosen = torch.zeros(len(points), count, dtype=torch.long, device=points.device) - nearest = torch.full(points.shape[:2], float("inf"), device=points.device) - farthest = torch.zeros(len(points), dtype=torch.long, device=points.device) - for k in range(count): - chosen[:, k] = farthest - distance = (points - points[worlds, farthest][:, None]).norm(dim=-1) - nearest = torch.minimum(nearest, distance) - farthest = nearest.argmax(dim=-1) - return chosen - - -def _fill_bank( - ctx: mdp2.TermContext, - *, - candidates: mdp2.TaskCfg, - bank_size: int, - oversample_factor: float = 2.0, - max_rolls: int = 2000, - **restore_params: float, -) -> None: - fields = ctx.outputs - num_worlds, device = ctx.num_worlds, ctx.rng.device - worlds = torch.arange(num_worlds, device=device) - - builder = mdp2.MDPBuilder(ctx.scene_data.schema) - builder.add_task(candidates) - mdp = builder.finalize(device=str(device), backend="warp") - state, transition = mdp.state(ctx.scene_data, seed=int(ctx.rng[0])), mdp.transition() - mdp2.startup(mdp, state) - - # With a descriptor, more states are harvested than kept, to choose the most spread ones from. - descriptor = transition.observations.get("descriptor") - harvest_size = bank_size if descriptor is None else round(bank_size * oversample_factor) - states = {name: field.new_zeros(num_worlds, harvest_size, *field.shape[1:]) for name, field in fields.items()} - if descriptor is not None: - fields = {**fields, "descriptor": descriptor.torch} - states["descriptor"] = descriptor.torch.new_zeros(num_worlds, harvest_size, descriptor.shape[1]) - - # Roll the candidates in every world until each world has harvested enough valid states. - mask = ProxyArray(wp.ones(num_worlds, dtype=wp.bool, device=str(device))) - commit = functools.partial(ctx.scene_data.commit, mask.warp, mdp.reset_writes) - filled = torch.zeros(num_worlds, dtype=torch.long, device=device) - for _ in range(max_rolls): - mdp2.reset(mdp, state, mask, commit) - commit() - mdp2.evaluate(mdp, state, transition) - - take = ~transition.terminated.torch & (filled < harvest_size) - slot = filled.clamp(max=harvest_size - 1) - for name, field in fields.items(): - states[name][worlds, slot] = torch.where(take[:, None], field, states[name][worlds, slot]) - filled += take - if (filled == harvest_size).all(): - break - else: - short = int((filled < harvest_size).sum()) - raise RuntimeError( - f"The reset bank found fewer than {harvest_size} valid start states in {short} of {num_worlds} worlds" - f" after {max_rolls} rolls of the candidates." - ) - - # Keep the states most spread over the descriptor, each axis rescaled to unit span so that all axes count. - if descriptor is not None: - values = states.pop("descriptor") - span = (values.amax(dim=(0, 1)) - values.amin(dim=(0, 1))).clamp(min=1e-6) - kept = _farthest_points(values / span, bank_size) - states = {name: value[worlds[:, None], kept] for name, value in states.items()} - for name, value in states.items(): - ctx.state[f"bank_{name}"].copy_(value) - - -reset_from_bank = mdp2.Term( - torch=_reset_from_bank_torch, - warp=_reset_from_bank, - state={ - "bank_joint_pos": mdp2.State(("worlds", "bank_size", "joint_pos"), persistent=True), - "bank_joint_vel": mdp2.State(("worlds", "bank_size", "joint_vel"), persistent=True), - "bank_object_pose_w": mdp2.State(("worlds", "bank_size", 7), persistent=True), - "bank_object_vel_w": mdp2.State(("worlds", "bank_size", 6), persistent=True), - "outcomes": mdp2.State(("worlds", "bank_size", "history_length"), persistent=True), - "episodes": mdp2.State(("worlds", "bank_size"), persistent=True), - "playing": mdp2.State(initial=-1.0, persistent=True), - }, - random=True, - init=_fill_bank, -) -"""Restart the reset worlds from one of their ``bank_size`` banked start states, like MDP1's ``conditional_reset``. - -Each world banks its own states of the robot's joints and of the object, so they fit the object it spawned. Before -training, the reset events of the ``candidates`` task are rolled in every world, and the states that none of its -terminations reject are harvested. If the task has a ``descriptor`` observation group, ``oversample_factor`` times as -many states are harvested, and the ones most spread over the descriptor are kept. - -A reset credits the episode that ended, whose success is the ``succeeded`` input, to the state it started from, in -that state's last ``history_length`` outcomes. It then draws a state with a weight that peaks where the success rate -is ``target_success_rate``, more sharply with a larger ``kappa``, and none (uniform) with zero. -""" diff --git a/source/isaaclab_tasks/test/mdp2/test_lift_kuka_allegro.py b/source/isaaclab_tasks/test/mdp2/test_lift_kuka_allegro.py index 7867400ed456..37f547470bf3 100644 --- a/source/isaaclab_tasks/test/mdp2/test_lift_kuka_allegro.py +++ b/source/isaaclab_tasks/test/mdp2/test_lift_kuka_allegro.py @@ -5,6 +5,7 @@ """Tests for the MDP2 Kuka Allegro lift task on Newton.""" +import dataclasses import math from collections.abc import Iterator from types import SimpleNamespace @@ -27,7 +28,6 @@ NUM_ENVS = 16 FINGERTIPS = ("index_link_3", "middle_link_3", "ring_link_3", "thumb_link_3") -BANKED = ("playing", "bank_joint_pos", "bank_joint_vel", "bank_object_pose_w", "bank_object_vel_w") PROGRESS = mdp2.term_state("events.adr", "progress") @@ -40,7 +40,8 @@ def scenario() -> Iterator[SimpleNamespace]: cfg.sim.device = "cuda:0" cfg.scene.num_envs = NUM_ENVS cfg.seed = 0 - cfg.task.events["reset"].params["bank_size"] = 2 + params = cfg.task.events["reset"].params + params["fill"] = dataclasses.replace(params["fill"], bank_size=2) env = MDP2RLEnv(cfg) try: generator = torch.Generator(device=env.device).manual_seed(0) @@ -77,8 +78,8 @@ def rand(*shape, scale=1.0): def bank_and_scene_state(env: MDP2RLEnv, state: mdp2.MDPState) -> dict[str, tuple[torch.Tensor, torch.Tensor]]: """Return, per banked field, the banked state that each world plays and the field's value in the scene.""" - bank = {name: state.arrays[mdp2.term_state("events.reset", name)].torch for name in BANKED} - rows = torch.arange(NUM_ENVS, device=env.device), bank["playing"].long() + cache = state.caches["events.reset"] + banked = cache["bank"].get_state(cache["sampler"].indices) robot, target = env.scene["robot"].data, env.scene["object"].data fields = { "joint_pos": robot.joint_pos, @@ -86,16 +87,26 @@ def bank_and_scene_state(env: MDP2RLEnv, state: mdp2.MDPState) -> dict[str, tupl "object_pose_w": target.root_link_pose_w, "object_vel_w": target.root_com_vel_w, } - return {name: (bank[f"bank_{name}"][rows].clone(), field.torch.clone()) for name, field in fields.items()} + return {name: (banked[name].torch.clone(), field.torch.clone()) for name, field in fields.items()} + + +def sampler_arrays(state: mdp2.MDPState) -> dict[str, torch.Tensor]: + """Return copies of the reset sampler's device state: its assignments, outcome history, and draw weights.""" + sampler = state.caches["events.reset"]["sampler"] + arrays = {name: value for name, value in vars(sampler).items() if isinstance(value, (wp.array, ProxyArray))} + return {name: wp.to_torch(value.warp if isinstance(value, ProxyArray) else value) for name, value in arrays.items()} def build(scenario: SimpleNamespace, backend: str) -> tuple[mdp2.MDP, mdp2.MDPState]: - """Compile the task for a backend, with the environment's term state: its point clouds and its bank.""" + """Compile the task for a backend, with the environment's term state, its point clouds, and its reset bank.""" env = scenario.env builder = mdp2.MDPBuilder(env.scene_data.schema) builder.add_task(scenario.cfg.task) mdp = builder.finalize(device=env.device, backend=backend, diagnostics=True) state = mdp.state(env.scene_data) + for name, cache in env.state.caches.items(): + if name in state.caches: + state.caches[name].update(cache) # in place: the hooks' arguments hold these dicts for op in mdp.term_ops: for name in op.state: @@ -232,13 +243,16 @@ def test_step_replays_as_one_graph_with_curriculum_and_bank(scenario: SimpleName env = scenario.env assert env.mdp.is_fully_capturable and env.is_captured and env.num_graphs == 1 - # Both backends draw the same banked state for every world, and restore it. + # Both backends draw the same banked state for every world from the same sampler state, and restore it. mask = ProxyArray(wp.ones(NUM_ENVS, dtype=wp.bool, device=env.device)) + before = {name: value.clone() for name, value in sampler_arrays(env.state).items()} playing = {} for backend in ("torch", "warp"): mdp, state = build(scenario, backend) + for name, value in sampler_arrays(state).items(): + value.copy_(before[name]) mdp2.reset(mdp, state, mask) - playing[backend] = state.arrays[mdp2.term_state("events.reset", "playing")].torch.clone() + playing[backend] = state.caches["events.reset"]["sampler"].indices.torch.clone() for name, (banked, restored) in bank_and_scene_state(env, state).items(): torch.testing.assert_close(restored, banked, atol=1e-5, rtol=0.0, msg=lambda message, name=name: name) assert torch.equal(playing["torch"], playing["warp"]) From 8b13f504b9fc31ff02b855716d9cf58f24eaa1ae Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 18:10:25 -0800 Subject: [PATCH 02/17] Add state writes, outcome resets, and per-environment draws to the reset API ResetStateBuffer.set_state is the inverse of get_state, so stored states can be replaced while running. ResetStateSampler.forget clears the outcomes of replaced entries and starts them at a prior success rate. A state_ids request of -1 now draws from the scores, so one captured reset can replay some environments and sample the others. --- .../changelog.d/mdp2-resets.added.rst | 4 + .../isaaclab/envs/reset/reset_state_buffer.py | 100 +++++++++++++++--- .../envs/reset/reset_state_sampler.py | 65 +++++++++++- .../test/envs/test_reset_state_sampler.py | 22 ++++ .../isaaclab/test/envs/test_reset_states.py | 19 ++++ 5 files changed, 194 insertions(+), 16 deletions(-) diff --git a/source/isaaclab/changelog.d/mdp2-resets.added.rst b/source/isaaclab/changelog.d/mdp2-resets.added.rst index a65bf391c462..859b18224a10 100644 --- a/source/isaaclab/changelog.d/mdp2-resets.added.rst +++ b/source/isaaclab/changelog.d/mdp2-resets.added.rst @@ -1,2 +1,6 @@ * Added an optional ``rng`` argument to :meth:`~isaaclab.envs.reset.ResetStateSampler.reset` so that callers' per-environment int32 seeds, such as MDP2's random streams, drive the draws. +* Added :meth:`~isaaclab.envs.reset.ResetStateBuffer.set_state`, the inverse of ``get_state``, to replace stored states + while running, and :meth:`~isaaclab.envs.reset.ResetStateSampler.forget` to clear the outcomes of replaced entries. +* Added per-environment sampling to explicit requests: a ``state_ids`` request of -1 in + :meth:`~isaaclab.envs.reset.ResetStateSampler.reset` draws from the scores instead of being invalid. diff --git a/source/isaaclab/isaaclab/envs/reset/reset_state_buffer.py b/source/isaaclab/isaaclab/envs/reset/reset_state_buffer.py index ac230357b6ac..f06fb1d42739 100644 --- a/source/isaaclab/isaaclab/envs/reset/reset_state_buffer.py +++ b/source/isaaclab/isaaclab/envs/reset/reset_state_buffer.py @@ -106,13 +106,9 @@ def get_state( Returns: The supplied output tree, or a new tree when ``out`` is None. """ - state_indices = _as_array(state_indices) - if state_indices.ndim != 1 or state_indices.dtype not in (wp.int32, wp.int64): - raise ValueError("state_indices must be a one-dimensional int32 or int64 array.") + state_indices = self._indices(state_indices, mask) if mask is not None: mask = _as_array(mask) - if mask.shape != state_indices.shape or mask.dtype != wp.bool or mask.device != state_indices.device: - raise ValueError("mask must be a boolean array matching state_indices shape and device.") if out is None: raise ValueError("Masked reads require a preallocated out tree.") num_rows = state_indices.shape[0] @@ -127,27 +123,66 @@ def get_state( ), ) + for source, target in self._pair_fields(out, state_indices, "out"): + _gather(source, state_indices, mask, target) + return out + + def set_state( + self, + state_indices: wp.array | ProxyArray | torch.Tensor, + values: ResetStateBuffer.State, + *, + mask: wp.array | ProxyArray | torch.Tensor | None = None, + ) -> None: + """Copy the value rows enabled by ``mask`` into the selected stored states, the inverse of :meth:`get_state`. + + Invalid indices are skipped. Enabled rows that select the same state write it in an unspecified order. Like + :meth:`get_state` with ``out``, this performs no allocation or host synchronization and can be captured. + + Args: + state_indices: Dense int32 or int64 row positions, shape [N], on the buffer device. + values: Tree with the stored schema and N leading rows. + mask: Boolean selection, shape [N]. None writes every value row. + """ + state_indices = self._indices(state_indices, mask) + mask = None if mask is None else _as_array(mask) + for source, value in self._pair_fields(values, state_indices, "values"): + _scatter(value, state_indices, mask, source) + + def _indices(self, state_indices, mask) -> wp.array: + state_indices = _as_array(state_indices) + if state_indices.ndim != 1 or state_indices.dtype not in (wp.int32, wp.int64): + raise ValueError("state_indices must be a one-dimensional int32 or int64 array.") + if mask is not None: + mask = _as_array(mask) + if mask.shape != state_indices.shape or mask.dtype != wp.bool or mask.device != state_indices.device: + raise ValueError("mask must be a boolean array matching state_indices shape and device.") + return state_indices + + def _pair_fields( + self, tree: ResetStateBuffer.State, state_indices: wp.array, name: str + ) -> list[tuple[wp.array, wp.array]]: + """Pair each stored field with the field of ``tree`` that has ``len(state_indices)`` rows.""" + num_rows = state_indices.shape[0] fields: list[tuple[wp.array, wp.array]] = [] def collect_fields(states, target): if not isinstance(target, dict) or target.keys() != states.keys(): - raise ValueError("out must match the stored state tree.") - for name, value in states.items(): + raise ValueError(f"{name} must match the stored state tree.") + for key, value in states.items(): if isinstance(value, dict): - collect_fields(value, target[name]) + collect_fields(value, target[key]) continue shape = (num_rows, *value.shape[1:]) - result = _as_array(target[name], dtype=value.dtype) + result = _as_array(target[key], dtype=value.dtype) if (result.shape, result.dtype, result.device) != (shape, value.dtype, value.device): - raise ValueError(f"out field {name!r} must match the stored trailing shape, dtype, and device.") + raise ValueError(f"{name} field {key!r} must match the stored trailing shape, dtype, and device.") if state_indices.device != value.device: raise ValueError("state_indices and stored states must share a device.") fields.append((value, result)) - collect_fields(self._states, out) - for source, target in fields: - _gather(source, state_indices, mask, target) - return out + collect_fields(self._states, tree) + return fields def _map_state(states: ResetStateBuffer.State, function: Callable) -> ResetStateBuffer.State: @@ -181,6 +216,11 @@ def _gather(source, ids, mask, target) -> None: ) +def _scatter(values, ids, mask, target) -> None: + if values.size: + wp.launch(_scatter_kernel, values.shape, [values, ids, mask, target], device=values.device) + + @wp.kernel def _gather_kernel( source: Any, @@ -211,3 +251,35 @@ def _gather_kernel( target[i, j, k] = source[row, j, k] else: target[i, j, k, component] = source[row, j, k, component] + + +@wp.kernel +def _scatter_kernel( + values: Any, + ids: wp.array(dtype=Any), + mask: wp.array(dtype=wp.bool), + target: Any, +): + i, j, k, component = int(0), int(0), int(0), int(0) + if wp.static(len(values.shape) == 1): + i = wp.tid() + elif wp.static(len(values.shape) == 2): + i, j = wp.tid() + elif wp.static(len(values.shape) == 3): + i, j, k = wp.tid() + else: + i, j, k, component = wp.tid() + if mask and not mask[i]: + return + index = wp.int64(ids[i]) + if index < wp.int64(0) or index >= wp.int64(target.shape[0]): + return + row = int(index) + if wp.static(len(values.shape) == 1): + target[row] = values[i] + elif wp.static(len(values.shape) == 2): + target[row, j] = values[i, j] + elif wp.static(len(values.shape) == 3): + target[row, j, k] = values[i, j, k] + else: + target[row, j, k, component] = values[i, j, k, component] diff --git a/source/isaaclab/isaaclab/envs/reset/reset_state_sampler.py b/source/isaaclab/isaaclab/envs/reset/reset_state_sampler.py index 95dc07fa240f..7e4e347978cc 100644 --- a/source/isaaclab/isaaclab/envs/reset/reset_state_sampler.py +++ b/source/isaaclab/isaaclab/envs/reset/reset_state_sampler.py @@ -183,7 +183,8 @@ def reset( env_ids: Alternative selection using environment indices or a slice. success: Previous episode success flags, shape [num_envs]. Omit at startup. valid: Completed-episode mask, shape [num_envs]. Exclude unfinished manual resets. - state_ids: Explicit catalog labels, shape [num_envs]. Omit to sample from scores. + state_ids: Explicit catalog labels, shape [num_envs]. Omit to sample from scores. A request of -1 + samples from the scores for that environment. rng: Caller-owned int32 seeds, shape [num_envs]. Each draw is then ``wp.randf(wp.rand_init(rng[env], 0))`` and the internal streams are untouched; the caller advances its seeds between resets. Omit to use the internal streams. @@ -230,6 +231,43 @@ def reset( ) return self.state_ids + def forget( + self, + state_indices: wp.array | ProxyArray | torch.Tensor, + mask: wp.array | ProxyArray | torch.Tensor | None = None, + *, + success_rate: float = 0.0, + ) -> None: + """Clear the outcome history of entries whose states the caller replaced. + + Their episode counts restart at zero and their success rate is ``success_rate`` until their next outcome, + such as a score's target, so that a new state is drawn before its outcomes are known. Probabilities follow at + the next :meth:`reset`. Captured like :meth:`reset`. + + Args: + state_indices: Dense int32 catalog positions, shape [N]. Invalid positions are skipped. + mask: Boolean selection, shape [N]. None forgets every listed entry. + success_rate: Success rate of the forgotten entries until their next outcome, in [0, 1]. + """ + indices = _warp_array(state_indices) + indices = self._input(indices, indices.shape[0] if isinstance(indices, wp.array) else -1) + if indices.dtype != wp.int32: + raise TypeError("state_indices must use the int32 dtype.") + selection = None if mask is None else self._input(mask, indices.shape[0]) + wp.launch( + _forget_outcomes, + indices.shape[0], + [ + indices, + selection, + float(success_rate), + self._success_history, + self.episode_counts.warp, + self.success_rate.warp, + ], + device=self.device, + ) + def _resolve_requested_indices(self, selection: wp.array, state_ids: wp.array | ProxyArray | torch.Tensor) -> None: """Resolve explicit catalog labels before any previous outcomes are credited.""" requests = self._input(state_ids, self.num_envs) @@ -373,6 +411,8 @@ def _resolve_requests( requested_indices[env] = -1 if mask[env]: value = wp.int64(requested[env]) + if value == wp.int64(-1): + return index = int(-1) if dense: if value >= wp.int64(0) and value < wp.int64(catalog_ids.shape[0]): @@ -394,6 +434,27 @@ def _resolve_requests( invalid[env] = True +@wp.kernel +def _forget_outcomes( + indices: wp.array(dtype=wp.int32), + mask: wp.array(dtype=wp.bool), + success_rate: float, + success_history: wp.array2d(dtype=float), + episode_counts: wp.array(dtype=wp.int64), + rates: wp.array(dtype=float), +): + i = wp.tid() + if mask and not mask[i]: + return + index = indices[i] + if index < 0 or index >= rates.shape[0]: + return + for h in range(success_history.shape[1]): + success_history[index, h] = 0.0 + episode_counts[index] = wp.int64(0) + rates[index] = success_rate + + @wp.kernel def _index_completed_outcomes( mask: wp.array(dtype=wp.bool), @@ -545,7 +606,7 @@ def _assign_reset_states( env = wp.tid() if mask[env] and not invalid[env]: index = int(-1) - if use_requested: + if use_requested and requested[env] >= 0: index = requested[env] else: start = env_group_ids[env] * group_size diff --git a/source/isaaclab/test/envs/test_reset_state_sampler.py b/source/isaaclab/test/envs/test_reset_state_sampler.py index cf0be2427c8a..7f2580698d1d 100644 --- a/source/isaaclab/test/envs/test_reset_state_sampler.py +++ b/source/isaaclab/test/envs/test_reset_state_sampler.py @@ -247,3 +247,25 @@ def test_caller_seeds_decide_draws_and_leave_internal_streams_untouched(): np.testing.assert_array_equal(sampler.reset().warp.numpy(), reference.reset().warp.numpy()) with pytest.raises(TypeError): sampler.reset(rng=wp.zeros(num_envs, dtype=wp.int64, device=device)) + + +def test_minus_one_requests_draw_and_forgotten_entries_restart_from_a_prior(): + sampler = ResetStateSampler( + ResetStateSamplerCfg(history_length=4, scores=[]), 4, 64, "cpu", group_ids=torch.arange(4), num_groups=4 + ) + requests = torch.tensor([-1, 21, -1, 63]) + # Worlds 0 and 2 draw within their own group; worlds 1 and 3 replay their requested entry. + sampler.reset(state_ids=requests) + indices = sampler.indices.warp.numpy() + assert 0 <= indices[0] < 16 and 32 <= indices[2] < 48 + np.testing.assert_array_equal(indices[[1, 3]], [21, 63]) + assert not sampler.invalid_requests.warp.numpy().any() + + sampler.reset(success=torch.ones(4, dtype=torch.bool), state_ids=requests) + np.testing.assert_array_equal(sampler.episode_counts.warp.numpy()[[21, 63]], [1, 1]) + sampler.forget(wp.array([21, 63], dtype=wp.int32, device="cpu"), torch.tensor([True, False]), success_rate=0.5) + np.testing.assert_array_equal(sampler.episode_counts.warp.numpy()[[21, 63]], [0, 1]) + np.testing.assert_allclose(sampler.success_rate.warp.numpy()[[21, 63]], [0.5, 1.0]) + # The next outcome replaces the prior. + sampler.reset(success=torch.zeros(4, dtype=torch.bool), state_ids=requests) + np.testing.assert_allclose(sampler.success_rate.warp.numpy()[[21, 63]], [0.0, 0.5]) diff --git a/source/isaaclab/test/envs/test_reset_states.py b/source/isaaclab/test/envs/test_reset_states.py index a028f95cc673..43b7b3f29c27 100644 --- a/source/isaaclab/test/envs/test_reset_states.py +++ b/source/isaaclab/test/envs/test_reset_states.py @@ -129,3 +129,22 @@ def test_masked_state_gather_replays_changed_indices_without_touching_other_worl ids.assign(np.array([2**32, 2**32, 2 - 2**32], dtype=np.int64)) wp.capture_launch(capture.graph) np.testing.assert_array_equal(padded.numpy(), [[30, -7, 31, -7], [30, -7, 31, -7], [20, -7, 21, -7]]) + + +def test_masked_state_scatter_writes_selected_rows_and_round_trips() -> None: + buffer = ResetStateBuffer( + {"pose": wp.zeros(3, dtype=wp.transformf, device="cpu"), "robot": {"joint": torch.zeros(3, 2)}} + ) + values = { + "pose": wp.array([[1, 2, 3, 0, 0, 0, 1], [4, 5, 6, 0, 0, 1, 0]], dtype=wp.transformf, device="cpu"), + "robot": {"joint": torch.tensor([[1.0, 2.0], [3.0, 4.0]])}, + } + # Row 0 goes to state 2; row 1 is masked out; an invalid index is skipped. + buffer.set_state(torch.tensor([2, 0]), values, mask=torch.tensor([True, False])) + buffer.set_state(torch.tensor([-1, 5]), values) + stored = buffer.states + np.testing.assert_array_equal(stored["pose"].warp.numpy()[:, :3], [[0, 0, 0], [0, 0, 0], [1, 2, 3]]) + torch.testing.assert_close(stored["robot"]["joint"].torch, torch.tensor([[0.0, 0.0], [0.0, 0.0], [1.0, 2.0]])) + np.testing.assert_array_equal(buffer.get_state(torch.tensor([2]))["pose"].warp.numpy(), values["pose"].numpy()[:1]) + with pytest.raises(ValueError, match="values must match the stored state tree"): + buffer.set_state(torch.tensor([0]), {"pose": values["pose"]}) From 399f770bed1697a291157a4c83dd6121d415cfe2 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 18:10:25 -0800 Subject: [PATCH 03/17] Run reset event updates every step and restore commands after resampling A reset event's update hook now runs once per step after the rewards, so it can observe the step, and a reset event that writes a command runs after the commands resample, so that a restored command stands. --- .../isaaclab_experimental/mdp2/config.py | 6 ++- .../isaaclab_experimental/mdp2/plan.py | 24 ++++++++---- .../isaaclab_experimental/mdp2/terms.py | 4 +- .../test/mdp2/test_mdp2.py | 38 +++++++++++++++++++ 4 files changed, 62 insertions(+), 10 deletions(-) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py index 9752552176d3..7fa20525f030 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py @@ -214,7 +214,11 @@ class Command(TermCfg): @dataclass class Event(TermCfg): - """Configuration for an event term, which writes its ``outputs`` for the worlds selected by ``mask``.""" + """Configuration for an event term, which writes its ``outputs`` for the worlds selected by ``mask``. + + A reset event that writes a command, such as one that restores a goal, runs after the commands resample, so that + its value stands. The other reset events run before them. + """ outputs: dict[str, FieldSelector] = field(default_factory=dict) # Passed by argument name; the event writes them mode: EventMode = EventMode.RESET diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py index 499440abe970..bc037deb122a 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py @@ -176,15 +176,22 @@ def build_plan(ops: Mapping[Phase, tuple], schema: SceneSchema) -> ExecutionPlan terminations_and_rewards.append(Step(StepKind.COMPUTE, op)) if op.update is not None: terminations_and_rewards.append(Step(StepKind.UPDATE_STATE, op)) - - reset_events = [] + # Reset events with an update hook observe every step, after the step's terminations and rewards. + terminations_and_rewards += [Step(StepKind.UPDATE_STATE, op) for op in ops[Phase.RESET_EVENTS] if op.update] + + # A reset event that writes a command runs after the commands resample, so that its value stands. + command_fields = {op.writes[0] for op in ops[Phase.COMMANDS]} + early = [op for op in ops[Phase.RESET_EVENTS] if not command_fields & set(op.writes)] + late = [op for op in ops[Phase.RESET_EVENTS] if command_fields & set(op.writes)] + reset_events, late_events = [], [] pending: set[FieldSelector] = set() # Scene fields written since the last commit - for op in ops[Phase.RESET_EVENTS]: - if op.commit or op.commit is None and pending and _reads_stale(op, pending, schema): - reset_events.append(Step(StepKind.COMMIT, op)) - pending.clear() - reset_events.append(Step(StepKind.COMPUTE, op)) - pending.update(selector for selector in op.writes if selector.scene) + for steps, events in ((reset_events, early), (late_events, late)): + for op in events: + if op.commit or op.commit is None and pending and _reads_stale(op, pending, schema): + steps.append(Step(StepKind.COMMIT, op)) + pending.clear() + steps.append(Step(StepKind.COMPUTE, op)) + pending.update(selector for selector in op.writes if selector.scene) return ExecutionPlan( startup=tuple(Step(StepKind.COMPUTE, op) for op in ops[Phase.STARTUP_EVENTS]), @@ -204,6 +211,7 @@ def build_plan(ops: Mapping[Phase, tuple], schema: SceneSchema) -> ExecutionPlan *(Step(StepKind.RESET_TIMER, op) for op in timed), *reset_events, *(Step(StepKind.COMPUTE, op) for op in ops[Phase.COMMANDS]), + *late_events, # State restarts last, from the fields and commands of the new episode. *(Step(StepKind.RESET_STATE, op) for op in stateful), ), diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/terms.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/terms.py index 073167aeffb4..e34a0ebdf527 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/terms.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/terms.py @@ -64,7 +64,9 @@ class Implementation: Event and command terms are ``compute(mask, **args)``, or a func ``compute(world, **args)`` run for the selected worlds, and write their outputs in place. A command gets its value as ``command``: ``compute`` resamples it and - writes the command's state, ``update`` may change it every step, and commands have no ``reset`` hook. + writes the command's state, ``update`` may change it every step, and commands have no ``reset`` hook. A reset + event's ``update`` runs once per step after the rewards, to observe the step without writing its outputs, such as + recording states to restart from. """ compute: Callable diff --git a/source/isaaclab_experimental/test/mdp2/test_mdp2.py b/source/isaaclab_experimental/test/mdp2/test_mdp2.py index a84b8a0d7b73..ee331e44753e 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2.py @@ -1201,6 +1201,44 @@ def test_command_updates_change_only_their_worlds(): assert torch.equal(state.arrays[mdp2.commands.count].torch, expected) +@wp.func +def pin_command_warp(world: int, command: wp.array(dtype=float)): + command[world] = 7.0 + + +@wp.func +def count_steps_warp(world: int, steps: wp.array(dtype=float)): + steps[world] = steps[world] + 1.0 + + +def count_steps_torch(steps): + steps.add_(1.0) + + +pin_command = mdp2.Term( + torch=mdp2.Implementation(compute=lambda mask, command: command.masked_fill_(mask, 7.0), update=count_steps_torch), + warp=mdp2.Implementation(compute=pin_command_warp, update=count_steps_warp), + state={"steps": mdp2.State(persistent=True)}, +) +"""A reset event that sets a command to 7 and counts the steps it observes.""" + + +def test_reset_events_that_write_commands_override_the_resample_and_observe_every_step(): + for backend in ("torch", "warp"): + scene = PointMassScene(num_worlds=2, device=DEVICE) + builder = mdp2.MDPBuilder(scene.schema) + builder.add_command("count", mdp2.Command(drifting_count, params={"step": 0.0})) + builder.add_event("pin", mdp2.Event(pin_command, outputs={"command": mdp2.commands.count})) + mdp = builder.finalize(device=DEVICE, backend=backend) + state, transition = mdp.state(scene), mdp.transition() + + mdp2.reset(mdp, state, ProxyArray(wp.array([True, False], dtype=wp.bool, device=DEVICE))) + assert state.arrays[mdp2.commands.count].torch.tolist() == [7.0, 0.0] + for _ in range(3): + mdp2.evaluate(mdp, state, transition) + assert state.arrays[mdp2.term_state("events.pin", "steps")].torch.tolist() == [3.0, 3.0] + + def test_library_commands(): """Commands stay in their ranges, agree across backends, and generated_commands observes them.""" pose_range = ((0.4, 0.6), (-0.2, 0.2), (0.1, 0.3), (-0.5, 0.5), (-0.5, 0.5), (-math.pi, math.pi)) From cb1ba083e71722eebdcaf30cb71e56af6c69be45 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 18:10:25 -0800 Subject: [PATCH 04/17] Record, replay, and save MDP2 reset banks reset_from_bank gains RecordStates, which banks states the worlds visit during training into their own slots, nominal_probability, which keeps a fraction of nominal resets, and reset_bank, which returns a ResetBank to inspect, replay, and save. FillFromFile loads a saved bank, and collect_reset_states.py saves the bank of any MDP2 task, to collect states separately from training. --- docs/source/how-to/reset_state_buffers.rst | 86 +++- scripts/tools/collect_reset_states.py | 55 +++ .../changelog.d/mdp2-resets.added.rst | 5 + .../mdp2/mdp/__init__.pyi | 15 +- .../mdp2/mdp/reset_states.py | 390 +++++++++++++++--- .../test/mdp2/test_mdp2_reset_states.py | 119 +++++- .../test/mdp2/test_lift_kuka_allegro.py | 55 ++- 7 files changed, 632 insertions(+), 93 deletions(-) create mode 100644 scripts/tools/collect_reset_states.py diff --git a/docs/source/how-to/reset_state_buffers.rst b/docs/source/how-to/reset_state_buffers.rst index d2ca887c73e7..cd33c9dbd9c2 100644 --- a/docs/source/how-to/reset_state_buffers.rst +++ b/docs/source/how-to/reset_state_buffers.rst @@ -128,6 +128,13 @@ A framework that owns its random streams passes them instead: ``sampler.reset(ma takes one int32 seed per environment, draws ``wp.randf(wp.rand_init(seeds[env], 0))``, and leaves the internal streams untouched. The caller advances its seeds between resets, as MDP2 does. +To replace stored states while running, such as states recorded during training, write them with +``buffer.set_state(indices, values, mask=mask)``, the inverse of ``get_state``, and clear their outcomes +with ``sampler.forget(indices, mask, success_rate=prior)``. A forgotten entry keeps ``prior`` as its +success rate until its next outcome. Both can be captured. In ``sampler.reset(..., state_ids=ids)``, a +request of -1 draws from the scores for that environment, so a captured reset can replay some +environments and sample the others. + Configure useful practice -------------------------- @@ -232,20 +239,87 @@ MDP2 commits. The outputs are the state: any writable scene fields. }, ) -* ``fill`` returns the states. :class:`~isaaclab_experimental.mdp2.mdp.reset_states.FillFromCandidates` rolls the reset events of a - ``candidates`` task, keeps the states its terminations accept, and, given a ``descriptor`` - observation group, keeps the most spread of an oversampled harvest. :class:`~isaaclab_experimental.mdp2.mdp.reset_states.FillFromStates` - takes given states, such as states saved from an earlier fill or demonstrations. +* ``fill`` returns the states. :class:`~isaaclab_experimental.mdp2.mdp.reset_states.FillFromCandidates` rolls the reset + events of a ``candidates`` task, keeps the states its terminations accept, and, given a ``descriptor`` + observation group, keeps the most spread of an oversampled harvest. + :class:`~isaaclab_experimental.mdp2.mdp.reset_states.FillFromStates` takes given states, such as demonstrations, + and :class:`~isaaclab_experimental.mdp2.mdp.reset_states.FillFromFile` loads a saved bank. * ``sampler`` weighs states by recent success; ``None`` draws uniformly. Binding ``succeeded`` credits each ended episode to the state it started from. * ``shared`` selects one bank for every world instead of one bank per world. Bind ``env_origins`` so poses are stored relative to each world's origin. Share a bank only between worlds whose states fit each other, such as worlds that spawn the same object. +* ``nominal_probability`` is the fraction of resets that keep what the earlier reset events wrote, + fresh draws from the nominal distribution. Those episodes are not credited to any state. +* ``record`` banks states that the worlds visit during training, see below. -Place the event after the other reset events: it overwrites the outputs they wrote. The init -hook warms every kernel, so the event is captured with the rest of the step. +Place the event after the other reset events: it overwrites the outputs they wrote. An event whose +outputs include a command runs after the commands resample, so that a restored goal stands. The +init hook warms every kernel, so the event is captured with the rest of the step. ``Isaac-Lift-KukaAllegro-MDP2`` uses a bank per world with the core Lift sampler settings. +Record states along the horizon +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +States that the policy reaches on its way to success make useful starts. With ``record``, the +event's update hook runs once per step after the rewards and records each world's outputs into +its own bank: + +.. code-block:: python + + "reset": mdp2.Event( + mdp.reset_from_bank, + inputs={ + "succeeded": mdp2.quantities.success, + "terminated": mdp2.terminated, # states that end the episode are not recorded + "record_when": mdp2.quantities.lifted, # optional: record only where above 0.5 + }, + outputs={**robot_state, **object_state}, + params={ + "fill": mdp.FillFromCandidates(CANDIDATES, bank_size=16), + "sampler": ResetStateSamplerCfg(scores=[BetaSamplingScoreCfg(target=0.5)]), + "record": mdp.RecordStates(slots=16, probability=0.01), + }, + ) + +Each step, a world that did not terminate records with ``probability`` into the oldest of its +``slots`` recorded slots, which start as copies of the filled states. A recorded slot forgets the +outcomes of the state it replaces and starts at the success rate the first score targets, so new +states are tried before their outcomes are known. An episode whose start is recorded over is not +credited. Include velocities, and commands for goal-conditioned tasks, in the outputs, so that a +restored state continues as it was recorded. Recording needs a bank per world. + +Inspect, replay, and save the bank +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +:func:`~isaaclab_experimental.mdp2.mdp.reset_states.reset_bank` returns the +:class:`~isaaclab_experimental.mdp2.mdp.reset_states.ResetBank` of a use. Slots are numbered within each +world's bank. + +.. code-block:: python + + bank = mdp.reset_bank(env.state) # the "events.reset" use + bank.states["joint_pos"] # (num_worlds, size, num_joints) + bank.success_rate, bank.episode_counts, bank.probabilities # (num_worlds, size) + bank.slots # the slot each world's episode started from, -1 for a nominal start + + bank.replay(torch.full((env.num_envs,), 3)) # restart every world from its slot 3 at its next reset + bank.replay(None) # draw again + bank.save("bank.pt") # fill a later run with mdp.FillFromFile("bank.pt") + +Replay requests hold until replaced and run inside the captured step, so they can sweep the +bank during evaluation. To collect states separately from training, for example a larger +candidates fill, run ``scripts/tools/collect_reset_states.py``, which builds the task and saves its +bank: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/tools/collect_reset_states.py --task Isaac-Lift-KukaAllegro-MDP2 \ + --num_envs 4096 --bank_size 64 --out kuka_lift_bank.pt physics=newton_mjwarp + +A bank per world fits only runs with the same number of worlds and object assignment; a shared +bank fits any. + Migrating existing reset configurations --------------------------------------- diff --git a/scripts/tools/collect_reset_states.py b/scripts/tools/collect_reset_states.py new file mode 100644 index 000000000000..e21a376a98e7 --- /dev/null +++ b/scripts/tools/collect_reset_states.py @@ -0,0 +1,55 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Collect the start states of an MDP2 task into a file, to fill its reset bank in later runs. + +Building the task fills the bank of its ``reset_from_bank`` event from the event's fill, typically a candidates task. +The script saves that bank. Fill later runs from it with ``fill=mdp.FillFromFile(path)``, in the same number of worlds +unless the bank is shared. For example:: + + uv run python scripts/tools/collect_reset_states.py --task Isaac-Lift-KukaAllegro-MDP2 --num_envs 4096 \\ + --bank_size 64 --out kuka_lift_bank.pt physics=newton_mjwarp +""" + +import argparse +import dataclasses +import sys + +import gymnasium as gym +from isaaclab_experimental.mdp2 import mdp + +from isaaclab.app import add_launcher_args, launch_simulation + +import isaaclab_tasks # noqa: F401 +from isaaclab_tasks.utils import resolve_task_config, setup_preset_cli + +parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) +parser.add_argument("--task", required=True, help="Name of an MDP2 task.") +parser.add_argument("--num_envs", type=int, default=None, help="Number of worlds; default: the task's.") +parser.add_argument("--bank_size", type=int, default=None, help="States per bank, for a candidates fill.") +parser.add_argument("--event", default="reset", help="Name of the reset_from_bank event.") +parser.add_argument("--out", required=True, help="File to save the states to.") +add_launcher_args(parser) +parser.set_defaults(device=None) # let the task select the device +args_cli, hydra_args = setup_preset_cli(parser) +sys.argv = [sys.argv[0]] + hydra_args + +env_cfg, _ = resolve_task_config(args_cli.task, "") +if args_cli.num_envs is not None: + env_cfg.scene.num_envs = args_cli.num_envs +params = env_cfg.task.events[args_cli.event].params +if args_cli.bank_size is not None: + if not isinstance(params["fill"], mdp.FillFromCandidates): + raise SystemExit(f"--bank_size needs a candidates fill, but the event fills with {params['fill']!r}.") + params["fill"] = dataclasses.replace(params["fill"], bank_size=args_cli.bank_size) +params.pop("record", None) # only the filled states + +with launch_simulation(env_cfg, args_cli): + env = gym.make(args_cli.task, cfg=env_cfg) + bank = mdp.reset_bank(env.unwrapped.state, f"events.{args_cli.event}") + bank.save(args_cli.out) + worlds = "one shared bank" if bank.shared else f"{bank.num_worlds} worlds" + print(f"Saved {bank.size} states for {worlds} to {args_cli.out}.") + env.close() diff --git a/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst b/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst index 05b37df96af0..c04ea85af269 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst @@ -3,3 +3,8 @@ ``FillFromCandidates`` and ``FillFromStates`` to fill the bank per world or shared across worlds. * Added ``cache`` to :class:`~isaaclab_experimental.mdp2.TermContext`, so init hooks can build host objects that the use's Python hooks reuse. +* Added recording, replay, and saving to ``reset_from_bank``: ``RecordStates`` banks states that the worlds visit during + training, ``nominal_probability`` keeps a fraction of nominal resets, and ``reset_bank`` returns a ``ResetBank`` to + inspect, replay, and save, which ``FillFromFile`` loads. +* Added scheduling of reset events' ``update`` hooks once per step after the rewards, and ordering of reset events + that write commands after the commands resample, so that a restored command stands. diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi index 1786c05e6dc4..bf3c33f514ee 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi @@ -19,8 +19,12 @@ __all__ = [ "reset_joints_by_scale", "reset_root_state_uniform", "FillFromCandidates", + "FillFromFile", "FillFromStates", + "RecordStates", + "ResetBank", "farthest_points", + "reset_bank", "reset_from_bank", "base_ang_vel", "base_lin_vel", @@ -76,7 +80,16 @@ from .events import ( reset_joints_by_scale, reset_root_state_uniform, ) -from .reset_states import FillFromCandidates, FillFromStates, farthest_points, reset_from_bank +from .reset_states import ( + FillFromCandidates, + FillFromFile, + FillFromStates, + RecordStates, + ResetBank, + farthest_points, + reset_bank, + reset_from_bank, +) from .observations import ( base_ang_vel, base_lin_vel, diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py index efbc5155b50b..dd519a1eef73 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py @@ -3,18 +3,20 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Reset from a bank of start states: the MDP2 term over :mod:`isaaclab.envs.reset`. +"""Reset from a bank of start states: the MDP2 event over :mod:`isaaclab.envs.reset`. -The term composes three parts that are chosen independently: +A :class:`ResetBank` composes three parts that are chosen independently: -- the states, a :class:`~isaaclab.envs.reset.ResetStateBuffer` that a fill builds once at startup; +- the states, a :class:`~isaaclab.envs.reset.ResetStateBuffer` that a fill builds once at startup, and that recording + extends with states visited during training; - the choice, a :class:`~isaaclab.envs.reset.ResetStateSampler` that credits each ended episode to the state it - started from and draws the next one, from the use's random stream; + started from and draws the next one from the use's random stream, unless a slot is requested for replay; - the restore, which gathers the drawn states into the event's ``outputs``. -The outputs are the state: any writable fields, such as ``robot.joint_pos`` and ``object.root_link_pose_w``. A fill is -a callable ``fill(ctx, shared) -> {output: tensor}`` that returns, per output, ``(num_worlds, bank_size, ...)`` states -for a bank per world, or ``(bank_size, ...)`` for one bank that every world shares. +The outputs are the state: any writable fields, such as ``robot.joint_pos`` and ``object.root_link_pose_w``, and +commands, whose restored value then stands over the resample. A fill is a callable ``fill(ctx, shared) -> {output: +tensor}`` that returns, per output, ``(num_worlds, size, ...)`` states for a bank per world, or ``(size, ...)`` for one +bank that every world shares. :func:`reset_bank` returns the bank of a use, to inspect, replay, or save it. """ from __future__ import annotations @@ -22,27 +24,43 @@ import functools from collections.abc import Callable, Mapping from dataclasses import dataclass +from pathlib import Path from typing import Any import torch import warp as wp -from isaaclab.envs.reset import ResetStateBuffer, ResetStateSampler, ResetStateSamplerCfg +from isaaclab.envs.reset import BetaSamplingScoreCfg, ResetStateBuffer, ResetStateSampler, ResetStateSamplerCfg from isaaclab.utils.warp import ProxyArray from ..builder import MDPBuilder +from ..compiled import MDPState from ..config import TaskCfg from ..eager import TermContext from ..runtime import evaluate, reset, startup -from ..terms import Term +from ..terms import Implementation, Term + + +@dataclass(frozen=True) +class RecordStates: + """Record states that the worlds visit during training into slots of their own bank. + + Each step, a world that did not terminate records its outputs with ``probability``, and only where the + ``record_when`` input, if bound, is above 0.5. Records go to ``slots`` extra slots per world, the oldest replaced + first; they start as copies of the filled states. A replaced slot forgets its outcomes and starts at the success + rate that the sampler's first score targets, so that new states are tried. + """ + + slots: int + probability: float @dataclass(frozen=True) class FillFromStates: - """Fill the bank with given states, such as states saved from an earlier fill or demonstrations. + """Fill the bank with given states, such as demonstrations. - ``states`` maps each output to ``(num_worlds, bank_size, ...)`` states, or ``(bank_size, ...)`` for a shared bank, - in the frame the event restores: poses relative to the environment origins when the use binds ``env_origins``. + ``states`` maps each output to ``(num_worlds, size, ...)`` states, or ``(size, ...)`` for a shared bank, in the + frame the event restores: poses relative to the environment origins when the use binds ``env_origins``. """ states: Mapping[str, torch.Tensor] @@ -51,6 +69,21 @@ def __call__(self, ctx: TermContext, shared: bool) -> dict[str, torch.Tensor]: return {name: value.to(ctx.rng.device) for name, value in self.states.items()} +@dataclass(frozen=True) +class FillFromFile: + """Fill the bank with states that :meth:`ResetBank.save` wrote, such as a separate collection run.""" + + path: str | Path + + def __call__(self, ctx: TermContext, shared: bool) -> dict[str, torch.Tensor]: + saved = torch.load(self.path, map_location=ctx.rng.device) + if saved["shared"] != shared or not shared and saved["num_worlds"] != ctx.num_worlds: + kind = "a shared bank" if saved["shared"] else f"banks of {saved['num_worlds']} worlds" + wanted = "a shared bank" if shared else f"banks of {ctx.num_worlds} worlds" + raise ValueError(f"{self.path} holds {kind}, but the event needs {wanted}.") + return saved["states"] + + @dataclass(frozen=True) class FillFromCandidates: """Fill the bank by rejection sampling the reset events of a ``candidates`` task. @@ -142,87 +175,324 @@ def farthest_points(points: torch.Tensor, count: int) -> torch.Tensor: return chosen +class ResetBank: + """The start states of a reset event, the sampler that chooses among them, and the worlds' current choices. + + Slots are numbered within a world's bank, or within the shared bank. Get it with :func:`reset_bank`. Reading + allocates and synchronizes; :meth:`replay` and the event's hooks do not, and replay inside the step's CUDA graph. + """ + + def __init__( + self, + states: Mapping[str, torch.Tensor], + outputs: Mapping[str, wp.array], + sampler: ResetStateSamplerCfg, + *, + shared: bool, + origins: wp.array | None, + nominal_probability: float, + record: RecordStates | None, + ) -> None: + first = next(iter(outputs.values())) + num_worlds, device = first.shape[0], first.device + filled = next(iter(states.values())).shape[0 if shared else 1] + recorded = 0 if record is None else record.slots + self.num_worlds, self.shared, self.size = num_worlds, shared, filled + recorded + self._filled, self._record, self._nominal = filled, record, float(nominal_probability) + + # Recorded slots start as copies of the filled ones, so every slot can be drawn from the start. + cycle = torch.arange(self.size, device=states[next(iter(states))].device) % filled + rows = {} + for name, value in states.items(): + value = value[cycle] if shared else value[:, cycle] + rows[name] = wp.from_torch( + value.reshape(-1, *value.shape[1 if shared else 2 :]).contiguous(), dtype=outputs[name].dtype + ) + self.buffer = ResetStateBuffer(rows) + num_groups = 1 if shared else num_worlds + groups = None if shared else wp.array(range(num_worlds), dtype=wp.int32, device=device) + self.sampler = ResetStateSampler( + sampler, num_worlds, self.size * num_groups, device, group_ids=groups, num_groups=num_groups + ) + scores = [score for score in sampler.scores if isinstance(score, BetaSamplingScoreCfg)] + self._prior = scores[0].target if scores else 0.0 + + self._outputs, self._origins = dict(outputs), origins + self._poses = ( + [value for value in outputs.values() if value.dtype == wp.transformf] if origins is not None else [] + ) + zeros = functools.partial(wp.zeros, num_worlds, device=device) + self._requests = wp.full(num_worlds, -1, dtype=wp.int32, device=device) + self._restored, self._credit, self._valid = zeros(dtype=wp.bool), zeros(dtype=wp.bool), zeros(dtype=wp.bool) + self._recording, self._record_rows = zeros(dtype=wp.bool), zeros(dtype=wp.int32) + self._cursor = zeros(dtype=wp.int32) + # Recording stores poses relative to the origins, from copies of the outputs. + self._record_values = { + name: wp.empty_like(value) if any(value is pose for pose in self._poses) else value + for name, value in self._outputs.items() + } + + @property + def states(self) -> dict[str, torch.Tensor]: + """Copies of the stored states, ``(num_worlds, size, ...)`` per output, or ``(size, ...)`` if shared. Poses + are relative to the environment origins when the use binds them.""" + rows = {name: value.torch for name, value in self.buffer.states.items()} + return ( + rows + if self.shared + else {name: value.view(self.num_worlds, self.size, *value.shape[1:]) for name, value in rows.items()} + ) + + @property + def success_rate(self) -> torch.Tensor: + """Recent success rate of each slot, ``(num_worlds, size)``, or ``(size,)`` if shared.""" + return self._per_slot(self.sampler.success_rate.torch) + + @property + def episode_counts(self) -> torch.Tensor: + """Episodes that started from each slot since it was filled, ``(num_worlds, size)`` or ``(size,)``.""" + return self._per_slot(self.sampler.episode_counts.torch) + + @property + def probabilities(self) -> torch.Tensor: + """Probability that the next draw picks each slot, ``(num_worlds, size)`` or ``(size,)``.""" + return self._per_slot(self.sampler.probabilities.torch) + + @property + def slots(self) -> torch.Tensor: + """The slot each world's episode started from, ``(num_worlds,)``; -1 for a nominal start or before the first + reset.""" + indices = self.sampler.indices.torch.long() + slots = indices if self.shared else indices - torch.arange(self.num_worlds, device=indices.device) * self.size + return torch.where(wp.to_torch(self._restored) & (indices >= 0), slots, -1) + + def replay(self, slots: torch.Tensor | None) -> None: + """Restart the worlds from the given slots at their next resets, ``(num_worlds,)``, -1 to draw as usual. + + The requests hold until replaced; None clears them. A slot outside the bank leaves the world's start unchanged + and sets the sampler's ``invalid_requests``. Replayed episodes are credited like drawn ones. + """ + requests = wp.to_torch(self._requests) + if slots is None: + requests.fill_(-1) + return + slots = slots.to(requests.device, torch.int32) + if not self.shared: + in_bank = (slots >= 0) & (slots < self.size) + rows = torch.arange(self.num_worlds, device=slots.device, dtype=torch.int32) * self.size + slots + slots = torch.where(in_bank, rows, torch.where(slots < 0, -1, self.size * self.num_worlds)) + requests.copy_(slots) + + def save(self, path: str | Path) -> None: + """Save the states, to fill a later run's bank with :class:`FillFromFile`.""" + torch.save({"states": self.states, "shared": self.shared, "num_worlds": self.num_worlds}, path) + + def restore(self, mask: wp.array, rng: wp.array, succeeded: wp.array | None) -> None: + """Credit the ended episodes, choose the next starts, and write the restored ones to the outputs.""" + wp.launch( + _choose_starts, + mask.shape, + [mask, rng, self._requests, self._nominal, self._credit, self._valid, self._restored], + device=mask.device, + ) + self.sampler.reset(mask, success=succeeded, valid=self._valid, state_ids=self._requests, rng=rng) + self.buffer.get_state(self.sampler.indices, out=self._outputs, mask=self._restored) + for pose in self._poses: + wp.launch(_shift_poses, mask.shape, [self._restored, self._origins, pose, pose, 1.0], device=mask.device) + + def record(self, rng: wp.array, terminated: wp.array, record_when: wp.array | None) -> None: + """Record the states of the worlds selected this step into their oldest recorded slots.""" + wp.launch( + _choose_records, + self.num_worlds, + [ + rng, + terminated, + record_when, + self._record.probability, + self._filled, + self._record.slots, + self.size, + self.sampler.indices.warp, + self._cursor, + self._credit, + self._recording, + self._record_rows, + ], + device=rng.device, + ) + for name, pose in self._outputs.items(): + if self._record_values[name] is not pose: + wp.launch( + _shift_poses, + self.num_worlds, + [self._recording, self._origins, pose, self._record_values[name], -1.0], + device=rng.device, + ) + self.sampler.forget(self._record_rows, self._recording, success_rate=self._prior) + self.buffer.set_state(self._record_rows, self._record_values, mask=self._recording) + + def _per_slot(self, values: torch.Tensor) -> torch.Tensor: + return values.clone() if self.shared else values.view(self.num_worlds, self.size).clone() + + +def reset_bank(state: MDPState, use: str = "events.reset") -> ResetBank: + """Return the bank of a :data:`reset_from_bank` use, by its name in the schedule.""" + cache = state.caches.get(use, {}) + if "bank" not in cache: + raise KeyError(f"'{use}' is not a reset_from_bank use. Uses with a cache: {sorted(state.caches)}.") + return cache["bank"] + + def _init( ctx: TermContext, *, fill: Callable[[TermContext, bool], dict[str, torch.Tensor]], sampler: ResetStateSamplerCfg | None = None, shared: bool = False, + nominal_probability: float = 0.0, + record: RecordStates | None = None, ) -> None: - """Fill the bank once, then build the sampler over it and bind the outputs it restores.""" + """Fill the bank once, then build its sampler and bind the outputs it restores.""" outputs = {name: _warp_view(ctx, name) for name in ctx.outputs} - if shared and "env_origins" not in ctx.inputs and any(value.dtype == wp.transformf for value in outputs.values()): + has_poses = any(value.dtype == wp.transformf for value in outputs.values()) + if shared and "env_origins" not in ctx.inputs and has_poses: raise ValueError("A shared bank of poses needs the env_origins input, so that poses transfer across worlds.") + if record is not None and (shared or "terminated" not in ctx.inputs or record.slots < 1): + raise ValueError( + "Recording needs a bank per world, at least one slot, and the terminated input (mdp2.terminated), so" + " that states which end the episode are not recorded." + ) + if not 0.0 <= nominal_probability <= 1.0: + raise ValueError(f"nominal_probability must be in [0, 1], got {nominal_probability}.") states = fill(ctx, shared) if states.keys() != outputs.keys(): raise ValueError(f"The fill returned states for {sorted(states)}, but the event writes {sorted(outputs)}.") - - num_worlds = ctx.num_worlds leading = 1 if shared else 2 - bank_sizes = {value.shape[leading - 1] for value in states.values()} - if len(bank_sizes) != 1 or (not shared and any(value.shape[0] != num_worlds for value in states.values())): + if ( + len({value.shape[leading - 1] for value in states.values()}) != 1 + or not shared + and any(value.shape[0] != ctx.num_worlds for value in states.values()) + ): raise ValueError("Every output needs the same number of states, per world unless the bank is shared.") - bank_size = bank_sizes.pop() - rows = { - name: wp.from_torch(value.reshape(-1, *value.shape[leading:]).contiguous(), dtype=outputs[name].dtype) - for name, value in states.items() - } - num_groups = 1 if shared else num_worlds - sampler_cfg = sampler if sampler is not None else ResetStateSamplerCfg(history_length=1, scores=[]) - device = outputs[next(iter(outputs))].device - groups = None if shared else wp.array(range(num_worlds), dtype=wp.int32, device=device) - origins = ctx.inputs.get("env_origins") - ctx.cache.update( - bank=ResetStateBuffer(rows), - sampler=ResetStateSampler( - sampler_cfg, num_worlds, bank_size * num_groups, device, group_ids=groups, num_groups=num_groups - ), - outputs=outputs, - poses=[value for value in outputs.values() if value.dtype == wp.transformf] if origins is not None else [], + origins = ctx.inputs.get("env_origins") + bank = ResetBank( + states, + outputs, + sampler if sampler is not None else ResetStateSamplerCfg(history_length=1, scores=[]), + shared=shared, origins=None if origins is None else wp.from_torch(origins.contiguous(), dtype=wp.vec3f), + nominal_probability=nominal_probability, + record=record, ) - # Load every kernel and the sampler's sort and scan scratch before a graph captures the hook: a reset of no worlds. - _reset_from_bank( - wp.zeros(num_worlds, dtype=wp.bool, device=device), ctx.cache, ctx.rng, ctx.inputs.get("succeeded") - ) + ctx.cache["bank"] = bank + # Load every kernel and the sampler's sort and scan scratch before a graph captures the hooks: a step and a reset + # of no worlds. + nothing = wp.zeros(ctx.num_worlds, dtype=wp.bool, device=bank.sampler.device) + rng, succeeded = _as_warp(ctx.rng), ctx.inputs.get("succeeded") + bank.restore(nothing, rng, None if succeeded is None else _as_warp(succeeded)) + if record is not None: + when = ctx.inputs.get("record_when") + bank.record(rng, wp.ones_like(nothing), None if when is None else _as_warp(when)) -def _reset_from_bank(mask: Any, cache: dict, rng: Any, succeeded: Any = None, **_: Any) -> None: - """Credit the ended episodes, draw the next states, and write them to the masked worlds' outputs.""" - mask, rng = _as_warp(mask), _as_warp(rng) - sampler: ResetStateSampler = cache["sampler"] - success = None if succeeded is None else _as_warp(succeeded) - sampler.reset(mask, success=success, rng=rng) - cache["bank"].get_state(sampler.indices, out=cache["outputs"], mask=mask) - for pose in cache["poses"]: - wp.launch(_add_origin, mask.shape, [mask, cache["origins"], pose], device=pose.device) +def _restore(mask: Any, cache: dict, rng: Any, succeeded: Any = None, **_: Any) -> None: + cache["bank"].restore(_as_warp(mask), _as_warp(rng), None if succeeded is None else _as_warp(succeeded)) -reset_from_bank = Term(torch=_reset_from_bank, warp=_reset_from_bank, random=True, init=_init) +def _record(cache: dict, rng: Any, terminated: Any = None, record_when: Any = None, **_: Any) -> None: + bank: ResetBank = cache["bank"] + if bank._record is not None: + bank.record(_as_warp(rng), _as_warp(terminated), None if record_when is None else _as_warp(record_when)) + + +_hooks = Implementation(compute=_restore, update=_record) +reset_from_bank = Term(torch=_hooks, warp=_hooks, random=True, init=_init) """Restart the reset worlds from start states drawn from a bank, the MDP2 counterpart of MDP1's lift ``conditional_reset``. -Params: ``fill``, a callable that returns the states, such as :class:`FillFromCandidates`; ``sampler``, a -:class:`~isaaclab.envs.reset.ResetStateSamplerCfg` that weighs the states by their recent success, or None to draw -uniformly; and ``shared``, whether every world draws from one bank rather than its own. Share a bank only between -worlds whose states fit each other: a state banked with one object spawned does not fit a world with another. +Params: + +- ``fill``: a callable that returns the states, such as :class:`FillFromCandidates` or :class:`FillFromFile`; +- ``sampler``: a :class:`~isaaclab.envs.reset.ResetStateSamplerCfg` that weighs the states by their recent success, + or None to draw uniformly; +- ``shared``: whether every world draws from one bank rather than its own. Share a bank only between worlds whose + states fit each other: a state banked with one object spawned does not fit a world with another; +- ``nominal_probability``: the fraction of resets that keep what the earlier reset events wrote. Those episodes are + not credited to any slot; +- ``record``: :class:`RecordStates`, to bank states visited during training. -Inputs: ``succeeded``, the ended episode's success, credited to the state it started from when bound; and -``env_origins``, which stores the poses relative to the environment origins so that a shared bank transfers across -worlds. +Inputs: ``succeeded``, the ended episode's success, credited to the slot it started from when bound; +``env_origins``, which stores the poses relative to the environment origins; ``terminated`` (``mdp2.terminated``), +required to record; and ``record_when``, a quantity above 0.5 where a state may be recorded. Place it after the other reset events: it overwrites the outputs they wrote. The bank and the sampler's history persist -across episodes. +across episodes; :func:`reset_bank` returns them. """ @wp.kernel -def _add_origin(mask: wp.array(dtype=wp.bool), origins: wp.array(dtype=wp.vec3f), pose: wp.array(dtype=wp.transformf)): +def _choose_starts( + mask: wp.array(dtype=wp.bool), + rng: wp.array(dtype=wp.int32), + requests: wp.array(dtype=wp.int32), + nominal_probability: float, + credit: wp.array(dtype=wp.bool), + valid: wp.array(dtype=wp.bool), + restored: wp.array(dtype=wp.bool), +): + world = wp.tid() + if not mask[world]: + return + # The ended episode counts if it started from a slot that was not recorded over since. + valid[world] = credit[world] + restore = requests[world] >= 0 or wp.randf(wp.rand_init(rng[world], 1)) >= nominal_probability + restored[world] = restore + credit[world] = restore + + +@wp.kernel +def _choose_records( + rng: wp.array(dtype=wp.int32), + terminated: wp.array(dtype=wp.bool), + record_when: wp.array(dtype=wp.float32), + probability: float, + first: int, + slots: int, + size: int, + indices: wp.array(dtype=wp.int32), + cursor: wp.array(dtype=wp.int32), + credit: wp.array(dtype=wp.bool), + recording: wp.array(dtype=wp.bool), + rows: wp.array(dtype=wp.int32), +): + world = wp.tid() + record = not terminated[world] and wp.randf(wp.rand_init(rng[world], 2)) < probability + if record_when: + record = record and record_when[world] > 0.5 + recording[world] = record + if not record: + return + row = world * size + first + cursor[world] + cursor[world] = (cursor[world] + 1) % slots + rows[world] = row + if indices[world] == row: + credit[world] = False + + +@wp.kernel +def _shift_poses( + mask: wp.array(dtype=wp.bool), + origins: wp.array(dtype=wp.vec3f), + pose: wp.array(dtype=wp.transformf), + out: wp.array(dtype=wp.transformf), + sign: float, +): world = wp.tid() if mask[world]: - pose[world] = wp.transformf( - wp.transform_get_translation(pose[world]) + origins[world], wp.transform_get_rotation(pose[world]) + out[world] = wp.transformf( + wp.transform_get_translation(pose[world]) + sign * origins[world], wp.transform_get_rotation(pose[world]) ) diff --git a/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py b/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py index 35dc9be1e90a..7ed73366626a 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py @@ -116,26 +116,29 @@ def reset(task_mdp, state, mask) -> None: mdp2.reset(task_mdp, state, ProxyArray(wp.from_torch(torch.tensor(mask, device=DEVICE)))) -def bank_rows(state) -> dict[str, np.ndarray]: - return {name: value.warp.numpy() for name, value in state.caches["events.reset"]["bank"].states.items()} +def joint_pos(scene: Scene) -> torch.Tensor: + return scene.data("robot", "joint_pos").torch[:, 0] + + +RECORDING = {"succeeded": mdp2.quantities.success, "terminated": mdp2.terminated} def test_candidates_fill_each_world_with_valid_states_and_restore_only_reset_worlds(): scene = Scene(num_worlds=8) task_mdp, state = build(scene, fill=mdp.FillFromCandidates(CANDIDATES, bank_size=4)) + bank = mdp.reset_bank(state) - banked = bank_rows(state)["joint_pos"].reshape(8, 4) - assert np.all(np.abs(banked) <= 0.5) and len(np.unique(banked)) == 32 + banked = bank.states["joint_pos"][..., 0].cpu() + assert banked.shape == (8, 4) and (banked.abs() <= 0.5).all() and len(banked.unique()) == 32 reset(task_mdp, state, [True] * 8) - joint_pos = scene.data("robot", "joint_pos").torch[:, 0].cpu().numpy() - assert all(joint_pos[world] in banked[world] for world in range(8)) # each world draws from its own bank + slots = bank.slots.cpu() + assert torch.equal(joint_pos(scene).cpu(), banked[torch.arange(8), slots]) # each world draws its own bank - before = scene.data("robot", "joint_pos").torch.clone() + before = joint_pos(scene).clone() for _ in range(8): reset(task_mdp, state, [True] + [False] * 7) - after = scene.data("robot", "joint_pos").torch - assert torch.equal(after[1:], before[1:]) + assert torch.equal(joint_pos(scene)[1:], before[1:]) def test_shared_bank_restores_poses_relative_to_each_world_origin(): @@ -150,10 +153,9 @@ def test_shared_bank_restores_poses_relative_to_each_world_origin(): ) reset(task_mdp, state, [True] * 4) - pose = scene.data("object", "root_link_pose_w").torch - slot = state.caches["events.reset"]["sampler"].indices.torch.long() + slot = mdp.reset_bank(state).slots origins = scene.data("scene", "env_origins").torch - torch.testing.assert_close(pose[:, :3], poses[slot, :3] + origins) + torch.testing.assert_close(scene.data("object", "root_link_pose_w").torch[:, :3], poses[slot, :3] + origins) torch.testing.assert_close(scene.data("robot", "joint_pos").torch, states["joint_pos"][slot]) @@ -171,34 +173,107 @@ def test_outcomes_are_credited_to_the_state_each_episode_started_from(): reset(task_mdp, state, [True] * 16) mdp2.evaluate(task_mdp, state, transition) # success: the restored joint position is positive - record = state.caches["events.reset"]["sampler"] - np.testing.assert_allclose(record.success_rate.warp.numpy(), [1.0, 0.0]) - assert record.episode_counts.warp.numpy().sum() == 5 * 16 # the first reset has no episode to credit + bank = mdp.reset_bank(state) + np.testing.assert_allclose(bank.success_rate.cpu().numpy(), [1.0, 0.0]) + assert bank.episode_counts.sum() == 5 * 16 # the first reset has no episode to credit + + +def test_recording_banks_visited_states_that_replay_restores(): + scene = Scene(num_worlds=2) + sampler = ResetStateSamplerCfg(history_length=4, scores=[BetaSamplingScoreCfg(target=0.5)]) + record = mdp.RecordStates(slots=2, probability=1.0) + inputs = {**RECORDING, "record_when": mdp2.quantities.success} + fill = mdp.FillFromCandidates(CANDIDATES, bank_size=2) + task_mdp, state = build(scene, fill=fill, sampler=sampler, record=record, inputs=inputs) + bank, transition = mdp.reset_bank(state), task_mdp.transition() + filled = bank.states["joint_pos"][:, :2].clone() + assert torch.equal(bank.states["joint_pos"][:, 2:], filled) # recorded slots start as copies + + # Only world 1 visits a successful state, which is recorded into its first recorded slot with a fresh prior. + joint_pos(scene).copy_(torch.tensor([-0.3, 0.7], device=DEVICE)) + mdp2.evaluate(task_mdp, state, transition) + banked = bank.states["joint_pos"][..., 0] + assert torch.equal(banked[0], filled[0, :, 0].repeat(2)) and banked[1, 2] == 0.7 + assert bank.episode_counts[1, 2] == 0 and bank.success_rate[1, 2] == 0.5 + + # Replay restarts world 1 from the recorded state; world 0 draws from its own bank. + bank.replay(torch.tensor([-1, 2])) + joint_pos(scene).fill_(9.0) + reset(task_mdp, state, [True, True]) + assert joint_pos(scene)[1] == 0.7 and joint_pos(scene)[0] in filled[0] + assert bank.slots.tolist()[1] == 2 + + # Recording over the slot the episode started from drops that episode's credit. + joint_pos(scene).copy_(torch.tensor([0.1, 0.2], device=DEVICE)) + mdp2.evaluate(task_mdp, state, transition) # world 1 records into slot 3 + mdp2.evaluate(task_mdp, state, transition) # then over slot 2 + bank.replay(None) + reset(task_mdp, state, [False, True]) + assert bank.episode_counts[1, 2] == 0 and (bank.states["joint_pos"][1, 2:, 0] == 0.2).all() + + +def test_nominal_resets_keep_the_earlier_events_and_are_not_credited(): + scene = Scene(num_worlds=4) + task_mdp, state = build(scene, fill=mdp.FillFromCandidates(CANDIDATES, bank_size=8), nominal_probability=1.0) + bank = mdp.reset_bank(state) + joint_pos(scene).fill_(9.0) + for _ in range(2): + reset(task_mdp, state, [True] * 4) + assert (joint_pos(scene) == 9.0).all() and (bank.slots == -1).all() and bank.episode_counts.sum() == 0 + + bank.replay(torch.tensor([5, -1, -1, -1])) # a replay request overrides the nominal draw + reset(task_mdp, state, [True] * 4) + assert joint_pos(scene)[0] == bank.states["joint_pos"][0, 5, 0] and (joint_pos(scene)[1:] == 9.0).all() -def test_backends_and_graph_replay_restore_the_same_states(): +def test_saved_banks_fill_later_runs_with_the_same_worlds(tmp_path): + scene = Scene(num_worlds=4) + _, state = build(scene, fill=mdp.FillFromCandidates(CANDIDATES, bank_size=3)) + path = tmp_path / "bank.pt" + mdp.reset_bank(state).save(path) + + _, loaded = build(Scene(num_worlds=4), fill=mdp.FillFromFile(path)) + for name, value in mdp.reset_bank(state).states.items(): + assert torch.equal(mdp.reset_bank(loaded).states[name], value) + with pytest.raises(ValueError, match="holds banks of 4 worlds"): + build(Scene(num_worlds=2), fill=mdp.FillFromFile(path)) + + +def test_backends_and_graph_replay_restore_and_record_the_same_states(): runs = [] for backend, capture in (("torch", False), ("warp", False), ("warp", True)): if capture and not DEVICE.startswith("cuda"): continue scene = Scene(num_worlds=32) - task_mdp, state = build(scene, backend, fill=mdp.FillFromCandidates(CANDIDATES, bank_size=8)) + task_mdp, state = build( + scene, + backend, + fill=mdp.FillFromCandidates(CANDIDATES, bank_size=8), + sampler=ResetStateSamplerCfg(history_length=4, scores=[BetaSamplingScoreCfg(target=0.5)]), + nominal_probability=0.25, + record=mdp.RecordStates(slots=4, probability=0.5), + inputs=RECORDING, + ) + bank = mdp.reset_bank(state) mask = ProxyArray(wp.zeros(32, dtype=wp.bool, device=DEVICE)) transition = task_mdp.transition() actions = ProxyArray(wp.zeros((32, 0), dtype=wp.float32, device=DEVICE)) captured = mdp2.CapturedMDP(task_mdp, state, transition, actions, mask) if capture else None generator = torch.Generator(device=DEVICE).manual_seed(0) history = [] - for _ in range(10): + for step in range(12): mask.torch.copy_(torch.rand(32, device=DEVICE, generator=generator) < 0.5) + joint_pos(scene).add_(0.01) # the worlds move, so that records differ from the filled states + bank.replay(torch.arange(32, device=DEVICE) % 12 - 4 if step == 6 else None) if captured is None: mdp2.reset(task_mdp, state, mask) mdp2.evaluate(task_mdp, state, transition) else: captured.reset() captured.evaluate() - history.append(scene.data("robot", "joint_pos").torch.clone()) + history.append(torch.cat([joint_pos(scene), bank.states["joint_pos"].flatten()])) runs.append(torch.stack(history)) + assert not torch.equal(runs[0][-1, 32:], runs[0][0, 32:]) # the worlds recorded states for run in runs[1:]: assert torch.equal(run, runs[0]) @@ -208,8 +283,12 @@ def test_backends_and_graph_replay_restore_the_same_states(): [ ({"fill": mdp.FillFromStates({"joint_pos": torch.zeros(2, 1, 1)})}, "but the event writes"), ({"fill": mdp.FillFromCandidates(CANDIDATES, bank_size=2), "shared": True}, "needs the env_origins input"), + ( + {"fill": mdp.FillFromCandidates(CANDIDATES, bank_size=2), "record": mdp.RecordStates(2, 0.1)}, + "the terminated input", + ), ], - ids=["fill_misses_an_output", "shared_poses_without_origins"], + ids=["fill_misses_an_output", "shared_poses_without_origins", "recording_without_terminated"], ) def test_invalid_banks_are_rejected_at_startup(params, message): with pytest.raises(ValueError, match=message): diff --git a/source/isaaclab_tasks/test/mdp2/test_lift_kuka_allegro.py b/source/isaaclab_tasks/test/mdp2/test_lift_kuka_allegro.py index 37f547470bf3..bf879021280c 100644 --- a/source/isaaclab_tasks/test/mdp2/test_lift_kuka_allegro.py +++ b/source/isaaclab_tasks/test/mdp2/test_lift_kuka_allegro.py @@ -78,8 +78,8 @@ def rand(*shape, scale=1.0): def bank_and_scene_state(env: MDP2RLEnv, state: mdp2.MDPState) -> dict[str, tuple[torch.Tensor, torch.Tensor]]: """Return, per banked field, the banked state that each world plays and the field's value in the scene.""" - cache = state.caches["events.reset"] - banked = cache["bank"].get_state(cache["sampler"].indices) + bank = mdp2.mdp.reset_bank(state) + banked = bank.buffer.get_state(bank.sampler.indices) robot, target = env.scene["robot"].data, env.scene["object"].data fields = { "joint_pos": robot.joint_pos, @@ -91,9 +91,15 @@ def bank_and_scene_state(env: MDP2RLEnv, state: mdp2.MDPState) -> dict[str, tupl def sampler_arrays(state: mdp2.MDPState) -> dict[str, torch.Tensor]: - """Return copies of the reset sampler's device state: its assignments, outcome history, and draw weights.""" - sampler = state.caches["events.reset"]["sampler"] - arrays = {name: value for name, value in vars(sampler).items() if isinstance(value, (wp.array, ProxyArray))} + """Return views of the reset bank's device state: its sampler's assignments, outcome history, and draw weights, + and the bank's own flags.""" + bank = mdp2.mdp.reset_bank(state) + arrays = { + f"{owner}.{name}": value + for owner, holder in (("sampler", bank.sampler), ("bank", bank)) + for name, value in vars(holder).items() + if isinstance(value, (wp.array, ProxyArray)) + } return {name: wp.to_torch(value.warp if isinstance(value, ProxyArray) else value) for name, value in arrays.items()} @@ -252,7 +258,7 @@ def test_step_replays_as_one_graph_with_curriculum_and_bank(scenario: SimpleName for name, value in sampler_arrays(state).items(): value.copy_(before[name]) mdp2.reset(mdp, state, mask) - playing[backend] = state.caches["events.reset"]["sampler"].indices.torch.clone() + playing[backend] = mdp2.mdp.reset_bank(state).sampler.indices.torch.clone() for name, (banked, restored) in bank_and_scene_state(env, state).items(): torch.testing.assert_close(restored, banked, atol=1e-5, rtol=0.0, msg=lambda message, name=name: name) assert torch.equal(playing["torch"], playing["warp"]) @@ -281,3 +287,40 @@ def test_play_mode_starts_the_curriculum_at_its_end(): params = cfg.task.events["adr"].params assert cfg.scene.num_envs == 50 and all(use.noise is None for use in uses) assert params["init_difficulty"] == params["max_difficulty"] and params["promotion_only"] + + +def test_recorded_states_restore_through_the_simulation(scenario: SimpleNamespace): + """A state recorded during a step is restored, through the scene's writers, when its slot is replayed.""" + env = scenario.env + task = dataclasses.replace(scenario.cfg.task, events=dict(scenario.cfg.task.events)) + event = task.events["reset"] + task.events["reset"] = dataclasses.replace( + event, + inputs={**event.inputs, "terminated": mdp2.terminated}, + params={**event.params, "record": mdp2.mdp.RecordStates(slots=1, probability=1.0)}, + ) + builder = mdp2.MDPBuilder(env.scene_data.schema) + builder.add_task(task) + mdp = builder.finalize(device=env.device, backend="warp") + state, transition = mdp.state(env.scene_data), mdp.transition() + mdp2.startup(mdp, state) # fills a new bank from the candidates + bank = mdp2.mdp.reset_bank(state) + + for _ in range(3): + env.sim.step(render=False) + env.scene.update(dt=env.physics_dt) + visited = {name: scene for name, (_, scene) in bank_and_scene_state(env, state).items()} + mdp2.evaluate(mdp, state, transition) + recorded = ~transition.terminated.torch + assert recorded.any() + + mask = ProxyArray(wp.ones(NUM_ENVS, dtype=wp.bool, device=env.device)) + bank.replay(torch.full((NUM_ENVS,), bank.size - 1, device=env.device)) + commit = lambda: env.scene_data.commit(mask.warp, mdp.reset_writes) # noqa: E731 + mdp2.reset(mdp, state, mask, commit) + commit() + env.scene.update(dt=0.0) + for name, (_, restored) in bank_and_scene_state(env, state).items(): + torch.testing.assert_close( + restored[recorded], visited[name][recorded], atol=1e-5, rtol=0.0, msg=lambda message, name=name: name + ) From 9ccd10563feb506c3eeeb44ac397a9214db65442 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 18:15:30 -0800 Subject: [PATCH 05/17] Bank commands from the candidates task and skip credit for manual resets FillFromCandidates now reads commands the event restores from the candidates' own state, where they are sampled, and rejects a candidates task without them. ResetBank.discard_outcomes keeps a reset by hand mid-episode from crediting the unfinished episodes. The -1 request change moves to the Changed changelog. --- .../changelog.d/mdp2-resets.added.rst | 2 - .../changelog.d/mdp2-resets.changed.rst | 3 ++ .../changelog.d/mdp2-resets.added.rst | 2 +- .../mdp2/mdp/reset_states.py | 15 ++++++- .../test/mdp2/test_mdp2_reset_states.py | 45 +++++++++++++++++++ 5 files changed, 63 insertions(+), 4 deletions(-) create mode 100644 source/isaaclab/changelog.d/mdp2-resets.changed.rst diff --git a/source/isaaclab/changelog.d/mdp2-resets.added.rst b/source/isaaclab/changelog.d/mdp2-resets.added.rst index 859b18224a10..47d094f3ae7b 100644 --- a/source/isaaclab/changelog.d/mdp2-resets.added.rst +++ b/source/isaaclab/changelog.d/mdp2-resets.added.rst @@ -2,5 +2,3 @@ per-environment int32 seeds, such as MDP2's random streams, drive the draws. * Added :meth:`~isaaclab.envs.reset.ResetStateBuffer.set_state`, the inverse of ``get_state``, to replace stored states while running, and :meth:`~isaaclab.envs.reset.ResetStateSampler.forget` to clear the outcomes of replaced entries. -* Added per-environment sampling to explicit requests: a ``state_ids`` request of -1 in - :meth:`~isaaclab.envs.reset.ResetStateSampler.reset` draws from the scores instead of being invalid. diff --git a/source/isaaclab/changelog.d/mdp2-resets.changed.rst b/source/isaaclab/changelog.d/mdp2-resets.changed.rst new file mode 100644 index 000000000000..5d946b57cb8e --- /dev/null +++ b/source/isaaclab/changelog.d/mdp2-resets.changed.rst @@ -0,0 +1,3 @@ +* Changed a ``state_ids`` request of -1 in :meth:`~isaaclab.envs.reset.ResetStateSampler.reset` to draw from the + scores for that environment, so that one captured reset can replay some environments and sample the others. It + was an invalid request that left the environment's start unchanged. diff --git a/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst b/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst index c04ea85af269..987f36f2abc0 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst @@ -5,6 +5,6 @@ use's Python hooks reuse. * Added recording, replay, and saving to ``reset_from_bank``: ``RecordStates`` banks states that the worlds visit during training, ``nominal_probability`` keeps a fraction of nominal resets, and ``reset_bank`` returns a ``ResetBank`` to - inspect, replay, and save, which ``FillFromFile`` loads. + inspect, replay, save, or discard the outcomes of manual resets, and ``FillFromFile`` loads a saved bank. * Added scheduling of reset events' ``update`` hooks once per step after the rewards, and ordering of reset events that write commands after the commands resample, so that a restored command stands. diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py index dd519a1eef73..69a329d60376 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py @@ -110,7 +110,16 @@ def __call__(self, ctx: TermContext, shared: bool) -> dict[str, torch.Tensor]: size = self.bank_size if descriptor is None else round(self.bank_size * self.oversample_factor) if self.bank_size < 1 or size < self.bank_size: raise ValueError("The bank must harvest at least as many states as it keeps, and keep at least one.") - fields = dict(ctx.outputs) + # Scene outputs are read from the scene the candidates write; commands from the candidates' own state. + fields = {} + for name, value in ctx.outputs.items(): + selector = ctx.selectors[name] + if selector.scene: + fields[name] = value + elif selector in state.arrays: + fields[name] = state.arrays[selector].torch + else: + raise ValueError(f"The candidates task must define '{selector}', which the event restores.") if descriptor is not None: fields["descriptor"] = descriptor.torch # Root poses are kept relative to the environment origins when the use binds them. @@ -283,6 +292,10 @@ def replay(self, slots: torch.Tensor | None) -> None: slots = torch.where(in_bank, rows, torch.where(slots < 0, -1, self.size * self.num_worlds)) requests.copy_(slots) + def discard_outcomes(self) -> None: + """Credit none of the worlds' current episodes, such as before resetting them by hand mid-episode.""" + self._credit.zero_() + def save(self, path: str | Path) -> None: """Save the states, to fill a later run's bank with :class:`FillFromFile`.""" torch.save({"states": self.states, "shared": self.shared, "num_worlds": self.num_worlds}, path) diff --git a/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py b/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py index 7ed73366626a..f2e617c5222b 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py @@ -177,6 +177,10 @@ def test_outcomes_are_credited_to_the_state_each_episode_started_from(): np.testing.assert_allclose(bank.success_rate.cpu().numpy(), [1.0, 0.0]) assert bank.episode_counts.sum() == 5 * 16 # the first reset has no episode to credit + bank.discard_outcomes() # a reset by hand mid-episode credits nothing + reset(task_mdp, state, [True] * 16) + assert bank.episode_counts.sum() == 5 * 16 + def test_recording_banks_visited_states_that_replay_restores(): scene = Scene(num_worlds=2) @@ -239,6 +243,47 @@ def test_saved_banks_fill_later_runs_with_the_same_worlds(tmp_path): build(Scene(num_worlds=2), fill=mdp.FillFromFile(path)) +@wp.func +def _sample_goal(world: int, command: wp.array(dtype=float), rng: wp.int32): + command[world] = wp.randf(wp.rand_init(rng, 0), 1.0, 2.0) + + +def _sample_goal_torch(mask, command, rng): + command.copy_(torch.where(mask, mdp2.uniform(rng, 1.0, 2.0), command)) + + +sample_goal = mdp2.Term(torch=_sample_goal_torch, warp=_sample_goal, random=True) + + +def test_banked_commands_are_sampled_by_the_candidates_and_stand_over_the_resample(): + goal = {"goal": mdp2.commands.goal} + commands = {"goal": mdp2.Command(sample_goal)} + candidates = mdp2.TaskCfg( + commands=commands, + events={"draw": mdp2.Event(draw, outputs=outputs)}, + terminations=CANDIDATES.terminations, + ) + for backend in ("torch", "warp"): + scene = Scene(num_worlds=4) + event = mdp2.Event( + mdp.reset_from_bank, + outputs={**outputs, **goal}, + params={"fill": mdp.FillFromCandidates(candidates, bank_size=3)}, + ) + builder = mdp2.MDPBuilder(scene.schema) + builder.add_task(mdp2.TaskCfg(commands=commands, events={"reset": event})) + task_mdp = builder.finalize(device=DEVICE, backend=backend) + state = task_mdp.state(scene, seed=3) + mdp2.startup(task_mdp, state) + bank = mdp.reset_bank(state) + + banked = bank.states["goal"] + assert ((banked >= 1.0) & (banked < 2.0)).all() and len(banked.unique()) == 12 # sampled, not the initial 0 + reset(task_mdp, state, [True] * 4) + restored = bank.states["goal"][torch.arange(4), bank.slots] + assert torch.equal(state.arrays[mdp2.commands.goal].torch, restored) + + def test_backends_and_graph_replay_restore_and_record_the_same_states(): runs = [] for backend, capture in (("torch", False), ("warp", False), ("warp", True)): From be8ad7bfdd702418034a582ae577e551b01c93a4 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 18:16:44 -0800 Subject: [PATCH 06/17] Extract the candidates roller from FillFromCandidates Candidates binds a candidates task to the scene and proposes a state in every world per roll, so that tools such as a viewer can show what the fill does. --- .../changelog.d/mdp2-resets.added.rst | 3 +- .../mdp2/mdp/__init__.pyi | 2 + .../mdp2/mdp/reset_states.py | 59 ++++++++++++------- 3 files changed, 41 insertions(+), 23 deletions(-) diff --git a/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst b/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst index 987f36f2abc0..77b7f1b48789 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst @@ -1,6 +1,7 @@ * Added ``isaaclab_experimental.mdp2.mdp.reset_from_bank``, an MDP2 reset event that restores start states from a :class:`~isaaclab.envs.reset.ResetStateBuffer` drawn by a :class:`~isaaclab.envs.reset.ResetStateSampler`, with - ``FillFromCandidates`` and ``FillFromStates`` to fill the bank per world or shared across worlds. + ``FillFromCandidates`` and ``FillFromStates`` to fill the bank per world or shared across worlds, and ``Candidates``, + a candidates task bound to the scene that proposes start states one roll at a time. * Added ``cache`` to :class:`~isaaclab_experimental.mdp2.TermContext`, so init hooks can build host objects that the use's Python hooks reuse. * Added recording, replay, and saving to ``reset_from_bank``: ``RecordStates`` banks states that the worlds visit during diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi index bf3c33f514ee..3091651db5d6 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi @@ -18,6 +18,7 @@ __all__ = [ "reset_joints_by_offset", "reset_joints_by_scale", "reset_root_state_uniform", + "Candidates", "FillFromCandidates", "FillFromFile", "FillFromStates", @@ -81,6 +82,7 @@ from .events import ( reset_root_state_uniform, ) from .reset_states import ( + Candidates, FillFromCandidates, FillFromFile, FillFromStates, diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py index 69a329d60376..fc70b9c7406f 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py @@ -84,6 +84,36 @@ def __call__(self, ctx: TermContext, shared: bool) -> dict[str, torch.Tensor]: return saved["states"] +class Candidates: + """A candidates task bound to a scene, rolled to propose start states. + + Each :meth:`roll` resets every world through the task's reset events, commits them to the scene, and evaluates + its terminations, which reject states. The scene then holds the proposals. + """ + + def __init__(self, task: TaskCfg, scene_data: Any, device: str, seed: int = 0) -> None: + builder = MDPBuilder(scene_data.schema) + builder.add_task(task) + self.mdp = builder.finalize(device=device, backend="warp") + self.state, self.transition = self.mdp.state(scene_data, seed=seed), self.mdp.transition() + startup(self.mdp, self.state) + self._mask = ProxyArray(wp.ones(self.mdp.num_worlds, dtype=wp.bool, device=device)) + self._commit = functools.partial(scene_data.commit, self._mask.warp, self.mdp.reset_writes) + + def roll(self) -> torch.Tensor: + """Propose a state in every world and return which ones no termination rejects, ``(num_worlds,)``.""" + reset(self.mdp, self.state, self._mask, self._commit) + self._commit() + evaluate(self.mdp, self.state, self.transition) + return ~self.transition.terminated.torch + + def field(self, selector: Any) -> torch.Tensor: + """Return the proposed values of a field of the MDP, such as a command that the candidates sample.""" + if selector not in self.state.arrays: + raise ValueError(f"The candidates task must define '{selector}', which the event restores.") + return self.state.arrays[selector].torch + + @dataclass(frozen=True) class FillFromCandidates: """Fill the bank by rejection sampling the reset events of a ``candidates`` task. @@ -100,26 +130,16 @@ class FillFromCandidates: def __call__(self, ctx: TermContext, shared: bool) -> dict[str, torch.Tensor]: num_worlds, device = ctx.num_worlds, ctx.rng.device - builder = MDPBuilder(ctx.scene_data.schema) - builder.add_task(self.candidates) - mdp = builder.finalize(device=str(device), backend="warp") - state, transition = mdp.state(ctx.scene_data, seed=int(ctx.rng[0])), mdp.transition() - startup(mdp, state) - - descriptor = transition.observations.get("descriptor") + candidates = Candidates(self.candidates, ctx.scene_data, str(device), seed=int(ctx.rng[0])) + descriptor = candidates.transition.observations.get("descriptor") size = self.bank_size if descriptor is None else round(self.bank_size * self.oversample_factor) if self.bank_size < 1 or size < self.bank_size: raise ValueError("The bank must harvest at least as many states as it keeps, and keep at least one.") # Scene outputs are read from the scene the candidates write; commands from the candidates' own state. - fields = {} - for name, value in ctx.outputs.items(): - selector = ctx.selectors[name] - if selector.scene: - fields[name] = value - elif selector in state.arrays: - fields[name] = state.arrays[selector].torch - else: - raise ValueError(f"The candidates task must define '{selector}', which the event restores.") + fields = { + name: value if ctx.selectors[name].scene else candidates.field(ctx.selectors[name]) + for name, value in ctx.outputs.items() + } if descriptor is not None: fields["descriptor"] = descriptor.torch # Root poses are kept relative to the environment origins when the use binds them. @@ -130,13 +150,8 @@ def __call__(self, ctx: TermContext, shared: bool) -> dict[str, torch.Tensor]: harvest = {name: value.new_zeros(*rows, *value.shape[1:]) for name, value in fields.items()} filled = torch.zeros(num_worlds if not shared else 1, dtype=torch.long, device=device) worlds = torch.arange(num_worlds, device=device) - mask = ProxyArray(wp.ones(num_worlds, dtype=wp.bool, device=str(device))) - commit = functools.partial(ctx.scene_data.commit, mask.warp, mdp.reset_writes) for _ in range(self.max_rolls): - reset(mdp, state, mask, commit) - commit() - evaluate(mdp, state, transition) - accepted = ~transition.terminated.torch + accepted = candidates.roll() values = {name: _minus_origin(value, origins) if name in poses else value for name, value in fields.items()} if shared: take = worlds[accepted][: size - int(filled)] From 1ab873baa2312b54b1fdd3b9b77833f5a8ba579a Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Sat, 21 Nov 2026 06:54:21 -0800 Subject: [PATCH 07/17] Dump callable config objects without a name as their fields Co-Authored-By: Claude Opus 5.5 --- .../changelog.d/callable-instance-dump.fixed.rst | 2 ++ source/isaaclab/isaaclab/utils/dict.py | 4 ++-- source/isaaclab/test/utils/test_dict.py | 13 +++++++++++++ 3 files changed, 17 insertions(+), 2 deletions(-) create mode 100644 source/isaaclab/changelog.d/callable-instance-dump.fixed.rst diff --git a/source/isaaclab/changelog.d/callable-instance-dump.fixed.rst b/source/isaaclab/changelog.d/callable-instance-dump.fixed.rst new file mode 100644 index 000000000000..f7d407f91cdb --- /dev/null +++ b/source/isaaclab/changelog.d/callable-instance-dump.fixed.rst @@ -0,0 +1,2 @@ +* Fixed :func:`~isaaclab.utils.dict.class_to_dict` failing on a callable object without a ``__name__``, such as a + configured reset bank filler; it is now serialized as its fields, so ``params/env.yaml`` can be saved. diff --git a/source/isaaclab/isaaclab/utils/dict.py b/source/isaaclab/isaaclab/utils/dict.py index 0869b73d08e6..c258abdd1490 100644 --- a/source/isaaclab/isaaclab/utils/dict.py +++ b/source/isaaclab/isaaclab/utils/dict.py @@ -62,8 +62,8 @@ def class_to_dict(obj: object) -> dict[str, Any]: # Keep lazy callable references as strings; don't force callable introspection. if isinstance(value, ResolvableString): data[key] = str(value) - # check if attribute is callable -- function - elif callable(value): + # check if attribute is callable -- function or class; a callable instance is dumped as its fields + elif callable(value) and hasattr(value, "__name__"): data[key] = callable_to_string(value) # check if attribute is a dictionary elif hasattr(value, "__dict__") or isinstance(value, dict): diff --git a/source/isaaclab/test/utils/test_dict.py b/source/isaaclab/test/utils/test_dict.py index 86140c4e5656..b2e5fc296ffc 100644 --- a/source/isaaclab/test/utils/test_dict.py +++ b/source/isaaclab/test/utils/test_dict.py @@ -155,6 +155,19 @@ def test_class_to_dict_serializes_enums_as_values(): assert not isinstance(data["level"], dict) +def test_class_to_dict_serializes_callable_instances_as_fields(): + """A callable object without a name, such as a configured sampler, should serialize to its fields.""" + + class _Fill: + def __init__(self): + self.bank_size = 16 + + def __call__(self): + pass + + assert dict_utils.class_to_dict({"fill": _Fill()}) == {"fill": {"bank_size": 16}} + + def test_update_class_from_dict_restores_enums_from_values(): """Serializing and reloading a config should hand back enum members, not raw scalars.""" cfg = _EnumCfg() From 221f2c1a93158b32f1a37f222ec9ec45c9e131ec Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Sat, 21 Nov 2026 22:52:08 -0800 Subject: [PATCH 08/17] Restore only the worlds that reset from the bank A reset rewrote every world that had restored from the bank at an earlier reset, so on a step that reset some worlds the others jumped back to their start states, and the robots of the lift never moved. Co-Authored-By: Claude Opus 5.5 --- .../isaaclab_experimental/mdp2/mdp/reset_states.py | 10 +++++++--- .../test/mdp2/test_mdp2_reset_states.py | 1 + 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py index fc70b9c7406f..07ffacacba17 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py @@ -248,6 +248,7 @@ def __init__( zeros = functools.partial(wp.zeros, num_worlds, device=device) self._requests = wp.full(num_worlds, -1, dtype=wp.int32, device=device) self._restored, self._credit, self._valid = zeros(dtype=wp.bool), zeros(dtype=wp.bool), zeros(dtype=wp.bool) + self._writes = zeros(dtype=wp.bool) # the worlds that this reset restores self._recording, self._record_rows = zeros(dtype=wp.bool), zeros(dtype=wp.int32) self._cursor = zeros(dtype=wp.int32) # Recording stores poses relative to the origins, from copies of the outputs. @@ -320,13 +321,13 @@ def restore(self, mask: wp.array, rng: wp.array, succeeded: wp.array | None) -> wp.launch( _choose_starts, mask.shape, - [mask, rng, self._requests, self._nominal, self._credit, self._valid, self._restored], + [mask, rng, self._requests, self._nominal, self._credit, self._valid, self._restored, self._writes], device=mask.device, ) self.sampler.reset(mask, success=succeeded, valid=self._valid, state_ids=self._requests, rng=rng) - self.buffer.get_state(self.sampler.indices, out=self._outputs, mask=self._restored) + self.buffer.get_state(self.sampler.indices, out=self._outputs, mask=self._writes) for pose in self._poses: - wp.launch(_shift_poses, mask.shape, [self._restored, self._origins, pose, pose, 1.0], device=mask.device) + wp.launch(_shift_poses, mask.shape, [self._writes, self._origins, pose, pose, 1.0], device=mask.device) def record(self, rng: wp.array, terminated: wp.array, record_when: wp.array | None) -> None: """Record the states of the worlds selected this step into their oldest recorded slots.""" @@ -469,14 +470,17 @@ def _choose_starts( credit: wp.array(dtype=wp.bool), valid: wp.array(dtype=wp.bool), restored: wp.array(dtype=wp.bool), + writes: wp.array(dtype=wp.bool), ): world = wp.tid() + writes[world] = False if not mask[world]: return # The ended episode counts if it started from a slot that was not recorded over since. valid[world] = credit[world] restore = requests[world] >= 0 or wp.randf(wp.rand_init(rng[world], 1)) >= nominal_probability restored[world] = restore + writes[world] = restore credit[world] = restore diff --git a/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py b/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py index f2e617c5222b..0df152ced84e 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py @@ -135,6 +135,7 @@ def test_candidates_fill_each_world_with_valid_states_and_restore_only_reset_wor slots = bank.slots.cpu() assert torch.equal(joint_pos(scene).cpu(), banked[torch.arange(8), slots]) # each world draws its own bank + joint_pos(scene).add_(1.0) # the worlds move on, as a step would move them before = joint_pos(scene).clone() for _ in range(8): reset(task_mdp, state, [True] + [False] * 7) From b87425519747dbc261eb35b95d4ab7a879278ee2 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Sun, 22 Nov 2026 11:39:36 -0800 Subject: [PATCH 09/17] Bank reset states per group of worlds, as MDP1's lift does per object reset_from_bank gains groups, a callable that returns the group of each world, for one bank per group whose worlds draw from its states and share its success statistics; prototype_groups groups the worlds by the object they spawned. A bank per world and a shared bank are the two ends of it. The MDP2 Kuka Allegro lift now banks 1024 states per object, harvested twice over and thinned to the most spread, as MDP1 does: with a bank of 16 states per world, each world's success statistics were too sparse for the sampler to adapt, and a trained MDP1 policy reached half its success in the MDP2 task. --- docs/source/how-to/reset_state_buffers.rst | 11 +- .../changelog.d/mdp2-resets.added.rst | 3 +- .../mdp2/mdp/__init__.pyi | 2 + .../mdp2/mdp/reset_states.py | 171 +++++++++++------- .../test/mdp2/test_mdp2_reset_states.py | 29 +++ .../changelog.d/mdp2-resets.changed.rst | 3 +- .../mdp2/lift_kuka_allegro/lift_env_cfg.py | 17 +- .../test/mdp2/test_lift_kuka_allegro.py | 4 +- 8 files changed, 167 insertions(+), 73 deletions(-) diff --git a/docs/source/how-to/reset_state_buffers.rst b/docs/source/how-to/reset_state_buffers.rst index cd33c9dbd9c2..abead237d82b 100644 --- a/docs/source/how-to/reset_state_buffers.rst +++ b/docs/source/how-to/reset_state_buffers.rst @@ -249,6 +249,10 @@ MDP2 commits. The outputs are the state: any writable scene fields. * ``shared`` selects one bank for every world instead of one bank per world. Bind ``env_origins`` so poses are stored relative to each world's origin. Share a bank only between worlds whose states fit each other, such as worlds that spawn the same object. +* ``groups`` selects one bank per group of worlds, given a callable that returns each world's group. + :func:`~isaaclab_experimental.mdp2.mdp.reset_states.prototype_groups` groups the worlds by the object, or other + prototype, that the scene cloned into them, as MDP1's lift bank does: the worlds of a group draw from one bank and + share its success statistics. Bind ``env_origins`` here too. * ``nominal_probability`` is the fraction of resets that keep what the earlier reset events wrote, fresh draws from the nominal distribution. Those episodes are not credited to any state. * ``record`` banks states that the worlds visit during training, see below. @@ -256,7 +260,8 @@ MDP2 commits. The outputs are the state: any writable scene fields. Place the event after the other reset events: it overwrites the outputs they wrote. An event whose outputs include a command runs after the commands resample, so that a restored goal stands. The init hook warms every kernel, so the event is captured with the rest of the step. -``Isaac-Lift-KukaAllegro-MDP2`` uses a bank per world with the core Lift sampler settings. +``Isaac-Lift-KukaAllegro-MDP2`` uses a bank of 1024 states per object, grouped with +:func:`~isaaclab_experimental.mdp2.mdp.reset_states.prototype_groups`, with the core Lift sampler settings. Record states along the horizon ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -317,8 +322,8 @@ bank: ./isaaclab.sh -p scripts/tools/collect_reset_states.py --task Isaac-Lift-KukaAllegro-MDP2 \ --num_envs 4096 --bank_size 64 --out kuka_lift_bank.pt physics=newton_mjwarp -A bank per world fits only runs with the same number of worlds and object assignment; a shared -bank fits any. +A bank per world or per group fits only runs with the same number of worlds and object assignment; +a shared bank fits any. Migrating existing reset configurations --------------------------------------- diff --git a/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst b/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst index 77b7f1b48789..622871932085 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst @@ -1,6 +1,7 @@ * Added ``isaaclab_experimental.mdp2.mdp.reset_from_bank``, an MDP2 reset event that restores start states from a :class:`~isaaclab.envs.reset.ResetStateBuffer` drawn by a :class:`~isaaclab.envs.reset.ResetStateSampler`, with - ``FillFromCandidates`` and ``FillFromStates`` to fill the bank per world or shared across worlds, and ``Candidates``, + ``FillFromCandidates`` and ``FillFromStates`` to fill the bank per world, per group of worlds (``groups``, such as + ``prototype_groups``, which groups worlds by the object they spawned), or shared across worlds, and ``Candidates``, a candidates task bound to the scene that proposes start states one roll at a time. * Added ``cache`` to :class:`~isaaclab_experimental.mdp2.TermContext`, so init hooks can build host objects that the use's Python hooks reuse. diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi index 3091651db5d6..9726034c5745 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi @@ -25,6 +25,7 @@ __all__ = [ "RecordStates", "ResetBank", "farthest_points", + "prototype_groups", "reset_bank", "reset_from_bank", "base_ang_vel", @@ -89,6 +90,7 @@ from .reset_states import ( RecordStates, ResetBank, farthest_points, + prototype_groups, reset_bank, reset_from_bank, ) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py index 07ffacacba17..668367ae95ec 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py @@ -14,9 +14,11 @@ - the restore, which gathers the drawn states into the event's ``outputs``. The outputs are the state: any writable fields, such as ``robot.joint_pos`` and ``object.root_link_pose_w``, and -commands, whose restored value then stands over the resample. A fill is a callable ``fill(ctx, shared) -> {output: -tensor}`` that returns, per output, ``(num_worlds, size, ...)`` states for a bank per world, or ``(size, ...)`` for one -bank that every world shares. :func:`reset_bank` returns the bank of a use, to inspect, replay, or save it. +commands, whose restored value then stands over the resample. A fill is a callable ``fill(ctx, groups) -> {output: +tensor}`` that returns, per output, ``(num_groups, size, ...)`` states for a bank per group of worlds, given the +group of each world as ``groups``, ``(num_worlds,)``, or ``(size, ...)`` for one bank that every world shares, given +None. A bank per world is a group per world. :func:`reset_bank` returns the bank of a use, to inspect, replay, or +save it. """ from __future__ import annotations @@ -59,13 +61,14 @@ class RecordStates: class FillFromStates: """Fill the bank with given states, such as demonstrations. - ``states`` maps each output to ``(num_worlds, size, ...)`` states, or ``(size, ...)`` for a shared bank, in the - frame the event restores: poses relative to the environment origins when the use binds ``env_origins``. + ``states`` maps each output to ``(num_groups, size, ...)`` states, ``(num_worlds, size, ...)`` for a bank per + world, or ``(size, ...)`` for a shared bank, in the frame the event restores: poses relative to the environment + origins when the use binds ``env_origins``. """ states: Mapping[str, torch.Tensor] - def __call__(self, ctx: TermContext, shared: bool) -> dict[str, torch.Tensor]: + def __call__(self, ctx: TermContext, groups: torch.Tensor | None) -> dict[str, torch.Tensor]: return {name: value.to(ctx.rng.device) for name, value in self.states.items()} @@ -75,15 +78,32 @@ class FillFromFile: path: str | Path - def __call__(self, ctx: TermContext, shared: bool) -> dict[str, torch.Tensor]: + def __call__(self, ctx: TermContext, groups: torch.Tensor | None) -> dict[str, torch.Tensor]: saved = torch.load(self.path, map_location=ctx.rng.device) - if saved["shared"] != shared or not shared and saved["num_worlds"] != ctx.num_worlds: - kind = "a shared bank" if saved["shared"] else f"banks of {saved['num_worlds']} worlds" - wanted = "a shared bank" if shared else f"banks of {ctx.num_worlds} worlds" - raise ValueError(f"{self.path} holds {kind}, but the event needs {wanted}.") + held = saved["groups"] + if (held is None) != (groups is None) or groups is not None and not torch.equal(held, groups): + raise ValueError(f"{self.path} holds {_describe(held)}, but the event needs {_describe(groups)}.") return saved["states"] +def _describe(groups: torch.Tensor | None) -> str: + if groups is None: + return "a shared bank" + num_groups = int(groups.max()) + 1 + if num_groups == len(groups): + return f"banks of {len(groups)} worlds" + return f"banks of {num_groups} groups over {len(groups)} worlds" + + +def prototype_groups(ctx: TermContext) -> torch.Tensor: + """Group the worlds by the prototype combination that the scene cloned into them, such as the object each world + spawned, as MDP1's lift bank does: worlds of a group share their bank and its success statistics.""" + from isaaclab.sim import SimulationContext + + layout = SimulationContext.instance().get_clone_plan().topology.world_prototype_layout + return torch.unique(torch.as_tensor(layout, device=ctx.rng.device), return_inverse=True)[1] + + class Candidates: """A candidates task bound to a scene, rolled to propose start states. @@ -128,8 +148,10 @@ class FillFromCandidates: oversample_factor: float = 2.0 max_rolls: int = 2000 - def __call__(self, ctx: TermContext, shared: bool) -> dict[str, torch.Tensor]: + def __call__(self, ctx: TermContext, groups: torch.Tensor | None) -> dict[str, torch.Tensor]: num_worlds, device = ctx.num_worlds, ctx.rng.device + group = groups if groups is not None else torch.zeros(num_worlds, dtype=torch.long, device=device) + num_groups = int(group.max()) + 1 candidates = Candidates(self.candidates, ctx.scene_data, str(device), seed=int(ctx.rng[0])) descriptor = candidates.transition.observations.get("descriptor") size = self.bank_size if descriptor is None else round(self.bank_size * self.oversample_factor) @@ -146,43 +168,40 @@ def __call__(self, ctx: TermContext, shared: bool) -> dict[str, torch.Tensor]: origins = ctx.inputs.get("env_origins") poses = {name for name in ctx.outputs if origins is not None and _warp_view(ctx, name).dtype == wp.transformf} - rows = (num_worlds, size) if not shared else (size,) - harvest = {name: value.new_zeros(*rows, *value.shape[1:]) for name, value in fields.items()} - filled = torch.zeros(num_worlds if not shared else 1, dtype=torch.long, device=device) + harvest = {name: value.new_zeros(num_groups, size, *value.shape[1:]) for name, value in fields.items()} + filled = torch.zeros(num_groups, dtype=torch.long, device=device) worlds = torch.arange(num_worlds, device=device) for _ in range(self.max_rolls): accepted = candidates.roll() values = {name: _minus_origin(value, origins) if name in poses else value for name, value in fields.items()} - if shared: - take = worlds[accepted][: size - int(filled)] - for name, value in values.items(): - harvest[name][int(filled) : int(filled) + len(take)] = value[take] - filled += len(take) - else: - take = accepted & (filled < size) - slot = filled.clamp(max=size - 1) - for name, value in values.items(): - harvest[name][worlds, slot] = torch.where(_rows(take, value), value, harvest[name][worlds, slot]) - filled += take + # Each group takes its accepted worlds in order, into its next free slots. + take = worlds[accepted] + order = torch.argsort(group[take], stable=True) + take = take[order] + members = group[take] + starts = torch.searchsorted(members, members) # index of the first accepted world of each one's group + slot = filled[members] + torch.arange(len(take), device=device) - starts + keep = slot < size + take, members, slot = take[keep], members[keep], slot[keep] + for name, value in values.items(): + harvest[name][members, slot] = value[take] + filled += torch.bincount(members, minlength=num_groups) if (filled == size).all(): break else: raise RuntimeError( f"The reset bank harvested fewer than {size} valid start states after {self.max_rolls} rolls of the" - f" candidates ({filled.min().item()} in the worst {'bank' if shared else 'world'})." + f" candidates ({filled.min().item()} in the worst bank)." ) if descriptor is not None: # Keep the most spread states, each descriptor axis rescaled to unit span so that all axes count. points = harvest.pop("descriptor") - points = points if not shared else points[None] span = (points.amax(dim=(0, 1)) - points.amin(dim=(0, 1))).clamp(min=1e-6) kept = farthest_points(points / span, self.bank_size) - if shared: - harvest = {name: value[kept[0]] for name, value in harvest.items()} - else: - harvest = {name: value[worlds[:, None], kept] for name, value in harvest.items()} - return harvest + banks = torch.arange(num_groups, device=device) + harvest = {name: value[banks[:, None], kept] for name, value in harvest.items()} + return harvest if groups is not None else {name: value[0] for name, value in harvest.items()} def farthest_points(points: torch.Tensor, count: int) -> torch.Tensor: @@ -202,8 +221,9 @@ def farthest_points(points: torch.Tensor, count: int) -> torch.Tensor: class ResetBank: """The start states of a reset event, the sampler that chooses among them, and the worlds' current choices. - Slots are numbered within a world's bank, or within the shared bank. Get it with :func:`reset_bank`. Reading - allocates and synchronizes; :meth:`replay` and the event's hooks do not, and replay inside the step's CUDA graph. + Slots are numbered within a group's bank, a world's for a bank per world, or within the shared bank. Get it with + :func:`reset_bank`. Reading allocates and synchronizes; :meth:`replay` and the event's hooks do not, and replay + inside the step's CUDA graph. """ def __init__( @@ -212,16 +232,22 @@ def __init__( outputs: Mapping[str, wp.array], sampler: ResetStateSamplerCfg, *, - shared: bool, + groups: torch.Tensor | None, origins: wp.array | None, nominal_probability: float, record: RecordStates | None, ) -> None: first = next(iter(outputs.values())) num_worlds, device = first.shape[0], first.device + shared = groups is None filled = next(iter(states.values())).shape[0 if shared else 1] recorded = 0 if record is None else record.slots self.num_worlds, self.shared, self.size = num_worlds, shared, filled + recorded + self.groups = groups # The group of each world, None for a shared bank + self.num_groups = 1 if shared else int(groups.max()) + 1 + self._group = torch.zeros(num_worlds, dtype=torch.long, device=wp.device_to_torch(device)) + if not shared: + self._group.copy_(groups) self._filled, self._record, self._nominal = filled, record, float(nominal_probability) # Recorded slots start as copies of the filled ones, so every slot can be drawn from the start. @@ -233,10 +259,13 @@ def __init__( value.reshape(-1, *value.shape[1 if shared else 2 :]).contiguous(), dtype=outputs[name].dtype ) self.buffer = ResetStateBuffer(rows) - num_groups = 1 if shared else num_worlds - groups = None if shared else wp.array(range(num_worlds), dtype=wp.int32, device=device) self.sampler = ResetStateSampler( - sampler, num_worlds, self.size * num_groups, device, group_ids=groups, num_groups=num_groups + sampler, + num_worlds, + self.size * self.num_groups, + device, + group_ids=None if shared else wp.from_torch(self._group.int()), + num_groups=self.num_groups, ) scores = [score for score in sampler.scores if isinstance(score, BetaSamplingScoreCfg)] self._prior = scores[0].target if scores else 0.0 @@ -259,28 +288,31 @@ def __init__( @property def states(self) -> dict[str, torch.Tensor]: - """Copies of the stored states, ``(num_worlds, size, ...)`` per output, or ``(size, ...)`` if shared. Poses - are relative to the environment origins when the use binds them.""" + """Copies of the stored states, ``(num_groups, size, ...)`` per output, ``(num_worlds, size, ...)`` for a bank + per world, or ``(size, ...)`` if shared. Poses are relative to the environment origins when the use binds + them.""" rows = {name: value.torch for name, value in self.buffer.states.items()} return ( rows if self.shared - else {name: value.view(self.num_worlds, self.size, *value.shape[1:]) for name, value in rows.items()} + else {name: value.view(self.num_groups, self.size, *value.shape[1:]) for name, value in rows.items()} ) @property def success_rate(self) -> torch.Tensor: - """Recent success rate of each slot, ``(num_worlds, size)``, or ``(size,)`` if shared.""" + """Recent success rate of each slot, ``(num_groups, size)``, or ``(size,)`` if shared.""" return self._per_slot(self.sampler.success_rate.torch) @property def episode_counts(self) -> torch.Tensor: - """Episodes that started from each slot since it was filled, ``(num_worlds, size)`` or ``(size,)``.""" + """Episodes that started from each slot since it was filled, ``(num_groups, size)`` or ``(size,)``.""" return self._per_slot(self.sampler.episode_counts.torch) @property def probabilities(self) -> torch.Tensor: - """Probability that the next draw picks each slot, ``(num_worlds, size)`` or ``(size,)``.""" + """Probability that the next draw picks each slot, ``(num_groups, size)`` or ``(size,)``. + + With groups, a slot's probability is that of a draw by a world of its group.""" return self._per_slot(self.sampler.probabilities.torch) @property @@ -288,7 +320,7 @@ def slots(self) -> torch.Tensor: """The slot each world's episode started from, ``(num_worlds,)``; -1 for a nominal start or before the first reset.""" indices = self.sampler.indices.torch.long() - slots = indices if self.shared else indices - torch.arange(self.num_worlds, device=indices.device) * self.size + slots = indices - self._group * self.size return torch.where(wp.to_torch(self._restored) & (indices >= 0), slots, -1) def replay(self, slots: torch.Tensor | None) -> None: @@ -304,8 +336,8 @@ def replay(self, slots: torch.Tensor | None) -> None: slots = slots.to(requests.device, torch.int32) if not self.shared: in_bank = (slots >= 0) & (slots < self.size) - rows = torch.arange(self.num_worlds, device=slots.device, dtype=torch.int32) * self.size + slots - slots = torch.where(in_bank, rows, torch.where(slots < 0, -1, self.size * self.num_worlds)) + rows = self._group.int() * self.size + slots + slots = torch.where(in_bank, rows, torch.where(slots < 0, -1, self.size * self.num_groups)) requests.copy_(slots) def discard_outcomes(self) -> None: @@ -314,7 +346,7 @@ def discard_outcomes(self) -> None: def save(self, path: str | Path) -> None: """Save the states, to fill a later run's bank with :class:`FillFromFile`.""" - torch.save({"states": self.states, "shared": self.shared, "num_worlds": self.num_worlds}, path) + torch.save({"states": self.states, "groups": self.groups}, path) def restore(self, mask: wp.array, rng: wp.array, succeeded: wp.array | None) -> None: """Credit the ended episodes, choose the next starts, and write the restored ones to the outputs.""" @@ -362,7 +394,7 @@ def record(self, rng: wp.array, terminated: wp.array, record_when: wp.array | No self.buffer.set_state(self._record_rows, self._record_values, mask=self._recording) def _per_slot(self, values: torch.Tensor) -> torch.Tensor: - return values.clone() if self.shared else values.view(self.num_worlds, self.size).clone() + return values.clone() if self.shared else values.view(self.num_groups, self.size).clone() def reset_bank(state: MDPState, use: str = "events.reset") -> ResetBank: @@ -376,41 +408,57 @@ def reset_bank(state: MDPState, use: str = "events.reset") -> ResetBank: def _init( ctx: TermContext, *, - fill: Callable[[TermContext, bool], dict[str, torch.Tensor]], + fill: Callable[[TermContext, torch.Tensor | None], dict[str, torch.Tensor]], sampler: ResetStateSamplerCfg | None = None, shared: bool = False, + groups: Callable[[TermContext], torch.Tensor] | None = None, nominal_probability: float = 0.0, record: RecordStates | None = None, ) -> None: """Fill the bank once, then build its sampler and bind the outputs it restores.""" outputs = {name: _warp_view(ctx, name) for name in ctx.outputs} has_poses = any(value.dtype == wp.transformf for value in outputs.values()) - if shared and "env_origins" not in ctx.inputs and has_poses: - raise ValueError("A shared bank of poses needs the env_origins input, so that poses transfer across worlds.") - if record is not None and (shared or "terminated" not in ctx.inputs or record.slots < 1): + if shared and groups is not None: + raise ValueError("A bank is either shared or per group of worlds, not both.") + if (shared or groups is not None) and "env_origins" not in ctx.inputs and has_poses: + raise ValueError( + "A shared or grouped bank of poses needs the env_origins input, so that poses transfer across worlds." + ) + if record is not None and (shared or groups is not None or "terminated" not in ctx.inputs or record.slots < 1): raise ValueError( "Recording needs a bank per world, at least one slot, and the terminated input (mdp2.terminated), so" " that states which end the episode are not recorded." ) if not 0.0 <= nominal_probability <= 1.0: raise ValueError(f"nominal_probability must be in [0, 1], got {nominal_probability}.") - states = fill(ctx, shared) + device = ctx.rng.device + if shared: + group = None + elif groups is not None: + # Number the groups 0, 1, ..., so that any labels work. + group = torch.unique(torch.as_tensor(groups(ctx), device=device), return_inverse=True)[1] + if group.shape != (ctx.num_worlds,): + raise ValueError(f"groups must give one group per world, got shape {tuple(group.shape)}.") + else: + group = torch.arange(ctx.num_worlds, device=device) + states = fill(ctx, group) if states.keys() != outputs.keys(): raise ValueError(f"The fill returned states for {sorted(states)}, but the event writes {sorted(outputs)}.") leading = 1 if shared else 2 + num_banks = 0 if shared else int(group.max()) + 1 if ( len({value.shape[leading - 1] for value in states.values()}) != 1 or not shared - and any(value.shape[0] != ctx.num_worlds for value in states.values()) + and any(value.shape[0] != num_banks for value in states.values()) ): - raise ValueError("Every output needs the same number of states, per world unless the bank is shared.") + raise ValueError("Every output needs the same number of states, per group of worlds unless the bank is shared.") origins = ctx.inputs.get("env_origins") bank = ResetBank( states, outputs, sampler if sampler is not None else ResetStateSamplerCfg(history_length=1, scores=[]), - shared=shared, + groups=group, origins=None if origins is None else wp.from_torch(origins.contiguous(), dtype=wp.vec3f), nominal_probability=nominal_probability, record=record, @@ -448,6 +496,9 @@ def _record(cache: dict, rng: Any, terminated: Any = None, record_when: Any = No or None to draw uniformly; - ``shared``: whether every world draws from one bank rather than its own. Share a bank only between worlds whose states fit each other: a state banked with one object spawned does not fit a world with another; +- ``groups``: a callable that returns the group of each world, such as :func:`prototype_groups`, for one bank per + group: the worlds of a group draw from its states and share their success statistics, as MDP1's lift bank does + per object. Without it, each world has its own bank; - ``nominal_probability``: the fraction of resets that keep what the earlier reset events wrote. Those episodes are not credited to any slot; - ``record``: :class:`RecordStates`, to bank states visited during training. @@ -543,9 +594,5 @@ def _minus_origin(pose: torch.Tensor, origins: torch.Tensor) -> torch.Tensor: return relative -def _rows(take: torch.Tensor, value: torch.Tensor) -> torch.Tensor: - return take.view(-1, *[1] * (value.ndim - 1)) - - def _as_warp(value: Any) -> wp.array: return wp.from_torch(value) if isinstance(value, torch.Tensor) else value diff --git a/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py b/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py index 0df152ced84e..625f339d1a0e 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py @@ -160,6 +160,35 @@ def test_shared_bank_restores_poses_relative_to_each_world_origin(): torch.testing.assert_close(scene.data("robot", "joint_pos").torch, states["joint_pos"][slot]) +def test_grouped_banks_fill_from_and_credit_the_worlds_of_each_group(): + """As MDP1's lift bank per object: the worlds of a group draw from one bank, filled from their candidates, and + share its success statistics.""" + scene = Scene(num_worlds=8) + sampler = ResetStateSamplerCfg(history_length=8, scores=[BetaSamplingScoreCfg(target=1.0)]) + task_mdp, state = build( + scene, + fill=mdp.FillFromCandidates(CANDIDATES, bank_size=4), + groups=lambda ctx: torch.arange(ctx.num_worlds) % 2, + sampler=sampler, + inputs={"succeeded": mdp2.quantities.success, "env_origins": scene_entity.env_origins}, + ) + bank = mdp.reset_bank(state) + banked = bank.states["joint_pos"][..., 0] + assert banked.shape == (2, 4) and len(banked.unique()) == 8 + + transition = task_mdp.transition() + for _ in range(4): + reset(task_mdp, state, [True] * 8) + mdp2.evaluate(task_mdp, state, transition) + group, slots = torch.arange(8, device=DEVICE) % 2, bank.slots + torch.testing.assert_close(joint_pos(scene), banked[group, slots]) + origins = scene.data("scene", "env_origins").torch + poses = scene.data("object", "root_link_pose_w").torch[:, :3] - origins + torch.testing.assert_close(poses, bank.states["object_pose_w"][group, slots, :3]) + # Each group's four worlds credit its bank: three ended episodes each. + assert bank.episode_counts.shape == (2, 4) and bank.episode_counts.sum(dim=1).tolist() == [12, 12] + + def test_outcomes_are_credited_to_the_state_each_episode_started_from(): scene = Scene(num_worlds=16) states = { diff --git a/source/isaaclab_tasks/changelog.d/mdp2-resets.changed.rst b/source/isaaclab_tasks/changelog.d/mdp2-resets.changed.rst index 127595f35aa6..f0d818fb71aa 100644 --- a/source/isaaclab_tasks/changelog.d/mdp2-resets.changed.rst +++ b/source/isaaclab_tasks/changelog.d/mdp2-resets.changed.rst @@ -1,2 +1,3 @@ * Changed ``Isaac-Lift-KukaAllegro-MDP2`` to reset through ``isaaclab_experimental.mdp2.mdp.reset_from_bank`` with the - MDP1 lift sampler settings, replacing its task-local reset bank. + MDP1 lift sampler settings and, as MDP1, a bank of 1024 states per object shared by the worlds that spawned it, + replacing its task-local reset bank. diff --git a/source/isaaclab_tasks/isaaclab_tasks/mdp2/lift_kuka_allegro/lift_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/mdp2/lift_kuka_allegro/lift_env_cfg.py index fa8f88b00876..81d0ed98e4eb 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/mdp2/lift_kuka_allegro/lift_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/mdp2/lift_kuka_allegro/lift_env_cfg.py @@ -453,14 +453,17 @@ class KukaAllegroLiftPhysicsCfg(PresetCfg): outputs={"gravity_w": scene.gravity_w}, params={"initial_gravity": (0.0, 0.0, 0.0), "final_gravity": (0.0, 0.0, -9.81)}, ), - # Restart from the valid start states that the policy solves about half the time. Each world banks its own - # states, so that they fit the object it spawned. + # Restart from the valid start states that the policy solves about half the time. As in MDP1, the worlds that + # spawned the same object share a bank of 1024 states, harvested twice over and thinned to the most spread, + # and share its success statistics. "reset": mdp2.Event( mdp.reset_from_bank, - inputs={"succeeded": mdp2.quantities.success}, + inputs={"succeeded": mdp2.quantities.success, "env_origins": scene.env_origins}, outputs={**robot_state, **object_state}, params={ - "fill": mdp.FillFromCandidates(CANDIDATES, bank_size=16), + # A world per object, as in small test runs, needs a roll per state. + "fill": mdp.FillFromCandidates(CANDIDATES, bank_size=1024, max_rolls=20000), + "groups": mdp.prototype_groups, "sampler": ResetStateSamplerCfg( history_length=10, scores=[BetaSamplingScoreCfg(target=0.5, kappa=1.0, weight=0.5)], @@ -489,4 +492,8 @@ def play_mode(self): super().play_mode() adr = self.task.events["adr"] params = {**adr.params, "init_difficulty": adr.params["max_difficulty"], "promotion_only": True} - self.task = replace(self.task, events={**self.task.events, "adr": replace(adr, params=params)}) + # As MDP1, a small bank taken as harvested: it only supplies starts to the few worlds that play. + bank = self.task.events["reset"] + fill = replace(bank.params["fill"], bank_size=32, oversample_factor=1.0) + events = {"adr": replace(adr, params=params), "reset": replace(bank, params={**bank.params, "fill": fill})} + self.task = replace(self.task, events={**self.task.events, **events}) diff --git a/source/isaaclab_tasks/test/mdp2/test_lift_kuka_allegro.py b/source/isaaclab_tasks/test/mdp2/test_lift_kuka_allegro.py index bf879021280c..77f33054456f 100644 --- a/source/isaaclab_tasks/test/mdp2/test_lift_kuka_allegro.py +++ b/source/isaaclab_tasks/test/mdp2/test_lift_kuka_allegro.py @@ -80,6 +80,7 @@ def bank_and_scene_state(env: MDP2RLEnv, state: mdp2.MDPState) -> dict[str, tupl """Return, per banked field, the banked state that each world plays and the field's value in the scene.""" bank = mdp2.mdp.reset_bank(state) banked = bank.buffer.get_state(bank.sampler.indices) + banked["object_pose_w"].torch[:, :3] += env.scene.env_origins # the bank stores poses relative to the origins robot, target = env.scene["robot"].data, env.scene["object"].data fields = { "joint_pos": robot.joint_pos, @@ -297,7 +298,8 @@ def test_recorded_states_restore_through_the_simulation(scenario: SimpleNamespac task.events["reset"] = dataclasses.replace( event, inputs={**event.inputs, "terminated": mdp2.terminated}, - params={**event.params, "record": mdp2.mdp.RecordStates(slots=1, probability=1.0)}, + # Recording needs a bank per world. + params={**event.params, "groups": None, "record": mdp2.mdp.RecordStates(slots=1, probability=1.0)}, ) builder = mdp2.MDPBuilder(env.scene_data.schema) builder.add_task(task) From 9da24481bb06b6aee6d6abf33b954cbe6dc59fe4 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Sun, 22 Nov 2026 13:15:16 -0800 Subject: [PATCH 10/17] Rename the MDP2 reset bank API to reset states reset_from_bank becomes reset_to_states, ResetBank and reset_bank become ResetStates and get_reset_states, the fill becomes a source (FromTask, FromFile, FromTensors), Candidates becomes StateGenerator, RecordStates becomes RecordVisited, replay becomes pin and unpin, and nominal resets become default resets. --- docs/source/how-to/reset_state_buffers.rst | 113 ++++---- scripts/tools/collect_reset_states.py | 55 ---- scripts/tools/generate_reset_states.py | 55 ++++ .../changelog.d/mdp2-resets.added.rst | 17 +- .../mdp2/mdp/__init__.pyi | 32 +-- .../mdp2/mdp/reset_states.py | 262 +++++++++--------- .../test/mdp2/test_mdp2_reset_states.py | 175 ++++++------ .../changelog.d/mdp2-resets.changed.rst | 6 +- .../mdp2/lift_kuka_allegro/lift_env_cfg.py | 27 +- .../test/mdp2/test_lift_kuka_allegro.py | 70 ++--- 10 files changed, 415 insertions(+), 397 deletions(-) delete mode 100644 scripts/tools/collect_reset_states.py create mode 100644 scripts/tools/generate_reset_states.py diff --git a/docs/source/how-to/reset_state_buffers.rst b/docs/source/how-to/reset_state_buffers.rst index abead237d82b..cadadf91bf1d 100644 --- a/docs/source/how-to/reset_state_buffers.rst +++ b/docs/source/how-to/reset_state_buffers.rst @@ -132,7 +132,7 @@ To replace stored states while running, such as states recorded during training, ``buffer.set_state(indices, values, mask=mask)``, the inverse of ``get_state``, and clear their outcomes with ``sampler.forget(indices, mask, success_rate=prior)``. A forgotten entry keeps ``prior`` as its success rate until its next outcome. Both can be captured. In ``sampler.reset(..., state_ids=ids)``, a -request of -1 draws from the scores for that environment, so a captured reset can replay some +request of -1 draws from the scores for that environment, so a captured reset can pin some environments and sample the others. Configure useful practice @@ -218,11 +218,11 @@ joints, and controller targets through public mask writers. Use the MDP2 reset event ------------------------ -MDP2 tasks use ``isaaclab_experimental.mdp2.mdp.reset_from_bank``. It composes the same three parts: -a fill builds a :class:`~isaaclab.envs.reset.ResetStateBuffer` once at startup, a -:class:`~isaaclab.envs.reset.ResetStateSampler` credits each ended episode and draws the next start -from the use's random stream, and the event gathers the drawn states into its ``outputs``, which -MDP2 commits. The outputs are the state: any writable scene fields. +MDP2 tasks use ``isaaclab_experimental.mdp2.mdp.reset_to_states``. It composes the same three parts: +a source builds a :class:`~isaaclab.envs.reset.ResetStateBuffer` of reset states once at startup, a +:class:`~isaaclab.envs.reset.ResetStateSampler` credits each ended episode and draws the next reset +state from the use's random stream, and the event gathers the drawn states into its ``outputs``, +which MDP2 commits. The outputs are the state: any writable scene fields. .. code-block:: python @@ -230,100 +230,103 @@ MDP2 commits. The outputs are the state: any writable scene fields. from isaaclab_experimental.mdp2 import mdp "reset": mdp2.Event( - mdp.reset_from_bank, + mdp.reset_to_states, inputs={"succeeded": mdp2.quantities.success}, outputs={"joint_pos": robot.joint_pos, "object_pose_w": target.root_link_pose_w}, params={ - "fill": mdp.FillFromCandidates(CANDIDATES, bank_size=16), + "source": mdp.FromTask(RESET_STATE_GENERATOR, num_states=16), "sampler": ResetStateSamplerCfg(scores=[BetaSamplingScoreCfg(target=0.5)]), }, ) -* ``fill`` returns the states. :class:`~isaaclab_experimental.mdp2.mdp.reset_states.FillFromCandidates` rolls the reset - events of a ``candidates`` task, keeps the states its terminations accept, and, given a ``descriptor`` - observation group, keeps the most spread of an oversampled harvest. - :class:`~isaaclab_experimental.mdp2.mdp.reset_states.FillFromStates` takes given states, such as demonstrations, - and :class:`~isaaclab_experimental.mdp2.mdp.reset_states.FillFromFile` loads a saved bank. +* ``source`` returns the states. :class:`~isaaclab_experimental.mdp2.mdp.reset_states.FromTask` rolls the + reset events of a generator task, keeps the states its terminations accept, and, given a + ``descriptor`` observation group, keeps the most spread of an oversampled harvest. + :class:`~isaaclab_experimental.mdp2.mdp.reset_states.FromTensors` takes given states, such as + demonstrations, and :class:`~isaaclab_experimental.mdp2.mdp.reset_states.FromFile` loads saved ones. * ``sampler`` weighs states by recent success; ``None`` draws uniformly. Binding ``succeeded`` credits each ended episode to the state it started from. -* ``shared`` selects one bank for every world instead of one bank per world. Bind - ``env_origins`` so poses are stored relative to each world's origin. Share a bank only between +* ``shared`` selects one set of states for every world instead of one set per world. Bind + ``env_origins`` so poses are stored relative to each world's origin. Share states only between worlds whose states fit each other, such as worlds that spawn the same object. -* ``groups`` selects one bank per group of worlds, given a callable that returns each world's group. - :func:`~isaaclab_experimental.mdp2.mdp.reset_states.prototype_groups` groups the worlds by the object, or other - prototype, that the scene cloned into them, as MDP1's lift bank does: the worlds of a group draw from one bank and - share its success statistics. Bind ``env_origins`` here too. -* ``nominal_probability`` is the fraction of resets that keep what the earlier reset events wrote, - fresh draws from the nominal distribution. Those episodes are not credited to any state. -* ``record`` banks states that the worlds visit during training, see below. +* ``groups`` selects one set of states per group of worlds, given a callable that returns each + world's group. :func:`~isaaclab_experimental.mdp2.mdp.reset_states.prototype_groups` groups the + worlds by the object, or other prototype, that the scene cloned into them, as MDP1's lift reset + does: the worlds of a group draw from one set and share its success statistics. Bind + ``env_origins`` here too. +* ``default_reset_probability`` is the fraction of resets that keep what the earlier reset events + wrote, the task's default reset. Those episodes are not credited to any state. +* ``record`` stores states that the worlds visit during training, see below. Place the event after the other reset events: it overwrites the outputs they wrote. An event whose outputs include a command runs after the commands resample, so that a restored goal stands. The init hook warms every kernel, so the event is captured with the rest of the step. -``Isaac-Lift-KukaAllegro-MDP2`` uses a bank of 1024 states per object, grouped with +``Isaac-Lift-KukaAllegro-MDP2`` uses 1024 reset states per object, grouped with :func:`~isaaclab_experimental.mdp2.mdp.reset_states.prototype_groups`, with the core Lift sampler settings. Record states along the horizon ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -States that the policy reaches on its way to success make useful starts. With ``record``, the -event's update hook runs once per step after the rewards and records each world's outputs into -its own bank: +States that the policy reaches on its way to success make useful reset states. With ``record``, +the event's update hook runs once per step after the rewards and records each world's outputs into +its own reset states: .. code-block:: python "reset": mdp2.Event( - mdp.reset_from_bank, + mdp.reset_to_states, inputs={ "succeeded": mdp2.quantities.success, "terminated": mdp2.terminated, # states that end the episode are not recorded - "record_when": mdp2.quantities.lifted, # optional: record only where above 0.5 + "record_if": mdp2.quantities.lifted, # optional: record only where above 0.5 }, outputs={**robot_state, **object_state}, params={ - "fill": mdp.FillFromCandidates(CANDIDATES, bank_size=16), + "source": mdp.FromTask(RESET_STATE_GENERATOR, num_states=16), "sampler": ResetStateSamplerCfg(scores=[BetaSamplingScoreCfg(target=0.5)]), - "record": mdp.RecordStates(slots=16, probability=0.01), + "record": mdp.RecordVisited(num_states=16, probability=0.01), }, ) Each step, a world that did not terminate records with ``probability`` into the oldest of its -``slots`` recorded slots, which start as copies of the filled states. A recorded slot forgets the -outcomes of the state it replaces and starts at the success rate the first score targets, so new -states are tried before their outcomes are known. An episode whose start is recorded over is not -credited. Include velocities, and commands for goal-conditioned tasks, in the outputs, so that a -restored state continues as it was recorded. Recording needs a bank per world. +``num_states`` recorded slots, which start as copies of the source's states. A recorded slot +forgets the outcomes of the state it replaces and starts at the success rate the first score +targets, so new states are tried before their outcomes are known. An episode whose reset state is +recorded over is not credited. Include velocities, and commands for goal-conditioned tasks, in the +outputs, so that a restored state continues as it was recorded. Recording needs reset states per +world. -Inspect, replay, and save the bank -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Inspect, pin, and save reset states +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -:func:`~isaaclab_experimental.mdp2.mdp.reset_states.reset_bank` returns the -:class:`~isaaclab_experimental.mdp2.mdp.reset_states.ResetBank` of a use. Slots are numbered within each -world's bank. +:func:`~isaaclab_experimental.mdp2.mdp.reset_states.get_reset_states` returns the +:class:`~isaaclab_experimental.mdp2.mdp.reset_states.ResetStates` of a use. Slots are numbered +within each world's reset states. .. code-block:: python - bank = mdp.reset_bank(env.state) # the "events.reset" use - bank.states["joint_pos"] # (num_worlds, size, num_joints) - bank.success_rate, bank.episode_counts, bank.probabilities # (num_worlds, size) - bank.slots # the slot each world's episode started from, -1 for a nominal start + reset_states = mdp.get_reset_states(env.state) # the "events.reset" use + reset_states.states["joint_pos"] # (num_worlds, size, num_joints) + reset_states.success_rate, reset_states.episode_counts, reset_states.probabilities # (num_worlds, size) + reset_states.started_from # the slot each world's episode started from, -1 for a default reset - bank.replay(torch.full((env.num_envs,), 3)) # restart every world from its slot 3 at its next reset - bank.replay(None) # draw again - bank.save("bank.pt") # fill a later run with mdp.FillFromFile("bank.pt") + reset_states.pin(torch.full((env.num_envs,), 3)) # reset every world to its slot 3 at its next reset + reset_states.unpin() # draw again + reset_states.save("reset_states.pt") # load in a later run with mdp.FromFile("reset_states.pt") -Replay requests hold until replaced and run inside the captured step, so they can sweep the -bank during evaluation. To collect states separately from training, for example a larger -candidates fill, run ``scripts/tools/collect_reset_states.py``, which builds the task and saves its -bank: +Pins hold until replaced and run inside the captured step, so they can sweep the reset states +during evaluation. Call ``reset_states.skip_current_episodes()`` before resetting worlds by hand +mid-episode, so those episodes are not credited. To generate states separately from training, for +example many more of them, run ``scripts/tools/generate_reset_states.py``, which builds the task and +saves its reset states: .. code-block:: bash - ./isaaclab.sh -p scripts/tools/collect_reset_states.py --task Isaac-Lift-KukaAllegro-MDP2 \ - --num_envs 4096 --bank_size 64 --out kuka_lift_bank.pt physics=newton_mjwarp + ./isaaclab.sh -p scripts/tools/generate_reset_states.py --task Isaac-Lift-KukaAllegro-MDP2 \ + --num_envs 4096 --num_states 64 --out kuka_lift_reset_states.pt physics=newton_mjwarp -A bank per world or per group fits only runs with the same number of worlds and object assignment; -a shared bank fits any. +Reset states per world or per group fit only runs with the same number of worlds and object +assignment; shared reset states fit any. Migrating existing reset configurations --------------------------------------- diff --git a/scripts/tools/collect_reset_states.py b/scripts/tools/collect_reset_states.py deleted file mode 100644 index e21a376a98e7..000000000000 --- a/scripts/tools/collect_reset_states.py +++ /dev/null @@ -1,55 +0,0 @@ -# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). -# All rights reserved. -# -# SPDX-License-Identifier: BSD-3-Clause - -"""Collect the start states of an MDP2 task into a file, to fill its reset bank in later runs. - -Building the task fills the bank of its ``reset_from_bank`` event from the event's fill, typically a candidates task. -The script saves that bank. Fill later runs from it with ``fill=mdp.FillFromFile(path)``, in the same number of worlds -unless the bank is shared. For example:: - - uv run python scripts/tools/collect_reset_states.py --task Isaac-Lift-KukaAllegro-MDP2 --num_envs 4096 \\ - --bank_size 64 --out kuka_lift_bank.pt physics=newton_mjwarp -""" - -import argparse -import dataclasses -import sys - -import gymnasium as gym -from isaaclab_experimental.mdp2 import mdp - -from isaaclab.app import add_launcher_args, launch_simulation - -import isaaclab_tasks # noqa: F401 -from isaaclab_tasks.utils import resolve_task_config, setup_preset_cli - -parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) -parser.add_argument("--task", required=True, help="Name of an MDP2 task.") -parser.add_argument("--num_envs", type=int, default=None, help="Number of worlds; default: the task's.") -parser.add_argument("--bank_size", type=int, default=None, help="States per bank, for a candidates fill.") -parser.add_argument("--event", default="reset", help="Name of the reset_from_bank event.") -parser.add_argument("--out", required=True, help="File to save the states to.") -add_launcher_args(parser) -parser.set_defaults(device=None) # let the task select the device -args_cli, hydra_args = setup_preset_cli(parser) -sys.argv = [sys.argv[0]] + hydra_args - -env_cfg, _ = resolve_task_config(args_cli.task, "") -if args_cli.num_envs is not None: - env_cfg.scene.num_envs = args_cli.num_envs -params = env_cfg.task.events[args_cli.event].params -if args_cli.bank_size is not None: - if not isinstance(params["fill"], mdp.FillFromCandidates): - raise SystemExit(f"--bank_size needs a candidates fill, but the event fills with {params['fill']!r}.") - params["fill"] = dataclasses.replace(params["fill"], bank_size=args_cli.bank_size) -params.pop("record", None) # only the filled states - -with launch_simulation(env_cfg, args_cli): - env = gym.make(args_cli.task, cfg=env_cfg) - bank = mdp.reset_bank(env.unwrapped.state, f"events.{args_cli.event}") - bank.save(args_cli.out) - worlds = "one shared bank" if bank.shared else f"{bank.num_worlds} worlds" - print(f"Saved {bank.size} states for {worlds} to {args_cli.out}.") - env.close() diff --git a/scripts/tools/generate_reset_states.py b/scripts/tools/generate_reset_states.py new file mode 100644 index 000000000000..745894cb8e54 --- /dev/null +++ b/scripts/tools/generate_reset_states.py @@ -0,0 +1,55 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Generate the reset states of an MDP2 task into a file, to load them in later runs. + +Building the task builds the reset states of its ``reset_to_states`` event from the event's source, typically +``mdp.FromTask`` with a generator task. The script saves them. Later runs load them with +``source=mdp.FromFile(path)``, in the same number of worlds unless the states are shared. For example:: + + uv run python scripts/tools/generate_reset_states.py --task Isaac-Lift-KukaAllegro-MDP2 --num_envs 4096 \\ + --num_states 64 --out kuka_lift_reset_states.pt physics=newton_mjwarp +""" + +import argparse +import dataclasses +import sys + +import gymnasium as gym +from isaaclab_experimental.mdp2 import mdp + +from isaaclab.app import add_launcher_args, launch_simulation + +import isaaclab_tasks # noqa: F401 +from isaaclab_tasks.utils import resolve_task_config, setup_preset_cli + +parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) +parser.add_argument("--task", required=True, help="Name of an MDP2 task.") +parser.add_argument("--num_envs", type=int, default=None, help="Number of worlds; default: the task's.") +parser.add_argument("--num_states", type=int, default=None, help="States per world, for a FromTask source.") +parser.add_argument("--event", default="reset", help="Name of the reset_to_states event.") +parser.add_argument("--out", required=True, help="File to save the states to.") +add_launcher_args(parser) +parser.set_defaults(device=None) # let the task select the device +args_cli, hydra_args = setup_preset_cli(parser) +sys.argv = [sys.argv[0]] + hydra_args + +env_cfg, _ = resolve_task_config(args_cli.task, "") +if args_cli.num_envs is not None: + env_cfg.scene.num_envs = args_cli.num_envs +params = env_cfg.task.events[args_cli.event].params +if args_cli.num_states is not None: + if not isinstance(params["source"], mdp.FromTask): + raise SystemExit(f"--num_states needs a FromTask source, but the event's source is {params['source']!r}.") + params["source"] = dataclasses.replace(params["source"], num_states=args_cli.num_states) +params.pop("record", None) # only the generated states + +with launch_simulation(env_cfg, args_cli): + env = gym.make(args_cli.task, cfg=env_cfg) + reset_states = mdp.get_reset_states(env.unwrapped.state, f"events.{args_cli.event}") + reset_states.save(args_cli.out) + worlds = "all worlds, shared" if reset_states.shared else f"each of {reset_states.num_worlds} worlds" + print(f"Saved {reset_states.size} states for {worlds} to {args_cli.out}.") + env.close() diff --git a/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst b/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst index 622871932085..85fcf333164b 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst @@ -1,12 +1,13 @@ -* Added ``isaaclab_experimental.mdp2.mdp.reset_from_bank``, an MDP2 reset event that restores start states from a - :class:`~isaaclab.envs.reset.ResetStateBuffer` drawn by a :class:`~isaaclab.envs.reset.ResetStateSampler`, with - ``FillFromCandidates`` and ``FillFromStates`` to fill the bank per world, per group of worlds (``groups``, such as - ``prototype_groups``, which groups worlds by the object they spawned), or shared across worlds, and ``Candidates``, - a candidates task bound to the scene that proposes start states one roll at a time. +* Added ``isaaclab_experimental.mdp2.mdp.reset_to_states``, an MDP2 reset event that resets worlds to reset states + stored in a :class:`~isaaclab.envs.reset.ResetStateBuffer` and drawn by a + :class:`~isaaclab.envs.reset.ResetStateSampler`, per world, per group of worlds (``groups``, such as + ``prototype_groups``, which groups worlds by the object they spawned), or shared across worlds. Its ``source`` is + ``FromTask``, which generates the states with a generator task, ``FromFile``, or ``FromTensors``; + ``StateGenerator`` binds a generator task to the scene and proposes reset states one roll at a time. * Added ``cache`` to :class:`~isaaclab_experimental.mdp2.TermContext`, so init hooks can build host objects that the use's Python hooks reuse. -* Added recording, replay, and saving to ``reset_from_bank``: ``RecordStates`` banks states that the worlds visit during - training, ``nominal_probability`` keeps a fraction of nominal resets, and ``reset_bank`` returns a ``ResetBank`` to - inspect, replay, save, or discard the outcomes of manual resets, and ``FillFromFile`` loads a saved bank. +* Added recording, pinning, and saving to ``reset_to_states``: ``RecordVisited`` stores states that the worlds visit + during training, ``default_reset_probability`` keeps a fraction of the default resets, and ``get_reset_states`` + returns a ``ResetStates`` to inspect, pin, save, or skip the outcomes of manual resets. * Added scheduling of reset events' ``update`` hooks once per step after the rewards, and ordering of reset events that write commands after the commands resample, so that a restored command stands. diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi index 9726034c5745..e176cba628fb 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi @@ -18,16 +18,16 @@ __all__ = [ "reset_joints_by_offset", "reset_joints_by_scale", "reset_root_state_uniform", - "Candidates", - "FillFromCandidates", - "FillFromFile", - "FillFromStates", - "RecordStates", - "ResetBank", + "StateGenerator", + "FromTask", + "FromFile", + "FromTensors", + "RecordVisited", + "ResetStates", "farthest_points", "prototype_groups", - "reset_bank", - "reset_from_bank", + "get_reset_states", + "reset_to_states", "base_ang_vel", "base_lin_vel", "generated_commands", @@ -83,16 +83,16 @@ from .events import ( reset_root_state_uniform, ) from .reset_states import ( - Candidates, - FillFromCandidates, - FillFromFile, - FillFromStates, - RecordStates, - ResetBank, + StateGenerator, + FromTask, + FromFile, + FromTensors, + RecordVisited, + ResetStates, farthest_points, prototype_groups, - reset_bank, - reset_from_bank, + get_reset_states, + reset_to_states, ) from .observations import ( base_ang_vel, diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py index 668367ae95ec..48bfd70bc030 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py @@ -3,22 +3,22 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Reset from a bank of start states: the MDP2 event over :mod:`isaaclab.envs.reset`. +"""Reset to stored reset states: the MDP2 event over :mod:`isaaclab.envs.reset`. -A :class:`ResetBank` composes three parts that are chosen independently: +A :class:`ResetStates` composes three parts that are chosen independently: -- the states, a :class:`~isaaclab.envs.reset.ResetStateBuffer` that a fill builds once at startup, and that recording - extends with states visited during training; +- the states, a :class:`~isaaclab.envs.reset.ResetStateBuffer` that a source builds once at startup, and that + recording extends with states visited during training; - the choice, a :class:`~isaaclab.envs.reset.ResetStateSampler` that credits each ended episode to the state it - started from and draws the next one from the use's random stream, unless a slot is requested for replay; + started from and draws the next one from the use's random stream, unless a slot is pinned; - the restore, which gathers the drawn states into the event's ``outputs``. The outputs are the state: any writable fields, such as ``robot.joint_pos`` and ``object.root_link_pose_w``, and -commands, whose restored value then stands over the resample. A fill is a callable ``fill(ctx, groups) -> {output: -tensor}`` that returns, per output, ``(num_groups, size, ...)`` states for a bank per group of worlds, given the -group of each world as ``groups``, ``(num_worlds,)``, or ``(size, ...)`` for one bank that every world shares, given -None. A bank per world is a group per world. :func:`reset_bank` returns the bank of a use, to inspect, replay, or -save it. +commands, whose restored value then stands over the resample. A source is a callable ``source(ctx, groups) -> +{output: tensor}`` that returns, per output, ``(num_groups, num_states, ...)`` states for each group of worlds, given +the group of each world as ``groups``, ``(num_worlds,)``, or ``(num_states, ...)`` for one set that every world shares, +given None. Reset states per world are a group per world. :func:`get_reset_states` returns the reset states of a use, +to inspect, pin, or save them. """ from __future__ import annotations @@ -44,26 +44,26 @@ @dataclass(frozen=True) -class RecordStates: - """Record states that the worlds visit during training into slots of their own bank. +class RecordVisited: + """Record states that the worlds visit during training as extra reset states of their own. Each step, a world that did not terminate records its outputs with ``probability``, and only where the - ``record_when`` input, if bound, is above 0.5. Records go to ``slots`` extra slots per world, the oldest replaced - first; they start as copies of the filled states. A replaced slot forgets its outcomes and starts at the success - rate that the sampler's first score targets, so that new states are tried. + ``record_if`` input, if bound, is above 0.5. Records go to ``num_states`` extra slots per world, the oldest + replaced first; they start as copies of the source's states. A replaced slot forgets its outcomes and starts at the + success rate that the sampler's first score targets, so that new states are tried. """ - slots: int + num_states: int probability: float @dataclass(frozen=True) -class FillFromStates: - """Fill the bank with given states, such as demonstrations. +class FromTensors: + """Reset states given as tensors, such as demonstrations. - ``states`` maps each output to ``(num_groups, size, ...)`` states, ``(num_worlds, size, ...)`` for a bank per - world, or ``(size, ...)`` for a shared bank, in the frame the event restores: poses relative to the environment - origins when the use binds ``env_origins``. + ``states`` maps each output to ``(num_groups, num_states, ...)`` states, ``(num_worlds, num_states, ...)`` for + states per world, or ``(num_states, ...)`` if shared, in the frame the event restores: poses relative to the + environment origins when the use binds ``env_origins``. """ states: Mapping[str, torch.Tensor] @@ -73,8 +73,8 @@ def __call__(self, ctx: TermContext, groups: torch.Tensor | None) -> dict[str, t @dataclass(frozen=True) -class FillFromFile: - """Fill the bank with states that :meth:`ResetBank.save` wrote, such as a separate collection run.""" +class FromFile: + """Reset states that :meth:`ResetStates.save` wrote, such as a separate generation run.""" path: str | Path @@ -88,24 +88,24 @@ def __call__(self, ctx: TermContext, groups: torch.Tensor | None) -> dict[str, t def _describe(groups: torch.Tensor | None) -> str: if groups is None: - return "a shared bank" + return "shared reset states" num_groups = int(groups.max()) + 1 if num_groups == len(groups): - return f"banks of {len(groups)} worlds" - return f"banks of {num_groups} groups over {len(groups)} worlds" + return f"reset states of {len(groups)} worlds" + return f"reset states of {num_groups} groups over {len(groups)} worlds" def prototype_groups(ctx: TermContext) -> torch.Tensor: """Group the worlds by the prototype combination that the scene cloned into them, such as the object each world - spawned, as MDP1's lift bank does: worlds of a group share their bank and its success statistics.""" + spawned, as MDP1's lift reset does: worlds of a group share their reset states and their success statistics.""" from isaaclab.sim import SimulationContext layout = SimulationContext.instance().get_clone_plan().topology.world_prototype_layout return torch.unique(torch.as_tensor(layout, device=ctx.rng.device), return_inverse=True)[1] -class Candidates: - """A candidates task bound to a scene, rolled to propose start states. +class StateGenerator: + """A reset state generator task bound to a scene, rolled to propose reset states. Each :meth:`roll` resets every world through the task's reset events, commits them to the scene, and evaluates its terminations, which reject states. The scene then holds the proposals. @@ -128,23 +128,23 @@ def roll(self) -> torch.Tensor: return ~self.transition.terminated.torch def field(self, selector: Any) -> torch.Tensor: - """Return the proposed values of a field of the MDP, such as a command that the candidates sample.""" + """Return the proposed values of a field of the MDP, such as a command that the generator samples.""" if selector not in self.state.arrays: - raise ValueError(f"The candidates task must define '{selector}', which the event restores.") + raise ValueError(f"The generator task must define '{selector}', which the event restores.") return self.state.arrays[selector].torch @dataclass(frozen=True) -class FillFromCandidates: - """Fill the bank by rejection sampling the reset events of a ``candidates`` task. +class FromTask: + """Generate reset states by rejection sampling the reset events of a generator ``task``. - The candidates' reset events draw a state in every world, and the states that none of its terminations reject are + The task's reset events draw a state in every world, and the states that none of its terminations reject are kept. If the task has a ``descriptor`` observation group, ``oversample_factor`` times as many states are harvested and the ones most spread over the descriptor are kept. """ - candidates: TaskCfg - bank_size: int + task: TaskCfg + num_states: int oversample_factor: float = 2.0 max_rolls: int = 2000 @@ -152,14 +152,14 @@ def __call__(self, ctx: TermContext, groups: torch.Tensor | None) -> dict[str, t num_worlds, device = ctx.num_worlds, ctx.rng.device group = groups if groups is not None else torch.zeros(num_worlds, dtype=torch.long, device=device) num_groups = int(group.max()) + 1 - candidates = Candidates(self.candidates, ctx.scene_data, str(device), seed=int(ctx.rng[0])) - descriptor = candidates.transition.observations.get("descriptor") - size = self.bank_size if descriptor is None else round(self.bank_size * self.oversample_factor) - if self.bank_size < 1 or size < self.bank_size: - raise ValueError("The bank must harvest at least as many states as it keeps, and keep at least one.") - # Scene outputs are read from the scene the candidates write; commands from the candidates' own state. + generator = StateGenerator(self.task, ctx.scene_data, str(device), seed=int(ctx.rng[0])) + descriptor = generator.transition.observations.get("descriptor") + size = self.num_states if descriptor is None else round(self.num_states * self.oversample_factor) + if self.num_states < 1 or size < self.num_states: + raise ValueError("FromTask must harvest at least as many states as it keeps, and keep at least one.") + # Scene outputs are read from the scene the generator writes; commands from the generator's own state. fields = { - name: value if ctx.selectors[name].scene else candidates.field(ctx.selectors[name]) + name: value if ctx.selectors[name].scene else generator.field(ctx.selectors[name]) for name, value in ctx.outputs.items() } if descriptor is not None: @@ -172,7 +172,7 @@ def __call__(self, ctx: TermContext, groups: torch.Tensor | None) -> dict[str, t filled = torch.zeros(num_groups, dtype=torch.long, device=device) worlds = torch.arange(num_worlds, device=device) for _ in range(self.max_rolls): - accepted = candidates.roll() + accepted = generator.roll() values = {name: _minus_origin(value, origins) if name in poses else value for name, value in fields.items()} # Each group takes its accepted worlds in order, into its next free slots. take = worlds[accepted] @@ -190,17 +190,17 @@ def __call__(self, ctx: TermContext, groups: torch.Tensor | None) -> dict[str, t break else: raise RuntimeError( - f"The reset bank harvested fewer than {size} valid start states after {self.max_rolls} rolls of the" - f" candidates ({filled.min().item()} in the worst bank)." + f"FromTask harvested fewer than {size} valid reset states after {self.max_rolls} rolls of the" + f" generator ({filled.min().item()} in the worst group)." ) if descriptor is not None: # Keep the most spread states, each descriptor axis rescaled to unit span so that all axes count. points = harvest.pop("descriptor") span = (points.amax(dim=(0, 1)) - points.amin(dim=(0, 1))).clamp(min=1e-6) - kept = farthest_points(points / span, self.bank_size) - banks = torch.arange(num_groups, device=device) - harvest = {name: value[banks[:, None], kept] for name, value in harvest.items()} + kept = farthest_points(points / span, self.num_states) + rows = torch.arange(num_groups, device=device) + harvest = {name: value[rows[:, None], kept] for name, value in harvest.items()} return harvest if groups is not None else {name: value[0] for name, value in harvest.items()} @@ -218,12 +218,12 @@ def farthest_points(points: torch.Tensor, count: int) -> torch.Tensor: return chosen -class ResetBank: - """The start states of a reset event, the sampler that chooses among them, and the worlds' current choices. +class ResetStates: + """The reset states of a reset event, the sampler that chooses among them, and the worlds' current choices. - Slots are numbered within a group's bank, a world's for a bank per world, or within the shared bank. Get it with - :func:`reset_bank`. Reading allocates and synchronizes; :meth:`replay` and the event's hooks do not, and replay - inside the step's CUDA graph. + Slots are numbered within a group's reset states, a world's for states per world, or within the shared ones. Get + it with :func:`get_reset_states`. Reading allocates and synchronizes; :meth:`pin` and the event's hooks do not, and + pinned slots restore inside the step's CUDA graph. """ def __init__( @@ -234,23 +234,23 @@ def __init__( *, groups: torch.Tensor | None, origins: wp.array | None, - nominal_probability: float, - record: RecordStates | None, + default_reset_probability: float, + record: RecordVisited | None, ) -> None: first = next(iter(outputs.values())) num_worlds, device = first.shape[0], first.device shared = groups is None filled = next(iter(states.values())).shape[0 if shared else 1] - recorded = 0 if record is None else record.slots + recorded = 0 if record is None else record.num_states self.num_worlds, self.shared, self.size = num_worlds, shared, filled + recorded - self.groups = groups # The group of each world, None for a shared bank + self.groups = groups # The group of each world, None if shared self.num_groups = 1 if shared else int(groups.max()) + 1 self._group = torch.zeros(num_worlds, dtype=torch.long, device=wp.device_to_torch(device)) if not shared: self._group.copy_(groups) - self._filled, self._record, self._nominal = filled, record, float(nominal_probability) + self._filled, self._record, self._default = filled, record, float(default_reset_probability) - # Recorded slots start as copies of the filled ones, so every slot can be drawn from the start. + # Recorded slots start as copies of the source's states, so every slot can be drawn from the start. cycle = torch.arange(self.size, device=states[next(iter(states))].device) % filled rows = {} for name, value in states.items(): @@ -288,7 +288,7 @@ def __init__( @property def states(self) -> dict[str, torch.Tensor]: - """Copies of the stored states, ``(num_groups, size, ...)`` per output, ``(num_worlds, size, ...)`` for a bank + """Copies of the stored states, ``(num_groups, size, ...)`` per output, ``(num_worlds, size, ...)`` for states per world, or ``(size, ...)`` if shared. Poses are relative to the environment origins when the use binds them.""" rows = {name: value.torch for name, value in self.buffer.states.items()} @@ -305,7 +305,7 @@ def success_rate(self) -> torch.Tensor: @property def episode_counts(self) -> torch.Tensor: - """Episodes that started from each slot since it was filled, ``(num_groups, size)`` or ``(size,)``.""" + """Episodes that started from each slot since it was stored, ``(num_groups, size)`` or ``(size,)``.""" return self._per_slot(self.sampler.episode_counts.torch) @property @@ -316,36 +316,37 @@ def probabilities(self) -> torch.Tensor: return self._per_slot(self.sampler.probabilities.torch) @property - def slots(self) -> torch.Tensor: - """The slot each world's episode started from, ``(num_worlds,)``; -1 for a nominal start or before the first + def started_from(self) -> torch.Tensor: + """The slot each world's episode started from, ``(num_worlds,)``; -1 for a default reset or before the first reset.""" indices = self.sampler.indices.torch.long() slots = indices - self._group * self.size return torch.where(wp.to_torch(self._restored) & (indices >= 0), slots, -1) - def replay(self, slots: torch.Tensor | None) -> None: - """Restart the worlds from the given slots at their next resets, ``(num_worlds,)``, -1 to draw as usual. + def pin(self, slots: torch.Tensor) -> None: + """Reset the worlds to the given slots at their next resets, ``(num_worlds,)``, -1 to draw as usual. - The requests hold until replaced; None clears them. A slot outside the bank leaves the world's start unchanged - and sets the sampler's ``invalid_requests``. Replayed episodes are credited like drawn ones. + The pins hold until replaced or :meth:`unpin`. A slot out of range leaves the world's reset unchanged and sets + the sampler's ``invalid_requests``. Pinned episodes are credited like drawn ones. """ requests = wp.to_torch(self._requests) - if slots is None: - requests.fill_(-1) - return slots = slots.to(requests.device, torch.int32) if not self.shared: - in_bank = (slots >= 0) & (slots < self.size) + in_range = (slots >= 0) & (slots < self.size) rows = self._group.int() * self.size + slots - slots = torch.where(in_bank, rows, torch.where(slots < 0, -1, self.size * self.num_groups)) + slots = torch.where(in_range, rows, torch.where(slots < 0, -1, self.size * self.num_groups)) requests.copy_(slots) - def discard_outcomes(self) -> None: + def unpin(self) -> None: + """Draw every world's reset states as usual again.""" + wp.to_torch(self._requests).fill_(-1) + + def skip_current_episodes(self) -> None: """Credit none of the worlds' current episodes, such as before resetting them by hand mid-episode.""" self._credit.zero_() def save(self, path: str | Path) -> None: - """Save the states, to fill a later run's bank with :class:`FillFromFile`.""" + """Save the states, for a later run to load with :class:`FromFile`.""" torch.save({"states": self.states, "groups": self.groups}, path) def restore(self, mask: wp.array, rng: wp.array, succeeded: wp.array | None) -> None: @@ -353,7 +354,7 @@ def restore(self, mask: wp.array, rng: wp.array, succeeded: wp.array | None) -> wp.launch( _choose_starts, mask.shape, - [mask, rng, self._requests, self._nominal, self._credit, self._valid, self._restored, self._writes], + [mask, rng, self._requests, self._default, self._credit, self._valid, self._restored, self._writes], device=mask.device, ) self.sampler.reset(mask, success=succeeded, valid=self._valid, state_ids=self._requests, rng=rng) @@ -361,7 +362,7 @@ def restore(self, mask: wp.array, rng: wp.array, succeeded: wp.array | None) -> for pose in self._poses: wp.launch(_shift_poses, mask.shape, [self._writes, self._origins, pose, pose, 1.0], device=mask.device) - def record(self, rng: wp.array, terminated: wp.array, record_when: wp.array | None) -> None: + def record(self, rng: wp.array, terminated: wp.array, record_if: wp.array | None) -> None: """Record the states of the worlds selected this step into their oldest recorded slots.""" wp.launch( _choose_records, @@ -369,10 +370,10 @@ def record(self, rng: wp.array, terminated: wp.array, record_when: wp.array | No [ rng, terminated, - record_when, + record_if, self._record.probability, self._filled, - self._record.slots, + self._record.num_states, self.size, self.sampler.indices.warp, self._cursor, @@ -397,40 +398,41 @@ def _per_slot(self, values: torch.Tensor) -> torch.Tensor: return values.clone() if self.shared else values.view(self.num_groups, self.size).clone() -def reset_bank(state: MDPState, use: str = "events.reset") -> ResetBank: - """Return the bank of a :data:`reset_from_bank` use, by its name in the schedule.""" +def get_reset_states(state: MDPState, use: str = "events.reset") -> ResetStates: + """Return the reset states of a :data:`reset_to_states` use, by its name in the schedule.""" cache = state.caches.get(use, {}) - if "bank" not in cache: - raise KeyError(f"'{use}' is not a reset_from_bank use. Uses with a cache: {sorted(state.caches)}.") - return cache["bank"] + if "reset_states" not in cache: + raise KeyError(f"'{use}' is not a reset_to_states use. Uses with a cache: {sorted(state.caches)}.") + return cache["reset_states"] def _init( ctx: TermContext, *, - fill: Callable[[TermContext, torch.Tensor | None], dict[str, torch.Tensor]], + source: Callable[[TermContext, torch.Tensor | None], dict[str, torch.Tensor]], sampler: ResetStateSamplerCfg | None = None, shared: bool = False, groups: Callable[[TermContext], torch.Tensor] | None = None, - nominal_probability: float = 0.0, - record: RecordStates | None = None, + default_reset_probability: float = 0.0, + record: RecordVisited | None = None, ) -> None: - """Fill the bank once, then build its sampler and bind the outputs it restores.""" + """Build the reset states once from the source, then the sampler and bind the outputs it restores.""" outputs = {name: _warp_view(ctx, name) for name in ctx.outputs} has_poses = any(value.dtype == wp.transformf for value in outputs.values()) if shared and groups is not None: - raise ValueError("A bank is either shared or per group of worlds, not both.") + raise ValueError("Reset states are either shared or per group of worlds, not both.") if (shared or groups is not None) and "env_origins" not in ctx.inputs and has_poses: raise ValueError( - "A shared or grouped bank of poses needs the env_origins input, so that poses transfer across worlds." + "Shared or grouped reset states with poses need the env_origins input, so that poses transfer across" + " worlds." ) - if record is not None and (shared or groups is not None or "terminated" not in ctx.inputs or record.slots < 1): + if record is not None and (shared or groups is not None or "terminated" not in ctx.inputs or record.num_states < 1): raise ValueError( - "Recording needs a bank per world, at least one slot, and the terminated input (mdp2.terminated), so" + "Recording needs reset states per world, at least one slot, and the terminated input (mdp2.terminated), so" " that states which end the episode are not recorded." ) - if not 0.0 <= nominal_probability <= 1.0: - raise ValueError(f"nominal_probability must be in [0, 1], got {nominal_probability}.") + if not 0.0 <= default_reset_probability <= 1.0: + raise ValueError(f"default_reset_probability must be in [0, 1], got {default_reset_probability}.") device = ctx.rng.device if shared: group = None @@ -441,74 +443,74 @@ def _init( raise ValueError(f"groups must give one group per world, got shape {tuple(group.shape)}.") else: group = torch.arange(ctx.num_worlds, device=device) - states = fill(ctx, group) + states = source(ctx, group) if states.keys() != outputs.keys(): - raise ValueError(f"The fill returned states for {sorted(states)}, but the event writes {sorted(outputs)}.") + raise ValueError(f"The source returned states for {sorted(states)}, but the event writes {sorted(outputs)}.") leading = 1 if shared else 2 - num_banks = 0 if shared else int(group.max()) + 1 + num_groups = 0 if shared else int(group.max()) + 1 if ( len({value.shape[leading - 1] for value in states.values()}) != 1 or not shared - and any(value.shape[0] != num_banks for value in states.values()) + and any(value.shape[0] != num_groups for value in states.values()) ): - raise ValueError("Every output needs the same number of states, per group of worlds unless the bank is shared.") + raise ValueError("Every output needs the same number of states, per group of worlds unless they are shared.") origins = ctx.inputs.get("env_origins") - bank = ResetBank( + reset_states = ResetStates( states, outputs, sampler if sampler is not None else ResetStateSamplerCfg(history_length=1, scores=[]), groups=group, origins=None if origins is None else wp.from_torch(origins.contiguous(), dtype=wp.vec3f), - nominal_probability=nominal_probability, + default_reset_probability=default_reset_probability, record=record, ) - ctx.cache["bank"] = bank + ctx.cache["reset_states"] = reset_states # Load every kernel and the sampler's sort and scan scratch before a graph captures the hooks: a step and a reset # of no worlds. - nothing = wp.zeros(ctx.num_worlds, dtype=wp.bool, device=bank.sampler.device) + nothing = wp.zeros(ctx.num_worlds, dtype=wp.bool, device=reset_states.sampler.device) rng, succeeded = _as_warp(ctx.rng), ctx.inputs.get("succeeded") - bank.restore(nothing, rng, None if succeeded is None else _as_warp(succeeded)) + reset_states.restore(nothing, rng, None if succeeded is None else _as_warp(succeeded)) if record is not None: - when = ctx.inputs.get("record_when") - bank.record(rng, wp.ones_like(nothing), None if when is None else _as_warp(when)) + when = ctx.inputs.get("record_if") + reset_states.record(rng, wp.ones_like(nothing), None if when is None else _as_warp(when)) def _restore(mask: Any, cache: dict, rng: Any, succeeded: Any = None, **_: Any) -> None: - cache["bank"].restore(_as_warp(mask), _as_warp(rng), None if succeeded is None else _as_warp(succeeded)) + cache["reset_states"].restore(_as_warp(mask), _as_warp(rng), None if succeeded is None else _as_warp(succeeded)) -def _record(cache: dict, rng: Any, terminated: Any = None, record_when: Any = None, **_: Any) -> None: - bank: ResetBank = cache["bank"] - if bank._record is not None: - bank.record(_as_warp(rng), _as_warp(terminated), None if record_when is None else _as_warp(record_when)) +def _record(cache: dict, rng: Any, terminated: Any = None, record_if: Any = None, **_: Any) -> None: + reset_states: ResetStates = cache["reset_states"] + if reset_states._record is not None: + reset_states.record(_as_warp(rng), _as_warp(terminated), None if record_if is None else _as_warp(record_if)) _hooks = Implementation(compute=_restore, update=_record) -reset_from_bank = Term(torch=_hooks, warp=_hooks, random=True, init=_init) -"""Restart the reset worlds from start states drawn from a bank, the MDP2 counterpart of MDP1's lift +reset_to_states = Term(torch=_hooks, warp=_hooks, random=True, init=_init) +"""Reset the worlds to reset states drawn from a stored set, the MDP2 counterpart of MDP1's lift ``conditional_reset``. Params: -- ``fill``: a callable that returns the states, such as :class:`FillFromCandidates` or :class:`FillFromFile`; +- ``source``: a callable that returns the states, such as :class:`FromTask` or :class:`FromFile`; - ``sampler``: a :class:`~isaaclab.envs.reset.ResetStateSamplerCfg` that weighs the states by their recent success, or None to draw uniformly; -- ``shared``: whether every world draws from one bank rather than its own. Share a bank only between worlds whose - states fit each other: a state banked with one object spawned does not fit a world with another; -- ``groups``: a callable that returns the group of each world, such as :func:`prototype_groups`, for one bank per - group: the worlds of a group draw from its states and share their success statistics, as MDP1's lift bank does - per object. Without it, each world has its own bank; -- ``nominal_probability``: the fraction of resets that keep what the earlier reset events wrote. Those episodes are - not credited to any slot; -- ``record``: :class:`RecordStates`, to bank states visited during training. +- ``shared``: whether every world draws from one set of states rather than its own. Share states only between worlds + whose states fit each other: a state stored with one object spawned does not fit a world with another; +- ``groups``: a callable that returns the group of each world, such as :func:`prototype_groups`, for one set of + states per group: the worlds of a group draw from its states and share their success statistics, as MDP1's lift + reset does per object. Without it, each world has its own states; +- ``default_reset_probability``: the fraction of resets that keep what the earlier reset events wrote. Those episodes + are not credited to any slot; +- ``record``: :class:`RecordVisited`, to store states visited during training. Inputs: ``succeeded``, the ended episode's success, credited to the slot it started from when bound; ``env_origins``, which stores the poses relative to the environment origins; ``terminated`` (``mdp2.terminated``), -required to record; and ``record_when``, a quantity above 0.5 where a state may be recorded. +required to record; and ``record_if``, a quantity above 0.5 where a state may be recorded. -Place it after the other reset events: it overwrites the outputs they wrote. The bank and the sampler's history persist -across episodes; :func:`reset_bank` returns them. +Place it after the other reset events: it overwrites the outputs they wrote. The states and the sampler's history +persist across episodes; :func:`get_reset_states` returns them. """ @@ -517,7 +519,7 @@ def _choose_starts( mask: wp.array(dtype=wp.bool), rng: wp.array(dtype=wp.int32), requests: wp.array(dtype=wp.int32), - nominal_probability: float, + default_reset_probability: float, credit: wp.array(dtype=wp.bool), valid: wp.array(dtype=wp.bool), restored: wp.array(dtype=wp.bool), @@ -529,7 +531,7 @@ def _choose_starts( return # The ended episode counts if it started from a slot that was not recorded over since. valid[world] = credit[world] - restore = requests[world] >= 0 or wp.randf(wp.rand_init(rng[world], 1)) >= nominal_probability + restore = requests[world] >= 0 or wp.randf(wp.rand_init(rng[world], 1)) >= default_reset_probability restored[world] = restore writes[world] = restore credit[world] = restore @@ -539,7 +541,7 @@ def _choose_starts( def _choose_records( rng: wp.array(dtype=wp.int32), terminated: wp.array(dtype=wp.bool), - record_when: wp.array(dtype=wp.float32), + record_if: wp.array(dtype=wp.float32), probability: float, first: int, slots: int, @@ -552,8 +554,8 @@ def _choose_records( ): world = wp.tid() record = not terminated[world] and wp.randf(wp.rand_init(rng[world], 2)) < probability - if record_when: - record = record and record_when[world] > 0.5 + if record_if: + record = record and record_if[world] > 0.5 recording[world] = record if not record: return diff --git a/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py b/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py index 625f339d1a0e..f7b32250afc4 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py @@ -3,7 +3,7 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Tests for resetting MDP2 tasks from a bank of start states, on an analytic scene.""" +"""Tests for resetting MDP2 tasks to stored reset states, on an analytic scene.""" from collections.abc import Collection @@ -91,18 +91,18 @@ def _positive(world: int, joint_pos: wp.array2d(dtype=float)) -> float: positive = mdp2.Term(torch=lambda joint_pos: (joint_pos[:, 0] > 0.0).float(), warp=_positive) -CANDIDATES = mdp2.TaskCfg( +RESET_STATE_GENERATOR = mdp2.TaskCfg( events={"draw": mdp2.Event(draw, outputs=outputs)}, terminations={"outside": mdp2.Termination(outside, inputs={"joint_pos": robot.joint_pos})}, ) def build(scene: Scene, backend: str = "warp", **params) -> tuple[mdp2.MDP, mdp2.MDPState]: - """Build a task whose only reset event restores from a bank, credited by whether the joint ended positive.""" + """Build a task whose only reset event resets to stored states, credited by whether the joint ended positive.""" inputs = params.pop("inputs", {"succeeded": mdp2.quantities.success}) task = mdp2.TaskCfg( quantities={"success": mdp2.Quantity(positive, inputs={"joint_pos": robot.joint_pos})}, - events={"reset": mdp2.Event(mdp.reset_from_bank, inputs=inputs, outputs=outputs, params=params)}, + events={"reset": mdp2.Event(mdp.reset_to_states, inputs=inputs, outputs=outputs, params=params)}, ) builder = mdp2.MDPBuilder(scene.schema) builder.add_task(task) @@ -123,17 +123,17 @@ def joint_pos(scene: Scene) -> torch.Tensor: RECORDING = {"succeeded": mdp2.quantities.success, "terminated": mdp2.terminated} -def test_candidates_fill_each_world_with_valid_states_and_restore_only_reset_worlds(): +def test_generator_gives_each_world_valid_states_and_restore_only_reset_worlds(): scene = Scene(num_worlds=8) - task_mdp, state = build(scene, fill=mdp.FillFromCandidates(CANDIDATES, bank_size=4)) - bank = mdp.reset_bank(state) + task_mdp, state = build(scene, source=mdp.FromTask(RESET_STATE_GENERATOR, num_states=4)) + reset_states = mdp.get_reset_states(state) - banked = bank.states["joint_pos"][..., 0].cpu() - assert banked.shape == (8, 4) and (banked.abs() <= 0.5).all() and len(banked.unique()) == 32 + stored = reset_states.states["joint_pos"][..., 0].cpu() + assert stored.shape == (8, 4) and (stored.abs() <= 0.5).all() and len(stored.unique()) == 32 reset(task_mdp, state, [True] * 8) - slots = bank.slots.cpu() - assert torch.equal(joint_pos(scene).cpu(), banked[torch.arange(8), slots]) # each world draws its own bank + slots = reset_states.started_from.cpu() + assert torch.equal(joint_pos(scene).cpu(), stored[torch.arange(8), slots]) # each world draws its own reset_states joint_pos(scene).add_(1.0) # the worlds move on, as a step would move them before = joint_pos(scene).clone() @@ -142,51 +142,51 @@ def test_candidates_fill_each_world_with_valid_states_and_restore_only_reset_wor assert torch.equal(joint_pos(scene)[1:], before[1:]) -def test_shared_bank_restores_poses_relative_to_each_world_origin(): +def test_shared_states_restore_poses_relative_to_each_world_origin(): scene = Scene(num_worlds=4) poses = torch.tensor([[0.1, 0.2, 0.3, 0, 0, 0, 1], [-0.1, 0.0, 0.5, 0, 0, 0, 1]], device=DEVICE) states = {"joint_pos": torch.tensor([[0.25], [-0.25]], device=DEVICE), "object_pose_w": poses} task_mdp, state = build( scene, - fill=mdp.FillFromStates(states), + source=mdp.FromTensors(states), shared=True, inputs={"succeeded": mdp2.quantities.success, "env_origins": scene_entity.env_origins}, ) reset(task_mdp, state, [True] * 4) - slot = mdp.reset_bank(state).slots + slot = mdp.get_reset_states(state).started_from origins = scene.data("scene", "env_origins").torch torch.testing.assert_close(scene.data("object", "root_link_pose_w").torch[:, :3], poses[slot, :3] + origins) torch.testing.assert_close(scene.data("robot", "joint_pos").torch, states["joint_pos"][slot]) -def test_grouped_banks_fill_from_and_credit_the_worlds_of_each_group(): - """As MDP1's lift bank per object: the worlds of a group draw from one bank, filled from their candidates, and - share its success statistics.""" +def test_grouped_states_come_from_and_credit_the_worlds_of_each_group(): + """As MDP1's lift reset per object: the worlds of a group draw from one set of states, generated in their worlds, + and share its success statistics.""" scene = Scene(num_worlds=8) sampler = ResetStateSamplerCfg(history_length=8, scores=[BetaSamplingScoreCfg(target=1.0)]) task_mdp, state = build( scene, - fill=mdp.FillFromCandidates(CANDIDATES, bank_size=4), + source=mdp.FromTask(RESET_STATE_GENERATOR, num_states=4), groups=lambda ctx: torch.arange(ctx.num_worlds) % 2, sampler=sampler, inputs={"succeeded": mdp2.quantities.success, "env_origins": scene_entity.env_origins}, ) - bank = mdp.reset_bank(state) - banked = bank.states["joint_pos"][..., 0] - assert banked.shape == (2, 4) and len(banked.unique()) == 8 + reset_states = mdp.get_reset_states(state) + stored = reset_states.states["joint_pos"][..., 0] + assert stored.shape == (2, 4) and len(stored.unique()) == 8 transition = task_mdp.transition() for _ in range(4): reset(task_mdp, state, [True] * 8) mdp2.evaluate(task_mdp, state, transition) - group, slots = torch.arange(8, device=DEVICE) % 2, bank.slots - torch.testing.assert_close(joint_pos(scene), banked[group, slots]) + group, slots = torch.arange(8, device=DEVICE) % 2, reset_states.started_from + torch.testing.assert_close(joint_pos(scene), stored[group, slots]) origins = scene.data("scene", "env_origins").torch poses = scene.data("object", "root_link_pose_w").torch[:, :3] - origins - torch.testing.assert_close(poses, bank.states["object_pose_w"][group, slots, :3]) - # Each group's four worlds credit its bank: three ended episodes each. - assert bank.episode_counts.shape == (2, 4) and bank.episode_counts.sum(dim=1).tolist() == [12, 12] + torch.testing.assert_close(poses, reset_states.states["object_pose_w"][group, slots, :3]) + # Each group's four worlds credit its reset_states: three ended episodes each. + assert reset_states.episode_counts.shape == (2, 4) and reset_states.episode_counts.sum(dim=1).tolist() == [12, 12] def test_outcomes_are_credited_to_the_state_each_episode_started_from(): @@ -197,80 +197,86 @@ def test_outcomes_are_credited_to_the_state_each_episode_started_from(): } sampler = ResetStateSamplerCfg(history_length=8, scores=[BetaSamplingScoreCfg(target=1.0)]) inputs = {"succeeded": mdp2.quantities.success, "env_origins": scene_entity.env_origins} - task_mdp, state = build(scene, fill=mdp.FillFromStates(states), shared=True, sampler=sampler, inputs=inputs) + task_mdp, state = build(scene, source=mdp.FromTensors(states), shared=True, sampler=sampler, inputs=inputs) transition = task_mdp.transition() for _ in range(6): reset(task_mdp, state, [True] * 16) mdp2.evaluate(task_mdp, state, transition) # success: the restored joint position is positive - bank = mdp.reset_bank(state) - np.testing.assert_allclose(bank.success_rate.cpu().numpy(), [1.0, 0.0]) - assert bank.episode_counts.sum() == 5 * 16 # the first reset has no episode to credit + reset_states = mdp.get_reset_states(state) + np.testing.assert_allclose(reset_states.success_rate.cpu().numpy(), [1.0, 0.0]) + assert reset_states.episode_counts.sum() == 5 * 16 # the first reset has no episode to credit - bank.discard_outcomes() # a reset by hand mid-episode credits nothing + reset_states.skip_current_episodes() # a reset by hand mid-episode credits nothing reset(task_mdp, state, [True] * 16) - assert bank.episode_counts.sum() == 5 * 16 + assert reset_states.episode_counts.sum() == 5 * 16 -def test_recording_banks_visited_states_that_replay_restores(): +def test_recorded_visited_states_restore_when_pinned(): scene = Scene(num_worlds=2) sampler = ResetStateSamplerCfg(history_length=4, scores=[BetaSamplingScoreCfg(target=0.5)]) - record = mdp.RecordStates(slots=2, probability=1.0) - inputs = {**RECORDING, "record_when": mdp2.quantities.success} - fill = mdp.FillFromCandidates(CANDIDATES, bank_size=2) - task_mdp, state = build(scene, fill=fill, sampler=sampler, record=record, inputs=inputs) - bank, transition = mdp.reset_bank(state), task_mdp.transition() - filled = bank.states["joint_pos"][:, :2].clone() - assert torch.equal(bank.states["joint_pos"][:, 2:], filled) # recorded slots start as copies + record = mdp.RecordVisited(num_states=2, probability=1.0) + inputs = {**RECORDING, "record_if": mdp2.quantities.success} + source = mdp.FromTask(RESET_STATE_GENERATOR, num_states=2) + task_mdp, state = build(scene, source=source, sampler=sampler, record=record, inputs=inputs) + reset_states, transition = mdp.get_reset_states(state), task_mdp.transition() + filled = reset_states.states["joint_pos"][:, :2].clone() + assert torch.equal(reset_states.states["joint_pos"][:, 2:], filled) # recorded slots start as copies # Only world 1 visits a successful state, which is recorded into its first recorded slot with a fresh prior. joint_pos(scene).copy_(torch.tensor([-0.3, 0.7], device=DEVICE)) mdp2.evaluate(task_mdp, state, transition) - banked = bank.states["joint_pos"][..., 0] - assert torch.equal(banked[0], filled[0, :, 0].repeat(2)) and banked[1, 2] == 0.7 - assert bank.episode_counts[1, 2] == 0 and bank.success_rate[1, 2] == 0.5 + stored = reset_states.states["joint_pos"][..., 0] + assert torch.equal(stored[0], filled[0, :, 0].repeat(2)) and stored[1, 2] == 0.7 + assert reset_states.episode_counts[1, 2] == 0 and reset_states.success_rate[1, 2] == 0.5 - # Replay restarts world 1 from the recorded state; world 0 draws from its own bank. - bank.replay(torch.tensor([-1, 2])) + # Pinning resets world 1 to the recorded state; world 0 draws from its own states. + reset_states.pin(torch.tensor([-1, 2])) joint_pos(scene).fill_(9.0) reset(task_mdp, state, [True, True]) assert joint_pos(scene)[1] == 0.7 and joint_pos(scene)[0] in filled[0] - assert bank.slots.tolist()[1] == 2 + assert reset_states.started_from.tolist()[1] == 2 # Recording over the slot the episode started from drops that episode's credit. joint_pos(scene).copy_(torch.tensor([0.1, 0.2], device=DEVICE)) mdp2.evaluate(task_mdp, state, transition) # world 1 records into slot 3 mdp2.evaluate(task_mdp, state, transition) # then over slot 2 - bank.replay(None) + reset_states.unpin() reset(task_mdp, state, [False, True]) - assert bank.episode_counts[1, 2] == 0 and (bank.states["joint_pos"][1, 2:, 0] == 0.2).all() + assert reset_states.episode_counts[1, 2] == 0 and (reset_states.states["joint_pos"][1, 2:, 0] == 0.2).all() -def test_nominal_resets_keep_the_earlier_events_and_are_not_credited(): +def test_default_resets_keep_the_earlier_events_and_are_not_credited(): scene = Scene(num_worlds=4) - task_mdp, state = build(scene, fill=mdp.FillFromCandidates(CANDIDATES, bank_size=8), nominal_probability=1.0) - bank = mdp.reset_bank(state) + task_mdp, state = build( + scene, source=mdp.FromTask(RESET_STATE_GENERATOR, num_states=8), default_reset_probability=1.0 + ) + reset_states = mdp.get_reset_states(state) joint_pos(scene).fill_(9.0) for _ in range(2): reset(task_mdp, state, [True] * 4) - assert (joint_pos(scene) == 9.0).all() and (bank.slots == -1).all() and bank.episode_counts.sum() == 0 + assert ( + (joint_pos(scene) == 9.0).all() + and (reset_states.started_from == -1).all() + and reset_states.episode_counts.sum() == 0 + ) - bank.replay(torch.tensor([5, -1, -1, -1])) # a replay request overrides the nominal draw + reset_states.pin(torch.tensor([5, -1, -1, -1])) # a pin overrides the default reset reset(task_mdp, state, [True] * 4) - assert joint_pos(scene)[0] == bank.states["joint_pos"][0, 5, 0] and (joint_pos(scene)[1:] == 9.0).all() + assert joint_pos(scene)[0] == reset_states.states["joint_pos"][0, 5, 0] and (joint_pos(scene)[1:] == 9.0).all() -def test_saved_banks_fill_later_runs_with_the_same_worlds(tmp_path): +def test_saved_states_load_in_later_runs_with_the_same_worlds(tmp_path): scene = Scene(num_worlds=4) - _, state = build(scene, fill=mdp.FillFromCandidates(CANDIDATES, bank_size=3)) - path = tmp_path / "bank.pt" - mdp.reset_bank(state).save(path) + _, state = build(scene, source=mdp.FromTask(RESET_STATE_GENERATOR, num_states=3)) + path = tmp_path / "reset_states.pt" + mdp.get_reset_states(state).save(path) - _, loaded = build(Scene(num_worlds=4), fill=mdp.FillFromFile(path)) - for name, value in mdp.reset_bank(state).states.items(): - assert torch.equal(mdp.reset_bank(loaded).states[name], value) - with pytest.raises(ValueError, match="holds banks of 4 worlds"): - build(Scene(num_worlds=2), fill=mdp.FillFromFile(path)) + _, loaded = build(Scene(num_worlds=4), source=mdp.FromFile(path)) + for name, value in mdp.get_reset_states(state).states.items(): + assert torch.equal(mdp.get_reset_states(loaded).states[name], value) + with pytest.raises(ValueError, match="holds reset states of 4 worlds"): + build(Scene(num_worlds=2), source=mdp.FromFile(path)) @wp.func @@ -285,32 +291,32 @@ def _sample_goal_torch(mask, command, rng): sample_goal = mdp2.Term(torch=_sample_goal_torch, warp=_sample_goal, random=True) -def test_banked_commands_are_sampled_by_the_candidates_and_stand_over_the_resample(): +def test_stored_commands_are_sampled_by_the_generator_and_stand_over_the_resample(): goal = {"goal": mdp2.commands.goal} commands = {"goal": mdp2.Command(sample_goal)} - candidates = mdp2.TaskCfg( + generator = mdp2.TaskCfg( commands=commands, events={"draw": mdp2.Event(draw, outputs=outputs)}, - terminations=CANDIDATES.terminations, + terminations=RESET_STATE_GENERATOR.terminations, ) for backend in ("torch", "warp"): scene = Scene(num_worlds=4) event = mdp2.Event( - mdp.reset_from_bank, + mdp.reset_to_states, outputs={**outputs, **goal}, - params={"fill": mdp.FillFromCandidates(candidates, bank_size=3)}, + params={"source": mdp.FromTask(generator, num_states=3)}, ) builder = mdp2.MDPBuilder(scene.schema) builder.add_task(mdp2.TaskCfg(commands=commands, events={"reset": event})) task_mdp = builder.finalize(device=DEVICE, backend=backend) state = task_mdp.state(scene, seed=3) mdp2.startup(task_mdp, state) - bank = mdp.reset_bank(state) + reset_states = mdp.get_reset_states(state) - banked = bank.states["goal"] - assert ((banked >= 1.0) & (banked < 2.0)).all() and len(banked.unique()) == 12 # sampled, not the initial 0 + stored = reset_states.states["goal"] + assert ((stored >= 1.0) & (stored < 2.0)).all() and len(stored.unique()) == 12 # sampled, not the initial 0 reset(task_mdp, state, [True] * 4) - restored = bank.states["goal"][torch.arange(4), bank.slots] + restored = reset_states.states["goal"][torch.arange(4), reset_states.started_from] assert torch.equal(state.arrays[mdp2.commands.goal].torch, restored) @@ -323,13 +329,13 @@ def test_backends_and_graph_replay_restore_and_record_the_same_states(): task_mdp, state = build( scene, backend, - fill=mdp.FillFromCandidates(CANDIDATES, bank_size=8), + source=mdp.FromTask(RESET_STATE_GENERATOR, num_states=8), sampler=ResetStateSamplerCfg(history_length=4, scores=[BetaSamplingScoreCfg(target=0.5)]), - nominal_probability=0.25, - record=mdp.RecordStates(slots=4, probability=0.5), + default_reset_probability=0.25, + record=mdp.RecordVisited(num_states=4, probability=0.5), inputs=RECORDING, ) - bank = mdp.reset_bank(state) + reset_states = mdp.get_reset_states(state) mask = ProxyArray(wp.zeros(32, dtype=wp.bool, device=DEVICE)) transition = task_mdp.transition() actions = ProxyArray(wp.zeros((32, 0), dtype=wp.float32, device=DEVICE)) @@ -338,15 +344,18 @@ def test_backends_and_graph_replay_restore_and_record_the_same_states(): history = [] for step in range(12): mask.torch.copy_(torch.rand(32, device=DEVICE, generator=generator) < 0.5) - joint_pos(scene).add_(0.01) # the worlds move, so that records differ from the filled states - bank.replay(torch.arange(32, device=DEVICE) % 12 - 4 if step == 6 else None) + joint_pos(scene).add_(0.01) # the worlds move, so that records differ from the generated states + if step == 6: + reset_states.pin(torch.arange(32, device=DEVICE) % 12 - 4) + else: + reset_states.unpin() if captured is None: mdp2.reset(task_mdp, state, mask) mdp2.evaluate(task_mdp, state, transition) else: captured.reset() captured.evaluate() - history.append(torch.cat([joint_pos(scene), bank.states["joint_pos"].flatten()])) + history.append(torch.cat([joint_pos(scene), reset_states.states["joint_pos"].flatten()])) runs.append(torch.stack(history)) assert not torch.equal(runs[0][-1, 32:], runs[0][0, 32:]) # the worlds recorded states for run in runs[1:]: @@ -356,15 +365,15 @@ def test_backends_and_graph_replay_restore_and_record_the_same_states(): @pytest.mark.parametrize( ("params", "message"), [ - ({"fill": mdp.FillFromStates({"joint_pos": torch.zeros(2, 1, 1)})}, "but the event writes"), - ({"fill": mdp.FillFromCandidates(CANDIDATES, bank_size=2), "shared": True}, "needs the env_origins input"), + ({"source": mdp.FromTensors({"joint_pos": torch.zeros(2, 1, 1)})}, "but the event writes"), + ({"source": mdp.FromTask(RESET_STATE_GENERATOR, num_states=2), "shared": True}, "need the env_origins input"), ( - {"fill": mdp.FillFromCandidates(CANDIDATES, bank_size=2), "record": mdp.RecordStates(2, 0.1)}, + {"source": mdp.FromTask(RESET_STATE_GENERATOR, num_states=2), "record": mdp.RecordVisited(2, 0.1)}, "the terminated input", ), ], ids=["fill_misses_an_output", "shared_poses_without_origins", "recording_without_terminated"], ) -def test_invalid_banks_are_rejected_at_startup(params, message): +def test_invalid_reset_states_are_rejected_at_startup(params, message): with pytest.raises(ValueError, match=message): build(Scene(num_worlds=2), **params) diff --git a/source/isaaclab_tasks/changelog.d/mdp2-resets.changed.rst b/source/isaaclab_tasks/changelog.d/mdp2-resets.changed.rst index f0d818fb71aa..95cefc9ddb19 100644 --- a/source/isaaclab_tasks/changelog.d/mdp2-resets.changed.rst +++ b/source/isaaclab_tasks/changelog.d/mdp2-resets.changed.rst @@ -1,3 +1,3 @@ -* Changed ``Isaac-Lift-KukaAllegro-MDP2`` to reset through ``isaaclab_experimental.mdp2.mdp.reset_from_bank`` with the - MDP1 lift sampler settings and, as MDP1, a bank of 1024 states per object shared by the worlds that spawned it, - replacing its task-local reset bank. +* Changed ``Isaac-Lift-KukaAllegro-MDP2`` to reset through ``isaaclab_experimental.mdp2.mdp.reset_to_states`` with the + MDP1 lift sampler settings and, as MDP1, 1024 reset states per object shared by the worlds that spawned it, + replacing its task-local reset state bank. diff --git a/source/isaaclab_tasks/isaaclab_tasks/mdp2/lift_kuka_allegro/lift_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/mdp2/lift_kuka_allegro/lift_env_cfg.py index 81d0ed98e4eb..c799994caa85 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/mdp2/lift_kuka_allegro/lift_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/mdp2/lift_kuka_allegro/lift_env_cfg.py @@ -152,7 +152,7 @@ class KukaAllegroLiftPhysicsCfg(PresetCfg): default: NewtonCfg = newton_mjwarp -CANDIDATES = mdp2.TaskCfg( +RESET_STATE_GENERATOR = mdp2.TaskCfg( observations={ "descriptor": { "grasp_travel_distance": mdp2.Observation( @@ -222,7 +222,7 @@ class KukaAllegroLiftPhysicsCfg(PresetCfg): "velocity_range": ((0.0, 0.0),) * 6, }, ), - # A quarter of the candidates start with the object at the palm, whose pose the joint resets changed: the + # A quarter of the generated states start with the object at the palm, whose pose the joint resets changed: the # scene commits them first, since the palm pose is derived from the joint state. "reset_object_to_target": mdp2.Event( lift.reset_to_target, @@ -232,7 +232,7 @@ class KukaAllegroLiftPhysicsCfg(PresetCfg): ), }, ) -"""Candidate start states of the reset bank: how they are drawn, which are rejected, and what spreads them.""" +"""The task that generates reset states: how they are drawn, which are rejected, and what spreads them.""" TASK = mdp2.TaskCfg( actions={ @@ -453,16 +453,16 @@ class KukaAllegroLiftPhysicsCfg(PresetCfg): outputs={"gravity_w": scene.gravity_w}, params={"initial_gravity": (0.0, 0.0, 0.0), "final_gravity": (0.0, 0.0, -9.81)}, ), - # Restart from the valid start states that the policy solves about half the time. As in MDP1, the worlds that - # spawned the same object share a bank of 1024 states, harvested twice over and thinned to the most spread, - # and share its success statistics. + # Reset to the valid reset states that the policy solves about half the time. As in MDP1, the worlds that + # spawned the same object share 1024 reset states, harvested twice over and thinned to the most spread, and + # share their success statistics. "reset": mdp2.Event( - mdp.reset_from_bank, + mdp.reset_to_states, inputs={"succeeded": mdp2.quantities.success, "env_origins": scene.env_origins}, outputs={**robot_state, **object_state}, params={ # A world per object, as in small test runs, needs a roll per state. - "fill": mdp.FillFromCandidates(CANDIDATES, bank_size=1024, max_rolls=20000), + "source": mdp.FromTask(RESET_STATE_GENERATOR, num_states=1024, max_rolls=20000), "groups": mdp.prototype_groups, "sampler": ResetStateSamplerCfg( history_length=10, @@ -492,8 +492,11 @@ def play_mode(self): super().play_mode() adr = self.task.events["adr"] params = {**adr.params, "init_difficulty": adr.params["max_difficulty"], "promotion_only": True} - # As MDP1, a small bank taken as harvested: it only supplies starts to the few worlds that play. - bank = self.task.events["reset"] - fill = replace(bank.params["fill"], bank_size=32, oversample_factor=1.0) - events = {"adr": replace(adr, params=params), "reset": replace(bank, params={**bank.params, "fill": fill})} + # As MDP1, a few reset states taken as harvested: they only supply the few worlds that play. + reset = self.task.events["reset"] + source = replace(reset.params["source"], num_states=32, oversample_factor=1.0) + events = { + "adr": replace(adr, params=params), + "reset": replace(reset, params={**reset.params, "source": source}), + } self.task = replace(self.task, events={**self.task.events, **events}) diff --git a/source/isaaclab_tasks/test/mdp2/test_lift_kuka_allegro.py b/source/isaaclab_tasks/test/mdp2/test_lift_kuka_allegro.py index 77f33054456f..69ebba90d053 100644 --- a/source/isaaclab_tasks/test/mdp2/test_lift_kuka_allegro.py +++ b/source/isaaclab_tasks/test/mdp2/test_lift_kuka_allegro.py @@ -41,7 +41,7 @@ def scenario() -> Iterator[SimpleNamespace]: cfg.scene.num_envs = NUM_ENVS cfg.seed = 0 params = cfg.task.events["reset"].params - params["fill"] = dataclasses.replace(params["fill"], bank_size=2) + params["source"] = dataclasses.replace(params["source"], num_states=2) env = MDP2RLEnv(cfg) try: generator = torch.Generator(device=env.device).manual_seed(0) @@ -50,7 +50,7 @@ def rand(*shape, scale=1.0): return scale * (2.0 * torch.rand(*shape, device=env.device, generator=generator) - 1.0) env.reset() - restored = bank_and_scene_state(env, env.state) + restored = stored_and_scene_state(env, env.state) for _ in range(10): env.step(rand(NUM_ENVS, env.mdp.action_dim)) @@ -76,11 +76,11 @@ def rand(*shape, scale=1.0): env.close() -def bank_and_scene_state(env: MDP2RLEnv, state: mdp2.MDPState) -> dict[str, tuple[torch.Tensor, torch.Tensor]]: - """Return, per banked field, the banked state that each world plays and the field's value in the scene.""" - bank = mdp2.mdp.reset_bank(state) - banked = bank.buffer.get_state(bank.sampler.indices) - banked["object_pose_w"].torch[:, :3] += env.scene.env_origins # the bank stores poses relative to the origins +def stored_and_scene_state(env: MDP2RLEnv, state: mdp2.MDPState) -> dict[str, tuple[torch.Tensor, torch.Tensor]]: + """Return, per stored field, the stored state that each world plays and the field's value in the scene.""" + reset_states = mdp2.mdp.get_reset_states(state) + stored = reset_states.buffer.get_state(reset_states.sampler.indices) + stored["object_pose_w"].torch[:, :3] += env.scene.env_origins # poses are stored relative to the origins robot, target = env.scene["robot"].data, env.scene["object"].data fields = { "joint_pos": robot.joint_pos, @@ -88,16 +88,16 @@ def bank_and_scene_state(env: MDP2RLEnv, state: mdp2.MDPState) -> dict[str, tupl "object_pose_w": target.root_link_pose_w, "object_vel_w": target.root_com_vel_w, } - return {name: (banked[name].torch.clone(), field.torch.clone()) for name, field in fields.items()} + return {name: (stored[name].torch.clone(), field.torch.clone()) for name, field in fields.items()} def sampler_arrays(state: mdp2.MDPState) -> dict[str, torch.Tensor]: - """Return views of the reset bank's device state: its sampler's assignments, outcome history, and draw weights, - and the bank's own flags.""" - bank = mdp2.mdp.reset_bank(state) + """Return views of the reset states' device state: its sampler's assignments, outcome history, and draw weights, + and their own flags.""" + reset_states = mdp2.mdp.get_reset_states(state) arrays = { f"{owner}.{name}": value - for owner, holder in (("sampler", bank.sampler), ("bank", bank)) + for owner, holder in (("sampler", reset_states.sampler), ("reset_states", reset_states)) for name, value in vars(holder).items() if isinstance(value, (wp.array, ProxyArray)) } @@ -105,7 +105,7 @@ def sampler_arrays(state: mdp2.MDPState) -> dict[str, torch.Tensor]: def build(scenario: SimpleNamespace, backend: str) -> tuple[mdp2.MDP, mdp2.MDPState]: - """Compile the task for a backend, with the environment's term state, its point clouds, and its reset bank.""" + """Compile the task for a backend, with the environment's term state, its point clouds, and its reset states.""" env = scenario.env builder = mdp2.MDPBuilder(env.scene_data.schema) builder.add_task(scenario.cfg.task) @@ -143,11 +143,11 @@ def evaluate(scenario: SimpleNamespace, backend: str, progress: float) -> tuple[ return mdp, state, results -def test_bank_restores_and_terms_agree_across_backends(scenario: SimpleNamespace): - """The first reset fills the bank and restarts every world from it, and observations, rewards, and terminations - agree on both backends, halfway through the curriculum.""" - for name, (banked, restored) in scenario.restored.items(): - torch.testing.assert_close(restored, banked, atol=1e-5, rtol=0.0, msg=lambda message, name=name: name) +def test_reset_states_restore_and_terms_agree_across_backends(scenario: SimpleNamespace): + """The first reset generates the reset states and resets every world to them, and observations, rewards, and + terminations agree on both backends, halfway through the curriculum.""" + for name, (stored, restored) in scenario.restored.items(): + torch.testing.assert_close(restored, stored, atol=1e-5, rtol=0.0, msg=lambda message, name=name: name) (mdp, _, torch_results), (_, _, warp_results) = (evaluate(scenario, backend, 0.5) for backend in ("torch", "warp")) @@ -244,13 +244,13 @@ def test_terms_match_mdp1(scenario: SimpleNamespace): assert torch.equal(state.arrays[mdp2.quantities.success].torch > 0.5, success.succeeded) -def test_step_replays_as_one_graph_with_curriculum_and_bank(scenario: SimpleNamespace): - """The whole step is one CUDA graph, in which resets restore banked states on both backends alike, and the +def test_step_replays_as_one_graph_with_curriculum_and_reset_states(scenario: SimpleNamespace): + """The whole step is one CUDA graph, in which resets restore stored states on both backends alike, and the curriculum's gravity reaches the solver.""" env = scenario.env assert env.mdp.is_fully_capturable and env.is_captured and env.num_graphs == 1 - # Both backends draw the same banked state for every world from the same sampler state, and restore it. + # Both backends draw the same stored state for every world from the same sampler state, and restore it. mask = ProxyArray(wp.ones(NUM_ENVS, dtype=wp.bool, device=env.device)) before = {name: value.clone() for name, value in sampler_arrays(env.state).items()} playing = {} @@ -259,12 +259,12 @@ def test_step_replays_as_one_graph_with_curriculum_and_bank(scenario: SimpleName for name, value in sampler_arrays(state).items(): value.copy_(before[name]) mdp2.reset(mdp, state, mask) - playing[backend] = mdp2.mdp.reset_bank(state).sampler.indices.torch.clone() - for name, (banked, restored) in bank_and_scene_state(env, state).items(): - torch.testing.assert_close(restored, banked, atol=1e-5, rtol=0.0, msg=lambda message, name=name: name) + playing[backend] = mdp2.mdp.get_reset_states(state).sampler.indices.torch.clone() + for name, (stored, restored) in stored_and_scene_state(env, state).items(): + torch.testing.assert_close(restored, stored, atol=1e-5, rtol=0.0, msg=lambda message, name=name: name) assert torch.equal(playing["torch"], playing["warp"]) - # At full progress, every world times out in the replayed graph, which restores banked states and sets the final + # At full progress, every world times out in the replayed graph, which restores stored states and sets the final # gravity. env.state.arrays[PROGRESS].torch.fill_(1.0) env.episode_length_buf = torch.full_like(env.episode_length_buf, env.max_episode_length) @@ -274,8 +274,8 @@ def test_step_replays_as_one_graph_with_curriculum_and_bank(scenario: SimpleName solver_gravity = wp.to_torch(env.sim.backend_manager.backend.solver.mjw_model.opt.gravity) torch.testing.assert_close(env.scene_data.data("scene", "gravity_w").torch[:, 2], final) torch.testing.assert_close(solver_gravity[:NUM_ENVS, 2], final) - for name, (banked, restored) in bank_and_scene_state(env, env.state).items(): - torch.testing.assert_close(restored, banked, atol=1e-5, rtol=0.0, msg=lambda message, name=name: name) + for name, (stored, restored) in stored_and_scene_state(env, env.state).items(): + torch.testing.assert_close(restored, stored, atol=1e-5, rtol=0.0, msg=lambda message, name=name: name) def test_play_mode_starts_the_curriculum_at_its_end(): @@ -291,38 +291,38 @@ def test_play_mode_starts_the_curriculum_at_its_end(): def test_recorded_states_restore_through_the_simulation(scenario: SimpleNamespace): - """A state recorded during a step is restored, through the scene's writers, when its slot is replayed.""" + """A state recorded during a step is restored, through the scene's writers, when its slot is pinned.""" env = scenario.env task = dataclasses.replace(scenario.cfg.task, events=dict(scenario.cfg.task.events)) event = task.events["reset"] task.events["reset"] = dataclasses.replace( event, inputs={**event.inputs, "terminated": mdp2.terminated}, - # Recording needs a bank per world. - params={**event.params, "groups": None, "record": mdp2.mdp.RecordStates(slots=1, probability=1.0)}, + # Recording needs reset states per world. + params={**event.params, "groups": None, "record": mdp2.mdp.RecordVisited(num_states=1, probability=1.0)}, ) builder = mdp2.MDPBuilder(env.scene_data.schema) builder.add_task(task) mdp = builder.finalize(device=env.device, backend="warp") state, transition = mdp.state(env.scene_data), mdp.transition() - mdp2.startup(mdp, state) # fills a new bank from the candidates - bank = mdp2.mdp.reset_bank(state) + mdp2.startup(mdp, state) # generates new reset states + reset_states = mdp2.mdp.get_reset_states(state) for _ in range(3): env.sim.step(render=False) env.scene.update(dt=env.physics_dt) - visited = {name: scene for name, (_, scene) in bank_and_scene_state(env, state).items()} + visited = {name: scene for name, (_, scene) in stored_and_scene_state(env, state).items()} mdp2.evaluate(mdp, state, transition) recorded = ~transition.terminated.torch assert recorded.any() mask = ProxyArray(wp.ones(NUM_ENVS, dtype=wp.bool, device=env.device)) - bank.replay(torch.full((NUM_ENVS,), bank.size - 1, device=env.device)) + reset_states.pin(torch.full((NUM_ENVS,), reset_states.size - 1, device=env.device)) commit = lambda: env.scene_data.commit(mask.warp, mdp.reset_writes) # noqa: E731 mdp2.reset(mdp, state, mask, commit) commit() env.scene.update(dt=0.0) - for name, (_, restored) in bank_and_scene_state(env, state).items(): + for name, (_, restored) in stored_and_scene_state(env, state).items(): torch.testing.assert_close( restored[recorded], visited[name][recorded], atol=1e-5, rtol=0.0, msg=lambda message, name=name: name ) From dd2acbb547f813f0ee93775237ed0171ff416936 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 18:23:20 -0800 Subject: [PATCH 11/17] Expose the Viser server of the Viser visualizer ViserVisualizer.server returns the viewer's viser.ViserServer, so tools can add their own GUI controls and scene labels without reaching into private state. --- .../changelog.d/mdp2-reset-viewer.added.rst | 2 ++ .../changelog.d/mdp2-reset-viewer.minor | 0 .../isaaclab_visualizers/viser/viser_visualizer.py | 6 ++++++ 3 files changed, 8 insertions(+) create mode 100644 source/isaaclab_visualizers/changelog.d/mdp2-reset-viewer.added.rst create mode 100644 source/isaaclab_visualizers/changelog.d/mdp2-reset-viewer.minor diff --git a/source/isaaclab_visualizers/changelog.d/mdp2-reset-viewer.added.rst b/source/isaaclab_visualizers/changelog.d/mdp2-reset-viewer.added.rst new file mode 100644 index 000000000000..c6757f56a5a7 --- /dev/null +++ b/source/isaaclab_visualizers/changelog.d/mdp2-reset-viewer.added.rst @@ -0,0 +1,2 @@ +* Added :attr:`~isaaclab_visualizers.viser.ViserVisualizer.server`, the Viser server of the viewer, so tools can add + their own GUI controls and scene labels. diff --git a/source/isaaclab_visualizers/changelog.d/mdp2-reset-viewer.minor b/source/isaaclab_visualizers/changelog.d/mdp2-reset-viewer.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/viser/viser_visualizer.py b/source/isaaclab_visualizers/isaaclab_visualizers/viser/viser_visualizer.py index 19f4d954e453..850626124422 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/viser/viser_visualizer.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/viser/viser_visualizer.py @@ -291,6 +291,12 @@ def __init__(self, cfg: VisualizerCfg): self._paused_rendering = False self._paused_simulation = False + @property + def server(self) -> Any: + """The ``viser.ViserServer`` that serves the viewer, to add GUI controls and scene labels; None until + initialized.""" + return None if self._viewer is None else self._viewer._server + def initialize(self, sim: SimulationContext, *, cameras: list[PerspectiveCameraCfg | Camera]) -> None: """Initialize viewer resources and bind scene data provider. From 1af0a4c2c1cf5e8f0954e08dce4bd1d5d27ddca0 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 18:23:20 -0800 Subject: [PATCH 12/17] Add a reset viewer for MDP2 tasks ResetViewer shows and drives the reset bank of an MDP2 task from Viser and Newton viewer panels: it restores a slot in every world, draws starts as training does, rolls the candidates task to show which proposals are rejected, and plays episodes, with each world's slot and success rate above it and the selected world's bank as a table. Panels only queue requests; the controller applies them on the main thread and credits no interrupted episode. view_reset_states.py opens it for any MDP2 task. --- .../isaaclab_experimental.envs.rst | 4 + docs/source/how-to/reset_state_buffers.rst | 18 + scripts/tools/view_reset_states.py | 58 +++ .../changelog.d/mdp2-reset-viewer.added.rst | 3 + .../changelog.d/mdp2-reset-viewer.minor | 0 .../isaaclab_experimental/envs/__init__.pyi | 2 + .../envs/mdp2_reset_viewer.py | 330 ++++++++++++++++++ .../mdp2/mdp/reset_states.py | 5 + .../test/mdp2/test_mdp2_reset_viewer.py | 78 +++++ 9 files changed, 498 insertions(+) create mode 100644 scripts/tools/view_reset_states.py create mode 100644 source/isaaclab_experimental/changelog.d/mdp2-reset-viewer.added.rst create mode 100644 source/isaaclab_experimental/changelog.d/mdp2-reset-viewer.minor create mode 100644 source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_reset_viewer.py create mode 100644 source/isaaclab_tasks/test/mdp2/test_mdp2_reset_viewer.py diff --git a/docs/source/api/lab_experimental/isaaclab_experimental.envs.rst b/docs/source/api/lab_experimental/isaaclab_experimental.envs.rst index 974c8d9a9252..9d13a0f1b45f 100644 --- a/docs/source/api/lab_experimental/isaaclab_experimental.envs.rst +++ b/docs/source/api/lab_experimental/isaaclab_experimental.envs.rst @@ -22,6 +22,7 @@ The following classes are part of the public :mod:`isaaclab_experimental.envs` A MDP2RLEnv MDP2RLEnvCfg ResetStep + ResetViewer Stage Step @@ -52,6 +53,9 @@ The following classes are part of the public :mod:`isaaclab_experimental.envs` A .. autoclass:: ResetStep :members: +.. autoclass:: ResetViewer + :members: + .. autoclass:: Stage .. autoclass:: Step diff --git a/docs/source/how-to/reset_state_buffers.rst b/docs/source/how-to/reset_state_buffers.rst index cadadf91bf1d..cc5a41203df8 100644 --- a/docs/source/how-to/reset_state_buffers.rst +++ b/docs/source/how-to/reset_state_buffers.rst @@ -328,6 +328,24 @@ saves its reset states: Reset states per world or per group fit only runs with the same number of worlds and object assignment; shared reset states fit any. +View the bank +^^^^^^^^^^^^^ + +``scripts/tools/view_reset_states.py`` opens a task with a panel in each Viser or Newton viewer: + +.. code-block:: bash + + uv run --extra viser python scripts/tools/view_reset_states.py --task Isaac-Lift-KukaAllegro-MDP2 \ + --num_envs 16 --viz viser physics=newton_mjwarp + +The panel restores one slot in every world, draws starts as training does, rolls the candidates task +to show which proposals its terminations reject, and plays episodes with zero or random actions. It +shows each world's slot and success rate above the world, and the selected world's bank as a table: +kind, success rate, episodes, and the probability of the next draw. ``--bank`` shows a saved bank. +Viewing interrupts episodes, so it credits none of them. In your own scripts, +:class:`~isaaclab_experimental.envs.ResetViewer` is the controller: call ``attach()`` once and +``update()`` in the loop instead of ``env.step``. + Migrating existing reset configurations --------------------------------------- diff --git a/scripts/tools/view_reset_states.py b/scripts/tools/view_reset_states.py new file mode 100644 index 000000000000..555a770994b8 --- /dev/null +++ b/scripts/tools/view_reset_states.py @@ -0,0 +1,58 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""View the reset states of an MDP2 task: browse its bank, roll its candidates, and play episodes from them. + +The panel opens in each Viser or Newton viewer, for example:: + + uv run --extra viser python scripts/tools/view_reset_states.py --task Isaac-Lift-KukaAllegro-MDP2 \\ + --num_envs 16 --viz viser physics=newton_mjwarp + +then open the printed URL. ``--bank`` shows a saved bank instead of filling a new one. +""" + +import argparse +import sys + +import gymnasium as gym +import torch +from isaaclab_experimental.envs import ResetViewer +from isaaclab_experimental.mdp2 import mdp + +from isaaclab.app import add_launcher_args, launch_simulation + +import isaaclab_tasks # noqa: F401 +from isaaclab_tasks.utils import resolve_task_config, setup_preset_cli + +parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) +parser.add_argument("--task", required=True, help="Name of an MDP2 task.") +parser.add_argument("--num_envs", type=int, default=16, help="Number of worlds.") +parser.add_argument("--event", default="reset", help="Name of the reset_from_bank event.") +parser.add_argument("--bank", default=None, help="A bank saved by ResetBank.save or collect_reset_states.py.") +parser.add_argument("--policy", choices=("zero", "random"), default="zero", help="Actions of played episodes.") +add_launcher_args(parser) +parser.set_defaults(device=None) # let the task select the device +args_cli, hydra_args = setup_preset_cli(parser) +sys.argv = [sys.argv[0]] + hydra_args + +env_cfg, _ = resolve_task_config(args_cli.task, "") +env_cfg.scene.num_envs = args_cli.num_envs +if args_cli.bank is not None: + env_cfg.task.events[args_cli.event].params["fill"] = mdp.FillFromFile(args_cli.bank) + +with launch_simulation(env_cfg, args_cli): + env = gym.make(args_cli.task, cfg=env_cfg) + env.reset() + unwrapped = env.unwrapped + shape = (unwrapped.num_envs, unwrapped.mdp.action_dim) + policy = None + if args_cli.policy == "random": + policy = lambda observations: 2.0 * torch.rand(shape, device=unwrapped.device) - 1.0 # noqa: E731 + viewer = ResetViewer(env, args_cli.event, policy) + if not viewer.attach(): + print("No Viser or Newton viewer is open: pass --viz viser or --viz newton_gl.") + while unwrapped.sim.is_running(): + viewer.update() + env.close() diff --git a/source/isaaclab_experimental/changelog.d/mdp2-reset-viewer.added.rst b/source/isaaclab_experimental/changelog.d/mdp2-reset-viewer.added.rst new file mode 100644 index 000000000000..75c7e4e7f191 --- /dev/null +++ b/source/isaaclab_experimental/changelog.d/mdp2-reset-viewer.added.rst @@ -0,0 +1,3 @@ +* Added :class:`~isaaclab_experimental.envs.ResetViewer`, which shows and drives the reset bank of an MDP2 task from + Viser and Newton viewer panels: it restores slots, draws starts, rolls the candidates task, and plays episodes. +* Added :attr:`~isaaclab_experimental.mdp2.mdp.ResetBank.filled`, the number of filled slots in each bank. diff --git a/source/isaaclab_experimental/changelog.d/mdp2-reset-viewer.minor b/source/isaaclab_experimental/changelog.d/mdp2-reset-viewer.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/__init__.pyi b/source/isaaclab_experimental/isaaclab_experimental/envs/__init__.pyi index 607556de7fdb..70b101cf68fc 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/__init__.pyi +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/__init__.pyi @@ -11,6 +11,7 @@ __all__ = [ "MDP2EnvCfg", "MDP2RLEnv", "MDP2RLEnvCfg", + "ResetViewer", "Stage", "Step", "ResetStep", @@ -24,4 +25,5 @@ from .manager_based_env_warp import ManagerBasedEnvWarp from .manager_based_rl_env_warp import ManagerBasedRLEnvWarp from .mdp2_env import MDP2Env, MDP2RLEnv from .mdp2_env_cfg import MDP2EnvCfg, MDP2RLEnvCfg, ResetStep, Stage, Step +from .mdp2_reset_viewer import ResetViewer from .mdp2_scene_data import InteractiveSceneData diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_reset_viewer.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_reset_viewer.py new file mode 100644 index 000000000000..51200a46278f --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_reset_viewer.py @@ -0,0 +1,330 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Show and drive the reset states of an MDP2 environment from a visualizer. + +:class:`ResetViewer` is the controller: it restores bank slots, samples starts as training does, rolls the bank's +candidates task, and plays episodes with a policy. Panels for Viser and the Newton viewer only queue requests, from +their own threads; :meth:`ResetViewer.update` applies them on the main thread and hands the panels plain values. +""" + +from __future__ import annotations + +import queue +import time +from collections.abc import Callable +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +import numpy as np +import torch + +from isaaclab_experimental.mdp2 import mdp + +from .mdp2_env import MDP2Env + +MODES = ("draw", "slot", "candidates") +"""Viewer modes: ``draw`` samples starts as training does, ``slot`` restores one slot in every world, and +``candidates`` shows the proposals of the bank's candidates task.""" + + +@dataclass +class ResetSnapshot: + """Plain values that panels show, taken on the main thread after each update.""" + + mode: str + slot: int # The slot that slot mode restores + playing: bool + size: int # Slots per bank + filled: int # Slots that the fill wrote; the others record + shared: bool + world: int # The world whose bank the table shows + slots: np.ndarray # (num_worlds,) the slot each world started from, -1 for a nominal start + episode_length: np.ndarray # (num_worlds,) + success_rate: np.ndarray # (size,) of the world's bank + episode_counts: np.ndarray # (size,) + probabilities: np.ndarray # (size,) + accepted: np.ndarray | None = None # (num_worlds,) after a roll of the candidates + message: str = "" + labels: list[str] = field(default_factory=list) # One per world + + +class ResetViewer: + """Controller for viewing the bank of a ``reset_from_bank`` event and the episodes that start from it. + + Args: + env: An MDP2 environment, or a wrapper of one. + event: Name of the ``reset_from_bank`` event in the task. + policy: Returns the actions of a step from the observations; None holds zero actions. + """ + + def __init__(self, env: Any, event: str = "reset", policy: Callable[[dict], torch.Tensor] | None = None) -> None: + self.env: MDP2Env = env.unwrapped + self.bank = mdp.reset_bank(self.env.state, f"events.{event}") + fill = self.env.cfg.task.events[event].params.get("fill") + self._candidates_cfg = fill.candidates if isinstance(fill, mdp.FillFromCandidates) else None + self._candidates: mdp.Candidates | None = None + zeros = torch.zeros(self.env.num_envs, self.env.mdp.action_dim, device=self.env.device) + self.policy = policy or (lambda observations: zeros) + self.mode, self.slot, self.world, self.playing = "draw", 0, 0, False + self._accepted: torch.Tensor | None = None + self._message = "" + self._requests: queue.SimpleQueue = queue.SimpleQueue() + self._panels: list[Any] = [] + self.snapshot = self._snapshot() + + @property + def has_candidates(self) -> bool: + """Whether the bank fills from a candidates task, which the viewer can roll.""" + return self._candidates_cfg is not None + + def request(self, action: str, *args: Any) -> None: + """Queue an action by method name, such as ``request("show", 3)``, from any thread.""" + self._requests.put((action, args)) + + def attach(self) -> int: + """Add a panel to every Viser and Newton viewer of the environment's simulation, and return how many.""" + for visualizer in self.env.sim.visualizers: + kind = visualizer.cfg.backend.visualizer_type + if kind == "viser" and visualizer.server is not None: + self._panels.append(ViserResetPanel(self, visualizer.server)) + elif kind == "newton_gl": + self._panels.append(NewtonResetPanel(self, visualizer)) + self._refresh() + return len(self._panels) + + def update(self) -> None: + """Apply the queued requests, step the episodes if playing, render, and refresh the panels.""" + while not self._requests.empty(): + action, args = self._requests.get() + getattr(self, action)(*args) + if self.playing: + self.env.step(self.policy(self.env.observations)) + else: + self.env.sim.render() + time.sleep(1.0 / 60.0) # nothing moves while paused + self._refresh() + + def show(self, slot: int) -> None: + """Restart every world from its slot ``slot``, paused, and keep restarting there while playing.""" + self.slot = int(np.clip(slot, 0, self.bank.size - 1)) + self.bank.replay(torch.full((self.env.num_envs,), self.slot, device=self.env.device)) + self._reset("slot") + + def draw(self) -> None: + """Restart every world from a start drawn as in training, paused.""" + self.bank.replay(None) + self._reset("draw") + + def roll(self) -> None: + """Propose a state in every world with the bank's candidates task, and mark the ones it rejects.""" + if self._candidates_cfg is None: + self._message = "The bank does not fill from a candidates task." + return + if self._candidates is None: + self._candidates = mdp.Candidates(self._candidates_cfg, self.env.scene_data, self.env.device) + self.bank.discard_outcomes() # the episodes are interrupted + self._accepted = self._candidates.roll() + self.mode, self.playing = "candidates", False + accepted = int(self._accepted.sum()) + self._message = f"{accepted} of {self.env.num_envs} proposals accepted." + + def play(self) -> None: + """Step the episodes with the policy. Candidates are not episodes: playing first samples starts.""" + if self.mode == "candidates": + self.draw() + self.playing = True + + def pause(self) -> None: + self.playing = False + + def step(self) -> None: + """Advance the episodes by one step, paused.""" + if self.mode == "candidates": + self.draw() + self.playing = False + self.env.step(self.policy(self.env.observations)) + + def select(self, world: int) -> None: + """Show the bank of a world in the table.""" + self.world = int(np.clip(world, 0, self.env.num_envs - 1)) + + def save(self, path: str) -> None: + """Save the bank, to fill later runs with ``mdp.FillFromFile``.""" + self.bank.save(Path(path)) + self._message = f"Saved {self.bank.size} slots to {path}." + + def _reset(self, mode: str) -> None: + # Viewing interrupts episodes, whose outcomes say nothing about their starts. + self.bank.discard_outcomes() + self.env.reset() + self.mode, self.playing, self._accepted, self._message = mode, False, None, "" + + def _snapshot(self) -> ResetSnapshot: + bank, world = self.bank, self.world + + def row(values: torch.Tensor) -> np.ndarray: + return (values if bank.shared else values[world]).cpu().numpy() + + slots = bank.slots.cpu().numpy() + rates = bank.success_rate.cpu().numpy() + accepted = None if self._accepted is None else self._accepted.cpu().numpy() + labels = [] + for w, slot in enumerate(slots): + if accepted is not None: + labels.append("accepted" if accepted[w] else "rejected") + elif slot < 0: + labels.append("nominal") + else: + rate = rates[slot] if bank.shared else rates[w, slot] + labels.append(f"slot {slot} | {rate:.0%}") + return ResetSnapshot( + mode=self.mode, + slot=self.slot, + playing=self.playing, + size=bank.size, + filled=bank.filled, + shared=bank.shared, + world=world, + slots=slots, + episode_length=self.env.episode_length_buf.cpu().numpy(), + success_rate=row(bank.success_rate), + episode_counts=row(bank.episode_counts), + probabilities=row(bank.probabilities), + accepted=accepted, + message=self._message, + labels=labels, + ) + + def _refresh(self) -> None: + self.snapshot = self._snapshot() + for panel in self._panels: + panel.refresh(self.snapshot) + + +def rows(snapshot: ResetSnapshot) -> list[tuple[str, ...]]: + """Return a row per slot of the shown world's bank: slot, kind, success, episodes, probability. The slot the + world started from is marked with ``*``.""" + # Candidate proposals start from no slot. + current = -1 if snapshot.accepted is not None else snapshot.slots[0 if snapshot.shared else snapshot.world] + return [ + ( + f"{slot}{' *' if slot == current else ''}", + "filled" if slot < snapshot.filled else "recorded", + f"{snapshot.success_rate[slot]:.0%}", + f"{snapshot.episode_counts[slot]}", + f"{snapshot.probabilities[slot]:.3f}", + ) + for slot in range(snapshot.size) + ] + + +HEADER = ("slot", "kind", "success", "episodes", "p") + + +def html_table(snapshot: ResetSnapshot) -> str: + """Return the shown world's bank as an HTML table; Viser's Markdown does not render tables.""" + cell = "{}" + head = "".join(f"{name}" for name in HEADER) + body = "".join("" + "".join(cell.format(value) for value in row) + "" for row in rows(snapshot)) + return f"World {snapshot.world}{head}{body}
" + + +def status(snapshot: ResetSnapshot) -> str: + """Return one line on the mode and what the worlds show.""" + state = "playing" if snapshot.playing else "paused" + shows = {"draw": "drawn starts", "slot": f"slot {snapshot.slot}", "candidates": "candidate proposals"} + return f"**{shows[snapshot.mode]}**, {state}. {snapshot.message}" + + +class ViserResetPanel: + """A Viser sidebar folder for a :class:`ResetViewer`, and a label above every shown world.""" + + MAX_LABELS = 64 + + def __init__(self, viewer: ResetViewer, server: Any) -> None: + self.viewer, self.server = viewer, server + snapshot = viewer.snapshot + gui = server.gui + with gui.add_folder("Reset states"): + self._status = gui.add_markdown(status(snapshot)) + self._slot = gui.add_slider("Slot", min=0, max=max(snapshot.size - 1, 1), step=1, initial_value=0) + show = gui.add_button("Show slot in every world", hint="Restart every world from this slot, paused.") + draw = gui.add_button("Draw starts", hint="Restart every world from a start drawn as in training.") + roll = gui.add_button("Roll candidates", disabled=not viewer.has_candidates) + play = gui.add_button_group("Episodes", ("Play", "Pause", "Step")) + self._world = gui.add_number("World", 0, min=0, max=viewer.env.num_envs - 1, step=1) + self._table = gui.add_html(html_table(snapshot)) + self._path = gui.add_text("File", "reset_bank.pt") + save = gui.add_button("Save bank") + + show.on_click(lambda _: viewer.request("show", int(self._slot.value))) + # The panel also sets these controls to the viewer's state, which must not request it again. + self._slot.on_update(lambda _: self._request_if_changed("show", int(self._slot.value), viewer.slot)) + draw.on_click(lambda _: viewer.request("draw")) + roll.on_click(lambda _: viewer.request("roll")) + play.on_click(lambda event: viewer.request(event.target.value.lower())) + self._world.on_update(lambda _: self._request_if_changed("select", int(self._world.value), viewer.world)) + save.on_click(lambda _: viewer.request("save", self._path.value)) + + origins = viewer.env.scene.env_origins.cpu().numpy() + self._labels = [ + server.scene.add_label(f"/reset_states/world_{w}", "", position=tuple(origins[w] + (0.0, 0.0, 0.8))) + for w in range(min(len(origins), self.MAX_LABELS)) + ] + self._last: tuple | None = None + + def refresh(self, snapshot: ResetSnapshot) -> None: + key = (status(snapshot), html_table(snapshot), tuple(snapshot.labels), snapshot.slot, snapshot.world) + if key == self._last: + return + self._last = key + self._status.content, self._table.content = key[0], key[1] + self._slot.value, self._world.value = snapshot.slot, snapshot.world + for label, text in zip(self._labels, snapshot.labels): + label.text = text + + def _request_if_changed(self, action: str, value: int, current: int) -> None: + if value != current: + self.viewer.request(action, value) + + +class NewtonResetPanel: + """A panel in the Newton viewer's ImGui interface for a :class:`ResetViewer`. It needs a display.""" + + def __init__(self, viewer: ResetViewer, visualizer: Any) -> None: + self.viewer, self._snapshot, self._slot = viewer, viewer.snapshot, 0 + visualizer.register_ui_callback(self._draw, position="side") + + def refresh(self, snapshot: ResetSnapshot) -> None: + self._snapshot = snapshot + + def _draw(self, imgui: Any) -> None: + snapshot, viewer = self._snapshot, self.viewer + if not imgui.collapsing_header("Reset states"): + return + imgui.text(status(snapshot).replace("**", "")) + changed, self._slot = imgui.slider_int("Slot", self._slot, 0, max(snapshot.size - 1, 0)) + if imgui.button("Show slot") or changed: + viewer.request("show", self._slot) + imgui.same_line() + if imgui.button("Draw starts"): + viewer.request("draw") + if viewer.has_candidates: + imgui.same_line() + if imgui.button("Roll candidates"): + viewer.request("roll") + for action in ("Play", "Pause", "Step"): + if imgui.button(action): + viewer.request(action.lower()) + imgui.same_line() + imgui.new_line() + changed, world = imgui.input_int("World", snapshot.world) + if changed: + viewer.request("select", world) + imgui.text(" ".join(HEADER)) + for row in rows(snapshot): + imgui.text(" ".join(row)) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py index 48bfd70bc030..f921a8b83bdf 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py @@ -286,6 +286,11 @@ def __init__( for name, value in self._outputs.items() } + @property + def filled(self) -> int: + """Slots that the fill wrote, first in each bank; the others record.""" + return self._filled + @property def states(self) -> dict[str, torch.Tensor]: """Copies of the stored states, ``(num_groups, size, ...)`` per output, ``(num_worlds, size, ...)`` for states diff --git a/source/isaaclab_tasks/test/mdp2/test_mdp2_reset_viewer.py b/source/isaaclab_tasks/test/mdp2/test_mdp2_reset_viewer.py new file mode 100644 index 000000000000..28bc046930fa --- /dev/null +++ b/source/isaaclab_tasks/test/mdp2/test_mdp2_reset_viewer.py @@ -0,0 +1,78 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Tests for the MDP2 reset viewer on the Kuka Allegro lift task, on Newton.""" + +import dataclasses +from collections.abc import Iterator + +import pytest +import torch +from isaaclab_experimental.envs import MDP2RLEnv, ResetViewer +from isaaclab_experimental.envs.mdp2_reset_viewer import ViserResetPanel + +from isaaclab_tasks.mdp2.lift_kuka_allegro.lift_env_cfg import KukaAllegroLiftEnvCfg, KukaAllegroLiftPhysicsCfg + +pytestmark = [pytest.mark.kitless, pytest.mark.skipif(not torch.cuda.is_available(), reason="Newton needs a GPU")] + +NUM_ENVS = 8 + + +@pytest.fixture(scope="module") +def viewer() -> Iterator[ResetViewer]: + cfg = KukaAllegroLiftEnvCfg() + cfg.sim.physics = KukaAllegroLiftPhysicsCfg().newton_mjwarp + cfg.sim.device = "cuda:0" + cfg.scene.num_envs = NUM_ENVS + cfg.seed = 0 + params = cfg.task.events["reset"].params + params["fill"] = dataclasses.replace(params["fill"], bank_size=3) + env = MDP2RLEnv(cfg) + try: + env.reset() + yield ResetViewer(env) + finally: + env.close() + + +def test_viewing_restores_slots_rolls_candidates_and_credits_nothing(viewer: ResetViewer): + env, bank = viewer.env, viewer.bank + viewer.request("show", 1) + viewer.request("select", 3) + viewer.update() + assert viewer.snapshot.mode == "slot" and viewer.snapshot.world == 3 + assert (bank.slots == 1).all() + torch.testing.assert_close(env.scene["robot"].data.joint_pos.torch, bank.states["joint_pos"][:, 1]) + + viewer.roll() + accepted = ~viewer._candidates.transition.terminated.torch + labels = ["accepted" if flag else "rejected" for flag in accepted.tolist()] + viewer.update() + assert viewer.snapshot.mode == "candidates" and viewer.snapshot.labels == labels + + # Candidates are not episodes: playing first draws starts as training does, and nothing is credited. + viewer.play() + assert viewer.mode == "draw" and viewer.playing + for _ in range(3): + viewer.update() + assert bank.episode_counts.sum() == 0 + viewer.show(0) + assert not viewer.playing and (bank.slots == 0).all() and bank.episode_counts.sum() == 0 + + +def test_viser_panel_shows_the_bank_and_labels_every_world(viewer: ResetViewer): + viser = pytest.importorskip("viser") + server = viser.ViserServer(host="127.0.0.1", port=0, verbose=False) + try: + panel = ViserResetPanel(viewer, server) + viewer.show(2) + viewer._panels.append(panel) + viewer.update() + assert [label.text for label in panel._labels] == viewer.snapshot.labels + assert ">2 *" in panel._table.content + assert "slot 2" in panel._status.content and panel._slot.value == 2 + finally: + viewer._panels.clear() + server.stop() From 935c0b2f5034e5693f0ae21446c2a0aa86cd38f0 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Fri, 20 Nov 2026 12:07:18 -0800 Subject: [PATCH 13/17] Play reset viewer episodes in real time --- .../changelog.d/mdp2-reset-viewer.added.rst | 3 ++- .../isaaclab_experimental/envs/mdp2_reset_viewer.py | 10 ++++++++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/source/isaaclab_experimental/changelog.d/mdp2-reset-viewer.added.rst b/source/isaaclab_experimental/changelog.d/mdp2-reset-viewer.added.rst index 75c7e4e7f191..9870251bd704 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-reset-viewer.added.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-reset-viewer.added.rst @@ -1,3 +1,4 @@ * Added :class:`~isaaclab_experimental.envs.ResetViewer`, which shows and drives the reset bank of an MDP2 task from - Viser and Newton viewer panels: it restores slots, draws starts, rolls the candidates task, and plays episodes. + Viser and Newton viewer panels: it restores slots, draws starts, rolls the candidates task, and plays episodes in + real time. * Added :attr:`~isaaclab_experimental.mdp2.mdp.ResetBank.filled`, the number of filled slots in each bank. diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_reset_viewer.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_reset_viewer.py index 51200a46278f..67f5e227bcba 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_reset_viewer.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_reset_viewer.py @@ -74,6 +74,7 @@ def __init__(self, env: Any, event: str = "reset", policy: Callable[[dict], torc self._message = "" self._requests: queue.SimpleQueue = queue.SimpleQueue() self._panels: list[Any] = [] + self._frame_end = time.perf_counter() self.snapshot = self._snapshot() @property @@ -97,7 +98,10 @@ def attach(self) -> int: return len(self._panels) def update(self) -> None: - """Apply the queued requests, step the episodes if playing, render, and refresh the panels.""" + """Apply the queued requests, step the episodes if playing, render, and refresh the panels. + + Episodes play in real time, one step per ``step_dt``, and a paused view renders at 30 frames per second. + """ while not self._requests.empty(): action, args = self._requests.get() getattr(self, action)(*args) @@ -105,8 +109,10 @@ def update(self) -> None: self.env.step(self.policy(self.env.observations)) else: self.env.sim.render() - time.sleep(1.0 / 60.0) # nothing moves while paused self._refresh() + # Unpaced, episodes would play as fast as the simulation steps. + self._frame_end = max(self._frame_end + (self.env.step_dt if self.playing else 1.0 / 30.0), time.perf_counter()) + time.sleep(max(0.0, self._frame_end - time.perf_counter())) def show(self, slot: int) -> None: """Restart every world from its slot ``slot``, paused, and keep restarting there while playing.""" From b1a504b03dd8ff3c5dda4746705a0f878094f04d Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Fri, 20 Nov 2026 12:12:03 -0800 Subject: [PATCH 14/17] Describe which viewer episodes the reset bank credits --- docs/source/how-to/reset_state_buffers.rst | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/source/how-to/reset_state_buffers.rst b/docs/source/how-to/reset_state_buffers.rst index cc5a41203df8..eb22c39ea004 100644 --- a/docs/source/how-to/reset_state_buffers.rst +++ b/docs/source/how-to/reset_state_buffers.rst @@ -339,10 +339,11 @@ View the bank --num_envs 16 --viz viser physics=newton_mjwarp The panel restores one slot in every world, draws starts as training does, rolls the candidates task -to show which proposals its terminations reject, and plays episodes with zero or random actions. It -shows each world's slot and success rate above the world, and the selected world's bank as a table: -kind, success rate, episodes, and the probability of the next draw. ``--bank`` shows a saved bank. -Viewing interrupts episodes, so it credits none of them. In your own scripts, +to show which proposals its terminations reject, and plays episodes in real time with zero or random +actions. It shows each world's slot and success rate above the world, and the selected world's bank as +a table: kind, success rate, episodes, and the probability of the next draw. ``--bank`` shows a saved +bank. Restoring, drawing, and rolling interrupt episodes, which are not credited. Episodes that end while +playing are credited, as in training. In your own scripts, :class:`~isaaclab_experimental.envs.ResetViewer` is the controller: call ``attach()`` once and ``update()`` in the loop instead of ``env.step``. From 90b2dbbd6eab5d5b4ae40112b7906ec26e9c9662 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Sun, 22 Nov 2026 13:12:44 -0800 Subject: [PATCH 15/17] Rename the reset viewer to ResetStateViewer Follow the reset states vocabulary: the viewer pins slots, rolls the generator task, and loads saved states with --states. --- .../isaaclab_experimental.envs.rst | 6 +- docs/source/how-to/reset_state_buffers.rst | 18 +- scripts/tools/view_reset_states.py | 18 +- .../changelog.d/mdp2-reset-viewer.added.rst | 8 +- .../isaaclab_experimental/envs/__init__.pyi | 4 +- .../envs/mdp2_reset_viewer.py | 178 +++++++++--------- .../mdp2/mdp/reset_states.py | 4 +- .../test/mdp2/test_mdp2_reset_viewer.py | 32 ++-- 8 files changed, 135 insertions(+), 133 deletions(-) diff --git a/docs/source/api/lab_experimental/isaaclab_experimental.envs.rst b/docs/source/api/lab_experimental/isaaclab_experimental.envs.rst index 9d13a0f1b45f..cab46f1809c1 100644 --- a/docs/source/api/lab_experimental/isaaclab_experimental.envs.rst +++ b/docs/source/api/lab_experimental/isaaclab_experimental.envs.rst @@ -21,8 +21,8 @@ The following classes are part of the public :mod:`isaaclab_experimental.envs` A MDP2EnvCfg MDP2RLEnv MDP2RLEnvCfg + ResetStateViewer ResetStep - ResetViewer Stage Step @@ -50,10 +50,10 @@ The following classes are part of the public :mod:`isaaclab_experimental.envs` A .. autoclass:: MDP2RLEnvCfg :show-inheritance: -.. autoclass:: ResetStep +.. autoclass:: ResetStateViewer :members: -.. autoclass:: ResetViewer +.. autoclass:: ResetStep :members: .. autoclass:: Stage diff --git a/docs/source/how-to/reset_state_buffers.rst b/docs/source/how-to/reset_state_buffers.rst index eb22c39ea004..04662234fdfd 100644 --- a/docs/source/how-to/reset_state_buffers.rst +++ b/docs/source/how-to/reset_state_buffers.rst @@ -328,8 +328,8 @@ saves its reset states: Reset states per world or per group fit only runs with the same number of worlds and object assignment; shared reset states fit any. -View the bank -^^^^^^^^^^^^^ +View reset states +^^^^^^^^^^^^^^^^^ ``scripts/tools/view_reset_states.py`` opens a task with a panel in each Viser or Newton viewer: @@ -338,13 +338,13 @@ View the bank uv run --extra viser python scripts/tools/view_reset_states.py --task Isaac-Lift-KukaAllegro-MDP2 \ --num_envs 16 --viz viser physics=newton_mjwarp -The panel restores one slot in every world, draws starts as training does, rolls the candidates task -to show which proposals its terminations reject, and plays episodes in real time with zero or random -actions. It shows each world's slot and success rate above the world, and the selected world's bank as -a table: kind, success rate, episodes, and the probability of the next draw. ``--bank`` shows a saved -bank. Restoring, drawing, and rolling interrupt episodes, which are not credited. Episodes that end while -playing are credited, as in training. In your own scripts, -:class:`~isaaclab_experimental.envs.ResetViewer` is the controller: call ``attach()`` once and +The panel resets every world to one slot, draws reset states as training does, rolls the generator +task to show which proposals its terminations reject, and plays episodes in real time with zero or +random actions. It shows each world's slot and success rate above the world, and the selected world's +reset states as a table: kind, success rate, episodes, and the probability of the next draw. +``--states`` shows saved reset states. Showing, drawing, and rolling interrupt episodes, which are not +credited. Episodes that end while playing are credited, as in training. In your own scripts, +:class:`~isaaclab_experimental.envs.ResetStateViewer` is the controller: call ``attach()`` once and ``update()`` in the loop instead of ``env.step``. Migrating existing reset configurations diff --git a/scripts/tools/view_reset_states.py b/scripts/tools/view_reset_states.py index 555a770994b8..b4478d3001b6 100644 --- a/scripts/tools/view_reset_states.py +++ b/scripts/tools/view_reset_states.py @@ -3,14 +3,14 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""View the reset states of an MDP2 task: browse its bank, roll its candidates, and play episodes from them. +"""View the reset states of an MDP2 task: browse them, roll its generator task, and play episodes from them. The panel opens in each Viser or Newton viewer, for example:: uv run --extra viser python scripts/tools/view_reset_states.py --task Isaac-Lift-KukaAllegro-MDP2 \\ --num_envs 16 --viz viser physics=newton_mjwarp -then open the printed URL. ``--bank`` shows a saved bank instead of filling a new one. +then open the printed URL. ``--states`` shows saved reset states instead of generating new ones. """ import argparse @@ -18,7 +18,7 @@ import gymnasium as gym import torch -from isaaclab_experimental.envs import ResetViewer +from isaaclab_experimental.envs import ResetStateViewer from isaaclab_experimental.mdp2 import mdp from isaaclab.app import add_launcher_args, launch_simulation @@ -29,8 +29,10 @@ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--task", required=True, help="Name of an MDP2 task.") parser.add_argument("--num_envs", type=int, default=16, help="Number of worlds.") -parser.add_argument("--event", default="reset", help="Name of the reset_from_bank event.") -parser.add_argument("--bank", default=None, help="A bank saved by ResetBank.save or collect_reset_states.py.") +parser.add_argument("--event", default="reset", help="Name of the reset_to_states event.") +parser.add_argument( + "--states", default=None, help="Reset states saved by ResetStates.save or generate_reset_states.py." +) parser.add_argument("--policy", choices=("zero", "random"), default="zero", help="Actions of played episodes.") add_launcher_args(parser) parser.set_defaults(device=None) # let the task select the device @@ -39,8 +41,8 @@ env_cfg, _ = resolve_task_config(args_cli.task, "") env_cfg.scene.num_envs = args_cli.num_envs -if args_cli.bank is not None: - env_cfg.task.events[args_cli.event].params["fill"] = mdp.FillFromFile(args_cli.bank) +if args_cli.states is not None: + env_cfg.task.events[args_cli.event].params["source"] = mdp.FromFile(args_cli.states) with launch_simulation(env_cfg, args_cli): env = gym.make(args_cli.task, cfg=env_cfg) @@ -50,7 +52,7 @@ policy = None if args_cli.policy == "random": policy = lambda observations: 2.0 * torch.rand(shape, device=unwrapped.device) - 1.0 # noqa: E731 - viewer = ResetViewer(env, args_cli.event, policy) + viewer = ResetStateViewer(env, args_cli.event, policy) if not viewer.attach(): print("No Viser or Newton viewer is open: pass --viz viser or --viz newton_gl.") while unwrapped.sim.is_running(): diff --git a/source/isaaclab_experimental/changelog.d/mdp2-reset-viewer.added.rst b/source/isaaclab_experimental/changelog.d/mdp2-reset-viewer.added.rst index 9870251bd704..851e0c527e86 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-reset-viewer.added.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-reset-viewer.added.rst @@ -1,4 +1,4 @@ -* Added :class:`~isaaclab_experimental.envs.ResetViewer`, which shows and drives the reset bank of an MDP2 task from - Viser and Newton viewer panels: it restores slots, draws starts, rolls the candidates task, and plays episodes in - real time. -* Added :attr:`~isaaclab_experimental.mdp2.mdp.ResetBank.filled`, the number of filled slots in each bank. +* Added :class:`~isaaclab_experimental.envs.ResetStateViewer`, which shows and drives the reset states of an MDP2 + task from Viser and Newton viewer panels: it pins slots, draws reset states, rolls the generator task, and plays + episodes in real time. +* Added ``ResetStates.num_source_states``, the number of slots in each world that come from the source. diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/__init__.pyi b/source/isaaclab_experimental/isaaclab_experimental/envs/__init__.pyi index 70b101cf68fc..5d5f4f3cdab6 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/__init__.pyi +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/__init__.pyi @@ -11,7 +11,7 @@ __all__ = [ "MDP2EnvCfg", "MDP2RLEnv", "MDP2RLEnvCfg", - "ResetViewer", + "ResetStateViewer", "Stage", "Step", "ResetStep", @@ -25,5 +25,5 @@ from .manager_based_env_warp import ManagerBasedEnvWarp from .manager_based_rl_env_warp import ManagerBasedRLEnvWarp from .mdp2_env import MDP2Env, MDP2RLEnv from .mdp2_env_cfg import MDP2EnvCfg, MDP2RLEnvCfg, ResetStep, Stage, Step -from .mdp2_reset_viewer import ResetViewer +from .mdp2_reset_viewer import ResetStateViewer from .mdp2_scene_data import InteractiveSceneData diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_reset_viewer.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_reset_viewer.py index 67f5e227bcba..b58b44bf1924 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_reset_viewer.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_reset_viewer.py @@ -5,9 +5,9 @@ """Show and drive the reset states of an MDP2 environment from a visualizer. -:class:`ResetViewer` is the controller: it restores bank slots, samples starts as training does, rolls the bank's -candidates task, and plays episodes with a policy. Panels for Viser and the Newton viewer only queue requests, from -their own threads; :meth:`ResetViewer.update` applies them on the main thread and hands the panels plain values. +:class:`ResetStateViewer` is the controller: it pins slots, draws reset states as training does, rolls the generator +task, and plays episodes with a policy. Panels for Viser and the Newton viewer only queue requests, from their own +threads; :meth:`ResetStateViewer.update` applies them on the main thread and hands the panels plain values. """ from __future__ import annotations @@ -26,47 +26,47 @@ from .mdp2_env import MDP2Env -MODES = ("draw", "slot", "candidates") -"""Viewer modes: ``draw`` samples starts as training does, ``slot`` restores one slot in every world, and -``candidates`` shows the proposals of the bank's candidates task.""" +MODES = ("draw", "slot", "generator") +"""Viewer modes: ``draw`` draws reset states as training does, ``slot`` resets every world to one slot, and +``generator`` shows the proposals of the generator task.""" @dataclass -class ResetSnapshot: +class ResetStateSnapshot: """Plain values that panels show, taken on the main thread after each update.""" mode: str slot: int # The slot that slot mode restores playing: bool - size: int # Slots per bank - filled: int # Slots that the fill wrote; the others record + size: int # Slots per world + num_source_states: int # Slots from the source; the others record shared: bool - world: int # The world whose bank the table shows - slots: np.ndarray # (num_worlds,) the slot each world started from, -1 for a nominal start + world: int # The world whose reset states the table shows + started_from: np.ndarray # (num_worlds,) the slot each world started from, -1 for a default reset episode_length: np.ndarray # (num_worlds,) - success_rate: np.ndarray # (size,) of the world's bank + success_rate: np.ndarray # (size,) of the world's reset states episode_counts: np.ndarray # (size,) probabilities: np.ndarray # (size,) - accepted: np.ndarray | None = None # (num_worlds,) after a roll of the candidates + accepted: np.ndarray | None = None # (num_worlds,) after a roll of the generator message: str = "" labels: list[str] = field(default_factory=list) # One per world -class ResetViewer: - """Controller for viewing the bank of a ``reset_from_bank`` event and the episodes that start from it. +class ResetStateViewer: + """Controller for viewing the reset states of a ``reset_to_states`` event and the episodes that start from them. Args: env: An MDP2 environment, or a wrapper of one. - event: Name of the ``reset_from_bank`` event in the task. + event: Name of the ``reset_to_states`` event in the task. policy: Returns the actions of a step from the observations; None holds zero actions. """ def __init__(self, env: Any, event: str = "reset", policy: Callable[[dict], torch.Tensor] | None = None) -> None: self.env: MDP2Env = env.unwrapped - self.bank = mdp.reset_bank(self.env.state, f"events.{event}") - fill = self.env.cfg.task.events[event].params.get("fill") - self._candidates_cfg = fill.candidates if isinstance(fill, mdp.FillFromCandidates) else None - self._candidates: mdp.Candidates | None = None + self.reset_states = mdp.get_reset_states(self.env.state, f"events.{event}") + source = self.env.cfg.task.events[event].params.get("source") + self._generator_cfg = source.task if isinstance(source, mdp.FromTask) else None + self._generator: mdp.StateGenerator | None = None zeros = torch.zeros(self.env.num_envs, self.env.mdp.action_dim, device=self.env.device) self.policy = policy or (lambda observations: zeros) self.mode, self.slot, self.world, self.playing = "draw", 0, 0, False @@ -78,9 +78,9 @@ def __init__(self, env: Any, event: str = "reset", policy: Callable[[dict], torc self.snapshot = self._snapshot() @property - def has_candidates(self) -> bool: - """Whether the bank fills from a candidates task, which the viewer can roll.""" - return self._candidates_cfg is not None + def has_generator(self) -> bool: + """Whether the reset states come from a generator task, which the viewer can roll.""" + return self._generator_cfg is not None def request(self, action: str, *args: Any) -> None: """Queue an action by method name, such as ``request("show", 3)``, from any thread.""" @@ -91,9 +91,9 @@ def attach(self) -> int: for visualizer in self.env.sim.visualizers: kind = visualizer.cfg.backend.visualizer_type if kind == "viser" and visualizer.server is not None: - self._panels.append(ViserResetPanel(self, visualizer.server)) + self._panels.append(ViserResetStatePanel(self, visualizer.server)) elif kind == "newton_gl": - self._panels.append(NewtonResetPanel(self, visualizer)) + self._panels.append(NewtonResetStatePanel(self, visualizer)) self._refresh() return len(self._panels) @@ -115,32 +115,32 @@ def update(self) -> None: time.sleep(max(0.0, self._frame_end - time.perf_counter())) def show(self, slot: int) -> None: - """Restart every world from its slot ``slot``, paused, and keep restarting there while playing.""" - self.slot = int(np.clip(slot, 0, self.bank.size - 1)) - self.bank.replay(torch.full((self.env.num_envs,), self.slot, device=self.env.device)) + """Reset every world to its slot ``slot``, paused, and keep resetting there while playing.""" + self.slot = int(np.clip(slot, 0, self.reset_states.size - 1)) + self.reset_states.pin(torch.full((self.env.num_envs,), self.slot, device=self.env.device)) self._reset("slot") def draw(self) -> None: - """Restart every world from a start drawn as in training, paused.""" - self.bank.replay(None) + """Reset every world to a reset state drawn as in training, paused.""" + self.reset_states.unpin() self._reset("draw") def roll(self) -> None: - """Propose a state in every world with the bank's candidates task, and mark the ones it rejects.""" - if self._candidates_cfg is None: - self._message = "The bank does not fill from a candidates task." + """Propose a state in every world with the generator task, and mark the ones it rejects.""" + if self._generator_cfg is None: + self._message = "The reset states do not come from a generator task." return - if self._candidates is None: - self._candidates = mdp.Candidates(self._candidates_cfg, self.env.scene_data, self.env.device) - self.bank.discard_outcomes() # the episodes are interrupted - self._accepted = self._candidates.roll() - self.mode, self.playing = "candidates", False + if self._generator is None: + self._generator = mdp.StateGenerator(self._generator_cfg, self.env.scene_data, self.env.device) + self.reset_states.skip_current_episodes() # the episodes are interrupted + self._accepted = self._generator.roll() + self.mode, self.playing = "generator", False accepted = int(self._accepted.sum()) self._message = f"{accepted} of {self.env.num_envs} proposals accepted." def play(self) -> None: - """Step the episodes with the policy. Candidates are not episodes: playing first samples starts.""" - if self.mode == "candidates": + """Step the episodes with the policy. Proposals are not episodes: playing first draws reset states.""" + if self.mode == "generator": self.draw() self.playing = True @@ -149,57 +149,57 @@ def pause(self) -> None: def step(self) -> None: """Advance the episodes by one step, paused.""" - if self.mode == "candidates": + if self.mode == "generator": self.draw() self.playing = False self.env.step(self.policy(self.env.observations)) def select(self, world: int) -> None: - """Show the bank of a world in the table.""" + """Show the reset states of a world in the table.""" self.world = int(np.clip(world, 0, self.env.num_envs - 1)) def save(self, path: str) -> None: - """Save the bank, to fill later runs with ``mdp.FillFromFile``.""" - self.bank.save(Path(path)) - self._message = f"Saved {self.bank.size} slots to {path}." + """Save the reset states, for later runs to load with ``mdp.FromFile``.""" + self.reset_states.save(Path(path)) + self._message = f"Saved {self.reset_states.size} slots to {path}." def _reset(self, mode: str) -> None: - # Viewing interrupts episodes, whose outcomes say nothing about their starts. - self.bank.discard_outcomes() + # Viewing interrupts episodes, whose outcomes say nothing about their reset states. + self.reset_states.skip_current_episodes() self.env.reset() self.mode, self.playing, self._accepted, self._message = mode, False, None, "" - def _snapshot(self) -> ResetSnapshot: - bank, world = self.bank, self.world + def _snapshot(self) -> ResetStateSnapshot: + states, world = self.reset_states, self.world def row(values: torch.Tensor) -> np.ndarray: - return (values if bank.shared else values[world]).cpu().numpy() + return (values if states.shared else values[world]).cpu().numpy() - slots = bank.slots.cpu().numpy() - rates = bank.success_rate.cpu().numpy() + started_from = states.started_from.cpu().numpy() + rates = states.success_rate.cpu().numpy() accepted = None if self._accepted is None else self._accepted.cpu().numpy() labels = [] - for w, slot in enumerate(slots): + for w, slot in enumerate(started_from): if accepted is not None: labels.append("accepted" if accepted[w] else "rejected") elif slot < 0: - labels.append("nominal") + labels.append("default") else: - rate = rates[slot] if bank.shared else rates[w, slot] + rate = rates[slot] if states.shared else rates[w, slot] labels.append(f"slot {slot} | {rate:.0%}") - return ResetSnapshot( + return ResetStateSnapshot( mode=self.mode, slot=self.slot, playing=self.playing, - size=bank.size, - filled=bank.filled, - shared=bank.shared, + size=states.size, + num_source_states=states.num_source_states, + shared=states.shared, world=world, - slots=slots, + started_from=started_from, episode_length=self.env.episode_length_buf.cpu().numpy(), - success_rate=row(bank.success_rate), - episode_counts=row(bank.episode_counts), - probabilities=row(bank.probabilities), + success_rate=row(states.success_rate), + episode_counts=row(states.episode_counts), + probabilities=row(states.probabilities), accepted=accepted, message=self._message, labels=labels, @@ -211,15 +211,15 @@ def _refresh(self) -> None: panel.refresh(self.snapshot) -def rows(snapshot: ResetSnapshot) -> list[tuple[str, ...]]: - """Return a row per slot of the shown world's bank: slot, kind, success, episodes, probability. The slot the - world started from is marked with ``*``.""" - # Candidate proposals start from no slot. - current = -1 if snapshot.accepted is not None else snapshot.slots[0 if snapshot.shared else snapshot.world] +def rows(snapshot: ResetStateSnapshot) -> list[tuple[str, ...]]: + """Return a row per slot of the shown world's reset states: slot, kind, success, episodes, probability. The slot + the world started from is marked with ``*``.""" + # Generator proposals start from no slot. + current = -1 if snapshot.accepted is not None else snapshot.started_from[0 if snapshot.shared else snapshot.world] return [ ( f"{slot}{' *' if slot == current else ''}", - "filled" if slot < snapshot.filled else "recorded", + "source" if slot < snapshot.num_source_states else "recorded", f"{snapshot.success_rate[slot]:.0%}", f"{snapshot.episode_counts[slot]}", f"{snapshot.probabilities[slot]:.3f}", @@ -231,41 +231,41 @@ def rows(snapshot: ResetSnapshot) -> list[tuple[str, ...]]: HEADER = ("slot", "kind", "success", "episodes", "p") -def html_table(snapshot: ResetSnapshot) -> str: - """Return the shown world's bank as an HTML table; Viser's Markdown does not render tables.""" +def html_table(snapshot: ResetStateSnapshot) -> str: + """Return the shown world's reset states as an HTML table; Viser's Markdown does not render tables.""" cell = "{}" head = "".join(f"{name}" for name in HEADER) body = "".join("" + "".join(cell.format(value) for value in row) + "" for row in rows(snapshot)) return f"World {snapshot.world}{head}{body}
" -def status(snapshot: ResetSnapshot) -> str: +def status(snapshot: ResetStateSnapshot) -> str: """Return one line on the mode and what the worlds show.""" state = "playing" if snapshot.playing else "paused" - shows = {"draw": "drawn starts", "slot": f"slot {snapshot.slot}", "candidates": "candidate proposals"} + shows = {"draw": "drawn reset states", "slot": f"slot {snapshot.slot}", "generator": "generator proposals"} return f"**{shows[snapshot.mode]}**, {state}. {snapshot.message}" -class ViserResetPanel: - """A Viser sidebar folder for a :class:`ResetViewer`, and a label above every shown world.""" +class ViserResetStatePanel: + """A Viser sidebar folder for a :class:`ResetStateViewer`, and a label above every shown world.""" MAX_LABELS = 64 - def __init__(self, viewer: ResetViewer, server: Any) -> None: + def __init__(self, viewer: ResetStateViewer, server: Any) -> None: self.viewer, self.server = viewer, server snapshot = viewer.snapshot gui = server.gui with gui.add_folder("Reset states"): self._status = gui.add_markdown(status(snapshot)) self._slot = gui.add_slider("Slot", min=0, max=max(snapshot.size - 1, 1), step=1, initial_value=0) - show = gui.add_button("Show slot in every world", hint="Restart every world from this slot, paused.") - draw = gui.add_button("Draw starts", hint="Restart every world from a start drawn as in training.") - roll = gui.add_button("Roll candidates", disabled=not viewer.has_candidates) + show = gui.add_button("Show slot in every world", hint="Reset every world to this slot, paused.") + draw = gui.add_button("Draw reset states", hint="Reset every world to a state drawn as in training.") + roll = gui.add_button("Roll generator", disabled=not viewer.has_generator) play = gui.add_button_group("Episodes", ("Play", "Pause", "Step")) self._world = gui.add_number("World", 0, min=0, max=viewer.env.num_envs - 1, step=1) self._table = gui.add_html(html_table(snapshot)) - self._path = gui.add_text("File", "reset_bank.pt") - save = gui.add_button("Save bank") + self._path = gui.add_text("File", "reset_states.pt") + save = gui.add_button("Save reset states") show.on_click(lambda _: viewer.request("show", int(self._slot.value))) # The panel also sets these controls to the viewer's state, which must not request it again. @@ -283,7 +283,7 @@ def __init__(self, viewer: ResetViewer, server: Any) -> None: ] self._last: tuple | None = None - def refresh(self, snapshot: ResetSnapshot) -> None: + def refresh(self, snapshot: ResetStateSnapshot) -> None: key = (status(snapshot), html_table(snapshot), tuple(snapshot.labels), snapshot.slot, snapshot.world) if key == self._last: return @@ -298,14 +298,14 @@ def _request_if_changed(self, action: str, value: int, current: int) -> None: self.viewer.request(action, value) -class NewtonResetPanel: - """A panel in the Newton viewer's ImGui interface for a :class:`ResetViewer`. It needs a display.""" +class NewtonResetStatePanel: + """A panel in the Newton viewer's ImGui interface for a :class:`ResetStateViewer`. It needs a display.""" - def __init__(self, viewer: ResetViewer, visualizer: Any) -> None: + def __init__(self, viewer: ResetStateViewer, visualizer: Any) -> None: self.viewer, self._snapshot, self._slot = viewer, viewer.snapshot, 0 visualizer.register_ui_callback(self._draw, position="side") - def refresh(self, snapshot: ResetSnapshot) -> None: + def refresh(self, snapshot: ResetStateSnapshot) -> None: self._snapshot = snapshot def _draw(self, imgui: Any) -> None: @@ -317,11 +317,11 @@ def _draw(self, imgui: Any) -> None: if imgui.button("Show slot") or changed: viewer.request("show", self._slot) imgui.same_line() - if imgui.button("Draw starts"): + if imgui.button("Draw reset states"): viewer.request("draw") - if viewer.has_candidates: + if viewer.has_generator: imgui.same_line() - if imgui.button("Roll candidates"): + if imgui.button("Roll generator"): viewer.request("roll") for action in ("Play", "Pause", "Step"): if imgui.button(action): diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py index f921a8b83bdf..7ff5ed6d5e04 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py @@ -287,8 +287,8 @@ def __init__( } @property - def filled(self) -> int: - """Slots that the fill wrote, first in each bank; the others record.""" + def num_source_states(self) -> int: + """Slots that the source wrote, first in each world's reset states; the others record.""" return self._filled @property diff --git a/source/isaaclab_tasks/test/mdp2/test_mdp2_reset_viewer.py b/source/isaaclab_tasks/test/mdp2/test_mdp2_reset_viewer.py index 28bc046930fa..886b4cd11aa0 100644 --- a/source/isaaclab_tasks/test/mdp2/test_mdp2_reset_viewer.py +++ b/source/isaaclab_tasks/test/mdp2/test_mdp2_reset_viewer.py @@ -10,8 +10,8 @@ import pytest import torch -from isaaclab_experimental.envs import MDP2RLEnv, ResetViewer -from isaaclab_experimental.envs.mdp2_reset_viewer import ViserResetPanel +from isaaclab_experimental.envs import MDP2RLEnv, ResetStateViewer +from isaaclab_experimental.envs.mdp2_reset_viewer import ViserResetStatePanel from isaaclab_tasks.mdp2.lift_kuka_allegro.lift_env_cfg import KukaAllegroLiftEnvCfg, KukaAllegroLiftPhysicsCfg @@ -21,52 +21,52 @@ @pytest.fixture(scope="module") -def viewer() -> Iterator[ResetViewer]: +def viewer() -> Iterator[ResetStateViewer]: cfg = KukaAllegroLiftEnvCfg() cfg.sim.physics = KukaAllegroLiftPhysicsCfg().newton_mjwarp cfg.sim.device = "cuda:0" cfg.scene.num_envs = NUM_ENVS cfg.seed = 0 params = cfg.task.events["reset"].params - params["fill"] = dataclasses.replace(params["fill"], bank_size=3) + params["source"] = dataclasses.replace(params["source"], num_states=3) env = MDP2RLEnv(cfg) try: env.reset() - yield ResetViewer(env) + yield ResetStateViewer(env) finally: env.close() -def test_viewing_restores_slots_rolls_candidates_and_credits_nothing(viewer: ResetViewer): - env, bank = viewer.env, viewer.bank +def test_viewing_pins_slots_rolls_the_generator_and_credits_nothing(viewer: ResetStateViewer): + env, reset_states = viewer.env, viewer.reset_states viewer.request("show", 1) viewer.request("select", 3) viewer.update() assert viewer.snapshot.mode == "slot" and viewer.snapshot.world == 3 - assert (bank.slots == 1).all() - torch.testing.assert_close(env.scene["robot"].data.joint_pos.torch, bank.states["joint_pos"][:, 1]) + assert (reset_states.started_from == 1).all() + torch.testing.assert_close(env.scene["robot"].data.joint_pos.torch, reset_states.states["joint_pos"][:, 1]) viewer.roll() - accepted = ~viewer._candidates.transition.terminated.torch + accepted = ~viewer._generator.transition.terminated.torch labels = ["accepted" if flag else "rejected" for flag in accepted.tolist()] viewer.update() - assert viewer.snapshot.mode == "candidates" and viewer.snapshot.labels == labels + assert viewer.snapshot.mode == "generator" and viewer.snapshot.labels == labels - # Candidates are not episodes: playing first draws starts as training does, and nothing is credited. + # Proposals are not episodes: playing first draws reset states as training does, and nothing is credited. viewer.play() assert viewer.mode == "draw" and viewer.playing for _ in range(3): viewer.update() - assert bank.episode_counts.sum() == 0 + assert reset_states.episode_counts.sum() == 0 viewer.show(0) - assert not viewer.playing and (bank.slots == 0).all() and bank.episode_counts.sum() == 0 + assert not viewer.playing and (reset_states.started_from == 0).all() and reset_states.episode_counts.sum() == 0 -def test_viser_panel_shows_the_bank_and_labels_every_world(viewer: ResetViewer): +def test_viser_panel_shows_the_reset_states_and_labels_every_world(viewer: ResetStateViewer): viser = pytest.importorskip("viser") server = viser.ViserServer(host="127.0.0.1", port=0, verbose=False) try: - panel = ViserResetPanel(viewer, server) + panel = ViserResetStatePanel(viewer, server) viewer.show(2) viewer._panels.append(panel) viewer.update() From f3a009c0f1bc024f04c8482ce1a2c1d3ac00164e Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Sun, 22 Nov 2026 13:16:22 -0800 Subject: [PATCH 16/17] Show grouped reset states in the reset viewer Per-slot statistics are per group of worlds since reset states can be grouped by object, so the table and labels index them by each world's group. --- .../envs/mdp2_reset_viewer.py | 14 +++++++------- .../test/mdp2/test_mdp2_reset_viewer.py | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_reset_viewer.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_reset_viewer.py index b58b44bf1924..7450d8d7927c 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_reset_viewer.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_reset_viewer.py @@ -38,9 +38,8 @@ class ResetStateSnapshot: mode: str slot: int # The slot that slot mode restores playing: bool - size: int # Slots per world + size: int # Slots per group of worlds num_source_states: int # Slots from the source; the others record - shared: bool world: int # The world whose reset states the table shows started_from: np.ndarray # (num_worlds,) the slot each world started from, -1 for a default reset episode_length: np.ndarray # (num_worlds,) @@ -171,12 +170,14 @@ def _reset(self, mode: str) -> None: def _snapshot(self) -> ResetStateSnapshot: states, world = self.reset_states, self.world + # Per-slot values are per group of worlds, a group per world by default, or one row if shared. + groups = np.zeros(self.env.num_envs, dtype=int) if states.shared else states.groups.cpu().numpy() def row(values: torch.Tensor) -> np.ndarray: - return (values if states.shared else values[world]).cpu().numpy() + return values.view(-1, states.size)[groups[world]].cpu().numpy() started_from = states.started_from.cpu().numpy() - rates = states.success_rate.cpu().numpy() + rates = states.success_rate.view(-1, states.size).cpu().numpy() accepted = None if self._accepted is None else self._accepted.cpu().numpy() labels = [] for w, slot in enumerate(started_from): @@ -185,7 +186,7 @@ def row(values: torch.Tensor) -> np.ndarray: elif slot < 0: labels.append("default") else: - rate = rates[slot] if states.shared else rates[w, slot] + rate = rates[groups[w], slot] labels.append(f"slot {slot} | {rate:.0%}") return ResetStateSnapshot( mode=self.mode, @@ -193,7 +194,6 @@ def row(values: torch.Tensor) -> np.ndarray: playing=self.playing, size=states.size, num_source_states=states.num_source_states, - shared=states.shared, world=world, started_from=started_from, episode_length=self.env.episode_length_buf.cpu().numpy(), @@ -215,7 +215,7 @@ def rows(snapshot: ResetStateSnapshot) -> list[tuple[str, ...]]: """Return a row per slot of the shown world's reset states: slot, kind, success, episodes, probability. The slot the world started from is marked with ``*``.""" # Generator proposals start from no slot. - current = -1 if snapshot.accepted is not None else snapshot.started_from[0 if snapshot.shared else snapshot.world] + current = -1 if snapshot.accepted is not None else snapshot.started_from[snapshot.world] return [ ( f"{slot}{' *' if slot == current else ''}", diff --git a/source/isaaclab_tasks/test/mdp2/test_mdp2_reset_viewer.py b/source/isaaclab_tasks/test/mdp2/test_mdp2_reset_viewer.py index 886b4cd11aa0..64174f78dd51 100644 --- a/source/isaaclab_tasks/test/mdp2/test_mdp2_reset_viewer.py +++ b/source/isaaclab_tasks/test/mdp2/test_mdp2_reset_viewer.py @@ -44,7 +44,7 @@ def test_viewing_pins_slots_rolls_the_generator_and_credits_nothing(viewer: Rese viewer.update() assert viewer.snapshot.mode == "slot" and viewer.snapshot.world == 3 assert (reset_states.started_from == 1).all() - torch.testing.assert_close(env.scene["robot"].data.joint_pos.torch, reset_states.states["joint_pos"][:, 1]) + torch.testing.assert_close(env.scene["robot"].data.joint_pos.torch, reset_states.states["joint_pos"][reset_states.groups, 1]) viewer.roll() accepted = ~viewer._generator.transition.terminated.torch From c45b38686102771749f53d981bf9157ea3a43966 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Sun, 22 Nov 2026 13:16:38 -0800 Subject: [PATCH 17/17] Format the reset viewer test --- source/isaaclab_tasks/test/mdp2/test_mdp2_reset_viewer.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/source/isaaclab_tasks/test/mdp2/test_mdp2_reset_viewer.py b/source/isaaclab_tasks/test/mdp2/test_mdp2_reset_viewer.py index 64174f78dd51..45c641da3227 100644 --- a/source/isaaclab_tasks/test/mdp2/test_mdp2_reset_viewer.py +++ b/source/isaaclab_tasks/test/mdp2/test_mdp2_reset_viewer.py @@ -44,7 +44,9 @@ def test_viewing_pins_slots_rolls_the_generator_and_credits_nothing(viewer: Rese viewer.update() assert viewer.snapshot.mode == "slot" and viewer.snapshot.world == 3 assert (reset_states.started_from == 1).all() - torch.testing.assert_close(env.scene["robot"].data.joint_pos.torch, reset_states.states["joint_pos"][reset_states.groups, 1]) + torch.testing.assert_close( + env.scene["robot"].data.joint_pos.torch, reset_states.states["joint_pos"][reset_states.groups, 1] + ) viewer.roll() accepted = ~viewer._generator.transition.terminated.torch