From 56122a15399f54ae47bb888d4a8aacd729475259 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 14:12:36 -0800 Subject: [PATCH 01/23] 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_experimental/isaaclab_tasks_experimental/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 cb0475c33d90..18df17cb4d55 100644 --- a/docs/source/api/lab_experimental/isaaclab_experimental.mdp2.mdp.rst +++ b/docs/source/api/lab_experimental/isaaclab_experimental.mdp2.mdp.rst @@ -27,6 +27,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 57d254b3326a..9d9b42531008 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, **op.tunables) # Tunable params at their default diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi index 240ebc92934b..7e618d10848a 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi @@ -27,6 +27,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", "body_incoming_wrench", @@ -102,6 +106,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_experimental/isaaclab_tasks_experimental/mdp2/lift_kuka_allegro/lift_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/mdp2/lift_kuka_allegro/lift_env_cfg.py index 25e5f3cdee24..b75416375040 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/mdp2/lift_kuka_allegro/lift_env_cfg.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/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_experimental/isaaclab_tasks_experimental/mdp2/lift_kuka_allegro/reset_bank.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/mdp2/lift_kuka_allegro/reset_bank.py deleted file mode 100644 index f9d087f2d9d5..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/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_experimental/test/mdp2/test_lift_kuka_allegro.py b/source/isaaclab_tasks_experimental/test/mdp2/test_lift_kuka_allegro.py index b302aceafbc5..764fc4217815 100644 --- a/source/isaaclab_tasks_experimental/test/mdp2/test_lift_kuka_allegro.py +++ b/source/isaaclab_tasks_experimental/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 @@ -30,7 +31,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") @@ -43,7 +43,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) @@ -80,8 +81,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, @@ -89,16 +90,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: @@ -235,13 +246,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 a9230a9f8a8f15e71c3b5f558a5271d1142fd25d Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 18:10:25 -0800 Subject: [PATCH 02/23] 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 e8eacee3784b8373756cc30dbc4e4eac68d7a037 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 18:10:25 -0800 Subject: [PATCH 03/23] 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 | 20 ++++++++-- .../isaaclab_experimental/mdp2/terms.py | 4 +- .../test/mdp2/test_mdp2.py | 38 +++++++++++++++++++ 4 files changed, 63 insertions(+), 5 deletions(-) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py index 8e5c1fbbee85..b8eaa0e5ae87 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py @@ -275,7 +275,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 e7096c1c0a06..9b0324ea6ad3 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py @@ -380,12 +380,19 @@ def computed(phase_ops: tuple) -> list[Step]: # Start events write the scene where their task starts; the others set up whole episodes. start_events = [op for op in ops[Phase.RESET_EVENTS] if op.start or op.entry_key is not None] reset_events = [op for op in ops[Phase.RESET_EVENTS] if not op.start and op.entry_key is None] + # An 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]} + + def restores(op: TermOp) -> bool: + return not command_fields.isdisjoint(op.writes) + if starts: scoped = [op for phase_ops in ops.values() for op in phase_ops if isinstance(op, TermOp) and op.entry_key] starts += [ *(Step(StepKind.RESET_TIMER, op, entry=True) for op in timed if op.entry_key), - *(Step(StepKind.COMPUTE, op, entry=True) for op in start_events if op.entry_key is not None), + *(Step(StepKind.COMPUTE, op, entry=True) for op in start_events if op.entry_key and not restores(op)), *(Step(StepKind.COMPUTE, op, entry=True) for op in scoped if op.phase is Phase.COMMANDS), + *(Step(StepKind.COMPUTE, op, entry=True) for op in start_events if op.entry_key and restores(op)), *(Step(StepKind.RESET_STATE, op, entry=True) for op in stateful if op.entry_key), ] @@ -393,9 +400,13 @@ def computed(phase_ops: tuple) -> list[Step]: unswitched = {op.name: replace(op, when=None, stages=()) for op in switched} # The reset events see the progress of the episode that ended; the start events of the tasks that run from the # start of the new one, after the progress restarts. - events = {"reset": [], "start": []} + events = {"reset": [], "start": [], "restore": []} pending: set[FieldSelector] = set() # Scene fields written since the last commit - for kind, event_ops in (("reset", reset_events), ("start", start_events)): + for kind, event_ops in ( + ("reset", [op for op in reset_events if not restores(op)]), + ("start", [op for op in start_events if not restores(op)]), + ("restore", [op for op in reset_events + start_events if restores(op)]), + ): for op in event_ops: if op.commit or op.commit is None and pending and _reads_stale(op, pending, schema): events[kind].append(Step(StepKind.COMMIT, op)) @@ -412,6 +423,8 @@ def computed(phase_ops: tuple) -> list[Step]: *computed(ops[Phase.QUANTITIES]), *progress, *computed(ops[Phase.TERMINATIONS] + ops[Phase.REWARDS]), + # Reset events with an update hook observe every step, after its terminations and rewards. + *(Step(StepKind.UPDATE_STATE, op) for op in ops[Phase.RESET_EVENTS] if op.update is not None), *(Step(StepKind.COMPUTE_IF_DUE, op) for op in timed if op.phase is Phase.COMMANDS), # Commands with an update hook track something every step, like a heading. *(Step(StepKind.UPDATE_STATE, op) for op in ops[Phase.COMMANDS] if op.update is not None), @@ -432,6 +445,7 @@ def computed(phase_ops: tuple) -> list[Step]: *(Step(StepKind.RESET_TIMER, unswitched.get(op.name, op)) for op in timed if op.entry_key), *events["start"], *(Step(StepKind.COMPUTE, unswitched.get(op.name, op)) for op in ops[Phase.COMMANDS]), + *events["restore"], # State restarts last, from the fields and commands of the new episode. *(Step(StepKind.RESET_STATE, unswitched.get(op.name, 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 3637424e71a6..fa12f372ef5b 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 f682c30486eb..c7f67a12988f 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2.py @@ -1269,6 +1269,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 bbc22cf34a094800b6d6f00e172f3d7e9da0b233 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 18:10:25 -0800 Subject: [PATCH 04/23] 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 7e618d10848a..16736820f0d4 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi @@ -28,8 +28,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", @@ -106,7 +110,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_experimental/test/mdp2/test_lift_kuka_allegro.py b/source/isaaclab_tasks_experimental/test/mdp2/test_lift_kuka_allegro.py index 764fc4217815..bc74695ab7ca 100644 --- a/source/isaaclab_tasks_experimental/test/mdp2/test_lift_kuka_allegro.py +++ b/source/isaaclab_tasks_experimental/test/mdp2/test_lift_kuka_allegro.py @@ -81,8 +81,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, @@ -94,9 +94,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()} @@ -255,7 +261,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"]) @@ -287,3 +293,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 d98094ab10a4ba861bb00fad99c84141f41d05fa Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 18:15:30 -0800 Subject: [PATCH 05/23] 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 f67efc5d0608eb2dc9ef89b7a9cf1023285be2ab Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 18:16:44 -0800 Subject: [PATCH 06/23] 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 16736820f0d4..414c1596472f 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi @@ -27,6 +27,7 @@ __all__ = [ "reset_joints_by_offset", "reset_joints_by_scale", "reset_root_state_uniform", + "Candidates", "FillFromCandidates", "FillFromFile", "FillFromStates", @@ -111,6 +112,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 4204c07f493003eb63a77c4fc6bde110725f07ae Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Sat, 21 Nov 2026 06:54:21 -0800 Subject: [PATCH 07/23] 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 75923d0ac0d49bb7a37c79d1dc3e3443ee20d373 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Sat, 21 Nov 2026 22:52:08 -0800 Subject: [PATCH 08/23] 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 644dfe636e46860df0a84f73bd78fbe6b71b94ea Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Sun, 22 Nov 2026 11:39:36 -0800 Subject: [PATCH 09/23] 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 414c1596472f..594a096fb8be 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi @@ -34,6 +34,7 @@ __all__ = [ "RecordStates", "ResetBank", "farthest_points", + "prototype_groups", "reset_bank", "reset_from_bank", "base_ang_vel", @@ -119,6 +120,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_experimental/isaaclab_tasks_experimental/mdp2/lift_kuka_allegro/lift_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/mdp2/lift_kuka_allegro/lift_env_cfg.py index b75416375040..b9ed41cbdc13 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/mdp2/lift_kuka_allegro/lift_env_cfg.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/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_experimental/test/mdp2/test_lift_kuka_allegro.py b/source/isaaclab_tasks_experimental/test/mdp2/test_lift_kuka_allegro.py index bc74695ab7ca..af3b5ff8dfd1 100644 --- a/source/isaaclab_tasks_experimental/test/mdp2/test_lift_kuka_allegro.py +++ b/source/isaaclab_tasks_experimental/test/mdp2/test_lift_kuka_allegro.py @@ -83,6 +83,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, @@ -303,7 +304,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 dc3398d6ec95b62230eeffa44d454011b7ba4c39 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Sun, 22 Nov 2026 13:15:16 -0800 Subject: [PATCH 10/23] 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 594a096fb8be..42616ad1d638 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi @@ -27,16 +27,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", "body_incoming_wrench", @@ -113,16 +113,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_experimental/isaaclab_tasks_experimental/mdp2/lift_kuka_allegro/lift_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/mdp2/lift_kuka_allegro/lift_env_cfg.py index b9ed41cbdc13..4945f4243ce6 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/mdp2/lift_kuka_allegro/lift_env_cfg.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/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_experimental/test/mdp2/test_lift_kuka_allegro.py b/source/isaaclab_tasks_experimental/test/mdp2/test_lift_kuka_allegro.py index af3b5ff8dfd1..6ae5947f011b 100644 --- a/source/isaaclab_tasks_experimental/test/mdp2/test_lift_kuka_allegro.py +++ b/source/isaaclab_tasks_experimental/test/mdp2/test_lift_kuka_allegro.py @@ -44,7 +44,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) @@ -53,7 +53,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)) @@ -79,11 +79,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, @@ -91,16 +91,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)) } @@ -108,7 +108,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) @@ -146,11 +146,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")) @@ -247,13 +247,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 = {} @@ -262,12 +262,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) @@ -277,8 +277,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(): @@ -297,38 +297,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 3227f5534fd3fbb0027cd80db35916f8e8f0830c Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Mon, 23 Nov 2026 21:08:47 -0800 Subject: [PATCH 11/23] Address review comments on MDP2 reset states - Leave a world's reset as the earlier events wrote it when the sampler rejects its pinned slot, instead of gathering its previous slot. - Shift only world-frame poses (scene transform fields named *_w) by the environment origins, so local ones such as default_root_pose stay; and shift poses with more than one per world, such as of bodies. - Save the labels that groups were numbered from, such as prototype IDs, and refuse to load states of other groups. - Validate FromTask's sizes before its generator runs startup events, use no outcome history for uniform draws, keep the farthest-point helper private and describe it as greedy, and type the hooks' inputs. - Tests: drop unused Torch generator terms and the uniqueness check, reset once to check isolation, and compare fresh samplers across backends instead of copying their private buffers. --- .../mdp2/mdp/__init__.pyi | 2 - .../mdp2/mdp/reset_states.py | 157 +++++++++++++----- .../test/mdp2/test_mdp2_reset_states.py | 35 ++-- .../test/mdp2/test_lift_kuka_allegro.py | 18 +- 4 files changed, 143 insertions(+), 69 deletions(-) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi index 42616ad1d638..413ebf2c82d5 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi @@ -33,7 +33,6 @@ __all__ = [ "FromTensors", "RecordVisited", "ResetStates", - "farthest_points", "prototype_groups", "get_reset_states", "reset_to_states", @@ -119,7 +118,6 @@ from .reset_states import ( FromTensors, RecordVisited, ResetStates, - farthest_points, prototype_groups, get_reset_states, reset_to_states, 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..566aa74a20ac 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py @@ -24,7 +24,7 @@ from __future__ import annotations import functools -from collections.abc import Callable, Mapping +from collections.abc import Callable, Collection, Mapping from dataclasses import dataclass from pathlib import Path from typing import Any @@ -80,9 +80,12 @@ class FromFile: def __call__(self, ctx: TermContext, groups: torch.Tensor | None) -> dict[str, torch.Tensor]: saved = torch.load(self.path, map_location=ctx.rng.device) - held = saved["groups"] + # The labels the groups were numbered from, such as prototype IDs, so that states fit the same objects. + held, labels = saved["groups"], ctx.cache.get("group_labels") 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)}.") + if labels is not None and not torch.equal(saved.get("labels", labels), labels): + raise ValueError(f"{self.path} holds states of other groups, such as other objects, than the event's.") return saved["states"] @@ -101,7 +104,7 @@ def prototype_groups(ctx: TermContext) -> torch.Tensor: 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] + return torch.as_tensor(layout, device=ctx.rng.device) class StateGenerator: @@ -152,11 +155,11 @@ 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 + if self.num_states < 1 or self.oversample_factor < 1.0: + raise ValueError("FromTask must harvest at least as many states as it keeps, and keep at least one.") 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 generator.field(ctx.selectors[name]) @@ -164,9 +167,9 @@ def __call__(self, ctx: TermContext, groups: torch.Tensor | None) -> dict[str, t } if descriptor is not None: fields["descriptor"] = descriptor.torch - # Root poses are kept relative to the environment origins when the use binds them. + # World-frame 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} + poses = _world_poses(ctx) if origins is not None else set() 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) @@ -198,15 +201,15 @@ def __call__(self, ctx: TermContext, groups: torch.Tensor | None) -> dict[str, t # 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.num_states) + 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()} -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.""" +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 chosen by + greedy farthest-point selection: from the first point, each next one is the farthest from those chosen.""" 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) @@ -233,7 +236,10 @@ def __init__( sampler: ResetStateSamplerCfg, *, groups: torch.Tensor | None, + labels: torch.Tensor | None, origins: wp.array | None, + poses: Collection[str], + uniform: bool, default_reset_probability: float, record: RecordVisited | None, ) -> None: @@ -244,6 +250,8 @@ def __init__( 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 if shared + self.labels = labels # The labels the groups were numbered from, such as prototype IDs, if given + self._uniform = uniform # Uniform draws use no outcome history 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: @@ -271,9 +279,8 @@ def __init__( 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 [] - ) + # World-frame poses, which restore shifts by the origins: one per world, or more, such as of bodies. + self._poses = {name: outputs[name] for name in poses} 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) @@ -282,8 +289,7 @@ def __init__( 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() + name: wp.empty_like(value) if name in self._poses else value for name, value in self._outputs.items() } @property @@ -347,7 +353,7 @@ def skip_current_episodes(self) -> None: def save(self, path: str | Path) -> None: """Save the states, for a later run to load with :class:`FromFile`.""" - torch.save({"states": self.states, "groups": self.groups}, path) + torch.save({"states": self.states, "groups": self.groups, "labels": self.labels}, 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.""" @@ -357,10 +363,18 @@ def restore(self, mask: wp.array, rng: wp.array, succeeded: wp.array | None) -> [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) + success = None if self._uniform else succeeded + self.sampler.reset(mask, success=success, valid=self._valid, state_ids=self._requests, rng=rng) + # A rejected request leaves the world's reset as the earlier events wrote it. + wp.launch( + _skip_invalid, + mask.shape, + [self.sampler.invalid_requests.warp, self._writes, self._restored, self._credit], + device=mask.device, + ) 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._writes, self._origins, pose, pose, 1.0], device=mask.device) + for pose in self._poses.values(): + _shift(self._writes, self._origins, pose, pose, 1.0) 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.""" @@ -383,14 +397,8 @@ def record(self, rng: wp.array, terminated: wp.array, record_if: wp.array | None ], 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, - ) + for name, pose in self._poses.items(): + _shift(self._recording, self._origins, pose, self._record_values[name], -1.0) 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) @@ -418,7 +426,8 @@ def _init( ) -> None: """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()) + poses = _world_poses(ctx) + has_poses = bool(poses) if shared and groups is not None: 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: @@ -434,11 +443,13 @@ def _init( 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 + labels = None 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] + # Number the groups 0, 1, ..., so that any labels work; the labels are saved with the states. + labels = ctx.cache["group_labels"] = torch.as_tensor(groups(ctx), device=device) + group = torch.unique(labels, 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: @@ -461,7 +472,10 @@ def _init( outputs, sampler if sampler is not None else ResetStateSamplerCfg(history_length=1, scores=[]), groups=group, + labels=labels, origins=None if origins is None else wp.from_torch(origins.contiguous(), dtype=wp.vec3f), + poses=poses if origins is not None else (), + uniform=sampler is None, default_reset_probability=default_reset_probability, record=record, ) @@ -476,11 +490,23 @@ def _init( 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: +def _restore( + mask: wp.array | torch.Tensor, + cache: dict[str, Any], + rng: wp.array | torch.Tensor, + succeeded: wp.array | torch.Tensor | None = None, + **_: Any, +) -> None: 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_if: Any = None, **_: Any) -> None: +def _record( + cache: dict[str, Any], + rng: wp.array | torch.Tensor, + terminated: wp.array | torch.Tensor | None = None, + record_if: wp.array | torch.Tensor | None = 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)) @@ -506,8 +532,10 @@ def _record(cache: dict, rng: Any, terminated: Any = None, record_if: Any = None - ``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_if``, a quantity above 0.5 where a state may be recorded. +``env_origins``, which stores the world-frame poses (scene fields ``*_w`` of transforms, such as +``root_link_pose_w``) relative to the environment origins, while local ones, such as ``default_root_pose``, stay; +``terminated`` (``mdp2.terminated``), 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 states and the sampler's history persist across episodes; :func:`get_reset_states` returns them. @@ -566,6 +594,20 @@ def _choose_records( credit[world] = False +@wp.kernel +def _skip_invalid( + invalid: wp.array(dtype=wp.bool), + writes: wp.array(dtype=wp.bool), + restored: wp.array(dtype=wp.bool), + credit: wp.array(dtype=wp.bool), +): + world = wp.tid() + if invalid[world]: + writes[world] = False + restored[world] = False + credit[world] = False + + @wp.kernel def _shift_poses( mask: wp.array(dtype=wp.bool), @@ -581,18 +623,57 @@ def _shift_poses( ) +@wp.kernel +def _shift_pose_rows( + mask: wp.array(dtype=wp.bool), + origins: wp.array(dtype=wp.vec3f), + pose: wp.array2d(dtype=wp.transformf), + out: wp.array2d(dtype=wp.transformf), + sign: float, +): + world, k = wp.tid() + if mask[world]: + out[world, k] = wp.transformf( + wp.transform_get_translation(pose[world, k]) + sign * origins[world], + wp.transform_get_rotation(pose[world, k]), + ) + + +def _shift(mask: wp.array, origins: wp.array, pose: wp.array, out: wp.array, sign: float) -> None: + """Shift the masked worlds' poses by ``sign`` times their origins into ``out``: one pose per world, or more, such + as of bodies, whose arrays are then contiguous.""" + if pose.ndim == 1: + wp.launch(_shift_poses, pose.shape, [mask, origins, pose, out, sign], device=pose.device) + return + rows = (pose.shape[0], -1) + pose, out = pose.reshape(rows), out.reshape(rows) + wp.launch(_shift_pose_rows, pose.shape, [mask, origins, pose, out, sign], device=pose.device) + + 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): + if selector.scene: return ctx.scene_data.data(selector.entity, selector.field).warp return wp.from_torch(ctx.outputs[name]) +def _world_poses(ctx: TermContext) -> set[str]: + """Return the outputs that are poses in the world frame: scene fields of transforms named ``*_w``.""" + return { + name + for name, selector in ctx.selectors.items() + if name in ctx.outputs + and selector.scene + and selector.field.endswith("_w") + and _warp_view(ctx, name).dtype == wp.transformf + } + + def _minus_origin(pose: torch.Tensor, origins: torch.Tensor) -> torch.Tensor: - """Return root poses of shape ``(num_worlds, 7)`` relative to the environment origins.""" + """Return poses of shape ``(num_worlds, ..., 7)`` relative to the environment origins.""" relative = pose.clone() - relative[:, :3] -= origins + relative[..., :3] -= origins.view(len(origins), *(1,) * (pose.dim() - 2), 3) return relative 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 f7b32250afc4..5ad9c9235e47 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py @@ -67,13 +67,8 @@ def _draw(world: int, joint_pos: wp.array2d(dtype=float), object_pose_w: wp.arra 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) +# Generator tasks compile with Warp only. +draw = mdp2.Term(warp=_draw, random=True) @wp.func @@ -81,7 +76,7 @@ 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) +outside = mdp2.Term(warp=_outside) @wp.func @@ -129,7 +124,7 @@ def test_generator_gives_each_world_valid_states_and_restore_only_reset_worlds() reset_states = mdp.get_reset_states(state) stored = reset_states.states["joint_pos"][..., 0].cpu() - assert stored.shape == (8, 4) and (stored.abs() <= 0.5).all() and len(stored.unique()) == 32 + assert stored.shape == (8, 4) and (stored.abs() <= 0.5).all() reset(task_mdp, state, [True] * 8) slots = reset_states.started_from.cpu() @@ -137,8 +132,7 @@ def test_generator_gives_each_world_valid_states_and_restore_only_reset_worlds() 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) + reset(task_mdp, state, [True] + [False] * 7) assert torch.equal(joint_pos(scene)[1:], before[1:]) @@ -174,7 +168,7 @@ def test_grouped_states_come_from_and_credit_the_worlds_of_each_group(): ) reset_states = mdp.get_reset_states(state) stored = reset_states.states["joint_pos"][..., 0] - assert stored.shape == (2, 4) and len(stored.unique()) == 8 + assert stored.shape == (2, 4) and (stored.abs() <= 0.5).all() transition = task_mdp.transition() for _ in range(4): @@ -265,6 +259,11 @@ def test_default_resets_keep_the_earlier_events_and_are_not_credited(): reset(task_mdp, state, [True] * 4) assert joint_pos(scene)[0] == reset_states.states["joint_pos"][0, 5, 0] and (joint_pos(scene)[1:] == 9.0).all() + reset_states.pin(torch.tensor([99, -1, -1, -1])) # a slot out of range leaves the reset unchanged + joint_pos(scene).fill_(9.0) + reset(task_mdp, state, [True] * 4) + assert (joint_pos(scene) == 9.0).all() and reset_states.started_from[0] == -1 + def test_saved_states_load_in_later_runs_with_the_same_worlds(tmp_path): scene = Scene(num_worlds=4) @@ -278,6 +277,18 @@ def test_saved_states_load_in_later_runs_with_the_same_worlds(tmp_path): with pytest.raises(ValueError, match="holds reset states of 4 worlds"): build(Scene(num_worlds=2), source=mdp.FromFile(path)) + # Groups keep the labels they were numbered from, such as the object each world spawned. + inputs = {"succeeded": mdp2.quantities.success, "env_origins": scene_entity.env_origins} + + def grouped(source, labels): + return build(Scene(num_worlds=4), source=source, groups=lambda ctx: torch.tensor(labels), inputs=inputs) + + _, state = grouped(mdp.FromTask(RESET_STATE_GENERATOR, num_states=3), [5, 5, 7, 7]) + mdp.get_reset_states(state).save(path) + grouped(mdp.FromFile(path), [5, 5, 7, 7]) + with pytest.raises(ValueError, match="other groups"): + grouped(mdp.FromFile(path), [5, 5, 8, 8]) + @wp.func def _sample_goal(world: int, command: wp.array(dtype=float), rng: wp.int32): diff --git a/source/isaaclab_tasks_experimental/test/mdp2/test_lift_kuka_allegro.py b/source/isaaclab_tasks_experimental/test/mdp2/test_lift_kuka_allegro.py index 6ae5947f011b..a3c1453405ce 100644 --- a/source/isaaclab_tasks_experimental/test/mdp2/test_lift_kuka_allegro.py +++ b/source/isaaclab_tasks_experimental/test/mdp2/test_lift_kuka_allegro.py @@ -94,19 +94,6 @@ def stored_and_scene_state(env: MDP2RLEnv, state: mdp2.MDPState) -> dict[str, tu 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 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", reset_states.sampler), ("reset_states", reset_states)) - 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()} - - 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 states.""" env = scenario.env @@ -253,14 +240,11 @@ def test_step_replays_as_one_graph_with_curriculum_and_reset_states(scenario: Si env = scenario.env assert env.mdp.is_fully_capturable and env.is_captured and env.num_graphs == 1 - # Both backends draw the same stored state for every world from the same sampler state, and restore it. + # Freshly built, both backends draw the same stored state for every world, 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] = mdp2.mdp.get_reset_states(state).sampler.indices.torch.clone() for name, (stored, restored) in stored_and_scene_state(env, state).items(): From 9be22ec1d02edfe1e2bfa693dfc8a945b3b63412 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 26 Nov 2026 22:28:31 -0800 Subject: [PATCH 12/23] Move the Kuka lift reset changelog to the experimental tasks package --- .../changelog.d/mdp2-resets.changed.rst | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename source/{isaaclab_tasks => isaaclab_tasks_experimental}/changelog.d/mdp2-resets.changed.rst (100%) diff --git a/source/isaaclab_tasks/changelog.d/mdp2-resets.changed.rst b/source/isaaclab_tasks_experimental/changelog.d/mdp2-resets.changed.rst similarity index 100% rename from source/isaaclab_tasks/changelog.d/mdp2-resets.changed.rst rename to source/isaaclab_tasks_experimental/changelog.d/mdp2-resets.changed.rst From 366232a5bb27bfb30ff0ae1b62121d1efbf2763c Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 26 Nov 2026 22:37:20 -0800 Subject: [PATCH 13/23] Restore commands after their task starts mid-episode as at resets Start events that write a command of their task run after the task's commands resample on entry too, as reset events that write commands do at resets. --- .../isaaclab_experimental/mdp2/plan.py | 2 ++ .../isaaclab_experimental/test/mdp2/test_mdp2.py | 16 ++++++++++++++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py index 9b0324ea6ad3..ddbcee8af368 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py @@ -334,6 +334,8 @@ def build_plan( ran when it started. Ops with ``when`` switch on or off at the same point, and in ``observe`` for new episodes; ``reset`` prepares them in all the worlds of their task. ``reset`` runs the reset events, which see the progress of the episode that ended, before the tasks restart, and then the start events of the tasks that run from the start. + Events that write a command run after the commands resample, also when a task starts, so that their values stand; + they see the restarted progress. With tunable values, it first applies the values tuned for it. """ timed = [op for op in ops[Phase.COMMANDS] + ops[Phase.INTERVAL_EVENTS] if op.timer is not None] diff --git a/source/isaaclab_experimental/test/mdp2/test_mdp2.py b/source/isaaclab_experimental/test/mdp2/test_mdp2.py index c7f67a12988f..b4e4faba0cf1 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2.py @@ -1279,8 +1279,8 @@ 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) +def count_steps_torch(steps, mask): + steps.add_(1.0 if mask is None else mask.float()) pin_command = mdp2.Term( @@ -1306,6 +1306,18 @@ def test_reset_events_that_write_commands_override_the_resample_and_observe_ever mdp2.evaluate(mdp, state, transition) assert state.arrays[mdp2.term_state("events.pin", "steps")].torch.tolist() == [3.0, 3.0] + # A start event that writes its task's command also stands when the task starts mid-episode. + command = mdp2.FieldSelector("commands", "second.count", scene=False) + pin = mdp2.Event(pin_command, outputs={"command": command}, mode=mdp2.EventMode.START) + second = mdp2.TaskCfg( + commands={"count": mdp2.Command(drifting_count, params={"step": 0.0})}, + events={"pin": pin}, + done=mdp2.quantities.b, + ) + sequence = mdp2.sequence(first=mdp2.TaskCfg(done=mdp2.quantities.a), second=second) + history = check_progress(mdp2.compose(mdp2.TaskCfg(quantities=above("a", "b")), sequence), [[0, 0], [1, 0], [1, 0]]) + assert [step[str(command)].tolist() for step in history] == [[0.0], [7.0], [7.0]] + def test_library_commands(): """Commands stay in their ranges, agree across backends, and generated_commands observes them.""" From e9d65dcdeaf167e997cf28c6f75b0f1c66074824 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 26 Nov 2026 22:37:20 -0800 Subject: [PATCH 14/23] Credit only ended episodes and record only in the worlds of the reset use The reset event latches which worlds' episodes ended at their last step, from the terminated and time_out inputs, and credits only those, so manual resets mid-episode credit nothing and skip_current_episodes is gone. Recording follows the mask of the worlds where its use runs. The sampler draws for -1 requests only with sample_unrequested, so existing callers keep -1 as an invalid request. --- docs/source/how-to/reset_state_buffers.rst | 15 ++- .../changelog.d/mdp2-resets.added.rst | 3 + .../changelog.d/mdp2-resets.changed.rst | 3 - .../envs/reset/reset_state_sampler.py | 16 ++- .../test/envs/test_reset_state_sampler.py | 10 +- .../changelog.d/mdp2-resets.added.rst | 6 +- .../mdp2/mdp/reset_states.py | 98 +++++++++++++------ .../test/mdp2/test_mdp2_reset_states.py | 76 ++++++++++---- .../mdp2/lift_kuka_allegro/lift_env_cfg.py | 7 +- .../test/mdp2/test_lift_kuka_allegro.py | 1 - 10 files changed, 166 insertions(+), 69 deletions(-) delete mode 100644 source/isaaclab/changelog.d/mdp2-resets.changed.rst diff --git a/docs/source/how-to/reset_state_buffers.rst b/docs/source/how-to/reset_state_buffers.rst index cadadf91bf1d..7ee05c068159 100644 --- a/docs/source/how-to/reset_state_buffers.rst +++ b/docs/source/how-to/reset_state_buffers.rst @@ -231,7 +231,11 @@ which MDP2 commits. The outputs are the state: any writable scene fields. "reset": mdp2.Event( mdp.reset_to_states, - inputs={"succeeded": mdp2.quantities.success}, + inputs={ + "succeeded": mdp2.quantities.success, + "terminated": mdp2.terminated, + "time_out": mdp2.time_out, + }, outputs={"joint_pos": robot.joint_pos, "object_pose_w": target.root_link_pose_w}, params={ "source": mdp.FromTask(RESET_STATE_GENERATOR, num_states=16), @@ -244,8 +248,8 @@ which MDP2 commits. The outputs are the state: any writable scene fields. ``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. +* ``sampler`` weighs states by recent success; ``None`` draws uniformly. Binding ``succeeded``, + with ``terminated`` and ``time_out``, credits each ended episode to the state it started from. * ``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. @@ -278,6 +282,7 @@ its own reset states: inputs={ "succeeded": mdp2.quantities.success, "terminated": mdp2.terminated, # states that end the episode are not recorded + "time_out": mdp2.time_out, # with terminated, only ended episodes are credited "record_if": mdp2.quantities.lifted, # optional: record only where above 0.5 }, outputs={**robot_state, **object_state}, @@ -315,8 +320,8 @@ within each world's reset states. reset_states.save("reset_states.pt") # load in a later run with mdp.FromFile("reset_states.pt") 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 +during evaluation. Only episodes that ended are credited, so resetting worlds by hand mid-episode +credits nothing. 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: diff --git a/source/isaaclab/changelog.d/mdp2-resets.added.rst b/source/isaaclab/changelog.d/mdp2-resets.added.rst index 47d094f3ae7b..471fac078123 100644 --- a/source/isaaclab/changelog.d/mdp2-resets.added.rst +++ b/source/isaaclab/changelog.d/mdp2-resets.added.rst @@ -2,3 +2,6 @@ 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 ``sample_unrequested`` to :meth:`~isaaclab.envs.reset.ResetStateSampler.reset`, with which a ``state_ids`` + request of -1 draws from the scores for that environment, so that one captured reset can replay some environments + and sample the others. diff --git a/source/isaaclab/changelog.d/mdp2-resets.changed.rst b/source/isaaclab/changelog.d/mdp2-resets.changed.rst deleted file mode 100644 index 5d946b57cb8e..000000000000 --- a/source/isaaclab/changelog.d/mdp2-resets.changed.rst +++ /dev/null @@ -1,3 +0,0 @@ -* 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/isaaclab/envs/reset/reset_state_sampler.py b/source/isaaclab/isaaclab/envs/reset/reset_state_sampler.py index 7e4e347978cc..eead87a03548 100644 --- a/source/isaaclab/isaaclab/envs/reset/reset_state_sampler.py +++ b/source/isaaclab/isaaclab/envs/reset/reset_state_sampler.py @@ -167,6 +167,7 @@ def reset( 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, + sample_unrequested: bool = False, ) -> ProxyArray: """Record previous outcomes and assign starts for selected environments. @@ -183,11 +184,12 @@ 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. A request of -1 - samples from the scores for that environment. + 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. + sample_unrequested: Whether a request of -1 in ``state_ids`` samples from the scores for that + environment rather than being invalid. Returns: Borrowed persistent full-environment ID assignments. Initially unassigned environments contain -1. @@ -199,7 +201,7 @@ def reset( if state_ids is None: self.invalid_requests.warp.zero_() else: - self._resolve_requested_indices(selection, state_ids) + self._resolve_requested_indices(selection, state_ids, sample_unrequested) # Credit the old assignments, then score and select their replacements. seeds = None if rng is not None: @@ -268,7 +270,9 @@ def forget( device=self.device, ) - def _resolve_requested_indices(self, selection: wp.array, state_ids: wp.array | ProxyArray | torch.Tensor) -> None: + def _resolve_requested_indices( + self, selection: wp.array, state_ids: wp.array | ProxyArray | torch.Tensor, sample_unrequested: bool + ) -> None: """Resolve explicit catalog labels before any previous outcomes are credited.""" requests = self._input(state_ids, self.num_envs) if requests.dtype not in (wp.int32, wp.int64): @@ -284,6 +288,7 @@ def _resolve_requested_indices(self, selection: wp.array, state_ids: wp.array | self._env_group_ids, self._group_size, self._dense_ids, + sample_unrequested, self._requested_indices, self.invalid_requests.warp, ], @@ -403,6 +408,7 @@ def _resolve_requests( env_group_ids: wp.array(dtype=wp.int32), group_size: int, dense: bool, + sample_unrequested: bool, requested_indices: wp.array(dtype=wp.int32), invalid: wp.array(dtype=wp.bool), ): @@ -411,7 +417,7 @@ def _resolve_requests( requested_indices[env] = -1 if mask[env]: value = wp.int64(requested[env]) - if value == wp.int64(-1): + if sample_unrequested and value == wp.int64(-1): return index = int(-1) if dense: diff --git a/source/isaaclab/test/envs/test_reset_state_sampler.py b/source/isaaclab/test/envs/test_reset_state_sampler.py index 7f2580698d1d..a71ac558f6f7 100644 --- a/source/isaaclab/test/envs/test_reset_state_sampler.py +++ b/source/isaaclab/test/envs/test_reset_state_sampler.py @@ -254,18 +254,20 @@ def test_minus_one_requests_draw_and_forgotten_entries_restart_from_a_prior(): 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) + sampler.reset(state_ids=requests) # -1 is an invalid request by default + np.testing.assert_array_equal(sampler.invalid_requests.warp.numpy(), [True, False, True, False]) + # Opted in, worlds 0 and 2 draw within their own group; worlds 1 and 3 replay their requested entry. + sampler.reset(state_ids=requests, sample_unrequested=True) 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) + sampler.reset(success=torch.ones(4, dtype=torch.bool), state_ids=requests, sample_unrequested=True) 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) + sampler.reset(success=torch.zeros(4, dtype=torch.bool), state_ids=requests, sample_unrequested=True) np.testing.assert_allclose(sampler.success_rate.warp.numpy()[[21, 63]], [0.0, 0.5]) diff --git a/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst b/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst index 85fcf333164b..6684f322a5af 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst @@ -8,6 +8,8 @@ use's Python hooks reuse. * 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. + returns a ``ResetStates`` to inspect, pin, or save. Only episodes that ended, by the ``terminated`` and + ``time_out`` inputs, are credited, not those reset by hand. * 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. + that write commands after the commands resample, also when a task starts mid-episode, 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 566aa74a20ac..a72347fb79fe 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py @@ -240,6 +240,7 @@ def __init__( origins: wp.array | None, poses: Collection[str], uniform: bool, + credits: bool, default_reset_probability: float, record: RecordVisited | None, ) -> None: @@ -252,6 +253,7 @@ def __init__( self.groups = groups # The group of each world, None if shared self.labels = labels # The labels the groups were numbered from, such as prototype IDs, if given self._uniform = uniform # Uniform draws use no outcome history + self.tracks_steps = credits or record is not None # Whether the update hook runs each step 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: @@ -284,6 +286,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._ended = zeros(dtype=wp.bool) # the worlds whose episodes ended at their last step 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) @@ -347,10 +350,6 @@ 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, for a later run to load with :class:`FromFile`.""" torch.save({"states": self.states, "groups": self.groups, "labels": self.labels}, path) @@ -360,11 +359,23 @@ def restore(self, mask: wp.array, rng: wp.array, succeeded: wp.array | None) -> wp.launch( _choose_starts, mask.shape, - [mask, rng, self._requests, self._default, self._credit, self._valid, self._restored, self._writes], + [ + mask, + rng, + self._requests, + self._default, + self._ended, + self._credit, + self._valid, + self._restored, + self._writes, + ], device=mask.device, ) success = None if self._uniform else succeeded - self.sampler.reset(mask, success=success, valid=self._valid, state_ids=self._requests, rng=rng) + self.sampler.reset( + mask, success=success, valid=self._valid, state_ids=self._requests, rng=rng, sample_unrequested=True + ) # A rejected request leaves the world's reset as the earlier events wrote it. wp.launch( _skip_invalid, @@ -376,27 +387,41 @@ def restore(self, mask: wp.array, rng: wp.array, succeeded: wp.array | None) -> for pose in self._poses.values(): _shift(self._writes, self._origins, pose, pose, 1.0) - 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.""" + def step( + self, + mask: wp.array | None, + rng: wp.array, + terminated: wp.array, + time_out: wp.array, + record_if: wp.array | None, + ) -> None: + """Note the masked worlds whose episodes ended, and record the states of those selected into their oldest + recorded slots.""" + record = self._record wp.launch( - _choose_records, + _after_step, self.num_worlds, [ + mask, rng, terminated, + time_out, record_if, - self._record.probability, + 0.0 if record is None else record.probability, self._filled, - self._record.num_states, + 0 if record is None else record.num_states, self.size, self.sampler.indices.warp, self._cursor, + self._ended, self._credit, self._recording, self._record_rows, ], device=rng.device, ) + if record is None: + return for name, pose in self._poses.items(): _shift(self._recording, self._origins, pose, self._record_values[name], -1.0) self.sampler.forget(self._record_rows, self._recording, success_rate=self._prior) @@ -435,10 +460,13 @@ def _init( "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.num_states < 1): + if record is not None and (shared or groups is not None or record.num_states < 1): + raise ValueError("Recording needs reset states per world and at least one slot.") + credits = sampler is not None and "succeeded" in ctx.inputs + if (credits or record is not None) and not {"terminated", "time_out"} <= ctx.inputs.keys(): raise ValueError( - "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." + "Crediting or recording needs the terminated and time_out inputs (mdp2.terminated, mdp2.time_out), so" + " that only ended episodes are credited and states that end episodes are not recorded." ) if not 0.0 <= default_reset_probability <= 1.0: raise ValueError(f"default_reset_probability must be in [0, 1], got {default_reset_probability}.") @@ -476,6 +504,7 @@ def _init( origins=None if origins is None else wp.from_torch(origins.contiguous(), dtype=wp.vec3f), poses=poses if origins is not None else (), uniform=sampler is None, + credits=credits, default_reset_probability=default_reset_probability, record=record, ) @@ -483,11 +512,11 @@ def _init( # 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=reset_states.sampler.device) - rng, succeeded = _as_warp(ctx.rng), ctx.inputs.get("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_if") - reset_states.record(rng, wp.ones_like(nothing), None if when is None else _as_warp(when)) + inputs = {name: _as_warp(value) for name, value in ctx.inputs.items()} + rng = _as_warp(ctx.rng) + reset_states.restore(nothing, rng, inputs.get("succeeded")) + if reset_states.tracks_steps: + reset_states.step(nothing, rng, inputs["terminated"], inputs["time_out"], inputs.get("record_if")) def _restore( @@ -497,22 +526,24 @@ def _restore( succeeded: wp.array | torch.Tensor | None = None, **_: Any, ) -> None: - cache["reset_states"].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), _as_warp(succeeded)) -def _record( +def _step( + mask: wp.array | torch.Tensor | None, cache: dict[str, Any], rng: wp.array | torch.Tensor, terminated: wp.array | torch.Tensor | None = None, + time_out: wp.array | torch.Tensor | None = None, record_if: wp.array | torch.Tensor | None = 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)) + if reset_states.tracks_steps: + reset_states.step(*map(_as_warp, (mask, rng, terminated, time_out, record_if))) -_hooks = Implementation(compute=_restore, update=_record) +_hooks = Implementation(compute=_restore, update=_step) 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``. @@ -534,7 +565,8 @@ def _record( Inputs: ``succeeded``, the ended episode's success, credited to the slot it started from when bound; ``env_origins``, which stores the world-frame poses (scene fields ``*_w`` of transforms, such as ``root_link_pose_w``) relative to the environment origins, while local ones, such as ``default_root_pose``, stay; -``terminated`` (``mdp2.terminated``), required to record; and ``record_if``, a quantity above 0.5 where a state +``terminated`` and ``time_out`` (``mdp2.terminated``, ``mdp2.time_out``), required to credit or record, so that only +ended episodes are credited, not those reset by hand mid-episode; 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 states and the sampler's history @@ -548,6 +580,7 @@ def _choose_starts( rng: wp.array(dtype=wp.int32), requests: wp.array(dtype=wp.int32), default_reset_probability: float, + ended: wp.array(dtype=wp.bool), credit: wp.array(dtype=wp.bool), valid: wp.array(dtype=wp.bool), restored: wp.array(dtype=wp.bool), @@ -557,8 +590,9 @@ def _choose_starts( 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] + # The episode counts if it ended, from a slot that was not recorded over since. + valid[world] = credit[world] and ended[world] + ended[world] = False restore = requests[world] >= 0 or wp.randf(wp.rand_init(rng[world], 1)) >= default_reset_probability restored[world] = restore writes[world] = restore @@ -566,9 +600,11 @@ def _choose_starts( @wp.kernel -def _choose_records( +def _after_step( + mask: wp.array(dtype=wp.bool), rng: wp.array(dtype=wp.int32), terminated: wp.array(dtype=wp.bool), + time_out: wp.array(dtype=wp.bool), record_if: wp.array(dtype=wp.float32), probability: float, first: int, @@ -576,11 +612,17 @@ def _choose_records( size: int, indices: wp.array(dtype=wp.int32), cursor: wp.array(dtype=wp.int32), + ended: wp.array(dtype=wp.bool), credit: wp.array(dtype=wp.bool), recording: wp.array(dtype=wp.bool), rows: wp.array(dtype=wp.int32), ): world = wp.tid() + if mask and not mask[world]: + ended[world] = False + recording[world] = False + return + ended[world] = terminated[world] or time_out[world] record = not terminated[world] and wp.randf(wp.rand_init(rng[world], 2)) < probability if record_if: record = record and record_if[world] > 0.5 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 5ad9c9235e47..9adca2cbd015 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py @@ -86,18 +86,39 @@ 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) + +@wp.func +def _always(world: int, joint_pos: wp.array2d(dtype=float)) -> bool: + return True + + +always = mdp2.Term(torch=lambda joint_pos: torch.ones_like(joint_pos[:, 0], dtype=torch.bool), warp=_always) + 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 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_to_states, inputs=inputs, outputs=outputs, params=params)}, +ENDED = {"terminated": mdp2.terminated, "time_out": mdp2.time_out} +CREDITED = {"succeeded": mdp2.quantities.success, **ENDED} + + +def build(scene: Scene, backend: str = "warp", worlds: int | None = None, **params) -> tuple[mdp2.MDP, mdp2.MDPState]: + """Build a task whose only reset event resets to stored states, credited by whether the joint ended positive, + in the first ``worlds`` worlds if given. Every step times out, so that each step ends the episodes.""" + inputs = params.pop("inputs", CREDITED) + resets = mdp2.TaskCfg( + events={"reset": mdp2.Event(mdp.reset_to_states, inputs=inputs, outputs=outputs, params=params)} + ) + if worlds is not None: + resets = mdp2.split(worlds={"a": worlds, "b": scene.schema.num_worlds - worlds}, a=resets, b=mdp2.TaskCfg()) + task = mdp2.compose( + mdp2.TaskCfg( + quantities={"success": mdp2.Quantity(positive, inputs={"joint_pos": robot.joint_pos})}, + terminations={"end": mdp2.Termination(always, inputs={"joint_pos": robot.joint_pos}, time_out=True)}, + ), + resets, ) builder = mdp2.MDPBuilder(scene.schema) builder.add_task(task) @@ -115,9 +136,6 @@ 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_generator_gives_each_world_valid_states_and_restore_only_reset_worlds(): scene = Scene(num_worlds=8) task_mdp, state = build(scene, source=mdp.FromTask(RESET_STATE_GENERATOR, num_states=4)) @@ -144,7 +162,7 @@ def test_shared_states_restore_poses_relative_to_each_world_origin(): scene, source=mdp.FromTensors(states), shared=True, - inputs={"succeeded": mdp2.quantities.success, "env_origins": scene_entity.env_origins}, + inputs={**CREDITED, "env_origins": scene_entity.env_origins}, ) reset(task_mdp, state, [True] * 4) @@ -164,7 +182,7 @@ def test_grouped_states_come_from_and_credit_the_worlds_of_each_group(): 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}, + inputs={**CREDITED, "env_origins": scene_entity.env_origins}, ) reset_states = mdp.get_reset_states(state) stored = reset_states.states["joint_pos"][..., 0] @@ -190,7 +208,7 @@ def test_outcomes_are_credited_to_the_state_each_episode_started_from(): "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} + inputs = {**CREDITED, "env_origins": scene_entity.env_origins} task_mdp, state = build(scene, source=mdp.FromTensors(states), shared=True, sampler=sampler, inputs=inputs) transition = task_mdp.transition() for _ in range(6): @@ -201,16 +219,17 @@ def test_outcomes_are_credited_to_the_state_each_episode_started_from(): 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 - reset_states.skip_current_episodes() # a reset by hand mid-episode credits nothing - reset(task_mdp, state, [True] * 16) - assert reset_states.episode_counts.sum() == 5 * 16 + # Only ended episodes are credited: the last step's, but not the new one reset again before a step. + for _ in range(2): + reset(task_mdp, state, [True] * 16) + assert reset_states.episode_counts.sum() == 6 * 16 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.RecordVisited(num_states=2, probability=1.0) - inputs = {**RECORDING, "record_if": mdp2.quantities.success} + inputs = {**CREDITED, "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() @@ -344,7 +363,7 @@ def test_backends_and_graph_replay_restore_and_record_the_same_states(): sampler=ResetStateSamplerCfg(history_length=4, scores=[BetaSamplingScoreCfg(target=0.5)]), default_reset_probability=0.25, record=mdp.RecordVisited(num_states=4, probability=0.5), - inputs=RECORDING, + inputs=CREDITED, ) reset_states = mdp.get_reset_states(state) mask = ProxyArray(wp.zeros(32, dtype=wp.bool, device=DEVICE)) @@ -379,12 +398,29 @@ def test_backends_and_graph_replay_restore_and_record_the_same_states(): ({"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"), ( - {"source": mdp.FromTask(RESET_STATE_GENERATOR, num_states=2), "record": mdp.RecordVisited(2, 0.1)}, - "the terminated input", + { + "source": mdp.FromTask(RESET_STATE_GENERATOR, num_states=2), + "sampler": ResetStateSamplerCfg(scores=[]), + "inputs": {"succeeded": mdp2.quantities.success}, + }, + "the terminated and time_out inputs", ), ], - ids=["fill_misses_an_output", "shared_poses_without_origins", "recording_without_terminated"], + ids=["fill_misses_an_output", "shared_poses_without_origins", "crediting_without_ended_episodes"], ) def test_invalid_reset_states_are_rejected_at_startup(params, message): with pytest.raises(ValueError, match=message): build(Scene(num_worlds=2), **params) + + +def test_recording_runs_only_in_the_worlds_of_its_use(): + scene = Scene(num_worlds=4) + record = mdp.RecordVisited(num_states=2, probability=1.0) + source = mdp.FromTask(RESET_STATE_GENERATOR, num_states=2) + task_mdp, state = build(scene, source=source, record=record, worlds=2) + reset_states = mdp.get_reset_states(state, next(use for use in state.caches if use.endswith("events.reset"))) + before = reset_states.states["joint_pos"].clone() + joint_pos(scene).fill_(0.3) + mdp2.evaluate(task_mdp, state, task_mdp.transition()) + after = reset_states.states["joint_pos"] + assert (after[:2, 2, 0] == 0.3).all() and torch.equal(after[2:], before[2:]) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/mdp2/lift_kuka_allegro/lift_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/mdp2/lift_kuka_allegro/lift_env_cfg.py index 4945f4243ce6..a0091d44ae23 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/mdp2/lift_kuka_allegro/lift_env_cfg.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/mdp2/lift_kuka_allegro/lift_env_cfg.py @@ -458,7 +458,12 @@ class KukaAllegroLiftPhysicsCfg(PresetCfg): # share their success statistics. "reset": mdp2.Event( mdp.reset_to_states, - inputs={"succeeded": mdp2.quantities.success, "env_origins": scene.env_origins}, + inputs={ + "succeeded": mdp2.quantities.success, + "terminated": mdp2.terminated, + "time_out": mdp2.time_out, + "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. diff --git a/source/isaaclab_tasks_experimental/test/mdp2/test_lift_kuka_allegro.py b/source/isaaclab_tasks_experimental/test/mdp2/test_lift_kuka_allegro.py index a3c1453405ce..955b3e276a62 100644 --- a/source/isaaclab_tasks_experimental/test/mdp2/test_lift_kuka_allegro.py +++ b/source/isaaclab_tasks_experimental/test/mdp2/test_lift_kuka_allegro.py @@ -287,7 +287,6 @@ def test_recorded_states_restore_through_the_simulation(scenario: SimpleNamespac event = task.events["reset"] task.events["reset"] = dataclasses.replace( event, - inputs={**event.inputs, "terminated": mdp2.terminated}, # Recording needs reset states per world. params={**event.params, "groups": None, "record": mdp2.mdp.RecordVisited(num_states=1, probability=1.0)}, ) From 0e2c1e03fcdeb02156e3fd38f909e203158b1d89 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 26 Nov 2026 22:41:59 -0800 Subject: [PATCH 15/23] Test manual resets after unended steps and register experimental tasks for the reset state generator A reset after steps that did not end the episodes credits nothing, recording follows its worlds on both backends, and generate_reset_states.py imports isaaclab_tasks_experimental, where the MDP2 lift task now lives. --- scripts/tools/generate_reset_states.py | 1 + .../mdp2/mdp/reset_states.py | 8 ++-- .../test/mdp2/test_mdp2_reset_states.py | 41 +++++++++++++------ 3 files changed, 33 insertions(+), 17 deletions(-) diff --git a/scripts/tools/generate_reset_states.py b/scripts/tools/generate_reset_states.py index 745894cb8e54..7da2024e71e7 100644 --- a/scripts/tools/generate_reset_states.py +++ b/scripts/tools/generate_reset_states.py @@ -18,6 +18,7 @@ import sys import gymnasium as gym +import isaaclab_tasks_experimental # noqa: F401 from isaaclab_experimental.mdp2 import mdp from isaaclab.app import add_launcher_args, launch_simulation 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 a72347fb79fe..d25e8e6c38df 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py @@ -512,11 +512,11 @@ def _init( # 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=reset_states.sampler.device) - inputs = {name: _as_warp(value) for name, value in ctx.inputs.items()} - rng = _as_warp(ctx.rng) - reset_states.restore(nothing, rng, inputs.get("succeeded")) + rng, inputs = _as_warp(ctx.rng), ctx.inputs + reset_states.restore(nothing, rng, _as_warp(inputs.get("succeeded"))) if reset_states.tracks_steps: - reset_states.step(nothing, rng, inputs["terminated"], inputs["time_out"], inputs.get("record_if")) + ended = (_as_warp(inputs[name]) for name in ("terminated", "time_out")) + reset_states.step(nothing, rng, *ended, _as_warp(inputs.get("record_if"))) def _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 9adca2cbd015..62fb214dc13a 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py @@ -104,9 +104,12 @@ def _always(world: int, joint_pos: wp.array2d(dtype=float)) -> bool: CREDITED = {"succeeded": mdp2.quantities.success, **ENDED} -def build(scene: Scene, backend: str = "warp", worlds: int | None = None, **params) -> tuple[mdp2.MDP, mdp2.MDPState]: +def build( + scene: Scene, backend: str = "warp", worlds: int | None = None, ends: bool = True, **params +) -> tuple[mdp2.MDP, mdp2.MDPState]: """Build a task whose only reset event resets to stored states, credited by whether the joint ended positive, - in the first ``worlds`` worlds if given. Every step times out, so that each step ends the episodes.""" + in the first ``worlds`` worlds if given. With ``ends``, every step times out, so that each step ends the + episodes.""" inputs = params.pop("inputs", CREDITED) resets = mdp2.TaskCfg( events={"reset": mdp2.Event(mdp.reset_to_states, inputs=inputs, outputs=outputs, params=params)} @@ -116,7 +119,9 @@ def build(scene: Scene, backend: str = "warp", worlds: int | None = None, **para task = mdp2.compose( mdp2.TaskCfg( quantities={"success": mdp2.Quantity(positive, inputs={"joint_pos": robot.joint_pos})}, - terminations={"end": mdp2.Termination(always, inputs={"joint_pos": robot.joint_pos}, time_out=True)}, + terminations={"end": mdp2.Termination(always, inputs={"joint_pos": robot.joint_pos}, time_out=True)} + if ends + else {}, ), resets, ) @@ -224,6 +229,15 @@ def test_outcomes_are_credited_to_the_state_each_episode_started_from(): reset(task_mdp, state, [True] * 16) assert reset_states.episode_counts.sum() == 6 * 16 + # Nor episodes that stepped without ending, reset by hand. + task_mdp, state = build( + scene, source=mdp.FromTensors(states), shared=True, sampler=sampler, inputs=inputs, ends=False + ) + for _ in range(2): + reset(task_mdp, state, [True] * 16) + mdp2.evaluate(task_mdp, state, task_mdp.transition()) + assert mdp.get_reset_states(state).episode_counts.sum() == 0 + def test_recorded_visited_states_restore_when_pinned(): scene = Scene(num_worlds=2) @@ -414,13 +428,14 @@ def test_invalid_reset_states_are_rejected_at_startup(params, message): def test_recording_runs_only_in_the_worlds_of_its_use(): - scene = Scene(num_worlds=4) - record = mdp.RecordVisited(num_states=2, probability=1.0) - source = mdp.FromTask(RESET_STATE_GENERATOR, num_states=2) - task_mdp, state = build(scene, source=source, record=record, worlds=2) - reset_states = mdp.get_reset_states(state, next(use for use in state.caches if use.endswith("events.reset"))) - before = reset_states.states["joint_pos"].clone() - joint_pos(scene).fill_(0.3) - mdp2.evaluate(task_mdp, state, task_mdp.transition()) - after = reset_states.states["joint_pos"] - assert (after[:2, 2, 0] == 0.3).all() and torch.equal(after[2:], before[2:]) + for backend in ("torch", "warp"): + scene = Scene(num_worlds=4) + record = mdp.RecordVisited(num_states=2, probability=1.0) + source = mdp.FromTask(RESET_STATE_GENERATOR, num_states=2) + task_mdp, state = build(scene, backend, source=source, record=record, worlds=2) + reset_states = mdp.get_reset_states(state, next(use for use in state.caches if use.endswith("events.reset"))) + before = reset_states.states["joint_pos"].clone() + joint_pos(scene).fill_(0.3) + mdp2.evaluate(task_mdp, state, task_mdp.transition()) + after = reset_states.states["joint_pos"] + assert (after[:2, 2, 0] == 0.3).all() and torch.equal(after[2:], before[2:]), backend From 1ea394aad8edcd8906b05a064a7886c7539a810e Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Mon, 30 Nov 2026 06:52:51 -0800 Subject: [PATCH 16/23] Tag dumped callable instances with their type and document reset sampler caveats class_to_dict dumps a callable instance under _type with its fields. The how-to passes sample_unrequested=True where -1 requests draw, and forget() documents that environments mid-episode from a replaced entry need valid=False at their next reset. --- docs/source/how-to/reset_state_buffers.rst | 14 +++++++++----- .../changelog.d/callable-instance-dump.fixed.rst | 3 ++- .../isaaclab/envs/reset/reset_state_sampler.py | 4 +++- source/isaaclab/isaaclab/utils/dict.py | 5 ++++- source/isaaclab/test/utils/test_dict.py | 5 +++-- 5 files changed, 21 insertions(+), 10 deletions(-) diff --git a/docs/source/how-to/reset_state_buffers.rst b/docs/source/how-to/reset_state_buffers.rst index 7ee05c068159..600dc69f4b7a 100644 --- a/docs/source/how-to/reset_state_buffers.rst +++ b/docs/source/how-to/reset_state_buffers.rst @@ -131,9 +131,12 @@ the internal streams untouched. The caller advances its seeds between resets, as 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 pin some -environments and sample the others. +success rate until its next outcome. Both can be captured. Environments whose episodes started from a +replaced entry stay assigned to it: pass ``valid=False`` for them at their next reset, so that the old +state's outcome is not credited to the new one. In +``sampler.reset(..., state_ids=ids, sample_unrequested=True)``, a request of -1 draws from the scores for +that environment, so a captured reset can pin some environments and sample the others. Without +``sample_unrequested``, a request of -1 is invalid and keeps the environment's previous assignment. Configure useful practice -------------------------- @@ -262,8 +265,9 @@ which MDP2 commits. The outputs are the state: any writable scene fields. 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 +Place the event after the other reset events: it overwrites the outputs they wrote. It restores +scene fields where it is scheduled, so that later reset events and the commands that resample see +them, and commands 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 1024 reset states per object, grouped with :func:`~isaaclab_experimental.mdp2.mdp.reset_states.prototype_groups`, with the core Lift sampler settings. diff --git a/source/isaaclab/changelog.d/callable-instance-dump.fixed.rst b/source/isaaclab/changelog.d/callable-instance-dump.fixed.rst index f7d407f91cdb..99cde52bcbee 100644 --- a/source/isaaclab/changelog.d/callable-instance-dump.fixed.rst +++ b/source/isaaclab/changelog.d/callable-instance-dump.fixed.rst @@ -1,2 +1,3 @@ * 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. + configured reset state source; it is now serialized as its type, under ``_type``, and its fields, so + ``params/env.yaml`` can be saved. diff --git a/source/isaaclab/isaaclab/envs/reset/reset_state_sampler.py b/source/isaaclab/isaaclab/envs/reset/reset_state_sampler.py index eead87a03548..ab7996970766 100644 --- a/source/isaaclab/isaaclab/envs/reset/reset_state_sampler.py +++ b/source/isaaclab/isaaclab/envs/reset/reset_state_sampler.py @@ -244,7 +244,9 @@ def forget( 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`. + the next :meth:`reset`. Captured like :meth:`reset`. Environments whose episodes started from a forgotten + entry stay assigned to it: pass ``valid=False`` for them at their next :meth:`reset`, so that the old + state's outcome is not credited to the new one. Args: state_indices: Dense int32 catalog positions, shape [N]. Invalid positions are skipped. diff --git a/source/isaaclab/isaaclab/utils/dict.py b/source/isaaclab/isaaclab/utils/dict.py index c258abdd1490..b1faa792405d 100644 --- a/source/isaaclab/isaaclab/utils/dict.py +++ b/source/isaaclab/isaaclab/utils/dict.py @@ -62,9 +62,12 @@ 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 or class; a callable instance is dumped as its fields + # check if attribute is callable -- function or class elif callable(value) and hasattr(value, "__name__"): data[key] = callable_to_string(value) + # a callable instance is dumped as its type and fields + elif callable(value): + data[key] = {"_type": callable_to_string(type(value)), **class_to_dict(value)} # check if attribute is a dictionary elif hasattr(value, "__dict__") or isinstance(value, dict): data[key] = class_to_dict(value) diff --git a/source/isaaclab/test/utils/test_dict.py b/source/isaaclab/test/utils/test_dict.py index b2e5fc296ffc..a2b45b7c8ed3 100644 --- a/source/isaaclab/test/utils/test_dict.py +++ b/source/isaaclab/test/utils/test_dict.py @@ -156,7 +156,7 @@ def test_class_to_dict_serializes_enums_as_values(): 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.""" + """A callable object without a name, such as a configured sampler, should serialize to its type and fields.""" class _Fill: def __init__(self): @@ -165,7 +165,8 @@ def __init__(self): def __call__(self): pass - assert dict_utils.class_to_dict({"fill": _Fill()}) == {"fill": {"bank_size": 16}} + fill = {"_type": dict_utils.callable_to_string(_Fill), "bank_size": 16} + assert dict_utils.class_to_dict({"fill": _Fill()}) == {"fill": fill} def test_update_class_from_dict_restores_enums_from_values(): From 0182200604549aeb66aac862bf33a73be607828a Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Mon, 30 Nov 2026 06:52:51 -0800 Subject: [PATCH 17/23] Restore reset_to_states commands after the resample and keep its states across task updates Reset events run in their validated order again: reset_to_states restores scene outputs where it is scheduled and commands in its reset hook, after the commands resample. migrate carries the caches of kept uses. Sources are mutable so CLI overrides apply, Kuka play mode adjusts only FromTask, FromFile rejects unlabeled files for labeled groups, and a scored sampler requires the succeeded input. --- .../changelog.d/mdp2-resets.added.rst | 8 +- .../isaaclab_experimental/mdp2/config.py | 6 +- .../mdp2/mdp/reset_states.py | 80 ++++++++--- .../isaaclab_experimental/mdp2/plan.py | 20 +-- .../isaaclab_experimental/mdp2/runtime.py | 16 ++- .../test/mdp2/test_mdp2.py | 35 +---- .../test/mdp2/test_mdp2_reset_states.py | 132 +++++++++++++++++- .../mdp2/lift_kuka_allegro/lift_env_cfg.py | 11 +- .../test/mdp2/test_lift_kuka_allegro.py | 21 +++ 9 files changed, 241 insertions(+), 88 deletions(-) diff --git a/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst b/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst index 6684f322a5af..e97fff87967a 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst @@ -10,6 +10,8 @@ during training, ``default_reset_probability`` keeps a fraction of the default resets, and ``get_reset_states`` returns a ``ResetStates`` to inspect, pin, or save. Only episodes that ended, by the ``terminated`` and ``time_out`` inputs, are credited, not those reset by hand. -* 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, also when a task starts mid-episode, so that a restored command - stands. +* Added scheduling of reset events' ``update`` hooks once per step after the rewards. ``reset_to_states`` restores + its scene outputs where it is scheduled and its command outputs in its ``reset`` hook, after the commands resample, + so that a restored command stands. +* Added carrying the cache of the uses that both tasks have in :func:`~isaaclab_experimental.mdp2.migrate`, so that + host objects that an init hook built, such as reset states, survive a task update. diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py index b8eaa0e5ae87..8e5c1fbbee85 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py @@ -275,11 +275,7 @@ class Command(TermCfg): @dataclass class Event(TermCfg): - """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. - """ + """Configuration for an event term, which writes its ``outputs`` for the worlds selected by ``mask``.""" 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/mdp/reset_states.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py index d25e8e6c38df..94707ea91ef2 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py @@ -14,11 +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 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. +commands, which are restored after the commands resample, so that their restored value stands. 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 @@ -43,21 +43,22 @@ from ..terms import Implementation, Term -@dataclass(frozen=True) +@dataclass 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_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. + replaced first; they start as copies of the source's states, so that every slot can be drawn from the start, and + the copied states are drawn about twice as often until their copies are recorded over. 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. """ num_states: int probability: float -@dataclass(frozen=True) +@dataclass class FromTensors: """Reset states given as tensors, such as demonstrations. @@ -72,7 +73,7 @@ def __call__(self, ctx: TermContext, groups: torch.Tensor | None) -> dict[str, t return {name: value.to(ctx.rng.device) for name, value in self.states.items()} -@dataclass(frozen=True) +@dataclass class FromFile: """Reset states that :meth:`ResetStates.save` wrote, such as a separate generation run.""" @@ -84,7 +85,8 @@ def __call__(self, ctx: TermContext, groups: torch.Tensor | None) -> dict[str, t held, labels = saved["groups"], ctx.cache.get("group_labels") 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)}.") - if labels is not None and not torch.equal(saved.get("labels", labels), labels): + held_labels = saved.get("labels") + if labels is not None and (held_labels is None or not torch.equal(held_labels, labels)): raise ValueError(f"{self.path} holds states of other groups, such as other objects, than the event's.") return saved["states"] @@ -137,7 +139,7 @@ def field(self, selector: Any) -> torch.Tensor: return self.state.arrays[selector].torch -@dataclass(frozen=True) +@dataclass class FromTask: """Generate reset states by rejection sampling the reset events of a generator ``task``. @@ -236,6 +238,7 @@ def __init__( sampler: ResetStateSamplerCfg, *, groups: torch.Tensor | None, + commands: Collection[str], labels: torch.Tensor | None, origins: wp.array | None, poses: Collection[str], @@ -250,6 +253,8 @@ def __init__( filled = next(iter(states.values())).shape[0 if shared else 1] recorded = 0 if record is None else record.num_states self.num_worlds, self.shared, self.size = num_worlds, shared, filled + recorded + # Commands are restored after they resample, the scene before, so that the later reset events see it. + self.commands = tuple(name for name in outputs if name in commands) self.groups = groups # The group of each world, None if shared self.labels = labels # The labels the groups were numbered from, such as prototype IDs, if given self._uniform = uniform # Uniform draws use no outcome history @@ -268,7 +273,10 @@ def __init__( rows[name] = wp.from_torch( value.reshape(-1, *value.shape[1 if shared else 2 :]).contiguous(), dtype=outputs[name].dtype ) - self.buffer = ResetStateBuffer(rows) + scene_rows = {name: value for name, value in rows.items() if name not in self.commands} + self.buffer = ResetStateBuffer(scene_rows) if scene_rows else None + command_rows = {name: rows[name] for name in self.commands} + self.command_buffer = ResetStateBuffer(command_rows) if command_rows else None self.sampler = ResetStateSampler( sampler, num_worlds, @@ -280,7 +288,9 @@ def __init__( 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 + # Scene outputs stay bound; commands are the state's, which the hooks get. + self._outputs = {name: value for name, value in outputs.items() if name not in self.commands} + self._origins = origins # World-frame poses, which restore shifts by the origins: one per world, or more, such as of bodies. self._poses = {name: outputs[name] for name in poses} zeros = functools.partial(wp.zeros, num_worlds, device=device) @@ -300,7 +310,8 @@ def states(self) -> dict[str, torch.Tensor]: """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()} + buffers = [buffer for buffer in (self.buffer, self.command_buffer) if buffer is not None] + rows = {name: value.torch for buffer in buffers for name, value in buffer.states.items()} return ( rows if self.shared @@ -383,10 +394,16 @@ def restore(self, mask: wp.array, rng: wp.array, succeeded: wp.array | None) -> [self.sampler.invalid_requests.warp, self._writes, self._restored, self._credit], device=mask.device, ) - self.buffer.get_state(self.sampler.indices, out=self._outputs, mask=self._writes) + if self.buffer is not None: + self.buffer.get_state(self.sampler.indices, out=self._outputs, mask=self._writes) for pose in self._poses.values(): _shift(self._writes, self._origins, pose, pose, 1.0) + def restore_commands(self, commands: Mapping[str, wp.array]) -> None: + """Write the restored commands, after the commands resample, in the worlds that :meth:`restore` restored.""" + if self.command_buffer is not None: + self.command_buffer.get_state(self.sampler.indices, out=dict(commands), mask=self._writes) + def step( self, mask: wp.array | None, @@ -394,6 +411,7 @@ def step( terminated: wp.array, time_out: wp.array, record_if: wp.array | None, + commands: Mapping[str, wp.array], ) -> None: """Note the masked worlds whose episodes ended, and record the states of those selected into their oldest recorded slots.""" @@ -425,7 +443,10 @@ def step( for name, pose in self._poses.items(): _shift(self._recording, self._origins, pose, self._record_values[name], -1.0) 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) + if self.buffer is not None: + self.buffer.set_state(self._record_rows, self._record_values, mask=self._recording) + if self.command_buffer is not None: + self.command_buffer.set_state(self._record_rows, dict(commands), mask=self._recording) def _per_slot(self, values: torch.Tensor) -> torch.Tensor: return values.clone() if self.shared else values.view(self.num_groups, self.size).clone() @@ -462,6 +483,8 @@ def _init( ) if record is not None and (shared or groups is not None or record.num_states < 1): raise ValueError("Recording needs reset states per world and at least one slot.") + if sampler is not None and sampler.scores and "succeeded" not in ctx.inputs: + raise ValueError("A sampler with scores needs the succeeded input, to score the states by their outcomes.") credits = sampler is not None and "succeeded" in ctx.inputs if (credits or record is not None) and not {"terminated", "time_out"} <= ctx.inputs.keys(): raise ValueError( @@ -500,6 +523,7 @@ def _init( outputs, sampler if sampler is not None else ResetStateSamplerCfg(history_length=1, scores=[]), groups=group, + commands={name for name in outputs if not ctx.selectors[name].scene}, labels=labels, origins=None if origins is None else wp.from_torch(origins.contiguous(), dtype=wp.vec3f), poses=poses if origins is not None else (), @@ -513,10 +537,12 @@ def _init( # of no worlds. nothing = wp.zeros(ctx.num_worlds, dtype=wp.bool, device=reset_states.sampler.device) rng, inputs = _as_warp(ctx.rng), ctx.inputs + commands = {name: outputs[name] for name in reset_states.commands} reset_states.restore(nothing, rng, _as_warp(inputs.get("succeeded"))) + reset_states.restore_commands(commands) if reset_states.tracks_steps: ended = (_as_warp(inputs[name]) for name in ("terminated", "time_out")) - reset_states.step(nothing, rng, *ended, _as_warp(inputs.get("record_if"))) + reset_states.step(nothing, rng, *ended, _as_warp(inputs.get("record_if")), commands) def _restore( @@ -529,6 +555,11 @@ def _restore( cache["reset_states"].restore(_as_warp(mask), _as_warp(rng), _as_warp(succeeded)) +def _restore_commands(cache: dict[str, Any], **arguments: Any) -> None: + reset_states: ResetStates = cache["reset_states"] + reset_states.restore_commands({name: _as_warp(arguments[name]) for name in reset_states.commands}) + + def _step( mask: wp.array | torch.Tensor | None, cache: dict[str, Any], @@ -536,14 +567,15 @@ def _step( terminated: wp.array | torch.Tensor | None = None, time_out: wp.array | torch.Tensor | None = None, record_if: wp.array | torch.Tensor | None = None, - **_: Any, + **arguments: Any, ) -> None: reset_states: ResetStates = cache["reset_states"] if reset_states.tracks_steps: - reset_states.step(*map(_as_warp, (mask, rng, terminated, time_out, record_if))) + commands = {name: _as_warp(arguments[name]) for name in reset_states.commands} + reset_states.step(*map(_as_warp, (mask, rng, terminated, time_out, record_if)), commands) -_hooks = Implementation(compute=_restore, update=_step) +_hooks = Implementation(compute=_restore, update=_step, reset=_restore_commands) 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``. @@ -562,14 +594,16 @@ def _step( 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; +Inputs: ``succeeded``, the ended episode's success, credited to the slot it started from, required by a sampler +with scores; ``env_origins``, which stores the world-frame poses (scene fields ``*_w`` of transforms, such as ``root_link_pose_w``) relative to the environment origins, while local ones, such as ``default_root_pose``, stay; ``terminated`` and ``time_out`` (``mdp2.terminated``, ``mdp2.time_out``), required to credit or record, so that only ended episodes are credited, not those reset by hand mid-episode; 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 states and the sampler's history +Place it after the other reset events: it overwrites the outputs they wrote. Its commands are restored after the +commands resample, so that they stand. The states and the sampler's history persist across episodes; :func:`get_reset_states` returns them. """ diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py index ddbcee8af368..05406dc32e7b 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py @@ -334,8 +334,6 @@ def build_plan( ran when it started. Ops with ``when`` switch on or off at the same point, and in ``observe`` for new episodes; ``reset`` prepares them in all the worlds of their task. ``reset`` runs the reset events, which see the progress of the episode that ended, before the tasks restart, and then the start events of the tasks that run from the start. - Events that write a command run after the commands resample, also when a task starts, so that their values stand; - they see the restarted progress. With tunable values, it first applies the values tuned for it. """ timed = [op for op in ops[Phase.COMMANDS] + ops[Phase.INTERVAL_EVENTS] if op.timer is not None] @@ -382,19 +380,12 @@ def computed(phase_ops: tuple) -> list[Step]: # Start events write the scene where their task starts; the others set up whole episodes. start_events = [op for op in ops[Phase.RESET_EVENTS] if op.start or op.entry_key is not None] reset_events = [op for op in ops[Phase.RESET_EVENTS] if not op.start and op.entry_key is None] - # An 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]} - - def restores(op: TermOp) -> bool: - return not command_fields.isdisjoint(op.writes) - if starts: scoped = [op for phase_ops in ops.values() for op in phase_ops if isinstance(op, TermOp) and op.entry_key] starts += [ *(Step(StepKind.RESET_TIMER, op, entry=True) for op in timed if op.entry_key), - *(Step(StepKind.COMPUTE, op, entry=True) for op in start_events if op.entry_key and not restores(op)), + *(Step(StepKind.COMPUTE, op, entry=True) for op in start_events if op.entry_key is not None), *(Step(StepKind.COMPUTE, op, entry=True) for op in scoped if op.phase is Phase.COMMANDS), - *(Step(StepKind.COMPUTE, op, entry=True) for op in start_events if op.entry_key and restores(op)), *(Step(StepKind.RESET_STATE, op, entry=True) for op in stateful if op.entry_key), ] @@ -402,13 +393,9 @@ def restores(op: TermOp) -> bool: unswitched = {op.name: replace(op, when=None, stages=()) for op in switched} # The reset events see the progress of the episode that ended; the start events of the tasks that run from the # start of the new one, after the progress restarts. - events = {"reset": [], "start": [], "restore": []} + events = {"reset": [], "start": []} pending: set[FieldSelector] = set() # Scene fields written since the last commit - for kind, event_ops in ( - ("reset", [op for op in reset_events if not restores(op)]), - ("start", [op for op in start_events if not restores(op)]), - ("restore", [op for op in reset_events + start_events if restores(op)]), - ): + for kind, event_ops in (("reset", reset_events), ("start", start_events)): for op in event_ops: if op.commit or op.commit is None and pending and _reads_stale(op, pending, schema): events[kind].append(Step(StepKind.COMMIT, op)) @@ -447,7 +434,6 @@ def restores(op: TermOp) -> bool: *(Step(StepKind.RESET_TIMER, unswitched.get(op.name, op)) for op in timed if op.entry_key), *events["start"], *(Step(StepKind.COMPUTE, unswitched.get(op.name, op)) for op in ops[Phase.COMMANDS]), - *events["restore"], # State restarts last, from the fields and commands of the new episode. *(Step(StepKind.RESET_STATE, unswitched.get(op.name, op)) for op in stateful), ), diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/runtime.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/runtime.py index 358055b15106..f09b63712b82 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/runtime.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/runtime.py @@ -134,7 +134,8 @@ def migrate(previous: MDP, previous_state: MDPState, mdp: MDP, state: MDPState) uses that both have, the commands, quantities, and progress, the episode lengths, and the last actions. So do the random streams of the uses that both have, and the values that both declare :class:`~.config.Tunable`, with those waiting for the next reset, as they may have been tuned; other reward weights and params are the new task's. The - init hooks of the uses that the previous MDP did not have, or whose params changed, run, as at startup. + host objects that the Python hooks of the uses that both have keep in their cache carry over too. The init hooks of + the uses that the previous MDP did not have, or whose params changed, run, as at startup. """ for key, array in state.arrays.items(): carried = isinstance(key, FieldSelector) and not key.scene or key == "revision" @@ -153,11 +154,16 @@ def migrate(previous: MDP, previous_state: MDPState, mdp: MDP, state: MDPState) state.rng.torch[row] = previous_state.rng.torch[previous.streams.index(name)] _migrate_tuned(previous, previous_state, mdp, state) - # A use of several world configs has an op per params: one that the previous MDP had keeps its state. - uses = [(op.use, op.params) for op in previous.term_ops] + # A use of several world configs has an op per params: one that the previous MDP had keeps its state, with the + # host objects of its Python hooks, such as what its init hook built. + uses = [(op.use, op.params, op.name) for op in previous.term_ops] for op in mdp.term_ops: - if op.init is not None and (op.use, op.params) not in uses: - call_init(mdp, op, state, op.init) + name = next((old for use, params, old in uses if use == op.use and params == op.params), None) + if name is None: + if op.init is not None: + call_init(mdp, op, state, op.init) + elif op.name in state.caches: + state.caches[op.name].update(previous_state.caches.get(name, {})) def _migrate_tuned(previous: MDP, previous_state: MDPState, mdp: MDP, state: MDPState) -> None: diff --git a/source/isaaclab_experimental/test/mdp2/test_mdp2.py b/source/isaaclab_experimental/test/mdp2/test_mdp2.py index b4e4faba0cf1..8a01ed1da942 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2.py @@ -1269,11 +1269,6 @@ 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 @@ -1283,40 +1278,24 @@ def count_steps_torch(steps, mask): steps.add_(1.0 if mask is None else mask.float()) -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), +count_steps = mdp2.Term( + torch=mdp2.Implementation(compute=lambda mask: None, update=count_steps_torch), + warp=mdp2.Implementation(compute=lambda mask: None, 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.""" +"""A reset event that counts the steps it observes.""" -def test_reset_events_that_write_commands_override_the_resample_and_observe_every_step(): +def test_reset_events_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})) + builder.add_event("count", mdp2.Event(count_steps)) 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] - - # A start event that writes its task's command also stands when the task starts mid-episode. - command = mdp2.FieldSelector("commands", "second.count", scene=False) - pin = mdp2.Event(pin_command, outputs={"command": command}, mode=mdp2.EventMode.START) - second = mdp2.TaskCfg( - commands={"count": mdp2.Command(drifting_count, params={"step": 0.0})}, - events={"pin": pin}, - done=mdp2.quantities.b, - ) - sequence = mdp2.sequence(first=mdp2.TaskCfg(done=mdp2.quantities.a), second=second) - history = check_progress(mdp2.compose(mdp2.TaskCfg(quantities=above("a", "b")), sequence), [[0, 0], [1, 0], [1, 0]]) - assert [step[str(command)].tolist() for step in history] == [[0.0], [7.0], [7.0]] + assert state.arrays[mdp2.term_state("events.count", "steps")].torch.tolist() == [3.0, 3.0] def test_library_commands(): 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 62fb214dc13a..40b41579ff4b 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py @@ -322,6 +322,12 @@ def grouped(source, labels): with pytest.raises(ValueError, match="other groups"): grouped(mdp.FromFile(path), [5, 5, 8, 8]) + # States saved per world have no labels, which no labeled groups match. + _, state = build(Scene(num_worlds=4), source=mdp.FromTask(RESET_STATE_GENERATOR, num_states=3)) + mdp.get_reset_states(state).save(path) + with pytest.raises(ValueError, match="other groups"): + grouped(mdp.FromFile(path), [5, 6, 7, 8]) + @wp.func def _sample_goal(world: int, command: wp.array(dtype=float), rng: wp.int32): @@ -419,8 +425,21 @@ def test_backends_and_graph_replay_restore_and_record_the_same_states(): }, "the terminated and time_out inputs", ), + ( + { + "source": mdp.FromTask(RESET_STATE_GENERATOR, num_states=2), + "sampler": ResetStateSamplerCfg(scores=[BetaSamplingScoreCfg(target=0.5)]), + "inputs": ENDED, + }, + "needs the succeeded input", + ), + ], + ids=[ + "fill_misses_an_output", + "shared_poses_without_origins", + "crediting_without_ended_episodes", + "scores_without_outcomes", ], - ids=["fill_misses_an_output", "shared_poses_without_origins", "crediting_without_ended_episodes"], ) def test_invalid_reset_states_are_rejected_at_startup(params, message): with pytest.raises(ValueError, match=message): @@ -439,3 +458,114 @@ def test_recording_runs_only_in_the_worlds_of_its_use(): mdp2.evaluate(task_mdp, state, task_mdp.transition()) after = reset_states.states["joint_pos"] assert (after[:2, 2, 0] == 0.3).all() and torch.equal(after[2:], before[2:]), backend + + +@wp.func +def _follow_joint(world: int, command: wp.array(dtype=float), joint_pos: wp.array2d(dtype=float)): + command[world] = joint_pos[world, 0] + + +follow_joint = mdp2.Term( + torch=lambda mask, command, joint_pos: command.copy_(torch.where(mask, joint_pos[:, 0], command)), + warp=_follow_joint, +) +"""A command that takes the joint position when it resamples.""" + + +@wp.func +def _object_at_joint(world: int, joint_pos: wp.array2d(dtype=float), object_pose_w: wp.array(dtype=wp.transformf)): + object_pose_w[world] = wp.transformf(wp.vec3(joint_pos[world, 0], 0.0, 0.0), wp.quat_identity()) + + +def _object_at_joint_torch(mask, joint_pos, object_pose_w): + object_pose_w[:, 0] = torch.where(mask, joint_pos[:, 0], object_pose_w[:, 0]) + + +object_at_joint = mdp2.Term(torch=_object_at_joint_torch, warp=_object_at_joint) +"""A reset event that moves the object to the joint position along x.""" + + +def build_restoring_a_command(scene: Scene, backend: str, **params) -> tuple[mdp2.MDP, mdp2.MDPState, mdp2.TaskCfg]: + """Build a task that restores the joint position and the goal, then moves the object to the joint position, and + whose ``follow`` command takes the joint position when it resamples.""" + restore = mdp2.Event( + mdp.reset_to_states, + inputs=params.pop("inputs", {}), + outputs={"joint_pos": robot.joint_pos, "goal": mdp2.commands.goal}, + params=params, + ) + task = mdp2.TaskCfg( + commands={ + "goal": mdp2.Command(sample_goal), + "follow": mdp2.Command(follow_joint, inputs={"joint_pos": robot.joint_pos}), + }, + events={ + "reset": restore, + "object": mdp2.Event( + object_at_joint, + inputs={"joint_pos": robot.joint_pos}, + outputs={"object_pose_w": target.root_link_pose_w}, + ), + }, + ) + 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, task + + +def test_restored_commands_stand_over_the_resample_and_the_scene_restores_in_order(): + """The scene restores before the later reset events and the commands that read it; the restored command stands.""" + states = {"joint_pos": torch.tensor([[0.25]], device=DEVICE), "goal": torch.tensor([0.5], device=DEVICE)} + for backend in ("torch", "warp"): + scene = Scene(num_worlds=3) + task_mdp, state, _ = build_restoring_a_command(scene, backend, source=mdp.FromTensors(states), shared=True) + joint_pos(scene).fill_(9.0) # the end of the previous episode + reset(task_mdp, state, [True, False, True]) + assert joint_pos(scene).tolist() == [0.25, 9.0, 0.25], backend + assert scene.data("object", "root_link_pose_w").torch[:, 0].tolist() == [0.25, 0.0, 0.25], backend + assert state.arrays[mdp2.commands.follow].torch.tolist() == [0.25, 0.0, 0.25], backend + assert state.arrays[mdp2.commands.goal].torch.tolist() == [0.5, 0.0, 0.5], backend + + +def test_reset_states_carry_over_to_an_updated_task(): + """A task updated on the same scene keeps the reset states, which restore the commands of the new state.""" + for backend in ("torch", "warp"): + scene = Scene(num_worlds=2) + record = mdp.RecordVisited(num_states=1, probability=1.0) + task_mdp, state, task = build_restoring_a_command( + scene, + backend, + source=mdp.FromTask(_GOAL_GENERATOR, num_states=2), + record=record, + inputs=ENDED, + ) + reset_states = mdp.get_reset_states(state) + # The worlds record a visited state with its goal into their recorded slot. + joint_pos(scene).fill_(0.375) + state.arrays[mdp2.commands.goal].torch.fill_(1.75) + mdp2.evaluate(task_mdp, state, task_mdp.transition()) + + builder = mdp2.MDPBuilder(scene.schema) + builder.add_task(task) + updated = builder.finalize(device=DEVICE, backend=backend) + updated_state = updated.state(scene, seed=3) + mdp2.migrate(task_mdp, state, updated, updated_state) + assert mdp.get_reset_states(updated_state) is reset_states, backend + + # Episodes go on and record, then the worlds reset to the recorded slot. + mdp2.evaluate(updated, updated_state, updated.transition()) + reset_states.pin(torch.tensor([2, 2])) + joint_pos(scene).fill_(9.0) + reset(updated, updated_state, [True, True]) + assert joint_pos(scene).tolist() == [0.375, 0.375], backend + assert updated_state.arrays[mdp2.commands.goal].torch.tolist() == [1.75, 1.75], backend + + +_GOAL_GENERATOR = mdp2.TaskCfg( + commands={"goal": mdp2.Command(sample_goal)}, + events={"draw": mdp2.Event(draw, outputs=outputs)}, + terminations=RESET_STATE_GENERATOR.terminations, +) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/mdp2/lift_kuka_allegro/lift_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/mdp2/lift_kuka_allegro/lift_env_cfg.py index a0091d44ae23..371f44f778e7 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/mdp2/lift_kuka_allegro/lift_env_cfg.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/mdp2/lift_kuka_allegro/lift_env_cfg.py @@ -497,11 +497,10 @@ 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 few reset states taken as harvested: they only supply the few worlds that play. + events = {"adr": replace(adr, params=params)} 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}), - } + if isinstance(reset.params["source"], mdp.FromTask): + # As MDP1, a few generated reset states taken as harvested: they only supply the few worlds that play. + source = replace(reset.params["source"], num_states=32, oversample_factor=1.0) + events["reset"] = replace(reset, params={**reset.params, "source": source}) self.task = replace(self.task, events={**self.task.events, **events}) diff --git a/source/isaaclab_tasks_experimental/test/mdp2/test_lift_kuka_allegro.py b/source/isaaclab_tasks_experimental/test/mdp2/test_lift_kuka_allegro.py index 955b3e276a62..099eb2e3b331 100644 --- a/source/isaaclab_tasks_experimental/test/mdp2/test_lift_kuka_allegro.py +++ b/source/isaaclab_tasks_experimental/test/mdp2/test_lift_kuka_allegro.py @@ -280,6 +280,27 @@ def test_play_mode_starts_the_curriculum_at_its_end(): assert params["init_difficulty"] == params["max_difficulty"] and params["promotion_only"] +def test_reset_state_sources_resolve_with_overrides_and_in_play_mode(): + """The generation options override from the command line, and play mode keeps a source that does not generate.""" + from isaaclab_experimental.mdp2 import mdp + + from isaaclab_tasks.utils.hydra import resolve_task_config + + overrides = [ + f"env.task.events.reset.params.source.{name}={value}" + for name, value in (("num_states", 64), ("max_rolls", 17), ("oversample_factor", 1.0)) + ] + cfg, _ = resolve_task_config("Isaac-Lift-KukaAllegro-MDP2", None, overrides=overrides) + source = cfg.task.events["reset"].params["source"] + assert (source.num_states, source.max_rolls, source.oversample_factor) == (64, 17, 1.0) + + cfg = KukaAllegroLiftEnvCfg() + source = mdp.FromFile("reset_states.pt") + cfg.task.events["reset"].params["source"] = source + cfg.play_mode() + assert cfg.task.events["reset"].params["source"] is source + + 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 pinned.""" env = scenario.env From 22ca2e87611693309208d8b7fa346e309922de08 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Mon, 30 Nov 2026 07:00:13 -0800 Subject: [PATCH 18/23] Scope event outputs to their task's commands and guard dumps of callables without fields A subtask's reset_to_states writes its own goal, which the generator holds under the local name. Crediting reads progress before it restarts, also with a restored goal; tests cover that, start events mid-episode, and graph replay of a restored command. class_to_dict keeps callables without __dict__ as they are. --- source/isaaclab/isaaclab/utils/dict.py | 2 +- .../changelog.d/mdp2-resets.added.rst | 2 + .../isaaclab_experimental/mdp2/builder.py | 2 + .../mdp2/mdp/reset_states.py | 12 ++- .../test/mdp2/test_mdp2_reset_states.py | 99 ++++++++++++++++++- 5 files changed, 110 insertions(+), 7 deletions(-) diff --git a/source/isaaclab/isaaclab/utils/dict.py b/source/isaaclab/isaaclab/utils/dict.py index b1faa792405d..cd811f116399 100644 --- a/source/isaaclab/isaaclab/utils/dict.py +++ b/source/isaaclab/isaaclab/utils/dict.py @@ -66,7 +66,7 @@ def class_to_dict(obj: object) -> dict[str, Any]: elif callable(value) and hasattr(value, "__name__"): data[key] = callable_to_string(value) # a callable instance is dumped as its type and fields - elif callable(value): + elif callable(value) and hasattr(value, "__dict__"): data[key] = {"_type": callable_to_string(type(value)), **class_to_dict(value)} # check if attribute is a dictionary elif hasattr(value, "__dict__") or isinstance(value, dict): diff --git a/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst b/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst index e97fff87967a..285ffb010182 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst @@ -15,3 +15,5 @@ so that a restored command stands. * Added carrying the cache of the uses that both tasks have in :func:`~isaaclab_experimental.mdp2.migrate`, so that host objects that an init hook built, such as reset states, survive a task update. +* Added scoping of event outputs to the commands of the task that defines the event, as for inputs, so that a + subtask's ``reset_to_states`` restores the subtask's goal, taken from the generator's goal of the same name. diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py index 8640d087e959..a98c7f5b861d 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py @@ -1399,6 +1399,8 @@ def _scoped(cfg: object, scope: Mapping[FieldSelector, FieldSelector]) -> object if not isinstance(cfg, TermCfg): return cfg changes = {"inputs": {arg: scope.get(selector, selector) for arg, selector in cfg.inputs.items()}} + if isinstance(cfg, Event): + changes["outputs"] = {arg: scope.get(selector, selector) for arg, selector in cfg.outputs.items()} if isinstance(cfg.when, FieldSelector): changes["when"] = scope.get(cfg.when, cfg.when) if isinstance(cfg, Observation) and cfg.noise is not None and cfg.noise.scale is not None: 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 94707ea91ef2..b224cb5dcf75 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py @@ -23,6 +23,7 @@ from __future__ import annotations +import dataclasses import functools from collections.abc import Callable, Collection, Mapping from dataclasses import dataclass @@ -133,10 +134,13 @@ 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 generator samples.""" - if selector not in self.state.arrays: - raise ValueError(f"The generator task must define '{selector}', which the event restores.") - return self.state.arrays[selector].torch + """Return the proposed values of a field of the MDP, such as a command that the generator samples. A command + of a subtask, such as ``commands.pick.goal``, is the generator's command of the same name, ``commands.goal``.""" + local = dataclasses.replace(selector, field=selector.field.rpartition(".")[2]) + for key in (selector, local): + if key in self.state.arrays: + return self.state.arrays[key].torch + raise ValueError(f"The generator task must define '{local}', which the event restores.") @dataclass 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 40b41579ff4b..84d100bfee58 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py @@ -519,11 +519,19 @@ def build_restoring_a_command(scene: Scene, backend: str, **params) -> tuple[mdp def test_restored_commands_stand_over_the_resample_and_the_scene_restores_in_order(): """The scene restores before the later reset events and the commands that read it; the restored command stands.""" states = {"joint_pos": torch.tensor([[0.25]], device=DEVICE), "goal": torch.tensor([0.5], device=DEVICE)} - for backend in ("torch", "warp"): + for backend, capture in (("torch", False), ("warp", False), ("warp", True)): + if capture and not DEVICE.startswith("cuda"): + continue scene = Scene(num_worlds=3) task_mdp, state, _ = build_restoring_a_command(scene, backend, source=mdp.FromTensors(states), shared=True) joint_pos(scene).fill_(9.0) # the end of the previous episode - reset(task_mdp, state, [True, False, True]) + mask = [True, False, True] + if capture: + masks = ProxyArray(wp.array(mask, dtype=wp.bool, device=DEVICE)) + actions = ProxyArray(wp.zeros((3, 0), dtype=wp.float32, device=DEVICE)) + mdp2.CapturedMDP(task_mdp, state, task_mdp.transition(), actions, masks).reset() + else: + reset(task_mdp, state, mask) assert joint_pos(scene).tolist() == [0.25, 9.0, 0.25], backend assert scene.data("object", "root_link_pose_w").torch[:, 0].tolist() == [0.25, 0.0, 0.25], backend assert state.arrays[mdp2.commands.follow].torch.tolist() == [0.25, 0.0, 0.25], backend @@ -569,3 +577,90 @@ def test_reset_states_carry_over_to_an_updated_task(): events={"draw": mdp2.Event(draw, outputs=outputs)}, terminations=RESET_STATE_GENERATOR.terminations, ) + + +@wp.func +def _never(world: int, joint_pos: wp.array2d(dtype=float)) -> float: + return 0.0 + + +never = mdp2.Term(torch=lambda joint_pos: torch.zeros_like(joint_pos[:, 0]), warp=_never) + + +def test_stored_goals_restore_in_subtasks_and_when_their_task_starts(): + """A subtask's event restores the subtask's goal from the generator's goal, at resets and, as a start event, when + the subtask starts mid-episode.""" + + def restore(mode: mdp2.EventMode) -> mdp2.Event: + return mdp2.Event( + mdp.reset_to_states, + outputs={"joint_pos": robot.joint_pos, "goal": mdp2.commands.goal}, + params={"source": mdp.FromTask(_GOAL_GENERATOR, num_states=3)}, + mode=mode, + ) + + commands = {"goal": mdp2.Command(sample_goal)} + picks = mdp2.compose(pick=mdp2.TaskCfg(commands=commands, events={"reset": restore(mdp2.EventMode.RESET)})) + # The second task starts when the joint is positive, and restores its goal as it starts. + second = mdp2.TaskCfg( + commands=commands, events={"reset": restore(mdp2.EventMode.START)}, done=mdp2.quantities.never + ) + quantities = { + "positive": mdp2.Quantity(positive, inputs={"joint_pos": robot.joint_pos}), + "never": mdp2.Quantity(never, inputs={"joint_pos": robot.joint_pos}), + } + sequence = mdp2.compose( + mdp2.TaskCfg(quantities=quantities), + mdp2.sequence(first=mdp2.TaskCfg(done=mdp2.quantities.positive), second=second), + ) + for backend in ("torch", "warp"): + for task, path in ((picks, "pick"), (sequence, "second")): + scene = Scene(num_worlds=4) + 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) + reset_states = mdp.get_reset_states(state, f"events.{path}.reset") + reset(task_mdp, state, [True] * 4) + if path == "second": + joint_pos(scene).fill_(0.75) + mdp2.evaluate(task_mdp, state, task_mdp.transition()) + assert (reset_states.started_from >= 0).all(), (backend, path) + restored = reset_states.states["goal"][torch.arange(4), reset_states.started_from] + goal = mdp2.FieldSelector("commands", f"{path}.goal", scene=False) + assert torch.equal(state.arrays[goal].torch, restored), (backend, path) + + +def test_episodes_that_restore_a_goal_are_credited_with_their_progress(): + """The outcome is read before the progress of the ended episode restarts, also when a goal is restored.""" + states = { + "joint_pos": torch.tensor([[0.5], [-0.5]], device=DEVICE), + "goal": torch.tensor([1.5, 1.5], device=DEVICE), + } + sampler = ResetStateSamplerCfg(history_length=8, scores=[BetaSamplingScoreCfg(target=1.0)]) + event = mdp2.Event( + mdp.reset_to_states, + inputs={"succeeded": mdp2.progress.done, **ENDED}, + outputs={"joint_pos": robot.joint_pos, "goal": mdp2.commands.goal}, + params={"source": mdp.FromTensors(states), "shared": True, "sampler": sampler}, + ) + task = mdp2.TaskCfg( + commands={"goal": mdp2.Command(sample_goal)}, + quantities={"success": mdp2.Quantity(positive, inputs={"joint_pos": robot.joint_pos})}, + terminations={"end": mdp2.Termination(always, inputs={"joint_pos": robot.joint_pos}, time_out=True)}, + events={"reset": event}, + done=mdp2.quantities.success, + ) + for backend in ("torch", "warp"): + scene = Scene(num_worlds=16) + builder = mdp2.MDPBuilder(scene.schema) + builder.add_task(task) + task_mdp = builder.finalize(device=DEVICE, backend=backend) + state, transition = task_mdp.state(scene, seed=3), task_mdp.transition() + mdp2.startup(task_mdp, state) + for _ in range(6): + reset(task_mdp, state, [True] * 16) + mdp2.evaluate(task_mdp, state, transition) + success_rate = mdp.get_reset_states(state).success_rate.cpu().numpy() + np.testing.assert_allclose(success_rate, [1.0, 0.0], err_msg=backend) From 00dcd9a5a320606ab54b623feeef5eb35263c931 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Mon, 30 Nov 2026 08:43:48 -0800 Subject: [PATCH 19/23] Note the removed Kuka reset bank term as breaking in the task changelog --- .../changelog.d/mdp2-resets.minor | 0 .../changelog.d/mdp2-resets.removed.rst | 6 ++++++ 2 files changed, 6 insertions(+) create mode 100644 source/isaaclab_tasks_experimental/changelog.d/mdp2-resets.minor create mode 100644 source/isaaclab_tasks_experimental/changelog.d/mdp2-resets.removed.rst diff --git a/source/isaaclab_tasks_experimental/changelog.d/mdp2-resets.minor b/source/isaaclab_tasks_experimental/changelog.d/mdp2-resets.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_tasks_experimental/changelog.d/mdp2-resets.removed.rst b/source/isaaclab_tasks_experimental/changelog.d/mdp2-resets.removed.rst new file mode 100644 index 000000000000..23c6e57cd231 --- /dev/null +++ b/source/isaaclab_tasks_experimental/changelog.d/mdp2-resets.removed.rst @@ -0,0 +1,6 @@ +* **Breaking:** Removed the task-local ``reset_bank.py`` of ``Isaac-Lift-KukaAllegro-MDP2``, its ``reset_from_bank`` + term, and its ``bank_size``, ``history_length``, ``target_success_rate`` and ``kappa`` parameters. Use + :func:`~isaaclab_experimental.mdp2.mdp.reset_to_states` with ``source=FromTask(..., num_states=...)`` and a + :class:`~isaaclab.envs.reset.ResetStateSamplerCfg` with a + :class:`~isaaclab.envs.reset.BetaSamplingScoreCfg`, and read the reset states with + :func:`~isaaclab_experimental.mdp2.mdp.get_reset_states`. From aaa587c161cd835f1866803086a680ad7002bc84 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Mon, 30 Nov 2026 10:23:47 -0800 Subject: [PATCH 20/23] Match bound fields and worlds before carrying a use's cache across a task update --- .../changelog.d/mdp2-resets.added.rst | 5 ++-- .../isaaclab_experimental/mdp2/runtime.py | 15 ++++++---- .../test/mdp2/test_mdp2_reset_states.py | 29 +++++++++++++++++++ 3 files changed, 41 insertions(+), 8 deletions(-) diff --git a/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst b/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst index 285ffb010182..5b7bafbabfdc 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-resets.added.rst @@ -13,7 +13,8 @@ * Added scheduling of reset events' ``update`` hooks once per step after the rewards. ``reset_to_states`` restores its scene outputs where it is scheduled and its command outputs in its ``reset`` hook, after the commands resample, so that a restored command stands. -* Added carrying the cache of the uses that both tasks have in :func:`~isaaclab_experimental.mdp2.migrate`, so that - host objects that an init hook built, such as reset states, survive a task update. +* Added carrying the cache of the uses that both tasks have, with the same params, bound fields, and worlds, in + :func:`~isaaclab_experimental.mdp2.migrate`, so that host objects that an init hook built, such as reset states, + survive a task update. * Added scoping of event outputs to the commands of the task that defines the event, as for inputs, so that a subtask's ``reset_to_states`` restores the subtask's goal, taken from the generator's goal of the same name. diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/runtime.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/runtime.py index f09b63712b82..dca890bf9f7a 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/runtime.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/runtime.py @@ -23,7 +23,7 @@ from .compiled import MDP, MDPState, Transition from .config import FieldSelector from .eager import call_init -from .plan import Call +from .plan import Call, TermOp def startup(mdp: MDP, state: MDPState) -> None: @@ -135,7 +135,7 @@ def migrate(previous: MDP, previous_state: MDPState, mdp: MDP, state: MDPState) random streams of the uses that both have, and the values that both declare :class:`~.config.Tunable`, with those waiting for the next reset, as they may have been tuned; other reward weights and params are the new task's. The host objects that the Python hooks of the uses that both have keep in their cache carry over too. The init hooks of - the uses that the previous MDP did not have, or whose params changed, run, as at startup. + the uses that the previous MDP did not have, or whose params, bound fields, or worlds changed, run, as at startup. """ for key, array in state.arrays.items(): carried = isinstance(key, FieldSelector) and not key.scene or key == "revision" @@ -154,11 +154,14 @@ def migrate(previous: MDP, previous_state: MDPState, mdp: MDP, state: MDPState) state.rng.torch[row] = previous_state.rng.torch[previous.streams.index(name)] _migrate_tuned(previous, previous_state, mdp, state) - # A use of several world configs has an op per params: one that the previous MDP had keeps its state, with the - # host objects of its Python hooks, such as what its init hook built. - uses = [(op.use, op.params, op.name) for op in previous.term_ops] + # A use of several world configs has an op per params, bindings, and worlds: one that the previous MDP had keeps + # its state, with the host objects of its Python hooks, such as what its init hook built. + def bound(op: TermOp) -> tuple: + return op.use, op.params, op.inputs, op.writes, op.worlds + + uses = [(bound(op), op.name) for op in previous.term_ops] for op in mdp.term_ops: - name = next((old for use, params, old in uses if use == op.use and params == op.params), None) + name = next((old for key, old in uses if key == bound(op)), None) if name is None: if op.init is not None: call_init(mdp, op, state, op.init) 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 84d100bfee58..0d129430f431 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py @@ -572,6 +572,35 @@ def test_reset_states_carry_over_to_an_updated_task(): assert updated_state.arrays[mdp2.commands.goal].torch.tolist() == [1.75, 1.75], backend +def test_split_reset_states_of_one_use_stay_with_their_outputs_in_an_updated_task(): + """Branches of a split that share a reset event's name and params but reset different assets keep their own reset + states when the task is updated.""" + for backend in ("torch", "warp"): + scene = Scene(num_worlds=2) + scene.schema.entities["other"] = scene.schema.entities["robot"] + scene._data["other", "joint_pos"] = ProxyArray(wp.zeros((2, 1), dtype=wp.float32, device=DEVICE)) + params = {"source": mdp.FromTensors({"value": torch.tensor([[0.5]], device=DEVICE)}), "shared": True} + + def resets(entity: mdp2.Entity) -> mdp2.TaskCfg: + event = mdp2.Event(mdp.reset_to_states, outputs={"value": entity.joint_pos}, params=params) + return mdp2.TaskCfg(events={"reset": event}) + + task = mdp2.split(a=resets(robot), b=resets(mdp2.Entity("other"))) + mdps = [] + for extra in ({}, {"unrelated": mdp2.Quantity(positive, inputs={"joint_pos": robot.joint_pos})}): + builder = mdp2.MDPBuilder(scene.schema) + builder.add_task(mdp2.compose(mdp2.TaskCfg(quantities=extra), task)) + mdps.append(builder.finalize(device=DEVICE, backend=backend)) + state = mdps[0].state(scene, seed=3) + mdp2.startup(mdps[0], state) + updated_state = mdps[1].state(scene, seed=3) + mdp2.migrate(mdps[0], state, mdps[1], updated_state) + + reset(mdps[1], updated_state, [True, True]) + assert joint_pos(scene).tolist() == [0.5, 0.0], backend + assert scene.data("other", "joint_pos").torch[:, 0].tolist() == [0.0, 0.5], backend + + _GOAL_GENERATOR = mdp2.TaskCfg( commands={"goal": mdp2.Command(sample_goal)}, events={"draw": mdp2.Event(draw, outputs=outputs)}, From cb6429e78e03c1af4ad10c625497c61d52356755 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Mon, 30 Nov 2026 17:26:10 -0800 Subject: [PATCH 21/23] Compare tensor reset state sources by value and match hooks before carrying a use's cache FromTensors compares its states element by element, so a split with different tensor banks builds and a replaced bank migrates. migrate carries a use's cache only to an op with the same hooks, so a reset event swapped for reset_to_states under its name runs its init. --- .../mdp2/mdp/reset_states.py | 15 ++++- .../isaaclab_experimental/mdp2/runtime.py | 9 +-- .../test/mdp2/test_mdp2_reset_states.py | 67 +++++++++++++++++++ 3 files changed, 86 insertions(+), 5 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 b224cb5dcf75..0a241f26fa99 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/reset_states.py @@ -59,7 +59,7 @@ class RecordVisited: probability: float -@dataclass +@dataclass(eq=False) class FromTensors: """Reset states given as tensors, such as demonstrations. @@ -73,6 +73,19 @@ class FromTensors: 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()} + def __eq__(self, other: object) -> bool: + # Equal states, element by element, as the builder and migrate compare params. + if not isinstance(other, FromTensors): + return NotImplemented + mine, theirs = self.states, other.states + return mine.keys() == theirs.keys() and all( + mine[name].shape == theirs[name].shape + and mine[name].dtype == theirs[name].dtype + and mine[name].device == theirs[name].device + and torch.equal(mine[name], theirs[name]) + for name in mine + ) + @dataclass class FromFile: diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/runtime.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/runtime.py index dca890bf9f7a..312fe46fa145 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/runtime.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/runtime.py @@ -135,7 +135,8 @@ def migrate(previous: MDP, previous_state: MDPState, mdp: MDP, state: MDPState) random streams of the uses that both have, and the values that both declare :class:`~.config.Tunable`, with those waiting for the next reset, as they may have been tuned; other reward weights and params are the new task's. The host objects that the Python hooks of the uses that both have keep in their cache carry over too. The init hooks of - the uses that the previous MDP did not have, or whose params, bound fields, or worlds changed, run, as at startup. + the uses that the previous MDP did not have, or whose hooks, params, bound fields, or worlds changed, run, as at + startup. """ for key, array in state.arrays.items(): carried = isinstance(key, FieldSelector) and not key.scene or key == "revision" @@ -154,10 +155,10 @@ def migrate(previous: MDP, previous_state: MDPState, mdp: MDP, state: MDPState) state.rng.torch[row] = previous_state.rng.torch[previous.streams.index(name)] _migrate_tuned(previous, previous_state, mdp, state) - # A use of several world configs has an op per params, bindings, and worlds: one that the previous MDP had keeps - # its state, with the host objects of its Python hooks, such as what its init hook built. + # A use of several world configs has an op per params, bindings, and worlds: one that the previous MDP had, with + # the same hooks, keeps its state, with the host objects of its Python hooks, such as what its init hook built. def bound(op: TermOp) -> tuple: - return op.use, op.params, op.inputs, op.writes, op.worlds + return op.use, op.params, op.inputs, op.writes, op.worlds, op.compute, op.update, op.reset, op.init uses = [(bound(op), op.name) for op in previous.term_ops] for op in mdp.term_ops: 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 0d129430f431..10a50f892e86 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py @@ -693,3 +693,70 @@ def test_episodes_that_restore_a_goal_are_credited_with_their_progress(): mdp2.evaluate(task_mdp, state, transition) success_rate = mdp.get_reset_states(state).success_rate.cpu().numpy() np.testing.assert_allclose(success_rate, [1.0, 0.0], err_msg=backend) + + +def _bank(value: float) -> mdp.FromTensors: + """Two reset states of one joint position, as a new tensor each time, so that equal banks are not the same object + and their comparison is not of single values.""" + return mdp.FromTensors({"value": torch.tensor([[value], [value]], device=DEVICE)}) + + +def _split_banks(scene: Scene, backend: str, a: float, b: float) -> mdp2.MDP: + def resets(value: float) -> mdp2.TaskCfg: + event = mdp2.Event( + mdp.reset_to_states, outputs={"value": robot.joint_pos}, params={"source": _bank(value), "shared": True} + ) + return mdp2.TaskCfg(events={"reset": event}) + + builder = mdp2.MDPBuilder(scene.schema) + builder.add_task(mdp2.split(worlds={"a": 2, "b": 2}, a=resets(a), b=resets(b))) + return builder.finalize(device=DEVICE, backend=backend) + + +def _first_branch(task_mdp: mdp2.MDP) -> str: + """The op of the reset event in the split's first branch, worlds 0 and 1.""" + return next(op.name for op in task_mdp.term_ops if op.use == "events.reset" and 0 in (op.worlds or (0,))) + + +def test_split_tensor_banks_restore_their_own_states_and_update_when_replaced(): + """Branches of a split whose reset events have different tensor banks build and restore their own states, and + replacing one bank in a running task restores the new states there while the other branch keeps its own.""" + for backend in ("torch", "warp"): + scene = Scene(num_worlds=4) + task_mdp = _split_banks(scene, backend, 0.5, 0.25) + state = task_mdp.state(scene, seed=3) + mdp2.startup(task_mdp, state) + reset(task_mdp, state, [True] * 4) + assert joint_pos(scene).tolist() == [0.5, 0.5, 0.25, 0.25], backend + kept = mdp.get_reset_states(state, _first_branch(task_mdp)) + + updated = _split_banks(scene, backend, 0.5, 0.75) + updated_state = updated.state(scene, seed=3) + mdp2.migrate(task_mdp, state, updated, updated_state) + reset(updated, updated_state, [True] * 4) + assert joint_pos(scene).tolist() == [0.5, 0.5, 0.75, 0.75], backend + assert mdp.get_reset_states(updated_state, _first_branch(updated)) is kept, backend + + +def _zero_joint(mask: torch.Tensor, value: torch.Tensor, **params) -> None: + value.masked_fill_(mask[:, None], 0.0) + + +def test_a_reset_event_replaced_by_reset_to_states_under_its_name_builds_its_states(): + """Replacing a running task's reset event by reset_to_states with the same name, bindings and params runs the new + event's init, so the next reset restores its states.""" + for backend in ("torch", "warp"): + scene = Scene(num_worlds=2) + mdps = [] + for term in (mdp2.Term(torch=_zero_joint), mdp.reset_to_states): + event = mdp2.Event(term, outputs={"value": robot.joint_pos}, params={"source": _bank(0.5), "shared": True}) + builder = mdp2.MDPBuilder(scene.schema) + builder.add_task(mdp2.TaskCfg(events={"reset": event})) + mdps.append(builder.finalize(device=DEVICE, backend=backend)) + state = mdps[0].state(scene, seed=3) + mdp2.startup(mdps[0], state) + updated_state = mdps[1].state(scene, seed=3) + mdp2.migrate(mdps[0], state, mdps[1], updated_state) + + reset(mdps[1], updated_state, [True, True]) + assert joint_pos(scene).tolist() == [0.5, 0.5], backend From 735b326125d9572a171fd6fb28431682ed3504f4 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Mon, 30 Nov 2026 17:26:11 -0800 Subject: [PATCH 22/23] Describe tensors in dumped YAML and read callable instance dumps back dump_yaml writes tensors as their shape and dtype instead of pickling them, which load_yaml cannot read. update_class_from_dict checks and drops the _type that class_to_dict adds to callable instances. --- .../callable-instance-dump.fixed.rst | 5 +++- source/isaaclab/isaaclab/utils/dict.py | 8 +++++++ source/isaaclab/isaaclab/utils/io/yaml.py | 17 ++++++++++++-- source/isaaclab/test/utils/test_dict.py | 23 +++++++++++++++++++ source/isaaclab/test/utils/test_yaml_io.py | 10 ++++++++ 5 files changed, 60 insertions(+), 3 deletions(-) diff --git a/source/isaaclab/changelog.d/callable-instance-dump.fixed.rst b/source/isaaclab/changelog.d/callable-instance-dump.fixed.rst index 99cde52bcbee..4ff4f033f832 100644 --- a/source/isaaclab/changelog.d/callable-instance-dump.fixed.rst +++ b/source/isaaclab/changelog.d/callable-instance-dump.fixed.rst @@ -1,3 +1,6 @@ * Fixed :func:`~isaaclab.utils.dict.class_to_dict` failing on a callable object without a ``__name__``, such as a configured reset state source; it is now serialized as its type, under ``_type``, and its fields, so - ``params/env.yaml`` can be saved. + ``params/env.yaml`` can be saved. :func:`~isaaclab.utils.dict.update_class_from_dict` reads such a dump back into + the instance, and rejects a ``_type`` that is not the instance's. +* Fixed :func:`~isaaclab.utils.io.dump_yaml` pickling tensors, which :func:`~isaaclab.utils.io.load_yaml` cannot read + back; tensors are written as their shape and dtype. diff --git a/source/isaaclab/isaaclab/utils/dict.py b/source/isaaclab/isaaclab/utils/dict.py index cd811f116399..ab9201c8127e 100644 --- a/source/isaaclab/isaaclab/utils/dict.py +++ b/source/isaaclab/isaaclab/utils/dict.py @@ -112,6 +112,14 @@ def update_class_from_dict(obj, data: dict[str, Any], _ns: str = "") -> None: # -- 1) nested mapping → recurse --------------------------- if isinstance(value, Mapping): + # class_to_dict tags a callable instance with its type, which must still be the instance's. + if "_type" in value and callable(obj_mem) and not hasattr(obj_mem, "__name__"): + if value["_type"] != callable_to_string(type(obj_mem)): + raise ValueError( + f"[Config]: Incorrect _type under namespace: {key_ns}. Expected:" + f" {callable_to_string(type(obj_mem))}, Received: {value['_type']}." + ) + value = {name: item for name, item in value.items() if name != "_type"} # recursively call if it is a dictionary update_class_from_dict(obj_mem, value, _ns=key_ns) continue diff --git a/source/isaaclab/isaaclab/utils/io/yaml.py b/source/isaaclab/isaaclab/utils/io/yaml.py index a37fd1af5175..759b1c19758f 100644 --- a/source/isaaclab/isaaclab/utils/io/yaml.py +++ b/source/isaaclab/isaaclab/utils/io/yaml.py @@ -7,11 +7,23 @@ import os +import torch import yaml from .. import to_dict +class _Dumper(yaml.Dumper): + """Writes tensors, such as reset states given as tensors, as their shape and dtype rather than pickled, since + :func:`load_yaml` does not read pickled objects back.""" + + +_Dumper.add_multi_representer( + torch.Tensor, + lambda dumper, tensor: dumper.represent_str(f"tensor(shape={list(tensor.shape)}, dtype={tensor.dtype})"), +) + + def load_yaml(filename: str) -> dict: """Loads an input YAML file. @@ -35,7 +47,8 @@ def dump_yaml(filename: str, data: dict | object, sort_keys: bool = False): """Saves data into a YAML file safely. Note: - The function creates any missing directory along the file's path. + The function creates any missing directory along the file's path. Tensors are written as their shape and + dtype. Args: filename: The path to save the file at. @@ -54,4 +67,4 @@ def dump_yaml(filename: str, data: dict | object, sort_keys: bool = False): data = to_dict(data) # save data with open(filename, "w") as f: - yaml.dump(data, f, default_flow_style=False, sort_keys=sort_keys) + yaml.dump(data, f, Dumper=_Dumper, default_flow_style=False, sort_keys=sort_keys) diff --git a/source/isaaclab/test/utils/test_dict.py b/source/isaaclab/test/utils/test_dict.py index a2b45b7c8ed3..6342b2cc191f 100644 --- a/source/isaaclab/test/utils/test_dict.py +++ b/source/isaaclab/test/utils/test_dict.py @@ -169,6 +169,29 @@ def __call__(self): assert dict_utils.class_to_dict({"fill": _Fill()}) == {"fill": fill} +class _Source: + """A callable config object without a name, such as a reset state source.""" + + def __init__(self, path: str = "states.pt"): + self.path = path + + def __call__(self): + pass + + +def test_callable_instances_round_trip_through_their_dump(): + """A dumped callable instance updates the instance it was dumped from, and its ``_type`` must match it.""" + cfg = {"source": _Source()} + data = dict_utils.class_to_dict({"source": _Source("other.pt")}) + + dict_utils.update_class_from_dict(cfg, data) + assert isinstance(cfg["source"], _Source) and cfg["source"].path == "other.pt" + + data["source"]["_type"] = dict_utils.callable_to_string(dict) + with pytest.raises(ValueError, match="_type"): + dict_utils.update_class_from_dict(cfg, data) + + 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() diff --git a/source/isaaclab/test/utils/test_yaml_io.py b/source/isaaclab/test/utils/test_yaml_io.py index 185d367d1867..fae02178ba69 100644 --- a/source/isaaclab/test/utils/test_yaml_io.py +++ b/source/isaaclab/test/utils/test_yaml_io.py @@ -36,3 +36,13 @@ def test_dump_yaml_preserves_yml_extension(monkeypatch, tmp_path, filename): assert (tmp_path / filename).is_file() assert not (tmp_path / f"{filename}.yaml").exists() assert load_yaml(filename) == {"value": 42} + + +def test_dump_yaml_writes_tensors_as_their_shape_and_dtype(tmp_path): + """A tensor in a config, such as reset states given as tensors, is described rather than pickled, so that + :func:`load_yaml` reads the file back.""" + import torch + + dump_yaml(str(tmp_path / "env.yaml"), {"states": {"pose": torch.zeros(32, 7)}}) + + assert load_yaml(str(tmp_path / "env.yaml")) == {"states": {"pose": "tensor(shape=[32, 7], dtype=torch.float32)"}} From ee7f93d2752a744c19e95103aa94d61cbdc52750 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Mon, 30 Nov 2026 17:42:20 -0800 Subject: [PATCH 23/23] Fold overlapping reset state tests into their regression owners The split migration test covers equal tensor banks given as separate tensors, the subtask goal test covers goals that the generator samples, the command order test covers partial resets, and the callable dump round trip covers the dump's type and fields. --- source/isaaclab/test/utils/test_dict.py | 18 +--- .../test/mdp2/test_mdp2_reset_states.py | 98 +++---------------- 2 files changed, 17 insertions(+), 99 deletions(-) diff --git a/source/isaaclab/test/utils/test_dict.py b/source/isaaclab/test/utils/test_dict.py index 6342b2cc191f..ffc780617350 100644 --- a/source/isaaclab/test/utils/test_dict.py +++ b/source/isaaclab/test/utils/test_dict.py @@ -155,20 +155,6 @@ 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 type and fields.""" - - class _Fill: - def __init__(self): - self.bank_size = 16 - - def __call__(self): - pass - - fill = {"_type": dict_utils.callable_to_string(_Fill), "bank_size": 16} - assert dict_utils.class_to_dict({"fill": _Fill()}) == {"fill": fill} - - class _Source: """A callable config object without a name, such as a reset state source.""" @@ -180,9 +166,11 @@ def __call__(self): def test_callable_instances_round_trip_through_their_dump(): - """A dumped callable instance updates the instance it was dumped from, and its ``_type`` must match it.""" + """A callable instance dumps as its type and fields, which update the instance it was dumped from, and its + ``_type`` must match it.""" cfg = {"source": _Source()} data = dict_utils.class_to_dict({"source": _Source("other.pt")}) + assert data == {"source": {"_type": dict_utils.callable_to_string(_Source), "path": "other.pt"}} dict_utils.update_class_from_dict(cfg, data) assert isinstance(cfg["source"], _Source) and cfg["source"].path == "other.pt" 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 10a50f892e86..d2227008675e 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2_reset_states.py @@ -141,7 +141,7 @@ def joint_pos(scene: Scene) -> torch.Tensor: return scene.data("robot", "joint_pos").torch[:, 0] -def test_generator_gives_each_world_valid_states_and_restore_only_reset_worlds(): +def test_generator_gives_each_world_valid_states(): scene = Scene(num_worlds=8) task_mdp, state = build(scene, source=mdp.FromTask(RESET_STATE_GENERATOR, num_states=4)) reset_states = mdp.get_reset_states(state) @@ -151,12 +151,7 @@ def test_generator_gives_each_world_valid_states_and_restore_only_reset_worlds() reset(task_mdp, state, [True] * 8) 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() - reset(task_mdp, state, [True] + [False] * 7) - assert torch.equal(joint_pos(scene)[1:], before[1:]) + assert torch.equal(joint_pos(scene).cpu(), stored[torch.arange(8), slots]) # each world draws its own states def test_shared_states_restore_poses_relative_to_each_world_origin(): @@ -341,35 +336,6 @@ def _sample_goal_torch(mask, command, rng): sample_goal = mdp2.Term(torch=_sample_goal_torch, warp=_sample_goal, random=True) -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)} - generator = mdp2.TaskCfg( - commands=commands, - events={"draw": mdp2.Event(draw, outputs=outputs)}, - terminations=RESET_STATE_GENERATOR.terminations, - ) - for backend in ("torch", "warp"): - scene = Scene(num_worlds=4) - event = mdp2.Event( - mdp.reset_to_states, - outputs={**outputs, **goal}, - 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) - reset_states = mdp.get_reset_states(state) - - 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 = reset_states.states["goal"][torch.arange(4), reset_states.started_from] - 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)): @@ -572,16 +538,22 @@ def test_reset_states_carry_over_to_an_updated_task(): assert updated_state.arrays[mdp2.commands.goal].torch.tolist() == [1.75, 1.75], backend +def _bank(value: float) -> mdp.FromTensors: + """Two reset states of one joint position, as a new tensor each time, so that equal banks are not the same object + and their comparison is not of single values.""" + return mdp.FromTensors({"value": torch.tensor([[value], [value]], device=DEVICE)}) + + def test_split_reset_states_of_one_use_stay_with_their_outputs_in_an_updated_task(): - """Branches of a split that share a reset event's name and params but reset different assets keep their own reset - states when the task is updated.""" + """Branches of a split that share a reset event's name and equal tensor states, as separate tensors, but reset + different assets build and keep their own reset states when the task is updated.""" for backend in ("torch", "warp"): scene = Scene(num_worlds=2) scene.schema.entities["other"] = scene.schema.entities["robot"] scene._data["other", "joint_pos"] = ProxyArray(wp.zeros((2, 1), dtype=wp.float32, device=DEVICE)) - params = {"source": mdp.FromTensors({"value": torch.tensor([[0.5]], device=DEVICE)}), "shared": True} def resets(entity: mdp2.Entity) -> mdp2.TaskCfg: + params = {"source": _bank(0.5), "shared": True} event = mdp2.Event(mdp.reset_to_states, outputs={"value": entity.joint_pos}, params=params) return mdp2.TaskCfg(events={"reset": event}) @@ -617,8 +589,8 @@ def _never(world: int, joint_pos: wp.array2d(dtype=float)) -> float: def test_stored_goals_restore_in_subtasks_and_when_their_task_starts(): - """A subtask's event restores the subtask's goal from the generator's goal, at resets and, as a start event, when - the subtask starts mid-episode.""" + """A subtask's event stores the goals that the generator samples, under the subtask's goal, and restores them over + the resample, at resets and, as a start event, when the subtask starts mid-episode.""" def restore(mode: mdp2.EventMode) -> mdp2.Event: return mdp2.Event( @@ -651,6 +623,7 @@ def restore(mode: mdp2.EventMode) -> mdp2.Event: state = task_mdp.state(scene, seed=3) mdp2.startup(task_mdp, state) reset_states = mdp.get_reset_states(state, f"events.{path}.reset") + assert len(reset_states.states["goal"].unique()) == 12, (backend, path) # sampled in every roll reset(task_mdp, state, [True] * 4) if path == "second": joint_pos(scene).fill_(0.75) @@ -695,49 +668,6 @@ def test_episodes_that_restore_a_goal_are_credited_with_their_progress(): np.testing.assert_allclose(success_rate, [1.0, 0.0], err_msg=backend) -def _bank(value: float) -> mdp.FromTensors: - """Two reset states of one joint position, as a new tensor each time, so that equal banks are not the same object - and their comparison is not of single values.""" - return mdp.FromTensors({"value": torch.tensor([[value], [value]], device=DEVICE)}) - - -def _split_banks(scene: Scene, backend: str, a: float, b: float) -> mdp2.MDP: - def resets(value: float) -> mdp2.TaskCfg: - event = mdp2.Event( - mdp.reset_to_states, outputs={"value": robot.joint_pos}, params={"source": _bank(value), "shared": True} - ) - return mdp2.TaskCfg(events={"reset": event}) - - builder = mdp2.MDPBuilder(scene.schema) - builder.add_task(mdp2.split(worlds={"a": 2, "b": 2}, a=resets(a), b=resets(b))) - return builder.finalize(device=DEVICE, backend=backend) - - -def _first_branch(task_mdp: mdp2.MDP) -> str: - """The op of the reset event in the split's first branch, worlds 0 and 1.""" - return next(op.name for op in task_mdp.term_ops if op.use == "events.reset" and 0 in (op.worlds or (0,))) - - -def test_split_tensor_banks_restore_their_own_states_and_update_when_replaced(): - """Branches of a split whose reset events have different tensor banks build and restore their own states, and - replacing one bank in a running task restores the new states there while the other branch keeps its own.""" - for backend in ("torch", "warp"): - scene = Scene(num_worlds=4) - task_mdp = _split_banks(scene, backend, 0.5, 0.25) - state = task_mdp.state(scene, seed=3) - mdp2.startup(task_mdp, state) - reset(task_mdp, state, [True] * 4) - assert joint_pos(scene).tolist() == [0.5, 0.5, 0.25, 0.25], backend - kept = mdp.get_reset_states(state, _first_branch(task_mdp)) - - updated = _split_banks(scene, backend, 0.5, 0.75) - updated_state = updated.state(scene, seed=3) - mdp2.migrate(task_mdp, state, updated, updated_state) - reset(updated, updated_state, [True] * 4) - assert joint_pos(scene).tolist() == [0.5, 0.5, 0.75, 0.75], backend - assert mdp.get_reset_states(updated_state, _first_branch(updated)) is kept, backend - - def _zero_joint(mask: torch.Tensor, value: torch.Tensor, **params) -> None: value.masked_fill_(mask[:, None], 0.0)