Skip to content

Add tracked tasks and per-occurrence events to MDP2 - #9323

Open
StafaH wants to merge 5 commits into
isaac-sim:mainfrom
StafaH:mh/mdp2-tracked-tasks
Open

StafaH wants to merge 5 commits into
isaac-sim:mainfrom
StafaH:mh/mdp2-tracked-tasks

Conversation

@StafaH

@StafaH StafaH commented Dec 1, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Ports Arena's tracked events to MDP2. A tracked event records when something of interest happens, such as an object being dropped, without changing what counts as success.

An event is built from the same pieces as success (Milestone, hold, sequence), plus two flags:

Flag Effect
repeat=True Counts every occurrence, and records the step of each one.
tracked=True Keeps the event out of the task's success and score.

Usage

1. Define the event beside the task

from isaaclab_experimental import mdp2

TASK = mdp2.compose(
    BASE,
    place=PICK_AND_PLACE,  # The task: decides success and score
    dropped_object=mdp2.sequence(  # An event: lifted, then resting outside the bowl
        lifted=mdp2.Milestone(q.lifted_and_grasped, hold=10),
        dropped=mdp2.Milestone(q.resting_outside_bowl, hold=10),
        repeat=True,
        tracked=True,
    ),
    slipped=mdp2.Milestone(q.slipped, repeat=True, tracked=True),  # An event of one condition
)

2. Read it during training

Tracked events are logged like any other task, and they don't change Progress/task:

_, _, _, _, extras = env.step(actions)
extras["log"]["Progress/dropped_object"]  # Share of the last episodes with at least one drop
extras["log"]["Progress/task"]            # Success rate, unaffected by the drops

The live state is in mdp2.progress.dropped_object.{count, done_at, ...}, for observations, rewards, or terminations.

3. Get per-episode results and the full timeline

With an episode budget, episode_records() gives one row per episode, and the new episode_events() gives one row per occurrence:

cfg.episode_budget = 100
env = MDP2RLEnv(cfg)
obs, _ = env.reset()
while env.episodes_completed < cfg.episode_budget:
    obs, *_ = env.step(policy(obs))

records = env.episode_records()
records["progress/task"]                   # Step the task was done, -1 if not
records["progress/dropped_object/count"]   # Drops per episode

drops = env.episode_events()["dropped_object"]
drops["world"], drops["episode"], drops["step"]  # One row per drop, sorted by world, episode, step

To get Arena's per-episode list of {name, step}, join the event rows to the records on (world, episode).

How it works

  • tracked: a tracked subtask keeps all of its own progress, but TaskTree.counted filters it out. counted is the single place that drives a parent's completion and score in both backends. Only subtasks that run together (compose) can be tracked. Tracking a subtask of a sequence, choice, or split, or the root, is a builder error.
  • episode_events(): each repeating task sets an internal occurred flag in the step it is done, in both backends. A parent's restart doesn't clear the flag, so an event inside a repeating task is recorded even when the parent restarts in the same step. The env's existing fused per-world log kernel, inside the captured step, writes a row wherever the flag is set. There are no new kernel launches and no host syncs.
    • Capacity: the buffer holds episode_budget × max_episode_length rows per repeating task. A task repeats at most once per step, so this always fits, and there is no capacity setting.

Performance

Event recording adds no measurable cost:

ms per step, 5 runs median
Recording off 0.514 – 0.519 0.518
Recording on 0.512 – 0.518 0.516
  • Setup: Cartpole on Newton (MJWarp), 4096 worlds, captured step, one repeating tracked task, episode_budget=100_000. Each run: 50 warm-up steps, then 1000 timed steps.
  • Comparison: commit ad129e6fa, with and without the recording block in _bind_logs. Runs alternated.
  • Hardware and versions: RTX PRO 6000 Blackwell, driver 595.99, torch 2.11, Warp 1.17.

Limitations

  • Main task gets a name. Adding an event makes the main task a named subtask (place= above). That prefixes its use names, progress paths, and observation names, for example goal becomes place.goal. Observation slices and widths don't change, so policies and checkpoints still load.
  • Time limit required for episode_events(). Without a time limit, the env still builds and records counts, but episode_events() raises an error, because the buffer can't be sized.
  • New sequence flags. sequence now takes repeat and tracked as keyword arguments, so a subtask can no longer be named repeat or tracked. Passing a task under those names raises a TypeError rather than dropping it. All other changes are additive: tracked is the last field of TaskCfg, so positional arguments keep their meaning.
  • Memory. The buffer takes 12 bytes per row, for example about 72 MB per repeating task for 100k episodes of 60 steps.

Type of change

  • New feature (non-breaking change which adds functionality)

Validation

  • test_mdp2.py (both backends, eager and captured):
    • a tracked milestone;
    • Arena's dropped-object sequence, counted twice beside the task;
    • a task whose only completion is tracked;
    • errors for tracking a subtask of a sequence, choice, or split, or the root.
  • test_mdp2_env.py:
    • A tracked task that is never done leaves Progress/task and progress/score at 1.
    • A budget runs a second episode in one world, with the event done on each episode's first and last step. Per episode, the rows match count, and the first row's step matches done_at.
    • An event inside a repeating task, done in the step its parent restarts, is recorded once per episode.
  • Mutation checks:
    • Removing the counted filter turns the tracked-task tests red.
    • Removing any of the event guards turns the event test red. The guards are: the active-world mask, counting worlds that just ended, and the episode-index correction.
    • Letting a parent's restart clear the occurred flag (the bug that greptile found) also turns it red.
  • All 93 tests in test/mdp2 and test/envs/test_mdp2_env.py pass locally. uv run isaaclab --format and the changelog check pass.

Checklist

  • I have read and understood the contribution guidelines
  • I have run the pre-commit checks with uv run isaaclab --format
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have validated the changed behavior with focused coverage and applied the test-audit criteria to any test changes
  • I have added a changelog fragment under source/<pkg>/changelog.d/ for every touched package (do not edit CHANGELOG.rst or bump package versions — CI handles that)
  • I have added my name to the CONTRIBUTORS.md or my name already exists there

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.
@github-actions github-actions Bot added documentation Improvements or additions to documentation isaac-lab Related to Isaac Lab team labels Dec 1, 2026
@StafaH StafaH changed the title Keep tracked MDP2 subtasks out of their parent's completion and score Add tracked tasks and per-occurrence events to MDP2 Dec 1, 2026
@StafaH
StafaH marked this pull request as ready for review December 2, 2026 05:43
@StafaH
StafaH requested a review from a team December 2, 2026 05:43

@isaaclab-review-bot isaaclab-review-bot Bot left a comment

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.

Isaac Lab Review Bot

Needs attention: Compatibility and deprecation (4), Implementation (2), Style consistency (2), Test quality (1). Other reviewed categories look good.

  • PR description: The title matches; correct non-breaking and time-limit claims, and substantiate “within noise” with baseline/candidate revisions, command, hardware, backend, environment count, budget, warmup, and latency spread; retain useful usage and validation sections.
  • Design and architecture: Architecture looks good.
  • Scope and over-engineering: No over-engineering issues.
  • API: API changes look good.
  • Compatibility and deprecation: Breaking changes: sequence consumes existing repeat/tracked subtask names, TaskCfg and TaskNode shift positional fields, and untimed repeating-task budgets fail construction; preserve these contracts before introducing the new behavior.
  • Implementation: Zero-initializing occurrence capacity writes storage never read before recording; allocate the event buffer with torch.empty.
  • Style consistency: The new event-condition comment restates the predicate without explaining a constraint; delete it and retain the episode-index correction rationale.
  • Test quality: The occurrence test transfers the entire step column inside each episode iteration; materialize it once outside the loop while retaining reset, budget-mask, and backend coverage.

Significant concerns. Posted 9 inline findings.

Automated review; human maintainers own approval decisions.

*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.

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 · Style Consistency — Remove predicate narration

This comment restates the active-world and count-rise condition immediately below it without explaining a constraint. Remove it; retain the episode-index correction comment.

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.

Removed; the env now reads a single occurred flag, so the condition is self-explanatory.


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

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 · Style Consistency — Qualify the record join

The docstring says occurrence rows join episode_records(), but also includes running episodes, which have no record yet. Limit the join claim to completed episodes.

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.

Done: the docstring now says only completed episodes join, and that running episodes have rows but no record yet.

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):

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 — Keep untimed episode budgets functional

A budgeted repeating task without a time limit now fails construction, even if callers only use count records. Keep the existing budget path functional; require a limit only for bounded occurrence recording.

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.

Fixed: a budget without a time limit builds and records counts as before; only episode_events() raises when called.

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)

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 · Implementation — Do not clear unread event rows

Only rows below _num_events are returned, and recording writes each row. Zeroing the potentially large capacity buffer adds initialization cost; allocate it with torch.empty.

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.

Done, torch.empty.

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

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 TaskCfg positional arguments

Inserting tracked before subtasks shifts the generated constructor’s existing positional fields; a positional subtasks mapping binds to tracked. Make the new field keyword-only.

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.

Moved tracked to the last field of TaskCfg, so positional fields keep their meaning.



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.

# ancestors repeats
staged: bool
repeat: bool = False
tracked: bool = False # Kept out of its parent's completion and score

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 TaskNode positional arguments

Inserting tracked before weights shifts TaskNode’s existing positional weights and stream arguments. Make tracked keyword-only so direct construction retains its meaning.

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.

Moved tracked to the last field of TaskNode.

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

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 · Implementation — Look up each child once

The tracked filter calls the linear self.node lookup twice for every retained child; the previous path called it once. Bind each child node before filtering.

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.

Fixed, one lookup per child.

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]

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 · Test Quality — Read event steps once

Calling events["step"].tolist() inside the episode loop transfers the full device column for every episode. Materialize it once before the loop.

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.

Fixed, each column is read once per task.

@greptile-apps

greptile-apps Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 4/5RetriggerView in Greptile

[Medium impact] The changes affect MDP2 task success and event results for opted-in workflows.

Fix the missing nested event records before merging.

Findings

  1. P1 Nested events can disappear ▶

Summary

Adds tracked subtasks and per-occurrence episode records to MDP2.

  • Tracked subtasks keep their progress without changing the main goal.
  • Budgeted runs record each occurrence of a repeating task.

Reviews (1) · Last reviewed commit: "Let MDP2 sequences repeat and be tracked..." · Reviewed by Greptile

Comment on lines +684 to +686
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]:",

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.

P1 Nested events can disappear

episode_events() misses a repeating child's completion when its parent restarts on the same step. For example, a repeating compose can contain a goal and a tracked repeating event. After the goal completes, its condition can fall on the same step the event fires. Both backends increment the event's count, then the parent's restart clears it before this logger reads it. The comparison sees no rise and silently drops the occurrence.

Record completions before parent restarts clear them, or keep a separate counter that survives those restarts.

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, fixed in ad129e6. Each repeating task now sets an occurred flag in _repeat (both backends), which ancestor restarts don't clear, and the env records rows from that flag instead of a rise in count. The env test now covers an event inside a repeating task, done in the step its parent restarts; letting the restart clear the flag turns it red.

… 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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation isaac-lab Related to Isaac Lab team

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant