Support DROID policy server for Cosmos3 OpenPI (#4282)

Signed-off-by: yuzhud <yuzhudong@gmail.com>
This commit is contained in:
Yuzhu Dong authored and GitHub committed 2026-06-15 21:22:59 +08:00
1 parent ae937320ff
commit e2e79177db
16 files changed
+1397 -154

No files matched your search

+23 -12
View File
@@ -195,18 +195,21 @@ class OmniOpenAIServingVideo:
# Merge extra_params into extra_args
gen_params.extra_args.update(request.extra_params)
# Redact the inline ``action`` array (hundreds of floats) when
# logging so it doesn't flood the logs; everything else is logged
# verbatim.
# Redact inline arrays when logging so RoboLab policy requests do
# not flood the server log with image/state payloads.
loggable = request.extra_params
action_val = loggable.get("action")
if action_val is not None:
summary = (
f"<{type(action_val).__name__} len={len(action_val)}>"
if hasattr(action_val, "__len__")
else f"<{type(action_val).__name__}>"
redacted = {}
for key in ("action", "robot_obs", "observation"):
value = loggable.get(key)
if value is None:
continue
redacted[key] = (
f"<{type(value).__name__} len={len(value)}>"
if hasattr(value, "__len__")
else f"<{type(value).__name__}>"
)
loggable = {**loggable, "action": summary}
if redacted:
loggable = {**loggable, **redacted}
logger.info("Applied extra_params: %s", loggable)
self._apply_lora(request.lora, gen_params)
@@ -220,7 +223,9 @@ class OmniOpenAIServingVideo:
)
result = await self._run_generation(prompt, gen_params, reference_id)
videos = self._extract_video_outputs(result)
custom_output = self._extract_custom_output(result)
action_only = isinstance(custom_output, dict) and bool(custom_output.get("action_only_output"))
videos = [{"action_only_output": True}] if action_only else self._extract_video_outputs(result)
audios = self._extract_audio_outputs(result, expected_count=len(videos))
actions = self._extract_action_outputs(result, expected_count=len(videos))
audio_sample_rate = self._resolve_audio_sample_rate(result)
@@ -314,6 +319,11 @@ class OmniOpenAIServingVideo:
if "video_codec_options" in request.extra_params:
video_codec_options = request.extra_params["video_codec_options"]
action = artifacts.actions[0]
if action is not None and isinstance(artifacts.videos[0], dict):
logger.info("Action-only video request %s completed; skipping MP4 encoding.", reference_id)
return b"", artifacts.stage_durations, artifacts.peak_memory_mb, action
_t_encode_start = time.perf_counter()
video_bytes = _encode_video_bytes(
artifacts.videos[0],
@@ -510,7 +520,8 @@ class OmniOpenAIServingVideo:
if not custom_output or "action" not in custom_output:
return [None] * expected_count
action_items = cls._split_action_payload(custom_output["action"], expected_count)
action_payload = custom_output.get("actions", custom_output["action"])
action_items = cls._split_action_payload(action_payload, expected_count)
return [
cls._make_video_action(action_item, custom_output) if action_item is not None else None
for action_item in action_items
+66 -11
View File
@@ -7,6 +7,10 @@ Protocol (compatible with OpenPI policy clients):
Connect -> server sends msgpack(PolicyServerConfig fields)
Infer -> client sends msgpack(obs), server sends msgpack(ndarray)
Reset -> client sends msgpack({endpoint:reset}), server sends msgpack(status)
NumPy values use the msgpack-numpy marker mapping:
ndarray -> {nd: true, type, kind, shape, data}
scalar -> {nd: false, type, kind, data}
"""
from __future__ import annotations
@@ -14,6 +18,8 @@ from __future__ import annotations
import asyncio
from typing import Any
import msgspec
import numpy as np
from fastapi import WebSocket
from starlette.websockets import WebSocketDisconnect
from vllm.logger import init_logger
@@ -25,26 +31,75 @@ from vllm_omni.entrypoints.openpi.serving import (
logger = init_logger(__name__)
_DEFAULT_IDLE_TIMEOUT = 30.0
MAX_OPENPI_PAYLOAD_BYTES = 64 * 1024 * 1024
_MISSING = object()
def _get_msgpack_numpy() -> Any:
try:
from openpi_client import msgpack_numpy
except ImportError as exc:
raise ImportError(
"The `/v1/realtime/robot/openpi` endpoint requires the optional "
"`openpi-client` dependency. Install it with `pip install openpi-client`."
) from exc
def _pack_numpy(obj: Any) -> Any:
if isinstance(obj, (np.ndarray, np.generic)) and obj.dtype.kind in ("V", "O", "c"):
raise ValueError(f"Unsupported dtype: {obj.dtype}")
if isinstance(obj, np.ndarray):
if not obj.flags.c_contiguous:
obj = np.ascontiguousarray(obj)
return {
b"nd": True,
b"data": obj.tobytes(),
b"type": obj.dtype.str,
b"kind": obj.dtype.kind,
b"shape": obj.shape,
}
if isinstance(obj, np.generic):
return {
b"nd": False,
b"data": obj.tobytes(),
b"type": obj.dtype.str,
b"kind": obj.dtype.kind,
}
raise TypeError(f"Unsupported type: {type(obj)!r}")
return msgpack_numpy
def _mapping_get(obj: dict[Any, Any], key: str, default: Any = None) -> Any:
return obj.get(key, obj.get(key.encode(), default))
def _decode_marker_text(value: Any) -> str:
if isinstance(value, bytes):
return value.decode()
return str(value)
def _unpack_numpy(obj: Any) -> Any:
if isinstance(obj, dict):
nd = _mapping_get(obj, "nd", _MISSING)
dtype = _mapping_get(obj, "type", _MISSING)
kind = _mapping_get(obj, "kind", _MISSING)
data = _mapping_get(obj, "data", _MISSING)
if nd is not _MISSING and dtype is not _MISSING and kind is not _MISSING and data is not _MISSING:
dtype_obj = np.dtype(_decode_marker_text(dtype))
kind_text = _decode_marker_text(kind)
if dtype_obj.kind != kind_text:
raise ValueError(f"NumPy dtype marker kind mismatch: {dtype_obj.kind!r} != {kind_text!r}")
if dtype_obj.kind in ("V", "O", "c"):
raise ValueError(f"Unsupported dtype: {dtype_obj}")
array = np.frombuffer(data, dtype=dtype_obj).copy()
if nd:
shape = _mapping_get(obj, "shape", _MISSING)
if shape is _MISSING:
raise ValueError("NumPy ndarray marker is missing shape")
return array.reshape(tuple(shape))
return array[0]
return {key: _unpack_numpy(value) for key, value in obj.items()}
if isinstance(obj, list):
return [_unpack_numpy(value) for value in obj]
return obj
def _pack(obj: Any) -> bytes:
return _get_msgpack_numpy().packb(obj)
return msgspec.msgpack.encode(obj, enc_hook=_pack_numpy)
def _unpack(data: bytes) -> Any:
return _get_msgpack_numpy().unpackb(data)
return _unpack_numpy(msgspec.msgpack.decode(data))
class RobotRealtimeConnection: