Skip to content

MDP2 Scenes That Carry Their Randomization - #9322

Open
StafaH wants to merge 1 commit into
isaac-sim:mainfrom
StafaH:mh/mdp2-usd-contract
Open

StafaH wants to merge 1 commit into
isaac-sim:mainfrom
StafaH:mh/mdp2-usd-contract

Conversation

@StafaH

@StafaH StafaH commented Dec 1, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Scenes that carry their randomization: an MDP2 task can take its scene and how that scene varies from one USD file, so teams can share an environment's layout and its randomization as a file, and each application samples it its own way.

Builds on #9112 (MDP2 Resets, now merged). This PR is a single commit on main.
Optional dependency: the file format is a usd_randomizer randomization contract. Only its usd_randomizer.contract package (usd-core and NumPy) is needed at run time. The task registers, and the tests run, only when it is installed.


The idea in one minute

A randomization contract stored in the USD declares distributions, the operators that write them to the scene, and the conditions every sample must keep, such as props on the table, apart, settled, and stable. MDP2 runs it with two executors:

What the contract varies How MDP2 runs it Why
Layouts: rigid-body poses under conditions Solved offline into a bank by the contract's reference solver, then the bank's rows become the shared reset states of a reset_to_states event (#9112) Conditions such as settled and stable need a physics solve and rejection, which don't belong inside a captured reset
Physical properties: attribute writes of physics:mass The contract's own keyed per-environment draws, at startup World i gets exactly the value any other executor of the same file draws for environment i

Because layouts are reset states, the resets from #9112 provide the rest at no extra cost:

  • Draws happen inside the step's CUDA graph.
  • An evaluation can pin worlds to chosen layouts: mdp.get_reset_states(env.state, "events.contract_layout").pin(rows).
  • A sampler with success scores can favour the layouts a policy fails on.
  • success_rate, episode_counts and started_from are available per layout.

At load, contract_task prints how it handles each contract node: bank, startup draws, checked offline, or ignored. Nothing is skipped silently.


Usage

from isaaclab_experimental.mdp2.contract import contract_scene, contract_task

# Scene: the file in every environment, plus one RigidObjectCfg per rigid body, named by its path.
for name, entry in contract_scene("tabletop.usda").items():
    setattr(scene, name, entry)

# Task: the contract's layout reset and mass draws, composed with an ordinary MDP2 task.
TASK = mdp2.compose(contract_task("tabletop.usda"), REACH_TARGET)

Solve the bank once, in the solver's own environment, then train:

<usd-randomizer venv>/bin/python scripts/tools/contract_bank.py tabletop.usda --rows 32
uv run python scripts/reinforcement_learning/train.py --rl_library rsl_rl \
    --task Isaac-Contract-Tabletop-Franka-MDP2 physics=newton_mjwarp
  • The bank (tabletop.bank/bank.npz) stores the contract's digest. A bank solved for an earlier version of the layout is refused at load.
  • Each row's record and receipt are committed next to it, so a layout can be reproduced and audited.
  • Changing the mass range in the file needs no new bank.

Changes

  • isaaclab_experimental.mdp2.contract: contract_scene and contract_task.
  • scripts/tools/contract_bank.py: samples verified layouts with the reference solver and writes the bank, with records and receipts.
  • Isaac-Contract-Tabletop-Franka-MDP2: a Franka hovering above a red prop. The table, three props and their randomization come from tabletop.usda; the robot and MDP come from Isaac Lab. author_scene.py regenerates the file.
  • Docs: a Scenes that carry their randomization section in the MDP2 guide, plus an API page.

Limits

  • Only rigid-body poses and physics:mass are run. Asset swaps, variants and presence would need different objects per world.
  • The solver checked each banked layout with its own draws of the masses, not the masses of the world that replays it.
  • The prop contacts on Newton are not reproducible run to run, nor are the Kuka lift's, so the capture check in the test compares the MDP with physics stubbed out.

Validation

  • test_contract.py:
    • Rows and draws (Newton, GPU, 4 worlds, verify_capture=20): each world's bodies sit at the bank row it drew, plus its origin, and its masses equal independent contract draws for its environment. Swapping the quaternion order in the bank's states turns it red.
    • Stale bank: a bank of an earlier contract is refused.
  • MDP2 environment smoke test: -k Contract passes.
  • Training: PPO, 4096 worlds, 300 iterations. Success went 9.7% (iteration 50) → 15% (100) → 99.0% (150) → 99.98% (299).
  • The dumped params/env.yaml reads back with load_yaml. The bank's tensors are described, not pickled, through the dump fix in MDP2 Resets #9112.
  • uv run isaaclab -f passes.

Type of change

  • New feature (non-breaking change which adds functionality)

Checklist

  • I have read and understood the contribution guidelines
  • I have run the pre-commit checks with uv run isaaclab --format
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have validated the changed behavior with focused coverage and applied the test-audit criteria to any test changes
  • I have added a changelog fragment under source/<pkg>/changelog.d/ for every touched package
  • I have added my name to the CONTRIBUTORS.md or my name already exists there

@StafaH
StafaH requested a review from a team December 1, 2026 01:27
@github-actions github-actions Bot added documentation Improvements or additions to documentation isaac-lab Related to Isaac Lab team labels Dec 1, 2026
@greptile-apps

greptile-apps Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 4/5RetriggerView in Greptile

[Medium impact] The new behavior is limited to optional experimental MDP2 scene-contract tasks.

Include the required scene and bank in the installed package before merging.

Findings

  1. P1 Installed task lacks required files ▶
  2. P2 Empty banks break startup ▶
  3. P2 Body names silently collide ▶
  4. P2 Bank generation can run forever ▶

Summary

Adds USD contract scenes to MDP2.

  • MDP2 can run supported randomization rules from a USD scene.
  • The Franka reach example gets its scene and randomization from USD.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  USD["USD scene and contract"] --> Solver["Offline solver"]
  Solver --> Bank["Layout bank and row records"]
  USD --> Scene["Scene entries"]
  USD --> Draws["Startup mass draws"]
  Bank --> Reset["Shared reset states"]
  Scene --> Task["MDP2 task"]
  Draws --> Task
  Reset --> Task
Loading

Reviews (2) · Last reviewed commit: "Run USD randomization contracts in MDP2 ..." · Reviewed by Greptile

if prim.HasAPI(UsdPhysics.RigidBodyAPI):
path = prim.GetPath().pathString
relative = path[len(root.GetPath().pathString) :]
entries[_entity_name(stage, path)] = RigidObjectCfg(prim_path=prim_path + relative, spawn=None)

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.

P2 Body names silently collide

contract_scene turns both /Scene/A/B and /Scene/A_B into A_B, so the later body replaces the earlier scene entry. contract_task uses the same names for its outputs and stored states, losing one body's reset data too. Reject duplicate names before inserting them, or use names that keep these paths distinct.

Comment on lines +53 to +58
while len(seeds) < args.rows:
sample = solver.sample(rc.Request(seed=seed))
if sample.status != "verified":
print(f"seed {seed}: {sample.status}, skipped")
seed += 1
continue

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.

P2 Bank generation can run forever

contract_bank.py has no overall limit on failed samples. A valid contract whose conditions cannot all be met keeps returning unverified samples, so this loop retries forever without saving a bank. Add a configurable attempt limit and stop with the number of rows collected and a useful error.

@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: Design and architecture (1), Scope and over-engineering (2), Compatibility and deprecation (4), Implementation (3), Style consistency (3), Test quality (3). Other reviewed categories look good.

  • PR description: Full-diff scope exceeds the title/body: correct non-breaking and mass-bank reuse claims, trim repeated rationale, preserve template sections, and supply reset-cost baseline/candidate revisions, command/workload, hardware, backend, environment count, warmup, and latency.
  • Design and architecture: prototype_groups bypasses the bound scene through the simulation singleton; pass resolved prototype layout from the scene owner to avoid global lifecycle coupling.
  • Scope and over-engineering: Minimal implementation: extend core buffer/sampler and MDP2 lifecycle owners; keep reset_states.py for persistent reset contracts, contract.py for USD adaptation, both generation scripts for separate runtimes, and contract_tabletop/{init,author_scene,mdp,tabletop_env_cfg}.py for registration, regeneration, terms, and configuration; eliminate identity bank copies and unused mass-mode calculations. Suggested PR breakdown: (1) core serialization/reset APIs, validated by core tests; (2) MDP2 resets/Lift migration, validated by analytic/physical tests; (3) USD adapter, bank tool, tabletop task/docs, validated by contract tests.
  • API: API changes look good.
  • Compatibility and deprecation: Breaking changes: Lift imports, CANDIDATES, reset overrides, and defaults lose their transition paths; YAML tensor dumps lose values; preserve old behavior with targeted deprecation, migration/removal guidance, and transition coverage.
  • Implementation: Bank generation retries indefinitely when no sample verifies; add a total attempt budget and fail with the verified-row count when exhausted.
  • Style consistency: contract_task prints library status outside configured logging; emit handling summaries through a module logger at INFO level.
  • Test quality: The default-reset test lacks an earlier reset writer and outcome tracking, so it cannot prove its claimed behavior; add those conditions or narrow the test.

Needs rework. Posted 16 inline findings.

Automated review; human maintainers own approval decisions.


prims, poses, seeds = None, [], []
seed, start = 0, time.perf_counter()
while len(seeds) < args.rows:

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.

🔴 Critical · Implementation — Bound bank sampling attempts

An infeasible contract never produces a verified row, so this loop runs forever. Set a total attempt budget and fail with the verified-row count when it is exhausted.


_Dumper.add_multi_representer(
torch.Tensor,
lambda dumper, tensor: dumper.represent_str(f"tensor(shape={list(tensor.shape)}, dtype={tensor.dtype})"),

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.

🔴 Critical · Compatibility — Keep YAML tensor contents

dump_yaml now replaces every tensor’s values with a shape-and-dtype string, irreversibly changing existing serialized output. Preserve value-bearing dumps by default and make reporting summaries opt-in.

ctx.state[f"bank_{name}"].copy_(value)


reset_from_bank = mdp2.Term(

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.

🔴 Critical · Compatibility — Keep the Lift reset contract

Deleting reset_from_bank breaks existing imports and configured Lift reset uses. Keep the old module and term functional during a targeted, documented deprecation with old- and new-path tests.

if prim.HasAPI(UsdPhysics.RigidBodyAPI):
path = prim.GetPath().pathString
relative = path[len(root.GetPath().pathString) :]
entries[_entity_name(stage, path)] = RigidObjectCfg(prim_path=prim_path + relative, spawn=None)

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.

🟡 Warning · Implementation — Reject flattened-name collisions

A/B and A_B both become A_B; the later entry silently replaces the first and contract events can target the wrong entity. Reject duplicate generated names.

# Layouts: the bank's rows are reset states that every world shares, in the frame of its origin.
if bank_file.exists():
data = np.load(bank_file)
if str(data["contract_digest"]) != rc.contract_digest(contract):

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.

🟡 Warning · Implementation — Separate layout and mass validity

The whole-contract digest rejects a layout bank after a mass-range edit, contradicting the documented no-resolve workflow. Validate against the layout’s dependencies instead.


def test_default_resets_keep_the_earlier_events_and_are_not_credited():
scene = Scene(num_worlds=4)
task_mdp, state = build(

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.

🟡 Warning · Test Quality — Exercise the claimed default-reset behavior

This case has no earlier reset writer and omits the outcome-tracking sampler; its sentinel and zero count cannot prove either claimed behavior. Add those conditions or narrow the test.

reset_states = mdp.get_reset_states(state)

stored = reset_states.states["goal"]
assert ((stored >= 1.0) & (stored < 2.0)).all() and len(stored.unique()) == 12 # sampled, not the initial 0

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.

🟡 Warning · Test Quality — Drop probabilistic uniqueness assertion

Twelve valid independent draws may repeat, so requiring twelve unique values makes this test fail without a regression. Retain the range and nonzero assertions instead.


@configclass
class TabletopPhysicsCfg(PresetCfg):
"""Newton MJWarp with Newton's collision pipeline, whose contacts with the props are reproducible run to run."""

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.

🟡 Warning · Style Consistency — Remove the contact reproducibility claim

This docstring promises reproducible prop contacts, while test_contract disables reproducible physics for them. Describe the configured collision pipeline without that claim.



CANDIDATES = mdp2.TaskCfg(
RESET_STATE_GENERATOR = mdp2.TaskCfg(

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.

🟡 Warning · Compatibility — Retain the candidate task name

Renaming module-level CANDIDATES breaks imports used to customize Lift generation. Keep a functional deprecated alias with replacement guidance and transition coverage.

"target_success_rate": 0.5,
"kappa": 1.0,
# A world per object, as in small test runs, needs a roll per state.
"source": mdp.FromTask(RESET_STATE_GENERATOR, num_states=1024, max_rolls=20000),

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.

🟡 Warning · Compatibility — Preserve Lift reset configuration

bank_size, history_length, target_success_rate, and kappa overrides no longer configure this task; its default also changes from 16 per-world states to 1024 grouped states. Preserve the old configuration through deprecation.

@StafaH
StafaH force-pushed the mh/mdp2-usd-contract branch from 6819cf5 to 07e2304 Compare December 1, 2026 01:42
A USD scene can carry its randomization as a usd-randomizer contract.
contract_scene spawns the file and its rigid bodies; contract_task makes
the layouts that scripts/tools/contract_bank.py solves offline the shared
reset states of a reset_to_states event, and draws the contract's
per-environment masses at startup. Adds Isaac-Contract-Tabletop-Franka-MDP2.
@StafaH
StafaH force-pushed the mh/mdp2-usd-contract branch from 07e2304 to a8c40fa Compare December 1, 2026 22:36
@StafaH
StafaH marked this pull request as draft December 1, 2026 22:38
@StafaH
StafaH marked this pull request as ready for review December 2, 2026 05:42
from ..reach.reach_env_cfg import joint_limits, joint_state, robot
from . import mdp as tabletop

SCENE_USD = str(Path(__file__).with_name("tabletop.usda"))

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.

P1 Installed task lacks required files

The task reads tabletop.usda and tabletop.bank/bank.npz beside this module, but the package only includes *.pyi as package data and has no MANIFEST.in. A non-editable wheel omits these files, so loading the task fails when contract_task opens the scene. Include the USD file, bank, and row records in the package data.

Comment on lines +120 to +124
events["contract_layout"] = Event(
mdp.reset_to_states,
inputs={"env_origins": Entity("scene").env_origins},
outputs=outputs,
params={"source": mdp.FromTensors(states), "shared": True},

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.

P2 Empty banks break startup

A valid contract that only changes masses produces verified samples with no moved bodies. The bank tool still writes empty prims, and contract_task creates a contract_layout event with no outputs. At startup, reset_to_states rejects its empty states with ValueError, so a scene that could run startup mass draws now fails to load. Reject banks with no moved rigid bodies with a clear message, or skip the layout event when the bank is empty.

This branch has not been deployed

No deployments
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.

1 participant