"""ATEC Task E pi0.5 native-8D websocket policy bridge.""" from __future__ import annotations from collections import deque import os import sys from pathlib import Path import numpy as np import torch import torchvision.transforms.functional as TF _OPENPI_REPO = Path(os.environ.get("OPENPI_REPO", "/home/ubuntu/src/openpi-ebench-clean")) _OPENPI_CLIENT = _OPENPI_REPO / "packages" / "openpi-client" / "src" if str(_OPENPI_CLIENT) not in sys.path: sys.path.insert(0, str(_OPENPI_CLIENT)) from openpi_client import websocket_client_policy # noqa: E402 class AlgSolution: _QPOS_SLICE = slice(0, 8) _DEFAULT_PROMPT = "identify all objects, pick them up, and place them into the target basket" def __init__(self): self.device = "cuda" if torch.cuda.is_available() else "cpu" host = os.environ.get("ATEC_PI05_HOST", "127.0.0.1") port = int(os.environ.get("ATEC_PI05_PORT", "8000")) self.policy = websocket_client_policy.WebsocketClientPolicy(host=host, port=port) self.prompt = os.environ.get("ATEC_PI05_PROMPT", self._DEFAULT_PROMPT) self.default_joint_pos = torch.tensor( [[0.0, 1.2, -1.5, 0.0, 1.2, 0.0, 0.035, -0.035]], dtype=torch.float32, device=self.device, ) self.teleop_home_joint_pos = torch.tensor( [[-0.000033, 0.924525, -1.514983, 0.000011, 1.219900, -0.000033, 0.035000, -0.035000]], dtype=torch.float32, device=self.device, ) self._home_action = torch.clamp( (self.teleop_home_joint_pos - self.default_joint_pos) / 0.5, -1.0, 1.0, ) self._startup_zero_steps = int(os.environ.get("ATEC_PI05_STARTUP_ZERO_STEPS", "25")) self._home_qpos_tolerance = float(os.environ.get("ATEC_PI05_HOME_QPOS_TOLERANCE", "0.10")) self._home_hold_steps = int(os.environ.get("ATEC_PI05_HOME_HOLD_STEPS", "5")) self._action_repeat = max(1, int(os.environ.get("ATEC_PI05_ACTION_REPEAT", "1"))) self._action_clip = float(os.environ.get("ATEC_PI05_ACTION_CLIP", "5.0")) self._chunk_exec_steps = max(1, int(os.environ.get("ATEC_PI05_CHUNK_EXEC_STEPS", "10"))) self._zero_noise = os.environ.get("ATEC_PI05_ZERO_NOISE", "0").lower() in ("1", "true", "yes") self._action_horizon = max(1, int(os.environ.get("ATEC_PI05_ACTION_HORIZON", "10"))) self._model_action_dim = max(8, int(os.environ.get("ATEC_PI05_MODEL_ACTION_DIM", "32"))) self._debug = os.environ.get("ATEC_PI05_DEBUG", "0").lower() in ("1", "true", "yes") self._resize_size = (224, 224) self.reset_episode() def reset_episode(self): self._startup_step = 0 self._home_stable_steps = 0 self._home_done = False self._action_queue: deque[np.ndarray] = deque() self._held_action: np.ndarray | None = None self._held_remaining = 0 self._debug_step = 0 self._policy_calls = 0 def _compute_home_action(self, proprio: torch.Tensor) -> tuple[torch.Tensor, bool]: qpos = proprio[:, self._QPOS_SLICE] + self.default_joint_pos qerr = self.teleop_home_joint_pos - qpos within_tolerance = torch.all(torch.abs(qerr) <= self._home_qpos_tolerance, dim=1) self._home_stable_steps = self._home_stable_steps + 1 if bool(torch.all(within_tolerance)) else 0 home_reached = self._home_stable_steps >= self._home_hold_steps if self._debug and self._debug_step % 50 == 0: print( "[PI05_DEBUG] " f"home step={self._debug_step} max_abs_qerr={torch.max(torch.abs(qerr)).item():.4f} " f"stable={self._home_stable_steps}/{self._home_hold_steps} " f"qpos={qpos[0].detach().cpu().numpy()[:8]}", flush=True, ) return self._home_action.repeat(proprio.shape[0], 1), home_reached def _rgb_from_obs(self, obs: dict) -> np.ndarray: rgb = obs["image"]["video_rgb"] if isinstance(rgb, torch.Tensor): rgb = rgb[0].detach().cpu() if rgb.ndim == 3 and rgb.shape[0] in (3, 4): rgb = rgb[:3].permute(1, 2, 0) if rgb.ndim == 3 and rgb.shape[-1] == 4: rgb = rgb[..., :3] if rgb.dtype != torch.uint8: rgb = (rgb.float() * 255.0).clamp(0, 255).to(torch.uint8) if tuple(rgb.shape[:2]) != self._resize_size: rgb = TF.resize( rgb.permute(2, 0, 1), list(self._resize_size), interpolation=TF.InterpolationMode.BILINEAR, antialias=True, ).permute(1, 2, 0) return rgb.numpy() rgb = np.asarray(rgb[0]) if rgb.shape[-1] == 4: rgb = rgb[..., :3] if np.issubdtype(rgb.dtype, np.floating): rgb = (rgb * 255.0).clip(0, 255).astype(np.uint8) return rgb.astype(np.uint8, copy=False) def _openpi_obs(self, obs: dict, proprio: torch.Tensor) -> dict: qpos = (proprio[:, self._QPOS_SLICE] + self.default_joint_pos).detach().cpu().numpy()[0] openpi_obs = { "state": qpos.astype(np.float32, copy=False), "image": self._rgb_from_obs(obs), "prompt": self.prompt, } if self._zero_noise: openpi_obs["noise"] = np.zeros((self._action_horizon, self._model_action_dim), dtype=np.float32) return openpi_obs def _next_pi05_action(self, obs: dict, proprio: torch.Tensor) -> np.ndarray: if self._held_action is not None and self._held_remaining > 0: self._held_remaining -= 1 return self._held_action if not self._action_queue: response = self.policy.infer(self._openpi_obs(obs, proprio)) actions = np.asarray(response["actions"], dtype=np.float32) if actions.ndim != 2 or actions.shape[-1] < 8: raise ValueError(f"Expected OpenPI native8 actions with shape (T, >=8), got {actions.shape}") self._policy_calls += 1 if self._debug: print( "[PI05_DEBUG] " f"policy_call={self._policy_calls} actions_shape={actions.shape} " f"first_action={actions[0, :8]}", flush=True, ) for action8 in actions[: self._chunk_exec_steps]: self._action_queue.append(np.clip(action8[:8], -self._action_clip, self._action_clip)) self._held_action = self._action_queue.popleft() self._held_remaining = self._action_repeat - 1 return self._held_action def predicts(self, obs, current_score): if not isinstance(obs, dict) or "proprio" not in obs: raise ValueError("Expected obs dict with 'proprio' key.") proprio = obs["proprio"].to(self.device) if proprio.shape[0] != 1: raise ValueError("solution_pi05_native8 supports num_envs=1.") if self._startup_step < self._startup_zero_steps: self._startup_step += 1 self._debug_step += 1 if self._debug and self._startup_step in (1, self._startup_zero_steps): print(f"[PI05_DEBUG] startup step={self._startup_step}/{self._startup_zero_steps}", flush=True) return {"action": np.zeros((1, 8), dtype=np.float32).tolist(), "giveup": False} if not self._home_done: home_action, home_reached = self._compute_home_action(proprio) if home_reached: self._home_done = True self._action_queue.clear() self._held_action = None self._held_remaining = 0 if self._debug: print(f"[PI05_DEBUG] home_done at step={self._debug_step}", flush=True) self._debug_step += 1 return {"action": home_action.detach().cpu().numpy().tolist(), "giveup": False} action = self._next_pi05_action(obs, proprio) if self._debug and self._debug_step % 50 == 0: print(f"[PI05_DEBUG] execute step={self._debug_step} action={action[:8]}", flush=True) self._debug_step += 1 return {"action": action.reshape(1, -1).tolist(), "giveup": False}