Repository navigation
Reuse shared reset sampling in Franka Pour #8965
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
a823a25
45002e1
f7d1c09
fcfee1f
97f93b2
e28a794
51fc7f6
ea99b61
f0b3a15
f394085
327d911
6ec0d7f
d6a30b1
5b83452
64f67b6
edb15d5
92d6968
3021625
97715ea
0ec4a73
e9f4eb8
f05f816
3a89e38
e6d93ec
0dd6ec5
0831c95
e61df06
11a902f
39eeb48
db60996
fe9d5e4
bd124ad
dce6bcc
cdb4774
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| * Fixed explicit reset seeding for manager-based tasks that use their own sampler. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| * Changed Franka Pour to use :class:`~isaaclab.envs.reset.ResetStateSampler` for adaptive reset sampling. | ||
| Existing reset datasets, settings, and exact cyclic replay remain supported. The shared sampler | ||
| uses a different random stream, so historical seeded runs may draw different rows. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| * Deprecated the Franka Pour task-local ``ResetDatasetSampler``. Use | ||
| :class:`~isaaclab.envs.reset.ResetStateSampler` and supply complete environment selections | ||
| and episode outcomes to its ``reset()`` method. The legacy import and behavior remain available. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -11,12 +11,14 @@ | |
| from typing import TYPE_CHECKING | ||
|
|
||
| import torch | ||
| import warp as wp | ||
|
|
||
| from isaaclab.envs.reset import BetaSamplingScoreCfg, ResetStateSampler, ResetStateSamplerCfg | ||
| from isaaclab.managers import CurriculumTermCfg | ||
| from isaaclab.managers.manager_base import ManagerTermBase | ||
| from isaaclab.utils import clone, index_fill_ | ||
| from isaaclab.utils import index_fill_ | ||
|
|
||
| from ..reset_sampler import ResetDatasetSampler, ResetDatasetSamplerCfg | ||
| from ..reset_sampler import ResetDatasetSamplerCfg, _CyclicReplay, _sampling_metrics | ||
|
|
||
| if TYPE_CHECKING: | ||
| from ..pour_env import FrankaPourEnv | ||
|
|
@@ -37,13 +39,39 @@ def __init__(self, cfg: CurriculumTermCfg, env: FrankaPourEnv): | |
| self._row_count = int(category.numel()) | ||
| self._device = category.device | ||
|
|
||
| self._sampling_mode = env.cfg.reset_dataset_sampling_mode | ||
| if self._sampling_mode not in ("adaptive", "uniform"): | ||
| sampling_mode = env.cfg.reset_dataset_sampling_mode | ||
| if sampling_mode not in ("adaptive", "uniform"): | ||
| raise ValueError("reset_dataset_sampling_mode must be 'adaptive' or 'uniform'.") | ||
| sampler_cfg = clone(env.cfg.reset_dataset_sampler) | ||
| sampler_cfg = env.cfg.reset_dataset_sampler | ||
| if not isinstance(sampler_cfg, ResetDatasetSamplerCfg): | ||
| raise TypeError("reset_dataset_sampler must be ResetDatasetSamplerCfg.") | ||
| self._sampler = ResetDatasetSampler(self._row_count, self._device, sampler_cfg) | ||
| sampler_cfg.validate_values() | ||
|
|
||
| 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._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) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Warning · Scope Complexity — Reuse the existing row buffer _requested_rows duplicates the task’s per-environment row buffer and requires a forwarding helper. Write requested rows into env.reset_dataset_row_id and pass that buffer to the sampler. |
||
|
|
||
| # Core's Beta score has unit peak. Restore the raw kernel's scale so its | ||
| # weight floor has the same effect as in the original Pour sampler. | ||
| target = float(sampler_cfg.target_success_rate) | ||
| kappa = float(sampler_cfg.kappa) | ||
| peak = target ** (kappa * target) * (1.0 - target) ** (kappa * (1.0 - target)) | ||
| scores = [BetaSamplingScoreCfg(target=target, kappa=kappa, weight=peak)] if sampling_mode == "adaptive" else [] | ||
| with self._sampler_stream(): | ||
| self._sampler = ResetStateSampler( | ||
| ResetStateSamplerCfg( | ||
| history_length=sampler_cfg.monitored_history_len, | ||
| scores=scores, | ||
| uniform_weight=float(sampler_cfg.epsilon), | ||
| seed=seed, | ||
| ), | ||
| env.num_envs, | ||
| self._row_count, | ||
| self._device, | ||
| ) | ||
|
|
||
| self._frozen_rows = torch.arange(self._row_count, device=self._device, dtype=torch.long) | ||
| top_grasp_count = env.cfg.reset_dataset_top_grasp_count | ||
|
|
@@ -70,36 +98,51 @@ def __call__( | |
| env_ids: Sequence[int] | torch.Tensor | slice, | ||
| ) -> dict[str, float]: | ||
| """Record completed episodes and assign the next reset rows.""" | ||
| num_envs = len(range(env.num_envs)[env_ids]) if isinstance(env_ids, slice) else len(env_ids) | ||
| if num_envs == 0: | ||
| return self._metrics(env) | ||
|
|
||
| completed = (env.episode_length_buf[env_ids] > 0) & (env.reset_dataset_row_id[env_ids] >= 0) | ||
| if not env.cfg.curriculum_freeze: | ||
| rows = env.reset_dataset_row_id[env_ids][completed] | ||
| if rows.numel() > 0: | ||
| progress = env.termination_manager.get_term_cfg("learning_progress_context").func | ||
| self._apply_outcomes(rows, progress.ever_success[env_ids][completed]) | ||
|
|
||
| if env.cfg.curriculum_freeze: | ||
| slots = torch.randint(self._frozen_rows.numel(), (num_envs,), device=self._device) | ||
| rows = self._frozen_rows[slots] | ||
| elif self._sampling_mode == "uniform": | ||
| rows = torch.randint(self._row_count, (num_envs,), device=self._device) | ||
| if isinstance(env_ids, slice): | ||
| env_ids = torch.arange(env.num_envs, device=self._device)[env_ids] | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Warning · Implementation — Materialize only selected slice indices A small sliced reset allocates indices for every environment before slicing them. Materialize only the selected range when the sampler needs tensor IDs. |
||
| else: | ||
| rows = self._sampler._sample_with_uniform_replay(num_envs) | ||
| if rows.shape != (num_envs,) or rows.dtype != torch.long: | ||
| raise RuntimeError("Adaptive sampler returned invalid reset-row IDs.") | ||
| env_ids = torch.as_tensor(env_ids, device=self._device, dtype=torch.long) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔴 Critical · Compatibility — Preserve Boolean reset selections Casting a Boolean mask to long turns True into environment ID 1; a one-environment all-True reset becomes out of bounds. Convert masks to selected indices before calling the sampler. |
||
| with self._sampler_stream(): | ||
| if (seed := env._reset_dataset_seed) is not None: | ||
| env._reset_dataset_seed = None | ||
| self._sampler.reseed(seed) | ||
| self._replay_generator.manual_seed(seed) | ||
| self._replay.restart(self._replay_generator) | ||
|
|
||
| num_envs = env_ids.numel() | ||
| if num_envs == 0: | ||
| return self._metrics(env) | ||
|
|
||
| if env.cfg.curriculum_freeze: | ||
| slots = torch.randint( | ||
| self._frozen_rows.numel(), (num_envs,), device=self._device, generator=self._replay_generator | ||
| ) | ||
| self._reset_requested_rows(env_ids, self._frozen_rows[slots]) | ||
| else: | ||
| completed = env.reset_buf & (env.episode_length_buf > 0) | ||
| progress = env.termination_manager.get_term_cfg("learning_progress_context").func | ||
| self._sampler.reset(env_ids=env_ids, success=progress.ever_success, valid=completed) | ||
| self._apply_cyclic_replay(env_ids) | ||
|
|
||
| env.reset_dataset_row_id[env_ids] = rows | ||
| index_fill_(env.pour_target_frac, env_ids, float(env.cfg.pour_target_frac)) | ||
| env.reset_dataset_row_id[env_ids] = self._sampler.state_ids.torch[env_ids] | ||
| index_fill_(env.pour_target_frac, env_ids, float(env.cfg.pour_target_frac)) | ||
|
|
||
| if not env.cfg.curriculum_freeze: | ||
| self._local_reset_assignments_since_metrics += num_envs | ||
| if self._local_reset_assignments_since_metrics >= self._local_metrics_refresh_interval: | ||
| self._refresh_metrics_cache() | ||
| return self._metrics(env) | ||
|
|
||
| def _sampler_stream(self) -> wp.ScopedStream: | ||
| """Order resets with Torch request writes and the sampler's persistent Warp state.""" | ||
| stream = None | ||
| if self._device.type == "cuda": | ||
| torch_stream = torch.cuda.current_stream(self._device) | ||
| stream = wp.get_stream(wp.device_from_torch(self._device)) | ||
| if stream.cuda_stream != torch_stream.cuda_stream: | ||
| stream = wp.stream_from_torch(torch_stream) | ||
| return wp.ScopedStream(stream, sync_enter=True, sync_exit=True) | ||
|
|
||
| def _metrics(self, env: FrankaPourEnv) -> dict[str, float]: | ||
| """Return playback or adaptive-sampler metrics.""" | ||
| if env.cfg.curriculum_freeze: | ||
|
|
@@ -109,11 +152,20 @@ def _metrics(self, env: FrankaPourEnv) -> dict[str, float]: | |
| } | ||
| return self._metrics_cache | ||
|
|
||
| def _apply_outcomes(self, rows: torch.Tensor, learning_progress: torch.Tensor) -> None: | ||
| """Apply completed outcomes to the adaptive sampler.""" | ||
| self._sampler._record_validated(rows, learning_progress) | ||
| def _reset_requested_rows(self, env_ids: torch.Tensor, rows: torch.Tensor) -> None: | ||
| self._requested_rows[env_ids] = rows | ||
| self._sampler.reset(env_ids=env_ids, state_ids=self._requested_rows) | ||
|
|
||
| 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() | ||
| 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.""" | ||
| self._metrics_cache = self._sampler.metrics() | ||
| 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 | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🟡 Warning · Compatibility — Preserve the uniform-mode metric
Uniform mode previously reported the configured uniform_fraction through the sampler metric; this sets that metric to zero. Preserve the existing value during deprecation and report effective replay separately.