From d6571ee5deb5c8d0553f2db4e209e9f27641c21a Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 18:02:29 -0800 Subject: [PATCH 01/49] Bring the MDP2 features of the Arena prototype to MDP2 Cameras, typed observation groups, action terms, an episode budget, and task composition with milestones, sequences, and splits, from the MDP2-Arena draft (#9091), without its pick-and-place example. --- .../isaaclab_experimental.mdp2.mdp.rst | 6 + .../isaaclab_experimental.mdp2.rst | 21 + docs/source/experimental-features/mdp2.rst | 100 +++- .../changelog.d/mdp2-part2.added.rst | 30 ++ .../changelog.d/mdp2-part2.changed.rst | 6 + .../changelog.d/mdp2-part2.major | 0 .../isaaclab_experimental/envs/mdp2_env.py | 289 +++++++++-- .../envs/mdp2_env_cfg.py | 50 +- .../envs/mdp2_scene_data.py | 28 +- .../isaaclab_experimental/envs/mdp2_verify.py | 9 +- .../isaaclab_experimental/mdp2/__init__.pyi | 28 +- .../isaaclab_experimental/mdp2/builder.py | 461 +++++++++++++++--- .../isaaclab_experimental/mdp2/compiled.py | 161 +++++- .../isaaclab_experimental/mdp2/config.py | 179 ++++++- .../mdp2/mdp/__init__.pyi | 10 + .../isaaclab_experimental/mdp2/mdp/actions.py | 62 +++ .../mdp2/mdp/observations.py | 56 +++ .../mdp2/mdp/terminations.py | 13 + .../isaaclab_experimental/mdp2/plan.py | 147 +++++- .../isaaclab_experimental/mdp2/terms.py | 1 + .../mdp2/torch_backend.py | 178 ++++++- .../mdp2/warp_backend.py | 344 +++++++++++-- .../test/envs/test_mdp2_env.py | 176 ++++++- .../test/mdp2/test_mdp2.py | 376 +++++++++++++- .../changelog.d/mdp2-part2.changed.rst | 2 + .../changelog.d/mdp2-part2.minor | 0 .../mdp2/velocity_go2/flat_env_cfg.py | 12 +- .../test/mdp2/test_lift_kuka_allegro.py | 2 +- 28 files changed, 2517 insertions(+), 230 deletions(-) create mode 100644 source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst create mode 100644 source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst create mode 100644 source/isaaclab_experimental/changelog.d/mdp2-part2.major create mode 100644 source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/actions.py create mode 100644 source/isaaclab_tasks/changelog.d/mdp2-part2.changed.rst create mode 100644 source/isaaclab_tasks/changelog.d/mdp2-part2.minor diff --git a/docs/source/api/lab_experimental/isaaclab_experimental.mdp2.mdp.rst b/docs/source/api/lab_experimental/isaaclab_experimental.mdp2.mdp.rst index e9c26d8e323e..b735735e3b21 100644 --- a/docs/source/api/lab_experimental/isaaclab_experimental.mdp2.mdp.rst +++ b/docs/source/api/lab_experimental/isaaclab_experimental.mdp2.mdp.rst @@ -9,6 +9,12 @@ Observations .. automodule:: isaaclab_experimental.mdp2.mdp.observations :members: +Actions +------- + +.. automodule:: isaaclab_experimental.mdp2.mdp.actions + :members: + Commands -------- diff --git a/docs/source/api/lab_experimental/isaaclab_experimental.mdp2.rst b/docs/source/api/lab_experimental/isaaclab_experimental.mdp2.rst index a0fdb19c863f..dff8ab9b0412 100644 --- a/docs/source/api/lab_experimental/isaaclab_experimental.mdp2.rst +++ b/docs/source/api/lab_experimental/isaaclab_experimental.mdp2.rst @@ -22,7 +22,9 @@ Terms and task configuration SubsetSelector TaskCfg DirectAction + Action Observation + ObservationGroup Reward Termination TimeLimit @@ -32,6 +34,13 @@ Terms and task configuration Quantity UniformNoise term_state + compose + sequence + split + Milestone + TaskMode + progress + progress_field Building and running -------------------- @@ -41,6 +50,7 @@ Building and running MDPBuilder MDP + ObservationColumns MDPState Transition Backend @@ -73,7 +83,9 @@ Scene data .. autoclass:: SubsetSelector .. autoclass:: TaskCfg .. autoclass:: DirectAction +.. autoclass:: Action .. autoclass:: Observation +.. autoclass:: ObservationGroup .. autoclass:: Reward .. autoclass:: Termination .. autoclass:: TimeLimit @@ -84,10 +96,19 @@ Scene data .. autoclass:: Quantity .. autoclass:: UniformNoise .. autofunction:: term_state +.. autofunction:: compose +.. autofunction:: sequence +.. autofunction:: split +.. autoclass:: Milestone +.. autoclass:: TaskMode + :members: +.. autodata:: progress +.. autofunction:: progress_field .. autoclass:: MDPBuilder :members: .. autoclass:: MDP :members: +.. autoclass:: ObservationColumns .. autoclass:: MDPState :members: .. autoclass:: Transition diff --git a/docs/source/experimental-features/mdp2.rst b/docs/source/experimental-features/mdp2.rst index 3eb0a2ca0210..0eabc9049274 100644 --- a/docs/source/experimental-features/mdp2.rst +++ b/docs/source/experimental-features/mdp2.rst @@ -95,7 +95,62 @@ each runtime function's steps. print(mdp.describe()) :class:`~isaaclab_experimental.mdp2.MDPBuilder.replicate` runs different task configs, with their own rewards and -weights, in different worlds of one scene. +weights, in different worlds of one scene; :func:`~isaaclab_experimental.mdp2.split` does it from a task config. + + +Subtasks and progress +--------------------- + +A task may say when it is ``done``, and hold named subtasks, which are tasks too. Three functions combine tasks into +one: + +.. list-table:: + :header-rows: 1 + + * - Function + - Subtasks run + - The task is done + * - :func:`~isaaclab_experimental.mdp2.compose` + - in the same worlds, at the same steps + - once ``require`` of them are (all by default) + * - :func:`~isaaclab_experimental.mdp2.sequence` + - in the same worlds, one after another + - once the last one is + * - :func:`~isaaclab_experimental.mdp2.split` + - each in its own worlds + - once the one of the world is + +.. code-block:: python + + q = mdp2.quantities + TASK = mdp2.compose( + BASE, # Uses of every step: observations, the action rate, the 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), + ), + ) + terminations = {"success": mdp2.Termination(mdp.is_true, inputs={"value": mdp2.progress.done})} + +- **Completion.** ``done`` is a field of one value per world, true where positive, that must hold for ``hold`` steps + in a row, counted from the step after the task starts. A :class:`~isaaclab_experimental.mdp2.Milestone` is a task + with only a completion. ``final=True`` (or ``False``) makes the parent done only while the subtask's completion + still holds (or does not), and ``score`` weighs the subtask in the parent's score. +- **Stages.** A subtask of a sequence starts at the step after the previous one is done, and the last one keeps + running. Its uses run only while it does: its rewards, terminations, commands, and events follow the subtask that + ran when the step started, and its observations the one that runs after it. Starting restarts their state, timers, + commands, and observation histories. Quantities are measurements: they run in every step, and only restart. Reset + and startup events set up whole episodes, so they run at every reset. +- **Names.** The uses of a subtask get its name as a prefix, as in ``rewards.grasp.grasp``, except in a split, whose + subtasks run apart. A subtask reads its own commands and quantities by their names, as a task alone does, so + each stage of a sequence can have its own ``reached``; ``term_state`` and ``mdp2.progress`` take full paths. Observations of the same name share their columns, as wide as the widest, so a ``goal`` of each + stage, or the ``joint_pos`` of two robots, is one input of the policy; :meth:`~isaaclab_experimental.mdp2.MDP.spec` + names the columns, and :meth:`~isaaclab_experimental.mdp2.MDP.observation_mask` gives those each world writes. +- **Progress.** Every task's progress is a set of fields that terms read: ``mdp2.progress.done``, + ``mdp2.progress.grasp.done``, and also ``holding``, ``active``, ``score``, ``done_at``, ``started_at``, and a + sequence's ``stage`` (observed with :data:`~isaaclab_experimental.mdp2.mdp.one_hot`). ``MDP2RLEnv`` logs whether each + task was done as ``Progress/``. Backends and capture @@ -124,14 +179,15 @@ in them; it calls ``fn(env)`` with full access to the environment, inside the st .. code-block:: python - cfg.step # [Step.PHYSICS, Step.EVALUATE, Step.RESET] + cfg.step # [Step.PHYSICS, Step.RENDER, Step.EVALUATE, Step.RESET] cfg.reset_step # [ResetStep.EVENTS, ResetStep.COMMIT, ResetStep.OBSERVE] cfg.step.insert(cfg.step.index(Step.PHYSICS) + 1, Stage(update_height_map)) # after the physics cfg.reset_step.insert(cfg.reset_step.index(ResetStep.OBSERVE), Stage(move_objects)) # after the commit cfg.step.append(Stage(log_episode_length, capturable=False)) # at the end, on the host -The built-in steps must each appear once, in this order; the environment raises otherwise. +The built-in steps must each appear once, in this order, except the optional ``Step.RENDER`` and +``ResetStep.RENDER``; the environment raises otherwise. The fused ``wp.func`` path is what makes MDP2 fast: one kernel per statement instead of fused kernels costs Go2 78 → 121 µs and Lift 234 → 293 µs per step at 4096 worlds, also inside a graph. Library terms use it; Python hooks and @@ -158,6 +214,44 @@ solver's model: about 250 µs per step for 4096 Cartpole worlds on MJWarp. Rando can. +Cameras, composition, and evaluation +------------------------------------ + +These features let an evaluation framework, such as Isaac Lab Arena, build its environments on MDP2: a policy such as +a vision-language-action model reads camera images and named observation terms, and the environment reports how each +episode ended. + +- **Cameras** are scene entities whose data types are fields, such as ``external_camera.rgb``. ``MDP2Env`` renders + them once per control step at ``Step.RENDER``, after the physics, inside the step's CUDA graph; a step without + ``Step.RENDER`` is an error when the scene has cameras. Insert ``ResetStep.RENDER`` before ``ResetStep.OBSERVE`` in + ``reset_step`` to render them again after the resets, so that new episodes start with their own images. +- **Observation groups.** A group in :attr:`~isaaclab_experimental.mdp2.TaskCfg.observations` is a dict of uses, + concatenated into one ``float32`` tensor, or an :class:`~isaaclab_experimental.mdp2.ObservationGroup`. With + ``concatenate=False``, the group is observed as a dict of tensors with each term's own shape and type, such as + ``uint8`` images from :data:`~isaaclab_experimental.mdp2.mdp.image_rgb`. +- **Action terms.** A :class:`~isaaclab_experimental.mdp2.DirectAction` scales its columns of the action into a + field. An :class:`~isaaclab_experimental.mdp2.Action` runs a term's hook on its columns instead, such as + :data:`~isaaclab_experimental.mdp2.mdp.binary_joint_position` for a gripper, which closes on either side of a + threshold, as MDP1's binary joint actions do. +- **Composition.** :func:`~isaaclab_experimental.mdp2.compose` merges partial task configs term by term, such as + those of a scene, an embodiment, and a task, and reports uses that two of them define; a later part removes a use + by setting it to ``None``. Uses keep the order of the parts. +- **Success** is the completion of the task, built from milestones and subtasks (see `Subtasks and progress`_), + which a :class:`~isaaclab_experimental.mdp2.Termination` ends the episode on. +- **Episode budget.** With ``episode_budget``, ``MDP2RLEnv`` runs that many episodes over its worlds, then stops them, + and records each episode on the device: its world, length, how it ended, its ``Quantity(record=True)`` values, and + the step at which each task was done. :meth:`~isaaclab_experimental.envs.MDP2RLEnv.episode_records` returns them. + +.. code-block:: python + + cfg.episode_budget = 50 + env = MDP2RLEnv(cfg) + obs, _ = env.reset() + while env.episodes_completed < cfg.episode_budget: + obs, *_ = env.step(policy(obs["policy"], obs["camera_obs"])) + success_rate = env.episode_records()["termination/success"].mean() + + Limitations ----------- diff --git a/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst new file mode 100644 index 000000000000..c4b1e094c27c --- /dev/null +++ b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst @@ -0,0 +1,30 @@ +* Added cameras to :class:`~isaaclab_experimental.envs.MDP2Env`: their data types are scene fields that terms read, + such as ``camera.rgb``, and the environment renders them once per control step at + :attr:`~isaaclab_experimental.envs.Step.RENDER`, inside the step's CUDA graph. + :attr:`~isaaclab_experimental.envs.ResetStep.RENDER` renders them again after resets. +* Added :class:`~isaaclab_experimental.mdp2.ObservationGroup`, whose ``concatenate=False`` keeps a buffer per term, + with the term's own shape and element type, such as ``uint8`` images, observed as a dict of tensors, and + :data:`~isaaclab_experimental.mdp2.mdp.image_rgb`. +* Added :class:`~isaaclab_experimental.mdp2.Action`, action terms whose hooks turn their columns of the action into + writes, and :data:`~isaaclab_experimental.mdp2.mdp.binary_joint_position`, a binary gripper command with a + threshold. +* Added :func:`~isaaclab_experimental.mdp2.compose`, which merges partial task configs, such as those of a scene, an + embodiment, and a task, in order. +* Added tasks of tasks to MDP2: a :class:`~isaaclab_experimental.mdp2.TaskCfg` may say when it is ``done`` (with + ``hold``, ``score``, and ``final``) and hold named subtasks, which run together + (:func:`~isaaclab_experimental.mdp2.compose`, with ``require``), one after another + (:func:`~isaaclab_experimental.mdp2.sequence`), or in their own worlds (:func:`~isaaclab_experimental.mdp2.split`). + :class:`~isaaclab_experimental.mdp2.Milestone` is a task with only a completion. The uses of a task of a sequence run + while it does, and restart when it starts. Terms read the progress of every task, such as + ``mdp2.progress.grasp.done``, and :class:`~isaaclab_experimental.envs.MDP2RLEnv` logs it as ``Progress/`` and + records the step at which each task was done. +* Added :meth:`~isaaclab_experimental.mdp2.MDP.spec` and :meth:`~isaaclab_experimental.mdp2.MDP.observation_mask`, + which name the columns of the observation buffers and the columns each world writes. +* Added :data:`~isaaclab_experimental.mdp2.mdp.joint_pos_normalized`, :data:`~isaaclab_experimental.mdp2.mdp.is_true`, + and :data:`~isaaclab_experimental.mdp2.mdp.one_hot`. +* Added an episode budget to :class:`~isaaclab_experimental.envs.MDP2RLEnv` for evaluation, ``episode_budget``: worlds + stop starting episodes once the budget is spent, and every episode is recorded on the device, with the quantities + marked ``Quantity(record=True)``, in :meth:`~isaaclab_experimental.envs.MDP2RLEnv.episode_records`. +* Added OptiX cameras to :class:`~isaaclab_experimental.envs.MDP2Env`: cameras with + :class:`~isaaclab_newton.renderers.NewtonOptixRendererCfg` render between the CUDA graphs of a step, since OptiX + refits its acceleration structures on the host. diff --git a/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst b/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst new file mode 100644 index 000000000000..abf206a6a438 --- /dev/null +++ b/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst @@ -0,0 +1,6 @@ +* **Breaking:** Changed :attr:`~isaaclab_experimental.envs.MDP2EnvCfg.task` to one task: a task that splits the worlds between + tasks is :func:`~isaaclab_experimental.mdp2.split`, which replaces the list of tasks and ``task_worlds``. Migrate + ``task=[WALK, STAND], task_worlds=[3072, 1024]`` to + ``task=mdp2.split(walk=WALK, stand=STAND, worlds={"walk": 3072, "stand": 1024})``. +* **Breaking:** Changed the observation columns of MDP2 world configs: observations of the same name share their columns, as wide + as the widest, and each name has its own, instead of each world config's observations starting at the first column. diff --git a/source/isaaclab_experimental/changelog.d/mdp2-part2.major b/source/isaaclab_experimental/changelog.d/mdp2-part2.major new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py index e3d1483d1b73..306e400045d8 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py @@ -8,6 +8,7 @@ from __future__ import annotations import copy +import dataclasses import functools import itertools import math @@ -19,9 +20,11 @@ import torch import warp as wp from isaaclab_newton.physics.newton_backend import capture_graph +from isaaclab_newton.renderers import NewtonOptixRendererCfg, NewtonWarpRendererCfg from isaaclab.envs.common import VecEnvObs, VecEnvStepReturn from isaaclab.scene import InteractiveScene +from isaaclab.sensors import Camera, CameraCfg, SensorBase from isaaclab.sim import SimulationContext from isaaclab.sim.utils import use_stage from isaaclab.utils.seed import configure_seed @@ -40,11 +43,14 @@ class MDP2Env: """An interactive scene driven by an MDP2 task, like a :class:`~isaaclab.envs.ManagerBasedEnv` without managers. - A control step applies the actions, steps the physics ``decimation`` times, evaluates the MDP, resets the - worlds whose episodes ended, and observes them, in the order of the config's ``step`` and ``reset_step``, with - their :class:`~.mdp2_env_cfg.Stage` s. Resets are masks over the worlds, so every step after the first replays as - CUDA graphs, physics included: one graph for a fully capturable step, and otherwise one per run of capturable - work, with the work that cannot be captured run between them. Newton only. + A control step applies the actions, steps the physics ``decimation`` times, renders the cameras, evaluates the + MDP, resets the worlds whose episodes ended, and observes them, in the order of the config's ``step`` and + ``reset_step``, with their :class:`~.mdp2_env_cfg.Stage` s. Resets are masks over the worlds, so every step after + the first replays as CUDA graphs, physics and rendering included: one graph for a fully capturable step, and + otherwise one per run of capturable work, with the work that cannot be captured run between them. Newton only. + + :attr:`observations` holds a tensor per concatenated group, and a dict of tensors, one per term with the term's + shape and type, per group that is not concatenated. """ diagnostics: ClassVar[bool] = False # Whether evaluate writes the reward and termination of every term @@ -77,12 +83,39 @@ def _init_sim(self) -> None: # shallow copy keeps the entities that were added to the config as attributes, and the caller's config. scene_cfg = copy.copy(cfg.scene) scene_cfg.lazy_sensor_update = False + scene_cfg.__dict__.update(_without_renderer_graphs(scene_cfg)) with use_stage(sim.stage): self.scene = InteractiveScene(scene_cfg) sim.register_interactive_scene(self.scene) with use_stage(sim.stage): sim.reset() - self.scene.update(dt=self.physics_dt) + # The cameras render once per control step, the other sensors refresh with every physics step. + scene = self.scene + self._cameras = [sensor for sensor in scene.sensors.values() if isinstance(sensor, Camera)] + # OptiX refits its acceleration structures on the host, which a CUDA graph cannot record: such cameras render + # between the graphs of a step. + self._render_capturable = not any( + isinstance(camera.cfg.renderer_cfg, NewtonOptixRendererCfg) for camera in self._cameras + ) + if self._cameras and Step.RENDER not in cfg.step: + raise ValueError("The scene has cameras, so MDP2EnvCfg.step must hold Step.RENDER, or they never render.") + sensors = [sensor for sensor in scene.sensors.values() if not isinstance(sensor, Camera)] + # Sensors that support it refresh together, as in the scene's update. + self._batched_sensors = [sensor for sensor in sensors if sensor.supports_batch_update] + self._sensors = [sensor for sensor in sensors if not sensor.supports_batch_update] + self._assets = [ + asset + for assets in ( + scene.articulations, + scene.rigid_objects, + scene.rigid_object_collections, + scene.deformable_objects, + scene.cable_objects, + scene.surface_grippers, + ) + for asset in assets.values() + ] + self._update_scene(self.physics_dt) sim.backend_manager.set_decimation(cfg.decimation) # Newton-native actuators step all substeps in one call. @@ -91,15 +124,7 @@ def _init_sim(self) -> None: self.scene_data = InteractiveSceneData(self.scene, sim, self.step_dt) schema = self.scene_data.schema builder = mdp2.MDPBuilder(schema) - if isinstance(cfg.task, mdp2.TaskCfg): - builder.add_task(cfg.task) - else: - # The first tasks get one more world when the worlds do not split evenly. - for index, task in enumerate(cfg.task): - task_builder = mdp2.MDPBuilder(schema) - task_builder.add_task(task) - num_worlds = schema.num_worlds // len(cfg.task) + (index < schema.num_worlds % len(cfg.task)) - builder.replicate(task_builder, num_worlds if cfg.task_worlds is None else cfg.task_worlds[index]) + builder.add_task(cfg.task) self.mdp = builder.finalize( device=self.device, backend=cfg.backend, @@ -113,6 +138,7 @@ def _init_sim(self) -> None: # Startup events write scene fields in place, which the scene commits to the solver. self.scene_data.commit(self._all_envs.warp, self.mdp.startup_writes) self.transition = self.mdp.transition() + self._observations = self._views(self.transition.observations) self.actions = ProxyArray(wp.zeros((self.num_envs, self.mdp.action_dim), dtype=wp.float32, device=self.device)) # The worlds whose scene writes a step commits: those reset, and those where an interval event wrote. @@ -153,7 +179,7 @@ def is_captured(self) -> bool: @property def observations(self) -> VecEnvObs: """The observations of every group, as Torch views of buffers that each step overwrites.""" - return {group: values.torch for group, values in self.transition.observations.items()} + return self._observations def reset(self, seed: int | None = None, options: dict[str, Any] | None = None) -> tuple[VecEnvObs, dict]: """Reset every world and return their observations. A seed also reseeds the MDP's random streams.""" @@ -161,7 +187,7 @@ def reset(self, seed: int | None = None, options: dict[str, Any] | None = None) seed = configure_seed(seed) # In place: captured graphs hold the buffer's address. self.state.rng.torch.copy_(rng.streams(seed, self.mdp.streams, self.num_envs, self.device)) - for _, work in self._reset_work(self._all_envs): + for _, work in self._reset_work(self._all_envs, render=True): work() return self.observations, self.extras @@ -214,6 +240,8 @@ def _step_work(self) -> list[tuple[bool, Callable[[], None]]]: for item in self.cfg.step: if item is Step.PHYSICS: work.append((True, self._simulate)) + elif item is Step.RENDER: + work += [(self._render_capturable, self._render)] if self._cameras else [] elif item is Step.EVALUATE: work += [ (launch.capturable, functools.partial(launch, evaluate)) for launch in self.mdp.launches.evaluate @@ -225,19 +253,26 @@ def _step_work(self) -> list[tuple[bool, Callable[[], None]]]: work.append(self._stage_work(item)) return work - def _reset_work(self, mask: ProxyArray) -> list[tuple[bool, Callable[[], None]]]: - """Return the work of resetting the masked worlds, in the order of the config's ``reset_step``.""" + def _reset_work(self, mask: ProxyArray, render: bool = False) -> list[tuple[bool, Callable[[], None]]]: + """Return the work of resetting the masked worlds, in the order of the config's ``reset_step``. With + ``render``, the cameras render before the observations also without ``ResetStep.RENDER``.""" launches = self.mdp.launches commit = functools.partial(self.scene_data.commit, mask.warp, self.mdp.reset_writes) reset = Call(self.state, mask=mask, commit=commit) observe = Call(self.state, mask=mask, observations=self.transition.observations) + rendering = [(self._render_capturable, self._render)] if self._cameras else [] + render = render and ResetStep.RENDER not in self.cfg.reset_step work = [] for item in self.cfg.reset_step: + if item is ResetStep.OBSERVE and render: + work += rendering if item is ResetStep.EVENTS: work.append((True, functools.partial(self._reset_scene, mask))) work += [(launch.capturable, functools.partial(launch, reset)) for launch in launches.reset] elif item is ResetStep.COMMIT: work.append((True, functools.partial(self._commit, mask))) + elif item is ResetStep.RENDER: + work += rendering elif item is ResetStep.OBSERVE: work += [(launch.capturable, functools.partial(launch, observe)) for launch in launches.observe] else: @@ -287,7 +322,39 @@ def _simulate(self) -> None: mdp2.apply_actions(self.mdp, self.state, self.actions) self.scene.write_data_to_sim() self.sim.step(render=False) - self.scene.update(dt=self.physics_dt * self._substeps) + self._update_scene(self.physics_dt * self._substeps) + + def _update_scene(self, dt: float) -> None: + """Refresh the asset data and the sensors other than cameras after a physics step, as the scene would.""" + self.sim.render_context.update_scene_state(self.sim.get_physics_step_count()) + for asset in self._assets: + asset.update(dt) + if self._batched_sensors: + SensorBase.update_batch(self._batched_sensors, dt) + for sensor in self._sensors: + sensor.update(dt, force_recompute=True) + + def _render(self) -> None: + """Render every camera in every world. Part of the captured step.""" + if not self._cameras: + return + if all(camera.supports_batch_update for camera in self._cameras): + SensorBase.update_batch(self._cameras, self.step_dt) + return + for camera in self._cameras: + camera.update(self.step_dt, force_recompute=True) + + def _views(self, buffers: dict[str, ProxyArray]) -> VecEnvObs: + """Return Torch views of observation buffers, grouped: a tensor per group, or a dict of term tensors.""" + observations: VecEnvObs = {} + for buffer, values in buffers.items(): + if "/" not in buffer: + observations[buffer] = values.torch + continue + group, term = buffer.split("/") + shape = self.mdp.observation_layouts[buffer][0] + observations.setdefault(group, {})[term] = values.torch.view(self.num_envs, *shape) + return observations def _commit(self, mask: ProxyArray) -> None: """Commit the writes of the reset events in the masked worlds, and of the interval events of the last step in @@ -308,8 +375,25 @@ def _reset_scene(self, mask: ProxyArray) -> None: sensor.reset(env_mask=mask.warp) +def _without_renderer_graphs(scene_cfg: Any) -> dict[str, CameraCfg]: + """Return the scene's Newton cameras with renderers that do not capture graphs of their own. + + The step's CUDA graph already holds the renders. With several cameras, the graph that the renderer captures per + camera goes stale once the scene allocates more memory, and renders black images. + """ + return { + name: dataclasses.replace(camera, renderer_cfg=dataclasses.replace(camera.renderer_cfg, use_cuda_graph=False)) + for name, camera in scene_cfg.__dict__.items() + if isinstance(camera, CameraCfg) and isinstance(camera.renderer_cfg, NewtonWarpRendererCfg) + } + + +_OPTIONAL_STEPS = (Step.RENDER, ResetStep.RENDER) # Built-in work that a step may leave out + + def _check_step(cfg: MDP2EnvCfg) -> None: - """Raise if the config's step or reset step leaves out, repeats, or reorders its built-in work.""" + """Raise if the config's step or reset step leaves out, repeats, or reorders its built-in work. Rendering may be + left out.""" orders = ( ( "step", @@ -327,10 +411,13 @@ def _check_step(cfg: MDP2EnvCfg) -> None: ) for name, items, order, reason in orders: builtin = [item for item in items if not isinstance(item, Stage)] - if builtin != order: + required = [item for item in order if item not in _OPTIONAL_STEPS] + if builtin != [item for item in order if item in builtin] or not set(required) <= set(builtin): + optional = [str(item) for item in order if item in _OPTIONAL_STEPS] raise ValueError( f"MDP2EnvCfg.{name} must hold {', '.join(map(str, order))} once each, in this order, with stages" - f" anywhere between them, got {[str(item) for item in builtin]}: {reason}." + f" anywhere between them and {', '.join(optional)} optional, got {[str(item) for item in builtin]}:" + f" {reason}." ) @@ -355,17 +442,24 @@ def __init__(self, cfg: MDP2RLEnvCfg, render_mode: str | None = None, **kwargs: self.final_observations = cfg.compute_final_obs super().__init__(cfg) if cfg.compute_final_obs: - self.extras["final_obs"] = { - group: values.torch for group, values in self.transition.final_observations.items() - } + self.extras["final_obs"] = self._views(self.transition.final_observations) self.render_mode = render_mode self.metadata = {**self.metadata, "render_fps": 1 / self.step_dt} + spaces: dict[str, Any] = {} + for buffer, (shape, dtype) in self.mdp.observation_layouts.items(): + if dtype is wp.float32: + space = gym.spaces.Box(low=-np.inf, high=np.inf, shape=shape) + else: + info = np.iinfo(wp.dtype_to_numpy(dtype)) + space = gym.spaces.Box(low=info.min, high=info.max, shape=shape, dtype=wp.dtype_to_numpy(dtype)) + if "/" in buffer: + group, term = buffer.split("/") + spaces.setdefault(group, {})[term] = space + else: + spaces[buffer] = space self.single_observation_space = gym.spaces.Dict( - { - group: gym.spaces.Box(low=-np.inf, high=np.inf, shape=(dim,)) - for group, dim in self.mdp.observation_dims.items() - } + {group: gym.spaces.Dict(space) if isinstance(space, dict) else space for group, space in spaces.items()} ) self.single_action_space = gym.spaces.Box(low=-np.inf, high=np.inf, shape=(self.mdp.action_dim,)) self.observation_space = gym.vector.utils.batch_space(self.single_observation_space, self.num_envs) @@ -395,13 +489,23 @@ def __init__(self, cfg: MDP2RLEnvCfg, render_mode: str | None = None, **kwargs: if op.log } # The time limit is not an op: whether it ended the last episode of each world is kept apart, under its name. - tasks = [cfg.task] if isinstance(cfg.task, mdp2.TaskCfg) else cfg.task - time_limits = [ - name for task in tasks for name, term in task.terminations.items() if isinstance(term, mdp2.TimeLimit) - ] + time_limits = [name for name, term in _terminations(cfg.task) if isinstance(term, mdp2.TimeLimit)] self._time_limit = time_limits[0] if time_limits else None + # Progress: whether each task with a completion was done in each world's last finished episode, logged over + # the worlds of the world configs that have it. + paths = list(dict.fromkeys(path for tree in self.mdp.tasks for path in sorted(tree.completes))) + self._tasks = { + f"Progress/{path or 'task'}": self.state.arrays[mdp2.progress_field(path, "done")].torch for path in paths + } + self._task_worlds = [] + for path in paths: + worlds = [world for tree in self.mdp.tasks if path in tree.completes for world in tree.worlds] + self._task_worlds.append(slice(None) if len(worlds) == self.num_envs else worlds) + self._last_done = torch.zeros(self.num_envs, len(self._tasks), device=self.device) self._last_time_outs = torch.zeros(self.num_envs, dtype=torch.bool, device=self.device) self.obs_buf: VecEnvObs = {} + if cfg.episode_budget is not None: + self._init_episode_budget(cfg.episode_budget) @property def max_episode_length(self) -> int | float: @@ -430,16 +534,18 @@ def reset(self, seed: int | None = None, options: dict[str, Any] | None = None) """Reset every world and return copies of their observations.""" super().reset(seed, options) self._episode_rewards.zero_() + if self.cfg.episode_budget is not None: + self._restart_episode_budget() # Learners keep the observations across the next step, which overwrites the buffers. - self.obs_buf = {group: values.clone() for group, values in self.observations.items()} + self.obs_buf = _clone(self.observations) return self.obs_buf, self.extras def step(self, action: torch.Tensor) -> VecEnvStepReturn: """Apply the actions, step the physics, evaluate the MDP, reset the worlds that ended, and observe.""" self._step_or_replay(action) self._log_episodes() - self.obs_buf = {group: values.clone() for group, values in self.observations.items()} + self.obs_buf = _clone(self.observations) transition = self.transition return ( @@ -450,11 +556,101 @@ def step(self, action: torch.Tensor) -> VecEnvStepReturn: self.extras, ) + @property + def episodes_completed(self) -> int: + """Episodes that ended since the last :meth:`reset`, with an episode budget. Waits for the device.""" + return int(self._completed.item()) + + def episode_records(self) -> dict[str, torch.Tensor]: + """Return a row per completed episode, with an episode budget, as columns by name, in the order they ended. + + The columns are ``world``, ``episode`` (its index among the world's episodes), ``length`` (control steps), + ``terminated`` and ``truncated``, the value at the end of each recorded quantity, whether each termination + ended it, as ``termination/``, and, for each task with a completion, the episode step at which it was + done (-1 if it was not) as ``progress/`` and the task's score as ``progress/score``. Rows of episodes that + ended in the same step are ordered by world. Waits for the device. + """ + rows = self._records[: self.episodes_completed] + return {name: rows[:, k] for k, name in enumerate(self._record_columns)} + + def _init_episode_budget(self, budget: int) -> None: + """Allocate the episode counters and the record buffer. The buffer has a spare last row, which the worlds + that did not end write in the captured step.""" + device = self.device + self._budget = budget + self._started = torch.zeros((), dtype=torch.long, device=device) + self._completed = torch.zeros((), dtype=torch.long, device=device) + self._active = torch.zeros(self.num_envs, dtype=torch.bool, device=device) + self._ended = torch.zeros(self.num_envs, dtype=torch.bool, device=device) # Episodes that ended this step + self._episode_index = torch.zeros(self.num_envs, device=device) + recorded = [op for op in self.mdp.ops[mdp2.Phase.QUANTITIES] if op.record] + self._recorded = [self.state.arrays[op.writes[0]].torch for op in recorded] + self._num_quantities = len(recorded) + self._record_columns = ["world", "episode", "length", "terminated", "truncated"] + self._record_columns += [op.name.split(".", 1)[1] for op in recorded] + self._record_columns += [f"termination/{name}" for name in self._termination_names] + completes = list(dict.fromkeys(path for tree in self.mdp.tasks for path in sorted(tree.completes))) + self._recorded += [self.state.arrays[mdp2.progress_field(path, "done_at")].torch for path in completes] + self._record_columns += [f"progress/{path or 'task'}" for path in completes] + if completes: + self._recorded.append(self.state.arrays[mdp2.progress_field("", "score")].torch) + self._record_columns.append("progress/score") + self._records = torch.zeros(budget + 1, len(self._record_columns), device=device) + self._worlds = torch.arange(self.num_envs, device=device) + + def _restart_episode_budget(self) -> None: + """Start the first episodes of the budget, in the first worlds.""" + self._started.fill_(min(self._budget, self.num_envs)) + self._completed.zero_() + self._episode_index.zero_() + torch.lt(self._worlds, self._budget, out=self._active) + + def _spend_episode_budget(self) -> None: + """Record the episodes of active worlds that ended, and restart only as many as the budget has left. + + Worlds that do not restart become inactive: they keep stepping, but their episodes no longer end or reset. + Part of the captured step, so it works on device tensors only. + """ + transition, ended = self.transition, self._ended + torch.logical_and(transition.done.torch, self._active, out=ended) + rank = torch.cumsum(ended, dim=0) # 1 for the first world that ended, and so on + + # Rows of the ended episodes, in world order after those of earlier steps; the others write the spare row. + rows = torch.where(ended, self._completed + rank - 1, self._budget) + values = [ + self._worlds.float(), + self._episode_index, + self.state.episode_length.torch.float(), + transition.terminated.torch.float(), + transition.truncated.torch.float(), + *self._recorded[: self._num_quantities], + *transition.termination_terms.torch.float().unbind(1), + *(values.float() for values in self._recorded[self._num_quantities :]), + ] + self._records.index_copy_(0, rows, torch.stack(values, dim=1)) + self._completed.add_(rank[-1]) + self._episode_index.add_(ended.float()) + + restarted = ended & (self._started + rank <= self._budget) + self._started.add_(restarted.sum()) + self._active.logical_and_(~ended | restarted) + # Only the worlds that restart are reset; the others report their episode once. + reported = ended | self._active + transition.terminated.torch.logical_and_(reported) + transition.truncated.torch.logical_and_(reported) + transition.done.torch.copy_(restarted) + def _after_evaluate(self) -> None: """Keep the logged quantities of the worlds that ended, and whether they timed out, before their reset.""" - done = self.transition.done.torch + # With an episode budget, only the episodes of active worlds count, and only some of them restart. + if self.cfg.episode_budget is not None: + self._spend_episode_budget() + done = self._ended if self.cfg.episode_budget is not None else self.transition.done.torch for value, last, _ in self._metrics.values(): torch.where(done, value, last, out=last) + if self._tasks: + done_tasks = torch.stack(list(self._tasks.values()), 1).float() + torch.where(done[:, None], done_tasks, self._last_done, out=self._last_done) if self._time_limit is not None: timed_out = self.state.episode_length.torch >= self.max_episode_length torch.where(done, timed_out, self._last_time_outs, out=self._last_time_outs) @@ -462,7 +658,7 @@ def _after_evaluate(self) -> None: def _log_episodes(self) -> None: """Add the step's term rewards to the episode sums, and record the episodes that ended in ``extras["log"]``.""" transition = self.transition - ended = transition.done.torch[:, None] + ended = (self._ended if self.cfg.episode_budget is not None else transition.done.torch)[:, None] self._episode_rewards += transition.reward_terms.torch torch.where(ended, self._episode_rewards, self._last_episode_rewards, out=self._last_episode_rewards) @@ -480,4 +676,21 @@ def _log_episodes(self) -> None: # A quantity that only some worlds compute is averaged over them. for name, (_, last, worlds) in self._metrics.items(): log[f"Metrics/{name}"] = last[worlds].mean() + # A task is averaged over the worlds of its world config. + for k, (name, worlds) in enumerate(zip(self._tasks, self._task_worlds)): + log[name] = self._last_done[worlds, k].mean() self.extras["log"] = log + + +def _terminations(task: mdp2.TaskCfg) -> list[tuple[str, Any]]: + """Return the terminations of a task and of its subtasks, by name.""" + subtasks = [_terminations(subtask) for subtask in task.subtasks.values()] + return [*task.terminations.items(), *(item for terminations in subtasks for item in terminations)] + + +def _clone(observations: VecEnvObs) -> VecEnvObs: + """Copy observations, also the term tensors of groups that are not concatenated.""" + return { + group: {term: values.clone() for term, values in value.items()} if isinstance(value, dict) else value.clone() + for group, value in observations.items() + } diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env_cfg.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env_cfg.py index fe1c2e209088..e37f042e19a7 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env_cfg.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env_cfg.py @@ -16,13 +16,15 @@ from isaaclab.sim import SimulationCfg from isaaclab.utils import configclass -from isaaclab_experimental.mdp2 import Backend, TaskCfg +from isaaclab_experimental.mdp2 import Backend, ObservationGroup, TaskCfg +from isaaclab_experimental.mdp2.config import group_terms class Step(enum.Enum): """Built-in work of a control step, in :attr:`MDP2EnvCfg.step`.""" PHYSICS = enum.auto() # Apply the actions and step the physics ``decimation`` times + RENDER = enum.auto() # Render the cameras, once per control step; nothing without cameras EVALUATE = enum.auto() # Evaluate the MDP: commands, quantities, terminations, rewards, observations RESET = enum.auto() # Reset the worlds whose episodes ended, by :attr:`MDP2EnvCfg.reset_step` @@ -32,6 +34,7 @@ class ResetStep(enum.Enum): EVENTS = enum.auto() # Reset the assets and sensors, and run the reset events, which write scene fields in place COMMIT = enum.auto() # Pass the writes of the reset events to the simulation + RENDER = enum.auto() # Render the cameras again, so that the observations see the new episodes; optional OBSERVE = enum.auto() # Observe the reset worlds @@ -57,16 +60,19 @@ class MDP2EnvCfg: sim: SimulationCfg = SimulationCfg() scene: InteractiveSceneCfg = MISSING - # Actions, commands, observations, rewards, terminations, and events; a list splits the worlds between tasks - task: TaskCfg | list[TaskCfg] = MISSING - task_worlds: list[int] | None = None # Number of worlds of each task of a list, in order; None for even shares + # Actions, commands, observations, rewards, terminations, and events, and subtasks; mdp2.split gives subtasks + # their own worlds + task: TaskCfg = MISSING decimation: int = MISSING # Physics steps per control step backend: Backend = Backend.WARP # How the task's term implementations run seed: int | None = None capture: bool = True # Replay each step, physics included, as one CUDA graph when the MDP allows it - # The work of a control step, in order: the built-in steps, each once and in this order, and stages anywhere - step: list[Step | Stage] = [Step.PHYSICS, Step.EVALUATE, Step.RESET] - # The work of resetting worlds, in a step's Step.RESET and in reset(): as for step + # The work of a control step, in order: the built-in steps, each once and in this order (Step.RENDER may be left + # out), and stages anywhere + step: list[Step | Stage] = [Step.PHYSICS, Step.RENDER, Step.EVALUATE, Step.RESET] + # The work of resetting worlds, in a step's Step.RESET and in reset(): as for step. Insert ResetStep.RENDER before + # ResetStep.OBSERVE to render the cameras again, so that the first observations of new episodes see them, at the + # cost of a second render per step; reset() always does. reset_step: list[ResetStep | Stage] = [ResetStep.EVENTS, ResetStep.COMMIT, ResetStep.OBSERVE] # Debug: before building, step the task this many times uncaptured and captured, and raise where they differ, # naming the value; see verify_capture. 0 to skip. @@ -80,23 +86,33 @@ class MDP2RLEnvCfg(MDP2EnvCfg): is_finite_horizon: bool = False # Whether time-outs are terminal states rather than truncations # Whether step returns, in extras["final_obs"], the observations of the worlds that ended before their reset compute_final_obs: bool = False + # Episodes to run from each reset, for evaluation: worlds stop starting episodes once the budget is spent, and + # each finished episode is recorded, see MDP2RLEnv.episode_records. None for no budget. + episode_budget: int | None = None log_dir: str | None = None # Set by the training scripts video_recorders: list = [] # Not supported yet; kept for the training scripts def play_mode(self) -> None: """Adjust the configuration for playing a trained policy, as MDP1 does: at most 50 worlds, and observations without noise. The play scripts call it; tasks may extend it.""" - if self.task_worlds is None: + # A split with a number of worlds per subtask needs all of them. + if not splits_by_count(self.task): self.scene.num_envs = min(self.scene.num_envs, 50) - tasks = [self.task] if isinstance(self.task, TaskCfg) else self.task - tasks = [_without_observation_noise(task) for task in tasks] - self.task = tasks[0] if isinstance(self.task, TaskCfg) else tasks + self.task = _without_observation_noise(self.task) + + +def splits_by_count(task: TaskCfg) -> bool: + """Return whether a task or one of its subtasks splits the worlds by counts.""" + return task.worlds is not None or any(splits_by_count(subtask) for subtask in task.subtasks.values()) def _without_observation_noise(task: TaskCfg) -> TaskCfg: - """Return a copy of a task whose observations have no noise; the uses it shares with others are not changed.""" - observations = { - group: {name: use if use is None else replace(use, noise=None) for name, use in uses.items()} - for group, uses in task.observations.items() - } - return replace(task, observations=observations) + """Return a copy of a task and its subtasks whose observations have no noise; the uses it shares with others are + not changed.""" + observations = {} + for group, uses in task.observations.items(): + terms, concatenate = group_terms(uses) + terms = {name: use if use is None else replace(use, noise=None) for name, use in terms.items()} + observations[group] = ObservationGroup(terms=terms, concatenate=concatenate) + subtasks = {name: _without_observation_noise(subtask) for name, subtask in task.subtasks.items()} + return replace(task, observations=observations, subtasks=subtasks) diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_scene_data.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_scene_data.py index 87385e27c301..126ee32f0434 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_scene_data.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_scene_data.py @@ -15,7 +15,7 @@ from isaaclab.actuators import DCMotorCfg, IdealPDActuatorCfg, ImplicitActuatorCfg from isaaclab.scene import InteractiveScene -from isaaclab.sensors import BaseContactSensor +from isaaclab.sensors import BaseContactSensor, Camera from isaaclab.sim import SimulationContext from isaaclab.utils.warp import ProxyArray @@ -50,6 +50,10 @@ class InteractiveSceneData: Sensors with filter objects also provide ``normal_force_matrix_w`` (``wp.vec3f``) [N] per world, body, and filter. + Cameras provide each of their data types, such as ``rgb`` (``uint8``) or ``depth`` [m], per world, pixel row, + pixel column, and channel, with the dimensions ``height``, ``width``, and ``_channels``. The + environment renders them once per control step, after the physics. Their fields are read-only. + Events and actions write fields in place, and :meth:`commit` makes the simulation see the writes to the joint and root state. Where the asset's data is the solver's own state, as Newton's joint positions and root state usually are, a commit only tells the solver which worlds changed. Otherwise, as for the joint positions of Newton @@ -215,6 +219,28 @@ def __init__(self, scene: InteractiveScene, sim: SimulationContext, step_dt: flo ) self._views[name] = views + # Cameras. + for name, sensor in scene.sensors.items(): + if not isinstance(sensor, Camera): + continue + if sensor.cfg.update_period > 0.0: + raise ValueError( + f"MDP2 renders cameras once per control step, so camera '{name}' must have an update_period of 0." + ) + # Data types have their own number of channels, such as rgb_channels. + views = dict(sensor.data.output) + _, height, width, _ = next(iter(views.values())).shape + names = {"height": tuple(map(str, range(height))), "width": tuple(map(str, range(width)))} + names |= {f"{field}_channels": tuple(map(str, range(view.shape[3]))) for field, view in views.items()} + entities[name] = EntitySchema( + names=names, + fields={ + field: FieldSchema(("height", "width", f"{field}_channels"), view.warp.dtype) + for field, view in views.items() + }, + ) + self._views[name] = views + # Scene-wide fields. self._views["scene"] = { "env_origins": ProxyArray(wp.from_torch(scene.env_origins.contiguous(), dtype=wp.vec3f)) diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_verify.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_verify.py index ab94945c09b3..20f59aee077c 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_verify.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_verify.py @@ -22,7 +22,7 @@ from isaaclab_experimental import mdp2 -from .mdp2_env_cfg import MDP2EnvCfg, Stage +from .mdp2_env_cfg import MDP2EnvCfg, Stage, splits_by_count if TYPE_CHECKING: from .mdp2_env import MDP2Env @@ -31,7 +31,7 @@ def verify_capture(env_type: type[MDP2Env], cfg: MDP2EnvCfg, num_steps: int) -> None: """Step a task ``num_steps`` times uncaptured, then captured, and raise where a step differs. - Both runs use a copy of the config with at most 8 worlds (unless it splits them between tasks), the same seed, and + Both runs use a copy of the config with at most 8 worlds (unless it splits them by counts), the same seed, and seeded random actions in ``[-1, 1]``. Steps are compared on the rewards, the terminated and truncated flags, the observations, and every quantity and term state, which are named in the error in schedule order, with the Python hooks and stages that run inside the graphs, where the cause usually is. The worlds start at staggered episode @@ -43,7 +43,7 @@ def verify_capture(env_type: type[MDP2Env], cfg: MDP2EnvCfg, num_steps: int) -> # One seed for both runs, also when the config asks for a random one. seed = 0 if cfg.seed in (None, -1) else cfg.seed cfg = dataclasses.replace(cfg, capture=False, verify_capture=0, seed=seed) - if cfg.task_worlds is None: + if not splits_by_count(cfg.task): # A shallow copy keeps the entities that were added to the scene config as attributes. cfg.scene = copy.copy(cfg.scene) cfg.scene.num_envs = min(cfg.scene.num_envs, 8) @@ -92,6 +92,9 @@ def _rollout(env_type: type[MDP2Env], cfg: MDP2EnvCfg, num_steps: int) -> tuple[ for name in op.state: selector = mdp2.term_state(op.use, name) named[str(selector)] = env.state.arrays[selector].torch + for key, values in env.state.arrays.items(): + if isinstance(key, mdp2.FieldSelector) and key.entity == "progress": + named[str(key)] = values.torch steps = [] for _ in range(num_steps): actions = 2.0 * torch.rand(env.num_envs, env.mdp.action_dim, device=env.device, generator=generator) - 1.0 diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/__init__.pyi b/source/isaaclab_experimental/isaaclab_experimental/mdp2/__init__.pyi index fddd9850f994..d5fc35d0899d 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/__init__.pyi +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/__init__.pyi @@ -5,6 +5,7 @@ __all__ = [ "MDP", + "Action", "CapturedMDP", "Backend", "Command", @@ -19,7 +20,11 @@ __all__ = [ "Implementation", "MDPBuilder", "MDPState", + "Milestone", "Observation", + "ObservationColumns", + "ObservationGroup", + "ObservationSlot", "Phase", "Quantity", "ExecutionPlan", @@ -33,6 +38,10 @@ __all__ = [ "StepKind", "SubsetSelector", "TaskCfg", + "TaskMode", + "TaskNode", + "TaskSelector", + "TaskTree", "Term", "TermCfg", "TermContext", @@ -43,12 +52,17 @@ __all__ = [ "WorldConfig", "apply_actions", "commands", + "compose", "episode_length", "evaluate", "last_action", "observe", + "progress", + "progress_field", "quantities", "reset", + "sequence", + "split", "startup", "step_dt", "term_state", @@ -60,8 +74,9 @@ __all__ = [ from . import mdp from .builder import MDPBuilder, ScheduleEntry from .capture import CapturedMDP -from .compiled import MDP, Backend, MDPState, Transition, WorldConfig +from .compiled import MDP, Backend, MDPState, ObservationColumns, Transition, WorldConfig from .config import ( + Action, Command, Constant, DirectAction, @@ -69,26 +84,35 @@ from .config import ( Event, EventMode, FieldSelector, + Milestone, Observation, + ObservationGroup, Phase, Quantity, Reward, SubsetSelector, TaskCfg, + TaskMode, + TaskSelector, TermCfg, Termination, TimeLimit, UniformNoise, commands, + compose, episode_length, last_action, + progress, + progress_field, quantities, + sequence, + split, step_dt, term_state, terminated, ) from .eager import TermContext -from .plan import ExecutionPlan, Segment, Step, StepKind +from .plan import ExecutionPlan, ObservationSlot, Segment, Step, StepKind, TaskNode, TaskTree from .rng import uniform from .runtime import apply_actions, evaluate, observe, reset, startup from .scene import EntitySchema, FieldSchema, SceneData, SceneSchema diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py index f94a20c02d59..a782bc0aaa08 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py @@ -23,6 +23,7 @@ from . import torch_backend, warp_backend from .compiled import MDP, Backend, WorldConfig from .config import ( + Action, Command, DirectAction, Entity, @@ -35,18 +36,21 @@ Reward, SubsetSelector, TaskCfg, + TaskMode, TermCfg, Termination, TimeLimit, commands, episode_length, + group_terms, last_action, + progress_field, quantities, step_dt, term_state, terminated, ) -from .plan import ActionOp, ObservationOutput, Segment, TermOp, build_plan +from .plan import ActionOp, ObservationOutput, ObservationSlot, Segment, TaskNode, TaskTree, TermOp, build_plan from .scene import SceneSchema from .terms import Implementation, hook_arguments @@ -56,7 +60,18 @@ class ScheduleEntry: """Handle to one term use in the schedule, returned by the ``add_*`` methods.""" path: tuple[str, ...] # Location in the task, e.g. ("observations", "policy", "joint_pos") - cfg: DirectAction | Command | Quantity | Observation | Reward | Termination | TimeLimit | Event + cfg: DirectAction | Action | Command | Quantity | Observation | Reward | Termination | TimeLimit | Event + concatenate: bool = True # Observations: whether the use writes its group's buffer rather than its own + name: str = "" # Name in its task, without the prefix of a subtask; the last part of the path if empty + stage: str | None = None # The task of a sequence that the use belongs to, see TermOp.stage + + @property + def buffer(self) -> str: + """Observations: the buffer the use writes, its group or, in a group that is not concatenated, "group/name". + + Uses of different tasks with the same name share their columns, see :meth:`MDPBuilder.finalize`. + """ + return self.path[1] if self.concatenate else f"{self.path[1]}/{self.name or self.path[-1]}" def __str__(self) -> str: return ".".join(self.path) @@ -84,7 +99,7 @@ def writes(self) -> tuple[FieldSelector, ...]: return (FieldSelector(commands.name, self.path[1], scene=False),) if isinstance(self.cfg, Quantity): return (FieldSelector(quantities.name, self.path[1], scene=False),) - if isinstance(self.cfg, Event): + if isinstance(self.cfg, (Event, Action)): return tuple(self.cfg.outputs.values()) return () @@ -122,8 +137,8 @@ class CompileContext: } ) subsets: dict[SubsetSelector, tuple[int, ...]] = field(default_factory=dict) - observation_dims: dict[str, int] = field(default_factory=dict) action_dim: int = 0 + tasks: tuple[TaskNode, ...] = () # The task tree, parents first, if the MDP tracks progress class MDPBuilder: @@ -138,7 +153,10 @@ class MDPBuilder: def __init__(self, schema: SceneSchema) -> None: self.schema = schema self._entries: dict[tuple[str, ...], ScheduleEntry] = {} - self._world_configs: list[tuple[tuple[ScheduleEntry, ...], range]] = [] # Schedules of replicated builders + # The tasks added with add_task by dotted path, "" for the root, and whether each is part of a sequence + self._tasks: dict[str, tuple[TaskCfg, bool]] = {} + # Schedules and tasks of replicated builders, and their worlds + self._world_configs: list[tuple[tuple[ScheduleEntry, ...], dict[str, tuple[TaskCfg, bool]], range]] = [] def replicate(self, builder: MDPBuilder, num_worlds: int) -> None: """Run the task of another builder in the next ``num_worlds`` worlds. @@ -149,35 +167,93 @@ def replicate(self, builder: MDPBuilder, num_worlds: int) -> None: if builder.schema != self.schema: raise ValueError("A replicated builder must be built against the same scene schema.") - start = self._world_configs[-1][1].stop if self._world_configs else 0 - self._world_configs.append((builder.schedule(), range(start, start + num_worlds))) + start = self._world_configs[-1][2].stop if self._world_configs else 0 + self._world_configs.append((builder.schedule(), dict(builder._tasks), range(start, start + num_worlds))) def add_task(self, task: TaskCfg) -> None: - """Add all term uses of a task in declaration order, skipping uses set to ``None``.""" - for name, action in task.actions.items(): - if action is not None: - self.add_action(name, action) - for name, command in task.commands.items(): - if command is not None: - self.add_command(name, command) - for name, quantity in task.quantities.items(): - if quantity is not None: - self.add_quantity(name, quantity) + """Add the term uses of a task and of its subtasks in declaration order, skipping uses set to ``None``. + + The uses of a subtask get its dotted path as a prefix, as in ``rewards.grasp.lift``. A task that splits the + worlds between subtasks replicates a builder with the rest of the task for each of them. + """ + configs = _expand(task, self.schema.num_worlds) + if len(configs) == 1: + self._add_task(configs[0][0], (), (), False, {}) + return + for config, num_worlds in configs: + builder = MDPBuilder(self.schema) + builder._add_task(config, (), (), False, {}) + self.replicate(builder, num_worlds) + + def _add_task( + self, + task: TaskCfg, + path: tuple[str, ...], + names: tuple[str, ...], + staged: bool, + scope: dict[FieldSelector, FieldSelector], + ) -> None: + """Add a task of one world config, its uses with the prefix ``names``, then its subtasks. + + The subtask of a split runs in worlds of its own, so its uses keep their names: equal uses of the world configs + then run once, see :meth:`replicate`. A task reads its own commands and quantities by their names, as a task + that runs alone does: ``scope`` maps the names that the task and its parents define to their fields. + """ + task_path = ".".join(path) + if task_path in self._tasks: + raise ValueError(f"The builder already has a task '{task_path}'.") + if task.done is not None and task.subtasks: + raise ValueError(f"Task '{task_path}': a task with subtasks is done when they are; it cannot have a done.") + prefix = ".".join(names) + stage = task_path if staged else None + scope = { + **scope, + **{ + FieldSelector(entity.name, name, scene=False): FieldSelector( + entity.name, f"{prefix}.{name}" if prefix else name, scene=False + ) + for entity, uses in ((commands, task.commands), (quantities, task.quantities)) + for name in uses + }, + } + self._tasks[task_path] = (replace(task, done=scope.get(task.done, task.done)), staged) + + def add(kind: str, name: str, cfg: object, group: str | None = None, concatenate: bool = True) -> None: + # A time limit ends episodes; a task of a sequence can end itself with a termination on its started_at. + if isinstance(cfg, TimeLimit) and staged: + raise ValueError(f"Task '{task_path}': the tasks of a sequence cannot have a time limit.") + if isinstance(cfg, (DirectAction, Action)) and staged: + raise ValueError(f"Task '{task_path}': the tasks of a sequence cannot have actions yet.") + # Reset and startup events set up whole episodes, so they run in every world of their task. + setup = isinstance(cfg, Event) and cfg.mode is not EventMode.INTERVAL + full = f"{prefix}.{name}" if prefix else name + entry_path = (kind, full) if group is None else (kind, group, full) + self._add(ScheduleEntry(entry_path, _scoped(cfg, scope), concatenate, name, None if setup else stage)) + + for kind in ("actions", "commands", "quantities"): + for name, use in getattr(task, kind).items(): + if use is not None: + add(kind, name, use) for group, observations in task.observations.items(): - for name, observation in observations.items(): + if "/" in group: + raise ValueError(f"Observation group names cannot contain '/': '{group}'.") + terms, concatenate = group_terms(observations) + uses = [entry for entry in self._entries.values() if entry.path[:2] == ("observations", group)] + if uses and uses[0].concatenate != concatenate: + raise ValueError(f"The observations of group '{group}' must all be concatenated or all be separate.") + for name, observation in terms.items(): if observation is not None: - self.add_observation(group, name, observation) - for name, reward in task.rewards.items(): - if reward is not None: - self.add_reward(name, reward) - for name, termination in task.terminations.items(): - if termination is not None: - self.add_termination(name, termination) - for name, event in task.events.items(): - if event is not None: - self.add_event(name, event) - - def add_action(self, name: str, action: DirectAction) -> ScheduleEntry: + add("observations", name, observation, group, concatenate) + for kind in ("rewards", "terminations", "events"): + for name, use in getattr(task, kind).items(): + if use is not None: + add(kind, name, use) + + for name, subtask in task.subtasks.items(): + subtask_names = names if task.mode is TaskMode.SPLIT else (*names, name) + self._add_task(subtask, (*path, name), subtask_names, staged or task.mode is TaskMode.SEQUENCE, scope) + + def add_action(self, name: str, action: DirectAction | Action) -> ScheduleEntry: return self._add(ScheduleEntry(("actions", name), action)) def add_command(self, name: str, command: Command) -> ScheduleEntry: @@ -189,8 +265,16 @@ def add_quantity(self, name: str, quantity: Quantity) -> ScheduleEntry: def add_event(self, name: str, event: Event) -> ScheduleEntry: return self._add(ScheduleEntry(("events", name), event)) - def add_observation(self, group: str, name: str, observation: Observation) -> ScheduleEntry: - return self._add(ScheduleEntry(("observations", group, name), observation)) + def add_observation( + self, group: str, name: str, observation: Observation, concatenate: bool = True + ) -> ScheduleEntry: + """Add an observation to a group, concatenated with the group's other terms or in a buffer of its own.""" + if "/" in group or "/" in name: + raise ValueError(f"Observation group and term names cannot contain '/': '{group}', '{name}'.") + uses = [entry for entry in self._entries.values() if entry.path[:2] == ("observations", group)] + if uses and uses[0].concatenate != concatenate: + raise ValueError(f"The observations of group '{group}' must all be concatenated or all be in own buffers.") + return self._add(ScheduleEntry(("observations", group, name), observation, concatenate)) def add_reward(self, name: str, reward: Reward) -> ScheduleEntry: return self._add(ScheduleEntry(("rewards", name), reward)) @@ -303,18 +387,24 @@ def _compile( self, device: str, backend: Backend, diagnostics: bool = False, final_observations: bool = False ) -> MDP: """Compile the schedule of each world config, then merge their ops, sharing the ones they have in common.""" - configs = self._world_configs or [(self.schedule(), range(self.schema.num_worlds))] - world_ranges = [worlds for _, worlds in configs] + configs = self._world_configs or [(self.schedule(), self._tasks, range(self.schema.num_worlds))] + world_ranges = [worlds for _, _, worlds in configs] errors = [] if self._world_configs and self._entries: errors.append("Add term uses to the replicated builders, not to the builder that replicates them.") if world_ranges[-1].stop != self.schema.num_worlds: errors.append(f"The world configs cover {world_ranges[-1].stop} of {self.schema.num_worlds} worlds.") + # Progress is tracked if any task has a completion or a sequence. + tracked = any( + task.done is not None or task.mode is TaskMode.SEQUENCE + for _, tasks, _ in configs + for task, _ in tasks.values() + ) contexts, time_limits = [], set() - for index, (schedule, worlds) in enumerate(configs): - context, time_limit = self._compile_schedule(schedule, backend) + for index, (schedule, tasks, worlds) in enumerate(configs): + context, time_limit = self._compile_schedule(schedule, tasks if tracked else {}, backend) prefix = f"world config {index} ({worlds.start}-{worlds.stop - 1}): " if len(configs) > 1 else "" errors += [prefix + error for error in context.errors] contexts.append(context) @@ -338,8 +428,8 @@ def _compile( errors.append(f"The world configs give '{op.writes[0]}' different shapes.") # The ops of one use share its state, each in its own worlds. for phase, ops in context.ops.items(): - for op in ops if phase is not Phase.ACTIONS else (): - for name, spec in op.state.items(): + for op in ops: + for name, spec in op.state.items() if isinstance(op, TermOp) else (): selector = term_state(op.use, name) if field_shapes.setdefault(selector, spec.shape) != spec.shape: errors.append(f"The world configs give '{selector}' different shapes.") @@ -347,6 +437,15 @@ def _compile( raise ValueError("Invalid MDP:\n " + "\n ".join(errors)) ops = _merge_ops([(context.ops, worlds) for context, worlds in zip(contexts, world_ranges)], self.schema) + trees = tuple( + TaskTree(worlds, context.tasks, frozenset(_completes(context.tasks))) + for context, worlds in zip(contexts, world_ranges) + if tracked + ) + modes = {node.path: node.mode for tree in trees for node in tree.nodes} + ops[Phase.OBSERVATIONS], slots, observation_dims, layouts = _allocate_slots( + ops[Phase.OBSERVATIONS], modes, errors + ) # Random streams are keyed by use name, so that every world draws what it would in its config alone. streams: dict[str, int] = {} @@ -371,10 +470,14 @@ def _compile( ) ops = MappingProxyType(ops) - groups = dict.fromkeys(group for context in contexts for group in context.observation_dims) - observation_dims = { - group: max(context.observation_dims.get(group, 0) for context in contexts) for group in groups + observation_layouts = { + buffer: layouts.get(buffer, ((dim,), wp.float32)) for buffer, dim in observation_dims.items() } + mixed = {buffer.split("/")[0] for buffer in observation_layouts if "/" in buffer} & set(observation_dims) + if mixed: + errors.append(f"The world configs disagree on whether the groups {sorted(mixed)} are concatenated.") + if errors: + raise ValueError("Invalid MDP:\n " + "\n ".join(errors)) subsets = {selector: ids for context in contexts for selector, ids in context.subsets.items()} time_limit = time_limits.pop() return MDP( @@ -382,25 +485,38 @@ def _compile( device=device, backend=backend, ops=ops, - plan=build_plan(ops, self.schema), + plan=build_plan(ops, self.schema, trees, slots), action_dim=action_dim, observation_dims=MappingProxyType(observation_dims), + observation_layouts=MappingProxyType(observation_layouts), max_episode_length=None if time_limit is None else math.ceil(time_limit / self.schema.step_dt), streams=tuple(streams), subsets=MappingProxyType(subsets), diagnostics=diagnostics, final_observations=final_observations, world_configs=tuple( - WorldConfig(worlds, context.action_dim, MappingProxyType(context.observation_dims)) + WorldConfig( + worlds, context.action_dim, MappingProxyType(_used_columns(ops[Phase.OBSERVATIONS], worlds)) + ) for context, worlds in zip(contexts, world_ranges) ), + tasks=trees, + slots=slots, ) def _compile_schedule( - self, schedule: tuple[ScheduleEntry, ...], backend: Backend + self, schedule: tuple[ScheduleEntry, ...], tasks: dict[str, tuple[TaskCfg, bool]], backend: Backend ) -> tuple[CompileContext, float | None]: - """Compile the ops of one world config, and return them with its episode length in seconds.""" + """Compile the ops of one world config, and its task tree if it has one, and return them with its episode + length in seconds.""" context = CompileContext(backend, _dependency_errors(schedule)) + # Terms may read the progress of every task. + for path, (task, _) in tasks.items(): + for name in ("done", "holding", "active"): + context.mdp_fields[progress_field(path, name)] = ArrayLayout(wp.bool, 1, {}) + for name in ("done_at", "started_at", *(["stage"] if task.mode is TaskMode.SEQUENCE else [])): + context.mdp_fields[progress_field(path, name)] = ArrayLayout(wp.int32, 1, {}) + context.mdp_fields[progress_field(path, "score")] = ArrayLayout(wp.float32, 1, {}) # The time limit compiles to no op, so it is known even when the other uses cannot be ordered. time_limits = [entry for entry in schedule if isinstance(entry.cfg, TimeLimit)] if len(time_limits) > 1: @@ -436,30 +552,57 @@ def _compile_schedule( # An offset may be a field of the MDP, such as a quantity, which exists once its use is compiled. for op in context.ops[Phase.ACTIONS]: - if not isinstance(op.offset, FieldSelector): + if not isinstance(op, ActionOp) or not isinstance(op.offset, FieldSelector): continue offset = self._resolve(op.name, "offset", op.offset, context) if offset is not None and offset.shape != self._resolve(op.name, "target", op.target, context).shape: context.errors.append(f"{op.name}: the offset '{op.offset}' must have the shape of '{op.target}'.") - # Restore the schedule order within each phase, with the positions and observation columns it gives. + # Restore the schedule order within each phase, with the positions it gives. Observation columns are given + # after the world configs merge, by name, see _allocate_slots. position = {str(entry): k for k, entry in enumerate(schedule)} for phase, ops in context.ops.items(): if phase is Phase.ACTIONS: continue ops.sort(key=lambda op: position[op.name]) - starts = dict.fromkeys(context.observation_dims, 0) for k, op in enumerate(ops): - observation = op.observation - if observation is not None: - start = starts[observation.group] - stop = start + observation.columns.stop - observation.columns.start - starts[observation.group] = stop - observation = replace(observation, columns=slice(start, stop)) - ops[k] = replace(op, index=k, observation=observation) + ops[k] = replace(op, index=k) + context.tasks = tuple(self._compile_task(path, tasks, context) for path in tasks) return context, time_limit + def _compile_task(self, path: str, tasks: dict[str, tuple[TaskCfg, bool]], context: CompileContext) -> TaskNode: + """Compile a task of the tree, or record why its progress cannot be tracked.""" + task, staged = tasks[path] + name, errors = f"Task '{path}'" if path else "The task", context.errors + children = tuple(f"{path}.{child}" if path else child for child in task.subtasks) + done_dtype = None + if task.done is not None: + layout = self._resolve(name, "done", task.done, context) + if layout is not None and (layout.ndim != 1 or layout.dtype not in (wp.bool, wp.float32, wp.int32)): + errors.append(f"{name}: done '{task.done}' must be a field of one bool, float, or int per world.") + done_dtype = None if layout is None else layout.dtype + if task.hold < 1: + errors.append(f"{name}: hold must be at least 1, got {task.hold}.") + completes = [child for child, subtask in task.subtasks.items() if _has_completion(subtask)] + if task.mode is TaskMode.SEQUENCE and len(completes) != len(children): + missing = sorted(set(task.subtasks) - set(completes)) + errors.append(f"{name}: every task of a sequence needs a completion, {missing} have none.") + if task.require is not None and not 1 <= task.require <= len(completes): + errors.append(f"{name}: require must be between 1 and {len(completes)}, the subtasks with a completion.") + return TaskNode( + path=path, + mode=task.mode, + children=children, + done=task.done, + done_dtype=done_dtype, + hold=task.hold, + score=task.score, + final=task.final, + require=task.require, + staged=staged, + ) + def _compile_action(self, entry: ScheduleEntry, context: CompileContext) -> None: """Compile an action use into an op, or record why it cannot be compiled.""" cfg = entry.cfg @@ -479,7 +622,10 @@ def _compile_action(self, entry: ScheduleEntry, context: CompileContext) -> None if self._resolve(entry, "subset", cfg.subset, context) is None: return elements = set(context.subsets[cfg.subset]) + # Action terms may write other elements of the same field, such as other joints, after or before it. for op in context.ops[Phase.ACTIONS]: + if isinstance(op, TermOp): + continue written = set(context.subsets[op.subset]) if op.subset is not None else elements if op.target == cfg.target and (op.subset is None or elements & written): context.errors.append(f"{entry}: '{cfg.target}' is already written by '{op.name}'.") @@ -500,10 +646,13 @@ def _compile_term(self, entry: ScheduleEntry, context: CompileContext) -> None: # Check the use, and resolve the shapes of its output and state. implementation = _implementation(entry, context.backend, errors) - outputs = cfg.outputs if isinstance(cfg, Event) else {} + outputs = cfg.outputs if isinstance(cfg, (Event, Action)) else {} # A command writes its own field, which every hook gets as ``command``. command = {"command": entry.writes[0]} if isinstance(cfg, Command) else {} - names = [*cfg.inputs, *outputs, *command, *term.state, *cfg.params, *(["rng"] if term.random else [])] + # An action gets its columns of the action as ``action``. + action = ["action"] if isinstance(cfg, Action) else [] + names = [*cfg.inputs, *outputs, *command, *action, *term.state, *cfg.params] + names += ["rng"] if term.random else [] if len(set(names)) != len(names): errors.append(f"{entry}: inputs, outputs, state, params, and rng must have distinct names, got {names}.") @@ -530,6 +679,10 @@ def _compile_term(self, entry: ScheduleEntry, context: CompileContext) -> None: output_shape = _resolve_shape(entry, "output", term.shape, sizes, errors) if output_shape and isinstance(cfg, (Reward, Termination)): errors.append(f"{entry}: {type(cfg).__name__} outputs must have shape ('worlds',), got {output_shape}.") + if isinstance(cfg, Action): + _check_action(entry, output_shape, errors) + dtype = wp.bool if isinstance(cfg, Termination) else term.dtype or wp.float32 + _check_output_type(entry, dtype, errors) # State without the world dimension is one buffer for every world. shared = {name for name, spec in term.state.items() if "worlds" not in spec.shape} state_shapes = {} @@ -540,8 +693,8 @@ def _compile_term(self, entry: ScheduleEntry, context: CompileContext) -> None: state_shapes[name] = dims if name in shared else (self.schema.num_worlds, *dims) if isinstance(cfg, Event) and (cfg.mode is EventMode.INTERVAL) != (cfg.interval_range_s is not None): errors.append(f"{entry}: interval events need an interval_range_s, and other events cannot have one.") - if isinstance(cfg, Quantity) and cfg.log and output_shape: - errors.append(f"{entry}: a logged quantity must have shape ('worlds',), got {output_shape}.") + if isinstance(cfg, Quantity) and (cfg.log or cfg.record) and output_shape: + errors.append(f"{entry}: a logged or recorded quantity must have shape ('worlds',), got {output_shape}.") if isinstance(cfg, Event) and cfg.commit is True and cfg.mode is not EventMode.RESET: errors.append(f"{entry}: only reset events can ask for a commit.") if isinstance(cfg, Command) and implementation is not None and implementation.reset is not None: @@ -555,12 +708,12 @@ def _compile_term(self, entry: ScheduleEntry, context: CompileContext) -> None: return # Check the hooks' signatures. Params and rng are not arrays. - dtype = wp.bool if isinstance(cfg, Termination) else wp.float32 arguments = { **dict.fromkeys(names), **fields, **{name: ArrayLayout(wp.float32, len(shape), {}) for name, shape in state_shapes.items()}, **{name: ArrayLayout(wp.float32, 1 + len(output_shape), {}) for name in command}, + **{name: ArrayLayout(wp.float32, 2, {}) for name in action}, } if term.init is not None: try: @@ -573,6 +726,9 @@ def _compile_term(self, entry: ScheduleEntry, context: CompileContext) -> None: # Events and commands take the mask of the worlds to write; other Warp functions take the output to write. if isinstance(cfg, (Command, Event)): _check_hook(entry, implementation.compute, arguments, errors, extra="mask") + elif isinstance(cfg, Action): + # A Python hook may take the worlds where the action is active, as ``mask``. + _check_hook(entry, implementation.compute, {**arguments, "mask": None}, errors) else: extra = "out" if implementation is term.warp else None _check_hook(entry, implementation.compute, arguments, errors, len(output_shape), extra, dtype) @@ -590,13 +746,7 @@ def _compile_term(self, entry: ScheduleEntry, context: CompileContext) -> None: elif isinstance(cfg, Event): timer = cfg.interval_range_s - observation = None - if isinstance(cfg, Observation): - group = entry.path[1] - start = context.observation_dims.get(group, 0) - columns = slice(start, start + math.prod(output_shape) * max(cfg.history_length, 1)) - context.observation_dims[group] = columns.stop - observation = ObservationOutput(group, columns, cfg.noise, cfg.clip, cfg.scale, cfg.history_length) + observation, columns = _allocate_columns(entry, output_shape, context) if isinstance(cfg, (Command, Quantity)): named = {dim: size for dim, size in zip(term.shape[1:], output_shape) if isinstance(dim, str)} context.mdp_fields[entry.writes[0]] = ArrayLayout(wp.float32, 1 + len(output_shape), named, output_shape) @@ -638,6 +788,9 @@ def _compile_term(self, entry: ScheduleEntry, context: CompileContext) -> None: init=term.init, commit=cfg.commit if isinstance(cfg, Event) else False, log=isinstance(cfg, Quantity) and cfg.log, + record=isinstance(cfg, Quantity) and cfg.record, + columns=columns, + stage=entry.stage, ) ) @@ -705,6 +858,54 @@ def _implementation(entry: ScheduleEntry, backend: Backend, errors: list[str]) - return implementation +def _allocate_columns( + entry: ScheduleEntry, output_shape: tuple[int, ...], context: CompileContext +) -> tuple[ObservationOutput | None, slice | None]: + """Give an observation its output, with as many columns as it writes, and an action term its columns of the + action, after those of the uses compiled before it. Returns the observation's output and the action term's + columns.""" + cfg = entry.cfg + if isinstance(cfg, Observation): + # Columns are given once the world configs merge, by name, see _allocate_slots. + columns = slice(0, math.prod(output_shape) * max(cfg.history_length, 1)) + output = ObservationOutput(entry.buffer, columns, cfg.noise, cfg.clip, cfg.scale, cfg.history_length) + return replace(output, slot=entry.name or entry.path[-1]), None + if isinstance(cfg, Action): + columns = slice(context.action_dim, context.action_dim + output_shape[0]) + context.action_dim = columns.stop + context.mdp_fields[last_action] = ArrayLayout(wp.float32, 2, {"actions": columns.stop}, (columns.stop,)) + return None, columns + return None, None + + +def _check_action(entry: ScheduleEntry, output_shape: tuple[int, ...] | None, errors: list[str]) -> None: + """Record why an action term cannot be compiled: its shape or its hooks. + + Actions write their fields in schedule order, so an action term may write elements of a field that other actions + also write, such as other joints of a joint target. + """ + term = entry.cfg.term + if term.random or term.init is not None: + errors.append(f"{entry}: action terms cannot be random or have an init hook.") + if output_shape is not None and len(output_shape) != 1: + errors.append(f"{entry}: an action's shape is ('worlds', columns), got {term.shape}.") + + +def _check_output_type(entry: ScheduleEntry, dtype: type, errors: list[str]) -> None: + """Record why a term's output type does not fit its use: only observations of groups that are not concatenated may + set one.""" + cfg = entry.cfg + if cfg.term.dtype is not None and not isinstance(cfg, Observation): + errors.append(f"{entry}: only observations can set an output type.") + if isinstance(cfg, Observation) and dtype is not wp.float32: + processed = cfg.noise is not None or cfg.clip is not None or cfg.scale is not None or cfg.history_length + if processed or entry.concatenate: + errors.append( + f"{entry}: an observation of type {dtype.__name__} must be in a group with concatenate=False, without" + " noise, clip, scale, or history." + ) + + def _dimension_sizes(fields: Mapping[str, ArrayLayout | None]) -> dict[str, int]: """Return the size of each named dimension of a term's inputs. @@ -852,3 +1053,129 @@ def _merge_ops( for position, (op, worlds, index, weights) in enumerate(phase_ops) ) return result + + +def _expand(task: TaskCfg, num_worlds: int) -> list[tuple[TaskCfg, int]]: + """Return the tasks without splits that a task runs, each with its number of worlds. + + A split becomes, in each of its shares of the worlds, a split with only that subtask. A split may be part of a + task that runs its subtasks together, but not of a sequence, and not of more than one subtask of a task. + """ + if task.mode is TaskMode.SPLIT: + names = list(task.subtasks) + if not names: + raise ValueError("A split needs at least one subtask.") + shares = task.worlds + if shares is None: + shares = {name: num_worlds // len(names) + (k < num_worlds % len(names)) for k, name in enumerate(names)} + if set(shares) != set(names) or sum(shares.values()) != num_worlds: + raise ValueError(f"A split must give its subtasks {names} all of its {num_worlds} worlds, got {shares}.") + return [ + (replace(task, subtasks={name: subtask}, worlds=None), count) + for name in names + for subtask, count in _expand(task.subtasks[name], shares[name]) + ] + + variants = {name: _expand(subtask, num_worlds) for name, subtask in task.subtasks.items()} + splits = [name for name, expanded in variants.items() if len(expanded) > 1] + if splits and task.mode is TaskMode.SEQUENCE: + raise ValueError(f"The subtasks {splits} of a sequence split the worlds, which a sequence cannot do.") + if len(splits) > 1: + raise ValueError(f"Only one subtask of a task may split the worlds, found {splits}.") + single = {name: expanded[0][0] for name, expanded in variants.items()} + if not splits: + return [(replace(task, subtasks=single), num_worlds)] + return [(replace(task, subtasks={**single, splits[0]: subtask}), count) for subtask, count in variants[splits[0]]] + + +def _scoped(cfg: object, scope: Mapping[FieldSelector, FieldSelector]) -> object: + """Return a use whose selectors of commands and quantities name the fields of the task that defines them.""" + if not scope: + return cfg + if isinstance(cfg, DirectAction): + return replace(cfg, offset=scope.get(cfg.offset, cfg.offset)) if isinstance(cfg.offset, FieldSelector) else cfg + if not isinstance(cfg, TermCfg): + return cfg + changes = {"inputs": {arg: scope.get(selector, selector) for arg, selector in cfg.inputs.items()}} + if isinstance(cfg, Observation) and cfg.noise is not None and cfg.noise.scale is not None: + changes["noise"] = replace(cfg.noise, scale=scope.get(cfg.noise.scale, cfg.noise.scale)) + return replace(cfg, **changes) + + +def _has_completion(task: TaskCfg) -> bool: + return task.done is not None or any(_has_completion(subtask) for subtask in task.subtasks.values()) + + +def _completes(nodes: tuple[TaskNode, ...]) -> set[str]: + """Return the paths of the tasks of a tree that have a completion.""" + completes = set() + for node in reversed(nodes): + if node.done is not None or any(child in completes for child in node.children): + completes.add(node.path) + return completes + + +def _allocate_slots( + ops: tuple[TermOp, ...], modes: Mapping[str, TaskMode], errors: list[str] +) -> tuple[tuple[TermOp, ...], tuple[ObservationSlot, ...], dict[str, int], dict[str, tuple[tuple[int, ...], type]]]: + """Give the observation ops their columns: one slot per name in each buffer, in order, as wide as its widest op. + + Ops of different world configs or of different tasks of a sequence may share a slot, since they never write it in + the same world at the same step. Returns the ops, the slots that some op writes only in some steps of an episode, + whose other columns are zeroed, the columns of each buffer, and the layouts of the buffers of separate terms. + """ + buffers: dict[str, dict[str, list[TermOp]]] = {} + for op in ops: + buffers.setdefault(op.observation.group, {}).setdefault(op.observation.slot, []).append(op) + + placed, slots, dims, layouts = {}, [], {}, {} + for buffer, named in buffers.items(): + start = 0 + for name, slot_ops in named.items(): + histories = {op.observation.history_length for op in slot_ops} + if len(histories) > 1: + errors.append(f"The observations named '{name}' of '{buffer}' must have the same history length.") + if "/" in buffer: + shapes = {(op.shape, op.dtype) for op in slot_ops} + if len(shapes) > 1: + errors.append(f"The observations '{buffer}' must have the same shape and type, got {shapes}.") + layouts[buffer] = (slot_ops[0].shape, slot_ops[0].dtype) + for first, second in itertools.combinations(slot_ops, 2): + if not _exclusive(first, second, modes): + errors.append( + f"'{first.name}' and '{second.name}' share the columns of '{name}' in '{buffer}', so they must" + " run in different world configs or in different tasks of a sequence." + ) + size = max(math.prod(op.shape) for op in slot_ops) + columns = slice(start, start + size * max(slot_ops[0].observation.history_length, 1)) + start = columns.stop + for op in slot_ops: + placed[op.name] = replace(op, observation=replace(op.observation, columns=columns, size=size)) + if any(op.stage for op in slot_ops): + slots.append(ObservationSlot(buffer, columns, size, tuple(placed[op.name] for op in slot_ops))) + dims[buffer] = start + return tuple(placed[op.name] for op in ops), tuple(slots), dims, layouts + + +def _exclusive(first: TermOp, second: TermOp, modes: Mapping[str, TaskMode]) -> bool: + """Return whether two ops never run in the same world at the same step.""" + if first.worlds is not None and second.worlds is not None and not set(first.worlds) & set(second.worlds): + return True + if first.stage is None or second.stage is None: + return False + # Tasks of a sequence run one after another: the ops are exclusive below different subtasks of a sequence. + a, b = first.stage.split("."), second.stage.split(".") + common = list(itertools.takewhile(lambda pair: pair[0] == pair[1], zip(a, b))) + if len(common) in (len(a), len(b)): + return False + return modes.get(".".join(part for part, _ in common)) is TaskMode.SEQUENCE + + +def _used_columns(ops: tuple[TermOp, ...], worlds: range) -> dict[str, int]: + """Return, per observation buffer, the columns up to the last that the ops active in some of ``worlds`` use.""" + used: dict[str, int] = {} + for op in ops: + if op.worlds is None or set(op.worlds) & set(worlds): + buffer = op.observation.group + used[buffer] = max(used.get(buffer, 0), op.observation.columns.stop) + return used diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py index 59e9d218822b..04922b57c0f4 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py @@ -11,16 +11,29 @@ import math from collections.abc import Hashable, Mapping from dataclasses import dataclass, field +from types import MappingProxyType from typing import Any import numpy as np +import torch import warp as wp from isaaclab.utils.warp import ProxyArray from . import rng -from .config import Entity, FieldSelector, Phase, SubsetSelector, episode_length, last_action, term_state, terminated -from .plan import ActionOp, ExecutionPlan, Launches, Segment, TermOp, segments +from .config import ( + Entity, + FieldSelector, + Phase, + SubsetSelector, + TaskMode, + episode_length, + last_action, + progress_field, + term_state, + terminated, +) +from .plan import ActionOp, ExecutionPlan, Launches, ObservationSlot, Segment, Step, TaskTree, TermOp, segments from .scene import SceneData, SceneSchema @@ -49,7 +62,9 @@ class MDPState: - ``("selected", op)``: the worlds that the hook of a timed op, or of an op active in some worlds, acts on; - ``("active", op)``: the worlds where an op is active, for an op that is active in only some; - ``"interval_worlds"``: the worlds where an interval event that writes scene fields ran in the last - ``evaluate``, for an MDP with such events. + ``evaluate``, for an MDP with such events; + - ``mdp2.progress_field(task, name)``: the progress of every task, with the internal ``streak`` (steps that a + task's ``done`` held) and ``entered`` (whether a task of a sequence started at this step). """ arrays: dict[Hashable, ProxyArray] @@ -101,6 +116,17 @@ class WorldConfig: observation_dims: Mapping[str, int] # Columns of each observation group it uses, from the first +@dataclass(frozen=True) +class ObservationColumns: + """Columns of an observation buffer that the observations of one name write, see :meth:`MDP.spec`.""" + + name: str + columns: slice # For every step of the history + size: int # Columns of one step of history + history_length: int + widths: Mapping[str, int] # Columns of one step that each op writes, by op name; the others are zero + + @dataclass(frozen=True) class MDP: """An immutable, compiled MDP, created with :meth:`MDPBuilder.finalize`.""" @@ -111,13 +137,19 @@ class MDP: ops: Mapping[Phase, tuple[ActionOp | TermOp, ...]] # In schedule order plan: ExecutionPlan action_dim: int - observation_dims: Mapping[str, int] + observation_dims: Mapping[str, int] # Elements per world of each observation buffer + # Per buffer: the shape after the world dimension and the element type. A concatenated group is (dim,) float32; + # a term of a group that is not concatenated is the buffer "group/term", with the term's own shape and type. + observation_layouts: Mapping[str, tuple[tuple[int, ...], type]] max_episode_length: int | None # Control steps until truncation, None without a time limit streams: tuple[str, ...] # Use names of the rows of MDPState.rng, with "/noise" for observation noise subsets: Mapping[SubsetSelector, tuple[int, ...]] # Indices of every selected subset diagnostics: bool # Whether evaluate also writes the reward and termination of every term final_observations: bool # Whether evaluate also writes the observations of the worlds that ended world_configs: tuple[WorldConfig, ...] # One per replicated builder, or one for every world + # The task tree of each world config, if the MDP tracks progress: some task has a completion or a sequence + tasks: tuple[TaskTree, ...] = () + slots: tuple[ObservationSlot, ...] = () # Observation slots that some op writes only in some steps launches: Launches | None = None # Set by finalize, None for an MDP that was only validated @property @@ -135,8 +167,8 @@ def step_dt(self) -> float: @property def term_ops(self) -> tuple[TermOp, ...]: - """Ops of every phase except actions, in schedule order.""" - return tuple(op for phase, ops in self.ops.items() if phase is not Phase.ACTIONS for op in ops) + """Ops of term uses, of every phase, in schedule order: all but the direct actions.""" + return tuple(op for ops in self.ops.values() for op in ops if isinstance(op, TermOp)) @property def schedule(self) -> tuple[str, ...]: @@ -175,6 +207,47 @@ def interval_writes(self) -> frozenset[FieldSelector]: def _scene_writes(self, phase: Phase) -> frozenset[FieldSelector]: return frozenset(selector for op in self.ops[phase] for selector in op.writes if selector.scene) + def spec(self) -> dict[str, tuple[ObservationColumns, ...]]: + """Return the columns of every observation buffer, by name, so that learners need not know their offsets. + + Observations of the same name share their columns, also across world configs and tasks of a sequence; see + :meth:`observation_mask` for the columns that the worlds write at a step. + """ + named: dict[str, dict[str, list[TermOp]]] = {} + for op in self.ops[Phase.OBSERVATIONS]: + named.setdefault(op.observation.group, {}).setdefault(op.observation.slot, []).append(op) + return { + buffer: tuple( + ObservationColumns( + name=name, + columns=ops[0].observation.columns, + size=ops[0].observation.size, + history_length=ops[0].observation.history_length, + widths=MappingProxyType({op.name: math.prod(op.shape) for op in ops}), + ) + for name, ops in slots.items() + ) + for buffer, slots in named.items() + } + + def observation_mask(self, state: MDPState, buffer: str) -> torch.Tensor: + """Return which columns of an observation buffer each world writes at this step, ``(num_worlds, dim)`` bool. + + The others are zero: they pad an observation to the widest of its name, or belong to observations of other + world configs or of tasks of a sequence that do not run. Torch operations only, so it can run in a graph. + """ + mask = torch.zeros(self.num_worlds, self.observation_dims[buffer], dtype=torch.bool, device=self.device) + for op in self.ops[Phase.OBSERVATIONS]: + if op.observation.group != buffer: + continue + columns = op.observation.columns + width = torch.arange(columns.stop - columns.start, device=self.device) % op.observation.size + written = (width < math.prod(op.shape))[None, :] + if op.active_key is not None: + written = written & state.arrays[op.active_key].torch[:, None] + mask[:, columns] |= written + return mask + def describe(self) -> str: """Return the compiled MDP as readable text: ops by phase with their layout, then each function's steps.""" lines = [ @@ -184,11 +257,23 @@ def describe(self) -> str: ] width = max((len(name) for name in self.schedule), default=0) + for tree in self.tasks: + worlds = f" (worlds {tree.worlds.start}-{tree.worlds.stop - 1})" if len(self.tasks) > 1 else "" + lines.append(f"tasks{worlds}") + for node in tree.nodes: + details = [node.mode.name.lower()] if node.children else [] + details += [f"done {node.done}"] if node.done is not None else [] + details += [f"hold {node.hold}"] if node.hold > 1 else [] + details += [f"require {node.require}"] if node.require is not None else [] + details += [f"final {node.final}"] if node.final is not None else [] + details += ["staged"] if node.staged else [] + lines.append(f" {node.path or '(root)'} {', '.join(details)}".rstrip()) + for phase, ops in self.ops.items(): if ops: lines.append(phase.name.lower().replace("_", " ")) for op in ops: - if phase is Phase.ACTIONS: + if isinstance(op, ActionOp): details = [f"columns {op.columns.start}:{op.columns.stop} -> {op.target}"] details += [f"scale {op.scale}", f"offset {op.offset}"] else: @@ -206,6 +291,7 @@ def describe(self) -> str: details += [f"state {', '.join(op.state)}"] if op.state else [] details += [f"stream {op.stream}"] if op.stream is not None else [] details += ["torch hooks"] if op.torch_hooks else [] + details += [f"during {op.stage}"] if op.stage else [] if op.worlds is not None: first, last = op.worlds[0], op.worlds[-1] contiguous = op.worlds == tuple(range(first, last + 1)) @@ -218,7 +304,7 @@ def describe(self) -> str: for segment in function_segments: lines.append(f" {'graph' if segment.capturable else 'eager'}") for step in segment.steps: - lines.append(f" {step.kind.name.lower().replace('_', ' '):14} {step.op.name}") + lines.append(f" {step.kind.name.lower().replace('_', ' '):14} {_target(step)}") return "\n".join(lines) @@ -235,6 +321,7 @@ def state(self, scene_data: SceneData, seed: int = 0) -> MDPState: } for action_dim in self.narrow_action_dims: arrays[last_action, action_dim] = self._zeros(self.num_worlds, action_dim) + arrays |= self._progress_arrays() for op in self.ops[Phase.COMMANDS] + self.ops[Phase.QUANTITIES]: arrays[op.writes[0]] = self._zeros(self.num_worlds, *op.shape) for subset, indices in self.subsets.items(): @@ -250,8 +337,9 @@ def state(self, scene_data: SceneData, seed: int = 0) -> MDPState: # Each world config starts the shared state of its worlds at its own initial value. arrays[key].torch[list(op.worlds)] = spec.initial - selectors = [op.target for op in self.ops[Phase.ACTIONS]] - selectors += [op.offset for op in self.ops[Phase.ACTIONS] if isinstance(op.offset, FieldSelector)] + direct = [op for op in self.ops[Phase.ACTIONS] if isinstance(op, ActionOp)] + selectors = [op.target for op in direct] + selectors += [op.offset for op in direct if isinstance(op.offset, FieldSelector)] selectors += [ selector for op in self.term_ops for selector in op.inputs.values() if not isinstance(selector, Entity) ] @@ -279,10 +367,10 @@ def state(self, scene_data: SceneData, seed: int = 0) -> MDPState: history_shape = (op.observation.history_length, math.prod(op.shape)) arrays["history", op.name] = self._zeros(self.num_worlds, *history_shape) launches = self.backend is Backend.WARP and not isinstance(op.compute, wp.Function) - if launches and op.phase not in events: + if launches and op.phase not in (*events, Phase.ACTIONS): arrays["scratch", op.name] = self._zeros(self.num_worlds, *op.shape, dtype=op.dtype) # Hooks of ops active in only some worlds get the reset worlds among those. - if op.timer is not None or op.worlds is not None: + if op.timer is not None or op.active_key is not None: arrays["selected", op.name] = self._zeros(self.num_worlds, dtype=wp.bool) for ops in self.ops.values(): for op in ops: @@ -311,9 +399,45 @@ def state(self, scene_data: SceneData, seed: int = 0) -> MDPState: return MDPState(arrays=arrays, arguments=arguments, scene_data=scene_data, caches=caches) + def _progress_arrays(self) -> dict[Hashable, ProxyArray]: + """Allocate the progress of every task, as at the start of an episode: only the tasks that run first are + active, in the worlds of their world config.""" + values: dict[FieldSelector, np.ndarray] = {} + + def array(path: str, name: str, dtype: type, initial: float = 0) -> np.ndarray: + return values.setdefault(progress_field(path, name), np.full(self.num_worlds, initial, dtype=dtype)) + + for tree in self.tasks: + worlds = slice(tree.worlds.start, tree.worlds.stop) + for node in tree.nodes: + for name in ("done", "holding", "active"): + array(node.path, name, np.bool_) + array(node.path, "done_at", np.int32, -1) + array(node.path, "started_at", np.int32) + array(node.path, "score", np.float32) + if node.mode is TaskMode.SEQUENCE: + array(node.path, "stage", np.int32) + if node.done is not None: + array(node.path, "streak", np.int32) + if node.staged: + array(node.path, "entered", np.bool_) + values[progress_field(node.path, "active")][worlds] = tree.runs_at_start(node) + + dtypes = {np.bool_: wp.bool, np.int32: wp.int32, np.float32: wp.float32} + return { + key: ProxyArray(wp.array(value, dtype=dtypes[value.dtype.type], device=self.device)) + for key, value in values.items() + } + def observations(self) -> dict[str, ProxyArray]: - """Allocate one zeroed observation buffer per group, of shape ``(num_worlds, group_dim)``.""" - return {group: self._zeros(self.num_worlds, dim) for group, dim in self.observation_dims.items()} + """Allocate one zeroed buffer per observation buffer, of shape ``(num_worlds, dim)`` and its element type. + + The buffer of a separate term is flat per world: view it with the shape in :attr:`observation_layouts`. + """ + return { + buffer: self._zeros(self.num_worlds, dim, dtype=self.observation_layouts[buffer][1]) + for buffer, dim in self.observation_dims.items() + } def transition(self) -> Transition: """Allocate the zeroed buffers of a transition, with the optional buffers that the MDP writes.""" @@ -335,3 +459,12 @@ def transition(self) -> Transition: def _zeros(self, *shape: int, dtype: type = wp.float32) -> ProxyArray: return ProxyArray(wp.zeros(shape, dtype=dtype, device=self.device)) + + +def _target(step: Step) -> str: + """Return what a step works on, for :meth:`MDP.describe`.""" + if isinstance(step.op, ObservationSlot): + return f"{step.op.buffer}[{step.op.columns.start}:{step.op.columns.stop}]" + if isinstance(step.op, tuple): + return "tasks" + return f"{step.op.name}{' on start' if step.entry else ''}" diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py index 9752552176d3..c10215ffc289 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py @@ -167,6 +167,8 @@ class Quantity(TermCfg): phase: ClassVar[Phase] = Phase.QUANTITIES log: bool = False # Log its average over the worlds' last finished episodes, taken at their end, as a metric + # Record its value at the end of every episode, in the episode records of an environment with an episode budget + record: bool = False @dataclass @@ -185,6 +187,27 @@ class Observation(TermCfg): history_length: int = 0 # Steps of history to observe, 0 for the latest value only +@dataclass +class ObservationGroup: + """A group of observation uses, like MDP1's ``ObservationGroupCfg``. A plain dict of uses is short for a + concatenated group. + + A concatenated group is one ``float32`` buffer of its terms in declaration order. Otherwise each term keeps its + own buffer, shape, and type, and may output another type, such as a ``uint8`` image, when it has no noise, clip, + scale, or history. + """ + + terms: dict[str, Observation | None] = field(default_factory=dict) + concatenate: bool = True # Concatenate the terms into one buffer, or keep a buffer per term + + +def group_terms(group: dict[str, Observation | None] | ObservationGroup) -> tuple[dict[str, Observation | None], bool]: + """Return the uses of an observation group of :attr:`TaskCfg.observations`, and whether they are concatenated.""" + if isinstance(group, ObservationGroup): + return group.terms, group.concatenate + return group, True + + @dataclass class Reward(TermCfg): """Configuration for a reward term, whose output adds ``weight * value * step_dt`` to the reward.""" @@ -255,15 +278,163 @@ class DirectAction: subset: SubsetSelector | None = None # Elements of the target to write, like robot.joints("slider_to_cart") +@dataclass +class Action(TermCfg): + """Configuration for an action term, whose hooks turn the columns of the action into writes to ``outputs``. + + The term's shape is ``("worlds", n)``, with the number of columns ``n`` it takes, and its hooks get them as + ``action``: a Python hook ``compute(action, **args)`` writes its outputs in place, and a func + ``compute(world, action, **args)`` writes its world. Actions apply before every physics step, as in MDP1. + """ + + phase: ClassVar[Phase] = Phase.ACTIONS + + outputs: dict[str, FieldSelector] = field(default_factory=dict) # Passed by argument name; the action writes them + + +class TaskMode(enum.Enum): + """How the subtasks of a task run, see :func:`compose`, :func:`sequence`, and :func:`split`.""" + + TOGETHER = enum.auto() # In the same worlds and steps + SEQUENCE = enum.auto() # In the same worlds, one after another + SPLIT = enum.auto() # Each in its own worlds + + @dataclass class TaskCfg: - """Configuration of the MDP of a task. Setting a term use to ``None`` disables it.""" + """Configuration of the MDP of a task. Setting a term use to ``None`` disables it. - actions: dict[str, DirectAction | None] = field(default_factory=dict) + A task may also say when it is done, and hold named subtasks, which are tasks too. Its uses run whenever it runs; + those of a subtask run when the subtask does, and their names get the subtask's name as a prefix, as in + ``rewards.grasp.lift``, except in a :func:`split`. A subtask reads its own commands and quantities by their names, + as a task that runs alone does; :func:`term_state` and :data:`progress` name uses and tasks by their full paths. + The progress of every task is a set of fields that terms read, see :data:`progress`. + """ + + actions: dict[str, DirectAction | Action | None] = field(default_factory=dict) commands: dict[str, Command | None] = field(default_factory=dict) quantities: dict[str, Quantity | None] = field(default_factory=dict) - # Groups, such as "policy", of observation uses that are concatenated in declaration order into one buffer. - observations: dict[str, dict[str, Observation | None]] = field(default_factory=dict) + # Groups, such as "policy", of observation uses: a dict of uses is a concatenated group, see ObservationGroup. + observations: dict[str, dict[str, Observation | None] | ObservationGroup] = field(default_factory=dict) rewards: dict[str, Reward | None] = field(default_factory=dict) terminations: dict[str, Termination | TimeLimit | None] = field(default_factory=dict) events: dict[str, Event | None] = field(default_factory=dict) + + # Completion of a task without subtasks: a field of one value per world, true where it is positive. + done: FieldSelector | None = None + hold: int = 1 # Consecutive steps that ``done`` must hold, counted from the step after the task starts + score: float = 1.0 # Weight of the task in its parent's score + # Whether the parent is done only while this task's completion holds (True) or does not (False); None to not check + final: bool | None = None + + subtasks: dict[str, TaskCfg] = field(default_factory=dict) + mode: TaskMode = TaskMode.TOGETHER + require: int | None = None # Together: the subtasks that must be done, None for all of those with a completion + worlds: dict[str, int] | None = None # Split: the worlds of each subtask, None for even shares + + +@dataclass(init=False) +class Milestone(TaskCfg): + """A task that only has a completion, such as a step of a :func:`sequence`.""" + + def __init__( + self, done: FieldSelector, hold: int = 1, score: float = 1.0, final: bool | None = None, **fields: Any + ) -> None: + # The other fields are those of a task, as ``dataclasses.replace`` passes them. + super().__init__(done=done, hold=hold, score=score, final=final, **fields) + + +PROGRESS_FIELDS = ("done", "holding", "active", "score", "done_at", "started_at", "stage") +"""Fields of the progress of a task: whether it is done (once done, until the episode ends), whether its completion +holds at this step, whether it runs, its score in ``[0, 1]``, the episode step at which it was done (-1 before) and at +which it last started, and the subtask that a sequence runs.""" + + +@dataclass(frozen=True) +class TaskSelector: + """Selects the progress of a task: ``mdp2.progress.done``, or ``mdp2.progress.grasp.done`` for a subtask.""" + + path: tuple[str, ...] = () + + def __getattr__(self, name: str) -> TaskSelector | FieldSelector: + if name.startswith("_"): + raise AttributeError(name) + if name in PROGRESS_FIELDS: + return progress_field(".".join(self.path), name) + return TaskSelector((*self.path, name)) + + +def progress_field(task: str, name: str) -> FieldSelector: + """Select a field of the progress of the task at the dotted path ``task``, "" for the root task.""" + return FieldSelector("progress", f"{task}.{name}" if task else name, scene=False) + + +progress = TaskSelector() +"""The progress of the task and its subtasks, as fields of one value per world, see :data:`PROGRESS_FIELDS`.""" + + +def compose(*tasks: TaskCfg, require: int | None = None, **subtasks: TaskCfg) -> TaskCfg: + """Run tasks together, in the same worlds and steps. + + Unnamed tasks, such as those of a scene, an embodiment, and a task, merge into one: uses keep the order of the + tasks, then their order within each task, and observation groups merge term by term. Two tasks may not both define + a use, unless the later one sets it to ``None``, which removes it, and only one may say when it is done or hold + subtasks. Named tasks become subtasks that run together, and the task is done once ``require`` of them are done + (None for all of them). Raises a single ``ValueError`` that lists every conflict. + """ + composed, errors = TaskCfg(), [] + owners: dict[tuple[str, ...], int] = {} # Task that defines each use + concatenated: dict[str, bool] = {} # Whether each observation group is concatenated + + def merge(path: tuple[str, ...], target: dict, uses: dict, index: int) -> None: + for name, use in uses.items(): + if use is not None and target.get(name) is not None: + errors.append(f"Tasks {owners[(*path, name)]} and {index} both define '{'.'.join((*path, name))}'.") + continue + owners[(*path, name)] = index + target[name] = use + + for index, task in enumerate(tasks): + merge(("actions",), composed.actions, task.actions, index) + merge(("commands",), composed.commands, task.commands, index) + merge(("quantities",), composed.quantities, task.quantities, index) + merge(("rewards",), composed.rewards, task.rewards, index) + merge(("terminations",), composed.terminations, task.terminations, index) + merge(("events",), composed.events, task.events, index) + for group, observations in task.observations.items(): + terms, concatenate = group_terms(observations) + if concatenated.setdefault(group, concatenate) != concatenate: + errors.append(f"Task {index} and an earlier task disagree on whether group '{group}' is concatenated.") + continue + target = composed.observations.setdefault(group, ObservationGroup(concatenate=concatenate)).terms + merge(("observations", group), target, terms, index) + + # The completion and subtasks come from the one task that has them. + cores = [task for task in tasks if task.done is not None or task.subtasks] + if len(cores) > 1: + errors.append("Only one of the tasks may have a completion or subtasks; name the others to make them subtasks.") + elif cores: + core = cores[0] + composed.done, composed.hold, composed.score, composed.final = core.done, core.hold, core.score, core.final + composed.subtasks, composed.mode = dict(core.subtasks), core.mode + composed.require, composed.worlds = core.require, core.worlds + if subtasks: + if cores: + errors.append("Tasks with a completion or subtasks cannot also get named subtasks; name them as well.") + composed.subtasks, composed.mode, composed.require = dict(subtasks), TaskMode.TOGETHER, require + + if errors: + raise ValueError("Cannot compose the tasks:\n " + "\n ".join(errors)) + return composed + + +def sequence(**subtasks: TaskCfg) -> TaskCfg: + """Run subtasks one after another, in the same worlds. A subtask starts at the step after the previous one is + done, and the task is done once the last one is, which keeps running until the episode ends.""" + return TaskCfg(subtasks=dict(subtasks), mode=TaskMode.SEQUENCE) + + +def split(worlds: dict[str, int] | None = None, **subtasks: TaskCfg) -> TaskCfg: + """Run each subtask in its own worlds, ``worlds[name]`` of them, or an even share if ``worlds`` is None; the first + subtasks get one more world when the worlds do not split evenly. A split cannot be part of a sequence.""" + return TaskCfg(subtasks=dict(subtasks), mode=TaskMode.SPLIT, worlds=worlds) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi index 28b43c3dd68a..5b34140f863a 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi @@ -4,6 +4,7 @@ # SPDX-License-Identifier: BSD-3-Clause __all__ = [ + "binary_joint_position", "heading_velocity_command", "uniform_pose_command", "uniform_velocity_command", @@ -21,7 +22,10 @@ __all__ = [ "base_ang_vel", "base_lin_vel", "generated_commands", + "image_rgb", + "one_hot", "joint_pos", + "joint_pos_normalized", "joint_pos_limit_normalized", "joint_pos_rel", "joint_vel", @@ -53,11 +57,13 @@ __all__ = [ "bad_orientation", "illegal_contact", "is_positive", + "is_true", "joint_pos_out_of_manual_limit", "joint_vel_out_of_limit", "root_height_below_minimum", ] +from .actions import binary_joint_position from .commands import heading_velocity_command, uniform_pose_command, uniform_velocity_command from .curriculums import difficulty_scheduler from .events import ( @@ -76,7 +82,10 @@ from .observations import ( base_ang_vel, base_lin_vel, generated_commands, + image_rgb, + one_hot, joint_pos, + joint_pos_normalized, joint_pos_limit_normalized, joint_pos_rel, joint_vel, @@ -112,6 +121,7 @@ from .terminations import ( bad_orientation, illegal_contact, is_positive, + is_true, joint_pos_out_of_manual_limit, joint_vel_out_of_limit, root_height_below_minimum, diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/actions.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/actions.py new file mode 100644 index 000000000000..5cd29ddba4be --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/actions.py @@ -0,0 +1,62 @@ +# 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 + +"""Action terms, the MDP2 counterparts of the action terms of :mod:`isaaclab.envs.mdp.actions`. + +An action term gets its columns of the action as ``action`` and writes its ``outputs``. Actions that only scale and +offset the action into a field are :class:`~isaaclab_experimental.mdp2.DirectAction` s, which need no term. +""" + +from __future__ import annotations + +import torch +import warp as wp + +from ..terms import Term + + +@wp.func +def _binary_joint_position( + world: int, + action: wp.array2d(dtype=float), + joint_pos_target: wp.array2d(dtype=float), + joint_ids: wp.array(dtype=wp.int32), + open_position: float, + close_position: float, + threshold: float, + close_above: bool, +): + target = open_position + if (action[world, 0] > threshold) == close_above: + target = close_position + for joint in range(joint_ids.shape[0]): + joint_pos_target[world, joint_ids[joint]] = target + + +def _binary_joint_position_torch( + action: torch.Tensor, + joint_pos_target: torch.Tensor, + joint_ids: torch.Tensor, + open_position: float, + close_position: float, + threshold: float, + close_above: bool, + mask: torch.Tensor | None, +) -> None: + close = (action[:, :1] > threshold) == close_above + target = torch.where(close, close_position, open_position).expand(-1, len(joint_ids)) + if mask is not None: + target = torch.where(mask[:, None], target, joint_pos_target[:, joint_ids]) + joint_pos_target[:, joint_ids] = target + + +binary_joint_position = Term(torch=_binary_joint_position_torch, warp=_binary_joint_position, shape=("worlds", 1)) +"""Binary gripper command, like MDP1's binary joint position actions: the target of the joints of ``joint_ids`` is +``close_position`` where the action is above ``threshold`` if ``close_above``, or at most ``threshold`` otherwise, +and ``open_position`` elsewhere. Bind ``joint_pos_target`` as an output. + +MDP1's ``BinaryJointPositionAction`` closes below zero: ``threshold=0.0, close_above=False``, which also closes at +zero. Its +``AbsBinaryJointPositionAction`` opens above 0.5 by default: ``threshold=0.5, close_above=False``.""" diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/observations.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/observations.py index 910d28ec1fa8..bcc507f9fb45 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/observations.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/observations.py @@ -120,6 +120,27 @@ def _joint_pos_limit_normalized_torch( """Joint positions scaled to [-1, 1] between the soft joint position limits.""" +@wp.func +def _joint_pos_normalized( + world: int, + joint: int, + joint_pos: wp.array2d(dtype=float), + joint_ids: wp.array(dtype=wp.int32), + zero: float, + one: float, +) -> float: + return (joint_pos[world, joint_ids[joint]] - zero) / (one - zero) + + +joint_pos_normalized = Term( + torch=lambda joint_pos, joint_ids, *, zero, one: (joint_pos[:, joint_ids] - zero) / (one - zero), + warp=_joint_pos_normalized, + shape=("worlds", "joint_ids"), +) +"""Joint positions mapped linearly so that the param ``zero`` gives 0 and ``one`` gives 1, such as a gripper's +openness from its open and closed positions.""" + + # Root state. @@ -242,3 +263,38 @@ def _generated_commands(world: int, element: int, command: wp.array2d(dtype=floa generated_commands = Term(torch=lambda command: command, warp=_generated_commands, shape=("worlds", "command")) """The value of a command, bound to ``mdp2.commands.``.""" + + +# Progress. + + +@wp.func +def _one_hot(world: int, index: int, value: wp.array(dtype=wp.int32)) -> float: + return wp.where(value[world] == index, 1.0, 0.0) + + +def _one_hot_torch(value: torch.Tensor, *, size: int) -> torch.Tensor: + return (value[:, None] == torch.arange(size, device=value.device)).float() + + +one_hot = Term(torch=_one_hot_torch, warp=_one_hot, shape=("worlds", "size")) +"""The ``value`` input, one int per world such as the subtask that a sequence runs (``mdp2.progress.stage``), as +``size`` columns, one where the column is the value. A value outside ``[0, size)`` gives zeros.""" + + +# Cameras. + + +@wp.func +def _image_rgb(world: int, row: int, column: int, channel: int, image: wp.array4d(dtype=wp.uint8)) -> wp.uint8: + return image[world, row, column, channel] + + +image_rgb = Term( + torch=lambda image: image, + warp=_image_rgb, + shape=("worlds", "height", "width", "rgb_channels"), + dtype=wp.uint8, +) +"""A camera's ``rgb`` image, ``uint8`` of shape ``(height, width, 3)``, bound as ``image=camera.rgb``. It goes in a +group that is not concatenated: ``ObservationGroup(..., concatenate=False)``.""" diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/terminations.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/terminations.py index 021f6f738d41..a10bcc4783db 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/terminations.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/terminations.py @@ -33,6 +33,19 @@ def _is_positive_torch(value: torch.Tensor) -> torch.Tensor: """Whether the ``value`` input, one float per world such as a quantity, is positive.""" +@wp.func +def _is_true(world: int, value: wp.array(dtype=wp.bool)) -> bool: + return value[world] + + +def _is_true_torch(value: torch.Tensor) -> torch.Tensor: + return value + + +is_true = Term(torch=_is_true_torch, warp=_is_true) +"""The ``value`` input, one bool per world, such as whether the task is done: ``mdp2.progress.done``.""" + + # Joint state. diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py index 499440abe970..2ad7a554aafc 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py @@ -18,7 +18,7 @@ from dataclasses import dataclass from typing import TYPE_CHECKING, Any -from .config import Entity, FieldSelector, Phase, SubsetSelector, UniformNoise, last_action +from .config import Entity, FieldSelector, Phase, SubsetSelector, TaskMode, UniformNoise, last_action, progress_field from .terms import State if TYPE_CHECKING: @@ -40,6 +40,11 @@ class ActionOp: worlds: tuple[int, ...] | None = None # Worlds where the op is active, None for every world subset: SubsetSelector | None = None # Elements of the target it writes, None for all of them + @property + def active_key(self) -> Hashable | None: + """Key in :attr:`MDPState.arrays` of the worlds where the op is active, None for every world.""" + return None if self.worlds is None else ("active", self.name) + @dataclass(frozen=True) class ObservationOutput: @@ -52,6 +57,8 @@ class ObservationOutput: scale: float | None = None history_length: int = 0 # Steps of history in the group, 0 for the latest value only noise_stream: int | None = None # Row of MDPState.rng for the noise + slot: str = "" # Name of its slot of the buffer, which the ops of the same name share + size: int = 0 # Columns of one step of history: those of its slot, which may be wider than the op's output @dataclass(frozen=True) @@ -83,9 +90,21 @@ class TermOp: # Reset events: whether the scene commits the earlier events' writes before it runs, None to infer it commit: bool | None = False log: bool = False # Quantities: whether the environment logs it as a metric + record: bool = False # Quantities: whether the environment records it at the end of every episode + columns: slice | None = None # Actions: the columns of the action that the term takes worlds: tuple[int, ...] | None = None # Worlds where the op is active, None for every world # Actions of its world config, if it reads the last actions and other world configs have more action_dim: int | None = None + # The task of a sequence that the op belongs to: it runs only while that task runs, and its state, timer, and + # command restart when the task starts. Quantities run in every step: they only restart. + stage: str | None = None + + @property + def active_key(self) -> Hashable | None: + """Key in :attr:`MDPState.arrays` of the worlds where the op runs at this step, None for every world.""" + if self.stage is not None and self.phase is not Phase.QUANTITIES: + return progress_field(self.stage, "active") + return None if self.worlds is None else ("active", self.name) def array_key(self, arg: str) -> Hashable: """Return the key in :attr:`MDPState.arrays` of the array that the input ``arg`` reads.""" @@ -104,19 +123,79 @@ class StepKind(enum.Enum): RESET_TIMER = enum.auto() # Draw a new time until the command resamples or the interval event runs RESET_STATE = enum.auto() # Run the reset hook, or set the state to its initial value COMMIT = enum.auto() # Have the scene commit the writes of the reset events so far, before the op's event + UPDATE_PROGRESS = enum.auto() # Count the tasks' completions, bottom up, and advance the sequences + START_TASKS = enum.auto() # Start the tasks that a sequence advanced to, top down, and stop those it left + RESET_PROGRESS = enum.auto() # Restart the progress of every task for a new episode + CLEAR = enum.auto() # Zero the columns of an observation slot that no op writes at this step + + +@dataclass(frozen=True) +class TaskNode: + """A task of the task tree of a world config, with what its progress depends on.""" + + path: str # Dotted path of names from the root task, "" for the root + mode: TaskMode + children: tuple[str, ...] # Paths of its subtasks, in order + done: FieldSelector | None # Completion of a task without subtasks + done_dtype: type | None # Element type of ``done`` + hold: int + score: float # Weight in its parent's score + final: bool | None + require: int | None + staged: bool # Whether it runs only in some steps of an episode: a sequence is one of its ancestors + + +@dataclass(frozen=True) +class TaskTree: + """The tasks of one world config, parents before children, and the tasks among them that have a completion.""" + + worlds: range + nodes: tuple[TaskNode, ...] + completes: frozenset[str] # Paths of the tasks that have a completion + + def node(self, path: str) -> TaskNode: + return next(node for node in self.nodes if node.path == path) + + def parent(self, node: TaskNode) -> TaskNode | None: + return None if not node.path else self.node(node.path.rpartition(".")[0]) + + def runs_at_start(self, node: TaskNode) -> bool: + """Return whether a task runs at the start of an episode: all but the later tasks of a sequence do.""" + parent = self.parent(node) + if parent is None: + return True + first = parent.mode is not TaskMode.SEQUENCE or parent.children[0] == node.path + return first and self.runs_at_start(parent) + + def counted(self, node: TaskNode) -> tuple[TaskNode, ...]: + """Return the subtasks of a task that count towards its completion: those that have one.""" + return tuple(self.node(child) for child in node.children if child in self.completes) + + +@dataclass(frozen=True) +class ObservationSlot: + """Columns of an observation buffer that several ops write, or that an op writes only in some steps.""" + + buffer: str + columns: slice # For every step of the history + size: int # Columns of one step of history + ops: tuple[TermOp, ...] # Ops that write it, each in its own worlds and steps @dataclass(frozen=True) class Step: - """One unit of work on an op in a runtime function.""" + """One unit of work on an op, the task trees, or an observation slot, in a runtime function.""" kind: StepKind - op: ActionOp | TermOp + op: ActionOp | TermOp | tuple[TaskTree, ...] | ObservationSlot + entry: bool = False # Whether it runs for the worlds whose task of the op just started, rather than for the mask @property def capturable(self) -> bool: """Whether the step may run inside a CUDA graph. Only steps that call a non-capturable hook may not.""" - if isinstance(self.op, ActionOp) or self.op.capturable or self.kind in (StepKind.RESET_TIMER, StepKind.COMMIT): + if not isinstance(self.op, TermOp) or self.op.capturable: + return True + if self.kind in (StepKind.RESET_TIMER, StepKind.COMMIT): return True return self.kind is StepKind.RESET_STATE and self.op.reset is None @@ -146,17 +225,29 @@ class ExecutionPlan: observe: tuple[Step, ...] -def build_plan(ops: Mapping[Phase, tuple], schema: SceneSchema) -> ExecutionPlan: - """Order the steps of every runtime function from the ops of each phase. This defines the step contract.""" +def build_plan( + ops: Mapping[Phase, tuple], + schema: SceneSchema, + trees: tuple[TaskTree, ...] = (), + slots: tuple[ObservationSlot, ...] = (), +) -> ExecutionPlan: + """Order the steps of every runtime function from the ops of each phase. This defines the step contract. + + With task trees, ``evaluate`` counts the tasks' completions after the quantities, so that terminations and + rewards see this step's progress, and starts the tasks that sequences advanced to after the events, so that the + successor observations see them. The terminations, rewards, commands, and events of the step run in the tasks that + ran when it started. + """ timed = [op for op in ops[Phase.COMMANDS] + ops[Phase.INTERVAL_EVENTS] if op.timer is not None] observations = tuple(Step(StepKind.COMPUTE, op) for op in ops[Phase.OBSERVATIONS]) + clears = tuple(Step(StepKind.CLEAR, slot) for slot in slots) # Commands write their state when they resample, and persistent state outlives episodes. stateful = [ op for phase in Phase - if phase not in (Phase.ACTIONS, Phase.COMMANDS) + if phase is not Phase.COMMANDS for op in ops[phase] - if op.reset is not None or any(not spec.persistent for spec in op.state.values()) + if isinstance(op, TermOp) and (op.reset is not None or any(not spec.persistent for spec in op.state.values())) ] # Observations and action offsets read quantities between steps, also in worlds that were just reset, where @@ -164,18 +255,32 @@ def build_plan(ops: Mapping[Phase, tuple], schema: SceneSchema) -> ExecutionPlan read = {selector for op in ops[Phase.OBSERVATIONS] for selector in op.inputs.values()} noises = [op.observation.noise for op in ops[Phase.OBSERVATIONS]] read |= {noise.scale for noise in noises if noise is not None and noise.scale is not None} - read |= {op.offset for op in ops[Phase.ACTIONS]} + read |= {op.offset for op in ops[Phase.ACTIONS] if isinstance(op, ActionOp)} observed = [] for op in reversed(ops[Phase.QUANTITIES]): if op.writes[0] in read: observed.insert(0, Step(StepKind.COMPUTE, op)) read |= set(op.inputs.values()) - terminations_and_rewards = [] - for op in ops[Phase.QUANTITIES] + ops[Phase.TERMINATIONS] + ops[Phase.REWARDS]: - terminations_and_rewards.append(Step(StepKind.COMPUTE, op)) - if op.update is not None: - terminations_and_rewards.append(Step(StepKind.UPDATE_STATE, op)) + def computed(phase_ops: tuple) -> list[Step]: + steps = [] + for op in phase_ops: + steps.append(Step(StepKind.COMPUTE, op)) + if op.update is not None: + steps.append(Step(StepKind.UPDATE_STATE, op)) + return steps + + progress = [Step(StepKind.UPDATE_PROGRESS, trees)] if trees else [] + # A task that starts restarts the timers, commands, and state of its ops, as a new episode does. + starts = [] + if any(node.staged for tree in trees for node in tree.nodes): + staged = [op for phase_ops in ops.values() for op in phase_ops if isinstance(op, TermOp) and op.stage] + starts = [ + Step(StepKind.START_TASKS, trees), + *(Step(StepKind.RESET_TIMER, op, entry=True) for op in timed if op.stage), + *(Step(StepKind.COMPUTE, op, entry=True) for op in staged if op.phase is Phase.COMMANDS), + *(Step(StepKind.RESET_STATE, op, entry=True) for op in stateful if op.stage), + ] reset_events = [] pending: set[FieldSelector] = set() # Scene fields written since the last commit @@ -190,24 +295,30 @@ def build_plan(ops: Mapping[Phase, tuple], schema: SceneSchema) -> ExecutionPlan startup=tuple(Step(StepKind.COMPUTE, op) for op in ops[Phase.STARTUP_EVENTS]), apply_actions=tuple(Step(StepKind.COMPUTE, op) for op in ops[Phase.ACTIONS]), evaluate=( - # Quantities, terminations, and rewards see the commands that governed the action. - *terminations_and_rewards, + # Quantities, progress, terminations, and rewards see the commands that governed the action. + *computed(ops[Phase.QUANTITIES]), + *progress, + *computed(ops[Phase.TERMINATIONS] + ops[Phase.REWARDS]), *(Step(StepKind.COMPUTE_IF_DUE, op) for op in timed if op.phase is Phase.COMMANDS), # Commands with an update hook track something every step, like a heading. *(Step(StepKind.UPDATE_STATE, op) for op in ops[Phase.COMMANDS] if op.update is not None), *(Step(StepKind.COMPUTE_IF_DUE, op) for op in timed if op.phase is Phase.INTERVAL_EVENTS), - # Successor observations see the new commands and the events. Their state advances after all of them. + *starts, + # Successor observations see the new commands, the events, and the tasks that started. Their state + # advances after all of them. *observations, + *clears, *(Step(StepKind.UPDATE_STATE, op) for op in ops[Phase.OBSERVATIONS] if op.update is not None), ), reset=( + *([Step(StepKind.RESET_PROGRESS, trees)] if trees else []), *(Step(StepKind.RESET_TIMER, op) for op in timed), *reset_events, *(Step(StepKind.COMPUTE, op) for op in ops[Phase.COMMANDS]), # State restarts last, from the fields and commands of the new episode. *(Step(StepKind.RESET_STATE, op) for op in stateful), ), - observe=(*observed, *observations), + observe=(*observed, *observations, *clears), ) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/terms.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/terms.py index 073167aeffb4..3637424e71a6 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/terms.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/terms.py @@ -85,6 +85,7 @@ class Term: # False for Python hooks that cannot run inside a CUDA graph, such as hooks that read values on the host. They run # between the graphs, which splits them. capturable: bool = True + dtype: type | None = None # Output element type of an observation, such as wp.uint8; float32 if None def __post_init__(self) -> None: if self.torch is not None and not isinstance(self.torch, Implementation): diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py index ced6ef7a506b..acf1a93fa01e 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py @@ -7,12 +7,15 @@ from __future__ import annotations +import functools +import math + import torch from . import rng from .compiled import MDP, MDPState -from .config import FieldSelector, Phase, last_action, term_state, terminated -from .plan import Call, Launch, Launches, Step, StepKind, TermOp +from .config import FieldSelector, Phase, TaskMode, last_action, progress_field, term_state, terminated +from .plan import Call, Launch, Launches, ObservationSlot, Step, StepKind, TaskTree, TermOp from .terms import hook_arguments @@ -41,6 +44,13 @@ def _apply_actions(mdp: MDP, call: Call) -> None: for step in mdp.plan.apply_actions: op = step.op + if isinstance(op, TermOp): + # The hook writes its outputs; it may take the worlds where it is active as ``mask``. + active = _active(op, call.state) + arguments = {**call.state.arguments[op.name], "action": actions[:, op.columns]} + arguments["mask"] = None if active is None else active.torch + op.compute(**hook_arguments(op.compute, arguments)) + continue target = call.state.arrays[op.target].torch.view(mdp.num_worlds, -1) ids = slice(None) if op.subset is None else call.state.arrays[op.subset].torch offset = op.offset @@ -48,7 +58,7 @@ def _apply_actions(mdp: MDP, call: Call) -> None: offset = call.state.arrays[offset].torch.view(mdp.num_worlds, -1)[:, ids] value = actions[:, op.columns] * op.scale + offset - active = call.state.arrays.get(("active", op.name)) + active = _active(op, call.state) if active is not None: value = torch.where(active.torch[:, None], value, target[:, ids]) target[:, ids] = value @@ -81,11 +91,35 @@ def _begin_reset(mdp: MDP, call: Call) -> None: call.state.arrays[last_action, action_dim].torch.masked_fill_(mask[:, None], 0.0) +def _active(op, state: MDPState): + """Return the worlds where an op runs at this step, None for every world.""" + return None if op.active_key is None else state.arrays[op.active_key] + + def _run(mdp: MDP, step: Step, call: Call, stepping: bool) -> None: - """Run one step, for the masked worlds if the call has a mask, and only where the op is active.""" + """Run one step, for the masked worlds if the call has a mask, and only where the op is active. + + A step on entry runs for the worlds where the op's task just started instead. + """ op, state = step.op, call.state + match step.kind: + case StepKind.UPDATE_PROGRESS: + _update_progress(op, state) + return + case StepKind.START_TASKS: + _start_tasks(op, state) + return + case StepKind.RESET_PROGRESS: + _reset_progress(op, state, call.mask.torch) + return + case StepKind.CLEAR: + _clear(mdp, op, call, stepping) + return + mask = None if call.mask is None else call.mask.torch - active = state.arrays.get(("active", op.name)) + active = _active(op, state) + if step.entry: + mask, active = state.arrays[progress_field(op.stage, "entered")].torch, None if active is not None: mask = active.torch if mask is None else mask & active.torch @@ -165,7 +199,10 @@ def _compute(mdp: MDP, op: TermOp, call: Call, mask: torch.Tensor | None, steppi return observation = op.observation - destination = call.observations[observation.group].torch[:, observation.columns] + # The op writes the first columns of each step of history of its slot. + steps = max(observation.history_length, 1) + slot = call.observations[observation.group].torch[:, observation.columns] + destination = slot.view(mdp.num_worlds, steps, observation.size)[:, :, : math.prod(op.shape)] if observation.noise is not None: noise = rng.uniform( state.rng.torch[observation.noise_stream], observation.noise.n_min, observation.noise.n_max, op.shape @@ -181,29 +218,34 @@ def _compute(mdp: MDP, op: TermOp, call: Call, mask: torch.Tensor | None, steppi value = _history(op, state, value.reshape(mdp.num_worlds, -1), mask, push=stepping) value = value.reshape(destination.shape) - destination.copy_(value if mask is None else torch.where(mask[:, None], value, destination)) + destination.copy_(value if mask is None else torch.where(mask[:, None, None], value, destination)) if stepping and transition.final_observations is not None: ended = transition.done.torch if mask is None else transition.done.torch & mask final = transition.final_observations[observation.group].torch[:, observation.columns] - final.copy_(torch.where(ended[:, None], value, final)) + final = final.view(destination.shape[0], steps, observation.size)[:, :, : destination.shape[2]] + final.copy_(torch.where(ended[:, None, None], value, final)) def _history(op: TermOp, state: MDPState, value: torch.Tensor, mask: torch.Tensor | None, push: bool) -> torch.Tensor: - """Push a value into an observation's history, or fill the history of new episodes if not ``push``. + """Push a value into an observation's history, or fill the history where it starts if not ``push``: in new + episodes, or, for an op of a task of a sequence, where the task started at this step. - Returns the history, oldest first, flattened per world. + Returns the history, oldest first, as ``(num_worlds, history_length, size)``. """ history = state.arrays["history", op.name].torch selected = torch.ones_like(value[:, 0], dtype=torch.bool) if mask is None else mask + length = state.episode_length.torch + starts = length == (0 if op.stage is None else state.arrays[progress_field(op.stage, "started_at")].torch) + filled = value[:, None].expand_as(history) if push: - shifted = torch.cat([history[:, 1:], value[:, None]], dim=1) + shifted = torch.where(starts[:, None, None], filled, torch.cat([history[:, 1:], value[:, None]], dim=1)) else: - selected = selected & (state.episode_length.torch == 0) - shifted = value[:, None].expand_as(history) + selected = selected & starts + shifted = filled history.copy_(torch.where(selected[:, None, None], shifted, history)) - return history.flatten(1) + return history def _tick(mdp: MDP, op: TermOp, state: MDPState) -> torch.Tensor: @@ -219,3 +261,111 @@ def _restart(op: TermOp, state: MDPState, mask: torch.Tensor) -> None: """Draw a new interval for the timer of an op in the masked worlds.""" time_left = state.arrays["timer", op.name].torch time_left.copy_(torch.where(mask, rng.uniform(state.rng.torch[op.stream], *op.timer, offset=-1), time_left)) + + +def _clear(mdp: MDP, slot: ObservationSlot, call: Call, stepping: bool) -> None: + """Zero the columns of a slot that no op writes at this step, in the masked worlds.""" + steps = slot.columns.stop - slot.columns.start + columns = torch.arange(steps, device=mdp.device) % slot.size + covered = torch.zeros(mdp.num_worlds, steps, dtype=torch.bool, device=mdp.device) + for op in slot.ops: + active = _active(op, call.state) + width = columns < math.prod(op.shape) + covered |= width if active is None else active.torch[:, None] & width + cleared = ~covered if call.mask is None else ~covered & call.mask.torch[:, None] + call.observations[slot.buffer].torch[:, slot.columns].masked_fill_(cleared, 0.0) + if stepping and call.transition.final_observations is not None: + final = call.transition.final_observations[slot.buffer].torch[:, slot.columns] + final.masked_fill_(cleared & call.transition.done.torch[:, None], 0.0) + + +def _progress(state: MDPState, tree: TaskTree, path: str, name: str) -> torch.Tensor: + """Return a field of a task's progress in the worlds of its tree.""" + return state.arrays[progress_field(path, name)].torch[tree.worlds.start : tree.worlds.stop] + + +def _update_progress(trees: tuple[TaskTree, ...], state: MDPState) -> None: + """Count the completions of the tasks of every tree, subtasks first, and advance the sequences once.""" + for tree in trees: + length = state.episode_length.torch[tree.worlds.start : tree.worlds.stop] + for node in reversed(tree.nodes): + if node.path not in tree.completes: + continue + field = functools.partial(_progress, state, tree, node.path) + active, done, holding, score = field("active"), field("done"), field("holding"), field("score") + + if node.done is not None: + # Done holds for ``hold`` steps in a row, counted while the task runs and, once done, after it. + condition = state.arrays[node.done].torch[tree.worlds.start : tree.worlds.stop] > 0 + streak, counting = field("streak"), active | done + streak.copy_( + torch.where(counting, torch.where(condition, (streak + 1).clamp(max=node.hold), 0), streak) + ) + holding.copy_(counting & (streak >= node.hold)) + complete = holding + else: + counted = tree.counted(node) + done_children = torch.stack([_progress(state, tree, child.path, "done") for child in counted], 1) + held = torch.stack([_progress(state, tree, child.path, "holding") for child in counted], 1) + finals = torch.ones_like(active) + for k, child in enumerate(counted): + if child.final is not None: + finals &= held[:, k] == child.final + if node.mode is TaskMode.SEQUENCE: + stage = field("stage") + current = done_children.gather(1, stage.long().clamp(max=len(counted) - 1)[:, None])[:, 0] + stage.add_((active & ~done & (stage < len(counted)) & current).int()) + complete = (stage == len(counted)) & finals + holding.copy_(held[:, -1]) + else: + required = node.require or len(counted) + complete = (done_children.sum(1) >= required) & finals + holding.copy_(held.sum(1) >= required) + + started = active & ~done & complete + field("done_at").copy_(torch.where(started, length, field("done_at"))) + done.logical_or_(started) + score.copy_(_score(state, tree, node) if node.done is None else done.float()) + + +def _score(state: MDPState, tree: TaskTree, node) -> torch.Tensor: + """Return a task's score from its subtasks': their weighted mean, or the mean of the best ``require`` of them.""" + counted = tree.counted(node) + scores = torch.stack([_progress(state, tree, child.path, "score") for child in counted], 1) + if node.mode is TaskMode.TOGETHER and node.require is not None: + return scores.topk(node.require, dim=1).values.mean(1) + total = sum(child.score for child in counted) + return sum(scores[:, k] * (child.score / total) for k, child in enumerate(counted)) + + +def _start_tasks(trees: tuple[TaskTree, ...], state: MDPState) -> None: + """Start the tasks of the sequences that advanced, parents first, and stop the tasks they left.""" + for tree in trees: + length = state.episode_length.torch[tree.worlds.start : tree.worlds.stop] + for node in tree.nodes: + if not node.staged: + continue + parent = tree.parent(node) + runs = _progress(state, tree, parent.path, "active").clone() + if parent.mode is TaskMode.SEQUENCE: + # The last task keeps running once it is done. + stage = _progress(state, tree, parent.path, "stage").clamp(max=len(parent.children) - 1) + runs &= stage == parent.children.index(node.path) + active, entered = _progress(state, tree, node.path, "active"), _progress(state, tree, node.path, "entered") + torch.logical_and(runs, ~active, out=entered) + started = _progress(state, tree, node.path, "started_at") + started.copy_(torch.where(entered, length, started)) + active.copy_(runs) + + +def _reset_progress(trees: tuple[TaskTree, ...], state: MDPState, mask: torch.Tensor) -> None: + """Restart the progress of every task in the masked worlds, as at the start of an episode.""" + for tree in trees: + selected = mask[tree.worlds.start : tree.worlds.stop] + for node in tree.nodes: + initial = {"done": False, "holding": False, "done_at": -1, "started_at": 0, "score": 0.0, "stage": 0} + initial |= {"streak": 0, "entered": False, "active": tree.runs_at_start(node)} + for name, value in initial.items(): + key = progress_field(node.path, name) + if key in state.arrays: + state.arrays[key].torch[tree.worlds.start : tree.worlds.stop].masked_fill_(selected, value) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py index 579b73ba0467..90ff800c5aba 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py @@ -14,6 +14,7 @@ from __future__ import annotations +import functools import math from collections.abc import Callable, Hashable, Iterable, Sequence @@ -21,9 +22,19 @@ import warp as wp from .compiled import MDP -from .config import Entity, FieldSelector, Phase, episode_length, last_action, term_state, terminated +from .config import ( + Entity, + FieldSelector, + Phase, + TaskMode, + episode_length, + last_action, + progress_field, + term_state, + terminated, +) from .fusion import Fusion -from .plan import Call, Launches, Step, StepKind, TermOp +from .plan import Call, Launches, ObservationSlot, Step, StepKind, TaskNode, TaskTree, TermOp from .terms import hook_arguments _RESULTS = { @@ -104,6 +115,9 @@ def rows(call: Call, selector: FieldSelector) -> wp.array: for step in mdp.plan.apply_actions: op = step.op + if isinstance(op, TermOp): + _apply_action_term(code, op) + continue target = code.argument(op.target, wp.array2d(dtype=wp.float32), lambda call, op=op: rows(call, op.target)) index = "element" if op.subset is None else f"{_array(code, op.subset, wp.array(dtype=wp.int32))}[element]" offset = code.constant(float, op.offset) @@ -120,6 +134,27 @@ def rows(call: Call, selector: FieldSelector) -> wp.array: return code.steps() +def _apply_action_term(code: Fusion, op: TermOp) -> None: + """Run an action term's compute hook, which writes its outputs from its columns of the action.""" + if isinstance(op.compute, wp.Function): + writes = [*op.writes, *(term_state(op.use, name) for name in op.state)] + code.world(*_under(_active(code, op), _call(code, op, op.compute)), writes=writes) + return + + def run(call: Call) -> None: + # Torch hooks get Torch views, and hooks that launch kernels Warp ones. + views = "torch" if op.torch_hooks else "warp" + active = None if op.active_key is None else call.state.arrays[op.active_key] + arguments = { + **call.state.arguments[op.name], + "action": getattr(call.actions, views)[:, op.columns], + "mask": None if active is None else getattr(active, views), + } + op.compute(**hook_arguments(op.compute, arguments)) + + code.call(run, op.capturable, *_accesses(op)) + + def _evaluate(mdp: MDP) -> tuple[Callable[[Call], None], ...]: code = Fusion("evaluate", mdp.num_worlds, mdp.device) length = _array(code, episode_length, wp.array(dtype=wp.int32)) @@ -176,9 +211,38 @@ def _observe(mdp: MDP) -> tuple[Callable[[Call], None], ...]: def _emit(code: Fusion, mdp: MDP, steps: Iterable[Step], stepping: bool = False) -> None: """Add the statements for the steps of a runtime function. ``stepping`` is true for ``evaluate``.""" for step in steps: + match step.kind: + case StepKind.UPDATE_PROGRESS: + _update_progress(code, step.op) + continue + case StepKind.START_TASKS: + _start_tasks(code, step.op) + continue + case StepKind.RESET_PROGRESS: + _reset_progress(code, step.op) + continue + case StepKind.CLEAR: + _clear(code, mdp, step.op, stepping) + continue op = step.op state = [term_state(op.use, name) for name in op.state] active = _active(code, op) + if step.entry: + # Where the op's task started at this step, instead of the reset worlds. + entered = progress_field(op.stage, "entered") + started = lambda call, entered=entered: call.state.arrays[entered].warp # noqa: E731 + conditions = [f"if {_array(code, entered, wp.array(dtype=wp.bool))}[world]:"] + match step.kind: + case StepKind.RESET_TIMER: + restart = f"{code.function(_restart)}({_timer(code, op)})" + code.world(*_under(conditions, restart), writes=[("timer", op.name)]) + case StepKind.COMPUTE: + _run(code, mdp, op, op.compute, [*op.writes, *state], conditions, mask=started) + case StepKind.RESET_STATE if op.reset is not None: + _run(code, mdp, op, op.reset, state, conditions, mask=started) + case StepKind.RESET_STATE: + _reset_state(code, op, conditions) + continue match step.kind: case StepKind.COMPUTE: _compute(code, mdp, op, active, stepping) @@ -191,14 +255,14 @@ def _emit(code: Fusion, mdp: MDP, steps: Iterable[Step], stepping: bool = False) code.world(*_under(due, f"{ran}[world] = True"), writes=["interval_worlds"]) case StepKind.UPDATE_STATE: # A function hook gets the worlds where the op runs, None for every world. - running = None if op.worlds is None else lambda call, op=op: call.state.arrays["active", op.name].warp + running = None if op.active_key is None else lambda call, op=op: call.state.arrays[op.active_key].warp _run(code, mdp, op, op.update, [*state, *op.writes], active, running) case StepKind.RESET_TIMER: restart = f"{code.function(_restart)}({_timer(code, op)})" code.world(*_under(active, restart), writes=[("timer", op.name)]) case StepKind.RESET_STATE if op.reset is not None: # A function hook gets the reset worlds where the op is active. - mask = _mask if op.worlds is None else lambda call, op=op: _selected(mdp, op, call) + mask = _mask if op.active_key is None else lambda call, op=op: _selected(mdp, op, call) _run(code, mdp, op, op.reset, state, active, mask=mask) case StepKind.RESET_STATE: _reset_state(code, op, active) @@ -222,7 +286,7 @@ def _compute(code: Fusion, mdp: MDP, op: TermOp, conditions: Sequence[str] = (), """Compute an op into its destination, nested under ``conditions``. Stepping advances observation histories.""" state = [term_state(op.use, name) for name in op.state] reset_like = op.phase in (Phase.STARTUP_EVENTS, Phase.RESET_EVENTS) or op.phase is Phase.COMMANDS and not stepping - if op.worlds is not None and reset_like and not isinstance(op.compute, wp.Function): + if op.active_key is not None and reset_like and not isinstance(op.compute, wp.Function): # The hook gets the reset worlds where the op is active. _run(code, mdp, op, op.compute, [*op.writes, *state], mask=lambda call: _selected(mdp, op, call)) return @@ -250,8 +314,12 @@ def _compute(code: Fusion, mdp: MDP, op: TermOp, conditions: Sequence[str] = (), flags.append(f"{done}[world] = True") lines = [f"ended = {_value(code, mdp, op)}", *_under(["if ended:"], *flags)] if mdp.diagnostics: - lines.append(f"{_result(code, 'termination_terms')}[world, {op.index}] = ended") + terms = _result(code, "termination_terms") + lines.append(f"{terms}[world, {op.index}] = ended") writes.append("termination_terms") + if op.stage: + # A task of a sequence that stopped leaves no flag. + code.world(f"{terms}[world, {op.index}] = False", writes=["termination_terms"]) code.world(*_under(conditions, *lines), writes=[*writes, *_computed_state(op)]) case Phase.REWARDS: weights = _array(code, "reward_weights", wp.array2d(dtype=wp.float32)) @@ -260,8 +328,12 @@ def _compute(code: Fusion, mdp: MDP, op: TermOp, conditions: Sequence[str] = (), lines = [f"reward = {scale} * {_value(code, mdp, op)}", f"{rewards}[world] = {rewards}[world] + reward"] writes = ["rewards"] if mdp.diagnostics: - lines.append(f"{_result(code, 'reward_terms')}[world, {op.index}] = reward") + terms = _result(code, "reward_terms") + lines.append(f"{terms}[world, {op.index}] = reward") writes.append("reward_terms") + if op.stage: + # A task of a sequence that stopped leaves no reward. + code.world(f"{terms}[world, {op.index}] = 0.0", writes=["reward_terms"]) code.world(*_under(conditions, *lines), writes=[*writes, *_computed_state(op)]) case Phase.COMMANDS | Phase.INTERVAL_EVENTS if stepping: writes = [*op.writes, *state] @@ -278,9 +350,8 @@ def _compute_observation(code: Fusion, mdp: MDP, op: TermOp, conditions: Sequenc """Compute an observation with its noise, clip, scale, and history into its columns of the group.""" observation = op.observation group, start = observation.group, observation.columns.start - out = code.argument( - ("observations", group), wp.array2d(dtype=wp.float32), lambda call: call.observations[group].warp - ) + dtype = mdp.observation_layouts[group][1] + out = code.argument(("observations", group), wp.array2d(dtype=dtype), lambda call: call.observations[group].warp) value = _value(code, mdp, op) if observation.noise is not None: @@ -301,11 +372,10 @@ def _compute_observation(code: Fusion, mdp: MDP, op: TermOp, conditions: Sequenc if stepping and mdp.final_observations: columns = [f"{start} + element"] if observation.history_length: - size = math.prod(op.shape) - columns = [f"{start} + {h * size} + element" for h in range(observation.history_length)] + columns = [f"{start} + {h * observation.size} + element" for h in range(observation.history_length)] copies = code.argument( ("final_observations", group), - wp.array2d(dtype=wp.float32), + wp.array2d(dtype=dtype), lambda call: call.transition.final_observations[group].warp, ) final = _under( @@ -316,24 +386,34 @@ def _compute_observation(code: Fusion, mdp: MDP, op: TermOp, conditions: Sequenc code.elements(op.shape, *_under(conditions, f"{out}[world, {start} + element] = {value}", *final)) return - # Each thread keeps the history of its element: stepping shifts it and appends the value, observing fills it for - # new episodes. The group holds the history oldest first. + # Each thread keeps the history of its element: stepping shifts it and appends the value, and observing fills it + # for new episodes. An op of a task of a sequence also fills it when stepping, where its task started at this step. + # The group holds the history oldest first, each step in ``size`` columns. history = _array(code, ("history", op.name), wp.array3d(dtype=wp.float32)) - size, last = math.prod(op.shape), observation.history_length - 1 - if stepping: - update = [ - f"for h in range({last}):", - f" {history}[world, h, element] = {history}[world, h + 1, element]", - f"{history}[world, {last}, element] = {value}", - ] + size, last = observation.size, observation.history_length - 1 + fill = [f"for h in range({observation.history_length}):", f" {history}[world, h, element] = value"] + shift = [ + f"for h in range({last}):", + f" {history}[world, h, element] = {history}[world, h + 1, element]", + f"{history}[world, {last}, element] = value", + ] + starts = "0" + if stepping and op.stage is None: + update = [*shift[:-1], f"{history}[world, {last}, element] = {value}"] else: - length = _array(code, episode_length, wp.array(dtype=wp.int32)) - update = [ - f"if {length}[world] == 0:", - " value = " + value, - f" for h in range({observation.history_length}):", - f" {history}[world, h, element] = value", - ] + length = f"{_array(code, episode_length, wp.array(dtype=wp.int32))}[world]" + if op.stage is not None: + starts = f"{_array(code, progress_field(op.stage, 'started_at'), wp.array(dtype=wp.int32))}[world]" + if stepping: + update = [ + "value = " + value, + f"if {length} == {starts}:", + *(f" {line}" for line in fill), + "else:", + *(f" {line}" for line in shift), + ] + else: + update = [f"if {length} == {starts}:", " value = " + value, *(f" {line}" for line in fill)] write = [ f"for h in range({observation.history_length}):", f" {out}[world, {start} + h * {size} + element] = {history}[world, h, element]", @@ -410,11 +490,11 @@ def _own_state(op: TermOp, run: Callable[[Call], None]) -> Callable[[Call], None The ops of different world configs may share the state of their use, as in the Torch backend. """ - if op.worlds is None or not op.state: + if op.active_key is None or not op.state: return run def run_in_own_worlds(call: Call) -> None: - active = call.state.arrays["active", op.name].torch + active = call.state.arrays[op.active_key].torch states = [call.state.arrays[term_state(op.use, name)].torch for name in op.state] states = [values for values in states if values.shape[:1] == active.shape] before = [values.clone() for values in states] @@ -441,6 +521,10 @@ def _call(code: Fusion, op: TermOp, hook: wp.Function, shape: tuple[int, ...] = elif name in op.inputs or name in op.state: key = op.array_key(name) if name in op.inputs else term_state(op.use, name) values.append(_array(code, key, annotation)) + elif name == "action" and op.columns is not None: + # The action's columns, as a strided view of the actions. + columns = op.columns + values.append(code.argument(("action", op.name), annotation, lambda call: call.actions.warp[:, columns])) else: values.append(f"{_rng(code)}[{op.stream}, world]") return f"{code.function(hook)}({', '.join(values)})" @@ -466,17 +550,19 @@ def _writes_scene(op: TermOp) -> bool: def _active(code: Fusion, op: TermOp) -> list[str]: - """Return the condition under which an op's statements run, if it is active in only some worlds.""" - if op.worlds is None: - return [] - active = _array(code, ("active", op.name), wp.array(dtype=wp.bool)) - return [f"if {active}[world]:"] + """Return the condition under which an op's statements run, if it runs in only some worlds or steps.""" + return [] if op.active_key is None else [f"if {_runs(code, op)}:"] + + +def _runs(code: Fusion, op: TermOp) -> str: + """Return source for whether an op runs at the thread's world, for an op that runs in only some worlds or steps.""" + return f"{_array(code, op.active_key, wp.array(dtype=wp.bool))}[world]" def _selected(mdp: MDP, op: TermOp, call: Call) -> wp.array: """Write the reset worlds where an op is active to its selected buffer, and return the buffer.""" selected = call.state.arrays["selected", op.name].warp - inputs = [call.mask.warp, call.state.arrays["active", op.name].warp] + inputs = [call.mask.warp, call.state.arrays[op.active_key].warp] wp.launch(_select, dim=mdp.num_worlds, inputs=inputs, outputs=[selected], device=mdp.device) return selected @@ -495,6 +581,8 @@ def _accesses(op: TermOp, mdp: MDP) -> tuple[set[Hashable], set[Hashable]]: """ state = {term_state(op.use, name) for name in op.state} reads = {*state, ("selected", op.name), *(["rng"] if op.random else [])} + # Hooks of a task of a sequence read where it runs and where it started. + reads |= {op.active_key, progress_field(op.stage, "entered")} if op.stage else set() for arg, selector in op.inputs.items(): if isinstance(selector, Entity): reads.update(FieldSelector(selector.name, field) for field in mdp.schema.entities[selector.name].fields) @@ -532,3 +620,185 @@ def _under(conditions: Sequence[str], *lines: str) -> list[str]: """Indent ``lines`` under ``conditions``, nesting each condition one level deeper than the previous one.""" nested = [f"{' ' * depth}{condition}" for depth, condition in enumerate(conditions)] return nested + [f"{' ' * len(conditions)}{line}" for line in lines] + + +_PROGRESS_TYPES = {"done": wp.bool, "holding": wp.bool, "active": wp.bool, "entered": wp.bool, "score": wp.float32} +"""Element types of the progress fields other than the ``int32`` ones.""" + + +def _progress(code: Fusion, path: str, name: str) -> str: + """Return source for a field of a task's progress at the thread's world.""" + key = progress_field(path, name) + return f"{_array(code, key, wp.array(dtype=_PROGRESS_TYPES.get(name, wp.int32)))}[world]" + + +def _in_tree(trees: tuple[TaskTree, ...], tree: TaskTree) -> list[str]: + """Return the condition for the worlds of a tree's world config, if there are several.""" + return [] if len(trees) == 1 else [f"if world >= {tree.worlds.start} and world < {tree.worlds.stop}:"] + + +def _tree_writes(tree: TaskTree, names: Iterable[str]) -> list[FieldSelector]: + """Return the keys of the progress fields of a tree that a statement may write.""" + return [progress_field(node.path, name) for node in tree.nodes for name in names] + + +def _update_progress(code: Fusion, trees: tuple[TaskTree, ...]) -> None: + """Count the completions of the tasks of every tree, subtasks first, and advance the sequences once.""" + length = f"{_array(code, episode_length, wp.array(dtype=wp.int32))}[world]" + for tree in trees: + lines = [] + for node in reversed(tree.nodes): + if node.path in tree.completes: + lines += _node_progress(code, tree, node, length) + names = ("done", "holding", "score", "done_at", "streak", "stage") + if lines: + code.world(*_under(_in_tree(trees, tree), *lines), writes=_tree_writes(tree, names)) + + +def _node_progress(code: Fusion, tree: TaskTree, node: TaskNode, length: str) -> list[str]: + """Return the statements that update the progress of one task, after those of its subtasks.""" + field = functools.partial(_progress, code, node.path) + active, done, holding, score = field("active"), field("done"), field("holding"), field("score") + + if node.done is not None: + # Done holds for ``hold`` steps in a row, counted while the task runs and, once done, after it. + condition = f"{_array(code, node.done, wp.array(dtype=node.done_dtype))}[world]" + positive = {wp.bool: "", wp.float32: " > 0.0", wp.int32: " > 0"}[node.done_dtype] + streak = field("streak") + lines = [ + f"if {active} or {done}:", + f" if {condition}{positive}:", + f" {streak} = wp.min({streak} + 1, {node.hold})", + " else:", + f" {streak} = 0", + f"{holding} = ({active} or {done}) and {streak} >= {node.hold}", + f"complete = {holding}", + ] + else: + counted = tree.counted(node) + children = [functools.partial(_progress, code, child.path) for child in counted] + finals = [f"{child('holding')} == {child_node.final}" for child, child_node in zip(children, counted)] + finals = [final for final, child_node in zip(finals, counted) if child_node.final is not None] + finals = " and ".join(finals) or "True" + if node.mode is TaskMode.SEQUENCE: + # One subtask at most per step: the next one starts at the step after. + stage = field("stage") + lines = [f"if {active} and not {done}:"] + for k, child in enumerate(children): + lines += [ + f" {'if' if k == 0 else 'elif'} {stage} == {k} and {child('done')}:", + f" {stage} = {k + 1}", + ] + lines += [ + f"complete = {stage} == {len(counted)} and ({finals})", + f"{holding} = {children[-1]('holding')}", + ] + else: + required = node.require or len(counted) + lines = [ + "count = int(0)", + "held = int(0)", + *(f"count = count + wp.where({child('done')}, 1, 0)" for child in children), + *(f"held = held + wp.where({child('holding')}, 1, 0)" for child in children), + f"complete = count >= {required} and ({finals})", + f"{holding} = held >= {required}", + ] + + lines += [ + f"if {active} and not {done} and complete:", + f" {done} = True", + f" {field('done_at')} = {length}", + ] + if node.done is not None: + return [*lines, f"{score} = wp.where({done}, 1.0, 0.0)"] + + counted = tree.counted(node) + scores = [_progress(code, child.path, "score") for child in counted] + if node.mode is TaskMode.TOGETHER and node.require is not None: + # The mean of the best ``require`` scores, picked one at a time. + lines += ["taken = int(0)", "total = float(0.0)"] + for _ in range(node.require): + lines += ["best = float(-1.0)", "pick = int(0)"] + for k, child_score in enumerate(scores): + lines += [ + f"if (taken & {1 << k}) == 0 and {child_score} > best:", + f" best = {child_score}", + f" pick = {1 << k}", + ] + lines += ["taken = taken | pick", "total = total + best"] + return [*lines, f"{score} = total / {float(node.require)}"] + weights = [child.score / sum(child.score for child in counted) for child in counted] + return [*lines, f"{score} = " + " + ".join(f"{weight!r} * {child}" for weight, child in zip(weights, scores))] + + +def _start_tasks(code: Fusion, trees: tuple[TaskTree, ...]) -> None: + """Start the tasks of the sequences that advanced, parents first, and stop the tasks they left.""" + length = f"{_array(code, episode_length, wp.array(dtype=wp.int32))}[world]" + for tree in trees: + lines = [] + for node in tree.nodes: + if not node.staged: + continue + parent = tree.parent(node) + runs = _progress(code, parent.path, "active") + if parent.mode is TaskMode.SEQUENCE: + # The last task keeps running once it is done. + stage = f"wp.min({_progress(code, parent.path, 'stage')}, {len(parent.children) - 1})" + runs = f"{runs} and {stage} == {parent.children.index(node.path)}" + field = functools.partial(_progress, code, node.path) + lines += [ + f"runs = {runs}", + f"{field('entered')} = runs and not {field('active')}", + f"if {field('entered')}:", + f" {field('started_at')} = {length}", + f"{field('active')} = runs", + ] + if lines: + writes = _tree_writes(tree, ("entered", "started_at", "active")) + code.world(*_under(_in_tree(trees, tree), *lines), writes=writes) + + +def _reset_progress(code: Fusion, trees: tuple[TaskTree, ...]) -> None: + """Restart the progress of every task in the masked worlds, as at the start of an episode.""" + for tree in trees: + lines = [] + for node in tree.nodes: + field = functools.partial(_progress, code, node.path) + lines += [ + f"{field('done')} = False", + f"{field('holding')} = False", + f"{field('done_at')} = -1", + f"{field('started_at')} = 0", + f"{field('score')} = 0.0", + f"{field('active')} = {tree.runs_at_start(node)}", + *([f"{field('stage')} = 0"] if node.mode is TaskMode.SEQUENCE else []), + *([f"{field('streak')} = 0"] if node.done is not None else []), + *([f"{field('entered')} = False"] if node.staged else []), + ] + names = ("done", "holding", "done_at", "started_at", "score", "active", "stage", "streak", "entered") + code.world(*_under(_in_tree(trees, tree), *lines), writes=_tree_writes(tree, names)) + + +def _clear(code: Fusion, mdp: MDP, slot: ObservationSlot, stepping: bool) -> None: + """Zero the columns of a slot that no op writes at this step. + + A column is written by the op that runs and is that wide, so the threads of different ops never write the same + column of a world. + """ + dtype = mdp.observation_layouts[slot.buffer][1] + group = slot.buffer + out = code.argument(("observations", group), wp.array2d(dtype=dtype), lambda call: call.observations[group].warp) + covers = [] + for op in slot.ops: + width = f"element % {slot.size} < {math.prod(op.shape)}" + covers.append(width if op.active_key is None else f"({_runs(code, op)} and {width})") + column, zero = f"{slot.columns.start} + element", f"wp.{dtype.__name__}(0)" + lines = [f"if not ({' or '.join(covers)}):", f" {out}[world, {column}] = {zero}"] + if stepping and mdp.final_observations: + copies = code.argument( + ("final_observations", group), + wp.array2d(dtype=dtype), + lambda call: call.transition.final_observations[group].warp, + ) + lines += [f" if {_result(code, 'done')}[world]:", f" {copies}[world, {column}] = {zero}"] + code.elements((slot.columns.stop - slot.columns.start,), *lines) diff --git a/source/isaaclab_experimental/test/envs/test_mdp2_env.py b/source/isaaclab_experimental/test/envs/test_mdp2_env.py index d09920018dc6..f14b5135a862 100644 --- a/source/isaaclab_experimental/test/envs/test_mdp2_env.py +++ b/source/isaaclab_experimental/test/envs/test_mdp2_env.py @@ -5,6 +5,7 @@ """Tests for MDP2RLEnv on a headless Newton Cartpole, built from a local USD file.""" +import importlib.util import math import weakref from dataclasses import replace @@ -17,12 +18,15 @@ from isaaclab_experimental import mdp2 from isaaclab_experimental.envs import MDP2RLEnv, MDP2RLEnvCfg, ResetStep, Stage, Step, mdp2_env, mdp2_scene_data from isaaclab_experimental.mdp2 import mdp, rng +from isaaclab_experimental.mdp2.config import group_terms from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg +from isaaclab_newton.renderers import NewtonOptixRendererCfg, NewtonWarpRendererCfg import isaaclab.sim as sim_utils from isaaclab.actuators import DelayedPDActuatorCfg, ImplicitActuatorCfg -from isaaclab.assets import ArticulationCfg +from isaaclab.assets import ArticulationCfg, RigidObjectCfg from isaaclab.scene import InteractiveSceneCfg +from isaaclab.sensors import CameraCfg from isaaclab.sim import SimulationCfg, SimulationContext pytestmark = [pytest.mark.kitless, pytest.mark.skipif(not torch.cuda.is_available(), reason="Newton needs a GPU")] @@ -373,8 +377,8 @@ def test_env_splits_the_worlds_between_tasks_and_logs_terms_where_they_run(task_ "steps": observation, } without_alive = replace(cfg.task, rewards={**cfg.task.rewards, "alive": None}) - cfg.task = [cfg.task, without_alive] - cfg.task_worlds = task_worlds + worlds = None if task_worlds is None else dict(zip(("alive", "still"), task_worlds)) + cfg.task = mdp2.split(alive=cfg.task, still=without_alive, worlds=worlds) env = MDP2RLEnv(cfg) try: # Even shares, or the given number of worlds per task. @@ -539,6 +543,38 @@ def test_built_in_steps_must_run_once_in_order(): MDP2RLEnv(cfg) +after_steps = mdp2.Term(torch=lambda episode_length, *, steps: (episode_length >= steps).float()) +"""One from the step ``steps`` of the episode on.""" + + +def test_env_runs_the_tasks_of_a_sequence_in_turn_and_logs_their_progress(): + """A sequence of two tasks, each with its own quantity and reward, steps the same captured and uncaptured, and + the environment logs how often each task was done in the last episodes.""" + + def stage(steps: int) -> mdp2.TaskCfg: + ready = mdp2.Quantity(after_steps, inputs={"episode_length": mdp2.episode_length}, params={"steps": steps}) + bonus = mdp2.Reward(mdp.is_alive, inputs={"terminated": mdp2.terminated}) + return mdp2.TaskCfg(quantities={"ready": ready}, rewards={"bonus": bonus}, done=mdp2.quantities.ready) + + cfg = cartpole_cfg() + cfg.task.terminations["cart_out_of_bounds"] = None + cfg.task = mdp2.compose(cfg.task, mdp2.sequence(warm=stage(3), hold=stage(6))) + cfg.verify_capture = 10 + env = MDP2RLEnv(cfg) + try: + env.reset() + for _ in range(env.max_episode_length): + _, _, _, _, extras = env.step(torch.zeros(NUM_ENVS, 1, device=env.device)) + log = extras["log"] + assert log["Progress/warm"] == 1.0 and log["Progress/hold"] == 1.0 and log["Progress/task"] == 1.0 + # The bonus of each task, per second of the episode: warm ran 3 steps, hold the others. + steps = env.max_episode_length + assert log["Episode_Reward/warm.bonus"].item() == pytest.approx(3 / steps) + assert log["Episode_Reward/hold.bonus"].item() == pytest.approx((steps - 3) / steps) + finally: + env.close() + + def test_verify_capture_finds_python_state_that_the_graph_freezes(): """The debug check passes a task whose captured steps are exact, and names a stage whose Python-side state the graph froze at capture.""" @@ -633,3 +669,137 @@ def test_stages_that_write_the_scene_are_seen_by_later_work(): assert env.is_captured and restarted > 0 finally: env.close() + + +def test_cameras_render_in_the_captured_step_and_the_budget_records_episodes(): + """Camera images are observed as uint8 terms and rendered by every replayed step, also with two cameras, and an + episode budget records each episode, then stops the worlds.""" + cfg = cartpole_cfg() + # The Cartpole has no geometry to render, so the camera watches a cube fall in front of it. + cfg.scene.cube = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/Cube", + spawn=sim_utils.CuboidCfg( + size=(0.2, 0.2, 0.2), rigid_props=sim_utils.UsdPhysicsRigidBodyCfg(), mass_props=sim_utils.MassCfg(mass=1.0) + ), + init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, 0.0, 1.2)), + ) + cfg.scene.camera = CameraCfg( + prim_path="{ENV_REGEX_NS}/Camera", + offset=CameraCfg.OffsetCfg(pos=(0.0, -1.0, 1.0), rot=(0.0, 0.0, 0.7071, 0.7071), convention="world"), + data_types=["rgb"], + width=96, + height=64, + spawn=sim_utils.PinholeCameraCfg(focal_length=2.0, horizontal_aperture=2.0, clipping_range=(0.01, 20.0)), + renderer_cfg=NewtonWarpRendererCfg(), + ) + # A second camera, watching from the other side; cameras share their renderer. + cfg.scene.camera_back = cfg.scene.camera.replace( + prim_path="{ENV_REGEX_NS}/CameraBack", + offset=CameraCfg.OffsetCfg(pos=(0.0, 1.0, 1.0), rot=(0.0, 0.0, -0.7071, 0.7071), convention="world"), + ) + cfg.task.observations["cameras"] = mdp2.ObservationGroup( + terms={ + name: mdp2.Observation(mdp.image_rgb, inputs={"image": mdp2.Entity(camera).rgb}) + for name, camera in (("rgb", "camera"), ("rgb_back", "camera_back")) + }, + concatenate=False, + ) + # Indexing with a 1-dimensional tensor, as a 0-dimensional one would be read on the host in the graph. + cart_x = mdp2.Term(torch=lambda joint_pos, joint_ids: joint_pos[:, joint_ids][:, 0]) + cfg.task.quantities["cart_x"] = mdp2.Quantity( + cart_x, inputs={"joint_pos": robot.joint_pos, "joint_ids": cart}, record=True + ) + # Cameras that never render would observe stale images. + cfg.step = [Step.PHYSICS, Step.EVALUATE, Step.RESET] + with pytest.raises(ValueError, match="must hold Step.RENDER"): + MDP2RLEnv(cfg) + cfg.step = [Step.PHYSICS, Step.RENDER, Step.EVALUATE, Step.RESET] + budget = NUM_ENVS + 4 + cfg.episode_budget = budget + env = MDP2RLEnv(cfg) + try: + assert env.single_observation_space["cameras"]["rgb"].shape == (64, 96, 3) + observations, _ = env.reset() + assert observations["cameras"]["rgb"].shape == (NUM_ENVS, 64, 96, 3) + assert observations["cameras"]["rgb"].dtype == torch.uint8 + images = [] + for step in range(13): + observations, *_ = env.step(torch.zeros(NUM_ENVS, 1, device=env.device)) + if step >= 9: + images.append({name: image.clone() for name, image in observations["cameras"].items()}) + assert env.is_captured and env.num_graphs == 1 + for name in ("rgb", "rgb_back"): + # The cube falls by pixels per step by then, so every replayed step renders a new image. + assert all(not torch.equal(before[name], after[name]) for before, after in zip(images, images[1:])) + # Lit: a stale render graph draws the geometry black. + assert images[-1][name].amax(dim=-1).min() > 0 + + # Push every cart out of its bounds until the budget is spent. + ended = [] + while env.episodes_completed < budget: + _, _, terminated, truncated, _ = env.step(torch.ones(NUM_ENVS, 1, device=env.device)) + ended.append(int((terminated | truncated).sum())) + records = env.episode_records() + assert sum(ended) == budget and len(records["world"]) == budget + # Every world ran an episode, the first worlds to end a second one, and none ended a third. + episodes = torch.bincount(records["world"].long(), minlength=NUM_ENVS) + assert episodes.min() == 1 and episodes.sum() == budget + assert records["termination/cart_out_of_bounds"].sum() + records["truncated"].sum() == budget + # Recorded values are those of the episode's last step, before its reset: out of bounds where it terminated. + out_of_bounds = records["cart_x"].abs() > 1.5 + assert torch.equal(out_of_bounds, records["terminated"].bool()) + for _ in range(env.max_episode_length): + _, _, terminated, truncated, _ = env.step(torch.ones(NUM_ENVS, 1, device=env.device)) + assert not (terminated | truncated).any() + assert env.episodes_completed == budget + finally: + env.close() + + +def test_play_mode_removes_observation_noise_and_keeps_each_group(): + """Play mode drops observation noise, in concatenated groups and in groups of a tensor per term alike.""" + cfg = cartpole_cfg() + noisy = mdp2.Observation(mdp.joint_pos, inputs={"joint_pos": robot.joint_pos}, noise=mdp2.UniformNoise(-0.1, 0.1)) + cfg.task.observations["separate"] = mdp2.ObservationGroup(terms={"joint_pos": noisy}, concatenate=False) + cfg.play_mode() + for group, concatenate in (("policy", True), ("separate", False)): + terms, concatenated = group_terms(cfg.task.observations[group]) + assert concatenated is concatenate + assert all(use.noise is None for use in terms.values() if use is not None) + + +@pytest.mark.skipif(importlib.util.find_spec("optix") is None, reason="needs the optix extra") +def test_optix_cameras_render_between_the_graphs_of_a_step(): + """OptiX refits its acceleration structures on the host, so its cameras render between two graphs, and every + replayed step still renders a new image.""" + cfg = cartpole_cfg() + cfg.scene.cube = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/Cube", + spawn=sim_utils.CuboidCfg( + size=(0.2, 0.2, 0.2), rigid_props=sim_utils.UsdPhysicsRigidBodyCfg(), mass_props=sim_utils.MassCfg(mass=1.0) + ), + init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, 0.0, 1.2)), + ) + cfg.scene.camera = CameraCfg( + prim_path="{ENV_REGEX_NS}/Camera", + offset=CameraCfg.OffsetCfg(pos=(0.0, -1.0, 1.0), rot=(0.0, 0.0, 0.7071, 0.7071), convention="world"), + data_types=["rgb"], + width=96, + height=64, + spawn=sim_utils.PinholeCameraCfg(focal_length=2.0, horizontal_aperture=2.0, clipping_range=(0.01, 20.0)), + renderer_cfg=NewtonOptixRendererCfg(), + ) + image = mdp2.Observation(mdp.image_rgb, inputs={"image": mdp2.Entity("camera").rgb}) + cfg.task.observations["cameras"] = mdp2.ObservationGroup(terms={"rgb": image}, concatenate=False) + env = MDP2RLEnv(cfg) + try: + env.reset() + images = [] + for step in range(10): + observations, *_ = env.step(torch.zeros(NUM_ENVS, 1, device=env.device)) + if step >= 6: + images.append(observations["cameras"]["rgb"].clone()) + assert env.is_captured and env.num_graphs == 2 + assert all(not torch.equal(before, after) for before, after in zip(images, images[1:])) + finally: + env.close() diff --git a/source/isaaclab_experimental/test/mdp2/test_mdp2.py b/source/isaaclab_experimental/test/mdp2/test_mdp2.py index a84b8a0d7b73..ed7661b55c6e 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2.py @@ -1010,17 +1010,20 @@ def test_world_configs_with_fewer_actions_read_their_own_actions(): scene.step() mdp2.evaluate(mdp, state, transition) + # Observations of the same name share columns, as wide as the widest, in the order they first appear: + # last_action (0-1), action_l2 (2), action_rate_l2 (3), eager_l2 (4), narrow_rate (5). policy = transition.observations["policy"].torch torch.testing.assert_close(policy[:2, :2], steps[1][:2]) torch.testing.assert_close(policy[:2, 2], steps[1][:2].square().sum(-1)) torch.testing.assert_close(policy[:2, 3], (steps[1][:2] - steps[0][:2]).square().sum(-1)) - # The second column of the actions pads the narrow config: its terms ignore it. + # The second column of the actions pads the narrow config: its terms ignore it, and its columns stay zero. torch.testing.assert_close(policy[2:, 0], steps[1][2:, 0]) - torch.testing.assert_close(policy[2:, 1], steps[1][2:, 0].square()) - torch.testing.assert_close(policy[2:, 2], (steps[1][2:, 0] - steps[0][2:, 0]).square()) + assert (policy[2:, 1] == 0.0).all() and (policy[2:, 3] == 0.0).all() and (policy[:2, 5] == 0.0).all() + torch.testing.assert_close(policy[2:, 2], steps[1][2:, 0].square()) + torch.testing.assert_close(policy[2:, 5], (steps[1][2:, 0] - steps[0][2:, 0]).square()) # Eager terms too. torch.testing.assert_close(policy[:2, 4], steps[1][:2].square().sum(-1)) - torch.testing.assert_close(policy[2:, 3], steps[1][2:, 0].square()) + torch.testing.assert_close(policy[2:, 4], steps[1][2:, 0].square()) def test_library_action_and_termination_terms(): @@ -1550,3 +1553,368 @@ def test_entity_outputs_write_every_writable_field_of_the_entity(): builder.add_event("fused", mdp2.Event(push_by_adding_velocity, inputs={"robot": robot})) with pytest.raises(ValueError, match="wp.func hooks cannot take scene entities"): builder.validate(backend="warp") + + +@pytest.mark.parametrize("close_above", [True, False]) +def test_action_terms_take_their_columns_after_direct_actions(close_above: bool): + """An action term takes the next columns of the action and writes its outputs, here a binary command that closes + on either side of its threshold.""" + for backend in ("torch", "warp"): + scene = PointMassScene(num_worlds=2, joint_names=("x", "y"), device=DEVICE) + builder = mdp2.MDPBuilder(scene.schema) + builder.add_action("x", mdp2.DirectAction(robot.joint_effort_target, subset=robot.joints("x"), scale=2.0)) + gripper = mdp2.Action( + mdp2.mdp.binary_joint_position, + inputs={"joint_ids": robot.joints("y")}, + outputs={"joint_pos_target": robot.joint_effort_target}, + params={"open_position": -1.0, "close_position": 1.0, "threshold": 0.5, "close_above": close_above}, + ) + builder.add_action("y", gripper) + mdp = builder.finalize(device=DEVICE, backend=backend) + state = mdp.state(scene) + + actions = torch.tensor([[0.5, 0.9], [-1.0, 0.2]], device=DEVICE) + mdp2.apply_actions(mdp, state, ProxyArray(wp.from_torch(actions))) + assert mdp.action_dim == 2 + gripper_targets = [1.0, -1.0] if close_above else [-1.0, 1.0] + assert scene.data("robot", "joint_effort_target").torch.tolist() == [ + [1.0, gripper_targets[0]], + [-2.0, gripper_targets[1]], + ] + torch.testing.assert_close(state.actions.torch, actions) + + +def image_scene(num_worlds: int) -> PointMassScene: + """A point-mass scene with a ``camera`` entity whose ``rgb`` field is a 2x3 image with 3 channels.""" + scene = PointMassScene(num_worlds=num_worlds, device=DEVICE) + names = {"height": ("0", "1"), "width": ("0", "1", "2"), "rgb_channels": ("0", "1", "2")} + rgb = mdp2.FieldSchema(("height", "width", "rgb_channels"), wp.uint8) + camera = mdp2.EntitySchema(names=names, fields={"rgb": rgb}) + scene.schema = dataclasses.replace(scene.schema, entities={**scene.schema.entities, "camera": camera}) + images = torch.arange(num_worlds * 18, device=DEVICE).reshape(num_worlds, 2, 3, 3).to(torch.uint8) + scene._data["camera"] = {"rgb": ProxyArray(wp.from_torch(images, dtype=wp.uint8))} + return scene + + +def test_groups_that_are_not_concatenated_keep_each_term_shape_and_type(): + """A group that is not concatenated gives each term its own buffer, of the term's shape and element type.""" + camera = mdp2.Entity("camera") + for backend in ("torch", "warp"): + scene = image_scene(num_worlds=2) + task = mdp2.TaskCfg( + observations={ + "policy": {"joint_pos": mdp2.Observation(joint_pos, inputs={"joint_pos": robot.joint_pos})}, + "cameras": mdp2.ObservationGroup( + terms={ + "rgb": mdp2.Observation(mdp2.mdp.image_rgb, inputs={"image": camera.rgb}), + "joint_pos": mdp2.Observation(joint_pos, inputs={"joint_pos": robot.joint_pos}), + }, + concatenate=False, + ), + } + ) + builder = mdp2.MDPBuilder(scene.schema) + builder.add_task(task) + mdp = builder.finalize(device=DEVICE, backend=backend) + state, transition = mdp.state(scene), mdp.transition() + scene.data("robot", "joint_pos").torch.copy_(torch.tensor([[1.0], [2.0]])) + mdp2.evaluate(mdp, state, transition) + + assert dict(mdp.observation_layouts) == { + "policy": ((1,), wp.float32), + "cameras/rgb": ((2, 3, 3), wp.uint8), + "cameras/joint_pos": ((1,), wp.float32), + } + rgb = transition.observations["cameras/rgb"].torch + assert rgb.dtype == torch.uint8 + assert torch.equal(rgb.view(2, 2, 3, 3), scene.data("camera", "rgb").torch) + assert transition.observations["cameras/joint_pos"].torch.tolist() == [[1.0], [2.0]] + + # Other types need their own buffer, without processing. + builder = mdp2.MDPBuilder(image_scene(num_worlds=1).schema) + builder.add_observation("policy", "rgb", mdp2.Observation(mdp2.mdp.image_rgb, inputs={"image": camera.rgb})) + scaled = mdp2.Observation(mdp2.mdp.image_rgb, inputs={"image": camera.rgb}, scale=2.0) + builder.add_observation("cameras", "scaled", scaled, concatenate=False) + with pytest.raises(ValueError) as error: + builder.validate() + for name in ("policy.rgb", "cameras.scaled"): + assert f"observations.{name}: an observation of type uint8 must be in a group with concatenate=False" in str( + error.value + ) + + +def test_compose_merges_tasks_in_order(): + """Composed tasks merge term by term in the order of the parts, a later part removes a use by setting it to None, + and two parts that define the same use conflict.""" + event = mdp2.Event(push_by_adding_velocity, outputs={"joint_vel": robot.joint_vel}) + observation = mdp2.Observation(joint_pos, inputs={"joint_pos": robot.joint_pos}) + scene_part = mdp2.TaskCfg(events={"place": event}, observations={"policy": {"a": observation}}) + embodiment = mdp2.TaskCfg(events={"reset_arm": event, "hold": event}, observations={"policy": {"b": observation}}) + task_part = mdp2.TaskCfg(events={"hold": None, "settle": event}) + task = mdp2.compose(scene_part, embodiment, task_part) + assert list(task.observations["policy"].terms) == ["a", "b"] and task.events["hold"] is None + + builder = mdp2.MDPBuilder(PointMassScene(num_worlds=1).schema) + builder.add_task(task) + events = [entry.path[1] for entry in builder.schedule() if entry.path[0] == "events"] + assert events == ["place", "reset_arm", "settle"] + + with pytest.raises(ValueError, match="Tasks 0 and 1 both define 'observations.policy.a'"): + mdp2.compose(scene_part, scene_part) + + +@wp.func +def joint_above_warp(world: int, joint_pos: wp.array2d(dtype=float), joint_ids: wp.array(dtype=wp.int32)) -> float: + return wp.where(joint_pos[world, joint_ids[0]] > 0.5, 1.0, 0.0) + + +joint_above = mdp2.Term( + torch=lambda joint_pos, joint_ids: (joint_pos[:, joint_ids][:, 0] > 0.5).float(), warp=joint_above_warp +) + + +def above(*joints: str) -> dict[str, mdp2.Quantity]: + """Quantities, one per joint, that are one where the joint is above 0.5.""" + return { + joint: mdp2.Quantity(joint_above, inputs={"joint_pos": robot.joint_pos, "joint_ids": robot.joints(joint)}) + for joint in joints + } + + +def run_progress( + task: mdp2.TaskCfg, joint_values: list, backend: str, capture: bool, num_worlds: int = 1, joints: tuple = () +): + """Run a task whose joints, named after its quantities unless given, are set at every step, and return per step + the fields of every task's progress by name, every other field of the MDP, such as term state, by selector, and + the rewards, terminations, per-term rewards, and observations.""" + joint_names = joints or tuple(task.quantities) + scene = PointMassScene(num_worlds=num_worlds, joint_names=joint_names, device=DEVICE) + builder = mdp2.MDPBuilder(scene.schema) + builder.add_task(task) + mdp = builder.finalize(device=DEVICE, backend=backend, diagnostics=True) + state, transition = mdp.state(scene), mdp.transition() + actions = ProxyArray(wp.zeros((num_worlds, max(mdp.action_dim, 1)), dtype=wp.float32, device=DEVICE)) + captured = mdp2.CapturedMDP(mdp, state, transition, actions, transition.done) if capture else None + env_reset(mdp, state, scene, transition.observations, torch.ones(num_worlds, dtype=torch.bool, device=DEVICE)) + + joints = scene.data("robot", "joint_pos").torch + fields = [key for key in state.arrays if isinstance(key, mdp2.FieldSelector) and not key.scene] + history = [] + for values in joint_values: + joints.copy_(torch.tensor(values, device=DEVICE).expand_as(joints)) + if captured is None: + mdp2.evaluate(mdp, state, transition) + else: + captured.evaluate() + step = {key.field if key.entity == "progress" else str(key): state.arrays[key].torch.clone() for key in fields} + step["rewards"] = transition.rewards.torch.clone() + step["reward_terms"] = transition.reward_terms.torch.clone() + step["terminated"] = transition.terminated.torch.clone() + step |= {group: values.torch.clone() for group, values in transition.observations.items()} + history.append(step) + return mdp, state, history + + +def check_progress(task: mdp2.TaskCfg, joint_values: list, joints: tuple = ()) -> list[dict[str, torch.Tensor]]: + """Run a task on both backends, eagerly and captured, check that the four runs agree bitwise, and return one.""" + runs = [] + for backend in ("torch", "warp"): + for capture in (False, True) if torch.cuda.is_available() else (False,): + runs.append(run_progress(task, joint_values, backend, capture, joints=joints)[2]) + for run in runs[1:]: + for expected, actual in zip(runs[0], run): + for name, value in expected.items(): + assert torch.equal(value, actual[name]), name + return runs[0] + + +def test_milestones_count_their_hold_from_the_step_after_the_previous_one(): + """Lift, then upright for 10 steps: the hold starts the step after the lift, and a break restarts it.""" + lift_and_hold = mdp2.compose( + mdp2.TaskCfg(quantities=above("lifted", "upright")), + mdp2.sequence( + lifted=mdp2.Milestone(mdp2.quantities.lifted), + upright=mdp2.Milestone(mdp2.quantities.upright, hold=10), + ), + ) + # Upright from the start; lifted from step 5 (episode steps count from 1). + steps = [[0.0, 1.0]] * 4 + [[1.0, 1.0]] * 16 + history = check_progress(lift_and_hold, steps) + done = [int(step["done"].item()) for step in history] + assert done.index(1) == 14 # Step 15: 10 upright steps after the lift at step 5 + assert history[-1]["lifted.done_at"].item() == 5 and history[-1]["done_at"].item() == 15 + assert history[5]["upright.started_at"].item() == 5 and history[4]["stage"].item() == 1 + + # Tipping over at step 10 restarts the count. + steps = [[0.0, 1.0]] * 4 + [[1.0, 1.0]] * 5 + [[1.0, 0.0]] + [[1.0, 1.0]] * 12 + history = check_progress(lift_and_hold, steps) + assert [int(step["done"].item()) for step in history].index(1) == 19 + + +def test_sequence_rechecks_the_final_completion_of_its_subtasks(): + """Put in, then close: the second subtask starts the step after the first, even if already satisfied, and the + task is done only while both still hold; reopening keeps the recorded completion of the first.""" + task = mdp2.compose( + mdp2.TaskCfg(quantities=above("inside", "closed")), + mdp2.sequence( + put=mdp2.Milestone(mdp2.quantities.inside, hold=2, final=True), + close=mdp2.Milestone(mdp2.quantities.closed, final=True), + ), + ) + # Closed from the start, inside from step 3: put is done at step 4, close at step 5, and so the task. + history = check_progress(task, [[0.0, 1.0]] * 2 + [[1.0, 1.0]] * 4) + final = history[-1] + assert (final["put.done_at"].item(), final["close.done_at"].item(), final["done_at"].item()) == (4, 5, 5) + + # Taken out again at step 5: close is done, but the task is not, since put no longer holds. + history = check_progress(task, [[0.0, 1.0]] * 2 + [[1.0, 1.0]] * 2 + [[0.0, 1.0]] * 3) + final = history[-1] + assert final["put.done_at"].item() == 4 and final["close.done"].item() and not final["done"].item() + + +def test_together_requires_some_subtasks_and_scores_the_best(): + """Two of three subtasks: done once two are, scored by the mean of the best two, each a weighted sequence.""" + + def sort(joint: str) -> mdp2.TaskCfg: + return mdp2.sequence( + grasped=mdp2.Milestone(getattr(mdp2.quantities, joint), score=0.25), + binned=mdp2.Milestone(getattr(mdp2.quantities, joint), score=0.75), + ) + + task = mdp2.compose( + mdp2.TaskCfg(quantities=above("red", "blue", "green")), + red=sort("red"), + blue=sort("blue"), + green=sort("green"), + require=2, + ) + history = check_progress(task, [[1.0, 0.0, 0.0]] * 2 + [[1.0, 1.0, 0.0]]) + assert history[0]["red.score"].item() == 0.25 and history[0]["score"].item() == 0.125 + assert history[1]["red.done"].item() and not history[1]["done"].item() + assert history[2]["score"].item() == 0.625 and not history[2]["done"].item() + + +def test_tasks_of_a_sequence_run_their_uses_in_turn(): + """Rewards follow the subtask that ran when the step started, and observations of the same name share their + columns, written by the subtask that runs, with a history that restarts with it. Terms read the progress.""" + + def stage(joint: str, reward: float) -> mdp2.TaskCfg: + position = mdp2.Observation( + joint_pos_subset, + inputs={"joint_pos": robot.joint_pos, "joint_ids": robot.joints(joint)}, + history_length=2, + ) + return mdp2.TaskCfg( + rewards={"alive": mdp2.Reward(is_alive, inputs={"joint_pos": robot.joint_pos}, weight=reward)}, + observations={"policy": {"position": position}}, + done=getattr(mdp2.quantities, joint), + ) + + stage_index = mdp2.Observation(mdp2.mdp.one_hot, inputs={"value": mdp2.progress.stage}, params={"size": 2}) + task = mdp2.compose( + mdp2.TaskCfg( + quantities=above("reach", "lift"), + observations={"policy": {"stage": stage_index}}, + terminations={"success": mdp2.Termination(mdp2.mdp.is_true, inputs={"value": mdp2.progress.done})}, + ), + mdp2.sequence(reach=stage("reach", 1.0), lift=stage("lift", 2.0)), + ) + history = check_progress(task, [[0.0, 0.25], [1.0, 0.25], [1.0, 0.75]]) + assert [step["terminated"].item() for step in history] == [False, False, True] + step_dt = 0.02 + rewards = [round(step["rewards"].item() / step_dt, 6) for step in history] + assert rewards == [1.0, 1.0, 2.0] # Reach until its step 2 is done, lift from step 3 + # The stage (columns 0-1), then the position of the subtask that runs, with its history (columns 2-3). + policy = [step["policy"][0].tolist() for step in history] + assert policy[0] == [1.0, 0.0, 0.0, 0.0] + assert policy[1] == [0.0, 1.0, 0.25, 0.25] # Lift's position, its history filled at its start + assert policy[2] == [0.0, 0.0, 0.25, 0.75] # The last subtask keeps running once the sequence is done + + mdp, state, _ = run_progress(task, [[0.0, 0.25]], "warp", capture=False) + position = mdp.spec()["policy"][1] + assert (position.name, position.columns, position.history_length) == ("position", slice(2, 4), 2) + assert mdp.observation_mask(state, "policy").tolist() == [[True] * 4] + assert "during reach" in mdp.describe() + + +def test_tasks_restart_their_state_timers_and_commands_when_they_start(): + """A task of a sequence restarts its term state (to its initial value, or with its reset hook), its timers, and + its commands when it starts, and its per-term rewards are zero once it stopped.""" + gain = {"joint_pos": robot.joint_pos} + + def stage(joint: str, hooked: bool) -> mdp2.TaskCfg: + rewards = {"fused": mdp2.Reward(accumulate, inputs=gain, params={"gain": 1.0})} + commands = {} + if hooked: + rewards["hooked"] = mdp2.Reward(torch_accumulate(5.0), inputs=gain, params={"gain": 1.0}) + commands["count"] = mdp2.Command(sample_count, resampling_time_range=(0.04, 0.04)) + return mdp2.TaskCfg(rewards=rewards, commands=commands, done=getattr(mdp2.quantities, joint)) + + task = mdp2.compose( + mdp2.TaskCfg(quantities=above("a", "b")), mdp2.sequence(first=stage("a", False), second=stage("b", True)) + ) + # The first task is done at step 2, the second runs from step 3. + history = check_progress(task, [[0.25, 0.0], [1.0, 0.0], [1.0, 0.0], [1.0, 0.0], [1.0, 0.0]]) + total = [step[str(mdp2.term_state("rewards.second.fused", "total"))].item() for step in history] + hooked = [step[str(mdp2.term_state("rewards.second.hooked", "total"))].item() for step in history] + samples = [step[str(mdp2.term_state("commands.second.count", "samples"))].item() for step in history] + assert total[2:] == [1.0, 2.0, 3.0] # Restarted at zero, then the first joint at every step + assert hooked[1:] == [15.0, 16.0, 17.0, 18.0] # Its initial 5, then its reset hook's 10, at its start + assert samples == [0.0, 1.0, 1.0, 2.0, 2.0] # Sampled at its start, then every two steps + first = [step[str(mdp2.term_state("rewards.first.fused", "total"))].item() for step in history] + assert first == [0.25, 1.25, 1.25, 1.25, 1.25] + assert all(step["reward_terms"][0, 0].item() == 0.0 for step in history[2:]) + + +def test_subtasks_read_their_own_quantities_by_name(): + """Subtasks written as tasks of their own read their quantities by their names, which their prefix keeps apart.""" + + def reach(joint: str) -> mdp2.TaskCfg: + inputs = {"joint_pos": robot.joint_pos, "joint_ids": robot.joints(joint)} + return mdp2.TaskCfg( + quantities={"reached": mdp2.Quantity(joint_above, inputs=inputs)}, done=mdp2.quantities.reached + ) + + task = mdp2.sequence(first=reach("a"), second=reach("b")) + history = check_progress(task, [[0.0, 1.0], [1.0, 0.0], [1.0, 1.0]], joints=("a", "b")) + assert [step["first.done_at"].item() for step in history] == [-1, 2, 2] + assert [step["second.done_at"].item() for step in history] == [-1, -1, 3] + + +def test_split_runs_a_sequence_beside_a_plain_task(): + """A split gives a sequence and a plain task their own worlds, and the root's progress is each world's own.""" + sequence = mdp2.sequence(first=mdp2.Milestone(mdp2.quantities.a), second=mdp2.Milestone(mdp2.quantities.b)) + task = mdp2.compose( + mdp2.TaskCfg(quantities=above("a", "b")), + mdp2.split(staged=sequence, plain=mdp2.TaskCfg(done=mdp2.quantities.b), worlds={"staged": 3, "plain": 1}), + ) + mdp, _, history = run_progress(task, [[1.0, 1.0], [1.0, 1.0]], "warp", capture=False, num_worlds=4) + assert [config.worlds for config in mdp.world_configs] == [range(0, 3), range(3, 4)] + assert history[0]["done"].tolist() == [False] * 3 + [True] + assert history[1]["done"].tolist() == [True] * 4 + assert history[1]["staged.done"].tolist() == [True] * 3 + [False] + + +def test_task_trees_report_errors(): + """A split in a sequence, a sequence task without a completion, a task with subtasks and a done, and two uses of + one name that may run together are errors.""" + schema = PointMassScene(num_worlds=2, joint_names=("a",)).schema + quantities = mdp2.TaskCfg(quantities=above("a")) + milestone = mdp2.Milestone(mdp2.quantities.a) + cases = [ + (mdp2.sequence(first=mdp2.split(x=milestone, y=milestone)), "a sequence cannot"), + (mdp2.sequence(first=milestone, second=mdp2.TaskCfg()), "needs a completion"), + (mdp2.TaskCfg(done=mdp2.quantities.a, subtasks={"first": milestone}), "cannot have a done"), + ] + for task, message in cases: + with pytest.raises(ValueError, match=message): + builder = mdp2.MDPBuilder(schema) + builder.add_task(mdp2.compose(quantities, task)) + builder.validate() + + observation = mdp2.Observation(joint_pos, inputs={"joint_pos": robot.joint_pos}) + sharing = mdp2.TaskCfg(observations={"policy": {"position": observation}}, done=mdp2.quantities.a) + builder = mdp2.MDPBuilder(schema) + builder.add_task(mdp2.compose(quantities, first=sharing, second=sharing)) + with pytest.raises(ValueError, match="share the columns of 'position'"): + builder.validate() diff --git a/source/isaaclab_tasks/changelog.d/mdp2-part2.changed.rst b/source/isaaclab_tasks/changelog.d/mdp2-part2.changed.rst new file mode 100644 index 000000000000..04e8f8b79d6f --- /dev/null +++ b/source/isaaclab_tasks/changelog.d/mdp2-part2.changed.rst @@ -0,0 +1,2 @@ +* Changed ``Isaac-Velocity-Flat-WalkStand-UnitreeGo2-MDP2`` to give its walking and standing tasks their worlds with + :func:`~isaaclab_experimental.mdp2.split`. diff --git a/source/isaaclab_tasks/changelog.d/mdp2-part2.minor b/source/isaaclab_tasks/changelog.d/mdp2-part2.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_tasks/isaaclab_tasks/mdp2/velocity_go2/flat_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/mdp2/velocity_go2/flat_env_cfg.py index cd2490992bd9..60a121e85ab5 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/mdp2/velocity_go2/flat_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/mdp2/velocity_go2/flat_env_cfg.py @@ -293,13 +293,17 @@ class UnitreeGo2FlatEnvCfg(MDP2RLEnvCfg): def play_mode(self): """Play without the random pushes, as the MDP1 velocity tasks do.""" super().play_mode() - tasks = [self.task] if isinstance(self.task, mdp2.TaskCfg) else self.task - tasks = [replace(task, events={**task.events, "push_robot": None}) for task in tasks] - self.task = tasks[0] if isinstance(self.task, mdp2.TaskCfg) else tasks + self.task = _without_pushes(self.task) + + +def _without_pushes(task: mdp2.TaskCfg) -> mdp2.TaskCfg: + """Return a task and its subtasks without the random pushes.""" + subtasks = {name: _without_pushes(subtask) for name, subtask in task.subtasks.items()} + return replace(task, events={**task.events, "push_robot": None}, subtasks=subtasks) @configclass class UnitreeGo2FlatWalkStandEnvCfg(UnitreeGo2FlatEnvCfg): """The Go2 flat environment with half of the worlds walking and the other half standing still.""" - task: list[mdp2.TaskCfg] = [TASK, STAND_TASK] + task: mdp2.TaskCfg = mdp2.split(walk=TASK, stand=STAND_TASK) diff --git a/source/isaaclab_tasks/test/mdp2/test_lift_kuka_allegro.py b/source/isaaclab_tasks/test/mdp2/test_lift_kuka_allegro.py index 7867400ed456..5d899053a2fc 100644 --- a/source/isaaclab_tasks/test/mdp2/test_lift_kuka_allegro.py +++ b/source/isaaclab_tasks/test/mdp2/test_lift_kuka_allegro.py @@ -263,7 +263,7 @@ def test_play_mode_starts_the_curriculum_at_its_end(): from isaaclab_tasks.utils.hydra import resolve_task_config cfg, _ = resolve_task_config("Isaac-Lift-KukaAllegro-MDP2", None, play_mode=True, overrides=[]) - uses = [use for group in cfg.task.observations.values() for use in group.values() if use is not None] + uses = [use for group in cfg.task.observations.values() for use in group.terms.values() if use is not None] params = cfg.task.events["adr"].params assert cfg.scene.num_envs == 50 and all(use.noise is None for use in uses) assert params["init_difficulty"] == params["max_difficulty"] and params["promotion_only"] From 97e16221210631f1d5a58c430755a2beb8b3dd55 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 18:09:27 -0800 Subject: [PATCH 02/49] Read where MDP2 ops run and start from the op Ops expose the worlds where their scope started at a step, next to where they run, so that history refills, restarts, slot clearing, and diagnostics do not depend on the scope being a task of a sequence. Kernels of plain tasks are unchanged. --- .../isaaclab_experimental/mdp2/builder.py | 2 +- .../isaaclab_experimental/mdp2/plan.py | 14 +++++-- .../mdp2/torch_backend.py | 12 +++--- .../mdp2/warp_backend.py | 42 +++++++++---------- 4 files changed, 37 insertions(+), 33 deletions(-) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py index a782bc0aaa08..2feb9581e597 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py @@ -1151,7 +1151,7 @@ def _allocate_slots( start = columns.stop for op in slot_ops: placed[op.name] = replace(op, observation=replace(op.observation, columns=columns, size=size)) - if any(op.stage for op in slot_ops): + if any(op.entry_key is not None for op in slot_ops): slots.append(ObservationSlot(buffer, columns, size, tuple(placed[op.name] for op in slot_ops))) dims[buffer] = start return tuple(placed[op.name] for op in ops), tuple(slots), dims, layouts diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py index 2ad7a554aafc..a3d3909c60d5 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py @@ -106,6 +106,12 @@ def active_key(self) -> Hashable | None: return progress_field(self.stage, "active") return None if self.worlds is None else ("active", self.name) + @property + def entry_key(self) -> Hashable | None: + """Key in :attr:`MDPState.arrays` of the worlds where the op's scope started at this step, in which its state, + timer, command, and history restart; None for an op whose scope does not change during an episode.""" + return None if self.stage is None else progress_field(self.stage, "entered") + def array_key(self, arg: str) -> Hashable: """Return the key in :attr:`MDPState.arrays` of the array that the input ``arg`` reads.""" selector = self.inputs[arg] @@ -274,12 +280,12 @@ def computed(phase_ops: tuple) -> list[Step]: # A task that starts restarts the timers, commands, and state of its ops, as a new episode does. starts = [] if any(node.staged for tree in trees for node in tree.nodes): - staged = [op for phase_ops in ops.values() for op in phase_ops if isinstance(op, TermOp) and op.stage] + scoped = [op for phase_ops in ops.values() for op in phase_ops if isinstance(op, TermOp) and op.entry_key] starts = [ Step(StepKind.START_TASKS, trees), - *(Step(StepKind.RESET_TIMER, op, entry=True) for op in timed if op.stage), - *(Step(StepKind.COMPUTE, op, entry=True) for op in staged if op.phase is Phase.COMMANDS), - *(Step(StepKind.RESET_STATE, op, entry=True) for op in stateful if op.stage), + *(Step(StepKind.RESET_TIMER, op, entry=True) for op in timed if op.entry_key), + *(Step(StepKind.COMPUTE, op, entry=True) for op in scoped if op.phase is Phase.COMMANDS), + *(Step(StepKind.RESET_STATE, op, entry=True) for op in stateful if op.entry_key), ] reset_events = [] diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py index acf1a93fa01e..813964fdfce6 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py @@ -119,7 +119,7 @@ def _run(mdp: MDP, step: Step, call: Call, stepping: bool) -> None: mask = None if call.mask is None else call.mask.torch active = _active(op, state) if step.entry: - mask, active = state.arrays[progress_field(op.stage, "entered")].torch, None + mask, active = state.arrays[op.entry_key].torch, None if active is not None: mask = active.torch if mask is None else mask & active.torch @@ -227,15 +227,17 @@ def _compute(mdp: MDP, op: TermOp, call: Call, mask: torch.Tensor | None, steppi def _history(op: TermOp, state: MDPState, value: torch.Tensor, mask: torch.Tensor | None, push: bool) -> torch.Tensor: - """Push a value into an observation's history, or fill the history where it starts if not ``push``: in new - episodes, or, for an op of a task of a sequence, where the task started at this step. + """Push a value into an observation's history, or fill it where it starts: in new episodes if not ``push``, + and, for an op whose scope changes, where its scope started at this step. Returns the history, oldest first, as ``(num_worlds, history_length, size)``. """ history = state.arrays["history", op.name].torch selected = torch.ones_like(value[:, 0], dtype=torch.bool) if mask is None else mask - length = state.episode_length.torch - starts = length == (0 if op.stage is None else state.arrays[progress_field(op.stage, "started_at")].torch) + if push: + starts = torch.zeros_like(selected) if op.entry_key is None else state.arrays[op.entry_key].torch + else: + starts = state.episode_length.torch == 0 filled = value[:, None].expand_as(history) if push: diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py index 90ff800c5aba..667755a24d93 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py @@ -228,8 +228,8 @@ def _emit(code: Fusion, mdp: MDP, steps: Iterable[Step], stepping: bool = False) state = [term_state(op.use, name) for name in op.state] active = _active(code, op) if step.entry: - # Where the op's task started at this step, instead of the reset worlds. - entered = progress_field(op.stage, "entered") + # Where the op's scope started at this step, instead of the reset worlds. + entered = op.entry_key started = lambda call, entered=entered: call.state.arrays[entered].warp # noqa: E731 conditions = [f"if {_array(code, entered, wp.array(dtype=wp.bool))}[world]:"] match step.kind: @@ -317,8 +317,8 @@ def _compute(code: Fusion, mdp: MDP, op: TermOp, conditions: Sequence[str] = (), terms = _result(code, "termination_terms") lines.append(f"{terms}[world, {op.index}] = ended") writes.append("termination_terms") - if op.stage: - # A task of a sequence that stopped leaves no flag. + if op.entry_key is not None: + # An op whose scope stopped leaves no flag. code.world(f"{terms}[world, {op.index}] = False", writes=["termination_terms"]) code.world(*_under(conditions, *lines), writes=[*writes, *_computed_state(op)]) case Phase.REWARDS: @@ -331,8 +331,8 @@ def _compute(code: Fusion, mdp: MDP, op: TermOp, conditions: Sequence[str] = (), terms = _result(code, "reward_terms") lines.append(f"{terms}[world, {op.index}] = reward") writes.append("reward_terms") - if op.stage: - # A task of a sequence that stopped leaves no reward. + if op.entry_key is not None: + # An op whose scope stopped leaves no reward. code.world(f"{terms}[world, {op.index}] = 0.0", writes=["reward_terms"]) code.world(*_under(conditions, *lines), writes=[*writes, *_computed_state(op)]) case Phase.COMMANDS | Phase.INTERVAL_EVENTS if stepping: @@ -387,7 +387,7 @@ def _compute_observation(code: Fusion, mdp: MDP, op: TermOp, conditions: Sequenc return # Each thread keeps the history of its element: stepping shifts it and appends the value, and observing fills it - # for new episodes. An op of a task of a sequence also fills it when stepping, where its task started at this step. + # for new episodes. An op whose scope changes also fills it when stepping, where its scope started at this step. # The group holds the history oldest first, each step in ``size`` columns. history = _array(code, ("history", op.name), wp.array3d(dtype=wp.float32)) size, last = observation.size, observation.history_length - 1 @@ -397,23 +397,19 @@ def _compute_observation(code: Fusion, mdp: MDP, op: TermOp, conditions: Sequenc f" {history}[world, h, element] = {history}[world, h + 1, element]", f"{history}[world, {last}, element] = value", ] - starts = "0" - if stepping and op.stage is None: + if stepping and op.entry_key is None: update = [*shift[:-1], f"{history}[world, {last}, element] = {value}"] + elif stepping: + update = [ + "value = " + value, + f"if {_array(code, op.entry_key, wp.array(dtype=wp.bool))}[world]:", + *(f" {line}" for line in fill), + "else:", + *(f" {line}" for line in shift), + ] else: length = f"{_array(code, episode_length, wp.array(dtype=wp.int32))}[world]" - if op.stage is not None: - starts = f"{_array(code, progress_field(op.stage, 'started_at'), wp.array(dtype=wp.int32))}[world]" - if stepping: - update = [ - "value = " + value, - f"if {length} == {starts}:", - *(f" {line}" for line in fill), - "else:", - *(f" {line}" for line in shift), - ] - else: - update = [f"if {length} == {starts}:", " value = " + value, *(f" {line}" for line in fill)] + update = [f"if {length} == 0:", " value = " + value, *(f" {line}" for line in fill)] write = [ f"for h in range({observation.history_length}):", f" {out}[world, {start} + h * {size} + element] = {history}[world, h, element]", @@ -581,8 +577,8 @@ def _accesses(op: TermOp, mdp: MDP) -> tuple[set[Hashable], set[Hashable]]: """ state = {term_state(op.use, name) for name in op.state} reads = {*state, ("selected", op.name), *(["rng"] if op.random else [])} - # Hooks of a task of a sequence read where it runs and where it started. - reads |= {op.active_key, progress_field(op.stage, "entered")} if op.stage else set() + # Hooks of an op whose scope changes read where it runs and where it started. + reads |= {op.active_key, op.entry_key} if op.entry_key is not None else set() for arg, selector in op.inputs.items(): if isinstance(selector, Entity): reads.update(FieldSelector(selector.name, field) for field in mdp.schema.entities[selector.name].fields) From 284d50166f9a8753f428988fabea89d465c9f28c Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 18:16:29 -0800 Subject: [PATCH 03/49] Add tunable MDP2 values that change per world while graphs replay A param or reward weight declared mdp2.Tunable is a field of one value per world, which wp.func hooks take as their world's value. mdp2.tune and MDP2Env.tune change it at each world's next reset, applied in the reset kernel, or from the next step. Tasks without tunable values compile to the same kernels. --- .../changelog.d/mdp2-part2.added.rst | 5 + .../isaaclab_experimental/envs/mdp2_env.py | 24 +++- .../isaaclab_experimental/mdp2/__init__.pyi | 10 +- .../isaaclab_experimental/mdp2/builder.py | 94 ++++++++++++-- .../isaaclab_experimental/mdp2/compiled.py | 50 +++++++- .../isaaclab_experimental/mdp2/config.py | 26 +++- .../isaaclab_experimental/mdp2/eager.py | 2 +- .../isaaclab_experimental/mdp2/plan.py | 21 +++- .../isaaclab_experimental/mdp2/runtime.py | 41 +++++- .../mdp2/torch_backend.py | 18 ++- .../mdp2/warp_backend.py | 43 ++++++- .../test/mdp2/test_mdp2.py | 118 ++++++++++++++++++ 12 files changed, 423 insertions(+), 29 deletions(-) diff --git a/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst index c4b1e094c27c..1eaedcc51d92 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst @@ -28,3 +28,8 @@ * Added OptiX cameras to :class:`~isaaclab_experimental.envs.MDP2Env`: cameras with :class:`~isaaclab_newton.renderers.NewtonOptixRendererCfg` render between the CUDA graphs of a step, since OptiX refits its acceleration structures on the host. +* Added runtime values to MDP2: a param or reward weight declared :class:`~isaaclab_experimental.mdp2.Tunable` holds + one value per world, which :func:`~isaaclab_experimental.mdp2.tune` and + :meth:`~isaaclab_experimental.envs.MDP2Env.tune` change at each world's next reset or from the next step, while + captured steps keep replaying. Terms read it as a field, :func:`~isaaclab_experimental.mdp2.tunable`, and each world + counts the tunings it applied, recorded as ``revision``. diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py index 306e400045d8..8a7d4264a60d 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py @@ -12,8 +12,8 @@ import functools import itertools import math -from collections.abc import Callable -from typing import Any, ClassVar +from collections.abc import Callable, Sequence +from typing import Any, ClassVar, Literal import gymnasium as gym import numpy as np @@ -196,6 +196,18 @@ def step(self, action: torch.Tensor) -> tuple[VecEnvObs, dict]: self._step_or_replay(action) return self.observations, self.extras + def tune( + self, + path: str, + value: Any, + worlds: slice | Sequence[int] | torch.Tensor | None = None, + at: Literal["reset", "step"] = "reset", + ) -> None: + """Change a value of the task declared :class:`~isaaclab_experimental.mdp2.Tunable`, such as + ``"rewards.track.weight"``, in some or all worlds, at their next reset or from the next step. Captured steps + keep replaying. See :func:`~isaaclab_experimental.mdp2.tune`.""" + mdp2.tune(self.mdp, self.state, path, value, worlds, at) + def close(self) -> None: if not self._is_closed: self.sim.stop() @@ -567,8 +579,9 @@ def episode_records(self) -> dict[str, torch.Tensor]: The columns are ``world``, ``episode`` (its index among the world's episodes), ``length`` (control steps), ``terminated`` and ``truncated``, the value at the end of each recorded quantity, whether each termination ended it, as ``termination/``, and, for each task with a completion, the episode step at which it was - done (-1 if it was not) as ``progress/`` and the task's score as ``progress/score``. Rows of episodes that - ended in the same step are ordered by world. Waits for the device. + done (-1 if it was not) as ``progress/`` and the task's score as ``progress/score``, and, for a task with + tunable values, the tunings its world had applied as ``revision``. Rows of episodes that ended in the same + step are ordered by world. Waits for the device. """ rows = self._records[: self.episodes_completed] return {name: rows[:, k] for k, name in enumerate(self._record_columns)} @@ -595,6 +608,9 @@ def _init_episode_budget(self, budget: int) -> None: if completes: self._recorded.append(self.state.arrays[mdp2.progress_field("", "score")].torch) self._record_columns.append("progress/score") + if self.state.revision is not None: + self._recorded.append(self.state.revision.torch) + self._record_columns.append("revision") self._records = torch.zeros(budget + 1, len(self._record_columns), device=device) self._worlds = torch.arange(self.num_envs, device=device) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/__init__.pyi b/source/isaaclab_experimental/isaaclab_experimental/mdp2/__init__.pyi index d5fc35d0899d..9a402d0b8912 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/__init__.pyi +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/__init__.pyi @@ -47,6 +47,8 @@ __all__ = [ "TermContext", "Termination", "TimeLimit", + "Tunable", + "TunedValue", "UniformNoise", "Transition", "WorldConfig", @@ -67,6 +69,8 @@ __all__ = [ "step_dt", "term_state", "terminated", + "tunable", + "tune", "uniform", "mdp", ] @@ -97,6 +101,7 @@ from .config import ( TermCfg, Termination, TimeLimit, + Tunable, UniformNoise, commands, compose, @@ -110,10 +115,11 @@ from .config import ( step_dt, term_state, terminated, + tunable, ) from .eager import TermContext -from .plan import ExecutionPlan, ObservationSlot, Segment, Step, StepKind, TaskNode, TaskTree +from .plan import ExecutionPlan, ObservationSlot, Segment, Step, StepKind, TaskNode, TaskTree, TunedValue from .rng import uniform -from .runtime import apply_actions, evaluate, observe, reset, startup +from .runtime import apply_actions, evaluate, observe, reset, startup, tune from .scene import EntitySchema, FieldSchema, SceneData, SceneSchema from .terms import Implementation, State, Term diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py index 2feb9581e597..e6a5c095a863 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py @@ -40,6 +40,7 @@ TermCfg, Termination, TimeLimit, + Tunable, commands, episode_length, group_terms, @@ -49,8 +50,19 @@ step_dt, term_state, terminated, + tunable, +) +from .plan import ( + ActionOp, + ObservationOutput, + ObservationSlot, + Segment, + TaskNode, + TaskTree, + TermOp, + TunedValue, + build_plan, ) -from .plan import ActionOp, ObservationOutput, ObservationSlot, Segment, TaskNode, TaskTree, TermOp, build_plan from .scene import SceneSchema from .terms import Implementation, hook_arguments @@ -105,11 +117,12 @@ def writes(self) -> tuple[FieldSelector, ...]: @property def provides(self) -> tuple[FieldSelector, ...]: - """Fields of the MDP that other uses can read once this one is compiled: its value and its state.""" + """Fields of the MDP that other uses can read once this one is compiled: its value, state, and tunables.""" if not isinstance(self.cfg, TermCfg): return () state = [term_state(str(self), name) for name in self.cfg.term.state] - return (*(selector for selector in self.writes if not selector.scene), *state) + tunables = [tunable(str(self), name) for name, value in self.cfg.params.items() if isinstance(value, Tunable)] + return (*(selector for selector in self.writes if not selector.scene), *state, *tunables) @dataclass(frozen=True) @@ -469,6 +482,7 @@ def _compile( for op in ops[Phase.OBSERVATIONS] ) ops = MappingProxyType(ops) + tuned = _tuned_values(ops, errors) observation_layouts = { buffer: layouts.get(buffer, ((dim,), wp.float32)) for buffer, dim in observation_dims.items() @@ -485,7 +499,7 @@ def _compile( device=device, backend=backend, ops=ops, - plan=build_plan(ops, self.schema, trees, slots), + plan=build_plan(ops, self.schema, trees, slots, tuned), action_dim=action_dim, observation_dims=MappingProxyType(observation_dims), observation_layouts=MappingProxyType(observation_layouts), @@ -502,6 +516,7 @@ def _compile( ), tasks=trees, slots=slots, + tuned=tuned, ) def _compile_schedule( @@ -655,6 +670,7 @@ def _compile_term(self, entry: ScheduleEntry, context: CompileContext) -> None: names += ["rng"] if term.random else [] if len(set(names)) != len(names): errors.append(f"{entry}: inputs, outputs, state, params, and rng must have distinct names, got {names}.") + tunables, params, weight = _tunables(entry, errors) # Scene entities bound as inputs or outputs reach Python hooks as objects, such as articulations. bound = {**cfg.inputs, **outputs} @@ -670,11 +686,13 @@ def _compile_term(self, entry: ScheduleEntry, context: CompileContext) -> None: fields = { arg: self._resolve(entry, arg, selector, context) for arg, selector in bound.items() if arg not in entities } + for name, default in tunables.items(): + fields[name] = context.mdp_fields[tunable(str(entry), name)] = _tunable_layout(entry, name, default, errors) for arg, selector in outputs.items(): if arg not in entities and fields[arg] is not None: self._check_writable(entry, selector, errors) # Int params, such as a number of points, can also size dimensions. - sizes = {name: value for name, value in cfg.params.items() if type(value) is int} + sizes = {name: value for name, value in params.items() if type(value) is int} sizes |= _dimension_sizes(fields) output_shape = _resolve_shape(entry, "output", term.shape, sizes, errors) if output_shape and isinstance(cfg, (Reward, Termination)): @@ -717,7 +735,7 @@ def _compile_term(self, entry: ScheduleEntry, context: CompileContext) -> None: } if term.init is not None: try: - inspect.signature(term.init).bind(None, **dict.fromkeys(cfg.params)) + inspect.signature(term.init).bind(None, **dict.fromkeys(cfg.params)) # Tunables at their default except TypeError as error: errors.append(f"{entry}: init {term.init.__name__!r} is called with (ctx, **params): {error}.") # Python hooks may also take ``cache``, a dict the use keeps for host objects. @@ -764,9 +782,11 @@ def _compile_term(self, entry: ScheduleEntry, context: CompileContext) -> None: compute=implementation.compute, update=implementation.update, reset=implementation.reset, - inputs=MappingProxyType({**cfg.inputs, **outputs, **command}), + inputs=MappingProxyType( + {**cfg.inputs, **outputs, **command, **{name: tunable(str(entry), name) for name in tunables}} + ), params=MappingProxyType( - {name: self.schema.step_dt if value is step_dt else value for name, value in cfg.params.items()} + {name: self.schema.step_dt if value is step_dt else value for name, value in params.items()} ), state=MappingProxyType( { @@ -778,7 +798,9 @@ def _compile_term(self, entry: ScheduleEntry, context: CompileContext) -> None: dtype=dtype, # An entity output writes any of the entity's writable fields. writes=tuple(dict.fromkeys(selector for write in entry.writes for selector in self._fields_of(write))), - weights=(cfg.weight,) if isinstance(cfg, Reward) else (), + weights=(weight,) if isinstance(cfg, Reward) else (), + tunables=MappingProxyType(tunables), + tunable_weight=isinstance(cfg, Reward) and isinstance(cfg.weight, Tunable), time_out=cfg.time_out if isinstance(cfg, Termination) else False, observation=observation, timer=timer, @@ -906,6 +928,49 @@ def _check_output_type(entry: ScheduleEntry, dtype: type, errors: list[str]) -> ) +def _tunables( + entry: ScheduleEntry, errors: list[str] +) -> tuple[dict[str, typing.Any], dict[str, typing.Any], float | None]: + """Return the defaults of a use's tunable params, which are fields of the MDP of one value per world that its + hooks read like inputs, its other params, and the default of a reward's weight.""" + cfg = entry.cfg + tunables = {name: value.default for name, value in cfg.params.items() if isinstance(value, Tunable)} + params = {name: value for name, value in cfg.params.items() if name not in tunables} + weight = cfg.weight if isinstance(cfg, Reward) else None + if isinstance(weight, Tunable): + weight = weight.default + if "weight" in tunables: + errors.append(f"{entry}: a reward with a tunable weight cannot have a tunable param named 'weight'.") + return tunables, params, weight + + +def _tunable_layout(entry: ScheduleEntry | str, name: str, default: object, errors: list[str]) -> ArrayLayout: + """Return the layout of the field of a tunable value: one bool, int, float, or float vector per world.""" + if isinstance(default, tuple) and default and all(type(value) in (int, float) for value in default): + return ArrayLayout(wp.types.vector(len(default), wp.float32), 1, {}) + dtypes = {bool: wp.bool, int: wp.int32, float: wp.float32} + if type(default) not in dtypes: + errors.append( + f"{entry}: the tunable {name!r} must be a bool, int, float, or tuple of numbers, got {default!r}." + ) + return ArrayLayout(dtypes.get(type(default), wp.float32), 1, {}) + + +def _tuned_values(ops: Mapping[Phase, tuple], errors: list[str]) -> tuple[TunedValue, ...]: + """Return the tunable values of the ops, once per use, with their reward weights.""" + tuned: dict[str, TunedValue] = {} + for op in (op for phase_ops in ops.values() for op in phase_ops if isinstance(op, TermOp)): + values = [ + TunedValue(f"{op.use}.{name}", op.inputs[name], dtype=_tunable_layout(op.name, name, default, []).dtype) + for name, default in op.tunables.items() + ] + values += [TunedValue(f"{op.use}.weight", "reward_weights", op.index)] if op.tunable_weight else [] + for value in values: + if tuned.setdefault(value.path, value) != value: + errors.append(f"The world configs tune '{value.path}' differently: tune it in all or none of them.") + return tuple(tuned.values()) + + def _dimension_sizes(fields: Mapping[str, ArrayLayout | None]) -> dict[str, int]: """Return the size of each named dimension of a term's inputs. @@ -951,7 +1016,16 @@ def _check_hook( return for name, annotation in annotations.items(): bound = arguments[name] - if bound is None or not isinstance(annotation, wp.array): + if bound is None: + continue + if not wp.types.is_array(annotation): + # A field of one value per world, such as a tunable param, binds to a scalar: its world's value. + if bound.ndim != 1 or not wp.types.types_equal(wp.array(dtype=annotation).dtype, bound.dtype): + errors.append( + f"{entry}: wp.func {hook.key!r} takes {name!r} as one value, but it is a" + f" {bound.ndim}-dimensional array of {bound.dtype.__name__}, not one value of that type per" + " world." + ) continue if annotation.dtype is not bound.dtype or annotation.ndim != bound.ndim: errors.append( diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py index 04922b57c0f4..fb67f1bcaccf 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py @@ -33,7 +33,18 @@ term_state, terminated, ) -from .plan import ActionOp, ExecutionPlan, Launches, ObservationSlot, Segment, Step, TaskTree, TermOp, segments +from .plan import ( + ActionOp, + ExecutionPlan, + Launches, + ObservationSlot, + Segment, + Step, + TaskTree, + TermOp, + TunedValue, + segments, +) from .scene import SceneData, SceneSchema @@ -64,7 +75,10 @@ class MDPState: - ``"interval_worlds"``: the worlds where an interval event that writes scene fields ran in the last ``evaluate``, for an MDP with such events; - ``mdp2.progress_field(task, name)``: the progress of every task, with the internal ``streak`` (steps that a - task's ``done`` held) and ``entered`` (whether a task of a sequence started at this step). + task's ``done`` held) and ``entered`` (whether a task of a sequence started at this step); + - ``mdp2.tunable(use, name)``: the value of a tunable param per world, and, for an MDP with tunable values, + ``("pending", key)``: the values tuned for the next reset of each array, ``"pending"``: the worlds that have + them, and ``"revision"``: the number of tunings applied in each world, see :func:`~.tune`. """ arrays: dict[Hashable, ProxyArray] @@ -90,6 +104,11 @@ def reward_weights(self) -> ProxyArray: def rng(self) -> ProxyArray: return self.arrays["rng"] + @property + def revision(self) -> ProxyArray | None: + """Tunings applied in each world, ``int32`` of shape ``(num_worlds,)``; None without tunable values.""" + return self.arrays.get("revision") + @dataclass class Transition: @@ -150,6 +169,7 @@ class MDP: # The task tree of each world config, if the MDP tracks progress: some task has a completion or a sequence tasks: tuple[TaskTree, ...] = () slots: tuple[ObservationSlot, ...] = () # Observation slots that some op writes only in some steps + tuned: tuple[TunedValue, ...] = () # Values declared Tunable, which tune changes launches: Launches | None = None # Set by finalize, None for an MDP that was only validated @property @@ -257,6 +277,8 @@ def describe(self) -> str: ] width = max((len(name) for name in self.schedule), default=0) + if self.tuned: + lines.append(f"tunable {', '.join(value.path for value in self.tuned)}") for tree in self.tasks: worlds = f" (worlds {tree.worlds.start}-{tree.worlds.stop - 1})" if len(self.tasks) > 1 else "" lines.append(f"tasks{worlds}") @@ -324,6 +346,15 @@ def state(self, scene_data: SceneData, seed: int = 0) -> MDPState: arrays |= self._progress_arrays() for op in self.ops[Phase.COMMANDS] + self.ops[Phase.QUANTITIES]: arrays[op.writes[0]] = self._zeros(self.num_worlds, *op.shape) + dtypes = {value.key: value.dtype for value in self.tuned} + for op in self.term_ops: + # Each world config starts the tunable values of its worlds at its own default. + for name, default in op.tunables.items(): + key = op.inputs[name] + if key not in arrays: + arrays[key] = self._zeros(self.num_worlds, dtype=dtypes[key]) + worlds = slice(None) if op.worlds is None else list(op.worlds) + arrays[key].torch[worlds] = torch.tensor(default, dtype=arrays[key].torch.dtype, device=self.device) for subset, indices in self.subsets.items(): arrays[subset] = ProxyArray(wp.array(indices, dtype=wp.int32, device=self.device)) # State belongs to the use: the ops that other world configs define differently share it. @@ -355,6 +386,12 @@ def state(self, scene_data: SceneData, seed: int = 0) -> MDPState: for index, config in enumerate(self.world_configs): weights[config.worlds.start : config.worlds.stop] = [op.weights[index] for op in self.ops[Phase.REWARDS]] arrays["reward_weights"] = ProxyArray(wp.array(weights, dtype=wp.float32, device=self.device)) + if self.tuned: + # Values tuned for the next reset wait in a copy of their array, in the worlds marked pending. + arrays["pending"] = self._zeros(self.num_worlds, dtype=wp.bool) + arrays["revision"] = self._zeros(self.num_worlds, dtype=wp.int32) + for key in dict.fromkeys(value.key for value in self.tuned): + arrays["pending", key] = ProxyArray(wp.clone(arrays[key].warp)) if self.interval_writes: arrays["interval_worlds"] = self._zeros(self.num_worlds, dtype=wp.bool) @@ -384,13 +421,20 @@ def state(self, scene_data: SceneData, seed: int = 0) -> MDPState: warp_views = {key: array.warp for key, array in arrays.items()} arguments, caches = {}, {} for op in self.term_ops: - views = torch_views if self.backend is Backend.TORCH or op.torch_hooks else warp_views + torch_hooks = self.backend is Backend.TORCH or op.torch_hooks + views = torch_views if torch_hooks else warp_views python = not isinstance(op.compute, wp.Function) arguments[op.name] = { **{ arg: scene_data.entity(selector.name) if isinstance(selector, Entity) else views[op.array_key(arg)] for arg, selector in op.inputs.items() }, + # Torch hooks get a tunable tuple as a tuple of per-world tensors. + **{ + name: tuple(torch_views[op.inputs[name]].unbind(1)) + for name, default in op.tunables.items() + if torch_hooks and isinstance(default, tuple) + }, **({"cache": caches.setdefault(op.name, {})} if python else {}), **{name: views[term_state(op.use, name)] for name in op.state}, **({"rng": views["rng"][op.stream]} if op.random else {}), diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py index c10215ffc289..e76dd291383c 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py @@ -133,6 +133,26 @@ def term_state(use: str, name: str) -> FieldSelector: """ +@dataclass(frozen=True) +class Tunable: + """A value that may change while the MDP runs, per world: a param, as in ``params={"std": mdp2.Tunable(0.5)}``, + or a reward's ``weight``. + + It is a field of the MDP, ``mdp2.tunable("rewards.track", "std")``, of one value per world: ``float32``, + ``int32``, ``bool``, or, for a tuple of numbers, a ``float32`` vector. A ``wp.func`` takes it as a param, of its + world's value; Python hooks get the array, which Torch hooks get as a ``(num_worlds,)`` tensor per number. + :func:`~.tune` changes it, at each world's next reset by default, so that no episode mixes two values; other terms + may read it and events may write it, such as a curriculum. + """ + + default: float | int | bool | tuple[float, ...] + + +def tunable(use: str, name: str) -> FieldSelector: + """Select the tunable value ``name`` of a use, a param or ``weight``, as in ``tunable("rewards.track", "std")``.""" + return FieldSelector("tunables", f"{use}.{name}", scene=False) + + @dataclass(frozen=True) class UniformNoise: """Noise drawn uniformly from ``[n_min, n_max]`` for each element, like MDP1's ``UniformNoiseCfg``.""" @@ -150,7 +170,8 @@ class TermCfg: term: Term inputs: dict[str, FieldSelector | SubsetSelector] = field(default_factory=dict) # Passed by name, read-only - # Constant keyword arguments. The MDP keeps the values themselves, not copies: do not change them after finalizing. + # Constant keyword arguments, or Tunable values. The MDP keeps the values themselves, not copies: do not change + # them after finalizing. params: dict[str, Any] = field(default_factory=dict) @@ -214,7 +235,8 @@ class Reward(TermCfg): phase: ClassVar[Phase] = Phase.REWARDS - weight: float = 1.0 # Initial weight, adjustable at runtime through MDPState.reward_weights + # Initial weight, which MDPState.reward_weights holds per world; a Tunable weight can be tuned at resets + weight: float | Tunable = 1.0 @dataclass diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/eager.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/eager.py index 398191cfbb1f..57d254b3326a 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/eager.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/eager.py @@ -62,4 +62,4 @@ def call_init(mdp: MDP, op: TermOp, state: MDPState, hook: Callable) -> None: selectors=op.inputs, scene_data=state.scene_data, ) - hook(context, **op.params) + hook(context, **op.params, **op.tunables) # Tunable params at their default diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py index a3d3909c60d5..68344f39daac 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py @@ -16,6 +16,7 @@ import itertools from collections.abc import Callable, Hashable, Mapping, Sequence from dataclasses import dataclass +from types import MappingProxyType from typing import TYPE_CHECKING, Any from .config import Entity, FieldSelector, Phase, SubsetSelector, TaskMode, UniformNoise, last_action, progress_field @@ -79,6 +80,9 @@ class TermOp: dtype: type # Output element type writes: tuple[FieldSelector, ...] = () # A command's value, or the outputs of an event weights: tuple[float, ...] = () # Rewards: initial weight per world config, 0 where the op is inactive + # Default value of each tunable param, by name; the param is an input bound to the field mdp2.tunable(use, name) + tunables: Mapping[str, Any] = MappingProxyType({}) + tunable_weight: bool = False # Rewards: whether the weight is tunable time_out: bool = False # Terminations: whether a true output truncates observation: ObservationOutput | None = None # Observations only timer: tuple[float, float] | None = None # Seconds between command resamples or interval events @@ -133,6 +137,17 @@ class StepKind(enum.Enum): START_TASKS = enum.auto() # Start the tasks that a sequence advanced to, top down, and stop those it left RESET_PROGRESS = enum.auto() # Restart the progress of every task for a new episode CLEAR = enum.auto() # Zero the columns of an observation slot that no op writes at this step + APPLY_TUNED = enum.auto() # Apply the values tuned for the next reset, in the worlds that have them + + +@dataclass(frozen=True) +class TunedValue: + """A value of the MDP that :func:`~.tune` changes, declared with :class:`~.config.Tunable`.""" + + path: str # Name of the use and of the value, such as "rewards.track.std" or "rewards.track.weight" + key: Hashable # Key of its array in MDPState.arrays: mdp2.tunable(use, name), or "reward_weights" + column: int | None = None # Reward weights: the column of the reward + dtype: Any = None # Element type of a tunable param's field @dataclass(frozen=True) @@ -193,7 +208,7 @@ class Step: """One unit of work on an op, the task trees, or an observation slot, in a runtime function.""" kind: StepKind - op: ActionOp | TermOp | tuple[TaskTree, ...] | ObservationSlot + op: ActionOp | TermOp | tuple[TaskTree, ...] | ObservationSlot | tuple[TunedValue, ...] entry: bool = False # Whether it runs for the worlds whose task of the op just started, rather than for the mask @property @@ -236,13 +251,14 @@ def build_plan( schema: SceneSchema, trees: tuple[TaskTree, ...] = (), slots: tuple[ObservationSlot, ...] = (), + tuned: tuple[TunedValue, ...] = (), ) -> ExecutionPlan: """Order the steps of every runtime function from the ops of each phase. This defines the step contract. With task trees, ``evaluate`` counts the tasks' completions after the quantities, so that terminations and rewards see this step's progress, and starts the tasks that sequences advanced to after the events, so that the successor observations see them. The terminations, rewards, commands, and events of the step run in the tasks that - ran when it started. + ran when it started. With tunable values, ``reset`` first applies the values tuned for it. """ timed = [op for op in ops[Phase.COMMANDS] + ops[Phase.INTERVAL_EVENTS] if op.timer is not None] observations = tuple(Step(StepKind.COMPUTE, op) for op in ops[Phase.OBSERVATIONS]) @@ -317,6 +333,7 @@ def computed(phase_ops: tuple) -> list[Step]: *(Step(StepKind.UPDATE_STATE, op) for op in ops[Phase.OBSERVATIONS] if op.update is not None), ), reset=( + *([Step(StepKind.APPLY_TUNED, tuned)] if tuned else []), *([Step(StepKind.RESET_PROGRESS, trees)] if trees else []), *(Step(StepKind.RESET_TIMER, op) for op in timed), *reset_events, diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/runtime.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/runtime.py index 5df07336d190..6e1a0a119a7f 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/runtime.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/runtime.py @@ -11,8 +11,10 @@ from __future__ import annotations -from collections.abc import Callable +from collections.abc import Callable, Sequence +from typing import Any, Literal +import torch import warp as wp from isaaclab.utils.warp import ProxyArray @@ -68,3 +70,40 @@ def observe(mdp: MDP, state: MDPState, observations: dict[str, ProxyArray], mask call = Call(state, mask=mask, observations=observations) for launch in mdp.launches.observe: launch(call) + + +def tune( + mdp: MDP, + state: MDPState, + path: str, + value: Any, + worlds: slice | Sequence[int] | torch.Tensor | None = None, + at: Literal["reset", "step"] = "reset", +) -> None: + """Change a value declared :class:`~.config.Tunable`, such as ``"rewards.track.std"`` or ``"rewards.track.weight"``. + + ``value`` is one value, or one per selected world. ``worlds`` selects worlds by index, slice, or ``bool`` mask, all + of them if None. At ``"reset"``, each world takes the value when its episode next resets, so that no episode mixes + two values; at ``"step"``, from the next step on. Each world counts the tunings it applied in + :attr:`MDPState.revision`. Writes in place, so captured steps keep replaying. Raises ``KeyError`` for a value that + is not tunable. + """ + tuned = {value.path: value for value in mdp.tuned} + if path not in tuned: + raise KeyError(f"{path!r} is not tunable: declare it with mdp2.Tunable. Tunable values: {sorted(tuned)}.") + if at not in ("reset", "step"): + raise ValueError(f"Tunings apply at 'reset' or 'step', got {at!r}.") + target = tuned[path] + selected = torch.zeros(mdp.num_worlds, dtype=torch.bool, device=mdp.device) + selected[slice(None) if worlds is None else worlds] = True + + # The value waits in the pending copy; a tuning for this step also writes it in place, and keeps the copy equal. + destinations = [state.arrays["pending", target.key].torch] + destinations += [state.arrays[target.key].torch] if at == "step" else [] + for destination in destinations: + values = destination if target.column is None else destination[:, target.column] + values[selected] = torch.as_tensor(value, dtype=values.dtype, device=mdp.device) + if at == "step": + state.arrays["revision"].torch.add_(selected.int()) + else: + state.arrays["pending"].torch.logical_or_(selected) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py index 813964fdfce6..ab72cecbb31c 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py @@ -15,7 +15,7 @@ from . import rng from .compiled import MDP, MDPState from .config import FieldSelector, Phase, TaskMode, last_action, progress_field, term_state, terminated -from .plan import Call, Launch, Launches, ObservationSlot, Step, StepKind, TaskTree, TermOp +from .plan import Call, Launch, Launches, ObservationSlot, Step, StepKind, TaskTree, TermOp, TunedValue from .terms import hook_arguments @@ -115,6 +115,9 @@ def _run(mdp: MDP, step: Step, call: Call, stepping: bool) -> None: case StepKind.CLEAR: _clear(mdp, op, call, stepping) return + case StepKind.APPLY_TUNED: + _apply_tuned(op, state, call.mask.torch) + return mask = None if call.mask is None else call.mask.torch active = _active(op, state) @@ -265,6 +268,19 @@ def _restart(op: TermOp, state: MDPState, mask: torch.Tensor) -> None: time_left.copy_(torch.where(mask, rng.uniform(state.rng.torch[op.stream], *op.timer, offset=-1), time_left)) +def _apply_tuned(tuned: tuple[TunedValue, ...], state: MDPState, mask: torch.Tensor) -> None: + """Apply the values tuned for the next reset in the reset worlds that have them, and count the tuning.""" + pending = state.arrays["pending"].torch + applied = pending & mask + for value in tuned: + live, waiting = state.arrays[value.key].torch, state.arrays["pending", value.key].torch + if value.column is not None: + live, waiting = live[:, value.column], waiting[:, value.column] + live.copy_(torch.where(applied.view(-1, *[1] * (live.ndim - 1)), waiting, live)) + state.arrays["revision"].torch.add_(applied.int()) + pending.logical_and_(~applied) + + def _clear(mdp: MDP, slot: ObservationSlot, call: Call, stepping: bool) -> None: """Zero the columns of a slot that no op writes at this step, in the masked worlds.""" steps = slot.columns.stop - slot.columns.start diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py index 667755a24d93..9c97c7649545 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py @@ -34,7 +34,7 @@ terminated, ) from .fusion import Fusion -from .plan import Call, Launches, ObservationSlot, Step, StepKind, TaskNode, TaskTree, TermOp +from .plan import Call, Launches, ObservationSlot, Step, StepKind, TaskNode, TaskTree, TermOp, TunedValue from .terms import hook_arguments _RESULTS = { @@ -224,6 +224,9 @@ def _emit(code: Fusion, mdp: MDP, steps: Iterable[Step], stepping: bool = False) case StepKind.CLEAR: _clear(code, mdp, step.op, stepping) continue + case StepKind.APPLY_TUNED: + _apply_tuned(code, step.op) + continue op = step.op state = [term_state(op.use, name) for name in op.state] active = _active(code, op) @@ -516,13 +519,19 @@ def _call(code: Fusion, op: TermOp, hook: wp.Function, shape: tuple[int, ...] = values.append(code.constant(annotation, op.params[name])) elif name in op.inputs or name in op.state: key = op.array_key(name) if name in op.inputs else term_state(op.use, name) - values.append(_array(code, key, annotation)) + if wp.types.is_array(annotation): + values.append(_array(code, key, annotation)) + else: + # A field of one value per world, such as a tunable param, passes its world's value. + values.append(f"{_array(code, key, wp.array(dtype=annotation))}[world]") elif name == "action" and op.columns is not None: # The action's columns, as a strided view of the actions. columns = op.columns values.append(code.argument(("action", op.name), annotation, lambda call: call.actions.warp[:, columns])) - else: + elif name == "rng": values.append(f"{_rng(code)}[{op.stream}, world]") + else: + raise ValueError(f"{op.name}: wp.func {hook.key!r} takes {name!r}, which the op does not bind.") return f"{code.function(hook)}({', '.join(values)})" @@ -775,6 +784,34 @@ def _reset_progress(code: Fusion, trees: tuple[TaskTree, ...]) -> None: code.world(*_under(_in_tree(trees, tree), *lines), writes=_tree_writes(tree, names)) +def _apply_tuned(code: Fusion, tuned: tuple[TunedValue, ...]) -> None: + """Apply the values tuned for the next reset in the reset worlds that have them, and count the tuning.""" + pending = _array(code, "pending", wp.array(dtype=wp.bool)) + revision = _array(code, "revision", wp.array(dtype=wp.int32)) + lines, writes = [], ["pending", "revision"] + for value in tuned: + if value.column is None: + annotation = wp.array(dtype=value.dtype) + live, waiting, index = ( + _array(code, value.key, annotation), + _array(code, ("pending", value.key), annotation), + "world", + ) + else: + annotation = wp.array2d(dtype=wp.float32) + live, waiting = _array(code, value.key, annotation), _array(code, ("pending", value.key), annotation) + index = f"world, {value.column}" + lines.append(f"{live}[{index}] = {waiting}[{index}]") + writes.append(value.key) + code.world( + f"if {pending}[world]:", + *(f" {line}" for line in lines), + f" {revision}[world] = {revision}[world] + 1", + f" {pending}[world] = False", + writes=writes, + ) + + def _clear(code: Fusion, mdp: MDP, slot: ObservationSlot, stepping: bool) -> None: """Zero the columns of a slot that no op writes at this step. diff --git a/source/isaaclab_experimental/test/mdp2/test_mdp2.py b/source/isaaclab_experimental/test/mdp2/test_mdp2.py index ed7661b55c6e..bad475768be1 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2.py @@ -1918,3 +1918,121 @@ def test_task_trees_report_errors(): builder.add_task(mdp2.compose(quantities, first=sharing, second=sharing)) with pytest.raises(ValueError, match="share the columns of 'position'"): builder.validate() + + +@wp.func +def scaled_sum_warp(world: int, joint_pos: wp.array2d(dtype=float), gain: float) -> float: + total = float(0.0) + for j in range(joint_pos.shape[1]): + total += joint_pos[world, j] + return gain * total + + +scaled_sum = mdp2.Term(torch=lambda joint_pos, *, gain: gain * joint_pos.sum(-1), warp=scaled_sum_warp) + + +@wp.func +def outside_warp(world: int, joint_pos: wp.array2d(dtype=float), bounds: wp.vec2f) -> bool: + return joint_pos[world, 0] < bounds[0] or joint_pos[world, 0] > bounds[1] + + +def outside_torch(joint_pos, *, bounds): + low, high = bounds + return (joint_pos[:, 0] < low) | (joint_pos[:, 0] > high) + + +outside = mdp2.Term(torch=outside_torch, warp=outside_warp) + + +def test_tunable_values_change_at_resets_or_steps_while_graphs_replay(): + """Tunable params and weights hold one value per world, which terms read as their world's value and observations + as a field. A tuning waits for each world's next reset, or applies at the next step, also between graph replays, + and every world counts the tunings it applied.""" + task = mdp2.TaskCfg( + observations={ + "policy": { + "gain": mdp2.Observation(generated_commands, inputs={"command": mdp2.tunable("rewards.scaled", "gain")}) + } + }, + rewards={ + "scaled": mdp2.Reward( + scaled_sum, + inputs={"joint_pos": robot.joint_pos}, + params={"gain": mdp2.Tunable(1.0)}, + weight=mdp2.Tunable(1.0), + ) + }, + terminations={ + "outside": mdp2.Termination( + outside, inputs={"joint_pos": robot.joint_pos}, params={"bounds": mdp2.Tunable((-10.0, 10.0))} + ) + }, + ) + num_worlds = 5 # Not the number of joints, so that a wrong broadcast cannot go unseen + + def run(backend: str, capture: bool) -> list[dict[str, torch.Tensor]]: + scene = PointMassScene(num_worlds=num_worlds, joint_names=("a", "b", "c"), device=DEVICE) + builder = mdp2.MDPBuilder(scene.schema) + builder.add_task(task) + mdp = builder.finalize(device=DEVICE, backend=backend) + state, transition = mdp.state(scene), mdp.transition() + mask = ProxyArray(wp.zeros(num_worlds, dtype=wp.bool, device=DEVICE)) + actions = ProxyArray(wp.zeros((num_worlds, 1), dtype=wp.float32, device=DEVICE)) + captured = mdp2.CapturedMDP(mdp, state, transition, actions, mask) if capture else None + env_reset(mdp, state, scene, transition.observations, torch.ones(num_worlds, dtype=torch.bool, device=DEVICE)) + scene.data("robot", "joint_pos").torch.fill_(0.5) + + tunings = { + 1: [("rewards.scaled.gain", 2.0, [1, 3], "reset")], + 3: [("rewards.scaled.weight", torch.arange(1.0, 6.0, device=DEVICE), None, "step")], + 4: [("terminations.outside.bounds", (-1.0, 0.25), [4], "step")], + } + resets = {2: [1]} + history = [] + for step in range(1, 6): + if captured is None: + mdp2.evaluate(mdp, state, transition) + else: + captured.evaluate() + mask.torch.zero_() + mask.torch[resets.get(step, [])] = True + if captured is None: + mdp2.reset(mdp, state, mask) + mdp2.observe(mdp, state, transition.observations, mask) + else: + captured.reset() + captured.observe() + history.append( + { + "rewards": transition.rewards.torch.clone(), + "terminated": transition.terminated.torch.clone(), + "policy": transition.observations["policy"].torch.clone(), + "revision": state.revision.torch.clone(), + } + ) + for path, value, worlds, at in tunings.get(step, []): + mdp2.tune(mdp, state, path, value, worlds, at) + return history + + runs = [run(backend, capture) for backend in ("torch", "warp") for capture in (False, True)] + for other in runs[1:]: + for expected, actual in zip(runs[0], other): + for name in expected: + assert torch.equal(expected[name], actual[name]), name + + history = runs[0] + step_dt = 0.02 + rewards = [(step["rewards"] / (step_dt * 1.5)).tolist() for step in history] + assert rewards[1] == pytest.approx([1.0] * 5) # Tuned for the next reset: no change yet + # World 1 reset after step 2 and took the gain of 2; world 3 still waits for its reset. + assert rewards[2] == pytest.approx([1.0, 2.0, 1.0, 1.0, 1.0]) + assert history[2]["policy"][:, 0].tolist() == [1.0, 2.0, 1.0, 1.0, 1.0] + assert rewards[3] == pytest.approx([1.0, 4.0, 3.0, 4.0, 5.0]) # Weights of 1 to 5 from the next step + assert history[4]["terminated"].tolist() == [False] * 4 + [True] # World 4's tighter bounds + assert history[4]["revision"].tolist() == [1, 2, 1, 1, 2] + + builder = mdp2.MDPBuilder(PointMassScene(num_worlds=2).schema) + builder.add_task(dataclasses.replace(task, observations={})) + mdp = builder.finalize(device=DEVICE) + with pytest.raises(KeyError, match="not tunable: declare it with mdp2.Tunable"): + mdp2.tune(mdp, mdp.state(PointMassScene(num_worlds=2, device=DEVICE)), "rewards.scaled.std", 1.0) From d8b4bbfe972e8672afc304a72589e5ccb310e304 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 18:22:39 -0800 Subject: [PATCH 04/49] Switch MDP2 uses on and off per world with when A use with when runs where its field was positive at the start of the step, as uses of a task of a sequence run while their task does, and restarts where it turns on. Resets prepare it in every world of its task. A Tunable when is a switch per world. Uses without when compile to the same kernels. --- .../changelog.d/mdp2-part2.added.rst | 4 + .../isaaclab_experimental/mdp2/builder.py | 43 +++++++++- .../isaaclab_experimental/mdp2/compiled.py | 12 ++- .../isaaclab_experimental/mdp2/config.py | 4 + .../isaaclab_experimental/mdp2/plan.py | 46 +++++++--- .../isaaclab_experimental/mdp2/runtime.py | 3 +- .../mdp2/torch_backend.py | 19 +++++ .../mdp2/warp_backend.py | 19 +++++ .../test/mdp2/test_mdp2.py | 85 +++++++++++++++++++ 9 files changed, 218 insertions(+), 17 deletions(-) diff --git a/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst index 1eaedcc51d92..0f96d741f86f 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst @@ -33,3 +33,7 @@ :meth:`~isaaclab_experimental.envs.MDP2Env.tune` change at each world's next reset or from the next step, while captured steps keep replaying. Terms read it as a field, :func:`~isaaclab_experimental.mdp2.tunable`, and each world counts the tunings it applied, recorded as ``revision``. +* Added ``when`` to MDP2 term uses: a reward, termination, observation, command, or interval event runs only in the + worlds where a field, such as a mode command, was positive at the start of the step, and restarts its state, timer, + command, and history where it turns on. ``when=mdp2.Tunable(True)`` is a switch per world that + :func:`~isaaclab_experimental.mdp2.tune` turns on and off. diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py index e6a5c095a863..bca6fe6ce3cb 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py @@ -102,6 +102,13 @@ def reads(self) -> tuple[FieldSelector, ...]: reads.append(self.cfg.noise.scale) return tuple(reads) + @property + def when(self) -> FieldSelector | None: + """The field that switches the use on and off, which it reads at the start of a step, if any.""" + if not isinstance(self.cfg, TermCfg) or self.cfg.when is None: + return None + return tunable(str(self), "when") if isinstance(self.cfg.when, Tunable) else self.cfg.when + @property def writes(self) -> tuple[FieldSelector, ...]: """Fields the use writes: an action's target, the value of a command or quantity, or an event's outputs.""" @@ -122,6 +129,7 @@ def provides(self) -> tuple[FieldSelector, ...]: return () state = [term_state(str(self), name) for name in self.cfg.term.state] tunables = [tunable(str(self), name) for name, value in self.cfg.params.items() if isinstance(value, Tunable)] + tunables += [self.when] if isinstance(self.cfg.when, Tunable) else [] return (*(selector for selector in self.writes if not selector.scene), *state, *tunables) @@ -542,8 +550,9 @@ def _compile_schedule( # provide the commands, quantities, and term state it reads. entries = {entry.path: entry for entry in schedule} providers = {selector: entry.path for entry in schedule for selector in entry.provides} + # A use's when is read at the start of a step, which no use of its phase needs to run before. reads = { - path: {providers[selector] for selector in entry.reads if selector in providers} - {path} + path: {providers[selector] for selector in (*entry.reads, entry.when) if selector in providers} - {path} for path, entry in entries.items() } try: @@ -722,6 +731,7 @@ def _compile_term(self, entry: ScheduleEntry, context: CompileContext) -> None: if layout is not None and (layout.ndim != 1 or layout.dtype is not wp.float32): errors.append(f"{entry}: the noise scale '{cfg.noise.scale}' must be a float field of one per world.") + when, when_dtype = self._compile_when(entry, context) if len(errors) > num_errors: return @@ -813,9 +823,37 @@ def _compile_term(self, entry: ScheduleEntry, context: CompileContext) -> None: record=isinstance(cfg, Quantity) and cfg.record, columns=columns, stage=entry.stage, + when=when, + when_dtype=when_dtype, + when_default=cfg.when.default if isinstance(cfg.when, Tunable) else None, ) ) + def _compile_when(self, entry: ScheduleEntry, context: CompileContext) -> tuple[FieldSelector | None, type | None]: + """Resolve the field that switches a use on and off, and its element type, or record why it cannot.""" + cfg, errors = entry.cfg, context.errors + if cfg.when is None: + return None, None + if isinstance(cfg, (Quantity, Action)) or isinstance(cfg, Event) and cfg.mode is not EventMode.INTERVAL: + errors.append( + f"{entry}: only rewards, terminations, observations, commands, and interval events can have a when." + ) + return None, None + if isinstance(cfg.when, Tunable): + if type(cfg.when.default) is not bool: + errors.append(f"{entry}: a tunable when switches the use on or off, so its default must be a bool.") + context.mdp_fields[entry.when] = ArrayLayout(wp.bool, 1, {}) + return entry.when, wp.bool + if cfg.when in entry.writes or cfg.when in entry.provides: + errors.append(f"{entry}: when '{cfg.when}' is written by the use itself, which could not turn it on again.") + return None, None + layout = self._resolve(entry, "when", cfg.when, context) + if layout is None: + return None, None + if layout.ndim != 1 or layout.dtype not in (wp.bool, wp.float32, wp.int32): + errors.append(f"{entry}: when '{cfg.when}' must be a field of one bool, float, or int per world.") + return cfg.when, layout.dtype + def _fields_of(self, selector: FieldSelector | Entity) -> tuple[FieldSelector, ...]: """Return the fields a write covers: a field itself, or the writable fields of a scene entity.""" if not isinstance(selector, Entity): @@ -965,6 +1003,7 @@ def _tuned_values(ops: Mapping[Phase, tuple], errors: list[str]) -> tuple[TunedV for name, default in op.tunables.items() ] values += [TunedValue(f"{op.use}.weight", "reward_weights", op.index)] if op.tunable_weight else [] + values += [TunedValue(f"{op.use}.when", op.when, dtype=wp.bool)] if op.when_default is not None else [] for value in values: if tuned.setdefault(value.path, value) != value: errors.append(f"The world configs tune '{value.path}' differently: tune it in all or none of them.") @@ -1171,6 +1210,8 @@ def _scoped(cfg: object, scope: Mapping[FieldSelector, FieldSelector]) -> object if not isinstance(cfg, TermCfg): return cfg changes = {"inputs": {arg: scope.get(selector, selector) for arg, selector in cfg.inputs.items()}} + if isinstance(cfg.when, FieldSelector): + changes["when"] = scope.get(cfg.when, cfg.when) if isinstance(cfg, Observation) and cfg.noise is not None and cfg.noise.scale is not None: changes["noise"] = replace(cfg.noise, scale=scope.get(cfg.noise.scale, cfg.noise.scale)) return replace(cfg, **changes) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py index fb67f1bcaccf..8a7652f197db 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py @@ -72,6 +72,8 @@ class MDPState: - ``("scratch", op)``: the output of a Python hook in a Warp MDP; - ``("selected", op)``: the worlds that the hook of a timed op, or of an op active in some worlds, acts on; - ``("active", op)``: the worlds where an op is active, for an op that is active in only some; + - ``("on", op)`` and ``("entered", op)``: for an op with ``when``, the worlds where it runs at this step, and + those where it turned on at this step; - ``"interval_worlds"``: the worlds where an interval event that writes scene fields ran in the last ``evaluate``, for an MDP with such events; - ``mdp2.progress_field(task, name)``: the progress of every task, with the internal ``streak`` (steps that a @@ -314,6 +316,7 @@ def describe(self) -> str: details += [f"stream {op.stream}"] if op.stream is not None else [] details += ["torch hooks"] if op.torch_hooks else [] details += [f"during {op.stage}"] if op.stage else [] + details += [f"when {op.when}"] if op.when is not None else [] if op.worlds is not None: first, last = op.worlds[0], op.worlds[-1] contiguous = op.worlds == tuple(range(first, last + 1)) @@ -349,12 +352,16 @@ def state(self, scene_data: SceneData, seed: int = 0) -> MDPState: dtypes = {value.key: value.dtype for value in self.tuned} for op in self.term_ops: # Each world config starts the tunable values of its worlds at its own default. - for name, default in op.tunables.items(): - key = op.inputs[name] + defaults = {op.inputs[name]: default for name, default in op.tunables.items()} + defaults |= {op.when: op.when_default} if op.when_default is not None else {} + for key, default in defaults.items(): if key not in arrays: arrays[key] = self._zeros(self.num_worlds, dtype=dtypes[key]) worlds = slice(None) if op.worlds is None else list(op.worlds) arrays[key].torch[worlds] = torch.tensor(default, dtype=arrays[key].torch.dtype, device=self.device) + if op.when is not None: + arrays["on", op.name] = self._zeros(self.num_worlds, dtype=wp.bool) + arrays["entered", op.name] = self._zeros(self.num_worlds, dtype=wp.bool) for subset, indices in self.subsets.items(): arrays[subset] = ProxyArray(wp.array(indices, dtype=wp.int32, device=self.device)) # State belongs to the use: the ops that other world configs define differently share it. @@ -376,6 +383,7 @@ def state(self, scene_data: SceneData, seed: int = 0) -> MDPState: ] noises = [op.observation.noise for op in self.ops[Phase.OBSERVATIONS]] selectors += [noise.scale for noise in noises if noise is not None and noise.scale is not None] + selectors += [op.when for op in self.term_ops if op.when is not None] for selector in selectors: if selector not in arrays: arrays[selector] = scene_data.data(selector.entity, selector.field) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py index e76dd291383c..dfa08681445b 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py @@ -173,6 +173,10 @@ class TermCfg: # Constant keyword arguments, or Tunable values. The MDP keeps the values themselves, not copies: do not change # them after finalizing. params: dict[str, Any] = field(default_factory=dict) + # Run only in the worlds where this field of one value per world is positive, taken at the start of each step: a + # use that does not run outputs zero, and its state, timer, command, and history restart when it turns on. A + # Tunable(True) is a switch per world, mdp2.tunable(use, "when"). Resets prepare the use in every world. + when: FieldSelector | Tunable | None = None @dataclass diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py index 68344f39daac..a344e9ea4f2a 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py @@ -15,7 +15,7 @@ import enum import itertools from collections.abc import Callable, Hashable, Mapping, Sequence -from dataclasses import dataclass +from dataclasses import dataclass, replace from types import MappingProxyType from typing import TYPE_CHECKING, Any @@ -102,18 +102,31 @@ class TermOp: # The task of a sequence that the op belongs to: it runs only while that task runs, and its state, timer, and # command restart when the task starts. Quantities run in every step: they only restart. stage: str | None = None + # A field of one value per world: the op runs, within its task, only where it was positive at the start of the + # step, and restarts where it turns on + when: FieldSelector | None = None + when_dtype: Any = None # Element type of ``when`` + when_default: bool | None = None # Default of a tunable ``when``, which the MDP owns; None for another field @property - def active_key(self) -> Hashable | None: - """Key in :attr:`MDPState.arrays` of the worlds where the op runs at this step, None for every world.""" + def scope_key(self) -> Hashable | None: + """Key in :attr:`MDPState.arrays` of the worlds where the op's task runs at this step, None for every world.""" if self.stage is not None and self.phase is not Phase.QUANTITIES: return progress_field(self.stage, "active") return None if self.worlds is None else ("active", self.name) + @property + def active_key(self) -> Hashable | None: + """Key in :attr:`MDPState.arrays` of the worlds where the op runs at this step, None for every world: its + task's, and with ``when``, those where ``when`` was positive at the start of the step.""" + return self.scope_key if self.when is None else ("on", self.name) + @property def entry_key(self) -> Hashable | None: """Key in :attr:`MDPState.arrays` of the worlds where the op's scope started at this step, in which its state, timer, command, and history restart; None for an op whose scope does not change during an episode.""" + if self.when is not None: + return "entered", self.name return None if self.stage is None else progress_field(self.stage, "entered") def array_key(self, arg: str) -> Hashable: @@ -138,6 +151,7 @@ class StepKind(enum.Enum): RESET_PROGRESS = enum.auto() # Restart the progress of every task for a new episode CLEAR = enum.auto() # Zero the columns of an observation slot that no op writes at this step APPLY_TUNED = enum.auto() # Apply the values tuned for the next reset, in the worlds that have them + SWITCH = enum.auto() # Turn the ops with ``when`` on or off from their field, and mark where they turned on @dataclass(frozen=True) @@ -208,7 +222,7 @@ class Step: """One unit of work on an op, the task trees, or an observation slot, in a runtime function.""" kind: StepKind - op: ActionOp | TermOp | tuple[TaskTree, ...] | ObservationSlot | tuple[TunedValue, ...] + op: ActionOp | TermOp | tuple[TaskTree, ...] | ObservationSlot | tuple[TunedValue, ...] | tuple[TermOp, ...] entry: bool = False # Whether it runs for the worlds whose task of the op just started, rather than for the mask @property @@ -258,7 +272,9 @@ def build_plan( With task trees, ``evaluate`` counts the tasks' completions after the quantities, so that terminations and rewards see this step's progress, and starts the tasks that sequences advanced to after the events, so that the successor observations see them. The terminations, rewards, commands, and events of the step run in the tasks that - ran when it started. With tunable values, ``reset`` first applies the values tuned for it. + ran when it started. Ops with ``when`` switch on or off at the same point, and in ``observe`` for new episodes; + ``reset`` prepares them in all the worlds of their task. With tunable values, ``reset`` first applies the values + tuned for it. """ timed = [op for op in ops[Phase.COMMANDS] + ops[Phase.INTERVAL_EVENTS] if op.timer is not None] observations = tuple(Step(StepKind.COMPUTE, op) for op in ops[Phase.OBSERVATIONS]) @@ -278,6 +294,8 @@ def build_plan( noises = [op.observation.noise for op in ops[Phase.OBSERVATIONS]] read |= {noise.scale for noise in noises if noise is not None and noise.scale is not None} read |= {op.offset for op in ops[Phase.ACTIONS] if isinstance(op, ActionOp)} + switched = tuple(op for phase_ops in ops.values() for op in phase_ops if isinstance(op, TermOp) and op.when) + read |= {op.when for op in switched} observed = [] for op in reversed(ops[Phase.QUANTITIES]): if op.writes[0] in read: @@ -294,16 +312,18 @@ def computed(phase_ops: tuple) -> list[Step]: progress = [Step(StepKind.UPDATE_PROGRESS, trees)] if trees else [] # A task that starts restarts the timers, commands, and state of its ops, as a new episode does. - starts = [] - if any(node.staged for tree in trees for node in tree.nodes): + starts = [Step(StepKind.START_TASKS, trees)] if any(node.staged for tree in trees for node in tree.nodes) else [] + starts += [Step(StepKind.SWITCH, switched)] if switched else [] + if starts: scoped = [op for phase_ops in ops.values() for op in phase_ops if isinstance(op, TermOp) and op.entry_key] - starts = [ - Step(StepKind.START_TASKS, trees), + starts += [ *(Step(StepKind.RESET_TIMER, op, entry=True) for op in timed if op.entry_key), *(Step(StepKind.COMPUTE, op, entry=True) for op in scoped if op.phase is Phase.COMMANDS), *(Step(StepKind.RESET_STATE, op, entry=True) for op in stateful if op.entry_key), ] + # A reset prepares the ops with ``when`` in every world of their task. + unswitched = {op.name: replace(op, when=None) for op in switched} reset_events = [] pending: set[FieldSelector] = set() # Scene fields written since the last commit for op in ops[Phase.RESET_EVENTS]: @@ -335,13 +355,13 @@ def computed(phase_ops: tuple) -> list[Step]: reset=( *([Step(StepKind.APPLY_TUNED, tuned)] if tuned else []), *([Step(StepKind.RESET_PROGRESS, trees)] if trees else []), - *(Step(StepKind.RESET_TIMER, op) for op in timed), + *(Step(StepKind.RESET_TIMER, unswitched.get(op.name, op)) for op in timed), *reset_events, - *(Step(StepKind.COMPUTE, op) for op in ops[Phase.COMMANDS]), + *(Step(StepKind.COMPUTE, unswitched.get(op.name, op)) for op in ops[Phase.COMMANDS]), # State restarts last, from the fields and commands of the new episode. - *(Step(StepKind.RESET_STATE, op) for op in stateful), + *(Step(StepKind.RESET_STATE, unswitched.get(op.name, op)) for op in stateful), ), - observe=(*observed, *observations, *clears), + observe=(*observed, *([Step(StepKind.SWITCH, switched)] if switched else []), *observations, *clears), ) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/runtime.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/runtime.py index 6e1a0a119a7f..9d6237497b73 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/runtime.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/runtime.py @@ -84,7 +84,8 @@ def tune( ``value`` is one value, or one per selected world. ``worlds`` selects worlds by index, slice, or ``bool`` mask, all of them if None. At ``"reset"``, each world takes the value when its episode next resets, so that no episode mixes - two values; at ``"step"``, from the next step on. Each world counts the tunings it applied in + two values; at ``"step"``, from the next step on, except a ``when``, which uses take at the end of a step and so + switch one step later. Each world counts the tunings it applied in :attr:`MDPState.revision`. Writes in place, so captured steps keep replaying. Raises ``KeyError`` for a value that is not tunable. """ diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py index ab72cecbb31c..cf73087bc291 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py @@ -118,6 +118,9 @@ def _run(mdp: MDP, step: Step, call: Call, stepping: bool) -> None: case StepKind.APPLY_TUNED: _apply_tuned(op, state, call.mask.torch) return + case StepKind.SWITCH: + _switch(op, state, None if call.mask is None else call.mask.torch) + return mask = None if call.mask is None else call.mask.torch active = _active(op, state) @@ -268,6 +271,22 @@ def _restart(op: TermOp, state: MDPState, mask: torch.Tensor) -> None: time_left.copy_(torch.where(mask, rng.uniform(state.rng.torch[op.stream], *op.timer, offset=-1), time_left)) +def _switch(ops: tuple[TermOp, ...], state: MDPState, mask: torch.Tensor | None) -> None: + """Turn each op with ``when`` on where its task runs and its field is positive. Stepping (no mask) marks the + worlds where it turned on; observing new episodes, in the masked worlds, marks none, since resets restarted them.""" + for op in ops: + runs = state.arrays[op.when].torch > 0 + if op.scope_key is not None: + runs = runs & state.arrays[op.scope_key].torch + on, entered = state.arrays[op.active_key].torch, state.arrays[op.entry_key].torch + if mask is None: + torch.logical_and(runs, ~on, out=entered) + on.copy_(runs) + else: + entered.masked_fill_(mask, False) + on.copy_(torch.where(mask, runs, on)) + + def _apply_tuned(tuned: tuple[TunedValue, ...], state: MDPState, mask: torch.Tensor) -> None: """Apply the values tuned for the next reset in the reset worlds that have them, and count the tuning.""" pending = state.arrays["pending"].torch diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py index 9c97c7649545..e6ab91c3ae8c 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py @@ -227,6 +227,9 @@ def _emit(code: Fusion, mdp: MDP, steps: Iterable[Step], stepping: bool = False) case StepKind.APPLY_TUNED: _apply_tuned(code, step.op) continue + case StepKind.SWITCH: + _switch(code, step.op, stepping) + continue op = step.op state = [term_state(op.use, name) for name in op.state] active = _active(code, op) @@ -784,6 +787,22 @@ def _reset_progress(code: Fusion, trees: tuple[TaskTree, ...]) -> None: code.world(*_under(_in_tree(trees, tree), *lines), writes=_tree_writes(tree, names)) +def _switch(code: Fusion, ops: tuple[TermOp, ...], stepping: bool) -> None: + """Turn each op with ``when`` on where its task runs and its field is positive. Stepping marks the worlds where it + turned on, whose state restarts; observing new episodes marks none, since resets restarted them.""" + for op in ops: + on, entered = ( + _array(code, op.active_key, wp.array(dtype=wp.bool)), + _array(code, op.entry_key, wp.array(dtype=wp.bool)), + ) + positive = {wp.bool: "", wp.float32: " > 0.0", wp.int32: " > 0"}[op.when_dtype] + runs = f"{_array(code, op.when, wp.array(dtype=op.when_dtype))}[world]{positive}" + if op.scope_key is not None: + runs = f"{_array(code, op.scope_key, wp.array(dtype=wp.bool))}[world] and {runs}" + lines = [f"runs = {runs}", f"{entered}[world] = {'runs and not ' + on + '[world]' if stepping else 'False'}"] + code.world(*lines, f"{on}[world] = runs", writes=[op.active_key, op.entry_key]) + + def _apply_tuned(code: Fusion, tuned: tuple[TunedValue, ...]) -> None: """Apply the values tuned for the next reset in the reset worlds that have them, and count the tuning.""" pending = _array(code, "pending", wp.array(dtype=wp.bool)) diff --git a/source/isaaclab_experimental/test/mdp2/test_mdp2.py b/source/isaaclab_experimental/test/mdp2/test_mdp2.py index bad475768be1..e55d850dc982 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2.py @@ -2036,3 +2036,88 @@ def run(backend: str, capture: bool) -> list[dict[str, torch.Tensor]]: mdp = builder.finalize(device=DEVICE) with pytest.raises(KeyError, match="not tunable: declare it with mdp2.Tunable"): mdp2.tune(mdp, mdp.state(PointMassScene(num_worlds=2, device=DEVICE)), "rewards.scaled.std", 1.0) + + +def test_uses_with_when_run_where_their_field_held_at_the_start_of_the_step(): + """A use with ``when`` follows its field as it was at the start of the step, as rewards follow the task that + governed the action: it outputs zero while off, and its state and history restart where it turns on. A reset + prepares it, and a new episode starts with the field's value at the reset. A tunable ``when`` is a switch.""" + inputs = {"joint_pos": robot.joint_pos} + position = mdp2.Observation(joint_pos, inputs=inputs, history_length=2, when=mdp2.quantities.a) + task = mdp2.TaskCfg( + quantities=above("a"), + observations={"policy": {"position": position}}, + rewards={"gated": mdp2.Reward(accumulate, inputs=inputs, params={"gain": 1.0}, when=mdp2.quantities.a)}, + terminations={ + "switched": mdp2.Termination( + mdp2.mdp.is_positive, inputs={"value": mdp2.quantities.a}, when=mdp2.Tunable(True) + ) + }, + ) + flags = [0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0] # Joint "a" at each step; joint "b" is 0.25 throughout + + def run(backend: str, capture: bool) -> list[dict[str, torch.Tensor]]: + scene = PointMassScene(num_worlds=1, joint_names=("b", "a"), device=DEVICE) + builder = mdp2.MDPBuilder(scene.schema) + builder.add_task(task) + mdp = builder.finalize(device=DEVICE, backend=backend, diagnostics=True) + state, transition = mdp.state(scene), mdp.transition() + mask = ProxyArray(wp.ones(1, dtype=wp.bool, device=DEVICE)) + actions = ProxyArray(wp.zeros((1, 1), dtype=wp.float32, device=DEVICE)) + captured = mdp2.CapturedMDP(mdp, state, transition, actions, mask) if capture else None + env_reset(mdp, state, scene, transition.observations, mask.torch) + joints = scene.data("robot", "joint_pos").torch + history = [] + for step, flag in enumerate(flags, start=1): + joints.copy_(torch.tensor([[0.25, flag]], device=DEVICE)) + if step == 6: + # A new episode, whose reset sees the joint "a" up. + mdp2.reset(mdp, state, mask) if captured is None else captured.reset() + mdp2.observe(mdp, state, transition.observations, mask) if captured is None else captured.observe() + mdp2.tune(mdp, state, "terminations.switched.when", False, at="step") + if captured is None: + mdp2.evaluate(mdp, state, transition) + else: + captured.evaluate() + total = state.arrays[mdp2.term_state("rewards.gated", "total")].torch + history.append( + { + "reward": transition.reward_terms.torch[0, 0].clone(), + "total": total.clone(), + "terminated": transition.terminated.torch.clone(), + "policy": transition.observations["policy"].torch.clone(), + } + ) + return history + + runs = [run(backend, capture) for backend in ("torch", "warp") for capture in (False, True)] + for other in runs[1:]: + for expected, actual in zip(runs[0], other): + for name in expected: + assert torch.equal(expected[name], actual[name]), name + + history = runs[0] + # Off at the start, on from the step after "a" rose, off from the step after it fell, and restarted when back on. + assert [round(step["reward"].item() / 0.02, 6) for step in history[:5]] == [0.0, 0.0, 0.25, 0.5, 0.0] + assert [step["total"].item() for step in history[:5]] == [0.0, 0.0, 0.25, 0.5, 0.5] + # The observation is zero while off, and its history restarts where it turns on: [b, a] per step of history. + policy = [step["policy"][0].tolist() for step in history] + assert policy[0] == [0.0] * 4 and policy[1] == [0.25, 1.0, 0.25, 1.0] and policy[3] == [0.0] * 4 + assert policy[2] == [0.25, 1.0, 0.25, 1.0] + # The reset saw "a" rise: the new episode's first step runs, with the state the reset restarted. + assert history[5]["total"].item() == 0.25 + # The termination ran while its switch was on, and stops from the step boundary after it was tuned off. + assert [step["terminated"].item() for step in history] == [False, True, True, False, False, True, False] + + gate = mdp2.quantities.a + reset_event = mdp2.Event(push_by_adding_velocity, outputs={"joint_vel": robot.joint_vel}, when=gate) + errors = { + "quantities.b": mdp2.TaskCfg(quantities={"b": dataclasses.replace(above("a")["a"], when=gate)}), + "events.push": mdp2.TaskCfg(events={"push": reset_event}), + "commands.c": mdp2.TaskCfg(commands={"c": mdp2.Command(uniform_command, when=mdp2.commands.c)}), + } + for name, part in errors.items(): + builder = mdp2.MDPBuilder(PointMassScene(num_worlds=1, joint_names=("a",)).schema) + builder.add_task(mdp2.compose(mdp2.TaskCfg(quantities=above("a")), part)) + with pytest.raises(ValueError, match=f"{name}: (only rewards|when 'commands.c' is written by the use)"): + builder.validate() From d5b5a66a75c720d69088fa04da26b9e41a1831c0 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 18:27:54 -0800 Subject: [PATCH 05/49] Count repeated completions of MDP2 tasks A task with repeat=True counts each completion, waits until its completion no longer holds, and restarts its progress, its subtasks, and its uses, which start again as they do in a sequence. Episode records hold the count. --- .../changelog.d/mdp2-part2.added.rst | 3 + .../isaaclab_experimental/envs/mdp2_env.py | 8 +- .../isaaclab_experimental/mdp2/builder.py | 16 ++-- .../isaaclab_experimental/mdp2/compiled.py | 8 +- .../isaaclab_experimental/mdp2/config.py | 20 +++-- .../isaaclab_experimental/mdp2/plan.py | 15 +++- .../mdp2/torch_backend.py | 56 +++++++++++-- .../mdp2/warp_backend.py | 81 +++++++++++++++---- .../test/mdp2/test_mdp2.py | 29 +++++++ 9 files changed, 200 insertions(+), 36 deletions(-) diff --git a/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst index 0f96d741f86f..6cee5e9c529c 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst @@ -37,3 +37,6 @@ worlds where a field, such as a mode command, was positive at the start of the step, and restarts its state, timer, command, and history where it turns on. ``when=mdp2.Tunable(True)`` is a switch per world that :func:`~isaaclab_experimental.mdp2.tune` turns on and off. +* Added ``repeat`` to MDP2 tasks: a task that repeats counts its completions as ``mdp2.progress..count``, such as + the drops of an object, and restarts with its subtasks and uses once its completion no longer holds. + :class:`~isaaclab_experimental.envs.MDP2RLEnv` records the count of every episode. diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py index 8a7d4264a60d..064e4f693b1b 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py @@ -579,8 +579,9 @@ def episode_records(self) -> dict[str, torch.Tensor]: The columns are ``world``, ``episode`` (its index among the world's episodes), ``length`` (control steps), ``terminated`` and ``truncated``, the value at the end of each recorded quantity, whether each termination ended it, as ``termination/``, and, for each task with a completion, the episode step at which it was - done (-1 if it was not) as ``progress/`` and the task's score as ``progress/score``, and, for a task with - tunable values, the tunings its world had applied as ``revision``. Rows of episodes that ended in the same + done (-1 if it was not) as ``progress/``, the task's score as ``progress/score``, how often each task that + repeats was done as ``progress//count``, and, for a task with tunable values, the tunings its world had + applied as ``revision``. Rows of episodes that ended in the same step are ordered by world. Waits for the device. """ rows = self._records[: self.episodes_completed] @@ -608,6 +609,9 @@ def _init_episode_budget(self, budget: int) -> None: if completes: self._recorded.append(self.state.arrays[mdp2.progress_field("", "score")].torch) self._record_columns.append("progress/score") + repeats = list(dict.fromkeys(node.path for tree in self.mdp.tasks for node in tree.nodes if node.repeat)) + self._recorded += [self.state.arrays[mdp2.progress_field(path, "count")].torch for path in repeats] + self._record_columns += [f"progress/{path or 'task'}/count" for path in repeats] if self.state.revision is not None: self._recorded.append(self.state.revision.torch) self._record_columns.append("revision") diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py index bca6fe6ce3cb..41e216d6f43e 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py @@ -213,8 +213,10 @@ def _add_task( names: tuple[str, ...], staged: bool, scope: dict[FieldSelector, FieldSelector], + restarts: bool = False, ) -> None: - """Add a task of one world config, its uses with the prefix ``names``, then its subtasks. + """Add a task of one world config, its uses with the prefix ``names``, then its subtasks. ``staged`` is + whether it is part of a sequence, and ``restarts`` whether it or a parent repeats. The subtask of a split runs in worlds of its own, so its uses keep their names: equal uses of the world configs then run once, see :meth:`replicate`. A task reads its own commands and quantities by their names, as a task @@ -226,7 +228,8 @@ def _add_task( if task.done is not None and task.subtasks: raise ValueError(f"Task '{task_path}': a task with subtasks is done when they are; it cannot have a done.") prefix = ".".join(names) - stage = task_path if staged else None + restarts = restarts or task.repeat + stage = task_path if staged or restarts else None scope = { **scope, **{ @@ -237,7 +240,7 @@ def _add_task( for name in uses }, } - self._tasks[task_path] = (replace(task, done=scope.get(task.done, task.done)), staged) + self._tasks[task_path] = (replace(task, done=scope.get(task.done, task.done)), staged or restarts) def add(kind: str, name: str, cfg: object, group: str | None = None, concatenate: bool = True) -> None: # A time limit ends episodes; a task of a sequence can end itself with a termination on its started_at. @@ -272,7 +275,8 @@ def add(kind: str, name: str, cfg: object, group: str | None = None, concatenate for name, subtask in task.subtasks.items(): subtask_names = names if task.mode is TaskMode.SPLIT else (*names, name) - self._add_task(subtask, (*path, name), subtask_names, staged or task.mode is TaskMode.SEQUENCE, scope) + in_sequence = staged or task.mode is TaskMode.SEQUENCE + self._add_task(subtask, (*path, name), subtask_names, in_sequence, scope, restarts) def add_action(self, name: str, action: DirectAction | Action) -> ScheduleEntry: return self._add(ScheduleEntry(("actions", name), action)) @@ -537,7 +541,8 @@ def _compile_schedule( for path, (task, _) in tasks.items(): for name in ("done", "holding", "active"): context.mdp_fields[progress_field(path, name)] = ArrayLayout(wp.bool, 1, {}) - for name in ("done_at", "started_at", *(["stage"] if task.mode is TaskMode.SEQUENCE else [])): + sequence, repeat = ["stage"] if task.mode is TaskMode.SEQUENCE else [], ["count"] if task.repeat else [] + for name in ("done_at", "started_at", *sequence, *repeat): context.mdp_fields[progress_field(path, name)] = ArrayLayout(wp.int32, 1, {}) context.mdp_fields[progress_field(path, "score")] = ArrayLayout(wp.float32, 1, {}) # The time limit compiles to no op, so it is known even when the other uses cannot be ordered. @@ -625,6 +630,7 @@ def _compile_task(self, path: str, tasks: dict[str, tuple[TaskCfg, bool]], conte final=task.final, require=task.require, staged=staged, + repeat=task.repeat, ) def _compile_action(self, entry: ScheduleEntry, context: CompileContext) -> None: diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py index 8a7652f197db..a375bd695a74 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py @@ -77,7 +77,8 @@ class MDPState: - ``"interval_worlds"``: the worlds where an interval event that writes scene fields ran in the last ``evaluate``, for an MDP with such events; - ``mdp2.progress_field(task, name)``: the progress of every task, with the internal ``streak`` (steps that a - task's ``done`` held) and ``entered`` (whether a task of a sequence started at this step); + task's ``done`` held), ``entered`` (whether a task of a sequence started at this step), and, for a task that + repeats, ``spent`` (done, and its completion still holds) and ``restarted`` (it restarted at this step); - ``mdp2.tunable(use, name)``: the value of a tunable param per world, and, for an MDP with tunable values, ``("pending", key)``: the values tuned for the next reset of each array, ``"pending"``: the worlds that have them, and ``"revision"``: the number of tunings applied in each world, see :func:`~.tune`. @@ -291,6 +292,7 @@ def describe(self) -> str: details += [f"require {node.require}"] if node.require is not None else [] details += [f"final {node.final}"] if node.final is not None else [] details += ["staged"] if node.staged else [] + details += ["repeat"] if node.repeat else [] lines.append(f" {node.path or '(root)'} {', '.join(details)}".rstrip()) for phase, ops in self.ops.items(): @@ -473,6 +475,10 @@ def array(path: str, name: str, dtype: type, initial: float = 0) -> np.ndarray: array(node.path, "streak", np.int32) if node.staged: array(node.path, "entered", np.bool_) + if node.repeat: + array(node.path, "count", np.int32) + array(node.path, "spent", np.bool_) + array(node.path, "restarted", np.bool_) values[progress_field(node.path, "active")][worlds] = tree.runs_at_start(node) dtypes = {np.bool_: wp.bool, np.int32: wp.int32, np.float32: wp.float32} diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py index dfa08681445b..feaaa73ce7d1 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py @@ -352,6 +352,9 @@ class TaskCfg: score: float = 1.0 # Weight of the task in its parent's score # Whether the parent is done only while this task's completion holds (True) or does not (False); None to not check final: bool | None = None + # Restart once done and its completion no longer holds, to count how often it happens in an episode, such as drops + # of an object: its progress and uses restart, ``count`` counts the completions, and ``done`` stays true + repeat: bool = False subtasks: dict[str, TaskCfg] = field(default_factory=dict) mode: TaskMode = TaskMode.TOGETHER @@ -364,16 +367,22 @@ class Milestone(TaskCfg): """A task that only has a completion, such as a step of a :func:`sequence`.""" def __init__( - self, done: FieldSelector, hold: int = 1, score: float = 1.0, final: bool | None = None, **fields: Any + self, + done: FieldSelector, + hold: int = 1, + score: float = 1.0, + final: bool | None = None, + repeat: bool = False, + **fields: Any, ) -> None: # The other fields are those of a task, as ``dataclasses.replace`` passes them. - super().__init__(done=done, hold=hold, score=score, final=final, **fields) + super().__init__(done=done, hold=hold, score=score, final=final, repeat=repeat, **fields) -PROGRESS_FIELDS = ("done", "holding", "active", "score", "done_at", "started_at", "stage") +PROGRESS_FIELDS = ("done", "holding", "active", "score", "done_at", "started_at", "stage", "count") """Fields of the progress of a task: whether it is done (once done, until the episode ends), whether its completion -holds at this step, whether it runs, its score in ``[0, 1]``, the episode step at which it was done (-1 before) and at -which it last started, and the subtask that a sequence runs.""" +holds at this step, whether it runs, its score in ``[0, 1]``, the episode step at which it was first done (-1 before) +and at which it last started, the subtask that a sequence runs, and how often a task that repeats was done.""" @dataclass(frozen=True) @@ -442,6 +451,7 @@ def merge(path: tuple[str, ...], target: dict, uses: dict, index: int) -> None: elif cores: core = cores[0] composed.done, composed.hold, composed.score, composed.final = core.done, core.hold, core.score, core.final + composed.repeat = core.repeat composed.subtasks, composed.mode = dict(core.subtasks), core.mode composed.require, composed.worlds = core.require, core.worlds if subtasks: diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py index a344e9ea4f2a..776942598875 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py @@ -177,7 +177,10 @@ class TaskNode: score: float # Weight in its parent's score final: bool | None require: int | None - staged: bool # Whether it runs only in some steps of an episode: a sequence is one of its ancestors + # Whether its uses start or restart during an episode: a sequence is one of its ancestors, or it or one of its + # ancestors repeats + staged: bool + repeat: bool = False @dataclass(frozen=True) @@ -202,6 +205,16 @@ def runs_at_start(self, node: TaskNode) -> bool: first = parent.mode is not TaskMode.SEQUENCE or parent.children[0] == node.path return first and self.runs_at_start(parent) + def restarts(self, node: TaskNode) -> bool: + """Return whether a task restarts while it runs: it or one of its ancestors repeats.""" + parent = self.parent(node) + return node.repeat or parent is not None and self.restarts(parent) + + def descendants(self, node: TaskNode) -> tuple[TaskNode, ...]: + """Return the subtasks of a task, theirs, and so on, parents first.""" + prefix = f"{node.path}." if node.path else "" + return tuple(other for other in self.nodes if other.path.startswith(prefix) and other.path != node.path) + def counted(self, node: TaskNode) -> tuple[TaskNode, ...]: """Return the subtasks of a task that count towards its completion: those that have one.""" return tuple(self.node(child) for child in node.children if child in self.completes) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py index cf73087bc291..5f294cdbf379 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py @@ -351,7 +351,9 @@ def _update_progress(trees: tuple[TaskTree, ...], state: MDPState) -> None: if node.mode is TaskMode.SEQUENCE: stage = field("stage") current = done_children.gather(1, stage.long().clamp(max=len(counted) - 1)[:, None])[:, 0] - stage.add_((active & ~done & (stage < len(counted)) & current).int()) + # A sequence that repeats advances again once it restarted. + finished = field("spent") if node.repeat else done + stage.add_((active & ~finished & (stage < len(counted)) & current).int()) complete = (stage == len(counted)) & finals holding.copy_(held[:, -1]) else: @@ -359,10 +361,41 @@ def _update_progress(trees: tuple[TaskTree, ...], state: MDPState) -> None: complete = (done_children.sum(1) >= required) & finals holding.copy_(held.sum(1) >= required) - started = active & ~done & complete - field("done_at").copy_(torch.where(started, length, field("done_at"))) - done.logical_or_(started) + if node.repeat: + _repeat(state, tree, node, complete, length) + else: + started = active & ~done & complete + field("done_at").copy_(torch.where(started, length, field("done_at"))) + done.logical_or_(started) score.copy_(_score(state, tree, node) if node.done is None else done.float()) + if node.repeat: + # A task that repeats keeps the score of being done once it was. + score.copy_(torch.where(done, 1.0, score)) + + +def _repeat(state: MDPState, tree: TaskTree, node, complete: torch.Tensor, length: torch.Tensor) -> None: + """Count the completions of a task that repeats, and restart it, with its subtasks' progress, once its completion + no longer holds.""" + field = functools.partial(_progress, state, tree, node.path) + active, done, spent = field("active"), field("done"), field("spent") + counted = active & complete & ~spent + spent.logical_or_(counted) + field("count").add_(counted.int()) + first = counted & ~done + field("done_at").copy_(torch.where(first, length, field("done_at"))) + done.logical_or_(first) + restarted = field("restarted") + torch.logical_and(active & spent, ~field("holding"), out=restarted) + spent.logical_and_(~restarted) + initial = {"done": False, "holding": False, "done_at": -1, "score": 0.0, "stage": 0, "streak": 0, "count": 0} + initial["spent"] = False + if node.mode is TaskMode.SEQUENCE: + field("stage").masked_fill_(restarted, 0) + for child in tree.descendants(node): + for name, value in initial.items(): + key = progress_field(child.path, name) + if key in state.arrays: + state.arrays[key].torch[tree.worlds.start : tree.worlds.stop].masked_fill_(restarted, value) def _score(state: MDPState, tree: TaskTree, node) -> torch.Tensor: @@ -383,13 +416,19 @@ def _start_tasks(trees: tuple[TaskTree, ...], state: MDPState) -> None: if not node.staged: continue parent = tree.parent(node) - runs = _progress(state, tree, parent.path, "active").clone() - if parent.mode is TaskMode.SEQUENCE: + active, entered = _progress(state, tree, node.path, "active"), _progress(state, tree, node.path, "entered") + runs = torch.ones_like(active) if parent is None else _progress(state, tree, parent.path, "active").clone() + if parent is not None and parent.mode is TaskMode.SEQUENCE: # The last task keeps running once it is done. stage = _progress(state, tree, parent.path, "stage").clamp(max=len(parent.children) - 1) runs &= stage == parent.children.index(node.path) - active, entered = _progress(state, tree, node.path, "active"), _progress(state, tree, node.path, "entered") - torch.logical_and(runs, ~active, out=entered) + # A task starts where it did not run, and restarts with a parent that started or a repeat. + fresh = ~active + if parent is not None and tree.restarts(parent): + fresh = fresh | _progress(state, tree, parent.path, "entered") + if node.repeat: + fresh = fresh | _progress(state, tree, node.path, "restarted") + torch.logical_and(runs, fresh, out=entered) started = _progress(state, tree, node.path, "started_at") started.copy_(torch.where(entered, length, started)) active.copy_(runs) @@ -402,6 +441,7 @@ def _reset_progress(trees: tuple[TaskTree, ...], state: MDPState, mask: torch.Te for node in tree.nodes: initial = {"done": False, "holding": False, "done_at": -1, "started_at": 0, "score": 0.0, "stage": 0} initial |= {"streak": 0, "entered": False, "active": tree.runs_at_start(node)} + initial |= {"count": 0, "spent": False, "restarted": False} for name, value in initial.items(): key = progress_field(node.path, name) if key in state.arrays: diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py index e6ab91c3ae8c..caaea0c619eb 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py @@ -630,7 +630,10 @@ def _under(conditions: Sequence[str], *lines: str) -> list[str]: return nested + [f"{' ' * len(conditions)}{line}" for line in lines] -_PROGRESS_TYPES = {"done": wp.bool, "holding": wp.bool, "active": wp.bool, "entered": wp.bool, "score": wp.float32} +_PROGRESS_TYPES = { + **dict.fromkeys(("done", "holding", "active", "entered", "spent", "restarted"), wp.bool), + "score": wp.float32, +} """Element types of the progress fields other than the ``int32`` ones.""" @@ -658,7 +661,7 @@ def _update_progress(code: Fusion, trees: tuple[TaskTree, ...]) -> None: for node in reversed(tree.nodes): if node.path in tree.completes: lines += _node_progress(code, tree, node, length) - names = ("done", "holding", "score", "done_at", "streak", "stage") + names = ("done", "holding", "score", "done_at", "streak", "stage", "count", "spent", "restarted") if lines: code.world(*_under(_in_tree(trees, tree), *lines), writes=_tree_writes(tree, names)) @@ -689,9 +692,10 @@ def _node_progress(code: Fusion, tree: TaskTree, node: TaskNode, length: str) -> finals = [final for final, child_node in zip(finals, counted) if child_node.final is not None] finals = " and ".join(finals) or "True" if node.mode is TaskMode.SEQUENCE: - # One subtask at most per step: the next one starts at the step after. + # One subtask at most per step: the next one starts at the step after. A sequence that repeats advances + # again once it restarted. stage = field("stage") - lines = [f"if {active} and not {done}:"] + lines = [f"if {active} and not {field('spent') if node.repeat else done}:"] for k, child in enumerate(children): lines += [ f" {'if' if k == 0 else 'elif'} {stage} == {k} and {child('done')}:", @@ -712,13 +716,18 @@ def _node_progress(code: Fusion, tree: TaskTree, node: TaskNode, length: str) -> f"{holding} = held >= {required}", ] - lines += [ - f"if {active} and not {done} and complete:", - f" {done} = True", - f" {field('done_at')} = {length}", - ] + if node.repeat: + lines += _repeat(code, tree, node, length) + else: + lines += [ + f"if {active} and not {done} and complete:", + f" {done} = True", + f" {field('done_at')} = {length}", + ] if node.done is not None: return [*lines, f"{score} = wp.where({done}, 1.0, 0.0)"] + # A task that repeats keeps the score of being done once it was. + kept = [f"{score} = wp.where({done}, 1.0, {score})"] if node.repeat else [] counted = tree.counted(node) scores = [_progress(code, child.path, "score") for child in counted] @@ -734,9 +743,46 @@ def _node_progress(code: Fusion, tree: TaskTree, node: TaskNode, length: str) -> f" pick = {1 << k}", ] lines += ["taken = taken | pick", "total = total + best"] - return [*lines, f"{score} = total / {float(node.require)}"] + return [*lines, f"{score} = total / {float(node.require)}", *kept] weights = [child.score / sum(child.score for child in counted) for child in counted] - return [*lines, f"{score} = " + " + ".join(f"{weight!r} * {child}" for weight, child in zip(weights, scores))] + weighted = " + ".join(f"{weight!r} * {child}" for weight, child in zip(weights, scores)) + return [*lines, f"{score} = {weighted}", *kept] + + +def _repeat(code: Fusion, tree: TaskTree, node: TaskNode, length: str) -> list[str]: + """Return the statements that count the completions of a task that repeats, and restart it, with its subtasks' + progress, once its completion no longer holds.""" + field = functools.partial(_progress, code, node.path) + spent, done = field("spent"), field("done") + restart = [*([f"{field('stage')} = 0"] if node.mode is TaskMode.SEQUENCE else [])] + for child in tree.descendants(node): + restart += _restart_lines(code, child) + return [ + f"if {field('active')} and complete and not {spent}:", + f" {spent} = True", + f" {field('count')} = {field('count')} + 1", + f" if not {done}:", + f" {done} = True", + f" {field('done_at')} = {length}", + f"{field('restarted')} = {field('active')} and {spent} and not {field('holding')}", + f"if {field('restarted')}:", + f" {spent} = False", + *(f" {line}" for line in restart), + ] + + +def _restart_lines(code: Fusion, node: TaskNode) -> list[str]: + """Return the statements that restart the progress of a task, but whether and since when it runs.""" + field = functools.partial(_progress, code, node.path) + return [ + f"{field('done')} = False", + f"{field('holding')} = False", + f"{field('done_at')} = -1", + f"{field('score')} = 0.0", + *([f"{field('stage')} = 0"] if node.mode is TaskMode.SEQUENCE else []), + *([f"{field('streak')} = 0"] if node.done is not None else []), + *([f"{field('count')} = 0", f"{field('spent')} = False"] if node.repeat else []), + ] def _start_tasks(code: Fusion, trees: tuple[TaskTree, ...]) -> None: @@ -748,15 +794,19 @@ def _start_tasks(code: Fusion, trees: tuple[TaskTree, ...]) -> None: if not node.staged: continue parent = tree.parent(node) - runs = _progress(code, parent.path, "active") - if parent.mode is TaskMode.SEQUENCE: + runs = "True" if parent is None else _progress(code, parent.path, "active") + if parent is not None and parent.mode is TaskMode.SEQUENCE: # The last task keeps running once it is done. stage = f"wp.min({_progress(code, parent.path, 'stage')}, {len(parent.children) - 1})" runs = f"{runs} and {stage} == {parent.children.index(node.path)}" field = functools.partial(_progress, code, node.path) + # A task starts where it did not run, and restarts with a parent that started or a repeat. + fresh = [f"not {field('active')}"] + fresh += [_progress(code, parent.path, "entered")] if parent is not None and tree.restarts(parent) else [] + fresh += [field("restarted")] if node.repeat else [] lines += [ f"runs = {runs}", - f"{field('entered')} = runs and not {field('active')}", + f"{field('entered')} = runs and {fresh[0] if len(fresh) == 1 else '(' + ' or '.join(fresh) + ')'}", f"if {field('entered')}:", f" {field('started_at')} = {length}", f"{field('active')} = runs", @@ -782,8 +832,11 @@ def _reset_progress(code: Fusion, trees: tuple[TaskTree, ...]) -> None: *([f"{field('stage')} = 0"] if node.mode is TaskMode.SEQUENCE else []), *([f"{field('streak')} = 0"] if node.done is not None else []), *([f"{field('entered')} = False"] if node.staged else []), + *([f"{field('count')} = 0", f"{field('spent')} = False"] if node.repeat else []), + *([f"{field('restarted')} = False"] if node.repeat else []), ] names = ("done", "holding", "done_at", "started_at", "score", "active", "stage", "streak", "entered") + names += ("count", "spent", "restarted") code.world(*_under(_in_tree(trees, tree), *lines), writes=_tree_writes(tree, names)) diff --git a/source/isaaclab_experimental/test/mdp2/test_mdp2.py b/source/isaaclab_experimental/test/mdp2/test_mdp2.py index e55d850dc982..5ea5d2f6e6f6 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2.py @@ -2121,3 +2121,32 @@ def run(backend: str, capture: bool) -> list[dict[str, torch.Tensor]]: builder.add_task(mdp2.compose(mdp2.TaskCfg(quantities=above("a")), part)) with pytest.raises(ValueError, match=f"{name}: (only rewards|when 'commands.c' is written by the use)"): builder.validate() + + +def test_tasks_that_repeat_count_each_time_they_are_done(): + """A task that repeats counts its completions, waits until its completion no longer holds, and then restarts: its + uses restart, as when a task of a sequence starts, and its ``done`` stays true from the first time.""" + held = mdp2.Reward(accumulate, inputs={"joint_pos": robot.joint_pos}, params={"gain": 1.0}) + task = mdp2.compose( + mdp2.TaskCfg(quantities=above("a")), + drops=mdp2.TaskCfg(rewards={"held": held}, done=mdp2.quantities.a, repeat=True), + ) + # Joint "a" rises at steps 2, 5, and 8; joint "b", which the reward sums, is 0.25 throughout. + steps = [[0.25, a] for a in (0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0)] + history = check_progress(task, steps, joints=("b", "a")) + assert [step["drops.count"].item() for step in history] == [0, 1, 1, 1, 2, 2, 2, 3] + assert history[-1]["drops.done_at"].item() == 2 and history[-1]["done_at"].item() == 2 + assert all(step["done"].item() for step in history[1:]) + # The reward's state restarts at the end of the steps where "a" fell after a completion. + total = [step[str(mdp2.term_state("rewards.drops.held", "total"))].item() for step in history] + assert total == [0.25, 0.5, 0.75, 0.0, 0.25, 0.0, 0.25, 0.5] + + # A sequence that repeats restarts its subtasks: each up-then-down cycle counts once. + cycle = dataclasses.replace( + mdp2.sequence(up=mdp2.Milestone(mdp2.quantities.a), down=mdp2.Milestone(mdp2.quantities.b)), repeat=True + ) + task = mdp2.compose(mdp2.TaskCfg(quantities=above("a", "b")), cycle) + history = check_progress(task, [[1.0, 0.0], [0.0, 1.0], [0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]) + assert [step["count"].item() for step in history] == [0, 1, 1, 1, 2] + assert [step["up.done"].item() for step in history] == [True, True, False, True, True] + assert [step["stage"].item() for step in history] == [1, 2, 0, 1, 2] From 7e50cf44e94ffe0a6bde319d5e20abcc86d77512 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 18:34:23 -0800 Subject: [PATCH 06/49] Give MDP2 actions name slots and a live mask Actions of the same name share their columns across world configs, as observations do, and the last actions zero the columns that a world does not take at a step, so every term reads one last-actions field. MDP.action_mask gives the columns each world takes. Tasks with one world config compile to the same kernels. --- .../changelog.d/mdp2-part2.changed.rst | 4 + .../isaaclab_experimental/mdp2/builder.py | 124 ++++++++++++------ .../isaaclab_experimental/mdp2/compiled.py | 26 ++-- .../isaaclab_experimental/mdp2/plan.py | 29 ++-- .../mdp2/torch_backend.py | 15 ++- .../mdp2/warp_backend.py | 28 ++-- .../test/mdp2/test_mdp2.py | 17 +-- 7 files changed, 161 insertions(+), 82 deletions(-) diff --git a/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst b/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst index abf206a6a438..c8dc10d0ad80 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst @@ -4,3 +4,7 @@ ``task=mdp2.split(walk=WALK, stand=STAND, worlds={"walk": 3072, "stand": 1024})``. * **Breaking:** Changed the observation columns of MDP2 world configs: observations of the same name share their columns, as wide as the widest, and each name has its own, instead of each world config's observations starting at the first column. +* **Breaking:** Changed the action columns of MDP2 world configs: actions of the same name share their columns, as wide + as the widest, as observations do, and the last actions hold zero in the columns a world does not take, which + :meth:`~isaaclab_experimental.mdp2.MDP.action_mask` gives. This replaces the narrow copies of the last actions and + ``MDP.narrow_action_dims``. diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py index 41e216d6f43e..176fdcae4c31 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py @@ -54,6 +54,7 @@ ) from .plan import ( ActionOp, + ActionSlot, ObservationOutput, ObservationSlot, Segment, @@ -158,8 +159,8 @@ class CompileContext: } ) subsets: dict[SubsetSelector, tuple[int, ...]] = field(default_factory=dict) - action_dim: int = 0 tasks: tuple[TaskNode, ...] = () # The task tree, parents first, if the MDP tracks progress + modes: dict[str, TaskMode] = field(default_factory=dict) # How the subtasks of each task run, by path class MDPBuilder: @@ -427,25 +428,22 @@ def _compile( for task, _ in tasks.values() ) + # The actions of every world config compile first: they share one layout, a range of columns per name, which + # sizes the last actions that the other uses read. contexts, time_limits = [], set() - for index, (schedule, tasks, worlds) in enumerate(configs): - context, time_limit = self._compile_schedule(schedule, tasks if tracked else {}, backend) - prefix = f"world config {index} ({worlds.start}-{worlds.stop - 1}): " if len(configs) > 1 else "" - errors += [prefix + error for error in context.errors] + for schedule, tasks, _ in configs: + context, time_limit = self._compile_actions(schedule, tasks if tracked else {}, backend) contexts.append(context) time_limits.add(time_limit) + action_dim = _allocate_action_slots(contexts) + for index, ((schedule, tasks, worlds), context) in enumerate(zip(configs, contexts)): + context.mdp_fields[last_action] = ArrayLayout(wp.float32, 2, {"actions": action_dim}, (action_dim,)) + self._compile_schedule(schedule, tasks if tracked else {}, context) + prefix = f"world config {index} ({worlds.start}-{worlds.stop - 1}): " if len(configs) > 1 else "" + errors += [prefix + error for error in context.errors] if len(time_limits) > 1: errors.append(f"The world configs must share one time limit, found {sorted(map(str, time_limits))} s.") - # The last actions are padded to the widest world config: the others read a copy with their own columns. - action_dim = max(context.action_dim for context in contexts) - for context in contexts: - for phase, ops in context.ops.items(): - if phase is Phase.ACTIONS or context.action_dim == action_dim: - continue - for k, op in enumerate(ops): - if last_action in op.inputs.values(): - ops[k] = replace(op, action_dim=context.action_dim) field_shapes = {} for context in contexts: for op in context.ops[Phase.COMMANDS] + context.ops[Phase.QUANTITIES]: @@ -462,6 +460,7 @@ def _compile( raise ValueError("Invalid MDP:\n " + "\n ".join(errors)) ops = _merge_ops([(context.ops, worlds) for context, worlds in zip(contexts, world_ranges)], self.schema) + action_slots = _action_slots(ops[Phase.ACTIONS]) trees = tuple( TaskTree(worlds, context.tasks, frozenset(_completes(context.tasks))) for context, worlds in zip(contexts, world_ranges) @@ -522,21 +521,25 @@ def _compile( final_observations=final_observations, world_configs=tuple( WorldConfig( - worlds, context.action_dim, MappingProxyType(_used_columns(ops[Phase.OBSERVATIONS], worlds)) + worlds, + max((op.columns.stop for op in context.ops[Phase.ACTIONS]), default=0), + MappingProxyType(_used_columns(ops[Phase.OBSERVATIONS], worlds)), ) for context, worlds in zip(contexts, world_ranges) ), + action_slots=action_slots, tasks=trees, slots=slots, tuned=tuned, ) - def _compile_schedule( + def _compile_actions( self, schedule: tuple[ScheduleEntry, ...], tasks: dict[str, tuple[TaskCfg, bool]], backend: Backend ) -> tuple[CompileContext, float | None]: - """Compile the ops of one world config, and its task tree if it has one, and return them with its episode - length in seconds.""" + """Start compiling one world config with its actions, whose columns are given once those of every world + config are known, see :func:`_allocate_action_slots`. Returns them with its episode length in seconds.""" context = CompileContext(backend, _dependency_errors(schedule)) + context.modes = {path: task.mode for path, (task, _) in tasks.items()} # Terms may read the progress of every task. for path, (task, _) in tasks.items(): for name in ("done", "holding", "active"): @@ -551,8 +554,18 @@ def _compile_schedule( context.errors.append(f"Only one time limit is allowed, found {', '.join(map(str, time_limits))}.") time_limit = time_limits[0].cfg.episode_length_s if time_limits else None - # Actions compile first, for the size of the last action. Every other use compiles after the uses that - # provide the commands, quantities, and term state it reads. + for entry in schedule: + if isinstance(entry.cfg, DirectAction): + self._compile_action(entry, context) + elif isinstance(entry.cfg, Action): + self._compile_term(entry, context) + return context, time_limit + + def _compile_schedule( + self, schedule: tuple[ScheduleEntry, ...], tasks: dict[str, tuple[TaskCfg, bool]], context: CompileContext + ) -> None: + """Compile the uses of one world config other than its actions, and its task tree if it has one.""" + # Every use compiles after the uses that provide the commands, quantities, and term state it reads. entries = {entry.path: entry for entry in schedule} providers = {selector: entry.path for entry in schedule for selector in entry.provides} # A use's when is read at the start of a step, which no use of its phase needs to run before. @@ -568,15 +581,10 @@ def _compile_schedule( f"Uses read each other's fields in a cycle: {', '.join(map('.'.join, error.args[1]))}. A use is" " compiled after the uses whose commands, quantities, and state it reads." ) - return context, time_limit + return - actions = [entry for entry in schedule if entry.phase is Phase.ACTIONS] - for entry in (*actions, *(entries[path] for path in order if entries[path].phase is not Phase.ACTIONS)): - if isinstance(entry.cfg, TimeLimit): - continue - if isinstance(entry.cfg, DirectAction): - self._compile_action(entry, context) - else: + for entry in (entries[path] for path in order): + if entry.phase is not Phase.ACTIONS and not isinstance(entry.cfg, TimeLimit): self._compile_term(entry, context) # An offset may be a field of the MDP, such as a quantity, which exists once its use is compiled. @@ -598,7 +606,6 @@ def _compile_schedule( ops[k] = replace(op, index=k) context.tasks = tuple(self._compile_task(path, tasks, context) for path in tasks) - return context, time_limit def _compile_task(self, path: str, tasks: dict[str, tuple[TaskCfg, bool]], context: CompileContext) -> TaskNode: """Compile a task of the tree, or record why its progress cannot be tracked.""" @@ -660,13 +667,10 @@ def _compile_action(self, entry: ScheduleEntry, context: CompileContext) -> None if op.target == cfg.target and (op.subset is None or elements & written): context.errors.append(f"{entry}: '{cfg.target}' is already written by '{op.name}'.") - columns = slice(context.action_dim, context.action_dim + len(elements)) - context.action_dim = columns.stop - context.mdp_fields[last_action] = ArrayLayout( - wp.float32, 2, {"actions": context.action_dim}, (context.action_dim,) - ) - action = ActionOp(str(entry), cfg.target, columns, cfg.scale, cfg.offset, subset=cfg.subset) - context.ops[Phase.ACTIONS].append(action) + # Its columns of the action are given with those of every world config, by name. + slot = entry.name or entry.path[-1] + action = ActionOp(str(entry), cfg.target, slice(0, len(elements)), cfg.scale, cfg.offset, subset=cfg.subset) + context.ops[Phase.ACTIONS].append(replace(action, slot=slot)) def _compile_term(self, entry: ScheduleEntry, context: CompileContext) -> None: """Compile a term use into an op, or record why it cannot be compiled.""" @@ -828,6 +832,7 @@ def _compile_term(self, entry: ScheduleEntry, context: CompileContext) -> None: log=isinstance(cfg, Quantity) and cfg.log, record=isinstance(cfg, Quantity) and cfg.record, columns=columns, + slot=(entry.name or entry.path[-1]) if isinstance(cfg, Action) else "", stage=entry.stage, when=when, when_dtype=when_dtype, @@ -937,10 +942,8 @@ def _allocate_columns( output = ObservationOutput(entry.buffer, columns, cfg.noise, cfg.clip, cfg.scale, cfg.history_length) return replace(output, slot=entry.name or entry.path[-1]), None if isinstance(cfg, Action): - columns = slice(context.action_dim, context.action_dim + output_shape[0]) - context.action_dim = columns.stop - context.mdp_fields[last_action] = ArrayLayout(wp.float32, 2, {"actions": columns.stop}, (columns.stop,)) - return None, columns + # Its columns of the action are given with those of every world config, by name. + return None, slice(0, output_shape[0]) return None, None @@ -1236,6 +1239,47 @@ def _completes(nodes: tuple[TaskNode, ...]) -> set[str]: return completes +def _allocate_action_slots(contexts: list[CompileContext]) -> int: + """Give the action ops of every world config their columns: one slot per name, in order, as wide as its widest + op, each op taking its first columns. Returns the number of columns. + + Ops of different world configs or of different tasks of a sequence may share a slot, since they never take it in + the same world at the same step; other ops of the same name are errors. + """ + widths: dict[str, int] = {} + for context in contexts: + named: dict[str, list] = {} + for op in context.ops[Phase.ACTIONS]: + named.setdefault(op.slot, []).append(op) + widths[op.slot] = max(widths.get(op.slot, 0), op.columns.stop) + for name, slot_ops in named.items(): + for first, second in itertools.combinations(slot_ops, 2): + if not _exclusive(first, second, context.modes): + context.errors.append( + f"'{first.name}' and '{second.name}' share the columns of the action '{name}', so they must run" + " in different world configs or in different tasks of a sequence." + ) + starts = dict(zip(widths, itertools.accumulate(widths.values(), initial=0))) + for context in contexts: + actions = context.ops[Phase.ACTIONS] + for k, op in enumerate(actions): + start = starts[op.slot] + actions[k] = replace(op, columns=slice(start, start + op.columns.stop)) + return sum(widths.values()) + + +def _action_slots(ops: tuple[ActionOp | TermOp, ...]) -> tuple[ActionSlot, ...]: + """Return the slots of the merged action ops, in column order.""" + named: dict[str, list] = {} + for op in ops: + named.setdefault(op.slot, []).append(op) + slots = [] + for name, slot_ops in named.items(): + start, stop = slot_ops[0].columns.start, max(op.columns.stop for op in slot_ops) + slots.append(ActionSlot(name, slice(start, stop), tuple(slot_ops))) + return tuple(sorted(slots, key=lambda slot: slot.columns.start)) + + def _allocate_slots( ops: tuple[TermOp, ...], modes: Mapping[str, TaskMode], errors: list[str] ) -> tuple[tuple[TermOp, ...], tuple[ObservationSlot, ...], dict[str, int], dict[str, tuple[tuple[int, ...], type]]]: diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py index a375bd695a74..b22367076123 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py @@ -35,6 +35,7 @@ ) from .plan import ( ActionOp, + ActionSlot, ExecutionPlan, Launches, ObservationSlot, @@ -63,8 +64,6 @@ class MDPState: - a field or subset selector: the selected fields of the scene, the fields of the MDP (``mdp2.last_action``, ``mdp2.commands.``, ...), and the state of every term use, ``mdp2.term_state(use, name)``; - - ``(mdp2.last_action, action_dim)``: the first columns of the last actions, which the terms of a world config - with ``action_dim`` actions read if other world configs have more; - ``"rng"``: the random streams, ``(num_streams, num_worlds)``, see :mod:`.rng`; - ``"reward_weights"``: ``(num_worlds, num_rewards)``, which may change while the MDP runs, also in a CUDA graph; - ``("timer", op)``: seconds left per world, for a timed op; @@ -134,7 +133,7 @@ class WorldConfig: """Worlds that run one task config, and the columns of the padded buffers that its terms use.""" worlds: range - action_dim: int # Columns of the actions it uses, from the first; the others are padding + action_dim: int # Columns of the action up to the last that it uses; see MDP.action_mask for those it uses observation_dims: Mapping[str, int] # Columns of each observation group it uses, from the first @@ -172,6 +171,7 @@ class MDP: # The task tree of each world config, if the MDP tracks progress: some task has a completion or a sequence tasks: tuple[TaskTree, ...] = () slots: tuple[ObservationSlot, ...] = () # Observation slots that some op writes only in some steps + action_slots: tuple[ActionSlot, ...] = () # The columns of the action of each name, in order tuned: tuple[TunedValue, ...] = () # Values declared Tunable, which tune changes launches: Launches | None = None # Set by finalize, None for an MDP that was only validated @@ -179,11 +179,6 @@ class MDP: def num_worlds(self) -> int: return self.schema.num_worlds - @property - def narrow_action_dims(self) -> tuple[int, ...]: - """Action counts of the world configs with fewer actions than the widest.""" - return tuple(sorted({config.action_dim for config in self.world_configs} - {self.action_dim})) - @property def step_dt(self) -> float: return self.schema.step_dt @@ -253,6 +248,19 @@ def spec(self) -> dict[str, tuple[ObservationColumns, ...]]: for buffer, slots in named.items() } + def action_mask(self, state: MDPState) -> torch.Tensor: + """Return which columns of the action each world takes at this step, ``(num_worlds, action_dim)`` bool. + + The others pad an action to the widest of its name, or belong to actions of other world configs or of tasks of + a sequence that do not run: the MDP ignores them, and stores them as zero in the last actions. Torch operations + only, so it can run in a graph. + """ + mask = torch.zeros(self.num_worlds, self.action_dim, dtype=torch.bool, device=self.device) + for op in self.ops[Phase.ACTIONS]: + taken = True if op.active_key is None else state.arrays[op.active_key].torch[:, None] + mask[:, op.columns] |= taken + return mask + def observation_mask(self, state: MDPState, buffer: str) -> torch.Tensor: """Return which columns of an observation buffer each world writes at this step, ``(num_worlds, dim)`` bool. @@ -346,8 +354,6 @@ def state(self, scene_data: SceneData, seed: int = 0) -> MDPState: episode_length: self._zeros(self.num_worlds, dtype=wp.int32), terminated: self._zeros(self.num_worlds, dtype=wp.bool), } - for action_dim in self.narrow_action_dims: - arrays[last_action, action_dim] = self._zeros(self.num_worlds, action_dim) arrays |= self._progress_arrays() for op in self.ops[Phase.COMMANDS] + self.ops[Phase.QUANTITIES]: arrays[op.writes[0]] = self._zeros(self.num_worlds, *op.shape) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py index 776942598875..6eccd284f092 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py @@ -19,7 +19,7 @@ from types import MappingProxyType from typing import TYPE_CHECKING, Any -from .config import Entity, FieldSelector, Phase, SubsetSelector, TaskMode, UniformNoise, last_action, progress_field +from .config import Entity, FieldSelector, Phase, SubsetSelector, TaskMode, UniformNoise, progress_field from .terms import State if TYPE_CHECKING: @@ -35,11 +35,12 @@ class ActionOp: name: str target: FieldSelector - columns: slice # Columns of the action + columns: slice # Columns of the action: the first of its slot, as many as it writes scale: float offset: float | FieldSelector # A field gives an offset per element worlds: tuple[int, ...] | None = None # Worlds where the op is active, None for every world subset: SubsetSelector | None = None # Elements of the target it writes, None for all of them + slot: str = "" # Name of its columns of the action, which the actions of the same name share @property def active_key(self) -> Hashable | None: @@ -97,8 +98,7 @@ class TermOp: record: bool = False # Quantities: whether the environment records it at the end of every episode columns: slice | None = None # Actions: the columns of the action that the term takes worlds: tuple[int, ...] | None = None # Worlds where the op is active, None for every world - # Actions of its world config, if it reads the last actions and other world configs have more - action_dim: int | None = None + slot: str = "" # Actions: the name of its columns of the action, which the actions of the same name share # The task of a sequence that the op belongs to: it runs only while that task runs, and its state, timer, and # command restart when the task starts. Quantities run in every step: they only restart. stage: str | None = None @@ -131,10 +131,7 @@ def entry_key(self) -> Hashable | None: def array_key(self, arg: str) -> Hashable: """Return the key in :attr:`MDPState.arrays` of the array that the input ``arg`` reads.""" - selector = self.inputs[arg] - if selector == last_action and self.action_dim is not None: - return last_action, self.action_dim - return selector + return self.inputs[arg] class StepKind(enum.Enum): @@ -220,6 +217,22 @@ def counted(self, node: TaskNode) -> tuple[TaskNode, ...]: return tuple(self.node(child) for child in node.children if child in self.completes) +@dataclass(frozen=True) +class ActionSlot: + """Columns of the action that the action ops of one name take, each op the first ones, in its worlds and steps.""" + + name: str + columns: slice + ops: tuple[ActionOp | TermOp, ...] + + @property + def partial(self) -> bool: + """Whether some world does not take all of its columns at some step: no op runs in every world and step + with as many columns as the slot.""" + size = self.columns.stop - self.columns.start + return not any(op.active_key is None and op.columns.stop - op.columns.start == size for op in self.ops) + + @dataclass(frozen=True) class ObservationSlot: """Columns of an observation buffer that several ops write, or that an op writes only in some steps.""" diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py index 5f294cdbf379..f32ced08ec9c 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py @@ -14,7 +14,7 @@ from . import rng from .compiled import MDP, MDPState -from .config import FieldSelector, Phase, TaskMode, last_action, progress_field, term_state, terminated +from .config import FieldSelector, Phase, TaskMode, progress_field, term_state, terminated from .plan import Call, Launch, Launches, ObservationSlot, Step, StepKind, TaskTree, TermOp, TunedValue from .terms import hook_arguments @@ -39,8 +39,15 @@ def _apply_actions(mdp: MDP, call: Call) -> None: """Store the actions as the last actions, and write each action's scaled columns to its target field.""" actions = call.actions.torch call.state.actions.torch.copy_(actions) - for action_dim in mdp.narrow_action_dims: - call.state.arrays[last_action, action_dim].torch.copy_(actions[:, :action_dim]) + # The last actions keep the columns that each world takes at this step, and zero the others. + for slot in (slot for slot in mdp.action_slots if slot.partial): + columns = torch.arange(slot.columns.start, slot.columns.stop, device=mdp.device) + covered = torch.zeros(mdp.num_worlds, len(columns), dtype=torch.bool, device=mdp.device) + for op in slot.ops: + active = _active(op, call.state) + width = columns < op.columns.stop + covered |= width if active is None else active.torch[:, None] & width + call.state.actions.torch[:, slot.columns].masked_fill_(~covered, 0.0) for step in mdp.plan.apply_actions: op = step.op @@ -87,8 +94,6 @@ def _begin_reset(mdp: MDP, call: Call) -> None: rng.advance(call.state.rng.torch, mask) call.state.episode_length.torch.masked_fill_(mask, 0) call.state.actions.torch.masked_fill_(mask[:, None], 0.0) - for action_dim in mdp.narrow_action_dims: - call.state.arrays[last_action, action_dim].torch.masked_fill_(mask[:, None], 0.0) def _active(op, state: MDPState): diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py index caaea0c619eb..d7a71896fe19 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py @@ -99,13 +99,20 @@ def _apply_actions(mdp: MDP) -> tuple[Callable[[Call], None], ...]: code = Fusion("apply_actions", mdp.num_worlds, mdp.device) actions = code.argument("actions", wp.array2d(dtype=wp.float32), lambda call: call.actions.warp) last_actions = _array(code, last_action, wp.array2d(dtype=wp.float32)) - code.elements( - (mdp.action_dim,), f"{last_actions}[world, element] = {actions}[world, element]", writes=[last_action] - ) - for action_dim in mdp.narrow_action_dims: - key = last_action, action_dim - narrow = _array(code, key, wp.array2d(dtype=wp.float32)) - code.elements((action_dim,), f"{narrow}[world, element] = {actions}[world, element]", writes=[key]) + # The last actions keep the columns that each world takes at this step, and zero the others. + ignored = [] + for slot in (slot for slot in mdp.action_slots if slot.partial): + covers = [] + for op in slot.ops: + cover = f"element < {op.columns.stop}" + covers.append(cover if op.active_key is None else f"({_runs(code, op)} and {cover})") + start, stop = slot.columns.start, slot.columns.stop + ignored += [f"if element >= {start} and element < {stop} and not ({' or '.join(covers)}):", " value = 0.0"] + if ignored: + copy = [f"value = {actions}[world, element]", *ignored, f"{last_actions}[world, element] = value"] + else: + copy = [f"{last_actions}[world, element] = {actions}[world, element]"] + code.elements((mdp.action_dim,), *copy, writes=[last_action]) # Fields with more dimensions per world are flattened; joint fields are views of the solver state that may be # strided, so they are passed as they are. @@ -189,13 +196,12 @@ def _evaluate(mdp: MDP) -> tuple[Callable[[Call], None], ...]: def _reset(mdp: MDP) -> tuple[Callable[[Call], None], ...]: code = Fusion("reset", mdp.num_worlds, mdp.device, _mask) length = _array(code, episode_length, wp.array(dtype=wp.int32)) - keys = [last_action, *((last_action, action_dim) for action_dim in mdp.narrow_action_dims)] - fills = [f"{code.function(_fill)}(world, {_array(code, key, wp.array2d(dtype=wp.float32))}, 0.0)" for key in keys] + fill = f"{code.function(_fill)}(world, {_array(code, last_action, wp.array2d(dtype=wp.float32))}, 0.0)" code.world( f"{code.function(_advance)}(world, {_rng(code)})", f"{length}[world] = 0", - *fills, - writes=["rng", episode_length, *keys], + fill, + writes=["rng", episode_length, last_action], ) _emit(code, mdp, mdp.plan.reset) diff --git a/source/isaaclab_experimental/test/mdp2/test_mdp2.py b/source/isaaclab_experimental/test/mdp2/test_mdp2.py index 5ea5d2f6e6f6..943cb332f02d 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2.py @@ -980,8 +980,8 @@ def test_world_configs_match_single_config_runs(): def test_world_configs_with_fewer_actions_read_their_own_actions(): - """The action terms of a world config, eager ones included, see its actions only, not the columns that pad them - for a wider config.""" + """The action terms of a world config, eager ones included, see its actions only: the last actions zero the + columns that pad them for a wider config, so equal terms of both configs are one op.""" for backend in ("torch", "warp"): scene = PointMassScene(num_worlds=4, joint_names=("x", "y"), device=DEVICE) configs = [] @@ -1010,20 +1010,21 @@ def test_world_configs_with_fewer_actions_read_their_own_actions(): scene.step() mdp2.evaluate(mdp, state, transition) - # Observations of the same name share columns, as wide as the widest, in the order they first appear: - # last_action (0-1), action_l2 (2), action_rate_l2 (3), eager_l2 (4), narrow_rate (5). + # Observations of the same name share columns, as wide as the widest, in the order of the merged ops: + # last_action (0-1), action_l2 (2), action_rate_l2 (3), narrow_rate (4), eager_l2 (5). policy = transition.observations["policy"].torch torch.testing.assert_close(policy[:2, :2], steps[1][:2]) torch.testing.assert_close(policy[:2, 2], steps[1][:2].square().sum(-1)) torch.testing.assert_close(policy[:2, 3], (steps[1][:2] - steps[0][:2]).square().sum(-1)) # The second column of the actions pads the narrow config: its terms ignore it, and its columns stay zero. torch.testing.assert_close(policy[2:, 0], steps[1][2:, 0]) - assert (policy[2:, 1] == 0.0).all() and (policy[2:, 3] == 0.0).all() and (policy[:2, 5] == 0.0).all() + assert (policy[2:, 1] == 0.0).all() and (policy[2:, 3] == 0.0).all() and (policy[:2, 4] == 0.0).all() torch.testing.assert_close(policy[2:, 2], steps[1][2:, 0].square()) - torch.testing.assert_close(policy[2:, 5], (steps[1][2:, 0] - steps[0][2:, 0]).square()) + torch.testing.assert_close(policy[2:, 4], (steps[1][2:, 0] - steps[0][2:, 0]).square()) # Eager terms too. - torch.testing.assert_close(policy[:2, 4], steps[1][:2].square().sum(-1)) - torch.testing.assert_close(policy[2:, 4], steps[1][2:, 0].square()) + torch.testing.assert_close(policy[:2, 5], steps[1][:2].square().sum(-1)) + torch.testing.assert_close(policy[2:, 5], steps[1][2:, 0].square()) + assert mdp.action_mask(state).tolist() == [[True, True]] * 2 + [[True, False]] * 2 def test_library_action_and_termination_terms(): From 201b0d88c5abfe7f41dfe151ea653160d9eba7ce Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 18:35:42 -0800 Subject: [PATCH 07/49] Let the tasks of an MDP2 sequence take actions An action of a task of a sequence writes only while its task runs, and two actions of tasks that never run together may write the same elements. --- .../changelog.d/mdp2-part2.added.rst | 2 + .../isaaclab_experimental/mdp2/builder.py | 17 +++---- .../isaaclab_experimental/mdp2/plan.py | 5 +- .../test/mdp2/test_mdp2.py | 49 +++++++++++++++++++ 4 files changed, 63 insertions(+), 10 deletions(-) diff --git a/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst index 6cee5e9c529c..596a6e34ea16 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst @@ -40,3 +40,5 @@ * Added ``repeat`` to MDP2 tasks: a task that repeats counts its completions as ``mdp2.progress..count``, such as the drops of an object, and restarts with its subtasks and uses once its completion no longer holds. :class:`~isaaclab_experimental.envs.MDP2RLEnv` records the count of every episode. +* Added actions to the tasks of an MDP2 sequence: each task writes its actions while it runs, and actions of the same + name share their columns of the action, so that one policy drives every task. diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py index 176fdcae4c31..5484c52fec0c 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py @@ -247,8 +247,6 @@ def add(kind: str, name: str, cfg: object, group: str | None = None, concatenate # A time limit ends episodes; a task of a sequence can end itself with a termination on its started_at. if isinstance(cfg, TimeLimit) and staged: raise ValueError(f"Task '{task_path}': the tasks of a sequence cannot have a time limit.") - if isinstance(cfg, (DirectAction, Action)) and staged: - raise ValueError(f"Task '{task_path}': the tasks of a sequence cannot have actions yet.") # Reset and startup events set up whole episodes, so they run in every world of their task. setup = isinstance(cfg, Event) and cfg.mode is not EventMode.INTERVAL full = f"{prefix}.{name}" if prefix else name @@ -659,18 +657,19 @@ def _compile_action(self, entry: ScheduleEntry, context: CompileContext) -> None if self._resolve(entry, "subset", cfg.subset, context) is None: return elements = set(context.subsets[cfg.subset]) - # Action terms may write other elements of the same field, such as other joints, after or before it. + # Its columns of the action are given with those of every world config, by name. + columns, slot = slice(0, len(elements)), entry.name or entry.path[-1] + action = ActionOp(str(entry), cfg.target, columns, cfg.scale, cfg.offset, subset=cfg.subset, slot=slot) + action = replace(action, stage=entry.stage) + # Action terms may write other elements of the same field, such as other joints, after or before it, and + # actions of tasks of a sequence that never run together the same ones. for op in context.ops[Phase.ACTIONS]: - if isinstance(op, TermOp): + if isinstance(op, TermOp) or _exclusive(op, action, context.modes): continue written = set(context.subsets[op.subset]) if op.subset is not None else elements if op.target == cfg.target and (op.subset is None or elements & written): context.errors.append(f"{entry}: '{cfg.target}' is already written by '{op.name}'.") - - # Its columns of the action are given with those of every world config, by name. - slot = entry.name or entry.path[-1] - action = ActionOp(str(entry), cfg.target, slice(0, len(elements)), cfg.scale, cfg.offset, subset=cfg.subset) - context.ops[Phase.ACTIONS].append(replace(action, slot=slot)) + context.ops[Phase.ACTIONS].append(action) def _compile_term(self, entry: ScheduleEntry, context: CompileContext) -> None: """Compile a term use into an op, or record why it cannot be compiled.""" diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py index 6eccd284f092..b53858de4a34 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py @@ -41,10 +41,13 @@ class ActionOp: worlds: tuple[int, ...] | None = None # Worlds where the op is active, None for every world subset: SubsetSelector | None = None # Elements of the target it writes, None for all of them slot: str = "" # Name of its columns of the action, which the actions of the same name share + stage: str | None = None # The task of a sequence that the op belongs to: it writes only while that task runs @property def active_key(self) -> Hashable | None: - """Key in :attr:`MDPState.arrays` of the worlds where the op is active, None for every world.""" + """Key in :attr:`MDPState.arrays` of the worlds where the op writes at this step, None for every world.""" + if self.stage is not None: + return progress_field(self.stage, "active") return None if self.worlds is None else ("active", self.name) diff --git a/source/isaaclab_experimental/test/mdp2/test_mdp2.py b/source/isaaclab_experimental/test/mdp2/test_mdp2.py index 943cb332f02d..b84ad92fdcfd 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2.py @@ -2151,3 +2151,52 @@ def test_tasks_that_repeat_count_each_time_they_are_done(): assert [step["count"].item() for step in history] == [0, 1, 1, 1, 2] assert [step["up.done"].item() for step in history] == [True, True, False, True, True] assert [step["stage"].item() for step in history] == [1, 2, 0, 1, 2] + + +def test_tasks_of_a_sequence_take_their_own_actions(): + """Each task of a sequence writes its actions while it runs. Actions of one name share their columns, so a policy + keeps its outputs across tasks, and the last actions zero the columns of a task that does not run.""" + + def stage(joint: str, actions: dict[str, mdp2.DirectAction]) -> mdp2.TaskCfg: + return mdp2.TaskCfg(actions=actions, done=getattr(mdp2.quantities, joint)) + + effort = mdp2.DirectAction(robot.joint_effort_target, subset=robot.joints("a")) + grip = mdp2.DirectAction(robot.joint_effort_target, subset=robot.joints("b")) + task = mdp2.compose( + mdp2.TaskCfg(quantities=above("a", "b")), + mdp2.sequence( + reach=stage("a", {"effort": effort}), + lift=stage("b", {"effort": dataclasses.replace(effort, scale=3.0), "grip": grip}), + ), + ) + + def run(backend: str, capture: bool) -> list[dict[str, torch.Tensor]]: + scene = PointMassScene(num_worlds=1, joint_names=("a", "b"), device=DEVICE) + builder = mdp2.MDPBuilder(scene.schema) + builder.add_task(task) + mdp = builder.finalize(device=DEVICE, backend=backend) + state, transition = mdp.state(scene), mdp.transition() + actions = ProxyArray(wp.from_torch(torch.tensor([[0.5, 0.25]], device=DEVICE))) + captured = mdp2.CapturedMDP(mdp, state, transition, actions, transition.done) if capture else None + env_reset(mdp, state, scene, transition.observations, torch.ones(1, dtype=torch.bool, device=DEVICE)) + history = [] + for joints in ([0.0, 0.0], [1.0, 0.0], [1.0, 0.0]): + mdp2.apply_actions(mdp, state, actions) if captured is None else captured.apply_actions() + scene.data("robot", "joint_pos").torch.copy_(torch.tensor([joints], device=DEVICE)) + mdp2.evaluate(mdp, state, transition) if captured is None else captured.evaluate() + target = scene.data("robot", "joint_effort_target").torch + history.append({"target": target.clone(), "last": state.actions.torch.clone()}) + history[-1]["mask"] = mdp.action_mask(state).clone() + return history + + runs = [run(backend, capture) for backend in ("torch", "warp") for capture in (False, True)] + for other in runs[1:]: + for expected, actual in zip(runs[0], other): + for name in expected: + assert torch.equal(expected[name], actual[name]), name + history = runs[0] + # Reach writes the effort until it is done at step 2; lift scales it by 3 and grips from step 3. + assert [step["target"][0].tolist() for step in history] == [[0.5, 0.0], [0.5, 0.0], [1.5, 0.25]] + assert [step["last"][0].tolist() for step in history] == [[0.5, 0.0], [0.5, 0.0], [0.5, 0.25]] + # The mask is of the next step: lift runs from step 3. + assert [step["mask"][0].tolist() for step in history] == [[True, False], [True, True], [True, True]] From e7e36741238aaac13df85c52660fec24b8f7d879 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 18:39:07 -0800 Subject: [PATCH 08/49] Apply MDP2 actions once per control step or before every physics step Actions take a rate: ActionRate.CONTROL applies once per control step, in process_actions, which the environment calls before its physics steps, and ActionRate.PHYSICS, the default, before every physics step. Tasks without control-rate actions compile to the same kernels. --- .../changelog.d/mdp2-part2.added.rst | 4 ++ .../isaaclab_experimental/envs/mdp2_env.py | 4 +- .../isaaclab_experimental/mdp2/__init__.pyi | 5 +- .../isaaclab_experimental/mdp2/builder.py | 4 +- .../isaaclab_experimental/mdp2/capture.py | 8 ++- .../isaaclab_experimental/mdp2/config.py | 13 ++++- .../isaaclab_experimental/mdp2/plan.py | 20 ++++++- .../isaaclab_experimental/mdp2/runtime.py | 11 +++- .../mdp2/torch_backend.py | 43 ++++++++++----- .../mdp2/warp_backend.py | 55 ++++++++++++------- .../test/mdp2/test_mdp2.py | 53 ++++++++++++++++++ 11 files changed, 178 insertions(+), 42 deletions(-) diff --git a/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst index 596a6e34ea16..a977002e428f 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst @@ -42,3 +42,7 @@ :class:`~isaaclab_experimental.envs.MDP2RLEnv` records the count of every episode. * Added actions to the tasks of an MDP2 sequence: each task writes its actions while it runs, and actions of the same name share their columns of the action, so that one policy drives every task. +* Added :class:`~isaaclab_experimental.mdp2.ActionRate` to MDP2 actions: an action at ``ActionRate.CONTROL`` applies + once per control step, before the physics steps, such as an embedded whole-body controller or inverse kinematics, + and one at ``ActionRate.PHYSICS``, the default, before every physics step. :func:`~isaaclab_experimental.mdp2. + process_actions` runs the former. diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py index 064e4f693b1b..48e411dfc138 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py @@ -329,7 +329,9 @@ def _after_evaluate(self) -> None: def _simulate(self) -> None: """Apply the actions and step the physics ``decimation`` times.""" - # Actions apply before every physics step, as in MDP1, so targets relative to the joint state follow it. + # Actions apply before every physics step, as in MDP1, so targets relative to the joint state follow it, + # unless they apply once per control step. + mdp2.process_actions(self.mdp, self.state, self.actions) for _ in range(self.cfg.decimation // self._substeps): mdp2.apply_actions(self.mdp, self.state, self.actions) self.scene.write_data_to_sim() diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/__init__.pyi b/source/isaaclab_experimental/isaaclab_experimental/mdp2/__init__.pyi index 9a402d0b8912..4abb371738cc 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/__init__.pyi +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/__init__.pyi @@ -6,6 +6,7 @@ __all__ = [ "MDP", "Action", + "ActionRate", "CapturedMDP", "Backend", "Command", @@ -59,6 +60,7 @@ __all__ = [ "evaluate", "last_action", "observe", + "process_actions", "progress", "progress_field", "quantities", @@ -81,6 +83,7 @@ from .capture import CapturedMDP from .compiled import MDP, Backend, MDPState, ObservationColumns, Transition, WorldConfig from .config import ( Action, + ActionRate, Command, Constant, DirectAction, @@ -120,6 +123,6 @@ from .config import ( from .eager import TermContext from .plan import ExecutionPlan, ObservationSlot, Segment, Step, StepKind, TaskNode, TaskTree, TunedValue from .rng import uniform -from .runtime import apply_actions, evaluate, observe, reset, startup, tune +from .runtime import apply_actions, evaluate, observe, process_actions, reset, startup, tune from .scene import EntitySchema, FieldSchema, SceneData, SceneSchema from .terms import Implementation, State, Term diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py index 5484c52fec0c..d975b4e9ef4d 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py @@ -24,6 +24,7 @@ from .compiled import MDP, Backend, WorldConfig from .config import ( Action, + ActionRate, Command, DirectAction, Entity, @@ -660,7 +661,7 @@ def _compile_action(self, entry: ScheduleEntry, context: CompileContext) -> None # Its columns of the action are given with those of every world config, by name. columns, slot = slice(0, len(elements)), entry.name or entry.path[-1] action = ActionOp(str(entry), cfg.target, columns, cfg.scale, cfg.offset, subset=cfg.subset, slot=slot) - action = replace(action, stage=entry.stage) + action = replace(action, stage=entry.stage, rate=cfg.rate) # Action terms may write other elements of the same field, such as other joints, after or before it, and # actions of tasks of a sequence that never run together the same ones. for op in context.ops[Phase.ACTIONS]: @@ -832,6 +833,7 @@ def _compile_term(self, entry: ScheduleEntry, context: CompileContext) -> None: record=isinstance(cfg, Quantity) and cfg.record, columns=columns, slot=(entry.name or entry.path[-1]) if isinstance(cfg, Action) else "", + rate=cfg.rate if isinstance(cfg, Action) else ActionRate.PHYSICS, stage=entry.stage, when=when, when_dtype=when_dtype, diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/capture.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/capture.py index fbd76a7d1c2b..8df3c39a3652 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/capture.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/capture.py @@ -57,6 +57,7 @@ def __init__( self._pool = torch.cuda.MemPool() if self._on_cuda else None launches = mdp.launches + self._process_actions = self._capture(launches.process_actions, Call(state, actions=actions)) self._apply_actions = self._capture(launches.apply_actions, Call(state, actions=actions)) self._evaluate = self._capture( launches.evaluate, Call(state, transition=transition, observations=transition.observations) @@ -64,8 +65,13 @@ def __init__( self._reset = self._capture(launches.reset, Call(state, mask=mask, commit=commit)) self._observe = self._capture(launches.observe, Call(state, mask=mask, observations=transition.observations)) + def process_actions(self) -> None: + """Store the bound actions and apply those that apply once per control step.""" + for run in self._process_actions: + run() + def apply_actions(self) -> None: - """Store the bound actions and write them to their target fields.""" + """Write the bound actions that apply before every physics step to their target fields.""" for run in self._apply_actions: run() diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py index feaaa73ce7d1..8c130a8101e7 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py @@ -292,6 +292,13 @@ class TimeLimit: episode_length_s: float # Episode duration [s] +class ActionRate(enum.Enum): + """How often an action applies in a control step.""" + + PHYSICS = enum.auto() # Before every physics step, as MDP1 applies actions + CONTROL = enum.auto() # Once, before the physics steps, as MDP1 processes actions: such as an embedded policy + + @dataclass class DirectAction: """Configuration for an action that writes ``scale * action + offset`` to an entity field.""" @@ -302,6 +309,7 @@ class DirectAction: scale: float = 1.0 offset: float | FieldSelector = 0.0 # A field gives an offset per element, like robot.default_joint_pos subset: SubsetSelector | None = None # Elements of the target to write, like robot.joints("slider_to_cart") + rate: ActionRate = ActionRate.PHYSICS @dataclass @@ -310,12 +318,15 @@ class Action(TermCfg): The term's shape is ``("worlds", n)``, with the number of columns ``n`` it takes, and its hooks get them as ``action``: a Python hook ``compute(action, **args)`` writes its outputs in place, and a func - ``compute(world, action, **args)`` writes its world. Actions apply before every physics step, as in MDP1. + ``compute(world, action, **args)`` writes its world. Actions apply before every physics step, as in MDP1, or + once per control step at ``ActionRate.CONTROL``, such as an embedded whole-body controller that writes joint + targets. """ phase: ClassVar[Phase] = Phase.ACTIONS outputs: dict[str, FieldSelector] = field(default_factory=dict) # Passed by argument name; the action writes them + rate: ActionRate = ActionRate.PHYSICS class TaskMode(enum.Enum): diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py index b53858de4a34..7af4a2bddcd6 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py @@ -19,7 +19,16 @@ from types import MappingProxyType from typing import TYPE_CHECKING, Any -from .config import Entity, FieldSelector, Phase, SubsetSelector, TaskMode, UniformNoise, progress_field +from .config import ( + ActionRate, + Entity, + FieldSelector, + Phase, + SubsetSelector, + TaskMode, + UniformNoise, + progress_field, +) from .terms import State if TYPE_CHECKING: @@ -42,6 +51,7 @@ class ActionOp: subset: SubsetSelector | None = None # Elements of the target it writes, None for all of them slot: str = "" # Name of its columns of the action, which the actions of the same name share stage: str | None = None # The task of a sequence that the op belongs to: it writes only while that task runs + rate: ActionRate = ActionRate.PHYSICS @property def active_key(self) -> Hashable | None: @@ -102,6 +112,7 @@ class TermOp: columns: slice | None = None # Actions: the columns of the action that the term takes worlds: tuple[int, ...] | None = None # Worlds where the op is active, None for every world slot: str = "" # Actions: the name of its columns of the action, which the actions of the same name share + rate: ActionRate = ActionRate.PHYSICS # Actions: how often it applies in a control step # The task of a sequence that the op belongs to: it runs only while that task runs, and its state, timer, and # command restart when the task starts. Quantities run in every step: they only restart. stage: str | None = None @@ -283,7 +294,8 @@ class ExecutionPlan: """Ordered steps of each runtime function. ``reset`` and ``observe`` only act on the masked worlds.""" startup: tuple[Step, ...] - apply_actions: tuple[Step, ...] + process_actions: tuple[Step, ...] # Once per control step, before the physics steps + apply_actions: tuple[Step, ...] # Before every physics step evaluate: tuple[Step, ...] reset: tuple[Step, ...] observe: tuple[Step, ...] @@ -364,7 +376,8 @@ def computed(phase_ops: tuple) -> list[Step]: return ExecutionPlan( startup=tuple(Step(StepKind.COMPUTE, op) for op in ops[Phase.STARTUP_EVENTS]), - apply_actions=tuple(Step(StepKind.COMPUTE, op) for op in ops[Phase.ACTIONS]), + process_actions=tuple(Step(StepKind.COMPUTE, op) for op in ops[Phase.ACTIONS] if op.rate is ActionRate.CONTROL), + apply_actions=tuple(Step(StepKind.COMPUTE, op) for op in ops[Phase.ACTIONS] if op.rate is ActionRate.PHYSICS), evaluate=( # Quantities, progress, terminations, and rewards see the commands that governed the action. *computed(ops[Phase.QUANTITIES]), @@ -440,6 +453,7 @@ class Launches: """Launches of each runtime function, in order, compiled from the execution plan by a backend.""" startup: tuple[Callable[[Call], None], ...] + process_actions: tuple[Callable[[Call], None], ...] apply_actions: tuple[Callable[[Call], None], ...] evaluate: tuple[Callable[[Call], None], ...] reset: tuple[Callable[[Call], None], ...] diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/runtime.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/runtime.py index 9d6237497b73..0094a3e136fc 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/runtime.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/runtime.py @@ -36,8 +36,17 @@ def startup(mdp: MDP, state: MDPState) -> None: launch(call) +def process_actions(mdp: MDP, state: MDPState, actions: ProxyArray) -> None: + """Store the actions, shape ``(num_worlds, action_dim)``, and apply those that apply once per control step, see + :class:`~.config.ActionRate`. Call it once per control step, before :func:`apply_actions`. Without such actions it + does nothing, and :func:`apply_actions` stores the actions.""" + call = Call(state, actions=actions) + for launch in mdp.launches.process_actions: + launch(call) + + def apply_actions(mdp: MDP, state: MDPState, actions: ProxyArray) -> None: - """Store the actions, shape ``(num_worlds, action_dim)``, and write them to their target fields.""" + """Write the actions that apply before every physics step to their target fields; call it before each.""" call = Call(state, actions=actions) for launch in mdp.launches.apply_actions: launch(call) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py index f32ced08ec9c..b9b82e8aa5cc 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py @@ -23,7 +23,15 @@ def compile_launches(mdp: MDP) -> Launches: """Turn every step of the execution plan into a launch, after the bookkeeping that starts each function.""" return Launches( startup=_launches(mdp, mdp.plan.startup), - apply_actions=(Launch(lambda call: _apply_actions(mdp, call)),), + # The actions are stored once per control step: with the actions that apply once, if any. + process_actions=( + (Launch(lambda call: _apply_actions(mdp, call, mdp.plan.process_actions, store=True)),) + if mdp.plan.process_actions + else () + ), + apply_actions=( + Launch(lambda call: _apply_actions(mdp, call, mdp.plan.apply_actions, store=not mdp.plan.process_actions)), + ), evaluate=(Launch(lambda call: _begin_evaluate(mdp, call)), *_launches(mdp, mdp.plan.evaluate, stepping=True)), reset=(Launch(lambda call: _begin_reset(mdp, call)), *_launches(mdp, mdp.plan.reset)), observe=_launches(mdp, mdp.plan.observe), @@ -35,21 +43,14 @@ def _launches(mdp: MDP, steps: tuple[Step, ...], stepping: bool = False) -> tupl return tuple(Launch(lambda call, step=step: _run(mdp, step, call, stepping), step.capturable) for step in steps) -def _apply_actions(mdp: MDP, call: Call) -> None: - """Store the actions as the last actions, and write each action's scaled columns to its target field.""" +def _apply_actions(mdp: MDP, call: Call, steps: tuple[Step, ...], store: bool) -> None: + """Store the actions as the last actions if ``store``, and run the action steps: write each action's scaled + columns to its target field, or run an action term.""" actions = call.actions.torch - call.state.actions.torch.copy_(actions) - # The last actions keep the columns that each world takes at this step, and zero the others. - for slot in (slot for slot in mdp.action_slots if slot.partial): - columns = torch.arange(slot.columns.start, slot.columns.stop, device=mdp.device) - covered = torch.zeros(mdp.num_worlds, len(columns), dtype=torch.bool, device=mdp.device) - for op in slot.ops: - active = _active(op, call.state) - width = columns < op.columns.stop - covered |= width if active is None else active.torch[:, None] & width - call.state.actions.torch[:, slot.columns].masked_fill_(~covered, 0.0) + if store: + _store_actions(mdp, call) - for step in mdp.plan.apply_actions: + for step in steps: op = step.op if isinstance(op, TermOp): # The hook writes its outputs; it may take the worlds where it is active as ``mask``. @@ -71,6 +72,20 @@ def _apply_actions(mdp: MDP, call: Call) -> None: target[:, ids] = value +def _store_actions(mdp: MDP, call: Call) -> None: + """Store the actions as the last actions, which keep the columns that each world takes at this step and zero the + others.""" + call.state.actions.torch.copy_(call.actions.torch) + for slot in (slot for slot in mdp.action_slots if slot.partial): + columns = torch.arange(slot.columns.start, slot.columns.stop, device=mdp.device) + covered = torch.zeros(mdp.num_worlds, len(columns), dtype=torch.bool, device=mdp.device) + for op in slot.ops: + active = _active(op, call.state) + width = columns < op.columns.stop + covered |= width if active is None else active.torch[:, None] & width + call.state.actions.torch[:, slot.columns].masked_fill_(~covered, 0.0) + + def _begin_evaluate(mdp: MDP, call: Call) -> None: """Advance the random streams and episode lengths, and clear the results of the last step.""" state, transition = call.state, call.transition diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py index d7a71896fe19..9ee2df0e58dc 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py @@ -86,7 +86,16 @@ def _select(mask: wp.array(dtype=wp.bool), active: wp.array(dtype=wp.bool), sele def compile_launches(mdp: MDP) -> Launches: """Generate the kernels of every runtime function, with the hooks that launch their own work between them.""" - return Launches(_startup(mdp), _apply_actions(mdp), _evaluate(mdp), _reset(mdp), _observe(mdp)) + # The actions are stored once per control step: with the actions that apply once, if any. + control = bool(mdp.plan.process_actions) + return Launches( + _startup(mdp), + _actions(mdp, "process_actions", mdp.plan.process_actions, store=control) if control else (), + _actions(mdp, "apply_actions", mdp.plan.apply_actions, store=not control), + _evaluate(mdp), + _reset(mdp), + _observe(mdp), + ) def _startup(mdp: MDP) -> tuple[Callable[[Call], None], ...]: @@ -95,24 +104,13 @@ def _startup(mdp: MDP) -> tuple[Callable[[Call], None], ...]: return code.steps() -def _apply_actions(mdp: MDP) -> tuple[Callable[[Call], None], ...]: - code = Fusion("apply_actions", mdp.num_worlds, mdp.device) +def _actions(mdp: MDP, name: str, steps: tuple[Step, ...], store: bool) -> tuple[Callable[[Call], None], ...]: + """Generate the kernels of the action steps of a runtime function, which first stores the last actions if + ``store``.""" + code = Fusion(name, mdp.num_worlds, mdp.device) actions = code.argument("actions", wp.array2d(dtype=wp.float32), lambda call: call.actions.warp) - last_actions = _array(code, last_action, wp.array2d(dtype=wp.float32)) - # The last actions keep the columns that each world takes at this step, and zero the others. - ignored = [] - for slot in (slot for slot in mdp.action_slots if slot.partial): - covers = [] - for op in slot.ops: - cover = f"element < {op.columns.stop}" - covers.append(cover if op.active_key is None else f"({_runs(code, op)} and {cover})") - start, stop = slot.columns.start, slot.columns.stop - ignored += [f"if element >= {start} and element < {stop} and not ({' or '.join(covers)}):", " value = 0.0"] - if ignored: - copy = [f"value = {actions}[world, element]", *ignored, f"{last_actions}[world, element] = value"] - else: - copy = [f"{last_actions}[world, element] = {actions}[world, element]"] - code.elements((mdp.action_dim,), *copy, writes=[last_action]) + if store: + _store_actions(code, mdp, actions) # Fields with more dimensions per world are flattened; joint fields are views of the solver state that may be # strided, so they are passed as they are. @@ -120,7 +118,7 @@ def rows(call: Call, selector: FieldSelector) -> wp.array: field = call.state.arrays[selector].warp return field if field.ndim == 2 else field.reshape((mdp.num_worlds, -1)) - for step in mdp.plan.apply_actions: + for step in steps: op = step.op if isinstance(op, TermOp): _apply_action_term(code, op) @@ -141,6 +139,25 @@ def rows(call: Call, selector: FieldSelector) -> wp.array: return code.steps() +def _store_actions(code: Fusion, mdp: MDP, actions: str) -> None: + """Store the actions as the last actions.""" + last_actions = _array(code, last_action, wp.array2d(dtype=wp.float32)) + # The last actions keep the columns that each world takes at this step, and zero the others. + ignored = [] + for slot in (slot for slot in mdp.action_slots if slot.partial): + covers = [] + for op in slot.ops: + cover = f"element < {op.columns.stop}" + covers.append(cover if op.active_key is None else f"({_runs(code, op)} and {cover})") + start, stop = slot.columns.start, slot.columns.stop + ignored += [f"if element >= {start} and element < {stop} and not ({' or '.join(covers)}):", " value = 0.0"] + if ignored: + copy = [f"value = {actions}[world, element]", *ignored, f"{last_actions}[world, element] = value"] + else: + copy = [f"{last_actions}[world, element] = {actions}[world, element]"] + code.elements((mdp.action_dim,), *copy, writes=[last_action]) + + def _apply_action_term(code: Fusion, op: TermOp) -> None: """Run an action term's compute hook, which writes its outputs from its columns of the action.""" if isinstance(op.compute, wp.Function): diff --git a/source/isaaclab_experimental/test/mdp2/test_mdp2.py b/source/isaaclab_experimental/test/mdp2/test_mdp2.py index b84ad92fdcfd..8e616cbf4c28 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2.py @@ -2200,3 +2200,56 @@ def run(backend: str, capture: bool) -> list[dict[str, torch.Tensor]]: assert [step["last"][0].tolist() for step in history] == [[0.5, 0.0], [0.5, 0.0], [0.5, 0.25]] # The mask is of the next step: lift runs from step 3. assert [step["mask"][0].tolist() for step in history] == [[True, False], [True, True], [True, True]] + + +@wp.func +def count_applications_warp( + world: int, action: wp.array2d(dtype=float), target: wp.array2d(dtype=float), calls: wp.array(dtype=float) +): + calls[world] = calls[world] + 1.0 + target[world, 0] = action[world, 0] * calls[world] + + +def count_applications_torch(action, target, calls): + calls.add_(1.0) + target[:, 0] = action[:, 0] * calls + + +count_applications = mdp2.Term( + torch=count_applications_torch, + warp=count_applications_warp, + shape=("worlds", 1), + state={"calls": mdp2.State(persistent=True)}, +) +"""Write the action's column times the number of times the action applied.""" + + +def test_actions_apply_once_per_control_step_or_before_every_physics_step(): + """An action at the control rate applies once per control step, before the physics steps, and one at the physics + rate before each of them. The actions are stored once.""" + task = mdp2.TaskCfg( + actions={ + "plan": mdp2.Action( + count_applications, outputs={"target": robot.joint_effort_target}, rate=mdp2.ActionRate.CONTROL + ), + "track": mdp2.DirectAction(robot.joint_effort_target, subset=robot.joints("b"), scale=2.0), + } + ) + for backend in ("torch", "warp"): + for capture in (False, True): + scene = PointMassScene(num_worlds=2, joint_names=("a", "b"), device=DEVICE) + builder = mdp2.MDPBuilder(scene.schema) + builder.add_task(task) + mdp = builder.finalize(device=DEVICE, backend=backend) + state, transition = mdp.state(scene), mdp.transition() + actions = ProxyArray(wp.from_torch(torch.tensor([[1.0, 0.5], [2.0, 0.25]], device=DEVICE))) + captured = mdp2.CapturedMDP(mdp, state, transition, actions, transition.done) if capture else None + for _ in range(3): + mdp2.process_actions(mdp, state, actions) if captured is None else captured.process_actions() + for _ in range(scene.decimation): + mdp2.apply_actions(mdp, state, actions) if captured is None else captured.apply_actions() + calls = state.arrays[mdp2.term_state("actions.plan", "calls")].torch + assert calls.tolist() == [3.0, 3.0], (backend, capture) + target = scene.data("robot", "joint_effort_target").torch + assert target.tolist() == [[3.0, 1.0], [6.0, 0.5]] and torch.equal(state.actions.torch, actions.torch) + assert len(mdp.launches.process_actions) == 1 and len(mdp.plan.apply_actions) == 1 From 01ba17d4c9d77646c95299ab335c627d43c4139a Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 18:39:11 -0800 Subject: [PATCH 09/49] Fix a role split across lines in the MDP2 changelog fragment --- source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst index a977002e428f..d6d339771e99 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst @@ -44,5 +44,5 @@ name share their columns of the action, so that one policy drives every task. * Added :class:`~isaaclab_experimental.mdp2.ActionRate` to MDP2 actions: an action at ``ActionRate.CONTROL`` applies once per control step, before the physics steps, such as an embedded whole-body controller or inverse kinematics, - and one at ``ActionRate.PHYSICS``, the default, before every physics step. :func:`~isaaclab_experimental.mdp2. - process_actions` runs the former. + and one at ``ActionRate.PHYSICS``, the default, before every physics step. + :func:`~isaaclab_experimental.mdp2.process_actions` runs the former. From 017be531b3eb531582e32a92297be317f5c79323 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 18:41:58 -0800 Subject: [PATCH 10/49] Name the action and observation columns of an MDP2 task in its spec MDP.spec returns the columns of the action and of every observation buffer by name, with the names of their elements, such as joint names, where the inputs of an op name them: the elements of a subset or of an entity dimension. --- .../isaaclab_experimental.mdp2.rst | 6 ++- .../changelog.d/mdp2-part2.added.rst | 6 ++- .../isaaclab_experimental/mdp2/__init__.pyi | 5 +- .../isaaclab_experimental/mdp2/builder.py | 37 +++++++++++++- .../isaaclab_experimental/mdp2/compiled.py | 48 +++++++++++++++---- .../isaaclab_experimental/mdp2/plan.py | 4 ++ .../test/mdp2/test_mdp2.py | 10 +++- 7 files changed, 99 insertions(+), 17 deletions(-) diff --git a/docs/source/api/lab_experimental/isaaclab_experimental.mdp2.rst b/docs/source/api/lab_experimental/isaaclab_experimental.mdp2.rst index dff8ab9b0412..17ef4ee24c41 100644 --- a/docs/source/api/lab_experimental/isaaclab_experimental.mdp2.rst +++ b/docs/source/api/lab_experimental/isaaclab_experimental.mdp2.rst @@ -50,7 +50,8 @@ Building and running MDPBuilder MDP - ObservationColumns + Columns + Spec MDPState Transition Backend @@ -108,7 +109,8 @@ Scene data :members: .. autoclass:: MDP :members: -.. autoclass:: ObservationColumns +.. autoclass:: Columns +.. autoclass:: Spec .. autoclass:: MDPState :members: .. autoclass:: Transition diff --git a/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst index d6d339771e99..daa7316cbc47 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst @@ -18,8 +18,10 @@ while it does, and restart when it starts. Terms read the progress of every task, such as ``mdp2.progress.grasp.done``, and :class:`~isaaclab_experimental.envs.MDP2RLEnv` logs it as ``Progress/`` and records the step at which each task was done. -* Added :meth:`~isaaclab_experimental.mdp2.MDP.spec` and :meth:`~isaaclab_experimental.mdp2.MDP.observation_mask`, - which name the columns of the observation buffers and the columns each world writes. +* Added :meth:`~isaaclab_experimental.mdp2.MDP.spec`, which names the columns of the action and of the observation + buffers, with the names of their elements, such as joint names, and + :meth:`~isaaclab_experimental.mdp2.MDP.action_mask` and :meth:`~isaaclab_experimental.mdp2.MDP.observation_mask`, + which give the columns each world takes and writes. * Added :data:`~isaaclab_experimental.mdp2.mdp.joint_pos_normalized`, :data:`~isaaclab_experimental.mdp2.mdp.is_true`, and :data:`~isaaclab_experimental.mdp2.mdp.one_hot`. * Added an episode budget to :class:`~isaaclab_experimental.envs.MDP2RLEnv` for evaluation, ``episode_budget``: worlds diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/__init__.pyi b/source/isaaclab_experimental/isaaclab_experimental/mdp2/__init__.pyi index 4abb371738cc..bd5699d0c015 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/__init__.pyi +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/__init__.pyi @@ -9,6 +9,7 @@ __all__ = [ "ActionRate", "CapturedMDP", "Backend", + "Columns", "Command", "Constant", "DirectAction", @@ -23,7 +24,6 @@ __all__ = [ "MDPState", "Milestone", "Observation", - "ObservationColumns", "ObservationGroup", "ObservationSlot", "Phase", @@ -34,6 +34,7 @@ __all__ = [ "SceneData", "SceneSchema", "Segment", + "Spec", "State", "Step", "StepKind", @@ -80,7 +81,7 @@ __all__ = [ from . import mdp from .builder import MDPBuilder, ScheduleEntry from .capture import CapturedMDP -from .compiled import MDP, Backend, MDPState, ObservationColumns, Transition, WorldConfig +from .compiled import MDP, Backend, Columns, MDPState, Spec, Transition, WorldConfig from .config import ( Action, ActionRate, diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py index d975b4e9ef4d..4a3fa2dada07 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py @@ -661,7 +661,10 @@ def _compile_action(self, entry: ScheduleEntry, context: CompileContext) -> None # Its columns of the action are given with those of every world config, by name. columns, slot = slice(0, len(elements)), entry.name or entry.path[-1] action = ActionOp(str(entry), cfg.target, columns, cfg.scale, cfg.offset, subset=cfg.subset, slot=slot) - action = replace(action, stage=entry.stage, rate=cfg.rate) + names = self._element_names({"target": cfg.target, **({"subset": cfg.subset} if cfg.subset else {})}, context) + labels = names.get("subset" if cfg.subset else next(iter(target.sizes), "")) + labels = labels if labels is not None and len(labels) == len(elements) else None + action = replace(action, stage=entry.stage, rate=cfg.rate, labels=labels) # Action terms may write other elements of the same field, such as other joints, after or before it, and # actions of tasks of a sequence that never run together the same ones. for op in context.ops[Phase.ACTIONS]: @@ -785,6 +788,10 @@ def _compile_term(self, entry: ScheduleEntry, context: CompileContext) -> None: timer = cfg.interval_range_s observation, columns = _allocate_columns(entry, output_shape, context) + labels = None + if len(term.shape) == 2: + labels = self._element_names(bound, context).get(term.shape[1]) + labels = labels if labels is not None and len(labels) == output_shape[0] else None if isinstance(cfg, (Command, Quantity)): named = {dim: size for dim, size in zip(term.shape[1:], output_shape) if isinstance(dim, str)} context.mdp_fields[entry.writes[0]] = ArrayLayout(wp.float32, 1 + len(output_shape), named, output_shape) @@ -834,6 +841,7 @@ def _compile_term(self, entry: ScheduleEntry, context: CompileContext) -> None: columns=columns, slot=(entry.name or entry.path[-1]) if isinstance(cfg, Action) else "", rate=cfg.rate if isinstance(cfg, Action) else ActionRate.PHYSICS, + labels=labels, stage=entry.stage, when=when, when_dtype=when_dtype, @@ -866,6 +874,33 @@ def _compile_when(self, entry: ScheduleEntry, context: CompileContext) -> tuple[ errors.append(f"{entry}: when '{cfg.when}' must be a field of one bool, float, or int per world.") return cfg.when, layout.dtype + def _element_names( + self, bound: Mapping[str, FieldSelector | SubsetSelector | Entity], context: CompileContext + ) -> dict[str, tuple[str, ...]]: + """Return the names of the elements of the dimensions that a use's inputs name, by dimension: those of each + entity dimension of its scene fields, and those of each subset, also under its argument name. A dimension + that inputs name differently, such as the bodies of two entities, is left out.""" + names: dict[str, tuple[str, ...]] = {} + ambiguous = set() + + def add(dim: str, elements: tuple[str, ...]) -> None: + if names.setdefault(dim, elements) != elements: + ambiguous.add(dim) + + for arg, selector in bound.items(): + if isinstance(selector, SubsetSelector) and selector in context.subsets: + entity = self.schema.entities[selector.entity] + add(arg, tuple(entity.names[selector.dim][index] for index in context.subsets[selector])) + elif isinstance(selector, FieldSelector) and selector.scene and selector.entity in self.schema.entities: + entity = self.schema.entities[selector.entity] + schema = entity.fields.get(selector.field) + dims = () if schema is None else schema.dims + for dim in dims: + add(dim, tuple(entity.names[dim])) + if len(dims) == 1: + add(arg, tuple(entity.names[dims[0]])) + return {dim: elements for dim, elements in names.items() if dim not in ambiguous} + def _fields_of(self, selector: FieldSelector | Entity) -> tuple[FieldSelector, ...]: """Return the fields a write covers: a field itself, or the writable fields of a scene entity.""" if not isinstance(selector, Entity): diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py index b22367076123..74b6465e4c7e 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py @@ -138,14 +138,25 @@ class WorldConfig: @dataclass(frozen=True) -class ObservationColumns: - """Columns of an observation buffer that the observations of one name write, see :meth:`MDP.spec`.""" +class Columns: + """Columns of the action, or of an observation buffer, that the ops of one name take or write, see + :meth:`MDP.spec`.""" name: str columns: slice # For every step of the history size: int # Columns of one step of history history_length: int - widths: Mapping[str, int] # Columns of one step that each op writes, by op name; the others are zero + widths: Mapping[str, int] # Columns of one step that each op takes or writes, by op name; the others are zero + # Names of the elements of each op, by op name, such as joint names, for the ops whose inputs name them + labels: Mapping[str, tuple[str, ...]] = field(default_factory=dict) + + +@dataclass(frozen=True) +class Spec: + """The interface of an MDP by name: the columns of its action and of its observation buffers.""" + + actions: tuple[Columns, ...] + observations: Mapping[str, tuple[Columns, ...]] # By buffer @dataclass(frozen=True) @@ -225,28 +236,47 @@ def interval_writes(self) -> frozenset[FieldSelector]: def _scene_writes(self, phase: Phase) -> frozenset[FieldSelector]: return frozenset(selector for op in self.ops[phase] for selector in op.writes if selector.scene) - def spec(self) -> dict[str, tuple[ObservationColumns, ...]]: - """Return the columns of every observation buffer, by name, so that learners need not know their offsets. + def spec(self) -> Spec: + """Return the columns of the action and of every observation buffer by name, with the names of their + elements where known, so that learners, policy servers, and exporters need not know their offsets. - Observations of the same name share their columns, also across world configs and tasks of a sequence; see - :meth:`observation_mask` for the columns that the worlds write at a step. + Actions, and observations, of the same name share their columns, also across world configs and tasks of a + sequence; see :meth:`action_mask` and :meth:`observation_mask` for the columns that the worlds take and write + at a step. """ + + def labels(ops: list) -> Mapping[str, tuple[str, ...]]: + return MappingProxyType({op.name: op.labels for op in ops if op.labels is not None}) + named: dict[str, dict[str, list[TermOp]]] = {} for op in self.ops[Phase.OBSERVATIONS]: named.setdefault(op.observation.group, {}).setdefault(op.observation.slot, []).append(op) - return { + observations = { buffer: tuple( - ObservationColumns( + Columns( name=name, columns=ops[0].observation.columns, size=ops[0].observation.size, history_length=ops[0].observation.history_length, widths=MappingProxyType({op.name: math.prod(op.shape) for op in ops}), + labels=labels(ops), ) for name, ops in slots.items() ) for buffer, slots in named.items() } + actions = tuple( + Columns( + name=slot.name, + columns=slot.columns, + size=slot.columns.stop - slot.columns.start, + history_length=0, + widths=MappingProxyType({op.name: op.columns.stop - op.columns.start for op in slot.ops}), + labels=labels(list(slot.ops)), + ) + for slot in self.action_slots + ) + return Spec(actions=actions, observations=MappingProxyType(observations)) def action_mask(self, state: MDPState) -> torch.Tensor: """Return which columns of the action each world takes at this step, ``(num_worlds, action_dim)`` bool. diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py index 7af4a2bddcd6..fd07de433f45 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py @@ -52,6 +52,7 @@ class ActionOp: slot: str = "" # Name of its columns of the action, which the actions of the same name share stage: str | None = None # The task of a sequence that the op belongs to: it writes only while that task runs rate: ActionRate = ActionRate.PHYSICS + labels: tuple[str, ...] | None = None # Names of the elements it writes, such as joint names @property def active_key(self) -> Hashable | None: @@ -113,6 +114,9 @@ class TermOp: worlds: tuple[int, ...] | None = None # Worlds where the op is active, None for every world slot: str = "" # Actions: the name of its columns of the action, which the actions of the same name share rate: ActionRate = ActionRate.PHYSICS # Actions: how often it applies in a control step + # Names of the elements of an output of one dimension after the worlds, such as joint names, where its inputs name + # them: the elements of a subset or of an entity dimension. None otherwise. + labels: tuple[str, ...] | None = None # The task of a sequence that the op belongs to: it runs only while that task runs, and its state, timer, and # command restart when the task starts. Quantities run in every step: they only restart. stage: str | None = None diff --git a/source/isaaclab_experimental/test/mdp2/test_mdp2.py b/source/isaaclab_experimental/test/mdp2/test_mdp2.py index 8e616cbf4c28..4d7be9a2865d 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2.py @@ -1832,8 +1832,12 @@ def stage(joint: str, reward: float) -> mdp2.TaskCfg: assert policy[2] == [0.0, 0.0, 0.25, 0.75] # The last subtask keeps running once the sequence is done mdp, state, _ = run_progress(task, [[0.0, 0.25]], "warp", capture=False) - position = mdp.spec()["policy"][1] + position = mdp.spec().observations["policy"][1] assert (position.name, position.columns, position.history_length) == ("position", slice(2, 4), 2) + assert dict(position.labels) == { + "observations.policy.reach.position": ("reach",), + "observations.policy.lift.position": ("lift",), + } assert mdp.observation_mask(state, "policy").tolist() == [[True] * 4] assert "during reach" in mdp.describe() @@ -2179,6 +2183,10 @@ def run(backend: str, capture: bool) -> list[dict[str, torch.Tensor]]: actions = ProxyArray(wp.from_torch(torch.tensor([[0.5, 0.25]], device=DEVICE))) captured = mdp2.CapturedMDP(mdp, state, transition, actions, transition.done) if capture else None env_reset(mdp, state, scene, transition.observations, torch.ones(1, dtype=torch.bool, device=DEVICE)) + spec = mdp.spec().actions + assert [(columns.name, columns.columns) for columns in spec] == [("effort", slice(0, 1)), ("grip", slice(1, 2))] + assert dict(spec[0].labels) == {"actions.reach.effort": ("a",), "actions.lift.effort": ("a",)} + assert dict(spec[1].labels) == {"actions.lift.grip": ("b",)} history = [] for joints in ([0.0, 0.0], [1.0, 0.0], [1.0, 0.0]): mdp2.apply_actions(mdp, state, actions) if captured is None else captured.apply_actions() From 22039bc384f929b5d1a2d2c042e7ba8cee5d0cf2 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 18:44:02 -0800 Subject: [PATCH 11/49] Resolve term state, tunables, and progress by name inside MDP2 subtasks A subtask reads the state and tunable values of its own uses and the progress of itself and its subtasks by the names a task that runs alone gives them, as it already read its commands and quantities. Inner names win. --- docs/source/experimental-features/mdp2.rst | 6 +- .../changelog.d/mdp2-part2.added.rst | 3 +- .../isaaclab_experimental/mdp2/builder.py | 56 +++++++++++++++---- .../isaaclab_experimental/mdp2/config.py | 7 ++- .../test/mdp2/test_mdp2.py | 20 ++++++- 5 files changed, 71 insertions(+), 21 deletions(-) diff --git a/docs/source/experimental-features/mdp2.rst b/docs/source/experimental-features/mdp2.rst index 0eabc9049274..280394f21383 100644 --- a/docs/source/experimental-features/mdp2.rst +++ b/docs/source/experimental-features/mdp2.rst @@ -143,8 +143,10 @@ one: commands, and observation histories. Quantities are measurements: they run in every step, and only restart. Reset and startup events set up whole episodes, so they run at every reset. - **Names.** The uses of a subtask get its name as a prefix, as in ``rewards.grasp.grasp``, except in a split, whose - subtasks run apart. A subtask reads its own commands and quantities by their names, as a task alone does, so - each stage of a sequence can have its own ``reached``; ``term_state`` and ``mdp2.progress`` take full paths. Observations of the same name share their columns, as wide as the widest, so a ``goal`` of each + subtasks run apart. A subtask reads its own fields by their names, as a task alone does, so each stage of a + sequence can have its own ``reached``: its commands and quantities, the ``term_state`` and ``tunable`` values of its + uses, and its ``mdp2.progress``; inner names win. Observations of the same name share their columns, as wide as the + widest, so a ``goal`` of each stage, or the ``joint_pos`` of two robots, is one input of the policy; :meth:`~isaaclab_experimental.mdp2.MDP.spec` names the columns, and :meth:`~isaaclab_experimental.mdp2.MDP.observation_mask` gives those each world writes. - **Progress.** Every task's progress is a set of fields that terms read: ``mdp2.progress.done``, diff --git a/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst index daa7316cbc47..9952b8e68fd0 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst @@ -15,7 +15,8 @@ (:func:`~isaaclab_experimental.mdp2.compose`, with ``require``), one after another (:func:`~isaaclab_experimental.mdp2.sequence`), or in their own worlds (:func:`~isaaclab_experimental.mdp2.split`). :class:`~isaaclab_experimental.mdp2.Milestone` is a task with only a completion. The uses of a task of a sequence run - while it does, and restart when it starts. Terms read the progress of every task, such as + while it does, and restart when it starts. A subtask reads its own fields by name, as a task that runs alone does: + its commands, quantities, term state, tunable values, and progress. Terms read the progress of every task, such as ``mdp2.progress.grasp.done``, and :class:`~isaaclab_experimental.envs.MDP2RLEnv` logs it as ``Progress/`` and records the step at which each task was done. * Added :meth:`~isaaclab_experimental.mdp2.MDP.spec`, which names the columns of the action and of the observation diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py index 4a3fa2dada07..557b506f9fd6 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py @@ -23,6 +23,7 @@ from . import torch_backend, warp_backend from .compiled import MDP, Backend, WorldConfig from .config import ( + PROGRESS_FIELDS, Action, ActionRate, Command, @@ -221,8 +222,9 @@ def _add_task( whether it is part of a sequence, and ``restarts`` whether it or a parent repeats. The subtask of a split runs in worlds of its own, so its uses keep their names: equal uses of the world configs - then run once, see :meth:`replicate`. A task reads its own commands and quantities by their names, as a task - that runs alone does: ``scope`` maps the names that the task and its parents define to their fields. + then run once, see :meth:`replicate`. A task reads its own fields by their names, as a task that runs alone + does: its commands and quantities, the state and tunable values of its uses, and its progress and that of its + subtasks. ``scope`` maps the names that the task and its parents define to their fields; inner names win. """ task_path = ".".join(path) if task_path in self._tasks: @@ -232,16 +234,7 @@ def _add_task( prefix = ".".join(names) restarts = restarts or task.repeat stage = task_path if staged or restarts else None - scope = { - **scope, - **{ - FieldSelector(entity.name, name, scene=False): FieldSelector( - entity.name, f"{prefix}.{name}" if prefix else name, scene=False - ) - for entity, uses in ((commands, task.commands), (quantities, task.quantities)) - for name in uses - }, - } + scope = {**scope, **_local_names(task, task_path, prefix)} self._tasks[task_path] = (replace(task, done=scope.get(task.done, task.done)), staged or restarts) def add(kind: str, name: str, cfg: object, group: str | None = None, concatenate: bool = True) -> None: @@ -1246,6 +1239,45 @@ def _expand(task: TaskCfg, num_worlds: int) -> list[tuple[TaskCfg, int]]: return [(replace(task, subtasks={**single, splits[0]: subtask}), count) for subtask, count in variants[splits[0]]] +def _local_names(task: TaskCfg, path: str, prefix: str) -> dict[FieldSelector, FieldSelector]: + """Return the fields that a task defines, under the names that a task that runs alone gives them: its commands and + quantities, the state and tunable values of its uses, which get the prefix of its uses' names, and the progress of + it and of its subtasks, by their paths from it.""" + + def full(name: str) -> str: + return f"{prefix}.{name}" if prefix else name + + names = { + FieldSelector(entity.name, name, scene=False): FieldSelector(entity.name, full(name), scene=False) + for entity, uses in ((commands, task.commands), (quantities, task.quantities)) + for name in uses + } + groups = [(f"observations.{group}", group_terms(uses)[0]) for group, uses in task.observations.items()] + kinds = [(kind, getattr(task, kind)) for kind in ("actions", "commands", "quantities", "rewards", "events")] + for kind, uses in (*kinds, ("terminations", task.terminations), *groups): + for name, cfg in uses.items(): + if not isinstance(cfg, TermCfg) or not prefix: + continue + local, use = f"{kind}.{name}", f"{kind}.{full(name)}" + names |= {term_state(local, state): term_state(use, state) for state in cfg.term.state} + tunables = [param for param, value in cfg.params.items() if isinstance(value, Tunable)] + tunables += ["when"] if isinstance(cfg.when, Tunable) else [] + names |= {tunable(local, param): tunable(use, param) for param in tunables} + for relative in _task_paths(task): + absolute = ".".join(part for part in (path, relative) if part) + if relative != absolute: + names |= {progress_field(relative, name): progress_field(absolute, name) for name in PROGRESS_FIELDS} + return names + + +def _task_paths(task: TaskCfg) -> list[str]: + """Return the paths from a task of it, "", and of its subtasks, their subtasks, and so on.""" + return [ + "", + *(f"{name}.{sub}" if sub else name for name, subtask in task.subtasks.items() for sub in _task_paths(subtask)), + ] + + def _scoped(cfg: object, scope: Mapping[FieldSelector, FieldSelector]) -> object: """Return a use whose selectors of commands and quantities name the fields of the task that defines them.""" if not scope: diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py index 8c130a8101e7..a9620bbd3751 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py @@ -343,9 +343,10 @@ class TaskCfg: A task may also say when it is done, and hold named subtasks, which are tasks too. Its uses run whenever it runs; those of a subtask run when the subtask does, and their names get the subtask's name as a prefix, as in - ``rewards.grasp.lift``, except in a :func:`split`. A subtask reads its own commands and quantities by their names, - as a task that runs alone does; :func:`term_state` and :data:`progress` name uses and tasks by their full paths. - The progress of every task is a set of fields that terms read, see :data:`progress`. + ``rewards.grasp.lift``, except in a :func:`split`. A subtask reads its own fields by their names, as a task that + runs alone does: its commands and quantities, the :func:`term_state` and :func:`tunable` values of its uses, and + the :data:`progress` of itself and its subtasks. Inner names win: inside a subtask, ``mdp2.progress.done`` is the + subtask's own. The progress of every task is a set of fields that terms read, see :data:`progress`. """ actions: dict[str, DirectAction | Action | None] = field(default_factory=dict) diff --git a/source/isaaclab_experimental/test/mdp2/test_mdp2.py b/source/isaaclab_experimental/test/mdp2/test_mdp2.py index 4d7be9a2865d..7d68757845e6 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2.py @@ -1871,19 +1871,33 @@ def stage(joint: str, hooked: bool) -> mdp2.TaskCfg: assert all(step["reward_terms"][0, 0].item() == 0.0 for step in history[2:]) -def test_subtasks_read_their_own_quantities_by_name(): - """Subtasks written as tasks of their own read their quantities by their names, which their prefix keeps apart.""" +def test_subtasks_read_their_own_fields_by_name(): + """Subtasks written as tasks of their own read their quantities, the state of their uses, and their progress by + their names, which their prefix keeps apart.""" def reach(joint: str) -> mdp2.TaskCfg: inputs = {"joint_pos": robot.joint_pos, "joint_ids": robot.joints(joint)} + started = mdp2.Observation(episode_length, inputs={"episode_length": mdp2.progress.started_at}) + total = {"command": mdp2.term_state("rewards.held", "total")} return mdp2.TaskCfg( - quantities={"reached": mdp2.Quantity(joint_above, inputs=inputs)}, done=mdp2.quantities.reached + quantities={ + "reached": mdp2.Quantity(joint_above, inputs=inputs), + "held": mdp2.Quantity(generated_commands, inputs=total), + }, + rewards={"held": mdp2.Reward(accumulate, inputs={"joint_pos": robot.joint_pos}, params={"gain": 1.0})}, + observations={"policy": {"started": started}}, + done=mdp2.quantities.reached, ) task = mdp2.sequence(first=reach("a"), second=reach("b")) history = check_progress(task, [[0.0, 1.0], [1.0, 0.0], [1.0, 1.0]], joints=("a", "b")) assert [step["first.done_at"].item() for step in history] == [-1, 2, 2] assert [step["second.done_at"].item() for step in history] == [-1, -1, 3] + # The step at which the subtask that runs started: the second from step 2. + assert [step["policy"][0, 0].item() for step in history] == [0.0, 2.0, 2.0] + # Each subtask's quantity reads the state of its own reward, from the step before. + assert [step["quantities.second.held"].item() for step in history] == [0.0, 0.0, 0.0] + assert [step["quantities.first.held"].item() for step in history] == [0.0, 0.0, 1.0] def test_split_runs_a_sequence_beside_a_plain_task(): From 732e9d1393abf8ab8ae32da0523a0c16db71c4bc Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 18:46:28 -0800 Subject: [PATCH 12/49] Let MDP2 splits nest and divide the same worlds A split may be a step of a sequence, and several subtasks that split divide the same worlds at the boundaries of all their shares, each world running the subtask of its share of each. --- .../changelog.d/mdp2-part2.added.rst | 3 ++ .../isaaclab_experimental/mdp2/builder.py | 28 +++++++++++-------- .../isaaclab_experimental/mdp2/config.py | 4 ++- .../test/mdp2/test_mdp2.py | 22 +++++++++++++-- 4 files changed, 42 insertions(+), 15 deletions(-) diff --git a/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst index 9952b8e68fd0..762a16254040 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst @@ -49,3 +49,6 @@ once per control step, before the physics steps, such as an embedded whole-body controller or inverse kinematics, and one at ``ActionRate.PHYSICS``, the default, before every physics step. :func:`~isaaclab_experimental.mdp2.process_actions` runs the former. +* Added nested splits to MDP2: a :func:`~isaaclab_experimental.mdp2.split` may be a step of a sequence, and several + subtasks that split divide the same worlds, such as robots and terrains, each world running the subtask of its + share of each. diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py index 557b506f9fd6..eef2ec4553c8 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py @@ -1207,10 +1207,10 @@ def _merge_ops( def _expand(task: TaskCfg, num_worlds: int) -> list[tuple[TaskCfg, int]]: - """Return the tasks without splits that a task runs, each with its number of worlds. + """Return the tasks without splits that a task runs, in order, each with its number of worlds. - A split becomes, in each of its shares of the worlds, a split with only that subtask. A split may be part of a - task that runs its subtasks together, but not of a sequence, and not of more than one subtask of a task. + A split becomes, in each of its shares of the worlds, a split with only that subtask. Subtasks that split divide + the same worlds: a world runs, of each, the subtask of its share. """ if task.mode is TaskMode.SPLIT: names = list(task.subtasks) @@ -1228,15 +1228,19 @@ def _expand(task: TaskCfg, num_worlds: int) -> list[tuple[TaskCfg, int]]: ] variants = {name: _expand(subtask, num_worlds) for name, subtask in task.subtasks.items()} - splits = [name for name, expanded in variants.items() if len(expanded) > 1] - if splits and task.mode is TaskMode.SEQUENCE: - raise ValueError(f"The subtasks {splits} of a sequence split the worlds, which a sequence cannot do.") - if len(splits) > 1: - raise ValueError(f"Only one subtask of a task may split the worlds, found {splits}.") - single = {name: expanded[0][0] for name, expanded in variants.items()} - if not splits: - return [(replace(task, subtasks=single), num_worlds)] - return [(replace(task, subtasks={**single, splits[0]: subtask}), count) for subtask, count in variants[splits[0]]] + # The worlds where every subtask runs one variant: between the boundaries of the shares of all of them. + ends = sorted({end for expanded in variants.values() for end in itertools.accumulate(n for _, n in expanded)}) + expanded = [] + for start, stop in itertools.pairwise([0, *ends]): + subtasks = {name: _variant_at(variants[name], start) for name in task.subtasks} + expanded.append((replace(task, subtasks=subtasks), stop - start)) + return expanded or [(task, num_worlds)] + + +def _variant_at(variants: list[tuple[TaskCfg, int]], world: int) -> TaskCfg: + """Return the variant of a task, of those that run in consecutive shares of the worlds, that runs in ``world``.""" + stops = list(itertools.accumulate(count for _, count in variants)) + return variants[next(k for k, stop in enumerate(stops) if world < stop)][0] def _local_names(task: TaskCfg, path: str, prefix: str) -> dict[FieldSelector, FieldSelector]: diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py index a9620bbd3751..65c227359902 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py @@ -484,5 +484,7 @@ def sequence(**subtasks: TaskCfg) -> TaskCfg: def split(worlds: dict[str, int] | None = None, **subtasks: TaskCfg) -> TaskCfg: """Run each subtask in its own worlds, ``worlds[name]`` of them, or an even share if ``worlds`` is None; the first - subtasks get one more world when the worlds do not split evenly. A split cannot be part of a sequence.""" + subtasks get one more world when the worlds do not split evenly. A split may be anywhere in a task, such as a step + of a sequence, and several subtasks that split divide the same worlds: a world runs, of each, the subtask of its + share.""" return TaskCfg(subtasks=dict(subtasks), mode=TaskMode.SPLIT, worlds=worlds) diff --git a/source/isaaclab_experimental/test/mdp2/test_mdp2.py b/source/isaaclab_experimental/test/mdp2/test_mdp2.py index 7d68757845e6..398d1798301e 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2.py @@ -1914,14 +1914,32 @@ def test_split_runs_a_sequence_beside_a_plain_task(): assert history[1]["staged.done"].tolist() == [True] * 3 + [False] +def test_splits_divide_the_same_worlds_and_may_be_steps_of_a_sequence(): + """Two subtasks that split divide the same worlds, each world running the subtask of its share of each, and a step + of a sequence may split the worlds.""" + a, b = mdp2.Milestone(mdp2.quantities.a), mdp2.Milestone(mdp2.quantities.b) + task = mdp2.compose( + mdp2.TaskCfg(quantities=above("a", "b")), + x=mdp2.split(p=a, r=b), + y=mdp2.split(worlds={"s": 1, "t": 3}, s=a, t=b), + z=mdp2.sequence(first=a, second=mdp2.split(p=a, r=b)), + ) + mdp, _, history = run_progress(task, [[1.0, 0.0], [1.0, 0.0]], "warp", capture=False, num_worlds=4) + assert [config.worlds for config in mdp.world_configs] == [range(0, 1), range(1, 2), range(2, 4)] + assert history[0]["x.done"].tolist() == [True, True, False, False] + assert history[0]["y.done"].tolist() == [True, False, False, False] + # The sequence's second step runs from step 2: on "a" in the first two worlds, on "b" in the others. + assert history[0]["z.done"].tolist() == [False] * 4 + assert history[1]["z.done"].tolist() == [True, True, False, False] + + def test_task_trees_report_errors(): - """A split in a sequence, a sequence task without a completion, a task with subtasks and a done, and two uses of + """A sequence task without a completion, a task with subtasks and a done, and two uses of one name that may run together are errors.""" schema = PointMassScene(num_worlds=2, joint_names=("a",)).schema quantities = mdp2.TaskCfg(quantities=above("a")) milestone = mdp2.Milestone(mdp2.quantities.a) cases = [ - (mdp2.sequence(first=mdp2.split(x=milestone, y=milestone)), "a sequence cannot"), (mdp2.sequence(first=milestone, second=mdp2.TaskCfg()), "needs a completion"), (mdp2.TaskCfg(done=mdp2.quantities.a, subtasks={"first": milestone}), "cannot have a done"), ] From cb95c955b9bbe87b6ffdebe59af0f36dcc145f35 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 18:51:15 -0800 Subject: [PATCH 13/49] Add mdp2.choice, which draws a subtask per episode and world A choice draws one subtask at each reset from a stream of its own, by its weights, and runs only that subtask's uses: the stage machinery of sequences, with the stage drawn instead of advanced. Progress logs average a drawn task over the worlds that drew it. --- .../changelog.d/mdp2-part2.added.rst | 3 ++ .../isaaclab_experimental/envs/mdp2_env.py | 14 +++++- .../isaaclab_experimental/mdp2/__init__.pyi | 2 + .../isaaclab_experimental/mdp2/builder.py | 30 ++++++++++-- .../isaaclab_experimental/mdp2/compiled.py | 2 +- .../isaaclab_experimental/mdp2/config.py | 14 +++++- .../isaaclab_experimental/mdp2/plan.py | 12 ++++- .../mdp2/torch_backend.py | 37 ++++++++++++++- .../mdp2/warp_backend.py | 47 +++++++++++++++++-- .../test/mdp2/test_mdp2.py | 28 +++++++++++ 10 files changed, 174 insertions(+), 15 deletions(-) diff --git a/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst index 762a16254040..c430f5945970 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst @@ -52,3 +52,6 @@ * Added nested splits to MDP2: a :func:`~isaaclab_experimental.mdp2.split` may be a step of a sequence, and several subtasks that split divide the same worlds, such as robots and terrains, each world running the subtask of its share of each. +* Added :func:`~isaaclab_experimental.mdp2.choice`, which draws one subtask per episode and world at the reset, by + weights, for multi-task learning: only the drawn subtask's uses run, and ``Progress/`` logs its success over + the worlds that drew it. diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py index 48e411dfc138..7a331a1adcd1 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py @@ -506,8 +506,15 @@ def __init__(self, cfg: MDP2RLEnvCfg, render_mode: str | None = None, **kwargs: time_limits = [name for name, term in _terminations(cfg.task) if isinstance(term, mdp2.TimeLimit)] self._time_limit = time_limits[0] if time_limits else None # Progress: whether each task with a completion was done in each world's last finished episode, logged over - # the worlds of the world configs that have it. + # the worlds of the world configs that have it, and for a task of a choice over those that drew it. paths = list(dict.fromkeys(path for tree in self.mdp.tasks for path in sorted(tree.completes))) + drawn = {node.path for tree in self.mdp.tasks for node in tree.nodes if tree.drawn(node)} + everywhere = torch.ones(self.num_envs, dtype=torch.bool, device=self.device) + self._task_runs = [ + self.state.arrays[mdp2.progress_field(path, "active")].torch if path in drawn else everywhere + for path in paths + ] + self._last_runs = torch.ones(self.num_envs, len(paths), device=self.device) self._tasks = { f"Progress/{path or 'task'}": self.state.arrays[mdp2.progress_field(path, "done")].torch for path in paths } @@ -673,6 +680,8 @@ def _after_evaluate(self) -> None: if self._tasks: done_tasks = torch.stack(list(self._tasks.values()), 1).float() torch.where(done[:, None], done_tasks, self._last_done, out=self._last_done) + runs = torch.stack(self._task_runs, 1).float() + torch.where(done[:, None], runs, self._last_runs, out=self._last_runs) if self._time_limit is not None: timed_out = self.state.episode_length.torch >= self.max_episode_length torch.where(done, timed_out, self._last_time_outs, out=self._last_time_outs) @@ -700,7 +709,8 @@ def _log_episodes(self) -> None: log[f"Metrics/{name}"] = last[worlds].mean() # A task is averaged over the worlds of its world config. for k, (name, worlds) in enumerate(zip(self._tasks, self._task_worlds)): - log[name] = self._last_done[worlds, k].mean() + runs = self._last_runs[worlds, k] + log[name] = (self._last_done[worlds, k] * runs).sum() / runs.sum().clamp(min=1.0) self.extras["log"] = log diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/__init__.pyi b/source/isaaclab_experimental/isaaclab_experimental/mdp2/__init__.pyi index bd5699d0c015..a1a564c41727 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/__init__.pyi +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/__init__.pyi @@ -55,6 +55,7 @@ __all__ = [ "Transition", "WorldConfig", "apply_actions", + "choice", "commands", "compose", "episode_length", @@ -107,6 +108,7 @@ from .config import ( TimeLimit, Tunable, UniformNoise, + choice, commands, compose, episode_length, diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py index eef2ec4553c8..23f8d940d6a9 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py @@ -268,7 +268,7 @@ def add(kind: str, name: str, cfg: object, group: str | None = None, concatenate for name, subtask in task.subtasks.items(): subtask_names = names if task.mode is TaskMode.SPLIT else (*names, name) - in_sequence = staged or task.mode is TaskMode.SEQUENCE + in_sequence = staged or task.mode in (TaskMode.SEQUENCE, TaskMode.CHOICE) self._add_task(subtask, (*path, name), subtask_names, in_sequence, scope, restarts) def add_action(self, name: str, action: DirectAction | Action) -> ScheduleEntry: @@ -415,7 +415,7 @@ def _compile( errors.append(f"The world configs cover {world_ranges[-1].stop} of {self.schema.num_worlds} worlds.") # Progress is tracked if any task has a completion or a sequence. tracked = any( - task.done is not None or task.mode is TaskMode.SEQUENCE + task.done is not None or task.mode in (TaskMode.SEQUENCE, TaskMode.CHOICE) for _, tasks, _ in configs for task, _ in tasks.values() ) @@ -484,6 +484,19 @@ def _compile( else op for op in ops[Phase.OBSERVATIONS] ) + # A choice draws its subtask from a stream of its own. + trees = tuple( + replace( + tree, + nodes=tuple( + replace(node, stream=streams.setdefault(f"choice/{node.path}", len(streams))) + if node.mode is TaskMode.CHOICE + else node + for node in tree.nodes + ), + ) + for tree in trees + ) ops = MappingProxyType(ops) tuned = _tuned_values(ops, errors) @@ -536,7 +549,8 @@ def _compile_actions( for path, (task, _) in tasks.items(): for name in ("done", "holding", "active"): context.mdp_fields[progress_field(path, name)] = ArrayLayout(wp.bool, 1, {}) - sequence, repeat = ["stage"] if task.mode is TaskMode.SEQUENCE else [], ["count"] if task.repeat else [] + staged = ["stage"] if task.mode in (TaskMode.SEQUENCE, TaskMode.CHOICE) else [] + sequence, repeat = staged, ["count"] if task.repeat else [] for name in ("done_at", "started_at", *sequence, *repeat): context.mdp_fields[progress_field(path, name)] = ArrayLayout(wp.int32, 1, {}) context.mdp_fields[progress_field(path, "score")] = ArrayLayout(wp.float32, 1, {}) @@ -616,6 +630,13 @@ def _compile_task(self, path: str, tasks: dict[str, tuple[TaskCfg, bool]], conte if task.mode is TaskMode.SEQUENCE and len(completes) != len(children): missing = sorted(set(task.subtasks) - set(completes)) errors.append(f"{name}: every task of a sequence needs a completion, {missing} have none.") + weights = () + if task.mode is TaskMode.CHOICE: + chances = task.weights or dict.fromkeys(task.subtasks, 1.0) + if set(chances) != set(task.subtasks) or not all(chance >= 0 for chance in chances.values()): + errors.append(f"{name}: a choice needs a weight of at least 0 for each of {list(task.subtasks)}.") + elif sum(chances.values()) > 0: + weights = tuple(chances[child] / sum(chances.values()) for child in task.subtasks) if task.require is not None and not 1 <= task.require <= len(completes): errors.append(f"{name}: require must be between 1 and {len(completes)}, the subtasks with a completion.") return TaskNode( @@ -630,6 +651,7 @@ def _compile_task(self, path: str, tasks: dict[str, tuple[TaskCfg, bool]], conte require=task.require, staged=staged, repeat=task.repeat, + weights=weights, ) def _compile_action(self, entry: ScheduleEntry, context: CompileContext) -> None: @@ -1405,7 +1427,7 @@ def _exclusive(first: TermOp, second: TermOp, modes: Mapping[str, TaskMode]) -> common = list(itertools.takewhile(lambda pair: pair[0] == pair[1], zip(a, b))) if len(common) in (len(a), len(b)): return False - return modes.get(".".join(part for part, _ in common)) is TaskMode.SEQUENCE + return modes.get(".".join(part for part, _ in common)) in (TaskMode.SEQUENCE, TaskMode.CHOICE) def _used_columns(ops: tuple[TermOp, ...], worlds: range) -> dict[str, int]: diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py index 74b6465e4c7e..ec23c5e79f9a 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py @@ -505,7 +505,7 @@ def array(path: str, name: str, dtype: type, initial: float = 0) -> np.ndarray: array(node.path, "done_at", np.int32, -1) array(node.path, "started_at", np.int32) array(node.path, "score", np.float32) - if node.mode is TaskMode.SEQUENCE: + if node.mode in (TaskMode.SEQUENCE, TaskMode.CHOICE): array(node.path, "stage", np.int32) if node.done is not None: array(node.path, "streak", np.int32) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py index 65c227359902..df0bf6bd1b45 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py @@ -335,6 +335,7 @@ class TaskMode(enum.Enum): TOGETHER = enum.auto() # In the same worlds and steps SEQUENCE = enum.auto() # In the same worlds, one after another SPLIT = enum.auto() # Each in its own worlds + CHOICE = enum.auto() # One per episode and world, drawn at the reset @dataclass @@ -372,6 +373,7 @@ class TaskCfg: mode: TaskMode = TaskMode.TOGETHER require: int | None = None # Together: the subtasks that must be done, None for all of those with a completion worlds: dict[str, int] | None = None # Split: the worlds of each subtask, None for even shares + weights: dict[str, float] | None = None # Choice: the relative chance of each subtask, None for even chances @dataclass(init=False) @@ -394,7 +396,8 @@ def __init__( PROGRESS_FIELDS = ("done", "holding", "active", "score", "done_at", "started_at", "stage", "count") """Fields of the progress of a task: whether it is done (once done, until the episode ends), whether its completion holds at this step, whether it runs, its score in ``[0, 1]``, the episode step at which it was first done (-1 before) -and at which it last started, the subtask that a sequence runs, and how often a task that repeats was done.""" +and at which it last started, the subtask that a sequence or a choice runs, and how often a task that repeats was +done.""" @dataclass(frozen=True) @@ -465,7 +468,7 @@ def merge(path: tuple[str, ...], target: dict, uses: dict, index: int) -> None: composed.done, composed.hold, composed.score, composed.final = core.done, core.hold, core.score, core.final composed.repeat = core.repeat composed.subtasks, composed.mode = dict(core.subtasks), core.mode - composed.require, composed.worlds = core.require, core.worlds + composed.require, composed.worlds, composed.weights = core.require, core.worlds, core.weights if subtasks: if cores: errors.append("Tasks with a completion or subtasks cannot also get named subtasks; name them as well.") @@ -482,6 +485,13 @@ def sequence(**subtasks: TaskCfg) -> TaskCfg: return TaskCfg(subtasks=dict(subtasks), mode=TaskMode.SEQUENCE) +def choice(weights: dict[str, float] | None = None, **subtasks: TaskCfg) -> TaskCfg: + """Run one of the subtasks in each episode and world, drawn at the reset with the relative chances ``weights``, + even ones if None, such as one skill of several for a policy to learn. The task is done once the drawn subtask is, + and ``mdp2.progress..stage`` is the index of the drawn subtask.""" + return TaskCfg(subtasks=dict(subtasks), mode=TaskMode.CHOICE, weights=weights) + + def split(worlds: dict[str, int] | None = None, **subtasks: TaskCfg) -> TaskCfg: """Run each subtask in its own worlds, ``worlds[name]`` of them, or an even share if ``worlds`` is None; the first subtasks get one more world when the worlds do not split evenly. A split may be anywhere in a task, such as a step diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py index fd07de433f45..3b3541eac395 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py @@ -196,6 +196,8 @@ class TaskNode: # ancestors repeats staged: bool repeat: bool = False + weights: tuple[float, ...] = () # Choice: the chance of each subtask + stream: int | None = None # Choice: row of MDPState.rng that draws the subtask @dataclass(frozen=True) @@ -213,13 +215,21 @@ def parent(self, node: TaskNode) -> TaskNode | None: return None if not node.path else self.node(node.path.rpartition(".")[0]) def runs_at_start(self, node: TaskNode) -> bool: - """Return whether a task runs at the start of an episode: all but the later tasks of a sequence do.""" + """Return whether a task runs at the start of every episode: all but the later tasks of a sequence and the + tasks of a choice, which the reset draws, do.""" parent = self.parent(node) if parent is None: return True + if parent.mode is TaskMode.CHOICE: + return False # Until the reset draws it first = parent.mode is not TaskMode.SEQUENCE or parent.children[0] == node.path return first and self.runs_at_start(parent) + def drawn(self, node: TaskNode) -> bool: + """Return whether the reset draws whether a task runs: it or one of its ancestors is a subtask of a choice.""" + parent = self.parent(node) + return parent is not None and (parent.mode is TaskMode.CHOICE or self.drawn(parent)) + def restarts(self, node: TaskNode) -> bool: """Return whether a task restarts while it runs: it or one of its ancestors repeats.""" parent = self.parent(node) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py index b9b82e8aa5cc..cecc7fcdaf35 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py @@ -8,6 +8,7 @@ from __future__ import annotations import functools +import itertools import math import torch @@ -376,6 +377,14 @@ def _update_progress(trees: tuple[TaskTree, ...], state: MDPState) -> None: stage.add_((active & ~finished & (stage < len(counted)) & current).int()) complete = (stage == len(counted)) & finals holding.copy_(held[:, -1]) + elif node.mode is TaskMode.CHOICE: + # Done once the drawn subtask is. + stage, complete = field("stage"), torch.zeros_like(active) + holding.zero_() + for k, child in enumerate(counted): + chosen = stage == node.children.index(child.path) + complete = torch.where(chosen, done_children[:, k], complete) + holding.copy_(torch.where(chosen, held[:, k], holding)) else: required = node.require or len(counted) complete = (done_children.sum(1) >= required) & finals @@ -414,7 +423,8 @@ def _repeat(state: MDPState, tree: TaskTree, node, complete: torch.Tensor, lengt for child in tree.descendants(node): for name, value in initial.items(): key = progress_field(child.path, name) - if key in state.arrays: + # A choice keeps the subtask it drew. + if key in state.arrays and not (name == "stage" and child.mode is TaskMode.CHOICE): state.arrays[key].torch[tree.worlds.start : tree.worlds.stop].masked_fill_(restarted, value) @@ -422,6 +432,12 @@ def _score(state: MDPState, tree: TaskTree, node) -> torch.Tensor: """Return a task's score from its subtasks': their weighted mean, or the mean of the best ``require`` of them.""" counted = tree.counted(node) scores = torch.stack([_progress(state, tree, child.path, "score") for child in counted], 1) + if node.mode is TaskMode.CHOICE: + # The score of the drawn subtask. + stage, score = _progress(state, tree, node.path, "stage"), torch.zeros_like(scores[:, 0]) + for k, child in enumerate(counted): + score = torch.where(stage == node.children.index(child.path), scores[:, k], score) + return score if node.mode is TaskMode.TOGETHER and node.require is not None: return scores.topk(node.require, dim=1).values.mean(1) total = sum(child.score for child in counted) @@ -442,6 +458,8 @@ def _start_tasks(trees: tuple[TaskTree, ...], state: MDPState) -> None: # The last task keeps running once it is done. stage = _progress(state, tree, parent.path, "stage").clamp(max=len(parent.children) - 1) runs &= stage == parent.children.index(node.path) + elif parent is not None and parent.mode is TaskMode.CHOICE: + runs &= _progress(state, tree, parent.path, "stage") == parent.children.index(node.path) # A task starts where it did not run, and restarts with a parent that started or a repeat. fresh = ~active if parent is not None and tree.restarts(parent): @@ -455,7 +473,8 @@ def _start_tasks(trees: tuple[TaskTree, ...], state: MDPState) -> None: def _reset_progress(trees: tuple[TaskTree, ...], state: MDPState, mask: torch.Tensor) -> None: - """Restart the progress of every task in the masked worlds, as at the start of an episode.""" + """Restart the progress of every task in the masked worlds, as at the start of an episode, parents first: a choice + draws its subtask.""" for tree in trees: selected = mask[tree.worlds.start : tree.worlds.stop] for node in tree.nodes: @@ -466,3 +485,17 @@ def _reset_progress(trees: tuple[TaskTree, ...], state: MDPState, mask: torch.Te key = progress_field(node.path, name) if key in state.arrays: state.arrays[key].torch[tree.worlds.start : tree.worlds.stop].masked_fill_(selected, value) + if node.mode is TaskMode.CHOICE: + draw = rng.uniform(state.rng.torch[node.stream], 0.0, 1.0)[tree.worlds.start : tree.worlds.stop] + drawn = sum((draw >= bound).int() for bound in itertools.accumulate(node.weights[:-1])) + stage = _progress(state, tree, node.path, "stage") + stage.copy_(torch.where(selected, drawn, stage)) + if tree.drawn(node): + parent, index = tree.parent(node), tree.parent(node).children.index(node.path) + runs = _progress(state, tree, parent.path, "active") + if parent.mode is TaskMode.CHOICE: + runs = runs & (_progress(state, tree, parent.path, "stage") == index) + elif parent.mode is TaskMode.SEQUENCE and index > 0: + runs = torch.zeros_like(runs) + active = _progress(state, tree, node.path, "active") + active.copy_(torch.where(selected, runs, active)) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py index 9ee2df0e58dc..a12b9327c919 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py @@ -15,6 +15,7 @@ from __future__ import annotations import functools +import itertools import math from collections.abc import Callable, Hashable, Iterable, Sequence @@ -728,6 +729,14 @@ def _node_progress(code: Fusion, tree: TaskTree, node: TaskNode, length: str) -> f"complete = {stage} == {len(counted)} and ({finals})", f"{holding} = {children[-1]('holding')}", ] + elif node.mode is TaskMode.CHOICE: + # Done once the drawn subtask is. + lines = ["complete = False", f"{holding} = False"] + for k, child_path in enumerate(node.children): + if child_path in tree.completes: + child = functools.partial(_progress, code, child_path) + lines += _under([f"if {field('stage')} == {k}:"], f"complete = {child('done')}") + lines += _under([f"if {field('stage')} == {k}:"], f"{holding} = {child('holding')}") else: required = node.require or len(counted) lines = [ @@ -754,6 +763,13 @@ def _node_progress(code: Fusion, tree: TaskTree, node: TaskNode, length: str) -> counted = tree.counted(node) scores = [_progress(code, child.path, "score") for child in counted] + if node.mode is TaskMode.CHOICE: + # The score of the drawn subtask. + lines.append(f"{score} = 0.0") + for child in counted: + k = node.children.index(child.path) + lines += _under([f"if {field('stage')} == {k}:"], f"{score} = {_progress(code, child.path, 'score')}") + return [*lines, *kept] if node.mode is TaskMode.TOGETHER and node.require is not None: # The mean of the best ``require`` scores, picked one at a time. lines += ["taken = int(0)", "total = float(0.0)"] @@ -822,6 +838,8 @@ def _start_tasks(code: Fusion, trees: tuple[TaskTree, ...]) -> None: # The last task keeps running once it is done. stage = f"wp.min({_progress(code, parent.path, 'stage')}, {len(parent.children) - 1})" runs = f"{runs} and {stage} == {parent.children.index(node.path)}" + elif parent is not None and parent.mode is TaskMode.CHOICE: + runs = f"{runs} and {_progress(code, parent.path, 'stage')} == {parent.children.index(node.path)}" field = functools.partial(_progress, code, node.path) # A task starts where it did not run, and restarts with a parent that started or a repeat. fresh = [f"not {field('active')}"] @@ -840,7 +858,8 @@ def _start_tasks(code: Fusion, trees: tuple[TaskTree, ...]) -> None: def _reset_progress(code: Fusion, trees: tuple[TaskTree, ...]) -> None: - """Restart the progress of every task in the masked worlds, as at the start of an episode.""" + """Restart the progress of every task in the masked worlds, as at the start of an episode, parents first: a choice + draws its subtask.""" for tree in trees: lines = [] for node in tree.nodes: @@ -851,8 +870,9 @@ def _reset_progress(code: Fusion, trees: tuple[TaskTree, ...]) -> None: f"{field('done_at')} = -1", f"{field('started_at')} = 0", f"{field('score')} = 0.0", - f"{field('active')} = {tree.runs_at_start(node)}", - *([f"{field('stage')} = 0"] if node.mode is TaskMode.SEQUENCE else []), + f"{field('active')} = {_runs_at_start(code, tree, node)}", + *([f"{field('stage')} = 0"] if node.mode in (TaskMode.SEQUENCE, TaskMode.CHOICE) else []), + *(_draw(code, node) if node.mode is TaskMode.CHOICE else []), *([f"{field('streak')} = 0"] if node.done is not None else []), *([f"{field('entered')} = False"] if node.staged else []), *([f"{field('count')} = 0", f"{field('spent')} = False"] if node.repeat else []), @@ -863,6 +883,27 @@ def _reset_progress(code: Fusion, trees: tuple[TaskTree, ...]) -> None: code.world(*_under(_in_tree(trees, tree), *lines), writes=_tree_writes(tree, names)) +def _runs_at_start(code: Fusion, tree: TaskTree, node: TaskNode) -> str: + """Return source for whether a task runs at the start of an episode, after its parent's start: below a choice, + where the choice drew it.""" + if not tree.drawn(node): + return str(tree.runs_at_start(node)) + parent = tree.parent(node) + runs = _progress(code, parent.path, "active") + index = parent.children.index(node.path) + if parent.mode is TaskMode.CHOICE: + return f"{runs} and {_progress(code, parent.path, 'stage')} == {index}" + return "False" if parent.mode is TaskMode.SEQUENCE and index > 0 else runs + + +def _draw(code: Fusion, node: TaskNode) -> list[str]: + """Return the statements that draw the subtask of a choice by its chances.""" + lines = [f"draw = wp.randf(wp.rand_init({_rng(code)}[{node.stream}, world], 0), 0.0, 1.0)"] + for k, bound in enumerate(itertools.accumulate(node.weights[:-1]), start=1): + lines += [f"if draw >= {bound!r}:", f" {_progress(code, node.path, 'stage')} = {k}"] + return lines + + def _switch(code: Fusion, ops: tuple[TermOp, ...], stepping: bool) -> None: """Turn each op with ``when`` on where its task runs and its field is positive. Stepping marks the worlds where it turned on, whose state restarts; observing new episodes marks none, since resets restarted them.""" diff --git a/source/isaaclab_experimental/test/mdp2/test_mdp2.py b/source/isaaclab_experimental/test/mdp2/test_mdp2.py index 398d1798301e..eb5a46b8d380 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2.py @@ -2293,3 +2293,31 @@ def test_actions_apply_once_per_control_step_or_before_every_physics_step(): target = scene.data("robot", "joint_effort_target").torch assert target.tolist() == [[3.0, 1.0], [6.0, 0.5]] and torch.equal(state.actions.torch, actions.torch) assert len(mdp.launches.process_actions) == 1 and len(mdp.plan.apply_actions) == 1 + + +def test_choice_draws_one_subtask_per_episode_and_world(): + """A choice draws one subtask per world at each reset, by its weights: only that subtask's uses run, the task is + done once it is, and its ``stage`` is the drawn subtask.""" + + def skill(joint: str, reward: float) -> mdp2.TaskCfg: + alive = mdp2.Reward(is_alive, inputs={"joint_pos": robot.joint_pos}, weight=reward) + return mdp2.TaskCfg(rewards={"alive": alive}, done=getattr(mdp2.quantities, joint)) + + task = mdp2.compose( + mdp2.TaskCfg(quantities=above("a", "b")), + skills=mdp2.choice(weights={"left": 3.0, "right": 1.0}, left=skill("a", 1.0), right=skill("b", 2.0)), + ) + runs = [] + for backend in ("torch", "warp"): + for capture in (False, True) if torch.cuda.is_available() else (False,): + runs.append(run_progress(task, [[1.0, 0.0]], backend, capture, num_worlds=256)[2][0]) + for run in runs[1:]: + for name, value in runs[0].items(): + assert torch.equal(value, run[name]), name + + step = runs[0] + left = step["skills.stage"] == 0 + assert 0.65 < left.float().mean().item() < 0.85 + assert torch.equal(step["skills.left.active"], left) and torch.equal(step["skills.right.active"], ~left) + assert torch.equal(step["done"], left) # Joint "a" is up, "b" is down + torch.testing.assert_close(step["rewards"] / 0.02, torch.where(left, 1.0, 2.0)) From e025fec17bf591cd6ad84124413561f5c864eda3 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 18:54:43 -0800 Subject: [PATCH 14/49] Give MDP2 subtasks that run together columns of their own, and add rename Uses of subtasks that run together get columns named with the subtask's name, while uses of subtasks that take turns share the columns of their name. mdp2.rename binds a part to other scene entities, so that one part, such as an arm, runs twice. --- .../changelog.d/mdp2-part2.added.rst | 3 ++ .../isaaclab_experimental/mdp2/__init__.pyi | 2 + .../isaaclab_experimental/mdp2/builder.py | 18 +++++-- .../isaaclab_experimental/mdp2/config.py | 26 ++++++++++ .../test/mdp2/test_mdp2.py | 47 ++++++++++++++----- 5 files changed, 80 insertions(+), 16 deletions(-) diff --git a/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst index c430f5945970..4d137c92c56b 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst @@ -55,3 +55,6 @@ * Added :func:`~isaaclab_experimental.mdp2.choice`, which draws one subtask per episode and world at the reset, by weights, for multi-task learning: only the drawn subtask's uses run, and ``Progress/`` logs its success over the worlds that drew it. +* Added :func:`~isaaclab_experimental.mdp2.rename`, which binds a part of a task to other scene entities, so that a + part can run twice, such as two arms. Uses of subtasks that run together get columns of their own, named with the + subtask's name, as in ``left.joint_pos``; uses of subtasks that take turns share the columns of their name. diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/__init__.pyi b/source/isaaclab_experimental/isaaclab_experimental/mdp2/__init__.pyi index a1a564c41727..baf0c79f74b1 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/__init__.pyi +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/__init__.pyi @@ -66,6 +66,7 @@ __all__ = [ "progress", "progress_field", "quantities", + "rename", "reset", "sequence", "split", @@ -116,6 +117,7 @@ from .config import ( progress, progress_field, quantities, + rename, sequence, split, step_dt, diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py index 23f8d940d6a9..5f2fd07b5e03 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py @@ -77,7 +77,9 @@ class ScheduleEntry: path: tuple[str, ...] # Location in the task, e.g. ("observations", "policy", "joint_pos") cfg: DirectAction | Action | Command | Quantity | Observation | Reward | Termination | TimeLimit | Event concatenate: bool = True # Observations: whether the use writes its group's buffer rather than its own - name: str = "" # Name in its task, without the prefix of a subtask; the last part of the path if empty + # Name of its columns, which uses of the same name share: its name in its task, after the names of its subtasks + # that run together with others; the last part of the path if empty + name: str = "" stage: str | None = None # The task of a sequence that the use belongs to, see TermOp.stage @property @@ -217,9 +219,15 @@ def _add_task( staged: bool, scope: dict[FieldSelector, FieldSelector], restarts: bool = False, + columns: tuple[str, ...] = (), ) -> None: """Add a task of one world config, its uses with the prefix ``names``, then its subtasks. ``staged`` is - whether it is part of a sequence, and ``restarts`` whether it or a parent repeats. + whether it is part of a sequence, ``restarts`` whether it or a parent repeats, and ``columns`` the prefix of + the names of its uses' columns. + + Uses of subtasks that run together get columns of their own, named with the subtask's name, as in + ``left.joint_pos``; uses of subtasks that take turns, in a sequence, a choice, or a split, share the columns of + their name. The subtask of a split runs in worlds of its own, so its uses keep their names: equal uses of the world configs then run once, see :meth:`replicate`. A task reads its own fields by their names, as a task that runs alone @@ -245,7 +253,8 @@ def add(kind: str, name: str, cfg: object, group: str | None = None, concatenate setup = isinstance(cfg, Event) and cfg.mode is not EventMode.INTERVAL full = f"{prefix}.{name}" if prefix else name entry_path = (kind, full) if group is None else (kind, group, full) - self._add(ScheduleEntry(entry_path, _scoped(cfg, scope), concatenate, name, None if setup else stage)) + slot = ".".join((*columns, name)) + self._add(ScheduleEntry(entry_path, _scoped(cfg, scope), concatenate, slot, None if setup else stage)) for kind in ("actions", "commands", "quantities"): for name, use in getattr(task, kind).items(): @@ -269,7 +278,8 @@ def add(kind: str, name: str, cfg: object, group: str | None = None, concatenate for name, subtask in task.subtasks.items(): subtask_names = names if task.mode is TaskMode.SPLIT else (*names, name) in_sequence = staged or task.mode in (TaskMode.SEQUENCE, TaskMode.CHOICE) - self._add_task(subtask, (*path, name), subtask_names, in_sequence, scope, restarts) + together = (*columns, name) if task.mode is TaskMode.TOGETHER else columns + self._add_task(subtask, (*path, name), subtask_names, in_sequence, scope, restarts, together) def add_action(self, name: str, action: DirectAction | Action) -> ScheduleEntry: return self._add(ScheduleEntry(("actions", name), action)) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py index df0bf6bd1b45..44510635de0f 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py @@ -7,6 +7,7 @@ from __future__ import annotations +import dataclasses import enum from dataclasses import dataclass, field from typing import Any, ClassVar @@ -479,6 +480,31 @@ def merge(path: tuple[str, ...], target: dict, uses: dict, index: int) -> None: return composed +def rename(task: TaskCfg, **entities: str) -> TaskCfg: + """Return a copy of a task whose uses read and write other scene entities, by their old names: with + ``rename(ARM, robot="left_arm")``, the uses of a part written for an entity ``robot`` act on ``left_arm``, so that + a part can appear twice, as subtasks that run together, such as ``compose(left=..., right=...)``.""" + return _renamed(task, entities) + + +def _renamed(value: Any, entities: dict[str, str]) -> Any: + """Return a copy of a config value with the scene entities of its selectors renamed; params and terms stay.""" + if isinstance(value, (FieldSelector, SubsetSelector)): + return dataclasses.replace(value, entity=entities.get(value.entity, value.entity)) if value.scene else value + if isinstance(value, Entity): + return Entity(entities.get(value.name, value.name), value.scene) if value.scene else value + if isinstance(value, dict): + return {key: _renamed(item, entities) for key, item in value.items()} + if dataclasses.is_dataclass(value) and not isinstance(value, (type, Term, Tunable)): + changes = { + spec.name: _renamed(getattr(value, spec.name), entities) + for spec in dataclasses.fields(value) + if spec.init and spec.name not in ("params", "term") + } + return dataclasses.replace(value, **changes) + return value + + def sequence(**subtasks: TaskCfg) -> TaskCfg: """Run subtasks one after another, in the same worlds. A subtask starts at the step after the previous one is done, and the task is done once the last one is, which keeps running until the episode ends.""" diff --git a/source/isaaclab_experimental/test/mdp2/test_mdp2.py b/source/isaaclab_experimental/test/mdp2/test_mdp2.py index eb5a46b8d380..b9d4146b8d8f 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2.py @@ -25,7 +25,8 @@ class PointMassScene: - """Scene for the tests: one ``"robot"`` whose joints are unit point masses driven by their effort targets.""" + """Scene for the tests: one ``"robot"``, or other entities, whose joints are unit point masses driven by their + effort targets.""" def __init__( self, @@ -34,6 +35,7 @@ def __init__( dt: float = 0.01, decimation: int = 2, device: str = "cpu", + entities: tuple[str, ...] = ("robot",), ): fields = dict.fromkeys( ("joint_pos", "joint_vel", "joint_effort_target"), mdp2.FieldSchema(("joints",), writable=True) @@ -46,13 +48,16 @@ def __init__( self.schema = mdp2.SceneSchema( num_worlds=num_worlds, step_dt=dt * decimation, - entities={"robot": mdp2.EntitySchema(names={"joints": joint_names}, fields=fields)}, + entities={entity: mdp2.EntitySchema(names={"joints": joint_names}, fields=fields) for entity in entities}, ) self.dt = dt self.decimation = decimation shape = (num_worlds, len(joint_names)) - self._data = {"robot": {name: ProxyArray(wp.zeros(shape, dtype=wp.float32, device=device)) for name in fields}} + self._data = { + entity: {name: ProxyArray(wp.zeros(shape, dtype=wp.float32, device=device)) for name in fields} + for entity in entities + } def data(self, entity: str, field: str) -> ProxyArray: return self._data[entity][field] @@ -1934,8 +1939,7 @@ def test_splits_divide_the_same_worlds_and_may_be_steps_of_a_sequence(): def test_task_trees_report_errors(): - """A sequence task without a completion, a task with subtasks and a done, and two uses of - one name that may run together are errors.""" + """A sequence task without a completion and a task with subtasks and a done are errors.""" schema = PointMassScene(num_worlds=2, joint_names=("a",)).schema quantities = mdp2.TaskCfg(quantities=above("a")) milestone = mdp2.Milestone(mdp2.quantities.a) @@ -1949,13 +1953,6 @@ def test_task_trees_report_errors(): builder.add_task(mdp2.compose(quantities, task)) builder.validate() - observation = mdp2.Observation(joint_pos, inputs={"joint_pos": robot.joint_pos}) - sharing = mdp2.TaskCfg(observations={"policy": {"position": observation}}, done=mdp2.quantities.a) - builder = mdp2.MDPBuilder(schema) - builder.add_task(mdp2.compose(quantities, first=sharing, second=sharing)) - with pytest.raises(ValueError, match="share the columns of 'position'"): - builder.validate() - @wp.func def scaled_sum_warp(world: int, joint_pos: wp.array2d(dtype=float), gain: float) -> float: @@ -2321,3 +2318,29 @@ def skill(joint: str, reward: float) -> mdp2.TaskCfg: assert torch.equal(step["skills.left.active"], left) and torch.equal(step["skills.right.active"], ~left) assert torch.equal(step["done"], left) # Joint "a" is up, "b" is down torch.testing.assert_close(step["rewards"] / 0.02, torch.where(left, 1.0, 2.0)) + + +def test_parts_renamed_to_other_entities_run_together_in_columns_of_their_own(): + """One part, renamed to act on two robots, runs twice as subtasks together: each copy's actions and observations + get columns of their own, named with the subtask's name.""" + arm = mdp2.TaskCfg( + actions={"effort": mdp2.DirectAction(robot.joint_effort_target)}, + observations={"policy": {"position": mdp2.Observation(joint_pos, inputs={"joint_pos": robot.joint_pos})}}, + ) + task = mdp2.compose(left=mdp2.rename(arm, robot="left"), right=mdp2.rename(arm, robot="right")) + scene = PointMassScene(num_worlds=2, joint_names=("a", "b"), device=DEVICE, entities=("left", "right")) + builder = mdp2.MDPBuilder(scene.schema) + builder.add_task(task) + mdp = builder.finalize(device=DEVICE, backend="warp") + spec = mdp.spec() + assert [(columns.name, columns.columns) for columns in spec.actions] == [ + ("left.effort", slice(0, 2)), + ("right.effort", slice(2, 4)), + ] + assert [columns.name for columns in spec.observations["policy"]] == ["left.position", "right.position"] + + state = mdp.state(scene) + actions = torch.tensor([[1.0, 2.0, 3.0, 4.0]] * 2, device=DEVICE) + mdp2.apply_actions(mdp, state, ProxyArray(wp.from_torch(actions))) + assert scene.data("left", "joint_effort_target").torch.tolist() == [[1.0, 2.0]] * 2 + assert scene.data("right", "joint_effort_target").torch.tolist() == [[3.0, 4.0]] * 2 From 98b4f36f2bb6c56c6b95079035cc8ab9608026f9 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 18:59:02 -0800 Subject: [PATCH 15/49] Add MDP2 start events, and let reset events read the ended progress An event with EventMode.START writes the scene when its task starts: at the reset for a task that runs from the start, and at the step it starts otherwise, in the worlds that the scene then commits. Reset events now run before the progress of the tasks restarts, so a curriculum can read the milestones of the episode that ended. --- .../changelog.d/mdp2-part2.added.rst | 2 + .../changelog.d/mdp2-part2.changed.rst | 3 + .../isaaclab_experimental/envs/mdp2_env.py | 10 ++-- .../isaaclab_experimental/mdp2/builder.py | 23 ++++++-- .../isaaclab_experimental/mdp2/compiled.py | 18 +++--- .../isaaclab_experimental/mdp2/config.py | 12 ++-- .../isaaclab_experimental/mdp2/plan.py | 33 +++++++---- .../mdp2/torch_backend.py | 9 ++- .../mdp2/warp_backend.py | 14 +++-- .../test/mdp2/test_mdp2.py | 55 +++++++++++++++++++ 10 files changed, 139 insertions(+), 40 deletions(-) diff --git a/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst index 4d137c92c56b..32894309d799 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst @@ -58,3 +58,5 @@ * Added :func:`~isaaclab_experimental.mdp2.rename`, which binds a part of a task to other scene entities, so that a part can run twice, such as two arms. Uses of subtasks that run together get columns of their own, named with the subtask's name, as in ``left.joint_pos``; uses of subtasks that take turns share the columns of their name. +* Added start events to MDP2, ``EventMode.START``: an event of a task of a sequence or a choice, or of a task that + repeats, writes the scene when its task starts, at the reset or during the episode, where the scene commits it. diff --git a/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst b/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst index c8dc10d0ad80..eb17d36226b6 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst @@ -8,3 +8,6 @@ as the widest, as observations do, and the last actions hold zero in the columns a world does not take, which :meth:`~isaaclab_experimental.mdp2.MDP.action_mask` gives. This replaces the narrow copies of the last actions and ``MDP.narrow_action_dims``. +* Changed the order of an MDP2 reset: reset events run before the progress of the tasks restarts, so that they read + the progress of the episode that ended, such as a curriculum over milestones. ``MDP.interval_writes`` is now + :attr:`~isaaclab_experimental.mdp2.MDP.step_writes`, which also holds the writes of start events. diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py index 7a331a1adcd1..07171238163a 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py @@ -142,8 +142,8 @@ def _init_sim(self) -> None: self.actions = ProxyArray(wp.zeros((self.num_envs, self.mdp.action_dim), dtype=wp.float32, device=self.device)) # The worlds whose scene writes a step commits: those reset, and those where an interval event wrote. - self._interval_worlds = self.state.arrays.get("interval_worlds") - if self._interval_worlds is not None: + self._event_worlds = self.state.arrays.get("event_worlds") + if self._event_worlds is not None: self._commit_mask = ProxyArray(wp.zeros(self.num_envs, dtype=wp.bool, device=self.device)) self.common_step_counter = 0 self.extras: dict[str, Any] = {} @@ -373,11 +373,11 @@ def _views(self, buffers: dict[str, ProxyArray]) -> VecEnvObs: def _commit(self, mask: ProxyArray) -> None: """Commit the writes of the reset events in the masked worlds, and of the interval events of the last step in the worlds where they ran. Part of the captured step.""" - if self._interval_worlds is None: + if self._event_worlds is None: self.scene_data.commit(mask.warp, self.mdp.reset_writes) return - torch.logical_or(mask.torch, self._interval_worlds.torch, out=self._commit_mask.torch) - self.scene_data.commit(self._commit_mask.warp, self.mdp.reset_writes | self.mdp.interval_writes) + torch.logical_or(mask.torch, self._event_worlds.torch, out=self._commit_mask.torch) + self.scene_data.commit(self._commit_mask.warp, self.mdp.reset_writes | self.mdp.step_writes) def _reset_scene(self, mask: ProxyArray) -> None: """Reset the assets and sensors of the masked worlds, before the MDP's reset events.""" diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py index 5f2fd07b5e03..e4eb436c2cc1 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py @@ -250,7 +250,7 @@ def add(kind: str, name: str, cfg: object, group: str | None = None, concatenate if isinstance(cfg, TimeLimit) and staged: raise ValueError(f"Task '{task_path}': the tasks of a sequence cannot have a time limit.") # Reset and startup events set up whole episodes, so they run in every world of their task. - setup = isinstance(cfg, Event) and cfg.mode is not EventMode.INTERVAL + setup = isinstance(cfg, Event) and cfg.mode in (EventMode.STARTUP, EventMode.RESET) full = f"{prefix}.{name}" if prefix else name entry_path = (kind, full) if group is None else (kind, group, full) slot = ".".join((*columns, name)) @@ -756,12 +756,10 @@ def _compile_term(self, entry: ScheduleEntry, context: CompileContext) -> None: dims = _resolve_shape(entry, f"state {name!r}", shape, sizes, errors) if dims is not None: state_shapes[name] = dims if name in shared else (self.schema.num_worlds, *dims) - if isinstance(cfg, Event) and (cfg.mode is EventMode.INTERVAL) != (cfg.interval_range_s is not None): - errors.append(f"{entry}: interval events need an interval_range_s, and other events cannot have one.") + if isinstance(cfg, Event): + _check_event(entry, errors) if isinstance(cfg, Quantity) and (cfg.log or cfg.record) and output_shape: errors.append(f"{entry}: a logged or recorded quantity must have shape ('worlds',), got {output_shape}.") - if isinstance(cfg, Event) and cfg.commit is True and cfg.mode is not EventMode.RESET: - errors.append(f"{entry}: only reset events can ask for a commit.") if isinstance(cfg, Command) and implementation is not None and implementation.reset is not None: errors.append(f"{entry}: commands write their state when they resample, so they have no reset hook.") if isinstance(cfg, Observation) and cfg.noise is not None and cfg.noise.scale is not None: @@ -1008,6 +1006,21 @@ def _allocate_columns( return None, None +def _check_event(entry: ScheduleEntry, errors: list[str]) -> None: + """Record why an event cannot be compiled: its interval, its commit, or a start event of a task that never + starts during an episode.""" + cfg = entry.cfg + if (cfg.mode is EventMode.INTERVAL) != (cfg.interval_range_s is not None): + errors.append(f"{entry}: interval events need an interval_range_s, and other events cannot have one.") + if cfg.commit is True and cfg.mode not in (EventMode.RESET, EventMode.START): + errors.append(f"{entry}: only reset and start events can ask for a commit.") + if cfg.mode is EventMode.START and entry.stage is None: + errors.append( + f"{entry}: a start event runs when its task starts, so it belongs to a task of a sequence or a choice," + " or to one that repeats." + ) + + def _check_action(entry: ScheduleEntry, output_shape: tuple[int, ...] | None, errors: list[str]) -> None: """Record why an action term cannot be compiled: its shape or its hooks. diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py index ec23c5e79f9a..14db74a8cb53 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py @@ -73,7 +73,7 @@ class MDPState: - ``("active", op)``: the worlds where an op is active, for an op that is active in only some; - ``("on", op)`` and ``("entered", op)``: for an op with ``when``, the worlds where it runs at this step, and those where it turned on at this step; - - ``"interval_worlds"``: the worlds where an interval event that writes scene fields ran in the last + - ``"event_worlds"``: the worlds where an interval or start event that writes scene fields ran in the last ``evaluate``, for an MDP with such events; - ``mdp2.progress_field(task, name)``: the progress of every task, with the internal ``streak`` (steps that a task's ``done`` held), ``entered`` (whether a task of a sequence started at this step), and, for a task that @@ -225,13 +225,17 @@ def startup_writes(self) -> frozenset[FieldSelector]: @property def reset_writes(self) -> frozenset[FieldSelector]: - """Scene fields that the reset events write, which the scene commits after a reset.""" + """Scene fields that the reset and start events write, which the scene commits after a reset.""" return self._scene_writes(Phase.RESET_EVENTS) @property - def interval_writes(self) -> frozenset[FieldSelector]: - """Scene fields that the interval events write, which the scene commits in the worlds where one ran.""" - return self._scene_writes(Phase.INTERVAL_EVENTS) + def step_writes(self) -> frozenset[FieldSelector]: + """Scene fields that events write during a step, the interval events and the start events of tasks that start + during an episode, which the scene commits in the worlds where one ran.""" + starts = [op for op in self.ops[Phase.RESET_EVENTS] if op.entry_key is not None] + return self._scene_writes(Phase.INTERVAL_EVENTS) | frozenset( + selector for op in starts for selector in op.writes if selector.scene + ) def _scene_writes(self, phase: Phase) -> frozenset[FieldSelector]: return frozenset(selector for op in self.ops[phase] for selector in op.writes if selector.scene) @@ -438,8 +442,8 @@ def state(self, scene_data: SceneData, seed: int = 0) -> MDPState: arrays["revision"] = self._zeros(self.num_worlds, dtype=wp.int32) for key in dict.fromkeys(value.key for value in self.tuned): arrays["pending", key] = ProxyArray(wp.clone(arrays[key].warp)) - if self.interval_writes: - arrays["interval_worlds"] = self._zeros(self.num_worlds, dtype=wp.bool) + if self.step_writes: + arrays["event_worlds"] = self._zeros(self.num_worlds, dtype=wp.bool) # Buffers of single ops. events = (Phase.STARTUP_EVENTS, Phase.INTERVAL_EVENTS, Phase.RESET_EVENTS) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py index 44510635de0f..9311f035db65 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py @@ -44,11 +44,14 @@ class Constant(enum.Enum): class EventMode(enum.Enum): - """When an event runs: once at startup, on reset, or at random intervals.""" + """When an event runs: once at startup, on reset, at random intervals, or when its task starts.""" STARTUP = enum.auto() RESET = enum.auto() INTERVAL = enum.auto() + # When its task starts: at the reset for a task that runs from the start of an episode, and at the step it starts + # otherwise, for a task of a sequence or a choice, or one that repeats + START = enum.auto() @dataclass(frozen=True) @@ -269,9 +272,9 @@ class Event(TermCfg): outputs: dict[str, FieldSelector] = field(default_factory=dict) # Passed by argument name; the event writes them mode: EventMode = EventMode.RESET interval_range_s: tuple[float, float] | None = None # Seconds between interval events - # Reset events: whether the scene commits the writes of the earlier reset events before it runs, so that it reads - # what they changed. None infers it: before an event that reads a field derived from written ones, such as the - # body poses after joint writes. True always commits first, and False never does. + # Reset and start events: whether the scene commits the writes of the earlier events of the reset before it runs, + # so that it reads what they changed. None infers it: before an event that reads a field derived from written + # ones, such as the body poses after joint writes. True always commits first, and False never does. commit: bool | None = None @property @@ -280,6 +283,7 @@ def phase(self) -> Phase: EventMode.STARTUP: Phase.STARTUP_EVENTS, EventMode.RESET: Phase.RESET_EVENTS, EventMode.INTERVAL: Phase.INTERVAL_EVENTS, + EventMode.START: Phase.RESET_EVENTS, } return phases[self.mode] diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py index 3b3541eac395..43826dab0643 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py @@ -328,8 +328,9 @@ def build_plan( rewards see this step's progress, and starts the tasks that sequences advanced to after the events, so that the successor observations see them. The terminations, rewards, commands, and events of the step run in the tasks that ran when it started. Ops with ``when`` switch on or off at the same point, and in ``observe`` for new episodes; - ``reset`` prepares them in all the worlds of their task. With tunable values, ``reset`` first applies the values - tuned for it. + ``reset`` prepares them in all the worlds of their task. ``reset`` runs the reset events, which see the progress of + the episode that ended, before the tasks restart, and then the start events of the tasks that run from the start. + With tunable values, it first applies the values tuned for it. """ timed = [op for op in ops[Phase.COMMANDS] + ops[Phase.INTERVAL_EVENTS] if op.timer is not None] observations = tuple(Step(StepKind.COMPUTE, op) for op in ops[Phase.OBSERVATIONS]) @@ -369,24 +370,31 @@ def computed(phase_ops: tuple) -> list[Step]: # A task that starts restarts the timers, commands, and state of its ops, as a new episode does. starts = [Step(StepKind.START_TASKS, trees)] if any(node.staged for tree in trees for node in tree.nodes) else [] starts += [Step(StepKind.SWITCH, switched)] if switched else [] + # Start events write the scene where their task starts; the others set up whole episodes. + start_events = [op for op in ops[Phase.RESET_EVENTS] if op.entry_key is not None] + reset_events = [op for op in ops[Phase.RESET_EVENTS] if op.entry_key is None] if starts: scoped = [op for phase_ops in ops.values() for op in phase_ops if isinstance(op, TermOp) and op.entry_key] starts += [ *(Step(StepKind.RESET_TIMER, op, entry=True) for op in timed if op.entry_key), + *(Step(StepKind.COMPUTE, op, entry=True) for op in start_events), *(Step(StepKind.COMPUTE, op, entry=True) for op in scoped if op.phase is Phase.COMMANDS), *(Step(StepKind.RESET_STATE, op, entry=True) for op in stateful if op.entry_key), ] # A reset prepares the ops with ``when`` in every world of their task. unswitched = {op.name: replace(op, when=None) for op in switched} - reset_events = [] + # The reset events see the progress of the episode that ended; the start events of the tasks that run from the + # start of the new one, after the progress restarts. + events = {"reset": [], "start": []} pending: set[FieldSelector] = set() # Scene fields written since the last commit - for op in ops[Phase.RESET_EVENTS]: - if op.commit or op.commit is None and pending and _reads_stale(op, pending, schema): - reset_events.append(Step(StepKind.COMMIT, op)) - pending.clear() - reset_events.append(Step(StepKind.COMPUTE, op)) - pending.update(selector for selector in op.writes if selector.scene) + for kind, event_ops in (("reset", reset_events), ("start", start_events)): + for op in event_ops: + if op.commit or op.commit is None and pending and _reads_stale(op, pending, schema): + events[kind].append(Step(StepKind.COMMIT, op)) + pending.clear() + events[kind].append(Step(StepKind.COMPUTE, op)) + pending.update(selector for selector in op.writes if selector.scene) return ExecutionPlan( startup=tuple(Step(StepKind.COMPUTE, op) for op in ops[Phase.STARTUP_EVENTS]), @@ -410,9 +418,12 @@ def computed(phase_ops: tuple) -> list[Step]: ), reset=( *([Step(StepKind.APPLY_TUNED, tuned)] if tuned else []), + *(Step(StepKind.RESET_TIMER, unswitched.get(op.name, op)) for op in timed if not op.entry_key), + *events["reset"], + # Then the tasks restart, and with them the timers and start events of those that run. *([Step(StepKind.RESET_PROGRESS, trees)] if trees else []), - *(Step(StepKind.RESET_TIMER, unswitched.get(op.name, op)) for op in timed), - *reset_events, + *(Step(StepKind.RESET_TIMER, unswitched.get(op.name, op)) for op in timed if op.entry_key), + *events["start"], *(Step(StepKind.COMPUTE, unswitched.get(op.name, op)) for op in ops[Phase.COMMANDS]), # State restarts last, from the fields and commands of the new episode. *(Step(StepKind.RESET_STATE, unswitched.get(op.name, op)) for op in stateful), diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py index cecc7fcdaf35..df8767d69485 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py @@ -100,8 +100,8 @@ def _begin_evaluate(mdp: MDP, call: Call) -> None: transition.done.torch.copy_(transition.truncated.torch) state.arrays[terminated].torch.zero_() transition.rewards.torch.zero_() - if "interval_worlds" in state.arrays: - state.arrays["interval_worlds"].torch.zero_() + if "event_worlds" in state.arrays: + state.arrays["event_worlds"].torch.zero_() def _begin_reset(mdp: MDP, call: Call) -> None: @@ -163,13 +163,16 @@ def _run(mdp: MDP, step: Step, call: Call, stepping: bool) -> None: for values, kept in zip(states, before): own = active.torch.view(-1, *[1] * (values.ndim - 1)) values.copy_(torch.where(own, values, kept)) + if step.entry and op.phase is Phase.RESET_EVENTS and any(selector.scene for selector in op.writes): + # The scene commits a start event's writes in the worlds where it ran. + state.arrays["event_worlds"].torch.logical_or_(mask) case StepKind.COMPUTE_IF_DUE: due = _tick(mdp, op, state) due = due if active is None else due & active.torch _compute(mdp, op, call, due, stepping) if any(selector.scene for selector in op.writes): # The scene commits the event's writes in the worlds where it ran. - state.arrays["interval_worlds"].torch.logical_or_(due) + state.arrays["event_worlds"].torch.logical_or_(due) case StepKind.UPDATE_STATE: op.update(**hook_arguments(op.update, {**state.arguments[op.name], "mask": mask})) case StepKind.RESET_TIMER: diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py index a12b9327c919..8dc59978013c 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py @@ -192,9 +192,9 @@ def _evaluate(mdp: MDP) -> tuple[Callable[[Call], None], ...]: if mdp.max_episode_length is not None: time_out = f"{length}[world] >= {code.constant(int, mdp.max_episode_length)}" lines, writes = [], [] - if mdp.interval_writes: - lines.append(f"{_array(code, 'interval_worlds', wp.array(dtype=wp.bool))}[world] = False") - writes.append("interval_worlds") + if mdp.step_writes: + lines.append(f"{_array(code, 'event_worlds', wp.array(dtype=wp.bool))}[world] = False") + writes.append("event_worlds") code.world( f"{code.function(_advance)}(world, {_rng(code)})", f"{length}[world] = {length}[world] + 1", @@ -268,6 +268,10 @@ def _emit(code: Fusion, mdp: MDP, steps: Iterable[Step], stepping: bool = False) code.world(*_under(conditions, restart), writes=[("timer", op.name)]) case StepKind.COMPUTE: _run(code, mdp, op, op.compute, [*op.writes, *state], conditions, mask=started) + if op.phase is Phase.RESET_EVENTS and _writes_scene(op): + # The scene commits a start event's writes in the worlds where it ran. + ran = _array(code, "event_worlds", wp.array(dtype=wp.bool)) + code.world(*_under(conditions, f"{ran}[world] = True"), writes=["event_worlds"]) case StepKind.RESET_STATE if op.reset is not None: _run(code, mdp, op, op.reset, state, conditions, mask=started) case StepKind.RESET_STATE: @@ -281,8 +285,8 @@ def _emit(code: Fusion, mdp: MDP, steps: Iterable[Step], stepping: bool = False) _compute(code, mdp, op, due, stepping) if _writes_scene(op): # The scene commits the event's writes in the worlds where it ran. - ran = _array(code, "interval_worlds", wp.array(dtype=wp.bool)) - code.world(*_under(due, f"{ran}[world] = True"), writes=["interval_worlds"]) + ran = _array(code, "event_worlds", wp.array(dtype=wp.bool)) + code.world(*_under(due, f"{ran}[world] = True"), writes=["event_worlds"]) case StepKind.UPDATE_STATE: # A function hook gets the worlds where the op runs, None for every world. running = None if op.active_key is None else lambda call, op=op: call.state.arrays[op.active_key].warp diff --git a/source/isaaclab_experimental/test/mdp2/test_mdp2.py b/source/isaaclab_experimental/test/mdp2/test_mdp2.py index b9d4146b8d8f..893b92c1dbb9 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2.py @@ -2344,3 +2344,58 @@ def test_parts_renamed_to_other_entities_run_together_in_columns_of_their_own(): mdp2.apply_actions(mdp, state, ProxyArray(wp.from_torch(actions))) assert scene.data("left", "joint_effort_target").torch.tolist() == [[1.0, 2.0]] * 2 assert scene.data("right", "joint_effort_target").torch.tolist() == [[3.0, 4.0]] * 2 + + +@wp.func +def count_successes_warp(world: int, done: wp.array(dtype=wp.bool), total: wp.array(dtype=float)): + if done[world]: + total[world] = total[world] + 1.0 + + +count_successes = mdp2.Term( + torch=lambda mask, done, total: total.add_((mask & done).float()), + warp=count_successes_warp, + state={"total": mdp2.State(persistent=True)}, +) +"""Count the episodes that ended done, such as a curriculum over milestones.""" + + +def test_start_events_write_the_scene_when_their_task_starts(): + """A start event writes the scene when its task starts: at the reset for the first task of a sequence, at the step + the next one starts for the others, whose worlds the scene then commits. Reset events see the progress of the + episode that ended.""" + push = mdp2.Event(push_by_adding_velocity, outputs={"joint_vel": robot.joint_vel}, mode=mdp2.EventMode.START) + velocity = mdp2.Observation(joint_vel, inputs={"joint_vel": robot.joint_vel}) + task = mdp2.compose( + mdp2.TaskCfg( + quantities=above("a", "b"), + observations={"policy": {"velocity": velocity}}, + events={"successes": mdp2.Event(count_successes, inputs={"done": mdp2.progress.done})}, + ), + mdp2.sequence( + first=mdp2.TaskCfg(events={"push": push}, done=mdp2.quantities.a), + second=mdp2.TaskCfg(events={"push": push}, done=mdp2.quantities.b), + ), + ) + history = check_progress(task, [[0.0, 0.0], [1.0, 0.0], [1.0, 0.0], [1.0, 1.0]]) + # Pushed at the reset by the first task, then when the second starts, after step 2. + assert [step["policy"][0].tolist() for step in history] == [[1.0, 1.0], [2.0, 2.0], [2.0, 2.0], [2.0, 2.0]] + + scene = PointMassScene(num_worlds=2, joint_names=("a", "b"), device=DEVICE) + builder = mdp2.MDPBuilder(scene.schema) + builder.add_task(task) + mdp = builder.finalize(device=DEVICE, backend="warp") + assert mdp.step_writes == {robot.joint_vel} and robot.joint_vel in mdp.reset_writes + state, transition = mdp.state(scene), mdp.transition() + everywhere = torch.ones(2, dtype=torch.bool, device=DEVICE) + env_reset(mdp, state, scene, transition.observations, everywhere) + scene.data("robot", "joint_pos").torch.copy_(torch.tensor([[1.0, 1.0], [0.0, 0.0]], device=DEVICE)) + for _ in range(2): # The first world finishes both tasks + mdp2.evaluate(mdp, state, transition) + env_reset(mdp, state, scene, transition.observations, everywhere) + assert state.arrays[mdp2.term_state("events.successes", "total")].torch.tolist() == [1.0, 0.0] + + builder = mdp2.MDPBuilder(scene.schema) + builder.add_task(mdp2.compose(mdp2.TaskCfg(quantities=above("a")), mdp2.TaskCfg(events={"push": push}))) + with pytest.raises(ValueError, match="a start event runs when its task starts"): + builder.validate() From 850e36bef55e3f36bc702d864e32dc085f04a23b Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 19:02:08 -0800 Subject: [PATCH 16/49] Record MDP2 quantities per episode with one flag, and keep done with budgets Quantity(record=True) replaces log=True: a recorded quantity is logged as a metric and recorded in the episode records of an episode budget. With a budget, done stays whether an episode ended, and a separate mask holds the worlds that restart. --- .../changelog.d/mdp2-part2.changed.rst | 3 +++ .../isaaclab_experimental/envs/mdp2_env.py | 18 ++++++++++++------ .../isaaclab_experimental/mdp2/builder.py | 5 ++--- .../isaaclab_experimental/mdp2/config.py | 4 ++-- .../isaaclab_experimental/mdp2/plan.py | 1 - .../test/envs/test_mdp2_env.py | 2 +- .../changelog.d/mdp2-part2.changed.rst | 1 + .../mdp2/lift_kuka_allegro/lift_env_cfg.py | 4 ++-- 8 files changed, 23 insertions(+), 15 deletions(-) diff --git a/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst b/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst index eb17d36226b6..0ea256fd455d 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst @@ -11,3 +11,6 @@ * Changed the order of an MDP2 reset: reset events run before the progress of the tasks restarts, so that they read the progress of the episode that ended, such as a curriculum over milestones. ``MDP.interval_writes`` is now :attr:`~isaaclab_experimental.mdp2.MDP.step_writes`, which also holds the writes of start events. +* **Breaking:** Changed ``Quantity(log=True)`` to ``Quantity(record=True)``: a recorded quantity is reduced per episode, + logged as ``Metrics/`` and recorded in the episode records of an episode budget. With an episode budget, + ``done`` stays whether an episode ended, and the environment resets only the worlds that restart. diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py index 07171238163a..cf560d4c9fd5 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py @@ -55,6 +55,7 @@ class MDP2Env: diagnostics: ClassVar[bool] = False # Whether evaluate writes the reward and termination of every term final_observations: bool = False # Whether evaluate writes the observations of the worlds that ended + _budgeted: bool = False # Whether an episode budget, rather than the ended episodes, decides the worlds to reset def __init__(self, cfg: MDP2EnvCfg) -> None: _check_step(cfg) @@ -139,6 +140,8 @@ def _init_sim(self) -> None: self.scene_data.commit(self._all_envs.warp, self.mdp.startup_writes) self.transition = self.mdp.transition() self._observations = self._views(self.transition.observations) + # The worlds that a step resets: those whose episodes ended, unless an episode budget restarts only some. + self._resets = ProxyArray(wp.zeros_like(self.transition.done.warp)) if self._budgeted else self.transition.done self.actions = ProxyArray(wp.zeros((self.num_envs, self.mdp.action_dim), dtype=wp.float32, device=self.device)) # The worlds whose scene writes a step commits: those reset, and those where an interval event wrote. @@ -260,7 +263,7 @@ def _step_work(self) -> list[tuple[bool, Callable[[], None]]]: ] work.append((True, self._after_evaluate)) elif item is Step.RESET: - work += self._reset_work(transition.done) + work += self._reset_work(self._resets) else: work.append(self._stage_work(item)) return work @@ -441,7 +444,7 @@ class MDP2RLEnv(MDP2Env, gym.Env): :meth:`step` returns copies of the observations after resets, and the rewards and the terminated and truncated flags of the step as Torch views of buffers that the next step overwrites. A world is truncated only if it did not terminate. ``extras["log"]`` holds, per term, the average over worlds of their last finished episode: the reward - sum per second, whether the term ended it, and the value that each logged quantity had at its end. With + sum per second, whether the term ended it, and the value that each recorded quantity had at its end. With :attr:`~MDP2RLEnvCfg.compute_final_obs`, ``extras["final_obs"]`` holds the observations that the worlds that ended had before their reset, also as views; only the rows of the worlds that ended are of this step. """ @@ -454,6 +457,7 @@ class MDP2RLEnv(MDP2Env, gym.Env): def __init__(self, cfg: MDP2RLEnvCfg, render_mode: str | None = None, **kwargs: Any) -> None: self.final_observations = cfg.compute_final_obs + self._budgeted = cfg.episode_budget is not None super().__init__(cfg) if cfg.compute_final_obs: self.extras["final_obs"] = self._views(self.transition.final_observations) @@ -500,7 +504,7 @@ def __init__(self, cfg: MDP2RLEnvCfg, render_mode: str | None = None, **kwargs: slice(None) if op.worlds is None else list(op.worlds), ) for op in self.mdp.ops[mdp2.Phase.QUANTITIES] - if op.log + if op.record } # The time limit is not an op: whether it ended the last episode of each world is kept apart, under its name. time_limits = [name for name, term in _terminations(cfg.task) if isinstance(term, mdp2.TimeLimit)] @@ -638,7 +642,8 @@ def _spend_episode_budget(self) -> None: """Record the episodes of active worlds that ended, and restart only as many as the budget has left. Worlds that do not restart become inactive: they keep stepping, but their episodes no longer end or reset. - Part of the captured step, so it works on device tensors only. + ``done`` stays whether an active world's episode ended; the worlds to reset are those that restart. Part of the + captured step, so it works on device tensors only. """ transition, ended = self.transition, self._ended torch.logical_and(transition.done.torch, self._active, out=ended) @@ -667,10 +672,11 @@ def _spend_episode_budget(self) -> None: reported = ended | self._active transition.terminated.torch.logical_and_(reported) transition.truncated.torch.logical_and_(reported) - transition.done.torch.copy_(restarted) + transition.done.torch.logical_and_(reported) + self._resets.torch.copy_(restarted) def _after_evaluate(self) -> None: - """Keep the logged quantities of the worlds that ended, and whether they timed out, before their reset.""" + """Keep the recorded quantities of the worlds that ended, and whether they timed out, before their reset.""" # With an episode budget, only the episodes of active worlds count, and only some of them restart. if self.cfg.episode_budget is not None: self._spend_episode_budget() diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py index e4eb436c2cc1..b09d3af95b51 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py @@ -758,8 +758,8 @@ def _compile_term(self, entry: ScheduleEntry, context: CompileContext) -> None: state_shapes[name] = dims if name in shared else (self.schema.num_worlds, *dims) if isinstance(cfg, Event): _check_event(entry, errors) - if isinstance(cfg, Quantity) and (cfg.log or cfg.record) and output_shape: - errors.append(f"{entry}: a logged or recorded quantity must have shape ('worlds',), got {output_shape}.") + if isinstance(cfg, Quantity) and cfg.record and output_shape: + errors.append(f"{entry}: a recorded quantity must have shape ('worlds',), got {output_shape}.") if isinstance(cfg, Command) and implementation is not None and implementation.reset is not None: errors.append(f"{entry}: commands write their state when they resample, so they have no reset hook.") if isinstance(cfg, Observation) and cfg.noise is not None and cfg.noise.scale is not None: @@ -859,7 +859,6 @@ def _compile_term(self, entry: ScheduleEntry, context: CompileContext) -> None: torch_hooks=context.backend is Backend.WARP and implementation is term.torch, init=term.init, commit=cfg.commit if isinstance(cfg, Event) else False, - log=isinstance(cfg, Quantity) and cfg.log, record=isinstance(cfg, Quantity) and cfg.record, columns=columns, slot=(entry.name or entry.path[-1]) if isinstance(cfg, Action) else "", diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py index 9311f035db65..475b7055e15e 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py @@ -195,8 +195,8 @@ class Quantity(TermCfg): phase: ClassVar[Phase] = Phase.QUANTITIES - log: bool = False # Log its average over the worlds' last finished episodes, taken at their end, as a metric - # Record its value at the end of every episode, in the episode records of an environment with an episode budget + # Reduce it per episode, taking its value at the end of each: the environment logs its average over the worlds' + # last finished episodes as a metric, and records it in the episode records of an episode budget record: bool = False diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py index 43826dab0643..1976d16d0bbe 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py @@ -108,7 +108,6 @@ class TermOp: init: Callable | None = None # Eager ``fn(ctx, **params)`` that fills the state once, before the startup events # Reset events: whether the scene commits the earlier events' writes before it runs, None to infer it commit: bool | None = False - log: bool = False # Quantities: whether the environment logs it as a metric record: bool = False # Quantities: whether the environment records it at the end of every episode columns: slice | None = None # Actions: the columns of the action that the term takes worlds: tuple[int, ...] | None = None # Worlds where the op is active, None for every world diff --git a/source/isaaclab_experimental/test/envs/test_mdp2_env.py b/source/isaaclab_experimental/test/envs/test_mdp2_env.py index f14b5135a862..d0b4e4b605b5 100644 --- a/source/isaaclab_experimental/test/envs/test_mdp2_env.py +++ b/source/isaaclab_experimental/test/envs/test_mdp2_env.py @@ -370,7 +370,7 @@ def test_captured_steps_match_eager_steps_and_the_torch_backend(): def test_env_splits_the_worlds_between_tasks_and_logs_terms_where_they_run(task_worlds): cfg = cartpole_cfg() # A logged quantity that a reset restarts and the observations of the new episode read again. - cfg.task.quantities = {"steps": mdp2.Quantity(step_count, log=True)} + cfg.task.quantities = {"steps": mdp2.Quantity(step_count, record=True)} observation = mdp2.Observation(mdp.value, inputs={"value": mdp2.quantities.steps}) cfg.task.observations["policy"] = { **cfg.task.observations["policy"], diff --git a/source/isaaclab_tasks/changelog.d/mdp2-part2.changed.rst b/source/isaaclab_tasks/changelog.d/mdp2-part2.changed.rst index 04e8f8b79d6f..5200b61333b5 100644 --- a/source/isaaclab_tasks/changelog.d/mdp2-part2.changed.rst +++ b/source/isaaclab_tasks/changelog.d/mdp2-part2.changed.rst @@ -1,2 +1,3 @@ * Changed ``Isaac-Velocity-Flat-WalkStand-UnitreeGo2-MDP2`` to give its walking and standing tasks their worlds with :func:`~isaaclab_experimental.mdp2.split`. +* Changed ``Isaac-Lift-KukaAllegro-MDP2`` to record its success and curriculum progress with ``Quantity(record=True)``. diff --git a/source/isaaclab_tasks/isaaclab_tasks/mdp2/lift_kuka_allegro/lift_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/mdp2/lift_kuka_allegro/lift_env_cfg.py index f0e7035eeb44..25e5f3cdee24 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/mdp2/lift_kuka_allegro/lift_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/mdp2/lift_kuka_allegro/lift_env_cfg.py @@ -267,7 +267,7 @@ class KukaAllegroLiftPhysicsCfg(PresetCfg): }, ), "success": mdp2.Quantity( - lift.succeeded, inputs=goal, params={"distance": 0.05, "contact_threshold": 0.01}, log=True + lift.succeeded, inputs=goal, params={"distance": 0.05, "contact_threshold": 0.01}, record=True ), "abnormal_robot": mdp2.Quantity( lift.abnormal_robot, @@ -277,7 +277,7 @@ class KukaAllegroLiftPhysicsCfg(PresetCfg): "joint_ids": joints, }, ), - "adr_progress": mdp2.Quantity(mdp.value, inputs={"value": progress}, log=True), + "adr_progress": mdp2.Quantity(mdp.value, inputs={"value": progress}, record=True), }, observations={ "policy": { From 5f4435c5f57d91f9dd5df64f01ea91ab16917bd7 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 19:05:53 -0800 Subject: [PATCH 17/49] Replace the task of a running MDP2 environment with update_task MDP2Env.update_task builds the new task's MDP on the same scene, carries over the arrays that both MDPs key alike with mdp2.migrate (term state, timers, histories, commands, progress, tunables, random streams by use, and reward weights by reward), runs the init hooks of new uses, truncates the episodes, and captures the step again. --- .../changelog.d/mdp2-part2.added.rst | 3 + .../isaaclab_experimental/envs/mdp2_env.py | 60 ++++++++++++++----- .../isaaclab_experimental/mdp2/__init__.pyi | 3 +- .../isaaclab_experimental/mdp2/runtime.py | 39 ++++++++++++ .../test/envs/test_mdp2_env.py | 44 ++++++++++++++ 5 files changed, 132 insertions(+), 17 deletions(-) diff --git a/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst index 32894309d799..ae973fd60fd0 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst @@ -60,3 +60,6 @@ subtask's name, as in ``left.joint_pos``; uses of subtasks that take turns share the columns of their name. * Added start events to MDP2, ``EventMode.START``: an event of a task of a sequence or a choice, or of a task that repeats, writes the scene when its task starts, at the reset or during the episode, where the scene commits it. +* Added :meth:`~isaaclab_experimental.envs.MDP2Env.update_task`, which replaces the task of a running environment on + the same scene, such as with a reward added, and :func:`~isaaclab_experimental.mdp2.migrate`, which carries over the + state, random streams, and reward weights of the uses that both tasks have. diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py index cf560d4c9fd5..b4d38f07d5f7 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py @@ -123,21 +123,32 @@ def _init_sim(self) -> None: self._substeps = cfg.decimation if sim.backend_manager.handles_decimation() else 1 self.scene_data = InteractiveSceneData(self.scene, sim, self.step_dt) - schema = self.scene_data.schema - builder = mdp2.MDPBuilder(schema) - builder.add_task(cfg.task) + self._all_envs = ProxyArray(wp.ones(self.num_envs, dtype=wp.bool, device=self.device)) + self.common_step_counter = 0 + self.extras: dict[str, Any] = {} + self._capturable = cfg.capture and wp.get_device(self.device).is_cuda + self._pool = torch.cuda.MemPool() if self._capturable else None # Torch memory that the graphs use + self._build(cfg.task) + + def _build(self, task: mdp2.TaskCfg, previous: tuple[mdp2.MDP, mdp2.MDPState] | None = None) -> None: + """Build the MDP of a task on the scene, and the step that runs it. Without a ``previous`` MDP, run its startup; + with one, carry its state over, see :func:`~isaaclab_experimental.mdp2.migrate`.""" + builder = mdp2.MDPBuilder(self.scene_data.schema) + builder.add_task(task) self.mdp = builder.finalize( device=self.device, - backend=cfg.backend, + backend=self.cfg.backend, diagnostics=self.diagnostics, final_observations=self.final_observations, ) self.state = self.mdp.state(self.scene_data, seed=self._seed) - self._all_envs = ProxyArray(wp.ones(self.num_envs, dtype=wp.bool, device=self.device)) - mdp2.startup(self.mdp, self.state) - if self.mdp.startup_writes: - # Startup events write scene fields in place, which the scene commits to the solver. - self.scene_data.commit(self._all_envs.warp, self.mdp.startup_writes) + if previous is not None: + mdp2.migrate(*previous, self.mdp, self.state) + else: + mdp2.startup(self.mdp, self.state) + if self.mdp.startup_writes: + # Startup events write scene fields in place, which the scene commits to the solver. + self.scene_data.commit(self._all_envs.warp, self.mdp.startup_writes) self.transition = self.mdp.transition() self._observations = self._views(self.transition.observations) # The worlds that a step resets: those whose episodes ended, unless an episode budget restarts only some. @@ -148,14 +159,10 @@ def _init_sim(self) -> None: self._event_worlds = self.state.arrays.get("event_worlds") if self._event_worlds is not None: self._commit_mask = ProxyArray(wp.zeros(self.num_envs, dtype=wp.bool, device=self.device)) - self.common_step_counter = 0 - self.extras: dict[str, Any] = {} self._work = self._step_work() # The work of a step, in order, each with whether a graph can capture it - self._capturable = cfg.capture and wp.get_device(self.device).is_cuda self._runs: list[Callable[[], None]] | None = None # The captured step: graph replays and the work between them self.num_graphs = 0 # CUDA graphs that one captured step replays - self._pool = torch.cuda.MemPool() if self._capturable else None # Torch memory that the graphs use self._stepped = False @property @@ -199,6 +206,23 @@ def step(self, action: torch.Tensor) -> tuple[VecEnvObs, dict]: self._step_or_replay(action) return self.observations, self.extras + def update_task(self, task: mdp2.TaskCfg, truncate: bool = True) -> None: + """Replace the task by another on the same scene, such as with a reward added or removed, and keep running. + + The state of the uses that both tasks have carries over, see :func:`~isaaclab_experimental.mdp2.migrate`: term + state, timers, histories, commands, progress, tunable values, random streams, and reward weights. With + ``truncate``, every world starts a new episode, so that no episode mixes two tasks; otherwise episodes go on. + The next step captures its graphs again, which compiles the kernels of a new task once, in about a second. + """ + self._build(task, previous=(self.mdp, self.state)) + self.cfg.task = task + self._bind() + if truncate: + self.reset() + + def _bind(self) -> None: + """Bind what an environment derives from the MDP, after it was built.""" + def tune( self, path: str, @@ -459,11 +483,16 @@ def __init__(self, cfg: MDP2RLEnvCfg, render_mode: str | None = None, **kwargs: self.final_observations = cfg.compute_final_obs self._budgeted = cfg.episode_budget is not None super().__init__(cfg) - if cfg.compute_final_obs: - self.extras["final_obs"] = self._views(self.transition.final_observations) self.render_mode = render_mode self.metadata = {**self.metadata, "render_fps": 1 / self.step_dt} + self.obs_buf: VecEnvObs = {} + self._bind() + def _bind(self) -> None: + """Bind the spaces, the final observations, and the episode statistics to the MDP.""" + cfg = self.cfg + if cfg.compute_final_obs: + self.extras["final_obs"] = self._views(self.transition.final_observations) spaces: dict[str, Any] = {} for buffer, (shape, dtype) in self.mdp.observation_layouts.items(): if dtype is wp.float32: @@ -528,7 +557,6 @@ def __init__(self, cfg: MDP2RLEnvCfg, render_mode: str | None = None, **kwargs: self._task_worlds.append(slice(None) if len(worlds) == self.num_envs else worlds) self._last_done = torch.zeros(self.num_envs, len(self._tasks), device=self.device) self._last_time_outs = torch.zeros(self.num_envs, dtype=torch.bool, device=self.device) - self.obs_buf: VecEnvObs = {} if cfg.episode_budget is not None: self._init_episode_budget(cfg.episode_budget) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/__init__.pyi b/source/isaaclab_experimental/isaaclab_experimental/mdp2/__init__.pyi index baf0c79f74b1..62729859715a 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/__init__.pyi +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/__init__.pyi @@ -61,6 +61,7 @@ __all__ = [ "episode_length", "evaluate", "last_action", + "migrate", "observe", "process_actions", "progress", @@ -128,6 +129,6 @@ from .config import ( from .eager import TermContext from .plan import ExecutionPlan, ObservationSlot, Segment, Step, StepKind, TaskNode, TaskTree, TunedValue from .rng import uniform -from .runtime import apply_actions, evaluate, observe, process_actions, reset, startup, tune +from .runtime import apply_actions, evaluate, migrate, observe, process_actions, reset, startup, tune from .scene import EntitySchema, FieldSchema, SceneData, SceneSchema from .terms import Implementation, State, Term diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/runtime.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/runtime.py index 0094a3e136fc..205ad80c32be 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/runtime.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/runtime.py @@ -20,6 +20,7 @@ from isaaclab.utils.warp import ProxyArray from .compiled import MDP, MDPState, Transition +from .config import FieldSelector, Phase from .eager import call_init from .plan import Call @@ -117,3 +118,41 @@ def tune( state.arrays["revision"].torch.add_(selected.int()) else: state.arrays["pending"].torch.logical_or_(selected) + + +_CARRIED = ("timer", "history", "on", "entered", "pending") +"""Kinds of the arrays of single ops that :func:`migrate` carries over, by the first part of their keys.""" + + +def migrate(previous: MDP, previous_state: MDPState, mdp: MDP, state: MDPState) -> None: + """Carry the state of an MDP over to another built on the same scene, such as for an edited task. + + Every array of the MDP that both key alike and shape alike carries over: the state, timers, histories, and + tunable values of the uses that both have, the commands, quantities, and progress, the episode lengths, and the + last actions. So do the random streams of the uses that both have, and the reward weights of the rewards. The init + hooks of the uses that the previous MDP did not have run, as at startup. + """ + for key, array in state.arrays.items(): + carried = isinstance(key, FieldSelector) and not key.scene + carried |= key in ("revision", "pending") or isinstance(key, tuple) and key[0] in _CARRIED + old = previous_state.arrays.get(key) + if ( + carried + and old is not None + and old.torch.shape == array.torch.shape + and old.torch.dtype == array.torch.dtype + ): + array.torch.copy_(old.torch) + + for row, name in enumerate(mdp.streams): + if name in previous.streams: + state.rng.torch[row] = previous_state.rng.torch[previous.streams.index(name)] + rewards = [op.name for op in previous.ops[Phase.REWARDS]] + for column, op in enumerate(mdp.ops[Phase.REWARDS]): + if op.name in rewards: + state.reward_weights.torch[:, column] = previous_state.reward_weights.torch[:, rewards.index(op.name)] + + uses = {op.use for op in previous.term_ops} + for op in mdp.term_ops: + if op.init is not None and op.use not in uses: + call_init(mdp, op, state, op.init) diff --git a/source/isaaclab_experimental/test/envs/test_mdp2_env.py b/source/isaaclab_experimental/test/envs/test_mdp2_env.py index d0b4e4b605b5..7a0db71ef254 100644 --- a/source/isaaclab_experimental/test/envs/test_mdp2_env.py +++ b/source/isaaclab_experimental/test/envs/test_mdp2_env.py @@ -803,3 +803,47 @@ def test_optix_cameras_render_between_the_graphs_of_a_step(): assert all(not torch.equal(before, after) for before, after in zip(images, images[1:])) finally: env.close() + + +lifetime_steps = mdp2.Term( + torch=mdp2.Implementation(compute=lambda steps: steps.clone(), update=lambda steps: steps.add_(1.0)), + state={"steps": mdp2.State(persistent=True)}, +) +"""Steps since the start, across episodes.""" + + +def test_update_task_keeps_the_state_of_the_uses_both_tasks_have(): + """Replacing the task on a running environment keeps the state, random streams, and reward weights of the uses + that both tasks have, truncates the episodes, and replays the new task's step as a graph.""" + cfg = cartpole_cfg() + cfg.task.quantities = {"lifetime": mdp2.Quantity(lifetime_steps)} + env = MDP2RLEnv(cfg) + try: + env.reset() + actions = torch.zeros(NUM_ENVS, 1, device=env.device) + for _ in range(3): + env.step(actions) + assert env.is_captured and env.num_graphs == 1 + env.state.reward_weights.torch[:, 0] = 7.0 # Changed at runtime: kept + streams = {name: env.state.rng.torch[row].clone() for row, name in enumerate(env.mdp.streams)} + + task = replace( + cfg.task, + rewards={**cfg.task.rewards, "upright": mdp2.Reward(mdp.is_alive, inputs={"terminated": mdp2.terminated})}, + ) + env.update_task(task) + lifetime = env.state.arrays[mdp2.term_state("quantities.lifetime", "steps")].torch + assert (lifetime == 3.0).all() and (env.episode_length_buf == 0).all() + assert (env.state.reward_weights.torch[:, 0] == 7.0).all() + assert env.state.reward_weights.torch[:, -1].tolist() == [1.0] * NUM_ENVS + for name, values in streams.items(): + # The reset that truncated the episodes advanced every stream once. + rng.advance(values[None]) + assert torch.equal(env.state.rng.torch[env.mdp.streams.index(name)], values), name + + _, _, _, _, extras = env.step(actions) + env.step(actions) + assert env.is_captured and env.num_graphs == 1 and "Episode_Reward/upright" in extras["log"] + assert (lifetime == 5.0).all() + finally: + env.close() From f1bcf02b0ce0c98a9d96b19493cee4ab115f162f Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 19:10:17 -0800 Subject: [PATCH 18/49] Add MDP2 variations that draw, record, and replay scene values mdp.variation returns a part of a task: a reset event that draws a value per world, uniformly in a tunable range, from a weighted choice, or replayed in the order of the resets, writes it to a scene field, and a quantity that records it per episode. --- .../isaaclab_experimental.mdp2.mdp.rst | 6 + .../changelog.d/mdp2-part2.added.rst | 5 + .../mdp2/mdp/__init__.pyi | 8 + .../mdp2/mdp/variations.py | 190 ++++++++++++++++++ .../test/mdp2/test_mdp2.py | 58 ++++++ 5 files changed, 267 insertions(+) create mode 100644 source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/variations.py diff --git a/docs/source/api/lab_experimental/isaaclab_experimental.mdp2.mdp.rst b/docs/source/api/lab_experimental/isaaclab_experimental.mdp2.mdp.rst index b735735e3b21..cb0475c33d90 100644 --- a/docs/source/api/lab_experimental/isaaclab_experimental.mdp2.mdp.rst +++ b/docs/source/api/lab_experimental/isaaclab_experimental.mdp2.mdp.rst @@ -44,3 +44,9 @@ Curriculums .. automodule:: isaaclab_experimental.mdp2.mdp.curriculums :members: + +Variations +---------- + +.. automodule:: isaaclab_experimental.mdp2.mdp.variations + :members: diff --git a/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst index ae973fd60fd0..d3782ed0b188 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst @@ -63,3 +63,8 @@ * Added :meth:`~isaaclab_experimental.envs.MDP2Env.update_task`, which replaces the task of a running environment on the same scene, such as with a reward added, and :func:`~isaaclab_experimental.mdp2.migrate`, which carries over the state, random streams, and reward weights of the uses that both tasks have. +* Added variations to the MDP2 library, :func:`~isaaclab_experimental.mdp2.mdp.variation`: a reset event that draws a + value per world, such as how far a drawer is open, writes it to a scene field, and records it per episode, drawn + :class:`~isaaclab_experimental.mdp2.mdp.Uniform` (in a tunable range), from a + :class:`~isaaclab_experimental.mdp2.mdp.Choice`, or replayed in the order of the resets with + :class:`~isaaclab_experimental.mdp2.mdp.Replay`, independent of the number of worlds. diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi index 5b34140f863a..da2bc8dbe079 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi @@ -4,6 +4,13 @@ # SPDX-License-Identifier: BSD-3-Clause __all__ = [ + "Choice", + "Replay", + "Uniform", + "choice_variation", + "replay_variation", + "uniform_variation", + "variation", "binary_joint_position", "heading_velocity_command", "uniform_pose_command", @@ -126,3 +133,4 @@ from .terminations import ( joint_vel_out_of_limit, root_height_below_minimum, ) +from .variations import Choice, Replay, Uniform, choice_variation, replay_variation, uniform_variation, variation diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/variations.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/variations.py new file mode 100644 index 000000000000..96338fc39085 --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/variations.py @@ -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 + +"""Variations: values of the scene that each episode draws, records, and can replay, such as how far a drawer is open. + +A variation is a reset event that draws one value per world and writes it to elements of a scene field, and a quantity +that holds the value, recorded at the end of every episode. :func:`variation` returns both as a part of a task, to +compose with the others:: + + task = mdp2.compose( + SCENE, + EMBODIMENT, + TASK, + mdp.variation("drawer", cabinet.joint_pos, cabinet.joints("drawer"), mdp.Uniform(0.0, 0.35)), + ) +""" + +from __future__ import annotations + +import itertools +from dataclasses import dataclass + +import torch +import warp as wp + +from ..config import Event, FieldSelector, Quantity, SubsetSelector, TaskCfg, Tunable, term_state +from ..eager import TermContext +from ..rng import uniform +from ..terms import State, Term +from .rewards import value + + +@dataclass(frozen=True) +class Uniform: + """Values drawn uniformly from ``[low, high)``. Both are tunable, as ``events..low`` and ``high``.""" + + low: float + high: float + + +@dataclass(frozen=True) +class Choice: + """One of ``values``, drawn with the relative chances ``weights``, even ones if None.""" + + values: tuple[float, ...] + weights: tuple[float, ...] | None = None + + +@dataclass(frozen=True) +class Replay: + """``values`` in the order the resets take them, such as those that an earlier run recorded, from the first again + once all were taken. Worlds that reset at the same step take them in world order, so the order of the values does + not depend on the number of worlds. The row each episode took is recorded as ``_row``.""" + + values: tuple[float, ...] + + +def variation(name: str, target: FieldSelector, subset: SubsetSelector, values: Uniform | Choice | Replay) -> TaskCfg: + """Return a part of a task that draws a value at every reset, writes it to the ``subset`` elements of the + ``target`` field, such as a drawer's joint position, and records it per episode as the quantity ``name``.""" + inputs = {"ids": subset} + if isinstance(values, Uniform): + term, params = uniform_variation, {"low": Tunable(float(values.low)), "high": Tunable(float(values.high))} + elif isinstance(values, Choice): + weights = values.weights or (1.0,) * len(values.values) + bounds = tuple(itertools.accumulate(weight / sum(weights) for weight in weights[:-1])) + params = {"values": tuple(map(float, values.values)), "chances": bounds} + params |= {"num_values": len(values.values), "num_bounds": max(len(bounds), 1)} + term = choice_variation + else: + term, params = replay_variation, {"values": tuple(map(float, values.values)), "num_values": len(values.values)} + event = Event(term, inputs=inputs, outputs={"target": target}, params=params) + + quantities = {name: Quantity(value, inputs={"value": term_state(f"events.{name}", "value")}, record=True)} + if isinstance(values, Replay): + row = Quantity(value, inputs={"value": term_state(f"events.{name}", "row")}, record=True) + quantities[f"{name}_row"] = row + return TaskCfg(events={name: event}, quantities=quantities) + + +def _write(target: torch.Tensor, ids: torch.Tensor, mask: torch.Tensor, drawn: torch.Tensor, kept: torch.Tensor): + """Keep the drawn values of the masked worlds, and write them to the elements ``ids`` of the target.""" + kept.copy_(torch.where(mask, drawn, kept)) + elements = target[:, ids.long()] + target[:, ids.long()] = torch.where(mask[:, None], kept[:, None].expand_as(elements), elements) + + +@wp.func +def _uniform( + world: int, + target: wp.array2d(dtype=float), + ids: wp.array(dtype=wp.int32), + value: wp.array(dtype=float), + rng: wp.int32, + low: float, + high: float, +): + value[world] = wp.randf(wp.rand_init(rng, 0), low, high) + for i in range(ids.shape[0]): + target[world, ids[i]] = value[world] + + +def _uniform_torch(mask, target, ids, value, rng, low, high): + # As Warp's randf: the span times a unit draw plus the low bound, fused on CUDA. + unit = uniform(rng, 0.0, 1.0) + drawn = torch.addcmul(low, high - low, unit) if unit.is_cuda else low + (high - low) * unit + _write(target, ids, mask, drawn, value) + + +uniform_variation = Term( + torch=_uniform_torch, + warp=_uniform, + state={"value": State(persistent=True)}, + random=True, +) +"""Draw a value per world uniformly from ``[low, high)``, write it to the ``ids`` elements of ``target``, and keep it +as the state ``value``.""" + + +@wp.func +def _choice( + world: int, + target: wp.array2d(dtype=float), + ids: wp.array(dtype=wp.int32), + value: wp.array(dtype=float), + rng: wp.int32, + table: wp.array(dtype=float), + bounds: wp.array(dtype=float), +): + draw = wp.randf(wp.rand_init(rng, 0)) + index = int(0) + for k in range(table.shape[0] - 1): + if draw >= bounds[k]: + index = k + 1 + value[world] = table[index] + for i in range(ids.shape[0]): + target[world, ids[i]] = value[world] + + +def _choice_torch(mask, target, ids, value, rng, table, bounds): + draw = uniform(rng, 0.0, 1.0) + index = (draw[:, None] >= bounds[None, : table.shape[0] - 1]).sum(dim=1) + _write(target, ids, mask, table[index], value) + + +def _fill_tables(ctx: TermContext, values: tuple[float, ...] = (), chances: tuple[float, ...] = (), **params) -> None: + """Fill the tables of the values to draw from, and of the cumulative chances that bound them, once.""" + ctx.state["table"].copy_(torch.tensor(values, dtype=torch.float32)) + if "bounds" in ctx.state and chances: + ctx.state["bounds"].copy_(torch.tensor(chances, dtype=torch.float32)) + + +choice_variation = Term( + torch=_choice_torch, + warp=_choice, + init=_fill_tables, + state={ + "value": State(persistent=True), + "table": State(("num_values",), persistent=True), + "bounds": State(("num_bounds",), persistent=True), + }, + random=True, +) +"""Draw one of ``values`` per world with the cumulative ``chances`` between them, write it to the ``ids`` +elements of ``target``, and keep it as the state ``value``.""" + + +def _replay_torch(mask, target, ids, value, row, table, taken): + # The rows of the worlds that reset, in world order, after those that earlier resets took. + rank = torch.cumsum(mask.long(), dim=0) - 1 + rows = (taken.long() + rank) % table.shape[0] + row.copy_(torch.where(mask, rows.float(), row)) + _write(target, ids, mask, table[rows], value) + taken.add_(mask.sum()) + + +replay_variation = Term( + torch=_replay_torch, + init=_fill_tables, + state={ + "value": State(persistent=True), + "row": State(persistent=True), + "table": State(("num_values",), persistent=True), + "taken": State((1,), persistent=True), + }, +) +"""Take the next of ``values`` in the order of the resets, write it to the ``ids`` elements of ``target``, and keep it +and its row as the states ``value`` and ``row``.""" diff --git a/source/isaaclab_experimental/test/mdp2/test_mdp2.py b/source/isaaclab_experimental/test/mdp2/test_mdp2.py index 893b92c1dbb9..1dd40a2362b3 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2.py @@ -2399,3 +2399,61 @@ def test_start_events_write_the_scene_when_their_task_starts(): builder.add_task(mdp2.compose(mdp2.TaskCfg(quantities=above("a")), mdp2.TaskCfg(events={"push": push}))) with pytest.raises(ValueError, match="a start event runs when its task starts"): builder.validate() + + +def test_variations_draw_record_and_replay_values(): + """Variations draw a value per world at every reset, write it to the scene, and hold it in a recorded quantity: + uniformly within a tunable range, from a weighted choice, or replayed in the order of the resets.""" + joints = robot.joints + task = mdp2.compose( + mdp2.mdp.variation("open", robot.joint_pos, joints("a"), mdp2.mdp.Uniform(0.25, 0.75)), + mdp2.mdp.variation( + "pick", robot.joint_pos, joints("b"), mdp2.mdp.Choice((0.1, 0.2, 0.3), weights=(1.0, 0.0, 1.0)) + ), + mdp2.mdp.variation("replay", robot.joint_pos, joints("c"), mdp2.mdp.Replay((1.0, 2.0, 3.0))), + ) + + def run(backend: str, capture: bool) -> list[torch.Tensor]: + scene = PointMassScene(num_worlds=4, joint_names=("a", "b", "c"), device=DEVICE) + builder = mdp2.MDPBuilder(scene.schema) + builder.add_task(task) + mdp_ = builder.finalize(device=DEVICE, backend=backend) + state, transition = mdp_.state(scene), mdp_.transition() + mask = ProxyArray(wp.ones(4, dtype=wp.bool, device=DEVICE)) + actions = ProxyArray(wp.zeros((4, 1), dtype=wp.float32, device=DEVICE)) + captured = mdp2.CapturedMDP(mdp_, state, transition, actions, mask) if capture else None + mdp2.startup(mdp_, state) + history = [] + for resets in ([0, 1, 2, 3], [1, 3], [0, 1, 2, 3]): + mask.torch.zero_() + mask.torch[resets] = True + mdp2.reset(mdp_, state, mask) if captured is None else captured.reset() + mdp2.evaluate(mdp_, state, transition) if captured is None else captured.evaluate() + values = [state.arrays[getattr(mdp2.quantities, name)].torch for name in ("open", "pick", "replay")] + history.append(torch.stack([scene.data("robot", "joint_pos").torch, torch.stack(values, 1)]).clone()) + mdp2.tune(mdp_, state, "events.open.low", 1.0) + mdp2.tune(mdp_, state, "events.open.high", 1.0) + assert [op.name for op in mdp_.ops[mdp2.Phase.QUANTITIES] if op.record] == [ + "quantities.open", + "quantities.pick", + "quantities.replay", + "quantities.replay_row", + ] + return history + + runs = [run(backend, capture) for backend in ("torch", "warp") for capture in (False, True)] + for other in runs[1:]: + for expected, actual in zip(runs[0], other): + assert torch.equal(expected, actual) + first, second, third = runs[0] + joint_pos, recorded = first + assert torch.equal(joint_pos, recorded) # The quantities hold the drawn values + assert ((joint_pos[:, 0] >= 0.25) & (joint_pos[:, 0] < 0.75)).all() + assert ((joint_pos[:, 1] - 0.1).abs() < 1e-6).logical_or((joint_pos[:, 1] - 0.3).abs() < 1e-6).all() + assert joint_pos[:, 2].tolist() == [1.0, 2.0, 3.0, 1.0] + # Worlds 1 and 3 reset again: they replay the next rows, and take the tuned range of the next reset. + assert second[0][:, 2].tolist() == [1.0, 2.0, 3.0, 3.0] + assert ( + second[0][[1, 3], 0].tolist() == [1.0, 1.0] and second[0][[0, 2], 0].tolist() == joint_pos[[0, 2], 0].tolist() + ) + assert third[0][:, 2].tolist() == [1.0, 2.0, 3.0, 1.0] From edea9e5d8e8fe37a27c0f5807c2ff205eae5abe2 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 19:27:12 -0800 Subject: [PATCH 19/49] Flag actuators that CUDA graphs can replay ActuatorBase.capturable says whether an actuator's compute and masked reset can be recorded into a graph with Torch work inside it. Delayed PD actuators now draw their delays on masked resets from a device stream, which a replayed graph advances, and qualify. MDP2 accepts capturable Isaac Lab actuators and graphable backend-native ones instead of a fixed list of types. --- .../isaaclab/changelog.d/mdp2-part2.added.rst | 3 ++ source/isaaclab/changelog.d/mdp2-part2.minor | 0 .../isaaclab/actuators/actuator_base.py | 9 +++++ .../isaaclab/actuators/actuator_pd.py | 33 +++++++++++++++++-- .../actuators/test_actuator_collection.py | 24 ++++++++++++++ .../changelog.d/mdp2-part2.changed.rst | 3 ++ .../envs/mdp2_scene_data.py | 23 +++++++------ 7 files changed, 83 insertions(+), 12 deletions(-) create mode 100644 source/isaaclab/changelog.d/mdp2-part2.added.rst create mode 100644 source/isaaclab/changelog.d/mdp2-part2.minor diff --git a/source/isaaclab/changelog.d/mdp2-part2.added.rst b/source/isaaclab/changelog.d/mdp2-part2.added.rst new file mode 100644 index 000000000000..29e0c6ce54ef --- /dev/null +++ b/source/isaaclab/changelog.d/mdp2-part2.added.rst @@ -0,0 +1,3 @@ +* Added :attr:`~isaaclab.actuators.ActuatorBase.capturable`, which says whether a CUDA graph can replay an actuator's + compute and masked reset with Torch work inside it. Delayed PD actuators qualify: their masked resets draw delays + from a device stream, which a replayed graph advances. diff --git a/source/isaaclab/changelog.d/mdp2-part2.minor b/source/isaaclab/changelog.d/mdp2-part2.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab/isaaclab/actuators/actuator_base.py b/source/isaaclab/isaaclab/actuators/actuator_base.py index f28db71cc976..c54ff2ed4bad 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_base.py +++ b/source/isaaclab/isaaclab/actuators/actuator_base.py @@ -109,6 +109,15 @@ class ActuatorBase(ABC): If a class inherits from :class:`ImplicitActuator`, then this flag should be set to :obj:`True`. """ + capturable: ClassVar[bool] = False + """Whether :meth:`compute` and :meth:`reset` with an ``env_mask`` can be recorded into a CUDA graph and replayed. + + They must then not synchronize with the host, nor draw from Torch's random generators, whose draws a replayed + graph repeats, when Torch joins the capture on the capturing stream. Environments that replay their steps as + graphs with Torch work inside them, such as MDP2's, accept only such actuators. Unlike + :attr:`ActuatorCollection.is_graphable`, Torch models qualify. + """ + computed_effort: torch.Tensor """The computed effort [N or N·m, depending on joint type] for the actuator group. diff --git a/source/isaaclab/isaaclab/actuators/actuator_pd.py b/source/isaaclab/isaaclab/actuators/actuator_pd.py index d7019a5e8bc2..f8fac3c6ca5c 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_pd.py +++ b/source/isaaclab/isaaclab/actuators/actuator_pd.py @@ -34,6 +34,18 @@ """ +@wp.kernel +def _draw_time_lags(seed: wp.array(dtype=wp.int32), low: int, high: int, time_lags: wp.array(dtype=wp.int32)): + """Draw a time lag in ``[low, high]`` for every environment from the stream ``seed``.""" + env = wp.tid() + time_lags[env] = wp.randi(wp.rand_init(seed[0], env), low, high + 1) + + +@wp.kernel +def _advance_seed(seed: wp.array(dtype=wp.int32)): + seed[0] = seed[0] + 1 + + class ImplicitActuator(ActuatorBase): """Implicit actuator model that is handled by the simulation. @@ -47,6 +59,7 @@ class ImplicitActuator(ActuatorBase): """The configuration for the actuator model.""" is_implicit_model: ClassVar[bool] = True + capturable: ClassVar[bool] = True def __init__( self, @@ -253,6 +266,8 @@ class IdealPDActuator(ActuatorBase): """ cfg: IdealPDActuatorCfg + + capturable: ClassVar[bool] = True """The configuration for the actuator model.""" actuator_effort_limit: torch.Tensor @@ -425,6 +440,8 @@ class DelayedPDActuator(IdealPDActuator): cfg: DelayedPDActuatorCfg """The configuration for the actuator model.""" + capturable: ClassVar[bool] = True # Masked resets draw delays from a device stream + def __init__(self, cfg: DelayedPDActuatorCfg, *args, **kwargs): super().__init__(cfg, *args, **kwargs) # masked resets write sampled delays without the host-side range check of set_time_lag @@ -435,14 +452,24 @@ def __init__(self, cfg: DelayedPDActuatorCfg, *args, **kwargs): self.velocities_delay_buffer = DelayBuffer(cfg.max_delay, self._num_envs, device=self._device) self.efforts_delay_buffer = DelayBuffer(cfg.max_delay, self._num_envs, device=self._device) self._delay_buffers = (self.positions_delay_buffer, self.velocities_delay_buffer, self.efforts_delay_buffer) + # Masked resets draw delays from a device stream, which a replayed CUDA graph advances, seeded from Torch. + seed = int(torch.randint(0, 2**31 - 1, (1,)).item()) + self._delay_seed = wp.array([seed], dtype=wp.int32, device=self._device) + self._drawn_time_lags = wp.zeros(self._num_envs, dtype=wp.int32, device=self._device) def reset(self, env_ids: Sequence[int] | slice | None = None, env_mask: wp.array | None = None) -> None: super().reset(env_ids, env_mask) if env_mask is not None: # draw a delay for every environment and keep the selected ones, so the mask stays on the device - time_lags = torch.randint( - self.cfg.min_delay, self.cfg.max_delay + 1, (self._num_envs,), dtype=torch.int, device=self._device + wp.launch( + _draw_time_lags, + dim=self._num_envs, + inputs=[self._delay_seed, self.cfg.min_delay, self.cfg.max_delay], + outputs=[self._drawn_time_lags], + device=self._device, ) + wp.launch(_advance_seed, dim=1, inputs=[self._delay_seed], device=self._device) + time_lags = wp.to_torch(self._drawn_time_lags) selected = wp.to_torch(env_mask) for delay_buffer in self._delay_buffers: torch.where(selected, time_lags, delay_buffer.time_lags, out=delay_buffer.time_lags) @@ -488,6 +515,8 @@ class RemotizedPDActuator(DelayedPDActuator): The torque limits are interpolated based on the current joint positions and applied to the actuator commands. """ + capturable: ClassVar[bool] = False # The lookup of the torque limits assigns through a boolean mask + def __init__( self, cfg: RemotizedPDActuatorCfg, diff --git a/source/isaaclab/test/actuators/test_actuator_collection.py b/source/isaaclab/test/actuators/test_actuator_collection.py index 062514cb45f0..95b89dd49e49 100644 --- a/source/isaaclab/test/actuators/test_actuator_collection.py +++ b/source/isaaclab/test/actuators/test_actuator_collection.py @@ -910,6 +910,30 @@ def test_write_command_mask_uses_full_sized_value(command_name): setter(value=value, env_mask=wp.array([1, 0], dtype=wp.int32, device="cpu"), joint_mask=joint_mask) +@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA graphs need a GPU") +def test_masked_resets_of_delayed_actuators_draw_new_delays_when_a_graph_replays_them(): + """Delayed actuators are capturable: a mask reset draws its delays on the device, so each replay draws anew.""" + device = "cuda:0" + control = FakeActuatorControl(num_envs=64, device=device) + cfg = DelayedPDActuatorCfg(joint_names_expr=[".*"], stiffness=1.0, damping=0.0, min_delay=0, max_delay=3) + collection = ActuatorCollection({"delayed": cfg}, control) + actuator = collection["delayed"] + assert type(actuator).capturable + env_mask = wp.ones(64, dtype=wp.bool, device=device) + collection.reset(env_mask=env_mask) # Loads the kernels + # Torch joins the capture on Warp's stream, with memory of its own, as environments that replay steps do. + pool = torch.cuda.MemPool() + with wp.ScopedCapture(device=device) as capture: + with torch.cuda.stream(wp.stream_to_torch(wp.get_stream(device))), torch.cuda.use_mem_pool(pool): + collection.reset(env_mask=env_mask) + draws = [] + for _ in range(2): + wp.capture_launch(capture.graph) + draws.append(actuator.positions_delay_buffer.time_lags.clone()) + assert not torch.equal(draws[0], draws[1]) + assert all(((draw >= 0) & (draw <= 3)).all() for draw in draws) + + @pytest.mark.parametrize("device", test_devices()) def test_masked_reset_leaves_unselected_envs_untouched(device): """A mask reset redraws the masked environments' delays without a device sync and keeps the others.""" diff --git a/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst b/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst index 0ea256fd455d..b43040c43158 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst @@ -14,3 +14,6 @@ * **Breaking:** Changed ``Quantity(log=True)`` to ``Quantity(record=True)``: a recorded quantity is reduced per episode, logged as ``Metrics/`` and recorded in the episode records of an episode budget. With an episode budget, ``done`` stays whether an episode ended, and the environment resets only the worlds that restart. +* Changed the actuators that MDP2 environments accept: any capturable Isaac Lab actuator + (:attr:`~isaaclab.actuators.ActuatorBase.capturable`) or graphable backend-native actuator, such as the delayed + actuators that Newton runs, instead of a fixed list of actuator types. diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_scene_data.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_scene_data.py index 126ee32f0434..dbefd9717b99 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_scene_data.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_scene_data.py @@ -13,7 +13,7 @@ import warp as wp -from isaaclab.actuators import DCMotorCfg, IdealPDActuatorCfg, ImplicitActuatorCfg +from isaaclab.actuators import ActuatorBase from isaaclab.scene import InteractiveScene from isaaclab.sensors import BaseContactSensor, Camera from isaaclab.sim import SimulationContext @@ -21,7 +21,6 @@ from isaaclab_experimental.mdp2 import EntitySchema, FieldSchema, FieldSelector, SceneSchema -CAPTURED_ACTUATORS = (ImplicitActuatorCfg, IdealPDActuatorCfg, DCMotorCfg) """Actuator configs whose actuators MDP2 can step and reset inside CUDA graphs. Matched exactly: subclasses, such as delayed actuators, may draw from Torch's random generators on reset, which a replayed graph repeats.""" @@ -117,16 +116,12 @@ def __init__(self, scene: InteractiveScene, sim: SimulationContext, step_dt: flo raise ValueError( f"MDP2 needs the solver's joint and body order, but '{name}' sets a joint or body ordering." ) - # Captured steps replay the actuators' masked resets, so they must not draw from Torch's random - # generators, as delayed actuators do for their delays: a graph would repeat the same draws. - unsupported = sorted( - group for group, cfg in asset.cfg.actuators.items() if type(cfg) not in CAPTURED_ACTUATORS - ) + # Captured steps replay the actuators' computes and masked resets. + unsupported = sorted(group for group, actuator in asset.actuators.items() if not _capturable(actuator)) if unsupported: raise ValueError( - f"MDP2 replays actuator resets inside CUDA graphs, so it supports" - f" {', '.join(cfg.__name__ for cfg in CAPTURED_ACTUATORS)} only, but '{name}' has the" - f" actuator groups {unsupported}." + f"MDP2 replays actuators inside CUDA graphs, so it supports capturable actuators only" + f" (ActuatorBase.capturable), but '{name}' has the actuator groups {unsupported}." ) views |= { "joint_pos": data.joint_pos, @@ -321,3 +316,11 @@ def _newton_backend(sim: SimulationContext) -> _NewtonBackend | None: if type(sim.backend_manager).__module__.split(".")[0] != "isaaclab_newton": return None return _NewtonBackend() + + +def _capturable(actuator: Any) -> bool: + """Return whether a CUDA graph can replay an actuator: an Isaac Lab model that is capturable, or a backend-native + actuator that is graphable, such as a delayed one that Newton runs.""" + if isinstance(actuator, ActuatorBase): + return type(actuator).capturable + return actuator.is_graphable() From 5b21b22ae9136f8f5576df5db4e8545e67ff5cbe Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 19:27:21 -0800 Subject: [PATCH 20/49] Capture MDP2 steps through the physics backend, and account for replays PhysicsManager gains supports_step_capture and capture, so an environment records its step as the physics backend records its own (Newton: relaxed on a stream of its own while Kit renders), and steps the physics between its graphs on a backend that cannot capture it. SimulationContext.after_replay does the host work of replayed physics steps. MDP2Env no longer imports Newton's capture function. --- .../isaaclab/changelog.d/mdp2-part2.added.rst | 4 + .../isaaclab/physics/physics_manager.py | 32 ++++++++ .../isaaclab/sim/simulation_context.py | 23 ++++++ .../changelog.d/mdp2-part2.changed.rst | 3 + .../isaaclab_experimental/envs/mdp2_env.py | 24 ++++-- .../test/envs/test_mdp2_env.py | 82 +++++++++++++++++-- .../changelog.d/mdp2-part2.added.rst | 3 + .../changelog.d/mdp2-part2.minor | 0 .../isaaclab_newton/physics/newton_manager.py | 19 ++++- 9 files changed, 170 insertions(+), 20 deletions(-) create mode 100644 source/isaaclab_newton/changelog.d/mdp2-part2.added.rst create mode 100644 source/isaaclab_newton/changelog.d/mdp2-part2.minor diff --git a/source/isaaclab/changelog.d/mdp2-part2.added.rst b/source/isaaclab/changelog.d/mdp2-part2.added.rst index 29e0c6ce54ef..30f229fa2228 100644 --- a/source/isaaclab/changelog.d/mdp2-part2.added.rst +++ b/source/isaaclab/changelog.d/mdp2-part2.added.rst @@ -1,3 +1,7 @@ * Added :attr:`~isaaclab.actuators.ActuatorBase.capturable`, which says whether a CUDA graph can replay an actuator's compute and masked reset with Torch work inside it. Delayed PD actuators qualify: their masked resets draw delays from a device stream, which a replayed graph advances. +* Added :meth:`~isaaclab.physics.PhysicsManager.supports_step_capture` and + :meth:`~isaaclab.physics.PhysicsManager.capture`, with which environments that replay their steps as CUDA graphs + record them as the physics backend records its own step, and :meth:`~isaaclab.sim.SimulationContext.after_replay`, + which does the host work of the physics steps that a replayed graph ran, such as counting them. diff --git a/source/isaaclab/isaaclab/physics/physics_manager.py b/source/isaaclab/isaaclab/physics/physics_manager.py index 6ccddf0f8361..9e6515fb3e67 100644 --- a/source/isaaclab/isaaclab/physics/physics_manager.py +++ b/source/isaaclab/isaaclab/physics/physics_manager.py @@ -693,6 +693,38 @@ def handles_decimation(self) -> bool: """ return False + def after_replay(self, num_steps: int) -> None: + """Do the host work of :meth:`step` for steps whose device work a CUDA graph replayed, such as advancing the + simulation time. The default does nothing. + + Args: + num_steps: Calls of :meth:`step` that the graph recorded. + """ + + def supports_step_capture(self) -> bool: + """Whether :meth:`step` can be recorded into a CUDA graph by :meth:`capture`, as part of a step of an + environment that replays the graph. The default is ``False``: such environments step the physics eagerly.""" + return False + + def capture(self, fn: Callable[[], None]) -> Any: + """Record ``fn`` into a Warp graph, without running it, for :func:`warp.capture_launch` to replay. + + ``fn`` may call :meth:`step` if :meth:`supports_step_capture` is ``True``. The backend chooses how to capture, + such as on a stream of its own while a renderer shares the device; the default records on Warp's current + stream of the device. + + Args: + fn: Work to record. Perform lazy initialization before capture. + + Returns: + The captured graph. + """ + import warp as wp + + with wp.ScopedCapture(device=self._device) as capture: + fn() + return capture.graph + def handle_actions(self, actions: ActionManager, scene: InteractiveScene) -> bool: """Run the environment's actions and asset writes inside :meth:`step`, before every physics step. diff --git a/source/isaaclab/isaaclab/sim/simulation_context.py b/source/isaaclab/isaaclab/sim/simulation_context.py index dcb84eaac411..9623c07fa633 100644 --- a/source/isaaclab/isaaclab/sim/simulation_context.py +++ b/source/isaaclab/isaaclab/sim/simulation_context.py @@ -605,6 +605,29 @@ def step(self, render: bool = True) -> None: if render and self.is_rendering: self.render() + def after_replay(self, num_steps: int) -> None: + """Do the host work of :meth:`step` for steps whose device work a CUDA graph replayed. + + A replayed graph runs the physics steps it recorded, but not their host work: this blocks while the timeline + or a visualizer is paused, counts the steps, and lets the physics backend account for them, such as its + simulation time. + + Args: + num_steps: Calls of :meth:`step` that the graph recorded. + """ + self.backend_manager.wait_for_playing() + visualizers_to_remove = [] + for viz in self._visualizers: + try: + while viz.is_training_paused() and viz.is_running(): + viz.step(0.0) + except Exception as exc: + logger.error("Error stepping visualizer '%s': %s", type(viz).__name__, exc) + visualizers_to_remove.append(viz) + self._remove_visualizers(visualizers_to_remove) + self._physics_step_count += num_steps + self.backend_manager.after_replay(num_steps) + def render(self, mode: int | None = None, skip_app_pumping: bool = False) -> None: """Update visualizers and render the scene. diff --git a/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst b/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst index b43040c43158..9c033e483d03 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst @@ -17,3 +17,6 @@ * Changed the actuators that MDP2 environments accept: any capturable Isaac Lab actuator (:attr:`~isaaclab.actuators.ActuatorBase.capturable`) or graphable backend-native actuator, such as the delayed actuators that Newton runs, instead of a fixed list of actuator types. +* Changed :class:`~isaaclab_experimental.envs.MDP2Env` to capture its steps through the physics backend + (:meth:`~isaaclab.physics.PhysicsManager.capture`) instead of a Newton function: a backend that cannot capture its + step steps between the MDP's graphs. Replayed steps now count their physics steps and advance the simulation time. diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py index b4d38f07d5f7..f5c2a139e7df 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py @@ -19,7 +19,6 @@ import numpy as np import torch import warp as wp -from isaaclab_newton.physics.newton_backend import capture_graph from isaaclab_newton.renderers import NewtonOptixRendererCfg, NewtonWarpRendererCfg from isaaclab.envs.common import VecEnvObs, VecEnvStepReturn @@ -250,12 +249,17 @@ def _step_or_replay(self, action: torch.Tensor) -> None: raise ValueError(f"Expected actions of shape {tuple(self.actions.torch.shape)}, got {tuple(action.shape)}.") self.actions.torch.copy_(action) + captured = False if self._runs is None and self._capturable and self._stepped: - # The first step loaded every kernel module, so the capture records launches only. - self._runs = self._capture_step() + # The first step loaded every kernel module, so the capture records launches only. Capturing did the host + # work of the physics steps of this step. + self._runs, captured = self._capture_step(), True if self._runs is not None: for run in self._runs: run() + # The graphs replayed the physics steps, but not their host work, such as counting them. + if not captured and self.sim.backend_manager.supports_step_capture(): + self.sim.after_replay(self.cfg.decimation // self._substeps) else: for _, work in self._work: work() @@ -278,7 +282,8 @@ def _step_work(self) -> list[tuple[bool, Callable[[], None]]]: work = [] for item in self.cfg.step: if item is Step.PHYSICS: - work.append((True, self._simulate)) + # A physics backend that cannot capture its step steps between the graphs of the MDP. + work.append((self.sim.backend_manager.supports_step_capture(), self._simulate)) elif item is Step.RENDER: work += [(self._render_capturable, self._render)] if self._cameras else [] elif item is Step.EVALUATE: @@ -340,12 +345,13 @@ def _capture_step(self) -> list[Callable[[], None]]: continue def run_all(steps: list[Callable[[], None]] = steps) -> None: - for step in steps: - step() + # Torch launches, of either backend, join the Warp capture, on the stream the physics captures on. + with torch_in_warp_capture(self.device, self._pool): + for step in steps: + step() - # Torch launches, of either backend, join the Warp capture. - with torch_in_warp_capture(self.device, self._pool): - graph = capture_graph(self.device, run_all) + # The physics backend records the graph as it records its own step, such as on a stream of its own. + graph = self.sim.backend_manager.capture(run_all) runs.append(functools.partial(wp.capture_launch, graph)) self.num_graphs += 1 diff --git a/source/isaaclab_experimental/test/envs/test_mdp2_env.py b/source/isaaclab_experimental/test/envs/test_mdp2_env.py index 7a0db71ef254..7b0f8f169380 100644 --- a/source/isaaclab_experimental/test/envs/test_mdp2_env.py +++ b/source/isaaclab_experimental/test/envs/test_mdp2_env.py @@ -23,7 +23,7 @@ from isaaclab_newton.renderers import NewtonOptixRendererCfg, NewtonWarpRendererCfg import isaaclab.sim as sim_utils -from isaaclab.actuators import DelayedPDActuatorCfg, ImplicitActuatorCfg +from isaaclab.actuators import DelayedPDActuatorCfg, ImplicitActuatorCfg, RemotizedPDActuatorCfg from isaaclab.assets import ArticulationCfg, RigidObjectCfg from isaaclab.scene import InteractiveSceneCfg from isaaclab.sensors import CameraCfg @@ -261,12 +261,24 @@ def test_env_follows_the_gym_interface_and_commits_resets(monkeypatch): env.close() -def delayed_cart(cfg: MDP2RLEnvCfg, tmp_path: Path) -> None: +def delayed_cart(cfg: MDP2RLEnvCfg, tmp_path: Path | None = None) -> None: cfg.scene.robot.actuators["cart"] = DelayedPDActuatorCfg( joint_names_expr=["slider_to_cart"], joint_effort_limit=400.0, stiffness=0.0, damping=10.0, max_delay=2 ) +def remotized_cart(cfg: MDP2RLEnvCfg, tmp_path: Path) -> None: + """A remotized actuator, which runs as an Isaac Lab model without Newton's own actuators.""" + cfg.sim.use_newton_actuators = False + cfg.scene.robot.actuators["cart"] = RemotizedPDActuatorCfg( + joint_names_expr=["slider_to_cart"], + joint_parameter_lookup=[[-2.0, 1.0, 400.0], [2.0, 1.0, 400.0]], + joint_effort_limit=400.0, + stiffness=0.0, + damping=10.0, + ) + + def reordered_bodies(cfg: MDP2RLEnvCfg, tmp_path: Path) -> None: cfg.scene.robot.body_ordering = ["rail", "pole", "cart"] @@ -298,14 +310,14 @@ def PhysicsSphericalJoint "pole_to_tip" @pytest.mark.parametrize( ("change", "message"), [ - (delayed_cart, r"'robot' has the actuator groups \['cart'\]"), + (remotized_cart, r"'robot' has the actuator groups \['cart'\]"), (reordered_bodies, r"'robot' sets a joint or body ordering"), ], ids=("actuator-with-state", "body-ordering"), ) def test_env_rejects_assets_it_cannot_reset_or_write_in_place(change, message, tmp_path): - """Captured steps replay the actuators' resets, so delayed actuators, which draw their delays from Torch on reset, - are refused; and so are body orderings, whose poses are copies that the asset refreshes outside the graphs.""" + """Captured steps replay the actuators, so actuators that are not capturable are refused; and so are body + orderings, whose poses are copies that the asset refreshes outside the graphs.""" cfg = cartpole_cfg() change(cfg, tmp_path) with pytest.raises(ValueError, match=message): @@ -551,14 +563,15 @@ def test_env_runs_the_tasks_of_a_sequence_in_turn_and_logs_their_progress(): """A sequence of two tasks, each with its own quantity and reward, steps the same captured and uncaptured, and the environment logs how often each task was done in the last episodes.""" - def stage(steps: int) -> mdp2.TaskCfg: + def stage(steps: int, weight: float) -> mdp2.TaskCfg: ready = mdp2.Quantity(after_steps, inputs={"episode_length": mdp2.episode_length}, params={"steps": steps}) - bonus = mdp2.Reward(mdp.is_alive, inputs={"terminated": mdp2.terminated}) + # The weights differ, so that the bonus is a use of each task rather than one of both. + bonus = mdp2.Reward(mdp.is_alive, inputs={"terminated": mdp2.terminated}, weight=weight) return mdp2.TaskCfg(quantities={"ready": ready}, rewards={"bonus": bonus}, done=mdp2.quantities.ready) cfg = cartpole_cfg() cfg.task.terminations["cart_out_of_bounds"] = None - cfg.task = mdp2.compose(cfg.task, mdp2.sequence(warm=stage(3), hold=stage(6))) + cfg.task = mdp2.compose(cfg.task, mdp2.sequence(warm=stage(3, 1.0), hold=stage(6, 2.0))) cfg.verify_capture = 10 env = MDP2RLEnv(cfg) try: @@ -570,7 +583,7 @@ def stage(steps: int) -> mdp2.TaskCfg: # The bonus of each task, per second of the episode: warm ran 3 steps, hold the others. steps = env.max_episode_length assert log["Episode_Reward/warm.bonus"].item() == pytest.approx(3 / steps) - assert log["Episode_Reward/hold.bonus"].item() == pytest.approx((steps - 3) / steps) + assert log["Episode_Reward/hold.bonus"].item() == pytest.approx(2 * (steps - 3) / steps) finally: env.close() @@ -847,3 +860,54 @@ def test_update_task_keeps_the_state_of_the_uses_both_tasks_have(): assert (lifetime == 5.0).all() finally: env.close() + + +def test_delayed_actuators_run_in_captured_steps(): + """Delayed actuators, which Newton runs natively, replay in the step's graph.""" + cfg = cartpole_cfg() + delayed_cart(cfg) + env = MDP2RLEnv(cfg) + try: + env.reset() + for _ in range(3): + env.step(torch.zeros(NUM_ENVS, 1, device=env.device)) + assert env.is_captured and env.num_graphs == 1 + finally: + env.close() + + +def test_physics_that_cannot_capture_its_step_steps_between_the_graphs(monkeypatch): + """A physics backend that cannot capture its step steps eagerly, between the graphs of the MDP, which the backend + still records with its own capture.""" + cfg = cartpole_cfg() + env = MDP2RLEnv(cfg) + try: + manager = env.sim.backend_manager + captures = [] + capture = manager.capture + monkeypatch.setattr(manager, "supports_step_capture", lambda: False) + monkeypatch.setattr(manager, "capture", lambda fn: captures.append(fn) or capture(fn)) + env._work = env._step_work() + env.reset() + actions = torch.zeros(NUM_ENVS, 1, device=env.device) + for _ in range(3): + env.step(actions) + # The physics steps eagerly, and the rest of the step replays as one graph after it. + assert env.is_captured and env.num_graphs == 1 and len(captures) == 1 + finally: + env.close() + + +def test_replayed_steps_do_the_host_work_of_their_physics_steps(): + """Replayed steps count their physics steps and advance the simulation time, as stepping eagerly does.""" + env = MDP2RLEnv(cartpole_cfg()) + try: + env.reset() + steps, time = env.sim.get_physics_step_count(), env.sim.backend_manager.get_simulation_time() + for _ in range(5): + env.step(torch.zeros(NUM_ENVS, 1, device=env.device)) + assert env.is_captured + assert env.sim.get_physics_step_count() - steps == 5 * env.cfg.decimation + assert env.sim.backend_manager.get_simulation_time() - time == pytest.approx(5 * env.step_dt) + finally: + env.close() diff --git a/source/isaaclab_newton/changelog.d/mdp2-part2.added.rst b/source/isaaclab_newton/changelog.d/mdp2-part2.added.rst new file mode 100644 index 000000000000..8a3fb1f420cb --- /dev/null +++ b/source/isaaclab_newton/changelog.d/mdp2-part2.added.rst @@ -0,0 +1,3 @@ +* Added the step capture hooks of :class:`~isaaclab_newton.physics.NewtonManager`: it captures environment steps as + it captures its own, relaxed on a stream of its own while Kit renders, and accounts for replayed steps in its + simulation time. diff --git a/source/isaaclab_newton/changelog.d/mdp2-part2.minor b/source/isaaclab_newton/changelog.d/mdp2-part2.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py b/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py index f668d84fdc2e..232e8d8749bd 100644 --- a/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py +++ b/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py @@ -189,15 +189,30 @@ def _flag_outer_capture(self) -> None: if self.backend.device.is_capturing: self.backend.transforms_may_change_on_graph_replay = True + def supports_step_capture(self) -> bool: + """Whether the step can be captured: :attr:`~isaaclab_newton.physics.NewtonCfg.use_cuda_graph` is on and + the solver supports capture.""" + return self.backend is not None and self.backend.capture is not None + + def capture(self, fn: Callable[[], None]) -> Any: + """Record ``fn`` as the physics step is captured: relaxed, on a stream of its own, while Kit renders.""" + if not self.supports_step_capture(): + return super().capture(fn) + return self.backend.capture(fn) + def step(self) -> None: """Advance physics by one environment step, or one physics step when the environment runs decimation.""" sim = self._sim if sim is None or not sim.is_playing(): return + self.backend.step() + self.after_replay(1) + + def after_replay(self, num_steps: int) -> None: + """Advance the simulation time by the steps, and publish that the bodies moved.""" backend = self.backend physics_steps = backend.decimation if backend.handles_decimation() else 1 - backend.step() - self._sim_time += backend.dt * physics_steps + self._sim_time += backend.dt * physics_steps * num_steps self._mark_transforms_changed() def close(self) -> None: From 6e2a3cd2ab36892253d69198e9a059a9f2b75fd8 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 19:27:29 -0800 Subject: [PATCH 21/49] Verify MDP2 captures bitwise without reproducible physics Where the physics backend has no reproducible mode, verify_capture replaces the physics step by nothing in both runs and compares the MDP alone, bitwise, instead of to a relative tolerance that contact drift could exceed. --- .../changelog.d/mdp2-part2.changed.rst | 2 ++ .../isaaclab_experimental/envs/mdp2_verify.py | 23 +++++++++++-------- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst b/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst index 9c033e483d03..b81b4ec09396 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst @@ -20,3 +20,5 @@ * Changed :class:`~isaaclab_experimental.envs.MDP2Env` to capture its steps through the physics backend (:meth:`~isaaclab.physics.PhysicsManager.capture`) instead of a Newton function: a backend that cannot capture its step steps between the MDP's graphs. Replayed steps now count their physics steps and advance the simulation time. +* Changed ``MDP2EnvCfg.verify_capture`` on physics without a reproducible mode to check the MDP alone, with the physics + step replaced by nothing, bitwise, instead of comparing to a relative tolerance. diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_verify.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_verify.py index 20f59aee077c..1419013c2d2f 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_verify.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_verify.py @@ -36,9 +36,9 @@ def verify_capture(env_type: type[MDP2Env], cfg: MDP2EnvCfg, num_steps: int) -> observations, and every quantity and term state, which are named in the error in schedule order, with the Python hooks and stages that run inside the graphs, where the cause usually is. The worlds start at staggered episode lengths, so that, with a time limit, every world times out and resets during the checked steps, also in the - captured ones. Contact-rich physics is not reproducible - run to run on GPUs, so the runs use the backend's reproducible mode where it has one (Newton's - ``deterministic_mode``) and compare bitwise; otherwise they compare to a relative 1e-3 and should be short. + captured ones. Contact-rich physics is not reproducible run to run on GPUs, so the runs use the backend's + reproducible mode where it has one (Newton's ``deterministic_mode``); otherwise they replace the physics step by + nothing and check the MDP alone. Either way they compare bitwise. """ # One seed for both runs, also when the config asks for a random one. seed = 0 if cfg.seed in (None, -1) else cfg.seed @@ -47,14 +47,13 @@ def verify_capture(env_type: type[MDP2Env], cfg: MDP2EnvCfg, num_steps: int) -> # A shallow copy keeps the entities that were added to the scene config as attributes. cfg.scene = copy.copy(cfg.scene) cfg.scene.num_envs = min(cfg.scene.num_envs, 8) - reproducible = _with_reproducible_physics(cfg) - runs = [_rollout(env_type, cfg, num_steps), _rollout(env_type, dataclasses.replace(cfg, capture=True), num_steps)] - (eager, _), (captured, suspects) = runs + physics = _with_reproducible_physics(cfg) + captured_cfg = dataclasses.replace(cfg, capture=True) + (eager, _), (captured, suspects) = (_rollout(env_type, run, num_steps, physics) for run in (cfg, captured_cfg)) for step, (expected, actual) in enumerate(zip(eager, captured)): for name, value in expected.items(): # NaN marks values such as an absent heading target, so it matches NaN. - tolerance = {"rtol": 0.0, "atol": 0.0} if reproducible else {"rtol": 1e-3, "atol": 1e-5} - if not torch.allclose(value.double(), actual[name].double(), equal_nan=True, **tolerance): + if not torch.allclose(value.double(), actual[name].double(), rtol=0.0, atol=0.0, equal_nan=True): raise RuntimeError( f"Captured step {step} differs from the uncaptured step at '{name}'. A capturable Python hook or" " stage may read a value on the host or keep Python-side state, which a CUDA graph freezes at" @@ -73,12 +72,16 @@ def _with_reproducible_physics(cfg: MDP2EnvCfg) -> bool: return True -def _rollout(env_type: type[MDP2Env], cfg: MDP2EnvCfg, num_steps: int) -> tuple[list[dict], list[str]]: - """Reset and step a copy of the task, and return each step's results by name, and its capturable Python code.""" +def _rollout(env_type: type[MDP2Env], cfg: MDP2EnvCfg, num_steps: int, physics: bool) -> tuple[list[dict], list[str]]: + """Reset and step a copy of the task, with or without the physics, and return each step's results by name, and + its capturable Python code.""" env = env_type(cfg) try: generator = torch.Generator(device=env.device).manual_seed(0) env.reset() + if not physics: + # Before the first step, so that the capture records no physics either. + env.sim.step = lambda render=False: None if env.mdp.max_episode_length is not None: # World k times out at step k + 1, cycling over the checked steps after the first, uncaptured, one. worlds = torch.arange(env.num_envs, device=env.device) From c71c30767edff6d74fd3dd1497a2ee7fe3a3fc35 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 19:27:29 -0800 Subject: [PATCH 22/49] Add the resting_on term for contact-based success in MDP2 One where a destination's contact force on an object is strong enough, within a cone around up, and the object is still, like Arena's object_on_destination. --- .../changelog.d/mdp2-part2.added.rst | 2 + .../mdp2/mdp/__init__.pyi | 2 + .../isaaclab_experimental/mdp2/mdp/rewards.py | 38 +++++++++++++++++++ 3 files changed, 42 insertions(+) diff --git a/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst index d3782ed0b188..6b8b09a28cd0 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst @@ -68,3 +68,5 @@ :class:`~isaaclab_experimental.mdp2.mdp.Uniform` (in a tunable range), from a :class:`~isaaclab_experimental.mdp2.mdp.Choice`, or replayed in the order of the resets with :class:`~isaaclab_experimental.mdp2.mdp.Replay`, independent of the number of worlds. +* Added :data:`~isaaclab_experimental.mdp2.mdp.resting_on`, one where an object rests on another by its contact force + in a cone and its speed, like Arena's ``object_on_destination``, for a milestone with ``hold``. diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi index da2bc8dbe079..629b8fc6a873 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi @@ -60,6 +60,7 @@ __all__ = [ "track_ang_vel_z_exp", "track_lin_vel_xy_exp", "undesired_contacts", + "resting_on", "value", "bad_orientation", "illegal_contact", @@ -121,6 +122,7 @@ from .rewards import ( lin_vel_z_l2, track_ang_vel_z_exp, track_lin_vel_xy_exp, + resting_on, undesired_contacts, value, ) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/rewards.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/rewards.py index f59960ae4ec2..4b14b77cc5de 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/rewards.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/rewards.py @@ -57,6 +57,44 @@ def _value_torch(value: torch.Tensor) -> torch.Tensor: """The ``value`` input itself, one float per world, such as a quantity or the state of another term.""" +@wp.func +def _resting_on( + world: int, + normal_force_matrix_w: wp.array3d(dtype=wp.vec3f), + body_ids: wp.array(dtype=wp.int32), + root_com_vel_w: wp.array(dtype=wp.spatial_vectorf), + filter_index: int, + min_force: float, + min_cos: float, + max_speed: float, +) -> float: + force = wp.vec3f(0.0) + for i in range(body_ids.shape[0]): + force += normal_force_matrix_w[world, body_ids[i], filter_index] + magnitude = wp.length(force) + supported = magnitude >= min_force and force[2] >= min_cos * magnitude + still = wp.length(wp.spatial_top(root_com_vel_w[world])) < max_speed + return wp.where(supported and still, 1.0, 0.0) + + +def _resting_on_torch( + normal_force_matrix_w, body_ids, root_com_vel_w, *, filter_index, min_force, min_cos, max_speed +) -> torch.Tensor: + force = normal_force_matrix_w[:, body_ids.long(), filter_index].sum(dim=1) + magnitude = force.norm(dim=-1) + supported = (magnitude >= min_force) & (force[:, 2] >= min_cos * magnitude) + still = root_com_vel_w[:, :3].norm(dim=-1) < max_speed + return (supported & still).float() + + +resting_on = Term(torch=_resting_on_torch, warp=_resting_on) +"""One where an object rests on another: the contact force that a filter object exerts on its ``body_ids`` bodies is +at least ``min_force`` [N], within the cone of cosine ``min_cos`` around up, and the object's speed is below +``max_speed`` [m/s], like Arena's ``object_on_destination``. ``normal_force_matrix_w`` is a contact sensor's on the +object filtered by the destination, the filter at ``filter_index``. Hold it with a milestone's ``hold``. +""" + + # Joint state. From 7be76ddf8e142096a2c158fbf18fce8eeb2d2ca3 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 19:27:29 -0800 Subject: [PATCH 23/49] Run uses that the tasks of an MDP2 sequence define alike as one Ops that tasks of a sequence or a choice define alike, but for their names, merge into one op that runs while any of these tasks runs, switched like ops with when: their state, timers, and observation histories carry on from one task to the next rather than restart. Uses that differ, such as in a reward's weight, stay apart. --- .../changelog.d/mdp2-part2.added.rst | 2 + .../isaaclab_experimental/mdp2/builder.py | 67 ++++++++++++- .../isaaclab_experimental/mdp2/compiled.py | 7 +- .../isaaclab_experimental/mdp2/plan.py | 15 ++- .../mdp2/torch_backend.py | 15 ++- .../mdp2/warp_backend.py | 18 ++-- .../test/mdp2/test_mdp2.py | 96 ++++++++++++++++++- 7 files changed, 191 insertions(+), 29 deletions(-) diff --git a/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst index 6b8b09a28cd0..dbd2464c5bf1 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst @@ -70,3 +70,5 @@ :class:`~isaaclab_experimental.mdp2.mdp.Replay`, independent of the number of worlds. * Added :data:`~isaaclab_experimental.mdp2.mdp.resting_on`, one where an object rests on another by its contact force in a cone and its speed, like Arena's ``object_on_destination``, for a milestone with ``hold``. +* Added sharing of uses across the tasks of an MDP2 sequence or choice: uses that the tasks define alike run as one, + while any of these tasks runs, so that their state and observation histories carry on from one task to the next. diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py index b09d3af95b51..48c20c0a602d 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py @@ -621,6 +621,7 @@ def _compile_schedule( for k, op in enumerate(ops): ops[k] = replace(op, index=k) + _share_across_stages(context) context.tasks = tuple(self._compile_task(path, tasks, context) for path in tasks) def _compile_task(self, path: str, tasks: dict[str, tuple[TaskCfg, bool]], context: CompileContext) -> TaskNode: @@ -1438,20 +1439,76 @@ def _allocate_slots( return tuple(placed[op.name] for op in ops), tuple(slots), dims, layouts -def _exclusive(first: TermOp, second: TermOp, modes: Mapping[str, TaskMode]) -> bool: +def _exclusive(first: TermOp | ActionOp, second: TermOp | ActionOp, modes: Mapping[str, TaskMode]) -> bool: """Return whether two ops never run in the same world at the same step.""" if first.worlds is not None and second.worlds is not None and not set(first.worlds) & set(second.worlds): return True - if first.stage is None or second.stage is None: - return False - # Tasks of a sequence run one after another: the ops are exclusive below different subtasks of a sequence. - a, b = first.stage.split("."), second.stage.split(".") + firsts, seconds = _stages(first), _stages(second) + return bool(firsts and seconds) and all(_apart(a, b, modes) for a in firsts for b in seconds) + + +def _stages(op: TermOp | ActionOp) -> tuple[str, ...]: + """Return the tasks of sequences or choices in which an op runs, none if it runs whenever its world config does.""" + if isinstance(op, TermOp) and op.stages: + return op.stages + return () if op.stage is None else (op.stage,) + + +def _apart(first: str, second: str, modes: Mapping[str, TaskMode]) -> bool: + """Return whether two tasks never run at the same step: they are below different subtasks of a sequence or a + choice, which run one at a time.""" + a, b = first.split("."), second.split(".") common = list(itertools.takewhile(lambda pair: pair[0] == pair[1], zip(a, b))) if len(common) in (len(a), len(b)): return False return modes.get(".".join(part for part, _ in common)) in (TaskMode.SEQUENCE, TaskMode.CHOICE) +def _share_across_stages(context: CompileContext) -> None: + """Merge the ops that tasks of a sequence or a choice define alike, but for their names, into one op that runs + while any of these tasks runs: its state, timer, and history carry on from one task to the next rather than + restart. Uses that differ, such as in a reward's weight, stay apart; so do quantities and commands, which write + fields of their own, actions, and start events, which run as each task starts.""" + renamed: dict[str, str] = {} # The uses of the merged ops, by those of the ops merged into them + for phase, ops in context.ops.items(): + if phase in (Phase.ACTIONS, Phase.QUANTITIES, Phase.COMMANDS, Phase.RESET_EVENTS): + continue + kept: list[TermOp] = [] + for op in ops: + key = replace(op, name="", use="", index=0, stage=None) + match = next( + ( + k + for k, other in enumerate(kept) + if op.stage is not None + and _stages(other) + and replace(other, name="", use="", index=0, stage=None, stages=()) == key + and _exclusive(other, op, context.modes) + ), + None, + ) + if match is None: + kept.append(op) + continue + other = kept[match] + kept[match] = replace(other, stage=None, stages=(*_stages(other), op.stage)) + renamed[op.use] = other.use + ops[:] = kept + if not renamed: + return + # Uses that read the state of a merged op read that of the op it merged into. + for ops in context.ops.values(): + for k, op in enumerate(ops): + if isinstance(op, TermOp): + inputs = { + arg: replace(selector, entity=renamed.get(selector.entity, selector.entity)) + if isinstance(selector, FieldSelector) and not selector.scene + else selector + for arg, selector in op.inputs.items() + } + ops[k] = replace(op, inputs=MappingProxyType(inputs)) + + def _used_columns(ops: tuple[TermOp, ...], worlds: range) -> dict[str, int]: """Return, per observation buffer, the columns up to the last that the ops active in some of ``worlds`` use.""" used: dict[str, int] = {} diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py index 14db74a8cb53..aa9e31f5fb80 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py @@ -71,8 +71,8 @@ class MDPState: - ``("scratch", op)``: the output of a Python hook in a Warp MDP; - ``("selected", op)``: the worlds that the hook of a timed op, or of an op active in some worlds, acts on; - ``("active", op)``: the worlds where an op is active, for an op that is active in only some; - - ``("on", op)`` and ``("entered", op)``: for an op with ``when``, the worlds where it runs at this step, and - those where it turned on at this step; + - ``("on", op)`` and ``("entered", op)``: for an op with ``when``, or of several tasks of a sequence or a choice, + the worlds where it runs at this step, and those where it turned on at this step; - ``"event_worlds"``: the worlds where an interval or start event that writes scene fields ran in the last ``evaluate``, for an MDP with such events; - ``mdp2.progress_field(task, name)``: the progress of every task, with the internal ``streak`` (steps that a @@ -360,6 +360,7 @@ def describe(self) -> str: details += [f"stream {op.stream}"] if op.stream is not None else [] details += ["torch hooks"] if op.torch_hooks else [] details += [f"during {op.stage}"] if op.stage else [] + details += [f"during {' or '.join(op.stages)}"] if op.stages else [] details += [f"when {op.when}"] if op.when is not None else [] if op.worlds is not None: first, last = op.worlds[0], op.worlds[-1] @@ -401,7 +402,7 @@ def state(self, scene_data: SceneData, seed: int = 0) -> MDPState: arrays[key] = self._zeros(self.num_worlds, dtype=dtypes[key]) worlds = slice(None) if op.worlds is None else list(op.worlds) arrays[key].torch[worlds] = torch.tensor(default, dtype=arrays[key].torch.dtype, device=self.device) - if op.when is not None: + if op.when is not None or op.stages: arrays["on", op.name] = self._zeros(self.num_worlds, dtype=wp.bool) arrays["entered", op.name] = self._zeros(self.num_worlds, dtype=wp.bool) for subset, indices in self.subsets.items(): diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py index 1976d16d0bbe..8cffe1bd6446 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py @@ -124,6 +124,9 @@ class TermOp: when: FieldSelector | None = None when_dtype: Any = None # Element type of ``when`` when_default: bool | None = None # Default of a tunable ``when``, which the MDP owns; None for another field + # The tasks of a sequence or a choice that define the op alike: it runs while any of them runs, and restarts only + # when none ran + stages: tuple[str, ...] = () @property def scope_key(self) -> Hashable | None: @@ -136,13 +139,13 @@ def scope_key(self) -> Hashable | None: def active_key(self) -> Hashable | None: """Key in :attr:`MDPState.arrays` of the worlds where the op runs at this step, None for every world: its task's, and with ``when``, those where ``when`` was positive at the start of the step.""" - return self.scope_key if self.when is None else ("on", self.name) + return self.scope_key if self.when is None and not self.stages else ("on", self.name) @property def entry_key(self) -> Hashable | None: """Key in :attr:`MDPState.arrays` of the worlds where the op's scope started at this step, in which its state, timer, command, and history restart; None for an op whose scope does not change during an episode.""" - if self.when is not None: + if self.when is not None or self.stages: return "entered", self.name return None if self.stage is None else progress_field(self.stage, "entered") @@ -349,8 +352,10 @@ def build_plan( noises = [op.observation.noise for op in ops[Phase.OBSERVATIONS]] read |= {noise.scale for noise in noises if noise is not None and noise.scale is not None} read |= {op.offset for op in ops[Phase.ACTIONS] if isinstance(op, ActionOp)} - switched = tuple(op for phase_ops in ops.values() for op in phase_ops if isinstance(op, TermOp) and op.when) - read |= {op.when for op in switched} + switched = tuple( + op for phase_ops in ops.values() for op in phase_ops if isinstance(op, TermOp) and (op.when or op.stages) + ) + read |= {op.when for op in switched if op.when is not None} observed = [] for op in reversed(ops[Phase.QUANTITIES]): if op.writes[0] in read: @@ -382,7 +387,7 @@ def computed(phase_ops: tuple) -> list[Step]: ] # A reset prepares the ops with ``when`` in every world of their task. - unswitched = {op.name: replace(op, when=None) for op in switched} + unswitched = {op.name: replace(op, when=None, stages=()) for op in switched} # The reset events see the progress of the episode that ended; the start events of the tasks that run from the # start of the new one, after the progress restarts. events = {"reset": [], "start": []} diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py index df8767d69485..85f9f6301728 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py @@ -296,12 +296,17 @@ def _restart(op: TermOp, state: MDPState, mask: torch.Tensor) -> None: def _switch(ops: tuple[TermOp, ...], state: MDPState, mask: torch.Tensor | None) -> None: - """Turn each op with ``when`` on where its task runs and its field is positive. Stepping (no mask) marks the - worlds where it turned on; observing new episodes, in the masked worlds, marks none, since resets restarted them.""" + """Turn each op with ``when`` on where its task runs and its field is positive, and each op of several tasks on + where any of them runs. Stepping (no mask) marks the worlds where it turned on; observing new episodes, in the + masked worlds, marks none, since resets restarted them.""" for op in ops: - runs = state.arrays[op.when].torch > 0 - if op.scope_key is not None: - runs = runs & state.arrays[op.scope_key].torch + runs = torch.ones(state.episode_length.torch.shape, dtype=torch.bool, device=state.episode_length.torch.device) + if op.stages: + runs = torch.stack([state.arrays[progress_field(stage, "active")].torch for stage in op.stages]).any(0) + elif op.scope_key is not None: + runs = state.arrays[op.scope_key].torch + if op.when is not None: + runs = runs & (state.arrays[op.when].torch > 0) on, entered = state.arrays[op.active_key].torch, state.arrays[op.entry_key].torch if mask is None: torch.logical_and(runs, ~on, out=entered) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py index 8dc59978013c..2034baea5137 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py @@ -909,17 +909,23 @@ def _draw(code: Fusion, node: TaskNode) -> list[str]: def _switch(code: Fusion, ops: tuple[TermOp, ...], stepping: bool) -> None: - """Turn each op with ``when`` on where its task runs and its field is positive. Stepping marks the worlds where it - turned on, whose state restarts; observing new episodes marks none, since resets restarted them.""" + """Turn each op with ``when`` on where its task runs and its field is positive, and each op of several tasks on + where any of them runs. Stepping marks the worlds where it turned on, whose state restarts; observing new episodes + marks none, since resets restarted them.""" for op in ops: on, entered = ( _array(code, op.active_key, wp.array(dtype=wp.bool)), _array(code, op.entry_key, wp.array(dtype=wp.bool)), ) - positive = {wp.bool: "", wp.float32: " > 0.0", wp.int32: " > 0"}[op.when_dtype] - runs = f"{_array(code, op.when, wp.array(dtype=op.when_dtype))}[world]{positive}" - if op.scope_key is not None: - runs = f"{_array(code, op.scope_key, wp.array(dtype=wp.bool))}[world] and {runs}" + conditions = [] + if op.stages: + conditions.append(f"({' or '.join(_progress(code, stage, 'active') for stage in op.stages)})") + elif op.scope_key is not None: + conditions.append(f"{_array(code, op.scope_key, wp.array(dtype=wp.bool))}[world]") + if op.when is not None: + positive = {wp.bool: "", wp.float32: " > 0.0", wp.int32: " > 0"}[op.when_dtype] + conditions.append(f"{_array(code, op.when, wp.array(dtype=op.when_dtype))}[world]{positive}") + runs = " and ".join(conditions) lines = [f"runs = {runs}", f"{entered}[world] = {'runs and not ' + on + '[world]' if stepping else 'False'}"] code.world(*lines, f"{on}[world] = runs", writes=[op.active_key, op.entry_key]) diff --git a/source/isaaclab_experimental/test/mdp2/test_mdp2.py b/source/isaaclab_experimental/test/mdp2/test_mdp2.py index 1dd40a2362b3..f17dcf18e61b 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2.py @@ -1853,7 +1853,8 @@ def test_tasks_restart_their_state_timers_and_commands_when_they_start(): gain = {"joint_pos": robot.joint_pos} def stage(joint: str, hooked: bool) -> mdp2.TaskCfg: - rewards = {"fused": mdp2.Reward(accumulate, inputs=gain, params={"gain": 1.0})} + # Uses that the tasks define alike run as one, so the gains differ. + rewards = {"fused": mdp2.Reward(accumulate, inputs=gain, params={"gain": 2.0 if hooked else 1.0})} commands = {} if hooked: rewards["hooked"] = mdp2.Reward(torch_accumulate(5.0), inputs=gain, params={"gain": 1.0}) @@ -1868,7 +1869,7 @@ def stage(joint: str, hooked: bool) -> mdp2.TaskCfg: total = [step[str(mdp2.term_state("rewards.second.fused", "total"))].item() for step in history] hooked = [step[str(mdp2.term_state("rewards.second.hooked", "total"))].item() for step in history] samples = [step[str(mdp2.term_state("commands.second.count", "samples"))].item() for step in history] - assert total[2:] == [1.0, 2.0, 3.0] # Restarted at zero, then the first joint at every step + assert total[2:] == [2.0, 4.0, 6.0] # Restarted at zero, then twice the first joint at every step assert hooked[1:] == [15.0, 16.0, 17.0, 18.0] # Its initial 5, then its reset hook's 10, at its start assert samples == [0.0, 1.0, 1.0, 2.0, 2.0] # Sampled at its start, then every two steps first = [step[str(mdp2.term_state("rewards.first.fused", "total"))].item() for step in history] @@ -1880,7 +1881,7 @@ def test_subtasks_read_their_own_fields_by_name(): """Subtasks written as tasks of their own read their quantities, the state of their uses, and their progress by their names, which their prefix keeps apart.""" - def reach(joint: str) -> mdp2.TaskCfg: + def reach(joint: str, gain: float) -> mdp2.TaskCfg: inputs = {"joint_pos": robot.joint_pos, "joint_ids": robot.joints(joint)} started = mdp2.Observation(episode_length, inputs={"episode_length": mdp2.progress.started_at}) total = {"command": mdp2.term_state("rewards.held", "total")} @@ -1889,12 +1890,13 @@ def reach(joint: str) -> mdp2.TaskCfg: "reached": mdp2.Quantity(joint_above, inputs=inputs), "held": mdp2.Quantity(generated_commands, inputs=total), }, - rewards={"held": mdp2.Reward(accumulate, inputs={"joint_pos": robot.joint_pos}, params={"gain": 1.0})}, + # The gains differ, so that the rewards are not one use of both subtasks. + rewards={"held": mdp2.Reward(accumulate, inputs={"joint_pos": robot.joint_pos}, params={"gain": gain})}, observations={"policy": {"started": started}}, done=mdp2.quantities.reached, ) - task = mdp2.sequence(first=reach("a"), second=reach("b")) + task = mdp2.sequence(first=reach("a", 1.0), second=reach("b", 2.0)) history = check_progress(task, [[0.0, 1.0], [1.0, 0.0], [1.0, 1.0]], joints=("a", "b")) assert [step["first.done_at"].item() for step in history] == [-1, 2, 2] assert [step["second.done_at"].item() for step in history] == [-1, -1, 3] @@ -2457,3 +2459,87 @@ def run(backend: str, capture: bool) -> list[torch.Tensor]: second[0][[1, 3], 0].tolist() == [1.0, 1.0] and second[0][[0, 2], 0].tolist() == joint_pos[[0, 2], 0].tolist() ) assert third[0][:, 2].tolist() == [1.0, 2.0, 3.0, 1.0] + + +class ContactScene: + """A scene with an ``object`` whose contact sensor is filtered by a destination: its normal forces, and its root + velocity.""" + + def __init__(self, num_worlds: int): + fields = { + "normal_force_matrix_w": mdp2.FieldSchema(("bodies", "filters"), wp.vec3f), + "root_com_vel_w": mdp2.FieldSchema((), wp.spatial_vectorf), + } + names = {"bodies": ("cube",), "filters": ("0",)} + entities = {"object": mdp2.EntitySchema(names=names, fields=fields)} + self.schema = mdp2.SceneSchema(num_worlds=num_worlds, step_dt=0.02, entities=entities) + self.forces = ProxyArray(wp.zeros((num_worlds, 1, 1), dtype=wp.vec3f, device=DEVICE)) + self.velocity = ProxyArray(wp.zeros(num_worlds, dtype=wp.spatial_vectorf, device=DEVICE)) + + def data(self, entity: str, field: str) -> ProxyArray: + return self.forces if field == "normal_force_matrix_w" else self.velocity + + def entity(self, name: str) -> "ContactScene": + return self + + def commit(self, mask: wp.array, fields: Collection[mdp2.FieldSelector]) -> None: + """Nothing to commit.""" + + +def test_resting_on_needs_an_upward_contact_force_and_a_still_object(): + """An object rests on its destination where the destination pushes it up, within the cone, hard enough, and the + object is still.""" + obj = mdp2.Entity("object") + rest = mdp2.Quantity( + mdp2.mdp.resting_on, + inputs={ + "normal_force_matrix_w": obj.normal_force_matrix_w, + "body_ids": obj.bodies("cube"), + "root_com_vel_w": obj.root_com_vel_w, + }, + params={"filter_index": 0, "min_force": 0.1, "min_cos": math.cos(math.pi / 4), "max_speed": 0.003}, + ) + # Resting; too light; pushed sideways; moving. + forces = [[0.0, 0.0, 1.0], [0.0, 0.0, 0.05], [1.0, 0.0, 0.5], [0.0, 0.0, 1.0]] + speeds = [0.0, 0.0, 0.0, 0.01] + for backend in ("torch", "warp"): + scene = ContactScene(num_worlds=4) + builder = mdp2.MDPBuilder(scene.schema) + builder.add_task(mdp2.TaskCfg(quantities={"rest": rest})) + mdp_ = builder.finalize(device=DEVICE, backend=backend) + state, transition = mdp_.state(scene), mdp_.transition() + scene.forces.torch.copy_(torch.tensor(forces, device=DEVICE).view(4, 1, 1, 3)) + scene.velocity.torch[:, 0] = torch.tensor(speeds, device=DEVICE) + mdp2.evaluate(mdp_, state, transition) + assert state.arrays[mdp2.quantities.rest].torch.tolist() == [1.0, 0.0, 0.0, 0.0], backend + + +def test_uses_that_tasks_of_a_sequence_define_alike_run_as_one(): + """Uses that the tasks of a sequence define alike are one op that runs while any of them runs: its state and + observation history carry on from one task to the next. Uses that differ stay apart and restart.""" + inputs = {"joint_pos": robot.joint_pos} + position = mdp2.Observation(joint_pos, inputs=inputs, history_length=2) + + def stage(joint: str, weight: float) -> mdp2.TaskCfg: + rewards = { + "shared": mdp2.Reward(accumulate, inputs=inputs, params={"gain": 1.0}), + "own": mdp2.Reward(accumulate, inputs=inputs, params={"gain": 1.0}, weight=weight), + } + return mdp2.TaskCfg( + rewards=rewards, observations={"policy": {"position": position}}, done=getattr(mdp2.quantities, joint) + ) + + task = mdp2.compose( + mdp2.TaskCfg(quantities=above("a", "b")), mdp2.sequence(first=stage("a", 1.0), second=stage("b", 2.0)) + ) + history = check_progress(task, [[0.25, 0.0], [1.0, 0.0], [0.5, 0.0], [0.75, 0.0]]) + mdp_, _, _ = run_progress(task, [[0.0, 0.0]], "warp", capture=False) + rewards = [op.name for op in mdp_.ops[mdp2.Phase.REWARDS]] + assert rewards == ["rewards.first.shared", "rewards.first.own", "rewards.second.own"] + assert "during first or second" in mdp_.describe() + shared = [step[str(mdp2.term_state("rewards.first.shared", "total"))].item() for step in history] + own = [step[str(mdp2.term_state("rewards.second.own", "total"))].item() for step in history] + assert shared == [0.25, 1.25, 1.75, 2.5] # Carries on into the second task, from step 3 + assert own == [0.0, 0.0, 0.5, 1.25] # Restarted when the second task started + # The history of joint "a" carries on too: [a, b] for the step before, then this step. + assert [step["policy"][0, :2].tolist() for step in history[2:]] == [[1.0, 0.0], [0.5, 0.0]] From 99208cd86c4c768aa238966b2b6a9c18310aa1c4 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 19:39:53 -0800 Subject: [PATCH 24/49] Run MDP2 uses of all the tasks of a sequence in its scope, and log progress at once A use that every task of a sequence or a choice defines alike is a use of that task, which needs no switch. Progress logs average all tasks with a fixed number of kernels per step instead of several per task. --- .../isaaclab_experimental/envs/mdp2_env.py | 18 +++++--- .../isaaclab_experimental/mdp2/builder.py | 14 +++++- .../test/mdp2/test_mdp2.py | 44 ++++++++++++------- 3 files changed, 53 insertions(+), 23 deletions(-) diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py index f5c2a139e7df..2ed7eabb8e10 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py @@ -557,10 +557,12 @@ def _bind(self) -> None: self._tasks = { f"Progress/{path or 'task'}": self.state.arrays[mdp2.progress_field(path, "done")].torch for path in paths } - self._task_worlds = [] - for path in paths: - worlds = [world for tree in self.mdp.tasks if path in tree.completes for world in tree.worlds] - self._task_worlds.append(slice(None) if len(worlds) == self.num_envs else worlds) + # The worlds of the world configs that have each task, if some do not. + members = torch.zeros(self.num_envs, len(paths), device=self.device) + for k, path in enumerate(paths): + for tree in self.mdp.tasks: + members[tree.worlds.start : tree.worlds.stop, k] = float(path in tree.completes) + self._task_members = None if bool(members.all()) else members self._last_done = torch.zeros(self.num_envs, len(self._tasks), device=self.device) self._last_time_outs = torch.zeros(self.num_envs, dtype=torch.bool, device=self.device) if cfg.episode_budget is not None: @@ -748,9 +750,11 @@ def _log_episodes(self) -> None: for name, (_, last, worlds) in self._metrics.items(): log[f"Metrics/{name}"] = last[worlds].mean() # A task is averaged over the worlds of its world config. - for k, (name, worlds) in enumerate(zip(self._tasks, self._task_worlds)): - runs = self._last_runs[worlds, k] - log[name] = (self._last_done[worlds, k] * runs).sum() / runs.sum().clamp(min=1.0) + if self._tasks: + # A few kernels for all tasks at once: each averaged over the worlds that ran it. + runs = self._last_runs if self._task_members is None else self._last_runs * self._task_members + rates = (self._last_done * runs).sum(dim=0) / runs.sum(dim=0).clamp(min=1.0) + log |= {name: rates[k] for k, name in enumerate(self._tasks)} self.extras["log"] = log diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py index 48c20c0a602d..173fc1313421 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py @@ -165,6 +165,7 @@ class CompileContext: subsets: dict[SubsetSelector, tuple[int, ...]] = field(default_factory=dict) tasks: tuple[TaskNode, ...] = () # The task tree, parents first, if the MDP tracks progress modes: dict[str, TaskMode] = field(default_factory=dict) # How the subtasks of each task run, by path + staged: dict[str, bool] = field(default_factory=dict) # Whether the uses of each task start during an episode class MDPBuilder: @@ -555,6 +556,7 @@ def _compile_actions( config are known, see :func:`_allocate_action_slots`. Returns them with its episode length in seconds.""" context = CompileContext(backend, _dependency_errors(schedule)) context.modes = {path: task.mode for path, (task, _) in tasks.items()} + context.staged = {path: staged for path, (_, staged) in tasks.items()} # Terms may read the progress of every task. for path, (task, _) in tasks.items(): for name in ("done", "holding", "active"): @@ -1454,6 +1456,16 @@ def _stages(op: TermOp | ActionOp) -> tuple[str, ...]: return () if op.stage is None else (op.stage,) +def _scoped_to(op: TermOp, context: CompileContext) -> TermOp: + """Return an op of several tasks that are all the subtasks of a sequence or a choice as an op of that task, which + runs exactly when one of them does and needs no switch.""" + parent = op.stages[0].rpartition(".")[0] + children = {path for path in context.modes if path.rpartition(".")[0] == parent and path != parent} + if set(op.stages) != children: + return op + return replace(op, stages=(), stage=parent if context.staged.get(parent) else None) + + def _apart(first: str, second: str, modes: Mapping[str, TaskMode]) -> bool: """Return whether two tasks never run at the same step: they are below different subtasks of a sequence or a choice, which run one at a time.""" @@ -1491,7 +1503,7 @@ def _share_across_stages(context: CompileContext) -> None: kept.append(op) continue other = kept[match] - kept[match] = replace(other, stage=None, stages=(*_stages(other), op.stage)) + kept[match] = _scoped_to(replace(other, stage=None, stages=(*_stages(other), op.stage)), context) renamed[op.use] = other.use ops[:] = kept if not renamed: diff --git a/source/isaaclab_experimental/test/mdp2/test_mdp2.py b/source/isaaclab_experimental/test/mdp2/test_mdp2.py index f17dcf18e61b..2253cd992bef 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2.py @@ -2515,14 +2515,15 @@ def test_resting_on_needs_an_upward_contact_force_and_a_still_object(): def test_uses_that_tasks_of_a_sequence_define_alike_run_as_one(): - """Uses that the tasks of a sequence define alike are one op that runs while any of them runs: its state and - observation history carry on from one task to the next. Uses that differ stay apart and restart.""" + """Uses that tasks of a sequence define alike are one op that runs while any of them runs: its state and + observation history carry on from one task to the next. A use of all the tasks is one of the sequence itself. + Uses that differ stay apart and restart.""" inputs = {"joint_pos": robot.joint_pos} position = mdp2.Observation(joint_pos, inputs=inputs, history_length=2) - def stage(joint: str, weight: float) -> mdp2.TaskCfg: + def stage(joint: str, shared: float, weight: float) -> mdp2.TaskCfg: rewards = { - "shared": mdp2.Reward(accumulate, inputs=inputs, params={"gain": 1.0}), + "shared": mdp2.Reward(accumulate, inputs=inputs, params={"gain": 1.0}, weight=shared), "own": mdp2.Reward(accumulate, inputs=inputs, params={"gain": 1.0}, weight=weight), } return mdp2.TaskCfg( @@ -2530,16 +2531,29 @@ def stage(joint: str, weight: float) -> mdp2.TaskCfg: ) task = mdp2.compose( - mdp2.TaskCfg(quantities=above("a", "b")), mdp2.sequence(first=stage("a", 1.0), second=stage("b", 2.0)) + mdp2.TaskCfg(quantities=above("a", "b")), + mdp2.sequence(first=stage("a", 1.0, 1.0), second=stage("b", 1.0, 2.0), third=stage("a", 3.0, 3.0)), ) - history = check_progress(task, [[0.25, 0.0], [1.0, 0.0], [0.5, 0.0], [0.75, 0.0]]) + # The first task is done at step 2, the second at step 3, so the third runs from step 4. + history = check_progress(task, [[0.25, 0.0], [1.0, 0.0], [0.5, 1.0], [0.75, 0.0]]) mdp_, _, _ = run_progress(task, [[0.0, 0.0]], "warp", capture=False) - rewards = [op.name for op in mdp_.ops[mdp2.Phase.REWARDS]] - assert rewards == ["rewards.first.shared", "rewards.first.own", "rewards.second.own"] - assert "during first or second" in mdp_.describe() - shared = [step[str(mdp2.term_state("rewards.first.shared", "total"))].item() for step in history] - own = [step[str(mdp2.term_state("rewards.second.own", "total"))].item() for step in history] - assert shared == [0.25, 1.25, 1.75, 2.5] # Carries on into the second task, from step 3 - assert own == [0.0, 0.0, 0.5, 1.25] # Restarted when the second task started - # The history of joint "a" carries on too: [a, b] for the step before, then this step. - assert [step["policy"][0, :2].tolist() for step in history[2:]] == [[1.0, 0.0], [0.5, 0.0]] + ops = {op.name: op for op in mdp_.ops[mdp2.Phase.REWARDS]} + assert list(ops) == [ + "rewards.first.shared", + "rewards.first.own", + "rewards.second.own", + "rewards.third.shared", + "rewards.third.own", + ] + assert ops["rewards.first.shared"].stages == ("first", "second") + # The position is one observation of all three tasks: one of the sequence, the root here. + position_op = mdp_.ops[mdp2.Phase.OBSERVATIONS][0] + assert len(mdp_.ops[mdp2.Phase.OBSERVATIONS]) == 1 and position_op.stage is None and not position_op.stages + + def total(use: str) -> list[float]: + return [step[str(mdp2.term_state(use, "total"))].item() for step in history] + + assert total("rewards.first.shared") == [0.25, 1.25, 1.75, 1.75] # Carries on into the second task, not the third + assert total("rewards.second.own") == [0.0, 0.0, 0.5, 0.5] # Restarted when the second task started + # The history of joint "a" carries on through all the tasks: [a, b] for the step before, then this step. + assert [step["policy"][0].tolist() for step in history[2:]] == [[1.0, 0.0, 0.5, 1.0], [0.5, 1.0, 0.75, 0.0]] From 761a0d82b93126d27dd314fcab2d55e9a188e3bb Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 19:46:29 -0800 Subject: [PATCH 25/49] Compute the MDP2 episode logs inside the captured step MDP2RLEnv writes the averages of extras["log"] into one buffer inside the captured step, whose elements the log holds, so that a step launches no logging work from the host. Progress tracking keeps bools, and stacks the drawn tasks only for tasks with a choice. --- .../isaaclab_experimental/envs/mdp2_env.py | 55 +++++++++++-------- .../test/envs/test_mdp2_env.py | 2 +- 2 files changed, 34 insertions(+), 23 deletions(-) diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py index 2ed7eabb8e10..2f2f0413c6d2 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py @@ -549,10 +549,13 @@ def _bind(self) -> None: paths = list(dict.fromkeys(path for tree in self.mdp.tasks for path in sorted(tree.completes))) drawn = {node.path for tree in self.mdp.tasks for node in tree.nodes if tree.drawn(node)} everywhere = torch.ones(self.num_envs, dtype=torch.bool, device=self.device) - self._task_runs = [ - self.state.arrays[mdp2.progress_field(path, "active")].torch if path in drawn else everywhere - for path in paths - ] + # Whether each world ran each task in its last episode, if a choice draws some tasks. + self._task_runs = None + if drawn & set(paths): + self._task_runs = [ + self.state.arrays[mdp2.progress_field(path, "active")].torch if path in drawn else everywhere + for path in paths + ] self._last_runs = torch.ones(self.num_envs, len(paths), device=self.device) self._tasks = { f"Progress/{path or 'task'}": self.state.arrays[mdp2.progress_field(path, "done")].torch for path in paths @@ -568,6 +571,15 @@ def _bind(self) -> None: if cfg.episode_budget is not None: self._init_episode_budget(cfg.episode_budget) + # The captured step writes the logged values into one buffer, whose elements extras["log"] holds as tensors. + names = [f"Episode_Reward/{name}" for name in self._reward_names] + names += [f"Episode_Termination/{name}" for name in self._termination_names] + names += [f"Episode_Termination/{self._time_limit}"] if self._time_limit is not None else [] + names += [f"Metrics/{name}" for name in self._metrics] + names += list(self._tasks) + self._log_values = torch.zeros(len(names), device=self.device) + self.extras["log"] = {name: self._log_values[k] for k, name in enumerate(names)} + @property def max_episode_length(self) -> int | float: """Control steps until a time-out, from the task's time limit.""" @@ -605,7 +617,6 @@ def reset(self, seed: int | None = None, options: dict[str, Any] | None = None) def step(self, action: torch.Tensor) -> VecEnvStepReturn: """Apply the actions, step the physics, evaluate the MDP, reset the worlds that ended, and observe.""" self._step_or_replay(action) - self._log_episodes() self.obs_buf = _clone(self.observations) transition = self.transition @@ -720,16 +731,19 @@ def _after_evaluate(self) -> None: for value, last, _ in self._metrics.values(): torch.where(done, value, last, out=last) if self._tasks: - done_tasks = torch.stack(list(self._tasks.values()), 1).float() + done_tasks = torch.stack(list(self._tasks.values()), 1) torch.where(done[:, None], done_tasks, self._last_done, out=self._last_done) - runs = torch.stack(self._task_runs, 1).float() - torch.where(done[:, None], runs, self._last_runs, out=self._last_runs) + if self._task_runs is not None: + runs = torch.stack(self._task_runs, 1) + torch.where(done[:, None], runs, self._last_runs, out=self._last_runs) if self._time_limit is not None: timed_out = self.state.episode_length.torch >= self.max_episode_length torch.where(done, timed_out, self._last_time_outs, out=self._last_time_outs) + self._log_episodes() def _log_episodes(self) -> None: - """Add the step's term rewards to the episode sums, and record the episodes that ended in ``extras["log"]``.""" + """Add the step's term rewards to the episode sums, and write the averages over the worlds' last finished + episodes to the values that ``extras["log"]`` holds. Part of the captured step.""" transition = self.transition ended = (self._ended if self.cfg.episode_budget is not None else transition.done.torch)[:, None] self._episode_rewards += transition.reward_terms.torch @@ -739,23 +753,20 @@ def _log_episodes(self) -> None: torch.where(ended, terminations, self._last_terminations, out=self._last_terminations) self._episode_rewards.masked_fill_(ended, 0.0) - rewards = self._last_episode_rewards.sum(dim=0) / self._active_worlds[mdp2.Phase.REWARDS] - rewards /= self.max_episode_length_s - terminations = self._last_terminations.sum(dim=0) / self._active_worlds[mdp2.Phase.TERMINATIONS] - log = {f"Episode_Reward/{name}": rewards[k] for k, name in enumerate(self._reward_names)} - log |= {f"Episode_Termination/{name}": terminations[k] for k, name in enumerate(self._termination_names)} + values = [ + self._last_episode_rewards.sum(dim=0) + / (self._active_worlds[mdp2.Phase.REWARDS] * self.max_episode_length_s) + ] + values.append(self._last_terminations.sum(dim=0) / self._active_worlds[mdp2.Phase.TERMINATIONS]) if self._time_limit is not None: - log[f"Episode_Termination/{self._time_limit}"] = self._last_time_outs.float().mean() + values.append(self._last_time_outs.float().mean()[None]) # A quantity that only some worlds compute is averaged over them. - for name, (_, last, worlds) in self._metrics.items(): - log[f"Metrics/{name}"] = last[worlds].mean() - # A task is averaged over the worlds of its world config. + values += [last[worlds].mean()[None] for _, last, worlds in self._metrics.values()] if self._tasks: - # A few kernels for all tasks at once: each averaged over the worlds that ran it. + # Each task is averaged over the worlds that ran it: of the world configs that have it, that drew it. runs = self._last_runs if self._task_members is None else self._last_runs * self._task_members - rates = (self._last_done * runs).sum(dim=0) / runs.sum(dim=0).clamp(min=1.0) - log |= {name: rates[k] for k, name in enumerate(self._tasks)} - self.extras["log"] = log + values.append((self._last_done * runs).sum(dim=0) / runs.sum(dim=0).clamp(min=1.0)) + torch.cat(values, out=self._log_values) def _terminations(task: mdp2.TaskCfg) -> list[tuple[str, Any]]: diff --git a/source/isaaclab_experimental/test/envs/test_mdp2_env.py b/source/isaaclab_experimental/test/envs/test_mdp2_env.py index 7b0f8f169380..d9f9276e0b2e 100644 --- a/source/isaaclab_experimental/test/envs/test_mdp2_env.py +++ b/source/isaaclab_experimental/test/envs/test_mdp2_env.py @@ -217,7 +217,7 @@ def test_env_follows_the_gym_interface_and_commits_resets(monkeypatch): observations, extras = env.reset() - assert observations["policy"].shape == (NUM_ENVS, 4) and "log" not in extras + assert observations["policy"].shape == (NUM_ENVS, 4) assert (robot_data.joint_pos.torch[:, 0].abs() <= 1.0).all() and robot_data.joint_pos.torch.std(0).min() > 0 with pytest.raises(ValueError, match=r"Expected actions of shape \(16, 1\), got \(1, 1\)"): env.step(torch.ones(1, 1, device=env.device)) From c7678844ffbe90024b055c26b603842213fe20d7 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 19:50:07 -0800 Subject: [PATCH 26/49] Average MDP2 progress logs with one mean where every world runs every task --- .../isaaclab_experimental/envs/mdp2_env.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py index 2f2f0413c6d2..dedf53902ab7 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py @@ -762,7 +762,9 @@ def _log_episodes(self) -> None: values.append(self._last_time_outs.float().mean()[None]) # A quantity that only some worlds compute is averaged over them. values += [last[worlds].mean()[None] for _, last, worlds in self._metrics.values()] - if self._tasks: + if self._tasks and self._task_runs is None and self._task_members is None: + values.append(self._last_done.mean(dim=0)) # Every world ran every task + elif self._tasks: # Each task is averaged over the worlds that ran it: of the world configs that have it, that drew it. runs = self._last_runs if self._task_members is None else self._last_runs * self._task_members values.append((self._last_done * runs).sum(dim=0) / runs.sum(dim=0).clamp(min=1.0)) From 31f6ac19c602f565dbb2a368aaee72984ebe3a5d Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 19:50:55 -0800 Subject: [PATCH 27/49] Check that the illegal-contact termination fires in the MDP2 contact parity test --- .../test/envs/test_mdp2_contact_terms.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/source/isaaclab_experimental/test/envs/test_mdp2_contact_terms.py b/source/isaaclab_experimental/test/envs/test_mdp2_contact_terms.py index 0cbda8e691ad..24303589ed03 100644 --- a/source/isaaclab_experimental/test/envs/test_mdp2_contact_terms.py +++ b/source/isaaclab_experimental/test/envs/test_mdp2_contact_terms.py @@ -184,13 +184,14 @@ def test_contact_terms_match_mdp1(robot_with_feet: Path): sensor_cfg.resolve(env.scene) env.reset() - rewarded = False + rewarded = ended = False for _ in range(40): env.step(torch.zeros(NUM_ENVS, env.mdp.action_dim, device=env.device)) undesired_contacts = mdp1.undesired_contacts(mdp1_env, 1.0, sensor_cfg).float() feet_air_time = velocity_mdp1.feet_air_time(mdp1_env, "forward", sensor_cfg, 0.1) illegal_contact = mdp1.illegal_contact(mdp1_env, 50.0, sensor_cfg) rewarded |= bool(feet_air_time.abs().sum() > 0.0) + ended |= bool(illegal_contact.any()) for model, state, transition in models.values(): mdp2.evaluate(model, state, transition) @@ -199,7 +200,7 @@ def test_contact_terms_match_mdp1(robot_with_feet: Path): torch.testing.assert_close(observations["feet_air_time"].torch[:, 0], feet_air_time) assert torch.equal(transition.termination_terms.torch[:, 0], illegal_contact) - assert rewarded # The feet landed during the rollout. + assert rewarded and ended # The feet landed during the rollout, hard enough to end an episode. # A reset clears the contacts that ended the last episode. env.reset() From 8dae7a2f91a99af056191f0dd1552fe5c23b63d6 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 19:52:56 -0800 Subject: [PATCH 28/49] Render only the cameras that MDP2 terms read A task that reads no camera neither renders nor needs Step.RENDER; cameras that share a renderer still render together. --- .../changelog.d/mdp2-part2.changed.rst | 2 ++ .../isaaclab_experimental/envs/mdp2_env.py | 23 ++++++++++++------- .../test/envs/test_mdp2_env.py | 4 +++- 3 files changed, 20 insertions(+), 9 deletions(-) diff --git a/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst b/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst index b81b4ec09396..f8f19c124f4a 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst @@ -22,3 +22,5 @@ step steps between the MDP's graphs. Replayed steps now count their physics steps and advance the simulation time. * Changed ``MDP2EnvCfg.verify_capture`` on physics without a reproducible mode to check the MDP alone, with the physics step replaced by nothing, bitwise, instead of comparing to a relative tolerance. +* Changed :class:`~isaaclab_experimental.envs.MDP2Env` to render only the cameras that some term of the task reads, + and to compute ``extras["log"]`` inside the captured step, as views of one buffer. diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py index dedf53902ab7..c2a113a68e8f 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py @@ -91,14 +91,7 @@ def _init_sim(self) -> None: sim.reset() # The cameras render once per control step, the other sensors refresh with every physics step. scene = self.scene - self._cameras = [sensor for sensor in scene.sensors.values() if isinstance(sensor, Camera)] - # OptiX refits its acceleration structures on the host, which a CUDA graph cannot record: such cameras render - # between the graphs of a step. - self._render_capturable = not any( - isinstance(camera.cfg.renderer_cfg, NewtonOptixRendererCfg) for camera in self._cameras - ) - if self._cameras and Step.RENDER not in cfg.step: - raise ValueError("The scene has cameras, so MDP2EnvCfg.step must hold Step.RENDER, or they never render.") + self._all_cameras = {name: sensor for name, sensor in scene.sensors.items() if isinstance(sensor, Camera)} sensors = [sensor for sensor in scene.sensors.values() if not isinstance(sensor, Camera)] # Sensors that support it refresh together, as in the scene's update. self._batched_sensors = [sensor for sensor in sensors if sensor.supports_batch_update] @@ -140,6 +133,20 @@ def _build(self, task: mdp2.TaskCfg, previous: tuple[mdp2.MDP, mdp2.MDPState] | diagnostics=self.diagnostics, final_observations=self.final_observations, ) + # The cameras that some term reads render, once per control step. + read = { + selector.name if isinstance(selector, mdp2.Entity) else selector.entity + for op in self.mdp.term_ops + for selector in op.inputs.values() + } + self._cameras = [camera for name, camera in self._all_cameras.items() if name in read] + # OptiX refits its acceleration structures on the host, which a CUDA graph cannot record: such cameras render + # between the graphs of a step. + self._render_capturable = not any( + isinstance(camera.cfg.renderer_cfg, NewtonOptixRendererCfg) for camera in self._cameras + ) + if self._cameras and Step.RENDER not in self.cfg.step: + raise ValueError("The task reads cameras, so MDP2EnvCfg.step must hold Step.RENDER, or they never render.") self.state = self.mdp.state(self.scene_data, seed=self._seed) if previous is not None: mdp2.migrate(*previous, self.mdp, self.state) diff --git a/source/isaaclab_experimental/test/envs/test_mdp2_env.py b/source/isaaclab_experimental/test/envs/test_mdp2_env.py index d9f9276e0b2e..373df2937767 100644 --- a/source/isaaclab_experimental/test/envs/test_mdp2_env.py +++ b/source/isaaclab_experimental/test/envs/test_mdp2_env.py @@ -722,10 +722,12 @@ def test_cameras_render_in_the_captured_step_and_the_budget_records_episodes(): cfg.task.quantities["cart_x"] = mdp2.Quantity( cart_x, inputs={"joint_pos": robot.joint_pos, "joint_ids": cart}, record=True ) - # Cameras that never render would observe stale images. + # Cameras that never render would observe stale images. Cameras that no term reads do not render. cfg.step = [Step.PHYSICS, Step.EVALUATE, Step.RESET] with pytest.raises(ValueError, match="must hold Step.RENDER"): MDP2RLEnv(cfg) + unread = replace(cfg, task=replace(cfg.task, observations={"policy": cfg.task.observations["policy"]})) + MDP2RLEnv(unread).close() cfg.step = [Step.PHYSICS, Step.RENDER, Step.EVALUATE, Step.RESET] budget = NUM_ENVS + 4 cfg.episode_budget = budget From 52a3b4b31e4f5f9bb896cf0ea13d2bfca3de0f84 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 19:59:06 -0800 Subject: [PATCH 29/49] Test the new MDP2 features in a captured Cartpole step, and fix two edges A Cartpole task with a tunable weight, a switched reward, a variation, a control-rate action, and a start event of a sequence verifies its capture, sees the solver step the pushed pole, and takes tunings between replays. MDP2RLEnv logs a copy of the in-graph log values each step, since learners keep the logs of a rollout's steps. Merged uses remap every selector of their state, and uses with tunable values are not merged. --- .../changelog.d/mdp2-part2.changed.rst | 3 + .../changelog.d/mdp2-part2.changed.rst | 2 +- .../isaaclab_experimental/envs/mdp2_env.py | 7 ++- .../isaaclab_experimental/mdp2/builder.py | 34 ++++++---- .../test/envs/test_mdp2_env.py | 63 +++++++++++++++++++ .../test/mdp2/test_mdp2.py | 9 ++- 6 files changed, 103 insertions(+), 15 deletions(-) create mode 100644 source/isaaclab/changelog.d/mdp2-part2.changed.rst diff --git a/source/isaaclab/changelog.d/mdp2-part2.changed.rst b/source/isaaclab/changelog.d/mdp2-part2.changed.rst new file mode 100644 index 000000000000..4325f5be8502 --- /dev/null +++ b/source/isaaclab/changelog.d/mdp2-part2.changed.rst @@ -0,0 +1,3 @@ +* Changed the masked resets of :class:`~isaaclab.actuators.DelayedPDActuator` to draw their delays from a Warp device + stream, seeded from Torch's generator when the actuator is created, so that replayed CUDA graphs draw new delays. + Resets with environment indices still draw from Torch. diff --git a/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst b/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst index f8f19c124f4a..9ad7c2b1975a 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst @@ -23,4 +23,4 @@ * Changed ``MDP2EnvCfg.verify_capture`` on physics without a reproducible mode to check the MDP alone, with the physics step replaced by nothing, bitwise, instead of comparing to a relative tolerance. * Changed :class:`~isaaclab_experimental.envs.MDP2Env` to render only the cameras that some term of the task reads, - and to compute ``extras["log"]`` inside the captured step, as views of one buffer. + and to compute the averages of ``extras["log"]`` inside the captured step. diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py index c2a113a68e8f..49057832d8c5 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py @@ -578,14 +578,16 @@ def _bind(self) -> None: if cfg.episode_budget is not None: self._init_episode_budget(cfg.episode_budget) - # The captured step writes the logged values into one buffer, whose elements extras["log"] holds as tensors. + # The captured step writes the logged values into one buffer; each step logs a copy, as learners keep the logs + # of the steps of a rollout. names = [f"Episode_Reward/{name}" for name in self._reward_names] names += [f"Episode_Termination/{name}" for name in self._termination_names] names += [f"Episode_Termination/{self._time_limit}"] if self._time_limit is not None else [] names += [f"Metrics/{name}" for name in self._metrics] names += list(self._tasks) + self._log_names = names self._log_values = torch.zeros(len(names), device=self.device) - self.extras["log"] = {name: self._log_values[k] for k, name in enumerate(names)} + self.extras["log"] = dict(zip(names, self._log_values.clone())) @property def max_episode_length(self) -> int | float: @@ -624,6 +626,7 @@ def reset(self, seed: int | None = None, options: dict[str, Any] | None = None) def step(self, action: torch.Tensor) -> VecEnvStepReturn: """Apply the actions, step the physics, evaluate the MDP, reset the worlds that ended, and observe.""" self._step_or_replay(action) + self.extras["log"] = dict(zip(self._log_names, self._log_values.clone())) self.obs_buf = _clone(self.observations) transition = self.transition diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py index 173fc1313421..1c6e07c3831a 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py @@ -166,6 +166,7 @@ class CompileContext: tasks: tuple[TaskNode, ...] = () # The task tree, parents first, if the MDP tracks progress modes: dict[str, TaskMode] = field(default_factory=dict) # How the subtasks of each task run, by path staged: dict[str, bool] = field(default_factory=dict) # Whether the uses of each task start during an episode + renamed: dict[str, str] = field(default_factory=dict) # Uses merged into others, see _share_across_stages class MDPBuilder: @@ -629,6 +630,7 @@ def _compile_schedule( def _compile_task(self, path: str, tasks: dict[str, tuple[TaskCfg, bool]], context: CompileContext) -> TaskNode: """Compile a task of the tree, or record why its progress cannot be tracked.""" task, staged = tasks[path] + task = replace(task, done=_renamed_field(task.done, context.renamed)) name, errors = f"Task '{path}'" if path else "The task", context.errors children = tuple(f"{path}.{child}" if path else child for child in task.subtasks) done_dtype = None @@ -1480,8 +1482,9 @@ def _share_across_stages(context: CompileContext) -> None: """Merge the ops that tasks of a sequence or a choice define alike, but for their names, into one op that runs while any of these tasks runs: its state, timer, and history carry on from one task to the next rather than restart. Uses that differ, such as in a reward's weight, stay apart; so do quantities and commands, which write - fields of their own, actions, and start events, which run as each task starts.""" - renamed: dict[str, str] = {} # The uses of the merged ops, by those of the ops merged into them + fields of their own, actions, start events, which run as each task starts, and uses with tunable values, which + each task tunes.""" + renamed = context.renamed # The uses of the merged ops, by those of the ops merged into them for phase, ops in context.ops.items(): if phase in (Phase.ACTIONS, Phase.QUANTITIES, Phase.COMMANDS, Phase.RESET_EVENTS): continue @@ -1493,6 +1496,7 @@ def _share_across_stages(context: CompileContext) -> None: k for k, other in enumerate(kept) if op.stage is not None + and not (op.tunables or op.tunable_weight or op.when_default is not None) and _stages(other) and replace(other, name="", use="", index=0, stage=None, stages=()) == key and _exclusive(other, op, context.modes) @@ -1508,17 +1512,25 @@ def _share_across_stages(context: CompileContext) -> None: ops[:] = kept if not renamed: return - # Uses that read the state of a merged op read that of the op it merged into. + # Uses that read the state of a merged op read that of the op it merged into, as do tasks' completions. for ops in context.ops.values(): for k, op in enumerate(ops): - if isinstance(op, TermOp): - inputs = { - arg: replace(selector, entity=renamed.get(selector.entity, selector.entity)) - if isinstance(selector, FieldSelector) and not selector.scene - else selector - for arg, selector in op.inputs.items() - } - ops[k] = replace(op, inputs=MappingProxyType(inputs)) + if isinstance(op, ActionOp): + ops[k] = replace(op, offset=_renamed_field(op.offset, renamed)) + continue + inputs = {arg: _renamed_field(selector, renamed) for arg, selector in op.inputs.items()} + changes = {"inputs": MappingProxyType(inputs), "when": _renamed_field(op.when, renamed)} + if op.observation is not None and op.observation.noise is not None: + noise = replace(op.observation.noise, scale=_renamed_field(op.observation.noise.scale, renamed)) + changes["observation"] = replace(op.observation, noise=noise) + ops[k] = replace(op, **changes) + + +def _renamed_field(selector: typing.Any, renamed: Mapping[str, str]) -> typing.Any: + """Return a selector of the state of a use merged into another as one of the state of that use.""" + if isinstance(selector, FieldSelector) and not selector.scene and selector.entity in renamed: + return replace(selector, entity=renamed[selector.entity]) + return selector def _used_columns(ops: tuple[TermOp, ...], worlds: range) -> dict[str, int]: diff --git a/source/isaaclab_experimental/test/envs/test_mdp2_env.py b/source/isaaclab_experimental/test/envs/test_mdp2_env.py index 373df2937767..4d47d2926eaa 100644 --- a/source/isaaclab_experimental/test/envs/test_mdp2_env.py +++ b/source/isaaclab_experimental/test/envs/test_mdp2_env.py @@ -913,3 +913,66 @@ def test_replayed_steps_do_the_host_work_of_their_physics_steps(): assert env.sim.backend_manager.get_simulation_time() - time == pytest.approx(5 * env.step_dt) finally: env.close() + + +def push_pole_torch(mask, joint_vel, joint_ids): + joint_vel[:, joint_ids.long()] += 5.0 * mask[:, None] + + +def test_tunables_switches_stages_variations_and_control_actions_run_in_the_captured_step(): + """A task with a tunable weight, a switched reward, a variation, an action at the control rate, and a sequence + whose second task pushes the pole when it starts, steps alike captured and uncaptured; the solver sees the push, + and tunings change replayed steps.""" + cfg = cartpole_cfg() + task = cfg.task + task = replace( + task, + actions={"joint_effort": replace(task.actions["joint_effort"], rate=mdp2.ActionRate.CONTROL)}, + rewards={ + **task.rewards, + "alive": replace(task.rewards["alive"], weight=mdp2.Tunable(1.0)), + "pole_vel": replace(task.rewards["pole_vel"], when=mdp2.Tunable(True)), + }, + ) + ready = mdp2.Quantity(after_steps, inputs={"episode_length": mdp2.episode_length}, params={"steps": 3}) + push = mdp2.Event( + mdp2.Term(torch=push_pole_torch), + inputs={"joint_ids": pole}, + outputs={"joint_vel": robot.joint_vel}, + mode=mdp2.EventMode.START, + ) + cfg.task = mdp2.compose( + task, + mdp.variation("cart_start", robot.joint_pos, cart, mdp.Uniform(-0.1, 0.1)), + mdp2.TaskCfg(quantities={"ready": ready}), + mdp2.sequence( + warm=mdp2.Milestone(mdp2.quantities.ready), + push=mdp2.TaskCfg(events={"push": push}, done=mdp2.terminated), + ), + ) + cfg.task.terminations["cart_out_of_bounds"] = None + cfg.verify_capture = 10 + env = MDP2RLEnv(cfg) + try: + env.reset() + cart_start = env.state.arrays[mdp2.quantities.cart_start].torch + actions = torch.zeros(NUM_ENVS, 1, device=env.device) + pole_vel = env.scene["robot"].data.joint_vel.torch[:, 1] + for step in range(1, 6): + _, _, _, _, extras = env.step(actions) + if step == 2: + still = pole_vel.abs().max().item() + # The push task started at the end of step 3, and the solver stepped the pushed pole from step 4. + assert env.is_captured and still < 2.0 and (pole_vel.abs() > 3.0).all() + assert ((cart_start >= -0.1) & (cart_start < 0.1)).all() and cart_start.std() > 0 + rewards = [op.name for op in env.mdp.ops[mdp2.Phase.REWARDS]] + alive, pole_vel_term = rewards.index("rewards.alive"), rewards.index("rewards.pole_vel") + env.tune("rewards.alive.weight", 0.0, at="step") + env.tune("rewards.pole_vel.when", False, at="step") + env.step(actions) + assert (env.transition.reward_terms.torch[:, alive] == 0.0).all() + env.step(actions) # The switch turned off at the end of the step before + assert (env.transition.reward_terms.torch[:, pole_vel_term] == 0.0).all() + assert env.state.revision.torch.tolist() == [2] * NUM_ENVS + finally: + env.close() diff --git a/source/isaaclab_experimental/test/mdp2/test_mdp2.py b/source/isaaclab_experimental/test/mdp2/test_mdp2.py index 2253cd992bef..7c724568ca9e 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2.py @@ -2526,8 +2526,13 @@ def stage(joint: str, shared: float, weight: float) -> mdp2.TaskCfg: "shared": mdp2.Reward(accumulate, inputs=inputs, params={"gain": 1.0}, weight=shared), "own": mdp2.Reward(accumulate, inputs=inputs, params={"gain": 1.0}, weight=weight), } + # Reads the state of its own shared reward, which may be the one that it shares with another task. + total = mdp2.Quantity(generated_commands, inputs={"command": mdp2.term_state("rewards.shared", "total")}) return mdp2.TaskCfg( - rewards=rewards, observations={"policy": {"position": position}}, done=getattr(mdp2.quantities, joint) + rewards=rewards, + quantities={"total": total}, + observations={"policy": {"position": position}}, + done=getattr(mdp2.quantities, joint), ) task = mdp2.compose( @@ -2554,6 +2559,8 @@ def total(use: str) -> list[float]: return [step[str(mdp2.term_state(use, "total"))].item() for step in history] assert total("rewards.first.shared") == [0.25, 1.25, 1.75, 1.75] # Carries on into the second task, not the third + # The second task's quantity reads the shared state, from the step before. + assert [step["quantities.second.total"].item() for step in history] == [0.0, 0.25, 1.25, 1.75] assert total("rewards.second.own") == [0.0, 0.0, 0.5, 0.5] # Restarted when the second task started # The history of joint "a" carries on through all the tasks: [a, b] for the step before, then this step. assert [step["policy"][0].tolist() for step in history[2:]] == [[1.0, 0.0, 0.5, 1.0], [0.5, 1.0, 0.75, 0.0]] From 4802915e76f6ba8c35f0fe5b3ab67b13e80488e0 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 19 Nov 2026 20:02:14 -0800 Subject: [PATCH 30/49] Document MDP2 runtime values, switches, choices, variations, and the Arena port The guide gains a section on changing a task while it trains, with measured costs, and a table that maps Arena's success and variation concepts to MDP2. The API pages list the new exports. --- .../isaaclab_experimental.mdp2.rst | 17 +++ docs/source/experimental-features/mdp2.rst | 112 +++++++++++++++--- .../isaaclab/actuators/actuator_base.py | 2 +- .../changelog.d/mdp2-part2.changed.rst | 10 +- 4 files changed, 121 insertions(+), 20 deletions(-) diff --git a/docs/source/api/lab_experimental/isaaclab_experimental.mdp2.rst b/docs/source/api/lab_experimental/isaaclab_experimental.mdp2.rst index 17ef4ee24c41..a0ffb9e9f691 100644 --- a/docs/source/api/lab_experimental/isaaclab_experimental.mdp2.rst +++ b/docs/source/api/lab_experimental/isaaclab_experimental.mdp2.rst @@ -23,6 +23,7 @@ Terms and task configuration TaskCfg DirectAction Action + ActionRate Observation ObservationGroup Reward @@ -33,10 +34,14 @@ Terms and task configuration EventMode Quantity UniformNoise + Tunable + tunable term_state compose sequence split + choice + rename Milestone TaskMode progress @@ -57,10 +62,13 @@ Building and running Backend CapturedMDP startup + process_actions apply_actions evaluate reset observe + tune + migrate Scene data ---------- @@ -85,6 +93,8 @@ Scene data .. autoclass:: TaskCfg .. autoclass:: DirectAction .. autoclass:: Action +.. autoclass:: ActionRate + :members: .. autoclass:: Observation .. autoclass:: ObservationGroup .. autoclass:: Reward @@ -96,10 +106,14 @@ Scene data :members: .. autoclass:: Quantity .. autoclass:: UniformNoise +.. autoclass:: Tunable +.. autofunction:: tunable .. autofunction:: term_state .. autofunction:: compose .. autofunction:: sequence .. autofunction:: split +.. autofunction:: choice +.. autofunction:: rename .. autoclass:: Milestone .. autoclass:: TaskMode :members: @@ -119,10 +133,13 @@ Scene data .. autoclass:: CapturedMDP :members: .. autofunction:: startup +.. autofunction:: process_actions .. autofunction:: apply_actions .. autofunction:: evaluate .. autofunction:: reset .. autofunction:: observe +.. autofunction:: tune +.. autofunction:: migrate .. autoclass:: SceneData :members: .. autoclass:: SceneSchema diff --git a/docs/source/experimental-features/mdp2.rst b/docs/source/experimental-features/mdp2.rst index 280394f21383..e6566dc65cbe 100644 --- a/docs/source/experimental-features/mdp2.rst +++ b/docs/source/experimental-features/mdp2.rst @@ -119,6 +119,9 @@ one: * - :func:`~isaaclab_experimental.mdp2.split` - each in its own worlds - once the one of the world is + * - :func:`~isaaclab_experimental.mdp2.choice` + - one per episode and world, drawn at the reset + - once the drawn one is .. code-block:: python @@ -141,14 +144,22 @@ one: running. Its uses run only while it does: its rewards, terminations, commands, and events follow the subtask that ran when the step started, and its observations the one that runs after it. Starting restarts their state, timers, commands, and observation histories. Quantities are measurements: they run in every step, and only restart. Reset - and startup events set up whole episodes, so they run at every reset. + and startup events set up whole episodes, so they run at every reset; ``EventMode.START`` events run when their + task starts, at the reset or during the episode. Uses that the tasks define alike, but for their names, run as one + while any of these tasks runs, so their state and histories carry on; a use of all of them is one of the sequence. +- **Repeats.** ``repeat=True`` counts a task's completions as ``mdp2.progress..count``, such as the drops of an + object: once done, it restarts, with its subtasks and uses, when its completion no longer holds. - **Names.** The uses of a subtask get its name as a prefix, as in ``rewards.grasp.grasp``, except in a split, whose subtasks run apart. A subtask reads its own fields by their names, as a task alone does, so each stage of a sequence can have its own ``reached``: its commands and quantities, the ``term_state`` and ``tunable`` values of its - uses, and its ``mdp2.progress``; inner names win. Observations of the same name share their columns, as wide as the - widest, so a ``goal`` of each - stage, or the ``joint_pos`` of two robots, is one input of the policy; :meth:`~isaaclab_experimental.mdp2.MDP.spec` - names the columns, and :meth:`~isaaclab_experimental.mdp2.MDP.observation_mask` gives those each world writes. + uses, and its ``mdp2.progress``; inner names win. Observations and actions of subtasks that take turns (a sequence, + a choice, or a split) share the columns of their name, as wide as the widest, so a ``goal`` of each stage, or the + ``joint_pos`` of two robots in two world configs, is one input of the policy. Those of subtasks that run together + get columns of their own, named with the subtask's name, as in ``left.joint_pos``; + :func:`~isaaclab_experimental.mdp2.rename` binds a part to other entities, so that it can run twice. + :meth:`~isaaclab_experimental.mdp2.MDP.spec` names the columns, with joint and body names, and + :meth:`~isaaclab_experimental.mdp2.MDP.action_mask` and :meth:`~isaaclab_experimental.mdp2.MDP.observation_mask` + give those each world takes and writes. - **Progress.** Every task's progress is a set of fields that terms read: ``mdp2.progress.done``, ``mdp2.progress.grasp.done``, and also ``holding``, ``active``, ``score``, ``done_at``, ``started_at``, and a sequence's ``stage`` (observed with :data:`~isaaclab_experimental.mdp2.mdp.one_hot`). ``MDP2RLEnv`` logs whether each @@ -224,9 +235,10 @@ a vision-language-action model reads camera images and named observation terms, episode ended. - **Cameras** are scene entities whose data types are fields, such as ``external_camera.rgb``. ``MDP2Env`` renders - them once per control step at ``Step.RENDER``, after the physics, inside the step's CUDA graph; a step without - ``Step.RENDER`` is an error when the scene has cameras. Insert ``ResetStep.RENDER`` before ``ResetStep.OBSERVE`` in - ``reset_step`` to render them again after the resets, so that new episodes start with their own images. + the cameras that terms read once per control step at ``Step.RENDER``, after the physics, inside the step's CUDA + graph; a step without ``Step.RENDER`` is an error when terms read cameras. Insert ``ResetStep.RENDER`` before + ``ResetStep.OBSERVE`` in ``reset_step`` to render them again after the resets, so that new episodes start with + their own images. - **Observation groups.** A group in :attr:`~isaaclab_experimental.mdp2.TaskCfg.observations` is a dict of uses, concatenated into one ``float32`` tensor, or an :class:`~isaaclab_experimental.mdp2.ObservationGroup`. With ``concatenate=False``, the group is observed as a dict of tensors with each term's own shape and type, such as @@ -254,24 +266,94 @@ episode ended. success_rate = env.episode_records()["termination/success"].mean() +Changing a task while it trains +------------------------------- + +The values and structure of a task can change while it runs, at the cost of what they invalidate. + +.. code-block:: python + + track = mdp2.Reward(mdp.track_lin_vel_xy_exp, ..., params={"std": mdp2.Tunable(0.5)}, weight=mdp2.Tunable(1.5)) + rewards = {"track": track} + env.tune("rewards.track.weight", 3.0) # In each world at its next reset + env.tune("rewards.track.std", 0.25, worlds=slice(0, 2048), at="step") # From the next step + + rewards = {"stand_still": mdp2.Reward(..., when=mdp2.commands.standing)} # Only where the mode command says so + env.update_task(new_task) # Recompile on the same scene, keep the state + +- **Runtime values.** A param or reward weight declared :class:`~isaaclab_experimental.mdp2.Tunable` is a field of + one value per world, ``mdp2.tunable(use, name)``, which ``wp.func`` s take as their world's value and other terms + and events may read and write, such as a curriculum. :meth:`~isaaclab_experimental.envs.MDP2Env.tune` changes it + in place while graphs replay, at each world's next reset by default, so that no episode mixes two values; each + world counts its tunings in ``state.revision``, which episode records hold. Tasks without tunable values compile + to the same kernels. +- **Switches.** ``when`` on a reward, termination, observation, command, or interval event runs it where a field was + positive at the start of the step, and restarts it where it turns on; ``when=mdp2.Tunable(True)`` is a switch per + world that ``tune`` flips. +- **Multi-task learning.** :func:`~isaaclab_experimental.mdp2.choice` draws one subtask per episode and world, by + weights; ``Progress/`` logs each over the worlds that drew it. +- **Variations.** :func:`~isaaclab_experimental.mdp2.mdp.variation` draws a value per world at every reset, writes it + to the scene, and records it per episode: :class:`~isaaclab_experimental.mdp2.mdp.Uniform` in a tunable range, + :class:`~isaaclab_experimental.mdp2.mdp.Choice`, or :class:`~isaaclab_experimental.mdp2.mdp.Replay` of recorded + values in the order of the resets, which does not depend on the number of worlds. +- **Actions at two rates.** ``rate=ActionRate.CONTROL`` applies an action once per control step, before the physics + steps, such as an embedded whole-body controller that writes joint targets; the default applies it before every + physics step. Tasks of a sequence may take actions of their own. +- **New structure.** :meth:`~isaaclab_experimental.envs.MDP2Env.update_task` builds another task on the same scene + and carries over, with :func:`~isaaclab_experimental.mdp2.migrate`, the state, random streams, and reward weights + of the uses that both have; it truncates the episodes by default, and the next step compiles and captures anew. + +Measured on Go2 at 4096 worlds (MDP time per step, physics replaced by nothing): the plain task 81 µs, every reward +weight and tracking width tunable 81 µs, all rewards switched 86 µs, the rewards in two stages of a sequence 103 µs. + + +Porting from Arena +------------------ + +.. list-table:: + :header-rows: 1 + + * - Arena + - MDP2 + * - ``CompletionCriteria`` with subtasks + - a task with ``done`` or milestones, combined with ``compose`` or ``sequence`` + * - ``subtasks_are_sequential`` + - :func:`~isaaclab_experimental.mdp2.sequence` rather than :func:`~isaaclab_experimental.mdp2.compose` + * - ``K`` of the subtasks + - ``compose(..., require=K)`` + * - ``desired_subtask_success_state`` + - ``final=True`` or ``False`` on the subtask + * - ``TrueForConsecutiveSteps`` + - ``hold=n`` + * - ``object_on_destination`` + - :data:`~isaaclab_experimental.mdp2.mdp.resting_on`, held with ``hold`` + * - tracked events + - ``repeat=True``, counted as ``progress..count`` + * - run-time variations and their JSONL records + - :func:`~isaaclab_experimental.mdp2.mdp.variation`, with ``episode_budget`` records + * - per-episode results + - ``env.episode_records()``: ``progress/`` (the step it was done), ``progress/score``, recorded quantities + * - configclass merging of scene, embodiment, and task + - :func:`~isaaclab_experimental.mdp2.compose`, and :func:`~isaaclab_experimental.mdp2.rename` for a part twice + + Limitations ----------- - Newton only. Different robots in different worlds are not supported, since Newton's articulation views need homogeneous worlds; different task configs on the same robot are. -- The environments support implicit, ideal PD, and DC motor actuators only. Captured steps replay the actuators' - masked resets, and delayed actuators draw their delays from Torch's random generator on reset, which a replayed - graph would repeat. Actuator-network and BAM actuators are not supported yet either. +- The environments support actuators that CUDA graphs can replay: Isaac Lab actuators with + :attr:`~isaaclab.actuators.ActuatorBase.capturable`, and Newton's own actuators, which run delayed and BAM ones. + Actuator networks are not supported. - Joint and body orderings (``ArticulationCfg.joint_ordering`` and ``body_ordering``) are not supported: terms read the asset's data in kernels, and orderings make the asset keep reordered copies that it refreshes outside the graphs. - Rendering runs on the host after each control step, outside the CUDA graphs: at most once per control step, when one of its physics steps reaches ``sim.render_interval``, and after the step's resets (MDP1 renders inside the decimation loop, before resets). ``render_enabled`` and ``num_rerenders_on_reset`` are not supported. -- A step that replays as a CUDA graph skips the host bookkeeping of ``SimulationContext.step``: the physics step - count and the simulation time stop advancing after the first steps, a visualizer that pauses training does not - block the training loop, and the solver's post-step host checks do not run. Consumers that key frames by the - physics step count, such as video recorders, are not supported. +- A step that replays as a CUDA graph does the host work of its physics steps once, after the replay + (:meth:`~isaaclab.sim.SimulationContext.after_replay`): it counts them, advances the simulation time, and waits + while a visualizer pauses training. The solver's post-step host checks do not run. - Asset data that is derived on demand, such as ``root_lin_vel_b``, is not refreshed by a captured step. Terms read the fields of the scene data, which alias the solver state; code outside the MDP that reads asset data between steps should use those too, for example ``root_com_vel_w`` rotated by ``root_link_pose_w``. diff --git a/source/isaaclab/isaaclab/actuators/actuator_base.py b/source/isaaclab/isaaclab/actuators/actuator_base.py index c54ff2ed4bad..303386750b17 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_base.py +++ b/source/isaaclab/isaaclab/actuators/actuator_base.py @@ -115,7 +115,7 @@ class ActuatorBase(ABC): They must then not synchronize with the host, nor draw from Torch's random generators, whose draws a replayed graph repeats, when Torch joins the capture on the capturing stream. Environments that replay their steps as graphs with Torch work inside them, such as MDP2's, accept only such actuators. Unlike - :attr:`ActuatorCollection.is_graphable`, Torch models qualify. + :attr:`~isaaclab.actuators.ActuatorCollection.is_graphable`, Torch models qualify. """ computed_effort: torch.Tensor diff --git a/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst b/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst index 9ad7c2b1975a..6288197027b0 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst @@ -1,9 +1,11 @@ -* **Breaking:** Changed :attr:`~isaaclab_experimental.envs.MDP2EnvCfg.task` to one task: a task that splits the worlds between - tasks is :func:`~isaaclab_experimental.mdp2.split`, which replaces the list of tasks and ``task_worlds``. Migrate +* **Breaking:** Changed :attr:`~isaaclab_experimental.envs.MDP2EnvCfg.task` to one task: a task that splits the + worlds between tasks is :func:`~isaaclab_experimental.mdp2.split`, which replaces the list of tasks and + ``task_worlds``. Migrate ``task=[WALK, STAND], task_worlds=[3072, 1024]`` to ``task=mdp2.split(walk=WALK, stand=STAND, worlds={"walk": 3072, "stand": 1024})``. -* **Breaking:** Changed the observation columns of MDP2 world configs: observations of the same name share their columns, as wide - as the widest, and each name has its own, instead of each world config's observations starting at the first column. +* **Breaking:** Changed the observation columns of MDP2 world configs: observations of the same name share their + columns, as wide as the widest, and each name has its own, instead of each world config's observations starting at + the first column. * **Breaking:** Changed the action columns of MDP2 world configs: actions of the same name share their columns, as wide as the widest, as observations do, and the last actions hold zero in the columns a world does not take, which :meth:`~isaaclab_experimental.mdp2.MDP.action_mask` gives. This replaces the narrow copies of the last actions and From bf4a67ea675d854e845c911a0cf2f3d9a5eb0703 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Fri, 20 Nov 2026 13:43:16 -0800 Subject: [PATCH 31/49] Keep MDP2 episode logs in one generated kernel per step The episode statistics were about 15 Torch operations plus two per recorded quantity inside the captured step. One fused world-thread kernel now sums the term rewards and keeps each column of the last finished episode, pre-scaled, and the log is their sum over worlds, computed once per step outside the graph. A quantity recorded in only some worlds no longer copies a host index inside the capture, and rewards log per second of the episode without a time limit. --- .../isaaclab_experimental/envs/mdp2_env.py | 223 ++++++++++-------- .../isaaclab_experimental/envs/mdp2_verify.py | 1 + .../test/envs/test_mdp2_env.py | 6 +- 3 files changed, 129 insertions(+), 101 deletions(-) diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py index 49057832d8c5..3a4748cd4fb8 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py @@ -32,6 +32,7 @@ from isaaclab_experimental import mdp2 from isaaclab_experimental.mdp2 import rng from isaaclab_experimental.mdp2.capture import torch_in_warp_capture +from isaaclab_experimental.mdp2.fusion import Fusion from isaaclab_experimental.mdp2.plan import Call from .mdp2_env_cfg import MDP2EnvCfg, MDP2RLEnvCfg, ResetStep, Stage, Step @@ -367,6 +368,11 @@ def run_all(steps: list[Callable[[], None]] = steps) -> None: def _after_evaluate(self) -> None: """Read the step's results before the worlds that ended are reset. Part of the captured step.""" + def step_buffers(self) -> dict[str, torch.Tensor]: + """Return, by name, the buffers beyond the MDP's that the captured step writes, which + :attr:`~MDP2EnvCfg.verify_capture` compares.""" + return {} + def _simulate(self) -> None: """Apply the actions and step the physics ``decimation`` times.""" # Actions apply before every physics step, as in MDP1, so targets relative to the joint state follow it, @@ -525,69 +531,114 @@ def _bind(self) -> None: self.observation_space = gym.vector.utils.batch_space(self.single_observation_space, self.num_envs) self.action_space = gym.vector.utils.batch_space(self.single_action_space, self.num_envs) - # Per-term episode statistics, kept on the device so that logging needs no host sync. self._reward_names = [op.name.split(".", 1)[1] for op in self.mdp.ops[mdp2.Phase.REWARDS]] self._termination_names = [op.name.split(".", 1)[1] for op in self.mdp.ops[mdp2.Phase.TERMINATIONS]] - # Terms are averaged over the worlds where they are active. - self._active_worlds = { - phase: torch.tensor( - [self.num_envs if op.worlds is None else len(op.worlds) for op in self.mdp.ops[phase]], - device=self.device, - ) - for phase in (mdp2.Phase.REWARDS, mdp2.Phase.TERMINATIONS) - } - self._episode_rewards = torch.zeros(self.num_envs, len(self._reward_names), device=self.device) - self._last_episode_rewards = torch.zeros_like(self._episode_rewards) - self._last_terminations = torch.zeros(self.num_envs, len(self._termination_names), device=self.device) - self._metrics = { - op.name.split(".", 1)[1]: ( - self.state.arrays[op.writes[0]].torch, - torch.zeros(self.num_envs, device=self.device), - slice(None) if op.worlds is None else list(op.worlds), - ) - for op in self.mdp.ops[mdp2.Phase.QUANTITIES] - if op.record - } - # The time limit is not an op: whether it ended the last episode of each world is kept apart, under its name. + # The time limit is not an op: whether it ended the last episode of each world is logged under its name. time_limits = [name for name, term in _terminations(cfg.task) if isinstance(term, mdp2.TimeLimit)] self._time_limit = time_limits[0] if time_limits else None - # Progress: whether each task with a completion was done in each world's last finished episode, logged over - # the worlds of the world configs that have it, and for a task of a choice over those that drew it. - paths = list(dict.fromkeys(path for tree in self.mdp.tasks for path in sorted(tree.completes))) - drawn = {node.path for tree in self.mdp.tasks for node in tree.nodes if tree.drawn(node)} - everywhere = torch.ones(self.num_envs, dtype=torch.bool, device=self.device) - # Whether each world ran each task in its last episode, if a choice draws some tasks. - self._task_runs = None - if drawn & set(paths): - self._task_runs = [ - self.state.arrays[mdp2.progress_field(path, "active")].torch if path in drawn else everywhere - for path in paths - ] - self._last_runs = torch.ones(self.num_envs, len(paths), device=self.device) - self._tasks = { - f"Progress/{path or 'task'}": self.state.arrays[mdp2.progress_field(path, "done")].torch for path in paths - } - # The worlds of the world configs that have each task, if some do not. - members = torch.zeros(self.num_envs, len(paths), device=self.device) - for k, path in enumerate(paths): - for tree in self.mdp.tasks: - members[tree.worlds.start : tree.worlds.stop, k] = float(path in tree.completes) - self._task_members = None if bool(members.all()) else members - self._last_done = torch.zeros(self.num_envs, len(self._tasks), device=self.device) - self._last_time_outs = torch.zeros(self.num_envs, dtype=torch.bool, device=self.device) if cfg.episode_budget is not None: self._init_episode_budget(cfg.episode_budget) + self._bind_logs() + + def _bind_logs(self) -> None: + """Generate the kernel that sums the term rewards of each world's episode and, where it ended, keeps the logged + values of the episode, scaled so that their sum over the worlds is the log: the reward sum per second and + whether each termination ended it, averaged over the worlds where the term runs, the value of each recorded + quantity, and whether each task with a completion was done, averaged over the worlds that ran the task.""" + n, device, transition = self.num_envs, self.device, self.transition + code = Fusion("mdp2_episode_log", n, device) + self._episode_rewards = torch.zeros(n, len(self._reward_names), device=device) + + def argument(tensor: torch.Tensor | ProxyArray, annotation: Any) -> str: + array = tensor.warp if isinstance(tensor, ProxyArray) else wp.from_torch(tensor, dtype=annotation.dtype) + self._log_arrays.append(array) + return code.argument(id(array), annotation, lambda call: array) + + def share(worlds: Sequence[int] | None) -> float: + return 1.0 / (n if worlds is None else len(worlds)) + + def member(worlds: Sequence[int] | None) -> str: + """The condition that a world is one of ``worlds``, true if None.""" + if worlds is None: + return "True" + mask = torch.zeros(n, dtype=torch.bool, device=device) + mask[list(worlds)] = True + return f"{argument(mask, wp.array(dtype=wp.bool))}[world]" + + self._log_arrays: list[wp.array] = [] # The kernel's arguments, kept alive with their Torch tensors + names: list[str] = [] + columns: list[str] = [] # The statement that keeps each column where an episode ended + # Rewards: their sums, also where the episodes go on. + rewards = self.mdp.ops[mdp2.Phase.REWARDS] + summed: list[str] = [] # Adds the step's reward to the sum + restarted: list[str] = [] # Restarts the sum where the episode ended + if rewards: + terms = argument(transition.reward_terms, wp.array2d(dtype=wp.float32)) + sums = argument(self._episode_rewards, wp.array2d(dtype=wp.float32)) + if math.isfinite(self.max_episode_length): + seconds = repr(float(self.max_episode_length_s)) + else: # Without a time limit, per second of the episode itself + length = argument(self.state.episode_length, wp.array(dtype=self.state.episode_length.warp.dtype)) + seconds = f"(float({length}[world]) * {float(self.step_dt)!r})" + for k, op in enumerate(rewards): + names.append(f"Episode_Reward/{self._reward_names[k]}") + summed.append(f"{sums}[world, {k}] = {sums}[world, {k}] + {terms}[world, {k}]") + restarted.append(f" {sums}[world, {k}] = 0.0") + columns.append(f"{sums}[world, {k}] * {share(op.worlds)!r} / {seconds}") + terminations = self.mdp.ops[mdp2.Phase.TERMINATIONS] + if terminations: + flags = argument(transition.termination_terms, wp.array2d(dtype=wp.bool)) + for k, op in enumerate(terminations): + names.append(f"Episode_Termination/{self._termination_names[k]}") + columns.append(f"wp.where({flags}[world, {k}], {share(op.worlds)!r}, 0.0)") + if self._time_limit is not None: + length = argument(self.state.episode_length, wp.array(dtype=self.state.episode_length.warp.dtype)) + names.append(f"Episode_Termination/{self._time_limit}") + columns.append(f"wp.where({length}[world] >= {int(self.max_episode_length)}, {share(None)!r}, 0.0)") + # Recorded quantities, averaged over the worlds that compute them. + for op in self.mdp.ops[mdp2.Phase.QUANTITIES]: + if op.record: + value = self.state.arrays[op.writes[0]] + array = argument(value, wp.array(dtype=value.warp.dtype)) + names.append(f"Metrics/{op.name.split('.', 1)[1]}") + columns.append(f"wp.where({member(op.worlds)}, float({array}[world]) * {share(op.worlds)!r}, 0.0)") + # Progress, over the worlds of the world configs that have each task, and for a task of a choice over those + # that drew it: such a task keeps a second column, of the worlds that ran it, to divide by. + paths = list(dict.fromkeys(path for tree in self.mdp.tasks for path in sorted(tree.completes))) + drawn = {node.path for tree in self.mdp.tasks for node in tree.nodes if tree.drawn(node)} + ratios: list[tuple[int, int]] = [] # Columns of the tasks of a choice: (done, ran) + for path in paths: + worlds = [w for tree in self.mdp.tasks if path in tree.completes for w in tree.worlds] + worlds = None if len(worlds) == n else worlds + done = argument(self.state.arrays[mdp2.progress_field(path, "done")], wp.array(dtype=wp.bool)) + names.append(f"Progress/{path or 'task'}") + if path in drawn: + active = argument(self.state.arrays[mdp2.progress_field(path, "active")], wp.array(dtype=wp.bool)) + ran = f"({member(worlds)} and {active}[world])" + columns.append(f"wp.where({ran} and {done}[world], 1.0, 0.0)") + ratios.append((len(columns) - 1, len(columns))) + columns.append(f"wp.where({ran}, 1.0, 0.0)") + else: + columns.append(f"wp.where({member(worlds)} and {done}[world], {share(worlds)!r}, 0.0)") - # The captured step writes the logged values into one buffer; each step logs a copy, as learners keep the logs - # of the steps of a rollout. - names = [f"Episode_Reward/{name}" for name in self._reward_names] - names += [f"Episode_Termination/{name}" for name in self._termination_names] - names += [f"Episode_Termination/{self._time_limit}"] if self._time_limit is not None else [] - names += [f"Metrics/{name}" for name in self._metrics] - names += list(self._tasks) self._log_names = names - self._log_values = torch.zeros(len(names), device=self.device) - self.extras["log"] = dict(zip(names, self._log_values.clone())) + self._last_episodes = torch.zeros(n, len(columns), device=device) + self._log_ratios = None + if ratios: + done, ran = zip(*ratios) + logged = [k for k in range(len(columns)) if k not in ran] + self._log_ratios = tuple(torch.tensor(k, device=device) for k in (done, ran, logged)) + if columns: + ended = self._ended if self.cfg.episode_budget is not None else transition.done + last = argument(self._last_episodes, wp.array2d(dtype=wp.float32)) + code.world( + *summed, + f"if {argument(ended, wp.array(dtype=wp.bool))}[world]:", + *(f" {last}[world, {k}] = {column}" for k, column in enumerate(columns)), + *restarted, + ) + self._log_kernels = code.steps() + self.extras["log"] = self._episode_log() @property def max_episode_length(self) -> int | float: @@ -626,7 +677,7 @@ def reset(self, seed: int | None = None, options: dict[str, Any] | None = None) def step(self, action: torch.Tensor) -> VecEnvStepReturn: """Apply the actions, step the physics, evaluate the MDP, reset the worlds that ended, and observe.""" self._step_or_replay(action) - self.extras["log"] = dict(zip(self._log_names, self._log_values.clone())) + self.extras["log"] = self._episode_log() self.obs_buf = _clone(self.observations) transition = self.transition @@ -733,52 +784,24 @@ def _spend_episode_budget(self) -> None: self._resets.torch.copy_(restarted) def _after_evaluate(self) -> None: - """Keep the recorded quantities of the worlds that ended, and whether they timed out, before their reset.""" - # With an episode budget, only the episodes of active worlds count, and only some of them restart. + """Spend the episode budget, and keep the logged values of the episodes that ended, before their reset.""" if self.cfg.episode_budget is not None: self._spend_episode_budget() - done = self._ended if self.cfg.episode_budget is not None else self.transition.done.torch - for value, last, _ in self._metrics.values(): - torch.where(done, value, last, out=last) - if self._tasks: - done_tasks = torch.stack(list(self._tasks.values()), 1) - torch.where(done[:, None], done_tasks, self._last_done, out=self._last_done) - if self._task_runs is not None: - runs = torch.stack(self._task_runs, 1) - torch.where(done[:, None], runs, self._last_runs, out=self._last_runs) - if self._time_limit is not None: - timed_out = self.state.episode_length.torch >= self.max_episode_length - torch.where(done, timed_out, self._last_time_outs, out=self._last_time_outs) - self._log_episodes() - - def _log_episodes(self) -> None: - """Add the step's term rewards to the episode sums, and write the averages over the worlds' last finished - episodes to the values that ``extras["log"]`` holds. Part of the captured step.""" - transition = self.transition - ended = (self._ended if self.cfg.episode_budget is not None else transition.done.torch)[:, None] - self._episode_rewards += transition.reward_terms.torch - - torch.where(ended, self._episode_rewards, self._last_episode_rewards, out=self._last_episode_rewards) - terminations = transition.termination_terms.torch.float() - torch.where(ended, terminations, self._last_terminations, out=self._last_terminations) - self._episode_rewards.masked_fill_(ended, 0.0) - - values = [ - self._last_episode_rewards.sum(dim=0) - / (self._active_worlds[mdp2.Phase.REWARDS] * self.max_episode_length_s) - ] - values.append(self._last_terminations.sum(dim=0) / self._active_worlds[mdp2.Phase.TERMINATIONS]) - if self._time_limit is not None: - values.append(self._last_time_outs.float().mean()[None]) - # A quantity that only some worlds compute is averaged over them. - values += [last[worlds].mean()[None] for _, last, worlds in self._metrics.values()] - if self._tasks and self._task_runs is None and self._task_members is None: - values.append(self._last_done.mean(dim=0)) # Every world ran every task - elif self._tasks: - # Each task is averaged over the worlds that ran it: of the world configs that have it, that drew it. - runs = self._last_runs if self._task_members is None else self._last_runs * self._task_members - values.append((self._last_done * runs).sum(dim=0) / runs.sum(dim=0).clamp(min=1.0)) - torch.cat(values, out=self._log_values) + for kernel in self._log_kernels: + kernel(None) + + def step_buffers(self) -> dict[str, torch.Tensor]: + return {"episode_rewards": self._episode_rewards, "last_episodes": self._last_episodes} + + def _episode_log(self) -> dict[str, torch.Tensor]: + """Return the logs of the worlds' last finished episodes, a new tensor per step, as learners keep the logs of + the steps of a rollout.""" + values = self._last_episodes.sum(dim=0) + if self._log_ratios is not None: + done, ran, logged = self._log_ratios + values[done] /= values[ran].clamp(min=1.0) + values = values[logged] + return dict(zip(self._log_names, values)) def _terminations(task: mdp2.TaskCfg) -> list[tuple[str, Any]]: diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_verify.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_verify.py index 1419013c2d2f..6552179099e0 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_verify.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_verify.py @@ -98,6 +98,7 @@ def _rollout(env_type: type[MDP2Env], cfg: MDP2EnvCfg, num_steps: int, physics: for key, values in env.state.arrays.items(): if isinstance(key, mdp2.FieldSelector) and key.entity == "progress": named[str(key)] = values.torch + named |= env.step_buffers() steps = [] for _ in range(num_steps): actions = 2.0 * torch.rand(env.num_envs, env.mdp.action_dim, device=env.device, generator=generator) - 1.0 diff --git a/source/isaaclab_experimental/test/envs/test_mdp2_env.py b/source/isaaclab_experimental/test/envs/test_mdp2_env.py index 4d47d2926eaa..701e4db7f990 100644 --- a/source/isaaclab_experimental/test/envs/test_mdp2_env.py +++ b/source/isaaclab_experimental/test/envs/test_mdp2_env.py @@ -389,8 +389,10 @@ def test_env_splits_the_worlds_between_tasks_and_logs_terms_where_they_run(task_ "steps": observation, } without_alive = replace(cfg.task, rewards={**cfg.task.rewards, "alive": None}) + # A logged quantity of one task only, averaged over its worlds. + alive = replace(cfg.task, quantities={**cfg.task.quantities, "alive_steps": mdp2.Quantity(step_count, record=True)}) worlds = None if task_worlds is None else dict(zip(("alive", "still"), task_worlds)) - cfg.task = mdp2.split(alive=cfg.task, still=without_alive, worlds=worlds) + cfg.task = mdp2.split(alive=alive, still=without_alive, worlds=worlds) env = MDP2RLEnv(cfg) try: # Even shares, or the given number of worlds per task. @@ -407,6 +409,8 @@ def test_env_splits_the_worlds_between_tasks_and_logs_terms_where_they_run(task_ assert extras["log"]["Episode_Reward/alive"].item() == pytest.approx(1.0) # The episodes ended at their last step, not at the restart of the next one. assert extras["log"]["Metrics/steps"].item() == env.max_episode_length - 1 + assert extras["log"]["Metrics/alive_steps"].item() == pytest.approx(env.max_episode_length - 1) + assert env.is_captured finally: env.close() From 67b1fb6cc15ef266deeba12cb42e6a2845bd2053 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Fri, 20 Nov 2026 13:56:20 -0800 Subject: [PATCH 32/49] Mark the network actuators as not capturable ActuatorNetMLP and ActuatorNetLSTM inherited capturable from DCMotor, but the MLP assigns its histories anew at every step, which a replayed graph cannot follow. Also move the docstring of IdealPDActuator.cfg back to its attribute. --- source/isaaclab/changelog.d/mdp2-part2.added.rst | 3 ++- source/isaaclab/isaaclab/actuators/actuator_net.py | 6 +++++- source/isaaclab/isaaclab/actuators/actuator_pd.py | 2 +- source/isaaclab/test/actuators/test_actuator_collection.py | 6 +++++- 4 files changed, 13 insertions(+), 4 deletions(-) diff --git a/source/isaaclab/changelog.d/mdp2-part2.added.rst b/source/isaaclab/changelog.d/mdp2-part2.added.rst index 30f229fa2228..7ef72572f22a 100644 --- a/source/isaaclab/changelog.d/mdp2-part2.added.rst +++ b/source/isaaclab/changelog.d/mdp2-part2.added.rst @@ -1,6 +1,7 @@ * Added :attr:`~isaaclab.actuators.ActuatorBase.capturable`, which says whether a CUDA graph can replay an actuator's compute and masked reset with Torch work inside it. Delayed PD actuators qualify: their masked resets draw delays - from a device stream, which a replayed graph advances. + from a device stream, which a replayed graph advances. The network actuators, which subclass a capturable motor + model, are not capturable. * Added :meth:`~isaaclab.physics.PhysicsManager.supports_step_capture` and :meth:`~isaaclab.physics.PhysicsManager.capture`, with which environments that replay their steps as CUDA graphs record them as the physics backend records its own step, and :meth:`~isaaclab.sim.SimulationContext.after_replay`, diff --git a/source/isaaclab/isaaclab/actuators/actuator_net.py b/source/isaaclab/isaaclab/actuators/actuator_net.py index 70f4120c8eba..590b66443fcc 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_net.py +++ b/source/isaaclab/isaaclab/actuators/actuator_net.py @@ -15,7 +15,7 @@ from __future__ import annotations from collections.abc import Sequence -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, ClassVar import torch import warp as wp @@ -44,6 +44,8 @@ class ActuatorNetLSTM(DCMotor): cfg: ActuatorNetLSTMCfg """The configuration of the actuator model.""" + capturable: ClassVar[bool] = False # Not checked in replayed graphs, so not inherited from DCMotor + def __init__(self, cfg: ActuatorNetLSTMCfg, *args, **kwargs): super().__init__(cfg, *args, **kwargs) @@ -122,6 +124,8 @@ class ActuatorNetMLP(DCMotor): cfg: ActuatorNetMLPCfg """The configuration of the actuator model.""" + capturable: ClassVar[bool] = False # The histories are assigned anew at every step, which a graph cannot follow + def __init__(self, cfg: ActuatorNetMLPCfg, *args, **kwargs): super().__init__(cfg, *args, **kwargs) diff --git a/source/isaaclab/isaaclab/actuators/actuator_pd.py b/source/isaaclab/isaaclab/actuators/actuator_pd.py index f8fac3c6ca5c..ab80e060e03e 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_pd.py +++ b/source/isaaclab/isaaclab/actuators/actuator_pd.py @@ -266,9 +266,9 @@ class IdealPDActuator(ActuatorBase): """ cfg: IdealPDActuatorCfg + """The configuration for the actuator model.""" capturable: ClassVar[bool] = True - """The configuration for the actuator model.""" actuator_effort_limit: torch.Tensor """Actuator-model effort clipping limit [N or N·m, depending on joint type]. diff --git a/source/isaaclab/test/actuators/test_actuator_collection.py b/source/isaaclab/test/actuators/test_actuator_collection.py index 95b89dd49e49..09c2aaaea2da 100644 --- a/source/isaaclab/test/actuators/test_actuator_collection.py +++ b/source/isaaclab/test/actuators/test_actuator_collection.py @@ -20,6 +20,8 @@ from isaaclab.actuators import ( ActuatorCollection, ActuatorControl, + ActuatorNetLSTM, + ActuatorNetMLP, DCMotor, DCMotorCfg, DelayedPDActuatorCfg, @@ -912,13 +914,15 @@ def test_write_command_mask_uses_full_sized_value(command_name): @pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA graphs need a GPU") def test_masked_resets_of_delayed_actuators_draw_new_delays_when_a_graph_replays_them(): - """Delayed actuators are capturable: a mask reset draws its delays on the device, so each replay draws anew.""" + """Delayed actuators are capturable: a mask reset draws its delays on the device, so each replay draws anew. The + network actuators, which subclass a capturable motor model, keep histories that a graph cannot follow.""" device = "cuda:0" control = FakeActuatorControl(num_envs=64, device=device) cfg = DelayedPDActuatorCfg(joint_names_expr=[".*"], stiffness=1.0, damping=0.0, min_delay=0, max_delay=3) collection = ActuatorCollection({"delayed": cfg}, control) actuator = collection["delayed"] assert type(actuator).capturable + assert not ActuatorNetMLP.capturable and not ActuatorNetLSTM.capturable env_mask = wp.ones(64, dtype=wp.bool, device=device) collection.reset(env_mask=env_mask) # Loads the kernels # Torch joins the capture on Warp's stream, with memory of its own, as environments that replay steps do. From 9cfdb3e72e7eee08027c73827a52d1ee8aae7158 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Fri, 20 Nov 2026 13:56:35 -0800 Subject: [PATCH 33/49] Tune MDP2 values without undoing other writes, and carry tuned values over task updates A reset that applied one tuned value copied every tunable from its pending copy, undoing what events had written since. Each tuned value now has its own pending bit, and a tuning for this step drops the one waiting for the reset. A reward that world configs define differently is tuned in each of its columns. migrate carries over the values declared Tunable, with what waits for the reset, and takes other weights and params from the new task, running the init hooks of uses whose params changed. update_task keeps the reward sums of ongoing episodes, and refuses to go on without truncating under an episode budget. A choice with all weights zero is an error, and a start event of a task that always runs runs at every reset, so that a part with start events runs alone. --- docs/source/experimental-features/mdp2.rst | 18 ++--- .../changelog.d/mdp2-part2.added.rst | 12 ++-- .../changelog.d/mdp2-part2.changed.rst | 8 ++- .../isaaclab_experimental/envs/mdp2_env.py | 18 ++++- .../isaaclab_experimental/mdp2/builder.py | 20 +++--- .../isaaclab_experimental/mdp2/compiled.py | 9 +-- .../isaaclab_experimental/mdp2/config.py | 11 +-- .../isaaclab_experimental/mdp2/plan.py | 2 +- .../isaaclab_experimental/mdp2/runtime.py | 67 +++++++++++++------ .../mdp2/torch_backend.py | 18 ++--- .../mdp2/warp_backend.py | 39 +++++------ .../test/envs/test_mdp2_env.py | 28 ++++++-- .../test/mdp2/test_mdp2.py | 24 ++++--- 13 files changed, 170 insertions(+), 104 deletions(-) diff --git a/docs/source/experimental-features/mdp2.rst b/docs/source/experimental-features/mdp2.rst index e6566dc65cbe..92d0c0840846 100644 --- a/docs/source/experimental-features/mdp2.rst +++ b/docs/source/experimental-features/mdp2.rst @@ -145,7 +145,7 @@ one: ran when the step started, and its observations the one that runs after it. Starting restarts their state, timers, commands, and observation histories. Quantities are measurements: they run in every step, and only restart. Reset and startup events set up whole episodes, so they run at every reset; ``EventMode.START`` events run when their - task starts, at the reset or during the episode. Uses that the tasks define alike, but for their names, run as one + task starts, at the reset or during the episode, and at every reset for a task that always runs. Uses that the tasks define alike, but for their names, run as one while any of these tasks runs, so their state and histories carry on; a use of all of them is one of the sequence. - **Repeats.** ``repeat=True`` counts a task's completions as ``mdp2.progress..count``, such as the drops of an object: once done, it restarts, with its subtasks and uses, when its completion no longer holds. @@ -281,11 +281,12 @@ The values and structure of a task can change while it runs, at the cost of what rewards = {"stand_still": mdp2.Reward(..., when=mdp2.commands.standing)} # Only where the mode command says so env.update_task(new_task) # Recompile on the same scene, keep the state -- **Runtime values.** A param or reward weight declared :class:`~isaaclab_experimental.mdp2.Tunable` is a field of - one value per world, ``mdp2.tunable(use, name)``, which ``wp.func`` s take as their world's value and other terms - and events may read and write, such as a curriculum. :meth:`~isaaclab_experimental.envs.MDP2Env.tune` changes it - in place while graphs replay, at each world's next reset by default, so that no episode mixes two values; each - world counts its tunings in ``state.revision``, which episode records hold. Tasks without tunable values compile +- **Runtime values.** A param declared :class:`~isaaclab_experimental.mdp2.Tunable` is a field of one value per + world, ``mdp2.tunable(use, name)``, which ``wp.func`` s take as their world's value and other terms and events may + read and write, such as a curriculum; a tunable reward weight is the reward's column of ``state.reward_weights``. + :meth:`~isaaclab_experimental.envs.MDP2Env.tune` changes either in place while graphs replay, at each world's next + reset by default, so that no episode mixes two values, and leaves the other values alone; each world counts the + tunings that took effect in ``state.revision``, which episode records hold. Tasks without tunable values compile to the same kernels. - **Switches.** ``when`` on a reward, termination, observation, command, or interval event runs it where a field was positive at the start of the step, and restarts it where it turns on; ``when=mdp2.Tunable(True)`` is a switch per @@ -300,8 +301,9 @@ The values and structure of a task can change while it runs, at the cost of what steps, such as an embedded whole-body controller that writes joint targets; the default applies it before every physics step. Tasks of a sequence may take actions of their own. - **New structure.** :meth:`~isaaclab_experimental.envs.MDP2Env.update_task` builds another task on the same scene - and carries over, with :func:`~isaaclab_experimental.mdp2.migrate`, the state, random streams, and reward weights - of the uses that both have; it truncates the episodes by default, and the next step compiles and captures anew. + and carries over, with :func:`~isaaclab_experimental.mdp2.migrate`, the state, random streams, and tunable values + of the uses that both have, while other weights and params are the new task's; it truncates the episodes by + default, and the next step compiles and captures anew. Measured on Go2 at 4096 worlds (MDP time per step, physics replaced by nothing): the plain task 81 µs, every reward weight and tracking width tunable 81 µs, all rewards switched 86 µs, the rewards in two stages of a sequence 103 µs. diff --git a/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst index dbd2464c5bf1..1e870d14714b 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst @@ -34,8 +34,9 @@ * Added runtime values to MDP2: a param or reward weight declared :class:`~isaaclab_experimental.mdp2.Tunable` holds one value per world, which :func:`~isaaclab_experimental.mdp2.tune` and :meth:`~isaaclab_experimental.envs.MDP2Env.tune` change at each world's next reset or from the next step, while - captured steps keep replaying. Terms read it as a field, :func:`~isaaclab_experimental.mdp2.tunable`, and each world - counts the tunings it applied, recorded as ``revision``. + captured steps keep replaying, leaving the other values as they are. Terms read a param as a field, + :func:`~isaaclab_experimental.mdp2.tunable`, and each world counts the tunings that took effect, recorded as + ``revision``. * Added ``when`` to MDP2 term uses: a reward, termination, observation, command, or interval event runs only in the worlds where a field, such as a mode command, was positive at the start of the step, and restarts its state, timer, command, and history where it turns on. ``when=mdp2.Tunable(True)`` is a switch per world that @@ -58,11 +59,12 @@ * Added :func:`~isaaclab_experimental.mdp2.rename`, which binds a part of a task to other scene entities, so that a part can run twice, such as two arms. Uses of subtasks that run together get columns of their own, named with the subtask's name, as in ``left.joint_pos``; uses of subtasks that take turns share the columns of their name. -* Added start events to MDP2, ``EventMode.START``: an event of a task of a sequence or a choice, or of a task that - repeats, writes the scene when its task starts, at the reset or during the episode, where the scene commits it. +* Added start events to MDP2, ``EventMode.START``: an event writes the scene when its task starts, at the reset or, + for a task of a sequence or a choice, or one that repeats, during the episode, where the scene commits it. * Added :meth:`~isaaclab_experimental.envs.MDP2Env.update_task`, which replaces the task of a running environment on the same scene, such as with a reward added, and :func:`~isaaclab_experimental.mdp2.migrate`, which carries over the - state, random streams, and reward weights of the uses that both tasks have. + state, random streams, and tunable values of the uses that both tasks have; other reward weights and params are the + new task's. * Added variations to the MDP2 library, :func:`~isaaclab_experimental.mdp2.mdp.variation`: a reset event that draws a value per world, such as how far a drawer is open, writes it to a scene field, and records it per episode, drawn :class:`~isaaclab_experimental.mdp2.mdp.Uniform` (in a tunable range), from a diff --git a/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst b/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst index 6288197027b0..74ec9fdbac9d 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst @@ -24,5 +24,9 @@ step steps between the MDP's graphs. Replayed steps now count their physics steps and advance the simulation time. * Changed ``MDP2EnvCfg.verify_capture`` on physics without a reproducible mode to check the MDP alone, with the physics step replaced by nothing, bitwise, instead of comparing to a relative tolerance. -* Changed :class:`~isaaclab_experimental.envs.MDP2Env` to render only the cameras that some term of the task reads, - and to compute the averages of ``extras["log"]`` inside the captured step. +* Changed :class:`~isaaclab_experimental.envs.MDP2Env` to render only the cameras that some term of the task reads. +* Changed :class:`~isaaclab_experimental.envs.MDP2RLEnv` to keep its episode statistics in one generated kernel + inside the captured step, instead of about 15 Torch operations per step, and to sum them once per step for + ``extras["log"]``: about 15 to 35 µs less per step at 4,096 worlds. Without a time limit, rewards are logged per + second of each episode rather than as zero, and a choice's tasks are averaged over the finished episodes that drew + them. diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py index 3a4748cd4fb8..0a75064bc4e9 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py @@ -217,10 +217,16 @@ def update_task(self, task: mdp2.TaskCfg, truncate: bool = True) -> None: """Replace the task by another on the same scene, such as with a reward added or removed, and keep running. The state of the uses that both tasks have carries over, see :func:`~isaaclab_experimental.mdp2.migrate`: term - state, timers, histories, commands, progress, tunable values, random streams, and reward weights. With + state, timers, histories, commands, progress, random streams, and tunable values; other reward weights and + params are the new task's. With ``truncate``, every world starts a new episode, so that no episode mixes two tasks; otherwise episodes go on. The next step captures its graphs again, which compiles the kernels of a new task once, in about a second. + With an episode budget, the new task starts a new evaluation, so it truncates the episodes. """ + if not truncate and self.cfg.episode_budget is not None: + raise ValueError( + "With an episode budget, a new task starts a new evaluation: update it with truncate=True." + ) self._build(task, previous=(self.mdp, self.state)) self.cfg.task = task self._bind() @@ -501,6 +507,7 @@ class MDP2RLEnv(MDP2Env, gym.Env): def __init__(self, cfg: MDP2RLEnvCfg, render_mode: str | None = None, **kwargs: Any) -> None: self.final_observations = cfg.compute_final_obs self._budgeted = cfg.episode_budget is not None + self._episode_rewards: torch.Tensor | None = None # Set by _bind super().__init__(cfg) self.render_mode = render_mode self.metadata = {**self.metadata, "render_fps": 1 / self.step_dt} @@ -547,7 +554,14 @@ def _bind_logs(self) -> None: quantity, and whether each task with a completion was done, averaged over the worlds that ran the task.""" n, device, transition = self.num_envs, self.device, self.transition code = Fusion("mdp2_episode_log", n, device) - self._episode_rewards = torch.zeros(n, len(self._reward_names), device=device) + # The episodes that go on after a task update keep the sums of the rewards that both tasks have. + previous = {} if self._episode_rewards is None else dict(zip(self._summed, self._episode_rewards.T)) + self._summed = list(self._reward_names) + self._episode_rewards = ( + torch.stack([previous.get(name, torch.zeros(n, device=device)) for name in self._summed], dim=1) + if self._summed + else torch.zeros(n, 0, device=device) + ) def argument(tensor: torch.Tensor | ProxyArray, annotation: Any) -> str: array = tensor.warp if isinstance(tensor, ProxyArray) else wp.from_torch(tensor, dtype=annotation.dtype) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py index 1c6e07c3831a..bbf0397812ae 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py @@ -650,7 +650,9 @@ def _compile_task(self, path: str, tasks: dict[str, tuple[TaskCfg, bool]], conte chances = task.weights or dict.fromkeys(task.subtasks, 1.0) if set(chances) != set(task.subtasks) or not all(chance >= 0 for chance in chances.values()): errors.append(f"{name}: a choice needs a weight of at least 0 for each of {list(task.subtasks)}.") - elif sum(chances.values()) > 0: + elif sum(chances.values()) <= 0: + errors.append(f"{name}: a choice needs some weight above 0, to draw one of {list(task.subtasks)}.") + else: weights = tuple(chances[child] / sum(chances.values()) for child in task.subtasks) if task.require is not None and not 1 <= task.require <= len(completes): errors.append(f"{name}: require must be between 1 and {len(completes)}, the subtasks with a completion.") @@ -1011,18 +1013,12 @@ def _allocate_columns( def _check_event(entry: ScheduleEntry, errors: list[str]) -> None: - """Record why an event cannot be compiled: its interval, its commit, or a start event of a task that never - starts during an episode.""" + """Record why an event cannot be compiled: its interval or its commit.""" cfg = entry.cfg if (cfg.mode is EventMode.INTERVAL) != (cfg.interval_range_s is not None): errors.append(f"{entry}: interval events need an interval_range_s, and other events cannot have one.") if cfg.commit is True and cfg.mode not in (EventMode.RESET, EventMode.START): errors.append(f"{entry}: only reset and start events can ask for a commit.") - if cfg.mode is EventMode.START and entry.stage is None: - errors.append( - f"{entry}: a start event runs when its task starts, so it belongs to a task of a sequence or a choice," - " or to one that repeats." - ) def _check_action(entry: ScheduleEntry, output_shape: tuple[int, ...] | None, errors: list[str]) -> None: @@ -1089,10 +1085,14 @@ def _tuned_values(ops: Mapping[Phase, tuple], errors: list[str]) -> tuple[TunedV TunedValue(f"{op.use}.{name}", op.inputs[name], dtype=_tunable_layout(op.name, name, default, []).dtype) for name, default in op.tunables.items() ] - values += [TunedValue(f"{op.use}.weight", "reward_weights", op.index)] if op.tunable_weight else [] + values += [TunedValue(f"{op.use}.weight", "reward_weights", (op.index,))] if op.tunable_weight else [] values += [TunedValue(f"{op.use}.when", op.when, dtype=wp.bool)] if op.when_default is not None else [] for value in values: - if tuned.setdefault(value.path, value) != value: + known = tuned.setdefault(value.path, value) + if known.columns != value.columns and known.key == value.key == "reward_weights": + # A reward that world configs define differently has a column in each. + tuned[value.path] = replace(known, columns=tuple(dict.fromkeys(known.columns + value.columns))) + elif known != value: errors.append(f"The world configs tune '{value.path}' differently: tune it in all or none of them.") return tuple(tuned.values()) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py index aa9e31f5fb80..252e572b194e 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py @@ -79,8 +79,9 @@ class MDPState: task's ``done`` held), ``entered`` (whether a task of a sequence started at this step), and, for a task that repeats, ``spent`` (done, and its completion still holds) and ``restarted`` (it restarted at this step); - ``mdp2.tunable(use, name)``: the value of a tunable param per world, and, for an MDP with tunable values, - ``("pending", key)``: the values tuned for the next reset of each array, ``"pending"``: the worlds that have - them, and ``"revision"``: the number of tunings applied in each world, see :func:`~.tune`. + ``("pending", key)``: the values tuned for the next reset of each array, ``"pending"``: which values wait in + each world, a bit per value of :attr:`MDP.tuned` in ``int32`` words, ``(num_worlds, words)``, and + ``"revision"``: the number of times tunings took effect in each world, see :func:`~.tune`. """ arrays: dict[Hashable, ProxyArray] @@ -438,8 +439,8 @@ def state(self, scene_data: SceneData, seed: int = 0) -> MDPState: weights[config.worlds.start : config.worlds.stop] = [op.weights[index] for op in self.ops[Phase.REWARDS]] arrays["reward_weights"] = ProxyArray(wp.array(weights, dtype=wp.float32, device=self.device)) if self.tuned: - # Values tuned for the next reset wait in a copy of their array, in the worlds marked pending. - arrays["pending"] = self._zeros(self.num_worlds, dtype=wp.bool) + # Values tuned for the next reset wait in a copy of their array, in the worlds whose bit of it is set. + arrays["pending"] = self._zeros(self.num_worlds, (len(self.tuned) + 31) // 32, dtype=wp.int32) arrays["revision"] = self._zeros(self.num_worlds, dtype=wp.int32) for key in dict.fromkeys(value.key for value in self.tuned): arrays["pending", key] = ProxyArray(wp.clone(arrays[key].warp)) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py index 475b7055e15e..d03490f5d8e1 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py @@ -142,18 +142,19 @@ class Tunable: """A value that may change while the MDP runs, per world: a param, as in ``params={"std": mdp2.Tunable(0.5)}``, or a reward's ``weight``. - It is a field of the MDP, ``mdp2.tunable("rewards.track", "std")``, of one value per world: ``float32``, + A param is a field of the MDP, ``mdp2.tunable("rewards.track", "std")``, of one value per world: ``float32``, ``int32``, ``bool``, or, for a tuple of numbers, a ``float32`` vector. A ``wp.func`` takes it as a param, of its - world's value; Python hooks get the array, which Torch hooks get as a ``(num_worlds,)`` tensor per number. - :func:`~.tune` changes it, at each world's next reset by default, so that no episode mixes two values; other terms - may read it and events may write it, such as a curriculum. + world's value; Python hooks get the array, which Torch hooks get as a ``(num_worlds,)`` tensor per number. A + weight is the reward's column of :attr:`~.MDPState.reward_weights`. :func:`~.tune` changes either, at each + world's next reset by default, so that no episode mixes two values; other terms may read a param and events may + write it, such as a curriculum. """ default: float | int | bool | tuple[float, ...] def tunable(use: str, name: str) -> FieldSelector: - """Select the tunable value ``name`` of a use, a param or ``weight``, as in ``tunable("rewards.track", "std")``.""" + """Select the tunable param ``name`` of a use, or its tunable ``when``: ``tunable("rewards.track", "std")``.""" return FieldSelector("tunables", f"{use}.{name}", scene=False) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py index 8cffe1bd6446..a20b8354f008 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py @@ -177,7 +177,7 @@ class TunedValue: path: str # Name of the use and of the value, such as "rewards.track.std" or "rewards.track.weight" key: Hashable # Key of its array in MDPState.arrays: mdp2.tunable(use, name), or "reward_weights" - column: int | None = None # Reward weights: the column of the reward + columns: tuple[int, ...] = () # Reward weights: the columns of the reward, one per world config that differs dtype: Any = None # Element type of a tunable param's field diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/runtime.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/runtime.py index 205ad80c32be..23a7f719f643 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/runtime.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/runtime.py @@ -11,6 +11,7 @@ from __future__ import annotations +import itertools from collections.abc import Callable, Sequence from typing import Any, Literal @@ -20,7 +21,7 @@ from isaaclab.utils.warp import ProxyArray from .compiled import MDP, MDPState, Transition -from .config import FieldSelector, Phase +from .config import FieldSelector from .eager import call_init from .plan import Call @@ -108,33 +109,36 @@ def tune( selected = torch.zeros(mdp.num_worlds, dtype=torch.bool, device=mdp.device) selected[slice(None) if worlds is None else worlds] = True - # The value waits in the pending copy; a tuning for this step also writes it in place, and keeps the copy equal. - destinations = [state.arrays["pending", target.key].torch] - destinations += [state.arrays[target.key].torch] if at == "step" else [] - for destination in destinations: - values = destination if target.column is None else destination[:, target.column] + # A tuning for the next reset waits in the pending copy, and sets the value's bit; a tuning for this step writes + # the value in place, and drops what waited for the next reset, as it is the newer tuning. + destination = state.arrays[("pending", target.key) if at == "reset" else target.key].torch + for values in [destination[:, column] for column in target.columns] or [destination]: values[selected] = torch.as_tensor(value, dtype=values.dtype, device=mdp.device) - if at == "step": - state.arrays["revision"].torch.add_(selected.int()) + word, bit = divmod(mdp.tuned.index(target), 32) + flags = state.arrays["pending"].torch[:, word] + if at == "reset": + flags.bitwise_or_(selected.int() << bit) else: - state.arrays["pending"].torch.logical_or_(selected) + flags.bitwise_and_(~(selected.int() << bit)) + state.arrays["revision"].torch.add_(selected.int()) -_CARRIED = ("timer", "history", "on", "entered", "pending") +_CARRIED = ("timer", "history", "on", "entered") """Kinds of the arrays of single ops that :func:`migrate` carries over, by the first part of their keys.""" def migrate(previous: MDP, previous_state: MDPState, mdp: MDP, state: MDPState) -> None: """Carry the state of an MDP over to another built on the same scene, such as for an edited task. - Every array of the MDP that both key alike and shape alike carries over: the state, timers, histories, and - tunable values of the uses that both have, the commands, quantities, and progress, the episode lengths, and the - last actions. So do the random streams of the uses that both have, and the reward weights of the rewards. The init - hooks of the uses that the previous MDP did not have run, as at startup. + Every array of the MDP that both key alike and shape alike carries over: the state, timers, and histories of the + uses that both have, the commands, quantities, and progress, the episode lengths, and the last actions. So do the + random streams of the uses that both have, and the values that both declare :class:`~.config.Tunable`, with those + waiting for the next reset, as they may have been tuned; other reward weights and params are the new task's. The + init hooks of the uses that the previous MDP did not have, or whose params changed, run, as at startup. """ for key, array in state.arrays.items(): - carried = isinstance(key, FieldSelector) and not key.scene - carried |= key in ("revision", "pending") or isinstance(key, tuple) and key[0] in _CARRIED + carried = isinstance(key, FieldSelector) and not key.scene or key == "revision" + carried |= isinstance(key, tuple) and key[0] in _CARRIED old = previous_state.arrays.get(key) if ( carried @@ -147,12 +151,31 @@ def migrate(previous: MDP, previous_state: MDPState, mdp: MDP, state: MDPState) for row, name in enumerate(mdp.streams): if name in previous.streams: state.rng.torch[row] = previous_state.rng.torch[previous.streams.index(name)] - rewards = [op.name for op in previous.ops[Phase.REWARDS]] - for column, op in enumerate(mdp.ops[Phase.REWARDS]): - if op.name in rewards: - state.reward_weights.torch[:, column] = previous_state.reward_weights.torch[:, rewards.index(op.name)] + _migrate_tuned(previous, previous_state, mdp, state) - uses = {op.use for op in previous.term_ops} + params = {op.use: op.params for op in previous.term_ops} for op in mdp.term_ops: - if op.init is not None and op.use not in uses: + if op.init is not None and params.get(op.use) != op.params: call_init(mdp, op, state, op.init) + + +def _migrate_tuned(previous: MDP, previous_state: MDPState, mdp: MDP, state: MDPState) -> None: + """Carry over the tunable values that both MDPs have: the reward weights, which the arrays did not, and what waits + for the next reset, with the bits that mark it.""" + indices = {value.path: index for index, value in enumerate(previous.tuned)} + for index, value in enumerate(mdp.tuned): + if value.path not in indices: + continue + old_index = indices[value.path] + old = previous.tuned[old_index] + for key in [value.key, ("pending", value.key)] if value.columns else [("pending", value.key)]: + source, target = previous_state.arrays[key].torch, state.arrays[key].torch + if value.columns: # By column, as rewards may have moved + for column, old_column in zip(value.columns, itertools.cycle(old.columns)): + target[:, column] = source[:, old_column] + elif source.shape == target.shape and source.dtype == target.dtype: + target.copy_(source) + word, bit = divmod(index, 32) + old_word, old_bit = divmod(old_index, 32) + waits = (previous_state.arrays["pending"].torch[:, old_word] >> old_bit) & 1 + state.arrays["pending"].torch[:, word].bitwise_or_(waits << bit) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py index 85f9f6301728..975b2634a0d1 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py @@ -317,16 +317,18 @@ def _switch(ops: tuple[TermOp, ...], state: MDPState, mask: torch.Tensor | None) def _apply_tuned(tuned: tuple[TunedValue, ...], state: MDPState, mask: torch.Tensor) -> None: - """Apply the values tuned for the next reset in the reset worlds that have them, and count the tuning.""" + """Apply, in the reset worlds, each value tuned for the next reset where it waits, and count the tunings that + took effect.""" pending = state.arrays["pending"].torch - applied = pending & mask - for value in tuned: + for index, value in enumerate(tuned): + word, bit = divmod(index, 32) + waits = ((pending[:, word] >> bit) & 1).bool() & mask live, waiting = state.arrays[value.key].torch, state.arrays["pending", value.key].torch - if value.column is not None: - live, waiting = live[:, value.column], waiting[:, value.column] - live.copy_(torch.where(applied.view(-1, *[1] * (live.ndim - 1)), waiting, live)) - state.arrays["revision"].torch.add_(applied.int()) - pending.logical_and_(~applied) + pairs = [(live[:, column], waiting[:, column]) for column in value.columns] or [(live, waiting)] + for live, waiting in pairs: + live.copy_(torch.where(waits.view(-1, *[1] * (live.ndim - 1)), waiting, live)) + state.arrays["revision"].torch.add_(((pending != 0).any(dim=1) & mask).int()) + pending.masked_fill_(mask[:, None], 0) def _clear(mdp: MDP, slot: ObservationSlot, call: Call, stepping: bool) -> None: diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py index 2034baea5137..b485dfb4ed4b 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py @@ -931,31 +931,24 @@ def _switch(code: Fusion, ops: tuple[TermOp, ...], stepping: bool) -> None: def _apply_tuned(code: Fusion, tuned: tuple[TunedValue, ...]) -> None: - """Apply the values tuned for the next reset in the reset worlds that have them, and count the tuning.""" - pending = _array(code, "pending", wp.array(dtype=wp.bool)) + """Apply, in the reset worlds, each value tuned for the next reset where it waits, and count the tunings that + took effect.""" + pending = _array(code, "pending", wp.array2d(dtype=wp.int32)) revision = _array(code, "revision", wp.array(dtype=wp.int32)) - lines, writes = [], ["pending", "revision"] - for value in tuned: - if value.column is None: - annotation = wp.array(dtype=value.dtype) - live, waiting, index = ( - _array(code, value.key, annotation), - _array(code, ("pending", value.key), annotation), - "world", - ) - else: - annotation = wp.array2d(dtype=wp.float32) + lines, writes = ["tuned_any = False"], ["pending", "revision"] + for word in range(0, len(tuned), 32): + lines += [f"tuned_bits = {pending}[world, {word // 32}]", "if tuned_bits != 0:"] + for bit, value in enumerate(tuned[word : word + 32]): + if value.columns: + annotation, indices = wp.array2d(dtype=wp.float32), [f"world, {column}" for column in value.columns] + else: + annotation, indices = wp.array(dtype=value.dtype), ["world"] live, waiting = _array(code, value.key, annotation), _array(code, ("pending", value.key), annotation) - index = f"world, {value.column}" - lines.append(f"{live}[{index}] = {waiting}[{index}]") - writes.append(value.key) - code.world( - f"if {pending}[world]:", - *(f" {line}" for line in lines), - f" {revision}[world] = {revision}[world] + 1", - f" {pending}[world] = False", - writes=writes, - ) + lines.append(f" if ((tuned_bits >> {bit}) & 1) != 0:") + lines += [f" {live}[{index}] = {waiting}[{index}]" for index in indices] + writes.append(value.key) + lines += [f" {pending}[world, {word // 32}] = 0", " tuned_any = True"] + code.world(*lines, "if tuned_any:", f" {revision}[world] = {revision}[world] + 1", writes=writes) def _clear(code: Fusion, mdp: MDP, slot: ObservationSlot, stepping: bool) -> None: diff --git a/source/isaaclab_experimental/test/envs/test_mdp2_env.py b/source/isaaclab_experimental/test/envs/test_mdp2_env.py index 701e4db7f990..8fe46e4fcc60 100644 --- a/source/isaaclab_experimental/test/envs/test_mdp2_env.py +++ b/source/isaaclab_experimental/test/envs/test_mdp2_env.py @@ -832,10 +832,13 @@ def test_optix_cameras_render_between_the_graphs_of_a_step(): def test_update_task_keeps_the_state_of_the_uses_both_tasks_have(): - """Replacing the task on a running environment keeps the state, random streams, and reward weights of the uses - that both tasks have, truncates the episodes, and replays the new task's step as a graph.""" + """Replacing the task on a running environment keeps the state, random streams, and tuned values of the uses + that both tasks have, takes the other weights from the new task, truncates the episodes, and replays the new + task's step as a graph. Without truncating, the episodes go on with the reward sums of the rewards both have.""" cfg = cartpole_cfg() cfg.task.quantities = {"lifetime": mdp2.Quantity(lifetime_steps)} + alive = replace(cfg.task.rewards["alive"], weight=mdp2.Tunable(1.0)) + cfg.task = replace(cfg.task, rewards={**cfg.task.rewards, "alive": alive}) env = MDP2RLEnv(cfg) try: env.reset() @@ -843,18 +846,25 @@ def test_update_task_keeps_the_state_of_the_uses_both_tasks_have(): for _ in range(3): env.step(actions) assert env.is_captured and env.num_graphs == 1 - env.state.reward_weights.torch[:, 0] = 7.0 # Changed at runtime: kept + env.tune("rewards.alive.weight", 7.0, at="step") streams = {name: env.state.rng.torch[row].clone() for row, name in enumerate(env.mdp.streams)} task = replace( cfg.task, - rewards={**cfg.task.rewards, "upright": mdp2.Reward(mdp.is_alive, inputs={"terminated": mdp2.terminated})}, + rewards={ + **cfg.task.rewards, + "terminating": replace(cfg.task.rewards["terminating"], weight=-5.0), + "upright": mdp2.Reward(mdp.is_alive, inputs={"terminated": mdp2.terminated}), + }, ) env.update_task(task) + rewards = [op.name for op in env.mdp.ops[mdp2.Phase.REWARDS]] lifetime = env.state.arrays[mdp2.term_state("quantities.lifetime", "steps")].torch assert (lifetime == 3.0).all() and (env.episode_length_buf == 0).all() - assert (env.state.reward_weights.torch[:, 0] == 7.0).all() - assert env.state.reward_weights.torch[:, -1].tolist() == [1.0] * NUM_ENVS + weights = env.state.reward_weights.torch + assert (weights[:, rewards.index("rewards.alive")] == 7.0).all() # Tuned: kept + assert (weights[:, rewards.index("rewards.terminating")] == -5.0).all() # Edited: the new task's + assert weights[:, rewards.index("rewards.upright")].tolist() == [1.0] * NUM_ENVS for name, values in streams.items(): # The reset that truncated the episodes advanced every stream once. rng.advance(values[None]) @@ -864,6 +874,12 @@ def test_update_task_keeps_the_state_of_the_uses_both_tasks_have(): env.step(actions) assert env.is_captured and env.num_graphs == 1 and "Episode_Reward/upright" in extras["log"] assert (lifetime == 5.0).all() + + sums = env.step_buffers()["episode_rewards"].clone() + env.update_task(cfg.task, truncate=False) + kept = [rewards.index(op.name) for op in env.mdp.ops[mdp2.Phase.REWARDS]] + assert (env.episode_length_buf == 2).all() + assert torch.equal(env.step_buffers()["episode_rewards"], sums[:, kept]) finally: env.close() diff --git a/source/isaaclab_experimental/test/mdp2/test_mdp2.py b/source/isaaclab_experimental/test/mdp2/test_mdp2.py index 7c724568ca9e..92986380cbbd 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2.py @@ -1941,13 +1941,15 @@ def test_splits_divide_the_same_worlds_and_may_be_steps_of_a_sequence(): def test_task_trees_report_errors(): - """A sequence task without a completion and a task with subtasks and a done are errors.""" + """A sequence task without a completion, a task with subtasks and a done, and a choice that cannot draw are + errors.""" schema = PointMassScene(num_worlds=2, joint_names=("a",)).schema quantities = mdp2.TaskCfg(quantities=above("a")) milestone = mdp2.Milestone(mdp2.quantities.a) cases = [ (mdp2.sequence(first=milestone, second=mdp2.TaskCfg()), "needs a completion"), (mdp2.TaskCfg(done=mdp2.quantities.a, subtasks={"first": milestone}), "cannot have a done"), + (mdp2.choice(weights={"first": 0.0, "second": 0.0}, first=milestone, second=milestone), "weight above 0"), ] for task, message in cases: with pytest.raises(ValueError, match=message): @@ -1983,7 +1985,8 @@ def outside_torch(joint_pos, *, bounds): def test_tunable_values_change_at_resets_or_steps_while_graphs_replay(): """Tunable params and weights hold one value per world, which terms read as their world's value and observations as a field. A tuning waits for each world's next reset, or applies at the next step, also between graph replays, - and every world counts the tunings it applied.""" + and every world counts the tunings it applied. A value that a term writes is not undone by a reset that applies + another.""" task = mdp2.TaskCfg( observations={ "policy": { @@ -2005,6 +2008,7 @@ def test_tunable_values_change_at_resets_or_steps_while_graphs_replay(): }, ) num_worlds = 5 # Not the number of joints, so that a wrong broadcast cannot go unseen + bounds = mdp2.tunable("terminations.outside", "bounds") def run(backend: str, capture: bool) -> list[dict[str, torch.Tensor]]: scene = PointMassScene(num_worlds=num_worlds, joint_names=("a", "b", "c"), device=DEVICE) @@ -2044,10 +2048,14 @@ def run(backend: str, capture: bool) -> list[dict[str, torch.Tensor]]: "terminated": transition.terminated.torch.clone(), "policy": transition.observations["policy"].torch.clone(), "revision": state.revision.torch.clone(), + "bounds": state.arrays[bounds].torch.clone(), } ) for path, value, worlds, at in tunings.get(step, []): mdp2.tune(mdp, state, path, value, worlds, at) + if step == 1: + # As an event or a curriculum would: world 1 also has a tuned gain waiting for its reset. + state.arrays[bounds].torch[1] = torch.tensor([-2.0, 2.0], device=DEVICE) return history runs = [run(backend, capture) for backend in ("torch", "warp") for capture in (False, True)] @@ -2063,6 +2071,7 @@ def run(backend: str, capture: bool) -> list[dict[str, torch.Tensor]]: # World 1 reset after step 2 and took the gain of 2; world 3 still waits for its reset. assert rewards[2] == pytest.approx([1.0, 2.0, 1.0, 1.0, 1.0]) assert history[2]["policy"][:, 0].tolist() == [1.0, 2.0, 1.0, 1.0, 1.0] + assert history[2]["bounds"][1].tolist() == [-2.0, 2.0] assert rewards[3] == pytest.approx([1.0, 4.0, 3.0, 4.0, 5.0]) # Weights of 1 to 5 from the next step assert history[4]["terminated"].tolist() == [False] * 4 + [True] # World 4's tighter bounds assert history[4]["revision"].tolist() == [1, 2, 1, 1, 2] @@ -2364,8 +2373,8 @@ def count_successes_warp(world: int, done: wp.array(dtype=wp.bool), total: wp.ar def test_start_events_write_the_scene_when_their_task_starts(): """A start event writes the scene when its task starts: at the reset for the first task of a sequence, at the step - the next one starts for the others, whose worlds the scene then commits. Reset events see the progress of the - episode that ended.""" + the next one starts for the others, whose worlds the scene then commits, and at every reset for a task that always + runs, so that a part can run alone. Reset events see the progress of the episode that ended.""" push = mdp2.Event(push_by_adding_velocity, outputs={"joint_vel": robot.joint_vel}, mode=mdp2.EventMode.START) velocity = mdp2.Observation(joint_vel, inputs={"joint_vel": robot.joint_vel}) task = mdp2.compose( @@ -2397,10 +2406,9 @@ def test_start_events_write_the_scene_when_their_task_starts(): env_reset(mdp, state, scene, transition.observations, everywhere) assert state.arrays[mdp2.term_state("events.successes", "total")].torch.tolist() == [1.0, 0.0] - builder = mdp2.MDPBuilder(scene.schema) - builder.add_task(mdp2.compose(mdp2.TaskCfg(quantities=above("a")), mdp2.TaskCfg(events={"push": push}))) - with pytest.raises(ValueError, match="a start event runs when its task starts"): - builder.validate() + alone = mdp2.TaskCfg(events={"push": push}, observations={"policy": {"velocity": velocity}}) + history = check_progress(mdp2.compose(mdp2.TaskCfg(quantities=above("a")), alone), [[0.0], [1.0]]) + assert [step["policy"][0].tolist() for step in history] == [[1.0], [1.0]] # Pushed at the reset only def test_variations_draw_record_and_replay_values(): From 4279f31585c01b2a3f444ea93f67b1ca33f7b46a Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Fri, 20 Nov 2026 13:59:15 -0800 Subject: [PATCH 34/49] Keep MDP2 episode statistics a row per column, so writes and sums are contiguous --- .../isaaclab_experimental/envs/mdp2_env.py | 25 ++++++++++--------- .../test/envs/test_mdp2_env.py | 2 +- 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py index 0a75064bc4e9..29865e691bb1 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py @@ -555,13 +555,14 @@ def _bind_logs(self) -> None: n, device, transition = self.num_envs, self.device, self.transition code = Fusion("mdp2_episode_log", n, device) # The episodes that go on after a task update keep the sums of the rewards that both tasks have. - previous = {} if self._episode_rewards is None else dict(zip(self._summed, self._episode_rewards.T)) + # Both buffers hold a row per column and a column per world, so that the kernel writes and the sum over the + # worlds reads contiguous memory. + previous = {} if self._episode_rewards is None else dict(zip(self._summed, self._episode_rewards)) self._summed = list(self._reward_names) - self._episode_rewards = ( - torch.stack([previous.get(name, torch.zeros(n, device=device)) for name in self._summed], dim=1) - if self._summed - else torch.zeros(n, 0, device=device) - ) + self._episode_rewards = torch.zeros(len(self._summed), n, device=device) + for row, name in enumerate(self._summed): + if name in previous: + self._episode_rewards[row] = previous[name] def argument(tensor: torch.Tensor | ProxyArray, annotation: Any) -> str: array = tensor.warp if isinstance(tensor, ProxyArray) else wp.from_torch(tensor, dtype=annotation.dtype) @@ -596,9 +597,9 @@ def member(worlds: Sequence[int] | None) -> str: seconds = f"(float({length}[world]) * {float(self.step_dt)!r})" for k, op in enumerate(rewards): names.append(f"Episode_Reward/{self._reward_names[k]}") - summed.append(f"{sums}[world, {k}] = {sums}[world, {k}] + {terms}[world, {k}]") - restarted.append(f" {sums}[world, {k}] = 0.0") - columns.append(f"{sums}[world, {k}] * {share(op.worlds)!r} / {seconds}") + summed.append(f"{sums}[{k}, world] = {sums}[{k}, world] + {terms}[world, {k}]") + restarted.append(f" {sums}[{k}, world] = 0.0") + columns.append(f"{sums}[{k}, world] * {share(op.worlds)!r} / {seconds}") terminations = self.mdp.ops[mdp2.Phase.TERMINATIONS] if terminations: flags = argument(transition.termination_terms, wp.array2d(dtype=wp.bool)) @@ -636,7 +637,7 @@ def member(worlds: Sequence[int] | None) -> str: columns.append(f"wp.where({member(worlds)} and {done}[world], {share(worlds)!r}, 0.0)") self._log_names = names - self._last_episodes = torch.zeros(n, len(columns), device=device) + self._last_episodes = torch.zeros(len(columns), n, device=device) self._log_ratios = None if ratios: done, ran = zip(*ratios) @@ -648,7 +649,7 @@ def member(worlds: Sequence[int] | None) -> str: code.world( *summed, f"if {argument(ended, wp.array(dtype=wp.bool))}[world]:", - *(f" {last}[world, {k}] = {column}" for k, column in enumerate(columns)), + *(f" {last}[{k}, world] = {column}" for k, column in enumerate(columns)), *restarted, ) self._log_kernels = code.steps() @@ -810,7 +811,7 @@ def step_buffers(self) -> dict[str, torch.Tensor]: def _episode_log(self) -> dict[str, torch.Tensor]: """Return the logs of the worlds' last finished episodes, a new tensor per step, as learners keep the logs of the steps of a rollout.""" - values = self._last_episodes.sum(dim=0) + values = self._last_episodes.sum(dim=1) if self._log_ratios is not None: done, ran, logged = self._log_ratios values[done] /= values[ran].clamp(min=1.0) diff --git a/source/isaaclab_experimental/test/envs/test_mdp2_env.py b/source/isaaclab_experimental/test/envs/test_mdp2_env.py index 8fe46e4fcc60..6e5db55aa81b 100644 --- a/source/isaaclab_experimental/test/envs/test_mdp2_env.py +++ b/source/isaaclab_experimental/test/envs/test_mdp2_env.py @@ -879,7 +879,7 @@ def test_update_task_keeps_the_state_of_the_uses_both_tasks_have(): env.update_task(cfg.task, truncate=False) kept = [rewards.index(op.name) for op in env.mdp.ops[mdp2.Phase.REWARDS]] assert (env.episode_length_buf == 2).all() - assert torch.equal(env.step_buffers()["episode_rewards"], sums[:, kept]) + assert torch.equal(env.step_buffers()["episode_rewards"], sums[kept]) finally: env.close() From d2bd603c8745f4b969faadde3fbe29709bca8b53 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Fri, 20 Nov 2026 14:13:30 -0800 Subject: [PATCH 35/49] Update the measured costs of MDP2 runtime values and stages --- docs/source/experimental-features/mdp2.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/source/experimental-features/mdp2.rst b/docs/source/experimental-features/mdp2.rst index 92d0c0840846..f3a42eea9135 100644 --- a/docs/source/experimental-features/mdp2.rst +++ b/docs/source/experimental-features/mdp2.rst @@ -305,8 +305,8 @@ The values and structure of a task can change while it runs, at the cost of what of the uses that both have, while other weights and params are the new task's; it truncates the episodes by default, and the next step compiles and captures anew. -Measured on Go2 at 4096 worlds (MDP time per step, physics replaced by nothing): the plain task 81 µs, every reward -weight and tracking width tunable 81 µs, all rewards switched 86 µs, the rewards in two stages of a sequence 103 µs. +Measured on Go2 at 4096 worlds (MDP time per step, physics replaced by nothing): the plain task 64 µs, every reward +weight and tracking width tunable 64 µs, all rewards switched 72 µs, the rewards in two stages of a sequence 74 µs. Porting from Arena From bc218ca6d54beef0ae159425ca515314c2fac741 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Sun, 22 Nov 2026 09:56:51 -0800 Subject: [PATCH 36/49] Keep earlier inertia changes when randomizing masses The mass event stored the inertias in its init, which runs before any startup event, so it scaled the inertias from before an inertia event that ran first and dropped its offset. The Kuka Allegro lift adds 0.01 to the objects' inertia this way; MDP2 objects kept about 1/45 of MDP1's inertia and spun freely when touched. Co-Authored-By: Claude Opus 5.5 --- .../changelog.d/mdp2-mass-inertia.fixed.rst | 3 +++ .../isaaclab_experimental/mdp2/mdp/events.py | 15 +++++++++++++-- .../test/envs/test_mdp2_terms.py | 19 ++++++++++++++++--- 3 files changed, 32 insertions(+), 5 deletions(-) create mode 100644 source/isaaclab_experimental/changelog.d/mdp2-mass-inertia.fixed.rst diff --git a/source/isaaclab_experimental/changelog.d/mdp2-mass-inertia.fixed.rst b/source/isaaclab_experimental/changelog.d/mdp2-mass-inertia.fixed.rst new file mode 100644 index 000000000000..17e0b5d2965b --- /dev/null +++ b/source/isaaclab_experimental/changelog.d/mdp2-mass-inertia.fixed.rst @@ -0,0 +1,3 @@ +* Fixed :data:`~isaaclab_experimental.mdp2.mdp.randomize_rigid_body_mass` scaling the inertias from before the + startup events: an inertia offset from :data:`~isaaclab_experimental.mdp2.mdp.randomize_rigid_body_inertia` that + ran before it was lost. It now scales the inertias at its first call, as MDP1 does. diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/events.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/events.py index e92d46eec929..611654554b4f 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/events.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/events.py @@ -334,6 +334,7 @@ def _randomize_rigid_body_mass( body_ids: torch.Tensor, mass: torch.Tensor, inertia: torch.Tensor, + captured: torch.Tensor, *, mass_distribution_params: tuple[float, float], operation: str, @@ -342,6 +343,11 @@ def _randomize_rigid_body_mass( ) -> None: body_ids = body_ids.long() env_ids = mask.nonzero().squeeze(-1) + # The inertias to scale are those at the event's first call, as in MDP1, so that an event before it at startup, + # such as an inertia offset, stays in them. + first = env_ids[captured[env_ids] == 0.0] + inertia[first] = asset.data.body_inertia.torch[first][:, body_ids] + captured[first] = 1.0 samples = _samples(rng, mass_distribution_params, distribution, (len(body_ids),))[env_ids] masses = mass[env_ids] @@ -355,12 +361,17 @@ def _randomize_rigid_body_mass( randomize_rigid_body_mass = Term( - torch=_randomize_rigid_body_mass, init=_init_body_defaults, state=_BODY_DEFAULTS, random=True, capturable=False + torch=_randomize_rigid_body_mass, + init=_init_body_defaults, + state={**_BODY_DEFAULTS, "captured": State(persistent=True)}, + random=True, + capturable=False, ) """Add to, scale, or set (``operation`` ``"add"``, ``"scale"``, ``"abs"``) the masses of the ``body_ids`` bodies. Samples come from ``mass_distribution_params`` with ``distribution`` ``"uniform"``, ``"log_uniform"``, or -``"gaussian"``, and apply to the masses at startup. With ``recompute_inertia``, the inertias scale with the masses. +``"gaussian"``, and apply to the masses at startup. With ``recompute_inertia``, the inertias scale with the masses, +from the inertias at the event's first call. """ diff --git a/source/isaaclab_experimental/test/envs/test_mdp2_terms.py b/source/isaaclab_experimental/test/envs/test_mdp2_terms.py index 8185323ef140..4c9a117a38ad 100644 --- a/source/isaaclab_experimental/test/envs/test_mdp2_terms.py +++ b/source/isaaclab_experimental/test/envs/test_mdp2_terms.py @@ -359,9 +359,15 @@ def test_heading_command_steers_towards_its_heading(env: MDP2Env): def test_model_events_randomize_the_startup_model_alike_on_both_backends(env: MDP2Env): """Events scale the base mass and offset its center of mass by the same samples on both backends, each time from - the values at startup, so resets do not compound them.""" + the values at startup, so resets do not compound them. The inertia scales with the mass and keeps the offset that + the inertia event before it adds, as in MDP1.""" base = robot.bodies("base") events = { + "base_inertia": mdp2.Event( + mdp.randomize_rigid_body_inertia, + inputs={"asset": robot, "body_ids": base}, + params={"inertia_distribution_params": (0.01, 0.01), "operation": "add"}, + ), "base_mass": mdp2.Event( mdp.randomize_rigid_body_mass, inputs={"asset": robot, "body_ids": base}, @@ -394,7 +400,11 @@ def test_model_events_randomize_the_startup_model_alike_on_both_backends(env: MD mdp2.startup(model, state) for _ in range(2): mdp2.reset(model, state, ProxyArray(wp.ones(NUM_ENVS, dtype=wp.bool, device=env.device))) - results[backend] = (data.body_mass.torch.clone(), data.body_com_pos_b.torch.clone()) + results[backend] = ( + data.body_mass.torch.clone(), + data.body_com_pos_b.torch.clone(), + data.body_inertia.torch.clone(), + ) env.scene["robot"].set_masses_index(masses=default_mass) env.scene["robot"].set_inertias_index(inertias=default_inertia) env.scene["robot"].set_coms_index(coms=default_com) @@ -402,9 +412,12 @@ def test_model_events_randomize_the_startup_model_alike_on_both_backends(env: MD for value, expected in zip(results["warp"], results["torch"]): torch.testing.assert_close(value, expected) - mass, com = results["warp"] + mass, com, inertia = results["warp"] ratio = mass[:, base_id] / default_mass[:, base_id] assert ((ratio >= 0.8 - 1e-6) & (ratio <= 1.25 + 1e-6)).all() and ratio.std() > 0.0 + expected = default_inertia[:, base_id].clone() + expected[:, [0, 4, 8]] += 0.01 + torch.testing.assert_close(inertia[:, base_id], expected * ratio[:, None]) assert torch.equal(mass[:, base_id + 1 :], default_mass[:, base_id + 1 :]) offset = com[:, base_id] - default_com[:, base_id] assert (offset[:, :2].abs() <= 0.05 + 1e-6).all() and (offset[:, 2].abs() <= 0.01 + 1e-6).all() From a0c4fd3f807225b9978f114031f1fde25f902803 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Mon, 23 Nov 2026 21:00:16 -0800 Subject: [PATCH 37/49] Address review comments on MDP2 Part 2 - Compile the commands and quantities that action terms read before the actions, and pass the MDP to the access tracking of Python action hooks. - Rename the entity of subset selectors in rename(). - Run the start events of a task that runs alone after its progress restarts, as those of a sequence's first task. - Rerun the init hooks of migrated uses per use and params, so that the ops of a use that world configs give different params keep their state. - Lay out the history of separate observations, and give observation spaces to boolean and other floating-point types. - Build and validate an updated task before the environment takes it. - Keep the Replay counter modulo its table, make `when` keyword-only, keep plain observation groups plain in play mode, allocate less in the Torch backend, and share the simulation's pause handling with after_replay. - Document that update_task does not run startup events, and that start events within an episode commit after the step. - Tests: capture rows only on CUDA, count physics-rate applications, redraw a choice, compare delayed actuators eager and captured, and check that eager physics advances. --- docs/source/experimental-features/mdp2.rst | 2 +- .../isaaclab/sim/simulation_context.py | 23 ++-- .../isaaclab_experimental/envs/mdp2_env.py | 32 +++--- .../envs/mdp2_env_cfg.py | 2 +- .../envs/mdp2_scene_data.py | 3 - .../isaaclab_experimental/mdp2/builder.py | 28 ++++- .../isaaclab_experimental/mdp2/config.py | 11 +- .../mdp2/mdp/variations.py | 3 +- .../isaaclab_experimental/mdp2/plan.py | 7 +- .../isaaclab_experimental/mdp2/runtime.py | 5 +- .../mdp2/torch_backend.py | 15 +-- .../mdp2/warp_backend.py | 6 +- .../test/envs/test_mdp2_env.py | 34 ++++-- .../test/mdp2/test_mdp2.py | 106 +++++++++++++++--- .../test/mdp2/test_lift_kuka_allegro.py | 5 +- 15 files changed, 201 insertions(+), 81 deletions(-) diff --git a/docs/source/experimental-features/mdp2.rst b/docs/source/experimental-features/mdp2.rst index f3a42eea9135..c64ac57cedb1 100644 --- a/docs/source/experimental-features/mdp2.rst +++ b/docs/source/experimental-features/mdp2.rst @@ -101,7 +101,7 @@ weights, in different worlds of one scene; :func:`~isaaclab_experimental.mdp2.sp Subtasks and progress --------------------- -A task may say when it is ``done``, and hold named subtasks, which are tasks too. Three functions combine tasks into +A task may say when it is ``done``, and hold named subtasks, which are tasks too. Four functions combine tasks into one: .. list-table:: diff --git a/source/isaaclab/isaaclab/sim/simulation_context.py b/source/isaaclab/isaaclab/sim/simulation_context.py index 9623c07fa633..8193fbca4351 100644 --- a/source/isaaclab/isaaclab/sim/simulation_context.py +++ b/source/isaaclab/isaaclab/sim/simulation_context.py @@ -590,6 +590,14 @@ def step(self, render: bool = True) -> None: """ # Block while the GUI timeline is paused so the entire training loop freezes. # See: https://github.com/isaac-sim/IsaacLab/issues/4279 + self._wait_while_paused() + self._physics_step_count += 1 + self.backend_manager.step() + if render and self.is_rendering: + self.render() + + def _wait_while_paused(self) -> None: + """Block while the timeline or a visualizer is paused, keeping the visualizers responsive.""" self.backend_manager.wait_for_playing() visualizers_to_remove = [] for viz in self._visualizers: @@ -600,10 +608,6 @@ def step(self, render: bool = True) -> None: logger.error("Error stepping visualizer '%s': %s", type(viz).__name__, exc) visualizers_to_remove.append(viz) self._remove_visualizers(visualizers_to_remove) - self._physics_step_count += 1 - self.backend_manager.step() - if render and self.is_rendering: - self.render() def after_replay(self, num_steps: int) -> None: """Do the host work of :meth:`step` for steps whose device work a CUDA graph replayed. @@ -615,16 +619,7 @@ def after_replay(self, num_steps: int) -> None: Args: num_steps: Calls of :meth:`step` that the graph recorded. """ - self.backend_manager.wait_for_playing() - visualizers_to_remove = [] - for viz in self._visualizers: - try: - while viz.is_training_paused() and viz.is_running(): - viz.step(0.0) - except Exception as exc: - logger.error("Error stepping visualizer '%s': %s", type(viz).__name__, exc) - visualizers_to_remove.append(viz) - self._remove_visualizers(visualizers_to_remove) + self._wait_while_paused() self._physics_step_count += num_steps self.backend_manager.after_replay(num_steps) diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py index 29865e691bb1..c89efa368d91 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py @@ -128,7 +128,7 @@ def _build(self, task: mdp2.TaskCfg, previous: tuple[mdp2.MDP, mdp2.MDPState] | with one, carry its state over, see :func:`~isaaclab_experimental.mdp2.migrate`.""" builder = mdp2.MDPBuilder(self.scene_data.schema) builder.add_task(task) - self.mdp = builder.finalize( + mdp = builder.finalize( device=self.device, backend=self.cfg.backend, diagnostics=self.diagnostics, @@ -137,21 +137,23 @@ def _build(self, task: mdp2.TaskCfg, previous: tuple[mdp2.MDP, mdp2.MDPState] | # The cameras that some term reads render, once per control step. read = { selector.name if isinstance(selector, mdp2.Entity) else selector.entity - for op in self.mdp.term_ops + for op in mdp.term_ops for selector in op.inputs.values() } - self._cameras = [camera for name, camera in self._all_cameras.items() if name in read] + cameras = [camera for name, camera in self._all_cameras.items() if name in read] + if cameras and Step.RENDER not in self.cfg.step: + raise ValueError("The task reads cameras, so MDP2EnvCfg.step must hold Step.RENDER, or they never render.") + state = mdp.state(self.scene_data, seed=self._seed) + if previous is not None: + mdp2.migrate(*previous, mdp, state) + # The environment takes the new MDP only once it is valid, so that a rejected task leaves it as it was. + self.mdp, self.state, self._cameras = mdp, state, cameras # OptiX refits its acceleration structures on the host, which a CUDA graph cannot record: such cameras render # between the graphs of a step. self._render_capturable = not any( isinstance(camera.cfg.renderer_cfg, NewtonOptixRendererCfg) for camera in self._cameras ) - if self._cameras and Step.RENDER not in self.cfg.step: - raise ValueError("The task reads cameras, so MDP2EnvCfg.step must hold Step.RENDER, or they never render.") - self.state = self.mdp.state(self.scene_data, seed=self._seed) - if previous is not None: - mdp2.migrate(*previous, self.mdp, self.state) - else: + if previous is None: mdp2.startup(self.mdp, self.state) if self.mdp.startup_writes: # Startup events write scene fields in place, which the scene commits to the solver. @@ -221,6 +223,7 @@ def update_task(self, task: mdp2.TaskCfg, truncate: bool = True) -> None: params are the new task's. With ``truncate``, every world starts a new episode, so that no episode mixes two tasks; otherwise episodes go on. The next step captures its graphs again, which compiles the kernels of a new task once, in about a second. + Startup events run once, when the environment is created: those that the new task adds do not run. With an episode budget, the new task starts a new evaluation, so it truncates the episodes. """ if not truncate and self.cfg.episode_budget is not None: @@ -521,11 +524,14 @@ def _bind(self) -> None: self.extras["final_obs"] = self._views(self.transition.final_observations) spaces: dict[str, Any] = {} for buffer, (shape, dtype) in self.mdp.observation_layouts.items(): - if dtype is wp.float32: - space = gym.spaces.Box(low=-np.inf, high=np.inf, shape=shape) + numpy_dtype = np.dtype(wp.dtype_to_numpy(dtype)) + if numpy_dtype == np.bool_: + space = gym.spaces.Box(low=0, high=1, shape=shape, dtype=np.bool_) + elif np.issubdtype(numpy_dtype, np.floating): + space = gym.spaces.Box(low=-np.inf, high=np.inf, shape=shape, dtype=numpy_dtype) else: - info = np.iinfo(wp.dtype_to_numpy(dtype)) - space = gym.spaces.Box(low=info.min, high=info.max, shape=shape, dtype=wp.dtype_to_numpy(dtype)) + info = np.iinfo(numpy_dtype) + space = gym.spaces.Box(low=info.min, high=info.max, shape=shape, dtype=numpy_dtype) if "/" in buffer: group, term = buffer.split("/") spaces.setdefault(group, {})[term] = space diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env_cfg.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env_cfg.py index e37f042e19a7..3ab2d76f0fee 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env_cfg.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env_cfg.py @@ -113,6 +113,6 @@ def _without_observation_noise(task: TaskCfg) -> TaskCfg: for group, uses in task.observations.items(): terms, concatenate = group_terms(uses) terms = {name: use if use is None else replace(use, noise=None) for name, use in terms.items()} - observations[group] = ObservationGroup(terms=terms, concatenate=concatenate) + observations[group] = ObservationGroup(terms, concatenate) if isinstance(uses, ObservationGroup) else terms subtasks = {name: _without_observation_noise(subtask) for name, subtask in task.subtasks.items()} return replace(task, observations=observations, subtasks=subtasks) diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_scene_data.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_scene_data.py index dbefd9717b99..1c5fff5de6ec 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_scene_data.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_scene_data.py @@ -21,9 +21,6 @@ from isaaclab_experimental.mdp2 import EntitySchema, FieldSchema, FieldSelector, SceneSchema -"""Actuator configs whose actuators MDP2 can step and reset inside CUDA graphs. Matched exactly: subclasses, such as -delayed actuators, may draw from Torch's random generators on reset, which a replayed graph repeats.""" - class InteractiveSceneData: """Live views of the asset data of an :class:`InteractiveScene`, by scene entity name and field. diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py index bbf0397812ae..1a1c47eff34d 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py @@ -167,6 +167,7 @@ class CompileContext: modes: dict[str, TaskMode] = field(default_factory=dict) # How the subtasks of each task run, by path staged: dict[str, bool] = field(default_factory=dict) # Whether the uses of each task start during an episode renamed: dict[str, str] = field(default_factory=dict) # Uses merged into others, see _share_across_stages + compiled: set[tuple[str, ...]] = field(default_factory=set) # Uses compiled early, for the actions that read them class MDPBuilder: @@ -573,10 +574,26 @@ def _compile_actions( context.errors.append(f"Only one time limit is allowed, found {', '.join(map(str, time_limits))}.") time_limit = time_limits[0].cfg.episode_length_s if time_limits else None + # Action terms may read commands and quantities, whose uses compile first, with the uses that they read. + providers = {selector: entry for entry in schedule for selector in entry.provides} + + def compile_providers(entry: ScheduleEntry) -> None: + for selector in (*entry.reads, *([entry.when] if entry.when is not None else [])): + provider = providers.get(selector) + if provider is not None and provider.path not in context.compiled and provider.path != entry.path: + context.compiled.add(provider.path) + if last_action in provider.reads: + context.errors.append( + f"{entry}: an action cannot read '{selector}', which reads the last action." + ) + compile_providers(provider) + self._compile_term(provider, context) + for entry in schedule: if isinstance(entry.cfg, DirectAction): self._compile_action(entry, context) elif isinstance(entry.cfg, Action): + compile_providers(entry) self._compile_term(entry, context) return context, time_limit @@ -603,7 +620,11 @@ def _compile_schedule( return for entry in (entries[path] for path in order): - if entry.phase is not Phase.ACTIONS and not isinstance(entry.cfg, TimeLimit): + if ( + entry.phase is not Phase.ACTIONS + and not isinstance(entry.cfg, TimeLimit) + and entry.path not in context.compiled + ): self._compile_term(entry, context) # An offset may be a field of the MDP, such as a quantity, which exists once its use is compiled. @@ -866,6 +887,7 @@ def _compile_term(self, entry: ScheduleEntry, context: CompileContext) -> None: torch_hooks=context.backend is Backend.WARP and implementation is term.torch, init=term.init, commit=cfg.commit if isinstance(cfg, Event) else False, + start=isinstance(cfg, Event) and cfg.mode is EventMode.START, record=isinstance(cfg, Quantity) and cfg.record, columns=columns, slot=(entry.name or entry.path[-1]) if isinstance(cfg, Action) else "", @@ -1425,7 +1447,9 @@ def _allocate_slots( shapes = {(op.shape, op.dtype) for op in slot_ops} if len(shapes) > 1: errors.append(f"The observations '{buffer}' must have the same shape and type, got {shapes}.") - layouts[buffer] = (slot_ops[0].shape, slot_ops[0].dtype) + # Oldest first, as in a concatenated group. + history = slot_ops[0].observation.history_length + layouts[buffer] = ((history, *slot_ops[0].shape) if history else slot_ops[0].shape, slot_ops[0].dtype) for first, second in itertools.combinations(slot_ops, 2): if not _exclusive(first, second, modes): errors.append( diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py index d03490f5d8e1..98ca5af44939 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py @@ -181,7 +181,7 @@ class TermCfg: # Run only in the worlds where this field of one value per world is positive, taken at the start of each step: a # use that does not run outputs zero, and its state, timer, command, and history restart when it turns on. A # Tunable(True) is a switch per world, mdp2.tunable(use, "when"). Resets prepare the use in every world. - when: FieldSelector | Tunable | None = None + when: FieldSelector | Tunable | None = field(default=None, kw_only=True) @dataclass @@ -275,7 +275,8 @@ class Event(TermCfg): interval_range_s: tuple[float, float] | None = None # Seconds between interval events # Reset and start events: whether the scene commits the writes of the earlier events of the reset before it runs, # so that it reads what they changed. None infers it: before an event that reads a field derived from written - # ones, such as the body poses after joint writes. True always commits first, and False never does. + # ones, such as the body poses after joint writes. True always commits first, and False never does. Within an + # episode, the start events of a task that starts commit together after the step, as interval events do. commit: bool | None = None @property @@ -494,8 +495,10 @@ def rename(task: TaskCfg, **entities: str) -> TaskCfg: def _renamed(value: Any, entities: dict[str, str]) -> Any: """Return a copy of a config value with the scene entities of its selectors renamed; params and terms stay.""" - if isinstance(value, (FieldSelector, SubsetSelector)): - return dataclasses.replace(value, entity=entities.get(value.entity, value.entity)) if value.scene else value + if isinstance(value, SubsetSelector) or isinstance(value, FieldSelector) and value.scene: + return dataclasses.replace(value, entity=entities.get(value.entity, value.entity)) + if isinstance(value, FieldSelector): + return value if isinstance(value, Entity): return Entity(entities.get(value.name, value.name), value.scene) if value.scene else value if isinstance(value, dict): diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/variations.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/variations.py index 96338fc39085..f696387828f1 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/variations.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/variations.py @@ -173,7 +173,8 @@ def _replay_torch(mask, target, ids, value, row, table, taken): rows = (taken.long() + rank) % table.shape[0] row.copy_(torch.where(mask, rows.float(), row)) _write(target, ids, mask, table[rows], value) - taken.add_(mask.sum()) + # Modulo the table, so that the count stays exact in float32. + taken.copy_((taken + mask.sum()) % table.shape[0]) replay_variation = Term( diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py index a20b8354f008..e8583241baec 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py @@ -108,6 +108,7 @@ class TermOp: init: Callable | None = None # Eager ``fn(ctx, **params)`` that fills the state once, before the startup events # Reset events: whether the scene commits the earlier events' writes before it runs, None to infer it commit: bool | None = False + start: bool = False # Events: a start event, which runs once its task starts, after the progress restarts record: bool = False # Quantities: whether the environment records it at the end of every episode columns: slice | None = None # Actions: the columns of the action that the term takes worlds: tuple[int, ...] | None = None # Worlds where the op is active, None for every world @@ -375,13 +376,13 @@ def computed(phase_ops: tuple) -> list[Step]: starts = [Step(StepKind.START_TASKS, trees)] if any(node.staged for tree in trees for node in tree.nodes) else [] starts += [Step(StepKind.SWITCH, switched)] if switched else [] # Start events write the scene where their task starts; the others set up whole episodes. - start_events = [op for op in ops[Phase.RESET_EVENTS] if op.entry_key is not None] - reset_events = [op for op in ops[Phase.RESET_EVENTS] if op.entry_key is None] + start_events = [op for op in ops[Phase.RESET_EVENTS] if op.start or op.entry_key is not None] + reset_events = [op for op in ops[Phase.RESET_EVENTS] if not op.start and op.entry_key is None] if starts: scoped = [op for phase_ops in ops.values() for op in phase_ops if isinstance(op, TermOp) and op.entry_key] starts += [ *(Step(StepKind.RESET_TIMER, op, entry=True) for op in timed if op.entry_key), - *(Step(StepKind.COMPUTE, op, entry=True) for op in start_events), + *(Step(StepKind.COMPUTE, op, entry=True) for op in start_events if op.entry_key is not None), *(Step(StepKind.COMPUTE, op, entry=True) for op in scoped if op.phase is Phase.COMMANDS), *(Step(StepKind.RESET_STATE, op, entry=True) for op in stateful if op.entry_key), ] diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/runtime.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/runtime.py index 23a7f719f643..358055b15106 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/runtime.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/runtime.py @@ -153,9 +153,10 @@ def migrate(previous: MDP, previous_state: MDPState, mdp: MDP, state: MDPState) state.rng.torch[row] = previous_state.rng.torch[previous.streams.index(name)] _migrate_tuned(previous, previous_state, mdp, state) - params = {op.use: op.params for op in previous.term_ops} + # A use of several world configs has an op per params: one that the previous MDP had keeps its state. + uses = [(op.use, op.params) for op in previous.term_ops] for op in mdp.term_ops: - if op.init is not None and params.get(op.use) != op.params: + if op.init is not None and (op.use, op.params) not in uses: call_init(mdp, op, state, op.init) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py index 975b2634a0d1..7db9bfe4d5fc 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py @@ -78,13 +78,13 @@ def _store_actions(mdp: MDP, call: Call) -> None: others.""" call.state.actions.torch.copy_(call.actions.torch) for slot in (slot for slot in mdp.action_slots if slot.partial): - columns = torch.arange(slot.columns.start, slot.columns.stop, device=mdp.device) - covered = torch.zeros(mdp.num_worlds, len(columns), dtype=torch.bool, device=mdp.device) + columns = call.state.actions.torch[:, slot.columns] + covered = torch.zeros_like(columns, dtype=torch.bool) for op in slot.ops: - active = _active(op, call.state) - width = columns < op.columns.stop - covered |= width if active is None else active.torch[:, None] & width - call.state.actions.torch[:, slot.columns].masked_fill_(~covered, 0.0) + # An op takes the first columns of its slot. + active, width = _active(op, call.state), op.columns.stop - slot.columns.start + covered[:, :width] |= True if active is None else active.torch[:, None] + columns.masked_fill_(~covered, 0.0) def _begin_evaluate(mdp: MDP, call: Call) -> None: @@ -300,11 +300,12 @@ def _switch(ops: tuple[TermOp, ...], state: MDPState, mask: torch.Tensor | None) where any of them runs. Stepping (no mask) marks the worlds where it turned on; observing new episodes, in the masked worlds, marks none, since resets restarted them.""" for op in ops: - runs = torch.ones(state.episode_length.torch.shape, dtype=torch.bool, device=state.episode_length.torch.device) if op.stages: runs = torch.stack([state.arrays[progress_field(stage, "active")].torch for stage in op.stages]).any(0) elif op.scope_key is not None: runs = state.arrays[op.scope_key].torch + else: + runs = torch.ones_like(state.episode_length.torch, dtype=torch.bool) if op.when is not None: runs = runs & (state.arrays[op.when].torch > 0) on, entered = state.arrays[op.active_key].torch, state.arrays[op.entry_key].torch diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py index b485dfb4ed4b..5af6902d95b3 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py @@ -122,7 +122,7 @@ def rows(call: Call, selector: FieldSelector) -> wp.array: for step in steps: op = step.op if isinstance(op, TermOp): - _apply_action_term(code, op) + _apply_action_term(code, op, mdp) continue target = code.argument(op.target, wp.array2d(dtype=wp.float32), lambda call, op=op: rows(call, op.target)) index = "element" if op.subset is None else f"{_array(code, op.subset, wp.array(dtype=wp.int32))}[element]" @@ -159,7 +159,7 @@ def _store_actions(code: Fusion, mdp: MDP, actions: str) -> None: code.elements((mdp.action_dim,), *copy, writes=[last_action]) -def _apply_action_term(code: Fusion, op: TermOp) -> None: +def _apply_action_term(code: Fusion, op: TermOp, mdp: MDP) -> None: """Run an action term's compute hook, which writes its outputs from its columns of the action.""" if isinstance(op.compute, wp.Function): writes = [*op.writes, *(term_state(op.use, name) for name in op.state)] @@ -177,7 +177,7 @@ def run(call: Call) -> None: } op.compute(**hook_arguments(op.compute, arguments)) - code.call(run, op.capturable, *_accesses(op)) + code.call(run, op.capturable, *_accesses(op, mdp)) def _evaluate(mdp: MDP) -> tuple[Callable[[Call], None], ...]: diff --git a/source/isaaclab_experimental/test/envs/test_mdp2_env.py b/source/isaaclab_experimental/test/envs/test_mdp2_env.py index 6e5db55aa81b..acfb0e1d0044 100644 --- a/source/isaaclab_experimental/test/envs/test_mdp2_env.py +++ b/source/isaaclab_experimental/test/envs/test_mdp2_env.py @@ -885,17 +885,24 @@ def test_update_task_keeps_the_state_of_the_uses_both_tasks_have(): def test_delayed_actuators_run_in_captured_steps(): - """Delayed actuators, which Newton runs natively, replay in the step's graph.""" - cfg = cartpole_cfg() - delayed_cart(cfg) - env = MDP2RLEnv(cfg) - try: - env.reset() - for _ in range(3): - env.step(torch.zeros(NUM_ENVS, 1, device=env.device)) - assert env.is_captured and env.num_graphs == 1 - finally: - env.close() + """Delayed actuators, which Newton runs natively, replay in the step's graph: the cart follows changing actions + as it does stepping eagerly.""" + velocities = [] + for capture in (True, False): + cfg = cartpole_cfg() + cfg.capture = capture + delayed_cart(cfg) + env = MDP2RLEnv(cfg) + try: + env.reset(seed=0) + for step in range(6): + env.step(torch.full((NUM_ENVS, 1), (-1.0) ** step, device=env.device)) + velocities.append(env.scene["robot"].data.joint_vel.torch[:, 0].clone()) + assert env.is_captured == capture + finally: + env.close() + torch.testing.assert_close(torch.stack(velocities[:6]), torch.stack(velocities[6:])) + assert torch.stack(velocities).abs().amax() > 0.0 def test_physics_that_cannot_capture_its_step_steps_between_the_graphs(monkeypatch): @@ -911,11 +918,14 @@ def test_physics_that_cannot_capture_its_step_steps_between_the_graphs(monkeypat monkeypatch.setattr(manager, "capture", lambda fn: captures.append(fn) or capture(fn)) env._work = env._step_work() env.reset() - actions = torch.zeros(NUM_ENVS, 1, device=env.device) + actions = torch.ones(NUM_ENVS, 1, device=env.device) + joint_pos = env.scene["robot"].data.joint_pos.torch + start = joint_pos.clone() for _ in range(3): env.step(actions) # The physics steps eagerly, and the rest of the step replays as one graph after it. assert env.is_captured and env.num_graphs == 1 and len(captures) == 1 + assert (joint_pos[:, 0] != start[:, 0]).all() # The cart moved finally: env.close() diff --git a/source/isaaclab_experimental/test/mdp2/test_mdp2.py b/source/isaaclab_experimental/test/mdp2/test_mdp2.py index 92986380cbbd..e5211b434ddd 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2.py @@ -18,6 +18,8 @@ from isaaclab.utils.warp import ProxyArray DEVICE = "cuda:0" if torch.cuda.is_available() else "cpu" +# Captured runs replay CUDA graphs; on the CPU, CapturedMDP runs eagerly, which the eager rows already cover. +CAPTURES = (False, True) if torch.cuda.is_available() else (False,) pytestmark = pytest.mark.kitless @@ -877,7 +879,7 @@ def test_captured_mdp_replays_like_eager_calls(): Torch hooks inside the graphs of a Warp MDP.""" for backend, torch_hooks in (("torch", False), ("warp", False), ("warp", True)): runs = [] - for capture in (False, True): + for capture in CAPTURES: scene = PointMassScene(num_worlds=64, joint_names=("x", "y", "z"), device=DEVICE) mdp, state = make_task( scene, backend=backend, episode_length_s=0.2, random=True, host=True, torch_hooks=torch_hooks @@ -1603,7 +1605,8 @@ def image_scene(num_worlds: int) -> PointMassScene: def test_groups_that_are_not_concatenated_keep_each_term_shape_and_type(): - """A group that is not concatenated gives each term its own buffer, of the term's shape and element type.""" + """A group that is not concatenated gives each term its own buffer, of the term's shape and element type, with + its history first.""" camera = mdp2.Entity("camera") for backend in ("torch", "warp"): scene = image_scene(num_worlds=2) @@ -1614,6 +1617,7 @@ def test_groups_that_are_not_concatenated_keep_each_term_shape_and_type(): terms={ "rgb": mdp2.Observation(mdp2.mdp.image_rgb, inputs={"image": camera.rgb}), "joint_pos": mdp2.Observation(joint_pos, inputs={"joint_pos": robot.joint_pos}), + "history": mdp2.Observation(joint_pos, inputs={"joint_pos": robot.joint_pos}, history_length=2), }, concatenate=False, ), @@ -1630,7 +1634,9 @@ def test_groups_that_are_not_concatenated_keep_each_term_shape_and_type(): "policy": ((1,), wp.float32), "cameras/rgb": ((2, 3, 3), wp.uint8), "cameras/joint_pos": ((1,), wp.float32), + "cameras/history": ((2, 1), wp.float32), # Oldest first } + assert transition.observations["cameras/history"].torch.shape == (2, 2) rgb = transition.observations["cameras/rgb"].torch assert rgb.dtype == torch.uint8 assert torch.equal(rgb.view(2, 2, 3, 3), scene.data("camera", "rgb").torch) @@ -1725,7 +1731,7 @@ def check_progress(task: mdp2.TaskCfg, joint_values: list, joints: tuple = ()) - """Run a task on both backends, eagerly and captured, check that the four runs agree bitwise, and return one.""" runs = [] for backend in ("torch", "warp"): - for capture in (False, True) if torch.cuda.is_available() else (False,): + for capture in CAPTURES: runs.append(run_progress(task, joint_values, backend, capture, joints=joints)[2]) for run in runs[1:]: for expected, actual in zip(runs[0], run): @@ -2058,7 +2064,7 @@ def run(backend: str, capture: bool) -> list[dict[str, torch.Tensor]]: state.arrays[bounds].torch[1] = torch.tensor([-2.0, 2.0], device=DEVICE) return history - runs = [run(backend, capture) for backend in ("torch", "warp") for capture in (False, True)] + runs = [run(backend, capture) for backend in ("torch", "warp") for capture in CAPTURES] for other in runs[1:]: for expected, actual in zip(runs[0], other): for name in expected: @@ -2135,7 +2141,7 @@ def run(backend: str, capture: bool) -> list[dict[str, torch.Tensor]]: ) return history - runs = [run(backend, capture) for backend in ("torch", "warp") for capture in (False, True)] + runs = [run(backend, capture) for backend in ("torch", "warp") for capture in CAPTURES] for other in runs[1:]: for expected, actual in zip(runs[0], other): for name in expected: @@ -2237,7 +2243,7 @@ def run(backend: str, capture: bool) -> list[dict[str, torch.Tensor]]: history[-1]["mask"] = mdp.action_mask(state).clone() return history - runs = [run(backend, capture) for backend in ("torch", "warp") for capture in (False, True)] + runs = [run(backend, capture) for backend in ("torch", "warp") for capture in CAPTURES] for other in runs[1:]: for expected, actual in zip(runs[0], other): for name in expected: @@ -2284,7 +2290,7 @@ def test_actions_apply_once_per_control_step_or_before_every_physics_step(): } ) for backend in ("torch", "warp"): - for capture in (False, True): + for capture in CAPTURES: scene = PointMassScene(num_worlds=2, joint_names=("a", "b"), device=DEVICE) builder = mdp2.MDPBuilder(scene.schema) builder.add_task(task) @@ -2292,15 +2298,40 @@ def test_actions_apply_once_per_control_step_or_before_every_physics_step(): state, transition = mdp.state(scene), mdp.transition() actions = ProxyArray(wp.from_torch(torch.tensor([[1.0, 0.5], [2.0, 0.25]], device=DEVICE))) captured = mdp2.CapturedMDP(mdp, state, transition, actions, transition.done) if capture else None + target = scene.data("robot", "joint_effort_target").torch + tracked = 0 for _ in range(3): mdp2.process_actions(mdp, state, actions) if captured is None else captured.process_actions() for _ in range(scene.decimation): + target[:, 1] = 0.0 # Cleared after every physics step, so that each must apply it again mdp2.apply_actions(mdp, state, actions) if captured is None else captured.apply_actions() + tracked += target[:, 1].tolist() == [1.0, 0.5] calls = state.arrays[mdp2.term_state("actions.plan", "calls")].torch - assert calls.tolist() == [3.0, 3.0], (backend, capture) - target = scene.data("robot", "joint_effort_target").torch - assert target.tolist() == [[3.0, 1.0], [6.0, 0.5]] and torch.equal(state.actions.torch, actions.torch) - assert len(mdp.launches.process_actions) == 1 and len(mdp.plan.apply_actions) == 1 + assert calls.tolist() == [3.0, 3.0] and tracked == 3 * scene.decimation, (backend, capture) + assert target[:, 0].tolist() == [3.0, 6.0] and torch.equal(state.actions.torch, actions.torch) + + +def test_action_terms_read_quantities(): + """An action term reads the quantities of its task, here with Torch hooks only, which a Warp MDP also runs.""" + follow = mdp2.Term(torch=lambda action, offset, target: target.copy_(action + offset), shape=("worlds", "joints")) + task = mdp2.TaskCfg( + quantities={"position": mdp2.Quantity(joint_pos, inputs={"joint_pos": robot.joint_pos})}, + actions={ + "follow": mdp2.Action( + follow, inputs={"offset": mdp2.quantities.position}, outputs={"target": robot.joint_effort_target} + ) + }, + ) + for backend in ("torch", "warp"): + scene = PointMassScene(num_worlds=2, joint_names=("a", "b"), device=DEVICE) + builder = mdp2.MDPBuilder(scene.schema) + builder.add_task(task) + mdp = builder.finalize(device=DEVICE, backend=backend) + state, transition = mdp.state(scene), mdp.transition() + scene.data("robot", "joint_pos").torch.fill_(1.0) + mdp2.evaluate(mdp, state, transition) + mdp2.apply_actions(mdp, state, ProxyArray(wp.full((2, 2), 0.5, dtype=wp.float32, device=DEVICE))) + assert scene.data("robot", "joint_effort_target").torch.tolist() == [[1.5, 1.5]] * 2, backend def test_choice_draws_one_subtask_per_episode_and_world(): @@ -2317,7 +2348,7 @@ def skill(joint: str, reward: float) -> mdp2.TaskCfg: ) runs = [] for backend in ("torch", "warp"): - for capture in (False, True) if torch.cuda.is_available() else (False,): + for capture in CAPTURES: runs.append(run_progress(task, [[1.0, 0.0]], backend, capture, num_worlds=256)[2][0]) for run in runs[1:]: for name, value in runs[0].items(): @@ -2326,6 +2357,11 @@ def skill(joint: str, reward: float) -> mdp2.TaskCfg: step = runs[0] left = step["skills.stage"] == 0 assert 0.65 < left.float().mean().item() < 0.85 + # The next reset draws again. + mdp, state, _ = run_progress(task, [[1.0, 0.0]], "warp", False, num_worlds=256) + mdp2.reset(mdp, state, ProxyArray(wp.ones(256, dtype=wp.bool, device=DEVICE))) + again = state.arrays[mdp2.progress.skills.stage].torch == 0 + assert not torch.equal(again, left) and 0.65 < again.float().mean().item() < 0.85 assert torch.equal(step["skills.left.active"], left) and torch.equal(step["skills.right.active"], ~left) assert torch.equal(step["done"], left) # Joint "a" is up, "b" is down torch.testing.assert_close(step["rewards"] / 0.02, torch.where(left, 1.0, 2.0)) @@ -2335,7 +2371,7 @@ def test_parts_renamed_to_other_entities_run_together_in_columns_of_their_own(): """One part, renamed to act on two robots, runs twice as subtasks together: each copy's actions and observations get columns of their own, named with the subtask's name.""" arm = mdp2.TaskCfg( - actions={"effort": mdp2.DirectAction(robot.joint_effort_target)}, + actions={"effort": mdp2.DirectAction(robot.joint_effort_target, subset=robot.joints("a", "b"))}, observations={"policy": {"position": mdp2.Observation(joint_pos, inputs={"joint_pos": robot.joint_pos})}}, ) task = mdp2.compose(left=mdp2.rename(arm, robot="left"), right=mdp2.rename(arm, robot="right")) @@ -2410,6 +2446,46 @@ def test_start_events_write_the_scene_when_their_task_starts(): history = check_progress(mdp2.compose(mdp2.TaskCfg(quantities=above("a")), alone), [[0.0], [1.0]]) assert [step["policy"][0].tolist() for step in history] == [[1.0], [1.0]] # Pushed at the reset only + # Alone, a start event also runs after the progress restarts: it sees none of the episode that ended. + count = mdp2.Event(count_successes, inputs={"done": mdp2.progress.done}, mode=mdp2.EventMode.START) + counted = mdp2.TaskCfg(quantities=above("a"), events={"count": count}, done=mdp2.quantities.a) + mdp, state, _ = run_progress(counted, [[1.0]], "warp", False) + mdp2.reset(mdp, state, ProxyArray(wp.ones(1, dtype=wp.bool, device=DEVICE))) + assert state.arrays[mdp2.term_state("events.count", "total")].torch.tolist() == [0.0] + + +fill_level = mdp2.Term( + torch=lambda mask, level: None, + init=lambda ctx, value: ctx.state["level"].fill_(value), + state={"level": mdp2.State(persistent=True)}, +) +"""Keep a level, such as a difficulty, that its init hook fills with ``value``.""" + + +def test_migrate_runs_init_hooks_only_for_new_uses_and_params(): + """Migrating to an MDP keeps the state of the uses it had with the same params, also those that their world + configs give different params, and runs the init hooks of the others.""" + + def task(hard: float) -> mdp2.TaskCfg: + def level(value: float) -> mdp2.TaskCfg: + return mdp2.TaskCfg(events={"level": mdp2.Event(fill_level, params={"value": value})}) + + return mdp2.split(easy=level(1.0), hard=level(hard)) + + scene = PointMassScene(num_worlds=2, joint_names=("a",), device=DEVICE) + mdps = [] + for hard in (2.0, 2.0, 3.0): + builder = mdp2.MDPBuilder(scene.schema) + builder.add_task(task(hard)) + mdp = builder.finalize(device=DEVICE, backend="torch") + mdps.append((mdp, mdp.state(scene))) + level = mdp2.term_state("events.level", "level") + mdps[0][1].arrays[level].torch.fill_(5.0) # Changed while running, as by a curriculum + mdp2.migrate(*mdps[0], *mdps[1]) + assert mdps[1][1].arrays[level].torch.tolist() == [5.0, 5.0] + mdp2.migrate(*mdps[1], *mdps[2]) + assert mdps[2][1].arrays[level].torch.tolist() == [3.0, 3.0] # The changed params ran the init hook + def test_variations_draw_record_and_replay_values(): """Variations draw a value per world at every reset, write it to the scene, and hold it in a recorded quantity: @@ -2443,6 +2519,8 @@ def run(backend: str, capture: bool) -> list[torch.Tensor]: history.append(torch.stack([scene.data("robot", "joint_pos").torch, torch.stack(values, 1)]).clone()) mdp2.tune(mdp_, state, "events.open.low", 1.0) mdp2.tune(mdp_, state, "events.open.high", 1.0) + # Replay counts the rows taken modulo the table, so that the count stays exact in float32. + assert state.arrays[mdp2.term_state("events.replay", "taken")].torch.item() == 10 % 3 assert [op.name for op in mdp_.ops[mdp2.Phase.QUANTITIES] if op.record] == [ "quantities.open", "quantities.pick", @@ -2451,7 +2529,7 @@ def run(backend: str, capture: bool) -> list[torch.Tensor]: ] return history - runs = [run(backend, capture) for backend in ("torch", "warp") for capture in (False, True)] + runs = [run(backend, capture) for backend in ("torch", "warp") for capture in CAPTURES] for other in runs[1:]: for expected, actual in zip(runs[0], other): assert torch.equal(expected, actual) diff --git a/source/isaaclab_tasks/test/mdp2/test_lift_kuka_allegro.py b/source/isaaclab_tasks/test/mdp2/test_lift_kuka_allegro.py index 5d899053a2fc..319b4d36d102 100644 --- a/source/isaaclab_tasks/test/mdp2/test_lift_kuka_allegro.py +++ b/source/isaaclab_tasks/test/mdp2/test_lift_kuka_allegro.py @@ -260,10 +260,13 @@ def test_step_replays_as_one_graph_with_curriculum_and_bank(scenario: SimpleName def test_play_mode_starts_the_curriculum_at_its_end(): """The play scripts' config starts the curriculum at full difficulty, so that a trained policy plays with gravity, and observes without noise.""" + from isaaclab_experimental.mdp2.config import group_terms + from isaaclab_tasks.utils.hydra import resolve_task_config cfg, _ = resolve_task_config("Isaac-Lift-KukaAllegro-MDP2", None, play_mode=True, overrides=[]) - uses = [use for group in cfg.task.observations.values() for use in group.terms.values() if use is not None] + groups = [group_terms(group)[0] for group in cfg.task.observations.values()] + uses = [use for terms in groups for use in terms.values() if use is not None] params = cfg.task.events["adr"].params assert cfg.scene.num_envs == 50 and all(use.noise is None for use in uses) assert params["init_difficulty"] == params["max_difficulty"] and params["promotion_only"] From 220266ee36961e5cbd552387765f6955d37c0cec Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Mon, 23 Nov 2026 21:00:49 -0800 Subject: [PATCH 38/49] List the one-task builder among the MDP2 breaking changes --- source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst b/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst index 74ec9fdbac9d..b9a07c5256bb 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst @@ -3,6 +3,8 @@ ``task_worlds``. Migrate ``task=[WALK, STAND], task_worlds=[3072, 1024]`` to ``task=mdp2.split(walk=WALK, stand=STAND, worlds={"walk": 3072, "stand": 1024})``. +* **Breaking:** Changed :meth:`~isaaclab_experimental.mdp2.MDPBuilder.add_task` to take one task per builder: + combine tasks with :func:`~isaaclab_experimental.mdp2.compose` and add the result once. * **Breaking:** Changed the observation columns of MDP2 world configs: observations of the same name share their columns, as wide as the widest, and each name has its own, instead of each world config's observations starting at the first column. From 6311633f4da1285fac3e8fc15a1f340a0e7924b5 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Wed, 25 Nov 2026 13:25:33 -0800 Subject: [PATCH 39/49] Describe the MDP2 actuator support and changelogs after merging main Newton-run actuator networks are supported again, with the physics between graphs where Newton cannot capture them; DelayedImplicitActuator draws its delays on the device too; the MDP2 tasks now live in isaaclab_tasks_experimental, so their changelog moves there. --- docs/source/experimental-features/mdp2.rst | 7 ++++--- source/isaaclab/changelog.d/mdp2-part2.added.rst | 2 +- source/isaaclab/changelog.d/mdp2-part2.changed.rst | 4 ++-- .../changelog.d/mdp2-part2.changed.rst | 5 +++-- .../changelog.d/mdp2-part2.changed.rst | 1 + .../changelog.d/mdp2-part2.minor | 0 6 files changed, 11 insertions(+), 8 deletions(-) rename source/{isaaclab_tasks => isaaclab_tasks_experimental}/changelog.d/mdp2-part2.changed.rst (73%) rename source/{isaaclab_tasks => isaaclab_tasks_experimental}/changelog.d/mdp2-part2.minor (100%) diff --git a/docs/source/experimental-features/mdp2.rst b/docs/source/experimental-features/mdp2.rst index beafb81c3e8e..db0b48b20a99 100644 --- a/docs/source/experimental-features/mdp2.rst +++ b/docs/source/experimental-features/mdp2.rst @@ -344,9 +344,10 @@ Limitations - Newton only. Different robots in different worlds are not supported, since Newton's articulation views need homogeneous worlds; different task configs on the same robot are. -- The environments support actuators that CUDA graphs can replay: Isaac Lab actuators with - :attr:`~isaaclab.actuators.ActuatorBase.capturable`, and Newton's own actuators, which run delayed and BAM ones. - Actuator networks are not supported. +- The environments support Isaac Lab actuators with :attr:`~isaaclab.actuators.ActuatorBase.capturable`, and + Newton's own actuators, which run delayed, BAM, and network ones. Newton cannot capture networks loaded from + TorchScript checkpoints, so with them the physics and the scene reset run between the graphs. Isaac Lab's own + actuator networks are not supported. - Joint and body orderings (``ArticulationCfg.joint_ordering`` and ``body_ordering``) are not supported: terms read the asset's data in kernels, and orderings make the asset keep reordered copies that it refreshes outside the graphs. diff --git a/source/isaaclab/changelog.d/mdp2-part2.added.rst b/source/isaaclab/changelog.d/mdp2-part2.added.rst index 7ef72572f22a..4dd3ff142b5e 100644 --- a/source/isaaclab/changelog.d/mdp2-part2.added.rst +++ b/source/isaaclab/changelog.d/mdp2-part2.added.rst @@ -1,5 +1,5 @@ * Added :attr:`~isaaclab.actuators.ActuatorBase.capturable`, which says whether a CUDA graph can replay an actuator's - compute and masked reset with Torch work inside it. Delayed PD actuators qualify: their masked resets draw delays + compute and masked reset with Torch work inside it. Delayed actuators qualify: their masked resets draw delays from a device stream, which a replayed graph advances. The network actuators, which subclass a capturable motor model, are not capturable. * Added :meth:`~isaaclab.physics.PhysicsManager.supports_step_capture` and diff --git a/source/isaaclab/changelog.d/mdp2-part2.changed.rst b/source/isaaclab/changelog.d/mdp2-part2.changed.rst index 4325f5be8502..6a292287518a 100644 --- a/source/isaaclab/changelog.d/mdp2-part2.changed.rst +++ b/source/isaaclab/changelog.d/mdp2-part2.changed.rst @@ -1,3 +1,3 @@ -* Changed the masked resets of :class:`~isaaclab.actuators.DelayedPDActuator` to draw their delays from a Warp device - stream, seeded from Torch's generator when the actuator is created, so that replayed CUDA graphs draw new delays. +* Changed the masked resets of :class:`~isaaclab.actuators.DelayedPDActuator` and + :class:`~isaaclab.actuators.DelayedImplicitActuator` to draw their delays from a Warp device stream, seeded from Torch's generator when the actuator is created, so that replayed CUDA graphs draw new delays. Resets with environment indices still draw from Torch. diff --git a/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst b/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst index b9a07c5256bb..a2691c1840aa 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst @@ -19,8 +19,9 @@ logged as ``Metrics/`` and recorded in the episode records of an episode budget. With an episode budget, ``done`` stays whether an episode ended, and the environment resets only the worlds that restart. * Changed the actuators that MDP2 environments accept: any capturable Isaac Lab actuator - (:attr:`~isaaclab.actuators.ActuatorBase.capturable`) or graphable backend-native actuator, such as the delayed - actuators that Newton runs, instead of a fixed list of actuator types. + (:attr:`~isaaclab.actuators.ActuatorBase.capturable`) and any actuator that Newton runs, instead of a fixed list of + actuator types. Where Newton cannot capture one, such as a network loaded from a TorchScript checkpoint, the physics + and the scene reset run between the graphs. * Changed :class:`~isaaclab_experimental.envs.MDP2Env` to capture its steps through the physics backend (:meth:`~isaaclab.physics.PhysicsManager.capture`) instead of a Newton function: a backend that cannot capture its step steps between the MDP's graphs. Replayed steps now count their physics steps and advance the simulation time. diff --git a/source/isaaclab_tasks/changelog.d/mdp2-part2.changed.rst b/source/isaaclab_tasks_experimental/changelog.d/mdp2-part2.changed.rst similarity index 73% rename from source/isaaclab_tasks/changelog.d/mdp2-part2.changed.rst rename to source/isaaclab_tasks_experimental/changelog.d/mdp2-part2.changed.rst index 5200b61333b5..daf83690f53d 100644 --- a/source/isaaclab_tasks/changelog.d/mdp2-part2.changed.rst +++ b/source/isaaclab_tasks_experimental/changelog.d/mdp2-part2.changed.rst @@ -1,3 +1,4 @@ * Changed ``Isaac-Velocity-Flat-WalkStand-UnitreeGo2-MDP2`` to give its walking and standing tasks their worlds with :func:`~isaaclab_experimental.mdp2.split`. * Changed ``Isaac-Lift-KukaAllegro-MDP2`` to record its success and curriculum progress with ``Quantity(record=True)``. +* Changed the locomotion and Reach MDP2 tasks to record their metrics with ``Quantity(record=True)``. diff --git a/source/isaaclab_tasks/changelog.d/mdp2-part2.minor b/source/isaaclab_tasks_experimental/changelog.d/mdp2-part2.minor similarity index 100% rename from source/isaaclab_tasks/changelog.d/mdp2-part2.minor rename to source/isaaclab_tasks_experimental/changelog.d/mdp2-part2.minor From 277d4d39833c94000206ca75a06296616a5ab5f6 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Wed, 25 Nov 2026 13:25:34 -0800 Subject: [PATCH 40/49] Test delayed-implicit replay, per-step bookkeeping of MDP2 tasks, and gear ratios on split The delay-replay test also covers DelayedImplicitActuator, whose masked resets now draw on the device. The task smoke test checks that eager, capturing and replayed steps count their physics steps and time once, also where the physics runs between graphs. The gear-ratio test builds its two world configs with mdp2.split. --- .../test/actuators/test_actuator_collection.py | 10 ++++++---- .../mdp2/test_experimental_mdp2_environments.py | 13 ++++++++++++- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/source/isaaclab/test/actuators/test_actuator_collection.py b/source/isaaclab/test/actuators/test_actuator_collection.py index 2bdef10e7aac..a315b9d74648 100644 --- a/source/isaaclab/test/actuators/test_actuator_collection.py +++ b/source/isaaclab/test/actuators/test_actuator_collection.py @@ -1017,12 +1017,14 @@ def test_write_command_mask_uses_full_sized_value(command_name): @pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA graphs need a GPU") -def test_masked_resets_of_delayed_actuators_draw_new_delays_when_a_graph_replays_them(): - """Delayed actuators are capturable: a mask reset draws its delays on the device, so each replay draws anew. The - network actuators, which subclass a capturable motor model, keep histories that a graph cannot follow.""" +@pytest.mark.parametrize("cfg_type", [DelayedPDActuatorCfg, DelayedImplicitActuatorCfg]) +def test_masked_resets_of_delayed_actuators_draw_new_delays_when_a_graph_replays_them(cfg_type): + """Delayed actuators, explicit and implicit, are capturable: a mask reset draws its delays on the device, so each + replay draws anew. The network actuators, which subclass a capturable motor model, keep histories that a graph + cannot follow.""" device = "cuda:0" control = FakeActuatorControl(num_envs=64, device=device) - cfg = DelayedPDActuatorCfg(joint_names_expr=[".*"], stiffness=1.0, damping=0.0, min_delay=0, max_delay=3) + cfg = cfg_type(joint_names_expr=[".*"], stiffness=1.0, damping=0.0, min_delay=0, max_delay=3) collection = ActuatorCollection({"delayed": cfg}, control) actuator = collection["delayed"] assert type(actuator).capturable diff --git a/source/isaaclab_tasks_experimental/test/mdp2/test_experimental_mdp2_environments.py b/source/isaaclab_tasks_experimental/test/mdp2/test_experimental_mdp2_environments.py index 60957d1d2724..98a6c09d7378 100644 --- a/source/isaaclab_tasks_experimental/test/mdp2/test_experimental_mdp2_environments.py +++ b/source/isaaclab_tasks_experimental/test/mdp2/test_experimental_mdp2_environments.py @@ -41,10 +41,20 @@ def test_mdp2_environment_resets_and_steps(task_name): env = gym.make(task_name, cfg=env_cfg) try: obs, _ = env.reset(seed=0) + sim = env.unwrapped.sim + counts, times = [sim.get_physics_step_count()], [sim.backend_manager.get_simulation_time()] for _ in range(3): actions = 2.0 * torch.rand(env.action_space.shape, device=env.unwrapped.device) - 1.0 obs, reward, terminated, truncated, _ = env.step(actions) + counts.append(sim.get_physics_step_count()) + times.append(sim.backend_manager.get_simulation_time()) assert all(torch.isfinite(value).all() for value in [*obs.values(), reward]) + # The eager, capturing, and replayed steps count their physics steps and advance the time once each, also + # where the physics runs between the graphs. + steps = [after - before for before, after in zip(counts, counts[1:])] + assert steps[0] > 0 and steps == [steps[0]] * 3, steps + for before, after in zip(times, times[1:]): + assert after - before == pytest.approx(env.unwrapped.step_dt) # The second step captured the step's graphs. if task_name in NUM_GRAPHS: assert env.unwrapped.num_graphs == NUM_GRAPHS[task_name] @@ -106,7 +116,8 @@ def test_locomotion_world_configs_must_share_gear_ratios(): env_cfg.scene.num_envs = 4 energy = env_cfg.task.rewards["energy"] even_gears = replace(energy, params={**energy.params, "gear_ratio": {".*": 1.0}}) - env_cfg.task = [env_cfg.task, replace(env_cfg.task, rewards={**env_cfg.task.rewards, "energy": even_gears})] + even = replace(env_cfg.task, rewards={**env_cfg.task.rewards, "energy": even_gears}) + env_cfg.task = mdp2.split(authored=env_cfg.task, even=even) with pytest.raises(ValueError, match="gear ratios"): gym.make(task_name, cfg=env_cfg) assert SimulationContext.instance() is None From e21451247a4369b516a781ec140de6457bb56453 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Wed, 25 Nov 2026 13:25:35 -0800 Subject: [PATCH 41/49] Compute the MDP2 physics capture flag with the step work The physics step and the replayed steps' host work follow whether the backend captures its step and every Newton actuator is graphable, computed where the step work is built; the scene reset follows the actuators alone, since only Newton's own actuators need it outside the graphs. --- .../isaaclab_experimental/envs/mdp2_env.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py index eefc9697c9b2..8db81a83e719 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py @@ -117,9 +117,7 @@ def _init_sim(self) -> None: # Newton actuators that it cannot capture, such as networks loaded from Torch checkpoints, run on the host: # the physics, which steps them, and the scene reset, which resets them, then run between the graphs. actuators = sim.backend_manager.backend.actuators - self._physics_capturable = sim.backend_manager.supports_step_capture() and ( - actuators is None or actuators.is_all_graphable - ) + self._actuators_capturable = actuators is None or actuators.is_all_graphable self.scene_data = InteractiveSceneData(self.scene, sim, self.step_dt) self._all_envs = ProxyArray(wp.ones(self.num_envs, dtype=wp.bool, device=self.device)) @@ -302,6 +300,8 @@ def _step_work(self) -> list[tuple[bool, Callable[[], None]]]: """Return the work of a control step, in the order of the config's ``step``, each with whether a CUDA graph can capture it.""" transition = self.transition + # The physics steps inside the graphs where the backend captures its step and every actuator it runs. + self._physics_capturable = self.sim.backend_manager.supports_step_capture() and self._actuators_capturable evaluate = Call(self.state, transition=transition, observations=transition.observations) work = [] for item in self.cfg.step: @@ -335,7 +335,8 @@ def _reset_work(self, mask: ProxyArray, render: bool = False) -> list[tuple[bool if item is ResetStep.OBSERVE and render: work += rendering if item is ResetStep.EVENTS: - work.append((self._physics_capturable, functools.partial(self._reset_scene, mask))) + # Newton resets its own actuators here: those it cannot capture keep the scene reset out of the graphs. + work.append((self._actuators_capturable, functools.partial(self._reset_scene, mask))) work += [(launch.capturable, functools.partial(launch, reset)) for launch in launches.reset] elif item is ResetStep.COMMIT: work.append((True, functools.partial(self._commit, mask))) From 58068010699ac79a2244d793f8be0af1d15cd4c2 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Wed, 25 Nov 2026 18:35:10 -0800 Subject: [PATCH 42/49] Raise on physics other than Newton in MDP2 environments --- .../changelog.d/mdp2-part2.changed.rst | 2 ++ .../isaaclab_experimental/envs/mdp2_env.py | 3 +++ source/isaaclab_experimental/test/envs/test_mdp2_env.py | 9 +++++++++ 3 files changed, 14 insertions(+) diff --git a/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst b/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst index a2691c1840aa..898f4e8faa7f 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst @@ -25,6 +25,8 @@ * Changed :class:`~isaaclab_experimental.envs.MDP2Env` to capture its steps through the physics backend (:meth:`~isaaclab.physics.PhysicsManager.capture`) instead of a Newton function: a backend that cannot capture its step steps between the MDP's graphs. Replayed steps now count their physics steps and advance the simulation time. +* Changed :class:`~isaaclab_experimental.envs.MDP2Env` to raise a ``ValueError`` on a physics backend other than + Newton, instead of capturing writes that the backend synchronizes or reading stale state. * Changed ``MDP2EnvCfg.verify_capture`` on physics without a reproducible mode to check the MDP alone, with the physics step replaced by nothing, bitwise, instead of comparing to a relative tolerance. * Changed :class:`~isaaclab_experimental.envs.MDP2Env` to render only the cameras that some term of the task reads. diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py index 8db81a83e719..02b5386a631f 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py @@ -19,6 +19,7 @@ import numpy as np import torch import warp as wp +from isaaclab_newton.physics import NewtonManager from isaaclab_newton.renderers import NewtonOptixRendererCfg, NewtonWarpRendererCfg from isaaclab.envs.common import VecEnvObs, VecEnvStepReturn @@ -79,6 +80,8 @@ def __init__(self, cfg: MDP2EnvCfg) -> None: def _init_sim(self) -> None: """Build the scene and the MDP; on failure, the caller clears the simulation context.""" cfg, sim = self.cfg, self.sim + if not isinstance(sim.backend_manager, NewtonManager): + raise ValueError(f"MDP2 runs on Newton only, got {type(sim.backend_manager).__name__}.") # Terms read sensor data in kernels, so sensors refresh every step rather than when their data is read. A # shallow copy keeps the entities that were added to the config as attributes, and the caller's config. diff --git a/source/isaaclab_experimental/test/envs/test_mdp2_env.py b/source/isaaclab_experimental/test/envs/test_mdp2_env.py index acfb0e1d0044..c5d84aaa9cc0 100644 --- a/source/isaaclab_experimental/test/envs/test_mdp2_env.py +++ b/source/isaaclab_experimental/test/envs/test_mdp2_env.py @@ -559,6 +559,15 @@ def test_built_in_steps_must_run_once_in_order(): MDP2RLEnv(cfg) +def test_env_refuses_physics_other_than_newton(monkeypatch): + """MDP2 binds and captures Newton's physics, so a manager of another backend is refused before the scene is + built, and the simulation context is cleared.""" + monkeypatch.setattr(mdp2_env, "NewtonManager", type("OtherManager", (), {})) + with pytest.raises(ValueError, match="MDP2 runs on Newton only, got NewtonManager"): + MDP2RLEnv(cartpole_cfg()) + assert SimulationContext.instance() is None + + after_steps = mdp2.Term(torch=lambda episode_length, *, steps: (episode_length >= steps).float()) """One from the step ``steps`` of the episode on.""" From adc02e533f49852e099ad131d27e43575639db6a Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Wed, 25 Nov 2026 18:37:39 -0800 Subject: [PATCH 43/49] Require mask in Python hooks of MDP2 action terms --- docs/source/experimental-features/mdp2.rst | 3 +- .../changelog.d/mdp2-part2.added.rst | 2 +- .../isaaclab_experimental/mdp2/builder.py | 4 +- .../isaaclab_experimental/mdp2/config.py | 8 ++-- .../test/mdp2/test_mdp2.py | 44 ++++++++++++++++++- 5 files changed, 51 insertions(+), 10 deletions(-) diff --git a/docs/source/experimental-features/mdp2.rst b/docs/source/experimental-features/mdp2.rst index db0b48b20a99..2877d78df661 100644 --- a/docs/source/experimental-features/mdp2.rst +++ b/docs/source/experimental-features/mdp2.rst @@ -246,7 +246,8 @@ episode ended. - **Action terms.** A :class:`~isaaclab_experimental.mdp2.DirectAction` scales its columns of the action into a field. An :class:`~isaaclab_experimental.mdp2.Action` runs a term's hook on its columns instead, such as :data:`~isaaclab_experimental.mdp2.mdp.binary_joint_position` for a gripper, which closes on either side of a - threshold, as MDP1's binary joint actions do. + threshold, as MDP1's binary joint actions do. A Python hook takes ``mask``, the worlds where the action applies, + such as those that drew its task of a choice, and writes only there. - **Composition.** :func:`~isaaclab_experimental.mdp2.compose` merges partial task configs term by term, such as those of a scene, an embodiment, and a task, and reports uses that two of them define; a later part removes a use by setting it to ``None``. Uses keep the order of the parts. diff --git a/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst index 1e870d14714b..5fb6b1b30c8e 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst @@ -7,7 +7,7 @@ :data:`~isaaclab_experimental.mdp2.mdp.image_rgb`. * Added :class:`~isaaclab_experimental.mdp2.Action`, action terms whose hooks turn their columns of the action into writes, and :data:`~isaaclab_experimental.mdp2.mdp.binary_joint_position`, a binary gripper command with a - threshold. + threshold. A Python hook takes ``mask``, the worlds where the action applies. * Added :func:`~isaaclab_experimental.mdp2.compose`, which merges partial task configs, such as those of a scene, an embodiment, and a task, in order. * Added tasks of tasks to MDP2: a :class:`~isaaclab_experimental.mdp2.TaskCfg` may say when it is ``done`` (with diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py index 5fa2f3a10bf3..5da73532019b 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py @@ -846,8 +846,8 @@ def _compile_term(self, entry: ScheduleEntry, context: CompileContext) -> None: if isinstance(cfg, (Command, Event)): _check_hook(entry, implementation.compute, arguments, errors, extra="mask") elif isinstance(cfg, Action): - # A Python hook may take the worlds where the action is active, as ``mask``. - _check_hook(entry, implementation.compute, {**arguments, "mask": None}, errors) + # A Python hook takes the worlds where the action is active, as ``mask``, so that it writes only there. + _check_hook(entry, implementation.compute, {**arguments, "mask": None}, errors, extra="mask") else: extra = "out" if implementation is term.warp else None _check_hook(entry, implementation.compute, arguments, errors, len(output_shape), extra, dtype) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py index 1d1070b38ca5..8e5c1fbbee85 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py @@ -336,10 +336,10 @@ class Action(TermCfg): """Configuration for an action term, whose hooks turn the columns of the action into writes to ``outputs``. The term's shape is ``("worlds", n)``, with the number of columns ``n`` it takes, and its hooks get them as - ``action``: a Python hook ``compute(action, **args)`` writes its outputs in place, and a func - ``compute(world, action, **args)`` writes its world. Actions apply before every physics step, as in MDP1, or - once per control step at ``ActionRate.CONTROL``, such as an embedded whole-body controller that writes joint - targets. + ``action``: a Python hook ``compute(action, mask, **args)`` writes its outputs in place in the worlds where + ``mask`` holds, every world when it is ``None``, and a func ``compute(world, action, **args)`` writes its world. + Actions apply before every physics step, as in MDP1, or once per control step at ``ActionRate.CONTROL``, such as + an embedded whole-body controller that writes joint targets. """ phase: ClassVar[Phase] = Phase.ACTIONS diff --git a/source/isaaclab_experimental/test/mdp2/test_mdp2.py b/source/isaaclab_experimental/test/mdp2/test_mdp2.py index 2754d4e184aa..0eb457e29f74 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2.py @@ -2321,7 +2321,8 @@ def count_applications_warp( target[world, 0] = action[world, 0] * calls[world] -def count_applications_torch(action, target, calls): +def count_applications_torch(action, target, calls, mask): + assert mask is None # The action applies in every world calls.add_(1.0) target[:, 0] = action[:, 0] * calls @@ -2370,7 +2371,9 @@ def test_actions_apply_once_per_control_step_or_before_every_physics_step(): def test_action_terms_read_quantities(): """An action term reads the quantities of its task, here with Torch hooks only, which a Warp MDP also runs.""" - follow = mdp2.Term(torch=lambda action, offset, target: target.copy_(action + offset), shape=("worlds", "joints")) + follow = mdp2.Term( + torch=lambda action, offset, target, mask: target.copy_(action + offset), shape=("worlds", "joints") + ) task = mdp2.TaskCfg( quantities={"position": mdp2.Quantity(joint_pos, inputs={"joint_pos": robot.joint_pos})}, actions={ @@ -2391,6 +2394,43 @@ def test_action_terms_read_quantities(): assert scene.data("robot", "joint_effort_target").torch.tolist() == [[1.5, 1.5]] * 2, backend +def test_python_action_hooks_write_only_where_their_action_applies(): + """A Python action hook gets the worlds where its action applies as ``mask``: the task of a choice that no world + drew writes nowhere. A hook without ``mask``, which would write in every world, is refused.""" + + def write(value: float): + def compute(action, target, mask): + fill = torch.full_like(target[:, 0], value) + target[:, 0] = fill if mask is None else torch.where(mask, fill, target[:, 0]) + + return compute + + def build(left, right, backend: str): + def branch(compute) -> mdp2.TaskCfg: + term = mdp2.Term(torch=compute, shape=("worlds", 1)) + act = mdp2.Action(term, outputs={"target": robot.joint_effort_target}) + return mdp2.TaskCfg(actions={"act": act}, done=mdp2.quantities.a) + + task = mdp2.compose( + mdp2.TaskCfg(quantities=above("a")), + pick=mdp2.choice(weights={"left": 1.0, "right": 0.0}, left=branch(left), right=branch(right)), + ) + scene = PointMassScene(num_worlds=4, joint_names=("a",), device=DEVICE) + builder = mdp2.MDPBuilder(scene.schema) + builder.add_task(task) + return scene, builder.finalize(device=DEVICE, backend=backend) + + for backend in ("torch", "warp"): + scene, mdp = build(write(1.0), write(2.0), backend) + state, transition = mdp.state(scene), mdp.transition() + env_reset(mdp, state, scene, transition.observations, torch.ones(4, dtype=torch.bool, device=DEVICE)) + mdp2.apply_actions(mdp, state, ProxyArray(wp.from_torch(torch.zeros(4, mdp.action_dim, device=DEVICE)))) + assert scene.data("robot", "joint_effort_target").torch[:, 0].tolist() == [1.0] * 4, backend + + with pytest.raises(ValueError, match="unexpected keyword argument 'mask'"): + build(write(1.0), lambda action, target: target.fill_(2.0), backend) + + def test_choice_draws_one_subtask_per_episode_and_world(): """A choice draws one subtask per world at each reset, by its weights: only that subtask's uses run, the task is done once it is, and its ``stage`` is the drawn subtask.""" From d2591d9474d1973492a1201dcbc2ededc28f2a7d Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Wed, 25 Nov 2026 18:38:45 -0800 Subject: [PATCH 44/49] Compute quantities that MDP2 actions read again after resets --- .../isaaclab_experimental/mdp2/plan.py | 5 +-- .../test/mdp2/test_mdp2.py | 34 +++++++++++++++++++ 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py index c6f7e2d43db2..e7096c1c0a06 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py @@ -348,12 +348,13 @@ def build_plan( if isinstance(op, TermOp) and (op.reset is not None or any(not spec.persistent for spec in op.state.values())) ] - # Observations and action offsets read quantities between steps, also in worlds that were just reset, where - # they are computed again, with the quantities that they read. The others keep the values of the last step. + # Observations and actions read quantities between steps, also in worlds that were just reset, where they are + # computed again, with the quantities that they read. The others keep the values of the last step. read = {selector for op in ops[Phase.OBSERVATIONS] for selector in op.inputs.values()} noises = [op.observation.noise for op in ops[Phase.OBSERVATIONS]] read |= {noise.scale for noise in noises if noise is not None and noise.scale is not None} read |= {op.offset for op in ops[Phase.ACTIONS] if isinstance(op, ActionOp)} + read |= {selector for op in ops[Phase.ACTIONS] if isinstance(op, TermOp) for selector in op.inputs.values()} switched = tuple( op for phase_ops in ops.values() for op in phase_ops if isinstance(op, TermOp) and (op.when or op.stages) ) diff --git a/source/isaaclab_experimental/test/mdp2/test_mdp2.py b/source/isaaclab_experimental/test/mdp2/test_mdp2.py index 0eb457e29f74..9b641bf2e272 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2.py @@ -2394,6 +2394,40 @@ def test_action_terms_read_quantities(): assert scene.data("robot", "joint_effort_target").torch.tolist() == [[1.5, 1.5]] * 2, backend +def set_joint_to_four(mask, joint_pos): + joint_pos[:, 0] = torch.where(mask, torch.full_like(joint_pos[:, 0], 4.0), joint_pos[:, 0]) + + +def copy_goal(action, goal, target, mask): + target[:, 0] = goal if mask is None else torch.where(mask, goal, target[:, 0]) + + +def test_quantities_that_only_actions_read_are_computed_again_after_a_reset(): + """A quantity that only an action term reads is computed again in the worlds that reset, so that the first + action of an episode reads the scene that the reset events wrote, as an observation would.""" + position = mdp2.Term(torch=lambda joint_pos: joint_pos[:, 0].clone()) + goal = mdp2.Quantity(position, inputs={"joint_pos": robot.joint_pos}) + act = mdp2.Action( + mdp2.Term(torch=copy_goal, shape=("worlds", 1)), + inputs={"goal": mdp2.quantities.goal}, + outputs={"target": robot.joint_effort_target}, + ) + task = mdp2.TaskCfg( + quantities={"goal": goal}, + actions={"act": act}, + events={"set": mdp2.Event(mdp2.Term(torch=set_joint_to_four), outputs={"joint_pos": robot.joint_pos})}, + ) + for backend in ("torch", "warp"): + scene = PointMassScene(num_worlds=2, joint_names=("a",), device=DEVICE) + builder = mdp2.MDPBuilder(scene.schema) + builder.add_task(task) + mdp = builder.finalize(device=DEVICE, backend=backend) + state, transition = mdp.state(scene), mdp.transition() + env_reset(mdp, state, scene, transition.observations, torch.ones(2, dtype=torch.bool, device=DEVICE)) + mdp2.apply_actions(mdp, state, ProxyArray(wp.from_torch(torch.zeros(2, mdp.action_dim, device=DEVICE)))) + assert scene.data("robot", "joint_effort_target").torch[:, 0].tolist() == [4.0, 4.0], backend + + def test_python_action_hooks_write_only_where_their_action_applies(): """A Python action hook gets the worlds where its action applies as ``mask``: the task of a choice that no world drew writes nowhere. A hook without ``mask``, which would write in every world, is refused.""" From ad9a06e7913438ada4a4f64b42a9f39729c37aaa Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Wed, 25 Nov 2026 18:39:58 -0800 Subject: [PATCH 45/49] Check the episode budget of MDP2 environments without an RL config --- .../isaaclab_experimental/envs/mdp2_env.py | 2 +- .../test/envs/test_mdp2_env.py | 29 ++++++++++++++++++- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py index 02b5386a631f..3579307912f1 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py @@ -233,7 +233,7 @@ def update_task(self, task: mdp2.TaskCfg, truncate: bool = True) -> None: Startup events run once, when the environment is created: those that the new task adds do not run. With an episode budget, the new task starts a new evaluation, so it truncates the episodes. """ - if not truncate and self.cfg.episode_budget is not None: + if not truncate and self._budgeted: raise ValueError( "With an episode budget, a new task starts a new evaluation: update it with truncate=True." ) diff --git a/source/isaaclab_experimental/test/envs/test_mdp2_env.py b/source/isaaclab_experimental/test/envs/test_mdp2_env.py index c5d84aaa9cc0..a605cbc94558 100644 --- a/source/isaaclab_experimental/test/envs/test_mdp2_env.py +++ b/source/isaaclab_experimental/test/envs/test_mdp2_env.py @@ -16,7 +16,17 @@ import torch import warp as wp from isaaclab_experimental import mdp2 -from isaaclab_experimental.envs import MDP2RLEnv, MDP2RLEnvCfg, ResetStep, Stage, Step, mdp2_env, mdp2_scene_data +from isaaclab_experimental.envs import ( + MDP2Env, + MDP2EnvCfg, + MDP2RLEnv, + MDP2RLEnvCfg, + ResetStep, + Stage, + Step, + mdp2_env, + mdp2_scene_data, +) from isaaclab_experimental.mdp2 import mdp, rng from isaaclab_experimental.mdp2.config import group_terms from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg @@ -893,6 +903,23 @@ def test_update_task_keeps_the_state_of_the_uses_both_tasks_have(): env.close() +def test_env_without_rl_config_updates_its_task_without_truncating(): + """An MDP2Env, whose config has no episode budget, updates its task without truncating: the episodes go on.""" + rl = cartpole_cfg() + cfg = MDP2EnvCfg( + sim=rl.sim, scene=rl.scene, task=rl.task, decimation=rl.decimation, backend=rl.backend, seed=rl.seed + ) + env = MDP2Env(cfg) + try: + env.reset() + for _ in range(2): + env.step(torch.zeros(NUM_ENVS, 1, device=env.device)) + env.update_task(cfg.task, truncate=False) + assert (env.state.episode_length.torch == 2).all() + finally: + env.close() + + def test_delayed_actuators_run_in_captured_steps(): """Delayed actuators, which Newton runs natively, replay in the step's graph: the cart follows changing actions as it does stepping eagerly.""" From 1d3054d6ac574cec10a5b3b4bfd7a54e7447cdb0 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Wed, 25 Nov 2026 18:42:21 -0800 Subject: [PATCH 46/49] Log MDP2 task progress over the episodes that ran each task --- .../changelog.d/mdp2-part2.changed.rst | 4 +-- .../isaaclab_experimental/envs/mdp2_env.py | 18 ++++++------- .../test/envs/test_mdp2_env.py | 26 +++++++++++++++++++ 3 files changed, 37 insertions(+), 11 deletions(-) diff --git a/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst b/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst index 898f4e8faa7f..c0381b8474c0 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst @@ -33,5 +33,5 @@ * Changed :class:`~isaaclab_experimental.envs.MDP2RLEnv` to keep its episode statistics in one generated kernel inside the captured step, instead of about 15 Torch operations per step, and to sum them once per step for ``extras["log"]``: about 15 to 35 µs less per step at 4,096 worlds. Without a time limit, rewards are logged per - second of each episode rather than as zero, and a choice's tasks are averaged over the finished episodes that drew - them. + second of each episode rather than as zero, and the progress of a task is averaged over the finished episodes that + ran it, such as those that drew a task of a choice, rather than over every world. diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py index 3579307912f1..e043e2027d3e 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py @@ -638,24 +638,24 @@ def member(worlds: Sequence[int] | None) -> str: array = argument(value, wp.array(dtype=value.warp.dtype)) names.append(f"Metrics/{op.name.split('.', 1)[1]}") columns.append(f"wp.where({member(op.worlds)}, float({array}[world]) * {share(op.worlds)!r}, 0.0)") - # Progress, over the worlds of the world configs that have each task, and for a task of a choice over those - # that drew it: such a task keeps a second column, of the worlds that ran it, to divide by. + # Progress, over the last episodes that ran each task: in the worlds of the world configs that have it, and for + # a task of a choice in those that drew it. Each task keeps a second column, of the worlds that ran it, to + # divide by, so that worlds without a finished episode, such as under an episode budget, do not count. paths = list(dict.fromkeys(path for tree in self.mdp.tasks for path in sorted(tree.completes))) drawn = {node.path for tree in self.mdp.tasks for node in tree.nodes if tree.drawn(node)} - ratios: list[tuple[int, int]] = [] # Columns of the tasks of a choice: (done, ran) + ratios: list[tuple[int, int]] = [] # Columns of the tasks: (done, ran) for path in paths: worlds = [w for tree in self.mdp.tasks if path in tree.completes for w in tree.worlds] worlds = None if len(worlds) == n else worlds done = argument(self.state.arrays[mdp2.progress_field(path, "done")], wp.array(dtype=wp.bool)) names.append(f"Progress/{path or 'task'}") + ran = member(worlds) if path in drawn: active = argument(self.state.arrays[mdp2.progress_field(path, "active")], wp.array(dtype=wp.bool)) - ran = f"({member(worlds)} and {active}[world])" - columns.append(f"wp.where({ran} and {done}[world], 1.0, 0.0)") - ratios.append((len(columns) - 1, len(columns))) - columns.append(f"wp.where({ran}, 1.0, 0.0)") - else: - columns.append(f"wp.where({member(worlds)} and {done}[world], {share(worlds)!r}, 0.0)") + ran = f"({ran} and {active}[world])" + columns.append(f"wp.where({ran} and {done}[world], 1.0, 0.0)") + ratios.append((len(columns) - 1, len(columns))) + columns.append(f"wp.where({ran}, 1.0, 0.0)") self._log_names = names self._last_episodes = torch.zeros(len(columns), n, device=device) diff --git a/source/isaaclab_experimental/test/envs/test_mdp2_env.py b/source/isaaclab_experimental/test/envs/test_mdp2_env.py index a605cbc94558..cc479fe97946 100644 --- a/source/isaaclab_experimental/test/envs/test_mdp2_env.py +++ b/source/isaaclab_experimental/test/envs/test_mdp2_env.py @@ -611,6 +611,32 @@ def stage(steps: int, weight: float) -> mdp2.TaskCfg: env.close() +def test_progress_is_logged_over_the_episodes_that_ran(): + """Under an episode budget of one episode, the progress of each task is logged over that episode, not over every + world, most of which finished none.""" + + def stage(steps: int) -> mdp2.TaskCfg: + ready = mdp2.Quantity(after_steps, inputs={"episode_length": mdp2.episode_length}, params={"steps": steps}) + return mdp2.TaskCfg(quantities={"ready": ready}, done=mdp2.quantities.ready) + + cfg = cartpole_cfg() + cfg.task.terminations["cart_out_of_bounds"] = None + cfg.task = mdp2.compose(cfg.task, mdp2.sequence(warm=stage(3), hold=stage(6))) + cfg.episode_budget = 1 + env = MDP2RLEnv(cfg) + try: + env.reset() + for _ in range(2 * env.max_episode_length): + _, _, _, _, extras = env.step(torch.zeros(NUM_ENVS, 1, device=env.device)) + if env.episodes_completed: + break + assert env.episodes_completed == 1 + log = extras["log"] + assert log["Progress/warm"] == 1.0 and log["Progress/hold"] == 1.0 and log["Progress/task"] == 1.0 + finally: + env.close() + + def test_verify_capture_finds_python_state_that_the_graph_freezes(): """The debug check passes a task whose captured steps are exact, and names a stage whose Python-side state the graph froze at capture.""" From a7daf597fbf2e002db33dfc086224e8088ce6bdd Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Wed, 25 Nov 2026 18:44:00 -0800 Subject: [PATCH 47/49] Keep the Torch delay draw of delayed actuators and mark them not capturable --- docs/source/experimental-features/mdp2.rst | 3 +- .../isaaclab/changelog.d/mdp2-part2.added.rst | 5 ++- .../changelog.d/mdp2-part2.changed.rst | 3 -- .../isaaclab/actuators/actuator_base.py | 4 +-- .../isaaclab/actuators/actuator_pd.py | 32 +++---------------- .../actuators/test_actuator_collection.py | 30 ----------------- 6 files changed, 10 insertions(+), 67 deletions(-) delete mode 100644 source/isaaclab/changelog.d/mdp2-part2.changed.rst diff --git a/docs/source/experimental-features/mdp2.rst b/docs/source/experimental-features/mdp2.rst index 2877d78df661..d51e1c7b8168 100644 --- a/docs/source/experimental-features/mdp2.rst +++ b/docs/source/experimental-features/mdp2.rst @@ -348,7 +348,8 @@ Limitations - The environments support Isaac Lab actuators with :attr:`~isaaclab.actuators.ActuatorBase.capturable`, and Newton's own actuators, which run delayed, BAM, and network ones. Newton cannot capture networks loaded from TorchScript checkpoints, so with them the physics and the scene reset run between the graphs. Isaac Lab's own - actuator networks are not supported. + delayed actuators and actuator networks are not supported: Newton runs delayed actuators itself, unless + ``use_newton_actuators=False``. - Joint and body orderings (``ArticulationCfg.joint_ordering`` and ``body_ordering``) are not supported: terms read the asset's data in kernels, and orderings make the asset keep reordered copies that it refreshes outside the graphs. diff --git a/source/isaaclab/changelog.d/mdp2-part2.added.rst b/source/isaaclab/changelog.d/mdp2-part2.added.rst index 4dd3ff142b5e..a3c337bd7628 100644 --- a/source/isaaclab/changelog.d/mdp2-part2.added.rst +++ b/source/isaaclab/changelog.d/mdp2-part2.added.rst @@ -1,7 +1,6 @@ * Added :attr:`~isaaclab.actuators.ActuatorBase.capturable`, which says whether a CUDA graph can replay an actuator's - compute and masked reset with Torch work inside it. Delayed actuators qualify: their masked resets draw delays - from a device stream, which a replayed graph advances. The network actuators, which subclass a capturable motor - model, are not capturable. + compute and masked reset with Torch work inside it: the implicit, ideal PD, and DC motor actuators. The delayed + actuators, whose masked resets draw from Torch's generator, and the network actuators are not capturable. * Added :meth:`~isaaclab.physics.PhysicsManager.supports_step_capture` and :meth:`~isaaclab.physics.PhysicsManager.capture`, with which environments that replay their steps as CUDA graphs record them as the physics backend records its own step, and :meth:`~isaaclab.sim.SimulationContext.after_replay`, diff --git a/source/isaaclab/changelog.d/mdp2-part2.changed.rst b/source/isaaclab/changelog.d/mdp2-part2.changed.rst deleted file mode 100644 index 6a292287518a..000000000000 --- a/source/isaaclab/changelog.d/mdp2-part2.changed.rst +++ /dev/null @@ -1,3 +0,0 @@ -* Changed the masked resets of :class:`~isaaclab.actuators.DelayedPDActuator` and - :class:`~isaaclab.actuators.DelayedImplicitActuator` to draw their delays from a Warp device stream, seeded from Torch's generator when the actuator is created, so that replayed CUDA graphs draw new delays. - Resets with environment indices still draw from Torch. diff --git a/source/isaaclab/isaaclab/actuators/actuator_base.py b/source/isaaclab/isaaclab/actuators/actuator_base.py index 303386750b17..94db24ce170b 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_base.py +++ b/source/isaaclab/isaaclab/actuators/actuator_base.py @@ -112,8 +112,8 @@ class ActuatorBase(ABC): capturable: ClassVar[bool] = False """Whether :meth:`compute` and :meth:`reset` with an ``env_mask`` can be recorded into a CUDA graph and replayed. - They must then not synchronize with the host, nor draw from Torch's random generators, whose draws a replayed - graph repeats, when Torch joins the capture on the capturing stream. Environments that replay their steps as + They must then not synchronize with the host, nor draw from Torch's random generators, which cannot record their + draws when Torch joins the capture on the capturing stream. Environments that replay their steps as graphs with Torch work inside them, such as MDP2's, accept only such actuators. Unlike :attr:`~isaaclab.actuators.ActuatorCollection.is_graphable`, Torch models qualify. """ diff --git a/source/isaaclab/isaaclab/actuators/actuator_pd.py b/source/isaaclab/isaaclab/actuators/actuator_pd.py index 17d35792c351..a7cb32e4a78d 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_pd.py +++ b/source/isaaclab/isaaclab/actuators/actuator_pd.py @@ -34,6 +34,8 @@ class _DelayedActuator: """Shared command history and reset lifecycle for delayed actuator models.""" + capturable: ClassVar[bool] = False # Masked resets draw delays from Torch's generator, which graphs cannot record + def __init__(self, cfg: DelayedImplicitActuatorCfg | DelayedPDActuatorCfg, *args, **kwargs) -> None: self._max_delay = 0 if cfg.max_delay is None else cfg.max_delay if not 0 <= cfg.min_delay <= self._max_delay: @@ -43,24 +45,14 @@ def __init__(self, cfg: DelayedImplicitActuatorCfg | DelayedPDActuatorCfg, *args self.velocities_delay_buffer = DelayBuffer(self._max_delay, self._num_envs, device=self._device) self.efforts_delay_buffer = DelayBuffer(self._max_delay, self._num_envs, device=self._device) self._delay_buffers = (self.positions_delay_buffer, self.velocities_delay_buffer, self.efforts_delay_buffer) - # Masked resets draw delays from a device stream, which a replayed CUDA graph advances, seeded from Torch. - seed = int(torch.randint(0, 2**31 - 1, (1,)).item()) - self._delay_seed = wp.array([seed], dtype=wp.int32, device=self._device) - self._drawn_time_lags = wp.zeros(self._num_envs, dtype=wp.int32, device=self._device) def reset(self, env_ids: Sequence[int] | slice | None = None, env_mask: wp.array | None = None) -> None: super().reset(env_ids, env_mask) if env_mask is not None: # draw a delay for every environment and keep the selected ones, so the mask stays on the device - wp.launch( - _draw_time_lags, - dim=self._num_envs, - inputs=[self._delay_seed, self.cfg.min_delay, self._max_delay], - outputs=[self._drawn_time_lags], - device=self._device, + time_lags = torch.randint( + self.cfg.min_delay, self._max_delay + 1, (self._num_envs,), dtype=torch.int, device=self._device ) - wp.launch(_advance_seed, dim=1, inputs=[self._delay_seed], device=self._device) - time_lags = wp.to_torch(self._drawn_time_lags) selected = wp.to_torch(env_mask) for delay_buffer in self._delay_buffers: torch.where(selected, time_lags, delay_buffer.time_lags, out=delay_buffer.time_lags) @@ -95,18 +87,6 @@ def compute( """ -@wp.kernel -def _draw_time_lags(seed: wp.array(dtype=wp.int32), low: int, high: int, time_lags: wp.array(dtype=wp.int32)): - """Draw a time lag in ``[low, high]`` for every environment from the stream ``seed``.""" - env = wp.tid() - time_lags[env] = wp.randi(wp.rand_init(seed[0], env), low, high + 1) - - -@wp.kernel -def _advance_seed(seed: wp.array(dtype=wp.int32)): - seed[0] = seed[0] + 1 - - class ImplicitActuator(ActuatorBase): """Implicit actuator model that is handled by the simulation. @@ -514,8 +494,6 @@ class DelayedPDActuator(_DelayedActuator, IdealPDActuator): cfg: DelayedPDActuatorCfg """The configuration for the actuator model.""" - capturable: ClassVar[bool] = True # Masked resets draw delays from a device stream - class RemotizedPDActuator(DelayedPDActuator): """Ideal PD actuator with angle-dependent torque limits. @@ -530,8 +508,6 @@ class RemotizedPDActuator(DelayedPDActuator): The torque limits are interpolated based on the current joint positions and applied to the actuator commands. """ - capturable: ClassVar[bool] = False # The lookup of the torque limits assigns through a boolean mask - def __init__( self, cfg: RemotizedPDActuatorCfg, diff --git a/source/isaaclab/test/actuators/test_actuator_collection.py b/source/isaaclab/test/actuators/test_actuator_collection.py index a315b9d74648..2ab078d58581 100644 --- a/source/isaaclab/test/actuators/test_actuator_collection.py +++ b/source/isaaclab/test/actuators/test_actuator_collection.py @@ -20,8 +20,6 @@ from isaaclab.actuators import ( ActuatorCollection, ActuatorControl, - ActuatorNetLSTM, - ActuatorNetMLP, DCMotor, DCMotorCfg, DelayedImplicitActuatorCfg, @@ -1016,34 +1014,6 @@ def test_write_command_mask_uses_full_sized_value(command_name): setter(value=value, env_mask=wp.array([1, 0], dtype=wp.int32, device="cpu"), joint_mask=joint_mask) -@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA graphs need a GPU") -@pytest.mark.parametrize("cfg_type", [DelayedPDActuatorCfg, DelayedImplicitActuatorCfg]) -def test_masked_resets_of_delayed_actuators_draw_new_delays_when_a_graph_replays_them(cfg_type): - """Delayed actuators, explicit and implicit, are capturable: a mask reset draws its delays on the device, so each - replay draws anew. The network actuators, which subclass a capturable motor model, keep histories that a graph - cannot follow.""" - device = "cuda:0" - control = FakeActuatorControl(num_envs=64, device=device) - cfg = cfg_type(joint_names_expr=[".*"], stiffness=1.0, damping=0.0, min_delay=0, max_delay=3) - collection = ActuatorCollection({"delayed": cfg}, control) - actuator = collection["delayed"] - assert type(actuator).capturable - assert not ActuatorNetMLP.capturable and not ActuatorNetLSTM.capturable - env_mask = wp.ones(64, dtype=wp.bool, device=device) - collection.reset(env_mask=env_mask) # Loads the kernels - # Torch joins the capture on Warp's stream, with memory of its own, as environments that replay steps do. - pool = torch.cuda.MemPool() - with wp.ScopedCapture(device=device) as capture: - with torch.cuda.stream(wp.stream_to_torch(wp.get_stream(device))), torch.cuda.use_mem_pool(pool): - collection.reset(env_mask=env_mask) - draws = [] - for _ in range(2): - wp.capture_launch(capture.graph) - draws.append(actuator.positions_delay_buffer.time_lags.clone()) - assert not torch.equal(draws[0], draws[1]) - assert all(((draw >= 0) & (draw <= 3)).all() for draw in draws) - - @pytest.mark.parametrize( ("device", "delay"), [(device, 2) for device in test_devices()] + [pytest.param("cpu", None, id="cpu-default-delay")], From 7962cb37a2a95f7b60857b1a3bc5d132fff3a774 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Wed, 25 Nov 2026 19:06:33 -0800 Subject: [PATCH 48/49] Describe MDP2 progress logs and delayed actuator support accurately --- docs/source/experimental-features/mdp2.rst | 4 ++-- .../changelog.d/mdp2-part2.changed.rst | 4 ++-- .../isaaclab_experimental/envs/mdp2_env.py | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/source/experimental-features/mdp2.rst b/docs/source/experimental-features/mdp2.rst index d51e1c7b8168..2e9e1eec5f4a 100644 --- a/docs/source/experimental-features/mdp2.rst +++ b/docs/source/experimental-features/mdp2.rst @@ -348,8 +348,8 @@ Limitations - The environments support Isaac Lab actuators with :attr:`~isaaclab.actuators.ActuatorBase.capturable`, and Newton's own actuators, which run delayed, BAM, and network ones. Newton cannot capture networks loaded from TorchScript checkpoints, so with them the physics and the scene reset run between the graphs. Isaac Lab's own - delayed actuators and actuator networks are not supported: Newton runs delayed actuators itself, unless - ``use_newton_actuators=False``. + delayed actuators and actuator networks are not supported: Newton runs delayed PD actuators itself unless + ``use_newton_actuators=False``, but not :class:`~isaaclab.actuators.DelayedImplicitActuator`, which Isaac Lab runs. - Joint and body orderings (``ArticulationCfg.joint_ordering`` and ``body_ordering``) are not supported: terms read the asset's data in kernels, and orderings make the asset keep reordered copies that it refreshes outside the graphs. diff --git a/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst b/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst index c0381b8474c0..2b67fa1aee3c 100644 --- a/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst +++ b/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst @@ -33,5 +33,5 @@ * Changed :class:`~isaaclab_experimental.envs.MDP2RLEnv` to keep its episode statistics in one generated kernel inside the captured step, instead of about 15 Torch operations per step, and to sum them once per step for ``extras["log"]``: about 15 to 35 µs less per step at 4,096 worlds. Without a time limit, rewards are logged per - second of each episode rather than as zero, and the progress of a task is averaged over the finished episodes that - ran it, such as those that drew a task of a choice, rather than over every world. + second of each episode rather than as zero, and the progress of a task is averaged over the last finished episodes + of the worlds that have it, for a task of a choice of those that drew it, rather than over every world. diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py index e043e2027d3e..888b3f4ae45e 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py @@ -638,9 +638,9 @@ def member(worlds: Sequence[int] | None) -> str: array = argument(value, wp.array(dtype=value.warp.dtype)) names.append(f"Metrics/{op.name.split('.', 1)[1]}") columns.append(f"wp.where({member(op.worlds)}, float({array}[world]) * {share(op.worlds)!r}, 0.0)") - # Progress, over the last episodes that ran each task: in the worlds of the world configs that have it, and for - # a task of a choice in those that drew it. Each task keeps a second column, of the worlds that ran it, to - # divide by, so that worlds without a finished episode, such as under an episode budget, do not count. + # Progress, over the last finished episodes of the worlds of the world configs that have each task, and for a + # task of a choice of those that drew it. Each task keeps a second column, of those episodes, to divide by, so + # that worlds without a finished episode, such as under an episode budget, do not count. paths = list(dict.fromkeys(path for tree in self.mdp.tasks for path in sorted(tree.completes))) drawn = {node.path for tree in self.mdp.tasks for node in tree.nodes if tree.drawn(node)} ratios: list[tuple[int, int]] = [] # Columns of the tasks: (done, ran) From 8dea79c30549b5e289ad0890f61e3f3adca1bbeb Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Thu, 26 Nov 2026 00:16:00 -0800 Subject: [PATCH 49/49] Trim the MDP2 action-hook check, capture flag, and progress tests Actions check their mask like events and commands, the physics capture flag is set where the step work is built rather than inside it, and the progress tests share one stage helper. --- .../isaaclab_experimental/envs/mdp2_env.py | 11 ++++------- .../isaaclab_experimental/mdp2/builder.py | 7 ++----- .../mdp2/torch_backend.py | 5 ++--- .../test/envs/test_mdp2_env.py | 19 +++++++------------ .../test/mdp2/test_mdp2.py | 4 ++-- 5 files changed, 17 insertions(+), 29 deletions(-) diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py index 888b3f4ae45e..ffb3da933d5f 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py @@ -176,6 +176,8 @@ def _build(self, task: mdp2.TaskCfg, previous: tuple[mdp2.MDP, mdp2.MDPState] | if self._event_worlds is not None: self._commit_mask = ProxyArray(wp.zeros(self.num_envs, dtype=wp.bool, device=self.device)) + # The physics steps in the graphs where the backend captures its step and every actuator it runs. + self._physics_capturable = self.sim.backend_manager.supports_step_capture() and self._actuators_capturable self._work = self._step_work() # The work of a step, in order, each with whether a graph can capture it self._runs: list[Callable[[], None]] | None = None # The captured step: graph replays and the work between them self.num_graphs = 0 # CUDA graphs that one captured step replays @@ -303,13 +305,10 @@ def _step_work(self) -> list[tuple[bool, Callable[[], None]]]: """Return the work of a control step, in the order of the config's ``step``, each with whether a CUDA graph can capture it.""" transition = self.transition - # The physics steps inside the graphs where the backend captures its step and every actuator it runs. - self._physics_capturable = self.sim.backend_manager.supports_step_capture() and self._actuators_capturable evaluate = Call(self.state, transition=transition, observations=transition.observations) work = [] for item in self.cfg.step: if item is Step.PHYSICS: - # A physics backend that cannot capture its step steps between the graphs of the MDP. work.append((self._physics_capturable, self._simulate)) elif item is Step.RENDER: work += [(self._render_capturable, self._render)] if self._cameras else [] @@ -338,7 +337,6 @@ def _reset_work(self, mask: ProxyArray, render: bool = False) -> list[tuple[bool if item is ResetStep.OBSERVE and render: work += rendering if item is ResetStep.EVENTS: - # Newton resets its own actuators here: those it cannot capture keep the scene reset out of the graphs. work.append((self._actuators_capturable, functools.partial(self._reset_scene, mask))) work += [(launch.capturable, functools.partial(launch, reset)) for launch in launches.reset] elif item is ResetStep.COMMIT: @@ -638,9 +636,8 @@ def member(worlds: Sequence[int] | None) -> str: array = argument(value, wp.array(dtype=value.warp.dtype)) names.append(f"Metrics/{op.name.split('.', 1)[1]}") columns.append(f"wp.where({member(op.worlds)}, float({array}[world]) * {share(op.worlds)!r}, 0.0)") - # Progress, over the last finished episodes of the worlds of the world configs that have each task, and for a - # task of a choice of those that drew it. Each task keeps a second column, of those episodes, to divide by, so - # that worlds without a finished episode, such as under an episode budget, do not count. + # Progress, over the last finished episodes of the worlds that have each task, for a task of a choice of those + # that drew it: a second column counts those episodes, so worlds that finished none do not count. paths = list(dict.fromkeys(path for tree in self.mdp.tasks for path in sorted(tree.completes))) drawn = {node.path for tree in self.mdp.tasks for node in tree.nodes if tree.drawn(node)} ratios: list[tuple[int, int]] = [] # Columns of the tasks: (done, ran) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py index 5da73532019b..8640d087e959 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py @@ -842,12 +842,9 @@ def _compile_term(self, entry: ScheduleEntry, context: CompileContext) -> None: # Python hooks may also take ``cache``, a dict the use keeps for host objects. if not isinstance(implementation.compute, wp.Function): arguments["cache"] = None - # Events and commands take the mask of the worlds to write; other Warp functions take the output to write. - if isinstance(cfg, (Command, Event)): + # Events, commands, and actions take the mask of their worlds; other Warp functions take their output. + if isinstance(cfg, (Command, Event, Action)): _check_hook(entry, implementation.compute, arguments, errors, extra="mask") - elif isinstance(cfg, Action): - # A Python hook takes the worlds where the action is active, as ``mask``, so that it writes only there. - _check_hook(entry, implementation.compute, {**arguments, "mask": None}, errors, extra="mask") else: extra = "out" if implementation is term.warp else None _check_hook(entry, implementation.compute, arguments, errors, len(output_shape), extra, dtype) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py index b56e0e3a588b..1b65b408a75b 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py @@ -54,11 +54,10 @@ def _apply_actions(mdp: MDP, call: Call, steps: tuple[Step, ...], store: bool) - for step in steps: op = step.op if isinstance(op, TermOp): - # The hook writes its outputs; it may take the worlds where it is active as ``mask``. + # The hook writes its outputs in the worlds where it is active, ``mask``. active = _active(op, call.state) arguments = {**call.state.arguments[op.name], "action": actions[:, op.columns]} - arguments["mask"] = None if active is None else active.torch - op.compute(**hook_arguments(op.compute, arguments)) + op.compute(mask=None if active is None else active.torch, **hook_arguments(op.compute, arguments)) continue target = call.state.arrays[op.target].torch.view(mdp.num_worlds, -1) ids = slice(None) if op.subset is None else call.state.arrays[op.subset].torch diff --git a/source/isaaclab_experimental/test/envs/test_mdp2_env.py b/source/isaaclab_experimental/test/envs/test_mdp2_env.py index cc479fe97946..2ec793bfca34 100644 --- a/source/isaaclab_experimental/test/envs/test_mdp2_env.py +++ b/source/isaaclab_experimental/test/envs/test_mdp2_env.py @@ -582,16 +582,16 @@ def test_env_refuses_physics_other_than_newton(monkeypatch): """One from the step ``steps`` of the episode on.""" +def stage(steps: int, weight: float = 1.0) -> mdp2.TaskCfg: + """A task done after ``steps`` steps, with a bonus of ``weight``, which makes the bonus a use of this task.""" + ready = mdp2.Quantity(after_steps, inputs={"episode_length": mdp2.episode_length}, params={"steps": steps}) + bonus = mdp2.Reward(mdp.is_alive, inputs={"terminated": mdp2.terminated}, weight=weight) + return mdp2.TaskCfg(quantities={"ready": ready}, rewards={"bonus": bonus}, done=mdp2.quantities.ready) + + def test_env_runs_the_tasks_of_a_sequence_in_turn_and_logs_their_progress(): """A sequence of two tasks, each with its own quantity and reward, steps the same captured and uncaptured, and the environment logs how often each task was done in the last episodes.""" - - def stage(steps: int, weight: float) -> mdp2.TaskCfg: - ready = mdp2.Quantity(after_steps, inputs={"episode_length": mdp2.episode_length}, params={"steps": steps}) - # The weights differ, so that the bonus is a use of each task rather than one of both. - bonus = mdp2.Reward(mdp.is_alive, inputs={"terminated": mdp2.terminated}, weight=weight) - return mdp2.TaskCfg(quantities={"ready": ready}, rewards={"bonus": bonus}, done=mdp2.quantities.ready) - cfg = cartpole_cfg() cfg.task.terminations["cart_out_of_bounds"] = None cfg.task = mdp2.compose(cfg.task, mdp2.sequence(warm=stage(3, 1.0), hold=stage(6, 2.0))) @@ -614,11 +614,6 @@ def stage(steps: int, weight: float) -> mdp2.TaskCfg: def test_progress_is_logged_over_the_episodes_that_ran(): """Under an episode budget of one episode, the progress of each task is logged over that episode, not over every world, most of which finished none.""" - - def stage(steps: int) -> mdp2.TaskCfg: - ready = mdp2.Quantity(after_steps, inputs={"episode_length": mdp2.episode_length}, params={"steps": steps}) - return mdp2.TaskCfg(quantities={"ready": ready}, done=mdp2.quantities.ready) - cfg = cartpole_cfg() cfg.task.terminations["cart_out_of_bounds"] = None cfg.task = mdp2.compose(cfg.task, mdp2.sequence(warm=stage(3), hold=stage(6))) diff --git a/source/isaaclab_experimental/test/mdp2/test_mdp2.py b/source/isaaclab_experimental/test/mdp2/test_mdp2.py index 9b641bf2e272..f682c30486eb 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2.py @@ -2461,8 +2461,8 @@ def branch(compute) -> mdp2.TaskCfg: mdp2.apply_actions(mdp, state, ProxyArray(wp.from_torch(torch.zeros(4, mdp.action_dim, device=DEVICE)))) assert scene.data("robot", "joint_effort_target").torch[:, 0].tolist() == [1.0] * 4, backend - with pytest.raises(ValueError, match="unexpected keyword argument 'mask'"): - build(write(1.0), lambda action, target: target.fill_(2.0), backend) + with pytest.raises(ValueError, match="unexpected keyword argument 'mask'"): + build(write(1.0), lambda action, target: target.fill_(2.0), "torch") def test_choice_draws_one_subtask_per_episode_and_world():