Repository navigation
Add native reset-state utilities for existing tasks - #8872
Conversation
Integrate upstream main at 6d37745 to keep the branch current with shared API and dependency changes. Validate the merged revision with focused checks and all repository formatting and lint hooks. Remote CI remains separate.
Integrate upstream main at 908e849 to keep the branch current with shared API and dependency changes. Validate the merged revision with focused checks and all repository formatting and lint hooks. Remote CI remains separate.
Integrate upstream main at c498443 while preserving the branch behavior and source history. Validate the merged revision with focused checks and the required repository hooks. Remote CI remains separate.
|
Consolidated into #8960 at the requested single-PR review boundary. The shared ResetStateSampler, sampling strategies and NIST compatibility imports are retained there. Closing this separate PR for now; the standalone extraction branch and review history remain available if maintainers later prefer a split. |
Collect reusable reset-state catalogs with bounded generation and task-defined acceptance checks. Reuse the sampler from isaac-sim#8872 to keep outcome tracking and row selection in one implementation. Add a sparse Franka cube reference with an immediate commanded goal, physical reset generation, and per-environment evaluation quotas.
StafaH
left a comment
There was a problem hiding this comment.
Couple issues I see in the overall design:
- Why is the buffer split from the rest of the implementation? Either all of it should go in core or all of it should go in tasks?
- The implementation is very torch-based, instead of warp native and torch-shimmed. This will mean we have to change it again for MDP2.
- We want it to be mask native as well (with ids as a shim into masks)
- The NIST code is mixing legacy code, we should just remove the legacy code and migrate completely to the new API
- The demo should be an event term (Like how NIST is already doing it), looks like the demo is something completely different.
I mentioned it inline, but I feel like the demo for this is very straightforward. Add a new event term that is driven by reset to one (or more) of the existing tasks, rather than creating a new task and new code.
|
Addressed the design review in e6b5b9c74.
Validation: 55 tests passed, real Lift captured replay and NIST smoke/explicit replay passed, and clean strict Sphinx plus full formatting/changelog checks passed. The Kit-only base-environment suite could not run locally because Isaac Sim is absent. Checked actual MDP2 #9016 at |
Withdrawing my request for changes to remove the merge block.
|
Readability follow-up in 93c9f6160:
Public API behavior, outcome ordering, and graph storage are preserved. All 16 affected tests passed, including real GPU capture, viewer attribution, and reseeding; full formatting/changelog checks and a clean strict documentation build passed. |
# 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
Adds a Warp-native reset-state API in
isaaclab.envs.resetand uses the existing Lift reset event as its reference. Tasks keep control of candidate generation, physical acceptance checks, and restoration.ResetStateBufferowns prepared array snapshots, supports empty banks and broadcasting one default state, and gathers into preallocated outputs with a full-environment mask.ResetStateSamplerrecords completed outcomes against previous assignments before selecting replacements. It supports explicit catalog IDs, asset-group partitions, and scores driven by named metrics. The default combines a Beta score peaked at 50% recent success with a uniform floor.Runtime uses Warp arrays and kernels; Torch inputs and environment IDs are boundary shims. Persistent storage is reused during CUDA graph replay. The sampler owns its per-environment random streams and supports explicit reseeding in place.
flowchart LR P["Task prefill and checks"] --> B["Core state buffer"] O["Previous outcome"] --> S["Score and select IDs"] S --> G["Masked gather"] B --> G G --> W["Native mask writers"] W --> E["Episode"] E --> OLift's existing
conditional_resetretains initialization-time validation and optional diversity selection. Its replay restores physical state and controller targets through public mask writers, excludes unfinished viewer resets, and uses the shared sampling policy.NIST keeps its existing success monitor for outcome history and reporting. The native sampler uses the monitor’s rates as an input metric. Migration notes cover the changed Lift and NIST configuration fields.
Validation
Focused reset buffer, sampler, manager, and Lift tests passed, including CUDA graph replay on Newton/MJWarp. A two-environment NIST smoke verified 16 prepared states, explicit replay, independent outcome history, and adaptive weights. Earlier capture validation against MDP2 #9016 exercised native Warp launch hooks and zero-copy Torch shims on an analytic scene.
Full formatting/lint, changelog checks, and clean strict Sphinx passed. The Kit-only base-environment suite needs CI because Isaac Sim is absent locally.