From a823a258bea881847a9e3366665e9e6c03ed7c74 Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Thu, 29 Oct 2026 02:10:03 +0100 Subject: [PATCH 01/10] Share success-guided reset-state sampling across tasks --- .../api/lab_tasks/isaaclab_tasks.utils.rst | 53 +++++++++++ .../shared-reset-state-sampling.added.rst | 4 + .../shared-reset-state-sampling.minor | 0 .../contrib/nist/utils/__init__.pyi | 2 +- .../contrib/nist/utils/event_combinators.py | 2 +- .../contrib/nist/utils/sampling/__init__.pyi | 8 +- .../contrib/nist/utils/sampling/sampler.py | 56 +---------- .../nist/utils/sampling/sampler_cfg.py | 28 +----- .../utils/sampling/sampling_strategies.py | 66 +------------ .../utils/sampling/sampling_strategies_cfg.py | 66 +------------ .../isaaclab_tasks/utils/__init__.pyi | 3 + .../isaaclab_tasks/utils/reset_states.py | 92 +++++++++++++++++++ .../isaaclab_tasks/utils/sampling/__init__.py | 10 ++ .../utils/sampling/__init__.pyi | 28 ++++++ .../isaaclab_tasks/utils/sampling/sampler.py | 60 ++++++++++++ .../utils/sampling/sampler_cfg.py | 26 ++++++ .../utils/sampling/sampling_strategies.py | 68 ++++++++++++++ .../utils/sampling/sampling_strategies_cfg.py | 68 ++++++++++++++ .../isaaclab_tasks/test/test_reset_states.py | 56 +++++++++++ 19 files changed, 486 insertions(+), 210 deletions(-) create mode 100644 source/isaaclab_tasks/changelog.d/shared-reset-state-sampling.added.rst create mode 100644 source/isaaclab_tasks/changelog.d/shared-reset-state-sampling.minor create mode 100644 source/isaaclab_tasks/isaaclab_tasks/utils/reset_states.py create mode 100644 source/isaaclab_tasks/isaaclab_tasks/utils/sampling/__init__.py create mode 100644 source/isaaclab_tasks/isaaclab_tasks/utils/sampling/__init__.pyi create mode 100644 source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampler.py create mode 100644 source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampler_cfg.py create mode 100644 source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampling_strategies.py create mode 100644 source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampling_strategies_cfg.py create mode 100644 source/isaaclab_tasks/test/test_reset_states.py diff --git a/docs/source/api/lab_tasks/isaaclab_tasks.utils.rst b/docs/source/api/lab_tasks/isaaclab_tasks.utils.rst index 3ffd8f075bc5..8a906c2707c4 100644 --- a/docs/source/api/lab_tasks/isaaclab_tasks.utils.rst +++ b/docs/source/api/lab_tasks/isaaclab_tasks.utils.rst @@ -4,3 +4,56 @@ .. automodule:: isaaclab_tasks.utils :members: :imported-members: + +Reset-state sampling +-------------------- + +:class:`~isaaclab_tasks.utils.ResetStateSampler` shares success-guided sampling between +tasks without prescribing their geometry or state representation. A task creates a fixed +catalog of valid starts, and the sampler assigns one catalog row to each environment. +The configured :class:`~isaaclab_tasks.utils.SuccessMonitor` records recent episode outcomes +for each row. The default Beta and uniform mixture favors starts with intermediate success +while keeping every row eligible. + +Generate and validate the catalog once when the environment starts. Procedural tasks can +store joint poses, object poses, and command metadata in device tensors indexed by row. +For cached simulation states, use +:meth:`~isaaclab.scene.InteractiveScene.get_state` with ``is_relative=True`` and restore +selected rows through :meth:`~isaaclab.scene.InteractiveScene.reset_to` with the same flag. +This preserves environment-relative positions and the public scene state format; no custom +asset serializer or private scene registries are needed. Catalog generation, acceptance +checks, and optional persistence remain task responsibilities. + +Construct the sampler once, then select rows before resetting the physical scene: + +.. code-block:: python + + from isaaclab_tasks.utils import ResetStateSampler, ResetStateSamplerCfg + + reset_sampler = ResetStateSampler(ResetStateSamplerCfg(), num_envs, row_count, device) + + # In the task's reset event, before clearing its previous success flags: + rows = reset_sampler.reset( + env_ids, + success=episode_success[env_ids], + valid=episode_length[env_ids] > 0, + ) + # Restore physical state and command metadata indexed by rows using public asset APIs. + +``success`` and ``valid`` contain one value per selected environment. Omit ``success`` for +the initial draw, or use ``valid`` to exclude zero-step manual resets. An optional ``row_mask`` +restricts the next draw without changing which completed episodes are credited. Outcomes +always belong to the previous assignments, and a partial reset preserves other environments' +assignments. Task code must also clear commands, action targets, and attachment state that +are not represented in its physical state bank. + +Keep evaluation starts fixed or uniformly sampled, and report success from complete task +starts separately from the adaptive training mixture. Sampling history belongs to the live +environment; ordinary policy checkpoints do not save it. + +Sampling strategies +------------------- + +.. automodule:: isaaclab_tasks.utils.sampling + :members: + :imported-members: diff --git a/source/isaaclab_tasks/changelog.d/shared-reset-state-sampling.added.rst b/source/isaaclab_tasks/changelog.d/shared-reset-state-sampling.added.rst new file mode 100644 index 000000000000..a5e335969ddf --- /dev/null +++ b/source/isaaclab_tasks/changelog.d/shared-reset-state-sampling.added.rst @@ -0,0 +1,4 @@ +* Added ``ResetStateSampler`` to share success-guided row assignment and completed-episode + bookkeeping between cached and procedural reset catalogs, using the existing success monitor. +* Moved reusable weighted sampling strategies to ``isaaclab_tasks.utils.sampling`` and retained + the previous NIST import paths for existing configurations. diff --git a/source/isaaclab_tasks/changelog.d/shared-reset-state-sampling.minor b/source/isaaclab_tasks/changelog.d/shared-reset-state-sampling.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/nist/utils/__init__.pyi b/source/isaaclab_tasks/isaaclab_tasks/contrib/nist/utils/__init__.pyi index c7f9b447a380..193b5bb4f97a 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/nist/utils/__init__.pyi +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/nist/utils/__init__.pyi @@ -41,7 +41,7 @@ from .pose_offset import Offset from .rigid_object_hasher import RigidObjectHasher from .event_combinators import ChainedResetTerms, TermChoice, reset_accumulator from .reset_state import get_reset_state, set_reset_state -from .sampling import ( +from isaaclab_tasks.utils.sampling import ( BetaSamplingStrategy, BetaSamplingStrategyCfg, Sampler, diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/nist/utils/event_combinators.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/nist/utils/event_combinators.py index cfa9cc0465a5..d28d4f46a5af 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/nist/utils/event_combinators.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/nist/utils/event_combinators.py @@ -35,7 +35,7 @@ from isaaclab_tasks.contrib.nist.utils import reset_state from isaaclab_tasks.contrib.nist.utils.grid_downsample import extract_features, grid_bucket_downsample -from isaaclab_tasks.contrib.nist.utils.sampling import Sampler, SamplerCfg +from isaaclab_tasks.utils.sampling import Sampler, SamplerCfg from isaaclab_tasks.utils.success_monitor import SuccessMonitorCfg if TYPE_CHECKING: diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/nist/utils/sampling/__init__.pyi b/source/isaaclab_tasks/isaaclab_tasks/contrib/nist/utils/sampling/__init__.pyi index 847c8832fbca..5fc33d20c3ab 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/nist/utils/sampling/__init__.pyi +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/nist/utils/sampling/__init__.pyi @@ -14,14 +14,12 @@ __all__ = [ "UniformSamplingStrategyCfg", ] -from .sampler import Sampler -from .sampler_cfg import SamplerCfg -from .sampling_strategies import ( +from isaaclab_tasks.utils.sampling import ( + Sampler, + SamplerCfg, BetaSamplingStrategy, SamplingStrategy, UniformSamplingStrategy, -) -from .sampling_strategies_cfg import ( BetaSamplingStrategyCfg, SamplingStrategyCfg, UniformSamplingStrategyCfg, diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/nist/utils/sampling/sampler.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/nist/utils/sampling/sampler.py index 12443a8469fd..e960f03ea6c7 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/nist/utils/sampling/sampler.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/nist/utils/sampling/sampler.py @@ -3,58 +3,6 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Weighted sampling over a fixed success-rate table.""" +"""Compatibility imports; use :mod:`isaaclab_tasks.utils.sampling`.""" -from __future__ import annotations - -from typing import TYPE_CHECKING - -import torch - -from isaaclab.utils import instantiate - -from isaaclab_tasks.contrib.nist.utils.sampling.sampling_strategies import SamplingStrategy - -if TYPE_CHECKING: - from isaaclab_tasks.contrib.nist.utils.sampling.sampler_cfg import SamplerCfg - - -class Sampler: - """Compose weighted sampling strategies over per-item success rates.""" - - def __init__(self, cfg: SamplerCfg, success_rates: torch.Tensor) -> None: - self.strategies: list[tuple[SamplingStrategy, float]] = [ - (instantiate(strategy_cfg, success_rates), float(strategy_cfg.weight)) for strategy_cfg in cfg.strategies - ] - self.eps = float(cfg.eps) - self.names = [strategy.name for strategy, _ in self.strategies] - self._score_rows = torch.empty( - (len(self.strategies), len(success_rates)), device=success_rates.device, dtype=torch.float32 - ) - self._weighted = torch.empty_like(success_rates, dtype=torch.float32) - self._probs = torch.empty_like(success_rates, dtype=torch.float32) - - def scores(self) -> torch.Tensor: - """Return contiguous per-strategy score rows shaped ``[num_strategies, num_items]``.""" - for i, (strategy, _) in enumerate(self.strategies): - strategy.score(self._score_rows[i]) - return self._score_rows - - def probabilities(self) -> torch.Tensor: - """Return ``[num_items]`` probability vector summing to 1.""" - scores = self.scores() - self._weighted.zero_() - for i, (_, weight) in enumerate(self.strategies): - self._weighted.add_(scores[i], alpha=max(0.0, weight)) - self._weighted.add_(self.eps) - torch.div(self._weighted, self._weighted.sum(), out=self._probs) - return self._probs - - def sample(self, probs: torch.Tensor, num_samples: int) -> torch.Tensor: - """Sample item indices from ``probs``.""" - return torch.multinomial(probs, num_samples, replacement=True) - - def probabilities_and_sample(self, num_samples: int) -> tuple[torch.Tensor, torch.Tensor]: - """Return probabilities and sampled item indices.""" - probs = self.probabilities() - return probs, self.sample(probs, num_samples) +from isaaclab_tasks.utils.sampling.sampler import Sampler as Sampler diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/nist/utils/sampling/sampler_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/nist/utils/sampling/sampler_cfg.py index 9c623659b4e6..fa7be410b033 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/nist/utils/sampling/sampler_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/nist/utils/sampling/sampler_cfg.py @@ -3,30 +3,6 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Configuration for :class:`Sampler`.""" +"""Compatibility imports; use :mod:`isaaclab_tasks.utils.sampling`.""" -from __future__ import annotations - -from dataclasses import field - -from isaaclab.utils import configclass - -from isaaclab_tasks.contrib.nist.utils.sampling.sampler import Sampler - - -@configclass -class SamplerCfg: - """Blueprint for a :class:`Sampler`. - - Attributes: - class_type: Runtime sampler class to instantiate. - strategies: Weighted sampling-strategy cfgs composed by the sampler. - eps: Soft floor on per-item probability. - """ - - class_type: type[Sampler] | str = "{DIR}.sampler:Sampler" - """Runtime sampler class.""" - strategies: list = field(default_factory=list) - """Weighted sampling-strategy cfgs composed by the sampler.""" - eps: float = 1e-3 - """Soft floor on per-item probability before normalization.""" +from isaaclab_tasks.utils.sampling.sampler_cfg import SamplerCfg as SamplerCfg diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/nist/utils/sampling/sampling_strategies.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/nist/utils/sampling/sampling_strategies.py index 13d3175690fe..180481015140 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/nist/utils/sampling/sampling_strategies.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/nist/utils/sampling/sampling_strategies.py @@ -3,66 +3,8 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Runtime sampling strategies. +"""Compatibility imports; use :mod:`isaaclab_tasks.utils.sampling`.""" -:meth:`SamplingStrategy.score` writes a per-item non-negative score tensor into -the pre-allocated ``out`` buffer; the sampler sums weighted scores and -normalizes. -""" - -from __future__ import annotations - -from typing import TYPE_CHECKING, Protocol - -import torch - -if TYPE_CHECKING: - from isaaclab_tasks.contrib.nist.utils.sampling.sampling_strategies_cfg import ( - BetaSamplingStrategyCfg, - UniformSamplingStrategyCfg, - ) - - -class SamplingStrategy(Protocol): - """Per-item scorer for sampler probability construction. - - :meth:`score` writes non-negative scores into ``out`` using the success-rate - tensor supplied at construction. - """ - - name: str - """Short identifier used in diagnostic / log keys.""" - - def score(self, out: torch.Tensor) -> None: - """Write ``[num_items]`` non-negative unnormalized scores into ``out``.""" - ... - - -class BetaSamplingStrategy: - """Per-item Beta-kernel score peaked at a target success rate.""" - - name = "beta" - - def __init__(self, cfg: BetaSamplingStrategyCfg, success_rates: torch.Tensor) -> None: - target = max(0.0, min(1.0, float(cfg.target))) - kappa = max(0.0, float(cfg.kappa)) - self._a = 1.0 + kappa * target - self._b = 1.0 + kappa * (1.0 - target) - self._rates = success_rates - - def score(self, out: torch.Tensor) -> None: - out.copy_(self._rates) - out.pow_(self._a - 1.0) - out.mul_((1.0 - self._rates).pow(self._b - 1.0)) - - -class UniformSamplingStrategy: - """Constant 1.0 per item -- the trivial baseline / floor.""" - - name = "uniform" - - def __init__(self, cfg: UniformSamplingStrategyCfg, success_rates: torch.Tensor) -> None: - del cfg, success_rates - - def score(self, out: torch.Tensor) -> None: - out.fill_(1.0) +from isaaclab_tasks.utils.sampling.sampling_strategies import BetaSamplingStrategy as BetaSamplingStrategy +from isaaclab_tasks.utils.sampling.sampling_strategies import SamplingStrategy as SamplingStrategy +from isaaclab_tasks.utils.sampling.sampling_strategies import UniformSamplingStrategy as UniformSamplingStrategy diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/nist/utils/sampling/sampling_strategies_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/nist/utils/sampling/sampling_strategies_cfg.py index 4da48a7e3881..1dfb776bdd6f 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/nist/utils/sampling/sampling_strategies_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/nist/utils/sampling/sampling_strategies_cfg.py @@ -3,66 +3,10 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Configuration classes for sampling strategies.""" +"""Compatibility imports; use :mod:`isaaclab_tasks.utils.sampling`.""" -from __future__ import annotations - -from isaaclab.utils import configclass - -from isaaclab_tasks.contrib.nist.utils.sampling.sampling_strategies import ( - BetaSamplingStrategy, - UniformSamplingStrategy, +from isaaclab_tasks.utils.sampling.sampling_strategies_cfg import BetaSamplingStrategyCfg as BetaSamplingStrategyCfg +from isaaclab_tasks.utils.sampling.sampling_strategies_cfg import SamplingStrategyCfg as SamplingStrategyCfg +from isaaclab_tasks.utils.sampling.sampling_strategies_cfg import ( + UniformSamplingStrategyCfg as UniformSamplingStrategyCfg, ) - - -@configclass -class BetaSamplingStrategyCfg: - """Blueprint for a :class:`BetaSamplingStrategy`. - - Score shape: - - .. code-block:: text - - score - ^ - | /\\ - | / \\ - |___________/ \\___________ - +----------------------------> success_rate - 0 target 1 - """ - - class_type: type[BetaSamplingStrategy] | str = "{DIR}.sampling_strategies:BetaSamplingStrategy" - """Runtime strategy class.""" - weight: float = 1.0 - """Multiplier on this strategy's score before sampler normalization.""" - target: float = 0.66 - """Success rate where the Beta score peaks.""" - kappa: float = 1.0 - """Peak sharpness around :attr:`target`; larger values concentrate more mass near the target.""" - - -@configclass -class UniformSamplingStrategyCfg: - """Blueprint for a :class:`UniformSamplingStrategy`. - - Score shape: - - .. code-block:: text - - score - ^ - |----------------------------- - | - | - +----------------------------> item index - """ - - class_type: type[UniformSamplingStrategy] | str = "{DIR}.sampling_strategies:UniformSamplingStrategy" - """Runtime strategy class.""" - weight: float = 1.0 - """Multiplier on this strategy's constant score before sampler normalization.""" - - -SamplingStrategyCfg = BetaSamplingStrategyCfg | UniformSamplingStrategyCfg -"""Discriminated union of sampling-strategy cfg types.""" diff --git a/source/isaaclab_tasks/isaaclab_tasks/utils/__init__.pyi b/source/isaaclab_tasks/isaaclab_tasks/utils/__init__.pyi index 5d86b9105fcf..739c652b2ac6 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/utils/__init__.pyi +++ b/source/isaaclab_tasks/isaaclab_tasks/utils/__init__.pyi @@ -13,6 +13,8 @@ __all__ = [ "resolve_task_config", "resolve_presets", "setup_preset_cli", + "ResetStateSampler", + "ResetStateSamplerCfg", "SuccessMonitor", "SuccessMonitorCfg", ] @@ -21,3 +23,4 @@ from .hydra import PresetCfg, preset, resolve_task_config, resolve_presets, setu from .importer import import_packages from .parse_cfg import get_checkpoint_path, load_cfg_from_registry, parse_env_cfg from .success_monitor import SuccessMonitor, SuccessMonitorCfg +from .reset_states import ResetStateSampler, ResetStateSamplerCfg diff --git a/source/isaaclab_tasks/isaaclab_tasks/utils/reset_states.py b/source/isaaclab_tasks/isaaclab_tasks/utils/reset_states.py new file mode 100644 index 000000000000..8c3fd5da48b4 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/utils/reset_states.py @@ -0,0 +1,92 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Success-guided row selection for cached or procedurally generated reset states.""" + +from __future__ import annotations + +import torch + +from isaaclab.utils import configclass, instantiate + +from .sampling import BetaSamplingStrategyCfg, Sampler, SamplerCfg, UniformSamplingStrategyCfg +from .success_monitor import SuccessMonitor, SuccessMonitorCfg + + +@configclass +class ResetStateSamplerCfg: + """Configure outcome tracking and sampling independently of a task's state representation.""" + + class_type: type[ResetStateSampler] | str = "{DIR}.reset_states:ResetStateSampler" + """Runtime sampler implementation.""" + + success_monitor: SuccessMonitorCfg = SuccessMonitorCfg(monitored_history_len=50) + """Rolling episode history for each reset row.""" + + sampling: SamplerCfg = SamplerCfg( + strategies=[BetaSamplingStrategyCfg(target=0.5, kappa=2.0), UniformSamplingStrategyCfg(weight=0.05)], + eps=1.0e-4, + ) + """Sampling strategies; the default favors intermediate success while retaining all rows.""" + + +class ResetStateSampler: + """Track the assigned reset row and completed outcomes for each environment. + + Tasks generate a fixed catalog of reset states and restore the selected rows through their + normal reset events. Rows can index tensor tables, cached scene states, or deterministic + procedural recipes. This class neither stores physical states nor writes to the scene. + + Args: + cfg: Outcome history and sampling configuration. + num_envs: Number of environments sharing the row catalog. + row_count: Number of reset rows in the catalog. + device: Device used by the catalog and episode outcomes. + """ + + def __init__(self, cfg: ResetStateSamplerCfg, num_envs: int, row_count: int, device: str | torch.device) -> None: + if num_envs < 1 or row_count < 1: + raise ValueError("num_envs and row_count must be positive.") + self.cfg = cfg + self.row_ids = torch.zeros(num_envs, dtype=torch.long, device=device) + """Current reset-row assignment for every environment, shape [num_envs].""" + self.success_monitor: SuccessMonitor = instantiate(cfg.success_monitor, 1, row_count, device) + """Rolling outcomes indexed by reset row.""" + self.sampler: Sampler = instantiate(cfg.sampling, self.success_monitor.success_rate) + self.probabilities = self.sampler.probabilities() + """Most recently used row probabilities, shape [row_count]. Treat this tensor as read-only.""" + + def reset( + self, + env_ids: torch.Tensor, + success: torch.Tensor | None = None, + valid: torch.Tensor | None = None, + row_mask: torch.Tensor | None = None, + ) -> torch.Tensor: + """Record the finished episodes before selecting their next reset rows. + + Call this before clearing task success flags or restoring physical state. Pass no outcomes + at startup, or mask zero-step/manual resets with ``valid``. Only selected environments' + assignments change; outcome history remains shared across the entire row catalog. + + Args: + env_ids: Resetting environment indices, shape [N], on the sampler device. + success: Whether each selected episode succeeded, shape [N]. ``None`` skips recording. + valid: Which selected outcomes to record, shape [N]. ``None`` records every outcome. + row_mask: Eligible catalog rows, shape [row_count]. ``None`` permits every row. + At least one permitted row must have positive sampling weight. + + Returns: + The newly assigned reset-row indices, shape [N], in ``env_ids`` order. + """ + if success is not None: + self.success_monitor.success_update(self.row_ids[env_ids], success, valid) + self.probabilities = self.sampler.probabilities() + if row_mask is not None: + self.probabilities = self.probabilities * row_mask + self.probabilities.div_(self.probabilities.sum()) + if env_ids.numel(): + self.row_ids[env_ids] = self.sampler.sample(self.probabilities, env_ids.numel()) + return self.row_ids[env_ids] diff --git a/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/__init__.py b/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/__init__.py new file mode 100644 index 000000000000..a72c683bbf2f --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Sampling strategies for multi-task curriculum selection.""" + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/__init__.pyi b/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/__init__.pyi new file mode 100644 index 000000000000..847c8832fbca --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/__init__.pyi @@ -0,0 +1,28 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +__all__ = [ + "BetaSamplingStrategy", + "BetaSamplingStrategyCfg", + "Sampler", + "SamplerCfg", + "SamplingStrategy", + "SamplingStrategyCfg", + "UniformSamplingStrategy", + "UniformSamplingStrategyCfg", +] + +from .sampler import Sampler +from .sampler_cfg import SamplerCfg +from .sampling_strategies import ( + BetaSamplingStrategy, + SamplingStrategy, + UniformSamplingStrategy, +) +from .sampling_strategies_cfg import ( + BetaSamplingStrategyCfg, + SamplingStrategyCfg, + UniformSamplingStrategyCfg, +) diff --git a/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampler.py b/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampler.py new file mode 100644 index 000000000000..3249b720680e --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampler.py @@ -0,0 +1,60 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Weighted sampling over a fixed success-rate table.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import torch + +from isaaclab.utils import instantiate + +from isaaclab_tasks.utils.sampling.sampling_strategies import SamplingStrategy + +if TYPE_CHECKING: + from isaaclab_tasks.utils.sampling.sampler_cfg import SamplerCfg + + +class Sampler: + """Compose weighted sampling strategies over per-item success rates.""" + + def __init__(self, cfg: SamplerCfg, success_rates: torch.Tensor) -> None: + self.strategies: list[tuple[SamplingStrategy, float]] = [ + (instantiate(strategy_cfg, success_rates), float(strategy_cfg.weight)) for strategy_cfg in cfg.strategies + ] + self.eps = float(cfg.eps) + self.names = [strategy.name for strategy, _ in self.strategies] + self._score_rows = torch.empty( + (len(self.strategies), len(success_rates)), device=success_rates.device, dtype=torch.float32 + ) + self._weighted = torch.empty_like(success_rates, dtype=torch.float32) + self._probs = torch.empty_like(success_rates, dtype=torch.float32) + + def scores(self) -> torch.Tensor: + """Return contiguous per-strategy score rows shaped ``[num_strategies, num_items]``.""" + for i, (strategy, _) in enumerate(self.strategies): + strategy.score(self._score_rows[i]) + return self._score_rows + + def probabilities(self) -> torch.Tensor: + """Return ``[num_items]`` probability vector summing to 1.""" + scores = self.scores() + self._weighted.zero_() + for i, (_, weight) in enumerate(self.strategies): + self._weighted.add_(scores[i], alpha=max(0.0, weight)) + self._weighted.add_(self.eps) + torch.div(self._weighted, self._weighted.sum(), out=self._probs) + return self._probs + + def sample(self, probs: torch.Tensor, num_samples: int) -> torch.Tensor: + """Sample item indices from ``probs``.""" + return torch.multinomial(probs, num_samples, replacement=True) + + def probabilities_and_sample(self, num_samples: int) -> tuple[torch.Tensor, torch.Tensor]: + """Return probabilities and sampled item indices.""" + probs = self.probabilities() + return probs, self.sample(probs, num_samples) diff --git a/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampler_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampler_cfg.py new file mode 100644 index 000000000000..44839269044f --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampler_cfg.py @@ -0,0 +1,26 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Configuration for :class:`Sampler`.""" + +from __future__ import annotations + +from dataclasses import field + +from isaaclab.utils import configclass + +from isaaclab_tasks.utils.sampling.sampler import Sampler + + +@configclass +class SamplerCfg: + """Blueprint for a :class:`Sampler`.""" + + class_type: type[Sampler] | str = "{DIR}.sampler:Sampler" + """Runtime sampler class.""" + strategies: list = field(default_factory=list) + """Weighted sampling-strategy cfgs composed by the sampler.""" + eps: float = 1e-3 + """Soft floor on per-item probability before normalization.""" diff --git a/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampling_strategies.py b/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampling_strategies.py new file mode 100644 index 000000000000..b5b07d7f2f83 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampling_strategies.py @@ -0,0 +1,68 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Runtime sampling strategies. + +:meth:`SamplingStrategy.score` writes a per-item non-negative score tensor into +the pre-allocated ``out`` buffer; the sampler sums weighted scores and +normalizes. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Protocol + +import torch + +if TYPE_CHECKING: + from isaaclab_tasks.utils.sampling.sampling_strategies_cfg import ( + BetaSamplingStrategyCfg, + UniformSamplingStrategyCfg, + ) + + +class SamplingStrategy(Protocol): + """Per-item scorer for sampler probability construction. + + :meth:`score` writes non-negative scores into ``out`` using the success-rate + tensor supplied at construction. + """ + + name: str + """Short identifier used in diagnostic / log keys.""" + + def score(self, out: torch.Tensor) -> None: + """Write ``[num_items]`` non-negative unnormalized scores into ``out``.""" + ... + + +class BetaSamplingStrategy: + """Per-item Beta-kernel score peaked at a target success rate.""" + + name = "beta" + + def __init__(self, cfg: BetaSamplingStrategyCfg, success_rates: torch.Tensor) -> None: + target = max(0.0, min(1.0, float(cfg.target))) + kappa = max(0.0, float(cfg.kappa)) + self._a = 1.0 + kappa * target + self._b = 1.0 + kappa * (1.0 - target) + self._rates = success_rates + + def score(self, out: torch.Tensor) -> None: + out.copy_(self._rates) + out.pow_(self._a - 1.0) + out.mul_((1.0 - self._rates).pow(self._b - 1.0)) + + +class UniformSamplingStrategy: + """Constant 1.0 per item -- the trivial baseline / floor.""" + + name = "uniform" + + def __init__(self, cfg: UniformSamplingStrategyCfg, success_rates: torch.Tensor) -> None: + del cfg, success_rates + + def score(self, out: torch.Tensor) -> None: + out.fill_(1.0) diff --git a/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampling_strategies_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampling_strategies_cfg.py new file mode 100644 index 000000000000..db5670d4355c --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampling_strategies_cfg.py @@ -0,0 +1,68 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Configuration classes for sampling strategies.""" + +from __future__ import annotations + +from isaaclab.utils import configclass + +from isaaclab_tasks.utils.sampling.sampling_strategies import ( + BetaSamplingStrategy, + UniformSamplingStrategy, +) + + +@configclass +class BetaSamplingStrategyCfg: + """Blueprint for a :class:`BetaSamplingStrategy`. + + Score shape: + + .. code-block:: text + + score + ^ + | /\\ + | / \\ + |___________/ \\___________ + +----------------------------> success_rate + 0 target 1 + """ + + class_type: type[BetaSamplingStrategy] | str = "{DIR}.sampling_strategies:BetaSamplingStrategy" + """Runtime strategy class.""" + weight: float = 1.0 + """Multiplier on this strategy's score before sampler normalization.""" + target: float = 0.66 + """Success rate where the Beta score peaks.""" + kappa: float = 1.0 + """Peak sharpness around :attr:`target`; larger values concentrate more mass near the target.""" + + +@configclass +class UniformSamplingStrategyCfg: + """Blueprint for a :class:`UniformSamplingStrategy`. + + Score shape: + + .. code-block:: text + + score + ^ + |----------------------------- + | + | + +----------------------------> item index + """ + + class_type: type[UniformSamplingStrategy] | str = "{DIR}.sampling_strategies:UniformSamplingStrategy" + """Runtime strategy class.""" + weight: float = 1.0 + """Multiplier on this strategy's constant score before sampler normalization.""" + + +SamplingStrategyCfg = BetaSamplingStrategyCfg | UniformSamplingStrategyCfg +"""Discriminated union of sampling-strategy cfg types.""" diff --git a/source/isaaclab_tasks/test/test_reset_states.py b/source/isaaclab_tasks/test/test_reset_states.py new file mode 100644 index 000000000000..16dc055631bd --- /dev/null +++ b/source/isaaclab_tasks/test/test_reset_states.py @@ -0,0 +1,56 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Outcome attribution and selective resets at the shared sampler boundary.""" + +import torch + +from isaaclab_tasks.utils import ResetStateSampler, ResetStateSamplerCfg, SuccessMonitorCfg + + +def test_reset_records_previous_rows_and_preserves_unselected_environments(): + """Startup masks and partial resets never credit a replacement row or an untouched episode.""" + sampler = ResetStateSampler( + ResetStateSamplerCfg(success_monitor=SuccessMonitorCfg(monitored_history_len=2)), 4, 3, "cpu" + ) + sampler.row_ids[:] = torch.tensor([0, 0, 1, 1]) + selected = torch.tensor([2, 0, 1]) + only_row_two = torch.tensor([False, False, True]) + # A zero-step startup has no outcome to record, even when success flags contain old values. + rows = sampler.reset(selected, torch.ones(3, dtype=torch.bool), torch.zeros(3, dtype=torch.bool), only_row_two) + assert rows.tolist() == [2, 2, 2] + assert sampler.success_monitor.success_size.tolist() == [0, 0, 0] + sampler.row_ids[selected] = torch.tensor([1, 0, 0]) + sampler.reset(selected, torch.tensor([False, True, False]), row_mask=only_row_two) + assert sampler.row_ids.tolist() == [2, 2, 2, 1] + assert sampler.success_monitor.success_size.tolist() == [2, 1, 0] + assert sampler.success_monitor.success_rate.tolist() == [0.5, 0.0, 0.0] + # Record only one completed episode on the next reset; the masked one contributes nothing. + sampler.reset( + torch.tensor([0, 2]), + torch.tensor([True, False]), + valid=torch.tensor([True, False]), + row_mask=torch.tensor([False, True, False]), + ) + assert sampler.success_monitor.success_size.tolist() == [2, 1, 1] + assert sampler.success_monitor.success_rate.tolist() == [0.5, 0.0, 1.0] + assert sampler.row_ids.tolist() == [1, 2, 1, 1] + sampler.reset(torch.empty(0, dtype=torch.long)) + assert sampler.success_monitor.success_size.tolist() == [2, 1, 1] + assert sampler.row_ids.tolist() == [1, 2, 1, 1] + + +def test_sampling_tracks_the_current_success_frontier_without_starving_other_rows(): + """The sampler observes live rolling outcomes and retains positive weight for easy and hard starts.""" + sampler = ResetStateSampler(ResetStateSamplerCfg(), 3, 3, "cpu") + env_ids = torch.arange(3) + for success in ([False, True, False], [False, True, True]): + sampler.row_ids[:] = env_ids + sampler.reset(env_ids, torch.tensor(success)) + assert sampler.success_monitor.success_rate.tolist() == [0.0, 1.0, 0.5] + assert (sampler.probabilities > 0).all() + torch.testing.assert_close(sampler.probabilities.sum(), torch.tensor(1.0)) + assert sampler.probabilities[2] > sampler.probabilities[0] + assert sampler.probabilities[2] > sampler.probabilities[1] From f3940859c44c95af92917131219a4d7a8992a1aa Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Fri, 6 Nov 2026 23:54:38 +0100 Subject: [PATCH 02/10] Add validated reset buffers and sparse pickup Collect reusable reset-state catalogs with bounded generation and task-defined acceptance checks. Reuse the sampler from #8872 to keep outcome tracking and row selection in one implementation. Add a sparse Franka cube reference with an immediate commanded goal, physical reset generation, and per-environment evaluation quotas. --- .../source/_static/css/environment-browser.js | 1 + docs/source/api/index.rst | 1 + docs/source/api/lab/isaaclab.envs.reset.rst | 21 ++ docs/source/api/lab/isaaclab.envs.rst | 1 + .../api/lab_tasks/isaaclab_tasks.utils.rst | 46 +--- docs/source/how-to/index.rst | 10 + docs/source/how-to/reset_state_buffers.rst | 177 +++++++++++++ scripts/environments/cube_pickup.py | 194 ++++++++++++++ .../changelog.d/reset-state-buffer.added.rst | 2 + .../changelog.d/reset-state-buffer.minor | 0 source/isaaclab/isaaclab/envs/__init__.pyi | 3 +- .../isaaclab/isaaclab/envs/reset/__init__.py | 10 + .../isaaclab/isaaclab/envs/reset/__init__.pyi | 6 + .../isaaclab/envs/reset/reset_state_buffer.py | 225 ++++++++++++++++ .../isaaclab/test/envs/test_reset_states.py | 87 ++++++ .../shared-reset-state-sampling.added.rst | 2 + .../contrib/cube_pickup/README.md | 62 +++++ .../contrib/cube_pickup/__init__.py | 19 ++ .../contrib/cube_pickup/cube_pickup_env.py | 250 ++++++++++++++++++ .../cube_pickup/cube_pickup_env_cfg.py | 229 ++++++++++++++++ .../isaaclab_tasks/contrib/cube_pickup/mdp.py | 84 ++++++ .../contrib/cube_pickup/rsl_rl_ppo_cfg.py | 41 +++ 22 files changed, 1429 insertions(+), 42 deletions(-) create mode 100644 docs/source/api/lab/isaaclab.envs.reset.rst create mode 100644 docs/source/how-to/reset_state_buffers.rst create mode 100644 scripts/environments/cube_pickup.py create mode 100644 source/isaaclab/changelog.d/reset-state-buffer.added.rst create mode 100644 source/isaaclab/changelog.d/reset-state-buffer.minor create mode 100644 source/isaaclab/isaaclab/envs/reset/__init__.py create mode 100644 source/isaaclab/isaaclab/envs/reset/__init__.pyi create mode 100644 source/isaaclab/isaaclab/envs/reset/reset_state_buffer.py create mode 100644 source/isaaclab/test/envs/test_reset_states.py create mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/README.md create mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/__init__.py create mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env.py create mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env_cfg.py create mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/mdp.py create mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/rsl_rl_ppo_cfg.py diff --git a/docs/source/_static/css/environment-browser.js b/docs/source/_static/css/environment-browser.js index 1030255ddaac..3639d5de662a 100644 --- a/docs/source/_static/css/environment-browser.js +++ b/docs/source/_static/css/environment-browser.js @@ -62,6 +62,7 @@ ["IsaacContrib-AutoMate-Disassembly-Direct", "rl_games", "", "", "", "environment-previews/automate_disassembly.jpg"], ["IsaacContrib-Cartpole-Camera-Showcase-Direct", "skrl", "", "", "box_box,box_discrete,box_multidiscrete,dict_box,dict_discrete,dict_multidiscrete,tuple_box,tuple_discrete,tuple_multidiscrete", "", false, {}, {}, "", null, ["||", "||box_box", "||box_discrete", "||box_multidiscrete", "||dict_box", "||dict_discrete", "||dict_multidiscrete", "||tuple_box", "||tuple_discrete", "||tuple_multidiscrete"]], ["IsaacContrib-Cartpole-Showcase-Direct", "skrl", "isaacsim_physx,newton_kamino,newton_mjwarp,ovphysx", "", "box_box,box_discrete,box_multidiscrete,dict_box,dict_discrete,dict_multidiscrete,discrete_box,discrete_discrete,discrete_multidiscrete,multidiscrete_box,multidiscrete_discrete,multidiscrete_multidiscrete,tuple_box,tuple_discrete,tuple_multidiscrete", "environment-previews/cartpole.jpg", false, {}, {}, "", null, ["||", "||box_box", "||box_discrete", "||box_multidiscrete", "||dict_box", "||dict_discrete", "||dict_multidiscrete", "||discrete_box", "||discrete_discrete", "||discrete_multidiscrete", "||multidiscrete_box", "||multidiscrete_discrete", "||multidiscrete_multidiscrete", "||tuple_box", "||tuple_discrete", "||tuple_multidiscrete", "isaacsim_physx||", "isaacsim_physx||box_box", "isaacsim_physx||box_discrete", "isaacsim_physx||box_multidiscrete", "isaacsim_physx||dict_box", "isaacsim_physx||dict_discrete", "isaacsim_physx||dict_multidiscrete", "isaacsim_physx||discrete_box", "isaacsim_physx||discrete_discrete", "isaacsim_physx||discrete_multidiscrete", "isaacsim_physx||multidiscrete_box", "isaacsim_physx||multidiscrete_discrete", "isaacsim_physx||multidiscrete_multidiscrete", "isaacsim_physx||tuple_box", "isaacsim_physx||tuple_discrete", "isaacsim_physx||tuple_multidiscrete", "newton_kamino||", "newton_kamino||box_box", "newton_kamino||box_discrete", "newton_kamino||box_multidiscrete", "newton_kamino||dict_box", "newton_kamino||dict_discrete", "newton_kamino||dict_multidiscrete", "newton_kamino||discrete_box", "newton_kamino||discrete_discrete", "newton_kamino||discrete_multidiscrete", "newton_kamino||multidiscrete_box", "newton_kamino||multidiscrete_discrete", "newton_kamino||multidiscrete_multidiscrete", "newton_kamino||tuple_box", "newton_kamino||tuple_discrete", "newton_kamino||tuple_multidiscrete", "newton_mjwarp||", "newton_mjwarp||box_box", "newton_mjwarp||box_discrete", "newton_mjwarp||box_multidiscrete", "newton_mjwarp||dict_box", "newton_mjwarp||dict_discrete", "newton_mjwarp||dict_multidiscrete", "newton_mjwarp||discrete_box", "newton_mjwarp||discrete_discrete", "newton_mjwarp||discrete_multidiscrete", "newton_mjwarp||multidiscrete_box", "newton_mjwarp||multidiscrete_discrete", "newton_mjwarp||multidiscrete_multidiscrete", "newton_mjwarp||tuple_box", "newton_mjwarp||tuple_discrete", "newton_mjwarp||tuple_multidiscrete", "ovphysx||", "ovphysx||box_box", "ovphysx||box_discrete", "ovphysx||box_multidiscrete", "ovphysx||dict_box", "ovphysx||dict_discrete", "ovphysx||dict_multidiscrete", "ovphysx||discrete_box", "ovphysx||discrete_discrete", "ovphysx||discrete_multidiscrete", "ovphysx||multidiscrete_box", "ovphysx||multidiscrete_discrete", "ovphysx||multidiscrete_multidiscrete", "ovphysx||tuple_box", "ovphysx||tuple_discrete", "ovphysx||tuple_multidiscrete"]], + ["IsaacContrib-Cube-Pickup-Franka", "rsl_rl", "newton_mjwarp", "", "", "", false, {}, {}, "", null, ["||", "newton_mjwarp||"]], ["IsaacContrib-Deploy-GearAssembly-Rizon4s-Grav", "rsl_rl", "", "", "", "environment-previews/rizon4s_gear_assembly.jpg"], ["IsaacContrib-Deploy-GearAssembly-Rizon4s-Grav-ROS-Inference", "rsl_rl", "", "", "", "environment-previews/rizon4s_gear_assembly.jpg"], ["IsaacContrib-Deploy-GearAssembly-UR10e-2F140", "rsl_rl", "", "", "", "environment-previews/ur10e_2f140_gear_assembly.jpg"], diff --git a/docs/source/api/index.rst b/docs/source/api/index.rst index 5ce509f53cff..fa5a26a6857f 100644 --- a/docs/source/api/index.rst +++ b/docs/source/api/index.rst @@ -37,6 +37,7 @@ The following modules are available in the ``isaaclab`` extension: :hidden: lab/isaaclab.envs.mdp + lab/isaaclab.envs.reset lab/isaaclab.envs.ui lab/isaaclab.sensors.patterns lab/isaaclab.sim.converters diff --git a/docs/source/api/lab/isaaclab.envs.reset.rst b/docs/source/api/lab/isaaclab.envs.reset.rst new file mode 100644 index 000000000000..1df45c46c592 --- /dev/null +++ b/docs/source/api/lab/isaaclab.envs.reset.rst @@ -0,0 +1,21 @@ +isaaclab.envs.reset +=================== + +.. automodule:: isaaclab.envs.reset + +.. currentmodule:: isaaclab.envs.reset + +.. autosummary:: + + ResetStateBuffer + ResetStateBufferCfg + +See :doc:`/source/how-to/reset_state_buffers` for collection, validation, replay, +and the sparse-reward cube pickup example. + +.. autoclass:: ResetStateBufferCfg + :members: + :exclude-members: __init__ + +.. autoclass:: ResetStateBuffer + :members: diff --git a/docs/source/api/lab/isaaclab.envs.rst b/docs/source/api/lab/isaaclab.envs.rst index b4e26d71a76e..3402b961a713 100644 --- a/docs/source/api/lab/isaaclab.envs.rst +++ b/docs/source/api/lab/isaaclab.envs.rst @@ -8,6 +8,7 @@ .. autosummary:: mdp + reset ui .. rubric:: Classes diff --git a/docs/source/api/lab_tasks/isaaclab_tasks.utils.rst b/docs/source/api/lab_tasks/isaaclab_tasks.utils.rst index 8a906c2707c4..544acdb6bc9b 100644 --- a/docs/source/api/lab_tasks/isaaclab_tasks.utils.rst +++ b/docs/source/api/lab_tasks/isaaclab_tasks.utils.rst @@ -8,48 +8,12 @@ Reset-state sampling -------------------- -:class:`~isaaclab_tasks.utils.ResetStateSampler` shares success-guided sampling between -tasks without prescribing their geometry or state representation. A task creates a fixed -catalog of valid starts, and the sampler assigns one catalog row to each environment. -The configured :class:`~isaaclab_tasks.utils.SuccessMonitor` records recent episode outcomes -for each row. The default Beta and uniform mixture favors starts with intermediate success -while keeping every row eligible. +:class:`~isaaclab_tasks.utils.ResetStateSampler` assigns reset rows using recent +episode outcomes tracked by :class:`~isaaclab_tasks.utils.SuccessMonitor`. Its +configurable sampling strategies support cached or procedural state catalogs. -Generate and validate the catalog once when the environment starts. Procedural tasks can -store joint poses, object poses, and command metadata in device tensors indexed by row. -For cached simulation states, use -:meth:`~isaaclab.scene.InteractiveScene.get_state` with ``is_relative=True`` and restore -selected rows through :meth:`~isaaclab.scene.InteractiveScene.reset_to` with the same flag. -This preserves environment-relative positions and the public scene state format; no custom -asset serializer or private scene registries are needed. Catalog generation, acceptance -checks, and optional persistence remain task responsibilities. - -Construct the sampler once, then select rows before resetting the physical scene: - -.. code-block:: python - - from isaaclab_tasks.utils import ResetStateSampler, ResetStateSamplerCfg - - reset_sampler = ResetStateSampler(ResetStateSamplerCfg(), num_envs, row_count, device) - - # In the task's reset event, before clearing its previous success flags: - rows = reset_sampler.reset( - env_ids, - success=episode_success[env_ids], - valid=episode_length[env_ids] > 0, - ) - # Restore physical state and command metadata indexed by rows using public asset APIs. - -``success`` and ``valid`` contain one value per selected environment. Omit ``success`` for -the initial draw, or use ``valid`` to exclude zero-step manual resets. An optional ``row_mask`` -restricts the next draw without changing which completed episodes are credited. Outcomes -always belong to the previous assignments, and a partial reset preserves other environments' -assignments. Task code must also clear commands, action targets, and attachment state that -are not represented in its physical state bank. - -Keep evaluation starts fixed or uniformly sampled, and report success from complete task -starts separately from the adaptive training mixture. Sampling history belongs to the live -environment; ordinary policy checkpoints do not save it. +See :doc:`/source/how-to/reset_state_buffers` for buffer creation, validation, +physical replay, outcome attribution, and evaluation from complete task starts. Sampling strategies ------------------- diff --git a/docs/source/how-to/index.rst b/docs/source/how-to/index.rst index fa71e2db08c2..d1afe9950070 100644 --- a/docs/source/how-to/index.rst +++ b/docs/source/how-to/index.rst @@ -204,6 +204,16 @@ How-to Guides .. rubric:: Environments and Training + .. container:: guide-entry + + :doc:`Building validated reset-state buffers ` + + Collect valid starting states and sample useful practice for sparse-reward tasks. + + .. container:: guide-metadata + + :guide-tag:`PhysX` :guide-tag-newton:`Newton` + .. container:: guide-entry :doc:`Creating a manager-based base environment ` diff --git a/docs/source/how-to/reset_state_buffers.rst b/docs/source/how-to/reset_state_buffers.rst new file mode 100644 index 000000000000..736bb56eec67 --- /dev/null +++ b/docs/source/how-to/reset_state_buffers.rst @@ -0,0 +1,177 @@ +:orphan: + +Building validated reset-state buffers +====================================== + +A reset-state buffer collects valid starting conditions once and reuses them +during training. Expensive inverse kinematics, scripted grasps, and settling can +then run during collection rather than on every episode reset. + +:mod:`isaaclab.envs.reset` separates collection from sampling and physical +restoration. The buffer stores a nested dictionary of tensors with one leading +row per start. The task decides which physical state and metadata those tensors +represent. The same utilities work with manager-based and Direct environments. + +Collect starts +-------------- + +Use :class:`~isaaclab.envs.reset.ResetStateBufferCfg` to configure the buffer size, +collection budget, and seed. Supply ordinary callbacks for generation, capture, +and named acceptance checks: + +.. code-block:: python + + from isaaclab.envs.reset import ResetStateBuffer, ResetStateBufferCfg + + buffer = ResetStateBuffer(ResetStateBufferCfg(size=4096, max_batches=100, seed=42)) + buffer.collect( + env_ids, + generate={"table": generate_table_starts, "grasped": generate_grasped_starts}, + capture=capture_reset_state, + checks={"joint_limits": check_joint_limits, "stable": check_stability}, + ) + +Each generator receives the selected environment indices, places the candidates, +and can return a Boolean validity mask. Named checks also return one Boolean per +candidate. Generation must synchronize the scene before checks read derived body +poses or contacts. Capture returns tensors for the accepted environments in the +order supplied to the callback. + +A single generator is sufficient for ordinary randomized starts. Named generators +collect balanced groups, which prevents an easily generated reset category from +filling the entire buffer. When the collection budget is exhausted, construction +fails with the number of accepted starts and rejected checks instead of waiting +indefinitely. + +Run collection during controlled initialization or in an offline script. A +generator that advances physics also advances other worlds in the simulation. +It must not run while unrelated training episodes are in progress. Reset the +environment normally after collection before starting the policy. + +Validate the intended start +--------------------------- + +Acceptance rules belong to the task. Useful checks include finite state, joint +limits, workspace bounds, successful IK, allowed contacts, and a brief grasp or +settling check. A valid grasp may intentionally contain contact; rejecting all +contact is not an appropriate general default. + +Validate restored starts as well as generated starts. Restoring poses can rebuild +contacts and controller targets differently from the original rollout. A short +replay test should check that the restored start remains usable and that it does +not already satisfy the task's success condition. + +The buffer does not certify solver compatibility. In particular, constrained +Kamino mechanisms must use the backend's normal constraint-consistent reset and +forward-kinematics path. Task callbacks can check the resulting state without +putting solver internals into the buffer implementation. + +Sample and restore +------------------ + +:class:`~isaaclab_tasks.utils.ResetStateSampler` tracks the starting row assigned +to each parallel environment and learns a rolling success rate for each row. +Its default favors starts near 50 percent success and retains uniform exploration. +This targets useful practice rather than enforcing a fixed overall success rate. + +.. code-block:: python + + from isaaclab_tasks.utils import ResetStateSampler, ResetStateSamplerCfg + + sampler = ResetStateSampler( + ResetStateSamplerCfg(), num_envs, buffer.num_states, device + ) + rows = sampler.reset( + env_ids, + success=episode_success[env_ids], + valid=completed_episode[env_ids], + ) + state = buffer.get_state(rows) + # Restore the task's physical state and associated metadata here. + +Record outcomes before clearing the previous episode's success flags. Omit +outcomes for the initial draw and mask manual or zero-step resets. Only resetting +environments receive new row assignments. + +The sampler reuses the shared success monitor and sampling strategies from +:mod:`isaaclab_tasks.utils.sampling`. For a uniform baseline, configure the existing +uniform strategy: + +.. code-block:: python + + from isaaclab_tasks.utils.sampling import SamplerCfg, UniformSamplingStrategyCfg + + uniform_cfg = ResetStateSamplerCfg( + sampling=SamplerCfg(strategies=[UniformSamplingStrategyCfg()], eps=0.0) + ) + +For physical scene states, reuse +:meth:`~isaaclab.scene.InteractiveScene.get_state` and +:meth:`~isaaclab.scene.InteractiveScene.reset_to`, with ``is_relative=True`` on +both sides. Capture callbacks must select the requested rows from the scene +state. Task-specific tensor recipes can instead use the public asset writers. +Keep positions relative to environment origins so starts transfer between worlds. + +Scene state is not a complete environment checkpoint. Restore commands, action +targets, attachment state, and other task metadata through the appropriate task +reset hooks. Account for the existing manager reset order: values restored by an +event can be overwritten by subsequent command or action manager resets. Solver +caches should be cleared through the backend reset lifecycle. + +Using existing task reset data +---------------------------------------- + +The buffer accepts task-specific tensor trees rather than prescribing a new asset +serializer. Existing reset workflows can therefore adopt collection independently +of their scene geometry and state representation: + +* Conveyor recipes can store robot poses, parcel layouts, and transfer metadata. +* Stacking can generate starts along a scripted approach, grasp, and placement. +* NIST can retain its collision checks and explicitly capture assembly variant IDs. +* Franka Pour can retain dataset compatibility checks and particle-layout IDs; + large particle layouts can remain separate from the per-row recipe tensors. + +These integrations do not change existing public task registrations or stored +dataset formats. Selecting rows and validating an artifact's compatibility are +different responsibilities from constructing physically valid starts. + +Evaluate complete task starts +---------------------------------------- + +Use the cube pickup reference to compare sparse-reward training with ordinary and +buffered starts. Generate grasp starts by physically approaching and closing the +fingers. Starts captured after grasping must remain outside the goal region. +The example succeeds as soon as a grasped cube reaches the commanded +point ``(0.5, 0.0, 0.15)`` [m] in environment coordinates, within a radius of +``0.04`` [m]. The reward is a terminal ``+1`` on that transition. + +The registered ``IsaacContrib-Cube-Pickup-Franka`` task collects table, approach, +pregrasp, and physical grasp starts. It uses relative Cartesian actions and a +binary pickup-to-point reward. Generate and inspect a small buffer first: + +.. code-block:: bash + + uv run python scripts/environments/cube_pickup.py --mode generate \ + --num_envs 64 --bank_size 256 --headless --output outputs/pickup/reset_states.json + +Train with the existing RSL-RL runner. ``--num_envs`` is the number of environments +per GPU in distributed training: + +.. code-block:: bash + + uv run isaaclab train_multigpu --num_gpus 4 --rl_library rsl_rl \ + --task IsaacContrib-Cube-Pickup-Franka --num_envs 1024 --headless + +The task saves its generated reset states alongside the training logs. Evaluate a +saved checkpoint from ordinary table starts using a separate seed: + +.. code-block:: bash + + uv run python scripts/environments/cube_pickup.py --mode evaluate \ + --checkpoint /path/to/model.pt --num_envs 64 --episodes 512 \ + --seed 10000 --headless --output outputs/pickup/evaluation.json + +Evaluate the learned policy separately from ordinary table starts using held-out +positions and seeds. Report that result separately from success under the adaptive +training mixture. Success on already-grasped starts alone does not establish that +the policy learned to pick up the cube from the table. diff --git a/scripts/environments/cube_pickup.py b/scripts/environments/cube_pickup.py new file mode 100644 index 000000000000..36cf6b939f20 --- /dev/null +++ b/scripts/environments/cube_pickup.py @@ -0,0 +1,194 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Generate reset states, prove scripted pickup, or evaluate sparse pickup from ordinary table starts. + +Train through the standard runner:: + + uv run isaaclab train --rl_library rsl_rl --task IsaacContrib-Cube-Pickup-Franka --num_envs 1024 + +Evaluate a trained policy from home with held-out cube positions:: + + uv run python scripts/environments/cube_pickup.py --mode evaluate --checkpoint model.pt \ + --num_envs 64 --episodes 512 --seed 10000 --output evaluation.json +""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import gymnasium as gym +import torch + +from isaaclab.app import add_launcher_args, launch_simulation +from isaaclab.utils import to_dict + +import isaaclab_tasks # noqa: F401 +from isaaclab_tasks.contrib.cube_pickup import mdp +from isaaclab_tasks.utils import resolve_task_config + +TASK_NAME = "IsaacContrib-Cube-Pickup-Franka" + + +def main() -> None: + """Run the bounded generation, scripted-control, or policy-evaluation probe.""" + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--mode", choices=("generate", "scripted", "evaluate"), required=True) + parser.add_argument("--num_envs", type=int, default=64) + parser.add_argument("--bank_size", type=int, default=256) + parser.add_argument("--bank_output", type=Path) + parser.add_argument("--checkpoint", type=Path) + parser.add_argument("--episodes", type=int, default=512) + parser.add_argument("--steps", type=int, default=3000) + parser.add_argument("--seed", type=int, default=10000) + parser.add_argument("--output", type=Path, required=True) + add_launcher_args(parser) + args, overrides = parser.parse_known_args() + if args.mode == "evaluate" and args.checkpoint is None: + parser.error("--checkpoint is required for policy evaluation") + if min(args.num_envs, args.bank_size, args.episodes, args.steps) < 1: + parser.error("environment, bank, episode and step counts must be positive") + + cfg, agent_cfg = resolve_task_config(TASK_NAME, "rsl_rl_cfg_entry_point", overrides=overrides) + cfg.scene.num_envs = args.num_envs + cfg.seed = args.seed + cfg.reset_buffer.size = args.bank_size + cfg.reset_buffer.seed = args.seed + cfg.reset_mode = "adaptive" if args.mode == "generate" else "table" + if args.device: + cfg.sim.device = args.device + args.output.parent.mkdir(parents=True, exist_ok=True) + with launch_simulation(cfg, args): + env = gym.make(TASK_NAME, cfg=cfg) + try: + task = env.unwrapped + if args.mode == "generate": + validation = _validate_replay(env) + bank_path = args.bank_output or args.output.with_suffix(".pt") + task.save_reset_buffer(bank_path) + report = {**task.generation_report, "bank_path": str(bank_path), "replay_validation": validation} + else: + report = _rollout(env, agent_cfg, args) + args.output.write_text(json.dumps(report, indent=2) + "\n") + print(json.dumps(report, indent=2)) + if args.mode != "generate": + if not report["all_finite"] or report["completed_episodes"] < args.episodes: + raise RuntimeError( + "The rollout did not finish the requested finite episodes; see the output report." + ) + if args.mode == "scripted" and report["success_rate"] < 0.9: + raise RuntimeError( + "Scripted pickup succeeded on fewer than 90 percent of episodes; see the report." + ) + finally: + env.close() + + +def _validate_replay(env: gym.Env) -> dict[str, bool]: + """Exercise actual partial bank replay, including isolation and post-reset steps.""" + task = env.unwrapped + observations, _ = env.reset() + if not torch.isfinite(observations["policy"]).all(): + raise RuntimeError("Reset produced non-finite observations.") + success_cfg = task.termination_manager.get_term_cfg("success") + if success_cfg.func(task, **success_cfg.params).any(): + raise RuntimeError("A reset state already satisfies the grasped-cube goal.") + before = task.scene.get_state(is_relative=True) + split = max(1, task.num_envs // 2) + task._reset_idx(torch.arange(split, device=task.device)) + if success_cfg.func(task, **success_cfg.params).any(): + raise RuntimeError("Partial replay produced an already successful reset state.") + after = task.scene.get_state(is_relative=True) + for kind, assets in before.items(): + for name, fields in assets.items(): + for field, value in fields.items(): + torch.testing.assert_close(value[split:], after[kind][name][field][split:], rtol=1.0e-5, atol=1.0e-6) + for _ in range(5): + observations, reward, _, _, _ = env.step(torch.zeros((task.num_envs, 7), device=task.device)) + if not torch.isfinite(observations["policy"]).all() or not torch.isfinite(reward).all(): + raise RuntimeError("Bank replay produced non-finite observations or rewards after stepping.") + return {"finite_reset_and_steps": True, "partial_reset_isolated": True, "no_initial_success": True} + + +def _rollout(env: gym.Env, agent_cfg, args: argparse.Namespace) -> dict: + """Count completed full-start attempts without using the reset bank.""" + task = env.unwrapped + if args.mode == "evaluate": + from rsl_rl.runners import OnPolicyRunner + + from isaaclab_rl.rsl_rl import RslRlVecEnvWrapper + + wrapped = RslRlVecEnvWrapper(env, clip_actions=agent_cfg.clip_actions) + agent_cfg.device = task.device + runner = OnPolicyRunner(wrapped, to_dict(agent_cfg), log_dir=None, device=task.device) + runner.load(str(args.checkpoint)) + policy = runner.get_inference_policy(device=task.device) + observations = wrapped.get_observations() + else: + env.reset() + + elapsed = torch.zeros(task.num_envs, device=task.device) + cube_start = mdp.object_position(task).clone() + orientation = task._tcp_pose()[:, 3:].clone() + orientation[:] = orientation.new_tensor((1.0, 0.0, 0.0, 0.0)) + completed = 0 + successes = 0 + remaining = torch.full((task.num_envs,), args.episodes // task.num_envs, dtype=torch.long, device=task.device) + remaining[: args.episodes % task.num_envs] += 1 + finite = True + maximum_height = 0.0 + with torch.inference_mode(): + for step in range(args.steps): + if args.mode == "evaluate": + observations, reward, done, _ = wrapped.step(policy(observations)) + done = done.bool() + policy.reset(done) + finite &= bool(torch.isfinite(observations["policy"]).all().item()) + else: + target = torch.cat((cube_start, orientation), dim=-1) + target[:, 2] += torch.where(elapsed < 5.0, 0.10, 0.0) + goal = task.command_manager.get_command("object_pose")[:, :3] + target[:, :3] = torch.where((elapsed >= 7.6)[:, None], goal, target[:, :3]) + action = task.scripted_action(target, close=False) + action[:, 6] = torch.where(elapsed >= 7.0, -1.0, 1.0) + observations, reward, terminated, truncated, _ = env.step(action) + done = terminated | truncated + finite &= bool(torch.isfinite(observations["policy"]).all().item()) + + # Same-step auto-reset restores the cube before this read. The successful terminal + # transition is counted from its binary reward, never from a post-reset observation. + finite &= bool(torch.isfinite(reward).all().item()) + counted = done & (remaining > 0) + completed += int(counted.sum().item()) + successes += int(((reward > 0.5) & counted).sum().item()) + remaining[counted] -= 1 + maximum_height = max(maximum_height, float(mdp.object_position(task)[:, 2].max().item())) + elapsed += task.step_dt + elapsed[done] = 0.0 + cube_start[done] = mdp.object_position(task)[done] + if not remaining.any() or not finite: + break + return { + "mode": args.mode, + "task": TASK_NAME, + "checkpoint": str(args.checkpoint) if args.checkpoint else None, + "seed": args.seed, + "reset_mode": "table", + "goal_position_robot_frame_m": task.command_manager.get_command("object_pose")[0, :3].tolist(), + "goal_threshold_m": task.cfg.terminations.success.params["threshold"], + "num_envs": task.num_envs, + "steps": step + 1, + "completed_episodes": completed, + "successful_episodes": successes, + "success_rate": successes / completed if completed else 0.0, + "all_finite": finite, + "maximum_observed_cube_height_m": maximum_height, + } + + +if __name__ == "__main__": + main() diff --git a/source/isaaclab/changelog.d/reset-state-buffer.added.rst b/source/isaaclab/changelog.d/reset-state-buffer.added.rst new file mode 100644 index 000000000000..aef99a71aff1 --- /dev/null +++ b/source/isaaclab/changelog.d/reset-state-buffer.added.rst @@ -0,0 +1,2 @@ +* Added :class:`~isaaclab.envs.reset.ResetStateBuffer` for collecting validated reset + states with bounded attempts, reproducible generation, and named acceptance checks. diff --git a/source/isaaclab/changelog.d/reset-state-buffer.minor b/source/isaaclab/changelog.d/reset-state-buffer.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab/isaaclab/envs/__init__.pyi b/source/isaaclab/isaaclab/envs/__init__.pyi index ca965881b655..5ed419470c25 100644 --- a/source/isaaclab/isaaclab/envs/__init__.pyi +++ b/source/isaaclab/isaaclab/envs/__init__.pyi @@ -5,6 +5,7 @@ __all__ = [ "mdp", + "reset", "ui", "VecEnvObs", "VecEnvStepReturn", @@ -30,7 +31,7 @@ __all__ = [ "MimicEnvCfg", ] -from . import mdp, ui +from . import mdp, reset, ui from .common import VecEnvObs, VecEnvStepReturn, ViewerCfg from .utils.video_recorder_cfg import VideoRecorderCfg from .direct_marl_env import DirectMARLEnv diff --git a/source/isaaclab/isaaclab/envs/reset/__init__.py b/source/isaaclab/isaaclab/envs/reset/__init__.py new file mode 100644 index 000000000000..822ffbfed39a --- /dev/null +++ b/source/isaaclab/isaaclab/envs/reset/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Utilities for collecting validated reset states.""" + +from ...utils.module import lazy_export + +lazy_export() diff --git a/source/isaaclab/isaaclab/envs/reset/__init__.pyi b/source/isaaclab/isaaclab/envs/reset/__init__.pyi new file mode 100644 index 000000000000..4a717702294a --- /dev/null +++ b/source/isaaclab/isaaclab/envs/reset/__init__.pyi @@ -0,0 +1,6 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from .reset_state_buffer import ResetStateBuffer, ResetStateBufferCfg diff --git a/source/isaaclab/isaaclab/envs/reset/reset_state_buffer.py b/source/isaaclab/isaaclab/envs/reset/reset_state_buffer.py new file mode 100644 index 000000000000..47494ade3097 --- /dev/null +++ b/source/isaaclab/isaaclab/envs/reset/reset_state_buffer.py @@ -0,0 +1,225 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Build a fixed buffer of accepted states using ordinary task callbacks.""" + +from __future__ import annotations + +import random +from collections.abc import Callable, Mapping +from typing import TypeAlias + +import numpy as np +import torch + +from isaaclab.utils import configclass + + +@configclass +class ResetStateBufferCfg: + """Configuration for bounded reset-state collection.""" + + size: int = 4096 + """Number of accepted states to collect, shared approximately equally across named generators.""" + + max_batches: int = 100 + """Maximum candidate batches per generator before collection fails.""" + + seed: int = 0 + """Collection seed. The caller's Torch, NumPy, and Python random states are restored afterward.""" + + +class ResetStateBuffer: + """Collect accepted task states independently of their sampling or application. + + The state representation is a nested dictionary of tensors with a leading row dimension, + compatible with :meth:`isaaclab.scene.InteractiveScene.get_state`. Physical units follow + the state fields supplied by the task. Capture scene states relative to environment origins + when the same buffer will be shared across environments. + + Generation and validation run only during :meth:`collect`. They may use simulation to + establish grasps or settle objects. At runtime, :meth:`get_state` only indexes stored tensors; + the task restores them through its existing scene and controller APIs. + + Args: + cfg: Collection size, attempt limit, and seed. + """ + + State: TypeAlias = dict[str, "torch.Tensor | ResetStateBuffer.State"] + + def __init__(self, cfg: ResetStateBufferCfg) -> None: + if any(type(value) is not int or value < 1 for value in (cfg.size, cfg.max_batches)): + raise ValueError("size and max_batches must be positive integers.") + if type(cfg.seed) is not int or not 0 <= cfg.seed < 2**32: + raise ValueError("seed must be an integer in [0, 2**32).") + self.cfg = cfg + self.state: ResetStateBuffer.State = {} + """Collected tensor tree. Treat its tensors as read-only.""" + self.group_names: tuple[str, ...] = () + """Generator names, in collection order.""" + self.group_ids = torch.empty(0, dtype=torch.long) + """Generator index for every stored row, shape [num_states].""" + self.rejection_counts: dict[str, int] = {} + """Rejected candidates per named condition; one candidate can fail several conditions.""" + self.collection_report: dict[str, dict[str, int]] = {} + """Attempted, accepted, and rejected candidate counts for each generator.""" + + @property + def num_states(self) -> int: + """Number of collected states.""" + return self.group_ids.numel() + + def collect( + self, + env_ids: torch.Tensor, + generate: Callable[[torch.Tensor], torch.Tensor | None] + | Mapping[str, Callable[[torch.Tensor], torch.Tensor | None]], + capture: Callable[[torch.Tensor], ResetStateBuffer.State], + checks: Mapping[str, Callable[[torch.Tensor], torch.Tensor]] | None = None, + ) -> None: + """Generate, check, and capture a complete buffer before training starts. + + Each generator receives all candidate environment indices on every attempt. Its optional + boolean return mask reports failed construction, such as an unsuccessful IK solve. Named + checks return additional acceptance masks. Only candidates passing every condition are + captured. Named generators receive equal quotas, differing by at most one row. + + The callbacks own simulation synchronization and any settling; collection does not step + the simulation or advance the environment's episode bookkeeping itself. + + Args: + env_ids: Candidate environment indices, shape [N], on the simulation device. + generate: A generator callback or a non-empty mapping of generator names to callbacks. + The optional returned mask has shape [N]. + capture: Callback returning a tensor tree with one leading row per supplied index. + checks: Named validity callbacks returning boolean tensors of shape [N]. The name + ``generator`` is reserved for the generator's own validity mask. + + Raises: + RuntimeError: A generator cannot fill its quota within :attr:`ResetStateBufferCfg.max_batches`. + ValueError: There are no candidate environments, or the buffer cannot cover every group. + """ + generators = dict(generate) if isinstance(generate, Mapping) else {"default": generate} + if env_ids.numel() == 0 or not generators or self.cfg.size < len(generators): + raise ValueError("Collection needs candidate environments and at least one buffer row per generator.") + checks = checks or {} + if "generator" in checks: + raise ValueError("The check name 'generator' is reserved for generator validity.") + batches: list[ResetStateBuffer.State] = [] + groups: list[torch.Tensor] = [] + self.rejection_counts = {} + self.collection_report = {} + devices = [env_ids.device.index] if env_ids.is_cuda else [] + numpy_state, python_state = np.random.get_state(), random.getstate() + try: + with torch.random.fork_rng(devices=devices): + torch.random.default_generator.manual_seed(self.cfg.seed) + if env_ids.is_cuda: + with torch.cuda.device(env_ids.device): + torch.cuda.manual_seed(self.cfg.seed) + np.random.seed(self.cfg.seed) + random.seed(self.cfg.seed) + for group, (name, generator) in enumerate(generators.items()): + quota = self.cfg.size // len(generators) + int(group < self.cfg.size % len(generators)) + accepted = 0 + report = self.collection_report[name] = {"attempted": 0, "accepted": 0} + for _ in range(self.cfg.max_batches): + report["attempted"] += env_ids.numel() + reported = generator(env_ids) + masks = {"generator": reported} if reported is not None else {} + masks.update({key: check(env_ids) for key, check in checks.items()}) + valid = torch.ones_like(env_ids, dtype=torch.bool) + for key, mask in masks.items(): + if mask.shape != env_ids.shape or mask.dtype != torch.bool: + raise ValueError( + f"{name}/{key} must return a boolean mask shaped {tuple(env_ids.shape)}." + ) + rejected = int((~mask).sum()) + self.rejection_counts[f"{name}/{key}"] = ( + self.rejection_counts.get(f"{name}/{key}", 0) + rejected + ) + report[f"rejected/{key}"] = report.get(f"rejected/{key}", 0) + rejected + valid &= mask + selected = env_ids[valid][: quota - accepted] + if selected.numel(): + captured = capture(selected) + if not _validate_state(captured, selected.numel(), batches[0] if batches else None): + raise ValueError("capture must return a non-empty tree of batched tensors.") + state = _map_state(captured, lambda value: value.detach().clone()) + batches.append(state) + groups.append(torch.full_like(selected, group)) + accepted += selected.numel() + report["accepted"] = accepted + if accepted == quota: + break + if accepted < quota: + raise RuntimeError( + f"Reset group '{name}' collected {accepted}/{quota} states after " + f"{self.cfg.max_batches} batches. Rejections: {self.rejection_counts}" + ) + finally: + np.random.set_state(numpy_state) + random.setstate(python_state) + self.state = _concatenate_states(batches) + self.group_ids = torch.cat(groups).long() + self.group_names = tuple(generators) + + def get_state(self, row_ids: torch.Tensor) -> ResetStateBuffer.State: + """Return the selected rows of the captured state tree. + + Args: + row_ids: Buffer row indices, shape [N], on the buffer device. + + Returns: + Tensor tree with a leading dimension of N and the captured fields' units. + """ + return _map_state(self.state, lambda value: value[row_ids]) + + +def _validate_state( + state: ResetStateBuffer.State, + rows: int, + reference: ResetStateBuffer.State | None = None, + path: str = "", +) -> int: + if not isinstance(state, dict) or reference is not None and state.keys() != reference.keys(): + raise ValueError(f"Captured state structure changed at '{path}'.") + leaves = 0 + for name, value in state.items(): + key = f"{path}/{name}" + expected = reference[name] if reference is not None else None + if isinstance(value, dict): + if expected is not None and not isinstance(expected, dict): + raise ValueError(f"Captured state structure changed at '{key}'.") + leaves += _validate_state(value, rows, expected, key) + else: + if not isinstance(value, torch.Tensor) or value.ndim < 1 or value.shape[0] != rows: + raise ValueError(f"Captured state '{key}' needs a leading dimension of {rows}.") + if expected is not None and ( + not isinstance(expected, torch.Tensor) + or (value.shape[1:], value.dtype, value.device) != (expected.shape[1:], expected.dtype, expected.device) + ): + raise ValueError(f"Captured tensor shape, dtype, or device changed at '{key}'.") + leaves += 1 + return leaves + + +def _map_state( + state: ResetStateBuffer.State, function: Callable[[torch.Tensor], torch.Tensor] +) -> ResetStateBuffer.State: + return { + key: _map_state(value, function) if isinstance(value, dict) else function(value) for key, value in state.items() + } + + +def _concatenate_states(states: list[ResetStateBuffer.State]) -> ResetStateBuffer.State: + return { + key: ( + _concatenate_states([state[key] for state in states]) + if isinstance(value, dict) + else torch.cat([state[key] for state in states]) + ) + for key, value in states[0].items() + } diff --git a/source/isaaclab/test/envs/test_reset_states.py b/source/isaaclab/test/envs/test_reset_states.py new file mode 100644 index 000000000000..7b79b7eb6a7d --- /dev/null +++ b/source/isaaclab/test/envs/test_reset_states.py @@ -0,0 +1,87 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Collection validity, reproducibility, and tensor-state consistency at the public API.""" + +import random + +import numpy as np +import pytest +import torch + +from isaaclab.envs.reset import ResetStateBuffer, ResetStateBufferCfg + +pytestmark = [pytest.mark.unit, pytest.mark.kitless, pytest.mark.windows_ci] + + +def test_collection_rejects_candidates_covers_groups_and_preserves_rng(): + values = torch.empty(4, 2) + env_ids = torch.arange(4) + + def generate(ids, sign): + values[ids, 0] = sign * (1.0 + torch.rand(len(ids))) + values[ids, 1] = torch.from_numpy(np.random.random(len(ids))).float() + random.random() + return ids != 0 + + def capture(ids): + return {"rigid_object": {"cube": {"root_pose": values[ids]}}} + + generators = {"table": lambda ids: generate(ids, 1), "grasped": lambda ids: generate(ids, -1)} + checks = {"reachable": lambda ids: ids != 3} + torch_state, numpy_state, python_state = torch.get_rng_state(), np.random.get_state(), random.getstate() + buffer = ResetStateBuffer(ResetStateBufferCfg(size=7, max_batches=2, seed=17)) + buffer.collect(env_ids, generators, capture, checks) + assert buffer.num_states == 7 + assert buffer.group_names == ("table", "grasped") + assert buffer.group_ids.tolist() == [0, 0, 0, 0, 1, 1, 1] + assert buffer.collection_report == { + "table": {"attempted": 8, "accepted": 4, "rejected/generator": 2, "rejected/reachable": 2}, + "grasped": {"attempted": 8, "accepted": 3, "rejected/generator": 2, "rejected/reachable": 2}, + } + selected = buffer.get_state(torch.tensor([6, 0, 4]))["rigid_object"]["cube"]["root_pose"] + assert (selected[:, 0] * torch.tensor([-1, 1, -1]) > 1.0).all() + torch.testing.assert_close(torch.get_rng_state(), torch_state) + np.testing.assert_equal(np.random.get_state(), numpy_state) + assert random.getstate() == python_state + repeated = ResetStateBuffer(buffer.cfg) + repeated.collect(env_ids, generators, capture, checks) + torch.testing.assert_close( + repeated.state["rigid_object"]["cube"]["root_pose"], buffer.state["rigid_object"]["cube"]["root_pose"] + ) + + +def test_impossible_validation_is_bounded_and_reports_the_condition(): + buffer = ResetStateBuffer(ResetStateBufferCfg(size=5, max_batches=2)) + with pytest.raises(RuntimeError, match="collected 0/5 states after 2 batches.*collision_free"): + buffer.collect( + torch.arange(3), + lambda ids: None, + lambda ids: {"pose": torch.zeros(len(ids), 7)}, + {"collision_free": lambda ids: torch.zeros_like(ids, dtype=torch.bool)}, + ) + assert buffer.num_states == 0 + assert buffer.rejection_counts == {"default/collision_free": 6} + with pytest.raises(ValueError, match="'generator' is reserved"): + buffer.collect( + torch.arange(3), + lambda ids: torch.zeros_like(ids, dtype=torch.bool), + lambda ids: {"pose": torch.zeros(len(ids), 7)}, + {"generator": lambda ids: torch.ones_like(ids, dtype=torch.bool)}, + ) + + +def test_capture_requires_selected_rows_and_a_consistent_state_tree(): + buffer = ResetStateBuffer(ResetStateBufferCfg(size=3, max_batches=2)) + with pytest.raises(ValueError, match="leading dimension of 2"): + buffer.collect(torch.arange(3), lambda ids: ids > 0, lambda ids: {"pose": torch.zeros(3, 7)}) + calls = 0 + + def capture(ids): + nonlocal calls + calls += 1 + return {"pose": torch.zeros(len(ids), 7 if calls == 1 else 6)} + + with pytest.raises(ValueError, match="shape, dtype, or device changed"): + buffer.collect(torch.arange(2), lambda ids: None, capture) diff --git a/source/isaaclab_tasks/changelog.d/shared-reset-state-sampling.added.rst b/source/isaaclab_tasks/changelog.d/shared-reset-state-sampling.added.rst index a5e335969ddf..45b50bac3159 100644 --- a/source/isaaclab_tasks/changelog.d/shared-reset-state-sampling.added.rst +++ b/source/isaaclab_tasks/changelog.d/shared-reset-state-sampling.added.rst @@ -2,3 +2,5 @@ bookkeeping between cached and procedural reset catalogs, using the existing success monitor. * Moved reusable weighted sampling strategies to ``isaaclab_tasks.utils.sampling`` and retained the previous NIST import paths for existing configurations. +* Added a sparse Franka cube-pickup reference task that generates validated reset states + through physical approach and grasp rollouts and samples them using recent success rates. diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/README.md b/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/README.md new file mode 100644 index 000000000000..b57df90c3747 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/README.md @@ -0,0 +1,62 @@ +# Generated reset states for sparse cube pickup + +This reference example exercises `isaaclab.envs.reset.ResetStateBuffer`: task callbacks +generate candidate states through simulation, reject invalid candidates, and freeze the +accepted states before reinforcement learning. The example currently supports Newton MJWarp. + +Support owner during reset API development: Maximilian Krause. Evaluate this example +with the reset-state-buffer API before promotion to a stable reference. Remove or +relocate it if that API is withdrawn or another example covers the same capability. + +A Franka carries a grasped 40 mm cube within 0.04 m of the fixed target point +`(0.5, 0.0, 0.15) m` in the robot root frame. Success is immediate when the cube +reaches the point while grasped. The only reward is a terminal `+1` for that success. +There are no reaching, grasping, motion, or progress rewards. Relative Cartesian IK and +a binary gripper command use the existing Franka asset and action implementations. +The gripper opens for actions above 0.5 and closes otherwise. + +The buffer contains four stages from physical scripted rollouts: home with the cube on +the table, approach targets interpolated from home to 0.10 m above the cube, open-finger +pregrasps spanning 0–0.10 m above it, and established grasps lifted by 0.025–0.098 m. +These continuous starts connect the pickup path without already satisfying the goal. +The generator closes the real fingers and performs a short lift; it +never places a cube into a closed hand. A grasp must survive state restoration and +continued physics before acceptance. Collection has a fixed attempt limit and reports +acceptance counts. Snapshots include velocities in environment-relative coordinates. +Acceptance excludes the same grasped-cube goal predicate used by reward and termination. +The goal is observed through the existing pose command. Replay preserves +physical velocities while clearing velocity targets for the position-controlled arm. + +Training records completed-episode outcomes against the previous reset row before +clearing task state. Sampling targets rows with approximately 50% recent success, with +uniform coverage retained. The policy observes neither reset-row IDs nor teacher actions. +The buffer changes the initial-state distribution; it supplies no demonstration loss. + +```bash +# Prove bank generation, partial replay isolation, and finite stepping. +uv run python scripts/environments/cube_pickup.py --mode generate \ + --num_envs 32 --bank_size 128 --seed 0 --output /tmp/pickup-generation.json + +# Prove pickup from ordinary home/table starts with the scripted controller. +uv run python scripts/environments/cube_pickup.py --mode scripted \ + --num_envs 32 --episodes 64 --seed 10000 --output /tmp/pickup-scripted.json + +# Train; the actual generated bank and collection report are saved in the run directory. +uv run isaaclab train --rl_library rsl_rl --task IsaacContrib-Cube-Pickup-Franka \ + --num_envs 1024 --max_iterations 3000 --seed 0 + +# Evaluate a checkpoint on full pickup attempts with a held-out seed and no reset bank. +uv run python scripts/environments/cube_pickup.py --mode evaluate \ + --checkpoint /path/to/model.pt --num_envs 64 --episodes 512 --seed 10000 \ + --output /tmp/pickup-evaluation.json +``` + +Set `env.reset_mode=uniform` when training to compare fixed uniform bank sampling, or +`env.reset_mode=table` to train from ordinary table starts without a bank. Change +`env.reset_buffer.size` to control collection size and `env.reset_buffer.seed` to vary +the generated bank independently of the training seed. + +Training success on the reset mixture does not establish full pickup learning. The +evaluation runner always resets the arm home and the cube onto the table, reports +completed episodes and binary successes, and bounds the rollout by `--steps`. Evaluate +multiple held-out seeds before claiming generalization. diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/__init__.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/__init__.py new file mode 100644 index 000000000000..f648f557fa70 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/__init__.py @@ -0,0 +1,19 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Sparse cube pickup demonstrating a generated and validated reset-state buffer.""" + +import gymnasium as gym + +gym.register( + id="IsaacContrib-Cube-Pickup-Franka", + entry_point=f"{__name__}.cube_pickup_env:CubePickupEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.cube_pickup_env_cfg:CubePickupEnvCfg", + "rsl_rl_cfg_entry_point": f"{__name__}.rsl_rl_ppo_cfg:CubePickupPPORunnerCfg", + "default_agent": "rsl_rl", + }, +) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env.py new file mode 100644 index 000000000000..549b0f2b40ed --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env.py @@ -0,0 +1,250 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Sparse pickup reference environment and its physical reset-state generator.""" + +from __future__ import annotations + +import json +import math +import os +from pathlib import Path + +import torch + +import isaaclab.envs.mdp as mdp +from isaaclab.envs import ManagerBasedRLEnv +from isaaclab.envs.reset import ResetStateBuffer +from isaaclab.managers import SceneEntityCfg +from isaaclab.utils import clone +from isaaclab.utils.math import compute_pose_error + +from isaaclab_tasks.utils import ResetStateSampler +from isaaclab_tasks.utils.sampling import UniformSamplingStrategyCfg + +from . import mdp as pickup_mdp +from .cube_pickup_env_cfg import CubePickupEnvCfg + + +class CubePickupEnv(ManagerBasedRLEnv): + """Train sparse pickup from snapshots of genuine simulated approach and grasp rollouts.""" + + cfg: CubePickupEnvCfg + + def __init__(self, cfg: CubePickupEnvCfg, **kwargs): + self.reset_buffer: ResetStateBuffer | None = None + self.reset_sampler: ResetStateSampler | None = None + super().__init__(cfg, **kwargs) + self._hand_cfg = SceneEntityCfg("robot", body_names="panda_hand") + self._hand_cfg.resolve(self.scene) + self._bank_generator = torch.Generator(device=self.device) + self._bank_generator.manual_seed(cfg.reset_buffer.seed) + self._reset_generator = torch.Generator(device=self.device) + self._reset_generator.manual_seed(torch.initial_seed() if cfg.seed is None else cfg.seed) + self._all_ids = torch.arange(self.num_envs, device=self.device) + self.generation_report: dict = {} + self.command_manager.reset() + if cfg.reset_mode != "table": + self._collect_reset_states() + + def _tcp_pose(self) -> torch.Tensor: + return pickup_mdp.hand_pose(self, self._hand_cfg) + + def _reset_table(self, env_ids: torch.Tensor, *, generating: bool = False) -> None: + mdp.reset_scene_to_default(self, env_ids) + cube = self.scene["object"] + state = cube.data.default_root_state.torch[env_ids].clone() + generator = self._bank_generator if generating else self._reset_generator + offsets = torch.rand((env_ids.numel(), 2), device=self.device, generator=generator) + state[:, 0] = 0.45 + 0.10 * offsets[:, 0] + state[:, 1] = -0.08 + 0.16 * offsets[:, 1] + state[:, :3] += self.scene.env_origins[env_ids] + cube.write_root_pose_to_sim_index(root_pose=state[:, :7], env_ids=env_ids) + cube.write_root_velocity_to_sim_index(root_velocity=state[:, 7:], env_ids=env_ids) + self.scene.write_data_to_sim() + self.sim.forward() + self.scene.update(0.0) + + def _physics_step(self, actions: torch.Tensor) -> None: + """Advance only the action/physics path while producing reset candidates.""" + self.action_manager.process_action(actions) + steps_per_call = self.cfg.decimation if self._physics_handles_decimation else 1 + for _ in range(0, self.cfg.decimation, steps_per_call): + self.action_manager.apply_action() + self.scene.write_data_to_sim() + self.sim.step(render=False) + self.scene.update(self.physics_dt * steps_per_call) + + def scripted_action(self, target: torch.Tensor, *, close: bool) -> torch.Tensor: + """Create a bounded relative IK action for target poses [m, xyzw].""" + current = self._tcp_pose() + position_error, rotation_error = compute_pose_error( + current[:, :3], current[:, 3:], target[:, :3], target[:, 3:], rot_error_type="axis_angle" + ) + action = torch.zeros((self.num_envs, 7), device=self.device) + action[:, :3] = (position_error / 0.025).clamp(-1.0, 1.0) + action[:, 3:6] = (rotation_error / 0.1).clamp(-1.0, 1.0) + action[:, 6] = -1.0 if close else 1.0 + return action + + def _drive(self, target: torch.Tensor, duration: float, *, close: bool = False) -> None: + for _ in range(math.ceil(duration / self.step_dt)): + self._physics_step(self.scripted_action(target, close=close)) + + def _generate(self, env_ids: torch.Tensor, stage: str) -> torch.Tensor: + # All candidates in one batch share the same generator phase. Unselected environments + # may advance during prefill; the normal reset lifecycle runs before training begins. + self._reset_table(env_ids, generating=True) + self.action_manager.reset() + rest = self._tcp_pose().clone() + self._drive(rest, 0.2) + if stage == "table": + return self._candidate_valid(env_ids) + + cube_position = pickup_mdp.object_position(self).clone() + target = rest.clone() + target[:, 3:] = target.new_tensor((1.0, 0.0, 0.0, 0.0)) + target[:, :3] = cube_position + target[:, 2] += 0.10 + if stage == "approach": + fraction = torch.rand((self.num_envs, 1), device=self.device, generator=self._bank_generator) + target[:, :3] = torch.lerp(rest[:, :3], target[:, :3], fraction) + self._drive(target, 5.0) + if stage == "approach": + return self._candidate_valid(env_ids) & ( + torch.linalg.vector_norm(self._tcp_pose()[env_ids, :3] - target[env_ids, :3], dim=-1) < 0.02 + ) + + target[:, :3] = cube_position + if stage == "pregrasp": + target[:, 2] += 0.10 * torch.rand((self.num_envs,), device=self.device, generator=self._bank_generator) + self._drive(target, 2.0) + aligned = torch.linalg.vector_norm(self._tcp_pose()[env_ids, :3] - target[env_ids, :3], dim=-1) < 0.015 + if stage == "pregrasp": + return self._candidate_valid(env_ids) & aligned + + # Establish the grasp through physical finger closure, then prove it can lift. + self._drive(target, 0.6, close=True) + target[:, 2] += 0.025 + 0.073 * torch.rand((self.num_envs,), device=self.device, generator=self._bank_generator) + self._drive(target, 1.0, close=True) + height = pickup_mdp.object_position(self)[env_ids, 2] + attached = torch.linalg.vector_norm(pickup_mdp.object_to_hand(self, self._hand_cfg)[env_ids], dim=-1) < 0.035 + valid = self._candidate_valid(env_ids) & aligned & attached & (height > 0.035) + # Contact solver caches are not scene state. Restore the actual snapshot and continue + # holding before accepting it, so a grasp must survive reconstruction of its contacts. + state = self._capture(env_ids) + self._restore_reset_state(state, env_ids) + self._drive(target, 1.0, close=True) + height = pickup_mdp.object_position(self)[env_ids, 2] + return valid & self._candidate_valid(env_ids) & (height > 0.035) + + def _candidate_valid(self, env_ids: torch.Tensor) -> torch.Tensor: + robot = self.scene["robot"] + cube = self.scene["object"] + position = pickup_mdp.object_position(self)[env_ids] + goal_cfg = self.termination_manager.get_term_cfg("success") + already_successful = goal_cfg.func(self, **goal_cfg.params)[env_ids] + return ( + torch.isfinite(robot.data.joint_pos.torch[env_ids]).all(dim=-1) + & torch.isfinite(cube.data.root_state_w.torch[env_ids]).all(dim=-1) + & (position[:, 2] > 0.017) + & ~already_successful + & (position[:, 0] > 0.35) + & (position[:, 0] < 0.65) + & (position[:, 1].abs() < 0.20) + & (torch.linalg.vector_norm(cube.data.root_lin_vel_w.torch[env_ids], dim=-1) < 0.15) + & (robot.data.joint_vel.torch[env_ids].abs().amax(dim=-1) < 3.0) + ) + + def _capture(self, env_ids: torch.Tensor) -> dict: + state = self.scene.get_state(is_relative=True) + return { + kind: { + name: {field: value[env_ids].clone() for field, value in fields.items()} + for name, fields in assets.items() + } + for kind, assets in state.items() + } + + def _restore_reset_state(self, state: ResetStateBuffer.State, env_ids: torch.Tensor) -> None: + self.scene.reset_to(state, env_ids=env_ids, is_relative=True) + # Scene state contains physical velocities. The position-controlled IK action requires + # zero desired joint velocities rather than continuing those captured motions. + self.scene["robot"].actuators.target_command.set_velocity_index( + value=torch.zeros_like(state["articulation"]["robot"]["joint_velocity"]), env_ids=env_ids + ) + self.scene.write_data_to_sim() + self.sim.forward() + self.scene.update(0.0) + + def _collect_reset_states(self) -> None: + self.reset_buffer = ResetStateBuffer(self.cfg.reset_buffer) + generators = { + stage: (lambda env_ids, stage=stage: self._generate(env_ids, stage)) + for stage in ("table", "approach", "pregrasp", "grasp") + } + self.reset_buffer.collect(self._all_ids, generators, self._capture) + sampler_cfg = clone(self.cfg.reset_sampler) + if self.cfg.reset_mode == "uniform": + sampler_cfg.sampling.strategies = [UniformSamplingStrategyCfg()] + self.reset_sampler = ResetStateSampler(sampler_cfg, self.num_envs, self.reset_buffer.num_states, self.device) + self.generation_report = { + "seed": self.cfg.reset_buffer.seed, + "num_states": self.reset_buffer.num_states, + "stages": { + name: int((self.reset_buffer.group_ids == i).sum().item()) + for i, name in enumerate(self.reset_buffer.group_names) + }, + "collection": self.reset_buffer.collection_report, + "validation": "Finite state, low velocity, replayed physical grasp; no initial goal success.", + } + if self.cfg.log_dir: + rank = os.getenv("RANK") + filename = "reset_states.pt" if rank is None else f"reset_states_rank_{rank}.pt" + self.save_reset_buffer(Path(self.cfg.log_dir) / filename) + + def save_reset_buffer(self, path: str | Path) -> None: + """Save generated scene states and stage metadata for reproducing the training distribution.""" + if self.reset_buffer is None: + raise ValueError("Table-only evaluation does not generate a reset buffer.") + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + torch.save( + { + "state": self.reset_buffer.state, + "group_names": self.reset_buffer.group_names, + "group_ids": self.reset_buffer.group_ids, + "report": self.generation_report, + }, + path, + ) + path.with_suffix(".json").write_text(json.dumps(self.generation_report, indent=2) + "\n") + + def _reset_idx(self, env_ids: torch.Tensor | slice): + ids = self.scene._ALL_INDICES[env_ids] + success = self.termination_manager.get_term("success")[ids].clone() + valid = (self.episode_length_buf[ids] > 0) & self.termination_manager.dones[ids] + metrics: dict[str, torch.Tensor] = {} + rows = None + if self.reset_sampler is not None: + previous_rows = self.reset_sampler.row_ids[ids] + previous_groups = self.reset_buffer.group_ids[previous_rows] + for group_id, name in enumerate(self.reset_buffer.group_names): + mask = valid & (previous_groups == group_id) + if mask.any(): + metrics[f"Reset/{name}_success"] = success[mask].float().mean() + # Credit the row that produced the episode before clearing success and episode buffers. + rows = self.reset_sampler.reset(ids, success=success, valid=valid) + for group_id, name in enumerate(self.reset_buffer.group_names): + mask = self.reset_buffer.group_ids == group_id + metrics[f"Reset/{name}_probability"] = self.reset_sampler.probabilities[mask].sum() + if valid.any(): + metrics["Metrics/success_rate"] = success[valid].float().mean() + super()._reset_idx(env_ids) + if rows is None: + self._reset_table(ids) + else: + self._restore_reset_state(self.reset_buffer.get_state(rows), ids) + self.extras["log"].update(metrics) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env_cfg.py new file mode 100644 index 000000000000..7652bb8df40e --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env_cfg.py @@ -0,0 +1,229 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Franka pickup with a binary goal reward and generated reset states.""" + +import math +from typing import Literal + +from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg +from isaaclab_newton.sim.schemas import MujocoRigidBodyCfg +from isaaclab_physx.sim.schemas import PhysxRigidBodyCfg + +import isaaclab.envs.mdp as mdp +import isaaclab.sim as sim_utils +from isaaclab.assets import ArticulationCfg, AssetBaseCfg, RigidObjectCfg +from isaaclab.controllers import DifferentialIKControllerCfg +from isaaclab.envs import ManagerBasedRLEnvCfg +from isaaclab.envs.reset import ResetStateBufferCfg +from isaaclab.managers import ( + EventTermCfg, + ObservationGroupCfg, + ObservationTermCfg, + RewardTermCfg, + SceneEntityCfg, + TerminationTermCfg, +) +from isaaclab.scene import InteractiveSceneCfg +from isaaclab.utils import configclass, replace +from isaaclab.visualizers import VisualizerCfg + +from isaaclab_tasks.core.lift.mdp import ObjectUniformPoseCommandCfg +from isaaclab_tasks.utils import PresetCfg, ResetStateSamplerCfg + +from isaaclab_assets.robots import FRANKA_PANDA_HIGH_PD_CFG + +from . import mdp as pickup_mdp + + +@configclass +class PhysicsCfg(PresetCfg): + """Supported physics backend for this example.""" + + newton_mjwarp = NewtonCfg( + solver_cfg=MJWarpSolverCfg( + njmax=128, + nconmax=64, + iterations=30, + ls_iterations=15, + cone="elliptic", + integrator="implicitfast", + use_mujoco_contacts=True, + ), + num_substeps=2, + ) + default = newton_mjwarp + + +@configclass +class SceneCfg(InteractiveSceneCfg): + """Existing Franka asset with a table and one 40 mm cube.""" + + robot: ArticulationCfg = replace(FRANKA_PANDA_HIGH_PD_CFG, prim_path="{ENV_REGEX_NS}/Robot") + table = AssetBaseCfg( + prim_path="{ENV_REGEX_NS}/Table", + init_state=AssetBaseCfg.InitialStateCfg(pos=(0.5, 0.0, -0.02)), + spawn=sim_utils.CuboidCfg(size=(0.8, 1.0, 0.04), collision_props=sim_utils.UsdPhysicsCollisionCfg()), + ) + object = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/Object", + init_state=RigidObjectCfg.InitialStateCfg(pos=(0.5, 0.0, 0.021)), + spawn=sim_utils.CuboidCfg( + size=(0.04, 0.04, 0.04), + rigid_props=sim_utils.UsdPhysicsRigidBodyCfg(), + collision_props=sim_utils.UsdPhysicsCollisionCfg(), + mass_props=sim_utils.MassCfg(mass=0.05), + physics_material=sim_utils.RigidBodyMaterialBaseCfg(static_friction=0.8, dynamic_friction=0.8), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.15, 0.45, 0.8)), + ), + ) + light = AssetBaseCfg(prim_path="/World/Light", spawn=sim_utils.DomeLightCfg(intensity=2000.0)) + + def __post_init__(self): + super().__post_init__() + self.robot.spawn.variants["Physics"] = "mujoco" + # Match the high-PD asset's gravity-free arm in the native MuJoCo model. + # The cube retains gravity throughout generation and training. + self.robot.spawn.rigid_props = [ + PhysxRigidBodyCfg(disable_gravity=True, max_depenetration_velocity=5.0), + MujocoRigidBodyCfg(gravcomp=1.0), + ] + # Keep the ordinary home start above the table with a downward-facing hand. + self.robot.init_state.joint_pos["panda_joint6"] = 2.241 + self.robot.init_state.joint_pos["panda_joint7"] = math.pi / 4.0 + # The authored mimic constraint drives the second finger. + self.robot.actuators["panda_hand"].stiffness = 1200.0 + self.robot.actuators["panda_hand"].damping = 60.0 + self.robot.actuators["panda_hand"].joint_effort_limit = 40.0 + + +@configclass +class ActionsCfg: + """Relative Cartesian pose increments and a binary gripper command.""" + + arm = mdp.DifferentialInverseKinematicsActionCfg( + asset_name="robot", + joint_names=["panda_joint[1-7]"], + body_name="panda_hand", + body_offset=mdp.DifferentialInverseKinematicsActionCfg.OffsetCfg(pos=(0.0, 0.0, 0.107)), + controller=DifferentialIKControllerCfg(command_type="pose", use_relative_mode=True, ik_method="dls"), + scale=(0.025, 0.025, 0.025, 0.1, 0.1, 0.1), + ) + gripper = mdp.AbsBinaryJointPositionActionCfg( + asset_name="robot", + joint_names=["panda_finger_joint1"], + open_command_expr={"panda_finger_joint1": 0.04}, + close_command_expr={"panda_finger_joint1": 0.0}, + threshold=0.5, + ) + + +@configclass +class CommandsCfg: + """Fixed pickup target expressed in the robot root frame [m].""" + + object_pose = ObjectUniformPoseCommandCfg( + asset_name="robot", + object_name="object", + resampling_time_range=(1.0e9, 1.0e9), + position_only=True, + debug_vis=False, + ranges=ObjectUniformPoseCommandCfg.Ranges( + pos_x=(0.5, 0.5), + pos_y=(0.0, 0.0), + pos_z=(0.15, 0.15), + roll=(0.0, 0.0), + pitch=(0.0, 0.0), + yaw=(0.0, 0.0), + ), + ) + + +@configclass +class ObservationsCfg: + """State observations; reset-row identities and teacher actions are never observed.""" + + @configclass + class PolicyCfg(ObservationGroupCfg): + joint_pos = ObservationTermCfg(func=mdp.joint_pos_rel) + joint_vel = ObservationTermCfg(func=mdp.joint_vel_rel, scale=0.1) + object_position = ObservationTermCfg(func=pickup_mdp.object_position) + goal = ObservationTermCfg(func=mdp.generated_commands, params={"command_name": "object_pose"}) + hand_pose = ObservationTermCfg( + func=pickup_mdp.hand_pose, params={"asset_cfg": SceneEntityCfg("robot", body_names="panda_hand")} + ) + object_to_hand = ObservationTermCfg( + func=pickup_mdp.object_to_hand, params={"asset_cfg": SceneEntityCfg("robot", body_names="panda_hand")} + ) + actions = ObservationTermCfg(func=mdp.last_action) + + def __post_init__(self): + self.enable_corruption = False + self.concatenate_terms = True + + policy = PolicyCfg() + + +@configclass +class RewardsCfg: + """One terminal success reward; its weight cancels reward-manager integration.""" + + success = RewardTermCfg(func=pickup_mdp.success_reward, weight=1.0) + + +@configclass +class TerminationsCfg: + """Success, table bounds, and a finite attempt duration.""" + + success = TerminationTermCfg( + func=pickup_mdp.goal_reached, + params={ + "command_name": "object_pose", + "threshold": 0.04, + "hand_cfg": SceneEntityCfg("robot", body_names="panda_hand"), + "gripper_cfg": SceneEntityCfg("robot", joint_names="panda_finger_joint.*"), + }, + ) + time_out = TerminationTermCfg(func=mdp.time_out, time_out=True) + dropped = TerminationTermCfg(func=pickup_mdp.object_dropped) + + +@configclass +class EventsCfg: + """Manager lifecycle reset; task-specific states are restored after manager cleanup.""" + + reset_scene = EventTermCfg(func=mdp.reset_scene_to_default, mode="reset") + + +@configclass +class CubePickupEnvCfg(ManagerBasedRLEnvCfg): + """Reference task for sparse learning with generated and validated reset states.""" + + scene: SceneCfg = SceneCfg(num_envs=1024, env_spacing=2.0) + actions: ActionsCfg = ActionsCfg() + observations: ObservationsCfg = ObservationsCfg() + rewards: RewardsCfg = RewardsCfg() + terminations: TerminationsCfg = TerminationsCfg() + events: EventsCfg = EventsCfg() + commands: CommandsCfg = CommandsCfg() + curriculum = None + reset_buffer: ResetStateBufferCfg = ResetStateBufferCfg(size=1024, max_batches=50, seed=0) + reset_sampler: ResetStateSamplerCfg = ResetStateSamplerCfg() + reset_mode: Literal["adaptive", "uniform", "table"] = "adaptive" + """Training distribution, or ordinary home/table starts for evaluation.""" + + def __post_init__(self): + self.decimation = 4 + self.sim.dt = 1.0 / 120.0 + self.sim.render_interval = self.decimation + self.sim.physics = PhysicsCfg() + self.episode_length_s = 12.0 + self.is_finite_horizon = True + self.rewards.success.weight = 1.0 / (self.sim.dt * self.decimation) + self.sim.visualizer_cfgs = VisualizerCfg(eye=(1.3, 1.1, 0.9), lookat=(0.45, 0.0, 0.15)) + + def play_mode(self): + super().play_mode() + self.reset_mode = "table" diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/mdp.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/mdp.py new file mode 100644 index 000000000000..a3aea2df001f --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/mdp.py @@ -0,0 +1,84 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""State observations and the sparse grasped-cube goal condition.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import torch + +from isaaclab.managers import SceneEntityCfg +from isaaclab.utils.math import quat_apply + +from isaaclab_tasks.core.lift.mdp import object_reached_goal + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedRLEnv + + +def object_position(env: ManagerBasedRLEnv) -> torch.Tensor: + """Cube center position relative to the environment origin [m].""" + return env.scene["object"].data.root_pos_w.torch - env.scene.env_origins + + +def hand_pose( + env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot", body_names="panda_hand") +) -> torch.Tensor: + """Grasp-center position [m] and orientation [xyzw] relative to the environment origin.""" + robot = env.scene[asset_cfg.name] + body_id = asset_cfg.body_ids[0] + orientation = robot.data.body_link_quat_w.torch[:, body_id] + offset = orientation.new_tensor((0.0, 0.0, 0.107)).expand(env.num_envs, -1) + position = robot.data.body_link_pos_w.torch[:, body_id] + quat_apply(orientation, offset) + return torch.cat((position - env.scene.env_origins, orientation), dim=-1) + + +def object_to_hand( + env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot", body_names="panda_hand") +) -> torch.Tensor: + """Cube displacement from the grasp center [m].""" + return object_position(env) - hand_pose(env, asset_cfg)[:, :3] + + +def goal_reached( + env: ManagerBasedRLEnv, + command_name: str, + threshold: float, + hand_cfg: SceneEntityCfg, + gripper_cfg: SceneEntityCfg, +) -> torch.Tensor: + """Return whether the grasped cube reached the commanded point. + + The cube must be within 0.035 m of the grasp center, with both finger positions + between 0.01 m and 0.025 m, consistent with grasping this 40 mm cube. + + Args: + env: Environment containing the robot and cube. + command_name: Object pose command expressed in the robot root frame. + threshold: Maximum cube-to-goal position error [m]. + hand_cfg: Robot hand used to measure the grasp center. + gripper_cfg: Robot finger joints used to measure the grasp opening. + + Returns: + Whether each environment's grasped cube reached the goal. + """ + finger_positions = env.scene[gripper_cfg.name].data.joint_pos.torch[:, gripper_cfg.joint_ids] + grasped = (torch.linalg.vector_norm(object_to_hand(env, hand_cfg), dim=-1) < 0.035) & ( + (finger_positions > 0.01) & (finger_positions < 0.025) + ).all(dim=-1) + return object_reached_goal(env, command_name=command_name, threshold=threshold) & grasped + + +def success_reward(env: ManagerBasedRLEnv) -> torch.Tensor: + """Return the binary goal success for the terminal transition.""" + return env.termination_manager.get_term("success").float() + + +def object_dropped(env: ManagerBasedRLEnv) -> torch.Tensor: + """Terminate when the cube leaves the table workspace [m].""" + position = object_position(env) + return (position[:, 2] < -0.02) | (position[:, 0] < 0.15) | (position[:, 0] > 0.85) | (position[:, 1].abs() > 0.45) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/rsl_rl_ppo_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/rsl_rl_ppo_cfg.py new file mode 100644 index 000000000000..ccee298ae2c7 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/rsl_rl_ppo_cfg.py @@ -0,0 +1,41 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""RSL-RL configuration for the sparse pickup reference example.""" + +from isaaclab.utils import configclass + +from isaaclab_rl.rsl_rl import RslRlMLPModelCfg, RslRlOnPolicyRunnerCfg, RslRlPpoAlgorithmCfg + + +@configclass +class CubePickupPPORunnerCfg(RslRlOnPolicyRunnerCfg): + num_steps_per_env = 32 + max_iterations = 3000 + save_interval = 100 + experiment_name = "cube_pickup_reset_buffer" + obs_groups = {"actor": ["policy"], "critic": ["policy"]} + clip_actions = 1.0 + actor = RslRlMLPModelCfg( + distribution_cfg=RslRlMLPModelCfg.GaussianDistributionCfg(init_std=0.7), + obs_normalization=True, + hidden_dims=[256, 128, 64], + activation="elu", + ) + critic = RslRlMLPModelCfg(obs_normalization=True, hidden_dims=[256, 128, 64], activation="elu") + algorithm = RslRlPpoAlgorithmCfg( + value_loss_coef=1.0, + use_clipped_value_loss=True, + clip_param=0.2, + entropy_coef=0.003, + num_learning_epochs=5, + num_mini_batches=4, + learning_rate=5.0e-4, + schedule="adaptive", + gamma=0.995, + lam=0.95, + desired_kl=0.01, + max_grad_norm=1.0, + ) From 6ec0d7fe78d9938c338d259a7a0a3c5a9a7e6ea7 Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Sat, 7 Nov 2026 02:49:13 +0100 Subject: [PATCH 03/10] Reuse shared reset sampling in Franka Pour --- ...nka-pour-shared-reset-sampling.changed.rst | 2 + .../contrib/franka_pour/README.md | 4 + .../contrib/franka_pour/reset_sampler.py | 117 +++--------------- .../contrib/test_franka_pour_reset_sampler.py | 48 +++---- .../isaaclab_tasks/test/test_reset_states.py | 26 +++- 5 files changed, 64 insertions(+), 133 deletions(-) create mode 100644 source/isaaclab_tasks/changelog.d/franka-pour-shared-reset-sampling.changed.rst diff --git a/source/isaaclab_tasks/changelog.d/franka-pour-shared-reset-sampling.changed.rst b/source/isaaclab_tasks/changelog.d/franka-pour-shared-reset-sampling.changed.rst new file mode 100644 index 000000000000..471d51b04d31 --- /dev/null +++ b/source/isaaclab_tasks/changelog.d/franka-pour-shared-reset-sampling.changed.rst @@ -0,0 +1,2 @@ +* Reused shared outcome history and Beta sampling utilities in Franka Pour while preserving its + existing configuration, cyclic replay coverage, and task-specific reset pipeline. diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/README.md b/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/README.md index 33c01a7a23f5..4aa38c61df94 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/README.md +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/README.md @@ -148,6 +148,10 @@ rows at 0% or 100%. A shuffled cyclic stream receives 50% of assignments through which keeps persistently difficult reaching and grasp-acquisition rows represented alongside the adaptive competence frontier. There are no runtime stages or region probabilities. +Outcome history and adaptive weighting use the shared `SuccessMonitor` and `Sampler` utilities. +The task adapter owns cyclic coverage, progress attribution, and playback selection; artifact +validation and particle restoration remain part of the Pour reset pipeline. + The sampler reports its effective pool size, concentration, and cyclic-replay fraction. Offline reset regions remain in the artifact as generation provenance, but runtime does not maintain a second set of per-region counters. Evaluate frozen policies separately rather than inferring diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/reset_sampler.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/reset_sampler.py index db97e66ba9f2..ef687054a404 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/reset_sampler.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/reset_sampler.py @@ -13,6 +13,9 @@ from isaaclab.utils import configclass +from isaaclab_tasks.utils import SuccessMonitor, SuccessMonitorCfg +from isaaclab_tasks.utils.sampling import BetaSamplingStrategyCfg, Sampler, SamplerCfg + __all__ = [ "ResetDatasetSamplerCfg", ] @@ -70,76 +73,8 @@ def validate_values(self) -> None: raise ValueError("uniform_fraction must lie strictly between zero and one.") -def _ring_append_bool_count_rate( - data: torch.Tensor, - stream_ids: torch.Tensor, - values: torch.Tensor, - pointer: torch.Tensor, - size: torch.Tensor, - true_count: torch.Tensor, - rate: torch.Tensor, -) -> None: - """Append outcomes to per-row Boolean rings and update rolling success rates.""" - if stream_ids.numel() == 0: - return - - capacity = data.shape[1] - unique_ids, inverse, counts = torch.unique(stream_ids, return_inverse=True, return_counts=True) - if unique_ids.numel() == stream_ids.numel(): - columns = pointer[stream_ids].long() - overwritten = torch.where( - size[stream_ids] == capacity, - data[stream_ids, columns].to(dtype=true_count.dtype), - torch.zeros_like(true_count[stream_ids]), - ) - new_true_counts = true_count[stream_ids] - overwritten + values.to(dtype=true_count.dtype) - data[stream_ids, columns] = values - pointer[stream_ids] = ((columns + 1) % capacity).to(dtype=pointer.dtype) - size[stream_ids] = (size[stream_ids] + 1).clamp(max=capacity) - true_count[stream_ids] = new_true_counts - rate[stream_ids] = new_true_counts.to(rate.dtype) / size[stream_ids].clamp(min=1) - return - - order = torch.argsort(inverse, stable=True) - sorted_ids = stream_ids[order] - sorted_values = values[order] - group_starts = counts.cumsum(0) - counts - local_rank = torch.arange(stream_ids.numel(), device=data.device) - torch.repeat_interleave(group_starts, counts) - inverse_sorted = inverse[order] - counts_sorted = counts[inverse_sorted] - true_added = torch.zeros(unique_ids.shape, device=data.device, dtype=true_count.dtype) - true_added.scatter_add_(0, inverse, values.to(dtype=true_count.dtype)) - - keep_start = (counts - capacity).clamp(min=0) - keep = local_rank >= torch.repeat_interleave(keep_start, counts) - true_kept = torch.zeros_like(true_added) - true_kept.scatter_add_(0, inverse_sorted[keep], sorted_values[keep].to(dtype=true_count.dtype)) - - overwrite_start = capacity - size[sorted_ids].long() - overwrite_mask = (counts_sorted < capacity) & (local_rank >= overwrite_start) - overwritten = torch.zeros_like(true_added) - overwrite_ids = sorted_ids[overwrite_mask] - overwrite_columns = (pointer[overwrite_ids].long() + local_rank[overwrite_mask]) % capacity - overwritten.scatter_add_( - 0, - inverse_sorted[overwrite_mask], - data[overwrite_ids, overwrite_columns].to(dtype=true_count.dtype), - ) - - kept_ids = sorted_ids[keep] - kept_columns = (pointer[kept_ids].long() + local_rank[keep]) % capacity - data[kept_ids, kept_columns] = sorted_values[keep] - replace = counts >= capacity - new_true_counts = torch.where(replace, true_kept, true_count[unique_ids] - overwritten + true_added) - new_size = (size[unique_ids].long() + counts).clamp(max=capacity) - pointer[unique_ids] = ((pointer[unique_ids].long() + counts) % capacity).to(dtype=pointer.dtype) - size[unique_ids] = new_size.to(dtype=size.dtype) - true_count[unique_ids] = new_true_counts - rate[unique_ids] = new_true_counts.to(rate.dtype) / new_size.clamp(min=1).to(rate.dtype) - - class ResetDatasetSampler: - """Sample reset rows using a rolling-success kernel and exact cyclic replay.""" + """Combine shared outcome weighting with Pour's exact cyclic replay.""" def __init__( self, @@ -152,28 +87,23 @@ def __init__( self.cfg = cfg if cfg is not None else ResetDatasetSamplerCfg() self.cfg.validate_values() self.row_count = row_count - self._alpha_minus_one = self.cfg.kappa * self.cfg.target_success_rate - self._beta_minus_one = self.cfg.kappa * (1.0 - self.cfg.target_success_rate) - - self._success_rates = torch.zeros(row_count, dtype=torch.float32, device=device) - self._success_history = torch.zeros( - (row_count, self.cfg.monitored_history_len), - dtype=torch.bool, - device=device, + self._success_monitor = SuccessMonitor( + SuccessMonitorCfg(monitored_history_len=self.cfg.monitored_history_len), 1, row_count, device + ) + self._sampler = Sampler( + SamplerCfg( + strategies=[BetaSamplingStrategyCfg(target=self.cfg.target_success_rate, kappa=self.cfg.kappa)], + eps=self.cfg.epsilon, + ), + self._success_monitor.success_rate, ) - self._history_pointers = torch.zeros(row_count, dtype=torch.int32, device=device) - self._history_sizes = torch.zeros_like(self._history_pointers) - self._history_success_counts = torch.zeros_like(self._history_pointers) self._uniform_order = torch.randperm(row_count, device=device) self._uniform_cursor = 0 self._uniform_credit = 0.0 def _probabilities(self) -> torch.Tensor: """Return normalized Beta scores with a per-row epsilon floor.""" - weights = self._success_rates.pow(self._alpha_minus_one) - weights *= (1.0 - self._success_rates).pow(self._beta_minus_one) - weights.add_(self.cfg.epsilon) - return weights / weights.sum() + return self._sampler.probabilities() def _sample_with_uniform_replay( self, @@ -182,7 +112,7 @@ def _sample_with_uniform_replay( generator: torch.Generator | None = None, ) -> torch.Tensor: """Sample rows with a mixture of adaptive and exact cyclic replay.""" - device = self._success_rates.device + device = self._uniform_order.device rows = torch.empty(count, device=device, dtype=torch.long) if count == 0: return rows @@ -204,21 +134,12 @@ def _sample_with_uniform_replay( def _record_validated(self, rows: torch.Tensor, success: torch.Tensor) -> None: """Append outcomes whose shape, dtype, device, and row values are already trusted.""" - _ring_append_bool_count_rate( - self._success_history, - rows, - success, - self._history_pointers, - self._history_sizes, - self._history_success_counts, - self._success_rates, - ) + self._success_monitor.success_update(rows, success) def metrics(self) -> dict[str, float]: """Return sampling-concentration and cyclic-replay metrics.""" replay_fraction = float(self.cfg.uniform_fraction) - probabilities = self._probabilities() - probabilities.mul_(1.0 - replay_fraction).add_(replay_fraction / self.row_count) + probabilities = self._probabilities() * (1.0 - replay_fraction) + replay_fraction / self.row_count top_count = max(1, math.ceil(0.01 * self.row_count)) values = torch.stack( ( @@ -248,7 +169,7 @@ def _take_uniform_rows( ) -> torch.Tensor: """Take rows from shuffled complete-cache cycles without replacement within a cycle.""" if count == 0: - return torch.empty(0, device=self._success_rates.device, dtype=torch.long) + return torch.empty(0, device=self._uniform_order.device, dtype=torch.long) remaining = count chunks = [] while remaining > 0: @@ -260,7 +181,7 @@ def _take_uniform_rows( if self._uniform_cursor == self.row_count: self._uniform_order = torch.randperm( self.row_count, - device=self._success_rates.device, + device=self._uniform_order.device, generator=generator, ) self._uniform_cursor = 0 diff --git a/source/isaaclab_tasks/test/contrib/test_franka_pour_reset_sampler.py b/source/isaaclab_tasks/test/contrib/test_franka_pour_reset_sampler.py index 3c22bf2a48bf..cd5bbb648575 100644 --- a/source/isaaclab_tasks/test/contrib/test_franka_pour_reset_sampler.py +++ b/source/isaaclab_tasks/test/contrib/test_franka_pour_reset_sampler.py @@ -5,50 +5,30 @@ """CPU tests for the Franka Pour reset-dataset sampler.""" -from collections import deque - import pytest import torch from isaaclab_tasks.contrib.franka_pour.reset_sampler import ResetDatasetSampler, ResetDatasetSamplerCfg - -def _ring_values(sampler: ResetDatasetSampler, row: int) -> list[bool]: - """Read one sampler ring in oldest-to-newest order.""" - size = int(sampler._history_sizes[row]) - pointer = int(sampler._history_pointers[row]) - capacity = sampler._success_history.shape[1] - start = pointer if size == capacity else 0 - return [bool(sampler._success_history[row, (start + index) % capacity]) for index in range(size)] +pytestmark = pytest.mark.kitless -def test_rolling_history_matches_per_row_deques(): - """Duplicate IDs, wraparound, and oversized batches match sequential deque updates.""" - capacity = 5 - row_count = 4 +def test_adaptive_weights_preserve_pour_configuration_and_recent_outcomes(): + """The adapter passes the target, concentration, floor, and history window to shared utilities.""" sampler = ResetDatasetSampler( - row_count, + 3, "cpu", - ResetDatasetSamplerCfg(monitored_history_len=capacity), + ResetDatasetSamplerCfg(monitored_history_len=4, target_success_rate=0.25, kappa=4.0, epsilon=0.01), ) - reference = [deque(maxlen=capacity) for _ in range(row_count)] - generator = torch.Generator().manual_seed(31) - - for batch_size in (4, 11, 2, 17, 7, 23): - rows = torch.randint(row_count, (batch_size,), generator=generator) - success = torch.rand(batch_size, generator=generator) > 0.45 - sampler._record_validated(rows, success) - for row, outcome in zip(rows.tolist(), success.tolist(), strict=True): - reference[row].append(outcome) - - expected_sizes = torch.tensor([len(history) for history in reference], dtype=torch.int32) - expected_counts = torch.tensor([sum(history) for history in reference], dtype=torch.int32) - expected_rates = expected_counts.float() / expected_sizes.clamp_min(1) - torch.testing.assert_close(sampler._history_sizes, expected_sizes) - torch.testing.assert_close(sampler._history_success_counts, expected_counts) - torch.testing.assert_close(sampler._success_rates, expected_rates) - for row, history in enumerate(reference): - assert _ring_values(sampler, row) == list(history) + torch.testing.assert_close(sampler._probabilities(), torch.full((3,), 1.0 / 3.0)) + sampler._record_validated( + torch.tensor([0] * 4 + [1] * 6 + [2] * 4), + torch.tensor([False] * 4 + [True, True, False, False, False, True] + [True] * 4), + ) + # Recent rates are 0, 1/4, and 1. Their normalized Beta weights including the floor are: + torch.testing.assert_close(sampler._probabilities(), torch.tensor([64.0 / 867, 739.0 / 867, 64.0 / 867])) + sampler._record_validated(torch.ones(4, dtype=torch.long), torch.ones(4, dtype=torch.bool)) + torch.testing.assert_close(sampler._probabilities(), torch.full((3,), 1.0 / 3.0)) def test_uniform_replay_covers_every_row_before_repeating(monkeypatch: pytest.MonkeyPatch): diff --git a/source/isaaclab_tasks/test/test_reset_states.py b/source/isaaclab_tasks/test/test_reset_states.py index 16dc055631bd..b6c89a92ac80 100644 --- a/source/isaaclab_tasks/test/test_reset_states.py +++ b/source/isaaclab_tasks/test/test_reset_states.py @@ -5,9 +5,33 @@ """Outcome attribution and selective resets at the shared sampler boundary.""" +from collections import deque + +import pytest import torch -from isaaclab_tasks.utils import ResetStateSampler, ResetStateSamplerCfg, SuccessMonitorCfg +from isaaclab_tasks.utils import ResetStateSampler, ResetStateSamplerCfg, SuccessMonitor, SuccessMonitorCfg + +pytestmark = pytest.mark.kitless + + +def test_rolling_history_matches_per_row_deques(): + """Duplicate IDs, wraparound, and oversized batches retain the latest outcomes in input order.""" + capacity = 5 + row_count = 4 + monitor = SuccessMonitor(SuccessMonitorCfg(monitored_history_len=capacity), 1, row_count, "cpu") + reference = [deque(maxlen=capacity) for _ in range(row_count)] + generator = torch.Generator().manual_seed(31) + + for batch_size in (4, 11, 2, 17, 7, 23): + rows = torch.randint(row_count, (batch_size,), generator=generator) + success = torch.rand(batch_size, generator=generator) > 0.45 + monitor.success_update(rows, success) + for row, outcome in zip(rows.tolist(), success.tolist(), strict=True): + reference[row].append(outcome) + + expected_rates = torch.tensor([sum(history) / max(1, len(history)) for history in reference]) + torch.testing.assert_close(monitor.get_success_rate(), expected_rates) def test_reset_records_previous_rows_and_preserves_unselected_environments(): From d6a30b1ab9ea8da20ed0d0ba1afa618aebb78bf1 Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Sat, 7 Nov 2026 03:46:14 +0100 Subject: [PATCH 04/10] Address reset buffer and pickup review findings --- scripts/environments/cube_pickup.py | 9 +- .../changelog.d/reset-buffer-review.fixed.rst | 1 + .../isaaclab/isaaclab/envs/reset/__init__.pyi | 2 + .../isaaclab/envs/reset/reset_state_buffer.py | 19 ++-- .../isaaclab/test/envs/test_reset_states.py | 6 ++ .../changelog.d/cube-pickup-review.fixed.rst | 2 + .../contrib/cube_pickup/cube_pickup_env.py | 6 +- .../cube_pickup/cube_pickup_env_cfg.py | 5 +- .../isaaclab_tasks/contrib/cube_pickup/mdp.py | 17 +++- .../contrib/nist/utils/__init__.pyi | 2 +- .../contrib/nist/utils/sampling/__init__.pyi | 8 +- .../test/contrib/test_cube_pickup_reset.py | 91 +++++++++++++++++++ .../isaaclab_tasks/test/test_reset_states.py | 3 + 13 files changed, 145 insertions(+), 26 deletions(-) create mode 100644 source/isaaclab/changelog.d/reset-buffer-review.fixed.rst create mode 100644 source/isaaclab_tasks/changelog.d/cube-pickup-review.fixed.rst create mode 100644 source/isaaclab_tasks/test/contrib/test_cube_pickup_reset.py diff --git a/scripts/environments/cube_pickup.py b/scripts/environments/cube_pickup.py index 36cf6b939f20..fc27c5feaf75 100644 --- a/scripts/environments/cube_pickup.py +++ b/scripts/environments/cube_pickup.py @@ -99,7 +99,7 @@ def _validate_replay(env: gym.Env) -> dict[str, bool]: raise RuntimeError("A reset state already satisfies the grasped-cube goal.") before = task.scene.get_state(is_relative=True) split = max(1, task.num_envs // 2) - task._reset_idx(torch.arange(split, device=task.device)) + task.reset(env_ids=torch.arange(split, device=task.device)) if success_cfg.func(task, **success_cfg.params).any(): raise RuntimeError("Partial replay produced an already successful reset state.") after = task.scene.get_state(is_relative=True) @@ -133,8 +133,7 @@ def _rollout(env: gym.Env, agent_cfg, args: argparse.Namespace) -> dict: elapsed = torch.zeros(task.num_envs, device=task.device) cube_start = mdp.object_position(task).clone() - orientation = task._tcp_pose()[:, 3:].clone() - orientation[:] = orientation.new_tensor((1.0, 0.0, 0.0, 0.0)) + orientation = cube_start.new_tensor((1.0, 0.0, 0.0, 0.0)).expand(task.num_envs, -1) completed = 0 successes = 0 remaining = torch.full((task.num_envs,), args.episodes // task.num_envs, dtype=torch.long, device=task.device) @@ -160,11 +159,11 @@ def _rollout(env: gym.Env, agent_cfg, args: argparse.Namespace) -> dict: finite &= bool(torch.isfinite(observations["policy"]).all().item()) # Same-step auto-reset restores the cube before this read. The successful terminal - # transition is counted from its binary reward, never from a post-reset observation. + # transition remains cached in the termination manager until the next step. finite &= bool(torch.isfinite(reward).all().item()) counted = done & (remaining > 0) completed += int(counted.sum().item()) - successes += int(((reward > 0.5) & counted).sum().item()) + successes += int((task.termination_manager.get_term("success") & counted).sum().item()) remaining[counted] -= 1 maximum_height = max(maximum_height, float(mdp.object_position(task)[:, 2].max().item())) elapsed += task.step_dt diff --git a/source/isaaclab/changelog.d/reset-buffer-review.fixed.rst b/source/isaaclab/changelog.d/reset-buffer-review.fixed.rst new file mode 100644 index 000000000000..079b6b87a193 --- /dev/null +++ b/source/isaaclab/changelog.d/reset-buffer-review.fixed.rst @@ -0,0 +1 @@ +* Derived reset-buffer rejection totals from the collection report to keep diagnostics consistent. diff --git a/source/isaaclab/isaaclab/envs/reset/__init__.pyi b/source/isaaclab/isaaclab/envs/reset/__init__.pyi index 4a717702294a..a5548e771f69 100644 --- a/source/isaaclab/isaaclab/envs/reset/__init__.pyi +++ b/source/isaaclab/isaaclab/envs/reset/__init__.pyi @@ -3,4 +3,6 @@ # # SPDX-License-Identifier: BSD-3-Clause +__all__ = ["ResetStateBuffer", "ResetStateBufferCfg"] + from .reset_state_buffer import ResetStateBuffer, ResetStateBufferCfg diff --git a/source/isaaclab/isaaclab/envs/reset/reset_state_buffer.py b/source/isaaclab/isaaclab/envs/reset/reset_state_buffer.py index 47494ade3097..9f2b97dff05f 100644 --- a/source/isaaclab/isaaclab/envs/reset/reset_state_buffer.py +++ b/source/isaaclab/isaaclab/envs/reset/reset_state_buffer.py @@ -61,8 +61,6 @@ def __init__(self, cfg: ResetStateBufferCfg) -> None: """Generator names, in collection order.""" self.group_ids = torch.empty(0, dtype=torch.long) """Generator index for every stored row, shape [num_states].""" - self.rejection_counts: dict[str, int] = {} - """Rejected candidates per named condition; one candidate can fail several conditions.""" self.collection_report: dict[str, dict[str, int]] = {} """Attempted, accepted, and rejected candidate counts for each generator.""" @@ -71,6 +69,19 @@ def num_states(self) -> int: """Number of collected states.""" return self.group_ids.numel() + @property + def rejection_counts(self) -> dict[str, int]: + """Derive rejected candidates per named condition from the collection report. + + One candidate can fail several conditions. Keys have the form ``generator/condition``. + """ + return { + f"{group}/{key.removeprefix('rejected/')}": count + for group, report in self.collection_report.items() + for key, count in report.items() + if key.startswith("rejected/") + } + def collect( self, env_ids: torch.Tensor, @@ -109,7 +120,6 @@ def collect( raise ValueError("The check name 'generator' is reserved for generator validity.") batches: list[ResetStateBuffer.State] = [] groups: list[torch.Tensor] = [] - self.rejection_counts = {} self.collection_report = {} devices = [env_ids.device.index] if env_ids.is_cuda else [] numpy_state, python_state = np.random.get_state(), random.getstate() @@ -137,9 +147,6 @@ def collect( f"{name}/{key} must return a boolean mask shaped {tuple(env_ids.shape)}." ) rejected = int((~mask).sum()) - self.rejection_counts[f"{name}/{key}"] = ( - self.rejection_counts.get(f"{name}/{key}", 0) + rejected - ) report[f"rejected/{key}"] = report.get(f"rejected/{key}", 0) + rejected valid &= mask selected = env_ids[valid][: quota - accepted] diff --git a/source/isaaclab/test/envs/test_reset_states.py b/source/isaaclab/test/envs/test_reset_states.py index 7b79b7eb6a7d..822dfc53f2ad 100644 --- a/source/isaaclab/test/envs/test_reset_states.py +++ b/source/isaaclab/test/envs/test_reset_states.py @@ -40,6 +40,12 @@ def capture(ids): "table": {"attempted": 8, "accepted": 4, "rejected/generator": 2, "rejected/reachable": 2}, "grasped": {"attempted": 8, "accepted": 3, "rejected/generator": 2, "rejected/reachable": 2}, } + assert buffer.rejection_counts == { + "table/generator": 2, + "table/reachable": 2, + "grasped/generator": 2, + "grasped/reachable": 2, + } selected = buffer.get_state(torch.tensor([6, 0, 4]))["rigid_object"]["cube"]["root_pose"] assert (selected[:, 0] * torch.tensor([-1, 1, -1]) > 1.0).all() torch.testing.assert_close(torch.get_rng_state(), torch_state) diff --git a/source/isaaclab_tasks/changelog.d/cube-pickup-review.fixed.rst b/source/isaaclab_tasks/changelog.d/cube-pickup-review.fixed.rst new file mode 100644 index 000000000000..b5c9b1053279 --- /dev/null +++ b/source/isaaclab_tasks/changelog.d/cube-pickup-review.fixed.rst @@ -0,0 +1,2 @@ +* Kept the cube pickup success reward invariant under timing overrides and excluded interrupted + viewer resets from reset-state outcome histories. diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env.py index 549b0f2b40ed..3e3b1429930d 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env.py @@ -18,7 +18,7 @@ from isaaclab.envs import ManagerBasedRLEnv from isaaclab.envs.reset import ResetStateBuffer from isaaclab.managers import SceneEntityCfg -from isaaclab.utils import clone +from isaaclab.utils import clone, instantiate from isaaclab.utils.math import compute_pose_error from isaaclab_tasks.utils import ResetStateSampler @@ -189,7 +189,7 @@ def _collect_reset_states(self) -> None: sampler_cfg = clone(self.cfg.reset_sampler) if self.cfg.reset_mode == "uniform": sampler_cfg.sampling.strategies = [UniformSamplingStrategyCfg()] - self.reset_sampler = ResetStateSampler(sampler_cfg, self.num_envs, self.reset_buffer.num_states, self.device) + self.reset_sampler = instantiate(sampler_cfg, self.num_envs, self.reset_buffer.num_states, self.device) self.generation_report = { "seed": self.cfg.reset_buffer.seed, "num_states": self.reset_buffer.num_states, @@ -225,7 +225,7 @@ def save_reset_buffer(self, path: str | Path) -> None: def _reset_idx(self, env_ids: torch.Tensor | slice): ids = self.scene._ALL_INDICES[env_ids] success = self.termination_manager.get_term("success")[ids].clone() - valid = (self.episode_length_buf[ids] > 0) & self.termination_manager.dones[ids] + valid = (self.episode_length_buf[ids] > 0) & self.reset_buf[ids] metrics: dict[str, torch.Tensor] = {} rows = None if self.reset_sampler is not None: diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env_cfg.py index 7652bb8df40e..7cc815edd365 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env_cfg.py @@ -40,7 +40,7 @@ @configclass class PhysicsCfg(PresetCfg): - """Supported physics backend for this example.""" + """Expose the supported ``physics=newton_mjwarp`` task selector.""" newton_mjwarp = NewtonCfg( solver_cfg=MJWarpSolverCfg( @@ -168,7 +168,7 @@ def __post_init__(self): @configclass class RewardsCfg: - """One terminal success reward; its weight cancels reward-manager integration.""" + """One unit terminal success reward.""" success = RewardTermCfg(func=pickup_mdp.success_reward, weight=1.0) @@ -221,7 +221,6 @@ def __post_init__(self): self.sim.physics = PhysicsCfg() self.episode_length_s = 12.0 self.is_finite_horizon = True - self.rewards.success.weight = 1.0 / (self.sim.dt * self.decimation) self.sim.visualizer_cfgs = VisualizerCfg(eye=(1.3, 1.1, 0.9), lookat=(0.45, 0.0, 0.15)) def play_mode(self): diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/mdp.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/mdp.py index a3aea2df001f..4e4546f72898 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/mdp.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/mdp.py @@ -12,7 +12,7 @@ import torch from isaaclab.managers import SceneEntityCfg -from isaaclab.utils.math import quat_apply +from isaaclab.utils.math import combine_frame_transforms from isaaclab_tasks.core.lift.mdp import object_reached_goal @@ -32,8 +32,15 @@ def hand_pose( robot = env.scene[asset_cfg.name] body_id = asset_cfg.body_ids[0] orientation = robot.data.body_link_quat_w.torch[:, body_id] - offset = orientation.new_tensor((0.0, 0.0, 0.107)).expand(env.num_envs, -1) - position = robot.data.body_link_pos_w.torch[:, body_id] + quat_apply(orientation, offset) + position = robot.data.body_link_pos_w.torch[:, body_id] + offset = env.cfg.actions.arm.body_offset + if offset is not None: + position, orientation = combine_frame_transforms( + position, + orientation, + position.new_tensor(offset.pos).expand_as(position), + orientation.new_tensor(offset.rot).expand_as(orientation), + ) return torch.cat((position - env.scene.env_origins, orientation), dim=-1) @@ -74,8 +81,8 @@ def goal_reached( def success_reward(env: ManagerBasedRLEnv) -> torch.Tensor: - """Return the binary goal success for the terminal transition.""" - return env.termination_manager.get_term("success").float() + """Return goal success per second [1/s] for a unit terminal reward.""" + return env.termination_manager.get_term("success").float() / env.step_dt def object_dropped(env: ManagerBasedRLEnv) -> torch.Tensor: diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/nist/utils/__init__.pyi b/source/isaaclab_tasks/isaaclab_tasks/contrib/nist/utils/__init__.pyi index 193b5bb4f97a..c7f9b447a380 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/nist/utils/__init__.pyi +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/nist/utils/__init__.pyi @@ -41,7 +41,7 @@ from .pose_offset import Offset from .rigid_object_hasher import RigidObjectHasher from .event_combinators import ChainedResetTerms, TermChoice, reset_accumulator from .reset_state import get_reset_state, set_reset_state -from isaaclab_tasks.utils.sampling import ( +from .sampling import ( BetaSamplingStrategy, BetaSamplingStrategyCfg, Sampler, diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/nist/utils/sampling/__init__.pyi b/source/isaaclab_tasks/isaaclab_tasks/contrib/nist/utils/sampling/__init__.pyi index 5fc33d20c3ab..847c8832fbca 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/nist/utils/sampling/__init__.pyi +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/nist/utils/sampling/__init__.pyi @@ -14,12 +14,14 @@ __all__ = [ "UniformSamplingStrategyCfg", ] -from isaaclab_tasks.utils.sampling import ( - Sampler, - SamplerCfg, +from .sampler import Sampler +from .sampler_cfg import SamplerCfg +from .sampling_strategies import ( BetaSamplingStrategy, SamplingStrategy, UniformSamplingStrategy, +) +from .sampling_strategies_cfg import ( BetaSamplingStrategyCfg, SamplingStrategyCfg, UniformSamplingStrategyCfg, diff --git a/source/isaaclab_tasks/test/contrib/test_cube_pickup_reset.py b/source/isaaclab_tasks/test/contrib/test_cube_pickup_reset.py new file mode 100644 index 000000000000..f267aed942c9 --- /dev/null +++ b/source/isaaclab_tasks/test/contrib/test_cube_pickup_reset.py @@ -0,0 +1,91 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""CPU regressions for pickup reward scaling and completed-episode bookkeeping.""" + +from types import SimpleNamespace + +import pytest +import torch + +from isaaclab.envs.reset import ResetStateBuffer, ResetStateBufferCfg +from isaaclab.managers import ( + ActionManager, + CommandManager, + CurriculumManager, + EventManager, + ObservationManager, + RecorderManager, + RewardManager, + TerminationManager, + TerminationTermCfg, +) +from isaaclab.utils import update_from_dict + +from isaaclab_tasks.contrib.cube_pickup.cube_pickup_env import CubePickupEnv +from isaaclab_tasks.contrib.cube_pickup.cube_pickup_env_cfg import CubePickupEnvCfg +from isaaclab_tasks.utils import ResetStateSampler, ResetStateSamplerCfg + +pytestmark = [pytest.mark.unit, pytest.mark.kitless, pytest.mark.windows_ci] + + +def _success(env): + return env.success_flags + + +def test_terminal_reward_stays_binary_after_timing_overrides(): + """Post-construction CLI overrides must not rescale the terminal +1 reward.""" + cfg = CubePickupEnvCfg() + update_from_dict(cfg, {"decimation": 2, "sim": {"dt": 1.0 / 240.0}}) + env = SimpleNamespace( + num_envs=2, + device="cpu", + step_dt=cfg.sim.dt * cfg.decimation, + sim=SimpleNamespace(is_playing=lambda: True), + success_flags=torch.tensor([True, False]), + ) + env.termination_manager = TerminationManager({"success": TerminationTermCfg(func=_success)}, env) + env.termination_manager.compute() + rewards = RewardManager(cfg.rewards, env).compute(dt=env.step_dt) + torch.testing.assert_close(rewards, torch.tensor([1.0, 0.0])) + + +def test_viewer_reset_does_not_record_an_unfinished_episode(): + """A viewer termination alias must not credit a manual reset as a completed failure.""" + env = CubePickupEnv.__new__(CubePickupEnv) + env._is_closed = True + env.cfg = CubePickupEnvCfg() + env.sim = SimpleNamespace(device="cpu", is_playing=lambda: True) + env.scene = SimpleNamespace(num_envs=2, _ALL_INDICES=torch.arange(2), reset=lambda env_ids: None) + # Only physics is omitted; the real task and manager reset bookkeeping still run. + env._restore_reset_state = lambda state, env_ids: None + env.extras = {} + env.episode_length_buf = torch.tensor([5, 5]) + env.success_flags = torch.tensor([True, False]) + env.termination_manager = TerminationManager({"success": TerminationTermCfg(func=_success)}, env) + for name, manager in ( + ("action_manager", ActionManager), + ("command_manager", CommandManager), + ("curriculum_manager", CurriculumManager), + ("event_manager", EventManager), + ("observation_manager", ObservationManager), + ("recorder_manager", RecorderManager), + ("reward_manager", RewardManager), + ): + setattr(env, name, manager(SimpleNamespace(), env)) + env.reset_buffer = ResetStateBuffer(ResetStateBufferCfg(size=2)) + env.reset_buffer.collect(torch.arange(2), lambda ids: None, lambda ids: {"row": ids[:, None]}) + env.reset_sampler = ResetStateSampler(ResetStateSamplerCfg(), 2, 2, "cpu") + env.reset_sampler.row_ids[:] = torch.tensor([0, 1]) + env.reset_sampler.success_monitor.success_update(torch.tensor([1]), torch.tensor([True])) + + # step() retains the natural compute result before the viewer marks its terminated alias. + env.reset_buf = env.termination_manager.compute() + env.reset_terminated = env.termination_manager.terminated + env.reset_terminated[1] = True + env._reset_idx(torch.tensor([0, 1])) + + torch.testing.assert_close(env.reset_sampler.success_monitor.get_success_rate(), torch.tensor([1.0, 1.0])) + assert env.extras["log"]["Reset/default_success"].item() == 1.0 diff --git a/source/isaaclab_tasks/test/test_reset_states.py b/source/isaaclab_tasks/test/test_reset_states.py index 16dc055631bd..032a322ecf38 100644 --- a/source/isaaclab_tasks/test/test_reset_states.py +++ b/source/isaaclab_tasks/test/test_reset_states.py @@ -5,10 +5,13 @@ """Outcome attribution and selective resets at the shared sampler boundary.""" +import pytest import torch from isaaclab_tasks.utils import ResetStateSampler, ResetStateSamplerCfg, SuccessMonitorCfg +pytestmark = [pytest.mark.unit, pytest.mark.kitless, pytest.mark.windows_ci] + def test_reset_records_previous_rows_and_preserves_unselected_environments(): """Startup masks and partial resets never credit a replacement row or an untouched episode.""" From 64f67b6613d9d089d8f4ec03d93df1f0ea259825 Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Mon, 9 Nov 2026 05:44:36 +0100 Subject: [PATCH 05/10] Fix cube pickup configuration and smoke collection --- source/isaaclab_tasks/changelog.d/cube-pickup-ci.fixed.rst | 2 ++ .../isaaclab_tasks/contrib/cube_pickup/cube_pickup_env_cfg.py | 4 +++- source/isaaclab_tasks/test/env_test_utils.py | 4 ++++ 3 files changed, 9 insertions(+), 1 deletion(-) create mode 100644 source/isaaclab_tasks/changelog.d/cube-pickup-ci.fixed.rst diff --git a/source/isaaclab_tasks/changelog.d/cube-pickup-ci.fixed.rst b/source/isaaclab_tasks/changelog.d/cube-pickup-ci.fixed.rst new file mode 100644 index 000000000000..5567b4c5461c --- /dev/null +++ b/source/isaaclab_tasks/changelog.d/cube-pickup-ci.fixed.rst @@ -0,0 +1,2 @@ +* Fixed the cube pickup environment class declaration and allowed its default reset collection + budget to fill the configured bank with one or two environments. diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env_cfg.py index 7cc815edd365..fcdcaf878bad 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env_cfg.py @@ -201,6 +201,8 @@ class EventsCfg: class CubePickupEnvCfg(ManagerBasedRLEnvCfg): """Reference task for sparse learning with generated and validated reset states.""" + class_type: type | str = "{DIR}.cube_pickup_env:CubePickupEnv" + scene: SceneCfg = SceneCfg(num_envs=1024, env_spacing=2.0) actions: ActionsCfg = ActionsCfg() observations: ObservationsCfg = ObservationsCfg() @@ -209,7 +211,7 @@ class CubePickupEnvCfg(ManagerBasedRLEnvCfg): events: EventsCfg = EventsCfg() commands: CommandsCfg = CommandsCfg() curriculum = None - reset_buffer: ResetStateBufferCfg = ResetStateBufferCfg(size=1024, max_batches=50, seed=0) + reset_buffer: ResetStateBufferCfg = ResetStateBufferCfg(size=1024, max_batches=512, seed=0) reset_sampler: ResetStateSamplerCfg = ResetStateSamplerCfg() reset_mode: Literal["adaptive", "uniform", "table"] = "adaptive" """Training distribution, or ordinary home/table starts for evaluation.""" diff --git a/source/isaaclab_tasks/test/env_test_utils.py b/source/isaaclab_tasks/test/env_test_utils.py index e32793d6658f..91042c83233c 100644 --- a/source/isaaclab_tasks/test/env_test_utils.py +++ b/source/isaaclab_tasks/test/env_test_utils.py @@ -15,6 +15,7 @@ import isaaclab.sim as sim_utils from isaaclab.app.settings_manager import get_settings_manager from isaaclab.envs.mdp.actions.actions_cfg import OperationalSpaceControllerActionCfg +from isaaclab.envs.reset import ResetStateBufferCfg from isaaclab.envs.utils.spaces import sample_space from isaaclab.physics import PhysicsCfg from isaaclab.sim import SimulationContext @@ -318,6 +319,9 @@ def _check_random_actions( env_cfg.scene.num_envs = num_envs else: env_cfg = parse_env_cfg(task_name, device=device, num_envs=num_envs) + reset_buffer_cfg = getattr(env_cfg, "reset_buffer", None) + if isinstance(reset_buffer_cfg, ResetStateBufferCfg): + reset_buffer_cfg.size = min(32, reset_buffer_cfg.size) reset_event = getattr(env_cfg.events, "reset_strategies", None) if reset_event is not None and "state_table_size" in reset_event.params: reset_event.params["state_table_size"] = min(32, reset_event.params["state_table_size"]) From 97715ea66fb9756802126bc71f18ef758c64d6bf Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Mon, 9 Nov 2026 06:56:04 +0100 Subject: [PATCH 06/10] Fix reset catalog persistence and replay validation --- docs/source/how-to/reset_state_buffers.rst | 8 +- scripts/environments/cube_pickup.py | 50 ++--- .../changelog.d/reset-buffer-review.fixed.rst | 1 + .../isaaclab/isaaclab/envs/reset/__init__.pyi | 3 +- .../isaaclab/envs/reset/reset_state_buffer.py | 35 ++-- .../envs/reset/reset_state_buffer_cfg.py | 22 +++ .../isaaclab/test/envs/test_reset_states.py | 23 ++- .../changelog.d/cube-pickup-review.fixed.rst | 1 + .../contrib/cube_pickup/cube_pickup_env.py | 171 ++++++++++-------- .../cube_pickup/cube_pickup_env_cfg.py | 15 +- .../isaaclab_tasks/contrib/cube_pickup/mdp.py | 10 +- .../isaaclab_tasks/utils/__init__.pyi | 6 +- .../isaaclab_tasks/utils/reset_states.py | 30 +-- .../isaaclab_tasks/utils/reset_states_cfg.py | 35 ++++ .../isaaclab_tasks/utils/sampling/__init__.py | 2 +- .../isaaclab_tasks/utils/sampling/sampler.py | 4 +- .../utils/sampling/sampler_cfg.py | 4 +- .../utils/sampling/sampling_strategies.py | 2 +- .../utils/sampling/sampling_strategies_cfg.py | 8 +- .../isaaclab_tasks/utils/success_monitor.py | 22 +-- .../utils/success_monitor_cfg.py | 35 ++++ .../test/contrib/test_cube_pickup_reset.py | 16 +- .../isaaclab_tasks/test/test_reset_states.py | 23 ++- 23 files changed, 309 insertions(+), 217 deletions(-) create mode 100644 source/isaaclab/isaaclab/envs/reset/reset_state_buffer_cfg.py create mode 100644 source/isaaclab_tasks/isaaclab_tasks/utils/reset_states_cfg.py create mode 100644 source/isaaclab_tasks/isaaclab_tasks/utils/success_monitor_cfg.py diff --git a/docs/source/how-to/reset_state_buffers.rst b/docs/source/how-to/reset_state_buffers.rst index 736bb56eec67..e8a018bd9a04 100644 --- a/docs/source/how-to/reset_state_buffers.rst +++ b/docs/source/how-to/reset_state_buffers.rst @@ -142,7 +142,7 @@ Use the cube pickup reference to compare sparse-reward training with ordinary an buffered starts. Generate grasp starts by physically approaching and closing the fingers. Starts captured after grasping must remain outside the goal region. The example succeeds as soon as a grasped cube reaches the commanded -point ``(0.5, 0.0, 0.15)`` [m] in environment coordinates, within a radius of +point ``(0.5, 0.0, 0.15)`` [m] in the robot root frame, within a radius of ``0.04`` [m]. The reward is a terminal ``+1`` on that transition. The registered ``IsaacContrib-Cube-Pickup-Franka`` task collects table, approach, @@ -152,7 +152,7 @@ binary pickup-to-point reward. Generate and inspect a small buffer first: .. code-block:: bash uv run python scripts/environments/cube_pickup.py --mode generate \ - --num_envs 64 --bank_size 256 --headless --output outputs/pickup/reset_states.json + --num_envs 64 --bank_size 256 --output outputs/pickup/reset_states.json Train with the existing RSL-RL runner. ``--num_envs`` is the number of environments per GPU in distributed training: @@ -160,7 +160,7 @@ per GPU in distributed training: .. code-block:: bash uv run isaaclab train_multigpu --num_gpus 4 --rl_library rsl_rl \ - --task IsaacContrib-Cube-Pickup-Franka --num_envs 1024 --headless + --task IsaacContrib-Cube-Pickup-Franka --num_envs 1024 The task saves its generated reset states alongside the training logs. Evaluate a saved checkpoint from ordinary table starts using a separate seed: @@ -169,7 +169,7 @@ saved checkpoint from ordinary table starts using a separate seed: uv run python scripts/environments/cube_pickup.py --mode evaluate \ --checkpoint /path/to/model.pt --num_envs 64 --episodes 512 \ - --seed 10000 --headless --output outputs/pickup/evaluation.json + --seed 10000 --output outputs/pickup/evaluation.json Evaluate the learned policy separately from ordinary table starts using held-out positions and seeds. Report that result separately from success under the adaptive diff --git a/scripts/environments/cube_pickup.py b/scripts/environments/cube_pickup.py index fc27c5feaf75..ae25ca97942f 100644 --- a/scripts/environments/cube_pickup.py +++ b/scripts/environments/cube_pickup.py @@ -25,6 +25,7 @@ import torch from isaaclab.app import add_launcher_args, launch_simulation +from isaaclab.app.logging_utils import configure_console_logging from isaaclab.utils import to_dict import isaaclab_tasks # noqa: F401 @@ -52,7 +53,16 @@ def main() -> None: parser.error("--checkpoint is required for policy evaluation") if min(args.num_envs, args.bank_size, args.episodes, args.steps) < 1: parser.error("environment, bank, episode and step counts must be positive") - + if args.mode == "generate": + bank_path = args.bank_output or args.output.with_suffix(".pt") + if bank_path.resolve() == args.output.resolve(): + parser.error("the reset-state bank and --output report must use different paths") + if bank_path.resolve() == bank_path.with_suffix(".json").resolve(): + parser.error("the reset-state bank must use a different path from its .json metadata") + elif args.mode == "evaluate" and args.checkpoint.resolve() == args.output.resolve(): + parser.error("--output must not overwrite the policy checkpoint") + + configure_console_logging(vars(args)) cfg, agent_cfg = resolve_task_config(TASK_NAME, "rsl_rl_cfg_entry_point", overrides=overrides) cfg.scene.num_envs = args.num_envs cfg.seed = args.seed @@ -68,7 +78,6 @@ def main() -> None: task = env.unwrapped if args.mode == "generate": validation = _validate_replay(env) - bank_path = args.bank_output or args.output.with_suffix(".pt") task.save_reset_buffer(bank_path) report = {**task.generation_report, "bank_path": str(bank_path), "replay_validation": validation} else: @@ -130,23 +139,21 @@ def _rollout(env: gym.Env, agent_cfg, args: argparse.Namespace) -> dict: observations = wrapped.get_observations() else: env.reset() + elapsed = torch.zeros(task.num_envs, device=task.device) + cube_start = mdp.object_position(task).clone() + orientation = cube_start.new_tensor((1.0, 0.0, 0.0, 0.0)).expand(task.num_envs, -1) - elapsed = torch.zeros(task.num_envs, device=task.device) - cube_start = mdp.object_position(task).clone() - orientation = cube_start.new_tensor((1.0, 0.0, 0.0, 0.0)).expand(task.num_envs, -1) - completed = 0 - successes = 0 + counts = torch.zeros(2, dtype=torch.long, device=task.device) remaining = torch.full((task.num_envs,), args.episodes // task.num_envs, dtype=torch.long, device=task.device) remaining[: args.episodes % task.num_envs] += 1 - finite = True - maximum_height = 0.0 + finite = torch.ones((), dtype=torch.bool, device=task.device) + maximum_height = torch.zeros((), device=task.device) with torch.inference_mode(): for step in range(args.steps): if args.mode == "evaluate": observations, reward, done, _ = wrapped.step(policy(observations)) done = done.bool() policy.reset(done) - finite &= bool(torch.isfinite(observations["policy"]).all().item()) else: target = torch.cat((cube_start, orientation), dim=-1) target[:, 2] += torch.where(elapsed < 5.0, 0.10, 0.0) @@ -156,21 +163,22 @@ def _rollout(env: gym.Env, agent_cfg, args: argparse.Namespace) -> dict: action[:, 6] = torch.where(elapsed >= 7.0, -1.0, 1.0) observations, reward, terminated, truncated, _ = env.step(action) done = terminated | truncated - finite &= bool(torch.isfinite(observations["policy"]).all().item()) # Same-step auto-reset restores the cube before this read. The successful terminal # transition remains cached in the termination manager until the next step. - finite &= bool(torch.isfinite(reward).all().item()) + finite &= torch.isfinite(observations["policy"]).all() & torch.isfinite(reward).all() counted = done & (remaining > 0) - completed += int(counted.sum().item()) - successes += int((task.termination_manager.get_term("success") & counted).sum().item()) + counts += torch.stack((counted.sum(), (task.termination_manager.get_term("success") & counted).sum())) remaining[counted] -= 1 - maximum_height = max(maximum_height, float(mdp.object_position(task)[:, 2].max().item())) - elapsed += task.step_dt - elapsed[done] = 0.0 - cube_start[done] = mdp.object_position(task)[done] - if not remaining.any() or not finite: + cube_position = mdp.object_position(task) + maximum_height = torch.fmax(maximum_height, cube_position[:, 2].max()) + if args.mode == "scripted": + elapsed += task.step_dt + elapsed[done] = 0.0 + cube_start[done] = cube_position[done] + if not (remaining.any() & finite): break + completed, successes = counts.tolist() return { "mode": args.mode, "task": TASK_NAME, @@ -184,8 +192,8 @@ def _rollout(env: gym.Env, agent_cfg, args: argparse.Namespace) -> dict: "completed_episodes": completed, "successful_episodes": successes, "success_rate": successes / completed if completed else 0.0, - "all_finite": finite, - "maximum_observed_cube_height_m": maximum_height, + "all_finite": bool(finite), + "maximum_observed_cube_height_m": float(maximum_height), } diff --git a/source/isaaclab/changelog.d/reset-buffer-review.fixed.rst b/source/isaaclab/changelog.d/reset-buffer-review.fixed.rst index 079b6b87a193..4bcbb9088cc1 100644 --- a/source/isaaclab/changelog.d/reset-buffer-review.fixed.rst +++ b/source/isaaclab/changelog.d/reset-buffer-review.fixed.rst @@ -1 +1,2 @@ * Derived reset-buffer rejection totals from the collection report to keep diagnostics consistent. +* Kept the previous reset catalog and diagnostics together when recollection fails. diff --git a/source/isaaclab/isaaclab/envs/reset/__init__.pyi b/source/isaaclab/isaaclab/envs/reset/__init__.pyi index a5548e771f69..8288e5b1f7c9 100644 --- a/source/isaaclab/isaaclab/envs/reset/__init__.pyi +++ b/source/isaaclab/isaaclab/envs/reset/__init__.pyi @@ -5,4 +5,5 @@ __all__ = ["ResetStateBuffer", "ResetStateBufferCfg"] -from .reset_state_buffer import ResetStateBuffer, ResetStateBufferCfg +from .reset_state_buffer import ResetStateBuffer +from .reset_state_buffer_cfg import ResetStateBufferCfg diff --git a/source/isaaclab/isaaclab/envs/reset/reset_state_buffer.py b/source/isaaclab/isaaclab/envs/reset/reset_state_buffer.py index 9f2b97dff05f..07e2b2e7f98c 100644 --- a/source/isaaclab/isaaclab/envs/reset/reset_state_buffer.py +++ b/source/isaaclab/isaaclab/envs/reset/reset_state_buffer.py @@ -14,21 +14,7 @@ import numpy as np import torch -from isaaclab.utils import configclass - - -@configclass -class ResetStateBufferCfg: - """Configuration for bounded reset-state collection.""" - - size: int = 4096 - """Number of accepted states to collect, shared approximately equally across named generators.""" - - max_batches: int = 100 - """Maximum candidate batches per generator before collection fails.""" - - seed: int = 0 - """Collection seed. The caller's Torch, NumPy, and Python random states are restored afterward.""" +from .reset_state_buffer_cfg import ResetStateBufferCfg class ResetStateBuffer: @@ -62,7 +48,7 @@ def __init__(self, cfg: ResetStateBufferCfg) -> None: self.group_ids = torch.empty(0, dtype=torch.long) """Generator index for every stored row, shape [num_states].""" self.collection_report: dict[str, dict[str, int]] = {} - """Attempted, accepted, and rejected candidate counts for each generator.""" + """Attempted, accepted, and rejected counts for the most recent successful collection.""" @property def num_states(self) -> int: @@ -99,6 +85,8 @@ def collect( The callbacks own simulation synchronization and any settling; collection does not step the simulation or advance the environment's episode bookkeeping itself. + Failed collection preserves the previous catalog, group metadata, and report. An exhausted + generation budget includes the failed attempt's report in its exception. Args: env_ids: Candidate environment indices, shape [N], on the simulation device. @@ -120,7 +108,7 @@ def collect( raise ValueError("The check name 'generator' is reserved for generator validity.") batches: list[ResetStateBuffer.State] = [] groups: list[torch.Tensor] = [] - self.collection_report = {} + collection_report: dict[str, dict[str, int]] = {} devices = [env_ids.device.index] if env_ids.is_cuda else [] numpy_state, python_state = np.random.get_state(), random.getstate() try: @@ -134,7 +122,7 @@ def collect( for group, (name, generator) in enumerate(generators.items()): quota = self.cfg.size // len(generators) + int(group < self.cfg.size % len(generators)) accepted = 0 - report = self.collection_report[name] = {"attempted": 0, "accepted": 0} + report = collection_report[name] = {"attempted": 0, "accepted": 0} for _ in range(self.cfg.max_batches): report["attempted"] += env_ids.numel() reported = generator(env_ids) @@ -164,14 +152,17 @@ def collect( if accepted < quota: raise RuntimeError( f"Reset group '{name}' collected {accepted}/{quota} states after " - f"{self.cfg.max_batches} batches. Rejections: {self.rejection_counts}" + f"{self.cfg.max_batches} batches. Collection report: {collection_report}" ) finally: np.random.set_state(numpy_state) random.setstate(python_state) - self.state = _concatenate_states(batches) - self.group_ids = torch.cat(groups).long() - self.group_names = tuple(generators) + self.state, self.group_ids, self.group_names, self.collection_report = ( + _concatenate_states(batches), + torch.cat(groups).long(), + tuple(generators), + collection_report, + ) def get_state(self, row_ids: torch.Tensor) -> ResetStateBuffer.State: """Return the selected rows of the captured state tree. diff --git a/source/isaaclab/isaaclab/envs/reset/reset_state_buffer_cfg.py b/source/isaaclab/isaaclab/envs/reset/reset_state_buffer_cfg.py new file mode 100644 index 000000000000..01c0c76d41d9 --- /dev/null +++ b/source/isaaclab/isaaclab/envs/reset/reset_state_buffer_cfg.py @@ -0,0 +1,22 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Configuration for bounded reset-state collection.""" + +from isaaclab.utils import configclass + + +@configclass +class ResetStateBufferCfg: + """Configuration for bounded reset-state collection.""" + + size: int = 4096 + """Number of accepted states to collect, shared approximately equally across named generators.""" + + max_batches: int = 100 + """Maximum candidate batches per generator before collection fails.""" + + seed: int = 0 + """Collection seed. The caller's Torch, NumPy, and Python random states are restored afterward.""" diff --git a/source/isaaclab/test/envs/test_reset_states.py b/source/isaaclab/test/envs/test_reset_states.py index 822dfc53f2ad..72d10790fbdc 100644 --- a/source/isaaclab/test/envs/test_reset_states.py +++ b/source/isaaclab/test/envs/test_reset_states.py @@ -51,24 +51,37 @@ def capture(ids): torch.testing.assert_close(torch.get_rng_state(), torch_state) np.testing.assert_equal(np.random.get_state(), numpy_state) assert random.getstate() == python_state + torch.rand(3) + np.random.random(3) + random.random() + torch_state, numpy_state, python_state = torch.get_rng_state(), np.random.get_state(), random.getstate() repeated = ResetStateBuffer(buffer.cfg) repeated.collect(env_ids, generators, capture, checks) torch.testing.assert_close( repeated.state["rigid_object"]["cube"]["root_pose"], buffer.state["rigid_object"]["cube"]["root_pose"] ) + torch.testing.assert_close(torch.get_rng_state(), torch_state) + np.testing.assert_equal(np.random.get_state(), numpy_state) + assert random.getstate() == python_state -def test_impossible_validation_is_bounded_and_reports_the_condition(): +def test_impossible_recollection_is_bounded_and_preserves_the_complete_catalog(): buffer = ResetStateBuffer(ResetStateBufferCfg(size=5, max_batches=2)) - with pytest.raises(RuntimeError, match="collected 0/5 states after 2 batches.*collision_free"): + buffer.collect(torch.arange(3), lambda ids: None, lambda ids: {"pose": ids[:, None].float()}) + catalog = buffer.get_state(torch.arange(5))["pose"] + with pytest.raises(RuntimeError, match="collected 0/5 states after 2 batches.*collision_free.*6"): buffer.collect( torch.arange(3), - lambda ids: None, + {"blocked": lambda ids: None}, lambda ids: {"pose": torch.zeros(len(ids), 7)}, {"collision_free": lambda ids: torch.zeros_like(ids, dtype=torch.bool)}, ) - assert buffer.num_states == 0 - assert buffer.rejection_counts == {"default/collision_free": 6} + assert buffer.num_states == 5 + torch.testing.assert_close(buffer.get_state(torch.arange(5))["pose"], catalog) + assert buffer.group_names == ("default",) + assert buffer.group_ids.tolist() == [0] * 5 + assert buffer.collection_report == {"default": {"attempted": 6, "accepted": 5}} + assert buffer.rejection_counts == {} with pytest.raises(ValueError, match="'generator' is reserved"): buffer.collect( torch.arange(3), diff --git a/source/isaaclab_tasks/changelog.d/cube-pickup-review.fixed.rst b/source/isaaclab_tasks/changelog.d/cube-pickup-review.fixed.rst index b5c9b1053279..bc4423fa3254 100644 --- a/source/isaaclab_tasks/changelog.d/cube-pickup-review.fixed.rst +++ b/source/isaaclab_tasks/changelog.d/cube-pickup-review.fixed.rst @@ -1,2 +1,3 @@ * Kept the cube pickup success reward invariant under timing overrides and excluded interrupted viewer resets from reset-state outcome histories. +* Revalidated physical attachment after grasp replay, respected configured action scales, and prevented reset-bank reports from overwriting saved states. diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env.py index 3e3b1429930d..3c0d98a8bed5 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env.py @@ -19,11 +19,10 @@ from isaaclab.envs.reset import ResetStateBuffer from isaaclab.managers import SceneEntityCfg from isaaclab.utils import clone, instantiate -from isaaclab.utils.math import compute_pose_error - -from isaaclab_tasks.utils import ResetStateSampler -from isaaclab_tasks.utils.sampling import UniformSamplingStrategyCfg +from isaaclab.utils.math import compute_pose_error, quat_apply_inverse +from ...utils import ResetStateSampler +from ...utils.sampling import UniformSamplingStrategyCfg from . import mdp as pickup_mdp from .cube_pickup_env_cfg import CubePickupEnvCfg @@ -43,14 +42,84 @@ def __init__(self, cfg: CubePickupEnvCfg, **kwargs): self._bank_generator.manual_seed(cfg.reset_buffer.seed) self._reset_generator = torch.Generator(device=self.device) self._reset_generator.manual_seed(torch.initial_seed() if cfg.seed is None else cfg.seed) - self._all_ids = torch.arange(self.num_envs, device=self.device) self.generation_report: dict = {} self.command_manager.reset() if cfg.reset_mode != "table": self._collect_reset_states() - def _tcp_pose(self) -> torch.Tensor: - return pickup_mdp.hand_pose(self, self._hand_cfg) + def scripted_action(self, target: torch.Tensor, *, close: bool) -> torch.Tensor: + """Create a bounded relative IK action for target poses [m, xyzw].""" + current = pickup_mdp.hand_pose(self, self._hand_cfg) + position_error, rotation_error = compute_pose_error( + current[:, :3], current[:, 3:], target[:, :3], target[:, 3:], rot_error_type="axis_angle" + ) + root_orientation = self.scene["robot"].data.root_quat_w.torch + delta = torch.cat( + ( + quat_apply_inverse(root_orientation, position_error), + quat_apply_inverse(root_orientation, rotation_error), + ), + dim=-1, + ) + arm = self.action_manager.get_term("arm") + action = torch.zeros((self.num_envs, 7), device=self.device) + action[:, :6] = torch.where(arm._scale != 0.0, (delta - arm._offset) / arm._scale, 0.0).clamp(-1.0, 1.0) + action[:, 6] = -1.0 if close else 1.0 + return action + + def save_reset_buffer(self, path: str | Path) -> None: + """Save generated scene states and stage metadata for reproducing the training distribution.""" + if self.reset_buffer is None: + raise ValueError("Table-only evaluation does not generate a reset buffer.") + path = Path(path) + report_path = path.with_suffix(".json") + if path.resolve() == report_path.resolve(): + raise ValueError("Reset bank and JSON report must use different paths.") + path.parent.mkdir(parents=True, exist_ok=True) + torch.save( + { + "state": self.reset_buffer.state, + "group_names": self.reset_buffer.group_names, + "group_ids": self.reset_buffer.group_ids, + "report": self.generation_report, + }, + path, + ) + report_path.write_text(json.dumps(self.generation_report, indent=2) + "\n") + + def _reset_idx(self, env_ids: torch.Tensor | slice): + ids = self.scene._ALL_INDICES[env_ids] + success = self.termination_manager.get_term("success")[ids].clone() + valid = (self.episode_length_buf[ids] > 0) & self.reset_buf[ids] + metrics: dict[str, torch.Tensor] = {} + rows = None + if self.reset_sampler is not None: + previous_rows = self.reset_sampler.row_ids[ids] + previous_groups = self.reset_buffer.group_ids[previous_rows] + counts = torch.zeros(len(self.reset_buffer.group_names), device=self.device) + counts.scatter_add_(0, previous_groups, valid.float()) + successes = torch.zeros_like(counts).scatter_add_(0, previous_groups, (success & valid).float()) + rates = successes / counts.clamp_min(1) + completed_counts = counts.tolist() + for group_id, name in enumerate(self.reset_buffer.group_names): + if completed_counts[group_id]: + metrics[f"Reset/{name}_success"] = rates[group_id] + rows = self.reset_sampler.reset(ids, success=success, valid=valid) + probabilities = torch.zeros_like(counts).scatter_add_( + 0, self.reset_buffer.group_ids, self.reset_sampler.probabilities + ) + for group_id, name in enumerate(self.reset_buffer.group_names): + metrics[f"Reset/{name}_probability"] = probabilities[group_id] + if any(completed_counts): + metrics["Metrics/success_rate"] = successes.sum() / counts.sum() + elif valid.any(): + metrics["Metrics/success_rate"] = (success & valid).float().sum() / valid.sum() + super()._reset_idx(env_ids) + if rows is None: + self._reset_table(ids) + else: + self._restore_reset_state(self.reset_buffer.get_state(rows), ids) + self.extras["log"].update(metrics) def _reset_table(self, env_ids: torch.Tensor, *, generating: bool = False) -> None: mdp.reset_scene_to_default(self, env_ids) @@ -77,28 +146,14 @@ def _physics_step(self, actions: torch.Tensor) -> None: self.sim.step(render=False) self.scene.update(self.physics_dt * steps_per_call) - def scripted_action(self, target: torch.Tensor, *, close: bool) -> torch.Tensor: - """Create a bounded relative IK action for target poses [m, xyzw].""" - current = self._tcp_pose() - position_error, rotation_error = compute_pose_error( - current[:, :3], current[:, 3:], target[:, :3], target[:, 3:], rot_error_type="axis_angle" - ) - action = torch.zeros((self.num_envs, 7), device=self.device) - action[:, :3] = (position_error / 0.025).clamp(-1.0, 1.0) - action[:, 3:6] = (rotation_error / 0.1).clamp(-1.0, 1.0) - action[:, 6] = -1.0 if close else 1.0 - return action - def _drive(self, target: torch.Tensor, duration: float, *, close: bool = False) -> None: for _ in range(math.ceil(duration / self.step_dt)): self._physics_step(self.scripted_action(target, close=close)) def _generate(self, env_ids: torch.Tensor, stage: str) -> torch.Tensor: - # All candidates in one batch share the same generator phase. Unselected environments - # may advance during prefill; the normal reset lifecycle runs before training begins. self._reset_table(env_ids, generating=True) self.action_manager.reset() - rest = self._tcp_pose().clone() + rest = pickup_mdp.hand_pose(self, self._hand_cfg) self._drive(rest, 0.2) if stage == "table": return self._candidate_valid(env_ids) @@ -114,18 +169,25 @@ def _generate(self, env_ids: torch.Tensor, stage: str) -> torch.Tensor: self._drive(target, 5.0) if stage == "approach": return self._candidate_valid(env_ids) & ( - torch.linalg.vector_norm(self._tcp_pose()[env_ids, :3] - target[env_ids, :3], dim=-1) < 0.02 + torch.linalg.vector_norm( + pickup_mdp.hand_pose(self, self._hand_cfg)[env_ids, :3] - target[env_ids, :3], dim=-1 + ) + < 0.02 ) target[:, :3] = cube_position if stage == "pregrasp": target[:, 2] += 0.10 * torch.rand((self.num_envs,), device=self.device, generator=self._bank_generator) self._drive(target, 2.0) - aligned = torch.linalg.vector_norm(self._tcp_pose()[env_ids, :3] - target[env_ids, :3], dim=-1) < 0.015 + aligned = ( + torch.linalg.vector_norm( + pickup_mdp.hand_pose(self, self._hand_cfg)[env_ids, :3] - target[env_ids, :3], dim=-1 + ) + < 0.015 + ) if stage == "pregrasp": return self._candidate_valid(env_ids) & aligned - # Establish the grasp through physical finger closure, then prove it can lift. self._drive(target, 0.6, close=True) target[:, 2] += 0.025 + 0.073 * torch.rand((self.num_envs,), device=self.device, generator=self._bank_generator) self._drive(target, 1.0, close=True) @@ -138,7 +200,8 @@ def _generate(self, env_ids: torch.Tensor, stage: str) -> torch.Tensor: self._restore_reset_state(state, env_ids) self._drive(target, 1.0, close=True) height = pickup_mdp.object_position(self)[env_ids, 2] - return valid & self._candidate_valid(env_ids) & (height > 0.035) + attached = torch.linalg.vector_norm(pickup_mdp.object_to_hand(self, self._hand_cfg)[env_ids], dim=-1) < 0.035 + return valid & self._candidate_valid(env_ids) & attached & (height > 0.035) def _candidate_valid(self, env_ids: torch.Tensor) -> torch.Tensor: robot = self.scene["robot"] @@ -161,10 +224,7 @@ def _candidate_valid(self, env_ids: torch.Tensor) -> torch.Tensor: def _capture(self, env_ids: torch.Tensor) -> dict: state = self.scene.get_state(is_relative=True) return { - kind: { - name: {field: value[env_ids].clone() for field, value in fields.items()} - for name, fields in assets.items() - } + kind: {name: {field: value[env_ids] for field, value in fields.items()} for name, fields in assets.items()} for kind, assets in state.items() } @@ -185,7 +245,7 @@ def _collect_reset_states(self) -> None: stage: (lambda env_ids, stage=stage: self._generate(env_ids, stage)) for stage in ("table", "approach", "pregrasp", "grasp") } - self.reset_buffer.collect(self._all_ids, generators, self._capture) + self.reset_buffer.collect(self.scene._ALL_INDICES, generators, self._capture) sampler_cfg = clone(self.cfg.reset_sampler) if self.cfg.reset_mode == "uniform": sampler_cfg.sampling.strategies = [UniformSamplingStrategyCfg()] @@ -193,10 +253,7 @@ def _collect_reset_states(self) -> None: self.generation_report = { "seed": self.cfg.reset_buffer.seed, "num_states": self.reset_buffer.num_states, - "stages": { - name: int((self.reset_buffer.group_ids == i).sum().item()) - for i, name in enumerate(self.reset_buffer.group_names) - }, + "stages": {name: report["accepted"] for name, report in self.reset_buffer.collection_report.items()}, "collection": self.reset_buffer.collection_report, "validation": "Finite state, low velocity, replayed physical grasp; no initial goal success.", } @@ -204,47 +261,3 @@ def _collect_reset_states(self) -> None: rank = os.getenv("RANK") filename = "reset_states.pt" if rank is None else f"reset_states_rank_{rank}.pt" self.save_reset_buffer(Path(self.cfg.log_dir) / filename) - - def save_reset_buffer(self, path: str | Path) -> None: - """Save generated scene states and stage metadata for reproducing the training distribution.""" - if self.reset_buffer is None: - raise ValueError("Table-only evaluation does not generate a reset buffer.") - path = Path(path) - path.parent.mkdir(parents=True, exist_ok=True) - torch.save( - { - "state": self.reset_buffer.state, - "group_names": self.reset_buffer.group_names, - "group_ids": self.reset_buffer.group_ids, - "report": self.generation_report, - }, - path, - ) - path.with_suffix(".json").write_text(json.dumps(self.generation_report, indent=2) + "\n") - - def _reset_idx(self, env_ids: torch.Tensor | slice): - ids = self.scene._ALL_INDICES[env_ids] - success = self.termination_manager.get_term("success")[ids].clone() - valid = (self.episode_length_buf[ids] > 0) & self.reset_buf[ids] - metrics: dict[str, torch.Tensor] = {} - rows = None - if self.reset_sampler is not None: - previous_rows = self.reset_sampler.row_ids[ids] - previous_groups = self.reset_buffer.group_ids[previous_rows] - for group_id, name in enumerate(self.reset_buffer.group_names): - mask = valid & (previous_groups == group_id) - if mask.any(): - metrics[f"Reset/{name}_success"] = success[mask].float().mean() - # Credit the row that produced the episode before clearing success and episode buffers. - rows = self.reset_sampler.reset(ids, success=success, valid=valid) - for group_id, name in enumerate(self.reset_buffer.group_names): - mask = self.reset_buffer.group_ids == group_id - metrics[f"Reset/{name}_probability"] = self.reset_sampler.probabilities[mask].sum() - if valid.any(): - metrics["Metrics/success_rate"] = success[valid].float().mean() - super()._reset_idx(env_ids) - if rows is None: - self._reset_table(ids) - else: - self._restore_reset_state(self.reset_buffer.get_state(rows), ids) - self.extras["log"].update(metrics) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env_cfg.py index fcdcaf878bad..4e0d79595a5b 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env_cfg.py @@ -19,7 +19,6 @@ from isaaclab.envs import ManagerBasedRLEnvCfg from isaaclab.envs.reset import ResetStateBufferCfg from isaaclab.managers import ( - EventTermCfg, ObservationGroupCfg, ObservationTermCfg, RewardTermCfg, @@ -30,11 +29,10 @@ from isaaclab.utils import configclass, replace from isaaclab.visualizers import VisualizerCfg -from isaaclab_tasks.core.lift.mdp import ObjectUniformPoseCommandCfg -from isaaclab_tasks.utils import PresetCfg, ResetStateSamplerCfg - from isaaclab_assets.robots import FRANKA_PANDA_HIGH_PD_CFG +from ...core.lift.mdp import ObjectUniformPoseCommandCfg +from ...utils import PresetCfg, ResetStateSamplerCfg from . import mdp as pickup_mdp @@ -190,13 +188,6 @@ class TerminationsCfg: dropped = TerminationTermCfg(func=pickup_mdp.object_dropped) -@configclass -class EventsCfg: - """Manager lifecycle reset; task-specific states are restored after manager cleanup.""" - - reset_scene = EventTermCfg(func=mdp.reset_scene_to_default, mode="reset") - - @configclass class CubePickupEnvCfg(ManagerBasedRLEnvCfg): """Reference task for sparse learning with generated and validated reset states.""" @@ -208,7 +199,7 @@ class CubePickupEnvCfg(ManagerBasedRLEnvCfg): observations: ObservationsCfg = ObservationsCfg() rewards: RewardsCfg = RewardsCfg() terminations: TerminationsCfg = TerminationsCfg() - events: EventsCfg = EventsCfg() + events: dict = {} commands: CommandsCfg = CommandsCfg() curriculum = None reset_buffer: ResetStateBufferCfg = ResetStateBufferCfg(size=1024, max_batches=512, seed=0) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/mdp.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/mdp.py index 4e4546f72898..ed2a247b9125 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/mdp.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/mdp.py @@ -14,7 +14,7 @@ from isaaclab.managers import SceneEntityCfg from isaaclab.utils.math import combine_frame_transforms -from isaaclab_tasks.core.lift.mdp import object_reached_goal +from ...core.lift.mdp import object_reached_goal if TYPE_CHECKING: from isaaclab.envs import ManagerBasedRLEnv @@ -33,13 +33,13 @@ def hand_pose( body_id = asset_cfg.body_ids[0] orientation = robot.data.body_link_quat_w.torch[:, body_id] position = robot.data.body_link_pos_w.torch[:, body_id] - offset = env.cfg.actions.arm.body_offset - if offset is not None: + arm = env.action_manager.get_term("arm") + if arm.cfg.body_offset is not None: position, orientation = combine_frame_transforms( position, orientation, - position.new_tensor(offset.pos).expand_as(position), - orientation.new_tensor(offset.rot).expand_as(orientation), + arm._offset_pos, + arm._offset_rot, ) return torch.cat((position - env.scene.env_origins, orientation), dim=-1) diff --git a/source/isaaclab_tasks/isaaclab_tasks/utils/__init__.pyi b/source/isaaclab_tasks/isaaclab_tasks/utils/__init__.pyi index 739c652b2ac6..850a0fa62118 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/utils/__init__.pyi +++ b/source/isaaclab_tasks/isaaclab_tasks/utils/__init__.pyi @@ -22,5 +22,7 @@ __all__ = [ from .hydra import PresetCfg, preset, resolve_task_config, resolve_presets, setup_preset_cli from .importer import import_packages from .parse_cfg import get_checkpoint_path, load_cfg_from_registry, parse_env_cfg -from .success_monitor import SuccessMonitor, SuccessMonitorCfg -from .reset_states import ResetStateSampler, ResetStateSamplerCfg +from .success_monitor import SuccessMonitor +from .success_monitor_cfg import SuccessMonitorCfg +from .reset_states import ResetStateSampler +from .reset_states_cfg import ResetStateSamplerCfg diff --git a/source/isaaclab_tasks/isaaclab_tasks/utils/reset_states.py b/source/isaaclab_tasks/isaaclab_tasks/utils/reset_states.py index 8c3fd5da48b4..a6ab209b7406 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/utils/reset_states.py +++ b/source/isaaclab_tasks/isaaclab_tasks/utils/reset_states.py @@ -9,27 +9,11 @@ import torch -from isaaclab.utils import configclass, instantiate +from isaaclab.utils import instantiate -from .sampling import BetaSamplingStrategyCfg, Sampler, SamplerCfg, UniformSamplingStrategyCfg -from .success_monitor import SuccessMonitor, SuccessMonitorCfg - - -@configclass -class ResetStateSamplerCfg: - """Configure outcome tracking and sampling independently of a task's state representation.""" - - class_type: type[ResetStateSampler] | str = "{DIR}.reset_states:ResetStateSampler" - """Runtime sampler implementation.""" - - success_monitor: SuccessMonitorCfg = SuccessMonitorCfg(monitored_history_len=50) - """Rolling episode history for each reset row.""" - - sampling: SamplerCfg = SamplerCfg( - strategies=[BetaSamplingStrategyCfg(target=0.5, kappa=2.0), UniformSamplingStrategyCfg(weight=0.05)], - eps=1.0e-4, - ) - """Sampling strategies; the default favors intermediate success while retaining all rows.""" +from .reset_states_cfg import ResetStateSamplerCfg +from .sampling import Sampler +from .success_monitor import SuccessMonitor class ResetStateSampler: @@ -63,7 +47,6 @@ def reset( env_ids: torch.Tensor, success: torch.Tensor | None = None, valid: torch.Tensor | None = None, - row_mask: torch.Tensor | None = None, ) -> torch.Tensor: """Record the finished episodes before selecting their next reset rows. @@ -75,8 +58,6 @@ def reset( env_ids: Resetting environment indices, shape [N], on the sampler device. success: Whether each selected episode succeeded, shape [N]. ``None`` skips recording. valid: Which selected outcomes to record, shape [N]. ``None`` records every outcome. - row_mask: Eligible catalog rows, shape [row_count]. ``None`` permits every row. - At least one permitted row must have positive sampling weight. Returns: The newly assigned reset-row indices, shape [N], in ``env_ids`` order. @@ -84,9 +65,6 @@ def reset( if success is not None: self.success_monitor.success_update(self.row_ids[env_ids], success, valid) self.probabilities = self.sampler.probabilities() - if row_mask is not None: - self.probabilities = self.probabilities * row_mask - self.probabilities.div_(self.probabilities.sum()) if env_ids.numel(): self.row_ids[env_ids] = self.sampler.sample(self.probabilities, env_ids.numel()) return self.row_ids[env_ids] diff --git a/source/isaaclab_tasks/isaaclab_tasks/utils/reset_states_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/utils/reset_states_cfg.py new file mode 100644 index 000000000000..c9352f406158 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/utils/reset_states_cfg.py @@ -0,0 +1,35 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Configuration for success-guided reset-row selection.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from isaaclab.utils import configclass + +from .sampling import BetaSamplingStrategyCfg, SamplerCfg, UniformSamplingStrategyCfg +from .success_monitor_cfg import SuccessMonitorCfg + +if TYPE_CHECKING: + from .reset_states import ResetStateSampler + + +@configclass +class ResetStateSamplerCfg: + """Configure outcome tracking and sampling independently of a task's state representation.""" + + class_type: type[ResetStateSampler] | str = "{DIR}.reset_states:ResetStateSampler" + """Runtime sampler implementation.""" + + success_monitor: SuccessMonitorCfg = SuccessMonitorCfg(monitored_history_len=50) + """Rolling episode history for each reset row.""" + + sampling: SamplerCfg = SamplerCfg( + strategies=[BetaSamplingStrategyCfg(target=0.5, kappa=2.0), UniformSamplingStrategyCfg(weight=0.05)], + eps=1.0e-4, + ) + """Sampling strategies; the default favors intermediate success while retaining all rows.""" diff --git a/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/__init__.py b/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/__init__.py index a72c683bbf2f..8fd0058143b3 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/__init__.py +++ b/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/__init__.py @@ -3,7 +3,7 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Sampling strategies for multi-task curriculum selection.""" +"""Success-guided sampling over fixed catalogs of task choices or reset states.""" from isaaclab.utils.module import lazy_export diff --git a/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampler.py b/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampler.py index 3249b720680e..a448e1dce266 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampler.py +++ b/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampler.py @@ -13,10 +13,10 @@ from isaaclab.utils import instantiate -from isaaclab_tasks.utils.sampling.sampling_strategies import SamplingStrategy +from .sampling_strategies import SamplingStrategy if TYPE_CHECKING: - from isaaclab_tasks.utils.sampling.sampler_cfg import SamplerCfg + from .sampler_cfg import SamplerCfg class Sampler: diff --git a/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampler_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampler_cfg.py index 44839269044f..177dfaaeab44 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampler_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampler_cfg.py @@ -8,10 +8,12 @@ from __future__ import annotations from dataclasses import field +from typing import TYPE_CHECKING from isaaclab.utils import configclass -from isaaclab_tasks.utils.sampling.sampler import Sampler +if TYPE_CHECKING: + from .sampler import Sampler @configclass diff --git a/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampling_strategies.py b/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampling_strategies.py index b5b07d7f2f83..048a2ea6a4fc 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampling_strategies.py +++ b/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampling_strategies.py @@ -17,7 +17,7 @@ import torch if TYPE_CHECKING: - from isaaclab_tasks.utils.sampling.sampling_strategies_cfg import ( + from .sampling_strategies_cfg import ( BetaSamplingStrategyCfg, UniformSamplingStrategyCfg, ) diff --git a/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampling_strategies_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampling_strategies_cfg.py index db5670d4355c..3b63f5fc521e 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampling_strategies_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampling_strategies_cfg.py @@ -7,12 +7,12 @@ from __future__ import annotations +from typing import TYPE_CHECKING + from isaaclab.utils import configclass -from isaaclab_tasks.utils.sampling.sampling_strategies import ( - BetaSamplingStrategy, - UniformSamplingStrategy, -) +if TYPE_CHECKING: + from .sampling_strategies import BetaSamplingStrategy, UniformSamplingStrategy @configclass diff --git a/source/isaaclab_tasks/isaaclab_tasks/utils/success_monitor.py b/source/isaaclab_tasks/isaaclab_tasks/utils/success_monitor.py index 7bafc1bf001e..1e2ad8815c0f 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/utils/success_monitor.py +++ b/source/isaaclab_tasks/isaaclab_tasks/utils/success_monitor.py @@ -9,27 +9,7 @@ import torch -from isaaclab.utils import configclass - - -@configclass -class SuccessMonitorCfg: - """Configuration for :class:`SuccessMonitor`.""" - - class_type: type[SuccessMonitor] | str = "{DIR}.success_monitor:SuccessMonitor" - """Monitor implementation, resolved when the environment starts.""" - - monitored_history_len: int = 10 - """Episodes remembered per slot.""" - - target_success_rate: float = 0.5 - """Success rate favored by sampling, in ``[0, 1]``.""" - - kappa: float = 1.0 - """Concentration around :attr:`target_success_rate`; zero is uniform.""" - - temperature: float = 1.0 - """Sampling-weight temperature, at or above ``1.0``.""" +from .success_monitor_cfg import SuccessMonitorCfg class SuccessMonitor: diff --git a/source/isaaclab_tasks/isaaclab_tasks/utils/success_monitor_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/utils/success_monitor_cfg.py new file mode 100644 index 000000000000..e50cd9e19e54 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/utils/success_monitor_cfg.py @@ -0,0 +1,35 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Configuration for per-slot success-rate monitoring.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from isaaclab.utils import configclass + +if TYPE_CHECKING: + from .success_monitor import SuccessMonitor + + +@configclass +class SuccessMonitorCfg: + """Configuration for :class:`SuccessMonitor`.""" + + class_type: type[SuccessMonitor] | str = "{DIR}.success_monitor:SuccessMonitor" + """Monitor implementation, resolved when the environment starts.""" + + monitored_history_len: int = 10 + """Episodes remembered per slot.""" + + target_success_rate: float = 0.5 + """Success rate favored by sampling, in ``[0, 1]``.""" + + kappa: float = 1.0 + """Concentration around :attr:`target_success_rate`; zero is uniform.""" + + temperature: float = 1.0 + """Sampling-weight temperature, at or above ``1.0``.""" diff --git a/source/isaaclab_tasks/test/contrib/test_cube_pickup_reset.py b/source/isaaclab_tasks/test/contrib/test_cube_pickup_reset.py index f267aed942c9..b818b497edae 100644 --- a/source/isaaclab_tasks/test/contrib/test_cube_pickup_reset.py +++ b/source/isaaclab_tasks/test/contrib/test_cube_pickup_reset.py @@ -3,7 +3,7 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""CPU regressions for pickup reward scaling and completed-episode bookkeeping.""" +"""CPU regressions for pickup rewards, completed episodes, and reset-bank persistence.""" from types import SimpleNamespace @@ -89,3 +89,17 @@ def test_viewer_reset_does_not_record_an_unfinished_episode(): torch.testing.assert_close(env.reset_sampler.success_monitor.get_success_rate(), torch.tensor([1.0, 1.0])) assert env.extras["log"]["Reset/default_success"].item() == 1.0 + + +def test_saving_reset_bank_rejects_its_json_report_path(tmp_path): + """Reject an output collision before replacing an existing catalog.""" + env = CubePickupEnv.__new__(CubePickupEnv) + env._is_closed = True + env.reset_buffer = ResetStateBuffer(ResetStateBufferCfg(size=1)) + env.reset_buffer.collect(torch.arange(1), lambda ids: None, lambda ids: {"row": ids[:, None]}) + env.generation_report = {} + path = tmp_path / "bank.json" + path.write_bytes(b"existing catalog") + with pytest.raises(ValueError, match="different paths"): + env.save_reset_buffer(path) + assert path.read_bytes() == b"existing catalog" diff --git a/source/isaaclab_tasks/test/test_reset_states.py b/source/isaaclab_tasks/test/test_reset_states.py index 032a322ecf38..f796c5b3187b 100644 --- a/source/isaaclab_tasks/test/test_reset_states.py +++ b/source/isaaclab_tasks/test/test_reset_states.py @@ -18,31 +18,36 @@ def test_reset_records_previous_rows_and_preserves_unselected_environments(): sampler = ResetStateSampler( ResetStateSamplerCfg(success_monitor=SuccessMonitorCfg(monitored_history_len=2)), 4, 3, "cpu" ) - sampler.row_ids[:] = torch.tensor([0, 0, 1, 1]) + sampler.row_ids[:] = torch.tensor([-1, -1, -1, 1]) selected = torch.tensor([2, 0, 1]) - only_row_two = torch.tensor([False, False, True]) # A zero-step startup has no outcome to record, even when success flags contain old values. - rows = sampler.reset(selected, torch.ones(3, dtype=torch.bool), torch.zeros(3, dtype=torch.bool), only_row_two) - assert rows.tolist() == [2, 2, 2] + rows = sampler.reset(selected, torch.ones(3, dtype=torch.bool), torch.zeros(3, dtype=torch.bool)) + torch.testing.assert_close(sampler.row_ids[selected], rows) + assert ((rows >= 0) & (rows < 3)).all() + assert sampler.row_ids[3] == 1 assert sampler.success_monitor.success_size.tolist() == [0, 0, 0] sampler.row_ids[selected] = torch.tensor([1, 0, 0]) - sampler.reset(selected, torch.tensor([False, True, False]), row_mask=only_row_two) - assert sampler.row_ids.tolist() == [2, 2, 2, 1] + with torch.random.fork_rng(devices=[]): + torch.manual_seed(17) + sampler.reset(selected, torch.tensor([False, True, False])) + assert sampler.row_ids[3] == 1 assert sampler.success_monitor.success_size.tolist() == [2, 1, 0] assert sampler.success_monitor.success_rate.tolist() == [0.5, 0.0, 0.0] # Record only one completed episode on the next reset; the masked one contributes nothing. + sampler.row_ids[torch.tensor([0, 2])] = 2 + untouched = sampler.row_ids[torch.tensor([1, 3])].clone() sampler.reset( torch.tensor([0, 2]), torch.tensor([True, False]), valid=torch.tensor([True, False]), - row_mask=torch.tensor([False, True, False]), ) assert sampler.success_monitor.success_size.tolist() == [2, 1, 1] assert sampler.success_monitor.success_rate.tolist() == [0.5, 0.0, 1.0] - assert sampler.row_ids.tolist() == [1, 2, 1, 1] + torch.testing.assert_close(sampler.row_ids[torch.tensor([1, 3])], untouched) + assigned = sampler.row_ids.clone() sampler.reset(torch.empty(0, dtype=torch.long)) assert sampler.success_monitor.success_size.tolist() == [2, 1, 1] - assert sampler.row_ids.tolist() == [1, 2, 1, 1] + torch.testing.assert_close(sampler.row_ids, assigned) def test_sampling_tracks_the_current_success_frontier_without_starving_other_rows(): From 0ec4a731ec65040ea51619333f90ad4b2f43dfee Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Mon, 9 Nov 2026 19:32:59 +0100 Subject: [PATCH 07/10] Fix seeded pickup resets and catalog ownership --- scripts/environments/cube_pickup.py | 2 +- .../changelog.d/reset-buffer-review.fixed.rst | 2 - .../changelog.d/reset-state-buffer.added.rst | 1 + .../isaaclab/envs/reset/reset_state_buffer.py | 58 +++++++++---------- .../envs/reset/reset_state_buffer_cfg.py | 2 +- .../isaaclab/test/envs/test_reset_states.py | 28 ++++----- .../changelog.d/cube-pickup-ci.fixed.rst | 2 - .../changelog.d/cube-pickup-review.fixed.rst | 3 - .../contrib/cube_pickup/cube_pickup_env.py | 55 ++++++++++++------ .../isaaclab_tasks/contrib/cube_pickup/mdp.py | 23 ++++---- .../isaaclab_tasks/utils/reset_states_cfg.py | 7 +-- .../utils/sampling/__init__.pyi | 6 +- .../utils/sampling/sampler_cfg.py | 8 +-- .../utils/sampling/sampling_strategies_cfg.py | 9 +-- .../utils/success_monitor_cfg.py | 7 +-- .../test/contrib/test_cube_pickup_reset.py | 10 ++-- .../isaaclab_tasks/test/test_reset_states.py | 4 +- 17 files changed, 106 insertions(+), 121 deletions(-) delete mode 100644 source/isaaclab/changelog.d/reset-buffer-review.fixed.rst delete mode 100644 source/isaaclab_tasks/changelog.d/cube-pickup-ci.fixed.rst delete mode 100644 source/isaaclab_tasks/changelog.d/cube-pickup-review.fixed.rst diff --git a/scripts/environments/cube_pickup.py b/scripts/environments/cube_pickup.py index ae25ca97942f..20a37ee84e0d 100644 --- a/scripts/environments/cube_pickup.py +++ b/scripts/environments/cube_pickup.py @@ -169,7 +169,7 @@ def _rollout(env: gym.Env, agent_cfg, args: argparse.Namespace) -> dict: finite &= torch.isfinite(observations["policy"]).all() & torch.isfinite(reward).all() counted = done & (remaining > 0) counts += torch.stack((counted.sum(), (task.termination_manager.get_term("success") & counted).sum())) - remaining[counted] -= 1 + remaining.sub_(counted.long()) cube_position = mdp.object_position(task) maximum_height = torch.fmax(maximum_height, cube_position[:, 2].max()) if args.mode == "scripted": diff --git a/source/isaaclab/changelog.d/reset-buffer-review.fixed.rst b/source/isaaclab/changelog.d/reset-buffer-review.fixed.rst deleted file mode 100644 index 4bcbb9088cc1..000000000000 --- a/source/isaaclab/changelog.d/reset-buffer-review.fixed.rst +++ /dev/null @@ -1,2 +0,0 @@ -* Derived reset-buffer rejection totals from the collection report to keep diagnostics consistent. -* Kept the previous reset catalog and diagnostics together when recollection fails. diff --git a/source/isaaclab/changelog.d/reset-state-buffer.added.rst b/source/isaaclab/changelog.d/reset-state-buffer.added.rst index aef99a71aff1..c8f1a072d3f0 100644 --- a/source/isaaclab/changelog.d/reset-state-buffer.added.rst +++ b/source/isaaclab/changelog.d/reset-state-buffer.added.rst @@ -1,2 +1,3 @@ * Added :class:`~isaaclab.envs.reset.ResetStateBuffer` for collecting validated reset states with bounded attempts, reproducible generation, and named acceptance checks. + Collection publishes complete catalogs and diagnostics together; exported states are copies. diff --git a/source/isaaclab/isaaclab/envs/reset/reset_state_buffer.py b/source/isaaclab/isaaclab/envs/reset/reset_state_buffer.py index 07e2b2e7f98c..20680ef3780e 100644 --- a/source/isaaclab/isaaclab/envs/reset/reset_state_buffer.py +++ b/source/isaaclab/isaaclab/envs/reset/reset_state_buffer.py @@ -41,8 +41,7 @@ def __init__(self, cfg: ResetStateBufferCfg) -> None: if type(cfg.seed) is not int or not 0 <= cfg.seed < 2**32: raise ValueError("seed must be an integer in [0, 2**32).") self.cfg = cfg - self.state: ResetStateBuffer.State = {} - """Collected tensor tree. Treat its tensors as read-only.""" + self._state: ResetStateBuffer.State = {} self.group_names: tuple[str, ...] = () """Generator names, in collection order.""" self.group_ids = torch.empty(0, dtype=torch.long) @@ -56,17 +55,12 @@ def num_states(self) -> int: return self.group_ids.numel() @property - def rejection_counts(self) -> dict[str, int]: - """Derive rejected candidates per named condition from the collection report. + def state(self) -> ResetStateBuffer.State: + """Copy of the collected tensor tree, preserving the captured fields' units. - One candidate can fail several conditions. Keys have the form ``generator/condition``. + Use :meth:`get_state` to copy only selected rows during reset. """ - return { - f"{group}/{key.removeprefix('rejected/')}": count - for group, report in self.collection_report.items() - for key, count in report.items() - if key.startswith("rejected/") - } + return _map_state(self._state, lambda value: value.clone()) def collect( self, @@ -106,8 +100,9 @@ def collect( checks = checks or {} if "generator" in checks: raise ValueError("The check name 'generator' is reserved for generator validity.") - batches: list[ResetStateBuffer.State] = [] - groups: list[torch.Tensor] = [] + state: ResetStateBuffer.State = {} + group_ids = torch.empty(self.cfg.size, dtype=torch.long, device=env_ids.device) + collected = 0 collection_report: dict[str, dict[str, int]] = {} devices = [env_ids.device.index] if env_ids.is_cuda else [] numpy_state, python_state = np.random.get_state(), random.getstate() @@ -140,11 +135,15 @@ def collect( selected = env_ids[valid][: quota - accepted] if selected.numel(): captured = capture(selected) - if not _validate_state(captured, selected.numel(), batches[0] if batches else None): + if not _validate_state(captured, selected.numel(), state if state else None): raise ValueError("capture must return a non-empty tree of batched tensors.") - state = _map_state(captured, lambda value: value.detach().clone()) - batches.append(state) - groups.append(torch.full_like(selected, group)) + if not state: + state = _map_state( + captured, lambda value: value.new_empty((self.cfg.size, *value.shape[1:])) + ) + _copy_state(state, captured, collected) + group_ids[collected : collected + selected.numel()] = group + collected += selected.numel() accepted += selected.numel() report["accepted"] = accepted if accepted == quota: @@ -157,9 +156,9 @@ def collect( finally: np.random.set_state(numpy_state) random.setstate(python_state) - self.state, self.group_ids, self.group_names, self.collection_report = ( - _concatenate_states(batches), - torch.cat(groups).long(), + self._state, self.group_ids, self.group_names, self.collection_report = ( + state, + group_ids, tuple(generators), collection_report, ) @@ -171,9 +170,9 @@ def get_state(self, row_ids: torch.Tensor) -> ResetStateBuffer.State: row_ids: Buffer row indices, shape [N], on the buffer device. Returns: - Tensor tree with a leading dimension of N and the captured fields' units. + Copied tensor tree with a leading dimension of N and the captured fields' units. """ - return _map_state(self.state, lambda value: value[row_ids]) + return _map_state(self._state, lambda value: value[row_ids]) def _validate_state( @@ -212,12 +211,9 @@ def _map_state( } -def _concatenate_states(states: list[ResetStateBuffer.State]) -> ResetStateBuffer.State: - return { - key: ( - _concatenate_states([state[key] for state in states]) - if isinstance(value, dict) - else torch.cat([state[key] for state in states]) - ) - for key, value in states[0].items() - } +def _copy_state(destination: ResetStateBuffer.State, source: ResetStateBuffer.State, start: int) -> None: + for key, value in source.items(): + if isinstance(value, dict): + _copy_state(destination[key], value, start) + else: + destination[key][start : start + value.shape[0]].copy_(value.detach()) diff --git a/source/isaaclab/isaaclab/envs/reset/reset_state_buffer_cfg.py b/source/isaaclab/isaaclab/envs/reset/reset_state_buffer_cfg.py index 01c0c76d41d9..d9dbda80dbff 100644 --- a/source/isaaclab/isaaclab/envs/reset/reset_state_buffer_cfg.py +++ b/source/isaaclab/isaaclab/envs/reset/reset_state_buffer_cfg.py @@ -5,7 +5,7 @@ """Configuration for bounded reset-state collection.""" -from isaaclab.utils import configclass +from ...utils import configclass @configclass diff --git a/source/isaaclab/test/envs/test_reset_states.py b/source/isaaclab/test/envs/test_reset_states.py index 72d10790fbdc..366625292310 100644 --- a/source/isaaclab/test/envs/test_reset_states.py +++ b/source/isaaclab/test/envs/test_reset_states.py @@ -16,7 +16,7 @@ pytestmark = [pytest.mark.unit, pytest.mark.kitless, pytest.mark.windows_ci] -def test_collection_rejects_candidates_covers_groups_and_preserves_rng(): +def test_collection_rejects_candidates_covers_groups_and_preserves_rng() -> None: values = torch.empty(4, 2) env_ids = torch.arange(4) @@ -40,14 +40,15 @@ def capture(ids): "table": {"attempted": 8, "accepted": 4, "rejected/generator": 2, "rejected/reachable": 2}, "grasped": {"attempted": 8, "accepted": 3, "rejected/generator": 2, "rejected/reachable": 2}, } - assert buffer.rejection_counts == { - "table/generator": 2, - "table/reachable": 2, - "grasped/generator": 2, - "grasped/reachable": 2, - } - selected = buffer.get_state(torch.tensor([6, 0, 4]))["rigid_object"]["cube"]["root_pose"] + row_ids = torch.tensor([6, 0, 4]) + selected = buffer.get_state(row_ids)["rigid_object"]["cube"]["root_pose"] assert (selected[:, 0] * torch.tensor([-1, 1, -1]) > 1.0).all() + expected = selected.clone() + values.zero_() + selected.zero_() + exported = buffer.state + exported["rigid_object"]["cube"]["root_pose"].zero_() + torch.testing.assert_close(buffer.get_state(row_ids)["rigid_object"]["cube"]["root_pose"], expected) torch.testing.assert_close(torch.get_rng_state(), torch_state) np.testing.assert_equal(np.random.get_state(), numpy_state) assert random.getstate() == python_state @@ -65,23 +66,22 @@ def capture(ids): assert random.getstate() == python_state -def test_impossible_recollection_is_bounded_and_preserves_the_complete_catalog(): +def test_impossible_recollection_is_bounded_and_preserves_the_complete_catalog() -> None: buffer = ResetStateBuffer(ResetStateBufferCfg(size=5, max_batches=2)) buffer.collect(torch.arange(3), lambda ids: None, lambda ids: {"pose": ids[:, None].float()}) catalog = buffer.get_state(torch.arange(5))["pose"] - with pytest.raises(RuntimeError, match="collected 0/5 states after 2 batches.*collision_free.*6"): + with pytest.raises(RuntimeError, match="collected 2/5 states after 2 batches.*collision_free.*4"): buffer.collect( torch.arange(3), {"blocked": lambda ids: None}, - lambda ids: {"pose": torch.zeros(len(ids), 7)}, - {"collision_free": lambda ids: torch.zeros_like(ids, dtype=torch.bool)}, + lambda ids: {"pose": torch.full((len(ids), 1), 999.0)}, + {"collision_free": lambda ids: ids == 1}, ) assert buffer.num_states == 5 torch.testing.assert_close(buffer.get_state(torch.arange(5))["pose"], catalog) assert buffer.group_names == ("default",) assert buffer.group_ids.tolist() == [0] * 5 assert buffer.collection_report == {"default": {"attempted": 6, "accepted": 5}} - assert buffer.rejection_counts == {} with pytest.raises(ValueError, match="'generator' is reserved"): buffer.collect( torch.arange(3), @@ -91,7 +91,7 @@ def test_impossible_recollection_is_bounded_and_preserves_the_complete_catalog() ) -def test_capture_requires_selected_rows_and_a_consistent_state_tree(): +def test_capture_requires_selected_rows_and_a_consistent_state_tree() -> None: buffer = ResetStateBuffer(ResetStateBufferCfg(size=3, max_batches=2)) with pytest.raises(ValueError, match="leading dimension of 2"): buffer.collect(torch.arange(3), lambda ids: ids > 0, lambda ids: {"pose": torch.zeros(3, 7)}) diff --git a/source/isaaclab_tasks/changelog.d/cube-pickup-ci.fixed.rst b/source/isaaclab_tasks/changelog.d/cube-pickup-ci.fixed.rst deleted file mode 100644 index 5567b4c5461c..000000000000 --- a/source/isaaclab_tasks/changelog.d/cube-pickup-ci.fixed.rst +++ /dev/null @@ -1,2 +0,0 @@ -* Fixed the cube pickup environment class declaration and allowed its default reset collection - budget to fill the configured bank with one or two environments. diff --git a/source/isaaclab_tasks/changelog.d/cube-pickup-review.fixed.rst b/source/isaaclab_tasks/changelog.d/cube-pickup-review.fixed.rst deleted file mode 100644 index bc4423fa3254..000000000000 --- a/source/isaaclab_tasks/changelog.d/cube-pickup-review.fixed.rst +++ /dev/null @@ -1,3 +0,0 @@ -* Kept the cube pickup success reward invariant under timing overrides and excluded interrupted - viewer resets from reset-state outcome histories. -* Revalidated physical attachment after grasp replay, respected configured action scales, and prevented reset-bank reports from overwriting saved states. diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env.py index 3c0d98a8bed5..2be51c342d93 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env.py @@ -32,23 +32,44 @@ class CubePickupEnv(ManagerBasedRLEnv): cfg: CubePickupEnvCfg - def __init__(self, cfg: CubePickupEnvCfg, **kwargs): + def __init__(self, cfg: CubePickupEnvCfg, **kwargs) -> None: self.reset_buffer: ResetStateBuffer | None = None self.reset_sampler: ResetStateSampler | None = None + self._arm_scale = torch.tensor(cfg.actions.arm.scale, dtype=torch.float32, device=cfg.sim.device).expand(6) + self._arm_offset = torch.tensor(cfg.actions.arm.offset, dtype=torch.float32, device=cfg.sim.device).expand(6) + offset = cfg.actions.arm.body_offset + self._tcp_offset_pos = ( + torch.tensor(offset.pos, dtype=torch.float32, device=cfg.sim.device).expand(cfg.scene.num_envs, -1) + if offset is not None + else None + ) + self._tcp_offset_rot = ( + torch.tensor(offset.rot, dtype=torch.float32, device=cfg.sim.device).expand(cfg.scene.num_envs, -1) + if offset is not None + else None + ) super().__init__(cfg, **kwargs) self._hand_cfg = SceneEntityCfg("robot", body_names="panda_hand") self._hand_cfg.resolve(self.scene) self._bank_generator = torch.Generator(device=self.device) self._bank_generator.manual_seed(cfg.reset_buffer.seed) - self._reset_generator = torch.Generator(device=self.device) - self._reset_generator.manual_seed(torch.initial_seed() if cfg.seed is None else cfg.seed) self.generation_report: dict = {} self.command_manager.reset() if cfg.reset_mode != "table": self._collect_reset_states() def scripted_action(self, target: torch.Tensor, *, close: bool) -> torch.Tensor: - """Create a bounded relative IK action for target poses [m, xyzw].""" + """Create normalized relative IK actions for target grasp-center poses. + + Args: + target: Poses with shape (num_envs, 7). Positions [m] are relative to environment + origins in world axes; orientations are world-frame quaternions in xyzw order. + close: Whether to close the gripper. + + Returns: + Actions with shape (num_envs, 7): scaled root-frame translation and axis-angle + rotation increments, followed by the binary gripper command (-1 closed, +1 open). + """ current = pickup_mdp.hand_pose(self, self._hand_cfg) position_error, rotation_error = compute_pose_error( current[:, :3], current[:, 3:], target[:, :3], target[:, 3:], rot_error_type="axis_angle" @@ -61,9 +82,10 @@ def scripted_action(self, target: torch.Tensor, *, close: bool) -> torch.Tensor: ), dim=-1, ) - arm = self.action_manager.get_term("arm") action = torch.zeros((self.num_envs, 7), device=self.device) - action[:, :6] = torch.where(arm._scale != 0.0, (delta - arm._offset) / arm._scale, 0.0).clamp(-1.0, 1.0) + action[:, :6] = torch.where(self._arm_scale != 0.0, (delta - self._arm_offset) / self._arm_scale, 0.0).clamp( + -1.0, 1.0 + ) action[:, 6] = -1.0 if close else 1.0 return action @@ -87,9 +109,9 @@ def save_reset_buffer(self, path: str | Path) -> None: ) report_path.write_text(json.dumps(self.generation_report, indent=2) + "\n") - def _reset_idx(self, env_ids: torch.Tensor | slice): - ids = self.scene._ALL_INDICES[env_ids] - success = self.termination_manager.get_term("success")[ids].clone() + def _reset_idx(self, env_ids: torch.Tensor | slice) -> None: + ids = self.scene._ALL_INDICES[env_ids] if isinstance(env_ids, slice) else env_ids + success = self.termination_manager.get_term("success")[ids] valid = (self.episode_length_buf[ids] > 0) & self.reset_buf[ids] metrics: dict[str, torch.Tensor] = {} rows = None @@ -100,20 +122,17 @@ def _reset_idx(self, env_ids: torch.Tensor | slice): counts.scatter_add_(0, previous_groups, valid.float()) successes = torch.zeros_like(counts).scatter_add_(0, previous_groups, (success & valid).float()) rates = successes / counts.clamp_min(1) - completed_counts = counts.tolist() for group_id, name in enumerate(self.reset_buffer.group_names): - if completed_counts[group_id]: - metrics[f"Reset/{name}_success"] = rates[group_id] + metrics[f"Reset/{name}_success"] = rates[group_id] rows = self.reset_sampler.reset(ids, success=success, valid=valid) probabilities = torch.zeros_like(counts).scatter_add_( 0, self.reset_buffer.group_ids, self.reset_sampler.probabilities ) for group_id, name in enumerate(self.reset_buffer.group_names): metrics[f"Reset/{name}_probability"] = probabilities[group_id] - if any(completed_counts): - metrics["Metrics/success_rate"] = successes.sum() / counts.sum() - elif valid.any(): - metrics["Metrics/success_rate"] = (success & valid).float().sum() / valid.sum() + metrics["Metrics/success_rate"] = successes.sum() / counts.sum().clamp_min(1) + else: + metrics["Metrics/success_rate"] = (success & valid).float().sum() / valid.sum().clamp_min(1) super()._reset_idx(env_ids) if rows is None: self._reset_table(ids) @@ -125,7 +144,7 @@ def _reset_table(self, env_ids: torch.Tensor, *, generating: bool = False) -> No mdp.reset_scene_to_default(self, env_ids) cube = self.scene["object"] state = cube.data.default_root_state.torch[env_ids].clone() - generator = self._bank_generator if generating else self._reset_generator + generator = self._bank_generator if generating else None offsets = torch.rand((env_ids.numel(), 2), device=self.device, generator=generator) state[:, 0] = 0.45 + 0.10 * offsets[:, 0] state[:, 1] = -0.08 + 0.16 * offsets[:, 1] @@ -221,7 +240,7 @@ def _candidate_valid(self, env_ids: torch.Tensor) -> torch.Tensor: & (robot.data.joint_vel.torch[env_ids].abs().amax(dim=-1) < 3.0) ) - def _capture(self, env_ids: torch.Tensor) -> dict: + def _capture(self, env_ids: torch.Tensor) -> ResetStateBuffer.State: state = self.scene.get_state(is_relative=True) return { kind: {name: {field: value[env_ids] for field, value in fields.items()} for name, fields in assets.items()} diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/mdp.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/mdp.py index ed2a247b9125..0fe22d807be5 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/mdp.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/mdp.py @@ -21,33 +21,30 @@ def object_position(env: ManagerBasedRLEnv) -> torch.Tensor: - """Cube center position relative to the environment origin [m].""" + """Cube center positions [m] relative to environment origins in world axes, shape (num_envs, 3).""" return env.scene["object"].data.root_pos_w.torch - env.scene.env_origins def hand_pose( env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot", body_names="panda_hand") ) -> torch.Tensor: - """Grasp-center position [m] and orientation [xyzw] relative to the environment origin.""" + """Grasp-center poses with shape (num_envs, 7). + + Positions [m] are relative to environment origins in world axes; orientations are + world-frame quaternions in xyzw order. + """ robot = env.scene[asset_cfg.name] body_id = asset_cfg.body_ids[0] orientation = robot.data.body_link_quat_w.torch[:, body_id] position = robot.data.body_link_pos_w.torch[:, body_id] - arm = env.action_manager.get_term("arm") - if arm.cfg.body_offset is not None: - position, orientation = combine_frame_transforms( - position, - orientation, - arm._offset_pos, - arm._offset_rot, - ) + position, orientation = combine_frame_transforms(position, orientation, env._tcp_offset_pos, env._tcp_offset_rot) return torch.cat((position - env.scene.env_origins, orientation), dim=-1) def object_to_hand( env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot", body_names="panda_hand") ) -> torch.Tensor: - """Cube displacement from the grasp center [m].""" + """Cube-minus-grasp-center displacements [m] in world axes, shape (num_envs, 3).""" return object_position(env) - hand_pose(env, asset_cfg)[:, :3] @@ -81,11 +78,11 @@ def goal_reached( def success_reward(env: ManagerBasedRLEnv) -> torch.Tensor: - """Return goal success per second [1/s] for a unit terminal reward.""" + """Return goal success per second [1/s], shape (num_envs,), for a unit terminal reward.""" return env.termination_manager.get_term("success").float() / env.step_dt def object_dropped(env: ManagerBasedRLEnv) -> torch.Tensor: - """Terminate when the cube leaves the table workspace [m].""" + """Return workspace-exit flags with shape (num_envs,), using positions in environment-frame [m].""" position = object_position(env) return (position[:, 2] < -0.02) | (position[:, 0] < 0.15) | (position[:, 0] > 0.85) | (position[:, 1].abs() > 0.45) diff --git a/source/isaaclab_tasks/isaaclab_tasks/utils/reset_states_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/utils/reset_states_cfg.py index c9352f406158..b81c7761b262 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/utils/reset_states_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/utils/reset_states_cfg.py @@ -7,22 +7,17 @@ from __future__ import annotations -from typing import TYPE_CHECKING - from isaaclab.utils import configclass from .sampling import BetaSamplingStrategyCfg, SamplerCfg, UniformSamplingStrategyCfg from .success_monitor_cfg import SuccessMonitorCfg -if TYPE_CHECKING: - from .reset_states import ResetStateSampler - @configclass class ResetStateSamplerCfg: """Configure outcome tracking and sampling independently of a task's state representation.""" - class_type: type[ResetStateSampler] | str = "{DIR}.reset_states:ResetStateSampler" + class_type: type | str = "{DIR}.reset_states:ResetStateSampler" """Runtime sampler implementation.""" success_monitor: SuccessMonitorCfg = SuccessMonitorCfg(monitored_history_len=50) diff --git a/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/__init__.pyi b/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/__init__.pyi index 847c8832fbca..b3b708b8fa22 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/__init__.pyi +++ b/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/__init__.pyi @@ -16,11 +16,7 @@ __all__ = [ from .sampler import Sampler from .sampler_cfg import SamplerCfg -from .sampling_strategies import ( - BetaSamplingStrategy, - SamplingStrategy, - UniformSamplingStrategy, -) +from .sampling_strategies import BetaSamplingStrategy, SamplingStrategy, UniformSamplingStrategy from .sampling_strategies_cfg import ( BetaSamplingStrategyCfg, SamplingStrategyCfg, diff --git a/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampler_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampler_cfg.py index 177dfaaeab44..a63a09f8171a 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampler_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampler_cfg.py @@ -8,21 +8,19 @@ from __future__ import annotations from dataclasses import field -from typing import TYPE_CHECKING from isaaclab.utils import configclass -if TYPE_CHECKING: - from .sampler import Sampler +from .sampling_strategies_cfg import SamplingStrategyCfg @configclass class SamplerCfg: """Blueprint for a :class:`Sampler`.""" - class_type: type[Sampler] | str = "{DIR}.sampler:Sampler" + class_type: type | str = "{DIR}.sampler:Sampler" """Runtime sampler class.""" - strategies: list = field(default_factory=list) + strategies: list[SamplingStrategyCfg] = field(default_factory=list) """Weighted sampling-strategy cfgs composed by the sampler.""" eps: float = 1e-3 """Soft floor on per-item probability before normalization.""" diff --git a/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampling_strategies_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampling_strategies_cfg.py index 3b63f5fc521e..8ad2f53ef8d7 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampling_strategies_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/utils/sampling/sampling_strategies_cfg.py @@ -7,13 +7,8 @@ from __future__ import annotations -from typing import TYPE_CHECKING - from isaaclab.utils import configclass -if TYPE_CHECKING: - from .sampling_strategies import BetaSamplingStrategy, UniformSamplingStrategy - @configclass class BetaSamplingStrategyCfg: @@ -32,7 +27,7 @@ class BetaSamplingStrategyCfg: 0 target 1 """ - class_type: type[BetaSamplingStrategy] | str = "{DIR}.sampling_strategies:BetaSamplingStrategy" + class_type: type | str = "{DIR}.sampling_strategies:BetaSamplingStrategy" """Runtime strategy class.""" weight: float = 1.0 """Multiplier on this strategy's score before sampler normalization.""" @@ -58,7 +53,7 @@ class UniformSamplingStrategyCfg: +----------------------------> item index """ - class_type: type[UniformSamplingStrategy] | str = "{DIR}.sampling_strategies:UniformSamplingStrategy" + class_type: type | str = "{DIR}.sampling_strategies:UniformSamplingStrategy" """Runtime strategy class.""" weight: float = 1.0 """Multiplier on this strategy's constant score before sampler normalization.""" diff --git a/source/isaaclab_tasks/isaaclab_tasks/utils/success_monitor_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/utils/success_monitor_cfg.py index e50cd9e19e54..3ad2787a7df6 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/utils/success_monitor_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/utils/success_monitor_cfg.py @@ -7,19 +7,14 @@ from __future__ import annotations -from typing import TYPE_CHECKING - from isaaclab.utils import configclass -if TYPE_CHECKING: - from .success_monitor import SuccessMonitor - @configclass class SuccessMonitorCfg: """Configuration for :class:`SuccessMonitor`.""" - class_type: type[SuccessMonitor] | str = "{DIR}.success_monitor:SuccessMonitor" + class_type: type | str = "{DIR}.success_monitor:SuccessMonitor" """Monitor implementation, resolved when the environment starts.""" monitored_history_len: int = 10 diff --git a/source/isaaclab_tasks/test/contrib/test_cube_pickup_reset.py b/source/isaaclab_tasks/test/contrib/test_cube_pickup_reset.py index b818b497edae..a36f2c149ad5 100644 --- a/source/isaaclab_tasks/test/contrib/test_cube_pickup_reset.py +++ b/source/isaaclab_tasks/test/contrib/test_cube_pickup_reset.py @@ -5,6 +5,7 @@ """CPU regressions for pickup rewards, completed episodes, and reset-bank persistence.""" +from pathlib import Path from types import SimpleNamespace import pytest @@ -31,11 +32,11 @@ pytestmark = [pytest.mark.unit, pytest.mark.kitless, pytest.mark.windows_ci] -def _success(env): +def _success(env) -> torch.Tensor: return env.success_flags -def test_terminal_reward_stays_binary_after_timing_overrides(): +def test_terminal_reward_stays_binary_after_timing_overrides() -> None: """Post-construction CLI overrides must not rescale the terminal +1 reward.""" cfg = CubePickupEnvCfg() update_from_dict(cfg, {"decimation": 2, "sim": {"dt": 1.0 / 240.0}}) @@ -52,7 +53,7 @@ def test_terminal_reward_stays_binary_after_timing_overrides(): torch.testing.assert_close(rewards, torch.tensor([1.0, 0.0])) -def test_viewer_reset_does_not_record_an_unfinished_episode(): +def test_viewer_reset_does_not_record_an_unfinished_episode() -> None: """A viewer termination alias must not credit a manual reset as a completed failure.""" env = CubePickupEnv.__new__(CubePickupEnv) env._is_closed = True @@ -91,12 +92,11 @@ def test_viewer_reset_does_not_record_an_unfinished_episode(): assert env.extras["log"]["Reset/default_success"].item() == 1.0 -def test_saving_reset_bank_rejects_its_json_report_path(tmp_path): +def test_saving_reset_bank_rejects_its_json_report_path(tmp_path: Path) -> None: """Reject an output collision before replacing an existing catalog.""" env = CubePickupEnv.__new__(CubePickupEnv) env._is_closed = True env.reset_buffer = ResetStateBuffer(ResetStateBufferCfg(size=1)) - env.reset_buffer.collect(torch.arange(1), lambda ids: None, lambda ids: {"row": ids[:, None]}) env.generation_report = {} path = tmp_path / "bank.json" path.write_bytes(b"existing catalog") diff --git a/source/isaaclab_tasks/test/test_reset_states.py b/source/isaaclab_tasks/test/test_reset_states.py index f796c5b3187b..dc3c528e4201 100644 --- a/source/isaaclab_tasks/test/test_reset_states.py +++ b/source/isaaclab_tasks/test/test_reset_states.py @@ -13,7 +13,7 @@ pytestmark = [pytest.mark.unit, pytest.mark.kitless, pytest.mark.windows_ci] -def test_reset_records_previous_rows_and_preserves_unselected_environments(): +def test_reset_records_previous_rows_and_preserves_unselected_environments() -> None: """Startup masks and partial resets never credit a replacement row or an untouched episode.""" sampler = ResetStateSampler( ResetStateSamplerCfg(success_monitor=SuccessMonitorCfg(monitored_history_len=2)), 4, 3, "cpu" @@ -50,7 +50,7 @@ def test_reset_records_previous_rows_and_preserves_unselected_environments(): torch.testing.assert_close(sampler.row_ids, assigned) -def test_sampling_tracks_the_current_success_frontier_without_starving_other_rows(): +def test_sampling_tracks_the_current_success_frontier_without_starving_other_rows() -> None: """The sampler observes live rolling outcomes and retains positive weight for easy and hard starts.""" sampler = ResetStateSampler(ResetStateSamplerCfg(), 3, 3, "cpu") env_ids = torch.arange(3) From e9f4eb84babc9adf453781f378938df6946ecbc4 Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Tue, 10 Nov 2026 02:47:33 +0100 Subject: [PATCH 08/10] Respect the robot frame in scripted pickup goals --- scripts/environments/cube_pickup.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/scripts/environments/cube_pickup.py b/scripts/environments/cube_pickup.py index 20a37ee84e0d..c40803cb82ef 100644 --- a/scripts/environments/cube_pickup.py +++ b/scripts/environments/cube_pickup.py @@ -27,6 +27,7 @@ from isaaclab.app import add_launcher_args, launch_simulation from isaaclab.app.logging_utils import configure_console_logging from isaaclab.utils import to_dict +from isaaclab.utils.math import combine_frame_transforms import isaaclab_tasks # noqa: F401 from isaaclab_tasks.contrib.cube_pickup import mdp @@ -158,6 +159,12 @@ def _rollout(env: gym.Env, agent_cfg, args: argparse.Namespace) -> dict: target = torch.cat((cube_start, orientation), dim=-1) target[:, 2] += torch.where(elapsed < 5.0, 0.10, 0.0) goal = task.command_manager.get_command("object_pose")[:, :3] + goal, _ = combine_frame_transforms( + task.scene["robot"].data.root_pos_w.torch, + task.scene["robot"].data.root_quat_w.torch, + goal, + ) + goal -= task.scene.env_origins target[:, :3] = torch.where((elapsed >= 7.6)[:, None], goal, target[:, :3]) action = task.scripted_action(target, close=False) action[:, 6] = torch.where(elapsed >= 7.0, -1.0, 1.0) From f05f8160d69b72a33556c694eff1feace3e64054 Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Tue, 10 Nov 2026 03:37:06 +0100 Subject: [PATCH 09/10] Fix reset diagnostics and simplify pickup sampling --- docs/source/how-to/reset_state_buffers.rst | 6 +- .../changelog.d/reset-state-buffer.added.rst | 3 +- .../isaaclab/envs/reset/reset_state_buffer.py | 20 +++++-- .../envs/reset/reset_state_buffer_cfg.py | 2 +- .../isaaclab/test/envs/test_reset_states.py | 9 +++ .../contrib/cube_pickup/cube_pickup_env.py | 38 ++++++++----- .../cube_pickup/cube_pickup_env_cfg.py | 43 ++++++--------- .../isaaclab_tasks/contrib/cube_pickup/mdp.py | 23 +++++--- .../contrib/cube_pickup/rsl_rl_ppo_cfg.py | 2 + .../isaaclab_tasks/utils/reset_states.py | 21 +++++-- .../isaaclab_tasks/utils/reset_states_cfg.py | 6 +- .../test/contrib/test_cube_pickup_reset.py | 55 +++++++++++++++---- .../isaaclab_tasks/test/test_reset_states.py | 13 +++-- 13 files changed, 163 insertions(+), 78 deletions(-) diff --git a/docs/source/how-to/reset_state_buffers.rst b/docs/source/how-to/reset_state_buffers.rst index e8a018bd9a04..8a83f2af3ab6 100644 --- a/docs/source/how-to/reset_state_buffers.rst +++ b/docs/source/how-to/reset_state_buffers.rst @@ -94,8 +94,10 @@ outcomes for the initial draw and mask manual or zero-step resets. Only resettin environments receive new row assignments. The sampler reuses the shared success monitor and sampling strategies from -:mod:`isaaclab_tasks.utils.sampling`. For a uniform baseline, configure the existing -uniform strategy: +:mod:`isaaclab_tasks.utils.sampling`. Configure row selection through +``ResetStateSamplerCfg.sampling``; the monitor config controls outcome history. +Non-default monitor sampling controls are rejected. For a uniform baseline, +configure the existing uniform strategy: .. code-block:: python diff --git a/source/isaaclab/changelog.d/reset-state-buffer.added.rst b/source/isaaclab/changelog.d/reset-state-buffer.added.rst index c8f1a072d3f0..56e2fb68d335 100644 --- a/source/isaaclab/changelog.d/reset-state-buffer.added.rst +++ b/source/isaaclab/changelog.d/reset-state-buffer.added.rst @@ -1,3 +1,4 @@ * Added :class:`~isaaclab.envs.reset.ResetStateBuffer` for collecting validated reset states with bounded attempts, reproducible generation, and named acceptance checks. - Collection publishes complete catalogs and diagnostics together; exported states are copies. + Collection publishes complete catalogs and diagnostics together; exported states and + group assignments are copies. diff --git a/source/isaaclab/isaaclab/envs/reset/reset_state_buffer.py b/source/isaaclab/isaaclab/envs/reset/reset_state_buffer.py index 20680ef3780e..d01f36839703 100644 --- a/source/isaaclab/isaaclab/envs/reset/reset_state_buffer.py +++ b/source/isaaclab/isaaclab/envs/reset/reset_state_buffer.py @@ -42,17 +42,25 @@ def __init__(self, cfg: ResetStateBufferCfg) -> None: raise ValueError("seed must be an integer in [0, 2**32).") self.cfg = cfg self._state: ResetStateBuffer.State = {} - self.group_names: tuple[str, ...] = () - """Generator names, in collection order.""" - self.group_ids = torch.empty(0, dtype=torch.long) - """Generator index for every stored row, shape [num_states].""" + self._group_names: tuple[str, ...] = () + self._group_ids = torch.empty(0, dtype=torch.long) self.collection_report: dict[str, dict[str, int]] = {} """Attempted, accepted, and rejected counts for the most recent successful collection.""" @property def num_states(self) -> int: """Number of collected states.""" - return self.group_ids.numel() + return self._group_ids.numel() + + @property + def group_names(self) -> tuple[str, ...]: + """Generator names, in collection order.""" + return self._group_names + + @property + def group_ids(self) -> torch.Tensor: + """Copy of each stored row's generator index, shape [num_states].""" + return self._group_ids.clone() @property def state(self) -> ResetStateBuffer.State: @@ -156,7 +164,7 @@ def collect( finally: np.random.set_state(numpy_state) random.setstate(python_state) - self._state, self.group_ids, self.group_names, self.collection_report = ( + self._state, self._group_ids, self._group_names, self.collection_report = ( state, group_ids, tuple(generators), diff --git a/source/isaaclab/isaaclab/envs/reset/reset_state_buffer_cfg.py b/source/isaaclab/isaaclab/envs/reset/reset_state_buffer_cfg.py index d9dbda80dbff..1bc2635183e7 100644 --- a/source/isaaclab/isaaclab/envs/reset/reset_state_buffer_cfg.py +++ b/source/isaaclab/isaaclab/envs/reset/reset_state_buffer_cfg.py @@ -3,7 +3,7 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Configuration for bounded reset-state collection.""" +"""Reset-state collection limits and seed settings.""" from ...utils import configclass diff --git a/source/isaaclab/test/envs/test_reset_states.py b/source/isaaclab/test/envs/test_reset_states.py index 366625292310..a87f4bca984c 100644 --- a/source/isaaclab/test/envs/test_reset_states.py +++ b/source/isaaclab/test/envs/test_reset_states.py @@ -36,6 +36,15 @@ def capture(ids): assert buffer.num_states == 7 assert buffer.group_names == ("table", "grasped") assert buffer.group_ids.tolist() == [0, 0, 0, 0, 1, 1, 1] + exported_groups = buffer.group_ids + exported_groups.fill_(-1) + assert buffer.group_ids.tolist() == [0, 0, 0, 0, 1, 1, 1] + exported_groups.resize_(0) + assert buffer.num_states == 7 + with pytest.raises(AttributeError): + buffer.group_ids = torch.empty(0, dtype=torch.long) + with pytest.raises(AttributeError): + buffer.group_names = () assert buffer.collection_report == { "table": {"attempted": 8, "accepted": 4, "rejected/generator": 2, "rejected/reachable": 2}, "grasped": {"attempted": 8, "accepted": 3, "rejected/generator": 2, "rejected/reachable": 2}, diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env.py index 2be51c342d93..28c759bed563 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env.py @@ -16,6 +16,7 @@ import isaaclab.envs.mdp as mdp from isaaclab.envs import ManagerBasedRLEnv +from isaaclab.envs.common import VecEnvStepReturn from isaaclab.envs.reset import ResetStateBuffer from isaaclab.managers import SceneEntityCfg from isaaclab.utils import clone, instantiate @@ -35,6 +36,7 @@ class CubePickupEnv(ManagerBasedRLEnv): def __init__(self, cfg: CubePickupEnvCfg, **kwargs) -> None: self.reset_buffer: ResetStateBuffer | None = None self.reset_sampler: ResetStateSampler | None = None + self._step_success_rate: torch.Tensor | None = None self._arm_scale = torch.tensor(cfg.actions.arm.scale, dtype=torch.float32, device=cfg.sim.device).expand(6) self._arm_offset = torch.tensor(cfg.actions.arm.offset, dtype=torch.float32, device=cfg.sim.device).expand(6) offset = cfg.actions.arm.body_offset @@ -51,13 +53,21 @@ def __init__(self, cfg: CubePickupEnvCfg, **kwargs) -> None: super().__init__(cfg, **kwargs) self._hand_cfg = SceneEntityCfg("robot", body_names="panda_hand") self._hand_cfg.resolve(self.scene) - self._bank_generator = torch.Generator(device=self.device) - self._bank_generator.manual_seed(cfg.reset_buffer.seed) self.generation_report: dict = {} self.command_manager.reset() if cfg.reset_mode != "table": self._collect_reset_states() + def step(self, action: torch.Tensor) -> VecEnvStepReturn: + """Publish success only for natural outcomes observed during this step.""" + self._step_success_rate = None + result = super().step(action) + if self._step_success_rate is None: + self.extras.get("log", {}).pop("Metrics/success_rate", None) + else: + self.extras["log"]["Metrics/success_rate"] = self._step_success_rate + return result + def scripted_action(self, target: torch.Tensor, *, close: bool) -> torch.Tensor: """Create normalized relative IK actions for target grasp-center poses. @@ -117,7 +127,7 @@ def _reset_idx(self, env_ids: torch.Tensor | slice) -> None: rows = None if self.reset_sampler is not None: previous_rows = self.reset_sampler.row_ids[ids] - previous_groups = self.reset_buffer.group_ids[previous_rows] + previous_groups = self._reset_group_ids[previous_rows] counts = torch.zeros(len(self.reset_buffer.group_names), device=self.device) counts.scatter_add_(0, previous_groups, valid.float()) successes = torch.zeros_like(counts).scatter_add_(0, previous_groups, (success & valid).float()) @@ -126,13 +136,13 @@ def _reset_idx(self, env_ids: torch.Tensor | slice) -> None: metrics[f"Reset/{name}_success"] = rates[group_id] rows = self.reset_sampler.reset(ids, success=success, valid=valid) probabilities = torch.zeros_like(counts).scatter_add_( - 0, self.reset_buffer.group_ids, self.reset_sampler.probabilities + 0, self._reset_group_ids, self.reset_sampler.probabilities ) for group_id, name in enumerate(self.reset_buffer.group_names): metrics[f"Reset/{name}_probability"] = probabilities[group_id] - metrics["Metrics/success_rate"] = successes.sum() / counts.sum().clamp_min(1) - else: - metrics["Metrics/success_rate"] = (success & valid).float().sum() / valid.sum().clamp_min(1) + if valid.any(): + self._step_success_rate = (success & valid).float().sum() / valid.sum() + metrics["Metrics/success_rate"] = self._step_success_rate super()._reset_idx(env_ids) if rows is None: self._reset_table(ids) @@ -140,12 +150,11 @@ def _reset_idx(self, env_ids: torch.Tensor | slice) -> None: self._restore_reset_state(self.reset_buffer.get_state(rows), ids) self.extras["log"].update(metrics) - def _reset_table(self, env_ids: torch.Tensor, *, generating: bool = False) -> None: + def _reset_table(self, env_ids: torch.Tensor) -> None: mdp.reset_scene_to_default(self, env_ids) cube = self.scene["object"] state = cube.data.default_root_state.torch[env_ids].clone() - generator = self._bank_generator if generating else None - offsets = torch.rand((env_ids.numel(), 2), device=self.device, generator=generator) + offsets = torch.rand((env_ids.numel(), 2), device=self.device) state[:, 0] = 0.45 + 0.10 * offsets[:, 0] state[:, 1] = -0.08 + 0.16 * offsets[:, 1] state[:, :3] += self.scene.env_origins[env_ids] @@ -170,7 +179,7 @@ def _drive(self, target: torch.Tensor, duration: float, *, close: bool = False) self._physics_step(self.scripted_action(target, close=close)) def _generate(self, env_ids: torch.Tensor, stage: str) -> torch.Tensor: - self._reset_table(env_ids, generating=True) + self._reset_table(env_ids) self.action_manager.reset() rest = pickup_mdp.hand_pose(self, self._hand_cfg) self._drive(rest, 0.2) @@ -183,7 +192,7 @@ def _generate(self, env_ids: torch.Tensor, stage: str) -> torch.Tensor: target[:, :3] = cube_position target[:, 2] += 0.10 if stage == "approach": - fraction = torch.rand((self.num_envs, 1), device=self.device, generator=self._bank_generator) + fraction = torch.rand((self.num_envs, 1), device=self.device) target[:, :3] = torch.lerp(rest[:, :3], target[:, :3], fraction) self._drive(target, 5.0) if stage == "approach": @@ -196,7 +205,7 @@ def _generate(self, env_ids: torch.Tensor, stage: str) -> torch.Tensor: target[:, :3] = cube_position if stage == "pregrasp": - target[:, 2] += 0.10 * torch.rand((self.num_envs,), device=self.device, generator=self._bank_generator) + target[:, 2] += 0.10 * torch.rand((self.num_envs,), device=self.device) self._drive(target, 2.0) aligned = ( torch.linalg.vector_norm( @@ -208,7 +217,7 @@ def _generate(self, env_ids: torch.Tensor, stage: str) -> torch.Tensor: return self._candidate_valid(env_ids) & aligned self._drive(target, 0.6, close=True) - target[:, 2] += 0.025 + 0.073 * torch.rand((self.num_envs,), device=self.device, generator=self._bank_generator) + target[:, 2] += 0.025 + 0.073 * torch.rand((self.num_envs,), device=self.device) self._drive(target, 1.0, close=True) height = pickup_mdp.object_position(self)[env_ids, 2] attached = torch.linalg.vector_norm(pickup_mdp.object_to_hand(self, self._hand_cfg)[env_ids], dim=-1) < 0.035 @@ -265,6 +274,7 @@ def _collect_reset_states(self) -> None: for stage in ("table", "approach", "pregrasp", "grasp") } self.reset_buffer.collect(self.scene._ALL_INDICES, generators, self._capture) + self._reset_group_ids = self.reset_buffer.group_ids sampler_cfg = clone(self.cfg.reset_sampler) if self.cfg.reset_mode == "uniform": sampler_cfg.sampling.strategies = [UniformSamplingStrategyCfg()] diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env_cfg.py index 4e0d79595a5b..afd0186b6812 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/cube_pickup_env_cfg.py @@ -32,29 +32,10 @@ from isaaclab_assets.robots import FRANKA_PANDA_HIGH_PD_CFG from ...core.lift.mdp import ObjectUniformPoseCommandCfg -from ...utils import PresetCfg, ResetStateSamplerCfg +from ...utils import ResetStateSamplerCfg, preset from . import mdp as pickup_mdp -@configclass -class PhysicsCfg(PresetCfg): - """Expose the supported ``physics=newton_mjwarp`` task selector.""" - - newton_mjwarp = NewtonCfg( - solver_cfg=MJWarpSolverCfg( - njmax=128, - nconmax=64, - iterations=30, - ls_iterations=15, - cone="elliptic", - integrator="implicitfast", - use_mujoco_contacts=True, - ), - num_substeps=2, - ) - default = newton_mjwarp - - @configclass class SceneCfg(InteractiveSceneCfg): """Existing Franka asset with a table and one 40 mm cube.""" @@ -79,7 +60,7 @@ class SceneCfg(InteractiveSceneCfg): ) light = AssetBaseCfg(prim_path="/World/Light", spawn=sim_utils.DomeLightCfg(intensity=2000.0)) - def __post_init__(self): + def __post_init__(self) -> None: super().__post_init__() self.robot.spawn.variants["Physics"] = "mujoco" # Match the high-PD asset's gravity-free arm in the native MuJoCo model. @@ -157,7 +138,7 @@ class PolicyCfg(ObservationGroupCfg): ) actions = ObservationTermCfg(func=mdp.last_action) - def __post_init__(self): + def __post_init__(self) -> None: self.enable_corruption = False self.concatenate_terms = True @@ -207,15 +188,27 @@ class CubePickupEnvCfg(ManagerBasedRLEnvCfg): reset_mode: Literal["adaptive", "uniform", "table"] = "adaptive" """Training distribution, or ordinary home/table starts for evaluation.""" - def __post_init__(self): + def __post_init__(self) -> None: self.decimation = 4 self.sim.dt = 1.0 / 120.0 self.sim.render_interval = self.decimation - self.sim.physics = PhysicsCfg() + newton = NewtonCfg( + solver_cfg=MJWarpSolverCfg( + njmax=128, + nconmax=64, + iterations=30, + ls_iterations=15, + cone="elliptic", + integrator="implicitfast", + use_mujoco_contacts=True, + ), + num_substeps=2, + ) + self.sim.physics = preset(default=newton, newton_mjwarp=newton) self.episode_length_s = 12.0 self.is_finite_horizon = True self.sim.visualizer_cfgs = VisualizerCfg(eye=(1.3, 1.1, 0.9), lookat=(0.45, 0.0, 0.15)) - def play_mode(self): + def play_mode(self) -> None: super().play_mode() self.reset_mode = "table" diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/mdp.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/mdp.py index 0fe22d807be5..2fb14e803835 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/mdp.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/mdp.py @@ -12,7 +12,7 @@ import torch from isaaclab.managers import SceneEntityCfg -from isaaclab.utils.math import combine_frame_transforms +from isaaclab.utils.math import quat_apply, quat_mul from ...core.lift.mdp import object_reached_goal @@ -33,11 +33,10 @@ def hand_pose( Positions [m] are relative to environment origins in world axes; orientations are world-frame quaternions in xyzw order. """ - robot = env.scene[asset_cfg.name] - body_id = asset_cfg.body_ids[0] - orientation = robot.data.body_link_quat_w.torch[:, body_id] - position = robot.data.body_link_pos_w.torch[:, body_id] - position, orientation = combine_frame_transforms(position, orientation, env._tcp_offset_pos, env._tcp_offset_rot) + orientation = env.scene[asset_cfg.name].data.body_link_quat_w.torch[:, asset_cfg.body_ids[0]] + if env._tcp_offset_rot is not None: + orientation = quat_mul(orientation, env._tcp_offset_rot) + position = _hand_position(env, asset_cfg) return torch.cat((position - env.scene.env_origins, orientation), dim=-1) @@ -45,7 +44,7 @@ def object_to_hand( env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot", body_names="panda_hand") ) -> torch.Tensor: """Cube-minus-grasp-center displacements [m] in world axes, shape (num_envs, 3).""" - return object_position(env) - hand_pose(env, asset_cfg)[:, :3] + return env.scene["object"].data.root_pos_w.torch - _hand_position(env, asset_cfg) def goal_reached( @@ -86,3 +85,13 @@ def object_dropped(env: ManagerBasedRLEnv) -> torch.Tensor: """Return workspace-exit flags with shape (num_envs,), using positions in environment-frame [m].""" position = object_position(env) return (position[:, 2] < -0.02) | (position[:, 0] < 0.15) | (position[:, 0] > 0.85) | (position[:, 1].abs() > 0.45) + + +def _hand_position(env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg) -> torch.Tensor: + """Compute the configured grasp-center position in the world frame.""" + robot = env.scene[asset_cfg.name] + body_id = asset_cfg.body_ids[0] + position = robot.data.body_link_pos_w.torch[:, body_id] + if env._tcp_offset_pos is not None: + position = position + quat_apply(robot.data.body_link_quat_w.torch[:, body_id], env._tcp_offset_pos) + return position diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/rsl_rl_ppo_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/rsl_rl_ppo_cfg.py index ccee298ae2c7..de8cf07ca6d8 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/rsl_rl_ppo_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/cube_pickup/rsl_rl_ppo_cfg.py @@ -12,6 +12,8 @@ @configclass class CubePickupPPORunnerCfg(RslRlOnPolicyRunnerCfg): + """PPO settings for learning the sparse pickup goal from generated reset states.""" + num_steps_per_env = 32 max_iterations = 3000 save_interval = 100 diff --git a/source/isaaclab_tasks/isaaclab_tasks/utils/reset_states.py b/source/isaaclab_tasks/isaaclab_tasks/utils/reset_states.py index a6ab209b7406..3cb3e20c67e5 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/utils/reset_states.py +++ b/source/isaaclab_tasks/isaaclab_tasks/utils/reset_states.py @@ -13,7 +13,7 @@ from .reset_states_cfg import ResetStateSamplerCfg from .sampling import Sampler -from .success_monitor import SuccessMonitor +from .success_monitor import SuccessMonitor, SuccessMonitorCfg class ResetStateSampler: @@ -33,14 +33,25 @@ class ResetStateSampler: def __init__(self, cfg: ResetStateSamplerCfg, num_envs: int, row_count: int, device: str | torch.device) -> None: if num_envs < 1 or row_count < 1: raise ValueError("num_envs and row_count must be positive.") + monitor_defaults = SuccessMonitorCfg() + if ( + cfg.success_monitor.target_success_rate != monitor_defaults.target_success_rate + or cfg.success_monitor.kappa != monitor_defaults.kappa + or cfg.success_monitor.temperature != monitor_defaults.temperature + ): + raise ValueError("Configure reset-row selection through sampling, not success_monitor sampling fields.") self.cfg = cfg self.row_ids = torch.zeros(num_envs, dtype=torch.long, device=device) """Current reset-row assignment for every environment, shape [num_envs].""" self.success_monitor: SuccessMonitor = instantiate(cfg.success_monitor, 1, row_count, device) """Rolling outcomes indexed by reset row.""" self.sampler: Sampler = instantiate(cfg.sampling, self.success_monitor.success_rate) - self.probabilities = self.sampler.probabilities() - """Most recently used row probabilities, shape [row_count]. Treat this tensor as read-only.""" + self._probabilities = self.sampler.probabilities() + + @property + def probabilities(self) -> torch.Tensor: + """Copy of the most recently used row probabilities, shape [row_count].""" + return self._probabilities.clone() def reset( self, @@ -64,7 +75,7 @@ def reset( """ if success is not None: self.success_monitor.success_update(self.row_ids[env_ids], success, valid) - self.probabilities = self.sampler.probabilities() + self._probabilities = self.sampler.probabilities() if env_ids.numel(): - self.row_ids[env_ids] = self.sampler.sample(self.probabilities, env_ids.numel()) + self.row_ids[env_ids] = self.sampler.sample(self._probabilities, env_ids.numel()) return self.row_ids[env_ids] diff --git a/source/isaaclab_tasks/isaaclab_tasks/utils/reset_states_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/utils/reset_states_cfg.py index b81c7761b262..acefffb90af3 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/utils/reset_states_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/utils/reset_states_cfg.py @@ -21,7 +21,11 @@ class ResetStateSamplerCfg: """Runtime sampler implementation.""" success_monitor: SuccessMonitorCfg = SuccessMonitorCfg(monitored_history_len=50) - """Rolling episode history for each reset row.""" + """Rolling episode history for each reset row. + + Leave the monitor's target, concentration, and temperature at their defaults; + :attr:`sampling` owns reset-row selection. + """ sampling: SamplerCfg = SamplerCfg( strategies=[BetaSamplingStrategyCfg(target=0.5, kappa=2.0), UniformSamplingStrategyCfg(weight=0.05)], diff --git a/source/isaaclab_tasks/test/contrib/test_cube_pickup_reset.py b/source/isaaclab_tasks/test/contrib/test_cube_pickup_reset.py index a36f2c149ad5..68209902482a 100644 --- a/source/isaaclab_tasks/test/contrib/test_cube_pickup_reset.py +++ b/source/isaaclab_tasks/test/contrib/test_cube_pickup_reset.py @@ -11,6 +11,7 @@ import pytest import torch +from isaaclab.benchmark.metrics import SuccessRateTracker from isaaclab.envs.reset import ResetStateBuffer, ResetStateBufferCfg from isaaclab.managers import ( ActionManager, @@ -54,17 +55,37 @@ def test_terminal_reward_stays_binary_after_timing_overrides() -> None: def test_viewer_reset_does_not_record_an_unfinished_episode() -> None: - """A viewer termination alias must not credit a manual reset as a completed failure.""" + """Only natural outcomes reach row history and the benchmark success tracker.""" env = CubePickupEnv.__new__(CubePickupEnv) env._is_closed = True env.cfg = CubePickupEnvCfg() - env.sim = SimpleNamespace(device="cpu", is_playing=lambda: True) - env.scene = SimpleNamespace(num_envs=2, _ALL_INDICES=torch.arange(2), reset=lambda env_ids: None) - # Only physics is omitted; the real task and manager reset bookkeeping still run. + env.sim = SimpleNamespace( + device="cpu", + is_playing=lambda: True, + is_rendering=False, + step=lambda render: None, + forward=lambda: None, + manual_reset=False, + ) + env.sim.consume_reset_request = lambda: env.sim.manual_reset + env.scene = SimpleNamespace( + num_envs=2, + _ALL_INDICES=torch.arange(2), + reset=lambda env_ids: None, + write_data_to_sim=lambda: None, + update=lambda dt: None, + ) env._restore_reset_state = lambda state, env_ids: None env.extras = {} - env.episode_length_buf = torch.tensor([5, 5]) - env.success_flags = torch.tensor([True, False]) + env.episode_length_buf = torch.zeros(2, dtype=torch.long) + env.success_flags = torch.zeros(2, dtype=torch.bool) + env.reset_buf = torch.zeros(2, dtype=torch.bool) + env.common_step_counter = 0 + env._sim_step_counter = 0 + env._physics_handles_decimation = False + env.render_enabled = False + env.has_rtx_sensors = False + env.video_recorders = [] env.termination_manager = TerminationManager({"success": TerminationTermCfg(func=_success)}, env) for name, manager in ( ("action_manager", ActionManager), @@ -78,18 +99,28 @@ def test_viewer_reset_does_not_record_an_unfinished_episode() -> None: setattr(env, name, manager(SimpleNamespace(), env)) env.reset_buffer = ResetStateBuffer(ResetStateBufferCfg(size=2)) env.reset_buffer.collect(torch.arange(2), lambda ids: None, lambda ids: {"row": ids[:, None]}) + env._reset_group_ids = env.reset_buffer.group_ids env.reset_sampler = ResetStateSampler(ResetStateSamplerCfg(), 2, 2, "cpu") + tracker = SuccessRateTracker(threshold=0.5, window=1, num_steps_per_env=1) + _, extras = env.reset() + tracker.record_step(extras) + observations = [tracker.end_iteration()] env.reset_sampler.row_ids[:] = torch.tensor([0, 1]) env.reset_sampler.success_monitor.success_update(torch.tensor([1]), torch.tensor([True])) - # step() retains the natural compute result before the viewer marks its terminated alias. - env.reset_buf = env.termination_manager.compute() - env.reset_terminated = env.termination_manager.terminated - env.reset_terminated[1] = True - env._reset_idx(torch.tensor([0, 1])) + env.episode_length_buf[:] = 5 + env.success_flags[0] = True + env.sim.manual_reset = True + tracker.record_step(env.step(torch.empty(2, 0))[4]) + observations.append(tracker.end_iteration()) torch.testing.assert_close(env.reset_sampler.success_monitor.get_success_rate(), torch.tensor([1.0, 1.0])) - assert env.extras["log"]["Reset/default_success"].item() == 1.0 + env.success_flags.zero_() + for manual_reset in (False, True): + env.sim.manual_reset = manual_reset + tracker.record_step(env.step(torch.empty(2, 0))[4]) + observations.append(tracker.end_iteration()) + assert observations == [None, 1.0, None, None] def test_saving_reset_bank_rejects_its_json_report_path(tmp_path: Path) -> None: diff --git a/source/isaaclab_tasks/test/test_reset_states.py b/source/isaaclab_tasks/test/test_reset_states.py index dc3c528e4201..eb07c08d8b25 100644 --- a/source/isaaclab_tasks/test/test_reset_states.py +++ b/source/isaaclab_tasks/test/test_reset_states.py @@ -52,13 +52,18 @@ def test_reset_records_previous_rows_and_preserves_unselected_environments() -> def test_sampling_tracks_the_current_success_frontier_without_starving_other_rows() -> None: """The sampler observes live rolling outcomes and retains positive weight for easy and hard starts.""" + with pytest.raises(ValueError, match="through sampling"): + ResetStateSampler(ResetStateSamplerCfg(success_monitor=SuccessMonitorCfg(target_success_rate=0.8)), 3, 3, "cpu") sampler = ResetStateSampler(ResetStateSamplerCfg(), 3, 3, "cpu") env_ids = torch.arange(3) for success in ([False, True, False], [False, True, True]): sampler.row_ids[:] = env_ids sampler.reset(env_ids, torch.tensor(success)) assert sampler.success_monitor.success_rate.tolist() == [0.0, 1.0, 0.5] - assert (sampler.probabilities > 0).all() - torch.testing.assert_close(sampler.probabilities.sum(), torch.tensor(1.0)) - assert sampler.probabilities[2] > sampler.probabilities[0] - assert sampler.probabilities[2] > sampler.probabilities[1] + exported = sampler.probabilities + exported.zero_() + probabilities = sampler.probabilities + assert (probabilities > 0).all() + torch.testing.assert_close(probabilities.sum(), torch.tensor(1.0)) + assert probabilities[2] > probabilities[0] + assert probabilities[2] > probabilities[1] From cdb477488031b8e713af0c0a88df970ce67472d7 Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Wed, 25 Nov 2026 15:04:32 +0100 Subject: [PATCH 10/10] Simplify Franka Pour reset sampling --- .../pour-reset-seed-hook.fixed.rst | 1 + .../isaaclab/envs/manager_based_env.py | 19 ++-- .../contrib/franka_pour/mdp/reset_dataset.py | 60 +++--------- .../contrib/franka_pour/pour_env.py | 62 ++---------- .../contrib/franka_pour/reset_sampler.py | 98 ++++++++++--------- .../contrib/test_franka_pour_reset_sampler.py | 50 ++++------ 6 files changed, 104 insertions(+), 186 deletions(-) create mode 100644 source/isaaclab/changelog.d/pour-reset-seed-hook.fixed.rst diff --git a/source/isaaclab/changelog.d/pour-reset-seed-hook.fixed.rst b/source/isaaclab/changelog.d/pour-reset-seed-hook.fixed.rst new file mode 100644 index 000000000000..ec2ca219a516 --- /dev/null +++ b/source/isaaclab/changelog.d/pour-reset-seed-hook.fixed.rst @@ -0,0 +1 @@ +* Fixed explicit reset seeding for manager-based tasks that use their own sampler. diff --git a/source/isaaclab/isaaclab/envs/manager_based_env.py b/source/isaaclab/isaaclab/envs/manager_based_env.py index d654d36e7a20..963ac5fc578b 100644 --- a/source/isaaclab/isaaclab/envs/manager_based_env.py +++ b/source/isaaclab/isaaclab/envs/manager_based_env.py @@ -463,12 +463,7 @@ def reset( # trigger recorder terms for pre-reset calls self.recorder_manager.record_pre_reset(env_ids) - # set the seed - if seed is not None: - self.seed(seed) - - # reset state of scene - self._reset_idx(env_ids) + self._reset_with_seed(env_ids, seed) # update articulation kinematics self.scene.write_data_to_sim() @@ -526,11 +521,7 @@ def reset_to( # trigger recorder terms for pre-reset calls self.recorder_manager.record_pre_reset(env_ids) - # set the seed - if seed is not None: - self.seed(seed) - - self._reset_idx(env_ids) + self._reset_with_seed(env_ids, seed) # set the state self.scene.reset_to(state, env_ids, is_relative=is_relative) @@ -671,6 +662,12 @@ def close(self): Helper functions. """ + def _reset_with_seed(self, env_ids: torch.Tensor | slice, seed: int | None) -> None: + """Reset selected environments after applying an optional explicit seed.""" + if seed is not None: + self.seed(seed) + self._reset_idx(env_ids) + def _reset_idx(self, env_ids: torch.Tensor | slice): """Reset environments based on specified indices. diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/mdp/reset_dataset.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/mdp/reset_dataset.py index a2f8f0f64c02..0da81e79fdd4 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/mdp/reset_dataset.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/mdp/reset_dataset.py @@ -7,7 +7,6 @@ from __future__ import annotations -import math from collections.abc import Sequence from typing import TYPE_CHECKING @@ -19,7 +18,7 @@ from isaaclab.managers.manager_base import ManagerTermBase from isaaclab.utils import index_fill_ -from ..reset_sampler import ResetDatasetSamplerCfg +from ..reset_sampler import ResetDatasetSamplerCfg, _CyclicReplay, _sampling_metrics if TYPE_CHECKING: from ..pour_env import FrankaPourEnv @@ -51,7 +50,8 @@ def __init__(self, cfg: CurriculumTermCfg, env: FrankaPourEnv): self._replay_generator = torch.Generator(device=self._device) seed = env.cfg.seed if env.cfg.seed is not None else self._replay_generator.seed() self._replay_fraction = float(sampler_cfg.uniform_fraction) if sampling_mode == "adaptive" else 0.0 - self._restart_replay(seed) + self._replay_generator.manual_seed(seed) + self._replay = _CyclicReplay(self._row_count, self._device, self._replay_generator) self._requested_rows = torch.empty_like(env.reset_dataset_row_id) # Core's Beta score has unit peak. Restore the raw kernel's scale so its @@ -103,10 +103,11 @@ def __call__( else: env_ids = torch.as_tensor(env_ids, device=self._device, dtype=torch.long) with self._sampler_stream(): - if env._reset_dataset_reseed_pending: - seed = torch.initial_seed() + if (seed := env._reset_dataset_seed) is not None: + env._reset_dataset_seed = None self._sampler.reseed(seed) - self._restart_replay(seed) + self._replay_generator.manual_seed(seed) + self._replay.restart(self._replay_generator) num_envs = env_ids.numel() if num_envs == 0: @@ -155,51 +156,16 @@ def _reset_requested_rows(self, env_ids: torch.Tensor, rows: torch.Tensor) -> No self._requested_rows[env_ids] = rows self._sampler.reset(env_ids=env_ids, state_ids=self._requested_rows) - def _restart_replay(self, seed: int) -> None: - self._replay_generator.manual_seed(seed) - self._replay_credit = 0.0 - self._replay_order = torch.randperm(self._row_count, device=self._device, generator=self._replay_generator) - self._replay_cursor = 0 - def _apply_cyclic_replay(self, env_ids: torch.Tensor) -> None: """Override the reserved assignments with complete shuffled passes over the dataset.""" count = env_ids.numel() - credit = self._replay_credit + self._replay_fraction * count - replay_count = min(count, math.floor(credit + 1.0e-12)) - self._replay_credit = credit - replay_count - if replay_count == 0: - return - - slots = torch.randperm(count, device=self._device, generator=self._replay_generator)[:replay_count] - remaining = replay_count - chunks = [] - while remaining: - take = min(remaining, self._row_count - self._replay_cursor) - chunks.append(self._replay_order[self._replay_cursor : self._replay_cursor + take]) - self._replay_cursor += take - remaining -= take - if self._replay_cursor == self._row_count: - self._replay_order = torch.randperm( - self._row_count, device=self._device, generator=self._replay_generator - ) - self._replay_cursor = 0 - self._reset_requested_rows(env_ids[slots], torch.cat(chunks)) + replay_count = self._replay.reserve(count, self._replay_fraction) + if replay_count: + slots = torch.randperm(count, device=self._device, generator=self._replay_generator)[:replay_count] + self._reset_requested_rows(env_ids[slots], self._replay.take(replay_count, self._replay_generator)) def _refresh_metrics_cache(self) -> None: """Refresh host logging metrics after a bounded number of reset assignments.""" - probabilities = self._sampler.probabilities.torch - replay_fraction = self._replay_fraction - probabilities = probabilities * (1.0 - replay_fraction) + replay_fraction / self._row_count - top_count = max(1, math.ceil(0.01 * self._row_count)) - effective_fraction, top_mass = torch.stack( - ( - probabilities.square().sum().reciprocal() / self._row_count, - torch.topk(probabilities, top_count, sorted=False).values.sum(), - ) - ).tolist() - self._metrics_cache = { - "sampler/effective_pool_fraction": effective_fraction, - "sampler/top_1_percent_mass": top_mass, - "sampler/uniform_replay_fraction": replay_fraction, - } + self._metrics_cache = _sampling_metrics(self._sampler.probabilities.torch, self._replay_fraction) + self._metrics_cache["sampler/uniform_replay_fraction"] = self._replay_fraction self._local_reset_assignments_since_metrics = 0 diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/pour_env.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/pour_env.py index f9ff55904448..0858a9bdfc8d 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/pour_env.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/pour_env.py @@ -20,10 +20,8 @@ from __future__ import annotations import logging -from collections.abc import Iterator -from contextlib import contextmanager from pathlib import Path -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING import newton import torch @@ -31,7 +29,7 @@ from isaaclab_newton.cloner import newton_builder_world_hook from isaaclab_newton.physics import reset_mpm_solver_state -from isaaclab.envs import ManagerBasedRLEnv, VecEnvObs +from isaaclab.envs import ManagerBasedRLEnv from isaaclab.utils import index_fill_ from isaaclab.utils import math as math_utils from isaaclab.utils.assets import retrieve_file_path @@ -112,7 +110,7 @@ class FrankaPourEnv(ManagerBasedRLEnv): cfg: FrankaPourResetDatasetEnvCfg def __init__(self, cfg: FrankaPourResetDatasetEnvCfg, render_mode: str | None = None, **kwargs): - self._reset_dataset_reseed_pending = False + self._reset_dataset_seed: int | None = None configure_mpm_capacities(cfg) self._prepare_newton_extras(cfg) with newton_builder_world_hook(self._add_pour_world_to_builder): @@ -122,56 +120,14 @@ def load_managers(self) -> None: self._setup_after_physics() super().load_managers() - def reset( - self, - env_ids: torch.Tensor | slice | None = slice(None), - *, - seed: int | None = None, - options: dict[str, Any] | None = None, - ) -> tuple[VecEnvObs, dict]: - """Reset the environments and include the dataset sampler in explicit reseeding. - - Args: - env_ids: Environment selection, or None for all environments. - seed: Optional seed for scene randomization and reset sampling. - options: Additional Gymnasium reset options. - - Returns: - Observations and extras for the reset. - """ - with self._reset_dataset_reseed(seed): - return super().reset(env_ids, seed=seed, options=options) - - def reset_to( - self, - state: dict[str, dict[str, dict[str, torch.Tensor]]], - env_ids: torch.Tensor | slice | None = slice(None), - seed: int | None = None, - is_relative: bool = False, - ) -> tuple[VecEnvObs, dict]: - """Restore a scene state and include the dataset sampler in explicit reseeding. - - Args: - state: Scene state in the format accepted by :meth:`InteractiveScene.reset_to`. - env_ids: Environment selection, or None for all environments. - seed: Optional seed for scene randomization and reset sampling. - is_relative: Whether the poses are relative to the environment origins. - - Returns: - Observations and extras for the reset. - """ - with self._reset_dataset_reseed(seed): - return super().reset_to(state, env_ids, seed, is_relative) - - @contextmanager - def _reset_dataset_reseed(self, seed: int | None) -> Iterator[None]: - """Let the curriculum restart its streams after the base reset resolves the seed.""" - previous = self._reset_dataset_reseed_pending - self._reset_dataset_reseed_pending = seed is not None + def _reset_with_seed(self, env_ids: torch.Tensor | slice, seed: int | None) -> None: + """Offer the resolved seed to the curriculum during an explicit reset.""" + previous = self._reset_dataset_seed + self._reset_dataset_seed = self.seed(seed) if seed is not None else None try: - yield + super()._reset_with_seed(env_ids, None) finally: - self._reset_dataset_reseed_pending = previous + self._reset_dataset_seed = previous def _prepare_newton_extras(self, cfg: FrankaPourResetDatasetEnvCfg) -> None: """Cache task geometry bounds and Newton contact values from the resolved config. diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/reset_sampler.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/reset_sampler.py index 679b45ee7237..c93036c21c7c 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/reset_sampler.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/reset_sampler.py @@ -71,6 +71,56 @@ def validate_values(self) -> None: raise ValueError("uniform_fraction must lie strictly between zero and one.") +class _CyclicReplay: + """Reserve a fraction of starts for complete shuffled passes through the dataset.""" + + def __init__(self, row_count: int, device: str | torch.device, generator: torch.Generator | None = None) -> None: + self._row_count = row_count + self._device = device + self.restart(generator) + + def restart(self, generator: torch.Generator | None) -> None: + self._order = torch.randperm(self._row_count, device=self._device, generator=generator) + self._cursor = 0 + self._credit = 0.0 + + def reserve(self, count: int, fraction: float) -> int: + credit = self._credit + fraction * count + reserved = math.floor(credit + 1.0e-12) + self._credit = credit - reserved + return min(count, reserved) + + def take(self, count: int, generator: torch.Generator | None) -> torch.Tensor: + if count == 0: + return torch.empty(0, device=self._device, dtype=torch.long) + chunks = [] + while count > 0: + take = min(count, self._row_count - self._cursor) + chunks.append(self._order[self._cursor : self._cursor + take]) + self._cursor += take + count -= take + if self._cursor == self._row_count: + self._order = torch.randperm(self._row_count, device=self._device, generator=generator) + self._cursor = 0 + return torch.cat(chunks) + + +def _sampling_metrics(probabilities: torch.Tensor, replay_fraction: float) -> dict[str, float]: + """Summarize the mixture of adaptive scores and uniform cyclic replay.""" + row_count = probabilities.numel() + mixture = probabilities * (1.0 - replay_fraction) + replay_fraction / row_count + top_count = max(1, math.ceil(0.01 * row_count)) + values = torch.stack( + ( + mixture.square().sum().reciprocal() / row_count, + torch.topk(mixture, top_count, sorted=False).values.sum(), + mixture.new_tensor(replay_fraction), + ) + ) + names = ("sampler/effective_pool_fraction", "sampler/top_1_percent_mass", "sampler/uniform_replay_fraction") + return dict(zip(names, values.tolist(), strict=True)) + + def _ring_append_bool_count_rate( data: torch.Tensor, stream_ids: torch.Tensor, @@ -173,9 +223,7 @@ def __init__( self._history_pointers = torch.zeros(row_count, dtype=torch.int32, device=device) self._history_sizes = torch.zeros_like(self._history_pointers) self._history_success_counts = torch.zeros_like(self._history_pointers) - self._uniform_order = torch.randperm(row_count, device=device) - self._uniform_cursor = 0 - self._uniform_credit = 0.0 + self._replay = _CyclicReplay(row_count, self._success_rates.device) def _probabilities(self) -> torch.Tensor: """Return normalized Beta scores with a per-row epsilon floor.""" @@ -225,52 +273,14 @@ def _record_validated(self, rows: torch.Tensor, success: torch.Tensor) -> None: def metrics(self) -> dict[str, float]: """Return sampling-concentration and cyclic-replay metrics.""" - replay_fraction = float(self.cfg.uniform_fraction) - probabilities = self._probabilities() - probabilities.mul_(1.0 - replay_fraction).add_(replay_fraction / self.row_count) - top_count = max(1, math.ceil(0.01 * self.row_count)) - values = torch.stack( - ( - probabilities.square().sum().reciprocal() / self.row_count, - torch.topk(probabilities, top_count, sorted=False).values.sum(), - probabilities.new_tensor(replay_fraction), - ) - ) - names = ( - "sampler/effective_pool_fraction", - "sampler/top_1_percent_mass", - "sampler/uniform_replay_fraction", - ) - return dict(zip(names, values.tolist(), strict=True)) + return _sampling_metrics(self._probabilities(), float(self.cfg.uniform_fraction)) def _uniform_assignment_count(self, unforced_count: int) -> int: - """Reserve the configured exact fraction for cyclic assignments over time.""" - replay_credit = self._uniform_credit + self.cfg.uniform_fraction * unforced_count - uniform_count = math.floor(replay_credit + 1.0e-12) - self._uniform_credit = replay_credit - uniform_count - return min(unforced_count, uniform_count) + return self._replay.reserve(unforced_count, self.cfg.uniform_fraction) def _take_uniform_rows( self, count: int, generator: torch.Generator | None, ) -> torch.Tensor: - """Take rows from shuffled complete-cache cycles without replacement within a cycle.""" - if count == 0: - return torch.empty(0, device=self._success_rates.device, dtype=torch.long) - remaining = count - chunks = [] - while remaining > 0: - available = self.row_count - self._uniform_cursor - take = min(remaining, available) - chunks.append(self._uniform_order[self._uniform_cursor : self._uniform_cursor + take]) - self._uniform_cursor += take - remaining -= take - if self._uniform_cursor == self.row_count: - self._uniform_order = torch.randperm( - self.row_count, - device=self._success_rates.device, - generator=generator, - ) - self._uniform_cursor = 0 - return torch.cat(chunks) + return self._replay.take(count, generator) diff --git a/source/isaaclab_tasks/test/contrib/test_franka_pour_reset_sampler.py b/source/isaaclab_tasks/test/contrib/test_franka_pour_reset_sampler.py index 884b6e7ea2ec..b3b8a6839c70 100644 --- a/source/isaaclab_tasks/test/contrib/test_franka_pour_reset_sampler.py +++ b/source/isaaclab_tasks/test/contrib/test_franka_pour_reset_sampler.py @@ -12,6 +12,7 @@ import torch from isaaclab.managers import CurriculumTermCfg +from isaaclab.test.utils import DeviceScope, test_devices from isaaclab_tasks.contrib.franka_pour.mdp.reset_dataset import PourResetDatasetCurriculum from isaaclab_tasks.contrib.franka_pour.pour_env import FrankaPourEnv @@ -20,7 +21,7 @@ pytestmark = [pytest.mark.unit, pytest.mark.kitless] -def _make_curriculum(num_envs, row_count, *, device="cpu", **overrides): +def _make_curriculum(num_envs, row_count, *, device="cpu", env=None, **overrides): cfg = SimpleNamespace( seed=17, reset_dataset_sampling_mode="adaptive", @@ -29,11 +30,11 @@ def _make_curriculum(num_envs, row_count, *, device="cpu", **overrides): curriculum_freeze=False, pour_target_frac=0.7, ) - for name, value in overrides.items(): - setattr(cfg, name, value) - + vars(cfg).update(overrides) progress = SimpleNamespace(ever_success=torch.zeros(num_envs, dtype=torch.bool, device=device)) - env = SimpleNamespace( + if env is None: + env = SimpleNamespace() + vars(env).update( cfg=cfg, num_envs=num_envs, _reset_dataset_states={ @@ -44,7 +45,7 @@ def _make_curriculum(num_envs, row_count, *, device="cpu", **overrides): reset_buf=torch.zeros(num_envs, dtype=torch.bool, device=device), reset_dataset_row_id=torch.full((num_envs,), -1, device=device), pour_target_frac=torch.zeros(num_envs, device=device), - _reset_dataset_reseed_pending=False, + _reset_dataset_seed=None, termination_manager=SimpleNamespace(get_term_cfg=lambda name: SimpleNamespace(func=progress)), ) return PourResetDatasetCurriculum(CurriculumTermCfg(func=PourResetDatasetCurriculum), env), env, progress @@ -99,7 +100,7 @@ def test_franka_pour_replay_visits_each_row_in_successive_cycles(): 1, row_count, reset_dataset_sampler=ResetDatasetSamplerCfg(uniform_fraction=0.95) ) env_ids = torch.tensor([0]) - curriculum(env, env_ids) + assert curriculum(env, env_ids)["sampler/uniform_replay_fraction"] == 0.95 for _ in range(2): rows = [] for _ in range(row_count): @@ -112,17 +113,15 @@ def test_franka_pour_replay_visits_each_row_in_successive_cycles(): def test_franka_pour_explicit_reset_seed_restarts_sampling(method): """The real public reset methods reseed the task samplers on every explicit seed call.""" count = 8 - _, buffers, _ = _make_curriculum(count, row_count=17) env = object.__new__(FrankaPourEnv) - env.__dict__.update(vars(buffers)) + env._is_closed = True env.scene = SimpleNamespace(num_envs=count, write_data_to_sim=lambda: None, reset_to=lambda *args, **kwargs: None) env.sim = SimpleNamespace(forward=lambda: None) env.recorder_manager = SimpleNamespace(record_pre_reset=lambda ids: None, record_post_reset=lambda ids: None) env.observation_manager = SimpleNamespace(compute=lambda **kwargs: {}) - env.cfg.wait_for_textures = False env.has_rtx_sensors = False env.extras = {} - curriculum = PourResetDatasetCurriculum(CurriculumTermCfg(func=PourResetDatasetCurriculum), env) + curriculum, _, _ = _make_curriculum(count, row_count=17, env=env, wait_for_textures=False) env._reset_idx = lambda ids: curriculum(env, ids) reset = env.reset if method == "reset" else lambda **kwargs: env.reset_to({}, **kwargs) @@ -135,25 +134,18 @@ def test_franka_pour_explicit_reset_seed_restarts_sampling(method): torch.testing.assert_close(env.reset_dataset_row_id, first) -def test_legacy_franka_pour_sampler_preserves_import_and_metrics(): - """The released sampler remains callable while downstream users migrate.""" - with pytest.warns(DeprecationWarning, match="isaaclab.envs.reset.ResetStateSampler"): - sampler = ResetDatasetSampler(3, "cpu", ResetDatasetSamplerCfg(uniform_fraction=0.5)) - assert sampler.metrics()["sampler/uniform_replay_fraction"] == pytest.approx(0.5) - - -@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires a non-default CUDA stream") -def test_franka_pour_resets_on_the_callers_cuda_stream(): +@pytest.mark.parametrize("device", test_devices(DeviceScope.CUDA)) +def test_franka_pour_resets_on_the_callers_cuda_stream(device): """An explicit playback row follows the queued Torch request on a non-default stream.""" curriculum, env, _ = _make_curriculum( 1, 2, - device="cuda", + device=device, curriculum_freeze=True, reset_dataset_top_grasp_count=1, reset_dataset_sampler=ResetDatasetSamplerCfg(uniform_fraction=0.95), ) - env_ids = torch.tensor([0], device="cuda") + env_ids = torch.tensor([0], device=device) curriculum(env, env_ids) # Warm the adaptive and forced paths and leave the last replay request at @@ -167,8 +159,8 @@ def test_franka_pour_resets_on_the_callers_cuda_stream(): assert env.reset_dataset_row_id.item() == 1 env.cfg.curriculum_freeze = True - stream = torch.cuda.Stream() - stream.wait_stream(torch.cuda.current_stream()) + stream = torch.cuda.Stream(device=device) + stream.wait_stream(torch.cuda.current_stream(device)) with torch.cuda.stream(stream): torch.cuda._sleep(100_000_000) curriculum(env, env_ids) @@ -215,14 +207,10 @@ def test_legacy_sampler_rolling_history_matches_per_row_deques(): assert _ring_values(sampler, row) == list(history) -@pytest.mark.filterwarnings("ignore:ResetDatasetSampler is deprecated:DeprecationWarning") def test_legacy_sampler_uniform_replay_covers_every_row_before_repeating(monkeypatch: pytest.MonkeyPatch): - """The configured replay fraction draws one complete shuffled cycle without replacement.""" - sampler = ResetDatasetSampler( - 5, - "cpu", - ResetDatasetSamplerCfg(uniform_fraction=0.5), - ) + """The deprecated sampler still draws a complete shuffled cycle without replacement.""" + with pytest.warns(DeprecationWarning, match="isaaclab.envs.reset.ResetStateSampler"): + sampler = ResetDatasetSampler(5, "cpu", ResetDatasetSamplerCfg(uniform_fraction=0.5)) cyclic_rows: list[int] = [] take_uniform_rows = sampler._take_uniform_rows