Skip to content

Add HeterogeneousTaskManager to run different tasks across environments - #9161

Closed
Fanxing-LI wants to merge 13 commits into
isaac-sim:mainfrom
Fanxing-LI:fansing/heterogeneous-task-manager-v2
Closed

Fanxing-LI wants to merge 13 commits into
isaac-sim:mainfrom
Fanxing-LI:fansing/heterogeneous-task-manager-v2

Conversation

@Fanxing-LI

@Fanxing-LI Fanxing-LI commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Description

Depends on #9156 (InclusionSet.variants), whose commits this branch includes until it merges. It is also the prerequisite of heterogeneous tasks and VLA evaluation example branch.

This PR adds HeterogeneousTaskManager, with which each environment of a ManagerBasedRLEnv runs one of several tasks and switches tasks on reset. It serves evaluating or training one policy on a bank of tasks, for example hundreds of pick-and-place tasks, in a single simulation: tasks are assigned to environments at run time instead of building one environment per task or restarting the simulation.

HeterogeneousTaskManager.compose_tasks(cfg, tasks) composes complete task configurations into one environment configuration, typically in its __post_init__. The k-th rigid object of every task becomes a candidate of the scene entity object_<k>, spawned as the reset-time mesh variants of a MultiAssetSpawnerCfg; objects with equal spawn configurations share a candidate, tasks with fewer objects get hidden placeholders, and placeholder() lets a task leave a slot empty explicitly. Each task's termination terms are added as <task>_<term>, masked to the environments running the task, with their scene entities renamed to the slots; a term that the configuration defines itself can evaluate the tasks' terms of its name together through task_terms(). The time_out term ends episodes at the episode length of each environment's task. The reset event select_task is the manager itself: it runs before the other reset events, switches the objects of the environments whose task changed and writes the task poses into the default root poses, which the existing reset events then apply. set_task(env_ids, task_ids) takes effect at the next reset, and task_ids and candidate_ids() expose per environment which task runs and which candidate each slot holds. The clone combinations of the scene pin the first candidate of every slot, so clone planning builds one world prototype instead of the product of all candidates.

Because the objects are selected as reset-time mesh variants, the manager supports the Newton backend with the MJWarp solver and use_mujoco_contacts=False, or with the XPBD solver. Of the camera renderers, the Newton Warp renderer shows the selected objects; the renderers of the USD stage (Isaac RTX, OVRTX) are not available right now, and we gonna cooperate with renderer teams to support.

Tests: source/isaaclab/test/managers/test_heterogeneous_task_composition.py covers the composition rules on plain configurations (slots, shared candidates, kinematic placeholders and the rejection of slots that mix kinematic and dynamic objects, renaming of nested, listed and string-function terms, default-entity population, terms the environment keeps, composing once, clone pins). source/isaaclab_newton/test/envs/test_heterogeneous_task_manager.py (kitless, CUDA) runs three tasks across four environments on Newton and checks the placed objects, per-task terminations and time-outs, task observations, and that a reset refreshes the geometry only where the task changed.

No linked issue.

Type of change

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

Screenshots

Not applicable: no visual change.

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

Clone planning enumerates the product of the variant counts of all replicated assets, which runs out of memory for scenes with several multi-variant assets. InclusionSet.variants pins the variant of assets in a clone combination, so a scene lists its legal compositions instead. Planning now raises a ValueError naming the pins when it would enumerate more than ten million world prototypes.
The limit counts the world prototypes of all clone combinations together, and a test covers the scene path without combinations. A pin given as a narrow NumPy integer selects its variant, the error states the exact count, and the API reference lists the fields of InclusionSet.
Planning enumerates the product of the variant counts again and runs out of memory for scenes that are too large, instead of raising a ValueError. InclusionSet.variants and its validation stay.
Pinning every asset of a combination into one world is already asserted by the pinned variants test, and the test no longer has a limit to contrast with.
ManagerBasedRLEnvCfg.tasks lists the tasks that the environments run. Their
rigid objects are composed into switchable slots, their termination terms
are masked to the environments of each task, and their episode lengths are
kept per environment. Each environment runs one task and switches tasks on
reset, only where its task changed.
The environment classes are left as they are: the environment configuration calls HeterogeneousTaskManager.compose_tasks(cfg, tasks), which also adds the reset event that creates the task manager and selects the tasks before the other reset events.

