[BugFix][Metrics] Fix per-stage time and token stats in metrics API (#4974)

Signed-off-by: akshatvishu <akshatnayak197@gmail.com>
This commit is contained in:
akshatvishu authored and GitHub committed 2026-08-01 03:54:17 +00:00
1 parent 8cb79308c6
commit cd5daaea6a
18 files changed
+618 -78

No files matched your search

@@ -56,6 +56,24 @@ class OmniGenerationScheduler(OmniSchedulerMixin, VLLMScheduler):
)
self._latest_omni_connector_output: OmniConnectorOutput | None = None
@staticmethod
def _record_prefill_stats(request: Request) -> None:
"""Mirror upstream first-prefill prompt accounting for generation stages.
Async-chunk generation stages can grow ``prompt_token_ids`` after the
first schedule; until this path tracks final chunk lengths, this records
the first scheduled prompt snapshot. Keep this in sync with vLLM
Scheduler.schedule() if this fast path gains prefix-cache or external-KV
accounting.
"""
if request.prefill_stats is None:
return
request.prefill_stats.set(
num_prompt_tokens=request.num_prompt_tokens,
num_local_cached_tokens=0,
num_external_cached_tokens=0,
)
def _handle_stopped_request(self, request: Request) -> bool:
if (
request.resumable
@@ -147,6 +165,8 @@ class OmniGenerationScheduler(OmniSchedulerMixin, VLLMScheduler):
break
if self.log_stats:
request.record_event(EngineCoreEventType.SCHEDULED, scheduled_timestamp)
if num_computed_tokens == 0:
self._record_prefill_stats(request)
req_to_new_blocks[request.request_id] = new_blocks
num_scheduled_tokens[request.request_id] = num_new_tokens
cached_prompt_token_ids[request.request_id] = request.prompt_token_ids
@@ -213,6 +233,8 @@ class OmniGenerationScheduler(OmniSchedulerMixin, VLLMScheduler):
self.running.append(request)
if self.log_stats:
request.record_event(EngineCoreEventType.SCHEDULED, scheduled_timestamp)
if request.num_computed_tokens == 0:
self._record_prefill_stats(request)
req_to_new_blocks[request.request_id] = new_blocks
num_scheduled_tokens[request.request_id] = num_new_tokens
@@ -7,6 +7,7 @@ from collections.abc import Callable, Mapping
from typing import Any
import torch
from vllm.v1.metrics.stats import PrefillStats
from vllm.v1.request import Request, RequestStatus
from vllm_omni.data_entry_keys import MetaStruct, OmniPayloadStruct, unflatten_payload
@@ -109,6 +110,12 @@ class OmniChunkTransferAdapter(OmniTransferAdapterBase):
num_placeholders = int(getattr(request, "num_output_placeholders", 0) or 0)
return max(0, num_computed - num_placeholders)
@staticmethod
def _refresh_generation_chunk_prefill_state(request: Request) -> None:
request.num_prompt_tokens = len(request.prompt_token_ids)
if getattr(request, "prefill_stats", None) is None:
request.prefill_stats = PrefillStats()
@classmethod
def create_connector(cls, model_config: Any):
connector_config = getattr(model_config, "stage_connector_config", None)
@@ -249,15 +256,18 @@ class OmniChunkTransferAdapter(OmniTransferAdapterBase):
new_ids = payload_data.get("codes", {}).get("audio")
has_tensor_codes = isinstance(new_ids, torch.Tensor)
use_tensor_codes = has_tensor_codes and new_ids.ndim >= 2
prompt_token_ids: list[int]
if use_tensor_codes:
request.prompt_token_ids = [0] if new_ids.numel() > 0 else []
prompt_token_ids = [0] if new_ids.numel() > 0 else []
elif has_tensor_codes:
new_ids = new_ids.tolist()
prompt_token_ids = new_ids
elif new_ids is None:
new_ids = []
request.prompt_token_ids = new_ids
if not use_tensor_codes:
request.prompt_token_ids = new_ids
prompt_token_ids = new_ids
else:
prompt_token_ids = new_ids
request.prompt_token_ids = prompt_token_ids
prev_info = getattr(request, "additional_information", None)
info = dict(prev_info) if isinstance(prev_info, dict) else {}
for key, value in payload_data.items():
@@ -293,6 +303,7 @@ class OmniChunkTransferAdapter(OmniTransferAdapterBase):
# chunk as ready, otherwise Stage1 can consume before the
# first DAC frame arrives.
return False
self._refresh_generation_chunk_prefill_state(request)
# Mark as finished for consumption
self._finished_load_reqs.add(req_id)
+1
View File
@@ -331,6 +331,7 @@ class AsyncOmniEngine:
omni_heartbeat_timeout=self._omni_heartbeat_timeout,
omni_lb_policy=self._omni_lb_policy,
request_queue=self.request_queue,
log_stats=self._log_stats,
)
self._runtime.initialize()
+11 -9
View File
@@ -362,6 +362,7 @@ class Orchestrator:
self.async_chunk = bool(async_chunk)
self.num_stages = len(stage_pools)
self.stage_pools: list[StagePool] = stage_pools
self.log_stats = log_stats
self._orch_monitor = create_orch_monitor(
enabled=enable_orch_monitor,
replica_sampler=self._sample_replica_metrics,
@@ -446,7 +447,10 @@ class Orchestrator:
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.
when the user did not request stats. When stats are enabled, record()
must still receive IterationStats even on ticks where scheduler_stats
is None; upstream PrometheusStatLogger records token/request metrics
from iteration_stats independently of scheduler gauges.
"""
self._running_counter = running_counter
self._transfer_emitter = transfer_emitter
@@ -937,19 +941,17 @@ class Orchestrator:
)
if req_state.streaming.enabled:
await self._apply_raw_terminal_stage_finish(stage_id, eco, req_state)
# 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
iteration_stats = (
IterationStats() if (self._stat_logger is not None and raw_outputs.outputs) else None
)
raw_output = await pool.process_llm_raw_outputs(
replica_id,
raw_outputs,
iteration_stats=iteration_stats,
)
if record_stats:
if self._stat_logger is not None and (
raw_outputs.scheduler_stats is not None or iteration_stats is not None
):
self._stat_logger.record(
raw_outputs.scheduler_stats,
iteration_stats,
+5 -2
View File
@@ -1081,7 +1081,11 @@ class StagePool:
async def _poll_stage_raw(self, client: StagePoolLLMClient) -> EngineCoreOutputs | None:
"""Pull raw EngineCoreOutputs from a stage replica without processing."""
outputs = await client.get_output_async()
if not outputs.outputs:
# Keep scheduler-only / finished-only batches. Omni schedulers mirror
# upstream by emitting SchedulerStats on throttled ticks even when no
# request output is produced, and dropping those batches loses KV/queue
# gauges for that interval.
if not outputs.outputs and outputs.scheduler_stats is None and not outputs.finished_requests:
return None
return outputs
@@ -1097,7 +1101,6 @@ class StagePool:
return []
client = cast(StagePoolLLMClient, raw_client)
processor = self.output_processor
iteration_stats = IterationStats()
processed = processor.process_outputs(
raw_outputs.outputs,
raw_outputs.timestamp,
+16 -3
View File
@@ -126,6 +126,7 @@ class StageRuntime:
diffusion_batch_size: int,
async_chunk: bool,
tokenizer: str | None = None,
log_stats: bool = False,
) -> None:
self._stage_configs = stage_configs
self._model = model
@@ -134,6 +135,7 @@ class StageRuntime:
self._diffusion_batch_size = diffusion_batch_size
self._async_chunk = async_chunk
self._tokenizer = tokenizer
self._log_stats = log_stats
self._num_stages = len(stage_configs)
# Populated by initialize()
@@ -575,7 +577,7 @@ class StageRuntime:
with launch_stage_replica(
vllm_config=vllm_config,
executor_class=executor_class,
log_stats=False,
log_stats=self._log_stats,
stage_id=plan.metadata.stage_id,
replica_id=plan.replica_id,
stage_config=plan.stage_cfg,
@@ -594,6 +596,7 @@ class StageRuntime:
stage_client = StageEngineCoreClientBase.make_async_mp_client(
vllm_config=vllm_config,
executor_class=executor_class,
log_stats=self._log_stats,
metadata=plan.metadata,
client_addresses=self._client_addresses_from_zmq(resources.addresses),
engine_manager=resources.manager,
@@ -704,7 +707,11 @@ class StageRuntime:
stage_vllm_config = plan.replicas[0].stage_vllm_config
if stage_vllm_config is None:
raise RuntimeError(f"Stage {plan.stage_id} is missing vllm_config")
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(
@@ -742,10 +749,11 @@ class DistStageRuntime(StageRuntime):
stage_init_timeout: int,
diffusion_batch_size: int,
async_chunk: bool,
tokenizer: str | None = None,
single_stage_id_filter: int | None,
omni_master_address: str,
omni_master_port: int,
tokenizer: str | None = None,
log_stats: bool = False,
omni_dp_size_local: int = 1,
omni_heartbeat_timeout: float = 30.0,
omni_lb_policy: str = "random",
@@ -759,6 +767,7 @@ class DistStageRuntime(StageRuntime):
diffusion_batch_size=diffusion_batch_size,
async_chunk=async_chunk,
tokenizer=tokenizer,
log_stats=log_stats,
)
self._single_stage_id_filter = single_stage_id_filter
self._omni_master_address = omni_master_address
@@ -1051,6 +1060,7 @@ class DistStageRuntime(StageRuntime):
client = StageEngineCoreClientBase.make_async_mp_client(
vllm_config=vllm_config,
executor_class=ctx.executor_class,
log_stats=self._log_stats,
metadata=metadata,
client_addresses=client_addresses,
engine_manager=resources.manager,
@@ -1089,6 +1099,7 @@ def create_stage_runtime(
omni_heartbeat_timeout: float = 30.0,
omni_lb_policy: str = "random",
request_queue: janus.Queue[EngineQueueMessage] | None = None,
log_stats: bool = False,
) -> StageRuntime:
"""Factory: select StageRuntime or DistStageRuntime."""
if single_stage_mode:
@@ -1102,6 +1113,7 @@ def create_stage_runtime(
diffusion_batch_size=diffusion_batch_size,
async_chunk=async_chunk,
tokenizer=tokenizer,
log_stats=log_stats,
single_stage_id_filter=single_stage_id_filter,
omni_master_address=omni_master_address,
omni_master_port=omni_master_port,
@@ -1118,4 +1130,5 @@ def create_stage_runtime(
diffusion_batch_size=diffusion_batch_size,
async_chunk=async_chunk,
tokenizer=tokenizer,
log_stats=log_stats,
)
+1
View File
@@ -612,6 +612,7 @@ class OmniBase(PDDisaggregationMixin):
request_id=req_id or "",
finished=finished,
stage_id=stage_id,
replica_id=result.replica_id,
final_output_type=output_type,
request_output=engine_outputs,
images=images,
+13 -9
View File
@@ -2062,15 +2062,19 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
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
)
replica_id = getattr(omni_res, "replica_id", None)
if replica_id is None:
stage_pools = getattr(self.engine_client.engine, "stage_pools", None)
# Fallback for older outputs. The orchestrator binds
# requests by internal id, but can release that
# binding before the API sees the final audio chunk,
# so prefer the OutputMessage replica copied onto
# OmniRequestOutput above.
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(
+4
View File
@@ -83,6 +83,7 @@ class OmniRequestOutput:
request_id: Unique identifier for this request
finished: Whether generation is complete
stage_id: Identifier of the stage that produced this output (pipeline mode)
replica_id: Identifier of the stage replica that produced this output
final_output_type: Type of output ("text", "image", "audio", "latents")
request_output: The underlying RequestOutput from the stage (pipeline mode)
images: List of generated PIL images (diffusion mode)
@@ -96,6 +97,7 @@ class OmniRequestOutput:
# Pipeline stage fields
stage_id: int | None = None
replica_id: int | None = None
final_output_type: str = "text"
request_output: RequestOutput | None = None
@@ -154,6 +156,7 @@ class OmniRequestOutput:
stage_id: int,
final_output_type: str,
request_output: RequestOutput,
replica_id: int | None = None,
) -> "OmniRequestOutput":
"""Create output from pipeline stage.
@@ -168,6 +171,7 @@ class OmniRequestOutput:
return cls(
request_id=getattr(request_output, "request_id", ""),
stage_id=stage_id,
replica_id=replica_id,
final_output_type=final_output_type,
request_output=request_output,
finished=True,
+22 -2
View File
@@ -523,7 +523,11 @@ class MultimodalOutputProcessor(VLLMOutputProcessor):
upstream_outputs.append(eco)
# Handle multimodal-only outputs (generation stages) locally.
mm_request_outputs = self._process_mm_only_outputs(mm_only_outputs)
mm_request_outputs = self._process_mm_only_outputs(
mm_only_outputs,
engine_core_timestamp=engine_core_timestamp,
iteration_stats=iteration_stats,
)
# Delegate text/pooling outputs to upstream.
processed = super().process_outputs(
@@ -537,6 +541,9 @@ class MultimodalOutputProcessor(VLLMOutputProcessor):
def _process_mm_only_outputs(
self,
engine_core_outputs: list[EngineCoreOutput],
*,
engine_core_timestamp: float | None = None,
iteration_stats: IterationStats | None = None,
) -> list[OmniRequestOutput | PoolingRequestOutput]:
"""Handle outputs from generation stages that have no detokenizer.
@@ -554,7 +561,15 @@ class MultimodalOutputProcessor(VLLMOutputProcessor):
stop_reason = eco.stop_reason
kv_transfer_params = eco.kv_transfer_params
routed_experts = eco.routed_experts
req_state.num_cached_tokens = eco.num_cached_tokens
self._update_stats_from_output(
req_state,
eco,
engine_core_timestamp,
iteration_stats,
)
prefill_stats = getattr(eco, "prefill_stats", None)
if prefill_stats is not None:
req_state.num_cached_tokens = prefill_stats.num_cached_tokens
req_state.is_prefilling = False
is_non_final_audio_chunk = (
@@ -578,6 +593,11 @@ class MultimodalOutputProcessor(VLLMOutputProcessor):
is_segment_finished = bool(getattr(eco, "is_segment_finished", False))
if finish_reason is not None and not is_segment_finished and not is_non_final_audio_chunk:
self._finish_request(req_state)
self._update_stats_from_finished(
req_state,
finish_reason,
iteration_stats,
)
return request_outputs
def _update_stats_from_output(