Skip to content

MDP2 Resets - #9112

Merged
StafaH merged 23 commits into
isaac-sim:mainfrom
StafaH:mh/mdp2-resets
Dec 1, 2026
Merged

StafaH merged 23 commits into
isaac-sim:mainfrom
StafaH:mh/mdp2-resets

Conversation

@StafaH

@StafaH StafaH commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

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:

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:

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

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:

"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 (MDP2 Reset 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

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

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

"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

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

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

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

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

  • dropping the credit on overwrite
  • flipping the default reset coin
  • a zero prior for new records
  • ignoring pins
  • removing the update scheduling
  • skipping the origin shift
  • 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

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

@StafaH
StafaH requested a review from a team November 19, 2026 23:28
@github-actions github-actions Bot added documentation Improvements or additions to documentation isaac-lab Related to Isaac Lab team labels Nov 19, 2026

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Isaac Lab Review Bot

Needs attention: Scope and over-engineering (2), Compatibility and deprecation (3), Implementation (4), Style consistency (5), Test quality (4). Other reviewed categories look good.

  • PR description: Correct the 1% weighting claim, shorten repeated design prose, and supplement supplied Kuka timings with baseline/candidate revisions, command, GPU, software versions, warmup, and timing method; backend, 4096 worlds, and metrics are specified.
  • Design and architecture: Architecture looks good.
  • Scope and over-engineering: Minimal implementation: Extend ResetStateSampler and eager.TermContext; keep mdp/reset_states.py for bank initialization and capture warmup, collapse both one-call fill classes into configured functions, and keep diversity selection private. Retain fill, credit, draw, gather, and commit. Replace with one smaller PR: these owners, Kuka configuration, exports, documentation, and focused tests covering seeds, frames, outcome attribution, and captured physical restoration.
  • API: API changes look good.
  • Compatibility and deprecation: Breaking changes: Kuka’s reset import, configuration keys, and persistent term-state fields disappear without functional bridges; retain them through targeted warnings, migration documentation, removal guidance, and transition coverage.
  • Implementation: Origin conversion assumes one pose per world, so component-shaped writable transform fields fail during filling or restoration; support their component dimensions in both conversions.
  • Style consistency: sampler_arrays documents copies but returns borrowed views, obscuring mutation ownership; correct its docstring to describe shared storage.
  • Test quality: Copying every private sampler array couples Kuka coverage to scratch storage; use independently initialized samplers while retaining distinct seed, frame, determinism, backend-parity, and physical-restoration coverage.

Significant concerns. Posted 18 inline findings.

Automated review; human maintainers own approval decisions.

@greptile-apps

greptile-apps Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] The PR changes reset behavior in MDP2 and the shared reset-state APIs.

Keep this PR open until saved groups can distinguish objects that happen to receive the same group number.

Findings

  1. P1 Saved groups lose object identity ▶
  2. P2 Local poses get shifted. ▶
  3. P2 Rejected replay changes the start ▶

Summary

Adds stored reset states to MDP2 through reset_to_states.

  • MDP2 worlds can restart from stored states chosen for each episode.
  • Reset events can record each step and restore commands after they resample.
  • Reset buffers and samplers can update stored starts as episodes run.
  • Kuka Allegro lift worlds share reset states with worlds that spawned the same object.
  • Callable config objects save their fields instead of failing to serialize.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  Source["FromTask / FromFile / FromTensors"] --> Buffer["ResetStateBuffer"]
  Outcomes["Ended episode outcomes"] --> Sampler["ResetStateSampler"]
  Pins["Pinned slots"] --> Sampler
  Sampler --> Gather["Gather selected states"]
  Buffer --> Gather
  Gather --> Outputs["Event outputs"]
  Visited["Visited states"] --> Buffer
Loading

Reviews (3) · Last reviewed commit: "Rename the MDP2 reset bank API to reset ..." · Reviewed by Greptile

@StafaH
StafaH marked this pull request as draft November 20, 2026 00:32
This was referenced Nov 20, 2026
@StafaH
StafaH marked this pull request as ready for review November 20, 2026 20:56
@maxkra15

maxkra15 commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Thanks Mustafa, I like that this builds on the reset buffer and sampler- ran the reset-state tests (12 passed) and hit two things I'd fix before merging.

  • An explicit reset credits episodes that are still in progress. In a two-world probe both worlds had done=False, and resetting them took the sampler count from 0 to 2. Can we use the completed-episode mask for credit? It's easy for a plain env.reset() caller to miss skip_current_episodes().
  • The recording hook gets a world mask but doesn't use it. I put the recorder in worlds 0–1 and it replaced the slots in worlds 2–3 as well, on both Torch and Warp. Please pass the mask through to the recording kernel.

I d also keep the current state_ids=-1 behavior in the shared sampler and make mixed pin-and-sample requests opt in. Otherwise the same MDP1 call can start changing assignments after this lands.

there's a conflict with #9120 in plan.py, so we should check command restore and stage entry together when Part 2 rebases

kellyguo11 pushed a commit that referenced this pull request Nov 27, 2026
# Description

