yayalong's picture
Add files using upload-large-folder tool
1e71a55 verified
Raw
History Blame Contribute Delete
7.13 kB
"""ATEC Task E adapter for an OpenPI/pi0.5 websocket policy server.
This is a local evaluation bridge, not the current submission default. Start
the OpenPI server first, then evaluate this solution against the Isaac task.
"""
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:
"""Competition-style solution wrapper backed by a pi0.5 action chunk server."""
_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", "5")))
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
def _compute_home_action(self, proprio: torch.Tensor) -> tuple[torch.Tensor, bool]:
joint_pos_rel = proprio[:, self._QPOS_SLICE]
qpos = joint_pos_rel + 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
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]
joints = np.zeros(12, dtype=np.float32)
gripper = np.zeros(4, dtype=np.float32)
joints[:6] = qpos[:6]
gripper[:2] = qpos[6:8]
rgb = self._rgb_from_obs(obs)
return {
"states/joint": joints,
"states/gripper": gripper,
"images/head": rgb,
"images/hand_left": rgb,
"images/hand_right": rgb,
"prompt": self.prompt,
}
@staticmethod
def _to_env_action(action16: np.ndarray) -> np.ndarray:
action16 = np.asarray(action16, dtype=np.float32)
env_action = np.zeros(8, dtype=np.float32)
env_action[:6] = action16[:6]
env_action[6:8] = action16[12:14]
return env_action
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] < 16:
raise ValueError(f"Expected OpenPI actions with shape (T, >=16), got {actions.shape}")
for action16 in actions:
self._action_queue.append(self._to_env_action(action16))
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)
num_envs = proprio.shape[0]
if num_envs != 1:
raise ValueError("solution_pi05 currently supports num_envs=1 for websocket inference.")
if self._startup_step < self._startup_zero_steps:
self._startup_step += 1
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
return {"action": home_action.detach().cpu().numpy().tolist(), "giveup": False}
action = self._next_pi05_action(obs, proprio)
return {"action": action.reshape(1, -1).tolist(), "giveup": False}