[Core][Diffusion] Add a typed pre-D2H video media contract (#6615)
Signed-off-by: NancyFyong <NancyFyong@users.noreply.github.com> Signed-off-by: Samit <285365963@qq.com> Co-authored-by: NancyFyong <NancyFyong@users.noreply.github.com> Co-authored-by: Samit <285365963@qq.com>
This commit is contained in:
31 files changed
+3054
-60
No files matched your search
@@ -29,6 +29,7 @@ from vllm_omni.diffusion.diffusion_kv.config import (
|
||||
parse_diffusion_kv_cache_mode,
|
||||
)
|
||||
from vllm_omni.diffusion.lora.manager import LoRABackend
|
||||
from vllm_omni.diffusion.media import DiffusionMediaOutput
|
||||
from vllm_omni.diffusion.model_metadata import get_diffusion_model_metadata
|
||||
from vllm_omni.diffusion.utils.network_utils import is_port_available
|
||||
from vllm_omni.errors import client_error_metadata
|
||||
@@ -758,6 +759,15 @@ def uses_diffusers_adapter(od_config: object) -> bool:
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class VideoOutputTransportConfig:
|
||||
enable_device_postprocess: bool = False
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not isinstance(self.enable_device_postprocess, bool):
|
||||
raise TypeError("enable_device_postprocess must be a bool")
|
||||
|
||||
|
||||
@dataclass
|
||||
class OmniDiffusionConfig:
|
||||
# Model and path configuration (for convenience)
|
||||
@@ -793,6 +803,7 @@ class OmniDiffusionConfig:
|
||||
# Cache backend configuration (NEW)
|
||||
cache_backend: str = "none" # "tea_cache", "deep_cache", etc.
|
||||
cache_config: DiffusionCacheConfig | dict[str, Any] = field(default_factory=dict)
|
||||
video_output_transport: VideoOutputTransportConfig = field(default_factory=VideoOutputTransportConfig)
|
||||
enable_cache_dit_summary: bool = False
|
||||
|
||||
# Prompt-embedding cache. When enabled, ``DiffusionModelRunner`` wraps the
|
||||
@@ -1258,6 +1269,13 @@ class OmniDiffusionConfig:
|
||||
# If it's neither dict nor DiffusionCacheConfig, convert to empty config
|
||||
self.cache_config = DiffusionCacheConfig()
|
||||
|
||||
if self.video_output_transport is None:
|
||||
self.video_output_transport = VideoOutputTransportConfig()
|
||||
elif isinstance(self.video_output_transport, Mapping):
|
||||
self.video_output_transport = VideoOutputTransportConfig(**dict(self.video_output_transport))
|
||||
elif not isinstance(self.video_output_transport, VideoOutputTransportConfig):
|
||||
raise TypeError("video_output_transport must be a VideoOutputTransportConfig or mapping")
|
||||
|
||||
# Auto-detect quantization from TransformerConfig if not explicitly set.
|
||||
# This covers the case where tf_model_config is passed at construction
|
||||
# time. For late (post-construction) assignment, callers should use
|
||||
@@ -1618,8 +1636,8 @@ class DiffusionOutput:
|
||||
|
||||
output: torch.Tensor | tuple[Any, ...] | dict[str, Any] | None = None
|
||||
|
||||
# Legacy compatibility fields. New pipeline-specific payloads should be
|
||||
# carried by output["payload"] instead.
|
||||
# Legacy compatibility fields. Decoded video uses ``media``; other new
|
||||
# payloads should be carried by output["payload"] instead.
|
||||
trajectory_timesteps: torch.Tensor | dict[str, Any] | None = None
|
||||
trajectory_latents: torch.Tensor | dict[str, Any] | None = None
|
||||
trajectory_log_probs: torch.Tensor | dict[str, Any] | None = None
|
||||
@@ -1658,7 +1676,18 @@ class DiffusionOutput:
|
||||
# mode) and the receiving side must not initialise a stray CUDA context.
|
||||
to_cpu: bool = False
|
||||
|
||||
# Typed video-media contract. Declared last so the pre-existing positional
|
||||
# constructor order (output, trajectory_timesteps, ...) that out-of-tree
|
||||
# pipelines rely on is preserved. Mutually exclusive with ``output``.
|
||||
media: DiffusionMediaOutput | None = None
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if self.media is not None and not isinstance(self.media, DiffusionMediaOutput):
|
||||
raise TypeError(f"media must be DiffusionMediaOutput, got {type(self.media).__name__}")
|
||||
if self.media is not None and self.output is not None:
|
||||
raise ValueError("DiffusionOutput cannot contain both media and legacy output")
|
||||
if self.media is not None and self.post_process_func is not None:
|
||||
raise ValueError("Typed diffusion media cannot carry a model-specific post_process_func")
|
||||
if not self.to_cpu:
|
||||
return
|
||||
|
||||
@@ -1674,6 +1703,10 @@ class DiffusionOutput:
|
||||
return value
|
||||
|
||||
self.output = _maybe_to_cpu(self.output)
|
||||
if self.media is not None:
|
||||
if not self.media.prepared_for_transport:
|
||||
raise ValueError("Diffusion media must be prepared before to_cpu=True")
|
||||
self.media = self.media.to_cpu()
|
||||
self.trajectory_timesteps = _maybe_to_cpu(self.trajectory_timesteps)
|
||||
self.trajectory_latents = _maybe_to_cpu(self.trajectory_latents)
|
||||
self.trajectory_log_probs = _maybe_to_cpu(self.trajectory_log_probs)
|
||||
|
||||
@@ -47,6 +47,7 @@ from vllm_omni.diffusion.output_formatter import (
|
||||
format_empty_diffusion_outputs,
|
||||
normalize_diffusion_postprocess_output,
|
||||
)
|
||||
from vllm_omni.diffusion.postprocess.media import finalize_diffusion_media
|
||||
from vllm_omni.diffusion.registry import (
|
||||
DiffusionModelRegistry,
|
||||
get_diffusion_post_process_func,
|
||||
@@ -534,26 +535,33 @@ class DiffusionEngine:
|
||||
raise RuntimeError(output.error)
|
||||
logger.debug("Generation completed successfully.")
|
||||
|
||||
if output.output is None:
|
||||
logger.warning("Output is None, returning empty OmniRequestOutput")
|
||||
return format_empty_diffusion_outputs(request, finished=output.finished)
|
||||
|
||||
# When CPU offload is enabled, move output to CPU before
|
||||
# post-processing to avoid device OOM — model weights may still
|
||||
# reside on the device and leave no headroom for intermediates.
|
||||
output_data = output.output
|
||||
if self.od_config.enable_cpu_offload:
|
||||
output_data = _move_tensor_tree_to_cpu(output_data)
|
||||
|
||||
if self.post_process_func is not None:
|
||||
# Some video pipelines need request-level controls during
|
||||
# postprocess (for example worker-side frame interpolation).
|
||||
postprocess_kwargs: dict[str, object] = {}
|
||||
if self._post_process_accepts_sampling_params:
|
||||
postprocess_kwargs["sampling_params"] = request.sampling_params
|
||||
outputs = self.post_process_func(output_data, **postprocess_kwargs)
|
||||
if output.media is not None:
|
||||
if output.output is not None:
|
||||
raise ValueError("DiffusionOutput cannot contain both media and legacy output")
|
||||
media = output.media.to_cpu() if self.od_config.enable_cpu_offload else output.media
|
||||
output_data = media.video.tensor
|
||||
outputs = finalize_diffusion_media(media, sampling_params=request.sampling_params)
|
||||
else:
|
||||
outputs = output_data
|
||||
if output.output is None:
|
||||
logger.warning("Output is None, returning empty OmniRequestOutput")
|
||||
return format_empty_diffusion_outputs(request, finished=output.finished)
|
||||
|
||||
# When CPU offload is enabled, move output to CPU before
|
||||
# post-processing to avoid device OOM — model weights may still
|
||||
# reside on the device and leave no headroom for intermediates.
|
||||
output_data = output.output
|
||||
if self.od_config.enable_cpu_offload:
|
||||
output_data = _move_tensor_tree_to_cpu(output_data)
|
||||
|
||||
if self.post_process_func is not None:
|
||||
# Some video pipelines need request-level controls during
|
||||
# postprocess (for example worker-side frame interpolation).
|
||||
postprocess_kwargs: dict[str, object] = {}
|
||||
if self._post_process_accepts_sampling_params:
|
||||
postprocess_kwargs["sampling_params"] = request.sampling_params
|
||||
outputs = self.post_process_func(output_data, **postprocess_kwargs)
|
||||
else:
|
||||
outputs = output_data
|
||||
|
||||
postprocess_output = normalize_diffusion_postprocess_output(outputs)
|
||||
|
||||
|
||||
+232
-25
@@ -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
|
||||
|
||||
"""IPC utilities for transferring large tensors via POSIX shared memory.
|
||||
|
||||
@@ -11,15 +11,32 @@ serialised through the queue.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterator
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from vllm_omni.diffusion.data import DiffusionOutput
|
||||
from vllm_omni.diffusion.media import (
|
||||
DiffusionMediaOutput,
|
||||
FloatVideoConsumer,
|
||||
VideoColorModel,
|
||||
VideoMediaOutput,
|
||||
VideoTensorEncoding,
|
||||
VideoTensorLayout,
|
||||
VideoTensorSpec,
|
||||
VideoTransportConstraints,
|
||||
VideoValueRange,
|
||||
)
|
||||
|
||||
_SHM_TENSOR_THRESHOLD = 1_000_000 # 1 MB
|
||||
DIFFUSION_RPC_RESULT_ENVELOPE = "diffusion_rpc_result"
|
||||
_DIFFUSION_MEDIA_WIRE_TYPE = "diffusion_media_v1"
|
||||
|
||||
# Sentinel so compute-then-assign packing can tell "field not packed" apart from
|
||||
# "field packed to None".
|
||||
_UNSET = object()
|
||||
|
||||
|
||||
def _array_to_shm(array: np.ndarray) -> dict[str, Any]:
|
||||
@@ -61,9 +78,39 @@ def _array_from_shm(handle: dict[str, Any]) -> np.ndarray:
|
||||
return array
|
||||
|
||||
|
||||
def _unlink_shm_handle(handle: dict[str, Any]) -> None:
|
||||
"""Best-effort removal of a shared-memory segment created during packing."""
|
||||
from multiprocessing import shared_memory
|
||||
|
||||
name = handle.get("name")
|
||||
if not name:
|
||||
return
|
||||
try:
|
||||
shm = shared_memory.SharedMemory(name=name)
|
||||
except FileNotFoundError:
|
||||
return
|
||||
try:
|
||||
shm.close()
|
||||
finally:
|
||||
try:
|
||||
shm.unlink()
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
|
||||
|
||||
def _unlink_shm_handles(handles: list[dict[str, Any]]) -> None:
|
||||
for handle in handles:
|
||||
try:
|
||||
_unlink_shm_handle(handle)
|
||||
except Exception:
|
||||
# Cleanup is best-effort; never mask the original packing failure.
|
||||
pass
|
||||
|
||||
|
||||
def _tensor_to_shm(
|
||||
tensor: torch.Tensor,
|
||||
d2h_stream: torch.Stream | None = None,
|
||||
created: list[dict[str, Any]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Copy a tensor into POSIX shared memory and return a metadata handle.
|
||||
|
||||
@@ -82,14 +129,17 @@ def _tensor_to_shm(
|
||||
torch.accelerator.set_stream(d2h_stream)
|
||||
try:
|
||||
t = tensor.detach()
|
||||
if original_dtype == torch.bfloat16:
|
||||
t = t.to(torch.float32)
|
||||
cpu = torch.empty(t.shape, dtype=t.dtype, pin_memory=True)
|
||||
cpu.copy_(t, non_blocking=True)
|
||||
finally:
|
||||
torch.accelerator.set_stream(old_stream)
|
||||
d2h_stream.synchronize()
|
||||
tensor = cpu
|
||||
# numpy has no bfloat16, so widen on the host after D2H. Never widen on
|
||||
# the accelerator before the copy: a payload that already fell back after
|
||||
# an fp32 OOM would OOM again on a second device-side fp32 allocation.
|
||||
if original_dtype == torch.bfloat16:
|
||||
tensor = tensor.to(torch.float32)
|
||||
else:
|
||||
tensor = tensor.detach().cpu().contiguous()
|
||||
if original_dtype == torch.bfloat16:
|
||||
@@ -101,6 +151,8 @@ def _tensor_to_shm(
|
||||
"torch_dtype": str(original_dtype),
|
||||
}
|
||||
)
|
||||
if created is not None:
|
||||
created.append(handle)
|
||||
return handle
|
||||
|
||||
|
||||
@@ -120,6 +172,7 @@ def _tensor_from_shm(handle: dict[str, Any]) -> torch.Tensor:
|
||||
def _pack_tensor_if_large(
|
||||
val: torch.Tensor,
|
||||
d2h_stream: torch.Stream | None = None,
|
||||
created: list[dict[str, Any]] | None = None,
|
||||
) -> torch.Tensor | dict:
|
||||
"""Replace a tensor with an SHM handle if it exceeds the threshold.
|
||||
|
||||
@@ -134,14 +187,16 @@ def _pack_tensor_if_large(
|
||||
except Exception:
|
||||
storage_bytes = view_bytes
|
||||
if max(view_bytes, storage_bytes) > _SHM_TENSOR_THRESHOLD:
|
||||
return _tensor_to_shm(val, d2h_stream=d2h_stream)
|
||||
return _tensor_to_shm(val, d2h_stream=d2h_stream, created=created)
|
||||
return val
|
||||
|
||||
|
||||
def _ndarray_to_shm(array: np.ndarray) -> dict[str, Any]:
|
||||
def _ndarray_to_shm(array: np.ndarray, created: list[dict[str, Any]] | None = None) -> dict[str, Any]:
|
||||
"""Copy a contiguous NumPy array into POSIX shared memory."""
|
||||
handle = _array_to_shm(array)
|
||||
handle["__ndarray_shm__"] = True
|
||||
if created is not None:
|
||||
created.append(handle)
|
||||
return handle
|
||||
|
||||
|
||||
@@ -153,6 +208,7 @@ def _ndarray_from_shm(handle: dict[str, Any]) -> np.ndarray:
|
||||
def _pack_value_if_large(
|
||||
val: object,
|
||||
d2h_stream: torch.Stream | None = None,
|
||||
created: list[dict[str, Any]] | None = None,
|
||||
) -> object:
|
||||
"""Recursively replace large tensors with SHM handles.
|
||||
|
||||
@@ -163,15 +219,19 @@ def _pack_value_if_large(
|
||||
the two in sync.
|
||||
"""
|
||||
if isinstance(val, torch.Tensor):
|
||||
return _pack_tensor_if_large(val, d2h_stream=d2h_stream)
|
||||
return _pack_tensor_if_large(val, d2h_stream=d2h_stream, created=created)
|
||||
if isinstance(val, np.ndarray):
|
||||
return _ndarray_to_shm(val) if not val.dtype.hasobject and val.nbytes > _SHM_TENSOR_THRESHOLD else val
|
||||
return (
|
||||
_ndarray_to_shm(val, created=created)
|
||||
if not val.dtype.hasobject and val.nbytes > _SHM_TENSOR_THRESHOLD
|
||||
else val
|
||||
)
|
||||
if isinstance(val, dict):
|
||||
return {key: _pack_value_if_large(value, d2h_stream=d2h_stream) for key, value in val.items()}
|
||||
return {key: _pack_value_if_large(value, d2h_stream=d2h_stream, created=created) for key, value in val.items()}
|
||||
if isinstance(val, list):
|
||||
return [_pack_value_if_large(item, d2h_stream=d2h_stream) for item in val]
|
||||
return [_pack_value_if_large(item, d2h_stream=d2h_stream, created=created) for item in val]
|
||||
if isinstance(val, tuple):
|
||||
return tuple(_pack_value_if_large(item, d2h_stream=d2h_stream) for item in val)
|
||||
return tuple(_pack_value_if_large(item, d2h_stream=d2h_stream, created=created) for item in val)
|
||||
return val
|
||||
|
||||
|
||||
@@ -190,18 +250,116 @@ def _unpack_if_shm_handle(val: object) -> object:
|
||||
return val
|
||||
|
||||
|
||||
def _pack_diffusion_media(
|
||||
media: DiffusionMediaOutput,
|
||||
*,
|
||||
d2h_stream: torch.Stream | None,
|
||||
created: list[dict[str, Any]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
media.validate()
|
||||
if not media.prepared_for_transport:
|
||||
raise ValueError("Diffusion media must be prepared before IPC packing")
|
||||
video = media.video
|
||||
packed_tensor = _pack_tensor_if_large(video.tensor, d2h_stream=d2h_stream, created=created)
|
||||
if isinstance(packed_tensor, torch.Tensor) and packed_tensor.device.type != "cpu":
|
||||
packed_tensor = packed_tensor.detach().cpu().contiguous()
|
||||
return {
|
||||
"__type__": _DIFFUSION_MEDIA_WIRE_TYPE,
|
||||
"schema_version": video.schema_version,
|
||||
"prepared_for_transport": True,
|
||||
"video": {
|
||||
"tensor": packed_tensor,
|
||||
"layout": video.spec.layout.value,
|
||||
"encoding": video.spec.encoding.value,
|
||||
"value_range": video.spec.value_range.value,
|
||||
"color_model": video.spec.color_model.value,
|
||||
"pending_float_consumers": sorted(consumer.value for consumer in video.constraints.pending_float_consumers),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _unpack_diffusion_media(packed: dict[str, Any]) -> DiffusionMediaOutput:
|
||||
if packed.get("__type__") != _DIFFUSION_MEDIA_WIRE_TYPE:
|
||||
raise ValueError("Invalid diffusion media wire payload")
|
||||
video_payload = packed.get("video")
|
||||
if not isinstance(video_payload, dict):
|
||||
raise ValueError("Diffusion media wire payload is missing video metadata")
|
||||
tensor = _unpack_if_shm_handle(video_payload.get("tensor"))
|
||||
if not isinstance(tensor, torch.Tensor):
|
||||
raise ValueError("Diffusion media wire payload contains an invalid video tensor")
|
||||
schema_version = packed.get("schema_version")
|
||||
if schema_version != 1:
|
||||
raise ValueError(f"Unsupported video media schema version: {schema_version}")
|
||||
if packed.get("prepared_for_transport") is not True:
|
||||
raise ValueError("Diffusion media wire payload was not prepared for transport")
|
||||
media = DiffusionMediaOutput(
|
||||
video=VideoMediaOutput(
|
||||
tensor=tensor,
|
||||
spec=VideoTensorSpec(
|
||||
layout=VideoTensorLayout(video_payload["layout"]),
|
||||
encoding=VideoTensorEncoding(video_payload["encoding"]),
|
||||
value_range=VideoValueRange(video_payload["value_range"]),
|
||||
color_model=VideoColorModel(video_payload["color_model"]),
|
||||
),
|
||||
constraints=VideoTransportConstraints(
|
||||
pending_float_consumers=frozenset(
|
||||
FloatVideoConsumer(value) for value in video_payload.get("pending_float_consumers", [])
|
||||
)
|
||||
),
|
||||
schema_version=1,
|
||||
),
|
||||
prepared_for_transport=True,
|
||||
)
|
||||
media.validate()
|
||||
return media
|
||||
|
||||
|
||||
def _pack_diffusion_fields(
|
||||
output: DiffusionOutput,
|
||||
d2h_stream: torch.Stream | None = None,
|
||||
created: list[dict[str, Any]] | None = None,
|
||||
pending_updates: list[tuple[DiffusionOutput, str, object]] | None = None,
|
||||
) -> DiffusionOutput:
|
||||
if output.media is not None and output.output is not None:
|
||||
raise ValueError("DiffusionOutput cannot contain both media and legacy output")
|
||||
if output.media is not None and not isinstance(output.media, DiffusionMediaOutput):
|
||||
raise TypeError(f"DiffusionOutput.media must be DiffusionMediaOutput, got {type(output.media).__name__}")
|
||||
|
||||
# Pack into locals first so a mid-payload failure leaves ``output`` unmutated
|
||||
# (never enqueue a half-packed object); the caller unlinks any SHM segments
|
||||
# accumulated in ``created`` on failure.
|
||||
packed_output = _UNSET
|
||||
if output.output is not None:
|
||||
output.output = _pack_value_if_large(output.output, d2h_stream=d2h_stream)
|
||||
if output.trajectory_latents is not None and isinstance(output.trajectory_latents, torch.Tensor):
|
||||
output.trajectory_latents = _pack_tensor_if_large(output.trajectory_latents, d2h_stream=d2h_stream)
|
||||
if output.trajectory_timesteps is not None and isinstance(output.trajectory_timesteps, torch.Tensor):
|
||||
output.trajectory_timesteps = _pack_tensor_if_large(output.trajectory_timesteps, d2h_stream=d2h_stream)
|
||||
if output.trajectory_log_probs is not None and isinstance(output.trajectory_log_probs, torch.Tensor):
|
||||
output.trajectory_log_probs = _pack_tensor_if_large(output.trajectory_log_probs, d2h_stream=d2h_stream)
|
||||
packed_output = _pack_value_if_large(output.output, d2h_stream=d2h_stream, created=created)
|
||||
packed_media = _UNSET
|
||||
if output.media is not None:
|
||||
packed_media = _pack_diffusion_media(output.media, d2h_stream=d2h_stream, created=created)
|
||||
packed_latents = _UNSET
|
||||
if isinstance(output.trajectory_latents, torch.Tensor):
|
||||
packed_latents = _pack_tensor_if_large(output.trajectory_latents, d2h_stream=d2h_stream, created=created)
|
||||
packed_timesteps = _UNSET
|
||||
if isinstance(output.trajectory_timesteps, torch.Tensor):
|
||||
packed_timesteps = _pack_tensor_if_large(output.trajectory_timesteps, d2h_stream=d2h_stream, created=created)
|
||||
packed_log_probs = _UNSET
|
||||
if isinstance(output.trajectory_log_probs, torch.Tensor):
|
||||
packed_log_probs = _pack_tensor_if_large(output.trajectory_log_probs, d2h_stream=d2h_stream, created=created)
|
||||
|
||||
updates = [
|
||||
(output, field_name, value)
|
||||
for field_name, value in (
|
||||
("output", packed_output),
|
||||
("media", packed_media),
|
||||
("trajectory_latents", packed_latents),
|
||||
("trajectory_timesteps", packed_timesteps),
|
||||
("trajectory_log_probs", packed_log_probs),
|
||||
)
|
||||
if value is not _UNSET
|
||||
]
|
||||
if pending_updates is None:
|
||||
for target, field_name, value in updates:
|
||||
setattr(target, field_name, value)
|
||||
else:
|
||||
pending_updates.extend(updates)
|
||||
return output
|
||||
|
||||
|
||||
@@ -223,35 +381,84 @@ def pack_diffusion_output_shm(
|
||||
|
||||
If *d2h_stream* is provided, D2H copies use that stream (non-blocking on
|
||||
the default stream). The caller must synchronize *d2h_stream* afterward.
|
||||
|
||||
Packing is failure-atomic: every SHM segment created during the call is
|
||||
tracked and unlinked if any part of the payload fails to pack, and field
|
||||
mutations are committed only after the complete payload succeeds.
|
||||
"""
|
||||
created: list[dict[str, Any]] = []
|
||||
pending_updates: list[tuple[DiffusionOutput, str, object]] = []
|
||||
try:
|
||||
packed = _pack_output_shm(
|
||||
output,
|
||||
d2h_stream=d2h_stream,
|
||||
created=created,
|
||||
pending_updates=pending_updates,
|
||||
)
|
||||
except BaseException:
|
||||
_unlink_shm_handles(created)
|
||||
raise
|
||||
|
||||
# Commit mutations only after every field and batch entry packed. Until
|
||||
# this point, a failure leaves the complete caller-owned payload untouched.
|
||||
for target, field_name, value in pending_updates:
|
||||
setattr(target, field_name, value)
|
||||
return packed
|
||||
|
||||
|
||||
def _iter_diffusion_outputs(output: object) -> Iterator[DiffusionOutput]:
|
||||
"""Yield every packable ``DiffusionOutput`` leaf in a worker payload."""
|
||||
if isinstance(output, DiffusionOutput):
|
||||
return _pack_diffusion_fields(output, d2h_stream=d2h_stream)
|
||||
yield output
|
||||
return
|
||||
|
||||
# DP multi-concurrency: {"dp_rank": int, "output": DiffusionOutput}
|
||||
if isinstance(output, dict) and "dp_rank" in output and "output" in output:
|
||||
inner = output["output"]
|
||||
if isinstance(inner, DiffusionOutput):
|
||||
output["output"] = _pack_diffusion_fields(inner, d2h_stream=d2h_stream)
|
||||
return output
|
||||
yield inner
|
||||
return
|
||||
|
||||
if _is_rpc_result_envelope(output):
|
||||
result = output.get("result")
|
||||
output["result"] = pack_diffusion_output_shm(result, d2h_stream=d2h_stream)
|
||||
return output
|
||||
yield from _iter_diffusion_outputs(output.get("result"))
|
||||
return
|
||||
|
||||
result = getattr(output, "result", None)
|
||||
if isinstance(result, DiffusionOutput):
|
||||
output.result = _pack_diffusion_fields(result, d2h_stream=d2h_stream)
|
||||
yield result
|
||||
|
||||
runner_outputs = getattr(output, "runner_outputs", None)
|
||||
if isinstance(runner_outputs, list):
|
||||
for runner_output in runner_outputs:
|
||||
pack_diffusion_output_shm(runner_output, d2h_stream=d2h_stream)
|
||||
yield from _iter_diffusion_outputs(runner_output)
|
||||
|
||||
|
||||
def payload_carries_typed_media(output: object) -> bool:
|
||||
"""True if *output* carries any typed ``DiffusionOutput.media`` payload."""
|
||||
return any(item.media is not None for item in _iter_diffusion_outputs(output))
|
||||
|
||||
|
||||
def _pack_output_shm(
|
||||
output: object,
|
||||
*,
|
||||
d2h_stream: torch.Stream | None,
|
||||
created: list[dict[str, Any]],
|
||||
pending_updates: list[tuple[DiffusionOutput, str, object]],
|
||||
) -> object:
|
||||
for item in _iter_diffusion_outputs(output):
|
||||
_pack_diffusion_fields(
|
||||
item,
|
||||
d2h_stream=d2h_stream,
|
||||
created=created,
|
||||
pending_updates=pending_updates,
|
||||
)
|
||||
return output
|
||||
|
||||
|
||||
def _unpack_diffusion_fields(output: DiffusionOutput) -> DiffusionOutput:
|
||||
output.output = _unpack_if_shm_handle(output.output)
|
||||
if isinstance(output.media, dict):
|
||||
output.media = _unpack_diffusion_media(output.media)
|
||||
output.trajectory_latents = _unpack_if_shm_handle(output.trajectory_latents)
|
||||
output.trajectory_timesteps = _unpack_if_shm_handle(output.trajectory_timesteps)
|
||||
output.trajectory_log_probs = _unpack_if_shm_handle(output.trajectory_log_probs)
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field, replace
|
||||
from enum import Enum
|
||||
from typing import Literal
|
||||
|
||||
import torch
|
||||
|
||||
|
||||
class VideoTensorLayout(str, Enum):
|
||||
BCTHW = "bcthw"
|
||||
BTHWC = "bthwc"
|
||||
|
||||
|
||||
class VideoTensorEncoding(str, Enum):
|
||||
NORMALIZED_FLOAT = "normalized_float"
|
||||
UINT8_FRAMES = "uint8_frames"
|
||||
|
||||
|
||||
class VideoValueRange(str, Enum):
|
||||
NEGATIVE_ONE_TO_ONE = "negative_one_to_one"
|
||||
ZERO_TO_ONE = "zero_to_one"
|
||||
ZERO_TO_255 = "zero_to_255"
|
||||
|
||||
|
||||
class VideoColorModel(str, Enum):
|
||||
RGB = "rgb"
|
||||
|
||||
|
||||
class FloatVideoConsumer(str, Enum):
|
||||
FRAME_INTERPOLATION = "frame_interpolation"
|
||||
VIDEO_GUARDRAILS = "video_guardrails"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class VideoTensorSpec:
|
||||
layout: VideoTensorLayout
|
||||
encoding: VideoTensorEncoding
|
||||
value_range: VideoValueRange
|
||||
color_model: VideoColorModel = VideoColorModel.RGB
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class VideoTransportConstraints:
|
||||
pending_float_consumers: frozenset[FloatVideoConsumer] = frozenset()
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class VideoMediaOutput:
|
||||
tensor: torch.Tensor
|
||||
spec: VideoTensorSpec
|
||||
constraints: VideoTransportConstraints = field(default_factory=VideoTransportConstraints)
|
||||
schema_version: Literal[1] = 1
|
||||
|
||||
def validate(self) -> None:
|
||||
if self.schema_version != 1:
|
||||
raise ValueError(f"Unsupported video media schema version: {self.schema_version}")
|
||||
if not isinstance(self.spec, VideoTensorSpec):
|
||||
raise TypeError(f"Video media spec must be a VideoTensorSpec, got {type(self.spec).__name__}")
|
||||
if not isinstance(self.constraints, VideoTransportConstraints):
|
||||
raise TypeError(
|
||||
f"Video media constraints must be VideoTransportConstraints, got {type(self.constraints).__name__}"
|
||||
)
|
||||
if not isinstance(self.constraints.pending_float_consumers, frozenset):
|
||||
raise TypeError("pending_float_consumers must be a frozenset")
|
||||
if not isinstance(self.tensor, torch.Tensor):
|
||||
raise TypeError(f"Video media tensor must be a torch.Tensor, got {type(self.tensor).__name__}")
|
||||
if self.tensor.ndim != 5:
|
||||
raise ValueError(f"Video media tensor must be rank 5, got shape {tuple(self.tensor.shape)}")
|
||||
if any(size <= 0 for size in self.tensor.shape):
|
||||
raise ValueError(f"Video media dimensions must be positive, got shape {tuple(self.tensor.shape)}")
|
||||
if self.spec.color_model is not VideoColorModel.RGB:
|
||||
raise ValueError(f"Unsupported video color model: {self.spec.color_model}")
|
||||
if any(not isinstance(consumer, FloatVideoConsumer) for consumer in self.constraints.pending_float_consumers):
|
||||
raise ValueError("pending_float_consumers must contain only FloatVideoConsumer values")
|
||||
|
||||
if self.spec.encoding is VideoTensorEncoding.NORMALIZED_FLOAT:
|
||||
self._validate_normalized_float()
|
||||
return
|
||||
if self.spec.encoding is VideoTensorEncoding.UINT8_FRAMES:
|
||||
self._validate_uint8_frames()
|
||||
return
|
||||
raise ValueError(f"Unsupported video tensor encoding: {self.spec.encoding}")
|
||||
|
||||
def _validate_normalized_float(self) -> None:
|
||||
if self.spec.layout is not VideoTensorLayout.BCTHW:
|
||||
raise ValueError("NORMALIZED_FLOAT video must use BCTHW layout")
|
||||
if self.tensor.shape[1] != 3:
|
||||
raise ValueError(f"RGB BCTHW video must have 3 channels, got {self.tensor.shape[1]}")
|
||||
if self.tensor.dtype not in {torch.float16, torch.bfloat16, torch.float32}:
|
||||
raise ValueError(f"NORMALIZED_FLOAT video must use fp16, bf16, or fp32, got {self.tensor.dtype}")
|
||||
if self.spec.value_range not in {
|
||||
VideoValueRange.NEGATIVE_ONE_TO_ONE,
|
||||
VideoValueRange.ZERO_TO_ONE,
|
||||
}:
|
||||
raise ValueError(f"NORMALIZED_FLOAT video has incompatible value range: {self.spec.value_range}")
|
||||
|
||||
def _validate_uint8_frames(self) -> None:
|
||||
if self.spec.layout is not VideoTensorLayout.BTHWC:
|
||||
raise ValueError("UINT8_FRAMES video must use BTHWC layout")
|
||||
if self.tensor.shape[-1] != 3:
|
||||
raise ValueError(f"RGB BTHWC video must have 3 channels, got {self.tensor.shape[-1]}")
|
||||
if self.tensor.dtype is not torch.uint8:
|
||||
raise ValueError(f"UINT8_FRAMES video must use torch.uint8, got {self.tensor.dtype}")
|
||||
if self.spec.value_range is not VideoValueRange.ZERO_TO_255:
|
||||
raise ValueError(f"UINT8_FRAMES video has incompatible value range: {self.spec.value_range}")
|
||||
if self.constraints.pending_float_consumers:
|
||||
raise ValueError("UINT8_FRAMES video cannot have pending float consumers")
|
||||
if not self.tensor.is_contiguous():
|
||||
raise ValueError("UINT8_FRAMES video tensor must be contiguous")
|
||||
|
||||
def with_tensor(self, tensor: torch.Tensor) -> VideoMediaOutput:
|
||||
return replace(self, tensor=tensor)
|
||||
|
||||
def to_cpu(self) -> VideoMediaOutput:
|
||||
return self.with_tensor(self.tensor.detach().cpu())
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class DiffusionMediaOutput:
|
||||
video: VideoMediaOutput
|
||||
# Only the model runner may set this before worker output packing.
|
||||
prepared_for_transport: bool = False
|
||||
|
||||
def validate(self) -> None:
|
||||
if not isinstance(self.video, VideoMediaOutput):
|
||||
raise TypeError(f"Diffusion media video must be a VideoMediaOutput, got {type(self.video).__name__}")
|
||||
if not isinstance(self.prepared_for_transport, bool):
|
||||
raise TypeError("prepared_for_transport must be a bool")
|
||||
self.video.validate()
|
||||
if not self.prepared_for_transport:
|
||||
return
|
||||
if not self.video.tensor.is_contiguous():
|
||||
raise ValueError("Prepared video media tensor must be contiguous")
|
||||
if not _owns_compact_storage(self.video.tensor):
|
||||
raise ValueError("Prepared video media tensor must own request-local storage")
|
||||
|
||||
def with_video(self, video: VideoMediaOutput) -> DiffusionMediaOutput:
|
||||
return replace(self, video=video)
|
||||
|
||||
def to_cpu(self) -> DiffusionMediaOutput:
|
||||
self.validate()
|
||||
moved = self.with_video(self.video.to_cpu())
|
||||
moved.validate()
|
||||
return moved
|
||||
|
||||
|
||||
def _owns_compact_storage(tensor: torch.Tensor) -> bool:
|
||||
"""True if *tensor* is contiguous and backed by exactly its own elements.
|
||||
|
||||
``tensor._base is None`` is not sufficient: ``batch[i : i + 1].detach()`` is
|
||||
contiguous with ``_base=None`` yet keeps a nonzero storage offset and the
|
||||
whole batch storage, so serializing it would leak every other request's
|
||||
pixels. Require a zero offset and a storage sized to the logical elements.
|
||||
"""
|
||||
if not tensor.is_contiguous():
|
||||
return False
|
||||
if tensor.storage_offset() != 0:
|
||||
return False
|
||||
try:
|
||||
storage_bytes = tensor.untyped_storage().nbytes()
|
||||
except Exception:
|
||||
return False
|
||||
return storage_bytes == tensor.numel() * tensor.element_size()
|
||||
|
||||
|
||||
def ensure_request_owned_tensor(tensor: torch.Tensor) -> torch.Tensor:
|
||||
if _owns_compact_storage(tensor):
|
||||
return tensor
|
||||
# A contiguous view may still retain another request's full batch storage.
|
||||
return tensor.clone(memory_format=torch.contiguous_format)
|
||||
|
||||
|
||||
def slice_diffusion_media_output(
|
||||
media: DiffusionMediaOutput,
|
||||
start: int,
|
||||
stop: int,
|
||||
) -> DiffusionMediaOutput:
|
||||
media.validate()
|
||||
source = media.video.tensor
|
||||
tensor = source if start == 0 and stop == source.shape[0] else source[start:stop]
|
||||
sliced = replace(media, video=media.video.with_tensor(tensor), prepared_for_transport=False)
|
||||
sliced.validate()
|
||||
return sliced
|
||||
@@ -26,6 +26,14 @@ from vllm_omni.diffusion.distributed.pipeline_parallel import AsyncLatents, Pipe
|
||||
from vllm_omni.diffusion.distributed.utils import get_local_device
|
||||
from vllm_omni.diffusion.forward_context import DenoiseProgressMixin
|
||||
from vllm_omni.diffusion.lora.loader import WanLoraLoaderMixin
|
||||
from vllm_omni.diffusion.media import (
|
||||
DiffusionMediaOutput,
|
||||
VideoMediaOutput,
|
||||
VideoTensorEncoding,
|
||||
VideoTensorLayout,
|
||||
VideoTensorSpec,
|
||||
VideoValueRange,
|
||||
)
|
||||
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
|
||||
from vllm_omni.diffusion.model_loader.hub_prefetch import from_pretrained_with_prefetch, prefetch_subfolders
|
||||
from vllm_omni.diffusion.models.dmd2 import DMD2PipelineMixin
|
||||
@@ -907,6 +915,7 @@ class Wan22Pipeline(
|
||||
|
||||
if DEBUG_PERF:
|
||||
_t_decode_start = time.perf_counter()
|
||||
media = None
|
||||
if output_type == "latent":
|
||||
output = latents
|
||||
else:
|
||||
@@ -920,7 +929,27 @@ class Wan22Pipeline(
|
||||
latents.device, latents.dtype
|
||||
)
|
||||
latents = latents / latents_std + latents_mean
|
||||
output = self.vae.decode(latents, return_dict=False)[0]
|
||||
decoded = self.vae.decode(latents, return_dict=False)[0]
|
||||
# Distributed VAE decode uses broadcast_result=False, so only the
|
||||
# output-owning rank receives the full [B, C, T, H, W] video; other
|
||||
# ranks get an empty placeholder. Emit typed media only from the
|
||||
# owning rank and keep the placeholder on the legacy output field, so
|
||||
# the media batch-dimension check in split_diffusion_output_by_request
|
||||
# does not trip on every non-owner rank.
|
||||
if decoded.dim() == 5:
|
||||
output = None
|
||||
media = DiffusionMediaOutput(
|
||||
video=VideoMediaOutput(
|
||||
tensor=decoded,
|
||||
spec=VideoTensorSpec(
|
||||
layout=VideoTensorLayout.BCTHW,
|
||||
encoding=VideoTensorEncoding.NORMALIZED_FLOAT,
|
||||
value_range=VideoValueRange.NEGATIVE_ONE_TO_ONE,
|
||||
),
|
||||
)
|
||||
)
|
||||
else:
|
||||
output = decoded
|
||||
|
||||
if DEBUG_PERF:
|
||||
current_omni_platform.synchronize()
|
||||
@@ -947,6 +976,7 @@ class Wan22Pipeline(
|
||||
return split_diffusion_output_by_request(
|
||||
DiffusionOutput(
|
||||
output=output,
|
||||
media=media,
|
||||
stage_durations=self.stage_durations if hasattr(self, "stage_durations") else None,
|
||||
),
|
||||
req,
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Device-side reduction of decoded video tensors to uint8 frames."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import replace
|
||||
|
||||
import torch
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.media import (
|
||||
DiffusionMediaOutput,
|
||||
FloatVideoConsumer,
|
||||
VideoMediaOutput,
|
||||
VideoTensorEncoding,
|
||||
VideoTensorLayout,
|
||||
VideoTensorSpec,
|
||||
VideoTransportConstraints,
|
||||
VideoValueRange,
|
||||
ensure_request_owned_tensor,
|
||||
)
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
# VaeImageProcessor.denormalize: (x * 0.5 + 0.5).clamp(0, 1)
|
||||
_DENORM_SCALE = 0.5
|
||||
_DENORM_SHIFT = 0.5
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def _request_float_consumers(
|
||||
sampling_params: OmniDiffusionSamplingParams | None,
|
||||
) -> frozenset[FloatVideoConsumer]:
|
||||
if sampling_params is not None and sampling_params.enable_frame_interpolation:
|
||||
return frozenset({FloatVideoConsumer.FRAME_INTERPOLATION})
|
||||
return frozenset()
|
||||
|
||||
|
||||
def _request_supports_uint8_frames(sampling_params: OmniDiffusionSamplingParams | None) -> bool:
|
||||
return sampling_params is None or (sampling_params.output_type or "np") == "np"
|
||||
|
||||
|
||||
def _prepare_float_media_for_transport(
|
||||
media: DiffusionMediaOutput,
|
||||
video: VideoMediaOutput,
|
||||
) -> DiffusionMediaOutput:
|
||||
prepared = replace(
|
||||
media,
|
||||
video=video.with_tensor(ensure_request_owned_tensor(video.tensor)),
|
||||
prepared_for_transport=True,
|
||||
)
|
||||
prepared.validate()
|
||||
return prepared
|
||||
|
||||
|
||||
def prepare_diffusion_media_for_transport(
|
||||
media: DiffusionMediaOutput,
|
||||
*,
|
||||
od_config: OmniDiffusionConfig,
|
||||
sampling_params: OmniDiffusionSamplingParams | None = None,
|
||||
) -> DiffusionMediaOutput:
|
||||
"""Validate and prepare one request-local media output before D2H."""
|
||||
media.validate()
|
||||
if media.prepared_for_transport:
|
||||
# Only the model runner prepares media, exactly once, on media the
|
||||
# pipeline emits unprepared. Accepting pre-prepared media here would let
|
||||
# a pipeline forge runner-owned state and skip request policy (e.g. a
|
||||
# forged uint8 payload silently bypasses frame interpolation).
|
||||
raise ValueError(
|
||||
"Media reached transport preparation already prepared; pipelines must "
|
||||
"emit unprepared media so request policy is applied by the runner"
|
||||
)
|
||||
if media.video.spec.encoding is not VideoTensorEncoding.NORMALIZED_FLOAT:
|
||||
raise ValueError("Pipelines must emit unprepared media as NORMALIZED_FLOAT video")
|
||||
|
||||
video = media.video
|
||||
constraints = VideoTransportConstraints(
|
||||
pending_float_consumers=(video.constraints.pending_float_consumers | _request_float_consumers(sampling_params))
|
||||
)
|
||||
constrained_video = replace(video, constraints=constraints)
|
||||
|
||||
enabled = od_config.video_output_transport.enable_device_postprocess
|
||||
output_supported = _request_supports_uint8_frames(sampling_params)
|
||||
if not enabled or constraints.pending_float_consumers or not output_supported:
|
||||
if not enabled:
|
||||
reason = "disabled"
|
||||
elif constraints.pending_float_consumers:
|
||||
reason = ",".join(sorted(consumer.value for consumer in constraints.pending_float_consumers))
|
||||
else:
|
||||
reason = "unsupported_presentation"
|
||||
logger.debug("Device video preparation kept normalized float: reason=%s", reason)
|
||||
return _prepare_float_media_for_transport(media, constrained_video)
|
||||
|
||||
try:
|
||||
frames = reduce_video_to_uint8_frames(
|
||||
constrained_video.tensor,
|
||||
do_denormalize=constrained_video.spec.value_range is VideoValueRange.NEGATIVE_ONE_TO_ONE,
|
||||
)
|
||||
except torch.OutOfMemoryError:
|
||||
logger.warning("Device video preparation ran out of memory; using normalized float transport")
|
||||
else:
|
||||
prepared_video = replace(
|
||||
constrained_video,
|
||||
tensor=frames,
|
||||
spec=VideoTensorSpec(
|
||||
layout=VideoTensorLayout.BTHWC,
|
||||
encoding=VideoTensorEncoding.UINT8_FRAMES,
|
||||
value_range=VideoValueRange.ZERO_TO_255,
|
||||
),
|
||||
constraints=VideoTransportConstraints(),
|
||||
)
|
||||
prepared = replace(media, video=prepared_video, prepared_for_transport=True)
|
||||
prepared.validate()
|
||||
logger.debug(
|
||||
"Device video preparation converted normalized float to uint8: shape=%s",
|
||||
tuple(frames.shape),
|
||||
)
|
||||
return prepared
|
||||
|
||||
# Leave the exception handler before allocator cleanup and fallback
|
||||
# construction. A late conversion OOM otherwise keeps the helper traceback
|
||||
# (and its live float32 intermediates) reachable while the fallback may need
|
||||
# to clone a non-compact request view.
|
||||
current_omni_platform.empty_cache()
|
||||
current_omni_platform.synchronize()
|
||||
return _prepare_float_media_for_transport(media, constrained_video)
|
||||
|
||||
|
||||
def reduce_video_to_uint8_frames(video: torch.Tensor, *, do_denormalize: bool = True) -> torch.Tensor:
|
||||
"""Reduce a decoded ``[B, C, F, H, W]`` video to uint8 ``[B, F, H, W, C]`` frames.
|
||||
|
||||
Runs denormalize/clamp/permute/round on the input's device so the following
|
||||
D2H copy carries uint8 instead of float. The result matches
|
||||
``VideoProcessor.postprocess_video(output_type="np")`` then the ``*255``
|
||||
rounding done in the API server. Pass ``do_denormalize=False`` for VAEs that
|
||||
already emit ``[0, 1]``.
|
||||
"""
|
||||
if video.dim() != 5:
|
||||
raise ValueError(f"expected a [B, C, F, H, W] video tensor, got shape {tuple(video.shape)}")
|
||||
|
||||
# Match the numpy path, which promotes to float before scaling.
|
||||
frames = video.to(torch.float32)
|
||||
if do_denormalize:
|
||||
frames = frames.mul(_DENORM_SCALE).add(_DENORM_SHIFT).clamp_(0.0, 1.0)
|
||||
else:
|
||||
frames = frames.clamp(0.0, 1.0)
|
||||
frames = frames.permute(0, 2, 3, 4, 1)
|
||||
frames = frames.mul_(255.0).round_().clamp_(0.0, 255.0).to(torch.uint8)
|
||||
return frames.contiguous()
|
||||
@@ -0,0 +1,92 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import replace
|
||||
|
||||
from vllm_omni.diffusion.media import (
|
||||
DiffusionMediaOutput,
|
||||
FloatVideoConsumer,
|
||||
VideoTensorEncoding,
|
||||
VideoTensorLayout,
|
||||
VideoTransportConstraints,
|
||||
VideoValueRange,
|
||||
)
|
||||
from vllm_omni.diffusion.postprocess.rife_interpolator import interpolate_video_tensor
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
|
||||
|
||||
|
||||
def finalize_diffusion_media(
|
||||
media: DiffusionMediaOutput,
|
||||
*,
|
||||
sampling_params: OmniDiffusionSamplingParams,
|
||||
) -> dict[str, object]:
|
||||
"""Finalize typed video media without invoking a model postprocessor."""
|
||||
media.validate()
|
||||
if not media.prepared_for_transport:
|
||||
raise ValueError("Diffusion media reached the engine before transport preparation")
|
||||
|
||||
video = media.video
|
||||
metadata: dict[str, object] = {}
|
||||
consumers = video.constraints.pending_float_consumers
|
||||
if FloatVideoConsumer.FRAME_INTERPOLATION in consumers:
|
||||
if video.spec.encoding is not VideoTensorEncoding.NORMALIZED_FLOAT:
|
||||
raise ValueError("Frame interpolation requires NORMALIZED_FLOAT video")
|
||||
# RIFE guesses [0,1] vs [-1,1] from the tensor's min/max, so relying on
|
||||
# the sample content misclassifies both an all-nonnegative [-1,1] clip
|
||||
# (read as [0,1]) and a [0,1] clip whose single bf16 value overshoots 1
|
||||
# (read as [-1,1]). Always map to unit range per the declared spec and
|
||||
# clamp to [0,1] before RIFE, then restore the declared range so
|
||||
# downstream denormalization is correct regardless of the sample.
|
||||
to_negative_one = video.spec.value_range is VideoValueRange.NEGATIVE_ONE_TO_ONE
|
||||
if to_negative_one:
|
||||
interp_input = video.tensor.mul(0.5).add(0.5).clamp_(0.0, 1.0)
|
||||
else:
|
||||
interp_input = video.tensor.clamp(0.0, 1.0)
|
||||
interpolated, multiplier = interpolate_video_tensor(
|
||||
interp_input,
|
||||
exp=sampling_params.frame_interpolation_exp,
|
||||
scale=sampling_params.frame_interpolation_scale,
|
||||
model_path=sampling_params.frame_interpolation_model_path,
|
||||
)
|
||||
if to_negative_one:
|
||||
interpolated = interpolated.mul(2.0).sub(1.0)
|
||||
consumers = consumers - {FloatVideoConsumer.FRAME_INTERPOLATION}
|
||||
video = replace(
|
||||
video,
|
||||
tensor=interpolated,
|
||||
constraints=VideoTransportConstraints(pending_float_consumers=frozenset(consumers)),
|
||||
)
|
||||
metadata["video"] = {"video_fps_multiplier": multiplier}
|
||||
|
||||
if consumers:
|
||||
names = sorted(consumer.value for consumer in consumers)
|
||||
raise ValueError(f"Video has pending float consumers at finalization: {names}")
|
||||
|
||||
output_type = getattr(sampling_params, "output_type", None) or "np"
|
||||
if output_type == "latent":
|
||||
raise ValueError("Latent output cannot be finalized from VideoMediaOutput")
|
||||
|
||||
if video.spec.encoding is VideoTensorEncoding.UINT8_FRAMES:
|
||||
if video.spec.layout is not VideoTensorLayout.BTHWC:
|
||||
raise ValueError("UINT8_FRAMES video must use BTHWC layout")
|
||||
if output_type != "np":
|
||||
raise ValueError(f"UINT8_FRAMES finalization does not support output_type={output_type!r}")
|
||||
frames = video.tensor.detach().cpu().numpy()
|
||||
else:
|
||||
if video.spec.layout is not VideoTensorLayout.BCTHW:
|
||||
raise ValueError("NORMALIZED_FLOAT video must use BCTHW layout")
|
||||
from diffusers.video_processor import VideoProcessor
|
||||
|
||||
do_denormalize = video.spec.value_range is VideoValueRange.NEGATIVE_ONE_TO_ONE
|
||||
frames = VideoProcessor(vae_scale_factor=8).postprocess_video(
|
||||
video.tensor,
|
||||
output_type=output_type,
|
||||
do_denormalize=[do_denormalize] * video.tensor.shape[2],
|
||||
)
|
||||
|
||||
return {
|
||||
"payload": {"video": frames},
|
||||
"metadata": metadata,
|
||||
}
|
||||
@@ -53,6 +53,7 @@ from vllm_omni.diffusion.models.interface import (
|
||||
)
|
||||
from vllm_omni.diffusion.offloader import enable_offload_backend
|
||||
from vllm_omni.diffusion.offloader.config import TEXT_ENCODER_COMPONENT, resolve_offload
|
||||
from vllm_omni.diffusion.postprocess.device_reduction import prepare_diffusion_media_for_transport
|
||||
from vllm_omni.diffusion.registry import _NO_CACHE_ACCELERATION
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.diffusion.sched.interface import (
|
||||
@@ -680,6 +681,21 @@ class DiffusionModelRunner(OmniConnectorModelRunnerMixin):
|
||||
od_config.cache_backend,
|
||||
)
|
||||
|
||||
def _prepare_output_for_transport(
|
||||
self,
|
||||
output: DiffusionOutput,
|
||||
sampling_params: OmniDiffusionSamplingParams,
|
||||
) -> DiffusionOutput:
|
||||
if output.media is not None:
|
||||
if output.output is not None:
|
||||
raise ValueError("DiffusionOutput cannot contain both media and legacy output")
|
||||
output.media = prepare_diffusion_media_for_transport(
|
||||
output.media,
|
||||
od_config=self.od_config,
|
||||
sampling_params=sampling_params,
|
||||
)
|
||||
return output
|
||||
|
||||
def _runner_output_from_outputs(
|
||||
self,
|
||||
reqs: list[OmniDiffusionRequest],
|
||||
@@ -774,6 +790,11 @@ class DiffusionModelRunner(OmniConnectorModelRunnerMixin):
|
||||
allow_single_output=allow_single_output,
|
||||
pipeline_name=type(self.pipeline).__name__,
|
||||
)
|
||||
with record_function("prepare_output_for_transport"):
|
||||
outputs = [
|
||||
self._prepare_output_for_transport(output, req.sampling_params)
|
||||
for req, output in zip(reqs, outputs, strict=True)
|
||||
]
|
||||
|
||||
if is_primary and outputs and record_output_peak_memory:
|
||||
batch_peak_memory_mb = self._sample_peak_memory_mb()
|
||||
@@ -1289,6 +1310,7 @@ class DiffusionModelRunner(OmniConnectorModelRunnerMixin):
|
||||
clear_pipeline_stage_durations(self.pipeline)
|
||||
result = self.pipeline.post_decode(req)
|
||||
if result is not None:
|
||||
result = self._prepare_output_for_transport(result, req.sampling)
|
||||
self._attach_stepwise_metadata(
|
||||
req,
|
||||
result,
|
||||
|
||||
@@ -64,7 +64,11 @@ from vllm_omni.diffusion.distributed.parallel_state import (
|
||||
model_parallel_is_initialized,
|
||||
)
|
||||
from vllm_omni.diffusion.forward_context import set_forward_context
|
||||
from vllm_omni.diffusion.ipc import DIFFUSION_RPC_RESULT_ENVELOPE, pack_diffusion_output_shm
|
||||
from vllm_omni.diffusion.ipc import (
|
||||
DIFFUSION_RPC_RESULT_ENVELOPE,
|
||||
pack_diffusion_output_shm,
|
||||
payload_carries_typed_media,
|
||||
)
|
||||
from vllm_omni.diffusion.lora.manager import DiffusionLoRAManager, LoRABackend
|
||||
from vllm_omni.diffusion.registry import get_diffusion_ir_op_priority_func
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
@@ -1131,7 +1135,15 @@ class WorkerProc:
|
||||
# Sync path (original, or async fallback).
|
||||
try:
|
||||
pack_diffusion_output_shm(output)
|
||||
except (TypeError, ValueError):
|
||||
raise
|
||||
except Exception as e:
|
||||
# Typed media that fails to pack is left unprepared/on device (the
|
||||
# pack is failure-atomic and does not mutate it), so enqueueing it
|
||||
# would ship a broken payload. Re-raise memory/packing failures here
|
||||
# instead of swallowing them for typed media.
|
||||
if payload_carries_typed_media(output):
|
||||
raise
|
||||
if hasattr(output, "output"):
|
||||
logger.warning("SHM pack failed for model output: %s", e)
|
||||
self._enqueue_result(output)
|
||||
|
||||
@@ -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
|
||||
"""Request-level batch abstraction for diffusion runner."""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -12,6 +12,7 @@ import numpy as np
|
||||
import torch
|
||||
|
||||
from vllm_omni.diffusion.data import DiffusionOutput
|
||||
from vllm_omni.diffusion.media import DiffusionMediaOutput, slice_diffusion_media_output
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams, OmniPromptType
|
||||
|
||||
@@ -35,6 +36,18 @@ def split_diffusion_output_by_request(
|
||||
"""Split a batched DiffusionOutput into one output per request."""
|
||||
if num_outputs_per_prompt <= 0:
|
||||
raise ValueError(f"num_outputs_per_prompt must be positive, got {num_outputs_per_prompt}.")
|
||||
if result.media is not None and result.output is not None:
|
||||
raise ValueError("DiffusionOutput cannot contain both media and legacy output")
|
||||
if result.media is not None and not isinstance(result.media, DiffusionMediaOutput):
|
||||
raise TypeError(f"DiffusionOutput.media must be DiffusionMediaOutput, got {type(result.media).__name__}")
|
||||
if result.media is not None:
|
||||
expected_batch = req.num_reqs * num_outputs_per_prompt
|
||||
actual_batch = result.media.video.tensor.shape[0]
|
||||
if actual_batch != expected_batch:
|
||||
raise ValueError(
|
||||
f"Video media batch dimension must equal request_count * num_outputs_per_prompt "
|
||||
f"({expected_batch}), got {actual_batch}"
|
||||
)
|
||||
|
||||
return [
|
||||
DiffusionOutput(
|
||||
@@ -43,6 +56,15 @@ def split_diffusion_output_by_request(
|
||||
idx * num_outputs_per_prompt,
|
||||
(idx + 1) * num_outputs_per_prompt,
|
||||
),
|
||||
media=(
|
||||
slice_diffusion_media_output(
|
||||
result.media,
|
||||
idx * num_outputs_per_prompt,
|
||||
(idx + 1) * num_outputs_per_prompt,
|
||||
)
|
||||
if result.media is not None
|
||||
else None
|
||||
),
|
||||
error=result.error,
|
||||
finished=result.finished,
|
||||
stage_durations=result.stage_durations,
|
||||
|
||||
Reference in new issue
Block a user