Cosmos3 action policy improvements (#6460)

Signed-off-by: Maciej Bala <mbala@nvidia.com>
Signed-off-by: MaciejBalaNV <mbala@nvidia.com>
Co-authored-by: Hongsheng Liu <liuhongsheng4@huawei.com>
This commit is contained in:
MaciejBalaNVandHongsheng Liu authored and GitHub committed 2026-09-10 22:32:50 +08:00
1 parent c8bef008eb
commit 05ab509269
21 files changed
+863 -105

No files matched your search

+11
View File
@@ -930,6 +930,15 @@ class OmniServeCommand(CLISubcommand):
action="store_true",
help="Disable Cosmos3 text/video safety guardrails for this server.",
)
omni_config_group.add_argument(
"--robot-openpi-idle-timeout",
type=_nonneg_finite_float,
default=30.0,
help=(
"Seconds the /v1/realtime/robot/openpi endpoint waits for the next request "
"before closing an idle WebSocket (default: 30). Set to 0 to disable the timeout."
),
)
# Enable diffusion pipeline profiling
omni_config_group.add_argument(
@@ -1011,6 +1020,8 @@ def run_headless(args: TrackingNamespace) -> None:
# Filter down to a dict of things explicitly requested by the user
args_dict = args.get_explicit_kwargs_dict()
# This controls only the API-process WebSocket and is not a stage-engine option.
args_dict.pop("robot_openpi_idle_timeout", None)
# This CLI-only negative alias is consumed below when selecting the
# launcher log_stats value; it is not a per-stage config override.
args_dict.pop("disable_log_stats", None)
+17 -2
View File
@@ -485,6 +485,8 @@ async def build_async_omni_from_stage_config(
try:
kwargs = args.get_explicit_kwargs_dict()
# This controls only the API-process WebSocket and is not an AsyncOmni option.
kwargs.pop("robot_openpi_idle_timeout", None)
model = kwargs.pop("model", None) or args.model
kwargs.setdefault("log_stats", not args.disable_log_stats)
async_omni = AsyncOmni(model=model, **kwargs)
@@ -1494,11 +1496,24 @@ async def realtime_robot_openpi(websocket: WebSocket):
serving = getattr(websocket.app.state, "openai_serving_realtime_robot", None)
if serving is None:
logger.warning(
"Rejecting robot OpenPI WebSocket: policy serving is disabled. "
"The diffusion stage must provide model_config.policy_server_config."
)
await websocket.accept()
await websocket.send_json({"type": "error", "error": "Robot policy not available", "code": "unsupported"})
await websocket.send_json(
{
"type": "error",
"error": "Robot policy not available",
"code": "unsupported",
}
)
await websocket.close()
return
connection = RobotRealtimeConnection(websocket, serving)
state_args = getattr(websocket.app.state, "args", None)
configured_timeout = getattr(state_args, "robot_openpi_idle_timeout", 30.0)
idle_timeout = None if configured_timeout == 0 else configured_timeout
connection = RobotRealtimeConnection(websocket, serving, idle_timeout=idle_timeout)
await connection.handle_connection()
+45 -18
View File
@@ -29,6 +29,7 @@ mappings.
from __future__ import annotations
import asyncio
from collections import OrderedDict
from typing import Any
import msgspec
@@ -45,10 +46,12 @@ logger = init_logger(__name__)
_DEFAULT_IDLE_TIMEOUT = 30.0
MAX_OPENPI_PAYLOAD_BYTES = 64 * 1024 * 1024
_MISSING = object()
# Upper bound on the per-connection set of seen session ids.
MAX_TRACKED_SESSIONS = 1024
def _pack_numpy(obj: Any) -> Any:
if isinstance(obj, (np.ndarray, np.generic)) and obj.dtype.kind in ("V", "O", "c"):
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:
@@ -165,17 +168,38 @@ class RobotRealtimeConnection:
self,
websocket: WebSocket,
serving: ServingRealtimeRobotOpenPI,
idle_timeout: float = _DEFAULT_IDLE_TIMEOUT,
idle_timeout: float | None = _DEFAULT_IDLE_TIMEOUT,
) -> None:
self.websocket = websocket
self.serving = serving
self._idle_timeout = idle_timeout
self._current_session_id: str | None = None
self._call_count = 0
# Session ids seen on this connection, most-recently-used last.
self._seen_sessions: OrderedDict[str, None] = OrderedDict()
def reset(self) -> None:
self._current_session_id = None
self._call_count = 0
self._seen_sessions.clear()
def _mark_session_seen(self, session_id: str) -> bool:
"""Record ``session_id``; return True when it is the first sighting.
A session's first observation is the one that carries ``reset`` to the
policy, so this needs per-session memory.
"""
if session_id in self._seen_sessions:
self._seen_sessions.move_to_end(session_id)
return False
self._seen_sessions[session_id] = None
if len(self._seen_sessions) > MAX_TRACKED_SESSIONS:
evicted, _ = self._seen_sessions.popitem(last=False)
logger.debug(
"Robot OpenPI connection is tracking more than %d sessions; dropped least-recently-used %s",
MAX_TRACKED_SESSIONS,
evicted,
)
return True
async def _send_error(self, message: str) -> None:
await self.websocket.send_bytes(_pack({"type": "error", "message": message}))
@@ -199,18 +223,22 @@ class RobotRealtimeConnection:
await self.websocket.send_bytes(_pack(metadata))
while True:
try:
msg = await asyncio.wait_for(
self.websocket.receive(),
timeout=self._idle_timeout,
)
except asyncio.TimeoutError:
logger.info("Robot OpenPI connection idle timeout after %.1f seconds", self._idle_timeout)
idle_timeout = self._idle_timeout
if idle_timeout is None:
msg = await self.websocket.receive()
else:
try:
await self.websocket.close()
except Exception:
logger.debug("Failed to close idle robot OpenPI websocket", exc_info=True)
return
msg = await asyncio.wait_for(
self.websocket.receive(),
timeout=idle_timeout,
)
except asyncio.TimeoutError:
logger.info("Robot OpenPI connection idle timeout after %.1f seconds", idle_timeout)
try:
await self.websocket.close()
except Exception:
logger.debug("Failed to close idle robot OpenPI websocket", exc_info=True)
return
if msg.get("type") == "websocket.disconnect":
break
@@ -245,13 +273,12 @@ class RobotRealtimeConnection:
session_id,
)
self._current_session_id = session_id
self._call_count = 0
self._call_count += 1
reset = self._mark_session_seen(session_id)
actions = await self.serving.infer(
obs,
session_id=session_id,
reset=self._call_count <= 1,
reset=reset,
)
await self.websocket.send_bytes(_pack(actions))
except Exception:
+23 -7
View File
@@ -148,16 +148,32 @@ class ServingRealtimeRobotOpenPI:
`AsyncOmni.generate()` and routed to the diffusion stage.
"""
from vllm_omni.diffusion.request import OmniDiffusionRequest
from vllm_omni.entrypoints.openai.stage_params import (
clone_sampling_params,
get_default_sampling_params_list,
)
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
# An optional integer ``seed`` in the inference message becomes the engine request's
# ``sampling_params.seed``; omitted, ``OmniDiffusionRequest`` assigns a random one.
# The engine applies stage default_sampling_params only to requests
# that carry no explicit params; this endpoint always passes explicit
# params, so start from a clone of the diffusion stage's defaults
# (e.g. a policy deploy yaml's ``extra_args``) and layer the OpenPI
# protocol fields on top.
seed = obs.pop("seed", None)
extra_args = {
"reset": reset,
"session_id": session_id,
"robot_obs": obs,
}
sampling_params = OmniDiffusionSamplingParams()
for default_params in get_default_sampling_params_list(self.engine_client):
if isinstance(default_params, OmniDiffusionSamplingParams):
sampling_params = clone_sampling_params(default_params)
break
extra_args = sampling_params.extra_args or {}
extra_args.update(
{
"reset": reset,
"session_id": session_id,
"robot_obs": obs,
}
)
prompt = obs.get("prompt", "")
sampling_params = OmniDiffusionSamplingParams(