Skip to content

MDP2 Reset Viewer - #9119

Draft
StafaH wants to merge 17 commits into
isaac-sim:mainfrom
StafaH:mh/mdp2-reset-viewer
Draft

StafaH wants to merge 17 commits into
isaac-sim:mainfrom
StafaH:mh/mdp2-reset-viewer

Conversation

@StafaH

@StafaH StafaH commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

Description

MDP2 Reset Viewer: see the reset states of an MDP2 task, and interact with them, in Viser or the Newton viewer.

Stacked on #9112 (MDP2 Resets). Until that merges, review only the last seven commits.

mdp2_reset_viewer

The recording predates the rename to reset states: its buttons read Draw starts, Roll candidates and Save bank, which are now Draw reset states, Roll generator and Save reset states.


Try it

uv run --extra viser python scripts/tools/view_reset_states.py \
    --task Isaac-Lift-KukaAllegro-MDP2 --num_envs 16 --viz viser physics=newton_mjwarp
Flag What it does Default
--task any MDP2 task with a reset_to_states event required
--num_envs worlds to show 16
--event name of the reset_to_states event reset
--states open saved reset states (FromFile) instead of generating them none
--policy actions for played episodes: zero or random zero

Open the printed Viser URL and use the Reset states folder in the sidebar.


What you can do

Button The worlds show The label above each world
Show slot in every world every world reset to slot k of its own reset states, paused slot k | success
Draw reset states reset states drawn the way training draws them the slot each world drew
Roll generator one proposal of the generator task in every world accepted or rejected, by its terminations
Play / Pause / Step episodes running from those reset states, no faster than real time updates live

The panel also has:

  • A table for the selected World: each slot's kind (source or recorded), success rate, episode count, and probability of the next draw. The world's current slot is starred. With groups (one set per object), the table shows the world's group.
  • Save reset states, which writes a file that FromFile and --states can load.

Use it from Python

from isaaclab_experimental.envs import ResetStateViewer

viewer = ResetStateViewer(env, event="reset", policy=None)  # None holds zero actions
viewer.attach()                                             # adds a panel to every Viser / Newton viewer
while env.unwrapped.sim.is_running():
    viewer.update()

You can drive it without any UI, for example in tests or notebooks:

viewer.show(3)      # every world at slot 3, paused
viewer.roll()       # one generator proposal per world
viewer.play()       # episodes run on the next update() calls
viewer.select(5)    # table shows world 5
viewer.save("reset_states.pt")

Panels call viewer.request("show", 3) instead, which is safe from any thread.


Design

Viser / Newton UI ──request()──▶ queue ──update()──▶ ResetStateViewer ──▶ ResetStates / StateGenerator / env.step
        ▲                                                │
        └──────────── refresh(snapshot of plain values) ◀┘
  • ResetStateViewer is a UI-agnostic controller over mdp.get_reset_states from MDP2 Resets #9112.
    • It shows slots through ResetStates.pin.
    • It rolls mdp.StateGenerator.
    • It plays episodes through env.step.
  • Panels only queue requests. Viser runs callbacks on its own thread, and the Newton viewer runs them inside a render. update() applies the requests on the main thread, then hands the panels a snapshot of plain values. All GPU reads stay on the main thread.
  • Playback is paced. Episodes advance at most one step per step_dt, so they play no faster than real time. A paused view renders at 30 frames per second.
  • Interrupting doesn't credit. Showing a slot, drawing, or rolling interrupts episodes, so the viewer calls ResetStates.skip_current_episodes() first.
    • Episodes that end on their own while playing are credited, as in training.
    • Playing after a roll draws fresh reset states first, because generator proposals aren't episodes the MDP knows about.
  • Two thin frontends:
    • ViserResetStatePanel: a sidebar folder plus a label above every world (up to 64), through the new public ViserVisualizer.server.
    • NewtonResetStatePanel: an ImGui panel through register_ui_callback.

Verification

Tests: test_mdp2_reset_viewer.py (Newton, 8 worlds)

  • Showing a slot writes that slot's states to the simulation.
  • A roll labels exactly the proposals its terminations accept.
  • Playing after a roll draws reset states.
  • Interrupting episodes credits nothing.
  • With a real ViserServer, the panel's table, status, slot control and labels follow the controller.

By hand

  • Viser, in a browser: the recording at the top is a real session on Kuka Allegro lift, recorded in headless Chrome. It used 9 worlds and 6 reset states per world, driven by a small script around the viewer. The cursor clicks the panel's own buttons.
  • That pass found and fixed two bugs, and one change:
    • Viser drops Markdown blocks that contain tables, so the table is HTML.
    • The slider and World field didn't follow the viewer's state.
    • Change: Play was unpaced, stepping as fast as the simulation could. It now advances at most one step per step_dt.
  • Not re-recorded after the rename or after grouping by object.

