Repository navigation
[release/3.1.0] Backport MDP2 resets, tracked tasks, and Newton contact history fix - #9362
Conversation
…filter object (isaac-sim#9297) ## Description `update_contact_sensor_kernel` ran one thread per (env, sensor) and looped over the filter objects, so the force-matrix history copies strided through memory. It now launches one thread per (env, sensor, filter object); the `f == 0` thread of each sensor rolls the per-sensor buffers and air/contact times as before. ```python # before wp.launch(update_contact_sensor_kernel, dim=(num_envs, num_sensors), ...) # after wp.launch(update_contact_sensor_kernel, dim=(num_envs, num_sensors, max(num_filter_objects, 1)), ...) ``` Sensors without filter objects launch one thread per sensor, as before. ## Performance G1 self-contact sensor (30 bodies × 30 filter bodies, `history_length=4`), 4096 envs, RTX PRO 6000: | | Before | After | |---|---|---| | Kernel alone (all envs updated) | 3.28 ms | 0.51 ms (6.4×) | | In the G1 motion-tracking task, per physics substep | 2.2 ms | 0.5 ms | The sensor updates every substep (4 per env step), so the task's env step drops by about 7 ms. ## Tests - `test_contact_sensor_history.py`: launch dim updated to `(2, 1, 1)`; newest-first ordering and env mask still checked. - `test_contact_sensor.py`: 28 passed, 3 skipped. `test_resting_object_contact_force[kamino*]` fails locally on `main` without this change too. ## Type of change - Performance improvement (non-breaking) ## Checklist - [x] I have run the `pre-commit` checks on the changed files - [x] I have added a changelog fragment - [x] I have updated the tests (cherry picked from commit 121fc81)
# 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 isaac-sim#9119. > **Built on:** the reset-state API that isaac-sim#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** (isaac-sim#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 <[email protected]> (cherry picked from commit 880939c)
# Description Ports Arena's [tracked events](https://isaac-sim.github.io/IsaacLab-Arena/main/pages/concepts/task/concept_progress_tracking_design.html#tracked-events) to MDP2. A tracked event records when something of interest happens, such as an object being dropped, without changing what counts as success. An event is built from the same pieces as success (`Milestone`, `hold`, `sequence`), plus two flags: | Flag | Effect | | --- | --- | | `repeat=True` | Counts every occurrence, and records the step of each one. | | `tracked=True` | Keeps the event out of the task's success and score. | ## Usage ### 1. Define the event beside the task ```python from isaaclab_experimental import mdp2 TASK = mdp2.compose( BASE, place=PICK_AND_PLACE, # The task: decides success and score dropped_object=mdp2.sequence( # An event: lifted, then resting outside the bowl lifted=mdp2.Milestone(q.lifted_and_grasped, hold=10), dropped=mdp2.Milestone(q.resting_outside_bowl, hold=10), repeat=True, tracked=True, ), slipped=mdp2.Milestone(q.slipped, repeat=True, tracked=True), # An event of one condition ) ``` ### 2. Read it during training Tracked events are logged like any other task, and they don't change `Progress/task`: ```python _, _, _, _, extras = env.step(actions) extras["log"]["Progress/dropped_object"] # Share of the last episodes with at least one drop extras["log"]["Progress/task"] # Success rate, unaffected by the drops ``` The live state is in `mdp2.progress.dropped_object.{count, done_at, ...}`, for observations, rewards, or terminations. ### 3. Get per-episode results and the full timeline With an episode budget, `episode_records()` gives one row per episode. Set `record_episode_events` and the new `episode_events()` also gives one row per occurrence: ```python cfg.episode_budget = 100 cfg.record_episode_events = True # Opt-in; needs a time limit env = MDP2RLEnv(cfg) obs, _ = env.reset() while env.episodes_completed < cfg.episode_budget: obs, *_ = env.step(policy(obs)) records = env.episode_records() records["progress/task"] # Step the task was done, -1 if not records["progress/dropped_object/count"] # Drops per episode drops = env.episode_events()["dropped_object"] drops["world"], drops["episode"], drops["step"] # One row per drop, sorted by world, episode, step ``` To get Arena's per-episode list of `{name, step}`, join the event rows to the records on `(world, episode)`. ## How it works - **`tracked`:** a tracked subtask keeps all of its own progress, but `TaskTree.counted` filters it out. `counted` is the single place that drives a parent's completion and score in both backends. Only subtasks that run together (`compose`) can be tracked. Tracking a subtask of a sequence, choice, or split, or the root, is a builder error. - **`episode_events()`:** each repeating task sets an internal `occurred` flag in the step it is done, in both backends. A parent's restart doesn't clear the flag, so an event inside a repeating task is recorded even when the parent restarts in the same step. The env's existing fused per-world log kernel, inside the captured step, writes a row wherever the flag is set. There are no new kernel launches and no host syncs. - **Capacity:** the buffer holds `episode_budget × max_episode_length` rows per repeating task. A task repeats at most once per step, so this always fits, and there is no capacity setting. It is allocated only with `record_episode_events=True` (default `False`). ### Performance Event recording adds no measurable cost: | | ms per step, 5 runs | median | | --- | --- | --- | | Recording off | 0.514 – 0.519 | 0.518 | | Recording on | 0.512 – 0.518 | 0.516 | - **Setup:** Cartpole on Newton (MJWarp), 4096 worlds, captured step, one repeating tracked task, `episode_budget=100_000`. Each run: 50 warm-up steps, then 1000 timed steps. - **Comparison:** commit `ad129e6fa`, with and without the recording block in `_bind_logs`. Runs alternated. - **Hardware and versions:** RTX PRO 6000 Blackwell, driver 595.99, torch 2.11, Warp 1.17. ## Limitations - **Main task gets a name.** Adding an event makes the main task a named subtask (`place=` above). That prefixes its use names, progress paths, and observation names, for example `goal` becomes `place.goal`. Observation slices and widths don't change, so policies and checkpoints still load. - **Opt-in, with a time limit.** `episode_events()` needs `record_episode_events=True`; without it, nothing is allocated and the call raises. The flag needs a time limit, since that sizes the buffer, and raises at construction otherwise. Counts are recorded either way. - **New `sequence` flags.** `sequence` now takes `repeat` and `tracked` as keyword arguments, so a subtask can no longer be named `repeat` or `tracked`. Passing a task under those names raises a `TypeError` rather than dropping it. All other changes are additive: `tracked` is the last field of `TaskCfg`, so positional arguments keep their meaning. - **Memory.** When on, the buffer is worst-case: 12 bytes per row, for example about 72 MB per repeating task for 100k episodes of 60 steps, or about 1.2 GB for 1000-step episodes. ## Type of change - New feature (non-breaking change which adds functionality) ## Validation - **`test_mdp2.py`** (both backends, eager and captured): - a tracked milestone; - Arena's dropped-object sequence, counted twice beside the task; - a task whose only completion is tracked; - errors for tracking a subtask of a sequence, choice, or split, or the root. - **`test_mdp2_env.py`:** - A tracked task that is never done leaves `Progress/task` and `progress/score` at 1. - A budget runs a second episode in one world, with the event done on each episode's first and last step. Per episode, the rows match `count`, and the first row's step matches `done_at`. - An event inside a repeating task, done in the step its parent restarts, is recorded once per episode. - **Mutation checks:** - Removing the `counted` filter turns the tracked-task tests red. - Removing any of the event guards turns the event test red. The guards are: the active-world mask, counting worlds that just ended, and the episode-index correction. - Letting a parent's restart clear the `occurred` flag (the bug that greptile found) also turns it red. - All 93 tests in `test/mdp2` and `test/envs/test_mdp2_env.py` pass locally. `uv run isaaclab --format` and the changelog check pass. ## Checklist - [x] I have read and understood the [contribution guidelines](https://isaac-sim.github.io/IsaacLab/main/source/refs/contributing.html) - [x] I have run the [`pre-commit` checks](https://pre-commit.com/) with `uv run isaaclab --format` - [x] I have made corresponding changes to the documentation - [x] My changes generate no new warnings - [x] I have validated the changed behavior with focused coverage and applied the [test-audit criteria](https://github.com/isaac-sim/IsaacLab/blob/HEAD/skills/developer/test-audit/SKILL.md) to any test changes - [x] I have added a changelog fragment under `source/<pkg>/changelog.d/` for every touched package (do **not** edit `CHANGELOG.rst` or bump package versions — CI handles that) - [x] I have added my name to the `CONTRIBUTORS.md` or my name already exists there (cherry picked from commit 5fa33d1)
|
run-ci |
There was a problem hiding this comment.
Isaac Lab Review Bot
Needs attention: Scope and over-engineering (1), Compatibility and deprecation (6), Implementation (2), Style consistency (4), Test quality (2). Other reviewed categories look good.
- PR description: Clarify that generation and saving run outside capture, disclose compatibility breaks, and substantiate the changelog’s 4× claim with baseline/candidate revisions, command, hardware, backend, environment count, warmup, environment details, and latency.
- Design and architecture: Architecture looks good.
- Scope and over-engineering: Minimal implementation: extend ResetStateBuffer, ResetStateSampler, MDP2 planning, and MDP2RLEnv; keep reset_states.py for its persistent lifecycle and generate_reset_states.py for its CLI contract; delete recording-only allocations when disabled, retaining source→sample→restore flow. Suggested PR breakdown: Newton history with sensor validation; core reset APIs and serialization with compatibility tests; MDP2 resets and Lift migration with capture tests; tracked tasks and event reporting with budget tests.
- API: API changes look good.
- Compatibility and deprecation: Breaking changes: tensor YAML contents, sequence subtask names, scoped command outputs, and Lift imports, overrides, and defaults change without deprecation bridges; preserve old contracts with targeted warnings, migration and removal guidance, and transition tests.
- Implementation: Grouped pinning converts every negative slot into the sampling sentinel, so invalid pins unexpectedly draw states; reserve only -1 for sampling.
- Style consistency: ResetStates documentation incorrectly promises allocation-free pinning and counts started rather than credited episodes; correct those public claims.
- Test quality: The event-budget test never steps after exhaustion, and the default-reset test lacks earlier writers and completed outcomes; extend those cases to exercise their claimed contracts.
Needs rework. Posted 15 inline findings.
Automated review; human maintainers own approval decisions.
|
|
||
| _Dumper.add_multi_representer( | ||
| torch.Tensor, | ||
| lambda dumper, tensor: dumper.represent_str(f"tensor(shape={list(tensor.shape)}, dtype={tensor.dtype})"), |
There was a problem hiding this comment.
🔴 Critical · Compatibility — Preserve tensor values in YAML
dump_yaml now replaces tensor contents with shape-and-dtype strings for every caller. Existing value-bearing dumps change irreversibly; keep the old output functional and make summaries opt-in or provide a complete deprecation transition.
| params.pop("record", None) # only the generated states | ||
|
|
||
| with launch_simulation(env_cfg, args_cli): | ||
| env = gym.make(args_cli.task, cfg=env_cfg) |
There was a problem hiding this comment.
🟡 Warning · Implementation — Close the environment on failure
If lookup or save raises, env.close() is skipped. Wrap the constructed environment’s work in try/finally and close it there.
| from .. import to_dict | ||
|
|
||
|
|
||
| class _Dumper(yaml.Dumper): |
There was a problem hiding this comment.
🟡 Warning · Style Consistency — Move the private dumper below APIs
_Dumper precedes load_yaml and dump_yaml, contrary to the prescribed public-functions-before-private-classes order. Move its definition and registration below those functions.
| return cfg | ||
| changes = {"inputs": {arg: scope.get(selector, selector) for arg, selector in cfg.inputs.items()}} | ||
| if isinstance(cfg, Event): | ||
| changes["outputs"] = {arg: scope.get(selector, selector) for arg, selector in cfg.outputs.items()} |
There was a problem hiding this comment.
🟡 Warning · Compatibility — Preserve event output bindings
A subtask event output bound to commands.goal now resolves to its local command instead of the previously bound root command. Keep the old target functional while introducing explicit scoped output binding.
|
|
||
|
|
||
| def sequence(**subtasks: TaskCfg) -> TaskCfg: | ||
| def sequence(*, repeat: bool = False, tracked: bool = False, **subtasks: TaskCfg) -> TaskCfg: |
There was a problem hiding this comment.
🟡 Warning · Compatibility — Preserve sequence subtask names
sequence(repeat=task) and sequence(tracked=task) previously named subtasks; they now raise TypeError. Continue accepting task-valued arguments under those names while warning and documenting their replacement.
| env.reset() | ||
| for _ in range(3 * env.max_episode_length): | ||
| env.step(torch.zeros(NUM_ENVS, 1, device=env.device)) | ||
| if env.episodes_completed == cfg.episode_budget: |
There was a problem hiding this comment.
🟡 Warning · Test Quality — Step after the budget expires
The test stops when the budget is spent, so it cannot detect events recorded afterward by worlds that keep stepping. Take further steps and assert event rows remain unchanged.
| assert reset_states.episode_counts[1, 2] == 0 and (reset_states.states["joint_pos"][1, 2:, 0] == 0.2).all() | ||
|
|
||
|
|
||
| def test_default_resets_keep_the_earlier_events_and_are_not_credited(): |
There was a problem hiding this comment.
🟡 Warning · Test Quality — Exercise the claimed default-reset behavior
This test has no earlier reset writer or completed episode, so it cannot detect lost earlier writes or wrongly credited default resets. Add both conditions before asserting their outcomes.
| "target_success_rate": 0.5, | ||
| "kappa": 1.0, | ||
| # A world per object, as in small test runs, needs a roll per state. | ||
| "source": mdp.FromTask(RESET_STATE_GENERATOR, num_states=1024, max_rolls=20000), |
There was a problem hiding this comment.
🟡 Warning · Compatibility — Preserve Lift reset overrides
Existing overrides for candidates, bank_size, history_length, target_success_rate, and kappa no longer configure this task. Accept and translate them with targeted warnings during the documented migration.
| "kappa": 1.0, | ||
| # A world per object, as in small test runs, needs a roll per state. | ||
| "source": mdp.FromTask(RESET_STATE_GENERATOR, num_states=1024, max_rolls=20000), | ||
| "groups": mdp.prototype_groups, |
There was a problem hiding this comment.
🟡 Warning · Compatibility — Keep the existing reset default
The registered Lift task changes from 16 states per world to 1024 shared per object, changing its training distribution. Preserve the former default during a documented, warned transition.
| if descriptor is not None: | ||
| values = states.pop("descriptor") | ||
| span = (values.amax(dim=(0, 1)) - values.amin(dim=(0, 1))).clamp(min=1e-6) | ||
| kept = _farthest_points(values / span, bank_size) |
There was a problem hiding this comment.
🟡 Warning · Compatibility — Retain the Lift reset entry point
Deleting reset_from_bank breaks existing imports and event configurations. Keep the old term functional with a targeted deprecation warning, migration guidance, and tests for both paths.
Confidence Score: 4/5
[High impact] The PR reaches reset behavior and task tracking across MDP2, shared reset tools, and Newton sensors. The PR appears safe to merge, with two non-blocking improvements to error reporting and test coverage. FindingsSummaryBackports stored reset states, tracked tasks, per-occurrence episode records, and the Newton contact-history update to
Diagram%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[Source generates or loads states] --> B[Stored reset states]
C[Step computes rewards and endings] --> D[Record visited states]
D --> B
C --> E[Reset credits the ended episode]
E --> F[Sampler chooses a state or uses a pin]
B --> F
F --> G[Restore scene fields]
G --> H[Commands resample]
H --> I[Restore saved commands]
Reviews (1) · Last reviewed commit: "Add tracked tasks and per-occurrence eve..." · Reviewed by Greptile |
| if self._events is None: | ||
| raise RuntimeError("Set 'record_episode_events' to record the times that repeating tasks are done.") |
There was a problem hiding this comment.
Missing budget gives wrong error
episode_events() reads self._events, but that attribute is created only when episode_budget is set. Calling this method on a normal training environment raises AttributeError instead of explaining the missing setting. Check the budget first or initialize the event attributes for every environment, and test the no-budget case.
| wp.launch( | ||
| update_contact_sensor_kernel, | ||
| dim=(2, 1), | ||
| dim=(2, 1, 1), |
There was a problem hiding this comment.
Extra filter threads are untested
The updated history test still launches only one filter thread, so it never exercises f > 0, which is the behavior this change adds. The test could pass even if later filters have broken histories. Add several filter objects with different forces and check every filter's history. Also check that total-force histories and air/contact timers advance only once per sensor.
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
Description
Backport #9297, #9112, and #9323 to
release/3.1.0. These merged tomainafter the release branch was cut. The first MDP2 parts (#9016, #9120) are already on the release branch.TaskCfg.tracked) and per-occurrence events (MDP2RLEnv.episode_events(), opt-in withrecord_episode_events), for Arena's tracked events.Cherry-picked with
-x, in merge order, from121fc8113,880939cae, and5fa33d124. All three applied without conflicts or manual edits, and their stable patch IDs match the original commits. The original changelog fragments are included.Type of change
Validation
Pre-commit hooks pass on all changed files, with
ISAACLAB_CHANGELOG_BASE_REF=upstream/release/3.1.0.The changelog check against
upstream/release/3.1.0passes, and so doesgit diff --check.Every touched test file passes locally on this branch:
isaaclab_experimental:test_mdp2.py63 passed,test_mdp2_env.py31 passed,test_mdp2_reset_states.py19 passedisaaclab_tasks_experimental:test_lift_kuka_allegro.py6 passedisaaclab:test_reset_state_sampler.py11,test_reset_states.py8,test_dict.py12,test_yaml_io.py5 passedisaaclab_newton:test_contact_sensor_history.py2 passedHardware: RTX PRO 6000 Blackwell, Linux. Full CI has not run yet.
Checklist