Repository navigation
MDP2 Reset Viewer - #9119
MDP2 Reset Viewer#9119StafaH wants to merge 17 commits into
Conversation
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.
[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
SummaryAdds tools to generate and inspect MDP2 reset states, plus Viser and Newton controls for browsing and playing episodes.
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
Reviews (2) · Last reviewed commit: "Format the reset viewer test" · Reviewed by Greptile |
| 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) |
There was a problem hiding this comment.
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.
| def save(self, path: str) -> None: | ||
| """Save the bank, to fill later runs with ``mdp.FillFromFile``.""" | ||
| self.bank.save(Path(path)) |
There was a problem hiding this comment.
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
| if self.playing: | ||
| self.env.step(self.policy(self.env.observations)) |
There was a problem hiding this comment.
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] |
There was a problem hiding this comment.
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.
| 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] |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
🔴 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) |
There was a problem hiding this comment.
🔴 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(): |
There was a problem hiding this comment.
🟡 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.") |
There was a problem hiding this comment.
🟡 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): |
There was a problem hiding this comment.
🟡 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)] |
There was a problem hiding this comment.
🟡 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): |
There was a problem hiding this comment.
🟡 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), |
There was a problem hiding this comment.
🟡 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) | ||
|
|
||
|
|
There was a problem hiding this comment.
🟡 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() |
There was a problem hiding this comment.
🟡 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.
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.
60082fe to
d433603
Compare
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.
d433603 to
f3a009c
Compare
| 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)] |
There was a problem hiding this comment.
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
| 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) |
There was a problem hiding this comment.
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.
# 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>
Description
MDP2 Reset Viewer: see the reset states of an MDP2 task, and interact with them, in Viser or the Newton viewer.
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--taskreset_to_statesevent--num_envs16--eventreset_to_stateseventreset--statesFromFile) instead of generating them--policyzeroorrandomzeroOpen the printed Viser URL and use the Reset states folder in the sidebar.
What you can do
slot k | successacceptedorrejected, by its terminationsThe panel also has:
sourceorrecorded), success rate, episode count, and probability of the next draw. The world's current slot is starred. Withgroups(one set per object), the table shows the world's group.FromFileand--statescan load.Use it from Python
You can drive it without any UI, for example in tests or notebooks:
Panels call
viewer.request("show", 3)instead, which is safe from any thread.Design
ResetStateVieweris a UI-agnostic controller overmdp.get_reset_statesfrom MDP2 Resets #9112.ResetStates.pin.mdp.StateGenerator.env.step.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.step_dt, so they play no faster than real time. A paused view renders at 30 frames per second.ResetStates.skip_current_episodes()first.ViserResetStatePanel: a sidebar folder plus a label above every world (up to 64), through the new publicViserVisualizer.server.NewtonResetStatePanel: an ImGui panel throughregister_ui_callback.Verification
Tests:
test_mdp2_reset_viewer.py(Newton, 8 worlds)ViserServer, the panel's table, status, slot control and labels follow the controller.By hand
step_dt.Not verified
add_launcher_argsboots Kit here, which waits for its EULA. Everything after the launcher (resolve_task_config,gym.make,FromFile, the viewer) ran directly.Type of change
Checklist
pre-commitchecks with./isaaclab.sh --formatsource/<package>/changelog.d/