Not verified

  • The Newton viewer panel. This machine has no display, so the Newton viewer runs without ImGui.
  • The script's launcher step. add_launcher_args boots Kit here, which waits for its EULA. Everything after the launcher (resolve_task_config, gym.make, FromFile, the viewer) ran directly.

Type of change

  • New feature (non-breaking change which adds functionality)

Checklist

  • I have read and understood the contribution guidelines
  • I have run the pre-commit checks with ./isaaclab.sh --format
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • I have added a changelog fragment under source/<package>/changelog.d/

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.
…set 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.
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.
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.
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.
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.
@StafaH
StafaH requested a review from a team November 20, 2026 02:23
@github-actions github-actions Bot added documentation Improvements or additions to documentation isaac-lab Related to Isaac Lab team labels Nov 20, 2026
@greptile-apps

greptile-apps Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 2/5

[Medium impact] The changes affect MDP2 reset workflows, one lift task, and viewer-based inspection.

Fix the reset-order issue and the previously reported browser-controlled file overwrite before merging.

Findings

  1. P1 Reset events run out of order ▶
  2. P1 Security Browser clients can overwrite files. ▶
  3. P2 Invalid pins replay old states ▶

Summary

Adds tools to generate and inspect MDP2 reset states, plus Viser and Newton controls for browsing and playing episodes.

  • MDP2 tasks can reset worlds from generated, loaded, or recorded states.
  • Kuka Allegro lift worlds share reset states with the same object.
  • Developers can browse reset states and play episodes in Viser or Newton.
  • Config saving now includes callable objects without names.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
    UI[Viser or Newton panel] --> Q[Request queue]
    Q --> V[ResetStateViewer.update]
    V --> R[Pin or draw reset states]
    V --> G[Roll generator]
    V --> E[Step episodes]
    R --> S[Simulation]
    G --> S
    E --> S
    S --> P[Snapshot of plain values]
    P --> UI
Loading

Reviews (2) · Last reviewed commit: "Format the reset viewer test" · Reviewed by Greptile

Comment on lines +332 to +334
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Continuing worlds get reset. After a world first draws a banked start, _restored stays true when later reset masks exclude it. This gather still writes that world's old start into its outputs, even on steps where no episode ends. On Newton, these outputs can be the solver's own buffers, so ongoing episodes snap back to their starts.

Use a separate write mask that includes only worlds selected by the current reset. Keep the per-episode flag needed by slots separate.

Comment on lines +155 to +157
def save(self, path: str) -> None:
"""Save the bank, to fill later runs with ``mdp.FillFromFile``."""
self.bank.save(Path(path))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 security Browser clients can overwrite files. The Viser panel sends its editable file path directly here, and ResetBank.save passes it to torch.save. Any connected client can enter an absolute path or ../ path and overwrite a checkpoint or another file writable by the host process. The Viser server listens on all interfaces by default.

Offer a browser download, or limit resolved paths to a host-selected output folder and prevent unintended overwrites.

How this was verified: The browser text reaches torch.save through the request queue without any path check.

Knowledge Base Used: Rendering pipelines and visualizer adapters

Comment on lines +104 to +105
if self.playing:
self.env.step(self.policy(self.env.observations))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Playback changes bank scores. update() steps without discarding outcomes. A preceding show() or draw() discards the interrupted episode, but the reset immediately makes the new episode count again. Once Play reaches a termination or time limit, the sampler adds its zero-action or random-action outcome to the bank. step() has the same problem.

Discard outcomes before both stepping paths, and extend the test through an episode boundary rather than only three steps.

"""Return a row per slot of the shown world's bank: slot, kind, success, episodes, probability. The slot the
world started from is marked with ``*``."""
# Candidate proposals start from no slot.
current = -1 if snapshot.accepted is not None else snapshot.slots[0 if snapshot.shared else snapshot.world]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Shared banks mark wrong slot. In shared-bank mode, rows() always reads world 0's slot, even when the user selects another world. Sharing the stored states does not make every world draw the same slot. Use snapshot.slots[snapshot.world] in both modes so the star matches the selected world's label.

Suggested change
current = -1 if snapshot.accepted is not None else snapshot.slots[0 if snapshot.shared else snapshot.world]
current = -1 if snapshot.accepted is not None else snapshot.slots[snapshot.world]

@isaaclab-review-bot isaaclab-review-bot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isaac Lab Review Bot

