Skip to content

Commit 587fc82

Browse files
Fanxing-LIooctipus
andauthored
Declare semantic inclusion matches and select compact clone worlds (#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>
1 parent 99a3acd commit 587fc82

12 files changed

Lines changed: 350 additions & 65 deletions

File tree

‎docs/source/api/lab/isaaclab.cloner.rst‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,9 @@ Additional Public Classes
7575
:show-inheritance:
7676

7777
.. autoclass:: InclusionSet
78+
:members:
7879
:show-inheritance:
80+
:exclude-members: __init__
7981

8082
.. autoclass:: ReplicateContext
8183
:members:
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
* Added :attr:`~isaaclab.cloner.InclusionSet.match_tags` to declare variant compatibility using
2+
existing semantic tags, including multiple acceptable values. Matching groups stayed factorized
3+
until the scene's clone strategy selected concrete worlds, avoiding exhaustive combination
4+
expansion without inclusion callbacks, separate variant labels, or inclusion-owned sampling settings.

‎source/isaaclab/changelog.d/inclusion-world-layouts.minor‎

Whitespace-only changes.

‎source/isaaclab/isaaclab/cloner/__init__.pyi‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,15 +30,14 @@ __all__ = [
3030
]
3131

3232
from .clone_plan import ClonePlan, PrototypeWorldTopology, grid_transforms, make_clone_plan, path, query, to_warp
33-
from .cloner_cfg import CloneCfg, InclusionSet, add, expand_env_regex_ns
33+
from .cloner_cfg import CloneCfg, InclusionSet, add, expand_env_regex_ns, make_valid_clone_combinations
3434
from .cloner_strategies import random, sequential
3535
from .collision_filter import filter_collisions
3636
from .fabric_notices import disabled_fabric_change_notifies
3737
from .replicate_context import ReplicateContext
3838
from .replicate_session import (
3939
ReplicateSession,
4040
clone_plan_from_env_0,
41-
make_valid_clone_combinations,
4241
num_spawn_variants,
4342
replicate,
4443
)

‎source/isaaclab/isaaclab/cloner/clone_plan.py‎

Lines changed: 39 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ def to_warp(topology: PrototypeWorldTopology, device: str) -> PrototypeWorldTopo
8686

8787
def make_clone_plan(
8888
asset_cfgs: Sequence[Any],
89-
world_prototypes: Sequence[Sequence[int]],
89+
world_prototypes: Sequence[Sequence[int | Sequence[int]]],
9090
num_worlds: int,
9191
*,
9292
weights: Sequence[float] | None = None,
@@ -100,10 +100,15 @@ def make_clone_plan(
100100
Args:
101101
asset_cfgs: Asset prototype definitions, retained by reference.
102102
world_prototypes: Asset indices in each world prototype, including repeated instances.
103+
A slot may instead contain candidate indices. Such factorized groups are selected
104+
before their individual slots, without enumerating the Cartesian product. Only selected
105+
concrete worlds are materialized and identical selections reuse one prototype.
103106
num_worlds: Number of destination worlds.
104107
weights: Relative world-prototype weights; ``None`` gives every prototype equal weight.
105108
shared_assets: Asset indices instantiated once in the shared world ``-1``.
106-
clone_strategy: Function selecting world-prototype indices from weights.
109+
clone_strategy: Function selecting world-prototype indices from weights. For factorized
110+
groups, also selects each slot's concrete candidates with uniform candidate weights.
111+
The same strategy owns both decisions and any randomness they require.
107112
env_template: Destination-world path template with one ``{}`` slot for the world ID.
108113
positions: Destination-world origins [m], shape [num_worlds, 3]; None preserves authored placement.
109114
@@ -114,11 +119,6 @@ def make_clone_plan(
114119
compositions = (shared_assets, *world_prototypes)
115120
if len(compositions) == 1:
116121
raise ValueError("At least one world prototype is required; an empty world is ().")
117-
members = np.asarray([asset for world in compositions for asset in world])
118-
if members.size and (
119-
not np.issubdtype(members.dtype, np.integer) or (members < 0).any() or (members >= len(asset_cfgs)).any()
120-
):
121-
raise ValueError("World members must be integer indices into asset_cfgs.")
122122
weights = np.ones(len(compositions) - 1) if weights is None else np.asarray(weights, dtype=np.float64)
123123
if weights.shape != (len(compositions) - 1,) or not np.isfinite(weights).all() or (weights < 0).any():
124124
raise ValueError("Each world prototype requires one finite, non-negative weight.")
@@ -129,6 +129,38 @@ def make_clone_plan(
129129
has_valid_ids = is_world_layout and (layout >= 0).all() and (layout < len(weights)).all()
130130
if not has_valid_ids:
131131
raise ValueError("clone_strategy must select one valid world-prototype index per destination.")
132+
if any(not isinstance(slot, (int, np.integer)) for world in compositions[1:] for slot in world):
133+
groups = []
134+
for world in compositions[1:]:
135+
group = []
136+
for slot in world:
137+
choices = np.asarray([slot] if isinstance(slot, (int, np.integer)) else slot)
138+
is_index_list = choices.ndim == 1 and choices.size and np.issubdtype(choices.dtype, np.integer)
139+
if not is_index_list or (choices < 0).any() or (choices >= len(asset_cfgs)).any():
140+
raise ValueError("World choices must be nonempty integer indices into asset_cfgs.")
141+
group.append(choices)
142+
groups.append(group)
143+
selected = [None] * num_worlds
144+
for group_id in np.unique(layout):
145+
env_ids = np.flatnonzero(layout == group_id)
146+
columns = []
147+
for choices in groups[group_id]:
148+
ids = np.asarray(clone_strategy(np.ones(len(choices)), len(env_ids)))
149+
is_candidate_layout = ids.shape == (len(env_ids),) and np.issubdtype(ids.dtype, np.integer)
150+
if not is_candidate_layout or (ids < 0).any() or (ids >= len(choices)).any():
151+
raise ValueError("clone_strategy must select one valid candidate index per destination.")
152+
columns.append(choices[ids])
153+
rows = zip(*columns, strict=True) if columns else [()] * len(env_ids)
154+
for env_id, row in zip(env_ids, rows, strict=True):
155+
selected[env_id] = tuple(int(member) for member in row)
156+
prototype_ids = {world: index for index, world in enumerate(dict.fromkeys(selected))}
157+
layout = np.asarray([prototype_ids[world] for world in selected], dtype=np.int32)
158+
compositions = (shared_assets, *prototype_ids)
159+
members = np.asarray([asset for world in compositions for asset in world])
160+
if members.size and (
161+
not np.issubdtype(members.dtype, np.integer) or (members < 0).any() or (members >= len(asset_cfgs)).any()
162+
):
163+
raise ValueError("World members must be integer indices into asset_cfgs.")
132164
topology = PrototypeWorldTopology(
133165
num_asset_prototypes=len(asset_cfgs),
134166
world_prototypes=np.ascontiguousarray(members, dtype=np.int32),

‎source/isaaclab/isaaclab/cloner/cloner_cfg.py‎

Lines changed: 103 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,20 @@
55

66
from __future__ import annotations
77

8+
import itertools
89
import warnings
9-
from collections.abc import Callable
10+
from collections.abc import Callable, Sequence
1011
from dataclasses import MISSING
12+
from typing import TYPE_CHECKING
1113

1214
import numpy as np
1315

1416
from ..utils import configclass
1517
from .cloner_strategies import sequential
1618

19+
if TYPE_CHECKING:
20+
from ..sim.spawners.spawner_cfg import SpawnerCfg
21+
1722
DEFAULT_ENV_TEMPLATE = "/World/envs/env_{}"
1823
"""Default path template for a replicated env prim; ``{}`` marks the environment index."""
1924

@@ -39,14 +44,24 @@ def expand_env_regex_ns(path_expr: str, env_template: str = DEFAULT_ENV_TEMPLATE
3944

4045
@configclass
4146
class InclusionSet:
42-
"""Legal clone combination defined by explicitly listing active assets."""
47+
"""Legal world layouts for explicitly selected scene assets."""
4348

4449
assets: list[str] = MISSING
4550
"""Scene asset names active in this clone combination."""
4651

4752
weight: float = 1.0
4853
"""Relative sampling weight for this clone combination."""
4954

55+
match_tags: list[str] = []
56+
"""Semantic tag types whose values must overlap across the selected assets.
57+
58+
Each selected variant must share a value for every listed tag type. Multiple values for a
59+
tag express alternatives: a fixture supporting several sizes can match any one of them.
60+
Assets not claimed by any inclusion set remain independent and do not participate in matching.
61+
Empty keeps the existing independent Cartesian product. Matching groups remain factorized
62+
until the scene's clone strategy selects concrete variants for its environments.
63+
"""
64+
5065

5166
@configclass
5267
class CloneCfg:
@@ -65,6 +80,10 @@ class CloneCfg:
6580
Each entry names the assets that are active in one legal combination.
6681
Assets not referenced by any entry are active in every combination. An
6782
empty list keeps the homogeneous/default behavior.
83+
84+
Inclusion sets declare semantic compatibility through :attr:`InclusionSet.match_tags`.
85+
Planning resolves compatible groups before replication. The clone strategy selects groups
86+
and concrete variants; inclusion definitions do not own environment counts or random seeds.
6887
"""
6988

7089
clone_template: str = DEFAULT_ENV_TEMPLATE
@@ -82,6 +101,88 @@ def __post_init__(self) -> None:
82101
warnings.warn("CloneCfg.replicate_physics is deprecated and ignored.", DeprecationWarning, stacklevel=2)
83102

84103

104+
def make_valid_clone_combinations(
105+
asset_names: Sequence[str],
106+
variant_cfgs: Sequence[Sequence[SpawnerCfg]],
107+
clone_combinations: Sequence[InclusionSet] | None = None,
108+
*,
109+
all_asset_names: Sequence[str] | None = None,
110+
) -> tuple[tuple[tuple[int | tuple[int, ...], ...], ...], np.ndarray]:
111+
"""Resolve inclusion membership and semantic compatibility before replication.
112+
113+
Repeated names create repeated instances. Unclaimed assets join every world independently.
114+
Without matching tags, preserve the existing exhaustive product. With matching tags, return
115+
compact compatible groups: each slot lists its candidate prototype IDs, without expanding
116+
the Cartesian product within a group. Concrete selection belongs to clone-plan construction.
117+
118+
Args:
119+
asset_names: Names of the replicated asset declarations.
120+
variant_cfgs: Concrete spawner configurations for each replicated declaration, including
121+
semantic tags inherited from their multi-asset wrapper.
122+
clone_combinations: Legal world definitions; None uses the default independent product.
123+
all_asset_names: Scene names, including shared assets that do not enter world memberships.
124+
125+
Returns:
126+
World definitions and their relative weights. A definition contains concrete prototype IDs
127+
or tuples of alternative IDs per slot. Inclusion weight is split equally across definitions.
128+
129+
Raises:
130+
ValueError: Candidate groups are empty or misaligned, asset names are unknown, or no
131+
compatible world exists.
132+
"""
133+
if len(asset_names) != len(variant_cfgs) or any(not candidates for candidates in variant_cfgs):
134+
raise ValueError("Each asset requires a nonempty group of variant configurations.")
135+
known = set(asset_names if all_asset_names is None else all_asset_names)
136+
combinations = clone_combinations or (InclusionSet(assets=list(dict.fromkeys(asset_names))),)
137+
claimed = set().union(*(combination.assets for combination in combinations))
138+
offsets = np.cumsum([0, *(len(candidates) for candidates in variant_cfgs)])
139+
worlds, weights = [], []
140+
for combination in combinations:
141+
if unknown := set(combination.assets) - known:
142+
raise ValueError(f"Unknown assets in clone combination: {sorted(unknown)}.")
143+
names, choices, candidates = [], [], []
144+
for index, name in enumerate(asset_names):
145+
count = combination.assets.count(name) if name in claimed else 1
146+
names.extend([name] * count)
147+
choices.extend([tuple(range(int(offsets[index]), int(offsets[index + 1])))] * count)
148+
candidates.extend([variant_cfgs[index]] * count)
149+
start = len(worlds)
150+
if not combination.match_tags:
151+
worlds.extend(itertools.product(*choices))
152+
else:
153+
buckets = []
154+
common = None
155+
for name, ids, configs in zip(names, choices, candidates, strict=True):
156+
if name not in combination.assets:
157+
buckets.append(None)
158+
continue
159+
groups = {}
160+
for prototype, cfg in zip(ids, configs, strict=True):
161+
tags = cfg.semantic_tags or ()
162+
values = [
163+
tuple(dict.fromkeys(value for tag, value in tags if tag == key))
164+
for key in combination.match_tags
165+
]
166+
for key in itertools.product(*values):
167+
groups.setdefault(key, []).append(prototype)
168+
buckets.append(groups)
169+
common = list(groups) if common is None else [key for key in common if key in groups]
170+
for key in [()] if common is None else common:
171+
worlds.append(
172+
tuple(
173+
tuple(group[key]) if group is not None else ids
174+
for group, ids in zip(buckets, choices, strict=True)
175+
)
176+
)
177+
# Identical groups can arise when all candidates carry several matching values.
178+
worlds[start:] = dict.fromkeys(worlds[start:])
179+
count = len(worlds) - start
180+
if not count:
181+
raise ValueError("An inclusion set must define at least one compatible world.")
182+
weights.extend([combination.weight / count] * count)
183+
return tuple(worlds), np.asarray(weights, dtype=np.float64)
184+
185+
85186
def add(this: CloneCfg, other: InclusionSet) -> CloneCfg:
86187
"""Append one clone combination to ``this`` and return it.
87188

‎source/isaaclab/isaaclab/cloner/replicate_session.py‎

Lines changed: 3 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
from ..utils.version import has_kit
2323
from .clone_plan import ClonePlan, grid_transforms, make_clone_plan
2424
from .clone_plan import path as cloner_path
25-
from .cloner_cfg import DEFAULT_ENV_TEMPLATE, CloneCfg, InclusionSet, expand_env_regex_ns
25+
from .cloner_cfg import DEFAULT_ENV_TEMPLATE, CloneCfg, expand_env_regex_ns
2626
from .cloner_strategies import sequential
2727
from .replicate_context import ReplicateContext
2828
from .usd import UsdReplicateContext
@@ -37,47 +37,6 @@ def num_spawn_variants(spawn_cfg: Any) -> int:
3737
return 1
3838

3939

40-
def make_valid_clone_combinations(
41-
asset_names: Sequence[str],
42-
variant_counts: Sequence[int],
43-
clone_combinations: Sequence[InclusionSet] | None = None,
44-
*,
45-
all_asset_names: Sequence[str] | None = None,
46-
) -> tuple[tuple[tuple[int, ...], ...], np.ndarray]:
47-
"""Expand named combinations into world memberships and relative weights.
48-
49-
Repeated names create repeated instances. Each combination's weight is divided equally
50-
between its variant combinations; neither padding nor duplicate weighted worlds is needed.
51-
52-
Args:
53-
asset_names: Names of the replicated asset declarations.
54-
variant_counts: Number of concrete prototypes for each declaration.
55-
clone_combinations: Allowed memberships; unnamed assets are present once in every world.
56-
all_asset_names: Scene names, including shared assets that do not enter world memberships.
57-
58-
Returns:
59-
World prototypes indexing the flat variant library, and one weight per world prototype.
60-
"""
61-
if len(asset_names) != len(variant_counts) or any(count <= 0 for count in variant_counts):
62-
raise ValueError("Each asset requires one positive variant count.")
63-
known = set(asset_names if all_asset_names is None else all_asset_names)
64-
combinations = clone_combinations or (InclusionSet(assets=list(dict.fromkeys(asset_names))),)
65-
claimed = set().union(*(combination.assets for combination in combinations))
66-
offsets = np.cumsum([0, *variant_counts])
67-
worlds, weights = [], []
68-
for combination in combinations:
69-
if unknown := set(combination.assets) - known:
70-
raise ValueError(f"Unknown assets in clone combination: {sorted(unknown)}.")
71-
choices = []
72-
for index, name in enumerate(asset_names):
73-
count = combination.assets.count(name) if name in claimed else 1
74-
choices.extend([range(*offsets[index : index + 2])] * count)
75-
variants = tuple(itertools.product(*choices))
76-
worlds.extend(variants)
77-
weights.extend([combination.weight / len(variants)] * len(variants))
78-
return tuple(worlds), np.asarray(weights, dtype=np.float64)
79-
80-
8140
def replicate(plan: ClonePlan, *, replicate_physics: bool | None = None) -> None:
8241
"""Execute one topology through its declared clone contexts.
8342
@@ -185,7 +144,7 @@ def __init__(
185144
env_spacing: float,
186145
*,
187146
clone_strategy: Callable[[np.ndarray, int], np.ndarray] = sequential,
188-
world_prototypes: Sequence[Sequence[int]] | None = None,
147+
world_prototypes: Sequence[Sequence[int | Sequence[int]]] | None = None,
189148
weights: Sequence[float] | None = None,
190149
replicate_physics: bool | None = None,
191150
env_template: str = DEFAULT_ENV_TEMPLATE,
@@ -215,7 +174,7 @@ def _prepare_cloning(
215174
env_spacing: float,
216175
*,
217176
clone_strategy: Callable[[np.ndarray, int], np.ndarray] = sequential,
218-
world_prototypes: Sequence[Sequence[int]] | None = None,
177+
world_prototypes: Sequence[Sequence[int | Sequence[int]]] | None = None,
219178
weights: Sequence[float] | None = None,
220179
env_template: str = DEFAULT_ENV_TEMPLATE,
221180
positions: np.ndarray | None = None,

0 commit comments

Comments
 (0)