The event creates the manager before the solver is built, where selecting objects has no effect. The clone combinations therefore pin the first candidate of every slot: every environment starts with the objects of the first task, and clone planning does not enumerate the combinations of all candidates.
Cover HeterogeneousTaskManager.task_terms and the rule that a termination defined by the environment configuration is not added again for each task.
Composing other tasks into a composed configuration raises instead of keeping the first select_task event; composing the same tasks again, as copying a configuration does, changes nothing. A configuration without events or terminations gets those of the tasks, and the docstring says when to compose configurations with presets.
The objects are selected as reset-time mesh variants: Newton physics simulates them, and of the camera renderers only the Newton Warp renderer shows the selected objects. The renderers of the USD stage keep showing the objects of the first task, and the Newton OptiX renderer rejects mesh variants.
Fold the task_terms lookup and the shared-candidate pose check into the test that runs the tasks, which now sets the task of every environment itself and compares the active termination terms as a set, since their order is incidental. Check that equal spawn configurations share a candidate in the composition unit test instead of on the simulator, drop the object observation term that no assertion read, and count the three tasks in the module docstring.
HeterogeneousTaskManager is the class-based reset event select_task itself, instead of a forwarding event term that created the manager and called its reset method: the switching happens in __call__. The slots start as the objects of the first task, which the clone plan pins, so the first reset writes variants only where a task changed; the variant ids are passed as int64, which the selection accepts; the parameters of a previous select_task event are read without a default. The class docstring reads "of which the rigid objects" and the task_terms summary is one line.
The task ids given to set_task are converted to int64, so int32 tensors are accepted instead of failing the assignment into the task buffer. A task whose terminations are None or missing contributes no terms instead of raising TypeError. compose_tasks rejects a slot whose objects are kinematic in one task and dynamic in another, because Newton gives all candidates of a slot the body of the first. The unit tests cover the None terminations and the rejection; the Newton test passes int32 task ids.
Unit tests now check that scene entities listed in a term parameter are renamed to the slots, that a term whose function is given as a resolvable string gets its omitted default renamed, that a task's own termination term is left untouched by the composition, and that a composed task term forwards its reset to a class-based nested term, which the termination manager does not see. The Newton test runs the default collision pipeline instead of pinning the SAP broad phase, which the task manager does not need.
@github-actions github-actions Bot added documentation Improvements or additions to documentation isaac-lab Related to Isaac Lab team labels Nov 23, 2026
@Fanxing-LI
Fanxing-LI requested a review from a team November 23, 2026 09:49

@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: Design and architecture (2), Scope and over-engineering (6), API (1), Implementation (5), Style consistency (2), Test quality (2). Other reviewed categories look good.

  • PR description: Shorten the API walkthrough, replace the renderer collaboration promise with current limitations, and report test outcomes plus reproducible step/reset baseline/candidate measurements: revisions, workload, hardware, backend, software environment, environment count, warmup, and metrics.
  • Design and architecture: Composition silently replaces occupied scene slots, redirecting destination terms to different assets; reject slot conflicts before modifying the scene.
  • Scope and over-engineering: Minimal implementation: keep heterogeneous_task_manager.py for pending-selection lifecycle state; extend EventManager and TerminationManager mechanisms, retaining pinning in cloner_cfg.py and replicate_session.py; collapse duplicate slot preparation, active-ID storage, repeated term renaming, unnecessary placeholders, quadratic deduplication, and full-batch reset indexing. Suggested PR breakdown: (1) clone pins and documentation, validated by planner and Newton initialization tests; (2) task composition and reset lifecycle, validated by composition and environment-boundary tests.
  • API: task_terms returns uninstantiated class-based configurations that callers cannot evaluate as documented; return prepared terms or evaluate them through the owning manager.
  • Compatibility and deprecation: No breaking changes identified.
  • Implementation: Composition mutates configuration before validating conflicts and accepts changed definitions under matching names, leaving missing events or stale terms; validate definitions and generated names before installing changes.
  • Style consistency: Absolute same-package imports and public-named internal term helpers violate repository conventions; use relative imports, private helper names, and the documented module ordering.
  • Test quality: The selective-refresh test cannot distinguish subset writes from rewriting every environment; observe selected writes or narrow its claim, and give the composition pin test actual alternatives.

Significant concerns. Posted 18 inline findings.

Automated review; human maintainers own approval decisions.

ValueError: If ``cfg`` is composed of other tasks already, or if the objects of a slot do not agree on
being kinematic.
"""
if cfg.events is None:

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.

🔴 Critical · Implementation — Initialize missing event configuration

When cfg.events is MISSING, _terms returns a detached dictionary; select_task is never installed. Initialize MISSING events on cfg, as done for terminations.

cfg.terminations = {}
events = _terms(cfg.events)
# Copying a configuration composes its tasks again; other tasks would leave slots and terms of the first.
previous = events.pop("select_task", None)

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.

🔴 Critical · Implementation — Validate before removing select_task

Recomposing with different task names pops the existing event before raising, leaving the original configuration without task selection. Inspect and validate the event before changing it.

events = _terms(cfg.events)
# Copying a configuration composes its tasks again; other tasks would leave slots and terms of the first.
previous = events.pop("select_task", None)
if previous is not None and list(previous.params["tasks"]) != list(tasks):

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.

🔴 Critical · Implementation — Reject changed task definitions

Matching task names permit recomposition with different objects or terms; old generated terms remain. Reject changed task definitions rather than treating matching keys as proof of identical composition.

obj = RigidObjectCfg(
prim_path=f"{{ENV_REGEX_NS}}/object_{slot}", spawn=spawn, init_state=objects[0].init_state
)
setattr(cfg.scene, f"object_{slot}", obj)

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.

🔴 Critical · Design Architecture — Reject occupied scene slots

An existing object_ is silently replaced, so destination terms can bind to a different asset. Check slot names before modifying the scene.

if term is None or term.time_out or name in terms:
continue
term = TerminationTermCfg(func=task_term, params={"task": index, "term": _slot_term(task, term)})
terms[f"{task_name}_{name}"] = term

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.

🔴 Critical · Implementation — Reject generated termination collisions

Tasks a_b and a with terms c and b_c both generate a_b_c; the later assignment discards one termination. Validate generated names before installing terms.

obj.data.default_root_pose.torch[env_ids] = self._poses[slot, tasks]


class task_term(ManagerTermBase):

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 — Mark internal term helpers private

task_term is an internal class named like a function, and task_time_out is also public-named without a package export. Give both private names and follow the documented module ordering.

f"The objects of slot {slot} mix kinematic and dynamic bodies, but the candidates of a slot share the"
" body of its first candidate: declare kinematic objects in the same slots in every task."
)
placeholder = HeterogeneousTaskManager.placeholder(slot, kinematic.pop())

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 · Scope Complexity — Allocate placeholders only when needed

_slot_objects constructs a placeholder even when every task fills the slot, and runs twice. Construct stand-ins only for slots with missing objects.

"""Return the distinct spawn configurations of a slot's objects and the index of each object's among them."""
keys = [dict_to_md5_hash(obj.spawn) for obj in objects]
variants = {key: index for index, key in enumerate(dict.fromkeys(keys))}
return [objects[keys.index(key)].spawn for key in variants], [variants[key] for key in keys]

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 · Scope Complexity — Deduplicate candidates in one pass

keys.index rescans the task list for every distinct candidate, making composition quadratic for large task banks. Record the first spawn and its index in one pass.

scene=SimpleNamespace(cube=_object("cube"), ball=_object("ball")), terminations={}, episode_length_s=5.0
)
cfg = _env_cfg()
HeterogeneousTaskManager.compose_tasks(cfg, {"a": task})

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 — Test pinning with actual alternatives

The fixture has one task and one candidate per slot, so pins cannot reduce prototype expansion. Use distinct candidates and assert the resulting clone-plan prototype count.

torch.testing.assert_close(position, torch.tensor([0.0, 0.2, 0.2], device=env.device))


def test_reset_switches_only_the_environments_whose_task_changed(env: ManagerBasedRLEnv):

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 — Prove or narrow selective refresh

A global geometry version increase and final masses still pass if every environment is rewritten. Observe selected variant writes, or limit the test's claim to unchanged resets.

@greptile-apps

greptile-apps Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 3/5

[Medium impact] The PR adds task selection and clone-planning options to configured simulation scenes.

Fix nested multi-asset spawning and termination-name collisions before merging.

Findings

  1. P1 Existing task objects cannot spawn ▶
  2. P1 Task termination checks disappear ▶
  3. P2 Starting velocities ignore task changes ▶

Summary

Adds HeterogeneousTaskManager to select tasks per environment on reset.

  • Environments in one batch can run different tasks and switch tasks on reset.
  • Clone combinations can pin assets to specific spawner variants.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[Task configurations] --> B[compose_tasks]
    B --> C[Object slots and pinned clone choices]
    B --> D[Task termination checks]
    B --> E[select_task reset event]
    F[set_task] --> E
    E --> G[Switch changed object variants]
    G --> H[Update default poses]
    H --> I[Run remaining reset events]
    D --> J[Mask results by selected task]
Loading

Reviews (1) · Last reviewed commit: "Cover the renaming, copying and reset of..." · Reviewed by Greptile

raise ValueError("The configuration is composed of other tasks already: compose its tasks once.")
slots = _slot_objects(tasks)
for slot, objects in enumerate(slots):
spawn = sim_utils.MultiAssetSpawnerCfg(assets_cfg=_variants(objects)[0], static=False, random_choice=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.

P1 Existing task objects cannot spawn

compose_tasks wraps existing multi-asset spawners inside another MultiAssetSpawnerCfg. The resolved default lift object already uses one. Only the outer spawner receives spawn_paths, so it calls the inner spawner with a concrete path. The inner spawner rejects that path because it has no wildcard, and environment creation fails.

Flatten these candidates with a clear selection rule, or reject them during composition with a useful error.

Comment on lines +140 to +146
terms = _terms(cfg.terminations)
for index, (task_name, task) in enumerate(tasks.items()):
for name, term in _terms(task.terminations).items():
if term is None or term.time_out or name in terms:
continue
term = TerminationTermCfg(func=task_term, params={"task": index, "term": _slot_term(task, term)})
terms[f"{task_name}_{name}"] = term

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 Task termination checks disappear

terms holds both the environment's terms and terms added by earlier tasks. This makes name in terms silently skip later checks: task a with term done adds a_done, which suppresses a later task's term named a_done.

Generated names can also collide. Task a_b with term c and task a with term b_c both write a_b_c, so the second replaces the first. These tasks can miss success or failure checks and continue when they should end.

Keep the original environment names separate and reject generated-name collisions.

Comment on lines +238 to +239
for slot, obj in enumerate(self._slots):
obj.data.default_root_pose.torch[env_ids] = self._poses[slot, tasks]

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.

P2 Starting velocities ignore task changes

Task changes update default_root_pose but leave default_root_vel at the first task's value. If another task sets different init_state.lin_vel or init_state.ang_vel, even reset_scene_to_default starts its object with the wrong velocity. This silently changes the task being run.

Preserve per-task velocities alongside poses, or explicitly reject differing velocities.

@Fanxing-LI Fanxing-LI mentioned this pull request Nov 24, 2026
6 tasks done
ooctipus added a commit that referenced this pull request Nov 24, 2026
…9156)

## Description

Multi-asset spawners can expose an enormous Cartesian product even when
a task only needs a few compatible worlds. Declare compatibility with
existing semantic tags and keep the legal choices compact until scene
planning selects concrete worlds.

```python
InclusionSet(assets=["gear", "fixture"], match_tags=["size", "assembly"])
```

- `InclusionSet` owns only asset membership, inclusion weight, and
matching tag types. No matching subclass, override method, positional
layouts, separate labels, environment count, or random seed is required.
- Selected variants must share a value for each requested tag type. A
universal fixture can list several `size` values. Repeat asset names for
cardinality; all selected instances share the requested tags. Unclaimed
assets remain independent. This expresses shared compatibility, not
separate pairwise constraints or sampling without replacement.
- Scene planning reads individual spawner tags, including inherited
wrapper tags, and resolves compatible tag-value groups. Each slot
retains its candidate prototype IDs instead of expanding every concrete
combination.
- `make_clone_plan` uses the existing scene clone strategy to select
groups and each slot's candidates, materializes only selected worlds,
and reuses identical concrete prototypes. Inclusion weights split
equally across compatible groups. Multi-valued tags can make groups
overlap; this is group-weighted selection, not uniform sampling over the
exhaustive union of concrete worlds.
- Without matching tags, retain the existing independent product and
assignment behavior.
- Replication execution remains unchanged. `ReplicateSession` only
receives broader type annotations for forwarding compact definitions;
inclusion interpretation stays outside it.

This is the generic prerequisite. Downstream task-manager,
heterogeneous-task, and VLA evaluation example changes (#9161, #9165 and
#9184 ) need to adopt the declarative API when restacked.

## Validation

- 36 clone-plan algebra tests, 17 replication-session tests, and one
Newton native asset test passed (54 total).
- Tests cover multi-valued universal tags, multiple matching tag types,
repeated instances, independent unclaimed assets, collection columns,
mixed concrete/factorized definitions, prototype reuse, invalid choices,
and external random-seed reproducibility.
- A case with 1,000 variants, five categories, and eight slots retained
five groups rather than expanding `5 * 200**8` concrete worlds; planning
128 environments created at most 128 concrete world prototypes.
- A standalone scene-planning check passed for collection members,
shared offsets, concrete MultiUsd candidates, inherited tags, and source
preservation. The Isaac Sim scene test cannot launch without its runtime
in this checkout.
- Removing inherited tag propagation makes the native regression fail;
restored code passes.
- Local planning benchmark: approximately 4.37 ms to resolve the
1,000-variant case and 0.85 ms to select 128 worlds, with about 510 KiB
peak Python planning allocation. This measures planning, not asset
loading or simulation.
- Full formatting checks and a file-by-file structural audit passed,
including unchanged replication execution after stripping annotations.

---------

Co-authored-by: Octi Zhang <zhengyuz@nvidia.com>
@Fanxing-LI Fanxing-LI closed this Nov 27, 2026
@Fanxing-LI

Fanxing-LI commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor Author

In #9184, implement in Event as alternative.

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