diff --git a/docs/source/experimental-features/mdp2.rst b/docs/source/experimental-features/mdp2.rst index 2e9e1eec5f4a..2bae0f3395a5 100644 --- a/docs/source/experimental-features/mdp2.rst +++ b/docs/source/experimental-features/mdp2.rst @@ -149,6 +149,23 @@ 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.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 sequence can have its own ``reached``: its commands and quantities, the ``term_state`` and ``tunable`` values of its @@ -256,6 +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. + 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 @@ -331,7 +352,8 @@ 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``, each time it was done in + ``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 new file mode 100644 index 000000000000..2cd92d664aee --- /dev/null +++ b/source/isaaclab_experimental/changelog.d/mh-mdp2-tracked-tasks.added.rst @@ -0,0 +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 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/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..ebbb75b017d5 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp2_env.py @@ -670,6 +670,25 @@ 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._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)) + lines = [] + for k, path in enumerate(self._event_paths): + occurred = argument(self.state.arrays[mdp2.progress_field(path, "occurred")], wp.array(dtype=wp.bool)) + lines += [ + 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])", + ] + code.world(*lines) self._log_kernels = code.steps() self.extras["log"] = self._episode_log() @@ -741,6 +760,23 @@ 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``. 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 ``record_episode_events``. Waits for the device. + """ + if self._events is None: + 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() + # 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.""" @@ -760,12 +796,21 @@ 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)) 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. + self._event_paths = repeats + self._events = self._num_events = None + 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) 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_() + 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/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/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..6156c4eba148 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(): @@ -538,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 8e5c1fbbee85..461f682e0682 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py @@ -393,6 +393,9 @@ class TaskCfg: 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) @@ -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: @@ -525,10 +529,13 @@ 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.""" + 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) def choice(weights: dict[str, float] | None = None, **subtasks: TaskCfg) -> TaskCfg: diff --git a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py index e7096c1c0a06..e094a87300ca 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py +++ b/source/isaaclab_experimental/isaaclab_experimental/mdp2/plan.py @@ -202,6 +202,7 @@ class TaskNode: 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 + tracked: bool = False # Kept out of its parent's completion and score @dataclass(frozen=True) @@ -245,8 +246,9 @@ 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.""" + 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 2ec793bfca34..428c87c92f9d 100644 --- a/source/isaaclab_experimental/test/envs/test_mdp2_env.py +++ b/source/isaaclab_experimental/test/envs/test_mdp2_env.py @@ -613,10 +613,12 @@ 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. Events are + recorded only on request.""" 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, steps=mdp2.sequence(warm=stage(3), hold=stage(6)), late=late) cfg.episode_budget = 1 env = MDP2RLEnv(cfg) try: @@ -627,7 +629,56 @@ 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/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 + with pytest.raises(RuntimeError, match="record_episode_events"): + env.episode_events() + finally: + 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. 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, *, 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 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 + cfg.record_episode_events = True + 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() + 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 + 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 f682c30486eb..671f676320f7 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,54 @@ 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() + + # Arena's dropped object: lifted for 2 steps, then dropped for 2 steps, counted each time, beside the task. + task = mdp2.compose( + mdp2.TaskCfg(quantities=above("placed", "lifted", "dropped")), + place=mdp2.Milestone(mdp2.quantities.placed), + 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) + 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")), + 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 keeps its outputs across tasks, and the last actions zero the columns of a task that does not run."""