Repository navigation
MDP2 - #9016
MDP2#9016
Conversation
Adds isaaclab_experimental.mdp2: term descriptors, task configs with entity field selectors, a Newton-style MDPBuilder that validates and compiles schedule entries into an immutable MDP, and functional apply_actions/evaluate/reset/observe that run on scene data views. Includes an analytic point-mass scene for simulator-free tests.
Terms provide Torch and Warp implementations. A Warp implementation writes its output buffer, usually with one kernel launch. Reward and termination outputs are rows of stacked buffers combined by one fixed kernel each, and observation terms write strided views of their group's columns, so a step launches one kernel per term plus two fixed kernels and copies nothing. MDP buffers and scene views are ProxyArrays, so each backend uses its own view without conversion. The runtime functions dispatch on a Backend enum.
Terms can keep per-world state with update and reset hooks. evaluate writes successor observations before resets, and observe recomputes only the masked worlds. Rename TensorSpec to Term.shape, MDPState.views to fields, and add_config to add_task, and reuse the shared masked copy and fill kernels.
Warp term hooks are now wp.funcs for one world by default. The Warp backend fuses each runtime function into a few generated kernels: per-world work runs in schedule order in one thread per world, and observations run one thread per output element. Hooks that launch their own kernels still work and split the fused kernels where they run. The builder checks func and function signatures. Streams now advance before evaluate and reset draw, so observe repeats a world's last sample. Config fields and test terms follow Isaac Lab MDP names: time_out, resampling_time_range, interval_range_s, episode_length_s, is_alive, joint_pos_out_of_manual_limit, and reset_joints_by_offset.
The builder can describe, inspect, validate, and reorder the schedule within each phase. Every edit checks that a use runs after the uses of its phase that write the fields it reads; events declare the fields they write as outputs. Finalize builds an execution plan, the ordered steps of each runtime function, which both backends run, so the step contract lives in one place. Term state now resets after reset events and command resampling. Terms can read the last action, the episode length, and joint or body subsets selected by name. Reward weights are runtime state, and diagnostics write per-term rewards and terminations. The builder checks array types and return types of Warp funcs.
Both backends compile the execution plan into launches that are each capturable or not, and the runtime functions run them the same way. CapturedMDP binds fixed buffers and captures every run of capturable launches as one CUDA graph, running the others eagerly between them. Eager terms, Term(eager=fn), are called as fn(ctx, **params) with Torch views of their inputs, outputs, state, random stream, mask, and output, and never run inside a graph. Terms with function hooks that cannot be captured set capturable=False. The schedule reports its segments, and the Warp backend runs hooks ahead of independent kernel statements, so consecutive hooks do not split its kernels.
MDPBuilder.replicate assigns the next worlds to another builder's task. Each config compiles on its own, and their ops merge phase by phase in each config's order: ops the configs share run once over the union of their worlds, and the others run only in their own worlds. Random streams are keyed by the use's path, so every world draws what it would in its config alone. Generated kernels and Torch steps skip the worlds where an op is inactive, and actions and observations are padded to the widest config.
The environments build an interactive scene, compile an MDP2 task against its articulation data, and step it with the Gym interface of the manager-based environments. Resets are masks over the worlds: the MDP's reset events write joint state in place, and the environment commits it to the solver. With the Warp backend and a fully capturable MDP, each control step after the first replays as one CUDA graph, physics included. DirectAction can write a subset of a field's elements, and terms are shared rather than copied, so configclasses can hold tasks with Warp funcs.
Built-in terms live in mdp2.mdp under the names of their MDP1 functions: joint and root observations, rewards, terminations, contact terms, velocity and pose commands, and joint and root reset and push events, on both backends. Observations take uniform noise, clipping, scaling, and history. mdp2.terminated exposes the step's terminations to rewards, mdp2.step_dt resolves to the control step, and the compiled-MDP module is now compiled.py. The scene data of MDP2Env covers rigid objects, root and body state, and contact sensors. Built-in terms are tested against their MDP1 functions on Newton states.
Isaac-Cartpole-MDP2 lives in isaaclab_tasks.mdp2, self-contained: its own scene, Newton physics presets, MDP2 task, and RSL-RL configuration. MDP2RLEnv returns copies of its observations, which learners keep across the next step, logs per-term episode statistics without host syncs, and has the configuration fields the training scripts set. The task importer's blacklist now matches whole package names, so ".mdp" no longer skips isaaclab_tasks.mdp2, and preset resolution keeps unchanged tuples instead of reassigning them, which failed on frozen dataclasses. The RL wrappers accept MDP2RLEnv.
Commands now resample like events: they write the command and their state in place for the resampled worlds, and update hooks may steer the command every step. Add startup events, field action offsets, the heading velocity command, locomotion rewards, eager mass, center of mass, and material randomization, and reset scene sensors on episode resets.
…weights Reward weights have one row per world, so world configs whose uses differ only in their weights share those uses. MDP2EnvCfg takes a list of tasks that split the worlds evenly, episode logging averages each term over the worlds where it runs, and function update hooks may take the worlds where their use runs as mask. Add the Go2 walk and stand task, which trains one policy for both halves of the worlds.
The task runs its curriculum, curriculum gravity, and reset bank inside the step's CUDA graph. Quantities share calculations between terms, events write scene fields that the scene commits, and the bank is filled once at startup from a task of candidate start states.
Uses compile in topological order of the MDP fields they read. Random streams are assigned once, by use name. The Warp backend resets term state through the state's own kernel argument.
The MDP state keeps every array in one store, under the key that the Warp backend names its kernel argument with. The compute hook of a quantity, termination, or reward may advance the term's state, so such terms need no update hook. The observation-only fields of a compiled op are one record.
A Warp MDP runs the Torch hooks of terms without Warp ones between its kernels. All capture is Warp capture: Torch work joins it on Warp's stream with a private memory pool, so the Torch backend and mixed MDPs are captured too. MDP2Env captures the step around eager launches, commits fixed-base root poses to the solver, and refuses actuators that keep state. Adds the MDP2 guide and API pages.
An action offset may be a quantity, so a policy can act relative to a reference that changes every step. After a reset, only the quantities that observations and action offsets read are computed again; the others keep the values of the episode that ended, which logged quantities and reset events read. Fused kernels accept declared writes that a hook has no argument for, such as state it does not take. The lift's point cloud meshes shapes with isaaclab.utils.mesh, which respects their axis.
# Conflicts: # source/isaaclab_experimental/isaaclab_experimental/envs/__init__.pyi
maxkra15
left a comment
There was a problem hiding this comment.
Reviewed the current MDP2 draft. I found three correctness cases worth fixing: term-state references after world-config merging, reset-hook masks on the Warp backend, and public reset seeding. Details and reproductions are inline.
43 CUDA owner tests passed across the core runtime, environment/capture, built-in/contact terms and Kuka-Allegro lift task; the core also passed 25 tests on CPU (one skipped). The additional probes below fail on this revision and pass with temporary runtime corrections. Task registration and training-config dumping also work. Full RL training wasn't run. The broader Hydra suite had two pre-existing installed-API compatibility failures, separate from these findings.
MDP2EnvCfg.task_worlds sets the number of worlds of each task of a task list, for shares other than even ones. A cycle of uses that read each other's fields is reported as the only error of its world config, instead of also reporting every use after it for fields it cannot find.
The state of a term use belongs to the use, not to each of its ops: the ops that world configs with different params compile share it, each in its own worlds, and the terms of every config read it by the use's name. The Torch backend keeps what a compute hook writes to its own worlds.
A logged quantity that only some world configs define was averaged over every world, so each config's metric showed the mean of all of them.
The last actions are padded to the world config with the most actions, and every term read the padded array. A term that sizes state by its actions, such as the action rate, then looped over the padding: it read and wrote past its state in the worlds of a config with fewer actions, and past the array in the last worlds. The terms of such a config now read a copy of the last actions with its own columns, so a term sees the actions of its world config only.
- Pass event writes to the simulation without assuming Newton: a commit tells the solver which worlds changed where a field is its own state, and calls the asset's write_*_to_sim_mask methods otherwise, which also supports ball joints. Only the assets that were written are recomputed. - Mark scene fields writable or read-only, and reject actions and events that write read-only ones. - Refuse body orderings, whose poses are copies refreshed outside graphs. - Apply model and state changes of eager work between captured graphs with sim.forward(). - Start the MDP's random streams from the seed that configure_seed set, also for seed -1. - Count a use's state as written by it in the schedule order check. - Add play_mode to MDP2RLEnvCfg, the lift task (curriculum at its end), and the Go2 tasks (no pushes). - Correct why delayed actuators are refused, and document what a captured step freezes.
AntoineRichard
left a comment
There was a problem hiding this comment.
My main concern is on the shape of an mdp. All the mdps are currently defined as warp functions. Thus they completely side-steps the writer APIs (eventhough they are graphable) and can lead to stale values unless the user takes good care to update things properly. In general I feel like making sure an MDP can be framed as a warp function may be too constraining. In the current implementation, this already leads to bugs and inaccurate accelerations for instance. D6 joints are another source of issues.
I would allow folks to define regular python functions that can call kernels, other isaaclab methods and so on. Still fully graphable, compilable. It would also go a long way with randomization since we could launch optimized randomization kernels before the "update kernels". Overall It would give some flexibility back. I think the current code is not that far away we could just let user add their own callables into the list of (capturable, callable).
In general i'm not that keen on locking everything or trying to force the wp.func. And the optional commit=True is one way to get screwed pretty hard. Better mark that in red bold whatever so agents catch it, but even then I feel like it will be an issue.
Recommendation: I'd make the free-form captured step the base contract, and the compiler an optional layer. I don't think it would make a difference. The overhead is 99% in the launch time for most tasks.
| @episode_length_buf.setter | ||
| def episode_length_buf(self, value: torch.Tensor) -> None: | ||
| # Copy in place: captured graphs hold the buffer's address. | ||
| self.state.episode_length.torch.copy_(value) |
There was a problem hiding this comment.
Do we want to set this?
There was a problem hiding this comment.
Yes: RSL-RL's init_at_random_ep_len assigns random episode lengths through it at the start of training, as with MDP1. The setter copies into the MDP's buffer in place, so captured graphs keep reading it.
- Add Stage and StagePoint: user work at named points of every step, inside the step's CUDA graph unless not capturable, each followed by the simulation's forward so that writes through assets are seen. - Let Python hooks take scene entities as inputs and outputs, and keep host objects in cache. Entity outputs cover the entity's writable fields for ordering, fusion, and commits. Replace eager terms with capturable=False, and run randomize_joint_parameters captured through the masked writers. - Infer reset commits from FieldSchema.derived_from and from entities with pending writes; Event.commit is now an override. - Add MDP2EnvCfg.verify_capture, which steps the task uncaptured and captured, on reproducible physics with staggered time-outs, and names the first value that differs. - Pass joint velocities through the asset writer, which keeps the previous ones, so joint accelerations are right on the first step of an episode.
|
Thanks all. Rounds 3 and 4 are in cc41f2b and a229346; inline replies are on each thread. @AntoineRichard, on your review:
@maxkra15: seeding is fixed in cc41f2b: the MDP streams start from the seed Follow-ups from this review (capture hook on the physics manager, actuator capability flag, a combined capture-safe |
|
@AntoineRichard, the items from your earlier review that are still open, all planned for follow-ups:
|
MDP2EnvCfg.step lists the work of a control step (Step.PHYSICS, Step.EVALUATE, Step.RESET) and reset_step that of a reset (ResetStep.EVENTS, COMMIT, OBSERVE), which reset() also runs. Stages are inserted anywhere in either list, replacing the named stage points. The environment checks that the built-in work appears once each and in order before building.
|
run-co |
|
run-ci |
1 similar comment
|
run-ci |
|
run-ci |
# Description
Adds a Warp-native reset-state API in `isaaclab.envs.reset` and uses the
existing Lift reset event as its reference. Tasks keep control of
candidate generation, physical acceptance checks, and restoration.
`ResetStateBuffer` owns prepared array snapshots, supports empty banks
and broadcasting one default state, and gathers into preallocated
outputs with a full-environment mask. `ResetStateSampler` records
completed outcomes against previous assignments before selecting
replacements. It supports explicit catalog IDs, asset-group partitions,
and scores driven by named metrics. The default combines a Beta score
peaked at **50% recent success** with a uniform floor.
Runtime uses Warp arrays and kernels; Torch inputs and environment IDs
are boundary shims. Persistent storage is reused during CUDA graph
replay. The sampler owns its per-environment random streams and supports
explicit reseeding in place.
```mermaid
flowchart LR
P["Task prefill and checks"] --> B["Core state buffer"]
O["Previous outcome"] --> S["Score and select IDs"]
S --> G["Masked gather"]
B --> G
G --> W["Native mask writers"]
W --> E["Episode"]
E --> O
```
Lift's existing `conditional_reset` retains initialization-time
validation and optional diversity selection. Its replay restores
physical state and controller targets through public mask writers,
excludes unfinished viewer resets, and uses the shared sampling policy.
NIST keeps its existing success monitor for outcome history and
reporting. The native sampler uses the monitor’s rates as an input
metric. Migration notes cover the changed Lift and NIST configuration
fields.
## Validation
Focused reset buffer, sampler, manager, and Lift tests passed, including
CUDA graph replay on Newton/MJWarp. A two-environment NIST smoke
verified 16 prepared states, explicit replay, independent outcome
history, and adaptive weights. Earlier capture validation against MDP2
#9016 exercised native Warp launch hooks and zero-copy Torch shims on an
analytic scene.
Full formatting/lint, changelog checks, and clean strict Sphinx passed.
The Kit-only base-environment suite needs CI because Isaac Sim is absent
locally.
# 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 <[email protected]> Co-authored-by: Jichuan Hu <[email protected]>
# 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 <[email protected]> Co-authored-by: Jichuan Hu <[email protected]> (cherry picked from commit 940bac7)
…ct history fix (#9362) ## Description Backport #9297, #9112, and #9323 to `release/3.1.0`. These merged to `main` after the release branch was cut. The first MDP2 parts (#9016, #9120) are already on the release branch. - #9297: Newton contact sensor rolls its force-matrix history with one thread per filter object. - #9112: MDP2 resets: reset MDP2 episodes to stored reset states, which can be generated, recorded during training, pinned, and saved, all inside the captured step. Its prerequisite, the reset-state API from #8872, is already on the release branch. - #9323: MDP2 tracked tasks (`TaskCfg.tracked`) and per-occurrence events (`MDP2RLEnv.episode_events()`, opt-in with `record_episode_events`), for Arena's tracked events. Cherry-picked with `-x`, in merge order, from `121fc8113`, `880939cae`, and `5fa33d124`. 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 - Release backport: features, a bug fix, tests, and documentation ## 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.0` passes, and so does `git diff --check`. - Every touched test file passes locally on this branch: - `isaaclab_experimental`: `test_mdp2.py` 63 passed, `test_mdp2_env.py` 31 passed, `test_mdp2_reset_states.py` 19 passed - `isaaclab_tasks_experimental`: `test_lift_kuka_allegro.py` 6 passed - `isaaclab`: `test_reset_state_sampler.py` 11, `test_reset_states.py` 8, `test_dict.py` 12, `test_yaml_io.py` 5 passed - `isaaclab_newton`: `test_contact_sensor_history.py` 2 passed - Hardware: RTX PRO 6000 Blackwell, Linux. Full CI has not run yet. ## Checklist - [x] Read the contribution guidelines - [x] Run formatting and lint checks - [x] Keep the original documentation, tests, and changelog fragments - [x] Verify the cherry-picks match the original patches --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
Summary
MDP2 is an experimental, compiled replacement for the manager-based MDP. A task describes its actions, observations, rewards, terminations, commands, events, and quantities as configuration.
MDPBuildercompiles that description into a few generated Warp kernels, and the whole environment step, physics included, replays as one CUDA graph.MDP2RLEnvhas the Gym interface ofManagerBasedRLEnv, so the RL wrappers andtrain.pywork unchanged.isaaclab_experimental.mdp2, with its tasks inisaaclab_tasks.mdp2.Isaac-Cartpole-MDP2,Isaac-Velocity-Flat-UnitreeGo2-MDP2(plus a walk/stand variant), andIsaac-Lift-KukaAllegro-MDP2.Results
Each task is compared with its MDP1 counterpart: the same physics settings, decimation, world count, and RSL-RL runner config. The runs use Newton MJWarp with 4,096 worlds on an RTX PRO 6000 Blackwell.
MDP time per step: everything except physics. This is what MDP2 replaces.
Full step and training. Physics is unchanged, so it bounds the end-to-end gain.
MDP time is
env.stepwith the physics step replaced by a no-op, so it includes the environment's action writes, scene updates, resets, and observation copies. Physics is not subtracted, because MDP1's CPU launch overhead partly overlaps with GPU physics in a normal step. Step times are the median of three warm runs of 300env.stepcalls with random actions; a cold-cache first run was discarded. Training time is the wall time ofrunner.learnwith one seed.Public API
Terms and uses
A term is a calculation: a batched Torch function, a per-world
wp.func, or both.A use binds a term to scene fields (
inputs,outputs) and to a role in the task:State and shared values:
Environment config
The step is a list
A control step is an ordered list of built-in work, and resets have their own list (also run by
env.reset()):Add your own work as
Stages anywhere in either list:Or write the whole list:
The built-in work must appear once each, in order:
Stage(fn)Stage(fn, capturable=False)sim.forward()passes asset writes and model changes to the solverReordering terms
Within a phase, uses run in the order of the task config:
On an
MDPBuilder:finalize()raises if a use reads what a later use of its phase writes, or another use's state before that use runs.Python hooks
A hook can take scene entities, call their writers and setters, and launch its own kernels. It runs inside the graph:
inputs={"asset": robot}outputs={"robot": robot}cachemdp2.Term(..., capturable=False)Commits
Reset events write in place; the scene commits once after them, or earlier when needed:
Writes to read-only fields (body poses, sensor data, joint accelerations) are rejected at build time.
Checking capture
Other
mdp2.mdp, with the names ofisaaclab.envs.mdp.Term(random=True)→rng); Torch and Warp draw the same numbers.Internals
finalizeTermOp/ActionOpper use; ops shared by task configs merge, the rest are maskedstartup,apply_actions,evaluate,reset,observewp.funcs into a few generated kernels (Go2: 27 uses → 5 kernels). Torch: one call per termCapture: the first step runs uncaptured, then each run of capturable work becomes one graph (
capture_graph).A
capturable=Falseterm or stage splits the step around it.Why fusion stays the default (MDP time per step, 4096 worlds, one graph either way):
Limitations
ArticulationCfg.joint_orderingandbody_orderingare not supported: their reordered copies refresh outside the graphs.root_lin_vel_b, is not refreshed by a captured step.Testing
source/isaaclab_experimental/test/mdp2/test_mdp2.py: builder, compiler, backends agree, capture, world configssource/isaaclab_experimental/test/envs/test_mdp2_{env,terms,contact_terms}.py: environments and the term library on Newtonsource/isaaclab_tasks/test/mdp2/test_lift_kuka_allegro.pydocs/source/experimental-features/mdp2.rst.🤖 Generated with Claude Code