[REFACT]Refactor diffusion outputs to payload metadata (#4922)
Signed-off-by: bjf-frz <frz123db@gmail.com>
This commit is contained in:
1 parent
4b9d09cb87
commit
1a4a042a83
44 files changed
+1373
-478
No files matched your search
+12
-11
@@ -1198,8 +1198,10 @@ class DiffusionOutput:
|
||||
Final output (after pipeline completion)
|
||||
"""
|
||||
|
||||
# Fields may be replaced with SHM handle dicts by ipc.pack_diffusion_output_shm
|
||||
output: torch.Tensor | tuple[Any, ...] | dict[str, Any] | None = None
|
||||
|
||||
# Legacy compatibility fields. New pipeline-specific 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
|
||||
@@ -1212,10 +1214,6 @@ class DiffusionOutput:
|
||||
|
||||
post_process_func: Callable[..., Any] | None = None
|
||||
|
||||
# Extra custom output data (e.g. latent trajectories, prompt embeds)
|
||||
# passed through to OmniRequestOutput.custom_output
|
||||
custom_output: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
# logged timings info, directly from Req.timings
|
||||
# timings: Optional["RequestTimings"] = None
|
||||
|
||||
@@ -1230,10 +1228,9 @@ class DiffusionOutput:
|
||||
# memory usage info
|
||||
peak_memory_mb: float = 0.0
|
||||
|
||||
# When True, move all tensor fields (including tensors inside
|
||||
# ``custom_output``) to CPU at construction time. Useful when the output
|
||||
# is shipped across process boundaries (e.g. step-execution mode) and the
|
||||
# receiving side must not initialise a stray CUDA context.
|
||||
# When True, move tensor fields to CPU at construction time. Useful when
|
||||
# the output is shipped across process boundaries (e.g. step-execution
|
||||
# mode) and the receiving side must not initialise a stray CUDA context.
|
||||
to_cpu: bool = False
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
@@ -1243,14 +1240,18 @@ class DiffusionOutput:
|
||||
def _maybe_to_cpu(value: Any) -> Any:
|
||||
if isinstance(value, torch.Tensor):
|
||||
return value.detach().cpu()
|
||||
if isinstance(value, dict):
|
||||
return {key: _maybe_to_cpu(item) for key, item in value.items()}
|
||||
if isinstance(value, list):
|
||||
return [_maybe_to_cpu(item) for item in value]
|
||||
if isinstance(value, tuple):
|
||||
return tuple(_maybe_to_cpu(item) for item in value)
|
||||
return value
|
||||
|
||||
self.output = _maybe_to_cpu(self.output)
|
||||
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)
|
||||
if self.custom_output:
|
||||
self.custom_output = {k: _maybe_to_cpu(v) for k, v in self.custom_output.items()}
|
||||
|
||||
@classmethod
|
||||
def from_exception(cls, exc: BaseException) -> "DiffusionOutput":
|
||||
|
||||
@@ -10,7 +10,7 @@ import queue
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import AsyncGenerator, Iterable
|
||||
from dataclasses import dataclass, field, replace
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import numpy as np
|
||||
@@ -40,7 +40,6 @@ from vllm_omni.diffusion.output_formatter import (
|
||||
)
|
||||
from vllm_omni.diffusion.registry import (
|
||||
DiffusionModelRegistry,
|
||||
get_diffusion_action_post_process_func,
|
||||
get_diffusion_post_process_func,
|
||||
get_diffusion_pre_process_func,
|
||||
)
|
||||
@@ -155,17 +154,10 @@ class DiffusionEngine:
|
||||
self.od_config = od_config
|
||||
|
||||
self.post_process_func = get_diffusion_post_process_func(od_config)
|
||||
self.action_post_process_func = get_diffusion_action_post_process_func(od_config)
|
||||
self.pre_process_func = get_diffusion_pre_process_func(od_config)
|
||||
# Cache whether the model-specific postprocess accepts request-level
|
||||
# sampling params so step() can support both legacy and extended hooks.
|
||||
self._post_process_accepts_sampling_params = _func_accepts_parameter(self.post_process_func, "sampling_params")
|
||||
self._action_post_process_accepts_sampling_params = _func_accepts_parameter(
|
||||
self.action_post_process_func, "sampling_params"
|
||||
)
|
||||
self._action_post_process_accepts_custom_output = _func_accepts_parameter(
|
||||
self.action_post_process_func, "custom_output"
|
||||
)
|
||||
|
||||
self.step_execution = bool(getattr(od_config, "step_execution", False))
|
||||
if self.od_config.streaming_output and not self.step_execution:
|
||||
@@ -307,46 +299,18 @@ class DiffusionEngine:
|
||||
if self.od_config.enable_cpu_offload:
|
||||
output_data = _move_tensor_tree_to_cpu(output_data)
|
||||
|
||||
custom_output = output.custom_output or {}
|
||||
action_payload = None
|
||||
action_only_output = bool(custom_output.get("action_only_output"))
|
||||
|
||||
postprocess_start_time = time.perf_counter()
|
||||
if action_only_output:
|
||||
outputs = []
|
||||
elif self.post_process_func is not None:
|
||||
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:
|
||||
outputs = self.post_process_func(output_data, sampling_params=request.sampling_params)
|
||||
else:
|
||||
outputs = self.post_process_func(output_data)
|
||||
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, custom_output)
|
||||
custom_output = postprocess_output.custom_output
|
||||
action_payload = postprocess_output.action_payload
|
||||
if action_payload is None:
|
||||
action_payload = custom_output.get("actions")
|
||||
if action_payload is not None:
|
||||
postprocess_output = replace(postprocess_output, action_payload=action_payload)
|
||||
action_post_process_func = getattr(self, "action_post_process_func", None)
|
||||
if action_payload is None and action_post_process_func is not None:
|
||||
raw_action_payload = custom_output.get("action")
|
||||
if raw_action_payload is not None:
|
||||
action_kwargs: dict[str, Any] = {}
|
||||
if getattr(self, "_action_post_process_accepts_custom_output", False):
|
||||
action_kwargs["custom_output"] = custom_output
|
||||
if getattr(self, "_action_post_process_accepts_sampling_params", False):
|
||||
action_kwargs["sampling_params"] = request.sampling_params
|
||||
action_payload = action_post_process_func(raw_action_payload, **action_kwargs)
|
||||
custom_output = {**custom_output, "actions": action_payload}
|
||||
postprocess_output = replace(
|
||||
postprocess_output,
|
||||
custom_output=custom_output,
|
||||
action_payload=action_payload,
|
||||
)
|
||||
postprocess_output = normalize_diffusion_postprocess_output(outputs)
|
||||
postprocess_time = time.perf_counter() - postprocess_start_time
|
||||
logger.debug("Post-processing completed in %.4f seconds", postprocess_time)
|
||||
|
||||
|
||||
@@ -60,6 +60,15 @@ def get_audiox_post_process_func(od_config: OmniDiffusionConfig):
|
||||
"""Convert the pipeline's float audio tensor to a CPU numpy array for serving."""
|
||||
|
||||
def post_process_func(audio: torch.Tensor) -> Any:
|
||||
if isinstance(audio, dict) and isinstance(audio.get("payload"), dict):
|
||||
payload = dict(audio["payload"])
|
||||
audio_payload = payload.get("audio")
|
||||
if isinstance(audio_payload, torch.Tensor):
|
||||
payload["audio"] = audio_payload.detach().cpu().float().numpy()
|
||||
return {
|
||||
"payload": payload,
|
||||
"metadata": audio.get("metadata") or {},
|
||||
}
|
||||
if isinstance(audio, torch.Tensor):
|
||||
return audio.detach().cpu().float().numpy()
|
||||
return audio
|
||||
@@ -915,9 +924,10 @@ class AudioXPipeline(nn.Module, SupportAudioOutput, DiffusionPipelineProfilerMix
|
||||
audio = audio[..., :target_samples]
|
||||
|
||||
stage_durations = self.stage_durations if getattr(self, "enable_diffusion_pipeline_profiler", False) else None
|
||||
custom_output = {"audiox_task": task_norm}
|
||||
return DiffusionOutput(
|
||||
output=audio,
|
||||
custom_output=custom_output,
|
||||
output={
|
||||
"payload": {"audio": audio},
|
||||
"metadata": {"audio": {"audiox_task": task_norm}},
|
||||
},
|
||||
stage_durations=stage_durations,
|
||||
)
|
||||
@@ -739,8 +739,10 @@ class BagelPipeline(nn.Module, SupportsComponentDiscovery, DiffusionPipelineProf
|
||||
text_output = text_output.split("<|im_start|>")[-1]
|
||||
|
||||
return DiffusionOutput(
|
||||
output=text_output,
|
||||
custom_output={"text_output": text_output},
|
||||
output={
|
||||
"payload": {"text": text_output},
|
||||
"metadata": {"text": {"text_output": text_output}},
|
||||
},
|
||||
stage_durations=self.stage_durations if hasattr(self, "stage_durations") else None,
|
||||
)
|
||||
|
||||
@@ -847,22 +849,28 @@ class BagelPipeline(nn.Module, SupportsComponentDiscovery, DiffusionPipelineProf
|
||||
if trajectory_log_probs:
|
||||
trajectory_log_probs_stacked = torch.stack(trajectory_log_probs)
|
||||
|
||||
custom = {}
|
||||
payload = {"image": img}
|
||||
metadata = {}
|
||||
if think_text is not None:
|
||||
custom["think_text"] = think_text
|
||||
# Mirror the PIL image into ``custom_output`` so callers reading via
|
||||
# the orchestrator IPC boundary (which strips the bare ``output``
|
||||
# field) can still recover the result. ``video_frames`` already
|
||||
# uses this pattern.
|
||||
custom["image"] = img
|
||||
metadata["text"] = {"think_text": think_text}
|
||||
trajectory_payload = {}
|
||||
if trajectory_latents_stacked is not None:
|
||||
trajectory_payload["latents"] = trajectory_latents_stacked
|
||||
if trajectory_timesteps_stacked is not None:
|
||||
trajectory_payload["timesteps"] = trajectory_timesteps_stacked
|
||||
if trajectory_log_probs_stacked is not None:
|
||||
trajectory_payload["log_probs"] = trajectory_log_probs_stacked
|
||||
if trajectory_decoded is not None:
|
||||
trajectory_payload["decoded"] = trajectory_decoded
|
||||
if trajectory_payload:
|
||||
payload["trajectory"] = trajectory_payload
|
||||
metadata["trajectory"] = {"type": "denoising"}
|
||||
|
||||
return DiffusionOutput(
|
||||
output=img,
|
||||
trajectory_latents=trajectory_latents_stacked,
|
||||
trajectory_timesteps=trajectory_timesteps_stacked,
|
||||
trajectory_log_probs=trajectory_log_probs_stacked,
|
||||
trajectory_decoded=trajectory_decoded,
|
||||
custom_output=custom,
|
||||
output={
|
||||
"payload": payload,
|
||||
"metadata": metadata,
|
||||
},
|
||||
stage_durations=self.stage_durations if hasattr(self, "stage_durations") else None,
|
||||
)
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
|
||||
from .pipeline_cosmos3 import (
|
||||
Cosmos3OmniDiffusersPipeline,
|
||||
get_cosmos3_action_post_process_func,
|
||||
get_cosmos3_post_process_func,
|
||||
get_cosmos3_pre_process_func,
|
||||
)
|
||||
@@ -11,7 +10,6 @@ from .transformer_cosmos3 import Cosmos3VFMTransformer
|
||||
|
||||
__all__ = [
|
||||
"Cosmos3OmniDiffusersPipeline",
|
||||
"get_cosmos3_action_post_process_func",
|
||||
"get_cosmos3_post_process_func",
|
||||
"get_cosmos3_pre_process_func",
|
||||
"Cosmos3VFMTransformer",
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
|
||||
These helpers cover action modes that use action tokens as an auxiliary output
|
||||
stream: ``policy``, ``forward_dynamics``, and ``inverse_dynamics``. The pipeline
|
||||
returns predicted actions through ``custom_output`` rather than as a normal
|
||||
``modalities`` entry.
|
||||
returns predicted actions through the diffusion output payload/metadata
|
||||
envelope rather than as a video frame stream.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -20,7 +20,8 @@ Video generation is further specialized by inputs and extra args:
|
||||
transfer video generation.
|
||||
* ``action_mode``: action-capable video generation. RoboLab/OpenPI observation
|
||||
payloads in ``extra_args["robot_obs"]`` or ``extra_args["observation"]``
|
||||
bypass normal video output and return action-only custom output.
|
||||
bypass normal video output and return an action-only payload/metadata
|
||||
envelope.
|
||||
|
||||
Generated sound is video-only, cannot be combined with action or transfer, and
|
||||
is produced from sound latents rather than from ``multi_modal_data["audio"]``.
|
||||
@@ -133,6 +134,7 @@ from .utils import (
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
COSMOS3_DEFAULT_CONDITION_PIXEL_FRAMES = (
|
||||
max(COSMOS3_DEFAULT_CONDITION_FRAME_INDEXES_VISION) * COSMOS3_VAE_TEMPORAL_COMPRESSION + 1
|
||||
)
|
||||
@@ -530,6 +532,37 @@ def get_cosmos3_post_process_func(od_config: OmniDiffusionConfig):
|
||||
if output_type == "latent":
|
||||
return output
|
||||
|
||||
def _postprocess_action(action: Any, metadata: dict[str, Any]) -> Any:
|
||||
internal_metadata = metadata.get("internal")
|
||||
inputs = (
|
||||
internal_metadata.get("robolab_action_postprocess") if isinstance(internal_metadata, dict) else None
|
||||
)
|
||||
if isinstance(inputs, RoboLabActionPostprocessInputs):
|
||||
return postprocess_robolab_action(action, inputs)
|
||||
return action
|
||||
|
||||
pending_action = None
|
||||
pending_action_metadata: dict[str, Any] = {}
|
||||
envelope_public_metadata: dict[str, Any] = {}
|
||||
if isinstance(output, dict) and isinstance(output.get("payload"), dict):
|
||||
envelope_payload = dict(output.get("payload") or {})
|
||||
metadata = output.get("metadata") or {}
|
||||
envelope_metadata = metadata if isinstance(metadata, dict) else {}
|
||||
envelope_public_metadata = {key: value for key, value in envelope_metadata.items() if key != "internal"}
|
||||
action = envelope_payload.pop("actions", None)
|
||||
if action is not None:
|
||||
pending_action = _postprocess_action(action, envelope_metadata)
|
||||
pending_action_metadata = envelope_public_metadata
|
||||
if not envelope_payload:
|
||||
return {
|
||||
"payload": {
|
||||
"video": [],
|
||||
"actions": pending_action,
|
||||
},
|
||||
"metadata": pending_action_metadata,
|
||||
}
|
||||
output = envelope_payload
|
||||
|
||||
audio = None
|
||||
audio_sample_rate = None
|
||||
if isinstance(output, dict):
|
||||
@@ -568,11 +601,31 @@ def get_cosmos3_post_process_func(od_config: OmniDiffusionConfig):
|
||||
# check_video_safety expects a 5D tensor; re-add T axis.
|
||||
checked = check_video_safety(image.unsqueeze(2))
|
||||
image = checked.squeeze(2)
|
||||
return video_processor.postprocess(image, output_type="pil")
|
||||
if is_guardrails_enabled(od_config, sampling_params):
|
||||
processed_image = video_processor.postprocess(image, output_type="pil")
|
||||
if envelope_public_metadata:
|
||||
return {
|
||||
"payload": {"image": processed_image},
|
||||
"metadata": envelope_public_metadata,
|
||||
}
|
||||
return processed_image
|
||||
guardrails_enabled = is_guardrails_enabled(od_config, sampling_params)
|
||||
if guardrails_enabled:
|
||||
video = check_video_safety(video)
|
||||
processed_video = video_processor.postprocess_video(video, output_type=output_type)
|
||||
if audio is None:
|
||||
if pending_action is not None:
|
||||
return {
|
||||
"payload": {
|
||||
"video": processed_video,
|
||||
"actions": pending_action,
|
||||
},
|
||||
"metadata": pending_action_metadata,
|
||||
}
|
||||
if envelope_public_metadata:
|
||||
return {
|
||||
"payload": {"video": processed_video},
|
||||
"metadata": envelope_public_metadata,
|
||||
}
|
||||
return processed_video
|
||||
if isinstance(audio, torch.Tensor):
|
||||
audio = audio.detach().cpu()
|
||||
@@ -583,33 +636,38 @@ def get_cosmos3_post_process_func(od_config: OmniDiffusionConfig):
|
||||
}
|
||||
if audio_sample_rate is not None:
|
||||
result["audio_sample_rate"] = int(audio_sample_rate)
|
||||
if pending_action is not None:
|
||||
return {
|
||||
"payload": {
|
||||
"video": result["video"],
|
||||
"audio": result["audio"],
|
||||
"actions": pending_action,
|
||||
},
|
||||
"metadata": {
|
||||
**pending_action_metadata,
|
||||
"video": {"fps": result["fps"]},
|
||||
"audio": {"sample_rate": result.get("audio_sample_rate")},
|
||||
},
|
||||
}
|
||||
if envelope_public_metadata:
|
||||
return {
|
||||
"payload": {
|
||||
"video": result["video"],
|
||||
"audio": result["audio"],
|
||||
},
|
||||
"metadata": {
|
||||
**envelope_public_metadata,
|
||||
"video": {"fps": result["fps"], **envelope_public_metadata.get("video", {})}
|
||||
if isinstance(envelope_public_metadata.get("video"), dict)
|
||||
else {"fps": result["fps"]},
|
||||
"audio": {"sample_rate": result.get("audio_sample_rate")},
|
||||
},
|
||||
}
|
||||
return result
|
||||
|
||||
return post_process_func
|
||||
|
||||
|
||||
def get_cosmos3_action_post_process_func(od_config: OmniDiffusionConfig):
|
||||
"""Build the custom-output postprocessor for Cosmos3 action predictions.
|
||||
|
||||
Action modes return predicted action tensors in ``custom_output`` alongside
|
||||
normal video output. RoboLab/OpenPI policy serving marks action-only output
|
||||
and carries observation metadata used here to map model-space actions back
|
||||
to the requested robot action representation.
|
||||
"""
|
||||
del od_config
|
||||
|
||||
def action_post_process_func(action: Any, custom_output: dict[str, Any] | None = None, sampling_params=None):
|
||||
del sampling_params
|
||||
inputs = custom_output.get("robolab_action_postprocess") if isinstance(custom_output, dict) else None
|
||||
if isinstance(inputs, RoboLabActionPostprocessInputs):
|
||||
processed_action = postprocess_robolab_action(action, inputs)
|
||||
custom_output.pop("robolab_action_postprocess", None)
|
||||
return processed_action
|
||||
return action
|
||||
|
||||
return action_post_process_func
|
||||
|
||||
|
||||
def get_cosmos3_ir_op_priority_func(od_config: OmniDiffusionConfig):
|
||||
del od_config
|
||||
|
||||
@@ -669,9 +727,10 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
T2I, transfer, and action+sound are rejected.
|
||||
* **Action generation** when ``action_mode`` is provided. ``policy`` and
|
||||
``forward_dynamics`` require an image or video input; ``inverse_dynamics``
|
||||
requires video input. Action predictions are returned in ``custom_output``.
|
||||
requires video input. Action predictions are returned in the diffusion
|
||||
output payload/metadata envelope.
|
||||
RoboLab/OpenPI observations in ``extra_args['robot_obs']`` or
|
||||
``extra_args['observation']`` return action-only custom output.
|
||||
``extra_args['observation']`` return an action-only envelope.
|
||||
* **T2V** otherwise (default video generation).
|
||||
"""
|
||||
|
||||
@@ -1409,15 +1468,25 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
logger.info("Total pipeline time: %.2fs", time.time() - pipeline_start)
|
||||
|
||||
action = action_latents[:, :, :raw_action_dim].detach().cpu()
|
||||
custom_action_output: dict[str, Any] = {
|
||||
"action": action,
|
||||
"raw_action_dim": raw_action_dim,
|
||||
"action_mode": action_mode,
|
||||
"domain_id": domain_id,
|
||||
"action_only_output": True,
|
||||
"robolab_action_postprocess": make_robolab_action_postprocess_inputs(inputs),
|
||||
action_output: dict[str, Any] = {
|
||||
"payload": {
|
||||
"actions": action,
|
||||
},
|
||||
"metadata": {
|
||||
"actions": {
|
||||
"raw_action_dim": raw_action_dim,
|
||||
"action_mode": action_mode,
|
||||
"domain_id": domain_id,
|
||||
},
|
||||
"common": {
|
||||
"action_only_output": True,
|
||||
},
|
||||
"internal": {
|
||||
"robolab_action_postprocess": make_robolab_action_postprocess_inputs(inputs),
|
||||
},
|
||||
},
|
||||
}
|
||||
return DiffusionOutput(output={}, custom_output=custom_action_output)
|
||||
return DiffusionOutput(output=action_output)
|
||||
|
||||
@staticmethod
|
||||
def _truthy(value) -> bool:
|
||||
@@ -2881,11 +2950,15 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
full_output = torch.cat([normalized_input.to(full_output), full_output], dim=-1)
|
||||
|
||||
return DiffusionOutput(
|
||||
output={"video": full_output},
|
||||
custom_output={
|
||||
"transfer_controls": full_controls,
|
||||
"transfer_hints": list(per_hint_frames),
|
||||
"fps": frame_rate,
|
||||
output={
|
||||
"payload": {"video": full_output},
|
||||
"metadata": {
|
||||
"transfer": {
|
||||
"controls": full_controls,
|
||||
"hints": list(per_hint_frames),
|
||||
},
|
||||
"video": {"fps": frame_rate},
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
@@ -3287,12 +3360,18 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
raise ValueError("Cosmos3 action generation finished without action latents.")
|
||||
action = action_latents[:, :, :raw_action_dim].detach().cpu()
|
||||
return DiffusionOutput(
|
||||
output={"video": video},
|
||||
custom_output={
|
||||
"action": action,
|
||||
"raw_action_dim": raw_action_dim,
|
||||
"action_mode": action_mode,
|
||||
"domain_id": domain_id,
|
||||
output={
|
||||
"payload": {
|
||||
"video": video,
|
||||
"actions": action,
|
||||
},
|
||||
"metadata": {
|
||||
"actions": {
|
||||
"raw_action_dim": raw_action_dim,
|
||||
"action_mode": action_mode,
|
||||
"domain_id": domain_id,
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@@ -2209,7 +2209,6 @@ class HunyuanImage3Pipeline(
|
||||
if output_type == "latent":
|
||||
return DiffusionOutput(
|
||||
output=latents,
|
||||
custom_output={},
|
||||
stage_durations=getattr(self, "stage_durations", None),
|
||||
)
|
||||
|
||||
@@ -2232,12 +2231,14 @@ class HunyuanImage3Pipeline(
|
||||
)
|
||||
|
||||
cot_text_list = state.extra.get(_STEP_COT_TEXT_LIST) or []
|
||||
custom_output = {}
|
||||
metadata = {}
|
||||
if any(text is not None for text in cot_text_list):
|
||||
custom_output["ar_generated_text"] = cot_text_list[0]
|
||||
metadata["text"] = {"ar_generated_text": cot_text_list[0]}
|
||||
return DiffusionOutput(
|
||||
output=image[0],
|
||||
custom_output=custom_output,
|
||||
output={
|
||||
"payload": {"image": image[0]},
|
||||
"metadata": metadata,
|
||||
},
|
||||
stage_durations=getattr(self, "stage_durations", None),
|
||||
)
|
||||
|
||||
@@ -2302,12 +2303,14 @@ class HunyuanImage3Pipeline(
|
||||
|
||||
outputs = self._generate(**model_inputs, **kwargs)
|
||||
image = outputs[0]
|
||||
custom_output = {}
|
||||
metadata = {}
|
||||
if any(t is not None for t in cot_text_list):
|
||||
custom_output["ar_generated_text"] = cot_text_list[0] if len(cot_text_list) == 1 else cot_text_list
|
||||
metadata["text"] = {"ar_generated_text": cot_text_list[0] if len(cot_text_list) == 1 else cot_text_list}
|
||||
stage_durations = self.stage_durations if hasattr(self, "stage_durations") else None
|
||||
return DiffusionOutput(
|
||||
output=image,
|
||||
custom_output=custom_output,
|
||||
output={
|
||||
"payload": {"image": image},
|
||||
"metadata": metadata,
|
||||
},
|
||||
stage_durations=stage_durations,
|
||||
)
|
||||
@@ -247,11 +247,13 @@ class InternVLAA1Pipeline(nn.Module, DiffusionPipelineProfilerMixin):
|
||||
noise=extra_args.get("noise"),
|
||||
decode_image=bool(extra_args.get("decode_image", False)),
|
||||
)
|
||||
custom_output: dict[str, Any] = {}
|
||||
metadata: dict[str, Any] = {}
|
||||
if decoded is not None:
|
||||
custom_output["decoded"] = decoded
|
||||
metadata["actions"] = {"decoded": decoded}
|
||||
return DiffusionOutput(
|
||||
output=output,
|
||||
custom_output=custom_output,
|
||||
output={
|
||||
"payload": {"actions": output},
|
||||
"metadata": metadata,
|
||||
},
|
||||
post_process_func=get_internvla_a1_post_process_func(self.od_config),
|
||||
)
|
||||
@@ -836,8 +836,10 @@ class LancePipeline(BagelPipeline):
|
||||
frames = [Image.fromarray(f) for f in frames_np]
|
||||
logger.info("Lance t2v: decoded %d frames at %dx%d", len(frames), frames[0].width, frames[0].height)
|
||||
return DiffusionOutput(
|
||||
output=frames[0],
|
||||
custom_output={"video_frames": frames, "video_shape": video_shape},
|
||||
output={
|
||||
"payload": {"video": frames},
|
||||
"metadata": {"video": {"shape": video_shape}},
|
||||
},
|
||||
stage_durations=self.stage_durations if hasattr(self, "stage_durations") else None,
|
||||
)
|
||||
|
||||
@@ -1069,13 +1071,11 @@ class LancePipeline(BagelPipeline):
|
||||
)
|
||||
|
||||
img = self._decode_image_from_latent(self.bagel, self.vae, latents[0], image_shape)
|
||||
# Put the PIL image into ``custom_output`` too — the orchestrator
|
||||
# serializes ``custom_output`` across the IPC boundary but strips
|
||||
# the bare ``output`` field, so consumers that only see
|
||||
# ``outputs[0].output`` (e.g. gradio_demo) get ``None`` otherwise.
|
||||
return DiffusionOutput(
|
||||
output=img,
|
||||
custom_output={"image": img, "image_shape": image_shape},
|
||||
output={
|
||||
"payload": {"image": img},
|
||||
"metadata": {"image": {"shape": image_shape}},
|
||||
},
|
||||
stage_durations=self.stage_durations if hasattr(self, "stage_durations") else None,
|
||||
)
|
||||
|
||||
@@ -1361,8 +1361,10 @@ class LancePipeline(BagelPipeline):
|
||||
frames_np = self._decode_video_from_latent(self.bagel, self.vae, latents[0], out_shape)
|
||||
frames = [Image.fromarray(f) for f in frames_np]
|
||||
return DiffusionOutput(
|
||||
output=frames[0],
|
||||
custom_output={"video_frames": frames, "video_shape": out_shape},
|
||||
output={
|
||||
"payload": {"video": frames},
|
||||
"metadata": {"video": {"shape": out_shape}},
|
||||
},
|
||||
stage_durations=self.stage_durations if hasattr(self, "stage_durations") else None,
|
||||
)
|
||||
|
||||
@@ -1622,8 +1624,10 @@ class LancePipeline(BagelPipeline):
|
||||
frames_np = self._decode_video_from_latent(self.bagel, self.vae, latents[0], video_shape)
|
||||
frames = [Image.fromarray(f) for f in frames_np]
|
||||
return DiffusionOutput(
|
||||
output=frames[0],
|
||||
custom_output={"video_frames": frames, "video_shape": video_shape},
|
||||
output={
|
||||
"payload": {"video": frames},
|
||||
"metadata": {"video": {"shape": video_shape}},
|
||||
},
|
||||
stage_durations=self.stage_durations if hasattr(self, "stage_durations") else None,
|
||||
)
|
||||
|
||||
@@ -1705,8 +1709,10 @@ class LancePipeline(BagelPipeline):
|
||||
text_output = text_output.lstrip("\n")
|
||||
logger.info("Lance x2t_video: generated %d tokens", token_ids.shape[0])
|
||||
return DiffusionOutput(
|
||||
output=text_output,
|
||||
custom_output={"text_output": text_output},
|
||||
output={
|
||||
"payload": {"text": text_output},
|
||||
"metadata": {"text": {"text_output": text_output}},
|
||||
},
|
||||
stage_durations=self.stage_durations if hasattr(self, "stage_durations") else None,
|
||||
)
|
||||
|
||||
@@ -1801,8 +1807,10 @@ class LancePipeline(BagelPipeline):
|
||||
text_output = text_output.lstrip("\n")
|
||||
logger.info("Lance x2t_image: generated %d tokens", token_ids.shape[0])
|
||||
return DiffusionOutput(
|
||||
output=text_output,
|
||||
custom_output={"text_output": text_output},
|
||||
output={
|
||||
"payload": {"text": text_output},
|
||||
"metadata": {"text": {"text_output": text_output}},
|
||||
},
|
||||
stage_durations=self.stage_durations if hasattr(self, "stage_durations") else None,
|
||||
)
|
||||
|
||||
|
||||
@@ -73,8 +73,19 @@ def get_qwen_image_post_process_func(
|
||||
image_processor = VaeImageProcessor(vae_scale_factor=vae_scale_factor * 2)
|
||||
|
||||
def post_process_func(
|
||||
images: torch.Tensor,
|
||||
images: torch.Tensor | dict[str, Any],
|
||||
):
|
||||
if isinstance(images, dict) and isinstance(images.get("payload"), dict):
|
||||
payload = dict(images["payload"])
|
||||
image_payload = payload.get("image")
|
||||
if image_payload is None:
|
||||
raise ValueError("Qwen-Image postprocess expected payload['image'] in output envelope.")
|
||||
payload["image"] = image_processor.postprocess(image_payload)
|
||||
metadata = images.get("metadata") or {}
|
||||
return {
|
||||
"payload": payload,
|
||||
"metadata": metadata if isinstance(metadata, dict) else {},
|
||||
}
|
||||
return image_processor.postprocess(images)
|
||||
|
||||
return post_process_func
|
||||
|
||||
@@ -938,8 +938,10 @@ class SenseNovaU1Pipeline(nn.Module, SupportsComponentDiscovery, DiffusionPipeli
|
||||
)
|
||||
logger.info("Text generation: %d chars", len(text_output))
|
||||
return DiffusionOutput(
|
||||
output=text_output,
|
||||
custom_output={"text_output": text_output},
|
||||
output={
|
||||
"payload": {"text": text_output},
|
||||
"metadata": {"text": {"text_output": text_output}},
|
||||
},
|
||||
)
|
||||
|
||||
# -----------------------------------------------------------------------
|
||||
@@ -1457,10 +1459,15 @@ class SenseNovaU1Pipeline(nn.Module, SupportsComponentDiscovery, DiffusionPipeli
|
||||
|
||||
images = _to_pil(image_prediction)
|
||||
img = images[0] if images else None
|
||||
custom = {}
|
||||
metadata = {}
|
||||
if think_text:
|
||||
custom["think_text"] = think_text
|
||||
return DiffusionOutput(output=img, custom_output=custom)
|
||||
metadata["text"] = {"think_text": think_text}
|
||||
return DiffusionOutput(
|
||||
output={
|
||||
"payload": {"image": img},
|
||||
"metadata": metadata,
|
||||
}
|
||||
)
|
||||
|
||||
# -----------------------------------------------------------------------
|
||||
# Weight loading
|
||||
|
||||
@@ -164,11 +164,11 @@ class SoulXPreprocessPipeline(nn.Module, SupportAudioInput, SupportsComponentDis
|
||||
sample_rate=self.target_sr,
|
||||
)
|
||||
|
||||
# Non-None placeholder so DiffusionEngine forwards custom_output to stage-1
|
||||
# (output=None triggers an early return that drops handoff).
|
||||
return DiffusionOutput(
|
||||
output=torch.zeros(0),
|
||||
custom_output={SOULX_PREPROCESSED_KEY: payload},
|
||||
output={
|
||||
"payload": {},
|
||||
"metadata": {SOULX_PREPROCESSED_KEY: payload},
|
||||
},
|
||||
to_cpu=True,
|
||||
)
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ from collections.abc import Callable
|
||||
from contextlib import contextmanager
|
||||
from typing import Any, ClassVar
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from vllm.logger import init_logger
|
||||
@@ -30,6 +31,21 @@ _SOULX_PROFILER_TARGETS = [
|
||||
]
|
||||
|
||||
|
||||
def convert_soulx_audio_output_to_numpy(audio: torch.Tensor | dict[str, Any]) -> np.ndarray | dict[str, Any]:
|
||||
if isinstance(audio, dict) and isinstance(audio.get("payload"), dict):
|
||||
payload = dict(audio["payload"])
|
||||
audio_payload = payload.get("audio")
|
||||
if isinstance(audio_payload, torch.Tensor):
|
||||
payload["audio"] = audio_payload.detach().cpu().float().numpy()
|
||||
return {
|
||||
"payload": payload,
|
||||
"metadata": audio.get("metadata") or {},
|
||||
}
|
||||
if isinstance(audio, torch.Tensor):
|
||||
return audio.detach().cpu().float().numpy()
|
||||
return audio
|
||||
|
||||
|
||||
class FlowMatchingAudioPipeline(
|
||||
nn.Module,
|
||||
CFGParallelMixin,
|
||||
@@ -326,7 +342,7 @@ class FlowMatchingAudioPipeline(
|
||||
req: OmniDiffusionRequest,
|
||||
*,
|
||||
kind: str,
|
||||
custom_output_key: str,
|
||||
metadata_key: str,
|
||||
infer_batch_fn: Callable[..., tuple[torch.Tensor, int]],
|
||||
prepare_extra_args: Callable[[dict[str, Any], Any], dict[str, Any]] | None = None,
|
||||
) -> DiffusionOutput:
|
||||
@@ -353,7 +369,9 @@ class FlowMatchingAudioPipeline(
|
||||
)
|
||||
|
||||
return DiffusionOutput(
|
||||
output=audio,
|
||||
custom_output={custom_output_key: pitch_shift},
|
||||
output={
|
||||
"payload": {"audio": audio},
|
||||
"metadata": {"audio": {metadata_key: pitch_shift}},
|
||||
},
|
||||
stage_durations=self._profiler_stage_durations() or {},
|
||||
)
|
||||
@@ -19,6 +19,7 @@ from vllm_omni.diffusion.models.soulx_singer.modules import (
|
||||
)
|
||||
from vllm_omni.diffusion.models.soulx_singer.pipeline_soulx_singer_base import (
|
||||
FlowMatchingAudioPipeline,
|
||||
convert_soulx_audio_output_to_numpy,
|
||||
)
|
||||
from vllm_omni.diffusion.models.soulx_singer.preprocess.payload import (
|
||||
SOULX_PREPROCESSED_KEY,
|
||||
@@ -96,7 +97,7 @@ def get_soulxsinger_svc_pre_process_func(od_config: OmniDiffusionConfig):
|
||||
|
||||
def get_soulxsinger_post_process_func(od_config: OmniDiffusionConfig):
|
||||
def post_process_func(audio: torch.Tensor):
|
||||
return audio.detach().cpu().float().numpy()
|
||||
return convert_soulx_audio_output_to_numpy(audio)
|
||||
|
||||
return post_process_func
|
||||
|
||||
@@ -400,7 +401,7 @@ class PipelineSoulXSingerSVC(FlowMatchingAudioPipeline):
|
||||
return self._forward_batch_from_request(
|
||||
req,
|
||||
kind="svc",
|
||||
custom_output_key="pitch_shift",
|
||||
metadata_key="pitch_shift",
|
||||
infer_batch_fn=self.infer_svc_batch,
|
||||
)
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ from vllm_omni.diffusion.models.soulx_singer.modules import (
|
||||
)
|
||||
from vllm_omni.diffusion.models.soulx_singer.pipeline_soulx_singer_base import (
|
||||
FlowMatchingAudioPipeline,
|
||||
convert_soulx_audio_output_to_numpy,
|
||||
)
|
||||
from vllm_omni.diffusion.models.soulx_singer.preprocess.payload import (
|
||||
SOULX_PREPROCESSED_KEY,
|
||||
@@ -97,7 +98,7 @@ def get_soulxsinger_post_process_func(od_config: OmniDiffusionConfig):
|
||||
"""Convert pipeline audio tensor output for offline consumers."""
|
||||
|
||||
def post_process_func(audio: torch.Tensor):
|
||||
return audio.detach().cpu().float().numpy()
|
||||
return convert_soulx_audio_output_to_numpy(audio)
|
||||
|
||||
return post_process_func
|
||||
|
||||
@@ -343,7 +344,7 @@ class PipelineSoulXSingerSVS(FlowMatchingAudioPipeline):
|
||||
return self._forward_batch_from_request(
|
||||
req,
|
||||
kind="svs",
|
||||
custom_output_key="f0_shift",
|
||||
metadata_key="f0_shift",
|
||||
infer_batch_fn=self.infer_svs_batch,
|
||||
prepare_extra_args=lambda extra_args, _sampling: normalize_svs_control_extra_args(extra_args),
|
||||
)
|
||||
|
||||
@@ -13,7 +13,7 @@ SOULX_PRECOMPUTED_KEYS_BY_KIND: dict[str, tuple[str, ...]] = {
|
||||
|
||||
|
||||
# Key under which the SoulX preprocess payload is stored in
|
||||
# prompt["additional_information"] or DiffusionOutput.custom_output.
|
||||
# prompt["additional_information"] or diffusion output metadata.
|
||||
SOULX_PREPROCESSED_KEY = "soulx_preprocessed"
|
||||
|
||||
|
||||
|
||||
@@ -187,7 +187,7 @@ def get_wan22_post_process_func(
|
||||
):
|
||||
if output_type == "latent":
|
||||
return video
|
||||
custom_output = {}
|
||||
video_metadata = {}
|
||||
if sampling_params is not None and getattr(sampling_params, "enable_frame_interpolation", False):
|
||||
video, multiplier = interpolate_video_tensor(
|
||||
video,
|
||||
@@ -195,10 +195,10 @@ def get_wan22_post_process_func(
|
||||
scale=sampling_params.frame_interpolation_scale,
|
||||
model_path=sampling_params.frame_interpolation_model_path,
|
||||
)
|
||||
custom_output["video_fps_multiplier"] = multiplier
|
||||
video_metadata["video_fps_multiplier"] = multiplier
|
||||
return {
|
||||
"video": video_processor.postprocess_video(video, output_type=output_type),
|
||||
"custom_output": custom_output,
|
||||
"payload": {"video": video_processor.postprocess_video(video, output_type=output_type)},
|
||||
"metadata": {"video": video_metadata} if video_metadata else {},
|
||||
}
|
||||
|
||||
return post_process_func
|
||||
|
||||
@@ -65,7 +65,7 @@ def get_wan22_i2v_post_process_func(
|
||||
):
|
||||
if output_type == "latent":
|
||||
return video
|
||||
custom_output = {}
|
||||
video_metadata = {}
|
||||
if sampling_params is not None and getattr(sampling_params, "enable_frame_interpolation", False):
|
||||
video, multiplier = interpolate_video_tensor(
|
||||
video,
|
||||
@@ -73,10 +73,10 @@ def get_wan22_i2v_post_process_func(
|
||||
scale=sampling_params.frame_interpolation_scale,
|
||||
model_path=sampling_params.frame_interpolation_model_path,
|
||||
)
|
||||
custom_output["video_fps_multiplier"] = multiplier
|
||||
video_metadata["video_fps_multiplier"] = multiplier
|
||||
return {
|
||||
"video": video_processor.postprocess_video(video, output_type=output_type),
|
||||
"custom_output": custom_output,
|
||||
"payload": {"video": video_processor.postprocess_video(video, output_type=output_type)},
|
||||
"metadata": {"video": video_metadata} if video_metadata else {},
|
||||
}
|
||||
|
||||
return post_process_func
|
||||
|
||||
@@ -3,8 +3,9 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TypeGuard
|
||||
|
||||
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.io_support import supports_audio_output
|
||||
@@ -12,6 +13,18 @@ from vllm_omni.diffusion.registry import DiffusionModelRegistry
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.inputs.data import OmniPromptType
|
||||
from vllm_omni.outputs import OmniRequestOutput
|
||||
from vllm_omni.outputs.output_metadata import (
|
||||
DiffusionMetadata,
|
||||
DiffusionMultimodalOutput,
|
||||
DiffusionOutputEnvelope,
|
||||
DiffusionPayload,
|
||||
DiffusionPayloadValue,
|
||||
DiffusionPostprocessRawOutput,
|
||||
DiffusionTrajectoryPayload,
|
||||
strip_internal_metadata,
|
||||
validate_diffusion_metadata,
|
||||
validate_public_diffusion_metadata,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -24,53 +37,79 @@ class DiffusionStepTimings:
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DiffusionPostprocessOutput:
|
||||
outputs: Any
|
||||
custom_output: dict[str, Any]
|
||||
audio_payload: Any | None = None
|
||||
action_payload: Any | None = None
|
||||
audio_sample_rate: int | None = None
|
||||
fps: float | None = None
|
||||
has_video_payload: bool = False
|
||||
outputs: DiffusionPayload
|
||||
metadata: DiffusionMetadata = field(default_factory=dict)
|
||||
primary_key: str | None = None
|
||||
|
||||
|
||||
def _is_output_envelope(outputs: DiffusionPostprocessRawOutput) -> TypeGuard[DiffusionOutputEnvelope]:
|
||||
return isinstance(outputs, dict) and isinstance(outputs.get("payload"), dict)
|
||||
|
||||
|
||||
def normalize_diffusion_postprocess_output(
|
||||
outputs: Any,
|
||||
custom_output: dict[str, Any],
|
||||
outputs: DiffusionPostprocessRawOutput,
|
||||
) -> DiffusionPostprocessOutput:
|
||||
"""Normalize the legacy postprocess dict shape used by diffusion models.
|
||||
"""Normalize diffusion postprocess output into payload and metadata."""
|
||||
|
||||
The returned envelope owns a shallow merged copy of ``custom_output`` so
|
||||
postprocess values keep legacy override precedence without mutating the
|
||||
caller-owned dict.
|
||||
"""
|
||||
if _is_output_envelope(outputs):
|
||||
payload: DiffusionPayload = outputs.get("payload") or {}
|
||||
metadata = outputs.get("metadata") or {}
|
||||
if not isinstance(metadata, dict):
|
||||
metadata = {}
|
||||
validate_diffusion_metadata(metadata)
|
||||
|
||||
audio_payload = None
|
||||
action_payload = None
|
||||
audio_sample_rate = None
|
||||
fps = None
|
||||
has_video_payload = False
|
||||
merged_custom_output = dict(custom_output)
|
||||
public_metadata = strip_internal_metadata(metadata)
|
||||
if "text" in payload and "text" not in public_metadata:
|
||||
public_metadata = {**public_metadata, "text": {}}
|
||||
validate_public_diffusion_metadata(public_metadata)
|
||||
|
||||
return DiffusionPostprocessOutput(
|
||||
outputs=payload,
|
||||
metadata=public_metadata,
|
||||
primary_key=_infer_primary_payload_key(payload),
|
||||
)
|
||||
|
||||
if isinstance(outputs, dict):
|
||||
has_video_payload = "video" in outputs
|
||||
audio_payload = outputs.get("audio")
|
||||
action_payload = outputs.get("actions")
|
||||
merged_custom_output.update(outputs.get("custom_output") or {})
|
||||
audio_sample_rate = outputs.get("audio_sample_rate")
|
||||
fps = outputs.get("fps")
|
||||
outputs = outputs.get("video", outputs)
|
||||
payload = {key: value for key, value in outputs.items() if key not in {"audio_sample_rate", "fps"}}
|
||||
metadata = _metadata_from_legacy_payload(outputs)
|
||||
if "text" in payload and "text" not in metadata:
|
||||
metadata["text"] = {}
|
||||
if metadata:
|
||||
validate_public_diffusion_metadata(metadata)
|
||||
return DiffusionPostprocessOutput(
|
||||
outputs=payload,
|
||||
metadata=metadata,
|
||||
primary_key=_infer_primary_payload_key(payload),
|
||||
)
|
||||
|
||||
return DiffusionPostprocessOutput(
|
||||
outputs=outputs,
|
||||
custom_output=merged_custom_output,
|
||||
audio_payload=audio_payload,
|
||||
action_payload=action_payload,
|
||||
audio_sample_rate=audio_sample_rate,
|
||||
fps=fps,
|
||||
has_video_payload=has_video_payload,
|
||||
outputs={"output": outputs},
|
||||
primary_key="output",
|
||||
)
|
||||
|
||||
|
||||
def _metadata_from_legacy_payload(payload: dict[str, DiffusionPayloadValue]) -> DiffusionMetadata:
|
||||
metadata: DiffusionMetadata = {}
|
||||
audio_sample_rate = payload.get("audio_sample_rate")
|
||||
if audio_sample_rate is not None:
|
||||
metadata["audio"] = {"sample_rate": audio_sample_rate}
|
||||
fps = payload.get("fps")
|
||||
if fps is not None:
|
||||
metadata["video"] = {"fps": fps}
|
||||
return metadata
|
||||
|
||||
|
||||
def _infer_primary_payload_key(payload: DiffusionPayload) -> str | None:
|
||||
for key in ("video", "image", "text", "audio", "output"):
|
||||
if key in payload:
|
||||
return key
|
||||
if set(payload).issubset({"actions", "trajectory"}):
|
||||
return None
|
||||
if "actions" in payload:
|
||||
return None
|
||||
return next(iter(payload), None)
|
||||
|
||||
|
||||
def format_empty_diffusion_outputs(
|
||||
request: OmniDiffusionRequest,
|
||||
*,
|
||||
@@ -93,13 +132,14 @@ def format_diffusion_outputs(
|
||||
request: OmniDiffusionRequest,
|
||||
od_config: OmniDiffusionConfig,
|
||||
diffusion_output: DiffusionOutput,
|
||||
output_data: Any,
|
||||
output_data: DiffusionPostprocessRawOutput,
|
||||
postprocess_output: DiffusionPostprocessOutput,
|
||||
timings: DiffusionStepTimings,
|
||||
) -> list[OmniRequestOutput]:
|
||||
"""Convert a finished diffusion model output into API-facing outputs."""
|
||||
|
||||
outputs = _ensure_list(postprocess_output.outputs)
|
||||
primary_payload = _primary_payload(postprocess_output)
|
||||
outputs = _ensure_list(primary_payload)
|
||||
metrics = {
|
||||
"preprocess_time_ms": timings.preprocess_time_s * 1000,
|
||||
"diffusion_engine_exec_time_ms": timings.exec_time_s * 1000,
|
||||
@@ -112,10 +152,10 @@ def format_diffusion_outputs(
|
||||
# Detect text output: when the pipeline returns a string (e.g.,
|
||||
# SenseNova-U1 / BAGEL single-stage img2text / text2text), wrap it
|
||||
# as a text-type response instead of an image.
|
||||
is_text_output = isinstance(output_data, str) and postprocess_output.custom_output.get("text_output") is not None
|
||||
is_text_output = postprocess_output.primary_key == "text" or "text" in postprocess_output.metadata
|
||||
|
||||
is_audio_output = supports_audio_output(od_config.model_class_name)
|
||||
audio_sample_rate = postprocess_output.audio_sample_rate
|
||||
audio_sample_rate = _metadata_audio_sample_rate(postprocess_output.metadata)
|
||||
if is_audio_output and audio_sample_rate is None:
|
||||
model_cls = DiffusionModelRegistry._try_load_model_cls(od_config.model_class_name)
|
||||
audio_sample_rate = getattr(model_cls, "audio_sample_rate", None)
|
||||
@@ -134,14 +174,42 @@ def format_diffusion_outputs(
|
||||
)
|
||||
|
||||
|
||||
def _ensure_list(outputs: Any) -> list[Any]:
|
||||
def _ensure_list(outputs: DiffusionPayloadValue) -> list[DiffusionPayloadValue]:
|
||||
if isinstance(outputs, list):
|
||||
return outputs
|
||||
return [outputs] if outputs is not None else []
|
||||
|
||||
|
||||
def _format_audio_multimodal_output(payload: Any, audio_sample_rate: int | None) -> dict[str, Any]:
|
||||
mm_output: dict[str, Any] = {"audio": payload}
|
||||
def _primary_payload(postprocess_output: DiffusionPostprocessOutput) -> DiffusionPayloadValue | None:
|
||||
if postprocess_output.primary_key is None:
|
||||
return []
|
||||
return postprocess_output.outputs.get(postprocess_output.primary_key)
|
||||
|
||||
|
||||
def _metadata_audio_sample_rate(metadata: DiffusionMetadata) -> int | None:
|
||||
audio_metadata = metadata.get("audio")
|
||||
if not isinstance(audio_metadata, dict):
|
||||
return None
|
||||
sample_rate = audio_metadata.get("sample_rate")
|
||||
return sample_rate if isinstance(sample_rate, int) else None
|
||||
|
||||
|
||||
def _metadata_video_fps(metadata: DiffusionMetadata) -> float | None:
|
||||
video_metadata = metadata.get("video")
|
||||
if not isinstance(video_metadata, dict):
|
||||
return None
|
||||
fps = video_metadata.get("fps")
|
||||
return fps if isinstance(fps, (int, float)) and not isinstance(fps, bool) else None
|
||||
|
||||
|
||||
def _format_audio_multimodal_output(
|
||||
payload: DiffusionPayloadValue,
|
||||
audio_sample_rate: int | None,
|
||||
metadata: DiffusionMetadata | None = None,
|
||||
) -> DiffusionMultimodalOutput:
|
||||
mm_output: DiffusionMultimodalOutput = {"audio": payload}
|
||||
if metadata:
|
||||
mm_output["metadata"] = metadata
|
||||
if audio_sample_rate is not None:
|
||||
mm_output["audio_sample_rate"] = audio_sample_rate
|
||||
return mm_output
|
||||
@@ -149,25 +217,29 @@ def _format_audio_multimodal_output(payload: Any, audio_sample_rate: int | None)
|
||||
|
||||
def _has_non_audio_postprocess_payload(postprocess_output: DiffusionPostprocessOutput) -> bool:
|
||||
return (
|
||||
postprocess_output.has_video_payload
|
||||
or postprocess_output.action_payload is not None
|
||||
or postprocess_output.fps is not None
|
||||
"video" in postprocess_output.outputs
|
||||
or "image" in postprocess_output.outputs
|
||||
or "text" in postprocess_output.metadata
|
||||
or "actions" in postprocess_output.outputs
|
||||
or "trajectory" in postprocess_output.outputs
|
||||
or _metadata_video_fps(postprocess_output.metadata) is not None
|
||||
)
|
||||
|
||||
|
||||
def _build_multimodal_output(
|
||||
postprocess_output: DiffusionPostprocessOutput,
|
||||
audio_sample_rate: int | None,
|
||||
) -> dict[str, Any]:
|
||||
mm_output: dict[str, Any] = {}
|
||||
if postprocess_output.audio_payload is not None:
|
||||
mm_output["audio"] = postprocess_output.audio_payload
|
||||
) -> DiffusionMultimodalOutput:
|
||||
mm_output: DiffusionMultimodalOutput = {}
|
||||
if postprocess_output.metadata:
|
||||
mm_output["metadata"] = postprocess_output.metadata
|
||||
for key, value in postprocess_output.outputs.items():
|
||||
if key in {"audio", "actions", "trajectory"}:
|
||||
mm_output[key] = value
|
||||
if audio_sample_rate is not None:
|
||||
mm_output["audio_sample_rate"] = audio_sample_rate
|
||||
if postprocess_output.fps is not None:
|
||||
mm_output["fps"] = postprocess_output.fps
|
||||
if postprocess_output.action_payload is not None:
|
||||
mm_output["actions"] = postprocess_output.action_payload
|
||||
if (fps := _metadata_video_fps(postprocess_output.metadata)) is not None:
|
||||
mm_output["fps"] = fps
|
||||
return mm_output
|
||||
|
||||
|
||||
@@ -176,8 +248,8 @@ def _format_single_prompt_output(
|
||||
request: OmniDiffusionRequest,
|
||||
prompt: OmniPromptType,
|
||||
diffusion_output: DiffusionOutput,
|
||||
outputs: list[Any],
|
||||
metrics: dict[str, Any],
|
||||
outputs: list[DiffusionPayloadValue],
|
||||
metrics: dict[str, object],
|
||||
postprocess_output: DiffusionPostprocessOutput,
|
||||
is_text_output: bool,
|
||||
is_audio_output: bool,
|
||||
@@ -186,6 +258,13 @@ def _format_single_prompt_output(
|
||||
) -> list[OmniRequestOutput]:
|
||||
request_id = request.request_id
|
||||
mm_output = _build_multimodal_output(postprocess_output, audio_sample_rate)
|
||||
if is_text_output:
|
||||
mm_output["text"] = outputs[0] if len(outputs) == 1 else outputs
|
||||
trajectory_payload = _trajectory_payload(postprocess_output, diffusion_output)
|
||||
trajectory_latents = trajectory_payload.get("latents")
|
||||
trajectory_timesteps = trajectory_payload.get("timesteps")
|
||||
trajectory_log_probs = trajectory_payload.get("log_probs")
|
||||
trajectory_decoded = trajectory_payload.get("decoded")
|
||||
|
||||
if is_text_output:
|
||||
return [
|
||||
@@ -194,7 +273,6 @@ def _format_single_prompt_output(
|
||||
images=[],
|
||||
prompt=prompt,
|
||||
metrics=metrics,
|
||||
custom_output=postprocess_output.custom_output,
|
||||
multimodal_output=mm_output,
|
||||
final_output_type="text",
|
||||
stage_durations=diffusion_output.stage_durations,
|
||||
@@ -204,7 +282,7 @@ def _format_single_prompt_output(
|
||||
]
|
||||
|
||||
if is_audio_output and not _has_non_audio_postprocess_payload(postprocess_output):
|
||||
request_audio_payload = postprocess_output.audio_payload
|
||||
request_audio_payload = postprocess_output.outputs.get("audio")
|
||||
if request_audio_payload is None:
|
||||
request_audio_payload = outputs[0] if len(outputs) == 1 else outputs
|
||||
return [
|
||||
@@ -213,14 +291,15 @@ def _format_single_prompt_output(
|
||||
images=[],
|
||||
prompt=prompt,
|
||||
metrics=metrics,
|
||||
latents=diffusion_output.trajectory_latents,
|
||||
trajectory_latents=diffusion_output.trajectory_latents,
|
||||
trajectory_timesteps=diffusion_output.trajectory_timesteps,
|
||||
trajectory_log_probs=diffusion_output.trajectory_log_probs,
|
||||
trajectory_decoded=diffusion_output.trajectory_decoded,
|
||||
latents=trajectory_latents,
|
||||
trajectory_latents=trajectory_latents,
|
||||
trajectory_timesteps=trajectory_timesteps,
|
||||
trajectory_log_probs=trajectory_log_probs,
|
||||
trajectory_decoded=trajectory_decoded,
|
||||
multimodal_output=_format_audio_multimodal_output(
|
||||
request_audio_payload,
|
||||
audio_sample_rate,
|
||||
postprocess_output.metadata,
|
||||
),
|
||||
final_output_type="audio",
|
||||
stage_durations=diffusion_output.stage_durations,
|
||||
@@ -235,15 +314,43 @@ def _format_single_prompt_output(
|
||||
images=outputs,
|
||||
prompt=prompt,
|
||||
metrics=metrics,
|
||||
latents=diffusion_output.trajectory_latents,
|
||||
trajectory_latents=diffusion_output.trajectory_latents,
|
||||
trajectory_timesteps=diffusion_output.trajectory_timesteps,
|
||||
trajectory_log_probs=diffusion_output.trajectory_log_probs,
|
||||
trajectory_decoded=diffusion_output.trajectory_decoded,
|
||||
custom_output=postprocess_output.custom_output,
|
||||
latents=trajectory_latents,
|
||||
trajectory_latents=trajectory_latents,
|
||||
trajectory_timesteps=trajectory_timesteps,
|
||||
trajectory_log_probs=trajectory_log_probs,
|
||||
trajectory_decoded=trajectory_decoded,
|
||||
multimodal_output=mm_output,
|
||||
stage_durations=diffusion_output.stage_durations,
|
||||
peak_memory_mb=diffusion_output.peak_memory_mb,
|
||||
finished=finished,
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def _trajectory_payload(
|
||||
postprocess_output: DiffusionPostprocessOutput,
|
||||
diffusion_output: DiffusionOutput,
|
||||
) -> DiffusionTrajectoryPayload:
|
||||
trajectory: DiffusionTrajectoryPayload = {}
|
||||
payload = postprocess_output.outputs.get("trajectory")
|
||||
if isinstance(payload, Mapping):
|
||||
for source_key, target_key in (
|
||||
("latents", "latents"),
|
||||
("timesteps", "timesteps"),
|
||||
("log_probs", "log_probs"),
|
||||
("decoded", "decoded"),
|
||||
):
|
||||
value = payload.get(source_key)
|
||||
if value is not None:
|
||||
trajectory[target_key] = value
|
||||
|
||||
fallback_fields = (
|
||||
("latents", diffusion_output.trajectory_latents),
|
||||
("timesteps", diffusion_output.trajectory_timesteps),
|
||||
("log_probs", diffusion_output.trajectory_log_probs),
|
||||
("decoded", diffusion_output.trajectory_decoded),
|
||||
)
|
||||
for key, value in fallback_fields:
|
||||
if key not in trajectory and value is not None:
|
||||
trajectory[key] = value
|
||||
return trajectory
|
||||
@@ -0,0 +1,10 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Compatibility imports for diffusion output metadata.
|
||||
|
||||
The shared output payload and metadata schema lives in
|
||||
``vllm_omni.outputs.output_metadata``. Keep this module as a stable import
|
||||
path for existing diffusion callers.
|
||||
"""
|
||||
|
||||
from vllm_omni.outputs.output_metadata import * # noqa: F403
|
||||
@@ -541,13 +541,6 @@ _DIFFUSION_POST_PROCESS_FUNCS = {
|
||||
"Krea2Pipeline": "get_krea2_post_process_func",
|
||||
}
|
||||
|
||||
_DIFFUSION_ACTION_POST_PROCESS_FUNCS = {
|
||||
# arch: action_post_process_func
|
||||
# `action_post_process_func` function must be placed in {mod_folder}/{mod_relname}.py,
|
||||
# where mod_folder and mod_relname are defined and mapped using `_DIFFUSION_MODELS` via the `arch` key.
|
||||
"Cosmos3OmniDiffusersPipeline": "get_cosmos3_action_post_process_func",
|
||||
}
|
||||
|
||||
_DIFFUSION_IR_OP_PRIORITY_FUNCS = {
|
||||
# arch: ir_op_priority_func
|
||||
# `ir_op_priority_func` function must be placed in {mod_folder}/{mod_relname}.py,
|
||||
@@ -588,8 +581,8 @@ def register_diffusion_model(
|
||||
class_name: str,
|
||||
pre_process_func_name: str | None = None,
|
||||
post_process_func_name: str | None = None,
|
||||
action_post_process_func_name: str | None = None,
|
||||
ir_op_priority_func_name: str | None = None,
|
||||
action_post_process_func_name: str | None = None,
|
||||
) -> None:
|
||||
"""Register a diffusion model pipeline from an out-of-tree plugin.
|
||||
|
||||
@@ -608,13 +601,23 @@ def register_diffusion_model(
|
||||
post_process_func_name: Optional name of the post-process function
|
||||
located in *module_name*. Pass ``None`` to keep the existing
|
||||
entry when replacing a built-in model.
|
||||
action_post_process_func_name: Optional name of the action post-process
|
||||
function located in *module_name*. Pass ``None`` to keep the
|
||||
existing entry when replacing a built-in model.
|
||||
ir_op_priority_func_name: Optional name of the IR op priority merge
|
||||
function located in *module_name*. Pass ``None`` to keep the
|
||||
existing entry when replacing a built-in model.
|
||||
action_post_process_func_name: Deprecated compatibility-only keyword
|
||||
for out-of-tree plugins. Action postprocess hooks are no longer
|
||||
registered separately; move action handling into
|
||||
``post_process_func_name`` and return a payload/metadata envelope.
|
||||
"""
|
||||
if action_post_process_func_name is not None:
|
||||
logger.warning(
|
||||
"Ignoring deprecated action_post_process_func_name=%r for diffusion "
|
||||
"model %s. Move action postprocess logic into post_process_func_name "
|
||||
"and return payload/metadata output.",
|
||||
action_post_process_func_name,
|
||||
model_arch,
|
||||
)
|
||||
|
||||
# Register model class in DiffusionModelRegistry
|
||||
DiffusionModelRegistry.register_model(
|
||||
model_arch,
|
||||
@@ -631,8 +634,6 @@ def register_diffusion_model(
|
||||
_DIFFUSION_PRE_PROCESS_FUNCS[model_arch] = pre_process_func_name
|
||||
if post_process_func_name is not None:
|
||||
_DIFFUSION_POST_PROCESS_FUNCS[model_arch] = post_process_func_name
|
||||
if action_post_process_func_name is not None:
|
||||
_DIFFUSION_ACTION_POST_PROCESS_FUNCS[model_arch] = action_post_process_func_name
|
||||
if ir_op_priority_func_name is not None:
|
||||
_DIFFUSION_IR_OP_PRIORITY_FUNCS[model_arch] = ir_op_priority_func_name
|
||||
|
||||
@@ -665,13 +666,6 @@ def get_diffusion_post_process_func(od_config: OmniDiffusionConfig):
|
||||
return _load_process_func(od_config, func_name)
|
||||
|
||||
|
||||
def get_diffusion_action_post_process_func(od_config: OmniDiffusionConfig):
|
||||
if od_config.model_class_name not in _DIFFUSION_ACTION_POST_PROCESS_FUNCS:
|
||||
return None
|
||||
func_name = _DIFFUSION_ACTION_POST_PROCESS_FUNCS[od_config.model_class_name]
|
||||
return _load_process_func(od_config, func_name)
|
||||
|
||||
|
||||
def get_diffusion_ir_op_priority_func(od_config: OmniDiffusionConfig):
|
||||
if od_config.model_class_name not in _DIFFUSION_IR_OP_PRIORITY_FUNCS:
|
||||
return None
|
||||
|
||||
Reference in new issue
Block a user