[Model] Optimize Qwen3-TTS streaming throughput and first audio on CUDA (#8163)

Signed-off-by: Sy03 <1370724210@qq.com>
This commit is contained in:
Sy03 authored and GitHub committed 2026-09-26 22:51:04 +08:00
1 parent 8a49c65bf9
commit e1303e5067
55 files changed
+4222 -230

No files matched your search

+98
View File
@@ -0,0 +1,98 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Private NVIDIA MPS lifetime for explicitly opted-in local stage processes."""
from __future__ import annotations
import os
import shutil
import subprocess
import tempfile
from pathlib import Path
from vllm.logger import init_logger
logger = init_logger(__name__)
def physical_gpu_uuid(device: str) -> str:
"""Resolve a physical ordinal/UUID through NVML without initializing CUDA."""
from vllm.utils.import_utils import import_pynvml
nvml = import_pynvml()
nvml.nvmlInit()
try:
if device.isdigit():
handle = nvml.nvmlDeviceGetHandleByIndex(int(device))
elif device.startswith("GPU-"):
handle = nvml.nvmlDeviceGetHandleByUUID(device)
else:
raise ValueError("cuda_mps requires one physical NVIDIA GPU ordinal or GPU UUID")
uuid = nvml.nvmlDeviceGetUUID(handle)
return uuid.decode() if isinstance(uuid, bytes) else str(uuid)
finally:
nvml.nvmlShutdown()
class CudaMPSServer:
"""Own a private control socket; never stop an operator's existing daemon."""
def __init__(self, gpu_uuid: str, *, pipe_directory: str | None = None) -> None:
control = shutil.which("nvidia-cuda-mps-control")
if control is None:
raise RuntimeError("cuda_mps requires nvidia-cuda-mps-control on PATH")
self._control = control
self._directory: Path | None = None
self._closed = False
# None inherits the parent; an explicit empty stage value selects a
# private daemon even when the parent names an operator-managed one.
self.operator_pipe_directory = (
os.environ.get("CUDA_MPS_PIPE_DIRECTORY") if pipe_directory is None else pipe_directory
) or None
if self.operator_pipe_directory:
self.env = {"CUDA_MPS_PIPE_DIRECTORY": self.operator_pipe_directory, "CUDA_VISIBLE_DEVICES": gpu_uuid}
self._run(input="get_server_list\n")
logger.info("Using operator-managed MPS at %s for %s", self.operator_pipe_directory, gpu_uuid)
return
self._directory = root = Path(tempfile.mkdtemp(prefix="vllm-omni-mps-"))
(root / "pipe").mkdir()
(root / "log").mkdir()
self.env = {
"CUDA_VISIBLE_DEVICES": gpu_uuid,
"CUDA_MPS_PIPE_DIRECTORY": str(root / "pipe"),
"CUDA_MPS_LOG_DIRECTORY": str(root / "log"),
}
try:
self._run("-d")
self._run(input="get_server_list\n")
except BaseException:
# A failed/timed-out launcher may already have forked the daemon.
# Always address our private socket; keep it if cleanup also fails.
try:
self.close()
except Exception:
logger.exception("MPS startup cleanup failed; control files remain at %s", root)
raise
logger.info("Started private MPS for %s at %s", gpu_uuid, self.env["CUDA_MPS_PIPE_DIRECTORY"])
def _run(self, *args: str, input: str | None = None) -> subprocess.CompletedProcess[str]:
return subprocess.run(
[self._control, *args],
input=input,
env=os.environ | self.env,
check=True,
text=True,
capture_output=True,
timeout=15,
)
def close(self) -> None:
if self._closed:
return
if self._directory is not None:
# Keep the control socket if quit fails, so cleanup can be retried.
self._run(input="quit\n")
shutil.rmtree(self._directory)
self._directory = None
self._closed = True
+120 -8
View File
@@ -21,7 +21,7 @@ import time as _time
from collections.abc import Awaitable, Callable, Coroutine
from dataclasses import dataclass, field
from http import HTTPStatus
from typing import Any
from typing import TYPE_CHECKING, Any
import janus
import torch
@@ -34,6 +34,7 @@ from vllm.v1.engine import EngineCoreOutputs, FinishReason
from vllm.v1.engine.exceptions import EngineDeadError
from vllm.v1.metrics.stats import IterationStats
from vllm_omni.data_entry_keys import FIRST_AUDIO_KEY, FIRST_AUDIO_REQUIRED_KEY
from vllm_omni.diffusion.data import is_diffusion_request_started_output
from vllm_omni.distributed.omni_connectors.utils.config import stage_receives_chunks
from vllm_omni.engine import OmniEngineCoreRequest
@@ -66,6 +67,9 @@ from vllm_omni.metrics.stat_logger import OmniPrometheusStatLogger
from vllm_omni.metrics.utils import DIFFUSION_METRICS_ONLY_REQUEST_ID
from vllm_omni.outputs import OmniRequestOutput
if TYPE_CHECKING:
from vllm_omni.engine import OmniEngineCoreOutput
logger = init_logger(__name__)
@@ -226,6 +230,10 @@ class OrchestratorRequestState:
running_counter_registered: bool = False
request_artifact_dirs: set[str] = field(default_factory=set)
native_kv_transfer_id: str | None = None
# First-frame delivery and final-stage outputs use different channels.
upstream_first_audio: bool = False
pending_upstream_first_audio: tuple[int, OmniEngineCoreOutput] | None = None
pending_first_audio_outputs: list[tuple[int, int, Any]] = field(default_factory=list)
@dataclass
@@ -272,7 +280,7 @@ class StreamingInputState:
Fresh rather than shared: ``output_metadata`` is handed out by reference.
"""
segment = self.segments.get(stage_id)
segment = self.segments.get(stage_id) if stage_id is not None else None
return segment if segment is not None else StreamingSegmentState()
@@ -440,9 +448,13 @@ class OrchestratorBase:
# Start membership watcher if distributed mode is active.
membership_watcher: asyncio.Task[None] | None = None
if self._membership is not None:
async def cleanup_member_requests(ids: list[str]) -> None:
await self._cleanup_request_ids(ids, abort=True)
self._membership.install_unregister_handlers(
output_queue=self.output_async_queue,
cleanup_callback=lambda ids: self._cleanup_request_ids(ids, abort=True),
cleanup_callback=cleanup_member_requests,
replica_removed_callback=self._remove_stage_replica_waiting,
)
membership_watcher = self._membership.start()
@@ -528,7 +540,7 @@ class OrchestratorBase:
# process exit as EngineDeadError during teardown.
for pool in self.stage_pools:
for client in pool.clients:
if hasattr(client, "_shutting_down"):
if client is not None and hasattr(client, "_shutting_down"):
client._shutting_down = True
# Stage teardown runs once in run()'s finally after the
# orchestration loop observes _shutdown_event and exits.
@@ -786,6 +798,7 @@ class OrchestratorBase:
``_finish_raw_terminal_requests`` once routing is done.
"""
pool = self.stage_pools[stage_id]
await self._route_upstream_first_audio(stage_id, replica_id, raw_outputs)
await self._handle_kv_ready_raw_outputs(stage_id, raw_outputs)
for eco in raw_outputs.outputs:
# Emit kv_wait_s before _handle_kv_ready_raw_outputs'
@@ -800,7 +813,8 @@ class OrchestratorBase:
kv_params.get("connector_type") or "unknown",
float(kv_wait_s),
)
req_state = self.request_states.get(getattr(eco, "request_id", None))
request_id = getattr(eco, "request_id", None)
req_state = self.request_states.get(request_id) if request_id is not None else None
if req_state is None:
continue
if (
@@ -861,6 +875,97 @@ class OrchestratorBase:
)
return processed
async def _route_upstream_first_audio(self, stage_id: int, replica_id: int, raw_outputs: Any) -> None:
"""Order explicitly marked first audio ahead of a codec that skipped it.
The sender and codec run independently. Keep overtaking codec outputs,
including terminal outputs, on the request until its first PCM arrives.
Cancellation and stage errors use ordinary request cleanup.
"""
kept = []
final_output = self.stage_pools[stage_id].final_output
for eco in raw_outputs.outputs:
mm = getattr(eco, "multimodal_output", None)
is_first = isinstance(mm, dict) and bool(mm.pop(FIRST_AUDIO_KEY, False))
requires_first = isinstance(mm, dict) and bool(mm.pop(FIRST_AUDIO_REQUIRED_KEY, False))
request_id = getattr(eco, "request_id", None)
req_state = self.request_states.get(request_id) if request_id is not None else None
if is_first:
assert isinstance(mm, dict)
# Only the dedicated first-frame channel is intercepted.
if (
req_state is None
or req_state.upstream_first_audio
or req_state.pending_upstream_first_audio is not None
or stage_id + 1 > req_state.final_stage_id
):
continue
audio = mm.get("model_outputs")
if not isinstance(audio, torch.Tensor) or audio.numel() == 0:
await self._handle_stage_error(stage_id, eco, error="Invalid or empty first-audio payload")
continue
req_state.pending_upstream_first_audio = (stage_id, eco)
await self._flush_upstream_first_audio(req_state)
continue
if (
req_state is not None
and final_output
and not req_state.upstream_first_audio
and (requires_first or req_state.pending_first_audio_outputs)
and getattr(eco, "finish_reason", None) != FinishReason.ERROR
):
req_state.pending_first_audio_outputs.append((stage_id, replica_id, eco))
continue
kept.append(eco)
raw_outputs.outputs = kept
async def _flush_upstream_first_audio(self, req_state: OrchestratorRequestState) -> None:
"""Feed upstream PCM through the codec's normal output-kind contract.
The source can finish its first frame while downstream prewarm is
still selecting/registering a replica. Retain that frame until the
codec owns an output-processor state, then accumulate it before any
codec output that omitted it. This preserves FINAL_ONLY/CUMULATIVE
waveforms and downstream consumers such as forced alignment.
"""
from vllm_omni.engine import OmniEngineCoreOutputs
pending = req_state.pending_upstream_first_audio
if pending is None or self.request_states.get(req_state.request_id) is not req_state:
return
source_stage, first_output = pending
codec_stage = source_stage + 1
pool = self.stage_pools[codec_stage]
replica_id = pool.get_bound_replica_id(req_state.request_id)
if replica_id is None or req_state.request_id not in pool.output_processor.request_states:
return
req_state.pending_upstream_first_audio = None
req_state.upstream_first_audio = True
try:
processed = await pool.process_llm_raw_outputs(replica_id, OmniEngineCoreOutputs(outputs=[first_output]))
await self._handle_processed_outputs(codec_stage, replica_id, processed)
except EngineDeadError as error:
await self._handle_dead_replica(codec_stage, replica_id, error)
return
except Exception as error:
# A promised first frame must either enter the codec accumulator
# or fail its request; leaving it pending would stall completion.
logger.exception("First-audio output processing failed for %s", req_state.request_id)
await self._handle_stage_error(codec_stage, first_output, error=str(error))
return
if self.request_states.get(req_state.request_id) is not req_state:
return
ready, req_state.pending_first_audio_outputs = req_state.pending_first_audio_outputs, []
for pending_stage, pending_replica, output in ready:
if self.request_states.get(req_state.request_id) is not req_state:
break
terminal: set[str] = set()
processed = await self._process_llm_stage_outputs(
pending_stage, pending_replica, OmniEngineCoreOutputs(outputs=[output]), terminal
)
await self._handle_processed_outputs(pending_stage, pending_replica, processed)
await self._finish_raw_terminal_requests(pending_stage, pending_replica, terminal)
def _absorb_diffusion_metrics(self, stage_id: int, replica_id: int, diffusion_output: Any) -> bool:
"""Drain a diffusion output's piggybacked metrics.
@@ -1543,7 +1648,7 @@ class OrchestratorBase:
self._pd_kv_params.pop(request_id, None)
req_state = self.request_states.pop(request_id, None)
if req_state is not None:
cleanup_request_artifact_dirs(getattr(req_state, "request_artifact_dirs", ()))
cleanup_request_artifact_dirs(getattr(req_state, "request_artifact_dirs", set()))
if req_state is not None and req_state.running_counter_registered and self._running_counter is not None:
self._running_counter.decrement()
req_state.running_counter_registered = False
@@ -2201,7 +2306,7 @@ class OrchestratorBase:
)
return
diffusion_source_outputs = [output, *companion_outputs]
if next_client.custom_process_input_func is not None:
if next_client is not None and next_client.custom_process_input_func is not None:
_t_ar2d = _time.perf_counter()
_fn = next_client.custom_process_input_func
_extra_kwargs: dict[str, Any] = {}
@@ -2386,7 +2491,9 @@ class OrchestratorBase:
req_state.streaming.source_token_decoder = decode
try:
next_inputs = next_client.process_engine_inputs(
assert next_client is not None
process_inputs = getattr(next_client, "process_engine_inputs")
next_inputs = process_inputs(
source_outputs,
req_state.prompt,
streaming_context=req_state.streaming,
@@ -2637,6 +2744,11 @@ class OrchestratorBase:
req_state,
)
if req_state.pending_upstream_first_audio is not None or req_state.upstream_first_audio:
await self._flush_upstream_first_audio(req_state)
if self.request_states.get(request_id) is not req_state:
return False
# async_chunk pre-submit fires per stage edge (N-1 -> N). Source
# replica is stage 0's bound replica (single-replica thinker in
# all current configs); fall back to 0 if unknown.
@@ -79,6 +79,23 @@ def _signal_exit_code(signum: int) -> int:
return _SIGNAL_EXIT_BASE + signum
def _bind_first_audio_sink(model_executor: Any, output_queue: Any, scheduler: Any) -> bool:
"""Let a TP1 in-process runner that decodes first audio deliver it as its own output."""
if not isinstance(model_executor, UniProcExecutor):
return False
worker = getattr(getattr(model_executor, "driver_worker", None), "worker", None)
model_runner = getattr(worker, "model_runner", None)
model_state = getattr(model_runner, "model_state", None)
model = getattr(model_runner, "model", None)
if getattr(model, "first_frame_decoder", None) is None or not hasattr(model_state, "set_first_audio_sink"):
return False
from vllm_omni.worker_v2.first_audio_sender import engine_output_queue_sink
assert model_state is not None
model_state.set_first_audio_sink(engine_output_queue_sink(output_queue, scheduler))
return True
def _bind_native_data_plane_ready_sink(model_executor: Any, scheduler: Any) -> bool:
"""Bind the TP1 in-process runner control plane directly to its scheduler."""
if not isinstance(model_executor, UniProcExecutor):
@@ -107,6 +124,7 @@ class StageEngineCoreProc(EngineCoreProc):
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
_bind_first_audio_sink(self.model_executor, self.output_queue, self.scheduler)
if _bind_native_data_plane_ready_sink(self.model_executor, self.scheduler):
logger.info("Bound native MRv2 connector readiness directly to the scheduler inbox.")
+11 -8
View File
@@ -1041,14 +1041,17 @@ def stage_runtime_env(stage_id: int, runtime_cfg: Any) -> Generator[None, None,
return
previous_env: dict[str, str | None] = {}
for key, value in runtime_env.items():
env_key = str(key)
previous_env[env_key] = os.environ.get(env_key)
os.environ[env_key] = str(value)
if previous_env:
logger.info("[stage_init] Stage-%s applied runtime env keys: %s", stage_id, sorted(previous_env))
try:
for key, value in runtime_env.items():
env_key = str(key)
old_value = os.environ.get(env_key)
os.environ[env_key] = str(value)
# Track only successful writes, preserving the original value
# if distinct keys normalize to the same environment name.
previous_env.setdefault(env_key, old_value)
if previous_env:
logger.info("[stage_init] Stage-%s applied runtime env keys: %s", stage_id, sorted(previous_env))
yield
finally:
for key, old_value in previous_env.items():
@@ -1107,7 +1110,7 @@ def _project_omni_stage_engine_args(
"default_sampling_params",
"has_sampling_extra_args",
}
runtime_excluded_fields = {"devices", "num_replicas", "env", "num_gpus"}
runtime_excluded_fields = {"devices", "num_replicas", "env", "num_gpus", "cuda_mps"}
if not is_diffusion:
# These values configure OmniDiffusionConfig or its worker process;
# OmniEngineArgs has no matching fields for LLM stages.
+67 -5
View File
@@ -30,6 +30,7 @@ from vllm_omni.distributed.omni_coordinator import (
RandomBalancer,
RoundRobinBalancer,
)
from vllm_omni.engine.cuda_mps import CudaMPSServer, physical_gpu_uuid
from vllm_omni.engine.messages import (
EngineQueueMessage,
RegisterRemoteReplicaMessage,
@@ -205,6 +206,7 @@ class StageRuntime:
# device groups can initialize concurrently.
self._replica_launch_lock = threading.Lock()
self._init_visible_devices_baseline: str | None = None
self._mps_servers: dict[str, CudaMPSServer] = {}
@staticmethod
def _client_addresses_from_zmq(addresses: Any) -> dict[str, str]:
@@ -423,6 +425,8 @@ class StageRuntime:
)
)
with self._replica_launch_lock:
mps_env = self._mps_environment(physical_devices, replica.metadata.runtime_cfg)
launch_context = launch_stage_replica(
vllm_config=replica.stage_vllm_config,
executor_class=replica.executor_class,
@@ -432,7 +436,7 @@ class StageRuntime:
stage_config=replica.stage_cfg,
omni_master_server=self._get_omni_master_server(),
omni_coordinator_address=self._get_coordinator_address(),
stage_visible_devices=physical_devices,
stage_visible_devices=mps_env.get("CUDA_VISIBLE_DEVICES", physical_devices),
spawn_device_lock=self._spawn_device_lock,
omni_parallel_stage_init=self._parallel_stage_init,
num_api_servers=num_api_servers,
@@ -441,7 +445,10 @@ class StageRuntime:
# Environment overlays are process-global. Serialize spawn;
# parallel initialization waits for READY outside this lock.
with self._replica_launch_lock:
with stage_runtime_env(replica.metadata.stage_id, replica.metadata.runtime_cfg):
with (
stage_runtime_env(replica.metadata.stage_id, replica.metadata.runtime_cfg),
stage_runtime_env(replica.metadata.stage_id, {"env": mps_env}),
):
stage_resources = launch_context.__enter__()
entered_contexts.append(launch_context)
if stage_resources is None:
@@ -514,6 +521,55 @@ class StageRuntime:
if lock_fds:
release_device_locks(lock_fds)
@staticmethod
def _mps_enabled(runtime_cfg: Any) -> bool:
return bool(
runtime_cfg.get("cuda_mps", False)
if isinstance(runtime_cfg, Mapping)
else getattr(runtime_cfg, "cuda_mps", False)
)
def _validate_mps_topology(self, stage_plans: Sequence[LogicalStageInitPlan]) -> None:
for plan in stage_plans:
for replica in plan.replicas:
runtime_cfg = getattr(replica.stage_cfg, "runtime_config", getattr(replica.stage_cfg, "runtime", None))
if not self._mps_enabled(runtime_cfg):
continue
if replica.launch_mode != "local" or replica.metadata.stage_type == "diffusion":
raise ValueError("cuda_mps currently supports local EngineCore stages only")
if self._parallel_stage_init:
raise ValueError(
"cuda_mps requires parallel_stage_init=false for physical GPU initialization locks"
)
def _mps_environment(self, devices: str | None, runtime_cfg: Any) -> dict[str, str]:
if not self._mps_enabled(runtime_cfg):
return {}
if not current_omni_platform.is_cuda() or devices is None or len(devices.split(",")) != 1:
raise ValueError("cuda_mps currently requires a local CUDA stage on exactly one explicit GPU")
runtime_env = runtime_cfg.get("env") if isinstance(runtime_cfg, Mapping) else getattr(runtime_cfg, "env", None)
pipe_directory = (
str(runtime_env["CUDA_MPS_PIPE_DIRECTORY"])
if isinstance(runtime_env, Mapping) and "CUDA_MPS_PIPE_DIRECTORY" in runtime_env
else None
)
uuid = physical_gpu_uuid(devices.strip())
if uuid not in self._mps_servers:
self._mps_servers[uuid] = CudaMPSServer(uuid, pipe_directory=pipe_directory)
server = self._mps_servers[uuid]
if pipe_directory is not None and (pipe_directory or None) != server.operator_pipe_directory:
raise ValueError(f"Conflicting CUDA_MPS_PIPE_DIRECTORY settings for stages sharing GPU {uuid}")
return server.env
def _close_mps_servers(self) -> None:
for uuid, server in list(self._mps_servers.items()):
try:
server.close()
except Exception:
logger.exception("Failed to close private MPS server for %s; retaining its control directory", uuid)
else:
del self._mps_servers[uuid]
def shutdown(self) -> None:
for pool in self.stage_pools:
for client in pool.clients:
@@ -525,6 +581,7 @@ class StageRuntime:
if self._stage_init_executor is not None:
self._stage_init_executor.shutdown(wait=True, cancel_futures=True)
self._stage_init_executor = None
self._close_mps_servers()
def create_membership_controller(self) -> Any | None:
"""Return a distributed membership controller, if this runtime needs one."""
@@ -540,6 +597,7 @@ class StageRuntime:
replicas_per_stage,
replica_devices_map,
)
self._validate_mps_topology(stage_plans)
self._validate_native_kv_topology(stage_plans)
return stage_plans
@@ -557,17 +615,20 @@ class StageRuntime:
def _cleanup_after_initialize_failure(self) -> None:
"""Hook for runtimes that own extra infrastructure during init."""
return None
self._close_mps_servers()
def _resolve_replica_physical_devices(self, stage_id: int, runtime_cfg: Any) -> str | None:
if runtime_cfg is None:
runtime_cfg = {}
devices = runtime_cfg.get("devices") if hasattr(runtime_cfg, "get") else getattr(runtime_cfg, "devices", None)
return resolve_stage_physical_devices(
physical = resolve_stage_physical_devices(
stage_id,
devices,
visible_baseline=self._init_visible_devices_baseline,
)
if self._mps_enabled(runtime_cfg) and (physical is None or not physical.isdigit()):
raise ValueError("cuda_mps requires one numeric physical GPU for initialization locking")
return physical
# ---- Internal methods ----
@@ -664,7 +725,7 @@ class StageRuntime:
port = int(extra.get("bootstrap_port", 8998)) + replica_metadata.replica_id
extra["bootstrap_addr"] = f"http://{kv_config.kv_ip}:{port}"
if isinstance(replica_cfg, BaseVllmOmniStageConfig):
runtime_cfg = replica_cfg.runtime_config
runtime_cfg: Any = replica_cfg.runtime_config
runtime_cfg.env = {
**(runtime_cfg.env or {}),
"VLLM_MOONCAKE_BOOTSTRAP_PORT": str(port),
@@ -1374,6 +1435,7 @@ class DistStageRuntime(StageRuntime):
self._stage_remote_factory_contexts = self._capture_stage_factory_contexts(stage_plans)
def _cleanup_after_initialize_failure(self) -> None:
super()._cleanup_after_initialize_failure()
self._cleanup_distributed_infra()
def shutdown(self) -> None: