Merge branch 'main' into feat/moss-tts-nano

Signed-off-by: Yueqian Lin <70319226+linyueqian@users.noreply.github.com>
This commit is contained in:
Yueqian Lin authored and GitHub committed 2026-04-24 11:00:13 -04:00
commit 74522ca3ec
307 files changed
+20557 -5581

No files matched your search

+63 -1
View File
@@ -1,11 +1,17 @@
# ruff: noqa: E402, I001
import argparse
import math
import os
import sys
import types
from pathlib import Path
import pytest
from PIL import Image
pytestmark = [pytest.mark.core_model, pytest.mark.diffusion, pytest.mark.cpu]
REPO_ROOT = Path(__file__).resolve().parents[2]
if str(REPO_ROOT) not in sys.path:
sys.path.insert(0, str(REPO_ROOT))
@@ -36,8 +42,64 @@ from benchmarks.accuracy.text_to_image.gbench import (
summarize_generated_records as summarize_gebench_generated_records,
summarize_gebench_results,
)
from tests.e2e.accuracy.qwen3_omni.qwen3_omni_acc_bench_core import seed_tts_bench_argv
from tests.e2e.accuracy.qwen3_omni.run_qwen_omni_acc_benchmark import sync_dataset_env_from_ns
from vllm_omni.benchmarks.data_modules.seed_tts_dataset import resolve_seed_tts_root
pytestmark = [pytest.mark.core_model, pytest.mark.diffusion, pytest.mark.cpu]
def test_seed_tts_bench_argv_preserves_hf_repo_id_from_env(monkeypatch):
monkeypatch.setenv("VLLM_SEED_TTS_DATASET_PATH", "zhaochenyang20/seed-tts-eval")
monkeypatch.delenv("VLLM_SEED_TTS_REPO", raising=False)
argv = seed_tts_bench_argv(locale="en")
dataset_idx = argv.index("--dataset-path")
assert argv[dataset_idx + 1] == "zhaochenyang20/seed-tts-eval"
def test_sync_dataset_env_preserves_seed_tts_hf_repo_id(monkeypatch):
ns = argparse.Namespace(
daily_omni_repo=None,
daily_omni_qa_json=None,
daily_omni_video_dir=None,
seed_tts_dataset_path="zhaochenyang20/seed-tts-eval",
seed_tts_root=None,
)
monkeypatch.delenv("VLLM_SEED_TTS_DATASET_PATH", raising=False)
sync_dataset_env_from_ns(ns)
assert os.environ["VLLM_SEED_TTS_DATASET_PATH"] == "zhaochenyang20/seed-tts-eval"
def test_resolve_seed_tts_root_downloads_only_requested_locale(monkeypatch, tmp_path: Path):
downloaded_root = tmp_path / "seed_tts_cache"
(downloaded_root / "zh" / "prompt-wavs").mkdir(parents=True)
(downloaded_root / "zh" / "meta.lst").write_text("", encoding="utf-8")
captured: dict[str, object] = {}
def fake_snapshot_download(*, repo_id, repo_type, allow_patterns):
captured["repo_id"] = repo_id
captured["repo_type"] = repo_type
captured["allow_patterns"] = allow_patterns
return str(downloaded_root)
monkeypatch.setitem(
sys.modules,
"huggingface_hub",
types.SimpleNamespace(snapshot_download=fake_snapshot_download),
)
resolved = resolve_seed_tts_root(
"zhaochenyang20/seed-tts-eval",
explicit_root=None,
locale="zh",
)
assert resolved == downloaded_root.resolve()
assert captured["repo_id"] == "zhaochenyang20/seed-tts-eval"
assert captured["repo_type"] == "dataset"
assert captured["allow_patterns"] == ["zh/**"]
def test_summarize_gebench_generated_records_groups_by_type():
@@ -0,0 +1,107 @@
import pytest
from benchmarks.diffusion.backends import RequestFuncInput, async_request_chat_completions
class _MockResponse:
def __init__(self, payload: dict, status: int = 200):
self._payload = payload
self.status = status
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc, tb):
return False
async def json(self):
return self._payload
async def text(self):
return str(self._payload)
class _MockSession:
def __init__(self, payload: dict):
self._payload = payload
def post(self, *args, **kwargs):
return _MockResponse(self._payload)
@pytest.mark.core_model
@pytest.mark.benchmark
@pytest.mark.cpu
@pytest.mark.asyncio
async def test_chat_completions_metrics_fallback_to_top_level():
payload = {
"choices": [
{
"message": {
"content": [
{
"type": "image_url",
"image_url": {"url": "data:image/png;base64,abc"},
}
]
}
}
],
"metrics": {
"stage_durations": {"diffusion": 1.25},
"peak_memory_mb": 4096.0,
},
}
output = await async_request_chat_completions(
RequestFuncInput(
prompt="draw a cat",
api_url="http://test.local/v1/chat/completions",
model="ByteDance-Seed/BAGEL-7B-MoT",
),
session=_MockSession(payload),
)
assert output.success is True
assert output.stage_durations == {"diffusion": 1.25}
assert output.peak_memory_mb == 4096.0
@pytest.mark.core_model
@pytest.mark.benchmark
@pytest.mark.cpu
@pytest.mark.asyncio
async def test_chat_completions_metrics_message_level_takes_precedence():
payload = {
"choices": [
{
"message": {
"content": [
{
"type": "image_url",
"image_url": {"url": "data:image/png;base64,abc"},
"stage_durations": {"message_stage": 0.7},
"peak_memory_mb": 1234.0,
}
]
}
}
],
"metrics": {
"stage_durations": {"top_level_stage": 9.9},
"peak_memory_mb": 9999.0,
},
}
output = await async_request_chat_completions(
RequestFuncInput(
prompt="draw a dog",
api_url="http://test.local/v1/chat/completions",
model="ByteDance-Seed/BAGEL-7B-MoT",
),
session=_MockSession(payload),
)
assert output.success is True
assert output.stage_durations == {"message_stage": 0.7}
assert output.peak_memory_mb == 1234.0
+174 -3
View File
@@ -1,4 +1,7 @@
import json
import os
import subprocess
from datetime import datetime
from pathlib import Path
from typing import Any
@@ -37,12 +40,45 @@ def modify_stage(default_path, updates, deletes):
return path
def _build_serve_args(serve_args: Any) -> list[str]:
"""Convert server_params.serve_args to a flat CLI args list."""
if serve_args is None:
return []
if isinstance(serve_args, list):
return [str(item) for item in serve_args]
if not isinstance(serve_args, dict):
raise TypeError(f"serve_args must be dict/list/None, got {type(serve_args).__name__}")
args: list[str] = []
for key, value in serve_args.items():
flag = f"--{str(key).replace('_', '-')}"
if isinstance(value, bool):
if value:
args.append(flag)
continue
if value is None:
continue
if isinstance(value, (dict, list)):
args.extend([flag, json.dumps(value, ensure_ascii=False, separators=(",", ":"))])
continue
args.extend([flag, str(value)])
return args
def create_unique_server_params(
configs: list[dict[str, Any]],
stage_configs_dir: Path,
) -> list[tuple[str, str, str | None, str | None, tuple[str, ...]]]:
unique_params = []
seen = set()
"""Return one row per unique server configuration (same 5-tuple shape as upstream).
``(test_name, model, deploy_yaml_path, stage_overrides_json, extra_cli_args)``.
JSON ``server_params.serve_args`` (dict/list) is expanded via ``_build_serve_args``
and **prepended** to ``extra_cli_args`` so perf / stability ``omni_server`` fixtures
stay identical to main while still honoring ``serve_args`` in benchmark JSON.
"""
unique_params: list[tuple[str, str, str | None, str | None, tuple[str, ...]]] = []
seen: set[tuple[str, str, str | None, str | None, tuple[str, ...]]] = set()
for config in configs:
test_name = config["test_name"]
server_params = config["server_params"]
@@ -63,7 +99,9 @@ def create_unique_server_params(
# ``vllm_omni.entrypoints.cli.main serve`` — used for flags that
# don't map to stage-level overrides, e.g. ``--async-chunk`` /
# ``--no-async-chunk`` toggling the deploy-level async_chunk bool.
extra_cli_args = tuple(server_params.get("extra_cli_args") or ())
serve_flat = _build_serve_args(server_params.get("serve_args"))
raw_extra = tuple(server_params.get("extra_cli_args") or ())
extra_cli_args = tuple(serve_flat) + raw_extra
server_param = (test_name, model, stage_config_path, stage_overrides_json, extra_cli_args)
if server_param not in seen:
@@ -109,6 +147,139 @@ def create_benchmark_indices(
return indices
def _safe_filename_token(value: Any | None, *, default: str = "na") -> str:
"""Make a single path segment safe for result filenames on common filesystems."""
if value is None:
return default
s = str(value).strip()
for bad in ("/", "\\", ":", "*", "?", '"', "<", ">", "|"):
s = s.replace(bad, "_")
return s if s else default
def _resolve_baseline_value(
baseline_raw: Any,
*,
sweep_index: int | None,
max_concurrency: Any = None,
request_rate: Any = None,
) -> Any:
"""Pick the baseline threshold for this sweep step."""
if baseline_raw is None:
return 100000
if isinstance(baseline_raw, dict):
if max_concurrency is not None:
for key in (max_concurrency, str(max_concurrency)):
if key in baseline_raw:
return baseline_raw[key]
if request_rate is not None:
for key in (request_rate, str(request_rate)):
if key in baseline_raw:
return baseline_raw[key]
raise KeyError(
f"baseline dict has no key for max_concurrency={max_concurrency!r} "
f"or request_rate={request_rate!r}; keys={list(baseline_raw.keys())!r}"
)
if isinstance(baseline_raw, (list, tuple)):
if sweep_index is None:
raise ValueError("list baseline requires sweep_index")
if not (0 <= sweep_index < len(baseline_raw)):
raise IndexError(f"baseline list len={len(baseline_raw)} has no index {sweep_index}")
return baseline_raw[sweep_index]
return baseline_raw
def _baseline_thresholds_for_step(
baseline_data: dict[str, Any],
*,
sweep_index: int | None = None,
max_concurrency: Any = None,
request_rate: Any = None,
) -> dict[str, Any]:
"""Resolve baseline config to one threshold per metric for this iteration."""
return {
metric_name: _resolve_baseline_value(
baseline_raw,
sweep_index=sweep_index,
max_concurrency=max_concurrency,
request_rate=request_rate,
)
for metric_name, baseline_raw in baseline_data.items()
}
def run_benchmark(
args: list[str],
test_name: str,
flow: Any,
dataset_name: str,
num_prompt: int,
*,
baseline_config: dict[str, Any] | None = None,
sweep_index: int | None = None,
request_rate: Any | None = None,
max_concurrency: Any | None = None,
random_input_len: Any | None = None,
random_output_len: Any | None = None,
) -> dict[str, Any]:
"""Run one ``vllm bench serve --omni`` iteration and return parsed metrics."""
current_dt = datetime.now().strftime("%Y%m%d-%H%M%S")
ri = _safe_filename_token(random_input_len)
ro = _safe_filename_token(random_output_len)
result_filename = f"result_{test_name}_{dataset_name}_{flow}_{num_prompt}_in{ri}_out{ro}_{current_dt}.json"
if "--result-filename" in args:
print(f"The result file will be overwritten by {result_filename}")
command = (
["vllm", "bench", "serve", "--omni"]
+ args
+ [
"--num-warmups",
"2",
"--save-result",
"--result-dir",
os.environ.get("BENCHMARK_DIR", "tests"),
"--result-filename",
result_filename,
]
)
process = subprocess.Popen(
command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1, universal_newlines=True
)
for line in iter(process.stdout.readline, ""):
print(line, end=" ")
for line in iter(process.stderr.readline, ""):
print(line, end=" ")
if "--result-dir" in command:
index = command.index("--result-dir")
result_dir = command[index + 1]
else:
result_dir = "./"
result_path = os.path.join(result_dir, result_filename)
with open(result_path, encoding="utf-8") as f:
result = json.load(f)
if baseline_config:
result["baseline"] = _baseline_thresholds_for_step(
baseline_config,
sweep_index=sweep_index,
request_rate=request_rate,
max_concurrency=max_concurrency,
)
else:
result["baseline"] = {}
if random_input_len is not None:
result["random_input_len"] = random_input_len
if random_output_len is not None:
result["random_output_len"] = random_output_len
with open(result_path, "w", encoding="utf-8") as f:
json.dump(result, f, ensure_ascii=False, indent=2)
return result
def pytest_addoption(parser: pytest.Parser) -> None:
"""Register shared CLI options for DFX benchmark suites."""
parser.addoption(
+4
View File
@@ -17,6 +17,9 @@ from tests.dfx.conftest import (
)
from tests.helpers.runtime import OmniServer
pytestmark = [pytest.mark.full_model, pytest.mark.omni]
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
os.environ["VLLM_TEST_CLEAN_GPU_MEMORY"] = "0"
@@ -293,6 +296,7 @@ def assert_result(
print(f"ERROR: Test results exceeded baseline: {metric_name}: {current_value} < {baseline_value}")
@pytest.mark.benchmark
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
@pytest.mark.parametrize("benchmark_params", benchmark_indices, indirect=True)
def test_performance_benchmark(omni_server, benchmark_params):
@@ -1,16 +1,17 @@
"""
Performance benchmark CI runner for diffusion models.
Supports vLLM-Omni server backend:
- vllm-omni (default): starts DiffusionServer via vllm_omni.entrypoints.cli.main,
benchmarks with diffusion_benchmark_serving.py --backend vllm-omni
This runner separates two concepts:
1. ``server_type``: how the serving process is started.
Currently only ``vllm-omni`` is supported here.
2. ``benchmark_backend``: which serving API the benchmark client calls.
Examples: ``vllm-omni`` for ``/v1/chat/completions`` and ``v1/videos``
for async video jobs.
A config JSON file is REQUIRED via --test-config-file:
pytest run_diffusion_benchmark.py --test-config-file tests/dfx/perf/tests/test_qwen_image_vllm_omni.json
JSON config entries use a "server_type" field, and this runner executes
the vllm-omni path.
All benchmark results for a session are consolidated into a single JSON file under
BENCHMARK_RESULT_DIR (override via the DIFFUSION_BENCHMARK_DIR environment variable).
Each entry in the file contains the test metadata (test_name, backend, benchmark_params,
@@ -32,6 +33,8 @@ from typing import Any, cast
import psutil
import pytest
pytestmark = [pytest.mark.diffusion, pytest.mark.full_model]
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
os.environ["VLLM_TEST_CLEAN_GPU_MEMORY"] = "0"
os.environ.setdefault("DIFFUSION_ATTENTION_BACKEND", "FLASH_ATTN")
@@ -387,17 +390,18 @@ def _unique_server_params(configs: list[dict[str, Any]]) -> list[dict[str, Any]]
if test_name in seen:
continue
seen.add(test_name)
if cfg.get("server_type", "vllm-omni") != "vllm-omni":
raise ValueError(f"Unsupported server_type in config: {cfg.get('server_type')}")
server_type = cfg.get("server_type", "vllm-omni")
if server_type != "vllm-omni":
raise ValueError(f"Unsupported server_type in config: {server_type}")
serve_args_dict = cfg["server_params"].get("serve_args", {})
result.append(
{
"test_name": test_name,
"server_type": "vllm-omni",
"server_type": server_type,
"model": cfg["server_params"]["model"],
"serve_args_dict": serve_args_dict,
"serve_args": _build_serve_args(serve_args_dict),
"benchmark_backend": "vllm-omni",
"benchmark_backend": cfg.get("benchmark_backend"),
"server_params": cfg["server_params"],
}
)
@@ -497,7 +501,8 @@ def run_benchmark(
log_dir = BENCHMARK_RESULT_DIR / "logs"
log_dir.mkdir(parents=True, exist_ok=True)
log_file = log_dir / f"{test_name}_{backend}_{timestamp}.log"
backend_label = backend.replace("/", "_")
log_file = log_dir / f"{test_name}_{backend_label}_{timestamp}.log"
with tempfile.NamedTemporaryFile(mode="w", suffix=".json", prefix="diffusion_bench_tmp_", delete=False) as tmp:
tmp_result_file = Path(tmp.name)
@@ -583,6 +588,7 @@ def run_benchmark(
tmp_result_file.unlink(missing_ok=True)
server_cfg = server_cfg or {}
server_type = cast(str, server_cfg.get("server_type", "vllm-omni"))
serve_args_dict = server_cfg.get("serve_args_dict", {})
if not isinstance(serve_args_dict, dict):
serve_args_dict = {}
@@ -599,18 +605,19 @@ def run_benchmark(
"result": metrics,
"log_file": str(log_file),
"Model": model,
"Framework": backend,
"Framework": server_type,
"API Backend": backend,
"Hardware": "",
"Deployment": "",
"Task": params.get("task", "t2i"),
"Dataset": params.get("dataset", "random"),
"resolution": _to_resolution_string(params),
"Parallelism": _to_parallelism_string(backend, serve_args_dict),
"Parallelism": _to_parallelism_string(server_type, serve_args_dict),
"max_concurrency": params.get("max-concurrency", ""),
"Cache": _to_cache_string(backend, serve_args_dict),
"Quantization": _to_quantization_value(backend, serve_args_dict),
"offload": _to_offload_string(backend, serve_args_dict),
"compile": _to_compile_value(backend, serve_args_dict),
"Cache": _to_cache_string(server_type, serve_args_dict),
"Quantization": _to_quantization_value(server_type, serve_args_dict),
"offload": _to_offload_string(server_type, serve_args_dict),
"compile": _to_compile_value(server_type, serve_args_dict),
"Attn_backend": os.environ.get("DIFFUSION_ATTENTION_BACKEND", ""),
"num_inference_steps": params.get("num-inference-steps", ""),
"completed": completed,
@@ -659,11 +666,27 @@ def assert_result(result: dict[str, Any], params: dict[str, Any]) -> None:
assert current <= threshold, f"{metric}: {current:.4f} > baseline {threshold}"
def _default_benchmark_backend_for_task(task: str) -> str:
"""Return the default client-side benchmark backend for a diffusion task."""
if task in {"t2v", "i2v", "ti2v"}:
return "v1/videos"
if task in {"t2i", "i2i", "ti2i"}:
return "vllm-omni"
raise ValueError(f"Unsupported task for benchmark backend resolution: {task}")
def _resolve_benchmark_backend(server_cfg: dict[str, Any], params: dict[str, Any]) -> str:
"""Resolve which serving API the benchmark client should call."""
configured = server_cfg.get("benchmark_backend")
if configured:
return cast(str, configured)
return _default_benchmark_backend_for_task(cast(str, params.get("task", "t2i")))
# ---------------------------------------------------------------------------
# Test entry point
# ---------------------------------------------------------------------------
@pytest.mark.benchmark
@pytest.mark.parametrize(
"diffusion_server",
server_params,
@@ -684,7 +707,8 @@ def test_diffusion_performance_benchmark(diffusion_server, benchmark_params):
"""
test_name = benchmark_params["test_name"]
params = benchmark_params["params"]
backend = diffusion_server.server_type # "vllm-omni"
server_cfg = getattr(diffusion_server, "server_cfg", {})
backend = _resolve_benchmark_backend(server_cfg, params)
result = run_benchmark(
host=diffusion_server.host,
@@ -693,7 +717,7 @@ def test_diffusion_performance_benchmark(diffusion_server, benchmark_params):
params=params,
test_name=test_name,
backend=backend,
server_cfg=getattr(diffusion_server, "server_cfg", {}),
server_cfg=server_cfg,
source_file=cast(str, CONFIG_FILE_PATH),
)
+32 -32
View File
@@ -10,16 +10,16 @@
"dataset_name": "random",
"backend": "openai-chat-omni",
"endpoint": "/v1/chat/completions",
"num_prompts": [4, 16, 40],
"max_concurrency": [1, 4, 10],
"num_prompts": [4, 16, 32, 64, 128],
"max_concurrency": [1, 4, 8, 16, 32],
"random_input_len": 2500,
"random_output_len": 900,
"ignore_eos": true,
"percentile-metrics": "ttft,tpot,itl,e2el,audio_rtf,audio_ttfp,audio_duration",
"baseline": {
"mean_ttft_ms": [1000, 3000, 5000],
"mean_audio_ttfp_ms": [30000, 60000, 90000],
"mean_audio_rtf": [0.35, 0.45, 0.55]
"mean_ttft_ms": [1000, 3000, 5000, 7000, 9000],
"mean_audio_ttfp_ms": [30000, 60000, 90000, 120000, 150000],
"mean_audio_rtf": [0.35, 0.45, 0.55, 0.65, 0.75]
}
},
{
@@ -52,7 +52,7 @@
"backend": "openai-chat-omni",
"endpoint": "/v1/chat/completions",
"num_prompts": [40],
"request_rate": [0.3],
"request_rate": [0.5],
"random_input_len": 100,
"random_output_len": 100,
"random_range_ratio": 0.0,
@@ -69,9 +69,9 @@
},
"percentile-metrics": "ttft,tpot,itl,e2el,audio_rtf,audio_ttfp,audio_duration",
"baseline": {
"mean_ttft_ms": [4000],
"mean_audio_ttfp_ms": [13000],
"mean_audio_rtf": [0.35]
"mean_ttft_ms": [6000],
"mean_audio_ttfp_ms": [15000],
"mean_audio_rtf": [0.45]
}
},
{
@@ -79,7 +79,7 @@
"backend": "openai-chat-omni",
"endpoint": "/v1/chat/completions",
"num_prompts": [100],
"request_rate": [0.5],
"request_rate": [1.0],
"random_input_len": 100,
"random_output_len": 100,
"random_range_ratio": 0.0,
@@ -98,9 +98,9 @@
},
"percentile-metrics": "ttft,tpot,itl,e2el,audio_rtf,audio_ttfp,audio_duration",
"baseline": {
"mean_ttft_ms": [6000],
"mean_audio_ttfp_ms": [15000],
"mean_audio_rtf": [0.45]
"mean_ttft_ms": [12000],
"mean_audio_ttfp_ms": [18000],
"mean_audio_rtf": [0.9]
}
}
]
@@ -116,16 +116,16 @@
"dataset_name": "random",
"backend": "openai-chat-omni",
"endpoint": "/v1/chat/completions",
"num_prompts": [4, 16, 40],
"max_concurrency": [1, 4, 10],
"num_prompts": [4, 16, 32, 64],
"max_concurrency": [1, 4, 8, 16],
"random_input_len": 2500,
"random_output_len": 900,
"ignore_eos": true,
"percentile-metrics": "ttft,tpot,itl,e2el,audio_rtf,audio_ttfp,audio_duration",
"baseline": {
"mean_ttft_ms": [1000, 3000, 5000],
"mean_audio_ttfp_ms": [1000, 3000, 5000],
"mean_audio_rtf": [0.2, 0.35, 0.6]
"mean_ttft_ms": [1000, 3000, 5000, 7000],
"mean_audio_ttfp_ms": [1000, 3000, 5000, 7000],
"mean_audio_rtf": [0.2, 0.35, 0.6, 0.85]
}
},
{
@@ -158,7 +158,7 @@
"backend": "openai-chat-omni",
"endpoint": "/v1/chat/completions",
"num_prompts": [40],
"request_rate": [0.3],
"request_rate": [0.5],
"random_input_len": 100,
"random_output_len": 100,
"random_range_ratio": 0.0,
@@ -175,9 +175,9 @@
},
"percentile-metrics": "ttft,tpot,itl,e2el,audio_rtf,audio_ttfp,audio_duration",
"baseline": {
"mean_ttft_ms": [4000],
"mean_audio_ttfp_ms": [4000],
"mean_audio_rtf": [0.4]
"mean_ttft_ms": [6000],
"mean_audio_ttfp_ms": [6000],
"mean_audio_rtf": [0.7]
}
},
{
@@ -185,7 +185,7 @@
"backend": "openai-chat-omni",
"endpoint": "/v1/chat/completions",
"num_prompts": [100],
"request_rate": [0.5],
"request_rate": [1.0],
"random_input_len": 100,
"random_output_len": 100,
"random_range_ratio": 0.0,
@@ -204,17 +204,17 @@
},
"percentile-metrics": "ttft,tpot,itl,e2el,audio_rtf,audio_ttfp,audio_duration",
"baseline": {
"mean_ttft_ms": [6000],
"mean_audio_ttfp_ms": [6000],
"mean_audio_rtf": [0.7]
"mean_ttft_ms": [12000],
"mean_audio_ttfp_ms": [12000],
"mean_audio_rtf": [1.0]
}
},
{
"dataset_name": "random",
"backend": "openai-chat-omni",
"endpoint": "/v1/chat/completions",
"num_prompts": [4, 16, 40],
"max_concurrency": [1, 4, 10],
"num_prompts": [4, 16, 32, 64, 128],
"max_concurrency": [1, 4, 8, 16, 32],
"random_input_len": 2500,
"random_output_len": 900,
"ignore_eos": true,
@@ -223,7 +223,7 @@
},
"percentile-metrics": "ttft,tpot,itl,e2el",
"baseline": {
"mean_ttft_ms": [1000, 3000, 5000]
"mean_ttft_ms": [1000, 3000, 5000, 7000, 9000]
}
},
{
@@ -257,7 +257,7 @@
"backend": "openai-chat-omni",
"endpoint": "/v1/chat/completions",
"num_prompts": [40],
"request_rate": [0.3],
"request_rate": [0.5],
"random_input_len": 100,
"random_output_len": 100,
"random_range_ratio": 0.0,
@@ -277,7 +277,7 @@
},
"percentile-metrics": "ttft,tpot,itl,e2el",
"baseline": {
"mean_ttft_ms": [4000]
"mean_ttft_ms": [6000]
}
},
{
@@ -285,7 +285,7 @@
"backend": "openai-chat-omni",
"endpoint": "/v1/chat/completions",
"num_prompts": [100],
"request_rate": [0.5],
"request_rate": [1.0],
"random_input_len": 100,
"random_output_len": 100,
"random_range_ratio": 0.0,
@@ -0,0 +1,107 @@
[
{
"test_name": "test_wan22_i2v_single_device",
"description": "Single-device baseline",
"server_type": "vllm-omni",
"server_params": {
"model": "Wan-AI/Wan2.2-I2V-A14B-Diffusers",
"serve_args": {
"enable-diffusion-pipeline-profiler": true
}
},
"benchmark_params": [
{
"name": "832x480_frames81_steps4",
"dataset": "random",
"task": "i2v",
"num-prompts": 10,
"max-concurrency": 1,
"num-input-images": 1,
"seed": 42,
"enable-negative-prompt": true,
"random-request-config": [
{
"width": 832,
"height": 480,
"num_inference_steps": 4,
"num_frames": 81,
"fps": 16,
"weight": 1
}
],
"baseline": {
"throughput_qps": 0.034,
"latency_mean": 26.0,
"peak_memory_mb_mean": 80000
}
}
]
},
{
"test_name": "test_wan22_i2v_usp2_vae_patch2_hsdp_slicing",
"description": "USP=2 + VAE patch parallel=2 + HSDP + VAE slicing",
"server_type": "vllm-omni",
"server_params": {
"model": "Wan-AI/Wan2.2-I2V-A14B-Diffusers",
"serve_args": {
"usp": 2,
"vae-patch-parallel-size": 2,
"use-hsdp": true,
"vae-use-slicing": true,
"enable-diffusion-pipeline-profiler": true
}
},
"benchmark_params": [
{
"name": "832x480_frames81_steps4",
"dataset": "random",
"task": "i2v",
"num-prompts": 10,
"max-concurrency": 1,
"num-input-images": 1,
"seed": 42,
"enable-negative-prompt": true,
"random-request-config": [
{
"width": 832,
"height": 480,
"num_inference_steps": 4,
"num_frames": 81,
"fps": 16,
"weight": 1
}
],
"baseline": {
"throughput_qps": 0.042,
"latency_mean": 21.6,
"peak_memory_mb_mean": 55300
}
},
{
"name": "1280x720_frames121_steps4",
"dataset": "random",
"task": "i2v",
"num-prompts": 10,
"max-concurrency": 1,
"num-input-images": 1,
"seed": 42,
"enable-negative-prompt": true,
"random-request-config": [
{
"width": 1280,
"height": 720,
"num_inference_steps": 4,
"num_frames": 121,
"fps": 16,
"weight": 1
}
],
"baseline": {
"throughput_qps": 0.0085,
"latency_mean": 101.6,
"peak_memory_mb_mean": 65200
}
}
]
}
]
+65 -1
View File
@@ -1,4 +1,14 @@
"""Stability pytest hooks and fixtures."""
"""
Stability-specific conftest: when pytest is executed under this directory,
resource monitoring is started before each test and finalized after each test,
so each stability test case gets its own HTML report (one report per case).
No need to wrap pytest with `bash resource_monitor.sh run -- pytest ...`.
Duration-based benchmark helper functions are hosted in ``helpers.py``,
while this file focuses on pytest fixtures and setup/teardown.
"""
from __future__ import annotations
import subprocess
import sys
@@ -6,12 +16,66 @@ import threading
import pytest
from tests.dfx.conftest import get_benchmark_params_for_server
from tests.dfx.stability.helpers import (
finalize_resource_monitor,
report_latest_gpu_samples,
start_resource_monitor,
wait_for_run_dir,
)
from tests.helpers.runtime import OmniServer
DEFAULT_STABILITY_SERVER_TIMEOUT_ARGS = ["--stage-init-timeout", "600", "--init-timeout", "900"]
_omni_server_lock = threading.Lock()
@pytest.fixture(scope="module")
def omni_server(request: pytest.FixtureRequest):
"""Start OmniServer for stability tests, with per-module timeout override."""
timeout_args = getattr(request.module, "STABILITY_SERVER_TIMEOUT_ARGS", DEFAULT_STABILITY_SERVER_TIMEOUT_ARGS)
with _omni_server_lock:
# Same 5-tuple and CLI composition as ``tests/dfx/perf/scripts/run_benchmark.py`` on main;
# ``serve_args`` from JSON are folded into ``extra_cli_args`` inside
# ``create_unique_server_params``.
test_name, model, deploy_path, stage_overrides, extra_cli_args = request.param
print(f"Starting OmniServer with test: {test_name}, model: {model}")
server_args = list(timeout_args)
if deploy_path:
server_args = ["--deploy-config", deploy_path] + server_args
if stage_overrides:
server_args = ["--stage-overrides", stage_overrides] + server_args
if extra_cli_args:
server_args = list(extra_cli_args) + server_args
with OmniServer(model, server_args) as server:
server.test_name = test_name
print("OmniServer started successfully")
yield server
print("OmniServer stopping...")
print("OmniServer stopped")
@pytest.fixture
def stability_benchmark_params(request: pytest.FixtureRequest, omni_server):
test_name, param_index = request.param
if test_name != omni_server.test_name:
pytest.skip(f"Skipping parameter for {test_name} - current server is {omni_server.test_name}")
server_to_benchmark_mapping = getattr(request.module, "server_to_benchmark_mapping", None)
if server_to_benchmark_mapping is None:
raise ValueError("server_to_benchmark_mapping must be defined in the test module")
all_params = get_benchmark_params_for_server(test_name, server_to_benchmark_mapping)
if not all_params:
raise ValueError(f"No benchmark parameters found for test: {test_name}")
if param_index >= len(all_params):
raise ValueError(f"No benchmark parameters found for index {param_index} in test: {test_name}")
current = param_index + 1
total = len(all_params)
print(f"\n Running benchmark {current}/{total} for {test_name}")
return {"test_name": test_name, "params": all_params[param_index]}
@pytest.fixture(autouse=True)
+388 -1
View File
@@ -1,17 +1,32 @@
"""Stability resource monitor helpers."""
"""Stability helpers for resource monitoring and benchmark execution."""
from __future__ import annotations
import json
import os
import random
import re
import shlex
import subprocess
import sys
import tempfile
import threading
import time
from collections.abc import Callable
from pathlib import Path
from typing import Any
from tests.dfx.conftest import run_benchmark
STABILITY_DIR = Path(__file__).resolve().parent
RESOURCE_MONITOR_SCRIPT = STABILITY_DIR / "scripts" / "resource_monitor.sh"
REPO_ROOT = STABILITY_DIR.parent.parent.parent
_BUCKET_KEY_PATTERN = re.compile(r"^\(\s*([^,]+)\s*,\s*([^,]+)\s*,\s*([^,]+)\s*\)$")
RunOneBatchFn = Callable[
[str, int, str, dict[str, Any], int, float | None, int | None, str, int],
dict[str, Any],
]
def start_resource_monitor():
@@ -115,3 +130,375 @@ def finalize_resource_monitor() -> str | None:
return None
except (FileNotFoundError, OSError, subprocess.TimeoutExpired):
return None
def _normalize_bench_metrics(raw: dict[str, Any]) -> dict[str, Any]:
completed = int(raw.get("completed", raw.get("completed_requests", 0) or 0))
failed = int(raw.get("failed", raw.get("failed_requests", 0) or 0))
duration = float(raw.get("duration", 0.0) or 0.0)
errors = list(raw.get("errors") or [])
if failed and not errors:
errors = [f"{failed} benchmark request(s) failed"]
return {"completed": completed, "failed": failed, "duration": duration, "errors": errors}
def _build_base_args(params: dict[str, Any], host: str, port: int) -> list[str]:
exclude = {
"request_rate",
"max_concurrency",
"num_prompts",
"baseline",
"duration_sec",
"num_prompts_per_batch",
}
args = ["--host", host, "--port", str(port)]
for key, value in params.items():
if key in exclude or value is None:
continue
arg_name = f"--{key.replace('_', '-')}"
if isinstance(value, bool) and value:
args.append(arg_name)
elif isinstance(value, dict):
args.extend([arg_name, json.dumps(value, ensure_ascii=False, separators=(",", ":"))])
elif not isinstance(value, bool):
args.extend([arg_name, str(value)])
return args
def _build_diffusion_cmd(
host: str,
port: int,
model: str,
params: dict[str, Any],
num_prompts: int,
request_rate: float | None,
max_concurrency: int | None,
output_path: Path,
diffusion_benchmark_script: Path,
) -> list[str]:
skip_keys = {
"request_rate",
"max_concurrency",
"num_prompts",
"baseline",
"duration_sec",
"num_prompts_per_batch",
}
cmd: list[str] = [
sys.executable,
"-u",
str(diffusion_benchmark_script),
"--host",
host,
"--port",
str(port),
"--model",
model,
"--output-file",
str(output_path),
]
for key, value in params.items():
if key in skip_keys or value is None:
continue
flag = f"--{str(key).replace('_', '-')}"
if isinstance(value, bool) and value:
cmd.append(flag)
elif isinstance(value, bool):
continue
elif isinstance(value, (dict, list)):
cmd.extend([flag, json.dumps(value, ensure_ascii=False, separators=(",", ":"))])
else:
cmd.extend([flag, str(value)])
cmd.extend(["--num-prompts", str(num_prompts)])
if request_rate is not None:
cmd.extend(["--request-rate", str(request_rate)])
else:
cmd.extend(["--max-concurrency", str(max_concurrency), "--request-rate", "inf"])
return cmd
def _sample_int_from_range_spec(value: Any, rng: random.Random) -> Any:
"""Resolve one value that may be scalar or range spec into an int."""
if isinstance(value, int):
return value
if isinstance(value, (list, tuple)) and len(value) == 2 and all(isinstance(v, int) for v in value):
low, high = int(value[0]), int(value[1])
if low > high:
low, high = high, low
return rng.randint(low, high)
if isinstance(value, dict) and {"min", "max"} <= set(value):
low, high = int(value["min"]), int(value["max"])
if low > high:
low, high = high, low
return rng.randint(low, high)
if isinstance(value, str):
raw = value.strip()
if raw.isdigit():
return int(raw)
if "-" in raw:
parts = [p.strip() for p in raw.split("-", 1)]
if len(parts) == 2 and parts[0].isdigit() and parts[1].isdigit():
low, high = int(parts[0]), int(parts[1])
if low > high:
low, high = high, low
return rng.randint(low, high)
return value
def _sample_bucket_key(raw_key: str, rng: random.Random) -> str:
"""Sample bucket tuple keys that use range syntax, e.g. ``(128-512, 128-512, 1)``."""
match = _BUCKET_KEY_PATTERN.match(raw_key.strip())
if not match:
return raw_key
sampled_parts: list[int] = []
for token in match.groups():
sampled = _sample_int_from_range_spec(token.strip(), rng)
if not isinstance(sampled, int):
return raw_key
sampled_parts.append(sampled)
# For video buckets (height>0 and num_frames>1), enforce even H/W to avoid
# ffmpeg yuv420p encoding/decoding failures ("Could not open video stream").
if sampled_parts[0] > 0 and sampled_parts[2] > 1:
sampled_parts[0] = max(2, sampled_parts[0] - (sampled_parts[0] % 2))
sampled_parts[1] = max(2, sampled_parts[1] - (sampled_parts[1] % 2))
return f"({sampled_parts[0]}, {sampled_parts[1]}, {sampled_parts[2]})"
def _sample_stability_batch_params(params: dict[str, Any], batch_index: int) -> dict[str, Any]:
"""Materialize per-batch random values for configured range fields."""
sampled = dict(params)
rng = random.Random(time.time_ns() + batch_index)
for field_name in (
"random_input_len",
"random_output_len",
"random_mm_base_items_per_request",
"width",
"height",
):
if field_name in sampled:
sampled[field_name] = _sample_int_from_range_spec(sampled[field_name], rng)
bucket_config = sampled.get("random_mm_bucket_config")
if isinstance(bucket_config, dict):
sampled_bucket_config: dict[str, float] = {}
for raw_key, probability in bucket_config.items():
sampled_key = _sample_bucket_key(str(raw_key), rng)
sampled_bucket_config[sampled_key] = sampled_bucket_config.get(sampled_key, 0.0) + float(probability)
sampled["random_mm_bucket_config"] = sampled_bucket_config
return sampled
def _run_one_vllm_bench_batch(
host: str,
port: int,
_model: str,
params: dict[str, Any],
num_prompts: int,
request_rate: float | None,
max_concurrency: int | None,
result_dir: str,
batch_index: int,
) -> dict[str, Any]:
base = _build_base_args(params, host, port)
if request_rate is not None:
args = base + ["--request-rate", str(request_rate), "--num-prompts", str(num_prompts)]
flow = request_rate
else:
args = base + [
"--max-concurrency",
str(max_concurrency),
"--num-prompts",
str(num_prompts),
"--request-rate",
"inf",
]
flow = max_concurrency
# Print the exact per-batch benchmark CLI (randomized params are already materialized).
preview_cmd = ["vllm", "bench", "serve", "--omni", *args]
print(f"\n[Stability][Batch {batch_index}] Benchmark command:")
print(shlex.join(preview_cmd))
dataset_name = params.get("dataset_name", "random")
old_benchmark_dir = os.environ.get("BENCHMARK_DIR")
try:
os.environ["BENCHMARK_DIR"] = result_dir
result = run_benchmark(
args=args,
test_name="stability",
flow=flow,
dataset_name=dataset_name,
num_prompt=num_prompts,
random_input_len=params.get("random_input_len"),
random_output_len=params.get("random_output_len"),
)
return _normalize_bench_metrics(result)
except (FileNotFoundError, OSError) as exc:
return {
"completed": 0,
"failed": 1,
"duration": 0.0,
"errors": [f"Benchmark batch failed: {type(exc).__name__}: {exc}"],
}
finally:
if old_benchmark_dir is not None:
os.environ["BENCHMARK_DIR"] = old_benchmark_dir
elif "BENCHMARK_DIR" in os.environ:
os.environ.pop("BENCHMARK_DIR")
def _run_one_diffusion_batch(
host: str,
port: int,
model: str,
params: dict[str, Any],
num_prompts: int,
request_rate: float | None,
max_concurrency: int | None,
_result_dir: str,
_batch_index: int,
) -> dict[str, Any]:
diffusion_benchmark_script = Path(REPO_ROOT / "benchmarks" / "diffusion" / "diffusion_benchmark_serving.py")
with tempfile.NamedTemporaryFile(mode="w", suffix=".json", prefix="stability_diffusion_", delete=False) as tmp:
out_path = Path(tmp.name)
try:
cmd = _build_diffusion_cmd(
host,
port,
model,
params,
num_prompts,
request_rate,
max_concurrency,
out_path,
diffusion_benchmark_script,
)
proc = subprocess.run(
cmd,
cwd=str(REPO_ROOT),
capture_output=True,
text=True,
)
if proc.stdout:
print(proc.stdout, end="" if proc.stdout.endswith("\n") else "\n")
if proc.stderr:
print(proc.stderr, end="" if proc.stderr.endswith("\n") else "\n")
if proc.returncode != 0:
return {
"completed": 0,
"failed": 1,
"duration": 0.0,
"errors": [f"diffusion_benchmark_serving.py exited {proc.returncode}"],
}
if not out_path.is_file():
return {
"completed": 0,
"failed": 1,
"duration": 0.0,
"errors": [f"Missing benchmark output: {out_path}"],
}
with open(out_path, encoding="utf-8") as file:
metrics = json.load(file)
return _normalize_bench_metrics(metrics)
except (FileNotFoundError, OSError, json.JSONDecodeError) as exc:
return {
"completed": 0,
"failed": 1,
"duration": 0.0,
"errors": [f"Diffusion batch failed: {type(exc).__name__}: {exc}"],
}
finally:
out_path.unlink(missing_ok=True)
def merge_batch_results(batch_results: list[dict[str, Any]], total_duration_sec: float) -> dict[str, Any]:
if not batch_results:
return {"completed": 0, "failed": 0, "duration": total_duration_sec, "errors": []}
completed = sum(result.get("completed", 0) for result in batch_results)
failed = sum(result.get("failed", 0) for result in batch_results)
merged: dict[str, Any] = {
"completed": completed,
"failed": failed,
"duration": total_duration_sec,
"errors": [],
}
for result in batch_results:
merged["errors"].extend(result.get("errors") or [])
return merged
def print_merged_report(result: dict[str, Any]) -> None:
fmt = "{:<40} {:<10}"
fmt_float = "{:<40} {:<10.2f}"
completed = result.get("completed", 0)
failed = result.get("failed", 0)
duration = float(result.get("duration", 0.0) or 0.0)
print("\n============ Stability Benchmark Summary ============")
print(fmt.format("Successful requests:", completed))
print(fmt.format("Failed requests:", failed))
print(fmt_float.format("Total duration (s):", duration))
print("==================================================\n")
def run_stability_benchmark_loop(
host: str,
port: int,
model: str,
duration_sec: int | float,
params: dict[str, Any],
*,
request_rate: float | None,
max_concurrency: int | None,
result_dir: str,
num_prompts_per_batch: int,
run_one_batch: RunOneBatchFn,
result_filename: str | None = None,
) -> dict[str, Any]:
if (request_rate is None) == (max_concurrency is None):
raise ValueError("Exactly one of request_rate or max_concurrency must be specified")
start_time = time.perf_counter()
batch_results: list[dict[str, Any]] = []
batch_index = 0
while True:
if (time.perf_counter() - start_time) >= duration_sec:
break
sampled_params = _sample_stability_batch_params(params, batch_index)
result = run_one_batch(
host,
port,
model,
sampled_params,
num_prompts_per_batch,
request_rate,
max_concurrency,
result_dir,
batch_index,
)
batch_results.append(result)
batch_index += 1
if (time.perf_counter() - start_time) >= duration_sec:
break
total_duration = time.perf_counter() - start_time
merged = merge_batch_results(batch_results, total_duration)
print_merged_report(merged)
if result_filename and result_dir:
result_path = Path(result_dir) / result_filename
with open(result_path, "w", encoding="utf-8") as file:
json.dump(merged, file, indent=2, ensure_ascii=False)
return merged
@@ -1,297 +0,0 @@
"""
Stability test cases: start OmniServer first, then run benchmark traffic with either
`request-rate` or `max-concurrency` for a fixed duration. No new requests are sent
after the duration is reached, and the test asserts that there are no failed requests.
The overall flow matches the perf logic: `load_configs`, `modify_stage`,
`create_unique_server_params`, `create_test_parameter_mapping`,
`get_benchmark_params_for_server`, `create_benchmark_indices`, and the
`omni_server` fixture are aligned with perf. Only the benchmark execution
(`run_stability_benchmark`, which is duration-based here) and the test cases differ.
All test-specific parameters, such as `duration_sec`, `request_rate` /
`max_concurrency`, and `num_prompts_per_batch`, are configured in
`tests/dfx/stability/tests/test.json` and are no longer overridden
through environment variables.
"""
import json
import os
import threading
import time
from pathlib import Path
from typing import Any
import pytest
from tests.dfx.conftest import (
create_benchmark_indices,
create_test_parameter_mapping,
create_unique_server_params,
get_benchmark_params_for_server,
load_configs,
)
from tests.dfx.perf.scripts.run_benchmark import run_benchmark
from tests.helpers.runtime import OmniServer
STABILITY_DIR = Path(__file__).resolve().parent.parent
DEPLOY_CONFIGS_DIR = STABILITY_DIR / "deploy"
CONFIG_FILE_PATH = str(STABILITY_DIR / "tests" / "test.json")
DEFAULT_NUM_PROMPTS_PER_BATCH = 20
try:
BENCHMARK_CONFIGS = load_configs(CONFIG_FILE_PATH)
except FileNotFoundError:
BENCHMARK_CONFIGS = []
test_params = create_unique_server_params(BENCHMARK_CONFIGS, DEPLOY_CONFIGS_DIR) if BENCHMARK_CONFIGS else []
server_to_benchmark_mapping = create_test_parameter_mapping(BENCHMARK_CONFIGS) if BENCHMARK_CONFIGS else {}
_omni_server_lock = threading.Lock()
benchmark_indices = create_benchmark_indices(BENCHMARK_CONFIGS, server_to_benchmark_mapping)
def _build_base_args(params: dict[str, Any], host: str, port: int) -> list[str]:
exclude = {
"request_rate",
"max_concurrency",
"num_prompts",
"baseline",
"duration_sec",
"num_prompts_per_batch",
}
args = ["--host", host, "--port", str(port)]
for key, value in params.items():
if key in exclude or value is None:
continue
arg_name = f"--{key.replace('_', '-')}"
if isinstance(value, bool) and value:
args.append(arg_name)
elif isinstance(value, dict):
args.extend([arg_name, json.dumps(value, ensure_ascii=False, separators=(",", ":"))])
elif not isinstance(value, bool):
args.extend([arg_name, str(value)])
return args
def _run_one_benchmark_batch(
host: str,
port: int,
params: dict[str, Any],
num_prompts: int,
request_rate: float | None,
max_concurrency: int | None,
result_dir: str,
batch_index: int,
) -> dict[str, Any]:
base = _build_base_args(params, host, port)
if request_rate is not None:
args = base + ["--request-rate", str(request_rate), "--num-prompts", str(num_prompts)]
flow = request_rate
else:
args = base + [
"--max-concurrency",
str(max_concurrency),
"--num-prompts",
str(num_prompts),
"--request-rate",
"inf",
]
flow = max_concurrency
dataset_name = params.get("dataset_name", "random")
old_benchmark_dir = os.environ.get("BENCHMARK_DIR")
try:
os.environ["BENCHMARK_DIR"] = result_dir
result = run_benchmark(
args=args,
test_name="stability",
flow=flow,
dataset_name=dataset_name,
num_prompt=num_prompts,
random_input_len=params.get("random_input_len"),
random_output_len=params.get("random_output_len"),
)
return result
except (FileNotFoundError, OSError) as e:
# Surface batch failure so the stability test does not false-pass when
# run_benchmark fails before writing JSON (e.g. command not found).
return {
"completed": 0,
"failed": 1,
"duration": 0.0,
"errors": [f"Benchmark batch failed: {type(e).__name__}: {e}"],
}
finally:
if old_benchmark_dir is not None:
os.environ["BENCHMARK_DIR"] = old_benchmark_dir
elif "BENCHMARK_DIR" in os.environ:
os.environ.pop("BENCHMARK_DIR")
def _merge_batch_results(batch_results: list[dict[str, Any]], total_duration_sec: float) -> dict[str, Any]:
if not batch_results:
return {"completed": 0, "failed": 0, "duration": total_duration_sec, "errors": []}
completed = sum(r.get("completed", 0) for r in batch_results)
failed = sum(r.get("failed", 0) for r in batch_results)
merged: dict[str, Any] = {
"completed": completed,
"failed": failed,
"duration": total_duration_sec,
"errors": [],
}
for r in batch_results:
merged["errors"].extend(r.get("errors") or [])
return merged
def _print_merged_report(result: dict[str, Any]) -> None:
"""Print the final summary: successful requests, failed requests, and total duration only."""
fmt = "{:<40} {:<10}"
fmt_float = "{:<40} {:<10.2f}"
completed = result.get("completed", 0)
failed = result.get("failed", 0)
duration = float(result.get("duration", 0.0) or 0.0)
print("\n============ Stability Benchmark Summary ============")
print(fmt.format("Successful requests:", completed))
print(fmt.format("Failed requests:", failed))
print(fmt_float.format("Total duration (s):", duration))
print("==================================================\n")
def run_stability_benchmark(
host: str,
port: int,
duration_sec: int | float,
params: dict[str, Any],
*,
request_rate: float | None = None,
max_concurrency: int | None = None,
result_filename: str | None = None,
result_dir: str = "./",
num_prompts_per_batch: int = DEFAULT_NUM_PROMPTS_PER_BATCH,
) -> dict[str, Any]:
if (request_rate is None) == (max_concurrency is None):
raise ValueError("Exactly one of request_rate or max_concurrency must be specified")
start_time = time.perf_counter()
batch_results: list[dict[str, Any]] = []
batch_index = 0
while True:
if (time.perf_counter() - start_time) >= duration_sec:
break
result = _run_one_benchmark_batch(
host=host,
port=port,
params=params,
num_prompts=num_prompts_per_batch,
request_rate=request_rate,
max_concurrency=max_concurrency,
result_dir=result_dir,
batch_index=batch_index,
)
batch_results.append(result)
batch_index += 1
if (time.perf_counter() - start_time) >= duration_sec:
break
total_duration = time.perf_counter() - start_time
merged = _merge_batch_results(batch_results, total_duration)
_print_merged_report(merged)
if result_filename and result_dir:
result_path = Path(result_dir) / result_filename
with open(result_path, "w", encoding="utf-8") as f:
json.dump(merged, f, indent=2, ensure_ascii=False)
return merged
@pytest.fixture(scope="module")
def omni_server(request):
"""Start vLLM-Omni server as a subprocess with actual model weights.
Uses session scope so the server starts only once for the entire test session.
Multi-stage initialization can take 10-20+ minutes.
"""
with _omni_server_lock:
test_name, model, stage_config_path, stage_overrides, extra_cli_args = request.param
print(f"Starting OmniServer with test: {test_name}, model: {model}")
server_args = ["--stage-init-timeout", "120"]
# --deploy-config and --stage-overrides compose at the CLI (see vllm_omni/entrypoints/utils.py):
# deploy-config sets the base; stage-overrides are applied on top. Both can be set.
if stage_config_path:
server_args = ["--deploy-config", stage_config_path] + server_args
if stage_overrides:
server_args = ["--stage-overrides", stage_overrides] + server_args
if extra_cli_args:
server_args = list(extra_cli_args) + server_args
with OmniServer(model, server_args) as server:
server.test_name = test_name
print("OmniServer started successfully")
yield server
print("OmniServer stopping...")
print("OmniServer stopped")
@pytest.fixture(params=benchmark_indices)
def stability_benchmark_params(request, omni_server):
"""Benchmark parameters fixture with proper parametrization (same as perf)."""
test_name, param_index = request.param
if test_name != omni_server.test_name:
pytest.skip(f"Skipping parameter for {test_name} - current server is {omni_server.test_name}")
all_params = get_benchmark_params_for_server(test_name, server_to_benchmark_mapping)
if not all_params:
raise ValueError(f"No benchmark parameters found for test: {test_name}")
if param_index >= len(all_params):
raise ValueError(f"No benchmark parameters found for index {param_index} in test: {test_name}")
current = param_index + 1
total = len(all_params)
print(f"\n Running benchmark {current}/{total} for {test_name}")
return {"test_name": test_name, "params": all_params[param_index]}
@pytest.mark.slow
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
@pytest.mark.parametrize("stability_benchmark_params", benchmark_indices, indirect=True)
def test_benchmark_stability(omni_server, stability_benchmark_params):
"""Run the benchmark for a fixed duration using request-rate or max-concurrency and assert zero failed requests."""
test_name = stability_benchmark_params["test_name"]
params = stability_benchmark_params["params"]
duration_sec = params.get("duration_sec", 300)
num_prompts_per_batch = params.get("num_prompts_per_batch", DEFAULT_NUM_PROMPTS_PER_BATCH)
request_rate = params.get("request_rate")
max_concurrency = params.get("max_concurrency")
bench_params = {
k: v
for k, v in params.items()
if k not in ("duration_sec", "request_rate", "max_concurrency", "num_prompts_per_batch")
}
result = run_stability_benchmark(
host=omni_server.host,
port=omni_server.port,
duration_sec=duration_sec,
params=bench_params,
request_rate=request_rate,
max_concurrency=max_concurrency,
result_dir=str(STABILITY_DIR),
num_prompts_per_batch=num_prompts_per_batch,
)
assert result.get("failed", 0) == 0, f"[{test_name}] Failed requests detected: {result.get('errors', [])}"
assert result.get("completed", 0) > 0, f"[{test_name}] No requests completed"
@@ -0,0 +1,68 @@
"""
Qwen3-Omni stability: OmniServer + ``vllm bench serve --omni`` for a fixed duration.
Configuration: ``tests/dfx/stability/tests/test_qwen3_omni.json``.
"""
from __future__ import annotations
from pathlib import Path
import pytest
from tests.dfx.conftest import (
create_benchmark_indices,
create_test_parameter_mapping,
create_unique_server_params,
load_configs,
)
from tests.dfx.stability.helpers import _run_one_vllm_bench_batch, run_stability_benchmark_loop
STABILITY_DIR = Path(__file__).resolve().parent.parent
DEPLOY_CONFIGS_DIR = STABILITY_DIR / "deploy"
CONFIG_FILE_PATH = str(STABILITY_DIR / "tests" / "test_qwen3_omni.json")
DEFAULT_NUM_PROMPTS_PER_BATCH = 20
STABILITY_SERVER_TIMEOUT_ARGS = ["--stage-init-timeout", "600"]
try:
BENCHMARK_CONFIGS = load_configs(CONFIG_FILE_PATH)
except FileNotFoundError:
BENCHMARK_CONFIGS = []
test_params = create_unique_server_params(BENCHMARK_CONFIGS, DEPLOY_CONFIGS_DIR) if BENCHMARK_CONFIGS else []
server_to_benchmark_mapping = create_test_parameter_mapping(BENCHMARK_CONFIGS) if BENCHMARK_CONFIGS else {}
benchmark_indices = create_benchmark_indices(BENCHMARK_CONFIGS, server_to_benchmark_mapping)
@pytest.mark.slow
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
@pytest.mark.parametrize("stability_benchmark_params", benchmark_indices, indirect=True)
def test_stability_qwen3_omni(omni_server, stability_benchmark_params):
test_name = stability_benchmark_params["test_name"]
params = stability_benchmark_params["params"]
duration_sec = params.get("duration_sec", 300)
num_prompts_per_batch = params.get("num_prompts_per_batch", DEFAULT_NUM_PROMPTS_PER_BATCH)
request_rate = params.get("request_rate")
max_concurrency = params.get("max_concurrency")
bench_params = {
k: v
for k, v in params.items()
if k not in ("duration_sec", "request_rate", "max_concurrency", "num_prompts_per_batch")
}
result = run_stability_benchmark_loop(
host=omni_server.host,
port=omni_server.port,
model=omni_server.model,
duration_sec=duration_sec,
params=bench_params,
request_rate=request_rate,
max_concurrency=max_concurrency,
result_dir=str(STABILITY_DIR),
num_prompts_per_batch=num_prompts_per_batch,
run_one_batch=_run_one_vllm_bench_batch,
)
assert result.get("failed", 0) == 0, f"[{test_name}] Failed requests detected: {result.get('errors', [])}"
assert result.get("completed", 0) > 0, f"[{test_name}] No requests completed"
@@ -0,0 +1,68 @@
"""
Qwen3-TTS stability: OmniServer + ``vllm bench serve --omni`` for a fixed duration.
Configuration: ``tests/dfx/stability/tests/test_qwen3_tts.json``.
"""
from __future__ import annotations
from pathlib import Path
import pytest
from tests.dfx.conftest import (
create_benchmark_indices,
create_test_parameter_mapping,
create_unique_server_params,
load_configs,
)
from tests.dfx.stability.helpers import _run_one_vllm_bench_batch, run_stability_benchmark_loop
STABILITY_DIR = Path(__file__).resolve().parent.parent
DEPLOY_CONFIGS_DIR = STABILITY_DIR / "deploy"
CONFIG_FILE_PATH = str(STABILITY_DIR / "tests" / "test_qwen3_tts.json")
DEFAULT_NUM_PROMPTS_PER_BATCH = 20
STABILITY_SERVER_TIMEOUT_ARGS = ["--stage-init-timeout", "600"]
try:
BENCHMARK_CONFIGS = load_configs(CONFIG_FILE_PATH)
except FileNotFoundError:
BENCHMARK_CONFIGS = []
test_params = create_unique_server_params(BENCHMARK_CONFIGS, DEPLOY_CONFIGS_DIR) if BENCHMARK_CONFIGS else []
server_to_benchmark_mapping = create_test_parameter_mapping(BENCHMARK_CONFIGS) if BENCHMARK_CONFIGS else {}
benchmark_indices = create_benchmark_indices(BENCHMARK_CONFIGS, server_to_benchmark_mapping)
@pytest.mark.slow
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
@pytest.mark.parametrize("stability_benchmark_params", benchmark_indices, indirect=True)
def test_stability_qwen3_tts(omni_server, stability_benchmark_params):
test_name = stability_benchmark_params["test_name"]
params = stability_benchmark_params["params"]
duration_sec = params.get("duration_sec", 300)
num_prompts_per_batch = params.get("num_prompts_per_batch", DEFAULT_NUM_PROMPTS_PER_BATCH)
request_rate = params.get("request_rate")
max_concurrency = params.get("max_concurrency")
bench_params = {
k: v
for k, v in params.items()
if k not in ("duration_sec", "request_rate", "max_concurrency", "num_prompts_per_batch")
}
result = run_stability_benchmark_loop(
host=omni_server.host,
port=omni_server.port,
model=omni_server.model,
duration_sec=duration_sec,
params=bench_params,
request_rate=request_rate,
max_concurrency=max_concurrency,
result_dir=str(STABILITY_DIR),
num_prompts_per_batch=num_prompts_per_batch,
run_one_batch=_run_one_vllm_bench_batch,
)
assert result.get("failed", 0) == 0, f"[{test_name}] Failed requests detected: {result.get('errors', [])}"
assert result.get("completed", 0) > 0, f"[{test_name}] No requests completed"
@@ -0,0 +1,68 @@
"""
Qwen-Image stability: OmniServer (diffusion) + ``diffusion_benchmark_serving.py``.
Configuration: ``tests/dfx/stability/tests/test_qwen_image.json``.
"""
from __future__ import annotations
from pathlib import Path
import pytest
from tests.dfx.conftest import (
create_benchmark_indices,
create_test_parameter_mapping,
create_unique_server_params,
load_configs,
)
from tests.dfx.stability.helpers import _run_one_diffusion_batch, run_stability_benchmark_loop
STABILITY_DIR = Path(__file__).resolve().parent.parent
DEPLOY_CONFIGS_DIR = STABILITY_DIR / "deploy"
CONFIG_FILE_PATH = str(STABILITY_DIR / "tests" / "test_qwen_image.json")
DEFAULT_NUM_PROMPTS_PER_BATCH = 20
STABILITY_SERVER_TIMEOUT_ARGS = ["--stage-init-timeout", "600", "--init-timeout", "900"]
try:
BENCHMARK_CONFIGS = load_configs(CONFIG_FILE_PATH)
except FileNotFoundError:
BENCHMARK_CONFIGS = []
test_params = create_unique_server_params(BENCHMARK_CONFIGS, DEPLOY_CONFIGS_DIR) if BENCHMARK_CONFIGS else []
server_to_benchmark_mapping = create_test_parameter_mapping(BENCHMARK_CONFIGS) if BENCHMARK_CONFIGS else {}
benchmark_indices = create_benchmark_indices(BENCHMARK_CONFIGS, server_to_benchmark_mapping)
@pytest.mark.slow
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
@pytest.mark.parametrize("stability_benchmark_params", benchmark_indices, indirect=True)
def test_stability_qwen_image(omni_server, stability_benchmark_params):
test_name = stability_benchmark_params["test_name"]
params = stability_benchmark_params["params"]
duration_sec = params.get("duration_sec", 300)
num_prompts_per_batch = params.get("num_prompts_per_batch", DEFAULT_NUM_PROMPTS_PER_BATCH)
request_rate = params.get("request_rate")
max_concurrency = params.get("max_concurrency")
bench_params = {
k: v
for k, v in params.items()
if k not in ("duration_sec", "request_rate", "max_concurrency", "num_prompts_per_batch")
}
result = run_stability_benchmark_loop(
host=omni_server.host,
port=omni_server.port,
model=omni_server.model,
duration_sec=duration_sec,
params=bench_params,
request_rate=request_rate,
max_concurrency=max_concurrency,
result_dir=str(STABILITY_DIR),
num_prompts_per_batch=num_prompts_per_batch,
run_one_batch=_run_one_diffusion_batch,
)
assert result.get("failed", 0) == 0, f"[{test_name}] Failed requests detected: {result.get('errors', [])}"
assert result.get("completed", 0) > 0, f"[{test_name}] No requests completed"
@@ -0,0 +1,68 @@
"""
Wan2.2 T2V stability: OmniServer (diffusion) + ``diffusion_benchmark_serving.py`` / ``v1/videos``.
Configuration: ``tests/dfx/stability/tests/test_wan22.json``.
"""
from __future__ import annotations
from pathlib import Path
import pytest
from tests.dfx.conftest import (
create_benchmark_indices,
create_test_parameter_mapping,
create_unique_server_params,
load_configs,
)
from tests.dfx.stability.helpers import _run_one_diffusion_batch, run_stability_benchmark_loop
STABILITY_DIR = Path(__file__).resolve().parent.parent
DEPLOY_CONFIGS_DIR = STABILITY_DIR / "deploy"
CONFIG_FILE_PATH = str(STABILITY_DIR / "tests" / "test_wan22.json")
DEFAULT_NUM_PROMPTS_PER_BATCH = 20
STABILITY_SERVER_TIMEOUT_ARGS = ["--stage-init-timeout", "600", "--init-timeout", "900"]
try:
BENCHMARK_CONFIGS = load_configs(CONFIG_FILE_PATH)
except FileNotFoundError:
BENCHMARK_CONFIGS = []
test_params = create_unique_server_params(BENCHMARK_CONFIGS, DEPLOY_CONFIGS_DIR) if BENCHMARK_CONFIGS else []
server_to_benchmark_mapping = create_test_parameter_mapping(BENCHMARK_CONFIGS) if BENCHMARK_CONFIGS else {}
benchmark_indices = create_benchmark_indices(BENCHMARK_CONFIGS, server_to_benchmark_mapping)
@pytest.mark.slow
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
@pytest.mark.parametrize("stability_benchmark_params", benchmark_indices, indirect=True)
def test_stability_wan22(omni_server, stability_benchmark_params):
test_name = stability_benchmark_params["test_name"]
params = stability_benchmark_params["params"]
duration_sec = params.get("duration_sec", 300)
num_prompts_per_batch = params.get("num_prompts_per_batch", DEFAULT_NUM_PROMPTS_PER_BATCH)
request_rate = params.get("request_rate")
max_concurrency = params.get("max_concurrency")
bench_params = {
k: v
for k, v in params.items()
if k not in ("duration_sec", "request_rate", "max_concurrency", "num_prompts_per_batch")
}
result = run_stability_benchmark_loop(
host=omni_server.host,
port=omni_server.port,
model=omni_server.model,
duration_sec=duration_sec,
params=bench_params,
request_rate=request_rate,
max_concurrency=max_concurrency,
result_dir=str(STABILITY_DIR),
num_prompts_per_batch=num_prompts_per_batch,
run_one_batch=_run_one_diffusion_batch,
)
assert result.get("failed", 0) == 0, f"[{test_name}] Failed requests detected: {result.get('errors', [])}"
assert result.get("completed", 0) > 0, f"[{test_name}] No requests completed"
-77
View File
@@ -1,77 +0,0 @@
[
{
"test_name": "test_qwen3_omni_stability",
"server_params": {
"model": "Qwen/Qwen3-Omni-30B-A3B-Instruct",
"stage_overrides": {
"2": {
"max_num_batched_tokens": 1000000
}
}
},
"benchmark_params": [
{
"dataset_name": "random",
"backend": "openai-chat-omni",
"endpoint": "/v1/chat/completions",
"duration_sec": 300,
"request_rate": 0.2,
"num_prompts_per_batch": 10,
"random_input_len": 2500,
"random_output_len": 900,
"ignore_eos": true,
"percentile-metrics": "ttft,tpot,itl,e2el,audio_rtf,audio_ttfp,audio_duration"
},
{
"dataset_name": "random",
"backend": "openai-chat-omni",
"endpoint": "/v1/chat/completions",
"duration_sec": 300,
"max_concurrency": 2,
"num_prompts_per_batch": 10,
"random_input_len": 2500,
"random_output_len": 900,
"ignore_eos": true,
"percentile-metrics": "ttft,tpot,itl,e2el,audio_rtf,audio_ttfp,audio_duration"
}
]
},
{
"test_name": "test_qwen3_omni_stability_async_chunk",
"server_params": {
"model": "Qwen/Qwen3-Omni-30B-A3B-Instruct",
"stage_overrides": {
"2": {
"max_num_batched_tokens": 1000000
}
},
"extra_cli_args": ["--async-chunk"]
},
"benchmark_params": [
{
"dataset_name": "random",
"backend": "openai-chat-omni",
"endpoint": "/v1/chat/completions",
"duration_sec": 300,
"request_rate": 0.2,
"num_prompts_per_batch": 10,
"random_input_len": 2500,
"random_output_len": 900,
"ignore_eos": true,
"percentile-metrics": "ttft,tpot,itl,e2el,audio_rtf,audio_ttfp,audio_duration"
},
{
"dataset_name": "random",
"backend": "openai-chat-omni",
"endpoint": "/v1/chat/completions",
"duration_sec": 300,
"max_concurrency": 2,
"num_prompts_per_batch": 10,
"random_input_len": 2500,
"random_output_len": 900,
"ignore_eos": true,
"percentile-metrics": "ttft,tpot,itl,e2el,audio_rtf,audio_ttfp,audio_duration"
}
]
}
]
@@ -0,0 +1,97 @@
[
{
"test_name": "test_qwen3_omni_stability",
"server_params": {
"model": "Qwen/Qwen3-Omni-30B-A3B-Instruct",
"stage_overrides": {
"2": {
"max_num_batched_tokens": 1000000
}
}
},
"benchmark_params": [
{
"dataset_name": "random-mm",
"backend": "openai-chat-omni",
"endpoint": "/v1/chat/completions",
"duration_sec": 86400,
"request_rate": 0.3,
"num_prompts_per_batch": 10,
"random_input_len": {
"min": 0,
"max": 8000
},
"random_output_len": {
"min": 0,
"max": 1000
},
"random_range_ratio": 0.0,
"random_mm_base_items_per_request": {
"min": 0,
"max": 6
},
"random_mm_num_mm_items_range_ratio": 0.0,
"random_mm_limit_mm_per_prompt": {
"image": 2,
"video": 2,
"audio": 2
},
"random_mm_bucket_config": {
"(128-1024, 128-1024, 1)": 0.34,
"(256-1080, 256-1920, 2-16)": 0.33,
"(0, 1-60, 1-3)": 0.33
},
"ignore_eos": true,
"percentile-metrics": "ttft,tpot,itl,e2el,audio_rtf,audio_ttfp,audio_duration"
}
]
},
{
"test_name": "test_qwen3_omni_stability_async_chunk",
"server_params": {
"model": "Qwen/Qwen3-Omni-30B-A3B-Instruct",
"stage_overrides": {
"2": {
"max_num_batched_tokens": 1000000
}
},
"extra_cli_args": ["--async-chunk"]
},
"benchmark_params": [
{
"dataset_name": "random-mm",
"backend": "openai-chat-omni",
"endpoint": "/v1/chat/completions",
"duration_sec": 86400,
"max_concurrency": 2,
"num_prompts_per_batch": 10,
"random_input_len": {
"min": 0,
"max": 8000
},
"random_output_len": {
"min": 0,
"max": 1000
},
"random_range_ratio": 0.0,
"random_mm_base_items_per_request": {
"min": 0,
"max": 6
},
"random_mm_num_mm_items_range_ratio": 0.0,
"random_mm_limit_mm_per_prompt": {
"image": 2,
"video": 2,
"audio": 2
},
"random_mm_bucket_config": {
"(128-1024, 128-1024, 1)": 0.34,
"(256-1080, 256-1920, 2-16)": 0.33,
"(0, 1-60, 1-3)": 0.33
},
"ignore_eos": true,
"percentile-metrics": "ttft,tpot,itl,e2el,audio_rtf,audio_ttfp,audio_duration"
}
]
}
]
@@ -0,0 +1,56 @@
[
{
"test_name": "test_qwen3_tts_stability",
"server_params": {
"model": "Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice"
},
"benchmark_params": [
{
"dataset_name": "random",
"backend": "openai-audio-speech",
"endpoint": "/v1/audio/speech",
"duration_sec": 86400,
"request_rate": 0.3,
"num_prompts_per_batch": 10,
"random_input_len": {
"min": 0,
"max": 1000
},
"random_output_len": {
"min": 0,
"max": 1000
},
"random_range_ratio": 0.0,
"extra_body": {
"voice": "Vivian",
"language": "English"
},
"ignore_eos": true,
"percentile-metrics": "ttft,e2el,audio_rtf,audio_ttfp,audio_duration"
},
{
"dataset_name": "random",
"backend": "openai-audio-speech",
"endpoint": "/v1/audio/speech",
"duration_sec": 86400,
"max_concurrency": 2,
"num_prompts_per_batch": 10,
"random_input_len": {
"min": 0,
"max": 1000
},
"random_output_len": {
"min": 0,
"max": 1000
},
"random_range_ratio": 0.0,
"extra_body": {
"voice": "Vivian",
"language": "English"
},
"ignore_eos": true,
"percentile-metrics": "ttft,e2el,audio_rtf,audio_ttfp,audio_duration"
}
]
}
]
@@ -0,0 +1,28 @@
[
{
"test_name": "test_qwen_image_stability",
"server_params": {
"model": "Qwen/Qwen-Image"
},
"benchmark_params": [
{
"dataset": "random",
"task": "t2i",
"backend": "vllm-omni",
"duration_sec": 86400,
"max_concurrency": 1,
"num_prompts_per_batch": 10,
"width": {
"min": 512,
"max": 2048
},
"height": {
"min": 512,
"max": 2048
},
"num_inference_steps": 50,
"enable_negative_prompt": true
}
]
}
]
+31
View File
@@ -0,0 +1,31 @@
[
{
"test_name": "test_wan22_i2v_stability_v1_videos",
"server_params": {
"model": "Wan-AI/Wan2.2-I2V-A14B-Diffusers",
"serve_args": {
"ulysses-degree": 2,
"vae-patch-parallel-size": 2,
"tensor-parallel-size": 1,
"use-hsdp": true,
"vae-use-slicing": true,
"vae-use-tiling": true
}
},
"benchmark_params": [
{
"dataset": "random",
"task": "i2v",
"backend": "v1/videos",
"duration_sec": 86400,
"max_concurrency": 1,
"num_prompts_per_batch": 20,
"enable_negative_prompt": true,
"random_request_config": [
{"width": 832, "height": 480, "num_inference_steps": 4, "num_frames": 81, "fps": 16, "weight": 0.5},
{"width": 1280, "height": 720, "num_inference_steps": 4, "num_frames": 121, "fps": 16, "weight": 0.5}
]
}
]
}
]
@@ -6,6 +6,8 @@ import pytest
from vllm_omni.diffusion.data import DiffusionParallelConfig
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
@pytest.fixture(scope="function", autouse=True)
def setup_sp_groups(mocker):
@@ -24,9 +26,6 @@ def setup_sp_groups(mocker):
yield
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
def test_glm_image_sp_plan_defined():
"""Test that _sp_plan is properly defined on GlmImageTransformer2DModel."""
from vllm_omni.diffusion.models.glm_image.glm_image_transformer import (
@@ -0,0 +1,230 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Unit tests for LTX-2.3 pipeline integration.
These tests verify:
- Pipeline is properly registered in the diffusion registry
- Post-process function is registered
- Cache-DiT enablers are registered
- Pipeline does NOT inherit from LTX2Pipeline
- Vocoder sample rate detection logic
- Re-export module works correctly
"""
import json
import os
import tempfile
import pytest
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
class TestPipelineIndependence:
"""Verify LTX23Pipeline is fully independent from LTX2Pipeline."""
def test_ltx23_pipeline_does_not_inherit_from_ltx2(self):
"""LTX23Pipeline must NOT inherit from LTX2Pipeline."""
from vllm_omni.diffusion.models.ltx2.pipeline_ltx2 import LTX2Pipeline
from vllm_omni.diffusion.models.ltx2.pipeline_ltx2_3 import LTX23Pipeline
assert not issubclass(LTX23Pipeline, LTX2Pipeline), (
"LTX23Pipeline should be fully independent and not inherit from LTX2Pipeline"
)
def test_ltx23_pipeline_is_nn_module(self):
"""LTX23Pipeline must be an nn.Module."""
import torch.nn as nn
from vllm_omni.diffusion.models.ltx2.pipeline_ltx2_3 import LTX23Pipeline
assert issubclass(LTX23Pipeline, nn.Module)
def test_ltx23_pipeline_has_progress_bar(self):
"""LTX23Pipeline must mix in ProgressBarMixin."""
from vllm_omni.diffusion.models.ltx2.pipeline_ltx2_3 import LTX23Pipeline
from vllm_omni.diffusion.models.progress_bar import ProgressBarMixin
assert issubclass(LTX23Pipeline, ProgressBarMixin)
class TestRegistryIntegration:
"""Verify all LTX-2.3 pipeline variants are registered."""
def test_pipeline_models_registered(self):
"""LTX-2.3 pipeline variants must be in _DIFFUSION_MODELS."""
from vllm_omni.diffusion.registry import _DIFFUSION_MODELS
expected = [
"LTX23Pipeline",
"LTX23ImageToVideoPipeline",
]
for name in expected:
assert name in _DIFFUSION_MODELS, f"{name} not found in _DIFFUSION_MODELS"
def test_pipeline_module_paths(self):
"""Registry entries must point to the correct modules."""
from vllm_omni.diffusion.registry import _DIFFUSION_MODELS
# T2V -> pipeline_ltx2_3
assert _DIFFUSION_MODELS["LTX23Pipeline"] == ("ltx2", "pipeline_ltx2_3", "LTX23Pipeline")
# I2V -> pipeline_ltx2_3_image2video
assert _DIFFUSION_MODELS["LTX23ImageToVideoPipeline"] == (
"ltx2",
"pipeline_ltx2_3_image2video",
"LTX23ImageToVideoPipeline",
)
def test_post_process_funcs_registered(self):
"""Pipeline variants must map to get_ltx2_post_process_func."""
from vllm_omni.diffusion.registry import _DIFFUSION_POST_PROCESS_FUNCS
expected = [
"LTX23Pipeline",
"LTX23ImageToVideoPipeline",
]
for name in expected:
assert name in _DIFFUSION_POST_PROCESS_FUNCS, f"{name} not in _DIFFUSION_POST_PROCESS_FUNCS"
assert _DIFFUSION_POST_PROCESS_FUNCS[name] == "get_ltx2_post_process_func"
def test_cache_dit_enablers_registered(self):
"""Pipeline variants must be registered in CUSTOM_DIT_ENABLERS."""
from vllm_omni.diffusion.cache.cache_dit_backend import CUSTOM_DIT_ENABLERS
expected = [
"LTX23Pipeline",
"LTX23ImageToVideoPipeline",
]
for name in expected:
assert name in CUSTOM_DIT_ENABLERS, f"{name} not in CUSTOM_DIT_ENABLERS"
class TestVocoderSampleRateDetection:
"""Test _detect_vocoder_output_sample_rate logic."""
def test_detects_48khz_from_config(self):
"""Should detect output_sampling_rate=48000 from vocoder/config.json."""
from vllm_omni.diffusion.models.ltx2.pipeline_ltx2_3 import _detect_vocoder_output_sample_rate
with tempfile.TemporaryDirectory() as tmpdir:
vocoder_dir = os.path.join(tmpdir, "vocoder")
os.makedirs(vocoder_dir)
with open(os.path.join(vocoder_dir, "config.json"), "w") as f:
json.dump({"output_sampling_rate": 48000, "input_sampling_rate": 16000}, f)
result = _detect_vocoder_output_sample_rate(tmpdir)
assert result == 48000
def test_returns_none_for_no_output_sr(self):
"""Should return None if vocoder config has no output_sampling_rate."""
from vllm_omni.diffusion.models.ltx2.pipeline_ltx2_3 import _detect_vocoder_output_sample_rate
with tempfile.TemporaryDirectory() as tmpdir:
vocoder_dir = os.path.join(tmpdir, "vocoder")
os.makedirs(vocoder_dir)
with open(os.path.join(vocoder_dir, "config.json"), "w") as f:
json.dump({"sampling_rate": 16000}, f)
result = _detect_vocoder_output_sample_rate(tmpdir)
assert result is None
def test_returns_none_for_missing_directory(self):
"""Should return None if vocoder directory doesn't exist."""
from vllm_omni.diffusion.models.ltx2.pipeline_ltx2_3 import _detect_vocoder_output_sample_rate
result = _detect_vocoder_output_sample_rate("/nonexistent/path")
assert result is None
class TestPostProcessFunction:
"""Test the post-process function factory."""
def test_post_process_includes_audio_sample_rate(self):
"""Post-process func should include audio_sample_rate when detected."""
import torch
from vllm_omni.diffusion.models.ltx2.pipeline_ltx2_3 import get_ltx2_post_process_func
with tempfile.TemporaryDirectory() as tmpdir:
vocoder_dir = os.path.join(tmpdir, "vocoder")
os.makedirs(vocoder_dir)
with open(os.path.join(vocoder_dir, "config.json"), "w") as f:
json.dump({"output_sampling_rate": 48000}, f)
# Create a minimal od_config mock
class MockConfig:
model = tmpdir
func = get_ltx2_post_process_func(MockConfig())
video = torch.zeros(1, 3, 4, 64, 64)
audio = torch.zeros(1, 1, 48000)
result = func((video, audio))
assert isinstance(result, dict)
assert "video" in result
assert "audio" in result
assert result["audio_sample_rate"] == 48000
def test_post_process_without_vocoder_config(self):
"""Post-process func should work without vocoder config (no audio_sample_rate key)."""
import torch
from vllm_omni.diffusion.models.ltx2.pipeline_ltx2_3 import get_ltx2_post_process_func
class MockConfig:
model = "/nonexistent/path"
func = get_ltx2_post_process_func(MockConfig())
video = torch.zeros(1, 3, 4, 64, 64)
audio = torch.zeros(1, 1, 16000)
result = func((video, audio))
assert isinstance(result, dict)
assert "video" in result
assert "audio" in result
assert "audio_sample_rate" not in result
class TestReExportModule:
"""Test that pipeline_ltx2_3_image2video.py correctly re-exports."""
def test_i2v_classes_importable(self):
"""I2V classes must be importable from the re-export module."""
from vllm_omni.diffusion.models.ltx2.pipeline_ltx2_3_image2video import LTX23ImageToVideoPipeline
assert LTX23ImageToVideoPipeline is not None
def test_post_process_func_importable(self):
"""get_ltx2_post_process_func must be importable from re-export module."""
from vllm_omni.diffusion.models.ltx2.pipeline_ltx2_3_image2video import get_ltx2_post_process_func
assert callable(get_ltx2_post_process_func)
def test_i2v_classes_are_same_as_direct_import(self):
"""Re-exported classes must be the same objects as direct imports."""
from vllm_omni.diffusion.models.ltx2.pipeline_ltx2_3 import LTX23ImageToVideoPipeline as Direct
from vllm_omni.diffusion.models.ltx2.pipeline_ltx2_3_image2video import (
LTX23ImageToVideoPipeline as ReExported,
)
assert Direct is ReExported
class TestInitExports:
"""Test that __init__.py exports all LTX-2.3 classes."""
def test_all_ltx23_classes_exported(self):
"""All LTX-2.3 pipeline classes must be in the ltx2 package __all__."""
from vllm_omni.diffusion.models import ltx2
expected_classes = [
"LTX23Pipeline",
"LTX23ImageToVideoPipeline",
]
for name in expected_classes:
assert hasattr(ltx2, name), f"{name} not exported from ltx2 package"
assert name in ltx2.__all__, f"{name} not in ltx2.__all__"
@@ -0,0 +1,164 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Tests for T5EncoderModel prefix handling and weight loading fix."""
import pytest
import torch
from transformers import T5Config
from vllm.config import DeviceConfig, VllmConfig, set_current_vllm_config
from vllm_omni.diffusion.models.t5_encoder.t5_encoder import T5EncoderModel
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
_SMALL_T5_CONFIG = dict(
d_model=64,
d_kv=8,
d_ff=128,
num_heads=8,
num_layers=2,
vocab_size=256,
relative_attention_num_buckets=32,
relative_attention_max_distance=128,
is_gated_act=True,
dense_act_fn="gelu_new",
layer_norm_epsilon=1e-6,
feed_forward_proj="gated-gelu",
)
_T5_MODULE = "vllm_omni.diffusion.models.t5_encoder.t5_encoder"
@pytest.fixture
def t5_config() -> T5Config:
return T5Config(**_SMALL_T5_CONFIG)
@pytest.fixture(scope="function", autouse=True)
def setup_vllm_config(monkeypatch, mocker):
"""Set up VllmConfig and TP=2 mocks for tests."""
device_config = DeviceConfig(device="cpu")
monkeypatch.setattr("vllm.model_executor.layers.linear.get_tensor_model_parallel_world_size", lambda: 2)
monkeypatch.setattr(f"{_T5_MODULE}.get_tensor_model_parallel_world_size", lambda: 2)
monkeypatch.setattr(
"vllm.model_executor.layers.vocab_parallel_embedding.get_tensor_model_parallel_world_size",
lambda: 2,
)
monkeypatch.setattr(f"{_T5_MODULE}.get_tensor_model_parallel_rank", lambda: 0)
monkeypatch.setattr(
"vllm.model_executor.layers.vocab_parallel_embedding.get_tensor_model_parallel_rank",
lambda: 0,
)
mock_tp_group = mocker.MagicMock()
mock_tp_group.world_size = 2
mocker.patch("vllm.distributed.parallel_state.get_tp_group", return_value=mock_tp_group)
monkeypatch.setattr(f"{_T5_MODULE}.get_act_fn", lambda _: torch.nn.GELU())
with set_current_vllm_config(VllmConfig(device_config=device_config)):
yield
class TestT5EncoderModelPrefixHandling:
"""Test that T5EncoderModel correctly handles prefix attribute."""
def test_prefix_stored_in_model(self, t5_config):
"""Test that prefix is stored in the model when provided."""
prefix = "text_encoder"
model = T5EncoderModel(t5_config, prefix=prefix)
assert hasattr(model, "prefix")
assert model.prefix == prefix
def test_prefix_empty_by_default(self, t5_config):
"""Test that prefix defaults to empty string when not provided."""
model = T5EncoderModel(t5_config)
assert hasattr(model, "prefix")
assert model.prefix == ""
class TestT5EncoderModelWeightLoadingWithPrefix:
"""Test weight loading with prefix handling."""
def test_load_weights_with_prefix(self, t5_config):
"""Test that weights without prefix are loaded when model has prefix."""
config = T5Config(**{**_SMALL_T5_CONFIG, "num_layers": 1})
model = T5EncoderModel(config, prefix="text_encoder")
inner_dim = config.num_heads * config.d_kv
weights = [
("encoder.block.0.layer.0.SelfAttention.q.weight", torch.randn(inner_dim, config.d_model)),
("encoder.block.0.layer.0.SelfAttention.k.weight", torch.randn(inner_dim, config.d_model)),
("encoder.block.0.layer.0.SelfAttention.v.weight", torch.randn(inner_dim, config.d_model)),
]
loaded = model.load_weights(weights)
assert len(loaded) > 0
def test_load_weights_embed_tokens_shared_sync(self, t5_config):
"""Test that embed_tokens and shared weights are synced."""
model = T5EncoderModel(t5_config, prefix="text_encoder")
d_model = t5_config.d_model
vocab_size = t5_config.vocab_size
embed_weight = torch.randn(vocab_size, d_model)
weights = [
("encoder.embed_tokens.weight", embed_weight.clone()),
]
model.load_weights(weights)
shared_param = model.shared.weight
embed_param = model.encoder.embed_tokens.weight
assert torch.allclose(shared_param, embed_param), (
"shared and embed_tokens should have the same weights after loading"
)
def test_load_weights_shared_without_prefix(self, t5_config):
"""Test shared.weight is recognized without relying on dot context."""
model = T5EncoderModel(t5_config, prefix="text_encoder")
shared_weight = torch.randn(t5_config.vocab_size, t5_config.d_model)
loaded = model.load_weights([("shared.weight", shared_weight)])
assert "shared.weight" in loaded
assert torch.allclose(model.shared.weight, model.encoder.embed_tokens.weight)
def test_unmatched_weights_are_not_reported_loaded(self, t5_config):
"""Test that skipped checkpoint weights are not added to loaded_params."""
model = T5EncoderModel(t5_config, prefix="text_encoder")
loaded = model.load_weights(
[
(
"text_encoder.encoder.block.0.layer.0.SelfAttention.missing.weight",
torch.randn(t5_config.d_model, t5_config.d_model),
),
]
)
assert loaded == set()
class TestT5EncoderModelWeightLoadingWithoutPrefix:
"""Test weight loading without prefix."""
def test_load_weights_without_prefix(self, t5_config):
"""Test that weights without prefix are loaded correctly."""
config = T5Config(**{**_SMALL_T5_CONFIG, "num_layers": 1})
model = T5EncoderModel(config)
inner_dim = config.num_heads * config.d_kv
weights = [
("encoder.block.0.layer.0.SelfAttention.q.weight", torch.randn(inner_dim, config.d_model)),
]
loaded = model.load_weights(weights)
assert len(loaded) > 0
@@ -0,0 +1,240 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Unit tests for ModuleDiscovery and SupportsModuleOffload."""
from typing import ClassVar
import pytest
from torch import nn
from vllm_omni.diffusion.models.interface import SupportsModuleOffload
from vllm_omni.diffusion.offloader.module_collector import ModuleDiscovery
pytestmark = [pytest.mark.diffusion, pytest.mark.cpu, pytest.mark.core_model]
# NOTE: tests for skipped/warned attributes verify the *behavioral*
# outcome (attribute excluded from results) but do not assert on log
# output. vllm's logger sets propagate=False, preventing caplog from
# capturing records. See https://github.com/pytest-dev/pytest/issues/3697
# ---------------------------------------------------------------------------
# Test pipelines
# ---------------------------------------------------------------------------
class FallbackPipeline(nn.Module):
"""Pipeline with standard attribute names (no protocol)."""
def __init__(self):
super().__init__()
self.transformer = nn.Linear(10, 10)
self.text_encoder = nn.Linear(10, 10)
self.text_encoder_2 = nn.Linear(10, 10)
self.vae = nn.Linear(10, 10)
class NonModuleAttrPipeline(nn.Module):
"""Pipeline where an attribute is not an nn.Module (fallback path)."""
def __init__(self):
super().__init__()
self.transformer = nn.Linear(10, 10)
self.text_encoder = "not_a_module"
self.vae = nn.Linear(10, 10)
class DuplicateAttrPipeline(nn.Module):
"""Pipeline where two encoder attrs point to the same module."""
def __init__(self):
super().__init__()
self.transformer = nn.Linear(10, 10)
encoder = nn.Linear(10, 10)
self.text_encoder = encoder
self.text_encoder_2 = encoder
self.vae = nn.Linear(10, 10)
class ProtocolPipeline(nn.Module, SupportsModuleOffload):
"""Pipeline with non-standard names, using the protocol."""
_dit_modules: ClassVar[list[str]] = ["gen_transformer"]
_encoder_modules: ClassVar[list[str]] = ["mllm", "vision_model"]
_vae_modules: ClassVar[list[str]] = ["gen_vae"]
def __init__(self):
super().__init__()
self.gen_transformer = nn.Linear(10, 10)
self.mllm = nn.Linear(10, 10)
self.vision_model = nn.Linear(10, 10)
self.gen_vae = nn.Linear(10, 10)
# Standard name present but NOT declared — should be ignored
self.transformer = nn.Linear(10, 10)
class MissingAttrPipeline(nn.Module, SupportsModuleOffload):
"""Pipeline that declares a non-existent attribute."""
_dit_modules: ClassVar[list[str]] = ["transformer"]
_encoder_modules: ClassVar[list[str]] = ["nonexistent_encoder"]
_vae_modules: ClassVar[list[str]] = ["vae"]
def __init__(self):
super().__init__()
self.transformer = nn.Linear(10, 10)
self.vae = nn.Linear(10, 10)
class MissingIntermediatePipeline(nn.Module, SupportsModuleOffload):
"""Pipeline with dotted path referencing non-existent intermediate."""
_dit_modules: ClassVar[list[str]] = ["nonexistent.transformer"]
_encoder_modules: ClassVar[list[str]] = []
_vae_modules: ClassVar[list[str]] = []
def __init__(self):
super().__init__()
class NestedPipeline(nn.Module, SupportsModuleOffload):
"""Pipeline with nested modules accessed via dotted paths."""
_dit_modules: ClassVar[list[str]] = ["pipe.transformer"]
_encoder_modules: ClassVar[list[str]] = ["pipe.text_encoder"]
_vae_modules: ClassVar[list[str]] = ["vae"]
def __init__(self):
super().__init__()
self.pipe = nn.Module()
self.pipe.transformer = nn.Linear(10, 10)
self.pipe.text_encoder = nn.Linear(10, 10)
self.vae = nn.Linear(10, 10)
class ResidentPipeline(nn.Module, SupportsModuleOffload):
"""Pipeline with resident modules that must stay on GPU."""
_dit_modules: ClassVar[list[str]] = ["language_model.model"]
_encoder_modules: ClassVar[list[str]] = []
_vae_modules: ClassVar[list[str]] = ["vae"]
_resident_modules: ClassVar[list[str]] = [
"bagel.time_embedder",
"bagel.vae2llm",
]
def __init__(self):
super().__init__()
self.language_model = nn.Module()
self.language_model.model = nn.Linear(10, 10)
self.bagel = nn.Module()
self.bagel.time_embedder = nn.Linear(10, 10)
self.bagel.vae2llm = nn.Linear(10, 10)
self.vae = nn.Linear(10, 10)
class MultiVaePipeline(nn.Module, SupportsModuleOffload):
"""Pipeline with multiple VAEs."""
_dit_modules: ClassVar[list[str]] = ["transformer"]
_encoder_modules: ClassVar[list[str]] = ["text_encoder"]
_vae_modules: ClassVar[list[str]] = ["vae", "audio_vae"]
def __init__(self):
super().__init__()
self.transformer = nn.Linear(10, 10)
self.text_encoder = nn.Linear(10, 10)
self.vae = nn.Linear(10, 10)
self.audio_vae = nn.Linear(10, 10)
# ---------------------------------------------------------------------------
# Tests
# ---------------------------------------------------------------------------
class TestFallbackDiscovery:
"""Test the fallback attribute scan (no SupportsModuleOffload)."""
def test_discovers_standard_attrs(self):
pipeline = FallbackPipeline()
result = ModuleDiscovery.discover(pipeline)
assert not isinstance(pipeline, SupportsModuleOffload)
assert result.dit_names == ["transformer"]
assert result.dits[0] is pipeline.transformer
assert result.encoder_names == ["text_encoder", "text_encoder_2"]
assert result.vaes[0] is pipeline.vae
assert result.resident_modules == []
def test_deduplicates_encoders(self):
pipeline = DuplicateAttrPipeline()
result = ModuleDiscovery.discover(pipeline)
assert len(result.encoders) == 1
assert result.encoder_names == ["text_encoder"]
def test_skips_non_module_attr(self):
pipeline = NonModuleAttrPipeline()
result = ModuleDiscovery.discover(pipeline)
assert len(result.encoders) == 0
class TestProtocolDiscovery:
"""Test discovery via SupportsModuleOffload protocol."""
def test_discovers_declared_attrs_and_ignores_undeclared(self):
pipeline = ProtocolPipeline()
result = ModuleDiscovery.discover(pipeline)
assert isinstance(pipeline, SupportsModuleOffload)
assert result.dit_names == ["gen_transformer"]
assert result.encoder_names == ["mllm", "vision_model"]
assert len(result.vaes) == 1
# self.transformer exists but is NOT in _dit_modules
assert "transformer" not in result.dit_names
# No _resident_modules declared — defaults to empty
assert result.resident_modules == []
def test_skips_missing_attr(self):
pipeline = MissingAttrPipeline()
result = ModuleDiscovery.discover(pipeline)
assert len(result.encoders) == 0
def test_skips_missing_intermediate(self):
result = ModuleDiscovery.discover(MissingIntermediatePipeline())
assert len(result.dits) == 0
def test_dotted_path_resolves_nested_modules(self):
pipeline = NestedPipeline()
result = ModuleDiscovery.discover(pipeline)
assert result.dit_names == ["pipe.transformer"]
assert result.dits[0] is pipeline.pipe.transformer
assert result.encoder_names == ["pipe.text_encoder"]
assert result.encoders[0] is pipeline.pipe.text_encoder
assert result.vaes[0] is pipeline.vae
def test_resident_modules(self):
pipeline = ResidentPipeline()
result = ModuleDiscovery.discover(pipeline)
assert result.resident_names == [
"bagel.time_embedder",
"bagel.vae2llm",
]
assert result.resident_modules[0] is pipeline.bagel.time_embedder
assert result.resident_modules[1] is pipeline.bagel.vae2llm
assert result.dits[0] is pipeline.language_model.model
def test_multiple_vaes(self):
pipeline = MultiVaePipeline()
result = ModuleDiscovery.discover(pipeline)
assert len(result.vaes) == 2
assert result.vaes[0] is pipeline.vae
assert result.vaes[1] is pipeline.audio_vae
@@ -0,0 +1,408 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Tests for component routing for quantization."""
from unittest.mock import MagicMock
import pytest
import torch
from vllm.model_executor.layers.quantization.base_config import (
QuantizationConfig,
)
from vllm.model_executor.models.utils import WeightsMapper
from vllm_omni.model_executor.models.qwen3_omni.qwen3_omni_moe_thinker import (
PRE_QUANTIZED_METHODS,
)
from vllm_omni.quantization.component_config import (
ComponentQuantizationConfig,
)
from vllm_omni.quantization.inc_config import OmniINCConfig
pytestmark = [pytest.mark.core_model]
# ---------------------------------------------------------------------------
# Helpers: lightweight mock quant configs
# ---------------------------------------------------------------------------
class _MockQuantConfig(QuantizationConfig):
"""Minimal mock that only implements get_name()."""
def __init__(self, name: str, **attrs):
self._name = name
for k, v in attrs.items():
setattr(self, k, v)
def get_name(self) -> str:
return self._name
def get_quant_method(self, layer, prefix):
return MagicMock()
@classmethod
def get_supported_act_dtypes(cls):
return [torch.bfloat16, torch.float16]
def get_min_capability(self):
return 0
@classmethod
def from_config(cls, config):
raise NotImplementedError
def get_config_filenames(self):
return []
def _make_inc_config(block_names="thinker.model.layers,talker.model.layers", extra_config=None):
"""Create a real OmniINCConfig with block_name_to_quantize."""
return OmniINCConfig(
weight_bits=4,
group_size=128,
sym=True,
block_name_to_quantize=block_names,
extra_config=extra_config or {},
)
THINKER_MAPPER = WeightsMapper(
orig_to_new_prefix={
"thinker.lm_head.": "language_model.lm_head.",
"thinker.model.": "language_model.model.",
"thinker.": "",
}
)
TALKER_MAPPER = WeightsMapper(
orig_to_new_prefix={
"talker.codec_head.": "language_model.lm_head.",
"talker.model.": "language_model.model.",
"talker.thinker_to_talker_proj.": "thinker_to_talker_proj.",
"talker.": "",
}
)
# ===================================================================
# 1. OmniINCConfig.apply_vllm_mapper
# ===================================================================
class TestApplyVllmMapper:
def test_inc_csv_string_normalized_to_list(self):
"""CSV string block_name_to_quantize is split into a list."""
cfg = _make_inc_config("thinker.model.layers,talker.model.layers")
cfg.apply_vllm_mapper(THINKER_MAPPER)
assert isinstance(cfg.block_name_to_quantize, list)
def test_thinker_blocks_remapped(self):
"""thinker.model.layers -> language_model.model.layers after apply_vllm_mapper."""
cfg = _make_inc_config("thinker.model.layers,talker.model.layers")
cfg.apply_vllm_mapper(THINKER_MAPPER)
assert any("language_model.model.layers" in b for b in cfg.block_name_to_quantize)
def test_cross_stage_blocks_kept_unchanged(self):
"""Blocks not matching any mapper prefix are kept unchanged (harmless)."""
cfg = _make_inc_config("thinker.model.layers,talker.model.layers")
cfg.apply_vllm_mapper(THINKER_MAPPER)
# talker.model.layers doesn't match any thinker mapper prefix → stays as-is
assert "talker.model.layers" in cfg.block_name_to_quantize
def test_talker_remap(self):
"""talker.model.layers -> language_model.model.layers with talker mapper."""
cfg = _make_inc_config("thinker.model.layers,talker.model.layers")
cfg.apply_vllm_mapper(TALKER_MAPPER)
assert any("language_model.model.layers" in b for b in cfg.block_name_to_quantize)
# thinker.model.layers doesn't match talker mapper → stays as-is
assert "thinker.model.layers" in cfg.block_name_to_quantize
def test_extra_config_keys_remapped(self):
"""Regex keys in extra_config get their escaped-dot prefixes remapped."""
extra = {
r".*thinker\.model\.layers\.0\.mlp\.gate.*": {"bits": 16, "data_type": "float"},
}
cfg = _make_inc_config("thinker.model.layers", extra_config=extra)
cfg.apply_vllm_mapper(THINKER_MAPPER)
# The key should now reference the vLLM runtime path
assert any("language_model" in k for k in cfg.extra_config)
# Original thinker\.model prefix should be replaced
assert not any(r"thinker\.model" in k for k in cfg.extra_config)
def test_single_block_name(self):
"""Only one block name (not CSV) still works."""
cfg = _make_inc_config("thinker.model.layers")
cfg.apply_vllm_mapper(THINKER_MAPPER)
assert any("language_model.model.layers" in b for b in cfg.block_name_to_quantize)
def test_already_list_block_names(self):
"""block_name_to_quantize already a list (not CSV string) works."""
cfg = _make_inc_config(["thinker.model.layers", "talker.model.layers"])
cfg.apply_vllm_mapper(THINKER_MAPPER)
assert isinstance(cfg.block_name_to_quantize, list)
assert any("language_model.model.layers" in b for b in cfg.block_name_to_quantize)
def test_mutates_in_place(self):
"""apply_vllm_mapper mutates the config in place (same as upstream INCConfig)."""
cfg = _make_inc_config("thinker.model.layers")
original_id = id(cfg)
cfg.apply_vllm_mapper(THINKER_MAPPER)
assert id(cfg) == original_id
# -- Stage prefix tests (runtime prefix = container + internal name) --
def test_thinker_block_has_stage_prefix(self):
"""Mapped block name must start with 'thinker.' so runtime startswith() works."""
cfg = _make_inc_config("thinker.model.layers,talker.model.layers")
cfg.apply_vllm_mapper(THINKER_MAPPER)
assert "thinker.language_model.model.layers" in cfg.block_name_to_quantize
def test_talker_block_has_stage_prefix(self):
"""Mapped block name must start with 'talker.' so runtime startswith() works."""
cfg = _make_inc_config("thinker.model.layers,talker.model.layers")
cfg.apply_vllm_mapper(TALKER_MAPPER)
assert "talker.language_model.model.layers" in cfg.block_name_to_quantize
def test_thinker_block_matches_runtime_prefix(self):
"""Simulates get_layer_config's startswith() check for FusedMoE layers."""
cfg = _make_inc_config("thinker.model.layers,talker.model.layers")
cfg.apply_vllm_mapper(THINKER_MAPPER)
runtime_prefix = "thinker.language_model.model.layers.0.mlp.experts"
assert any(runtime_prefix.startswith(b) for b in cfg.block_name_to_quantize)
def test_talker_block_matches_runtime_prefix(self):
"""Simulates get_layer_config's startswith() check for talker FusedMoE."""
cfg = _make_inc_config("thinker.model.layers,talker.model.layers")
cfg.apply_vllm_mapper(TALKER_MAPPER)
runtime_prefix = "talker.language_model.model.layers.0.mlp.experts"
assert any(runtime_prefix.startswith(b) for b in cfg.block_name_to_quantize)
def test_extra_config_plain_key_has_stage_prefix(self):
"""Plain extra_config keys are remapped with stage prefix."""
extra = {
"talker.model.layers.0.mlp.shared_expert_gate": {"bits": 16},
}
cfg = _make_inc_config("talker.model.layers", extra_config=extra)
cfg.apply_vllm_mapper(TALKER_MAPPER)
assert "talker.language_model.model.layers.0.mlp.shared_expert_gate" in cfg.extra_config
def test_extra_config_regex_key_still_works(self):
"""Regex extra_config keys use re.search so no stage prefix needed."""
import re
extra = {
r".*thinker\.model\.layers\.0\.mlp\.gate.*": {"bits": 16},
}
cfg = _make_inc_config("thinker.model.layers", extra_config=extra)
cfg.apply_vllm_mapper(THINKER_MAPPER)
runtime_name = "thinker.language_model.model.layers.0.mlp.gate"
matched = any(re.search(k, runtime_name) for k in cfg.extra_config)
assert matched
# ===================================================================
# 2. OmniINCConfig upgrade helpers
# ===================================================================
class TestOmniINCConfigUpgrade:
def test_maybe_upgrade_none(self):
assert OmniINCConfig.maybe_upgrade(None) is None
def test_maybe_upgrade_non_inc(self):
"""Non-INC configs are passed through unchanged."""
cfg = _MockQuantConfig("fp8")
assert OmniINCConfig.maybe_upgrade(cfg) is cfg
def test_maybe_upgrade_already_omni(self):
"""Already OmniINCConfig is returned as-is."""
cfg = _make_inc_config()
assert OmniINCConfig.maybe_upgrade(cfg) is cfg
def test_maybe_upgrade_vanilla_inc(self):
"""Vanilla INCConfig is promoted to OmniINCConfig."""
from vllm.model_executor.layers.quantization.inc import INCConfig
vanilla = INCConfig(weight_bits=4, group_size=128, sym=True)
upgraded = OmniINCConfig.maybe_upgrade(vanilla)
assert isinstance(upgraded, OmniINCConfig)
assert upgraded.weight_bits == 4
assert upgraded.group_size == 128
# ===================================================================
# 2. Three-branch thinker routing (simulated)
# ===================================================================
def _simulate_thinker_routing(quant_config):
"""Simulate the three-branch routing in thinker __init__.
Returns (visual_quant_config, language_quant_config, wrapped_vllm_quant).
"""
if isinstance(quant_config, ComponentQuantizationConfig):
visual_quant_config = quant_config.resolve("visual")
language_quant_config = quant_config.resolve("language_model")
return visual_quant_config, language_quant_config, quant_config
elif quant_config is not None:
if quant_config.get_name() in PRE_QUANTIZED_METHODS:
return quant_config, quant_config, quant_config
else:
language_quant_config = quant_config
wrapped = ComponentQuantizationConfig(
component_configs={"language_model": quant_config},
default_config=None,
)
return None, language_quant_config, wrapped
else:
return None, None, None
class TestThinkerRouting:
def test_none(self):
vis, lang, wrapped = _simulate_thinker_routing(None)
assert vis is None
assert lang is None
assert wrapped is None
@pytest.mark.parametrize("method", ["modelopt", "modelopt_fp4", "modelopt_mxfp8"])
def test_pre_quantized_all_components(self, method):
"""Pre-quantized methods pass config to all components."""
cfg = _MockQuantConfig(method)
vis, lang, wrapped = _simulate_thinker_routing(cfg)
assert vis is cfg
assert lang is cfg
assert wrapped is cfg
def test_fp8_dynamic_language_only(self):
"""fp8 dynamic: visual=None, language gets original config."""
cfg = _MockQuantConfig("fp8")
vis, lang, wrapped = _simulate_thinker_routing(cfg)
assert vis is None
assert lang is cfg
assert isinstance(wrapped, ComponentQuantizationConfig)
assert wrapped.resolve("language_model") is cfg
assert wrapped.resolve("visual") is None
def test_inc_autoround_language_only(self):
"""INC/AutoRound: not in _PRE_QUANTIZED_METHODS -> wrapped like fp8."""
cfg = _MockQuantConfig("inc")
vis, lang, wrapped = _simulate_thinker_routing(cfg)
assert vis is None
assert lang is cfg
assert isinstance(wrapped, ComponentQuantizationConfig)
def test_component_config_passthrough(self):
"""Explicit ComponentQuantizationConfig is used directly."""
inner_fp8 = _MockQuantConfig("fp8")
inner_modelopt = _MockQuantConfig("modelopt")
cqc = ComponentQuantizationConfig(
component_configs={
"visual": inner_modelopt,
"language_model": inner_fp8,
}
)
vis, lang, wrapped = _simulate_thinker_routing(cqc)
assert vis is inner_modelopt
assert lang is inner_fp8
assert wrapped is cqc
# ===================================================================
# 3. Talker visual routing (init_multi_modal guard)
# ===================================================================
def _simulate_talker_visual_routing(quant_config):
"""Simulate the talker init_multi_modal visual routing."""
if quant_config is not None and quant_config.get_name() in PRE_QUANTIZED_METHODS:
return quant_config
return None
class TestTalkerVisualRouting:
def test_none(self):
assert _simulate_talker_visual_routing(None) is None
@pytest.mark.parametrize("method", ["modelopt", "modelopt_fp4", "modelopt_mxfp8"])
def test_pre_quantized_passes_through(self, method):
"""Pre-quantized methods pass quant config to visual."""
cfg = _MockQuantConfig(method)
assert _simulate_talker_visual_routing(cfg) is cfg
def test_fp8_blocked(self):
"""fp8 dynamic must NOT be passed to visual."""
cfg = _MockQuantConfig("fp8")
assert _simulate_talker_visual_routing(cfg) is None
def test_inc_blocked(self):
"""INC/AutoRound must NOT be passed to visual (not in _PRE_QUANTIZED_METHODS)."""
cfg = _MockQuantConfig("inc")
assert _simulate_talker_visual_routing(cfg) is None
# ===================================================================
# 4. ComponentQuantizationConfig.resolve
# ===================================================================
class TestComponentResolve:
def test_longest_prefix_match(self):
a = _MockQuantConfig("a")
b = _MockQuantConfig("b")
cqc = ComponentQuantizationConfig(component_configs={"language_model": a, "language_model.model": b})
assert cqc.resolve("language_model.model.layers.0") is b
assert cqc.resolve("language_model.lm_head") is a
def test_no_match_returns_default(self):
a = _MockQuantConfig("a")
default = _MockQuantConfig("default")
cqc = ComponentQuantizationConfig(
component_configs={"language_model": a},
default_config=default,
)
assert cqc.resolve("visual") is default
def test_no_match_no_default_returns_none(self):
a = _MockQuantConfig("a")
cqc = ComponentQuantizationConfig(
component_configs={"language_model": a},
)
assert cqc.resolve("visual") is None
def test_get_name(self):
cqc = ComponentQuantizationConfig(component_configs={})
assert cqc.get_name() == "component"
def test_get_quant_method_delegates(self):
"""get_quant_method dispatches to the resolved config."""
inner = _MockQuantConfig("fp8")
cqc = ComponentQuantizationConfig(
component_configs={"language_model": inner},
)
layer = MagicMock()
result = cqc.get_quant_method(layer, "language_model.model.layers.0.mlp")
assert result is not None # delegates to inner.get_quant_method
def test_get_quant_method_returns_none_for_unmatched(self):
"""get_quant_method returns None when no config matches."""
inner = _MockQuantConfig("fp8")
cqc = ComponentQuantizationConfig(
component_configs={"language_model": inner},
)
layer = MagicMock()
result = cqc.get_quant_method(layer, "visual.blocks.0.mlp")
assert result is None
def test_min_capability(self):
a = _MockQuantConfig("a")
a.get_min_capability = lambda: 80
b = _MockQuantConfig("b")
b.get_min_capability = lambda: 70
cqc = ComponentQuantizationConfig(component_configs={"x": a, "y": b})
assert cqc.get_min_capability() == 70
def test_min_capability_empty(self):
cqc = ComponentQuantizationConfig(component_configs={})
assert cqc.get_min_capability() == 0
+186
View File
@@ -0,0 +1,186 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections import namedtuple
from types import SimpleNamespace
import pytest
import torch
from diffusers import DiffusionPipeline
from PIL import Image
from vllm_omni.diffusion.data import (
DiffusionOutput,
DiffusionParallelConfig,
OmniDiffusionConfig,
)
from vllm_omni.diffusion.models.diffusers_adapter import DiffusersAdapterPipeline
from vllm_omni.diffusion.request import OmniDiffusionRequest
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
pytestmark = [pytest.mark.core_model, pytest.mark.diffusion, pytest.mark.cpu]
def _make_od_config(**overrides) -> OmniDiffusionConfig:
od_config = OmniDiffusionConfig(
model="test/model",
model_class_name="DiffusersAdapterPipeline",
dtype=torch.float16,
diffusion_load_format="diffusers",
diffusers_load_kwargs={},
diffusers_call_kwargs={},
output_type="pil",
parallel_config=DiffusionParallelConfig(cfg_parallel_size=1, sequence_parallel_size=1),
cache_backend="none",
)
for key, value in overrides.items():
setattr(od_config, key, value)
return od_config
def _make_request(**overrides) -> OmniDiffusionRequest:
prompt = overrides.pop("prompt", "a test prompt")
negative_prompt = overrides.pop("negative_prompt", None)
prompt_obj: dict[str, str] = {"prompt": prompt}
if negative_prompt is not None:
prompt_obj["negative_prompt"] = negative_prompt
defaults = {
"prompts": [prompt_obj],
"sampling_params": OmniDiffusionSamplingParams(
num_inference_steps=20,
guidance_scale=7.5,
height=16,
width=16,
num_frames=1,
num_outputs_per_prompt=1,
seed=42,
output_type="pil",
generator_device="cpu",
),
}
defaults.update(overrides)
return OmniDiffusionRequest(**defaults)
class TestDiffusersAdapterPipeline:
def test_adapter_forward_returns_output(self, mocker):
od_config = _make_od_config()
request = _make_request()
stub_image = Image.new("RGB", (request.sampling_params.width, request.sampling_params.height)) # pyright: ignore[reportArgumentType]
adapter = DiffusersAdapterPipeline(od_config=od_config)
MockPipelineOutput = namedtuple("MockPipelineOutput", ["image"])
MockPipeline = type("MockPipeline", (DiffusionPipeline,), {})
adapter._pipeline = MockPipeline()
mocker.patch.object(
MockPipeline,
"__call__",
return_value=MockPipelineOutput(image=stub_image),
)
output = adapter.forward(request)
assert isinstance(output, DiffusionOutput)
assert isinstance(output.output, MockPipelineOutput)
assert output.output.image is stub_image
@pytest.mark.parametrize(
"feature_id",
["cfg_parallel", "ulysses", "ring", "teacache", "cache_dit", "enforce_eager", "quantization"],
)
def test_adapter_guard_unsupported_feature(self, feature_id):
if feature_id == "cfg_parallel":
od_config = _make_od_config(
parallel_config=DiffusionParallelConfig(cfg_parallel_size=2, sequence_parallel_size=1),
cache_backend="none",
)
elif feature_id == "ulysses":
od_config = _make_od_config(
parallel_config=DiffusionParallelConfig(cfg_parallel_size=1, ulysses_degree=2),
cache_backend="none",
)
elif feature_id == "ring":
od_config = _make_od_config(
parallel_config=DiffusionParallelConfig(cfg_parallel_size=1, ring_degree=2),
cache_backend="none",
)
elif feature_id == "teacache":
od_config = _make_od_config(
parallel_config=DiffusionParallelConfig(cfg_parallel_size=1, sequence_parallel_size=1),
cache_backend="tea_cache",
)
elif feature_id == "cache_dit":
od_config = _make_od_config(
parallel_config=DiffusionParallelConfig(cfg_parallel_size=1, sequence_parallel_size=1),
cache_backend="cache_dit",
)
elif feature_id == "enforce_eager":
od_config = _make_od_config(enforce_eager=True)
elif feature_id == "quantization":
od_config = _make_od_config(quantization_config=SimpleNamespace(quant_method="fp8"))
else:
raise ValueError(f"Unknown feature ID: {feature_id}")
with pytest.raises(NotImplementedError):
DiffusersAdapterPipeline(od_config=od_config)
def test_adapter_guard_unknown_output_type(self, mocker):
"""Test that the adapter wraps an unknown output type as-is.
This is useful when `return_dict=True` and the diffusers pipeline returns an OrderedDict subclass."""
adapter = DiffusersAdapterPipeline(od_config=_make_od_config())
raw_output = {"unexpected": "dict-output"}
MockPipeline = type("MockPipeline", (DiffusionPipeline,), {})
adapter._pipeline = MockPipeline()
mocker.patch.object(
MockPipeline,
"__call__",
return_value=raw_output,
)
output = adapter.forward(_make_request())
assert isinstance(output, DiffusionOutput)
assert output.output == raw_output
def test_adapter_build_call_kwargs(self):
adapter = DiffusersAdapterPipeline(
od_config=_make_od_config(
diffusers_call_kwargs={
"guidance_scale": 1.25,
"eta": 0.3,
"output_type": "np",
}
)
)
req = _make_request(
prompt="a cat on mars",
negative_prompt="low quality",
sampling_params=OmniDiffusionSamplingParams(
num_inference_steps=9,
guidance_scale=8.0,
height=320,
width=640,
num_frames=8,
num_outputs_per_prompt=2,
seed=123,
output_type="pil",
),
)
kwargs = adapter._build_call_kwargs(req)
assert kwargs["prompt"] == "a cat on mars"
assert kwargs["negative_prompt"] == "low quality"
assert kwargs["num_inference_steps"] == 9
assert kwargs["guidance_scale"] == 8.0
assert kwargs["height"] == 320
assert kwargs["width"] == 640
assert kwargs["num_frames"] == 8
assert kwargs["num_images_per_prompt"] == 2
assert kwargs["output_type"] == "pil"
assert isinstance(kwargs["generator"], torch.Generator)
assert kwargs["generator"].device.type == "cpu"
assert kwargs["generator"].initial_seed() == 123
@@ -17,8 +17,6 @@ from vllm_omni.distributed.omni_coordinator import (
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
def _bind_router() -> tuple[zmq.Context, zmq.Socket, str]:
ctx = zmq.Context.instance()
@@ -41,6 +41,74 @@ def _wait_for_instance_list(
return None
def _drain_sub_messages(sub: zmq.Socket, max_seconds: float = 0.4) -> None:
"""Drain queued SUB messages for a short window."""
deadline = time.time() + max_seconds
while time.time() < deadline:
_recv_instance_list(sub, timeout_ms=50)
def test_omni_coordinator_pub_coalescing_on_rapid_queue_updates():
"""Rapid updates should be coalesced into fewer PUB messages."""
router_addr = get_engine_client_zmq_addr(
local_only=False,
host="127.0.0.1",
port=0,
)
pub_addr = get_engine_client_zmq_addr(
local_only=False,
host="127.0.0.1",
port=0,
)
coordinator = OmniCoordinator(
router_zmq_addr=router_addr,
pub_zmq_addr=pub_addr,
heartbeat_timeout=1000.0,
)
sub_ctx = zmq.Context.instance()
sub = sub_ctx.socket(zmq.SUB)
sub.connect(pub_addr)
sub.setsockopt(zmq.SUBSCRIBE, b"")
time.sleep(0.3) # PUB/SUB slow-joiner
client = OmniCoordClientForStage(
router_addr,
"tcp://stage:coalesce",
"tcp://stage:coalesce-out",
0,
)
# Wait for initial registration broadcast and clear any queued messages.
msg = _wait_for_instance_list(sub, expected_count=1)
assert msg is not None
_drain_sub_messages(sub)
# Burst many queue updates in a short period.
update_count = 80
for i in range(update_count):
client.update_info(queue_length=i)
# With publish_min_interval=0.1s, received messages over ~1s should be
# much smaller than update_count (coalescing effect).
window_s = 1.1
deadline = time.time() + window_s
recv_count = 0
while time.time() < deadline:
if _recv_instance_list(sub, timeout_ms=100) is not None:
recv_count += 1
assert recv_count < update_count // 2, (
f"expected coalesced PUB traffic, got {recv_count} for {update_count} updates"
)
client.close()
coordinator.close()
sub.close(0)
sub_ctx.term()
def test_omni_coordinator_registration_broadcast():
"""Verify that after multiple OmniCoordClientForStage instances register,
OmniCoordinator publishes an InstanceList containing all registered instances.
@@ -0,0 +1,2 @@
# SPDX-License-Identifier: Apache-2.0
"""Qwen3-Omni accuracy benchmarks (Daily-Omni / Seed-TTS ``vllm bench serve --omni``)."""
@@ -0,0 +1,201 @@
# SPDX-License-Identifier: Apache-2.0
"""Shared helpers for Qwen3-Omni Daily-Omni / Seed-TTS ``vllm bench serve --omni`` accuracy runs.
Local dataset paths are **optional**. When ``VLLM_DAILY_OMNI_QA_JSON`` + ``VLLM_DAILY_OMNI_VIDEO_DIR``
point to existing files, those are used with inline video. Otherwise the benchmark falls back to
the HuggingFace dataset id (``liarliar/Daily-Omni``); QA loads via ``datasets``, and the first
bench request that needs media downloads ``Videos.tar`` from the Hub when no video dir is set.
Similarly for Seed-TTS: a local directory wins; otherwise ``--dataset-path`` uses the Hub id
and ``huggingface_hub.snapshot_download`` inside ``resolve_seed_tts_root`` pulls files on demand.
Use :func:`build_acc_benchmark_cli_argv` to assemble ``argv`` for a live Omni server (host/port/model
and small bench defaults) before ``parse_args`` / ``run_acc_benchmark`` in the accuracy driver.
"""
from __future__ import annotations
import json
import os
import shutil
import subprocess
from pathlib import Path
from typing import Any, Protocol
DEFAULT_DAILY_OMNI_HF_REPO = "liarliar/Daily-Omni"
DEFAULT_SEED_TTS_HF_REPO = "zhaochenyang20/seed-tts-eval"
class OmniBenchServerEndpoint(Protocol):
"""Anything with ``host`` / ``port`` / ``model`` (e.g. :class:`tests.conftest.OmniServer`)."""
host: str
port: int
model: str
def build_acc_benchmark_cli_argv(
server: OmniBenchServerEndpoint,
*,
skip_seed: bool,
skip_daily: bool,
num_prompts: int | None = None,
max_concurrency: int | None = None,
) -> list[str]:
"""Prefix argv for :func:`run_qwen_omni_acc_benchmark.parse_acc_benchmark_args` + :func:`run_acc_benchmark`.
Wires ``--host`` / ``--port`` / ``--model`` to a running Omni OpenAI server, sets small
``--num-prompts`` / ``--max-concurrency`` defaults (overridable via ``ACC_BENCH_NUM_PROMPTS`` /
``ACC_BENCH_MAX_CONCURRENCY``), and when Daily-Omni runs adds ``--daily-omni-repo`` so Hub QA
matches :func:`daily_omni_bench_argv` once ``run_acc_benchmark`` mirrors ``--daily-omni-repo`` into env.
"""
n_prompts = int(os.environ.get("ACC_BENCH_NUM_PROMPTS", "2000")) if num_prompts is None else int(num_prompts)
n_conc = int(os.environ.get("ACC_BENCH_MAX_CONCURRENCY", "10")) if max_concurrency is None else int(max_concurrency)
argv = [
"--host",
server.host,
"--port",
str(server.port),
"--model",
server.model,
"--num-prompts",
str(n_prompts),
"--max-concurrency",
str(n_conc),
]
if not skip_daily:
repo = os.environ.get("VLLM_DAILY_OMNI_REPO", DEFAULT_DAILY_OMNI_HF_REPO).strip() or DEFAULT_DAILY_OMNI_HF_REPO
argv.extend(["--daily-omni-repo", repo])
if skip_seed:
argv.append("--skip-seed-tts")
if skip_daily:
argv.append("--skip-daily-omni")
return argv
def daily_omni_bench_argv() -> list[str]:
"""CLI args for Daily-Omni (after ``vllm bench serve --omni``)."""
qa = os.environ.get("VLLM_DAILY_OMNI_QA_JSON", "").strip()
vd = os.environ.get("VLLM_DAILY_OMNI_VIDEO_DIR", "").strip()
if qa and vd:
qap = Path(qa).expanduser()
vdp = Path(vd).expanduser()
if qap.is_file() and vdp.is_dir():
return [
"--dataset-name",
"daily-omni",
"--daily-omni-qa-json",
str(qap.resolve()),
"--daily-omni-video-dir",
str(vdp.resolve()),
"--daily-omni-inline-local-video",
]
repo = os.environ.get("VLLM_DAILY_OMNI_REPO", DEFAULT_DAILY_OMNI_HF_REPO).strip() or DEFAULT_DAILY_OMNI_HF_REPO
return [
"--dataset-name",
"daily-omni",
"--dataset-path",
repo,
]
def seed_tts_bench_argv(*, locale: str = "en") -> list[str]:
"""CLI args for Seed-TTS (after ``vllm bench serve --omni``)."""
dp = os.environ.get("VLLM_SEED_TTS_DATASET_PATH", "").strip()
if dp:
p = Path(dp).expanduser()
# Preserve Hugging Face repo ids verbatim. Only canonicalize to an
# absolute path when the value actually exists as a local directory.
dataset_path = str(p.resolve()) if p.exists() and p.is_dir() else dp
else:
dataset_path = (
os.environ.get("VLLM_SEED_TTS_REPO", DEFAULT_SEED_TTS_HF_REPO).strip() or DEFAULT_SEED_TTS_HF_REPO
)
out = ["--dataset-name", "seed-tts", "--dataset-path", dataset_path]
root = os.environ.get("SEED_TTS_ROOT", "").strip()
if root:
out.extend(["--seed-tts-root", str(Path(root).expanduser().resolve())])
out.extend(["--seed-tts-locale", locale])
return out
def find_vllm_cli() -> str:
exe = shutil.which("vllm")
if not exe:
raise FileNotFoundError("Could not find `vllm` on PATH (install vLLM-Omni with CLI entrypoints).")
return exe
def run_vllm_bench_subprocess(vllm: str, argv: list[str], *, extra_env: dict[str, str] | None = None) -> None:
env = os.environ.copy()
if extra_env:
env.update(extra_env)
subprocess.run([vllm, *argv], env=env, check=True)
def load_benchmark_result(path: Path) -> dict[str, Any]:
with path.open(encoding="utf-8") as f:
return json.load(f)
def build_serve_common_argv(
*,
host: str,
port: int,
model: str,
num_prompts: int,
max_concurrency: int,
num_warmups: int,
percentile_metrics: str,
result_dir: Path,
result_filename: str,
ready_check_timeout_sec: int | None = None,
) -> list[str]:
out = [
"bench",
"serve",
"--omni",
"--host",
host,
"--port",
str(port),
"--model",
model,
"--endpoint",
"/v1/chat/completions",
"--backend",
"openai-chat-omni",
"--request-rate",
"inf",
"--num-prompts",
str(num_prompts),
"--max-concurrency",
str(max_concurrency),
"--no-oversample",
"--num-warmups",
str(num_warmups),
"--percentile-metrics",
percentile_metrics,
"--save-result",
"--result-dir",
str(result_dir),
"--result-filename",
result_filename,
]
if ready_check_timeout_sec is not None:
out.extend(["--ready-check-timeout-sec", str(int(ready_check_timeout_sec))])
return out
def assert_daily_omni_scored(result: dict[str, Any]) -> None:
acc = result.get("daily_omni_accuracy")
assert acc is not None, "daily_omni_accuracy missing — wrong dataset or benchmark wiring"
assert int(result.get("daily_omni_evaluated_ok", 0) or 0) > 0, "no successful MCQ rows (daily_omni_evaluated_ok==0)"
def assert_seed_tts_scored(result: dict[str, Any]) -> None:
err = result.get("seed_tts_eval_setup_error")
assert not err, f"Seed-TTS eval deps/setup failed: {err}"
assert int(result.get("seed_tts_content_evaluated", 0) or 0) > 0, (
"seed_tts_content_evaluated==0 — enable WER eval and check PCM capture / modalities"
)
@@ -0,0 +1,428 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""Accuracy (and light perf) checks for Qwen3-Omni via ``vllm bench serve --omni``.
The standalone CLI uses small ``--num-prompts`` / ``--max-concurrency`` defaults suitable for
L4-style smoke runs against an already-running server. The pytest wrappers in
``tests/e2e/accuracy/qwen3_omni/test_qwen3_omni.py`` may still require larger GPUs (currently
H100 / MI325) because they launch the live Omni server inside the test.
1. **Daily-Omni** — MCQ accuracy fields in the saved JSON (``daily_omni_accuracy``, …); by default the
run **fails** if accuracy is strictly below **0.69** (``--min-daily-omni-accuracy`` / ``ACC_BENCH_MIN_DAILY_OMNI_ACCURACY``).
2. **Seed-TTS** — ``seed-tts-eval``-style metrics when ``--seed-tts-wer-eval`` is used
(WER / SIM / UTMOS keys from :func:`compute_seed_tts_wer_metrics`).
Prerequisites
-------------
* A running Omni OpenAI-compatible server (same machine or reachable host), e.g.::
vllm serve Qwen/Qwen3-Omni-30B-A3B-Instruct --omni --port 8000
On L4 you may need a smaller checkpoint, quantization, or tighter engine flags; this script
only drives the **client** benchmark.
* ``vllm`` CLI from **vLLM-Omni** (so ``bench serve`` registers ``daily-omni`` / ``seed-tts``).
* **Daily-Omni** — if local ``qa.json`` + ``Videos/`` are not both provided (CLI or matching env),
the client passes ``--dataset-path`` with a Hub id (default ``liarliar/Daily-Omni``). The **child**
``vllm bench serve`` process then loads QA via ``datasets.load_dataset`` (needs ``pip install datasets``,
network or HF cache). Without ``--daily-omni-video-dir``, the benchmark **lazily** downloads and
extracts ``Videos.tar`` from the Hub (``huggingface_hub``) on first multimodal request. Override
the dataset repo with ``--daily-omni-repo`` or ``VLLM_DAILY_OMNI_REPO``; override the tar repo
with ``VLLM_DAILY_OMNI_MEDIA_REPO`` if needed.
* **Seed-TTS** optional extras for WER/SIM/UTMOS::
pip install 'vllm-omni[seed-tts-eval]'
Examples
--------
Pytest (same checks; needs a running server)::
pytest -sv tests/e2e/accuracy/qwen3_omni/test_qwen3_omni.py
Smoke on localhost (server already up)::
python tests/e2e/accuracy/qwen3_omni/run_qwen_omni_acc_benchmark.py \\
--model Qwen/Qwen3-Omni-30B-A3B-Instruct \\
--daily-omni-qa-json ./qa.json \\
--daily-omni-video-dir ./Videos \\
--seed-tts-dataset-path ./seed-tts-eval
Skip one suite, tighten gates::
python tests/e2e/accuracy/qwen3_omni/run_qwen_omni_acc_benchmark.py \\
--skip-daily-omni \\
--max-seed-tts-mean-wer 0.35 \\
--min-seed-tts-mean-sim 0.75
"""
from __future__ import annotations
import argparse
import contextlib
import json
import os
import sys
from datetime import datetime
from pathlib import Path
from typing import Any
from tests.e2e.accuracy.qwen3_omni.qwen3_omni_acc_bench_core import (
build_serve_common_argv,
daily_omni_bench_argv,
find_vllm_cli,
load_benchmark_result,
run_vllm_bench_subprocess,
seed_tts_bench_argv,
)
_REPO_ROOT = Path(__file__).resolve().parents[4]
def _repo_root() -> Path:
return _REPO_ROOT
def _default_result_dir() -> Path:
return Path(__file__).resolve().parent / "results" / "qwen_omni_acc"
def _validate_daily_omni(result: dict[str, Any], *, min_accuracy: float | None) -> list[str]:
errs: list[str] = []
acc = result.get("daily_omni_accuracy")
if acc is None:
errs.append("Missing daily_omni_accuracy (wrong dataset or no gold-evaluated rows).")
return errs
ev = int(result.get("daily_omni_evaluated_ok", 0) or 0)
if ev <= 0:
errs.append("daily_omni_evaluated_ok is 0; no successful MCQ rows to score.")
if min_accuracy is not None and float(acc) + 1e-12 < float(min_accuracy):
errs.append(f"daily_omni_accuracy={acc:.6f} < --min-daily-omni-accuracy={min_accuracy}")
return errs
def _validate_seed_tts(
result: dict[str, Any],
*,
max_mean_wer: float | None,
min_mean_sim: float | None,
min_mean_utmos: float | None,
) -> list[str]:
errs: list[str] = []
setup = result.get("seed_tts_eval_setup_error")
if setup:
errs.append(f"Seed-TTS eval setup failed: {setup}")
return errs
n = int(result.get("seed_tts_content_evaluated", 0) or 0)
if n <= 0:
errs.append("seed_tts_content_evaluated is 0 (enable --seed-tts-wer-eval and check PCM capture).")
mean_wer = result.get("seed_tts_content_error_mean")
if mean_wer is not None and max_mean_wer is not None and float(mean_wer) > float(max_mean_wer) + 1e-12:
errs.append(f"seed_tts_content_error_mean (WER)={mean_wer:.6f} > --max-seed-tts-mean-wer={max_mean_wer}")
sim_m = result.get("seed_tts_sim_mean")
if sim_m is not None and min_mean_sim is not None and float(sim_m) + 1e-12 < float(min_mean_sim):
errs.append(f"seed_tts_sim_mean={sim_m:.6f} < --min-seed-tts-mean-sim={min_mean_sim}")
ut_m = result.get("seed_tts_utmos_mean")
if ut_m is not None and min_mean_utmos is not None and float(ut_m) + 1e-12 < float(min_mean_utmos):
errs.append(f"seed_tts_utmos_mean={ut_m:.6f} < --min-seed-tts-mean-utmos={min_mean_utmos}")
return errs
def sync_dataset_env_from_ns(ns: argparse.Namespace) -> None:
"""Mirror CLI path flags into env vars read by ``daily_omni_bench_argv`` / ``seed_tts_bench_argv``."""
repo = getattr(ns, "daily_omni_repo", None)
if repo is not None and str(repo).strip():
os.environ["VLLM_DAILY_OMNI_REPO"] = str(repo).strip()
if ns.daily_omni_qa_json is not None:
os.environ["VLLM_DAILY_OMNI_QA_JSON"] = str(Path(ns.daily_omni_qa_json).expanduser().resolve())
if ns.daily_omni_video_dir is not None:
os.environ["VLLM_DAILY_OMNI_VIDEO_DIR"] = str(Path(ns.daily_omni_video_dir).expanduser().resolve())
if ns.seed_tts_dataset_path is not None:
# ``--seed-tts-dataset-path`` accepts either a local directory or a
# Hugging Face repo id. Only resolve to an absolute filesystem path
# when the value actually exists locally; otherwise preserve the repo
# string verbatim so downstream code can pass it to snapshot_download.
raw = str(ns.seed_tts_dataset_path).strip()
p = Path(raw).expanduser()
os.environ["VLLM_SEED_TTS_DATASET_PATH"] = str(p.resolve()) if p.exists() and p.is_dir() else raw
if ns.seed_tts_root is not None:
os.environ["SEED_TTS_ROOT"] = str(Path(ns.seed_tts_root).expanduser().resolve())
@contextlib.contextmanager
def _preserve_benchmark_dataset_env() -> Any:
"""Save/restore dataset-related env vars so benchmark tests don't leak state."""
keys = (
"VLLM_DAILY_OMNI_REPO",
"VLLM_DAILY_OMNI_QA_JSON",
"VLLM_DAILY_OMNI_VIDEO_DIR",
"VLLM_SEED_TTS_DATASET_PATH",
"SEED_TTS_ROOT",
)
original = {k: os.environ.get(k) for k in keys}
try:
yield
finally:
for key, value in original.items():
if value is None:
os.environ.pop(key, None)
else:
os.environ[key] = value
def _build_common_args(ns: argparse.Namespace, *, result_filename: str) -> list[str]:
return build_serve_common_argv(
host=ns.host,
port=ns.port,
model=ns.model,
num_prompts=ns.num_prompts,
max_concurrency=ns.max_concurrency,
num_warmups=ns.num_warmups,
percentile_metrics=ns.percentile_metrics,
result_dir=ns.result_dir,
result_filename=result_filename,
ready_check_timeout_sec=ns.ready_check_timeout_sec,
)
def run_daily_omni(ns: argparse.Namespace, vllm: str) -> Path:
ns.result_dir.mkdir(parents=True, exist_ok=True)
tag = datetime.now().strftime("%Y%m%d-%H%M%S")
result_filename = f"qwen_omni_acc_daily_omni_{tag}.json"
extra = json.loads(ns.daily_extra_body_json)
argv = (
_build_common_args(ns, result_filename=result_filename)
+ daily_omni_bench_argv()
+ [
"--daily-omni-input-mode",
ns.daily_omni_input_mode,
"--extra-body",
json.dumps(extra, ensure_ascii=False, separators=(",", ":")),
]
)
if ns.daily_omni_save_eval_items:
argv.append("--daily-omni-save-eval-items")
print("\n$", vllm, *argv, "\n", flush=True)
run_vllm_bench_subprocess(vllm, argv)
out = Path(ns.result_dir) / result_filename
if not out.is_file():
raise FileNotFoundError(f"Expected result JSON at {out}")
return out
def run_seed_tts(ns: argparse.Namespace, vllm: str) -> Path:
ns.result_dir.mkdir(parents=True, exist_ok=True)
tag = datetime.now().strftime("%Y%m%d-%H%M%S")
result_filename = f"qwen_omni_acc_seed_tts_{tag}.json"
extra = json.loads(ns.seed_extra_body_json)
argv = (
_build_common_args(ns, result_filename=result_filename)
+ seed_tts_bench_argv(locale=ns.seed_tts_locale)
+ [
"--seed-tts-wer-eval",
"--extra-body",
json.dumps(extra, ensure_ascii=False, separators=(",", ":")),
]
)
if ns.seed_tts_wer_save_items:
argv.append("--seed-tts-wer-save-items")
if ns.seed_tts_file_ref_audio:
argv.append("--seed-tts-file-ref-audio")
extra_env: dict[str, str] = {"SEED_TTS_WER_EVAL": "1"}
if ns.seed_tts_eval_device:
extra_env["SEED_TTS_EVAL_DEVICE"] = ns.seed_tts_eval_device
print("\n$", vllm, *argv, "\n", flush=True)
run_vllm_bench_subprocess(vllm, argv, extra_env=extra_env)
out = Path(ns.result_dir) / result_filename
if not out.is_file():
raise FileNotFoundError(f"Expected result JSON at {out}")
return out
def build_arg_parser() -> argparse.ArgumentParser:
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("--host", default=os.environ.get("ACC_BENCH_HOST", "127.0.0.1"))
p.add_argument("--port", type=int, default=int(os.environ.get("ACC_BENCH_PORT", "8000")))
p.add_argument(
"--model",
default=os.environ.get(
"ACC_BENCH_MODEL",
"Qwen/Qwen3-Omni-30B-A3B-Instruct",
),
help="Model id passed to ``vllm bench serve`` (must match the running server).",
)
p.add_argument("--num-prompts", type=int, default=int(os.environ.get("ACC_BENCH_NUM_PROMPTS", "2000")))
p.add_argument("--max-concurrency", type=int, default=int(os.environ.get("ACC_BENCH_MAX_CONCURRENCY", "10")))
p.add_argument("--num-warmups", type=int, default=int(os.environ.get("ACC_BENCH_NUM_WARMUPS", "0")))
p.add_argument(
"--percentile-metrics",
default=os.environ.get("ACC_BENCH_PERCENTILE_METRICS", "ttft,tpot,itl,e2el,audio_ttfp,audio_rtf"),
)
p.add_argument(
"--ready-check-timeout-sec",
type=int,
default=None,
help="If set, forwarded to ``vllm bench serve`` (probe first request until success). "
"Omit to use upstream default (typically skip).",
)
p.add_argument(
"--result-dir",
type=Path,
default=Path(os.environ.get("ACC_BENCH_RESULT_DIR", str(_default_result_dir()))),
)
p.add_argument("--skip-daily-omni", action="store_true")
p.add_argument("--skip-seed-tts", action="store_true")
p.add_argument(
"--daily-omni-repo",
type=str,
default=None,
help="Hugging Face dataset id for Daily-Omni Hub mode (sets VLLM_DAILY_OMNI_REPO). "
"Ignored when local qa.json + video dir are used.",
)
p.add_argument(
"--daily-omni-qa-json",
type=Path,
default=None,
help="Optional local qa.json; if omitted with no env, uses Hub liarliar/Daily-Omni.",
)
p.add_argument(
"--daily-omni-video-dir",
type=Path,
default=None,
help="Optional local Videos root; if omitted, media is fetched lazily from Hub Videos.tar.",
)
p.add_argument("--daily-omni-input-mode", choices=("all", "visual", "audio"), default="all")
p.add_argument(
"--daily-extra-body-json",
default='{"modalities":["text"]}',
help="JSON merged into each chat request for Daily-Omni (default matches common L4 / text-output runs).",
)
p.add_argument(
"--daily-omni-save-eval-items",
action="store_true",
help="Sets env via CLI flag so per-item rows are stored in the result JSON.",
)
p.add_argument(
"--min-daily-omni-accuracy",
type=float,
default=float((os.environ.get("ACC_BENCH_MIN_DAILY_OMNI_ACCURACY") or "0.69").strip() or "0.69"),
help="Fail when daily_omni_accuracy is strictly below this threshold (0–1). "
"Default baseline 0.69; override with env ACC_BENCH_MIN_DAILY_OMNI_ACCURACY or pass 0 to disable the floor.",
)
p.add_argument(
"--seed-tts-dataset-path",
type=str,
default=None,
help="Optional local root or Hub id; if omitted, uses zhaochenyang20/seed-tts-eval.",
)
p.add_argument("--seed-tts-root", type=Path, default=None, help="Optional override for Seed-TTS filesystem root.")
p.add_argument("--seed-tts-locale", choices=("en", "zh"), default="en")
p.add_argument(
"--seed-extra-body-json",
default='{"modalities":["text","audio"]}',
help="JSON for Seed-TTS chat requests (must include audio for synthesis + PCM capture).",
)
p.add_argument("--seed-tts-wer-save-items", action="store_true")
p.add_argument(
"--seed-tts-file-ref-audio",
action="store_true",
help="Use file:// ref_audio; server must allow local media paths.",
)
p.add_argument(
"--seed-tts-eval-device",
default=os.environ.get("SEED_TTS_EVAL_DEVICE"),
help="Sets SEED_TTS_EVAL_DEVICE for Whisper / WavLM / UTMOS (e.g. cuda:0).",
)
p.add_argument(
"--max-seed-tts-mean-wer",
type=float,
default=0.02,
help="If set, fail when seed_tts_content_error_mean is strictly above this value.",
)
p.add_argument(
"--min-seed-tts-mean-sim",
type=float,
default=None,
help="If set, fail when seed_tts_sim_mean is strictly below this value.",
)
p.add_argument(
"--min-seed-tts-mean-utmos",
type=float,
default=None,
help="If set, fail when seed_tts_utmos_mean is strictly below this value.",
)
return p
def parse_acc_benchmark_args(argv: list[str] | None = None) -> argparse.Namespace:
"""Parse CLI args; when ``argv`` is ``None``, use ``sys.argv[1:]`` (standalone script)."""
if argv is None:
argv = sys.argv[1:]
return build_arg_parser().parse_args(argv)
def run_acc_benchmark(ns: argparse.Namespace) -> int:
"""Run Daily-Omni and/or Seed-TTS client benches against a running server; return 0 on success."""
failed: list[str] = []
with _preserve_benchmark_dataset_env():
sync_dataset_env_from_ns(ns)
vllm = find_vllm_cli()
print(f"Using vLLM CLI: {vllm}", flush=True)
print(f"Repo root (for cwd reference): {_repo_root()}", flush=True)
if not ns.skip_daily_omni:
path = run_daily_omni(ns, vllm)
print(f"\n[Daily-Omni] result JSON: {path}", flush=True)
data = load_benchmark_result(path)
errs = _validate_daily_omni(data, min_accuracy=ns.min_daily_omni_accuracy)
if errs:
failed.extend([f"[Daily-Omni] {e}" for e in errs])
else:
print(
f"[Daily-Omni] daily_omni_accuracy={data.get('daily_omni_accuracy')} "
f"evaluated_ok={data.get('daily_omni_evaluated_ok')}",
flush=True,
)
if not ns.skip_seed_tts:
path = run_seed_tts(ns, vllm)
print(f"\n[Seed-TTS] result JSON: {path}", flush=True)
data = load_benchmark_result(path)
errs = _validate_seed_tts(
data,
max_mean_wer=ns.max_seed_tts_mean_wer,
min_mean_sim=ns.min_seed_tts_mean_sim,
min_mean_utmos=ns.min_seed_tts_mean_utmos,
)
if errs:
failed.extend([f"[Seed-TTS] {e}" for e in errs])
else:
print(
f"[Seed-TTS] mean_wer={data.get('seed_tts_content_error_mean')} "
f"mean_sim={data.get('seed_tts_sim_mean')} mean_utmos={data.get('seed_tts_utmos_mean')} "
f"evaluated={data.get('seed_tts_content_evaluated')}",
flush=True,
)
if failed:
print("\nACCURACY CHECK FAILED:", file=sys.stderr)
for line in failed:
print(f" - {line}", file=sys.stderr)
return 1
print("\nAll configured accuracy checks passed.", flush=True)
return 0
def main() -> int:
return run_acc_benchmark(parse_acc_benchmark_args())
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,137 @@
# SPDX-License-Identifier: Apache-2.0
"""Qwen3-Omni accuracy benchmarks (Daily-Omni MCQ + Seed-TTS WER) via ``vllm bench serve --omni``.
Starts a **module-scoped** Omni OpenAI-compatible server (same pattern as ``tests/dfx/perf`` and
``tests/e2e/online_serving/test_qwen3_omni.py``), then runs the client benches against
``omni_server.host`` / ``omni_server.port`` / ``omni_server.model``.
**Daily-Omni from Hugging Face:** unless ``VLLM_DAILY_OMNI_QA_JSON`` and ``VLLM_DAILY_OMNI_VIDEO_DIR``
point at a full local tree, the bench uses ``--dataset-path`` (default ``liarliar/Daily-Omni`` via
``VLLM_DAILY_OMNI_REPO`` / ``--daily-omni-repo``). QA loads through ``datasets``; ``Videos.tar`` is
downloaded and extracted under ``HF_HOME`` on demand. The tests patch in
``--daily-omni-inline-local-video`` so multimodal payloads use data URLs (no
``--allowed-local-media-path`` on the server). Use small ``--num-prompts`` defaults suitable for CI
(override with ``ACC_BENCH_NUM_PROMPTS`` / ``ACC_BENCH_MAX_CONCURRENCY``; see
:func:`tests.e2e.accuracy.qwen3_omni.qwen3_omni_acc_bench_core.build_acc_benchmark_cli_argv`).
This package lives under ``tests/e2e/accuracy/qwen3_omni/``, so pytest still loads
``tests/e2e/accuracy/conftest.py``, which imports ``tests.conftest`` (heavy deps: ``vllm``, ``torch``, …).
A broken or partial install can therefore **fail during collection** before these tests run.
If ``vllm`` is not on ``PATH``, the tests **skip** instead of erroring. Without
``VLLM_SKIP_ACC_BENCH=1``, a failed bench still yields a **failed** run (non-zero subprocess exit).
Run::
pytest -sv tests/e2e/accuracy/qwen3_omni/test_qwen3_omni.py
Only the subprocess accuracy marker::
pytest -sv tests/e2e/accuracy/qwen3_omni/test_qwen3_omni.py -m qwen3_omni_acc
Skip when you do not have GPUs, a server, or datasets (CI opt-out)::
VLLM_SKIP_ACC_BENCH=1 pytest -sv tests/e2e/accuracy/qwen3_omni/test_qwen3_omni.py
Standalone CLI (expects a server already up; uses ``ACC_BENCH_*`` env defaults)::
python tests/e2e/accuracy/qwen3_omni/run_qwen_omni_acc_benchmark.py --help
"""
from __future__ import annotations
from pathlib import Path
import pytest
from tests.e2e.accuracy.qwen3_omni import run_qwen_omni_acc_benchmark as _acc_bench
from tests.e2e.accuracy.qwen3_omni.qwen3_omni_acc_bench_core import (
build_acc_benchmark_cli_argv,
find_vllm_cli,
)
from tests.helpers.mark import hardware_test
from tests.helpers.runtime import OmniServerParams
from tests.helpers.stage_config import get_deploy_config_path, modify_stage_config
from vllm_omni.platforms import current_omni_platform
_E2E_ROOT = Path(__file__).resolve().parent.parent.parent
models = ["Qwen/Qwen3-Omni-30B-A3B-Instruct"]
pytestmark = [pytest.mark.full_model, pytest.mark.omni]
_CI_DEPLOY = get_deploy_config_path("ci/qwen3_omni_moe.yaml")
def get_chunk_config(config_path: str | None = None):
"""Load the qwen3_omni CI deploy yaml with async_chunk modifications for streaming mode."""
if config_path is None:
config_path = _CI_DEPLOY
# TODO: remove this workaround once legacy `stage_args` path is deleted.
# The pipeline (qwen3_omni/pipeline.py) already wires
# thinker2talker_async_chunk / talker2code2wav_async_chunk on stage 0/1,
# so only async_chunk needs flipping. Writing nested `engine_args:` into
# the new-schema overlay trips _parse_stage_deploy's legacy branch and
# drops flat fields (load_format, max_num_seqs, ...).
return modify_stage_config(config_path, updates={"async_chunk": True})
if current_omni_platform.is_xpu():
stage_configs = [_CI_DEPLOY]
else: # CUDA + ROCm MI325 share the same deploy config
stage_configs = [get_chunk_config()]
test_params = [
OmniServerParams(model=model, stage_config_path=stage_config) for model in models for stage_config in stage_configs
]
def _require_vllm_cli() -> None:
try:
find_vllm_cli()
except FileNotFoundError as exc:
pytest.skip(str(exc))
@pytest.fixture(autouse=True)
def _daily_omni_hub_inline_media(monkeypatch: pytest.MonkeyPatch) -> None:
"""Hub / lazy-cache mode uses local files → default ``file://`` needs server allowlist.
``run_qwen_omni_acc_benchmark`` binds ``daily_omni_bench_argv`` at import time; patch that copy
so we append ``--daily-omni-inline-local-video`` whenever the core helper did not already set it
(local qa.json + video-dir mode already passes the flag).
"""
orig = _acc_bench.daily_omni_bench_argv
def _wrapped() -> list[str]:
out = list(orig())
if "--daily-omni-inline-local-video" not in out:
out.append("--daily-omni-inline-local-video")
return out
monkeypatch.setattr(_acc_bench, "daily_omni_bench_argv", _wrapped)
monkeypatch.setenv("VLLM_WORKER_MULTIPROC_METHOD", "spawn")
monkeypatch.setenv("VLLM_TEST_CLEAN_GPU_MEMORY", "0")
@hardware_test(res={"cuda": "H100", "rocm": "MI325"}, num_cards=2)
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
def test_qwen3_omni_daily_omni_accuracy_bench(omni_server) -> None:
_require_vllm_cli()
pytest.importorskip("datasets")
pytest.importorskip("huggingface_hub")
ns = _acc_bench.parse_acc_benchmark_args(
build_acc_benchmark_cli_argv(omni_server, skip_seed=True, skip_daily=False)
)
assert _acc_bench.run_acc_benchmark(ns) == 0
@hardware_test(res={"cuda": "H100", "rocm": "MI325"}, num_cards=2)
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
def test_qwen3_omni_seed_tts_wer_bench(omni_server) -> None:
_require_vllm_cli()
pytest.importorskip("huggingface_hub")
ns = _acc_bench.parse_acc_benchmark_args(
build_acc_benchmark_cli_argv(omni_server, skip_seed=False, skip_daily=True)
)
assert _acc_bench.run_acc_benchmark(ns) == 0
@@ -9,10 +9,10 @@ from benchmarks.accuracy.text_to_image.gbench import main as gbench_main
from tests.e2e.accuracy.helpers import infer_model_label, reset_artifact_dir
from tests.helpers.mark import hardware_test
pytestmark = [pytest.mark.diffusion, pytest.mark.full_model]
@pytest.mark.advanced_model
@pytest.mark.benchmark
@pytest.mark.diffusion
@hardware_test(res={"cuda": "H100"}, num_cards=1)
def test_gebench_h100_smoke(
gebench_accuracy_servers,
@@ -10,10 +10,10 @@ from benchmarks.accuracy.image_to_image.gedit_bench import main as gedit_main
from tests.e2e.accuracy.helpers import infer_model_label, reset_artifact_dir
from tests.helpers.mark import hardware_test
pytestmark = [pytest.mark.diffusion, pytest.mark.full_model]
@pytest.mark.advanced_model
@pytest.mark.benchmark
@pytest.mark.diffusion
@hardware_test(res={"cuda": "H100"}, num_cards=1)
def test_gedit_bench_h100_smoke(
gedit_accuracy_servers,
@@ -0,0 +1,410 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
SSIM/PSNR accuracy tests for LTX-2.3.
1. **Transformer parity** (``test_ltx2_3_transformer_matches_diffusers``):
Swaps our custom transformer into diffusers' ``LTX2Pipeline`` to measure
numerical parity in isolation. Thresholds: SSIM >= 0.95, PSNR >= 28 dB.
Result: SSIM 0.999987 (bit-identical).
2. **Full pipeline** (``test_ltx2_3_pipeline_matches_diffusers``):
Runs the full vLLM-Omni serving stack (``OmniServer`` -> HTTP API) and
compares per-frame against stock diffusers. Currently skipped because
the OmniServer subprocess creates a different RNG state than in-process
diffusers, producing different initial latents from the same seed.
This is a test infrastructure limitation, not a model accuracy issue.
"""
from __future__ import annotations
import gc
import os
import tempfile
from pathlib import Path
import diffusers
import numpy as np
import pytest
import requests
import torch
from PIL import Image
from tests.e2e.accuracy.helpers import compute_image_ssim_psnr, model_output_dir
from tests.helpers.env import run_post_test_cleanup, run_pre_test_cleanup
from tests.helpers.mark import hardware_test
from tests.helpers.runtime import OmniServer
# Parse diffusers version for compatibility check
_DIFFUSERS_VERSION = tuple(int(x) for x in diffusers.__version__.split(".")[:2] if x.isdigit())
_DIFFUSERS_038 = _DIFFUSERS_VERSION >= (0, 38)
MODEL_ID = "dg845/LTX-2.3-Diffusers"
MODEL_ENV_VAR = "VLLM_TEST_LTX23_MODEL"
PROMPT = "A lighthouse on a rocky cliff at sunset, waves crashing below, golden hour lighting"
NEGATIVE_PROMPT = "blurry, low quality, distorted, watermark"
WIDTH = 512
HEIGHT = 384
NUM_FRAMES = 25 # ~1 second at 24fps
NUM_INFERENCE_STEPS = 20
GUIDANCE_SCALE = 4.0
SEED = 42
# Transformer-swap test: near-identical output expected
TRANSFORMER_SSIM_THRESHOLD = 0.95
TRANSFORMER_PSNR_THRESHOLD = 28.0
# Full-pipeline test: allows minor divergence from RNG / pipeline differences
PIPELINE_SSIM_THRESHOLD = 0.94
PIPELINE_PSNR_THRESHOLD = 28.0
def _model_name() -> str:
return os.environ.get(MODEL_ENV_VAR, MODEL_ID)
def _local_files_only(model: str) -> bool:
return Path(model).exists()
# ---------------------------------------------------------------------------
# Frame extraction helpers
# ---------------------------------------------------------------------------
def _video_to_frames(video_np: np.ndarray) -> list[Image.Image]:
"""Convert numpy video to list of PIL Images."""
while video_np.ndim > 4:
video_np = video_np[0]
if video_np.dtype in (np.float32, np.float64, np.float16):
video_np = np.clip(video_np * 255, 0, 255).astype(np.uint8)
return [Image.fromarray(video_np[t]) for t in range(video_np.shape[0])]
def _extract_diffusers_frames(result) -> list[Image.Image]:
"""Extract frames from diffusers pipeline output."""
video = result.frames
if isinstance(video, np.ndarray):
return _video_to_frames(video)
if isinstance(video, list):
if isinstance(video[0], list):
return [img.convert("RGB") for img in video[0]]
if isinstance(video[0], Image.Image):
return [img.convert("RGB") for img in video]
raise ValueError(f"Unexpected output type: {type(video)}")
def _extract_mp4_frames(mp4_bytes: bytes) -> list[Image.Image]:
"""Extract frames from an MP4 video using ffmpeg."""
import subprocess
with tempfile.TemporaryDirectory() as tmpdir:
mp4_path = os.path.join(tmpdir, "video.mp4")
with open(mp4_path, "wb") as f:
f.write(mp4_bytes)
# Extract video frames as PNG files using ffmpeg
frame_pattern = os.path.join(tmpdir, "frame_%04d.png")
subprocess.run(
["ffmpeg", "-i", mp4_path, "-vsync", "0", frame_pattern],
capture_output=True,
check=True,
)
# Load frames in order
frames = []
i = 1
while True:
fpath = os.path.join(tmpdir, f"frame_{i:04d}.png")
if not os.path.exists(fpath):
break
frames.append(Image.open(fpath).convert("RGB").copy())
i += 1
return frames
# ---------------------------------------------------------------------------
# Comparison helper
# ---------------------------------------------------------------------------
def _assert_video_similarity(
*,
model_name: str,
vllm_frames: list[Image.Image],
diffusers_frames: list[Image.Image],
ssim_threshold: float,
psnr_threshold: float,
) -> tuple[float, float]:
"""Compare video frames and assert SSIM/PSNR meet thresholds."""
min_frames = min(len(vllm_frames), len(diffusers_frames))
assert min_frames > 0, "No frames to compare"
ssim_scores = []
psnr_scores = []
for i in range(min_frames):
ssim_val, psnr_val = compute_image_ssim_psnr(
prediction=vllm_frames[i],
reference=diffusers_frames[i],
)
ssim_scores.append(ssim_val)
psnr_scores.append(psnr_val)
avg_ssim = sum(ssim_scores) / len(ssim_scores)
avg_psnr = sum(psnr_scores) / len(psnr_scores)
print(f"\n{model_name} video similarity ({min_frames} frames):")
print(f" SSIM: avg={avg_ssim:.6f}, min={min(ssim_scores):.6f}, threshold>={ssim_threshold:.6f}")
print(f" PSNR: avg={avg_psnr:.6f} dB, min={min(psnr_scores):.6f} dB, threshold>={psnr_threshold:.6f} dB")
assert avg_ssim >= ssim_threshold, f"SSIM below threshold: got {avg_ssim:.6f}, expected >= {ssim_threshold:.6f}."
assert avg_psnr >= psnr_threshold, f"PSNR below threshold: got {avg_psnr:.6f}, expected >= {psnr_threshold:.6f}."
return avg_ssim, avg_psnr
# ---------------------------------------------------------------------------
# Diffusers baseline (shared by both tests)
# ---------------------------------------------------------------------------
def _run_diffusers_baseline(model: str, output_dir: Path) -> list[Image.Image]:
"""Generate video using stock diffusers LTX2Pipeline."""
from diffusers import LTX2Pipeline
run_pre_test_cleanup(enable_force=True)
pipe = None
try:
pipe = LTX2Pipeline.from_pretrained(
model, torch_dtype=torch.bfloat16, local_files_only=_local_files_only(model)
).to("cuda")
generator = torch.Generator(device="cuda").manual_seed(SEED)
result = pipe(
prompt=PROMPT,
negative_prompt=NEGATIVE_PROMPT,
width=WIDTH,
height=HEIGHT,
num_frames=NUM_FRAMES,
num_inference_steps=NUM_INFERENCE_STEPS,
guidance_scale=GUIDANCE_SCALE,
generator=generator,
output_type="np",
)
frames = _extract_diffusers_frames(result)
for i, f in enumerate(frames):
f.save(output_dir / f"diffusers_frame_{i:04d}.png")
return frames
finally:
del pipe
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
run_post_test_cleanup(enable_force=True)
# ---------------------------------------------------------------------------
# Test 1: Transformer-swap parity
# ---------------------------------------------------------------------------
def _run_with_custom_transformer(model: str, output_dir: Path) -> list[Image.Image]:
"""Run diffusers pipeline with our custom transformer swapped in."""
from contextlib import nullcontext
from diffusers import LTX2Pipeline
from vllm.config import VllmConfig, set_current_vllm_config
from vllm.distributed.parallel_state import init_distributed_environment, initialize_model_parallel
from vllm_omni.diffusion.models.ltx2.pipeline_ltx2 import create_transformer_from_config, load_transformer_config
vllm_config = VllmConfig()
ctx = set_current_vllm_config(vllm_config)
ctx.__enter__()
if not torch.distributed.is_initialized():
os.environ.setdefault("MASTER_ADDR", "localhost")
os.environ.setdefault("MASTER_PORT", "29503")
os.environ.setdefault("RANK", "0")
os.environ.setdefault("WORLD_SIZE", "1")
init_distributed_environment(world_size=1, rank=0, local_rank=0)
initialize_model_parallel(tensor_model_parallel_size=1)
local = _local_files_only(model)
pipe = LTX2Pipeline.from_pretrained(model, torch_dtype=torch.bfloat16, local_files_only=local)
transformer_config = load_transformer_config(model, "transformer", local)
our_transformer = create_transformer_from_config(transformer_config)
diffusers_state = dict(pipe.transformer.named_parameters())
def _weight_iter():
for name, param in diffusers_state.items():
yield name, param.data
our_transformer.load_weights(_weight_iter())
our_transformer = our_transformer.to(dtype=torch.bfloat16, device="cuda").eval()
# Compatibility shims for diffusers pipeline
our_transformer.dtype = torch.bfloat16
if not hasattr(our_transformer, "cache_context"):
our_transformer.cache_context = lambda name: nullcontext()
del pipe.transformer
pipe.transformer = our_transformer
for name, component in pipe.components.items():
if name != "transformer" and hasattr(component, "to"):
try:
component.to("cuda")
except Exception:
pass
generator = torch.Generator(device="cuda").manual_seed(SEED)
result = pipe(
prompt=PROMPT,
negative_prompt=NEGATIVE_PROMPT,
width=WIDTH,
height=HEIGHT,
num_frames=NUM_FRAMES,
num_inference_steps=NUM_INFERENCE_STEPS,
guidance_scale=GUIDANCE_SCALE,
generator=generator,
output_type="np",
)
frames = _extract_diffusers_frames(result)
for i, f in enumerate(frames):
f.save(output_dir / f"vllm_transformer_frame_{i:04d}.png")
del pipe, result, our_transformer
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
return frames
@pytest.mark.advanced_model
@pytest.mark.benchmark
@pytest.mark.diffusion
@pytest.mark.skipif(
not _DIFFUSERS_038, reason="LTX-2.3 requires diffusers >= 0.38.0 for cross_attn_mod and BWE vocoder"
)
@hardware_test(res={"cuda": "H100"}, num_cards=1)
def test_ltx2_3_transformer_matches_diffusers(accuracy_artifact_root: Path) -> None:
"""Transformer-level parity: swap our transformer into diffusers pipeline.
Isolates transformer numerical accuracy from pipeline-level differences.
Both runs use diffusers' denoising loop, CFG, scheduler, and RNG.
"""
model = _model_name()
output_dir = model_output_dir(accuracy_artifact_root, MODEL_ID)
diffusers_frames = _run_diffusers_baseline(model=model, output_dir=output_dir)
vllm_frames = _run_with_custom_transformer(model=model, output_dir=output_dir)
_assert_video_similarity(
model_name=f"{MODEL_ID} (transformer-swap)",
vllm_frames=vllm_frames,
diffusers_frames=diffusers_frames,
ssim_threshold=TRANSFORMER_SSIM_THRESHOLD,
psnr_threshold=TRANSFORMER_PSNR_THRESHOLD,
)
# ---------------------------------------------------------------------------
# Test 2: Full pipeline (OmniServer → HTTP API vs diffusers)
# ---------------------------------------------------------------------------
def _run_vllm_omni_serving(model: str, output_dir: Path) -> list[Image.Image]:
"""Generate video via the full vLLM-Omni serving stack."""
server_args = [
"--model-class-name",
"LTX23Pipeline",
"--stage-init-timeout",
"600",
]
with OmniServer(model, server_args, use_omni=True) as server:
# Submit generation request
response = requests.post(
f"http://{server.host}:{server.port}/v1/videos",
files={
"prompt": (None, PROMPT),
"negative_prompt": (None, NEGATIVE_PROMPT),
"model": (None, server.model),
"num_frames": (None, str(NUM_FRAMES)),
"fps": (None, "24"),
"size": (None, f"{WIDTH}x{HEIGHT}"),
"num_inference_steps": (None, str(NUM_INFERENCE_STEPS)),
"guidance_scale": (None, str(GUIDANCE_SCALE)),
"seed": (None, str(SEED)),
},
timeout=120,
)
response.raise_for_status()
video_id = response.json()["id"]
# Poll for completion
import time
for _ in range(120):
status_resp = requests.get(
f"http://{server.host}:{server.port}/v1/videos/{video_id}",
timeout=30,
)
status_resp.raise_for_status()
status = status_resp.json()["status"]
if status == "completed":
break
if status in ("error", "failed"):
raise RuntimeError(f"Video generation failed: {status_resp.json()}")
time.sleep(5)
else:
raise TimeoutError(f"Video generation timed out after 600s (id={video_id})")
# Download video content
content_resp = requests.get(
f"http://{server.host}:{server.port}/v1/videos/{video_id}/content",
timeout=120,
)
content_resp.raise_for_status()
mp4_bytes = content_resp.content
# Save MP4
mp4_path = output_dir / "vllm_omni_pipeline.mp4"
with open(mp4_path, "wb") as f:
f.write(mp4_bytes)
# Extract frames
frames = _extract_mp4_frames(mp4_bytes)
for i, frame in enumerate(frames):
frame.save(output_dir / f"vllm_pipeline_frame_{i:04d}.png")
return frames
@pytest.mark.advanced_model
@pytest.mark.benchmark
@pytest.mark.diffusion
@pytest.mark.skipif(
not _DIFFUSERS_038, reason="LTX-2.3 requires diffusers >= 0.38.0 for cross_attn_mod and BWE vocoder"
)
@hardware_test(res={"cuda": "H100"}, num_cards=1)
def test_ltx2_3_pipeline_matches_diffusers(accuracy_artifact_root: Path) -> None:
"""Full-pipeline parity: vLLM-Omni serving stack vs diffusers.
Runs the complete vLLM-Omni OmniServer (subprocess, HTTP API, video
encoding) and compares per-frame against stock diffusers output.
Follows the Wan2.2 / Qwen Image pattern with seed-based determinism.
"""
model = _model_name()
output_dir = model_output_dir(accuracy_artifact_root, MODEL_ID)
diffusers_frames = _run_diffusers_baseline(model=model, output_dir=output_dir)
vllm_frames = _run_vllm_omni_serving(model=model, output_dir=output_dir)
_assert_video_similarity(
model_name=f"{MODEL_ID} (full-pipeline)",
vllm_frames=vllm_frames,
diffusers_frames=diffusers_frames,
ssim_threshold=PIPELINE_SSIM_THRESHOLD,
psnr_threshold=PIPELINE_PSNR_THRESHOLD,
)
+3 -2
View File
@@ -17,6 +17,9 @@ from tests.helpers.env import run_post_test_cleanup, run_pre_test_cleanup
from tests.helpers.mark import hardware_test
from tests.helpers.runtime import OmniServer
pytestmark = [pytest.mark.full_model, pytest.mark.diffusion]
MODEL_ID = "Qwen/Qwen-Image"
MODEL_ENV_VAR = "QWEN_IMAGE_MODEL"
PROMPT = "A photo of a cat sitting on a laptop keyboard, digital art style."
@@ -99,9 +102,7 @@ def _run_diffusers_qwen_image(*, model: str, output_path: Path) -> Image.Image:
run_post_test_cleanup(enable_force=True)
@pytest.mark.advanced_model
@pytest.mark.benchmark
@pytest.mark.diffusion
@hardware_test(res={"cuda": "H100"}, num_cards=1)
def test_qwen_image_matches_diffusers(accuracy_artifact_root: Path) -> None:
model = _model_name()
+3 -4
View File
@@ -15,6 +15,9 @@ from tests.helpers.env import run_post_test_cleanup, run_pre_test_cleanup
from tests.helpers.mark import hardware_test
from tests.helpers.runtime import OmniServer
pytestmark = [pytest.mark.full_model, pytest.mark.diffusion]
SINGLE_MODEL = "Qwen/Qwen-Image-Edit"
MULTIPLE_MODEL = "Qwen/Qwen-Image-Edit-2509"
WIDTH = 512
@@ -169,9 +172,7 @@ def _diffusers_output_multiple_image(
)
@pytest.mark.advanced_model
@pytest.mark.benchmark
@pytest.mark.diffusion
@hardware_test(res={"cuda": "H100"}, num_cards=1)
def test_qwen_image_edit_single_matches_diffusers(
accuracy_artifact_root: Path,
@@ -196,9 +197,7 @@ def test_qwen_image_edit_single_matches_diffusers(
)
@pytest.mark.advanced_model
@pytest.mark.benchmark
@pytest.mark.diffusion
@hardware_test(res={"cuda": "H100"}, num_cards=1)
@pytest.mark.skip(
reason="Skipping as the second image seems to be ignored by the API. Will come back to this later after #2772 is merged."
@@ -17,6 +17,9 @@ from tests.helpers.env import run_post_test_cleanup, run_pre_test_cleanup
from tests.helpers.mark import hardware_test
from tests.helpers.runtime import OmniServer
pytestmark = [pytest.mark.full_model, pytest.mark.diffusion]
MODEL_ID = "Qwen/Qwen-Image-Layered"
MODEL_ENV_VAR = "QWEN_IMAGE_LAYERED_MODEL"
PROMPT = "decompose into layers"
@@ -126,9 +129,7 @@ def _run_diffusers_qwen_image_layered(*, model: str, input_image: Image.Image, o
run_post_test_cleanup(enable_force=True)
@pytest.mark.advanced_model
@pytest.mark.benchmark
@pytest.mark.diffusion
@hardware_test(res={"cuda": "H100"}, num_cards=1)
def test_qwen_image_layered_matches_diffusers(accuracy_artifact_root: Path, qwen_bear_image: Image.Image) -> None:
model = _model_name()
@@ -50,6 +50,8 @@ from tests.e2e.accuracy.wan22_i2v.wan22_i2v_video_similarity_common import (
from tests.helpers.mark import hardware_test
from tests.helpers.runtime import OmniServerParams
pytestmark = [pytest.mark.diffusion, pytest.mark.full_model]
def test_parse_video_metadata_extracts_dimensions_and_fps() -> None:
payload = {
@@ -537,9 +539,7 @@ def _generate_offline_video(*, image_source: str) -> tuple[Path, Path]:
return offline_path, offline_metadata_path
@pytest.mark.advanced_model
@pytest.mark.benchmark
@pytest.mark.diffusion
@hardware_test(res={"cuda": "H100"}, num_cards=1)
def test_wan22_i2v_diffusers_offline_generates_video(
wan22_i2v_image_source: str | None,
@@ -563,9 +563,7 @@ def test_wan22_i2v_diffusers_offline_generates_video(
assert offline_metadata["frame_count"] == NUM_FRAMES
@pytest.mark.advanced_model
@pytest.mark.benchmark
@pytest.mark.diffusion
@hardware_test(res={"cuda": "H100"}, num_cards=2)
@pytest.mark.parametrize("omni_server", SERVER_CASES, indirect=True)
def test_wan22_i2v_online_serving_generates_video(
@@ -594,9 +592,7 @@ def test_wan22_i2v_online_serving_generates_video(
assert online_metadata["frame_count"] == NUM_FRAMES
@pytest.mark.advanced_model
@pytest.mark.benchmark
@pytest.mark.diffusion
@hardware_test(res={"cuda": "H100"}, num_cards=2)
def test_wan22_i2v_serving_matches_diffusers_video_similarity(
wan22_i2v_image_source: str | None,
@@ -1,79 +0,0 @@
# stage config for running BAGEL with Mooncake connector for CI e2e tests.
# This config is optimized for single GPU tests with Mooncake inter-stage communication.
stage_args:
- stage_id: 0
stage_type: llm
prompt_expand_func: vllm_omni.model_executor.stage_input_processors.bagel.expand_cfg_prompts
runtime:
devices: "0"
engine_args:
model_stage: thinker
max_num_seqs: 1
model_arch: BagelForConditionalGeneration
worker_type: ar
scheduler_cls: vllm_omni.core.sched.omni_ar_scheduler.OmniARScheduler
gpu_memory_utilization: 0.45
enforce_eager: true
trust_remote_code: true
engine_output_type: text
distributed_executor_backend: mp
enable_prefix_caching: false
max_num_batched_tokens: 32768
tensor_parallel_size: 1
load_format: dummy
omni_kv_config:
need_send_cache: true
kv_transfer_criteria:
type: prefill_finished
final_output: true
final_output_type: text
is_comprehension: true
default_sampling_params:
temperature: 0.4
top_p: 0.9
top_k: 1
max_tokens: 2048
seed: 52
detokenize: true
repetition_penalty: 1.05
output_connectors:
to_stage_1: mooncake_connector
- stage_id: 1
stage_type: diffusion
cfg_kv_collect_func: vllm_omni.model_executor.stage_input_processors.bagel.collect_cfg_kv_caches
runtime:
devices: "0"
engine_args:
model_stage: dit
max_num_seqs: 1
enforce_eager: true
trust_remote_code: true
distributed_executor_backend: mp
omni_kv_config:
need_recv_cache: true
engine_input_source: [0]
final_output: true
final_output_type: image
is_comprehension: false
default_sampling_params:
seed: 52
input_connectors:
from_stage_0: mooncake_connector
# Top-level runtime config with Mooncake connector
runtime:
enabled: true
connectors:
mooncake_connector:
name: MooncakeConnector
extra:
host: "${MOONCAKE_HOST}"
metadata_server: "http://${MOONCAKE_HOST}:${MOONCAKE_HTTP_PORT}/metadata"
master: "${MOONCAKE_HOST}:${MOONCAKE_RPC_PORT}"
segment: 64000000
localbuf: 64000000
proto: tcp
edges:
- from: 0
to: 1
@@ -1,76 +0,0 @@
# stage config for running BAGEL with SharedMemory connector for CI e2e tests.
# This config is optimized for single GPU tests with SharedMemory inter-stage communication.
stage_args:
- stage_id: 0
stage_type: llm
prompt_expand_func: vllm_omni.model_executor.stage_input_processors.bagel.expand_cfg_prompts
runtime:
devices: "0"
engine_args:
model_stage: thinker
max_num_seqs: 1
model_arch: OmniBagelForConditionalGeneration
worker_type: ar
scheduler_cls: vllm_omni.core.sched.omni_ar_scheduler.OmniARScheduler
gpu_memory_utilization: 0.45
enforce_eager: true
trust_remote_code: true
engine_output_type: text
distributed_executor_backend: "mp"
enable_prefix_caching: false
max_num_batched_tokens: 32768
tensor_parallel_size: 1
load_format: dummy
omni_kv_config:
need_send_cache: true
kv_transfer_criteria:
type: prefill_finished #or special token generated
final_output: true
final_output_type: text
is_comprehension: true
default_sampling_params:
temperature: 0.4
top_p: 0.9
top_k: 1
max_tokens: 2048
seed: 52
detokenize: True
repetition_penalty: 1.05
- stage_id: 1
stage_type: diffusion
cfg_kv_collect_func: vllm_omni.model_executor.stage_input_processors.bagel.collect_cfg_kv_caches
runtime:
devices: "0"
engine_args:
model_stage: dit
max_num_seqs: 1
enforce_eager: true
trust_remote_code: true
distributed_executor_backend: "mp"
omni_kv_config:
need_recv_cache: true
engine_input_source: [0]
final_output: true
final_output_type: image
is_comprehension: false
default_sampling_params:
seed: 52
# Runtime edges
runtime:
enabled: true
# Distributed connectors configuration (optional)
# More connectors will be supported in the future.
connectors:
shared_memory_connector:
name: SharedMemoryConnector
extra:
shm_threshold_bytes: 65536 # 64KB threshold
edges:
- from: 0
to: 1
@@ -15,7 +15,6 @@ Equivalent to running:
"""
import socket
from pathlib import Path
from typing import Any
import pytest
@@ -24,10 +23,12 @@ from vllm.assets.image import ImageAsset
from tests.helpers.mark import hardware_test
from tests.helpers.runtime import OmniRunner
from tests.helpers.stage_config import modify_stage_config
from tests.helpers.stage_config import get_deploy_config_path, modify_stage_config
from vllm_omni.entrypoints.omni import Omni
from vllm_omni.platforms import current_omni_platform
BAGEL_CI_DEPLOY = get_deploy_config_path("ci/bagel.yaml")
# Reference pixel data extracted from the known-good output image
# Generated with seed=52, num_inference_steps=15,
# prompt='Change the grass color to red',
@@ -183,8 +184,8 @@ def _generate_bagel_img2img(
return generated_image
def _resolve_stage_config(config_path: str, run_level: str) -> str:
"""Resolve stage config based on run level.
def _resolve_deploy_config(config_path: str, run_level: str) -> str:
"""Resolve deploy config based on run level.
For advanced_model (real weights), strip load_format: dummy so the model
falls back to loading real weights from HuggingFace.
@@ -193,9 +194,9 @@ def _resolve_stage_config(config_path: str, run_level: str) -> str:
return modify_stage_config(
config_path,
deletes={
"stage_args": {
0: ["engine_args.load_format"],
1: ["engine_args.load_format"],
"stages": {
0: ["load_format"],
1: ["load_format"],
}
},
)
@@ -209,8 +210,7 @@ def _resolve_stage_config(config_path: str, run_level: str) -> str:
def test_bagel_img2img_shared_memory_connector(run_level):
"""Test Bagel img2img with shared memory connector."""
input_image = _load_input_image()
config_path = str(Path(__file__).parent / "stage_configs" / "bagel_sharedmemory_ci.yaml")
config_path = _resolve_stage_config(config_path, run_level)
config_path = _resolve_deploy_config(BAGEL_CI_DEPLOY, run_level)
with OmniRunner(
"ByteDance-Seed/BAGEL-7B-MoT",
stage_configs_path=config_path,
+10 -11
View File
@@ -17,14 +17,13 @@ Assertions:
import json
import os
from pathlib import Path
from vllm_omni.inputs.data import OmniSamplingParams
from vllm_omni.outputs import OmniRequestOutput
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
from pathlib import Path
import numpy as np
import pytest
import torch
@@ -33,13 +32,13 @@ from safetensors.torch import save_file
from tests.helpers.mark import hardware_test
from tests.helpers.runtime import OmniRunner
from tests.helpers.stage_config import modify_stage_config
from tests.helpers.stage_config import get_deploy_config_path, modify_stage_config
from vllm_omni.entrypoints.omni import Omni
from vllm_omni.lora.request import LoRARequest
from vllm_omni.lora.utils import stable_lora_int_id
MODEL = "ByteDance-Seed/BAGEL-7B-MoT"
BAGEL_STAGE_CONFIG = str(Path(__file__).parent / "stage_configs" / "bagel_sharedmemory_ci.yaml")
BAGEL_STAGE_CONFIG = get_deploy_config_path("ci/bagel.yaml")
DEFAULT_PROMPT = "<|im_start|>A cute cat<|im_end|>"
@@ -48,14 +47,14 @@ DEFAULT_PROMPT = "<|im_start|>A cute cat<|im_end|>"
# ---------------------------------------------------------------------------
def _resolve_stage_config(config_path: str, run_level: str) -> str:
def _resolve_deploy_config(config_path: str, run_level: str) -> str:
if run_level == "advanced_model":
return modify_stage_config(
config_path,
deletes={
"stage_args": {
0: ["engine_args.load_format"],
1: ["engine_args.load_format"],
"stages": {
0: ["load_format"],
1: ["load_format"],
}
},
)
@@ -153,7 +152,7 @@ def _make_file_lora_request(adapter_dir: Path) -> LoRARequest:
@hardware_test(res={"cuda": "H100", "rocm": "MI325"})
def test_bagel_lora_scale_and_deactivation(run_level, tmp_path):
"""Validate LoRA effect, bounded perturbation, and clean deactivation."""
config_path = _resolve_stage_config(BAGEL_STAGE_CONFIG, run_level)
config_path = _resolve_deploy_config(BAGEL_STAGE_CONFIG, run_level)
with OmniRunner(MODEL, stage_configs_path=config_path) as runner:
omni = runner.omni
lora_request = _make_file_lora_request(tmp_path / "bagel_lora")
@@ -188,9 +187,9 @@ def test_bagel_lora_scale_and_deactivation(run_level, tmp_path):
f"LoRA scale has no effect: diff_1x={diff_1x:.2f}, diff_2x={diff_2x:.2f}"
)
# (c) Output is not corrupted
# (c) Output is not corrupted (scale=2.0 can produce ~2x the diff of scale=1.0)
assert diff_1x < 80, f"LoRA output looks corrupted: diff_1x={diff_1x}"
assert diff_2x < 80, f"LoRA output looks corrupted: diff_2x={diff_2x}"
assert diff_2x < 120, f"LoRA output looks corrupted: diff_2x={diff_2x}"
# (d) Deactivation fully restores base model
assert diff_restored == 0.0, f"Base model not restored after LoRA deactivation: diff={diff_restored}"
@@ -21,7 +21,6 @@ import socket
import subprocess
import tempfile
import time
from pathlib import Path
from typing import Any
import pytest
@@ -29,10 +28,13 @@ from PIL import Image
from tests.helpers.mark import hardware_test
from tests.helpers.runtime import OmniRunner
from tests.helpers.stage_config import modify_stage_config
from tests.helpers.stage_config import get_deploy_config_path, modify_stage_config
from vllm_omni.entrypoints.omni import Omni
from vllm_omni.platforms import current_omni_platform
BAGEL_CI_DEPLOY = get_deploy_config_path("ci/bagel.yaml")
BAGEL_MOONCAKE_CI_DEPLOY = get_deploy_config_path("ci/bagel_mooncake.yaml")
# Reference pixel data extracted from the known-good output image
# Each entry contains (x, y) position and expected (R, G, B) values
# "Generated with seed=52, num_inference_steps=15,
@@ -172,8 +174,8 @@ def _generate_bagel_image(omni: Omni, prompt: str = DEFAULT_PROMPT) -> Image.Ima
return generated_image
def _resolve_stage_config(config_path: str, run_level: str) -> str:
"""Resolve stage config based on run level.
def _resolve_deploy_config(config_path: str, run_level: str) -> str:
"""Resolve deploy config based on run level.
For advanced_model (real weights), strip load_format: dummy so the model
falls back to loading real weights from HuggingFace.
@@ -182,9 +184,9 @@ def _resolve_stage_config(config_path: str, run_level: str) -> str:
return modify_stage_config(
config_path,
deletes={
"stage_args": {
0: ["engine_args.load_format"],
1: ["engine_args.load_format"],
"stages": {
0: ["load_format"],
1: ["load_format"],
}
},
)
@@ -197,8 +199,7 @@ def _resolve_stage_config(config_path: str, run_level: str) -> str:
@hardware_test(res={"cuda": "H100", "rocm": "MI325"})
def test_bagel_text2img_shared_memory_connector(run_level):
"""Test Bagel text2img with shared memory connector."""
config_path = str(Path(__file__).parent / "stage_configs" / "bagel_sharedmemory_ci.yaml")
config_path = _resolve_stage_config(config_path, run_level)
config_path = _resolve_deploy_config(BAGEL_CI_DEPLOY, run_level)
with OmniRunner(
"ByteDance-Seed/BAGEL-7B-MoT",
stage_configs_path=config_path,
@@ -277,7 +278,7 @@ def _cleanup_mooncake_processes(timeout_secs: int = 5) -> None:
def _load_mooncake_config(host: str, rpc_port: int, http_port: int) -> str:
"""Load Mooncake config from YAML and substitute placeholders.
"""Load Mooncake config from CI overlay and substitute placeholders.
Args:
host: Mooncake host address.
@@ -287,16 +288,13 @@ def _load_mooncake_config(host: str, rpc_port: int, http_port: int) -> str:
Returns:
Path to the temporary config file with substituted values.
"""
config_path = str(Path(__file__).parent / "stage_configs" / "bagel_mooncake_ci.yaml")
with open(config_path) as f:
with open(BAGEL_MOONCAKE_CI_DEPLOY) as f:
config_content = f.read()
# Substitute placeholders
config_content = config_content.replace("${MOONCAKE_HOST}", host)
config_content = config_content.replace("${MOONCAKE_RPC_PORT}", str(rpc_port))
config_content = config_content.replace("${MOONCAKE_HTTP_PORT}", str(http_port))
# Write to temp file
temp_file = tempfile.NamedTemporaryFile(mode="w", suffix=".yaml", delete=False)
temp_file.write(config_content)
temp_file.close()
@@ -346,7 +344,7 @@ def test_bagel_text2img_mooncake_connector(run_level):
http_port=MOONCAKE_HTTP_PORT,
)
temp_config_file = _resolve_stage_config(temp_config_file, run_level)
temp_config_file = _resolve_deploy_config(temp_config_file, run_level)
with OmniRunner(
"ByteDance-Seed/BAGEL-7B-MoT",
stage_configs_path=temp_config_file,
@@ -21,17 +21,16 @@ Equivalent to running:
import os
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
from pathlib import Path
import pytest
from vllm.assets.image import ImageAsset
from tests.helpers.mark import hardware_test
from tests.helpers.runtime import OmniRunner
from tests.helpers.stage_config import modify_stage_config
from tests.helpers.stage_config import get_deploy_config_path, modify_stage_config
MODEL_NAME = "ByteDance-Seed/BAGEL-7B-MoT"
STAGE_CONFIG = str(Path(__file__).parent / "stage_configs" / "bagel_sharedmemory_ci.yaml")
STAGE_CONFIG = get_deploy_config_path("ci/bagel.yaml")
REFERENCE_TEXT_TEXT2TEXT = "The capital of France is Paris."
@@ -44,15 +43,15 @@ REFERENCE_TEXT_IMG2TEXT = (
)
def _resolve_stage_config(config_path: str, run_level: str) -> str:
def _resolve_deploy_config(config_path: str, run_level: str) -> str:
"""Strip load_format: dummy for advanced_model (real weights)."""
if run_level == "advanced_model":
return modify_stage_config(
config_path,
deletes={
"stage_args": {
0: ["engine_args.load_format"],
1: ["engine_args.load_format"],
"stages": {
0: ["load_format"],
1: ["load_format"],
}
},
)
@@ -74,7 +73,7 @@ def _extract_text(omni_outputs: list) -> str:
@hardware_test(res={"cuda": "H100", "rocm": "MI325"})
def test_bagel_text2text(run_level):
"""Test Bagel text2text produces correct text output."""
config_path = _resolve_stage_config(STAGE_CONFIG, run_level)
config_path = _resolve_deploy_config(STAGE_CONFIG, run_level)
with OmniRunner(
MODEL_NAME,
stage_configs_path=config_path,
@@ -106,7 +105,7 @@ def test_bagel_text2text(run_level):
def test_bagel_img2text(run_level):
"""Test Bagel img2text produces correct text output."""
input_image = ImageAsset("2560px-Gfp-wisconsin-madison-the-nature-boardwalk").pil_image.convert("RGB")
config_path = _resolve_stage_config(STAGE_CONFIG, run_level)
config_path = _resolve_deploy_config(STAGE_CONFIG, run_level)
with OmniRunner(
MODEL_NAME,
stage_configs_path=config_path,
@@ -16,6 +16,7 @@ import pytest
import torch
from PIL import Image, ImageDraw
from vllm_omni.entrypoints.omni import Omni
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
from vllm_omni.outputs import OmniRequestOutput
from vllm_omni.platforms import current_omni_platform
@@ -24,8 +25,6 @@ REPO_ROOT = Path(__file__).resolve().parents[2]
if str(REPO_ROOT) not in sys.path:
sys.path.insert(0, str(REPO_ROOT))
from vllm_omni import Omni
os.environ["VLLM_TEST_CLEAN_GPU_MEMORY"] = "1"
MODEL = "black-forest-labs/FLUX.2-klein-4B"
@@ -66,6 +65,18 @@ def _extract_images_from_output(outputs: list) -> list[Image.Image]:
return images
# Regression test for https://github.com/vllm-project/vllm-omni/issues/3097
@pytest.mark.core_model
@pytest.mark.diffusion
def test_flux2_klein_can_accept_text_inputs():
model = Omni(model=MODEL)
outputs = model.generate(
"a cup of coffee on the table",
OmniDiffusionSamplingParams(num_inference_steps=2, seed=42),
)
assert len(outputs[0].images) == 1
@pytest.mark.core_model
@pytest.mark.diffusion
def test_flux2_klein_inpaint_basic():
@@ -36,6 +36,21 @@ def build_prompt(user_text: str) -> str:
def get_eager_config():
path = modify_stage_config(
str(Path(__file__).parent.parent / "stage_configs" / "bailingmm_moe_v2_lite_thinker_only_ci.yaml"),
updates={
"stage_args": {
0: {
"engine_args.enforce_eager": "true",
},
},
},
)
return path
def get_eager_tts_config():
"""Thinker+talker CI config with enforce_eager on the thinker stage."""
path = modify_stage_config(
str(Path(__file__).parent.parent / "stage_configs" / "bailingmm_moe_v2_lite_ci.yaml"),
updates={
@@ -49,9 +64,14 @@ def get_eager_config():
return path
# Thinker-only config — used by text-output tests.
stage_configs = [get_eager_config()]
test_params = [(model, stage_config) for model in models for stage_config in stage_configs]
# Thinker+talker config — used by audio-output tests.
stage_configs_tts = [get_eager_tts_config()]
test_params_tts = [(model, stage_config) for model in models for stage_config in stage_configs_tts]
@pytest.mark.core_model
@pytest.mark.omni
@@ -140,3 +160,36 @@ def test_mixed_to_text(omni_runner, omni_runner_handler) -> None:
request_config = {"prompts": prompt, "images": image, "audios": audio, "modalities": ["text"]}
omni_runner_handler.send_request(request_config)
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100"}, num_cards=4)
@pytest.mark.parametrize("omni_runner", test_params_tts, indirect=True)
def test_text_to_audio(omni_runner, omni_runner_handler) -> None:
"""
Test text input with audio output via the thinker+talker pipeline.
Input Modal: text
Output Modal: audio
"""
prompt = build_prompt("请简单介绍一下北京。")
request_config = {"prompts": prompt, "modalities": ["audio"]}
omni_runner_handler.send_request(request_config)
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100"}, num_cards=4)
@pytest.mark.parametrize("omni_runner", test_params_tts, indirect=True)
def test_image_to_audio(omni_runner, omni_runner_handler) -> None:
"""
Test image + text input with audio output via the thinker+talker pipeline.
Input Modal: image + text
Output Modal: audio
"""
image = generate_synthetic_image(224, 224)["np_array"]
prompt = build_prompt(f"{IMAGE_TOKEN}Describe this image briefly.")
request_config = {"prompts": prompt, "images": image, "modalities": ["audio"]}
omni_runner_handler.send_request(request_config)
@@ -38,8 +38,8 @@ def get_dynamic_devices(stage_idx, num_stages, tp_size):
# Test 1: Diffusion Model (2-Stage BAGEL)
@pytest.mark.advanced_model
@pytest.mark.omni
@pytest.mark.parametrize("tp_size", [1, 2])
@hardware_test(res={"cuda": "H100", "rocm": "MI325"}, num_cards=2)
@pytest.mark.parametrize("tp_size", [1])
@hardware_test(res={"cuda": "H100", "rocm": "MI325"}, num_cards=1)
@pytest.mark.asyncio
async def test_diffusion_model_sleep_tp(tp_size):
num_gpus = torch.cuda.device_count()
@@ -123,7 +123,7 @@ async def test_multistage_sleep_h100(tp_size):
pass
acks = await engine.sleep(stage_ids=[0, 1], level=2)
assert len(acks) == 2 * tp_size
assert len(acks) == 2
await engine.wake_up(stage_ids=[0, 1])
async for _ in engine.generate("verify", sampling_params=[SamplingParams(), sp]):
@@ -30,7 +30,6 @@ import os
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
from pathlib import Path
from typing import Any
import pytest
@@ -38,12 +37,15 @@ import torch
from tests.helpers.mark import hardware_test
from tests.helpers.runtime import OmniRunner
from tests.helpers.stage_config import get_deploy_config_path
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
from vllm_omni.outputs import OmniRequestOutput
from vllm_omni.platforms import current_omni_platform
pytestmark = [pytest.mark.core_model, pytest.mark.diffusion]
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
# ─── helpers ──────────────────────────────────────────────────────────────────
@@ -102,7 +104,7 @@ def _generate_bagel_image(
Returns (generated_image, peak_memory_gib).
"""
config_path = str(Path(__file__).parent / "stage_configs" / "bagel_sharedmemory_ci.yaml")
config_path = get_deploy_config_path("ci/bagel.yaml")
omni_kwargs: dict[str, Any] = {
"model": "ByteDance-Seed/BAGEL-7B-MoT",
"stage_configs_path": config_path,
@@ -0,0 +1,170 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""E2E tests for Qwen2.5-Omni AutoRound W4A16 quantized inference.
These tests cover text, audio, image, video, and mixed-modality inputs
to verify multimodal understanding with quantized weights.
Requirements:
- CUDA GPUs (4x L4 / 24 GB or equivalent)
- The quantized model checkpoint (Intel/Qwen2.5-Omni-7B-int4-AutoRound)
"""
import os
import pytest
from tests.helpers.mark import hardware_test
from tests.helpers.media import (
generate_synthetic_audio,
generate_synthetic_image,
generate_synthetic_video,
)
from tests.helpers.stage_config import get_deploy_config_path, modify_stage_config
QUANTIZED_MODEL = "Intel/Qwen2.5-Omni-7B-int4-AutoRound"
BASELINE_MODEL = "Qwen/Qwen2.5-Omni-7B"
# Allow overriding via environment for local testing
QUANTIZED_MODEL = os.environ.get("QWEN2_5_OMNI_AUTOROUND_MODEL", QUANTIZED_MODEL)
BASELINE_MODEL = os.environ.get("QWEN2_5_OMNI_BASELINE_MODEL", BASELINE_MODEL)
_CI_DEPLOY = get_deploy_config_path("ci/qwen2_5_omni.yaml")
def _get_stage_config():
"""Build a CI-friendly stage config with eager mode."""
return modify_stage_config(
_CI_DEPLOY,
updates={
"stages": {
0: {"enforce_eager": True},
1: {"enforce_eager": True},
},
},
)
stage_config = _get_stage_config()
# Parametrise: (model, stage_config)
quant_params = [(QUANTIZED_MODEL, stage_config)]
# ------------------------------------------------------------------
# Test: text-only input → text output
# ------------------------------------------------------------------
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "L4"}, num_cards=4)
@pytest.mark.parametrize("omni_runner", quant_params, indirect=True)
def test_text_to_text(omni_runner, omni_runner_handler):
"""Text input → text output with W4A16 quantized Qwen2.5-Omni."""
request_config = {
"prompts": "What is the capital of China?",
"modalities": ["text"],
}
response = omni_runner_handler.send_request(request_config)
assert response.success, f"Request failed: {response.error_message}"
assert response.text_content and len(response.text_content.strip()) > 0
# ------------------------------------------------------------------
# Test: audio input → text output
# ------------------------------------------------------------------
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "L4"}, num_cards=4)
@pytest.mark.parametrize("omni_runner", quant_params, indirect=True)
def test_audio_to_text(omni_runner, omni_runner_handler):
"""Audio input → text output with W4A16 quantized Qwen2.5-Omni."""
audio = generate_synthetic_audio(1, 1, 16000)["np_array"]
if len(audio.shape) == 2:
audio = audio.squeeze()
request_config = {
"prompts": "What is the content of this audio?",
"audios": (audio, 16000),
"modalities": ["text"],
}
response = omni_runner_handler.send_request(request_config)
assert response.success, f"Request failed: {response.error_message}"
assert response.text_content and len(response.text_content.strip()) > 0
# ------------------------------------------------------------------
# Test: image input → text output
# ------------------------------------------------------------------
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "L4"}, num_cards=4)
@pytest.mark.parametrize("omni_runner", quant_params, indirect=True)
def test_image_to_text(omni_runner, omni_runner_handler):
"""Image input → text output with W4A16 quantized Qwen2.5-Omni."""
image = generate_synthetic_image(16, 16)["np_array"]
request_config = {
"prompts": "Describe what you see in this image.",
"images": image,
"modalities": ["text"],
}
response = omni_runner_handler.send_request(request_config)
assert response.success, f"Request failed: {response.error_message}"
assert response.text_content and len(response.text_content.strip()) > 0
# ------------------------------------------------------------------
# Test: video input → text output
# ------------------------------------------------------------------
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "L4"}, num_cards=4)
@pytest.mark.parametrize("omni_runner", quant_params, indirect=True)
def test_video_to_text(omni_runner, omni_runner_handler):
"""Video input → text output with W4A16 quantized Qwen2.5-Omni."""
video = generate_synthetic_video(16, 16, 30)["np_array"]
request_config = {
"prompts": "Describe the video briefly.",
"videos": video,
"modalities": ["text"],
}
response = omni_runner_handler.send_request(request_config)
assert response.success, f"Request failed: {response.error_message}"
assert response.text_content and len(response.text_content.strip()) > 0
# ------------------------------------------------------------------
# Test: mixed modality (audio + image + video) → audio output
# ------------------------------------------------------------------
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "L4"}, num_cards=4)
@pytest.mark.parametrize("omni_runner", quant_params, indirect=True)
def test_mix_to_audio(omni_runner, omni_runner_handler):
"""Mixed-modality input → audio output with W4A16 quantized Qwen2.5-Omni."""
video = generate_synthetic_video(16, 16, 30)["np_array"]
image = generate_synthetic_image(16, 16)["np_array"]
audio = generate_synthetic_audio(1, 1, 16000)["np_array"]
if len(audio.shape) == 2:
audio = audio.squeeze()
request_config = {
"prompts": "What is recited in the audio? What is in this image? Describe the video briefly.",
"videos": video,
"images": image,
"audios": (audio, 16000),
"modalities": ["audio"],
}
response = omni_runner_handler.send_request(request_config)
assert response.success, f"Request failed: {response.error_message}"
@@ -0,0 +1,205 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""E2E tests for Qwen3-Omni AutoRound W4A16 quantized inference.
These tests cover text, audio, image, video, and mixed-modality inputs
to verify multimodal understanding with quantized weights.
Requirements:
- CUDA GPUs (2x H100-80G or equivalent)
- The quantized model checkpoint (Intel/Qwen3-Omni-30B-A3B-Instruct-int4-AutoRound)
"""
import os
import pytest
from tests.helpers.mark import hardware_test
from tests.helpers.media import (
generate_synthetic_audio,
generate_synthetic_image,
generate_synthetic_video,
)
from tests.helpers.stage_config import get_deploy_config_path, modify_stage_config
QUANTIZED_MODEL = "Intel/Qwen3-Omni-30B-A3B-Instruct-int4-AutoRound"
BASELINE_MODEL = "Qwen/Qwen3-Omni-30B-A3B-Instruct"
# Allow overriding via environment for local testing
QUANTIZED_MODEL = os.environ.get("QWEN3_OMNI_AUTOROUND_MODEL", QUANTIZED_MODEL)
BASELINE_MODEL = os.environ.get("QWEN3_OMNI_BASELINE_MODEL", BASELINE_MODEL)
_CI_DEPLOY = get_deploy_config_path("ci/qwen3_omni_moe.yaml")
@pytest.fixture(scope="module", autouse=True)
def _qwen3_omni_env():
"""Set env vars required by multi-stage worker spawning.
Must run before CUDA context init. Reverted after every test module
so that values do not leak into unrelated test files.
"""
with pytest.MonkeyPatch.context() as mp:
mp.setenv("VLLM_WORKER_MULTIPROC_METHOD", "spawn")
mp.setenv("VLLM_TEST_CLEAN_GPU_MEMORY", "0")
yield
def _get_stage_config():
"""Build a CI-friendly stage config with eager mode."""
return modify_stage_config(
_CI_DEPLOY,
updates={
"stages": {
0: {"enforce_eager": True},
1: {"enforce_eager": True},
},
},
)
stage_config = _get_stage_config()
# Parametrise: (model, stage_config)
quant_params = [(QUANTIZED_MODEL, stage_config)]
# ------------------------------------------------------------------
# Test: text-only input → text output
# ------------------------------------------------------------------
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100"}, num_cards=2)
@pytest.mark.parametrize("omni_runner", quant_params, indirect=True)
def test_text_to_text(omni_runner, omni_runner_handler):
"""Text input → text output with W4A16 quantized Qwen3-Omni."""
request_config = {
"prompts": "What is the capital of France?",
"modalities": ["text"],
}
response = omni_runner_handler.send_request(request_config)
assert response.success, f"Request failed: {response.error_message}"
assert response.text_content and len(response.text_content.strip()) > 0
# ------------------------------------------------------------------
# Test: audio input → text output
# ------------------------------------------------------------------
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100"}, num_cards=2)
@pytest.mark.parametrize("omni_runner", quant_params, indirect=True)
def test_audio_to_text(omni_runner, omni_runner_handler):
"""Audio input → text output with W4A16 quantized Qwen3-Omni."""
audio = generate_synthetic_audio(1, 1, 16000)["np_array"]
if len(audio.shape) == 2:
audio = audio.squeeze()
request_config = {
"prompts": "What is the content of this audio?",
"audios": (audio, 16000),
"modalities": ["text"],
}
response = omni_runner_handler.send_request(request_config)
assert response.success, f"Request failed: {response.error_message}"
assert response.text_content and len(response.text_content.strip()) > 0
# ------------------------------------------------------------------
# Test: image input → text output
# ------------------------------------------------------------------
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100"}, num_cards=2)
@pytest.mark.parametrize("omni_runner", quant_params, indirect=True)
def test_image_to_text(omni_runner, omni_runner_handler):
"""Image input → text output with W4A16 quantized Qwen3-Omni."""
image = generate_synthetic_image(16, 16)["np_array"]
request_config = {
"prompts": "Describe what you see in this image.",
"images": image,
"modalities": ["text"],
}
response = omni_runner_handler.send_request(request_config)
assert response.success, f"Request failed: {response.error_message}"
assert response.text_content and len(response.text_content.strip()) > 0
# ------------------------------------------------------------------
# Test: video input → text output
# ------------------------------------------------------------------
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100"}, num_cards=2)
@pytest.mark.parametrize("omni_runner", quant_params, indirect=True)
def test_video_to_text(omni_runner, omni_runner_handler):
"""Video input → text output with W4A16 quantized Qwen3-Omni."""
video = generate_synthetic_video(224, 224, 300)["np_array"]
request_config = {
"prompts": "Describe the video briefly.",
"videos": video,
"modalities": ["text"],
}
response = omni_runner_handler.send_request(request_config)
assert response.success, f"Request failed: {response.error_message}"
assert response.text_content and len(response.text_content.strip()) > 0
# ------------------------------------------------------------------
# Test: video input → audio output
# ------------------------------------------------------------------
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100"}, num_cards=2)
@pytest.mark.parametrize("omni_runner", quant_params, indirect=True)
def test_video_to_audio(omni_runner, omni_runner_handler):
"""Video input → audio output with W4A16 quantized Qwen3-Omni."""
video = generate_synthetic_video(224, 224, 300)["np_array"]
request_config = {
"prompts": "Describe the video briefly.",
"videos": video,
"modalities": ["audio"],
}
response = omni_runner_handler.send_request(request_config)
assert response.success, f"Request failed: {response.error_message}"
# ------------------------------------------------------------------
# Test: mixed modality (audio + image + video) → audio output
# ------------------------------------------------------------------
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100"}, num_cards=2)
@pytest.mark.parametrize("omni_runner", quant_params, indirect=True)
def test_mix_to_audio(omni_runner, omni_runner_handler):
"""Mixed-modality input → audio output with W4A16 quantized Qwen3-Omni."""
video = generate_synthetic_video(224, 224, 300)["np_array"]
image = generate_synthetic_image(16, 16)["np_array"]
audio = generate_synthetic_audio(1, 1, 16000)["np_array"]
if len(audio.shape) == 2:
audio = audio.squeeze()
request_config = {
"prompts": "What is recited in the audio? What is in this image? Describe the video briefly.",
"videos": video,
"images": image,
"audios": (audio, 16000),
"modalities": ["audio"],
}
response = omni_runner_handler.send_request(request_config)
assert response.success, f"Request failed: {response.error_message}"
@@ -22,6 +22,8 @@ from vllm_omni.inputs.data import OmniDiffusionSamplingParams
from vllm_omni.outputs import OmniRequestOutput
from vllm_omni.platforms import current_omni_platform
pytestmark = [pytest.mark.full_model, pytest.mark.diffusion]
_SAMPLE_RATE = 44100
_CLIP_DURATION_S = 2.0
@@ -72,8 +74,6 @@ def generate_stable_audio_short_clip(
return audio
@pytest.mark.advanced_model
@pytest.mark.diffusion
@pytest.mark.cache
@hardware_test(res={"cuda": "L4", "xpu": "B60"})
def test_stable_audio_quantization_and_teacache() -> None:
@@ -19,6 +19,8 @@ import pytest
from tests.helpers.mark import hardware_marks
from tests.helpers.runtime import OmniServer, OmniServerParams, OpenAIClientHandler, dummy_messages_from_mix_data
pytestmark = [pytest.mark.diffusion, pytest.mark.full_model]
PROMPT = "A futuristic city skyline at twilight, cyberpunk style, ultra-detailed, high resolution."
NEGATIVE_PROMPT = "low quality, blurry, distorted, deformed, watermark"
@@ -112,8 +114,6 @@ def _get_diffusion_feature_cases(model: str):
]
@pytest.mark.advanced_model
@pytest.mark.diffusion
@pytest.mark.parametrize(
"omni_server",
_get_diffusion_feature_cases("ByteDance-Seed/BAGEL-7B-MoT"),
@@ -23,21 +23,19 @@ Equivalent to running:
import base64
import os
from io import BytesIO
from pathlib import Path
import pytest
from vllm.assets.image import ImageAsset
from tests.helpers.mark import hardware_test
from tests.helpers.runtime import OmniServerParams
from tests.helpers.stage_config import get_deploy_config_path
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
os.environ["VLLM_TEST_CLEAN_GPU_MEMORY"] = "0"
MODEL = "ByteDance-Seed/BAGEL-7B-MoT"
STAGE_CONFIGS_PATH = str(
Path(__file__).parent.parent / "offline_inference" / "stage_configs" / "bagel_sharedmemory_ci.yaml"
)
STAGE_CONFIGS_PATH = get_deploy_config_path("ci/bagel.yaml")
TEXT2IMG_PROMPT = "A cute cat"
IMG2IMG_PROMPT = "Change the grass color to red"
@@ -0,0 +1,56 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""End-to-end tests for DiffusersAdapterPipeline.
It tests the full user flow of launching a diffusers-backed model and running inference.
"""
import pytest
from PIL import Image
from tests.helpers.mark import hardware_test
from tests.helpers.runtime import OmniServer, OmniServerParams, OpenAIClientHandler, dummy_messages_from_mix_data
pytestmark = [pytest.mark.diffusion, pytest.mark.core_model]
@pytest.mark.parametrize(
"omni_server",
[
OmniServerParams(
model="tiny-random/Qwen-Image",
server_args=[
"--diffusion-load-format",
"diffusers",
"--diffusers-call-kwargs",
'{"height": 512, "width": 0}', # deliberately weird width to be overridden
],
),
],
indirect=True,
)
@hardware_test(res={"cuda": "L4"}, num_cards=1)
def test_t2i_with_diffusers_adapter(
omni_server: OmniServer,
openai_client: OpenAIClientHandler,
):
messages = dummy_messages_from_mix_data(content_text="a photo of an astronaut riding a horse on mars")
request_config = {
"model": omni_server.model,
"messages": messages,
"extra_body": {
"width": 512,
"num_inference_steps": 2,
"negative_prompt": "blurry",
"true_cfg_scale": 4.0,
"seed": 42,
},
}
response = openai_client.send_diffusion_request(request_config)
image: Image.Image = response[0].images[0] # pyright: ignore[reportOptionalSubscript]
# Request config has incomplete width/height, so internal assertion in `send_diffusion_request` is incomplete.
assert image.size == (512, 512)
@@ -5,29 +5,26 @@ Example online tests for Dynin-Omni model.
"""
import base64
import gc
import os
from io import BytesIO
from pathlib import Path
import numpy as np
import pytest
import soundfile as sf
from vllm.assets.image import ImageAsset
from tests.helpers.mark import hardware_test
from tests.helpers.media import convert_audio_bytes_to_text
from tests.helpers.runtime import OmniServerParams
pytestmark = [pytest.mark.full_model, pytest.mark.omni]
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
os.environ["VLLM_TEST_CLEAN_GPU_MEMORY"] = "0"
MODEL = "snu-aidas/Dynin-Omni"
STAGE_CONFIG = str(Path(__file__).parent.parent / "stage_configs" / "dynin_omni_ci.yaml")
_WHISPER_SAMPLE_RATE_HZ = 16_000
T2I_PROMPT = "A high quality detailed living room interior photo."
T2S_PROMPT = "Please read this sentence naturally: Hello from Dynin-Omni online serving."
T2S_PROMPT = "Please read this sentence naturally: Hello from online serving."
I2I_PROMPT = "Transform this outdoor nature boardwalk scene into a painting style with vivid colors."
TEST_PARAMS = [OmniServerParams(model=MODEL, stage_config_path=STAGE_CONFIG, stage_init_timeout=600)]
@@ -35,65 +32,6 @@ _STAGE_COUNT = 3
_I2I_STAGE_SAMPLING = {"max_tokens": 1, "temperature": 0.0, "top_p": 1.0, "detokenize": False}
def _prepare_audio_waveform_for_whisper(audio_data: np.ndarray, samplerate: int) -> np.ndarray:
"""Normalize decoded audio into a mono 16 kHz float32 waveform for Whisper."""
if samplerate <= 0:
raise ValueError(f"Invalid audio sample rate: {samplerate}")
waveform = np.asarray(audio_data, dtype=np.float32)
if waveform.ndim == 0:
raise ValueError("Audio waveform must have at least one dimension")
if waveform.ndim > 1:
waveform = np.mean(waveform, axis=1)
if waveform.size == 0:
raise ValueError("Empty audio waveform")
if samplerate != _WHISPER_SAMPLE_RATE_HZ:
target_num_samples = max(int(round(waveform.shape[0] * _WHISPER_SAMPLE_RATE_HZ / samplerate)), 1)
source_positions = np.arange(waveform.shape[0], dtype=np.float64)
target_positions = np.linspace(
0.0,
max(waveform.shape[0] - 1, 0),
num=target_num_samples,
dtype=np.float64,
)
waveform = np.interp(target_positions, source_positions, waveform).astype(np.float32)
return np.ascontiguousarray(np.clip(waveform, -1.0, 1.0), dtype=np.float32)
def _convert_audio_bytes_to_text_without_ffmpeg(raw_bytes: bytes) -> str:
"""Dynin t2s keeps Whisper transcription local to this test module and avoids ffmpeg."""
import whisper
data, samplerate = sf.read(BytesIO(raw_bytes), dtype="float32", always_2d=True)
audio_waveform = _prepare_audio_waveform_for_whisper(data, samplerate)
model = whisper.load_model("small", device="cpu")
try:
transcript = model.transcribe(
audio_waveform,
temperature=0.0,
word_timestamps=True,
condition_on_previous_text=False,
)["text"]
finally:
del model
gc.collect()
return transcript or ""
@pytest.fixture
def dynin_t2s_openai_client(openai_client, monkeypatch):
monkeypatch.setattr(
convert_audio_bytes_to_text,
"convert_audio_bytes_to_text",
_convert_audio_bytes_to_text_without_ffmpeg,
)
return openai_client
def _build_t2i_messages(prompt: str) -> list[dict]:
return [{"role": "user", "content": [{"type": "text", "text": f"<|t2i|> {prompt}"}]}]
@@ -118,8 +56,6 @@ def _build_i2i_messages(prompt: str) -> list[dict]:
]
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100", "rocm": "MI325"})
@pytest.mark.parametrize("omni_server", TEST_PARAMS, indirect=True)
def test_send_i2i_request_001(omni_server, openai_client) -> None:
@@ -134,8 +70,6 @@ def test_send_i2i_request_001(omni_server, openai_client) -> None:
openai_client.send_diffusion_request(request_config)
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100", "rocm": "MI325"})
@pytest.mark.parametrize("omni_server", TEST_PARAMS, indirect=True)
def test_send_t2i_request_001(omni_server, openai_client) -> None:
@@ -147,14 +81,13 @@ def test_send_t2i_request_001(omni_server, openai_client) -> None:
openai_client.send_diffusion_request(request_config)
@pytest.mark.core_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100", "rocm": "MI325"})
@pytest.mark.parametrize("omni_server", TEST_PARAMS, indirect=True)
def test_send_t2s_request_001(omni_server, dynin_t2s_openai_client) -> None:
def test_send_t2s_request_001(omni_server, openai_client) -> None:
request_config = {
"model": omni_server.model,
"messages": _build_t2s_messages(T2S_PROMPT),
"modalities": ["audio"],
"audio_ref_text": T2S_PROMPT,
}
dynin_t2s_openai_client.send_omni_request(request_config)
openai_client.send_omni_request(request_config)
@@ -14,6 +14,8 @@ import pytest
from tests.helpers.mark import hardware_marks
from tests.helpers.runtime import OmniServer, OmniServerParams, OpenAIClientHandler
pytestmark = [pytest.mark.diffusion, pytest.mark.full_model]
FOUR_CARD_FEATURE_MARKS = hardware_marks(res={"cuda": "L4"}, num_cards=4)
POSITIVE_PROMPT = "A cat sitting on a windowsill"
NEGATIVE_PROMPT = "blurry, low quality"
@@ -86,8 +88,6 @@ def _get_diffusion_feature_cases(model: str):
]
@pytest.mark.advanced_model
@pytest.mark.diffusion
@pytest.mark.parametrize(
"omni_server",
_get_diffusion_feature_cases(
@@ -16,6 +16,8 @@ from PIL import Image, ImageDraw
from tests.helpers.runtime import OmniServer, OmniServerParams
pytestmark = [pytest.mark.full_model, pytest.mark.diffusion]
MODEL = "black-forest-labs/FLUX.2-klein-4B"
_HEIGHT = 512
@@ -66,8 +68,6 @@ def _send_edit_request(host: str, port: int, model: str, image_b64: str, mask_b6
return response.json()
@pytest.mark.advanced_model
@pytest.mark.diffusion
@pytest.mark.parametrize("omni_server", _get_diffusion_feature_cases(MODEL), indirect=True)
def test_flux2_klein_inpaint_basic(omni_server: OmniServer):
input_image_b64 = _image_to_base64_jpeg(Image.new("RGB", (_WIDTH, _HEIGHT), (128, 128, 128)))
@@ -92,8 +92,6 @@ def test_flux2_klein_inpaint_basic(omni_server: OmniServer):
assert img.size == (_WIDTH, _HEIGHT)
@pytest.mark.advanced_model
@pytest.mark.diffusion
@pytest.mark.parametrize("omni_server", _get_diffusion_feature_cases(MODEL), indirect=True)
def test_flux2_klein_inpaint_deterministic(omni_server: OmniServer):
input_image_b64 = _image_to_base64_jpeg(Image.new("RGB", (_WIDTH, _HEIGHT), (128, 128, 128)))
@@ -137,8 +135,6 @@ def test_flux2_klein_inpaint_deterministic(omni_server: OmniServer):
)
@pytest.mark.advanced_model
@pytest.mark.diffusion
@pytest.mark.parametrize("omni_server", _get_diffusion_feature_cases(MODEL), indirect=True)
def test_flux2_klein_inpaint_multiple_outputs(omni_server: OmniServer):
input_image_b64 = _image_to_base64_jpeg(Image.new("RGB", (_WIDTH, _HEIGHT), (128, 128, 128)))
@@ -17,6 +17,8 @@ import pytest
from tests.helpers.mark import hardware_marks
from tests.helpers.runtime import OmniServer, OmniServerParams, OpenAIClientHandler, dummy_messages_from_mix_data
pytestmark = [pytest.mark.diffusion, pytest.mark.full_model]
MODEL = "black-forest-labs/FLUX.2-dev"
PROMPT = "A cinematic mountain landscape at sunrise, dramatic clouds, ultra-detailed, realistic photography."
NEGATIVE_PROMPT = "low quality, blurry, distorted, deformed, watermark"
@@ -54,8 +56,6 @@ def _get_flux_2_dev_feature_cases(model: str):
]
@pytest.mark.advanced_model
@pytest.mark.diffusion
@pytest.mark.parametrize(
"omni_server",
_get_flux_2_dev_feature_cases(MODEL),
@@ -8,6 +8,8 @@ import pytest
from tests.helpers.media import generate_synthetic_image
from tests.helpers.runtime import OmniServer, OmniServerParams, OpenAIClientHandler, dummy_messages_from_mix_data
pytestmark = [pytest.mark.diffusion, pytest.mark.full_model]
EDIT_PROMPT = "Transform this modern, geometrist image into a Vincent van Gogh style impressionist painting."
NEGATIVE_PROMPT = "blurry, low quality, modern, geometrist"
MODEL = "black-forest-labs/FLUX.1-Kontext-dev"
@@ -29,8 +31,6 @@ def _get_diffusion_feature_cases(model: str):
]
@pytest.mark.advanced_model
@pytest.mark.diffusion
@pytest.mark.parametrize(
"omni_server",
_get_diffusion_feature_cases(MODEL),
@@ -54,8 +54,6 @@ def test_flux_kontext_text_to_image(omni_server: OmniServer, openai_client: Open
openai_client.send_diffusion_request(request_config)
@pytest.mark.advanced_model
@pytest.mark.diffusion
@pytest.mark.parametrize(
"omni_server",
_get_diffusion_feature_cases(MODEL),
@@ -83,8 +81,6 @@ def test_flux_kontext_image_edit(omni_server: OmniServer, openai_client: OpenAIC
openai_client.send_diffusion_request(request_config)
@pytest.mark.advanced_model
@pytest.mark.diffusion
@pytest.mark.parametrize(
"omni_server",
_get_diffusion_feature_cases(MODEL),
@@ -110,8 +106,6 @@ def test_flux_kontext_image_edit_no_negative(omni_server: OmniServer, openai_cli
openai_client.send_diffusion_request(request_config)
@pytest.mark.advanced_model
@pytest.mark.diffusion
@pytest.mark.parametrize(
"omni_server",
_get_diffusion_feature_cases(MODEL),
@@ -135,8 +129,6 @@ def test_flux_kontext_high_resolution(omni_server: OmniServer, openai_client: Op
openai_client.send_diffusion_request(request_config)
@pytest.mark.advanced_model
@pytest.mark.diffusion
@pytest.mark.parametrize(
"omni_server",
_get_diffusion_feature_cases(MODEL),
@@ -14,6 +14,8 @@ import pytest
from tests.helpers.mark import hardware_marks
from tests.helpers.runtime import OmniServer, OmniServerParams, OpenAIClientHandler
pytestmark = [pytest.mark.diffusion, pytest.mark.full_model]
PROMPT = "A cat walking across a sunlit garden, cinematic lighting, slow motion."
NEGATIVE_PROMPT = "low quality, blurry, distorted"
@@ -62,8 +64,6 @@ def _get_diffusion_feature_cases(model: str):
]
@pytest.mark.advanced_model
@pytest.mark.diffusion
@pytest.mark.parametrize(
"omni_server",
_get_diffusion_feature_cases(MODEL),
@@ -17,6 +17,8 @@ from tests.helpers.mark import hardware_marks
from tests.helpers.media import generate_synthetic_image
from tests.helpers.runtime import OmniServer, OmniServerParams, OpenAIClientHandler, dummy_messages_from_mix_data
pytestmark = [pytest.mark.diffusion, pytest.mark.full_model]
EDIT_PROMPT = "Transform this modern image into a cinematic animation style with vibrant colors and soft lighting."
NEGATIVE_PROMPT = "blurry, low quality, distorted, oversaturated"
SINGLE_CARD_FEATURE_MARKS = hardware_marks(res={"cuda": "H100"})
@@ -50,8 +52,6 @@ def _get_diffusion_feature_cases(model: str):
]
@pytest.mark.advanced_model
@pytest.mark.diffusion
@pytest.mark.parametrize(
"omni_server",
_get_diffusion_feature_cases("meituan-longcat/LongCat-Image-Edit"),
@@ -16,6 +16,8 @@ import pytest
from tests.helpers.mark import hardware_marks
from tests.helpers.runtime import OmniServer, OmniServerParams, OpenAIClientHandler, dummy_messages_from_mix_data
pytestmark = [pytest.mark.diffusion, pytest.mark.full_model]
TEXT_TO_IMAGE_PROMPT = (
"A cinematic illustration of a cat typing on a silver laptop, soft window light, highly detailed."
)
@@ -51,8 +53,6 @@ def _get_diffusion_feature_cases(model: str):
]
@pytest.mark.advanced_model
@pytest.mark.diffusion
@pytest.mark.parametrize(
"omni_server",
_get_diffusion_feature_cases("meituan-longcat/LongCat-Image"),
@@ -14,6 +14,8 @@ from tests.helpers.runtime import (
dummy_messages_from_mix_data,
)
pytestmark = [pytest.mark.full_model, pytest.mark.diffusion]
# L4: 4 GPUs + TP=4; XPU B60: 2 cards (use num_cards={"cuda": 4, "xpu": 4} if needed)
FOUR_CARD_MARKS = hardware_marks(
res={"cuda": "L4", "xpu": "B60"},
@@ -45,8 +47,6 @@ def _get_diffusion_feature_cases(model: str):
]
@pytest.mark.advanced_model
@pytest.mark.diffusion
@pytest.mark.parametrize(
"omni_server",
_get_diffusion_feature_cases(model=os.environ.get("VLLM_TEST_NEXTSTEP_MODEL", _DEFAULT_MODEL)),
+11 -8
View File
@@ -180,14 +180,19 @@ def test_text_to_text_001(omni_server, openai_client) -> None:
@pytest.mark.omni
@hardware_test(res={"cuda": "H100", "rocm": "MI325"}, num_cards=2)
@pytest.mark.parametrize("omni_server", prefix_test_params, indirect=True)
@pytest.mark.skip(reason="issue: #2833")
def test_thinker_prefix_caching(omni_server, openai_client) -> None:
"""
Test thinker prefix caching by sending identical requests with an image (i.e.,
a large shared prefix) and verifying that the second request uses cached tokens
& produces the same output.
& produces the same output with greedy decoding.
NOTE: The seed for this test is used as a regression test for the issue linked below;
https://github.com/vllm-project/vllm-omni/issues/2833; without passing the sampling
params, this test will fail with the current default stage configs.
"""
image_data_url = f"data:image/jpeg;base64,{generate_synthetic_image(224, 224)['base64']}"
seed = 10
img_res = generate_synthetic_image(224, 224, seed=seed)
image_data_url = f"data:image/jpeg;base64,{img_res['base64']}"
messages = dummy_messages_from_mix_data(
system_prompt=get_system_prompt(),
image_data_url=image_data_url,
@@ -199,16 +204,14 @@ def test_thinker_prefix_caching(omni_server, openai_client) -> None:
"messages": messages,
"stream": False,
"modalities": ["text"],
"sampling_params_list": [{"seed": seed, "temperature": 0, "max_tokens": 16}] * 3,
}
response_1 = openai_client.send_omni_request(request_config, request_num=1)[0]
response_2 = openai_client.send_omni_request(request_config, request_num=1)[0]
assert response_1.success
assert response_2.success
assert response_2.cached_tokens is not None
# We should cache the vast majority of the prompt (image + up to last full block),
# and set seed in the CI config, so the second request should give an identical
# and set seed + temperature, so the second request should give an identical
# response for the generated input image, even if we use dummy weights
assert response_2.cached_tokens > 0
assert response_2.cached_tokens is not None and response_2.cached_tokens > 0
assert response_1.text_content == response_2.text_content
@@ -6,8 +6,6 @@ E2E Online tests for Qwen3-Omni model.
import os
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
import pytest
from tests.helpers.mark import hardware_test
@@ -15,6 +13,10 @@ from tests.helpers.media import generate_synthetic_audio, generate_synthetic_ima
from tests.helpers.runtime import OmniServerParams, dummy_messages_from_mix_data
from tests.helpers.stage_config import get_deploy_config_path, modify_stage_config
pytestmark = [pytest.mark.full_model, pytest.mark.omni]
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
model = "Qwen/Qwen3-Omni-30B-A3B-Instruct"
AUDIO_KEY = ["test"]
@@ -82,6 +84,7 @@ test_params = [
model=model,
stage_config_path=get_async_chunk_config(default_path),
use_stage_cli=True,
server_args=["--async-chunk"],
),
id="async_chunk",
),
@@ -130,8 +133,6 @@ def get_max_batch_size(size_type="few"):
return batch_sizes.get(size_type, 5)
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100", "rocm": "MI325"}, num_cards=2)
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
def test_text_to_audio_001(omni_server, openai_client) -> None:
@@ -154,8 +155,6 @@ def test_text_to_audio_001(omni_server, openai_client) -> None:
openai_client.send_omni_request(request_config)
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100", "rocm": "MI325"}, num_cards=2)
@pytest.mark.parametrize("omni_server", test_params + test_token_params, indirect=True)
def test_text_to_text_audio_001(omni_server, openai_client) -> None:
@@ -176,8 +175,6 @@ def test_text_to_text_audio_001(omni_server, openai_client) -> None:
openai_client.send_omni_request(request_config, request_num=get_max_batch_size())
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100", "rocm": "MI325"}, num_cards=2)
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
def test_text_video_to_text_001(omni_server, openai_client) -> None:
@@ -202,8 +199,6 @@ def test_text_video_to_text_001(omni_server, openai_client) -> None:
openai_client.send_omni_request(request_config, request_num=get_max_batch_size())
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100", "rocm": "MI325"}, num_cards=2)
@pytest.mark.parametrize("omni_server", test_params + test_token_params, indirect=True)
def test_text_audio_to_text_audio_001(omni_server, openai_client) -> None:
@@ -227,8 +222,6 @@ def test_text_audio_to_text_audio_001(omni_server, openai_client) -> None:
openai_client.send_omni_request(request_config)
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100", "rocm": "MI325"}, num_cards=2)
@pytest.mark.parametrize("omni_server", test_params + test_token_params, indirect=True)
def test_text_audio_to_text_audio_002(omni_server, openai_client) -> None:
@@ -254,8 +247,6 @@ def test_text_audio_to_text_audio_002(omni_server, openai_client) -> None:
openai_client.send_omni_request(request_config, request_num=get_max_batch_size())
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100", "rocm": "MI325"}, num_cards=2)
@pytest.mark.parametrize("omni_server", test_params + test_token_params, indirect=True)
def test_text_image_to_text_audio_001(omni_server, openai_client) -> None:
@@ -280,8 +271,6 @@ def test_text_image_to_text_audio_001(omni_server, openai_client) -> None:
openai_client.send_omni_request(request_config)
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100", "rocm": "MI325"}, num_cards=2)
@pytest.mark.parametrize("omni_server", test_params + test_token_params, indirect=True)
def test_large_image_to_text_audio_001(omni_server, openai_client) -> None:
@@ -310,8 +299,6 @@ def test_large_image_to_text_audio_001(omni_server, openai_client) -> None:
openai_client.send_omni_request(request_config, request_num=get_max_batch_size())
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100", "rocm": "MI325"}, num_cards=2)
@pytest.mark.parametrize("omni_server", test_params + test_token_params, indirect=True)
def test_text_video_to_text_audio_001(omni_server, openai_client) -> None:
@@ -338,8 +325,6 @@ def test_text_video_to_text_audio_001(omni_server, openai_client) -> None:
@pytest.mark.skip(reason="There is a known issue with shape mismatch error.")
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100", "rocm": "MI325"}, num_cards=2)
@pytest.mark.parametrize("omni_server", test_params + test_token_params, indirect=True)
def test_mix_to_text_audio_001(omni_server, openai_client) -> None:
@@ -369,8 +354,6 @@ def test_mix_to_text_audio_001(omni_server, openai_client) -> None:
openai_client.send_omni_request(request_config, request_num=get_max_batch_size())
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100", "rocm": "MI325"}, num_cards=2)
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
@pytest.mark.skip(reason="issue: #2827")
@@ -398,8 +381,6 @@ def test_audio_in_video_001(omni_server, openai_client) -> None:
openai_client.send_omni_request(request_config)
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100", "rocm": "MI325"}, num_cards=2)
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
def test_audio_in_video_002(omni_server, openai_client) -> None:
@@ -427,8 +408,6 @@ def test_audio_in_video_002(omni_server, openai_client) -> None:
openai_client.send_omni_request(request_config, request_num=get_max_batch_size())
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100", "rocm": "MI325"}, num_cards=2)
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
def test_one_word_prompt_001(omni_server, openai_client) -> None:
@@ -463,8 +442,6 @@ def test_one_word_prompt_001(omni_server, openai_client) -> None:
print(f"Similarity assertion failed, retrying {attempt + 2}/{_max_retries}: {e!r}")
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100", "rocm": "MI325"}, num_cards=2)
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
def test_speaker_001(omni_server, openai_client) -> None:
@@ -490,8 +467,6 @@ def test_speaker_001(omni_server, openai_client) -> None:
openai_client.send_omni_request(request_config)
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100", "rocm": "MI325"}, num_cards=2)
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
@pytest.mark.skip(reason="Known issue: occasional inaccuracy in voice recognition.")
@@ -528,8 +503,6 @@ def test_speaker_002(omni_server, openai_client) -> None:
print(f"Gender assertion failed, retrying {attempt + 2}/{_max_retries}: {e!r}")
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100", "rocm": "MI325"}, num_cards=2)
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
def test_speaker_003(omni_server, openai_client) -> None:
@@ -555,8 +528,6 @@ def test_speaker_003(omni_server, openai_client) -> None:
openai_client.send_omni_request(request_config)
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100", "rocm": "MI325"}, num_cards=2)
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
def test_language_001(omni_server, openai_client) -> None:
@@ -9,15 +9,17 @@ actual model inference, not mocks.
import os
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
os.environ["VLLM_TEST_CLEAN_GPU_MEMORY"] = "0"
import pytest
from tests.helpers.mark import hardware_test
from tests.helpers.runtime import OmniServerParams
from tests.helpers.stage_config import get_deploy_config_path
pytestmark = [pytest.mark.full_model, pytest.mark.omni]
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
os.environ["VLLM_TEST_CLEAN_GPU_MEMORY"] = "0"
MODEL = "Qwen/Qwen3-TTS-12Hz-0.6B-Base"
REF_AUDIO_URL = "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen3-TTS-Repo/clone_2.wav"
@@ -61,9 +63,6 @@ tts_server_params = [
]
@pytest.mark.advanced_model
@pytest.mark.core_model
@pytest.mark.omni
@hardware_test(res={"cuda": "L4"}, num_cards=1)
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
def test_voice_clone_streaming_001(omni_server, openai_client) -> None:
@@ -89,9 +88,6 @@ def test_voice_clone_streaming_001(omni_server, openai_client) -> None:
openai_client.send_audio_speech_request(request_config, request_num=get_max_batch_size("few"))
@pytest.mark.advanced_model
@pytest.mark.core_model
@pytest.mark.omni
@hardware_test(res={"cuda": "L4"}, num_cards=1)
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
def test_response_format_001(omni_server, openai_client) -> None:
@@ -9,15 +9,17 @@ actual model inference, not mocks.
import os
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
os.environ["VLLM_TEST_CLEAN_GPU_MEMORY"] = "0"
import pytest
from tests.helpers.mark import hardware_test
from tests.helpers.runtime import OmniServerParams
from tests.helpers.stage_config import get_deploy_config_path
pytestmark = [pytest.mark.full_model, pytest.mark.omni]
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
os.environ["VLLM_TEST_CLEAN_GPU_MEMORY"] = "0"
MODEL = "Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice"
@@ -59,8 +61,6 @@ tts_server_params = [
]
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "L4"}, num_cards=1)
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
def test_voice_001(omni_server, openai_client) -> None:
@@ -92,8 +92,6 @@ def test_voice_001(omni_server, openai_client) -> None:
raise
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "L4"}, num_cards=1)
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
def test_voice_002(omni_server, openai_client) -> None:
@@ -117,8 +115,6 @@ def test_voice_002(omni_server, openai_client) -> None:
openai_client.send_audio_speech_request(request_config)
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "L4"}, num_cards=1)
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
def test_voice_003(omni_server, openai_client) -> None:
@@ -142,8 +138,6 @@ def test_voice_003(omni_server, openai_client) -> None:
openai_client.send_audio_speech_request(request_config)
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "L4"}, num_cards=1)
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
def test_language_001(omni_server, openai_client) -> None:
@@ -11,6 +11,8 @@ from tests.helpers.mark import hardware_marks
from tests.helpers.media import generate_synthetic_image
from tests.helpers.runtime import OmniServer, OmniServerParams, OpenAIClientHandler, dummy_messages_from_mix_data
pytestmark = [pytest.mark.diffusion, pytest.mark.full_model]
EDIT_PROMPT = "Transform this modern, geometrist image into a Vincent van Gogh style impressionist painting."
MULTI_EDIT_PROMPT = (
"Transform the first image into a Dadaism collage art. "
@@ -108,8 +110,6 @@ def _get_diffusion_feature_cases(model: str):
]
@pytest.mark.advanced_model
@pytest.mark.diffusion
@pytest.mark.parametrize(
"omni_server",
_get_diffusion_feature_cases("Qwen/Qwen-Image-Edit"),
@@ -138,8 +138,6 @@ def test_qwen_image_edit(omni_server: OmniServer, openai_client: OpenAIClientHan
openai_client.send_diffusion_request(request_config)
@pytest.mark.advanced_model
@pytest.mark.diffusion
@pytest.mark.parametrize(
"omni_server",
_get_diffusion_feature_cases("Qwen/Qwen-Image-Edit-2509"),
@@ -15,6 +15,8 @@ import pytest
from tests.helpers.mark import hardware_marks
from tests.helpers.runtime import OmniServer, OmniServerParams, OpenAIClientHandler, dummy_messages_from_mix_data
pytestmark = [pytest.mark.diffusion, pytest.mark.full_model]
T2I_PROMPT = "A photo of a cat sitting on a laptop keyboard, digital art style."
NEGATIVE_PROMPT = "blurry, low quality"
SINGLE_CARD_FEATURE_MARKS = hardware_marks(res={"cuda": "H100"})
@@ -117,8 +119,6 @@ def _get_diffusion_feature_cases(model: str):
]
@pytest.mark.advanced_model
@pytest.mark.diffusion
@pytest.mark.parametrize(
"omni_server",
_get_diffusion_feature_cases("Qwen/Qwen-Image"),
@@ -142,8 +142,6 @@ def test_qwen_image(omni_server: OmniServer, openai_client: OpenAIClientHandler)
openai_client.send_diffusion_request(request_config)
@pytest.mark.advanced_model
@pytest.mark.diffusion
@pytest.mark.parametrize(
"omni_server",
_get_diffusion_feature_cases("Qwen/Qwen-Image-2512"),
@@ -18,6 +18,8 @@ from tests.helpers.mark import hardware_marks
from tests.helpers.media import decode_b64_image, generate_synthetic_image
from tests.helpers.runtime import OmniServer, OmniServerParams, OpenAIClientHandler, dummy_messages_from_mix_data
pytestmark = [pytest.mark.diffusion, pytest.mark.full_model]
MODEL = "Qwen/Qwen-Image-Layered"
EDIT_PROMPT = "Decompose this image into layers."
EMPTY_EDIT_PROMPT = ""
@@ -71,8 +73,6 @@ FEATURE_CASES = [
]
@pytest.mark.advanced_model
@pytest.mark.diffusion
@pytest.mark.parametrize("omni_server", FEATURE_CASES, indirect=True)
def test_feature(omni_server: OmniServer, openai_client: OpenAIClientHandler):
"""Test feature combinations with Qwen-Image-Layered."""
@@ -149,8 +149,6 @@ def _collect_image_url_items(openai_client: OpenAIClientHandler, request_config:
return image_items
@pytest.mark.advanced_model
@pytest.mark.diffusion
@pytest.mark.parametrize(
"omni_server, expected_layers",
LAYERS_GUARD_CASES,
@@ -224,8 +222,6 @@ PROMPT_CASES = [
]
@pytest.mark.advanced_model
@pytest.mark.diffusion
@pytest.mark.parametrize("omni_server", PROMPT_CASES, indirect=True)
def test_empty_prompt(omni_server: OmniServer, openai_client: OpenAIClientHandler):
"""Test feature combinations with Qwen-Image-Layered."""
@@ -7,6 +7,8 @@ import pytest
from tests.helpers.mark import hardware_marks
from tests.helpers.runtime import OmniServer, OmniServerParams, OpenAIClientHandler
pytestmark = [pytest.mark.diffusion, pytest.mark.full_model]
FOUR_CARD_FEATURE_MARKS = hardware_marks(res={"cuda": "L4"}, num_cards=4)
POSITIVE_PROMPT = "A serene mountain landscape at sunset"
NEGATIVE_PROMPT = "blurry, low quality, distorted"
@@ -35,8 +37,6 @@ def _get_diffusion_feature_cases(model: str):
]
@pytest.mark.advanced_model
@pytest.mark.diffusion
@pytest.mark.parametrize(
"omni_server",
_get_diffusion_feature_cases(
@@ -23,6 +23,8 @@ from tests.helpers.mark import hardware_marks
from tests.helpers.media import generate_synthetic_image
from tests.helpers.runtime import OmniServer, OmniServerParams, OpenAIClientHandler
pytestmark = [pytest.mark.diffusion, pytest.mark.full_model]
PROMPT = "Two anthropomorphic cats in comfy boxing gear and bright gloves fight intensely on a spotlighted stage."
NEGATIVE_PROMPT = "low quality, blurry, distorted face, extra limbs, bad anatomy, watermark, logo, text, ugly, deformed, mutated, jpeg artifacts"
SINGLE_CARD_FEATURE_MARKS = hardware_marks(res={"cuda": "H100"})
@@ -79,8 +81,6 @@ def _get_wan22_feature_cases():
return cases
@pytest.mark.advanced_model
@pytest.mark.diffusion
@pytest.mark.parametrize(
"omni_server",
_get_wan22_feature_cases(),
@@ -26,6 +26,8 @@ import pytest
from tests.helpers.mark import hardware_marks
from tests.helpers.runtime import OmniServer, OmniServerParams, OpenAIClientHandler
pytestmark = [pytest.mark.diffusion, pytest.mark.full_model]
MODEL = "Wan-AI/Wan2.1-VACE-1.3B-diffusers"
PROMPT = "A cat walking slowly across a sunlit garden path"
@@ -131,8 +133,6 @@ def _get_vace_feature_cases():
]
@pytest.mark.advanced_model
@pytest.mark.diffusion
@pytest.mark.parametrize(
"omni_server",
_get_vace_feature_cases(),
@@ -16,6 +16,8 @@ import pytest
from tests.helpers.mark import hardware_marks
from tests.helpers.runtime import OmniServer, OmniServerParams, OpenAIClientHandler
pytestmark = [pytest.mark.diffusion, pytest.mark.full_model]
MODEL = "Tongyi-MAI/Z-Image-Turbo"
PROMPT = "A high-detail studio photo of an orange tabby cat sitting on a laptop keyboard."
@@ -101,8 +103,6 @@ def _get_diffusion_feature_cases():
]
@pytest.mark.advanced_model
@pytest.mark.diffusion
@pytest.mark.parametrize(
"omni_server",
_get_diffusion_feature_cases(),
@@ -1,4 +1,8 @@
# Thinker stage only
# CI stage config for Ming-flash-omni-2.0 thinker+talker pipeline.
# Stage 0: Thinker (multimodal understanding -> text generation)
# Stage 1: Talker (text -> audio waveform via CFM + AudioVAE)
#
# The following config has been verified on 4x H100-80G GPUs
stage_args:
- stage_id: 0
stage_type: llm
@@ -10,10 +14,12 @@ stage_args:
model_arch: MingFlashOmniForConditionalGeneration
worker_type: ar
scheduler_cls: vllm_omni.core.sched.omni_ar_scheduler.OmniARScheduler
gpu_memory_utilization: 0.9
gpu_memory_utilization: 0.74
enforce_eager: false
trust_remote_code: true
engine_output_type: latent
# Ming Thinker -> talker bridge reads detokenised text from
# source_output.outputs[0].text (not hidden states).
engine_output_type: text
distributed_executor_backend: "mp"
enable_prefix_caching: false
max_num_batched_tokens: 32768
@@ -22,14 +28,48 @@ stage_args:
hf_config_name: llm_config
load_format: dummy
mm_processor_cache_gb: 0
compilation_config:
pass_config:
# Disable fused all-reduce to avoid a vllm/flashinfer version mismatch.
fuse_allreduce_rms: false
final_output: true
final_output_type: text
is_comprehension: true
default_sampling_params:
temperature: 0.4
temperature: 0.0
top_p: 0.9
max_tokens: 100
repetition_penalty: 1.05
seed: 42
detokenize: true
ignore_eos: false
- stage_id: 1
stage_type: llm
runtime:
devices: "3"
max_batch_size: 1
engine_args:
model_stage: ming_tts
model_arch: MingFlashOmniTalkerForConditionalGeneration
worker_cls: vllm_omni.worker.gpu_generation_worker.GPUGenerationWorker
scheduler_cls: vllm_omni.core.sched.omni_generation_scheduler.OmniGenerationScheduler
gpu_memory_utilization: 0.18
enforce_eager: true
trust_remote_code: true
engine_output_type: audio
enable_prefix_caching: false
max_num_batched_tokens: 1000000
tokenizer_subdir: talker/llm
# The HF repo ships BailingMM2Config (thinker-only) at root;
# OmniModelConfig treats that as "stage does not share outer mrope".
hf_config_name: talker_config
load_format: dummy
engine_input_source: [0]
custom_process_input_func: vllm_omni.model_executor.stage_input_processors.ming_flash_omni.thinker2talker
final_output: true
final_output_type: audio
default_sampling_params:
temperature: 0.0
max_tokens: 1
seed: 42
@@ -0,0 +1,35 @@
# Thinker stage only
stage_args:
- stage_id: 0
stage_type: llm
runtime:
devices: "0,1,2,3"
max_batch_size: 1
engine_args:
model_stage: thinker
model_arch: MingFlashOmniForConditionalGeneration
worker_type: ar
scheduler_cls: vllm_omni.core.sched.omni_ar_scheduler.OmniARScheduler
gpu_memory_utilization: 0.9
enforce_eager: false
trust_remote_code: true
engine_output_type: latent
distributed_executor_backend: "mp"
enable_prefix_caching: false
max_num_batched_tokens: 32768
max_model_len: 32768
tensor_parallel_size: 4
hf_config_name: llm_config
load_format: dummy
mm_processor_cache_gb: 0
final_output: true
final_output_type: text
is_comprehension: true
default_sampling_params:
temperature: 0.4
top_p: 0.9
max_tokens: 100
repetition_penalty: 1.05
seed: 42
detokenize: true
ignore_eos: false
+35
View File
@@ -139,6 +139,41 @@ def test_from_cli_args_picks_up_stage_configs_path():
assert args.custom_pipeline_args is None
def test_qwen3_tts_code2wav_injects_max_position_embeddings(monkeypatch):
"""Ensure Code2Wav mirrors stage max_model_len into nested HF overrides.
Qwen3-TTS Code2Wav is a pure decoder stage whose runtime max_model_len can
legitimately exceed the base checkpoint's default text max length. Recent
vLLM validates these values during ModelConfig creation, so we inject
``talker_config.max_position_embeddings`` before delegating to vLLM.
"""
captured: dict[str, object] = {}
baseline_config = Mock()
def fake_create_model_config(self):
captured["hf_overrides"] = self.hf_overrides
return baseline_config
monkeypatch.setattr(EngineArgs, "create_model_config", fake_create_model_config)
monkeypatch.setattr(
OmniModelConfig,
"from_vllm_model_config",
classmethod(lambda cls, model_config, **omni_kwargs: model_config),
)
OmniEngineArgs(
model_arch="Qwen3TTSCode2Wav",
max_model_len=65536,
).create_model_config()
assert captured["hf_overrides"] == {
"architectures": ["Qwen3TTSCode2Wav"],
"talker_config": {
"max_position_embeddings": 65536,
},
}
def test_stage_specific_text_config_override():
"""Ensure dependent attributes are updated when using stage-specific config."""
vllm_config = EngineArgs().create_model_config()
+94
View File
@@ -10,11 +10,14 @@ from types import SimpleNamespace
from typing import Any
import janus
import psutil
import pytest
from vllm.outputs import CompletionOutput, RequestOutput
from vllm.sampling_params import SamplingParams
from vllm.v1.engine.core_client import AsyncMPClient
from vllm_omni.engine.orchestrator import Orchestrator
from vllm_omni.engine.stage_engine_core_client import StageEngineCoreClient
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
from vllm_omni.outputs import OmniRequestOutput
@@ -104,6 +107,42 @@ class FakeOutputProcessor:
return None
class _FakeProc:
pid = 1234
def __init__(self):
self.terminated = False
self.killed = False
self.join_calls = []
def is_alive(self):
return not self.terminated and not self.killed
def terminate(self):
self.terminated = True
def kill(self):
self.killed = True
def join(self, timeout=None):
self.join_calls.append(timeout)
class _FakeChildProc:
def __init__(self):
self.terminated = False
self.killed = False
def is_running(self):
return not self.terminated and not self.killed
def terminate(self):
self.terminated = True
def kill(self):
self.killed = True
def _sampling_params(max_tokens: int = 4) -> SamplingParams:
return SamplingParams(max_tokens=max_tokens)
@@ -269,6 +308,61 @@ async def _enqueue_abort_request(orchestrator_fixture: OrchestratorFixture, requ
)
def test_stage_engine_core_client_shutdown_cleans_children_if_base_shutdown_fails(monkeypatch):
fake_proc = _FakeProc()
fake_child = _FakeChildProc()
class FakePsutilProcess:
def __init__(self, pid):
assert pid == fake_proc.pid
def children(self, recursive=True):
assert recursive
return [fake_child]
def fail_base_shutdown(self):
raise RuntimeError("base shutdown failed")
monkeypatch.setattr(psutil, "Process", FakePsutilProcess)
monkeypatch.setattr(psutil, "wait_procs", lambda procs, timeout: (list(procs), []))
monkeypatch.setattr(AsyncMPClient, "shutdown", fail_base_shutdown)
client = object.__new__(StageEngineCoreClient)
client._proc = fake_proc
with pytest.raises(RuntimeError, match="base shutdown failed"):
client.shutdown()
assert fake_proc.terminated
assert fake_proc.join_calls == [5]
assert fake_child.terminated
def test_stage_engine_core_client_shutdown_kills_stubborn_children(monkeypatch):
fake_proc = _FakeProc()
fake_child = _FakeChildProc()
class FakePsutilProcess:
def __init__(self, pid):
assert pid == fake_proc.pid
def children(self, recursive=True):
assert recursive
return [fake_child]
monkeypatch.setattr(psutil, "Process", FakePsutilProcess)
monkeypatch.setattr(psutil, "wait_procs", lambda procs, timeout: ([], list(procs)))
monkeypatch.setattr(AsyncMPClient, "shutdown", lambda self: None)
client = object.__new__(StageEngineCoreClient)
client._proc = fake_proc
client.shutdown()
assert fake_child.terminated
assert fake_child.killed
@pytest.fixture
def orchestrator_factory():
fixtures: list[OrchestratorFixture] = []
@@ -183,6 +183,52 @@ def test_forward_to_diffusion_uses_engine_input_source_for_kv_sender_info():
}
def test_forward_to_diffusion_returns_terminal_error_for_empty_custom_inputs():
orchestrator = object.__new__(Orchestrator)
sender_stage = _DummySenderStage({"host": "10.0.0.2", "zmq_port": 50151})
diffusion_stage = _DummyDiffusionStage(engine_input_source=[0])
diffusion_stage.custom_process_input_func = lambda *_args, **_kwargs: []
class _AsyncQueue:
def __init__(self):
self.items = []
async def put(self, item):
self.items.append(item)
orchestrator.num_stages = 2
orchestrator.stage_clients = [sender_stage, diffusion_stage]
orchestrator._cfg_tracker = CfgCompanionTracker()
orchestrator.stage_vllm_configs = [None, None]
orchestrator.output_processors = [None, None]
orchestrator.output_async_queue = _AsyncQueue()
orchestrator.request_states = {}
orchestrator._pd_kv_params = {}
params = OmniDiffusionSamplingParams()
req_state = OrchestratorRequestState(
request_id="req-empty",
prompt={"prompt": "hello"},
sampling_params_list=[SamplingParams(max_tokens=4), params],
final_stage_id=1,
)
orchestrator.request_states["req-empty"] = req_state
output = SimpleNamespace(request_id="req-empty", finished=True)
asyncio.run(Orchestrator._forward_to_next_stage(orchestrator, "req-empty", 0, output, req_state))
assert sender_stage.engine_outputs == [output]
assert diffusion_stage.calls == []
assert len(orchestrator.output_async_queue.items) == 1
terminal_msg = orchestrator.output_async_queue.items[0]
assert terminal_msg["type"] == "output"
assert terminal_msg["request_id"] == "req-empty"
assert terminal_msg["stage_id"] == 1
assert terminal_msg["finished"] is True
assert "produced no valid inputs" in terminal_msg["engine_outputs"].error
assert "req-empty" not in orchestrator.request_states
def test_prewarm_diffusion_attaches_kv_sender_info():
orchestrator = object.__new__(Orchestrator)
sender_stage = _DummySenderStage({"host": "10.0.0.3", "zmq_port": 50151})
+33
View File
@@ -422,6 +422,39 @@ class TestSingleStageModeDetection:
)
assert engine._single_stage_id_filter is None
def test_engine_args_create_only_forwards_explicit_fields(self, mocker: MockerFixture):
from vllm_omni.engine.arg_utils import OmniEngineArgs
captured: dict[str, Any] = {}
def fake_resolve(self, model: str, kwargs: dict[str, Any]):
captured.update(kwargs)
return "/fake/path", [_make_stage_cfg(0)]
mocker.patch.object(AsyncOmniEngine, "_resolve_stage_configs", fake_resolve)
mocker.patch.object(AsyncOmniEngine, "_bootstrap_orchestrator")
mock_thread_cls = mocker.patch("threading.Thread")
mock_future_cls = mocker.patch("concurrent.futures.Future")
mock_future = mocker.Mock()
mock_future.result.return_value = mocker.Mock()
mock_future_cls.return_value = mock_future
mock_thread = mocker.Mock()
mock_thread.is_alive.return_value = False
mock_thread_cls.return_value = mock_thread
ea = OmniEngineArgs.create(model="ignored", gpu_memory_utilization=0.5)
AsyncOmniEngine(model="fake-model", engine_args=ea)
assert captured["gpu_memory_utilization"] == 0.5
assert "model" not in captured
assert "max_num_seqs" not in captured
def test_bare_engine_args_rejected(self, mocker: MockerFixture):
from vllm_omni.engine.arg_utils import OmniEngineArgs
with pytest.raises(TypeError, match="OmniEngineArgs.create"):
self._make_engine_no_thread(mocker, engine_args=OmniEngineArgs(model="fake-model"))
def test_master_address_and_port_stored(self, mocker: MockerFixture):
engine = self._make_engine_no_thread(
mocker,
@@ -0,0 +1,31 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Shared test helpers for video streaming tests."""
from __future__ import annotations
import io
import pytest
np = pytest.importorskip("numpy", reason="numpy required for video stream tests")
PIL = pytest.importorskip("PIL", reason="Pillow required for video stream tests")
from PIL import Image # noqa: E402
def make_jpeg(r: int = 128, g: int = 128, b: int = 128, size: int = 64) -> bytes:
"""Create a solid-colour JPEG image."""
img = Image.new("RGB", (size, size), (r, g, b))
buf = io.BytesIO()
img.save(buf, format="JPEG", quality=95)
return buf.getvalue()
def make_gradient_jpeg(seed: int, size: int = 64) -> bytes:
"""Create a random-gradient JPEG that varies based on *seed*."""
rng = np.random.RandomState(seed)
arr = rng.randint(0, 256, (size, size, 3), dtype=np.uint8)
img = Image.fromarray(arr, "RGB")
buf = io.BytesIO()
img.save(buf, format="JPEG", quality=95)
return buf.getvalue()
@@ -13,16 +13,22 @@ from argparse import Namespace
from types import SimpleNamespace
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from PIL import Image
from pytest_mock import MockerFixture
from vllm import SamplingParams
from vllm.entrypoints.openai.models.protocol import BaseModelPath
from vllm_omni.entrypoints.async_omni import AsyncOmni
from vllm_omni.entrypoints.openai.api_server import _DiffusionServingModels, router
from vllm_omni.entrypoints.openai.image_api_utils import (
encode_image_base64,
parse_size,
)
from vllm_omni.entrypoints.openai.serving_chat import OmniOpenAIServingChat
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
from vllm_omni.model_executor.stage_input_processors.glm_image import compute_max_tokens
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
@@ -569,6 +575,84 @@ def test_multistage_images_async_omni_construction(async_omni_test_client):
assert captured[1].guidance_scale == 6.5
def test_generate_images_async_omni_glm_image_sets_stage0_max_tokens():
"""GLM-Image multistage requests must compute stage-0 max_tokens from size."""
class FakeAsyncOmniClass(AsyncOmni):
def __init__(self):
stage_configs = [
SimpleNamespace(stage_type="llm", is_comprehension=True, model_arch="GlmImageForConditionalGeneration"),
SimpleNamespace(stage_type="diffusion", is_comprehension=False, model_arch="GlmImagePipeline"),
]
default_sampling_params_list = [
SamplingParams(temperature=0.1, seed=42),
OmniDiffusionSamplingParams(height=1024, width=1024),
]
self.engine = SimpleNamespace(
stage_configs=stage_configs,
default_sampling_params_list=default_sampling_params_list,
)
self.default_sampling_params_list = default_sampling_params_list
self.captured_sampling_params_list = None
self.captured_prompt = None
self._images = [Image.new("RGB", (64, 64), color="green")]
self.od_config = SimpleNamespace(supports_multimodal_inputs=True)
async def generate(self, prompt, request_id, sampling_params=None, sampling_params_list=None):
self.captured_sampling_params_list = (
sampling_params_list if sampling_params_list is not None else [sampling_params]
)
self.captured_prompt = prompt
yield MockGenerationResult([img.copy() for img in self._images])
def __class_getitem__(cls, item):
return cls
def get_diffusion_od_config(self):
return self.od_config
app = FastAPI()
app.include_router(router)
engine = FakeAsyncOmniClass()
chat_handler = object.__new__(OmniOpenAIServingChat)
chat_handler.engine_client = engine
chat_handler._diffusion_engine = None
app.state.openai_serving_chat = chat_handler
app.state.engine_client = engine
app.state.stage_configs = [
SimpleNamespace(stage_type="llm", model_arch="GlmImageForConditionalGeneration"),
SimpleNamespace(stage_type="diffusion", model_arch="GlmImagePipeline"),
]
app.state.openai_serving_models = _DiffusionServingModels(
[BaseModelPath(name="THUDM/GLM-4.5V", model_path="THUDM/GLM-4.5V")]
)
app.state.args = Namespace(
default_sampling_params='{"1": {"num_inference_steps":4, "guidance_scale":7.5, "generator_device":"cpu"}}',
max_generated_image_size=1048576,
)
client = TestClient(app)
response = client.post(
"/v1/images/generations",
json={
"prompt": "a coral reef",
"n": 1,
"size": "1024x1024",
"seed": 7,
},
)
assert response.status_code == 200
captured = engine.captured_sampling_params_list
assert captured is not None
assert len(captured) == 2
assert captured[0].max_tokens == compute_max_tokens(1024, 1024, is_i2i=False)
assert captured[0].extra_args["target_h"] == 1024
assert captured[0].extra_args["target_w"] == 1024
assert captured[1].height == 1024
assert captured[1].width == 1024
def test_image_edits_async_omni_stage_configs_only(async_omni_stage_configs_only_client):
"""Regression: image edits accepts refactored AsyncOmni without stage_list."""
img_bytes = make_test_image_bytes((16, 16))
@@ -23,33 +23,28 @@ from tests.helpers.media import (
generate_synthetic_audio,
)
from tests.helpers.runtime import OmniServerParams
from tests.helpers.stage_config import get_deploy_config_path, modify_stage_config
from tests.helpers.stage_config import get_deploy_config_path
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
MODEL = "Qwen/Qwen3-Omni-30B-A3B-Instruct"
# Synthetic input for realtime E2E (``generate_synthetic_audio``); distinct cache file per phrase.
REALTIME_SYNTH_PHRASE_TEXT = "Translate into Chinese: Beijing is the Capital of China"
# The new-schema CI overlay bakes in async_chunk: False and covers CUDA/ROCm/XPU
# via its ``platforms:`` section, so one path serves all three.
default_stage_config = get_deploy_config_path("ci/qwen3_omni_moe.yaml")
def _realtime_stage_config_path() -> str:
"""CI omni layout without async_chunk; stage 0 thinker max_tokens=10."""
return modify_stage_config(
default_stage_config,
updates={"stages": {0: {"default_sampling_params.max_tokens": 10}}},
)
realtime_server_params = [
pytest.param(
OmniServerParams(
model=MODEL,
stage_config_path=_realtime_stage_config_path(),
stage_config_path=default_stage_config,
use_stage_cli=True,
server_args=["--no-async-chunk"],
),
id="thinker_max_tokens_10",
id="default",
),
]
@@ -169,9 +164,15 @@ class TestQwen3OmniRealtimeWebSocket:
"""
Short streamed 16 kHz mono PCM16 input; expect streamed PCM16 audio deltas and
transcription. Verify Whisper(output audio) aligns with model text (same idea
as multimodal omni e2e).
as multimodal omni e2e). Input speech is synthesized from
``REALTIME_SYNTH_PHRASE_TEXT``.
"""
syn = generate_synthetic_audio(10, 1, sample_rate=16000)
syn = generate_synthetic_audio(
10,
1,
sample_rate=16000,
phrase_text=REALTIME_SYNTH_PHRASE_TEXT,
)
wav_bytes = base64.b64decode(syn["base64"])
pcm16 = _pcm16_mono_16k_from_wav_bytes(wav_bytes)
@@ -1,6 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
"""Unit tests for OmniChatCompletionResponse/StreamResponse metrics field."""
from types import SimpleNamespace
import pytest
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
@@ -50,3 +52,36 @@ def test_omni_chat_completion_stream_response_metrics():
)
assert response.modality == "audio"
assert response.metrics == {"stage_latency": 0.5}
def test_create_image_choice_exposes_diffusion_metrics():
"""Ensure image chat content exposes profiler metrics for clients."""
from PIL import Image
from vllm_omni.entrypoints.openai.serving_chat import OmniOpenAIServingChat
stage_durations = {"prefill": 0.12, "diffusion": 1.23}
peak_memory_mb = 3210.5
omni_outputs = SimpleNamespace(
request_output=None,
stage_durations=stage_durations,
peak_memory_mb=peak_memory_mb,
images=[Image.new("RGB", (2, 2), color=(255, 0, 0))],
)
choices = OmniOpenAIServingChat._create_image_choice( # type: ignore[misc]
None,
omni_outputs=omni_outputs,
role="assistant",
request=SimpleNamespace(return_token_ids=False),
)
assert len(choices) == 1
content = choices[0].message.content
assert isinstance(content, list)
assert len(content) == 1
first_item = content[0]
assert first_item["type"] == "image_url"
assert first_item["image_url"]["url"].startswith("data:image/png;base64,")
assert first_item["stage_durations"] == stage_durations
assert first_item["peak_memory_mb"] == peak_memory_mb
@@ -18,6 +18,7 @@ from pydantic import ValidationError
from pytest_mock import MockerFixture
from vllm.entrypoints.openai.engine.protocol import ErrorInfo, ErrorResponse
from vllm_omni.entrypoints.omni_base import OmniEngineDeadError
from vllm_omni.entrypoints.openai import api_server as api_server_module
from vllm_omni.entrypoints.openai.audio_utils_mixin import AudioMixin
from vllm_omni.entrypoints.openai.protocol.audio import (
@@ -1707,6 +1708,77 @@ def test_api_server_create_speech_wraps_error_response_status(mocker: MockerFixt
assert response.status_code == 400
def test_api_server_create_speech_engine_error_response_includes_request_and_stage_id(mocker: MockerFixture):
handler = mocker.MagicMock()
handler.create_speech = mocker.AsyncMock(
side_effect=OmniEngineDeadError(
"engine dead",
error_stage_id=1,
)
)
terminate_mock = mocker.patch.object(api_server_module, "terminate_if_errored")
app = FastAPI()
app.state.args = SimpleNamespace(log_error_stack=False)
app.state.openai_serving_speech = handler
app.state.engine_client = SimpleNamespace(
engine=SimpleNamespace(is_alive=lambda: False),
errored=True,
)
app.state.server = SimpleNamespace()
scope = {
"type": "http",
"app": app,
"method": "POST",
"path": "/v1/audio/speech",
"headers": [],
"query_string": b"",
"client": ("127.0.0.1", 12345),
"server": ("testserver", 80),
"scheme": "http",
}
raw_request = Request(scope)
raw_request.state.request_metadata = SimpleNamespace(request_id="speech-req-1")
request = OpenAICreateSpeechRequest(input="Hello")
response = asyncio.run(api_server_module.create_speech(request, raw_request))
assert isinstance(response, JSONResponse)
assert response.status_code == 500
assert response.body.decode("utf-8") == (
'{"error":{"message":"engine dead","type":"InternalServerError","param":null,'
'"code":500,"request_id":"speech-req-1","error_stage_id":1}}'
)
terminate_mock.assert_called_once()
def test_omni_engine_error_handler_includes_request_and_stage_id(mocker: MockerFixture):
app = FastAPI()
app.state.args = SimpleNamespace(log_error_stack=False)
app.state.engine_client = SimpleNamespace(
engine=SimpleNamespace(is_alive=lambda: False),
errored=True,
)
app.state.server = SimpleNamespace()
terminate_mock = mocker.patch.object(api_server_module, "terminate_if_errored")
api_server_module._register_omni_exception_handlers(app)
@app.get("/boom")
async def boom(request: Request):
request.state.request_metadata = SimpleNamespace(request_id="speech-req-1")
exc = OmniEngineDeadError("engine dead", error_stage_id=1)
raise exc
response = TestClient(app).get("/boom")
assert response.status_code == 500
assert response.json()["error"]["request_id"] == "speech-req-1"
assert response.json()["error"]["error_stage_id"] == 1
terminate_mock.assert_called_once()
class TestWAVHeaderGeneration:
"""Unit tests for WAV header generation with placeholder values."""
@@ -0,0 +1,650 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Tests for the serving-layer streaming video WebSocket handler."""
from __future__ import annotations
import asyncio
import base64
import io
import json
import threading
from typing import Any
import pytest
from PIL import Image
from vllm_omni.entrypoints.openai import serving_video_stream, video_stream_envs
from vllm_omni.entrypoints.openai.serving_video_stream import (
OmniStreamingVideoHandler,
StreamingVideoSessionConfig,
)
from vllm_omni.outputs import OmniRequestOutput
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
def _make_jpeg(r: int = 128, g: int = 128, b: int = 128) -> bytes:
img = Image.new("RGB", (64, 64), (r, g, b))
buf = io.BytesIO()
img.save(buf, format="JPEG", quality=95)
return buf.getvalue()
def _b64(data: bytes) -> str:
return base64.b64encode(data).decode()
def _text_result(text: str) -> OmniRequestOutput:
class Output:
pass
class RequestOutput:
pass
output = Output()
output.text = text
request_output = RequestOutput()
request_output.outputs = [output]
return OmniRequestOutput(final_output_type="text", request_output=request_output)
def _audio_result(audio_data: Any) -> OmniRequestOutput:
class Output:
pass
class RequestOutput:
pass
output = Output()
output.multimodal_output = {"audio": audio_data}
request_output = RequestOutput()
request_output.outputs = [output]
return OmniRequestOutput(final_output_type="audio", request_output=request_output)
class MockWebSocket:
def __init__(self, messages: list[str] | None = None):
self._messages = list(messages or [])
self._idx = 0
self.accepted = False
self.sent: list[dict[str, Any]] = []
async def accept(self):
self.accepted = True
async def receive_text(self) -> str:
if self._idx >= len(self._messages):
await asyncio.sleep(999)
msg = self._messages[self._idx]
self._idx += 1
return msg
async def send_json(self, data: dict[str, Any]):
self.sent.append(data)
class TimedWebSocket:
def __init__(self):
self._q: asyncio.Queue[str] = asyncio.Queue()
self.accepted = False
self.sent: list[dict[str, Any]] = []
async def accept(self):
self.accepted = True
async def receive_text(self) -> str:
return await self._q.get()
async def send_json(self, data: dict[str, Any]):
self.sent.append(data)
def put(self, msg: dict[str, Any]):
self._q.put_nowait(json.dumps(msg))
def sent_types(self) -> list[str]:
return [m.get("type", "") for m in self.sent]
def test_api_server_registers_video_stream_route():
from vllm_omni.entrypoints.openai.api_server import router
assert any(getattr(route, "path", None) == "/v1/video/chat/stream" for route in router.routes)
@pytest.mark.asyncio
async def test_receive_config_accepts_client_legacy_aliases():
ws = MockWebSocket(
[
json.dumps(
{
"type": "session.config",
"model": "test",
"num_sample_frames": 7,
"evs_enabled": False,
"evs_threshold": 0.87,
}
)
]
)
handler = OmniStreamingVideoHandler(chat_service=object())
config = await handler._receive_config(ws)
assert config is not None
assert config.num_frames == 7
assert config.enable_frame_filter is False
assert config.frame_filter_threshold == 0.87
@pytest.mark.asyncio
async def test_audio_in_video_sets_mm_processor_kwargs():
captured_requests = []
class EmptyEngine:
def generate(self, **_kwargs):
async def _gen():
if False:
yield None
return _gen()
class CapturingHandler(OmniStreamingVideoHandler):
async def _preprocess_to_engine_prompt(self, request):
captured_requests.append(request)
return {"prompt": "x"}
ws = MockWebSocket()
handler = CapturingHandler(chat_service=object(), engine_client=EmptyEngine())
config = StreamingVideoSessionConfig(model="test", modalities=["text", "audio"], use_audio_in_video=True)
await handler._process_query_engine(
ws,
config,
[_b64(_make_jpeg())],
bytearray(b"\x00\x00"),
[],
"what is happening?",
"req-1",
asyncio.Event(),
{},
)
assert captured_requests
assert captured_requests[0].mm_processor_kwargs == {"use_audio_in_video": True}
@pytest.mark.asyncio
async def test_audio_in_video_disabled_omits_mm_processor_kwargs():
captured_requests = []
class EmptyEngine:
def generate(self, **_kwargs):
async def _gen():
if False:
yield None
return _gen()
class CapturingHandler(OmniStreamingVideoHandler):
async def _preprocess_to_engine_prompt(self, request):
captured_requests.append(request)
return {"prompt": "x"}
ws = MockWebSocket()
handler = CapturingHandler(chat_service=object(), engine_client=EmptyEngine())
config = StreamingVideoSessionConfig(model="test", modalities=["text", "audio"], use_audio_in_video=False)
await handler._process_query_engine(
ws,
config,
[_b64(_make_jpeg())],
bytearray(b"\x00\x00"),
[],
"what is happening?",
"req-1",
asyncio.Event(),
{},
)
assert captured_requests
assert captured_requests[0].mm_processor_kwargs is None
@pytest.mark.asyncio
async def test_query_inline_audio_data_sets_mm_processor_kwargs():
captured_requests = []
class EmptyEngine:
def generate(self, **_kwargs):
async def _gen():
if False:
yield None
return _gen()
class CapturingHandler(OmniStreamingVideoHandler):
async def _preprocess_to_engine_prompt(self, request):
captured_requests.append(request)
return {"prompt": "x"}
ws = MockWebSocket(
[
json.dumps({"type": "session.config", "model": "test"}),
json.dumps({"type": "video.frame", "data": _b64(_make_jpeg())}),
json.dumps(
{
"type": "video.query",
"text": "describe",
"audio_data": _b64(b"\x00\x00"),
}
),
json.dumps({"type": "video.done"}),
]
)
handler = CapturingHandler(chat_service=object(), engine_client=EmptyEngine(), idle_timeout=2.0)
await handler.handle_session(ws)
assert captured_requests
assert captured_requests[0].mm_processor_kwargs == {"use_audio_in_video": True}
assert "session.done" in [m.get("type") for m in ws.sent]
def test_audio_delta_mode_is_read_by_serving_code_at_runtime(monkeypatch):
handler = OmniStreamingVideoHandler(chat_service=object())
result = _audio_result([object()])
monkeypatch.setattr(
OmniStreamingVideoHandler,
"_delta_fast",
classmethod(lambda cls, audio_data, chunks_drained: ("fast-path", chunks_drained)),
)
monkeypatch.setattr(
OmniStreamingVideoHandler,
"_delta_slow",
classmethod(lambda cls, audio_data, chunks_drained: ("slow-path", chunks_drained)),
)
monkeypatch.setenv("VLLM_VIDEO_AUDIO_DELTA_MODE", "fast")
assert handler._extract_audio_delta_b64(result, 0)[0] == "fast-path"
monkeypatch.setenv("VLLM_VIDEO_AUDIO_DELTA_MODE", "slow")
assert handler._extract_audio_delta_b64(result, 0)[0] == "slow-path"
def test_video_stream_envs_strip_and_warn_once_per_invalid_value(monkeypatch):
warnings = []
video_stream_envs._warned_invalid_envs.clear()
try:
monkeypatch.setattr(
video_stream_envs.logger,
"warning",
lambda message, *args, **_kwargs: warnings.append((message, args)),
)
monkeypatch.setenv("VLLM_VIDEO_ASYNC_CHUNK", " off ")
assert video_stream_envs.VLLM_VIDEO_ASYNC_CHUNK == "off"
assert not warnings
monkeypatch.setenv("VLLM_VIDEO_ASYNC_CHUNK", "bad")
assert video_stream_envs.VLLM_VIDEO_ASYNC_CHUNK == "on"
assert video_stream_envs.VLLM_VIDEO_ASYNC_CHUNK == "on"
assert len(warnings) == 1
monkeypatch.setenv("VLLM_VIDEO_ASYNC_CHUNK", "still_bad")
assert video_stream_envs.VLLM_VIDEO_ASYNC_CHUNK == "on"
assert len(warnings) == 2
finally:
video_stream_envs._warned_invalid_envs.clear()
@pytest.mark.asyncio
async def test_async_chunk_mode_is_read_by_engine_path_at_runtime(monkeypatch):
class TextEngine:
def generate(self, **_kwargs):
async def _gen():
yield _text_result("hello")
return _gen()
class CapturingHandler(OmniStreamingVideoHandler):
async def _preprocess_to_engine_prompt(self, request):
return {"prompt": "x"}
handler = CapturingHandler(chat_service=object(), engine_client=TextEngine())
config = StreamingVideoSessionConfig(model="test", modalities=["text"])
monkeypatch.setenv("VLLM_VIDEO_ASYNC_CHUNK", "on")
ws_on = MockWebSocket()
await handler._process_query_engine(
ws_on,
config,
[_b64(_make_jpeg())],
bytearray(),
[],
"describe",
"req-on",
asyncio.Event(),
{},
)
assert {"type": "response.text.delta", "delta": "hello"} in ws_on.sent
monkeypatch.setenv("VLLM_VIDEO_ASYNC_CHUNK", "off")
ws_off = MockWebSocket()
await handler._process_query_engine(
ws_off,
config,
[_b64(_make_jpeg())],
bytearray(),
[],
"describe",
"req-off",
asyncio.Event(),
{},
)
assert {"type": "response.text.done", "text": "hello"} in ws_off.sent
assert not any(m.get("type") == "response.text.delta" for m in ws_off.sent)
@pytest.mark.asyncio
async def test_query_without_engine_client_sends_error():
ws = MockWebSocket()
handler = OmniStreamingVideoHandler(chat_service=object(), engine_client=None)
await handler._process_query(
ws,
StreamingVideoSessionConfig(model="test"),
[],
bytearray(),
[],
"describe",
"req-1",
asyncio.Event(),
{},
)
assert {"type": "error", "message": "Streaming video requires an engine client"} in ws.sent
@pytest.mark.asyncio
async def test_new_query_cancels_in_flight_query():
query_started = asyncio.Event()
query_cancelled = asyncio.Event()
calls = 0
class BlockingHandler(OmniStreamingVideoHandler):
async def _process_query(self, *args, **kwargs):
nonlocal calls
calls += 1
if calls > 1:
return
query_started.set()
try:
await asyncio.sleep(999)
except asyncio.CancelledError:
query_cancelled.set()
raise
ws = TimedWebSocket()
handler = BlockingHandler(chat_service=object(), idle_timeout=5.0)
task = asyncio.create_task(handler.handle_session(ws))
ws.put({"type": "session.config", "model": "test"})
await asyncio.sleep(0)
ws.put({"type": "video.frame", "data": _b64(_make_jpeg())})
await asyncio.sleep(0)
ws.put({"type": "video.query", "text": "describe"})
await asyncio.wait_for(query_started.wait(), timeout=2.0)
ws.put({"type": "video.query", "text": "interrupt"})
await asyncio.wait_for(query_cancelled.wait(), timeout=2.0)
ws.put({"type": "video.done"})
await asyncio.wait_for(task, timeout=2.0)
assert "session.done" in ws.sent_types()
@pytest.mark.asyncio
async def test_video_done_waits_for_in_flight_query():
query_started = asyncio.Event()
allow_finish = asyncio.Event()
query_finished = asyncio.Event()
class BlockingHandler(OmniStreamingVideoHandler):
async def _process_query(self, *args, **kwargs):
query_started.set()
await allow_finish.wait()
query_finished.set()
ws = TimedWebSocket()
handler = BlockingHandler(chat_service=object(), idle_timeout=5.0)
task = asyncio.create_task(handler.handle_session(ws))
ws.put({"type": "session.config", "model": "test"})
await asyncio.sleep(0)
ws.put({"type": "video.frame", "data": _b64(_make_jpeg())})
await asyncio.sleep(0)
ws.put({"type": "video.query", "text": "describe"})
await asyncio.wait_for(query_started.wait(), timeout=2.0)
ws.put({"type": "video.done"})
await asyncio.sleep(0.05)
assert not task.done()
assert not query_finished.is_set()
allow_finish.set()
await asyncio.wait_for(task, timeout=2.0)
assert query_finished.is_set()
assert "session.done" in ws.sent_types()
@pytest.mark.asyncio
async def test_frame_prewarm_does_not_block_following_query(monkeypatch):
decode_started = threading.Event()
release_decode = threading.Event()
query_started = asyncio.Event()
def blocked_decode(raw_bytes: bytes):
decode_started.set()
release_decode.wait(timeout=2.0)
return Image.open(io.BytesIO(raw_bytes)).convert("RGB")
class BlockingHandler(OmniStreamingVideoHandler):
async def _process_query(self, *args, **kwargs):
query_started.set()
monkeypatch.setattr(serving_video_stream, "_decode_frame_bytes", blocked_decode)
ws = TimedWebSocket()
handler = BlockingHandler(chat_service=object(), idle_timeout=5.0)
task = asyncio.create_task(handler.handle_session(ws))
ws.put({"type": "session.config", "model": "test"})
await asyncio.sleep(0)
ws.put({"type": "video.frame", "data": _b64(_make_jpeg())})
for _ in range(100):
if decode_started.is_set():
break
await asyncio.sleep(0.01)
assert decode_started.is_set()
ws.put({"type": "video.query", "text": "describe"})
await asyncio.wait_for(query_started.wait(), timeout=2.0)
release_decode.set()
ws.put({"type": "video.done"})
await asyncio.wait_for(task, timeout=2.0)
assert "session.done" in ws.sent_types()
@pytest.mark.asyncio
async def test_client_cannot_send_internal_frame_decode_failed_message():
captured_frames: list[list[str]] = []
frame = _b64(_make_jpeg())
class CapturingHandler(OmniStreamingVideoHandler):
async def _process_query(
self,
websocket,
config,
frame_buffer,
audio_buffer,
message_history,
query_text,
request_id,
interrupt_event,
prewarmed_frames,
):
captured_frames.append(list(frame_buffer))
ws = TimedWebSocket()
handler = CapturingHandler(chat_service=object(), idle_timeout=5.0)
task = asyncio.create_task(handler.handle_session(ws))
ws.put({"type": "session.config", "model": "test"})
await asyncio.sleep(0)
ws.put({"type": "video.frame", "data": frame})
await asyncio.sleep(0)
ws.put({"type": "_internal.frame_decode_failed", "b64": frame})
await asyncio.sleep(0)
ws.put({"type": "video.query", "text": "describe"})
await asyncio.sleep(0)
ws.put({"type": "video.done"})
await asyncio.wait_for(task, timeout=2.0)
assert {"type": "error", "message": "Unknown type: _internal.frame_decode_failed"} in ws.sent
assert captured_frames == [[frame]]
@pytest.mark.asyncio
async def test_failed_frame_prewarm_removes_frame_before_query():
ws = TimedWebSocket()
handler = OmniStreamingVideoHandler(chat_service=object(), idle_timeout=5.0)
task = asyncio.create_task(handler.handle_session(ws))
ws.put({"type": "session.config", "model": "test", "enable_frame_filter": False})
await asyncio.sleep(0)
ws.put({"type": "video.frame", "data": _b64(b"not-a-jpeg")})
for _ in range(100):
if any(m.get("message") == "Frame decode failed" for m in ws.sent):
break
await asyncio.sleep(0.01)
assert {"type": "error", "message": "Frame decode failed"} in ws.sent
ws.put({"type": "video.query", "text": "describe"})
await asyncio.sleep(0)
ws.put({"type": "video.done"})
await asyncio.wait_for(task, timeout=2.0)
assert {"type": "error", "message": "No frames buffered"} in ws.sent
@pytest.mark.asyncio
async def test_frame_filter_error_sends_invalid_image(monkeypatch):
def fail_should_retain(self, frame_jpeg):
raise ValueError("decode failed")
monkeypatch.setattr(serving_video_stream.FrameSimilarityFilter, "should_retain", fail_should_retain)
ws = TimedWebSocket()
handler = OmniStreamingVideoHandler(chat_service=object(), idle_timeout=5.0)
task = asyncio.create_task(handler.handle_session(ws))
ws.put({"type": "session.config", "model": "test"})
await asyncio.sleep(0)
ws.put({"type": "video.frame", "data": _b64(_make_jpeg())})
await asyncio.sleep(0)
ws.put({"type": "video.done"})
await asyncio.wait_for(task, timeout=2.0)
assert {"type": "error", "message": "Invalid image data"} in ws.sent
assert "session.done" in ws.sent_types()
@pytest.mark.asyncio
async def test_audio_buffer_overflow_clears_buffer_before_query(monkeypatch):
captured_audio_lengths: list[int] = []
class EmptyEngine:
def generate(self, **_kwargs):
async def _gen():
if False:
yield None
return _gen()
class CapturingHandler(OmniStreamingVideoHandler):
async def _process_query_engine(
self,
websocket,
config,
frame_buffer,
audio_buffer,
message_history,
query_text,
request_id,
interrupt_event,
prewarmed_frames,
):
captured_audio_lengths.append(len(audio_buffer))
monkeypatch.setattr(serving_video_stream, "_MAX_AUDIO_BUFFER_BYTES", 4)
ws = TimedWebSocket()
handler = CapturingHandler(chat_service=object(), engine_client=EmptyEngine(), idle_timeout=5.0)
task = asyncio.create_task(handler.handle_session(ws))
ws.put({"type": "session.config", "model": "test"})
await asyncio.sleep(0)
ws.put({"type": "audio.chunk", "data": _b64(b"1234")})
await asyncio.sleep(0)
ws.put({"type": "audio.chunk", "data": _b64(b"5")})
await asyncio.sleep(0)
ws.put({"type": "video.frame", "data": _b64(_make_jpeg())})
await asyncio.sleep(0)
ws.put({"type": "video.query", "text": "describe"})
await asyncio.sleep(0)
ws.put({"type": "video.done"})
await asyncio.wait_for(task, timeout=2.0)
assert {"type": "error", "message": "Audio buffer overflow"} in ws.sent
assert captured_audio_lengths == [0]
def test_build_messages_keeps_recent_history_text_only():
handler = OmniStreamingVideoHandler(chat_service=object())
old_frame = _b64(_make_jpeg(1, 2, 3))
current_frame = _b64(_make_jpeg(4, 5, 6))
history = [
{"role": "user", "content": [{"type": "text", "text": "old question"}]},
{"role": "assistant", "content": "old answer"},
{
"role": "user",
"content": [
{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{old_frame}"}},
{"type": "input_audio", "input_audio": {"data": "ignored", "format": "wav"}},
{"type": "text", "text": "recent question"},
],
},
{"role": "assistant", "content": "recent answer"},
]
messages, user_message = handler._build_messages(
StreamingVideoSessionConfig(model="test", num_frames=1),
[current_frame],
bytearray(),
history,
"current question",
{},
)
assert messages[0] == {"role": "user", "content": "recent question"}
assert messages[1] == {"role": "assistant", "content": "recent answer"}
assert messages[2] == user_message
assert user_message["content"][-1] == {"type": "text", "text": "current question"}
@@ -0,0 +1,89 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Unit tests for FrameSimilarityFilter (Phase 2 EVS)."""
from __future__ import annotations
import pytest
from tests.entrypoints.openai_api.conftest_video import (
make_gradient_jpeg,
make_jpeg,
)
from vllm_omni.entrypoints.openai.video_frame_filter import FrameSimilarityFilter
class TestFrameSimilarityFilter:
def test_first_frame_always_retained(self):
f = FrameSimilarityFilter(threshold=0.99)
assert f.should_retain(make_jpeg()) is True
def test_identical_frames_dropped(self):
f = FrameSimilarityFilter(threshold=0.90)
frame = make_jpeg(100, 100, 100)
assert f.should_retain(frame) is True
assert f.should_retain(frame) is False
def test_very_different_frames_retained(self):
f = FrameSimilarityFilter(threshold=0.95)
assert f.should_retain(make_jpeg(255, 255, 255)) is True
assert f.should_retain(make_jpeg(0, 0, 0)) is True
def test_low_threshold_keeps_slightly_different(self):
f = FrameSimilarityFilter(threshold=0.50)
assert f.should_retain(make_jpeg(100, 100, 100)) is True
assert f.should_retain(make_jpeg(110, 110, 110)) is True
def test_random_frames_all_retained(self):
f = FrameSimilarityFilter(threshold=0.95)
for i in range(5):
assert f.should_retain(make_gradient_jpeg(seed=i)) is True
def test_reset_clears_state(self):
f = FrameSimilarityFilter(threshold=0.90)
frame = make_jpeg(128, 128, 128)
assert f.should_retain(frame) is True
assert f.should_retain(frame) is False
f.reset()
assert f.should_retain(frame) is True
def test_stats_counting(self):
f = FrameSimilarityFilter(threshold=0.90)
frame = make_jpeg(50, 50, 50)
f.should_retain(frame) # retained
f.should_retain(frame) # dropped
f.should_retain(frame) # dropped
stats = f.stats
assert stats["retained_count"] == 1
assert stats["dropped_count"] == 2
assert stats["total_count"] == 3
assert abs(stats["drop_rate"] - 2.0 / 3.0) < 1e-6
def test_stats_empty(self):
stats = FrameSimilarityFilter().stats
assert stats["total_count"] == 0
assert stats["drop_rate"] == 0.0
def test_stats_reset(self):
f = FrameSimilarityFilter(threshold=0.90)
f.should_retain(make_jpeg())
f.reset()
assert f.stats["total_count"] == 0
def test_invalid_threshold(self):
with pytest.raises(ValueError, match="threshold"):
FrameSimilarityFilter(threshold=1.5)
with pytest.raises(ValueError, match="threshold"):
FrameSimilarityFilter(threshold=-0.1)
def test_invalid_thumbnail_size(self):
with pytest.raises(ValueError, match="thumbnail_size"):
FrameSimilarityFilter(thumbnail_size=0)
def test_different_image_sizes_same_colour(self):
"""Filter should handle frames of varying resolutions."""
f = FrameSimilarityFilter(threshold=0.90)
small = make_jpeg(100, 100, 100, size=32)
large = make_jpeg(100, 100, 100, size=256)
assert f.should_retain(small) is True
assert f.should_retain(large) is False
@@ -29,6 +29,7 @@ from vllm_omni.entrypoints.openai.protocol.videos import (
from vllm_omni.entrypoints.openai.serving_video import OmniOpenAIServingVideo
from vllm_omni.entrypoints.openai.storage import LocalStorageManager
from vllm_omni.entrypoints.openai.stores import AsyncDictStore, TaskRegistry
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
@@ -60,6 +61,7 @@ class MockVideoResult:
class FakeAsyncOmni:
def __init__(self):
self.stage_configs = [SimpleNamespace(stage_type="diffusion")]
self.default_sampling_params_list = [OmniDiffusionSamplingParams()]
self.captured_prompt = None
self.captured_sampling_params_list = None
@@ -442,6 +444,87 @@ def test_frame_interpolation_params_pass_to_diffusion_sampling_params(test_clien
assert captured.frame_interpolation_model_path == "local-rife"
def test_default_sampling_params_apply_to_video_requests(test_client, mocker: MockerFixture):
mocker.patch(
"vllm_omni.entrypoints.openai.serving_video._encode_video_bytes",
return_value=b"fake-video",
)
engine = test_client.app.state.openai_serving_video._engine_client
engine.default_sampling_params_list = [
OmniDiffusionSamplingParams(
num_inference_steps=4,
guidance_scale=7.5,
generator_device="cpu",
enable_frame_interpolation=True,
frame_interpolation_exp=2,
frame_interpolation_scale=0.5,
frame_interpolation_model_path="default-rife",
)
]
response = test_client.post(
"/v1/videos",
data={
"prompt": "default param pass-through",
},
)
assert response.status_code == 200
video_id = response.json()["id"]
_wait_for_status(test_client, video_id, VideoGenerationStatus.COMPLETED.value)
captured = engine.captured_sampling_params_list[0]
assert captured.num_inference_steps == 4
assert captured.guidance_scale == 7.5
assert captured.generator_device == "cpu"
assert captured.enable_frame_interpolation is True
assert captured.frame_interpolation_exp == 2
assert captured.frame_interpolation_scale == 0.5
assert captured.frame_interpolation_model_path == "default-rife"
def test_request_params_override_default_video_sampling_params(test_client, mocker: MockerFixture):
mocker.patch(
"vllm_omni.entrypoints.openai.serving_video._encode_video_bytes",
return_value=b"fake-video",
)
engine = test_client.app.state.openai_serving_video._engine_client
engine.default_sampling_params_list = [
OmniDiffusionSamplingParams(
num_inference_steps=4,
guidance_scale=7.5,
enable_frame_interpolation=True,
frame_interpolation_exp=2,
frame_interpolation_scale=0.5,
frame_interpolation_model_path="default-rife",
)
]
response = test_client.post(
"/v1/videos",
data={
"prompt": "explicit override",
"num_inference_steps": "8",
"enable_frame_interpolation": "false",
"frame_interpolation_exp": "1",
"frame_interpolation_scale": "1.0",
"frame_interpolation_model_path": "custom-rife",
},
)
assert response.status_code == 200
video_id = response.json()["id"]
_wait_for_status(test_client, video_id, VideoGenerationStatus.COMPLETED.value)
captured = engine.captured_sampling_params_list[0]
assert captured.num_inference_steps == 8
assert captured.guidance_scale == 7.5
assert captured.enable_frame_interpolation is False
assert captured.frame_interpolation_exp == 1
assert captured.frame_interpolation_scale == 1.0
assert captured.frame_interpolation_model_path == "custom-rife"
def test_worker_fps_multiplier_is_applied_to_async_encoding(test_client, mocker: MockerFixture):
fps_values = []
engine = test_client.app.state.openai_serving_video._engine_client
@@ -1149,6 +1232,39 @@ def test_sync_frame_interpolation_params_pass_to_sampling_params(test_client, mo
assert kwargs["fps"] == 8
def test_sync_default_sampling_params_apply_to_video_requests(test_client, mocker: MockerFixture):
_mock_encode_video_bytes(mocker)
engine = test_client.app.state.openai_serving_video._engine_client
engine.default_sampling_params_list = [
OmniDiffusionSamplingParams(
num_inference_steps=4,
guidance_scale=7.5,
enable_frame_interpolation=True,
frame_interpolation_exp=2,
frame_interpolation_scale=0.5,
frame_interpolation_model_path="default-rife",
)
]
response = test_client.post(
"/v1/videos/sync",
data={
"prompt": "sync default param pass-through",
"fps": "8",
},
)
assert response.status_code == 200
engine = test_client.app.state.openai_serving_video._engine_client
captured = engine.captured_sampling_params_list[0]
assert captured.num_inference_steps == 4
assert captured.guidance_scale == 7.5
assert captured.enable_frame_interpolation is True
assert captured.frame_interpolation_exp == 2
assert captured.frame_interpolation_scale == 0.5
assert captured.frame_interpolation_model_path == "default-rife"
def test_worker_fps_multiplier_is_applied_to_sync_encoding(test_client, mocker: MockerFixture):
engine = test_client.app.state.openai_serving_video._engine_client
fps_values = []
@@ -0,0 +1,593 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Runtime behavior tests for VideoStreamHandler.
Every test creates a mock WebSocket, drives handle_session through a
specific code path, and asserts on the JSON messages actually sent back.
No inspect.getsource() tricks — these test real async execution.
"""
from __future__ import annotations
import asyncio
import base64
import io
import json
from unittest.mock import AsyncMock
import pytest
from PIL import Image
from vllm_omni.entrypoints.openai.video_stream_session import (
VideoStreamHandler,
)
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _make_jpeg(r: int = 128, g: int = 128, b: int = 128) -> bytes:
img = Image.new("RGB", (64, 64), (r, g, b))
buf = io.BytesIO()
img.save(buf, format="JPEG", quality=95)
return buf.getvalue()
def _b64(data: bytes) -> str:
return base64.b64encode(data).decode()
def _config_msg(**overrides) -> str:
msg = {"type": "session.config", "model": "test", "evs_enabled": False}
msg.update(overrides)
return json.dumps(msg)
def _frame_msg(jpeg: bytes | None = None) -> str:
if jpeg is None:
jpeg = _make_jpeg()
return json.dumps({"type": "video.frame", "data": _b64(jpeg)})
def _query_msg(text: str = "What do you see?") -> str:
return json.dumps({"type": "video.query", "text": text})
def _done_msg() -> str:
return json.dumps({"type": "video.done"})
def _audio_msg(pcm: bytes = b"\x00" * 320) -> str:
return json.dumps({"type": "audio.chunk", "data": _b64(pcm)})
def _make_sse_line(content: str) -> str:
payload = {"choices": [{"delta": {"content": content}}]}
return f"data: {json.dumps(payload)}\n\n"
class MockWebSocket:
"""Async-compatible mock WebSocket that feeds messages from a list."""
def __init__(self, messages: list[str]):
self._messages = list(messages)
self._idx = 0
self._sent: list[dict | bytes] = []
self._accepted = False
async def accept(self):
self._accepted = True
async def receive_text(self) -> str:
if self._idx >= len(self._messages):
# Simulate connection close by hanging forever (will be timed out)
await asyncio.sleep(999)
msg = self._messages[self._idx]
self._idx += 1
return msg
async def send_json(self, data: dict):
self._sent.append(data)
async def send_bytes(self, data: bytes):
self._sent.append(data)
@property
def sent_messages(self) -> list[dict]:
return [m for m in self._sent if isinstance(m, dict)]
def sent_types(self) -> list[str]:
return [m.get("type", "") for m in self.sent_messages]
class MockChatHandler:
"""Mock OmniOpenAIServingChat for testing _handle_query paths."""
def __init__(self, response=None):
self._response = response
async def create_chat_completion(self, request, raw_request=None):
if self._response is not None:
return self._response
# Default: return a simple streaming generator
async def _gen():
yield _make_sse_line("Hello")
yield _make_sse_line("World")
yield "data: [DONE]\n\n"
return _gen()
# ---------------------------------------------------------------------------
# _receive_config path tests
# ---------------------------------------------------------------------------
class TestReceiveConfig:
@pytest.mark.asyncio
async def test_config_timeout(self):
"""No message within config_timeout → error sent, session ends."""
ws = MockWebSocket([]) # no messages — will hang
handler = VideoStreamHandler(chat_handler=MockChatHandler(), config_timeout=0.05)
await handler.handle_session(ws)
assert ws._accepted
errors = [m for m in ws.sent_messages if m["type"] == "error"]
assert len(errors) == 1
assert "Timeout" in errors[0]["message"]
@pytest.mark.asyncio
async def test_config_invalid_json(self):
"""Non-JSON config message → error, session ends."""
ws = MockWebSocket(["not json"])
handler = VideoStreamHandler(chat_handler=MockChatHandler(), config_timeout=1.0)
await handler.handle_session(ws)
errors = [m for m in ws.sent_messages if m["type"] == "error"]
assert any("Invalid JSON" in e["message"] for e in errors)
@pytest.mark.asyncio
async def test_config_wrong_type(self):
"""Message with wrong type → error, session ends."""
ws = MockWebSocket([json.dumps({"type": "wrong"})])
handler = VideoStreamHandler(chat_handler=MockChatHandler(), config_timeout=1.0)
await handler.handle_session(ws)
errors = [m for m in ws.sent_messages if m["type"] == "error"]
assert any("Expected session.config" in e["message"] for e in errors)
@pytest.mark.asyncio
async def test_config_invalid_field_type(self):
"""Config with wrong field type → error, session ends."""
ws = MockWebSocket(
[
json.dumps(
{
"type": "session.config",
"model": "test",
"max_frames": "potato",
}
)
]
)
handler = VideoStreamHandler(chat_handler=MockChatHandler(), config_timeout=1.0)
await handler.handle_session(ws)
errors = [m for m in ws.sent_messages if m["type"] == "error"]
assert any("max_frames" in e["message"] for e in errors)
# ---------------------------------------------------------------------------
# Normal session flow
# ---------------------------------------------------------------------------
class TestNormalFlow:
@pytest.mark.asyncio
async def test_frame_query_done(self):
"""Happy path: config → frame → query → done → session.done."""
ws = MockWebSocket(
[
_config_msg(),
_frame_msg(),
_query_msg("Describe."),
_done_msg(),
]
)
handler = VideoStreamHandler(chat_handler=MockChatHandler(), idle_timeout=2.0)
await handler.handle_session(ws)
types = ws.sent_types()
assert "response.start" in types
assert "response.text.delta" in types
assert "response.text.done" in types
assert "session.done" in types
# Check text content was streamed
deltas = [m["delta"] for m in ws.sent_messages if m.get("type") == "response.text.delta"]
assert "Hello" in deltas
assert "World" in deltas
# response.text.done has full text
done_msg = next(m for m in ws.sent_messages if m.get("type") == "response.text.done")
assert done_msg["text"] == "HelloWorld"
@pytest.mark.asyncio
async def test_multiple_frames_before_query(self):
"""Multiple frames accumulate, query uses sampled frames."""
frames = [_frame_msg(_make_jpeg(r=i * 50)) for i in range(5)]
ws = MockWebSocket(
[
_config_msg(num_sample_frames=3),
*frames,
_query_msg(),
_done_msg(),
]
)
handler = VideoStreamHandler(chat_handler=MockChatHandler(), idle_timeout=2.0)
await handler.handle_session(ws)
assert "session.done" in ws.sent_types()
@pytest.mark.asyncio
async def test_evs_stats_in_done(self):
"""EVS stats sent before session.done when evs_enabled=True."""
frame = _frame_msg(_make_jpeg(100, 100, 100))
ws = MockWebSocket(
[
_config_msg(evs_enabled=True, evs_threshold=0.90),
frame,
frame, # second should be dropped
_done_msg(),
]
)
handler = VideoStreamHandler(chat_handler=MockChatHandler(), idle_timeout=2.0)
await handler.handle_session(ws)
evs_msgs = [m for m in ws.sent_messages if m.get("type") == "response.evs_stats"]
assert len(evs_msgs) == 1
assert evs_msgs[0]["retained_count"] == 1
assert evs_msgs[0]["dropped_count"] == 1
# ---------------------------------------------------------------------------
# _handle_query error paths
# ---------------------------------------------------------------------------
class TestHandleQueryErrors:
@pytest.mark.asyncio
async def test_query_with_no_frames(self):
"""Query before any frames → error, session continues."""
ws = MockWebSocket(
[
_config_msg(),
_query_msg("Hello?"),
_done_msg(),
]
)
handler = VideoStreamHandler(chat_handler=MockChatHandler(), idle_timeout=2.0)
await handler.handle_session(ws)
errors = [m for m in ws.sent_messages if m["type"] == "error"]
assert any("No frames" in e["message"] for e in errors)
# Session still ends cleanly
assert "session.done" in ws.sent_types()
@pytest.mark.asyncio
async def test_query_returns_error_response(self):
"""create_chat_completion returns ErrorResponse → error forwarded."""
from vllm.entrypoints.openai.engine.protocol import ErrorResponse
err = ErrorResponse(
message="model overloaded",
type="server_error",
code=503,
)
chat = AsyncMock()
chat.create_chat_completion = AsyncMock(return_value=err)
ws = MockWebSocket(
[
_config_msg(),
_frame_msg(),
_query_msg(),
_done_msg(),
]
)
handler = VideoStreamHandler(chat_handler=chat, idle_timeout=2.0)
await handler.handle_session(ws)
# Should see response.start, then error, then response.text.done
assert "response.start" in ws.sent_types()
assert "response.text.done" in ws.sent_types()
errors = [m for m in ws.sent_messages if m["type"] == "error"]
assert any("model overloaded" in e["message"] for e in errors)
@pytest.mark.asyncio
async def test_query_generator_raises(self):
"""Exception during streaming → error sent, session continues."""
async def _exploding_gen():
yield _make_sse_line("partial")
raise RuntimeError("CUDA OOM")
chat = MockChatHandler()
chat._response = None # override below
class BoomChat:
async def create_chat_completion(self, req, raw_request=None):
return _exploding_gen()
ws = MockWebSocket(
[
_config_msg(),
_frame_msg(),
_query_msg(),
_done_msg(),
]
)
handler = VideoStreamHandler(chat_handler=BoomChat(), idle_timeout=2.0)
await handler.handle_session(ws)
errors = [m for m in ws.sent_messages if m["type"] == "error"]
assert any("Query processing failed" in e["message"] for e in errors)
# Crucially: no raw exception message leaked
assert not any("CUDA OOM" in e["message"] for e in errors)
# Protocol: response.text.done always sent after response.start
assert "response.text.done" in ws.sent_types()
# Session still ends cleanly
assert "session.done" in ws.sent_types()
@pytest.mark.asyncio
async def test_empty_query_text_rejected(self):
"""video.query with empty text → error, session continues."""
ws = MockWebSocket(
[
_config_msg(),
_frame_msg(),
json.dumps({"type": "video.query", "text": ""}),
_done_msg(),
]
)
handler = VideoStreamHandler(chat_handler=MockChatHandler(), idle_timeout=2.0)
await handler.handle_session(ws)
errors = [m for m in ws.sent_messages if m["type"] == "error"]
assert any("non-empty" in e["message"] for e in errors)
assert "session.done" in ws.sent_types()
# ---------------------------------------------------------------------------
# Timeout paths
# ---------------------------------------------------------------------------
class TestTimeouts:
@pytest.mark.asyncio
async def test_idle_timeout(self):
"""No message after config within idle_timeout → error, session ends."""
ws = MockWebSocket([_config_msg()]) # config then nothing
handler = VideoStreamHandler(chat_handler=MockChatHandler(), idle_timeout=0.05)
await handler.handle_session(ws)
errors = [m for m in ws.sent_messages if m["type"] == "error"]
assert any("Idle timeout" in e["message"] for e in errors)
# ---------------------------------------------------------------------------
# Reader error paths
# ---------------------------------------------------------------------------
class TestReaderErrors:
@pytest.mark.asyncio
async def test_invalid_json_mid_session(self):
"""Invalid JSON mid-session → error sent, session continues."""
ws = MockWebSocket(
[
_config_msg(),
"{{bad json",
_done_msg(),
]
)
handler = VideoStreamHandler(chat_handler=MockChatHandler(), idle_timeout=2.0)
await handler.handle_session(ws)
errors = [m for m in ws.sent_messages if m["type"] == "error"]
assert any("Invalid JSON" in e["message"] for e in errors)
assert "session.done" in ws.sent_types()
@pytest.mark.asyncio
async def test_non_dict_message(self):
"""Non-object JSON → error sent, continues."""
ws = MockWebSocket(
[
_config_msg(),
json.dumps([1, 2, 3]),
_done_msg(),
]
)
handler = VideoStreamHandler(chat_handler=MockChatHandler(), idle_timeout=2.0)
await handler.handle_session(ws)
errors = [m for m in ws.sent_messages if m["type"] == "error"]
assert any("JSON objects" in e["message"] for e in errors)
@pytest.mark.asyncio
async def test_unknown_message_type(self):
"""Unknown type → error, session continues."""
ws = MockWebSocket(
[
_config_msg(),
json.dumps({"type": "teleport.now"}),
_done_msg(),
]
)
handler = VideoStreamHandler(chat_handler=MockChatHandler(), idle_timeout=2.0)
await handler.handle_session(ws)
errors = [m for m in ws.sent_messages if m["type"] == "error"]
assert any("Unknown message type" in e["message"] for e in errors)
assert "session.done" in ws.sent_types()
@pytest.mark.asyncio
async def test_invalid_base64_frame(self):
"""Invalid base64 in video.frame → error, continues."""
ws = MockWebSocket(
[
_config_msg(),
json.dumps({"type": "video.frame", "data": "!!!not-base64!!!"}),
_done_msg(),
]
)
handler = VideoStreamHandler(chat_handler=MockChatHandler(), idle_timeout=2.0)
await handler.handle_session(ws)
errors = [m for m in ws.sent_messages if m["type"] == "error"]
assert any("Invalid base64" in e["message"] for e in errors)
assert "session.done" in ws.sent_types()
# ---------------------------------------------------------------------------
# Concurrency: frames arrive during query processing
# ---------------------------------------------------------------------------
class TestConcurrency:
@pytest.mark.asyncio
async def test_frames_during_query(self):
"""Frames sent while a query is processing must be buffered."""
query_started = asyncio.Event()
query_can_finish = asyncio.Event()
captured_frame_count: list[int] = []
class SlowChat:
async def create_chat_completion(self, req, raw_request=None):
query_started.set()
await query_can_finish.wait()
async def _gen():
yield _make_sse_line("answer")
yield "data: [DONE]\n\n"
return _gen()
class InspectingSlowChat(SlowChat):
"""On the second query, record how many frames are in the request."""
_call_count = 0
async def create_chat_completion(self, req, raw_request=None):
self._call_count += 1
if self._call_count == 2:
# Count image_url blocks in the request to verify buffering
for msg in req.messages:
if isinstance(msg.get("content", msg), list):
content = msg.get("content", msg)
else:
content = getattr(msg, "content", [])
if isinstance(content, list):
n = sum(
1
for p in content
if (isinstance(p, dict) and p.get("type") == "image_url")
or (hasattr(p, "type") and p.type == "image_url")
)
captured_frame_count.append(n)
return await super().create_chat_completion(req, raw_request)
# Custom WebSocket that can inject frames after query starts
class TimedWebSocket(MockWebSocket):
def __init__(self):
self._q: asyncio.Queue[str] = asyncio.Queue()
self._sent: list[dict | bytes] = []
self._accepted = False
async def accept(self):
self._accepted = True
async def receive_text(self) -> str:
return await self._q.get()
def put(self, msg: str):
self._q.put_nowait(msg)
ws = TimedWebSocket()
chat = InspectingSlowChat()
handler = VideoStreamHandler(chat_handler=chat, idle_timeout=5.0)
session_task = asyncio.create_task(handler.handle_session(ws))
# 1. Config
ws.put(_config_msg())
await asyncio.sleep(0.01)
# 2. Initial frame + query
ws.put(_frame_msg(_make_jpeg(10, 10, 10)))
await asyncio.sleep(0.01)
ws.put(_query_msg("first"))
# 3. Wait for query to start processing
await asyncio.wait_for(query_started.wait(), timeout=2.0)
# 4. Send more frames WHILE query is running
ws.put(_frame_msg(_make_jpeg(200, 200, 200)))
ws.put(_frame_msg(_make_jpeg(50, 50, 50)))
await asyncio.sleep(0.05)
# 5. Let query finish
query_can_finish.set()
await asyncio.sleep(0.1)
# 6. Second query — should see all 3 frames (1 initial + 2 during)
query_started.clear()
query_can_finish.clear()
ws.put(_query_msg("second"))
await asyncio.wait_for(query_started.wait(), timeout=2.0)
query_can_finish.set()
await asyncio.sleep(0.1)
# 7. Done
ws.put(_done_msg())
await asyncio.wait_for(session_task, timeout=5.0)
assert "session.done" in ws.sent_types()
# Verify: the 2 frames sent during query 1 were buffered and
# included in query 2 (total 3 frames).
assert captured_frame_count == [3]
# ---------------------------------------------------------------------------
# SSE parsing (kept from original, these are valid unit tests)
# ---------------------------------------------------------------------------
class TestParseSSEDeltas:
def test_single_delta(self):
assert VideoStreamHandler._parse_sse_deltas(_make_sse_line("hello")) == ["hello"]
def test_multiple_deltas(self):
chunk = _make_sse_line("a") + _make_sse_line("b")
assert VideoStreamHandler._parse_sse_deltas(chunk) == ["a", "b"]
def test_done_skipped(self):
chunk = _make_sse_line("x") + "data: [DONE]\n\n"
assert VideoStreamHandler._parse_sse_deltas(chunk) == ["x"]
def test_empty_content_skipped(self):
p = json.dumps({"choices": [{"delta": {"content": ""}}]})
assert VideoStreamHandler._parse_sse_deltas(f"data: {p}\n\n") == []
def test_malformed_json_skipped(self):
chunk = "data: {bad}\n\n" + _make_sse_line("ok")
assert VideoStreamHandler._parse_sse_deltas(chunk) == ["ok"]
def test_empty_string(self):
assert VideoStreamHandler._parse_sse_deltas("") == []
def test_unicode(self):
assert VideoStreamHandler._parse_sse_deltas(_make_sse_line("你好🌍")) == ["你好🌍"]
@@ -0,0 +1,289 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Unit tests for VideoStreamSession (Phase 2 + 3)."""
from __future__ import annotations
import pytest
from tests.entrypoints.openai_api.conftest_video import (
make_gradient_jpeg,
make_jpeg,
)
from vllm_omni.entrypoints.openai.video_stream_session import (
VideoStreamConfig,
VideoStreamSession,
)
# ---------------------------------------------------------------------------
# VideoStreamConfig
# ---------------------------------------------------------------------------
class TestVideoStreamConfig:
def test_defaults(self):
cfg = VideoStreamConfig()
assert cfg.max_frames == 64
assert cfg.num_sample_frames == 16
assert cfg.evs_enabled is True
assert cfg.evs_threshold == 0.95
def test_from_dict(self):
cfg = VideoStreamConfig.from_dict(
{
"model": "test-model",
"max_frames": 32,
"evs_threshold": 0.90,
"unknown_field": "ignored",
}
)
assert cfg.model == "test-model"
assert cfg.max_frames == 32
assert cfg.evs_threshold == 0.90
def test_from_dict_empty(self):
cfg = VideoStreamConfig.from_dict({})
assert cfg.model == ""
assert cfg.max_frames == 64
def test_from_dict_invalid_type(self):
with pytest.raises(TypeError, match="max_frames.*expected int.*got str"):
VideoStreamConfig.from_dict({"max_frames": "potato"})
def test_from_dict_invalid_bool(self):
with pytest.raises(TypeError, match="evs_enabled.*expected bool"):
VideoStreamConfig.from_dict({"evs_enabled": "yes"})
def test_from_dict_invalid_modalities(self):
with pytest.raises(TypeError, match="modalities.*expected list"):
VideoStreamConfig.from_dict({"modalities": 42})
def test_from_dict_evs_threshold_int_accepted(self):
"""JSON doesn't distinguish int/float — int 1 is a valid threshold."""
cfg = VideoStreamConfig.from_dict({"evs_threshold": 1})
assert cfg.evs_threshold == 1
# ---------------------------------------------------------------------------
# Frame buffer & sliding window (uses deque)
# ---------------------------------------------------------------------------
class TestFrameBuffer:
def test_add_frame_basic(self):
cfg = VideoStreamConfig(evs_enabled=False, max_frames=10)
session = VideoStreamSession(cfg)
assert session.add_frame(make_jpeg()) is True
assert session.frame_count == 1
def test_add_frame_too_large(self):
cfg = VideoStreamConfig(evs_enabled=False, max_frames=10)
session = VideoStreamSession(cfg)
huge = b"\xff" * (10 * 1024 * 1024 + 1) # just over 10 MB
with pytest.raises(ValueError, match="Frame too large"):
session.add_frame(huge)
def test_sliding_window(self):
cfg = VideoStreamConfig(evs_enabled=False, max_frames=3)
session = VideoStreamSession(cfg)
for i in range(5):
session.add_frame(make_jpeg(r=i * 50))
assert session.frame_count == 3
def test_sliding_window_keeps_newest(self):
cfg = VideoStreamConfig(evs_enabled=False, max_frames=2)
session = VideoStreamSession(cfg)
f1 = make_jpeg(10, 10, 10)
f2 = make_jpeg(20, 20, 20)
f3 = make_jpeg(30, 30, 30)
session.add_frame(f1)
session.add_frame(f2)
session.add_frame(f3)
sampled = session.sample_frames()
assert len(sampled) == 2
assert sampled[0] == f2
assert sampled[1] == f3
# ---------------------------------------------------------------------------
# EVS integration
# ---------------------------------------------------------------------------
class TestEVSIntegration:
def test_evs_drops_identical_frames(self):
cfg = VideoStreamConfig(evs_enabled=True, evs_threshold=0.90)
session = VideoStreamSession(cfg)
frame = make_jpeg(100, 100, 100)
assert session.add_frame(frame) is True
assert session.add_frame(frame) is False
assert session.frame_count == 1
def test_evs_keeps_different_frames(self):
cfg = VideoStreamConfig(evs_enabled=True, evs_threshold=0.95)
session = VideoStreamSession(cfg)
for i in range(5):
assert session.add_frame(make_gradient_jpeg(seed=i)) is True
assert session.frame_count == 5
def test_evs_disabled(self):
cfg = VideoStreamConfig(evs_enabled=False)
session = VideoStreamSession(cfg)
frame = make_jpeg()
assert session.add_frame(frame) is True
assert session.add_frame(frame) is True
assert session.frame_count == 2
def test_evs_stats(self):
cfg = VideoStreamConfig(evs_enabled=True, evs_threshold=0.90)
session = VideoStreamSession(cfg)
frame = make_jpeg()
session.add_frame(frame)
session.add_frame(frame)
stats = session.evs_stats
assert stats is not None
assert stats["retained_count"] == 1
assert stats["dropped_count"] == 1
def test_evs_stats_none_when_disabled(self):
cfg = VideoStreamConfig(evs_enabled=False)
session = VideoStreamSession(cfg)
assert session.evs_stats is None
# ---------------------------------------------------------------------------
# Uniform sampling
# ---------------------------------------------------------------------------
class TestSampling:
def test_sample_exact(self):
cfg = VideoStreamConfig(evs_enabled=False, num_sample_frames=3, max_frames=10)
session = VideoStreamSession(cfg)
frames = [make_gradient_jpeg(i) for i in range(3)]
for f in frames:
session.add_frame(f)
sampled = session.sample_frames()
assert len(sampled) == 3
assert sampled == frames
def test_sample_fewer_than_requested(self):
cfg = VideoStreamConfig(evs_enabled=False, num_sample_frames=10, max_frames=64)
session = VideoStreamSession(cfg)
for i in range(3):
session.add_frame(make_gradient_jpeg(i))
assert len(session.sample_frames()) == 3
def test_sample_uniform(self):
cfg = VideoStreamConfig(evs_enabled=False, num_sample_frames=4, max_frames=64)
session = VideoStreamSession(cfg)
for i in range(10):
session.add_frame(make_gradient_jpeg(i))
sampled = session.sample_frames()
assert len(sampled) == 4
expected = [session._frames[i] for i in [0, 3, 6, 9]]
assert sampled == expected
def test_sample_empty(self):
cfg = VideoStreamConfig(evs_enabled=False)
session = VideoStreamSession(cfg)
assert session.sample_frames() == []
def test_sample_single_frame_from_multi_frame_buffer(self):
cfg = VideoStreamConfig(evs_enabled=False, num_sample_frames=1, max_frames=64)
session = VideoStreamSession(cfg)
first = make_gradient_jpeg(0)
second = make_gradient_jpeg(1)
session.add_frame(first)
session.add_frame(second)
assert session.sample_frames() == [second]
# ---------------------------------------------------------------------------
# Audio buffer (Phase 3)
# ---------------------------------------------------------------------------
class TestAudioBuffer:
def test_add_audio_chunk(self):
session = VideoStreamSession(VideoStreamConfig())
assert session.has_audio is False
session.add_audio_chunk(b"\x00" * 100)
assert session.has_audio is True
def test_clear_audio(self):
session = VideoStreamSession(VideoStreamConfig())
session.add_audio_chunk(b"\x00" * 100)
session.clear_audio()
assert session.has_audio is False
# ---------------------------------------------------------------------------
# build_chat_request
# ---------------------------------------------------------------------------
class TestBuildChatRequest:
def test_video_only_request(self):
cfg = VideoStreamConfig(model="test-model", evs_enabled=False, num_sample_frames=4)
session = VideoStreamSession(cfg)
for i in range(4):
session.add_frame(make_gradient_jpeg(i))
request = session.build_chat_request("Describe this scene.")
assert request.model == "test-model"
assert request.stream is True
content = request.messages[0]["content"]
assert len(content) == 5 # 4 image_url + 1 text
image_parts = [p for p in content if p["type"] == "image_url"]
text_parts = [p for p in content if p["type"] == "text"]
assert len(image_parts) == 4
assert len(text_parts) == 1
assert text_parts[0]["text"] == "Describe this scene."
mm_kw = getattr(request, "mm_processor_kwargs", None)
assert mm_kw is None or not mm_kw.get("use_audio_in_video", False)
def test_video_plus_audio_request(self):
cfg = VideoStreamConfig(model="test-model", evs_enabled=False, num_sample_frames=2)
session = VideoStreamSession(cfg)
session.add_frame(make_gradient_jpeg(0))
session.add_frame(make_gradient_jpeg(1))
session.add_audio_chunk(b"\x00" * 3200)
request = session.build_chat_request("What is being said?")
content = request.messages[0]["content"]
assert len(content) == 4 # 2 image_url + 1 audio_url + 1 text
audio_parts = [p for p in content if p["type"] == "audio_url"]
assert len(audio_parts) == 1
# RFC 3551: audio/L16 for linear 16-bit PCM
assert audio_parts[0]["audio_url"]["url"].startswith("data:audio/L16;rate=16000;base64,")
mm_kw = getattr(request, "mm_processor_kwargs", None) or {}
assert mm_kw.get("use_audio_in_video") is True
def test_image_url_is_valid_base64(self):
cfg = VideoStreamConfig(evs_enabled=False, num_sample_frames=1)
session = VideoStreamSession(cfg)
session.add_frame(make_jpeg(200, 100, 50))
request = session.build_chat_request("test")
content = request.messages[0]["content"]
img_url = content[0]["image_url"]["url"]
assert img_url.startswith("data:image/jpeg;base64,")
import base64
b64_data = img_url.split(",", 1)[1]
decoded = base64.b64decode(b64_data)
assert len(decoded) > 0
def test_clear_audio_after_query(self):
session = VideoStreamSession(VideoStreamConfig(evs_enabled=False))
session.add_frame(make_jpeg())
session.add_audio_chunk(b"\x00" * 100)
session.build_chat_request("test")
session.clear_audio()
assert session.has_audio is False
assert session.frame_count == 1
+46 -3
View File
@@ -1,5 +1,6 @@
from __future__ import annotations
import argparse
import queue
from collections.abc import Callable
from types import SimpleNamespace
@@ -14,6 +15,7 @@ from vllm.v1.engine.exceptions import EngineDeadError, EngineGenerateError
from vllm_omni.entrypoints.async_omni import AsyncOmni
from vllm_omni.entrypoints.omni import Omni
from vllm_omni.entrypoints.omni_base import OmniEngineDeadError
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
@@ -165,6 +167,31 @@ def _patch_engine(monkeypatch: pytest.MonkeyPatch, engine: FakeAsyncOmniEngine)
monkeypatch.setattr("vllm_omni.entrypoints.omni_base.omni_snapshot_download", lambda model: model)
def test_from_cli_args_only_nulls_untyped_override_fields(monkeypatch: pytest.MonkeyPatch):
from vllm_omni.entrypoints.omni import Omni
captured: dict[str, Any] = {}
def fake_engine(*args: Any, **kwargs: Any) -> FakeAsyncOmniEngine:
captured.update(kwargs)
return FakeAsyncOmniEngine()
monkeypatch.setattr("vllm_omni.entrypoints.omni_base.AsyncOmniEngine", fake_engine)
monkeypatch.setattr("vllm_omni.entrypoints.omni_base.omni_snapshot_download", lambda model: model)
monkeypatch.setattr("sys.argv", ["prog"])
parser = argparse.ArgumentParser()
parser.add_argument("--gpu-memory-utilization", type=float, default=0.9)
parser.add_argument("--hsdp-shard-size", type=int, default=-1)
args = parser.parse_args([])
args.model = "fake-model"
Omni.from_cli_args(args, parser=parser)
assert captured["gpu_memory_utilization"] is None
assert captured["hsdp_shard_size"] == -1
def _make_base():
from vllm_omni.entrypoints.omni_base import OmniBase
@@ -335,6 +362,18 @@ def _enqueue_error_message(engine: FakeAsyncOmniEngine, msg: dict[str, Any]) ->
)
def _enqueue_fatal_error_message(engine: FakeAsyncOmniEngine, msg: dict[str, Any]) -> None:
engine.output_q.put_nowait(
{
"type": "error",
"fatal": True,
"request_id": msg["request_id"],
"stage_id": 2,
"error": "engine dead",
}
)
@pytest.mark.asyncio
async def test_get_supported_tasks_returns_engine_supported_tasks():
omni = object.__new__(AsyncOmni)
@@ -546,18 +585,22 @@ async def test_async_omni_abort_forwards_to_engine(monkeypatch: pytest.MonkeyPat
@pytest.mark.asyncio
async def test_async_omni_propagates_engine_error(monkeypatch: pytest.MonkeyPatch):
engine = FakeAsyncOmniEngine(stage_metadata=THREE_STAGE_META, on_add_request=_enqueue_error_message)
async def test_async_omni_propagates_fatal_error_context(monkeypatch: pytest.MonkeyPatch):
engine = FakeAsyncOmniEngine(stage_metadata=THREE_STAGE_META, on_add_request=_enqueue_fatal_error_message)
_patch_engine(monkeypatch, engine)
app = AsyncOmni("dummy-model")
try:
with pytest.raises(RuntimeError, match="engine boom"):
with pytest.raises(EngineDeadError, match="engine dead") as exc_info:
async for _ in app.generate(prompt="hello", request_id="req-1"):
pass
finally:
app.shutdown()
assert isinstance(exc_info.value, OmniEngineDeadError)
assert str(exc_info.value) == "engine dead"
assert getattr(exc_info.value, "error_stage_id") == 2
def test_omni_generate_py_generator_yields_final_outputs_for_each_request(monkeypatch: pytest.MonkeyPatch):
sampling_params = [SamplingParams(max_tokens=8) for _ in range(3)]
@@ -11,7 +11,8 @@ from tests.examples.helpers import EXAMPLES, ExampleRunner, ReadmeSnippet
from tests.helpers.assertions import assert_image_valid
from tests.helpers.mark import hardware_marks
pytestmark = [pytest.mark.advanced_model, pytest.mark.example, *hardware_marks(res={"cuda": "H100"})]
pytestmark = [pytest.mark.full_model, pytest.mark.example, *hardware_marks(res={"cuda": "H100"})]
T2I_SCRIPT = EXAMPLES / "offline_inference" / "text_to_image" / "text_to_image.py"
README_PATH = T2I_SCRIPT.with_name("README.md")
@@ -4,9 +4,6 @@ See examples/online_serving/qwen2_5_omni/README.md
"""
import os
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
from pathlib import Path
import pytest
@@ -21,7 +18,9 @@ from tests.helpers.media import convert_audio_file_to_text, cosine_similarity_te
from tests.helpers.runtime import OmniServerParams
from tests.helpers.stage_config import get_deploy_config_path
pytestmark = [pytest.mark.advanced_model, pytest.mark.example]
pytestmark = [pytest.mark.full_model, pytest.mark.example, pytest.mark.omni]
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
models = ["Qwen/Qwen2.5-Omni-7B"]
@@ -40,8 +39,6 @@ test_params = [
common_args = ["python", os.path.join(example_dir, "openai_chat_completion_client_for_multimodal_generation.py")]
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "L4", "rocm": "MI325"}, num_cards={"cuda": 4, "rocm": 2})
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
def test_send_multimodal_request_001(omni_server) -> None:
@@ -77,8 +74,6 @@ def test_send_multimodal_request_001(omni_server) -> None:
# TODO: Verify the E2E latency after confirmation baseline.
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "L4", "rocm": "MI325"}, num_cards={"cuda": 4, "rocm": 2})
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
def test_send_multimodal_request_002(omni_server) -> None:
@@ -114,8 +109,6 @@ def test_send_multimodal_request_002(omni_server) -> None:
# TODO: Verify the E2E latency after confirmation baseline.
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "L4", "rocm": "MI325"}, num_cards={"cuda": 4, "rocm": 2})
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
def test_send_multimodal_request_003(omni_server) -> None:
@@ -141,8 +134,6 @@ def test_send_multimodal_request_003(omni_server) -> None:
# TODO: Verify the E2E latency after confirmation baseline.
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "L4", "rocm": "MI325"}, num_cards={"cuda": 4, "rocm": 2})
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
def test_modality_control_001(omni_server) -> None:
@@ -171,8 +162,6 @@ def test_modality_control_001(omni_server) -> None:
# TODO: Verify the E2E latency after confirmation baseline.
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "L4", "rocm": "MI325"}, num_cards={"cuda": 4, "rocm": 2})
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
def test_modality_control_002(omni_server) -> None:
@@ -200,8 +189,6 @@ def test_modality_control_002(omni_server) -> None:
# TODO: Verify the E2E latency after confirmation baseline.
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "L4", "rocm": "MI325"}, num_cards={"cuda": 4, "rocm": 2})
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
def test_modality_control_003(omni_server) -> None:
@@ -238,8 +225,6 @@ def test_modality_control_003(omni_server) -> None:
# TODO: Verify the E2E latency after confirmation baseline.
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "L4", "rocm": "MI325"}, num_cards={"cuda": 4, "rocm": 2})
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
def test_stream_001(omni_server) -> None:
@@ -4,9 +4,6 @@ See examples/online_serving/qwen3_omni/README.md
"""
import os
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
from pathlib import Path
import pytest
@@ -21,7 +18,9 @@ from tests.helpers.media import convert_audio_file_to_text, cosine_similarity_te
from tests.helpers.runtime import OmniServerParams
from tests.helpers.stage_config import get_deploy_config_path
pytestmark = [pytest.mark.advanced_model, pytest.mark.example]
pytestmark = [pytest.mark.full_model, pytest.mark.example, pytest.mark.omni]
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
models = ["Qwen/Qwen3-Omni-30B-A3B-Instruct"]
@@ -39,8 +38,6 @@ test_params = [
common_args = ["python", os.path.join(example_dir, "openai_chat_completion_client_for_multimodal_generation.py")]
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100", "rocm": "MI325"}, num_cards=2)
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
def test_send_multimodal_request_001(omni_server) -> None:
@@ -69,8 +66,6 @@ def test_send_multimodal_request_001(omni_server) -> None:
# TODO: Verify the E2E latency after confirmation baseline.
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100", "rocm": "MI325"}, num_cards=2)
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
def test_send_multimodal_request_002(omni_server) -> None:
@@ -102,8 +97,6 @@ def test_send_multimodal_request_002(omni_server) -> None:
# TODO: Verify the E2E latency after confirmation baseline.
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100", "rocm": "MI325"}, num_cards=2)
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
def test_send_multimodal_request_003(omni_server) -> None:
@@ -119,8 +112,6 @@ def test_send_multimodal_request_003(omni_server) -> None:
# TODO: Verify the E2E latency after confirmation baseline.
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100", "rocm": "MI325"}, num_cards=2)
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
def test_modality_control_001(omni_server) -> None:
@@ -143,8 +134,6 @@ def test_modality_control_001(omni_server) -> None:
# TODO: Verify the E2E latency after confirmation baseline.
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100", "rocm": "MI325"}, num_cards=2)
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
def test_modality_control_002(omni_server) -> None:
@@ -167,8 +156,6 @@ def test_modality_control_002(omni_server) -> None:
# TODO: Verify the E2E latency after confirmation baseline.
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100", "rocm": "MI325"}, num_cards=2)
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
def test_modality_control_003(omni_server) -> None:
@@ -199,8 +186,6 @@ def test_modality_control_003(omni_server) -> None:
# TODO: Verify the E2E latency after confirmation baseline.
@pytest.mark.advanced_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100", "rocm": "MI325"}, num_cards=2)
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
def test_stream_001(omni_server) -> None:
@@ -18,7 +18,7 @@ from tests.helpers.assertions import assert_image_valid
from tests.helpers.mark import hardware_marks
from tests.helpers.runtime import OmniServer, OmniServerParams
pytestmark = [pytest.mark.advanced_model, pytest.mark.example, *hardware_marks(res={"cuda": "H100"})]
pytestmark = [pytest.mark.full_model, pytest.mark.example, *hardware_marks(res={"cuda": "H100"})]
T2I_ONLINE_CLIENT = EXAMPLES / "online_serving" / "text_to_image" / "openai_chat_client.py"
EXAMPLE_OUTPUT_SUBFOLDER = "example_online_t2i"
+27 -11
View File
@@ -11,7 +11,9 @@ import numpy as np
import soundfile as sf
from PIL import Image
from tests.helpers.media import cosine_similarity_text
from tests.helpers.media import (
cosine_similarity_text,
)
_GENDER_PIPELINE = None
_GENDER_PIPELINE_LOCK = threading.Lock()
@@ -56,7 +58,7 @@ def assert_image_diffusion_response(
f"Expected {num_outputs_per_prompt} images, got {len(response.images)}"
)
if run_level == "advanced_model":
if run_level in {"advanced_model", "full_model"}:
width = extra_body.get("width")
height = extra_body.get("height")
@@ -407,7 +409,8 @@ def assert_omni_response(response: Any, request_config: dict[str, Any], run_leve
modalities = request_config.get("modalities", ["text", "audio"])
if run_level == "advanced_model":
if run_level in {"advanced_model", "full_model"}:
# Verify output success
if "audio" in modalities:
assert response.audio_content is not None, "No audio output is generated"
print(f"audio content is: {response.audio_content}")
@@ -417,12 +420,11 @@ def assert_omni_response(response: Any, request_config: dict[str, Any], run_leve
response.audio_bytes,
speaker,
)
if "text" in modalities:
assert response.text_content is not None, "No text output is generated"
print(f"text content is: {response.text_content}")
# Verify image description
# Verify keywords in output
word_types = ["text", "image", "audio", "video"]
keywords_dict = request_config.get("key_words", {})
for word_type in word_types:
@@ -441,11 +443,25 @@ def assert_omni_response(response: Any, request_config: dict[str, Any], run_leve
)
# Verify similarity (Whisper transcript vs streamed/detokenized text)
if "text" in modalities and "audio" in modalities:
assert response.similarity is not None and response.similarity > 0.9, (
"The audio content is not same as the text"
)
print(f"similarity is: {response.similarity}")
if "audio" in modalities:
audio_ref_text = request_config.get("audio_ref_text")
if "text" in modalities:
transcript = (response.audio_content or "").strip()
text_output = (response.text_content or "").strip()
similarity = cosine_similarity_text(
transcript.lower(),
text_output.lower(),
)
assert similarity > 0.9, "The audio content is not same as the text"
print(f"similarity is: {similarity}")
if audio_ref_text:
audio_similarity = cosine_similarity_text(
response.audio_content.lower(),
str(audio_ref_text).lower(),
)
assert audio_similarity > 0.9, (
f"The audio content does not match reference text: similarity={audio_similarity:.3f}"
)
def assert_audio_speech_response(response: Any, request_config: dict[str, Any], run_level: str) -> None:
@@ -464,7 +480,7 @@ def assert_audio_speech_response(response: Any, request_config: dict[str, Any],
elif req_fmt == "wav" and response.audio_format:
assert req_fmt in response.audio_format
if run_level == "advanced_model" and req_fmt != "pcm":
if run_level in {"advanced_model", "full_model"} and req_fmt != "pcm":
expected_text = request_config.get("input")
if expected_text:
transcript = (response.audio_content or "").strip()
+2 -2
View File
@@ -6,8 +6,8 @@ def pytest_addoption(parser):
"--run-level",
action="store",
default="core_model",
choices=["core_model", "advanced_model"],
help="Test level to run: L2, L3",
choices=["core_model", "advanced_model", "full_model"],
help="Test level to run: L2, L3, L4",
)
+1 -1
View File
@@ -36,7 +36,7 @@ def omni_server(request: pytest.FixtureRequest, run_level: str, model_prefix: st
model = model_prefix + params.model
port = params.port
stage_config_path = params.stage_config_path
if run_level == "advanced_model" and stage_config_path is not None:
if run_level in {"advanced_model", "full_model"} and stage_config_path is not None:
with open(stage_config_path, encoding="utf-8") as f:
cfg = yaml.safe_load(f) or {}
# Strip ``load_format: dummy`` (CI overlay default) so advanced_model
+13 -4
View File
@@ -3,6 +3,7 @@
import base64
import concurrent.futures
import gc
import hashlib
import io
import logging
import math
@@ -66,6 +67,7 @@ def generate_synthetic_audio(
num_channels: int,
sample_rate: int = 48000,
*,
phrase_text: str = "test",
force_regenerate: bool = False,
cache_dir: Path | str | None = None,
) -> dict[str, Any]:
@@ -74,12 +76,16 @@ def generate_synthetic_audio(
Caches the WAV under ``cache_dir`` when given, else under the default temp
subdirectory. Reuses the file when the same
``duration`` / ``num_channels`` / ``sample_rate`` are requested unless
``force_regenerate`` is true.
``duration`` / ``num_channels`` / ``sample_rate`` / ``phrase_text`` are
requested unless ``force_regenerate`` is true.
The cache filename includes a SHA-256 digest of ``phrase_text`` so different
phrases never share a WAV cache entry.
"""
root = _resolve_synthetic_media_cache_dir(cache_dir)
root.mkdir(parents=True, exist_ok=True)
cache_path = root / f"synth_audio_d{duration}_ch{num_channels}_sr{sample_rate}.wav"
phrase_key = hashlib.sha256(phrase_text.encode("utf-8")).hexdigest()
cache_path = root / f"synth_audio_d{duration}_ch{num_channels}_sr{sample_rate}_pt{phrase_key}.wav"
if not force_regenerate and cache_path.is_file():
data, _sr = sf.read(str(cache_path), dtype="float32", always_2d=True)
@@ -204,7 +210,6 @@ def generate_synthetic_audio(
enhanced = enhanced / peak * 0.95
return enhanced.astype(np.float32)
phrase_text = "test"
num_samples = int(sample_rate * max(1, duration))
audio_data = np.zeros((num_samples, num_channels), dtype=np.float32)
@@ -442,12 +447,16 @@ def generate_synthetic_image(
*,
force_regenerate: bool = False,
cache_dir: Path | str | None = None,
seed: int | None = None,
) -> dict[str, Any]:
"""
Random colored squares on white background. Caches JPEG by ``width`` /
``height`` unless ``force_regenerate`` is true. Cache root: ``cache_dir``
if given, else the default temp subdirectory.
"""
if seed is not None:
random.seed(seed)
root = _resolve_synthetic_media_cache_dir(cache_dir)
root.mkdir(parents=True, exist_ok=True)
cache_path = root / f"synth_image_w{width}_h{height}.jpg"
+3 -10
View File
@@ -35,7 +35,6 @@ from tests.helpers.env import run_forced_gpu_cleanup_round
from tests.helpers.media import (
_merge_base64_audio_to_segment,
convert_audio_bytes_to_text,
cosine_similarity_text,
decode_b64_image,
)
from vllm_omni.config.stage_config import resolve_deploy_yaml
@@ -500,7 +499,6 @@ class OmniResponse:
audio_content: str | None = None
audio_format: str | None = None
audio_bytes: bytes | None = None
similarity: float | None = None
e2e_latency: float | None = None
success: bool = False
error_message: str | None = None
@@ -542,19 +540,15 @@ class OpenAIClientHandler:
text_content += content
result.e2e_latency = time.perf_counter() - start_time
audio_content = None
similarity = None
if audio_data:
merged_seg = _merge_base64_audio_to_segment(audio_data)
wav_buf = BytesIO()
merged_seg.export(wav_buf, format="wav")
result.audio_bytes = wav_buf.getvalue()
audio_content = convert_audio_bytes_to_text(result.audio_bytes)
if audio_content and text_content:
similarity = cosine_similarity_text(audio_content.lower(), text_content.lower())
result.text_content = text_content
result.audio_data = audio_data
result.audio_content = audio_content
result.similarity = similarity
result.success = True
except Exception as e:
result.error_message = f"Stream processing error: {str(e)}"
@@ -578,15 +572,11 @@ class OpenAIClientHandler:
result.cached_tokens = details.cached_tokens
result.e2e_latency = time.perf_counter() - start_time
audio_content = None
similarity = None
if audio_data:
result.audio_bytes = base64.b64decode(audio_data)
audio_content = convert_audio_bytes_to_text(result.audio_bytes)
if audio_content and text_content:
similarity = cosine_similarity_text(audio_content.lower(), text_content.lower())
result.text_content = text_content
result.audio_content = audio_content
result.similarity = similarity
result.success = True
except Exception as e:
result.error_message = f"Non-stream processing error: {str(e)}"
@@ -630,6 +620,9 @@ class OpenAIClientHandler:
mm = dict(extra_body.get("mm_processor_kwargs") or {})
mm["use_audio_in_video"] = True
extra_body["mm_processor_kwargs"] = mm
if "sampling_params_list" in request_config:
extra_body["sampling_params_list"] = request_config["sampling_params_list"]
create_kwargs: dict[str, Any] = {
"model": request_config.get("model"),
"messages": request_config.get("messages"),
Loaded 100 of 307 files, more files were not shown because too many files have changed in this diff. Show more