import os import torch class AlgSolution: ACTION_SCALE = 0.5 EE_BODY_NAME_CANDIDATES = ("gripper_base", "piper_gripper_base") ARM_JOINT_NAME_CANDIDATES = ( ["joint1", "joint2", "joint3", "joint4", "joint5", "joint6"], ["arm_joint1", "arm_joint2", "arm_joint3", "arm_joint4", "arm_joint5", "arm_joint6"], ) def __init__(self): policy_path = os.path.dirname(os.path.abspath(__file__)) + '/policy.pt' self.device = 'cuda' self.policy = torch.jit.load(policy_path, map_location=self.device) self.policy.eval() self.leg_action_dim = 12 self.arm_action_dim = 8 self.leg_joint_indices = list(range(12)) self.arm_joint_indices = list(range(12, 20)) self.train_to_env_action_scale = torch.tensor( [ 0.25, 0.5, 0.5, 0.25, 0.5, 0.5, 0.25, 0.5, 0.5, 0.25, 0.5, 0.5, ], device=self.device, dtype=torch.float32, ).view(1, -1) self.env_to_train_action_scale = torch.tensor( [ 4.0, 2.0, 2.0, 4.0, 2.0, 2.0, 4.0, 2.0, 2.0, 4.0, 2.0, 2.0, ], device=self.device, dtype=torch.float32, ).view(1, -1) # Fixed zero base velocity command for policy input. self.fixed_velocity_commands = torch.tensor( [0.5, 0.0, 0.0], device=self.device, dtype=torch.float32, ).view(1, 3) self.arm_default_action = torch.zeros( (1, self.arm_action_dim), device=self.device, dtype=torch.float32, ) def _resolve_joint_ids(self, candidates: tuple[list[str], ...]) -> list[int]: last_error = None for names in candidates: try: ids, found_names = self.robot.find_joints(names) except ValueError as err: last_error = err continue if len(ids) == len(names): if candidates is self.ARM_JOINT_NAME_CANDIDATES: self.arm_joint_names = list(found_names) return list(ids) raise ValueError( f"Cannot resolve required joints from candidates: {candidates}. Last error: {last_error}" ) def _resolve_ee_body_name(self) -> str: last_error = None for name in self.EE_BODY_NAME_CANDIDATES: try: body_ids, _ = self.robot.find_bodies(name) except ValueError as err: last_error = err continue if len(body_ids) == 1: return name raise ValueError( f"Cannot resolve EE body from candidates: {self.EE_BODY_NAME_CANDIDATES}. Last error: {last_error}" ) def _ensure_cartesian_targets(self): self.cartesian_ctrl.reset() def _compute_arm_overlay_action(self) -> torch.Tensor: self._ensure_cartesian_targets() arm_jpos_des = self.cartesian_ctrl.compute_base( self.ee_pos_target_b, self.ee_quat_target_b, ) full_target = self.robot.data.joint_pos.clone() full_target[:, self.arm_ids] = arm_jpos_des full_target[:, self.gripper_ids] = self.gripper_open_pos.repeat(full_target.shape[0], 1) return (full_target - self.default_joint_pos) / self.ACTION_SCALE def _get_velocity_commands(self, proprio: torch.Tensor) -> torch.Tensor: """Return fixed velocity commands for policy input.""" num_envs = proprio.shape[0] cmd = self.fixed_velocity_commands.to(dtype=proprio.dtype, device=self.device) if num_envs > 1: cmd = cmd.repeat(num_envs, 1) return cmd def _extract_policy_obs(self, obs, action_dim) -> torch.Tensor: proprio = obs["proprio"].to(self.device) expected_dim = 3 + 3 + 3 + 3 + action_dim + action_dim + action_dim idx = 0 _base_lin_vel = proprio[:, idx:idx + 3] idx += 3 base_ang_vel = proprio[:, idx:idx + 3] idx += 3 _velocity_commands_env = proprio[:, idx:idx + 3] idx += 3 projected_gravity = proprio[:, idx:idx + 3] idx += 3 joint_pos_all = proprio[:, idx:idx + action_dim] idx += action_dim joint_vel_all = proprio[:, idx:idx + action_dim] idx += action_dim actions_all = proprio[:, idx:idx + action_dim] joint_pos_leg = joint_pos_all[:, self.leg_joint_indices] joint_vel_leg = joint_vel_all[:, self.leg_joint_indices] actions_env_leg = actions_all[:, self.leg_joint_indices] actions_train_leg = actions_env_leg * self.env_to_train_action_scale.to(dtype=proprio.dtype) velocity_commands = self._get_velocity_commands(proprio) policy_obs = torch.cat( [ base_ang_vel * 0.25, projected_gravity, velocity_commands, joint_pos_leg, joint_vel_leg * 0.05, actions_train_leg, ], dim=-1, ) return policy_obs def _map_policy_action_to_env_action(self, action_train: torch.Tensor, action_dim: int) -> torch.Tensor: """Map training-time 12D leg action to current env 20D full-body action.""" if action_train.shape[-1] != self.leg_action_dim: raise ValueError( f"Policy output dim mismatch: got {action_train.shape[-1]}, expected {self.leg_action_dim}" ) num_envs = action_train.shape[0] leg_action_env = action_train * self.train_to_env_action_scale action_env = torch.zeros( (num_envs, action_dim), device=self.device, dtype=torch.float32, ) action_env[:, self.leg_joint_indices] = leg_action_env action_env[:, self.arm_joint_indices] = self.arm_default_action.repeat(num_envs, 1) return action_env def predicts(self, obs, current_score): """Run policy inference and return current-env full-body action.""" if current_score > 1: return {'action': [], 'giveup': True} proprio = obs["proprio"].to(self.device) action_dim = (int(proprio.shape[-1]) - 12) // 3 policy_obs = self._extract_policy_obs(obs, action_dim) with torch.inference_mode(): action_train = self.policy(policy_obs) if not isinstance(action_train, torch.Tensor): action_train = torch.as_tensor( action_train, device=self.device, dtype=torch.float32 ) action_train = action_train.to(device=self.device, dtype=torch.float32) if action_train.ndim == 1: action_train = action_train.unsqueeze(0) action_env = self._map_policy_action_to_env_action(action_train, action_dim) action_env = action_env.cpu().numpy().tolist() return {'action': action_env, 'giveup': False}