Add Cosmos3 action modality (#4102)
Signed-off-by: Maciej Bala <mbala@nvidia.com> Signed-off-by: Bartosz Stefaniak <bstefaniak@nvidia.com> Signed-off-by: lishunyang12 <lishunyang12@163.com> Co-authored-by: Maciej Bala <mbala@nvidia.com> Co-authored-by: lishunyang12 <lishunyang12@163.com> Co-authored-by: SYLAR <125541396+lishunyang12@users.noreply.github.com>
This commit is contained in:
15 files changed
+1314
-90
No files matched your search
@@ -100,6 +100,9 @@ class OmniServeCommand(CLISubcommand):
|
||||
model_config = dict(existing) if isinstance(existing, dict) else {}
|
||||
model_config["guardrails"] = False
|
||||
args.model_config = model_config
|
||||
explicit_keys = getattr(args, "explicit_keys", None)
|
||||
if explicit_keys is not None:
|
||||
args.explicit_keys = explicit_keys | {"model_config"}
|
||||
|
||||
if args.headless:
|
||||
run_headless(args)
|
||||
|
||||
@@ -2545,7 +2545,7 @@ async def _run_video_generation_job(
|
||||
started_at = time.perf_counter()
|
||||
output_path = None
|
||||
try:
|
||||
video_bytes, stage_durations, peak_memory_mb = await handler.generate_video_bytes(
|
||||
video_bytes, stage_durations, peak_memory_mb, action = await handler.generate_video_bytes(
|
||||
request, video_id, reference_image=reference_image
|
||||
)
|
||||
|
||||
@@ -2563,6 +2563,7 @@ async def _run_video_generation_job(
|
||||
"inference_time_s": time.perf_counter() - started_at,
|
||||
"stage_durations": stage_durations,
|
||||
"peak_memory_mb": peak_memory_mb,
|
||||
"action": action,
|
||||
},
|
||||
)
|
||||
except (EngineGenerateError, EngineDeadError) as exc:
|
||||
@@ -2774,7 +2775,7 @@ async def create_video_sync(
|
||||
raw_request.state.request_metadata = RequestResponseMetadata(request_id=request_id)
|
||||
started_at = time.perf_counter()
|
||||
try:
|
||||
video_bytes, stage_durations, peak_memory_mb = await asyncio.wait_for(
|
||||
video_bytes, stage_durations, peak_memory_mb, _action = await asyncio.wait_for(
|
||||
handler.generate_video_bytes(request, request_id, reference_image=reference_image),
|
||||
timeout=VIDEO_SYNC_TIMEOUT_S,
|
||||
)
|
||||
|
||||
@@ -13,6 +13,7 @@ from vllm_omni.entrypoints.openai.protocol.images import (
|
||||
ResponseFormat,
|
||||
)
|
||||
from vllm_omni.entrypoints.openai.protocol.videos import (
|
||||
VideoAction,
|
||||
VideoData,
|
||||
VideoGenerationRequest,
|
||||
VideoGenerationResponse,
|
||||
@@ -27,6 +28,7 @@ __all__ = [
|
||||
"ImageGenerationRequest",
|
||||
"ImageGenerationResponse",
|
||||
"ResponseFormat",
|
||||
"VideoAction",
|
||||
"VideoData",
|
||||
"VideoGenerationRequest",
|
||||
"VideoGenerationResponse",
|
||||
|
||||
@@ -220,12 +220,24 @@ class VideoGenerationRequest(BaseModel):
|
||||
return vp
|
||||
|
||||
|
||||
class VideoAction(BaseModel):
|
||||
"""Generated action sequence returned by action-capable video models."""
|
||||
|
||||
data: list[Any] = Field(..., description="JSON-serializable nested action values")
|
||||
shape: list[int] = Field(..., description="Shape of the returned action data")
|
||||
dtype: str | None = Field(default=None, description="Source action dtype, if available")
|
||||
raw_action_dim: int | None = Field(default=None, description="Raw action dimension requested by the model")
|
||||
action_mode: str | None = Field(default=None, description="Action generation mode")
|
||||
domain_id: int | None = Field(default=None, description="Action embodiment domain id")
|
||||
|
||||
|
||||
class VideoData(BaseModel):
|
||||
"""Single generated video data."""
|
||||
|
||||
b64_json: str | None = Field(default=None, description="Base64-encoded MP4 video")
|
||||
url: str | None = Field(default=None, description="Video URL (not implemented)")
|
||||
revised_prompt: str | None = Field(default=None, description="Revised prompt (OpenAI compatibility, always null)")
|
||||
action: VideoAction | None = Field(default=None, description="Generated action sequence metadata, if any")
|
||||
|
||||
|
||||
class VideoGenerationResponse(BaseModel):
|
||||
@@ -298,6 +310,7 @@ class VideoResponse(BaseModel):
|
||||
default=0.0,
|
||||
description="Peak device memory usage in MB reported by the diffusion pipeline.",
|
||||
)
|
||||
action: VideoAction | None = Field(default=None, description="Generated action sequence metadata, if any")
|
||||
|
||||
@property
|
||||
def file_extension(self) -> str:
|
||||
|
||||
@@ -16,6 +16,7 @@ from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.entrypoints.async_omni import AsyncOmni
|
||||
from vllm_omni.entrypoints.openai.protocol.videos import (
|
||||
VideoAction,
|
||||
VideoData,
|
||||
VideoGenerationRequest,
|
||||
VideoGenerationResponse,
|
||||
@@ -44,6 +45,7 @@ class VideoGenerationArtifacts:
|
||||
|
||||
videos: list[Any]
|
||||
audios: list[Any | None]
|
||||
actions: list[VideoAction | None]
|
||||
audio_sample_rate: int
|
||||
output_fps: int
|
||||
stage_durations: dict[str, float]
|
||||
@@ -162,7 +164,20 @@ class OmniOpenAIServingVideo:
|
||||
)
|
||||
# Merge extra_params into extra_args
|
||||
gen_params.extra_args.update(request.extra_params)
|
||||
logger.info("Applied extra_params: %s", 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.
|
||||
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__}>"
|
||||
)
|
||||
loggable = {**loggable, "action": summary}
|
||||
logger.info("Applied extra_params: %s", loggable)
|
||||
|
||||
self._apply_lora(request.lora, gen_params)
|
||||
|
||||
@@ -177,11 +192,13 @@ class OmniOpenAIServingVideo:
|
||||
result = await self._run_generation(prompt, gen_params, reference_id)
|
||||
videos = 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)
|
||||
output_fps = (vp.fps or self._resolve_fps(result) or 24) * self._resolve_video_fps_multiplier(result)
|
||||
return VideoGenerationArtifacts(
|
||||
videos=videos,
|
||||
audios=audios,
|
||||
actions=actions,
|
||||
audio_sample_rate=audio_sample_rate,
|
||||
output_fps=output_fps,
|
||||
stage_durations=self._extract_stage_durations(result),
|
||||
@@ -215,7 +232,8 @@ class OmniOpenAIServingVideo:
|
||||
audio_sample_rate=artifacts.audio_sample_rate,
|
||||
video_codec_options=video_codec_options,
|
||||
)
|
||||
)
|
||||
),
|
||||
action=artifacts.actions[idx],
|
||||
)
|
||||
for idx, video in enumerate(artifacts.videos)
|
||||
]
|
||||
@@ -234,7 +252,7 @@ class OmniOpenAIServingVideo:
|
||||
reference_id: str,
|
||||
*,
|
||||
reference_image: ReferenceImage | None = None,
|
||||
) -> tuple[bytes, dict[str, float], float]:
|
||||
) -> tuple[bytes, dict[str, float], float, VideoAction | None]:
|
||||
"""Generate a video and return raw MP4 bytes, bypassing base64 encoding."""
|
||||
artifacts = await self._run_and_extract(request, reference_id, reference_image=reference_image)
|
||||
if len(artifacts.videos) > 1:
|
||||
@@ -259,7 +277,7 @@ class OmniOpenAIServingVideo:
|
||||
)
|
||||
_t_encode_ms = (time.perf_counter() - _t_encode_start) * 1000
|
||||
logger.info("Video response encoding (MP4 bytes): %.2f ms", _t_encode_ms)
|
||||
return video_bytes, artifacts.stage_durations, artifacts.peak_memory_mb
|
||||
return video_bytes, artifacts.stage_durations, artifacts.peak_memory_mb, artifacts.actions[0]
|
||||
|
||||
@staticmethod
|
||||
def _resolve_video_fps_multiplier(result: Any) -> int:
|
||||
@@ -440,6 +458,18 @@ class OmniOpenAIServingVideo:
|
||||
|
||||
return 24000
|
||||
|
||||
@classmethod
|
||||
def _extract_action_outputs(cls, result: Any, expected_count: int) -> list[VideoAction | None]:
|
||||
custom_output = cls._extract_custom_output(result)
|
||||
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)
|
||||
return [
|
||||
cls._make_video_action(action_item, custom_output) if action_item is not None else None
|
||||
for action_item in action_items
|
||||
]
|
||||
|
||||
@staticmethod
|
||||
def _extract_custom_output(result: Any) -> dict[str, Any]:
|
||||
custom_output = getattr(result, "custom_output", None)
|
||||
@@ -458,6 +488,89 @@ class OmniOpenAIServingVideo:
|
||||
|
||||
return custom_output if isinstance(custom_output, dict) else {}
|
||||
|
||||
@classmethod
|
||||
def _split_action_payload(cls, action: Any, expected_count: int) -> list[Any | None]:
|
||||
if expected_count <= 0:
|
||||
return []
|
||||
|
||||
shape = cls._shape_of(action)
|
||||
if len(shape) >= 3:
|
||||
count = min(shape[0], expected_count)
|
||||
actions = [cls._index_action(action, i) for i in range(count)]
|
||||
actions.extend([None] * (expected_count - count))
|
||||
return actions
|
||||
|
||||
return [action] + [None] * (expected_count - 1)
|
||||
|
||||
@classmethod
|
||||
def _make_video_action(cls, action: Any, custom_output: dict[str, Any]) -> VideoAction:
|
||||
data = cls._to_jsonable(action)
|
||||
if not isinstance(data, list):
|
||||
data = [data]
|
||||
|
||||
action_mode = custom_output.get("action_mode")
|
||||
return VideoAction(
|
||||
data=data,
|
||||
shape=cls._shape_of(action),
|
||||
dtype=cls._dtype_of(action),
|
||||
raw_action_dim=cls._coerce_optional_int(custom_output.get("raw_action_dim")),
|
||||
action_mode=str(action_mode) if action_mode is not None else None,
|
||||
domain_id=cls._coerce_optional_int(custom_output.get("domain_id")),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _index_action(action: Any, index: int) -> Any:
|
||||
try:
|
||||
return action[index]
|
||||
except (IndexError, KeyError, TypeError):
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def _to_jsonable(cls, value: Any) -> Any:
|
||||
if hasattr(value, "detach"):
|
||||
value = value.detach()
|
||||
if hasattr(value, "cpu"):
|
||||
value = value.cpu()
|
||||
if hasattr(value, "tolist"):
|
||||
return cls._to_jsonable(value.tolist())
|
||||
if isinstance(value, (list, tuple)):
|
||||
return [cls._to_jsonable(item) for item in value]
|
||||
if hasattr(value, "item"):
|
||||
try:
|
||||
return value.item()
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return value
|
||||
|
||||
@classmethod
|
||||
def _shape_of(cls, value: Any) -> list[int]:
|
||||
shape = getattr(value, "shape", None)
|
||||
if shape is not None:
|
||||
try:
|
||||
return [int(dim) for dim in shape]
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
if isinstance(value, (list, tuple)):
|
||||
if not value:
|
||||
return [0]
|
||||
return [len(value)] + cls._shape_of(value[0])
|
||||
return []
|
||||
|
||||
@staticmethod
|
||||
def _dtype_of(value: Any) -> str | None:
|
||||
dtype = getattr(value, "dtype", None)
|
||||
return str(dtype) if dtype is not None else None
|
||||
|
||||
@staticmethod
|
||||
def _coerce_optional_int(value: Any) -> int | None:
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
value = value.item() if hasattr(value, "item") else value
|
||||
return int(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _resolve_fps(result: Any) -> int | None:
|
||||
"""Extract fps from multimodal_output if the model reported it."""
|
||||
|
||||
Reference in new issue
Block a user