From b2ee30305f6036f8bde3079081997d3484b57da5 Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Tue, 17 Nov 2026 23:37:46 +0100 Subject: [PATCH 01/13] Require the expected height between stacked cubes --- .../stack-success-height.fixed.rst | 2 + .../contrib/stack/mdp/terminations.py | 48 +++++++++---------- .../test/contrib/stack/test_cubes_stacked.py | 46 ++++++++++++++++++ 3 files changed, 70 insertions(+), 26 deletions(-) create mode 100644 source/isaaclab_tasks/changelog.d/stack-success-height.fixed.rst create mode 100644 source/isaaclab_tasks/test/contrib/stack/test_cubes_stacked.py diff --git a/source/isaaclab_tasks/changelog.d/stack-success-height.fixed.rst b/source/isaaclab_tasks/changelog.d/stack-success-height.fixed.rst new file mode 100644 index 000000000000..b316959cc837 --- /dev/null +++ b/source/isaaclab_tasks/changelog.d/stack-success-height.fixed.rst @@ -0,0 +1,2 @@ +* Fixed cube stacking success to require each adjacent pair to be within the configured height tolerance + of its expected center separation. diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/terminations.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/terminations.py index 5ad8c508438a..0876e274a72f 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/terminations.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/terminations.py @@ -3,7 +3,7 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Common functions that can be used to activate certain terminations for the lift task. +"""Common functions that can be used to activate certain terminations for the stack task. The functions can be passed to the :class:`isaaclab.managers.TerminationTermCfg` object to enable the termination introduced by the function. @@ -23,6 +23,22 @@ from isaaclab.envs import ManagerBasedRLEnv +def cube_pair_is_aligned( + separation: torch.Tensor, xy_threshold: float, height_diff: float, height_threshold: float +) -> torch.Tensor: + """Check adjacent cubes given their upper-minus-lower center displacement. + + The upper cube must lie above the lower cube, within `xy_threshold` horizontally and + `height_threshold` of the expected vertical separation `height_diff`. All distances are in meters. + """ + height = separation[:, 2] + return ( + (torch.linalg.norm(separation[:, :2], dim=1) < xy_threshold) + & (height > 0.0) + & (torch.abs(height - height_diff) < height_threshold) + ) + + def cubes_stacked( env: ManagerBasedRLEnv, robot_cfg: SceneEntityCfg = SceneEntityCfg("robot"), @@ -46,7 +62,7 @@ def cubes_stacked( cube_3_cfg: Scene entity configuration for the cube above cube_2. None disables the third-cube checks for a two-cube task. xy_threshold: Maximum horizontal distance [m] between adjacent cube centers. - height_threshold: Upper tolerance [m] on the vertical center separation minus height_diff. + height_threshold: Tolerance [m] on either side of the expected vertical center separation. height_diff: Expected vertical center separation [m] between adjacent cubes. atol: Absolute tolerance for gripper joint positions [m or rad, depending on joint type] when checking the configured open value. @@ -59,33 +75,13 @@ def cubes_stacked( cube_1: RigidObject = env.scene[cube_1_cfg.name] cube_2: RigidObject = env.scene[cube_2_cfg.name] - pos_diff_c12 = cube_1.data.root_pos_w.torch - cube_2.data.root_pos_w.torch - - # Compute cube position difference in x-y plane - xy_dist_c12 = torch.linalg.norm(pos_diff_c12[:, :2], dim=1) - - # Compute cube height difference - h_dist_c12 = torch.linalg.norm(pos_diff_c12[:, 2:], dim=1) - - # Check cube positions - stacked = xy_dist_c12 < xy_threshold - stacked = torch.logical_and(h_dist_c12 - height_diff < height_threshold, stacked) - stacked = torch.logical_and(pos_diff_c12[:, 2] < 0.0, stacked) + separation_c12 = cube_2.data.root_pos_w.torch - cube_1.data.root_pos_w.torch + stacked = cube_pair_is_aligned(separation_c12, xy_threshold, height_diff, height_threshold) if cube_3_cfg is not None: cube_3: RigidObject = env.scene[cube_3_cfg.name] - pos_diff_c23 = cube_2.data.root_pos_w.torch - cube_3.data.root_pos_w.torch - - # Compute cube position difference in x-y plane - xy_dist_c23 = torch.linalg.norm(pos_diff_c23[:, :2], dim=1) - - # Compute cube height difference - h_dist_c23 = torch.linalg.norm(pos_diff_c23[:, 2:], dim=1) - - # Check cube positions - stacked = torch.logical_and(xy_dist_c23 < xy_threshold, stacked) - stacked = torch.logical_and(h_dist_c23 - height_diff < height_threshold, stacked) - stacked = torch.logical_and(pos_diff_c23[:, 2] < 0.0, stacked) + separation_c23 = cube_3.data.root_pos_w.torch - cube_2.data.root_pos_w.torch + stacked &= cube_pair_is_aligned(separation_c23, xy_threshold, height_diff, height_threshold) # Check gripper positions if hasattr(env.scene, "surface_grippers") and len(env.scene.surface_grippers) > 0: diff --git a/source/isaaclab_tasks/test/contrib/stack/test_cubes_stacked.py b/source/isaaclab_tasks/test/contrib/stack/test_cubes_stacked.py new file mode 100644 index 000000000000..bb22bd48a16a --- /dev/null +++ b/source/isaaclab_tasks/test/contrib/stack/test_cubes_stacked.py @@ -0,0 +1,46 @@ +# 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 types import SimpleNamespace + +import torch + +from isaaclab_tasks.contrib.stack.mdp import cubes_stacked + + +def test_stacked_cubes_require_the_expected_vertical_separation(): + """Nearby cubes with too little vertical separation must not count as stacked.""" + # Each row holds the center heights of one scene, bottom to top. + heights = torch.tensor( + [ + [0.0, 0.0477, 0.0954], + [0.0, 0.0020, 0.0497], + [0.0, 0.0477, 0.0497], + ] + ) + num_envs = len(heights) + scene = { + "robot": SimpleNamespace( + data=SimpleNamespace(joint_pos=SimpleNamespace(torch=torch.full((num_envs, 2), 0.04))), + find_joints=lambda names: ([0, 1], names), + ) + } + for index, center_z in enumerate(heights.T, start=1): + positions = torch.zeros((num_envs, 3)) + positions[:, 2] = center_z + scene[f"cube_{index}"] = SimpleNamespace( + data=SimpleNamespace( + root_pos_w=SimpleNamespace(torch=positions), + root_lin_vel_w=SimpleNamespace(torch=torch.zeros_like(positions)), + ) + ) + env = SimpleNamespace( + scene=scene, + cfg=SimpleNamespace(gripper_joint_names=["finger_joint.*"], gripper_open_val=0.04), + device="cpu", + ) + + assert cubes_stacked(env).tolist() == [True, False, False] + assert cubes_stacked(env, cube_3_cfg=None).tolist() == [True, False, True] From e76e2bec30e361fcb2b4c5a2923eec6f20f1d2b9 Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Wed, 18 Nov 2026 00:07:05 +0100 Subject: [PATCH 02/13] Preserve the default stack height tolerance --- .../stack-success-height.added.rst | 2 + .../stack-success-height.fixed.rst | 4 +- .../changelog.d/stack-success-height.minor | 0 .../config/franka/stack_joint_pos_env_cfg.py | 2 + .../contrib/stack/mdp/terminations.py | 68 ++++++++++++------- .../test/contrib/stack/test_cubes_stacked.py | 11 +-- 6 files changed, 57 insertions(+), 30 deletions(-) create mode 100644 source/isaaclab_tasks/changelog.d/stack-success-height.added.rst create mode 100644 source/isaaclab_tasks/changelog.d/stack-success-height.minor diff --git a/source/isaaclab_tasks/changelog.d/stack-success-height.added.rst b/source/isaaclab_tasks/changelog.d/stack-success-height.added.rst new file mode 100644 index 000000000000..781ab589ecfc --- /dev/null +++ b/source/isaaclab_tasks/changelog.d/stack-success-height.added.rst @@ -0,0 +1,2 @@ +* Added the optional ``symmetric_height_tolerance`` parameter to ``cubes_stacked`` for tasks + that need a lower bound as well as an upper bound on vertical center separation. diff --git a/source/isaaclab_tasks/changelog.d/stack-success-height.fixed.rst b/source/isaaclab_tasks/changelog.d/stack-success-height.fixed.rst index b316959cc837..63add237e979 100644 --- a/source/isaaclab_tasks/changelog.d/stack-success-height.fixed.rst +++ b/source/isaaclab_tasks/changelog.d/stack-success-height.fixed.rst @@ -1,2 +1,2 @@ -* Fixed cube stacking success to require each adjacent pair to be within the configured height tolerance - of its expected center separation. +* Fixed Franka joint-position cube stacking success to reject adjacent cube pairs that are + vertically closer than the expected center separation minus the configured tolerance. diff --git a/source/isaaclab_tasks/changelog.d/stack-success-height.minor b/source/isaaclab_tasks/changelog.d/stack-success-height.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_joint_pos_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_joint_pos_env_cfg.py index 03ae2cbb68ce..eadc40ad4135 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_joint_pos_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_joint_pos_env_cfg.py @@ -76,6 +76,8 @@ def __post_init__(self): self.gripper_open_val = 0.04 self.gripper_threshold = 0.005 + self.terminations.success.params["symmetric_height_tolerance"] = True + # End-effector frame (the shared cubes/spawns come from the base scene). self.scene.ee_frame = make_ee_frame_cfg( base_prim_path="{ENV_REGEX_NS}/Robot/(Geometry/)?panda_link0", diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/terminations.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/terminations.py index 0876e274a72f..47b25067ff98 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/terminations.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/terminations.py @@ -3,11 +3,7 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Common functions that can be used to activate certain terminations for the stack task. - -The functions can be passed to the :class:`isaaclab.managers.TerminationTermCfg` object to enable -the termination introduced by the function. -""" +"""Termination terms for the cube stack task.""" from __future__ import annotations @@ -23,22 +19,6 @@ from isaaclab.envs import ManagerBasedRLEnv -def cube_pair_is_aligned( - separation: torch.Tensor, xy_threshold: float, height_diff: float, height_threshold: float -) -> torch.Tensor: - """Check adjacent cubes given their upper-minus-lower center displacement. - - The upper cube must lie above the lower cube, within `xy_threshold` horizontally and - `height_threshold` of the expected vertical separation `height_diff`. All distances are in meters. - """ - height = separation[:, 2] - return ( - (torch.linalg.norm(separation[:, :2], dim=1) < xy_threshold) - & (height > 0.0) - & (torch.abs(height - height_diff) < height_threshold) - ) - - def cubes_stacked( env: ManagerBasedRLEnv, robot_cfg: SceneEntityCfg = SceneEntityCfg("robot"), @@ -51,6 +31,7 @@ def cubes_stacked( atol: float = 0.0001, rtol: float = 0.0001, max_lin_vel: float | None = 0.05, + symmetric_height_tolerance: bool = False, ) -> torch.Tensor: """Whether the cubes are stacked, released, and at rest. @@ -62,7 +43,7 @@ def cubes_stacked( cube_3_cfg: Scene entity configuration for the cube above cube_2. None disables the third-cube checks for a two-cube task. xy_threshold: Maximum horizontal distance [m] between adjacent cube centers. - height_threshold: Tolerance [m] on either side of the expected vertical center separation. + height_threshold: Upper tolerance [m] on the vertical center separation minus height_diff. height_diff: Expected vertical center separation [m] between adjacent cubes. atol: Absolute tolerance for gripper joint positions [m or rad, depending on joint type] when checking the configured open value. @@ -70,18 +51,27 @@ def cubes_stacked( open value. Gripper joint tolerances are unused for surface grippers. max_lin_vel: Speed [m/s] below which a cube counts as at rest, so that a cube passing through the stacked configuration mid-fall is not scored as success. ``None`` disables the check. + symmetric_height_tolerance: Also require the vertical separation to be within + ``height_threshold`` below ``height_diff``. + + Returns: + A boolean tensor of shape [N] indicating success in each environment. """ robot: Articulation = env.scene[robot_cfg.name] cube_1: RigidObject = env.scene[cube_1_cfg.name] cube_2: RigidObject = env.scene[cube_2_cfg.name] separation_c12 = cube_2.data.root_pos_w.torch - cube_1.data.root_pos_w.torch - stacked = cube_pair_is_aligned(separation_c12, xy_threshold, height_diff, height_threshold) + stacked = _cube_pair_is_aligned( + separation_c12, xy_threshold, height_diff, height_threshold, symmetric_height_tolerance + ) if cube_3_cfg is not None: cube_3: RigidObject = env.scene[cube_3_cfg.name] separation_c23 = cube_3.data.root_pos_w.torch - cube_2.data.root_pos_w.torch - stacked &= cube_pair_is_aligned(separation_c23, xy_threshold, height_diff, height_threshold) + stacked &= _cube_pair_is_aligned( + separation_c23, xy_threshold, height_diff, height_threshold, symmetric_height_tolerance + ) # Check gripper positions if hasattr(env.scene, "surface_grippers") and len(env.scene.surface_grippers) > 0: @@ -115,3 +105,33 @@ def cubes_stacked( stacked &= torch.linalg.norm(cube.data.root_lin_vel_w.torch, dim=1) < max_lin_vel return stacked + + +def _cube_pair_is_aligned( + separation: torch.Tensor, + xy_threshold: float, + height_diff: float, + height_threshold: float, + symmetric_height_tolerance: bool, +) -> torch.Tensor: + """Check the world-frame upper-minus-lower cube displacement. + + Args: + separation: Cube center displacements in meters, with shape [N, 3]. + xy_threshold: Maximum horizontal separation in meters. + height_diff: Expected vertical separation in meters. + height_threshold: Tolerance on the vertical separation in meters. + symmetric_height_tolerance: Apply the tolerance below as well as above ``height_diff``. + + Returns: + A boolean tensor of shape [N] indicating aligned cube pairs. + """ + height = separation[:, 2] + height_error = height - height_diff + if symmetric_height_tolerance: + height_error = height_error.abs() + return ( + (torch.linalg.norm(separation[:, :2], dim=1) < xy_threshold) + & (height > 0.0) + & (height_error < height_threshold) + ) diff --git a/source/isaaclab_tasks/test/contrib/stack/test_cubes_stacked.py b/source/isaaclab_tasks/test/contrib/stack/test_cubes_stacked.py index bb22bd48a16a..4e1b3b7e05d5 100644 --- a/source/isaaclab_tasks/test/contrib/stack/test_cubes_stacked.py +++ b/source/isaaclab_tasks/test/contrib/stack/test_cubes_stacked.py @@ -5,13 +5,15 @@ from types import SimpleNamespace +import pytest import torch from isaaclab_tasks.contrib.stack.mdp import cubes_stacked +pytestmark = pytest.mark.kitless -def test_stacked_cubes_require_the_expected_vertical_separation(): - """Nearby cubes with too little vertical separation must not count as stacked.""" + +def test_stacked_cubes_can_require_the_expected_vertical_separation() -> None: # Each row holds the center heights of one scene, bottom to top. heights = torch.tensor( [ @@ -42,5 +44,6 @@ def test_stacked_cubes_require_the_expected_vertical_separation(): device="cpu", ) - assert cubes_stacked(env).tolist() == [True, False, False] - assert cubes_stacked(env, cube_3_cfg=None).tolist() == [True, False, True] + assert cubes_stacked(env).tolist() == [True, True, True] + assert cubes_stacked(env, symmetric_height_tolerance=True).tolist() == [True, False, False] + assert cubes_stacked(env, cube_3_cfg=None, symmetric_height_tolerance=True).tolist() == [True, False, True] From 611d070e70f1b789e05a2fc067b5506f22586b0f Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Wed, 18 Nov 2026 00:09:53 +0100 Subject: [PATCH 03/13] Exercise the configured Franka stack termination --- .../changelog.d/stack-success-height.fixed.rst | 4 ++-- .../test/contrib/stack/test_cubes_stacked.py | 9 ++++++--- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/source/isaaclab_tasks/changelog.d/stack-success-height.fixed.rst b/source/isaaclab_tasks/changelog.d/stack-success-height.fixed.rst index 63add237e979..a173f9ff00df 100644 --- a/source/isaaclab_tasks/changelog.d/stack-success-height.fixed.rst +++ b/source/isaaclab_tasks/changelog.d/stack-success-height.fixed.rst @@ -1,2 +1,2 @@ -* Fixed Franka joint-position cube stacking success to reject adjacent cube pairs that are - vertically closer than the expected center separation minus the configured tolerance. +* Fixed the Franka cube stack success term in the joint-position base configuration to reject + adjacent pairs closer than the expected height minus the vertical tolerance. diff --git a/source/isaaclab_tasks/test/contrib/stack/test_cubes_stacked.py b/source/isaaclab_tasks/test/contrib/stack/test_cubes_stacked.py index 4e1b3b7e05d5..5e5fd5aaa6af 100644 --- a/source/isaaclab_tasks/test/contrib/stack/test_cubes_stacked.py +++ b/source/isaaclab_tasks/test/contrib/stack/test_cubes_stacked.py @@ -8,6 +8,7 @@ import pytest import torch +from isaaclab_tasks.contrib.stack.config.franka.stack_joint_pos_env_cfg import FrankaCubeStackEnvCfg from isaaclab_tasks.contrib.stack.mdp import cubes_stacked pytestmark = pytest.mark.kitless @@ -38,12 +39,14 @@ def test_stacked_cubes_can_require_the_expected_vertical_separation() -> None: root_lin_vel_w=SimpleNamespace(torch=torch.zeros_like(positions)), ) ) + cfg = FrankaCubeStackEnvCfg() + success = cfg.terminations.success env = SimpleNamespace( scene=scene, - cfg=SimpleNamespace(gripper_joint_names=["finger_joint.*"], gripper_open_val=0.04), + cfg=cfg, device="cpu", ) assert cubes_stacked(env).tolist() == [True, True, True] - assert cubes_stacked(env, symmetric_height_tolerance=True).tolist() == [True, False, False] - assert cubes_stacked(env, cube_3_cfg=None, symmetric_height_tolerance=True).tolist() == [True, False, True] + assert success.func(env, **success.params).tolist() == [True, False, False] + assert success.func(env, cube_3_cfg=None, **success.params).tolist() == [True, False, True] From 9ab2bfb5f7df7b7e7defd5a6a2e547c435697469 Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Wed, 18 Nov 2026 00:10:53 +0100 Subject: [PATCH 04/13] Keep the existing stack tasks on their configured height checks --- .../changelog.d/stack-success-height.fixed.rst | 2 -- .../stack/config/franka/stack_joint_pos_env_cfg.py | 2 -- .../test/contrib/stack/test_cubes_stacked.py | 9 +++------ 3 files changed, 3 insertions(+), 10 deletions(-) delete mode 100644 source/isaaclab_tasks/changelog.d/stack-success-height.fixed.rst diff --git a/source/isaaclab_tasks/changelog.d/stack-success-height.fixed.rst b/source/isaaclab_tasks/changelog.d/stack-success-height.fixed.rst deleted file mode 100644 index a173f9ff00df..000000000000 --- a/source/isaaclab_tasks/changelog.d/stack-success-height.fixed.rst +++ /dev/null @@ -1,2 +0,0 @@ -* Fixed the Franka cube stack success term in the joint-position base configuration to reject - adjacent pairs closer than the expected height minus the vertical tolerance. diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_joint_pos_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_joint_pos_env_cfg.py index eadc40ad4135..03ae2cbb68ce 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_joint_pos_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_joint_pos_env_cfg.py @@ -76,8 +76,6 @@ def __post_init__(self): self.gripper_open_val = 0.04 self.gripper_threshold = 0.005 - self.terminations.success.params["symmetric_height_tolerance"] = True - # End-effector frame (the shared cubes/spawns come from the base scene). self.scene.ee_frame = make_ee_frame_cfg( base_prim_path="{ENV_REGEX_NS}/Robot/(Geometry/)?panda_link0", diff --git a/source/isaaclab_tasks/test/contrib/stack/test_cubes_stacked.py b/source/isaaclab_tasks/test/contrib/stack/test_cubes_stacked.py index 5e5fd5aaa6af..4e1b3b7e05d5 100644 --- a/source/isaaclab_tasks/test/contrib/stack/test_cubes_stacked.py +++ b/source/isaaclab_tasks/test/contrib/stack/test_cubes_stacked.py @@ -8,7 +8,6 @@ import pytest import torch -from isaaclab_tasks.contrib.stack.config.franka.stack_joint_pos_env_cfg import FrankaCubeStackEnvCfg from isaaclab_tasks.contrib.stack.mdp import cubes_stacked pytestmark = pytest.mark.kitless @@ -39,14 +38,12 @@ def test_stacked_cubes_can_require_the_expected_vertical_separation() -> None: root_lin_vel_w=SimpleNamespace(torch=torch.zeros_like(positions)), ) ) - cfg = FrankaCubeStackEnvCfg() - success = cfg.terminations.success env = SimpleNamespace( scene=scene, - cfg=cfg, + cfg=SimpleNamespace(gripper_joint_names=["finger_joint.*"], gripper_open_val=0.04), device="cpu", ) assert cubes_stacked(env).tolist() == [True, True, True] - assert success.func(env, **success.params).tolist() == [True, False, False] - assert success.func(env, cube_3_cfg=None, **success.params).tolist() == [True, False, True] + assert cubes_stacked(env, symmetric_height_tolerance=True).tolist() == [True, False, False] + assert cubes_stacked(env, cube_3_cfg=None, symmetric_height_tolerance=True).tolist() == [True, False, True] From ced1fda5ca0d46a12c1371e49ab552cb9cd128f9 Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Wed, 18 Nov 2026 00:43:55 +0100 Subject: [PATCH 05/13] Restore Franka stacking resets and adaptive sampling --- .../franka-stack-reset-curriculum.added.rst | 2 + .../franka-stack-reset-curriculum.minor | 0 .../isaaclab_tasks/contrib/stack/constants.py | 28 + .../contrib/stack/mdp/curriculums.py | 168 ++++ .../contrib/stack/mdp/reset_events.py | 893 ++++++++++++++++++ .../contrib/stack/mdp/runtime_state.py | 55 ++ 6 files changed, 1146 insertions(+) create mode 100644 source/isaaclab_tasks/changelog.d/franka-stack-reset-curriculum.added.rst create mode 100644 source/isaaclab_tasks/changelog.d/franka-stack-reset-curriculum.minor create mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/stack/constants.py create mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/curriculums.py create mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/reset_events.py create mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/runtime_state.py diff --git a/source/isaaclab_tasks/changelog.d/franka-stack-reset-curriculum.added.rst b/source/isaaclab_tasks/changelog.d/franka-stack-reset-curriculum.added.rst new file mode 100644 index 000000000000..a4145c6bc776 --- /dev/null +++ b/source/isaaclab_tasks/changelog.d/franka-stack-reset-curriculum.added.rst @@ -0,0 +1,2 @@ +* Added validated phase-specific Franka cube-stacking resets and a curriculum that + retains table starts alongside starts sampled from recent episode outcomes. diff --git a/source/isaaclab_tasks/changelog.d/franka-stack-reset-curriculum.minor b/source/isaaclab_tasks/changelog.d/franka-stack-reset-curriculum.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/constants.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/constants.py new file mode 100644 index 000000000000..ffc6e0bdfe08 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/constants.py @@ -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 + +"""Shared physical constants for cube-stacking tasks.""" + +FRANKA_STACK_ARM_WORKSPACE_LOWER: tuple[float, ...] = ( + -0.303, + -0.200, + -0.328, + -2.759, + -0.124, + 2.393, + 0.271, +) +"""Lower joint-position boundary of the validated Franka stacking workspace [rad].""" + +FRANKA_STACK_ARM_WORKSPACE_UPPER: tuple[float, ...] = ( + 0.450, + 0.603, + 0.147, + -2.000, + 0.345, + 3.112, + 1.200, +) +"""Upper joint-position boundary of the validated Franka stacking workspace [rad].""" diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/curriculums.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/curriculums.py new file mode 100644 index 000000000000..3e10e7d59ef4 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/curriculums.py @@ -0,0 +1,168 @@ +# 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-monitored reset sampling for cube stacking.""" + +from __future__ import annotations + +import math +from collections.abc import Sequence +from typing import TYPE_CHECKING + +import torch + +from isaaclab.managers import CurriculumTermCfg, ManagerTermBase +from isaaclab.utils.configclass import instantiate + +from isaaclab_tasks.utils.success_monitor import SuccessMonitorCfg + +from .reset_events import StackResetRecipe, StackResetStateTable +from .runtime_state import get_stack_reset_runtime_state + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedRLEnv + + +class StackResetTableCurriculum(ManagerTermBase): + """Mix guaranteed table starts with target-rate reset sampling.""" + + def __init__(self, cfg: CurriculumTermCfg, env: ManagerBasedRLEnv): + super().__init__(cfg, env) + reset_term = env.event_manager.get_term_cfg("reset_from_state_buffer").func + if not isinstance(reset_term, StackResetStateTable): + raise RuntimeError("StackResetTableCurriculum requires StackResetStateTable.") + self._reset_term = reset_term + monitor_cfg = cfg.params.get("success_monitor") + if not isinstance(monitor_cfg, SuccessMonitorCfg): + raise TypeError("StackResetTableCurriculum requires a SuccessMonitorCfg.") + self._progress_monitor = instantiate( + monitor_cfg, + num_partitions=1, + partition_size=reset_term.row_count, + device=env.device, + ) + self._attempts = torch.zeros(reset_term.row_count, dtype=torch.long, device=env.device) + self._progress_successes = torch.zeros_like(self._attempts) + self._table_sampling_probability = float(cfg.params.get("table_sampling_probability", 0.35)) + if not 0.0 < self._table_sampling_probability < 1.0: + raise ValueError("table_sampling_probability must lie strictly between zero and one.") + self._table_rows = reset_term.recipe_ids == StackResetRecipe.TABLE + if not bool(torch.any(self._table_rows)) or bool(torch.all(self._table_rows)): + raise RuntimeError("The stack reset table must contain both table and intermediate rows.") + self._layout_count = reset_term.layout_count + self._metric_partitions: dict[str, tuple[tuple[str, torch.Tensor], ...]] = { + "recipe": tuple( + (name, reset_term.recipe_ids == recipe) for recipe, name in enumerate(reset_term.recipe_names) + ) + } + self._full_task_successes_by_row = torch.zeros_like(self._attempts) + + def _sampling_distribution(self) -> torch.Tensor: + """Mix uniform table starts with layout-balanced intermediate starts.""" + adaptive = self._progress_monitor.target_weights() + adaptive[self._table_rows] = 0.0 + layout_ids = self._reset_term.layout_ids + layout_mass = torch.zeros(self._layout_count, dtype=adaptive.dtype, device=adaptive.device) + layout_mass.scatter_add_(0, layout_ids, adaptive) + adaptive /= layout_mass[layout_ids].clamp_min(torch.finfo(adaptive.dtype).tiny) + adaptive /= adaptive.sum() + table = self._table_rows.to(dtype=adaptive.dtype) + table /= table.sum() + probabilities = (1.0 - self._table_sampling_probability) * adaptive + self._table_sampling_probability * table + return probabilities + + def __call__( + self, + env: ManagerBasedRLEnv, + env_ids: Sequence[int] | torch.Tensor | slice | None, + success_monitor: SuccessMonitorCfg, + success_context_name: str = "learning_progress_context", + final_success_context_name: str = "progress_context", + table_sampling_probability: float = 0.35, + ) -> dict[str, torch.Tensor]: + """Credit completed episodes and update the reset event's distribution.""" + del ( + success_monitor, + table_sampling_probability, + ) + if env_ids is None or isinstance(env_ids, slice): + env_ids = torch.arange(env.num_envs, device=env.device)[env_ids if env_ids is not None else slice(None)] + ids = torch.as_tensor(env_ids, dtype=torch.long, device=env.device).flatten() + metrics: dict[str, torch.Tensor] = { + "batch_table_full_task_attempts": torch.zeros((), device=env.device), + } + if ids.numel(): + state = get_stack_reset_runtime_state(env) + completed = (state.row_ids[ids] >= 0) & (env.episode_length_buf[ids] > 0) & env.reset_buf[ids] + completed_ids = ids[completed] + if completed_ids.numel(): + success_context = env.termination_manager.get_term_cfg(success_context_name).func + succeeded = success_context.ever_success[completed_ids] + final_success_context = env.termination_manager.get_term_cfg(final_success_context_name).func + final_succeeded = final_success_context.ever_success[completed_ids] + metrics["batch_success_rate"] = succeeded.float().mean() + metrics["batch_full_task_success_rate"] = final_succeeded.float().mean() + completed_rows = state.row_ids[completed_ids] + completed_table = self._table_rows[completed_rows] + table_attempts = completed_table.sum() + metrics["batch_table_full_task_attempts"] = table_attempts + if bool(table_attempts): + metrics["batch_table_full_task_success_rate"] = final_succeeded[completed_table].float().mean() + self._progress_monitor.success_update(completed_rows, succeeded) + self._attempts.add_(torch.bincount(completed_rows, minlength=self._reset_term.row_count)) + self._progress_successes.add_( + torch.bincount(completed_rows[succeeded], minlength=self._reset_term.row_count) + ) + self._full_task_successes_by_row.add_( + torch.bincount(completed_rows[final_succeeded], minlength=self._reset_term.row_count) + ) + + probabilities = self._sampling_distribution() + self._reset_term.update_sampling_probabilities(probabilities) + + attempts = self._attempts + observed = attempts > 0 + success_rate = self._progress_successes.sum().float() / attempts.sum().clamp_min(1) + entropy = -(probabilities * probabilities.clamp_min(torch.finfo(probabilities.dtype).tiny).log()).sum() + entropy /= math.log(probabilities.numel()) + active_rows = ~self._table_rows + unseen_rows = active_rows & ~observed + rolling_rates = self._progress_monitor.get_success_rate() + observed_count = observed.sum().clamp_min(1) + metrics.update( + { + "row_coverage": observed.float().mean(), + "row_success_rate": success_rate, + "rolling_row_success_rate": (rolling_rates * observed).sum() / observed_count, + "sampling_entropy": entropy, + "unseen_row_probability_mass": probabilities[unseen_rows].sum(), + "table_probability": probabilities[self._table_rows].sum(), + "target_band_fraction": ( + ((rolling_rates - self._progress_monitor.cfg.target_success_rate).abs() <= 0.1) & observed + ).sum() + / observed_count, + "full_task_attempts": attempts.sum().float(), + "full_task_success_rate": self._full_task_successes_by_row.sum().float() / attempts.sum().clamp_min(1), + "table_curriculum_success_rate": self._progress_successes[self._table_rows].sum().float() + / self._attempts[self._table_rows].sum().clamp_min(1), + "table_full_task_success_rate": self._full_task_successes_by_row[self._table_rows].sum().float() + / attempts[self._table_rows].sum().clamp_min(1), + "table_full_task_attempts": attempts[self._table_rows].sum().float(), + } + ) + for prefix, partitions in self._metric_partitions.items(): + for name, rows in partitions: + partition_attempts = attempts[rows].sum() + metric_prefix = f"{prefix}_{name}" + metrics[f"{metric_prefix}_attempts"] = partition_attempts + metrics[f"{metric_prefix}_full_stack_attempts"] = partition_attempts + metrics[f"{metric_prefix}_probability"] = probabilities[rows].sum() + metrics[f"{metric_prefix}_curriculum_success"] = self._progress_successes[ + rows + ].sum().float() / partition_attempts.clamp_min(1) + metrics[f"{metric_prefix}_full_stack_success"] = self._full_task_successes_by_row[ + rows + ].sum().float() / partition_attempts.clamp_min(1) + return metrics diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/reset_events.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/reset_events.py new file mode 100644 index 000000000000..b8ca414bd7d3 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/reset_events.py @@ -0,0 +1,893 @@ +# 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 + +"""Collision-free phase reset states for Franka cube-stack reinforcement learning.""" + +from __future__ import annotations + +import math +from collections.abc import Sequence +from enum import IntEnum +from itertools import permutations +from typing import TYPE_CHECKING + +import torch + +from isaaclab.managers import EventTermCfg, ManagerTermBase +from isaaclab.utils.math import matrix_from_quat, normalize, quat_mul + +from ..constants import FRANKA_STACK_ARM_WORKSPACE_LOWER, FRANKA_STACK_ARM_WORKSPACE_UPPER +from .runtime_state import create_stack_reset_runtime_state + +if TYPE_CHECKING: + from isaaclab.assets import Articulation, RigidObject + from isaaclab.envs import ManagerBasedRLEnv + + +# These center-column seeds were generated with constrained Franka +# differential IK against the active Newton articulation. Rows are workspace +# anchors; columns are +# near-grasp, pre-grasp, lifted/aligned, final-aligned, and release heights. +# The gripper tool poses are 0.04, 0.08, 0.14, 0.17, and 0.1175 m above the +# table with a common downward-facing tool orientation. +_ARM_POSES = ( + ( + (-0.1572749, 0.4348711, -0.1066657, -2.3711381, 0.1346695, 2.8009815, 0.4043023), + (-0.1275118, 0.3274296, -0.1422084, -2.3924634, 0.1102695, 2.7145238, 0.4227046), + (-0.0635889, 0.1786218, -0.2144134, -2.3994358, 0.0702603, 2.5729306, 0.4514749), + (-0.0389951, 0.1104695, -0.2425126, -2.3916225, 0.0441574, 2.4984162, 0.4699694), + (-0.1165679, 0.2313573, -0.1596608, -2.4005361, 0.0742505, 2.6278727, 0.4486592), + ), + ( + (0.0746626, 0.3993853, -0.0614371, -2.4394584, 0.0797585, 2.8372586, 0.7273404), + (0.0850676, 0.2860484, -0.0767592, -2.4610789, 0.0561473, 2.7457693, 0.7450000), + (0.0856794, 0.1286848, -0.0835223, -2.4678085, 0.0206312, 2.5959551, 0.7706067), + (0.0800510, 0.0578652, -0.0794689, -2.4595215, 0.0078535, 2.5171897, 0.7797412), + (0.0834069, 0.1854414, -0.0795486, -2.4689438, 0.0312558, 2.6536098, 0.7630054), + ), + ( + (0.3427543, 0.4323400, -0.0496637, -2.3724809, 0.0627942, 2.8037355, 1.0237991), + (0.3287566, 0.3239155, -0.0409105, -2.3935080, 0.0316034, 2.7169836, 1.0465709), + (0.2909108, 0.1743402, -0.0069321, -2.3998964, 0.0022373, 2.5742316, 1.0675952), + (0.2686295, 0.1071830, 0.0150251, -2.3918052, -0.0026820, 2.4989743, 1.0711135), + (0.3086198, 0.2282527, -0.0237074, -2.4010389, 0.0109410, 2.6292043, 1.0613892), + ), +) + +# The reset table extends those three x=0.48 m seeds to a two-dimensional +# workspace grid. The x=0.43 m and x=0.53 m rows were solved with constrained +# IK while preserving the downward tool orientation and all task joint bounds. +# Rows are ordered by y, then x; pose columns use the same heights as the seeds. +_STATE_TABLE_ANCHORS = ( + (0.43, -0.14), + (0.48, -0.14), + (0.53, -0.14), + (0.43, 0.00), + (0.48, 0.00), + (0.53, 0.00), + (0.43, 0.14), + (0.48, 0.14), + (0.53, 0.14), +) +_STATE_TABLE_ARM_POSES = ( + ( + (-0.1827602, 0.3566961, -0.1050870, -2.5290027, 0.1427738, 2.8813359, 0.3660968), + (-0.1405546, 0.2356171, -0.1561482, -2.5522243, 0.1037001, 2.7832902, 0.3957875), + (-0.0762273, 0.0652657, -0.2344268, -2.5599217, 0.0305949, 2.6231837, 0.4486480), + (-0.0567678, -0.0127596, -0.2585924, -2.5512829, -0.0057401, 2.5389172, 0.4747868), + (-0.1281367, 0.1264810, -0.1788741, -2.5610143, 0.0509304, 2.6849632, 0.4340674), + ), + _ARM_POSES[0], + ( + (-0.1393943, 0.5199573, -0.1061595, -2.2020593, 0.1280282, 2.7165339, 0.4370434), + (-0.1174986, 0.4231741, -0.1322305, -2.2222437, 0.1127438, 2.6394885, 0.4482890), + (-0.0615496, 0.2909696, -0.1942067, -2.2286049, 0.0942004, 2.5123129, 0.4613796), + (-0.0375556, 0.2308812, -0.2210795, -2.2211458, 0.0782906, 2.4451143, 0.4723408), + (-0.1101384, 0.3372053, -0.1440187, -2.2298284, 0.0868206, 2.5620956, 0.4665478), + ), + ( + (0.0759730, 0.3203934, -0.0586236, -2.6010992, 0.0841265, 2.9201983, 0.7236422), + (0.0905887, 0.1910140, -0.0812289, -2.6248224, 0.0480300, 2.8148493, 0.7507357), + (0.0851180, 0.0105646, -0.0848236, -2.6321305, 0.0018844, 2.6426351, 0.7840414), + (0.0770806, -0.0701720, -0.0783512, -2.6230035, -0.0098754, 2.5530024, 0.7925323), + (0.0854193, 0.0756269, -0.0828133, -2.6334135, 0.0149155, 2.7087184, 0.7746989), + ), + _ARM_POSES[1], + ( + (0.0715528, 0.4848095, -0.0624548, -2.2682690, 0.0765225, 2.7512705, 0.7308913), + (0.0786326, 0.3836816, -0.0728342, -2.2885879, 0.0600667, 2.6706451, 0.7429353), + (0.0798587, 0.2440989, -0.0782379, -2.2949124, 0.0332810, 2.5380599, 0.7619260), + (0.0758883, 0.1812225, -0.0755081, -2.2871444, 0.0217849, 2.4677707, 0.7699870), + (0.0770234, 0.2943766, -0.0742011, -2.2959744, 0.0409981, 2.5892367, 0.7564962), + ), + ( + (0.3733737, 0.3543693, -0.0466062, -2.5305452, 0.0635564, 2.8840421, 1.0535889), + (0.3549292, 0.2323785, -0.0360207, -2.5531699, 0.0238133, 2.7852886, 1.0829521), + (0.3077923, 0.0634289, 0.0068468, -2.5600088, -0.0008622, 2.6234150, 1.1007691), + (0.2840671, -0.0123435, 0.0307596, -2.5512871, 0.0006774, 2.5389282, 1.0996615), + (0.3281968, 0.1243308, -0.0128874, -2.5612529, 0.0036501, 2.6855496, 1.0975263), + ), + _ARM_POSES[2], + ( + (0.3161607, 0.5173145, -0.0516801, -2.2032379, 0.0623529, 2.7192778, 0.9997473), + (0.3037271, 0.4195258, -0.0427033, -2.2233085, 0.0363061, 2.6422440, 1.0182483), + (0.2721164, 0.2853546, -0.0136850, -2.2294290, 0.0065578, 2.5147738, 1.0390748), + (0.2527010, 0.2252003, 0.0055606, -2.2217196, -0.0019461, 2.4469407, 1.0450170), + (0.2871863, 0.3336694, -0.0281290, -2.2305052, 0.0168593, 2.5640130, 1.0318844), + ), +) + +# Every stack location receives both source-order variants. Source anchors are +# chosen by maximin distance, so every pick begins at least 14.8 cm from the +# other two roles and no physical left/right order is privileged. +_STATE_TABLE_LAYOUTS = ( + (0, 5, 6), + (0, 6, 5), + (1, 5, 6), + (1, 6, 5), + (2, 3, 8), + (2, 8, 3), + (3, 2, 8), + (3, 8, 2), + (4, 2, 8), + (4, 8, 2), + (5, 0, 6), + (5, 6, 0), + (6, 0, 5), + (6, 5, 0), + (7, 0, 5), + (7, 5, 0), + (8, 2, 3), + (8, 3, 2), +) +_NEAR_GRASP_POSE_INDEX = 0 +_PREGRASP_POSE_INDEX = 1 +_LIFTED_OR_RED_ALIGNED_POSE_INDEX = 2 +_GREEN_ALIGNED_POSE_INDEX = 3 +_GREEN_RELEASE_POSE_INDEX = 4 + + +class StackResetRecipe(IntEnum): + """Physical reset recipes in the order-invariant stack table.""" + + FINAL_RELEASE = 0 + SECOND_PLACE = 1 + SECOND_TRANSPORT = 2 + SECOND_PICK = 3 + PAIR_READY = 4 + FIRST_PLACE = 5 + FIRST_TRANSPORT = 6 + FIRST_PICK = 7 + TABLE = 8 + + +_RECIPE_TARGET_POTENTIAL = { + StackResetRecipe.FINAL_RELEASE: 10.0, + StackResetRecipe.SECOND_PLACE: 10.0, + StackResetRecipe.SECOND_TRANSPORT: 8.0, + StackResetRecipe.SECOND_PICK: 6.0, + StackResetRecipe.PAIR_READY: 6.0, + StackResetRecipe.FIRST_PLACE: 5.0, + StackResetRecipe.FIRST_TRANSPORT: 3.0, + StackResetRecipe.FIRST_PICK: 1.0, + StackResetRecipe.TABLE: 1.0, +} + + +_FRANKA_JOINT_ORIGINS = ( + ((0.0, 0.0, 0.333), (0.0, 0.0, 0.0)), + ((0.0, 0.0, 0.0), (-math.pi / 2.0, 0.0, 0.0)), + ((0.0, -0.316, 0.0), (math.pi / 2.0, 0.0, 0.0)), + ((0.0825, 0.0, 0.0), (math.pi / 2.0, 0.0, 0.0)), + ((-0.0825, 0.384, 0.0), (-math.pi / 2.0, 0.0, 0.0)), + ((0.0, 0.0, 0.0), (math.pi / 2.0, 0.0, 0.0)), + ((0.088, 0.0, 0.0), (math.pi / 2.0, 0.0, 0.0)), +) +_FRANKA_HAND_AND_TOOL_OFFSET = 0.107 + 0.1034 + + +def _rotation_matrix_from_rpy( + roll: float, + pitch: float, + yaw: float, + reference: torch.Tensor, +) -> torch.Tensor: + """Return a fixed-origin XYZ roll-pitch-yaw rotation matrix.""" + cx, sx = math.cos(roll), math.sin(roll) + cy, sy = math.cos(pitch), math.sin(pitch) + cz, sz = math.cos(yaw), math.sin(yaw) + return reference.new_tensor( + ( + (cz * cy, cz * sy * sx - sz * cx, cz * sy * cx + sz * sx), + (sz * cy, sz * sy * sx + cz * cx, sz * sy * cx - cz * sx), + (-sy, cy * sx, cy * cx), + ) + ) + + +def _oriented_cube_pair_intersections( + first_centers: torch.Tensor, + first_rotations: torch.Tensor, + second_centers: torch.Tensor, + second_rotations: torch.Tensor, + *, + edge_length: float, + penetration_tolerance: float = 1.0e-4, +) -> torch.Tensor: + """Return rows where two oriented cubes overlap by more than a tolerance. + + This is an exact 15-axis separating-axis test for two oriented boxes. + Face-normal checks alone are insufficient for tilted reset cubes, and the + previous center-distance approximation missed corner/edge intersections. + Degenerate cross products from parallel box axes are ignored. + """ + if first_centers.shape != second_centers.shape or first_centers.shape[-1] != 3: + raise ValueError("Cube centers must have matching shapes ending in three coordinates.") + expected_rotation_shape = first_centers.shape[:-1] + (3, 3) + if first_rotations.shape != expected_rotation_shape or second_rotations.shape != expected_rotation_shape: + raise ValueError("Cube rotations must match the center batch shape and end in (3, 3).") + if edge_length <= 0.0: + raise ValueError("Cube edge length must be positive.") + if penetration_tolerance < 0.0: + raise ValueError("Cube penetration tolerance must be non-negative.") + + # Rotation-matrix columns are each box's local axes in world coordinates. + first_axes = first_rotations.transpose(-1, -2) + second_axes = second_rotations.transpose(-1, -2) + cross_axes = torch.linalg.cross( + first_axes.unsqueeze(-2), + second_axes.unsqueeze(-3), + dim=-1, + ).flatten(start_dim=-3, end_dim=-2) + candidate_axes = torch.cat((first_axes, second_axes, cross_axes), dim=-2) + axis_norms = torch.linalg.vector_norm(candidate_axes, dim=-1) + valid_axes = axis_norms > 1.0e-7 + normalized_axes = candidate_axes / axis_norms.clamp_min(1.0e-7).unsqueeze(-1) + + center_delta = second_centers - first_centers + center_projection = torch.abs(torch.sum(center_delta.unsqueeze(-2) * normalized_axes, dim=-1)) + first_projection = torch.abs(torch.sum(first_axes.unsqueeze(-3) * normalized_axes.unsqueeze(-2), dim=-1)).sum( + dim=-1 + ) + second_projection = torch.abs(torch.sum(second_axes.unsqueeze(-3) * normalized_axes.unsqueeze(-2), dim=-1)).sum( + dim=-1 + ) + projected_radius = 0.5 * edge_length * (first_projection + second_projection) + + separated = valid_axes & (center_projection >= projected_radius - penetration_tolerance) + return ~torch.any(separated, dim=-1) + + +def _franka_tool_position(joint_positions: torch.Tensor) -> torch.Tensor: + """Compute configured Panda tool-center positions from seven joints. + + Reset rows must preserve the rigid transform between a held cube and the + fingers. Interpolating robot joints and cube Cartesian positions + independently violates that transform by up to two centimeters and + produces a floating object that immediately falls under gravity. This + compact forward kinematics follows the Franka joint origins authored in + the task's robot asset and includes the configured 10.34 cm action-frame + offset from ``panda_hand``. + + Args: + joint_positions: Franka arm positions [rad], shape ``(..., 7)``. + + Returns: + Tool-center positions [m], shape ``(..., 3)``. + """ + if joint_positions.ndim < 1 or joint_positions.shape[-1] != 7: + raise ValueError("Franka reset forward kinematics expects seven joint positions.") + batch_shape = joint_positions.shape[:-1] + flat_joints = joint_positions.reshape(-1, 7) + batch_size = flat_joints.shape[0] + rotation = ( + torch.eye(3, dtype=joint_positions.dtype, device=joint_positions.device) + .unsqueeze(0) + .expand(batch_size, -1, -1) + .clone() + ) + position = torch.zeros((batch_size, 3), dtype=joint_positions.dtype, device=joint_positions.device) + reference = flat_joints[0] if batch_size > 0 else joint_positions.new_zeros(7) + for joint_id, (origin_position, origin_rpy) in enumerate(_FRANKA_JOINT_ORIGINS): + origin = joint_positions.new_tensor(origin_position).expand(batch_size, -1) + position = position + torch.bmm(rotation, origin.unsqueeze(-1)).squeeze(-1) + origin_rotation = _rotation_matrix_from_rpy(*origin_rpy, reference=reference) + rotation = torch.matmul(rotation, origin_rotation) + angle = flat_joints[:, joint_id] + cosine, sine = torch.cos(angle), torch.sin(angle) + zeros = torch.zeros_like(angle) + ones = torch.ones_like(angle) + joint_rotation = torch.stack( + ( + torch.stack((cosine, -sine, zeros), dim=1), + torch.stack((sine, cosine, zeros), dim=1), + torch.stack((zeros, zeros, ones), dim=1), + ), + dim=1, + ) + rotation = torch.bmm(rotation, joint_rotation) + tool_offset = joint_positions.new_tensor((0.0, 0.0, _FRANKA_HAND_AND_TOOL_OFFSET)).expand(batch_size, -1) + tool_position = position + torch.bmm(rotation, tool_offset.unsqueeze(-1)).squeeze(-1) + return tool_position.reshape(*batch_shape, 3) + + +class StackResetStateTable(ManagerTermBase): + """Apply a validated cache of order-invariant stack states. + + Rows describe physical roles (base, first movable cube, second movable + cube), not cube colors. Every reset independently permutes the three + colored assets over those roles. The curriculum therefore learns one + physical reset manifold and aggregates evidence across all six color + orders instead of treating color order as task semantics. + + The cache deliberately contains many more rows than there are semantic + phases. Motion phases are densely interpolated and table starts span a + deterministic low-discrepancy layout set. Complete physical states are + sampled from a shared validated cache, with a learned success rate for + each state. + """ + + _TABLE_HEIGHT = 0.0205 + _CUBE_HEIGHT = 0.04 + _PICK_PROGRESS_BINS = 17 + _RELEASE_PROGRESS_BINS = 17 + _MOTION_PROGRESS_BINS = 33 + # Eighteen workspace/source-order layouts each contribute 64 independent + # table arrangements: 1,152 deployment starts and 6,786 rows overall. + _TABLE_ROWS_PER_LAYOUT = 64 + _EXPECTED_ARM_JOINTS = 7 + _EXPECTED_HAND_JOINTS = 2 + + def __init__(self, cfg: EventTermCfg, env: ManagerBasedRLEnv): + super().__init__(cfg, env) + self._robot: Articulation = env.scene["robot"] + self._cubes: tuple[RigidObject, ...] = tuple(env.scene[name] for name in ("cube_1", "cube_2", "cube_3")) + self._arm_joint_ids = self._robot.find_joints("panda_joint.*", preserve_order=True)[0] + self._hand_joint_ids = self._robot.find_joints("panda_finger.*", preserve_order=True)[0] + if ( + len(self._arm_joint_ids) != self._EXPECTED_ARM_JOINTS + or len(self._hand_joint_ids) != self._EXPECTED_HAND_JOINTS + ): + raise ValueError( + "Franka stack resets require " + f"{self._EXPECTED_ARM_JOINTS} arm and {self._EXPECTED_HAND_JOINTS} active-hand joints, " + f"found {len(self._arm_joint_ids)} and {len(self._hand_joint_ids)}." + ) + + self._arm_anchors = torch.tensor(_STATE_TABLE_ARM_POSES, dtype=torch.float32, device=env.device) + self._role_permutations = torch.tensor( + tuple(permutations(range(3))), + dtype=torch.long, + device=env.device, + ) + self._build_table( + closed_finger_position=float(cfg.params.get("closed_finger_position", 0.020)), + placed_finger_position=float(cfg.params.get("placed_finger_position", 0.021)), + open_finger_position=float(cfg.params.get("open_finger_position", 0.040)), + table_rows_per_layout=int(cfg.params.get("table_rows_per_layout", self._TABLE_ROWS_PER_LAYOUT)), + ) + self._validate_table() + self._rows_by_recipe = tuple( + torch.nonzero(self._recipe_ids == int(recipe), as_tuple=False).flatten() for recipe in StackResetRecipe + ) + self._runtime_state = create_stack_reset_runtime_state(env) + self._sampling_probabilities: torch.Tensor | None = None + + @property + def row_count(self) -> int: + """Number of physical rows in the reset table.""" + return int(self._arm_positions.shape[0]) + + @property + def recipe_ids(self) -> torch.Tensor: + """Recipe ID for every reset-table row.""" + return self._recipe_ids + + @property + def layout_ids(self) -> torch.Tensor: + """Workspace/source-order layout ID for every reset-table row.""" + return self._layout_ids + + @property + def layout_count(self) -> int: + """Number of workspace/source-order layouts represented by the table.""" + return len(_STATE_TABLE_LAYOUTS) + + @property + def recipe_names(self) -> tuple[str, ...]: + """Stable diagnostic names for reset recipes.""" + return tuple(recipe.name.lower() for recipe in StackResetRecipe) + + def update_sampling_probabilities(self, probabilities: torch.Tensor) -> None: + """Use the curriculum's distribution for subsequent reset draws.""" + self._sampling_probabilities = probabilities + + def _build_table( + self, + *, + closed_finger_position: float, + placed_finger_position: float, + open_finger_position: float, + table_rows_per_layout: int = _TABLE_ROWS_PER_LAYOUT, + ) -> None: + """Construct dense pick, transport, place, release, and table rows.""" + if table_rows_per_layout < 1: + raise ValueError("table_rows_per_layout must be positive.") + if not closed_finger_position < open_finger_position: + raise ValueError("closed_finger_position must be less than open_finger_position.") + arm_rows: list[torch.Tensor] = [] + hand_rows: list[torch.Tensor] = [] + position_rows: list[torch.Tensor] = [] + recipe_rows: list[int] = [] + held_role_rows: list[int] = [] + layout_rows: list[int] = [] + + def append( + recipe: StackResetRecipe, + arm_position: torch.Tensor, + role_positions: torch.Tensor, + finger_position: float, + held_role: int, + ) -> None: + arm_rows.append(arm_position) + hand_rows.append(self._arm_anchors.new_full((self._EXPECTED_HAND_JOINTS,), finger_position)) + position_rows.append(role_positions) + recipe_rows.append(int(recipe)) + held_role_rows.append(held_role) + layout_rows.append(layout_id) + + # Author scalar waypoints on the CPU; iterating GPU tensors would synchronize each row. + pick_progress = tuple(index / (self._PICK_PROGRESS_BINS - 1) for index in range(self._PICK_PROGRESS_BINS)) + motion_progress = tuple(index / (self._MOTION_PROGRESS_BINS - 1) for index in range(self._MOTION_PROGRESS_BINS)) + release_progress = tuple( + index / (self._RELEASE_PROGRESS_BINS - 1) for index in range(self._RELEASE_PROGRESS_BINS) + ) + for layout_id, (base_anchor, first_anchor, second_anchor) in enumerate(_STATE_TABLE_LAYOUTS): + base_x, base_y = _STATE_TABLE_ANCHORS[base_anchor] + first_x, first_y = _STATE_TABLE_ANCHORS[first_anchor] + second_x, second_y = _STATE_TABLE_ANCHORS[second_anchor] + base_position = self._arm_anchors.new_tensor((base_x, base_y, self._TABLE_HEIGHT)) + first_source = base_position.new_tensor((first_x, first_y, self._TABLE_HEIGHT)) + second_source = base_position.new_tensor((second_x, second_y, self._TABLE_HEIGHT)) + table_positions = torch.stack((base_position, first_source, second_source)) + first_stack_position = base_position + base_position.new_tensor((0.0, 0.0, self._CUBE_HEIGHT)) + second_stack_position = first_stack_position + base_position.new_tensor((0.0, 0.0, self._CUBE_HEIGHT)) + first_placed_alpha = float((first_stack_position[2] - 0.04) / (0.08 - 0.04)) + second_placed_alpha = float((second_stack_position[2] - 0.08) / (0.1175 - 0.08)) + first_placed_arm = torch.lerp( + self._arm_anchors[base_anchor, _NEAR_GRASP_POSE_INDEX], + self._arm_anchors[base_anchor, _PREGRASP_POSE_INDEX], + first_placed_alpha, + ) + second_placed_arm = torch.lerp( + self._arm_anchors[base_anchor, _PREGRASP_POSE_INDEX], + self._arm_anchors[base_anchor, _GREEN_RELEASE_POSE_INDEX], + second_placed_alpha, + ) + + append( + StackResetRecipe.FINAL_RELEASE, + # The easiest row still requires a policy action. Starting + # with the top cube held at its support avoids giving the + # terminal tower away for free at reset. + second_placed_arm, + torch.stack((base_position, first_stack_position, second_stack_position)), + closed_finger_position, + 2, + ) + + # Reset sampling must cover the terminal transition, not only the + # state just before it. These rows keep the completed + # tower supported while continuously opening and retracting the + # gripper. The easiest rows deliberately bootstrap success; the + # adaptive sampler then expands toward harder precursor states. + full_stack_positions = torch.stack((base_position, first_stack_position, second_stack_position)) + for progress in release_progress: + value = float(progress) + append( + StackResetRecipe.FINAL_RELEASE, + torch.lerp( + second_placed_arm, + self._arm_anchors[base_anchor, _GREEN_RELEASE_POSE_INDEX], + progress, + ), + full_stack_positions, + placed_finger_position + value * (open_finger_position - placed_finger_position), + -1, + ) + + # Both movable cubes follow the same place, lift, transport, and + # pick path. Only the support height and calibrated arm anchors differ. + for phase in ( + ( + 2, + second_anchor, + second_placed_arm, + _GREEN_ALIGNED_POSE_INDEX, + (StackResetRecipe.SECOND_PLACE, StackResetRecipe.SECOND_TRANSPORT, StackResetRecipe.SECOND_PICK), + ), + ( + 1, + first_anchor, + first_placed_arm, + _LIFTED_OR_RED_ALIGNED_POSE_INDEX, + (StackResetRecipe.FIRST_PLACE, StackResetRecipe.FIRST_TRANSPORT, StackResetRecipe.FIRST_PICK), + ), + ): + role, source_anchor, placed_arm, aligned_pose, recipes = phase + place_recipe, transport_recipe, pick_recipe = recipes + source_positions = table_positions.clone() + if role == 2: + source_positions[1] = first_stack_position + placed_positions = source_positions.clone() + placed_positions[role] = base_position + base_position.new_tensor((0.0, 0.0, role * self._CUBE_HEIGHT)) + near_grasp_arm = self._arm_anchors[source_anchor, _NEAR_GRASP_POSE_INDEX] + pregrasp_arm = self._arm_anchors[source_anchor, _PREGRASP_POSE_INDEX] + lifted_arm = self._arm_anchors[source_anchor, _LIFTED_OR_RED_ALIGNED_POSE_INDEX] + aligned_arm = self._arm_anchors[base_anchor, aligned_pose] + + for progress in motion_progress: + supported = progress == 1.0 + append( + place_recipe, + torch.lerp(aligned_arm, placed_arm, progress), + placed_positions if supported else source_positions, + placed_finger_position if supported else closed_finger_position, + -1 if supported else role, + ) + + # Join the lift and transport at one shared waypoint. + for progress in motion_progress: + append( + transport_recipe, + torch.lerp(near_grasp_arm, lifted_arm, progress), + source_positions, + closed_finger_position, + role, + ) + for progress in motion_progress[1:]: + append( + transport_recipe, + torch.lerp(lifted_arm, aligned_arm, progress), + source_positions, + closed_finger_position, + role, + ) + + # Include finger closure so the policy can learn acquisition, + # rather than only continuing from a reset-supplied grasp. + for progress in pick_progress: + append( + pick_recipe, + torch.lerp(pregrasp_arm, near_grasp_arm, progress), + source_positions, + open_finger_position, + -1, + ) + for progress in pick_progress[1:]: + append( + pick_recipe, + near_grasp_arm, + source_positions, + open_finger_position + progress * (closed_finger_position - open_finger_position), + role if progress == 1.0 else -1, + ) + + if role == 2: + # Connect first-cube release to second-cube acquisition. + for progress in motion_progress: + append( + StackResetRecipe.PAIR_READY, + torch.lerp( + self._arm_anchors[base_anchor, _GREEN_RELEASE_POSE_INDEX], pregrasp_arm, progress + ), + source_positions, + open_finger_position, + -1, + ) + + # Deployment starts independently sample all three roles over the + # reachable rectangle. Rejection keeps enough clearance for a + # top-down grasp; unlike the old side-by-side template, no role is + # assigned the spatial center or a preferred left/right order. + for table_row in range(table_rows_per_layout): + lattice_index = layout_id * table_rows_per_layout + table_row + + def lattice(multiplier: int, offset: int) -> float: + return ((lattice_index * multiplier + offset) % 4093) / 4092.0 + + table_xy: tuple[tuple[float, float], ...] | None = None + for attempt in range(32): + candidates = tuple( + ( + 0.40 + + 0.16 + * lattice( + 151 + 38 * role_id + 12 * attempt, + 67 + 43 * role_id + 19 * attempt, + ), + -0.18 + + 0.36 + * lattice( + 193 + 46 * role_id + 14 * attempt, + 89 + 53 * role_id + 23 * attempt, + ), + ) + for role_id in range(3) + ) + if all( + math.dist(candidates[first], candidates[second]) >= 0.085 + for first in range(3) + for second in range(first + 1, 3) + ): + table_xy = candidates + break + if table_xy is None: + table_xy = tuple( + _STATE_TABLE_ANCHORS[anchor] for anchor in (base_anchor, first_anchor, second_anchor) + ) + randomized_table_positions = base_position.new_tensor( + tuple((x, y, self._TABLE_HEIGHT) for x, y in table_xy) + ) + approach_anchor = min(int(lattice(263, 113) * len(_STATE_TABLE_ANCHORS)), len(_STATE_TABLE_ANCHORS) - 1) + arm_noise = self._arm_anchors.new_tensor( + tuple(0.04 * (lattice(271 + 18 * joint_id, 127 + 31 * joint_id) - 0.5) for joint_id in range(7)) + ) + append( + StackResetRecipe.TABLE, + self._arm_anchors[approach_anchor, _PREGRASP_POSE_INDEX] + arm_noise, + randomized_table_positions, + open_finger_position, + -1, + ) + + self._arm_positions = torch.stack(arm_rows) + self._hand_positions = torch.stack(hand_rows) + self._role_positions = torch.stack(position_rows) + self._recipe_ids = torch.tensor(recipe_rows, dtype=torch.long, device=self.device) + self._held_roles = torch.tensor(held_role_rows, dtype=torch.long, device=self.device) + self._layout_ids = torch.tensor(layout_rows, dtype=torch.long, device=self.device) + self._target_potentials = torch.tensor( + tuple(_RECIPE_TARGET_POTENTIAL[StackResetRecipe(recipe)] for recipe in recipe_rows), + dtype=torch.float32, + device=self.device, + ) + # Cache complete cube pose state, not only position. Random yaw is + # physically immaterial for perfect cubes but prevents the reset + # mechanism from relying on one authored quaternion representation. + row_ids = torch.arange(self._role_positions.shape[0], device=self.device).unsqueeze(1) + role_ids = torch.arange(3, device=self.device).unsqueeze(0) + yaw_fraction = torch.remainder(row_ids * 193 + role_ids * 389 + 17, 1021).float() / 1020.0 + half_yaw = math.pi * (2.0 * yaw_fraction - 1.0) + self._role_quaternions = torch.zeros( + (self._role_positions.shape[0], 3, 4), + dtype=torch.float32, + device=self.device, + ) + self._role_quaternions[..., 2] = torch.sin(half_yaw) + self._role_quaternions[..., 3] = torch.cos(half_yaw) + held_rows = torch.nonzero(self._held_roles >= 0, as_tuple=False).flatten() + if held_rows.numel() > 0: + # Held cubes follow the actual hand FK, not an independent Cartesian trajectory. + self._role_positions[held_rows, self._held_roles[held_rows]] = _franka_tool_position( + self._arm_positions[held_rows] + ) + self._role_quaternions[held_rows, self._held_roles[held_rows]] = self._role_quaternions.new_tensor( + (0.0, 0.0, 0.0, 1.0) + ) + + def _validate_table(self) -> None: + """Reject non-finite, penetrating, or semantically inconsistent rows.""" + tensors = ( + self._arm_positions, + self._hand_positions, + self._role_positions, + self._role_quaternions, + ) + if any(not bool(torch.isfinite(value).all()) for value in tensors): + raise RuntimeError("Stack reset table contains non-finite values.") + if self._layout_ids.shape != self._recipe_ids.shape: + raise RuntimeError("Stack reset table layout IDs do not align with its physical rows.") + if bool(torch.any((self._layout_ids < 0) | (self._layout_ids >= self.layout_count))): + raise RuntimeError("Stack reset table contains an invalid workspace layout ID.") + if bool(torch.any(self._role_positions[..., 2] < self._TABLE_HEIGHT - 1.0e-6)): + raise RuntimeError("Stack reset table places a cube below the table support height.") + + role_rotations = matrix_from_quat(self._role_quaternions) + for first_role, second_role in ((0, 1), (0, 2), (1, 2)): + intersecting = _oriented_cube_pair_intersections( + self._role_positions[:, first_role], + role_rotations[:, first_role], + self._role_positions[:, second_role], + role_rotations[:, second_role], + edge_length=self._CUBE_HEIGHT, + ) + if bool(torch.any(intersecting)): + invalid_rows = torch.nonzero(intersecting, as_tuple=False).flatten() + raise RuntimeError( + "Stack reset table contains intersecting oriented cube volumes " + f"(roles={first_role}/{second_role}, rows={invalid_rows[:8].tolist()}, " + f"count={invalid_rows.numel()})." + ) + # Every phase after the first placement assumes role one is already + # supported on role zero. A geometrically valid row with role one at + # its source makes the second-stage target potential impossible. + second_stage_recipes = torch.tensor( + ( + int(StackResetRecipe.FINAL_RELEASE), + int(StackResetRecipe.SECOND_PLACE), + int(StackResetRecipe.SECOND_TRANSPORT), + int(StackResetRecipe.SECOND_PICK), + int(StackResetRecipe.PAIR_READY), + ), + dtype=self._recipe_ids.dtype, + device=self.device, + ) + second_stage_rows = torch.isin(self._recipe_ids, second_stage_recipes) + first_support_delta = self._role_positions[second_stage_rows, 1] - self._role_positions[second_stage_rows, 0] + expected_support_delta = first_support_delta.new_tensor((0.0, 0.0, self._CUBE_HEIGHT)) + if bool(torch.any(torch.abs(first_support_delta - expected_support_delta) > 1.0e-5)): + raise RuntimeError("A second-stage stack reset row does not place the first movable cube on the base.") + + def __call__( + self, + env: ManagerBasedRLEnv, + env_ids: Sequence[int] | torch.Tensor | slice | None, + closed_finger_position: float = 0.020, + placed_finger_position: float = 0.021, + open_finger_position: float = 0.040, + table_rows_per_layout: int = _TABLE_ROWS_PER_LAYOUT, + fixed_recipe: int | None = None, + fixed_role_permutation: int | None = None, + arm_joint_noise_range: float = 0.0, + table_arm_joint_noise_range: float = 0.0, + table_cube_planar_translation_range: float = 0.0, + table_cube_rotation_range: float = 0.0, + ) -> None: + """Restore cached states with bounded continuous state randomization.""" + del ( + closed_finger_position, + placed_finger_position, + open_finger_position, + table_rows_per_layout, + ) + if env_ids is None or isinstance(env_ids, slice): + env_ids = torch.arange(env.num_envs, device=env.device)[env_ids if env_ids is not None else slice(None)] + env_ids = torch.as_tensor(env_ids, dtype=torch.long, device=env.device).flatten() + if env_ids.numel() == 0: + return + if ( + min( + arm_joint_noise_range, + table_arm_joint_noise_range, + table_cube_planar_translation_range, + table_cube_rotation_range, + ) + < 0.0 + ): + raise ValueError("Reset-state randomization ranges must be non-negative.") + state = self._runtime_state + if fixed_recipe is None and self._sampling_probabilities is not None: + row_ids = torch.multinomial(self._sampling_probabilities, env_ids.numel(), replacement=True) + else: + recipe = StackResetRecipe.TABLE if fixed_recipe is None else StackResetRecipe(fixed_recipe) + recipe_rows = self._rows_by_recipe[recipe] + row_ids = recipe_rows[torch.randint(recipe_rows.numel(), (env_ids.numel(),), device=self.device)] + if fixed_role_permutation is None: + permutation_ids = torch.randint( + self._role_permutations.shape[0], + (env_ids.numel(),), + device=self.device, + ) + else: + if not 0 <= fixed_role_permutation < self._role_permutations.shape[0]: + raise ValueError("fixed_role_permutation is outside the six cube permutations.") + permutation_ids = torch.full( + (env_ids.numel(),), + fixed_role_permutation, + dtype=torch.long, + device=self.device, + ) + role_to_cube = self._role_permutations[permutation_ids] + held_roles = self._held_roles[row_ids] + has_held_cube = held_roles >= 0 + selected_cube_ids = role_to_cube.gather(1, held_roles.clamp_min(0).unsqueeze(1)).squeeze(1) + held_cube_ids = torch.where(has_held_cube, selected_cube_ids, -1) + + joint_positions = self._robot.data.default_joint_pos.torch[env_ids].clone() + joint_velocities = torch.zeros_like(joint_positions) + joint_positions[:, self._arm_joint_ids] = self._arm_positions[row_ids] + joint_positions[:, self._hand_joint_ids] = self._hand_positions[row_ids] + table_rows = self._recipe_ids[row_ids] == int(StackResetRecipe.TABLE) + arm_noise_scale = torch.full( + (env_ids.numel(), 1), + arm_joint_noise_range, + dtype=torch.float32, + device=self.device, + ) + arm_noise_scale[table_rows] = table_arm_joint_noise_range + # Joint-ID indexing may be advanced indexing and therefore return a + # copy. Write the randomized values back explicitly after clamping. + arm_positions = joint_positions[:, self._arm_joint_ids].clone() + arm_positions += (2.0 * torch.rand_like(arm_positions) - 1.0) * arm_noise_scale + arm_lower = arm_positions.new_tensor(FRANKA_STACK_ARM_WORKSPACE_LOWER) + arm_upper = arm_positions.new_tensor(FRANKA_STACK_ARM_WORKSPACE_UPPER) + arm_positions.clamp_(min=arm_lower, max=arm_upper) + joint_positions[:, self._arm_joint_ids] = arm_positions + self._robot.actuators.target_command.set_position_index(value=joint_positions, env_ids=env_ids) + self._robot.actuators.target_command.set_velocity_index(value=joint_velocities, env_ids=env_ids) + self._robot.write_joint_position_to_sim_index(position=joint_positions, env_ids=env_ids) + self._robot.write_joint_velocity_to_sim_index(velocity=joint_velocities, env_ids=env_ids) + + role_positions = self._role_positions[row_ids].clone() + role_quaternions = self._role_quaternions[row_ids].clone() + if table_cube_planar_translation_range > 0.0: + translation = ( + 2.0 + * torch.rand( + (env_ids.numel(), 2), + dtype=torch.float32, + device=self.device, + ) + - 1.0 + ) * table_cube_planar_translation_range + role_positions[table_rows, :, :2] += translation[table_rows].unsqueeze(1) + if table_cube_rotation_range > 0.0: + angles = ( + 2.0 + * torch.rand( + env_ids.numel(), + dtype=torch.float32, + device=self.device, + ) + - 1.0 + ) * table_cube_rotation_range + angles = angles[table_rows] + table_xy = role_positions[table_rows, :, :2] + centers = table_xy.mean(dim=1, keepdim=True) + centered = table_xy - centers + cosine = torch.cos(angles).unsqueeze(1) + sine = torch.sin(angles).unsqueeze(1) + rotated_x = cosine * centered[..., 0] - sine * centered[..., 1] + rotated_y = sine * centered[..., 0] + cosine * centered[..., 1] + role_positions[table_rows, :, :2] = centers + torch.stack((rotated_x, rotated_y), dim=-1) + + half_angles = 0.5 * angles + yaw_w = torch.cos(half_angles).unsqueeze(1) + yaw_z = torch.sin(half_angles).unsqueeze(1) + yaw_quaternions = torch.zeros_like(role_quaternions[table_rows]) + yaw_quaternions[..., 2] = yaw_z + yaw_quaternions[..., 3] = yaw_w + role_quaternions[table_rows] = normalize(quat_mul(yaw_quaternions, role_quaternions[table_rows])) + + # Joint perturbations must never detach a reset-authored grasp. Move + # the held role to the perturbed FK tool center before colors are + # scattered over physical roles. + role_positions[has_held_cube, held_roles[has_held_cube]] = _franka_tool_position(arm_positions[has_held_cube]) + cube_positions = torch.zeros_like(role_positions) + cube_quaternions = torch.zeros_like(role_quaternions) + cube_positions.scatter_( + 1, + role_to_cube.unsqueeze(-1).expand_as(role_positions), + role_positions, + ) + cube_quaternions.scatter_( + 1, + role_to_cube.unsqueeze(-1).expand_as(role_quaternions), + role_quaternions, + ) + root_velocity = torch.zeros((env_ids.numel(), 6), dtype=torch.float32, device=self.device) + for cube_id, cube in enumerate(self._cubes): + root_pose = cube.data.default_root_pose.torch[env_ids].clone() + root_pose[:, :3] = cube_positions[:, cube_id] + env.scene.env_origins[env_ids] + root_pose[:, 3:7] = cube_quaternions[:, cube_id] + cube.write_root_pose_to_sim_index(root_pose=root_pose, env_ids=env_ids) + cube.write_root_velocity_to_sim_index(root_velocity=root_velocity, env_ids=env_ids) + + state.row_ids[env_ids] = row_ids + state.role_to_cube[env_ids] = role_to_cube + state.recipes[env_ids] = self._recipe_ids[row_ids] + state.target_potentials[env_ids] = self._target_potentials[row_ids] + state.held_cube_ids[env_ids] = held_cube_ids diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/runtime_state.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/runtime_state.py new file mode 100644 index 000000000000..aec2d5d2de0a --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/runtime_state.py @@ -0,0 +1,55 @@ +# 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 + +"""Typed runtime state shared by the Franka stack reset MDP terms.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING + +import torch + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedRLEnv + + +@dataclass +class StackResetRuntimeState: + """Episode-local reset metadata shared across stack MDP managers.""" + + row_ids: torch.Tensor + recipes: torch.Tensor + target_potentials: torch.Tensor + held_cube_ids: torch.Tensor + role_to_cube: torch.Tensor + + @property + def initialized(self) -> torch.Tensor: + """Whether each environment has restored its first row.""" + return self.row_ids >= 0 + + +def create_stack_reset_runtime_state( + env: ManagerBasedRLEnv, +) -> StackResetRuntimeState: + """Create and attach one typed reset-state owner to an environment.""" + state = StackResetRuntimeState( + row_ids=torch.full((env.num_envs,), -1, dtype=torch.long, device=env.device), + recipes=torch.zeros(env.num_envs, dtype=torch.long, device=env.device), + target_potentials=torch.ones(env.num_envs, dtype=torch.float32, device=env.device), + held_cube_ids=torch.full((env.num_envs,), -1, dtype=torch.long, device=env.device), + role_to_cube=torch.arange(3, dtype=torch.long, device=env.device).repeat(env.num_envs, 1), + ) + env.stack_reset_state = state + return state + + +def get_stack_reset_runtime_state(env: ManagerBasedRLEnv) -> StackResetRuntimeState: + """Return the reset state created by :class:`StackResetStateTable`.""" + state = getattr(env, "stack_reset_state", None) + if state is None: + raise AttributeError("Stack reset runtime state is unavailable before the reset-table event is initialized.") + return state From 4b6de1645d710697b580865a2831b6ae4c88aa6a Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Wed, 18 Nov 2026 00:48:33 +0100 Subject: [PATCH 06/13] Reuse manager-resolved parameters for Franka resets --- .../isaaclab_tasks/contrib/stack/mdp/curriculums.py | 4 ++-- .../isaaclab_tasks/contrib/stack/mdp/reset_events.py | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/curriculums.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/curriculums.py index 3e10e7d59ef4..da4b0d495a77 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/curriculums.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/curriculums.py @@ -34,7 +34,7 @@ def __init__(self, cfg: CurriculumTermCfg, env: ManagerBasedRLEnv): if not isinstance(reset_term, StackResetStateTable): raise RuntimeError("StackResetTableCurriculum requires StackResetStateTable.") self._reset_term = reset_term - monitor_cfg = cfg.params.get("success_monitor") + monitor_cfg = cfg.params["success_monitor"] if not isinstance(monitor_cfg, SuccessMonitorCfg): raise TypeError("StackResetTableCurriculum requires a SuccessMonitorCfg.") self._progress_monitor = instantiate( @@ -45,7 +45,7 @@ def __init__(self, cfg: CurriculumTermCfg, env: ManagerBasedRLEnv): ) self._attempts = torch.zeros(reset_term.row_count, dtype=torch.long, device=env.device) self._progress_successes = torch.zeros_like(self._attempts) - self._table_sampling_probability = float(cfg.params.get("table_sampling_probability", 0.35)) + self._table_sampling_probability = float(cfg.params["table_sampling_probability"]) if not 0.0 < self._table_sampling_probability < 1.0: raise ValueError("table_sampling_probability must lie strictly between zero and one.") self._table_rows = reset_term.recipe_ids == StackResetRecipe.TABLE diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/reset_events.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/reset_events.py index b8ca414bd7d3..70f72d18d516 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/reset_events.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/reset_events.py @@ -363,10 +363,10 @@ def __init__(self, cfg: EventTermCfg, env: ManagerBasedRLEnv): device=env.device, ) self._build_table( - closed_finger_position=float(cfg.params.get("closed_finger_position", 0.020)), - placed_finger_position=float(cfg.params.get("placed_finger_position", 0.021)), - open_finger_position=float(cfg.params.get("open_finger_position", 0.040)), - table_rows_per_layout=int(cfg.params.get("table_rows_per_layout", self._TABLE_ROWS_PER_LAYOUT)), + closed_finger_position=float(cfg.params["closed_finger_position"]), + placed_finger_position=float(cfg.params["placed_finger_position"]), + open_finger_position=float(cfg.params["open_finger_position"]), + table_rows_per_layout=int(cfg.params["table_rows_per_layout"]), ) self._validate_table() self._rows_by_recipe = tuple( From 6737a61f67e649a94bc8eec060a05dc002ddd583 Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Wed, 18 Nov 2026 00:50:47 +0100 Subject: [PATCH 07/13] Test prior-row credit through the stack reset managers --- .../stack/test_franka_stack_curriculum.py | 88 +++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 source/isaaclab_tasks/test/contrib/stack/test_franka_stack_curriculum.py diff --git a/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_curriculum.py b/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_curriculum.py new file mode 100644 index 000000000000..1e68f63eb692 --- /dev/null +++ b/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_curriculum.py @@ -0,0 +1,88 @@ +# 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 types import SimpleNamespace +from unittest.mock import Mock + +import pytest +import torch + +from isaaclab.managers import CurriculumManager, CurriculumTermCfg, EventManager, EventTermCfg + +from isaaclab_tasks.contrib.stack.mdp.curriculums import StackResetTableCurriculum +from isaaclab_tasks.contrib.stack.mdp.reset_events import StackResetRecipe, StackResetStateTable +from isaaclab_tasks.contrib.stack.mdp.runtime_state import get_stack_reset_runtime_state +from isaaclab_tasks.utils import SuccessMonitorCfg + +pytestmark = pytest.mark.kitless + + +def test_curriculum_credits_the_completed_row_before_reset() -> None: + num_envs = 4 + robot = Mock() + robot.data.default_joint_pos.torch = torch.zeros(num_envs, 9) + robot.find_joints.side_effect = [(list(range(7)), []), ([7, 8], [])] + cubes = [Mock() for _ in range(3)] + for cube in cubes: + cube.data.default_root_pose.torch = torch.zeros(num_envs, 7) + entities = {"robot": robot, **{f"cube_{i}": cube for i, cube in enumerate(cubes, start=1)}} + # The asset mocks record backend writes. The event and curriculum are the real manager terms. + scene = _Scene(entities, torch.zeros(num_envs, 3)) + outcome = SimpleNamespace(ever_success=torch.tensor([True, False, False, True])) + env = SimpleNamespace( + num_envs=num_envs, + device="cpu", + scene=scene, + sim=SimpleNamespace(is_playing=lambda: True), + episode_length_buf=torch.zeros(num_envs, dtype=torch.long), + reset_buf=torch.zeros(num_envs, dtype=torch.bool), + termination_manager=SimpleNamespace(get_term_cfg=lambda name: SimpleNamespace(func=outcome)), + ) + env.event_manager = EventManager( + { + "reset_from_state_buffer": EventTermCfg( + func=StackResetStateTable, mode="reset", params={"fixed_recipe": int(StackResetRecipe.SECOND_TRANSPORT)} + ) + }, + env, + ) + curriculum = CurriculumManager( + { + "reset_sampling": CurriculumTermCfg( + func=StackResetTableCurriculum, params={"success_monitor": SuccessMonitorCfg(monitored_history_len=4)} + ) + }, + env, + ) + curriculum.compute(slice(None)) + env.event_manager.apply("reset", env_ids=slice(None), global_env_step_count=0) + initial = curriculum.reset(slice(None)) + assert "Curriculum/reset_sampling/batch_success_rate" not in initial + + state = get_stack_reset_runtime_state(env) + old_row = state.row_ids[-1].clone() + env.episode_length_buf[:] = torch.tensor([4, 4, 0, 4]) + # Environment 0 completed, 1 was reset manually, and 2 has no elapsed steps. + env.reset_buf[:] = torch.tensor([True, False, True, False]) + env_ids = torch.tensor([0, 1, 2]) + term = env.event_manager.get_term_cfg("reset_from_state_buffer") + term.params["fixed_recipe"] = int(StackResetRecipe.TABLE) + curriculum.compute(env_ids) + env.event_manager.apply("reset", env_ids=env_ids, global_env_step_count=4) + metrics = curriculum.reset(env_ids) + assert metrics["Curriculum/reset_sampling/full_task_attempts"].item() == 1 + assert metrics["Curriculum/reset_sampling/recipe_second_transport_attempts"].item() == 1 + assert metrics["Curriculum/reset_sampling/recipe_table_attempts"].item() == 0 + assert metrics["Curriculum/reset_sampling/batch_success_rate"].item() == 1 + assert "Curriculum/reset_sampling/batch_table_full_task_success_rate" not in metrics + assert state.row_ids[-1] == old_row + assert (state.recipes[env_ids] == StackResetRecipe.TABLE).all() + assert torch.equal(robot.write_joint_position_to_sim_index.call_args.kwargs["env_ids"], env_ids) + + +class _Scene(dict): + def __init__(self, entities: dict[str, Mock], origins: torch.Tensor) -> None: + super().__init__(entities) + self.env_origins = origins From 74b990a9742413bc72f56c63a879b3d5d9fa0dd4 Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Wed, 18 Nov 2026 00:50:56 +0100 Subject: [PATCH 08/13] Restore the Franka base with the selected reset state --- .../isaaclab_tasks/contrib/stack/mdp/reset_events.py | 7 +++++++ .../test/contrib/stack/test_franka_stack_curriculum.py | 2 ++ 2 files changed, 9 insertions(+) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/reset_events.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/reset_events.py index 70f72d18d516..c1fd000ad835 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/reset_events.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/reset_events.py @@ -796,6 +796,13 @@ def __call__( selected_cube_ids = role_to_cube.gather(1, held_roles.clamp_min(0).unsqueeze(1)).squeeze(1) held_cube_ids = torch.where(has_held_cube, selected_cube_ids, -1) + # Restore the fixed base before applying the selected joint and cube state. + root_pose = self._robot.data.default_root_pose.torch[env_ids].clone() + root_pose[:, :3] += env.scene.env_origins[env_ids] + root_velocity = self._robot.data.default_root_vel.torch[env_ids] + self._robot.write_root_pose_to_sim_index(root_pose=root_pose, env_ids=env_ids) + self._robot.write_root_velocity_to_sim_index(root_velocity=root_velocity, env_ids=env_ids) + joint_positions = self._robot.data.default_joint_pos.torch[env_ids].clone() joint_velocities = torch.zeros_like(joint_positions) joint_positions[:, self._arm_joint_ids] = self._arm_positions[row_ids] diff --git a/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_curriculum.py b/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_curriculum.py index 1e68f63eb692..6ae11edf43bd 100644 --- a/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_curriculum.py +++ b/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_curriculum.py @@ -23,6 +23,8 @@ def test_curriculum_credits_the_completed_row_before_reset() -> None: num_envs = 4 robot = Mock() robot.data.default_joint_pos.torch = torch.zeros(num_envs, 9) + robot.data.default_root_pose.torch = torch.zeros(num_envs, 7) + robot.data.default_root_vel.torch = torch.zeros(num_envs, 6) robot.find_joints.side_effect = [(list(range(7)), []), ([7, 8], [])] cubes = [Mock() for _ in range(3)] for cube in cubes: From 14363a481f1c60423302f61887f6e05cb2a407b3 Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Wed, 18 Nov 2026 00:54:02 +0100 Subject: [PATCH 09/13] Use the live table sampling probability --- .../contrib/stack/mdp/curriculums.py | 16 ++++++---------- .../stack/test_franka_stack_curriculum.py | 5 +++++ 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/curriculums.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/curriculums.py index da4b0d495a77..b099b680cd3c 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/curriculums.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/curriculums.py @@ -45,9 +45,6 @@ def __init__(self, cfg: CurriculumTermCfg, env: ManagerBasedRLEnv): ) self._attempts = torch.zeros(reset_term.row_count, dtype=torch.long, device=env.device) self._progress_successes = torch.zeros_like(self._attempts) - self._table_sampling_probability = float(cfg.params["table_sampling_probability"]) - if not 0.0 < self._table_sampling_probability < 1.0: - raise ValueError("table_sampling_probability must lie strictly between zero and one.") self._table_rows = reset_term.recipe_ids == StackResetRecipe.TABLE if not bool(torch.any(self._table_rows)) or bool(torch.all(self._table_rows)): raise RuntimeError("The stack reset table must contain both table and intermediate rows.") @@ -59,7 +56,7 @@ def __init__(self, cfg: CurriculumTermCfg, env: ManagerBasedRLEnv): } self._full_task_successes_by_row = torch.zeros_like(self._attempts) - def _sampling_distribution(self) -> torch.Tensor: + def _sampling_distribution(self, table_sampling_probability: float) -> torch.Tensor: """Mix uniform table starts with layout-balanced intermediate starts.""" adaptive = self._progress_monitor.target_weights() adaptive[self._table_rows] = 0.0 @@ -70,7 +67,7 @@ def _sampling_distribution(self) -> torch.Tensor: adaptive /= adaptive.sum() table = self._table_rows.to(dtype=adaptive.dtype) table /= table.sum() - probabilities = (1.0 - self._table_sampling_probability) * adaptive + self._table_sampling_probability * table + probabilities = (1.0 - table_sampling_probability) * adaptive + table_sampling_probability * table return probabilities def __call__( @@ -83,10 +80,9 @@ def __call__( table_sampling_probability: float = 0.35, ) -> dict[str, torch.Tensor]: """Credit completed episodes and update the reset event's distribution.""" - del ( - success_monitor, - table_sampling_probability, - ) + del success_monitor + if not 0.0 < table_sampling_probability < 1.0: + raise ValueError("table_sampling_probability must lie strictly between zero and one.") if env_ids is None or isinstance(env_ids, slice): env_ids = torch.arange(env.num_envs, device=env.device)[env_ids if env_ids is not None else slice(None)] ids = torch.as_tensor(env_ids, dtype=torch.long, device=env.device).flatten() @@ -119,7 +115,7 @@ def __call__( torch.bincount(completed_rows[final_succeeded], minlength=self._reset_term.row_count) ) - probabilities = self._sampling_distribution() + probabilities = self._sampling_distribution(table_sampling_probability) self._reset_term.update_sampling_probabilities(probabilities) attempts = self._attempts diff --git a/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_curriculum.py b/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_curriculum.py index 6ae11edf43bd..59860fbed15f 100644 --- a/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_curriculum.py +++ b/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_curriculum.py @@ -83,6 +83,11 @@ def test_curriculum_credits_the_completed_row_before_reset() -> None: assert (state.recipes[env_ids] == StackResetRecipe.TABLE).all() assert torch.equal(robot.write_joint_position_to_sim_index.call_args.kwargs["env_ids"], env_ids) + curriculum.cfg["reset_sampling"].params["table_sampling_probability"] = 0.60 + curriculum.compute(slice(0, 0)) + updated = curriculum.reset(slice(0, 0)) + assert updated["Curriculum/reset_sampling/table_probability"].item() == pytest.approx(0.60) + class _Scene(dict): def __init__(self, entities: dict[str, Mock], origins: torch.Tensor) -> None: From 3c9d60f5ef8c83ca8c30bc209be04e7042fd3d0e Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Wed, 18 Nov 2026 00:55:08 +0100 Subject: [PATCH 10/13] Verify selected base poses include environment origins --- .../test/contrib/stack/test_franka_stack_curriculum.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_curriculum.py b/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_curriculum.py index 59860fbed15f..f0ae840c77e8 100644 --- a/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_curriculum.py +++ b/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_curriculum.py @@ -31,7 +31,9 @@ def test_curriculum_credits_the_completed_row_before_reset() -> None: cube.data.default_root_pose.torch = torch.zeros(num_envs, 7) entities = {"robot": robot, **{f"cube_{i}": cube for i, cube in enumerate(cubes, start=1)}} # The asset mocks record backend writes. The event and curriculum are the real manager terms. - scene = _Scene(entities, torch.zeros(num_envs, 3)) + origins = torch.zeros(num_envs, 3) + origins[:, 0] = torch.arange(num_envs) + scene = _Scene(entities, origins) outcome = SimpleNamespace(ever_success=torch.tensor([True, False, False, True])) env = SimpleNamespace( num_envs=num_envs, @@ -82,6 +84,9 @@ def test_curriculum_credits_the_completed_row_before_reset() -> None: assert state.row_ids[-1] == old_row assert (state.recipes[env_ids] == StackResetRecipe.TABLE).all() assert torch.equal(robot.write_joint_position_to_sim_index.call_args.kwargs["env_ids"], env_ids) + root_write = robot.write_root_pose_to_sim_index.call_args.kwargs + assert torch.equal(root_write["env_ids"], env_ids) + assert torch.equal(root_write["root_pose"][:, :3], origins[env_ids]) curriculum.cfg["reset_sampling"].params["table_sampling_probability"] = 0.60 curriculum.compute(slice(0, 0)) From c9601b287a85ebb141f4ed352020593a8a3f4fe2 Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Wed, 18 Nov 2026 01:18:41 +0100 Subject: [PATCH 11/13] Preserve contact-safe Franka grasps during reset noise --- .../contrib/stack/mdp/reset_events.py | 59 ++++++---- .../stack/test_franka_stack_curriculum.py | 101 ++++++++++++------ 2 files changed, 107 insertions(+), 53 deletions(-) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/reset_events.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/reset_events.py index c1fd000ad835..335aacf95528 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/reset_events.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/reset_events.py @@ -796,16 +796,9 @@ def __call__( selected_cube_ids = role_to_cube.gather(1, held_roles.clamp_min(0).unsqueeze(1)).squeeze(1) held_cube_ids = torch.where(has_held_cube, selected_cube_ids, -1) - # Restore the fixed base before applying the selected joint and cube state. - root_pose = self._robot.data.default_root_pose.torch[env_ids].clone() - root_pose[:, :3] += env.scene.env_origins[env_ids] - root_velocity = self._robot.data.default_root_vel.torch[env_ids] - self._robot.write_root_pose_to_sim_index(root_pose=root_pose, env_ids=env_ids) - self._robot.write_root_velocity_to_sim_index(root_velocity=root_velocity, env_ids=env_ids) - joint_positions = self._robot.data.default_joint_pos.torch[env_ids].clone() joint_velocities = torch.zeros_like(joint_positions) - joint_positions[:, self._arm_joint_ids] = self._arm_positions[row_ids] + authored_arm_positions = self._arm_positions[row_ids] joint_positions[:, self._hand_joint_ids] = self._hand_positions[row_ids] table_rows = self._recipe_ids[row_ids] == int(StackResetRecipe.TABLE) arm_noise_scale = torch.full( @@ -815,21 +808,36 @@ def __call__( device=self.device, ) arm_noise_scale[table_rows] = table_arm_joint_noise_range - # Joint-ID indexing may be advanced indexing and therefore return a - # copy. Write the randomized values back explicitly after clamping. - arm_positions = joint_positions[:, self._arm_joint_ids].clone() - arm_positions += (2.0 * torch.rand_like(arm_positions) - 1.0) * arm_noise_scale + arm_positions = authored_arm_positions + (2.0 * torch.rand_like(authored_arm_positions) - 1.0) * arm_noise_scale arm_lower = arm_positions.new_tensor(FRANKA_STACK_ARM_WORKSPACE_LOWER) arm_upper = arm_positions.new_tensor(FRANKA_STACK_ARM_WORKSPACE_UPPER) arm_positions.clamp_(min=arm_lower, max=arm_upper) - joint_positions[:, self._arm_joint_ids] = arm_positions - self._robot.actuators.target_command.set_position_index(value=joint_positions, env_ids=env_ids) - self._robot.actuators.target_command.set_velocity_index(value=joint_velocities, env_ids=env_ids) - self._robot.write_joint_position_to_sim_index(position=joint_positions, env_ids=env_ids) - self._robot.write_joint_velocity_to_sim_index(velocity=joint_velocities, env_ids=env_ids) role_positions = self._role_positions[row_ids].clone() role_quaternions = self._role_quaternions[row_ids].clone() + if arm_joint_noise_range > 0.0: + held_env_ids = has_held_cube.nonzero(as_tuple=False).flatten() + if held_env_ids.numel(): + held_role_ids = held_roles[held_env_ids] + candidate_positions = _franka_tool_position(arm_positions[held_env_ids]) + other_roles = (held_role_ids.unsqueeze(1) + torch.arange(1, 3, device=self.device)) % 3 + rotations = matrix_from_quat(role_quaternions[held_env_ids]) + rows = torch.arange(held_env_ids.numel(), device=self.device) + intersects = _oriented_cube_pair_intersections( + candidate_positions[:, None].expand(-1, 2, -1), + rotations[rows, held_role_ids][:, None].expand(-1, 2, -1, -1), + role_positions[held_env_ids[:, None], other_roles], + rotations[rows[:, None], other_roles], + edge_length=self._CUBE_HEIGHT, + ) + valid = (candidate_positions[:, 2] >= self._TABLE_HEIGHT - 1.0e-6) & ~intersects.any(dim=1) + # Restore the validated grasp as a pair if its noisy pose would intersect a support or the table. + arm_positions[held_env_ids] = torch.where( + valid.unsqueeze(1), arm_positions[held_env_ids], authored_arm_positions[held_env_ids] + ) + role_positions[held_env_ids, held_role_ids] = torch.where( + valid.unsqueeze(1), candidate_positions, role_positions[held_env_ids, held_role_ids] + ) if table_cube_planar_translation_range > 0.0: translation = ( 2.0 @@ -869,10 +877,19 @@ def __call__( yaw_quaternions[..., 3] = yaw_w role_quaternions[table_rows] = normalize(quat_mul(yaw_quaternions, role_quaternions[table_rows])) - # Joint perturbations must never detach a reset-authored grasp. Move - # the held role to the perturbed FK tool center before colors are - # scattered over physical roles. - role_positions[has_held_cube, held_roles[has_held_cube]] = _franka_tool_position(arm_positions[has_held_cube]) + # Restore the fixed base before applying the selected joint and cube state. + root_pose = self._robot.data.default_root_pose.torch[env_ids].clone() + root_pose[:, :3] += env.scene.env_origins[env_ids] + root_velocity = self._robot.data.default_root_vel.torch[env_ids] + self._robot.write_root_pose_to_sim_index(root_pose=root_pose, env_ids=env_ids) + self._robot.write_root_velocity_to_sim_index(root_velocity=root_velocity, env_ids=env_ids) + + joint_positions[:, self._arm_joint_ids] = arm_positions + self._robot.actuators.target_command.set_position_index(value=joint_positions, env_ids=env_ids) + self._robot.actuators.target_command.set_velocity_index(value=joint_velocities, env_ids=env_ids) + self._robot.write_joint_position_to_sim_index(position=joint_positions, env_ids=env_ids) + self._robot.write_joint_velocity_to_sim_index(velocity=joint_velocities, env_ids=env_ids) + cube_positions = torch.zeros_like(role_positions) cube_quaternions = torch.zeros_like(role_quaternions) cube_positions.scatter_( diff --git a/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_curriculum.py b/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_curriculum.py index f0ae840c77e8..19ad3f73f363 100644 --- a/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_curriculum.py +++ b/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_curriculum.py @@ -20,38 +20,9 @@ def test_curriculum_credits_the_completed_row_before_reset() -> None: - num_envs = 4 - robot = Mock() - robot.data.default_joint_pos.torch = torch.zeros(num_envs, 9) - robot.data.default_root_pose.torch = torch.zeros(num_envs, 7) - robot.data.default_root_vel.torch = torch.zeros(num_envs, 6) - robot.find_joints.side_effect = [(list(range(7)), []), ([7, 8], [])] - cubes = [Mock() for _ in range(3)] - for cube in cubes: - cube.data.default_root_pose.torch = torch.zeros(num_envs, 7) - entities = {"robot": robot, **{f"cube_{i}": cube for i, cube in enumerate(cubes, start=1)}} - # The asset mocks record backend writes. The event and curriculum are the real manager terms. - origins = torch.zeros(num_envs, 3) - origins[:, 0] = torch.arange(num_envs) - scene = _Scene(entities, origins) - outcome = SimpleNamespace(ever_success=torch.tensor([True, False, False, True])) - env = SimpleNamespace( - num_envs=num_envs, - device="cpu", - scene=scene, - sim=SimpleNamespace(is_playing=lambda: True), - episode_length_buf=torch.zeros(num_envs, dtype=torch.long), - reset_buf=torch.zeros(num_envs, dtype=torch.bool), - termination_manager=SimpleNamespace(get_term_cfg=lambda name: SimpleNamespace(func=outcome)), - ) - env.event_manager = EventManager( - { - "reset_from_state_buffer": EventTermCfg( - func=StackResetStateTable, mode="reset", params={"fixed_recipe": int(StackResetRecipe.SECOND_TRANSPORT)} - ) - }, - env, - ) + env = _make_env({"fixed_recipe": int(StackResetRecipe.SECOND_TRANSPORT)}) + robot = env.scene["robot"] + origins = env.scene.env_origins curriculum = CurriculumManager( { "reset_sampling": CurriculumTermCfg( @@ -94,6 +65,72 @@ def test_curriculum_credits_the_completed_row_before_reset() -> None: assert updated["Curriculum/reset_sampling/table_probability"].item() == pytest.approx(0.60) +def test_reset_rejects_arm_noise_that_pushes_a_held_cube_into_its_support() -> None: + env = _make_env({"fixed_recipe": int(StackResetRecipe.FINAL_RELEASE), "fixed_role_permutation": 0}) + event = env.event_manager.get_term_cfg("reset_from_state_buffer") + state = get_stack_reset_runtime_state(env) + robot = env.scene["robot"] + top_cube = env.scene["cube_3"] + support_cube = env.scene["cube_2"] + + with torch.random.fork_rng(devices=[]): + torch.manual_seed(1) + env.event_manager.apply("reset", env_ids=slice(None), global_env_step_count=0) + initial_rows = state.row_ids.clone() + held = state.held_cube_ids == 2 + assert held.any() and not held.all() + authored_arm = robot.write_joint_position_to_sim_index.call_args.kwargs["position"] + authored_top = top_cube.write_root_pose_to_sim_index.call_args.kwargs["root_pose"] + + event.params["arm_joint_noise_range"] = 0.01 + torch.manual_seed(1) + env.event_manager.apply("reset", env_ids=slice(None), global_env_step_count=1) + + torch.testing.assert_close(state.row_ids, initial_rows) + arm = robot.write_joint_position_to_sim_index.call_args.kwargs["position"] + target = robot.actuators.target_command.set_position_index.call_args.kwargs["value"] + top = top_cube.write_root_pose_to_sim_index.call_args.kwargs["root_pose"] + support = support_cube.write_root_pose_to_sim_index.call_args.kwargs["root_pose"] + # With this draw the held cube penetrates its support by 4 mm without validation. + assert (top[held, 2] - support[held, 2] >= 0.04 - 1.0e-4).all() + torch.testing.assert_close(top[held], authored_top[held], rtol=0.0, atol=0.0) + torch.testing.assert_close(arm[held], authored_arm[held], rtol=0.0, atol=0.0) + torch.testing.assert_close(target, arm, rtol=0.0, atol=0.0) + assert not torch.equal(arm[~held], authored_arm[~held]) + + +def _make_env(reset_params: dict[str, int | float]) -> SimpleNamespace: + num_envs = 4 + robot = Mock() + robot.data.default_joint_pos.torch = torch.zeros(num_envs, 9) + robot.data.default_root_pose.torch = torch.zeros(num_envs, 7) + robot.data.default_root_vel.torch = torch.zeros(num_envs, 6) + robot.find_joints.side_effect = [(list(range(7)), []), ([7, 8], [])] + cubes = [Mock() for _ in range(3)] + for cube in cubes: + cube.data.default_root_pose.torch = torch.zeros(num_envs, 7) + entities = {"robot": robot, **{f"cube_{i}": cube for i, cube in enumerate(cubes, start=1)}} + # The asset mocks record backend writes. The event and curriculum are the real manager terms. + origins = torch.zeros(num_envs, 3) + origins[:, 0] = torch.arange(num_envs) + scene = _Scene(entities, origins) + outcome = SimpleNamespace(ever_success=torch.tensor([True, False, False, True])) + env = SimpleNamespace( + num_envs=num_envs, + device="cpu", + scene=scene, + sim=SimpleNamespace(is_playing=lambda: True), + episode_length_buf=torch.zeros(num_envs, dtype=torch.long), + reset_buf=torch.zeros(num_envs, dtype=torch.bool), + termination_manager=SimpleNamespace(get_term_cfg=lambda name: SimpleNamespace(func=outcome)), + ) + env.event_manager = EventManager( + {"reset_from_state_buffer": EventTermCfg(func=StackResetStateTable, mode="reset", params=reset_params)}, + env, + ) + return env + + class _Scene(dict): def __init__(self, entities: dict[str, Mock], origins: torch.Tensor) -> None: super().__init__(entities) From 0c4b4d7b014270bdf43734aab0a36c94ab9e080d Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Wed, 18 Nov 2026 01:20:38 +0100 Subject: [PATCH 12/13] Honor the configured Franka reset workspace --- .../contrib/stack/mdp/curriculums.py | 47 +++---- .../contrib/stack/mdp/reset_events.py | 128 ++++++++++-------- .../stack/test_franka_stack_curriculum.py | 22 ++- 3 files changed, 118 insertions(+), 79 deletions(-) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/curriculums.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/curriculums.py index b099b680cd3c..10cc499e71ae 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/curriculums.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/curriculums.py @@ -49,11 +49,9 @@ def __init__(self, cfg: CurriculumTermCfg, env: ManagerBasedRLEnv): if not bool(torch.any(self._table_rows)) or bool(torch.all(self._table_rows)): raise RuntimeError("The stack reset table must contain both table and intermediate rows.") self._layout_count = reset_term.layout_count - self._metric_partitions: dict[str, tuple[tuple[str, torch.Tensor], ...]] = { - "recipe": tuple( - (name, reset_term.recipe_ids == recipe) for recipe, name in enumerate(reset_term.recipe_names) - ) - } + self._recipe_rows = tuple( + (name, reset_term.recipe_ids == recipe) for recipe, name in enumerate(reset_term.recipe_names) + ) self._full_task_successes_by_row = torch.zeros_like(self._attempts) def _sampling_distribution(self, table_sampling_probability: float) -> torch.Tensor: @@ -120,7 +118,10 @@ def __call__( attempts = self._attempts observed = attempts > 0 - success_rate = self._progress_successes.sum().float() / attempts.sum().clamp_min(1) + total_attempts = attempts.sum() + table_attempts = attempts[self._table_rows].sum() + total_denominator = total_attempts.clamp_min(1) + table_denominator = table_attempts.clamp_min(1) entropy = -(probabilities * probabilities.clamp_min(torch.finfo(probabilities.dtype).tiny).log()).sum() entropy /= math.log(probabilities.numel()) active_rows = ~self._table_rows @@ -130,7 +131,7 @@ def __call__( metrics.update( { "row_coverage": observed.float().mean(), - "row_success_rate": success_rate, + "row_success_rate": self._progress_successes.sum().float() / total_denominator, "rolling_row_success_rate": (rolling_rates * observed).sum() / observed_count, "sampling_entropy": entropy, "unseen_row_probability_mass": probabilities[unseen_rows].sum(), @@ -139,26 +140,22 @@ def __call__( ((rolling_rates - self._progress_monitor.cfg.target_success_rate).abs() <= 0.1) & observed ).sum() / observed_count, - "full_task_attempts": attempts.sum().float(), - "full_task_success_rate": self._full_task_successes_by_row.sum().float() / attempts.sum().clamp_min(1), + "full_task_attempts": total_attempts.float(), + "full_task_success_rate": self._full_task_successes_by_row.sum().float() / total_denominator, "table_curriculum_success_rate": self._progress_successes[self._table_rows].sum().float() - / self._attempts[self._table_rows].sum().clamp_min(1), + / table_denominator, "table_full_task_success_rate": self._full_task_successes_by_row[self._table_rows].sum().float() - / attempts[self._table_rows].sum().clamp_min(1), - "table_full_task_attempts": attempts[self._table_rows].sum().float(), + / table_denominator, + "table_full_task_attempts": table_attempts.float(), } ) - for prefix, partitions in self._metric_partitions.items(): - for name, rows in partitions: - partition_attempts = attempts[rows].sum() - metric_prefix = f"{prefix}_{name}" - metrics[f"{metric_prefix}_attempts"] = partition_attempts - metrics[f"{metric_prefix}_full_stack_attempts"] = partition_attempts - metrics[f"{metric_prefix}_probability"] = probabilities[rows].sum() - metrics[f"{metric_prefix}_curriculum_success"] = self._progress_successes[ - rows - ].sum().float() / partition_attempts.clamp_min(1) - metrics[f"{metric_prefix}_full_stack_success"] = self._full_task_successes_by_row[ - rows - ].sum().float() / partition_attempts.clamp_min(1) + for name, rows in self._recipe_rows: + recipe_attempts = attempts[rows].sum() + denominator = recipe_attempts.clamp_min(1) + metrics[f"recipe_{name}_attempts"] = recipe_attempts + metrics[f"recipe_{name}_probability"] = probabilities[rows].sum() + metrics[f"recipe_{name}_curriculum_success"] = self._progress_successes[rows].sum().float() / denominator + metrics[f"recipe_{name}_full_stack_success"] = ( + self._full_task_successes_by_row[rows].sum().float() / denominator + ) return metrics diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/reset_events.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/reset_events.py index 335aacf95528..c75499cdafac 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/reset_events.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/reset_events.py @@ -11,14 +11,13 @@ from collections.abc import Sequence from enum import IntEnum from itertools import permutations -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, ClassVar import torch from isaaclab.managers import EventTermCfg, ManagerTermBase from isaaclab.utils.math import matrix_from_quat, normalize, quat_mul -from ..constants import FRANKA_STACK_ARM_WORKSPACE_LOWER, FRANKA_STACK_ARM_WORKSPACE_UPPER from .runtime_state import create_stack_reset_runtime_state if TYPE_CHECKING: @@ -144,9 +143,9 @@ ) _NEAR_GRASP_POSE_INDEX = 0 _PREGRASP_POSE_INDEX = 1 -_LIFTED_OR_RED_ALIGNED_POSE_INDEX = 2 -_GREEN_ALIGNED_POSE_INDEX = 3 -_GREEN_RELEASE_POSE_INDEX = 4 +_LIFTED_OR_FIRST_ALIGNED_POSE_INDEX = 2 +_SECOND_ALIGNED_POSE_INDEX = 3 +_SECOND_RELEASE_POSE_INDEX = 4 class StackResetRecipe(IntEnum): @@ -218,10 +217,8 @@ def _oriented_cube_pair_intersections( ) -> torch.Tensor: """Return rows where two oriented cubes overlap by more than a tolerance. - This is an exact 15-axis separating-axis test for two oriented boxes. - Face-normal checks alone are insufficient for tilted reset cubes, and the - previous center-distance approximation missed corner/edge intersections. - Degenerate cross products from parallel box axes are ignored. + The separating-axis test checks both cubes' face normals and the cross products of their edges. + Cross products of parallel axes are ignored. """ if first_centers.shape != second_centers.shape or first_centers.shape[-1] != 3: raise ValueError("Cube centers must have matching shapes ending in three coordinates.") @@ -261,15 +258,11 @@ def _oriented_cube_pair_intersections( def _franka_tool_position(joint_positions: torch.Tensor) -> torch.Tensor: - """Compute configured Panda tool-center positions from seven joints. + """Compute the stock fixed-base Panda's tool-center positions from seven joints. - Reset rows must preserve the rigid transform between a held cube and the - fingers. Interpolating robot joints and cube Cartesian positions - independently violates that transform by up to two centimeters and - produces a floating object that immediately falls under gravity. This - compact forward kinematics follows the Franka joint origins authored in - the task's robot asset and includes the configured 10.34 cm action-frame - offset from ``panda_hand``. + The authored table assumes the stock Panda geometry with its base at the environment origin. This chain + evaluates candidate arm poses before writing simulation state and includes the 10.34 cm tool offset + from ``panda_hand``. A different robot linkage or base pose requires recalibrating the reset table. Args: joint_positions: Franka arm positions [rad], shape ``(..., 7)``. @@ -326,19 +319,20 @@ class StackResetStateTable(ManagerTermBase): phases. Motion phases are densely interpolated and table starts span a deterministic low-discrepancy layout set. Complete physical states are sampled from a shared validated cache, with a learned success rate for - each state. + each state. The configured arm action supplies the workspace for both + catalog eligibility and reset perturbations. """ - _TABLE_HEIGHT = 0.0205 - _CUBE_HEIGHT = 0.04 - _PICK_PROGRESS_BINS = 17 - _RELEASE_PROGRESS_BINS = 17 - _MOTION_PROGRESS_BINS = 33 + _TABLE_HEIGHT: ClassVar[float] = 0.0205 + _CUBE_HEIGHT: ClassVar[float] = 0.04 + _PICK_PROGRESS_BINS: ClassVar[int] = 17 + _RELEASE_PROGRESS_BINS: ClassVar[int] = 17 + _MOTION_PROGRESS_BINS: ClassVar[int] = 33 # Eighteen workspace/source-order layouts each contribute 64 independent # table arrangements: 1,152 deployment starts and 6,786 rows overall. - _TABLE_ROWS_PER_LAYOUT = 64 - _EXPECTED_ARM_JOINTS = 7 - _EXPECTED_HAND_JOINTS = 2 + _TABLE_ROWS_PER_LAYOUT: ClassVar[int] = 64 + _EXPECTED_ARM_JOINTS: ClassVar[int] = 7 + _EXPECTED_HAND_JOINTS: ClassVar[int] = 2 def __init__(self, cfg: EventTermCfg, env: ManagerBasedRLEnv): super().__init__(cfg, env) @@ -356,7 +350,17 @@ def __init__(self, cfg: EventTermCfg, env: ManagerBasedRLEnv): f"found {len(self._arm_joint_ids)} and {len(self._hand_joint_ids)}." ) - self._arm_anchors = torch.tensor(_STATE_TABLE_ARM_POSES, dtype=torch.float32, device=env.device) + arm_action = env.cfg.actions.arm_action + self._workspace_lower = torch.tensor(arm_action.workspace_lower, dtype=torch.float32, device=self.device) + self._workspace_upper = torch.tensor(arm_action.workspace_upper, dtype=torch.float32, device=self.device) + joint_shape = (self._EXPECTED_ARM_JOINTS,) + if self._workspace_lower.shape != joint_shape or self._workspace_upper.shape != joint_shape: + raise ValueError("Franka stack arm action workspace must contain one lower and upper bound per joint.") + if not torch.isfinite(self._workspace_lower).all() or not torch.isfinite(self._workspace_upper).all(): + raise ValueError("Franka stack arm action workspace bounds must be finite.") + if (self._workspace_lower >= self._workspace_upper).any(): + raise ValueError("Franka stack arm action workspace lower bounds must be below the upper bounds.") + self._role_permutations = torch.tensor( tuple(permutations(range(3))), dtype=torch.long, @@ -369,9 +373,12 @@ def __init__(self, cfg: EventTermCfg, env: ManagerBasedRLEnv): table_rows_per_layout=int(cfg.params["table_rows_per_layout"]), ) self._validate_table() + self._restrict_to_workspace() self._rows_by_recipe = tuple( torch.nonzero(self._recipe_ids == int(recipe), as_tuple=False).flatten() for recipe in StackResetRecipe ) + if self._rows_by_recipe[StackResetRecipe.TABLE].numel() == 0: + raise ValueError("Franka stack arm action workspace excludes every table start.") self._runtime_state = create_stack_reset_runtime_state(env) self._sampling_probabilities: torch.Tensor | None = None @@ -417,6 +424,7 @@ def _build_table( raise ValueError("table_rows_per_layout must be positive.") if not closed_finger_position < open_finger_position: raise ValueError("closed_finger_position must be less than open_finger_position.") + arm_anchors = torch.tensor(_STATE_TABLE_ARM_POSES, dtype=torch.float32, device="cpu") arm_rows: list[torch.Tensor] = [] hand_rows: list[torch.Tensor] = [] position_rows: list[torch.Tensor] = [] @@ -432,13 +440,13 @@ def append( held_role: int, ) -> None: arm_rows.append(arm_position) - hand_rows.append(self._arm_anchors.new_full((self._EXPECTED_HAND_JOINTS,), finger_position)) + hand_rows.append(arm_anchors.new_full((self._EXPECTED_HAND_JOINTS,), finger_position)) position_rows.append(role_positions) recipe_rows.append(int(recipe)) held_role_rows.append(held_role) layout_rows.append(layout_id) - # Author scalar waypoints on the CPU; iterating GPU tensors would synchronize each row. + # Author waypoints on the CPU and transfer the stacked rows in batches. pick_progress = tuple(index / (self._PICK_PROGRESS_BINS - 1) for index in range(self._PICK_PROGRESS_BINS)) motion_progress = tuple(index / (self._MOTION_PROGRESS_BINS - 1) for index in range(self._MOTION_PROGRESS_BINS)) release_progress = tuple( @@ -448,7 +456,7 @@ def append( base_x, base_y = _STATE_TABLE_ANCHORS[base_anchor] first_x, first_y = _STATE_TABLE_ANCHORS[first_anchor] second_x, second_y = _STATE_TABLE_ANCHORS[second_anchor] - base_position = self._arm_anchors.new_tensor((base_x, base_y, self._TABLE_HEIGHT)) + base_position = arm_anchors.new_tensor((base_x, base_y, self._TABLE_HEIGHT)) first_source = base_position.new_tensor((first_x, first_y, self._TABLE_HEIGHT)) second_source = base_position.new_tensor((second_x, second_y, self._TABLE_HEIGHT)) table_positions = torch.stack((base_position, first_source, second_source)) @@ -457,13 +465,13 @@ def append( first_placed_alpha = float((first_stack_position[2] - 0.04) / (0.08 - 0.04)) second_placed_alpha = float((second_stack_position[2] - 0.08) / (0.1175 - 0.08)) first_placed_arm = torch.lerp( - self._arm_anchors[base_anchor, _NEAR_GRASP_POSE_INDEX], - self._arm_anchors[base_anchor, _PREGRASP_POSE_INDEX], + arm_anchors[base_anchor, _NEAR_GRASP_POSE_INDEX], + arm_anchors[base_anchor, _PREGRASP_POSE_INDEX], first_placed_alpha, ) second_placed_arm = torch.lerp( - self._arm_anchors[base_anchor, _PREGRASP_POSE_INDEX], - self._arm_anchors[base_anchor, _GREEN_RELEASE_POSE_INDEX], + arm_anchors[base_anchor, _PREGRASP_POSE_INDEX], + arm_anchors[base_anchor, _SECOND_RELEASE_POSE_INDEX], second_placed_alpha, ) @@ -490,7 +498,7 @@ def append( StackResetRecipe.FINAL_RELEASE, torch.lerp( second_placed_arm, - self._arm_anchors[base_anchor, _GREEN_RELEASE_POSE_INDEX], + arm_anchors[base_anchor, _SECOND_RELEASE_POSE_INDEX], progress, ), full_stack_positions, @@ -505,14 +513,14 @@ def append( 2, second_anchor, second_placed_arm, - _GREEN_ALIGNED_POSE_INDEX, + _SECOND_ALIGNED_POSE_INDEX, (StackResetRecipe.SECOND_PLACE, StackResetRecipe.SECOND_TRANSPORT, StackResetRecipe.SECOND_PICK), ), ( 1, first_anchor, first_placed_arm, - _LIFTED_OR_RED_ALIGNED_POSE_INDEX, + _LIFTED_OR_FIRST_ALIGNED_POSE_INDEX, (StackResetRecipe.FIRST_PLACE, StackResetRecipe.FIRST_TRANSPORT, StackResetRecipe.FIRST_PICK), ), ): @@ -523,10 +531,10 @@ def append( source_positions[1] = first_stack_position placed_positions = source_positions.clone() placed_positions[role] = base_position + base_position.new_tensor((0.0, 0.0, role * self._CUBE_HEIGHT)) - near_grasp_arm = self._arm_anchors[source_anchor, _NEAR_GRASP_POSE_INDEX] - pregrasp_arm = self._arm_anchors[source_anchor, _PREGRASP_POSE_INDEX] - lifted_arm = self._arm_anchors[source_anchor, _LIFTED_OR_RED_ALIGNED_POSE_INDEX] - aligned_arm = self._arm_anchors[base_anchor, aligned_pose] + near_grasp_arm = arm_anchors[source_anchor, _NEAR_GRASP_POSE_INDEX] + pregrasp_arm = arm_anchors[source_anchor, _PREGRASP_POSE_INDEX] + lifted_arm = arm_anchors[source_anchor, _LIFTED_OR_FIRST_ALIGNED_POSE_INDEX] + aligned_arm = arm_anchors[base_anchor, aligned_pose] for progress in motion_progress: supported = progress == 1.0 @@ -580,9 +588,7 @@ def append( for progress in motion_progress: append( StackResetRecipe.PAIR_READY, - torch.lerp( - self._arm_anchors[base_anchor, _GREEN_RELEASE_POSE_INDEX], pregrasp_arm, progress - ), + torch.lerp(arm_anchors[base_anchor, _SECOND_RELEASE_POSE_INDEX], pregrasp_arm, progress), source_positions, open_finger_position, -1, @@ -632,20 +638,20 @@ def lattice(multiplier: int, offset: int) -> float: tuple((x, y, self._TABLE_HEIGHT) for x, y in table_xy) ) approach_anchor = min(int(lattice(263, 113) * len(_STATE_TABLE_ANCHORS)), len(_STATE_TABLE_ANCHORS) - 1) - arm_noise = self._arm_anchors.new_tensor( + arm_noise = arm_anchors.new_tensor( tuple(0.04 * (lattice(271 + 18 * joint_id, 127 + 31 * joint_id) - 0.5) for joint_id in range(7)) ) append( StackResetRecipe.TABLE, - self._arm_anchors[approach_anchor, _PREGRASP_POSE_INDEX] + arm_noise, + arm_anchors[approach_anchor, _PREGRASP_POSE_INDEX] + arm_noise, randomized_table_positions, open_finger_position, -1, ) - self._arm_positions = torch.stack(arm_rows) - self._hand_positions = torch.stack(hand_rows) - self._role_positions = torch.stack(position_rows) + self._arm_positions = torch.stack(arm_rows).to(self.device) + self._hand_positions = torch.stack(hand_rows).to(self.device) + self._role_positions = torch.stack(position_rows).to(self.device) self._recipe_ids = torch.tensor(recipe_rows, dtype=torch.long, device=self.device) self._held_roles = torch.tensor(held_role_rows, dtype=torch.long, device=self.device) self._layout_ids = torch.tensor(layout_rows, dtype=torch.long, device=self.device) @@ -670,7 +676,7 @@ def lattice(multiplier: int, offset: int) -> float: self._role_quaternions[..., 3] = torch.cos(half_yaw) held_rows = torch.nonzero(self._held_roles >= 0, as_tuple=False).flatten() if held_rows.numel() > 0: - # Held cubes follow the actual hand FK, not an independent Cartesian trajectory. + # Place held cubes at the tool center for their authored arm pose. self._role_positions[held_rows, self._held_roles[held_rows]] = _franka_tool_position( self._arm_positions[held_rows] ) @@ -731,6 +737,22 @@ def _validate_table(self) -> None: if bool(torch.any(torch.abs(first_support_delta - expected_support_delta) > 1.0e-5)): raise RuntimeError("A second-stage stack reset row does not place the first movable cube on the base.") + def _restrict_to_workspace(self) -> None: + """Keep authored states that the action can replay at their validated poses.""" + in_workspace = ( + (self._arm_positions >= self._workspace_lower) & (self._arm_positions <= self._workspace_upper) + ).all(dim=1) + if in_workspace.all(): + return + self._arm_positions = self._arm_positions[in_workspace] + self._hand_positions = self._hand_positions[in_workspace] + self._role_positions = self._role_positions[in_workspace] + self._role_quaternions = self._role_quaternions[in_workspace] + self._recipe_ids = self._recipe_ids[in_workspace] + self._held_roles = self._held_roles[in_workspace] + self._layout_ids = self._layout_ids[in_workspace] + self._target_potentials = self._target_potentials[in_workspace] + def __call__( self, env: ManagerBasedRLEnv, @@ -774,6 +796,8 @@ def __call__( else: recipe = StackResetRecipe.TABLE if fixed_recipe is None else StackResetRecipe(fixed_recipe) recipe_rows = self._rows_by_recipe[recipe] + if recipe_rows.numel() == 0: + raise ValueError(f"Franka stack arm action workspace excludes every {recipe.name.lower()} start.") row_ids = recipe_rows[torch.randint(recipe_rows.numel(), (env_ids.numel(),), device=self.device)] if fixed_role_permutation is None: permutation_ids = torch.randint( @@ -809,9 +833,7 @@ def __call__( ) arm_noise_scale[table_rows] = table_arm_joint_noise_range arm_positions = authored_arm_positions + (2.0 * torch.rand_like(authored_arm_positions) - 1.0) * arm_noise_scale - arm_lower = arm_positions.new_tensor(FRANKA_STACK_ARM_WORKSPACE_LOWER) - arm_upper = arm_positions.new_tensor(FRANKA_STACK_ARM_WORKSPACE_UPPER) - arm_positions.clamp_(min=arm_lower, max=arm_upper) + arm_positions.clamp_(min=self._workspace_lower, max=self._workspace_upper) role_positions = self._role_positions[row_ids].clone() role_quaternions = self._role_quaternions[row_ids].clone() diff --git a/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_curriculum.py b/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_curriculum.py index 19ad3f73f363..a4411fa643e8 100644 --- a/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_curriculum.py +++ b/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_curriculum.py @@ -11,6 +11,7 @@ from isaaclab.managers import CurriculumManager, CurriculumTermCfg, EventManager, EventTermCfg +from isaaclab_tasks.contrib.stack.constants import FRANKA_STACK_ARM_WORKSPACE_LOWER, FRANKA_STACK_ARM_WORKSPACE_UPPER from isaaclab_tasks.contrib.stack.mdp.curriculums import StackResetTableCurriculum from isaaclab_tasks.contrib.stack.mdp.reset_events import StackResetRecipe, StackResetStateTable from isaaclab_tasks.contrib.stack.mdp.runtime_state import get_stack_reset_runtime_state @@ -99,7 +100,24 @@ def test_reset_rejects_arm_noise_that_pushes_a_held_cube_into_its_support() -> N assert not torch.equal(arm[~held], authored_arm[~held]) -def _make_env(reset_params: dict[str, int | float]) -> SimpleNamespace: +def test_reset_uses_the_configured_action_workspace() -> None: + # Exclude table starts on one side of the default controller workspace. + workspace_upper = (0.0, *FRANKA_STACK_ARM_WORKSPACE_UPPER[1:]) + env = _make_env( + {"fixed_recipe": int(StackResetRecipe.TABLE), "table_arm_joint_noise_range": 0.05}, + workspace_upper=workspace_upper, + ) + with torch.random.fork_rng(devices=[]): + torch.manual_seed(1) + env.event_manager.apply("reset", env_ids=slice(None), global_env_step_count=0) + robot = env.scene["robot"] + arm = robot.write_joint_position_to_sim_index.call_args.kwargs["position"][:, :7] + assert (arm[:, 0] <= workspace_upper[0]).all() + + +def _make_env( + reset_params: dict[str, int | float], workspace_upper: tuple[float, ...] = FRANKA_STACK_ARM_WORKSPACE_UPPER +) -> SimpleNamespace: num_envs = 4 robot = Mock() robot.data.default_joint_pos.torch = torch.zeros(num_envs, 9) @@ -115,7 +133,9 @@ def _make_env(reset_params: dict[str, int | float]) -> SimpleNamespace: origins[:, 0] = torch.arange(num_envs) scene = _Scene(entities, origins) outcome = SimpleNamespace(ever_success=torch.tensor([True, False, False, True])) + arm_action = SimpleNamespace(workspace_lower=FRANKA_STACK_ARM_WORKSPACE_LOWER, workspace_upper=workspace_upper) env = SimpleNamespace( + cfg=SimpleNamespace(actions=SimpleNamespace(arm_action=arm_action)), num_envs=num_envs, device="cpu", scene=scene, From 42c30cdbb1eccde07a890123ca1b50d84e105d2b Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Fri, 20 Nov 2026 11:57:06 +0100 Subject: [PATCH 13/13] Reuse native reset-state APIs for Franka stacking --- .../franka-stack-reset-curriculum.added.rst | 4 +- .../stack-success-height.added.rst | 2 - .../changelog.d/stack-success-height.minor | 0 .../contrib/stack/mdp/curriculums.py | 159 +++++++++++------- .../contrib/stack/mdp/reset_events.py | 148 ++++++++-------- .../contrib/stack/mdp/runtime_state.py | 7 + .../contrib/stack/mdp/terminations.py | 74 ++++---- .../test/contrib/stack/test_cubes_stacked.py | 49 ------ .../stack/test_franka_stack_curriculum.py | 18 ++ 9 files changed, 231 insertions(+), 230 deletions(-) delete mode 100644 source/isaaclab_tasks/changelog.d/stack-success-height.added.rst delete mode 100644 source/isaaclab_tasks/changelog.d/stack-success-height.minor delete mode 100644 source/isaaclab_tasks/test/contrib/stack/test_cubes_stacked.py diff --git a/source/isaaclab_tasks/changelog.d/franka-stack-reset-curriculum.added.rst b/source/isaaclab_tasks/changelog.d/franka-stack-reset-curriculum.added.rst index a4145c6bc776..93b62a98f603 100644 --- a/source/isaaclab_tasks/changelog.d/franka-stack-reset-curriculum.added.rst +++ b/source/isaaclab_tasks/changelog.d/franka-stack-reset-curriculum.added.rst @@ -1,2 +1,2 @@ -* Added validated phase-specific Franka cube-stacking resets and a curriculum that - retains table starts alongside starts sampled from recent episode outcomes. +* Added validated phase-specific Franka cube-stacking resets using the shared reset-state APIs, + with a curriculum that retains table starts alongside starts sampled from recent outcomes. diff --git a/source/isaaclab_tasks/changelog.d/stack-success-height.added.rst b/source/isaaclab_tasks/changelog.d/stack-success-height.added.rst deleted file mode 100644 index 781ab589ecfc..000000000000 --- a/source/isaaclab_tasks/changelog.d/stack-success-height.added.rst +++ /dev/null @@ -1,2 +0,0 @@ -* Added the optional ``symmetric_height_tolerance`` parameter to ``cubes_stacked`` for tasks - that need a lower bound as well as an upper bound on vertical center separation. diff --git a/source/isaaclab_tasks/changelog.d/stack-success-height.minor b/source/isaaclab_tasks/changelog.d/stack-success-height.minor deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/curriculums.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/curriculums.py index 10cc499e71ae..a3f835e1f9fe 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/curriculums.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/curriculums.py @@ -8,23 +8,60 @@ from __future__ import annotations import math -from collections.abc import Sequence +from collections.abc import Mapping, Sequence from typing import TYPE_CHECKING import torch +import warp as wp +from isaaclab.envs.reset import ResetStateSampler, ResetStateSamplerCfg, SamplingScoreCfg from isaaclab.managers import CurriculumTermCfg, ManagerTermBase -from isaaclab.utils.configclass import instantiate +from isaaclab.utils import configclass from isaaclab_tasks.utils.success_monitor import SuccessMonitorCfg from .reset_events import StackResetRecipe, StackResetStateTable -from .runtime_state import get_stack_reset_runtime_state +from .runtime_state import get_stack_reset_runtime_state, torch_warp_stream if TYPE_CHECKING: from isaaclab.envs import ManagerBasedRLEnv +class _StackSamplingScore: + """Preserve the curriculum's table share and balance intermediate layouts.""" + + def __init__(self, cfg: _StackSamplingScoreCfg): + self._cfg = cfg + + def score(self, metrics: Mapping[str, wp.array], out: wp.array) -> None: + rate = wp.to_torch(metrics["success_rate"]) + table_rows = wp.to_torch(metrics["table_rows"]) + layout_ids = wp.to_torch(metrics["layout_ids"]) + table_probability = wp.to_torch(metrics["table_probability"])[0] + + cfg = self._cfg.monitor + target = min(max(cfg.target_success_rate, 0.0), 1.0) + kappa = max(cfg.kappa, 0.0) + eps = 1.0e-4 + adaptive = (rate + eps).pow(kappa * target) * (1.0 - rate + eps).pow(kappa * (1.0 - target)) + adaptive = adaptive.clamp_min(eps).pow(1.0 / max(cfg.temperature, 1.0)) + adaptive.masked_fill_(table_rows, 0.0) + layout_mass = adaptive.new_zeros(self._cfg.layout_count) + layout_mass.scatter_add_(0, layout_ids, adaptive) + adaptive /= layout_mass[layout_ids].clamp_min(torch.finfo(adaptive.dtype).tiny) + adaptive /= adaptive.sum() + table = table_rows.to(dtype=adaptive.dtype) + table /= table.sum() + wp.to_torch(out).copy_(adaptive * (1.0 - table_probability) + table * table_probability) + + +@configclass +class _StackSamplingScoreCfg(SamplingScoreCfg): + class_type: type = _StackSamplingScore + monitor: SuccessMonitorCfg = SuccessMonitorCfg() + layout_count: int = 1 + + class StackResetTableCurriculum(ManagerTermBase): """Mix guaranteed table starts with target-rate reset sampling.""" @@ -37,36 +74,38 @@ def __init__(self, cfg: CurriculumTermCfg, env: ManagerBasedRLEnv): monitor_cfg = cfg.params["success_monitor"] if not isinstance(monitor_cfg, SuccessMonitorCfg): raise TypeError("StackResetTableCurriculum requires a SuccessMonitorCfg.") - self._progress_monitor = instantiate( - monitor_cfg, - num_partitions=1, - partition_size=reset_term.row_count, - device=env.device, - ) - self._attempts = torch.zeros(reset_term.row_count, dtype=torch.long, device=env.device) - self._progress_successes = torch.zeros_like(self._attempts) + self._target_success_rate = monitor_cfg.target_success_rate + self._progress_successes = torch.zeros(reset_term.row_count, dtype=torch.long, device=env.device) + self._full_task_successes_by_row = torch.zeros_like(self._progress_successes) self._table_rows = reset_term.recipe_ids == StackResetRecipe.TABLE if not bool(torch.any(self._table_rows)) or bool(torch.all(self._table_rows)): raise RuntimeError("The stack reset table must contain both table and intermediate rows.") - self._layout_count = reset_term.layout_count self._recipe_rows = tuple( (name, reset_term.recipe_ids == recipe) for recipe, name in enumerate(reset_term.recipe_names) ) - self._full_task_successes_by_row = torch.zeros_like(self._attempts) - - def _sampling_distribution(self, table_sampling_probability: float) -> torch.Tensor: - """Mix uniform table starts with layout-balanced intermediate starts.""" - adaptive = self._progress_monitor.target_weights() - adaptive[self._table_rows] = 0.0 - layout_ids = self._reset_term.layout_ids - layout_mass = torch.zeros(self._layout_count, dtype=adaptive.dtype, device=adaptive.device) - layout_mass.scatter_add_(0, layout_ids, adaptive) - adaptive /= layout_mass[layout_ids].clamp_min(torch.finfo(adaptive.dtype).tiny) - adaptive /= adaptive.sum() - table = self._table_rows.to(dtype=adaptive.dtype) - table /= table.sum() - probabilities = (1.0 - table_sampling_probability) * adaptive + table_sampling_probability * table - return probabilities + table_probability = cfg.params.get("table_sampling_probability", 0.35) + if not 0.0 < table_probability < 1.0: + raise ValueError("table_sampling_probability must lie strictly between zero and one.") + self._table_probability = torch.full((reset_term.row_count,), table_probability, device=env.device) + sampler_cfg = ResetStateSamplerCfg( + history_length=monitor_cfg.monitored_history_len, + scores=[_StackSamplingScoreCfg(monitor=monitor_cfg, layout_count=reset_term.layout_count)], + uniform_weight=0.0, + seed=getattr(env.cfg, "seed", 0) or 0, + ) + with torch_warp_stream(env.device): + self._sampler = ResetStateSampler( + sampler_cfg, + num_envs=env.num_envs, + num_states=reset_term.row_count, + device=env.device, + metrics={ + "table_rows": self._table_rows, + "layout_ids": reset_term.layout_ids, + "table_probability": self._table_probability, + }, + ) + reset_term.set_sampler(self._sampler) def __call__( self, @@ -87,36 +126,37 @@ def __call__( metrics: dict[str, torch.Tensor] = { "batch_table_full_task_attempts": torch.zeros((), device=env.device), } - if ids.numel(): - state = get_stack_reset_runtime_state(env) - completed = (state.row_ids[ids] >= 0) & (env.episode_length_buf[ids] > 0) & env.reset_buf[ids] - completed_ids = ids[completed] - if completed_ids.numel(): - success_context = env.termination_manager.get_term_cfg(success_context_name).func - succeeded = success_context.ever_success[completed_ids] - final_success_context = env.termination_manager.get_term_cfg(final_success_context_name).func - final_succeeded = final_success_context.ever_success[completed_ids] - metrics["batch_success_rate"] = succeeded.float().mean() - metrics["batch_full_task_success_rate"] = final_succeeded.float().mean() - completed_rows = state.row_ids[completed_ids] - completed_table = self._table_rows[completed_rows] - table_attempts = completed_table.sum() - metrics["batch_table_full_task_attempts"] = table_attempts - if bool(table_attempts): - metrics["batch_table_full_task_success_rate"] = final_succeeded[completed_table].float().mean() - self._progress_monitor.success_update(completed_rows, succeeded) - self._attempts.add_(torch.bincount(completed_rows, minlength=self._reset_term.row_count)) - self._progress_successes.add_( - torch.bincount(completed_rows[succeeded], minlength=self._reset_term.row_count) - ) - self._full_task_successes_by_row.add_( - torch.bincount(completed_rows[final_succeeded], minlength=self._reset_term.row_count) - ) - - probabilities = self._sampling_distribution(table_sampling_probability) - self._reset_term.update_sampling_probabilities(probabilities) - - attempts = self._attempts + state = get_stack_reset_runtime_state(env) + completed = (state.row_ids[ids] >= 0) & (env.episode_length_buf[ids] > 0) & env.reset_buf[ids] + completed_ids = ids[completed] + success = None + if completed_ids.numel(): + success = env.termination_manager.get_term_cfg(success_context_name).func.ever_success + succeeded = success[completed_ids] + final_success_context = env.termination_manager.get_term_cfg(final_success_context_name).func + final_succeeded = final_success_context.ever_success[completed_ids] + metrics["batch_success_rate"] = succeeded.float().mean() + metrics["batch_full_task_success_rate"] = final_succeeded.float().mean() + completed_rows = state.row_ids[completed_ids] + completed_table = self._table_rows[completed_rows] + table_attempts = completed_table.sum() + metrics["batch_table_full_task_attempts"] = table_attempts + if bool(table_attempts): + metrics["batch_table_full_task_success_rate"] = final_succeeded[completed_table].float().mean() + self._progress_successes.add_( + torch.bincount(completed_rows[succeeded], minlength=self._reset_term.row_count) + ) + self._full_task_successes_by_row.add_( + torch.bincount(completed_rows[final_succeeded], minlength=self._reset_term.row_count) + ) + + # Keep assignments when recording outcomes. The reset event draws for the actual restoration mask. + self._table_probability.fill_(table_sampling_probability) + with torch_warp_stream(env.device): + self._sampler.reset(env_ids=completed_ids, success=success, state_ids=state.row_ids) + probabilities = self._sampler.probabilities.torch + attempts = self._sampler.episode_counts.torch + rolling_rates = self._sampler.success_rate.torch observed = attempts > 0 total_attempts = attempts.sum() table_attempts = attempts[self._table_rows].sum() @@ -126,7 +166,6 @@ def __call__( entropy /= math.log(probabilities.numel()) active_rows = ~self._table_rows unseen_rows = active_rows & ~observed - rolling_rates = self._progress_monitor.get_success_rate() observed_count = observed.sum().clamp_min(1) metrics.update( { @@ -136,9 +175,7 @@ def __call__( "sampling_entropy": entropy, "unseen_row_probability_mass": probabilities[unseen_rows].sum(), "table_probability": probabilities[self._table_rows].sum(), - "target_band_fraction": ( - ((rolling_rates - self._progress_monitor.cfg.target_success_rate).abs() <= 0.1) & observed - ).sum() + "target_band_fraction": (((rolling_rates - self._target_success_rate).abs() <= 0.1) & observed).sum() / observed_count, "full_task_attempts": total_attempts.float(), "full_task_success_rate": self._full_task_successes_by_row.sum().float() / total_denominator, diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/reset_events.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/reset_events.py index c75499cdafac..2adc7a167e21 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/reset_events.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/reset_events.py @@ -15,10 +15,11 @@ import torch +from isaaclab.envs.reset import ResetStateBuffer, ResetStateSampler from isaaclab.managers import EventTermCfg, ManagerTermBase from isaaclab.utils.math import matrix_from_quat, normalize, quat_mul -from .runtime_state import create_stack_reset_runtime_state +from .runtime_state import create_stack_reset_runtime_state, torch_warp_stream if TYPE_CHECKING: from isaaclab.assets import Articulation, RigidObject @@ -366,26 +367,34 @@ def __init__(self, cfg: EventTermCfg, env: ManagerBasedRLEnv): dtype=torch.long, device=env.device, ) - self._build_table( + table = self._build_table( closed_finger_position=float(cfg.params["closed_finger_position"]), placed_finger_position=float(cfg.params["placed_finger_position"]), open_finger_position=float(cfg.params["open_finger_position"]), table_rows_per_layout=int(cfg.params["table_rows_per_layout"]), ) - self._validate_table() - self._restrict_to_workspace() + self._validate_table(table) + in_workspace = ( + (table["arm_positions"] >= self._workspace_lower) & (table["arm_positions"] <= self._workspace_upper) + ).all(dim=1) + table = {name: rows[in_workspace] for name, rows in table.items()} + self._recipe_ids = table["recipes"] + self._layout_ids = table.pop("layouts") self._rows_by_recipe = tuple( torch.nonzero(self._recipe_ids == int(recipe), as_tuple=False).flatten() for recipe in StackResetRecipe ) if self._rows_by_recipe[StackResetRecipe.TABLE].numel() == 0: raise ValueError("Franka stack arm action workspace excludes every table start.") + with torch_warp_stream(self.device): + self._buffer = ResetStateBuffer(table) + self._selected = {name: value.new_empty((env.num_envs, *value.shape[1:])) for name, value in table.items()} self._runtime_state = create_stack_reset_runtime_state(env) - self._sampling_probabilities: torch.Tensor | None = None + self._sampler: ResetStateSampler | None = None @property def row_count(self) -> int: """Number of physical rows in the reset table.""" - return int(self._arm_positions.shape[0]) + return self._buffer.num_states @property def recipe_ids(self) -> torch.Tensor: @@ -407,9 +416,9 @@ def recipe_names(self) -> tuple[str, ...]: """Stable diagnostic names for reset recipes.""" return tuple(recipe.name.lower() for recipe in StackResetRecipe) - def update_sampling_probabilities(self, probabilities: torch.Tensor) -> None: - """Use the curriculum's distribution for subsequent reset draws.""" - self._sampling_probabilities = probabilities + def set_sampler(self, sampler: ResetStateSampler) -> None: + """Share the curriculum's native history, probabilities, and row assignments.""" + self._sampler = sampler def _build_table( self, @@ -649,13 +658,13 @@ def lattice(multiplier: int, offset: int) -> float: -1, ) - self._arm_positions = torch.stack(arm_rows).to(self.device) - self._hand_positions = torch.stack(hand_rows).to(self.device) - self._role_positions = torch.stack(position_rows).to(self.device) - self._recipe_ids = torch.tensor(recipe_rows, dtype=torch.long, device=self.device) - self._held_roles = torch.tensor(held_role_rows, dtype=torch.long, device=self.device) - self._layout_ids = torch.tensor(layout_rows, dtype=torch.long, device=self.device) - self._target_potentials = torch.tensor( + arm_positions = torch.stack(arm_rows).to(self.device) + hand_positions = torch.stack(hand_rows).to(self.device) + role_positions = torch.stack(position_rows).to(self.device) + recipe_ids = torch.tensor(recipe_rows, dtype=torch.long, device=self.device) + held_roles = torch.tensor(held_role_rows, dtype=torch.long, device=self.device) + layout_ids = torch.tensor(layout_rows, dtype=torch.long, device=self.device) + target_potentials = torch.tensor( tuple(_RECIPE_TARGET_POTENTIAL[StackResetRecipe(recipe)] for recipe in recipe_rows), dtype=torch.float32, device=self.device, @@ -663,50 +672,56 @@ def lattice(multiplier: int, offset: int) -> float: # Cache complete cube pose state, not only position. Random yaw is # physically immaterial for perfect cubes but prevents the reset # mechanism from relying on one authored quaternion representation. - row_ids = torch.arange(self._role_positions.shape[0], device=self.device).unsqueeze(1) + row_ids = torch.arange(role_positions.shape[0], device=self.device).unsqueeze(1) role_ids = torch.arange(3, device=self.device).unsqueeze(0) yaw_fraction = torch.remainder(row_ids * 193 + role_ids * 389 + 17, 1021).float() / 1020.0 half_yaw = math.pi * (2.0 * yaw_fraction - 1.0) - self._role_quaternions = torch.zeros( - (self._role_positions.shape[0], 3, 4), + role_quaternions = torch.zeros( + (role_positions.shape[0], 3, 4), dtype=torch.float32, device=self.device, ) - self._role_quaternions[..., 2] = torch.sin(half_yaw) - self._role_quaternions[..., 3] = torch.cos(half_yaw) - held_rows = torch.nonzero(self._held_roles >= 0, as_tuple=False).flatten() + role_quaternions[..., 2] = torch.sin(half_yaw) + role_quaternions[..., 3] = torch.cos(half_yaw) + held_rows = torch.nonzero(held_roles >= 0, as_tuple=False).flatten() if held_rows.numel() > 0: # Place held cubes at the tool center for their authored arm pose. - self._role_positions[held_rows, self._held_roles[held_rows]] = _franka_tool_position( - self._arm_positions[held_rows] - ) - self._role_quaternions[held_rows, self._held_roles[held_rows]] = self._role_quaternions.new_tensor( - (0.0, 0.0, 0.0, 1.0) - ) - - def _validate_table(self) -> None: + role_positions[held_rows, held_roles[held_rows]] = _franka_tool_position(arm_positions[held_rows]) + role_quaternions[held_rows, held_roles[held_rows]] = role_quaternions.new_tensor((0.0, 0.0, 0.0, 1.0)) + + return { + "arm_positions": arm_positions, + "hand_positions": hand_positions, + "role_positions": role_positions, + "role_quaternions": role_quaternions, + "recipes": recipe_ids, + "held_roles": held_roles, + "layouts": layout_ids, + "target_potentials": target_potentials, + } + + def _validate_table(self, table: dict[str, torch.Tensor]) -> None: """Reject non-finite, penetrating, or semantically inconsistent rows.""" - tensors = ( - self._arm_positions, - self._hand_positions, - self._role_positions, - self._role_quaternions, - ) + role_positions = table["role_positions"] + role_quaternions = table["role_quaternions"] + layout_ids = table["layouts"] + recipe_ids = table["recipes"] + tensors = (table["arm_positions"], table["hand_positions"], role_positions, role_quaternions) if any(not bool(torch.isfinite(value).all()) for value in tensors): raise RuntimeError("Stack reset table contains non-finite values.") - if self._layout_ids.shape != self._recipe_ids.shape: + if layout_ids.shape != recipe_ids.shape: raise RuntimeError("Stack reset table layout IDs do not align with its physical rows.") - if bool(torch.any((self._layout_ids < 0) | (self._layout_ids >= self.layout_count))): + if bool(torch.any((layout_ids < 0) | (layout_ids >= self.layout_count))): raise RuntimeError("Stack reset table contains an invalid workspace layout ID.") - if bool(torch.any(self._role_positions[..., 2] < self._TABLE_HEIGHT - 1.0e-6)): + if bool(torch.any(role_positions[..., 2] < self._TABLE_HEIGHT - 1.0e-6)): raise RuntimeError("Stack reset table places a cube below the table support height.") - role_rotations = matrix_from_quat(self._role_quaternions) + role_rotations = matrix_from_quat(role_quaternions) for first_role, second_role in ((0, 1), (0, 2), (1, 2)): intersecting = _oriented_cube_pair_intersections( - self._role_positions[:, first_role], + role_positions[:, first_role], role_rotations[:, first_role], - self._role_positions[:, second_role], + role_positions[:, second_role], role_rotations[:, second_role], edge_length=self._CUBE_HEIGHT, ) @@ -728,31 +743,15 @@ def _validate_table(self) -> None: int(StackResetRecipe.SECOND_PICK), int(StackResetRecipe.PAIR_READY), ), - dtype=self._recipe_ids.dtype, + dtype=recipe_ids.dtype, device=self.device, ) - second_stage_rows = torch.isin(self._recipe_ids, second_stage_recipes) - first_support_delta = self._role_positions[second_stage_rows, 1] - self._role_positions[second_stage_rows, 0] + second_stage_rows = torch.isin(recipe_ids, second_stage_recipes) + first_support_delta = role_positions[second_stage_rows, 1] - role_positions[second_stage_rows, 0] expected_support_delta = first_support_delta.new_tensor((0.0, 0.0, self._CUBE_HEIGHT)) if bool(torch.any(torch.abs(first_support_delta - expected_support_delta) > 1.0e-5)): raise RuntimeError("A second-stage stack reset row does not place the first movable cube on the base.") - def _restrict_to_workspace(self) -> None: - """Keep authored states that the action can replay at their validated poses.""" - in_workspace = ( - (self._arm_positions >= self._workspace_lower) & (self._arm_positions <= self._workspace_upper) - ).all(dim=1) - if in_workspace.all(): - return - self._arm_positions = self._arm_positions[in_workspace] - self._hand_positions = self._hand_positions[in_workspace] - self._role_positions = self._role_positions[in_workspace] - self._role_quaternions = self._role_quaternions[in_workspace] - self._recipe_ids = self._recipe_ids[in_workspace] - self._held_roles = self._held_roles[in_workspace] - self._layout_ids = self._layout_ids[in_workspace] - self._target_potentials = self._target_potentials[in_workspace] - def __call__( self, env: ManagerBasedRLEnv, @@ -791,8 +790,9 @@ def __call__( ): raise ValueError("Reset-state randomization ranges must be non-negative.") state = self._runtime_state - if fixed_recipe is None and self._sampling_probabilities is not None: - row_ids = torch.multinomial(self._sampling_probabilities, env_ids.numel(), replacement=True) + if fixed_recipe is None and self._sampler is not None: + # ManagerBasedEnv.reset(seed=...) reseeds Torch but has no hook for the sampler's independent RNG. + row_ids = torch.multinomial(self._sampler.probabilities.torch, env_ids.numel(), replacement=True) else: recipe = StackResetRecipe.TABLE if fixed_recipe is None else StackResetRecipe(fixed_recipe) recipe_rows = self._rows_by_recipe[recipe] @@ -815,16 +815,19 @@ def __call__( device=self.device, ) role_to_cube = self._role_permutations[permutation_ids] - held_roles = self._held_roles[row_ids] + selected = {name: value[: env_ids.numel()] for name, value in self._selected.items()} + with torch_warp_stream(self.device): + self._buffer.get_state(row_ids, out=selected) + held_roles = selected["held_roles"] has_held_cube = held_roles >= 0 selected_cube_ids = role_to_cube.gather(1, held_roles.clamp_min(0).unsqueeze(1)).squeeze(1) held_cube_ids = torch.where(has_held_cube, selected_cube_ids, -1) joint_positions = self._robot.data.default_joint_pos.torch[env_ids].clone() joint_velocities = torch.zeros_like(joint_positions) - authored_arm_positions = self._arm_positions[row_ids] - joint_positions[:, self._hand_joint_ids] = self._hand_positions[row_ids] - table_rows = self._recipe_ids[row_ids] == int(StackResetRecipe.TABLE) + authored_arm_positions = selected["arm_positions"] + joint_positions[:, self._hand_joint_ids] = selected["hand_positions"] + table_rows = selected["recipes"] == int(StackResetRecipe.TABLE) arm_noise_scale = torch.full( (env_ids.numel(), 1), arm_joint_noise_range, @@ -835,8 +838,8 @@ def __call__( arm_positions = authored_arm_positions + (2.0 * torch.rand_like(authored_arm_positions) - 1.0) * arm_noise_scale arm_positions.clamp_(min=self._workspace_lower, max=self._workspace_upper) - role_positions = self._role_positions[row_ids].clone() - role_quaternions = self._role_quaternions[row_ids].clone() + role_positions = selected["role_positions"] + role_quaternions = selected["role_quaternions"] if arm_joint_noise_range > 0.0: held_env_ids = has_held_cube.nonzero(as_tuple=False).flatten() if held_env_ids.numel(): @@ -934,6 +937,9 @@ def __call__( state.row_ids[env_ids] = row_ids state.role_to_cube[env_ids] = role_to_cube - state.recipes[env_ids] = self._recipe_ids[row_ids] - state.target_potentials[env_ids] = self._target_potentials[row_ids] + state.recipes[env_ids] = selected["recipes"] + state.target_potentials[env_ids] = selected["target_potentials"] state.held_cube_ids[env_ids] = held_cube_ids + if self._sampler is not None: + with torch_warp_stream(self.device): + self._sampler.reset(env_ids=env_ids, state_ids=state.row_ids) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/runtime_state.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/runtime_state.py index aec2d5d2de0a..7d13c57808dd 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/runtime_state.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/runtime_state.py @@ -11,6 +11,7 @@ from typing import TYPE_CHECKING import torch +import warp as wp if TYPE_CHECKING: from isaaclab.envs import ManagerBasedRLEnv @@ -53,3 +54,9 @@ def get_stack_reset_runtime_state(env: ManagerBasedRLEnv) -> StackResetRuntimeSt if state is None: raise AttributeError("Stack reset runtime state is unavailable before the reset-table event is initialized.") return state + + +def torch_warp_stream(device: str) -> wp.ScopedStream: + """Order the reset terms' Warp kernels with their Torch inputs and consumers.""" + stream = wp.stream_from_torch(torch.cuda.current_stream(device)) if torch.device(device).type == "cuda" else None + return wp.ScopedStream(stream, sync_enter=False) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/terminations.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/terminations.py index 47b25067ff98..5ad8c508438a 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/terminations.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/terminations.py @@ -3,7 +3,11 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Termination terms for the cube stack task.""" +"""Common functions that can be used to activate certain terminations for the lift task. + +The functions can be passed to the :class:`isaaclab.managers.TerminationTermCfg` object to enable +the termination introduced by the function. +""" from __future__ import annotations @@ -31,7 +35,6 @@ def cubes_stacked( atol: float = 0.0001, rtol: float = 0.0001, max_lin_vel: float | None = 0.05, - symmetric_height_tolerance: bool = False, ) -> torch.Tensor: """Whether the cubes are stacked, released, and at rest. @@ -51,27 +54,38 @@ def cubes_stacked( open value. Gripper joint tolerances are unused for surface grippers. max_lin_vel: Speed [m/s] below which a cube counts as at rest, so that a cube passing through the stacked configuration mid-fall is not scored as success. ``None`` disables the check. - symmetric_height_tolerance: Also require the vertical separation to be within - ``height_threshold`` below ``height_diff``. - - Returns: - A boolean tensor of shape [N] indicating success in each environment. """ robot: Articulation = env.scene[robot_cfg.name] cube_1: RigidObject = env.scene[cube_1_cfg.name] cube_2: RigidObject = env.scene[cube_2_cfg.name] - separation_c12 = cube_2.data.root_pos_w.torch - cube_1.data.root_pos_w.torch - stacked = _cube_pair_is_aligned( - separation_c12, xy_threshold, height_diff, height_threshold, symmetric_height_tolerance - ) + pos_diff_c12 = cube_1.data.root_pos_w.torch - cube_2.data.root_pos_w.torch + + # Compute cube position difference in x-y plane + xy_dist_c12 = torch.linalg.norm(pos_diff_c12[:, :2], dim=1) + + # Compute cube height difference + h_dist_c12 = torch.linalg.norm(pos_diff_c12[:, 2:], dim=1) + + # Check cube positions + stacked = xy_dist_c12 < xy_threshold + stacked = torch.logical_and(h_dist_c12 - height_diff < height_threshold, stacked) + stacked = torch.logical_and(pos_diff_c12[:, 2] < 0.0, stacked) if cube_3_cfg is not None: cube_3: RigidObject = env.scene[cube_3_cfg.name] - separation_c23 = cube_3.data.root_pos_w.torch - cube_2.data.root_pos_w.torch - stacked &= _cube_pair_is_aligned( - separation_c23, xy_threshold, height_diff, height_threshold, symmetric_height_tolerance - ) + pos_diff_c23 = cube_2.data.root_pos_w.torch - cube_3.data.root_pos_w.torch + + # Compute cube position difference in x-y plane + xy_dist_c23 = torch.linalg.norm(pos_diff_c23[:, :2], dim=1) + + # Compute cube height difference + h_dist_c23 = torch.linalg.norm(pos_diff_c23[:, 2:], dim=1) + + # Check cube positions + stacked = torch.logical_and(xy_dist_c23 < xy_threshold, stacked) + stacked = torch.logical_and(h_dist_c23 - height_diff < height_threshold, stacked) + stacked = torch.logical_and(pos_diff_c23[:, 2] < 0.0, stacked) # Check gripper positions if hasattr(env.scene, "surface_grippers") and len(env.scene.surface_grippers) > 0: @@ -105,33 +119,3 @@ def cubes_stacked( stacked &= torch.linalg.norm(cube.data.root_lin_vel_w.torch, dim=1) < max_lin_vel return stacked - - -def _cube_pair_is_aligned( - separation: torch.Tensor, - xy_threshold: float, - height_diff: float, - height_threshold: float, - symmetric_height_tolerance: bool, -) -> torch.Tensor: - """Check the world-frame upper-minus-lower cube displacement. - - Args: - separation: Cube center displacements in meters, with shape [N, 3]. - xy_threshold: Maximum horizontal separation in meters. - height_diff: Expected vertical separation in meters. - height_threshold: Tolerance on the vertical separation in meters. - symmetric_height_tolerance: Apply the tolerance below as well as above ``height_diff``. - - Returns: - A boolean tensor of shape [N] indicating aligned cube pairs. - """ - height = separation[:, 2] - height_error = height - height_diff - if symmetric_height_tolerance: - height_error = height_error.abs() - return ( - (torch.linalg.norm(separation[:, :2], dim=1) < xy_threshold) - & (height > 0.0) - & (height_error < height_threshold) - ) diff --git a/source/isaaclab_tasks/test/contrib/stack/test_cubes_stacked.py b/source/isaaclab_tasks/test/contrib/stack/test_cubes_stacked.py deleted file mode 100644 index 4e1b3b7e05d5..000000000000 --- a/source/isaaclab_tasks/test/contrib/stack/test_cubes_stacked.py +++ /dev/null @@ -1,49 +0,0 @@ -# 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 types import SimpleNamespace - -import pytest -import torch - -from isaaclab_tasks.contrib.stack.mdp import cubes_stacked - -pytestmark = pytest.mark.kitless - - -def test_stacked_cubes_can_require_the_expected_vertical_separation() -> None: - # Each row holds the center heights of one scene, bottom to top. - heights = torch.tensor( - [ - [0.0, 0.0477, 0.0954], - [0.0, 0.0020, 0.0497], - [0.0, 0.0477, 0.0497], - ] - ) - num_envs = len(heights) - scene = { - "robot": SimpleNamespace( - data=SimpleNamespace(joint_pos=SimpleNamespace(torch=torch.full((num_envs, 2), 0.04))), - find_joints=lambda names: ([0, 1], names), - ) - } - for index, center_z in enumerate(heights.T, start=1): - positions = torch.zeros((num_envs, 3)) - positions[:, 2] = center_z - scene[f"cube_{index}"] = SimpleNamespace( - data=SimpleNamespace( - root_pos_w=SimpleNamespace(torch=positions), - root_lin_vel_w=SimpleNamespace(torch=torch.zeros_like(positions)), - ) - ) - env = SimpleNamespace( - scene=scene, - cfg=SimpleNamespace(gripper_joint_names=["finger_joint.*"], gripper_open_val=0.04), - device="cpu", - ) - - assert cubes_stacked(env).tolist() == [True, True, True] - assert cubes_stacked(env, symmetric_height_tolerance=True).tolist() == [True, False, False] - assert cubes_stacked(env, cube_3_cfg=None, symmetric_height_tolerance=True).tolist() == [True, False, True] diff --git a/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_curriculum.py b/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_curriculum.py index a4411fa643e8..3c83b9f23880 100644 --- a/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_curriculum.py +++ b/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_curriculum.py @@ -52,6 +52,7 @@ def test_curriculum_credits_the_completed_row_before_reset() -> None: assert metrics["Curriculum/reset_sampling/recipe_second_transport_attempts"].item() == 1 assert metrics["Curriculum/reset_sampling/recipe_table_attempts"].item() == 0 assert metrics["Curriculum/reset_sampling/batch_success_rate"].item() == 1 + assert metrics["Curriculum/reset_sampling/table_probability"].item() == pytest.approx(0.35) assert "Curriculum/reset_sampling/batch_table_full_task_success_rate" not in metrics assert state.row_ids[-1] == old_row assert (state.recipes[env_ids] == StackResetRecipe.TABLE).all() @@ -65,6 +66,23 @@ def test_curriculum_credits_the_completed_row_before_reset() -> None: updated = curriculum.reset(slice(0, 0)) assert updated["Curriculum/reset_sampling/table_probability"].item() == pytest.approx(0.60) + term.params["fixed_recipe"] = None + env.reset_buf.zero_() + with torch.random.fork_rng(devices=[]): + torch.manual_seed(42) + curriculum.compute(env_ids) + env.event_manager.apply("reset", env_ids=env_ids, global_env_step_count=5) + sampled_rows = state.row_ids.clone() + sampled_roles = state.role_to_cube.clone() + + torch.manual_seed(42) + curriculum.compute(env_ids) + env.event_manager.apply("reset", env_ids=env_ids, global_env_step_count=6) + + torch.testing.assert_close(state.row_ids, sampled_rows) + torch.testing.assert_close(state.role_to_cube, sampled_roles) + assert curriculum.reset(env_ids)["Curriculum/reset_sampling/full_task_attempts"].item() == 1 + def test_reset_rejects_arm_noise_that_pushes_a_held_cube_into_its_support() -> None: env = _make_env({"fixed_recipe": int(StackResetRecipe.FINAL_RELEASE), "fixed_role_permutation": 0})