Merge origin/main into codex-vae-spatial-decode-auto

Signed-off-by: Hongsheng Liu <liuhongsheng4@huawei.com>
This commit is contained in:
Hongsheng Liu committed 2026-08-13 23:49:11 +08:00
commit 089851e55a
244 files changed
+16669 -2175

No files matched your search

@@ -0,0 +1,92 @@
# SPDX-License-Identifier: Apache-2.0
"""Offline Daily-Omni sources: local mirrors must not fall back to the Hub id."""
import json
import os
import tarfile
from pathlib import Path
import pytest
from vllm_omni.benchmarks.data_modules.daily_omni_dataset import (
daily_omni_local_qa_json,
daily_omni_local_videos_dir,
resolve_daily_omni_local_root,
)
pytestmark = [pytest.mark.core_model, pytest.mark.cpu, pytest.mark.benchmark]
def _write_qa_json(root: Path) -> Path:
qa = root / "qa.json"
qa.write_text(json.dumps([{"Question": "q", "Answer": "A", "video_id": "vid0"}]), encoding="utf-8")
return qa
def test_resolve_local_root_returns_none_for_hub_id() -> None:
assert resolve_daily_omni_local_root("liarliar/Daily-Omni") is None
assert resolve_daily_omni_local_root("") is None
assert resolve_daily_omni_local_root(None) is None
def test_plain_local_mirror(tmp_path: Path) -> None:
_write_qa_json(tmp_path)
(tmp_path / "Videos" / "vid0").mkdir(parents=True)
root = resolve_daily_omni_local_root(str(tmp_path))
assert root == tmp_path.resolve()
assert daily_omni_local_qa_json(root) == (tmp_path / "qa.json").resolve()
assert daily_omni_local_videos_dir(root) == root / "Videos"
def test_hf_cache_dir_resolves_to_snapshot(tmp_path: Path) -> None:
cache_dir = tmp_path / "datasets--liarliar--Daily-Omni"
snapshot = cache_dir / "snapshots" / "deadbeef"
snapshot.mkdir(parents=True)
_write_qa_json(snapshot)
(cache_dir / "refs").mkdir()
(cache_dir / "refs" / "main").write_text("deadbeef", encoding="utf-8")
root = resolve_daily_omni_local_root(str(cache_dir))
assert root == snapshot.resolve()
assert daily_omni_local_qa_json(root) == (snapshot / "qa.json").resolve()
def test_hf_cache_dir_without_refs_picks_newest_snapshot(tmp_path: Path) -> None:
cache_dir = tmp_path / "datasets--liarliar--Daily-Omni"
older = cache_dir / "snapshots" / "aaa"
newer = cache_dir / "snapshots" / "bbb"
older.mkdir(parents=True)
newer.mkdir(parents=True)
os.utime(older, (1, 1))
os.utime(newer, (10, 10))
assert resolve_daily_omni_local_root(str(cache_dir)) == newer.resolve()
def test_videos_tar_is_extracted(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("HF_HOME", str(tmp_path / "hf_home"))
root = tmp_path / "mirror"
(root / "Videos" / "vid0").mkdir(parents=True)
(root / "Videos" / "vid0" / "vid0_video.mp4").write_bytes(b"fake")
with tarfile.open(root / "Videos.tar", "w") as tf:
tf.add(root / "Videos", arcname="Videos")
# Only the tarball is left in the mirror.
for child in (root / "Videos").rglob("*"):
if child.is_file():
child.unlink()
(root / "Videos" / "vid0").rmdir()
(root / "Videos").rmdir()
videos_dir = daily_omni_local_videos_dir(root)
assert videos_dir is not None
assert (videos_dir / "vid0" / "vid0_video.mp4").is_file()
# Second call reuses the extraction instead of redoing it.
assert daily_omni_local_videos_dir(root) == videos_dir
def test_missing_qa_json_reports_none(tmp_path: Path) -> None:
root = resolve_daily_omni_local_root(str(tmp_path))
assert daily_omni_local_qa_json(root) is None
assert daily_omni_local_videos_dir(root) is None
+7 -19
View File
@@ -2,9 +2,8 @@
The ``minicpm-interleave`` mode is an accuracy-critical protocol: MiniCPM-o only reaches
OpenBMB's reported Daily-Omni score when frames and 1s audio segments arrive strictly
interleaved, with ``max_slice_nums=1`` / ``use_image_id=False`` and an empty MiniCPM
system message (not the Qwen system prompt). These tests pin that contract so a refactor
cannot silently regress the score.
interleaved, with ``max_slice_nums=1`` / ``use_image_id=False`` and no Qwen system prompt.
These tests pin that contract so a refactor cannot silently regress the score.
vllm stubs are installed by tests/benchmarks/conftest.py before collection.
"""
@@ -99,22 +98,13 @@ def _stub_extract(monkeypatch, dataset: DailyOmniDataset, counter: list[int]) ->
# ---------------------------------------------------------------------------
@pytest.mark.parametrize(("n", "k"), [(10, 4), (100, 64), (1000, 64), (7, 7), (3, 5), (1, 1)])
def test_uniform_sample_indices_matches_openbmb_midpoint(n: int, k: int) -> None:
"""Pin OpenBMB midpoint-bin sampling (not np.linspace endpoints)."""
@pytest.mark.parametrize(("n", "k"), [(10, 4), (100, 64), (7, 7), (3, 5), (1, 1)])
def test_uniform_sample_indices_matches_numpy_linspace(n: int, k: int) -> None:
got = _uniform_sample_indices(n, k)
if n <= k:
assert got == list(range(n))
else:
gap = n / k
expected = [int(i * gap + gap / 2) for i in range(k)]
assert got == expected
# Endpoints differ from linspace for typical Daily-Omni downsample sizes.
linspace = [int(i) for i in np.linspace(0, n - 1, k, dtype=int)]
if n == 1000 and k == 64:
assert got[0] == 7 and got[-1] == 992
assert linspace[0] == 0 and linspace[-1] == 999
assert got != linspace
assert got == [int(i) for i in np.linspace(0, n - 1, k, dtype=int)]
def test_uniform_sample_indices_non_positive_k() -> None:
@@ -223,16 +213,14 @@ def test_minicpm_interleave_missing_local_video_returns_none(qa_json, tmp_path)
# ---------------------------------------------------------------------------
def test_minicpm_interleave_keeps_empty_system_message(monkeypatch, qa_json, video_dir) -> None:
"""Official MiniCPM omni mode still sends role=system with empty content."""
def test_minicpm_interleave_omits_qwen_system_message(monkeypatch, qa_json, video_dir) -> None:
ds = _make_dataset(qa_json, video_dir, pack_mode="minicpm-interleave", input_mode="all")
_stub_extract(monkeypatch, ds, [])
parts, _extra, _position = ds._compose_daily_omni_multimodal(_VIDEO_ID, None)
messages = ds._build_daily_omni_openai_messages(parts, "q?", {"A": "a"})
assert [m["role"] for m in messages] == ["system", "user"]
assert messages[0]["content"][0]["text"] == ""
assert [m["role"] for m in messages] == ["user"]
def test_qwen_pack_mode_keeps_system_message(qa_json, video_dir) -> None:
+4 -48
View File
@@ -6,7 +6,7 @@ Unit tests for StageConfigFactory and related classes.
import importlib
import warnings
from dataclasses import dataclass, fields
from dataclasses import dataclass
from pathlib import Path
from unittest.mock import patch
@@ -34,9 +34,8 @@ from vllm_omni.config.stage_config import (
load_deploy_config,
merge_pipeline_deploy,
pipeline_cfg_resolver,
strip_parent_engine_args,
)
from vllm_omni.engine.arg_utils import SHARED_FIELDS, EngineArgs, internal_blacklist_keys
from vllm_omni.engine.arg_utils import SHARED_FIELDS, internal_blacklist_keys
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
@@ -475,7 +474,7 @@ class TestStageConfigFactory:
cli_overrides = {
"gpu_memory_utilization": 0.9,
"model": "some_model", # Internal
"stage_configs_path": "/path", # Internal
"deploy_config": "/path", # Internal
"batch_timeout": 10, # Internal
}
@@ -483,7 +482,7 @@ class TestStageConfigFactory:
assert overrides["gpu_memory_utilization"] == 0.9
assert "model" not in overrides
assert "stage_configs_path" not in overrides
assert "deploy_config" not in overrides
assert "batch_timeout" not in overrides
def test_per_stage_override_excludes_internal_keys(self):
@@ -525,49 +524,6 @@ class TestStageResolutionHelpers:
assert "model" not in overrides
assert "parallel_config" not in overrides
def test_strip_parent_engine_args_reports_only_surprising_parent_overrides(self):
parent_fields = {f.name: f for f in fields(EngineArgs)}
filtered, overridden = strip_parent_engine_args(
{
"model": "some/model",
"stage_configs_path": "/tmp/stages.yaml",
"tensor_parallel_size": 4,
"worker_extension_cls": "some.Extension",
"custom_pipeline_args": {"pipeline_class": "demo.Pipeline"},
},
parent_fields=parent_fields,
keep_keys={"worker_extension_cls"},
strip_keys={"stage_configs_path"},
no_warn_keys={"model"},
)
assert filtered == {
"worker_extension_cls": "some.Extension",
"custom_pipeline_args": {"pipeline_class": "demo.Pipeline"},
}
assert overridden == ["tensor_parallel_size"]
def test_strip_parent_engine_args_keeps_allowed_media_access_controls(self):
parent_fields = {f.name: f for f in fields(EngineArgs)}
filtered, overridden = strip_parent_engine_args(
{
"model": "some/model",
"stage_configs_path": "/tmp/stages.yaml",
"allowed_local_media_path": "/data/qwentts",
"allowed_media_domains": ["example.com"],
},
parent_fields=parent_fields,
keep_keys={"allowed_local_media_path", "allowed_media_domains"},
strip_keys={"stage_configs_path"},
no_warn_keys={"model"},
)
assert filtered == {
"allowed_local_media_path": "/data/qwentts",
"allowed_media_domains": ["example.com"],
}
assert overridden == []
class TestPipelineDiscovery:
"""Tests for the central pipeline registry (``OMNI_PIPELINES``)."""
@@ -0,0 +1,71 @@
import pytest
import vllm_omni.config.pipeline_registry # noqa: F401 (populate registry)
from vllm_omni.config.pipeline_registry import OMNI_PIPELINES as _PIPELINE_REGISTRY
from vllm_omni.config.stage_config import (
DeployConfig,
StageExecutionType,
)
from vllm_omni.model_executor.stage_input_processors.forced_aligner import (
POOLING_OUTPUT_DECODER_PATH,
TIMESTAMPS_MODALITY,
)
from vllm_omni.utils.forced_aligner import _DEFAULT_CONFIG_PATH, inject_forced_aligner_stage
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
def test_inject_appends_pooling_aligner_stage():
pipeline = _PIPELINE_REGISTRY["qwen3_tts"]
deploy = DeployConfig()
n0 = len(pipeline.stages)
ext_pipeline, ext_deploy = inject_forced_aligner_stage(
pipeline, deploy, {"forced_aligner": "/models/Qwen3-ForcedAligner-0.6B"}
)
# A new pooling stage is appended; the original pipeline is unchanged.
assert len(pipeline.stages) == n0
assert len(ext_pipeline.stages) == n0 + 1
# The original deploy config is not mutated either (double-injection safe).
assert len(deploy.stages) == 0
assert len(ext_deploy.stages) == 1
aligner = ext_pipeline.stages[-1]
# Pooling stage reuses LLM_AR (+ runner=pooling), no dedicated LLM_POOLING.
assert aligner.execution_type == StageExecutionType.LLM_AR
assert aligner.final_output is True
assert aligner.final_output_type == TIMESTAMPS_MODALITY
assert aligner.input_sources == (n0 - 1,)
assert aligner.requires_multimodal_data is True
assert aligner.owns_tokenizer is True
# The deploy stage carries the separate aligner checkpoint + decoder hook.
ds = ext_deploy.stages[-1]
assert ds.engine_extras["model"] == "/models/Qwen3-ForcedAligner-0.6B"
assert ds.engine_extras["runner"] == "pooling"
assert ds.engine_extras["pooling_output_decoder"] == POOLING_OUTPUT_DECODER_PATH
def test_inject_from_config_only():
# --forced-aligner-config alone (model in the YAML) must also inject.
pipeline = _PIPELINE_REGISTRY["qwen3_tts"]
deploy = DeployConfig()
n0 = len(pipeline.stages)
ext_pipeline, ext_deploy = inject_forced_aligner_stage(
pipeline, deploy, {"forced_aligner": None, "forced_aligner_config": str(_DEFAULT_CONFIG_PATH)}
)
assert len(ext_pipeline.stages) == n0 + 1
assert ext_pipeline.stages[-1].final_output_type == TIMESTAMPS_MODALITY
assert ext_deploy.stages[-1].engine_extras["model"] == "Qwen/Qwen3-ForcedAligner-0.6B"
def test_inject_noop_without_forced_aligner():
pipeline = _PIPELINE_REGISTRY["qwen3_tts"]
deploy = DeployConfig()
ext_pipeline, ext_deploy = inject_forced_aligner_stage(pipeline, deploy, {})
assert ext_pipeline is pipeline
assert len(ext_deploy.stages) == 0
+1
View File
@@ -513,6 +513,7 @@ def test_sub_config_fields_match_structured_scopes():
"enable_prefix_caching",
"disable_hybrid_kv_cache_manager",
"mm_processor_cache_gb",
"mamba_ssm_cache_dtype",
}
assert {f.name for f in fields(OmniStageSchedulerConfig)} == {
"max_num_seqs",
@@ -27,6 +27,7 @@ _MIXIN_UPDATE_HELPERS = (
"_attach_finished_request_sets",
"_attach_scheduler_stats",
"_capture_omni_connector_output",
"_maybe_decode_pooling_output",
)
@@ -138,6 +139,7 @@ def _make_scheduler_stub(requests: list[_Request]) -> SimpleNamespace:
pending_stop_after_extraction=set(),
waiting_for_transfer_free=set(),
_new_prompt_len_snapshot={},
_pooling_output_decoder=None,
finished_req_ids=set(),
finished_req_ids_dict=defaultdict(set),
kv_cache_manager=SimpleNamespace(take_events=lambda: None),
@@ -267,3 +269,72 @@ def test_invalid_logprobs_finish_only_the_affected_scheduler_request() -> None:
assert output_by_id["bad"].new_token_ids == []
assert output_by_id["good"].new_token_ids == [8]
np.testing.assert_array_equal(output_by_id["good"].new_logprobs.logprob_token_ids[:, 0], [8])
def _pooling_model_runner_output(pooler_tensor) -> SimpleNamespace:
return SimpleNamespace(
sampled_token_ids=[[]],
logprobs=None,
prompt_logprobs_dict={},
pooler_output=[pooler_tensor],
num_nans_in_logits=None,
kv_connector_output=None,
cudagraph_stats=None,
req_id_to_index={"req": 0},
routed_experts=None,
)
def _make_pooling_stub(decoder) -> tuple[_Request, SimpleNamespace]:
request = _Request("req")
request.sampling_params = SimpleNamespace(num_logprobs=None)
request.pooling_params = SimpleNamespace()
scheduler = _make_scheduler_stub([request])
scheduler._pooling_output_decoder = decoder
scheduler.vllm_config = SimpleNamespace(model_config=SimpleNamespace(hf_config=None))
_bind_request_lifecycle(scheduler, update_request=lambda req, tokens: (tokens, False))
return request, scheduler
def test_pooling_decode_success_emits_decoded_payload() -> None:
import torch
decoded = torch.tensor([[1, 2]], dtype=torch.int32)
request, scheduler = _make_pooling_stub(lambda logits, req, hf: decoded)
scheduler_output = SimpleNamespace(
num_scheduled_tokens={"req": 1},
scheduled_spec_decode_tokens={},
num_invalid_spec_tokens=0,
)
outputs = OmniARScheduler.update_from_output(
scheduler, scheduler_output, _pooling_model_runner_output(torch.zeros(2, 4))
)
(output,) = outputs[0].outputs
assert output.finish_reason is FinishReason.STOP
assert output.pooling_output is decoded
def test_pooling_decode_failure_finishes_request_with_error() -> None:
import torch
def raising_decoder(logits, req, hf):
raise ValueError("boom")
request, scheduler = _make_pooling_stub(raising_decoder)
scheduler_output = SimpleNamespace(
num_scheduled_tokens={"req": 1},
scheduled_spec_decode_tokens={},
num_invalid_spec_tokens=0,
)
outputs = OmniARScheduler.update_from_output(
scheduler, scheduler_output, _pooling_model_runner_output(torch.zeros(2, 4))
)
(output,) = outputs[0].outputs
# Decoder failure is a request error (500), not an empty success.
assert output.finish_reason is FinishReason.ERROR
assert output.pooling_output is None
assert "pooling output decode failed" in str(request.stop_reason)
@@ -120,6 +120,9 @@ class TestFullPayloadCoordinatorSelection(unittest.TestCase):
("MiMoAudioModel", "code2wav"),
("Qwen3TTSCode2Wav", "code2wav"),
("MiniCPMO45Code2Wav", "code2wav"),
# nemotron_voicechat: sync-path RVQ-VAE decode waits for the
# talker's full [frames, 31] code-stack payload.
("NemotronVoiceChatCode2Wav", "code2wav"),
("CosyVoice3Model", "cosyvoice3_code2wav"),
# audex: sync-path TTS decoder (async_chunk: false deploys) and
# the TTA XCodec1 stage (always sync full-payload).
@@ -125,7 +125,7 @@ def _extract_images(output: OmniRequestOutput) -> list:
return output.images
# When the output comes from the orchestrator pipeline, images may be
# nested inside request_output.
inner = getattr(output, "request_output", None)
inner = output
if inner is not None and hasattr(inner, "images") and inner.images:
return inner.images
return []
+2 -2
View File
@@ -56,10 +56,10 @@ def test_teacache(model_name: str):
# Extract images from request_output['images']
first_output = outputs[0]
assert first_output.final_output_type == "image"
if not hasattr(first_output, "request_output") or not first_output.request_output:
if not isinstance(first_output, OmniRequestOutput) or not first_output:
raise ValueError("No request_output found in OmniRequestOutput")
req_out = first_output.request_output
req_out = first_output
if not isinstance(req_out, OmniRequestOutput) or not hasattr(req_out, "images"):
raise ValueError("Invalid request_output structure or missing 'images' key")
@@ -131,7 +131,7 @@ def _run_inference(
elapsed_ms = (time.time() - start) * 1000
return InferenceResult(
images=outputs[0].request_output.images,
images=outputs[0].images,
elapsed_ms=elapsed_ms,
)
finally:
@@ -49,10 +49,10 @@ def _diff_metrics(a: Image.Image, b: Image.Image) -> tuple[float, float]:
def _extract_single_image(outputs) -> Image.Image:
first_output = outputs[0]
assert first_output.final_output_type == "image"
if not hasattr(first_output, "request_output") or not first_output.request_output:
if not isinstance(first_output, OmniRequestOutput) or not first_output:
raise ValueError("No request_output found in OmniRequestOutput")
req_out = first_output.request_output
req_out = first_output
if not isinstance(req_out, OmniRequestOutput) or not hasattr(req_out, "images"):
raise ValueError("Invalid request_output structure or missing 'images' key")
+2 -2
View File
@@ -29,10 +29,10 @@ def test_diffusion_model(tmp_path: Path, omni_runner):
raise ValueError("Empty outputs from Omni.generate()")
first_output = outputs[0]
assert first_output.final_output_type == "image"
if not hasattr(first_output, "request_output") or not first_output.request_output:
if not isinstance(first_output, OmniRequestOutput) or not first_output:
raise ValueError("No request_output found in OmniRequestOutput")
req_out = first_output.request_output
req_out = first_output
if not isinstance(req_out, OmniRequestOutput) or not hasattr(req_out, "images"):
raise ValueError("Invalid request_output structure or missing 'images' key")
return req_out.images
@@ -0,0 +1,26 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import torch
from vllm_omni.diffusion.layers.norm import RMSNorm
from vllm_omni.diffusion.models.minimax_h3.encoder import MiniMaxH3Qwen3VLRMSNorm
def test_qwen3_vl_rmsnorm_uses_common_fused_rmsnorm_contract() -> None:
"""Qwen keeps BF16 gamma while native fallback accumulates in FP32."""
eps = 1e-6
norm = MiniMaxH3Qwen3VLRMSNorm(hidden_size=4, eps=eps, dtype=torch.bfloat16)
norm.weight.data.copy_(torch.tensor([1.0, 0.5, 1.5, 2.0], dtype=torch.bfloat16))
x = torch.tensor(
[[1.0, -2.0, 3.0, -4.0], [-5.0, 6.0, -7.0, 8.0]],
dtype=torch.bfloat16,
)
x_fp32 = x.float()
expected = (x_fp32 * torch.rsqrt(x_fp32.square().mean(-1, keepdim=True) + eps) * norm.weight.float()).to(x.dtype)
assert isinstance(norm, RMSNorm)
assert norm.weight.dtype == torch.bfloat16
assert set(norm.state_dict()) == {"weight"}
torch.testing.assert_close(norm.forward_native(x), expected, atol=0, rtol=0)
@@ -122,8 +122,8 @@ def test_cpu_offload_diffusion_model(model_name: str):
print(f"No offload peak memory: {no_offload_peak_memory} MB")
if model_name == "stabilityai/stable-audio-open-1.0":
audio_offload = output_offload[0].request_output.multimodal_output.get("audio")
audio_no_offload = output_no_offload[0].request_output.multimodal_output.get("audio")
audio_offload = output_offload[0].multimodal_output.get("audio")
audio_no_offload = output_no_offload[0].multimodal_output.get("audio")
check_audio_determinism(audio_offload, audio_no_offload, atol=1e-2)
# Set platform-specific VRAM saving thresholds to account
@@ -20,18 +20,10 @@ IMAGE_VIDEO_MODELS = {
MODELS = {**AUDIO_MODEL, **IMAGE_VIDEO_MODELS}
LAYERWISE_MODEL_CASES = [
pytest.param(
"stabilityai/stable-audio-open-1.0",
marks=[pytest.mark.full_model, pytest.mark.diffusion],
id="stable_audio",
),
pytest.param(
"riverclouds/qwen_image_random",
marks=[pytest.mark.core_model, pytest.mark.diffusion],
id="qwen_image_random",
),
]
MODEL_MARKS = {
"riverclouds/qwen_image_random": pytest.mark.core_model,
"stabilityai/stable-audio-open-1.0": pytest.mark.full_model,
}
AUDIO_MODEL_PARAMS = {
"runner_params": {},
@@ -101,8 +93,9 @@ def run_inference(
return peak, output
@pytest.mark.diffusion
@hardware_test(res={"cuda": "L4", "rocm": "MI325"})
@pytest.mark.parametrize("model_name", LAYERWISE_MODEL_CASES)
@pytest.mark.parametrize("model_name", list(MODELS.keys()))
def test_layerwise_offload_diffusion_model(model_name: str):
"""Test that layerwise offloading reduces GPU memory usage.
@@ -134,8 +127,8 @@ def test_layerwise_offload_diffusion_model(model_name: str):
print(f"No offload peak memory: {no_offload_peak_memory} MB")
if model_name == "stabilityai/stable-audio-open-1.0":
audio_offload = output_offload[0].request_output.multimodal_output.get("audio")
audio_no_offload = output_no_offload[0].request_output.multimodal_output.get("audio")
audio_offload = output_offload[0].multimodal_output.get("audio")
audio_no_offload = output_no_offload[0].multimodal_output.get("audio")
# Match the sibling cpu-offload test's tolerance: layerwise offload moves
# blocks across the PCIe bus on a side stream, which can perturb cuBLAS
# algorithm selection and produce ~ULP-level drift larger than 1e-3.
@@ -94,8 +94,8 @@ def _generate_single_stage_image(
if hasattr(first_output, "images") and first_output.images:
images = first_output.images
else:
assert hasattr(first_output, "request_output") and first_output.request_output
request_output = first_output.request_output
assert isinstance(first_output, OmniRequestOutput) and first_output
request_output = first_output
if isinstance(request_output, list):
req_out = request_output[0]
else:
@@ -88,8 +88,8 @@ def _generate_single_stage_image(
if hasattr(first_output, "images") and first_output.images:
images = first_output.images
else:
assert hasattr(first_output, "request_output") and first_output.request_output
request_output = first_output.request_output
assert isinstance(first_output, OmniRequestOutput) and first_output
request_output = first_output
if isinstance(request_output, list):
req_out = request_output[0]
else:
@@ -147,10 +147,10 @@ def _generate_single_stage_video(
first = outputs[0]
# Unwrap pipeline-style outputs (multi-stage / OmniRequestOutput.request_output).
# Unwrap pipeline-style outputs (multi-stage / OmniRequestOutput).
frames: Any = None
if hasattr(first, "request_output") and isinstance(first.request_output, list):
inner = first.request_output[0]
if isinstance(first, OmniRequestOutput) and isinstance(first, list):
inner = first[0]
if isinstance(inner, OmniRequestOutput) and inner.images:
frames = inner.images[0]
if frames is None and hasattr(first, "images") and first.images:
@@ -189,7 +189,7 @@ def _generate_single_stage_video(
def _generate_bagel_image(
quantization_config: str | None = None,
diffusion_quantization_config: str | None = None,
num_inference_steps: int = 15,
) -> tuple[Any, float]:
"""Generate an image with BAGEL (multi-stage: LLM + Diffusion).
@@ -199,11 +199,11 @@ def _generate_bagel_image(
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,
"deploy_config": config_path,
"stage_init_timeout": 300,
}
if quantization_config:
omni_kwargs["quantization_config"] = quantization_config
if diffusion_quantization_config:
omni_kwargs["diffusion_quantization_config"] = diffusion_quantization_config
model_name = omni_kwargs.pop("model")
with OmniRunner(model_name, **omni_kwargs) as runner:
@@ -234,8 +234,8 @@ def _generate_bagel_image(
if images := getattr(req_output, "images", None):
generated_image = images[0]
break
if hasattr(req_output, "request_output") and req_output.request_output:
stage_outputs = req_output.request_output
if isinstance(req_output, OmniRequestOutput) and req_output:
stage_outputs = req_output
if not isinstance(stage_outputs, list):
stage_outputs = [stage_outputs]
for stage_out in stage_outputs:
@@ -250,8 +250,8 @@ def _generate_bagel_image(
# Check LLM stage output — should have finish_reason=stop (not length)
for req_output in omni_outputs:
if hasattr(req_output, "request_output") and req_output.request_output:
stage_outputs = req_output.request_output
if isinstance(req_output, OmniRequestOutput) and req_output:
stage_outputs = req_output
if not isinstance(stage_outputs, list):
stage_outputs = [stage_outputs]
for stage_out in stage_outputs:
@@ -380,21 +380,21 @@ def test_single_stage_ltx2_fp8_uses_less_memory():
@hardware_test(res={"cuda": "H100"})
def test_bagel_fp8_generates_image():
"""BAGEL with FP8 quantization_config generates a valid image.
"""BAGEL with diffusion-stage FP8 generates a valid image.
FP8 should only apply to the diffusion stage (Stage-1), not the
LLM stage (Stage-0). We verify this by checking:
1. Image is generated successfully
2. LLM stage finish_reason is 'stop' (not 'length' from garbled output)
"""
image, _ = _generate_bagel_image(quantization_config="fp8")
image, _ = _generate_bagel_image(diffusion_quantization_config="fp8")
image.save("test_bagel_fp8.png")
@hardware_test(res={"cuda": "H100"})
def test_bagel_bf16_generates_image():
"""BAGEL without quantization generates a valid image (baseline)."""
image, _ = _generate_bagel_image(quantization_config=None)
image, _ = _generate_bagel_image(diffusion_quantization_config=None)
image.save("test_bagel_bf16.png")
@@ -310,7 +310,7 @@ def _generate_image(omni, config: QualityTestConfig):
first = outputs[0]
if hasattr(first, "images") and first.images:
return first.images[0], peak_mem
inner = first.request_output
inner = first
if inner is not None and hasattr(inner, "images") and inner.images:
return inner.images[0], peak_mem
raise ValueError("Could not extract image from output.")
@@ -341,15 +341,15 @@ def _generate_video(omni, config: QualityTestConfig):
)
peak_mem = torch.accelerator.max_memory_allocated() / (1024**3)
first = outputs[0]
if hasattr(first, "request_output") and isinstance(first.request_output, list):
inner = first.request_output[0]
if isinstance(inner, OmniRequestOutput) and hasattr(inner, "images"):
frames = inner.images[0] if inner.images else None
else:
frames = inner
elif hasattr(first, "images") and first.images:
frames = first.images[0]
if isinstance(outputs, list) and isinstance(outputs[0], OmniRequestOutput):
first = outputs[0]
elif isinstance(outputs, OmniRequestOutput):
first = outputs
else:
raise ValueError("Could not extract video frames from output.")
if hasattr(first, "images"):
frames = first.images[0] if first.images else None
else:
raise ValueError("Could not extract video frames from output.")
@@ -444,11 +444,11 @@ def test_benchmark_generate_image_unwraps_nested_omni_request_output(monkeypatch
image = Image.new("RGB", (2, 2))
inner = OmniRequestOutput.from_diffusion(request_id="req", images=[image])
outer = OmniRequestOutput(
outer = OmniRequestOutput.from_stage_output(
inner,
request_id="req",
stage_id=0,
final_output_type="image",
request_output=inner,
finished=True,
)
@@ -73,11 +73,9 @@ def test_run_summary_reports_worker_peak_memory():
assert summary["per_run_peak_memory_mb"] == [100.0, 150.0]
def test_request_peak_memory_prefers_inner_diffusion_output():
inner = type("InnerOutput", (), {"peak_memory_mb": 321.0})()
outer = type("OuterOutput", (), {"request_output": inner, "peak_memory_mb": 123.0})()
assert _request_peak_memory_mb(outer) == 321.0
def test_request_peak_memory_reads_peak_memory_mb_directly():
result = type("Output", (), {"peak_memory_mb": 123.0})()
assert _request_peak_memory_mb(result) == 123.0
def test_metric_guidance_describes_thresholds():
@@ -95,6 +95,7 @@ def test_formatter_preserves_single_video_audio_actions_and_metadata(
"resolution": 512,
"width": None,
"height": None,
"num_inference_steps": 1,
}
@@ -273,7 +273,7 @@ class TestPipelineStreamingOutputToEntrypoint:
await _wait_for(lambda: len(pipeline.requests) == 1)
assert pipeline.requests[0].request_id.startswith("req-omni-")
assert [output.multimodal_output["metadata"]["stream"]["chunk"] for output in outputs] == [0, 1]
assert [getattr(output.request_output, "finished", output.finished) for output in outputs] == [False, True]
assert [output.finished for output in outputs] == [False, True]
finally:
await self._shutdown_pipeline_omni_harness(omni, fixture, inline_client)
@@ -25,6 +25,7 @@ from tests.helpers.mark import hardware_test
from tests.helpers.runtime import OmniRunner
from tests.helpers.stage_config import get_deploy_config_path, modify_stage_config
from vllm_omni.entrypoints.omni import Omni
from vllm_omni.outputs import OmniRequestOutput
pytestmark = [pytest.mark.usefixtures("clean_gpu_memory_between_tests")]
@@ -95,8 +96,8 @@ def _extract_generated_image(omni_outputs: list) -> Image.Image | None:
for req_output in omni_outputs:
if images := getattr(req_output, "images", None):
return images[0]
if hasattr(req_output, "request_output") and req_output.request_output:
stage_out = req_output.request_output
if isinstance(req_output, OmniRequestOutput) and req_output:
stage_out = req_output
if hasattr(stage_out, "images") and stage_out.images:
return stage_out.images[0]
return None
@@ -313,7 +314,7 @@ def test_bagel_text2img_mooncake_connector(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,
deploy_config=temp_config_file,
stage_init_timeout=300,
) as runner:
generated_image = _generate_bagel_image(runner.omni)
@@ -24,6 +24,7 @@ from tests.helpers.mark import hardware_test
from tests.helpers.runtime import OmniRunner
from tests.helpers.stage_config import get_deploy_config_path, modify_stage_config
from vllm_omni.entrypoints.omni import Omni
from vllm_omni.outputs import OmniRequestOutput
pytestmark = [pytest.mark.usefixtures("clean_gpu_memory_between_tests")]
@@ -122,8 +123,8 @@ def _extract_generated_image(omni_outputs: list) -> Image.Image | None:
for req_output in omni_outputs:
if images := getattr(req_output, "images", None):
return images[0]
if hasattr(req_output, "request_output") and req_output.request_output:
stage_out = req_output.request_output
if isinstance(req_output, OmniRequestOutput) and req_output:
stage_out = req_output
if hasattr(stage_out, "images") and stage_out.images:
return stage_out.images[0]
return None
@@ -250,7 +251,7 @@ def test_bagel_img2img_shared_memory_connector(run_level):
config_path = _resolve_deploy_config(BAGEL_CI_DEPLOY, run_level)
with OmniRunner(
"ByteDance-Seed/BAGEL-7B-MoT",
stage_configs_path=config_path,
deploy_config=config_path,
) as runner:
generated_image = _generate_bagel_img2img(runner.omni, input_image)
if run_level == "advanced_model":
@@ -265,7 +266,7 @@ def test_bagel_text2img_shared_memory_connector(run_level):
config_path = _resolve_deploy_config(BAGEL_CI_DEPLOY, run_level)
with OmniRunner(
"ByteDance-Seed/BAGEL-7B-MoT",
stage_configs_path=config_path,
deploy_config=config_path,
) as runner:
generated_image = _generate_bagel_text2img(runner.omni)
if run_level == "advanced_model":
@@ -3,8 +3,8 @@
Daily-Omni settings follow the MiniCPM interleaved AV recipe that reaches
~78% overall accuracy on Daily-Omni (``minicpm-interleave``, ``temperature=0``,
text modalities with ``use_tts_template``, and server ``--interleave-mm-strings``
+ 1fps / 128-frame media-io kwargs, also pinned in ``minicpmo_4_5.yaml``).
text modalities, and server ``--interleave-mm-strings`` + 1fps / 128-frame
media-io kwargs, also pinned in ``minicpmo_4_5.yaml``).
"""
from __future__ import annotations
@@ -40,10 +40,7 @@ _MAX_SEED_TTS_MEAN_WER = 0.05
# Match the validated Daily-Omni client body from daily_omni_bench.sh.
_DAILY_EXTRA_BODY = {
"modalities": ["text"],
"chat_template_kwargs": {
"enable_thinking": False,
"use_tts_template": True,
},
"chat_template_kwargs": {"enable_thinking": False},
}
_SEED_EXTRA_BODY = {
"modalities": ["text", "audio"],
+2 -2
View File
@@ -328,7 +328,7 @@ def _run_offline(deploy_config_path: str, output_path: Path) -> tuple[Image.Imag
images = None
cot_text = ""
for out in outputs:
ro = getattr(out, "request_output", None)
ro = out
if ro and getattr(ro, "outputs", None):
cot_text = "".join(getattr(o, "text", "") or "" for o in ro.outputs)
if not cot_text:
@@ -467,7 +467,7 @@ def _extract_image(outputs) -> Image.Image:
assert outputs, "Pipeline produced no outputs"
for output in outputs:
images = getattr(output, "images", None)
request_output = getattr(output, "request_output", None)
request_output = output
if not images and request_output is not None:
images = getattr(request_output, "images", None)
if images:
@@ -141,8 +141,8 @@ def _extract_frames(result) -> list[Image.Image]:
if isinstance(result, list):
result = result[0] if result else None
if isinstance(result, OmniRequestOutput) and result.is_pipeline_output and result.request_output is not None:
result = result.request_output
if isinstance(result, OmniRequestOutput) and result.is_pipeline_output and result is not None:
result = result
images = getattr(result, "images", None)
if not images:
raise AssertionError("Pipeline output had no images")
@@ -171,11 +171,11 @@ def _build_text_output(text: str = "This is a test response.") -> OmniRequestOut
metrics=None,
lora_request=None,
)
return OmniRequestOutput(
return OmniRequestOutput.from_stage_output(
request_output,
request_id="test_req_text",
finished=True,
final_output_type="text",
request_output=request_output,
)
@@ -200,11 +200,11 @@ def _build_audio_chat_output(num_samples: int = 24000) -> OmniRequestOutput:
metrics=None,
lora_request=None,
)
return OmniRequestOutput(
return OmniRequestOutput.from_stage_output(
request_output,
request_id="test_req_audio_chat",
finished=True,
final_output_type="audio",
request_output=request_output,
)
@@ -240,11 +240,11 @@ def _build_diffusion_image_output_for_chat_endpoint() -> OmniRequestOutput:
images=[_build_image_output(color="blue")],
finished=True,
)
return OmniRequestOutput(
return OmniRequestOutput.from_stage_output(
request_output,
request_id="test_req_img_chat",
finished=True,
images=[_build_image_output(color="blue")],
final_output_type="image",
request_output=request_output,
)
@@ -515,8 +515,19 @@ def mock_async_omni(
@pytest.fixture
def api_server(unused_tcp_port_factory, server_case: ServerCase, mock_async_omni):
def api_server(unused_tcp_port_factory, server_case: ServerCase, mock_async_omni, tmp_path):
"""Set up a API server in background process from command line with parametrized model name and mocked AsyncOmni."""
# Override the STORAGE_MANAGER path to a writable temp directory before
# forking the server subprocess. The default /tmp/storage may be owned
# by a different user (e.g. from a previous CI run) and cause
# PermissionError when the server tries to save generated video files.
from vllm_omni.entrypoints.openai.storage import STORAGE_MANAGER
old_storage_path = STORAGE_MANAGER.storage_path
new_storage_path = tmp_path / "omni_storage"
new_storage_path.mkdir(exist_ok=True)
STORAGE_MANAGER.storage_path = str(new_storage_path)
parser = TrackingArgumentParser()
subparsers = parser.add_subparsers(dest="command")
cmd = OmniServeCommand()
@@ -555,6 +566,9 @@ def api_server(unused_tcp_port_factory, server_case: ServerCase, mock_async_omni
yield f"http://127.0.0.1:{port}/v1"
# Restore the original storage path after the test.
STORAGE_MANAGER.storage_path = old_storage_path
if server_process.is_alive():
server_process.terminate()
server_process.join(timeout=10)
@@ -294,7 +294,7 @@ class vLLMOmniHttpServerLocal:
"global_steps": self.global_steps,
}
req_output = final_res.request_output
req_output = final_res
if req_output is not None and hasattr(req_output, "finish_reason"):
finish_reason = req_output.finish_reason or "stop"
else:
@@ -17,7 +17,7 @@ from vllm_omni.platforms import current_omni_platform
# Override in CI if needed: AUDIOX_TEST_MODEL=<model-or-local-path>
models = [os.environ.get("AUDIOX_TEST_MODEL", "zhangj1an/audiox_random")]
# (model, stage_configs_path, extra_omni_kwargs) for ``omni_runner`` indirect parametrize
# (model, deploy_config_path, extra_omni_kwargs) for ``omni_runner`` indirect parametrize
_OMNI_RUNNER_PARAMS = [(m, None, {"model_class_name": "AudioXPipeline"}) for m in models]
pytestmark = [
@@ -53,9 +53,9 @@ def test_audiox_model(omni_runner: OmniRunner) -> None:
assert outputs is not None
first_output = outputs[0]
assert first_output.final_output_type == "audio"
assert hasattr(first_output, "request_output") and first_output.request_output
assert isinstance(first_output, OmniRequestOutput) and first_output
req_out = first_output.request_output
req_out = first_output
assert isinstance(req_out, OmniRequestOutput)
assert req_out.final_output_type == "audio"
assert hasattr(req_out, "multimodal_output") and req_out.multimodal_output
+1 -1
View File
@@ -55,7 +55,7 @@ pytestmark = [
def _extract_text(omni_outputs: list) -> str:
"""Extract generated text from OmniRequestOutput list."""
for req_output in omni_outputs:
ro = getattr(req_output, "request_output", None)
ro = req_output
if ro and getattr(ro, "outputs", None):
return "".join(getattr(o, "text", "") or "" for o in ro.outputs)
return ""
@@ -43,7 +43,7 @@ MODEL = "ByteDance-Seed/BAGEL-7B-MoT"
BAGEL_STAGE_CONFIG = get_deploy_config_path("ci/bagel.yaml")
DEFAULT_PROMPT = "<|im_start|>A cute cat<|im_end|>"
# (model, stage_configs_path) for ``@pytest.mark.parametrize("omni_runner", ..., indirect=True)``
# (model, deploy_config_path) for ``@pytest.mark.parametrize("omni_runner", ..., indirect=True)``
_OMNI_RUNNER_PARAM = (MODEL, BAGEL_STAGE_CONFIG)
@@ -28,7 +28,6 @@ from tests.helpers.media import get_asset_path
from tests.helpers.runtime import OmniRunner
from tests.helpers.stage_config import get_deploy_config_path
from vllm_omni.model_executor.models.cosyvoice3.tokenizer import get_qwen_tokenizer
from vllm_omni.outputs import OmniRequestOutput
from vllm_omni.transformers_utils.configs.cosyvoice3 import CosyVoice3Config
MODEL = "FunAudioLLM/Fun-CosyVoice3-0.5B-2512"
@@ -127,7 +126,7 @@ def _build_reference_inputs(prompt_audio: tuple[np.ndarray, int]) -> list[dict[s
]
# (model, stage_configs_path, extra_omni_kwargs) for ``@pytest.mark.parametrize("omni_runner", ..., indirect=True)``
# (model, deploy_config_path, extra_omni_kwargs) for ``@pytest.mark.parametrize("omni_runner", ..., indirect=True)``
_cosy_deployment = get_deploy_config_path("cosyvoice3.yaml")
_cosy_model_path = str(_resolve_model_dir())
_OMNI_RUNNER_PARAMS = [
@@ -176,12 +175,12 @@ def test_cosyvoice3_offline_reference_zero_shot(omni_runner: OmniRunner) -> None
assert 2.8 <= duration_s <= 8.8, f"Unexpected duration={duration_s:.3f}s (samples={audio.size}, sr={sr})"
# Code2wav is ``final_output`` (stage 1); ``Omni.generate`` yields its ``request_output`` / completions.
pipeline_out = OmniRequestOutput.unwrap_result(outputs[0])
pipeline_out = outputs[0]
assert pipeline_out.stage_id == 1, f"expected final stage 1, got {pipeline_out.stage_id}"
assert pipeline_out.final_output_type == "audio", (
f"expected audio final_output_type, got {pipeline_out.final_output_type!r}"
)
ro = pipeline_out.request_output
ro = pipeline_out
assert ro is not None, "stage 1 should include request_output"
completions = getattr(ro, "outputs", None) or []
assert completions, "stage 1 request_output should include at least one completion"
@@ -175,7 +175,7 @@ def _find_stage_output(outputs: list[Any], output_type: str) -> Any | None:
# Prefer the latest finished chunk to avoid picking an intermediate stream output.
for stage_output in reversed(matched):
if _is_finished_request_output(getattr(stage_output, "request_output", None)):
if _is_finished_request_output(stage_output):
return stage_output
return matched[-1]
@@ -205,7 +205,7 @@ def _to_token_list(value: Any) -> list[int]:
def _extract_text(stage_output: Any, tokenizer: Any | None = None) -> str:
request_output = getattr(stage_output, "request_output", None)
request_output = stage_output
if request_output is None:
return ""
req_list = request_output if isinstance(request_output, list) else [request_output]
@@ -240,7 +240,7 @@ def _extract_text(stage_output: Any, tokenizer: Any | None = None) -> str:
def _extract_audio(stage_output: Any) -> Any | None:
request_output = getattr(stage_output, "request_output", None)
request_output = stage_output
if request_output is None:
return None
req_list = request_output if isinstance(request_output, list) else [request_output]
@@ -256,7 +256,7 @@ def _extract_audio(stage_output: Any) -> Any | None:
def _extract_image(stage_output: Any) -> Any | None:
request_output = getattr(stage_output, "request_output", None)
request_output = stage_output
if request_output is None:
return None
req_list = request_output if isinstance(request_output, list) else [request_output]
@@ -17,7 +17,7 @@ from vllm_omni.inputs.data import OmniDiffusionSamplingParams
MODEL = "baidu/ERNIE-Image"
# (model, stage_configs_path, extra_omni_kwargs) for ``omni_runner`` indirect parametrize
# (model, deploy_config_path, extra_omni_kwargs) for ``omni_runner`` indirect parametrize
_OMNI_RUNNER_PARAM = (
MODEL,
None,
@@ -54,7 +54,7 @@ def _sampling_params() -> OmniDiffusionSamplingParams:
def _first_request_images(outputs) -> list:
first_output = outputs[0]
assert first_output.final_output_type == "image"
req_out = first_output.request_output
req_out = first_output
assert isinstance(req_out, OmniRequestOutput) and hasattr(req_out, "images")
return req_out.images
@@ -161,7 +161,7 @@ def test_glm_image_autoround_w4a16_generates_image(omni_runner_handler: OmniRunn
first_output = outputs[0]
assert first_output.final_output_type == "image"
req_out = first_output.request_output
req_out = first_output
assert isinstance(req_out, OmniRequestOutput) and hasattr(req_out, "images")
images = req_out.images
@@ -224,7 +224,7 @@ def test_glm_image_autoround_w4a16_image_to_image(omni_runner_handler: OmniRunne
first_output = outputs[0]
assert first_output.final_output_type == "image"
req_out = first_output.request_output
req_out = first_output
assert isinstance(req_out, OmniRequestOutput) and hasattr(req_out, "images")
images = req_out.images
@@ -96,7 +96,7 @@ def test_offline_voice_clone_zh(async_chunk: bool) -> None:
with OmniRunner(
MODEL,
stage_configs_path=_get_deploy_config(async_chunk=async_chunk),
deploy_config=_get_deploy_config(async_chunk=async_chunk),
stage_init_timeout=600,
trust_remote_code=True,
) as omni_runner:
@@ -288,7 +288,7 @@ def _extract_generated_image(outputs: list[object]) -> Image.Image:
if images := getattr(first_output, "images", None):
return images[0]
request_output = getattr(first_output, "request_output", None)
request_output = first_output
if request_output is not None and (images := getattr(request_output, "images", None)):
return images[0]
@@ -52,7 +52,7 @@ pytestmark = [pytest.mark.full_model, pytest.mark.diffusion]
def omni() -> Generator[Omni, None, None]:
with OmniRunner(
MODEL_NAME,
stage_configs_path=str(STAGE_CONFIG_PATH),
deploy_config=str(STAGE_CONFIG_PATH),
trust_remote_code=True,
) as runner:
yield runner.omni
@@ -74,7 +74,7 @@ def test_i2t_generates_text(omni: Omni) -> None:
outputs = omni.generate(prompts=[prompt_dict])
assert outputs, "No outputs returned from Omni.generate()"
request_output = outputs[0].request_output
request_output = outputs[0]
assert request_output.outputs, "No completion outputs"
completion = request_output.outputs[0]
@@ -84,7 +84,6 @@ def longcat_omni_runner() -> Generator[OmniRunner, None, None]:
with OmniRunner(
model,
seed=42,
stage_configs_path=None,
model_class_name="LongCatVideoAvatarPipeline",
additional_config={
"model_type": "avatar-v1.5",
@@ -38,7 +38,7 @@ _AR_PATCH_SIZE = 16
MODEL_PATH = "bytedance-research/MammothModa2-Preview"
T2I_DEPLOY_CONFIG = get_deploy_config_path("mammoth_moda2.yaml")
_OMNI_RUNNER_PARAM = (MODEL_PATH, None, {"deploy_config": T2I_DEPLOY_CONFIG})
_OMNI_RUNNER_PARAM = (MODEL_PATH, T2I_DEPLOY_CONFIG)
# Golden pixel reference file. Set UPDATE_GOLDEN=1 to regenerate.
_GOLDEN_T2I_PATH = Path(__file__).parent / "fixtures" / "mammoth_moda2_t2i_golden.json"
@@ -172,7 +172,7 @@ def test_mammothmoda2_t2i_e2e(omni_runner: OmniRunner):
found_image = False
for out in outputs:
ro_list = getattr(out, "request_output", out)
ro_list = out
if not isinstance(ro_list, list):
ro_list = [ro_list]
for ro in ro_list:
@@ -137,14 +137,11 @@ def _extract_final_audio_outputs(outputs):
if getattr(item, "final_output_type", None) == "audio":
final_outputs.append(item)
continue
request_output = getattr(item, "request_output", None)
if request_output is None:
continue
multimodal_output = getattr(request_output, "multimodal_output", None)
multimodal_output = getattr(item, "multimodal_output", None)
if isinstance(multimodal_output, Mapping):
final_outputs.append(item)
continue
completions = getattr(request_output, "outputs", None) or []
completions = getattr(item, "outputs", None) or []
if any(isinstance(getattr(completion, "multimodal_output", None), Mapping) for completion in completions):
final_outputs.append(item)
return final_outputs
@@ -155,16 +152,11 @@ def _extract_multimodal_output(output) -> Mapping[str, Any]:
if isinstance(multimodal_output, Mapping):
return multimodal_output
request_output = getattr(output, "request_output", None)
if request_output is not None:
multimodal_output = getattr(request_output, "multimodal_output", None)
completions = getattr(output, "outputs", None) or []
for completion in completions:
multimodal_output = getattr(completion, "multimodal_output", None)
if isinstance(multimodal_output, Mapping):
return multimodal_output
completions = getattr(request_output, "outputs", None) or []
for completion in completions:
multimodal_output = getattr(completion, "multimodal_output", None)
if isinstance(multimodal_output, Mapping):
return multimodal_output
raise AssertionError("No multimodal audio output found in Ming generate results")
@@ -17,7 +17,7 @@ models = ["openbmb/MiniCPM-o-4_5"]
_CI_DEPLOY = get_deploy_config_path("minicpmo_4_5.yaml")
test_params = [(model, None, {"deploy_config": _CI_DEPLOY, "trust_remote_code": True}) for model in models]
test_params = [(model, _CI_DEPLOY, {"trust_remote_code": True}) for model in models]
def get_question(prompt_type: str = "text") -> str:
@@ -25,7 +25,7 @@ from vllm_omni import Omni
MODEL_NAME = "OpenMOSS-Team/MOSS-TTS-Nano"
STAGE_CONFIG = get_deploy_config_path("moss_tts_nano.yaml")
# (model, stage_configs_path, extra_omni_kwargs) for ``omni_runner`` indirect parametrize
# (model, deploy_config_path, extra_omni_kwargs) for ``omni_runner`` indirect parametrize
_OMNI_RUNNER_PARAM = (
MODEL_NAME,
STAGE_CONFIG,
@@ -108,7 +108,7 @@ def _build_request(
def _collect_audio(omni: Omni, request: dict) -> tuple[torch.Tensor, int]:
"""Run a single request and return (waveform, sample_rate)."""
for stage_outputs in omni.generate(request, DEFAULT_SAMPLING):
req_output = stage_outputs.request_output
req_output = stage_outputs
if req_output is not None:
mm = req_output.outputs[0].multimodal_output
assert mm is not None, "Expected multimodal_output to be non-None"
@@ -167,7 +167,7 @@ def test_moss_tts_nano_batch(omni_runner: OmniRunner, ref_audio_path) -> None:
results = []
# Single-stage model (num_stages=1): one sampling param for all requests.
for stage_outputs in omni_runner.omni.generate(requests, [DEFAULT_SAMPLING]):
req_output = stage_outputs.request_output
req_output = stage_outputs
if req_output is not None:
mm = req_output.outputs[0].multimodal_output
assert mm is not None
@@ -20,13 +20,11 @@ from tests.helpers.stage_config import get_deploy_config_path
MODEL = "k2-fsa/OmniVoice"
DEPLOY_CONFIG = get_deploy_config_path("omnivoice.yaml")
# OmniRunner tuple: model, legacy stage config path, extra Omni kwargs.
# The migrated test passes deploy_config through extra Omni kwargs.
# OmniRunner tuple: model, deploy config path, extra Omni kwargs.
_OMNI_RUNNER_PARAM = (
MODEL,
None,
DEPLOY_CONFIG,
{
"deploy_config": DEPLOY_CONFIG,
"trust_remote_code": True,
"log_stats": True,
},
@@ -58,7 +56,7 @@ def test_omnivoice_text_to_audio(omni_runner: OmniRunner) -> None:
# Check final output has audio
final_output = outputs[-1]
ro = final_output.request_output
ro = final_output
assert ro is not None, "No request_output"
mm = getattr(ro, "multimodal_output", None)
@@ -42,7 +42,7 @@ def _sampling_params() -> OmniDiffusionSamplingParams:
def _first_request_images(outputs) -> list:
first_output = outputs[0]
assert first_output.final_output_type == "image"
req_out = first_output.request_output
req_out = first_output
assert isinstance(req_out, OmniRequestOutput) and hasattr(req_out, "images")
return req_out.images
@@ -131,7 +131,7 @@ def test_sensenova_u1_lora_scale_and_deactivation(tmp_path) -> None:
"""Validate LoRA effect, scale sensitivity, bounded perturbation, and clean deactivation."""
lora_request = _make_file_lora_request(tmp_path / "sensenova_lora")
with OmniRunner(MODEL, stage_configs_path=None) as runner:
with OmniRunner(MODEL) as runner:
omni = runner.omni
baseline = _generate(omni)
img_1x = _generate(omni, lora_request, lora_scale=1.0)
@@ -164,10 +164,7 @@ def _generate_sensenova_u1_img2img(
def test_sensenova_u1_img2img(run_level):
"""Test SenseNova-U1 img2img (single-stage diffusion, no deploy YAML)."""
input_image = _load_input_image()
with OmniRunner(
"SenseNova/SenseNova-U1-8B-MoT",
stage_configs_path=None,
) as runner:
with OmniRunner("SenseNova/SenseNova-U1-8B-MoT") as runner:
generated_image = _generate_sensenova_u1_img2img(runner.omni, input_image)
if run_level == "full_model" or run_level == "advanced_model":
_validate_pixels(generated_image)
@@ -182,7 +179,6 @@ def test_sensenova_u1_img2img_cache_dit():
input_image = _load_input_image()
with OmniRunner(
"SenseNova/SenseNova-U1-8B-MoT",
stage_configs_path=None,
cache_backend="cache_dit",
) as runner:
_generate_sensenova_u1_img2img(runner.omni, input_image)
@@ -151,10 +151,7 @@ def _generate_sensenova_u1_image(
@hardware_test(res={"cuda": "H100"})
def test_sensenova_u1_text2img(run_level):
"""Test SenseNova-U1 text2img (single-stage diffusion, no deploy YAML)."""
with OmniRunner(
"SenseNova/SenseNova-U1-8B-MoT",
stage_configs_path=None,
) as runner:
with OmniRunner("SenseNova/SenseNova-U1-8B-MoT") as runner:
generated_image = _generate_sensenova_u1_image(runner.omni)
if run_level == "full_model" or run_level == "advanced_model":
_validate_pixels(generated_image)
@@ -168,7 +165,6 @@ def test_sensenova_u1_text2img_cache_dit():
"""Test SenseNova-U1 text2img with Cache-DiT enabled."""
with OmniRunner(
"SenseNova/SenseNova-U1-8B-MoT",
stage_configs_path=None,
cache_backend="cache_dit",
) as runner:
_generate_sensenova_u1_image(runner.omni)
@@ -159,7 +159,7 @@ def test_soulxsinger_multistage_from_audio(
with OmniRunner(
model,
stage_configs_path=get_deploy_config_path(deploy_yaml),
deploy_config=get_deploy_config_path(deploy_yaml),
async_chunk=False,
) as runner:
sampling = OmniDiffusionSamplingParams(
@@ -212,7 +212,7 @@ def test_soulxsinger_svs_precomputed(soulx_weights: tuple[Path, Path, Path]) ->
with OmniRunner(
str(base_dir),
stage_configs_path=get_deploy_config_path("soulxsinger_svs.yaml"),
deploy_config=get_deploy_config_path("soulxsinger_svs.yaml"),
async_chunk=False,
) as runner:
sampling = OmniDiffusionSamplingParams(
@@ -62,9 +62,9 @@ def generate_stable_audio_short_clip(
# Audio-output diffusion pipelines (those with ``support_audio_output = True``) now have
# ``final_output_type="audio"`` set on the outer stage metadata as well as the inner request.
assert first_output.final_output_type == "audio"
assert hasattr(first_output, "request_output") and first_output.request_output
assert isinstance(first_output, OmniRequestOutput) and first_output
req_out = first_output.request_output
req_out = first_output
assert isinstance(req_out, OmniRequestOutput)
assert req_out.final_output_type == "audio"
assert hasattr(req_out, "multimodal_output") and req_out.multimodal_output
@@ -19,7 +19,7 @@ from vllm_omni.outputs import OmniRequestOutput
MODEL = "stepfun-ai/Step-Audio-2-mini"
DEPLOY_CONFIG = get_deploy_config_path("step_audio2_ci.yaml")
TEST_PARAMS = [(MODEL, None, {"deploy_config": DEPLOY_CONFIG, "trust_remote_code": True})]
TEST_PARAMS = [(MODEL, DEPLOY_CONFIG, {"trust_remote_code": True})]
pytestmark = [pytest.mark.slow, pytest.mark.tts]
@@ -63,8 +63,8 @@ def _assert_non_empty_text_output(outputs: list[OmniRequestOutput]) -> None:
text_output = next((o for o in outputs if o.final_output_type == "text"), None)
assert text_output is not None
assert text_output.request_output is not None
text_content = text_output.request_output.outputs[0].text
assert text_output is not None
text_content = text_output.outputs[0].text
assert text_content is not None
assert len(text_content.strip()) > 0
@@ -81,8 +81,8 @@ def test_audio_to_text_and_audio(omni_runner: OmniRunner) -> None:
audio_output = next((o for o in outputs if o.final_output_type == "audio"), None)
if audio_output is not None:
assert audio_output.request_output is not None
audio_tensor = audio_output.request_output.outputs[0].multimodal_output.get("audio")
assert audio_output is not None
audio_tensor = audio_output.outputs[0].multimodal_output.get("audio")
if audio_tensor is not None:
assert audio_tensor.numel() > 0
@@ -102,7 +102,7 @@ def test_voxtral_tts_offline_streaming():
async def _run():
async_omni = AsyncOmni(
model=MODEL,
stage_configs_path=STAGE_CONFIG,
deploy_config=STAGE_CONFIG,
stage_init_timeout=300,
enforce_eager=True,
)
@@ -53,7 +53,11 @@ def test_duplex_admission_and_expiry_reaper(omni_server, model_prefix: str, tmp_
assert result["admission"]["overflow_error_code"] == "resource_exhausted"
@hardware_test(res={"cuda": "H100", "npu": "A3"}, num_cards=1)
# CUDA-only for now: this contract asserts the model speaks while the user is
# still talking, which only holds when the duplex pipeline sustains real-time
# throughput. The current NPU stack runs several times slower than real time,
# so it never reaches a mid-stream decision point.
@hardware_test(res={"cuda": "H100"}, num_cards=1)
@pytest.mark.parametrize("omni_server", SERVER_PARAMS, indirect=True)
def test_duplex_soft_interrupt(omni_server, model_prefix: str, tmp_path: Path) -> None:
input_wav = validated_soft_interrupt_wav()
@@ -70,13 +74,8 @@ def test_duplex_soft_interrupt(omni_server, model_prefix: str, tmp_path: Path) -
timeout_s=180.0,
require_audio=True,
no_realtime_pacing=False,
# Single-GPU co-location cannot reliably finish the fixture's
# two-response soft-interrupt handoff before the WAV ends.
# model-policy + deterministic sampling checks streaming audio
# lifecycle instead of the diagnostic two-response contract.
validation_mode="model-policy",
temperature=0.0,
min_responses=1,
validation_mode="response-required",
min_responses=2,
min_audio_deltas_per_response=2,
input_sha256=SOFT_INTERRUPT_SHA256,
expect_followup_response_substring=None,
@@ -88,5 +87,4 @@ def test_duplex_soft_interrupt(omni_server, model_prefix: str, tmp_path: Path) -
assert result["error_count"] == 0
assert result["response_lifecycle_ok"] is True
assert result["response_audio_contract_ok"] is True
assert result["response_before_final_commit"] is True
assert result["enough_responses"] is True
assert result["followup_response_transcript_ok"] is True
@@ -65,7 +65,7 @@ def test_realtime_duplex_multi_session_script_is_directly_executable():
cwd=MULTI_DEMO_PATH.parents[3],
capture_output=True,
text=True,
timeout=20,
timeout=60,
check=False,
)
@@ -78,7 +78,7 @@ def test_realtime_duplex_demo_pair_script_is_directly_executable():
cwd=PAIR_DEMO_PATH.parents[3],
capture_output=True,
text=True,
timeout=20,
timeout=60,
check=False,
)
@@ -91,7 +91,7 @@ def test_realtime_duplex_soft_interrupt_script_is_directly_executable():
cwd=SOFT_INTERRUPT_DEMO_PATH.parents[3],
capture_output=True,
text=True,
timeout=20,
timeout=60,
check=False,
)
-139
View File
@@ -4,7 +4,6 @@ invariant to the specific attributes of vLLM config except in cases where we
explicitly patch values that differ from vLLM.
"""
import argparse
import inspect
import json
import os
@@ -20,7 +19,6 @@ from vllm.engine.arg_utils import EngineArgs
from vllm_omni.config.model import OmniModelConfig
from vllm_omni.engine.arg_utils import OmniEngineArgs
from vllm_omni.engine.async_omni_engine import AsyncOmniEngine
from vllm_omni.engine.stage_init_utils import build_engine_args_dict
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
@@ -149,19 +147,6 @@ def test_qwen3_tts_startup_task_type_is_validated():
)
def test_from_cli_args_picks_up_stage_configs_path():
"""from_cli_args should pick up stage_configs_path from namespace."""
ns = argparse.Namespace(
model="facebook/opt-125m",
stage_configs_path="/some/path.yaml",
custom_pipeline_args=None,
)
args = OmniEngineArgs.from_cli_args(ns)
assert args.stage_configs_path == "/some/path.yaml"
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.
@@ -418,130 +403,6 @@ def test_non_override_ar_stage_inputs_embeds_size_matches_hidden_size():
assert omni_config.get_inputs_embeds_size() == omni_config.hf_text_config.hidden_size
def test_stage_configs_path_field():
"""OmniEngineArgs with stage_configs_path should construct without error."""
args = OmniEngineArgs(stage_configs_path="/some/path.yaml")
assert args.stage_configs_path == "/some/path.yaml"
def test_strip_single_engine_args():
"""_strip_single_engine_args should remove EngineArgs fields but keep omni fields."""
kwargs = {
# Parent EngineArgs fields — stripped unless explicitly allowlisted
"compilation_config": '{"cudagraph_mode": "FULL_AND_PIECEWISE"}',
"tensor_parallel_size": 4,
"gpu_memory_utilization": 0.9,
"model": "some/model",
# Parent field that should be kept (allowlisted)
"worker_extension_cls": "some.Extension",
# OmniEngineArgs-only / non-engine fields — should pass through
"stage_configs_path": "/path/to/yaml",
"custom_pipeline_args": {"pipeline_class": "my.Pipeline"},
"mode": "text-to-image",
"lora_path": "/some/lora",
}
filtered = AsyncOmniEngine._strip_single_engine_args(kwargs)
# Stripped — parent EngineArgs fields
assert "compilation_config" not in filtered
assert filtered["tensor_parallel_size"] == 4
assert "gpu_memory_utilization" not in filtered
assert "model" not in filtered
# Stripped — orchestrator-level OmniEngineArgs field
assert "stage_configs_path" not in filtered
# Kept
assert filtered["worker_extension_cls"] == "some.Extension"
assert filtered["custom_pipeline_args"] == {"pipeline_class": "my.Pipeline"}
assert filtered["mode"] == "text-to-image"
assert filtered["lora_path"] == "/some/lora"
def test_strip_single_engine_args_model_does_not_trigger_warning(mocker):
"""model is always in kwargs (callers set it via from_cli_args/asdict),
so it should not cause the override warning by itself or appear in it."""
mock_warn = mocker.patch("vllm_omni.engine.async_omni_engine.logger.warning")
# Typical caller kwargs: model is always present, no other parent
# EngineArgs fields are explicitly overridden.
AsyncOmniEngine._strip_single_engine_args(
{
"model": "some/model",
"custom_pipeline_args": {"pipeline_class": "my.Pipeline"},
}
)
mock_warn.assert_not_called()
# When there *are* genuinely surprising overrides alongside model,
# the warning should mention them but not model. Keep-listed fields such as
# tensor_parallel_size are intentionally passed through and should not warn.
AsyncOmniEngine._strip_single_engine_args(
{
"model": "some/model",
"compilation_config": '{"cudagraph_mode": "FULL_AND_PIECEWISE"}',
"tensor_parallel_size": 4,
"custom_pipeline_args": {"pipeline_class": "my.Pipeline"},
}
)
mock_warn.assert_called_once()
warned_args = mock_warn.call_args[0][-1] # the formatted arg list
assert "compilation_config" in warned_args
assert "tensor_parallel_size" not in warned_args
assert "model" not in warned_args
def test_new_format_deploy_yaml_does_not_strip_interleave_cli_overrides(tmp_path):
"""New-format deploy YAMLs must not strip interleave_mm_strings / media_io_kwargs.
Pytest historically passed ``--stage-configs-path`` for deploy YAMLs; stripping
those CLI flags dropped MiniCPM interleaved AV packing and cut Daily-Omni
accuracy from ~78% to ~70%.
"""
from vllm_omni.entrypoints.utils import is_new_format_deploy_config
yaml_path = tmp_path / "minicpm_deploy.yaml"
yaml_path.write_text(
"""
pipeline: minicpmo_4_5
async_chunk: true
stages:
- stage_id: 0
devices: "0"
""".strip(),
encoding="utf-8",
)
path = str(yaml_path)
assert is_new_format_deploy_config(path)
kwargs = {
"stage_configs_path": path,
"trust_remote_code": True,
"interleave_mm_strings": True,
"media_io_kwargs": {"video": {"fps": 1, "num_frames": 128}},
"gpu_memory_utilization": 0.55,
}
# Mirror AsyncOmniEngine._resolve_stage_configs strip decision.
if kwargs.get("stage_configs_path") is not None and not is_new_format_deploy_config(kwargs["stage_configs_path"]):
base = AsyncOmniEngine._strip_single_engine_args(dict(kwargs))
else:
base = dict(kwargs)
assert base.get("interleave_mm_strings") is True
assert base.get("media_io_kwargs") == {"video": {"fps": 1, "num_frames": 128}}
# Parent EngineArgs fields also remain available for deploy merge.
assert base.get("gpu_memory_utilization") == 0.55
legacy = tmp_path / "legacy.yaml"
legacy.write_text("stage_args:\n - stage_id: 0\n", encoding="utf-8")
assert not is_new_format_deploy_config(str(legacy))
legacy_kwargs = dict(kwargs, stage_configs_path=str(legacy))
stripped = AsyncOmniEngine._strip_single_engine_args(legacy_kwargs)
assert "interleave_mm_strings" not in stripped
assert "media_io_kwargs" not in stripped
assert "gpu_memory_utilization" not in stripped
# For https://github.com/vllm-project/vllm-omni/issues/3293
def test_tensor_parallel_size_none_is_handled():
"""Ensure the tensor parallel size of None isn't forwarded."""
+2 -2
View File
@@ -50,7 +50,7 @@ async def generate(
output_modalities=["text"],
):
stage_id = omni_output.stage_id
out = omni_output.request_output
out = omni_output
if stage_id == 0:
num_tokens = sum(len(output.token_ids) for output in out.outputs)
count = num_tokens
@@ -68,7 +68,7 @@ async def test_abort():
with ExitStack() as after:
engine = AsyncOmni(
model=model,
stage_configs_path=stage_config,
deploy_config=stage_config,
)
after.callback(engine.shutdown)
+246 -148
View File
@@ -4,171 +4,269 @@
import pytest
from PIL import Image
from pytest_mock import MockerFixture
from vllm.outputs import CompletionOutput, RequestOutput
from vllm_omni.outputs import OmniRequestOutput
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
class TestOmniRequestOutput:
"""Tests for OmniRequestOutput class."""
# ── helpers ────────────────────────────────────────────────────────────────
def test_from_diffusion(self):
"""Test creating output from diffusion model."""
images = [Image.new("RGB", (64, 64), color="red")]
output = OmniRequestOutput.from_diffusion(
request_id="test-123",
images=images,
prompt="a cat",
def _make_text_request_output(
request_id: str = "req-1",
text: str = "hello world",
token_ids: list[int] | None = None,
finished: bool = True,
) -> RequestOutput:
"""Build a minimal vLLM RequestOutput for testing."""
return RequestOutput(
request_id=request_id,
prompt="test prompt",
prompt_token_ids=[1, 2, 3],
prompt_logprobs=None,
outputs=[
CompletionOutput(
index=0,
text=text,
token_ids=token_ids or [10, 11, 12],
cumulative_logprob=-1.0,
logprobs=None,
finish_reason="stop" if finished else None,
stop_reason=None,
)
],
finished=finished,
metrics=None,
lora_request=None,
)
# ── from_stage_output ──────────────────────────────────────────────────────
class TestFromStageOutput:
"""Tests for OmniRequestOutput.from_stage_output()."""
def test_copies_request_output_content(self):
"""Content from a vLLM RequestOutput is flattened onto the new object."""
source = _make_text_request_output(text="copied text")
out = OmniRequestOutput.from_stage_output(source, request_id="req-1", stage_id=0, final_output_type="text")
assert out.prompt == "test prompt"
assert out.prompt_token_ids == [1, 2, 3]
assert len(out.outputs) == 1
assert out.outputs[0].text == "copied text"
assert out.finished is True
assert out.stage_id == 0
assert out.final_output_type == "text"
def test_copies_omni_content(self):
"""Diffusion fields are copied when source is another OmniRequestOutput."""
image = Image.new("RGB", (64, 64), color="blue")
inner = OmniRequestOutput.from_diffusion(request_id="req-diff", images=[image], prompt="a cat")
outer = OmniRequestOutput.from_stage_output(inner, request_id="req-diff", stage_id=0, final_output_type="image")
assert len(outer.images) == 1
assert outer.images[0] is image
assert outer.prompt == "a cat"
assert outer.is_diffusion_output
def test_with_duck_typed_source(self):
"""A duck-typed source (SimpleNamespace-style) copies correctly."""
from types import SimpleNamespace
source = SimpleNamespace(
outputs=[],
prompt="duck prompt",
prompt_token_ids=[7, 8, 9],
finished=False,
)
out = OmniRequestOutput.from_stage_output(source, request_id="duck-1", stage_id=2)
assert out.prompt == "duck prompt"
assert out.prompt_token_ids == [7, 8, 9]
assert out.finished is False
assert out.stage_id == 2
def test_request_id_always_copied_from_source(self):
"""request_id is always copied from source, even when passed in kwargs."""
source = _make_text_request_output(request_id="source-id")
out = OmniRequestOutput.from_stage_output(source, request_id="kwargs-id", stage_id=1)
# Source wins — request_id is content, not a control field.
assert out.request_id == "source-id"
def test_passes_control_fields(self):
"""Control fields (metrics, stage_durations, peak_memory_mb) are set."""
source = _make_text_request_output()
out = OmniRequestOutput.from_stage_output(
source,
request_id="r1",
stage_id=3,
metrics={"ttft": 0.5},
stage_durations={"prefill": 0.12},
peak_memory_mb=1024.0,
)
assert out.metrics == {"ttft": 0.5}
assert out.stage_durations == {"prefill": 0.12}
assert out.peak_memory_mb == 1024.0
def test_finished_field_copied(self):
"""The *finished* flag is copied from the source when present."""
source = _make_text_request_output(finished=False)
out = OmniRequestOutput.from_stage_output(source, request_id="r1")
assert out.finished is False
source2 = _make_text_request_output(finished=True)
out2 = OmniRequestOutput.from_stage_output(source2, request_id="r2")
assert out2.finished is True
def test_outputs_field_copied(self):
"""The *outputs* list is copied from the source."""
source = _make_text_request_output(text="hello", token_ids=[1, 2, 3])
out = OmniRequestOutput.from_stage_output(source, request_id="r1")
assert len(out.outputs) == 1
assert out.outputs[0].text == "hello"
assert out.outputs[0].token_ids == [1, 2, 3]
# ── dataclass safety ────────────────────────────────────────────────────────
class TestDataclassSafety:
def test_from_stage_output_is_classmethod(self):
"""from_stage_output must be a classmethod."""
assert callable(OmniRequestOutput.from_stage_output)
# ── msgpack round-trip ─────────────────────────────────────────────────────
class TestMsgpackRoundTrip:
"""Tests that OmniRequestOutput survives msgpack encode → decode without
infinite recursion or data loss."""
def test_round_trip_pipeline_output(self):
"""A pipeline output round-trips without data loss."""
from vllm_omni.distributed.omni_connectors.utils.serialization import (
OmniMsgpackDecoder,
OmniMsgpackEncoder,
)
source = _make_text_request_output(text="round trip")
out = OmniRequestOutput.from_stage_output(
source,
request_id="rt-1",
stage_id=0,
final_output_type="text",
)
encoder = OmniMsgpackEncoder()
decoder = OmniMsgpackDecoder()
encoded = encoder.encode(out)
decoded = decoder.decode(encoded)
assert isinstance(decoded, OmniRequestOutput)
assert decoded.request_id == "req-1"
assert decoded.stage_id == 0
assert decoded.final_output_type == "text"
assert decoded.finished is True
assert decoded.outputs[0].text == "round trip"
assert decoded.prompt == "test prompt"
assert decoded.prompt_token_ids == [1, 2, 3]
def test_round_trip_diffusion_output(self):
"""A diffusion output round-trips without data loss."""
from vllm_omni.distributed.omni_connectors.utils.serialization import (
OmniMsgpackDecoder,
OmniMsgpackEncoder,
)
image = Image.new("RGB", (64, 64), color="red")
out = OmniRequestOutput.from_diffusion(
request_id="diff-1",
images=[image],
prompt="a red image",
metrics={"steps": 50},
)
assert output.request_id == "test-123"
assert output.images == images
assert output.prompt == "a cat"
assert output.metrics == {"steps": 50}
assert output.is_diffusion_output
assert output.num_images == 1
def test_from_pipeline(self, mocker: MockerFixture):
"""Test creating output from pipeline stage."""
mock_request_output = mocker.Mock()
mock_request_output.request_id = "pipeline-123"
mock_request_output.prompt_token_ids = [1, 2, 3]
mock_request_output.outputs = [mocker.Mock()]
mock_request_output.encoder_prompt_token_ids = None
mock_request_output.prompt_logprobs = None
mock_request_output.num_cached_tokens = 10
mock_request_output.kv_transfer_params = None
mock_request_output.multimodal_output = {"image": mocker.Mock()}
output = OmniRequestOutput.from_pipeline(
stage_id=0,
final_output_type="text",
request_output=mock_request_output,
multimodal_output={"audio": None},
)
assert output.request_id == "pipeline-123"
assert output.stage_id == 0
assert output.final_output_type == "text"
assert output.is_pipeline_output
encoder = OmniMsgpackEncoder()
decoder = OmniMsgpackDecoder()
def test_prompt_token_ids_property(self, mocker: MockerFixture):
"""Test prompt_token_ids property for streaming compatibility."""
mock_request_output = mocker.Mock()
mock_request_output.prompt_token_ids = [1, 2, 3, 4, 5]
encoded = encoder.encode(out)
decoded = decoder.decode(encoded)
output = OmniRequestOutput.from_pipeline(
stage_id=0,
final_output_type="text",
request_output=mock_request_output,
assert isinstance(decoded, OmniRequestOutput)
assert decoded.request_id == "diff-1"
assert decoded.prompt == "a red image"
assert decoded.num_images == 1
assert decoded.images[0].size == (64, 64)
assert decoded.metrics == {"steps": 50}
def test_round_trip_does_not_recurse(self):
"""Encoding a pipeline output must not trigger infinite recursion."""
from vllm_omni.distributed.omni_connectors.utils.serialization import (
OmniMsgpackEncoder,
)
assert output.prompt_token_ids == [1, 2, 3, 4, 5]
source = _make_text_request_output(text="no recursion")
out = OmniRequestOutput.from_stage_output(source, request_id="rec-1", stage_id=0)
def test_prompt_token_ids_none_when_no_request_output(self):
"""Test prompt_token_ids returns None when no request_output."""
output = OmniRequestOutput.from_diffusion(
request_id="test-123",
images=[],
prompt="a cat",
)
assert output.prompt_token_ids is None
encoder = OmniMsgpackEncoder()
encoded = encoder.encode(out)
assert isinstance(encoded, bytes)
assert len(encoded) > 0
def test_outputs_property(self, mocker: MockerFixture):
"""Test outputs property for chat completion compatibility."""
mock_output = mocker.Mock()
mock_request_output = mocker.Mock()
mock_request_output.outputs = [mock_output]
output = OmniRequestOutput.from_pipeline(
stage_id=0,
final_output_type="text",
request_output=mock_request_output,
def test_legacy_wire_format_deserialized(self):
"""When the wire format contains a nested ``request_output`` key
(pre-inheritance legacy), it is merged via _copy_content_from."""
from vllm_omni.distributed.omni_connectors.utils.serialization import (
OmniMsgpackDecoder,
)
assert output.outputs == [mock_output]
# Build a legacy-style dict: OmniRequestOutput fields + a nested
# request_output dict containing RequestOutput-like content.
legacy_dict = {
"request_id": "legacy-1",
"finished": True,
"stage_id": 1,
"final_output_type": "text",
"images": [],
"_multimodal_output": {},
"_custom_output": {},
"stage_durations": {},
"peak_memory_mb": 0.0,
# --- nested request_output key (legacy) ---
"request_output": {
"request_id": "legacy-1",
"prompt": "legacy prompt",
"prompt_token_ids": [1, 2],
"prompt_logprobs": None,
"outputs": [],
"finished": True,
"metrics": {},
"lora_request": None,
"encoder_prompt": None,
"encoder_prompt_token_ids": None,
"num_cached_tokens": None,
"kv_transfer_params": None,
},
}
def test_outputs_empty_when_no_request_output(self):
"""Test outputs returns empty list when no request_output."""
output = OmniRequestOutput.from_diffusion(
request_id="test-123",
images=[],
prompt="a cat",
)
assert output.outputs == []
# Manually run the decoder's post_process to test legacy path.
# The decoder's _decode_omni_request_output pops "request_output"
# and merges it via _copy_content_from.
decoder = OmniMsgpackDecoder()
result = decoder._post_process(legacy_dict)
def test_encoder_prompt_token_ids_property(self, mocker: MockerFixture):
"""Test encoder_prompt_token_ids property."""
mock_request_output = mocker.Mock()
mock_request_output.encoder_prompt_token_ids = [10, 20, 30]
output = OmniRequestOutput.from_pipeline(
stage_id=0,
final_output_type="text",
request_output=mock_request_output,
)
assert output.encoder_prompt_token_ids == [10, 20, 30]
def test_num_cached_tokens_property(self, mocker: MockerFixture):
"""Test num_cached_tokens property."""
mock_request_output = mocker.Mock()
mock_request_output.num_cached_tokens = 42
output = OmniRequestOutput.from_pipeline(
stage_id=0,
final_output_type="text",
request_output=mock_request_output,
)
assert output.num_cached_tokens == 42
def test_multimodal_output_property(self, mocker: MockerFixture):
"""Test multimodal_output property."""
mock_request_output = mocker.Mock()
mock_audio = mocker.Mock()
expected_output = {"audio": mock_audio}
mock_request_output.outputs = []
mock_request_output.multimodal_output = expected_output
output = OmniRequestOutput.from_pipeline(
stage_id=0,
final_output_type="audio",
request_output=mock_request_output,
)
assert output.multimodal_output is expected_output
def test_to_dict_diffusion(self):
"""Test to_dict for diffusion output."""
output = OmniRequestOutput.from_diffusion(
request_id="test-123",
images=[Image.new("RGB", (64, 64), color="red")],
prompt="a cat",
metrics={"steps": 50},
)
result = output.to_dict()
assert result["request_id"] == "test-123"
assert result["finished"] is True
assert result["final_output_type"] == "image"
assert result["num_images"] == 1
assert result["prompt"] == "a cat"
def test_to_dict_pipeline(self, mocker: MockerFixture):
"""Test to_dict for pipeline output."""
mock_request_output = mocker.Mock()
mock_request_output.request_id = "pipeline-123"
output = OmniRequestOutput.from_pipeline(
stage_id=0,
final_output_type="text",
request_output=mock_request_output,
)
result = output.to_dict()
assert result["request_id"] == "pipeline-123"
assert result["finished"] is True
assert result["final_output_type"] == "text"
assert result["stage_id"] == 0
assert isinstance(result, OmniRequestOutput)
assert result.request_id == "legacy-1"
assert result.finished is True
# Content merged from legacy nested key
assert result.prompt == "legacy prompt"
assert result.prompt_token_ids == [1, 2]
+2 -2
View File
@@ -428,7 +428,7 @@ class TestSingleStageModeDetection:
assert engine.single_stage_mode is False
assert engine._single_stage_id_filter is None
def test_stage_configs_path_loads_duplex_runtime_config(self, mocker: MockerFixture):
def test_deploy_config_loads_duplex_runtime_config(self, mocker: MockerFixture):
duplex_session = DuplexSessionRuntimeConfig(max_sessions=2)
get_pipeline_config = mocker.patch(
"vllm_omni.engine.async_omni_engine.StageConfigFactory.get_pipeline_config",
@@ -441,7 +441,7 @@ class TestSingleStageModeDetection:
engine = self._make_engine_no_thread(
mocker,
stage_configs_path="/fake/duplex.yaml",
deploy_config="/fake/duplex.yaml",
)
get_pipeline_config.assert_called_once_with(
@@ -2156,12 +2156,12 @@ def test_direct_listen_decision_survives_inner_completion_metadata():
)
assert decision is not None
output = attach_duplex_output_decision(
OmniRequestOutput(
OmniRequestOutput.from_stage_output(
inner_output,
request_id="duplex-direct-listen",
finished=True,
stage_id=0,
final_output_type=decision.final_output_type,
request_output=inner_output,
metrics={
"stage_metrics": {
"0": {
@@ -3049,12 +3049,12 @@ async def test_minicpmo_auto_response_listen_without_response_does_not_defer_com
)
assert decision is not None
listen_output = attach_duplex_output_decision(
OmniRequestOutput(
OmniRequestOutput.from_stage_output(
inner_output,
request_id=request_id,
finished=True,
stage_id=0,
final_output_type=decision.final_output_type,
request_output=inner_output,
),
decision,
)
@@ -119,7 +119,6 @@ class MockGenerationResult:
def __init__(self, images):
self.images = images
self.request_output = SimpleNamespace(images=images)
self.stage_durations = {}
self.peak_memory_mb = 0.0
@@ -137,10 +136,7 @@ class MockStageResult:
outputs = [SimpleNamespace(text=text, index=0)]
else:
outputs = []
self.request_output = SimpleNamespace(
outputs=outputs,
images=self.images,
)
self.outputs = outputs
self.stage_durations = {}
self.peak_memory_mb = 0.0
@@ -2080,22 +2076,20 @@ def test_extract_images_from_result():
assert all(isinstance(img, Image.Image) for img in images)
assert all(img.size == (64, 64) for img in images)
# Test dict path: result.request_output["images"]
# Test result with "images" attribute set in __init__
class DictRequestOutput:
def __init__(self):
self.request_output = {"images": [np.random.randint(0, 255, (64, 64, 3), dtype=np.uint8)]}
self.images = [np.random.randint(0, 255, (64, 64, 3), dtype=np.uint8)]
result = DictRequestOutput()
images = _extract_images_from_result(result)
assert len(images) == 1
assert isinstance(images[0], Image.Image)
# Test attribute path: result.request_output.images
# Test result with "images" attribute from an inner object
class AttrRequestOutput:
def __init__(self):
self.request_output = type(
"obj", (), {"images": [np.random.randint(0, 255, (32, 32, 3), dtype=np.uint8)]}
)()
self.images = [np.random.randint(0, 255, (32, 32, 3), dtype=np.uint8)]
result = AttrRequestOutput()
images = _extract_images_from_result(result)
@@ -180,10 +180,10 @@ def create_mock_audio_output_for_test(
audio_tensor = torch.sin(torch.linspace(0, 440 * 2 * torch.pi, num_samples))
mock_request_output = MockRequestOutput(request_id=request_id, audio_tensor=audio_tensor)
return OmniRequestOutput(
return OmniRequestOutput.from_stage_output(
mock_request_output,
stage_id=0,
final_output_type="audio",
request_output=mock_request_output,
)
@@ -680,7 +680,7 @@ class TestSpeechAPI:
@pytest.mark.asyncio
async def test_create_diffusion_speech_extra_params(self, mocker: MockerFixture):
"""Test that extra_params are correctly applied to sampling_params_list in diffusion mode."""
"""Test public diffusion speech success and extra_params propagation."""
# Mock the engine client
mock_engine = mocker.MagicMock()
@@ -704,7 +704,11 @@ class TestSpeechAPI:
req = OpenAICreateSpeechRequest(input="Hello", extra_params={"new_arg": 123, "existing_arg": "new_value"})
await server._create_diffusion_speech(req)
response = await server.create_speech(req)
assert response.status_code == 200
assert response.media_type == "audio/wav"
assert response.body == b"dummy"
# Verify generate was called
mock_engine.generate.assert_called_once()
@@ -737,6 +741,19 @@ class TestTTSMethods:
yield server
server.shutdown()
def test_diffusion_audio_encode_speed_skips_ar_adapter(self, mocker: MockerFixture):
"""Pure-diffusion speech keeps generic speed handling outside AR adapters."""
server = OmniOpenAIServingSpeech.for_diffusion(
diffusion_engine=mocker.MagicMock(),
model_name="test-model",
)
resolve_adapter = mocker.patch.object(serving_speech_module, "resolve_adapter")
speed = server._audio_encode_speed(OpenAICreateSpeechRequest(input="Hello", speed=1.25))
assert speed == 1.25
resolve_adapter.assert_not_called()
def test_is_tts_detection_no_stage(self, speech_server):
"""Test TTS model detection when no TTS stage exists."""
# Fixture creates server with stage_configs = [] -> _is_tts should be False
@@ -2292,10 +2309,10 @@ class TestStreamingResponse:
self.prompt_logprobs = None
self.kv_transfer_params = None
return OmniRequestOutput(
return OmniRequestOutput.from_stage_output(
MockRequestOutput(audio_tensor=chunk),
stage_id=0,
final_output_type="audio",
request_output=MockRequestOutput(audio_tensor=chunk),
finished=finished,
)
@@ -3441,10 +3458,10 @@ class TestWAVStreaming:
self.prompt_logprobs = None
self.kv_transfer_params = None
return OmniRequestOutput(
return OmniRequestOutput.from_stage_output(
MockRequestOutput(audio_tensor=chunk),
stage_id=0,
final_output_type="audio",
request_output=MockRequestOutput(audio_tensor=chunk),
finished=finished,
)
@@ -3,6 +3,7 @@ import base64
from types import SimpleNamespace
import pytest
import torch
from fastapi import FastAPI, WebSocket
from pytest_mock import MockerFixture
from starlette.testclient import TestClient
@@ -11,11 +12,24 @@ from starlette.websockets import WebSocketDisconnect
from vllm_omni.entrypoints.openai import serving_speech_stream as streaming_speech_module
from vllm_omni.entrypoints.openai.serving_speech import OmniOpenAIServingSpeech
from vllm_omni.entrypoints.openai.serving_speech_stream import OmniStreamingSpeechHandler
from vllm_omni.utils.forced_aligner import WordTimestamp
from vllm_omni.model_executor.stage_input_processors.forced_aligner import ALIGNER_WORDS_KEY
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
def _fake_aligner_res(pairs, words):
"""Build a stand-in for the forced-aligner stage's pooling output.
Mirrors what rides the generator in production: ``res.outputs.data`` is a
``[n_words, 2]`` int32 tensor of ``[start_ms, end_ms]`` and the word strings
travel in ``additional_information``. Decoded by ``extract_word_timestamps``.
"""
return SimpleNamespace(
outputs=SimpleNamespace(data=torch.tensor(pairs, dtype=torch.int32), additional_information=None),
additional_information={ALIGNER_WORDS_KEY: list(words)},
)
def _build_test_app(
speech_service=None,
*,
@@ -28,9 +42,9 @@ def _build_test_app(
speech_service = mocker.MagicMock(spec=OmniOpenAIServingSpeech)
speech_service._generate_audio_bytes = mocker.AsyncMock(return_value=(b"RIFF" + b"\x00" * 32, "audio/wav"))
speech_service._prepare_speech_generation = mocker.AsyncMock(return_value=("req-1", object(), {}))
speech_service.forced_aligner_config = None
speech_service.forced_aligner_enabled = False
async def mock_generate_pcm_chunks(_generator, _request_id, *, include_sample_rate=False):
async def mock_generate_pcm_chunks(_generator, _request_id, *, include_sample_rate=False, collect=None):
for chunk in (b"\x01\x02", b"\x03\x04\x05"):
yield (chunk, 24000) if include_sample_rate else chunk
@@ -235,7 +249,7 @@ class TestStreamingSpeechWebSocket:
speech_service._generate_audio_bytes = mocker.AsyncMock(return_value=(b"", "audio/wav"))
speech_service.engine_client = mocker.MagicMock()
speech_service.engine_client.abort = mocker.AsyncMock()
speech_service.forced_aligner_config = None
speech_service.forced_aligner_enabled = False
async def mock_prepare_speech_generation(request):
captured_requests.append(request)
@@ -311,13 +325,13 @@ class TestStreamingSpeechWebSocket:
assert error["type"] == "error"
assert "without --forced-aligner" in error["message"]
def test_word_timestamps_emit_sidecar_json_frame(self, mocker: MockerFixture):
def test_word_timestamps_emit_pipeline_json_frame(self, mocker: MockerFixture):
captured_requests = []
speech_service = mocker.MagicMock(spec=OmniOpenAIServingSpeech)
speech_service._generate_audio_bytes = mocker.AsyncMock(return_value=(b"", "audio/wav"))
speech_service.engine_client = mocker.MagicMock()
speech_service.engine_client.abort = mocker.AsyncMock()
speech_service.forced_aligner_config = SimpleNamespace(model="aligner")
speech_service.forced_aligner_enabled = True
async def mock_prepare_speech_generation(request):
captured_requests.append(request)
@@ -328,19 +342,15 @@ class TestStreamingSpeechWebSocket:
first_chunk = b"\x01" * 1000
second_chunk = b"\x02" * 1000
async def mock_generate_pcm_chunks(_generator, _request_id, *, include_sample_rate=False):
# The forced-aligner stage rides the same generator: its pooling output
# is surfaced via the ``collect`` channel once the audio has streamed.
async def mock_generate_pcm_chunks(_generator, _request_id, *, include_sample_rate=False, collect=None):
for chunk in (first_chunk, second_chunk):
yield (chunk, 1000) if include_sample_rate else chunk
if collect is not None:
collect["aligner_res"] = _fake_aligner_res([[0, 200], [200, 900]], ["Hello", "world"])
speech_service._generate_pcm_chunks = mock_generate_pcm_chunks
# Sentence-level: aligner runs once over the whole sentence audio.
mock_align = mocker.AsyncMock(
return_value=[
WordTimestamp("Hello", 0, 200),
WordTimestamp("world", 200, 900),
]
)
mocker.patch.object(streaming_speech_module, "forced_align", mock_align)
app, _ = _build_test_app(speech_service)
with TestClient(app) as client:
@@ -406,7 +416,6 @@ class TestStreamingSpeechWebSocket:
}
assert captured_requests[0].word_timestamps is True
assert mock_align.await_count == 1
def test_word_timestamps_emit_word_dicts(self, mocker: MockerFixture):
# The streaming layer forwards the aligner's (already monotonic,
@@ -415,21 +424,16 @@ class TestStreamingSpeechWebSocket:
speech_service._generate_audio_bytes = mocker.AsyncMock(return_value=(b"", "audio/wav"))
speech_service.engine_client = mocker.MagicMock()
speech_service.engine_client.abort = mocker.AsyncMock()
speech_service.forced_aligner_config = SimpleNamespace(model="aligner")
speech_service.forced_aligner_enabled = True
speech_service._prepare_speech_generation = mocker.AsyncMock(return_value=("req", object(), {}))
async def mock_generate_pcm_chunks(_generator, _request_id, *, include_sample_rate=False):
async def mock_generate_pcm_chunks(_generator, _request_id, *, include_sample_rate=False, collect=None):
chunk = b"\x01" * 1000
yield (chunk, 1000) if include_sample_rate else chunk
if collect is not None:
collect["aligner_res"] = _fake_aligner_res([[0, 1000], [1000, 1200]], ["Hello", "world"])
speech_service._generate_pcm_chunks = mock_generate_pcm_chunks
mock_align = mocker.AsyncMock(
return_value=[
WordTimestamp("Hello", 0, 1000),
WordTimestamp("world", 1000, 1200),
]
)
mocker.patch.object(streaming_speech_module, "forced_align", mock_align)
app, _ = _build_test_app(speech_service)
with TestClient(app) as client:
@@ -572,7 +576,7 @@ class TestStreamingSpeechWebSocket:
speech_service._generate_pcm_chunks = mocker.AsyncMock()
speech_service.engine_client = mocker.MagicMock()
speech_service.engine_client.abort = mocker.AsyncMock()
speech_service.forced_aligner_config = None
speech_service.forced_aligner_enabled = False
app, _ = _build_test_app(speech_service)
with TestClient(app) as client:
@@ -602,7 +606,7 @@ class TestStreamingSpeechWebSocket:
speech_service._prepare_speech_generation = mocker.AsyncMock(return_value=("req-stream-err", object(), {}))
speech_service.engine_client = mocker.MagicMock()
speech_service.engine_client.abort = mocker.AsyncMock()
speech_service.forced_aligner_config = None
speech_service.forced_aligner_enabled = False
async def mock_generate_pcm_chunks(_generator, _request_id, *, include_sample_rate=False):
yield b"\x01\x02"
@@ -696,7 +700,7 @@ class TestStreamingSpeechWebSocket:
speech_service._prepare_speech_generation = mocker.AsyncMock(return_value=("req-abort", object(), {}))
speech_service.engine_client = mocker.MagicMock()
speech_service.engine_client.abort = mocker.AsyncMock()
speech_service.forced_aligner_config = None
speech_service.forced_aligner_enabled = False
async def mock_generate_pcm_chunks(_generator, _request_id, *, include_sample_rate=False):
yield b"\x01\x02"
@@ -47,7 +47,7 @@ def _text_result(text: str) -> OmniRequestOutput:
output.text = text
request_output = RequestOutput()
request_output.outputs = [output]
return OmniRequestOutput(final_output_type="text", request_output=request_output)
return OmniRequestOutput.from_stage_output(request_output, final_output_type="text")
def _audio_result(audio_data: Any) -> OmniRequestOutput:
@@ -61,7 +61,7 @@ def _audio_result(audio_data: Any) -> OmniRequestOutput:
output.multimodal_output = {"audio": audio_data}
request_output = RequestOutput()
request_output.outputs = [output]
return OmniRequestOutput(final_output_type="audio", request_output=request_output)
return OmniRequestOutput.from_stage_output(request_output, final_output_type="audio")
class MockWebSocket:
+1 -1
View File
@@ -364,7 +364,7 @@ async def test_omni_generate_request_id():
Text modality only; asserts caller-visible ids are preserved across the
multi-stage orchestrator path on H100.
"""
engine = AsyncOmni(model=OMNI_MODEL, stage_configs_path=OMNI_STAGE_CONFIG)
engine = AsyncOmni(model=OMNI_MODEL, deploy_config=OMNI_STAGE_CONFIG)
try:
for req_id in _OMNI_REQ_IDS:
async for output in engine.generate(
@@ -478,12 +478,11 @@ def test_resolve_stage_configs_injects_additional_config_into_diffusion_stage(mo
)
engine = AsyncOmniEngine.__new__(AsyncOmniEngine)
engine._strip_single_engine_args = lambda kwargs: kwargs
_, stage_configs = engine._resolve_stage_configs(
"dummy-model",
{
"stage_configs_path": "dummy.yaml",
"deploy_config": "dummy.yaml",
"additional_config": {"torchair_graph_config": {"enabled": True}},
},
trust_remote_code=False,
@@ -516,12 +515,11 @@ def test_resolve_stage_configs_injects_quantization_config_into_diffusion_stage(
)
engine = AsyncOmniEngine.__new__(AsyncOmniEngine)
engine._strip_single_engine_args = lambda kwargs: kwargs
_, stage_configs = engine._resolve_stage_configs(
"dummy-model",
{
"stage_configs_path": "dummy.yaml",
"deploy_config": "dummy.yaml",
"quantization_config": {"method": "bitsandbytes"},
},
trust_remote_code=False,
+4 -6
View File
@@ -480,11 +480,9 @@ def test_async_omni_duplex_direct_output_prefers_outer_control_metadata():
OmniRequestOutput(
request_id="duplex-sid-e0-stage0",
stage_id=0,
request_output=SimpleNamespace(
outputs=[],
multimodal_output=SimpleNamespace(kind="processed-payload"),
_custom_output={"inner": "completion"},
),
outputs=[],
_multimodal_output={"kind": "processed-payload"},
_custom_output={"inner": "completion"},
),
decision,
)
@@ -557,7 +555,7 @@ async def test_async_omni_duplex_collect_wraps_raw_response_stage_output():
assert outputs[0].finished is False
assert outputs[0].stage_id == 1
assert outputs[0].final_output_type == "audio"
assert outputs[0].request_output is raw_stage1_output
assert outputs[0].peak_memory_mb == raw_stage1_output.peak_memory_mb
def test_async_omni_duplex_request_info_includes_response_stage():
+9 -10
View File
@@ -72,8 +72,8 @@ def make_output_msg(
final_output_type=final_output_type,
images=images or [],
stage_durations={},
outputs=[SimpleNamespace(text=payload, index=0)],
)
engine_output.payload = payload
return OutputMessage(
request_id=request_id,
stage_id=stage_id,
@@ -474,7 +474,7 @@ async def test_async_omni_yields_only_final_stage_outputs(monkeypatch: pytest.Mo
app.shutdown()
assert [output.stage_id for output in outputs] == [2]
assert [output.request_output.payload for output in outputs] == ["final"]
assert [output.outputs[0].text for output in outputs] == ["final"]
assert "req-1" not in app.request_states
@@ -492,7 +492,7 @@ async def test_async_omni_accepts_multiple_final_stage_streams(monkeypatch: pyte
app.shutdown()
assert [output.stage_id for output in outputs] == [0, 0, 0, 2, 2, 2]
assert [output.request_output.payload for output in outputs] == [
assert [output.outputs[0].text for output in outputs] == [
"req-1-stage0-0",
"req-1-stage0-1",
"req-1-stage0-2",
@@ -517,7 +517,7 @@ async def test_async_omni_stops_on_final_stage_finished(monkeypatch: pytest.Monk
finally:
app.shutdown()
assert [output.request_output.payload for output in outputs] == [
assert [output.outputs[0].text for output in outputs] == [
"req-1-stage0",
"req-1-stage2-final",
]
@@ -544,7 +544,7 @@ async def test_async_omni_diffusion_only_yields_single_image_output(monkeypatch:
assert outputs[0].stage_id == 0
assert outputs[0].final_output_type == "image"
assert outputs[0].images == ["req-1-image"]
assert outputs[0].request_output.payload == "req-1-diffusion-final"
assert outputs[0].outputs[0].text == "req-1-diffusion-final"
@pytest.mark.asyncio
@@ -565,7 +565,7 @@ async def test_async_omni_llm_diffusion_yields_text_stream_then_image(monkeypatc
assert [output.stage_id for output in outputs] == [0, 0, 0, 1]
assert [output.final_output_type for output in outputs] == ["text", "text", "text", "image"]
assert [output.request_output.payload for output in outputs] == [
assert [output.outputs[0].text for output in outputs] == [
"req-1-text-0",
"req-1-text-1",
"req-1-text-2",
@@ -695,7 +695,7 @@ def test_omni_generate_py_generator_yields_final_outputs_for_each_request(monkey
assert len(outputs) == 4
assert [output.stage_id for output in outputs] == [0, 2, 0, 2]
assert [output.request_output.payload for output in outputs] == [
assert [output.outputs[0].text for output in outputs] == [
f"{engine.submitted[0]['request_id']}-stage0-0",
f"{engine.submitted[0]['request_id']}-stage2-final",
f"{engine.submitted[1]['request_id']}-stage0-0",
@@ -739,7 +739,7 @@ def test_omni_generate_diffusion_only_yields_single_image_per_request(monkeypatc
assert len(outputs) == 2
assert [output.stage_id for output in outputs] == [0, 0]
assert [output.final_output_type for output in outputs] == ["image", "image"]
assert [output.request_output.payload for output in outputs] == [
assert [output.outputs[0].text for output in outputs] == [
f"{engine.submitted[0]['request_id']}-diffusion-final",
f"{engine.submitted[1]['request_id']}-diffusion-final",
]
@@ -767,7 +767,7 @@ def test_omni_generate_llm_diffusion_yields_final_text_then_image_per_request(
assert len(outputs) == 4
assert [output.stage_id for output in outputs] == [0, 1, 0, 1]
assert [output.final_output_type for output in outputs] == ["text", "image", "text", "image"]
assert [output.request_output.payload for output in outputs] == [
assert [output.outputs[0].text for output in outputs] == [
f"{engine.submitted[0]['request_id']}-text-0",
f"{engine.submitted[0]['request_id']}-image-final",
f"{engine.submitted[1]['request_id']}-text-0",
@@ -1046,7 +1046,6 @@ def _enqueue_stage_error(
if kill_engine:
engine._alive = False
engine_output = OmniRequestOutput.from_error(msg["request_id"], error_text)
engine_output.payload = ""
engine.output_q.put_nowait(
OutputMessage(
request_id=msg["request_id"],
+1 -1
View File
@@ -205,7 +205,7 @@ def test_run_headless_parses_and_forwards_stage_overrides(mocker: MockerFixture)
with pytest.raises(ValueError, match="No stage config found for stage_id=0"):
run_headless(args)
assert captured["args"][1] is None
assert len(captured["args"]) == 2
assert captured["deploy_config_path"] == "/tmp/deploy.yaml"
assert captured["stage_overrides"] == {"0": {"devices": "0,1"}, "1": {"devices": "2"}}
assert captured["strategy_config_path"] == "/tmp/strategy.yaml"
@@ -69,10 +69,10 @@ def _make_text_omni_output(
],
finished=finish_reason is not None,
)
return OmniRequestOutput(
return OmniRequestOutput.from_stage_output(
res,
request_id=request_id,
final_output_type="text",
request_output=res,
finished=finish_reason is not None,
)
@@ -108,12 +108,12 @@ def _make_audio_omni_output(
outputs=[completion],
finished=True,
)
return OmniRequestOutput(
return OmniRequestOutput.from_stage_output(
res,
request_id=request_id,
stage_id=stage_id,
replica_id=replica_id,
final_output_type="audio",
request_output=res,
finished=True,
)
@@ -151,7 +151,7 @@ def _build_serving_chat():
)
instance._create_audio_choice = MagicMock(
side_effect=lambda omni_res, role, request, stream=False: _mock_audio_choices(
index=omni_res.request_output.outputs[0].index,
index=omni_res.outputs[0].index,
role=role,
)
)
@@ -489,7 +489,7 @@ async def test_audio_chunk_without_waveform_keeps_stream_alive():
request = _make_request(modalities=["text", "audio"])
empty_audio = _make_audio_omni_output()
empty_audio.request_output.outputs[0].multimodal_output = {"audio": []}
empty_audio.outputs[0].multimodal_output = {"audio": []}
def create_audio_choice(omni_res, role, request, stream=False):
return OmniOpenAIServingChat._create_audio_choice(serving_chat, omni_res, role, request, stream=stream)
+9 -7
View File
@@ -381,7 +381,6 @@ class TestLoadAndResolveStageConfigs:
config_path, stage_configs, _ = load_and_resolve_stage_configs(
model="black-forest-labs/FLUX.2-klein-4B",
stage_configs_path=None,
kwargs=kwargs,
trust_remote_code=False,
default_stage_cfg_factory=lambda: AsyncOmniEngine._create_default_diffusion_stage_cfg(kwargs),
@@ -390,9 +389,7 @@ class TestLoadAndResolveStageConfigs:
assert len(stage_configs) == 1
assert "dtype" in stage_configs[0]["engine_args"]
def test_stage_configs_path_promotes_new_deploy_yaml_without_expanding_replicas(
self, tmp_path, mocker: MockerFixture
):
def test_deploy_config_preserves_cli_overrides_and_replicas(self, tmp_path, mocker: MockerFixture):
deploy_path = tmp_path / "qwen3_multi.yaml"
deploy_path.write_text(
'stages:\n - stage_id: 0\n devices: "0"\n - stage_id: 1\n devices: "1,2,3"\n num_replicas: 3\n',
@@ -413,18 +410,23 @@ class TestLoadAndResolveStageConfigs:
"vllm_omni.entrypoints.utils.load_stage_configs_from_model",
return_value=(returned_stage_configs, None),
)
cli_overrides = {
"interleave_mm_strings": True,
"media_io_kwargs": {"video": {"fps": 1, "num_frames": 128}},
"gpu_memory_utilization": 0.55,
}
config_path, stage_configs, _ = load_and_resolve_stage_configs(
model="dummy-model",
stage_configs_path=str(deploy_path),
kwargs={},
kwargs=cli_overrides,
trust_remote_code=True,
deploy_config_path=str(deploy_path),
)
load_stage_configs.assert_called_once_with(
"dummy-model",
trust_remote_code=True,
base_engine_args={},
base_engine_args=cli_overrides,
deploy_config_path=str(deploy_path),
stage_overrides=None,
strategy_config_path=None,
@@ -0,0 +1,91 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
import pytest
import torch
from examples.offline_inference.text_to_video.text_to_video import (
_MODEL_PRESETS,
_detect_preset,
_normalize_float_tensor,
build_text_to_video_prompt,
)
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
@pytest.mark.parametrize(
("negative_prompt", "expected_negative_prompt"),
[(None, None), ("", ""), ("blurry", "blurry")],
)
def test_text_to_video_builds_canonical_prompt(
negative_prompt: str | None,
expected_negative_prompt: str | None,
) -> None:
result = build_text_to_video_prompt("a robot waves", negative_prompt)
assert result["prompt"] == "a robot waves"
assert result["modalities"] == ["video"]
if expected_negative_prompt is None:
assert "negative_prompt" not in result
else:
assert result["negative_prompt"] == expected_negative_prompt
@pytest.mark.parametrize(
("model", "model_class_name", "preset_name"),
[
("robbyant/lingbot-video-dense-1.3b", None, "lingbot"),
("/models/custom-checkpoint", "LingBotVideoPipeline", "lingbot"),
("Lightricks/LTX-2", "LTX2DistilledPipeline", "ltx2_distilled"),
("BestWishYsh/Helios-Distilled", None, "helios"),
("/models/cosmos-edge", "Cosmos3EdgeVFMTransformer", "cosmos3_edge"),
("/models/vace", "WanVACEPipeline", "vace"),
],
)
def test_detect_preset_is_scoped_to_model_family(
model: str,
model_class_name: str | None,
preset_name: str,
) -> None:
assert _detect_preset(model, model_class_name) is _MODEL_PRESETS[preset_name]
def test_lingbot_preset_matches_lingbot_defaults() -> None:
assert _MODEL_PRESETS["lingbot"] == {
"model_class_name": "LingBotVideoPipeline",
"height": 192,
"width": 320,
"num_frames": 9,
"num_inference_steps": 2,
"guidance_scale": 3.0,
"fps": 24,
"flow_shift": 3.0,
"output": "lingbot_video_output.mp4",
}
def test_normalize_float_tensor_preserves_zero_to_one_frames() -> None:
frames = torch.tensor([0.0, 0.25, 1.0, 1.5])
assert torch.equal(_normalize_float_tensor(frames, "zero_to_one"), torch.tensor([0.0, 0.25, 1.0, 1.0]))
def test_normalize_float_tensor_maps_negative_one_to_one_frames() -> None:
frames = torch.tensor([-1.5, -1.0, 0.0, 1.0, 1.5])
assert torch.equal(
_normalize_float_tensor(frames, "negative_one_to_one"),
torch.tensor([0.0, 0.0, 0.5, 1.0, 1.0]),
)
def test_normalize_float_tensor_uses_one_contract_for_ambiguous_frames() -> None:
frames = [torch.tensor([0.0, 0.5, 1.0]), torch.tensor([-1.0, 0.0, 1.0])]
normalized = [_normalize_float_tensor(frame, "negative_one_to_one") for frame in frames]
assert torch.equal(normalized[0], torch.tensor([0.5, 0.75, 1.0]))
assert torch.equal(normalized[1], torch.tensor([0.0, 0.5, 1.0]))
+19 -1
View File
@@ -26,10 +26,28 @@ from PIL import Image
logger = logging.getLogger(__name__)
_synthetic_media_fallback_dir: Path | None = None
def _resolve_synthetic_media_cache_dir(cache_dir: Path | str | None) -> Path:
if cache_dir is not None:
return Path(cache_dir).expanduser().resolve()
return Path(tempfile.gettempdir()) / "vllm_omni_test_synthetic_media"
default = Path(tempfile.gettempdir()) / "vllm_omni_test_synthetic_media"
try:
default.mkdir(parents=True, exist_ok=True)
# Verify write access: the directory may exist but belong to
# another user (e.g. a previous CI job), causing PermissionError
# later when individual files are saved.
canary = default / ".write_test"
canary.touch()
canary.unlink()
return default
except (PermissionError, OSError):
global _synthetic_media_fallback_dir
if _synthetic_media_fallback_dir is None:
_synthetic_media_fallback_dir = Path(tempfile.mkdtemp(prefix="vllm_omni_test_synthetic_media_"))
return _synthetic_media_fallback_dir
def _np_array_from_mp4_bytes(video_bytes: bytes) -> np.ndarray:
+7 -12
View File
@@ -2635,7 +2635,7 @@ class OmniRunner:
# affects the test runner wrapper.
init_timeout: int = 1800,
log_stats: bool = False,
stage_configs_path: str | None = None,
deploy_config: str | None = None,
**kwargs,
) -> None:
startup_t0 = time.perf_counter()
@@ -2653,7 +2653,7 @@ class OmniRunner:
stage_init_timeout=stage_init_timeout,
batch_timeout=batch_timeout,
init_timeout=init_timeout,
stage_configs_path=stage_configs_path,
deploy_config=deploy_config,
**kwargs,
)
startup_s = time.perf_counter() - startup_t0
@@ -2938,9 +2938,9 @@ class OmniRunnerHandler:
audio_content = None
for stage_output in outputs:
if getattr(stage_output, "final_output_type", None) == "text":
text_content = stage_output.request_output.outputs[0].text
text_content = stage_output.outputs[0].text
if getattr(stage_output, "final_output_type", None) == "audio":
audio_content = stage_output.request_output.outputs[0].multimodal_output["audio"]
audio_content = stage_output.outputs[0].multimodal_output["audio"]
result.audio_content = audio_content
result.text_content = text_content
result.success = True
@@ -3080,7 +3080,7 @@ class OmniRunnerHandler:
mm_out: dict[str, Any] | None = None
for stage_out in outputs:
if getattr(stage_out, "final_output_type", None) == "audio":
mm_out = stage_out.request_output.outputs[0].multimodal_output
mm_out = stage_out.outputs[0].multimodal_output
break
if mm_out is None:
raise AssertionError("No audio output from pipeline")
@@ -3179,12 +3179,7 @@ def iter_omni_server(
print("OmniServer stopping...")
else:
if stage_config_path is not None:
from vllm_omni.entrypoints.utils import is_new_format_deploy_config
if is_new_format_deploy_config(stage_config_path):
server_args += ["--deploy-config", stage_config_path]
else:
server_args += ["--stage-configs-path", stage_config_path]
server_args += ["--deploy-config", stage_config_path]
with (
OmniServer(
@@ -3237,7 +3232,7 @@ def iter_omni_runner(
model = model_prefix + model
if run_level == "core_model" and request.node.get_closest_marker("diffusion"):
model = resolve_tiny_model_path(model)
with OmniRunner(model, seed=42, stage_configs_path=stage_config_path, **extra_omni_kwargs) as runner:
with OmniRunner(model, seed=42, deploy_config=stage_config_path, **extra_omni_kwargs) as runner:
print("OmniRunner started successfully")
yield runner
print("OmniRunner stopping...")
+147 -3
View File
@@ -42,6 +42,10 @@ _EXPECTED_FAMILIES = [
defs.AUDIO_UNDERRUN_S,
defs.AUDIO_CONTINUITY_OK_METRIC,
defs.AUDIO_SKIPPED_REQUESTS_METRIC,
defs.DIFFUSION_EXEC_S,
defs.DIFFUSION_EXEC_PER_STEP_S,
defs.DIFFUSION_PREPROCESS_S,
defs.DIFFUSION_POSTPROCESS_S,
]
@@ -55,6 +59,10 @@ class TestRegistration:
mod.observe_audio_underrun("s", "r", 0.01)
mod.inc_audio_continuity_ok("s", "r", 100)
mod.inc_audio_skipped("s", "r", "malformed_codec")
mod.observe_diffusion_exec("s", "r", 0.5)
mod.observe_diffusion_exec_per_step("s", "r", 0.01)
mod.observe_diffusion_preprocess("s", "r", 0.01)
mod.observe_diffusion_postprocess("s", "r", 0.2)
out = generate_latest(REGISTRY).decode()
for name in _EXPECTED_FAMILIES:
@@ -156,6 +164,50 @@ class TestAudio:
assert unknown == 1.0
# ---------------------------------------------------------------------------
# Diffusion observe API
# ---------------------------------------------------------------------------
class TestDiffusion:
def test_diffusion_exec_observed(self, mod: OmniModalityMetrics) -> None:
stage, replica = "dit_exec", "0"
mod.observe_diffusion_exec(stage, replica, 1.25)
out = generate_latest(REGISTRY).decode()
prefix = f'{defs.DIFFUSION_EXEC_S}_sum{{model_name="{_MODEL}",replica="{replica}",stage="{stage}"}}'
assert _sample_value(out, prefix) == 1.25
def test_diffusion_preprocess_observed(self, mod: OmniModalityMetrics) -> None:
stage, replica = "dit_pre", "0"
mod.observe_diffusion_preprocess(stage, replica, 0.03)
out = generate_latest(REGISTRY).decode()
prefix = f'{defs.DIFFUSION_PREPROCESS_S}_sum{{model_name="{_MODEL}",replica="{replica}",stage="{stage}"}}'
assert _sample_value(out, prefix) == pytest.approx(0.03)
def test_diffusion_postprocess_observed(self, mod: OmniModalityMetrics) -> None:
stage, replica = "dit_post", "0"
mod.observe_diffusion_postprocess(stage, replica, 0.8)
out = generate_latest(REGISTRY).decode()
prefix = f'{defs.DIFFUSION_POSTPROCESS_S}_sum{{model_name="{_MODEL}",replica="{replica}",stage="{stage}"}}'
assert _sample_value(out, prefix) == 0.8
def test_diffusion_exec_per_step_observed(self, mod: OmniModalityMetrics) -> None:
stage, replica = "dit_per_step", "0"
mod.observe_diffusion_exec_per_step(stage, replica, 0.078)
out = generate_latest(REGISTRY).decode()
prefix = f'{defs.DIFFUSION_EXEC_PER_STEP_S}_sum{{model_name="{_MODEL}",replica="{replica}",stage="{stage}"}}'
assert _sample_value(out, prefix) == pytest.approx(0.078)
def test_log_stats_false_skips(self) -> None:
silent = OmniModalityMetrics(model_name="silent-model", log_stats=False)
silent.observe_diffusion_exec("s", "r", 1.0)
silent.observe_diffusion_exec_per_step("s", "r", 0.02)
silent.observe_diffusion_preprocess("s", "r", 0.01)
silent.observe_diffusion_postprocess("s", "r", 0.5)
out = generate_latest(REGISTRY).decode()
assert 'model_name="silent-model"' not in out
# ---------------------------------------------------------------------------
# Stub-driven routing tests for the finalize / streaming helpers.
# ---------------------------------------------------------------------------
@@ -183,6 +235,18 @@ class _StubModMetrics:
def inc_audio_skipped(self, s, r, reason):
self.calls.append(("inc_audio_skipped", s, r, reason))
def observe_diffusion_exec(self, s, r, v):
self.calls.append(("observe_diffusion_exec", s, r, v))
def observe_diffusion_exec_per_step(self, s, r, v):
self.calls.append(("observe_diffusion_exec_per_step", s, r, v))
def observe_diffusion_preprocess(self, s, r, v):
self.calls.append(("observe_diffusion_preprocess", s, r, v))
def observe_diffusion_postprocess(self, s, r, v):
self.calls.append(("observe_diffusion_postprocess", s, r, v))
class _Bag:
def __init__(self, **kw):
@@ -239,8 +303,88 @@ class TestObserveModalityAtFinalize:
)
assert ("observe_audio_duration", "1", "0", 1.0) in stub.calls
def test_non_audio_output_type_skipped(self):
# Image / video / text output types are out of scope for this module.
def test_diffusion_path_full(self):
stub = _StubModMetrics()
stage_metrics = _Bag(
stage_gen_time_ms=1000.0,
diffusion_metrics={
"preprocess_time_s": 0.05,
"diffusion_engine_exec_time_s": 1.2,
"postprocess_time_s": 0.3,
"image_num": 1,
"resolution": 1024,
"num_inference_steps": 50,
},
)
observe_modality_at_finalize(
stub,
output_type="image",
stage_id=2,
replica_id=0,
stage_metrics=stage_metrics,
engine_outputs=_Bag(),
)
assert ("observe_diffusion_preprocess", "2", "0", 0.05) in stub.calls
assert ("observe_diffusion_exec", "2", "0", 1.2) in stub.calls
assert ("observe_diffusion_postprocess", "2", "0", 0.3) in stub.calls
assert ("observe_diffusion_exec_per_step", "2", "0", pytest.approx(0.024)) in stub.calls
def test_diffusion_per_step_skipped_without_num_inference_steps(self):
stub = _StubModMetrics()
stage_metrics = _Bag(
stage_gen_time_ms=1000.0,
diffusion_metrics={
"diffusion_engine_exec_time_s": 1.2,
"preprocess_time_s": 0.05,
"postprocess_time_s": 0.3,
},
)
observe_modality_at_finalize(
stub,
output_type="image",
stage_id=2,
replica_id=0,
stage_metrics=stage_metrics,
engine_outputs=_Bag(),
)
assert ("observe_diffusion_exec", "2", "0", 1.2) in stub.calls
assert not any(c[0] == "observe_diffusion_exec_per_step" for c in stub.calls)
def test_diffusion_metrics_none_skipped(self):
stub = _StubModMetrics()
observe_modality_at_finalize(
stub,
output_type="image",
stage_id=2,
replica_id=0,
stage_metrics=_Bag(stage_gen_time_ms=500.0, diffusion_metrics=None),
engine_outputs=_Bag(),
)
assert not any(c[0].startswith("observe_diffusion") for c in stub.calls)
def test_diffusion_zero_values_observed(self):
stub = _StubModMetrics()
stage_metrics = _Bag(
stage_gen_time_ms=500.0,
diffusion_metrics={
"preprocess_time_s": 0.0,
"diffusion_engine_exec_time_s": 0.0,
"postprocess_time_s": 0.0,
},
)
observe_modality_at_finalize(
stub,
output_type="image",
stage_id=2,
replica_id=0,
stage_metrics=stage_metrics,
engine_outputs=_Bag(),
)
assert ("observe_diffusion_preprocess", "2", "0", 0.0) in stub.calls
assert ("observe_diffusion_exec", "2", "0", 0.0) in stub.calls
assert ("observe_diffusion_postprocess", "2", "0", 0.0) in stub.calls
def test_non_audio_output_type_skips_audio_but_still_checks_diffusion(self):
stub = _StubModMetrics()
for output_type in ("text", "image", "video"):
observe_modality_at_finalize(
@@ -251,7 +395,7 @@ class TestObserveModalityAtFinalize:
stage_metrics=_Bag(stage_gen_time_ms=100.0),
engine_outputs=_Bag(),
)
assert stub.calls == []
assert not any(c[0].startswith("observe_audio") or c[0].startswith("inc_audio") for c in stub.calls)
def test_replica_id_none_skipped(self):
stub = _StubModMetrics()
@@ -1,21 +1,24 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from functools import lru_cache
from types import SimpleNamespace
from unittest.mock import Mock
import pytest
import torch
import torch.nn as nn
from vllm.platforms import current_platform
from vllm_omni.model_executor.models.cosyvoice3.code2wav_core.hifigan import (
HiFTGenerator,
)
from vllm_omni.model_executor.models.minicpmo_4_5.cuda_graph_wrapper import (
CFMGraphWrapper,
HiFTGraphWrapper,
)
pytestmark = [pytest.mark.core_model]
pytestmark = [pytest.mark.core_model, pytest.mark.cuda]
class _F0Predictor(nn.Module):
@@ -142,3 +145,248 @@ def test_lazy_capture_limit_falls_back_to_eager(monkeypatch: pytest.MonkeyPatch)
wrapper._capture.assert_not_called()
wrapper.decode_fn.assert_called_once_with(speech_feat, cache_source)
assert result is wrapper.decode_fn.return_value
# ---------------------------------------------------------------------------
# CFMGraphWrapper tests
# ---------------------------------------------------------------------------
class _MiniDiT(nn.Module):
"""Minimal DiT-like module with blocks_forward_chunk for CFM graph testing.
Mimics the upstream cosyvoice2 DiT's cache semantics:
- CausalConv1d.forward_chunk: cat([cnn_cache, x], dim=time) when cache is not None
- Attention.forward_chunk: cat([k, k_cache], dim=seq) when att_cache is not None
"""
def __init__(self, in_dim: int = 16, hidden: int = 8, depth: int = 2) -> None:
super().__init__()
self.in_proj = nn.Linear(in_dim, hidden)
self.blocks = nn.ModuleList([nn.LayerNorm(hidden) for _ in range(depth)])
self.final_layer = nn.Linear(hidden, in_dim)
def blocks_forward_chunk(
self,
x: torch.Tensor,
t: torch.Tensor,
mask: torch.Tensor | None,
cnn_cache: torch.Tensor | None = None,
att_cache: torch.Tensor | None = None,
cnn_cache_buffer: torch.Tensor | None = None,
att_cache_buffer: torch.Tensor | None = None,
) -> torch.Tensor:
x = x.transpose(1, 2)
x = self.in_proj(x)
for b_idx in range(len(self.blocks)):
# Simulate CausalConv1d: cnn_cache contributes to the first frames.
# Upstream: if cnn_cache[b_idx] is None, creates zeros internally (same as zeros).
cnn_b = cnn_cache[b_idx] if cnn_cache is not None else None
if cnn_b is not None:
x[:, : cnn_b.shape[2], :] += cnn_b.transpose(1, 2)
# Simulate Attention: att_cache contributes a bias when non-empty.
# Upstream: if att_cache[b_idx] is None, skips cat entirely (different path).
att_b = att_cache[b_idx] if att_cache is not None else None
if att_b is not None and att_b.shape[3] > 0:
x += att_b.sum(dim=(1, 2), keepdim=False).unsqueeze(1)
x = self.blocks[b_idx](x)
x = x + t
cnn_cache_buffer[b_idx] = x[:, -2:, :].transpose(1, 2).contiguous()
dt = x.shape[1]
att_cache_buffer[b_idx][:, :, :dt, :] = x.unsqueeze(1)
x = self.final_layer(x)
x = x.transpose(1, 2)
return x
def _cfm_inputs(
batch_size: int, chunk_size: int, old_att_len: int, *, device: str = "cuda"
) -> tuple[torch.Tensor, ...]:
depth = 2
hidden = 8
estimator_input = torch.randn(batch_size, 16, chunk_size, device=device)
time_emb = torch.randn(batch_size, 1, hidden, device=device)
cnn_cache = torch.randn(depth, batch_size, hidden, 2, device=device)
att_cache = torch.randn(depth, batch_size, 1, old_att_len, hidden, device=device)
cnn_out = torch.empty(depth, batch_size, hidden, 2, device=device)
att_out = torch.empty(depth, batch_size, 1, old_att_len + chunk_size, hidden, device=device)
return estimator_input, time_emb, cnn_cache, att_cache, cnn_out, att_out
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA is required")
def test_cfm_graph_replay_matches_eager_for_uncached_and_cached_shapes(
monkeypatch: pytest.MonkeyPatch,
) -> None:
pool = torch.cuda.graph_pool_handle()
monkeypatch.setattr(current_platform, "get_global_graph_pool", lambda: pool)
torch.manual_seed(0)
estimator = _MiniDiT().eval().cuda()
wrapper = CFMGraphWrapper(graph_fn=estimator.blocks_forward_chunk, max_graphs=32)
with torch.inference_mode():
for _, chunk_size, old_att_len in ((2, 10, 0), (2, 10, 5)):
inputs = _cfm_inputs(2, chunk_size, old_att_len)
eager_inputs = tuple(v.clone() for v in inputs)
with torch.no_grad():
eager_result = estimator.blocks_forward_chunk(
eager_inputs[0],
eager_inputs[1],
None,
eager_inputs[2],
eager_inputs[3],
eager_inputs[4],
eager_inputs[5],
)
wrapper.replay(*inputs)
replay_inputs = tuple(v.clone() for v in inputs)
graph_result, graph_cnn, graph_att = wrapper.replay(*replay_inputs)
torch.testing.assert_close(graph_result, eager_result, rtol=1e-4, atol=1e-5)
torch.testing.assert_close(graph_cnn, eager_inputs[4], rtol=1e-4, atol=1e-5)
torch.testing.assert_close(graph_att, eager_inputs[5], rtol=1e-4, atol=1e-5)
wrapper._capture_graph.cache_clear()
def _cfm_mock_wrapper(monkeypatch: pytest.MonkeyPatch, *, max_graphs: int = 1) -> CFMGraphWrapper:
monkeypatch.setattr(torch.cuda, "is_current_stream_capturing", lambda: False)
wrapper = object.__new__(CFMGraphWrapper)
wrapper.max_graphs = max_graphs
wrapper.graph_fn = Mock(return_value=torch.tensor([42.0]))
wrapper.device = torch.device("cuda")
@lru_cache(maxsize=max_graphs)
def _capture_graph(key: tuple):
return wrapper._do_capture(key)
wrapper._capture_graph = _capture_graph
wrapper._do_capture = Mock(return_value=None)
return wrapper
def test_cfm_unseen_shape_is_lazily_captured(monkeypatch: pytest.MonkeyPatch) -> None:
wrapper = _cfm_mock_wrapper(monkeypatch)
wrapper._capture_graph = Mock(return_value=None)
inputs = _cfm_inputs(2, 10, 0)
wrapper.replay(*inputs)
wrapper._capture_graph.assert_called_once()
wrapper.graph_fn.assert_called_once()
def test_cfm_capture_failure_falls_back_to_eager(monkeypatch: pytest.MonkeyPatch) -> None:
wrapper = _cfm_mock_wrapper(monkeypatch)
wrapper._capture_graph = lru_cache(maxsize=1)(lambda key: None)
inputs = _cfm_inputs(2, 10, 0)
result = wrapper.replay(*inputs)
wrapper.graph_fn.assert_called_once()
assert result[0] is wrapper.graph_fn.return_value
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA is required")
def test_cfm_lru_eviction(monkeypatch: pytest.MonkeyPatch) -> None:
"""Verify that LRU cache evicts oldest entries when full."""
pool = torch.cuda.graph_pool_handle()
monkeypatch.setattr(current_platform, "get_global_graph_pool", lambda: pool)
torch.manual_seed(0)
estimator = _MiniDiT().eval().cuda()
wrapper = CFMGraphWrapper(graph_fn=estimator.blocks_forward_chunk, max_graphs=2)
with torch.inference_mode():
inputs_a = _cfm_inputs(2, 10, 0)
wrapper.replay(*inputs_a)
assert wrapper._capture_graph.cache_info().currsize == 1
inputs_b = _cfm_inputs(2, 12, 0)
wrapper.replay(*inputs_b)
assert wrapper._capture_graph.cache_info().currsize == 2
wrapper.replay(*inputs_a)
assert wrapper._capture_graph.cache_info().currsize == 2
inputs_c = _cfm_inputs(2, 14, 0)
wrapper.replay(*inputs_c)
assert wrapper._capture_graph.cache_info().currsize == 2
wrapper.replay(*inputs_b)
hits_before = wrapper._capture_graph.cache_info().hits
wrapper.replay(*inputs_b)
hits_after = wrapper._capture_graph.cache_info().hits
assert hits_after == hits_before + 1
wrapper._capture_graph.cache_clear()
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA is required")
def test_cfm_none_cache_parity_between_graph_and_eager(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Verify that None→zeros (graph path) matches [None]*depth (eager path).
setup_batch calls _decode_cfm with cnn_cache=None on every request's
prompt pass. The graph path replaces None with zeros; the eager path
passes [None]*depth. Both must produce identical outputs.
"""
torch.accelerator.synchronize()
pool = torch.cuda.graph_pool_handle()
monkeypatch.setattr(current_platform, "get_global_graph_pool", lambda: pool)
torch.manual_seed(0)
estimator = _MiniDiT().eval().cuda()
wrapper = CFMGraphWrapper(graph_fn=estimator.blocks_forward_chunk, max_graphs=32)
depth = len(estimator.blocks)
hidden = 8
batch_size = 2
chunk_size = 20
estimator_input = torch.randn(batch_size, 16, chunk_size, device="cuda")
time_emb = torch.randn(batch_size, 1, hidden, device="cuda")
cnn_out = torch.empty(depth, batch_size, hidden, 2, device="cuda")
att_out = torch.empty(depth, batch_size, 1, chunk_size, hidden, device="cuda")
# Eager path: cnn_cache=[None]*depth, att_cache=[None]*depth
eager_input = estimator_input.clone()
eager_time = time_emb.clone()
eager_cnn_out = torch.empty_like(cnn_out)
eager_att_out = torch.empty_like(att_out)
with torch.no_grad():
eager_result = estimator.blocks_forward_chunk(
eager_input,
eager_time,
None,
[None] * depth,
[None] * depth,
eager_cnn_out,
eager_att_out,
)
# Graph path: cnn_cache=zeros, att_cache=zero-length (simulating _estimator_step's None→zeros)
zero_cnn = torch.zeros_like(cnn_out)
zero_att = estimator_input.new_zeros(att_out.shape[:3] + (0,) + att_out.shape[4:])
wrapper.replay(estimator_input, time_emb, zero_cnn, zero_att, cnn_out, att_out)
graph_input = estimator_input.clone()
graph_time = time_emb.clone()
graph_cnn_out = torch.empty_like(cnn_out)
graph_att_out = torch.empty_like(att_out)
graph_zero_cnn = torch.zeros_like(cnn_out)
graph_zero_att = estimator_input.new_zeros(att_out.shape[:3] + (0,) + att_out.shape[4:])
graph_result, graph_cnn, graph_att = wrapper.replay(
graph_input,
graph_time,
graph_zero_cnn,
graph_zero_att,
graph_cnn_out,
graph_att_out,
)
torch.testing.assert_close(graph_result, eager_result, rtol=1e-4, atol=1e-5)
torch.testing.assert_close(graph_cnn, eager_cnn_out, rtol=1e-4, atol=1e-5)
torch.testing.assert_close(graph_att, eager_att_out, rtol=1e-4, atol=1e-5)
@@ -0,0 +1,129 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""L1 registration + config-shim tests for NemotronVoiceChat (CPU, no weights)."""
import subprocess
from pathlib import Path
import pytest
from vllm_omni.config.pipeline_registry import OMNI_PIPELINES
from vllm_omni.config.stage_config import StageExecutionType
from vllm_omni.model_executor.models.nemotron_voicechat.configuration_nemotron_voicechat import (
NemotronVoiceChatConfig,
)
from vllm_omni.model_executor.models.registry import _OMNI_MODELS
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
_ARCHS = (
"NemotronVoiceChatThinkerForConditionalGeneration",
"NemotronVoiceChatTalkerForConditionalGeneration",
"NemotronVoiceChatCode2Wav",
)
def _minimal_nemo_dict() -> dict:
return {
"data": {"frame_length": 0.08, "source_sample_rate": 16000, "target_sample_rate": 22050},
"model": {
"inference_speaker_name": "Aria",
"stt": {
"model": {
"perception": {"encoder": {}, "preprocessor": {}, "modality_adapter": {}},
"pretrained_llm": "nvidia/NVIDIA-Nemotron-Nano-9B-v2",
"use_function_head": True,
}
},
"speech_generation": {
"model": {
"tts_config": {"backbone_config": {"hidden_size": 1152, "sliding_window": 7500}},
"codec_config": {"num_quantizers": 31, "codebook_size": 1024},
}
},
},
}
def test_pipeline_registered_with_three_stages() -> None:
pipeline = OMNI_PIPELINES["nemotron_voicechat"]
assert OMNI_PIPELINES["nemotron_labs_voicechat"] is pipeline
assert len(pipeline.stages) == 3
thinker, talker, code2wav = pipeline.stages
assert thinker.execution_type == StageExecutionType.LLM_AR
assert thinker.final_output and thinker.final_output_type == "text"
assert thinker.owns_tokenizer
assert talker.execution_type == StageExecutionType.LLM_AR
assert talker.model_arch == "NemotronVoiceChatTalkerForConditionalGeneration"
assert talker.input_sources == (0,)
assert code2wav.execution_type == StageExecutionType.LLM_GENERATION
assert code2wav.final_output and code2wav.final_output_type == "audio"
assert code2wav.input_sources == (1,)
assert pipeline.validate() == []
def test_architectures_registered() -> None:
for arch in _ARCHS:
assert arch in _OMNI_MODELS, f"{arch} missing from _OMNI_MODELS"
def test_full_payload_whitelists_cover_code2wav_only() -> None:
from vllm_omni.core.sched.omni_scheduling_coordinator import _FULL_PAYLOAD_INPUT_STAGES
assert ("NemotronVoiceChatCode2Wav", "code2wav") in _FULL_PAYLOAD_INPUT_STAGES
# The thinker->talker hop is token-path only: the talker must NOT wait on a
# connector payload or stage 1 hangs.
assert ("NemotronVoiceChatTalkerForConditionalGeneration", "talker") not in _FULL_PAYLOAD_INPUT_STAGES
def test_config_parses_nemo_layout_without_hub_access(monkeypatch) -> None:
# Provide the thinker text config explicitly so the test never touches HF.
cfg = NemotronVoiceChatConfig(
thinker_text_config={"model_type": "llama", "hidden_size": 4480, "num_hidden_layers": 56},
**_minimal_nemo_dict(),
)
assert cfg.get_text_config().hidden_size == 4480
assert cfg.talker_config.hidden_size == 1152
assert cfg.talker_config.sliding_window == 7500
assert cfg.code2wav_config.num_quantizers == 31
assert cfg.inference_speaker_name == "Aria"
@pytest.mark.parametrize(
"mutation",
["drop_stt", "drop_speech_generation", "drop_perception", "drop_codec"],
)
def test_config_rejects_non_voicechat_checkpoints(mutation: str) -> None:
raw = _minimal_nemo_dict()
if mutation == "drop_stt":
del raw["model"]["stt"]
elif mutation == "drop_speech_generation":
del raw["model"]["speech_generation"]
elif mutation == "drop_perception":
del raw["model"]["stt"]["model"]["perception"]
else:
del raw["model"]["speech_generation"]["model"]["codec_config"]
with pytest.raises(ValueError, match="NemotronVoiceChat|missing"):
NemotronVoiceChatConfig(
thinker_text_config={"model_type": "llama", "hidden_size": 4480},
**raw,
)
def test_no_nemo_imports_in_nemotron_voicechat_tree() -> None:
"""Dependency guard: the vendored tree must not import the nemo package.
Scoped to the nemotron_voicechat model tree (other models may have their
own optional nemo integrations).
"""
repo_root = Path(__file__).resolve().parents[3]
targets = [
str(repo_root / "vllm_omni/model_executor/models/nemotron_voicechat"),
str(repo_root / "vllm_omni/model_executor/stage_input_processors/nemotron_voicechat.py"),
]
result = subprocess.run(
["grep", "-rnE", r"^\s*(import nemo\b|from nemo(\.|\s))", *targets, "--include=*.py"],
capture_output=True,
text=True,
)
assert result.returncode != 0, f"Found nemo imports in the nemotron_voicechat tree:\n{result.stdout}"
@@ -0,0 +1,227 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Golden shape test for the NemotronVoiceChat frame-locked timeline contract.
Pins the exact prefill/off-by-one arithmetic against values verified with the
NeMo reference run on sample_general.wav (fp32, greedy): perception produced
196 acoustic frames for the 249,734-sample 16 kHz fixture (the NeMo dump's
250,760 was the loader's padded batch width; perception consumed the true
length); the system prompt tokenized to 56 ids ([bos] + 54 + [eos]); NeMo's
timeline T = 252 = 56 + 196; and our fp32 pipeline matched the reference text
channel 196/196 tokens.
"""
import pytest
from vllm_omni.model_executor.models.nemotron_voicechat.nemotron_voicechat_thinker import (
compute_acoustic_frame_count,
)
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
# Perception config subset matching the checkpoint (mel 10 ms hop, n_fft 512,
# dw-striding 8x CAUSAL subsampling, conv kernel 3). causal_downsampling is
# what the real checkpoint sets; omitting it here is exactly what let the
# non-causal padding formula pass review round 0 (helper vs itself).
_STT_CFG = {
"perception": {
"preprocessor": {"sample_rate": 16000, "window_stride": 0.01, "window_size": 0.025, "n_fft": 512},
"encoder": {
"subsampling": "dw_striding",
"subsampling_factor": 8,
"subsampling_conv_kernel_size": 3,
"causal_downsampling": True,
},
}
}
# (num_16k_samples, expected 12.5 Hz frames), all verified against the REAL
# vendored AudioPerceptionModule built from the checkpoint config. The first
# row is the sample_general.wav acceptance fixture (196 frames -> the NeMo
# T=252 timeline). 71271 is the reviewer's 4.45 s repro that the non-causal
# formula undersized by one; 250760 is the NeMo loader's padded width, which
# genuinely yields 197 (not the fixture's 196).
_GOLDEN = [
(249734, 196),
(250760, 197),
(71271, 57),
(16000, 14),
(16000 * 2, 26),
(16000 * 4, 51),
(16000 * 8, 101),
]
@pytest.mark.parametrize(("num_samples", "expected_frames"), _GOLDEN)
def test_acoustic_frame_count_golden(num_samples: int, expected_frames: int) -> None:
assert compute_acoustic_frame_count(_STT_CFG, num_samples) == expected_frames
def test_frame_count_matches_vendored_subsampling_geometry() -> None:
"""Pin the helper against the real ConvSubsampling, not against itself.
Builds the vendored subsampling module with the checkpoint geometry (both
causal and non-causal) and checks the helper's padding arithmetic against
the module's actual ``_left_padding + _right_padding`` and its
``calc_length`` output over a spread of mel lengths.
"""
import torch
from vllm_omni.model_executor.models.nemotron_voicechat.nemo_vendored.asr.subsampling import (
ConvSubsampling,
calc_length,
)
for causal in (True, False):
sub = ConvSubsampling(
subsampling="dw_striding",
subsampling_factor=8,
feat_in=128,
feat_out=8,
conv_channels=8,
is_causal=causal,
)
expected_paddings = sub._left_padding + sub._right_padding
cfg = {
"perception": {
"preprocessor": _STT_CFG["perception"]["preprocessor"],
"encoder": {
"subsampling": "dw_striding",
"subsampling_factor": 8,
"subsampling_conv_kernel_size": 3,
"causal_downsampling": causal,
},
}
}
for num_samples in (16000, 71271, 249734, 250760):
# Recompute the helper's mel length, then ask the module's own
# calc_length what the subsampled length should be.
mel_len = (num_samples + 512 - 512) // 160 + 1
module_frames = int(
calc_length(
torch.tensor([mel_len]),
all_paddings=expected_paddings,
kernel_size=3,
stride=2,
ceil_mode=False,
repeat_num=3,
)[0]
)
assert compute_acoustic_frame_count(cfg, num_samples) == module_frames, (
f"helper diverged from vendored geometry (causal={causal}, samples={num_samples})"
)
def test_timeline_max_model_len_validation() -> None:
from vllm_omni.model_executor.models.nemotron_voicechat.nemotron_voicechat_thinker import (
validate_timeline_fits_max_model_len,
)
# The acceptance fixture (56 + 1 + 196 = 253) fits the shipped 8192 limit.
validate_timeline_fits_max_model_len(56, 196, 8192)
# Exactly at the limit: the vLLM request occupies prompt + 1 (frame-0
# placeholder) + frames tokens, so 57 + 8135 == 8192 is allowed...
validate_timeline_fits_max_model_len(56, 8135, 8192)
# ...and one more frame must be rejected, naming every offending length.
with pytest.raises(ValueError) as excinfo:
validate_timeline_fits_max_model_len(56, 8136, 8192)
message = str(excinfo.value)
for fragment in (
"vllm_prefill_len=57",
"acoustic_frame_count=8136",
"vllm_total_len=8193",
"max_model_len=8192",
"logical_prompt_token_len=56",
"logical_total_len=8192",
):
assert fragment in message
def _bare_thinker():
import torch
from torch import nn
from vllm_omni.model_executor.models.nemotron_voicechat.nemotron_voicechat_thinker import (
NemotronVoiceChatThinkerForConditionalGeneration,
)
thinker = NemotronVoiceChatThinkerForConditionalGeneration.__new__(NemotronVoiceChatThinkerForConditionalGeneration)
nn.Module.__init__(thinker)
thinker._use_function_head = True
thinker._dtype = torch.float32
thinker.function_head = nn.Linear(8, 16, bias=False)
return thinker
def test_postprocess_appends_function_token_to_timeline(monkeypatch: pytest.MonkeyPatch) -> None:
import torch
thinker = _bare_thinker()
hidden = torch.randn(3, 8)
expected = int(thinker.function_head(hidden[-1:]).argmax(dim=-1))
# Default: only the load-bearing prev-token; the cumulative debug timeline
# (a per-step host sync + growing concat) stays off.
update = thinker.postprocess(hidden)
assert int(update["nvc_prev_function_token"]) == expected
assert "nvc_function_tokens" not in update
monkeypatch.setenv("NEMOTRON_VOICECHAT_DEBUG_FUNCTION_TIMELINE", "1")
# No existing timeline: starts one.
update = thinker.postprocess(hidden)
assert update["nvc_function_tokens"].tolist() == [expected]
# Existing timeline: appended, not replaced.
existing = torch.tensor([7, 8, 9], dtype=torch.long)
update = thinker.postprocess(hidden, nvc_function_tokens=existing)
assert update["nvc_function_tokens"].tolist() == [7, 8, 9, expected]
def test_postprocess_skips_intermediate_prefill_chunks(monkeypatch: pytest.MonkeyPatch) -> None:
import torch
monkeypatch.setenv("NEMOTRON_VOICECHAT_DEBUG_FUNCTION_TIMELINE", "1")
thinker = _bare_thinker()
hidden = torch.randn(4, 8)
# Intermediate chunk: 0 computed + 4 rows < prompt_len 10 -> no token.
assert thinker.postprocess(hidden, _omni_is_prefill=True, _omni_num_computed_tokens=0, _omni_prompt_len=10) == {}
# Final chunk reaches the last prefill position (acoustic frame 0).
update = thinker.postprocess(hidden, _omni_is_prefill=True, _omni_num_computed_tokens=6, _omni_prompt_len=10)
assert "nvc_prev_function_token" in update
assert update["nvc_function_tokens"].numel() == 1
def test_prefill_contract_arithmetic() -> None:
# vllm_prefill_len = logical_prompt_token_len + 1 (the +1 is acoustic
# frame 0); decode steps == acoustic_frame_count; NeMo timeline
# T == prompt + frames. Values from the verified sample_general.wav run.
logical_prompt_len = 56
frames = compute_acoustic_frame_count(_STT_CFG, 249734)
vllm_prefill_len = logical_prompt_len + 1
assert vllm_prefill_len == 57
assert logical_prompt_len + frames == 252 # NeMo reference T
# The talker consumes the full timeline from t=1 and the producer trims
# the prompt region: rows P-1 onward of the (T-1)-row code stack.
talker_rows = (logical_prompt_len + frames) - 1
trimmed = talker_rows - (logical_prompt_len - 1)
assert trimmed == frames
def test_torchaudio_mel_filterbank_matches_librosa() -> None:
"""The perception frontend builds its mel filterbank with torchaudio.
torchaudio's melscale_fbanks(norm="slaney", mel_scale="slaney") implements
the same slaney-convention math as librosa.filters.mel (the NeMo reference
dependency) up to float32 rounding. The 1e-6 tolerance is ~4x the observed
2.6e-7 max diff; e2e this stays token- and WAV-identical to the reference
on the parity fixture (per-feature normalization absorbs it).
"""
librosa = pytest.importorskip("librosa")
torchaudio = pytest.importorskip("torchaudio")
# The checkpoint's perception preprocessor config (16 kHz, n_fft=512, 128 mels).
ta = torchaudio.functional.melscale_fbanks(
n_freqs=257, f_min=0.0, f_max=8000.0, n_mels=128, sample_rate=16000, norm="slaney", mel_scale="slaney"
).T.numpy()
reference = librosa.filters.mel(sr=16000, n_fft=512, n_mels=128, fmin=0.0, fmax=8000.0, norm="slaney")
assert ta.shape == reference.shape
assert abs(ta - reference).max() < 1e-6
@@ -0,0 +1,117 @@
from types import SimpleNamespace
import numpy as np
import pytest
import torch
from vllm_omni.model_executor.stage_input_processors.forced_aligner import (
ALIGNER_WORDS_KEY,
_extract_text,
_extract_waveform,
code2wav2aligner,
decode_pooling_output,
)
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
class _FakeCompletion:
def __init__(self, multimodal_output):
self.multimodal_output = multimodal_output
class _FakeOutput:
def __init__(self, multimodal_output, finished=True):
self.finished = finished
self.outputs = [_FakeCompletion(multimodal_output)]
def _audio_mm(n=2400, sr=24000):
return {"audio": torch.zeros(n, dtype=torch.float32), "sr": torch.tensor(sr, dtype=torch.int32)}
def test_extract_waveform_from_audio_key():
wav, sr = _extract_waveform(_audio_mm(n=100, sr=16000))
assert isinstance(wav, np.ndarray) and wav.dtype == np.float32
assert wav.shape == (100,)
assert sr == 16000
def test_extract_waveform_falls_back_to_model_outputs_and_default_sr():
wav, sr = _extract_waveform({"model_outputs": [torch.ones(50)]})
assert wav.shape == (50,)
assert sr == 24000 # default when sr missing
def test_extract_text_unwraps_additional_information_list():
prompt = {"additional_information": {"text": ["Hello world."]}}
assert _extract_text(prompt) == "Hello world."
def test_code2wav2aligner_builds_text_prompt_and_audio():
prompt = {"additional_information": {"text": ["U.S.A test"], "language": ["English"]}}
out = code2wav2aligner([_FakeOutput(_audio_mm())], prompt)
assert len(out) == 1
item = out[0]
# text prompt: tokenization + audio features deferred to the stage preprocessor
assert "prompt_token_ids" not in item
# prompt built from official segmentation: "U.S.A" -> "USA"
assert "USA<timestamp><timestamp>test" in item["prompt"]
# audio carried as (np.float32, sr) tuple
audio, sr = item["multi_modal_data"]["audio"]
assert isinstance(audio, np.ndarray) and sr == 24000
assert item["additional_information"]["aligner_words"] == [["USA", "test"]]
assert item["additional_information"]["language"] == ["English"]
def test_code2wav2aligner_skips_unfinished_and_empty():
# unfinished -> skipped
assert code2wav2aligner([_FakeOutput(_audio_mm(), finished=False)], {}) == []
# finished but empty waveform -> skipped
empty = _FakeOutput({"audio": torch.zeros(0), "sr": torch.tensor(24000)})
assert code2wav2aligner([empty], {"additional_information": {"text": ["hi"]}}) == []
def test_decode_pooling_output_produces_word_timestamps_ms():
# 2 words -> 4 <timestamp> markers (id=99). classify_num=5, seg=200ms.
hf_config = SimpleNamespace(
timestamp_token_id=99,
timestamp_segment_time=200.0,
thinker_config=SimpleNamespace(classify_num=5),
)
# prompt: marker positions at indices 2,3,5,6
prompt_token_ids = [1, 1, 99, 99, 1, 99, 99]
request = SimpleNamespace(
prompt_token_ids=prompt_token_ids,
additional_information={ALIGNER_WORDS_KEY: [["hello", "world"]]},
)
logits = torch.zeros((7, 5), dtype=torch.float32)
logits[2, 0] = 1.0 # word0 start -> bin 0
logits[3, 2] = 1.0 # word0 end -> bin 2
logits[5, 2] = 1.0 # word1 start -> bin 2
logits[6, 4] = 1.0 # word1 end -> bin 4
ms = decode_pooling_output(logits, request, hf_config)
# decoder returns a bare [n_words, 2] int32 tensor (not a dict)
assert ms.tolist() == [[0, 400], [400, 800]] # bins x 200ms
def test_decode_pooling_output_handles_hf_config_without_thinker():
# hf_config without thinker_config falls back to itself for classify_num.
hf_config = SimpleNamespace(
timestamp_token_id=99,
timestamp_segment_time=100.0,
classify_num=4,
)
request = SimpleNamespace(
prompt_token_ids=[99, 99],
additional_information={ALIGNER_WORDS_KEY: [["hi"]]},
)
logits = torch.zeros((2, 4), dtype=torch.float32)
logits[0, 1] = 1.0
logits[1, 3] = 1.0
ms = decode_pooling_output(logits, request, hf_config)
assert ms.tolist() == [[100, 300]]
@@ -0,0 +1,422 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from types import SimpleNamespace
import pytest
import torch
from vllm_omni.model_executor.stage_input_processors.nemotron_voicechat import (
_FULL_PAYLOAD_REPLACE_KEYS,
talker2code2wav_full_payload,
talker2code2wav_token_only,
thinker2talker_token_only,
)
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
_PAD = 12
def _thinker_output(prompt_len: int, generated: list[int]):
return SimpleNamespace(
finished=True,
prompt_token_ids=list(range(100, 100 + prompt_len)) + [_PAD],
additional_information=None,
outputs=[SimpleNamespace(token_ids=generated, cumulative_token_ids=None)],
)
def test_thinker2talker_builds_pad_prompt_timeline() -> None:
generated = [7, 8, 9, 10]
inputs = thinker2talker_token_only([_thinker_output(prompt_len=5, generated=generated)])
assert len(inputs) == 1
prompt = inputs[0]
# 1-token placeholder prompt; the timeline rides additional_information.
assert prompt["prompt_token_ids"] == [0]
info = prompt["additional_information"]
assert info["nvc_logical_prompt_len"] == 5
assert info["nvc_frame_count"] == 4
assert info["nvc_text_timeline"] == [_PAD] * 5 + generated
def test_thinker2talker_skips_unfinished() -> None:
out = _thinker_output(3, [1])
out.finished = False
assert thinker2talker_token_only([out]) == []
def test_full_payload_trims_prompt_region_rows() -> None:
# Rows correspond to timeline steps t=1..T-1; with prompt_len P the NeMo
# trim keeps rows for t >= P, i.e. row index P-1 onward.
prompt_len = 4
frames, q = 10, 31
codes = torch.arange(frames * q, dtype=torch.long).reshape(frames, q) % 1024
request = SimpleNamespace(
additional_information={
"codes": {"audio": codes},
"nvc_logical_prompt_len": prompt_len,
},
additional_information_cpu=None,
)
payload = talker2code2wav_full_payload(request=request, is_finished=True)
assert payload.codes.audio.shape == (frames - (prompt_len - 1), q)
assert torch.equal(payload.codes.audio, codes[prompt_len - 1 :])
assert bool(payload.meta.finished)
def test_full_payload_without_codes_is_empty_finished() -> None:
# The sync producer must never emit a meta-only "pending" struct (it would
# be shipped as the real payload); with no codes it ships an empty finished
# payload regardless of the request's is_finished flag.
payload = talker2code2wav_full_payload(request=SimpleNamespace(), is_finished=False)
assert payload is not None
assert bool(payload.meta.finished)
assert payload.codes.audio.numel() == 0
def test_full_payload_replace_semantics_declared() -> None:
# Full-sequence tensors must REPLACE in the accumulator, not concatenate.
# The AR runner flattens nested payloads before accumulation, so the
# flattened "codes.audio" key is the one that matters.
assert "codes.audio" in _FULL_PAYLOAD_REPLACE_KEYS
assert "codes" in _FULL_PAYLOAD_REPLACE_KEYS
def test_full_payload_missing_prompt_len_fails_explicitly() -> None:
codes = torch.zeros((5, 31), dtype=torch.long)
request = SimpleNamespace(
additional_information={"codes": {"audio": codes}},
additional_information_cpu=None,
)
with pytest.raises(ValueError, match="nvc_logical_prompt_len"):
talker2code2wav_full_payload(request=request, is_finished=True)
def test_code2wav_distinguishes_empty_payload_from_missing_info() -> None:
from vllm_omni.model_executor.models.nemotron_voicechat.nemotron_voicechat_code2wav import (
NemotronVoiceChatCode2Wav,
)
extract = NemotronVoiceChatCode2Wav._codes_from_runtime_info
# Explicit empty payload (e.g. zero frames after the prompt trim): the
# empty tensor comes back as-is -> empty audio, never a placeholder-id
# decode.
empty = extract(None, {"codes": {"audio": torch.empty(0, dtype=torch.long)}})
assert isinstance(empty, torch.Tensor) and empty.numel() == 0
# Missing codes info entirely -> None (forward raises: placeholder
# input_ids are never decoded).
assert extract(None, {"meta": {}}) is None
assert extract(None, None) is None
# Normal payload passes through (nested and flattened key forms).
codes = torch.zeros((3, 31), dtype=torch.long)
assert extract(None, {"codes": {"audio": codes}}) is codes
assert extract(None, {"codes.audio": codes}) is codes
def test_validate_code_stack_negatives() -> None:
from vllm_omni.model_executor.models.nemotron_voicechat.nemotron_voicechat_code2wav import (
validate_code_stack,
)
good = torch.zeros((4, 31), dtype=torch.long)
assert validate_code_stack(good, 31, 1024).shape == (4, 31)
with pytest.raises(ValueError, match="not divisible"):
validate_code_stack(torch.zeros(100, dtype=torch.long), 31, 1024)
with pytest.raises(ValueError, match="shaped"):
validate_code_stack(torch.zeros((4, 30), dtype=torch.long), 31, 1024)
bad = good.clone()
bad[1, 5] = 1024
with pytest.raises(ValueError, match="out-of-range"):
validate_code_stack(bad, 31, 1024)
def test_tokenizer_resolution_failure_is_actionable(monkeypatch) -> None:
from transformers import AutoConfig
from vllm_omni.model_executor.models.nemotron_voicechat.configuration_nemotron_voicechat import (
NemotronVoiceChatConfig,
)
def _boom(*args, **kwargs):
raise OSError("offline")
monkeypatch.setattr(AutoConfig, "from_pretrained", _boom)
with pytest.raises(RuntimeError, match="NEMOTRON_VOICECHAT_LLM_PATH"):
NemotronVoiceChatConfig(
data={"frame_length": 0.08, "source_sample_rate": 16000, "target_sample_rate": 22050},
model={
"inference_speaker_name": "Aria",
"stt": {"model": {"perception": {"encoder": {}}, "pretrained_llm": "nvidia/nope"}},
"speech_generation": {"model": {"tts_config": {}, "codec_config": {}}},
},
)
def test_sanitize_tts_model_cfg_disables_pretrained_loads(monkeypatch) -> None:
from vllm_omni.model_executor.models.nemotron_voicechat.nemotron_voicechat_talker import (
sanitize_tts_model_cfg,
)
original = {
"pretrained_lm_name": "nvidia/NVIDIA-Nemotron-Nano-9B-v2",
"pretrained_codec_model": "/some/external/codec.ckpt",
"tts_config": {
"pretrained_text_name": "some/hub-llm",
"backbone_type": "gemma3_text",
"cas_config": {"pretrained_tokenizer_name": "some/hub-tokenizer", "keep": 1},
},
}
monkeypatch.delenv("NEMOTRON_VOICECHAT_LLM_PATH", raising=False)
cfg = sanitize_tts_model_cfg(original)
# External weight-load triggers are gone; construction is config-only.
assert "pretrained_text_name" not in cfg["tts_config"]
assert "pretrained_codec_model" not in cfg
assert "pretrained_tokenizer_name" not in cfg["tts_config"]["cas_config"]
assert cfg["tts_config"]["cas_config"]["keep"] == 1
# Tokenizer reference survives.
assert cfg["pretrained_lm_name"] == "nvidia/NVIDIA-Nemotron-Nano-9B-v2"
# The shared stage config is never mutated (deep copy).
assert original["tts_config"]["pretrained_text_name"] == "some/hub-llm"
# Air-gapped override reroutes the tokenizer reference.
monkeypatch.setenv("NEMOTRON_VOICECHAT_LLM_PATH", "/local/nemotron")
cfg = sanitize_tts_model_cfg(original)
assert cfg["pretrained_lm_name"] == "/local/nemotron"
def test_code2wav_token_only_sizes_placeholder() -> None:
talker_output = SimpleNamespace(
finished=True,
outputs=[SimpleNamespace(token_ids=[0] * 9, cumulative_token_ids=None)],
)
inputs = talker2code2wav_token_only([talker_output])
assert len(inputs) == 1
assert len(inputs[0]["prompt_token_ids"]) == 9
# =========================
# Async-chunk (streaming) producers
# =========================
def _fake_transfer_manager(codec_chunk_frames: int | None = None):
extra = {}
if codec_chunk_frames is not None:
extra["codec_chunk_frames"] = codec_chunk_frames
return SimpleNamespace(
request_payload={},
connector=SimpleNamespace(config={"extra": extra}),
put_req_chunk={},
)
def _streaming_request(prompt_len: int, generated: list[int], info: dict | None = None):
return SimpleNamespace(
external_req_id="req-0",
prompt_token_ids=list(range(100, 100 + prompt_len)) + [_PAD],
output_token_ids=generated,
additional_information=info,
)
def test_thinker2talker_async_chunk_cumulative_timeline() -> None:
from vllm_omni.model_executor.stage_input_processors.nemotron_voicechat import (
thinker2talker_async_chunk,
)
tm = _fake_transfer_manager()
req = _streaming_request(prompt_len=3, generated=[7])
payload = thinker2talker_async_chunk(tm, {}, req, is_finished=False)
assert payload is not None
assert payload.ids.all == [_PAD] * 3 + [7]
assert payload.meta.num_processed_tokens == 3
assert not bool(payload.meta.finished)
# No new tokens since the last chunk -> skip.
assert thinker2talker_async_chunk(tm, {}, req, is_finished=False) is None
# More tokens -> longer cumulative timeline; final chunk sets finished.
req.output_token_ids = [7, 8, 9]
payload = thinker2talker_async_chunk(tm, {}, req, is_finished=True)
assert payload.ids.all == [_PAD] * 3 + [7, 8, 9]
assert bool(payload.meta.finished)
def test_talker2code2wav_async_chunk_cadence_and_left_context() -> None:
from vllm_omni.model_executor.stage_input_processors.nemotron_voicechat import (
talker2code2wav_async_chunk,
)
tm = _fake_transfer_manager(codec_chunk_frames=2)
prompt_len = 3
info = {"nvc_logical_prompt_len": prompt_len}
req = _streaming_request(prompt_len=prompt_len, generated=[], info=info)
def cumulative(rows: int) -> dict:
# Talker rows are timeline steps t=1..; prompt region occupies the
# first prompt_len-1 rows before acoustic frames start.
return {"codes": {"audio": torch.arange((prompt_len - 1 + rows) * 31).reshape(-1, 31)}}
# Only prompt-region rows so far -> nothing to ship.
assert talker2code2wav_async_chunk(tm, cumulative(0), req, is_finished=False) is None
# One new frame < chunk size 2 -> hold.
assert talker2code2wav_async_chunk(tm, cumulative(1), req, is_finished=False) is None
# Two frames -> first chunk, no left context.
payload = talker2code2wav_async_chunk(tm, cumulative(2), req, is_finished=False)
assert payload is not None
assert payload.meta.left_context_size == 0
assert payload.codes.audio.shape == (2, 31)
# Third frame + finished -> cumulative history with left context 2.
payload = talker2code2wav_async_chunk(tm, cumulative(3), req, is_finished=True)
assert payload.meta.left_context_size == 2
assert payload.codes.audio.shape == (3, 31)
assert bool(payload.meta.finished)
def test_talker2code2wav_async_chunk_requires_prompt_len() -> None:
from vllm_omni.model_executor.stage_input_processors.nemotron_voicechat import (
talker2code2wav_async_chunk,
)
tm = _fake_transfer_manager()
req = _streaming_request(prompt_len=3, generated=[], info=None)
with pytest.raises(ValueError, match="logical prompt length"):
talker2code2wav_async_chunk(tm, {"codes": {"audio": torch.zeros(5, 31, dtype=torch.long)}}, req)
# =========================
# Talker drain-per-wake (async scheduling review P1/P2)
# =========================
class _FakeTTSModelOutput:
past_key_values = None
class _FakeTTS:
"""Stub DuplexEARTTS: infer_codes_one_step returns a constant code row."""
def __init__(self, q: int = 31):
self.q = q
self.steps = 0
def set_init_inputs(self, speaker_name: str) -> None:
del speaker_name
def get_init_inputs(self, B: int) -> dict: # noqa: N803 — mirrors the vendored DuplexEARTTS signature
return {
"code": torch.zeros((B, 2, self.q), dtype=torch.long),
"subword_ids": torch.zeros((B, 3), dtype=torch.long),
}
def _get_generation_config(self, guidance_enabled: bool):
del guidance_enabled
return {}
def tts_model(self, **kwargs):
del kwargs
return _FakeTTSModelOutput()
def infer_codes_one_step(self, **kwargs):
del kwargs
self.steps += 1
return torch.full((1, 1, self.q), self.steps, dtype=torch.long), None
def _bare_talker():
from torch import nn
from vllm_omni.model_executor.models.nemotron_voicechat.nemotron_voicechat_talker import (
NemotronVoiceChatTalkerForConditionalGeneration,
)
talker = NemotronVoiceChatTalkerForConditionalGeneration.__new__(NemotronVoiceChatTalkerForConditionalGeneration)
nn.Module.__init__(talker)
talker.tts = _FakeTTS()
talker._sessions = {}
talker._hidden = 8
talker._dtype = torch.float32
talker._speaker_name = "Aria"
talker.config = SimpleNamespace(tts_cfg={"inference_guidance_enabled": False})
return talker
def _async_info(timeline: list[int], prompt_len: int, finished: bool, request_id: str = "req-0") -> dict:
return {
"request_id": request_id,
"additional_information": {
"ids": {"all": list(timeline)},
"meta": {
"num_processed_tokens": prompt_len,
"finished": torch.tensor(finished),
"request_id": request_id,
},
},
}
def test_talker_drains_all_received_positions_per_wake() -> None:
"""P2: chunk 0's PAD prompt region must not cost one upstream chunk per step,
and P1: a coalesced chunk (2+ new positions, 1 wake) must be fully drained."""
talker = _bare_talker()
pad, prompt_len = 12, 4
ids = torch.zeros(1, dtype=torch.long)
# Prefill wake: chunk 0 carries only the PAD prompt region.
info = _async_info([pad] * prompt_len, prompt_len, finished=False)
talker.preprocess(ids, None, _omni_is_prefill=True, **info)
session = talker._sessions["req-0"]
assert session["step"] == 1 and not session["sync_mode"]
# First decode wake: drains ALL prompt-region steps (t=1..P-1) at once.
_, embeds, update = talker.preprocess(ids, None, _omni_is_prefill=False, **info)
assert session["step"] == prompt_len # t advanced 1 -> P in one wake
assert update["codes"]["audio"].shape == (prompt_len - 1, 31)
assert float(embeds[0, 0]) == 0.0 # not finished
# Coalesced chunk: TWO new frame tokens arrive in ONE wake (delayed save
# thread merged two thinker steps). Both must be consumed by this wake.
info2 = _async_info([pad] * prompt_len + [7, 8], prompt_len, finished=False)
_, embeds, update = talker.preprocess(ids, None, _omni_is_prefill=False, **info2)
assert session["step"] == prompt_len + 2
assert update["codes"]["audio"].shape == (prompt_len + 1, 31)
assert float(embeds[0, 0]) == 0.0
# Zero-progress wake (no new positions, not finished): plain CONTINUE, no
# fabricated frames, no codes update.
_, embeds, update = talker.preprocess(ids, None, _omni_is_prefill=False, **info2)
assert session["step"] == prompt_len + 2
assert update == {}
assert float(embeds[0, 0]) == 0.0
# Final chunk: one more token + finished marker -> drain + stop flag.
info3 = _async_info([pad] * prompt_len + [7, 8, 9], prompt_len, finished=True)
_, embeds, update = talker.preprocess(ids, None, _omni_is_prefill=False, **info3)
assert session["step"] == prompt_len + 3
assert update["codes"]["audio"].shape == (prompt_len + 2, 31)
assert float(embeds[0, 0]) == 1.0 # stop
def test_talker_sync_mode_steps_once_per_wake() -> None:
"""The verified sync parity path keeps its one-TTS-step-per-engine-step cadence."""
talker = _bare_talker()
pad, prompt_len = 12, 3
ids = torch.zeros(1, dtype=torch.long)
info = {
"request_id": "req-1",
"additional_information": {
"nvc_text_timeline": [pad] * prompt_len + [7, 8],
"nvc_logical_prompt_len": prompt_len,
},
}
talker.preprocess(ids, None, _omni_is_prefill=True, **info)
session = talker._sessions["req-1"]
assert session["sync_mode"] and session["upstream_finished"]
for expected_step in (2, 3, 4):
_, embeds, _ = talker.preprocess(ids, None, _omni_is_prefill=False, **info)
assert session["step"] == expected_step
# Last position -> stop flag on the final step.
_, embeds, _ = talker.preprocess(ids, None, _omni_is_prefill=False, **info)
assert session["step"] == 5
assert float(embeds[0, 0]) == 1.0
+3
View File
@@ -17,6 +17,7 @@ from vllm_omni.model_extras import (
build_x_to_text_prompt,
get_extra_body_params,
get_extra_output_params,
get_output_tensor_range,
get_x_to_text_model_family,
should_init_extra_args_for_non_diffusion_stages,
)
@@ -134,6 +135,8 @@ def test_lingbot_extra_registry_declares_request_params() -> None:
}
)
assert get_extra_output_params("LingBotVideoPipeline") == frozenset()
assert get_output_tensor_range("LingBotVideoPipeline") == "zero_to_one"
assert get_output_tensor_range("WanPipeline") == "negative_one_to_one"
assert should_init_extra_args_for_non_diffusion_stages("LingBotVideoPipeline") is False
@@ -13,10 +13,13 @@ def _shrink_dit_rope_config(
target_head_dim: int = 32,
target_heads: int = 4,
default_axes_dims_rope: list[int] | None = None,
joint_attention_dim: int | None = None,
) -> dict:
config["num_layers"] = num_layers
if num_single_layers is not None:
config["num_single_layers"] = num_single_layers
if joint_attention_dim is not None:
config["joint_attention_dim"] = joint_attention_dim
axes_dims_rope = config.get("axes_dims_rope", default_axes_dims_rope)
factor = config["attention_head_dim"] / target_head_dim
config["attention_head_dim"] = target_head_dim
@@ -50,22 +53,55 @@ def _shrink_flux_t5_text_encoder(config: dict) -> dict:
return config
def tiny_qwen_image_builder() -> str:
def shrink_text_encoder(config: dict) -> dict:
config["num_hidden_layers"] = 2
config["intermediate_size"] = 64
config["text_config"]["num_hidden_layers"] = 2
config["text_config"]["intermediate_size"] = 64
config["text_config"]["layer_types"] = config["text_config"]["layer_types"][:2]
config["vision_config"]["depth"] = 2
config["vision_config"]["intermediate_size"] = 64
config["vision_config"]["fullatt_block_indexes"] = [0, 1]
return config
def _shrink_qwen_text_encoder_config(config: dict, hidden_size: int = 64) -> dict:
text_config = config["text_config"]
old_head_dim = text_config["hidden_size"] / text_config["num_attention_heads"]
text_config["num_hidden_layers"] = 2
text_config["intermediate_size"] = 64
text_config["hidden_size"] = hidden_size
text_config["num_attention_heads"] = 2
text_config["num_key_value_heads"] = 2
text_config["layer_types"] = text_config["layer_types"][:2]
factor = old_head_dim / (hidden_size / 2)
mrope_section = text_config["rope_scaling"]["mrope_section"]
text_config["rope_scaling"]["mrope_section"] = [round(d / factor) for d in mrope_section]
config["num_hidden_layers"] = 2
config["intermediate_size"] = 64
config["hidden_size"] = hidden_size
config["num_attention_heads"] = 2
config["num_key_value_heads"] = 2
config["vision_config"]["depth"] = 2
config["vision_config"]["intermediate_size"] = 64
config["vision_config"]["fullatt_block_indexes"] = [0, 1]
config["vision_config"]["out_hidden_size"] = hidden_size
return config
def _shrink_qwen_transformer_config(config: dict, joint_attention_dim: int = 64) -> dict:
return _shrink_dit_rope_config(config, joint_attention_dim=joint_attention_dim)
def tiny_qwen_image_builder() -> str:
return build_tiny_from_configs(
"QwenImagePipeline",
"Qwen/Qwen-Image",
transform={"text_encoder": shrink_text_encoder, "transformer": _shrink_dit_rope_config},
transform={"text_encoder": _shrink_qwen_text_encoder_config, "transformer": _shrink_qwen_transformer_config},
)
def tiny_qwen_image_edit_builder() -> str:
return build_tiny_from_configs(
"QwenImageEditPipeline",
"Qwen/Qwen-Image-Edit",
transform={"text_encoder": _shrink_qwen_text_encoder_config, "transformer": _shrink_qwen_transformer_config},
)
def tiny_qwen_image_edit_plus_builder() -> str:
return build_tiny_from_configs(
"QwenImageEditPlusPipeline",
"Qwen/Qwen-Image-Edit-2511",
transform={"text_encoder": _shrink_qwen_text_encoder_config, "transformer": _shrink_qwen_transformer_config},
)
@@ -74,4 +74,14 @@ DIFFUSION_TEST_SETTINGS = {
builder=diff_model_builders.tiny_flux2_builder,
supported_tasks=[DiffusionTasks.TEXT_TO_IMAGE],
),
"QwenImageEditPipeline": DiffusionModelTestOpts(
model="Qwen/Qwen-Image-Edit",
builder=diff_model_builders.tiny_qwen_image_edit_builder,
supported_tasks=[DiffusionTasks.IMAGE_TO_IMAGE],
),
"QwenImageEditPlusPipeline": DiffusionModelTestOpts(
model="Qwen/Qwen-Image-Edit-2511",
builder=diff_model_builders.tiny_qwen_image_edit_plus_builder,
supported_tasks=[DiffusionTasks.IMAGE_TO_IMAGE],
),
}
@@ -21,8 +21,6 @@ pytestmark = [pytest.mark.diffusion, pytest.mark.cpu, pytest.mark.core_model]
# if you are adding a new model and see the tests below fail, please follow the pattern
# for adding a new tiny model builder and corresponding entry in DIFFUSION_TEST_SETTINGS.
EXCLUDED_MODELS = [
"QwenImageEditPipeline",
"QwenImageEditPlusPipeline",
"QwenImageLayeredPipeline",
"GlmImagePipeline",
"ZImagePipeline",
+3 -23
View File
@@ -105,9 +105,7 @@ forced_aligner:
""",
encoding="utf-8",
)
args = type("Args", (), {"forced_aligner": None, "forced_aligner_config": str(cfg)})()
out = forced_aligner.build_forced_aligner_config(args)
out = forced_aligner.build_forced_aligner_config(None, str(cfg))
assert out == forced_aligner.ForcedAlignerConfig(
model="Qwen/Qwen3-ForcedAligner-0.6B",
@@ -127,16 +125,7 @@ def test_build_config_cli_model_overrides_yaml(tmp_path):
"forced_aligner:\n model: old\n gpu_memory_utilization: 0.2\n dtype: float16\n",
encoding="utf-8",
)
args = type(
"Args",
(),
{
"forced_aligner": "new",
"forced_aligner_config": str(cfg),
},
)()
out = forced_aligner.build_forced_aligner_config(args)
out = forced_aligner.build_forced_aligner_config("new", str(cfg))
assert out is not None
# --forced-aligner overrides the YAML model; gpu_memory_utilization/dtype
@@ -148,16 +137,7 @@ def test_build_config_cli_model_overrides_yaml(tmp_path):
def test_build_config_from_cli_model_uses_default_yaml():
args = type(
"Args",
(),
{
"forced_aligner": "local-aligner",
"forced_aligner_config": None,
},
)()
out = forced_aligner.build_forced_aligner_config(args)
out = forced_aligner.build_forced_aligner_config("local-aligner", None)
assert out is not None
assert out.model == "local-aligner"
@@ -46,20 +46,3 @@ def test_fix_timestamp_repairs_dip_onto_monotonic_sequence():
def test_fix_timestamp_passes_through_monotonic():
assert processor.fix_timestamp([0, 100, 100, 250]) == [0, 100, 100, 250]
def test_resolve_timestamp_token_id_defaults_to_marker_token():
# Regression: the default must resolve the same <timestamp> marker that
# build_prompt inserts, not None (which would degrade every request).
seen = {}
class FakeTokenizer:
def convert_tokens_to_ids(self, token):
seen["token"] = token
return 151705
tid = processor.resolve_timestamp_token_id(FakeTokenizer())
assert tid == 151705
assert seen["token"] == processor.TIMESTAMP_TOKEN
assert processor.TIMESTAMP_TOKEN in processor.build_prompt(["hello", "world"])