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..cb0475c33d90 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 -------- @@ -38,3 +44,9 @@ Curriculums .. automodule:: isaaclab_experimental.mdp2.mdp.curriculums :members: + +Variations +---------- + +.. automodule:: isaaclab_experimental.mdp2.mdp.variations + :members: diff --git a/docs/source/api/lab_experimental/isaaclab_experimental.mdp2.rst b/docs/source/api/lab_experimental/isaaclab_experimental.mdp2.rst index a0fdb19c863f..a0ffb9e9f691 100644 --- a/docs/source/api/lab_experimental/isaaclab_experimental.mdp2.rst +++ b/docs/source/api/lab_experimental/isaaclab_experimental.mdp2.rst @@ -22,7 +22,10 @@ Terms and task configuration SubsetSelector TaskCfg DirectAction + Action + ActionRate Observation + ObservationGroup Reward Termination TimeLimit @@ -31,7 +34,18 @@ Terms and task configuration EventMode Quantity UniformNoise + Tunable + tunable term_state + compose + sequence + split + choice + rename + Milestone + TaskMode + progress + progress_field Building and running -------------------- @@ -41,15 +55,20 @@ Building and running MDPBuilder MDP + Columns + Spec MDPState Transition Backend CapturedMDP startup + process_actions apply_actions evaluate reset observe + tune + migrate Scene data ---------- @@ -73,7 +92,11 @@ Scene data .. autoclass:: SubsetSelector .. autoclass:: TaskCfg .. autoclass:: DirectAction +.. autoclass:: Action +.. autoclass:: ActionRate + :members: .. autoclass:: Observation +.. autoclass:: ObservationGroup .. autoclass:: Reward .. autoclass:: Termination .. autoclass:: TimeLimit @@ -83,11 +106,25 @@ 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: +.. autodata:: progress +.. autofunction:: progress_field .. autoclass:: MDPBuilder :members: .. autoclass:: MDP :members: +.. autoclass:: Columns +.. autoclass:: Spec .. autoclass:: MDPState :members: .. autoclass:: Transition @@ -96,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 cbee75be30c3..2e9e1eec5f4a 100644 --- a/docs/source/experimental-features/mdp2.rst +++ b/docs/source/experimental-features/mdp2.rst @@ -95,7 +95,75 @@ 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. Four 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 + * - :func:`~isaaclab_experimental.mdp2.choice` + - one per episode and world, drawn at the reset + - once the drawn one 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; ``EventMode.START`` events run when their + 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. +- **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 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 + task was done as ``Progress/``. Backends and capture @@ -124,14 +192,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,24 +227,138 @@ 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 + 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 + ``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. 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. +- **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() + + +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 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 + 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 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 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 +------------------ + +.. 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 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 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. - 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/changelog.d/mdp2-part2.added.rst b/source/isaaclab/changelog.d/mdp2-part2.added.rst new file mode 100644 index 000000000000..a3c337bd7628 --- /dev/null +++ b/source/isaaclab/changelog.d/mdp2-part2.added.rst @@ -0,0 +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: 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`, + which does the host work of the physics steps that a replayed graph ran, such as counting them. 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..94db24ce170b 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, 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. + """ + 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_net.py b/source/isaaclab/isaaclab/actuators/actuator_net.py index c12394f22b0d..4f125ac9f290 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): if cfg.network_file is None: raise ValueError("network_file must be provided for the Isaac Lab neural actuator model.") @@ -124,6 +126,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): if cfg.network_file is None: raise ValueError("network_file must be provided for the Isaac Lab neural actuator model.") diff --git a/source/isaaclab/isaaclab/actuators/actuator_pd.py b/source/isaaclab/isaaclab/actuators/actuator_pd.py index ef1fcf28c52e..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: @@ -98,6 +100,7 @@ class ImplicitActuator(ActuatorBase): """The configuration for the actuator model.""" is_implicit_model: ClassVar[bool] = True + capturable: ClassVar[bool] = True def __init__( self, @@ -319,6 +322,8 @@ class IdealPDActuator(ActuatorBase): cfg: IdealPDActuatorCfg """The configuration for the actuator model.""" + capturable: ClassVar[bool] = True + actuator_effort_limit: torch.Tensor """Actuator-model effort clipping limit [N or N·m, depending on joint type]. diff --git a/source/isaaclab/isaaclab/physics/physics_manager.py b/source/isaaclab/isaaclab/physics/physics_manager.py index d1c23601afb0..b1614511826a 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 477ae7ab5ddc..a23aafb42fd7 100644 --- a/source/isaaclab/isaaclab/sim/simulation_context.py +++ b/source/isaaclab/isaaclab/sim/simulation_context.py @@ -586,6 +586,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: @@ -596,10 +604,20 @@ 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. + + 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._wait_while_paused() + 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-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/changelog.d/mdp2-part2.added.rst b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst new file mode 100644 index 000000000000..5fb6b1b30c8e --- /dev/null +++ b/source/isaaclab_experimental/changelog.d/mdp2-part2.added.rst @@ -0,0 +1,76 @@ +* 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. 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 + ``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. 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 + 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 + 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. +* 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, 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 + :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. +* 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. +* 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. +* 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 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 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 + :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``. +* 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/changelog.d/mdp2-part2.changed.rst b/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst new file mode 100644 index 000000000000..2b67fa1aee3c --- /dev/null +++ b/source/isaaclab_experimental/changelog.d/mdp2-part2.changed.rst @@ -0,0 +1,37 @@ +* **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 :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. +* **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``. +* 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. +* Changed the actuators that MDP2 environments accept: any capturable Isaac Lab actuator + (: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. +* 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. +* 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 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/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 ddf92d7aed3a..ffb3da933d5f 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py @@ -8,20 +8,23 @@ from __future__ import annotations import copy +import dataclasses 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 import torch import warp as wp -from isaaclab_newton.physics.newton_backend import capture_graph +from isaaclab_newton.physics import NewtonManager +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 @@ -30,6 +33,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 @@ -40,15 +44,19 @@ 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 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) @@ -72,17 +80,39 @@ 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. 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._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] + 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. @@ -90,47 +120,67 @@ 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 = 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) - 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]) - self.mdp = builder.finalize( + 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) + 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) + # 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 mdp.term_ops + for selector in op.inputs.values() + } + 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 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. + 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. - 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] = {} + # 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._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 @@ -157,7 +207,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.""" @@ -165,7 +215,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 @@ -174,6 +224,42 @@ 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, 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. + 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._budgeted: + 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() + 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, + 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: # The captured steps reference scene buffers and solver hooks. @@ -190,12 +276,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._physics_capturable: + self.sim.after_replay(self.cfg.decimation // self._substeps) else: for _, work in self._work: work() @@ -219,30 +310,39 @@ def _step_work(self) -> list[tuple[bool, Callable[[], None]]]: for item in self.cfg.step: if item is Step.PHYSICS: work.append((self._physics_capturable, 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 ] 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 - 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((self._physics_capturable, functools.partial(self._reset_scene, mask))) + 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))) + 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: @@ -271,12 +371,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 @@ -285,23 +386,62 @@ 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. + # 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() 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 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.""" @@ -317,8 +457,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", @@ -336,10 +493,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}." ) @@ -349,7 +509,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. """ @@ -362,55 +522,156 @@ 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) - if cfg.compute_final_obs: - self.extras["final_obs"] = { - group: values.torch for group, values in self.transition.final_observations.items() - } 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(): + 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(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 + 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) 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.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) - ] + # 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 - 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) + 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) + # The episodes that go on after a task update keep the sums of the rewards that both tasks have. + # 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.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) + 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}[{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)) + 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 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) + 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"({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) + 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}[{k}, world] = {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: @@ -439,16 +700,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.extras["log"] = self._episode_log() + self.obs_buf = _clone(self.observations) transition = self.transition return ( @@ -459,34 +722,130 @@ def step(self, action: torch.Tensor) -> VecEnvStepReturn: self.extras, ) - 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 - for value, last, _ in self._metrics.values(): - torch.where(done, value, last, out=last) - 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) + @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/``, 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] + 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") + 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") + 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. + ``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) + 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.logical_and_(reported) + self._resets.torch.copy_(restarted) - 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] - 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) - - 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)} - if self._time_limit is not None: - log[f"Episode_Termination/{self._time_limit}"] = self._last_time_outs.float().mean() - # 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() - self.extras["log"] = log + def _after_evaluate(self) -> None: + """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() + 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=1) + 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]]: + """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..3ab2d76f0fee 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, 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 c9332bcffd18..a5a76e2cafb8 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_scene_data.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_scene_data.py @@ -13,30 +13,14 @@ import warp as wp -from isaaclab.actuators import ( - ActuatorBase, - ActuatorNetLSTMCfg, - ActuatorNetMLPCfg, - DCMotorCfg, - IdealPDActuatorCfg, - ImplicitActuatorCfg, -) +from isaaclab.actuators import ActuatorBase from isaaclab.scene import InteractiveScene -from isaaclab.sensors import BaseContactSensor, BaseJointWrenchSensor +from isaaclab.sensors import BaseContactSensor, BaseJointWrenchSensor, Camera from isaaclab.sim import SimulationContext from isaaclab.utils.warp import ProxyArray 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.""" - -NEWTON_NETWORK_ACTUATORS = (ActuatorNetLSTMCfg, ActuatorNetMLPCfg) -"""Actuator network configs that MDP2 supports when Newton runs them as its own neural drives -(``use_newton_actuators``), not as Isaac Lab's Torch models. Newton resets them. Newton cannot capture networks loaded -from TorchScript checkpoints, so for them the environment runs the physics and the scene reset between its graphs.""" - class InteractiveSceneData: """Live views of the asset data of an :class:`InteractiveScene`, by scene entity name and field. @@ -67,6 +51,10 @@ class InteractiveSceneData: Joint wrench sensors provide ``force`` [N] and ``torque`` [N·m] as ``wp.vec3f`` per world and body, in the incoming joint frame. + 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 @@ -130,20 +118,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. Actuator - # networks are supported where Newton runs them, not Isaac Lab's Torch models. - unsupported = sorted( - group - for group, cfg in asset.cfg.actuators.items() - if type(cfg) not in CAPTURED_ACTUATORS - and (type(cfg) not in NEWTON_NETWORK_ACTUATORS or isinstance(asset.actuators[group], ActuatorBase)) - ) + # 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 supports {', '.join(cfg.__name__ for cfg in CAPTURED_ACTUATORS)}, and" - f" {', '.join(cfg.__name__ for cfg in NEWTON_NETWORK_ACTUATORS)} that Newton runs, but" - f" '{name}' has the 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 |= { "body_com_vel_w": data.body_com_vel_w, @@ -246,6 +226,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)) @@ -326,3 +328,12 @@ 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 + # Newton runs and resets its own actuators; where it cannot capture them, the physics runs between the graphs. + return True diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_verify.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_verify.py index ab94945c09b3..6552179099e0 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,30 +31,29 @@ 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 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 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) - 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) @@ -92,6 +95,10 @@ 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 + 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/isaaclab_experimental/mdp2/__init__.pyi b/source/isaaclab_experimental/isaaclab_experimental/mdp2/__init__.pyi index 7173160d476a..071bcb615ace 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/__init__.pyi +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/__init__.pyi @@ -5,8 +5,11 @@ __all__ = [ "MDP", + "Action", + "ActionRate", "CapturedMDP", "Backend", + "Columns", "Command", "Constant", "DirectAction", @@ -19,7 +22,10 @@ __all__ = [ "Implementation", "MDPBuilder", "MDPState", + "Milestone", "Observation", + "ObservationGroup", + "ObservationSlot", "Phase", "Quantity", "ExecutionPlan", @@ -28,32 +34,50 @@ __all__ = [ "SceneData", "SceneSchema", "Segment", + "Spec", "State", "Step", "StepKind", "SubsetSelector", "TaskCfg", + "TaskMode", + "TaskNode", + "TaskSelector", + "TaskTree", "Term", "TermCfg", "TermContext", "Termination", "TimeLimit", + "Tunable", + "TunedValue", "UniformNoise", "Transition", "WorldConfig", "apply_actions", + "choice", "commands", + "compose", "episode_length", "evaluate", "last_action", + "migrate", "observe", + "process_actions", + "progress", + "progress_field", "quantities", + "rename", "reset", + "sequence", + "split", "startup", "step_dt", "term_state", "terminated", "time_out", + "tunable", + "tune", "uniform", "mdp", ] @@ -61,8 +85,10 @@ __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, Columns, MDPState, Spec, Transition, WorldConfig from .config import ( + Action, + ActionRate, Command, Constant, DirectAction, @@ -70,28 +96,41 @@ from .config import ( Event, EventMode, FieldSelector, + Milestone, Observation, + ObservationGroup, Phase, Quantity, Reward, SubsetSelector, TaskCfg, + TaskMode, + TaskSelector, TermCfg, Termination, TimeLimit, + Tunable, UniformNoise, + choice, commands, + compose, episode_length, last_action, + progress, + progress_field, quantities, + rename, + sequence, + split, step_dt, term_state, terminated, time_out, + tunable, ) from .eager import TermContext -from .plan import ExecutionPlan, Segment, Step, StepKind +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, 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/builder.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py index cf27376ba3e2..8640d087e959 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py @@ -25,6 +25,9 @@ from . import torch_backend, warp_backend from .compiled import MDP, Backend, WorldConfig from .config import ( + PROGRESS_FIELDS, + Action, + ActionRate, Command, DirectAction, Entity, @@ -37,19 +40,35 @@ Reward, SubsetSelector, TaskCfg, + TaskMode, TermCfg, Termination, TimeLimit, + Tunable, commands, episode_length, + group_terms, last_action, + progress_field, quantities, step_dt, term_state, terminated, time_out, + tunable, +) +from .plan import ( + ActionOp, + ActionSlot, + ObservationOutput, + ObservationSlot, + Segment, + TaskNode, + TaskTree, + TermOp, + TunedValue, + build_plan, ) -from .plan import ActionOp, ObservationOutput, Segment, TermOp, build_plan from .scene import SceneSchema from .terms import Implementation, hook_arguments @@ -59,7 +78,20 @@ 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 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 + 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) @@ -78,6 +110,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.""" @@ -87,17 +126,19 @@ 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 () @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)] + tunables += [self.when] if isinstance(self.cfg.when, Tunable) else [] + return (*(selector for selector in self.writes if not selector.scene), *state, *tunables) @dataclass(frozen=True) @@ -126,8 +167,11 @@ 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 + 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: @@ -142,7 +186,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. @@ -153,35 +200,95 @@ 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], + 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, ``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 + 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: + 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) + restarts = restarts or task.repeat + stage = task_path if staged or restarts else None + 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: + # 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.") + # Reset and startup events set up whole episodes, so they run in every world of their task. + 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)) + 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(): + 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) + in_sequence = staged or task.mode in (TaskMode.SEQUENCE, TaskMode.CHOICE) + 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)) def add_command(self, name: str, command: Command) -> ScheduleEntry: @@ -193,8 +300,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)) @@ -307,34 +422,37 @@ 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 in (TaskMode.SEQUENCE, TaskMode.CHOICE) + for _, tasks, _ in configs + 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, worlds) in enumerate(configs): - context, time_limit = self._compile_schedule(schedule, 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]: @@ -342,8 +460,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.") @@ -351,6 +469,16 @@ 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) + 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] = {} @@ -373,12 +501,30 @@ 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) - 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( @@ -386,37 +532,85 @@ def _compile( device=device, backend=backend, ops=ops, - plan=build_plan(ops, self.schema), + plan=build_plan(ops, self.schema, trees, slots, tuned), 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, + 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( - self, schedule: tuple[ScheduleEntry, ...], backend: Backend + 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 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()} + 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"): + context.mdp_fields[progress_field(path, name)] = ArrayLayout(wp.bool, 1, {}) + 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, {}) # 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: 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. + # 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 + + 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. 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: @@ -427,42 +621,80 @@ 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) + 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. 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) - - return context, time_limit + 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: + """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 + 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.") + 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: + 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.") + 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, + repeat=task.repeat, + weights=weights, + ) def _compile_action(self, entry: ScheduleEntry, context: CompileContext) -> None: """Compile an action use into an op, or record why it cannot be compiled.""" @@ -485,7 +717,18 @@ def _compile_action(self, entry: ScheduleEntry, context: CompileContext) -> None return indices = context.subsets[cfg.subset] elements = set(indices) + # 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) + 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]: + 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}'.") @@ -509,12 +752,7 @@ def _compile_action(self, entry: ScheduleEntry, context: CompileContext) -> None if cfg.clip is not None and not isinstance(cfg.clip, dict): clip = (cfg.clip,) * len(indices) - columns = slice(context.action_dim, context.action_dim + len(indices)) - 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, scale, cfg.offset, subset=cfg.subset, clip=clip) + action = replace(action, scale=scale, clip=clip) context.ops[Phase.ACTIONS].append(action) def _compile_term(self, entry: ScheduleEntry, context: CompileContext) -> None: @@ -525,12 +763,16 @@ 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}.") + 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} @@ -546,15 +788,21 @@ 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)): 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 = {} @@ -563,12 +811,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, Quantity) and cfg.log and output_shape: - errors.append(f"{entry}: a logged 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, Event): + _check_event(entry, errors) + 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: @@ -576,27 +822,28 @@ 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 # 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: - 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. 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") else: extra = "out" if implementation is term.warp else None @@ -615,13 +862,11 @@ 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) + 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) @@ -639,9 +884,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( { @@ -653,7 +900,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, @@ -662,10 +911,71 @@ 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, + 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 "", + rate=cfg.rate if isinstance(cfg, Action) else ActionRate.PHYSICS, + labels=labels, + 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 _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): @@ -743,6 +1053,109 @@ 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): + # 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 + + +def _check_event(entry: ScheduleEntry, errors: list[str]) -> None: + """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.") + + +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 _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 [] + values += [TunedValue(f"{op.use}.when", op.when, dtype=wp.bool)] if op.when_default is not None else [] + for value in values: + 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()) + + def _dimension_sizes(fields: Mapping[str, ArrayLayout | None]) -> dict[str, int]: """Return the size of each named dimension of a term's inputs. @@ -788,7 +1201,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( @@ -890,3 +1312,293 @@ 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, 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. 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) + 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()} + # 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]: + """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: + 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.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) + + +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_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]]]: + """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}.") + # 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( + 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.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 + + +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 + 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 _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.""" + 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, 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 + 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 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) + ), + None, + ) + if match is None: + kept.append(op) + continue + other = kept[match] + kept[match] = _scoped_to(replace(other, stage=None, stages=(*_stages(other), op.stage)), context) + 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, as do tasks' completions. + for ops in context.ops.values(): + for k, op in enumerate(ops): + 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]: + """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/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/compiled.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py index 2f82b73cb5c6..94ff118d75b6 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py @@ -11,9 +11,11 @@ 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 @@ -24,13 +26,27 @@ FieldSelector, Phase, SubsetSelector, + TaskMode, episode_length, last_action, + progress_field, term_state, terminated, time_out, ) -from .plan import ActionOp, ExecutionPlan, Launches, Segment, TermOp, segments +from .plan import ( + ActionOp, + ActionSlot, + ExecutionPlan, + Launches, + ObservationSlot, + Segment, + Step, + TaskTree, + TermOp, + TunedValue, + segments, +) from .scene import SceneData, SceneSchema @@ -49,8 +65,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; @@ -58,8 +72,17 @@ 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; - - ``"interval_worlds"``: the worlds where an interval event that writes scene fields ran in the last - ``evaluate``, for an MDP with such events. + - ``("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 + 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"``: 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] @@ -85,6 +108,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: @@ -107,10 +135,32 @@ 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 +@dataclass(frozen=True) +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 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) class MDP: """An immutable, compiled MDP, created with :meth:`MDPBuilder.finalize`.""" @@ -121,32 +171,35 @@ 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 + 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 @property 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 @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, ...]: @@ -174,17 +227,94 @@ 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) + 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. + + 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) + observations = { + buffer: tuple( + 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. + + 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. + + 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 = [ @@ -194,11 +324,26 @@ 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}") + 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 [] + details += ["repeat"] if node.repeat 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}"] if op.clip is not None: @@ -218,6 +363,9 @@ 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 [] + 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] contiguous = op.worlds == tuple(range(first, last + 1)) @@ -230,7 +378,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) @@ -246,17 +394,25 @@ def state(self, scene_data: SceneData, seed: int = 0) -> MDPState: terminated: self._zeros(self.num_worlds, dtype=wp.bool), time_out: 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) + 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. + 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 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(): arrays[subset] = ProxyArray(wp.array(indices, dtype=wp.int32, device=self.device)) - for op in self.ops[Phase.ACTIONS]: - if isinstance(op.scale, tuple): - arrays["action_scale", op.name] = ProxyArray(wp.array(op.scale, dtype=wp.float32, device=self.device)) - if op.clip is not None: - arrays["action_clip", op.name] = ProxyArray(wp.array(op.clip, dtype=wp.vec2f, device=self.device)) + arrays |= self._direct_action_arrays() # State belongs to the use: the ops that other world configs define differently share it. for op in self.term_ops: for name, spec in op.state.items(): @@ -268,13 +424,15 @@ 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) ] 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) @@ -285,8 +443,14 @@ 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.interval_writes: - arrays["interval_worlds"] = self._zeros(self.num_worlds, dtype=wp.bool) + if self.tuned: + # 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)) + 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) @@ -297,10 +461,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: @@ -314,13 +478,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 {}), @@ -329,9 +500,61 @@ def state(self, scene_data: SceneData, seed: int = 0) -> MDPState: return MDPState(arrays=arrays, arguments=arguments, scene_data=scene_data, caches=caches) + def _direct_action_arrays(self) -> dict[Hashable, ProxyArray]: + """Allocate the per-element scales and clip ranges of the direct actions that have them.""" + arrays = {} + for op in self.ops[Phase.ACTIONS]: + if not isinstance(op, ActionOp): + continue # Action terms write their outputs themselves + if isinstance(op.scale, tuple): + arrays["action_scale", op.name] = ProxyArray(wp.array(op.scale, dtype=wp.float32, device=self.device)) + if op.clip is not None: + arrays["action_clip", op.name] = ProxyArray(wp.array(op.clip, dtype=wp.vec2f, device=self.device)) + return arrays + + 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 in (TaskMode.SEQUENCE, TaskMode.CHOICE): + 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_) + 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} + 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.""" @@ -353,3 +576,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 1e7f3e6eea66..8e5c1fbbee85 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 @@ -43,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) @@ -140,6 +144,27 @@ 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``. + + 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. 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 param ``name`` of a use, or its tunable ``when``: ``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``.""" @@ -157,8 +182,13 @@ 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) + # 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 = field(default=None, kw_only=True) @dataclass @@ -173,7 +203,9 @@ 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 + # 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 @dataclass @@ -192,13 +224,35 @@ 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.""" 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 @@ -226,9 +280,10 @@ 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. 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 @@ -237,6 +292,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] @@ -250,6 +306,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: """Write ``scale * action + offset`` to an entity field, clipping the result if configured. @@ -265,17 +328,219 @@ class DirectAction: 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") clip: tuple[float, float] | dict[str, tuple[float, float]] | None = None + rate: ActionRate = ActionRate.PHYSICS + + +@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, 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 + + outputs: dict[str, FieldSelector] = field(default_factory=dict) # Passed by argument name; the action writes them + rate: ActionRate = ActionRate.PHYSICS + + +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 + CHOICE = enum.auto() # One per episode and world, drawn at the reset @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. + + 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 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 | None] = field(default_factory=dict) + 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 + # 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 + 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) +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, + 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, repeat=repeat, **fields) + + +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 or a choice runs, and how often a task that repeats was +done.""" + + +@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.repeat = core.repeat + composed.subtasks, composed.mode = dict(core.subtasks), core.mode + 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.") + 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 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, 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): + 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.""" + 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 + 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/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/mdp/__init__.pyi b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi index 1b0d780fc75a..240ebc92934b 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/__init__.pyi @@ -4,6 +4,14 @@ # SPDX-License-Identifier: BSD-3-Clause __all__ = [ + "Choice", + "Replay", + "Uniform", + "choice_variation", + "replay_variation", + "uniform_variation", + "variation", + "binary_joint_position", "heading_velocity_command", "heading_velocity_command_steered_on_resample", "uniform_pose_command", @@ -23,7 +31,10 @@ __all__ = [ "base_lin_vel", "body_incoming_wrench", "generated_commands", + "image_rgb", + "one_hot", "joint_pos", + "joint_pos_normalized", "joint_pos_limit_normalized", "joint_pos_rel", "joint_vel", @@ -59,16 +70,19 @@ __all__ = [ "track_lin_vel_xy_exp", "track_lin_vel_xy_yaw_frame_exp", "undesired_contacts", + "resting_on", "value", "bad_orientation", "illegal_contact", "is_positive", + "is_true", "joint_pos_out_of_manual_limit", "joint_vel_out_of_limit", "pose_command_success", "root_height_below_minimum", ] +from .actions import binary_joint_position from .commands import ( heading_velocity_command, heading_velocity_command_steered_on_resample, @@ -93,7 +107,10 @@ from .observations import ( base_lin_vel, body_incoming_wrench, generated_commands, + image_rgb, + one_hot, joint_pos, + joint_pos_normalized, joint_pos_limit_normalized, joint_pos_rel, joint_vel, @@ -130,6 +147,7 @@ from .rewards import ( track_ang_vel_z_world_exp, track_lin_vel_xy_exp, track_lin_vel_xy_yaw_frame_exp, + resting_on, undesired_contacts, value, ) @@ -137,8 +155,10 @@ from .terminations import ( bad_orientation, illegal_contact, is_positive, + is_true, joint_pos_out_of_manual_limit, joint_vel_out_of_limit, pose_command_success, 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/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/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/isaaclab_experimental/mdp2/mdp/observations.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/observations.py index 1e74c5e852c2..6e62ead9fc41 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. @@ -267,3 +288,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/rewards.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/rewards.py index 96fe4c837af4..68dc074c82c0 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/rewards.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/rewards.py @@ -73,6 +73,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. diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/terminations.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/terminations.py index 550032d5cf84..3f2ff300730e 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/mdp/variations.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/variations.py new file mode 100644 index 000000000000..f696387828f1 --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/mdp/variations.py @@ -0,0 +1,191 @@ +# 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) + # Modulo the table, so that the count stays exact in float32. + taken.copy_((taken + mask.sum()) % table.shape[0]) + + +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/isaaclab_experimental/mdp2/plan.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py index d9429c514e54..e7096c1c0a06 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py @@ -15,10 +15,20 @@ 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 -from .config import Entity, FieldSelector, Phase, SubsetSelector, UniformNoise, last_action +from .config import ( + ActionRate, + Entity, + FieldSelector, + Phase, + SubsetSelector, + TaskMode, + UniformNoise, + progress_field, +) from .terms import State if TYPE_CHECKING: @@ -34,12 +44,23 @@ 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 | tuple[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 clip: tuple[tuple[float, float], ...] | None = None + 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: + """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) @dataclass(frozen=True) @@ -53,6 +74,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) @@ -73,6 +96,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 @@ -83,17 +109,51 @@ 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 + 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 - # 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 + 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 + # 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 + # 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: + """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 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 or self.stages: + return "entered", self.name + 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] - 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): @@ -105,19 +165,130 @@ 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 + 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) +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" + 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 + + +@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 + # 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 + 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) +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 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) + 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) + + +@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.""" + + 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 | 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 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 @@ -141,74 +312,130 @@ 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, ...] -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, ...] = (), + 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. 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. ``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]) + 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 - # 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]} + 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) + ) + 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: 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)) - - reset_events = [] + 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 = [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.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 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), + ] + + # A reset prepares the ops with ``when`` in every world of their task. + 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": []} 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]), - 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, 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_TIMER, op) for op in timed), - *reset_events, - *(Step(StepKind.COMPUTE, op) for op in ops[Phase.COMMANDS]), + *([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 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, op) for op in stateful), + *(Step(StepKind.RESET_STATE, unswitched.get(op.name, op)) for op in stateful), ), - observe=(*observed, *observations), + observe=(*observed, *([Step(StepKind.SWITCH, switched)] if switched else []), *observations, *clears), ) @@ -258,6 +485,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 5df07336d190..358055b15106 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/runtime.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/runtime.py @@ -11,13 +11,17 @@ from __future__ import annotations -from collections.abc import Callable +import itertools +from collections.abc import Callable, Sequence +from typing import Any, Literal +import torch import warp as wp from isaaclab.utils.warp import ProxyArray from .compiled import MDP, MDPState, Transition +from .config import FieldSelector from .eager import call_init from .plan import Call @@ -34,8 +38,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) @@ -68,3 +81,102 @@ 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, 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. + """ + 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 + + # 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) + word, bit = divmod(mdp.tuned.index(target), 32) + flags = state.arrays["pending"].torch[:, word] + if at == "reset": + flags.bitwise_or_(selected.int() << bit) + else: + flags.bitwise_and_(~(selected.int() << bit)) + state.arrays["revision"].torch.add_(selected.int()) + + +_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, 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 or key == "revision" + carried |= 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)] + _migrate_tuned(previous, previous_state, mdp, state) + + # 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 (op.use, op.params) not in uses: + 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/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 42bd97b9adfa..1b65b408a75b 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py @@ -7,12 +7,16 @@ from __future__ import annotations +import functools +import itertools +import math + import torch from . import rng from .compiled import MDP, MDPState -from .config import FieldSelector, Phase, last_action, term_state, terminated, time_out -from .plan import Call, Launch, Launches, Step, StepKind, TermOp +from .config import FieldSelector, Phase, TaskMode, progress_field, term_state, terminated, time_out +from .plan import Call, Launch, Launches, ObservationSlot, Step, StepKind, TaskTree, TermOp, TunedValue from .terms import hook_arguments @@ -20,7 +24,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), @@ -32,15 +44,21 @@ 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) - for action_dim in mdp.narrow_action_dims: - call.state.arrays[last_action, action_dim].torch.copy_(actions[:, :action_dim]) + 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 in the worlds where it is active, ``mask``. + active = _active(op, call.state) + arguments = {**call.state.arguments[op.name], "action": actions[:, op.columns]} + 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 offset = op.offset @@ -52,12 +70,26 @@ def _apply_actions(mdp: MDP, call: Call) -> None: clip = call.state.arrays["action_clip", op.name].torch value = value.clamp(min=clip[:, 0], max=clip[:, 1]) - 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 +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 = call.state.actions.torch[:, slot.columns] + covered = torch.zeros_like(columns, dtype=torch.bool) + for op in slot.ops: + # 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: """Advance the random streams and episode lengths, and clear the results of the last step.""" state, transition = call.state, call.transition @@ -73,8 +105,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: @@ -83,15 +115,43 @@ 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): + """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 + 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 = state.arrays.get(("active", op.name)) + active = _active(op, state) + if step.entry: + 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 @@ -108,13 +168,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: @@ -172,7 +235,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 @@ -188,29 +254,36 @@ 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 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, 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 + 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: - 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: @@ -226,3 +299,220 @@ 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 _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, 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: + 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 + 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, 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 + 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 + 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: + """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] + # 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]) + 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 + holding.copy_(held.sum(1) >= required) + + 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) + # 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) + + +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) + 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) + 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) + 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): + 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) + + +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, parents first: a choice + draws its subtask.""" + 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)} + initial |= {"count": 0, "spent": False, "restarted": False} + 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) + 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 7963b9f752ad..fef77660afa7 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py @@ -14,6 +14,8 @@ from __future__ import annotations +import functools +import itertools import math from collections.abc import Callable, Hashable, Iterable, Sequence @@ -21,9 +23,20 @@ import warp as wp from .compiled import MDP -from .config import Entity, FieldSelector, Phase, episode_length, last_action, term_state, terminated, time_out +from .config import ( + Entity, + FieldSelector, + Phase, + TaskMode, + episode_length, + last_action, + progress_field, + term_state, + terminated, + time_out, +) from .fusion import Fusion -from .plan import Call, Launches, Step, StepKind, TermOp +from .plan import Call, Launches, ObservationSlot, Step, StepKind, TaskNode, TaskTree, TermOp, TunedValue from .terms import hook_arguments _RESULTS = { @@ -75,7 +88,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], ...]: @@ -84,17 +106,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)) - 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]) + 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. @@ -102,8 +120,11 @@ 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, 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]" if isinstance(op.offset, FieldSelector): @@ -128,6 +149,46 @@ 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, 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)] + 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, mdp)) + + 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)) @@ -141,9 +202,9 @@ def _evaluate(mdp: MDP) -> tuple[Callable[[Call], None], ...]: if mdp.max_episode_length is not None: limit = 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", @@ -164,13 +225,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) @@ -186,9 +246,48 @@ 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 + 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) + if step.entry: + # 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: + 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) + 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: + _reset_state(code, op, conditions) + continue match step.kind: case StepKind.COMPUTE: _compute(code, mdp, op, active, stepping) @@ -197,18 +296,18 @@ 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.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) @@ -232,7 +331,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 @@ -264,8 +363,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.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: weights = _array(code, "reward_weights", wp.array2d(dtype=wp.float32)) @@ -274,8 +377,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.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: writes = [*op.writes, *state] @@ -292,9 +399,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: @@ -315,11 +421,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( @@ -330,24 +435,30 @@ 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 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 = math.prod(op.shape), observation.history_length - 1 - if stepping: + 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", + ] + if stepping and op.entry_key is None: + update = [*shift[:-1], f"{history}[world, {last}, element] = {value}"] + elif stepping: update = [ - f"for h in range({last}):", - f" {history}[world, h, element] = {history}[world, h + 1, element]", - f"{history}[world, {last}, element] = {value}", + "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 = _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]" + 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]", @@ -424,11 +535,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] @@ -454,9 +565,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)) - else: + 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])) + 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)})" @@ -480,17 +601,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 @@ -509,6 +632,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 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) @@ -546,3 +671,321 @@ 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 = { + **dict.fromkeys(("done", "holding", "active", "entered", "spent", "restarted"), 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", "count", "spent", "restarted") + 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. A sequence that repeats advances + # again once it restarted. + stage = field("stage") + 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')}:", + f" {stage} = {k + 1}", + ] + lines += [ + 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 = [ + "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}", + ] + + 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] + 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)"] + 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)}", *kept] + weights = [child.score / sum(child.score for child in counted) for child in counted] + 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: + """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 = "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)}" + 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')}"] + 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 {fresh[0] if len(fresh) == 1 else '(' + ' or '.join(fresh) + ')'}", + 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, parents first: a choice + draws its subtask.""" + 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')} = {_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 []), + *([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)) + + +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, 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)), + ) + 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]) + + +def _apply_tuned(code: Fusion, tuned: tuple[TunedValue, ...]) -> None: + """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 = ["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) + 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: + """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_contact_terms.py b/source/isaaclab_experimental/test/envs/test_mdp2_contact_terms.py index 849128989cfd..7009650a7f17 100644 --- a/source/isaaclab_experimental/test/envs/test_mdp2_contact_terms.py +++ b/source/isaaclab_experimental/test/envs/test_mdp2_contact_terms.py @@ -263,6 +263,7 @@ def replicated_feet_slide(*shanks: str) -> mdp2.MDPBuilder: rewards = ("feet_air_time", "feet_air_time_positive_biped", "feet_air_time_variance", "feet_slide") nonzero = dict.fromkeys(rewards, False) + 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() @@ -277,6 +278,7 @@ def replicated_feet_slide(*shanks: str) -> mdp2.MDPBuilder: } for name, value in expected.items(): nonzero[name] = nonzero[name] or bool(value.abs().sum() > 0.0) + ended |= bool(illegal_contact.any()) for model, state, transition in models.values(): mdp2.evaluate(model, state, transition) @@ -291,6 +293,7 @@ def replicated_feet_slide(*shanks: str) -> mdp2.MDPBuilder: torch.testing.assert_close(feet_slide, world_scales * expected["feet_slide"]) assert all(nonzero.values()), nonzero # The feet landed and slid during the rollout. + assert ended # The feet landed hard enough to end an episode. # A reset clears the contacts that ended the last episode. env.reset() diff --git a/source/isaaclab_experimental/test/envs/test_mdp2_env.py b/source/isaaclab_experimental/test/envs/test_mdp2_env.py index d09920018dc6..2ec793bfca34 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 @@ -15,14 +16,27 @@ 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 +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.actuators import DelayedPDActuatorCfg, ImplicitActuatorCfg, RemotizedPDActuatorCfg +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")] @@ -213,7 +227,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)) @@ -257,12 +271,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"] @@ -294,14 +320,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): @@ -366,15 +392,17 @@ 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"], "steps": observation, } without_alive = replace(cfg.task, rewards={**cfg.task.rewards, "alive": None}) - cfg.task = [cfg.task, without_alive] - cfg.task_worlds = task_worlds + # 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=alive, still=without_alive, worlds=worlds) env = MDP2RLEnv(cfg) try: # Even shares, or the given number of worlds per task. @@ -391,6 +419,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() @@ -539,6 +569,69 @@ 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.""" + + +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.""" + 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))) + 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(2 * (steps - 3) / steps) + finally: + 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.""" + 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.""" @@ -633,3 +726,340 @@ 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. 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 + 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() + + +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 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() + 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.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, + "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() + 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]) + 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() + + 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() + + +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.""" + 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): + """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.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() + + +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() + + +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/envs/test_mdp2_terms.py b/source/isaaclab_experimental/test/envs/test_mdp2_terms.py index 233520f7b887..c751e42ed209 100644 --- a/source/isaaclab_experimental/test/envs/test_mdp2_terms.py +++ b/source/isaaclab_experimental/test/envs/test_mdp2_terms.py @@ -496,9 +496,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}, @@ -531,7 +537,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) @@ -539,9 +549,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() diff --git a/source/isaaclab_experimental/test/mdp2/test_mdp2.py b/source/isaaclab_experimental/test/mdp2/test_mdp2.py index d72f34ff0550..f682c30486eb 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 @@ -25,7 +27,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 +37,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 +50,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] @@ -876,7 +883,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 @@ -984,8 +991,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 = [] @@ -1014,17 +1021,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 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. + # 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, 4] == 0.0).all() + torch.testing.assert_close(policy[2:, 2], steps[1][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:, 3], 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_direct_actions_scale_and_clip_by_element_name(): @@ -1607,3 +1618,1166 @@ 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, with + its history first.""" + 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}), + "history": mdp2.Observation(joint_pos, inputs={"joint_pos": robot.joint_pos}, history_length=2), + }, + 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), + "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) + 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 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): + 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().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() + + +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: + # 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}) + 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:] == [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] + 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_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, 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")} + return mdp2.TaskCfg( + quantities={ + "reached": mdp2.Quantity(joint_above, inputs=inputs), + "held": mdp2.Quantity(generated_commands, inputs=total), + }, + # 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", 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] + # 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(): + """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_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 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): + builder = mdp2.MDPBuilder(schema) + builder.add_task(mdp2.compose(quantities, task)) + 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. A value that a term writes is not undone by a reset that applies + another.""" + 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 + 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) + 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(), + "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 CAPTURES] + 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 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] + + 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) + + +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 CAPTURES] + 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() + + +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] + + +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)) + 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() + 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 CAPTURES] + 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]] + + +@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, mask): + assert mask is None # The action applies in every world + 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 CAPTURES: + 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 + 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] 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, mask: 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 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.""" + + 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), "torch") + + +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 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(): + assert torch.equal(value, run[name]), name + + 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)) + + +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, 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")) + 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 + + +@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, 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( + 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] + + 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 + + # 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: + 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) + # 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", + "quantities.replay", + "quantities.replay_row", + ] + return history + + 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) + 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] + + +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 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, shared: float, weight: float) -> mdp2.TaskCfg: + rewards = { + "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, + quantities={"total": total}, + 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, 1.0), second=stage("b", 1.0, 2.0), third=stage("a", 3.0, 3.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) + 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 + # 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]] 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 18f4afbb326d..517d1ff21e85 100644 --- a/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py +++ b/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py @@ -190,15 +190,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: diff --git a/source/isaaclab_tasks_experimental/changelog.d/mdp2-part2.changed.rst b/source/isaaclab_tasks_experimental/changelog.d/mdp2-part2.changed.rst new file mode 100644 index 000000000000..daf83690f53d --- /dev/null +++ b/source/isaaclab_tasks_experimental/changelog.d/mdp2-part2.changed.rst @@ -0,0 +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_experimental/changelog.d/mdp2-part2.minor b/source/isaaclab_tasks_experimental/changelog.d/mdp2-part2.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/mdp2/lift_kuka_allegro/lift_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/mdp2/lift_kuka_allegro/lift_env_cfg.py index f0e7035eeb44..25e5f3cdee24 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/mdp2/lift_kuka_allegro/lift_env_cfg.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/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": { diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/mdp2/locomotion/locomotion_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/mdp2/locomotion/locomotion_env_cfg.py index fe1bc919e923..424f6120aba6 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/mdp2/locomotion/locomotion_env_cfg.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/mdp2/locomotion/locomotion_env_cfg.py @@ -29,7 +29,7 @@ quantities={ "up": mdp2.Quantity(locomotion.base_up_proj, inputs={**root, "gravity_w": scene.gravity_w}), "heading": mdp2.Quantity(locomotion.base_heading_proj, inputs=to_target, params=target), - "success_rate": mdp2.Quantity(locomotion.survival, inputs={"time_out": mdp2.time_out}, log=True), + "success_rate": mdp2.Quantity(locomotion.survival, inputs={"time_out": mdp2.time_out}, record=True), }, observations={ "policy": { diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/mdp2/reach/franka_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/mdp2/reach/franka_env_cfg.py index 057164f6ec2a..2b4cb1113f03 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/mdp2/reach/franka_env_cfg.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/mdp2/reach/franka_env_cfg.py @@ -71,10 +71,10 @@ }, quantities={ "position_error": mdp2.Quantity( - mdp.position_command_error, inputs={**pose_tracking, "body_ids": robot.bodies("panda_hand")}, log=True + mdp.position_command_error, inputs={**pose_tracking, "body_ids": robot.bodies("panda_hand")}, record=True ), "orientation_error": mdp2.Quantity( - mdp.orientation_command_error, inputs={**pose_tracking, "body_ids": robot.bodies("panda_hand")}, log=True + mdp.orientation_command_error, inputs={**pose_tracking, "body_ids": robot.bodies("panda_hand")}, record=True ), }, rewards={ diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/mdp2/reach/ur10_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/mdp2/reach/ur10_env_cfg.py index ffcc95bc31d1..fea996449aba 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/mdp2/reach/ur10_env_cfg.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/mdp2/reach/ur10_env_cfg.py @@ -45,10 +45,10 @@ }, quantities={ "position_error": mdp2.Quantity( - mdp.position_command_error, inputs={**pose_tracking, "body_ids": robot.bodies("ee_link")}, log=True + mdp.position_command_error, inputs={**pose_tracking, "body_ids": robot.bodies("ee_link")}, record=True ), "orientation_error": mdp2.Quantity( - mdp.orientation_command_error, inputs={**pose_tracking, "body_ids": robot.bodies("ee_link")}, log=True + mdp.orientation_command_error, inputs={**pose_tracking, "body_ids": robot.bodies("ee_link")}, record=True ), }, rewards={ diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/mdp2/velocity_go2/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/mdp2/velocity_go2/flat_env_cfg.py index cd2490992bd9..60a121e85ab5 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/mdp2/velocity_go2/flat_env_cfg.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/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_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 diff --git a/source/isaaclab_tasks_experimental/test/mdp2/test_lift_kuka_allegro.py b/source/isaaclab_tasks_experimental/test/mdp2/test_lift_kuka_allegro.py index 54fe224aa796..b302aceafbc5 100644 --- a/source/isaaclab_tasks_experimental/test/mdp2/test_lift_kuka_allegro.py +++ b/source/isaaclab_tasks_experimental/test/mdp2/test_lift_kuka_allegro.py @@ -263,10 +263,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.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"]