text and image metric (#6150)

Signed-off-by: zhuhh97 <zhuhonghan@huawei.com>
Signed-off-by: Gao Han <hgaoaf@connect.ust.hk>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
Co-authored-by: Gao Han <hgaoaf@connect.ust.hk>
This commit is contained in:
authored and GitHub committed 2026-08-26 02:54:45 +00:00
1 parent aeb348d8f8
commit 7ae15c74c8
33 files changed
+1802 -162

No files matched your search

@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Source-level regression tests for diffusion output/engine helpers.
These tests verify naming conventions and patterns by inspecting source code
@@ -37,10 +37,50 @@ _FORMATTER_PATH = os.path.normpath(
"output_formatter.py",
)
)
_METRICS_PATH = os.path.normpath(
os.path.join(
os.path.dirname(__file__),
os.pardir,
os.pardir,
"vllm_omni",
"metrics",
"utils.py",
)
)
_INLINE_CLIENT_PATH = os.path.normpath(
os.path.join(
os.path.dirname(__file__),
os.pardir,
os.pardir,
"vllm_omni",
"diffusion",
"inline_stage_diffusion_client.py",
)
)
_STAGE_PROC_PATH = os.path.normpath(
os.path.join(
os.path.dirname(__file__),
os.pardir,
os.pardir,
"vllm_omni",
"diffusion",
"stage_diffusion_proc.py",
)
)
_ORCHESTRATOR_PATH = os.path.normpath(
os.path.join(
os.path.dirname(__file__),
os.pardir,
os.pardir,
"vllm_omni",
"engine",
"orchestrator.py",
)
)
def _read_source(path: str) -> str:
with open(path) as f:
with open(path, encoding="utf-8") as f:
return f.read()
@@ -100,9 +140,99 @@ class TestMetricKeys:
raise AssertionError("diffusion_engine_total_time_ms should be attached in step_streaming()")
assert '"diffusion_engine_exec_time_ms": exec_total_time * 1000' in step_streaming_source
assert '"diffusion_engine_total_time_ms": step_total_ms' in step_streaming_source
# step_total_ms is no longer emitted as a metric (no family consumes
# it); it lives only in the debug log breakdown below.
assert '"diffusion_engine_total_time_ms"' not in step_streaming_source
assert '"postprocess_time_ms": postprocess_time * 1000' in step_streaming_source
def test_step_streaming_piggybacks_scheduler_waiting_snapshot(self) -> None:
source = _read_source(_ENGINE_PATH)
step_streaming_source = _get_function_source(source, "DiffusionEngine", "step_streaming")
assert "diffusion_scheduler_waiting_metrics(" in step_streaming_source
assert "_scheduler_num_waiting_reqs" in step_streaming_source
def test_step_streaming_preserves_snapshot_on_postprocess_error(self) -> None:
source = _read_source(_ENGINE_PATH)
step_streaming_source = _get_function_source(source, "DiffusionEngine", "step_streaming")
assert "scheduler_metrics = diffusion_scheduler_waiting_metrics(" in step_streaming_source
assert 'setattr(exc, "diffusion_metrics", scheduler_metrics)' in step_streaming_source
assert step_streaming_source.index("scheduler_metrics =") < step_streaming_source.index(
"self.postprocess_output("
)
def test_abort_keeps_output_consumers_alive_for_terminal_snapshot(self) -> None:
inline_source = _read_source(_INLINE_CLIENT_PATH)
abort_source = _get_function_source(inline_source, "InlineStageDiffusionClient", "abort_requests_async")
assert ".cancel(" not in abort_source
proc_source = _read_source(_STAGE_PROC_PATH)
run_loop_source = _get_function_source(proc_source, "StageDiffusionProc", "run_loop")
abort_branch = run_loop_source[run_loop_source.index('elif msg_type == "abort":') :]
abort_branch = abort_branch[: abort_branch.index('elif msg_type == "collective_rpc":')]
assert ".cancel(" not in abort_branch
def test_orchestrator_consumes_metrics_only_output_without_routing(self) -> None:
source = _read_source(_ORCHESTRATOR_PATH)
loop_source = _get_function_source(source, "Orchestrator", "_orchestration_loop")
snapshot_pos = loop_source.index("_update_stage_replica_waiting(")
sentinel_pos = loop_source.index("diffusion_output.request_id == DIFFUSION_METRICS_ONLY_REQUEST_ID")
route_pos = loop_source.index("pool.record_output_timestamps([diffusion_output])")
assert snapshot_pos < sentinel_pos < route_pos
class TestVaeDecodeEmit:
"""VAE decode timing is sourced from ``DiffusionOutput.stage_durations``
(populated by the diffusion pipeline profiler) and emitted as
``vae_decode_time_ms`` so the ``_MS_TO_S`` accumulator picks it up.
"""
def test_extract_vae_decode_ms_helper_exists(self) -> None:
source = _read_source(_METRICS_PATH)
helper_src = _get_function_source(source, None, "extract_diffusion_vae_decode_ms")
assert ".vae.decode" in helper_src, "helper must key on the '.vae.decode' suffix"
def test_step_streaming_emits_vae_decode_time_ms(self) -> None:
source = _read_source(_ENGINE_PATH)
step_streaming_source = _get_function_source(source, "DiffusionEngine", "step_streaming")
assert "extract_diffusion_vae_decode_ms(" in step_streaming_source, (
"step_streaming must call extract_diffusion_vae_decode_ms to source VAE decode timing"
)
assert '"vae_decode_time_ms"' in step_streaming_source, (
"step_streaming must emit vae_decode_time_ms key for the _MS_TO_S accumulator"
)
class TestDiffuseForwardEmit:
"""Forward-only timing → forward_time_ms, mirroring TestVaeDecodeEmit."""
def test_extract_diffuse_ms_helper_exists(self) -> None:
source = _read_source(_METRICS_PATH)
helper_src = _get_function_source(source, None, "extract_diffusion_denoise_ms")
assert ".diffuse" in helper_src, "helper must key on the '.diffuse' suffix"
def test_step_streaming_emits_forward_time_ms(self) -> None:
source = _read_source(_ENGINE_PATH)
step_streaming_source = _get_function_source(source, "DiffusionEngine", "step_streaming")
assert "extract_diffusion_denoise_ms(" in step_streaming_source, (
"step_streaming must call extract_diffusion_denoise_ms to source forward-only timing"
)
assert '"forward_time_ms"' in step_streaming_source, (
"step_streaming must emit forward_time_ms key for the _MS_TO_S accumulator"
)
class TestKvRecvEmit:
"""KV-recv timing → kv_recv_time_ms, sourced from DiffusionOutput.kv_recv_ms
(set by the runner's _prepare_request_for_forward, not the profiler)."""
def test_step_streaming_emits_kv_recv_time_ms(self) -> None:
source = _read_source(_ENGINE_PATH)
step_streaming_source = _get_function_source(source, "DiffusionEngine", "step_streaming")
assert "kv_recv_ms" in step_streaming_source, "step_streaming must read output.kv_recv_ms"
assert '"kv_recv_time_ms"' in step_streaming_source, (
"step_streaming must emit kv_recv_time_ms key for the _MS_TO_S accumulator"
)
class TestDummyRunAllocation:
"""Verify _dummy_run generates exact-sized audio arrays."""
@@ -773,6 +773,19 @@ class TestRequestScheduler:
assert third.num_running_reqs == 1
assert third.num_waiting_reqs == 0
def test_records_initial_scheduler_queue_wait(self, mocker: MockerFixture) -> None:
perf_counter = mocker.patch(
"vllm_omni.diffusion.sched.base_scheduler.time.perf_counter",
side_effect=[10.0, 10.125],
)
request = _make_step_request("queue-wait", num_inference_steps=2)
self.scheduler.add_request(request)
self.scheduler.schedule()
assert request.scheduler_queue_wait_ms == pytest.approx(125.0)
assert perf_counter.call_count == 2
def test_batches_compatible_requests_up_to_max_num_seqs(self) -> None:
scheduler = RequestScheduler()
scheduler.initialize(SimpleNamespace(max_num_seqs=2))
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
import asyncio
import multiprocessing as mp
@@ -1079,6 +1079,42 @@ class TestStageDiffusionClientErrorPropagation:
assert client.get_diffusion_output_nowait() is None
def test_error_response_preserves_scheduler_metrics(self):
from vllm_omni.metrics import definitions as metric_defs
client = self._make_client()
client._response_socket.recv.side_effect = [b"message", zmq.Again()]
client._decoder.decode.return_value = {
"type": "error",
"request_id": "req-error",
"error": "gpu fault",
"metrics": {metric_defs.DIFFUSION_SCHEDULER_WAITING_KEY: 0},
}
output = client.get_diffusion_output_nowait()
assert output is not None
assert output.error == "gpu fault"
assert output.metrics[metric_defs.DIFFUSION_SCHEDULER_WAITING_KEY] == 0
def test_metrics_response_creates_metrics_only_output(self):
from vllm_omni.metrics import definitions as metric_defs
from vllm_omni.metrics.utils import DIFFUSION_METRICS_ONLY_REQUEST_ID
client = self._make_client()
client._response_socket.recv.side_effect = [b"message", zmq.Again()]
client._decoder.decode.return_value = {
"type": "metrics",
"metrics": {metric_defs.DIFFUSION_SCHEDULER_WAITING_KEY: 0},
}
output = client.get_diffusion_output_nowait()
assert output is not None
assert output.request_id == DIFFUSION_METRICS_ONLY_REQUEST_ID
assert output.error is None
assert output.metrics[metric_defs.DIFFUSION_SCHEDULER_WAITING_KEY] == 0
def test_check_health_raises_when_proc_dead(self):
"""``check_health`` detects a dead subprocess via the manager's proc
and raises ``EngineDeadError``, setting ``_engine_dead`` as a
+22 -2
View File
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
@@ -47,6 +47,7 @@ class FakePool:
self.invalidated = []
self.hub = None
self.lb = None
self.replica_ids = {}
def attach_hub(self, hub):
self.hub = hub
@@ -57,7 +58,9 @@ class FakePool:
def add_client(self, input_addr, client, *, replica_id=None):
self.added.append((input_addr, client, replica_id))
self.clients.append(client)
return len(self.clients) - 1 if replica_id is None else replica_id
resolved_replica_id = len(self.clients) - 1 if replica_id is None else replica_id
self.replica_ids[input_addr] = resolved_replica_id
return resolved_replica_id
def invalidate_addr(self, input_addr):
self.invalidated.append(input_addr)
@@ -67,6 +70,12 @@ class FakePool:
self.removed.append(input_addr)
return SimpleNamespace(shutdown=lambda: self.removed.append("shutdown"))
def get_client_by_addr(self, input_addr):
return SimpleNamespace() if input_addr in self.replica_ids else None
def get_replica_id_by_addr(self, input_addr):
return self.replica_ids.get(input_addr)
def _snapshot(*replicas):
return SimpleNamespace(replicas=list(replicas))
@@ -209,6 +218,16 @@ async def test_unregister_then_register_restores_coordinator_replica_slot(monkey
return replacement
controller = _controller(monkeypatch, pool, FakeHub(), remote_replica_factory=factory)
removed_replicas = []
async def cleanup(_request_ids):
return None
controller.install_unregister_handlers(
output_queue=asyncio.Queue(),
cleanup_callback=cleanup,
replica_removed_callback=lambda stage_id, replica_id: removed_replicas.append((stage_id, replica_id)),
)
await controller.handle_unregister(0, "tcp://old-0")
await controller.handle_unregister(0, "tcp://old-1")
@@ -219,6 +238,7 @@ async def test_unregister_then_register_restores_coordinator_replica_slot(monkey
assert pool.get_replica_id_by_addr("tcp://new-1") == 1
assert pool.get_replica_id_by_addr("tcp://old-1") is None
assert pool.available_replica_ids() == [1]
assert removed_replicas == [(0, 0), (0, 1)]
@pytest.mark.asyncio
+25
View File
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
import asyncio
@@ -2063,6 +2066,28 @@ def test_stage_pool_metrics_use_resumable_segment_token_count() -> None:
assert metrics.output_unit_count == 3
def test_image_ttfo_preserves_request_time_and_tracks_stage_time() -> None:
stage = FakeStageClient(stage_type="diffusion", final_output=True, final_output_type="image")
pool = StagePool(
1,
[stage],
output_processor=FakeOutputProcessor(),
stage_vllm_config=SimpleNamespace(model_config=SimpleNamespace(max_model_len=64)),
)
output = SimpleNamespace(request_id="req-image", _custom_output={"image": "non-empty"})
pool.record_output_timestamps([output], output_ts=132.0)
metrics = pool.build_stage_metrics(
[output],
submit_ts=130.0,
request_timestamp=120.0,
replica_id=0,
)
assert metrics.serving_time_to_first_output_ms == pytest.approx(12000.0)
assert metrics.image_time_to_first_output_ms == pytest.approx(2000.0)
@pytest.mark.asyncio
async def test_stage_pool_submit_initial_rolls_back_output_processor_when_client_submit_fails() -> None:
class FailingStageClient(FakeStageClient):
@@ -611,7 +611,13 @@ async def test_async_omni_abort_forwards_to_engine(monkeypatch: pytest.MonkeyPat
# external ID to avoid collisions, so this also tests mapping
external_req_id = "req-1"
req_id = "req-1-12345678"
recorded_failures = []
try:
monkeypatch.setattr(
app,
"_record_request_failure_once",
lambda request_id, reason: recorded_failures.append((request_id, reason)),
)
app.request_states[req_id] = ClientRequestState(
request_id=req_id,
external_request_id=external_req_id,
@@ -622,6 +628,7 @@ async def test_async_omni_abort_forwards_to_engine(monkeypatch: pytest.MonkeyPat
assert engine.aborted == [[req_id]]
assert external_req_id not in app.request_states
assert recorded_failures == [(req_id, "client_abort")]
@pytest.mark.asyncio
@@ -814,7 +821,13 @@ def test_omni_abort_forwards_to_engine(monkeypatch: pytest.MonkeyPatch):
_patch_engine(monkeypatch, engine)
app = Omni("dummy-model")
recorded_failures = []
try:
monkeypatch.setattr(
app,
"_record_request_failure_once",
lambda request_id, reason: recorded_failures.append((request_id, reason)),
)
app.request_states["req-1"] = object()
app.abort("req-1")
finally:
@@ -822,6 +835,7 @@ def test_omni_abort_forwards_to_engine(monkeypatch: pytest.MonkeyPatch):
assert engine.aborted == [["req-1"]]
assert "req-1" not in app.request_states
assert recorded_failures == [("req-1", "client_abort")]
def test_omni_forces_final_only_on_llm_stages(monkeypatch: pytest.MonkeyPatch):
+499
View File
@@ -0,0 +1,499 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Verify emit-call wiring in production code paths.
Uses behavior and Prometheus exposition to verify production call semantics.
"""
from __future__ import annotations
import time
from types import SimpleNamespace
from typing import TYPE_CHECKING
import pytest
from vllm_omni.metrics import OmniPrometheusMetrics
from vllm_omni.metrics import definitions as defs
if TYPE_CHECKING:
from vllm_omni.core.sched.omni_ar_scheduler import OmniARScheduler
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
_MODEL = "emit-calls-test"
# ---------------------------------------------------------------------------
# Behavioral pins — verify call semantics with mock OmniPrometheusMetrics.
# ---------------------------------------------------------------------------
def _make_omni_base_with_mock_prom(mocker):
"""Build a minimal OmniBase shell wired with a mock prom_metrics.
Mirrors the pattern in ``test_prometheus.py::TestRequestLifecycleGauges``
— ``object.__new__`` skips ``__init__`` so we don't need a real engine.
"""
from vllm_omni.entrypoints.omni_base import OmniBase
obj = object.__new__(OmniBase)
obj.prom_metrics = mocker.Mock(spec=OmniPrometheusMetrics)
obj.request_states = {}
obj._consumed_metric_messages = {}
obj.log_stats = True
return obj, obj.prom_metrics
class TestFailureCounterWiring:
"""All failure paths share one request-idempotent counter helper."""
def test_failure_reason_taxonomy_is_bounded(self) -> None:
from vllm_omni.metrics.utils import normalize_failure_reason
assert normalize_failure_reason("client_abort") == "client_abort"
assert normalize_failure_reason("client_disconnect") == "client_disconnect"
assert normalize_failure_reason("stage_error") == "stage_error"
assert normalize_failure_reason("unknown") == "unknown"
assert normalize_failure_reason("timeout for request req-1") == "unknown"
assert normalize_failure_reason("") == "unknown"
assert normalize_failure_reason(None) == "unknown"
def test_fire_failure_counter_passes_reason_through(self, mocker) -> None:
obj, prom = _make_omni_base_with_mock_prom(mocker)
obj.request_states["req-1"] = SimpleNamespace(
metrics=SimpleNamespace(e2e_done=set()),
failure_recorded=False,
)
obj._record_request_failure_once("req-1", reason="client_disconnect")
prom.request_failed.assert_called_once()
prom.inc_requests_failed.assert_called_once_with("client_disconnect")
def test_fire_failure_counter_normalizes_unrecognized_reason(self, mocker) -> None:
obj, prom = _make_omni_base_with_mock_prom(mocker)
obj.request_states["req-1"] = SimpleNamespace(
metrics=SimpleNamespace(e2e_done=set()),
failure_recorded=False,
)
obj._record_request_failure_once("req-1", reason="CUDA error for req-1")
prom.inc_requests_failed.assert_called_once_with("unknown")
def test_fire_failure_counter_skips_when_request_already_succeeded(self, mocker) -> None:
# When the request is in e2e_done (i.e. finalize already fired
# request_succeeded), the failure path must NOT double-count.
obj, prom = _make_omni_base_with_mock_prom(mocker)
obj.request_states["req-1"] = SimpleNamespace(
metrics=SimpleNamespace(e2e_done={"req-1"}),
failure_recorded=False,
)
obj._record_request_failure_once("req-1", reason="client_disconnect")
prom.request_failed.assert_not_called()
prom.inc_requests_failed.assert_not_called()
def test_fire_failure_counter_skips_when_request_state_missing(self, mocker) -> None:
# No request_states entry — already popped by abort path. Fail-safe
# must NOT raise.
obj, prom = _make_omni_base_with_mock_prom(mocker)
obj._record_request_failure_once("missing-req", reason="oom")
prom.request_failed.assert_not_called()
prom.inc_requests_failed.assert_not_called()
def test_failure_counter_is_idempotent_across_abort_and_cleanup(self, mocker) -> None:
obj, prom = _make_omni_base_with_mock_prom(mocker)
obj.request_states["req-1"] = SimpleNamespace(
metrics=SimpleNamespace(
e2e_done=set(),
build_and_log_summary=lambda: None,
),
failure_recorded=False,
)
obj._record_request_failure_once("req-1", reason="client_disconnect")
obj._log_summary_and_cleanup("req-1", reason="stage_error")
prom.request_failed.assert_called_once()
prom.inc_requests_failed.assert_called_once_with("client_disconnect")
def test_log_summary_and_cleanup_default_reason(self, mocker) -> None:
obj, prom = _make_omni_base_with_mock_prom(mocker)
obj.request_states["req-1"] = SimpleNamespace(
metrics=SimpleNamespace(
e2e_done=set(),
build_and_log_summary=lambda: None,
),
failure_recorded=False,
)
obj._log_summary_and_cleanup("req-1")
prom.inc_requests_failed.assert_called_once_with("stage_error")
class TestEarlyReturnOnLogStatsOff:
"""When --log-stats is off (default), observe methods must be silent no-ops.
This is the gating contract — emit sites can call unconditionally and the
helper short-circuits.
"""
def test_observe_methods_silent_when_log_stats_false(self) -> None:
prom = OmniPrometheusMetrics(model_name=_MODEL, log_stats=False)
# None of these should raise or write to the registry.
prom.observe_stage_gen_time(stage=0, stage_type="llm", gen_time_s=1.5)
prom.observe_stage_in_queue(stage=0, in_queue_s=0.2)
prom.observe_queue_wait(queue_wait_s=0.5)
prom.set_stage_waiting_requests(stage=0, n_waiting=3)
prom.observe_num_inference_steps(n_steps=20)
prom.inc_image_count(n_images=1)
prom.observe_image_pixels(n_pixels=512 * 512)
prom.set_peak_memory(stage=0, peak_memory_mb=1024.0)
prom.inc_requests_failed(reason="oom")
prom.observe_kv_wait(connector_type="shm", kv_wait_s=0.01)
class TestStageGenerationLabels:
def test_stage_gen_time_exposes_bounded_stage_type(self) -> None:
from prometheus_client import REGISTRY, generate_latest
model = _MODEL + "-stage-type"
prom = OmniPrometheusMetrics(model_name=model, log_stats=True)
prom.observe_stage_gen_time(stage=0, stage_type="llm", gen_time_s=0.25)
prom.observe_stage_gen_time(stage=1, stage_type="diffusion", gen_time_s=1.5)
out = generate_latest(REGISTRY).decode()
assert f'{defs.STAGE_GEN_TIME_S}_count{{model_name="{model}",stage="0",stage_type="llm"}} 1.0' in out
assert f'{defs.STAGE_GEN_TIME_S}_count{{model_name="{model}",stage="1",stage_type="diffusion"}} 1.0' in out
class TestCounterExpositionNames:
def test_counter_families_have_exactly_one_total_suffix(self) -> None:
from prometheus_client import REGISTRY, generate_latest
model = _MODEL + "-counter-suffix"
prom = OmniPrometheusMetrics(model_name=model, log_stats=True)
prom.inc_image_count(2)
prom.inc_requests_failed("stage_error")
out = generate_latest(REGISTRY).decode()
assert f'{defs.IMAGE_COUNT_METRIC}_total{{model_name="{model}"}} 2.0' in out
assert f'{defs.REQUESTS_FAILED}_total{{model_name="{model}",reason="stage_error"}} 1.0' in out
assert f"{defs.IMAGE_COUNT_METRIC}_total_total" not in out
assert f"{defs.REQUESTS_FAILED}_total_total" not in out
class TestQueueWaitExtraction:
def test_present_zero_is_a_valid_observation(self) -> None:
from vllm_omni.metrics.utils import extract_queue_wait_s
assert extract_queue_wait_s({"queue_wait_ms": 0.0}) == 0.0
def test_missing_queue_wait_is_not_synthetic_zero(self) -> None:
from vllm_omni.metrics.utils import extract_queue_wait_s
assert extract_queue_wait_s({"preprocess_ms": 2.0}) is None
assert extract_queue_wait_s(None) is None
class TestStageInQueueObservation:
def test_prometheus_records_valid_zero_wait(self) -> None:
from prometheus_client import REGISTRY, generate_latest
model = _MODEL + "-zero-stage-wait"
prom = OmniPrometheusMetrics(model_name=model, log_stats=True)
prom.observe_stage_in_queue(stage=1, in_queue_s=0.0)
out = generate_latest(REGISTRY).decode()
sample = f'{defs.STAGE_IN_QUEUE_S}_count{{model_name="{model}",stage="1"}} 1.0'
assert sample in out
class TestStageWorkloadMetricScope:
@staticmethod
def _observe(mocker, *, stage_type: str, output_unit_type: str):
from vllm_omni.metrics.utils import observe_stage_workload_metrics
prom = mocker.Mock(spec=OmniPrometheusMetrics)
stage_metrics = SimpleNamespace(
num_inference_steps=50,
output_unit_type=output_unit_type,
image_pixels=1024 * 1024,
output_unit_count=2,
)
observe_stage_workload_metrics(
prom,
stage_type=stage_type,
stage_metrics=stage_metrics,
)
return prom
def test_diffusion_image_observes_steps_and_image_workload(self, mocker) -> None:
prom = self._observe(mocker, stage_type="diffusion", output_unit_type="image")
prom.observe_num_inference_steps.assert_called_once_with(50)
prom.observe_image_pixels.assert_called_once_with(1024 * 1024)
prom.inc_image_count.assert_called_once_with(2)
def test_diffusion_video_observes_steps_only(self, mocker) -> None:
prom = self._observe(mocker, stage_type="diffusion", output_unit_type="video")
prom.observe_num_inference_steps.assert_called_once_with(50)
prom.observe_image_pixels.assert_not_called()
prom.inc_image_count.assert_not_called()
def test_llm_text_observes_no_workload_metrics(self, mocker) -> None:
prom = self._observe(mocker, stage_type="llm", output_unit_type="text")
prom.observe_num_inference_steps.assert_not_called()
prom.observe_image_pixels.assert_not_called()
prom.inc_image_count.assert_not_called()
def test_non_diffusion_image_observes_image_workload_only(self, mocker) -> None:
prom = self._observe(mocker, stage_type="llm", output_unit_type="image")
prom.observe_num_inference_steps.assert_not_called()
prom.observe_image_pixels.assert_called_once_with(1024 * 1024)
prom.inc_image_count.assert_called_once_with(2)
@pytest.mark.parametrize("peak_memory_mb", [2048.0, 0.0])
def test_same_finished_image_message_is_observed_exactly_once(self, mocker, peak_memory_mb: float) -> None:
from vllm_omni.entrypoints.omni_base import OmniBase
obj = object.__new__(OmniBase)
obj._enable_ar_profiler = False
obj._consumed_metric_messages = {}
obj.prom_metrics = mocker.Mock(spec=OmniPrometheusMetrics)
obj.mod_metrics = mocker.Mock()
obj.engine = SimpleNamespace(
get_stage_metadata=lambda _stage_id: SimpleNamespace(
stage_type="diffusion",
final_output=False,
final_output_type="image",
)
)
stage_metrics = SimpleNamespace(
stage_gen_time_ms=1000.0,
diffusion_metrics={"diffusion_engine_exec_time_s": 0.8, "scheduler_queue_wait_s": 0.1},
num_inference_steps=20,
output_unit_type="image",
image_pixels=1024 * 1024,
output_unit_count=1,
serving_time_to_first_output_ms=250.0,
image_time_to_first_output_ms=250.0,
pipeline_timings={},
)
result = SimpleNamespace(
request_id="req-replay",
stage_id=1,
replica_id=0,
stage_submit_ts=10.0,
metrics=stage_metrics,
engine_outputs=SimpleNamespace(
stage_durations={},
peak_memory_mb=peak_memory_mb,
finished=True,
final_output_type="image",
),
)
aggregator = mocker.Mock()
aggregator.stage_events = {}
aggregator.stage_first_ts = [None, None]
aggregator.stage_last_ts = [None, None]
for _ in range(2):
assert obj._process_single_result(result, 1, aggregator, {}, 0.0, 1) is None
aggregator.on_stage_metrics.assert_called_once_with(1, "req-replay", stage_metrics, "image")
obj.prom_metrics.inc_image_count.assert_called_once_with(1)
obj.prom_metrics.observe_image_pixels.assert_called_once_with(1024 * 1024)
obj.prom_metrics.observe_num_inference_steps.assert_called_once_with(20)
obj.prom_metrics.observe_stage_in_queue.assert_called_once_with(1, 0.1)
if peak_memory_mb > 0:
obj.prom_metrics.set_peak_memory.assert_called_once_with(1, peak_memory_mb)
else:
obj.prom_metrics.set_peak_memory.assert_not_called()
obj.mod_metrics.observe_image_ttfp.assert_called_once_with("1", "0", 0.25)
class TestStageWaitingAggregation:
@staticmethod
def _make_orchestrator(mocker):
from vllm_omni.engine.orchestrator import Orchestrator
orchestrator = object.__new__(Orchestrator)
orchestrator._prom_metrics = mocker.Mock()
orchestrator._stage_replica_waiting = {}
return orchestrator
def test_multiple_replicas_are_summed(self, mocker) -> None:
orchestrator = self._make_orchestrator(mocker)
orchestrator._update_stage_replica_waiting(1, 0, 3)
orchestrator._update_stage_replica_waiting(1, 1, 5)
orchestrator._prom_metrics.set_stage_waiting_requests.assert_called_with(1, 8)
def test_zero_update_and_stage_isolation(self, mocker) -> None:
orchestrator = self._make_orchestrator(mocker)
orchestrator._update_stage_replica_waiting(1, 0, 3)
orchestrator._update_stage_replica_waiting(2, 0, 7)
orchestrator._update_stage_replica_waiting(1, 0, 0)
orchestrator._prom_metrics.set_stage_waiting_requests.assert_called_with(1, 0)
assert orchestrator._stage_replica_waiting[(2, 0)] == 7
def test_dead_replica_snapshot_is_removed(self, mocker) -> None:
orchestrator = self._make_orchestrator(mocker)
orchestrator._update_stage_replica_waiting(1, 0, 3)
orchestrator._update_stage_replica_waiting(1, 1, 5)
orchestrator._remove_stage_replica_waiting(1, 1)
orchestrator._prom_metrics.set_stage_waiting_requests.assert_called_with(1, 3)
# ---------------------------------------------------------------------------
# Behavioral pin: call sites now scope workload observations by stage/output
# type. Keep the Prometheus wrapper's <= 0 guard as a second line of defense.
# ---------------------------------------------------------------------------
class TestZeroGuardContract:
"""Zero-valued observations must not bump histogram ``_count``."""
def test_zero_image_pixels_not_observed(self) -> None:
from prometheus_client import REGISTRY, generate_latest
prom = OmniPrometheusMetrics(model_name=_MODEL + "-zero-guard")
prom.observe_image_pixels(n_pixels=0)
out = generate_latest(REGISTRY).decode()
# ``.labels()`` in OmniPrometheusMetrics.__init__ already creates the
# child sample, so the ``_count`` line exists with value 0.0 even
# without observations. The guard prevents ``_count`` from bumping
# to 1.0 — assert the value stays at 0.
needle = f'vllm_omni:image_pixels_count{{model_name="{_MODEL}-zero-guard"}}'
count_lines = [ln for ln in out.splitlines() if ln.startswith(needle)]
assert count_lines, "expected image_pixels_count line to exist after OmniPrometheusMetrics construction"
assert float(count_lines[0].split()[-1]) == 0.0, (
"zero-pixel observation leaked to registry — guard should early-return on <= 0"
)
def test_zero_num_inference_steps_not_observed(self) -> None:
from prometheus_client import REGISTRY, generate_latest
prom = OmniPrometheusMetrics(model_name=_MODEL + "-zero-steps")
prom.observe_num_inference_steps(n_steps=0)
out = generate_latest(REGISTRY).decode()
needle = f'vllm_omni:num_inference_steps_count{{model_name="{_MODEL}-zero-steps"}}'
count_lines = [ln for ln in out.splitlines() if ln.startswith(needle)]
assert count_lines, "expected num_inference_steps_count line to exist after construction"
assert float(count_lines[0].split()[-1]) == 0.0, (
"zero-step observation leaked to registry — guard should early-return on <= 0"
)
def test_positive_image_pixels_observed(self) -> None:
# Sanity check: positive values DO get observed.
from prometheus_client import REGISTRY, generate_latest
prom = OmniPrometheusMetrics(model_name=_MODEL + "-pos-guard")
prom.observe_image_pixels(n_pixels=512)
out = generate_latest(REGISTRY).decode()
needle = f'vllm_omni:image_pixels_count{{model_name="{_MODEL}-pos-guard"}}'
count_lines = [ln for ln in out.splitlines() if ln.startswith(needle)]
assert count_lines, "expected image_pixels_count line after positive observation"
assert float(count_lines[0].split()[-1]) == 1.0, "positive-pixel observation did not increment count to 1"
# ---------------------------------------------------------------------------
# KV-wait emit wiring — scheduler ENTER/EXIT lifecycle + orchestrator dispatch.
# ---------------------------------------------------------------------------
def _make_scheduler_shell() -> OmniARScheduler:
"""Minimal OmniARScheduler shell — skips upstream __init__ via object.__new__."""
from vllm_omni.core.sched.omni_ar_scheduler import OmniARScheduler
obj = object.__new__(OmniARScheduler)
obj.requests = {}
obj.running = []
obj.waiting = []
obj._kv_wait_start_ts = {}
obj._omni_kv_config = None
return obj
class TestKvWaitSchedulerEmit:
"""Scheduler-side half of kv_wait_s: pops start ts, carries the wait across."""
def test_skips_when_no_start_ts_recorded(self) -> None:
sched = _make_scheduler_shell()
outputs: dict[int, list] = {}
sched._emit_kv_wait_output(outputs, "req-no-wait", req=SimpleNamespace(client_index=0))
assert outputs == {}, "emit must not append output when no start ts recorded"
assert "req-no-wait" not in sched._kv_wait_start_ts
def test_emits_wait_duration_and_connector_type(self) -> None:
sched = _make_scheduler_shell()
sched._kv_wait_start_ts["req-1"] = time.monotonic() - 0.25
outputs: dict[int, list] = {}
live_req = SimpleNamespace(client_index=3)
sched._emit_kv_wait_output(outputs, "req-1", req=live_req)
assert "req-1" not in sched._kv_wait_start_ts, "start ts must be popped after emit"
assert 3 in outputs and len(outputs[3]) == 1
params = outputs[3][0].kv_transfer_params
assert "kv_wait_s" in params and "connector_type" in params
assert 0.0 < params["kv_wait_s"] < 1.0
assert params["connector_type"] == "unknown"
def test_connector_type_resolved_from_omni_kv_config(self) -> None:
sched = _make_scheduler_shell()
sched._omni_kv_config = {"connector_config": {"type": "SharedMemoryConnector"}}
sched._kv_wait_start_ts["req-3"] = time.monotonic() - 0.01
outputs: dict[int, list] = {}
sched._emit_kv_wait_output(outputs, "req-3", req=SimpleNamespace(client_index=0))
eco = outputs[0][0]
assert eco.kv_transfer_params["connector_type"] == "SharedMemoryConnector"
class TestKvWaitTerminalCleanup:
def test_finish_requests_clears_requested_wait_only(self) -> None:
from vllm.v1.request import RequestStatus
scheduler = _make_scheduler_shell()
scheduler._kv_wait_start_ts = {"req-1": 10.0, "req-2": 20.0}
finished = scheduler.finish_requests(
(request_id for request_id in ["req-1"]),
RequestStatus.FINISHED_ABORTED,
)
assert finished == []
assert "req-1" not in scheduler._kv_wait_start_ts
assert scheduler._kv_wait_start_ts["req-2"] == 20.0
def test_cleanup_is_idempotent_when_timestamp_is_already_gone(self) -> None:
from vllm.v1.request import RequestStatus
scheduler = _make_scheduler_shell()
scheduler.finish_requests("req-already-emitted", RequestStatus.FINISHED_ABORTED)
assert scheduler._kv_wait_start_ts == {}
+208
View File
@@ -1,5 +1,10 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
from types import SimpleNamespace
import pytest
from prometheus_client import REGISTRY, generate_latest
@@ -10,6 +15,7 @@ from vllm_omni.metrics.modality import (
observe_audio_streaming_finalize,
observe_modality_at_finalize,
)
from vllm_omni.metrics.stats import OrchestratorAggregator
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
@@ -46,6 +52,11 @@ _EXPECTED_FAMILIES = [
defs.DIFFUSION_EXEC_PER_STEP_S,
defs.DIFFUSION_PREPROCESS_S,
defs.DIFFUSION_POSTPROCESS_S,
defs.VAE_DECODE_S,
defs.DIFFUSION_FORWARD_S,
defs.DIFFUSION_KV_LOAD_S,
defs.IMAGE_TTFP_S,
defs.DENOISE_STEP_LATENCY_S,
]
@@ -63,6 +74,11 @@ class TestRegistration:
mod.observe_diffusion_exec_per_step("s", "r", 0.01)
mod.observe_diffusion_preprocess("s", "r", 0.01)
mod.observe_diffusion_postprocess("s", "r", 0.2)
mod.observe_vae_decode("s", "r", 0.3)
mod.observe_diffusion_forward("s", "r", 0.8)
mod.observe_diffusion_kv_load("s", "r", 0.04)
mod.observe_image_ttfp("s", "r", 2.5)
mod.observe_denoise_step_latency("s", "r", 0.05)
out = generate_latest(REGISTRY).decode()
for name in _EXPECTED_FAMILIES:
@@ -247,6 +263,21 @@ class _StubModMetrics:
def observe_diffusion_postprocess(self, s, r, v):
self.calls.append(("observe_diffusion_postprocess", s, r, v))
def observe_vae_decode(self, s, r, seconds):
self.calls.append(("observe_vae_decode", s, r, seconds))
def observe_diffusion_forward(self, s, r, seconds):
self.calls.append(("observe_diffusion_forward", s, r, seconds))
def observe_diffusion_kv_load(self, s, r, seconds):
self.calls.append(("observe_diffusion_kv_load", s, r, seconds))
def observe_image_ttfp(self, s, r, seconds):
self.calls.append(("observe_image_ttfp", s, r, seconds))
def observe_denoise_step_latency(self, s, r, seconds):
self.calls.append(("observe_denoise_step_latency", s, r, seconds))
class _Bag:
def __init__(self, **kw):
@@ -306,11 +337,13 @@ class TestObserveModalityAtFinalize:
def test_diffusion_path_full(self):
stub = _StubModMetrics()
stage_metrics = _Bag(
output_unit_type="image",
stage_gen_time_ms=1000.0,
diffusion_metrics={
"preprocess_time_s": 0.05,
"diffusion_engine_exec_time_s": 1.2,
"postprocess_time_s": 0.3,
"forward_time_s": 1.0,
"image_num": 1,
"resolution": 1024,
"num_inference_steps": 50,
@@ -328,6 +361,71 @@ class TestObserveModalityAtFinalize:
assert ("observe_diffusion_exec", "2", "0", 1.2) in stub.calls
assert ("observe_diffusion_postprocess", "2", "0", 0.3) in stub.calls
assert ("observe_diffusion_exec_per_step", "2", "0", pytest.approx(0.024)) in stub.calls
assert ("observe_denoise_step_latency", "2", "0", pytest.approx(0.02)) in stub.calls
def test_denoise_step_latency_requires_forward_time(self):
stub = _StubModMetrics()
stage_metrics = _Bag(
output_unit_type="image",
num_inference_steps=20,
diffusion_metrics={"diffusion_engine_exec_time_s": 1.2},
)
observe_modality_at_finalize(
stub,
output_type="image",
stage_id=2,
replica_id=0,
stage_metrics=stage_metrics,
engine_outputs=_Bag(),
)
assert not any(c[0] == "observe_denoise_step_latency" for c in stub.calls)
def test_stage_snapshot_keeps_forward_based_denoise_latency(self):
aggregator = OrchestratorAggregator(
num_stages=1,
log_stats=False,
wall_start_ts=0.0,
final_stage_id_for_e2e=0,
)
aggregator.diffusion_metrics["req-image"]["forward_time_s"] = 0.8
stage_metrics = _Bag(
stage_id=None,
request_id=None,
final_output_type=None,
num_tokens_in=0,
num_tokens_out=0,
stage_gen_time_ms=1200.0,
rx_transfer_bytes=0,
rx_decode_time_ms=0.0,
rx_in_flight_time_ms=0.0,
stage_stats=_Bag(),
diffusion_metrics=None,
num_inference_steps=20,
output_unit_type="image",
denoise_step_latency_ms=0.0,
)
stats = aggregator._as_stage_request_stats(0, "req-image", stage_metrics, "image")
assert stats.denoise_step_latency_ms == pytest.approx(40.0)
def test_stage_snapshot_falls_back_to_stage_time_without_profiler(self):
aggregator = object.__new__(OrchestratorAggregator)
stage_metrics = _Bag(
stage_id=None,
request_id=None,
final_output_type=None,
stage_gen_time_ms=1200.0,
diffusion_metrics=None,
num_inference_steps=20,
output_unit_type="image",
denoise_step_latency_ms=0.0,
)
stats = aggregator._as_stage_request_stats(0, "req-image", stage_metrics, "image")
assert stats.diffusion_metrics is None
assert stats.denoise_step_latency_ms == pytest.approx(60.0)
def test_diffusion_per_step_skipped_without_num_inference_steps(self):
stub = _StubModMetrics()
@@ -422,6 +520,80 @@ class TestObserveModalityAtFinalize:
assert stub.calls == []
class TestDiffusionUnitConversion:
def test_accumulator_converts_all_engine_milliseconds_to_seconds(self):
aggregator = OrchestratorAggregator(
num_stages=1,
log_stats=False,
wall_start_ts=0.0,
final_stage_id_for_e2e=0,
)
engine_output = SimpleNamespace(
metrics={
"preprocess_time_ms": 50.0,
"diffusion_engine_exec_time_ms": 1500.0,
"postprocess_time_ms": 20.0,
"vae_decode_time_ms": 300.0,
"forward_time_ms": 800.0,
"scheduler_queue_wait_ms": 125.0,
"kv_recv_time_ms": 40.0,
}
)
aggregator.accumulate_diffusion_metrics("diffusion", "req-units", engine_output)
assert dict(aggregator.diffusion_metrics["req-units"]) == {
"preprocess_time_s": pytest.approx(0.05),
"diffusion_engine_exec_time_s": pytest.approx(1.5),
"postprocess_time_s": pytest.approx(0.02),
"vae_decode_time_s": pytest.approx(0.3),
"forward_time_s": pytest.approx(0.8),
"scheduler_queue_wait_s": pytest.approx(0.125),
"kv_recv_time_s": pytest.approx(0.04),
}
class TestObserveDiffusionFinalize:
@pytest.mark.parametrize(
("metric_key", "call_name", "value"),
[
("vae_decode_time_s", "observe_vae_decode", 0.3),
("forward_time_s", "observe_diffusion_forward", 0.8),
("kv_recv_time_s", "observe_diffusion_kv_load", 0.04),
],
)
def test_emits_optional_breakdown_metric(self, metric_key, call_name, value):
stub = _StubModMetrics()
observe_modality_at_finalize(
stub,
output_type="image",
stage_id=2,
replica_id=0,
stage_metrics=_Bag(diffusion_metrics={metric_key: value}),
engine_outputs=_Bag(),
)
assert (call_name, "2", "0", value) in stub.calls
def test_audio_diffusion_stage_fires_both_paths(self):
stub = _StubModMetrics()
observe_modality_at_finalize(
stub,
output_type="audio",
stage_id=1,
replica_id=0,
stage_metrics=_Bag(
stage_gen_time_ms=1500.0,
audio_generated_frames=24000,
diffusion_metrics={"diffusion_engine_exec_time_s": 1.2},
),
engine_outputs=_Bag(multimodal_output={"audio_sample_rate": 24000}),
)
assert ("observe_diffusion_exec", "1", "0", 1.2) in stub.calls
assert ("observe_audio_duration", "1", "0", 1.0) in stub.calls
class TestObserveAudioFirstPacket:
def test_observes_with_valid_inputs(self):
stub = _StubModMetrics()
@@ -541,3 +713,39 @@ class TestBucketSelection:
# SECONDS_FAST_BUCKETS includes le=0.001 which is absent from SECONDS_BUCKETS.
fast_marker = f'{defs.AUDIO_UNDERRUN_S}_bucket{{le="0.001"'
assert fast_marker in out, "audio_underrun_s should use SECONDS_FAST_BUCKETS containing le=0.001"
def test_vae_decode_uses_seconds_buckets(self, mod: OmniModalityMetrics) -> None:
# VAE decode can stretch into seconds for high-resolution latents;
# stays on the wide bucket so the 300 s ceiling covers video VAE.
stage, replica = "vae_decode_sec", "0"
mod.observe_vae_decode(stage, replica, 1.5)
out = generate_latest(REGISTRY).decode()
sec_marker = f'{defs.VAE_DECODE_S}_bucket{{le="300.0"'
assert sec_marker in out, "vae_decode_s should use SECONDS_BUCKETS containing le=300.0"
def test_diffusion_forward_uses_seconds_buckets(self, mod: OmniModalityMetrics) -> None:
# Denoise loop can exceed the 60s fast-bucket ceiling for video gen.
stage, replica = "diff_forward_sec", "0"
mod.observe_diffusion_forward(stage, replica, 2.0)
out = generate_latest(REGISTRY).decode()
sec_marker = f'{defs.DIFFUSION_FORWARD_S}_bucket{{le="300.0"'
assert sec_marker in out, "diffusion_forward_s should use SECONDS_BUCKETS containing le=300.0"
def test_denoise_step_latency_uses_seconds_fast_buckets(self, mod: OmniModalityMetrics) -> None:
# Per-step denoise is sub-second; stays on the fast bucket for ms-level
# resolution.
stage, replica = "denoise_fast", "0"
mod.observe_denoise_step_latency(stage, replica, 0.075)
out = generate_latest(REGISTRY).decode()
fast_marker = f'{defs.DENOISE_STEP_LATENCY_S}_bucket{{le="0.001"'
assert fast_marker in out, "denoise_step_latency_s should use SECONDS_FAST_BUCKETS containing le=0.001"
class TestDenoiseStepLatencyGuard:
@pytest.mark.parametrize(("value", "expected_count"), [(0.0, None), (-0.1, None), (0.05, 1.0)])
def test_nonpositive_values_are_skipped(self, mod: OmniModalityMetrics, value, expected_count) -> None:
stage, replica = f"denoise_{value}", "0"
mod.observe_denoise_step_latency(stage, replica, value)
out = generate_latest(REGISTRY).decode()
prefix = f'{defs.DENOISE_STEP_LATENCY_S}_count{{model_name="{_MODEL}",replica="{replica}",stage="{stage}"}}'
assert _sample_value(out, prefix) == expected_count