**MDP2 Part 2** is the second update of MDP2 (#9016). It collects two
lines of work:
- the MDP2 features prototyped for [Isaac Lab
Arena](https://github.com/isaac-sim/IsaacLab-Arena) in #9091, without
its pick-and-place example;
- the remaining follow-ups of #9016.

The theme is **training in many ways from one compiled MDP**. Tasks are
built from tasks, values and switches change per world while the CUDA
graphs keep replaying, and policies see a named interface.

Tasks that use none of this compile to **byte-identical MDP kernels**,
and every MDP2 task now steps **15 to 34 µs faster than on `main`**,
because the env keeps its episode logs in one generated kernel. Resets
from a bank of states are developed separately in #9112.

**Contents**
1. [Tasks made of tasks](#1-tasks-made-of-tasks): `compose`, `sequence`,
`split`, `choice`, progress
2. [Changing a task while it
trains](#2-changing-a-task-while-it-trains): `Tunable`, `when`,
`update_task`, variations
3. [Actions](#3-actions): name slots, actions in stages, control rate
4. [Using a part twice](#4-using-a-part-twice): `rename`
5. [The policy interface](#5-the-policy-interface): `spec`, masks
6. [Evaluation, from Arena](#6-evaluation-from-arena): episode budget,
records, cameras, `resting_on`
7. [Any physics backend](#7-any-physics-backend): capture through the
physics manager
8. [Performance](#performance) · [Breaking changes](#breaking-changes) ·
[Not in this PR](#not-in-this-pr)

**At a glance**

| You want to | Use |
|---|---|
| Build a task in steps, or from a scene, an embodiment and a task |
`mdp2.sequence`, `mdp2.compose`, `mdp2.Milestone` |
| Train different tasks in different worlds | `mdp2.split` (fixed
worlds), `mdp2.choice` (drawn per episode) |
| Read how far a task got | `mdp2.progress.<task>.done`, `.active`,
`.score`, `.count`, ... |
| Change a reward weight or a param during training | `mdp2.Tunable`,
`env.tune(...)` |
| Turn a term on or off per world | `when=<field>`,
`when=mdp2.Tunable(True)` |
| Edit the task of a running env | `env.update_task(task)` |
| Randomize a value per episode, record it, replay it |
`mdp.variation(..., mdp.Uniform / Choice / Replay)` |
| Run an embedded controller once per control step |
`rate=mdp2.ActionRate.CONTROL` |
| Use one part for two robots | `mdp2.rename(part, robot="left_arm")` |
| Know which policy column is what | `env.mdp.spec()`, `action_mask`,
`observation_mask` |
| Run a fixed number of evaluation episodes | `episode_budget`,
`env.episode_records()` |

---

## 1. Tasks made of tasks

A task can say when it is done, and it can hold named subtasks, which
are tasks too. Four functions combine them:

| Function | Subtasks run | The task is done when |
|---|---|---|
| `compose(a=..., b=..., require=k)` | together | `k` of them are (all
by default) |
| `sequence(a=..., b=...)` | one after another; the next starts the step
after | the last is |
| `split(a=..., b=..., worlds={"a": 3072, "b": 1024})` | each in its own
worlds | the world's own is |
| `choice(a=..., b=..., weights={"a": 3, "b": 1})` | one per episode and
world, drawn at the reset | the drawn one is |

### Sequences

```python
q = mdp2.quantities
TASK = mdp2.compose(
    BASE,                                                      # observations, action rate, time limit
    mdp2.sequence(
        reach=mdp2.TaskCfg(rewards={"reach": ...}, done=q.near_object),
        grasp=mdp2.TaskCfg(rewards={"grasp": ...}, done=q.grasped, hold=3),
        lift=mdp2.Milestone(q.lifted, hold=10),               # lifted for 10 steps in a row
    ),
)
success = mdp2.Termination(mdp.is_true, inputs={"value": mdp2.progress.done})
```

- **Done.** `done=` is a field of one value per world. `hold=n` asks for
it on `n` steps in a row.
- **Uses.** A task of a sequence runs its uses only while it is active,
and they restart when it starts.
- **Shared uses.** Uses that the tasks of a sequence define alike are
one op, so a shared action-rate term or observation history carries on
across stages.

<!-- GIF: mdp2_sequence.gif -->

*Recorded from 4,096 Cartpole worlds drifting along the rail. Each row
is a world, each color the task it runs, and a gap is a reset.*

### Progress

Every task's progress is a set of fields that any term can read:

```python
mdp2.progress.done                   # the whole task
mdp2.progress.grasp.done             # a subtask; also .holding .active .score .done_at .started_at .stage .count
```

| Field | Meaning |
|---|---|
| `done` | done once, until the episode ends |
| `holding` | its completion holds at this step |
| `active` | it runs at this step |
| `score` | in `[0, 1]`: its subtasks done, weighted by their `score=` |
| `done_at`, `started_at` | episode step it was first done (-1 before)
and last started |
| `stage` | the subtask a sequence or a choice runs |
| `count` | how often a task with `repeat=True` was done |

```python
mdp2.Milestone(q.dropped, repeat=True)                                # counts drops: progress.dropped.count
mdp2.Event(spawn_target, outputs={...}, mode=mdp2.EventMode.START)   # writes the scene when its task starts
```

- **Names.** A subtask reads its own commands, quantities, term state,
tunables and progress by name, as a task alone does. Inner names win.
- **Logs.** `Progress/<task>` is the share of the last episodes in which
each task was done.
- **Reset order.** Reset events run before progress restarts, so a
curriculum can read the milestones of the episode that ended.

### Splits and choices

```python
TASK = mdp2.compose(BASE, mdp2.split(walk=WALK, stand=STAND, worlds={"walk": 3072, "stand": 1024}))
TASK = mdp2.compose(BASE, mdp2.choice(walk=WALK, stand=STAND, weights={"walk": 3, "stand": 1}))
```

- **Split.** Each subtask runs in fixed worlds. A split may be a step of
a sequence, and several splits divide the same worlds.
- **Choice.** It draws one subtask per episode and world, which is
multi-task training in one run. `progress.stage` is the drawn index, and
`Progress/<task>` logs each task over the worlds that drew it.

<!-- GIF: mdp2_choice.gif -->

*The left grid is set by the config. The right grid is recorded: each
cell is a world colored by its drawn task, and it redraws at every
reset.*

---

## 2. Changing a task while it trains

### Tunable values

```python
track = mdp2.Reward(
    mdp.track_lin_vel_xy_exp, ...,
    params={"std": mdp2.Tunable(0.5)},
    weight=mdp2.Tunable(1.5),
)

env.tune("rewards.track.weight", 3.0)                                   # each world at its next reset
env.tune("rewards.track.std", 0.25, worlds=slice(0, 2048), at="step")  # from the next step
```

- **What it is.** A `Tunable` param is a field of one value per world. A
`wp.func` gets its world's value, as for any param. A tunable weight is
the reward's column of `state.reward_weights`.
- **Reading and writing it.** Other terms read a param, and events write
it, for example a curriculum: `mdp2.tunable("rewards.track", "std")`.
- **No recapture.** `tune` writes in place, so the captured graphs keep
replaying.
- **When it applies.** With `at="reset"` (the default), the value waits
in a pending copy that the reset kernel applies, so no episode mixes two
values. Each value has its own pending bit, so a reset leaves values
that events wrote alone.
- **Revisions.** Each world counts the tunings that took effect in
`state.revision`, and the episode records keep that count.

<!-- GIF: mdp2_tune.gif -->

*Recorded: one Cartpole run tunes the left half of the worlds at their
next reset and the right half from the next step.*

### Switches

```python
mdp2.Reward(..., when=mdp2.commands.standing)          # runs where the mode command is positive
mdp2.Reward(..., when=mdp2.Tunable(True))              # a switch per world
env.tune("rewards.feet_air_time.when", False, worlds=eval_worlds)
```

- **Where it works.** `when=` takes any field, on a reward, termination,
observation, command or interval event.
- **Timing.** The field is read at the start of the step, the same rule
as for stages.
- **Off and on.** The use outputs zero while it is off, and it restarts
where it turns on.

### Editing a running task

```python
env.update_task(mdp2.compose(env.cfg.task, mdp2.TaskCfg(rewards={"new": ...})))
```

- **What it does.** It builds the new MDP on the same scene, truncates
the episodes (`truncate=True`), and captures again on the next step,
which takes about a second.
- **What carries over.** `mdp2.migrate(previous, previous_state, mdp,
state)` keeps every array that both MDPs key alike:
  - term state, timers, histories, commands and progress;
  - random streams, by use;
- values declared `Tunable`, with what waits for the reset, as they may
have been tuned.
- **What is new.** Other reward weights and params come from the new
task, and init hooks run again for uses whose params changed.
- **Without truncating.** `update_task(task, truncate=False)` lets the
episodes go on, keeping the reward sums of the rewards both tasks have.
Under an episode budget it raises, since a new task starts a new
evaluation.

### Variations

```python
DRAWER = mdp.variation("drawer", cabinet.joint_pos, cabinet.joints("drawer"), mdp.Uniform(0.0, 0.35))
task = mdp2.compose(SCENE, EMBODIMENT, TASK, DRAWER)

# later: replay what a run recorded
REPLAY = mdp.variation("drawer", cabinet.joint_pos, cabinet.joints("drawer"), mdp.Replay(records["drawer"].tolist()))
```

A variation is a reset event that writes the scene, plus a recorded
quantity:

| Values | Draw |
|---|---|
| `mdp.Uniform(low, high)` | uniform; `low` and `high` are tunable |
| `mdp.Choice(values, weights)` | one of the values |
| `mdp.Replay(values)` | in reset order, by world within a step, so a
replay does not depend on `num_envs`; the row is recorded as
`<name>_row` |

---

## 3. Actions

```python
actions = {
    "wbc": mdp2.Action(g1_wbc_policy, outputs={"targets": robot.joint_pos_target}, rate=mdp2.ActionRate.CONTROL),
    "hand": mdp2.DirectAction(robot.joint_pos_target, subset=robot.joints(".*_hand_.*")),  # every physics step
}
```

- **Control rate.** `ActionRate.CONTROL` applies an action once per
control step, for an embedded controller or IK, like MDP1's
`process_actions`. The default applies it before every physics step.
- **Without the env.** Call `mdp2.process_actions(mdp, state, actions)`
once per control step, before `apply_actions`.
- **Name slots.** Actions have name slots, as observations do: an action
name gets one column range across world configs and stages.
- **Actions in stages.** Tasks of a sequence may take actions of their
own.
- **Last actions.** The last action holds zero in the columns a world
does not take, which replaces `MDP.narrow_action_dims`.

---

## 4. Using a part twice

```python
TASK = mdp2.compose(
    left=mdp2.rename(ARM, robot="left_arm"),
    right=mdp2.rename(ARM, robot="right_arm"),
)
# actions "left.effort", "right.effort"; observations "left.joint_pos", "right.joint_pos"
```

- **`rename`.** It rebinds the entities a part reads and writes.
- **Running together.** Subtasks that run together get their own
columns, named with the subtask's name.
- **Taking turns.** Subtasks that take turns (a sequence, a choice, a
split) share the columns of their name, as wide as the widest.

---

## 5. The policy interface

```python
spec = env.mdp.spec()
spec.actions[1].name, spec.actions[1].columns      # "hand", its slice of the action
spec.actions[1].labels                             # {"actions.hand": ("left_hand_0", ...)}: joint names per op
spec.observations["policy"][0].labels              # body or joint names, where the inputs name them

env.mdp.action_mask(env.state)                     # (num_worlds, action_dim): columns each world takes now
env.mdp.observation_mask(env.state, "policy")      # (num_worlds, dim): columns each world writes now
```

Learners, policy servers and exporters can find a column by name instead
of by offset. Both masks are Torch-only, so they can run inside a graph.

---

## 6. Evaluation, from Arena

```python
cfg.episode_budget = 1000                          # worlds stop starting episodes once 1000 have run
env.reset()
while env.episodes_completed < 1000:
    env.step(policy(obs))
records = env.episode_records()                    # columns: world, episode, length, terminated, <quantity>, progress/<task>, revision
```

```python
cameras = mdp2.ObservationGroup(terms={"rgb": mdp2.Observation(mdp.image_rgb, inputs={"image": camera.rgb})}, concatenate=False)
on_target = mdp2.Quantity(mdp.resting_on, inputs={"normal_force_matrix_w": obj.normal_force_matrix_w, ...},
                          params={"filter_index": 0, "min_force": 0.1, "min_cos": 0.7, "max_speed": 0.003})
done = mdp2.Milestone(mdp2.quantities.on_target, hold=10)
```

- **Cameras.** They render inside the step's graph, and cameras that no
term reads are not rendered.
- **Uncombined groups.** `ObservationGroup(concatenate=False)` keeps a
tensor per term, so `uint8` images stay as they are.
- **Contact checks.** `mdp.resting_on` is Arena's
`object_on_destination`: a contact force within a cone and a speed below
a bound, held with `hold`.
- **Records.** `Quantity(record=True)` (previously `log=True`) is logged
and also recorded per episode.

**Porting from Arena**

| Arena | MDP2 |
|---|---|
| `CompletionCriteria`, `subtasks_are_sequential`, `K` | milestones in
`sequence`, or `compose(require=K)` |
| `desired_subtask_success_state`, `TrueForConsecutiveSteps` | `final=`,
`hold=` |
| tracked events | `repeat=True` |
| run-time variations with JSONL records | `mdp.variation`,
`episode_records()` |
| configclass merging | `mdp2.compose`, `mdp2.rename` |

---

## 7. Any physics backend

```python
manager = env.sim.backend_manager
manager.supports_step_capture()   # Newton: use_cuda_graph and a capturable solver
graph = manager.capture(fn)       # records as the backend records its own step
env.sim.after_replay(num_steps)   # host work of replayed physics steps: step count, sim time
type(actuator).capturable         # ActuatorBase flag; Newton-native actuators by is_graphable()
```

- **Capture.** `MDP2Env` no longer imports Newton's capture function. A
backend that cannot capture its step runs the physics eagerly between
the MDP's graphs.
- **Actuators.** Delayed PD actuators draw the delays of reset worlds
from a device stream, so replayed graphs draw new delays. The network
actuators set `capturable = False` rather than inherit it from
`DCMotor`.
- **`verify_capture`.** Without reproducible physics, it compares the
MDP alone, bitwise.

These core changes are in their own commits, so they can be split out.

---

## Performance

MDP time per step: `env.step` with the physics step replaced by a no-op,
at 4,096 worlds, Newton MJWarp, RTX PRO 6000 Blackwell. Each value is
the median of 5 warm runs, alternating with `main`.

| Task | `main` | this PR | Δ |
|---|---|---|---|
| Cartpole | 74.9 µs | 41.0 µs | -33.9 |
| Go2 flat | 80.0 µs | 63.6 µs | -16.4 |
| Go2 walk/stand (split) | 80.2 µs | 65.5 µs | -14.7 |
| Kuka Allegro lift | 234.4 µs | 212.4 µs | -22.0 |

- **MDP kernels.** They are byte-identical to `main` for all four MDP2
tasks, checked on every commit by dumping the generated sources and the
launch counts.
- **Where the time went.** `MDP2RLEnv` kept its episode statistics with
about 15 Torch operations per step, plus 2 per recorded quantity. Now
one generated world-thread kernel keeps them, a row per logged column,
and one sum per step gives `extras["log"]`.
- **Learning.** A 40-iteration Cartpole RSL-RL run logs the same values
as `main`. The logs match the old path to float rounding.
- **Benchmarks.** About 1 in 7 runs, on `main` and on this branch alike,
take twice as long because of the GPU. They are dropped as runs above
1.5× the fastest.

**What the features cost, on Go2**

| Variant | MDP time | vs plain |
|---|---|---|
| plain | 63.6 µs | |
| every reward weight and tracking width `Tunable` | 63.6 µs | 0 |
| all 10 rewards under `when=Tunable(True)` | 71.6 µs | +8.0 |
| `when` on one observation | 65.6 µs | +2.0 (one more observe kernel) |
| rewards in two stages of a sequence | 73.8 µs | +10.2 (+77 before this
PR's fixes) |
| the same rewards, shared by both stages | 67.6 µs | +4.0 |

The staged cost is down from +77 µs for three reasons:
- uses of every stage now run in the parent's scope;
- progress is logged from the same kernel as the rest of the statistics;
- staged uses that the stages define alike run as one op.

## Design notes

A review of the whole design settled these choices:

| Choice | Why |
|---|---|
| Uses that stages define alike run as one op | A history or action-rate
term carries on across stages without hoisting it. The op compiles
exactly as if hoisted. The cost: it logs under the first stage's name. |
| One pending bit per tuned value | A reset applies only what was tuned,
so values that events or curricula wrote stay. |
| `update_task` keeps only `Tunable` values | Edited weights and params
take effect; tuned ones survive. |
| `when` tuned with `at="step"` switches one step later | Switches latch
at the end of a step, the same rule as stages. |
| Episode logs in an env kernel, not in the MDP's | MDP kernels stay
identical to `main`; the log kernel costs about 3 µs. |

Not built, because each needs a measured gain or a use case first:
- `entered` flags only where read;
- skipping `streak` and `score` where nothing reads them;
- fusing the observation kernel that stages split off;
- tunable choice weights;
- a Warp `Replay`.

---

## Breaking changes

```python
# Before                                         # After
cfg.task = [WALK, STAND]                          cfg.task = mdp2.split(walk=WALK, stand=STAND,
cfg.task_worlds = [3072, 1024]                                          worlds={"walk": 3072, "stand": 1024})
mdp2.Quantity(term, log=True)                     mdp2.Quantity(term, record=True)   # logged and recorded
mdp.interval_writes                               mdp.step_writes
mdp.narrow_action_dims / (last_action, dim)       one last_action, zero where not taken; MDP.action_mask
```

- **Columns.** Observation and action columns of world configs are
allocated by name, rather than packed from the first column.
- **Subtasks.** Two subtasks that run together get separate columns, and
two that take turns share theirs.
- **Episode budget.** `done` stays "terminated or truncated", and a
separate mask selects the worlds that restart.
- **Logs.** Without a time limit, `Episode_Reward/*` is per second of
each episode, rather than 0. A choice's `Progress/<task>` averages over
the finished episodes that drew the task.
- **Merged uses.** A use that two stages define alike is one op, logged
under the first stage's name, so `Episode_Reward/<second stage>.x` no
longer exists. Give the uses different weights to keep them apart.

---

## Not in this PR

| Item | Status |
|---|---|
| Resets from banks of states, resets from milestones | #9112 |
| In-process scene rebuild (Arena build-time variants) | blocked: needs
reliable `SimulationContext` teardown |
| RTX cameras in MDP2 | blocked: Kit path; MDP2 stays Newton-only for
now |
| Newton assets for Arena's library | asset owners and Newton |
| Material randomization without Newton internals, per-world gravity
setter, asset-level state commit, refreshing only changed worlds of the
model | core asset and Newton work |
| Self-describing sensors (stage, rate, capturability), re-rendering
only reset worlds | sensor API work |
| Skipping compute in worlds whose budget is spent | deferred: a branch
in every kernel for the tail of an evaluation |
| Stacked inputs | dropped: built-in progress replaced the need |
| Non-linear milestone graphs | no use case yet |

**Known gaps**
- **Camera workaround.** The Newton camera workaround (no renderer
graphs, for the stale two-camera graph) lost its only test along with
the example, and the upstream bug is still open.
- **Overlap with #9112.** `lift_env_cfg.py` and `eager.py` also change
in #9112. Here they only change `log=` to `record=` and pass default
tunables to `init`.

## Type of change

- New feature (non-breaking change which adds functionality)
- Breaking change (existing functionality will not work without user
modification)
- Documentation update

## Release backport

- [x] <!-- backport-active-release --> Backport this pull request to the
active release branch after it merges into `main`

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Jichuan Hu <jichuanh@nvidia.com>
isaaclab-bot Bot pushed a commit that referenced this pull request Nov 27, 2026
# Description

**MDP2 Part 2** is the second update of MDP2 (#9016). It collects two
lines of work:
- the MDP2 features prototyped for [Isaac Lab
Arena](https://github.com/isaac-sim/IsaacLab-Arena) in #9091, without
its pick-and-place example;
- the remaining follow-ups of #9016.

The theme is **training in many ways from one compiled MDP**. Tasks are
built from tasks, values and switches change per world while the CUDA
graphs keep replaying, and policies see a named interface.

Tasks that use none of this compile to **byte-identical MDP kernels**,
and every MDP2 task now steps **15 to 34 µs faster than on `main`**,
because the env keeps its episode logs in one generated kernel. Resets
from a bank of states are developed separately in #9112.

**Contents**
1. [Tasks made of tasks](#1-tasks-made-of-tasks): `compose`, `sequence`,
`split`, `choice`, progress
2. [Changing a task while it
trains](#2-changing-a-task-while-it-trains): `Tunable`, `when`,
`update_task`, variations
3. [Actions](#3-actions): name slots, actions in stages, control rate
4. [Using a part twice](#4-using-a-part-twice): `rename`
5. [The policy interface](#5-the-policy-interface): `spec`, masks
6. [Evaluation, from Arena](#6-evaluation-from-arena): episode budget,
records, cameras, `resting_on`
7. [Any physics backend](#7-any-physics-backend): capture through the
physics manager
8. [Performance](#performance) · [Breaking changes](#breaking-changes) ·
[Not in this PR](#not-in-this-pr)

**At a glance**

| You want to | Use |
|---|---|
| Build a task in steps, or from a scene, an embodiment and a task |
`mdp2.sequence`, `mdp2.compose`, `mdp2.Milestone` |
| Train different tasks in different worlds | `mdp2.split` (fixed
worlds), `mdp2.choice` (drawn per episode) |
| Read how far a task got | `mdp2.progress.<task>.done`, `.active`,
`.score`, `.count`, ... |
| Change a reward weight or a param during training | `mdp2.Tunable`,
`env.tune(...)` |
| Turn a term on or off per world | `when=<field>`,
`when=mdp2.Tunable(True)` |
| Edit the task of a running env | `env.update_task(task)` |
| Randomize a value per episode, record it, replay it |
`mdp.variation(..., mdp.Uniform / Choice / Replay)` |
| Run an embedded controller once per control step |
`rate=mdp2.ActionRate.CONTROL` |
| Use one part for two robots | `mdp2.rename(part, robot="left_arm")` |
| Know which policy column is what | `env.mdp.spec()`, `action_mask`,
`observation_mask` |
| Run a fixed number of evaluation episodes | `episode_budget`,
`env.episode_records()` |

---

## 1. Tasks made of tasks

A task can say when it is done, and it can hold named subtasks, which
are tasks too. Four functions combine them:

| Function | Subtasks run | The task is done when |
|---|---|---|
| `compose(a=..., b=..., require=k)` | together | `k` of them are (all
by default) |
| `sequence(a=..., b=...)` | one after another; the next starts the step
after | the last is |
| `split(a=..., b=..., worlds={"a": 3072, "b": 1024})` | each in its own
worlds | the world's own is |
| `choice(a=..., b=..., weights={"a": 3, "b": 1})` | one per episode and
world, drawn at the reset | the drawn one is |

### Sequences

```python
q = mdp2.quantities
TASK = mdp2.compose(
    BASE,                                                      # observations, action rate, time limit
    mdp2.sequence(
        reach=mdp2.TaskCfg(rewards={"reach": ...}, done=q.near_object),
        grasp=mdp2.TaskCfg(rewards={"grasp": ...}, done=q.grasped, hold=3),
        lift=mdp2.Milestone(q.lifted, hold=10),               # lifted for 10 steps in a row
    ),
)
success = mdp2.Termination(mdp.is_true, inputs={"value": mdp2.progress.done})
```

- **Done.** `done=` is a field of one value per world. `hold=n` asks for
it on `n` steps in a row.
- **Uses.** A task of a sequence runs its uses only while it is active,
and they restart when it starts.
- **Shared uses.** Uses that the tasks of a sequence define alike are
one op, so a shared action-rate term or observation history carries on
across stages.

<!-- GIF: mdp2_sequence.gif -->

*Recorded from 4,096 Cartpole worlds drifting along the rail. Each row
is a world, each color the task it runs, and a gap is a reset.*

### Progress

Every task's progress is a set of fields that any term can read:

```python
mdp2.progress.done                   # the whole task
mdp2.progress.grasp.done             # a subtask; also .holding .active .score .done_at .started_at .stage .count
```

| Field | Meaning |
|---|---|
| `done` | done once, until the episode ends |
| `holding` | its completion holds at this step |
| `active` | it runs at this step |
| `score` | in `[0, 1]`: its subtasks done, weighted by their `score=` |
| `done_at`, `started_at` | episode step it was first done (-1 before)
and last started |
| `stage` | the subtask a sequence or a choice runs |
| `count` | how often a task with `repeat=True` was done |

```python
mdp2.Milestone(q.dropped, repeat=True)                                # counts drops: progress.dropped.count
mdp2.Event(spawn_target, outputs={...}, mode=mdp2.EventMode.START)   # writes the scene when its task starts
```

- **Names.** A subtask reads its own commands, quantities, term state,
tunables and progress by name, as a task alone does. Inner names win.
- **Logs.** `Progress/<task>` is the share of the last episodes in which
each task was done.
- **Reset order.** Reset events run before progress restarts, so a
curriculum can read the milestones of the episode that ended.

### Splits and choices

```python
TASK = mdp2.compose(BASE, mdp2.split(walk=WALK, stand=STAND, worlds={"walk": 3072, "stand": 1024}))
TASK = mdp2.compose(BASE, mdp2.choice(walk=WALK, stand=STAND, weights={"walk": 3, "stand": 1}))
```

- **Split.** Each subtask runs in fixed worlds. A split may be a step of
a sequence, and several splits divide the same worlds.
- **Choice.** It draws one subtask per episode and world, which is
multi-task training in one run. `progress.stage` is the drawn index, and
`Progress/<task>` logs each task over the worlds that drew it.

<!-- GIF: mdp2_choice.gif -->

*The left grid is set by the config. The right grid is recorded: each
cell is a world colored by its drawn task, and it redraws at every
reset.*

---

## 2. Changing a task while it trains

### Tunable values

```python
track = mdp2.Reward(
    mdp.track_lin_vel_xy_exp, ...,
    params={"std": mdp2.Tunable(0.5)},
    weight=mdp2.Tunable(1.5),
)

env.tune("rewards.track.weight", 3.0)                                   # each world at its next reset
env.tune("rewards.track.std", 0.25, worlds=slice(0, 2048), at="step")  # from the next step
```

- **What it is.** A `Tunable` param is a field of one value per world. A
`wp.func` gets its world's value, as for any param. A tunable weight is
the reward's column of `state.reward_weights`.
- **Reading and writing it.** Other terms read a param, and events write
it, for example a curriculum: `mdp2.tunable("rewards.track", "std")`.
- **No recapture.** `tune` writes in place, so the captured graphs keep
replaying.
- **When it applies.** With `at="reset"` (the default), the value waits
in a pending copy that the reset kernel applies, so no episode mixes two
values. Each value has its own pending bit, so a reset leaves values
that events wrote alone.
- **Revisions.** Each world counts the tunings that took effect in
`state.revision`, and the episode records keep that count.

<!-- GIF: mdp2_tune.gif -->

*Recorded: one Cartpole run tunes the left half of the worlds at their
next reset and the right half from the next step.*

### Switches

```python
mdp2.Reward(..., when=mdp2.commands.standing)          # runs where the mode command is positive
mdp2.Reward(..., when=mdp2.Tunable(True))              # a switch per world
env.tune("rewards.feet_air_time.when", False, worlds=eval_worlds)
```

- **Where it works.** `when=` takes any field, on a reward, termination,
observation, command or interval event.
- **Timing.** The field is read at the start of the step, the same rule
as for stages.
- **Off and on.** The use outputs zero while it is off, and it restarts
where it turns on.

### Editing a running task

```python
env.update_task(mdp2.compose(env.cfg.task, mdp2.TaskCfg(rewards={"new": ...})))
```

- **What it does.** It builds the new MDP on the same scene, truncates
the episodes (`truncate=True`), and captures again on the next step,
which takes about a second.
- **What carries over.** `mdp2.migrate(previous, previous_state, mdp,
state)` keeps every array that both MDPs key alike:
  - term state, timers, histories, commands and progress;
  - random streams, by use;
- values declared `Tunable`, with what waits for the reset, as they may
have been tuned.
- **What is new.** Other reward weights and params come from the new
task, and init hooks run again for uses whose params changed.
- **Without truncating.** `update_task(task, truncate=False)` lets the
episodes go on, keeping the reward sums of the rewards both tasks have.
Under an episode budget it raises, since a new task starts a new
evaluation.

### Variations

```python
DRAWER = mdp.variation("drawer", cabinet.joint_pos, cabinet.joints("drawer"), mdp.Uniform(0.0, 0.35))
task = mdp2.compose(SCENE, EMBODIMENT, TASK, DRAWER)

# later: replay what a run recorded
REPLAY = mdp.variation("drawer", cabinet.joint_pos, cabinet.joints("drawer"), mdp.Replay(records["drawer"].tolist()))
```

A variation is a reset event that writes the scene, plus a recorded
quantity:

| Values | Draw |
|---|---|
| `mdp.Uniform(low, high)` | uniform; `low` and `high` are tunable |
| `mdp.Choice(values, weights)` | one of the values |
| `mdp.Replay(values)` | in reset order, by world within a step, so a
replay does not depend on `num_envs`; the row is recorded as
`<name>_row` |

---

## 3. Actions

```python
actions = {
    "wbc": mdp2.Action(g1_wbc_policy, outputs={"targets": robot.joint_pos_target}, rate=mdp2.ActionRate.CONTROL),
    "hand": mdp2.DirectAction(robot.joint_pos_target, subset=robot.joints(".*_hand_.*")),  # every physics step
}
```

- **Control rate.** `ActionRate.CONTROL` applies an action once per
control step, for an embedded controller or IK, like MDP1's
`process_actions`. The default applies it before every physics step.
- **Without the env.** Call `mdp2.process_actions(mdp, state, actions)`
once per control step, before `apply_actions`.
- **Name slots.** Actions have name slots, as observations do: an action
name gets one column range across world configs and stages.
- **Actions in stages.** Tasks of a sequence may take actions of their
own.
- **Last actions.** The last action holds zero in the columns a world
does not take, which replaces `MDP.narrow_action_dims`.

---

## 4. Using a part twice

```python
TASK = mdp2.compose(
    left=mdp2.rename(ARM, robot="left_arm"),
    right=mdp2.rename(ARM, robot="right_arm"),
)
# actions "left.effort", "right.effort"; observations "left.joint_pos", "right.joint_pos"
```

- **`rename`.** It rebinds the entities a part reads and writes.
- **Running together.** Subtasks that run together get their own
columns, named with the subtask's name.
- **Taking turns.** Subtasks that take turns (a sequence, a choice, a
split) share the columns of their name, as wide as the widest.

---

## 5. The policy interface

```python
spec = env.mdp.spec()
spec.actions[1].name, spec.actions[1].columns      # "hand", its slice of the action
spec.actions[1].labels                             # {"actions.hand": ("left_hand_0", ...)}: joint names per op
spec.observations["policy"][0].labels              # body or joint names, where the inputs name them

env.mdp.action_mask(env.state)                     # (num_worlds, action_dim): columns each world takes now
env.mdp.observation_mask(env.state, "policy")      # (num_worlds, dim): columns each world writes now
```

Learners, policy servers and exporters can find a column by name instead
of by offset. Both masks are Torch-only, so they can run inside a graph.

---

## 6. Evaluation, from Arena

```python
cfg.episode_budget = 1000                          # worlds stop starting episodes once 1000 have run
env.reset()
while env.episodes_completed < 1000:
    env.step(policy(obs))
records = env.episode_records()                    # columns: world, episode, length, terminated, <quantity>, progress/<task>, revision
```

```python
cameras = mdp2.ObservationGroup(terms={"rgb": mdp2.Observation(mdp.image_rgb, inputs={"image": camera.rgb})}, concatenate=False)
on_target = mdp2.Quantity(mdp.resting_on, inputs={"normal_force_matrix_w": obj.normal_force_matrix_w, ...},
                          params={"filter_index": 0, "min_force": 0.1, "min_cos": 0.7, "max_speed": 0.003})
done = mdp2.Milestone(mdp2.quantities.on_target, hold=10)
```

- **Cameras.** They render inside the step's graph, and cameras that no
term reads are not rendered.
- **Uncombined groups.** `ObservationGroup(concatenate=False)` keeps a
tensor per term, so `uint8` images stay as they are.
- **Contact checks.** `mdp.resting_on` is Arena's
`object_on_destination`: a contact force within a cone and a speed below
a bound, held with `hold`.
- **Records.** `Quantity(record=True)` (previously `log=True`) is logged
and also recorded per episode.

**Porting from Arena**

| Arena | MDP2 |
|---|---|
| `CompletionCriteria`, `subtasks_are_sequential`, `K` | milestones in
`sequence`, or `compose(require=K)` |
| `desired_subtask_success_state`, `TrueForConsecutiveSteps` | `final=`,
`hold=` |
| tracked events | `repeat=True` |
| run-time variations with JSONL records | `mdp.variation`,
`episode_records()` |
| configclass merging | `mdp2.compose`, `mdp2.rename` |

---

## 7. Any physics backend

```python
manager = env.sim.backend_manager
manager.supports_step_capture()   # Newton: use_cuda_graph and a capturable solver
graph = manager.capture(fn)       # records as the backend records its own step
env.sim.after_replay(num_steps)   # host work of replayed physics steps: step count, sim time
type(actuator).capturable         # ActuatorBase flag; Newton-native actuators by is_graphable()
```

- **Capture.** `MDP2Env` no longer imports Newton's capture function. A
backend that cannot capture its step runs the physics eagerly between
the MDP's graphs.
- **Actuators.** Delayed PD actuators draw the delays of reset worlds
from a device stream, so replayed graphs draw new delays. The network
actuators set `capturable = False` rather than inherit it from
`DCMotor`.
- **`verify_capture`.** Without reproducible physics, it compares the
MDP alone, bitwise.

These core changes are in their own commits, so they can be split out.

---

## Performance

MDP time per step: `env.step` with the physics step replaced by a no-op,
at 4,096 worlds, Newton MJWarp, RTX PRO 6000 Blackwell. Each value is
the median of 5 warm runs, alternating with `main`.

| Task | `main` | this PR | Δ |
|---|---|---|---|
| Cartpole | 74.9 µs | 41.0 µs | -33.9 |
| Go2 flat | 80.0 µs | 63.6 µs | -16.4 |
| Go2 walk/stand (split) | 80.2 µs | 65.5 µs | -14.7 |
| Kuka Allegro lift | 234.4 µs | 212.4 µs | -22.0 |

- **MDP kernels.** They are byte-identical to `main` for all four MDP2
tasks, checked on every commit by dumping the generated sources and the
launch counts.
- **Where the time went.** `MDP2RLEnv` kept its episode statistics with
about 15 Torch operations per step, plus 2 per recorded quantity. Now
one generated world-thread kernel keeps them, a row per logged column,
and one sum per step gives `extras["log"]`.
- **Learning.** A 40-iteration Cartpole RSL-RL run logs the same values
as `main`. The logs match the old path to float rounding.
- **Benchmarks.** About 1 in 7 runs, on `main` and on this branch alike,
take twice as long because of the GPU. They are dropped as runs above
1.5× the fastest.

**What the features cost, on Go2**

| Variant | MDP time | vs plain |
|---|---|---|
| plain | 63.6 µs | |
| every reward weight and tracking width `Tunable` | 63.6 µs | 0 |
| all 10 rewards under `when=Tunable(True)` | 71.6 µs | +8.0 |
| `when` on one observation | 65.6 µs | +2.0 (one more observe kernel) |
| rewards in two stages of a sequence | 73.8 µs | +10.2 (+77 before this
PR's fixes) |
| the same rewards, shared by both stages | 67.6 µs | +4.0 |

The staged cost is down from +77 µs for three reasons:
- uses of every stage now run in the parent's scope;
- progress is logged from the same kernel as the rest of the statistics;
- staged uses that the stages define alike run as one op.

## Design notes

A review of the whole design settled these choices:

| Choice | Why |
|---|---|
| Uses that stages define alike run as one op | A history or action-rate
term carries on across stages without hoisting it. The op compiles
exactly as if hoisted. The cost: it logs under the first stage's name. |
| One pending bit per tuned value | A reset applies only what was tuned,
so values that events or curricula wrote stay. |
| `update_task` keeps only `Tunable` values | Edited weights and params
take effect; tuned ones survive. |
| `when` tuned with `at="step"` switches one step later | Switches latch
at the end of a step, the same rule as stages. |
| Episode logs in an env kernel, not in the MDP's | MDP kernels stay
identical to `main`; the log kernel costs about 3 µs. |

Not built, because each needs a measured gain or a use case first:
- `entered` flags only where read;
- skipping `streak` and `score` where nothing reads them;
- fusing the observation kernel that stages split off;
- tunable choice weights;
- a Warp `Replay`.

---

## Breaking changes

```python
# Before                                         # After
cfg.task = [WALK, STAND]                          cfg.task = mdp2.split(walk=WALK, stand=STAND,
cfg.task_worlds = [3072, 1024]                                          worlds={"walk": 3072, "stand": 1024})
mdp2.Quantity(term, log=True)                     mdp2.Quantity(term, record=True)   # logged and recorded
mdp.interval_writes                               mdp.step_writes
mdp.narrow_action_dims / (last_action, dim)       one last_action, zero where not taken; MDP.action_mask
```

- **Columns.** Observation and action columns of world configs are
allocated by name, rather than packed from the first column.
- **Subtasks.** Two subtasks that run together get separate columns, and
two that take turns share theirs.
- **Episode budget.** `done` stays "terminated or truncated", and a
separate mask selects the worlds that restart.
- **Logs.** Without a time limit, `Episode_Reward/*` is per second of
each episode, rather than 0. A choice's `Progress/<task>` averages over
the finished episodes that drew the task.
- **Merged uses.** A use that two stages define alike is one op, logged
under the first stage's name, so `Episode_Reward/<second stage>.x` no
longer exists. Give the uses different weights to keep them apart.

---

## Not in this PR

| Item | Status |
|---|---|
| Resets from banks of states, resets from milestones | #9112 |
| In-process scene rebuild (Arena build-time variants) | blocked: needs
reliable `SimulationContext` teardown |
| RTX cameras in MDP2 | blocked: Kit path; MDP2 stays Newton-only for
now |
| Newton assets for Arena's library | asset owners and Newton |
| Material randomization without Newton internals, per-world gravity
setter, asset-level state commit, refreshing only changed worlds of the
model | core asset and Newton work |
| Self-describing sensors (stage, rate, capturability), re-rendering
only reset worlds | sensor API work |
| Skipping compute in worlds whose budget is spent | deferred: a branch
in every kernel for the tail of an evaluation |
| Stacked inputs | dropped: built-in progress replaced the need |
| Non-linear milestone graphs | no use case yet |

**Known gaps**
- **Camera workaround.** The Newton camera workaround (no renderer
graphs, for the stale two-camera graph) lost its only test along with
the example, and the upstream bug is still open.
- **Overlap with #9112.** `lift_env_cfg.py` and `eager.py` also change
in #9112. Here they only change `log=` to `record=` and pass default
tunables to `init`.

## Type of change

- New feature (non-breaking change which adds functionality)
- Breaking change (existing functionality will not work without user
modification)
- Documentation update

## Release backport

- [x] <!-- backport-active-release --> Backport this pull request to the
active release branch after it merges into `main`

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Jichuan Hu <jichuanh@nvidia.com>

(cherry picked from commit 940bac7)
StafaH and others added 9 commits November 26, 2026 22:23
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.
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.
Start events that write a command of their task run after the task's commands resample on entry too, as reset
events that write commands do at resets.
… use

The reset event latches which worlds' episodes ended at their last step, from the terminated and time_out inputs,
and credits only those, so manual resets mid-episode credit nothing and skip_current_episodes is gone. Recording
follows the mask of the worlds where its use runs. The sampler draws for -1 requests only with sample_unrequested,
so existing callers keep -1 as an invalid request.
…s for the reset state generator

A reset after steps that did not end the episodes credits nothing, recording follows its worlds on both backends,
and generate_reset_states.py imports isaaclab_tasks_experimental, where the MDP2 lift task now lives.
@StafaH

StafaH commented Nov 27, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks @maxkra15, all four addressed after rebasing on Part 2:

  • Credit only completed episodes: the event latches which episodes ended (new required terminated + time_out inputs when crediting) and credits only those; skip_current_episodes() is gone. Your probe is a test now. (e9d65dc, 0e2c1e0)
  • Recording mask: the update hook passes its world mask to the recording kernel; tested on Torch and Warp. (e9d65dc)
  • state_ids=-1: unchanged by default; mixed pin-and-sample is opt-in via sample_unrequested=True. (e9d65dc)
  • plan.py conflict: resolved; command-writing events run after the resample both at reset and on stage entry, with a test. (366232a)

@maxkra15

maxkra15 commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Thanks Mustafa, earlier fixes look good. still hit three things when combining reset banks with Part 2:

  • Restoring a goal can credit a success as a failure. With succeeded=mdp2.progress.done, the same successful episodes got 100% credit when the bank restored scene fields and 0% when it also restored a goal. I got that on Torch and Warp. The late restore reads progress after it's been cleared. Can we latch success alongside the episode-ended flag? Reset ordering
  • Editing a running task drops the bank. I added an unrelated quantity, migrated the task, and the next reset raised KeyError('reset_states') on both backends. The unchanged event's init is skipped and the new cache is empty. Can we preserve the bank and rebind its outputs to the new MDP state? Migration
  • Stored goals fail to compile inside a named subtask. The same bank works standalone, but compose(pick=...) registers commands.pick.goal while the reset event still writes commands.goal. Can we scope the output and keep the generator's local goal binding? Builder

@AntoineRichard AntoineRichard left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Four confirmed P2 findings, verified against head 0e2c1e03fcdeb02156e3fd38f909e203158b1d89 and exact base 19cff013cbafcf2670f54bff8c0fbfbe13bff254.

The task-migration crash and reset-event dependency reversal are important runtime issues to address before merge. Saved-source playback and nested generation-option overrides block specific configuration workflows. Each inline comment includes reproduction details, observed results, controls, impact, and a focused remediation.

Runtime verification used both Torch and native Warp execution on CPU with analytic scene/simulator adapters. First-party imports were pinned to each tested source snapshot. Default train/play configuration resolution passed. GPU physics, CUDA capture, and complete training/playback jobs were not run.

@AntoineRichard AntoineRichard left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Six further findings on head 0e2c1e0, all reproduced on CPU with the public APIs and the analytic scene of test_mdp2_reset_states.py; none needed a physics launch, and GPU capture was not exercised. They are lower priority (P3) than the four posted earlier: none blocks the default Kuka configuration.

Comment thread source/isaaclab/isaaclab/utils/dict.py Resolved
…ler caveats

class_to_dict dumps a callable instance under _type with its fields. The
how-to passes sample_unrequested=True where -1 requests draw, and forget()
documents that environments mid-episode from a replaced entry need
valid=False at their next reset.
…es across task updates

Reset events run in their validated order again: reset_to_states restores
scene outputs where it is scheduled and commands in its reset hook, after
the commands resample. migrate carries the caches of kept uses. Sources
are mutable so CLI overrides apply, Kuka play mode adjusts only FromTask,
FromFile rejects unlabeled files for labeled groups, and a scored sampler
requires the succeeded input.
…bles without fields

A subtask's reset_to_states writes its own goal, which the generator holds
under the local name. Crediting reads progress before it restarts, also
with a restored goal; tests cover that, start events mid-episode, and
graph replay of a restored command. class_to_dict keeps callables without
__dict__ as they are.
@StafaH

StafaH commented Nov 30, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks @maxkra15, all three are addressed:

  • Restored goal credited as failure: fixed by 0182200. The plan no longer moves command-writing events after the resample. reset_to_states credits and restores scene outputs in compute, where it is scheduled, so it reads succeeded before progress restarts. Commands are written in a new reset hook, after the commands resample. test_episodes_that_restore_a_goal_are_credited_with_their_progress uses succeeded=mdp2.progress.done with a restored goal on Torch and Warp, and gets [1.0, 0.0]. It fails on the previous head.
  • Task edit drops the bank: fixed by 0182200. migrate carries the cache of every use that both tasks keep. Command outputs come from the hook arguments, so they write the new state's arrays. Covered by test_reset_states_carry_over_to_an_updated_task, and checked with env.update_task(...) on the Kuka env.
  • Stored goals in a named subtask: fixed by 22ca2e8. The builder scopes an event's outputs like its inputs, so compose(pick=...) writes commands.pick.goal, and FromTask takes the generator's local commands.goal. test_stored_goals_restore_in_subtasks_and_when_their_task_starts covers compose(pick=...) and a start event in a sequence subtask that starts mid-episode, on both backends.

@StafaH

StafaH commented Nov 30, 2026

Copy link
Copy Markdown
Collaborator Author

Replies to the review bot's summary and Greptile's summary. Every inline thread from both has a reply and is resolved.

Review bot

  • PR description:
    • The weighting claim is corrected. Relative weights match the old term within 2%, not 1%. The largest gap is at 0% and 100% success, where the floors differ.
    • The design prose is shorter.
    • The description now covers the reset ordering, migrate, output scoping, and the tests added in this round.
    • The benchmark's GPU, versions, warm-up and revisions were not recorded with the numbers. The Performance section now says so, and says the numbers predate 1024 states per object and the command reset hook.
  • Scope: kept. The sources stay config objects so they dump and compare by their fields. They are no longer frozen, so Hydra overrides of their fields work.
  • Compatibility: no shim, since Isaac-Lift-KukaAllegro-MDP2 is an experimental task. 00dcd9a adds a Breaking: removed changelog entry for reset_bank.py, reset_from_bank and the bank_size, history_length, target_success_rate and kappa parameters, with migration guidance.
  • Implementation: fixed in e0ba6f1. Poses with more than one per world are shifted per row, and only world-frame *_w transforms are shifted.
  • Style: the sampler_arrays docstring is moot. The helper was removed in e0ba6f1.
  • Tests: fixed in e0ba6f1. The Kuka test compares freshly initialized samplers across backends instead of copying sampler internals.

Greptile

  • "Saved groups lose object identity" (P1): fixed in e0ba6f1. The group labels are saved with the reset states, and FromFile compares them. Since 0182200, a file with no labels is also rejected when the event has labels.
  • Local poses get shifted, and rejected replay changes the start (P2): fixed in e0ba6f1, with tests.

@maxkra15 maxkra15 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The three earlier fixes check out. I hit one more case in the cache migration.

@StafaH

StafaH commented Nov 30, 2026

Copy link
Copy Markdown
Collaborator Author

run-ci

@isaaclab-bot isaaclab-bot Bot added ci:run-docker Trigger the on-demand Docker and GPU CI workflow and removed ci:run-docker Trigger the on-demand Docker and GPU CI workflow labels Nov 30, 2026

@maxkra15 maxkra15 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

One remaining blocker from the recheck.

@maxkra15

Copy link
Copy Markdown
Contributor

Two things worth investigating as follow-ups:

  • Swapping a running task's regular reset hook for reset_to_states under the same name and bindings can skip the new hook's init. I got KeyError('reset_states') on the next reset. Might make sense to include hook identity in the cache match in a broader update_task() fix. Migration code
  • I also tried dumping a FromFile source with class_to_dict and feeding it back through update_class_from_dict. The dump adds _type, and the updater rejects it. Worth checking how the reader should handle this metadata when we tackle the broader config round-trip. Existing Hydra discussion

…rrying a use's cache

FromTensors compares its states element by element, so a split with different tensor banks builds and a replaced bank migrates. migrate carries a use's cache only to an op with the same hooks, so a reset event swapped for reset_to_states under its name runs its init.
dump_yaml writes tensors as their shape and dtype instead of pickling them, which load_yaml cannot read. update_class_from_dict checks and drops the _type that class_to_dict adds to callable instances.
@StafaH StafaH mentioned this pull request Dec 1, 2026
7 tasks done
The split migration test covers equal tensor banks given as separate tensors, the subtask goal test covers goals that the generator samples, the command order test covers partial resets, and the callable dump round trip covers the dump's type and fields.
@StafaH

StafaH commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks @maxkra15, both follow-ups are fixed in this PR rather than deferred:

  • Swapping a reset hook for reset_to_states under the same name: fixed in cb6429e. migrate now carries a use's cache only to an op with the same compute, update, reset and init hooks, besides the use, params, bound fields and worlds, so the swapped-in event runs its init. test_a_reset_event_replaced_by_reset_to_states_under_its_name_builds_its_states reproduces your KeyError('reset_states') without the change, on both backends.
  • _type in the dump round trip: fixed in 735b326. update_class_from_dict checks a mapping's _type against the callable instance it updates, drops it, and raises ValueError on a mismatch. test_callable_instances_round_trip_through_their_dump covers the dump, the update and the mismatch.

The FromTensors equality thread is fixed in cb6429e too (reply inline).

Change from my earlier reply on env.yaml: I'd left tensors alone, but a dumped tensor made env.yaml unreadable with our own load_yaml (full_load rejects the pickled python/object/apply tags). dump_yaml now writes tensors as tensor(shape=[...], dtype=...); class_to_dict still returns real tensors (735b326).

Test cleanup (ee7f93d): folded overlapping tests into the tests that own each regression, with no assertion dropped:

  • The split migration test now uses separate two-state tensor banks, so it covers the FromTensors comparison in both finalize and migrate.
  • The subtask goal test now checks that stored goals are the generator's samples; the standalone generator-command test is gone.
  • Partial-reset isolation stays covered by the command-order test's [True, False, True] mask, including the captured path.
  • The two class_to_dict tests are one round trip.

Each folded assertion still fails when its fix is reverted (the FromTensors comparison, the bound-field and worlds match from aaa587c, harvesting commands from the main task).

Ran: isaaclab_experimental/test/mdp2, the reset API tests, test_dict.py, test_yaml_io.py and test_configclass.py, and test_lift_kuka_allegro.py on Newton GPU. All pass.

@maxkra15
maxkra15 self-requested a review December 1, 2026 15:11

@maxkra15 maxkra15 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Looks good now, left some suggestions we could pick up on later

@StafaH
StafaH merged commit 880939c into isaac-sim:main Dec 1, 2026
62 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants