From ace1e8609dae1a113091dcf936c0121c734bd5a5 Mon Sep 17 00:00:00 2001 From: Fanxing-LI Date: Sun, 22 Nov 2026 02:08:11 +0800 Subject: [PATCH 1/8] Pin spawner variants in clone combinations 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. --- docs/source/how-to/multi_asset_spawning.rst | 15 +++++++- .../pinned-clone-variants.added.rst | 2 ++ .../pinned-clone-variants.changed.rst | 2 ++ .../changelog.d/pinned-clone-variants.minor | 0 source/isaaclab/isaaclab/cloner/cloner_cfg.py | 15 ++++++++ .../isaaclab/cloner/replicate_session.py | 34 +++++++++++++++++-- .../test/cloner/test_replicate_session.py | 34 +++++++++++++++++++ .../changelog.d/pinned-clone-variants.skip | 0 .../assets/test_rigid_object_mesh_variants.py | 33 ++++++++++++++++++ 9 files changed, 131 insertions(+), 4 deletions(-) create mode 100644 source/isaaclab/changelog.d/pinned-clone-variants.added.rst create mode 100644 source/isaaclab/changelog.d/pinned-clone-variants.changed.rst create mode 100644 source/isaaclab/changelog.d/pinned-clone-variants.minor create mode 100644 source/isaaclab_newton/changelog.d/pinned-clone-variants.skip diff --git a/docs/source/how-to/multi_asset_spawning.rst b/docs/source/how-to/multi_asset_spawning.rst index c7c8fea60849..eb36c3bf43b8 100644 --- a/docs/source/how-to/multi_asset_spawning.rst +++ b/docs/source/how-to/multi_asset_spawning.rst @@ -131,13 +131,26 @@ variant because their batched Newton views currently require a uniform body layo :end-at: scene_cfg.robot.spawn.usd_path = scene_cfg.robot.spawn.usd_path[0] :dedent: 8 +Clone planning creates one world prototype per choice of variant of every multi-variant asset, so their number is the +product of the variant counts. When only some compositions are legal, or the product is too large to enumerate, list +them by pinning variants with :attr:`~isaaclab.cloner.InclusionSet.variants`. Each combination then expands only over +the assets it leaves unpinned, and the clone strategy distributes the worlds over the combinations by their weights: + +.. code-block:: python + + scene_cfg.clone_cfg.clone_combinations = [ + InclusionSet(assets=["part", "fixture"], variants={"part": 0, "fixture": 2}), + InclusionSet(assets=["part", "fixture"], variants={"part": 1, "fixture": 0}, weight=3.0), + ] + For more detail on prototype assignment and replication, see :doc:`cloning`. Reset-time selection ~~~~~~~~~~~~~~~~~~~~ A rigid object's multi-asset spawner defines the variants and their IDs in list order. Clone composition chooses -the initial variant for each world. A reset event can change it before writing the episode's pose and velocity: +the initial variant for each world; pinned variants use the same IDs. A reset event can change it before writing the +episode's pose and velocity: .. code-block:: python diff --git a/source/isaaclab/changelog.d/pinned-clone-variants.added.rst b/source/isaaclab/changelog.d/pinned-clone-variants.added.rst new file mode 100644 index 000000000000..563ce846da03 --- /dev/null +++ b/source/isaaclab/changelog.d/pinned-clone-variants.added.rst @@ -0,0 +1,2 @@ +* Added :attr:`~isaaclab.cloner.InclusionSet.variants` to pin the spawner variant of assets in a clone combination, so + scenes can list their legal variant-level compositions instead of enumerating the product of all variant counts. diff --git a/source/isaaclab/changelog.d/pinned-clone-variants.changed.rst b/source/isaaclab/changelog.d/pinned-clone-variants.changed.rst new file mode 100644 index 000000000000..525ce34b997e --- /dev/null +++ b/source/isaaclab/changelog.d/pinned-clone-variants.changed.rst @@ -0,0 +1,2 @@ +* Changed clone planning to raise a ``ValueError`` that names :attr:`~isaaclab.cloner.InclusionSet.variants` when it + would enumerate more than ten million world prototypes, instead of exhausting memory. diff --git a/source/isaaclab/changelog.d/pinned-clone-variants.minor b/source/isaaclab/changelog.d/pinned-clone-variants.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab/isaaclab/cloner/cloner_cfg.py b/source/isaaclab/isaaclab/cloner/cloner_cfg.py index 6f951e36c5ec..cd42c289c82a 100644 --- a/source/isaaclab/isaaclab/cloner/cloner_cfg.py +++ b/source/isaaclab/isaaclab/cloner/cloner_cfg.py @@ -47,6 +47,17 @@ class InclusionSet: weight: float = 1.0 """Relative sampling weight for this clone combination.""" + variants: dict[str, int] = {} + """Spawner variant pinned for assets of this clone combination, keyed by scene asset name. + + The value indexes the asset's multi-asset spawner list. A pinned asset contributes only that + variant, in each of its repeated instances and each member of a rigid object collection. Every + other multi-variant asset of the combination still contributes all of its variants, so the + combination expands into their product; pinning all of them states one world composition. The + asset must be active in the combination: listed in :attr:`assets`, or referenced by no + combination. + """ + @configclass class CloneCfg: @@ -65,6 +76,10 @@ class CloneCfg: Each entry names the assets that are active in one legal combination. Assets not referenced by any entry are active in every combination. An empty list keeps the homogeneous/default behavior. + + A combination expands into one world prototype per choice of spawner variant + of its multi-variant assets. Pin variants with :attr:`InclusionSet.variants` + to list the legal variant-level compositions instead of their product. """ clone_template: str = DEFAULT_ENV_TEMPLATE diff --git a/source/isaaclab/isaaclab/cloner/replicate_session.py b/source/isaaclab/isaaclab/cloner/replicate_session.py index 65d65d60249c..8dc7bcef61f8 100644 --- a/source/isaaclab/isaaclab/cloner/replicate_session.py +++ b/source/isaaclab/isaaclab/cloner/replicate_session.py @@ -9,6 +9,7 @@ import copy import itertools +import math import warnings from collections.abc import Callable, Iterable, Sequence from typing import Any @@ -27,6 +28,9 @@ from .replicate_context import ReplicateContext from .usd import UsdReplicateContext +_MAX_WORLD_PROTOTYPES = 10_000_000 +"""Largest number of world prototypes that clone planning enumerates.""" + def num_spawn_variants(spawn_cfg: Any) -> int: """Return the number of concrete prototypes declared by a spawner configuration.""" @@ -48,6 +52,8 @@ def make_valid_clone_combinations( Repeated names create repeated instances. Each combination's weight is divided equally between its variant combinations; neither padding nor duplicate weighted worlds is needed. + Only the assets a combination does not pin through :attr:`InclusionSet.variants` are + enumerated, so a combination pinning every multi-variant asset is one world prototype. Args: asset_names: Names of the replicated asset declarations. @@ -68,16 +74,38 @@ def make_valid_clone_combinations( for combination in combinations: if unknown := set(combination.assets) - known: raise ValueError(f"Unknown assets in clone combination: {sorted(unknown)}.") + active = {name for name in asset_names if name in combination.assets or name not in claimed} + if inactive := set(combination.variants) - active: + raise ValueError(f"Clone combination pins variants of assets it does not replicate: {sorted(inactive)}.") choices = [] for index, name in enumerate(asset_names): count = combination.assets.count(name) if name in claimed else 1 - choices.extend([range(*offsets[index : index + 2])] * count) - variants = tuple(itertools.product(*choices)) + rows = range(*offsets[index : index + 2]) + if name in combination.variants: + variant = combination.variants[name] + is_index = isinstance(variant, (int, np.integer)) and not isinstance(variant, bool) + if not is_index or not 0 <= variant < len(rows): + raise ValueError(f"Cannot pin variant {variant!r} of {name!r}: it declares {len(rows)}.") + rows = rows[variant : variant + 1] + choices.extend([rows] * count) + variants = _world_prototypes(choices) worlds.extend(variants) weights.extend([combination.weight / len(variants)] * len(variants)) return tuple(worlds), np.asarray(weights, dtype=np.float64) +def _world_prototypes(choices: Sequence[Sequence[int]]) -> tuple[tuple[int, ...], ...]: + """Return every world prototype that takes one prototype row from each entry of ``choices``.""" + count = math.prod(map(len, choices)) + if count > _MAX_WORLD_PROTOTYPES: + raise ValueError( + f"Clone planning would enumerate {count:.3g} world prototypes, the product of the variant counts of the" + f" replicated assets, which exceeds {_MAX_WORLD_PROTOTYPES}. Pin the variants of the legal compositions" + " with InclusionSet.variants." + ) + return tuple(itertools.product(*choices)) + + def replicate(plan: ClonePlan, *, replicate_physics: bool | None = None) -> None: """Execute one topology through its declared clone contexts. @@ -263,7 +291,7 @@ def _prepare_cloning( shared.extend(indices) else: groups.append(indices) - worlds = tuple(itertools.product(*groups)) if world_prototypes is None else world_prototypes + worlds = _world_prototypes(groups) if world_prototypes is None else world_prototypes positions = grid_transforms(num_clones, env_spacing)[0] if positions is None else positions options = dict(weights=weights, shared_assets=shared, clone_strategy=clone_strategy, env_template=env_template) plan = make_clone_plan(asset_prototypes, worlds, num_clones, positions=positions, **options) diff --git a/source/isaaclab/test/cloner/test_replicate_session.py b/source/isaaclab/test/cloner/test_replicate_session.py index 308b13063ab7..fd585adc1cd7 100644 --- a/source/isaaclab/test/cloner/test_replicate_session.py +++ b/source/isaaclab/test/cloner/test_replicate_session.py @@ -17,11 +17,13 @@ from isaaclab.assets import AssetBaseCfg, RigidObjectCfg from isaaclab.cloner import ( CloneCfg, + InclusionSet, ReplicateContext, ReplicateSession, UsdReplicateContext, clone_plan_from_env_0, grid_transforms, + make_valid_clone_combinations, ) from isaaclab.cloner import path as cloner_path from isaaclab.renderers import RenderContext, RendererCfg @@ -285,6 +287,38 @@ def test_multi_spawner_creates_concrete_asset_prototypes(simulation, unused_vari assert all(1 not in ids for _, _, ids in simulation.calls) +def test_pinned_variants_narrow_a_combination_to_its_unpinned_product(): + """A pin fixes one asset's variant, also for repeated instances; only unpinned assets multiply.""" + # Flat prototype rows: robot 0, part 1-3, tool 4-5, lamp 6-7. Unclaimed robot and lamp join every world. + names, counts = ["robot", "part", "tool", "lamp"], [1, 3, 2, 2] + combinations = [ + InclusionSet(assets=["part", "tool"], variants={"part": 2, "tool": 0, "lamp": 0}, weight=3.0), + InclusionSet(assets=["part", "part", "tool"], variants={"part": 1, "lamp": 1}), + ] + worlds, weights = make_valid_clone_combinations(names, counts, combinations) + # Pinning every multi-variant asset leaves one world carrying the whole weight; the free tool splits the other. + assert worlds == ((0, 3, 4, 6), (0, 2, 2, 4, 7), (0, 2, 2, 5, 7)) + np.testing.assert_array_equal(weights, [3.0, 0.5, 0.5]) + + with pytest.raises(ValueError, match="does not replicate.*'tool'"): + absent = [InclusionSet(assets=["part"], variants={"tool": 0}), InclusionSet(assets=["tool"])] + make_valid_clone_combinations(names, counts, absent) + # A pin is an index into the asset's variants; None does not leave the asset free. + for variant in (3, -1, None, True): + with pytest.raises(ValueError, match=f"Cannot pin variant {variant} of 'part'"): + make_valid_clone_combinations(names, counts, [InclusionSet(assets=["part"], variants={"part": variant})]) + + +def test_clone_planning_rejects_products_too_large_to_enumerate(): + """Planning names the pins instead of running out of memory, with and without clone combinations.""" + names, counts = [f"object_{index}" for index in range(9)], [20] * 9 + with pytest.raises(ValueError, match="5.12e\\+11 world prototypes.*InclusionSet.variants"): + make_valid_clone_combinations(names, counts) + pins = [InclusionSet(assets=names, variants=dict.fromkeys(names, task)) for task in range(20)] + worlds, _ = make_valid_clone_combinations(names, counts, pins) + assert len(worlds) == 20 + + def test_replicate_session_clears_plan_when_asset_init_fails(simulation): """Failed construction releases the plan without dispatching any clone backend.""" with pytest.raises(RuntimeError, match="asset boom"): diff --git a/source/isaaclab_newton/changelog.d/pinned-clone-variants.skip b/source/isaaclab_newton/changelog.d/pinned-clone-variants.skip new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_newton/test/assets/test_rigid_object_mesh_variants.py b/source/isaaclab_newton/test/assets/test_rigid_object_mesh_variants.py index dafee5374c5b..eb75d2d7bc3e 100644 --- a/source/isaaclab_newton/test/assets/test_rigid_object_mesh_variants.py +++ b/source/isaaclab_newton/test/assets/test_rigid_object_mesh_variants.py @@ -19,6 +19,7 @@ import isaaclab.sim as sim_utils from isaaclab.assets import RigidObjectCfg +from isaaclab.cloner import InclusionSet from isaaclab.scene import InteractiveScene, InteractiveSceneCfg from isaaclab.sim import build_simulation_context from isaaclab.test.utils import DeviceScope, test_devices @@ -149,6 +150,38 @@ def test_native_selection_preserves_initial_worlds_and_unused_variant(device: st torch.testing.assert_close(asset.mesh_variant_ids.torch.cpu(), torch.tensor([2, 1], dtype=torch.int32)) +@pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) +def test_pinned_clone_combinations_choose_initial_variants(device: str) -> None: + """Each world starts with the variants its clone combination pins, for reset-time and static spawners.""" + scene_cfg = _VariantSceneCfg(num_envs=4, env_spacing=2.0) + third = scene_cfg.object.spawn.assets_cfg[0].copy() + third.radius, third.mass_props.mass = 0.06, 27.0 + scene_cfg.object.spawn.assets_cfg.append(third) + scene_cfg.fixture = _variant_object() + scene_cfg.fixture.prim_path = "{ENV_REGEX_NS}/Fixture" + scene_cfg.fixture.spawn.static = True + scene_cfg.fixture.init_state.pos = (0.5, 0.0, 0.2) + # The second combination leaves the fixture free, so it expands into one world prototype per fixture variant. + scene_cfg.clone_cfg.clone_combinations = [ + InclusionSet(assets=["object", "fixture"], variants={"object": 2, "fixture": 1}), + InclusionSet(assets=["object", "fixture"], variants={"object": 0}), + ] + sim_cfg = SimulationCfg( + device=device, + gravity=(0.0, 0.0, 0.0), + physics=NewtonCfg(solver_cfg=MJWarpSolverCfg(use_mujoco_contacts=False), use_cuda_graph=False), + ) + with build_simulation_context(sim_cfg=sim_cfg) as sim: + sim._app_control_on_stop_handle = None + scene = InteractiveScene(scene_cfg) + sim.register_interactive_scene(scene) + sim.reset() + asset, fixture = scene["object"], scene["fixture"] + torch.testing.assert_close(asset.mesh_variant_ids.torch.cpu(), torch.tensor([2, 2, 0, 0], dtype=torch.int32)) + torch.testing.assert_close(asset.data.body_mass.torch[:, 0].cpu(), torch.tensor([27.0, 27.0, 1.0, 1.0])) + torch.testing.assert_close(fixture.data.body_mass.torch[:, 0].cpu(), torch.tensor([8.0, 8.0, 1.0, 8.0])) + + @pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) @pytest.mark.parametrize( "solver_cfg, static", From 9c7a0f815b0b3920d04a3723ce6d47d51504ca4f Mon Sep 17 00:00:00 2001 From: Fanxing-LI Date: Sun, 22 Nov 2026 03:35:37 +0800 Subject: [PATCH 2/8] Bound the world prototypes of the whole clone plan 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. --- docs/source/api/lab/isaaclab.cloner.rst | 2 ++ .../pinned-clone-variants.changed.rst | 2 +- .../isaaclab/cloner/replicate_session.py | 17 +++++++++----- .../test/cloner/test_replicate_session.py | 23 ++++++++++++++++--- 4 files changed, 34 insertions(+), 10 deletions(-) diff --git a/docs/source/api/lab/isaaclab.cloner.rst b/docs/source/api/lab/isaaclab.cloner.rst index e62630515597..b82da7bb583e 100644 --- a/docs/source/api/lab/isaaclab.cloner.rst +++ b/docs/source/api/lab/isaaclab.cloner.rst @@ -75,7 +75,9 @@ Additional Public Classes :show-inheritance: .. autoclass:: InclusionSet + :members: :show-inheritance: + :exclude-members: __init__ .. autoclass:: ReplicateContext :members: diff --git a/source/isaaclab/changelog.d/pinned-clone-variants.changed.rst b/source/isaaclab/changelog.d/pinned-clone-variants.changed.rst index 525ce34b997e..eaab5a9427e8 100644 --- a/source/isaaclab/changelog.d/pinned-clone-variants.changed.rst +++ b/source/isaaclab/changelog.d/pinned-clone-variants.changed.rst @@ -1,2 +1,2 @@ * Changed clone planning to raise a ``ValueError`` that names :attr:`~isaaclab.cloner.InclusionSet.variants` when it - would enumerate more than ten million world prototypes, instead of exhausting memory. + would enumerate more than ten million world prototypes, instead of enumerating them. diff --git a/source/isaaclab/isaaclab/cloner/replicate_session.py b/source/isaaclab/isaaclab/cloner/replicate_session.py index 8dc7bcef61f8..1303d8fde6cb 100644 --- a/source/isaaclab/isaaclab/cloner/replicate_session.py +++ b/source/isaaclab/isaaclab/cloner/replicate_session.py @@ -86,20 +86,25 @@ def make_valid_clone_combinations( is_index = isinstance(variant, (int, np.integer)) and not isinstance(variant, bool) if not is_index or not 0 <= variant < len(rows): raise ValueError(f"Cannot pin variant {variant!r} of {name!r}: it declares {len(rows)}.") - rows = rows[variant : variant + 1] + rows = (rows[int(variant)],) choices.extend([rows] * count) - variants = _world_prototypes(choices) + variants = _world_prototypes(choices, len(worlds)) worlds.extend(variants) weights.extend([combination.weight / len(variants)] * len(variants)) return tuple(worlds), np.asarray(weights, dtype=np.float64) -def _world_prototypes(choices: Sequence[Sequence[int]]) -> tuple[tuple[int, ...], ...]: - """Return every world prototype that takes one prototype row from each entry of ``choices``.""" - count = math.prod(map(len, choices)) +def _world_prototypes(choices: Sequence[Sequence[int]], planned: int = 0) -> tuple[tuple[int, ...], ...]: + """Return every world prototype that takes one prototype row from each entry of ``choices``. + + Args: + choices: Prototype rows to choose from, per asset instance. + planned: Number of world prototypes that the plan already holds. + """ + count = planned + math.prod(map(len, choices)) if count > _MAX_WORLD_PROTOTYPES: raise ValueError( - f"Clone planning would enumerate {count:.3g} world prototypes, the product of the variant counts of the" + f"Clone planning would enumerate {count} world prototypes, the product of the variant counts of the" f" replicated assets, which exceeds {_MAX_WORLD_PROTOTYPES}. Pin the variants of the legal compositions" " with InclusionSet.variants." ) diff --git a/source/isaaclab/test/cloner/test_replicate_session.py b/source/isaaclab/test/cloner/test_replicate_session.py index fd585adc1cd7..2972cfca9f18 100644 --- a/source/isaaclab/test/cloner/test_replicate_session.py +++ b/source/isaaclab/test/cloner/test_replicate_session.py @@ -309,15 +309,32 @@ def test_pinned_variants_narrow_a_combination_to_its_unpinned_product(): make_valid_clone_combinations(names, counts, [InclusionSet(assets=["part"], variants={"part": variant})]) -def test_clone_planning_rejects_products_too_large_to_enumerate(): - """Planning names the pins instead of running out of memory, with and without clone combinations.""" +def test_clone_planning_rejects_products_too_large_to_enumerate(simulation, monkeypatch): + """Planning names the pins instead of enumerating too many world prototypes, for combinations and for a scene.""" names, counts = [f"object_{index}" for index in range(9)], [20] * 9 - with pytest.raises(ValueError, match="5.12e\\+11 world prototypes.*InclusionSet.variants"): + with pytest.raises(ValueError, match="512000000000 world prototypes.*InclusionSet.variants"): make_valid_clone_combinations(names, counts) pins = [InclusionSet(assets=names, variants=dict.fromkeys(names, task)) for task in range(20)] worlds, _ = make_valid_clone_combinations(names, counts, pins) assert len(worlds) == 20 + monkeypatch.setattr(replicate_session, "_MAX_WORLD_PROTOTYPES", 10) + # The limit bounds the plan, not each combination. + with pytest.raises(ValueError, match="12 world prototypes"): + make_valid_clone_combinations(["part"], [6], [InclusionSet(assets=["part"])] * 2) + # A scene without clone combinations enumerates the product in the session. + shapes = [CuboidCfg(size=(1, 1, 1)), SphereCfg(radius=1)] * 2 + objects = [ + RigidObjectCfg(prim_path=f"{{ENV_REGEX_NS}}/Object{index}", spawn=MultiAssetSpawnerCfg(assets_cfg=shapes)) + for index in range(2) + ] + with ( + pytest.raises(ValueError, match="16 world prototypes.*InclusionSet.variants"), + ReplicateSession(objects, 4, 2.0), + ): + pass + assert simulation.plan is None + def test_replicate_session_clears_plan_when_asset_init_fails(simulation): """Failed construction releases the plan without dispatching any clone backend.""" From 75dc8660769cfefa133d3446d2a42aa8b3eccbf3 Mon Sep 17 00:00:00 2001 From: Fanxing-LI Date: Mon, 23 Nov 2026 11:25:27 +0800 Subject: [PATCH 3/8] Remove the world prototype limit of clone planning 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. --- .../pinned-clone-variants.changed.rst | 2 -- .../isaaclab/cloner/replicate_session.py | 25 ++----------------- .../test/cloner/test_replicate_session.py | 23 ++--------------- 3 files changed, 4 insertions(+), 46 deletions(-) delete mode 100644 source/isaaclab/changelog.d/pinned-clone-variants.changed.rst diff --git a/source/isaaclab/changelog.d/pinned-clone-variants.changed.rst b/source/isaaclab/changelog.d/pinned-clone-variants.changed.rst deleted file mode 100644 index eaab5a9427e8..000000000000 --- a/source/isaaclab/changelog.d/pinned-clone-variants.changed.rst +++ /dev/null @@ -1,2 +0,0 @@ -* Changed clone planning to raise a ``ValueError`` that names :attr:`~isaaclab.cloner.InclusionSet.variants` when it - would enumerate more than ten million world prototypes, instead of enumerating them. diff --git a/source/isaaclab/isaaclab/cloner/replicate_session.py b/source/isaaclab/isaaclab/cloner/replicate_session.py index 1303d8fde6cb..7c29bdb64cfb 100644 --- a/source/isaaclab/isaaclab/cloner/replicate_session.py +++ b/source/isaaclab/isaaclab/cloner/replicate_session.py @@ -9,7 +9,6 @@ import copy import itertools -import math import warnings from collections.abc import Callable, Iterable, Sequence from typing import Any @@ -28,9 +27,6 @@ from .replicate_context import ReplicateContext from .usd import UsdReplicateContext -_MAX_WORLD_PROTOTYPES = 10_000_000 -"""Largest number of world prototypes that clone planning enumerates.""" - def num_spawn_variants(spawn_cfg: Any) -> int: """Return the number of concrete prototypes declared by a spawner configuration.""" @@ -88,29 +84,12 @@ def make_valid_clone_combinations( raise ValueError(f"Cannot pin variant {variant!r} of {name!r}: it declares {len(rows)}.") rows = (rows[int(variant)],) choices.extend([rows] * count) - variants = _world_prototypes(choices, len(worlds)) + variants = tuple(itertools.product(*choices)) worlds.extend(variants) weights.extend([combination.weight / len(variants)] * len(variants)) return tuple(worlds), np.asarray(weights, dtype=np.float64) -def _world_prototypes(choices: Sequence[Sequence[int]], planned: int = 0) -> tuple[tuple[int, ...], ...]: - """Return every world prototype that takes one prototype row from each entry of ``choices``. - - Args: - choices: Prototype rows to choose from, per asset instance. - planned: Number of world prototypes that the plan already holds. - """ - count = planned + math.prod(map(len, choices)) - if count > _MAX_WORLD_PROTOTYPES: - raise ValueError( - f"Clone planning would enumerate {count} world prototypes, the product of the variant counts of the" - f" replicated assets, which exceeds {_MAX_WORLD_PROTOTYPES}. Pin the variants of the legal compositions" - " with InclusionSet.variants." - ) - return tuple(itertools.product(*choices)) - - def replicate(plan: ClonePlan, *, replicate_physics: bool | None = None) -> None: """Execute one topology through its declared clone contexts. @@ -296,7 +275,7 @@ def _prepare_cloning( shared.extend(indices) else: groups.append(indices) - worlds = _world_prototypes(groups) if world_prototypes is None else world_prototypes + worlds = tuple(itertools.product(*groups)) if world_prototypes is None else world_prototypes positions = grid_transforms(num_clones, env_spacing)[0] if positions is None else positions options = dict(weights=weights, shared_assets=shared, clone_strategy=clone_strategy, env_template=env_template) plan = make_clone_plan(asset_prototypes, worlds, num_clones, positions=positions, **options) diff --git a/source/isaaclab/test/cloner/test_replicate_session.py b/source/isaaclab/test/cloner/test_replicate_session.py index 2972cfca9f18..4ab3ededa6c9 100644 --- a/source/isaaclab/test/cloner/test_replicate_session.py +++ b/source/isaaclab/test/cloner/test_replicate_session.py @@ -309,32 +309,13 @@ def test_pinned_variants_narrow_a_combination_to_its_unpinned_product(): make_valid_clone_combinations(names, counts, [InclusionSet(assets=["part"], variants={"part": variant})]) -def test_clone_planning_rejects_products_too_large_to_enumerate(simulation, monkeypatch): - """Planning names the pins instead of enumerating too many world prototypes, for combinations and for a scene.""" +def test_pinned_combinations_list_compositions_instead_of_their_product(): + """Pinning every asset of a combination yields one world prototype per combination.""" names, counts = [f"object_{index}" for index in range(9)], [20] * 9 - with pytest.raises(ValueError, match="512000000000 world prototypes.*InclusionSet.variants"): - make_valid_clone_combinations(names, counts) pins = [InclusionSet(assets=names, variants=dict.fromkeys(names, task)) for task in range(20)] worlds, _ = make_valid_clone_combinations(names, counts, pins) assert len(worlds) == 20 - monkeypatch.setattr(replicate_session, "_MAX_WORLD_PROTOTYPES", 10) - # The limit bounds the plan, not each combination. - with pytest.raises(ValueError, match="12 world prototypes"): - make_valid_clone_combinations(["part"], [6], [InclusionSet(assets=["part"])] * 2) - # A scene without clone combinations enumerates the product in the session. - shapes = [CuboidCfg(size=(1, 1, 1)), SphereCfg(radius=1)] * 2 - objects = [ - RigidObjectCfg(prim_path=f"{{ENV_REGEX_NS}}/Object{index}", spawn=MultiAssetSpawnerCfg(assets_cfg=shapes)) - for index in range(2) - ] - with ( - pytest.raises(ValueError, match="16 world prototypes.*InclusionSet.variants"), - ReplicateSession(objects, 4, 2.0), - ): - pass - assert simulation.plan is None - def test_replicate_session_clears_plan_when_asset_init_fails(simulation): """Failed construction releases the plan without dispatching any clone backend.""" From c763fc34a5df42a742b50ec1a67d280ea395609e Mon Sep 17 00:00:00 2001 From: Fanxing-LI Date: Mon, 23 Nov 2026 13:51:30 +0800 Subject: [PATCH 4/8] Remove the redundant pinned-world count test 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. --- source/isaaclab/test/cloner/test_replicate_session.py | 8 -------- 1 file changed, 8 deletions(-) diff --git a/source/isaaclab/test/cloner/test_replicate_session.py b/source/isaaclab/test/cloner/test_replicate_session.py index 4ab3ededa6c9..58ef5a35d87f 100644 --- a/source/isaaclab/test/cloner/test_replicate_session.py +++ b/source/isaaclab/test/cloner/test_replicate_session.py @@ -309,14 +309,6 @@ def test_pinned_variants_narrow_a_combination_to_its_unpinned_product(): make_valid_clone_combinations(names, counts, [InclusionSet(assets=["part"], variants={"part": variant})]) -def test_pinned_combinations_list_compositions_instead_of_their_product(): - """Pinning every asset of a combination yields one world prototype per combination.""" - names, counts = [f"object_{index}" for index in range(9)], [20] * 9 - pins = [InclusionSet(assets=names, variants=dict.fromkeys(names, task)) for task in range(20)] - worlds, _ = make_valid_clone_combinations(names, counts, pins) - assert len(worlds) == 20 - - def test_replicate_session_clears_plan_when_asset_init_fails(simulation): """Failed construction releases the plan without dispatching any clone backend.""" with pytest.raises(RuntimeError, match="asset boom"): From 41f14dbede54b207377cba8843ff385bf783d03f Mon Sep 17 00:00:00 2001 From: Octi Zhang Date: Mon, 23 Nov 2026 15:10:02 -0800 Subject: [PATCH 5/8] Define inclusion world layouts before replication --- docs/source/how-to/multi_asset_spawning.rst | 29 +++-- docs/source/refs/contributing.rst | 3 + .../inclusion-world-layouts.added.rst | 3 + ...ts.minor => inclusion-world-layouts.minor} | 0 .../pinned-clone-variants.added.rst | 2 - source/isaaclab/isaaclab/cloner/__init__.pyi | 3 +- source/isaaclab/isaaclab/cloner/cloner_cfg.py | 101 +++++++++++++++--- .../isaaclab/cloner/replicate_session.py | 55 +--------- .../test/cloner/test_clone_plan_algebra.py | 65 ++++++++++- .../test/cloner/test_replicate_session.py | 24 ----- .../changelog.d/inclusion-world-layouts.skip | 0 .../assets/test_rigid_object_mesh_variants.py | 10 +- 12 files changed, 186 insertions(+), 109 deletions(-) create mode 100644 source/isaaclab/changelog.d/inclusion-world-layouts.added.rst rename source/isaaclab/changelog.d/{pinned-clone-variants.minor => inclusion-world-layouts.minor} (100%) delete mode 100644 source/isaaclab/changelog.d/pinned-clone-variants.added.rst create mode 100644 source/isaaclab_newton/changelog.d/inclusion-world-layouts.skip diff --git a/docs/source/how-to/multi_asset_spawning.rst b/docs/source/how-to/multi_asset_spawning.rst index eb36c3bf43b8..0fbd1317ee62 100644 --- a/docs/source/how-to/multi_asset_spawning.rst +++ b/docs/source/how-to/multi_asset_spawning.rst @@ -131,25 +131,40 @@ variant because their batched Newton views currently require a uniform body layo :end-at: scene_cfg.robot.spawn.usd_path = scene_cfg.robot.spawn.usd_path[0] :dedent: 8 -Clone planning creates one world prototype per choice of variant of every multi-variant asset, so their number is the -product of the variant counts. When only some compositions are legal, or the product is too large to enumerate, list -them by pinning variants with :attr:`~isaaclab.cloner.InclusionSet.variants`. Each combination then expands only over -the assets it leaves unpinned, and the clone strategy distributes the worlds over the combinations by their weights: +An :class:`~isaaclab.cloner.InclusionSet` defines the legal world layouts before replication. By default, its +active assets choose variants independently. Explicit :attr:`~isaaclab.cloner.InclusionSet.layouts` list only +legal pairings; each row selects local spawner variant indices in active scene declaration order, including +unclaimed assets and repeated instances. For a scene declaring ``part`` then ``fixture``: .. code-block:: python scene_cfg.clone_cfg.clone_combinations = [ - InclusionSet(assets=["part", "fixture"], variants={"part": 0, "fixture": 2}), - InclusionSet(assets=["part", "fixture"], variants={"part": 1, "fixture": 0}, weight=3.0), + InclusionSet(assets=["part", "fixture"], layouts=[(0, 2), (1, 0)]), ] +For mathematical pairing rules, override :meth:`~isaaclab.cloner.InclusionSet.worlds`: + +.. code-block:: python + + class MatchedWorlds(InclusionSet): + def worlds(self, asset_names, variants): + return zip(*variants, strict=True) + + scene_cfg.clone_cfg.clone_combinations = [MatchedWorlds(assets=["part", "fixture"])] + +Each candidate range indexes one active asset instance's spawner. This definition pairs equal variant indices +instead of constructing their Cartesian product; the example requires equal candidate counts. More general +subclasses can express coupled choices directly. Their outputs are validated and translated into prototype IDs +by scene planning; ``ReplicateSession`` consumes those IDs without interpreting the definition. An inclusion +set's weight is split equally over its generated layouts. + For more detail on prototype assignment and replication, see :doc:`cloning`. Reset-time selection ~~~~~~~~~~~~~~~~~~~~ A rigid object's multi-asset spawner defines the variants and their IDs in list order. Clone composition chooses -the initial variant for each world; pinned variants use the same IDs. A reset event can change it before writing the +the initial variant for each world, using those same IDs. A reset event can change it before writing the episode's pose and velocity: .. code-block:: python diff --git a/docs/source/refs/contributing.rst b/docs/source/refs/contributing.rst index 3cc5aa051dc7..490ceb8c3676 100644 --- a/docs/source/refs/contributing.rst +++ b/docs/source/refs/contributing.rst @@ -439,6 +439,9 @@ before changing an interface. Apply these rules when adding code or cleaning up required attribute; express optional fields explicitly in the interface. Use concrete defaults for known empty selections. Reserve ``None`` for a distinct policy or lifecycle state, such as choosing an environment's frame rate or waiting for a client to connect. +* Inclusion definitions own legal world layouts, including explicit rows and pairing formulas. Resolve them + during scene planning before entering ``ReplicateSession``. Keep inclusion interpretation and task-specific + combination policies out of replication execution; do not add variant-pinning exceptions there. * Give each piece of state and validation one owner. Consumers should use the owner's contract instead of repairing results or maintaining duplicate state. Cache derived values only when their lifetime and invalidation are clear; do not expose mutable cached results for callers to modify accidentally. diff --git a/source/isaaclab/changelog.d/inclusion-world-layouts.added.rst b/source/isaaclab/changelog.d/inclusion-world-layouts.added.rst new file mode 100644 index 000000000000..73504ac68322 --- /dev/null +++ b/source/isaaclab/changelog.d/inclusion-world-layouts.added.rst @@ -0,0 +1,3 @@ +* Added explicit :attr:`~isaaclab.cloner.InclusionSet.layouts` and an overridable + :meth:`~isaaclab.cloner.InclusionSet.worlds` definition for legal world pairings. Scene planning + resolves these definitions before replication, without enumerating excluded Cartesian combinations. diff --git a/source/isaaclab/changelog.d/pinned-clone-variants.minor b/source/isaaclab/changelog.d/inclusion-world-layouts.minor similarity index 100% rename from source/isaaclab/changelog.d/pinned-clone-variants.minor rename to source/isaaclab/changelog.d/inclusion-world-layouts.minor diff --git a/source/isaaclab/changelog.d/pinned-clone-variants.added.rst b/source/isaaclab/changelog.d/pinned-clone-variants.added.rst deleted file mode 100644 index 563ce846da03..000000000000 --- a/source/isaaclab/changelog.d/pinned-clone-variants.added.rst +++ /dev/null @@ -1,2 +0,0 @@ -* Added :attr:`~isaaclab.cloner.InclusionSet.variants` to pin the spawner variant of assets in a clone combination, so - scenes can list their legal variant-level compositions instead of enumerating the product of all variant counts. diff --git a/source/isaaclab/isaaclab/cloner/__init__.pyi b/source/isaaclab/isaaclab/cloner/__init__.pyi index 09718dfa6f1a..ef2eb17b1062 100644 --- a/source/isaaclab/isaaclab/cloner/__init__.pyi +++ b/source/isaaclab/isaaclab/cloner/__init__.pyi @@ -30,7 +30,7 @@ __all__ = [ ] from .clone_plan import ClonePlan, PrototypeWorldTopology, grid_transforms, make_clone_plan, path, query, to_warp -from .cloner_cfg import CloneCfg, InclusionSet, add, expand_env_regex_ns +from .cloner_cfg import CloneCfg, InclusionSet, add, expand_env_regex_ns, make_valid_clone_combinations from .cloner_strategies import random, sequential from .collision_filter import filter_collisions from .fabric_notices import disabled_fabric_change_notifies @@ -38,7 +38,6 @@ from .replicate_context import ReplicateContext from .replicate_session import ( ReplicateSession, clone_plan_from_env_0, - make_valid_clone_combinations, num_spawn_variants, replicate, ) diff --git a/source/isaaclab/isaaclab/cloner/cloner_cfg.py b/source/isaaclab/isaaclab/cloner/cloner_cfg.py index cd42c289c82a..20af748ffcaf 100644 --- a/source/isaaclab/isaaclab/cloner/cloner_cfg.py +++ b/source/isaaclab/isaaclab/cloner/cloner_cfg.py @@ -5,8 +5,9 @@ from __future__ import annotations +import itertools import warnings -from collections.abc import Callable +from collections.abc import Callable, Iterable, Sequence from dataclasses import MISSING import numpy as np @@ -39,7 +40,7 @@ def expand_env_regex_ns(path_expr: str, env_template: str = DEFAULT_ENV_TEMPLATE @configclass class InclusionSet: - """Legal clone combination defined by explicitly listing active assets.""" + """Legal world layouts for explicitly selected scene assets.""" assets: list[str] = MISSING """Scene asset names active in this clone combination.""" @@ -47,17 +48,30 @@ class InclusionSet: weight: float = 1.0 """Relative sampling weight for this clone combination.""" - variants: dict[str, int] = {} - """Spawner variant pinned for assets of this clone combination, keyed by scene asset name. + layouts: Sequence[Sequence[int]] | None = None + """Explicit variant-index rows; None uses the independent product. - The value indexes the asset's multi-asset spawner list. A pinned asset contributes only that - variant, in each of its repeated instances and each member of a rigid object collection. Every - other multi-variant asset of the combination still contributes all of its variants, so the - combination expands into their product; pinning all of them states one world composition. The - asset must be active in the combination: listed in :attr:`assets`, or referenced by no - combination. + Columns follow active scene declaration order; repeated instances and members of a rigid + object collection each have their own column. Unclaimed assets also contribute columns, + once per declaration. Indices are local to each declaration's spawner, starting at zero. """ + def worlds(self, asset_names: Sequence[str], variants: Sequence[range]) -> Iterable[Sequence[int]]: + """Generate legal layouts without constructing combinations that the definition excludes. + + Override this method to pair or otherwise couple asset choices. The default returns + :attr:`layouts` when supplied, otherwise the Cartesian product of the candidate ranges. + The inclusion set's weight is divided equally over the generated layouts. + + Args: + asset_names: Active scene declaration name of each column, including repeated instances. + variants: Candidate variant indices for each column, as ``range(variant_count)``. + + Returns: + Rows selecting one local variant index per column, in the supplied order. + """ + return itertools.product(*variants) if self.layouts is None else self.layouts + @configclass class CloneCfg: @@ -77,9 +91,9 @@ class CloneCfg: Assets not referenced by any entry are active in every combination. An empty list keeps the homogeneous/default behavior. - A combination expands into one world prototype per choice of spawner variant - of its multi-variant assets. Pin variants with :attr:`InclusionSet.variants` - to list the legal variant-level compositions instead of their product. + Each inclusion set defines its legal world layouts through :meth:`InclusionSet.worlds`. + Explicit rows and custom inclusion subclasses are resolved before replication; replication + consumes the resulting world prototypes without interpreting inclusion rules. """ clone_template: str = DEFAULT_ENV_TEMPLATE @@ -97,6 +111,67 @@ def __post_init__(self) -> None: warnings.warn("CloneCfg.replicate_physics is deprecated and ignored.", DeprecationWarning, stacklevel=2) +def make_valid_clone_combinations( + asset_names: Sequence[str], + variant_counts: Sequence[int], + clone_combinations: Sequence[InclusionSet] | None = None, + *, + all_asset_names: Sequence[str] | None = None, +) -> tuple[tuple[tuple[int, ...], ...], np.ndarray]: + """Resolve inclusion definitions into flat asset-prototype memberships and relative weights. + + Repeated names create repeated instances. Unclaimed assets join every world. Each inclusion + set owns the layouts it generates; explicit or coupled layouts never expand into an independent + Cartesian product. Columns follow replicated scene declaration order, including repeated instances. + + Args: + asset_names: Names of the replicated asset declarations. + variant_counts: Number of concrete prototypes for each declaration. + clone_combinations: Legal world definitions; None uses the default independent product. + all_asset_names: Scene names, including shared assets that do not enter world memberships. + + Returns: + World memberships indexing the flat variant library, and one relative weight per world. + + Raises: + ValueError: A declaration, asset name, layout width, or variant index is invalid, or a + definition produces no worlds. + """ + if len(asset_names) != len(variant_counts) or any(count <= 0 for count in variant_counts): + raise ValueError("Each asset requires one positive variant count.") + known = set(asset_names if all_asset_names is None else all_asset_names) + combinations = clone_combinations or (InclusionSet(assets=list(dict.fromkeys(asset_names))),) + claimed = set().union(*(combination.assets for combination in combinations)) + offsets = np.cumsum([0, *variant_counts]) + worlds, weights = [], [] + for combination in combinations: + if unknown := set(combination.assets) - known: + raise ValueError(f"Unknown assets in clone combination: {sorted(unknown)}.") + names, choices, starts = [], [], [] + for index, name in enumerate(asset_names): + count = combination.assets.count(name) if name in claimed else 1 + names.extend([name] * count) + choices.extend([range(variant_counts[index])] * count) + starts.extend([offsets[index]] * count) + layouts = combination.worlds(names, choices) + num_worlds = len(worlds) + for layout in layouts: + if len(layout) != len(choices): + raise ValueError(f"World layout requires {len(choices)} variant indices, got {len(layout)}.") + for variant, candidates in zip(layout, choices, strict=True): + is_index = isinstance(variant, (int, np.integer)) and not isinstance(variant, bool) + if not is_index or not 0 <= variant < len(candidates): + raise ValueError( + f"Invalid variant index {variant!r}: expected an integer in [0, {len(candidates)})." + ) + worlds.append(tuple(int(start + variant) for start, variant in zip(starts, layout, strict=True))) + count = len(worlds) - num_worlds + if not count: + raise ValueError("An inclusion set must define at least one world layout.") + weights.extend([combination.weight / count] * count) + return tuple(worlds), np.asarray(weights, dtype=np.float64) + + def add(this: CloneCfg, other: InclusionSet) -> CloneCfg: """Append one clone combination to ``this`` and return it. diff --git a/source/isaaclab/isaaclab/cloner/replicate_session.py b/source/isaaclab/isaaclab/cloner/replicate_session.py index 7c29bdb64cfb..811e558134f6 100644 --- a/source/isaaclab/isaaclab/cloner/replicate_session.py +++ b/source/isaaclab/isaaclab/cloner/replicate_session.py @@ -22,7 +22,7 @@ from ..utils.version import has_kit from .clone_plan import ClonePlan, grid_transforms, make_clone_plan from .clone_plan import path as cloner_path -from .cloner_cfg import DEFAULT_ENV_TEMPLATE, CloneCfg, InclusionSet, expand_env_regex_ns +from .cloner_cfg import DEFAULT_ENV_TEMPLATE, CloneCfg, expand_env_regex_ns from .cloner_strategies import sequential from .replicate_context import ReplicateContext from .usd import UsdReplicateContext @@ -37,59 +37,6 @@ def num_spawn_variants(spawn_cfg: Any) -> int: return 1 -def make_valid_clone_combinations( - asset_names: Sequence[str], - variant_counts: Sequence[int], - clone_combinations: Sequence[InclusionSet] | None = None, - *, - all_asset_names: Sequence[str] | None = None, -) -> tuple[tuple[tuple[int, ...], ...], np.ndarray]: - """Expand named combinations into world memberships and relative weights. - - Repeated names create repeated instances. Each combination's weight is divided equally - between its variant combinations; neither padding nor duplicate weighted worlds is needed. - Only the assets a combination does not pin through :attr:`InclusionSet.variants` are - enumerated, so a combination pinning every multi-variant asset is one world prototype. - - Args: - asset_names: Names of the replicated asset declarations. - variant_counts: Number of concrete prototypes for each declaration. - clone_combinations: Allowed memberships; unnamed assets are present once in every world. - all_asset_names: Scene names, including shared assets that do not enter world memberships. - - Returns: - World prototypes indexing the flat variant library, and one weight per world prototype. - """ - if len(asset_names) != len(variant_counts) or any(count <= 0 for count in variant_counts): - raise ValueError("Each asset requires one positive variant count.") - known = set(asset_names if all_asset_names is None else all_asset_names) - combinations = clone_combinations or (InclusionSet(assets=list(dict.fromkeys(asset_names))),) - claimed = set().union(*(combination.assets for combination in combinations)) - offsets = np.cumsum([0, *variant_counts]) - worlds, weights = [], [] - for combination in combinations: - if unknown := set(combination.assets) - known: - raise ValueError(f"Unknown assets in clone combination: {sorted(unknown)}.") - active = {name for name in asset_names if name in combination.assets or name not in claimed} - if inactive := set(combination.variants) - active: - raise ValueError(f"Clone combination pins variants of assets it does not replicate: {sorted(inactive)}.") - choices = [] - for index, name in enumerate(asset_names): - count = combination.assets.count(name) if name in claimed else 1 - rows = range(*offsets[index : index + 2]) - if name in combination.variants: - variant = combination.variants[name] - is_index = isinstance(variant, (int, np.integer)) and not isinstance(variant, bool) - if not is_index or not 0 <= variant < len(rows): - raise ValueError(f"Cannot pin variant {variant!r} of {name!r}: it declares {len(rows)}.") - rows = (rows[int(variant)],) - choices.extend([rows] * count) - variants = tuple(itertools.product(*choices)) - worlds.extend(variants) - weights.extend([combination.weight / len(variants)] * len(variants)) - return tuple(worlds), np.asarray(weights, dtype=np.float64) - - def replicate(plan: ClonePlan, *, replicate_physics: bool | None = None) -> None: """Execute one topology through its declared clone contexts. diff --git a/source/isaaclab/test/cloner/test_clone_plan_algebra.py b/source/isaaclab/test/cloner/test_clone_plan_algebra.py index ba2c2a015f91..5bd9a67edd41 100644 --- a/source/isaaclab/test/cloner/test_clone_plan_algebra.py +++ b/source/isaaclab/test/cloner/test_clone_plan_algebra.py @@ -3,7 +3,7 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Tests for the cloner path/query algebra. +"""Tests for inclusion definitions and the cloner path/query algebra. These exercise :class:`isaaclab.cloner.path` and :class:`isaaclab.cloner.query`, which are pure string/array operations over topology and path templates. They need no stage, no @@ -11,6 +11,7 @@ """ import ast +import itertools import subprocess import sys from pathlib import Path @@ -21,7 +22,7 @@ from isaaclab import cloner from isaaclab.assets import AssetBaseCfg -from isaaclab.cloner import make_clone_plan +from isaaclab.cloner import InclusionSet, make_clone_plan, make_valid_clone_combinations from isaaclab.sim import CuboidCfg ## @@ -105,9 +106,21 @@ def test_clone_ownership_and_import_boundaries(): assert result.returncode == 0, result.stderr assert result.stdout.strip() == "False", "generic clone topology and queries imported the USD backend" + assert "variants" not in InclusionSet.__dataclass_fields__, "InclusionSet owns layouts rather than variant pins" + source = Path(__file__).resolve().parents[3] for file in source.glob("*/isaaclab*/**/*.py"): tree = ast.parse(file.read_text()) + if file.name == "replicate_session.py": + assert not any( + isinstance(node, (ast.FunctionDef, ast.ClassDef)) + and node.name in {"InclusionSet", "make_valid_clone_combinations"} + or isinstance(node, ast.Attribute) + and node.attr in {"layouts", "worlds"} + or isinstance(node, ast.Name) + and node.id == "InclusionSet" + for node in ast.walk(tree) + ), "Inclusion definitions must resolve legal layouts before ReplicateSession consumes them" # Only cloning execution and its lifecycle owners may access context instances. if "cloner" not in file.parts and file.name not in {"simulation_context.py", "render_context.py"}: assert not any( @@ -327,3 +340,51 @@ def test_batched_world_queries(device, worlds, num_worlds, shared, selectors): starts = short[1] if device == "numpy" else short[1].numpy() np.testing.assert_array_equal(values, [-99]) assert starts[-1, -1] == len(expected) + + +class _PairedWorlds(InclusionSet): + def worlds(self, asset_names, variants): + return itertools.islice(zip(*variants), 3) + + +def test_inclusion_layouts_generate_legal_worlds_before_replication(): + """Explicit and paired definitions avoid an astronomical product; default products still work.""" + names = [f"object_{index}" for index in range(8)] + worlds, weights = make_valid_clone_combinations(names, [1_000_000] * 8, [_PairedWorlds(assets=names)]) + assert worlds == ( + (0, 1000000, 2000000, 3000000, 4000000, 5000000, 6000000, 7000000), + (1, 1000001, 2000001, 3000001, 4000001, 5000001, 6000001, 7000001), + (2, 1000002, 2000002, 3000002, 4000002, 5000002, 6000002, 7000002), + ) + np.testing.assert_array_equal(weights, [1 / 3] * 3) + + # Repeated declarations, unclaimed assets, and weights retain their membership semantics. + selections = [ + InclusionSet(assets=["part", "tool"], layouts=[(0, 2, 0, 0)], weight=3.0), + InclusionSet(assets=["part", "part", "tool"], layouts=[(0, 1, 1, 0, 1), (0, 1, 1, 1, 1)]), + ] + worlds, weights = make_valid_clone_combinations(["robot", "part", "tool", "lamp"], [1, 3, 2, 2], selections) + assert worlds == ((0, 3, 4, 6), (0, 2, 2, 4, 7), (0, 2, 2, 5, 7)) + np.testing.assert_array_equal(weights, [3.0, 0.5, 0.5]) + + worlds, weights = make_valid_clone_combinations(["part", "tool"], [2, 3]) + assert worlds == ((0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4)) + np.testing.assert_array_equal(weights, [1 / 6] * 6) + + +@pytest.mark.parametrize( + "layouts, message", + [ + ([(0,)], "requires 2 variant indices"), + ([(0, 2)], "Invalid variant index 2"), + ([(0, -1)], "Invalid variant index -1"), + ([(True, 0)], "Invalid variant index True"), + ([(None, 0)], "Invalid variant index None"), + ([], "at least one world"), + ], +) +def test_inclusion_layouts_reject_invalid_definitions(layouts, message): + with pytest.raises(ValueError, match=message): + make_valid_clone_combinations( + ["part", "tool"], [2, 2], [InclusionSet(assets=["part", "tool"], layouts=layouts)] + ) diff --git a/source/isaaclab/test/cloner/test_replicate_session.py b/source/isaaclab/test/cloner/test_replicate_session.py index 58ef5a35d87f..308b13063ab7 100644 --- a/source/isaaclab/test/cloner/test_replicate_session.py +++ b/source/isaaclab/test/cloner/test_replicate_session.py @@ -17,13 +17,11 @@ from isaaclab.assets import AssetBaseCfg, RigidObjectCfg from isaaclab.cloner import ( CloneCfg, - InclusionSet, ReplicateContext, ReplicateSession, UsdReplicateContext, clone_plan_from_env_0, grid_transforms, - make_valid_clone_combinations, ) from isaaclab.cloner import path as cloner_path from isaaclab.renderers import RenderContext, RendererCfg @@ -287,28 +285,6 @@ def test_multi_spawner_creates_concrete_asset_prototypes(simulation, unused_vari assert all(1 not in ids for _, _, ids in simulation.calls) -def test_pinned_variants_narrow_a_combination_to_its_unpinned_product(): - """A pin fixes one asset's variant, also for repeated instances; only unpinned assets multiply.""" - # Flat prototype rows: robot 0, part 1-3, tool 4-5, lamp 6-7. Unclaimed robot and lamp join every world. - names, counts = ["robot", "part", "tool", "lamp"], [1, 3, 2, 2] - combinations = [ - InclusionSet(assets=["part", "tool"], variants={"part": 2, "tool": 0, "lamp": 0}, weight=3.0), - InclusionSet(assets=["part", "part", "tool"], variants={"part": 1, "lamp": 1}), - ] - worlds, weights = make_valid_clone_combinations(names, counts, combinations) - # Pinning every multi-variant asset leaves one world carrying the whole weight; the free tool splits the other. - assert worlds == ((0, 3, 4, 6), (0, 2, 2, 4, 7), (0, 2, 2, 5, 7)) - np.testing.assert_array_equal(weights, [3.0, 0.5, 0.5]) - - with pytest.raises(ValueError, match="does not replicate.*'tool'"): - absent = [InclusionSet(assets=["part"], variants={"tool": 0}), InclusionSet(assets=["tool"])] - make_valid_clone_combinations(names, counts, absent) - # A pin is an index into the asset's variants; None does not leave the asset free. - for variant in (3, -1, None, True): - with pytest.raises(ValueError, match=f"Cannot pin variant {variant} of 'part'"): - make_valid_clone_combinations(names, counts, [InclusionSet(assets=["part"], variants={"part": variant})]) - - def test_replicate_session_clears_plan_when_asset_init_fails(simulation): """Failed construction releases the plan without dispatching any clone backend.""" with pytest.raises(RuntimeError, match="asset boom"): diff --git a/source/isaaclab_newton/changelog.d/inclusion-world-layouts.skip b/source/isaaclab_newton/changelog.d/inclusion-world-layouts.skip new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_newton/test/assets/test_rigid_object_mesh_variants.py b/source/isaaclab_newton/test/assets/test_rigid_object_mesh_variants.py index eb75d2d7bc3e..3adc4436385c 100644 --- a/source/isaaclab_newton/test/assets/test_rigid_object_mesh_variants.py +++ b/source/isaaclab_newton/test/assets/test_rigid_object_mesh_variants.py @@ -151,8 +151,8 @@ def test_native_selection_preserves_initial_worlds_and_unused_variant(device: st @pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) -def test_pinned_clone_combinations_choose_initial_variants(device: str) -> None: - """Each world starts with the variants its clone combination pins, for reset-time and static spawners.""" +def test_explicit_world_layouts_choose_initial_variants(device: str) -> None: + """Each world starts with its explicitly selected variants, for reset-time and static spawners.""" scene_cfg = _VariantSceneCfg(num_envs=4, env_spacing=2.0) third = scene_cfg.object.spawn.assets_cfg[0].copy() third.radius, third.mass_props.mass = 0.06, 27.0 @@ -161,10 +161,10 @@ def test_pinned_clone_combinations_choose_initial_variants(device: str) -> None: scene_cfg.fixture.prim_path = "{ENV_REGEX_NS}/Fixture" scene_cfg.fixture.spawn.static = True scene_cfg.fixture.init_state.pos = (0.5, 0.0, 0.2) - # The second combination leaves the fixture free, so it expands into one world prototype per fixture variant. + # The second definition explicitly pairs the first object with both fixture variants. scene_cfg.clone_cfg.clone_combinations = [ - InclusionSet(assets=["object", "fixture"], variants={"object": 2, "fixture": 1}), - InclusionSet(assets=["object", "fixture"], variants={"object": 0}), + InclusionSet(assets=["object", "fixture"], layouts=[(2, 1)]), + InclusionSet(assets=["object", "fixture"], layouts=[(0, 0), (0, 1)]), ] sim_cfg = SimulationCfg( device=device, From 99002df8ed30d3ccf41f8a1c0320976396d7e323 Mon Sep 17 00:00:00 2001 From: Octi Zhang Date: Mon, 23 Nov 2026 15:27:06 -0800 Subject: [PATCH 6/8] Select inclusion worlds using existing spawner semantics --- docs/source/how-to/multi_asset_spawning.rst | 63 +++++++--- docs/source/refs/contributing.rst | 8 +- .../inclusion-world-layouts.added.rst | 7 +- source/isaaclab/isaaclab/cloner/cloner_cfg.py | 94 +++++++------- .../isaaclab/scene/interactive_scene.py | 22 +++- .../test/cloner/test_clone_plan_algebra.py | 118 +++++++++++++----- .../assets/test_rigid_object_mesh_variants.py | 28 ++++- 7 files changed, 239 insertions(+), 101 deletions(-) diff --git a/docs/source/how-to/multi_asset_spawning.rst b/docs/source/how-to/multi_asset_spawning.rst index 0fbd1317ee62..d6434219e78c 100644 --- a/docs/source/how-to/multi_asset_spawning.rst +++ b/docs/source/how-to/multi_asset_spawning.rst @@ -131,32 +131,67 @@ variant because their batched Newton views currently require a uniform body layo :end-at: scene_cfg.robot.spawn.usd_path = scene_cfg.robot.spawn.usd_path[0] :dedent: 8 -An :class:`~isaaclab.cloner.InclusionSet` defines the legal world layouts before replication. By default, its -active assets choose variants independently. Explicit :attr:`~isaaclab.cloner.InclusionSet.layouts` list only -legal pairings; each row selects local spawner variant indices in active scene declaration order, including -unclaimed assets and repeated instances. For a scene declaring ``part`` then ``fixture``: +An :class:`~isaaclab.cloner.InclusionSet` defines legal worlds before replication. Its default +:meth:`~isaaclab.cloner.InclusionSet.worlds` combines variants independently. A task can override that +method to select compatible configurations using their existing ``semantic_tags``. No separate variant +labels, positional layout indices, or matching policy are required in core. + +For example, tag each part and fixture spawner configuration with its size and assembly. A configuration +can have several semantic tags: .. code-block:: python - scene_cfg.clone_cfg.clone_combinations = [ - InclusionSet(assets=["part", "fixture"], layouts=[(0, 2), (1, 0)]), + small_part_cfg.semantic_tags = [ + ("class", "gear"), ("size", "small"), ("assembly", "drive"), + ] + small_fixture_cfg.semantic_tags = [ + ("class", "fixture"), ("size", "small"), ("assembly", "drive"), ] -For mathematical pairing rules, override :meth:`~isaaclab.cloner.InclusionSet.worlds`: +Define the matching rule in the task, alongside its scene configuration: .. code-block:: python + import re + class MatchedWorlds(InclusionSet): def worlds(self, asset_names, variants): - return zip(*variants, strict=True) + candidates = dict(zip(asset_names, variants, strict=True)) + fixtures = {} + for fixture in candidates["fixture"]: + tags = dict(fixture.semantic_tags or ()) + key = (tags.get("size"), tags.get("assembly")) + if None not in key: + fixtures.setdefault(key, []).append(fixture) + for part in candidates["part"]: + tags = dict(part.semantic_tags or ()) + if re.fullmatch(r"gear|shaft", tags.get("class", "")): + key = (tags.get("size"), tags.get("assembly")) + for fixture in fixtures.get(key, ()): + yield {"part": [part], "fixture": [fixture]} - scene_cfg.clone_cfg.clone_combinations = [MatchedWorlds(assets=["part", "fixture"])] + scene_cfg.clone_cfg.clone_combinations = [ + MatchedWorlds(assets=["part", "fixture"]), + ] -Each candidate range indexes one active asset instance's spawner. This definition pairs equal variant indices -instead of constructing their Cartesian product; the example requires equal candidate counts. More general -subclasses can express coupled choices directly. Their outputs are validated and translated into prototype IDs -by scene planning; ``ReplicateSession`` consumes those IDs without interpreting the definition. An inclusion -set's weight is split equally over its generated layouts. +This task-local definition joins parts and fixtures by size and assembly, filtering part classes with a +regex. It generates compatible pairs directly instead of constructing the independent Cartesian product. +Variant order does not determine compatibility. Other tasks can use different tag keys, multi-valued tags, +or configuration properties without adding matching subclasses to core. Untagged variants remain valid +for the default independent combination policy. + +The method receives one candidate group per active declaration instance, including unclaimed assets. +Candidate configurations include semantic tags inherited from ``MultiAssetSpawnerCfg``. For +``MultiUsdFileCfg``, each candidate has one concrete ``usd_path`` and the wrapper's tags. Treat these +configurations as read-only and return the supplied objects rather than copies. Each returned world maps +an asset name to a list of selected configurations. Lists allow repeated asset instances and rigid object +collection members; their selections follow the corresponding declaration order. The example above is +for a scene containing one part and one fixture declaration. A task with additional active assets must +include their selections in each returned world too. + +Scene planning validates the selections and translates them into prototype IDs. ``ReplicateSession`` +consumes those IDs without interpreting semantic tags or inclusion rules. An inclusion set's weight is +split equally over its generated worlds. For more detail on prototype assignment and replication, see :doc:`cloning`. diff --git a/docs/source/refs/contributing.rst b/docs/source/refs/contributing.rst index 490ceb8c3676..55b722061ed9 100644 --- a/docs/source/refs/contributing.rst +++ b/docs/source/refs/contributing.rst @@ -439,9 +439,11 @@ before changing an interface. Apply these rules when adding code or cleaning up required attribute; express optional fields explicitly in the interface. Use concrete defaults for known empty selections. Reserve ``None`` for a distinct policy or lifecycle state, such as choosing an environment's frame rate or waiting for a client to connect. -* Inclusion definitions own legal world layouts, including explicit rows and pairing formulas. Resolve them - during scene planning before entering ``ReplicateSession``. Keep inclusion interpretation and task-specific - combination policies out of replication execution; do not add variant-pinning exceptions there. +* Inclusion definitions own legal world selections. Task-local subclasses may inspect spawner configurations' + existing ``semantic_tags`` and select compatible configurations directly. Do not add positional variant-pin + fields, parallel variant-label metadata, or task-specific matching subclasses to core. Resolve selections + during scene planning before entering ``ReplicateSession``; keep inclusion interpretation out of replication + execution. * Give each piece of state and validation one owner. Consumers should use the owner's contract instead of repairing results or maintaining duplicate state. Cache derived values only when their lifetime and invalidation are clear; do not expose mutable cached results for callers to modify accidentally. diff --git a/source/isaaclab/changelog.d/inclusion-world-layouts.added.rst b/source/isaaclab/changelog.d/inclusion-world-layouts.added.rst index 73504ac68322..1acfeeb462bb 100644 --- a/source/isaaclab/changelog.d/inclusion-world-layouts.added.rst +++ b/source/isaaclab/changelog.d/inclusion-world-layouts.added.rst @@ -1,3 +1,4 @@ -* Added explicit :attr:`~isaaclab.cloner.InclusionSet.layouts` and an overridable - :meth:`~isaaclab.cloner.InclusionSet.worlds` definition for legal world pairings. Scene planning - resolves these definitions before replication, without enumerating excluded Cartesian combinations. +* Added an overridable :meth:`~isaaclab.cloner.InclusionSet.worlds` definition that lets task-local + inclusion rules select compatible spawner configurations using their existing semantic tags. + Scene planning resolved these selections into prototype IDs before replication, without enumerating + excluded Cartesian combinations or adding a separate variant-label system. diff --git a/source/isaaclab/isaaclab/cloner/cloner_cfg.py b/source/isaaclab/isaaclab/cloner/cloner_cfg.py index 20af748ffcaf..0af78756e84c 100644 --- a/source/isaaclab/isaaclab/cloner/cloner_cfg.py +++ b/source/isaaclab/isaaclab/cloner/cloner_cfg.py @@ -7,14 +7,18 @@ import itertools import warnings -from collections.abc import Callable, Iterable, Sequence +from collections.abc import Callable, Iterable, Mapping, Sequence from dataclasses import MISSING +from typing import TYPE_CHECKING import numpy as np from ..utils import configclass from .cloner_strategies import sequential +if TYPE_CHECKING: + from ..sim.spawners.spawner_cfg import SpawnerCfg + DEFAULT_ENV_TEMPLATE = "/World/envs/env_{}" """Default path template for a replicated env prim; ``{}`` marks the environment index.""" @@ -48,29 +52,32 @@ class InclusionSet: weight: float = 1.0 """Relative sampling weight for this clone combination.""" - layouts: Sequence[Sequence[int]] | None = None - """Explicit variant-index rows; None uses the independent product. - - Columns follow active scene declaration order; repeated instances and members of a rigid - object collection each have their own column. Unclaimed assets also contribute columns, - once per declaration. Indices are local to each declaration's spawner, starting at zero. - """ + def worlds( + self, asset_names: Sequence[str], variants: Sequence[Sequence[SpawnerCfg]] + ) -> Iterable[Mapping[str, Sequence[SpawnerCfg]]]: + """Select legal worlds from the available spawner configurations. - def worlds(self, asset_names: Sequence[str], variants: Sequence[range]) -> Iterable[Sequence[int]]: - """Generate legal layouts without constructing combinations that the definition excludes. - - Override this method to pair or otherwise couple asset choices. The default returns - :attr:`layouts` when supplied, otherwise the Cartesian product of the candidate ranges. - The inclusion set's weight is divided equally over the generated layouts. + Override this method in the task to select compatible variants using their existing + ``semantic_tags`` or other configuration properties. No matching policy is built into core. + The default independently combines all candidates. Args: - asset_names: Active scene declaration name of each column, including repeated instances. - variants: Candidate variant indices for each column, as ``range(variant_count)``. - - Returns: - Rows selecting one local variant index per column, in the supplied order. + asset_names: Scene name for each active declaration instance. Repeated instances and + rigid object collection members have separate entries, possibly with the same name. + variants: Candidate spawner configurations for each entry in ``asset_names``. These + include inherited multi-asset semantic tags and must be treated as read-only. + + Yields: + Asset names mapped to selected candidate configurations, one per active instance. + For repeated names, selections follow the corresponding declaration order. Return + the supplied configurations themselves; copies and foreign configurations are invalid. + The inclusion weight is divided equally over the generated worlds. """ - return itertools.product(*variants) if self.layouts is None else self.layouts + for choices in itertools.product(*variants): + world = {} + for name, choice in zip(asset_names, choices, strict=True): + world.setdefault(name, []).append(choice) + yield world @configclass @@ -92,7 +99,7 @@ class CloneCfg: empty list keeps the homogeneous/default behavior. Each inclusion set defines its legal world layouts through :meth:`InclusionSet.worlds`. - Explicit rows and custom inclusion subclasses are resolved before replication; replication + Task-local inclusion subclasses are resolved before replication; replication consumes the resulting world prototypes without interpreting inclusion rules. """ @@ -113,7 +120,7 @@ def __post_init__(self) -> None: def make_valid_clone_combinations( asset_names: Sequence[str], - variant_counts: Sequence[int], + variant_cfgs: Sequence[Sequence[SpawnerCfg]], clone_combinations: Sequence[InclusionSet] | None = None, *, all_asset_names: Sequence[str] | None = None, @@ -121,12 +128,12 @@ def make_valid_clone_combinations( """Resolve inclusion definitions into flat asset-prototype memberships and relative weights. Repeated names create repeated instances. Unclaimed assets join every world. Each inclusion - set owns the layouts it generates; explicit or coupled layouts never expand into an independent - Cartesian product. Columns follow replicated scene declaration order, including repeated instances. + set selects configurations directly, without enumerating excluded Cartesian combinations. + Candidate groups follow replicated scene declaration order, including repeated instances. Args: asset_names: Names of the replicated asset declarations. - variant_counts: Number of concrete prototypes for each declaration. + variant_cfgs: Concrete spawner configurations for each replicated declaration. clone_combinations: Legal world definitions; None uses the default independent product. all_asset_names: Scene names, including shared assets that do not enter world memberships. @@ -134,15 +141,15 @@ def make_valid_clone_combinations( World memberships indexing the flat variant library, and one relative weight per world. Raises: - ValueError: A declaration, asset name, layout width, or variant index is invalid, or a - definition produces no worlds. + ValueError: Candidate groups are empty or misaligned, selected assets or configurations + are invalid, or a definition produces no worlds. """ - if len(asset_names) != len(variant_counts) or any(count <= 0 for count in variant_counts): - raise ValueError("Each asset requires one positive variant count.") + if len(asset_names) != len(variant_cfgs) or any(not candidates for candidates in variant_cfgs): + raise ValueError("Each asset requires a nonempty group of variant configurations.") known = set(asset_names if all_asset_names is None else all_asset_names) combinations = clone_combinations or (InclusionSet(assets=list(dict.fromkeys(asset_names))),) claimed = set().union(*(combination.assets for combination in combinations)) - offsets = np.cumsum([0, *variant_counts]) + offsets = np.cumsum([0, *(len(candidates) for candidates in variant_cfgs)]) worlds, weights = [], [] for combination in combinations: if unknown := set(combination.assets) - known: @@ -151,20 +158,23 @@ def make_valid_clone_combinations( for index, name in enumerate(asset_names): count = combination.assets.count(name) if name in claimed else 1 names.extend([name] * count) - choices.extend([range(variant_counts[index])] * count) + choices.extend([variant_cfgs[index]] * count) starts.extend([offsets[index]] * count) - layouts = combination.worlds(names, choices) + candidate_ids = [{id(cfg): index for index, cfg in enumerate(candidates)} for candidates in choices] num_worlds = len(worlds) - for layout in layouts: - if len(layout) != len(choices): - raise ValueError(f"World layout requires {len(choices)} variant indices, got {len(layout)}.") - for variant, candidates in zip(layout, choices, strict=True): - is_index = isinstance(variant, (int, np.integer)) and not isinstance(variant, bool) - if not is_index or not 0 <= variant < len(candidates): - raise ValueError( - f"Invalid variant index {variant!r}: expected an integer in [0, {len(candidates)})." - ) - worlds.append(tuple(int(start + variant) for start, variant in zip(starts, layout, strict=True))) + for world in combination.worlds(names, choices): + if set(world) != set(names): + raise ValueError(f"World assets must be {sorted(set(names))}, got {sorted(world)}.") + if any(len(world[name]) != names.count(name) for name in world): + raise ValueError("World selections must provide one configuration per active asset instance.") + selections = {name: iter(configs) for name, configs in world.items()} + members = [] + for name, candidates, start in zip(names, candidate_ids, starts, strict=True): + selected = next(selections[name]) + if id(selected) not in candidates: + raise ValueError(f"Selected configuration for {name!r} is not one of its supplied variants.") + members.append(int(start + candidates[id(selected)])) + worlds.append(tuple(members)) count = len(worlds) - num_worlds if not count: raise ValueError("An inclusion set must define at least one world layout.") diff --git a/source/isaaclab/isaaclab/scene/interactive_scene.py b/source/isaaclab/isaaclab/scene/interactive_scene.py index e3581ee63a86..b3b010132b2c 100644 --- a/source/isaaclab/isaaclab/scene/interactive_scene.py +++ b/source/isaaclab/isaaclab/scene/interactive_scene.py @@ -219,9 +219,10 @@ def _collect_asset_cfgs(self) -> tuple[list[Any], tuple[tuple[int, ...], ...] | nested_material_names = {name for name, cfg in flat_items if id(cfg) in nested_visual_material_ids} scene_asset_names = [name for name in scene_asset_names if name not in nested_material_names] + combinations = self.cloner_cfg.clone_combinations cfgs: list[Any] = [] clone_asset_names: list[str] = [] - variant_counts: list[int] = [] + variant_cfgs: list[list[sim_utils.SpawnerCfg]] = [] prototype_indices: list[int] = [] prototype_count = 0 for asset_name, child in flat_items: @@ -233,16 +234,27 @@ def _collect_asset_cfgs(self) -> tuple[list[Any], tuple[tuple[int, ...], ...] | count = cloner.num_spawn_variants(getattr(child, "spawn", None)) is_per_env = cloner.path.match(child.prim_path, self._env_fmt) is not None is_spawned = isinstance(child, (AssetBaseCfg, CameraCfg)) and child.spawn is not None - if is_per_env and is_spawned: + if is_per_env and is_spawned and combinations: clone_asset_names.append(asset_name) - variant_counts.append(count) + spawn = child.spawn + if isinstance(spawn, sim_utils.MultiAssetSpawnerCfg): + candidates = [copy.copy(candidate) for candidate in spawn.assets_cfg] + if spawn.semantic_tags: + for candidate in candidates: + candidate.semantic_tags = [*(candidate.semantic_tags or ()), *spawn.semantic_tags] + elif isinstance(spawn, sim_utils.MultiUsdFileCfg) and not isinstance(spawn.usd_path, str): + candidates = [copy.copy(spawn) for _ in spawn.usd_path] + for candidate, usd_path in zip(candidates, spawn.usd_path, strict=True): + candidate.usd_path = usd_path + else: + candidates = [spawn] + variant_cfgs.append(candidates) prototype_indices.extend(range(prototype_count, prototype_count + count)) prototype_count += count - combinations = self.cloner_cfg.clone_combinations if combinations and clone_asset_names: worlds, weights = cloner.make_valid_clone_combinations( - clone_asset_names, variant_counts, combinations, all_asset_names=scene_asset_names + clone_asset_names, variant_cfgs, combinations, all_asset_names=scene_asset_names ) return cfgs, tuple(tuple(prototype_indices[index] for index in world) for world in worlds), weights return cfgs, None, None diff --git a/source/isaaclab/test/cloner/test_clone_plan_algebra.py b/source/isaaclab/test/cloner/test_clone_plan_algebra.py index 5bd9a67edd41..d22e633cd711 100644 --- a/source/isaaclab/test/cloner/test_clone_plan_algebra.py +++ b/source/isaaclab/test/cloner/test_clone_plan_algebra.py @@ -11,7 +11,7 @@ """ import ast -import itertools +import re import subprocess import sys from pathlib import Path @@ -24,6 +24,7 @@ from isaaclab.assets import AssetBaseCfg from isaaclab.cloner import InclusionSet, make_clone_plan, make_valid_clone_combinations from isaaclab.sim import CuboidCfg +from isaaclab.utils import configclass ## # Path primitives. @@ -106,7 +107,11 @@ def test_clone_ownership_and_import_boundaries(): assert result.returncode == 0, result.stderr assert result.stdout.strip() == "False", "generic clone topology and queries imported the USD backend" - assert "variants" not in InclusionSet.__dataclass_fields__, "InclusionSet owns layouts rather than variant pins" + assert not {"variants", "layouts"} & InclusionSet.__dataclass_fields__.keys(), ( + "Inclusion rules select semantic configurations rather than positional variant pins" + ) + + assert not hasattr(cloner, "MatchedWorlds"), "Matching policies belong in tasks" source = Path(__file__).resolve().parents[3] for file in source.glob("*/isaaclab*/**/*.py"): @@ -342,49 +347,104 @@ def test_batched_world_queries(device, worlds, num_worlds, shared, selectors): assert starts[-1, -1] == len(expected) -class _PairedWorlds(InclusionSet): +class _SemanticWorlds(InclusionSet): + def worlds(self, asset_names, variants): + groups = [] + for candidates in variants: + matches = {} + for candidate in candidates: + tags = dict(candidate.semantic_tags) + if re.fullmatch("gear|fixture", tags["class"]): + matches[tags["size"], tags["assembly"]] = candidate + groups.append(matches) + for key in groups[0]: + if all(key in group for group in groups): + world = {} + for name, group in zip(asset_names, groups, strict=True): + world.setdefault(name, []).append(group[key]) + yield world + + +@configclass +class _ExplicitWorlds(InclusionSet): + selections: list = [] + def worlds(self, asset_names, variants): - return itertools.islice(zip(*variants), 3) + return self.selections -def test_inclusion_layouts_generate_legal_worlds_before_replication(): - """Explicit and paired definitions avoid an astronomical product; default products still work.""" +def test_inclusion_semantics_generate_legal_worlds_before_replication(): + """Task-local semantic matching selects three worlds from 64**8 possible combinations.""" names = [f"object_{index}" for index in range(8)] - worlds, weights = make_valid_clone_combinations(names, [1_000_000] * 8, [_PairedWorlds(assets=names)]) + variants = [] + for group in range(8): + candidates = [ + CuboidCfg( + size=(1.0, 1.0, 1.0), + semantic_tags=[ + ("size", str(index)), + ("assembly", "drive"), + ("class", "gear" if index < 3 else "decoy"), + ], + ) + for index in range(64) + ] + variants.append(candidates[::-1] if group % 2 else candidates) + worlds, weights = make_valid_clone_combinations(names, variants, [_SemanticWorlds(assets=names)]) assert worlds == ( - (0, 1000000, 2000000, 3000000, 4000000, 5000000, 6000000, 7000000), - (1, 1000001, 2000001, 3000001, 4000001, 5000001, 6000001, 7000001), - (2, 1000002, 2000002, 3000002, 4000002, 5000002, 6000002, 7000002), + (0, 127, 128, 255, 256, 383, 384, 511), + (1, 126, 129, 254, 257, 382, 385, 510), + (2, 125, 130, 253, 258, 381, 386, 509), ) np.testing.assert_array_equal(weights, [1 / 3] * 3) # Repeated declarations, unclaimed assets, and weights retain their membership semantics. + robot, parts, tools, lamps = [[CuboidCfg(size=(1.0, 1.0, 1.0)) for _ in range(n)] for n in (1, 3, 2, 2)] selections = [ - InclusionSet(assets=["part", "tool"], layouts=[(0, 2, 0, 0)], weight=3.0), - InclusionSet(assets=["part", "part", "tool"], layouts=[(0, 1, 1, 0, 1), (0, 1, 1, 1, 1)]), + _ExplicitWorlds(assets=["part", "tool"], weight=3.0), + _ExplicitWorlds(assets=["part", "part", "tool"]), + ] + selections[0].selections = [ + {"robot": robot, "part": [parts[2]], "tool": [tools[0]], "lamp": [lamps[0]]}, ] - worlds, weights = make_valid_clone_combinations(["robot", "part", "tool", "lamp"], [1, 3, 2, 2], selections) + selections[1].selections = [ + {"robot": robot, "part": [parts[1], parts[1]], "tool": [tools[0]], "lamp": [lamps[1]]}, + {"robot": robot, "part": [parts[1], parts[1]], "tool": [tools[1]], "lamp": [lamps[1]]}, + ] + worlds, weights = make_valid_clone_combinations( + ["robot", "part", "tool", "lamp"], [robot, parts, tools, lamps], selections + ) assert worlds == ((0, 3, 4, 6), (0, 2, 2, 4, 7), (0, 2, 2, 5, 7)) np.testing.assert_array_equal(weights, [3.0, 0.5, 0.5]) - worlds, weights = make_valid_clone_combinations(["part", "tool"], [2, 3]) + # Collection members share a scene name but each retains its own candidates. + worlds, weights = make_valid_clone_combinations(["collection", "collection"], [parts[:2], tools]) + assert worlds == ((0, 2), (0, 3), (1, 2), (1, 3)) + np.testing.assert_array_equal(weights, [0.25] * 4) + worlds, weights = make_valid_clone_combinations(["part", "tool"], [parts[:2], tools + lamps[:1]]) assert worlds == ((0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4)) np.testing.assert_array_equal(weights, [1 / 6] * 6) -@pytest.mark.parametrize( - "layouts, message", - [ - ([(0,)], "requires 2 variant indices"), - ([(0, 2)], "Invalid variant index 2"), - ([(0, -1)], "Invalid variant index -1"), - ([(True, 0)], "Invalid variant index True"), - ([(None, 0)], "Invalid variant index None"), - ([], "at least one world"), - ], -) -def test_inclusion_layouts_reject_invalid_definitions(layouts, message): +@pytest.mark.parametrize("invalid", ["missing", "extra", "count", "foreign", "copied", "empty"]) +def test_inclusion_worlds_reject_invalid_definitions(invalid): + part, tool = CuboidCfg(size=(1.0, 1.0, 1.0)), CuboidCfg(size=(2.0, 2.0, 2.0)) + selections = [{"part": [part], "tool": [tool]}] + message = "World assets must be" + if invalid == "missing": + del selections[0]["tool"] + elif invalid == "extra": + selections[0]["unknown"] = [part] + elif invalid == "count": + selections[0]["part"] = [part, part] + message = "one configuration per active asset instance" + elif invalid in ("foreign", "copied"): + selections[0]["part"] = [tool if invalid == "foreign" else part.copy()] + message = "not one of its supplied variants" + else: + selections = [] + message = "at least one world" + inclusion = _ExplicitWorlds(assets=["part", "tool"]) + inclusion.selections = selections with pytest.raises(ValueError, match=message): - make_valid_clone_combinations( - ["part", "tool"], [2, 2], [InclusionSet(assets=["part", "tool"], layouts=layouts)] - ) + make_valid_clone_combinations(["part", "tool"], [[part], [tool]], [inclusion]) diff --git a/source/isaaclab_newton/test/assets/test_rigid_object_mesh_variants.py b/source/isaaclab_newton/test/assets/test_rigid_object_mesh_variants.py index 3adc4436385c..1fae5b59d76e 100644 --- a/source/isaaclab_newton/test/assets/test_rigid_object_mesh_variants.py +++ b/source/isaaclab_newton/test/assets/test_rigid_object_mesh_variants.py @@ -151,8 +151,21 @@ def test_native_selection_preserves_initial_worlds_and_unused_variant(device: st @pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) -def test_explicit_world_layouts_choose_initial_variants(device: str) -> None: - """Each world starts with its explicitly selected variants, for reset-time and static spawners.""" +def test_semantic_worlds_choose_initial_variants(device: str) -> None: + """Semantic rules select the right native variants, including inherited wrapper tags.""" + + @configclass + class AssemblyWorlds(InclusionSet): + assembly: str = "" + + def worlds(self, asset_names, variants): + candidates = dict(zip(asset_names, variants, strict=True)) + for obj in candidates["object"]: + for fixture in candidates["fixture"]: + required = {("assembly", self.assembly), ("domain", "mechanical")} + if required.issubset(obj.semantic_tags) and required.issubset(fixture.semantic_tags): + yield {"object": [obj], "fixture": [fixture]} + scene_cfg = _VariantSceneCfg(num_envs=4, env_spacing=2.0) third = scene_cfg.object.spawn.assets_cfg[0].copy() third.radius, third.mass_props.mass = 0.06, 27.0 @@ -161,10 +174,15 @@ def test_explicit_world_layouts_choose_initial_variants(device: str) -> None: scene_cfg.fixture.prim_path = "{ENV_REGEX_NS}/Fixture" scene_cfg.fixture.spawn.static = True scene_cfg.fixture.init_state.pos = (0.5, 0.0, 0.2) - # The second definition explicitly pairs the first object with both fixture variants. + for obj, tags in zip(scene_cfg.object.spawn.assets_cfg, ([("assembly", "spare")], [], [("assembly", "drive")])): + obj.semantic_tags = tags + scene_cfg.fixture.spawn.assets_cfg[0].semantic_tags = [("assembly", "spare")] + scene_cfg.fixture.spawn.assets_cfg[1].semantic_tags = [("assembly", "spare"), ("assembly", "drive")] + scene_cfg.object.spawn.semantic_tags = [("domain", "mechanical")] + scene_cfg.fixture.spawn.semantic_tags = [("domain", "mechanical")] scene_cfg.clone_cfg.clone_combinations = [ - InclusionSet(assets=["object", "fixture"], layouts=[(2, 1)]), - InclusionSet(assets=["object", "fixture"], layouts=[(0, 0), (0, 1)]), + AssemblyWorlds(assets=["object", "fixture"], assembly="drive"), + AssemblyWorlds(assets=["object", "fixture"], assembly="spare"), ] sim_cfg = SimulationCfg( device=device, From ec2d14e81c0c8dd2cc6816edf1a2c5e45fdfceda Mon Sep 17 00:00:00 2001 From: Octi Zhang Date: Mon, 23 Nov 2026 15:50:12 -0800 Subject: [PATCH 7/8] Declare semantic inclusion matches and select compact world groups --- docs/source/how-to/multi_asset_spawning.rst | 96 ++++----- docs/source/refs/contributing.rst | 11 +- .../inclusion-world-layouts.added.rst | 8 +- source/isaaclab/isaaclab/cloner/clone_plan.py | 46 +++- source/isaaclab/isaaclab/cloner/cloner_cfg.py | 119 +++++----- .../isaaclab/cloner/replicate_session.py | 4 +- .../isaaclab/scene/interactive_scene.py | 13 +- .../test/cloner/test_clone_plan_algebra.py | 204 +++++++++--------- .../assets/test_rigid_object_mesh_variants.py | 21 +- 9 files changed, 277 insertions(+), 245 deletions(-) diff --git a/docs/source/how-to/multi_asset_spawning.rst b/docs/source/how-to/multi_asset_spawning.rst index d6434219e78c..c9d24ad94716 100644 --- a/docs/source/how-to/multi_asset_spawning.rst +++ b/docs/source/how-to/multi_asset_spawning.rst @@ -131,67 +131,61 @@ variant because their batched Newton views currently require a uniform body layo :end-at: scene_cfg.robot.spawn.usd_path = scene_cfg.robot.spawn.usd_path[0] :dedent: 8 -An :class:`~isaaclab.cloner.InclusionSet` defines legal worlds before replication. Its default -:meth:`~isaaclab.cloner.InclusionSet.worlds` combines variants independently. A task can override that -method to select compatible configurations using their existing ``semantic_tags``. No separate variant -labels, positional layout indices, or matching policy are required in core. - -For example, tag each part and fixture spawner configuration with its size and assembly. A configuration -can have several semantic tags: +An :class:`~isaaclab.cloner.InclusionSet` declares which assets are active and which semantic tag +values must match. No subclass or callback is needed. For a scene with ``gear`` and ``fixture`` assets: .. code-block:: python - small_part_cfg.semantic_tags = [ - ("class", "gear"), ("size", "small"), ("assembly", "drive"), - ] - small_fixture_cfg.semantic_tags = [ - ("class", "fixture"), ("size", "small"), ("assembly", "drive"), + scene_cfg.clone_cfg.clone_combinations = [ + InclusionSet(assets=["gear", "fixture"], match_tags=["size", "assembly"]), ] -Define the matching rule in the task, alongside its scene configuration: +Tag the individual spawner configurations using the existing semantic API: .. code-block:: python - import re - - class MatchedWorlds(InclusionSet): - def worlds(self, asset_names, variants): - candidates = dict(zip(asset_names, variants, strict=True)) - fixtures = {} - for fixture in candidates["fixture"]: - tags = dict(fixture.semantic_tags or ()) - key = (tags.get("size"), tags.get("assembly")) - if None not in key: - fixtures.setdefault(key, []).append(fixture) - for part in candidates["part"]: - tags = dict(part.semantic_tags or ()) - if re.fullmatch(r"gear|shaft", tags.get("class", "")): - key = (tags.get("size"), tags.get("assembly")) - for fixture in fixtures.get(key, ()): - yield {"part": [part], "fixture": [fixture]} - - scene_cfg.clone_cfg.clone_combinations = [ - MatchedWorlds(assets=["part", "fixture"]), + small_gear_cfg.semantic_tags = [("size", "small"), ("assembly", "drive")] + small_fixture_cfg.semantic_tags = [("size", "small"), ("assembly", "drive")] + universal_fixture_cfg.semantic_tags = [ + ("size", "small"), ("size", "medium"), ("size", "large"), + ("assembly", "drive"), ] -This task-local definition joins parts and fixtures by size and assembly, filtering part classes with a -regex. It generates compatible pairs directly instead of constructing the independent Cartesian product. -Variant order does not determine compatibility. Other tasks can use different tag keys, multi-valued tags, -or configuration properties without adding matching subclasses to core. Untagged variants remain valid -for the default independent combination policy. - -The method receives one candidate group per active declaration instance, including unclaimed assets. -Candidate configurations include semantic tags inherited from ``MultiAssetSpawnerCfg``. For -``MultiUsdFileCfg``, each candidate has one concrete ``usd_path`` and the wrapper's tags. Treat these -configurations as read-only and return the supplied objects rather than copies. Each returned world maps -an asset name to a list of selected configurations. Lists allow repeated asset instances and rigid object -collection members; their selections follow the corresponding declaration order. The example above is -for a scene containing one part and one fixture declaration. A task with additional active assets must -include their selections in each returned world too. - -Scene planning validates the selections and translates them into prototype IDs. ``ReplicateSession`` -consumes those IDs without interpreting semantic tags or inclusion rules. An inclusion set's weight is -split equally over its generated worlds. +Every selected gear and fixture must share a value for each requested tag type. The universal fixture +can therefore match small, medium, or large gears in the drive assembly. Missing requested tags do not +match. Tag values are compared exactly; there are no reserved wildcard values or implicit regex rules. +Tags inherited from ``MultiAssetSpawnerCfg`` also participate. ``MultiUsdFileCfg`` candidates inherit +the wrapper's tags and retain their individual USD paths. + +Repeat an asset name to request multiple instances: + +.. code-block:: python + + InclusionSet(assets=["gear", "gear", "fixture"], match_tags=["size", "assembly"]) + +This requests two gear instances and one fixture, all sharing a size and assembly. It does not express +separate pairwise constraints. Repeated instances may use the same variant. Assets not referenced by +any inclusion definition remain active independently and do not participate in tag matching. Collection +members retain their separate candidate slots even when they share a scene asset name. + +Matching definitions remain compact until clone-plan construction. For example, 1,000 candidates across +five categories and eight asset slots can be represented as five compatible groups, rather than +expanding every valid concrete world. The scene's ``num_envs`` determines how many worlds to instantiate. +Its :attr:`~isaaclab.cloner.CloneCfg.clone_strategy` selects compatible groups according to their weights, +then selects each slot's concrete variant within the chosen group. Identical concrete worlds share a +prototype. The inclusion weight is divided equally across its compatible groups; this gives equal +weight to tag-value groups, rather than to every possible concrete combination. Multi-valued tags can +make groups overlap. + +The existing ``sequential`` strategy distributes environments across groups and candidate lists in order. +The ``random`` strategy draws groups by weight and candidates uniformly, using the existing NumPy random +state. ``InclusionSet`` does not own an environment count or random seed. Planning cost depends on +candidate metadata and selected worlds, without expanding the product within each matching group; +loading and simulating concrete assets still has its own cost. + +With ``match_tags=[]`` (the default), the existing independent Cartesian product and assignment behavior +are preserved. Inclusion interpretation stays in scene planning. ``ReplicateSession`` forwards the +resolved definitions without applying tag matching or task-specific rules. For more detail on prototype assignment and replication, see :doc:`cloning`. diff --git a/docs/source/refs/contributing.rst b/docs/source/refs/contributing.rst index 55b722061ed9..44aafd85070a 100644 --- a/docs/source/refs/contributing.rst +++ b/docs/source/refs/contributing.rst @@ -439,11 +439,12 @@ before changing an interface. Apply these rules when adding code or cleaning up required attribute; express optional fields explicitly in the interface. Use concrete defaults for known empty selections. Reserve ``None`` for a distinct policy or lifecycle state, such as choosing an environment's frame rate or waiting for a client to connect. -* Inclusion definitions own legal world selections. Task-local subclasses may inspect spawner configurations' - existing ``semantic_tags`` and select compatible configurations directly. Do not add positional variant-pin - fields, parallel variant-label metadata, or task-specific matching subclasses to core. Resolve selections - during scene planning before entering ``ReplicateSession``; keep inclusion interpretation out of replication - execution. +* Inclusion definitions declare membership and shared semantic tag types through ``match_tags``. + Reuse existing spawner ``semantic_tags`` rather than adding variant labels, positional pins, or + user-overridable matching callbacks. Inclusion sets do not own environment counts or random seeds. + Resolve compatibility into factorized candidate groups during scene planning; let clone-plan construction + and the scene's clone strategy select concrete worlds without expanding every valid combination. + Keep inclusion interpretation and task-specific matching classes out of replication execution. * Give each piece of state and validation one owner. Consumers should use the owner's contract instead of repairing results or maintaining duplicate state. Cache derived values only when their lifetime and invalidation are clear; do not expose mutable cached results for callers to modify accidentally. diff --git a/source/isaaclab/changelog.d/inclusion-world-layouts.added.rst b/source/isaaclab/changelog.d/inclusion-world-layouts.added.rst index 1acfeeb462bb..b4cdd620e8ea 100644 --- a/source/isaaclab/changelog.d/inclusion-world-layouts.added.rst +++ b/source/isaaclab/changelog.d/inclusion-world-layouts.added.rst @@ -1,4 +1,4 @@ -* Added an overridable :meth:`~isaaclab.cloner.InclusionSet.worlds` definition that lets task-local - inclusion rules select compatible spawner configurations using their existing semantic tags. - Scene planning resolved these selections into prototype IDs before replication, without enumerating - excluded Cartesian combinations or adding a separate variant-label system. +* Added :attr:`~isaaclab.cloner.InclusionSet.match_tags` to declare variant compatibility using + existing semantic tags, including multiple acceptable values. Matching groups stayed factorized + until the scene's clone strategy selected concrete worlds, avoiding exhaustive combination + expansion without inclusion callbacks, separate variant labels, or inclusion-owned sampling settings. diff --git a/source/isaaclab/isaaclab/cloner/clone_plan.py b/source/isaaclab/isaaclab/cloner/clone_plan.py index 0a5d33aae9d7..7e1c8a74aa10 100644 --- a/source/isaaclab/isaaclab/cloner/clone_plan.py +++ b/source/isaaclab/isaaclab/cloner/clone_plan.py @@ -86,7 +86,7 @@ def to_warp(topology: PrototypeWorldTopology, device: str) -> PrototypeWorldTopo def make_clone_plan( asset_cfgs: Sequence[Any], - world_prototypes: Sequence[Sequence[int]], + world_prototypes: Sequence[Sequence[int | Sequence[int]]], num_worlds: int, *, weights: Sequence[float] | None = None, @@ -100,10 +100,15 @@ def make_clone_plan( Args: asset_cfgs: Asset prototype definitions, retained by reference. world_prototypes: Asset indices in each world prototype, including repeated instances. + A slot may instead contain candidate indices. Such factorized groups are selected + before their individual slots, without enumerating the Cartesian product. Only selected + concrete worlds are materialized and identical selections reuse one prototype. num_worlds: Number of destination worlds. weights: Relative world-prototype weights; ``None`` gives every prototype equal weight. shared_assets: Asset indices instantiated once in the shared world ``-1``. - clone_strategy: Function selecting world-prototype indices from weights. + clone_strategy: Function selecting world-prototype indices from weights. For factorized + groups, also selects each slot's concrete candidates with uniform candidate weights. + The same strategy owns both decisions and any randomness they require. env_template: Destination-world path template with one ``{}`` slot for the world ID. positions: Destination-world origins [m], shape [num_worlds, 3]; None preserves authored placement. @@ -114,11 +119,6 @@ def make_clone_plan( compositions = (shared_assets, *world_prototypes) if len(compositions) == 1: raise ValueError("At least one world prototype is required; an empty world is ().") - members = np.asarray([asset for world in compositions for asset in world]) - if members.size and ( - not np.issubdtype(members.dtype, np.integer) or (members < 0).any() or (members >= len(asset_cfgs)).any() - ): - raise ValueError("World members must be integer indices into asset_cfgs.") weights = np.ones(len(compositions) - 1) if weights is None else np.asarray(weights, dtype=np.float64) if weights.shape != (len(compositions) - 1,) or not np.isfinite(weights).all() or (weights < 0).any(): raise ValueError("Each world prototype requires one finite, non-negative weight.") @@ -129,6 +129,38 @@ def make_clone_plan( has_valid_ids = is_world_layout and (layout >= 0).all() and (layout < len(weights)).all() if not has_valid_ids: raise ValueError("clone_strategy must select one valid world-prototype index per destination.") + if any(not isinstance(slot, (int, np.integer)) for world in compositions[1:] for slot in world): + groups = [] + for world in compositions[1:]: + group = [] + for slot in world: + choices = np.asarray([slot] if isinstance(slot, (int, np.integer)) else slot) + is_index_list = choices.ndim == 1 and choices.size and np.issubdtype(choices.dtype, np.integer) + if not is_index_list or (choices < 0).any() or (choices >= len(asset_cfgs)).any(): + raise ValueError("World choices must be nonempty integer indices into asset_cfgs.") + group.append(choices) + groups.append(group) + selected = [None] * num_worlds + for group_id in np.unique(layout): + env_ids = np.flatnonzero(layout == group_id) + columns = [] + for choices in groups[group_id]: + ids = np.asarray(clone_strategy(np.ones(len(choices)), len(env_ids))) + is_candidate_layout = ids.shape == (len(env_ids),) and np.issubdtype(ids.dtype, np.integer) + if not is_candidate_layout or (ids < 0).any() or (ids >= len(choices)).any(): + raise ValueError("clone_strategy must select one valid candidate index per destination.") + columns.append(choices[ids]) + rows = zip(*columns, strict=True) if columns else [()] * len(env_ids) + for env_id, row in zip(env_ids, rows, strict=True): + selected[env_id] = tuple(int(member) for member in row) + prototype_ids = {world: index for index, world in enumerate(dict.fromkeys(selected))} + layout = np.asarray([prototype_ids[world] for world in selected], dtype=np.int32) + compositions = (shared_assets, *prototype_ids) + members = np.asarray([asset for world in compositions for asset in world]) + if members.size and ( + not np.issubdtype(members.dtype, np.integer) or (members < 0).any() or (members >= len(asset_cfgs)).any() + ): + raise ValueError("World members must be integer indices into asset_cfgs.") topology = PrototypeWorldTopology( num_asset_prototypes=len(asset_cfgs), world_prototypes=np.ascontiguousarray(members, dtype=np.int32), diff --git a/source/isaaclab/isaaclab/cloner/cloner_cfg.py b/source/isaaclab/isaaclab/cloner/cloner_cfg.py index 0af78756e84c..01a558ab0692 100644 --- a/source/isaaclab/isaaclab/cloner/cloner_cfg.py +++ b/source/isaaclab/isaaclab/cloner/cloner_cfg.py @@ -7,7 +7,7 @@ import itertools import warnings -from collections.abc import Callable, Iterable, Mapping, Sequence +from collections.abc import Callable, Sequence from dataclasses import MISSING from typing import TYPE_CHECKING @@ -52,32 +52,15 @@ class InclusionSet: weight: float = 1.0 """Relative sampling weight for this clone combination.""" - def worlds( - self, asset_names: Sequence[str], variants: Sequence[Sequence[SpawnerCfg]] - ) -> Iterable[Mapping[str, Sequence[SpawnerCfg]]]: - """Select legal worlds from the available spawner configurations. - - Override this method in the task to select compatible variants using their existing - ``semantic_tags`` or other configuration properties. No matching policy is built into core. - The default independently combines all candidates. - - Args: - asset_names: Scene name for each active declaration instance. Repeated instances and - rigid object collection members have separate entries, possibly with the same name. - variants: Candidate spawner configurations for each entry in ``asset_names``. These - include inherited multi-asset semantic tags and must be treated as read-only. - - Yields: - Asset names mapped to selected candidate configurations, one per active instance. - For repeated names, selections follow the corresponding declaration order. Return - the supplied configurations themselves; copies and foreign configurations are invalid. - The inclusion weight is divided equally over the generated worlds. - """ - for choices in itertools.product(*variants): - world = {} - for name, choice in zip(asset_names, choices, strict=True): - world.setdefault(name, []).append(choice) - yield world + match_tags: list[str] = [] + """Semantic tag types whose values must overlap across the selected assets. + + Each selected variant must share a value for every listed tag type. Multiple values for a + tag express alternatives: a fixture supporting several sizes can match any one of them. + Assets not claimed by any inclusion set remain independent and do not participate in matching. + Empty keeps the existing independent Cartesian product. Matching groups remain factorized + until the scene's clone strategy selects concrete variants for its environments. + """ @configclass @@ -98,9 +81,9 @@ class CloneCfg: Assets not referenced by any entry are active in every combination. An empty list keeps the homogeneous/default behavior. - Each inclusion set defines its legal world layouts through :meth:`InclusionSet.worlds`. - Task-local inclusion subclasses are resolved before replication; replication - consumes the resulting world prototypes without interpreting inclusion rules. + Inclusion sets declare semantic compatibility through :attr:`InclusionSet.match_tags`. + Planning resolves compatible groups before replication. The clone strategy selects groups + and concrete variants; inclusion definitions do not own environment counts or random seeds. """ clone_template: str = DEFAULT_ENV_TEMPLATE @@ -124,25 +107,28 @@ def make_valid_clone_combinations( clone_combinations: Sequence[InclusionSet] | None = None, *, all_asset_names: Sequence[str] | None = None, -) -> tuple[tuple[tuple[int, ...], ...], np.ndarray]: - """Resolve inclusion definitions into flat asset-prototype memberships and relative weights. +) -> tuple[tuple[tuple[int | tuple[int, ...], ...], ...], np.ndarray]: + """Resolve inclusion membership and semantic compatibility before replication. - Repeated names create repeated instances. Unclaimed assets join every world. Each inclusion - set selects configurations directly, without enumerating excluded Cartesian combinations. - Candidate groups follow replicated scene declaration order, including repeated instances. + Repeated names create repeated instances. Unclaimed assets join every world independently. + Without matching tags, preserve the existing exhaustive product. With matching tags, return + compact compatible groups: each slot lists its candidate prototype IDs, without expanding + the Cartesian product within a group. Concrete selection belongs to clone-plan construction. Args: asset_names: Names of the replicated asset declarations. - variant_cfgs: Concrete spawner configurations for each replicated declaration. + variant_cfgs: Concrete spawner configurations for each replicated declaration, including + semantic tags inherited from their multi-asset wrapper. clone_combinations: Legal world definitions; None uses the default independent product. all_asset_names: Scene names, including shared assets that do not enter world memberships. Returns: - World memberships indexing the flat variant library, and one relative weight per world. + World definitions and their relative weights. A definition contains concrete prototype IDs + or tuples of alternative IDs per slot. Inclusion weight is split equally across definitions. Raises: - ValueError: Candidate groups are empty or misaligned, selected assets or configurations - are invalid, or a definition produces no worlds. + ValueError: Candidate groups are empty or misaligned, asset names are unknown, or no + compatible world exists. """ if len(asset_names) != len(variant_cfgs) or any(not candidates for candidates in variant_cfgs): raise ValueError("Each asset requires a nonempty group of variant configurations.") @@ -154,30 +140,45 @@ def make_valid_clone_combinations( for combination in combinations: if unknown := set(combination.assets) - known: raise ValueError(f"Unknown assets in clone combination: {sorted(unknown)}.") - names, choices, starts = [], [], [] + names, choices, candidates = [], [], [] for index, name in enumerate(asset_names): count = combination.assets.count(name) if name in claimed else 1 names.extend([name] * count) - choices.extend([variant_cfgs[index]] * count) - starts.extend([offsets[index]] * count) - candidate_ids = [{id(cfg): index for index, cfg in enumerate(candidates)} for candidates in choices] - num_worlds = len(worlds) - for world in combination.worlds(names, choices): - if set(world) != set(names): - raise ValueError(f"World assets must be {sorted(set(names))}, got {sorted(world)}.") - if any(len(world[name]) != names.count(name) for name in world): - raise ValueError("World selections must provide one configuration per active asset instance.") - selections = {name: iter(configs) for name, configs in world.items()} - members = [] - for name, candidates, start in zip(names, candidate_ids, starts, strict=True): - selected = next(selections[name]) - if id(selected) not in candidates: - raise ValueError(f"Selected configuration for {name!r} is not one of its supplied variants.") - members.append(int(start + candidates[id(selected)])) - worlds.append(tuple(members)) - count = len(worlds) - num_worlds + choices.extend([tuple(range(int(offsets[index]), int(offsets[index + 1])))] * count) + candidates.extend([variant_cfgs[index]] * count) + start = len(worlds) + if not combination.match_tags: + worlds.extend(itertools.product(*choices)) + else: + buckets = [] + common = None + for name, ids, configs in zip(names, choices, candidates, strict=True): + if name not in combination.assets: + buckets.append(None) + continue + groups = {} + for prototype, cfg in zip(ids, configs, strict=True): + tags = cfg.semantic_tags or () + values = [ + tuple(dict.fromkeys(value for tag, value in tags if tag == key)) + for key in combination.match_tags + ] + for key in itertools.product(*values): + groups.setdefault(key, []).append(prototype) + buckets.append(groups) + common = list(groups) if common is None else [key for key in common if key in groups] + for key in [()] if common is None else common: + worlds.append( + tuple( + tuple(group[key]) if group is not None else ids + for group, ids in zip(buckets, choices, strict=True) + ) + ) + # Identical groups can arise when all candidates carry several matching values. + worlds[start:] = dict.fromkeys(worlds[start:]) + count = len(worlds) - start if not count: - raise ValueError("An inclusion set must define at least one world layout.") + raise ValueError("An inclusion set must define at least one compatible world.") weights.extend([combination.weight / count] * count) return tuple(worlds), np.asarray(weights, dtype=np.float64) diff --git a/source/isaaclab/isaaclab/cloner/replicate_session.py b/source/isaaclab/isaaclab/cloner/replicate_session.py index 811e558134f6..974fd30d5e2e 100644 --- a/source/isaaclab/isaaclab/cloner/replicate_session.py +++ b/source/isaaclab/isaaclab/cloner/replicate_session.py @@ -144,7 +144,7 @@ def __init__( env_spacing: float, *, clone_strategy: Callable[[np.ndarray, int], np.ndarray] = sequential, - world_prototypes: Sequence[Sequence[int]] | None = None, + world_prototypes: Sequence[Sequence[int | Sequence[int]]] | None = None, weights: Sequence[float] | None = None, replicate_physics: bool | None = None, env_template: str = DEFAULT_ENV_TEMPLATE, @@ -174,7 +174,7 @@ def _prepare_cloning( env_spacing: float, *, clone_strategy: Callable[[np.ndarray, int], np.ndarray] = sequential, - world_prototypes: Sequence[Sequence[int]] | None = None, + world_prototypes: Sequence[Sequence[int | Sequence[int]]] | None = None, weights: Sequence[float] | None = None, env_template: str = DEFAULT_ENV_TEMPLATE, positions: np.ndarray | None = None, diff --git a/source/isaaclab/isaaclab/scene/interactive_scene.py b/source/isaaclab/isaaclab/scene/interactive_scene.py index b3b010132b2c..814886ff6cd5 100644 --- a/source/isaaclab/isaaclab/scene/interactive_scene.py +++ b/source/isaaclab/isaaclab/scene/interactive_scene.py @@ -183,7 +183,9 @@ def _read_usd_export_base(self): logger.warning(f"USD export is unavailable: reading the engine at startup failed ({error}).") self._usd_export_base = error - def _collect_asset_cfgs(self) -> tuple[list[Any], tuple[tuple[int, ...], ...] | None, np.ndarray | None]: + def _collect_asset_cfgs( + self, + ) -> tuple[list[Any], tuple[tuple[int | tuple[int, ...], ...], ...] | None, np.ndarray | None]: """Flatten user-declared cfgs and declare shared prim roots for clone planning. Expands :class:`~isaaclab.assets.RigidObjectCollectionCfg` into its members, @@ -256,7 +258,14 @@ def _collect_asset_cfgs(self) -> tuple[list[Any], tuple[tuple[int, ...], ...] | worlds, weights = cloner.make_valid_clone_combinations( clone_asset_names, variant_cfgs, combinations, all_asset_names=scene_asset_names ) - return cfgs, tuple(tuple(prototype_indices[index] for index in world) for world in worlds), weights + worlds = tuple( + tuple( + prototype_indices[slot] if isinstance(slot, int) else tuple(prototype_indices[i] for i in slot) + for slot in world + ) + for world in worlds + ) + return cfgs, worlds, weights return cfgs, None, None def filter_collisions(self, global_prim_paths: list[str] | None = None): diff --git a/source/isaaclab/test/cloner/test_clone_plan_algebra.py b/source/isaaclab/test/cloner/test_clone_plan_algebra.py index d22e633cd711..7b376460d592 100644 --- a/source/isaaclab/test/cloner/test_clone_plan_algebra.py +++ b/source/isaaclab/test/cloner/test_clone_plan_algebra.py @@ -11,7 +11,6 @@ """ import ast -import re import subprocess import sys from pathlib import Path @@ -24,7 +23,6 @@ from isaaclab.assets import AssetBaseCfg from isaaclab.cloner import InclusionSet, make_clone_plan, make_valid_clone_combinations from isaaclab.sim import CuboidCfg -from isaaclab.utils import configclass ## # Path primitives. @@ -107,11 +105,12 @@ def test_clone_ownership_and_import_boundaries(): assert result.returncode == 0, result.stderr assert result.stdout.strip() == "False", "generic clone topology and queries imported the USD backend" - assert not {"variants", "layouts"} & InclusionSet.__dataclass_fields__.keys(), ( + assert not {"variants", "layouts", "num_worlds", "seed"} & InclusionSet.__dataclass_fields__.keys(), ( "Inclusion rules select semantic configurations rather than positional variant pins" ) - assert not hasattr(cloner, "MatchedWorlds"), "Matching policies belong in tasks" + assert not hasattr(cloner, "MatchedWorlds"), "InclusionSet owns declarative semantic matching" + assert not hasattr(InclusionSet, "worlds"), "Users configure semantic matching without overriding methods" source = Path(__file__).resolve().parents[3] for file in source.glob("*/isaaclab*/**/*.py"): @@ -236,9 +235,20 @@ def test_world_topology_weights_empty_worlds_and_invalid_membership(): result = cloner.query.get_asset_prototype_world_index(topology, selector) for actual, expected in zip(result, (indices, starts), strict=True): np.testing.assert_array_equal(actual, expected) - for members in ((2,), (-1,), (0.5,), ("0",)): + # Factorized and concrete definitions can share one plan; identical sampled worlds reuse a prototype. + grouped = make_clone_plan(assets, (((0, 1),), (0,)), 4, shared_assets=(1,)) + np.testing.assert_array_equal(grouped.topology.world_prototype_layout, [0, 1, 0, 0]) + np.testing.assert_array_equal(grouped.topology.world_prototype_starts, [0, 1, 2, 3]) + np.testing.assert_array_equal(grouped.topology.world_prototypes, [1, 0, 1]) + for members in ((2,), (-1,), (0.5,), ("0",), ((),), ((0, 2),), (np.array([[0]]),)): with pytest.raises(ValueError, match="integer indices"): make_clone_plan(assets, (members,), 1) + + def invalid_candidates(weights, count): + return np.full(count, 0 if len(weights) == 1 else -1, dtype=np.int32) + + with pytest.raises(ValueError, match="valid candidate index"): + make_clone_plan(assets, (((0, 1),),), 1, clone_strategy=invalid_candidates) for selector in ("/Banana", np.array([0.5]), np.array([[0]])): with pytest.raises(TypeError, match="integer IDs"): cloner.query.get_asset_prototype_world_index(plan.topology, selector) @@ -347,104 +357,102 @@ def test_batched_world_queries(device, worlds, num_worlds, shared, selectors): assert starts[-1, -1] == len(expected) -class _SemanticWorlds(InclusionSet): - def worlds(self, asset_names, variants): - groups = [] - for candidates in variants: - matches = {} - for candidate in candidates: - tags = dict(candidate.semantic_tags) - if re.fullmatch("gear|fixture", tags["class"]): - matches[tags["size"], tags["assembly"]] = candidate - groups.append(matches) - for key in groups[0]: - if all(key in group for group in groups): - world = {} - for name, group in zip(asset_names, groups, strict=True): - world.setdefault(name, []).append(group[key]) - yield world - - -@configclass -class _ExplicitWorlds(InclusionSet): - selections: list = [] - - def worlds(self, asset_names, variants): - return self.selections - - -def test_inclusion_semantics_generate_legal_worlds_before_replication(): - """Task-local semantic matching selects three worlds from 64**8 possible combinations.""" +def test_inclusion_semantic_groups_remain_factorized_until_scene_selection(): + """One thousand variants in five categories need five groups, not 200**8 worlds per group.""" + variants = [CuboidCfg(size=(1.0, 1.0, 1.0), semantic_tags=[("category", str(i % 5))]) for i in range(1000)] names = [f"object_{index}" for index in range(8)] - variants = [] - for group in range(8): - candidates = [ - CuboidCfg( - size=(1.0, 1.0, 1.0), - semantic_tags=[ - ("size", str(index)), - ("assembly", "drive"), - ("class", "gear" if index < 3 else "decoy"), - ], - ) - for index in range(64) - ] - variants.append(candidates[::-1] if group % 2 else candidates) - worlds, weights = make_valid_clone_combinations(names, variants, [_SemanticWorlds(assets=names)]) - assert worlds == ( - (0, 127, 128, 255, 256, 383, 384, 511), - (1, 126, 129, 254, 257, 382, 385, 510), - (2, 125, 130, 253, 258, 381, 386, 509), - ) - np.testing.assert_array_equal(weights, [1 / 3] * 3) - - # Repeated declarations, unclaimed assets, and weights retain their membership semantics. - robot, parts, tools, lamps = [[CuboidCfg(size=(1.0, 1.0, 1.0)) for _ in range(n)] for n in (1, 3, 2, 2)] - selections = [ - _ExplicitWorlds(assets=["part", "tool"], weight=3.0), - _ExplicitWorlds(assets=["part", "part", "tool"]), + rules = [InclusionSet(assets=names, match_tags=["category"])] + groups, weights = make_valid_clone_combinations(names, [variants] * 8, rules) + assert len(groups) == 5 + assert all(len(group) == 8 and all(len(slot) == 200 for slot in group) for group in groups) + np.testing.assert_array_equal(weights, [0.2] * 5) + plan = make_clone_plan(variants * 8, groups, 128, weights=weights) + topology = plan.topology + assert len(topology.world_prototype_layout) == 128 + assert len(topology.world_prototype_starts) <= 130 + categories = [] + for prototype in topology.world_prototype_layout: + start, end = topology.world_prototype_starts[prototype + 1 : prototype + 3] + row = topology.world_prototypes[start:end] + assert len(row) == 8 + assert len(set(row % 1000 % 5)) == 1 + categories.append(row[0] % 5) + np.testing.assert_array_equal(np.bincount(categories), [26, 25, 26, 25, 26]) + + # The existing random strategy and external NumPy seed own both levels of selection. + state = np.random.get_state() + try: + np.random.seed(42) + random_plan = make_clone_plan(variants * 8, groups, 128, weights=weights, clone_strategy=cloner.random) + np.random.seed(42) + repeated = make_clone_plan(variants * 8, groups, 128, weights=weights, clone_strategy=cloner.random) + finally: + np.random.set_state(state) + np.testing.assert_array_equal(random_plan.topology.world_prototypes, repeated.topology.world_prototypes) + np.testing.assert_array_equal(random_plan.topology.world_prototype_layout, repeated.topology.world_prototype_layout) + rows = random_plan.topology.world_prototypes.reshape(-1, 8) + assert (rows % 5 == rows[:, :1] % 5).all() + assert (rows[:, 0] % 1000 != rows[:, 1] % 1000).any() + + +def test_inclusion_multi_value_tags_repeated_instances_and_unclaimed_assets(): + gears = [ + CuboidCfg(size=(1.0, 1.0, 1.0), semantic_tags=[("size", size), ("assembly", "drive")]) + for size in ("small", "medium", "large") ] - selections[0].selections = [ - {"robot": robot, "part": [parts[2]], "tool": [tools[0]], "lamp": [lamps[0]]}, - ] - selections[1].selections = [ - {"robot": robot, "part": [parts[1], parts[1]], "tool": [tools[0]], "lamp": [lamps[1]]}, - {"robot": robot, "part": [parts[1], parts[1]], "tool": [tools[1]], "lamp": [lamps[1]]}, - ] - worlds, weights = make_valid_clone_combinations( - ["robot", "part", "tool", "lamp"], [robot, parts, tools, lamps], selections + fixtures = [gear.copy() for gear in gears] + fixtures.append( + CuboidCfg( + size=(1.0, 1.0, 1.0), + semantic_tags=[ + ("size", "small"), + ("size", "medium"), + ("size", "large"), + ("assembly", "drive"), + ], + ) ) - assert worlds == ((0, 3, 4, 6), (0, 2, 2, 4, 7), (0, 2, 2, 5, 7)) - np.testing.assert_array_equal(weights, [3.0, 0.5, 0.5]) - - # Collection members share a scene name but each retains its own candidates. - worlds, weights = make_valid_clone_combinations(["collection", "collection"], [parts[:2], tools]) - assert worlds == ((0, 2), (0, 3), (1, 2), (1, 3)) - np.testing.assert_array_equal(weights, [0.25] * 4) - worlds, weights = make_valid_clone_combinations(["part", "tool"], [parts[:2], tools + lamps[:1]]) + # A size match alone is insufficient when the assembly differs. + fixtures.append(CuboidCfg(size=(1.0, 1.0, 1.0), semantic_tags=[("size", "small"), ("assembly", "other")])) + robot = CuboidCfg(size=(1.0, 1.0, 1.0)) + groups, weights = make_valid_clone_combinations( + ["robot", "gear", "fixture"], + [[robot], gears, fixtures], + [InclusionSet(assets=["gear", "gear", "fixture"], match_tags=["size", "assembly"], weight=3.0)], + ) + assert groups == ( + ((0,), (1,), (1,), (4, 7)), + ((0,), (2,), (2,), (5, 7)), + ((0,), (3,), (3,), (6, 7)), + ) + np.testing.assert_array_equal(weights, [1.0] * 3) + plan = make_clone_plan([robot, *gears, *fixtures], groups, 6, weights=weights) + np.testing.assert_array_equal( + plan.topology.world_prototypes, [0, 1, 1, 4, 0, 1, 1, 7, 0, 2, 2, 5, 0, 2, 2, 7, 0, 3, 3, 6, 0, 3, 3, 7] + ) + # No matching configured retains the existing independent product and weights. + worlds, weights = make_valid_clone_combinations(["gear", "fixture"], [gears[:2], fixtures[:3]]) assert worlds == ((0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4)) np.testing.assert_array_equal(weights, [1 / 6] * 6) + # A collection's members retain separate columns, despite sharing one scene name. + worlds, _ = make_valid_clone_combinations(["collection", "collection"], [gears[:2], fixtures[:2]]) + assert worlds == ((0, 2), (0, 3), (1, 2), (1, 3)) -@pytest.mark.parametrize("invalid", ["missing", "extra", "count", "foreign", "copied", "empty"]) -def test_inclusion_worlds_reject_invalid_definitions(invalid): - part, tool = CuboidCfg(size=(1.0, 1.0, 1.0)), CuboidCfg(size=(2.0, 2.0, 2.0)) - selections = [{"part": [part], "tool": [tool]}] - message = "World assets must be" - if invalid == "missing": - del selections[0]["tool"] - elif invalid == "extra": - selections[0]["unknown"] = [part] - elif invalid == "count": - selections[0]["part"] = [part, part] - message = "one configuration per active asset instance" - elif invalid in ("foreign", "copied"): - selections[0]["part"] = [tool if invalid == "foreign" else part.copy()] - message = "not one of its supplied variants" - else: - selections = [] - message = "at least one world" - inclusion = _ExplicitWorlds(assets=["part", "tool"]) - inclusion.selections = selections +@pytest.mark.parametrize("invalid", ["missing-tag", "incompatible", "unknown", "empty"]) +def test_inclusion_matching_rejects_invalid_definitions(invalid): + part = CuboidCfg(size=(1.0, 1.0, 1.0), semantic_tags=[("size", "small")]) + tool = CuboidCfg(size=(1.0, 1.0, 1.0), semantic_tags=[("size", "large")]) + inclusion = InclusionSet(assets=["part", "tool"], match_tags=["size"]) + candidates = [[part], [tool]] + message = "at least one compatible world" + if invalid == "missing-tag": + tool.semantic_tags = None + elif invalid == "unknown": + inclusion.assets.append("unknown") + message = "Unknown assets" + elif invalid == "empty": + candidates[0] = [] + message = "nonempty group" with pytest.raises(ValueError, match=message): - make_valid_clone_combinations(["part", "tool"], [[part], [tool]], [inclusion]) + make_valid_clone_combinations(["part", "tool"], candidates, [inclusion]) diff --git a/source/isaaclab_newton/test/assets/test_rigid_object_mesh_variants.py b/source/isaaclab_newton/test/assets/test_rigid_object_mesh_variants.py index 1fae5b59d76e..c6ba8ee22f23 100644 --- a/source/isaaclab_newton/test/assets/test_rigid_object_mesh_variants.py +++ b/source/isaaclab_newton/test/assets/test_rigid_object_mesh_variants.py @@ -154,18 +154,6 @@ def test_native_selection_preserves_initial_worlds_and_unused_variant(device: st def test_semantic_worlds_choose_initial_variants(device: str) -> None: """Semantic rules select the right native variants, including inherited wrapper tags.""" - @configclass - class AssemblyWorlds(InclusionSet): - assembly: str = "" - - def worlds(self, asset_names, variants): - candidates = dict(zip(asset_names, variants, strict=True)) - for obj in candidates["object"]: - for fixture in candidates["fixture"]: - required = {("assembly", self.assembly), ("domain", "mechanical")} - if required.issubset(obj.semantic_tags) and required.issubset(fixture.semantic_tags): - yield {"object": [obj], "fixture": [fixture]} - scene_cfg = _VariantSceneCfg(num_envs=4, env_spacing=2.0) third = scene_cfg.object.spawn.assets_cfg[0].copy() third.radius, third.mass_props.mass = 0.06, 27.0 @@ -181,8 +169,7 @@ def worlds(self, asset_names, variants): scene_cfg.object.spawn.semantic_tags = [("domain", "mechanical")] scene_cfg.fixture.spawn.semantic_tags = [("domain", "mechanical")] scene_cfg.clone_cfg.clone_combinations = [ - AssemblyWorlds(assets=["object", "fixture"], assembly="drive"), - AssemblyWorlds(assets=["object", "fixture"], assembly="spare"), + InclusionSet(assets=["object", "fixture"], match_tags=["assembly", "domain"]), ] sim_cfg = SimulationCfg( device=device, @@ -195,9 +182,9 @@ def worlds(self, asset_names, variants): sim.register_interactive_scene(scene) sim.reset() asset, fixture = scene["object"], scene["fixture"] - torch.testing.assert_close(asset.mesh_variant_ids.torch.cpu(), torch.tensor([2, 2, 0, 0], dtype=torch.int32)) - torch.testing.assert_close(asset.data.body_mass.torch[:, 0].cpu(), torch.tensor([27.0, 27.0, 1.0, 1.0])) - torch.testing.assert_close(fixture.data.body_mass.torch[:, 0].cpu(), torch.tensor([8.0, 8.0, 1.0, 8.0])) + torch.testing.assert_close(asset.mesh_variant_ids.torch.cpu(), torch.tensor([0, 0, 2, 2], dtype=torch.int32)) + torch.testing.assert_close(asset.data.body_mass.torch[:, 0].cpu(), torch.tensor([1.0, 1.0, 27.0, 27.0])) + torch.testing.assert_close(fixture.data.body_mass.torch[:, 0].cpu(), torch.tensor([1.0, 8.0, 8.0, 8.0])) @pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) From e1a6080cfa1fc156f784decaf472b3e9550c8fcd Mon Sep 17 00:00:00 2001 From: Octi Zhang Date: Tue, 24 Nov 2026 02:50:11 -0800 Subject: [PATCH 8/8] Trim unrelated documentation from semantic inclusion PR --- docs/source/how-to/multi_asset_spawning.rst | 59 +-------------------- docs/source/refs/contributing.rst | 6 --- 2 files changed, 1 insertion(+), 64 deletions(-) diff --git a/docs/source/how-to/multi_asset_spawning.rst b/docs/source/how-to/multi_asset_spawning.rst index c9d24ad94716..c7c8fea60849 100644 --- a/docs/source/how-to/multi_asset_spawning.rst +++ b/docs/source/how-to/multi_asset_spawning.rst @@ -131,70 +131,13 @@ variant because their batched Newton views currently require a uniform body layo :end-at: scene_cfg.robot.spawn.usd_path = scene_cfg.robot.spawn.usd_path[0] :dedent: 8 -An :class:`~isaaclab.cloner.InclusionSet` declares which assets are active and which semantic tag -values must match. No subclass or callback is needed. For a scene with ``gear`` and ``fixture`` assets: - -.. code-block:: python - - scene_cfg.clone_cfg.clone_combinations = [ - InclusionSet(assets=["gear", "fixture"], match_tags=["size", "assembly"]), - ] - -Tag the individual spawner configurations using the existing semantic API: - -.. code-block:: python - - small_gear_cfg.semantic_tags = [("size", "small"), ("assembly", "drive")] - small_fixture_cfg.semantic_tags = [("size", "small"), ("assembly", "drive")] - universal_fixture_cfg.semantic_tags = [ - ("size", "small"), ("size", "medium"), ("size", "large"), - ("assembly", "drive"), - ] - -Every selected gear and fixture must share a value for each requested tag type. The universal fixture -can therefore match small, medium, or large gears in the drive assembly. Missing requested tags do not -match. Tag values are compared exactly; there are no reserved wildcard values or implicit regex rules. -Tags inherited from ``MultiAssetSpawnerCfg`` also participate. ``MultiUsdFileCfg`` candidates inherit -the wrapper's tags and retain their individual USD paths. - -Repeat an asset name to request multiple instances: - -.. code-block:: python - - InclusionSet(assets=["gear", "gear", "fixture"], match_tags=["size", "assembly"]) - -This requests two gear instances and one fixture, all sharing a size and assembly. It does not express -separate pairwise constraints. Repeated instances may use the same variant. Assets not referenced by -any inclusion definition remain active independently and do not participate in tag matching. Collection -members retain their separate candidate slots even when they share a scene asset name. - -Matching definitions remain compact until clone-plan construction. For example, 1,000 candidates across -five categories and eight asset slots can be represented as five compatible groups, rather than -expanding every valid concrete world. The scene's ``num_envs`` determines how many worlds to instantiate. -Its :attr:`~isaaclab.cloner.CloneCfg.clone_strategy` selects compatible groups according to their weights, -then selects each slot's concrete variant within the chosen group. Identical concrete worlds share a -prototype. The inclusion weight is divided equally across its compatible groups; this gives equal -weight to tag-value groups, rather than to every possible concrete combination. Multi-valued tags can -make groups overlap. - -The existing ``sequential`` strategy distributes environments across groups and candidate lists in order. -The ``random`` strategy draws groups by weight and candidates uniformly, using the existing NumPy random -state. ``InclusionSet`` does not own an environment count or random seed. Planning cost depends on -candidate metadata and selected worlds, without expanding the product within each matching group; -loading and simulating concrete assets still has its own cost. - -With ``match_tags=[]`` (the default), the existing independent Cartesian product and assignment behavior -are preserved. Inclusion interpretation stays in scene planning. ``ReplicateSession`` forwards the -resolved definitions without applying tag matching or task-specific rules. - For more detail on prototype assignment and replication, see :doc:`cloning`. Reset-time selection ~~~~~~~~~~~~~~~~~~~~ A rigid object's multi-asset spawner defines the variants and their IDs in list order. Clone composition chooses -the initial variant for each world, using those same IDs. A reset event can change it before writing the -episode's pose and velocity: +the initial variant for each world. A reset event can change it before writing the episode's pose and velocity: .. code-block:: python diff --git a/docs/source/refs/contributing.rst b/docs/source/refs/contributing.rst index 44aafd85070a..3cc5aa051dc7 100644 --- a/docs/source/refs/contributing.rst +++ b/docs/source/refs/contributing.rst @@ -439,12 +439,6 @@ before changing an interface. Apply these rules when adding code or cleaning up required attribute; express optional fields explicitly in the interface. Use concrete defaults for known empty selections. Reserve ``None`` for a distinct policy or lifecycle state, such as choosing an environment's frame rate or waiting for a client to connect. -* Inclusion definitions declare membership and shared semantic tag types through ``match_tags``. - Reuse existing spawner ``semantic_tags`` rather than adding variant labels, positional pins, or - user-overridable matching callbacks. Inclusion sets do not own environment counts or random seeds. - Resolve compatibility into factorized candidate groups during scene planning; let clone-plan construction - and the scene's clone strategy select concrete worlds without expanding every valid combination. - Keep inclusion interpretation and task-specific matching classes out of replication execution. * Give each piece of state and validation one owner. Consumers should use the owner's contract instead of repairing results or maintaining duplicate state. Cache derived values only when their lifetime and invalidation are clear; do not expose mutable cached results for callers to modify accidentally.