Needs attention: Design and architecture (1), Scope and over-engineering (4), API (1), Compatibility and deprecation (4), Implementation (6), Style consistency (4), Test quality (2).

  • PR description: Describe the full reset-and-viewer diff, qualify playback credit and frontend capabilities, and benchmark recording/refresh costs using baseline/candidate revisions, command/workload, hardware, backend, environment count, warmup, and latency/allocation metrics while preserving template sections.
  • Design and architecture: Registered callbacks and panel handles retain the controller and environment; add explicit cleanup and invoke it before closing the environment.
  • Scope and over-engineering: Minimal implementation: Extend ResetStateBuffer, ResetStateSampler, and the MDP2 plan; keep reset_states.py for bank lifecycle, mdp2_reset_viewer.py for controller/panel lifecycle, and collect_reset_states.py and view_reset_states.py as distinct entry points; delete unused mode/snapshot state, duplicate rate transfers, and unconditional recording allocations. Suggested PR breakdown: core APIs with unit validation; MDP2 bank and Lift migration with compatibility, analytic, and simulation validation; collection and viewer with persistence, launcher, and frontend validation.
  • API: Exporting farthest_points creates an unnecessary public contract for one internal caller; restore its private name and remove the lazy export.
  • Compatibility and deprecation: Breaking changes: minus-one requests, reset-event ordering, legacy Lift reset parameters, and the task-local reset term change without functional deprecation bridges; retain old paths with targeted warnings, migration/removal guidance, and transition tests.
  • Implementation: Persistent restoration flags include unselected worlds, so partial resets overwrite continuing episodes; clear unselected flags before gathering.
  • Style consistency: ResetBank claims replay is allocation-free despite allocating per-world index and selection tensors; remove the claim or eliminate those allocations.
  • Test quality: The post-roll Play assertion checks mode flags but not restored state, so skipped drawing passes; assert scene fields match the newly assigned bank slots.

Needs rework. Posted 22 inline findings.

Automated review; human maintainers own approval decisions.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Critical · Implementation — Exclude rejected replay requests

A nonnegative invalid request enables restoration before the sampler rejects it. Gathering then writes the previous assignment instead of preserving the incoming reset state. Exclude invalid requests from the restore mask.

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Critical · Implementation — Mask restoration to reset worlds

_choose_starts leaves _restored set for unselected worlds. A later partial reset gathers their old slots and can shift their poses again. Clear unselected flags before gathering.

if args_cli.policy == "random":
policy = lambda observations: 2.0 * torch.rand(shape, device=unwrapped.device) - 1.0 # noqa: E731
viewer = ResetViewer(env, args_cli.event, policy)
if not viewer.attach():

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Warning · Implementation — Exit without an attached viewer

When attach() returns zero, the script reports the missing viewer but enters a render loop with no controls. Exit before the loop.

policy = lambda observations: 2.0 * torch.rand(shape, device=unwrapped.device) - 1.0 # noqa: E731
viewer = ResetViewer(env, args_cli.event, policy)
if not viewer.attach():
print("No Viser or Newton viewer is open: pass --viz viser or --viz newton_gl.")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Warning · Style Consistency — Log the missing-viewer warning

This user-facing warning uses print and bypasses logging controls. Configure console logging at entry and issue a logger warning.

requested_indices[env] = -1
if mask[env]:
value = wp.int64(requested[env])
if value == wp.int64(-1):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Warning · Compatibility — Preserve invalid minus-one requests

state_ids=-1 previously marked an invalid request and retained the assignment; it now draws and may credit an outcome. Make mixed sampling opt-in while deprecating the old behavior with guidance and tests.


# A reset event that writes a command runs after the commands resample, so that its value stands.
command_fields = {op.writes[0] for op in ops[Phase.COMMANDS]}
early = [op for op in ops[Phase.RESET_EVENTS] if not command_fields & set(op.writes)]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Warning · Compatibility — Preserve reset-event order

Partitioning events moves command-writing events past later-declared events, changing their reads and writes. Preserve declaration order and provide a functional, warned migration for any required ordering change.

assert torch.equal(joint_pos(scene).cpu(), banked[torch.arange(8), slots]) # each world draws its own bank

before = joint_pos(scene).clone()
for _ in range(8):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Warning · Test Quality — Remove repeated identical resets

Eight calls use the same mask and assert only that untouched worlds stay unchanged. One call establishes that contract; remove the seven redundant resets.

"history_length": 10,
"target_success_rate": 0.5,
"kappa": 1.0,
"fill": mdp.FillFromCandidates(CANDIDATES, bank_size=16),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Warning · Compatibility — Translate legacy reset parameters

Overrides using bank_size, candidates, history_length, target_success_rate, or kappa no longer configure this task and can fail startup. Accept them through a warned, documented, tested transition.

for name, value in states.items():
ctx.state[f"bank_{name}"].copy_(value)


Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Warning · Compatibility — Retain the task-local reset term

Deleting this module breaks imports of its existing reset_from_bank term. Keep a functional deprecated entry point with a targeted warning, migration guidance, and old/new-path validation.

assert viewer.snapshot.mode == "candidates" and viewer.snapshot.labels == labels

# Candidates are not episodes: playing first draws starts as training does, and nothing is credited.
viewer.play()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Warning · Test Quality — Verify the post-roll draw

Checking mode and playing cannot detect candidate proposals left in the scene. Assert that Play restores scene fields from newly drawn bank slots.

@StafaH StafaH mentioned this pull request Nov 20, 2026
13 tasks done
@StafaH
StafaH marked this pull request as draft November 20, 2026 19:26
StafaH and others added 3 commits November 21, 2026 06:58
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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.
@StafaH
StafaH force-pushed the mh/mdp2-reset-viewer branch from 60082fe to d433603 Compare November 22, 2026 21:12
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.
ViserVisualizer.server returns the viewer's viser.ViserServer, so tools can add
their own GUI controls and scene labels without reaching into private state.
ResetViewer shows and drives the reset bank of an MDP2 task from Viser and
Newton viewer panels: it restores a slot in every world, draws starts as
training does, rolls the candidates task to show which proposals are rejected,
and plays episodes, with each world's slot and success rate above it and the
selected world's bank as a table. Panels only queue requests; the controller
applies them on the main thread and credits no interrupted episode.
view_reset_states.py opens it for any MDP2 task.
Follow the reset states vocabulary: the viewer pins slots, rolls the generator task, and loads saved states with --states.
Per-slot statistics are per group of worlds since reset states can be grouped by object, so the table and labels index them by each world's group.
@StafaH
StafaH force-pushed the mh/mdp2-reset-viewer branch from d433603 to f3a009c Compare November 22, 2026 21:16
Comment on lines +184 to +185
early = [op for op in ops[Phase.RESET_EVENTS] if not command_fields & set(op.writes)]
late = [op for op in ops[Phase.RESET_EVENTS] if command_fields & set(op.writes)]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Reset events run out of order

The early/late split can reverse a valid reset order. A reset_to_states event that restores both a goal command and an object pose moves into late, while a following event that reads that pose stays in early. The reader then uses the old pose, leaving the world in the wrong starting state. The builder checks dependencies before this split, so it accepts the original order without catching the reversal.

Keep dependent events after their writers, or reject schedules the split cannot preserve.

Knowledge Base Used: Experimental MDP2 runtime

Comment on lines +365 to +368
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._writes)
for pose in self._poses:
wp.launch(_shift_poses, mask.shape, [self._writes, self._origins, pose, pose, 1.0], device=mask.device)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Invalid pins replay old states

An out-of-range pin restores the previous slot instead of leaving the reset unchanged, contrary to pin()'s contract. _choose_starts enables writes before the sampler checks the request. The sampler rejects the request and keeps its old assignment, but get_state still restores that assignment because writes remains true. This unexpectedly overwrites values from earlier reset events.

Exclude rejected requests from the write mask before gathering states or shifting poses.

StafaH added a commit that referenced this pull request Dec 1, 2026
# Description

**MDP2 Resets:** reset MDP2 episodes to **stored reset states**. You can
generate them from a task, record them during training, generate them
once in a separate run, pin worlds to specific ones, and save them.
Restoring, recording, and pinning all run inside the captured step.

> **Stacked PR:** the viewer for reset states is #9119.
> **Built on:** the reset-state API that #8872 merged into
`isaaclab.envs.reset`.

---

## The idea in one minute

A **reset state** is a state to reset to. The reset states of an event
answer three questions. Each answer has one owner, and you can swap each
one on its own:

| Question | Owner | How you change it |
|---|---|---|
| **Which reset states exist?** | `ResetStateBuffer` | `source=` and
`record=` |
| **Which one does each world reset to?** | `ResetStateSampler` |
`sampler=`, `default_reset_probability=`, `reset_states.pin(...)` |
| **How does a state reach the simulation?** | the event's `outputs` |
nothing to configure: any writable scene field or command works |

Some vocabulary:

