[Refactor/Bugfix] Use Delta Messages for Streaming (#2911)

Signed-off-by: Alex Brooks <albrooks@redhat.com>
Signed-off-by: Sy03 <1370724210@qq.com>
Signed-off-by: Yueqian Lin <linyueqian@outlook.com>
Signed-off-by: Yueqian Lin <70319226+linyueqian@users.noreply.github.com>
Co-authored-by: Sy03 <1370724210@qq.com>
Co-authored-by: Yueqian Lin <linyueqian@outlook.com>
Co-authored-by: Yueqian Lin <70319226+linyueqian@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-04-26 15:11:53 +12:00
1 parent 6e35bfbbae
commit e03ab82dd2
27 files changed
+623 -177

No files matched your search

+12 -5
View File
@@ -31,6 +31,7 @@ from vllm_omni.entrypoints.omni_base import (
OmniBase,
OmniEngineDeadError,
)
from vllm_omni.inputs.data import OmniSamplingParams
from vllm_omni.metrics.stats import OrchestratorAggregator as OrchestratorMetrics
from vllm_omni.outputs import OmniRequestOutput
from vllm_omni.platforms import current_omni_platform
@@ -40,7 +41,7 @@ if TYPE_CHECKING:
from vllm.tokenizers import TokenizerLike
from vllm.v1.engine import PauseMode
from vllm_omni.inputs.data import OmniPromptType, OmniSamplingParams
from vllm_omni.inputs.data import OmniPromptType
logger = init_logger(__name__)
_FINAL_OUTPUT_IDLE_SLEEP_S = 0.001
@@ -278,7 +279,13 @@ class AsyncOmni(EngineClient, OmniBase):
and not isinstance(sampling_params_list, (str, bytes))
):
sampling_params_list = self._maybe_expand_sampling_params(list(sampling_params_list))
sampling_params_list = self.resolve_sampling_params_list(sampling_params_list)
# Set the output kind to delta output if sampling params were omitted,
# since AsyncOmni is typically used for streaming.
sampling_params_list = self.resolve_sampling_params_list(
sampling_params_list,
allow_delta_coercion=True,
)
# Track per-request metrics
wall_start_ts = time.time()
@@ -366,15 +373,15 @@ class AsyncOmni(EngineClient, OmniBase):
# only check thinker's sampling params now
stage0_params = sampling_params_list[0]
self._validate_streaming_input_sampling_params(stage0_params)
req_state = self.request_states[request_id]
has_submitted_first_chunk = False
# NOTE: InputProcessor in vLLM should generally do this too, but for
# now we do it defensively. TODO (Alex) ensure clones/copying are optimized
if not stage0_params.skip_clone:
stage0_params = stage0_params.clone()
stage0_params.skip_clone = True
has_submitted_first_chunk = False
async def handle_inputs() -> None:
nonlocal has_submitted_first_chunk
cancelled = False
+6 -1
View File
@@ -16,7 +16,7 @@ from vllm.v1.engine.exceptions import EngineDeadError, EngineGenerateError
from vllm_omni.engine.async_omni_engine import AsyncOmniEngine
from vllm_omni.entrypoints.client_request_state import ClientRequestState
from vllm_omni.entrypoints.pd_utils import PDDisaggregationMixin
from vllm_omni.entrypoints.utils import get_final_stage_id_for_e2e
from vllm_omni.entrypoints.utils import coerce_param_message_types, get_final_stage_id_for_e2e
from vllm_omni.metrics.stats import OrchestratorAggregator as OrchestratorMetrics
from vllm_omni.model_executor.model_loader.weight_utils import download_weights_from_hf_specific
from vllm_omni.outputs import OmniRequestOutput
@@ -232,9 +232,14 @@ class OmniBase(PDDisaggregationMixin):
def resolve_sampling_params_list(
self,
sampling_params_list: Sequence[Any] | Any | None,
allow_delta_coercion: bool = False,
) -> Sequence[Any]:
if sampling_params_list is None:
normalized = self.default_sampling_params_list
# Set the output kind to delta since no params were specified
if allow_delta_coercion:
normalized = coerce_param_message_types(list(normalized), is_streaming=True)
elif isinstance(sampling_params_list, Sequence) and not isinstance(sampling_params_list, (str, bytes)):
normalized = sampling_params_list
elif self.num_stages == 1:
@@ -4,6 +4,7 @@ import asyncio
import base64
import json
from collections.abc import AsyncGenerator
from typing import cast
from uuid import uuid4
import numpy as np
@@ -12,6 +13,9 @@ from vllm.entrypoints.openai.realtime.connection import RealtimeConnection as Vl
from vllm.entrypoints.openai.realtime.protocol import TranscriptionDelta, TranscriptionDone
from vllm.logger import init_logger
from vllm_omni.entrypoints.async_omni import AsyncOmni
from vllm_omni.entrypoints.utils import coerce_param_message_types
logger = init_logger(__name__)
@@ -24,8 +28,7 @@ class RealtimeConnection(VllmRealtimeConnection):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Last audio buffer seen for this realtime generation (cumulative or concatenation
# of increments); used to turn server cumulative PCM into true deltas.
self.engine = cast(AsyncOmni, self.serving.engine_client)
self._realtime_audio_ref: np.ndarray | None = None
async def start_generation(self):
@@ -115,41 +118,48 @@ class RealtimeConnection(VllmRealtimeConnection):
sent_audio = False
audio_done_sent = False
full_text = ""
sent_text_len = 0
prompt_token_ids_len = 0
completion_tokens_len = 0
self._realtime_audio_ref = None
# Coerce cumulative outputs to delta outputs; this ensures
# we don't emit redundant MM data & drain after emitting.
sampling_params_list = list(self.engine.default_sampling_params_list)
sampling_params_list = coerce_param_message_types(
sampling_params_list,
is_streaming=True,
)
try:
result_gen = self.serving.engine_client.generate(
result_gen = self.engine.generate(
prompt=streaming_input_gen,
request_id=request_id,
sampling_params_list=sampling_params_list,
)
async for output in result_gen:
# Handle delta texts; this is very similar to the client from vLLM
if output.outputs and len(output.outputs) > 0:
output0 = output.outputs[0]
token_ids = list(output0.token_ids)
if token_ids:
input_stream.put_nowait(token_ids)
# token_ids are cumulative per request
completion_tokens_len = len(token_ids)
first_output = output.outputs[0]
new_token_ids = list(first_output.token_ids)
new_tokens_len = len(new_token_ids)
if not prompt_token_ids_len and output.prompt_token_ids:
prompt_token_ids_len = len(output.prompt_token_ids)
cumulative_text = output0.text or ""
if cumulative_text:
if len(cumulative_text) >= sent_text_len:
delta_text = cumulative_text[sent_text_len:]
else:
delta_text = cumulative_text
sent_text_len = len(cumulative_text)
full_text = cumulative_text
else:
delta_text = ""
if new_tokens_len:
input_stream.put_nowait(new_token_ids)
delta_text = first_output.text or ""
full_text += delta_text
# append output to input if there was any delta text
if delta_text:
await self.send(TranscriptionDelta(delta=delta_text))
completion_tokens_len += new_tokens_len
# Handle audio chunking; this is Omni specific
audio_chunks, sample_rate = self._extract_audio_chunks(output)
for chunk in audio_chunks:
+7 -6
View File
@@ -16,6 +16,7 @@ from pydantic import TypeAdapter
from vllm_omni.entrypoints.async_omni import AsyncOmni
from vllm_omni.entrypoints.openai.protocol.chat_completion import OmniChatCompletionResponse
from vllm_omni.entrypoints.utils import coerce_param_message_types
from vllm_omni.inputs.data import OmniDiffusionSamplingParams, OmniTextPrompt
try:
@@ -391,6 +392,11 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
# Use standard OpenAI API parameters for comprehension stage
sampling_params_list = self._build_sampling_params_list_from_request(request)
# If this is a streaming (output) request, coerce cumulative outputs
# to delta to ensure emitted outputs are correctly drained. Otherwise
# convert cumulative to Final Only to ensure the output is correct.
sampling_params_list = coerce_param_message_types(sampling_params_list, request.stream)
# Apply user-specified overrides to diffusion stage(s) for image generation
for idx, sp in enumerate(sampling_params_list):
if hasattr(sp, "height") and _image_gen_height is not None:
@@ -1007,12 +1013,7 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
cur_channel = harmony_parser.current_channel
cur_recipient = harmony_parser.current_recipient
else:
# output.text is cumulative, extract only the delta portion
previous_text = previous_texts[i] if previous_texts else ""
if output.text is not None:
delta_text = output.text[len(previous_text) :]
else:
delta_text = ""
delta_text = output.text or ""
if not delta_text and not output.token_ids and not previous_num_tokens[i]:
# Chunked prefill case, don't return empty chunks
@@ -40,6 +40,7 @@ from vllm_omni.entrypoints.openai.protocol.audio import (
SpeechBatchItem,
SpeechBatchItemResult,
)
from vllm_omni.entrypoints.utils import coerce_param_message_types
from vllm_omni.model_executor.models.fish_speech.prompt_utils import (
build_fish_text_only_prompt_ids,
estimate_fish_voice_clone_prompt_len_from_normalized,
@@ -1628,6 +1629,13 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
if self.engine_client.errored:
raise self.engine_client.dead_error
# If this is a streaming request, we need to coerce
# cumulative outputs to delta outputs; this ensures
# we don't emit redundant MM data & drain after emitting.
# list() makes a copy to avoid mutating the params.
sampling_params_list = list(self.engine_client.default_sampling_params_list)
sampling_params_list = coerce_param_message_types(sampling_params_list, request.stream)
if self._is_fish_speech:
validation_error = self._validate_fish_tts_request(request)
if validation_error:
@@ -1743,8 +1751,6 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
model_type,
)
sampling_params_list = self.engine_client.default_sampling_params_list
# CosyVoice3: set dynamic min/max tokens based on text length.
# The official model requires min_token_text_ratio to prevent early
# EOS and max_token_text_ratio to cap generation length.
+39
View File
@@ -8,12 +8,14 @@ from typing import Any, get_args, get_origin
import yaml
from vllm.logger import init_logger
from vllm.sampling_params import RequestOutputKind, SamplingParams
from vllm.transformers_utils.config import get_config, get_hf_file_to_dict
from vllm.transformers_utils.repo_utils import file_or_path_exists
from vllm_omni.config.stage_config import StageConfigFactory
from vllm_omni.config.yaml_util import create_config, load_yaml_config, merge_configs
from vllm_omni.entrypoints.stage_utils import _to_dict
from vllm_omni.inputs.data import OmniSamplingParams
from vllm_omni.platforms import current_omni_platform
# Get the project root directory (2 levels up from this file)
@@ -850,3 +852,40 @@ def detect_pid_host() -> bool:
return True
return has_pid_host()
### Helpers for handling delta messages
def coerce_param_message_types(params: list[OmniSamplingParams], is_streaming: bool):
"""Iterate over the sampling params and convert to the message types
to DELTA messages, if streaming is enabled, or FINAL_ONLY if
it's disabled, while respecting `.skip_clone` on the params.
This is needed to avoid emitting redundant multimodal data.
"""
# Coerce vLLM's default output kinds as needed to handle streaming
# (i.e., DELTA output kind). Note that this is only applied to non
# Diffusion sampling params.
#
# NOTE: Hidden states will still be passed between stages.
for idx, sp in enumerate(params):
# For OmniDiffusionParams don't set output kind
if isinstance(sp, SamplingParams):
params[idx] = maybe_coerce_to_message_type(sp, is_streaming)
return params
def maybe_coerce_to_message_type(params: SamplingParams, is_streaming: bool):
"""If this is a CUMULATIVE message, coerce it to DELTA if streaming, otherwise FINAL_ONLY."""
target_type = RequestOutputKind.DELTA if is_streaming else RequestOutputKind.FINAL_ONLY
if params.output_kind == target_type:
return params
elif is_streaming and params.output_kind == RequestOutputKind.FINAL_ONLY:
logger.warning("Request appears to be streaming, but got request type final only!")
elif not is_streaming and params.output_kind == RequestOutputKind.DELTA:
logger.warning("Request appears to not be streaming, but got request type delta!")
if not params.skip_clone:
params = params.clone()
params.skip_clone = True
params.output_kind = target_type
return params