diff --git a/docs/index.rst b/docs/index.rst index 88d11d1f843a..6ee0c0044601 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 4d9dd92ca4d5..4026a40bf284 100644 --- a/docs/source/_static/css/environment-browser.js +++ b/docs/source/_static/css/environment-browser.js @@ -143,6 +143,7 @@ ["IsaacContrib-Stack-Cube-Franka-IK-Rel-Skillgen", "", "isaacsim_physx,ovphysx", "", "", "environment-previews/franka_stack.jpg", false, {}, {}, "", null, ["||", "isaacsim_physx||", "ovphysx||"]], ["IsaacContrib-Stack-Cube-Franka-IK-Rel-Visuomotor", "", "isaacsim_physx,ovphysx", "", "", "environment-previews/franka_stack.jpg", false, {}, {}, "", null, ["||", "isaacsim_physx||", "ovphysx||"]], ["IsaacContrib-Stack-Cube-Franka-IK-Rel-Visuomotor-Cosmos", "", "isaacsim_physx,ovphysx", "", "", "environment-previews/franka_stack.jpg", false, {}, {}, "", null, ["||", "isaacsim_physx||", "ovphysx||"]], + ["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,ovphysx", "", "", "environment-previews/galbot_stack_cube.jpg", false, {}, {}, "", null, ["||", "isaacsim_physx||", "ovphysx||"]], ["IsaacContrib-Stack-Cube-Galbot-Left-Arm-Gripper-Visuomotor", "", "isaacsim_physx,ovphysx", "isaacsim_rtx,newton_optix,newton_warp,ovrtx", "", "environment-previews/galbot_stack_cube.jpg", false, {}, {}, "", null, ["||", "|newton_optix|", "|newton_warp|", "|ovrtx|", "isaacsim_physx||", "isaacsim_physx|isaacsim_rtx|", "isaacsim_physx|newton_optix|", "isaacsim_physx|newton_warp|", "ovphysx||", "ovphysx|newton_optix|", "ovphysx|newton_warp|", "ovphysx|ovrtx|"]], ["IsaacContrib-Stack-Cube-Galbot-Left-Arm-Gripper-Visuomotor-Joint-Position", "", "isaacsim_physx,ovphysx", "isaacsim_rtx,newton_optix,newton_warp,ovrtx", "", "environment-previews/galbot_stack_cube.jpg", false, {}, {}, "", null, ["||", "|newton_optix|", "|newton_warp|", "|ovrtx|", "isaacsim_physx||", "isaacsim_physx|isaacsim_rtx|", "isaacsim_physx|newton_optix|", "isaacsim_physx|newton_warp|", "ovphysx||", "ovphysx|newton_optix|", "ovphysx|newton_warp|", "ovphysx|ovrtx|"]], @@ -157,7 +158,7 @@ ["IsaacContrib-Stack-Cube-SO101-v0", "", "isaacsim_physx,ovphysx", "", "", "environment-previews/so101_stack.jpg", false, {}, {}, "", null, ["||", "isaacsim_physx||", "ovphysx||"]], ["IsaacContrib-Stack-Cube-UR10-Long-Suction-IK-Rel", "", "isaacsim_physx", "", "", "environment-previews/ur10_stack_surface_gripper.jpg", false, {}, {}, "", null, ["||", "isaacsim_physx||"]], ["IsaacContrib-Stack-Cube-UR10-Short-Suction-IK-Rel", "", "isaacsim_physx", "", "", "environment-previews/ur10_stack_surface_gripper.jpg", false, {}, {}, "", null, ["||", "isaacsim_physx||"]], - ["IsaacContrib-TableTop-PickPlace-Franka", "", "", "", "", "environment-previews/heterogeneous_tabletop.jpg"], + ["IsaacContrib-TableTop-PickPlace-Franka", "", "newton_mjwarp,newton_steel", "", "", "environment-previews/heterogeneous_tabletop.jpg", false, {}, {}, "", null, ["||", "newton_mjwarp||", "newton_steel||"]], ["IsaacContrib-TrackPositionNoObstacles-ARL-Robot-1", "rl_games,rsl_rl,skrl", "", "", "", "environments/previews/drone_arl/arl_robot_1_track_position_state_based.jpg"], ["IsaacContrib-Tracking-LocoManip-Digit", "rsl_rl", "isaacsim_physx,newton_mjwarp,ovphysx", "", "", "environment-previews/agility_digit_loco_manip.jpg", false, {}, {}, "", null, ["||", "isaacsim_physx||", "newton_mjwarp||", "ovphysx||"]], ["IsaacContrib-UR10-Particle-Push", "rsl_rl", "", "", "", "environment-previews/ur10_particle_push.jpg"], 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. 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..85045831cadf --- /dev/null +++ b/source/isaaclab_tasks/changelog.d/franka-stack-ppo.added.rst @@ -0,0 +1,2 @@ +* 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/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/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..93b62a98f603 --- /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 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/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/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..a348f83c5e77 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/agents/rsl_rl_ppo_cfg.py @@ -0,0 +1,67 @@ +# 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 configurations for state-based Franka stacking.""" + +from isaaclab.utils import configclass + +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 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 = 25 + experiment_name = "franka_stack" + clip_actions = 1.0 + obs_groups = {"actor": ["policy"], "critic": ["policy"]} + actor = STATE_POLICY_CFG + critic = STATE_CRITIC_CFG + algorithm = ALGORITHM_CFG 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..4791dee72f51 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/config/franka/stack_rl_env_cfg.py @@ -0,0 +1,425 @@ +# 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 + +"""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.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 +from isaaclab.managers import ObservationTermCfg as ObsTerm +from isaaclab.managers import RewardTermCfg as RewTerm +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 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 + + +@configclass +class EventCfg: + """Reset from a shared cache of validated full-task stack states.""" + + 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 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) + + def __post_init__(self) -> None: + self.enable_corruption = False + self.concatenate_terms = True + + +@configclass +class FrankaStackObservationsCfg: + """Observation groups for state-based Franka stacking.""" + + policy: FrankaStackStateObservationCfg = FrankaStackStateObservationCfg() + + +@configclass +class RewardsCfg: + """Sparse terminal objective plus safety regularizers.""" + + 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.finite_joint_velocity_l2, + params={ + "asset_cfg": SceneEntityCfg("robot", joint_names=["panda_joint.*"]), + "maximum_velocity": 3.0, + }, + weight=-1.0e-4, + ) + + +@configclass +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, + }, + ) + + +@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.CubeOutOfWorkspace) + + +@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() + terminations: FrankaStackTerminationsCfg = FrankaStackTerminationsCfg() + + def __post_init__(self) -> None: + super().__post_init__() + + 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 + 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 + + # Solve constraints with MJWarp and generate contacts with Newton's collision pipeline. + physics = NewtonCfg( + solver_cfg=MJWarpSolverCfg( + solver="newton", + integrator="implicitfast", + njmax=256, + nconmax=100, + impratio=10.0, + cone="elliptic", + use_mujoco_contacts=False, + ), + # Refresh contacts for each 5 ms substep so a released tower can settle. + num_substeps=2, + 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. + 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, + ) + + 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/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/__init__.pyi b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/__init__.pyi index c7184d285121..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,23 +4,47 @@ # SPDX-License-Identifier: BSD-3-Clause __all__ = [ + "CubeOutOfWorkspace", + "ResetBufferedGripperActionCfg", + "StableOrderInvariantStackGoal", + "StackResetLearningProgress", + "StackResetRecipe", + "StackResetStateTable", + "StackResetTableCurriculum", + "WorkspaceBoundedRelativeJointPositionActionCfg", + "action_term_l2", "cube_orientations_in_world_frame", "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 ( + CubeOutOfWorkspace, + 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/curriculums.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/curriculums.py new file mode 100644 index 000000000000..a3f835e1f9fe --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/curriculums.py @@ -0,0 +1,198 @@ +# 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 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 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, 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.""" + + 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["success_monitor"] + if not isinstance(monitor_cfg, SuccessMonitorCfg): + raise TypeError("StackResetTableCurriculum requires a SuccessMonitorCfg.") + 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._recipe_rows = tuple( + (name, reset_term.recipe_ids == recipe) for recipe, name in enumerate(reset_term.recipe_names) + ) + 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, + 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 + 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() + metrics: dict[str, torch.Tensor] = { + "batch_table_full_task_attempts": torch.zeros((), device=env.device), + } + 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() + 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 + unseen_rows = active_rows & ~observed + observed_count = observed.sum().clamp_min(1) + metrics.update( + { + "row_coverage": observed.float().mean(), + "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(), + "table_probability": probabilities[self._table_rows].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, + "table_curriculum_success_rate": self._progress_successes[self._table_rows].sum().float() + / table_denominator, + "table_full_task_success_rate": self._full_task_successes_by_row[self._table_rows].sum().float() + / table_denominator, + "table_full_task_attempts": table_attempts.float(), + } + ) + 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/goal_context.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/goal_context.py new file mode 100644 index 000000000000..9ab7a0852e98 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/goal_context.py @@ -0,0 +1,186 @@ +# 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 ( + _resolve_finger_joint_ids, + 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) + 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.""" + 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 = 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), dim=(1, 2)) < maximum_cube_velocity + robot: Articulation = env.scene["robot"] + 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) + # 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 + + +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} + 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.""" + if env_ids is None: + env_ids = slice(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 + 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, + finger_joint_ids=self._finger_joint_ids, + ) + 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..6b6bba100b60 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,116 @@ 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 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, + body_name=tool_body_name, + body_offset=tool_offset, + ) + + +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, ...] = ( + 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 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 _stack_progress_from_positions + + 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: + 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) + 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) + + vertical_offset = local_positions.new_tensor((0.0, 0.0, cube_height)) + 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), + pair_errors.flatten(start_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/reset_events.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/reset_events.py new file mode 100644 index 000000000000..2adc7a167e21 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/reset_events.py @@ -0,0 +1,945 @@ +# 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, ClassVar + +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, torch_warp_stream + +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_FIRST_ALIGNED_POSE_INDEX = 2 +_SECOND_ALIGNED_POSE_INDEX = 3 +_SECOND_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. + + 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.") + 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 the stock fixed-base Panda's tool-center positions from seven joints. + + 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)``. + + 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. The configured arm action supplies the workspace for both + catalog eligibility and reset perturbations. + """ + + _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: 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) + 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)}." + ) + + 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, + device=env.device, + ) + 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(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._sampler: ResetStateSampler | None = None + + @property + def row_count(self) -> int: + """Number of physical rows in the reset table.""" + return self._buffer.num_states + + @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 set_sampler(self, sampler: ResetStateSampler) -> None: + """Share the curriculum's native history, probabilities, and row assignments.""" + self._sampler = sampler + + 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_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] = [] + 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(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 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( + 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 = 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( + arm_anchors[base_anchor, _NEAR_GRASP_POSE_INDEX], + arm_anchors[base_anchor, _PREGRASP_POSE_INDEX], + first_placed_alpha, + ) + second_placed_arm = torch.lerp( + arm_anchors[base_anchor, _PREGRASP_POSE_INDEX], + arm_anchors[base_anchor, _SECOND_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, + arm_anchors[base_anchor, _SECOND_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, + _SECOND_ALIGNED_POSE_INDEX, + (StackResetRecipe.SECOND_PLACE, StackResetRecipe.SECOND_TRANSPORT, StackResetRecipe.SECOND_PICK), + ), + ( + 1, + first_anchor, + first_placed_arm, + _LIFTED_OR_FIRST_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 = 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 + 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(arm_anchors[base_anchor, _SECOND_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 = 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, + arm_anchors[approach_anchor, _PREGRASP_POSE_INDEX] + arm_noise, + randomized_table_positions, + open_finger_position, + -1, + ) + + 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, + ) + # 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(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) + role_quaternions = torch.zeros( + (role_positions.shape[0], 3, 4), + dtype=torch.float32, + device=self.device, + ) + 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. + 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.""" + 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 layout_ids.shape != recipe_ids.shape: + raise RuntimeError("Stack reset table layout IDs do not align with its physical rows.") + 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(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(role_quaternions) + for first_role, second_role in ((0, 1), (0, 2), (1, 2)): + intersecting = _oriented_cube_pair_intersections( + role_positions[:, first_role], + role_rotations[:, first_role], + 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=recipe_ids.dtype, + device=self.device, + ) + 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 __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._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] + 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( + 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] + 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 = 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, + dtype=torch.float32, + device=self.device, + ) + 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_positions.clamp_(min=self._workspace_lower, max=self._workspace_upper) + + 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(): + 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 + * 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])) + + # 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_( + 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] = 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/rewards.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/rewards.py new file mode 100644 index 000000000000..fa61cf74faf9 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/rewards.py @@ -0,0 +1,330 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Sparse objectives and task-state helpers for cube stacking.""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import TYPE_CHECKING + +import torch + +from isaaclab.managers import SceneEntityCfg + +from .robot_state import end_effector_pose +from .runtime_state import get_stack_reset_runtime_state + +if TYPE_CHECKING: + from isaaclab.assets import Articulation + from isaaclab.envs import ManagerBasedRLEnv + + +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) + + +def irrecoverable_stack_failure( + env: ManagerBasedRLEnv, + success_termination_name: str = "success", +) -> torch.Tensor: + """Return a unit-integral pulse for a non-timeout terminal failure. + + 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. + """ + 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 _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 joint_ids + + +_CUBE_PERMUTATIONS = ( + (0, 1, 2), + (0, 2, 1), + (1, 0, 2), + (1, 2, 0), + (2, 0, 1), + (2, 1, 0), +) + + +def _cube_positions( + env: ManagerBasedRLEnv, + cube_cfgs: tuple[SceneEntityCfg, ...], + 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( + 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.""" + return _stack_progress_from_positions(_cube_positions(env, cube_cfgs), xy_threshold, height_threshold, cube_height) + + +def _cube_pair_is_aligned( + separation: torch.Tensor, xy_threshold: float, cube_height: float, height_threshold: float +) -> torch.Tensor: + """Check upper-minus-lower cube offsets against the task's stack tolerances.""" + height = separation[..., 2] + return ( + (torch.linalg.vector_norm(separation[..., :2], dim=-1) < xy_threshold) + & (height > 0.0) + & ((height - cube_height).abs() < height_threshold) + ) + + +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) + pair_exists = pair_is_stacked.flatten(start_dim=1).any(dim=1) + + 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() + + +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) + top_stacked = middle_stacked & _cube_pair_is_aligned( + top_position - middle_position, xy_threshold, cube_height, height_threshold + ) + 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, + *, + finger_joint_ids: Sequence[int] | None = None, + env_ids: Sequence[int] | torch.Tensor | slice = slice(None), +) -> torch.Tensor: + """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`` + makes the two movable cubes interchangeable. + """ + reset_state = get_stack_reset_runtime_state(env) + + 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, 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) + 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..0ed3eaf1c721 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/robot_state.py @@ -0,0 +1,85 @@ +# 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 collections.abc import Sequence +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), + *, + 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[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 + + +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/runtime_state.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/runtime_state.py new file mode 100644 index 000000000000..7d13c57808dd --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/runtime_state.py @@ -0,0 +1,62 @@ +# 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 +import warp as wp + +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 + + +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 5ad8c508438a..33e6015c9f1f 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/terminations.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/mdp/terminations.py @@ -11,18 +11,37 @@ from __future__ import annotations +import math from typing import TYPE_CHECKING 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 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"), @@ -119,3 +138,59 @@ def cubes_stacked( stacked &= torch.linalg.norm(cube.data.root_lin_vel_w.torch, dim=1) < max_lin_vel return stacked + + +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 + + +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/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/isaaclab_tasks/contrib/stack/stack_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/stack/stack_env_cfg.py index a63db10ee10e..e34de3b0a937 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 @@ -289,8 +289,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) @@ -306,6 +306,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_curriculum.py b/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_curriculum.py new file mode 100644 index 000000000000..3c83b9f23880 --- /dev/null +++ b/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_curriculum.py @@ -0,0 +1,175 @@ +# 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.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 +from isaaclab_tasks.utils import SuccessMonitorCfg + +pytestmark = pytest.mark.kitless + + +def test_curriculum_credits_the_completed_row_before_reset() -> None: + env = _make_env({"fixed_recipe": int(StackResetRecipe.SECOND_TRANSPORT)}) + robot = env.scene["robot"] + origins = env.scene.env_origins + 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 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() + 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)) + 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}) + 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 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) + 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])) + 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, + 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) + self.env_origins = origins 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..e081b6a3564e --- /dev/null +++ b/source/isaaclab_tasks/test/contrib/stack/test_franka_stack_state.py @@ -0,0 +1,175 @@ +# 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, TerminationManager +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 + +pytestmark = pytest.mark.kitless + + +@pytest.fixture(scope="module") +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: FrankaCubeStackRLEnvCfg) -> None: + 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_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: FrankaCubeStackRLEnvCfg) -> None: + 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: FrankaCubeStackRLEnvCfg) -> None: + num_envs = 4 + + class Scene(dict): + env_origins = torch.zeros(num_envs, 3) + + # The candidate stack order is asset 2 -> asset 3 -> asset 1. + scene = Scene() + for cube_index, height in enumerate((0.10, 0.02, 0.06), start=1): + positions = torch.zeros(num_envs, 3) + positions[:, 2] = height + velocities = torch.zeros(num_envs, 6) + if cube_index == 1: + velocities[2, 2] = 0.2 + # Only 18 mm separates the top and middle centers in this environment. + positions[3, 2] = 0.078 + pose = torch.zeros(num_envs, 7) + pose[:, :3] = positions + pose[:, 6] = 1.0 + scene[f"cube_{cube_index}"] = SimpleNamespace( + data=SimpleNamespace( + 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(num_envs, 9) + joint_positions[:, 7:] = 0.04 + joint_positions[1, 7:] = 0.02 + scene["robot"] = SimpleNamespace( + 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(num_envs, 1, 3)), + body_quat_w=SimpleNamespace(torch=torch.tensor([[[0.0, 0.0, 0.0, 1.0]]]).expand(num_envs, -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=num_envs, + device="cpu", + cfg=stack_cfg, + scene=scene, + sim=SimpleNamespace(is_playing=lambda: True), + max_episode_length=100, + episode_length_buf=torch.full((num_envs,), 3), + step_dt=0.02, + extras={}, + ) + create_stack_reset_runtime_state(env) + env.termination_manager = TerminationManager(stack_cfg.terminations, env) + reward = stack_cfg.rewards.success + + for _ in range(4): + assert not env.termination_manager.compute().any() + assert not reward.func(env, **reward.params).any() + env.episode_length_buf += 1 + + assert env.termination_manager.compute().tolist() == [True, False, False, False] + assert env.termination_manager.get_term("success").tolist() == [True, False, False, False] + torch.testing.assert_close( + reward.func(env, **reward.params) * env.step_dt * reward.weight, torch.tensor([2.0, 0.0, 0.0, 0.0]) + ) + env.termination_manager.reset(env_ids=torch.tensor([0])) + assert env.extras["successes"].tolist() == [True, False, False, False] + assert not reward.func(env, **reward.params).any()