- **Slot:** one stored reset state. Slots are numbered within each
world's reset states (or each group's, see recipe 7).
- **Source:** where the reset states come from at startup: a generator
task, a file, or tensors.
- **Credit:** when an episode ends, its success is credited to the slot
it started from. The sampler uses that history to pick the next reset
state. Episodes reset by hand before they end are not credited.
- **Default reset:** a reset that keeps what the task's other reset
events wrote.

This follows mujoco and Newton: a keyframe is just arrays with a leading
index, and choosing the index is up to the caller.

---

## Quick start

Add one reset event to an MDP2 task:

```python
from isaaclab.envs.reset import BetaSamplingScoreCfg, ResetStateSamplerCfg
from isaaclab_experimental import mdp2
from isaaclab_experimental.mdp2 import mdp

"reset": mdp2.Event(
    mdp.reset_to_states,
    inputs={
        "succeeded": mdp2.quantities.success,                          # credited to the starting slot
        "terminated": mdp2.terminated,                                 # with time_out: only ended episodes count
        "time_out": mdp2.time_out,
    },
    outputs={**robot_state, **object_state},                           # the outputs *are* the state
    params={
        "source": mdp.FromTask(RESET_STATE_GENERATOR, num_states=16),  # generated at startup
        "sampler": ResetStateSamplerCfg(scores=[BetaSamplingScoreCfg(target=0.5)]),
    },
)
```

Then read the reset states from the env state:

```python
reset_states = mdp.get_reset_states(env.state)   # the ResetStates of "events.reset"
reset_states.states["joint_pos"]                 # (num_worlds, num_states, num_joints)
reset_states.success_rate                        # (num_worlds, num_states)
```

`mdp2.quantities.<name>` refers to a quantity your task declares under
that name, such as `success` in the Kuka lift task.

---

## Recipes

### 1. Write a task that generates reset states

The states come from a **generator task**: an ordinary MDP2 `TaskCfg`
that lives next to your main task, so there is nothing new to learn.
Each part of it has one job:

| Part of the generator task | Its job |
|---|---|
| `events` | propose a reset state |
| `terminations` | reject bad proposals |
| `observations["descriptor"]` (optional) | spread the kept states by
farthest-point sampling |

Here is the one from the Kuka Allegro lift task
(`isaaclab_tasks_experimental/mdp2/lift_kuka_allegro/lift_env_cfg.py`),
with long input lists shortened to `...`:

```python
RESET_STATE_GENERATOR = mdp2.TaskCfg(
    # 1. Propose: scatter the arm, spin the wrist, and drop the object somewhere above the table.
    events={
        "reset_robot_joints": mdp2.Event(
            mdp.reset_joints_by_offset,
            inputs={**joint_limits, "joint_ids": joints},
            outputs=robot_state,
            params={"position_range": (-0.5, 0.5), "velocity_range": (0.0, 0.0)},
        ),
        "reset_robot_wrist_joint": mdp2.Event(
            mdp.reset_joints_by_offset,
            inputs={**joint_limits, "joint_ids": robot.joints("iiwa7_joint_7")},
            outputs=robot_state,
            params={"position_range": (-3.0, 3.0), "velocity_range": (0.0, 0.0)},
        ),
        "reset_object": mdp2.Event(
            mdp.reset_root_state_uniform,
            inputs={...},
            outputs={"root_link_pose_w": target.root_link_pose_w, "root_com_vel_w": target.root_com_vel_w},
            params={"pose_range": ((-0.2, 0.2), (-0.2, 0.2), (0.0, 0.4), (-3.14, 3.14), (-3.14, 3.14), (-3.14, 3.14))},
        ),
        # A quarter of the proposals start with the object already in the palm.
        "reset_object_to_target": mdp2.Event(
            lift.reset_to_target,
            inputs={"body_link_pose_w": robot.body_link_pose_w, "body_ids": robot.bodies("palm_link")},
            outputs=object_state,
            params={"position_range": ((0.03, 0.07), (-0.04, 0.04), (0.02, 0.08)), "probability": 0.25},
        ),
    },
    # 2. Reject: the robot must not overlap the object or the table.
    terminations={
        "object_robot_clearance": mdp2.Termination(mesh_clearance, inputs={...}, params={"min_clearance": 0.0}),
        "robot_table_clearance": mdp2.Termination(slab_clearance, inputs={...}, params={"min_clearance": 0.02, ...}),
    },
    # 3. Spread (optional): prefer kept states that differ in how far the hand is from a grasp.
    observations={
        "descriptor": {
            "grasp_travel_distance": mdp2.Observation(lift.grasp_travel_distance, inputs={...}, params={...}),
        },
    },
)
```

Then point the main task's reset event at it:

```python
"source": mdp.FromTask(RESET_STATE_GENERATOR, num_states=16, oversample_factor=2.0, max_rolls=2000)
```

How `FromTask` uses it:

- It rolls the generator task in every world: runs its events, then
checks its terminations.
- It keeps the proposals no termination fired on, until each world (or
group) has enough.
- With a `descriptor`, it harvests `oversample_factor` times more and
keeps the most spread-out ones.
- It gives up with an error after `max_rolls` rolls.

The same task works three ways:

- **at startup**, through `FromTask`;
- **in a separate run**, with `generate_reset_states.py` (recipe 3);
- **in the viewer** (#9119), where *Roll generator* shows one proposal
per world, labelled accepted or rejected.

Two more details:

- Commands that the event restores, such as goals, are taken from the
generator task, where they are sampled. Inside a named subtask
(`compose(pick=...)`), the event writes `commands.pick.goal` and takes
the generator's local `commands.goal`.
- `mdp.StateGenerator` is the same task bound to the scene and rolled
one proposal at a time. The viewer uses it.

### 2. Record visited states during training

```python
"reset": mdp2.Event(
    mdp.reset_to_states,
    inputs={
        "succeeded": mdp2.quantities.success,
        "terminated": mdp2.terminated,       # required: terminal states are never recorded
        "time_out": mdp2.time_out,
        "record_if": mdp2.quantities.lifted, # optional: only where this quantity is 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),
    },
)
```

What happens on each step:

- Each world that did not terminate records its outputs, with the given
`probability`.
- A record replaces the oldest of the world's own recorded slots.
- A replaced slot forgets its old outcomes and starts at the first
score's target success rate, so new states get tried. Without this, a
fresh slot would weigh only `uniform_weight` against established ones.
- An episode whose slot is recorded over is not credited.

> Recording needs reset states per world (no `shared` or `groups`).
Include velocities, and commands for goal-conditioned tasks, in the
outputs, so a restored state continues as it was recorded.

### 3. Generate once, train many times

Generate many reset states in their own run:

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

Then load them in training, which skips generation at startup:

```python
"source": mdp.FromFile("kuka_lift_reset_states.pt")
```

> Reset states per world or per group only fit a run with the same
worlds, and loading checks that. Shared reset states fit any run.

### 4. Pin worlds to specific reset states

```python
reset_states.pin(torch.full((env.num_envs,), 3))  # every world resets to its slot 3 at its next reset
reset_states.unpin()                              # back to sampling
```

- A slot of `-1` draws as usual, so you can pin some worlds and sample
the others.
- Pins hold until replaced and run inside the captured step, so an
evaluation can sweep the reset states.

### 5. Keep some default resets

```python
params={..., "default_reset_probability": 0.2}
```

In 20% of resets, the event keeps what the earlier reset events wrote: a
fresh draw from the task's default reset distribution. Those episodes
are credited to no slot.

### 6. Share one set of reset states across worlds

```python
inputs={..., "env_origins": mdp2.Entity("scene").env_origins},
params={..., "shared": True},
```

Poses are stored relative to each world's origin. Share reset states
only between worlds whose states fit each other, such as worlds that
spawn the same object.

### 7. One set per object

```python
inputs={..., "env_origins": mdp2.Entity("scene").env_origins},
params={..., "groups": mdp.prototype_groups},
```

`prototype_groups` groups the worlds by the object, or other prototype,
that the scene cloned into them, as MDP1's lift does. The worlds of a
group draw from one set of reset states and share its success
statistics. `groups` takes any callable that returns each world's group.
The Kuka lift task uses this with 1024 reset states per object.

### 8. Inspect and save

| Member | What it gives you |
|---|---|
| `reset_states.states` | the stored outputs, per world (or group) and
slot |
| `reset_states.success_rate`, `.episode_counts`, `.probabilities` | per
world (or group) and slot |
| `reset_states.started_from` | the slot each world started from (`-1`
for a default reset) |
| `reset_states.save(path)` | writes a file for `FromFile` |

---

## How it fits into MDP2

### Where `reset_to_states` runs

1. **Scene outputs restore where the event is scheduled.** Later reset
events, and the commands that resample from scene fields, see the
restored scene. Credit is taken here too, so `succeeded` is read before
progress restarts.
2. **Command outputs restore in the event's `reset` hook**, which runs
after the commands resample, at resets and when its task starts
mid-episode, so a restored goal stands.
3. **The `update` hook runs once per step, after the rewards.** That is
where recording observes the step. This is the one new plan rule: reset
events with an `update` hook get an `UPDATE_STATE` step.

Other events keep their usual order: a plain event that writes a command
is still overwritten by the resample.

### Design choices

| Choice | Why |
|---|---|
| **One event, not three** (store / choose / restore) | Only the owning
use writes its own state; three uses would need plumbing between them.
Buffer and sampler are already separate one level down. |
| **Not a fused `wp.func`** | The reset already replays inside the
step's CUDA graph (0.066 ms of a 10.5 ms step, see Performance). |
| **Reset states in the use's cache** |
`mdp.get_reset_states(env.state)` reads them, so tools like the viewer
can too. `get_reset_states`, because `mdp.reset_states` is the module. |

---

## Changes underneath

### `isaaclab.envs.reset`

| API | What's new |
|---|---|
| `ResetStateBuffer.set_state(indices, values, mask=)` | Inverse of
`get_state`: replaces stored states while running. Capturable. |
| `ResetStateSampler.forget(indices, mask, success_rate=)` | Clears the
outcomes of replaced entries and starts them at a prior. Capturable. |
| `ResetStateSampler.reset(..., rng=seeds)` | Takes caller-owned int32
per-world seeds, so `env.reset(seed=...)` reseeds the draws. |
| `ResetStateSampler.reset(..., sample_unrequested=True)` | A
`state_ids` request of `-1` draws for that environment, so one captured
reset can pin some worlds and sample the others. Opt-in: by default `-1`
stays an invalid request. |


### MDP2

- `TermContext.cache` gives init hooks the use's cache.
- Reset events with an `update` hook run it once per step, after the
rewards.
- `migrate` (`env.update_task`) carries the cache of every use that both
tasks keep with the same params, bound fields and worlds, so the reset
states survive a task edit, and split branches of one use keep their
own.
- The builder scopes an event's outputs like its inputs, so a reset
event inside a named subtask writes that subtask's commands.

### `reset_to_states` sources and checks

- `FromTask`, `FromFile`, `FromTensors` and `RecordVisited` are plain
(not frozen) configs, so Hydra overrides such as
`env.task.events.reset.params.source.num_states=...` work.
- `FromFile` rejects a file saved without group labels when the event
uses groups.
- A sampler with scores requires the `succeeded` input, checked at
startup.

### `isaaclab.utils`

- `class_to_dict` dumps a callable instance with fields as `{"_type":
..., **fields}`, so `env.yaml` records which source class was
configured.

### Port of the MDP1 example

- `Isaac-Lift-KukaAllegro-MDP2` now uses `mdp.reset_to_states` with the
core Lift sampler settings and, as MDP1, 1024 reset states per object
(`prototype_groups`), without recording.
- **Breaking (experimental task):** its task-local `reset_bank.py`, the
`reset_from_bank` term, and the `bank_size`, `history_length`,
`target_success_rate` and `kappa` parameters are removed. The changelog
gives the migration.
- `play_mode` changes the source only when it is a `FromTask`, so
playing from a `FromFile` keeps the file.
- At the same success rate, a state's weight relative to a 50%-success
state matches the old term within 2% (largest at 0% and 100%, where the
floors differ), across the 11 rates a 10-episode history can take. Draws
are not bitwise identical to `main`.
- `Isaac-Lift-Franka` (MDP1) is not ported: it has no MDP2 task yet.

---

## Performance

**Setup:** Kuka Allegro lift, 4096 worlds, Newton MJWarp, 300 steps × 3
repeats per run, each run started on an idle GPU.

- MDP1 runs `Isaac-Lift-KukaAllegro`; MDP2 runs
`Isaac-Lift-KukaAllegro-MDP2`.
- MDP2 rows use 16 reset states per world and ran twice, interleaved;
they are shown as `a / b`.
- MDP1 ran once.

> These numbers were measured before the change to 1024 reset states per
object and before the command `reset` hook, and have not been rerun
since. The GPU, software versions, warm-up and the revisions benchmarked
were not recorded with them, so read them as indicative only.

| Variant | Step (ms) | MDP-only step (ms) | Reset in graph (ms) | Reset
eager (ms) | `env.reset()` (ms) |
|---|---|---|---|---|---|
| MDP1 Lift, `conditional_reset` | 15.38 | 4.08 | 0.127 | 0.53 | 2.73 |
| MDP2 `main`, bespoke bank term | 10.50 / 11.40 | 0.231 / 0.234 | 0.080
/ 0.077 | 0.077 / 0.078 | 0.42 / 0.39 |
| MDP2 **this PR** | 10.47 / 10.56 | 0.289 / 0.292 | 0.067 / 0.068 |
0.39 / 0.40 | 0.76 / 0.84 |
| MDP2 this PR, without the `update` hook | 10.41 / 10.58 | 0.290 /
0.289 | 0.067 / 0.069 | 0.35 / 0.38 | 0.71 / 0.73 |

**What the numbers say**

- **Training step:** unchanged within noise. The 11.40 ms run on `main`
had a normal MDP-only time (0.234 ms), so its extra time was outside the
MDP.
- **Recording costs nothing measurable when it is off.**
- The no-hook variant really drops the hook: its plan has no
`UPDATE_STATE` step for `events.reset` (24 evaluate steps against 25).
- Its MDP-only step is the same within noise, so recording stays in one
term.
- ⚠️ **Regression: the MDP-only step grows by about 0.06 ms** (0.23 →
0.29 ms, about 0.6% of a full step).
- The reset events alone are *faster* in the graph, and the hook is not
the cause, so this is **not yet attributed**.
- ⚠️ **Regression: eager calls are slower.**
- Eager reset events take 0.39 ms against 0.08 ms on `main` (about 5×).
  - `env.reset()` takes 0.8 ms against 0.4 ms (about 2×).
- The likely cause is Python overhead in the library buffer and sampler.
It was not profiled.
- Captured steps don't pay it. Uncaptured steps (the torch backend, or
capture off) pay it on every step that resets.
- **Against MDP1:** a 32% shorter step and a 14× smaller MDP-only step.
MDP1 kept 1024 states per object prototype rather than 16 per world, so
this compares the two stacks, not the reset alone.

