Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 23 additions & 1 deletion docs/source/experimental-features/mdp2.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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.<task>.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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.<task>.count``
- a subtask with ``repeat=True, tracked=True``, counted as ``progress.<task>.count``, each time it was done in
``env.episode_events()[<task>]`` with ``record_episode_events``
* - run-time variations and their JSONL records
- :func:`~isaaclab_experimental.mdp2.mdp.variation`, with ``episode_budget`` records
* - per-episode results
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Empty file.
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down Expand Up @@ -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."""
Expand All @@ -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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This allocates worst-case rows for every repeating task, tracked or not, even when episode_events() is never called (~1.2 GB per task for 1000-step episodes, like Go2 flat, with a 100k budget). Could event recording be opt-in?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, made it opt-in in 1cd2ef3: MDP2RLEnvCfg.record_episode_events (default False). Off, nothing is allocated and episode_events() raises asking for the flag. On, the buffer is still worst-case (budget × time-limit steps × 12 bytes per repeating task), so that cost is now documented on the field, and it raises at construction without a time limit.

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")
Expand All @@ -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:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
22 changes: 17 additions & 5 deletions source/isaaclab_experimental/isaaclab_experimental/mdp2/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.")
Expand All @@ -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,
)

Expand Down Expand Up @@ -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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down Expand Up @@ -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}
Expand Down
17 changes: 12 additions & 5 deletions source/isaaclab_experimental/isaaclab_experimental/mdp2/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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")
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Warning · Compatibility — Preserve sequence subtask names

Previously valid subtasks named repeat or tracked now bind to flags and disappear from the sequence. Keep TaskCfg-valued keywords as subtasks and configure these flags outside that namespace.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Keeping the keywords: avoiding dataclasses.replace for a repeating event is the point, and choice(weights=...) already shares its namespace with subtasks the same way. To keep it from failing silently, sequence now raises a TypeError when a task is passed as repeat or tracked, with a test.

"""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:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down Expand Up @@ -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))

Expand Down Expand Up @@ -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}:",
Expand Down
Loading
Loading