Merge main into dev/vllm-align for vLLM 0.31 release
Signed-off-by: tzhouam <tzhouam@connect.ust.hk>
This commit is contained in:
commit
008fa25263
252 files changed
+27589
-1237
No files matched your search
@@ -130,6 +130,7 @@ class AsyncOmni(AsyncOmniBase, EngineClient):
|
||||
reasoning_ended: bool | None = None,
|
||||
reasoning_parser_kwargs: dict[str, Any] | None = None,
|
||||
arrival_time: float | None = None,
|
||||
submitted: asyncio.Future[None] | None = None,
|
||||
) -> AsyncGenerator[OmniRequestOutput, None]:
|
||||
"""Generate outputs for the given prompt(s) asynchronously.
|
||||
|
||||
@@ -300,6 +301,9 @@ class AsyncOmni(AsyncOmniBase, EngineClient):
|
||||
if admitting:
|
||||
await self._release_generate_admission()
|
||||
admitting = False
|
||||
# Callers wait on this before abort so Stage0 observes the sender cache.
|
||||
if submitted is not None and not submitted.done():
|
||||
submitted.set_result(None)
|
||||
# Refresh gauges on arrival.
|
||||
self._publish_request_gauges(len(self.request_states))
|
||||
|
||||
|
||||
@@ -560,6 +560,15 @@ class OmniServeCommand(CLISubcommand):
|
||||
"custom_pipeline, dummy, or diffusers for the HF diffusers adapter."
|
||||
),
|
||||
)
|
||||
omni_config_group.add_argument(
|
||||
"--hsdp-weight-load-strategy",
|
||||
choices=["full", "pre_sharded"],
|
||||
default=None,
|
||||
help=(
|
||||
"HSDP checkpoint loading strategy: 'full' loads then shards; "
|
||||
"'pre_sharded' shards meta parameters first and reads rank-local HF safetensors slices."
|
||||
),
|
||||
)
|
||||
omni_config_group.add_argument(
|
||||
"--lora-path",
|
||||
type=str,
|
||||
|
||||
@@ -441,7 +441,7 @@ class OmniBase(PDDisaggregationMixin):
|
||||
if self.log_stats:
|
||||
# Emit per-request orchestrator timing (including e2e_total_ms)
|
||||
# before dropping request state.
|
||||
req_state.metrics.build_and_log_summary()
|
||||
req_state.metrics.log_timing_summary()
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"[%s] Failed to build/log summary for req=%s",
|
||||
|
||||
@@ -249,6 +249,33 @@ async def omni_run_server(args, **uvicorn_kwargs) -> None:
|
||||
await omni_run_server_worker(listen_address, sock, args, **uvicorn_kwargs)
|
||||
|
||||
|
||||
def _own_reuseport_socket(sock: socket.socket, client_count: int) -> socket.socket:
|
||||
"""Give this API server its own SO_REUSEPORT listener on the shared address.
|
||||
|
||||
All API servers accepting from the one inherited socket lets whichever
|
||||
wakes first take a whole burst of connections (the event loop accepts
|
||||
in a loop), and keep-alive then pins that imbalance for the connections'
|
||||
lifetime. Separate reuseport listeners let the kernel spread connections
|
||||
by hash. The inherited socket is bound but never listened on, so it
|
||||
receives nothing.
|
||||
"""
|
||||
if client_count <= 1:
|
||||
return sock
|
||||
if sock.family not in (socket.AF_INET, socket.AF_INET6):
|
||||
return sock
|
||||
try:
|
||||
if not sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT):
|
||||
return sock
|
||||
own = socket.socket(family=sock.family, type=socket.SOCK_STREAM)
|
||||
own.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
own.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
|
||||
own.bind(sock.getsockname()[:2])
|
||||
except OSError as e:
|
||||
logger.warning("Per-server reuseport listener unavailable (%s); sharing the inherited socket", e)
|
||||
return sock
|
||||
return own
|
||||
|
||||
|
||||
def run_omni_api_server_worker_proc(
|
||||
listen_address: str,
|
||||
sock: socket.socket,
|
||||
@@ -278,6 +305,7 @@ def run_omni_api_server_worker_proc(
|
||||
|
||||
set_process_title("APIServer", str(client_index))
|
||||
decorate_logs("APIServer", skip_if_decorated=True)
|
||||
sock = _own_reuseport_socket(sock, int(omni_client_config["client_count"]))
|
||||
uvloop.run(
|
||||
omni_run_server_worker(
|
||||
listen_address,
|
||||
@@ -512,7 +540,7 @@ async def build_async_omni(
|
||||
# Ensures everything is shutdown and cleaned up on error/exit
|
||||
async with build_async_omni_from_stage_config(
|
||||
args,
|
||||
disable_frontend_multiprocessing=disable_frontend_multiprocessing,
|
||||
disable_frontend_multiprocessing=bool(disable_frontend_multiprocessing),
|
||||
client_config=client_config,
|
||||
) as async_omni:
|
||||
yield async_omni
|
||||
|
||||
@@ -46,6 +46,15 @@ except ImportError:
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def _float32_to_pcm16_bytes(audio: np.ndarray) -> bytes:
|
||||
"""PCM_16 bytes of float32 samples, bit-identical to libsndfile's RAW writer.
|
||||
|
||||
libsndfile (1.2) converts with ``floor(x * 0x8000)`` clipped to int16.
|
||||
"""
|
||||
scaled = np.floor(audio.astype(np.float64) * 32768.0)
|
||||
return np.clip(scaled, -32768, 32767).astype("<i2").tobytes()
|
||||
|
||||
|
||||
class AudioMixin:
|
||||
"""Mixin class to add audio-related utilities."""
|
||||
|
||||
@@ -93,9 +102,15 @@ class AudioMixin:
|
||||
|
||||
soundfile_format, media_type, kwargs = supported_formats[response_format]
|
||||
|
||||
with BytesIO() as buffer:
|
||||
soundfile.write(buffer, audio_tensor, sample_rate, format=soundfile_format, **kwargs)
|
||||
audio_data = buffer.getvalue()
|
||||
audio_data: bytes | str
|
||||
if response_format == "pcm" and isinstance(audio_tensor, np.ndarray) and audio_tensor.dtype == np.float32:
|
||||
# Through BytesIO, soundfile makes a Python callback per block;
|
||||
# streamed chunks made that the API workers' largest cost.
|
||||
audio_data = _float32_to_pcm16_bytes(audio_tensor)
|
||||
else:
|
||||
with BytesIO() as buffer:
|
||||
soundfile.write(buffer, audio_tensor, sample_rate, format=soundfile_format, **kwargs)
|
||||
audio_data = buffer.getvalue()
|
||||
|
||||
if base64_encode:
|
||||
import base64
|
||||
|
||||
@@ -2275,6 +2275,22 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
if ts is not None:
|
||||
collect["word_timestamps"] = ts
|
||||
|
||||
# Let the adapter fold engine-side metadata (e.g. YuE2's
|
||||
# meta.truncated) into ``collect`` for response headers.
|
||||
if collect is not None and (adapter := self._get_tts_adapter()) is not None:
|
||||
adapter.collect_response_metadata(audio_output, collect)
|
||||
|
||||
# A model can flag a per-request synthesis failure through the
|
||||
# adapter (e.g. YuE2's terminal NAR/VAE pass OOMing on one
|
||||
# request); answer 500 instead of shipping a zero-length WAV.
|
||||
# Raising (not returning a Response) keeps this function's
|
||||
# tuple contract; create_speech maps TTSGenerationError to 500.
|
||||
if collect is not None and collect.get("audio_synthesis_error"):
|
||||
raise TTSGenerationError(
|
||||
"The model failed to synthesize audio for this request",
|
||||
retryable=False,
|
||||
)
|
||||
|
||||
audio_tensor = audio_output[audio_key]
|
||||
sr_raw = audio_output.get("sr", 24000)
|
||||
sr_val = sr_raw[-1] if isinstance(sr_raw, list) and sr_raw else sr_raw
|
||||
@@ -2715,6 +2731,8 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
"(use the WebSocket streaming path for long transcripts)",
|
||||
len(ts_json),
|
||||
)
|
||||
if collect.get("audio_truncated") is not None:
|
||||
headers["X-Audio-Truncated"] = "true" if collect["audio_truncated"] else "false"
|
||||
return Response(content=audio_bytes, media_type=media_type, headers=headers)
|
||||
|
||||
except asyncio.CancelledError:
|
||||
|
||||
@@ -66,29 +66,10 @@ class QwenOmniStreamingVideoHandler(OmniStreamingVideoHandlerBase):
|
||||
) -> tuple[list[dict[str, Any]], dict[str, Any]]:
|
||||
prewarmed = prewarmed_frames or {}
|
||||
if frame_indices is None:
|
||||
frame_indices = self._sample_frame_indices(frame_buffer, config.num_frames, prewarmed)
|
||||
user_content: list[dict] = []
|
||||
for index in frame_indices:
|
||||
frame_b64 = frame_buffer[index]
|
||||
cached = prewarmed.get(frame_b64)
|
||||
if cached is not None:
|
||||
# The shared selector excludes failed decodes before this point.
|
||||
assert isinstance(cached, tuple)
|
||||
pil, pil_uuid = cached
|
||||
user_content.append(
|
||||
{
|
||||
"type": "image_pil",
|
||||
"image_pil": pil,
|
||||
"uuid": pil_uuid,
|
||||
}
|
||||
)
|
||||
else:
|
||||
user_content.append(
|
||||
{
|
||||
"type": "image_url",
|
||||
"image_url": {"url": f"data:image/jpeg;base64,{frame_b64}"},
|
||||
}
|
||||
)
|
||||
frame_indices = self._select_frame_indices(config, frame_buffer, prewarmed)
|
||||
frames = [frame_buffer[index] for index in frame_indices]
|
||||
|
||||
user_content: list[dict] = self._build_frame_image_parts(frames, prewarmed)
|
||||
|
||||
if len(audio_buffer) > 0:
|
||||
wav_b64 = self._pcm_to_wav_b64(bytes(audio_buffer))
|
||||
@@ -107,14 +88,7 @@ class QwenOmniStreamingVideoHandler(OmniStreamingVideoHandlerBase):
|
||||
|
||||
user_message: dict[str, Any] = {"role": "user", "content": user_content}
|
||||
|
||||
messages: list[dict[str, Any]] = []
|
||||
if config.system_prompt:
|
||||
messages.append({"role": "system", "content": config.system_prompt})
|
||||
|
||||
recent_history = message_history[-2:] if len(message_history) > 2 else message_history
|
||||
for hist_msg in recent_history:
|
||||
messages.append(self._text_only_message(hist_msg))
|
||||
|
||||
messages = self._history_prefix_messages(config, message_history)
|
||||
messages.append(user_message)
|
||||
|
||||
return messages, user_message
|
||||
|
||||
@@ -124,6 +124,7 @@ from vllm_omni.entrypoints.openai.tts_adapters import ( # noqa: E402,F401
|
||||
step_audio2,
|
||||
voxcpm2,
|
||||
voxtral,
|
||||
yue2,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
|
||||
@@ -81,13 +81,24 @@ def conditioning_cache_salt(
|
||||
This replaces the uploaded data URI in the hash without changing the request.
|
||||
"""
|
||||
h = hashlib.sha256()
|
||||
ref_audio: str | list[str] | tuple[str, int] | None = request.ref_audio
|
||||
if (
|
||||
isinstance(ref_audio, str)
|
||||
and len(ref_audio) > 256
|
||||
and tts_params is not None
|
||||
and tts_params.get("ref_audio_cache_key") is not None
|
||||
):
|
||||
# The resolve key below is already a content-aware digest of this
|
||||
# locator. Hashing a repr of a large inline data URI again dominates
|
||||
# the per-request serving cost without adding information.
|
||||
ref_audio = ("ref_audio_cache_key", len(ref_audio))
|
||||
for part in (
|
||||
request.input,
|
||||
request.task_type,
|
||||
request.language,
|
||||
request.voice,
|
||||
request.ref_text,
|
||||
registered_voice if registered_voice is not None else request.ref_audio,
|
||||
registered_voice if registered_voice is not None else ref_audio,
|
||||
request.instructions,
|
||||
request.x_vector_only_mode,
|
||||
request.speaker_embedding,
|
||||
@@ -320,6 +331,15 @@ class TTSModelAdapter(ABC):
|
||||
to unrelated TTS models.
|
||||
"""
|
||||
|
||||
def collect_response_metadata(self, audio_output: Mapping[str, Any], collect: dict) -> None:
|
||||
"""Fold engine-side metadata from the mm payload into ``collect``.
|
||||
|
||||
Non-streaming only. The orchestrator surfaces select ``collect``
|
||||
entries as response headers (precedent: ``word_timestamps`` ->
|
||||
``X-Word-Timestamps``, ``audio_truncated`` -> ``X-Audio-Truncated``);
|
||||
adapters opt in by setting the keys it knows. Default: no-op.
|
||||
"""
|
||||
|
||||
async def warmup(self) -> None:
|
||||
return
|
||||
|
||||
|
||||
@@ -32,6 +32,59 @@ if TYPE_CHECKING:
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def _local_continuation_prompt(proc: Any, user_kwargs: dict[str, Any], reference: Any) -> tuple[list[int], Any] | None:
|
||||
"""Build the Local-v1.5 continuation prompt without the generic processor call.
|
||||
|
||||
Mirrors ``_build_continuation_codes`` of the model's processor: every
|
||||
template segment is encoded separately there, so the constant segments
|
||||
(keyed by ``language``) are cached and only the request text is
|
||||
tokenized. Returns ``(text_ids, audio_codes)`` equal to
|
||||
``unified[:, 0].tolist()`` / ``unified[:, 1:]``, or ``None`` when the
|
||||
request or processor does not match that exact layout.
|
||||
"""
|
||||
import torch
|
||||
|
||||
if set(user_kwargs) - {"text", "language"}:
|
||||
return None
|
||||
if not isinstance(reference, list) or len(reference) != 1 or not isinstance(reference[0], torch.Tensor):
|
||||
return None
|
||||
cfg = getattr(proc, "model_config", None)
|
||||
n_vq = getattr(cfg, "n_vq", None)
|
||||
if cfg is None or not isinstance(n_vq, int) or n_vq <= 0:
|
||||
return None
|
||||
codes = reference[0]
|
||||
if codes.ndim != 2 or int(codes.shape[1]) != n_vq or codes.shape[0] == 0:
|
||||
return None
|
||||
required = (
|
||||
"_user_prompt_prefix_ids",
|
||||
"_encode_text",
|
||||
"_user_prompt_after_reference_ids",
|
||||
"_assistant_prompt_prefix_ids",
|
||||
)
|
||||
if not all(callable(getattr(proc, name, None)) for name in required):
|
||||
return None
|
||||
language = user_kwargs.get("language")
|
||||
cache = proc.__dict__.setdefault("_vllm_omni_continuation_segments", {})
|
||||
segments = cache.get(language)
|
||||
if segments is None:
|
||||
fields = {} if language is None else {"language": language}
|
||||
head = (
|
||||
proc._user_prompt_prefix_ids()
|
||||
+ proc._encode_text("None")
|
||||
+ proc._user_prompt_after_reference_ids(language, fields)
|
||||
)
|
||||
tail = proc._assistant_prompt_prefix_ids() + [int(cfg.audio_start_token_id)]
|
||||
segments = cache[language] = ([int(t) for t in head], [int(t) for t in tail])
|
||||
head, tail = segments
|
||||
text = user_kwargs.get("text")
|
||||
prompt_ids = head + [int(t) for t in proc._encode_text("" if text is None else str(text))] + tail
|
||||
num_audio = int(codes.shape[0])
|
||||
text_ids = prompt_ids + [int(cfg.audio_assistant_slot_token_id)] * num_audio
|
||||
audio_codes = torch.full((len(text_ids), n_vq), int(cfg.audio_pad_token_id), dtype=torch.int64)
|
||||
audio_codes[len(prompt_ids) :] = codes.to(dtype=torch.int64, device="cpu")
|
||||
return text_ids, audio_codes
|
||||
|
||||
|
||||
class _MossTTSAdapterBase(ARTTSAdapter):
|
||||
accumulate_nonstreaming: bool = False
|
||||
|
||||
@@ -82,6 +135,28 @@ class _MossTTSAdapterBase(ARTTSAdapter):
|
||||
self._moss_ref_encoder = encoder
|
||||
return encoder
|
||||
|
||||
async def warmup(self) -> None:
|
||||
"""Set up the reference encoder at startup, not on the first cloning request.
|
||||
|
||||
Its CUDA graph capture takes seconds per API process (about a minute for
|
||||
a shared encoder's workers).
|
||||
"""
|
||||
if self._moss_variant not in ("tts", "local", "ttsd"):
|
||||
return
|
||||
from vllm_omni.model_executor.models.moss_tts.reference_encoder import reference_graphs_enabled
|
||||
from vllm_omni.model_executor.models.moss_tts.shared_reference_encoder import SharedReferenceEncoderStartupError
|
||||
|
||||
if not reference_graphs_enabled():
|
||||
return
|
||||
try:
|
||||
await asyncio.to_thread(self._get_moss_ref_encoder().prepare)
|
||||
except SharedReferenceEncoderStartupError:
|
||||
# Do not advertise readiness and trigger concurrent local captures
|
||||
# while the shared host is still compiling or has failed startup.
|
||||
raise
|
||||
except Exception: # noqa: BLE001 - requests still encode (and capture) on demand
|
||||
logger.warning("MOSS reference encoder warmup failed", exc_info=True)
|
||||
|
||||
async def _encode_moss_references(
|
||||
self,
|
||||
request: "OpenAICreateSpeechRequest",
|
||||
@@ -269,8 +344,16 @@ class _MossTTSAdapterBase(ARTTSAdapter):
|
||||
proc = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
|
||||
if hasattr(proc, "audio_tokenizer"):
|
||||
device = self._resolve_ref_encoder_device()
|
||||
proc.audio_tokenizer = proc.audio_tokenizer.to(device).eval()
|
||||
logger.info("MOSS reference-audio encoder (audio_tokenizer) placed on %s", device)
|
||||
proc._vllm_omni_ref_encoder_device = device
|
||||
from vllm_omni.model_executor.models.moss_tts.reference_encoder import shared_encoder_role
|
||||
|
||||
if shared_encoder_role() == "client":
|
||||
# Another API process hosts the shared encoder on the GPU.
|
||||
proc.audio_tokenizer = proc.audio_tokenizer.eval()
|
||||
logger.info("MOSS reference-audio encoder: using the shared encoder of another API process")
|
||||
else:
|
||||
proc.audio_tokenizer = proc.audio_tokenizer.to(device).eval()
|
||||
logger.info("MOSS reference-audio encoder (audio_tokenizer) placed on %s", device)
|
||||
self._moss_processor_cache = proc
|
||||
return proc
|
||||
|
||||
@@ -405,18 +488,24 @@ class _MossTTSAdapterBase(ARTTSAdapter):
|
||||
# Build the unified-codes prompt: (L, 1+n_vq) where col 0 is text/special
|
||||
# tokens and cols 1..n_vq are the delay-pattern audio code grid (mostly
|
||||
# audio_pad_code outside the reference block).
|
||||
fast = None
|
||||
if v == "local" and request.ref_text and request.ref_text.strip():
|
||||
reference = user_kwargs.pop("reference")
|
||||
user_kwargs["text"] = request.ref_text.strip() + " " + (request.input or "")
|
||||
user_msg = proc.build_user_message(**user_kwargs)
|
||||
assistant_msg = proc.build_assistant_message(audio_codes_list=reference)
|
||||
batch = proc(conversations=[[user_msg, assistant_msg]], mode="continuation")
|
||||
fast = _local_continuation_prompt(proc, user_kwargs, reference)
|
||||
if fast is None:
|
||||
user_msg = proc.build_user_message(**user_kwargs)
|
||||
assistant_msg = proc.build_assistant_message(audio_codes_list=reference)
|
||||
batch = proc(conversations=[[user_msg, assistant_msg]], mode="continuation")
|
||||
else:
|
||||
user_msg = proc.build_user_message(**user_kwargs)
|
||||
batch = proc(conversations=[[user_msg]], mode="generation")
|
||||
unified = batch["input_ids"][0] # torch.LongTensor (L, 1+n_vq)
|
||||
text_ids: list[int] = unified[:, 0].tolist()
|
||||
audio_codes: torch.Tensor = unified[:, 1:].contiguous().to(torch.int64)
|
||||
if fast is not None:
|
||||
text_ids, audio_codes = fast
|
||||
else:
|
||||
unified = batch["input_ids"][0] # torch.LongTensor (L, 1+n_vq)
|
||||
text_ids = unified[:, 0].tolist()
|
||||
audio_codes = unified[:, 1:].contiguous().to(torch.int64)
|
||||
|
||||
params = {
|
||||
"prompt_token_ids": text_ids,
|
||||
|
||||
@@ -397,34 +397,60 @@ class Qwen3TTSAdapter(ARTTSAdapter):
|
||||
|
||||
return params
|
||||
|
||||
def _load_text_tokenizer(self) -> None:
|
||||
server = self.ctx.server
|
||||
if server._tts_tokenizer is not None:
|
||||
return
|
||||
import transformers
|
||||
from transformers import AutoTokenizer
|
||||
|
||||
# Same construction as the engine's text tokenizer
|
||||
# (Qwen3TTSPromptEmbedsBuilder.get_text_tokenizer), so the ids computed
|
||||
# here can be handed to the engine.
|
||||
kwargs: dict[str, Any] = dict(trust_remote_code=True, use_fast=True, padding_side="left")
|
||||
if transformers.__version__ < "5":
|
||||
kwargs["fix_mistral_regex"] = True
|
||||
assert self.ctx.engine_client is not None
|
||||
model_name = self.ctx.engine_client.model_config.model
|
||||
server._tts_tokenizer = AutoTokenizer.from_pretrained(model_name, **kwargs)
|
||||
|
||||
def _estimate_prompt_len(self, tts_params: dict[str, Any]) -> int:
|
||||
"""Estimate prompt length so the placeholder matches model-side embeddings."""
|
||||
try:
|
||||
from vllm_omni.model_executor.models.qwen3_tts.prompt_embeds_builder import (
|
||||
PRECOMPUTED_TEXT_IDS_KEY,
|
||||
Qwen3TTSPromptEmbedsBuilder,
|
||||
build_assistant_text,
|
||||
)
|
||||
|
||||
server = self.ctx.server
|
||||
if server._tts_tokenizer is None:
|
||||
from transformers import AutoTokenizer
|
||||
|
||||
model_name = self.ctx.engine_client.model_config.model
|
||||
server._tts_tokenizer = AutoTokenizer.from_pretrained(
|
||||
model_name,
|
||||
trust_remote_code=True,
|
||||
padding_side="left",
|
||||
)
|
||||
self._load_text_tokenizer()
|
||||
assert self.ctx.engine_client is not None
|
||||
hf_config = self.ctx.engine_client.model_config.hf_config
|
||||
talker_config = hf_config.talker_config
|
||||
task_type = (tts_params.get("task_type") or ["CustomVoice"])[0]
|
||||
return Qwen3TTSPromptEmbedsBuilder.estimate_prompt_len_from_additional_information(
|
||||
text = (tts_params.get("text") or [""])[0]
|
||||
assistant_text = build_assistant_text(text) if isinstance(text, str) else None
|
||||
assistant_ids: list[list[int]] = []
|
||||
|
||||
def tokenize_prompt(t: str) -> list[int]:
|
||||
ids = server._tts_tokenizer(t, padding=False)["input_ids"]
|
||||
if t == assistant_text:
|
||||
assistant_ids.append(ids)
|
||||
return ids
|
||||
|
||||
prompt_len = Qwen3TTSPromptEmbedsBuilder.estimate_prompt_len_from_additional_information(
|
||||
additional_information=tts_params,
|
||||
task_type=task_type,
|
||||
tokenize_prompt=lambda t: server._tts_tokenizer(t, padding=False)["input_ids"],
|
||||
tokenize_prompt=tokenize_prompt,
|
||||
codec_language_id=getattr(talker_config, "codec_language_id", None),
|
||||
spk_is_dialect=getattr(talker_config, "spk_is_dialect", None),
|
||||
estimate_ref_code_len=self._estimate_ref_code_len,
|
||||
)
|
||||
if assistant_ids:
|
||||
# Spares the engine tokenizing the same text on its step thread.
|
||||
tts_params[PRECOMPUTED_TEXT_IDS_KEY] = [assistant_ids[0]]
|
||||
return prompt_len
|
||||
except Exception as e:
|
||||
logger.warning("Failed to estimate TTS prompt length, using fallback 2048: %s", e)
|
||||
return 2048
|
||||
|
||||
@@ -0,0 +1,276 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""YuE2-3B serving adapter for ``/v1/audio/speech``.
|
||||
|
||||
This is a text-to-music model on a speech endpoint, so most of the speech
|
||||
contract does not apply. ``input`` carries the lyrics and ``instructions`` the
|
||||
style caption (genre, instrumentation, tempo, mood). There is no speaker to
|
||||
select, no reference audio, and no sampling knobs: the request-local preset is
|
||||
pinned by the checkpoint's reference config. Model-specific controls travel in
|
||||
``extra_params``:
|
||||
|
||||
- ``cot``: ``"off"`` (default) | ``"melody"`` | ``"full"`` — how the ABC
|
||||
score span in the prompt is handled.
|
||||
- ``abc``: an ABC score as text, required for ``cot=melody|full``. Serving v1
|
||||
does not run the model-generated ABC phase (that is two sequential engine
|
||||
requests; use the offline example for it).
|
||||
|
||||
Unsupported parameters are rejected rather than silently ignored, following
|
||||
the MiniMax Music 3 precedent.
|
||||
"""
|
||||
|
||||
import secrets
|
||||
from collections.abc import Mapping
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import torch
|
||||
|
||||
from vllm_omni.entrypoints.openai.tts_adapters import register_tts_adapter
|
||||
from vllm_omni.entrypoints.openai.tts_adapters.base import (
|
||||
ARTTSAdapter,
|
||||
PreparedRequest,
|
||||
resolve_stage_model_path,
|
||||
)
|
||||
from vllm_omni.model_executor.models.yue2.yue2 import (
|
||||
CONTEXT,
|
||||
FRAMES_PER_SECOND,
|
||||
KEY_MAX_AUDIO_FRAMES,
|
||||
KEY_MAX_HOLD_STEPS,
|
||||
KEY_MIN_TOKENS,
|
||||
KEY_PENALTY_WINDOW,
|
||||
KEY_PHASE,
|
||||
KEY_PREFIX_IDS,
|
||||
KEY_REPETITION_PENALTY,
|
||||
KEY_SEED,
|
||||
KEY_SKIP_SYNTHESIS,
|
||||
KEY_TEMPERATURE,
|
||||
KEY_TOP_K,
|
||||
KEY_TOP_P,
|
||||
SEMANTIC_SAMPLING,
|
||||
STOP_TOKEN_IDS,
|
||||
SYNTHESIS_HOLD_STEPS,
|
||||
)
|
||||
from vllm_omni.tokenizers.yue2_prompt import semantic_prefix_ids
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm_omni.entrypoints.openai.protocol.audio import OpenAICreateSpeechRequest
|
||||
|
||||
_COT_MODES = ("off", "melody", "full")
|
||||
|
||||
# Without max_new_tokens the budget is the preset ceiling, so the model's
|
||||
# own end token sets the song length (upstream reference behavior).
|
||||
_DEFAULT_MAX_FRAMES = int(SEMANTIC_SAMPLING["max_tokens"])
|
||||
|
||||
# Sampling is fixed by the checkpoint's reference preset. Accepting these
|
||||
# would imply a control the model does not honor.
|
||||
_UNSUPPORTED_SAMPLING_PARAMS = ("temperature", "top_p", "top_k", "repetition_penalty")
|
||||
|
||||
|
||||
@register_tts_adapter
|
||||
class Yue2Adapter(ARTTSAdapter):
|
||||
"""Lyrics plus a style caption in, one 48 kHz stereo song out."""
|
||||
|
||||
name = "yue2"
|
||||
stage_keys = frozenset({"yue2"})
|
||||
model_archs = frozenset({"Yue2ForCausalLM"})
|
||||
max_new_tokens_min = int(SEMANTIC_SAMPLING["min_tokens"])
|
||||
max_new_tokens_max = int(SEMANTIC_SAMPLING["max_tokens"])
|
||||
|
||||
def __init__(self, ctx: Any) -> None:
|
||||
super().__init__(ctx)
|
||||
self._cached_tokenizer: Any = None
|
||||
|
||||
def validate(self, request: "OpenAICreateSpeechRequest") -> str | None:
|
||||
if not request.input or not request.input.strip():
|
||||
return "YuE2 requires non-empty 'input' carrying the lyrics"
|
||||
|
||||
instructions = request.instructions
|
||||
if not isinstance(instructions, str) or not instructions.strip():
|
||||
return (
|
||||
"YuE2 requires 'instructions' describing the music "
|
||||
"(genre, instrumentation, tempo, mood); it is what decides the arrangement"
|
||||
)
|
||||
|
||||
extra: dict[str, Any] = request.extra_params or {}
|
||||
cot = extra.get("cot", "off")
|
||||
if cot not in _COT_MODES:
|
||||
return f"extra_params.cot must be one of {_COT_MODES}; got {cot!r}"
|
||||
abc = extra.get("abc")
|
||||
if cot == "off":
|
||||
if abc is not None:
|
||||
return "extra_params.abc requires cot=melody|full"
|
||||
elif not isinstance(abc, str) or not abc.strip():
|
||||
return (
|
||||
f"cot={cot} requires extra_params.abc carrying an ABC score. "
|
||||
"Model-generated ABC is two engine requests and is not served "
|
||||
"in v1; use examples/offline_inference/yue2 for that."
|
||||
)
|
||||
|
||||
if request.max_new_tokens is not None:
|
||||
if request.max_new_tokens < self.max_new_tokens_min:
|
||||
return f"'max_new_tokens' must be at least {self.max_new_tokens_min}"
|
||||
if request.max_new_tokens > self.max_new_tokens_max:
|
||||
return (
|
||||
f"'max_new_tokens' counts audio frames at {FRAMES_PER_SECOND} per second "
|
||||
f"and cannot exceed {self.max_new_tokens_max}"
|
||||
)
|
||||
|
||||
voice = (request.voice or "").strip().lower()
|
||||
if voice not in ("", "default"):
|
||||
return (
|
||||
"YuE2 has no speaker to select; the vocal comes from "
|
||||
f"'instructions'. Omit 'voice' or pass 'default'; got {request.voice!r}"
|
||||
)
|
||||
if request.ref_audio is not None or request.ref_text is not None:
|
||||
return "YuE2 does not support reference-audio conditioning"
|
||||
if request.language is not None:
|
||||
return "YuE2 has no language tag; the language follows the lyrics"
|
||||
if request.task_type is not None:
|
||||
return "YuE2 does not support 'task_type'"
|
||||
if request.speed is not None and float(request.speed) != 1.0:
|
||||
return "YuE2 only supports speed=1.0; put the tempo in 'instructions', e.g. 'at 120 BPM'"
|
||||
if request.is_streaming():
|
||||
return (
|
||||
"YuE2 does not support streaming: the song is decoded in one "
|
||||
"terminal NAR/VAE pass after AR decoding finishes. Use stream=false."
|
||||
)
|
||||
|
||||
rejected = sorted(key for key in _UNSUPPORTED_SAMPLING_PARAMS if extra.get(key) is not None)
|
||||
if rejected:
|
||||
return "YuE2 has fixed sampling and does not accept: " + ", ".join(rejected)
|
||||
return None
|
||||
|
||||
async def warmup(self) -> None:
|
||||
# Resolve (and possibly download) qwen.tiktoken at startup: build()
|
||||
# runs on the request path and must not block on a hub download, and a
|
||||
# bad path should surface before the first request.
|
||||
self._tokenizer()
|
||||
|
||||
async def build(
|
||||
self,
|
||||
request: "OpenAICreateSpeechRequest",
|
||||
sampling_params_list: list,
|
||||
has_inline_ref_audio: bool,
|
||||
) -> PreparedRequest:
|
||||
del sampling_params_list, has_inline_ref_audio
|
||||
extra: dict[str, Any] = request.extra_params or {}
|
||||
cot = extra.get("cot", "off")
|
||||
encode = self._tokenizer().encode
|
||||
abc_ids = encode(extra["abc"]) if cot != "off" else None
|
||||
# validate() has already rejected blank lyrics/caption.
|
||||
instructions = request.instructions or ""
|
||||
lyrics = request.input or ""
|
||||
prefix = semantic_prefix_ids(encode, instructions, lyrics, cot, abc_ids=abc_ids)
|
||||
max_frames = int(request.max_new_tokens or _DEFAULT_MAX_FRAMES)
|
||||
# +1: the song is delivered on the step after its last frame (the
|
||||
# model acts on its draws one step late), which also needs a slot.
|
||||
if len(prefix) + max_frames + 1 > CONTEXT:
|
||||
return_err = (
|
||||
f"YuE2 prompt is {len(prefix)} tokens and the {max_frames}-frame budget "
|
||||
f"exceeds the {CONTEXT}-token context. Shorten the lyrics/style or "
|
||||
"lower max_new_tokens."
|
||||
)
|
||||
raise ValueError(return_err)
|
||||
return PreparedRequest(
|
||||
prompt={"prompt_token_ids": prefix},
|
||||
tts_params={"max_audio_frames": [max_frames]},
|
||||
model_type=self.name,
|
||||
)
|
||||
|
||||
def apply_sampling_overrides(
|
||||
self,
|
||||
sampling_params_list: list,
|
||||
request: "OpenAICreateSpeechRequest",
|
||||
prompt: dict[str, Any] | None = None,
|
||||
request_id: str | None = None,
|
||||
) -> list:
|
||||
import copy
|
||||
|
||||
sampling_params_list = copy.deepcopy(sampling_params_list)
|
||||
params = sampling_params_list[0]
|
||||
max_frames = int(request.max_new_tokens or _DEFAULT_MAX_FRAMES)
|
||||
# A service must not give every caller the same song; without an
|
||||
# explicit seed, draw one per request.
|
||||
seed = request.seed if request.seed is not None else secrets.randbelow(2**31)
|
||||
assert prompt is not None # the engine always passes the scheduled prompt
|
||||
params.extra_args = {
|
||||
**(params.extra_args or {}),
|
||||
KEY_PHASE: "semantic",
|
||||
KEY_SEED: seed,
|
||||
KEY_TEMPERATURE: SEMANTIC_SAMPLING["temperature"],
|
||||
KEY_TOP_P: SEMANTIC_SAMPLING["top_p"],
|
||||
KEY_TOP_K: SEMANTIC_SAMPLING["top_k"],
|
||||
KEY_REPETITION_PENALTY: SEMANTIC_SAMPLING["repetition_penalty"],
|
||||
KEY_PENALTY_WINDOW: SEMANTIC_SAMPLING["penalty_window"],
|
||||
KEY_MIN_TOKENS: SEMANTIC_SAMPLING["min_tokens"],
|
||||
KEY_MAX_AUDIO_FRAMES: max_frames,
|
||||
KEY_SKIP_SYNTHESIS: False,
|
||||
# Full prompt ids: under a KV prefix-cache hit the engine schedules
|
||||
# only the uncached tail, so the model cannot rebuild its NAR
|
||||
# conditioning prefix from the scheduled tokens alone.
|
||||
KEY_PREFIX_IDS: list(prompt["prompt_token_ids"]),
|
||||
}
|
||||
# The model needs one decode step beyond the last frame to deliver the
|
||||
# terminal NAR/VAE pass, so do not cap the engine at exactly max_frames.
|
||||
# Synthesize on a side stream while other songs keep decoding; the
|
||||
# request may emit up to SYNTHESIS_HOLD_STEPS hold tokens meanwhile
|
||||
# (see the model), so max_tokens leaves that much headroom.
|
||||
prompt_len = len(prompt["prompt_token_ids"])
|
||||
params.max_tokens = min(max_frames + 1 + SYNTHESIS_HOLD_STEPS, CONTEXT - prompt_len)
|
||||
params.extra_args[KEY_MAX_HOLD_STEPS] = max(0, params.max_tokens - max_frames - 1)
|
||||
params.stop_token_ids = list(STOP_TOKEN_IDS)
|
||||
params.detokenize = False
|
||||
return sampling_params_list
|
||||
|
||||
@staticmethod
|
||||
def _last_meta_flag(audio_output: Mapping[str, Any], name: str) -> Any:
|
||||
"""Read a per-request 0/1 meta flag in all three wire shapes.
|
||||
|
||||
The runner flattens nested meta.* to dotted keys (flatten_payload)
|
||||
and the wire payload is tensor-only (_ensure_tensor_values), so by
|
||||
serving time the flag is usually a 0-d "0"/"1" tensor under a dotted
|
||||
key; accept the nested/offline shapes too.
|
||||
"""
|
||||
flags = audio_output.get(f"meta.{name}")
|
||||
if flags is None:
|
||||
meta = audio_output.get("meta")
|
||||
if isinstance(meta, dict):
|
||||
flags = meta.get(name)
|
||||
if isinstance(flags, torch.Tensor):
|
||||
flags = flags.reshape(-1)[-1].item() if flags.numel() else None
|
||||
elif isinstance(flags, (list, tuple)):
|
||||
flags = flags[-1] if flags else None
|
||||
return flags
|
||||
|
||||
def collect_response_metadata(self, audio_output: Mapping[str, Any], collect: dict) -> None:
|
||||
"""Surface meta.truncated / meta.error as response headers."""
|
||||
truncated = self._last_meta_flag(audio_output, "truncated")
|
||||
if truncated is not None:
|
||||
collect["audio_truncated"] = truncated is True or str(truncated) == "1"
|
||||
# meta.error=1 marks a failed NAR/VAE pass (empty clip); serving turns
|
||||
# it into a 500 via this generic key. Absent/0 means success.
|
||||
error = self._last_meta_flag(audio_output, "error")
|
||||
if error is not None and (error is True or str(error) == "1"):
|
||||
collect["audio_synthesis_error"] = True
|
||||
|
||||
def _tokenizer(self) -> Any:
|
||||
"""The checkpoint-native tiktoken BPE, loaded once per process."""
|
||||
if self._cached_tokenizer is None:
|
||||
from vllm_omni.tokenizers.yue2_tokenizer import YuE2TextTokenizer
|
||||
|
||||
model_path = resolve_stage_model_path(self.ctx.engine_client)
|
||||
if model_path is None:
|
||||
raise RuntimeError("YuE2 tokenizer needs a resolvable stage model path")
|
||||
merge_file = Path(model_path).expanduser() / "qwen.tiktoken"
|
||||
if not merge_file.is_file():
|
||||
# model_path is an HF repo id: pull just the merge file into
|
||||
# the hub cache (vae.py does the same for the VAE snapshot).
|
||||
from vllm_omni.transformers_utils.repo_utils import hf_api
|
||||
|
||||
merge_file = Path(hf_api().hf_hub_download(model_path, "qwen.tiktoken"))
|
||||
self._cached_tokenizer = YuE2TextTokenizer(merge_file)
|
||||
return self._cached_tokenizer
|
||||
|
||||
|
||||
__all__ = ["Yue2Adapter"]
|
||||
@@ -38,7 +38,7 @@ import wave
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
from typing import Any, Final, Protocol, TypeAlias, runtime_checkable
|
||||
from typing import Any, Final, Protocol, TypeAlias, TypeGuard, runtime_checkable
|
||||
|
||||
import torch
|
||||
from fastapi import WebSocket, WebSocketDisconnect
|
||||
@@ -77,6 +77,21 @@ def _decode_frame_bytes(raw_bytes: bytes) -> Any:
|
||||
return Image.open(io.BytesIO(raw_bytes)).convert("RGB")
|
||||
|
||||
|
||||
def _usable_prewarmed_frame(cached: PrewarmedFrame | None) -> TypeGuard[tuple[Any, str]]:
|
||||
return cached is not None and cached is not _BAD_FRAME
|
||||
|
||||
|
||||
def _stage0_prefix_caching_enabled(engine_client: Any) -> bool:
|
||||
"""Read stage-0 (thinker) prefix caching from the engine. Called once
|
||||
at handler init: incremental prefill is a server-side capability, not a
|
||||
per-request choice."""
|
||||
engine = getattr(engine_client, "engine", None)
|
||||
stage_vllm_configs = getattr(engine, "stage_vllm_configs", None)
|
||||
stage0 = stage_vllm_configs[0] if stage_vllm_configs else None
|
||||
cache_config = getattr(stage0, "cache_config", None)
|
||||
return bool(getattr(cache_config, "enable_prefix_caching", False))
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class VideoStreamPipelineHooks(Protocol):
|
||||
"""Pipeline-specific hooks for streaming video handlers."""
|
||||
@@ -108,6 +123,20 @@ class VideoStreamPipelineHooks(Protocol):
|
||||
"""Update session state after a successful turn."""
|
||||
...
|
||||
|
||||
def build_engine_prompt_prefix(
|
||||
self,
|
||||
config: "StreamingVideoSessionConfig",
|
||||
frame_buffer: list[str],
|
||||
message_history: list[dict[str, Any]],
|
||||
prewarmed_frames: Mapping[str, PrewarmedFrame],
|
||||
) -> list[dict[str, Any]] | None:
|
||||
"""Prefix of the next :meth:`build_engine_prompt` through the last vision token.
|
||||
|
||||
History plus arriving video frames, without query text or input audio.
|
||||
Return None when there are no usable frames (or to disable incremental prefill).
|
||||
"""
|
||||
...
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class VideoStreamTurnTrigger:
|
||||
@@ -144,7 +173,10 @@ class StreamingVideoSessionConfig(BaseModel):
|
||||
)
|
||||
use_audio_in_video: bool = Field(
|
||||
default=True,
|
||||
description="Interleave audio chunks with video frames when audio input is present.",
|
||||
description=(
|
||||
"Pass use_audio_in_video to the processor when this is true and "
|
||||
"(incremental prefill is active, or this query has input audio)."
|
||||
),
|
||||
)
|
||||
sampling_params_list: list[dict[str, Any]] | None = Field(
|
||||
default=None,
|
||||
@@ -194,10 +226,77 @@ class OmniStreamingVideoHandler:
|
||||
) -> None:
|
||||
raise NotImplementedError
|
||||
|
||||
@staticmethod
|
||||
def _build_frame_image_parts(
|
||||
frames: list[str],
|
||||
prewarmed_frames: Mapping[str, PrewarmedFrame] | None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Decoded frame parts. Prefix and query both wait for PIL prewarm so
|
||||
every frame is ``image_pil`` plus the arrival-time uuid."""
|
||||
prewarmed = prewarmed_frames or {}
|
||||
parts: list[dict[str, Any]] = []
|
||||
for frame_b64 in frames:
|
||||
cached = prewarmed.get(frame_b64)
|
||||
if not _usable_prewarmed_frame(cached):
|
||||
continue
|
||||
pil, mm_uuid = cached
|
||||
parts.append(
|
||||
{
|
||||
"type": "image_pil",
|
||||
"image_pil": pil,
|
||||
"uuid": mm_uuid,
|
||||
}
|
||||
)
|
||||
return parts
|
||||
|
||||
def _history_prefix_messages(
|
||||
self,
|
||||
config: StreamingVideoSessionConfig,
|
||||
message_history: list[dict[str, Any]],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Shared prompt prefix (system + compressed text-only history).
|
||||
|
||||
:meth:`build_engine_prompt_prefix` and :meth:`build_engine_prompt`
|
||||
MUST build this identically: any divergence before the frame parts
|
||||
voids the warmed KV from that token onward.
|
||||
"""
|
||||
messages: list[dict[str, Any]] = []
|
||||
if config.system_prompt:
|
||||
messages.append({"role": "system", "content": config.system_prompt})
|
||||
recent_history = message_history[-2:] if len(message_history) > 2 else message_history
|
||||
for hist_msg in recent_history:
|
||||
messages.append(self._text_only_message(hist_msg))
|
||||
return messages
|
||||
|
||||
def build_engine_prompt_prefix(
|
||||
self,
|
||||
config: StreamingVideoSessionConfig,
|
||||
frame_buffer: list[str],
|
||||
message_history: list[dict[str, Any]],
|
||||
prewarmed_frames: Mapping[str, PrewarmedFrame],
|
||||
) -> list[dict[str, Any]] | None:
|
||||
"""Prefix of the next :meth:`build_engine_prompt` through the last vision token.
|
||||
|
||||
History plus arriving video frames, without query text or input audio.
|
||||
A mismatch voids the warmed KV from the first diverging token.
|
||||
Return None when there are no usable frames (or override to disable).
|
||||
"""
|
||||
frame_parts = self._build_frame_image_parts(frame_buffer, prewarmed_frames)
|
||||
if not frame_parts:
|
||||
return None
|
||||
|
||||
messages = self._history_prefix_messages(config, message_history)
|
||||
messages.append({"role": "user", "content": frame_parts})
|
||||
return messages
|
||||
|
||||
def create_message_history(self, config: StreamingVideoSessionConfig) -> Any:
|
||||
"""Per-session conversation state (default: empty OpenAI-style list)."""
|
||||
return []
|
||||
|
||||
def _incremental_prefill_active(self, config: StreamingVideoSessionConfig) -> bool:
|
||||
"""Incremental frame prefill: stage-0 prefix caching on, text-only output."""
|
||||
return self._incremental_prefill_supported and "audio" not in config.modalities
|
||||
|
||||
def on_frame_buffered(
|
||||
self,
|
||||
raw_bytes: bytes,
|
||||
@@ -219,6 +318,7 @@ class OmniStreamingVideoHandler:
|
||||
self._idle_timeout = idle_timeout
|
||||
self._config_timeout = config_timeout
|
||||
self._engine_client = engine_client
|
||||
self._incremental_prefill_supported = _stage0_prefix_caching_enabled(engine_client)
|
||||
|
||||
async def handle_session(self, websocket: WebSocket) -> None:
|
||||
"""Main session loop for a single WebSocket connection."""
|
||||
@@ -244,6 +344,53 @@ class OmniStreamingVideoHandler:
|
||||
interrupt_event = asyncio.Event()
|
||||
prewarm_tasks: set[asyncio.Task[Any]] = set()
|
||||
query_task: asyncio.Task[Any] | None = None
|
||||
session_alive = True
|
||||
# Session-owned decode readiness. Warmup/query wait on these
|
||||
# Events, not on the prewarm tasks, so cancelling an engine
|
||||
# request cannot cascade into JPEG decode.
|
||||
frame_ready: dict[str, asyncio.Event] = {}
|
||||
# In-flight warmup/query snapshots keep their PIL entries if FIFO
|
||||
# evicts the live buffer while they await readiness.
|
||||
pinned_frame_refs: dict[str, int] = {}
|
||||
|
||||
def _drop_frame_cache(frame_b64: str) -> None:
|
||||
frame_pil_cache.pop(frame_b64, None)
|
||||
frame_ready.pop(frame_b64, None)
|
||||
|
||||
def _pin_frames(frames: list[str]) -> None:
|
||||
for frame_b64 in frames:
|
||||
pinned_frame_refs[frame_b64] = pinned_frame_refs.get(frame_b64, 0) + 1
|
||||
|
||||
def _unpin_frames(frames: list[str]) -> None:
|
||||
for frame_b64 in frames:
|
||||
remaining = pinned_frame_refs.get(frame_b64, 0) - 1
|
||||
if remaining <= 0:
|
||||
pinned_frame_refs.pop(frame_b64, None)
|
||||
# Settle the eviction this pin deferred: the frame left
|
||||
# the buffer, so its cache entry is orphaned.
|
||||
if frame_b64 not in frame_buffer:
|
||||
_drop_frame_cache(frame_b64)
|
||||
else:
|
||||
pinned_frame_refs[frame_b64] = remaining
|
||||
|
||||
def _snapshot_prewarmed(frames: list[str]) -> dict[str, Any]:
|
||||
return {frame_b64: frame_pil_cache[frame_b64] for frame_b64 in frames if frame_b64 in frame_pil_cache}
|
||||
|
||||
def _frames_ready(frames: list[str]) -> bool:
|
||||
for frame_b64 in frames:
|
||||
event = frame_ready.get(frame_b64)
|
||||
if event is None or not event.is_set():
|
||||
return False
|
||||
return True
|
||||
|
||||
async def _await_frames_ready(frames: list[str]) -> None:
|
||||
waits: list[Any] = []
|
||||
for frame_b64 in dict.fromkeys(frames):
|
||||
event = frame_ready.get(frame_b64)
|
||||
if event is not None and not event.is_set():
|
||||
waits.append(event.wait())
|
||||
if waits:
|
||||
await asyncio.gather(*waits)
|
||||
|
||||
msg_queue: asyncio.Queue[dict[str, Any] | None] = asyncio.Queue(maxsize=_MAX_MSG_QUEUE)
|
||||
|
||||
@@ -294,15 +441,95 @@ class OmniStreamingVideoHandler:
|
||||
interrupt_event.set()
|
||||
prev_was_interrupted = True
|
||||
logger.info("Interrupt signaled for %s", active_request_id)
|
||||
if query_task is not None and not query_task.done():
|
||||
query_task.cancel()
|
||||
await asyncio.gather(query_task, return_exceptions=True)
|
||||
query_task = None
|
||||
# Abort after the task reaches Stage0 so a cancel during preprocess still submits.
|
||||
if abort_now and self._engine_client:
|
||||
try:
|
||||
await self._engine_client.abort(active_request_id)
|
||||
except Exception:
|
||||
logger.debug("Abort failed for %s", active_request_id, exc_info=True)
|
||||
if query_task is not None and not query_task.done():
|
||||
query_task.cancel()
|
||||
await asyncio.gather(query_task, return_exceptions=True)
|
||||
query_task = None
|
||||
|
||||
# --- Incremental prefill: keep the prefix cache warmed to the latest
|
||||
# buffered frame so a query only pays for its own text suffix. ---
|
||||
warmup_task: asyncio.Task[Any] | None = None
|
||||
warmup_request_id: str | None = None
|
||||
warmed_signature: tuple[Any, ...] | None = None
|
||||
|
||||
def _context_signature() -> tuple[Any, ...]:
|
||||
history_len = len(message_history) if isinstance(message_history, list) else None
|
||||
return (history_len, tuple(frame_buffer))
|
||||
|
||||
def _maybe_start_warmup() -> None:
|
||||
nonlocal warmup_task, warmup_request_id
|
||||
if not session_alive:
|
||||
return
|
||||
if self._engine_client is None or not self._incremental_prefill_active(config):
|
||||
return
|
||||
if active_request_id is not None:
|
||||
return
|
||||
if warmup_task is not None and not warmup_task.done():
|
||||
return
|
||||
if not frame_buffer or _context_signature() == warmed_signature:
|
||||
return
|
||||
frames = list(frame_buffer)
|
||||
# Decode is session-owned: do not start prefill until PIL is
|
||||
# already in cache, so this task is only engine work.
|
||||
if not _frames_ready(frames):
|
||||
return
|
||||
signature = _context_signature()
|
||||
request_id = f"video-warmup-{uuid.uuid4().hex[:12]}"
|
||||
warmup_request_id = request_id
|
||||
_pin_frames(frames)
|
||||
|
||||
async def _run_warmup() -> None:
|
||||
nonlocal warmup_request_id, warmed_signature
|
||||
cancelled = False
|
||||
try:
|
||||
messages = self.build_engine_prompt_prefix(
|
||||
config, frames, message_history, _snapshot_prewarmed(frames)
|
||||
)
|
||||
if not messages:
|
||||
warmed_signature = signature
|
||||
return
|
||||
await self._prefill_context(config, messages, request_id)
|
||||
warmed_signature = signature
|
||||
except asyncio.CancelledError:
|
||||
cancelled = True
|
||||
raise
|
||||
except Exception:
|
||||
# Mark attempted so a persistently failing state does
|
||||
# not hot-loop; the next frame retriggers naturally.
|
||||
warmed_signature = signature
|
||||
logger.debug("Context warmup failed for %s", request_id, exc_info=True)
|
||||
finally:
|
||||
_unpin_frames(frames)
|
||||
if warmup_request_id == request_id:
|
||||
warmup_request_id = None
|
||||
# Skip on cancel: query already owns the session and will
|
||||
# call_soon after it finishes. Restarting here can spawn a
|
||||
# second warmup with the same frames before active_request_id
|
||||
# is set.
|
||||
if not cancelled:
|
||||
asyncio.get_running_loop().call_soon(_maybe_start_warmup)
|
||||
|
||||
warmup_task = asyncio.create_task(_run_warmup())
|
||||
|
||||
async def _cancel_warmup() -> None:
|
||||
nonlocal warmup_task, warmup_request_id
|
||||
request_id = warmup_request_id
|
||||
if warmup_task is not None and not warmup_task.done():
|
||||
warmup_task.cancel()
|
||||
await asyncio.gather(warmup_task, return_exceptions=True)
|
||||
warmup_task = None
|
||||
warmup_request_id = None
|
||||
if request_id and self._engine_client:
|
||||
try:
|
||||
await self._engine_client.abort(request_id)
|
||||
except Exception:
|
||||
logger.debug("Warmup abort failed for %s", request_id, exc_info=True)
|
||||
|
||||
async def _start_query_turn(*, query_text: str) -> None:
|
||||
"""Schedule a new inference turn from the current buffers."""
|
||||
@@ -311,28 +538,43 @@ class OmniStreamingVideoHandler:
|
||||
await _cancel_active_query()
|
||||
|
||||
if not frame_buffer:
|
||||
await _cancel_warmup()
|
||||
await self._send_error(websocket, "No frames buffered")
|
||||
return
|
||||
|
||||
# Claim the session before cancelling warmup so a leftover
|
||||
# call_soon from a just-finished warmup hits the 405 gate.
|
||||
request_id = f"video-{uuid.uuid4().hex[:12]}"
|
||||
active_request_id = request_id
|
||||
interrupt_event.clear()
|
||||
# Free prefill capacity for the query; completed warmup blocks
|
||||
# stay in the prefix cache and are reused by it.
|
||||
await _cancel_warmup()
|
||||
|
||||
if prev_was_interrupted and prev_request_id and self._engine_client:
|
||||
try:
|
||||
await self._engine_client.abort(prev_request_id)
|
||||
except Exception:
|
||||
pass
|
||||
prev_was_interrupted = False
|
||||
|
||||
request_id = f"video-{uuid.uuid4().hex[:12]}"
|
||||
active_request_id = request_id
|
||||
interrupt_event.clear()
|
||||
query_frames = list(frame_buffer)
|
||||
query_frame_metadata = list(frame_metadata)
|
||||
query_audio_buffer = bytearray(audio_buffer)
|
||||
audio_buffer.clear()
|
||||
query_prewarmed_frames = dict(frame_pil_cache)
|
||||
# Legacy stride positions ignore decode status. Waiting on the
|
||||
# whole buffer would stall the query on a frame it will not use.
|
||||
if self._incremental_prefill_active(config):
|
||||
wait_indices = list(range(len(query_frames)))
|
||||
else:
|
||||
wait_indices = self._candidate_frame_indices(query_frames, config.num_frames)
|
||||
wait_frames = [query_frames[index] for index in wait_indices]
|
||||
_pin_frames(wait_frames)
|
||||
|
||||
async def _run_query() -> None:
|
||||
nonlocal active_request_id, prev_request_id
|
||||
try:
|
||||
await _await_frames_ready(wait_frames)
|
||||
query_prewarmed_frames = _snapshot_prewarmed(query_frames)
|
||||
process_kwargs: dict[str, Any] = {}
|
||||
if any(metadata.get("frame_id") for metadata in query_frame_metadata):
|
||||
process_kwargs["frame_metadata"] = query_frame_metadata
|
||||
@@ -349,19 +591,25 @@ class OmniStreamingVideoHandler:
|
||||
**process_kwargs,
|
||||
)
|
||||
finally:
|
||||
_unpin_frames(wait_frames)
|
||||
if active_request_id == request_id:
|
||||
prev_request_id = request_id
|
||||
active_request_id = None
|
||||
# Warm frames that arrived during the turn (fires after
|
||||
# this task completes; gated on no active query).
|
||||
asyncio.get_running_loop().call_soon(_maybe_start_warmup)
|
||||
|
||||
query_task = asyncio.create_task(_run_query())
|
||||
|
||||
async def _processor() -> None:
|
||||
"""Process enqueued messages."""
|
||||
nonlocal active_request_id, prev_request_id, prev_was_interrupted, query_task
|
||||
nonlocal session_alive
|
||||
|
||||
while True:
|
||||
msg = await msg_queue.get()
|
||||
if msg is None:
|
||||
session_alive = False
|
||||
await _cancel_active_query(abort_now=True)
|
||||
return
|
||||
|
||||
@@ -376,8 +624,8 @@ class OmniStreamingVideoHandler:
|
||||
]
|
||||
frame_buffer[:] = [frame_buffer[index] for index in retained_indices]
|
||||
frame_metadata[:] = [frame_metadata[index] for index in retained_indices]
|
||||
if frame_pil_cache.get(frame_data) is _BAD_FRAME:
|
||||
frame_pil_cache.pop(frame_data, None)
|
||||
if frame_pil_cache.get(frame_data) is _BAD_FRAME and frame_data not in pinned_frame_refs:
|
||||
_drop_frame_cache(frame_data)
|
||||
if removed:
|
||||
await self._send_error(websocket, "Frame decode failed")
|
||||
|
||||
@@ -410,10 +658,24 @@ class OmniStreamingVideoHandler:
|
||||
max_buf = config.max_frames
|
||||
dropped_frame_id: str | None = None
|
||||
if len(frame_buffer) >= max_buf:
|
||||
dropped = frame_buffer.pop(0)
|
||||
dropped_metadata = frame_metadata.pop(0)
|
||||
dropped_frame_id = dropped_metadata.get("frame_id")
|
||||
frame_pil_cache.pop(dropped, None)
|
||||
# Legacy drops one frame. Incremental drops the oldest half so later frames append.
|
||||
drop_count = max(1, max_buf // 2) if self._incremental_prefill_active(config) else 1
|
||||
for _ in range(drop_count):
|
||||
dropped = frame_buffer.pop(0)
|
||||
dropped_metadata = frame_metadata.pop(0)
|
||||
if dropped_frame_id is None:
|
||||
dropped_frame_id = dropped_metadata.get("frame_id")
|
||||
# Duplicate frames share one cache entry keyed by
|
||||
# b64: keep it while any duplicate remains buffered.
|
||||
if dropped not in pinned_frame_refs and dropped not in frame_buffer:
|
||||
_drop_frame_cache(dropped)
|
||||
if drop_count > 1:
|
||||
logger.warning(
|
||||
"incremental prefill dropped %d oldest frames at max_frames=%d; "
|
||||
"buffered_frames is the remaining suffix",
|
||||
drop_count,
|
||||
max_buf,
|
||||
)
|
||||
frame_buffer.append(frame_data)
|
||||
frame_metadata.append(
|
||||
{
|
||||
@@ -435,17 +697,23 @@ class OmniStreamingVideoHandler:
|
||||
)
|
||||
# Prewarm: decode PIL off the event loop so query-time chat_template
|
||||
# can skip base64+Image.open. uuid=md5 lets mm_cache dedupe identical frames.
|
||||
if frame_data not in frame_pil_cache:
|
||||
if frame_data not in frame_pil_cache and frame_data not in frame_ready:
|
||||
mm_uuid = hashlib.md5(raw_bytes, usedforsecurity=False).hexdigest()
|
||||
frame_ready[frame_data] = asyncio.Event()
|
||||
|
||||
async def _prewarm(b64: str, b: bytes, u: str) -> None:
|
||||
cancelled = False
|
||||
try:
|
||||
pil = await asyncio.to_thread(_decode_frame_bytes, b)
|
||||
# The frame may have been evicted while decoding.
|
||||
if b64 in frame_buffer:
|
||||
# The frame may have been evicted (and unpinned)
|
||||
# while decoding; frame_ready tracks liveness.
|
||||
if b64 in frame_ready:
|
||||
frame_pil_cache[b64] = (pil, u)
|
||||
except asyncio.CancelledError:
|
||||
cancelled = True
|
||||
raise
|
||||
except Exception:
|
||||
if b64 not in frame_buffer:
|
||||
if b64 not in frame_ready:
|
||||
return
|
||||
frame_pil_cache[b64] = _BAD_FRAME
|
||||
logger.warning("prewarm decode failed for frame (len=%d)", len(b))
|
||||
@@ -455,10 +723,18 @@ class OmniStreamingVideoHandler:
|
||||
logger.warning(
|
||||
"frame decode failure event dropped because message queue is full"
|
||||
)
|
||||
finally:
|
||||
event = frame_ready.get(b64)
|
||||
if event is not None:
|
||||
event.set()
|
||||
if not cancelled:
|
||||
asyncio.get_running_loop().call_soon(_maybe_start_warmup)
|
||||
|
||||
task = asyncio.create_task(_prewarm(frame_data, raw_bytes, mm_uuid))
|
||||
prewarm_tasks.add(task)
|
||||
task.add_done_callback(prewarm_tasks.discard)
|
||||
elif frame_data in frame_pil_cache:
|
||||
frame_ready.setdefault(frame_data, asyncio.Event()).set()
|
||||
|
||||
is_generating = active_request_id is not None or (
|
||||
query_task is not None and not query_task.done()
|
||||
@@ -471,6 +747,8 @@ class OmniStreamingVideoHandler:
|
||||
)
|
||||
):
|
||||
await _start_query_turn(query_text="")
|
||||
else:
|
||||
_maybe_start_warmup()
|
||||
|
||||
elif msg_type == "audio.chunk":
|
||||
data_b64 = msg.get("data", "")
|
||||
@@ -501,6 +779,7 @@ class OmniStreamingVideoHandler:
|
||||
await _start_query_turn(query_text=query_text)
|
||||
|
||||
elif msg_type == "video.done":
|
||||
session_alive = False
|
||||
if query_task is not None and not query_task.done():
|
||||
await asyncio.gather(query_task, return_exceptions=True)
|
||||
query_task = None
|
||||
@@ -520,6 +799,7 @@ class OmniStreamingVideoHandler:
|
||||
try:
|
||||
await _processor()
|
||||
finally:
|
||||
session_alive = False
|
||||
reader_task.cancel()
|
||||
try:
|
||||
await reader_task
|
||||
@@ -529,6 +809,7 @@ class OmniStreamingVideoHandler:
|
||||
t.cancel()
|
||||
if prewarm_tasks:
|
||||
await asyncio.gather(*prewarm_tasks, return_exceptions=True)
|
||||
await _cancel_warmup()
|
||||
if query_task is not None and not query_task.done():
|
||||
await _cancel_active_query(abort_now=True)
|
||||
|
||||
@@ -643,9 +924,10 @@ class OmniStreamingVideoHandler:
|
||||
ChatCompletionRequest,
|
||||
)
|
||||
|
||||
reuse_active = self._incremental_prefill_active(config)
|
||||
# Select once from this turn's snapshot so prompt images and the
|
||||
# consumed event refer to exactly the same frames, including decode failures.
|
||||
frame_indices = self._sample_frame_indices(frame_buffer, config.num_frames, prewarmed_frames)
|
||||
frame_indices = self._select_frame_indices(config, frame_buffer, prewarmed_frames)
|
||||
messages, user_message = self.build_engine_prompt(
|
||||
config,
|
||||
frame_buffer,
|
||||
@@ -665,7 +947,9 @@ class OmniStreamingVideoHandler:
|
||||
"continue_final_message": False,
|
||||
"add_special_tokens": False,
|
||||
}
|
||||
if config.use_audio_in_video and len(audio_buffer) > 0:
|
||||
# Incremental: same kwargs as warmup so frame mm hashes stay a prefix.
|
||||
# Legacy: only when this query actually has input audio.
|
||||
if config.use_audio_in_video and (reuse_active or len(audio_buffer) > 0):
|
||||
request_kwargs["mm_processor_kwargs"] = {
|
||||
"use_audio_in_video": True,
|
||||
}
|
||||
@@ -680,97 +964,142 @@ class OmniStreamingVideoHandler:
|
||||
await self._send_error(websocket, f"Failed to build request: {e}")
|
||||
return
|
||||
|
||||
try:
|
||||
engine_prompt = await self._preprocess_to_engine_prompt(chat_request)
|
||||
except Exception as e:
|
||||
await self._send_error(websocket, f"Preprocess failed: {e}")
|
||||
return
|
||||
decoded_ready_ts_ms = _time.monotonic() * 1000
|
||||
selected_metadata = [frame_metadata[index] for index in frame_indices] if frame_metadata else []
|
||||
model_selected_ts_ms = _time.monotonic() * 1000
|
||||
submitted = asyncio.get_running_loop().create_future()
|
||||
|
||||
await websocket.send_json({"type": "response.start"})
|
||||
text_parts: list[str] = []
|
||||
text_done_sent = False
|
||||
audio_chunk_count = 0
|
||||
# Count emitted tensors only to identify the first audio emission.
|
||||
# Default and explicit sampling parameters use DELTA audio outputs.
|
||||
audio_chunks_drained = 0
|
||||
previous_text = ""
|
||||
interrupted = False
|
||||
frames_consumed_sent = False
|
||||
t_start = _time.monotonic()
|
||||
t_first_text = None
|
||||
t_first_audio = None
|
||||
async def _drive_query() -> None:
|
||||
decoded_ready_ts_ms = _time.monotonic() * 1000
|
||||
selected_metadata = [frame_metadata[index] for index in frame_indices] if frame_metadata else []
|
||||
model_selected_ts_ms = _time.monotonic() * 1000
|
||||
|
||||
# Wire-level async-chunk switch. "off" means
|
||||
# buffer all deltas server-side and flush once at the end; the engine
|
||||
# pipeline still overlaps internally.
|
||||
async_chunk_mode = video_stream_envs.VLLM_VIDEO_ASYNC_CHUNK
|
||||
streaming = async_chunk_mode == "on"
|
||||
audio_tail_tensors: list[Any] = []
|
||||
if not interrupt_event.is_set():
|
||||
await websocket.send_json({"type": "response.start"})
|
||||
text_parts: list[str] = []
|
||||
text_done_sent = False
|
||||
audio_chunk_count = 0
|
||||
# Count emitted tensors only to identify the first audio emission.
|
||||
# Default and explicit sampling parameters use DELTA audio outputs.
|
||||
audio_chunks_drained = 0
|
||||
previous_text = ""
|
||||
interrupted = False
|
||||
frames_consumed_sent = False
|
||||
t_start = _time.monotonic()
|
||||
t_first_text = None
|
||||
t_first_audio = None
|
||||
|
||||
try:
|
||||
result_gen = engine_client.generate(
|
||||
prompt=engine_prompt,
|
||||
request_id=request_id,
|
||||
output_modalities=config.modalities,
|
||||
**sampling_kwargs,
|
||||
)
|
||||
# Wire-level async-chunk switch. "off" means
|
||||
# buffer all deltas server-side and flush once at the end; the engine
|
||||
# pipeline still overlaps internally.
|
||||
async_chunk_mode = video_stream_envs.VLLM_VIDEO_ASYNC_CHUNK
|
||||
streaming = async_chunk_mode == "on"
|
||||
audio_tail_tensors: list[Any] = []
|
||||
|
||||
async for output in result_gen:
|
||||
# Soft interrupt: drain without sending
|
||||
if interrupt_event.is_set():
|
||||
if not interrupted:
|
||||
logger.info("Generation interrupted — draining")
|
||||
interrupted = True
|
||||
continue
|
||||
try:
|
||||
assert engine_client is not None
|
||||
result_gen = engine_client.generate(
|
||||
prompt=engine_prompt,
|
||||
request_id=request_id,
|
||||
output_modalities=config.modalities,
|
||||
submitted=submitted,
|
||||
**sampling_kwargs,
|
||||
)
|
||||
|
||||
if not isinstance(output, OmniRequestOutput):
|
||||
continue
|
||||
async for output in result_gen:
|
||||
# Soft interrupt: drain without sending
|
||||
if interrupt_event.is_set():
|
||||
if not interrupted:
|
||||
logger.info("Generation interrupted — draining")
|
||||
interrupted = True
|
||||
continue
|
||||
|
||||
if not frames_consumed_sent and frame_metadata:
|
||||
await websocket.send_json(
|
||||
{
|
||||
"type": "video.frames.consumed",
|
||||
"request_id": request_id,
|
||||
"model_selected_ts_ms": model_selected_ts_ms,
|
||||
"frame_ids": [
|
||||
metadata["frame_id"]
|
||||
for metadata in selected_metadata
|
||||
if isinstance(metadata.get("frame_id"), str)
|
||||
],
|
||||
"frames": [
|
||||
{
|
||||
"frame_id": metadata.get("frame_id"),
|
||||
"pts_ms": metadata.get("pts_ms"),
|
||||
"source_pts_ms": metadata.get("source_pts_ms"),
|
||||
"quality_profile": metadata.get("quality_profile"),
|
||||
"receiver_received_ts_ms": metadata.get("receiver_received_ts_ms"),
|
||||
"decoded_ready_ts_ms": decoded_ready_ts_ms,
|
||||
}
|
||||
for metadata in selected_metadata
|
||||
],
|
||||
"latest_pts_ms": selected_metadata[-1].get("pts_ms") if selected_metadata else None,
|
||||
}
|
||||
)
|
||||
frames_consumed_sent = True
|
||||
if not isinstance(output, OmniRequestOutput):
|
||||
continue
|
||||
|
||||
out_type = getattr(output, "final_output_type", "text")
|
||||
if not frames_consumed_sent and frame_metadata:
|
||||
await websocket.send_json(
|
||||
{
|
||||
"type": "video.frames.consumed",
|
||||
"request_id": request_id,
|
||||
"model_selected_ts_ms": model_selected_ts_ms,
|
||||
"frame_ids": [
|
||||
metadata["frame_id"]
|
||||
for metadata in selected_metadata
|
||||
if isinstance(metadata.get("frame_id"), str)
|
||||
],
|
||||
"frames": [
|
||||
{
|
||||
"frame_id": metadata.get("frame_id"),
|
||||
"pts_ms": metadata.get("pts_ms"),
|
||||
"source_pts_ms": metadata.get("source_pts_ms"),
|
||||
"quality_profile": metadata.get("quality_profile"),
|
||||
"receiver_received_ts_ms": metadata.get("receiver_received_ts_ms"),
|
||||
"decoded_ready_ts_ms": decoded_ready_ts_ms,
|
||||
}
|
||||
for metadata in selected_metadata
|
||||
],
|
||||
"latest_pts_ms": selected_metadata[-1].get("pts_ms") if selected_metadata else None,
|
||||
}
|
||||
)
|
||||
frames_consumed_sent = True
|
||||
|
||||
if out_type == "audio":
|
||||
if streaming and not text_done_sent:
|
||||
full_text = "".join(text_parts)
|
||||
await websocket.send_json({"type": "response.text.done", "text": full_text})
|
||||
text_done_sent = True
|
||||
out_type = getattr(output, "final_output_type", "text")
|
||||
|
||||
if t_first_audio is None:
|
||||
t_first_audio = _time.monotonic()
|
||||
audio_chunk_count += 1
|
||||
if streaming:
|
||||
b64, audio_chunks_drained = self._extract_audio_delta_b64(
|
||||
if out_type == "audio":
|
||||
if streaming and not text_done_sent:
|
||||
full_text = "".join(text_parts)
|
||||
await websocket.send_json({"type": "response.text.done", "text": full_text})
|
||||
text_done_sent = True
|
||||
|
||||
if t_first_audio is None:
|
||||
t_first_audio = _time.monotonic()
|
||||
audio_chunk_count += 1
|
||||
if streaming:
|
||||
b64, audio_chunks_drained = self._extract_audio_delta_b64(
|
||||
output,
|
||||
audio_chunks_drained,
|
||||
)
|
||||
if b64:
|
||||
await websocket.send_json(
|
||||
{
|
||||
"type": "response.output_audio.delta",
|
||||
"data": b64,
|
||||
"format": "wav",
|
||||
}
|
||||
)
|
||||
else:
|
||||
audio_data = self._get_audio_data(output)
|
||||
if audio_data is not None:
|
||||
if isinstance(audio_data, list):
|
||||
audio_tail_tensors.extend(audio_data)
|
||||
else:
|
||||
audio_tail_tensors.append(audio_data)
|
||||
else:
|
||||
delta_text, previous_text = self._extract_text_delta(
|
||||
output,
|
||||
audio_chunks_drained,
|
||||
previous_text,
|
||||
)
|
||||
if delta_text:
|
||||
if t_first_text is None:
|
||||
t_first_text = _time.monotonic()
|
||||
text_parts.append(delta_text)
|
||||
if streaming:
|
||||
await websocket.send_json({"type": "response.text.delta", "delta": delta_text})
|
||||
|
||||
if not text_done_sent:
|
||||
full_text = "".join(text_parts)
|
||||
await websocket.send_json({"type": "response.text.done", "text": full_text})
|
||||
text_done_sent = True
|
||||
|
||||
if not streaming and audio_tail_tensors:
|
||||
try:
|
||||
coalesced = audio_tail_tensors[0]
|
||||
if len(audio_tail_tensors) != 1:
|
||||
coalesced = torch.cat(audio_tail_tensors, dim=-1)
|
||||
tail_np = self._tensor_to_1d_np(coalesced)
|
||||
b64, _ = self._encode_tail(
|
||||
tail_np,
|
||||
0,
|
||||
new_drained=len(audio_tail_tensors),
|
||||
is_first=True,
|
||||
)
|
||||
if b64:
|
||||
await websocket.send_json(
|
||||
@@ -780,76 +1109,45 @@ class OmniStreamingVideoHandler:
|
||||
"format": "wav",
|
||||
}
|
||||
)
|
||||
else:
|
||||
audio_data = self._get_audio_data(output)
|
||||
if audio_data is not None:
|
||||
if isinstance(audio_data, list):
|
||||
audio_tail_tensors.extend(audio_data)
|
||||
else:
|
||||
audio_tail_tensors.append(audio_data)
|
||||
else:
|
||||
delta_text, previous_text = self._extract_text_delta(
|
||||
output,
|
||||
previous_text,
|
||||
)
|
||||
if delta_text:
|
||||
if t_first_text is None:
|
||||
t_first_text = _time.monotonic()
|
||||
text_parts.append(delta_text)
|
||||
if streaming:
|
||||
await websocket.send_json({"type": "response.text.delta", "delta": delta_text})
|
||||
except Exception:
|
||||
logger.exception("Failed to coalesce off-path audio")
|
||||
|
||||
if not text_done_sent:
|
||||
if audio_chunk_count > 0:
|
||||
await websocket.send_json({"type": "response.output_audio.done"})
|
||||
|
||||
response_text = "".join(text_parts)
|
||||
self.on_turn_complete(message_history, user_message, response_text)
|
||||
|
||||
t_end = _time.monotonic()
|
||||
logger.info(
|
||||
"[TIMING] mode=%s total=%.2fs first_text=%.2fs first_audio=%.2fs audio_chunks=%d",
|
||||
async_chunk_mode,
|
||||
t_end - t_start,
|
||||
(t_first_text - t_start) if t_first_text else -1,
|
||||
(t_first_audio - t_start) if t_first_audio else -1,
|
||||
audio_chunk_count,
|
||||
)
|
||||
|
||||
except Exception:
|
||||
logger.exception("Engine query failed")
|
||||
await self._send_error(websocket, "Query processing failed")
|
||||
|
||||
if not text_done_sent and not interrupt_event.is_set():
|
||||
full_text = "".join(text_parts)
|
||||
await websocket.send_json({"type": "response.text.done", "text": full_text})
|
||||
text_done_sent = True
|
||||
|
||||
if not streaming and audio_tail_tensors:
|
||||
try:
|
||||
coalesced = (
|
||||
audio_tail_tensors[0] if len(audio_tail_tensors) == 1 else torch.cat(audio_tail_tensors, dim=-1)
|
||||
)
|
||||
tail_np = self._tensor_to_1d_np(coalesced)
|
||||
b64, _ = self._encode_tail(
|
||||
tail_np,
|
||||
0,
|
||||
new_drained=len(audio_tail_tensors),
|
||||
is_first=True,
|
||||
)
|
||||
if b64:
|
||||
await websocket.send_json(
|
||||
{
|
||||
"type": "response.output_audio.delta",
|
||||
"data": b64,
|
||||
"format": "wav",
|
||||
}
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Failed to coalesce off-path audio")
|
||||
|
||||
if audio_chunk_count > 0:
|
||||
await websocket.send_json({"type": "response.output_audio.done"})
|
||||
|
||||
response_text = "".join(text_parts)
|
||||
self.on_turn_complete(message_history, user_message, response_text)
|
||||
|
||||
t_end = _time.monotonic()
|
||||
logger.info(
|
||||
"[TIMING] mode=%s total=%.2fs first_text=%.2fs first_audio=%.2fs audio_chunks=%d",
|
||||
async_chunk_mode,
|
||||
t_end - t_start,
|
||||
(t_first_text - t_start) if t_first_text else -1,
|
||||
(t_first_audio - t_start) if t_first_audio else -1,
|
||||
audio_chunk_count,
|
||||
)
|
||||
|
||||
except Exception:
|
||||
logger.exception("Engine query failed")
|
||||
await self._send_error(websocket, "Query processing failed")
|
||||
|
||||
if not text_done_sent:
|
||||
full_text = "".join(text_parts)
|
||||
await websocket.send_json({"type": "response.text.done", "text": full_text})
|
||||
prompt_task = asyncio.ensure_future(self._preprocess_to_engine_prompt(chat_request))
|
||||
try:
|
||||
engine_prompt = await asyncio.shield(prompt_task)
|
||||
except asyncio.CancelledError:
|
||||
# Sender cache is updated in preprocess; submit before the caller aborts.
|
||||
engine_prompt = await asyncio.shield(prompt_task)
|
||||
await self._stop_after_submit(asyncio.ensure_future(_drive_query()), submitted)
|
||||
raise
|
||||
except Exception as e:
|
||||
await self._send_error(websocket, f"Preprocess failed: {e}")
|
||||
return
|
||||
await self._await_until_submitted(asyncio.ensure_future(_drive_query()), submitted)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Audio helpers
|
||||
@@ -1009,6 +1307,105 @@ class OmniStreamingVideoHandler:
|
||||
return text[len(previous_text) :], text
|
||||
return text, text
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Incremental prefill (context warmup)
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
async def _stop_after_submit(self, drive: asyncio.Future[Any], submitted: asyncio.Future[None]) -> None:
|
||||
"""Stage0 must observe the request before the caller aborts it."""
|
||||
if not submitted.done():
|
||||
submit_wait = asyncio.ensure_future(asyncio.shield(submitted))
|
||||
await asyncio.wait({submit_wait, drive}, return_when=asyncio.FIRST_COMPLETED)
|
||||
if not submitted.done():
|
||||
submit_wait.cancel()
|
||||
exc = drive.exception() if drive.done() else None
|
||||
if exc is not None:
|
||||
raise exc
|
||||
if not drive.done():
|
||||
drive.cancel()
|
||||
await asyncio.gather(drive, return_exceptions=True)
|
||||
|
||||
async def _await_until_submitted(self, drive: asyncio.Future[Any], submitted: asyncio.Future[None]) -> None:
|
||||
"""On cancel, wait until Stage0 has accepted the request before aborting."""
|
||||
try:
|
||||
# Shield so cancelling this task does not cancel generate before Stage0 submit.
|
||||
await asyncio.shield(drive)
|
||||
except asyncio.CancelledError:
|
||||
await self._stop_after_submit(drive, submitted)
|
||||
raise
|
||||
|
||||
async def _drive_warmup_generate(
|
||||
self,
|
||||
engine_client: Any,
|
||||
engine_prompt: Any,
|
||||
request_id: str,
|
||||
modalities: list[str],
|
||||
*,
|
||||
stop_after_submit: bool = False,
|
||||
) -> None:
|
||||
"""max_tokens=1 generate; cancellation still submits before abort."""
|
||||
from vllm import SamplingParams
|
||||
|
||||
submitted = asyncio.get_running_loop().create_future()
|
||||
result_gen = engine_client.generate(
|
||||
prompt=engine_prompt,
|
||||
request_id=request_id,
|
||||
sampling_params=SamplingParams(max_tokens=1, temperature=0.0),
|
||||
output_modalities=modalities,
|
||||
submitted=submitted,
|
||||
)
|
||||
|
||||
async def _drive() -> None:
|
||||
async for _ in result_gen:
|
||||
pass
|
||||
|
||||
drive = asyncio.ensure_future(_drive())
|
||||
if stop_after_submit:
|
||||
await self._stop_after_submit(drive, submitted)
|
||||
return
|
||||
await self._await_until_submitted(drive, submitted)
|
||||
|
||||
async def _prefill_context(
|
||||
self,
|
||||
config: StreamingVideoSessionConfig,
|
||||
messages: list[dict[str, Any]],
|
||||
request_id: str,
|
||||
) -> None:
|
||||
"""max_tokens=1 generate so arriving frames land in the prefix cache."""
|
||||
from vllm.entrypoints.openai.chat_completion.protocol import (
|
||||
ChatCompletionRequest,
|
||||
)
|
||||
|
||||
engine_client = self._engine_client
|
||||
if engine_client is None:
|
||||
return
|
||||
|
||||
request_kwargs: dict[str, Any] = {
|
||||
"model": config.model or "default",
|
||||
"messages": messages,
|
||||
"stream": True,
|
||||
"modalities": config.modalities,
|
||||
"add_generation_prompt": True,
|
||||
"continue_final_message": False,
|
||||
"add_special_tokens": False,
|
||||
}
|
||||
if config.use_audio_in_video:
|
||||
request_kwargs["mm_processor_kwargs"] = {
|
||||
"use_audio_in_video": True,
|
||||
}
|
||||
chat_request = ChatCompletionRequest(**request_kwargs)
|
||||
prompt_task = asyncio.ensure_future(self._preprocess_to_engine_prompt(chat_request))
|
||||
try:
|
||||
engine_prompt = await asyncio.shield(prompt_task)
|
||||
except asyncio.CancelledError:
|
||||
# Sender cache is updated in preprocess; submit before the caller aborts.
|
||||
engine_prompt = await asyncio.shield(prompt_task)
|
||||
await self._drive_warmup_generate(
|
||||
engine_client, engine_prompt, request_id, config.modalities, stop_after_submit=True
|
||||
)
|
||||
raise
|
||||
await self._drive_warmup_generate(engine_client, engine_prompt, request_id, config.modalities)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Preprocessing
|
||||
# ------------------------------------------------------------------
|
||||
@@ -1043,6 +1440,18 @@ class OmniStreamingVideoHandler:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def _candidate_frame_indices(frame_buffer: list[str], num_frames: int) -> list[int]:
|
||||
"""Stride positions for a legacy query, including the last frame.
|
||||
|
||||
Ignores decode status so a frame still decoding is waited on, not skipped.
|
||||
"""
|
||||
n_buf = len(frame_buffer)
|
||||
if n_buf <= num_frames:
|
||||
return list(range(n_buf))
|
||||
stride = max(1, n_buf // num_frames)
|
||||
return [index * stride for index in range(num_frames - 1)] + [n_buf - 1]
|
||||
|
||||
@staticmethod
|
||||
def _sample_frame_indices(
|
||||
frame_buffer: list[str],
|
||||
@@ -1050,13 +1459,26 @@ class OmniStreamingVideoHandler:
|
||||
prewarmed_frames: Mapping[str, PrewarmedFrame],
|
||||
) -> list[int]:
|
||||
"""Stride-sample with the last frame, then drop known bad frames without refilling."""
|
||||
n_buf = len(frame_buffer)
|
||||
if n_buf <= num_frames:
|
||||
indices = list(range(n_buf))
|
||||
else:
|
||||
stride = max(1, n_buf // num_frames)
|
||||
indices = [index * stride for index in range(num_frames - 1)] + [n_buf - 1]
|
||||
return [index for index in indices if prewarmed_frames.get(frame_buffer[index]) is not _BAD_FRAME]
|
||||
indices = OmniStreamingVideoHandler._candidate_frame_indices(frame_buffer, num_frames)
|
||||
return [index for index in indices if _usable_prewarmed_frame(prewarmed_frames.get(frame_buffer[index]))]
|
||||
|
||||
def _select_frame_indices(
|
||||
self,
|
||||
config: StreamingVideoSessionConfig,
|
||||
frame_buffer: list[str],
|
||||
prewarmed_frames: Mapping[str, PrewarmedFrame],
|
||||
) -> list[int]:
|
||||
"""This turn's frame selection, shared by the prompt and the consumed event."""
|
||||
if self._incremental_prefill_active(config):
|
||||
# Frames are sampled at arrival time only (EVS + max_frames), so
|
||||
# the buffer already is the warmed sequence. Query-time
|
||||
# subsampling would pick a subset, which is not a prefix.
|
||||
return [
|
||||
index
|
||||
for index, frame_b64 in enumerate(frame_buffer)
|
||||
if _usable_prewarmed_frame(prewarmed_frames.get(frame_b64))
|
||||
]
|
||||
return self._sample_frame_indices(frame_buffer, config.num_frames, prewarmed_frames)
|
||||
|
||||
@staticmethod
|
||||
async def _send_frame_ack(
|
||||
|
||||
Reference in new issue
Block a user