---

## Validation

### Tests

**`test_mdp2_reset_states.py`** (kitless, analytic scene)

- Generating: `FromTask` validity, and commands taken from the generator
task.
- Drawing: per-world draws, partial-reset isolation, shared origin
frames, and per-group draws and credit.
- Credit: goes to the slot the episode started from, only for episodes
that ended, not manual resets, including episodes that restore a goal
(`succeeded=mdp2.progress.done`).
- Commands: a restored goal stands over the resample while the scene
restores before it (Torch, Warp, and captured Warp), in a named subtask,
and when its task starts mid-episode.
- `env.update_task`: the reset states carry over to the updated task,
and split branches of one use keep their own.
- Recording: `record_if`, the fresh prior, the dropped credit, and only
in the worlds of its use.
- Pinning and the default reset fraction.
- Save and `FromFile`, with a world-count mismatch or missing group
labels rejected.
- **Bitwise torch == warp == captured**, with recording, pinning and the
default reset fraction on.
- Invalid configurations are rejected.

**Other files**

- `test_mdp2.py`: a reset event's `update` hook runs once per step.
- `test_reset_state_sampler.py`, `test_reset_states.py`: caller seeds,
`-1` draws only when opted in, `forget`, `set_state`.
- `test_lift_kuka_allegro.py` (Newton, 16 worlds):
- source overrides through `resolve_task_config`, and `play_mode` with
`FromFile`;
  - restore, and torch/warp parity;
  - one CUDA graph per step;
