[BugFix][Cosmos3] Decode uploaded video paths in v2v preprocess (#8106)
Signed-off-by: NumberWan <wantszkin2003@gmail.com>
This commit is contained in:
1 parent
69de153f6e
commit
e5613794ca
4 files changed
+277
-35
No files matched your search
@@ -72,6 +72,7 @@ from vllm_omni.diffusion.models.schedulers.scheduling_flow_unipc_multistep impor
|
||||
from vllm_omni.diffusion.offloader.config import OffloadStrategy, resolve_offload
|
||||
from vllm_omni.diffusion.profiler.diffusion_pipeline_profiler import DiffusionPipelineProfilerMixin
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.diffusion.utils.video_decode import decode_path_video_frames, is_video_file_path
|
||||
from vllm_omni.diffusion.worker.request_batch import DiffusionRequestBatch
|
||||
from vllm_omni.entrypoints.openai.video_api_utils import positive_float
|
||||
from vllm_omni.experimental.world_models.adapters.state_cosmos3_adapter import (
|
||||
@@ -465,10 +466,39 @@ def get_cosmos3_pre_process_func(od_config: OmniDiffusionConfig):
|
||||
return nested
|
||||
return video
|
||||
|
||||
def _video_payload_to_frames(video: Any) -> list[Any]:
|
||||
def _decode_video_file_to_frames(
|
||||
path: str | os.PathLike,
|
||||
*,
|
||||
max_frames: int | None,
|
||||
keep: str,
|
||||
) -> list[PIL.Image.Image]:
|
||||
rgb_frames = decode_path_video_frames(path, max_frames=max_frames, keep=keep)
|
||||
return [PIL.Image.fromarray(frame).convert("RGB") for frame in rgb_frames]
|
||||
|
||||
def _expand_video_payload_item(
|
||||
item: Any,
|
||||
*,
|
||||
max_frames: int | None,
|
||||
keep: str,
|
||||
) -> list[Any]:
|
||||
if is_video_file_path(item):
|
||||
return _decode_video_file_to_frames(item, max_frames=max_frames, keep=keep)
|
||||
return [item]
|
||||
|
||||
def _video_payload_to_frames(
|
||||
video: Any,
|
||||
*,
|
||||
max_frames: int | None,
|
||||
keep: str,
|
||||
) -> list[Any]:
|
||||
video = _unwrap_video_payload(video)
|
||||
if is_video_file_path(video):
|
||||
return _decode_video_file_to_frames(video, max_frames=max_frames, keep=keep)
|
||||
if isinstance(video, list):
|
||||
return video
|
||||
frames: list[Any] = []
|
||||
for item in video:
|
||||
frames.extend(_expand_video_payload_item(item, max_frames=max_frames, keep=keep))
|
||||
return frames
|
||||
if isinstance(video, torch.Tensor):
|
||||
tensor = video.detach().cpu()
|
||||
if tensor.ndim == 5:
|
||||
@@ -531,11 +561,31 @@ def get_cosmos3_pre_process_func(od_config: OmniDiffusionConfig):
|
||||
if "additional_information" not in prompt:
|
||||
prompt["additional_information"] = {}
|
||||
|
||||
extra = _extra_args(request)
|
||||
transfer_requested = action_mode is None and has_transfer_hints(extra)
|
||||
condition_frame_indexes_vision = normalize_condition_frame_indexes_vision(
|
||||
extra.get("condition_frame_indexes_vision", prompt.get("condition_frame_indexes_vision"))
|
||||
)
|
||||
condition_video_keep = normalize_condition_video_keep(
|
||||
extra.get("condition_video_keep", prompt.get("condition_video_keep"))
|
||||
)
|
||||
|
||||
raw_video_frames: list[Any] | None = None
|
||||
transfer_input_fps: float | None = None
|
||||
if raw_video is not None:
|
||||
transfer_input_fps = _video_payload_fps(raw_video)
|
||||
raw_video_frames = _video_payload_to_frames(raw_video)
|
||||
decode_extra = dict(extra)
|
||||
decode_extra["condition_frame_indexes_vision"] = list(condition_frame_indexes_vision)
|
||||
decode_extra["condition_video_keep"] = condition_video_keep
|
||||
decode_spec = Cosmos3OmniDiffusersPipeline.reference_video_decode_spec(
|
||||
num_frames=getattr(request.sampling_params, "num_frames", None),
|
||||
extra_args=decode_extra,
|
||||
)
|
||||
raw_video_frames = _video_payload_to_frames(
|
||||
raw_video,
|
||||
max_frames=decode_spec.max_frames,
|
||||
keep=decode_spec.keep,
|
||||
)
|
||||
if not raw_video_frames:
|
||||
raise TypeError("Cosmos3 video input must be a non-empty list of PIL images or image paths.")
|
||||
|
||||
@@ -544,8 +594,6 @@ def get_cosmos3_pre_process_func(od_config: OmniDiffusionConfig):
|
||||
image = _pil_to_rgb(raw_video_frames[0])
|
||||
else:
|
||||
image = _pil_to_rgb(raw_image)
|
||||
extra = _extra_args(request)
|
||||
transfer_requested = action_mode is None and has_transfer_hints(extra)
|
||||
|
||||
# Resolve missing H/W.
|
||||
if transfer_requested:
|
||||
@@ -610,22 +658,13 @@ def get_cosmos3_pre_process_func(od_config: OmniDiffusionConfig):
|
||||
dtype=torch.float32,
|
||||
)
|
||||
else:
|
||||
condition_frame_indexes_vision = normalize_condition_frame_indexes_vision(
|
||||
extra.get(
|
||||
"condition_frame_indexes_vision",
|
||||
prompt.get("condition_frame_indexes_vision"),
|
||||
)
|
||||
)
|
||||
keep = normalize_condition_video_keep(
|
||||
extra.get("condition_video_keep", prompt.get("condition_video_keep"))
|
||||
)
|
||||
max_frames = condition_pixel_frame_count(condition_frame_indexes_vision)
|
||||
prompt["additional_information"]["preprocessed_video"] = _preprocess_condition_video(
|
||||
raw_video_frames,
|
||||
int(target_h),
|
||||
int(target_w),
|
||||
max_frames,
|
||||
keep,
|
||||
condition_video_keep,
|
||||
)
|
||||
prompt["additional_information"]["condition_frame_indexes_vision"] = list(
|
||||
condition_frame_indexes_vision
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Cosmos3 transfer inference helpers.
|
||||
|
||||
The reference Cosmos Framework transfer path accepts one or more control hints
|
||||
@@ -25,6 +25,8 @@ import PIL.Image
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
from vllm_omni.diffusion.utils.video_decode import decode_path_video_frames
|
||||
|
||||
TRANSFER_HINT_KEYS: tuple[str, ...] = ("edge", "blur", "depth", "seg", "wsm")
|
||||
_TRANSFER_HINT_COMMON_FIELDS = frozenset({"control_path", "control", "control_weight"})
|
||||
_TRANSFER_HINT_FIELDS: dict[str, frozenset[str]] = {
|
||||
@@ -538,23 +540,9 @@ def _path_media_to_uint8_cthw(path: str | Path, max_frames: int | None) -> torch
|
||||
array = _pil_to_uint8_rgb(media_path)
|
||||
return torch.from_numpy(array).permute(2, 0, 1).unsqueeze(1).contiguous()
|
||||
|
||||
try:
|
||||
import imageio.v3 as iio
|
||||
except ImportError as exc:
|
||||
raise ImportError(
|
||||
"Cosmos3 transfer video control_path loading requires imageio. "
|
||||
"Install imageio[ffmpeg] or provide decoded control frames."
|
||||
) from exc
|
||||
|
||||
frames: list[torch.Tensor] = []
|
||||
limit = max_frames if max_frames is not None else None
|
||||
for frame in iio.imiter(media_path):
|
||||
frames.append(torch.from_numpy(_pil_to_uint8_rgb(frame)).permute(2, 0, 1))
|
||||
if limit is not None and len(frames) >= int(limit):
|
||||
break
|
||||
if not frames:
|
||||
raise ValueError(f"Cosmos3 transfer control_path produced no frames: {media_path}")
|
||||
return torch.stack(frames, dim=1).contiguous()
|
||||
rgb_frames = decode_path_video_frames(media_path, max_frames=max_frames, keep="first")
|
||||
stacked = [torch.from_numpy(frame).permute(2, 0, 1) for frame in rgb_frames]
|
||||
return torch.stack(stacked, dim=1).contiguous()
|
||||
|
||||
|
||||
def media_to_uint8_cthw(value: Any, *, height: int, width: int, max_frames: int | None = None) -> torch.Tensor:
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Decode video file paths to RGB frames.
|
||||
|
||||
Path suffix checks and bounded first/last-N imageio decoding. Model-specific
|
||||
conditioning and decode-budget stay in each pipeline's preprocess layer.
|
||||
|
||||
Currently used by Cosmos3 V2V preprocess and transfer ``control_path``.
|
||||
Unifying with ``OmniVideoBackend`` / ``_decode_video_bytes`` is a follow-up.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from collections import deque
|
||||
from pathlib import Path
|
||||
from typing import Any, Literal
|
||||
|
||||
import numpy as np
|
||||
import PIL.Image
|
||||
|
||||
VIDEO_EXTENSIONS = {".avi", ".m4v", ".mkv", ".mov", ".mp4", ".webm"}
|
||||
|
||||
|
||||
def is_video_file_path(value: Any) -> bool:
|
||||
"""True when ``value`` is a filesystem path with a known video suffix.
|
||||
|
||||
Serving may leave uploaded references as temp paths such as
|
||||
``/tmp/vllm_omni_video_reference_*.mp4`` instead of decoded frames.
|
||||
"""
|
||||
if not isinstance(value, str | os.PathLike):
|
||||
return False
|
||||
suffix = os.path.splitext(os.fspath(value))[1].lower()
|
||||
return suffix in VIDEO_EXTENSIONS
|
||||
|
||||
|
||||
def _frame_to_uint8_rgb(value: Any) -> np.ndarray:
|
||||
if isinstance(value, PIL.Image.Image):
|
||||
return np.array(value.convert("RGB"), dtype=np.uint8, copy=True)
|
||||
if isinstance(value, np.ndarray):
|
||||
array = value
|
||||
if array.ndim == 3 and array.shape[0] in (3, 4) and array.shape[-1] not in (3, 4):
|
||||
array = np.transpose(array[:3], (1, 2, 0))
|
||||
if np.issubdtype(array.dtype, np.floating):
|
||||
if array.size and (array.min() < 0.0 or array.max() > 1.0):
|
||||
array = np.clip(array, -1.0, 1.0) * 0.5 + 0.5
|
||||
array = (np.clip(array, 0.0, 1.0) * 255.0).round().astype(np.uint8)
|
||||
return array[..., :3].astype(np.uint8)
|
||||
raise TypeError(f"Video decode expected an RGB frame, got {type(value)!r}.")
|
||||
|
||||
|
||||
def decode_path_video_frames(
|
||||
path: str | Path,
|
||||
*,
|
||||
max_frames: int | None = None,
|
||||
keep: Literal["first", "last"] = "first",
|
||||
) -> list[np.ndarray]:
|
||||
"""Decode a video file to RGB uint8 frames (H, W, C).
|
||||
|
||||
``keep='first'`` stops after ``max_frames``. ``keep='last'`` still scans the
|
||||
file and retains only the tail window.
|
||||
"""
|
||||
media_path = Path(path)
|
||||
if not media_path.exists():
|
||||
raise FileNotFoundError(f"Video path does not exist: {media_path}")
|
||||
if keep not in {"first", "last"}:
|
||||
raise ValueError("Video keep must be either 'first' or 'last'.")
|
||||
if max_frames is not None and int(max_frames) <= 0:
|
||||
raise ValueError("Video max_frames must be positive.")
|
||||
try:
|
||||
import imageio.v3 as iio
|
||||
except ImportError as exc:
|
||||
raise ImportError(
|
||||
"Video path decoding requires imageio. Install imageio[ffmpeg] or provide decoded frames."
|
||||
) from exc
|
||||
|
||||
limit = None if max_frames is None else int(max_frames)
|
||||
if keep == "last" and limit is not None:
|
||||
window: deque[np.ndarray] = deque(maxlen=limit)
|
||||
for frame in iio.imiter(media_path):
|
||||
window.append(_frame_to_uint8_rgb(frame))
|
||||
frames = list(window)
|
||||
else:
|
||||
frames = []
|
||||
for frame in iio.imiter(media_path):
|
||||
frames.append(_frame_to_uint8_rgb(frame))
|
||||
if limit is not None and len(frames) >= limit:
|
||||
break
|
||||
if not frames:
|
||||
raise ValueError(f"Video path produced no frames: {media_path}")
|
||||
return frames
|
||||
Reference in new issue
Block a user