Repository navigation
MDP2 Scenes That Carry Their Randomization #9322
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| isaaclab\_experimental.mdp2.contract | ||
| ==================================== | ||
|
|
||
| .. automodule:: isaaclab_experimental.mdp2.contract | ||
| :members: |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,91 @@ | ||
| # Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). | ||
| # All rights reserved. | ||
| # | ||
| # SPDX-License-Identifier: BSD-3-Clause | ||
|
|
||
| """Sample a scene's randomization contract offline into a bank of verified layouts that MDP2 replays at resets. | ||
|
|
||
| Each row is one sample of the reference solver (``usd_randomizer.solver``): the pose, relative to the scene's default | ||
| prim, of every rigid body that the sample moves. Rows that the solver cannot verify are skipped. Beside ``bank.npz``, | ||
| the record and receipt of each row reproduce and audit it. | ||
|
|
||
| The solver needs its own environment (``usd-randomizer[settle]``), not Isaac Lab's:: | ||
|
|
||
| <usd-randomizer venv>/bin/python scripts/tools/contract_bank.py scene.usda --rows 64 | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import argparse | ||
| import time | ||
| from pathlib import Path | ||
|
|
||
| import numpy as np | ||
| from usd_randomizer import contract as rc | ||
| from usd_randomizer.solver import Solver | ||
|
|
||
| from pxr import Usd, UsdGeom, UsdPhysics | ||
|
|
||
|
|
||
| def main() -> None: | ||
| parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) | ||
| parser.add_argument("scene", type=Path, help="USD scene with a randomization contract.") | ||
| parser.add_argument("--rows", type=int, default=64, help="Verified rows to bank.") | ||
| parser.add_argument("--output", type=Path, help="Bank directory; <scene>.bank beside the scene by default.") | ||
| args = parser.parse_args() | ||
| output = args.output or args.scene.with_suffix(".bank") | ||
| (output / "rows").mkdir(parents=True, exist_ok=True) | ||
|
|
||
| stage = Usd.Stage.Open(str(args.scene)) | ||
| (contract,) = rc.read(stage) | ||
| if not contract.ok: | ||
| raise rc.ContractError(contract.errors) | ||
| solver = Solver(contract, stage) | ||
|
|
||
| # A second stage, on which each sample's edits are applied in the session layer to read the poses they make. | ||
| posed = Usd.Stage.Open(str(args.scene)) | ||
| posed.SetEditTarget(posed.GetSessionLayer()) | ||
| root = posed.GetDefaultPrim() | ||
| to_root = UsdGeom.Xformable(root).ComputeLocalToWorldTransform(Usd.TimeCode.Default()).GetInverse() | ||
|
|
||
| prims, poses, seeds = None, [], [] | ||
| seed, start = 0, time.perf_counter() | ||
| 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 | ||
|
Comment on lines
+53
to
+58
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| posed.GetSessionLayer().Clear() | ||
| rc.apply(posed, sample.changes) | ||
| moved = sorted({c.path for c in sample.changes if c.kind == "transform"}) | ||
| moved = [p for p in moved if posed.GetPrimAtPath(p).HasAPI(UsdPhysics.RigidBodyAPI)] | ||
| if prims is None: | ||
| prims = moved | ||
| elif moved != prims: | ||
| raise ValueError(f"seed {seed} moves {moved}, other rows move {prims}: rows must move the same bodies") | ||
| row = [] | ||
| for path in prims: | ||
| world = UsdGeom.Xformable(posed.GetPrimAtPath(path)).ComputeLocalToWorldTransform(Usd.TimeCode.Default()) | ||
| matrix = (world * to_root).RemoveScaleShear() | ||
| q = matrix.ExtractRotationQuat() | ||
| row.append([*matrix.ExtractTranslation(), *q.GetImaginary(), q.GetReal()]) | ||
| poses.append(row) | ||
| sample.record.write(output / "rows" / f"{len(seeds):04}.record.jsonl") | ||
| sample.receipt.write(output / "rows" / f"{len(seeds):04}.receipt.json") | ||
| seeds.append(seed) | ||
| print(f"seed {seed}: verified, row {len(seeds) - 1} ({time.perf_counter() - start:.1f} s)") | ||
| seed += 1 | ||
|
|
||
| np.savez( | ||
| output / "bank.npz", | ||
| prims=np.array([p[len(root.GetPath().pathString) + 1 :] for p in prims]), | ||
| poses=np.array(poses, dtype=np.float32), | ||
| seeds=np.array(seeds), | ||
| contract_digest=rc.contract_digest(contract), | ||
| ) | ||
| print(f"{len(seeds)} rows of {len(prims)} bodies in {output}") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| * Added :mod:`isaaclab_experimental.mdp2.contract`, which runs the randomization contract of a USD scene | ||
| (``usd_randomizer``) in MDP2: layouts that ``scripts/tools/contract_bank.py`` solves offline are the reset states of | ||
| a ``reset_to_states`` event, and the masses that the contract draws per environment apply at startup. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,190 @@ | ||
| # Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). | ||
| # All rights reserved. | ||
| # | ||
| # SPDX-License-Identifier: BSD-3-Clause | ||
|
|
||
| """Scenes that carry their own randomization: a USD file with a randomization contract, run as part of an MDP2 task. | ||
|
|
||
| A randomization contract (``usd_randomizer.contract``) stores in the scene what may vary in it: distributions, the | ||
| operators that write their values to the scene, and the conditions that every sample keeps. Any tool that opens the | ||
| file can sample it. MDP2 runs what the contract says with two executors: | ||
|
|
||
| - **Layouts**, the poses that the contract's operators move rigid bodies to under its conditions (placed on a table, | ||
| apart, settled, stable), are solved offline by the reference solver into a bank (``scripts/tools/contract_bank.py``), | ||
| whose rows are the shared reset states of a :data:`~isaaclab_experimental.mdp2.mdp.reset_to_states` event | ||
| ``contract_layout``: every reset draws a row inside the CUDA graphs, and an evaluation can pin worlds to rows with | ||
| :meth:`~isaaclab_experimental.mdp2.mdp.ResetStates.pin`. Row ``i`` is the bank's ``rows/i`` record and receipt, | ||
| which reproduce and audit it. The solver checked the conditions of each row with its own draws of the other | ||
| operators, such as the masses, not with the masses of the world that replays it. | ||
| - **Physical properties** that ``attribute`` operators write, such as ``physics:mass``, are drawn per world with the | ||
| contract's own keyed draws at startup, so world ``i`` gets the values that any executor of the contract draws for | ||
| environment ``i``. | ||
|
|
||
| The scene file is spawned once per environment, and each rigid body in it is an entity named after its path below the | ||
| default prim:: | ||
|
|
||
| scene = contract_scene("tabletop.usda") # {"scene_file": AssetBaseCfg, "Target": RigidObjectCfg, ...} | ||
| task = mdp2.compose(contract_task("tabletop.usda"), TASK) | ||
|
|
||
| Nodes that neither executor runs are reported ``ignored`` by :func:`contract_task`. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import functools | ||
| from pathlib import Path | ||
|
|
||
| import numpy as np | ||
| import torch | ||
|
|
||
| from pxr import Usd, UsdPhysics | ||
|
|
||
| from isaaclab.assets import AssetBaseCfg, RigidObjectCfg | ||
| from isaaclab.sim import UsdFileCfg | ||
|
|
||
| from . import mdp | ||
| from .config import Entity, Event, EventMode, TaskCfg | ||
| from .eager import TermContext | ||
| from .terms import State, Term | ||
|
|
||
| BODY_ATTRIBUTES = ("physics:mass",) | ||
| """Attributes of rigid bodies that ``attribute`` operators may write; others are ignored.""" | ||
|
|
||
| POSE_OPERATORS = ("transform", "layout.placement", "layout.drop", "layout.settle") | ||
| """Operators whose writes to rigid bodies a bank holds, as their poses.""" | ||
|
|
||
|
|
||
| def _contract(usd_path: str): | ||
| """Return the stage of ``usd_path`` and its one randomization contract.""" | ||
| from usd_randomizer import contract as rc | ||
|
|
||
| stage = Usd.Stage.Open(str(usd_path)) | ||
| contracts = rc.read(stage) | ||
| if len(contracts) != 1: | ||
| raise ValueError(f"{usd_path} holds {len(contracts)} randomization contracts, expected one") | ||
| if not contracts[0].ok: | ||
| raise rc.ContractError(contracts[0].errors) | ||
| return stage, contracts[0] | ||
|
|
||
|
|
||
| def _entity_name(stage: Usd.Stage, path: str) -> str: | ||
| """The entity of a prim: its path below the default prim, with ``_`` for ``/``.""" | ||
| root = stage.GetDefaultPrim().GetPath().pathString | ||
| return path[len(root) + 1 :].replace("/", "_") | ||
|
|
||
|
|
||
| def contract_scene(usd_path: str, prim_path: str = "{ENV_REGEX_NS}/Scene") -> dict[str, AssetBaseCfg]: | ||
| """Return the scene entries of a USD scene: the file at ``prim_path``, as ``"scene_file"``, and each rigid body | ||
| under its default prim as a rigid object named after its path.""" | ||
| stage = Usd.Stage.Open(str(usd_path)) | ||
| root = stage.GetDefaultPrim() | ||
| entries: dict[str, AssetBaseCfg] = { | ||
| "scene_file": AssetBaseCfg(prim_path=prim_path, spawn=UsdFileCfg(usd_path=usd_path)) | ||
| } | ||
| for prim in Usd.PrimRange(root): | ||
| 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) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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. |
||
| return entries | ||
|
|
||
|
|
||
| def contract_task(usd_path: str, bank: str | None = None, seed: int = 0) -> TaskCfg: | ||
| """Return the part of a task that runs the contract of a USD scene. | ||
|
|
||
| Args: | ||
| usd_path: The scene, whose rigid bodies :func:`contract_scene` made entities. | ||
| bank: Directory of the layouts that ``scripts/tools/contract_bank.py`` solved; ``<usd_path>.bank`` if it | ||
| exists. Without one, the contract's layouts are ignored. | ||
| seed: Seed of the contract's draws. | ||
| """ | ||
| from usd_randomizer import contract as rc | ||
|
|
||
| stage, contract = _contract(usd_path) | ||
| bank = bank or Path(usd_path).with_suffix(".bank") | ||
| bank_file = Path(bank) / "bank.npz" | ||
| events, handled = {}, {} | ||
|
|
||
| # 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): | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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. |
||
| raise ValueError(f"{bank_file} was solved for another version of the contract: run contract_bank.py again") | ||
| poses = torch.from_numpy(data["poses"]).float() | ||
| num_rows = poses.shape[0] | ||
| outputs, states = {}, {} | ||
| for k, prim in enumerate(data["prims"]): | ||
| body = Entity(str(prim).replace("/", "_")) | ||
| outputs |= {f"{body.name}_pose": body.root_link_pose_w, f"{body.name}_velocity": body.root_com_vel_w} | ||
| states |= {f"{body.name}_pose": poses[:, k], f"{body.name}_velocity": torch.zeros(num_rows, 6)} | ||
| events["contract_layout"] = Event( | ||
| mdp.reset_to_states, | ||
| inputs={"env_origins": Entity("scene").env_origins}, | ||
| outputs=outputs, | ||
| params={"source": mdp.FromTensors(states), "shared": True}, | ||
|
Comment on lines
+120
to
+124
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. A valid contract that only changes masses produces verified samples with no moved bodies. The bank tool still writes empty |
||
| ) | ||
| # The bank holds the poses of the rigid bodies, and the solver checked every condition in every row. | ||
| banked = {f"{stage.GetDefaultPrim().GetPath()}/{prim}" for prim in data["prims"]} | ||
| for node in contract.operators: | ||
| targets = node.edge("targets").targets if node.edge("targets") else () | ||
| if node.type in POSE_OPERATORS and targets and set(targets) <= banked: | ||
| handled[node.path] = f"bank ({num_rows} rows)" | ||
| handled |= {node.path: f"checked offline ({num_rows} rows)" for node in contract.conditions} | ||
|
|
||
| # Physical properties: the contract's own draws per world, at startup. | ||
| @functools.cache | ||
| def draws(num_worlds: int): | ||
| sampler = rc.Sampler(contract, stage, envs=num_worlds) | ||
| return sampler, sampler.draw(rc.Request(seed=seed)) | ||
|
|
||
| for node in contract.operators: | ||
| if node.type != "attribute" or node.value("attribute") not in BODY_ATTRIBUTES: | ||
| continue | ||
| targets = node.edge("targets").targets | ||
| if not all(stage.GetPrimAtPath(t).HasAPI(UsdPhysics.RigidBodyAPI) for t in targets): | ||
| continue | ||
| nominal = [stage.GetPrimAtPath(t).GetAttribute(node.value("attribute")).Get() for t in targets] | ||
| for target, nominal_value in zip(targets, nominal): | ||
| body = _entity_name(stage, target) | ||
| events[f"contract_{node.id}_{body}"] = Event( | ||
| Term( | ||
| torch=_set_body_mass, | ||
| init=_body_value_drawer( | ||
| draws, node.first("distribution"), target, node.value("mode"), float(nominal_value) | ||
| ), | ||
| state={"value": State(persistent=True)}, | ||
| capturable=False, | ||
| ), | ||
| mode=EventMode.STARTUP, | ||
| inputs={"asset": Entity(body)}, | ||
| ) | ||
| handled[node.path] = "startup draws" | ||
|
|
||
| for node in contract.nodes: | ||
| if not node.is_distribution: | ||
| print(f"[contract] {node.type:18} {node.path}: {handled.get(node.path, 'ignored')}") | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Warning · Style Consistency — Log contract handling status Printing from contract_task bypasses configured log handlers and verbosity controls. Emit handling status through a module logger at INFO level. |
||
| return TaskCfg(events=events) | ||
|
|
||
|
|
||
| def _body_value_drawer(draws, distribution: str, target: str, mode: str, nominal: float): | ||
| """Return an init hook that keeps the value of ``distribution`` for ``target`` in every world, with the | ||
| operator's ``mode`` applied to the nominal value.""" | ||
|
|
||
| def draw_body_values(ctx: TermContext, **params) -> None: | ||
| sampler, drawn = draws(ctx.num_worlds) | ||
| identity = sampler.identity(target) | ||
| values = torch.tensor([drawn.value(distribution, identity, env) for env in range(ctx.num_worlds)]) | ||
| ctx.state["value"].copy_({"set": values, "offset": nominal + values, "scale": nominal * values}[mode]) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Warning · Scope Complexity — Compute only the selected mass mode Building this dictionary computes offset and scale tensors even for set mode. Branch on mode before arithmetic so initialization creates only the selected result. |
||
|
|
||
| return draw_body_values | ||
|
|
||
|
|
||
| def _set_body_mass(mask: torch.Tensor, asset, value: torch.Tensor) -> None: | ||
| env_ids = mask.nonzero().squeeze(-1) | ||
| body_ids = torch.zeros(1, dtype=torch.long, device=value.device) | ||
| old = asset.data.body_mass.torch[env_ids][:, body_ids] | ||
| new = value[env_ids, None].clamp(min=1e-6) | ||
| asset.set_masses_index(masses=new, body_ids=body_ids, env_ids=env_ids) | ||
| # Uniform density: the inertia scales with the mass. | ||
| inertia = asset.data.body_inertia.torch[env_ids][:, body_ids] * (new / old)[..., None] | ||
| asset.set_inertias_index(inertias=inertia, body_ids=body_ids, env_ids=env_ids) | ||
There was a problem hiding this comment.
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.