From d21b3265ab97079fae937f9a7286c4ad9173ce91 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Mon, 30 Nov 2026 17:44:12 -0800 Subject: [PATCH 1/7] Keep tracked MDP2 subtasks out of their parent's completion and score Arena's tracked events record when something happens, such as a drop, without changing what counts as success. MDP2 already counts such events with repeat=True, but every subtask with a completion counted towards its parent, so composing a drop counter beside the task made success require a drop and diluted the score, as logged in Progress/task and recorded in progress/score. tracked=True keeps a subtask's own progress (done, done_at, count, and its log and record columns) and drops it from TaskTree.counted, which drives the parent's completion, holding, final checks, and score in both backends. Only subtasks that run together can be tracked: a sequence, choice, or split needs each subtask to complete or run in turn. --- docs/source/experimental-features/mdp2.rst | 13 ++++++++- .../mh-mdp2-tracked-tasks.added.rst | 3 ++ .../changelog.d/mh-mdp2-tracked-tasks.minor | 0 .../isaaclab_experimental/envs/mdp2_env.py | 2 +- .../isaaclab_experimental/mdp2/builder.py | 22 +++++++++++---- .../isaaclab_experimental/mdp2/compiled.py | 1 + .../isaaclab_experimental/mdp2/config.py | 8 ++++-- .../isaaclab_experimental/mdp2/plan.py | 7 +++-- .../test/envs/test_mdp2_env.py | 8 ++++-- .../test/mdp2/test_mdp2.py | 28 +++++++++++++++++-- 10 files changed, 77 insertions(+), 15 deletions(-) create mode 100644 source/isaaclab_experimental/changelog.d/mh-mdp2-tracked-tasks.added.rst create mode 100644 source/isaaclab_experimental/changelog.d/mh-mdp2-tracked-tasks.minor diff --git a/docs/source/experimental-features/mdp2.rst b/docs/source/experimental-features/mdp2.rst index 2e9e1eec5f4a..de3a5a04f4b5 100644 --- a/docs/source/experimental-features/mdp2.rst +++ b/docs/source/experimental-features/mdp2.rst @@ -149,6 +149,17 @@ 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. +- **Tracked tasks.** ``tracked=True`` keeps a subtask out of its parent's completion and score, for an event to watch + rather than a goal. It keeps its own progress, which the environment logs and records like any other, and only a + subtask that runs together with others can be tracked, so the task it watches becomes a named subtask too: + + .. code-block:: python + + TASK = mdp2.compose( + BASE, + place=mdp2.sequence(...), # Done and scored as the task + drops=mdp2.Milestone(q.dropped, hold=10, repeat=True, tracked=True), # Counted as progress.drops.count + ) - **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 @@ -331,7 +342,7 @@ Porting from Arena * - ``object_on_destination`` - :data:`~isaaclab_experimental.mdp2.mdp.resting_on`, held with ``hold`` * - tracked events - - ``repeat=True``, counted as ``progress..count`` + - a subtask with ``repeat=True, tracked=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 diff --git a/source/isaaclab_experimental/changelog.d/mh-mdp2-tracked-tasks.added.rst b/source/isaaclab_experimental/changelog.d/mh-mdp2-tracked-tasks.added.rst new file mode 100644 index 000000000000..7473e7e9050e --- /dev/null +++ b/source/isaaclab_experimental/changelog.d/mh-mdp2-tracked-tasks.added.rst @@ -0,0 +1,3 @@ +* Added ``tracked`` to :class:`~isaaclab_experimental.mdp2.TaskCfg` and :class:`~isaaclab_experimental.mdp2.Milestone`. + A tracked subtask keeps its own progress, such as how often an object drops, but stays out of its parent's + completion and score, so watching an event does not change what counts as success. diff --git a/source/isaaclab_experimental/changelog.d/mh-mdp2-tracked-tasks.minor b/source/isaaclab_experimental/changelog.d/mh-mdp2-tracked-tasks.minor 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 ffb3da933d5f..2a3e6e412108 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py @@ -760,7 +760,7 @@ def _init_episode_budget(self, budget: int) -> None: 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: + if "" in completes: # Not for a task whose only completions are tracked 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)) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py index 8640d087e959..88fa9a70cb14 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py @@ -666,7 +666,15 @@ def _compile_task(self, path: str, tasks: dict[str, tuple[TaskCfg, bool]], conte 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.tracked and not path: + errors.append(f"{name}: only a subtask can be tracked.") + tracked = [child for child, subtask in task.subtasks.items() if subtask.tracked] + if tracked and task.mode is not TaskMode.TOGETHER: + mode = task.mode.name.lower() + errors.append(f"{name}: only subtasks that run together can be tracked, not {tracked} of a {mode}.") + completes = [ + child for child, subtask in task.subtasks.items() if _has_completion(subtask) and not subtask.tracked + ] 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.") @@ -693,6 +701,7 @@ def _compile_task(self, path: str, tasks: dict[str, tuple[TaskCfg, bool]], conte require=task.require, staged=staged, repeat=task.repeat, + tracked=task.tracked, weights=weights, ) @@ -1407,14 +1416,17 @@ def _scoped(cfg: object, scope: Mapping[FieldSelector, FieldSelector]) -> object def _has_completion(task: TaskCfg) -> bool: - return task.done is not None or any(_has_completion(subtask) for subtask in task.subtasks.values()) + """Return whether a task has a completion: a done, or a subtask that has one and is not tracked.""" + return task.done is not None or any( + _has_completion(subtask) and not subtask.tracked 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() + """Return the paths of the tasks of a tree that have a completion, of their own or from untracked subtasks.""" + completes, tracked = set(), {node.path for node in nodes if node.tracked} for node in reversed(nodes): - if node.done is not None or any(child in completes for child in node.children): + if node.done is not None or any(child in completes and child not in tracked for child in node.children): completes.add(node.path) return completes diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py index 94ff118d75b6..06965234219e 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py @@ -337,6 +337,7 @@ def describe(self) -> str: details += [f"final {node.final}"] if node.final is not None else [] details += ["staged"] if node.staged else [] details += ["repeat"] if node.repeat else [] + details += ["tracked"] if node.tracked else [] lines.append(f" {node.path or '(root)'} {', '.join(details)}".rstrip()) for phase, ops in self.ops.items(): diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py index 8e5c1fbbee85..3f2946117098 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py @@ -387,6 +387,9 @@ class TaskCfg: # 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 + # Keep the task's progress out of its parent's completion and score, for an event to watch rather than a goal, such + # as drops of an object. Only a subtask of a task that runs its subtasks together can be tracked + tracked: bool = False subtasks: dict[str, TaskCfg] = field(default_factory=dict) mode: TaskMode = TaskMode.TOGETHER @@ -406,10 +409,11 @@ def __init__( score: float = 1.0, final: bool | None = None, repeat: bool = False, + tracked: 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) + super().__init__(done=done, hold=hold, score=score, final=final, repeat=repeat, tracked=tracked, **fields) PROGRESS_FIELDS = ("done", "holding", "active", "score", "done_at", "started_at", "stage", "count") @@ -485,7 +489,7 @@ def merge(path: tuple[str, ...], target: dict, uses: dict, index: int) -> None: elif cores: core = cores[0] composed.done, composed.hold, composed.score, composed.final = core.done, core.hold, core.score, core.final - composed.repeat = core.repeat + composed.repeat, composed.tracked = core.repeat, core.tracked composed.subtasks, composed.mode = dict(core.subtasks), core.mode composed.require, composed.worlds, composed.weights = core.require, core.worlds, core.weights if subtasks: diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py index e7096c1c0a06..515e409913cd 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py @@ -200,6 +200,7 @@ class TaskNode: # ancestors repeats staged: bool repeat: bool = False + tracked: bool = False # Kept out of its parent's completion and score weights: tuple[float, ...] = () # Choice: the chance of each subtask stream: int | None = None # Choice: row of MDPState.rng that draws the subtask @@ -245,8 +246,10 @@ def descendants(self, node: TaskNode) -> tuple[TaskNode, ...]: 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) + """Return the subtasks of a task that count towards its completion: those that have one and are not tracked.""" + return tuple( + self.node(child) for child in node.children if child in self.completes and not self.node(child).tracked + ) @dataclass(frozen=True) diff --git a/source/isaaclab_experimental/test/envs/test_mdp2_env.py b/source/isaaclab_experimental/test/envs/test_mdp2_env.py index 2ec793bfca34..2e25830b0865 100644 --- a/source/isaaclab_experimental/test/envs/test_mdp2_env.py +++ b/source/isaaclab_experimental/test/envs/test_mdp2_env.py @@ -613,10 +613,11 @@ def test_env_runs_the_tasks_of_a_sequence_in_turn_and_logs_their_progress(): 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.""" + world, most of which finished none. A tracked task that is never done leaves the task's progress alone.""" 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))) + late = replace(stage(10**6), tracked=True) + cfg.task = mdp2.compose(cfg.task, warm=stage(3), hold=stage(6), late=late) cfg.episode_budget = 1 env = MDP2RLEnv(cfg) try: @@ -628,6 +629,9 @@ def test_progress_is_logged_over_the_episodes_that_ran(): 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 + assert log["Progress/late"] == 0.0 + records = env.episode_records() + assert records["progress/late"].item() == -1 and records["progress/score"].item() == 1.0 finally: env.close() diff --git a/source/isaaclab_experimental/test/mdp2/test_mdp2.py b/source/isaaclab_experimental/test/mdp2/test_mdp2.py index f682c30486eb..d30f9bdb59df 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2.py @@ -2004,15 +2004,20 @@ def test_splits_divide_the_same_worlds_and_may_be_steps_of_a_sequence(): def test_task_trees_report_errors(): - """A sequence task without a completion, a task with subtasks and a done, and a choice that cannot draw are - errors.""" + """A sequence task without a completion, a task with subtasks and a done, a choice that cannot draw, and a tracked + task that does not run together with others are errors.""" schema = PointMassScene(num_worlds=2, joint_names=("a",)).schema quantities = mdp2.TaskCfg(quantities=above("a")) milestone = mdp2.Milestone(mdp2.quantities.a) + tracked = mdp2.Milestone(mdp2.quantities.a, tracked=True) 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"), + (mdp2.sequence(first=milestone, second=tracked), "can be tracked"), + (mdp2.choice(first=milestone, second=tracked), "can be tracked"), + (mdp2.split(first=milestone, second=tracked), "can be tracked"), + (tracked, "can be tracked"), ] for task, message in cases: with pytest.raises(ValueError, match=message): @@ -2260,6 +2265,25 @@ def test_tasks_that_repeat_count_each_time_they_are_done(): assert [step["stage"].item() for step in history] == [1, 2, 0, 1, 2] +def test_tracked_tasks_keep_their_progress_out_of_their_parent(): + """A tracked subtask, such as the drops of an object, counts its completions, but its parent is done and scored + by the other subtasks alone.""" + task = mdp2.compose( + mdp2.TaskCfg(quantities=above("placed", "dropped")), + place=mdp2.Milestone(mdp2.quantities.placed), + drops=mdp2.Milestone(mdp2.quantities.dropped, repeat=True, tracked=True), + ) + # Dropped at steps 2 and 4, placed at step 5. + history = check_progress(task, [[0.0, 0.0], [0.0, 1.0], [0.0, 0.0], [0.0, 1.0], [1.0, 0.0]]) + assert [step["drops.count"].item() for step in history] == [0, 1, 1, 2, 2] + assert history[-1]["drops.done_at"].item() == 2 + assert [step["score"].item() for step in history] == [0.0, 0.0, 0.0, 0.0, 1.0] + assert [step["done"].item() for step in history] == [False] * 4 + [True] + + # Done without any drop. + assert check_progress(task, [[1.0, 0.0]])[0]["done"].item() + + 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.""" From 1bb2dc7b05acb10a19e742920410905ccccd1a6c Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Mon, 30 Nov 2026 17:51:05 -0800 Subject: [PATCH 2/7] Test tracked sequences, tracked-only tasks, and keep the env test's sequence --- .../test/envs/test_mdp2_env.py | 6 ++--- .../test/mdp2/test_mdp2.py | 23 +++++++++++++++++++ 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/source/isaaclab_experimental/test/envs/test_mdp2_env.py b/source/isaaclab_experimental/test/envs/test_mdp2_env.py index 2e25830b0865..1b260609b6bb 100644 --- a/source/isaaclab_experimental/test/envs/test_mdp2_env.py +++ b/source/isaaclab_experimental/test/envs/test_mdp2_env.py @@ -617,7 +617,7 @@ def test_progress_is_logged_over_the_episodes_that_ran(): cfg = cartpole_cfg() cfg.task.terminations["cart_out_of_bounds"] = None late = replace(stage(10**6), tracked=True) - cfg.task = mdp2.compose(cfg.task, warm=stage(3), hold=stage(6), late=late) + cfg.task = mdp2.compose(cfg.task, steps=mdp2.sequence(warm=stage(3), hold=stage(6)), late=late) cfg.episode_budget = 1 env = MDP2RLEnv(cfg) try: @@ -628,8 +628,8 @@ def test_progress_is_logged_over_the_episodes_that_ran(): 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 - assert log["Progress/late"] == 0.0 + assert log["Progress/steps.warm"] == 1.0 and log["Progress/steps.hold"] == 1.0 + assert log["Progress/task"] == 1.0 and log["Progress/late"] == 0.0 records = env.episode_records() assert records["progress/late"].item() == -1 and records["progress/score"].item() == 1.0 finally: diff --git a/source/isaaclab_experimental/test/mdp2/test_mdp2.py b/source/isaaclab_experimental/test/mdp2/test_mdp2.py index d30f9bdb59df..830072525607 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2.py @@ -2283,6 +2283,29 @@ def test_tracked_tasks_keep_their_progress_out_of_their_parent(): # Done without any drop. assert check_progress(task, [[1.0, 0.0]])[0]["done"].item() + # Arena's dropped object: lifted for 2 steps, then dropped for 2 steps, counted each time, beside the task. + drops = mdp2.sequence( + lifted=mdp2.Milestone(mdp2.quantities.lifted, hold=2), dropped=mdp2.Milestone(mdp2.quantities.dropped, hold=2) + ) + task = mdp2.compose( + mdp2.TaskCfg(quantities=above("placed", "lifted", "dropped")), + place=mdp2.Milestone(mdp2.quantities.placed), + drops=dataclasses.replace(drops, repeat=True, tracked=True), + ) + cycle = [[0.0, 1.0, 0.0]] * 2 + [[0.0, 0.0, 1.0]] * 3 + [[0.0, 0.0, 0.0]] + history = check_progress(task, cycle * 2) + assert [step["drops.count"].item() for step in history] == [0] * 3 + [1] * 6 + [2] * 3 + assert not any(step["done"].item() or step["score"].item() for step in history) + + # A task whose only completion is tracked has none of its own. + task = mdp2.compose( + mdp2.TaskCfg(quantities=above("dropped")), + drops=mdp2.Milestone(mdp2.quantities.dropped, repeat=True, tracked=True), + ) + history = check_progress(task, [[1.0], [0.0], [1.0]]) + assert [step["drops.count"].item() for step in history] == [1, 1, 2] + assert not any(step["done"].item() for step in history) + 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 From 75922bf25e821804866f2f3e57a2315e85de1435 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Tue, 1 Dec 2026 15:18:45 -0800 Subject: [PATCH 3/7] Record each time a repeating MDP2 task is done with an episode budget --- docs/source/experimental-features/mdp2.rst | 6 ++- .../mh-mdp2-tracked-tasks.added.rst | 2 + .../isaaclab_experimental/envs/mdp2_env.py | 47 +++++++++++++++++++ .../test/envs/test_mdp2_env.py | 33 +++++++++++++ 4 files changed, 87 insertions(+), 1 deletion(-) diff --git a/docs/source/experimental-features/mdp2.rst b/docs/source/experimental-features/mdp2.rst index de3a5a04f4b5..c41a3a71105e 100644 --- a/docs/source/experimental-features/mdp2.rst +++ b/docs/source/experimental-features/mdp2.rst @@ -267,6 +267,9 @@ episode ended. - **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. + :meth:`~isaaclab_experimental.envs.MDP2RLEnv.episode_events` returns, for each task that repeats, a row per time it + was done: its world, episode, and step, which join the episode's record. Its rows fit any run, as a task repeats at + most once per step, but they need a time limit. .. code-block:: python @@ -342,7 +345,8 @@ Porting from Arena * - ``object_on_destination`` - :data:`~isaaclab_experimental.mdp2.mdp.resting_on`, held with ``hold`` * - tracked events - - a subtask with ``repeat=True, tracked=True``, counted as ``progress..count`` + - a subtask with ``repeat=True, tracked=True``, counted as ``progress..count``, each time it was done in + ``env.episode_events()[]`` * - run-time variations and their JSONL records - :func:`~isaaclab_experimental.mdp2.mdp.variation`, with ``episode_budget`` records * - per-episode results diff --git a/source/isaaclab_experimental/changelog.d/mh-mdp2-tracked-tasks.added.rst b/source/isaaclab_experimental/changelog.d/mh-mdp2-tracked-tasks.added.rst index 7473e7e9050e..ad5f4d479444 100644 --- a/source/isaaclab_experimental/changelog.d/mh-mdp2-tracked-tasks.added.rst +++ b/source/isaaclab_experimental/changelog.d/mh-mdp2-tracked-tasks.added.rst @@ -1,3 +1,5 @@ * Added ``tracked`` to :class:`~isaaclab_experimental.mdp2.TaskCfg` and :class:`~isaaclab_experimental.mdp2.Milestone`. A tracked subtask keeps its own progress, such as how often an object drops, but stays out of its parent's completion and score, so watching an event does not change what counts as success. +* Added :meth:`~isaaclab_experimental.envs.MDP2RLEnv.episode_events`, which returns, with an episode budget, a row per + time each repeating task was done, with its world, episode, and step, such as each time an object dropped. diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py index 2a3e6e412108..2391b3395596 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py @@ -670,6 +670,28 @@ def member(worlds: Sequence[int] | None) -> str: *(f" {last}[{k}, world] = {column}" for k, column in enumerate(columns)), *restarted, ) + if self.cfg.episode_budget is not None and self._event_paths: + # A task that repeats occurred in an episode of the budget where its count rose since the last step. + ended = argument(self._ended, wp.array(dtype=wp.bool)) + active = argument(self._active, wp.array(dtype=wp.bool)) + episode = argument(self._episode_index, wp.array(dtype=wp.float32)) + length = argument(self.state.episode_length, wp.array(dtype=self.state.episode_length.warp.dtype)) + events = argument(self._events, wp.array3d(dtype=wp.int32)) + totals = argument(self._num_events, wp.array(dtype=wp.int32)) + last = argument(self._last_counts, wp.array2d(dtype=wp.int32)) + lines = [] + for k, path in enumerate(self._event_paths): + count = argument(self.state.arrays[mdp2.progress_field(path, "count")], wp.array(dtype=wp.int32)) + lines += [ + f"if ({ended}[world] or {active}[world]) and {count}[world] > {last}[{k}, world]:", + f" row{k} = wp.atomic_add({totals}, {k}, 1)", + f" {events}[{k}, row{k}, 0] = world", + # The budget counted the episodes that ended this step already. + f" {events}[{k}, row{k}, 1] = int({episode}[world]) - wp.where({ended}[world], 1, 0)", + f" {events}[{k}, row{k}, 2] = int({length}[world])", + f"{last}[{k}, world] = wp.where({ended}[world], 0, {count}[world])", + ] + code.world(*lines) self._log_kernels = code.steps() self.extras["log"] = self._episode_log() @@ -741,6 +763,21 @@ def episode_records(self) -> dict[str, torch.Tensor]: rows = self._records[: self.episodes_completed] return {name: rows[:, k] for k, name in enumerate(self._record_columns)} + def episode_events(self) -> dict[str, dict[str, torch.Tensor]]: + """Return, for each task that repeats, a row per time it was done in an episode of the budget, as columns by + name: ``world``, ``episode`` and ``step``, which join the rows of :meth:`episode_records` on ``world`` and + ``episode``. Includes the episodes that still run. Rows are ordered by world, episode, then step. Waits for the + device. + """ + events = {} + for k, path in enumerate(self._event_paths): + rows = self._events[k, : int(self._num_events[k])].long() + # The rows of one step land in any order. + key = (rows[:, 0] * (self._budget + 1) + rows[:, 1]) * (self._events.shape[1] + 1) + rows[:, 2] + rows = rows[key.argsort()] + events[path or "task"] = {name: rows[:, j] for j, name in enumerate(("world", "episode", "step"))} + return events + 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.""" @@ -766,6 +803,14 @@ def _init_episode_budget(self, budget: int) -> None: 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] + # A task that repeats is done at most once per step, so its rows fit the steps of the budget. + if repeats and not math.isfinite(self.max_episode_length): + raise ValueError("An episode budget needs a time limit to record the times that repeating tasks are done.") + capacity = budget * int(self.max_episode_length) if repeats else 0 + self._event_paths = repeats + self._events = torch.zeros(len(repeats), capacity, 3, dtype=torch.int32, device=device) + self._num_events = torch.zeros(len(repeats), dtype=torch.int32, device=device) + self._last_counts = torch.zeros(len(repeats), self.num_envs, dtype=torch.int32, device=device) if self.state.revision is not None: self._recorded.append(self.state.revision.torch) self._record_columns.append("revision") @@ -777,6 +822,8 @@ def _restart_episode_budget(self) -> None: self._started.fill_(min(self._budget, self.num_envs)) self._completed.zero_() self._episode_index.zero_() + self._num_events.zero_() + self._last_counts.zero_() torch.lt(self._worlds, self._budget, out=self._active) def _spend_episode_budget(self) -> None: diff --git a/source/isaaclab_experimental/test/envs/test_mdp2_env.py b/source/isaaclab_experimental/test/envs/test_mdp2_env.py index 1b260609b6bb..e7a08c5c7853 100644 --- a/source/isaaclab_experimental/test/envs/test_mdp2_env.py +++ b/source/isaaclab_experimental/test/envs/test_mdp2_env.py @@ -636,6 +636,39 @@ def test_progress_is_logged_over_the_episodes_that_ran(): env.close() +def test_repeating_tasks_record_each_time_they_were_done(): + """Under an episode budget that runs a second episode in one world, a repeating task records a row per time it was + done, on the first and the last step of an episode too, joined to its episode's record: as many as its count, the + first at its done step. Worlds whose budget ran out keep stepping but record none.""" + cfg = cartpole_cfg() + cfg.task.terminations["cart_out_of_bounds"] = None + every = mdp2.Term(torch=lambda episode_length, *, steps: (episode_length % steps == 1).float()) + # Done on the first and the last of the 60 steps of an episode, the steps around a reset. + tick = mdp2.Quantity(every, inputs={"episode_length": mdp2.episode_length}, params={"steps": 59}) + ticks = mdp2.TaskCfg(quantities={"tick": tick}, done=mdp2.quantities.tick, repeat=True, tracked=True) + cfg.task = mdp2.compose(cfg.task, ticks=ticks) + cfg.episode_budget = NUM_ENVS + 1 + env = MDP2RLEnv(cfg) + try: + env.reset() + for _ in range(3 * env.max_episode_length): + env.step(torch.zeros(NUM_ENVS, 1, device=env.device)) + if env.episodes_completed == cfg.episode_budget: + break + records, events = env.episode_records(), env.episode_events()["ticks"] + assert len(records["world"]) == cfg.episode_budget + episodes = [(int(w), int(e)) for w, e in zip(records["world"], records["episode"])] + assert (0, 1) in episodes + occurred = list(zip(events["world"].tolist(), events["episode"].tolist())) + assert set(occurred) == set(episodes) + for k, episode in enumerate(episodes): + steps = [s for o, s in zip(occurred, events["step"].tolist()) if o == episode] + assert steps == [1, env.max_episode_length] + assert len(steps) == records["progress/ticks/count"][k] and steps[0] == records["progress/ticks"][k] + finally: + env.close() + + def test_verify_capture_finds_python_state_that_the_graph_freezes(): """The debug check passes a task whose captured steps are exact, and names a stage whose Python-side state the graph froze at capture.""" From cbb5b5048203849260c63b2e7d9e96d0df6385d2 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Tue, 1 Dec 2026 21:33:45 -0800 Subject: [PATCH 4/7] Let MDP2 sequences repeat and be tracked without dataclasses.replace --- docs/source/experimental-features/mdp2.rst | 8 +++++++- .../changelog.d/mh-mdp2-tracked-tasks.added.rst | 2 ++ .../isaaclab_experimental/mdp2/config.py | 7 ++++--- source/isaaclab_experimental/test/mdp2/test_mdp2.py | 10 ++++++---- 4 files changed, 19 insertions(+), 8 deletions(-) diff --git a/docs/source/experimental-features/mdp2.rst b/docs/source/experimental-features/mdp2.rst index c41a3a71105e..fe07a9d8efee 100644 --- a/docs/source/experimental-features/mdp2.rst +++ b/docs/source/experimental-features/mdp2.rst @@ -158,7 +158,13 @@ one: TASK = mdp2.compose( BASE, place=mdp2.sequence(...), # Done and scored as the task - drops=mdp2.Milestone(q.dropped, hold=10, repeat=True, tracked=True), # Counted as progress.drops.count + drops=mdp2.sequence( # Counted as progress.drops.count; each drop is a row of env.episode_events()["drops"] + lifted=mdp2.Milestone(q.lifted, hold=10), + dropped=mdp2.Milestone(q.dropped, hold=10), + repeat=True, + tracked=True, + ), + slips=mdp2.Milestone(q.slipped, repeat=True, tracked=True), # An event of one condition ) - **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 diff --git a/source/isaaclab_experimental/changelog.d/mh-mdp2-tracked-tasks.added.rst b/source/isaaclab_experimental/changelog.d/mh-mdp2-tracked-tasks.added.rst index ad5f4d479444..8991b01c6090 100644 --- a/source/isaaclab_experimental/changelog.d/mh-mdp2-tracked-tasks.added.rst +++ b/source/isaaclab_experimental/changelog.d/mh-mdp2-tracked-tasks.added.rst @@ -3,3 +3,5 @@ completion and score, so watching an event does not change what counts as success. * Added :meth:`~isaaclab_experimental.envs.MDP2RLEnv.episode_events`, which returns, with an episode budget, a row per time each repeating task was done, with its world, episode, and step, such as each time an object dropped. +* Added ``repeat`` and ``tracked`` to :func:`~isaaclab_experimental.mdp2.sequence`, for an event of several steps, + such as a lift then a drop. diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py index 3f2946117098..faf182b8e378 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py @@ -529,10 +529,11 @@ def _renamed(value: Any, entities: dict[str, str]) -> Any: return value -def sequence(**subtasks: TaskCfg) -> TaskCfg: +def sequence(*, repeat: bool = False, tracked: bool = False, **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) + done, and the task is done once the last one is, which keeps running until the episode ends. ``repeat`` and + ``tracked`` are those of :class:`TaskCfg`, such as for an event of several steps to count beside the task.""" + return TaskCfg(subtasks=dict(subtasks), mode=TaskMode.SEQUENCE, repeat=repeat, tracked=tracked) def choice(weights: dict[str, float] | None = None, **subtasks: TaskCfg) -> TaskCfg: diff --git a/source/isaaclab_experimental/test/mdp2/test_mdp2.py b/source/isaaclab_experimental/test/mdp2/test_mdp2.py index 830072525607..fc120b124b59 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2.py @@ -2284,13 +2284,15 @@ def test_tracked_tasks_keep_their_progress_out_of_their_parent(): assert check_progress(task, [[1.0, 0.0]])[0]["done"].item() # Arena's dropped object: lifted for 2 steps, then dropped for 2 steps, counted each time, beside the task. - drops = mdp2.sequence( - lifted=mdp2.Milestone(mdp2.quantities.lifted, hold=2), dropped=mdp2.Milestone(mdp2.quantities.dropped, hold=2) - ) task = mdp2.compose( mdp2.TaskCfg(quantities=above("placed", "lifted", "dropped")), place=mdp2.Milestone(mdp2.quantities.placed), - drops=dataclasses.replace(drops, repeat=True, tracked=True), + drops=mdp2.sequence( + lifted=mdp2.Milestone(mdp2.quantities.lifted, hold=2), + dropped=mdp2.Milestone(mdp2.quantities.dropped, hold=2), + repeat=True, + tracked=True, + ), ) cycle = [[0.0, 1.0, 0.0]] * 2 + [[0.0, 0.0, 1.0]] * 3 + [[0.0, 0.0, 0.0]] history = check_progress(task, cycle * 2) From ad129e6fae07cf8ec4f4f4c03350b11a24821894 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Wed, 2 Dec 2026 08:21:41 -0800 Subject: [PATCH 5/7] Record occurrences that a parent's restart clears, and address review findings Repeating tasks set an occurred flag that restarts keep, so the env records a nested event done in the step its parent restarts. Budgets without a time limit build again; only episode_events needs one. tracked moves to the end of TaskCfg and TaskNode so positional fields keep their meaning, and sequence rejects subtasks passed as its flags. --- .../isaaclab_experimental/envs/mdp2_env.py | 32 ++++++++--------- .../isaaclab_experimental/mdp2/compiled.py | 1 + .../isaaclab_experimental/mdp2/config.py | 8 +++-- .../isaaclab_experimental/mdp2/plan.py | 7 ++-- .../mdp2/torch_backend.py | 1 + .../mdp2/warp_backend.py | 7 ++-- .../test/envs/test_mdp2_env.py | 36 ++++++++++++------- .../test/mdp2/test_mdp2.py | 4 +++ 8 files changed, 56 insertions(+), 40 deletions(-) diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py index 2391b3395596..b32f11b20ebd 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py @@ -670,26 +670,23 @@ def member(worlds: Sequence[int] | None) -> str: *(f" {last}[{k}, world] = {column}" for k, column in enumerate(columns)), *restarted, ) - if self.cfg.episode_budget is not None and self._event_paths: - # A task that repeats occurred in an episode of the budget where its count rose since the last step. + if self.cfg.episode_budget is not None and self._events is not None and self._event_paths: ended = argument(self._ended, wp.array(dtype=wp.bool)) active = argument(self._active, wp.array(dtype=wp.bool)) episode = argument(self._episode_index, wp.array(dtype=wp.float32)) length = argument(self.state.episode_length, wp.array(dtype=self.state.episode_length.warp.dtype)) events = argument(self._events, wp.array3d(dtype=wp.int32)) totals = argument(self._num_events, wp.array(dtype=wp.int32)) - last = argument(self._last_counts, wp.array2d(dtype=wp.int32)) lines = [] for k, path in enumerate(self._event_paths): - count = argument(self.state.arrays[mdp2.progress_field(path, "count")], wp.array(dtype=wp.int32)) + occurred = argument(self.state.arrays[mdp2.progress_field(path, "occurred")], wp.array(dtype=wp.bool)) lines += [ - f"if ({ended}[world] or {active}[world]) and {count}[world] > {last}[{k}, world]:", + f"if ({ended}[world] or {active}[world]) and {occurred}[world]:", f" row{k} = wp.atomic_add({totals}, {k}, 1)", f" {events}[{k}, row{k}, 0] = world", # The budget counted the episodes that ended this step already. f" {events}[{k}, row{k}, 1] = int({episode}[world]) - wp.where({ended}[world], 1, 0)", f" {events}[{k}, row{k}, 2] = int({length}[world])", - f"{last}[{k}, world] = wp.where({ended}[world], 0, {count}[world])", ] code.world(*lines) self._log_kernels = code.steps() @@ -765,10 +762,12 @@ def episode_records(self) -> dict[str, torch.Tensor]: def episode_events(self) -> dict[str, dict[str, torch.Tensor]]: """Return, for each task that repeats, a row per time it was done in an episode of the budget, as columns by - name: ``world``, ``episode`` and ``step``, which join the rows of :meth:`episode_records` on ``world`` and - ``episode``. Includes the episodes that still run. Rows are ordered by world, episode, then step. Waits for the - device. + name: ``world``, ``episode`` and ``step``. Rows of completed episodes join their rows of :meth:`episode_records` + on ``world`` and ``episode``; episodes that still run have rows but no record yet. Rows are ordered by world, + episode, then step. Needs a time limit, which bounds the rows. Waits for the device. """ + if self._events is None: + raise RuntimeError("Recording the times that repeating tasks are done needs a time limit.") events = {} for k, path in enumerate(self._event_paths): rows = self._events[k, : int(self._num_events[k])].long() @@ -804,13 +803,12 @@ def _init_episode_budget(self, budget: int) -> None: 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] # A task that repeats is done at most once per step, so its rows fit the steps of the budget. - if repeats and not math.isfinite(self.max_episode_length): - raise ValueError("An episode budget needs a time limit to record the times that repeating tasks are done.") - capacity = budget * int(self.max_episode_length) if repeats else 0 self._event_paths = repeats - self._events = torch.zeros(len(repeats), capacity, 3, dtype=torch.int32, device=device) - self._num_events = torch.zeros(len(repeats), dtype=torch.int32, device=device) - self._last_counts = torch.zeros(len(repeats), self.num_envs, dtype=torch.int32, device=device) + self._events = self._num_events = None + if math.isfinite(self.max_episode_length): + capacity = budget * int(self.max_episode_length) + self._events = torch.empty(len(repeats), capacity, 3, dtype=torch.int32, device=device) + self._num_events = torch.zeros(len(repeats), dtype=torch.int32, device=device) if self.state.revision is not None: self._recorded.append(self.state.revision.torch) self._record_columns.append("revision") @@ -822,8 +820,8 @@ def _restart_episode_budget(self) -> None: self._started.fill_(min(self._budget, self.num_envs)) self._completed.zero_() self._episode_index.zero_() - self._num_events.zero_() - self._last_counts.zero_() + if self._num_events is not None: + self._num_events.zero_() torch.lt(self._worlds, self._budget, out=self._active) def _spend_episode_budget(self) -> None: diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py index 06965234219e..6156c4eba148 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/compiled.py @@ -539,6 +539,7 @@ def array(path: str, name: str, dtype: type, initial: float = 0) -> np.ndarray: array(node.path, "count", np.int32) array(node.path, "spent", np.bool_) array(node.path, "restarted", np.bool_) + array(node.path, "occurred", np.bool_) # Done again this step; restarts keep it values[progress_field(node.path, "active")][worlds] = tree.runs_at_start(node) dtypes = {np.bool_: wp.bool, np.int32: wp.int32, np.float32: wp.float32} diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py index faf182b8e378..461f682e0682 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py @@ -387,15 +387,15 @@ class TaskCfg: # 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 - # Keep the task's progress out of its parent's completion and score, for an event to watch rather than a goal, such - # as drops of an object. Only a subtask of a task that runs its subtasks together can be tracked - tracked: 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 + # Keep the task's progress out of its parent's completion and score, for an event to watch rather than a goal, such + # as drops of an object. Only a subtask of a task that runs its subtasks together can be tracked + tracked: bool = False @dataclass(init=False) @@ -533,6 +533,8 @@ def sequence(*, repeat: bool = False, tracked: bool = False, **subtasks: 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. ``repeat`` and ``tracked`` are those of :class:`TaskCfg`, such as for an event of several steps to count beside the task.""" + if not isinstance(repeat, bool) or not isinstance(tracked, bool): + raise TypeError("'repeat' and 'tracked' are flags of the sequence and cannot name its subtasks") return TaskCfg(subtasks=dict(subtasks), mode=TaskMode.SEQUENCE, repeat=repeat, tracked=tracked) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py index 515e409913cd..e094a87300ca 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py @@ -200,9 +200,9 @@ class TaskNode: # ancestors repeats staged: bool repeat: bool = False - tracked: bool = False # Kept out of its parent's completion and score weights: tuple[float, ...] = () # Choice: the chance of each subtask stream: int | None = None # Choice: row of MDPState.rng that draws the subtask + tracked: bool = False # Kept out of its parent's completion and score @dataclass(frozen=True) @@ -247,9 +247,8 @@ def descendants(self, node: TaskNode) -> tuple[TaskNode, ...]: def counted(self, node: TaskNode) -> tuple[TaskNode, ...]: """Return the subtasks of a task that count towards its completion: those that have one and are not tracked.""" - return tuple( - self.node(child) for child in node.children if child in self.completes and not self.node(child).tracked - ) + children = (self.node(child) for child in node.children if child in self.completes) + return tuple(child for child in children if not child.tracked) @dataclass(frozen=True) diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py index 1b65b408a75b..885b778c6185 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/torch_backend.py @@ -425,6 +425,7 @@ def _repeat(state: MDPState, tree: TaskTree, node, complete: torch.Tensor, lengt field = functools.partial(_progress, state, tree, node.path) active, done, spent = field("active"), field("done"), field("spent") counted = active & complete & ~spent + field("occurred").copy_(counted) spent.logical_or_(counted) field("count").add_(counted.int()) first = counted & ~done diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py index fef77660afa7..c492e88a2c93 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/warp_backend.py @@ -674,7 +674,7 @@ def _under(conditions: Sequence[str], *lines: str) -> list[str]: _PROGRESS_TYPES = { - **dict.fromkeys(("done", "holding", "active", "entered", "spent", "restarted"), wp.bool), + **dict.fromkeys(("done", "holding", "active", "entered", "spent", "restarted", "occurred"), wp.bool), "score": wp.float32, } """Element types of the progress fields other than the ``int32`` ones.""" @@ -704,7 +704,7 @@ def _update_progress(code: Fusion, trees: tuple[TaskTree, ...]) -> None: for node in reversed(tree.nodes): if node.path in tree.completes: lines += _node_progress(code, tree, node, length) - names = ("done", "holding", "score", "done_at", "streak", "stage", "count", "spent", "restarted") + names = ("done", "holding", "score", "done_at", "streak", "stage", "count", "spent", "restarted", "occurred") if lines: code.world(*_under(_in_tree(trees, tree), *lines), writes=_tree_writes(tree, names)) @@ -816,7 +816,8 @@ def _repeat(code: Fusion, tree: TaskTree, node: TaskNode, length: str) -> list[s for child in tree.descendants(node): restart += _restart_lines(code, child) return [ - f"if {field('active')} and complete and not {spent}:", + f"{field('occurred')} = {field('active')} and complete and not {spent}", + f"if {field('occurred')}:", f" {spent} = True", f" {field('count')} = {field('count')} + 1", f" if not {done}:", diff --git a/source/isaaclab_experimental/test/envs/test_mdp2_env.py b/source/isaaclab_experimental/test/envs/test_mdp2_env.py index e7a08c5c7853..8fb89043f0e7 100644 --- a/source/isaaclab_experimental/test/envs/test_mdp2_env.py +++ b/source/isaaclab_experimental/test/envs/test_mdp2_env.py @@ -639,14 +639,22 @@ def test_progress_is_logged_over_the_episodes_that_ran(): def test_repeating_tasks_record_each_time_they_were_done(): """Under an episode budget that runs a second episode in one world, a repeating task records a row per time it was done, on the first and the last step of an episode too, joined to its episode's record: as many as its count, the - first at its done step. Worlds whose budget ran out keep stepping but record none.""" + first at its done step. A repeating subtask of a repeating task records the time it was done in the step its + parent restarts, which clears its count. Worlds whose budget ran out keep stepping but record none.""" cfg = cartpole_cfg() cfg.task.terminations["cart_out_of_bounds"] = None - every = mdp2.Term(torch=lambda episode_length, *, steps: (episode_length % steps == 1).float()) - # Done on the first and the last of the 60 steps of an episode, the steps around a reset. - tick = mdp2.Quantity(every, inputs={"episode_length": mdp2.episode_length}, params={"steps": 59}) - ticks = mdp2.TaskCfg(quantities={"tick": tick}, done=mdp2.quantities.tick, repeat=True, tracked=True) - cfg.task = mdp2.compose(cfg.task, ticks=ticks) + every = mdp2.Term(torch=lambda episode_length, *, step: (episode_length % 59 == step).float()) + + def on(step: int, **flags) -> mdp2.TaskCfg: + """Done on the steps of an episode that are ``step`` modulo 59: of its 60 steps, the first and the last for 1.""" + at = mdp2.Quantity(every, inputs={"episode_length": mdp2.episode_length}, params={"step": step}) + return mdp2.TaskCfg(quantities={"at": at}, done=mdp2.quantities.at, **flags) + + # The cycle is done on step 1 and restarts on step 2, when its event is done. + cycle = mdp2.compose(goal=on(1), event=on(2, repeat=True, tracked=True)) + cfg.task = mdp2.compose( + cfg.task, ticks=on(1, repeat=True, tracked=True), cycle=replace(cycle, repeat=True, tracked=True) + ) cfg.episode_budget = NUM_ENVS + 1 env = MDP2RLEnv(cfg) try: @@ -655,16 +663,18 @@ def test_repeating_tasks_record_each_time_they_were_done(): env.step(torch.zeros(NUM_ENVS, 1, device=env.device)) if env.episodes_completed == cfg.episode_budget: break - records, events = env.episode_records(), env.episode_events()["ticks"] + records, events = env.episode_records(), env.episode_events() assert len(records["world"]) == cfg.episode_budget episodes = [(int(w), int(e)) for w, e in zip(records["world"], records["episode"])] assert (0, 1) in episodes - occurred = list(zip(events["world"].tolist(), events["episode"].tolist())) - assert set(occurred) == set(episodes) - for k, episode in enumerate(episodes): - steps = [s for o, s in zip(occurred, events["step"].tolist()) if o == episode] - assert steps == [1, env.max_episode_length] - assert len(steps) == records["progress/ticks/count"][k] and steps[0] == records["progress/ticks"][k] + for path, expected in (("ticks", [1, env.max_episode_length]), ("cycle.event", [2])): + rows = list(zip(events[path]["world"].tolist(), events[path]["episode"].tolist())) + steps = events[path]["step"].tolist() + assert set(rows) == set(episodes) + for k, episode in enumerate(episodes): + assert [s for row, s in zip(rows, steps) if row == episode] == expected + if path == "ticks": + assert records["progress/ticks/count"][k] == 2 and records["progress/ticks"][k] == 1 finally: env.close() diff --git a/source/isaaclab_experimental/test/mdp2/test_mdp2.py b/source/isaaclab_experimental/test/mdp2/test_mdp2.py index fc120b124b59..671f676320f7 100644 --- a/source/isaaclab_experimental/test/mdp2/test_mdp2.py +++ b/source/isaaclab_experimental/test/mdp2/test_mdp2.py @@ -2299,6 +2299,10 @@ def test_tracked_tasks_keep_their_progress_out_of_their_parent(): assert [step["drops.count"].item() for step in history] == [0] * 3 + [1] * 6 + [2] * 3 assert not any(step["done"].item() or step["score"].item() for step in history) + # The flags of a sequence cannot silently swallow subtasks of their names. + with pytest.raises(TypeError, match="cannot name its subtasks"): + mdp2.sequence(repeat=mdp2.Milestone(mdp2.quantities.lifted)) + # A task whose only completion is tracked has none of its own. task = mdp2.compose( mdp2.TaskCfg(quantities=above("dropped")), From 1cd2ef3860cd61d0a4f2814406654cc0f2bfff26 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Wed, 2 Dec 2026 14:00:41 -0800 Subject: [PATCH 6/7] Record MDP2 episode events only when asked The event buffer holds budget * time-limit steps rows per repeating task, which is ~1.2 GB per task for 1000-step episodes and a 100k budget. MDP2RLEnvCfg.record_episode_events turns it on, off by default, and raises at construction without a time limit. --- docs/source/experimental-features/mdp2.rst | 9 +++++---- .../changelog.d/mh-mdp2-tracked-tasks.added.rst | 5 +++-- .../isaaclab_experimental/envs/mdp2_env.py | 8 +++++--- .../isaaclab_experimental/envs/mdp2_env_cfg.py | 3 +++ source/isaaclab_experimental/test/envs/test_mdp2_env.py | 6 +++++- 5 files changed, 21 insertions(+), 10 deletions(-) diff --git a/docs/source/experimental-features/mdp2.rst b/docs/source/experimental-features/mdp2.rst index fe07a9d8efee..2bae0f3395a5 100644 --- a/docs/source/experimental-features/mdp2.rst +++ b/docs/source/experimental-features/mdp2.rst @@ -273,9 +273,10 @@ episode ended. - **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. - :meth:`~isaaclab_experimental.envs.MDP2RLEnv.episode_events` returns, for each task that repeats, a row per time it - was done: its world, episode, and step, which join the episode's record. Its rows fit any run, as a task repeats at - most once per step, but they need a time limit. + With ``record_episode_events``, :meth:`~isaaclab_experimental.envs.MDP2RLEnv.episode_events` returns, for each task + that repeats, a row per time it was done: its world, episode, and step, which join the episode's record. Its rows + fit any run, as a task repeats at most once per step, so they need a time limit and take budget × time-limit steps × + 12 bytes per repeating task. .. code-block:: python @@ -352,7 +353,7 @@ Porting from Arena - :data:`~isaaclab_experimental.mdp2.mdp.resting_on`, held with ``hold`` * - tracked events - a subtask with ``repeat=True, tracked=True``, counted as ``progress..count``, each time it was done in - ``env.episode_events()[]`` + ``env.episode_events()[]`` with ``record_episode_events`` * - run-time variations and their JSONL records - :func:`~isaaclab_experimental.mdp2.mdp.variation`, with ``episode_budget`` records * - per-episode results diff --git a/source/isaaclab_experimental/changelog.d/mh-mdp2-tracked-tasks.added.rst b/source/isaaclab_experimental/changelog.d/mh-mdp2-tracked-tasks.added.rst index 8991b01c6090..2cd92d664aee 100644 --- a/source/isaaclab_experimental/changelog.d/mh-mdp2-tracked-tasks.added.rst +++ b/source/isaaclab_experimental/changelog.d/mh-mdp2-tracked-tasks.added.rst @@ -1,7 +1,8 @@ * Added ``tracked`` to :class:`~isaaclab_experimental.mdp2.TaskCfg` and :class:`~isaaclab_experimental.mdp2.Milestone`. A tracked subtask keeps its own progress, such as how often an object drops, but stays out of its parent's completion and score, so watching an event does not change what counts as success. -* Added :meth:`~isaaclab_experimental.envs.MDP2RLEnv.episode_events`, which returns, with an episode budget, a row per - time each repeating task was done, with its world, episode, and step, such as each time an object dropped. +* Added :meth:`~isaaclab_experimental.envs.MDP2RLEnv.episode_events`, which returns, with an episode budget and + ``record_episode_events``, a row per time each repeating task was done, with its world, episode, and step, such as + each time an object dropped. * Added ``repeat`` and ``tracked`` to :func:`~isaaclab_experimental.mdp2.sequence`, for an event of several steps, such as a lift then a drop. diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py index b32f11b20ebd..ebbb75b017d5 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py @@ -764,10 +764,10 @@ def episode_events(self) -> dict[str, dict[str, torch.Tensor]]: """Return, for each task that repeats, a row per time it was done in an episode of the budget, as columns by name: ``world``, ``episode`` and ``step``. Rows of completed episodes join their rows of :meth:`episode_records` on ``world`` and ``episode``; episodes that still run have rows but no record yet. Rows are ordered by world, - episode, then step. Needs a time limit, which bounds the rows. Waits for the device. + episode, then step. Needs ``record_episode_events``. Waits for the device. """ if self._events is None: - raise RuntimeError("Recording the times that repeating tasks are done needs a time limit.") + raise RuntimeError("Set 'record_episode_events' to record the times that repeating tasks are done.") events = {} for k, path in enumerate(self._event_paths): rows = self._events[k, : int(self._num_events[k])].long() @@ -805,7 +805,9 @@ def _init_episode_budget(self, budget: int) -> None: # A task that repeats is done at most once per step, so its rows fit the steps of the budget. self._event_paths = repeats self._events = self._num_events = None - if math.isfinite(self.max_episode_length): + if self.cfg.record_episode_events: + if not math.isfinite(self.max_episode_length): + raise ValueError("'record_episode_events' needs a time limit, which bounds the rows.") capacity = budget * int(self.max_episode_length) self._events = torch.empty(len(repeats), capacity, 3, dtype=torch.int32, device=device) self._num_events = torch.zeros(len(repeats), dtype=torch.int32, device=device) 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 3ab2d76f0fee..36ecbcd72bc3 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env_cfg.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env_cfg.py @@ -89,6 +89,9 @@ class MDP2RLEnvCfg(MDP2EnvCfg): # 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 + # Whether the budget records a row per time each repeating task is done, see MDP2RLEnv.episode_events. Needs a + # time limit; holds budget * time-limit steps * 12 bytes per repeating task. + record_episode_events: bool = False log_dir: str | None = None # Set by the training scripts video_recorders: list = [] # Not supported yet; kept for the training scripts diff --git a/source/isaaclab_experimental/test/envs/test_mdp2_env.py b/source/isaaclab_experimental/test/envs/test_mdp2_env.py index 8fb89043f0e7..6d01745a017f 100644 --- a/source/isaaclab_experimental/test/envs/test_mdp2_env.py +++ b/source/isaaclab_experimental/test/envs/test_mdp2_env.py @@ -613,7 +613,8 @@ def test_env_runs_the_tasks_of_a_sequence_in_turn_and_logs_their_progress(): 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. A tracked task that is never done leaves the task's progress alone.""" + world, most of which finished none. A tracked task that is never done leaves the task's progress alone. Events are + recorded only on request.""" cfg = cartpole_cfg() cfg.task.terminations["cart_out_of_bounds"] = None late = replace(stage(10**6), tracked=True) @@ -632,6 +633,8 @@ def test_progress_is_logged_over_the_episodes_that_ran(): assert log["Progress/task"] == 1.0 and log["Progress/late"] == 0.0 records = env.episode_records() assert records["progress/late"].item() == -1 and records["progress/score"].item() == 1.0 + with pytest.raises(RuntimeError, match="record_episode_events"): + env.episode_events() finally: env.close() @@ -656,6 +659,7 @@ def on(step: int, **flags) -> mdp2.TaskCfg: cfg.task, ticks=on(1, repeat=True, tracked=True), cycle=replace(cycle, repeat=True, tracked=True) ) cfg.episode_budget = NUM_ENVS + 1 + cfg.record_episode_events = True env = MDP2RLEnv(cfg) try: env.reset() From 888b0c3cf2d046a31aca09e72634f2f1e8fcc63a Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Wed, 2 Dec 2026 14:32:21 -0800 Subject: [PATCH 7/7] Fit a test docstring within the line limit --- source/isaaclab_experimental/test/envs/test_mdp2_env.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/isaaclab_experimental/test/envs/test_mdp2_env.py b/source/isaaclab_experimental/test/envs/test_mdp2_env.py index 6d01745a017f..428c87c92f9d 100644 --- a/source/isaaclab_experimental/test/envs/test_mdp2_env.py +++ b/source/isaaclab_experimental/test/envs/test_mdp2_env.py @@ -649,7 +649,7 @@ def test_repeating_tasks_record_each_time_they_were_done(): every = mdp2.Term(torch=lambda episode_length, *, step: (episode_length % 59 == step).float()) def on(step: int, **flags) -> mdp2.TaskCfg: - """Done on the steps of an episode that are ``step`` modulo 59: of its 60 steps, the first and the last for 1.""" + """Done on the steps of an episode that are ``step`` modulo 59: of its 60 steps, the first and last for 1.""" at = mdp2.Quantity(every, inputs={"episode_length": mdp2.episode_length}, params={"step": step}) return mdp2.TaskCfg(quantities={"at": at}, done=mdp2.quantities.at, **flags)