- a state recorded on the simulation and restored when its slot is
pinned.

### Mutation checks

Each of these broke a test (checked on `0e2c1e03f`; the regression tests
added since fail on that head):

- [x] dropping the credit on overwrite
- [x] flipping the default reset coin
- [x] a zero prior for new records
- [x] ignoring pins
- [x] removing the update scheduling
- [x] skipping the origin shift
- [x] harvesting commands from the main task

### Also run

- On the head: the `test/mdp2` suite of `isaaclab_experimental`,
`test_dict.py`, the reset API, MDP1 `test_lift_reset.py`, NIST
`test_nist_reset_monitor.py`, and Kuka MDP2 on GPU. **All pass.**
- `env.update_task(...)` on the Kuka env on GPU, with `truncate=True`
and `False`.
- `generate_reset_states.py` (then named `collect_reset_states.py`) ran
on Kuka through config resolution and `gym.make`, and saved reset states
that `FromFile` reloads identically.
- Not run here: the launcher step. `add_launcher_args` boots Kit, which
waits for its EULA in this environment.
- `pre-commit` and the changelog gate pass against `upstream/main`.

---

## Type of change

- New feature (non-breaking change which adds functionality)
- Breaking change for the experimental `Isaac-Lift-KukaAllegro-MDP2`
reset term and parameters (see Port of the MDP1 example)

## Checklist

- [x] I have read and understood the contribution guidelines
- [x] I have run the `pre-commit` checks with `./isaaclab.sh --format`
- [x] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] I have added a changelog fragment under
`source/<package>/changelog.d/`

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation isaac-lab Related to Isaac Lab team

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant