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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/source/api/lab/isaaclab.cloner.rst
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,9 @@ Additional Public Classes
:show-inheritance:

.. autoclass:: InclusionSet
:members:
:show-inheritance:
:exclude-members: __init__

.. autoclass:: ReplicateContext
:members:
Expand Down
15 changes: 14 additions & 1 deletion docs/source/how-to/multi_asset_spawning.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 2 additions & 0 deletions source/isaaclab/changelog.d/pinned-clone-variants.added.rst
Original file line number Diff line number Diff line change
@@ -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.
Empty file.
15 changes: 15 additions & 0 deletions source/isaaclab/isaaclab/cloner/cloner_cfg.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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
Expand Down
14 changes: 13 additions & 1 deletion source/isaaclab/isaaclab/cloner/replicate_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,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.
Expand All @@ -68,10 +70,20 @@ 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)
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))
Expand Down
24 changes: 24 additions & 0 deletions source/isaaclab/test/cloner/test_replicate_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -285,6 +287,28 @@ 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():

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Warning · Test Quality — Mark the planning test kitless

CI selects kitless files by marker text. This pure-planning test has no kitless marker, so that selection omits it. Add pytest.mark.kitless to the test.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Warning · Style Consistency — Remove assertion-narrating comment

The comment repeats the test docstring and narrates the following world and weight assertions. Remove it; the prototype-row mapping above explains the non-obvious numeric IDs.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Warning · Style Consistency — Use functional configuration cloning

New configuration code should use the guide's functional operations. Replace this added .copy() call with clone(...); the legacy method remains supported but is not the preferred new-code convention.

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",
Expand Down
Loading