Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
56122a1
Add an MDP2 reset event over the shared reset-state API
StafaH Nov 19, 2026
a9230a9
Add state writes, outcome resets, and per-environment draws to the re…
StafaH Nov 20, 2026
e8eacee
Run reset event updates every step and restore commands after resampling
StafaH Nov 20, 2026
bbc22cf
Record, replay, and save MDP2 reset banks
StafaH Nov 20, 2026
d98094a
Bank commands from the candidates task and skip credit for manual resets
StafaH Nov 20, 2026
f67efc5
Extract the candidates roller from FillFromCandidates
StafaH Nov 20, 2026
4204c07
Dump callable config objects without a name as their fields
StafaH Nov 21, 2026
75923d0
Restore only the worlds that reset from the bank
StafaH Nov 22, 2026
644dfe6
Bank reset states per group of worlds, as MDP1's lift does per object
StafaH Nov 22, 2026
dc3398d
Rename the MDP2 reset bank API to reset states
StafaH Nov 22, 2026
3227f55
Address review comments on MDP2 reset states
StafaH Nov 24, 2026
9be22ec
Move the Kuka lift reset changelog to the experimental tasks package
StafaH Nov 27, 2026
366232a
Restore commands after their task starts mid-episode as at resets
StafaH Nov 27, 2026
e9d65dc
Credit only ended episodes and record only in the worlds of the reset…
StafaH Nov 27, 2026
0e2c1e0
Test manual resets after unended steps and register experimental task…
StafaH Nov 27, 2026
1ea394a
Tag dumped callable instances with their type and document reset samp…
StafaH Nov 30, 2026
0182200
Restore reset_to_states commands after the resample and keep its stat…
StafaH Nov 30, 2026
22ca2e8
Scope event outputs to their task's commands and guard dumps of calla…
StafaH Nov 30, 2026
00dcd9a
Note the removed Kuka reset bank term as breaking in the task changelog
StafaH Nov 30, 2026
aaa587c
Match bound fields and worlds before carrying a use's cache across a …
StafaH Nov 30, 2026
cb6429e
Compare tensor reset state sources by value and match hooks before ca…
StafaH Dec 1, 2026
735b326
Describe tensors in dumped YAML and read callable instance dumps back
StafaH Dec 1, 2026
ee7f93d
Fold overlapping reset state tests into their regression owners
StafaH Dec 1, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,12 @@ Events
.. automodule:: isaaclab_experimental.mdp2.mdp.events
:members:

Reset states
------------

.. automodule:: isaaclab_experimental.mdp2.mdp.reset_states
:members:

Rewards
-------

Expand Down
133 changes: 133 additions & 0 deletions docs/source/how-to/reset_state_buffers.rst
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,20 @@ 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.

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

Expand Down Expand Up @@ -204,6 +218,125 @@ 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_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

from isaaclab_experimental import mdp2
from isaaclab_experimental.mdp2 import mdp

"reset": mdp2.Event(
mdp.reset_to_states,
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),
"sampler": ResetStateSamplerCfg(scores=[BetaSamplingScoreCfg(target=0.5)]),
},
)

* ``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``,
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.
* ``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. 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.

Record states along the horizon
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

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_to_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},
params={
"source": mdp.FromTask(RESET_STATE_GENERATOR, num_states=16),
"sampler": ResetStateSamplerCfg(scores=[BetaSamplingScoreCfg(target=0.5)]),
"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
``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, pin, and save reset states
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

: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

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

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")

Pins hold until replaced and run inside the captured step, so they can sweep the reset states
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:

.. code-block:: bash

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

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

Expand Down
56 changes: 56 additions & 0 deletions scripts/tools/generate_reset_states.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# 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
import isaaclab_tasks_experimental # noqa: F401
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()
6 changes: 6 additions & 0 deletions source/isaaclab/changelog.d/callable-instance-dump.fixed.rst
Original file line number Diff line number Diff line change
@@ -0,0 +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. :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.
7 changes: 7 additions & 0 deletions source/isaaclab/changelog.d/mdp2-resets.added.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
* 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 ``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.
Empty file.
100 changes: 86 additions & 14 deletions source/isaaclab/isaaclab/envs/reset/reset_state_buffer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand All @@ -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:
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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]
Loading
Loading