From b2ee30305f6036f8bde3079081997d3484b57da5 Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Tue, 17 Nov 2026 23:37:46 +0100 Subject: [PATCH 01/28] 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 ef7b1240c1a8fe17943d7be3a84d0eb9e706d0cb Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Tue, 17 Nov 2026 23:41:10 +0100 Subject: [PATCH 02/28] Add state-based Franka cube stacking with PPO --- .../source/_static/css/environment-browser.js | 1 + .../changelog.d/franka-stack-ppo.added.rst | 1 + .../changelog.d/franka-stack-ppo.minor | 0 .../contrib/stack/config/franka/__init__.py | 11 ++++ .../config/franka/agents/rsl_rl_ppo_cfg.py | 41 ++++++++++++++ .../stack/config/franka/stack_rl_env_cfg.py | 53 +++++++++++++++++++ .../contrib/stack/mdp/rewards.py | 40 ++++++++++++++ 7 files changed, 147 insertions(+) create mode 100644 source/isaaclab_tasks/changelog.d/franka-stack-ppo.added.rst create mode 100644 source/isaaclab_tasks/changelog.d/franka-stack-ppo.minor create mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/agents/rsl_rl_ppo_cfg.py create mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_rl_env_cfg.py create mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/rewards.py diff --git a/docs/source/_static/css/environment-browser.js b/docs/source/_static/css/environment-browser.js index 192099aa37f9..13af348ef4a6 100644 --- a/docs/source/_static/css/environment-browser.js +++ b/docs/source/_static/css/environment-browser.js @@ -124,6 +124,7 @@ ["IsaacContrib-Stack-Cube-Franka-IK-Rel-Skillgen", "", "isaacsim_physx", "", "", "environment-previews/franka_stack.jpg", false, {}, {}, "", null, ["||", "isaacsim_physx||"]], ["IsaacContrib-Stack-Cube-Franka-IK-Rel-Visuomotor", "", "isaacsim_physx", "", "", "environment-previews/franka_stack.jpg", false, {}, {}, "", null, ["||", "isaacsim_physx||"]], ["IsaacContrib-Stack-Cube-Franka-IK-Rel-Visuomotor-Cosmos", "", "isaacsim_physx", "", "", "environment-previews/franka_stack.jpg", false, {}, {}, "", null, ["||", "isaacsim_physx||"]], + ["IsaacContrib-Stack-Cube-Franka-RL", "rsl_rl", "isaacsim_physx,newton_mjwarp", "", "", "environment-previews/franka_stack.jpg", false, {}, {}, "", null, ["||", "isaacsim_physx||", "newton_mjwarp||"]], ["IsaacContrib-Stack-Cube-Galbot-Left-Arm-Gripper-RmpFlow", "", "isaacsim_physx", "", "", "environment-previews/galbot_stack_cube.jpg", false, {}, {}, "", null, ["||", "isaacsim_physx||"]], ["IsaacContrib-Stack-Cube-Galbot-Left-Arm-Gripper-Visuomotor", "", "isaacsim_physx", "isaacsim_rtx,newton_renderer", "", "environment-previews/galbot_stack_cube.jpg", false, {}, {}, "", null, ["||", "|isaacsim_rtx|", "|newton_renderer|", "isaacsim_physx||", "isaacsim_physx|isaacsim_rtx|", "isaacsim_physx|newton_renderer|"]], ["IsaacContrib-Stack-Cube-Galbot-Left-Arm-Gripper-Visuomotor-Joint-Position", "", "isaacsim_physx", "isaacsim_rtx,newton_renderer", "", "environment-previews/galbot_stack_cube.jpg", false, {}, {}, "", null, ["||", "|isaacsim_rtx|", "|newton_renderer|", "isaacsim_physx||", "isaacsim_physx|isaacsim_rtx|", "isaacsim_physx|newton_renderer|"]], diff --git a/source/isaaclab_tasks/changelog.d/franka-stack-ppo.added.rst b/source/isaaclab_tasks/changelog.d/franka-stack-ppo.added.rst new file mode 100644 index 000000000000..02996c1c0774 --- /dev/null +++ b/source/isaaclab_tasks/changelog.d/franka-stack-ppo.added.rst @@ -0,0 +1 @@ +* Added a state-based Franka cube stacking task with an RSL-RL PPO configuration. diff --git a/source/isaaclab_tasks/changelog.d/franka-stack-ppo.minor b/source/isaaclab_tasks/changelog.d/franka-stack-ppo.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/__init__.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/__init__.py index 31c4329a447e..a9f6e538f127 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/__init__.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/__init__.py @@ -23,6 +23,17 @@ disable_env_checker=True, ) +gym.register( + id="IsaacContrib-Stack-Cube-Franka-RL", + entry_point="isaaclab.envs:ManagerBasedRLEnv", + kwargs={ + "env_cfg_entry_point": f"{__name__}.stack_rl_env_cfg:FrankaCubeStackRLEnvCfg", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:FrankaStackPPORunnerCfg", + "default_agent": "rsl_rl", + }, + disable_env_checker=True, +) + gym.register( id="IsaacContrib-Stack-Cube-Instance-Randomize-Franka", entry_point="isaaclab.envs:ManagerBasedRLEnv", diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/agents/rsl_rl_ppo_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/agents/rsl_rl_ppo_cfg.py new file mode 100644 index 000000000000..899ca667bd34 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/agents/rsl_rl_ppo_cfg.py @@ -0,0 +1,41 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from isaaclab.utils import configclass + +from isaaclab_rl.rsl_rl import RslRlMLPModelCfg, RslRlOnPolicyRunnerCfg, RslRlPpoAlgorithmCfg + + +@configclass +class FrankaStackPPORunnerCfg(RslRlOnPolicyRunnerCfg): + """PPO settings for the state-based Franka stack task.""" + + num_steps_per_env = 32 + max_iterations = 7000 + save_interval = 100 + experiment_name = "franka_stack" + clip_actions = 1.0 + obs_groups = {"actor": ["policy"], "critic": ["policy"]} + actor = RslRlMLPModelCfg( + hidden_dims=[256, 128, 64], + activation="elu", + obs_normalization=True, + distribution_cfg=RslRlMLPModelCfg.GaussianDistributionCfg(init_std=0.5), + ) + critic = RslRlMLPModelCfg(hidden_dims=[256, 128, 64], activation="elu", obs_normalization=True) + algorithm = RslRlPpoAlgorithmCfg( + value_loss_coef=1.0, + use_clipped_value_loss=True, + clip_param=0.2, + entropy_coef=0.005, + num_learning_epochs=5, + num_mini_batches=4, + learning_rate=1.0e-4, + schedule="adaptive", + gamma=0.99, + lam=0.95, + desired_kl=0.01, + max_grad_norm=1.0, + ) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_rl_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_rl_env_cfg.py new file mode 100644 index 000000000000..9bd6cd23848d --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_rl_env_cfg.py @@ -0,0 +1,53 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""State-based reinforcement learning in the existing Franka cube stack scene.""" + +from isaaclab.managers import ObservationGroupCfg as ObsGroup +from isaaclab.managers import ObservationTermCfg as ObsTerm +from isaaclab.managers import RewardTermCfg as RewTerm +from isaaclab.utils import configclass + +from ... import mdp +from ...mdp.rewards import stack_progress +from .stack_joint_pos_env_cfg import FrankaCubeStackEnvCfg + + +@configclass +class ObservationsCfg: + """State inputs for the actor and critic.""" + + @configclass + class PolicyCfg(ObsGroup): + """Robot joints, cube poses, and previous action.""" + + joint_pos = ObsTerm(func=mdp.joint_pos_rel) + joint_vel = ObsTerm(func=mdp.joint_vel_rel) + objects = ObsTerm(func=mdp.object_obs) + actions = ObsTerm(func=mdp.last_action) + + policy: PolicyCfg = PolicyCfg() + + +@configclass +class RewardsCfg: + """Guide both placements and reward the existing success termination.""" + + progress = RewTerm(func=stack_progress, weight=1.0) + success = RewTerm(func=mdp.is_terminated_term, params={"term_keys": "success"}, weight=1000.0) + action_rate = RewTerm(func=mdp.action_rate_l2, weight=-1.0e-4) + joint_vel = RewTerm(func=mdp.joint_vel_l2, weight=-1.0e-4) + + +@configclass +class FrankaCubeStackRLEnvCfg(FrankaCubeStackEnvCfg): + """Train the Franka to stack three cubes in the existing task order.""" + + observations: ObservationsCfg = ObservationsCfg() + rewards: RewardsCfg = RewardsCfg() + + def __post_init__(self) -> None: + super().__post_init__() + self.sim.render_interval = self.decimation diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/rewards.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/rewards.py new file mode 100644 index 000000000000..cfc1b507c96f --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/rewards.py @@ -0,0 +1,40 @@ +# 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 + +"""Rewards for ordered cube stacking.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import torch + +from .terminations import cube_pair_is_aligned + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedRLEnv + + +def stack_progress(env: ManagerBasedRLEnv) -> torch.Tensor: + """Reward reaching, lifting, and placing the next cube in the stack.""" + bottom = env.scene["cube_1"].data.root_pos_w.torch + middle = env.scene["cube_2"].data.root_pos_w.torch + top = env.scene["cube_3"].data.root_pos_w.torch + ee = env.scene["ee_frame"].data.target_pos_w.torch[:, 0] + + # Switch goals on alignment alone so closing the gripper for the next pick keeps the new goal. + success = env.termination_manager.get_term_cfg("success").params + height = success["height_diff"] + middle_placed = cube_pair_is_aligned(middle - bottom, success["xy_threshold"], height, success["height_threshold"]) + cube = torch.where(middle_placed[:, None], top, middle) + support = torch.where(middle_placed[:, None], middle, bottom) + target_error = cube - support + target_error[:, 2] -= height + + reach = 1.0 - torch.tanh(torch.linalg.vector_norm(cube - ee, dim=1) / 0.1) + # Measure lift above the bottom cube's center while it remains on the table. + lift = ((cube[:, 2] - bottom[:, 2]) / height).clamp(0.0, 1.0) + place = 1.0 - torch.tanh(torch.linalg.vector_norm(target_error, dim=1) / 0.1) + return middle_placed.float() + 0.25 * ((1.0 - lift) * reach + lift) + 0.75 * lift * place From e76e2bec30e361fcb2b4c5a2923eec6f20f1d2b9 Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Wed, 18 Nov 2026 00:07:05 +0100 Subject: [PATCH 03/28] 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 6b4a6a2e07c663489e25cf311fb4506619d86676 Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Wed, 18 Nov 2026 00:07:20 +0100 Subject: [PATCH 04/28] Document the Franka stack progress reward --- .../contrib/stack/mdp/rewards.py | 31 ++++++++++++++----- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/rewards.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/rewards.py index cfc1b507c96f..217685ba0fd8 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/rewards.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/rewards.py @@ -11,30 +11,47 @@ import torch -from .terminations import cube_pair_is_aligned +from .terminations import _cube_pair_is_aligned if TYPE_CHECKING: from isaaclab.envs import ManagerBasedRLEnv def stack_progress(env: ManagerBasedRLEnv) -> torch.Tensor: - """Reward reaching, lifting, and placing the next cube in the stack.""" + """Reward reaching, lifting, and placing the next cube in the stack. + + Compare the world-frame positions of ``cube_1``, ``cube_2``, ``cube_3``, and ``ee_frame``. + The ``success`` termination term supplies the target height and alignment tolerances. + + Args: + env: The Franka cube stacking environment. + + Returns: + One progress reward per environment, with shape ``(num_envs,)``. + """ bottom = env.scene["cube_1"].data.root_pos_w.torch middle = env.scene["cube_2"].data.root_pos_w.torch top = env.scene["cube_3"].data.root_pos_w.torch ee = env.scene["ee_frame"].data.target_pos_w.torch[:, 0] - # Switch goals on alignment alone so closing the gripper for the next pick keeps the new goal. - success = env.termination_manager.get_term_cfg("success").params - height = success["height_diff"] - middle_placed = cube_pair_is_aligned(middle - bottom, success["xy_threshold"], height, success["height_threshold"]) + # The termination manager resolves omitted defaults when it prepares the success term. + success_params = env.termination_manager.get_term_cfg("success").params + height = success_params["height_diff"] + # Use alignment alone so closing the gripper for the next pick keeps the new goal. + middle_placed = _cube_pair_is_aligned( + middle - bottom, + success_params["xy_threshold"], + height, + success_params["height_threshold"], + success_params["symmetric_height_tolerance"], + ) cube = torch.where(middle_placed[:, None], top, middle) support = torch.where(middle_placed[:, None], middle, bottom) target_error = cube - support target_error[:, 2] -= height reach = 1.0 - torch.tanh(torch.linalg.vector_norm(cube - ee, dim=1) / 0.1) - # Measure lift above the bottom cube's center while it remains on the table. + # Measure lift relative to the bottom cube's center. lift = ((cube[:, 2] - bottom[:, 2]) / height).clamp(0.0, 1.0) place = 1.0 - torch.tanh(torch.linalg.vector_norm(target_error, dim=1) / 0.1) return middle_placed.float() + 0.25 * ((1.0 - lift) * reach + lift) + 0.75 * lift * place From 611d070e70f1b789e05a2fc067b5506f22586b0f Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Wed, 18 Nov 2026 00:09:53 +0100 Subject: [PATCH 05/28] 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 06/28] 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 eef1c81eadbb639a22b6cd2e627d245fb94ea133 Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Wed, 18 Nov 2026 00:11:33 +0100 Subject: [PATCH 07/28] Scope strict stacking geometry to the new PPO task --- .../contrib/stack/config/franka/stack_rl_env_cfg.py | 1 + .../isaaclab_tasks/contrib/stack/mdp/rewards.py | 13 ++++++------- .../test/contrib/stack/test_cubes_stacked.py | 7 +++++-- 3 files changed, 12 insertions(+), 9 deletions(-) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_rl_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_rl_env_cfg.py index 9bd6cd23848d..5e4fdfd81a75 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_rl_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_rl_env_cfg.py @@ -50,4 +50,5 @@ class FrankaCubeStackRLEnvCfg(FrankaCubeStackEnvCfg): def __post_init__(self) -> None: super().__post_init__() + self.terminations.success.params["symmetric_height_tolerance"] = True self.sim.render_interval = self.decimation diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/rewards.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/rewards.py index 217685ba0fd8..1aa85e39159a 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/rewards.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/rewards.py @@ -20,8 +20,8 @@ def stack_progress(env: ManagerBasedRLEnv) -> torch.Tensor: """Reward reaching, lifting, and placing the next cube in the stack. - Compare the world-frame positions of ``cube_1``, ``cube_2``, ``cube_3``, and ``ee_frame``. - The ``success`` termination term supplies the target height and alignment tolerances. + Compare the world-frame positions of the three cubes and the ``ee_frame`` sensor. The + ``success`` termination term supplies their order, target height, and alignment tolerances. Args: env: The Franka cube stacking environment. @@ -29,13 +29,12 @@ def stack_progress(env: ManagerBasedRLEnv) -> torch.Tensor: Returns: One progress reward per environment, with shape ``(num_envs,)``. """ - bottom = env.scene["cube_1"].data.root_pos_w.torch - middle = env.scene["cube_2"].data.root_pos_w.torch - top = env.scene["cube_3"].data.root_pos_w.torch - ee = env.scene["ee_frame"].data.target_pos_w.torch[:, 0] - # The termination manager resolves omitted defaults when it prepares the success term. success_params = env.termination_manager.get_term_cfg("success").params + bottom = env.scene[success_params["cube_1_cfg"].name].data.root_pos_w.torch + middle = env.scene[success_params["cube_2_cfg"].name].data.root_pos_w.torch + top = env.scene[success_params["cube_3_cfg"].name].data.root_pos_w.torch + ee = env.scene["ee_frame"].data.target_pos_w.torch[:, 0] height = success_params["height_diff"] # Use alignment alone so closing the gripper for the next pick keeps the new goal. middle_placed = _cube_pair_is_aligned( 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..6f7806bed5ce 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_rl_env_cfg import FrankaCubeStackRLEnvCfg 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 = FrankaCubeStackRLEnvCfg() + 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 success.func(env, **success.params).tolist() == [True, False, False] assert cubes_stacked(env, cube_3_cfg=None, symmetric_height_tolerance=True).tolist() == [True, False, True] From a5e126f2b49b8a5099af8bc4bc13ab678e9c8ddb Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Wed, 18 Nov 2026 00:11:55 +0100 Subject: [PATCH 08/28] Award stacking success at the episode limit --- .../contrib/stack/config/franka/stack_rl_env_cfg.py | 4 ++-- .../isaaclab_tasks/contrib/stack/mdp/rewards.py | 5 +++++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_rl_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_rl_env_cfg.py index 5e4fdfd81a75..cc73b0ce4de1 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_rl_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_rl_env_cfg.py @@ -11,7 +11,7 @@ from isaaclab.utils import configclass from ... import mdp -from ...mdp.rewards import stack_progress +from ...mdp.rewards import stack_progress, stack_success from .stack_joint_pos_env_cfg import FrankaCubeStackEnvCfg @@ -36,7 +36,7 @@ class RewardsCfg: """Guide both placements and reward the existing success termination.""" progress = RewTerm(func=stack_progress, weight=1.0) - success = RewTerm(func=mdp.is_terminated_term, params={"term_keys": "success"}, weight=1000.0) + success = RewTerm(func=stack_success, weight=1000.0) action_rate = RewTerm(func=mdp.action_rate_l2, weight=-1.0e-4) joint_vel = RewTerm(func=mdp.joint_vel_l2, weight=-1.0e-4) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/rewards.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/rewards.py index 1aa85e39159a..87716afaeab8 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/rewards.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/rewards.py @@ -54,3 +54,8 @@ def stack_progress(env: ManagerBasedRLEnv) -> torch.Tensor: lift = ((cube[:, 2] - bottom[:, 2]) / height).clamp(0.0, 1.0) place = 1.0 - torch.tanh(torch.linalg.vector_norm(target_error, dim=1) / 0.1) return middle_placed.float() + 0.25 * ((1.0 - lift) * reach + lift) + 0.75 * lift * place + + +def stack_success(env: ManagerBasedRLEnv) -> torch.Tensor: + """Reward the per-environment success signal even when the episode limit also fires.""" + return env.termination_manager.get_term("success").float() From ced1fda5ca0d46a12c1371e49ab552cb9cd128f9 Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Wed, 18 Nov 2026 00:43:55 +0100 Subject: [PATCH 09/28] 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 d957b34fbcd6af1d1a4991835c4342a96ccc829c Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Wed, 18 Nov 2026 00:45:02 +0100 Subject: [PATCH 10/28] Restore the full Franka state stacking policy --- .../franka-stack-hidden-shapes.fixed.rst | 1 + .../isaaclab/sim/spawners/shapes/shapes.py | 10 +- source/isaaclab/test/sim/test_spawn_shapes.py | 11 + .../changelog.d/franka-stack-ppo.added.rst | 3 +- .../config/franka/agents/rsl_rl_ppo_cfg.py | 74 ++-- .../stack/config/franka/franka_robot_cfg.py | 72 ++++ .../stack/config/franka/stack_rl_env_cfg.py | 377 ++++++++++++++++-- .../contrib/stack/mdp/__init__.pyi | 46 ++- .../contrib/stack/mdp/actions.py | 121 ++++++ .../contrib/stack/mdp/actions_cfg.py | 53 +++ .../contrib/stack/mdp/goal_context.py | 184 +++++++++ .../contrib/stack/mdp/observations.py | 112 ++++++ .../contrib/stack/mdp/rewards.py | 329 +++++++++++++-- .../contrib/stack/mdp/robot_state.py | 80 ++++ .../contrib/stack/mdp/terminations.py | 76 +++- .../isaaclab_tasks/contrib/stack/spawners.py | 75 ++++ .../test/contrib/stack/test_cubes_stacked.py | 7 +- .../contrib/stack/test_franka_stack_state.py | 101 +++++ 18 files changed, 1632 insertions(+), 100 deletions(-) create mode 100644 source/isaaclab/changelog.d/franka-stack-hidden-shapes.fixed.rst create mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/franka_robot_cfg.py create mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/actions.py create mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/actions_cfg.py create mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/goal_context.py create mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/robot_state.py create mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/stack/spawners.py create mode 100644 source/isaaclab_tasks/test/contrib/stack/test_franka_stack_state.py diff --git a/source/isaaclab/changelog.d/franka-stack-hidden-shapes.fixed.rst b/source/isaaclab/changelog.d/franka-stack-hidden-shapes.fixed.rst new file mode 100644 index 000000000000..2f2670ddf878 --- /dev/null +++ b/source/isaaclab/changelog.d/franka-stack-hidden-shapes.fixed.rst @@ -0,0 +1 @@ +* Fixed procedural shape spawning so an invisible collision surface stays hidden in the scene. diff --git a/source/isaaclab/isaaclab/sim/spawners/shapes/shapes.py b/source/isaaclab/isaaclab/sim/spawners/shapes/shapes.py index e2081ec89693..7831294be80f 100644 --- a/source/isaaclab/isaaclab/sim/spawners/shapes/shapes.py +++ b/source/isaaclab/isaaclab/sim/spawners/shapes/shapes.py @@ -14,7 +14,14 @@ from isaaclab.utils import validate from ... import schemas -from ...utils import bind_physics_material, bind_visual_material, clone, create_prim, get_current_stage +from ...utils import ( + bind_physics_material, + bind_visual_material, + clone, + create_prim, + get_current_stage, + set_prim_visibility, +) from ..materials.physics_materials import spawn_physics_material from ..spawner_cfg import RigidObjectSpawnerCfg from ..utils import apply_mesh_collision_props, apply_schema_props @@ -315,6 +322,7 @@ def spawn_geom_from_prim_type( geom_prim_path = prim_path + "/geometry" mesh_prim_path = geom_prim_path + "/mesh" create_prim(mesh_prim_path, prim_type, scale=scale, attributes=attributes, stage=stage) + set_prim_visibility(stage.GetPrimAtPath(prim_path), cfg.visible) if geometry_schema_func is not None: geometry_schema_func(mesh_prim_path, stage=stage) diff --git a/source/isaaclab/test/sim/test_spawn_shapes.py b/source/isaaclab/test/sim/test_spawn_shapes.py index 7e9e2b406679..e5afd80b5468 100644 --- a/source/isaaclab/test/sim/test_spawn_shapes.py +++ b/source/isaaclab/test/sim/test_spawn_shapes.py @@ -10,6 +10,8 @@ import pytest from isaaclab_physx.sim.schemas import PhysxRigidBodyCfg +from pxr import UsdGeom + import isaaclab.sim as sim_utils from isaaclab.sim import SimulationCfg, SimulationContext @@ -98,6 +100,15 @@ def test_spawn_cuboid(sim): assert prim.GetAttribute("size").Get() == min(cfg.size) +def test_spawn_invisible_cuboid(sim): + """Test that a hidden procedural shape remains invisible to renderers.""" + cfg = sim_utils.CuboidCfg(size=(1.0, 2.0, 3.0), visible=False) + cfg.func("/World/InvisibleCube", cfg) + + prim = sim.stage.GetPrimAtPath("/World/InvisibleCube/geometry/mesh") + assert UsdGeom.Imageable(prim).ComputeVisibility() == UsdGeom.Tokens.invisible + + def test_spawn_sphere(sim): """Test spawning of UsdGeom.Sphere prim.""" cfg = sim_utils.SphereCfg(radius=1.0) diff --git a/source/isaaclab_tasks/changelog.d/franka-stack-ppo.added.rst b/source/isaaclab_tasks/changelog.d/franka-stack-ppo.added.rst index 02996c1c0774..85045831cadf 100644 --- a/source/isaaclab_tasks/changelog.d/franka-stack-ppo.added.rst +++ b/source/isaaclab_tasks/changelog.d/franka-stack-ppo.added.rst @@ -1 +1,2 @@ -* Added a state-based Franka cube stacking task with an RSL-RL PPO configuration. +* Added Franka state-policy cube stacking on Newton MJWarp with RSL-RL PPO, bounded relative arm control, + and a stable released-stack objective. Preserved the published state policy's observation order. diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/agents/rsl_rl_ppo_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/agents/rsl_rl_ppo_cfg.py index 899ca667bd34..a348f83c5e77 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/agents/rsl_rl_ppo_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/agents/rsl_rl_ppo_cfg.py @@ -3,39 +3,65 @@ # # SPDX-License-Identifier: BSD-3-Clause +"""RSL-RL configurations for state-based Franka stacking.""" + from isaaclab.utils import configclass -from isaaclab_rl.rsl_rl import RslRlMLPModelCfg, RslRlOnPolicyRunnerCfg, RslRlPpoAlgorithmCfg +from isaaclab_rl.rsl_rl import ( + RslRlMLPModelCfg, + RslRlOnPolicyRunnerCfg, + RslRlPpoAlgorithmCfg, +) + +STATE_EXPLORATION_CFG = RslRlMLPModelCfg.GaussianDistributionCfg( + init_std=0.2, + std_range=(0.05, 0.3), + std_type="scalar", +) + +STATE_POLICY_CFG = RslRlMLPModelCfg( + hidden_dims=[512, 256, 128], + activation="elu", + obs_normalization=True, + distribution_cfg=STATE_EXPLORATION_CFG, +) + +STATE_CRITIC_CFG = RslRlMLPModelCfg( + hidden_dims=[512, 256, 128], + activation="elu", + obs_normalization=True, +) + +ALGORITHM_CFG = RslRlPpoAlgorithmCfg( + value_loss_coef=1.0, + use_clipped_value_loss=True, + clip_param=0.2, + entropy_coef=0.001, + num_learning_epochs=5, + num_mini_batches=16, + learning_rate=1.0e-4, + schedule="fixed", + # At 50 Hz, the full two-pick sequence needs a longer effective horizon + # than the manipulation-task default. + gamma=0.999, + lam=0.95, + desired_kl=0.01, + max_grad_norm=1.0, +) @configclass class FrankaStackPPORunnerCfg(RslRlOnPolicyRunnerCfg): - """PPO settings for the state-based Franka stack task.""" + """PPO configuration for order-invariant three-cube Franka stacking.""" num_steps_per_env = 32 + # Reset-table curricula need a complete first outcome for every row. + init_at_random_ep_len = False max_iterations = 7000 - save_interval = 100 + save_interval = 25 experiment_name = "franka_stack" clip_actions = 1.0 obs_groups = {"actor": ["policy"], "critic": ["policy"]} - actor = RslRlMLPModelCfg( - hidden_dims=[256, 128, 64], - activation="elu", - obs_normalization=True, - distribution_cfg=RslRlMLPModelCfg.GaussianDistributionCfg(init_std=0.5), - ) - critic = RslRlMLPModelCfg(hidden_dims=[256, 128, 64], activation="elu", obs_normalization=True) - algorithm = RslRlPpoAlgorithmCfg( - value_loss_coef=1.0, - use_clipped_value_loss=True, - clip_param=0.2, - entropy_coef=0.005, - num_learning_epochs=5, - num_mini_batches=4, - learning_rate=1.0e-4, - schedule="adaptive", - gamma=0.99, - lam=0.95, - desired_kl=0.01, - max_grad_norm=1.0, - ) + actor = STATE_POLICY_CFG + critic = STATE_CRITIC_CFG + algorithm = ALGORITHM_CFG diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/franka_robot_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/franka_robot_cfg.py new file mode 100644 index 000000000000..216325984c9c --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/franka_robot_cfg.py @@ -0,0 +1,72 @@ +# 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 + +"""Task-specific Franka configuration for cube stacking.""" + +from isaaclab.actuators import ImplicitActuatorCfg +from isaaclab.assets import ArticulationCfg +from isaaclab.utils import clone + +from isaaclab_assets.robots.franka import FRANKA_PANDA_CFG + +FRANKA_PANDA_DEXSUITE_CFG = clone(FRANKA_PANDA_CFG) +FRANKA_PANDA_DEXSUITE_CFG.spawn.variants["Physics"] = "mujoco" +FRANKA_PANDA_DEXSUITE_CFG.init_state = ArticulationCfg.InitialStateCfg( + joint_pos={ + "panda_joint1": 0.0444, + "panda_joint2": -0.1894, + "panda_joint3": -0.1107, + "panda_joint4": -2.5148, + "panda_joint5": 0.0044, + "panda_joint6": 2.3775, + "panda_joint7": 0.6952, + "panda_finger_joint.*": 0.04, + }, +) +# Keep the shared asset's passive mimic follower; tune only the active drives. +FRANKA_PANDA_DEXSUITE_CFG.actuators.update( + { + "panda_arm": ImplicitActuatorCfg( + joint_names_expr=["panda_joint[1-7]"], + joint_effort_limit={"panda_joint[1-4]": 87.0, "panda_joint[5-7]": 12.0}, + # Record the Panda's rated joint-speed envelope. MJWarp exposes but + # does not enforce these fields; action scaling, gains, effort limits, + # and armature determine the live Newton response. + joint_velocity_limit={"panda_joint[1-4]": 2.175, "panda_joint[5-7]": 2.61}, + stiffness={ + "panda_joint[1-4]": 600.0, + "panda_joint5": 250.0, + "panda_joint6": 150.0, + "panda_joint7": 50.0, + }, + damping={ + "panda_joint[1-4]": 50.0, + "panda_joint5": 30.0, + "panda_joint6": 25.0, + "panda_joint7": 15.0, + }, + armature={ + "panda_joint[1-2]": 0.6057, + "panda_joint[3-4]": 0.4625, + "panda_joint[5-7]": 0.2055, + }, + viscous_friction=0.0, + ), + "panda_hand": ImplicitActuatorCfg( + joint_names_expr=["panda_finger_joint1"], + joint_effort_limit=70.0, + joint_velocity_limit=2.0, + stiffness=350.0, + damping=175.0, + armature=0.1, + viscous_friction=0.0, + ), + } +) +"""DexSuite-calibrated Franka with physical gravity enabled. + +The arm controller combines these joint-impedance gains with configuration- +dependent gravity feedforward in the stack task's action term. +""" diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_rl_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_rl_env_cfg.py index cc73b0ce4de1..dd8a1174757d 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_rl_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_rl_env_cfg.py @@ -3,52 +3,383 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""State-based reinforcement learning in the existing Franka cube stack scene.""" +"""Reinforcement-learning configuration for Franka cube stacking.""" +import math + +from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg, NewtonCollisionPipelineCfg, NewtonShapeCfg +from isaaclab_newton.sim.schemas import NewtonMaterialPropertiesCfg + +import isaaclab.sim as sim_utils +from isaaclab.assets import AssetBaseCfg +from isaaclab.managers import CurriculumTermCfg as CurrTerm +from isaaclab.managers import EventTermCfg as EventTerm from isaaclab.managers import ObservationGroupCfg as ObsGroup from isaaclab.managers import ObservationTermCfg as ObsTerm from isaaclab.managers import RewardTermCfg as RewTerm -from isaaclab.utils import configclass +from isaaclab.managers import SceneEntityCfg +from isaaclab.managers import TerminationTermCfg as DoneTerm +from isaaclab.sim.schemas import UsdPhysicsCollisionCfg, UsdPhysicsRigidBodyCfg +from isaaclab.utils.configclass import configclass +from isaaclab.visualizers import VisualizerCfg + +from isaaclab_tasks.utils import SuccessMonitorCfg, preset from ... import mdp -from ...mdp.rewards import stack_progress, stack_success -from .stack_joint_pos_env_cfg import FrankaCubeStackEnvCfg +from ...constants import FRANKA_STACK_ARM_WORKSPACE_LOWER, FRANKA_STACK_ARM_WORKSPACE_UPPER +from ...spawners import ColoredCuboidCfg +from ...stack_env_cfg import StackEnvCfg, apply_default_semantics +from .franka_robot_cfg import FRANKA_PANDA_DEXSUITE_CFG + + +@configclass +class EventCfg: + """Reset from a shared cache of validated full-task stack states.""" + + # Restore the authored robot root state before applying sampled joints and cubes. + reset_all = EventTerm(func=mdp.reset_scene_to_default, mode="reset") + + reset_from_state_buffer = EventTerm( + func=mdp.StackResetStateTable, + mode="reset", + params={ + "closed_finger_position": 0.020, + "placed_finger_position": 0.021, + "open_finger_position": 0.04, + # Eighteen balanced workspace/source-order layouts each receive 64 + # independently scattered table starts. This yields 1,152 broad + # table starts without making the table family dominate. + "table_rows_per_layout": 64, + # Cached intermediate states are authored hand-object contacts and + # must remain exact. Table starts receive broad + # robot variation and coherent planar cube transforms instead. + "arm_joint_noise_range": 0.0, + "table_arm_joint_noise_range": 0.080, + "table_cube_planar_translation_range": 0.015, + "table_cube_rotation_range": 0.45, + "fixed_recipe": None, + "fixed_role_permutation": None, + }, + ) @configclass -class ObservationsCfg: - """State inputs for the actor and critic.""" +class FrankaStackStateObservationCfg(ObsGroup): + """Canonical full-state interface for the Franka stack policy.""" + + # The published state actors were trained with action history first. + actions = ObsTerm(func=mdp.last_action) + joint_pos = ObsTerm( + func=mdp.joint_pos_rel, + params={"asset_cfg": SceneEntityCfg("robot", joint_names=["panda_joint.*"])}, + ) + joint_vel = ObsTerm( + func=mdp.joint_vel_rel, + params={"asset_cfg": SceneEntityCfg("robot", joint_names=["panda_joint.*"])}, + ) + object = ObsTerm(func=mdp.role_conditioned_stack_obs) + gripper_pos = ObsTerm(func=mdp.gripper_pos) + eef_velocity = ObsTerm(func=mdp.franka_ee_velocity) + eef_axes = ObsTerm(func=mdp.franka_ee_axes) - @configclass - class PolicyCfg(ObsGroup): - """Robot joints, cube poses, and previous action.""" + def __post_init__(self) -> None: + self.enable_corruption = False + self.concatenate_terms = True - joint_pos = ObsTerm(func=mdp.joint_pos_rel) - joint_vel = ObsTerm(func=mdp.joint_vel_rel) - objects = ObsTerm(func=mdp.object_obs) - actions = ObsTerm(func=mdp.last_action) - policy: PolicyCfg = PolicyCfg() +@configclass +class FrankaStackObservationsCfg: + """Observation groups for state-based Franka stacking.""" + + policy: FrankaStackStateObservationCfg = FrankaStackStateObservationCfg() @configclass class RewardsCfg: - """Guide both placements and reward the existing success termination.""" + """Sparse terminal objective plus safety regularizers.""" - progress = RewTerm(func=stack_progress, weight=1.0) - success = RewTerm(func=stack_success, weight=1000.0) + success = RewTerm( + func=mdp.stack_success_pulse, + params={"context_term_name": "progress_context"}, + # The reward function cancels RewardManager's step_dt integration, so + # this is an exact +2 episode impulse at any policy frequency. + weight=2.0, + ) + failure = RewTerm( + func=mdp.irrecoverable_stack_failure, + params={"success_termination_name": "success"}, + # Preserve the established -0.0002 terminal impulse independently of + # the policy timestep. + weight=-2.0e-4, + ) + action_l2 = RewTerm(func=mdp.action_term_l2, params={"action_name": "arm_action"}, weight=-1.0e-4) action_rate = RewTerm(func=mdp.action_rate_l2, weight=-1.0e-4) - joint_vel = RewTerm(func=mdp.joint_vel_l2, weight=-1.0e-4) + joint_vel = RewTerm( + func=mdp.finite_joint_velocity_l2, + params={ + "asset_cfg": SceneEntityCfg("robot", joint_names=["panda_joint.*"]), + "maximum_velocity": 3.0, + }, + weight=-1.0e-4, + ) @configclass -class FrankaCubeStackRLEnvCfg(FrankaCubeStackEnvCfg): - """Train the Franka to stack three cubes in the existing task order.""" +class CurriculumCfg: + """Guaranteed table starts plus target-rate intermediate states.""" + + reset_sampling = CurrTerm( + func=mdp.StackResetTableCurriculum, + params={ + "success_context_name": "learning_progress_context", + "final_success_context_name": "progress_context", + # Use the same shared rolling-success monitor as Lift and the + # conveyor task. Its target-rate weights concentrate sampling near + # 50% competence while retaining a floor at both extremes. + "success_monitor": SuccessMonitorCfg( + monitored_history_len=50, + target_success_rate=0.50, + kappa=1.0, + temperature=1.0, + ), + # Preserve a table-start learning stream regardless of the + # adaptive intermediate-state distribution. The remaining 65% is + # sampled from non-table rows by the rolling-success kernel. + "table_sampling_probability": 0.35, + }, + ) + - observations: ObservationsCfg = ObservationsCfg() +@configclass +class FrankaCubeStackRLEnvCfg(StackEnvCfg): + """Train a color-order-invariant three-cube stack from physical reset rows.""" + + observations: FrankaStackObservationsCfg = FrankaStackObservationsCfg() rewards: RewardsCfg = RewardsCfg() + events: EventCfg = EventCfg() + curriculum: CurriculumCfg = CurriculumCfg() def __post_init__(self) -> None: super().__post_init__() - self.terminations.success.params["symmetric_height_tolerance"] = True - self.sim.render_interval = self.decimation + + self.scene.robot = FRANKA_PANDA_DEXSUITE_CFG.replace( + prim_path="{ENV_REGEX_NS}/Robot", + ) + apply_default_semantics(self.scene) + self.gripper_joint_names = ["panda_finger_.*"] + self.gripper_open_val = 0.04 + self.gripper_threshold = 0.005 + # Newton needs a fixed rigid root to discover the Seattle table's + # separately instanced visual and collision subtrees. Keep this + # backend-specific override local to the RL task. + self.scene.table.spawn.rigid_props = UsdPhysicsRigidBodyCfg(kinematic_enabled=True) + # The Seattle table's authored collision top is 3 mm below its visible + # tabletop. Add an invisible native contact surface at visual z=0 so + # cubes rest on what the policy and viewer see. The original collider + # remains below as a fallback for the rest of the table geometry. + self.scene.table_contact_surface = AssetBaseCfg( + prim_path="{ENV_REGEX_NS}/TableContactSurface", + init_state=AssetBaseCfg.InitialStateCfg(pos=(0.3439, 0.0, -0.02)), + spawn=sim_utils.CuboidCfg( + size=(1.28, 0.91, 0.04), + visible=False, + rigid_props=UsdPhysicsRigidBodyCfg(kinematic_enabled=True), + collision_props=UsdPhysicsCollisionCfg(collision_enabled=True), + physics_material=NewtonMaterialPropertiesCfg( + static_friction=1.0, + dynamic_friction=0.8, + restitution=0.0, + torsional_friction=0.002, + rolling_friction=0.0001, + contact_stiffness=1.0e4, + contact_damping=200.0, + ), + ), + ) + self.sim.gravity = (0.0, 0.0, -9.81) + self.scene.robot.spawn.rigid_props.disable_gravity = False + + # Use MJWarp only as the rigid-body constraint solver. Contact + # generation is delegated to Newton's external collision pipeline. + # The Franka plus three cubes reached 148 constraint rows in + # the 4,096-environment reset distribution. Keep measured headroom so + # contacts are never silently truncated while avoiding an oversized + # contact buffer. + physics = NewtonCfg( + solver_cfg=MJWarpSolverCfg( + solver="newton", + integrator="implicitfast", + njmax=256, + nconmax=100, + impratio=10.0, + cone="elliptic", + use_mujoco_contacts=False, + ), + # Match the fast, stable Newton Cube Lift integration cadence: + # two 5 ms solver steps per 10 ms physics tick. Ten 1 ms substeps + # were stable but made collection roughly eight times slower. + num_substeps=2, + # Refresh external contacts for every 5 ms solver step. Reusing + # one contact set for the full 10 ms tick is sufficient for Lift, + # but lets a released three-cube tower drift or tip. + collision_decimation=1, + use_cuda_graph=True, + collision_cfg=NewtonCollisionPipelineCfg( + broad_phase="explicit", + reduce_contacts=True, + ), + # Preserve the authored 4 cm cube and finger surfaces. A positive + # gap creates speculative contacts before those surfaces touch; + # fresh 5 ms collision queries make that unnecessary here. + default_shape_cfg=NewtonShapeCfg(margin=0.0, gap=0.0), + ) + self.sim.physics = preset(default=physics, newton_mjwarp=physics) + self.scene.replicate_physics = True + # Match Cube Lift's 50 Hz policy rate: two 100 Hz physics ticks for + # every relative joint-position command. + self.decimation = 2 + self.sim.render_interval = 2 + + # Keep the standard Franka Lift joint-position interface, but express + # each command as a residual around the measured reset pose. The reset + # table contains valid grasps and near-placement states; a zero-mean + # absolute target immediately destroys those states, whereas a zero + # residual holds them. The larger scale restores enough joint-space + # authority to acquire cubes from table starts. + self.actions.arm_action = mdp.WorkspaceBoundedRelativeJointPositionActionCfg( + asset_name="robot", + joint_names=["panda_joint.*"], + # At 50 Hz, a 0.05 rad measured-state residual caps the commanded + # target slew at 2.5 rad/s. MJWarp does not hard-enforce actuator + # velocity-limit fields. + scale=0.05, + max_delta=0.05, + workspace_lower=FRANKA_STACK_ARM_WORKSPACE_LOWER, + workspace_upper=FRANKA_STACK_ARM_WORKSPACE_UPPER, + gravity_compensation=True, + ) + self.actions.gripper_action = mdp.ResetBufferedGripperActionCfg( + asset_name="robot", + joint_names=["panda_finger_joint1"], + open_command_expr={"panda_finger_.*": 0.04}, + close_command_expr={"panda_finger_.*": 0.0}, + # Give Newton 100 ms to establish reset-authored finger contacts. + # Supported place endpoints are tagged as released, so this guard + # cannot crush a cube that already rests on the stack. + force_close_steps=5, + ) + + # Side-by-side table rows must have time for two picks, two placements, + # and release. Near-goal rows still terminate early on success. + self.episode_length_s = 20.0 + + # Keep cube identity stable through an episode. The reset table maps + # stack roles over all six physical cube permutations, providing order + # invariance as data augmentation without dynamically re-sorting input + # slots at the critical grasp-to-lift transition. + arm_cfg = SceneEntityCfg("robot", joint_names=["panda_joint.*"]) + self.scene.ee_frame = None + + # Provide one backend-neutral camera hint. The selected Kit or Newton + # visualizer receives these values at runtime. + self.sim.default_visualizer_cfg = VisualizerCfg( + eye=(1.4, 1.4, 0.9), + lookat=(0.5, 0.0, 0.1), + ) + + # Native cuboids avoid asset-specific block materials. Their standard geometry + # owns both collision and rendering; a USD displayColor keeps the + # colors available in both Kit and kitless Newton visualization. + cube_colors = ((0.05, 0.15, 0.80), (0.80, 0.05, 0.05), (0.05, 0.65, 0.10)) + for cube, color in zip((self.scene.cube_1, self.scene.cube_2, self.scene.cube_3), cube_colors, strict=True): + semantic_tags = cube.spawn.semantic_tags + cube.spawn = ColoredCuboidCfg( + size=(0.04, 0.04, 0.04), + display_color=color, + rigid_props=UsdPhysicsRigidBodyCfg(), + collision_props=UsdPhysicsCollisionCfg(collision_enabled=True), + mass_props=sim_utils.MassCfg(mass=0.05), + physics_material=NewtonMaterialPropertiesCfg( + static_friction=1.0, + dynamic_friction=0.8, + restitution=0.0, + torsional_friction=0.002, + rolling_friction=0.0001, + # Reduce visible resting overlap in a three-cube tower. + # Newton's 2.5 kN/m fallback shortens the 12 cm tower by + # roughly 0.9 mm; these gains reduce that to about 0.25 mm. + contact_stiffness=1.0e4, + contact_damping=200.0, + ), + semantic_tags=semantic_tags, + ) + + self.terminations.progress_context = DoneTerm( + func=mdp.StableOrderInvariantStackGoal, + params={ + "minimum_episode_steps": 3, + "hold_steps": 5, + "maximum_cube_velocity": 0.10, + "minimum_finger_release_position": 0.023, + }, + ) + self.terminations.learning_progress_context = DoneTerm( + func=mdp.StackResetLearningProgress, + params={"minimum_episode_steps": 3}, + ) + self.terminations.success = DoneTerm( + func=mdp.success_after_minimum_horizon, + params={ + "context_term_name": "progress_context", + # The context already requires five consecutive stable, + # released-stack frames. Terminate on that physical hold + # instead of leaving a solved scene alive for five seconds, + # which invites post-success oscillation and reward cycling. + "minimum_episode_length_s": 0.1, + }, + ) + self.terminations.time_out = DoneTerm( + func=mdp.time_out, + time_out=True, + ) + self.terminations.nonfinite_robot_state = DoneTerm( + func=mdp.nonfinite_robot_state, + params={"robot_cfg": arm_cfg}, + ) + self.terminations.nonfinite_cube_state = DoneTerm(func=mdp.nonfinite_cube_state) + self.terminations.cube_workspace_invalid = DoneTerm( + func=mdp.cube_out_of_workspace, + ) + + def validate_config(self) -> None: + """Validate task-specific constraints beyond the shared configuration checks.""" + physics = self.sim.physics + if not isinstance(physics, NewtonCfg) or not isinstance(physics.solver_cfg, MJWarpSolverCfg): + raise TypeError("Stack RL tasks require Newton MJWarp.") + if physics.solver_cfg.use_mujoco_contacts or physics.collision_decimation > physics.num_substeps: + raise ValueError("Stacking requires external contacts refreshed at least once per physics tick.") + + arm = self.actions.arm_action + if not 0.0 < arm.scale <= arm.max_delta: + raise ValueError("Relative-action scale must be positive and cannot exceed max_delta.") + if len(arm.workspace_lower) != len(arm.workspace_upper) or not arm.workspace_lower: + raise ValueError("Arm workspace bounds must have equal, non-zero lengths.") + if any( + not math.isfinite(lower) + or not math.isfinite(upper) + or lower + arm.joint_limit_margin >= upper - arm.joint_limit_margin + for lower, upper in zip(arm.workspace_lower, arm.workspace_upper, strict=True) + ): + raise ValueError("Arm workspace bounds must be finite and wider than twice the joint-limit margin.") + + def play_mode(self) -> None: + """Configure randomized table starts for policy evaluation.""" + super().play_mode() + self.scene.env_spacing = 2.5 + self.episode_length_s = 30.0 + # Sample only from the randomized table partition. Avoid a brittle + # numeric row ID so evaluation follows cache-size changes. + self.events.reset_from_state_buffer.params["fixed_recipe"] = int(mdp.StackResetRecipe.TABLE) + if isinstance(self.actions.gripper_action, mdp.ResetBufferedGripperActionCfg): + self.actions.gripper_action.force_close_steps = 0 + self.curriculum = None diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/__init__.pyi b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/__init__.pyi index c7184d285121..42a353b48f16 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/__init__.pyi +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/__init__.pyi @@ -4,23 +4,47 @@ # SPDX-License-Identifier: BSD-3-Clause __all__ = [ + "ResetBufferedGripperActionCfg", + "StableOrderInvariantStackGoal", + "StackResetLearningProgress", + "StackResetRecipe", + "StackResetStateTable", + "StackResetTableCurriculum", + "WorkspaceBoundedRelativeJointPositionActionCfg", + "action_term_l2", "cube_orientations_in_world_frame", + "cube_out_of_workspace", "cube_poses_in_base_frame", "cube_positions_in_world_frame", + "cubes_stacked", "ee_frame_pos", "ee_frame_pose_in_base_frame", "ee_frame_quat", + "finite_joint_velocity_l2", + "franka_ee_axes", + "franka_ee_velocity", "gripper_pos", "instance_randomize_cube_orientations_in_world_frame", "instance_randomize_cube_positions_in_world_frame", "instance_randomize_object_obs", + "irrecoverable_stack_failure", + "nonfinite_cube_state", + "nonfinite_robot_state", "object_abs_obs_in_base_frame", "object_grasped", "object_obs", "object_stacked", - "cubes_stacked", + "order_invariant_stack_progress", + "role_conditioned_stack_obs", + "stack_success_pulse", + "success_after_minimum_horizon", ] +from isaaclab.envs.mdp import * # noqa: F403 + +from .actions_cfg import ResetBufferedGripperActionCfg, WorkspaceBoundedRelativeJointPositionActionCfg +from .curriculums import StackResetTableCurriculum +from .goal_context import StableOrderInvariantStackGoal, StackResetLearningProgress from .observations import ( cube_orientations_in_world_frame, cube_poses_in_base_frame, @@ -28,6 +52,8 @@ from .observations import ( ee_frame_pos, ee_frame_pose_in_base_frame, ee_frame_quat, + franka_ee_axes, + franka_ee_velocity, gripper_pos, instance_randomize_cube_orientations_in_world_frame, instance_randomize_cube_positions_in_world_frame, @@ -36,6 +62,20 @@ from .observations import ( object_grasped, object_obs, object_stacked, + role_conditioned_stack_obs, +) +from .reset_events import StackResetRecipe, StackResetStateTable +from .rewards import ( + action_term_l2, + finite_joint_velocity_l2, + irrecoverable_stack_failure, + order_invariant_stack_progress, + stack_success_pulse, +) +from .terminations import ( + cube_out_of_workspace, + cubes_stacked, + nonfinite_cube_state, + nonfinite_robot_state, + success_after_minimum_horizon, ) -from .terminations import cubes_stacked -from isaaclab.envs.mdp import * diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/actions.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/actions.py new file mode 100644 index 000000000000..b20cd898e7ec --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/actions.py @@ -0,0 +1,121 @@ +# 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 + +"""Task-specific actions for reset-table cube stacking.""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import TYPE_CHECKING + +import torch + +from isaaclab.envs.mdp.actions.binary_joint_actions import BinaryJointPositionAction +from isaaclab.envs.mdp.actions.joint_actions import JointAction + +from .runtime_state import get_stack_reset_runtime_state + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedEnv + + from .actions_cfg import ( + ResetBufferedGripperActionCfg, + WorkspaceBoundedRelativeJointPositionActionCfg, + ) + + +class ResetBufferedGripperAction(BinaryJointPositionAction): + """Keep reset-supplied grasps closed only while the reset state settles. + + Newton Cube Lift keeps the physical gripper closed throughout the + reset-assisted grasp portion of its curriculum. Stacking can use that + protection only during the reset grace period: continuing to mask an open + policy command through transport would credit an action that drops the + cube in an uninterrupted table-start episode. Raw actions remain visible + to the termination manager, and after the grace period the policy owns the + physical gripper completely. + """ + + cfg: ResetBufferedGripperActionCfg + + def process_actions(self, actions: torch.Tensor) -> None: + """Map binary policy actions and protect reset-assisted acquisition.""" + super().process_actions(actions) + if self.cfg.force_close_steps == 0: + return + held_cube_ids = get_stack_reset_runtime_state(self._env).held_cube_ids + force_close = (held_cube_ids >= 0) & (self._env.episode_length_buf < self.cfg.force_close_steps) + self._processed_actions[force_close] = self._close_command + + +class WorkspaceBoundedRelativeJointPositionAction(JointAction): + """Map policy joint deltas to gravity-compensated, bounded position targets. + + Each policy output directly controls the corresponding arm joint. A scaled + delta is added to the measured joint position exactly once + per policy step, then the resulting target is held through every physics + substep. This preserves standard relative-joint semantics without applying + the same delta repeatedly during simulation decimation. Targets are also + clamped to both the robot's soft limits and the reset-buffer workspace. + Model-based gravity effort can be added alongside the impedance target. + """ + + cfg: WorkspaceBoundedRelativeJointPositionActionCfg + + def __init__(self, cfg: WorkspaceBoundedRelativeJointPositionActionCfg, env: ManagerBasedEnv) -> None: + super().__init__(cfg, env) + # Use int64 indices for PyTorch reads and keep the backend indices for commands. + self._torch_joint_ids = self._joint_ids.long() if isinstance(self._joint_ids, torch.Tensor) else self._joint_ids + self._processed_actions.copy_(self._asset.data.joint_pos.torch[:, self._torch_joint_ids]) + self._gravity_joint_ids = ( + [joint_id + self._asset.num_base_dofs for joint_id in range(self._asset.num_joints)] + if isinstance(self._torch_joint_ids, slice) + else self._torch_joint_ids + self._asset.num_base_dofs + ) + self._workspace_lower = torch.tensor(cfg.workspace_lower, device=self.device, dtype=torch.float32) + self._workspace_upper = torch.tensor(cfg.workspace_upper, device=self.device, dtype=torch.float32) + if self._workspace_lower.shape != (self.action_dim,) or self._workspace_upper.shape != (self.action_dim,): + raise ValueError( + "workspace_lower and workspace_upper must each contain one value " + f"per controlled joint ({self.action_dim})." + ) + if torch.any(self._workspace_lower >= self._workspace_upper): + raise ValueError("Every workspace_lower value must be less than workspace_upper.") + + def process_actions(self, actions: torch.Tensor) -> None: + """Create one bounded position target from the measured joint pose.""" + super().process_actions(actions) + target_delta = torch.clamp( + self._processed_actions, + min=-self.cfg.max_delta, + max=self.cfg.max_delta, + ) + current_position = self._asset.data.joint_pos.torch[:, self._torch_joint_ids] + limits = self._asset.data.soft_joint_pos_limits.torch[:, self._torch_joint_ids] + lower = torch.maximum( + limits[..., 0] + self.cfg.joint_limit_margin, + self._workspace_lower, + ) + upper = torch.minimum( + limits[..., 1] - self.cfg.joint_limit_margin, + self._workspace_upper, + ) + self._processed_actions[:] = torch.clamp(current_position + target_delta, min=lower, max=upper) + + def apply_actions(self) -> None: + """Apply the fixed target and gravity feedforward during every physics substep.""" + command = self._asset.actuators.target_command + command.set_position_index(value=self.processed_actions, joint_ids=self._joint_ids) + if self.cfg.gravity_compensation: + gravity = self._asset.data.gravity_compensation_forces.torch[:, self._gravity_joint_ids] + gravity = torch.where(torch.isfinite(gravity), gravity, torch.zeros_like(gravity)) + command.set_effort_index(value=gravity, joint_ids=self._joint_ids) + + def reset(self, env_ids: Sequence[int] | None = None) -> None: + """Initialize the held target from each sampled reset pose.""" + super().reset(env_ids) + current_position = self._asset.data.joint_pos.torch[:, self._torch_joint_ids] + selection = slice(None) if env_ids is None else env_ids + self._processed_actions[selection] = current_position[selection] diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/actions_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/actions_cfg.py new file mode 100644 index 000000000000..dc4d71a0bf99 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/actions_cfg.py @@ -0,0 +1,53 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Configuration classes for task-specific cube-stacking actions.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from isaaclab.envs.mdp.actions.actions_cfg import BinaryJointPositionActionCfg, JointActionCfg +from isaaclab.utils.configclass import configclass + +if TYPE_CHECKING: + from .actions import ( + ResetBufferedGripperAction, + WorkspaceBoundedRelativeJointPositionAction, + ) + + +@configclass +class ResetBufferedGripperActionCfg(BinaryJointPositionActionCfg): + """Configuration for :class:`ResetBufferedGripperAction`.""" + + class_type: type[ResetBufferedGripperAction] | str = "{DIR}.actions:ResetBufferedGripperAction" + + force_close_steps: int = 5 + """Number of initial policy steps for which a reset-supplied grasp is protected.""" + + +@configclass +class WorkspaceBoundedRelativeJointPositionActionCfg(JointActionCfg): + """Configuration for bounded, gravity-compensated relative joint control.""" + + class_type: type[WorkspaceBoundedRelativeJointPositionAction] | str = ( + "{DIR}.actions:WorkspaceBoundedRelativeJointPositionAction" + ) + + joint_limit_margin: float = 0.02 + """Distance kept from each soft joint-position limit [rad].""" + + max_delta: float = 0.10 + """Maximum position-target change from one policy step [rad].""" + + workspace_lower: tuple[float, ...] = (-2.0,) * 7 + """Lower joint-space boundary of the task manipulation workspace [rad].""" + + workspace_upper: tuple[float, ...] = (2.0,) * 7 + """Upper joint-space boundary of the task manipulation workspace [rad].""" + + gravity_compensation: bool = False + """Whether to add model-based gravity feedforward to the controlled joints.""" diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/goal_context.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/goal_context.py new file mode 100644 index 000000000000..906e1005c147 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/goal_context.py @@ -0,0 +1,184 @@ +# 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 + +"""Stateful success contexts shared by stack rewards, curricula, and terminations.""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import TYPE_CHECKING + +import torch + +from isaaclab.managers import ManagerTermBase, SceneEntityCfg, TerminationTermCfg + +from .rewards import ( + _gripper_joint_positions, + _order_invariant_cube_state, + order_invariant_stack_progress, + role_conditioned_stack_potential, +) +from .runtime_state import get_stack_reset_runtime_state + +if TYPE_CHECKING: + from isaaclab.assets import Articulation + from isaaclab.envs import ManagerBasedRLEnv + + +class _StackSuccessContext(ManagerTermBase): + """Own common current/new/episode success state for context terms.""" + + def __init__(self, cfg: TerminationTermCfg, env: ManagerBasedRLEnv): + super().__init__(cfg, env) + self.is_success = torch.zeros(env.num_envs, dtype=torch.bool, device=env.device) + self.new_success = torch.zeros_like(self.is_success) + self.ever_success = torch.zeros_like(self.is_success) + self._no_termination = torch.zeros_like(self.is_success) + + def reset(self, env_ids: Sequence[int] | None = None) -> None: + """Clear success state for reset environments.""" + if env_ids is None: + env_ids = slice(None) + self.is_success[env_ids] = False + self.new_success[env_ids] = False + self.ever_success[env_ids] = False + + def _update_success(self, reached: torch.Tensor) -> None: + """Update current, edge-triggered, and sticky success buffers.""" + self.is_success.copy_(reached) + self.new_success.copy_(self.is_success & ~self.ever_success) + self.ever_success |= self.is_success + + +class StableOrderInvariantStackGoal(_StackSuccessContext): + """Track stable full-stack success without immediately resetting the scene. + + This non-terminating context exposes current, newly reached, and + episode-ever success tensors to the reward, reset curriculum, and + delayed-success termination terms. Returning all false prevents near-goal + reset rows from producing three-step episodes. + """ + + def __init__(self, cfg: TerminationTermCfg, env: ManagerBasedRLEnv): + super().__init__(cfg, env) + self._stable_steps = torch.zeros(env.num_envs, dtype=torch.long, device=env.device) + + def reset(self, env_ids: Sequence[int] | None = None) -> None: + """Clear the stability dwell counter for reset environments.""" + if env_ids is None: + env_ids = slice(None) + super().reset(env_ids) + self._stable_steps[env_ids] = 0 + + def __call__( + self, + env: ManagerBasedRLEnv, + minimum_episode_steps: int = 3, + hold_steps: int = 5, + maximum_cube_velocity: float = 0.15, + minimum_finger_release_position: float = 0.023, + xy_threshold: float = 0.025, + height_threshold: float = 0.012, + cube_height: float = 0.04, + ) -> torch.Tensor: + """Update full-task success state and return a non-terminating mask.""" + if ( + minimum_episode_steps < 0 + or hold_steps < 1 + or maximum_cube_velocity <= 0.0 + or minimum_finger_release_position < 0.0 + or xy_threshold <= 0.0 + or height_threshold <= 0.0 + or cube_height <= 0.0 + ): + raise ValueError("Invalid stable stack-goal thresholds.") + stack_progress = order_invariant_stack_progress( + env, + xy_threshold=xy_threshold, + height_threshold=height_threshold, + cube_height=cube_height, + ) + _, velocities = _order_invariant_cube_state( + env, + ( + SceneEntityCfg("cube_1"), + SceneEntityCfg("cube_2"), + SceneEntityCfg("cube_3"), + ), + ) + slow = torch.amax(torch.abs(velocities[..., :3]), dim=(1, 2)) < maximum_cube_velocity + robot: Articulation = env.scene["robot"] + released = (_gripper_joint_positions(env, robot) > minimum_finger_release_position).all(dim=1) + stable = (stack_progress >= 2.0) & slow & released & (env.episode_length_buf >= minimum_episode_steps) + self._stable_steps = torch.where(stable, self._stable_steps + 1, torch.zeros_like(self._stable_steps)) + self._update_success(self._stable_steps >= hold_steps) + env.extras["successes"] = self.ever_success + return self._no_termination + + +class StackResetLearningProgress(_StackSuccessContext): + """Track meaningful forward progress from every sampled reset row. + + This is curriculum evidence only: it never terminates an episode. Every + rollout remains free to continue toward the strict released full-stack + goal, while early table/pick rows can still become competent before the + complete multi-pick sequence is learned. + """ + + def __init__(self, cfg: TerminationTermCfg, env: ManagerBasedRLEnv): + super().__init__(cfg, env) + self._target_potential = torch.ones(env.num_envs, dtype=torch.float32, device=env.device) + potential_param_names = ( + "robot_cfg", + "tool_body_name", + "tool_offset", + "xy_threshold", + "height_threshold", + "cube_height", + ) + self._potential_kwargs = {name: cfg.params[name] for name in potential_param_names if name in cfg.params} + + def reset(self, env_ids: Sequence[int] | None = None) -> None: + """Set a non-free target from the newly sampled physical row.""" + if env_ids is None: + env_ids = slice(None) + super().reset(env_ids) + initial = role_conditioned_stack_potential( + self._env, + **self._potential_kwargs, + ) + reset_state = get_stack_reset_runtime_state(self._env) + row_target = reset_state.target_potentials[env_ids] + self._target_potential[env_ids] = torch.maximum( + row_target, + initial[env_ids] + 0.25, + ).clamp_max(10.0) + + def __call__( + self, + env: ManagerBasedRLEnv, + minimum_episode_steps: int = 3, + robot_cfg: SceneEntityCfg = SceneEntityCfg("robot"), + tool_body_name: str = "panda_hand", + tool_offset: tuple[float, float, float] = (0.0, 0.0, 0.1034), + xy_threshold: float = 0.025, + height_threshold: float = 0.012, + cube_height: float = 0.04, + ) -> torch.Tensor: + """Update sticky curriculum success and return a non-terminating mask.""" + if minimum_episode_steps < 0 or min(xy_threshold, height_threshold, cube_height) <= 0.0: + raise ValueError("Invalid reset-learning progress thresholds.") + current = role_conditioned_stack_potential( + env, + robot_cfg=robot_cfg, + tool_body_name=tool_body_name, + tool_offset=tool_offset, + xy_threshold=xy_threshold, + height_threshold=height_threshold, + cube_height=cube_height, + ) + reached = (current >= self._target_potential) & (env.episode_length_buf >= minimum_episode_steps) + self._update_success(reached) + return self._no_termination diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/observations.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/observations.py index 7f00d26898b4..61306a60ecc7 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/observations.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/observations.py @@ -15,6 +15,9 @@ import isaaclab.utils.math as math_utils from isaaclab.managers import SceneEntityCfg +from .robot_state import end_effector_pose, end_effector_velocity +from .runtime_state import get_stack_reset_runtime_state + if TYPE_CHECKING: from isaaclab.assets import Articulation, RigidObject, RigidObjectCollection from isaaclab.envs import ManagerBasedRLEnv @@ -179,6 +182,115 @@ def object_obs( ) +def franka_ee_axes( + env: ManagerBasedRLEnv, + robot_cfg: SceneEntityCfg = SceneEntityCfg("robot"), + tool_body_name: str = "panda_hand", + tool_offset: tuple[float, float, float] = (0.0, 0.0, 0.1034), +) -> torch.Tensor: + """Return continuous configured-tool x/z axes.""" + _, orientation = end_effector_pose( + env, + robot_cfg=robot_cfg, + body_name=tool_body_name, + body_offset=tool_offset, + ) + rotation = math_utils.matrix_from_quat(orientation) + return torch.cat((rotation[:, :, 0], rotation[:, :, 2]), dim=1) + + +def franka_ee_velocity( + env: ManagerBasedRLEnv, + robot_cfg: SceneEntityCfg = SceneEntityCfg("robot"), + tool_body_name: str = "panda_hand", + tool_offset: tuple[float, float, float] = (0.0, 0.0, 0.1034), +) -> torch.Tensor: + """Return the configured tool-center linear/angular velocity.""" + return end_effector_velocity( + env, + robot_cfg=robot_cfg, + body_name=tool_body_name, + body_offset=tool_offset, + ) + + +def role_conditioned_stack_obs( + env: ManagerBasedRLEnv, + cube_cfgs: tuple[SceneEntityCfg, ...] = ( + SceneEntityCfg("cube_1"), + SceneEntityCfg("cube_2"), + SceneEntityCfg("cube_3"), + ), + robot_cfg: SceneEntityCfg = SceneEntityCfg("robot"), + cube_height: float = 0.04, + tool_body_name: str = "panda_hand", + tool_offset: tuple[float, float, float] = (0.0, 0.0, 0.1034), + xy_threshold: float = 0.025, + height_threshold: float = 0.012, +) -> torch.Tensor: + """Return stable base/side-role tracks with randomized cube colors. + + The reset table stores one episode-long mapping from physical stack roles + to cube assets. Gathering through that mapping makes the input exactly + invariant to reset-time color permutations while keeping each role in a + stable slot through grasp, lift, and placement. Role zero is the spatially + central base; roles one and two are interchangeable side cubes. + + The 64-entry layout contains role-local positions, tool-relative + positions, up axes, spatial velocities, every directed pair-placement + error, and stack progress. + """ + from .rewards import order_invariant_stack_progress + + reset_state = get_stack_reset_runtime_state(env) + + cubes: tuple[RigidObject, ...] = tuple(env.scene[cfg.name] for cfg in cube_cfgs) + positions = torch.stack(tuple(cube.data.root_pos_w.torch for cube in cubes), dim=1) + quaternions = torch.stack(tuple(cube.data.root_quat_w.torch for cube in cubes), dim=1) + velocities = torch.stack(tuple(cube.data.root_vel_w.torch for cube in cubes), dim=1) + role_to_cube = reset_state.role_to_cube + + def by_role(values: torch.Tensor) -> torch.Tensor: + gather_index = role_to_cube.view(env.num_envs, 3, *([1] * (values.ndim - 2))).expand_as(values) + return torch.gather(values, 1, gather_index) + + local_positions = by_role(positions) - env.scene.env_origins.unsqueeze(1) + role_quaternions = by_role(quaternions) + role_velocities = by_role(velocities) + tool_position, _ = end_effector_pose(env, robot_cfg, tool_body_name, tool_offset) + rotation = math_utils.matrix_from_quat(role_quaternions.flatten(end_dim=1)).view(env.num_envs, 3, 3, 3) + up_axes = rotation[..., 2] + tool_relative = local_positions - (tool_position - env.scene.env_origins).unsqueeze(1) + + pair_errors = [] + vertical_offset = local_positions.new_tensor((0.0, 0.0, cube_height)) + for upper_id in range(3): + for lower_id in range(3): + if upper_id != lower_id: + pair_errors.append(local_positions[:, lower_id] + vertical_offset - local_positions[:, upper_id]) + progress = ( + order_invariant_stack_progress( + env, + cube_cfgs=cube_cfgs, + xy_threshold=xy_threshold, + height_threshold=height_threshold, + cube_height=cube_height, + ).unsqueeze(1) + / 2.0 + ) + return torch.cat( + ( + local_positions.flatten(start_dim=1), + tool_relative.flatten(start_dim=1), + up_axes.flatten(start_dim=1), + role_velocities.flatten(start_dim=1), + torch.cat(pair_errors, dim=1), + progress, + ), + dim=1, + ) + + def instance_randomize_object_obs( env: ManagerBasedRLEnv, cube_1_cfg: SceneEntityCfg = SceneEntityCfg("cube_1"), diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/rewards.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/rewards.py index 87716afaeab8..efc653ca4c0c 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/rewards.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/rewards.py @@ -3,7 +3,7 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Rewards for ordered cube stacking.""" +"""Sparse objectives and task-state helpers for cube stacking.""" from __future__ import annotations @@ -11,51 +11,302 @@ import torch +from isaaclab.managers import SceneEntityCfg + +from .robot_state import end_effector_pose +from .runtime_state import get_stack_reset_runtime_state from .terminations import _cube_pair_is_aligned if TYPE_CHECKING: + from isaaclab.assets import Articulation, RigidObject from isaaclab.envs import ManagerBasedRLEnv -def stack_progress(env: ManagerBasedRLEnv) -> torch.Tensor: - """Reward reaching, lifting, and placing the next cube in the stack. +def action_term_l2(env: ManagerBasedRLEnv, action_name: str) -> torch.Tensor: + """Penalize the magnitude of one named raw action term.""" + action = env.action_manager.get_term(action_name).raw_actions + return torch.sum(torch.square(action), dim=1) + + +def finite_joint_velocity_l2( + env: ManagerBasedRLEnv, + asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), + maximum_velocity: float = 3.0, +) -> torch.Tensor: + """Penalize bounded joint velocity without propagating solver divergence. + + Nonfinite robot states are terminated separately. Sanitizing this + regularizer keeps the reward finite on the same transition so one diverged + environment cannot poison the complete PPO rollout before it is reset. + """ + if maximum_velocity <= 0.0: + raise ValueError("maximum_velocity must be positive.") + asset: Articulation = env.scene[asset_cfg.name] + velocity = asset.data.joint_vel.torch[:, asset_cfg.joint_ids] + velocity = torch.nan_to_num( + velocity, + nan=0.0, + posinf=maximum_velocity, + neginf=-maximum_velocity, + ) + velocity = torch.clamp(velocity, min=-maximum_velocity, max=maximum_velocity) + return torch.sum(torch.square(velocity), dim=1) - Compare the world-frame positions of the three cubes and the ``ee_frame`` sensor. The - ``success`` termination term supplies their order, target height, and alignment tolerances. - Args: - env: The Franka cube stacking environment. +def irrecoverable_stack_failure( + env: ManagerBasedRLEnv, + success_termination_name: str = "success", +) -> torch.Tensor: + """Return a unit-integral pulse for a non-timeout terminal failure. - Returns: - One progress reward per environment, with shape ``(num_envs,)``. + Intermediate reset rows deliberately include states far from the final + stack. Treating an ordinary horizon timeout as a failure overwhelms rare + forward-transition samples and teaches the policy to stop. Drops, + out-of-workspace states, and numerical divergence remain penalized. """ - # The termination manager resolves omitted defaults when it prepares the success term. - success_params = env.termination_manager.get_term_cfg("success").params - bottom = env.scene[success_params["cube_1_cfg"].name].data.root_pos_w.torch - middle = env.scene[success_params["cube_2_cfg"].name].data.root_pos_w.torch - top = env.scene[success_params["cube_3_cfg"].name].data.root_pos_w.torch - ee = env.scene["ee_frame"].data.target_pos_w.torch[:, 0] - height = success_params["height_diff"] - # Use alignment alone so closing the gripper for the next pick keeps the new goal. - middle_placed = _cube_pair_is_aligned( - middle - bottom, - success_params["xy_threshold"], - height, - success_params["height_threshold"], - success_params["symmetric_height_tolerance"], - ) - cube = torch.where(middle_placed[:, None], top, middle) - support = torch.where(middle_placed[:, None], middle, bottom) - target_error = cube - support - target_error[:, 2] -= height - - reach = 1.0 - torch.tanh(torch.linalg.vector_norm(cube - ee, dim=1) / 0.1) - # Measure lift relative to the bottom cube's center. - lift = ((cube[:, 2] - bottom[:, 2]) / height).clamp(0.0, 1.0) - place = 1.0 - torch.tanh(torch.linalg.vector_norm(target_error, dim=1) / 0.1) - return middle_placed.float() + 0.25 * ((1.0 - lift) * reach + lift) + 0.75 * lift * place - - -def stack_success(env: ManagerBasedRLEnv) -> torch.Tensor: - """Reward the per-environment success signal even when the episode limit also fires.""" - return env.termination_manager.get_term("success").float() + succeeded = env.termination_manager.get_term(success_termination_name) + failed = env.reset_terminated & ~succeeded + # RewardManager integrates rates by multiplying every term by step_dt. + # Dividing here makes the configured weight the exact episode impulse. + return failed.float() / max(float(env.step_dt), 1.0e-6) + + +def _gripper_joint_positions(env: ManagerBasedRLEnv, robot: Articulation) -> torch.Tensor: + """Read both fingers of the Franka parallel gripper.""" + joint_ids, _ = robot.find_joints(env.cfg.gripper_joint_names) + if len(joint_ids) != 2: + raise ValueError("Franka stack gripper thresholds require a two-finger parallel gripper.") + return robot.data.joint_pos.torch[:, joint_ids] + + +_CUBE_PERMUTATIONS = ( + (0, 1, 2), + (0, 2, 1), + (1, 0, 2), + (1, 2, 0), + (2, 0, 1), + (2, 1, 0), +) + + +def _order_invariant_cube_state( + env: ManagerBasedRLEnv, + cube_cfgs: tuple[SceneEntityCfg, ...], +) -> tuple[torch.Tensor, torch.Tensor]: + """Return cube COM positions [m] and spatial velocities [m/s, rad/s].""" + cubes: tuple[RigidObject, ...] = tuple(env.scene[cfg.name] for cfg in cube_cfgs) + positions = torch.stack(tuple(cube.data.root_pos_w.torch for cube in cubes), dim=1) + velocities = torch.stack(tuple(cube.data.root_vel_w.torch for cube in cubes), dim=1) + return positions, velocities + + +def order_invariant_stack_progress( + env: ManagerBasedRLEnv, + cube_cfgs: tuple[SceneEntityCfg, ...] = ( + SceneEntityCfg("cube_1"), + SceneEntityCfg("cube_2"), + SceneEntityCfg("cube_3"), + ), + xy_threshold: float = 0.025, + height_threshold: float = 0.012, + cube_height: float = 0.04, +) -> torch.Tensor: + """Return zero, one, or two stacked pairs without assigning cube roles.""" + positions, _ = _order_invariant_cube_state(env, cube_cfgs) + delta = positions[:, :, None, :] - positions[:, None, :, :] + pair_is_stacked = _cube_pair_is_aligned(delta, xy_threshold, cube_height, height_threshold, True) + pair_exists = pair_is_stacked.flatten(start_dim=1).any(dim=1) + + complete = torch.zeros(env.num_envs, dtype=torch.bool, device=env.device) + for base_id, middle_id, top_id in _CUBE_PERMUTATIONS: + complete |= pair_is_stacked[:, middle_id, base_id] & pair_is_stacked[:, top_id, middle_id] + return pair_exists.float() + complete.float() + + +def _role_plan_potential( + base_position: torch.Tensor, + middle_position: torch.Tensor, + top_position: torch.Tensor, + *, + ee_position: torch.Tensor, + gripper_release_progress: torch.Tensor, + gripper_released: torch.Tensor, + gripper_closed: torch.Tensor, + reach_std: float, + align_std: float, + place_std: float, + grasp_distance: float, + lift_height: float, + lifted_fraction: float, + align_distance: float, + xy_threshold: float, + height_threshold: float, + cube_height: float, +) -> torch.Tensor: + """Return continuous progress through one fixed-base side-cube order.""" + middle_distance = torch.linalg.vector_norm(middle_position - ee_position, dim=1) + top_distance = torch.linalg.vector_norm(top_position - ee_position, dim=1) + middle_xy_distance = torch.linalg.vector_norm(middle_position[:, :2] - base_position[:, :2], dim=1) + top_xy_distance = torch.linalg.vector_norm(top_position[:, :2] - middle_position[:, :2], dim=1) + middle_place_error = torch.linalg.vector_norm( + torch.cat( + ( + middle_position[:, :2] - base_position[:, :2], + (middle_position[:, 2] - base_position[:, 2] - cube_height).unsqueeze(1), + ), + dim=1, + ), + dim=1, + ) + top_place_error = torch.linalg.vector_norm( + torch.cat( + ( + top_position[:, :2] - middle_position[:, :2], + (top_position[:, 2] - middle_position[:, 2] - cube_height).unsqueeze(1), + ), + dim=1, + ), + dim=1, + ) + + middle_stacked = _cube_pair_is_aligned( + middle_position - base_position, xy_threshold, cube_height, height_threshold, True + ) + top_stacked = middle_stacked & _cube_pair_is_aligned( + top_position - middle_position, xy_threshold, cube_height, height_threshold, True + ) + middle_near = middle_distance < grasp_distance + top_near = top_distance < grasp_distance + middle_grasped = middle_near & gripper_closed & ~middle_stacked + top_grasped = top_near & gripper_closed & ~top_stacked + middle_released = middle_stacked & (~middle_near | gripper_released) + + middle_reach = 1.0 - torch.tanh(middle_distance / reach_std) + top_reach = 1.0 - torch.tanh(top_distance / reach_std) + middle_lift = torch.clamp( + (middle_position[:, 2] - base_position[:, 2]) / lift_height, + min=0.0, + max=1.0, + ) + top_lift = torch.clamp( + (top_position[:, 2] - base_position[:, 2]) / lift_height, + min=0.0, + max=1.0, + ) + middle_align = 1.0 - torch.tanh(middle_xy_distance / align_std) + top_align = 1.0 - torch.tanh(top_xy_distance / align_std) + middle_place = 1.0 - torch.tanh(middle_place_error / place_std) + top_place = 1.0 - torch.tanh(top_place_error / place_std) + + potential = middle_reach + potential = torch.where(middle_grasped, torch.maximum(potential, 1.0 + middle_lift), potential) + middle_lifted = middle_grasped & (middle_lift > lifted_fraction) + potential = torch.where(middle_lifted, torch.maximum(potential, 2.0 + middle_align), potential) + middle_aligned = middle_lifted & (middle_xy_distance < align_distance) + potential = torch.where(middle_aligned, torch.maximum(potential, 3.0 + middle_place), potential) + potential = torch.where( + middle_stacked, + torch.maximum(potential, 4.0 + gripper_release_progress), + potential, + ) + potential = torch.where(middle_released, torch.maximum(potential, 5.0 + top_reach), potential) + potential = torch.where( + middle_released & top_grasped, + torch.maximum(potential, 6.0 + top_lift), + potential, + ) + top_lifted = middle_released & top_grasped & (top_lift > lifted_fraction) + potential = torch.where(top_lifted, torch.maximum(potential, 7.0 + top_align), potential) + top_aligned = top_lifted & (top_xy_distance < align_distance) + potential = torch.where(top_aligned, torch.maximum(potential, 8.0 + top_place), potential) + potential = torch.where( + top_stacked, + torch.maximum(potential, 9.0 + gripper_release_progress), + potential, + ) + return potential + + +def role_conditioned_stack_potential( + env: ManagerBasedRLEnv, + robot_cfg: SceneEntityCfg = SceneEntityCfg("robot"), + tool_body_name: str = "panda_hand", + tool_offset: tuple[float, float, float] = (0.0, 0.0, 0.1034), + cube_cfgs: tuple[SceneEntityCfg, ...] = ( + SceneEntityCfg("cube_1"), + SceneEntityCfg("cube_2"), + SceneEntityCfg("cube_3"), + ), + reach_std: float = 0.10, + align_std: float = 0.08, + place_std: float = 0.05, + grasp_distance: float = 0.045, + maximum_grasp_finger_position: float = 0.03, + lift_height: float = 0.10, + lifted_fraction: float = 0.45, + align_distance: float = 0.06, + xy_threshold: float = 0.025, + height_threshold: float = 0.012, + cube_height: float = 0.04, +) -> torch.Tensor: + """Return fixed-center-base progress with either side-cube order. + + Reset-time color permutations are gathered into stable physical roles. + Role zero remains the base while the maximum over ``1→2`` and ``2→1`` + makes the two movable cubes interchangeable. + """ + reset_state = get_stack_reset_runtime_state(env) + + positions, _ = _order_invariant_cube_state(env, cube_cfgs) + role_to_cube = reset_state.role_to_cube.long() + gather_index = role_to_cube.unsqueeze(-1).expand(-1, -1, 3) + role_positions = torch.gather(positions, 1, gather_index) + robot: Articulation = env.scene[robot_cfg.name] + ee_position, _ = end_effector_pose(env, robot_cfg, tool_body_name, tool_offset) + finger_positions = _gripper_joint_positions(env, robot) + gripper_release_progress = ((finger_positions.amin(dim=1) - 0.020) / (0.024 - 0.020)).clamp(0.0, 1.0) + gripper_released = (finger_positions > 0.023).all(dim=1) + gripper_closed = (finger_positions < maximum_grasp_finger_position).all(dim=1) + common = { + "ee_position": ee_position, + "gripper_release_progress": gripper_release_progress, + "gripper_released": gripper_released, + "gripper_closed": gripper_closed, + "reach_std": reach_std, + "align_std": align_std, + "place_std": place_std, + "grasp_distance": grasp_distance, + "lift_height": lift_height, + "lifted_fraction": lifted_fraction, + "align_distance": align_distance, + "xy_threshold": xy_threshold, + "height_threshold": height_threshold, + "cube_height": cube_height, + } + first_then_second = _role_plan_potential( + role_positions[:, 0], + role_positions[:, 1], + role_positions[:, 2], + **common, + ) + second_then_first = _role_plan_potential( + role_positions[:, 0], + role_positions[:, 2], + role_positions[:, 1], + **common, + ) + return torch.nan_to_num( + torch.maximum(first_then_second, second_then_first), + nan=0.0, + posinf=0.0, + neginf=0.0, + ) + + +def stack_success_pulse( + env: ManagerBasedRLEnv, + context_term_name: str = "progress_context", +) -> torch.Tensor: + """Return a unit-integral pulse for the first stable stack event.""" + context = env.termination_manager.get_term_cfg(context_term_name).func + return context.new_success.float() / max(float(env.step_dt), 1.0e-6) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/robot_state.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/robot_state.py new file mode 100644 index 000000000000..30b852ed52a4 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/robot_state.py @@ -0,0 +1,80 @@ +# 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 + +"""Backend-independent end-effector state helpers for stack tasks.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import torch + +from isaaclab.managers import SceneEntityCfg +from isaaclab.utils import math as math_utils + +if TYPE_CHECKING: + from isaaclab.assets import Articulation + from isaaclab.envs import ManagerBasedRLEnv + + +def _end_effector_cache_entry( + env: ManagerBasedRLEnv, + robot_cfg: SceneEntityCfg, + body_name: str, + body_offset: tuple[float, float, float], +) -> tuple[Articulation, int, torch.Tensor]: + """Resolve and cache one articulation body and its tool-frame offset.""" + robot: Articulation = env.scene[robot_cfg.name] + cache = getattr(env, "_stack_end_effector_cache", None) + if cache is None: + cache = {} + env._stack_end_effector_cache = cache + + cache_key = (robot_cfg.name, body_name, body_offset) + entry = cache.get(cache_key) + if entry is None: + body_ids, _ = robot.find_bodies(body_name) + if len(body_ids) != 1: + raise ValueError(f"Expected one end-effector body matching '{body_name}', found {len(body_ids)}.") + entry = ( + body_ids[0], + torch.tensor(body_offset, dtype=torch.float32, device=env.device), + ) + cache[cache_key] = entry + return robot, entry[0], entry[1] + + +def end_effector_pose( + env: ManagerBasedRLEnv, + robot_cfg: SceneEntityCfg = SceneEntityCfg("robot"), + body_name: str = "panda_hand", + body_offset: tuple[float, float, float] = (0.0, 0.0, 0.1034), +) -> tuple[torch.Tensor, torch.Tensor]: + """Return a configured tool-center position [m] and orientation.""" + robot, body_id, tool_offset = _end_effector_cache_entry(env, robot_cfg, body_name, body_offset) + + body_position = robot.data.body_pos_w.torch[:, body_id] + body_orientation = robot.data.body_quat_w.torch[:, body_id] + tool_position = body_position + math_utils.quat_apply(body_orientation, tool_offset.expand(env.num_envs, -1)) + return tool_position, body_orientation + + +def end_effector_velocity( + env: ManagerBasedRLEnv, + robot_cfg: SceneEntityCfg = SceneEntityCfg("robot"), + body_name: str = "panda_hand", + body_offset: tuple[float, float, float] = (0.0, 0.0, 0.1034), +) -> torch.Tensor: + """Return the tool-center linear/angular velocity in world coordinates.""" + robot, body_id, tool_offset = _end_effector_cache_entry(env, robot_cfg, body_name, body_offset) + + body_orientation = robot.data.body_quat_w.torch[:, body_id] + body_velocity = robot.data.body_vel_w.torch[:, body_id] + tool_offset_world = math_utils.quat_apply(body_orientation, tool_offset.expand(env.num_envs, -1)) + tool_linear_velocity = body_velocity[:, :3] + torch.linalg.cross( + body_velocity[:, 3:], + tool_offset_world, + ) + return torch.cat((tool_linear_velocity, body_velocity[:, 3:]), dim=1) 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..ac5f301aa45a 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/terminations.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/terminations.py @@ -7,6 +7,7 @@ from __future__ import annotations +import math from typing import TYPE_CHECKING import torch @@ -19,6 +20,24 @@ from isaaclab.envs import ManagerBasedRLEnv +def success_after_minimum_horizon( + env: ManagerBasedRLEnv, + context_term_name: str = "progress_context", + minimum_episode_length_s: float = 5.0, +) -> torch.Tensor: + """Terminate successful episodes after a configurable minimum horizon. + + The success context owns the physical stability hold. This separate gate + exists only to prevent success inherited directly from a reset state; it + should not keep a policy in an already solved scene. + """ + if minimum_episode_length_s <= 0.0: + raise ValueError("minimum_episode_length_s must be positive.") + context = env.termination_manager.get_term_cfg(context_term_name).func + minimum_steps = math.ceil(minimum_episode_length_s / env.step_dt) + return context.ever_success & (env.episode_length_buf >= minimum_steps) + + def cubes_stacked( env: ManagerBasedRLEnv, robot_cfg: SceneEntityCfg = SceneEntityCfg("robot"), @@ -117,21 +136,70 @@ def _cube_pair_is_aligned( """Check the world-frame upper-minus-lower cube displacement. Args: - separation: Cube center displacements in meters, with shape [N, 3]. + separation: Cube center displacements in meters, with shape (..., 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. + A boolean tensor of shape (...) indicating aligned cube pairs. """ - height = separation[:, 2] + 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) + (torch.linalg.vector_norm(separation[..., :2], dim=-1) < xy_threshold) & (height > 0.0) & (height_error < height_threshold) ) + + +def nonfinite_robot_state( + env: ManagerBasedRLEnv, + robot_cfg: SceneEntityCfg = SceneEntityCfg("robot"), +) -> torch.Tensor: + """Detect non-finite robot joint state.""" + robot: Articulation = env.scene[robot_cfg.name] + joint_position = robot.data.joint_pos.torch[:, robot_cfg.joint_ids] + joint_velocity = robot.data.joint_vel.torch[:, robot_cfg.joint_ids] + return ~torch.isfinite(joint_position).all(dim=1) | ~torch.isfinite(joint_velocity).all(dim=1) + + +def nonfinite_cube_state( + env: ManagerBasedRLEnv, + cube_cfgs: tuple[SceneEntityCfg, ...] = ( + SceneEntityCfg("cube_1"), + SceneEntityCfg("cube_2"), + SceneEntityCfg("cube_3"), + ), +) -> torch.Tensor: + """Detect non-finite cube pose or velocity state.""" + invalid = torch.zeros(env.num_envs, dtype=torch.bool, device=env.device) + for cube_cfg in cube_cfgs: + cube: RigidObject = env.scene[cube_cfg.name] + invalid |= ~torch.isfinite(cube.data.root_pose_w.torch).all(dim=1) + invalid |= ~torch.isfinite(cube.data.root_vel_w.torch).all(dim=1) + return invalid + + +def cube_out_of_workspace( + env: ManagerBasedRLEnv, + cube_cfgs: tuple[SceneEntityCfg, ...] = ( + SceneEntityCfg("cube_1"), + SceneEntityCfg("cube_2"), + SceneEntityCfg("cube_3"), + ), + workspace_lower: tuple[float, float, float] = (-0.2, -0.7, -0.1), + workspace_upper: tuple[float, float, float] = (1.2, 0.7, 1.0), +) -> torch.Tensor: + """Detect cubes outside the local task workspace [m].""" + lower = torch.tensor(workspace_lower, dtype=torch.float32, device=env.device) + upper = torch.tensor(workspace_upper, dtype=torch.float32, device=env.device) + invalid = torch.zeros(env.scene.env_origins.shape[0], dtype=torch.bool, device=env.device) + for cube_cfg in cube_cfgs: + cube: RigidObject = env.scene[cube_cfg.name] + position = cube.data.root_pos_w.torch - env.scene.env_origins + invalid |= ((position < lower) | (position > upper)).any(dim=1) + return invalid diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/spawners.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/spawners.py new file mode 100644 index 000000000000..440548b009b3 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/spawners.py @@ -0,0 +1,75 @@ +# 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 + +"""Small display-color extension for native cuboid assets.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +import isaaclab.sim as sim_utils +from isaaclab.utils.configclass import configclass + +if TYPE_CHECKING: + from pxr import Usd + + +def _author_display_color(prim_path: str, cfg: ColoredCuboidCfg, stage: Usd.Stage) -> None: + """Author a portable USD display color on the standard cuboid geometry.""" + from pxr import Gf, UsdGeom + + mesh_prim = stage.GetPrimAtPath(f"{prim_path}/geometry/mesh") + UsdGeom.Gprim(mesh_prim).CreateDisplayColorPrimvar(UsdGeom.Tokens.constant).Set([Gf.Vec3f(*cfg.display_color)]) + + +def _spawn_colored_cuboid_impl( + prim_path: str, + cfg: ColoredCuboidCfg, + translation: tuple[float, float, float] | None = None, + orientation: tuple[float, float, float, float] | None = None, + **kwargs: Any, +) -> Usd.Prim: + """Spawn and color one standard cuboid before the asset is cloned.""" + from isaaclab.sim.spawners.shapes import spawn_cuboid + from isaaclab.sim.utils import get_current_stage + + prim = spawn_cuboid.__wrapped__( + prim_path, + cfg, + translation=translation, + orientation=orientation, + **kwargs, + ) + _author_display_color(prim_path, cfg, get_current_stage()) + return prim + + +def spawn_colored_cuboid( + prim_path: str, + cfg: ColoredCuboidCfg, + translation: tuple[float, float, float] | None = None, + orientation: tuple[float, float, float, float] | None = None, + **kwargs: Any, +) -> Usd.Prim: + """Spawn a standard cuboid with a kitless-compatible display color.""" + from isaaclab.sim.utils import clone + + return clone(_spawn_colored_cuboid_impl)( + prim_path, + cfg, + translation=translation, + orientation=orientation, + **kwargs, + ) + + +@configclass +class ColoredCuboidCfg(sim_utils.CuboidCfg): + """Native cuboid with an authored USD ``displayColor``.""" + + func = spawn_colored_cuboid + + display_color: tuple[float, float, float] = (0.18, 0.18, 0.18) + """Display color of the render-only geometry.""" 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 6f7806bed5ce..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_rl_env_cfg import FrankaCubeStackRLEnvCfg 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 = FrankaCubeStackRLEnvCfg() - 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 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_state.py b/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_state.py new file mode 100644 index 000000000000..bf746d4c930d --- /dev/null +++ b/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_state.py @@ -0,0 +1,101 @@ +# 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 + +"""Tests of the published state-policy input and full-stack success contracts.""" + +from types import SimpleNamespace + +import pytest +import torch + +from isaaclab.managers import ObservationTermCfg + +from isaaclab_tasks.contrib.stack import mdp +from isaaclab_tasks.utils import parse_env_cfg + +pytestmark = pytest.mark.kitless + + +@pytest.fixture(scope="module") +def stack_cfg(): + """Load the registered state task without starting a renderer.""" + cfg = parse_env_cfg("IsaacContrib-Stack-Cube-Franka-RL", device="cpu", num_envs=3) + cfg.validate_config() + return cfg + + +def test_state_policy_observation_order_matches_published_checkpoints(stack_cfg): + policy = stack_cfg.observations.policy + assert [name for name, term in vars(policy).items() if isinstance(term, ObservationTermCfg)] == [ + "actions", + "joint_pos", + "joint_vel", + "object", + "gripper_pos", + "eef_velocity", + "eef_axes", + ] + + +def test_explicit_newton_selector_keeps_the_task_physics(stack_cfg): + explicit = parse_env_cfg( + "IsaacContrib-Stack-Cube-Franka-RL", device="cpu", num_envs=3, overrides=["physics=newton_mjwarp"] + ) + assert explicit.sim.physics == stack_cfg.sim.physics + + +def test_play_mode_selects_randomized_table_starts(stack_cfg): + cfg = stack_cfg.copy() + cfg.play_mode() + + assert cfg.events.reset_from_state_buffer.params["fixed_recipe"] == int(mdp.StackResetRecipe.TABLE) + assert cfg.curriculum is None + assert cfg.actions.gripper_action.force_close_steps == 0 + + +def test_success_requires_an_order_invariant_released_stack_held_at_rest(stack_cfg): + # The physical stack is asset 2 -> asset 3 -> asset 1 in each environment. + scene = {} + for cube_index, height in enumerate((0.10, 0.02, 0.06), start=1): + positions = torch.zeros(3, 3) + positions[:, 2] = height + velocities = torch.zeros(3, 6) + if cube_index == 1: + velocities[2, 2] = 0.2 + scene[f"cube_{cube_index}"] = SimpleNamespace( + data=SimpleNamespace( + root_pos_w=SimpleNamespace(torch=positions), root_vel_w=SimpleNamespace(torch=velocities) + ) + ) + scene["robot"] = SimpleNamespace( + data=SimpleNamespace(joint_pos=SimpleNamespace(torch=torch.tensor([[0.04, 0.04], [0.02, 0.02], [0.04, 0.04]]))), + find_joints=lambda names: ([0, 1], names), + ) + env = SimpleNamespace( + num_envs=3, + device="cpu", + cfg=stack_cfg, + scene=scene, + episode_length_buf=torch.full((3,), 3), + step_dt=0.02, + extras={}, + ) + progress_cfg = stack_cfg.terminations.progress_context + context = progress_cfg.func(progress_cfg, env) + env.termination_manager = SimpleNamespace(get_term_cfg=lambda name: SimpleNamespace(func=context)) + success = stack_cfg.terminations.success + reward = stack_cfg.rewards.success + + for _ in range(4): + context(env, **progress_cfg.params) + assert not success.func(env, **success.params).any() + env.episode_length_buf += 1 + + context(env, **progress_cfg.params) + assert success.func(env, **success.params).tolist() == [True, False, False] + torch.testing.assert_close(reward.func(env, **reward.params) * env.step_dt, torch.tensor([1.0, 0.0, 0.0])) + + context(env, **progress_cfg.params) + assert not reward.func(env, **reward.params).any() From 8e37573dc74498780cc1f7e6e446f8c8dd53982a Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Wed, 18 Nov 2026 00:46:01 +0100 Subject: [PATCH 11/28] Add camera PPO and distillation for Franka stacking --- .../changelog.d/franka-stack-camera.added.rst | 1 + .../changelog.d/franka-stack-camera.minor | 0 .../contrib/stack/config/franka/__init__.py | 24 +++ .../config/franka/agents/distillation.py | 22 +++ .../franka/agents/rsl_rl_camera_ppo_cfg.py | 47 +++++ .../franka/agents/rsl_rl_distillation_cfg.py | 50 ++++++ .../config/franka/stack_camera_rl_env_cfg.py | 166 ++++++++++++++++++ .../contrib/stack/mdp/__init__.pyi | 5 + .../contrib/stack/mdp/camera.py | 149 ++++++++++++++++ .../contrib/stack/test_franka_stack_camera.py | 79 +++++++++ 10 files changed, 543 insertions(+) create mode 100644 source/isaaclab_tasks/changelog.d/franka-stack-camera.added.rst create mode 100644 source/isaaclab_tasks/changelog.d/franka-stack-camera.minor create mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/agents/distillation.py create mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/agents/rsl_rl_camera_ppo_cfg.py create mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/agents/rsl_rl_distillation_cfg.py create mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_camera_rl_env_cfg.py create mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/camera.py create mode 100644 source/isaaclab_tasks/test/contrib/stack/test_franka_stack_camera.py diff --git a/source/isaaclab_tasks/changelog.d/franka-stack-camera.added.rst b/source/isaaclab_tasks/changelog.d/franka-stack-camera.added.rst new file mode 100644 index 000000000000..56fc331d5ebd --- /dev/null +++ b/source/isaaclab_tasks/changelog.d/franka-stack-camera.added.rst @@ -0,0 +1 @@ +* Added RGB-based Franka cube stacking with asymmetric PPO and distillation from the state-based PPO teacher. diff --git a/source/isaaclab_tasks/changelog.d/franka-stack-camera.minor b/source/isaaclab_tasks/changelog.d/franka-stack-camera.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/__init__.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/__init__.py index a9f6e538f127..e51a04de39f4 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/__init__.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/__init__.py @@ -34,6 +34,30 @@ disable_env_checker=True, ) +gym.register( + id="IsaacContrib-Stack-Cube-Franka-RL-Camera", + entry_point="isaaclab.envs:ManagerBasedRLEnv", + kwargs={ + "env_cfg_entry_point": f"{__name__}.stack_camera_rl_env_cfg:FrankaCubeStackCameraRLEnvCfg", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_camera_ppo_cfg:FrankaStackCameraPPORunnerCfg", + "default_agent": "rsl_rl", + }, + disable_env_checker=True, +) + +gym.register( + id="IsaacContrib-Stack-Cube-Franka-RL-Camera-Distillation", + entry_point="isaaclab.envs:ManagerBasedRLEnv", + kwargs={ + "env_cfg_entry_point": f"{__name__}.stack_camera_rl_env_cfg:FrankaCubeStackCameraRLEnvCfg", + "rsl_rl_cfg_entry_point": ( + f"{agents.__name__}.rsl_rl_distillation_cfg:FrankaStackCameraDistillationRunnerCfg" + ), + "default_agent": "rsl_rl", + }, + disable_env_checker=True, +) + gym.register( id="IsaacContrib-Stack-Cube-Instance-Randomize-Franka", entry_point="isaaclab.envs:ManagerBasedRLEnv", diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/agents/distillation.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/agents/distillation.py new file mode 100644 index 000000000000..7d6527a327c4 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/agents/distillation.py @@ -0,0 +1,22 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Action clipping for Franka stack distillation.""" + +from __future__ import annotations + +import torch +from rsl_rl.algorithms import Distillation +from tensordict import TensorDict + + +class ClippedTeacherDistillation(Distillation): + """Match teacher labels to the stack runner's action bounds.""" + + def act(self, obs: TensorDict) -> torch.Tensor: + """Collect a student action and clamp its teacher label to the action contract.""" + actions = super().act(obs) + self.transition.privileged_actions = self.transition.privileged_actions.clamp(-1.0, 1.0) + return actions diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/agents/rsl_rl_camera_ppo_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/agents/rsl_rl_camera_ppo_cfg.py new file mode 100644 index 000000000000..d66bc2903c8e --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/agents/rsl_rl_camera_ppo_cfg.py @@ -0,0 +1,47 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""RSL-RL PPO configuration for RGB-based Franka stacking.""" + +from isaaclab.utils import configclass + +from isaaclab_rl.rsl_rl import RslRlCNNModelCfg, RslRlMLPModelCfg + +from .rsl_rl_ppo_cfg import ALGORITHM_CFG, FrankaStackPPORunnerCfg + +CAMERA_POLICY_CFG = RslRlCNNModelCfg( + hidden_dims=[512, 256, 128], + activation="elu", + obs_normalization=True, + distribution_cfg=RslRlMLPModelCfg.GaussianDistributionCfg( + init_std=0.2, + std_range=(0.05, 0.3), + std_type="log", + ), + cnn_cfg=RslRlCNNModelCfg.CNNCfg( + output_channels=[16, 32, 32], + kernel_size=[8, 4, 3], + stride=[4, 2, 1], + activation="elu", + ), +) + + +@configclass +class FrankaStackCameraPPORunnerCfg(FrankaStackPPORunnerCfg): + """Use RGB and proprioception for the actor and state for the critic.""" + + max_iterations = 15000 + save_interval = 50 + experiment_name = "franka_stack_camera" + obs_groups = {"actor": ["policy", "base_image"], "critic": ["privileged"]} + actor = CAMERA_POLICY_CFG + # Use a smaller learning rate and more samples per batch for the visual encoder. + algorithm = ALGORITHM_CFG.replace( + entropy_coef=0.005, + num_mini_batches=8, + learning_rate=7.0e-5, + schedule="fixed", + ) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/agents/rsl_rl_distillation_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/agents/rsl_rl_distillation_cfg.py new file mode 100644 index 000000000000..e63f63235b31 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/agents/rsl_rl_distillation_cfg.py @@ -0,0 +1,50 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""RSL-RL teacher-student distillation for camera-based Franka stacking.""" + +from isaaclab.utils import configclass + +from isaaclab_rl.rsl_rl import RslRlDistillationAlgorithmCfg, RslRlDistillationRunnerCfg, RslRlMLPModelCfg + +from .rsl_rl_camera_ppo_cfg import CAMERA_POLICY_CFG +from .rsl_rl_ppo_cfg import STATE_POLICY_CFG + + +@configclass +class FrankaStackCameraDistillationRunnerCfg(RslRlDistillationRunnerCfg): + """Distill the state-based PPO actor into an RGB and proprioception policy.""" + + num_steps_per_env = 8 + # Reset-table curricula need a complete first outcome for every row. + init_at_random_ep_len = False + max_iterations = 3000 + save_interval = 50 + experiment_name = "franka_stack_camera_distillation" + clip_actions = 1.0 + obs_groups = { + "student": ["policy", "base_image"], + "teacher": ["privileged"], + } + # A small Gaussian makes RSL-RL collect teacher labels at states visited + # by the student while keeping the architecture identical to camera PPO. + student = CAMERA_POLICY_CFG.replace( + distribution_cfg=RslRlMLPModelCfg.GaussianDistributionCfg( + init_std=0.1, + std_range=(0.05, 0.3), + std_type="log", + ), + ) + # Keep this architecture identical to the state actor so a PPO checkpoint + # can be loaded as the frozen teacher with strict state-dict validation. + teacher = STATE_POLICY_CFG + algorithm = RslRlDistillationAlgorithmCfg( + class_name="isaaclab_tasks.contrib.stack.config.franka.agents.distillation:ClippedTeacherDistillation", + num_learning_epochs=2, + learning_rate=1.0e-4, + gradient_length=1, + max_grad_norm=1.0, + loss_type="mse", + ) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_camera_rl_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_camera_rl_env_cfg.py new file mode 100644 index 000000000000..5d9499ba90d7 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_camera_rl_env_cfg.py @@ -0,0 +1,166 @@ +# 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 + +"""Vision-policy variant of the reset-oriented Franka stack task.""" + +import isaaclab.sim as sim_utils +from isaaclab.managers import EventTermCfg as EventTerm +from isaaclab.managers import ObservationGroupCfg as ObsGroup +from isaaclab.managers import ObservationTermCfg as ObsTerm +from isaaclab.managers import SceneEntityCfg +from isaaclab.sensors import CameraCfg +from isaaclab.utils import tensor_processors +from isaaclab.utils.configclass import configclass +from isaaclab.utils.noise import UniformNoiseCfg as Unoise + +from isaaclab_tasks.utils.presets import MultiBackendRendererCfg + +from ... import mdp +from ...stack_env_cfg import ObjectTableSceneCfg +from .stack_rl_env_cfg import EventCfg, FrankaCubeStackRLEnvCfg, FrankaStackStateObservationCfg + + +@configclass +class FrankaStackCameraSceneCfg(ObjectTableSceneCfg): + """Franka stack scene with one fixed RGB camera.""" + + # The oblique view resolves both table-plane axes and keeps the complete + # 0.40-0.56 m by -0.18-0.18 m reset workspace in frame. The quaternion is + # the OpenGL look-at rotation from ``pos`` to (0.48, 0.0, 0.08). + base_camera: CameraCfg = CameraCfg( + prim_path="{ENV_REGEX_NS}/Camera", + update_period=0.0, + # Keep cube edges and fingers visible to the CNN across the workspace. + height=128, + width=128, + data_types=["rgb"], + spawn=sim_utils.PinholeCameraCfg( + focal_length=24.0, + focus_distance=400.0, + horizontal_aperture=20.955, + clipping_range=(0.05, 2.5), + ), + offset=CameraCfg.OffsetCfg( + pos=(0.90, -0.55, 0.48), + rot=(0.4734479, 0.1600998, 0.2774602, 0.8205066), + convention="opengl", + ), + renderer_cfg=MultiBackendRendererCfg(), + ) + + +@configclass +class CameraEventCfg(EventCfg): + """Physical reset table plus fixed-per-environment camera calibration error.""" + + camera_calibration = EventTerm( + func=mdp.randomize_camera_calibration, + mode="startup", + params={ + "sensor_cfg": SceneEntityCfg("base_camera"), + "eye": (0.90, -0.55, 0.48), + "lookat": (0.48, 0.0, 0.08), + "eye_position_noise": (0.020, 0.020, 0.015), + "lookat_position_noise": (0.015, 0.015, 0.010), + }, + ) + + +@configclass +class CameraObservationsCfg: + """RGB and proprioception for the actor, full state for the critic and teacher.""" + + @configclass + class PolicyCfg(ObsGroup): + """Proprioception and action history for the visual policy.""" + + joint_pos = ObsTerm( + func=mdp.joint_pos_rel, + params={"asset_cfg": SceneEntityCfg("robot", joint_names=["panda_joint.*"])}, + noise=Unoise(n_min=-0.005, n_max=0.005), + ) + joint_vel = ObsTerm( + func=mdp.joint_vel_rel, + params={"asset_cfg": SceneEntityCfg("robot", joint_names=["panda_joint.*"])}, + noise=Unoise(n_min=-0.05, n_max=0.05), + ) + joint_target = ObsTerm( + func=mdp.joint_position_target, + noise=Unoise(n_min=-0.005, n_max=0.005), + ) + gripper_pos = ObsTerm( + func=mdp.gripper_pos, + noise=Unoise(n_min=-0.001, n_max=0.001), + ) + actions = ObsTerm(func=mdp.last_action) + + def __post_init__(self) -> None: + self.enable_corruption = True + self.concatenate_terms = True + + @configclass + class BaseImageCfg(ObsGroup): + """Single-frame, channel-first RGB input for the visual encoder. + + Scale each frame by ``1 / 255`` before applying photometric noise in + normalized image units. + """ + + rgb = ObsTerm( + func=mdp.image_rgb, + params={ + "sensor_cfg": SceneEntityCfg("base_camera"), + "data_type": "rgb", + "normalize": False, + "channel_first": True, + }, + tensor_processors=[ + tensor_processors.TensorProcessorCfg(func=tensor_processors.scale, params={"multiplier": 1.0 / 255.0}) + ], + noise=mdp.EpisodeCameraNoiseCfg(), + clip=(0.0, 1.0), + ) + + def __post_init__(self) -> None: + self.enable_corruption = True + self.concatenate_terms = True + + policy: PolicyCfg = PolicyCfg() + privileged: FrankaStackStateObservationCfg = FrankaStackStateObservationCfg() + base_image: BaseImageCfg = BaseImageCfg() + + +@configclass +class FrankaCubeStackCameraRLEnvCfg(FrankaCubeStackRLEnvCfg): + """Stack from RGB and proprioception with no actor-side object state.""" + + scene: FrankaStackCameraSceneCfg = FrankaStackCameraSceneCfg( + # The 32-step rollout stores about 1.5 GiB of float RGB observations. + num_envs=256, + env_spacing=2.5, + replicate_physics=True, + ) + observations: CameraObservationsCfg = CameraObservationsCfg() + events: CameraEventCfg = CameraEventCfg() + + def __post_init__(self) -> None: + super().__post_init__() + + # Assign the teacher's role order to fixed cube colors so the visual + # student can identify each role. Any physical stack order can succeed. + self.events.reset_from_state_buffer.params["fixed_role_permutation"] = 0 + + # The first action after a reset must see the new robot and cube poses. + self.num_rerenders_on_reset = 1 + + def validate_config(self) -> None: + """Require a fresh RGB frame at each policy step and after a reset.""" + super().validate_config() + if ( + self.scene.base_camera.update_period != 0.0 + or self.sim.render_interval != self.decimation + or self.num_rerenders_on_reset < 1 + ): + raise ValueError("Stack camera observations must refresh at every policy step and after scene resets.") diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/__init__.pyi b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/__init__.pyi index 42a353b48f16..46a0f1ea6f91 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/__init__.pyi +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/__init__.pyi @@ -4,6 +4,8 @@ # SPDX-License-Identifier: BSD-3-Clause __all__ = [ + "EpisodeCameraNoise", + "EpisodeCameraNoiseCfg", "ResetBufferedGripperActionCfg", "StableOrderInvariantStackGoal", "StackResetLearningProgress", @@ -28,6 +30,7 @@ __all__ = [ "instance_randomize_cube_positions_in_world_frame", "instance_randomize_object_obs", "irrecoverable_stack_failure", + "joint_position_target", "nonfinite_cube_state", "nonfinite_robot_state", "object_abs_obs_in_base_frame", @@ -35,6 +38,7 @@ __all__ = [ "object_obs", "object_stacked", "order_invariant_stack_progress", + "randomize_camera_calibration", "role_conditioned_stack_obs", "stack_success_pulse", "success_after_minimum_horizon", @@ -43,6 +47,7 @@ __all__ = [ from isaaclab.envs.mdp import * # noqa: F403 from .actions_cfg import ResetBufferedGripperActionCfg, WorkspaceBoundedRelativeJointPositionActionCfg +from .camera import EpisodeCameraNoise, EpisodeCameraNoiseCfg, joint_position_target, randomize_camera_calibration from .curriculums import StackResetTableCurriculum from .goal_context import StableOrderInvariantStackGoal, StackResetLearningProgress from .observations import ( diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/camera.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/camera.py new file mode 100644 index 000000000000..e5ea9105fd56 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/camera.py @@ -0,0 +1,149 @@ +# 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 + +"""Camera domain randomization for stack policies.""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import TYPE_CHECKING + +import torch + +from isaaclab.managers import SceneEntityCfg +from isaaclab.utils import configclass +from isaaclab.utils.noise import NoiseModel, NoiseModelCfg, UniformNoiseCfg + +if TYPE_CHECKING: + from isaaclab.assets import Articulation + from isaaclab.envs import ManagerBasedEnv + from isaaclab.sensors import Camera + + +class EpisodeCameraNoise(NoiseModel): + """Apply episode-consistent photometric variation and per-frame sensor noise.""" + + def __init__(self, noise_model_cfg: EpisodeCameraNoiseCfg, num_envs: int, device: str): + super().__init__(noise_model_cfg, num_envs, device) + self._exposure_range = self._validate_range("exposure_range", noise_model_cfg.exposure_range, positive=True) + self._contrast_range = self._validate_range("contrast_range", noise_model_cfg.contrast_range, positive=True) + self._white_balance_range = self._validate_range( + "white_balance_range", noise_model_cfg.white_balance_range, positive=True + ) + self._brightness_range = self._validate_range("brightness_range", noise_model_cfg.brightness_range) + scalar_shape = (num_envs, 1, 1, 1) + self._exposure = torch.ones(scalar_shape, device=device) + self._contrast = torch.ones(scalar_shape, device=device) + self._white_balance = torch.ones((num_envs, 3, 1, 1), device=device) + self._brightness = torch.zeros(scalar_shape, device=device) + self.reset() + + @staticmethod + def _validate_range(name: str, values: tuple[float, float], *, positive: bool = False) -> tuple[float, float]: + lower, upper = values + if lower > upper or (positive and lower <= 0.0): + qualifier = "positive and ordered" if positive else "ordered" + raise ValueError(f"{name} must be {qualifier}, got {values}.") + return float(lower), float(upper) + + @staticmethod + def _resample( + tensor: torch.Tensor, env_ids: Sequence[int] | torch.Tensor | None, value_range: tuple[float, float] + ) -> None: + if env_ids is None: + tensor.uniform_(*value_range) + else: + tensor[env_ids] = torch.empty_like(tensor[env_ids]).uniform_(*value_range) + + def reset(self, env_ids: Sequence[int] | torch.Tensor | None = None) -> None: + """Resample photometric parameters for the selected environments.""" + self._resample(self._exposure, env_ids, self._exposure_range) + self._resample(self._contrast, env_ids, self._contrast_range) + self._resample(self._white_balance, env_ids, self._white_balance_range) + self._resample(self._brightness, env_ids, self._brightness_range) + + def __call__(self, data: torch.Tensor) -> torch.Tensor: + """Apply photometric and sensor variation to NCHW RGB in the ``[0, 1]`` range.""" + if data.ndim != 4 or data.shape[1] != 3: + raise ValueError(f"EpisodeCameraNoise expects NCHW RGB input, got shape {tuple(data.shape)}.") + data = (data - 0.5) * self._contrast + 0.5 + data = data * self._exposure * self._white_balance + self._brightness + return super().__call__(data) + + +@configclass +class EpisodeCameraNoiseCfg(NoiseModelCfg): + """Episode-consistent camera randomization with small per-frame pixel noise.""" + + class_type: type[EpisodeCameraNoise] | str = EpisodeCameraNoise + """Noise-model implementation used by the observation manager.""" + + noise_cfg: UniformNoiseCfg = UniformNoiseCfg(n_min=-0.025, n_max=0.025) + """Per-frame additive pixel noise in normalized image units.""" + + exposure_range: tuple[float, float] = (0.75, 1.25) + """Uniform episode-level multiplicative exposure range.""" + + contrast_range: tuple[float, float] = (0.85, 1.15) + """Uniform episode-level contrast range around mid-gray.""" + + white_balance_range: tuple[float, float] = (0.90, 1.10) + """Uniform episode-level per-channel white-balance range.""" + + brightness_range: tuple[float, float] = (-0.05, 0.05) + """Uniform episode-level additive brightness range in normalized image units.""" + + +def joint_position_target(env: ManagerBasedEnv, robot_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor: + """Return commanded joint position targets [m or rad, depending on joint type].""" + robot: Articulation = env.scene[robot_cfg.name] + return robot.actuators.target_command.position.torch[:, robot_cfg.joint_ids] + + +def randomize_camera_calibration( + env: ManagerBasedEnv, + env_ids: Sequence[int] | torch.Tensor | slice | None, + eye: tuple[float, float, float], + lookat: tuple[float, float, float], + eye_position_noise: tuple[float, float, float], + lookat_position_noise: tuple[float, float, float], + sensor_cfg: SceneEntityCfg = SceneEntityCfg("base_camera"), +) -> None: + """Apply one small, independent extrinsic perturbation per camera. + + Startup-only randomization models variation in camera mounting. + + Args: + env: The stack environment containing the camera sensor. + env_ids: Environments whose camera poses are randomized, or ``None`` + for every environment. + eye: Nominal camera position relative to each environment origin [m]. + lookat: Nominal look-at point relative to each environment origin [m]. + eye_position_noise: Independent uniform position-noise half-widths for + the camera eye [m]. + lookat_position_noise: Independent uniform position-noise half-widths + for the look-at point [m]. + sensor_cfg: Scene entity selecting the camera. + """ + camera: Camera = env.scene.sensors[sensor_cfg.name] + 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)] + resolved_env_ids = torch.as_tensor(env_ids, device=env.device, dtype=torch.long).reshape(-1) + if resolved_env_ids.numel() == 0: + return + + origins = env.scene.env_origins[resolved_env_ids] + eye_offset = origins.new_tensor(eye).expand(resolved_env_ids.numel(), -1) + lookat_offset = origins.new_tensor(lookat).expand(resolved_env_ids.numel(), -1) + eye_amplitude = origins.new_tensor(eye_position_noise) + lookat_amplitude = origins.new_tensor(lookat_position_noise) + eye_noise = (2.0 * torch.rand_like(eye_offset) - 1.0) * eye_amplitude + lookat_noise = (2.0 * torch.rand_like(lookat_offset) - 1.0) * lookat_amplitude + + camera.set_world_poses_from_view( + origins + eye_offset + eye_noise, + origins + lookat_offset + lookat_noise, + env_ids=resolved_env_ids, + ) diff --git a/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_camera.py b/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_camera.py new file mode 100644 index 000000000000..d7c9a076e834 --- /dev/null +++ b/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_camera.py @@ -0,0 +1,79 @@ +# 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 + +"""Camera randomization and teacher checkpoint behavior for Franka stacking.""" + +from types import SimpleNamespace + +import pytest +import torch + +from isaaclab.utils.noise import UniformNoiseCfg + +from isaaclab_tasks.contrib.stack.mdp.camera import EpisodeCameraNoise, EpisodeCameraNoiseCfg +from isaaclab_tasks.utils import load_cfg_from_registry + +pytestmark = pytest.mark.kitless + + +def test_episode_camera_noise_resamples_only_reset_environments() -> None: + """An environment reset preserves the camera calibration of every other environment.""" + cfg = EpisodeCameraNoiseCfg( + noise_cfg=UniformNoiseCfg(n_min=0.0, n_max=0.0), + exposure_range=(0.5, 1.5), + contrast_range=(1.0, 1.0), + white_balance_range=(1.0, 1.0), + brightness_range=(0.0, 0.0), + ) + with torch.random.fork_rng(devices=[]): + torch.manual_seed(7) + noise = EpisodeCameraNoise(cfg, num_envs=4, device="cpu") + image = torch.ones(4, 3, 2, 2) + before = noise(image) + noise.reset(torch.tensor([1, 3])) + after = noise(image) + + torch.testing.assert_close(after[[0, 2]], before[[0, 2]], rtol=0.0, atol=0.0) + assert torch.all((after[[1, 3]] != before[[1, 3]]).any(dim=(1, 2, 3))) + + +def test_camera_student_loads_the_ppo_actor_and_uses_clipped_teacher_labels() -> None: + """A native PPO actor checkpoint is a teacher, while the student runs on RGB and proprioception.""" + pytest.importorskip("rsl_rl") + from rsl_rl.algorithms import Distillation + from rsl_rl.models import MLPModel + from tensordict import TensorDict + + state_task = "IsaacContrib-Stack-Cube-Franka-RL" + student_task = "IsaacContrib-Stack-Cube-Franka-RL-Camera-Distillation" + state_cfg = load_cfg_from_registry(state_task, "rsl_rl_cfg_entry_point") + distillation_cfg = load_cfg_from_registry(student_task, "rsl_rl_cfg_entry_point").to_dict() + + state = torch.zeros(1, 100) + state_obs = TensorDict({"policy": state}, [1]) + state_actor_cfg = state_cfg.actor.to_dict() + state_actor_cfg.pop("class_name") + state_actor = MLPModel(state_obs, state_cfg.obs_groups, "actor", 8, **state_actor_cfg) + output = torch.tensor([[-2.0, 2.0, 0.25, 0.0, 0.0, 0.0, 0.0, 0.0]]) + linear_layers = [module for module in state_actor.modules() if isinstance(module, torch.nn.Linear)] + last_linear = linear_layers[-1] + with torch.no_grad(): + last_linear.weight.zero_() + last_linear.bias.copy_(output[0]) + torch.testing.assert_close(state_actor(state_obs), output) + + visual_obs = TensorDict({"policy": torch.zeros(1, 33), "base_image": torch.zeros(1, 3, 128, 128)}, [1]) + camera_obs = visual_obs.clone().set("privileged", state) + distillation_cfg["multi_gpu"] = None + env_spec = SimpleNamespace(num_actions=8, num_envs=1) + algorithm = Distillation.construct_algorithm(camera_obs, env_spec, distillation_cfg, device="cpu") + algorithm.load({"actor_state_dict": state_actor.state_dict()}, load_cfg=None, strict=True) + + with torch.no_grad(): + assert algorithm.get_policy()(visual_obs).shape == (1, 8) + algorithm.act(camera_obs) + + expected_labels = torch.tensor([[-1.0, 1.0, 0.25, 0, 0, 0, 0, 0]]) + torch.testing.assert_close(algorithm.transition.privileged_actions, expected_labels) From 68f218da09269f23f4a4c311ab5cca4aea362baa Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Wed, 18 Nov 2026 00:47:12 +0100 Subject: [PATCH 12/28] Reuse shape visibility already provided by the spawner --- .../changelog.d/franka-stack-hidden-shapes.fixed.rst | 1 - .../isaaclab/isaaclab/sim/spawners/shapes/shapes.py | 10 +--------- source/isaaclab/test/sim/test_spawn_shapes.py | 11 ----------- 3 files changed, 1 insertion(+), 21 deletions(-) delete mode 100644 source/isaaclab/changelog.d/franka-stack-hidden-shapes.fixed.rst diff --git a/source/isaaclab/changelog.d/franka-stack-hidden-shapes.fixed.rst b/source/isaaclab/changelog.d/franka-stack-hidden-shapes.fixed.rst deleted file mode 100644 index 2f2670ddf878..000000000000 --- a/source/isaaclab/changelog.d/franka-stack-hidden-shapes.fixed.rst +++ /dev/null @@ -1 +0,0 @@ -* Fixed procedural shape spawning so an invisible collision surface stays hidden in the scene. diff --git a/source/isaaclab/isaaclab/sim/spawners/shapes/shapes.py b/source/isaaclab/isaaclab/sim/spawners/shapes/shapes.py index 7831294be80f..e2081ec89693 100644 --- a/source/isaaclab/isaaclab/sim/spawners/shapes/shapes.py +++ b/source/isaaclab/isaaclab/sim/spawners/shapes/shapes.py @@ -14,14 +14,7 @@ from isaaclab.utils import validate from ... import schemas -from ...utils import ( - bind_physics_material, - bind_visual_material, - clone, - create_prim, - get_current_stage, - set_prim_visibility, -) +from ...utils import bind_physics_material, bind_visual_material, clone, create_prim, get_current_stage from ..materials.physics_materials import spawn_physics_material from ..spawner_cfg import RigidObjectSpawnerCfg from ..utils import apply_mesh_collision_props, apply_schema_props @@ -322,7 +315,6 @@ def spawn_geom_from_prim_type( geom_prim_path = prim_path + "/geometry" mesh_prim_path = geom_prim_path + "/mesh" create_prim(mesh_prim_path, prim_type, scale=scale, attributes=attributes, stage=stage) - set_prim_visibility(stage.GetPrimAtPath(prim_path), cfg.visible) if geometry_schema_func is not None: geometry_schema_func(mesh_prim_path, stage=stage) diff --git a/source/isaaclab/test/sim/test_spawn_shapes.py b/source/isaaclab/test/sim/test_spawn_shapes.py index e5afd80b5468..7e9e2b406679 100644 --- a/source/isaaclab/test/sim/test_spawn_shapes.py +++ b/source/isaaclab/test/sim/test_spawn_shapes.py @@ -10,8 +10,6 @@ import pytest from isaaclab_physx.sim.schemas import PhysxRigidBodyCfg -from pxr import UsdGeom - import isaaclab.sim as sim_utils from isaaclab.sim import SimulationCfg, SimulationContext @@ -100,15 +98,6 @@ def test_spawn_cuboid(sim): assert prim.GetAttribute("size").Get() == min(cfg.size) -def test_spawn_invisible_cuboid(sim): - """Test that a hidden procedural shape remains invisible to renderers.""" - cfg = sim_utils.CuboidCfg(size=(1.0, 2.0, 3.0), visible=False) - cfg.func("/World/InvisibleCube", cfg) - - prim = sim.stage.GetPrimAtPath("/World/InvisibleCube/geometry/mesh") - assert UsdGeom.Imageable(prim).ComputeVisibility() == UsdGeom.Tokens.invisible - - def test_spawn_sphere(sim): """Test spawning of UsdGeom.Sphere prim.""" cfg = sim_utils.SphereCfg(radius=1.0) From c215696749b0c1c936b45848718dfab74247a85b Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Wed, 18 Nov 2026 00:47:28 +0100 Subject: [PATCH 13/28] Document Franka cube stacking training and resets --- docs/index.rst | 1 + .../source/_static/css/environment-browser.js | 2 +- docs/source/isaaclab/contrib_stacking.rst | 53 +++++++++++++++++++ 3 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 docs/source/isaaclab/contrib_stacking.rst diff --git a/docs/index.rst b/docs/index.rst index c7e135472e95..58a69990c25b 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -103,6 +103,7 @@ Table of Contents source/isaaclab/ecosystem source/isaaclab/installation source/isaaclab/environments + source/isaaclab/contrib_stacking source/isaaclab/quickstart source/isaaclab/tutorial source/isaaclab/demos diff --git a/docs/source/_static/css/environment-browser.js b/docs/source/_static/css/environment-browser.js index 13af348ef4a6..d459ee363674 100644 --- a/docs/source/_static/css/environment-browser.js +++ b/docs/source/_static/css/environment-browser.js @@ -124,7 +124,7 @@ ["IsaacContrib-Stack-Cube-Franka-IK-Rel-Skillgen", "", "isaacsim_physx", "", "", "environment-previews/franka_stack.jpg", false, {}, {}, "", null, ["||", "isaacsim_physx||"]], ["IsaacContrib-Stack-Cube-Franka-IK-Rel-Visuomotor", "", "isaacsim_physx", "", "", "environment-previews/franka_stack.jpg", false, {}, {}, "", null, ["||", "isaacsim_physx||"]], ["IsaacContrib-Stack-Cube-Franka-IK-Rel-Visuomotor-Cosmos", "", "isaacsim_physx", "", "", "environment-previews/franka_stack.jpg", false, {}, {}, "", null, ["||", "isaacsim_physx||"]], - ["IsaacContrib-Stack-Cube-Franka-RL", "rsl_rl", "isaacsim_physx,newton_mjwarp", "", "", "environment-previews/franka_stack.jpg", false, {}, {}, "", null, ["||", "isaacsim_physx||", "newton_mjwarp||"]], + ["IsaacContrib-Stack-Cube-Franka-RL", "rsl_rl", "newton_mjwarp", "", "", "environment-previews/franka_stack.jpg", false, {}, {}, "", null, ["||", "newton_mjwarp||"]], ["IsaacContrib-Stack-Cube-Galbot-Left-Arm-Gripper-RmpFlow", "", "isaacsim_physx", "", "", "environment-previews/galbot_stack_cube.jpg", false, {}, {}, "", null, ["||", "isaacsim_physx||"]], ["IsaacContrib-Stack-Cube-Galbot-Left-Arm-Gripper-Visuomotor", "", "isaacsim_physx", "isaacsim_rtx,newton_renderer", "", "environment-previews/galbot_stack_cube.jpg", false, {}, {}, "", null, ["||", "|isaacsim_rtx|", "|newton_renderer|", "isaacsim_physx||", "isaacsim_physx|isaacsim_rtx|", "isaacsim_physx|newton_renderer|"]], ["IsaacContrib-Stack-Cube-Galbot-Left-Arm-Gripper-Visuomotor-Joint-Position", "", "isaacsim_physx", "isaacsim_rtx,newton_renderer", "", "environment-previews/galbot_stack_cube.jpg", false, {}, {}, "", null, ["||", "|isaacsim_rtx|", "|newton_renderer|", "isaacsim_physx||", "isaacsim_physx|isaacsim_rtx|", "isaacsim_physx|newton_renderer|"]], diff --git a/docs/source/isaaclab/contrib_stacking.rst b/docs/source/isaaclab/contrib_stacking.rst new file mode 100644 index 000000000000..efa10d3c9de3 --- /dev/null +++ b/docs/source/isaaclab/contrib_stacking.rst @@ -0,0 +1,53 @@ +.. Copyright (c) 2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +.. All rights reserved. +.. +.. SPDX-License-Identifier: BSD-3-Clause + +Franka cube stacking +==================== + +``IsaacContrib-Stack-Cube-Franka-RL`` trains an RSL-RL PPO policy to stack three +4 cm cubes with Newton MJWarp. It uses the standard Franka asset's MuJoCo +physics variant and passive mimic finger. The actor observes robot state and +cube state in reset-assigned role order. Success requires a stable tower and +a released gripper. + +Reset curriculum +---------------- + +A reset event builds a bank of validated full-scene states. The bank includes +table starts and intermediate pick, transport, placement, and release states. +Restoring a row writes the robot state, cube poses, zero velocities, and +matching actuator targets. Held cubes follow the reset pose of the hand. +Cube colors are permuted across the physical roles. + +The curriculum records each completed outcome against its previous row before +the reset event selects a replacement. Training draws 35% of starts from the +table and uses the remaining starts for intermediate states, weighted toward +50% recent success. Progress used for sampling and final stack success are +tracked separately. Play mode samples randomized table starts. + +To test a specific phase, configure the reset event before creating the +environment: + +.. code-block:: python + + from isaaclab_tasks.contrib.stack import mdp + from isaaclab_tasks.utils import parse_env_cfg + + cfg = parse_env_cfg("IsaacContrib-Stack-Cube-Franka-RL", num_envs=4) + cfg.curriculum = None + cfg.events.reset_from_state_buffer.params["fixed_recipe"] = int(mdp.StackResetRecipe.FIRST_PICK) + +Training and playback +--------------------- + +.. code-block:: bash + + uv run --extra rsl-rl isaaclab train --rl_library rsl_rl --task IsaacContrib-Stack-Cube-Franka-RL physics=newton_mjwarp + uv run --extra rsl-rl isaaclab play --rl_library rsl_rl --task IsaacContrib-Stack-Cube-Franka-RL \ + --checkpoint /path/to/model.pt --num_envs 1 --visualizer newton_gl physics=newton_mjwarp + +The state actor uses a fixed 100-input observation order. The flat asset's +MuJoCo physics variant and passive finger change the dynamics relative to +earlier stack runs. Revalidate earlier checkpoints against the current task. From 4b6de1645d710697b580865a2831b6ae4c88aa6a Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Wed, 18 Nov 2026 00:48:33 +0100 Subject: [PATCH 14/28] 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 23c40609274cd90efb1692f7dc9dff56bdcac637 Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Wed, 18 Nov 2026 00:49:11 +0100 Subject: [PATCH 15/28] Document the Franka camera training variants --- .../source/_static/css/environment-browser.js | 2 ++ docs/source/isaaclab/contrib_stacking.rst | 27 +++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/docs/source/_static/css/environment-browser.js b/docs/source/_static/css/environment-browser.js index d459ee363674..c1dd49901ce7 100644 --- a/docs/source/_static/css/environment-browser.js +++ b/docs/source/_static/css/environment-browser.js @@ -125,6 +125,8 @@ ["IsaacContrib-Stack-Cube-Franka-IK-Rel-Visuomotor", "", "isaacsim_physx", "", "", "environment-previews/franka_stack.jpg", false, {}, {}, "", null, ["||", "isaacsim_physx||"]], ["IsaacContrib-Stack-Cube-Franka-IK-Rel-Visuomotor-Cosmos", "", "isaacsim_physx", "", "", "environment-previews/franka_stack.jpg", false, {}, {}, "", null, ["||", "isaacsim_physx||"]], ["IsaacContrib-Stack-Cube-Franka-RL", "rsl_rl", "newton_mjwarp", "", "", "environment-previews/franka_stack.jpg", false, {}, {}, "", null, ["||", "newton_mjwarp||"]], + ["IsaacContrib-Stack-Cube-Franka-RL-Camera", "rsl_rl", "newton_mjwarp", "isaacsim_rtx,newton_renderer,ovrtx", "", "environment-previews/franka_stack.jpg", false, {}, {}, "", null, ["||", "|isaacsim_rtx|", "|newton_renderer|", "|ovrtx|", "newton_mjwarp||", "newton_mjwarp|isaacsim_rtx|", "newton_mjwarp|newton_renderer|", "newton_mjwarp|ovrtx|"]], + ["IsaacContrib-Stack-Cube-Franka-RL-Camera-Distillation", "rsl_rl", "newton_mjwarp", "isaacsim_rtx,newton_renderer,ovrtx", "", "environment-previews/franka_stack.jpg", false, {}, {}, "", null, ["||", "|isaacsim_rtx|", "|newton_renderer|", "|ovrtx|", "newton_mjwarp||", "newton_mjwarp|isaacsim_rtx|", "newton_mjwarp|newton_renderer|", "newton_mjwarp|ovrtx|"]], ["IsaacContrib-Stack-Cube-Galbot-Left-Arm-Gripper-RmpFlow", "", "isaacsim_physx", "", "", "environment-previews/galbot_stack_cube.jpg", false, {}, {}, "", null, ["||", "isaacsim_physx||"]], ["IsaacContrib-Stack-Cube-Galbot-Left-Arm-Gripper-Visuomotor", "", "isaacsim_physx", "isaacsim_rtx,newton_renderer", "", "environment-previews/galbot_stack_cube.jpg", false, {}, {}, "", null, ["||", "|isaacsim_rtx|", "|newton_renderer|", "isaacsim_physx||", "isaacsim_physx|isaacsim_rtx|", "isaacsim_physx|newton_renderer|"]], ["IsaacContrib-Stack-Cube-Galbot-Left-Arm-Gripper-Visuomotor-Joint-Position", "", "isaacsim_physx", "isaacsim_rtx,newton_renderer", "", "environment-previews/galbot_stack_cube.jpg", false, {}, {}, "", null, ["||", "|isaacsim_rtx|", "|newton_renderer|", "isaacsim_physx||", "isaacsim_physx|isaacsim_rtx|", "isaacsim_physx|newton_renderer|"]], diff --git a/docs/source/isaaclab/contrib_stacking.rst b/docs/source/isaaclab/contrib_stacking.rst index efa10d3c9de3..edf2f5c543fc 100644 --- a/docs/source/isaaclab/contrib_stacking.rst +++ b/docs/source/isaaclab/contrib_stacking.rst @@ -51,3 +51,30 @@ Training and playback The state actor uses a fixed 100-input observation order. The flat asset's MuJoCo physics variant and passive finger change the dynamics relative to earlier stack runs. Revalidate earlier checkpoints against the current task. + +Camera PPO and distillation +--------------------------- + +``IsaacContrib-Stack-Cube-Franka-RL-Camera`` trains PPO with one fixed +128 × 128 RGB camera and robot proprioception. Its actor uses the camera +and robot signals. The critic also observes the simulator state. Training +varies camera calibration at startup and image appearance between episodes. +The variant uses a fixed role-to-color assignment so the visual student can +identify the intended stacking order. + +``IsaacContrib-Stack-Cube-Franka-RL-Camera-Distillation`` trains the same camera +actor using a compatible state PPO checkpoint as its frozen teacher. +Teacher labels use the same action clipping as the student. The teacher +uses the state task's 100-input observation order, so older 109-input +checkpoints require retraining. + +.. code-block:: bash + + uv run --extra rsl-rl isaaclab train --rl_library rsl_rl --task IsaacContrib-Stack-Cube-Franka-RL-Camera \ + physics=newton_mjwarp renderer=newton_renderer + uv run --extra rsl-rl isaaclab train --rl_library rsl_rl --task IsaacContrib-Stack-Cube-Franka-RL-Camera-Distillation \ + --checkpoint /path/to/teacher.pt physics=newton_mjwarp renderer=newton_renderer + +The camera image is channel-first RGB scaled by ``1 / 255``. Checkpoint +observation order, image size, and policy distribution must match the +selected task and its agent configuration. From 78b4bb9172bad4f8fe3cb516feb3e58c2ecab186 Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Wed, 18 Nov 2026 00:49:42 +0100 Subject: [PATCH 16/28] Report Franka stack success on the terminating step --- .../stack/config/franka/stack_rl_env_cfg.py | 79 ++++++++++--------- .../contrib/stack/mdp/goal_context.py | 5 +- .../contrib/stack/mdp/observations.py | 6 +- .../contrib/stack/stack_env_cfg.py | 9 ++- .../contrib/stack/test_franka_stack_state.py | 55 +++++++++---- 5 files changed, 95 insertions(+), 59 deletions(-) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_rl_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_rl_env_cfg.py index dd8a1174757d..082e30c03fc6 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_rl_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_rl_env_cfg.py @@ -28,7 +28,7 @@ from ... import mdp from ...constants import FRANKA_STACK_ARM_WORKSPACE_LOWER, FRANKA_STACK_ARM_WORKSPACE_UPPER from ...spawners import ColoredCuboidCfg -from ...stack_env_cfg import StackEnvCfg, apply_default_semantics +from ...stack_env_cfg import StackCommonTerminationsCfg, StackEnvCfg, apply_default_semantics from .franka_robot_cfg import FRANKA_PANDA_DEXSUITE_CFG @@ -150,6 +150,44 @@ class CurriculumCfg: ) +@configclass +class FrankaStackTerminationsCfg(StackCommonTerminationsCfg): + """Evaluate the newly settled stack before forwarding it to the success term.""" + + progress_context = DoneTerm( + func=mdp.StableOrderInvariantStackGoal, + params={ + "minimum_episode_steps": 3, + "hold_steps": 5, + "maximum_cube_velocity": 0.10, + "minimum_finger_release_position": 0.023, + }, + ) + learning_progress_context = DoneTerm( + func=mdp.StackResetLearningProgress, + params={"minimum_episode_steps": 3}, + ) + success = DoneTerm( + func=mdp.success_after_minimum_horizon, + params={ + "context_term_name": "progress_context", + # The context already requires five consecutive stable, + # released-stack frames. Terminate on that physical hold + # instead of leaving a solved scene alive for five seconds, + # which invites post-success oscillation and reward cycling. + "minimum_episode_length_s": 0.1, + }, + ) + nonfinite_robot_state = DoneTerm( + func=mdp.nonfinite_robot_state, + params={"robot_cfg": SceneEntityCfg("robot", joint_names=["panda_joint.*"])}, + ) + nonfinite_cube_state = DoneTerm(func=mdp.nonfinite_cube_state) + cube_workspace_invalid = DoneTerm( + func=mdp.cube_out_of_workspace, + ) + + @configclass class FrankaCubeStackRLEnvCfg(StackEnvCfg): """Train a color-order-invariant three-cube stack from physical reset rows.""" @@ -158,6 +196,7 @@ class FrankaCubeStackRLEnvCfg(StackEnvCfg): rewards: RewardsCfg = RewardsCfg() events: EventCfg = EventCfg() curriculum: CurriculumCfg = CurriculumCfg() + terminations: FrankaStackTerminationsCfg = FrankaStackTerminationsCfg() def __post_init__(self) -> None: super().__post_init__() @@ -277,7 +316,6 @@ def __post_init__(self) -> None: # stack roles over all six physical cube permutations, providing order # invariance as data augmentation without dynamically re-sorting input # slots at the critical grasp-to-lift transition. - arm_cfg = SceneEntityCfg("robot", joint_names=["panda_joint.*"]) self.scene.ee_frame = None # Provide one backend-neutral camera hint. The selected Kit or Newton @@ -314,43 +352,6 @@ def __post_init__(self) -> None: semantic_tags=semantic_tags, ) - self.terminations.progress_context = DoneTerm( - func=mdp.StableOrderInvariantStackGoal, - params={ - "minimum_episode_steps": 3, - "hold_steps": 5, - "maximum_cube_velocity": 0.10, - "minimum_finger_release_position": 0.023, - }, - ) - self.terminations.learning_progress_context = DoneTerm( - func=mdp.StackResetLearningProgress, - params={"minimum_episode_steps": 3}, - ) - self.terminations.success = DoneTerm( - func=mdp.success_after_minimum_horizon, - params={ - "context_term_name": "progress_context", - # The context already requires five consecutive stable, - # released-stack frames. Terminate on that physical hold - # instead of leaving a solved scene alive for five seconds, - # which invites post-success oscillation and reward cycling. - "minimum_episode_length_s": 0.1, - }, - ) - self.terminations.time_out = DoneTerm( - func=mdp.time_out, - time_out=True, - ) - self.terminations.nonfinite_robot_state = DoneTerm( - func=mdp.nonfinite_robot_state, - params={"robot_cfg": arm_cfg}, - ) - self.terminations.nonfinite_cube_state = DoneTerm(func=mdp.nonfinite_cube_state) - self.terminations.cube_workspace_invalid = DoneTerm( - func=mdp.cube_out_of_workspace, - ) - def validate_config(self) -> None: """Validate task-specific constraints beyond the shared configuration checks.""" physics = self.sim.physics diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/goal_context.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/goal_context.py index 906e1005c147..d588237ac960 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/goal_context.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/goal_context.py @@ -64,6 +64,7 @@ class StableOrderInvariantStackGoal(_StackSuccessContext): def __init__(self, cfg: TerminationTermCfg, env: ManagerBasedRLEnv): super().__init__(cfg, env) self._stable_steps = torch.zeros(env.num_envs, dtype=torch.long, device=env.device) + self._reported_success = torch.zeros_like(self.ever_success) def reset(self, env_ids: Sequence[int] | None = None) -> None: """Clear the stability dwell counter for reset environments.""" @@ -114,7 +115,9 @@ def __call__( stable = (stack_progress >= 2.0) & slow & released & (env.episode_length_buf >= minimum_episode_steps) self._stable_steps = torch.where(stable, self._stable_steps + 1, torch.zeros_like(self._stable_steps)) self._update_success(self._stable_steps >= hold_steps) - env.extras["successes"] = self.ever_success + # The manager resets episode state before returning the step extras. + self._reported_success.copy_(self.ever_success) + env.extras["successes"] = self._reported_success return self._no_termination diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/observations.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/observations.py index 61306a60ecc7..e6b2841b4a50 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/observations.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/observations.py @@ -205,7 +205,11 @@ def franka_ee_velocity( tool_body_name: str = "panda_hand", tool_offset: tuple[float, float, float] = (0.0, 0.0, 0.1034), ) -> torch.Tensor: - """Return the configured tool-center linear/angular velocity.""" + """Return the tool velocity approximation used by the published state policy. + + The linear component adds the link-origin tool offset correction to the hand's + center-of-mass velocity. Preserve this convention for compatible checkpoints. + """ return end_effector_velocity( env, robot_cfg=robot_cfg, diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/stack_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/stack_env_cfg.py index 4ec36c98c53d..019b3c9f23b1 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/stack_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/stack_env_cfg.py @@ -288,8 +288,8 @@ def __post_init__(self): @configclass -class TerminationsCfg: - """Termination terms for the MDP.""" +class StackCommonTerminationsCfg: + """Time limit and drop checks shared by the stacking tasks.""" time_out = DoneTerm(func=mdp.time_out, time_out=True) @@ -305,6 +305,11 @@ class TerminationsCfg: func=mdp.root_height_below_minimum, params={"minimum_height": -0.05, "asset_cfg": SceneEntityCfg("cube_3")} ) + +@configclass +class TerminationsCfg(StackCommonTerminationsCfg): + """Termination terms for ordered cube stacking.""" + success = DoneTerm(func=mdp.cubes_stacked) diff --git a/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_state.py b/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_state.py index bf746d4c930d..4c6cb2f03579 100644 --- a/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_state.py +++ b/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_state.py @@ -10,9 +10,11 @@ import pytest import torch -from isaaclab.managers import ObservationTermCfg +from isaaclab.managers import ObservationTermCfg, TerminationManager +from isaaclab.utils.string import resolve_matching_names from isaaclab_tasks.contrib.stack import mdp +from isaaclab_tasks.contrib.stack.mdp.runtime_state import create_stack_reset_runtime_state from isaaclab_tasks.utils import parse_env_cfg pytestmark = pytest.mark.kitless @@ -56,46 +58,67 @@ def test_play_mode_selects_randomized_table_starts(stack_cfg): def test_success_requires_an_order_invariant_released_stack_held_at_rest(stack_cfg): + class Scene(dict): + env_origins = torch.zeros(3, 3) + # The physical stack is asset 2 -> asset 3 -> asset 1 in each environment. - scene = {} + scene = Scene() for cube_index, height in enumerate((0.10, 0.02, 0.06), start=1): positions = torch.zeros(3, 3) positions[:, 2] = height + pose = torch.zeros(3, 7) + pose[:, :3] = positions + pose[:, 6] = 1.0 velocities = torch.zeros(3, 6) if cube_index == 1: velocities[2, 2] = 0.2 scene[f"cube_{cube_index}"] = SimpleNamespace( data=SimpleNamespace( - root_pos_w=SimpleNamespace(torch=positions), root_vel_w=SimpleNamespace(torch=velocities) + root_pos_w=SimpleNamespace(torch=positions), + root_pose_w=SimpleNamespace(torch=pose), + root_vel_w=SimpleNamespace(torch=velocities), ) ) + joint_names = [f"panda_joint{number}" for number in range(1, 8)] + ["panda_finger_joint1", "panda_finger_joint2"] + joint_positions = torch.zeros(3, 9) + joint_positions[:, 7:] = torch.tensor([[0.04, 0.04], [0.02, 0.02], [0.04, 0.04]]) scene["robot"] = SimpleNamespace( - data=SimpleNamespace(joint_pos=SimpleNamespace(torch=torch.tensor([[0.04, 0.04], [0.02, 0.02], [0.04, 0.04]]))), - find_joints=lambda names: ([0, 1], names), + num_joints=9, + joint_names=joint_names, + data=SimpleNamespace( + joint_pos=SimpleNamespace(torch=joint_positions), + joint_vel=SimpleNamespace(torch=torch.zeros_like(joint_positions)), + body_pos_w=SimpleNamespace(torch=torch.zeros(3, 1, 3)), + body_quat_w=SimpleNamespace(torch=torch.tensor([[[0.0, 0.0, 0.0, 1.0]]]).expand(3, -1, -1)), + ), + find_joints=lambda names, preserve_order=False: resolve_matching_names(names, joint_names, preserve_order), + find_bodies=lambda name: ([0], [name]), ) env = SimpleNamespace( num_envs=3, device="cpu", cfg=stack_cfg, scene=scene, + sim=SimpleNamespace(is_playing=lambda: True), + max_episode_length=100, episode_length_buf=torch.full((3,), 3), step_dt=0.02, extras={}, ) - progress_cfg = stack_cfg.terminations.progress_context - context = progress_cfg.func(progress_cfg, env) - env.termination_manager = SimpleNamespace(get_term_cfg=lambda name: SimpleNamespace(func=context)) - success = stack_cfg.terminations.success + create_stack_reset_runtime_state(env) + env.termination_manager = TerminationManager(stack_cfg.terminations, env) reward = stack_cfg.rewards.success for _ in range(4): - context(env, **progress_cfg.params) - assert not success.func(env, **success.params).any() + assert not env.termination_manager.compute().any() + assert not reward.func(env, **reward.params).any() env.episode_length_buf += 1 - context(env, **progress_cfg.params) - assert success.func(env, **success.params).tolist() == [True, False, False] - torch.testing.assert_close(reward.func(env, **reward.params) * env.step_dt, torch.tensor([1.0, 0.0, 0.0])) - - context(env, **progress_cfg.params) + assert env.termination_manager.compute().tolist() == [True, False, False] + assert env.termination_manager.get_term("success").tolist() == [True, False, False] + torch.testing.assert_close( + reward.func(env, **reward.params) * env.step_dt * reward.weight, torch.tensor([2.0, 0.0, 0.0]) + ) + env.termination_manager.reset(env_ids=torch.tensor([0])) + assert env.extras["successes"].tolist() == [True, False, False] assert not reward.func(env, **reward.params).any() From 6737a61f67e649a94bc8eec060a05dc002ddd583 Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Wed, 18 Nov 2026 00:50:47 +0100 Subject: [PATCH 17/28] 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 18/28] 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 fdcb11276fe73571a67f2bdefe7d557722e169a9 Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Wed, 18 Nov 2026 00:51:15 +0100 Subject: [PATCH 19/28] Match Franka teacher labels to configured action clipping --- .../config/franka/agents/distillation.py | 21 ++++++++++++++++++- .../contrib/stack/test_franka_stack_camera.py | 9 ++++---- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/agents/distillation.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/agents/distillation.py index 7d6527a327c4..d88b0a9571a7 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/agents/distillation.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/agents/distillation.py @@ -7,16 +7,35 @@ from __future__ import annotations +from typing import TYPE_CHECKING, cast + import torch from rsl_rl.algorithms import Distillation from tensordict import TensorDict +if TYPE_CHECKING: + from rsl_rl.env import VecEnv + + from isaaclab_rl.rsl_rl import RslRlVecEnvWrapper + class ClippedTeacherDistillation(Distillation): """Match teacher labels to the stack runner's action bounds.""" + _clip_actions: float | None + + @staticmethod + def construct_algorithm(obs: TensorDict, env: VecEnv, cfg: dict, device: str) -> ClippedTeacherDistillation: + """Build the distillation algorithm using the training wrapper's action bound.""" + algorithm = cast(ClippedTeacherDistillation, Distillation.construct_algorithm(obs, env, cfg, device)) + algorithm._clip_actions = cast("RslRlVecEnvWrapper", env).clip_actions + return algorithm + def act(self, obs: TensorDict) -> torch.Tensor: """Collect a student action and clamp its teacher label to the action contract.""" actions = super().act(obs) - self.transition.privileged_actions = self.transition.privileged_actions.clamp(-1.0, 1.0) + if self._clip_actions is not None: + self.transition.privileged_actions = self.transition.privileged_actions.clamp( + -self._clip_actions, self._clip_actions + ) return actions diff --git a/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_camera.py b/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_camera.py index d7c9a076e834..0b8aa0f6a7fa 100644 --- a/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_camera.py +++ b/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_camera.py @@ -42,10 +42,11 @@ def test_episode_camera_noise_resamples_only_reset_environments() -> None: def test_camera_student_loads_the_ppo_actor_and_uses_clipped_teacher_labels() -> None: """A native PPO actor checkpoint is a teacher, while the student runs on RGB and proprioception.""" pytest.importorskip("rsl_rl") - from rsl_rl.algorithms import Distillation from rsl_rl.models import MLPModel from tensordict import TensorDict + from isaaclab_tasks.contrib.stack.config.franka.agents.distillation import ClippedTeacherDistillation + state_task = "IsaacContrib-Stack-Cube-Franka-RL" student_task = "IsaacContrib-Stack-Cube-Franka-RL-Camera-Distillation" state_cfg = load_cfg_from_registry(state_task, "rsl_rl_cfg_entry_point") @@ -67,13 +68,13 @@ def test_camera_student_loads_the_ppo_actor_and_uses_clipped_teacher_labels() -> visual_obs = TensorDict({"policy": torch.zeros(1, 33), "base_image": torch.zeros(1, 3, 128, 128)}, [1]) camera_obs = visual_obs.clone().set("privileged", state) distillation_cfg["multi_gpu"] = None - env_spec = SimpleNamespace(num_actions=8, num_envs=1) - algorithm = Distillation.construct_algorithm(camera_obs, env_spec, distillation_cfg, device="cpu") + env_spec = SimpleNamespace(num_actions=8, num_envs=1, clip_actions=0.5) + algorithm = ClippedTeacherDistillation.construct_algorithm(camera_obs, env_spec, distillation_cfg, device="cpu") algorithm.load({"actor_state_dict": state_actor.state_dict()}, load_cfg=None, strict=True) with torch.no_grad(): assert algorithm.get_policy()(visual_obs).shape == (1, 8) algorithm.act(camera_obs) - expected_labels = torch.tensor([[-1.0, 1.0, 0.25, 0, 0, 0, 0, 0]]) + expected_labels = torch.tensor([[-0.5, 0.5, 0.25, 0, 0, 0, 0, 0]]) torch.testing.assert_close(algorithm.transition.privileged_actions, expected_labels) From ffa28b2313075451e6da5cce3c0cf9f650672cf6 Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Wed, 18 Nov 2026 00:51:41 +0100 Subject: [PATCH 20/28] Use one event to restore the Franka stack --- .../contrib/stack/config/franka/stack_rl_env_cfg.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_rl_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_rl_env_cfg.py index 082e30c03fc6..3c5f99bb1e32 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_rl_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_rl_env_cfg.py @@ -36,9 +36,6 @@ class EventCfg: """Reset from a shared cache of validated full-task stack states.""" - # Restore the authored robot root state before applying sampled joints and cubes. - reset_all = EventTerm(func=mdp.reset_scene_to_default, mode="reset") - reset_from_state_buffer = EventTerm( func=mdp.StackResetStateTable, mode="reset", From 360b42601aa6a0cc679ff804ede343a07e2d903d Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Wed, 18 Nov 2026 00:52:01 +0100 Subject: [PATCH 21/28] Clarify the teacher checkpoint required for camera distillation --- docs/source/isaaclab/contrib_stacking.rst | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/source/isaaclab/contrib_stacking.rst b/docs/source/isaaclab/contrib_stacking.rst index edf2f5c543fc..3e5d9f1a6d8d 100644 --- a/docs/source/isaaclab/contrib_stacking.rst +++ b/docs/source/isaaclab/contrib_stacking.rst @@ -66,7 +66,9 @@ identify the intended stacking order. actor using a compatible state PPO checkpoint as its frozen teacher. Teacher labels use the same action clipping as the student. The teacher uses the state task's 100-input observation order, so older 109-input -checkpoints require retraining. +checkpoints require retraining. Add ``--checkpoint`` with the path to the +teacher when starting distillation from the environment browser's base +training command. .. code-block:: bash From 14363a481f1c60423302f61887f6e05cb2a407b3 Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Wed, 18 Nov 2026 00:54:02 +0100 Subject: [PATCH 22/28] 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 23/28] 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 24/28] 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 f0bf3a27392b234d113c02400d3d27bd00f8f0fd Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Wed, 18 Nov 2026 01:20:26 +0100 Subject: [PATCH 25/28] Address Franka state stacking review findings --- .../stack/config/franka/franka_robot_cfg.py | 72 ----------------- .../stack/config/franka/stack_rl_env_cfg.py | 80 ++++++++++++++----- .../contrib/stack/mdp/__init__.pyi | 4 +- .../contrib/stack/mdp/goal_context.py | 23 +++--- .../contrib/stack/mdp/observations.py | 57 +++++++------ .../contrib/stack/mdp/rewards.py | 45 ++++++----- .../contrib/stack/mdp/robot_state.py | 11 ++- .../contrib/stack/mdp/terminations.py | 47 ++++++----- .../contrib/stack/test_franka_stack_state.py | 56 +++++++++++-- 9 files changed, 214 insertions(+), 181 deletions(-) delete mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/franka_robot_cfg.py diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/franka_robot_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/franka_robot_cfg.py deleted file mode 100644 index 216325984c9c..000000000000 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/franka_robot_cfg.py +++ /dev/null @@ -1,72 +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 - -"""Task-specific Franka configuration for cube stacking.""" - -from isaaclab.actuators import ImplicitActuatorCfg -from isaaclab.assets import ArticulationCfg -from isaaclab.utils import clone - -from isaaclab_assets.robots.franka import FRANKA_PANDA_CFG - -FRANKA_PANDA_DEXSUITE_CFG = clone(FRANKA_PANDA_CFG) -FRANKA_PANDA_DEXSUITE_CFG.spawn.variants["Physics"] = "mujoco" -FRANKA_PANDA_DEXSUITE_CFG.init_state = ArticulationCfg.InitialStateCfg( - joint_pos={ - "panda_joint1": 0.0444, - "panda_joint2": -0.1894, - "panda_joint3": -0.1107, - "panda_joint4": -2.5148, - "panda_joint5": 0.0044, - "panda_joint6": 2.3775, - "panda_joint7": 0.6952, - "panda_finger_joint.*": 0.04, - }, -) -# Keep the shared asset's passive mimic follower; tune only the active drives. -FRANKA_PANDA_DEXSUITE_CFG.actuators.update( - { - "panda_arm": ImplicitActuatorCfg( - joint_names_expr=["panda_joint[1-7]"], - joint_effort_limit={"panda_joint[1-4]": 87.0, "panda_joint[5-7]": 12.0}, - # Record the Panda's rated joint-speed envelope. MJWarp exposes but - # does not enforce these fields; action scaling, gains, effort limits, - # and armature determine the live Newton response. - joint_velocity_limit={"panda_joint[1-4]": 2.175, "panda_joint[5-7]": 2.61}, - stiffness={ - "panda_joint[1-4]": 600.0, - "panda_joint5": 250.0, - "panda_joint6": 150.0, - "panda_joint7": 50.0, - }, - damping={ - "panda_joint[1-4]": 50.0, - "panda_joint5": 30.0, - "panda_joint6": 25.0, - "panda_joint7": 15.0, - }, - armature={ - "panda_joint[1-2]": 0.6057, - "panda_joint[3-4]": 0.4625, - "panda_joint[5-7]": 0.2055, - }, - viscous_friction=0.0, - ), - "panda_hand": ImplicitActuatorCfg( - joint_names_expr=["panda_finger_joint1"], - joint_effort_limit=70.0, - joint_velocity_limit=2.0, - stiffness=350.0, - damping=175.0, - armature=0.1, - viscous_friction=0.0, - ), - } -) -"""DexSuite-calibrated Franka with physical gravity enabled. - -The arm controller combines these joint-impedance gains with configuration- -dependent gravity feedforward in the stack task's action term. -""" diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_rl_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_rl_env_cfg.py index 3c5f99bb1e32..4791dee72f51 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_rl_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_rl_env_cfg.py @@ -11,7 +11,8 @@ from isaaclab_newton.sim.schemas import NewtonMaterialPropertiesCfg import isaaclab.sim as sim_utils -from isaaclab.assets import AssetBaseCfg +from isaaclab.actuators import ImplicitActuatorCfg +from isaaclab.assets import ArticulationCfg, AssetBaseCfg from isaaclab.managers import CurriculumTermCfg as CurrTerm from isaaclab.managers import EventTermCfg as EventTerm from isaaclab.managers import ObservationGroupCfg as ObsGroup @@ -25,11 +26,12 @@ from isaaclab_tasks.utils import SuccessMonitorCfg, preset +from isaaclab_assets.robots.franka import FRANKA_PANDA_CFG + from ... import mdp from ...constants import FRANKA_STACK_ARM_WORKSPACE_LOWER, FRANKA_STACK_ARM_WORKSPACE_UPPER from ...spawners import ColoredCuboidCfg from ...stack_env_cfg import StackCommonTerminationsCfg, StackEnvCfg, apply_default_semantics -from .franka_robot_cfg import FRANKA_PANDA_DEXSUITE_CFG @configclass @@ -180,9 +182,7 @@ class FrankaStackTerminationsCfg(StackCommonTerminationsCfg): params={"robot_cfg": SceneEntityCfg("robot", joint_names=["panda_joint.*"])}, ) nonfinite_cube_state = DoneTerm(func=mdp.nonfinite_cube_state) - cube_workspace_invalid = DoneTerm( - func=mdp.cube_out_of_workspace, - ) + cube_workspace_invalid = DoneTerm(func=mdp.CubeOutOfWorkspace) @configclass @@ -198,9 +198,61 @@ class FrankaCubeStackRLEnvCfg(StackEnvCfg): def __post_init__(self) -> None: super().__post_init__() - self.scene.robot = FRANKA_PANDA_DEXSUITE_CFG.replace( - prim_path="{ENV_REGEX_NS}/Robot", + robot = FRANKA_PANDA_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + robot.spawn.variants["Physics"] = "mujoco" + robot.init_state = ArticulationCfg.InitialStateCfg( + joint_pos={ + "panda_joint1": 0.0444, + "panda_joint2": -0.1894, + "panda_joint3": -0.1107, + "panda_joint4": -2.5148, + "panda_joint5": 0.0044, + "panda_joint6": 2.3775, + "panda_joint7": 0.6952, + "panda_finger_joint.*": 0.04, + }, + ) + # Keep the shared asset's passive mimic follower; tune only the active drives. + robot.actuators.update( + { + "panda_arm": ImplicitActuatorCfg( + joint_names_expr=["panda_joint[1-7]"], + joint_effort_limit={"panda_joint[1-4]": 87.0, "panda_joint[5-7]": 12.0}, + # Record the Panda's rated joint-speed envelope. MJWarp exposes but + # does not enforce these fields; action scaling, gains, effort limits, + # and armature determine the live Newton response. + joint_velocity_limit={"panda_joint[1-4]": 2.175, "panda_joint[5-7]": 2.61}, + stiffness={ + "panda_joint[1-4]": 600.0, + "panda_joint5": 250.0, + "panda_joint6": 150.0, + "panda_joint7": 50.0, + }, + damping={ + "panda_joint[1-4]": 50.0, + "panda_joint5": 30.0, + "panda_joint6": 25.0, + "panda_joint7": 15.0, + }, + armature={ + "panda_joint[1-2]": 0.6057, + "panda_joint[3-4]": 0.4625, + "panda_joint[5-7]": 0.2055, + }, + viscous_friction=0.0, + ), + "panda_hand": ImplicitActuatorCfg( + joint_names_expr=["panda_finger_joint1"], + joint_effort_limit=70.0, + joint_velocity_limit=2.0, + stiffness=350.0, + damping=175.0, + armature=0.1, + viscous_friction=0.0, + ), + } ) + self.scene.robot = robot apply_default_semantics(self.scene) self.gripper_joint_names = ["panda_finger_.*"] self.gripper_open_val = 0.04 @@ -235,12 +287,7 @@ def __post_init__(self) -> None: self.sim.gravity = (0.0, 0.0, -9.81) self.scene.robot.spawn.rigid_props.disable_gravity = False - # Use MJWarp only as the rigid-body constraint solver. Contact - # generation is delegated to Newton's external collision pipeline. - # The Franka plus three cubes reached 148 constraint rows in - # the 4,096-environment reset distribution. Keep measured headroom so - # contacts are never silently truncated while avoiding an oversized - # contact buffer. + # Solve constraints with MJWarp and generate contacts with Newton's collision pipeline. physics = NewtonCfg( solver_cfg=MJWarpSolverCfg( solver="newton", @@ -251,13 +298,8 @@ def __post_init__(self) -> None: cone="elliptic", use_mujoco_contacts=False, ), - # Match the fast, stable Newton Cube Lift integration cadence: - # two 5 ms solver steps per 10 ms physics tick. Ten 1 ms substeps - # were stable but made collection roughly eight times slower. + # Refresh contacts for each 5 ms substep so a released tower can settle. num_substeps=2, - # Refresh external contacts for every 5 ms solver step. Reusing - # one contact set for the full 10 ms tick is sufficient for Lift, - # but lets a released three-cube tower drift or tip. collision_decimation=1, use_cuda_graph=True, collision_cfg=NewtonCollisionPipelineCfg( diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/__init__.pyi b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/__init__.pyi index 42a353b48f16..6bdd499d0a94 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/__init__.pyi +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/__init__.pyi @@ -4,6 +4,7 @@ # SPDX-License-Identifier: BSD-3-Clause __all__ = [ + "CubeOutOfWorkspace", "ResetBufferedGripperActionCfg", "StableOrderInvariantStackGoal", "StackResetLearningProgress", @@ -13,7 +14,6 @@ __all__ = [ "WorkspaceBoundedRelativeJointPositionActionCfg", "action_term_l2", "cube_orientations_in_world_frame", - "cube_out_of_workspace", "cube_poses_in_base_frame", "cube_positions_in_world_frame", "cubes_stacked", @@ -73,7 +73,7 @@ from .rewards import ( stack_success_pulse, ) from .terminations import ( - cube_out_of_workspace, + CubeOutOfWorkspace, cubes_stacked, nonfinite_cube_state, nonfinite_robot_state, diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/goal_context.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/goal_context.py index d588237ac960..9ab7a0852e98 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/goal_context.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/goal_context.py @@ -15,8 +15,7 @@ from isaaclab.managers import ManagerTermBase, SceneEntityCfg, TerminationTermCfg from .rewards import ( - _gripper_joint_positions, - _order_invariant_cube_state, + _resolve_finger_joint_ids, order_invariant_stack_progress, role_conditioned_stack_potential, ) @@ -65,6 +64,7 @@ def __init__(self, cfg: TerminationTermCfg, env: ManagerBasedRLEnv): super().__init__(cfg, env) self._stable_steps = torch.zeros(env.num_envs, dtype=torch.long, device=env.device) self._reported_success = torch.zeros_like(self.ever_success) + self._finger_joint_ids = _resolve_finger_joint_ids(env, env.scene["robot"]) def reset(self, env_ids: Sequence[int] | None = None) -> None: """Clear the stability dwell counter for reset environments.""" @@ -101,17 +101,12 @@ def __call__( height_threshold=height_threshold, cube_height=cube_height, ) - _, velocities = _order_invariant_cube_state( - env, - ( - SceneEntityCfg("cube_1"), - SceneEntityCfg("cube_2"), - SceneEntityCfg("cube_3"), - ), + velocities = torch.stack( + [env.scene[name].data.root_vel_w.torch[:, :3] for name in ("cube_1", "cube_2", "cube_3")], dim=1 ) - slow = torch.amax(torch.abs(velocities[..., :3]), dim=(1, 2)) < maximum_cube_velocity + slow = torch.amax(torch.abs(velocities), dim=(1, 2)) < maximum_cube_velocity robot: Articulation = env.scene["robot"] - released = (_gripper_joint_positions(env, robot) > minimum_finger_release_position).all(dim=1) + released = (robot.data.joint_pos.torch[:, self._finger_joint_ids] > minimum_finger_release_position).all(dim=1) stable = (stack_progress >= 2.0) & slow & released & (env.episode_length_buf >= minimum_episode_steps) self._stable_steps = torch.where(stable, self._stable_steps + 1, torch.zeros_like(self._stable_steps)) self._update_success(self._stable_steps >= hold_steps) @@ -142,6 +137,7 @@ def __init__(self, cfg: TerminationTermCfg, env: ManagerBasedRLEnv): "cube_height", ) self._potential_kwargs = {name: cfg.params[name] for name in potential_param_names if name in cfg.params} + self._finger_joint_ids = _resolve_finger_joint_ids(env, env.scene[cfg.params["robot_cfg"].name]) def reset(self, env_ids: Sequence[int] | None = None) -> None: """Set a non-free target from the newly sampled physical row.""" @@ -150,13 +146,15 @@ def reset(self, env_ids: Sequence[int] | None = None) -> None: super().reset(env_ids) initial = role_conditioned_stack_potential( self._env, + finger_joint_ids=self._finger_joint_ids, + env_ids=env_ids, **self._potential_kwargs, ) reset_state = get_stack_reset_runtime_state(self._env) row_target = reset_state.target_potentials[env_ids] self._target_potential[env_ids] = torch.maximum( row_target, - initial[env_ids] + 0.25, + initial + 0.25, ).clamp_max(10.0) def __call__( @@ -181,6 +179,7 @@ def __call__( xy_threshold=xy_threshold, height_threshold=height_threshold, cube_height=cube_height, + finger_joint_ids=self._finger_joint_ids, ) reached = (current >= self._target_potential) & (env.episode_length_buf >= minimum_episode_steps) self._update_success(reached) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/observations.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/observations.py index e6b2841b4a50..6b6bba100b60 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/observations.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/observations.py @@ -218,6 +218,12 @@ def franka_ee_velocity( ) +def joint_position_target(env: ManagerBasedRLEnv, robot_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor: + """Return commands for the selected robot joint positions [m or rad].""" + robot: Articulation = env.scene[robot_cfg.name] + return robot.actuators.target_command.position.torch[:, robot_cfg.joint_ids] + + def role_conditioned_stack_obs( env: ManagerBasedRLEnv, cube_cfgs: tuple[SceneEntityCfg, ...] = ( @@ -232,19 +238,22 @@ def role_conditioned_stack_obs( xy_threshold: float = 0.025, height_threshold: float = 0.012, ) -> torch.Tensor: - """Return stable base/side-role tracks with randomized cube colors. - - The reset table stores one episode-long mapping from physical stack roles - to cube assets. Gathering through that mapping makes the input exactly - invariant to reset-time color permutations while keeping each role in a - stable slot through grasp, lift, and placement. Role zero is the spatially - central base; roles one and two are interchangeable side cubes. - - The 64-entry layout contains role-local positions, tool-relative - positions, up axes, spatial velocities, every directed pair-placement - error, and stack progress. + """Return the published 64-value cube state in reset-assigned role order. + + The reset fixes an episode-long mapping from cube assets to the base and + two movable roles. Changing the color assignment leaves these values + unchanged when the physical states stay with their roles. + + Returns: + Tensor of shape ``(num_envs, 64)``. Columns contain positions from the + environment origin (9 m), positions from the tool center (9 m), cube + local z axes (9 unitless), linear and angular velocities within each + role (18 m/s and rad/s), directed placement errors (18 m), and half the + number of stacked pairs (1 unitless). All vectors use world-aligned axes. + The placement errors are ordered by upper role then lower role, omitting + identical roles, and point from the upper cube to its target on the lower. """ - from .rewards import order_invariant_stack_progress + from .rewards import _stack_progress_from_positions reset_state = get_stack_reset_runtime_state(env) @@ -255,8 +264,7 @@ def role_conditioned_stack_obs( role_to_cube = reset_state.role_to_cube def by_role(values: torch.Tensor) -> torch.Tensor: - gather_index = role_to_cube.view(env.num_envs, 3, *([1] * (values.ndim - 2))).expand_as(values) - return torch.gather(values, 1, gather_index) + return values.gather(1, role_to_cube.unsqueeze(-1).expand_as(values)) local_positions = by_role(positions) - env.scene.env_origins.unsqueeze(1) role_quaternions = by_role(quaternions) @@ -266,29 +274,18 @@ def by_role(values: torch.Tensor) -> torch.Tensor: up_axes = rotation[..., 2] tool_relative = local_positions - (tool_position - env.scene.env_origins).unsqueeze(1) - pair_errors = [] vertical_offset = local_positions.new_tensor((0.0, 0.0, cube_height)) - for upper_id in range(3): - for lower_id in range(3): - if upper_id != lower_id: - pair_errors.append(local_positions[:, lower_id] + vertical_offset - local_positions[:, upper_id]) - progress = ( - order_invariant_stack_progress( - env, - cube_cfgs=cube_cfgs, - xy_threshold=xy_threshold, - height_threshold=height_threshold, - cube_height=cube_height, - ).unsqueeze(1) - / 2.0 - ) + upper_roles = (0, 0, 1, 1, 2, 2) + lower_roles = (1, 2, 0, 2, 0, 1) + pair_errors = local_positions[:, lower_roles] + vertical_offset - local_positions[:, upper_roles] + progress = _stack_progress_from_positions(positions, xy_threshold, height_threshold, cube_height).unsqueeze(1) / 2.0 return torch.cat( ( local_positions.flatten(start_dim=1), tool_relative.flatten(start_dim=1), up_axes.flatten(start_dim=1), role_velocities.flatten(start_dim=1), - torch.cat(pair_errors, dim=1), + pair_errors.flatten(start_dim=1), progress, ), dim=1, diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/rewards.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/rewards.py index efc653ca4c0c..21cf2d107a37 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/rewards.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/rewards.py @@ -7,6 +7,7 @@ from __future__ import annotations +from collections.abc import Sequence from typing import TYPE_CHECKING import torch @@ -18,7 +19,7 @@ from .terminations import _cube_pair_is_aligned if TYPE_CHECKING: - from isaaclab.assets import Articulation, RigidObject + from isaaclab.assets import Articulation from isaaclab.envs import ManagerBasedRLEnv @@ -71,12 +72,12 @@ def irrecoverable_stack_failure( return failed.float() / max(float(env.step_dt), 1.0e-6) -def _gripper_joint_positions(env: ManagerBasedRLEnv, robot: Articulation) -> torch.Tensor: - """Read both fingers of the Franka parallel gripper.""" +def _resolve_finger_joint_ids(env: ManagerBasedRLEnv, robot: Articulation) -> list[int]: + """Resolve both fingers of the Franka parallel gripper.""" joint_ids, _ = robot.find_joints(env.cfg.gripper_joint_names) if len(joint_ids) != 2: raise ValueError("Franka stack gripper thresholds require a two-finger parallel gripper.") - return robot.data.joint_pos.torch[:, joint_ids] + return joint_ids _CUBE_PERMUTATIONS = ( @@ -89,15 +90,13 @@ def _gripper_joint_positions(env: ManagerBasedRLEnv, robot: Articulation) -> tor ) -def _order_invariant_cube_state( +def _cube_positions( env: ManagerBasedRLEnv, cube_cfgs: tuple[SceneEntityCfg, ...], -) -> tuple[torch.Tensor, torch.Tensor]: - """Return cube COM positions [m] and spatial velocities [m/s, rad/s].""" - cubes: tuple[RigidObject, ...] = tuple(env.scene[cfg.name] for cfg in cube_cfgs) - positions = torch.stack(tuple(cube.data.root_pos_w.torch for cube in cubes), dim=1) - velocities = torch.stack(tuple(cube.data.root_vel_w.torch for cube in cubes), dim=1) - return positions, velocities + env_ids: Sequence[int] | torch.Tensor | slice = slice(None), +) -> torch.Tensor: + """Read selected world-frame cube positions [m].""" + return torch.stack([env.scene[cfg.name].data.root_pos_w.torch[env_ids] for cfg in cube_cfgs], dim=1) def order_invariant_stack_progress( @@ -112,12 +111,17 @@ def order_invariant_stack_progress( cube_height: float = 0.04, ) -> torch.Tensor: """Return zero, one, or two stacked pairs without assigning cube roles.""" - positions, _ = _order_invariant_cube_state(env, cube_cfgs) + return _stack_progress_from_positions(_cube_positions(env, cube_cfgs), xy_threshold, height_threshold, cube_height) + + +def _stack_progress_from_positions( + positions: torch.Tensor, xy_threshold: float, height_threshold: float, cube_height: float +) -> torch.Tensor: delta = positions[:, :, None, :] - positions[:, None, :, :] pair_is_stacked = _cube_pair_is_aligned(delta, xy_threshold, cube_height, height_threshold, True) pair_exists = pair_is_stacked.flatten(start_dim=1).any(dim=1) - complete = torch.zeros(env.num_envs, dtype=torch.bool, device=env.device) + complete = torch.zeros_like(pair_exists) for base_id, middle_id, top_id in _CUBE_PERMUTATIONS: complete |= pair_is_stacked[:, middle_id, base_id] & pair_is_stacked[:, top_id, middle_id] return pair_exists.float() + complete.float() @@ -248,8 +252,11 @@ def role_conditioned_stack_potential( xy_threshold: float = 0.025, height_threshold: float = 0.012, cube_height: float = 0.04, + *, + finger_joint_ids: Sequence[int] | None = None, + env_ids: Sequence[int] | torch.Tensor | slice = slice(None), ) -> torch.Tensor: - """Return fixed-center-base progress with either side-cube order. + """Return progress with the reset-assigned base and either movable cube order. Reset-time color permutations are gathered into stable physical roles. Role zero remains the base while the maximum over ``1→2`` and ``2→1`` @@ -257,13 +264,15 @@ def role_conditioned_stack_potential( """ reset_state = get_stack_reset_runtime_state(env) - positions, _ = _order_invariant_cube_state(env, cube_cfgs) - role_to_cube = reset_state.role_to_cube.long() + positions = _cube_positions(env, cube_cfgs, env_ids) + role_to_cube = reset_state.role_to_cube[env_ids] gather_index = role_to_cube.unsqueeze(-1).expand(-1, -1, 3) role_positions = torch.gather(positions, 1, gather_index) robot: Articulation = env.scene[robot_cfg.name] - ee_position, _ = end_effector_pose(env, robot_cfg, tool_body_name, tool_offset) - finger_positions = _gripper_joint_positions(env, robot) + ee_position, _ = end_effector_pose(env, robot_cfg, tool_body_name, tool_offset, env_ids=env_ids) + if finger_joint_ids is None: + finger_joint_ids = _resolve_finger_joint_ids(env, robot) + finger_positions = robot.data.joint_pos.torch[env_ids][:, finger_joint_ids] gripper_release_progress = ((finger_positions.amin(dim=1) - 0.020) / (0.024 - 0.020)).clamp(0.0, 1.0) gripper_released = (finger_positions > 0.023).all(dim=1) gripper_closed = (finger_positions < maximum_grasp_finger_position).all(dim=1) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/robot_state.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/robot_state.py index 30b852ed52a4..0ed3eaf1c721 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/robot_state.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/robot_state.py @@ -7,6 +7,7 @@ from __future__ import annotations +from collections.abc import Sequence from typing import TYPE_CHECKING import torch @@ -51,13 +52,17 @@ def end_effector_pose( robot_cfg: SceneEntityCfg = SceneEntityCfg("robot"), body_name: str = "panda_hand", body_offset: tuple[float, float, float] = (0.0, 0.0, 0.1034), + *, + env_ids: Sequence[int] | torch.Tensor | slice = slice(None), ) -> tuple[torch.Tensor, torch.Tensor]: """Return a configured tool-center position [m] and orientation.""" robot, body_id, tool_offset = _end_effector_cache_entry(env, robot_cfg, body_name, body_offset) - body_position = robot.data.body_pos_w.torch[:, body_id] - body_orientation = robot.data.body_quat_w.torch[:, body_id] - tool_position = body_position + math_utils.quat_apply(body_orientation, tool_offset.expand(env.num_envs, -1)) + body_position = robot.data.body_pos_w.torch[env_ids, body_id] + body_orientation = robot.data.body_quat_w.torch[env_ids, body_id] + tool_position = body_position + math_utils.quat_apply( + body_orientation, tool_offset.expand(body_orientation.shape[0], -1) + ) return tool_position, body_orientation 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 ac5f301aa45a..8bd6033af21d 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/terminations.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/terminations.py @@ -13,7 +13,7 @@ import torch import warp as wp -from isaaclab.managers import SceneEntityCfg +from isaaclab.managers import ManagerTermBase, SceneEntityCfg, TerminationTermCfg if TYPE_CHECKING: from isaaclab.assets import Articulation, RigidObject @@ -184,22 +184,29 @@ def nonfinite_cube_state( return invalid -def cube_out_of_workspace( - env: ManagerBasedRLEnv, - cube_cfgs: tuple[SceneEntityCfg, ...] = ( - SceneEntityCfg("cube_1"), - SceneEntityCfg("cube_2"), - SceneEntityCfg("cube_3"), - ), - workspace_lower: tuple[float, float, float] = (-0.2, -0.7, -0.1), - workspace_upper: tuple[float, float, float] = (1.2, 0.7, 1.0), -) -> torch.Tensor: - """Detect cubes outside the local task workspace [m].""" - lower = torch.tensor(workspace_lower, dtype=torch.float32, device=env.device) - upper = torch.tensor(workspace_upper, dtype=torch.float32, device=env.device) - invalid = torch.zeros(env.scene.env_origins.shape[0], dtype=torch.bool, device=env.device) - for cube_cfg in cube_cfgs: - cube: RigidObject = env.scene[cube_cfg.name] - position = cube.data.root_pos_w.torch - env.scene.env_origins - invalid |= ((position < lower) | (position > upper)).any(dim=1) - return invalid +class CubeOutOfWorkspace(ManagerTermBase): + """Detect cubes outside fixed environment-local bounds [m].""" + + def __init__(self, cfg: TerminationTermCfg, env: ManagerBasedRLEnv): + super().__init__(cfg, env) + self._lower = torch.tensor(cfg.params["workspace_lower"], dtype=torch.float32, device=env.device) + self._upper = torch.tensor(cfg.params["workspace_upper"], dtype=torch.float32, device=env.device) + + def __call__( + self, + env: ManagerBasedRLEnv, + cube_cfgs: tuple[SceneEntityCfg, ...] = ( + SceneEntityCfg("cube_1"), + SceneEntityCfg("cube_2"), + SceneEntityCfg("cube_3"), + ), + workspace_lower: tuple[float, float, float] = (-0.2, -0.7, -0.1), + workspace_upper: tuple[float, float, float] = (1.2, 0.7, 1.0), + ) -> torch.Tensor: + """Return whether any configured cube has left its environment's workspace.""" + invalid = torch.zeros(env.scene.env_origins.shape[0], dtype=torch.bool, device=env.device) + for cube_cfg in cube_cfgs: + cube: RigidObject = env.scene[cube_cfg.name] + position = cube.data.root_pos_w.torch - env.scene.env_origins + invalid |= ((position < self._lower) | (position > self._upper)).any(dim=1) + return invalid diff --git a/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_state.py b/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_state.py index 4c6cb2f03579..be1f01ebf4ee 100644 --- a/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_state.py +++ b/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_state.py @@ -14,6 +14,7 @@ from isaaclab.utils.string import resolve_matching_names from isaaclab_tasks.contrib.stack import mdp +from isaaclab_tasks.contrib.stack.config.franka.stack_rl_env_cfg import FrankaCubeStackRLEnvCfg from isaaclab_tasks.contrib.stack.mdp.runtime_state import create_stack_reset_runtime_state from isaaclab_tasks.utils import parse_env_cfg @@ -21,14 +22,14 @@ @pytest.fixture(scope="module") -def stack_cfg(): +def stack_cfg() -> FrankaCubeStackRLEnvCfg: """Load the registered state task without starting a renderer.""" cfg = parse_env_cfg("IsaacContrib-Stack-Cube-Franka-RL", device="cpu", num_envs=3) cfg.validate_config() return cfg -def test_state_policy_observation_order_matches_published_checkpoints(stack_cfg): +def test_state_policy_observation_order_matches_published_checkpoints(stack_cfg: FrankaCubeStackRLEnvCfg) -> None: policy = stack_cfg.observations.policy assert [name for name, term in vars(policy).items() if isinstance(term, ObservationTermCfg)] == [ "actions", @@ -41,14 +42,59 @@ def test_state_policy_observation_order_matches_published_checkpoints(stack_cfg) ] -def test_explicit_newton_selector_keeps_the_task_physics(stack_cfg): +def test_cube_state_preserves_published_directed_pair_order(stack_cfg: FrankaCubeStackRLEnvCfg) -> None: + orientations = torch.tensor([[0.0, 0.0, 0.0, 1.0]]) + scene = { + "robot": SimpleNamespace( + data=SimpleNamespace( + body_pos_w=SimpleNamespace(torch=torch.zeros(1, 1, 3)), + body_quat_w=SimpleNamespace(torch=orientations.unsqueeze(1)), + ), + find_bodies=lambda name: ([0], [name]), + ) + } + for index, position in enumerate(((0.5, 0.7, 0.9), (0.0, 0.0, 0.0), (0.2, 0.3, 0.4)), start=1): + scene[f"cube_{index}"] = SimpleNamespace( + data=SimpleNamespace( + root_pos_w=SimpleNamespace(torch=torch.tensor([position])), + root_quat_w=SimpleNamespace(torch=orientations), + root_vel_w=SimpleNamespace(torch=torch.zeros(1, 6)), + ) + ) + + class Scene(dict): + env_origins = torch.zeros(1, 3) + + env = SimpleNamespace(num_envs=1, device="cpu", scene=Scene(scene)) + state = create_stack_reset_runtime_state(env) + state.role_to_cube[0] = torch.tensor([1, 2, 0]) + term = stack_cfg.observations.policy.object + observation = term.func(env, **term.params) + + assert observation.shape == (1, 64) + torch.testing.assert_close( + observation[0, 45:63].reshape(6, 3), + torch.tensor( + [ + [0.2, 0.3, 0.44], + [0.5, 0.7, 0.94], + [-0.2, -0.3, -0.36], + [0.3, 0.4, 0.54], + [-0.5, -0.7, -0.86], + [-0.3, -0.4, -0.46], + ] + ), + ) + + +def test_explicit_newton_selector_keeps_the_task_physics(stack_cfg: FrankaCubeStackRLEnvCfg) -> None: explicit = parse_env_cfg( "IsaacContrib-Stack-Cube-Franka-RL", device="cpu", num_envs=3, overrides=["physics=newton_mjwarp"] ) assert explicit.sim.physics == stack_cfg.sim.physics -def test_play_mode_selects_randomized_table_starts(stack_cfg): +def test_play_mode_selects_randomized_table_starts(stack_cfg: FrankaCubeStackRLEnvCfg) -> None: cfg = stack_cfg.copy() cfg.play_mode() @@ -57,7 +103,7 @@ def test_play_mode_selects_randomized_table_starts(stack_cfg): assert cfg.actions.gripper_action.force_close_steps == 0 -def test_success_requires_an_order_invariant_released_stack_held_at_rest(stack_cfg): +def test_success_requires_an_order_invariant_released_stack_held_at_rest(stack_cfg: FrankaCubeStackRLEnvCfg) -> None: class Scene(dict): env_origins = torch.zeros(3, 3) From 0c4b4d7b014270bdf43734aab0a36c94ab9e080d Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Wed, 18 Nov 2026 01:20:38 +0100 Subject: [PATCH 26/28] 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 c3f5ce37e5146bce53e931bb0033a50ce02f7f5d Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Wed, 18 Nov 2026 01:21:03 +0100 Subject: [PATCH 27/28] Derive Franka camera calibration from the configured pose --- .../franka/agents/rsl_rl_camera_ppo_cfg.py | 2 +- .../config/franka/stack_camera_rl_env_cfg.py | 7 +- .../contrib/stack/mdp/__init__.pyi | 4 +- .../contrib/stack/mdp/camera.py | 86 +++++++++---------- .../contrib/stack/mdp/camera_noise_cfg.py | 39 +++++++++ .../contrib/stack/test_franka_stack_camera.py | 35 +++++++- 6 files changed, 117 insertions(+), 56 deletions(-) create mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/camera_noise_cfg.py diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/agents/rsl_rl_camera_ppo_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/agents/rsl_rl_camera_ppo_cfg.py index d66bc2903c8e..871421eb1b1f 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/agents/rsl_rl_camera_ppo_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/agents/rsl_rl_camera_ppo_cfg.py @@ -38,7 +38,7 @@ class FrankaStackCameraPPORunnerCfg(FrankaStackPPORunnerCfg): experiment_name = "franka_stack_camera" obs_groups = {"actor": ["policy", "base_image"], "critic": ["privileged"]} actor = CAMERA_POLICY_CFG - # Use a smaller learning rate and more samples per batch for the visual encoder. + # Use a smaller learning rate and more samples per mini-batch for the visual encoder. algorithm = ALGORITHM_CFG.replace( entropy_coef=0.005, num_mini_batches=8, diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_camera_rl_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_camera_rl_env_cfg.py index 5d9499ba90d7..0d640b9dba31 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_camera_rl_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_camera_rl_env_cfg.py @@ -56,12 +56,12 @@ class CameraEventCfg(EventCfg): """Physical reset table plus fixed-per-environment camera calibration error.""" camera_calibration = EventTerm( - func=mdp.randomize_camera_calibration, + func=f"{mdp.__name__}.camera:randomize_camera_calibration", mode="startup", params={ "sensor_cfg": SceneEntityCfg("base_camera"), - "eye": (0.90, -0.55, 0.48), - "lookat": (0.48, 0.0, 0.08), + # Distance from the default camera offset to the look-at point. + "lookat_distance": 0.7993122, "eye_position_noise": (0.020, 0.020, 0.015), "lookat_position_noise": (0.015, 0.015, 0.010), }, @@ -137,7 +137,6 @@ class FrankaCubeStackCameraRLEnvCfg(FrankaCubeStackRLEnvCfg): """Stack from RGB and proprioception with no actor-side object state.""" scene: FrankaStackCameraSceneCfg = FrankaStackCameraSceneCfg( - # The 32-step rollout stores about 1.5 GiB of float RGB observations. num_envs=256, env_spacing=2.5, replicate_physics=True, diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/__init__.pyi b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/__init__.pyi index f23c39ebb5af..226dea6e179c 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/__init__.pyi +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/__init__.pyi @@ -47,7 +47,8 @@ __all__ = [ from isaaclab.envs.mdp import * # noqa: F403 from .actions_cfg import ResetBufferedGripperActionCfg, WorkspaceBoundedRelativeJointPositionActionCfg -from .camera import EpisodeCameraNoise, EpisodeCameraNoiseCfg, joint_position_target, randomize_camera_calibration +from .camera import EpisodeCameraNoise, randomize_camera_calibration +from .camera_noise_cfg import EpisodeCameraNoiseCfg from .curriculums import StackResetTableCurriculum from .goal_context import StableOrderInvariantStackGoal, StackResetLearningProgress from .observations import ( @@ -63,6 +64,7 @@ from .observations import ( instance_randomize_cube_orientations_in_world_frame, instance_randomize_cube_positions_in_world_frame, instance_randomize_object_obs, + joint_position_target, object_abs_obs_in_base_frame, object_grasped, object_obs, diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/camera.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/camera.py index e5ea9105fd56..8db6988b05fa 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/camera.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/camera.py @@ -7,20 +7,26 @@ from __future__ import annotations +import logging from collections.abc import Sequence from typing import TYPE_CHECKING import torch +from pxr import UsdGeom + from isaaclab.managers import SceneEntityCfg -from isaaclab.utils import configclass -from isaaclab.utils.noise import NoiseModel, NoiseModelCfg, UniformNoiseCfg +from isaaclab.utils import math as math_utils +from isaaclab.utils.noise import NoiseModel if TYPE_CHECKING: - from isaaclab.assets import Articulation from isaaclab.envs import ManagerBasedEnv from isaaclab.sensors import Camera + from .camera_noise_cfg import EpisodeCameraNoiseCfg + +logger = logging.getLogger(__name__) + class EpisodeCameraNoise(NoiseModel): """Apply episode-consistent photometric variation and per-frame sensor noise.""" @@ -73,40 +79,10 @@ def __call__(self, data: torch.Tensor) -> torch.Tensor: return super().__call__(data) -@configclass -class EpisodeCameraNoiseCfg(NoiseModelCfg): - """Episode-consistent camera randomization with small per-frame pixel noise.""" - - class_type: type[EpisodeCameraNoise] | str = EpisodeCameraNoise - """Noise-model implementation used by the observation manager.""" - - noise_cfg: UniformNoiseCfg = UniformNoiseCfg(n_min=-0.025, n_max=0.025) - """Per-frame additive pixel noise in normalized image units.""" - - exposure_range: tuple[float, float] = (0.75, 1.25) - """Uniform episode-level multiplicative exposure range.""" - - contrast_range: tuple[float, float] = (0.85, 1.15) - """Uniform episode-level contrast range around mid-gray.""" - - white_balance_range: tuple[float, float] = (0.90, 1.10) - """Uniform episode-level per-channel white-balance range.""" - - brightness_range: tuple[float, float] = (-0.05, 0.05) - """Uniform episode-level additive brightness range in normalized image units.""" - - -def joint_position_target(env: ManagerBasedEnv, robot_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor: - """Return commanded joint position targets [m or rad, depending on joint type].""" - robot: Articulation = env.scene[robot_cfg.name] - return robot.actuators.target_command.position.torch[:, robot_cfg.joint_ids] - - def randomize_camera_calibration( env: ManagerBasedEnv, env_ids: Sequence[int] | torch.Tensor | slice | None, - eye: tuple[float, float, float], - lookat: tuple[float, float, float], + lookat_distance: float, eye_position_noise: tuple[float, float, float], lookat_position_noise: tuple[float, float, float], sensor_cfg: SceneEntityCfg = SceneEntityCfg("base_camera"), @@ -119,8 +95,7 @@ def randomize_camera_calibration( env: The stack environment containing the camera sensor. env_ids: Environments whose camera poses are randomized, or ``None`` for every environment. - eye: Nominal camera position relative to each environment origin [m]. - lookat: Nominal look-at point relative to each environment origin [m]. + lookat_distance: Distance from the configured camera position to the nominal look-at point [m]. eye_position_noise: Independent uniform position-noise half-widths for the camera eye [m]. lookat_position_noise: Independent uniform position-noise half-widths @@ -135,15 +110,32 @@ def randomize_camera_calibration( return origins = env.scene.env_origins[resolved_env_ids] - eye_offset = origins.new_tensor(eye).expand(resolved_env_ids.numel(), -1) - lookat_offset = origins.new_tensor(lookat).expand(resolved_env_ids.numel(), -1) - eye_amplitude = origins.new_tensor(eye_position_noise) - lookat_amplitude = origins.new_tensor(lookat_position_noise) - eye_noise = (2.0 * torch.rand_like(eye_offset) - 1.0) * eye_amplitude - lookat_noise = (2.0 * torch.rand_like(lookat_offset) - 1.0) * lookat_amplitude - - camera.set_world_poses_from_view( - origins + eye_offset + eye_noise, - origins + lookat_offset + lookat_noise, - env_ids=resolved_env_ids, + eye_offset = origins.new_tensor(camera.cfg.offset.pos).unsqueeze(0) + orientation = math_utils.convert_camera_frame_orientation_convention( + origins.new_tensor(camera.cfg.offset.rot), origin=camera.cfg.offset.convention, target="opengl" + ) + camera_rotation = math_utils.matrix_from_quat(orientation) + lookat_offset = eye_offset - lookat_distance * camera_rotation[:, 2] + + eye_noise = (2.0 * torch.rand_like(origins) - 1.0) * origins.new_tensor(eye_position_noise) + lookat_noise = (2.0 * torch.rand_like(origins) - 1.0) * origins.new_tensor(lookat_position_noise) + eyes = origins + eye_offset + eye_noise + targets = origins + lookat_offset + lookat_noise + + # Preserve the configured roll relative to a stage-up look-at frame. + up_axis = UsdGeom.GetStageUpAxis(camera.stage) + nominal_view = math_utils.create_rotation_matrix_from_view(eye_offset, lookat_offset, up_axis, env.device) + roll = nominal_view.mT @ camera_rotation + views = math_utils.create_rotation_matrix_from_view(eyes, targets, up_axis, env.device) + valid = torch.isfinite(views).all(dim=(-2, -1)).nonzero(as_tuple=True)[0] + if valid.numel() == 0: + raise ValueError("Camera calibration requires distinct finite eye and look-at positions.") + skipped = resolved_env_ids.numel() - valid.numel() + if skipped: + logger.warning("Skipping %d camera poses with undefined look-at directions.", skipped) + camera.set_world_poses( + eyes[valid], + math_utils.quat_from_matrix(views[valid] @ roll), + env_ids=resolved_env_ids[valid], + convention="opengl", ) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/camera_noise_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/camera_noise_cfg.py new file mode 100644 index 000000000000..4b13b42a6923 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/camera_noise_cfg.py @@ -0,0 +1,39 @@ +# 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 + +"""Photometric noise configuration for Franka stack policies.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from isaaclab.utils import configclass +from isaaclab.utils.noise import NoiseModelCfg, UniformNoiseCfg + +if TYPE_CHECKING: + from .camera import EpisodeCameraNoise + + +@configclass +class EpisodeCameraNoiseCfg(NoiseModelCfg): + """Episode-consistent camera randomization with small per-frame pixel noise.""" + + class_type: type[EpisodeCameraNoise] | str = "{DIR}.camera:EpisodeCameraNoise" + """Noise-model implementation used by the observation manager.""" + + noise_cfg: UniformNoiseCfg = UniformNoiseCfg(n_min=-0.025, n_max=0.025) + """Per-frame additive pixel noise in normalized image units.""" + + exposure_range: tuple[float, float] = (0.75, 1.25) + """Uniform episode-level multiplicative exposure range.""" + + contrast_range: tuple[float, float] = (0.85, 1.15) + """Uniform episode-level contrast range around mid-gray.""" + + white_balance_range: tuple[float, float] = (0.90, 1.10) + """Uniform episode-level per-channel white-balance range.""" + + brightness_range: tuple[float, float] = (-0.05, 0.05) + """Uniform episode-level additive brightness range in normalized image units.""" diff --git a/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_camera.py b/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_camera.py index 0b8aa0f6a7fa..c384f95c8b71 100644 --- a/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_camera.py +++ b/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_camera.py @@ -6,20 +6,26 @@ """Camera randomization and teacher checkpoint behavior for Franka stacking.""" from types import SimpleNamespace +from unittest.mock import Mock import pytest import torch +from pxr import Usd + +from isaaclab.sensors import CameraCfg +from isaaclab.utils import instantiate from isaaclab.utils.noise import UniformNoiseCfg -from isaaclab_tasks.contrib.stack.mdp.camera import EpisodeCameraNoise, EpisodeCameraNoiseCfg +from isaaclab_tasks.contrib.stack.mdp.camera import randomize_camera_calibration +from isaaclab_tasks.contrib.stack.mdp.camera_noise_cfg import EpisodeCameraNoiseCfg from isaaclab_tasks.utils import load_cfg_from_registry pytestmark = pytest.mark.kitless def test_episode_camera_noise_resamples_only_reset_environments() -> None: - """An environment reset preserves the camera calibration of every other environment.""" + """An environment reset preserves episode photometric parameters in other environments.""" cfg = EpisodeCameraNoiseCfg( noise_cfg=UniformNoiseCfg(n_min=0.0, n_max=0.0), exposure_range=(0.5, 1.5), @@ -29,7 +35,7 @@ def test_episode_camera_noise_resamples_only_reset_environments() -> None: ) with torch.random.fork_rng(devices=[]): torch.manual_seed(7) - noise = EpisodeCameraNoise(cfg, num_envs=4, device="cpu") + noise = instantiate(cfg, num_envs=4, device="cpu") image = torch.ones(4, 3, 2, 2) before = noise(image) noise.reset(torch.tensor([1, 3])) @@ -39,6 +45,29 @@ def test_episode_camera_noise_resamples_only_reset_environments() -> None: assert torch.all((after[[1, 3]] != before[[1, 3]]).any(dim=(1, 2, 3))) +def test_camera_calibration_keeps_the_configured_pose_without_jitter() -> None: + """An edited camera offset controls the nominal pose, including roll, in the selected environment.""" + camera = SimpleNamespace( + cfg=CameraCfg(offset=CameraCfg.OffsetCfg(pos=(1.0, 2.0, 3.0), rot=(0.5, 0.5, 0.5, 0.5), convention="opengl")), + stage=Usd.Stage.CreateInMemory(), + set_world_poses=Mock(), + ) + env = SimpleNamespace( + device="cpu", + num_envs=2, + scene=SimpleNamespace(sensors={"base_camera": camera}, env_origins=torch.tensor([[0.0, 0, 0], [2.5, 0, 0]])), + ) + + randomize_camera_calibration(env, [1], 0.7993122, (0.0, 0.0, 0.0), (0.0, 0.0, 0.0)) + + camera.set_world_poses.assert_called_once() + (position, orientation), kwargs = camera.set_world_poses.call_args + torch.testing.assert_close(position, torch.tensor([[3.5, 2.0, 3.0]])) + torch.testing.assert_close(orientation * orientation[:, 3:].sign(), torch.full((1, 4), 0.5)) + torch.testing.assert_close(kwargs["env_ids"], torch.tensor([1])) + assert kwargs["convention"] == "opengl" + + def test_camera_student_loads_the_ppo_actor_and_uses_clipped_teacher_labels() -> None: """A native PPO actor checkpoint is a teacher, while the student runs on RGB and proprioception.""" pytest.importorskip("rsl_rl") From 42c30cdbb1eccde07a890123ca1b50d84e105d2b Mon Sep 17 00:00:00 2001 From: Maximilian Krause Date: Fri, 20 Nov 2026 11:57:06 +0100 Subject: [PATCH 28/28] 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})