Add xctrl-style flat-obs policy server (Tianming template)
Browse files- deploy/serve_bread_xctrl.py +147 -0
deploy/serve_bread_xctrl.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Serve the bread R1 policy (pi05_bread_r1_lora) over WebSocket, xctrl-style.
|
| 2 |
+
|
| 3 |
+
Modeled on Tianming's poke/serve_xctrl_openpi_policy.py flat-obs contract.
|
| 4 |
+
|
| 5 |
+
Client sends a flat obs dict:
|
| 6 |
+
{
|
| 7 |
+
"state": ndarray(14,), # per arm [xyz(3), axis_angle(3), grip(1)], L then R
|
| 8 |
+
# ABSOLUTE grasp_site poses <-- CONFIRM layout/frame
|
| 9 |
+
"camera_ego": ndarray(H, W, 3), # accepted but IGNORED (model's base slot is masked)
|
| 10 |
+
"camera_left": ndarray(H, W, 3),
|
| 11 |
+
"camera_right": ndarray(H, W, 3),
|
| 12 |
+
"prompt": str, # optional; defaults to the training prompt
|
| 13 |
+
"reset": bool, # optional; True on the first frame of an episode
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
Server returns:
|
| 17 |
+
{
|
| 18 |
+
"actions": ndarray(40, 14), # per arm [dxyz(3), axis-angle drot(3), ABS grip(1)],
|
| 19 |
+
# stepwise-chained deltas @30Hz:
|
| 20 |
+
# T_cmd,k = T_cmd,k-1 @ delta_k from T_current
|
| 21 |
+
... (openpi policy timing fields passed through)
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
Differences vs the cooking server -- all handled inside this shim:
|
| 25 |
+
1. key names: our BreadInputs takes left_wrist_image / right_wrist_image /
|
| 26 |
+
state / prompt (no ego/base camera -- it was a human egocam in training).
|
| 27 |
+
2. state conversion: client 14D axis-angle -> model 20D rot6d.
|
| 28 |
+
3. relative_to_first: the model was trained on states re-expressed in each
|
| 29 |
+
arm's EPISODE-START frame. This server is therefore STATEFUL: it records
|
| 30 |
+
the first absolute pose after start/reset and re-expresses every
|
| 31 |
+
subsequent state. Send {"reset": True} at every new episode, or restart
|
| 32 |
+
the server. Getting this wrong produces confidently wrong actions.
|
| 33 |
+
|
| 34 |
+
Usage:
|
| 35 |
+
uv run python deploy/serve_bread_xctrl.py \
|
| 36 |
+
--port=8000 \
|
| 37 |
+
policy:checkpoint \
|
| 38 |
+
--policy.config=pi05_bread_r1_lora \
|
| 39 |
+
--policy.dir=/PATH/TO/pi05-bread-r1-top200/10000
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
from __future__ import annotations
|
| 43 |
+
|
| 44 |
+
import dataclasses
|
| 45 |
+
import logging
|
| 46 |
+
import socket
|
| 47 |
+
from typing import Any
|
| 48 |
+
|
| 49 |
+
import numpy as np
|
| 50 |
+
import tyro
|
| 51 |
+
from scipy.spatial.transform import Rotation
|
| 52 |
+
|
| 53 |
+
from openpi.policies import policy_config as _policy_config
|
| 54 |
+
from openpi.serving import websocket_policy_server # swap for xctrl.policies.WebSocketPolicyServer inside xctrl
|
| 55 |
+
from openpi.training import config as _config
|
| 56 |
+
|
| 57 |
+
TRAIN_PROMPT = "take the bread out of the bowl and put the bread into the toaster"
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _pose_from_7d(x: np.ndarray) -> np.ndarray:
|
| 61 |
+
"""[xyz(3), axis_angle(3)] -> 4x4."""
|
| 62 |
+
T = np.eye(4)
|
| 63 |
+
T[:3, :3] = Rotation.from_rotvec(x[3:6]).as_matrix()
|
| 64 |
+
T[:3, 3] = x[:3]
|
| 65 |
+
return T
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _rot6d(R: np.ndarray) -> np.ndarray:
|
| 69 |
+
return np.concatenate([R[:, 0], R[:, 1]])
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@dataclasses.dataclass
|
| 73 |
+
class Checkpoint:
|
| 74 |
+
config: str = "pi05_bread_r1_lora"
|
| 75 |
+
dir: str = ""
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
@dataclasses.dataclass
|
| 79 |
+
class Args:
|
| 80 |
+
port: int = 8000
|
| 81 |
+
default_prompt: str = TRAIN_PROMPT
|
| 82 |
+
policy: Checkpoint = dataclasses.field(default_factory=Checkpoint)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class BreadPolicyServer:
|
| 86 |
+
"""Flat xctrl obs -> BreadInputs keys, with stateful relative_to_first."""
|
| 87 |
+
|
| 88 |
+
def __init__(self, openpi_policy, default_prompt: str = TRAIN_PROMPT) -> None:
|
| 89 |
+
self._policy = openpi_policy
|
| 90 |
+
self._default_prompt = default_prompt
|
| 91 |
+
self._start_inv: list[np.ndarray] | None = None # [inv(T_L0), inv(T_R0)]
|
| 92 |
+
|
| 93 |
+
def _state_20d(self, state14: np.ndarray, reset: bool) -> np.ndarray:
|
| 94 |
+
state14 = np.asarray(state14, dtype=np.float64).reshape(14)
|
| 95 |
+
poses = [_pose_from_7d(state14[0:6]), _pose_from_7d(state14[7:13])]
|
| 96 |
+
grips = [state14[6], state14[13]]
|
| 97 |
+
if reset or self._start_inv is None:
|
| 98 |
+
self._start_inv = [np.linalg.inv(p) for p in poses]
|
| 99 |
+
logging.info("relative_to_first anchor set (episode start)")
|
| 100 |
+
out = np.zeros(20, dtype=np.float32)
|
| 101 |
+
for i, (inv0, T, g) in enumerate(zip(self._start_inv, poses, grips)):
|
| 102 |
+
rel = inv0 @ T
|
| 103 |
+
off = i * 10
|
| 104 |
+
out[off:off + 3] = rel[:3, 3]
|
| 105 |
+
out[off + 3:off + 9] = _rot6d(rel[:3, :3])
|
| 106 |
+
out[off + 9] = g
|
| 107 |
+
return out
|
| 108 |
+
|
| 109 |
+
def infer(self, obs: dict[str, Any]) -> dict[str, Any]:
|
| 110 |
+
prompt = obs.get("prompt", self._default_prompt)
|
| 111 |
+
if isinstance(prompt, bytes):
|
| 112 |
+
prompt = prompt.decode("utf-8")
|
| 113 |
+
openpi_obs = {
|
| 114 |
+
"state": self._state_20d(obs["state"], bool(obs.get("reset", False))),
|
| 115 |
+
"left_wrist_image": np.asarray(obs["camera_left"]),
|
| 116 |
+
"right_wrist_image": np.asarray(obs["camera_right"]),
|
| 117 |
+
"prompt": str(prompt),
|
| 118 |
+
# camera_ego intentionally dropped: the model's base_0_rgb slot is
|
| 119 |
+
# zeroed+masked (training top view was a human egocam).
|
| 120 |
+
}
|
| 121 |
+
result = self._policy.infer(openpi_obs)
|
| 122 |
+
result["actions"] = np.asarray(result["actions"])[:, :14]
|
| 123 |
+
return result
|
| 124 |
+
|
| 125 |
+
@property
|
| 126 |
+
def metadata(self) -> dict[str, Any]:
|
| 127 |
+
return getattr(self._policy, "metadata", {}) or {}
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def main(args: Args) -> None:
|
| 131 |
+
if not args.policy.dir:
|
| 132 |
+
raise ValueError("policy.dir is required (…/pi05-bread-r1-top200/10000)")
|
| 133 |
+
policy = BreadPolicyServer(
|
| 134 |
+
_policy_config.create_trained_policy(
|
| 135 |
+
_config.get_config(args.policy.config), args.policy.dir,
|
| 136 |
+
default_prompt=args.default_prompt),
|
| 137 |
+
default_prompt=args.default_prompt)
|
| 138 |
+
hostname = socket.gethostname()
|
| 139 |
+
logging.info("bread policy server on %s (%s):%d", hostname,
|
| 140 |
+
socket.gethostbyname(hostname), args.port)
|
| 141 |
+
websocket_policy_server.WebsocketPolicyServer(
|
| 142 |
+
policy=policy, host="0.0.0.0", port=args.port).serve_forever()
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
if __name__ == "__main__":
|
| 146 |
+
logging.basicConfig(level=logging.INFO, force=True)
|
| 147 |
+
main(tyro.cli(Args))
|