[Frontend] Add midway prompt update for streaming video generation (#4652)
Signed-off-by: Huang, Zeyu <11222265+fhfuih@users.noreply.github.com>
This commit is contained in:
1 parent
1f01d05603
commit
eaf90d8eff
28 files changed
+2615
-133
No files matched your search
@@ -1274,6 +1274,9 @@ class DiffusionOutput:
|
||||
finished: bool = True
|
||||
chunk_index: int = 0
|
||||
total_chunks: int = 1
|
||||
started_event_ids: list[str] = field(default_factory=list)
|
||||
active_event_ids: list[str] = field(default_factory=list)
|
||||
completed_event_ids: list[str] = field(default_factory=list)
|
||||
|
||||
# logged duration of stages
|
||||
stage_durations: dict[str, float] = field(default_factory=dict)
|
||||
|
||||
@@ -21,7 +21,7 @@ from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.engine.stage_client import StageClientBase
|
||||
from vllm_omni.engine.stage_init_utils import StageMetadata
|
||||
from vllm_omni.errors import client_error_metadata
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams, OmniInteractionPrompt
|
||||
from vllm_omni.outputs import OmniRequestOutput
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -179,6 +179,25 @@ class InlineStageDiffusionClient(StageClientBase):
|
||||
task.cancel()
|
||||
self._engine.abort(rid)
|
||||
|
||||
async def submit_interaction_async(
|
||||
self,
|
||||
request_id: str,
|
||||
interaction: OmniInteractionPrompt,
|
||||
timeout: float | None = None,
|
||||
) -> Any:
|
||||
"""Apply a midway interaction to an active streaming request."""
|
||||
logger.debug(
|
||||
"[InlineStageDiffusionClient] stage-%s [rep-%s] interaction: %s",
|
||||
self.stage_id,
|
||||
self.replica_id,
|
||||
request_id,
|
||||
)
|
||||
return await self.collective_rpc_async(
|
||||
"submit_interaction",
|
||||
timeout=timeout,
|
||||
args=(request_id, interaction),
|
||||
)
|
||||
|
||||
async def collective_rpc_async(
|
||||
self,
|
||||
method: str,
|
||||
|
||||
@@ -29,6 +29,7 @@ from vllm_omni.diffusion.models.helios.scheduling_helios import HeliosScheduler
|
||||
from vllm_omni.diffusion.models.interface import SupportsComponentDiscovery
|
||||
from vllm_omni.diffusion.models.progress_bar import ProgressBarMixin
|
||||
from vllm_omni.diffusion.profiler.diffusion_pipeline_profiler import DiffusionPipelineProfilerMixin
|
||||
from vllm_omni.diffusion.prompt_update import PromptUpdateMixin
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.diffusion.worker.request_batch import DiffusionRequestBatch
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
@@ -155,7 +156,12 @@ def get_helios_pre_process_func(
|
||||
|
||||
|
||||
class HeliosPipeline(
|
||||
nn.Module, CFGParallelMixin, ProgressBarMixin, DiffusionPipelineProfilerMixin, SupportsComponentDiscovery
|
||||
nn.Module,
|
||||
CFGParallelMixin,
|
||||
ProgressBarMixin,
|
||||
DiffusionPipelineProfilerMixin,
|
||||
PromptUpdateMixin,
|
||||
SupportsComponentDiscovery,
|
||||
):
|
||||
"""Helios text-to-video / image-to-video / video-to-video pipeline for vllm-omni.
|
||||
|
||||
@@ -894,9 +900,12 @@ class HeliosPipeline(
|
||||
|
||||
output = current_latents if extra["output_type"] == "latent" else current_video
|
||||
completed_chunk_index = state.chunk_index
|
||||
prompt_update_metadata = state.extra.pop("prompt_update_chunk_metadata", {})
|
||||
state.chunk_index += 1
|
||||
finished = state.request_denoise_completed
|
||||
if not finished:
|
||||
# Apply queued/advancing prompt updates before preparing the next chunk.
|
||||
self._apply_prompt_update_at_chunk_boundary(state)
|
||||
self._prepare_next_chunk(state)
|
||||
else:
|
||||
self._current_timestep = None
|
||||
@@ -908,6 +917,9 @@ class HeliosPipeline(
|
||||
stage_durations=self.stage_durations if hasattr(self, "stage_durations") else {},
|
||||
chunk_index=completed_chunk_index,
|
||||
total_chunks=state.total_chunks,
|
||||
started_event_ids=prompt_update_metadata.get("started_event_ids", []),
|
||||
active_event_ids=prompt_update_metadata.get("active_event_ids", []),
|
||||
completed_event_ids=prompt_update_metadata.get("completed_event_ids", []),
|
||||
finished=finished,
|
||||
)
|
||||
|
||||
@@ -1585,12 +1597,13 @@ class HeliosPipeline(
|
||||
negative_prompt: str | list[str] | None = None,
|
||||
do_classifier_free_guidance: bool = True,
|
||||
num_videos_per_prompt: int = 1,
|
||||
max_sequence_length: int = 226,
|
||||
max_sequence_length: int | None = None,
|
||||
device: torch.device | None = None,
|
||||
dtype: torch.dtype | None = None,
|
||||
):
|
||||
device = device or self.device
|
||||
dtype = dtype or self.text_encoder.dtype
|
||||
max_sequence_length = max_sequence_length or 226
|
||||
|
||||
prompt = [prompt] if isinstance(prompt, str) else prompt
|
||||
prompt_clean = [self._prompt_clean(p) for p in prompt]
|
||||
|
||||
@@ -13,6 +13,8 @@ from typing import (
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Sequence
|
||||
|
||||
import torch
|
||||
|
||||
from vllm_omni.diffusion.data import DiffusionOutput
|
||||
@@ -58,7 +60,9 @@ class SupportsStepExecution(Protocol):
|
||||
"""Prepare request-level inputs and return initialized state."""
|
||||
...
|
||||
|
||||
def denoise_step(self, input_batch: InputBatch, **kwargs: Any) -> torch.Tensor | None:
|
||||
def denoise_step(
|
||||
self, input_batch: InputBatch, *, states: Sequence[StepRequestState] | None = None, **kwargs: Any
|
||||
) -> torch.Tensor | None:
|
||||
"""Run one denoise forward on the runner-assembled batch."""
|
||||
...
|
||||
|
||||
@@ -100,3 +104,30 @@ def supports_step_execution(pipeline: object) -> bool:
|
||||
"""Return whether `pipeline` implements :class:`SupportsStepExecution`."""
|
||||
|
||||
return isinstance(pipeline, SupportsStepExecution)
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class SupportsPromptUpdate(Protocol):
|
||||
"""Optional protocol for pipelines that support midway prompt updates.
|
||||
|
||||
Pipelines typically implement this via
|
||||
:class:`~vllm_omni.diffusion.prompt_update.PromptUpdateMixin`.
|
||||
"""
|
||||
|
||||
supports_prompt_update: ClassVar[bool] = True
|
||||
|
||||
def prepare_prompt_update(
|
||||
self,
|
||||
state: StepRequestState,
|
||||
prompt: str,
|
||||
event_id: str,
|
||||
transition_chunks: int | None = None,
|
||||
) -> None:
|
||||
"""Encode and queue a prompt update on request-local state."""
|
||||
...
|
||||
|
||||
|
||||
def supports_prompt_update(pipeline: object) -> bool:
|
||||
"""Return whether ``pipeline`` implements :class:`SupportsPromptUpdate`."""
|
||||
|
||||
return isinstance(pipeline, SupportsPromptUpdate)
|
||||
@@ -5,7 +5,7 @@ from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TypeGuard
|
||||
from typing import TypeGuard, cast
|
||||
|
||||
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.io_support import supports_audio_output
|
||||
@@ -150,6 +150,13 @@ def format_diffusion_outputs(
|
||||
model_cls = DiffusionModelRegistry._try_load_model_cls(od_config.model_class_name)
|
||||
audio_sample_rate = getattr(model_cls, "audio_sample_rate", None)
|
||||
|
||||
stream_metadata = _stream_metadata_from_diffusion_output(diffusion_output)
|
||||
if stream_metadata:
|
||||
existing_stream = postprocess_output.metadata.get("stream")
|
||||
merged_stream = dict(existing_stream) if isinstance(existing_stream, Mapping) else {}
|
||||
merged_stream.update(stream_metadata)
|
||||
postprocess_output.metadata["stream"] = merged_stream
|
||||
|
||||
return _format_single_prompt_output(
|
||||
request=request,
|
||||
prompt=request.prompt,
|
||||
@@ -164,6 +171,27 @@ def format_diffusion_outputs(
|
||||
)
|
||||
|
||||
|
||||
def _stream_metadata_from_diffusion_output(diffusion_output: DiffusionOutput) -> DiffusionMetadata | None:
|
||||
has_stream_data = (
|
||||
diffusion_output.total_chunks > 1
|
||||
or not diffusion_output.finished
|
||||
or bool(diffusion_output.started_event_ids)
|
||||
or bool(diffusion_output.active_event_ids)
|
||||
or bool(diffusion_output.completed_event_ids)
|
||||
)
|
||||
if not has_stream_data:
|
||||
return None
|
||||
return cast(
|
||||
DiffusionMetadata,
|
||||
{
|
||||
"generation_chunk_index": diffusion_output.chunk_index,
|
||||
"started_event_ids": diffusion_output.started_event_ids,
|
||||
"active_event_ids": diffusion_output.active_event_ids,
|
||||
"completed_event_ids": diffusion_output.completed_event_ids,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _ensure_list(outputs: DiffusionPayloadValue) -> list[DiffusionPayloadValue]:
|
||||
if isinstance(outputs, list):
|
||||
return outputs
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Midway prompt updates for chunked diffusion step execution.
|
||||
|
||||
``PromptUpdateMixin`` exposes
|
||||
- a pipeline interface for the external to queue a prompt update,
|
||||
- a pipeline internal method to apply prompt transitions at chunk boundaries.
|
||||
|
||||
``prompt_update_versions``: a helper for ``InputBatch`` cache invalidation.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass
|
||||
from threading import Lock
|
||||
from typing import ClassVar, TypedDict, cast
|
||||
|
||||
import torch
|
||||
|
||||
from vllm_omni.diffusion.worker.utils import StepRequestState
|
||||
|
||||
DEFAULT_TRANSITION_CHUNKS = 3
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class PromptUpdateExtra(TypedDict, total=False):
|
||||
"""A "protocol" for ``StepRequestState.extra`` keys used by the prompt-update feature."""
|
||||
|
||||
pending_prompt_update: _PendingPromptUpdate
|
||||
prompt_update_state: _PromptUpdateState
|
||||
prompt_update_chunk_metadata: _PromptUpdateChunkMetadata
|
||||
prompt_update_version: int # Bumped when prompt_embeds change; invalidates InputBatch cache.
|
||||
|
||||
# The lock for storing/updating pending prompt updates.
|
||||
# Saved in state.extra to be naturally cleaned up with the request state.
|
||||
# As PromptUpdateMixin (the pipeline) currently lacks an obvious request-finish hook
|
||||
prompt_update_lock: Lock
|
||||
|
||||
|
||||
def prompt_update_versions(states: Sequence[StepRequestState]) -> tuple[int, ...]:
|
||||
"""Return per-request prompt-update versions for batch cache comparison.
|
||||
|
||||
To be used by ``InputBatch`` or other external to determine if the cached batch is still valid.
|
||||
"""
|
||||
return tuple(int(cast(PromptUpdateExtra, state.extra).get("prompt_update_version", 0)) for state in states)
|
||||
|
||||
|
||||
class PromptUpdateMixin:
|
||||
"""Mixin for chunked streaming pipelines that support midway prompt updates.
|
||||
|
||||
Implements the behavior expected by :class:`~vllm_omni.diffusion.models.interface.SupportsPromptUpdate`.
|
||||
All per-request transition state lives on ``StepRequestState.extra``; this mixin itself is stateless.
|
||||
"""
|
||||
|
||||
supports_prompt_update: ClassVar[bool] = True
|
||||
|
||||
@staticmethod
|
||||
def _prompt_update_lock(extra: PromptUpdateExtra) -> Lock:
|
||||
return extra.setdefault("prompt_update_lock", Lock())
|
||||
|
||||
def prepare_prompt_update(
|
||||
self,
|
||||
state: StepRequestState,
|
||||
prompt: str,
|
||||
event_id: str,
|
||||
transition_chunks: int | None = None,
|
||||
) -> None:
|
||||
"""Encode and queue a prompt update to apply at the next chunk boundary.
|
||||
It does not actually apply the prompt transition.
|
||||
|
||||
This is an extended interface for the pipeline, to be called by the runner.
|
||||
"""
|
||||
if not prompt:
|
||||
raise ValueError("prompt must be non-empty")
|
||||
if not event_id:
|
||||
raise ValueError("event_id must be non-empty")
|
||||
if state.prompt_embeds is None:
|
||||
raise ValueError(
|
||||
f"prompt_update is not allowed before initial generation has started (request_id={state.request_id!r})"
|
||||
)
|
||||
duration = DEFAULT_TRANSITION_CHUNKS if transition_chunks is None else transition_chunks
|
||||
if duration < 0:
|
||||
raise ValueError("transition_chunks must be >= 0")
|
||||
|
||||
target_prompt_embeds, _ = self.encode_prompt(
|
||||
prompt=prompt,
|
||||
negative_prompt=None,
|
||||
do_classifier_free_guidance=False,
|
||||
num_videos_per_prompt=state.sampling.num_outputs_per_prompt,
|
||||
max_sequence_length=state.sampling.max_sequence_length,
|
||||
device=self.device,
|
||||
dtype=self.transformer.dtype,
|
||||
)
|
||||
extra = cast(PromptUpdateExtra, state.extra)
|
||||
with self._prompt_update_lock(extra):
|
||||
extra["pending_prompt_update"] = {
|
||||
"event_id": event_id,
|
||||
"prompt": prompt,
|
||||
"target_prompt_embeds": target_prompt_embeds,
|
||||
"transition_chunks": duration,
|
||||
}
|
||||
|
||||
def _apply_prompt_update_at_chunk_boundary(self, state: StepRequestState) -> None:
|
||||
"""Advance or start prompt interpolation before the next chunk."""
|
||||
extra = cast(PromptUpdateExtra, state.extra)
|
||||
update_state: _PromptUpdateState | None = extra.get("prompt_update_state")
|
||||
with self._prompt_update_lock(extra):
|
||||
pending = extra.pop("pending_prompt_update", None)
|
||||
embeds_changed = False
|
||||
next_chunk_index = state.chunk_index
|
||||
started_event_ids: list[str] = []
|
||||
active_event_ids: list[str] = []
|
||||
completed_event_ids: list[str] = []
|
||||
|
||||
# If current transition is not complete, advance it.
|
||||
# After completion, leave prompt_update_state in place (so a later pending
|
||||
# update can abort/overwrite), but do not keep bumping the version.
|
||||
if update_state is not None:
|
||||
in_transition = (
|
||||
update_state.transition_chunks > 0
|
||||
and update_state.elapsed_transition_chunks < update_state.transition_chunks
|
||||
)
|
||||
if in_transition:
|
||||
update_state.advance_transition()
|
||||
state.prompt_embeds = update_state.blended_prompt_embeds()
|
||||
embeds_changed = True
|
||||
active_event_ids.append(update_state.event_id)
|
||||
if update_state.elapsed_transition_chunks >= update_state.transition_chunks:
|
||||
state.prompt_embeds = update_state.target_prompt_embeds
|
||||
update_state.source_prompt_embeds = update_state.target_prompt_embeds
|
||||
completed_event_ids.append(update_state.event_id)
|
||||
if update_state.target_prompt is not None:
|
||||
logger.debug(
|
||||
"prompt_update transition complete request_id=%s next_chunk_index=%d prompt=%.20s...",
|
||||
state.request_id,
|
||||
next_chunk_index,
|
||||
update_state.target_prompt,
|
||||
)
|
||||
|
||||
# If a new prompt update is pending, start a new transition.
|
||||
if pending is not None:
|
||||
if state.prompt_embeds is None:
|
||||
raise RuntimeError(
|
||||
"internal error: trying to apply a pending prompt update but "
|
||||
f"current prompt_embeds is None (request_id={state.request_id!r})"
|
||||
)
|
||||
source = state.prompt_embeds.detach().clone()
|
||||
target = pending["target_prompt_embeds"]
|
||||
duration = int(pending["transition_chunks"])
|
||||
prompt = str(pending.get("prompt", ""))
|
||||
event_id = pending.get("event_id")
|
||||
update_state = _PromptUpdateState(
|
||||
source_prompt_embeds=source,
|
||||
target_prompt_embeds=target,
|
||||
transition_chunks=duration,
|
||||
event_id=event_id,
|
||||
target_prompt=prompt,
|
||||
)
|
||||
extra["prompt_update_state"] = update_state
|
||||
started_event_ids.append(event_id)
|
||||
active_event_ids.append(event_id)
|
||||
if duration <= 0:
|
||||
# A hard/immediate transition
|
||||
state.prompt_embeds = target
|
||||
completed_event_ids.append(event_id)
|
||||
logger.debug(
|
||||
"prompt_update sharp transition request_id=%s next_chunk_index=%d prompt=%.20s...",
|
||||
state.request_id,
|
||||
next_chunk_index,
|
||||
prompt,
|
||||
)
|
||||
else:
|
||||
# A transition that really takes some time
|
||||
update_state.advance_transition()
|
||||
state.prompt_embeds = update_state.blended_prompt_embeds()
|
||||
if update_state.elapsed_transition_chunks >= update_state.transition_chunks:
|
||||
state.prompt_embeds = update_state.target_prompt_embeds
|
||||
update_state.source_prompt_embeds = update_state.target_prompt_embeds
|
||||
completed_event_ids.append(event_id)
|
||||
logger.debug(
|
||||
"prompt_update transition start request_id=%s next_chunk_index=%d prompt=%.20s...",
|
||||
state.request_id,
|
||||
next_chunk_index,
|
||||
prompt,
|
||||
)
|
||||
embeds_changed = True
|
||||
|
||||
# Indicate that prompt embeddings have changed---clear input batch cache.
|
||||
if embeds_changed:
|
||||
new_version = int(extra.get("prompt_update_version", 0)) + 1
|
||||
extra["prompt_update_version"] = new_version
|
||||
|
||||
extra["prompt_update_chunk_metadata"] = {
|
||||
"started_event_ids": started_event_ids,
|
||||
"active_event_ids": active_event_ids,
|
||||
"completed_event_ids": completed_event_ids,
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class _PromptUpdateState:
|
||||
"""Per-request prompt interpolation stored in ``state.extra["prompt_update_state"]``."""
|
||||
|
||||
source_prompt_embeds: torch.Tensor
|
||||
target_prompt_embeds: torch.Tensor
|
||||
transition_chunks: int
|
||||
event_id: str
|
||||
elapsed_transition_chunks: int = 0
|
||||
target_prompt: str | None = None
|
||||
|
||||
def blended_prompt_embeds(self) -> torch.Tensor:
|
||||
alpha = self._current_alpha()
|
||||
if alpha >= 1.0:
|
||||
return self.target_prompt_embeds
|
||||
return (1.0 - alpha) * self.source_prompt_embeds + alpha * self.target_prompt_embeds
|
||||
|
||||
def advance_transition(self) -> None:
|
||||
if self.transition_chunks <= 0:
|
||||
self.source_prompt_embeds = self.target_prompt_embeds
|
||||
return
|
||||
self.elapsed_transition_chunks += 1
|
||||
if self.elapsed_transition_chunks >= self.transition_chunks:
|
||||
self.source_prompt_embeds = self.target_prompt_embeds
|
||||
self.elapsed_transition_chunks = self.transition_chunks
|
||||
|
||||
def _current_alpha(self) -> float:
|
||||
if self.transition_chunks <= 0:
|
||||
return 1.0
|
||||
return min(1.0, self.elapsed_transition_chunks / self.transition_chunks)
|
||||
|
||||
|
||||
class _PendingPromptUpdate(TypedDict):
|
||||
event_id: str
|
||||
prompt: str
|
||||
target_prompt_embeds: torch.Tensor
|
||||
transition_chunks: int
|
||||
|
||||
|
||||
class _PromptUpdateChunkMetadata(TypedDict):
|
||||
started_event_ids: list[str]
|
||||
active_event_ids: list[str]
|
||||
completed_event_ids: list[str]
|
||||
@@ -34,7 +34,7 @@ from vllm_omni.outputs import OmniRequestOutput
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams, OmniPromptType
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams, OmniInteractionPrompt, OmniPromptType
|
||||
|
||||
logger = init_logger(__name__)
|
||||
_MISSING_RPC_RESULT = object()
|
||||
@@ -395,6 +395,19 @@ class StageDiffusionClient(StageClientBase):
|
||||
)
|
||||
)
|
||||
|
||||
async def submit_interaction_async(
|
||||
self,
|
||||
request_id: str,
|
||||
interaction: OmniInteractionPrompt,
|
||||
timeout: float | None = None,
|
||||
) -> Any:
|
||||
"""Apply a midway interaction to an active streaming request."""
|
||||
return await self.collective_rpc_async(
|
||||
"submit_interaction",
|
||||
timeout=timeout,
|
||||
args=(request_id, interaction),
|
||||
)
|
||||
|
||||
async def collective_rpc_async(
|
||||
self,
|
||||
method: str,
|
||||
|
||||
@@ -14,7 +14,7 @@ import copy
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from contextlib import AbstractContextManager, nullcontext
|
||||
from typing import Any
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
|
||||
import torch
|
||||
from torch.profiler import record_function
|
||||
@@ -32,7 +32,7 @@ from vllm_omni.diffusion.compile import regionally_compile
|
||||
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.forward_context import set_forward_context
|
||||
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
|
||||
from vllm_omni.diffusion.models.interface import supports_step_execution
|
||||
from vllm_omni.diffusion.models.interface import SupportsPromptUpdate, supports_prompt_update, supports_step_execution
|
||||
from vllm_omni.diffusion.offloader import get_offload_backend
|
||||
from vllm_omni.diffusion.registry import _NO_CACHE_ACCELERATION
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
@@ -53,6 +53,9 @@ from vllm_omni.inputs.data import OmniDiffusionSamplingParams
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
from vllm_omni.worker.omni_connector_model_runner_mixin import OmniConnectorModelRunnerMixin
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm_omni.inputs.data import OmniInteractionPrompt
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
@@ -803,3 +806,48 @@ class DiffusionModelRunner(OmniConnectorModelRunnerMixin):
|
||||
self._update_states_after(states, input_batch, pipeline_interrupted)
|
||||
|
||||
return BatchRunnerOutput.from_list(runner_output_list)
|
||||
|
||||
def submit_interaction(
|
||||
self,
|
||||
request_id: str,
|
||||
interaction: OmniInteractionPrompt,
|
||||
) -> None:
|
||||
"""Route a midway interaction to the matching active stepwise request feature."""
|
||||
assert self.pipeline is not None, "Model not loaded. Call load_model() first."
|
||||
if not self.od_config.streaming_output:
|
||||
raise ValueError("submit_interaction requires streaming_output=True")
|
||||
if not self._supports_step_mode():
|
||||
raise ValueError("submit_interaction requires step execution support")
|
||||
|
||||
event = interaction.get("event")
|
||||
if isinstance(event, dict) and "prompt" in event and "multi_modal_data" not in event:
|
||||
# Is a prompt update interaction.
|
||||
self._submit_prompt_update_interaction(request_id, interaction)
|
||||
return
|
||||
|
||||
raise NotImplementedError(
|
||||
"Only text-only prompt update interactions with 'event.prompt' and optional "
|
||||
"'transition_chunks' are supported in this release"
|
||||
)
|
||||
|
||||
def _submit_prompt_update_interaction(
|
||||
self,
|
||||
request_id: str,
|
||||
interaction: OmniInteractionPrompt,
|
||||
) -> None:
|
||||
"""Queue a prompt-update interaction for an active stepwise request."""
|
||||
if not supports_prompt_update(self.pipeline):
|
||||
raise ValueError(f"prompt_update is not supported by pipeline {self.od_config.model_class_name!r}")
|
||||
|
||||
state = self.state_cache.get(request_id)
|
||||
if state is None:
|
||||
raise ValueError(f"No active request state for prompt_update: {request_id!r}")
|
||||
|
||||
event = cast(dict[str, Any], interaction.get("event"))
|
||||
prompt = event["prompt"]
|
||||
transition_chunks = interaction.get("transition_chunks")
|
||||
event_id = interaction.get("event_id")
|
||||
if not isinstance(event_id, str) or not event_id:
|
||||
raise ValueError("event_id must be non-empty")
|
||||
pipeline = cast(SupportsPromptUpdate, self.pipeline)
|
||||
pipeline.prepare_prompt_update(state, prompt, event_id, transition_chunks)
|
||||
@@ -50,6 +50,7 @@ from vllm_omni.diffusion.sched.interface import DiffusionSchedulerOutput, KVPref
|
||||
from vllm_omni.diffusion.worker.diffusion_model_runner import DiffusionModelRunner
|
||||
from vllm_omni.diffusion.worker.utils import BaseRunnerOutput, BatchRunnerOutput
|
||||
from vllm_omni.engine.stage_init_utils import set_death_signal
|
||||
from vllm_omni.inputs.data import OmniInteractionPrompt
|
||||
from vllm_omni.lora.request import LoRARequest
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
from vllm_omni.profiler import OmniTorchProfilerWrapper, create_omni_profiler
|
||||
@@ -511,6 +512,15 @@ class DiffusionWorker:
|
||||
# for the frontend server yet.
|
||||
return self.lora_manager.add_adapter(lora_request)
|
||||
|
||||
def submit_interaction(
|
||||
self,
|
||||
request_id: str,
|
||||
interaction: OmniInteractionPrompt,
|
||||
) -> None:
|
||||
"""Apply a midway interaction to an active stepwise request."""
|
||||
assert self.model_runner is not None, "Model runner not initialized"
|
||||
self.model_runner.submit_interaction(request_id, interaction)
|
||||
|
||||
def list_loras(self) -> list[int]:
|
||||
return self.lora_manager.list_adapters()
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ from dataclasses import dataclass, field
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from vllm_omni.diffusion.prompt_update import prompt_update_versions
|
||||
from vllm_omni.diffusion.worker.utils import StepRequestState
|
||||
|
||||
|
||||
@@ -535,12 +536,17 @@ def _same_composition(
|
||||
cached_batch: InputBatch | None,
|
||||
request_ids: list[str],
|
||||
idx_mapping_np: np.ndarray,
|
||||
states: Sequence[StepRequestState],
|
||||
) -> bool:
|
||||
if cached_batch is None:
|
||||
return False
|
||||
if cached_batch.request_ids != request_ids:
|
||||
return False
|
||||
return np.array_equal(cached_batch.idx_mapping_np, idx_mapping_np)
|
||||
if not np.array_equal(cached_batch.idx_mapping_np, idx_mapping_np):
|
||||
return False
|
||||
# Midway prompt updates (typically for video generation) can change prompt_embeds without changing ids/mapping.
|
||||
# In this case, each request state manages the embedding's "version". Use it to determine if cache is still valid.
|
||||
return cached_batch._prompt_update_versions == prompt_update_versions(states)
|
||||
|
||||
|
||||
def _scatter_batch_tensor_by_mapping(
|
||||
@@ -615,6 +621,10 @@ class InputBatch:
|
||||
negative_txt_seq_lens: list[int] | None = None
|
||||
states: Sequence[StepRequestState] = field(default_factory=tuple)
|
||||
|
||||
# For midway prompt updates (typically for video generation) that changes embeddings without changing ids,
|
||||
# Keep a snapshot of the current per-request versions of prompt embeddings for later runtime comparison
|
||||
_prompt_update_versions: tuple[int, ...] = ()
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if len(self.request_ids) != int(self.idx_mapping.numel()):
|
||||
raise ValueError("`request_ids` and `idx_mapping` must have the same length.")
|
||||
@@ -653,6 +663,7 @@ class InputBatch:
|
||||
self.img_shapes = _prepare_img_shapes(states)
|
||||
self.txt_seq_lens = _prepare_seq_lens(states, "txt_seq_lens")
|
||||
self.negative_txt_seq_lens = _prepare_seq_lens(states, "negative_txt_seq_lens")
|
||||
self._prompt_update_versions = prompt_update_versions(states)
|
||||
|
||||
def _repack_dynamic_fields(
|
||||
self,
|
||||
@@ -693,7 +704,7 @@ class InputBatch:
|
||||
selected_states, idx_mapping, idx_mapping_np = _select_states(states, idx_mapping)
|
||||
request_ids = _prepare_request_ids(selected_states)
|
||||
|
||||
if _same_composition(cached_batch, request_ids, idx_mapping_np):
|
||||
if _same_composition(cached_batch, request_ids, idx_mapping_np, selected_states):
|
||||
assert cached_batch is not None
|
||||
cached_batch._repack_dynamic_fields(selected_states)
|
||||
return cached_batch
|
||||
@@ -733,6 +744,7 @@ class InputBatch:
|
||||
"negative_txt_seq_lens",
|
||||
),
|
||||
states=tuple(selected_states),
|
||||
_prompt_update_versions=prompt_update_versions(selected_states),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -48,6 +48,9 @@ def split_diffusion_output_by_request(
|
||||
peak_memory_mb=result.peak_memory_mb,
|
||||
chunk_index=result.chunk_index,
|
||||
total_chunks=result.total_chunks,
|
||||
started_event_ids=result.started_event_ids,
|
||||
active_event_ids=result.active_event_ids,
|
||||
completed_event_ids=result.completed_event_ids,
|
||||
)
|
||||
for idx in range(req.num_reqs)
|
||||
]
|
||||
|
||||
@@ -55,6 +55,7 @@ from vllm_omni.engine.messages import (
|
||||
CollectiveRPCResultMessage,
|
||||
EngineQueueMessage,
|
||||
ErrorMessage,
|
||||
InteractionMessage,
|
||||
StageSubmissionMessage,
|
||||
)
|
||||
from vllm_omni.engine.orchestrator import Orchestrator
|
||||
@@ -71,7 +72,7 @@ from vllm_omni.entrypoints.utils import (
|
||||
load_and_resolve_stage_configs,
|
||||
parse_stage_overrides,
|
||||
)
|
||||
from vllm_omni.inputs.data import OmniSamplingParams
|
||||
from vllm_omni.inputs.data import OmniInteractionPrompt, OmniSamplingParams
|
||||
from vllm_omni.metrics.prometheus import OmniRequestCounter
|
||||
|
||||
logger = init_logger(__name__)
|
||||
@@ -1703,6 +1704,30 @@ class AsyncOmniEngine:
|
||||
"""Async abort API."""
|
||||
self.abort(request_ids)
|
||||
|
||||
def submit_interaction(
|
||||
self,
|
||||
request_id: str,
|
||||
interaction: OmniInteractionPrompt,
|
||||
) -> None:
|
||||
"""Send an interaction control message to the Orchestrator."""
|
||||
if self.request_queue is None:
|
||||
raise RuntimeError("request_queue is not initialized")
|
||||
|
||||
self.request_queue.sync_q.put_nowait(
|
||||
InteractionMessage(
|
||||
request_id=request_id,
|
||||
interaction=interaction,
|
||||
)
|
||||
)
|
||||
|
||||
async def submit_interaction_async(
|
||||
self,
|
||||
request_id: str,
|
||||
interaction: OmniInteractionPrompt,
|
||||
) -> None:
|
||||
"""Async interaction API."""
|
||||
self.submit_interaction(request_id, interaction)
|
||||
|
||||
def collective_rpc(
|
||||
self,
|
||||
method: str,
|
||||
|
||||
@@ -6,7 +6,7 @@ import msgspec
|
||||
from vllm.inputs import PromptType
|
||||
from vllm.v1.engine import EngineCoreRequest
|
||||
|
||||
from vllm_omni.inputs.data import OmniSamplingParams
|
||||
from vllm_omni.inputs.data import OmniInteractionPrompt, OmniSamplingParams
|
||||
from vllm_omni.metrics.stats import StageRequestStats as StageRequestMetrics
|
||||
from vllm_omni.outputs import OmniRequestOutput
|
||||
|
||||
@@ -44,6 +44,12 @@ class AbortRequestMessage(EngineQueueMessage, kw_only=True):
|
||||
request_ids: list[str]
|
||||
|
||||
|
||||
class InteractionMessage(EngineQueueMessage, kw_only=True):
|
||||
type: Literal["interaction"] = "interaction"
|
||||
request_id: str
|
||||
interaction: OmniInteractionPrompt
|
||||
|
||||
|
||||
class CollectiveRPCRequestMessage(EngineQueueMessage, kw_only=True):
|
||||
type: Literal["collective_rpc"] = "collective_rpc"
|
||||
rpc_id: str
|
||||
@@ -78,6 +84,7 @@ class ErrorMessage(EngineQueueMessage, kw_only=True):
|
||||
fatal: bool = False
|
||||
request_id: str | None = None
|
||||
stage_id: int | None = None
|
||||
event_id: str | None = None # for interactions on diffusion generation requests
|
||||
|
||||
|
||||
class OutputMessage(EngineQueueMessage, kw_only=True):
|
||||
|
||||
@@ -40,6 +40,7 @@ from vllm_omni.engine.messages import (
|
||||
CollectiveRPCResultMessage,
|
||||
EngineQueueMessage,
|
||||
ErrorMessage,
|
||||
InteractionMessage,
|
||||
OutputMessage,
|
||||
RegisterRemoteReplicaMessage,
|
||||
ShutdownRequestMessage,
|
||||
@@ -577,6 +578,8 @@ class Orchestrator:
|
||||
self.duplex_control_plane.dispatch(msg)
|
||||
elif msg_type == "abort":
|
||||
await self._handle_abort(msg)
|
||||
elif msg_type == "interaction":
|
||||
await self._handle_interaction(msg)
|
||||
elif msg_type == "collective_rpc":
|
||||
await self._handle_collective_rpc(msg)
|
||||
elif isinstance(msg, RegisterRemoteReplicaMessage):
|
||||
@@ -768,6 +771,44 @@ class Orchestrator:
|
||||
)
|
||||
logger.info("[Orchestrator] Aborted request(s) %s", request_ids)
|
||||
|
||||
async def _handle_interaction(self, msg: InteractionMessage) -> None:
|
||||
"""Handle a midway interaction for an active streaming diffusion request."""
|
||||
stage_id = 0
|
||||
request_id = msg.request_id
|
||||
event_id = msg.interaction.get("event_id")
|
||||
req_state = self.request_states.get(request_id)
|
||||
if req_state is None:
|
||||
logger.info("[Orchestrator] Dropping interaction for inactive req %s", request_id)
|
||||
await self.output_async_queue.put(
|
||||
ErrorMessage(
|
||||
error=f"No active request for interaction: {request_id}",
|
||||
fatal=False,
|
||||
request_id=request_id,
|
||||
event_id=event_id,
|
||||
stage_id=stage_id,
|
||||
)
|
||||
)
|
||||
return
|
||||
|
||||
try:
|
||||
await self.stage_pools[stage_id].submit_interaction(request_id, msg.interaction)
|
||||
except Exception as exc:
|
||||
logger.info(
|
||||
"[Orchestrator] Failed interaction for req %s: %s",
|
||||
request_id,
|
||||
exc,
|
||||
exc_info=True,
|
||||
)
|
||||
await self.output_async_queue.put(
|
||||
ErrorMessage(
|
||||
error=f"Failed interaction for request {request_id}: {exc}",
|
||||
fatal=False,
|
||||
request_id=request_id,
|
||||
event_id=event_id,
|
||||
stage_id=stage_id,
|
||||
)
|
||||
)
|
||||
|
||||
async def _abort_request_ids(self, request_ids: list[str]) -> None:
|
||||
"""Forward abort requests to all stage pools."""
|
||||
if not request_ids:
|
||||
|
||||
@@ -8,7 +8,12 @@ from typing import TYPE_CHECKING, Any, Protocol
|
||||
if TYPE_CHECKING:
|
||||
from vllm.v1.engine import EngineCoreOutput, EngineCoreOutputs, EngineCoreRequest
|
||||
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams, OmniPromptType, OmniTokensPrompt
|
||||
from vllm_omni.inputs.data import (
|
||||
OmniDiffusionSamplingParams,
|
||||
OmniInteractionPrompt,
|
||||
OmniPromptType,
|
||||
OmniTokensPrompt,
|
||||
)
|
||||
from vllm_omni.outputs import OmniRequestOutput
|
||||
|
||||
from vllm_omni.inputs.data import OmniSamplingParams
|
||||
@@ -101,3 +106,10 @@ class StagePoolDiffusionClient(StagePoolClient, Protocol):
|
||||
) -> None: ...
|
||||
|
||||
def get_diffusion_output_nowait(self) -> OmniRequestOutput | None: ...
|
||||
|
||||
async def submit_interaction_async(
|
||||
self,
|
||||
request_id: str,
|
||||
interaction: OmniInteractionPrompt,
|
||||
timeout: float | None = None,
|
||||
) -> Any: ...
|
||||
@@ -24,7 +24,7 @@ from vllm_omni.engine.stage_client import (
|
||||
StagePoolDiffusionClient,
|
||||
StagePoolLLMClient,
|
||||
)
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams, OmniInteractionPrompt
|
||||
from vllm_omni.metrics import (
|
||||
count_audio_frames,
|
||||
count_image_pixels,
|
||||
@@ -1048,6 +1048,24 @@ class StagePool:
|
||||
raise
|
||||
return replica_id
|
||||
|
||||
async def submit_interaction(
|
||||
self,
|
||||
request_id: str,
|
||||
interaction: OmniInteractionPrompt,
|
||||
) -> int:
|
||||
"""Submit a midway interaction to an active diffusion (typically video generation) request."""
|
||||
replica_id = self.get_bound_replica_id(request_id)
|
||||
if replica_id is None or self.clients[replica_id] is None:
|
||||
replica_id = await self._pick_or_select(request_id)
|
||||
|
||||
client = self._diffusion_client(replica_id)
|
||||
result = await client.submit_interaction_async(request_id, interaction)
|
||||
# Interaction may raise error if underlying check against ODConfig fails.
|
||||
if isinstance(result, dict) and result.get("error"):
|
||||
reason = result.get("reason") or "Unknown interaction RPC error"
|
||||
raise ValueError(str(reason))
|
||||
return replica_id
|
||||
|
||||
async def _pick_or_select(
|
||||
self,
|
||||
request_id: str,
|
||||
|
||||
@@ -50,7 +50,7 @@ if TYPE_CHECKING:
|
||||
DuplexSessionLifecycleMessage,
|
||||
)
|
||||
from vllm_omni.experimental.fullduplex.request_client import DuplexRequestClient
|
||||
from vllm_omni.inputs.data import OmniPromptType
|
||||
from vllm_omni.inputs.data import OmniInteractionPrompt, OmniPromptType
|
||||
|
||||
logger = init_logger(__name__)
|
||||
_FINAL_OUTPUT_IDLE_SLEEP_S = 0.001
|
||||
@@ -1006,6 +1006,46 @@ class AsyncOmni(EngineClient, OmniBase):
|
||||
internal_ids = [s.request_id for s in self.request_states.values() if s.external_request_id in request_ids]
|
||||
await self._abort(internal_ids)
|
||||
|
||||
async def submit_interaction_async(
|
||||
self,
|
||||
request_id: str,
|
||||
*,
|
||||
interaction: OmniInteractionPrompt,
|
||||
) -> None:
|
||||
"""Apply a midway interaction to an active streaming diffusion request.
|
||||
|
||||
``request_id`` is the external id created by the server-side session,
|
||||
matching the value passed to :meth:`generate`.
|
||||
"""
|
||||
event = interaction.get("event")
|
||||
prompt = event.get("prompt") if isinstance(event, dict) else None
|
||||
if isinstance(event, dict) and "prompt" in event and (not isinstance(prompt, str) or not prompt):
|
||||
raise ValueError("prompt must be non-empty")
|
||||
transition_chunks = interaction.get("transition_chunks")
|
||||
if transition_chunks is not None and transition_chunks < 0:
|
||||
raise ValueError("transition_chunks must be >= 0")
|
||||
|
||||
if self.num_stages != 1:
|
||||
raise ValueError("interaction requires single-stage diffusion")
|
||||
stage_meta = self.engine.get_stage_metadata(0)
|
||||
if stage_meta.stage_type != "diffusion":
|
||||
raise ValueError("interaction requires a diffusion stage")
|
||||
|
||||
internal_ids = [s.request_id for s in self.request_states.values() if s.external_request_id == request_id]
|
||||
if not internal_ids:
|
||||
raise ValueError(f"No active request for interaction: {request_id!r}")
|
||||
if len(internal_ids) > 1:
|
||||
raise ValueError(
|
||||
f"interaction requires exactly one active request for {request_id!r}, found {len(internal_ids)}"
|
||||
)
|
||||
|
||||
await self.engine.submit_interaction_async(
|
||||
internal_ids[0],
|
||||
interaction=interaction,
|
||||
)
|
||||
if self.log_stats:
|
||||
logger.info("[AsyncOmni] Queued interaction for request %s", request_id)
|
||||
|
||||
async def _abort_internal_requests(self, request_id: str | Iterable[str]):
|
||||
"""Abort request(s) via the Orchestrator given internal request IDs,
|
||||
which take the format <external_request_id>-<UUID>.
|
||||
|
||||
@@ -5,13 +5,22 @@
|
||||
Protocol:
|
||||
Client -> Server:
|
||||
{"type": "session.start", "model": "...", "prompt": "...", "format": "m4s", ...}
|
||||
{"type": "session.prompt_update", "prompt": "..."} # currently unsupported
|
||||
{
|
||||
"type": "session.interaction",
|
||||
"interaction": {
|
||||
"event_id": "...",
|
||||
"event": {"prompt": "..."},
|
||||
"transition_chunks": (optional, integer),
|
||||
},
|
||||
}
|
||||
{"type": "session.stop"}
|
||||
{"type": "session.ping"} # optional; refreshes stall clock
|
||||
|
||||
Server -> Client:
|
||||
{"type": "video.start", "request_id": "...", "config": {...}, "format": "m4s"}
|
||||
{"type": "video.chunk_metadata", ...}
|
||||
<binary frame: fragmented MP4 bytes>
|
||||
{"type": "session.interaction.queued", "request_id": "...", "event_id": "..."}
|
||||
{"type": "session.done", ...}
|
||||
{"type": "session.pong"} # reply to session.ping
|
||||
{"type": "error", "message": "..."}
|
||||
@@ -21,7 +30,6 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import copy
|
||||
import inspect
|
||||
import json
|
||||
import time
|
||||
import uuid
|
||||
@@ -29,19 +37,34 @@ from collections.abc import AsyncGenerator
|
||||
from http import HTTPStatus
|
||||
from typing import Any, cast
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from fastapi import HTTPException, WebSocket, WebSocketDisconnect
|
||||
from PIL import Image
|
||||
from pydantic import ValidationError
|
||||
from vllm.engine.protocol import EngineClient
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.entrypoints.async_omni import AsyncOmni
|
||||
from vllm_omni.entrypoints.openai.errors import InvalidInputReferenceError
|
||||
from vllm_omni.entrypoints.openai.protocol.videos import VideoGenerationRequest, VideoParams
|
||||
from vllm_omni.entrypoints.openai.stage_params import (
|
||||
build_stage_sampling_params_list,
|
||||
get_default_sampling_params_list,
|
||||
)
|
||||
from vllm_omni.entrypoints.openai.utils import get_stage_type, parse_lora_request
|
||||
from vllm_omni.entrypoints.openai.video_api_utils import StreamingVideoFormat, create_streaming_video_encoder
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams, OmniTextPrompt
|
||||
from vllm_omni.entrypoints.openai.video_api_utils import (
|
||||
StreamingVideoFormat,
|
||||
create_streaming_video_encoder,
|
||||
decode_input_reference,
|
||||
)
|
||||
from vllm_omni.inputs.data import (
|
||||
OmniDiffusionSamplingParams,
|
||||
OmniInteractionEvent,
|
||||
OmniInteractionPrompt,
|
||||
OmniTextPrompt,
|
||||
)
|
||||
from vllm_omni.outputs import OmniRequestOutput
|
||||
from vllm_omni.outputs.output_metadata import DiffusionPayloadValue
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
@@ -70,7 +93,7 @@ class OmniStreamingVideoOutputHandler:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
engine_client: EngineClient,
|
||||
engine_client: AsyncOmni,
|
||||
model_name: str | None = None,
|
||||
stage_configs: list[Any] | None = None,
|
||||
stall_timeout: float = _DEFAULT_STALL_TIMEOUT,
|
||||
@@ -91,6 +114,7 @@ class OmniStreamingVideoOutputHandler:
|
||||
control_task: asyncio.Task[None] | None = None
|
||||
stopped = False
|
||||
chunks_sent = 0
|
||||
interaction_payloads_by_id: dict[str, OmniInteractionPrompt] = {}
|
||||
|
||||
try:
|
||||
start = await self._receive_start(websocket)
|
||||
@@ -112,13 +136,22 @@ class OmniStreamingVideoOutputHandler:
|
||||
progress.touch()
|
||||
|
||||
control_task = asyncio.create_task(
|
||||
self._control_loop(websocket, request_id, stop_event, send_lock, progress)
|
||||
self._control_loop(
|
||||
websocket,
|
||||
request_id,
|
||||
stop_event,
|
||||
send_lock,
|
||||
progress,
|
||||
interaction_payloads_by_id,
|
||||
)
|
||||
)
|
||||
async for chunk in self._stream_video_bytes(request, request_id, output_format, progress):
|
||||
async for chunk, metadata in self._stream_video_bytes(request, request_id, output_format, progress):
|
||||
if stop_event.is_set():
|
||||
stopped = True
|
||||
break
|
||||
async with send_lock:
|
||||
metadata["transport_chunk_index"] = chunks_sent
|
||||
await websocket.send_json(metadata)
|
||||
await websocket.send_bytes(chunk)
|
||||
chunks_sent += 1
|
||||
progress.touch()
|
||||
@@ -234,6 +267,7 @@ class OmniStreamingVideoOutputHandler:
|
||||
stop_event: asyncio.Event,
|
||||
send_lock: asyncio.Lock,
|
||||
progress: _SessionProgress,
|
||||
interaction_payloads_by_id: dict[str, OmniInteractionPrompt],
|
||||
) -> None:
|
||||
while not stop_event.is_set():
|
||||
if progress.stalled_for(self._stall_timeout):
|
||||
@@ -282,34 +316,151 @@ class OmniStreamingVideoOutputHandler:
|
||||
except Exception:
|
||||
pass
|
||||
continue
|
||||
if msg_type == "session.prompt_update":
|
||||
await self._send_error(
|
||||
if msg_type == "session.interaction":
|
||||
await self._handle_interaction(
|
||||
websocket,
|
||||
"session.prompt_update is not supported by this backend yet",
|
||||
msg,
|
||||
request_id=request_id,
|
||||
send_lock=send_lock,
|
||||
interaction_payloads_by_id=interaction_payloads_by_id,
|
||||
)
|
||||
continue
|
||||
await self._send_error(websocket, f"Unknown message type: {msg_type}", send_lock=send_lock)
|
||||
|
||||
async def _abort_request(self, request_id: str) -> None:
|
||||
try:
|
||||
abort = getattr(self._engine_client, "abort", None)
|
||||
if callable(abort):
|
||||
result = abort(request_id)
|
||||
if inspect.isawaitable(result):
|
||||
await result
|
||||
await self._engine_client.abort(request_id)
|
||||
except Exception:
|
||||
logger.debug("Failed to abort streaming video request %s", request_id, exc_info=True)
|
||||
|
||||
async def _handle_interaction(
|
||||
self,
|
||||
websocket: WebSocket,
|
||||
msg: dict[str, Any],
|
||||
*,
|
||||
request_id: str,
|
||||
send_lock: asyncio.Lock,
|
||||
interaction_payloads_by_id: dict[str, OmniInteractionPrompt],
|
||||
) -> None:
|
||||
interaction = msg.get("interaction")
|
||||
if not isinstance(interaction, dict):
|
||||
await self._send_error(websocket, "session.interaction requires an interaction object", send_lock=send_lock)
|
||||
return
|
||||
|
||||
event_id = interaction.get("event_id")
|
||||
if event_id is None:
|
||||
event_id = uuid.uuid4().hex
|
||||
elif not isinstance(event_id, str) or not event_id:
|
||||
await self._send_error(
|
||||
websocket,
|
||||
"session.interaction event_id must be a non-empty string",
|
||||
send_lock=send_lock,
|
||||
)
|
||||
return
|
||||
|
||||
event = interaction.get("event")
|
||||
if not isinstance(event, dict):
|
||||
await self._send_error(websocket, "session.interaction requires event object", send_lock=send_lock)
|
||||
return
|
||||
|
||||
prompt = event.get("prompt")
|
||||
if not isinstance(prompt, str) or not prompt.strip():
|
||||
await self._send_error(
|
||||
websocket,
|
||||
"session.interaction requires a non-empty event.prompt",
|
||||
send_lock=send_lock,
|
||||
)
|
||||
return
|
||||
|
||||
if "negative_prompt" in event and event["negative_prompt"] is not None:
|
||||
await self._send_error(
|
||||
websocket,
|
||||
"session.interaction negative_prompt is not supported in this release",
|
||||
send_lock=send_lock,
|
||||
)
|
||||
return
|
||||
|
||||
normalized: OmniInteractionPrompt = {
|
||||
"event_id": event_id,
|
||||
"event": cast(OmniInteractionEvent, event),
|
||||
}
|
||||
transition_chunks = interaction.get("transition_chunks")
|
||||
if transition_chunks is not None:
|
||||
try:
|
||||
if (
|
||||
isinstance(transition_chunks, bool)
|
||||
or not isinstance(transition_chunks, (int, float))
|
||||
or (isinstance(transition_chunks, float) and not transition_chunks.is_integer())
|
||||
):
|
||||
raise ValueError
|
||||
normalized["transition_chunks"] = int(transition_chunks)
|
||||
except (TypeError, ValueError):
|
||||
await self._send_error(
|
||||
websocket,
|
||||
"session.interaction transition_chunks must be an integer",
|
||||
send_lock=send_lock,
|
||||
)
|
||||
return
|
||||
if normalized["transition_chunks"] < 0:
|
||||
await self._send_error(
|
||||
websocket,
|
||||
"session.interaction transition_chunks must be >= 0",
|
||||
send_lock=send_lock,
|
||||
)
|
||||
return
|
||||
|
||||
if event_id in interaction_payloads_by_id:
|
||||
await self._send_error(
|
||||
websocket,
|
||||
"event_id_conflict",
|
||||
code="event_id_conflict",
|
||||
request_id=request_id,
|
||||
event_id=event_id,
|
||||
send_lock=send_lock,
|
||||
)
|
||||
return
|
||||
|
||||
interaction_payloads_by_id[event_id] = normalized
|
||||
|
||||
try:
|
||||
await self._engine_client.submit_interaction_async(
|
||||
request_id,
|
||||
interaction=normalized,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Failed to apply interaction for request %s", request_id, exc_info=True)
|
||||
interaction_payloads_by_id.pop(event_id, None)
|
||||
await self._send_error(
|
||||
websocket,
|
||||
"Failed to apply interaction",
|
||||
code="interaction_failed",
|
||||
request_id=request_id,
|
||||
event_id=event_id,
|
||||
send_lock=send_lock,
|
||||
)
|
||||
return
|
||||
|
||||
try:
|
||||
async with send_lock:
|
||||
await websocket.send_json(
|
||||
{
|
||||
"type": "session.interaction.queued",
|
||||
"request_id": request_id,
|
||||
"event_id": event_id,
|
||||
}
|
||||
)
|
||||
except Exception:
|
||||
logger.debug("Failed to send interaction acknowledgement for %s", request_id, exc_info=True)
|
||||
|
||||
async def _stream_video_bytes(
|
||||
self,
|
||||
request: VideoGenerationRequest,
|
||||
request_id: str,
|
||||
output_format: StreamingVideoFormat,
|
||||
progress: _SessionProgress,
|
||||
) -> AsyncGenerator[bytes, None]:
|
||||
) -> AsyncGenerator[tuple[bytes, dict[str, Any]], None]:
|
||||
"""Yield encoded video bytes from diffusion streaming outputs."""
|
||||
prompt, gen_params, vp = self._build_prompt_and_sampling_params(request)
|
||||
prompt, gen_params, vp = await self._build_prompt_and_sampling_params(request)
|
||||
video_codec_options = {"preset": "ultrafast", "threads": "0", "tune": "zerolatency"}
|
||||
if isinstance(request.extra_params, dict) and "video_codec_options" in request.extra_params:
|
||||
video_codec_options = request.extra_params["video_codec_options"]
|
||||
@@ -323,23 +474,41 @@ class OmniStreamingVideoOutputHandler:
|
||||
completed = False
|
||||
try:
|
||||
async for result in self._iter_generation_outputs(prompt, gen_params, request_id, progress):
|
||||
if error := getattr(result, "error", None):
|
||||
raise RuntimeError(str(error))
|
||||
if result.error:
|
||||
raise RuntimeError(str(result.error))
|
||||
videos = self._extract_video_outputs(result)
|
||||
for video in videos:
|
||||
chunk = encoder.encode(video)
|
||||
if chunk:
|
||||
yield chunk
|
||||
yield (
|
||||
chunk,
|
||||
self._build_chunk_metadata(
|
||||
request_id=request_id,
|
||||
kind="media",
|
||||
byte_length=len(chunk),
|
||||
num_frames=self._num_video_frames(video),
|
||||
stream_metadata=self._extract_stream_metadata(result),
|
||||
),
|
||||
)
|
||||
|
||||
completed = True
|
||||
final_chunk = encoder.close()
|
||||
if final_chunk:
|
||||
yield final_chunk
|
||||
yield (
|
||||
final_chunk,
|
||||
self._build_chunk_metadata(
|
||||
request_id=request_id,
|
||||
kind="trailer",
|
||||
byte_length=len(final_chunk),
|
||||
num_frames=0,
|
||||
stream_metadata={},
|
||||
),
|
||||
)
|
||||
finally:
|
||||
if not completed:
|
||||
encoder.close()
|
||||
|
||||
def _build_prompt_and_sampling_params(
|
||||
async def _build_prompt_and_sampling_params(
|
||||
self,
|
||||
request: VideoGenerationRequest,
|
||||
) -> tuple[OmniTextPrompt, OmniDiffusionSamplingParams, VideoParams]:
|
||||
@@ -350,6 +519,10 @@ class OmniStreamingVideoOutputHandler:
|
||||
|
||||
gen_params = self._resolve_default_sampling_params()
|
||||
vp = request.resolve_video_params()
|
||||
input_image = await self._decode_image_reference(request)
|
||||
if input_image is not None:
|
||||
prompt["multi_modal_data"] = {"image": input_image}
|
||||
|
||||
if vp.width is not None and vp.height is not None:
|
||||
gen_params.width = vp.width
|
||||
gen_params.height = vp.height
|
||||
@@ -386,12 +559,28 @@ class OmniStreamingVideoOutputHandler:
|
||||
self._apply_lora(request.lora, gen_params)
|
||||
return prompt, gen_params, vp
|
||||
|
||||
@staticmethod
|
||||
async def _decode_image_reference(request: VideoGenerationRequest) -> Image.Image | None:
|
||||
try:
|
||||
media_data = await decode_input_reference(
|
||||
request.image_reference,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
except InvalidInputReferenceError as exc:
|
||||
raise HTTPException(HTTPStatus.BAD_REQUEST.value, detail=str(exc)) from exc
|
||||
if media_data is not None and not isinstance(media_data, Image.Image):
|
||||
raise HTTPException(
|
||||
HTTPStatus.BAD_REQUEST.value,
|
||||
detail="image_reference must resolve to an image.",
|
||||
)
|
||||
return media_data
|
||||
|
||||
def _resolve_default_sampling_params(self) -> OmniDiffusionSamplingParams:
|
||||
default_sampling_params_list = getattr(self._engine_client, "default_sampling_params_list", None)
|
||||
if default_sampling_params_list:
|
||||
for params in default_sampling_params_list:
|
||||
if isinstance(params, OmniDiffusionSamplingParams):
|
||||
return copy.deepcopy(params)
|
||||
default_sampling_params_list = self._engine_client.default_sampling_params_list
|
||||
for params in default_sampling_params_list:
|
||||
if isinstance(params, OmniDiffusionSamplingParams):
|
||||
return copy.deepcopy(params)
|
||||
return OmniDiffusionSamplingParams()
|
||||
|
||||
@staticmethod
|
||||
@@ -417,8 +606,8 @@ class OmniStreamingVideoOutputHandler:
|
||||
gen_params: OmniDiffusionSamplingParams,
|
||||
request_id: str,
|
||||
progress: _SessionProgress,
|
||||
) -> AsyncGenerator[Any, None]:
|
||||
stage_configs = self._stage_configs or getattr(self._engine_client, "stage_configs", None)
|
||||
) -> AsyncGenerator[OmniRequestOutput, None]:
|
||||
stage_configs = self._stage_configs or self._engine_client.stage_configs
|
||||
if not stage_configs:
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.SERVICE_UNAVAILABLE.value,
|
||||
@@ -433,15 +622,14 @@ class OmniStreamingVideoOutputHandler:
|
||||
detail=f"Video generation only supports diffusion stages, found '{stage_type}' stage.",
|
||||
)
|
||||
|
||||
engine_client = cast(Any, self._engine_client)
|
||||
sampling_params_list = build_stage_sampling_params_list(
|
||||
list(stage_configs),
|
||||
get_default_sampling_params_list(engine_client),
|
||||
get_default_sampling_params_list(self._engine_client),
|
||||
diffusion_params=gen_params,
|
||||
replace_diffusion_params=True,
|
||||
)
|
||||
|
||||
async for output in engine_client.generate(
|
||||
async for output in self._engine_client.generate(
|
||||
prompt=prompt,
|
||||
request_id=request_id,
|
||||
sampling_params_list=sampling_params_list,
|
||||
@@ -450,44 +638,49 @@ class OmniStreamingVideoOutputHandler:
|
||||
yield output
|
||||
|
||||
@staticmethod
|
||||
def _normalize_video_outputs(videos: Any) -> list[Any]:
|
||||
def _normalize_video_outputs(videos: DiffusionPayloadValue | None) -> list[DiffusionPayloadValue]:
|
||||
if videos is None:
|
||||
return []
|
||||
if hasattr(videos, "ndim") and videos.ndim == 5:
|
||||
if isinstance(videos, (torch.Tensor, np.ndarray)) and videos.ndim == 5:
|
||||
return [videos[i] for i in range(videos.shape[0])]
|
||||
if isinstance(videos, list):
|
||||
if not videos:
|
||||
return []
|
||||
first = videos[0]
|
||||
if hasattr(first, "ndim") and first.ndim == 5:
|
||||
flattened: list[Any] = []
|
||||
if isinstance(first, (torch.Tensor, np.ndarray)) and first.ndim == 5:
|
||||
flattened: list[DiffusionPayloadValue] = []
|
||||
for item in videos:
|
||||
if hasattr(item, "ndim") and item.ndim == 5:
|
||||
if isinstance(item, (torch.Tensor, np.ndarray)) and item.ndim == 5:
|
||||
flattened.extend([item[i] for i in range(item.shape[0])])
|
||||
else:
|
||||
flattened.append(item)
|
||||
return flattened
|
||||
if isinstance(first, list):
|
||||
return videos
|
||||
if hasattr(first, "ndim") and first.ndim == 3:
|
||||
if isinstance(first, (torch.Tensor, np.ndarray)) and first.ndim == 3:
|
||||
return [videos]
|
||||
if isinstance(first, Image.Image):
|
||||
return [videos]
|
||||
return videos
|
||||
return [videos]
|
||||
|
||||
def _extract_video_outputs(self, result: Any) -> list[Any]:
|
||||
videos = None
|
||||
if hasattr(result, "images") and result.images:
|
||||
videos = result.images
|
||||
elif hasattr(result, "request_output"):
|
||||
def _extract_video_outputs(self, result: OmniRequestOutput) -> list[DiffusionPayloadValue]:
|
||||
videos: DiffusionPayloadValue | None = None
|
||||
if result.images:
|
||||
# Video frames may be list[list[Image.Image]] despite images: list[Image.Image].
|
||||
videos = result.images # type: ignore[assignment]
|
||||
elif result.request_output is not None:
|
||||
request_output = result.request_output
|
||||
if isinstance(request_output, dict) and request_output.get("images"):
|
||||
videos = request_output["images"]
|
||||
elif not isinstance(request_output, dict):
|
||||
if hasattr(request_output, "images") and request_output.images:
|
||||
videos = request_output.images
|
||||
elif hasattr(request_output, "multimodal_output") and request_output.multimodal_output:
|
||||
videos = request_output.multimodal_output.get("video")
|
||||
if videos is None and hasattr(result, "multimodal_output") and result.multimodal_output:
|
||||
elif isinstance(request_output, OmniRequestOutput):
|
||||
if request_output.images:
|
||||
# Same nested-frames mismatch as result.images above.
|
||||
videos = request_output.images # type: ignore[assignment]
|
||||
else:
|
||||
request_multimodal_output = request_output.multimodal_output
|
||||
videos = request_multimodal_output.get("video")
|
||||
if videos is None:
|
||||
videos = result.multimodal_output.get("video")
|
||||
|
||||
normalized = self._normalize_video_outputs(videos)
|
||||
@@ -498,18 +691,64 @@ class OmniStreamingVideoOutputHandler:
|
||||
)
|
||||
return normalized
|
||||
|
||||
@staticmethod
|
||||
def _extract_stream_metadata(result: OmniRequestOutput) -> dict[str, Any]:
|
||||
multimodal_output = result.multimodal_output
|
||||
if not isinstance(multimodal_output, dict):
|
||||
return {}
|
||||
metadata = multimodal_output.get("metadata")
|
||||
if not isinstance(metadata, dict):
|
||||
return {}
|
||||
stream = metadata.get("stream")
|
||||
return dict(stream) if isinstance(stream, dict) else {}
|
||||
|
||||
@staticmethod
|
||||
def _num_video_frames(video: DiffusionPayloadValue) -> int:
|
||||
if isinstance(video, (torch.Tensor, np.ndarray)) and len(video.shape) > 0:
|
||||
return int(video.shape[0])
|
||||
if isinstance(video, list):
|
||||
return len(video)
|
||||
return 0
|
||||
|
||||
@staticmethod
|
||||
def _build_chunk_metadata(
|
||||
*,
|
||||
request_id: str,
|
||||
kind: str,
|
||||
byte_length: int,
|
||||
num_frames: int,
|
||||
stream_metadata: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
return {
|
||||
"type": "video.chunk_metadata",
|
||||
"request_id": request_id,
|
||||
"kind": kind,
|
||||
"num_frames": num_frames,
|
||||
"byte_length": byte_length,
|
||||
"generation_chunk_index": (stream_metadata.get("generation_chunk_index") if kind == "media" else None),
|
||||
"started_event_ids": stream_metadata.get("started_event_ids", []),
|
||||
"active_event_ids": stream_metadata.get("active_event_ids", []),
|
||||
"completed_event_ids": stream_metadata.get("completed_event_ids", []),
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
async def _send_error(
|
||||
websocket: WebSocket,
|
||||
message: str,
|
||||
code: int | None = None,
|
||||
code: int | str | None = None,
|
||||
*,
|
||||
request_id: str | None = None,
|
||||
event_id: str | None = None,
|
||||
send_lock: asyncio.Lock | None = None,
|
||||
) -> None:
|
||||
try:
|
||||
payload: dict[str, Any] = {"type": "error", "message": message}
|
||||
if code is not None:
|
||||
payload["code"] = code
|
||||
if request_id is not None:
|
||||
payload["request_id"] = request_id
|
||||
if event_id is not None:
|
||||
payload["event_id"] = event_id
|
||||
if send_lock is None:
|
||||
await websocket.send_json(payload)
|
||||
else:
|
||||
|
||||
@@ -43,6 +43,20 @@ class OmniTextPrompt(TextPrompt):
|
||||
model_intermediate_buffer: NotRequired[dict[str, Any]]
|
||||
|
||||
|
||||
class OmniInteractionEvent(OmniTextPrompt, total=False):
|
||||
"""Prompt-event payload for mid-stream interactions."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class OmniInteractionPrompt(TypedDict, total=False):
|
||||
"""Mid-stream interaction payload."""
|
||||
|
||||
event_id: NotRequired[str]
|
||||
event: NotRequired[OmniInteractionEvent]
|
||||
transition_chunks: NotRequired[int]
|
||||
|
||||
|
||||
class OmniTokensPrompt(TokensPrompt):
|
||||
"""Tokens prompt with optional embeddings and stage payloads.
|
||||
|
||||
|
||||
Reference in new issue
Block a user