[Metrics] Add audio SLOs + cross-stage transfer families + per-(stage, replica) wrap for upstream vllm:* (#3576)

Signed-off-by: vraiti <vraiti@redhat.com>
Signed-off-by: LHXuuu <xulianhao.xlh@antgroup.com>
Co-authored-by: vraiti <vraiti@redhat.com>
This commit is contained in:
LHXuuuandvraiti authored and GitHub committed 2026-06-01 20:20:48 +08:00
1 parent ee33601571
commit 41a795b5d6
29 files changed
+3377 -25

No files matched your search

+14 -12
View File
@@ -7,6 +7,8 @@ from vllm.benchmarks.lib.endpoint_request_func import RequestFuncOutput
from vllm.benchmarks.serve import MILLISECONDS_TO_SECONDS_CONVERSION, TERM_PLOTLIB_AVAILABLE, BenchmarkMetrics, TaskType
from vllm.tokenizers import TokenizerLike
from vllm_omni.metrics import definitions as defs
@dataclass
class MultiModalsBenchmarkMetrics(BenchmarkMetrics):
@@ -109,17 +111,17 @@ def process_one_metric(
"tpot": "Time per Output Token (excl. 1st token)",
"itl": "Inter-token Latency",
"e2el": "End-to-end Latency",
"audio_ttfp": "Time to First Packet",
"audio_rtf": "Real Time Factor",
"audio_duration": "Audio Duration",
"audio_underrun": "Streaming Audio Underrun",
defs.AUDIO_TTFP: "Time to First Packet",
defs.AUDIO_RTF: "Real Time Factor",
defs.AUDIO_DURATION: "Audio Duration",
defs.AUDIO_UNDERRUN: "Streaming Audio Underrun",
}
header = metric_header_map.get(metric_attribute_name, metric_attribute_name)
print("{s:{c}^{n}}".format(s=header, n=50, c="-"))
is_audio_rtf = metric_attribute_name == "audio_rtf"
is_audio_duration_or_underrun = metric_attribute_name in ("audio_duration", "audio_underrun")
is_audio_rtf = metric_attribute_name == defs.AUDIO_RTF
is_audio_duration_or_underrun = metric_attribute_name in (defs.AUDIO_DURATION, defs.AUDIO_UNDERRUN)
suffix = "_ms"
unit_suffix = " (ms)"
@@ -216,12 +218,12 @@ def calculate_metrics(
all_tpots.append(tpot)
itls += outputs[i].itl
ttfts.append(outputs[i].ttft)
audio_ttfps.append(getattr(outputs[i], "audio_ttfp", 0.0))
audio_rtfs.append(getattr(outputs[i], "audio_rtf", 0.0))
audio_duration.append(getattr(outputs[i], "audio_duration", 0.0))
audio_frames.append(getattr(outputs[i], "audio_frames", 0.0))
audio_underruns.append(getattr(outputs[i], "audio_underrun_s", 0.0))
audio_continuity_ok.append(bool(getattr(outputs[i], "audio_continuity_ok", True)))
audio_ttfps.append(getattr(outputs[i], defs.AUDIO_TTFP, 0.0))
audio_rtfs.append(getattr(outputs[i], defs.AUDIO_RTF, 0.0))
audio_duration.append(getattr(outputs[i], defs.AUDIO_DURATION, 0.0))
audio_frames.append(getattr(outputs[i], defs.AUDIO_FRAMES, 0.0))
audio_underruns.append(getattr(outputs[i], f"{defs.AUDIO_UNDERRUN}_s", 0.0))
audio_continuity_ok.append(bool(getattr(outputs[i], defs.AUDIO_CONTINUITY_OK, True)))
e2els.append(outputs[i].latency)
input_audio_duration += outputs[i].input_audio_duration
completed += 1
@@ -1,16 +1,20 @@
from __future__ import annotations
import os
import time
from typing import Any
from vllm.logger import init_logger
from vllm.v1.core.sched.output import SchedulerOutput
from vllm.v1.metrics.stats import SchedulerStats
from vllm.v1.request import RequestStatus
from vllm_omni.core.sched.output import OmniChunkRecvHandle, OmniSchedulerOutput
logger = init_logger(__name__)
_STATS_INTERVAL_S = 1.0
# Upper bound on how long a request may sit in full-payload-input wait
# (the state ``OmniSchedulingCoordinator`` records via ``_waiting_since``)
# before the scheduler force-fails it. Defends against stuck consumer-side
@@ -145,3 +149,10 @@ class OmniSchedulerMixin:
finished_requests_needing_kv_transfer=finished_requests_needing_kv_transfer or {},
pending_input_registrations=pending_input_registrations,
)
def make_stats(self, *args, **kwargs) -> SchedulerStats | None:
now = time.monotonic()
if now - getattr(self, "_last_stats_time", 0.0) < _STATS_INTERVAL_S:
return None
self._last_stats_time = now
return super().make_stats(*args, **kwargs)
+26 -3
View File
@@ -110,6 +110,7 @@ from vllm_omni.entrypoints.utils import (
load_and_resolve_stage_configs,
)
from vllm_omni.inputs.data import OmniSamplingParams
from vllm_omni.metrics.prometheus import OmniRequestCounter
from vllm_omni.platforms import current_omni_platform
if TYPE_CHECKING:
@@ -259,6 +260,12 @@ class AsyncOmniEngine:
**kwargs: Additional arguments
"""
# Class-level defaults so tests that bypass __init__ via object.__new__
# don't AttributeError when stage-init / forward paths touch these attrs.
_log_stats: bool = False
_coordinator_runtime: Any = None
_transfer_emitter: Any = None
def __init__(
self,
model: str,
@@ -267,11 +274,23 @@ class AsyncOmniEngine:
init_timeout: int = 600,
diffusion_batch_size: int = 1,
single_stage_mode: bool = False,
transfer_emitter: Any = None,
log_stats: bool = False,
**kwargs: Any,
) -> None:
self.model = model
self.diffusion_batch_size = diffusion_batch_size
startup_timeout = int(init_timeout)
# Forwarded into Orchestrator so its _forward_to_next_stage path can
# emit per-edge transfer_tx_s / transfer_size_bytes histograms.
# Optional: when None, Orchestrator silently skips TX emit (existing
# RX path still works via OrchestratorAggregator).
self._transfer_emitter = transfer_emitter
# Drives upstream EngineCore + scheduler stats production. When False
# the engine skips SchedulerStats / IterationStats; the per-(stage,
# replica) vllm:* wrap stays registered but reads zero. Respects the
# --log-stats CLI flag set by the user via OmniBase.
self._log_stats = log_stats
logger.info(f"[AsyncOmniEngine] Initializing with model {model}")
@@ -357,6 +376,7 @@ class AsyncOmniEngine:
self._stage_init_executor: concurrent.futures.ThreadPoolExecutor | None = None
self._weak_finalizer: weakref.finalize | None = None
self._rpc_lock = threading.Lock()
self._running_counter = OmniRequestCounter()
logger.info(f"[AsyncOmniEngine] Launching Orchestrator thread with {self.num_stages} stages")
@@ -905,7 +925,7 @@ class AsyncOmniEngine:
launch_omni_core_engines(
vllm_config=vllm_config,
executor_class=executor_class,
log_stats=False,
log_stats=self._log_stats,
omni_master_server=self._omni_master_server,
stage_id=plan.metadata.stage_id,
stage_config=stage_cfg,
@@ -917,7 +937,7 @@ class AsyncOmniEngine:
addresses, proc, handshake_address = spawn_stage_core(
vllm_config=vllm_config,
executor_class=executor_class,
log_stats=False,
log_stats=self._log_stats,
)
logger.info(
"[AsyncOmniEngine] Stage %s engine launch started",
@@ -1229,7 +1249,7 @@ class AsyncOmniEngine:
if plan.replicas[0].metadata.stage_type != "diffusion":
stage_vllm_config = plan.replicas[0].stage_vllm_config
assert stage_vllm_config is not None
output_processor = build_llm_stage_output_processor(plan, stage_vllm_config)
output_processor = build_llm_stage_output_processor(plan, stage_vllm_config, log_stats=self._log_stats)
stage_pools.append(
StagePool(
@@ -1374,9 +1394,12 @@ class AsyncOmniEngine:
stage_pools=self.stage_pools,
async_chunk=self.async_chunk,
pd_config=pd_config,
running_counter=self._running_counter,
coordinator_pub_address=coordinator_pub_address,
load_balancer_factory=load_balancer_factory,
remote_replica_factory=remote_replica_factory,
transfer_emitter=self._transfer_emitter,
log_stats=self._log_stats,
)
if not startup_future.done():
startup_future.set_result(asyncio.get_running_loop())
+2
View File
@@ -80,6 +80,7 @@ class OutputMessage(EngineQueueMessage, kw_only=True):
type: Literal["output"] = "output"
request_id: str
stage_id: int
replica_id: int | None = None
engine_outputs: OmniRequestOutput
metrics: StageRequestMetrics | None = None
finished: bool
@@ -90,6 +91,7 @@ class StageMetricsMessage(EngineQueueMessage, kw_only=True):
type: Literal["stage_metrics"] = "stage_metrics"
request_id: str
stage_id: int
replica_id: int | None = None
metrics: StageRequestMetrics
stage_submit_ts: float | None = None
+186 -3
View File
@@ -29,6 +29,7 @@ from vllm.pooling_params import PoolingParams
from vllm.sampling_params import SamplingParams
from vllm.v1.engine import EngineCoreOutputs
from vllm.v1.engine.exceptions import EngineDeadError
from vllm.v1.metrics.stats import IterationStats
from vllm_omni.distributed.omni_coordinator import (
LoadBalancer,
@@ -54,6 +55,8 @@ from vllm_omni.engine.messages import (
)
from vllm_omni.engine.serialization import serialize_additional_information
from vllm_omni.engine.stage_pool import StagePool
from vllm_omni.metrics.prometheus import OmniRequestCounter
from vllm_omni.metrics.stat_logger import OmniPrometheusStatLogger
from vllm_omni.outputs import OmniRequestOutput
# Factory signature for building a head-side stage client for a
@@ -155,6 +158,12 @@ class Orchestrator:
_WATCH_REPLICA_INTERVAL_S: float = 0.5
_WATCH_REPLICA_IDLE_INTERVAL_S: float = 1.0
# Class-level defaults so tests that bypass __init__ via object.__new__
# don't AttributeError when transfer / counter emit paths access them.
_running_counter: OmniRequestCounter | None = None
_transfer_emitter: Any = None
_stat_logger: OmniPrometheusStatLogger | None = None
def __init__(
self,
request_async_queue: janus.AsyncQueue[EngineQueueMessage],
@@ -164,9 +173,12 @@ class Orchestrator:
*,
async_chunk: bool = False,
pd_config: dict[str, Any] | None = None,
running_counter: OmniRequestCounter | None = None,
coordinator_pub_address: str | None = None,
load_balancer_factory: Callable[[], LoadBalancer] | None = None,
remote_replica_factory: RemoteReplicaFactory | None = None,
transfer_emitter: Any = None,
log_stats: bool = False,
) -> None:
self.request_async_queue = request_async_queue
self.output_async_queue = output_async_queue
@@ -186,6 +198,8 @@ class Orchestrator:
self._pd_bootstrap_addr = pd_config.get("bootstrap_addr")
self._pd_prefill_engine_id = pd_config.get("prefill_engine_id")
self.request_states: dict[str, OrchestratorRequestState] = {}
self._init_metrics_state(stage_pools, running_counter, transfer_emitter, log_stats=log_stats)
self._cfg_tracker = CfgCompanionTracker()
self._shutdown_event = asyncio.Event()
@@ -215,6 +229,71 @@ class Orchestrator:
pool.attach_hub(self._hub)
pool.attach_load_balancer(factory())
def _init_metrics_state(
self,
stage_pools: list[StagePool],
running_counter: OmniRequestCounter | None,
transfer_emitter: Any,
log_stats: bool = False,
) -> None:
"""Wire up all metric-related orchestrator state.
Sets ``self._running_counter`` and ``self._transfer_emitter``
(both optional, used by request-add / forward paths), builds the
``(stage_id, replica_id) ↔ engine_idx`` lookup used at record() time,
and best-effort constructs the ``OmniPrometheusStatLogger`` wrap
that exposes ~37 upstream ``vllm:*`` families with per-(stage,
replica) labels. Failure to build the wrap is logged and metrics
are simply disabled — orchestrator construction continues so unit
tests with a minimal ``vllm_config`` still pass.
``log_stats=False`` short-circuits the wrap entirely so the
~65 upstream ``vllm:*`` families are not registered in the
Prometheus default registry at all. The per-step record() path
already no-ops on ``scheduler_stats is None`` (which is what
the upstream scheduler returns when its own log_stats is False),
so this gate is mainly to keep the ``/metrics`` surface clean
when the user did not request stats.
"""
self._running_counter = running_counter
self._transfer_emitter = transfer_emitter
# Flat engine_idx ↔ (stage, replica) maps. The reverse map is
# consulted at record() time to translate the orchestrator's
# (stage_id, replica_id) loop variables into an engine_idx the
# underlying PrometheusStatLogger can address.
stage_replica_map: dict[int, tuple[str, str]] = {}
self._stage_replica_to_engine_idx: dict[tuple[int, int], int] = {}
flat_idx = 0
for stage_id, pool in enumerate(stage_pools):
for replica_id in range(pool.num_replicas):
stage_replica_map[flat_idx] = (str(stage_id), str(replica_id))
self._stage_replica_to_engine_idx[(stage_id, replica_id)] = flat_idx
flat_idx += 1
if not log_stats:
self._stat_logger = None
return
vllm_config_for_stats = next(
(p.stage_vllm_config for p in stage_pools if p.stage_vllm_config is not None),
None,
)
if vllm_config_for_stats is None:
self._stat_logger = None
return
try:
self._stat_logger = OmniPrometheusStatLogger(
vllm_config=vllm_config_for_stats,
stage_replica_map=stage_replica_map,
)
except Exception:
# Minimal vllm_config in unit-test contexts can lack fields the
# upstream PrometheusStatLogger expects. Skip wrap rather than
# break orchestrator construction.
logger.exception("[Orchestrator] OmniPrometheusStatLogger init failed; metrics wrap disabled")
self._stat_logger = None
async def run(self) -> None:
"""Main entry point for the Orchestrator event loop."""
logger.info("[Orchestrator] Starting event loop")
@@ -393,6 +472,8 @@ class Orchestrator:
mm_features=getattr(prompt, "mm_features", None),
)
self.request_states[request_id] = req_state
if self._running_counter is not None:
self._running_counter.increment()
req_state.streaming.enabled = bool(getattr(prompt, "resumable", False))
req_state.stage_submit_ts[stage_id] = _time.time()
enqueue_ts = msg.enqueue_ts
@@ -603,7 +684,24 @@ class Orchestrator:
"new_prompt_len_snapshot",
None,
)
raw_output = await pool.process_llm_raw_outputs(replica_id, raw_outputs)
# OmniSchedulerMixin.make_stats() already throttles
# per-scheduler at 1 Hz, so raw_outputs.scheduler_stats
# being non-None means this replica passed its own gate.
# A second global throttle here would drop stats for
# other (stage, replica) pairs in the same 1s window.
record_stats = self._stat_logger is not None and raw_outputs.scheduler_stats is not None
iteration_stats = IterationStats() if record_stats else None
raw_output = await pool.process_llm_raw_outputs(
replica_id,
raw_outputs,
iteration_stats=iteration_stats,
)
if record_stats:
self._stat_logger.record(
raw_outputs.scheduler_stats,
iteration_stats,
engine_idx=self._stage_replica_to_engine_idx[(stage_id, replica_id)],
)
except asyncio.CancelledError:
raise
except EngineDeadError as e:
@@ -681,7 +779,7 @@ class Orchestrator:
)
stage_metrics.pipeline_timings = dict(req_state.pipeline_timings)
await self._route_output(stage_id, output, req_state, stage_metrics)
await self._route_output(stage_id, replica_id, output, req_state, stage_metrics)
async def _handle_stage_error(self, stage_id: int, output: Any) -> None:
"""Emit a frontend-visible error and clean up request state."""
@@ -713,7 +811,8 @@ class Orchestrator:
self._release_request_bindings(request_ids)
for request_id in request_ids:
self._pd_kv_params.pop(request_id, None)
self.request_states.pop(request_id, None)
if self.request_states.pop(request_id, None) is not None and self._running_counter is not None:
self._running_counter.decrement()
def _maybe_clone_diffusion_params_for_cfg(self, request_id: str, params: Any) -> Any:
"""Attach CFG companion ids to diffusion sampling params when needed."""
@@ -735,6 +834,7 @@ class Orchestrator:
async def _route_output(
self,
stage_id: int,
replica_id: int,
output: Any,
req_state: OrchestratorRequestState,
stage_metrics: Any,
@@ -757,6 +857,7 @@ class Orchestrator:
OutputMessage(
request_id=req_id,
stage_id=stage_id,
replica_id=replica_id,
engine_outputs=output,
metrics=stage_metrics,
finished=finished and stage_id == req_state.final_stage_id,
@@ -768,6 +869,7 @@ class Orchestrator:
StageMetricsMessage(
request_id=req_id,
stage_id=stage_id,
replica_id=replica_id,
metrics=stage_metrics,
stage_submit_ts=submit_ts,
)
@@ -797,6 +899,7 @@ class Orchestrator:
stage_id,
output,
req_state,
src_replica_id=replica_id,
is_streaming_session=req_state.streaming.enabled,
is_final_update=False,
)
@@ -807,6 +910,7 @@ class Orchestrator:
stage_id,
output,
req_state,
src_replica_id=replica_id,
is_streaming_session=True,
is_final_update=True,
)
@@ -918,6 +1022,41 @@ class Orchestrator:
)
return sp
def _emit_tx_edge(
self,
*,
from_stage: int,
from_replica: int,
to_stage: int,
to_pool: StagePool,
request_id: str,
tx_ms: float,
) -> None:
"""Emit per-edge transfer_tx_s + transfer_size_bytes histograms.
``tx_ms`` is the orchestrator-side wall-clock spent in ``next_pool.
submit_*`` (serialize + queue submit to the receiving worker). Best-
effort size_bytes left at 0 — orchestrator doesn't have a cheap handle
on the serialized payload size; a follow-up can plumb that from the
connector adapter.
"""
if self._transfer_emitter is None:
return
to_replica = to_pool.get_bound_replica_id(request_id)
if to_replica is None:
return
try:
self._transfer_emitter.observe_size(from_stage, from_replica, to_stage, to_replica, 0)
self._transfer_emitter.observe_tx_time(from_stage, from_replica, to_stage, to_replica, tx_ms / 1000.0)
except Exception:
logger.debug(
"[Orchestrator] transfer_tx emit failed for edge %d->%d req=%s",
from_stage,
to_stage,
request_id,
exc_info=True,
)
async def _forward_to_next_stage(
self,
req_id: str,
@@ -925,6 +1064,7 @@ class Orchestrator:
output: Any,
req_state: OrchestratorRequestState,
*,
src_replica_id: int | None = None,
is_streaming_session: bool = False,
is_final_update: bool = False,
) -> None:
@@ -937,6 +1077,7 @@ class Orchestrator:
next_stage_resumable = is_streaming_session and not is_final_update
already_submitted = self._next_stage_already_submitted(src_stage_id, req_state)
requires_multimodal_data = getattr(next_client, "requires_multimodal_data", False)
_t_submit_start = _time.perf_counter()
if next_pool.stage_type == "diffusion":
companion_outputs = self._cfg_tracker.pop_companion_outputs(req_id)
@@ -1024,6 +1165,15 @@ class Orchestrator:
params_override=self._maybe_clone_diffusion_params_for_cfg(req_id, params),
)
req_state.stage_submit_ts[next_logical] = _time.time()
_tx_ms = (_time.perf_counter() - _t_submit_start) * 1000.0
self._emit_tx_edge(
from_stage=src_stage_id,
from_replica=src_replica_id if src_replica_id is not None else 0,
to_stage=next_logical,
to_pool=next_pool,
request_id=req_id,
tx_ms=_tx_ms,
)
return
# PD disaggregation: prefill → decode routing uses original prompt + KV transfer params
@@ -1063,6 +1213,15 @@ class Orchestrator:
await next_pool.submit_initial(req_id, req_state, request, prompt_text=None)
req_state.stage_submit_ts[next_logical] = _time.time()
_tx_ms = (_time.perf_counter() - _t_submit_start) * 1000.0
self._emit_tx_edge(
from_stage=src_stage_id,
from_replica=src_replica_id if src_replica_id is not None else 0,
to_stage=next_logical,
to_pool=next_pool,
request_id=req_id,
tx_ms=_tx_ms,
)
return
if req_state.pd_prefill_multimodal_output is not None:
@@ -1107,6 +1266,15 @@ class Orchestrator:
await next_pool.submit_initial(req_id, req_state, request, prompt_text=None)
req_state.stage_submit_ts[next_logical] = _time.time()
_tx_ms = (_time.perf_counter() - _t_submit_start) * 1000.0
self._emit_tx_edge(
from_stage=src_stage_id,
from_replica=src_replica_id if src_replica_id is not None else 0,
to_stage=next_logical,
to_pool=next_pool,
request_id=req_id,
tx_ms=_tx_ms,
)
async def _prewarm_async_chunk_stages(
self,
@@ -1131,6 +1299,7 @@ class Orchestrator:
params = req_state.sampling_params_list[next_stage_id]
req_state.stage_submit_ts[next_stage_id] = _time.time()
_t_submit_start = _time.perf_counter()
if next_pool.stage_type == "diffusion":
await next_pool.submit_initial(
@@ -1174,6 +1343,20 @@ class Orchestrator:
request.external_req_id = request.request_id
await next_pool.submit_initial(request_id, req_state, request, prompt_text=None)
# 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.
_tx_ms = (_time.perf_counter() - _t_submit_start) * 1000.0
src_replica = self.stage_pools[next_stage_id - 1].get_bound_replica_id(request_id)
self._emit_tx_edge(
from_stage=next_stage_id - 1,
from_replica=src_replica if src_replica is not None else 0,
to_stage=next_stage_id,
to_pool=next_pool,
request_id=request_id,
tx_ms=_tx_ms,
)
def _build_kv_sender_info(
self,
sender_stage_ids: list[int],
+13 -3
View File
@@ -831,8 +831,18 @@ def build_vllm_config(
return vllm_config, executor_class
def build_llm_stage_output_processor(plan: LogicalStageInitPlan, stage_vllm_config: Any) -> Any | None:
"""Build one output processor per logical LLM stage."""
def build_llm_stage_output_processor(
plan: LogicalStageInitPlan,
stage_vllm_config: Any,
log_stats: bool = False,
) -> Any | None:
"""Build one output processor per logical LLM stage.
``log_stats`` controls whether the processor populates per-request
IterationStats (consumed by the Prometheus wrap). Default False matches
the upstream MultimodalOutputProcessor default and respects the
--log-stats CLI flag plumbed through AsyncOmniEngine.
"""
metadata = plan.replicas[0].metadata
if stage_vllm_config.model_config.skip_tokenizer_init:
@@ -843,7 +853,7 @@ def build_llm_stage_output_processor(plan: LogicalStageInitPlan, stage_vllm_conf
)
return MultimodalOutputProcessor(
tokenizer=tokenizer,
log_stats=False,
log_stats=log_stats,
engine_core_output_type=metadata.engine_output_type,
)
+4 -1
View File
@@ -9,6 +9,7 @@ from typing import TYPE_CHECKING, Any, cast
from vllm.logger import init_logger
from vllm.v1.engine import EngineCoreOutputs
from vllm.v1.metrics.stats import IterationStats
from vllm_omni.distributed.omni_coordinator import (
LoadBalancer,
@@ -510,6 +511,7 @@ class StagePool:
stage_gen_time_ms=stage_gen_time_ms,
batch_id=batch_id,
batch_size=1,
replica_id=replica_id,
rx_decode_time_ms=0.0,
rx_transfer_bytes=0,
rx_in_flight_time_ms=0.0,
@@ -648,6 +650,7 @@ class StagePool:
self,
replica_id: int,
raw_outputs: EngineCoreOutputs,
iteration_stats: IterationStats | None = None,
) -> list[Any]:
"""Run the shared LLM output processor on one raw poll result."""
raw_client = self.clients[replica_id]
@@ -658,7 +661,7 @@ class StagePool:
processed = processor.process_outputs(
raw_outputs.outputs,
raw_outputs.timestamp,
None,
iteration_stats,
)
if processed.reqs_to_abort:
+19
View File
@@ -160,6 +160,20 @@ class AsyncOmni(EngineClient, OmniBase):
renderer = renderer_from_config(vllm_config)
self.io_processor = get_io_processor(vllm_config, renderer, io_processor_plugin)
def _resolve_transfer_replica(self, stage_id: int, request_id: str) -> int | None:
"""Look up the sticky-routed replica for (stage_id, request_id).
Used as the ``replica_resolver`` callback by ``OrchestratorAggregator``
to label transfer_* metrics without plumbing replica ids through
``TransferEdgeStats`` / ``StageRequestStats`` / connector adapters.
Returns None when stage_id is out of range or the request hasn't been
bound to a replica yet — the metric emit then defensive-skips.
"""
pools = getattr(self.engine, "stage_pools", None)
if pools is None or not (0 <= stage_id < len(pools)):
return None
return pools[stage_id].get_bound_replica_id(request_id)
def _get_comprehension_stage_index(self) -> int | None:
fallback_idx: int | None = None
for idx, stage_client in enumerate(self.engine.stage_clients):
@@ -331,6 +345,8 @@ class AsyncOmni(EngineClient, OmniBase):
self.log_stats,
wall_start_ts,
final_stage_id_for_e2e,
transfer_emitter=getattr(self, "transfer_metrics", None),
replica_resolver=self._resolve_transfer_replica,
)
req_state = ClientRequestState(
@@ -338,6 +354,7 @@ class AsyncOmni(EngineClient, OmniBase):
external_request_id=external_request_id,
)
req_state.metrics = metrics
req_state.request_arrival_ts = wall_start_ts
self.request_states[request_id] = req_state
# PD disaggregation: modify prefill-stage sampling params per request
@@ -387,10 +404,12 @@ class AsyncOmni(EngineClient, OmniBase):
except (asyncio.CancelledError, GeneratorExit):
if input_stream_task is not None and not input_stream_task.done():
input_stream_task.cancel()
self._fire_failure_counter_if_alive(request_id)
await self._abort_internal_requests(request_id)
logger.info(f"[AsyncOmni] Request {request_id} aborted.")
raise
except Exception as e:
self._fire_failure_counter_if_alive(request_id)
await self._abort_internal_requests(request_id)
logger.info(f"[AsyncOmni] Request {request_id} failed (input error): {e}")
raise
@@ -17,3 +17,23 @@ class ClientRequestState:
self.stage_id: int | None = None
self.queue = queue if queue is not None else asyncio.Queue()
self.metrics: OrchestratorAggregator | None = None
# Wall-clock time at which the user's request arrived in the engine
# entrypoint. Set in async_omni.generate() before the orchestrator
# accepts the request. Used as the t0 anchor for audio_ttfp.
self.request_arrival_ts: float = 0.0
# Wall-clock time at which the first audio packet was observed for
# this request. None means the streaming hook hasn't fired yet.
# Used as the once-per-request guard for audio_ttfp_s emit.
self.first_audio_ts: float | None = None
# Per-chunk timeline (seconds since request_arrival_ts) and PCM byte
# counts for the audio streaming response. Populated by the streaming
# endpoint on every audio.chunk emit; consumed at request finalize to
# compute audio_underrun_s and audio_continuity_ok_total.
self.audio_chunk_arrivals_s: list[float] = []
self.audio_chunk_bytes: list[int] = []
self.audio_sample_rate: int | None = None
# Stage / replica that produced the audio packets — captured at the
# first-packet hook so the finalize-time emit can label correctly
# without re-querying stage_pools.
self.audio_emit_stage_id: int | None = None
self.audio_emit_replica_id: int | None = None
+73 -1
View File
@@ -23,7 +23,10 @@ from vllm_omni.engine.messages import (
from vllm_omni.entrypoints.client_request_state import ClientRequestState
from vllm_omni.entrypoints.pd_utils import PDDisaggregationMixin
from vllm_omni.entrypoints.utils import coerce_param_message_types, get_final_stage_id_for_e2e
from vllm_omni.metrics.modality import OmniModalityMetrics, observe_modality_at_finalize
from vllm_omni.metrics.prometheus import OmniPrometheusMetrics
from vllm_omni.metrics.stats import OrchestratorAggregator as OrchestratorMetrics
from vllm_omni.metrics.transfer import OmniTransferMetrics
from vllm_omni.model_executor.model_loader.weight_utils import download_weights_from_hf_specific
from vllm_omni.outputs import OmniRequestOutput
@@ -170,6 +173,10 @@ class OmniBase(PDDisaggregationMixin):
self.tts_batch_max_items: int = kwargs.pop("tts_batch_max_items", 32)
logger.info("[%s] Initializing with model %s", self.__class__.__name__, model)
# Construct transfer_metrics first so we can hand it to AsyncOmniEngine
# (which forwards it to the Orchestrator background thread for
# TX-side emit; see Orchestrator._forward_to_next_stage).
self.transfer_metrics = OmniTransferMetrics(model_name=model, log_stats=log_stats)
st = time.time()
self.engine = AsyncOmniEngine(
model=model,
@@ -177,6 +184,8 @@ class OmniBase(PDDisaggregationMixin):
init_timeout=init_timeout,
stage_init_timeout=stage_init_timeout,
diffusion_batch_size=diffusion_batch_size,
transfer_emitter=self.transfer_metrics,
log_stats=log_stats,
**kwargs,
)
self._shutdown_called = False
@@ -190,6 +199,8 @@ class OmniBase(PDDisaggregationMixin):
self.async_chunk = bool(getattr(self.engine, "async_chunk", False))
self.request_states: dict[str, ClientRequestState] = {}
self.prom_metrics = OmniPrometheusMetrics(model_name=model, log_stats=log_stats)
self.mod_metrics = OmniModalityMetrics(model_name=model, log_stats=log_stats)
self.default_sampling_params_list = self.engine.default_sampling_params_list
if not self.output_modalities:
@@ -272,11 +283,29 @@ class OmniBase(PDDisaggregationMixin):
raise ValueError(f"Expected {self.num_stages} sampling params, got {len(normalized)}")
return normalized
def _fire_failure_counter_if_alive(self, request_id: str) -> None:
"""Fire the abort/exception bucket of requests_success_total.
Called from cancel / exception paths in async_omni.generate() BEFORE
_abort_internal_requests pops request_states — that method resolves
the internal id by dict lookup, so popping first would no-op it. We
keep this counter fire separate from _log_summary_and_cleanup (which
pops) so the abort path can still find the state to clean up.
"""
req_state = self.request_states.get(request_id)
prom = getattr(self, "prom_metrics", None)
if req_state is None or req_state.metrics is None or prom is None:
return
if str(request_id) not in req_state.metrics.e2e_done:
prom.request_failed()
def _log_summary_and_cleanup(self, request_id: str) -> None:
req_state = self.request_states.get(request_id)
try:
if req_state is None or req_state.metrics is None:
return
if str(request_id) not in req_state.metrics.e2e_done:
self.prom_metrics.request_failed()
if self.log_stats:
# Emit per-request orchestrator timing (including e2e_total_ms)
# before dropping request state.
@@ -289,6 +318,16 @@ class OmniBase(PDDisaggregationMixin):
)
finally:
self.request_states.pop(request_id, None)
# Republish gauges so any stale value left by the per-stage
# publish in _process_single_result (which runs while the request
# is still in self.request_states) is corrected after the pop.
prom = getattr(self, "prom_metrics", None)
counter = getattr(getattr(self, "engine", None), "_running_counter", None)
if prom is not None:
total = len(self.request_states)
running = counter.value if counter is not None else total
prom.set_running(running)
prom.set_waiting(max(0, total - running))
def _compute_final_stage_id(self, output_modalities: list[str] | None) -> int:
return get_final_stage_id_for_e2e(
@@ -435,6 +474,8 @@ class OmniBase(PDDisaggregationMixin):
if not stage_meta.final_output:
return None
output_type = getattr(engine_outputs, "final_output_type", stage_meta.final_output_type)
try:
rid_key = str(req_id)
if stage_id == final_stage_id_for_e2e and rid_key not in metrics.e2e_done and finished:
@@ -443,10 +484,41 @@ class OmniBase(PDDisaggregationMixin):
req_id,
req_start_ts.get(req_id, wall_start_ts),
)
e2e_seconds = now - req_start_ts.get(req_id, wall_start_ts)
# Extract finished_reason from upstream CompletionOutput so
# the per-reason completion Counter is labelled correctly.
completion_outputs = getattr(engine_outputs, "outputs", None) or []
fr = (getattr(completion_outputs[0], "finish_reason", None) if completion_outputs else None) or "stop"
self.prom_metrics.request_succeeded(
e2e_seconds,
finished_reason=fr,
)
# Modality observe inside the same finalize guard so it fires
# once per request and inherits the try/except isolation.
observe_modality_at_finalize(
self.mod_metrics,
output_type=output_type,
stage_id=stage_id,
replica_id=result.replica_id,
stage_metrics=_m,
engine_outputs=engine_outputs,
)
except Exception:
logger.exception("[%s] Finalize request handling error", self.__class__.__name__)
output_type = getattr(engine_outputs, "final_output_type", stage_meta.final_output_type)
# When this result finalizes the request, the orchestrator has
# already decremented _running_counter but _log_summary_and_cleanup
# hasn't popped self.request_states yet — exclude the finalizing
# request from `total` so waiting doesn't read 1 and stay stuck
# there until the next request arrives.
counter = getattr(self.engine, "_running_counter", None)
is_finalizing = finished and stage_id == final_stage_id_for_e2e
total = max(0, len(self.request_states) - (1 if is_finalizing else 0))
running = counter.value if counter is not None else total
self.prom_metrics.set_running(running)
self.prom_metrics.set_waiting(max(0, total - running))
images = getattr(engine_outputs, "images", []) if output_type == "image" else []
return OmniRequestOutput(
request_id=req_id or "",
@@ -20,6 +20,11 @@ from vllm_omni.entrypoints.async_omni import AsyncOmni
from vllm_omni.entrypoints.openai.protocol.chat_completion import OmniChatCompletionResponse
from vllm_omni.entrypoints.utils import coerce_param_message_types
from vllm_omni.inputs.data import OmniDiffusionSamplingParams, OmniTextPrompt
from vllm_omni.metrics import definitions as _metric_defs
from vllm_omni.metrics.modality import (
observe_audio_first_packet,
observe_audio_streaming_finalize,
)
try:
import soundfile
@@ -110,6 +115,7 @@ from vllm_omni.entrypoints.openai.utils import (
)
from vllm_omni.lora.request import LoRARequest
from vllm_omni.outputs import OmniRequestOutput
from vllm_omni.utils.audio import audio_chunk_pcm_bytes, audio_chunk_sample_rate
logger = init_logger(__name__)
@@ -1032,6 +1038,11 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
include_usage, include_continuous_usage = should_include_usage(stream_options, self.enable_force_include_usage)
last_metrics: dict[str, Any] | None = None
# Hold a strong reference to the audio request state so the
# streaming-finalize hook below survives the inner generator's
# _log_summary_and_cleanup, which pops request_states[request_id]
# before this outer block runs.
req_state_audio_ref: Any = None
try:
async for omni_res in result_generator:
final_output_type = omni_res.final_output_type
@@ -1605,8 +1616,53 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
yield f"data: {data}\n\n"
elif final_output_type == "audio":
# Observe audio_ttfp_s on first audio packet for this request_id
# (once-per-request guard via first_audio_ts). The same hook
# also captures (stage, replica) for the streaming-continuity
# emit at request finalize. self.engine_client.request_states
# is keyed by the internal UUID-suffixed id (set by
# AsyncOmni.generate via _get_unique_request_id), but the
# `request_id` we have here is the external (user-visible) id,
# so resolve via the external_request_id field.
req_state = next(
(s for s in self.engine_client.request_states.values() if s.external_request_id == request_id),
None,
)
if req_state is not None and req_state_audio_ref is None:
req_state_audio_ref = req_state
now_ts = time.time()
if req_state is not None and req_state.first_audio_ts is None:
req_state.first_audio_ts = now_ts
stage_pools = getattr(self.engine_client.engine, "stage_pools", None)
# The orchestrator binds requests by their internal id,
# not the user-visible external id, so look up the
# replica with req_state.request_id (internal).
replica_id = (
stage_pools[omni_res.stage_id].get_bound_replica_id(req_state.request_id)
if stage_pools is not None and 0 <= omni_res.stage_id < len(stage_pools)
else None
)
req_state.audio_emit_stage_id = omni_res.stage_id
req_state.audio_emit_replica_id = replica_id
observe_audio_first_packet(
self.engine_client.mod_metrics,
stage_id=omni_res.stage_id,
replica_id=replica_id,
arrival_ts=req_state.request_arrival_ts,
now_ts=now_ts,
)
role = self.get_chat_request_role(request)
choices_data = self._create_audio_choice(omni_res, role, request, stream=True)
# Record per-chunk PCM byte count + arrival timestamp for
# audio_underrun_s / audio_continuity_ok_total at finalize.
if req_state is not None and req_state.request_arrival_ts > 0:
chunk_bytes = audio_chunk_pcm_bytes(omni_res)
if chunk_bytes > 0:
req_state.audio_chunk_arrivals_s.append(max(now_ts - req_state.request_arrival_ts, 0.0))
req_state.audio_chunk_bytes.append(chunk_bytes)
if req_state.audio_sample_rate is None:
req_state.audio_sample_rate = audio_chunk_sample_rate(omni_res)
chunk = OmniChatCompletionStreamResponse(
id=request_id,
object=chunk_object_type,
@@ -1627,6 +1683,24 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
logger.warning(f"Unsupported streaming final output type: {final_output_type}")
continue
# Emit audio_underrun_s + audio_continuity_ok_total once per
# request after the audio chunk stream is exhausted. The
# captured reference (req_state_audio_ref) outlives the inner
# _log_summary_and_cleanup that pops request_states[request_id].
if (
req_state_audio_ref is not None
and req_state_audio_ref.audio_chunk_arrivals_s
and req_state_audio_ref.audio_emit_replica_id is not None
):
observe_audio_streaming_finalize(
self.engine_client.mod_metrics,
stage_id=req_state_audio_ref.audio_emit_stage_id or 0,
replica_id=req_state_audio_ref.audio_emit_replica_id,
chunk_arrival_times_s=req_state_audio_ref.audio_chunk_arrivals_s,
chunk_bytes=req_state_audio_ref.audio_chunk_bytes,
sample_rate=(req_state_audio_ref.audio_sample_rate or _metric_defs.DEFAULT_AUDIO_SAMPLE_RATE),
)
# once the final token is handled, if stream_options.include_usage
# is sent, send the usage
if include_usage:
+3
View File
@@ -1,7 +1,10 @@
from .prometheus import OmniPrometheusMetrics, OmniRequestCounter
from .stats import OrchestratorAggregator, StageRequestStats, StageStats
from .utils import count_tokens_from_outputs
__all__ = [
"OmniPrometheusMetrics",
"OmniRequestCounter",
"OrchestratorAggregator",
"StageStats",
"StageRequestStats",
+221
View File
@@ -0,0 +1,221 @@
"""Single source of truth for vLLM-Omni Prometheus + bench CLI metric naming.
Consumed by:
- vllm_omni.metrics.prometheus (server-side /metrics pipeline families)
- vllm_omni.metrics.modality (audio families)
- vllm_omni.metrics.transfer (cross-stage transfer families)
- vllm_omni.benchmarks.metrics.metrics (bench CLI MultiModalsBenchmarkMetrics)
Naming conventions for the ``vllm_omni:*`` families exposed here:
time-bearing metrics use the ``_s`` suffix (values in seconds), counters use
``_total`` (auto-suffixed by the prometheus client), sizes use ``_bytes``.
"""
# vllm:omni_ avoids upstream's unregister_vllm_metrics() stripping, which
# removes every collector whose ``_name`` does not start with ``vllm``.
METRIC_PREFIX = "vllm:omni_"
# ============================================================================
# Bench-side stems (also used as RequestFuncOutput attribute names)
# ============================================================================
AUDIO_TTFP = "audio_ttfp"
AUDIO_DURATION = "audio_duration"
AUDIO_RTF = "audio_rtf"
AUDIO_FRAMES = "audio_frames"
AUDIO_UNDERRUN = "audio_underrun"
AUDIO_CONTINUITY_OK = "audio_continuity_ok"
AUDIO_SKIPPED_REQUESTS = "audio_skipped_requests"
# ============================================================================
# Pipeline-level metric families (request counts + e2e latency)
# ============================================================================
NUM_REQUESTS_RUNNING = METRIC_PREFIX + "num_requests_running"
NUM_REQUESTS_WAITING = METRIC_PREFIX + "num_requests_waiting"
E2E_REQUEST_LATENCY_S = METRIC_PREFIX + "e2e_request_latency_s"
# Per-finished_reason Counter; finished_reason ∈ {stop, length, abort, ...}.
# Aborts include client disconnect / cancellation paths. Counter auto-suffixes
# ``_total`` at exposition time.
REQUESTS_SUCCESS = METRIC_PREFIX + "requests_success"
# ============================================================================
# Audio family (per-stage + per-replica audio path metrics)
# ============================================================================
AUDIO_TTFP_S = METRIC_PREFIX + AUDIO_TTFP + "_s"
AUDIO_DURATION_S = METRIC_PREFIX + AUDIO_DURATION + "_s"
AUDIO_RTF_METRIC = METRIC_PREFIX + AUDIO_RTF
AUDIO_FRAMES_METRIC = METRIC_PREFIX + AUDIO_FRAMES
AUDIO_UNDERRUN_S = METRIC_PREFIX + AUDIO_UNDERRUN + "_s"
AUDIO_CONTINUITY_OK_METRIC = METRIC_PREFIX + AUDIO_CONTINUITY_OK
AUDIO_SKIPPED_REQUESTS_METRIC = METRIC_PREFIX + AUDIO_SKIPPED_REQUESTS
# ============================================================================
# Cross-stage Transfer family (per-physical-hop TX/RX/in-flight timings)
# ============================================================================
TRANSFER_SIZE_BYTES = METRIC_PREFIX + "transfer_size_bytes"
TRANSFER_TX_S = METRIC_PREFIX + "transfer_tx_s"
TRANSFER_RX_S = METRIC_PREFIX + "transfer_rx_s"
TRANSFER_IN_FLIGHT_S = METRIC_PREFIX + "transfer_in_flight_s"
# ============================================================================
# Label sets
# ============================================================================
PIPELINE_LABELS = ("model_name",)
SUCCESS_LABELS = ("model_name", "finished_reason")
# Per-stage / per-replica label set used by the audio families and by the
# OmniPrometheusStatLogger wrap which relabels upstream ``engine`` into
# ``stage`` + ``replica``.
STAGE_LABELS = ("model_name", "stage", "replica")
# Audio continuity Counter carries an extra ``threshold_ms`` label so multiple
# threshold buckets can be tracked simultaneously. The ``_ms`` suffix names a
# numeric threshold *value* in ms, not a time-bearing metric.
AUDIO_CONTINUITY_LABELS = ("model_name", "stage", "replica", "threshold_ms")
# Audio skipped-requests Counter carries a `reason` label so the silent-loss
# path (e.g. code2wav rejecting malformed codec input) can be distinguished
# from other "200 OK + empty audio" cases.
AUDIO_SKIPPED_LABELS = ("model_name", "stage", "replica", "reason")
# Cross-stage transfer label set. Each observation is one physical hop from
# (from_stage, from_replica) to (to_stage, to_replica).
TRANSFER_LABELS = (
"model_name",
"from_stage",
"from_replica",
"to_stage",
"to_replica",
)
# ============================================================================
# Histogram buckets
# ============================================================================
# Seconds bucket for e2e / generation / TTFP-style metrics that range from
# ~10 ms to several minutes.
SECONDS_BUCKETS = (
0.05,
0.1,
0.25,
0.5,
1.0,
2.0,
5.0,
10.0,
20.0,
30.0,
60.0,
120.0,
300.0,
)
# Seconds bucket for fine-grained metrics (cross-stage transfer + audio
# underrun) that need millisecond-level resolution.
SECONDS_FAST_BUCKETS = (
0.001,
0.005,
0.01,
0.025,
0.05,
0.1,
0.25,
0.5,
1.0,
2.5,
5.0,
10.0,
60.0,
)
# RTF SLO red line is 1.0 — TTS must generate faster than playback.
RTF_BUCKETS = (
0.1,
0.25,
0.5,
0.75,
0.9,
1.0,
1.25,
1.5,
2.0,
5.0,
10.0,
)
# Bytes bucket for transfer payload size.
BYTES_BUCKETS = (
1024,
4096,
16384,
65536,
262144,
1048576,
4194304,
16777216,
67108864,
268435456,
)
# ============================================================================
# Audio-continuity defaults
# ============================================================================
# Default underrun threshold — kept aligned with the bench-side default and
# the commonly-cited "audible gap" threshold for streaming TTS.
AUDIO_CONTINUITY_DEFAULT_THRESHOLD_S = 0.1
# ============================================================================
# Formula helpers (shared by server-side observe and bench-side calculation)
# ============================================================================
def compute_audio_rtf(stage_gen_time_s: float, audio_duration_s: float) -> float:
"""RTF = stage_gen_time / audio_content_duration.
SLO red line < 1 — must generate faster than content plays back to stream.
Returns 0.0 when audio_duration_s is non-positive (caller decides whether
to observe; we don't want to divide by zero or emit negative samples).
"""
if audio_duration_s <= 0:
return 0.0
return stage_gen_time_s / audio_duration_s
# ============================================================================
# Audio sample-rate resolution
# ============================================================================
# Most common across vllm-omni talker variants (cosyvoice3, omnivoice,
# qwen3_tts, mimo_audio). voxcpm2 uses 48000, stable_audio 44100,
# ming_flash 16000 — these models populate multimodal_output["audio_sample_rate"]
# at runtime so this default only kicks in when the field is missing.
DEFAULT_AUDIO_SAMPLE_RATE = 24000
_SAMPLE_RATE_KEYS = ("audio_sample_rate", "sample_rate", "sampling_rate", "sr")
def resolve_audio_sample_rate(multimodal_output: dict | None) -> int:
"""Extract audio sample_rate from a multimodal_output dict, with fallbacks.
Tries the same key chain as serving_chat.py's audio response path so
/metrics audio_duration_s = audio_frames / sample_rate stays consistent
with what the OpenAI streaming endpoint reports back to clients.
Returns DEFAULT_AUDIO_SAMPLE_RATE when no usable value is present.
"""
if not multimodal_output:
return DEFAULT_AUDIO_SAMPLE_RATE
for key in _SAMPLE_RATE_KEYS:
raw = multimodal_output.get(key)
if raw is None:
continue
try:
value = int(raw)
except (TypeError, ValueError):
continue
if value > 0:
return value
return DEFAULT_AUDIO_SAMPLE_RATE
+303
View File
@@ -0,0 +1,303 @@
"""OmniModalityMetrics — per-modality Prometheus families (audio path only).
7 audio business-semantic metric families. Text-path metrics (TTFT / ITL /
TPOT / e2e) are NOT here — they come from the upstream
``vllm:*{stage="thinker", ...}`` families exposed via the
``OmniPrometheusStatLogger`` wrap.
Contents:
- Audio family declarations (Histograms + Counters)
- ``OmniModalityMetrics``: label-bound observe API for the audio family
- ``observe_modality_at_finalize``: dispatcher called from omni_base's e2e
finalize hook; currently handles the audio path only.
- ``observe_audio_first_packet``: TTFP emit from the streaming SSE first
audio packet.
- ``observe_audio_streaming_finalize``: emits ``audio_underrun_s`` +
``audio_continuity_ok_total`` at SSE close using accumulated per-chunk
arrival timestamps.
- ``_extract_mm_output`` / ``_count_audio_frames``: shape-tolerant helpers
for the heterogeneous multimodal_output payloads emitted by different
audio pipelines.
"""
from __future__ import annotations
from typing import Any
from prometheus_client import Counter, Histogram
from vllm_omni.metrics import definitions as defs
_stage_labels = list(defs.STAGE_LABELS)
# ----------------------------------------------------------------------------
# Audio family
# ----------------------------------------------------------------------------
_audio_ttfp_family = Histogram(
defs.AUDIO_TTFP_S,
"Time from request arrival to first audio packet/frame, in seconds.",
labelnames=_stage_labels,
buckets=defs.SECONDS_BUCKETS,
)
_audio_duration_family = Histogram(
defs.AUDIO_DURATION_S,
"Generated audio content duration in seconds (audio_frames / sample_rate).",
labelnames=_stage_labels,
buckets=defs.SECONDS_BUCKETS,
)
_audio_rtf_family = Histogram(
defs.AUDIO_RTF_METRIC,
"Audio real-time factor (stage_gen_time_s / audio_duration_s); streaming TTS requires < 1.",
labelnames=_stage_labels,
buckets=defs.RTF_BUCKETS,
)
_audio_frames_family = Counter(
defs.AUDIO_FRAMES_METRIC,
"Cumulative audio frame count; per-model rate (not summable across models). Throughput recovered via rate().",
labelnames=_stage_labels,
)
_audio_underrun_family = Histogram(
defs.AUDIO_UNDERRUN_S,
"Per-request worst-case player-deficit in seconds (max time the player "
"ran out of buffered audio). > 0 indicates listener experienced silent gaps.",
labelnames=_stage_labels,
buckets=defs.SECONDS_FAST_BUCKETS,
)
_audio_continuity_ok_family = Counter(
defs.AUDIO_CONTINUITY_OK_METRIC,
"Incremented when the request's worst underrun stayed below threshold_ms. "
"Pair with requests_success_total to compute streaming-continuity health rate.",
labelnames=list(defs.AUDIO_CONTINUITY_LABELS),
)
_audio_skipped_family = Counter(
defs.AUDIO_SKIPPED_REQUESTS_METRIC,
"Silent-loss counter — code2wav rejected malformed codec input and returned 200 OK with empty audio.",
labelnames=list(defs.AUDIO_SKIPPED_LABELS),
)
class OmniModalityMetrics:
"""Per-modality observe API. Stage/replica are passed at observe time
because a single OmniModalityMetrics instance per pipeline serves all
stage+replica combinations.
"""
def __init__(self, model_name: str, log_stats: bool = True) -> None:
self._model_name = model_name
self._log_stats = log_stats
# ---- Audio ------------------------------------------------------------
def observe_audio_ttfp(self, stage: str, replica: str, ttfp_seconds: float) -> None:
if not self._log_stats:
return
_audio_ttfp_family.labels(model_name=self._model_name, stage=stage, replica=replica).observe(ttfp_seconds)
def observe_audio_duration(self, stage: str, replica: str, duration_seconds: float) -> None:
if not self._log_stats:
return
_audio_duration_family.labels(model_name=self._model_name, stage=stage, replica=replica).observe(
duration_seconds
)
def observe_audio_rtf(self, stage: str, replica: str, rtf: float) -> None:
if not self._log_stats:
return
_audio_rtf_family.labels(model_name=self._model_name, stage=stage, replica=replica).observe(rtf)
def inc_audio_frames(self, stage: str, replica: str, n_frames: int) -> None:
if not self._log_stats or n_frames <= 0:
return
_audio_frames_family.labels(model_name=self._model_name, stage=stage, replica=replica).inc(n_frames)
def observe_audio_underrun(self, stage: str, replica: str, underrun_s: float) -> None:
if not self._log_stats:
return
_audio_underrun_family.labels(model_name=self._model_name, stage=stage, replica=replica).observe(
max(underrun_s, 0.0)
)
def inc_audio_continuity_ok(self, stage: str, replica: str, threshold_ms: int) -> None:
if not self._log_stats:
return
_audio_continuity_ok_family.labels(
model_name=self._model_name,
stage=stage,
replica=replica,
threshold_ms=str(int(threshold_ms)),
).inc()
def inc_audio_skipped(self, stage: str, replica: str, reason: str) -> None:
if not self._log_stats:
return
_audio_skipped_family.labels(
model_name=self._model_name,
stage=stage,
replica=replica,
reason=reason or "unknown",
).inc()
def _extract_mm_output(engine_outputs: Any) -> dict[str, Any]:
"""Return the multimodal_output dict regardless of where it's nested.
Three shapes seen in the wild:
* ``engine_outputs.multimodal_output`` — synthesized on OmniRequestOutput
for some pipelines (often empty for AR audio)
* ``engine_outputs.outputs[0].multimodal_output`` — vllm CompletionOutput
nesting (where actual qwen3-omni audio data lives)
* neither — returns ``{}``
"""
mm = getattr(engine_outputs, "multimodal_output", None)
if isinstance(mm, dict) and mm:
return mm
outs = getattr(engine_outputs, "outputs", None)
if outs:
nested = getattr(outs[0], "multimodal_output", None)
if isinstance(nested, dict):
return nested
return {}
def _count_audio_frames(mm_out: dict[str, Any]) -> int:
"""Sum the per-tensor sample count of audio chunks in mm_out["audio"].
Returns the total number of audio frames (samples) across all chunks.
For multi-dim tensors (e.g. shape [channels, samples]) the last axis is
treated as the sample dim; for 1-D tensors the only axis is the sample
dim; scalars count as 1.
"""
audio_chunks = mm_out.get("audio") if isinstance(mm_out, dict) else None
if audio_chunks is None:
return 0
chunks = audio_chunks if isinstance(audio_chunks, list) else [audio_chunks]
n = 0
for t in chunks:
try:
ndim = getattr(t, "ndim", 0)
shape = getattr(t, "shape", None)
if ndim == 0 or shape is None or len(shape) == 0:
n += 1
else:
n += int(shape[-1])
except Exception:
continue
return n
def observe_modality_at_finalize(
mod_metrics: OmniModalityMetrics,
*,
output_type: str | None,
stage_id: int,
replica_id: int | None,
stage_metrics: Any,
engine_outputs: Any,
) -> None:
"""Route audio-path observations for a finalized request.
Used by ``omni_base._process_single_result`` inside the e2e_done finalize
guard so it fires once per request. Skips text path (covered by upstream
``vllm:*{stage="thinker", ...}``) and any case where required inputs are
missing — caller should not need to pre-validate.
audio_ttfp is intentionally NOT observed here; it's emitted by the
streaming hook at first-packet time, not at finalize.
"""
if replica_id is None or stage_metrics is None or output_type is None:
return
if output_type != "audio":
return
stage_label = str(stage_id)
replica_label = str(replica_id)
gen_time_s = float(getattr(stage_metrics, "stage_gen_time_ms", 0.0)) / 1000.0
mm_out = _extract_mm_output(engine_outputs)
sample_rate = defs.resolve_audio_sample_rate(mm_out)
# `stage_metrics.audio_generated_frames` is the legacy per-chunk
# accumulator field on StageRequestStats. No production path currently
# fills it, so the fallback below is the live source — but we leave the
# field lookup in place in case the accumulator gets re-wired upstream.
n_frames = int(getattr(stage_metrics, "audio_generated_frames", 0) or 0)
if n_frames == 0:
n_frames = _count_audio_frames(mm_out)
mod_metrics.inc_audio_frames(stage_label, replica_label, n_frames)
duration_s = n_frames / sample_rate if sample_rate > 0 else 0.0
if duration_s > 0:
mod_metrics.observe_audio_duration(stage_label, replica_label, duration_s)
mod_metrics.observe_audio_rtf(
stage_label,
replica_label,
defs.compute_audio_rtf(gen_time_s, duration_s),
)
else:
# Request completed (finish_reason ∈ {stop, length} — error paths
# don't reach finalize) but no audio samples were produced. Covers
# silent `return None` skips in the talker→code2wav stage
# processors and the `parsed.append((0,0))` malformed-length path
# in qwen3-tts code2wav. raise-paths surface via the upstream
# vllm:request_success_total{finished_reason="error"} channel and
# never reach this branch.
mod_metrics.inc_audio_skipped(stage_label, replica_label, "no_audio_data")
# audio_underrun / continuity are emitted from the streaming path in
# observe_audio_streaming_finalize; finalize is too late for the
# per-chunk timeline they need.
def observe_audio_first_packet(
mod_metrics: OmniModalityMetrics,
*,
stage_id: int,
replica_id: int | None,
arrival_ts: float,
now_ts: float,
) -> None:
"""Observe audio_ttfp_s on a request's first audio packet.
Caller is responsible for the once-per-request guard (e.g. checking
``ClientRequestState.first_audio_ts is None``) so this function fires at
most once per request_id. Defensive-skips when ``replica_id`` or
``arrival_ts`` is insufficient — both can legitimately be missing in error
paths and we'd rather drop the sample than emit a wrong (stage, replica).
"""
if replica_id is None or arrival_ts <= 0:
return
ttfp = max(now_ts - arrival_ts, 0.0)
mod_metrics.observe_audio_ttfp(str(stage_id), str(replica_id), ttfp)
def observe_audio_streaming_finalize(
mod_metrics: OmniModalityMetrics,
*,
stage_id: int,
replica_id: int | None,
chunk_arrival_times_s: list[float],
chunk_bytes: list[int],
sample_rate: int,
threshold_s: float = defs.AUDIO_CONTINUITY_DEFAULT_THRESHOLD_S,
) -> None:
"""Emit audio_underrun_s + audio_continuity_ok_total at request end.
Reuses the math from ``vllm_omni.benchmarks.audio_continuity`` so the
server-side and bench-side definitions stay aligned. Caller is responsible
for collecting per-chunk arrival timestamps and byte sizes during the
streaming response.
"""
if replica_id is None or not chunk_arrival_times_s:
return
# Local import to keep the bench module optional at import time.
from vllm_omni.benchmarks.audio_continuity import compute_continuity_stats
stats = compute_continuity_stats(
chunk_arrival_times_s=chunk_arrival_times_s,
chunk_bytes=chunk_bytes,
sample_rate=sample_rate,
threshold_s=threshold_s,
)
stage_label = str(stage_id)
replica_label = str(replica_id)
mod_metrics.observe_audio_underrun(stage_label, replica_label, stats.max_underrun_s)
if stats.is_continuous:
mod_metrics.inc_audio_continuity_ok(stage_label, replica_label, int(threshold_s * 1000))
+91
View File
@@ -0,0 +1,91 @@
from prometheus_client import Counter, Gauge, Histogram
from vllm_omni.metrics import definitions as defs
_labelnames = list(defs.PIPELINE_LABELS)
_running_family = Gauge(
defs.NUM_REQUESTS_RUNNING,
"Number of requests currently running across all pipeline stages.",
labelnames=_labelnames,
)
_waiting_family = Gauge(
defs.NUM_REQUESTS_WAITING,
"Number of requests waiting to be scheduled.",
labelnames=_labelnames,
)
_completion_family = Counter(
defs.REQUESTS_SUCCESS,
"Total requests by completion reason "
"(stop / length / abort / ...). Aborts cover client-disconnect / "
"cancellation paths in addition to upstream FinishReason.ABORT.",
labelnames=list(defs.SUCCESS_LABELS),
)
_e2e_latency_family = Histogram(
defs.E2E_REQUEST_LATENCY_S,
"Pipeline-global end-to-end request latency in seconds (user arrival to complete response).",
labelnames=_labelnames,
buckets=defs.SECONDS_BUCKETS,
)
class OmniPrometheusMetrics:
"""Label-bound wrapper around the raw Prometheus metrics.
Metric collectors use the ``vllm:omni_`` prefix to avoid being
removed by upstream vLLM's ``unregister_vllm_metrics()``, which
strips every collector whose ``_name`` contains ``"vllm"``.
"""
def __init__(self, model_name: str, log_stats: bool = True) -> None:
self._model_name = model_name
self._log_stats = log_stats
self._running = _running_family.labels(model_name=model_name)
self._waiting = _waiting_family.labels(model_name=model_name)
self._e2e_latency = _e2e_latency_family.labels(model_name=model_name)
def set_running(self, n: int) -> None:
if not self._log_stats:
return
self._running.set(n)
def set_waiting(self, n: int) -> None:
if not self._log_stats:
return
self._waiting.set(n)
def request_succeeded(
self,
e2e_seconds: float,
finished_reason: str = "stop",
) -> None:
if not self._log_stats:
return
_completion_family.labels(
model_name=self._model_name,
finished_reason=finished_reason,
).inc()
self._e2e_latency.observe(e2e_seconds)
def request_failed(self) -> None:
if not self._log_stats:
return
# Pipeline-level "fail" maps to the upstream FinishReason.ABORT bucket;
# a single counter family now covers both normal stops and aborts.
_completion_family.labels(
model_name=self._model_name,
finished_reason="abort",
).inc()
class OmniRequestCounter:
"""Running-request counter written by the orchestrator thread, read by the client thread."""
def __init__(self) -> None:
self.value = 0
def increment(self) -> None:
self.value += 1
def decrement(self) -> None:
self.value = max(0, self.value - 1)
+243
View File
@@ -0,0 +1,243 @@
"""OmniPrometheusStatLogger — wrap upstream PrometheusStatLogger.
Rewrites the upstream ``engine`` single-label scheme into a ``stage`` +
``replica`` two-label scheme so the ~37 ``vllm:*`` metric families gain
per-(stage, replica) visibility for multi-replica deployments.
Contents:
- ``_ENGINE_INDEX_MAP``: process-wide engine_idx → (stage_name, replica_id)
lookup, populated by ``OmniPrometheusStatLogger.__init__``.
- ``_RelabelMixin``: rewrites ``labelnames`` at family creation and translates
``.labels()`` calls; applied via ``_RelabelGauge`` / ``_RelabelCounter`` /
``_RelabelHistogram``.
- ``_OmniPerfMetricsProm`` / ``_OmniSpecDecodingProm`` / ``_OmniKVConnectorProm``:
helper-class wraps so the upstream sub-collectors construct their internal
families through the relabel mixin too.
- ``OmniPrometheusStatLogger``: the subclass that wires everything together
and rewrites ``per_engine_labelvalues`` from 2-tuple to 3-tuple at setter
time.
"""
from __future__ import annotations
from prometheus_client import Counter, Gauge, Histogram
from vllm.config import VllmConfig
from vllm.distributed.kv_transfer.kv_connector.v1.metrics import KVConnectorProm
from vllm.v1.metrics.loggers import PrometheusStatLogger
from vllm.v1.metrics.perf import PerfMetricsProm
from vllm.v1.spec_decode.metrics import SpecDecodingProm
# Process-wide translation table written by OmniPrometheusStatLogger at init.
# Keys are flat engine_idx values (as upstream PrometheusStatLogger sees them);
# values are the (stage_name, replica_id_str) tuple we expose as labels.
#
# Module-level rather than per-instance because the wrapper metric classes are
# constructed by upstream's __init__ and never get a back-reference to the
# StatLogger that owns them. vLLM runs a single Orchestrator/StatLogger per
# process, so a module global is safe; tests isolate by .clear()ing first.
_ENGINE_INDEX_MAP: dict[int, tuple[str, str]] = {}
def _rewrite_labelnames(labelnames):
"""Replace `engine` in ``labelnames`` with (`stage`, `replica`) in place.
Preserves ordering (so ``["model_name", "engine", "reason"]`` becomes
``["model_name", "stage", "replica", "reason"]``) and the original
container type (list vs tuple).
"""
if labelnames is None:
return labelnames
seq = list(labelnames)
if "engine" not in seq:
return labelnames
out: list[str] = []
for name in seq:
if name == "engine":
out.extend(("stage", "replica"))
else:
out.append(name)
return type(labelnames)(out) if not isinstance(labelnames, list) else out
def _engine_to_stage_replica(engine_value) -> tuple[str, str]:
"""Look up (stage, replica) for an engine_idx, accepting int or str input.
Upstream emits engine values in two flavors:
- int form, e.g. ``gauge_engine_sleep_state.labels(engine=idx, ...)`` (loggers.py:510)
- str form, e.g. ``info_gauge.labels(**metrics_info)`` where ``metrics_info["engine"] = str(idx)`` (loggers.py:1055)
Raises ``KeyError`` when the value is missing from the map — fail-fast is
preferable to silently emitting series under a wrong (stage, replica).
"""
key = int(engine_value) if isinstance(engine_value, str) else engine_value
return _ENGINE_INDEX_MAP[key]
class _RelabelMixin:
"""Mixin: rewrite ``labelnames`` at family creation and ``.labels()`` calls.
Handles all four upstream forms encountered in
``vllm.v1.metrics.loggers.PrometheusStatLogger``:
1. ``.labels(engine=idx, ...)`` kwarg with int engine (loggers.py:510)
2. ``.labels(model_name, str(idx), source)`` positional with str engine
(loggers.py:646, 679)
3. ``.labels(**metrics_info)`` kwarg with str engine (loggers.py:1056)
4. Families without an ``engine`` label — passthrough (e.g. lora_info)
Drops into upstream's ``_gauge_cls`` / ``_counter_cls`` / ``_histogram_cls``
class slots.
"""
def __init__(self, *args, **kwargs):
# Remember where `engine` sat in the original labelnames so positional
# `.labels()` calls can splice (stage, replica) at the right offset.
labelnames = kwargs.get("labelnames")
if labelnames is not None:
original = list(labelnames)
self._engine_label_index = original.index("engine") if "engine" in original else -1
kwargs["labelnames"] = _rewrite_labelnames(labelnames)
else:
self._engine_label_index = -1
super().__init__(*args, **kwargs)
def labels(self, *args, **kwargs):
if self._engine_label_index >= 0:
if args:
# Positional form. There are TWO upstream patterns:
#
# (a) Pre-rewritten path: create_metric_per_engine fans
# `per_engine_labelvalues` (already a 3-tuple
# [model_name, stage, replica] thanks to the property-
# descriptor setter on OmniPrometheusStatLogger) into
# `metric.labels(*values)`. len(args) matches the
# rewritten label set already, so just pass through.
#
# (b) Legacy 2-tuple path: upstream sites like
# `counter_request_success.labels(model_name, str(idx),
# str(reason))` pass values shaped to the *original*
# labelnames (engine still present at idx). Here
# len(args) is short by 1 — splice (stage, replica)
# in place of the engine value at engine_label_index.
if len(args) == len(self._labelnames):
return super().labels(*args, **kwargs)
idx = self._engine_label_index
if idx < len(args):
stage, replica = _engine_to_stage_replica(args[idx])
args = (*args[:idx], stage, replica, *args[idx + 1 :])
elif "engine" in kwargs:
stage, replica = _engine_to_stage_replica(kwargs.pop("engine"))
kwargs["stage"] = stage
kwargs["replica"] = replica
return super().labels(*args, **kwargs)
class _RelabelGauge(_RelabelMixin, Gauge):
pass
class _RelabelCounter(_RelabelMixin, Counter):
pass
class _RelabelHistogram(_RelabelMixin, Histogram):
pass
# ----------------------------------------------------------------------------
# Helper-class wraps for the three sub-metric collectors that upstream
# PrometheusStatLogger constructs in its __init__ (loggers.py:438-446):
#
# self.spec_decoding_prom = self._spec_decoding_cls(...)
# self.kv_connector_prom = self._kv_connector_cls(...)
# self.perf_metrics_prom = self._perf_metrics_cls(...)
#
# Each helper receives raw `labelnames` as a constructor argument and uses
# its own class-level `_counter_cls` / `_gauge_cls` / `_histogram_cls` slots
# to build internal Counter/Gauge/Histogram families. The slot overrides on
# OmniPrometheusStatLogger only reach families created via *its* slots, so
# the helpers would otherwise still construct 2-label families and then hit
# `Incorrect label count` when create_metric_per_engine feeds the rewritten
# 3-element per_engine_labelvalues. Subclassing each helper and overriding
# its slots routes the relabel mixin through to the helper-internal families
# too. The helper kept seeing the OLD 2-element labelnames param, but that
# is fine because the wrapper rewrites it at family-creation time.
# ----------------------------------------------------------------------------
class _OmniPerfMetricsProm(PerfMetricsProm):
_counter_cls = _RelabelCounter
class _OmniSpecDecodingProm(SpecDecodingProm):
_counter_cls = _RelabelCounter
class _OmniKVConnectorProm(KVConnectorProm):
_gauge_cls = _RelabelGauge
_counter_cls = _RelabelCounter
_histogram_cls = _RelabelHistogram
class OmniPrometheusStatLogger(PrometheusStatLogger):
"""Wrap upstream PrometheusStatLogger to expose per-(stage, replica) labels.
Replaces the upstream single ``engine`` label with two labels ``stage`` and
``replica`` so the ~37 ``vllm:*`` metric families gain per-replica
visibility for multi-replica deployments.
The orchestrator builds ``stage_replica_map`` from the static stage_pools
config; flat engine_idx values map 1:1 to (stage_name, replica_id) tuples.
Dynamic add/remove of replicas at runtime is intentionally not supported —
the map is built once at construction and never mutated afterward.
"""
# Inject our wrapper metric classes into upstream's class-level slots so
# every ~37 family is created with `engine` rewritten to `stage`+`replica`.
_gauge_cls = _RelabelGauge
_counter_cls = _RelabelCounter
_histogram_cls = _RelabelHistogram
# Inject helper-class wraps too so the perf / spec-decoding / kv-connector
# sub-collectors get the same labelname rewrite and don't crash with
# `Incorrect label count` when create_metric_per_engine fans out the
# rewritten 3-element per_engine_labelvalues over their internal families.
_perf_metrics_cls = _OmniPerfMetricsProm
_spec_decoding_cls = _OmniSpecDecodingProm
_kv_connector_cls = _OmniKVConnectorProm
def __init__(
self,
vllm_config: VllmConfig,
stage_replica_map: dict[int, tuple[str, str]],
) -> None:
self._stage_replica_map = stage_replica_map
# Populate the process-level translation table that wrapper metric
# classes consult on every `.labels()` call. Cleared first so a
# second OmniPrometheusStatLogger in the same process (e.g. tests,
# orchestrator restart) starts from a clean slate.
_ENGINE_INDEX_MAP.clear()
_ENGINE_INDEX_MAP.update(stage_replica_map)
super().__init__(
vllm_config=vllm_config,
engine_indexes=list(stage_replica_map.keys()),
)
@property
def stage_replica_map(self) -> dict[int, tuple[str, str]]:
return self._stage_replica_map
@property
def per_engine_labelvalues(self) -> dict[int, list[object]]:
return self._omni_per_engine_labelvalues
@per_engine_labelvalues.setter
def per_engine_labelvalues(self, value: dict[int, list[object]]) -> None:
# Upstream sets {idx: [model_name, str(idx)]} (loggers.py:433); we drop
# the engine str and append (stage, replica) so labelvalues match the
# 3-element labelnames our wrapper classes produce.
rewritten: dict[int, list[object]] = {}
for idx, vals in value.items():
model_name = vals[0]
stage, replica = self._stage_replica_map[idx]
rewritten[idx] = [model_name, stage, replica]
self._omni_per_engine_labelvalues = rewritten
+108 -1
View File
@@ -5,12 +5,15 @@ from collections import defaultdict
from collections.abc import Callable
from contextlib import contextmanager
from dataclasses import dataclass
from typing import Any
from typing import TYPE_CHECKING, Any
from vllm.logger import init_logger
from vllm_omni.metrics.utils import _build_field_defs, _build_row, _format_table
if TYPE_CHECKING:
from vllm_omni.metrics.transfer import OmniTransferMetrics
logger = init_logger(__name__)
@@ -36,6 +39,7 @@ class StageRequestStats:
rx_in_flight_time_ms: float
stage_stats: StageStats
stage_id: int | None = None
replica_id: int | None = None
final_output_type: str | None = None
request_id: str | None = None
postprocess_time_ms: float = 0.0
@@ -121,6 +125,9 @@ class OrchestratorAggregator:
log_stats: bool,
wall_start_ts: float,
final_stage_id_for_e2e: dict[str, int] | int,
*,
transfer_emitter: OmniTransferMetrics | None = None,
replica_resolver: Callable[[int, str], int | None] | None = None,
) -> None:
self.num_stages = int(num_stages)
self.log_stats = bool(log_stats)
@@ -131,6 +138,20 @@ class OrchestratorAggregator:
tuple[int, int, str], TransferEdgeStats
] = {} # Key: (from_stage, to_stage, request_id)
self.e2e_events: list[RequestE2EStats] = []
# Emit per-physical-transfer Histogram observations to Prometheus
# alongside the existing TransferEdgeStats accumulation. Both deps
# are optional so OrchestratorAggregator stays usable in contexts
# that don't have a Prometheus registry (e.g. unit tests).
self._transfer_emitter = transfer_emitter
self._replica_resolver = replica_resolver
# Snapshot of (stage_id -> replica_id) per request, captured at
# ``record_transfer_rx`` time from the receiving stage's own
# ``StageRequestStats.replica_id``. Survives pool-side
# ``release_binding`` so the transfer emit can resolve label values
# even when the downstream stage's binding has already been released
# by the orchestrator's cleanup path (e.g. final-stage cleanup races
# the omni_base finalize emit).
self._replica_cache: dict[tuple[int, str], int] = {}
def init_run_state(self, wall_start_ts: float) -> None:
# Per-run aggregates and timing state
@@ -191,6 +212,14 @@ class OrchestratorAggregator:
evt.size_bytes += int(size_bytes)
evt.tx_time_ms += float(tx_time_ms)
evt.used_shm = evt.used_shm or bool(used_shm)
# Emit per-physical-transfer Histogram observations to Prometheus.
self._emit_transfer_tx(
from_stage=int(from_stage),
to_stage=int(to_stage),
request_id=str(request_id),
size_bytes=int(size_bytes),
tx_time_ms=float(tx_time_ms),
)
return evt
except Exception:
return None
@@ -205,6 +234,11 @@ class OrchestratorAggregator:
from_stage = int(stats.stage_id) - 1
to_stage = int(stats.stage_id)
rid_key = str(stats.request_id)
# Snapshot the receiving (stage, replica) binding before the
# pool may release it on cleanup. Used by _resolve_edge_replicas
# as a fallback when get_bound_replica_id has already cleared.
if stats.replica_id is not None:
self._replica_cache[(to_stage, rid_key)] = int(stats.replica_id)
evt = self._get_or_create_transfer_event(from_stage, to_stage, rid_key)
# Accumulate rx metrics
if evt.size_bytes == 0:
@@ -212,10 +246,79 @@ class OrchestratorAggregator:
evt.size_bytes = int(stats.rx_transfer_bytes)
evt.rx_decode_time_ms += float(stats.rx_decode_time_ms)
evt.in_flight_time_ms += float(stats.rx_in_flight_time_ms)
# Emit per-physical-receive Histogram observations to Prometheus.
self._emit_transfer_rx(
from_stage=from_stage,
to_stage=to_stage,
request_id=rid_key,
rx_decode_time_ms=float(stats.rx_decode_time_ms),
in_flight_time_ms=float(stats.rx_in_flight_time_ms),
)
return evt
except Exception:
return None
# ------------------------------------------------------------------
# Prometheus emit hooks. Both helpers are no-ops when transfer_emitter
# or replica_resolver is None, or when the resolver cannot find a
# (stage_id, request_id) -> replica_id mapping. We deliberately
# fail-safe (skip) rather than emit a series with a wrong or invented
# replica label.
# ------------------------------------------------------------------
def _resolve_edge_replicas(self, from_stage: int, to_stage: int, request_id: str) -> tuple[int, int] | None:
# Prefer the per-request replica snapshot captured by
# record_transfer_rx (survives pool binding release); fall back to the
# resolver callback (pool.get_bound_replica_id) when the cache
# misses, e.g. for the TX side that fires before the receiving stage
# has recorded its stats.
from_r = self._replica_cache.get((from_stage, request_id))
to_r = self._replica_cache.get((to_stage, request_id))
if (from_r is None or to_r is None) and self._replica_resolver is not None:
if from_r is None:
from_r = self._replica_resolver(from_stage, request_id)
if to_r is None:
to_r = self._replica_resolver(to_stage, request_id)
if from_r is None or to_r is None:
return None
return int(from_r), int(to_r)
def _emit_transfer_tx(
self,
*,
from_stage: int,
to_stage: int,
request_id: str,
size_bytes: int,
tx_time_ms: float,
) -> None:
if self._transfer_emitter is None:
return
replicas = self._resolve_edge_replicas(from_stage, to_stage, request_id)
if replicas is None:
return
from_r, to_r = replicas
self._transfer_emitter.observe_size(from_stage, from_r, to_stage, to_r, size_bytes)
self._transfer_emitter.observe_tx_time(from_stage, from_r, to_stage, to_r, tx_time_ms / 1000.0)
def _emit_transfer_rx(
self,
*,
from_stage: int,
to_stage: int,
request_id: str,
rx_decode_time_ms: float,
in_flight_time_ms: float,
) -> None:
if self._transfer_emitter is None:
return
replicas = self._resolve_edge_replicas(from_stage, to_stage, request_id)
if replicas is None:
return
from_r, to_r = replicas
self._transfer_emitter.observe_rx_time(from_stage, from_r, to_stage, to_r, rx_decode_time_ms / 1000.0)
self._transfer_emitter.observe_in_flight_time(from_stage, from_r, to_stage, to_r, in_flight_time_ms / 1000.0)
def record_audio_generated_frames(
self,
output_to_yield: Any,
@@ -462,6 +565,10 @@ class OrchestratorAggregator:
),
)
self.e2e_events.append(per_req_record)
# Drop per-request replica snapshots once the request is finalized.
if self._replica_cache:
for cached_key in [k for k in self._replica_cache if k[1] == rid_key]:
self._replica_cache.pop(cached_key, None)
def build_and_log_summary(self) -> dict[str, Any]:
if not self.log_stats:
+145
View File
@@ -0,0 +1,145 @@
"""OmniTransferMetrics — cross-stage transfer Prometheus families.
Four families with ``{model_name, from_stage, from_replica, to_stage,
to_replica}`` labels. Each ``observe_*()`` call corresponds to one physical
transfer event (one chunk hop from a sender replica to a receiver replica),
so the Histogram tracks the distribution of physical transfers, not
request-aggregated sums.
Data source: ``vllm_omni.metrics.stats.TransferEdgeStats`` accumulators in
``OrchestratorAggregator.record_transfer_tx`` / ``record_transfer_rx``. The
emit hook lives in stats.py; this module only registers the families and
exposes the typed observe API.
"""
from __future__ import annotations
from prometheus_client import Histogram
from vllm_omni.metrics import definitions as defs
_labelnames = list(defs.TRANSFER_LABELS)
# ----------------------------------------------------------------------------
# TX-side families (observed when record_transfer_tx fires)
# ----------------------------------------------------------------------------
_transfer_size_bytes_family = Histogram(
defs.TRANSFER_SIZE_BYTES,
"Per-transfer payload size in bytes (one observation per physical hop).",
labelnames=_labelnames,
buckets=defs.BYTES_BUCKETS,
)
_transfer_tx_family = Histogram(
defs.TRANSFER_TX_S,
"Sender-side time in seconds (serialize + submit to connector).",
labelnames=_labelnames,
buckets=defs.SECONDS_FAST_BUCKETS,
)
# ----------------------------------------------------------------------------
# RX-side families (observed when record_transfer_rx fires)
# ----------------------------------------------------------------------------
_transfer_rx_family = Histogram(
defs.TRANSFER_RX_S,
"Receiver-side time in seconds (recv + deserialize).",
labelnames=_labelnames,
buckets=defs.SECONDS_FAST_BUCKETS,
)
_transfer_in_flight_family = Histogram(
defs.TRANSFER_IN_FLIGHT_S,
"Network in-flight time in seconds (TX done -> RX recv start).",
labelnames=_labelnames,
buckets=defs.SECONDS_FAST_BUCKETS,
)
class OmniTransferMetrics:
"""Per-(from, to) replica observe API for cross-stage transfers.
A single instance per pipeline; ``model_name`` is bound at init and
every observe call carries it in the label set. Stage/replica are
passed at observe time because the same instance serves all
(from_stage, from_replica) -> (to_stage, to_replica) edges.
"""
def __init__(self, model_name: str, log_stats: bool = True) -> None:
self._model_name = model_name
self._log_stats = log_stats
# ---- TX side (record_transfer_tx hook) -------------------------------
def observe_size(
self,
from_stage: int,
from_replica: int,
to_stage: int,
to_replica: int,
size_bytes: int,
) -> None:
if not self._log_stats:
return
_transfer_size_bytes_family.labels(
model_name=self._model_name,
from_stage=str(from_stage),
from_replica=str(from_replica),
to_stage=str(to_stage),
to_replica=str(to_replica),
).observe(size_bytes)
def observe_tx_time(
self,
from_stage: int,
from_replica: int,
to_stage: int,
to_replica: int,
tx_time_s: float,
) -> None:
if not self._log_stats:
return
_transfer_tx_family.labels(
model_name=self._model_name,
from_stage=str(from_stage),
from_replica=str(from_replica),
to_stage=str(to_stage),
to_replica=str(to_replica),
).observe(tx_time_s)
# ---- RX side (record_transfer_rx hook) -------------------------------
def observe_rx_time(
self,
from_stage: int,
from_replica: int,
to_stage: int,
to_replica: int,
rx_time_s: float,
) -> None:
if not self._log_stats:
return
_transfer_rx_family.labels(
model_name=self._model_name,
from_stage=str(from_stage),
from_replica=str(from_replica),
to_stage=str(to_stage),
to_replica=str(to_replica),
).observe(rx_time_s)
def observe_in_flight_time(
self,
from_stage: int,
from_replica: int,
to_stage: int,
to_replica: int,
in_flight_time_s: float,
) -> None:
if not self._log_stats:
return
_transfer_in_flight_family.labels(
model_name=self._model_name,
from_stage=str(from_stage),
from_replica=str(from_replica),
to_stage=str(to_stage),
to_replica=str(to_replica),
).observe(in_flight_time_s)
+38
View File
@@ -1,3 +1,4 @@
import logging
import sys
from functools import cached_property
@@ -129,6 +130,43 @@ for module_name, module in list(sys.modules.items()):
if hasattr(module, "EngineCoreRequest") and module.EngineCoreRequest == _OriginalEngineCoreRequest:
module.EngineCoreRequest = OmniEngineCoreRequest
# =============================================================================
# Patch unregister_vllm_metrics to skip vllm:omni_* collectors
# =============================================================================
# WHY: Upstream unregister_vllm_metrics() uses `"vllm" in collector._name` to
# strip collectors before each new PrometheusStatLogger registers, which is
# how it avoids "Duplicated timeseries" when the same process spawns multiple
# engines / orchestrators. But its substring match also wipes our vllm:omni_*
# families, so we must replace it with a scoped version that keeps ours.
#
# REMOVAL: Remove this patch once upstream vLLM adds
# _STAT_LOGGER_METRIC_NAMES to vllm.v1.metrics.prometheus and scopes
# unregister_vllm_metrics() to that set. Track:
# https://github.com/vllm-project/vllm/pull/42331
import vllm.v1.metrics.prometheus as _vllm_prometheus # noqa: E402
_logger = logging.getLogger(__name__)
def _scoped_unregister_vllm_metrics():
"""Drop upstream vllm:* collectors but preserve vllm:omni_* (ours)."""
from prometheus_client import REGISTRY
for collector in list(REGISTRY._collector_to_names):
name = getattr(collector, "_name", "")
if "vllm" not in name:
continue
if name.startswith("vllm:omni_") or name.startswith("vllm_omni"):
continue
REGISTRY.unregister(collector)
_vllm_prometheus.unregister_vllm_metrics = _scoped_unregister_vllm_metrics
_logger.warning(
"Monkey-patched unregister_vllm_metrics() to scope drops to non-omni vllm:* collectors. "
"Remove this patch once vLLM adds _STAT_LOGGER_METRIC_NAMES."
)
# Patch: add qwen3_omni_moe to vllm's chat template fallback registry.
# Qwen/Qwen3-Omni-30B-A3B-Instruct stores its chat_template in a standalone
+39
View File
@@ -7,6 +7,9 @@ import numpy as np
import torch
from torchaudio.functional import melscale_fbanks
from vllm_omni.metrics import definitions as _metric_defs
from vllm_omni.outputs import OmniRequestOutput
def mel_filter_bank(
sr: int,
@@ -66,3 +69,39 @@ def peak_normalize(
return audio
target = 10.0 ** (db_level / 20.0)
return audio * (target / peak)
def audio_chunk_pcm_bytes(omni_res: OmniRequestOutput) -> int:
"""Best-effort PCM byte count of the last audio chunk in ``omni_res``.
Used by the audio-streaming continuity tracker to size the player buffer.
Returns 0 when the chunk shape can't be interpreted — caller drops the
sample rather than recording a wrong byte count.
"""
try:
final_res = omni_res.request_output
mm_output = final_res.outputs[0].multimodal_output
audio_data = mm_output.get("audio")
if isinstance(audio_data, list):
if not audio_data:
return 0
audio_tensor = audio_data[-1]
else:
audio_tensor = audio_data
if audio_tensor is None:
return 0
n_samples = int(audio_tensor.numel() if hasattr(audio_tensor, "numel") else audio_tensor.size)
# PCM s16le mono → 2 bytes per sample. This matches what
# _create_audio_choice serialises via CreateAudio (response_format="wav").
return max(n_samples, 0) * 2
except Exception:
return 0
def audio_chunk_sample_rate(omni_res: OmniRequestOutput) -> int:
"""Resolve audio sample rate for the request's audio stream."""
try:
mm_output = omni_res.request_output.outputs[0].multimodal_output
except Exception:
return _metric_defs.DEFAULT_AUDIO_SAMPLE_RATE
return _metric_defs.resolve_audio_sample_rate(mm_output)