[Maintenance] Refresh MOSS-TTS optimization on main
Signed-off-by: Sy03 <1370724210@qq.com>
This commit is contained in:
commit
28dd49a541
334 files changed
+24909
-6187
No files matched your search
@@ -457,5 +457,136 @@ def test_text_benchmark_still_reports_ttft(capsys):
|
||||
assert "Time to First Token" in out, "text benchmarks must keep TTFT"
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Suppress text metrics for pure image / video endpoints
|
||||
# ============================================================================
|
||||
|
||||
|
||||
def _make_image_output(prompt_len: int) -> MixRequestFuncOutput:
|
||||
output = MixRequestFuncOutput()
|
||||
output.success = True
|
||||
output.prompt_len = prompt_len
|
||||
output.output_tokens = 0
|
||||
output.generated_text = ""
|
||||
output.ttft = 0.0
|
||||
output.text_latency = 0.0
|
||||
output.latency = 2.5
|
||||
output.start_time = 0.0
|
||||
output.itl = []
|
||||
output.image_count = 1
|
||||
output.image_generation_time_ms = 2000.0
|
||||
output.image_pixels = 1024 * 1024
|
||||
output.input_audio_duration = 0.0
|
||||
output.error = ""
|
||||
return output
|
||||
|
||||
|
||||
def _make_video_output(prompt_len: int) -> MixRequestFuncOutput:
|
||||
output = MixRequestFuncOutput()
|
||||
output.success = True
|
||||
output.prompt_len = prompt_len
|
||||
output.output_tokens = 0
|
||||
output.generated_text = ""
|
||||
output.ttft = 0.0
|
||||
output.text_latency = 0.0
|
||||
output.latency = 5.0
|
||||
output.start_time = 0.0
|
||||
output.itl = []
|
||||
output.video_duration = 2.0
|
||||
output.video_frames = 48
|
||||
output.video_generation_time_ms = 4000.0
|
||||
output.video_rtf = 2.0
|
||||
output.input_audio_duration = 0.0
|
||||
output.error = ""
|
||||
return output
|
||||
|
||||
|
||||
_MEDIA_PERCENTILE_METRICS = ["e2el", "ttft"]
|
||||
|
||||
|
||||
def test_pure_image_benchmark_omits_text_result(capsys):
|
||||
"""Pure image generation must not print Text Result or invent peak tok/s."""
|
||||
outputs = [_make_image_output(64), _make_image_output(64)]
|
||||
|
||||
metrics, actual_output_lens = calculate_metrics(
|
||||
input_requests=[],
|
||||
outputs=outputs,
|
||||
dur_s=5.0,
|
||||
tokenizer=None,
|
||||
selected_percentiles=[99.0],
|
||||
goodput_config_dict={},
|
||||
task_type=TaskType.GENERATION,
|
||||
selected_percentile_metrics=_MEDIA_PERCENTILE_METRICS,
|
||||
max_concurrency=None,
|
||||
request_rate=float("inf"),
|
||||
benchmark_duration=5.0,
|
||||
)
|
||||
|
||||
out = capsys.readouterr().out
|
||||
assert actual_output_lens == [0, 0]
|
||||
assert metrics.total_output == 0
|
||||
assert metrics.max_output_tokens_per_s == 0.0
|
||||
assert " Text Result " not in out
|
||||
assert "Peak output token throughput" not in out
|
||||
assert "Time to First Token" not in out
|
||||
assert " Image Result " in out
|
||||
|
||||
|
||||
def test_pure_video_benchmark_omits_text_result(capsys):
|
||||
"""Pure video generation must not print Text Result or invent peak tok/s."""
|
||||
outputs = [_make_video_output(63), _make_video_output(63)]
|
||||
|
||||
metrics, actual_output_lens = calculate_metrics(
|
||||
input_requests=[],
|
||||
outputs=outputs,
|
||||
dur_s=10.0,
|
||||
tokenizer=None,
|
||||
selected_percentiles=[99.0],
|
||||
goodput_config_dict={},
|
||||
task_type=TaskType.GENERATION,
|
||||
selected_percentile_metrics=_MEDIA_PERCENTILE_METRICS,
|
||||
max_concurrency=None,
|
||||
request_rate=float("inf"),
|
||||
benchmark_duration=10.0,
|
||||
)
|
||||
|
||||
out = capsys.readouterr().out
|
||||
assert actual_output_lens == [0, 0]
|
||||
assert metrics.total_output == 0
|
||||
assert metrics.max_output_tokens_per_s == 0.0
|
||||
assert " Text Result " not in out
|
||||
assert "Peak output token throughput" not in out
|
||||
assert "Time to First Token" not in out
|
||||
assert " Video Result " in out
|
||||
|
||||
|
||||
def test_image_with_generated_text_still_reports_text_result(capsys):
|
||||
"""Image edits / AR text alongside images must keep Text Result."""
|
||||
output = _make_image_output(64)
|
||||
output.output_tokens = 8
|
||||
output.generated_text = "revised caption"
|
||||
output.ttft = 0.05
|
||||
output.itl = [0.01] * 7
|
||||
|
||||
calculate_metrics(
|
||||
input_requests=[],
|
||||
outputs=[output],
|
||||
dur_s=3.0,
|
||||
tokenizer=_EmptyAwareTokenizer(),
|
||||
selected_percentiles=[99.0],
|
||||
goodput_config_dict={},
|
||||
task_type=TaskType.GENERATION,
|
||||
selected_percentile_metrics=_MEDIA_PERCENTILE_METRICS,
|
||||
max_concurrency=None,
|
||||
request_rate=float("inf"),
|
||||
benchmark_duration=3.0,
|
||||
)
|
||||
|
||||
out = capsys.readouterr().out
|
||||
assert " Text Result " in out
|
||||
assert "Time to First Token" in out
|
||||
assert " Image Result " in out
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
pytest.main([__file__, "-v", "-s"])
|
||||
@@ -22,9 +22,16 @@ from vllm_omni.benchmarks.data_modules.seed_tts_dataset import (
|
||||
)
|
||||
from vllm_omni.benchmarks.patch.patch import (
|
||||
MixRequestFuncOutput,
|
||||
_add_video_extra_body_to_form,
|
||||
_add_video_reference_to_form,
|
||||
_apply_stage0_token_timings,
|
||||
_apply_video_metrics_from_payload,
|
||||
_attach_seed_tts_to_request_func_input,
|
||||
_build_benchmark_session,
|
||||
_omni_request_timeout_s,
|
||||
async_request_openai_chat_omni_completions,
|
||||
async_request_openai_image_edits_omni,
|
||||
async_request_openai_image_generations_omni,
|
||||
async_request_openai_realtime_duplex,
|
||||
should_request_stage_metrics,
|
||||
)
|
||||
@@ -1196,5 +1203,337 @@ async def test_prompt_len_assigned_from_usage(mocker: MockerFixture):
|
||||
)
|
||||
|
||||
|
||||
class TestOmniRequestTimeout:
|
||||
"""``--omni-request-timeout-s`` precedence: explicit value > 900 s default."""
|
||||
|
||||
_OVERRIDE = "vllm_omni.benchmarks.patch.patch._REQUEST_TIMEOUT_OVERRIDE_S"
|
||||
|
||||
def test_default_timeout_is_900s_when_not_set(self, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(self._OVERRIDE, None)
|
||||
assert _omni_request_timeout_s() == 900.0
|
||||
|
||||
def test_explicit_value_wins_over_default(self, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(self._OVERRIDE, 123.5)
|
||||
assert _omni_request_timeout_s() == 123.5
|
||||
|
||||
def test_non_positive_restores_legacy_6h_cap(self, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(self._OVERRIDE, 0)
|
||||
assert _omni_request_timeout_s() == 6 * 60 * 60.0
|
||||
|
||||
async def test_benchmark_session_uses_configured_timeout(self, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(self._OVERRIDE, 42.0)
|
||||
session = _build_benchmark_session(max_concurrency=8, ssl_setting=False)
|
||||
try:
|
||||
assert session.timeout.total == 42.0
|
||||
assert session.connector.limit == 8
|
||||
assert session.connector.limit_per_host == 8
|
||||
finally:
|
||||
await session.close()
|
||||
|
||||
async def test_hung_server_request_times_out_as_failed(self, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""A server that accepts the request but never responds must surface as ``failed``."""
|
||||
|
||||
async def handler(reader, writer):
|
||||
# Drain the request but never respond — the original hang failure mode.
|
||||
try:
|
||||
while await reader.read(4096):
|
||||
pass
|
||||
except ConnectionResetError:
|
||||
pass
|
||||
finally:
|
||||
# Close our side of the socket: the client aborts after the
|
||||
# timeout and only sends FIN, so without writer.close() the
|
||||
# half-closed connection keeps Server.wait_closed() (which on
|
||||
# Python 3.12+ waits for every accepted connection to drop)
|
||||
# blocked forever.
|
||||
writer.close()
|
||||
try:
|
||||
await writer.wait_closed()
|
||||
except (ConnectionResetError, BrokenPipeError):
|
||||
pass
|
||||
|
||||
monkeypatch.setattr(self._OVERRIDE, 1.0)
|
||||
server = await asyncio.start_server(handler, "127.0.0.1", 0)
|
||||
port = server.sockets[0].getsockname()[1]
|
||||
session = _build_benchmark_session(max_concurrency=1, ssl_setting=False)
|
||||
try:
|
||||
request_input = _seed_tts_request_func_input()
|
||||
request_input.api_url = f"http://127.0.0.1:{port}/v1/chat/completions"
|
||||
output = await async_request_openai_chat_omni_completions(request_input, session)
|
||||
assert output.success is False
|
||||
assert output.error
|
||||
finally:
|
||||
await session.close()
|
||||
server.close()
|
||||
await server.wait_closed()
|
||||
|
||||
|
||||
def test_video_rtf_prefers_generation_time_over_poll_latency():
|
||||
"""RTF must not grow with client poll_interval overshoot in output.latency."""
|
||||
payload = {
|
||||
"duration_s": 2.0,
|
||||
"num_frames": 48,
|
||||
"fps": 24.0,
|
||||
"stage_durations": {"stage_0_gen_ms": 4000.0},
|
||||
}
|
||||
request_body: dict[str, object] = {}
|
||||
|
||||
short_poll = MixRequestFuncOutput()
|
||||
short_poll.latency = 4.2 # ~generation + small poll overshoot
|
||||
_apply_video_metrics_from_payload(short_poll, payload, request_body)
|
||||
|
||||
long_poll = MixRequestFuncOutput()
|
||||
long_poll.latency = 8.0 # same job, larger poll_interval_s overshoot
|
||||
_apply_video_metrics_from_payload(long_poll, payload, request_body)
|
||||
|
||||
assert short_poll.video_generation_time_ms == pytest.approx(4000.0)
|
||||
assert long_poll.video_generation_time_ms == pytest.approx(4000.0)
|
||||
assert short_poll.video_rtf == pytest.approx(2.0)
|
||||
assert long_poll.video_rtf == pytest.approx(2.0)
|
||||
assert short_poll.video_rtf == long_poll.video_rtf
|
||||
|
||||
|
||||
def test_video_rtf_falls_back_to_e2e_latency_without_generation_time():
|
||||
output = MixRequestFuncOutput()
|
||||
output.latency = 6.0
|
||||
_apply_video_metrics_from_payload(
|
||||
output,
|
||||
{"duration_s": 2.0, "num_frames": 48, "fps": 24.0},
|
||||
{},
|
||||
)
|
||||
assert output.video_generation_time_ms == 0.0
|
||||
assert output.video_rtf == pytest.approx(3.0)
|
||||
|
||||
|
||||
# 1x1 PNG used as a valid b64_json image payload in edit-client tests.
|
||||
_MIN_PNG_B64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_image_edits_defaults_to_non_streaming_json(mocker: MockerFixture) -> None:
|
||||
"""Single-stage servers reject stream=true; default path must send stream=false + JSON."""
|
||||
|
||||
class MockJsonResponse:
|
||||
status = 200
|
||||
|
||||
def __init__(self):
|
||||
self._payload = {
|
||||
"created": 1,
|
||||
"data": [
|
||||
{
|
||||
"b64_json": _MIN_PNG_B64,
|
||||
"stage_durations": {"stage_0_gen_ms": 12.5},
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
async def json(self):
|
||||
return self._payload
|
||||
|
||||
async def text(self):
|
||||
return json.dumps(self._payload)
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *_args):
|
||||
return None
|
||||
|
||||
captured_stream: list[str] = []
|
||||
real_add_field = None
|
||||
|
||||
def tracking_add_field(self, name, value=None, **kwargs):
|
||||
if name == "stream":
|
||||
captured_stream.append(str(value))
|
||||
return real_add_field(self, name, value, **kwargs)
|
||||
|
||||
import aiohttp
|
||||
|
||||
real_add_field = aiohttp.FormData.add_field
|
||||
mocker.patch.object(aiohttp.FormData, "add_field", tracking_add_field)
|
||||
|
||||
mock_session = mocker.AsyncMock()
|
||||
mock_session.post = mocker.MagicMock(return_value=MockJsonResponse())
|
||||
|
||||
request = RequestFuncInput(
|
||||
model="single-stage-edit",
|
||||
model_name="single-stage-edit",
|
||||
prompt="make it sunny",
|
||||
api_url="http://test.com/v1/images/edits",
|
||||
prompt_len=4,
|
||||
output_len=1,
|
||||
multi_modal_content=[{"type": "image_url", "image_url": {"url": f"data:image/png;base64,{_MIN_PNG_B64}"}}],
|
||||
extra_body={"num_inference_steps": 4},
|
||||
)
|
||||
output = await async_request_openai_image_edits_omni(request, mock_session, pbar=None)
|
||||
|
||||
assert captured_stream == ["false"]
|
||||
assert output.success is True
|
||||
assert not output.error
|
||||
assert output.image_count == 1
|
||||
assert output.image_generation_time_ms == pytest.approx(12.5)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_image_edits_stream_true_uses_sse_path(mocker: MockerFixture) -> None:
|
||||
"""Explicit stream=true keeps the multi-stage SSE client path."""
|
||||
sse_chunk = (
|
||||
b'data: {"type":"image","data":[{"b64_json":"' + _MIN_PNG_B64.encode() + b'"}]}\n\n' + b"data: [DONE]\n\n"
|
||||
)
|
||||
mock_response = MockResponse(200, [sse_chunk])
|
||||
captured_stream: list[str] = []
|
||||
|
||||
import aiohttp
|
||||
|
||||
real_add_field = aiohttp.FormData.add_field
|
||||
|
||||
def tracking_add_field(self, name, value=None, **kwargs):
|
||||
if name == "stream":
|
||||
captured_stream.append(str(value))
|
||||
return real_add_field(self, name, value, **kwargs)
|
||||
|
||||
mocker.patch.object(aiohttp.FormData, "add_field", tracking_add_field)
|
||||
|
||||
mock_session = mocker.AsyncMock()
|
||||
mock_session.post = mocker.MagicMock(return_value=mock_response)
|
||||
|
||||
request = RequestFuncInput(
|
||||
model="multi-stage-edit",
|
||||
model_name="multi-stage-edit",
|
||||
prompt="edit",
|
||||
api_url="http://test.com/v1/images/edits",
|
||||
prompt_len=2,
|
||||
output_len=1,
|
||||
multi_modal_content=[{"type": "image_url", "image_url": {"url": f"data:image/png;base64,{_MIN_PNG_B64}"}}],
|
||||
extra_body={"stream": True},
|
||||
)
|
||||
output = await async_request_openai_image_edits_omni(request, mock_session, pbar=None)
|
||||
|
||||
assert captured_stream == ["true"]
|
||||
assert output.success is True
|
||||
assert output.image_count == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_image_generations_e2el_includes_json_body_consume(mocker: MockerFixture) -> None:
|
||||
"""E2EL must include body transfer/decode, not stop at HTTP headers."""
|
||||
|
||||
class SlowJsonResponse:
|
||||
status = 200
|
||||
|
||||
def __init__(self):
|
||||
self._payload = {
|
||||
"created": 1,
|
||||
"data": [{"b64_json": _MIN_PNG_B64, "stage_durations": {"stage_0_gen_ms": 1.0}}],
|
||||
}
|
||||
|
||||
async def json(self):
|
||||
await asyncio.sleep(0.05)
|
||||
return self._payload
|
||||
|
||||
async def text(self):
|
||||
return json.dumps(self._payload)
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *_args):
|
||||
return None
|
||||
|
||||
mock_session = mocker.AsyncMock()
|
||||
mock_session.post = mocker.MagicMock(return_value=SlowJsonResponse())
|
||||
request = RequestFuncInput(
|
||||
model="img-gen",
|
||||
model_name="img-gen",
|
||||
prompt="a cat",
|
||||
api_url="http://test.com/v1/images/generations",
|
||||
prompt_len=2,
|
||||
output_len=1,
|
||||
extra_body={},
|
||||
)
|
||||
output = await async_request_openai_image_generations_omni(request, mock_session, pbar=None)
|
||||
assert output.success is True
|
||||
assert output.latency >= 0.05
|
||||
|
||||
|
||||
def test_video_local_image_reference_not_forwarded_as_raw_extra_field(tmp_path, mocker: MockerFixture) -> None:
|
||||
"""Local image_reference must only be uploaded via dedicated serializer."""
|
||||
import aiohttp
|
||||
|
||||
ref_path = tmp_path / "ref.png"
|
||||
ref_path.write_bytes(base64.b64decode(_MIN_PNG_B64))
|
||||
|
||||
captured: list[tuple[str, object]] = []
|
||||
real_add_field = aiohttp.FormData.add_field
|
||||
|
||||
def tracking_add_field(self, name, value=None, **kwargs):
|
||||
captured.append((str(name), value))
|
||||
return real_add_field(self, name, value, **kwargs)
|
||||
|
||||
mocker.patch.object(aiohttp.FormData, "add_field", tracking_add_field)
|
||||
|
||||
form = aiohttp.FormData()
|
||||
extra_body = {
|
||||
"num_inference_steps": 2,
|
||||
"image_reference": str(ref_path),
|
||||
}
|
||||
request_body = {"model": "vid", "prompt": "p", **extra_body}
|
||||
_add_video_extra_body_to_form(form, extra_body, request_body)
|
||||
assert _add_video_reference_to_form(form, extra_body["image_reference"]) is True
|
||||
|
||||
field_names = [name for name, _ in captured]
|
||||
assert "image_reference" not in field_names
|
||||
assert field_names.count("input_reference") == 1
|
||||
# Dedicated uploader sends file bytes, not the raw local path string.
|
||||
uploaded = next(value for name, value in captured if name == "input_reference")
|
||||
assert uploaded == base64.b64decode(_MIN_PNG_B64)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"reference",
|
||||
[
|
||||
{"image_url": "https://example.com/ref.png"},
|
||||
{"file_id": "file-abc"},
|
||||
[{"image_url": "https://example.com/a.png"}, {"file_id": "file-xyz"}],
|
||||
],
|
||||
)
|
||||
def test_video_structured_image_reference_serialized_to_form(reference: object, mocker: MockerFixture) -> None:
|
||||
"""Object-form image_reference must be JSON-serialized, not silently dropped."""
|
||||
import aiohttp
|
||||
|
||||
captured: list[tuple[str, object]] = []
|
||||
real_add_field = aiohttp.FormData.add_field
|
||||
|
||||
def tracking_add_field(self, name, value=None, **kwargs):
|
||||
captured.append((str(name), value))
|
||||
return real_add_field(self, name, value, **kwargs)
|
||||
|
||||
mocker.patch.object(aiohttp.FormData, "add_field", tracking_add_field)
|
||||
|
||||
form = aiohttp.FormData()
|
||||
extra_body = {"image_reference": reference}
|
||||
request_body = {"model": "vid", "prompt": "p", **extra_body}
|
||||
_add_video_extra_body_to_form(form, extra_body, request_body)
|
||||
assert _add_video_reference_to_form(form, reference) is True
|
||||
|
||||
field_names = [name for name, _ in captured]
|
||||
# Reserved key must not be double-forwarded as a generic extra field;
|
||||
# exactly one dedicated image_reference field.
|
||||
assert field_names.count("image_reference") == 1
|
||||
assert "input_reference" not in field_names
|
||||
payload = next(value for name, value in captured if name == "image_reference")
|
||||
assert json.loads(payload) == reference
|
||||
|
||||
|
||||
def test_video_unsupported_image_reference_raises() -> None:
|
||||
import aiohttp
|
||||
|
||||
form = aiohttp.FormData()
|
||||
with pytest.raises(ValueError, match="Unsupported image_reference"):
|
||||
_add_video_reference_to_form(form, {"not_a_supported_key": "x"})
|
||||
with pytest.raises(ValueError, match="Unsupported image_reference"):
|
||||
_add_video_reference_to_form(form, "/tmp/does-not-exist-ref.png")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
pytest.main([__file__, "-v", "-s"])
|
||||
@@ -1,9 +1,11 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
# ruff: noqa: E402, I001
|
||||
import argparse
|
||||
import math
|
||||
import os
|
||||
import sys
|
||||
import types
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
@@ -106,11 +108,9 @@ def test_resolve_seed_tts_root_downloads_only_requested_locale(monkeypatch, tmp_
|
||||
captured["allow_patterns"] = allow_patterns
|
||||
return str(downloaded_root)
|
||||
|
||||
monkeypatch.setitem(
|
||||
sys.modules,
|
||||
"huggingface_hub",
|
||||
types.SimpleNamespace(snapshot_download=fake_snapshot_download),
|
||||
)
|
||||
from vllm_omni.transformers_utils import repo_utils
|
||||
|
||||
monkeypatch.setattr(repo_utils.hf_api(), "snapshot_download", fake_snapshot_download)
|
||||
|
||||
resolved = resolve_seed_tts_root(
|
||||
"zhaochenyang20/seed-tts-eval",
|
||||
|
||||
@@ -167,6 +167,26 @@ def test_preprocess_serve_args_applies_safe_omniinteract_prompt_default(
|
||||
{"bot_task": "recaption"},
|
||||
{"backend", "print_stage", "bot_task"},
|
||||
),
|
||||
(
|
||||
[
|
||||
"--endpoint",
|
||||
"/v1/images/edits",
|
||||
"--image-edits-bot-task",
|
||||
"think",
|
||||
],
|
||||
{"bot_task": "think"},
|
||||
{"endpoint", "bot_task"},
|
||||
),
|
||||
(
|
||||
[
|
||||
"--backend",
|
||||
"/v1/images/edits",
|
||||
"--image-edits-bot-task",
|
||||
"recaption",
|
||||
],
|
||||
{"bot_task": "recaption"},
|
||||
{"backend", "bot_task"},
|
||||
),
|
||||
(
|
||||
["--extra-body", '{"bot_task":"vanilla"}'],
|
||||
{"bot_task": "vanilla"},
|
||||
@@ -182,6 +202,7 @@ def test_omni_args_parse_and_preprocess(
|
||||
parser = TrackingArgumentParser()
|
||||
parser.add_argument("--extra-body", type=json.loads, default=None)
|
||||
parser.add_argument("--backend", default="openai-chat-omni")
|
||||
parser.add_argument("--endpoint", default="/v1/chat/completions")
|
||||
add_omni_args(parser)
|
||||
|
||||
args = parser.parse_args(argv)
|
||||
@@ -358,3 +379,17 @@ def test_bench_serve_cli_mocks_http_request(tmp_path: Path):
|
||||
)
|
||||
assert bench_requests
|
||||
assert all(url == expected_url for url in bench_requests), f"Unexpected target URLs: {bench_requests}"
|
||||
|
||||
|
||||
def test_omni_request_timeout_s_flag_defaults_and_parses() -> None:
|
||||
parser = TrackingArgumentParser()
|
||||
add_omni_args(parser)
|
||||
|
||||
args = parser.parse_args([])
|
||||
assert args.omni_request_timeout_s is None
|
||||
|
||||
args = parser.parse_args(["--omni-request-timeout-s", "0"])
|
||||
assert args.omni_request_timeout_s == 0.0
|
||||
|
||||
args = parser.parse_args(["--omni-request-timeout-s", "3600"])
|
||||
assert args.omni_request_timeout_s == 3600.0
|
||||
@@ -6,7 +6,6 @@ Unit tests for StageConfigFactory and related classes.
|
||||
|
||||
import importlib
|
||||
import warnings
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
@@ -37,6 +36,7 @@ from vllm_omni.config.stage_config import (
|
||||
normalize_pipeline_cli_overrides,
|
||||
pipeline_cfg_resolver,
|
||||
)
|
||||
from vllm_omni.diffusion.data import DiffusionParallelConfig
|
||||
from vllm_omni.engine.arg_utils import SHARED_FIELDS, internal_blacklist_keys
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
@@ -451,13 +451,8 @@ class TestStageConfigFactory:
|
||||
|
||||
def test_default_diffusion_with_parallel_config(self):
|
||||
"""Test diffusion config calculates devices from parallel_config."""
|
||||
|
||||
@dataclass
|
||||
class MockParallelConfig:
|
||||
world_size: int = 4
|
||||
|
||||
kwargs = {
|
||||
"parallel_config": MockParallelConfig(),
|
||||
"parallel_config": DiffusionParallelConfig(tensor_parallel_size=4),
|
||||
"cache_backend": "tea_cache",
|
||||
}
|
||||
configs = StageConfigFactory.create_default_diffusion(kwargs)
|
||||
@@ -937,6 +932,44 @@ class TestPipelineRegistration:
|
||||
assert isinstance(omni_config, VllmOmniConfig)
|
||||
assert omni_config.stage_by_id(0).diffusion_config.model == "fake/model"
|
||||
|
||||
def test_cosyvoice3_deploy_resolves_hash_snapshot_without_hf_metadata(self, tmp_path):
|
||||
snapshot = tmp_path / "models--FunAudioLLM--Fun-CosyVoice3-0.5B-2512" / "snapshots" / ("a" * 40)
|
||||
snapshot.mkdir(parents=True)
|
||||
(snapshot / "config.json").write_text("{}\n", encoding="utf-8")
|
||||
model = str(snapshot)
|
||||
deploy_path = get_deploy_config_path("cosyvoice3.yaml")
|
||||
|
||||
assert StageConfigFactory.try_infer_model_type(model, trust_remote_code=False) is None
|
||||
assert StageConfigFactory.get_pipeline_config(model, trust_remote_code=False) is None
|
||||
|
||||
omni_config = StageConfigFactory.create_from_model(
|
||||
model,
|
||||
trust_remote_code=False,
|
||||
cli_overrides={},
|
||||
deploy_config_path=deploy_path,
|
||||
)
|
||||
legacy_configs, _ = StageConfigFactory.create_legacy_stage_configs_from_model(
|
||||
model,
|
||||
trust_remote_code=False,
|
||||
cli_overrides={},
|
||||
deploy_config_path=deploy_path,
|
||||
)
|
||||
|
||||
assert omni_config is not None
|
||||
assert omni_config.pipeline_config.model_type == "cosyvoice3"
|
||||
assert [
|
||||
(stage.stage_id, stage.stage_type, stage.worker_type, stage.model_stage)
|
||||
for stage in omni_config.stage_configs
|
||||
] == [
|
||||
(0, StageType.LLM, "ar", "cosyvoice3_talker"),
|
||||
(1, StageType.LLM, "generation", "cosyvoice3_code2wav"),
|
||||
]
|
||||
assert all(stage.model_config.model == model for stage in omni_config.stage_configs)
|
||||
assert all(stage.stage_type is not StageType.DIFFUSION for stage in omni_config.stage_configs)
|
||||
|
||||
assert legacy_configs is not None
|
||||
assert [stage.stage_type for stage in legacy_configs] == [StageType.LLM, StageType.LLM]
|
||||
|
||||
def test_pipeline_registration(self, clean_pipeline_registry):
|
||||
"""Ensure that we can register and create a custom pipeline config."""
|
||||
new_model_type = "new_model_type"
|
||||
@@ -1602,7 +1635,7 @@ stages:
|
||||
assert stage.max_model_len == 1024
|
||||
assert stage.max_num_batched_tokens == 1024
|
||||
assert stage.max_num_seqs == 1
|
||||
assert stage.gpu_memory_utilization == 0.7
|
||||
assert stage.gpu_memory_utilization == 0.8
|
||||
assert stage.skip_mm_profiling is True
|
||||
assert stage.enforce_eager is True
|
||||
assert stage.async_scheduling is False
|
||||
|
||||
@@ -167,7 +167,7 @@ def test_inventory_matches_reviewed_snapshot_counts():
|
||||
EnvironmentVariableCategory.PUBLIC_OMNI: 24,
|
||||
EnvironmentVariableCategory.INHERITED_VLLM: 20,
|
||||
EnvironmentVariableCategory.PLATFORM_EXTERNAL: 27,
|
||||
EnvironmentVariableCategory.MODEL_SPECIFIC: 62,
|
||||
EnvironmentVariableCategory.MODEL_SPECIFIC: 61,
|
||||
EnvironmentVariableCategory.BENCHMARK_TRANSITIONAL: 20,
|
||||
EnvironmentVariableCategory.INTERNAL: 2,
|
||||
}
|
||||
@@ -179,7 +179,7 @@ def test_inventory_matches_reviewed_snapshot_counts():
|
||||
)
|
||||
assert {disposition: disposition_counts[disposition] for disposition in ModelEnvironmentVariableDisposition} == {
|
||||
ModelEnvironmentVariableDisposition.PROMOTE: 37,
|
||||
ModelEnvironmentVariableDisposition.REQUEST_SCOPE: 7,
|
||||
ModelEnvironmentVariableDisposition.REQUEST_SCOPE: 6,
|
||||
ModelEnvironmentVariableDisposition.EXTERNAL: 0,
|
||||
ModelEnvironmentVariableDisposition.INTERNALIZE: 13,
|
||||
ModelEnvironmentVariableDisposition.DEPRECATE_REMOVE: 5,
|
||||
|
||||
@@ -261,6 +261,57 @@ def test_from_pipeline_config_rejects_unowned_deploy_engine_extras(engine_extras
|
||||
VllmOmniConfig.from_pipeline_config(pipeline, user_deploy_config=deploy)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stage_id", [0, 2], ids=["ar", "generation"])
|
||||
def test_llm_additional_config_roundtrip_and_isolation(stage_id, monkeypatch):
|
||||
from vllm_omni.engine import stage_init_utils
|
||||
from vllm_omni.engine.stage_init_utils import build_engine_args_dict_from_omni_stage_config
|
||||
|
||||
# Worker discovery requires hardware support; this test covers config transport.
|
||||
monkeypatch.setattr(stage_init_utils, "resolve_worker_cls", lambda engine_args: None)
|
||||
additional_config = {"backend_options": {"enabled": True}}
|
||||
pipeline = _resolve_pipeline_or_skip("minicpmo_4_5")
|
||||
deploy = DeployConfig(
|
||||
stages=[StageDeployConfig(stage_id=i, engine_extras={"additional_config": additional_config}) for i in (0, 2)]
|
||||
)
|
||||
config = VllmOmniConfig.from_pipeline_config(pipeline, user_deploy_config=deploy)
|
||||
stage = config.stage_by_id(stage_id)
|
||||
assert stage.runtime_config.additional_config == additional_config
|
||||
engine_args = build_engine_args_dict_from_omni_stage_config(stage, model="test-model")
|
||||
assert engine_args["additional_config"] == additional_config
|
||||
|
||||
engine_args["additional_config"]["backend_options"]["enabled"] = False
|
||||
assert stage.runtime_config.additional_config["backend_options"]["enabled"] is True
|
||||
stage.runtime_config.additional_config["backend_options"]["enabled"] = False
|
||||
assert config.stage_by_id(2 if stage_id == 0 else 0).runtime_config.additional_config == additional_config
|
||||
assert additional_config["backend_options"]["enabled"] is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize("deploy_name", ["minicpmo_4_5", "minicpmo_4_5_2gpu", "minicpmo_4_5_3gpu"])
|
||||
def test_minicpmo_npu_additional_config_reaches_engine_args(monkeypatch, deploy_name):
|
||||
from vllm_omni.engine import stage_init_utils
|
||||
from vllm_omni.engine.stage_init_utils import build_engine_args_dict_from_omni_stage_config
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
monkeypatch.setattr(current_omni_platform, "device_name", "npu")
|
||||
monkeypatch.setattr(stage_init_utils, "resolve_worker_cls", lambda engine_args: None)
|
||||
stage = _from_pipeline_key("minicpmo_4_5", deploy_config_path=deploy_name).stage_by_id(2)
|
||||
expected = {"code2wav_enable_npu_graph": True, "code2wav_max_npu_graphs": 32}
|
||||
assert stage.runtime_config.additional_config == expected
|
||||
engine_args = build_engine_args_dict_from_omni_stage_config(stage, model="test-model")
|
||||
assert engine_args["additional_config"] == expected
|
||||
|
||||
|
||||
def test_diffusion_additional_config_keeps_diffusion_owner():
|
||||
from vllm_omni.engine.stage_init_utils import build_engine_args_dict_from_omni_stage_config
|
||||
|
||||
additional_config = {"torchair_graph_config": {"enabled": True}}
|
||||
stage = _from_pipeline_key("dreamzero", cli_overrides={"additional_config": additional_config}).stage_by_id(0)
|
||||
assert stage.runtime_config.additional_config is None
|
||||
assert stage.diffusion_config.additional_config == additional_config
|
||||
engine_args = build_engine_args_dict_from_omni_stage_config(stage, model="test-model")
|
||||
assert engine_args["additional_config"] == additional_config
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("engine_extras", "cli_overrides"),
|
||||
[
|
||||
@@ -532,6 +583,17 @@ def test_from_pipeline_config_dispatches_async_chunk_processors_without_mutating
|
||||
assert pipeline.get_stage(1).custom_process_input_func is None
|
||||
|
||||
|
||||
def test_joyai_code2wav_waits_for_full_payload():
|
||||
config = _from_pipeline_key("joyai_vl_interaction")
|
||||
talker = config.stage_by_id(1)
|
||||
code2wav = config.stage_by_id(2)
|
||||
|
||||
assert talker.custom_process_next_stage_input_func.endswith("talker2code2wav_full_payload")
|
||||
assert code2wav.custom_process_input_func.endswith("talker2code2wav_token_only")
|
||||
assert code2wav.connector_config.async_chunk is False
|
||||
assert code2wav.model_config.requires_full_payload_input is True
|
||||
|
||||
|
||||
def test_vllm_omni_stage_config_public_fields_use_typed_stage_realizations():
|
||||
assert not hasattr(BaseVllmOmniStageConfig, "from_stage_config")
|
||||
assert not hasattr(BaseVllmOmniStageConfig, "to_legacy_stage_config")
|
||||
@@ -559,6 +621,7 @@ def test_vllm_omni_stage_config_public_fields_use_typed_stage_realizations():
|
||||
|
||||
def test_runtime_config_fields_match_structured_runtime_scope():
|
||||
assert {f.name for f in fields(OmniStageRuntimeConfig)} == {
|
||||
"additional_config",
|
||||
"distributed_executor_backend",
|
||||
"worker_cls",
|
||||
"devices",
|
||||
@@ -1253,6 +1316,70 @@ def test_diffusion_config_from_kwargs_reuses_legacy_normalization(monkeypatch):
|
||||
assert cfg.diffusers_call_kwargs == {}
|
||||
|
||||
|
||||
def test_diffusion_config_none_values_preserve_dataclass_defaults():
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig
|
||||
|
||||
normalized = OmniDiffusionConfig.normalize_init_kwargs(
|
||||
{
|
||||
"lora_scale": None,
|
||||
"enable_sleep_mode": None,
|
||||
"diffusers_load_kwargs": None,
|
||||
}
|
||||
)
|
||||
|
||||
assert "lora_scale" not in normalized
|
||||
assert "enable_sleep_mode" not in normalized
|
||||
assert normalized["diffusers_load_kwargs"] == {}
|
||||
|
||||
config = OmniDiffusionConfig.from_kwargs(
|
||||
lora_scale=None,
|
||||
enable_sleep_mode=None,
|
||||
)
|
||||
assert config.lora_scale == 1.0
|
||||
assert config.enable_sleep_mode is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("canonical_key", "alias_key", "canonical_value", "alias_value"),
|
||||
[
|
||||
("lora_scale", "static_lora_scale", 0.75, 0.25),
|
||||
(
|
||||
"quantization_config",
|
||||
"diffusion_quantization_config",
|
||||
{"method": "canonical"},
|
||||
{"method": "diffusion-alias"},
|
||||
),
|
||||
(
|
||||
"quantization_config",
|
||||
"quantization",
|
||||
{"method": "canonical"},
|
||||
"legacy-alias",
|
||||
),
|
||||
("diffusion_kv_cache_dtype", "kv_cache_dtype", "fp8", "fp16"),
|
||||
("diffusion_kv_cache_skip_steps", "kv_cache_skip_steps", "0-1", "2-3"),
|
||||
("diffusion_kv_cache_skip_layers", "kv_cache_skip_layers", "1-2", "3-4"),
|
||||
("streaming_output", "diffusion_streaming_output", False, True),
|
||||
],
|
||||
)
|
||||
def test_diffusion_alias_conflicts_prefer_canonical_key(
|
||||
canonical_key,
|
||||
alias_key,
|
||||
canonical_value,
|
||||
alias_value,
|
||||
):
|
||||
from vllm_omni.diffusion.data import normalize_omni_diffusion_kwargs
|
||||
|
||||
normalized = normalize_omni_diffusion_kwargs(
|
||||
{
|
||||
canonical_key: canonical_value,
|
||||
alias_key: alias_value,
|
||||
}
|
||||
)
|
||||
|
||||
assert normalized[canonical_key] == canonical_value
|
||||
assert alias_key not in normalized
|
||||
|
||||
|
||||
def test_from_pipeline_config_normalizes_diffusion_config_aliases_from_engine_args(tmp_path, monkeypatch):
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""
|
||||
Performance benchmark CI runner for diffusion models.
|
||||
|
||||
@@ -356,6 +359,8 @@ def _resolve_offline_model(model: str) -> str:
|
||||
"""
|
||||
import huggingface_hub
|
||||
|
||||
from vllm_omni.transformers_utils.repo_utils import hf_api
|
||||
|
||||
if not model or os.path.isdir(model):
|
||||
return model
|
||||
|
||||
@@ -380,9 +385,7 @@ def _resolve_offline_model(model: str) -> str:
|
||||
if len(parts) >= 3:
|
||||
repo_id = "/".join(parts[:2])
|
||||
subfolder = "/".join(parts[2:])
|
||||
from huggingface_hub import snapshot_download
|
||||
|
||||
snapshot_root = snapshot_download(
|
||||
snapshot_root = hf_api().snapshot_download(
|
||||
repo_id,
|
||||
allow_patterns=[f"{subfolder}/**"],
|
||||
local_files_only=huggingface_hub.constants.HF_HUB_OFFLINE,
|
||||
@@ -391,9 +394,7 @@ def _resolve_offline_model(model: str) -> str:
|
||||
|
||||
if not huggingface_hub.constants.HF_HUB_OFFLINE:
|
||||
return model
|
||||
from huggingface_hub import snapshot_download
|
||||
|
||||
return snapshot_download(model, local_files_only=True)
|
||||
return hf_api().snapshot_download(model, local_files_only=True)
|
||||
|
||||
|
||||
class DiffusionServer:
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import weakref
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from diffusers.models.autoencoders import AutoencoderKLWan
|
||||
|
||||
from vllm_omni.diffusion.distributed.autoencoders import wan_spatial_shard
|
||||
from vllm_omni.diffusion.distributed.autoencoders.autoencoder_kl_wan import (
|
||||
DistributedAutoencoderKLWan,
|
||||
OmniAutoencoderKLWan,
|
||||
)
|
||||
from vllm_omni.diffusion.models.interface import supports_chunked_vae_decode
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu, pytest.mark.diffusion]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def vae():
|
||||
# Real causal convolutions and caches, with small random weights for CPU CI.
|
||||
return OmniAutoencoderKLWan(
|
||||
base_dim=4,
|
||||
z_dim=2,
|
||||
dim_mult=[1, 2],
|
||||
num_res_blocks=1,
|
||||
temperal_downsample=[True],
|
||||
scale_factor_spatial=2,
|
||||
scale_factor_temporal=2,
|
||||
).eval()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("patch_size", [None, 2])
|
||||
@pytest.mark.parametrize("return_dict", [False, True])
|
||||
@torch.no_grad()
|
||||
def test_chunked_decode_matches_diffusers(vae, patch_size, return_dict):
|
||||
if patch_size is not None:
|
||||
vae = OmniAutoencoderKLWan.from_config(vae.config, patch_size=patch_size, out_channels=12).eval()
|
||||
z = torch.randn(1, 2, 3, 2, 2)
|
||||
expected = AutoencoderKLWan._decode(vae, z).sample
|
||||
actual = vae.decode(z, return_dict=return_dict)
|
||||
torch.testing.assert_close(actual.sample if return_dict else actual[0], expected, rtol=0, atol=0)
|
||||
chunks: list[torch.Tensor] = []
|
||||
assert supports_chunked_vae_decode(vae)
|
||||
assert not supports_chunked_vae_decode(object())
|
||||
assert vae.decode_with_chunks(z, on_chunk=chunks.append) is None
|
||||
assert [chunk.shape[2] for chunk in chunks] == [1, 2, 2]
|
||||
torch.testing.assert_close(torch.cat(chunks, dim=2), expected, rtol=0, atol=0)
|
||||
assert all(entry is None for entry in vae._feat_map)
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def test_slicing_and_forward_hooks(vae):
|
||||
z = torch.randn(2, 2, 2, 2, 2)
|
||||
vae.enable_slicing()
|
||||
batches = []
|
||||
handle = vae.post_quant_conv.register_forward_pre_hook(lambda module, args: batches.append(args[0].shape[0]))
|
||||
vae._hf_hook = SimpleNamespace(pre_forward=Mock())
|
||||
try:
|
||||
assert vae.decode(z).sample.shape[0] == 2
|
||||
assert batches == [1, 1]
|
||||
vae._hf_hook.pre_forward.assert_called_once_with(vae)
|
||||
batches.clear()
|
||||
with pytest.raises(ValueError, match="use_slicing"):
|
||||
vae.decode_with_chunks(z, on_chunk=Mock())
|
||||
assert batches == []
|
||||
vae._hf_hook.pre_forward.reset_mock()
|
||||
vae.decode_with_chunks(z[:1], on_chunk=Mock())
|
||||
assert batches == [1]
|
||||
vae._hf_hook.pre_forward.assert_called_once_with(vae)
|
||||
finally:
|
||||
handle.remove()
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def test_callback_failure_drains_and_clears_cache(vae):
|
||||
z = torch.randn(1, 2, 4, 2, 2)
|
||||
decoded = Mock(return_value=None)
|
||||
handle = vae.decoder.register_forward_hook(lambda *args: decoded())
|
||||
error = RuntimeError("consumer failed")
|
||||
callback = Mock(side_effect=error)
|
||||
try:
|
||||
with pytest.raises(RuntimeError, match="consumer failed") as exc:
|
||||
vae.decode_with_chunks(z, on_chunk=callback)
|
||||
assert exc.value is error
|
||||
assert callback.call_count == 1
|
||||
assert decoded.call_count == z.shape[2]
|
||||
assert all(entry is None for entry in vae._feat_map)
|
||||
finally:
|
||||
handle.remove()
|
||||
# The same instance can decode again after the failure.
|
||||
chunks: list[torch.Tensor] = []
|
||||
vae.decode_with_chunks(z, on_chunk=chunks.append)
|
||||
torch.testing.assert_close(torch.cat(chunks, 2), vae.decode(z).sample, rtol=0, atol=0)
|
||||
|
||||
|
||||
def test_chunked_decode_rejects_spatial_tiling(vae):
|
||||
vae.enable_tiling(tile_sample_min_height=2, tile_sample_min_width=2)
|
||||
with pytest.raises(ValueError, match="spatial tiling"):
|
||||
vae.decode_with_chunks(torch.zeros(1, 2, 2, 2, 2), on_chunk=Mock())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rank", [0, 1])
|
||||
@pytest.mark.parametrize("fail_callback", [False, True])
|
||||
def test_spatial_callback_ownership_and_bounded_retention(monkeypatch, rank, fail_callback):
|
||||
# Isolate the temporal loop from halo kernels; weakrefs detect retention of
|
||||
# decoded GPU-sized tensors even after the consumer has failed.
|
||||
monkeypatch.setattr(wan_spatial_shard, "install_wan_spatial_shard_decode", lambda *args, **kwargs: None)
|
||||
monkeypatch.setattr(wan_spatial_shard, "_rank_world", lambda group: (rank, 2))
|
||||
references: list[weakref.ReferenceType[torch.Tensor]] = []
|
||||
|
||||
def decode(x, **kwargs):
|
||||
assert sum(ref() is not None for ref in references) <= 1
|
||||
chunk = x.clone()
|
||||
references.append(weakref.ref(chunk))
|
||||
return chunk
|
||||
|
||||
vae = SimpleNamespace(
|
||||
config=SimpleNamespace(patch_size=None),
|
||||
clear_cache=Mock(),
|
||||
post_quant_conv=lambda z: z,
|
||||
decoder=decode,
|
||||
_feat_map=[],
|
||||
)
|
||||
callback = Mock(side_effect=RuntimeError("consumer failed") if fail_callback else None)
|
||||
z = torch.zeros(1, 3, 6, 2, 2)
|
||||
if rank == 0 and fail_callback:
|
||||
with pytest.raises(RuntimeError, match="consumer failed"):
|
||||
wan_spatial_shard.spatial_shard_decode(vae, z, group=None, on_chunk=callback)
|
||||
else:
|
||||
assert wan_spatial_shard.spatial_shard_decode(vae, z, group=None, on_chunk=callback) is None
|
||||
assert len(references) == z.shape[2]
|
||||
assert callback.call_count == (0 if rank else 1 if fail_callback else z.shape[2])
|
||||
assert vae.clear_cache.call_count == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rank", [0, 1])
|
||||
@torch.no_grad()
|
||||
def test_distributed_small_latent_callback_ownership(vae, monkeypatch, rank):
|
||||
vae.is_distributed_enabled = lambda: True
|
||||
vae.distributed_executor = SimpleNamespace(group=None)
|
||||
monkeypatch.setattr(torch.distributed, "get_rank", lambda **kwargs: rank)
|
||||
callback = Mock()
|
||||
vae.decode_with_chunks(torch.zeros(1, 2, 2, 2, 2), on_chunk=callback)
|
||||
assert callback.call_count == (2 if rank == 0 else 0)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", ["spatial_shard_height", "spatial_shard_width", "tile"])
|
||||
def test_distributed_chunked_routing(monkeypatch, mode):
|
||||
vae = DistributedAutoencoderKLWan.__new__(DistributedAutoencoderKLWan)
|
||||
torch.nn.Module.__init__(vae)
|
||||
vae.use_tiling = True
|
||||
vae.use_slicing = False
|
||||
vae.tile_sample_min_height = vae.tile_sample_min_width = 2
|
||||
vae.spatial_compression_ratio = 2
|
||||
vae.distributed_executor = SimpleNamespace(group=None, parallel_mode=mode, parallel_size=2)
|
||||
monkeypatch.setattr(vae, "is_distributed_enabled", lambda: True)
|
||||
monkeypatch.setattr(torch.distributed, "get_world_size", lambda **kwargs: 2)
|
||||
decode = Mock()
|
||||
monkeypatch.setattr(wan_spatial_shard, "spatial_shard_decode", decode)
|
||||
callback = Mock()
|
||||
z = torch.zeros(1, 2, 2, 2, 2)
|
||||
if mode == "tile":
|
||||
with pytest.raises(ValueError, match="require spatial-shard"):
|
||||
vae.decode_with_chunks(z, on_chunk=callback)
|
||||
decode.assert_not_called()
|
||||
else:
|
||||
assert vae.decode_with_chunks(z, on_chunk=callback) is None
|
||||
decode.assert_called_once_with(
|
||||
vae, z, group=None, return_dict=True, split_dim=mode.removeprefix("spatial_shard_"), on_chunk=callback
|
||||
)
|
||||
@@ -1,5 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Shared test helpers for diffusion LoRA tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -26,15 +26,39 @@ class DummyBaseLayerWithLoRA(torch.nn.Module):
|
||||
tuple[list[torch.Tensor | None] | torch.Tensor, list[torch.Tensor | None] | torch.Tensor]
|
||||
] = []
|
||||
self.reset_calls: int = 0
|
||||
self.suspend_calls: int = 0
|
||||
self.resume_calls: int = 0
|
||||
self.active_slices: tuple[bool, ...] = ()
|
||||
self.suspended_slices: tuple[bool, ...] | None = None
|
||||
self.create_calls: int = 0
|
||||
|
||||
def set_lora(self, index: int, lora_a, lora_b):
|
||||
assert index == 0
|
||||
self.set_calls.append((lora_a, lora_b))
|
||||
if isinstance(lora_b, list):
|
||||
self.active_slices = tuple(b is not None for b in lora_b)
|
||||
else:
|
||||
self.active_slices = (True,)
|
||||
self.suspended_slices = None
|
||||
|
||||
def reset_lora(self, index: int):
|
||||
assert index == 0
|
||||
self.reset_calls += 1
|
||||
self.active_slices = ()
|
||||
self.suspended_slices = None
|
||||
|
||||
def suspend_lora(self) -> None:
|
||||
if self.suspended_slices is not None:
|
||||
return
|
||||
self.suspended_slices = self.active_slices
|
||||
self.active_slices = (False,) * len(self.active_slices)
|
||||
self.suspend_calls += 1
|
||||
|
||||
def resume_lora(self) -> None:
|
||||
if self.suspended_slices is not None:
|
||||
self.active_slices = self.suspended_slices
|
||||
self.suspended_slices = None
|
||||
self.resume_calls += 1
|
||||
|
||||
def create_lora_weights(self, max_loras, lora_config, model_config):
|
||||
self.create_calls += 1
|
||||
|
||||
@@ -30,14 +30,38 @@ class _DummyLoRALayer:
|
||||
tuple[list[torch.Tensor | None] | torch.Tensor, list[torch.Tensor | None] | torch.Tensor]
|
||||
] = []
|
||||
self.reset_calls: int = 0
|
||||
self.suspend_calls: int = 0
|
||||
self.resume_calls: int = 0
|
||||
self.active_slices: tuple[bool, ...] = ()
|
||||
self.suspended_slices: tuple[bool, ...] | None = None
|
||||
|
||||
def set_lora(self, index: int, lora_a, lora_b):
|
||||
assert index == 0
|
||||
self.set_calls.append((lora_a, lora_b))
|
||||
if isinstance(lora_b, list):
|
||||
self.active_slices = tuple(b is not None for b in lora_b)
|
||||
else:
|
||||
self.active_slices = (True,)
|
||||
self.suspended_slices = None
|
||||
|
||||
def reset_lora(self, index: int):
|
||||
assert index == 0
|
||||
self.reset_calls += 1
|
||||
self.active_slices = ()
|
||||
self.suspended_slices = None
|
||||
|
||||
def suspend_lora(self) -> None:
|
||||
if self.suspended_slices is not None:
|
||||
return
|
||||
self.suspended_slices = self.active_slices
|
||||
self.active_slices = (False,) * len(self.active_slices)
|
||||
self.suspend_calls += 1
|
||||
|
||||
def resume_lora(self) -> None:
|
||||
if self.suspended_slices is not None:
|
||||
self.active_slices = self.suspended_slices
|
||||
self.suspended_slices = None
|
||||
self.resume_calls += 1
|
||||
|
||||
|
||||
# Aliases for backward compatibility within this file
|
||||
@@ -723,3 +747,104 @@ def test_lora_manager_discovers_unet_component(monkeypatch):
|
||||
assert "unet.down_block.proj" in manager._lora_modules
|
||||
# Verify the module was actually replaced in the tree (not just recorded)
|
||||
assert isinstance(pipeline.unet.down_block.proj, _DummyBaseLayerWithLoRA)
|
||||
|
||||
|
||||
def _suspend_harness(monkeypatch, adapter_id: int = 7, rank: int = 2):
|
||||
"""Manager wired to a single dummy layer, ready to activate `adapter_id`."""
|
||||
import vllm_omni.diffusion.lora.manager as manager_mod
|
||||
|
||||
monkeypatch.setattr(manager_mod, "BaseLayerWithLoRA", _DummyBaseLayerWithLoRA)
|
||||
|
||||
lora_model = _DummyLM(rank=rank)
|
||||
manager = DiffusionLoRAManager(
|
||||
pipeline=_DummyPipeline(),
|
||||
device=torch.device("cpu"),
|
||||
dtype=torch.bfloat16,
|
||||
)
|
||||
monkeypatch.setattr(manager, "_load_adapter", lambda _req: (lora_model, type("PH", (), {"r": rank})()))
|
||||
manager._registered_adapters = {adapter_id: lora_model}
|
||||
manager._lora_modules = {"transformer.foo": lora_model.transformer.foo}
|
||||
return manager, lora_model.transformer.foo
|
||||
|
||||
|
||||
def test_reactivating_same_adapter_resumes_without_rebinding(monkeypatch):
|
||||
"""activate -> deactivate -> activate at the same scale must re-arm the
|
||||
saved mask instead of re-uploading every layer."""
|
||||
adapter_id = 7
|
||||
req = _dummy_lora_request(adapter_id)
|
||||
manager, layer = _suspend_harness(monkeypatch, adapter_id)
|
||||
|
||||
manager.set_active_adapter(req, lora_scale=0.5)
|
||||
assert len(layer.set_calls) == 1
|
||||
assert layer.active_slices == (True,)
|
||||
|
||||
manager.set_active_adapter(None)
|
||||
assert manager._suspended_adapter_id == adapter_id
|
||||
assert layer.suspend_calls == 1
|
||||
assert layer.active_slices == (False,)
|
||||
# Suspending must not tear the upload down.
|
||||
assert layer.reset_calls == 0
|
||||
|
||||
manager.set_active_adapter(req, lora_scale=0.5)
|
||||
assert layer.resume_calls == 1
|
||||
assert len(layer.set_calls) == 1, "resume must not rebind"
|
||||
assert layer.active_slices == (True,)
|
||||
assert manager._active_adapter_id == adapter_id
|
||||
assert manager._suspended_adapter_id is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("second_scale", [0.5, 0.25])
|
||||
def test_scale_or_adapter_change_forces_rebind(monkeypatch, second_scale):
|
||||
"""A different scale, or a different adapter, must take the full bind
|
||||
path rather than re-arming a stale mask."""
|
||||
adapter_id = 7
|
||||
manager, layer = _suspend_harness(monkeypatch, adapter_id)
|
||||
|
||||
manager.set_active_adapter(_dummy_lora_request(adapter_id), lora_scale=0.5)
|
||||
manager.set_active_adapter(None)
|
||||
assert manager._suspended_adapter_id == adapter_id
|
||||
|
||||
# Same id at a new scale, or a different id entirely.
|
||||
other_id = adapter_id if second_scale != 0.5 else adapter_id + 1
|
||||
if other_id != adapter_id:
|
||||
manager._registered_adapters[other_id] = manager._registered_adapters[adapter_id]
|
||||
|
||||
manager.set_active_adapter(_dummy_lora_request(other_id), lora_scale=second_scale)
|
||||
assert len(layer.set_calls) == 2, "must rebind"
|
||||
assert manager._suspended_adapter_id is None
|
||||
assert manager._active_adapter_id == other_id
|
||||
|
||||
|
||||
def test_partial_packed_mask_survives_suspend_resume(monkeypatch):
|
||||
"""A packed layer where only some slices carry LoRA must come back with
|
||||
the same mask, not an all-True one."""
|
||||
adapter_id = 7
|
||||
manager, layer = _suspend_harness(monkeypatch, adapter_id)
|
||||
|
||||
# Emulate a packed bind that left slice 1 empty.
|
||||
layer.set_lora(0, [torch.ones(2, 2), None], [torch.ones(2, 2), None])
|
||||
manager._active_adapter_id = adapter_id
|
||||
manager._update_adapter_scale(adapter_id, 0.5)
|
||||
assert layer.active_slices == (True, False)
|
||||
|
||||
manager.set_active_adapter(None)
|
||||
assert layer.active_slices == (False, False)
|
||||
|
||||
manager.set_active_adapter(_dummy_lora_request(adapter_id), lora_scale=0.5)
|
||||
assert layer.active_slices == (True, False), "mask must survive unchanged"
|
||||
|
||||
|
||||
def test_removing_suspended_adapter_drops_the_upload(monkeypatch):
|
||||
"""A removed adapter can never be resumed, so its weights must not stay
|
||||
in the stacked buffers."""
|
||||
adapter_id = 7
|
||||
manager, layer = _suspend_harness(monkeypatch, adapter_id)
|
||||
|
||||
manager.set_active_adapter(_dummy_lora_request(adapter_id), lora_scale=0.5)
|
||||
manager.set_active_adapter(None)
|
||||
assert manager._suspended_adapter_id == adapter_id
|
||||
|
||||
manager.remove_adapter(adapter_id)
|
||||
assert manager._suspended_adapter_id is None
|
||||
assert layer.reset_calls == 1, "the upload must be torn down"
|
||||
assert layer.suspended_slices is None
|
||||
@@ -13,7 +13,6 @@ from unittest.mock import MagicMock
|
||||
import pytest
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from huggingface_hub import snapshot_download
|
||||
from safetensors.torch import save_file
|
||||
from vllm.config.load import LoadConfig
|
||||
|
||||
@@ -32,6 +31,7 @@ from vllm_omni.diffusion.models.helios import HeliosPipeline
|
||||
from vllm_omni.diffusion.models.host_weight_contract import FinalLayoutModelContract
|
||||
from vllm_omni.diffusion.registry import initialize_model
|
||||
from vllm_omni.quantization.component_config import ComponentQuantizationConfig
|
||||
from vllm_omni.transformers_utils.repo_utils import hf_api
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.diffusion, pytest.mark.cpu]
|
||||
|
||||
@@ -41,7 +41,7 @@ model_path = "hf-internal-testing/tiny-helios-modular-pipe"
|
||||
@pytest.fixture(scope="module")
|
||||
def prefetch_helios_model():
|
||||
"""Downloads the tiny helios model prior to running a test."""
|
||||
snapshot_download(model_path)
|
||||
hf_api().snapshot_download(model_path)
|
||||
|
||||
|
||||
@pytest.fixture(scope="function")
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import contextlib
|
||||
|
||||
@@ -14,10 +14,10 @@ pytestmark = [pytest.mark.core_model, pytest.mark.diffusion, pytest.mark.cpu]
|
||||
def test_prefetch_subfolders_propagates_revision(monkeypatch):
|
||||
calls = []
|
||||
|
||||
def fake_snapshot_download(**kwargs):
|
||||
def fake_snapshot_download(self, **kwargs):
|
||||
calls.append(kwargs)
|
||||
|
||||
monkeypatch.setattr(huggingface_hub, "snapshot_download", fake_snapshot_download)
|
||||
monkeypatch.setattr(huggingface_hub.HfApi, "snapshot_download", fake_snapshot_download)
|
||||
monkeypatch.setattr(hub_prefetch, "_repo_prefetch_lock", lambda _model: contextlib.nullcontext())
|
||||
|
||||
hub_prefetch.prefetch_subfolders(
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm_omni.diffusion.models.utils import make_attention_mask
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu, pytest.mark.diffusion]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("seq_lengths", [[16], [16, 16]])
|
||||
def test_attention_mask_is_skipped_for_dense_batch(seq_lengths):
|
||||
hidden_states = torch.empty(len(seq_lengths), 16, 64)
|
||||
|
||||
assert make_attention_mask(hidden_states, seq_lengths) is None
|
||||
|
||||
|
||||
def test_attention_mask_preserves_variable_length_padding():
|
||||
hidden_states = torch.empty(2, 16, 64)
|
||||
|
||||
attention_mask = make_attention_mask(hidden_states, [16, 12])
|
||||
|
||||
expected = torch.tensor(
|
||||
[
|
||||
[True] * 16,
|
||||
[True] * 12 + [False] * 4,
|
||||
]
|
||||
)
|
||||
torch.testing.assert_close(attention_mask, expected)
|
||||
@@ -0,0 +1,96 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""L1 tests for checkpoint-to-pipeline routing of Boogu-Image Turbo."""
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu, pytest.mark.diffusion]
|
||||
|
||||
|
||||
def test_turbo_registry_entry_loads_the_turbo_class():
|
||||
from vllm_omni.diffusion.models.boogu_image import BooguImageTurboPipeline
|
||||
from vllm_omni.diffusion.registry import DiffusionModelRegistry
|
||||
|
||||
assert DiffusionModelRegistry._try_load_model_cls("BooguImageTurboPipeline") is BooguImageTurboPipeline
|
||||
|
||||
|
||||
def test_turbo_entry_disables_request_batching():
|
||||
from vllm_omni.diffusion.models.boogu_image import BooguImagePipeline, BooguImageTurboPipeline
|
||||
|
||||
assert BooguImagePipeline.supports_request_batch
|
||||
assert not BooguImageTurboPipeline.supports_request_batch
|
||||
|
||||
|
||||
def test_turbo_process_funcs_resolve_to_the_shared_boogu_helpers():
|
||||
from vllm_omni.diffusion.models import boogu_image
|
||||
from vllm_omni.diffusion.registry import _DIFFUSION_POST_PROCESS_FUNCS, _DIFFUSION_PRE_PROCESS_FUNCS
|
||||
|
||||
module = boogu_image.pipeline_boogu_image
|
||||
for funcs in (_DIFFUSION_PRE_PROCESS_FUNCS, _DIFFUSION_POST_PROCESS_FUNCS):
|
||||
name = funcs["BooguImageTurboPipeline"]
|
||||
assert name == funcs["BooguImagePipeline"]
|
||||
assert callable(getattr(module, name))
|
||||
|
||||
|
||||
def test_turbo_inherits_the_base_multimodal_metadata():
|
||||
from vllm_omni.diffusion.model_metadata import get_diffusion_model_metadata
|
||||
|
||||
metadata = get_diffusion_model_metadata("BooguImageTurboPipeline")
|
||||
|
||||
assert metadata == get_diffusion_model_metadata("BooguImagePipeline")
|
||||
assert metadata.supports_multimodal_inputs
|
||||
assert metadata.max_multimodal_image_inputs == 1
|
||||
|
||||
|
||||
def test_turbo_model_index_resolves_and_enriches(tmp_path):
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig, resolve_model_class_name
|
||||
|
||||
(tmp_path / "model_index.json").write_text(
|
||||
json.dumps({"_class_name": "BooguImageTurboPipeline"}),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
assert resolve_model_class_name(str(tmp_path)) == "BooguImageTurboPipeline"
|
||||
|
||||
config = OmniDiffusionConfig(model=str(tmp_path))
|
||||
config.enrich_config()
|
||||
|
||||
assert config.model_class_name == "BooguImageTurboPipeline"
|
||||
assert config.supports_multimodal_inputs
|
||||
assert config.max_multimodal_image_inputs == 1
|
||||
|
||||
|
||||
def test_edit_turbo_override_selects_the_turbo_class(tmp_path):
|
||||
"""Edit-Turbo publishes ``BooguImagePipeline``; ``--model-class-name`` must win."""
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.registry import DiffusionModelRegistry
|
||||
|
||||
(tmp_path / "model_index.json").write_text(
|
||||
json.dumps({"_class_name": "BooguImagePipeline"}),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
config = OmniDiffusionConfig(model=str(tmp_path), model_class_name="BooguImageTurboPipeline")
|
||||
config.enrich_config()
|
||||
|
||||
assert config.model_class_name == "BooguImageTurboPipeline"
|
||||
assert DiffusionModelRegistry._try_load_model_cls(config.model_class_name)._is_turbo
|
||||
|
||||
|
||||
def test_edit_turbo_without_override_keeps_the_base_class(tmp_path):
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.registry import DiffusionModelRegistry
|
||||
|
||||
(tmp_path / "model_index.json").write_text(
|
||||
json.dumps({"_class_name": "BooguImagePipeline"}),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
config = OmniDiffusionConfig(model=str(tmp_path))
|
||||
config.enrich_config()
|
||||
|
||||
assert config.model_class_name == "BooguImagePipeline"
|
||||
assert not DiffusionModelRegistry._try_load_model_cls(config.model_class_name)._is_turbo
|
||||
@@ -2401,6 +2401,42 @@ def test_forward_transfer_runs_multichunk_overlap_path(
|
||||
torch.testing.assert_close(captured["targets"][1][:, :, 0], torch.full((1, 3, 16, 16), -0.2))
|
||||
|
||||
|
||||
def test_forward_transfer_non_output_rank_uses_canonical_envelope(
|
||||
make_cosmos3_pipeline,
|
||||
sequential_cfg_parallel,
|
||||
) -> None:
|
||||
pipeline = make_cosmos3_pipeline()
|
||||
pipeline.vae.distributed_executor = SimpleNamespace(rank=1)
|
||||
pipeline.vae.is_distributed_enabled = lambda: True
|
||||
pipeline._transfer_bucket_size = lambda sp, source_hw: (16, 16, "1,1")
|
||||
pipeline._format_and_tokenize_prompts = lambda *args, **kwargs: (_ids(2), _mask(), _ids(1), _mask())
|
||||
pipeline._set_flow_shift = lambda *_args, **_kwargs: None
|
||||
decoded = torch.zeros(1, 3, 1, 16, 16)
|
||||
pipeline._decode_latents = lambda latents: decoded
|
||||
|
||||
request = SimpleNamespace(
|
||||
prompts=[{"prompt": "transfer", "modalities": ["video"]}],
|
||||
sampling_params=make_sampling_params(
|
||||
height=16,
|
||||
width=16,
|
||||
num_inference_steps=1,
|
||||
guidance_scale=1.0,
|
||||
extra_args={
|
||||
"edge": {"control": torch.zeros(3, 1, 16, 16, dtype=torch.uint8)},
|
||||
"max_frames": 1,
|
||||
"num_video_frames_per_chunk": 1,
|
||||
},
|
||||
),
|
||||
)
|
||||
|
||||
output = pipeline.forward(request)
|
||||
|
||||
assert set(output.output) == {"payload", "metadata"}
|
||||
assert set(output.output["payload"]) == {"video"}
|
||||
torch.testing.assert_close(output.output["payload"]["video"], decoded)
|
||||
assert output.output["metadata"] == {"video": {"fps": 24.0}}
|
||||
|
||||
|
||||
def test_diffuse_keeps_paired_cfg_when_cache_dit_active(make_cosmos3_pipeline) -> None:
|
||||
"""With cache-dit active the uncond pass is kept even outside the guidance
|
||||
interval (so cache-dit's has_separate_cfg parity stays in phase), and the
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -81,9 +81,8 @@ def test_from_config_loads_local_diffusers_component(tmp_path, monkeypatch: pyte
|
||||
|
||||
|
||||
def test_from_config_downloads_component_from_hf_repo(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
import huggingface_hub
|
||||
|
||||
from vllm_omni.diffusion.models.cosmos3 import sound_tokenizer
|
||||
from vllm_omni.transformers_utils import repo_utils
|
||||
|
||||
cache_dir = tmp_path / "hf"
|
||||
_write_component(cache_dir, checkpoint_name=DIFFUSERS_SOUND_TOKENIZER_CHECKPOINT_NAME)
|
||||
@@ -95,7 +94,7 @@ def test_from_config_downloads_component_from_hf_repo(tmp_path, monkeypatch: pyt
|
||||
calls.append((repo_id, revision, allow_patterns))
|
||||
return str(cache_dir)
|
||||
|
||||
monkeypatch.setattr(huggingface_hub, "snapshot_download", fake_snapshot_download)
|
||||
monkeypatch.setattr(repo_utils.hf_api(), "snapshot_download", fake_snapshot_download)
|
||||
|
||||
sound_tokenizer.Cosmos3SoundTokenizer.from_config(
|
||||
SimpleNamespace(
|
||||
|
||||
@@ -383,6 +383,117 @@ def test_transformer_sharding_offload_and_patch_round_trip_contracts() -> None:
|
||||
)
|
||||
|
||||
|
||||
def test_gen_sp_plan_auto_pads_hidden_states_and_rope_together() -> None:
|
||||
from vllm_omni.diffusion.models.cosmos3.transformer_cosmos3 import Cosmos3VFMTransformer
|
||||
|
||||
prepare_plan = Cosmos3VFMTransformer._sp_plan["gen_sp_prepare"]
|
||||
assert set(prepare_plan) == {0, 1, 2}
|
||||
assert all(spec.auto_pad for spec in prepare_plan.values())
|
||||
assert [prepare_plan[index].split_dim for index in range(3)] == [1, 1, 1]
|
||||
|
||||
|
||||
def test_gen_sp_prepare_resets_branch_local_padding_metadata() -> None:
|
||||
from vllm_omni.diffusion.forward_context import ForwardContext, override_forward_context
|
||||
from vllm_omni.diffusion.models.cosmos3.transformer_cosmos3 import Cosmos3GenSPPrepare
|
||||
|
||||
ctx = ForwardContext(sp_padding_size=1, sp_original_seq_len=12121)
|
||||
hidden = torch.zeros(1, 4, 8)
|
||||
rope = torch.zeros(1, 4, 1, 2)
|
||||
with override_forward_context(ctx):
|
||||
output = Cosmos3GenSPPrepare()(hidden, rope, rope)
|
||||
|
||||
assert output[0] is hidden
|
||||
assert output[1] is rope
|
||||
assert output[2] is rope
|
||||
assert ctx.sp_padding_size == 0
|
||||
assert ctx.sp_original_seq_len is None
|
||||
|
||||
|
||||
def test_sp_attention_masks_padded_gen_and_joint_und_keys() -> None:
|
||||
from vllm_omni.diffusion.forward_context import ForwardContext, override_forward_context
|
||||
from vllm_omni.diffusion.models.cosmos3.transformer_cosmos3 import Cosmos3CrossAttention
|
||||
|
||||
class RecordingAttention(nn.Module):
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
self.metadata: Any | None = None
|
||||
|
||||
def forward(self, query, key, value, metadata):
|
||||
del key, value
|
||||
self.metadata = metadata
|
||||
return query
|
||||
|
||||
module = object.__new__(Cosmos3CrossAttention)
|
||||
nn.Module.__init__(module)
|
||||
module.num_heads_local = 2
|
||||
module.head_dim = 4
|
||||
recording_attention = RecordingAttention()
|
||||
module.attn = recording_attention
|
||||
|
||||
q = torch.zeros(1, 2, 2, 4)
|
||||
k = torch.zeros_like(q)
|
||||
v = torch.zeros_like(q)
|
||||
k_und = torch.zeros(1, 3, 2, 4)
|
||||
v_und = torch.zeros_like(k_und)
|
||||
ctx = ForwardContext(sp_padding_size=1, sp_original_seq_len=3)
|
||||
with override_forward_context(ctx):
|
||||
output = module._forward_sp(q, k, v, k_und, v_und)
|
||||
|
||||
assert output.shape == (1, 2, 8)
|
||||
assert recording_attention.metadata is not None
|
||||
assert recording_attention.metadata.attn_mask.tolist() == [[True, True, True, False]]
|
||||
assert recording_attention.metadata.joint_attn_mask.tolist() == [[True, True, True]]
|
||||
|
||||
|
||||
def test_ulysses_2d_mask_uses_key_length_with_kv_only_joint_context(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
|
||||
from vllm_omni.diffusion.attention.parallel import ulysses
|
||||
|
||||
def fake_all_to_all(
|
||||
_group: object,
|
||||
tensor: torch.Tensor,
|
||||
_scatter_idx: int,
|
||||
_gather_idx: int,
|
||||
_use_sync: bool,
|
||||
) -> torch.Tensor:
|
||||
return torch.cat([tensor, tensor], dim=1)[:, :, :1]
|
||||
|
||||
monkeypatch.setattr(ulysses.SeqAllToAll4D, "apply", staticmethod(fake_all_to_all))
|
||||
strategy = ulysses.UlyssesParallelAttention(
|
||||
sp_group=SimpleNamespace(
|
||||
ulysses_group=object(),
|
||||
ulysses_world_size=2,
|
||||
ulysses_rank=0,
|
||||
ring_world_size=1,
|
||||
),
|
||||
scatter_idx=2,
|
||||
gather_idx=1,
|
||||
use_sync=False,
|
||||
)
|
||||
query = torch.zeros(1, 2, 2, 4)
|
||||
key = torch.zeros_like(query)
|
||||
value = torch.zeros_like(query)
|
||||
joint_query = torch.zeros(1, 0, 2, 4)
|
||||
joint_key = torch.zeros(1, 3, 2, 4)
|
||||
metadata = AttentionMetadata(
|
||||
attn_mask=torch.tensor([[True, True, True, False]]),
|
||||
joint_attn_mask=torch.ones(1, 3, dtype=torch.bool),
|
||||
joint_query=joint_query,
|
||||
joint_key=joint_key,
|
||||
joint_value=torch.zeros_like(joint_key),
|
||||
joint_strategy="front",
|
||||
)
|
||||
|
||||
query_out, key_out, _, metadata_out, _ = strategy.pre_attention(query, key, value, metadata)
|
||||
|
||||
assert query_out.shape[1] == 4
|
||||
assert key_out.shape[1] == 7
|
||||
assert metadata_out is not None
|
||||
assert metadata_out.attn_mask.tolist() == [[True, True, True, True, True, True, False]]
|
||||
|
||||
|
||||
def test_forward_returns_video_prediction(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
from vllm_omni.diffusion.models.cosmos3 import transformer_cosmos3
|
||||
|
||||
@@ -721,7 +832,7 @@ def test_forward_returns_video_plus_optional_modality_predictions(
|
||||
assert [tuple(tensor.shape) for tensor in output] == expected_shapes
|
||||
|
||||
|
||||
def test_forward_with_sound_ulysses_error_mentions_combined_sequence(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
def test_forward_with_sound_odd_sequence_uses_auto_padding_contract(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
import vllm_omni.diffusion.models.cosmos3.transformer_cosmos3 as cosmos3_module
|
||||
|
||||
model = cosmos3_module.Cosmos3VFMTransformer(
|
||||
@@ -732,16 +843,17 @@ def test_forward_with_sound_ulysses_error_mentions_combined_sequence(monkeypatch
|
||||
)
|
||||
monkeypatch.setattr(cosmos3_module, "_get_ulysses_state", lambda: (2, 0, None))
|
||||
|
||||
with pytest.raises(ValueError, match=r"GEN sequence length \(3 = video tokens 2 \+ sound tokens 1\)"):
|
||||
model(
|
||||
hidden_states=torch.zeros(1, 2, 1, 1, 2),
|
||||
timestep=torch.tensor([1.0]),
|
||||
text_ids=torch.tensor([[1, 2]], dtype=torch.long),
|
||||
text_mask=torch.ones(1, 2, dtype=torch.long),
|
||||
video_shape=(1, 1, 2),
|
||||
fps=24.0,
|
||||
sound_latents=torch.zeros(1, 3, 1),
|
||||
)
|
||||
output = model(
|
||||
hidden_states=torch.zeros(1, 2, 1, 1, 2),
|
||||
timestep=torch.tensor([1.0]),
|
||||
text_ids=torch.tensor([[1, 2]], dtype=torch.long),
|
||||
text_mask=torch.ones(1, 2, dtype=torch.long),
|
||||
video_shape=(1, 1, 2),
|
||||
fps=24.0,
|
||||
sound_latents=torch.zeros(1, 3, 1),
|
||||
)
|
||||
|
||||
assert [tuple(tensor.shape) for tensor in output] == [(1, 2, 1, 1, 2), (1, 3, 1)]
|
||||
|
||||
|
||||
def test_sound_latent_frames_padded_for_sequence_parallel(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""The request's seed must reach GR00T's flow-matching noise.
|
||||
|
||||
The runner builds ``sampling_params.generator`` from ``sampling_params.seed``, the pipeline hands
|
||||
that generator to the policy, and the action head draws its initial noise from it, so the same
|
||||
seed reproduces the same action chunk and different seeds give independent ones. These tests pin
|
||||
both ends of that plumbing.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
import torch
|
||||
from torch import nn
|
||||
from transformers.feature_extraction_utils import BatchFeature
|
||||
|
||||
from vllm_omni.diffusion.models.gr00t import pipeline_gr00t
|
||||
from vllm_omni.diffusion.models.gr00t.configs.gr00t_n1d7 import Gr00tN1d7Config
|
||||
from vllm_omni.diffusion.models.gr00t.modeling.gr00t_n1d7 import Gr00tN1d7ActionHead
|
||||
from vllm_omni.diffusion.models.gr00t.pipeline_gr00t import Gr00tN1d7Pipeline
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
ROBOT_OBS = {
|
||||
"images": {"cam": np.zeros((1, 1, 8, 8, 3), dtype=np.uint8)},
|
||||
"state": {"joint": np.zeros((1, 1, 2), dtype=np.float32)},
|
||||
"prompt": "pick the cube",
|
||||
}
|
||||
|
||||
|
||||
class _OptionsRecordingPolicy:
|
||||
"""Stand-in for ``Gr00tPolicy``; the pipeline only needs ``language_key`` and ``get_action``."""
|
||||
|
||||
def __init__(self, *, model_path: str, embodiment_tag: str, device: str, strict: bool) -> None:
|
||||
del model_path, embodiment_tag, device, strict # the pipeline's constructor contract; unused here
|
||||
self.language_key = "annotation.language.language_instruction"
|
||||
self.seen_options: dict[str, object] | None = None
|
||||
|
||||
def get_action(self, obs: dict[str, object], options: dict[str, object] | None = None):
|
||||
self.seen_options = options
|
||||
return {"arm": np.zeros((1, 2, 2), dtype=np.float32)}, {}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def pipeline(monkeypatch) -> Gr00tN1d7Pipeline:
|
||||
monkeypatch.setattr(pipeline_gr00t, "Gr00tPolicy", _OptionsRecordingPolicy)
|
||||
od_config = SimpleNamespace(
|
||||
model="nvidia/GR00T-N1.7-3B",
|
||||
model_config={"embodiment_tag": "LIBERO_PANDA", "strict": False},
|
||||
custom_pipeline_args={},
|
||||
)
|
||||
return Gr00tN1d7Pipeline(od_config=od_config)
|
||||
|
||||
|
||||
def _request(**sampling_kwargs) -> OmniDiffusionRequest:
|
||||
return OmniDiffusionRequest(
|
||||
prompt="pick",
|
||||
request_id="req",
|
||||
sampling_params=OmniDiffusionSamplingParams(extra_args={"robot_obs": ROBOT_OBS}, **sampling_kwargs),
|
||||
)
|
||||
|
||||
|
||||
def test_runner_generator_is_passed_through_untouched(pipeline):
|
||||
"""In serving the runner has already built ``sampling_params.generator``; the head must get that object."""
|
||||
generator = torch.Generator().manual_seed(99)
|
||||
|
||||
assert pipeline.forward(_request(generator=generator)).error is None
|
||||
|
||||
assert pipeline.policy.seen_options["generator"] is generator
|
||||
|
||||
|
||||
def test_seed_without_generator_builds_one_on_the_pipeline_device(pipeline):
|
||||
"""Callers that bypass the runner (direct use, tests) still get the seed honoured."""
|
||||
pipeline.forward(_request(seed=1234))
|
||||
|
||||
generator = pipeline.policy.seen_options["generator"]
|
||||
assert isinstance(generator, torch.Generator)
|
||||
assert generator.initial_seed() == 1234
|
||||
assert generator.device.type == pipeline.device
|
||||
|
||||
|
||||
def test_auto_assigned_seed_reaches_the_head(pipeline):
|
||||
"""``OmniDiffusionRequest`` seeds every request, so the head is never left on the global RNG."""
|
||||
req = _request()
|
||||
assert req.sampling_params.seed is not None
|
||||
|
||||
pipeline.forward(req)
|
||||
|
||||
assert pipeline.policy.seen_options["generator"].initial_seed() == req.sampling_params.seed
|
||||
|
||||
|
||||
def _captured_warnings(monkeypatch) -> list[tuple]:
|
||||
"""vLLM loggers do not propagate to the root logger, so ``caplog`` cannot see them; record calls instead."""
|
||||
captured: list[tuple] = []
|
||||
monkeypatch.setattr(pipeline_gr00t.logger, "warning", lambda *args, **kwargs: captured.append(args))
|
||||
return captured
|
||||
|
||||
|
||||
def test_unexpected_generator_form_warns_and_falls_back_to_the_seed(pipeline, monkeypatch):
|
||||
"""GR00T draws one noise tensor per request, so a list of several generators cannot be honoured."""
|
||||
warnings = _captured_warnings(monkeypatch)
|
||||
generators = [torch.Generator().manual_seed(1), torch.Generator().manual_seed(2)]
|
||||
|
||||
pipeline.forward(_request(generator=generators, seed=7))
|
||||
|
||||
assert len(warnings) == 1
|
||||
assert "torch.Generator" in warnings[0][0]
|
||||
assert pipeline.policy.seen_options["generator"].initial_seed() == 7
|
||||
|
||||
|
||||
def test_unexpected_generator_form_without_a_seed_warns_and_leaves_the_global_rng(pipeline, monkeypatch):
|
||||
warnings = _captured_warnings(monkeypatch)
|
||||
generators = [torch.Generator().manual_seed(1), torch.Generator().manual_seed(2)]
|
||||
|
||||
pipeline.forward(_request(generator=generators))
|
||||
|
||||
assert len(warnings) == 1
|
||||
assert pipeline.policy.seen_options is None
|
||||
|
||||
|
||||
def _noise_only_head(action_horizon: int, action_dim: int) -> Gr00tN1d7ActionHead:
|
||||
"""An action head whose single denoising step is the identity, so ``action_pred`` is the initial noise."""
|
||||
config = Gr00tN1d7Config(
|
||||
max_action_dim=action_dim,
|
||||
action_horizon=action_horizon,
|
||||
num_inference_timesteps=1,
|
||||
add_pos_embed=False,
|
||||
use_alternate_vl_dit=False,
|
||||
)
|
||||
head = Gr00tN1d7ActionHead.__new__(Gr00tN1d7ActionHead)
|
||||
nn.Module.__init__(head)
|
||||
head.config = config
|
||||
head.action_dim = config.max_action_dim
|
||||
head.action_horizon = config.action_horizon
|
||||
head.num_inference_timesteps = config.num_inference_timesteps
|
||||
head.num_timestep_buckets = config.num_timestep_buckets
|
||||
head.action_encoder = lambda actions, timesteps, embodiment_id: actions
|
||||
head.model = lambda hidden_states, encoder_hidden_states, timestep: hidden_states
|
||||
head.action_decoder = lambda hidden_states, embodiment_id: torch.zeros_like(hidden_states)
|
||||
return head
|
||||
|
||||
|
||||
def _predict(head: Gr00tN1d7ActionHead, options) -> torch.Tensor:
|
||||
batch, seq, dim = 2, 3, head.action_dim
|
||||
return head.get_action_with_features(
|
||||
backbone_features=torch.zeros(batch, seq, dim),
|
||||
state_features=torch.zeros(batch, 1, dim),
|
||||
embodiment_id=torch.zeros(batch, dtype=torch.long),
|
||||
backbone_output=BatchFeature(data={}),
|
||||
action_input=BatchFeature(data={}),
|
||||
options=options,
|
||||
)["action_pred"]
|
||||
|
||||
|
||||
def test_head_draws_its_noise_from_the_request_generator():
|
||||
head = _noise_only_head(action_horizon=4, action_dim=3)
|
||||
expected = torch.randn(2, 4, 3, generator=torch.Generator().manual_seed(5))
|
||||
|
||||
assert torch.equal(_predict(head, {"generator": torch.Generator().manual_seed(5)}), expected)
|
||||
assert not torch.equal(_predict(head, {"generator": torch.Generator().manual_seed(6)}), expected)
|
||||
|
||||
|
||||
def test_head_without_generator_stays_on_the_global_rng():
|
||||
"""Upstream Isaac-GR00T parity: no generator means a bare ``torch.randn`` on the global RNG."""
|
||||
head = _noise_only_head(action_horizon=4, action_dim=3)
|
||||
|
||||
torch.manual_seed(5)
|
||||
expected = torch.randn(2, 4, 3)
|
||||
torch.manual_seed(5)
|
||||
|
||||
assert torch.equal(_predict(head, None), expected)
|
||||
@@ -1,4 +1,8 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
@@ -12,12 +16,12 @@ pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
class FakeGr00tPolicy:
|
||||
instances = []
|
||||
instances: list["FakeGr00tPolicy"] = []
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
self.kwargs = kwargs
|
||||
self.reset_calls = 0
|
||||
self.seen_obs = None
|
||||
self.seen_obs: dict[str, Any] | None = None
|
||||
self.embodiment_tag = SimpleNamespace(value="fake_embodiment")
|
||||
self.language_key = "annotation.language.language_instruction"
|
||||
self.modality_configs = {
|
||||
@@ -40,7 +44,7 @@ class FakeGr00tPolicy:
|
||||
)
|
||||
FakeGr00tPolicy.instances.append(self)
|
||||
|
||||
def get_action(self, obs):
|
||||
def get_action(self, obs, options=None):
|
||||
self.seen_obs = obs
|
||||
return {
|
||||
"arm": np.array([[[1.0, 2.0]]], dtype=np.float64),
|
||||
@@ -107,6 +111,7 @@ def test_forward_returns_dict_actions_in_output():
|
||||
assert actions["arm"].dtype == np.float32
|
||||
np.testing.assert_allclose(actions["arm"], np.array([[[1.0, 2.0]]], dtype=np.float32))
|
||||
policy = FakeGr00tPolicy.instances[0]
|
||||
assert policy.seen_obs is not None
|
||||
assert "video" in policy.seen_obs
|
||||
assert policy.seen_obs["language"] == {"annotation.language.language_instruction": [["pick the cube"]]}
|
||||
assert "images" not in policy.seen_obs
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""GR00T-N1.7 eval image transform: chosen from ``processor_config.json`` and bit-exact with Isaac-GR00T.
|
||||
|
||||
``GOLDEN`` holds sha256 digests of the ``(C, H, W)`` uint8 output of Isaac-GR00T's own eval transform
|
||||
(``build_image_transformations_albumentations(...)[1]`` applied through ``apply_with_replay``) for the
|
||||
synthetic frames built below, at Isaac-GR00T 51d4c89 / albumentations 1.4.18 / opencv 5.0.0.93. The frame
|
||||
generators are integer-only so they are identical on every platform.
|
||||
|
||||
Regenerating a digest needs Isaac-GR00T installed, whose transformers pin conflicts with this repo's, so it
|
||||
cannot run here: in an Isaac-GR00T environment push each ``synthetic_frames()`` frame through that transform
|
||||
with ``letter_box_transform`` False and True and hash the output with ``digest()``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
import torch
|
||||
import torchvision.transforms.v2 as transforms
|
||||
|
||||
from vllm_omni.diffusion.models.gr00t.modeling import processing_gr00t_n1d7 as processing
|
||||
from vllm_omni.diffusion.models.gr00t.modeling.processing_gr00t_n1d7 import (
|
||||
AlbumentationsEvalImageTransform,
|
||||
Gr00tN1d7Processor,
|
||||
LetterBoxTransform,
|
||||
_build_eval_image_transform,
|
||||
_fractional_center_crop,
|
||||
_smallest_edge_resize,
|
||||
)
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
# nvidia/GR00T-N1.7-3B and nvidia/GR00T-N1.7-DROID both ship exactly these processor_kwargs.
|
||||
TARGET, CROP, EDGE, FRACTION = [256, 256], [230, 230], 256, 0.95
|
||||
MODALITY_CONFIGS = {
|
||||
"new_embodiment": {
|
||||
"video": {"delta_indices": [0], "modality_keys": ["cam"]},
|
||||
"state": {"delta_indices": [0], "modality_keys": ["joint"]},
|
||||
"action": {"delta_indices": [0, 1], "modality_keys": ["joint"]},
|
||||
}
|
||||
}
|
||||
|
||||
# Isaac-GR00T eval transform output for synthetic_frames(); key = "<frame>|letterbox=<flag>".
|
||||
GOLDEN: dict[str, tuple[tuple[int, int, int], str]] = {
|
||||
"gradient_256x256|letterbox=False": (
|
||||
(3, 256, 256),
|
||||
"4e90a1a3c49539b3648aad752bba59af452bd7231e5712e871ab941cbea1d715",
|
||||
),
|
||||
"checker_256x256|letterbox=False": (
|
||||
(3, 256, 256),
|
||||
"d2225b94efea5ab3f1c3e6dbae52b7afa3e0f7172d5de24439a2e729ab56080c",
|
||||
),
|
||||
"noise_256x256|letterbox=False": (
|
||||
(3, 256, 256),
|
||||
"a427ae3b84ebcc6e87470c79c0e45cf684770d6e31158a49f8736685e0da72c6",
|
||||
),
|
||||
"noise_512x768|letterbox=False": (
|
||||
(3, 256, 383),
|
||||
"45bc3a309f3d06c3f31051911bc8a544ff3f067b023b999dd9c2b7e6029ecc93",
|
||||
),
|
||||
"gradient_256x256|letterbox=True": (
|
||||
(3, 256, 256),
|
||||
"4e90a1a3c49539b3648aad752bba59af452bd7231e5712e871ab941cbea1d715",
|
||||
),
|
||||
"checker_256x256|letterbox=True": (
|
||||
(3, 256, 256),
|
||||
"d2225b94efea5ab3f1c3e6dbae52b7afa3e0f7172d5de24439a2e729ab56080c",
|
||||
),
|
||||
"noise_256x256|letterbox=True": ((3, 256, 256), "a427ae3b84ebcc6e87470c79c0e45cf684770d6e31158a49f8736685e0da72c6"),
|
||||
"noise_512x768|letterbox=True": ((3, 256, 256), "52a3db185e6ee4f00617b87711dd198b8f2e2ad53865713d34e56225a4ec61a2"),
|
||||
}
|
||||
|
||||
|
||||
def _hash_noise(height: int, width: int, seed: int) -> np.ndarray:
|
||||
"""Integer-only pseudo-noise (murmur-style mixing on uint32); no RNG or float, so identical everywhere."""
|
||||
ys, xs = np.mgrid[0:height, 0:width].astype(np.uint32)
|
||||
channels = []
|
||||
for channel in range(3):
|
||||
v = xs * np.uint32(73856093) ^ ys * np.uint32(19349663) ^ np.uint32((seed * 3 + channel) * 83492791)
|
||||
v ^= v >> np.uint32(13)
|
||||
v *= np.uint32(0x5BD1E995)
|
||||
v ^= v >> np.uint32(15)
|
||||
channels.append((v & np.uint32(0xFF)).astype(np.uint8))
|
||||
return np.stack(channels, axis=-1)
|
||||
|
||||
|
||||
def synthetic_frames() -> dict[str, np.ndarray]:
|
||||
"""Deterministic HWC uint8 RGB frames: smooth, hard-edged, noisy, and a non-square noisy one.
|
||||
|
||||
The non-square frame is 512x768 so both INTER_AREA downscales (2x without letterbox, 3x with it)
|
||||
are integer factors, which OpenCV computes with exact integer sums: the goldens do not depend on
|
||||
the CPU architecture. The 243->256 upscale is a fixed-point bilinear on uint8, also exact.
|
||||
"""
|
||||
ys, xs = np.mgrid[0:256, 0:256].astype(np.int64)
|
||||
frames = {
|
||||
"gradient_256x256": np.stack([xs % 256, ys % 256, (xs + ys) // 2 % 256], axis=-1).astype(np.uint8),
|
||||
"checker_256x256": np.stack(
|
||||
[((ys // 16 + xs // 16) % 2) * 255, ((ys // 8 + xs // 8) % 2) * 255, ((ys // 32) % 2) * 255],
|
||||
axis=-1,
|
||||
).astype(np.uint8),
|
||||
"noise_256x256": _hash_noise(256, 256, seed=1),
|
||||
"noise_512x768": _hash_noise(512, 768, seed=2),
|
||||
}
|
||||
return frames
|
||||
|
||||
|
||||
def digest(tensor: torch.Tensor) -> str:
|
||||
return hashlib.sha256(np.ascontiguousarray(tensor.numpy()).tobytes()).hexdigest()
|
||||
|
||||
|
||||
class _FakeTokenizer:
|
||||
padding_side = "right"
|
||||
|
||||
|
||||
class _FakeVlmProcessor:
|
||||
"""The two attributes ``Gr00tN1d7Processor`` and its collator touch on the Qwen3-VL processor."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.tokenizer = _FakeTokenizer()
|
||||
|
||||
def apply_chat_template(self, *_args: object, **_kwargs: object) -> str:
|
||||
return "<prompt>"
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def fake_vlm_processor(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""The real Qwen3-VL processor is a gated download and irrelevant to the image pipeline."""
|
||||
monkeypatch.setattr(processing, "build_processor", lambda _model_name, _kwargs: _FakeVlmProcessor())
|
||||
|
||||
|
||||
def _processor(**kwargs) -> Gr00tN1d7Processor:
|
||||
return Gr00tN1d7Processor(
|
||||
modality_configs=MODALITY_CONFIGS, image_crop_size=CROP, image_target_size=TARGET, **kwargs
|
||||
)
|
||||
|
||||
|
||||
def _has_letterbox(compose: transforms.Compose) -> bool:
|
||||
return any(isinstance(step, LetterBoxTransform) for step in compose.transforms)
|
||||
|
||||
|
||||
def test_processor_builds_the_pipeline_named_by_processor_config():
|
||||
albumentations = _processor(use_albumentations=True, shortest_image_edge=EDGE, crop_fraction=FRACTION)
|
||||
transform = albumentations.eval_image_transform
|
||||
assert isinstance(transform, AlbumentationsEvalImageTransform)
|
||||
assert (transform.max_size, transform.fraction, transform.letter_box_transform) == (EDGE, FRACTION, False)
|
||||
assert albumentations.use_albumentations is True
|
||||
|
||||
torchvision = _processor(use_albumentations=False)
|
||||
assert isinstance(torchvision.eval_image_transform, transforms.Compose)
|
||||
assert not _has_letterbox(torchvision.eval_image_transform)
|
||||
|
||||
letterboxed = _processor(use_albumentations=False, letter_box_transform=True)
|
||||
assert _has_letterbox(letterboxed.eval_image_transform)
|
||||
assert _processor(use_albumentations=True, letter_box_transform=True).eval_image_transform.letter_box_transform
|
||||
|
||||
|
||||
def test_legacy_config_without_the_flags_keeps_the_torchvision_recipe():
|
||||
"""Checkpoints predating the flags behave like Isaac-GR00T's defaults; training-only keys stay ignored."""
|
||||
processor = _processor(state_dropout_prob=0.2, extra_augmentation_config=None)
|
||||
assert processor.use_albumentations is False
|
||||
assert processor.letter_box_transform is False
|
||||
assert isinstance(processor.eval_image_transform, transforms.Compose)
|
||||
assert not _has_letterbox(processor.eval_image_transform)
|
||||
|
||||
|
||||
def test_fraction_and_max_size_fall_back_like_isaac_gr00t():
|
||||
transform = _build_eval_image_transform(
|
||||
TARGET, CROP, shortest_image_edge=None, crop_fraction=None, use_albumentations=True
|
||||
)
|
||||
assert isinstance(transform, AlbumentationsEvalImageTransform)
|
||||
assert transform.fraction == CROP[0] / TARGET[0]
|
||||
assert transform.max_size == TARGET[0]
|
||||
with pytest.raises(ValueError, match="crop_fraction is None"):
|
||||
_build_eval_image_transform(TARGET, None, crop_fraction=None, use_albumentations=True)
|
||||
|
||||
|
||||
def test_geometry_follows_isaac_rounding_rules():
|
||||
frame = _hash_noise(540, 640, seed=3)
|
||||
resized = _smallest_edge_resize(frame, EDGE)
|
||||
assert resized.shape == (256, 303, 3) # round() per dimension, shortest edge -> 256
|
||||
cropped = _fractional_center_crop(resized, FRACTION)
|
||||
assert cropped.shape == (243, 287, 3) # int() truncation: 243.2 -> 243, 287.85 -> 287
|
||||
assert np.array_equal(cropped, resized[6:249, 8:295]) # (256-243)//2, (303-287)//2
|
||||
square = frame[:256, :256]
|
||||
assert _smallest_edge_resize(square, EDGE) is square # scale == 1.0 is a no-op, not a resample
|
||||
|
||||
|
||||
@pytest.mark.parametrize("case", sorted(GOLDEN))
|
||||
def test_albumentations_recipe_is_bit_exact_with_isaac_gr00t(case: str):
|
||||
name, flag = case.split("|letterbox=")
|
||||
transform = _build_eval_image_transform(
|
||||
TARGET,
|
||||
CROP,
|
||||
shortest_image_edge=EDGE,
|
||||
crop_fraction=FRACTION,
|
||||
use_albumentations=True,
|
||||
letter_box_transform=(flag == "True"),
|
||||
)
|
||||
out = transform(synthetic_frames()[name])
|
||||
expected_shape, expected_digest = GOLDEN[case]
|
||||
assert out.dtype == torch.uint8
|
||||
assert tuple(out.shape) == expected_shape
|
||||
assert digest(out) == expected_digest
|
||||
|
||||
|
||||
def test_letterbox_is_gated_on_both_recipes():
|
||||
frame = _hash_noise(540, 640, seed=3)
|
||||
|
||||
def albumentations(letterbox: bool) -> torch.Tensor:
|
||||
return _build_eval_image_transform(
|
||||
TARGET,
|
||||
CROP,
|
||||
shortest_image_edge=EDGE,
|
||||
crop_fraction=FRACTION,
|
||||
use_albumentations=True,
|
||||
letter_box_transform=letterbox,
|
||||
)(frame)
|
||||
|
||||
padded, unpadded = albumentations(True), albumentations(False)
|
||||
assert tuple(padded.shape) == (3, 256, 256) # 540x640 -> 640x640 -> 256x256 -> 243x243 -> 256x256
|
||||
assert tuple(unpadded.shape) == (3, 256, 302) # aspect preserved: 256x303 -> 243x287 -> 256x302
|
||||
|
||||
tv_padded = _build_eval_image_transform(TARGET, CROP, use_albumentations=False, letter_box_transform=True)(frame)
|
||||
tv_unpadded = _build_eval_image_transform(TARGET, CROP, use_albumentations=False, letter_box_transform=False)(frame)
|
||||
assert tuple(tv_padded.shape) == tuple(tv_unpadded.shape) == (3, 256, 256)
|
||||
assert not torch.equal(tv_padded, tv_unpadded)
|
||||
assert (tv_padded[:, :2, :] == 0).all() and not (tv_unpadded[:, :2, :] == 0).all() # black bars only when gated
|
||||
|
||||
|
||||
def test_albumentations_recipe_rejects_frames_outside_the_contract():
|
||||
transform = _build_eval_image_transform(TARGET, CROP, use_albumentations=True)
|
||||
with pytest.raises(ValueError, match="HWC uint8"):
|
||||
transform(np.zeros((256, 256, 3), dtype=np.float32))
|
||||
with pytest.raises(ValueError, match="HWC uint8"):
|
||||
transform(np.zeros((3, 256, 256), dtype=np.uint8))
|
||||
with pytest.raises(ValueError, match="HWC uint8"):
|
||||
transform(np.zeros((256, 256), dtype=np.uint8))
|
||||
|
||||
|
||||
def test_get_vlm_inputs_runs_the_selected_transform_per_frame():
|
||||
processor = _processor(use_albumentations=True, shortest_image_edge=EDGE, crop_fraction=FRACTION)
|
||||
frames = np.stack([_hash_noise(540, 640, seed=3)] * 2) # (T, H, W, C) like policy.py hands over
|
||||
vlm_inputs = processor._get_vlm_inputs(
|
||||
image_keys=["cam"],
|
||||
images={"cam": frames},
|
||||
masks=None,
|
||||
image_transform=processor.eval_image_transform,
|
||||
language="x",
|
||||
)
|
||||
images = vlm_inputs["vlm_content"]["images"]
|
||||
assert len(images) == 2
|
||||
assert all(img.size == (302, 256) for img in images) # PIL reports (W, H); no letterbox for this checkpoint
|
||||
|
||||
|
||||
def test_flags_round_trip_through_save_pretrained_and_from_pretrained(tmp_path):
|
||||
saved = _processor(
|
||||
use_albumentations=True, letter_box_transform=True, shortest_image_edge=EDGE, crop_fraction=FRACTION
|
||||
)
|
||||
saved.save_pretrained(tmp_path)
|
||||
kwargs = json.loads((tmp_path / "processor_config.json").read_text())["processor_kwargs"]
|
||||
assert kwargs["use_albumentations"] is True
|
||||
assert kwargs["letter_box_transform"] is True
|
||||
|
||||
loaded = Gr00tN1d7Processor.from_pretrained(tmp_path)
|
||||
assert loaded.use_albumentations is True
|
||||
assert loaded.letter_box_transform is True
|
||||
assert isinstance(loaded.eval_image_transform, AlbumentationsEvalImageTransform)
|
||||
assert loaded.eval_image_transform.letter_box_transform is True
|
||||
|
||||
|
||||
def test_from_pretrained_defaults_missing_flags_to_isaac_gr00t_defaults(tmp_path):
|
||||
(tmp_path / "processor_config.json").write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"processor_class": "Gr00tN1d7Processor",
|
||||
"processor_kwargs": {
|
||||
"modality_configs": MODALITY_CONFIGS,
|
||||
"image_crop_size": CROP,
|
||||
"image_target_size": TARGET,
|
||||
},
|
||||
}
|
||||
)
|
||||
)
|
||||
(tmp_path / "statistics.json").write_text("{}")
|
||||
loaded = Gr00tN1d7Processor.from_pretrained(tmp_path)
|
||||
assert loaded.use_albumentations is False
|
||||
assert loaded.letter_box_transform is False
|
||||
assert isinstance(loaded.eval_image_transform, transforms.Compose)
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
import json
|
||||
from dataclasses import replace
|
||||
from threading import Lock
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
@@ -500,6 +501,32 @@ def test_ltx25_checkpoint_selects_distilled_two_stage_profile(tmp_path, monkeypa
|
||||
assert pipe.pipeline_recipe is LTX25_DISTILLED_TWO_STAGE_RECIPE
|
||||
|
||||
|
||||
def test_ltx_runtime_profiles_phase_methods_separately(monkeypatch):
|
||||
pipe = object.__new__(LTX2DistilledTwoStagePipeline)
|
||||
pipe.enable_diffusion_pipeline_profiler = True
|
||||
pipe._profiler_lock = Lock()
|
||||
pipe._stage_durations = {}
|
||||
monkeypatch.setattr(ltx2_runtime.current_omni_platform, "is_available", lambda: False)
|
||||
|
||||
with pipe._profile_phase_method("run_phase", "generate_lowres"):
|
||||
pass
|
||||
with pipe._profile_phase_method("run_phase", "refine"):
|
||||
pass
|
||||
with pipe._profile_phase_method("decode_phase"):
|
||||
pass
|
||||
output = DiffusionOutput()
|
||||
assert pipe._attach_profiled_stage_durations(output) is output
|
||||
|
||||
expected_keys = {
|
||||
"LTX2DistilledTwoStagePipeline.generate_lowres.run_phase",
|
||||
"LTX2DistilledTwoStagePipeline.refine.run_phase",
|
||||
"LTX2DistilledTwoStagePipeline.decode_phase",
|
||||
}
|
||||
assert set(pipe.stage_durations) == expected_keys
|
||||
assert set(output.stage_durations) == expected_keys
|
||||
assert all(duration >= 0.0 for duration in pipe.stage_durations.values())
|
||||
|
||||
|
||||
def test_ltx25_full_config_enrichment_uses_selected_transformer_subfolder(tmp_path):
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig
|
||||
|
||||
|
||||
@@ -103,7 +103,7 @@ def test_prepare_audio_latents_samples_directly_in_packed_token_space():
|
||||
torch.testing.assert_close(actual, expected, rtol=0, atol=0)
|
||||
|
||||
|
||||
def test_prepare_audio_latents_pads_generated_dummy_length_for_sp():
|
||||
def test_prepare_audio_latents_pads_short_audio_for_sp():
|
||||
pipeline = _make_pipeline(LTX2Pipeline, sequence_parallel_size=2)
|
||||
|
||||
latents, original_num_frames, padded_num_frames = pipeline.prepare_audio_latents(
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Unit tests for LTX guidance and forward-parallel behavior."""
|
||||
|
||||
@@ -85,14 +85,14 @@ class TestCFGParallelHelpers:
|
||||
|
||||
LTX_GUIDANCE_EXECUTOR.validate_guidance_world_size(plan, guidance_world_size)
|
||||
|
||||
def test_guidance_parallel_dummy_warms_full_guidance_plan(self, monkeypatch):
|
||||
def test_guidance_parallel_preserves_full_guidance_plan(self, monkeypatch):
|
||||
from vllm_omni.diffusion.models.ltx2 import ltx2_runtime
|
||||
from vllm_omni.diffusion.models.ltx2.ltx2_recipes import LTX23_ONE_STAGE_RECIPE
|
||||
from vllm_omni.diffusion.models.ltx2.pipeline_ltx2 import LTX2Pipeline
|
||||
|
||||
monkeypatch.setattr(ltx2_runtime, "get_guidance_parallel_world_size", lambda: 2)
|
||||
pipe = object.__new__(LTX2Pipeline)
|
||||
req = SimpleNamespace(is_dummy_run=lambda: True)
|
||||
req = SimpleNamespace()
|
||||
request_inputs = SimpleNamespace(guidance=LTX23_ONE_STAGE_RECIPE.request_guidance)
|
||||
|
||||
guidance_parallel_ready = pipe._setup_forward_runtime(req, request_inputs, attention_kwargs=None)
|
||||
|
||||
@@ -10,6 +10,7 @@ from dataclasses import replace
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
import huggingface_hub
|
||||
import numpy as np
|
||||
import pytest
|
||||
import torch
|
||||
@@ -175,7 +176,19 @@ def test_ltx_device_uint8_output_rejects_invalid_contract(video, error):
|
||||
_prepare_ltx2_video_output(video, do_normalize=True)
|
||||
|
||||
|
||||
def test_ltx_profiler_covers_video_output_transport(tmp_path, monkeypatch):
|
||||
@pytest.mark.parametrize(
|
||||
"parallel_config",
|
||||
[
|
||||
None,
|
||||
SimpleNamespace(ulysses_degree=4),
|
||||
SimpleNamespace(tensor_parallel_size=2),
|
||||
SimpleNamespace(use_hsdp=True, hsdp_shard_size=2),
|
||||
SimpleNamespace(ulysses_degree=2, tensor_parallel_size=2),
|
||||
SimpleNamespace(ulysses_degree=2, use_hsdp=True, hsdp_shard_size=2),
|
||||
],
|
||||
ids=["single", "ulysses", "tp", "hsdp", "tp-ulysses", "hsdp-ulysses"],
|
||||
)
|
||||
def test_ltx_supported_parallel_configs_keep_output_profiling(tmp_path, monkeypatch, parallel_config):
|
||||
from vllm_omni.diffusion.models.ltx2 import ltx2_runtime
|
||||
|
||||
(tmp_path / "model_index.json").write_text(json.dumps({"vocoder": ["ltx2", "LTX2Vocoder"]}))
|
||||
@@ -193,7 +206,13 @@ def test_ltx_profiler_covers_video_output_transport(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(ltx2_runtime, "initialize_pipeline_components", stub_components)
|
||||
monkeypatch.setattr(LTXRuntime, "setup_diffusion_pipeline_profiler", capture_profiler_setup)
|
||||
|
||||
LTX2Pipeline(od_config=SimpleNamespace(model=str(tmp_path), enable_diffusion_pipeline_profiler=False))
|
||||
LTX2Pipeline(
|
||||
od_config=SimpleNamespace(
|
||||
model=str(tmp_path),
|
||||
parallel_config=parallel_config,
|
||||
enable_diffusion_pipeline_profiler=False,
|
||||
)
|
||||
)
|
||||
|
||||
assert "video_processor.postprocess_video" in profiler_setup["profiler_targets"]
|
||||
assert "_prepare_video_output_for_transport" in profiler_setup["profiler_targets"]
|
||||
@@ -284,11 +303,11 @@ def test_ltx_artifact_uses_source_revision_and_hub_fallback(
|
||||
filename = "ltx-sidecar.safetensors"
|
||||
calls = []
|
||||
|
||||
def fake_download(**kwargs):
|
||||
def fake_download(self, **kwargs):
|
||||
calls.append(kwargs)
|
||||
return "/cache/ltx-sidecar.safetensors"
|
||||
|
||||
monkeypatch.setattr(ltx2_components, "hf_hub_download", fake_download)
|
||||
monkeypatch.setattr(huggingface_hub.HfApi, "hf_hub_download", fake_download)
|
||||
|
||||
assert (
|
||||
resolve_ltx_artifact(
|
||||
@@ -313,7 +332,9 @@ def test_ltx_artifact_prefers_model_root(tmp_path, monkeypatch):
|
||||
filename = "ltx-sidecar.safetensors"
|
||||
expected = tmp_path / filename
|
||||
expected.write_bytes(b"sidecar")
|
||||
monkeypatch.setattr(ltx2_components, "hf_hub_download", lambda **_kwargs: pytest.fail("unexpected Hub lookup"))
|
||||
monkeypatch.setattr(
|
||||
huggingface_hub.HfApi, "hf_hub_download", lambda *_args, **_kwargs: pytest.fail("unexpected Hub lookup")
|
||||
)
|
||||
|
||||
assert resolve_ltx_artifact(
|
||||
str(tmp_path),
|
||||
@@ -327,11 +348,11 @@ def test_ltx_artifact_prefers_model_root(tmp_path, monkeypatch):
|
||||
def test_ltx_artifact_local_model_missing_sidecar_falls_back_to_hub(tmp_path, monkeypatch):
|
||||
calls = []
|
||||
|
||||
def fake_download(**kwargs):
|
||||
def fake_download(self, **kwargs):
|
||||
calls.append(kwargs)
|
||||
return "/cache/ltx-sidecar.safetensors"
|
||||
|
||||
monkeypatch.setattr(ltx2_components, "hf_hub_download", fake_download)
|
||||
monkeypatch.setattr(huggingface_hub.HfApi, "hf_hub_download", fake_download)
|
||||
|
||||
assert (
|
||||
resolve_ltx_artifact(
|
||||
@@ -383,14 +404,42 @@ def test_ltx_checkpoint_validation_rejects_mismatched_scheduler_metadata(expecte
|
||||
)
|
||||
|
||||
|
||||
def test_ltx_rejects_advanced_uaa_before_component_initialization():
|
||||
@pytest.mark.parametrize(
|
||||
"pipeline_cls",
|
||||
[
|
||||
LTX2Pipeline,
|
||||
LTX2DistilledOneStagePipeline,
|
||||
LTX2TwoStagePipeline,
|
||||
LTX2DistilledTwoStagePipeline,
|
||||
LTX2T2VDMD2Pipeline,
|
||||
LTX2I2VDMD2Pipeline,
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
("parallel_config", "error"),
|
||||
[
|
||||
(SimpleNamespace(ulysses_mode="advanced_uaa"), "does not support ulysses_mode='advanced_uaa'"),
|
||||
(SimpleNamespace(ring_degree=2), "pure Ulysses sequence parallelism only"),
|
||||
(SimpleNamespace(ulysses_degree=2, ring_degree=2), "pure Ulysses sequence parallelism only"),
|
||||
(SimpleNamespace(allgather_degree=2), "pure Ulysses sequence parallelism only"),
|
||||
],
|
||||
ids=["advanced-uaa", "ring", "hybrid", "allgather-kv"],
|
||||
)
|
||||
def test_ltx_rejects_unsupported_sp_before_component_initialization(pipeline_cls, parallel_config, error, monkeypatch):
|
||||
from vllm_omni.diffusion.models.ltx2 import ltx2_runtime
|
||||
|
||||
def unexpected_model_access(*_args, **_kwargs):
|
||||
pytest.fail("Unsupported SP must be rejected before accessing model files or initializing components")
|
||||
|
||||
monkeypatch.setattr(ltx2_runtime, "detect_ltx_model_version", unexpected_model_access)
|
||||
monkeypatch.setattr(ltx2_runtime, "initialize_pipeline_components", unexpected_model_access)
|
||||
od_config = SimpleNamespace(
|
||||
model="unused",
|
||||
parallel_config=SimpleNamespace(ulysses_mode="advanced_uaa"),
|
||||
parallel_config=parallel_config,
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="does not support ulysses_mode='advanced_uaa'"):
|
||||
LTX2Pipeline(od_config=od_config)
|
||||
with pytest.raises(ValueError, match=error):
|
||||
pipeline_cls(od_config=od_config)
|
||||
|
||||
|
||||
def test_ltx23_checkpoint_selects_version_specific_one_stage_profile(tmp_path, monkeypatch):
|
||||
@@ -1409,39 +1458,19 @@ def test_ltx_distilled_forward_rejects_fixed_recipe_overrides(direct_kwargs, sam
|
||||
pipeline.forward(req, **direct_kwargs)
|
||||
|
||||
|
||||
def test_ltx_distilled_dummy_run_uses_fixed_recipe_values():
|
||||
from vllm_omni.diffusion.request import DUMMY_DIFFUSION_REQUEST_ID, OmniDiffusionRequest
|
||||
from vllm_omni.diffusion.worker.request_batch import DiffusionRequestBatch
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
|
||||
|
||||
req = DiffusionRequestBatch(
|
||||
[
|
||||
OmniDiffusionRequest(
|
||||
prompt="dummy run",
|
||||
sampling_params=OmniDiffusionSamplingParams(
|
||||
height=512,
|
||||
width=512,
|
||||
num_frames=LTX2DistilledPipeline.dummy_run_num_frames,
|
||||
num_inference_steps=1,
|
||||
guidance_scale=0.0,
|
||||
),
|
||||
request_id=DUMMY_DIFFUSION_REQUEST_ID,
|
||||
)
|
||||
]
|
||||
)
|
||||
pipeline = _make_ltx_request_pipe(LTX2DistilledPipeline)
|
||||
seen = {}
|
||||
|
||||
def fake_run_recipe(_req, request_inputs, **_kwargs):
|
||||
seen["request_inputs"] = request_inputs
|
||||
return "dummy-output"
|
||||
|
||||
object.__setattr__(pipeline, "_run_recipe", fake_run_recipe)
|
||||
|
||||
assert pipeline.forward(req) == "dummy-output"
|
||||
assert seen["request_inputs"].num_frames == 1
|
||||
assert seen["request_inputs"].num_inference_steps == 8
|
||||
assert seen["request_inputs"].guidance == LTXGuidanceSpec.positive_only()
|
||||
@pytest.mark.parametrize(
|
||||
"pipeline_cls",
|
||||
[
|
||||
LTX2Pipeline,
|
||||
LTX2DistilledOneStagePipeline,
|
||||
LTX2TwoStagePipeline,
|
||||
LTX2DistilledTwoStagePipeline,
|
||||
LTX2T2VDMD2Pipeline,
|
||||
LTX2I2VDMD2Pipeline,
|
||||
],
|
||||
)
|
||||
def test_ltx_pipelines_disable_startup_dummy_run(pipeline_cls):
|
||||
assert pipeline_cls.dummy_run_num_frames == 0
|
||||
|
||||
|
||||
def test_ltx_custom_sigmas_bypass_scheduler_shifting():
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import timedelta
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
import torch.nn.functional as F
|
||||
|
||||
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
|
||||
from vllm_omni.diffusion.models.ltx2.ltx2_sequence_parallel import (
|
||||
LTX2VideoToAudioParallelAttention,
|
||||
)
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.diffusion, pytest.mark.cpu]
|
||||
|
||||
|
||||
def _run_video_to_audio_parity(rank: int, world_size: int, master_port: int) -> None:
|
||||
dist.init_process_group(
|
||||
"gloo",
|
||||
init_method=f"tcp://127.0.0.1:{master_port}",
|
||||
rank=rank,
|
||||
world_size=world_size,
|
||||
timeout=timedelta(seconds=60),
|
||||
)
|
||||
try:
|
||||
# Non-contiguous SP subgroups match TP-fastest rank ordering. Different
|
||||
# seeds across groups catch collectives that accidentally use WORLD.
|
||||
group_count = world_size // 2
|
||||
ulysses_group = dist.group.WORLD
|
||||
if group_count > 1:
|
||||
for offset in range(group_count):
|
||||
ranks = list(range(offset, world_size, group_count))
|
||||
group = dist.new_group(ranks)
|
||||
if rank in ranks:
|
||||
ulysses_group = group
|
||||
ulysses_rank = dist.get_rank(ulysses_group)
|
||||
sp_group = SimpleNamespace(
|
||||
ring_world_size=1,
|
||||
ulysses_group=ulysses_group,
|
||||
ulysses_world_size=2,
|
||||
ulysses_rank=ulysses_rank,
|
||||
)
|
||||
strategy = LTX2VideoToAudioParallelAttention(sp_group)
|
||||
|
||||
for batch_size, masked in [(1, False), (2, True)]:
|
||||
torch.manual_seed(17 + rank % group_count)
|
||||
query = torch.randn(batch_size, 3, 4, 8)
|
||||
global_key = torch.randn(batch_size, 6, 4, 8)
|
||||
global_value = torch.randn(batch_size, 6, 4, 8)
|
||||
key = global_key.chunk(2, dim=1)[ulysses_rank].contiguous()
|
||||
value = global_value.chunk(2, dim=1)[ulysses_rank].contiguous()
|
||||
mask = None
|
||||
if masked:
|
||||
mask = torch.ones(batch_size, 1, 1, 6, dtype=torch.bool)
|
||||
mask[0, ..., -1] = False
|
||||
mask[1, ..., -2:] = False
|
||||
metadata = AttentionMetadata(attn_mask=mask) if masked else None
|
||||
|
||||
local_query, local_key, local_value, local_metadata, ctx = strategy.pre_attention(
|
||||
query, key, value, metadata
|
||||
)
|
||||
assert local_metadata is metadata
|
||||
local_output = F.scaled_dot_product_attention(
|
||||
local_query.transpose(1, 2),
|
||||
local_key.transpose(1, 2),
|
||||
local_value.transpose(1, 2),
|
||||
attn_mask=local_metadata.attn_mask if local_metadata is not None else None,
|
||||
).transpose(1, 2)
|
||||
actual = strategy.post_attention(local_output, ctx)
|
||||
expected = F.scaled_dot_product_attention(
|
||||
query.transpose(1, 2),
|
||||
global_key.transpose(1, 2),
|
||||
global_value.transpose(1, 2),
|
||||
attn_mask=mask,
|
||||
).transpose(1, 2)
|
||||
|
||||
torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-6)
|
||||
finally:
|
||||
dist.destroy_process_group()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("world_size", [2, 4], ids=["world", "subgroups"])
|
||||
def test_ltx_video_to_audio_sp_matches_replicated_attention(unused_tcp_port, world_size):
|
||||
torch.multiprocessing.spawn(
|
||||
_run_video_to_audio_parity,
|
||||
args=(world_size, unused_tcp_port),
|
||||
nprocs=world_size,
|
||||
)
|
||||
|
||||
|
||||
def test_ltx_video_to_audio_sp_rejects_ring_parallelism():
|
||||
sp_group = SimpleNamespace(ring_world_size=2)
|
||||
|
||||
with pytest.raises(NotImplementedError, match="ring_degree must be 1"):
|
||||
LTX2VideoToAudioParallelAttention(sp_group)
|
||||
@@ -141,16 +141,54 @@ def test_ltx_transformer_exposes_hsdp_shard_conditions_for_blocks():
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rope_type", ["interleaved", "split"])
|
||||
def test_ltx_sp_plan_shards_video_and_audio_timesteps_together(rope_type):
|
||||
root_plan = LTX2VideoTransformer3DModel._build_sp_plan(rope_type)[""]
|
||||
def test_ltx_sp_plan_only_shards_video_stream(rope_type):
|
||||
plan = LTX2VideoTransformer3DModel._build_sp_plan(rope_type)
|
||||
root_plan = plan[""]
|
||||
|
||||
video_timestep = root_plan["timestep"]
|
||||
audio_timestep = root_plan["audio_timestep"]
|
||||
assert set(root_plan) == {"hidden_states", "keyframes_mask", "timestep"}
|
||||
assert root_plan["hidden_states"].split_dim == 1
|
||||
assert root_plan["keyframes_mask"].split_dim == 1
|
||||
assert root_plan["timestep"].split_dim == 1
|
||||
assert root_plan["timestep"].expected_dims == 2
|
||||
assert not root_plan["timestep"].split_output
|
||||
assert set(plan) == {"", "rope", "cross_attn_rope", "proj_out"}
|
||||
|
||||
assert video_timestep.split_dim == audio_timestep.split_dim == 1
|
||||
assert video_timestep.expected_dims == audio_timestep.expected_dims == 2
|
||||
assert not video_timestep.split_output
|
||||
assert not audio_timestep.split_output
|
||||
|
||||
def test_ltx_attention_assigns_video_only_sp_modes(monkeypatch):
|
||||
modes = {}
|
||||
|
||||
class FakeAttention(nn.Module):
|
||||
def __init__(self, *, prefix, sequence_parallel_mode="local", **_kwargs):
|
||||
super().__init__()
|
||||
modes[prefix.rsplit(".", 1)[-1]] = sequence_parallel_mode
|
||||
|
||||
class FakeFeedForward(nn.Module):
|
||||
def __init__(self, *_args, **_kwargs):
|
||||
super().__init__()
|
||||
|
||||
monkeypatch.setattr(ltx2_transformer, "LTX2Attention", FakeAttention)
|
||||
monkeypatch.setattr(ltx2_transformer, "LTX2FeedForward", FakeFeedForward)
|
||||
|
||||
LTX2VideoTransformerBlock(
|
||||
dim=8,
|
||||
num_attention_heads=2,
|
||||
attention_head_dim=4,
|
||||
cross_attention_dim=8,
|
||||
audio_dim=8,
|
||||
audio_num_attention_heads=2,
|
||||
audio_attention_head_dim=4,
|
||||
audio_cross_attention_dim=8,
|
||||
prefix="transformer_blocks.0",
|
||||
)
|
||||
|
||||
assert modes == {
|
||||
"attn1": "video_self",
|
||||
"audio_attn1": "local",
|
||||
"attn2": "local",
|
||||
"audio_attn2": "local",
|
||||
"audio_to_video_attn": "local",
|
||||
"video_to_audio_attn": "video_to_audio",
|
||||
}
|
||||
|
||||
|
||||
def test_ltx_sp_keeps_cross_attention_key_padding_mask(monkeypatch):
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Full-transformer numeric parity for LTX Ulysses sequence parallelism.
|
||||
|
||||
This FP32/SDPA check verifies that Ulysses preserves the complete transformer
|
||||
mathematical path. It does not guarantee pixel-level E2E parity: production
|
||||
BF16 and compiled attention kernels can change rounding order, and diffusion
|
||||
can amplify that drift across denoising steps.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from tests.helpers.mark import hardware_test
|
||||
from vllm_omni.diffusion.config import set_current_diffusion_config
|
||||
from vllm_omni.diffusion.data import DiffusionParallelConfig, OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.distributed.parallel_state import (
|
||||
destroy_distributed_env,
|
||||
init_distributed_environment,
|
||||
initialize_model_parallel,
|
||||
)
|
||||
from vllm_omni.diffusion.distributed.sp_plan import SequenceParallelConfig
|
||||
from vllm_omni.diffusion.forward_context import get_forward_context, set_forward_context
|
||||
from vllm_omni.diffusion.hooks.sequence_parallel import apply_sequence_parallel
|
||||
from vllm_omni.diffusion.models.ltx2.ltx2_transformer import LTX2VideoTransformer3DModel
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.diffusion, pytest.mark.parallel]
|
||||
|
||||
_FP32_REL_L2 = 1e-5
|
||||
_TINY_CONFIG = {
|
||||
"in_channels": 4,
|
||||
"out_channels": 4,
|
||||
"num_attention_heads": 2,
|
||||
"attention_head_dim": 4,
|
||||
"cross_attention_dim": 8,
|
||||
"vae_scale_factors": (1, 1, 1),
|
||||
"pos_embed_max_pos": 4,
|
||||
"base_height": 2,
|
||||
"base_width": 2,
|
||||
"audio_in_channels": 4,
|
||||
"audio_out_channels": 4,
|
||||
"audio_num_attention_heads": 2,
|
||||
"audio_attention_head_dim": 4,
|
||||
"audio_cross_attention_dim": 8,
|
||||
"audio_scale_factor": 1,
|
||||
"audio_pos_embed_max_pos": 4,
|
||||
"audio_sampling_rate": 16,
|
||||
"audio_hop_length": 4,
|
||||
"num_layers": 1,
|
||||
"caption_channels": 8,
|
||||
"rope_type": "split",
|
||||
"use_prompt_embeddings": False,
|
||||
"use_keyframes_abs_pos_embedding": True,
|
||||
}
|
||||
|
||||
|
||||
def _relative_l2(actual: torch.Tensor, expected: torch.Tensor) -> float:
|
||||
return ((actual - expected).double().norm() / expected.double().norm()).item()
|
||||
|
||||
|
||||
def _omni_config(sp_size: int) -> OmniDiffusionConfig:
|
||||
return OmniDiffusionConfig.from_kwargs(
|
||||
model="test",
|
||||
dtype=torch.float32,
|
||||
parallel_config=DiffusionParallelConfig(
|
||||
pipeline_parallel_size=1,
|
||||
data_parallel_size=1,
|
||||
tensor_parallel_size=1,
|
||||
sequence_parallel_size=sp_size,
|
||||
ulysses_degree=sp_size,
|
||||
ring_degree=1,
|
||||
cfg_parallel_size=1,
|
||||
),
|
||||
diffusion_attention_backend="TORCH_SDPA",
|
||||
)
|
||||
|
||||
|
||||
def _inputs(device: torch.device) -> dict[str, torch.Tensor | int | bool]:
|
||||
generator = torch.Generator().manual_seed(123)
|
||||
return {
|
||||
"hidden_states": torch.randn(1, 8, 4, generator=generator, device="cpu").to(device),
|
||||
"audio_hidden_states": torch.randn(1, 4, 4, generator=generator, device="cpu").to(device),
|
||||
"encoder_hidden_states": torch.randn(1, 3, 8, generator=generator, device="cpu").to(device),
|
||||
"audio_encoder_hidden_states": torch.randn(1, 3, 8, generator=generator, device="cpu").to(device),
|
||||
"timestep": torch.linspace(0.1, 0.8, 8, device=device).view(1, 8),
|
||||
"audio_timestep": torch.linspace(0.2, 0.5, 4, device=device).view(1, 4),
|
||||
"keyframes_mask": torch.tensor([[[1.0], [0.0], [1.0], [0.0], [0.0], [1.0], [0.0], [0.0]]], device=device),
|
||||
"sigma": torch.tensor([0.1], device=device),
|
||||
"audio_sigma": torch.tensor([0.2], device=device),
|
||||
"num_frames": 2,
|
||||
"height": 2,
|
||||
"width": 2,
|
||||
"audio_num_frames": 4,
|
||||
"return_dict": False,
|
||||
}
|
||||
|
||||
|
||||
def _run_transformer_parity(rank: int, world_size: int, master_port: int) -> None:
|
||||
device = torch.device(f"{current_omni_platform.device_type}:{rank}")
|
||||
current_omni_platform.set_device(device)
|
||||
os.environ.update(
|
||||
{
|
||||
"RANK": str(rank),
|
||||
"LOCAL_RANK": str(rank),
|
||||
"WORLD_SIZE": str(world_size),
|
||||
"MASTER_ADDR": "localhost",
|
||||
"MASTER_PORT": str(master_port),
|
||||
}
|
||||
)
|
||||
|
||||
try:
|
||||
init_distributed_environment()
|
||||
initialize_model_parallel(sequence_parallel_size=world_size, ulysses_degree=world_size)
|
||||
|
||||
sp_config = _omni_config(world_size)
|
||||
torch.manual_seed(42)
|
||||
with set_forward_context(omni_diffusion_config=sp_config), set_current_diffusion_config(sp_config):
|
||||
model = LTX2VideoTransformer3DModel(**_TINY_CONFIG).to(device).eval()
|
||||
with torch.no_grad():
|
||||
for _, parameter in sorted(model.named_parameters()):
|
||||
torch.nn.init.normal_(parameter, mean=0.0, std=0.02)
|
||||
|
||||
inputs = _inputs(device)
|
||||
reference_config = _omni_config(1)
|
||||
with torch.no_grad(), set_forward_context(omni_diffusion_config=reference_config):
|
||||
expected_video, expected_audio = model(**inputs)
|
||||
|
||||
apply_sequence_parallel(
|
||||
model,
|
||||
SequenceParallelConfig(ulysses_degree=world_size, ring_degree=1),
|
||||
model._sp_plan,
|
||||
)
|
||||
with torch.no_grad(), set_forward_context(omni_diffusion_config=sp_config):
|
||||
get_forward_context().sp_plan_hooks_applied = True
|
||||
actual_video, actual_audio = model(**inputs)
|
||||
|
||||
v2a_attention = model.transformer_blocks[0].video_to_audio_attn.attn
|
||||
assert v2a_attention._video_to_audio_strategy is not None
|
||||
assert torch.isfinite(expected_video).all()
|
||||
assert torch.isfinite(expected_audio).all()
|
||||
for modality, actual, expected in (
|
||||
("video", actual_video, expected_video),
|
||||
("audio", actual_audio, expected_audio),
|
||||
):
|
||||
drift = _relative_l2(actual, expected)
|
||||
assert drift <= _FP32_REL_L2, (
|
||||
f"LTX SP{world_size} {modality} output drifted rel_l2={drift:.3e} from SP1 (bound {_FP32_REL_L2:.1e})"
|
||||
)
|
||||
finally:
|
||||
destroy_distributed_env()
|
||||
|
||||
|
||||
@pytest.mark.full_model
|
||||
@hardware_test(res={"cuda": "L4", "rocm": "MI325"}, num_cards=2)
|
||||
def test_ltx_ulysses_transformer_matches_sp1(unused_tcp_port) -> None:
|
||||
"""Exercise real plan hooks, RoPE/timestep sharding, and attention routing."""
|
||||
world_size = 2
|
||||
device_count = current_omni_platform.device_count()
|
||||
assert device_count >= world_size, (
|
||||
f"LTX Ulysses parity requires {world_size} accelerator devices; only {device_count} are visible"
|
||||
)
|
||||
torch.multiprocessing.spawn(
|
||||
_run_transformer_parity,
|
||||
args=(world_size, unused_tcp_port),
|
||||
nprocs=world_size,
|
||||
)
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
import json
|
||||
import sys
|
||||
from contextlib import contextmanager
|
||||
from multiprocessing.reduction import ForkingPickler
|
||||
from types import SimpleNamespace
|
||||
from typing import Any, TypeVar
|
||||
@@ -176,9 +177,9 @@ def _write_partition_index(path, *, partition, tasks):
|
||||
|
||||
|
||||
def test_modular_diffusers_index_is_resolved_generically(tmp_path):
|
||||
from vllm_omni.config.resolver import resolve_omni_config
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig, resolve_model_class_name
|
||||
from vllm_omni.diffusion.utils.hf_utils import is_diffusion_model
|
||||
from vllm_omni.entrypoints.utils import resolve_model_config_path
|
||||
|
||||
(tmp_path / "modular_model_index.json").write_text(
|
||||
json.dumps(
|
||||
@@ -192,7 +193,16 @@ def test_modular_diffusers_index_is_resolved_generically(tmp_path):
|
||||
|
||||
assert is_diffusion_model(str(tmp_path))
|
||||
assert resolve_model_class_name(str(tmp_path)) == "MiniMaxH3ModularPipeline"
|
||||
assert resolve_model_config_path(str(tmp_path)) is None
|
||||
resolved = resolve_omni_config(
|
||||
str(tmp_path),
|
||||
trust_remote_code=False,
|
||||
deploy_config_path=None,
|
||||
cli_overrides=None,
|
||||
stage_overrides=None,
|
||||
strategy_config_path=None,
|
||||
)
|
||||
assert resolved.config_path is None
|
||||
assert resolved.stage_by_id(0).engine_args.model_class_name == "MiniMaxH3ModularPipeline"
|
||||
|
||||
config = OmniDiffusionConfig(model=str(tmp_path))
|
||||
config.enrich_config()
|
||||
@@ -1550,6 +1560,97 @@ def test_video_vae_keeps_reference_fp32_weights(monkeypatch):
|
||||
assert next(video_vae.parameters()).dtype == torch.float32
|
||||
|
||||
|
||||
def test_keyframe_encode_pins_and_restores_cudnn_settings():
|
||||
from vllm_omni.diffusion.models.minimax_h3.vae import (
|
||||
_minimax_h3_keyframe_encode_context,
|
||||
)
|
||||
|
||||
cudnn = torch.backends.cudnn
|
||||
original = (
|
||||
cudnn.enabled,
|
||||
cudnn.benchmark,
|
||||
cudnn.deterministic,
|
||||
cudnn.allow_tf32,
|
||||
)
|
||||
try:
|
||||
cudnn.enabled = False
|
||||
cudnn.benchmark = True
|
||||
cudnn.deterministic = False
|
||||
cudnn.allow_tf32 = False
|
||||
|
||||
with _minimax_h3_keyframe_encode_context(torch.device("cuda")):
|
||||
assert cudnn.enabled
|
||||
assert not cudnn.benchmark
|
||||
assert cudnn.deterministic
|
||||
assert cudnn.allow_tf32
|
||||
|
||||
assert not cudnn.enabled
|
||||
assert cudnn.benchmark
|
||||
assert not cudnn.deterministic
|
||||
assert not cudnn.allow_tf32
|
||||
finally:
|
||||
(
|
||||
cudnn.enabled,
|
||||
cudnn.benchmark,
|
||||
cudnn.deterministic,
|
||||
cudnn.allow_tf32,
|
||||
) = original
|
||||
|
||||
|
||||
@pytest.mark.parametrize("fail_encode", [False, True])
|
||||
def test_keyframe_encode_enters_backend_context(monkeypatch, fail_encode):
|
||||
from PIL import Image
|
||||
|
||||
from vllm_omni.diffusion.models.minimax_h3 import vae as vae_module
|
||||
|
||||
events = []
|
||||
input_image = Image.new("RGB", (32, 32))
|
||||
|
||||
@contextmanager
|
||||
def track_context(device):
|
||||
assert device == torch.device("cpu")
|
||||
events.append("enter")
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
events.append("exit")
|
||||
|
||||
class FakeModel(torch.nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.weight = torch.nn.Parameter(torch.ones(1))
|
||||
self.parallel_tiling = True
|
||||
|
||||
def encode_images(self, image, *, use_fp16_latent):
|
||||
assert events == ["enter"]
|
||||
assert image is input_image
|
||||
assert use_fp16_latent
|
||||
events.append("encode")
|
||||
if fail_encode:
|
||||
raise RuntimeError("encode failed")
|
||||
return [torch.ones(1, 1, 2, 2)]
|
||||
|
||||
video_vae = object.__new__(vae_module.MiniMaxH3VideoVAE)
|
||||
torch.nn.Module.__init__(video_vae)
|
||||
video_vae.model = FakeModel()
|
||||
video_vae.config_dict = {
|
||||
"latent_channels": 1,
|
||||
"latents_mean": [0.0],
|
||||
"latents_std": [1.0],
|
||||
}
|
||||
monkeypatch.setattr(vae_module, "_minimax_h3_keyframe_encode_context", track_context)
|
||||
|
||||
if fail_encode:
|
||||
with pytest.raises(RuntimeError, match="encode failed"):
|
||||
video_vae.encode_image(input_image)
|
||||
else:
|
||||
rows = video_vae.encode_image(input_image)
|
||||
torch.testing.assert_close(rows, torch.ones(1, 4))
|
||||
|
||||
assert events == ["enter", "encode", "exit"]
|
||||
assert video_vae.model.parallel_tiling
|
||||
|
||||
|
||||
def test_video_vae_can_load_on_cpu_for_staged_gpu_residency(monkeypatch):
|
||||
from vllm_omni.diffusion.models.minimax_h3 import vae as vae_module
|
||||
|
||||
|
||||
@@ -5,14 +5,154 @@ import pytest
|
||||
import torch
|
||||
from vllm.triton_utils import HAS_TRITON
|
||||
|
||||
from tests.helpers.mark import hardware_marks
|
||||
from vllm_omni.diffusion.attention.ops.minimax_h3_modulation import (
|
||||
_MAX_1D_GRID_SIZE,
|
||||
_iter_row_chunks,
|
||||
_launch_row_chunks,
|
||||
indexed_gate,
|
||||
indexed_gate_rms_norm_scale_shift,
|
||||
indexed_scale_shift_,
|
||||
rms_norm_indexed_scale_shift,
|
||||
)
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.diffusion, pytest.mark.cuda]
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.diffusion]
|
||||
|
||||
|
||||
@pytest.mark.cpu
|
||||
@pytest.mark.parametrize(
|
||||
("rows", "expected"),
|
||||
[
|
||||
(0, []),
|
||||
(_MAX_1D_GRID_SIZE, [(0, _MAX_1D_GRID_SIZE)]),
|
||||
(_MAX_1D_GRID_SIZE + 1, [(0, _MAX_1D_GRID_SIZE), (_MAX_1D_GRID_SIZE, 1)]),
|
||||
(69888, [(0, _MAX_1D_GRID_SIZE), (_MAX_1D_GRID_SIZE, 4353)]),
|
||||
],
|
||||
)
|
||||
def test_row_chunks_respect_ascend_grid_limit(rows, expected):
|
||||
assert list(_iter_row_chunks(rows)) == expected
|
||||
|
||||
|
||||
@pytest.mark.cpu
|
||||
@pytest.mark.parametrize(
|
||||
("device_type", "expected_grids_and_offsets"),
|
||||
[
|
||||
("npu", [(_MAX_1D_GRID_SIZE, 0), (4353, _MAX_1D_GRID_SIZE)]),
|
||||
("cuda", [(69888, 0)]),
|
||||
],
|
||||
)
|
||||
def test_launch_row_chunks_is_npu_only(device_type, expected_grids_and_offsets):
|
||||
class RecordingKernel:
|
||||
def __init__(self):
|
||||
self.calls = []
|
||||
|
||||
def __getitem__(self, grid):
|
||||
def launch(*args, **kwargs):
|
||||
self.calls.append((grid, args, kwargs))
|
||||
|
||||
return launch
|
||||
|
||||
kernel = RecordingKernel()
|
||||
first_arg = object()
|
||||
second_arg = object()
|
||||
|
||||
_launch_row_chunks(kernel, 69888, device_type, first_arg, second_arg, block_n=16)
|
||||
|
||||
assert kernel.calls == [
|
||||
((grid,), (first_arg, second_arg, row_offset), {"block_n": 16})
|
||||
for grid, row_offset in expected_grids_and_offsets
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_omni_platform.is_npu(), reason="requires Ascend NPU")
|
||||
@pytest.mark.parametrize(
|
||||
"device",
|
||||
[pytest.param("npu", marks=hardware_marks(res={"npu": "A3"}, num_cards=1))],
|
||||
)
|
||||
def test_modulation_wrappers_match_reference_above_grid_limit(device):
|
||||
rows = 69888
|
||||
hidden_size = 16
|
||||
num_conditions = 7
|
||||
eps = 1e-6
|
||||
dtype = torch.bfloat16
|
||||
|
||||
torch.manual_seed(0)
|
||||
x = torch.randn(rows, hidden_size, dtype=dtype)
|
||||
residual = torch.randn_like(x)
|
||||
branch = torch.randn_like(x)
|
||||
weight = torch.randn(hidden_size, dtype=dtype)
|
||||
shift = torch.randn(num_conditions, hidden_size, dtype=dtype)
|
||||
scale = torch.randn_like(shift)
|
||||
gate = torch.randn_like(shift)
|
||||
indices = torch.arange(rows) % num_conditions
|
||||
|
||||
indexed_shift = shift.index_select(0, indices)
|
||||
indexed_scale = scale.index_select(0, indices)
|
||||
indexed_gate_values = gate.index_select(0, indices)
|
||||
|
||||
x_float = x.float()
|
||||
branch_float = branch.float()
|
||||
indexed_shift_float = indexed_shift.float()
|
||||
indexed_scale_float = indexed_scale.float()
|
||||
indexed_gate_float = indexed_gate_values.float()
|
||||
|
||||
expected_scale_shift = (x_float * (1.0 + indexed_scale_float) + indexed_shift_float).to(dtype)
|
||||
expected_gate = (x_float + indexed_gate_float * branch_float).to(dtype)
|
||||
|
||||
normalized = x_float
|
||||
normalized = normalized * torch.rsqrt(normalized.pow(2).mean(-1, keepdim=True) + eps)
|
||||
normalized = normalized * weight.float()
|
||||
expected_rms = (normalized * (1.0 + indexed_scale_float) + indexed_shift_float).to(dtype)
|
||||
|
||||
updated_residual = residual.float() + indexed_gate_float * branch_float
|
||||
expected_residual = updated_residual.to(dtype)
|
||||
normalized_residual = updated_residual
|
||||
normalized_residual = normalized_residual * torch.rsqrt(normalized_residual.pow(2).mean(-1, keepdim=True) + eps)
|
||||
normalized_residual = normalized_residual * weight.float()
|
||||
expected_modulated = (normalized_residual * (1.0 + indexed_scale_float) + indexed_shift_float).to(dtype)
|
||||
|
||||
npu_x = x.to(device)
|
||||
npu_residual = residual.to(device)
|
||||
npu_branch = branch.to(device)
|
||||
npu_weight = weight.to(device)
|
||||
npu_shift = shift.to(device)
|
||||
npu_scale = scale.to(device)
|
||||
npu_gate = gate.to(device)
|
||||
npu_indices = indices.to(device)
|
||||
|
||||
actual_scale_shift = indexed_scale_shift_(npu_x.clone(), npu_shift, npu_scale, npu_indices)
|
||||
actual_gate = indexed_gate(npu_x, npu_gate, npu_branch, npu_indices)
|
||||
actual_rms = rms_norm_indexed_scale_shift(
|
||||
npu_x,
|
||||
npu_weight,
|
||||
npu_shift,
|
||||
npu_scale,
|
||||
npu_indices,
|
||||
eps,
|
||||
)
|
||||
actual_residual, actual_modulated = indexed_gate_rms_norm_scale_shift(
|
||||
npu_residual,
|
||||
npu_gate,
|
||||
npu_branch,
|
||||
npu_weight,
|
||||
npu_shift,
|
||||
npu_scale,
|
||||
npu_indices,
|
||||
eps,
|
||||
)
|
||||
|
||||
for actual, expected in (
|
||||
(actual_scale_shift, expected_scale_shift),
|
||||
(actual_gate, expected_gate),
|
||||
(actual_rms, expected_rms),
|
||||
(actual_residual, expected_residual),
|
||||
(actual_modulated, expected_modulated),
|
||||
):
|
||||
torch.testing.assert_close(actual.cpu(), expected, atol=2e-2, rtol=2e-2)
|
||||
|
||||
|
||||
@pytest.mark.cuda
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required")
|
||||
@pytest.mark.skipif(not HAS_TRITON, reason="Triton required")
|
||||
def test_fused_modulation_preserves_bf16_residual_boundary() -> None:
|
||||
|
||||
@@ -42,10 +42,10 @@ _QUALITY_CONFIG = QualityTestConfig(
|
||||
|
||||
|
||||
def _resolve_fl2va_model_ref() -> str:
|
||||
from huggingface_hub import snapshot_download
|
||||
from vllm_omni.transformers_utils.repo_utils import hf_api
|
||||
|
||||
repo_root = Path(
|
||||
snapshot_download(
|
||||
hf_api().snapshot_download(
|
||||
repo_id=_MINIMAX_H3_REPO,
|
||||
revision=_MINIMAX_H3_REVISION,
|
||||
allow_patterns=["FL2VA/**"],
|
||||
@@ -253,13 +253,13 @@ def test_resolve_fl2va_model_ref(tmp_path, monkeypatch):
|
||||
fl2va_root.mkdir()
|
||||
(fl2va_root / "model_index.json").write_text("{}", encoding="utf-8")
|
||||
|
||||
def fake_snapshot_download(*, repo_id, revision, allow_patterns):
|
||||
def fake_snapshot_download(self, *, repo_id, revision, allow_patterns):
|
||||
assert repo_id == _MINIMAX_H3_REPO
|
||||
assert revision == _MINIMAX_H3_REVISION
|
||||
assert allow_patterns == ["FL2VA/**"]
|
||||
return str(tmp_path)
|
||||
|
||||
monkeypatch.setattr("huggingface_hub.snapshot_download", fake_snapshot_download)
|
||||
monkeypatch.setattr("huggingface_hub.HfApi.snapshot_download", fake_snapshot_download)
|
||||
assert _resolve_fl2va_model_ref() == str(fl2va_root)
|
||||
|
||||
|
||||
|
||||
@@ -49,3 +49,29 @@ def test_qwen3_vl_npu_swiglu_matches_two_projection_reference() -> None:
|
||||
atol=2e-2,
|
||||
rtol=2e-2,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_omni_platform.is_npu(), reason="requires Ascend NPU")
|
||||
def test_qwen3_vl_npu_swiglu_forward_uses_projection_module(mocker) -> None:
|
||||
from vllm_omni.platforms.npu.models import minimax_h3
|
||||
from vllm_omni.platforms.npu.models.minimax_h3 import (
|
||||
_forward_minimax_h3_qwen3vl_text_mlp_npu,
|
||||
)
|
||||
|
||||
x = torch.randn(1, 16, 128, device="npu", dtype=torch.bfloat16)
|
||||
packed = torch.randn(1, 16, 256, device="npu", dtype=torch.bfloat16)
|
||||
activated = torch.randn(1, 16, 128, device="npu", dtype=torch.bfloat16)
|
||||
gate_up_proj = mocker.Mock(return_value=packed)
|
||||
down_proj = mocker.Mock(side_effect=lambda value: value)
|
||||
mlp = mocker.Mock(gate_up_proj=gate_up_proj, down_proj=down_proj)
|
||||
swiglu = mocker.patch.object(minimax_h3, "npu_swiglu_from_packed", return_value=activated)
|
||||
|
||||
output = _forward_minimax_h3_qwen3vl_text_mlp_npu(mlp, x)
|
||||
|
||||
gate_up_proj.assert_called_once()
|
||||
assert gate_up_proj.call_args.args[0] is x
|
||||
swiglu.assert_called_once()
|
||||
assert swiglu.call_args.args[0] is packed
|
||||
down_proj.assert_called_once()
|
||||
assert down_proj.call_args.args[0] is activated
|
||||
assert output is activated
|
||||
@@ -52,6 +52,7 @@ from vllm_omni.diffusion.offloader.offload_plan import (
|
||||
OffloadPlan,
|
||||
get_offload_plan,
|
||||
)
|
||||
from vllm_omni.diffusion.offloader.plan_resolver import resolve_offload_plan
|
||||
from vllm_omni.diffusion.offloader.startup import OffloadStartupState, attach_offload_startup_state
|
||||
from vllm_omni.host_weight_runtime import MappedHostRegion
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
@@ -2813,18 +2814,21 @@ class TestDistributedComponentSelection:
|
||||
|
||||
def test_encoder_allgather_rejects_stub_rank_before_block_discovery(self):
|
||||
"""Every rank must reject an unsafe encoder group, including stub ranks."""
|
||||
backend = DistributedLayerwiseOffloadBackend(
|
||||
OffloadConfig(
|
||||
strategy=OffloadStrategy.DISTRIBUTED_LAYER_WISE,
|
||||
pin_cpu_memory=False,
|
||||
dp_size=2,
|
||||
components=frozenset({"text_encoder"}),
|
||||
dlo_transfers={"dit": "rank-local", "text_encoder": "allgather"},
|
||||
),
|
||||
torch.device("cpu"),
|
||||
|
||||
class StubEncoderPipeline(nn.Module):
|
||||
_offload_plan = OffloadPlan(encoder_block_attrs={"text_encoder": ("missing.blocks",)})
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.text_encoder = nn.Module()
|
||||
|
||||
config = OffloadConfig(
|
||||
strategy=OffloadStrategy.DISTRIBUTED_LAYER_WISE,
|
||||
pin_cpu_memory=False,
|
||||
dp_size=2,
|
||||
components=frozenset({"text_encoder"}),
|
||||
dlo_transfers={"dit": "rank-local", "text_encoder": "allgather"},
|
||||
)
|
||||
backend.dp_group = object()
|
||||
stub_plan = OffloadPlan(encoder_block_attrs={"text_encoder": ("missing.blocks",)})
|
||||
|
||||
with pytest.raises(ValueError, match="not declared replicated"):
|
||||
backend._try_layerwise_offload_encoder(nn.Module(), "text_encoder", stub_plan)
|
||||
resolve_offload_plan(StubEncoderPipeline(), config)
|
||||
@@ -488,7 +488,8 @@ class TestLayerwiseComponentSelection:
|
||||
with pytest.raises(ValueError, match="Selected text encoder 'text_encoder_2' requires"):
|
||||
backend.enable(pipeline)
|
||||
|
||||
assert not pipeline.text_encoder._omni_layerwise_enabled
|
||||
# The plan resolver rejects the topology before any encoder is hooked.
|
||||
assert not getattr(pipeline.text_encoder, "_omni_layerwise_enabled", False)
|
||||
|
||||
def test_default_selection_preserves_unplanned_auxiliaries(self, patched_offload_runtime):
|
||||
pipeline = _LegacyComponentPipeline()
|
||||
|
||||
@@ -0,0 +1,458 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Unit tests for the shared offload plan resolver."""
|
||||
|
||||
from typing import ClassVar
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from tests.diffusion.offloader.helpers import (
|
||||
_DummyBlock,
|
||||
_PlainEncoder,
|
||||
_SingleBlockModel,
|
||||
_StagedEncoder,
|
||||
_StagedVAE,
|
||||
patch_offload_runtime,
|
||||
)
|
||||
from vllm_omni.diffusion.offloader import layerwise_backend as layerwise_backend_module
|
||||
from vllm_omni.diffusion.offloader import plan_resolver as plan_resolver_module
|
||||
from vllm_omni.diffusion.offloader.base import OffloadConfig, OffloadStrategy
|
||||
from vllm_omni.diffusion.offloader.layerwise_backend import LayerWiseOffloadBackend
|
||||
from vllm_omni.diffusion.offloader.offload_plan import OffloadPlan
|
||||
from vllm_omni.diffusion.offloader.plan_resolver import resolve_offload_plan
|
||||
|
||||
pytestmark = [pytest.mark.diffusion, pytest.mark.cpu, pytest.mark.core_model]
|
||||
|
||||
CPU = torch.device("cpu")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def patched_offload_runtime(monkeypatch):
|
||||
patch_offload_runtime(monkeypatch, layerwise_backend_module.current_omni_platform)
|
||||
|
||||
|
||||
def _config(
|
||||
components: set[str] | None = None,
|
||||
strategy: OffloadStrategy = OffloadStrategy.LAYER_WISE,
|
||||
**kwargs,
|
||||
) -> OffloadConfig:
|
||||
return OffloadConfig(
|
||||
strategy=strategy,
|
||||
pin_cpu_memory=False,
|
||||
components=None if components is None else frozenset(components),
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
|
||||
def _stack_of(component):
|
||||
assert len(component.stacks) == 1
|
||||
return component.stacks[0]
|
||||
|
||||
|
||||
class _WanStylePipeline(nn.Module):
|
||||
"""Streamable DiT plus a plan-declared, replicated text encoder."""
|
||||
|
||||
_dit_modules: ClassVar[list[str]] = ["transformer"]
|
||||
_encoder_modules: ClassVar[list[str]] = ["text_encoder"]
|
||||
_vae_modules: ClassVar[list[str]] = ["vae"]
|
||||
_resident_modules: ClassVar[list[str]] = []
|
||||
_offload_plan = OffloadPlan(
|
||||
encoder_component_types={"text_encoder": "text_encoder"},
|
||||
encoder_block_attrs={"text_encoder": ("encoder.block",)},
|
||||
encoder_dlo_weight_replication=frozenset({"text_encoder"}),
|
||||
)
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.transformer = _SingleBlockModel(num_blocks=4)
|
||||
self.text_encoder = _PlainEncoder()
|
||||
self.vae = _StagedVAE()
|
||||
|
||||
|
||||
class _StagedComponentPipeline(nn.Module):
|
||||
"""MiniMax-H3 shape: two encoder stacks plus pipeline-staged components."""
|
||||
|
||||
_dit_modules: ClassVar[list[str]] = ["transformer"]
|
||||
_encoder_modules: ClassVar[list[str]] = ["text_encoder"]
|
||||
_vae_modules: ClassVar[list[str]] = ["vae"]
|
||||
_resident_modules: ClassVar[list[str]] = []
|
||||
_offload_plan = OffloadPlan(
|
||||
encoder_component_types={"text_encoder": "text_encoder"},
|
||||
encoder_block_attrs={"text_encoder": ("vision.blocks", "text_model.layers")},
|
||||
on_demand_component_paths=frozenset({"text_encoder", "vae"}),
|
||||
resident_dit_paths=frozenset({"transformer"}),
|
||||
)
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.transformer = _SingleBlockModel(num_blocks=4)
|
||||
self.text_encoder = _StagedEncoder()
|
||||
self.vae = _StagedVAE()
|
||||
|
||||
|
||||
class _LegacyScanPipeline(nn.Module):
|
||||
"""No SupportsComponentDiscovery declaration and no OffloadPlan."""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.transformer = _SingleBlockModel(num_blocks=3)
|
||||
self.text_encoder = _PlainEncoder()
|
||||
|
||||
|
||||
class TestProducerPrecedence:
|
||||
def test_plan_block_attrs_win_over_class_attributes(self):
|
||||
class TwoStackDiT(nn.Module):
|
||||
_layerwise_offload_blocks_attrs = ["blocks"]
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.blocks = nn.ModuleList([_DummyBlock() for _ in range(2)])
|
||||
self.alt_blocks = nn.ModuleList([_DummyBlock() for _ in range(3)])
|
||||
|
||||
class Pipeline(nn.Module):
|
||||
_offload_plan = OffloadPlan(block_attrs={"transformer": ("alt_blocks",)})
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.transformer = TwoStackDiT()
|
||||
|
||||
pipeline = Pipeline()
|
||||
resolved = resolve_offload_plan(pipeline, _config({"dit"}))
|
||||
|
||||
stack = _stack_of(resolved.dits[0])
|
||||
assert stack.attrs == ("alt_blocks",)
|
||||
assert list(stack.blocks) == list(pipeline.transformer.alt_blocks)
|
||||
|
||||
def test_class_attributes_are_used_without_a_plan(self):
|
||||
pipeline = _LegacyScanPipeline()
|
||||
resolved = resolve_offload_plan(pipeline, _config({"dit"}))
|
||||
|
||||
assert list(_stack_of(resolved.dits[0]).blocks) == list(pipeline.transformer.blocks)
|
||||
|
||||
def test_declared_component_type_wins_over_leaf_name(self):
|
||||
class Pipeline(nn.Module):
|
||||
_dit_modules: ClassVar[list[str]] = ["transformer"]
|
||||
_encoder_modules: ClassVar[list[str]] = ["mllm"]
|
||||
_vae_modules: ClassVar[list[str]] = []
|
||||
_resident_modules: ClassVar[list[str]] = []
|
||||
_offload_plan = OffloadPlan(
|
||||
encoder_component_types={"mllm": "text_encoder"},
|
||||
encoder_block_attrs={"mllm": ("encoder.block",)},
|
||||
)
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.transformer = _SingleBlockModel(num_blocks=2)
|
||||
self.mllm = _PlainEncoder()
|
||||
|
||||
resolved = resolve_offload_plan(Pipeline(), _config({"text_encoder"}))
|
||||
|
||||
encoder = resolved.encoders[0]
|
||||
assert encoder.path == "mllm"
|
||||
assert encoder.selected
|
||||
assert len(_stack_of(encoder).blocks) == 2
|
||||
|
||||
def test_component_declaration_wins_over_attribute_scan(self):
|
||||
class Pipeline(nn.Module):
|
||||
_dit_modules: ClassVar[list[str]] = ["custom_dit"]
|
||||
_encoder_modules: ClassVar[list[str]] = []
|
||||
_vae_modules: ClassVar[list[str]] = []
|
||||
_resident_modules: ClassVar[list[str]] = []
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.custom_dit = _SingleBlockModel(num_blocks=2)
|
||||
# Would be picked up by the deprecated attribute scan.
|
||||
self.transformer = _SingleBlockModel(num_blocks=2)
|
||||
|
||||
resolved = resolve_offload_plan(Pipeline(), _config({"dit"}))
|
||||
|
||||
assert [component.path for component in resolved.dits] == ["custom_dit"]
|
||||
|
||||
def test_attribute_scan_warns_once_per_pipeline_class(self, monkeypatch):
|
||||
warnings: list[str] = []
|
||||
|
||||
class _Recorder:
|
||||
def warning(self, message, *args):
|
||||
warnings.append(message % args if args else message)
|
||||
|
||||
def __getattr__(self, _name):
|
||||
return lambda *args, **kwargs: None
|
||||
|
||||
monkeypatch.setattr(plan_resolver_module, "logger", _Recorder())
|
||||
|
||||
class UndeclaredPipeline(nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.transformer = _SingleBlockModel(num_blocks=2)
|
||||
|
||||
resolve_offload_plan(UndeclaredPipeline(), _config({"dit"}))
|
||||
resolve_offload_plan(UndeclaredPipeline(), _config({"dit"}))
|
||||
|
||||
scan_warnings = [message for message in warnings if "SupportsComponentDiscovery" in message]
|
||||
assert len(scan_warnings) == 1
|
||||
assert "deprecated" in scan_warnings[0]
|
||||
|
||||
|
||||
class TestResolvedTopology:
|
||||
def test_encoder_plan_resolves_one_stack_per_declared_path(self):
|
||||
pipeline = _WanStylePipeline()
|
||||
resolved = resolve_offload_plan(pipeline, _config({"dit", "text_encoder"}))
|
||||
|
||||
encoder = resolved.encoders[0]
|
||||
assert encoder.selected and not encoder.on_demand
|
||||
assert list(_stack_of(encoder).blocks) == list(pipeline.text_encoder.encoder.block)
|
||||
assert [component.path for component in resolved.vaes] == ["vae"]
|
||||
|
||||
def test_staged_plan_resolves_every_declared_stack(self):
|
||||
pipeline = _StagedComponentPipeline()
|
||||
resolved = resolve_offload_plan(pipeline, _config({"text_encoder"}))
|
||||
|
||||
encoder = resolved.encoders[0]
|
||||
assert encoder.on_demand
|
||||
assert [len(stack.blocks) for stack in encoder.stacks] == [2, 2]
|
||||
# An explicit selection never stages a VAE through the legacy plan.
|
||||
assert not resolved.vaes[0].on_demand
|
||||
# DiT is unselected, so it keeps no streaming topology.
|
||||
assert resolved.dits[0].selected is False
|
||||
assert resolved.dits[0].stacks == ()
|
||||
|
||||
def test_omitted_selector_keeps_the_legacy_staged_vae(self):
|
||||
resolved = resolve_offload_plan(_StagedComponentPipeline(), _config())
|
||||
|
||||
assert resolved.vaes[0].on_demand
|
||||
assert resolved.encoders[0].on_demand
|
||||
assert resolved.dits[0].selected
|
||||
|
||||
def test_on_demand_only_plan_resolves_without_stacks(self):
|
||||
class Pipeline(nn.Module):
|
||||
_dit_modules: ClassVar[list[str]] = ["transformer"]
|
||||
_encoder_modules: ClassVar[list[str]] = ["text_encoder"]
|
||||
_vae_modules: ClassVar[list[str]] = ["vae"]
|
||||
_resident_modules: ClassVar[list[str]] = []
|
||||
_offload_plan = OffloadPlan(on_demand_component_paths=frozenset({"text_encoder", "vae"}))
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.transformer = _SingleBlockModel(num_blocks=2)
|
||||
self.text_encoder = _StagedEncoder()
|
||||
self.vae = _StagedVAE()
|
||||
|
||||
resolved = resolve_offload_plan(Pipeline(), _config({"text_encoder"}))
|
||||
|
||||
assert resolved.encoders[0].on_demand
|
||||
assert resolved.encoders[0].stacks == ()
|
||||
|
||||
def test_module_strategy_resolves_selection_without_stacks(self):
|
||||
resolved = resolve_offload_plan(
|
||||
_WanStylePipeline(),
|
||||
_config({"dit", "text_encoder"}, strategy=OffloadStrategy.MODEL_LEVEL),
|
||||
)
|
||||
|
||||
assert [component.path for component in resolved.components] == ["transformer", "text_encoder", "vae"]
|
||||
assert all(component.stacks == () for component in resolved.components)
|
||||
assert resolved.encoders[0].selected
|
||||
|
||||
def test_module_strategy_leaves_staged_residency_to_the_pipeline(self):
|
||||
resolved = resolve_offload_plan(
|
||||
_StagedComponentPipeline(),
|
||||
_config({"dit", "text_encoder"}, strategy=OffloadStrategy.MODEL_LEVEL),
|
||||
)
|
||||
|
||||
assert not any(component.on_demand for component in resolved.components)
|
||||
|
||||
|
||||
class TestResidentLayers:
|
||||
def _dlo_config(self, resident_layers: int, components: set[str] | None = None) -> OffloadConfig:
|
||||
return _config(
|
||||
components,
|
||||
strategy=OffloadStrategy.DISTRIBUTED_LAYER_WISE,
|
||||
dlo_transfers={"dit": "rank-local", "text_encoder": "rank-local"},
|
||||
dlo_resident_layers=resident_layers,
|
||||
)
|
||||
|
||||
def test_resident_head_splits_the_declared_dit(self):
|
||||
pipeline = _StagedComponentPipeline()
|
||||
resolved = resolve_offload_plan(pipeline, self._dlo_config(2, {"dit"}))
|
||||
|
||||
stack = _stack_of(resolved.dits[0])
|
||||
assert stack.resident_head == 2
|
||||
assert list(stack.resident) == list(pipeline.transformer.blocks)[:2]
|
||||
assert list(stack.streaming) == list(pipeline.transformer.blocks)[2:]
|
||||
|
||||
def test_resident_count_beyond_the_stack_keeps_every_block(self):
|
||||
resolved = resolve_offload_plan(_StagedComponentPipeline(), self._dlo_config(9, {"dit"}))
|
||||
|
||||
stack = _stack_of(resolved.dits[0])
|
||||
assert stack.resident_head == 4
|
||||
assert stack.streaming == ()
|
||||
|
||||
def test_resident_head_leaving_one_streaming_block_is_rejected(self):
|
||||
with pytest.raises(ValueError, match="leaves only one streaming block"):
|
||||
resolve_offload_plan(_StagedComponentPipeline(), self._dlo_config(3, {"dit"}))
|
||||
|
||||
def test_legacy_single_streaming_block_stays_resident(self):
|
||||
resolved = resolve_offload_plan(_StagedComponentPipeline(), self._dlo_config(3))
|
||||
|
||||
stack = _stack_of(resolved.dits[0])
|
||||
assert stack.resident_head == 4
|
||||
assert stack.streaming == ()
|
||||
|
||||
def test_resident_layers_without_a_declared_path_is_rejected(self):
|
||||
with pytest.raises(ValueError, match="no matching resident_dit_paths"):
|
||||
resolve_offload_plan(_WanStylePipeline(), self._dlo_config(2, {"dit"}))
|
||||
|
||||
|
||||
class TestValidation:
|
||||
def test_selected_dit_requires_a_discovered_module(self):
|
||||
pipeline = nn.Module()
|
||||
pipeline.text_encoder = _PlainEncoder()
|
||||
|
||||
with pytest.raises(ValueError, match="No DiT/transformer modules found"):
|
||||
resolve_offload_plan(pipeline, _config({"dit"}))
|
||||
|
||||
def test_model_level_selection_requires_both_swap_sides(self):
|
||||
pipeline = nn.Module()
|
||||
pipeline.transformer = _SingleBlockModel(num_blocks=2)
|
||||
|
||||
with pytest.raises(ValueError, match="requires an encoder execution stage"):
|
||||
resolve_offload_plan(pipeline, _config({"dit"}, strategy=OffloadStrategy.MODEL_LEVEL))
|
||||
|
||||
def test_selected_text_encoder_requires_a_matching_module(self):
|
||||
pipeline = nn.Module()
|
||||
pipeline.transformer = _SingleBlockModel(num_blocks=2)
|
||||
|
||||
with pytest.raises(ValueError, match="No text encoder modules found"):
|
||||
resolve_offload_plan(pipeline, _config({"text_encoder"}))
|
||||
|
||||
def test_selected_encoder_requires_a_streamable_or_staged_plan(self):
|
||||
pipeline = nn.Module()
|
||||
pipeline.transformer = _SingleBlockModel(num_blocks=2)
|
||||
pipeline.text_encoder = _PlainEncoder()
|
||||
|
||||
with pytest.raises(ValueError, match="Selected text encoder 'text_encoder' requires"):
|
||||
resolve_offload_plan(pipeline, _config({"text_encoder"}))
|
||||
|
||||
def test_staged_component_requires_the_explicit_lifecycle(self):
|
||||
class Pipeline(nn.Module):
|
||||
_offload_plan = OffloadPlan(on_demand_component_paths=frozenset({"text_encoder"}))
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.transformer = _SingleBlockModel(num_blocks=2)
|
||||
self.text_encoder = _PlainEncoder()
|
||||
|
||||
with pytest.raises(ValueError, match="must implement load_to_device"):
|
||||
resolve_offload_plan(Pipeline(), _config({"text_encoder"}))
|
||||
|
||||
def test_single_block_dit_is_rejected_for_layer_offload(self):
|
||||
pipeline = nn.Module()
|
||||
pipeline.transformer = _SingleBlockModel(num_blocks=1)
|
||||
|
||||
with pytest.raises(ValueError, match="requires at least two streamable"):
|
||||
resolve_offload_plan(pipeline, _config({"dit"}))
|
||||
|
||||
def test_encoder_allgather_requires_declared_replication(self):
|
||||
config = _config(
|
||||
{"text_encoder"},
|
||||
strategy=OffloadStrategy.DISTRIBUTED_LAYER_WISE,
|
||||
dp_size=2,
|
||||
dlo_transfers={"dit": "rank-local", "text_encoder": "allgather"},
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="not declared replicated"):
|
||||
resolve_offload_plan(_StagedComponentPipeline(), config)
|
||||
|
||||
def test_two_dits_cannot_own_the_same_blocks(self):
|
||||
class Pipeline(nn.Module):
|
||||
_dit_modules: ClassVar[list[str]] = ["transformer", "transformer_2"]
|
||||
_encoder_modules: ClassVar[list[str]] = []
|
||||
_vae_modules: ClassVar[list[str]] = []
|
||||
_resident_modules: ClassVar[list[str]] = []
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.transformer = _SingleBlockModel(num_blocks=2)
|
||||
self.transformer_2 = _SingleBlockModel(num_blocks=2)
|
||||
self.transformer_2.blocks = self.transformer.blocks
|
||||
|
||||
with pytest.raises(ValueError, match="claimed by both"):
|
||||
resolve_offload_plan(Pipeline(), _config({"dit"}))
|
||||
|
||||
def test_legacy_selection_keeps_unstreamable_components(self):
|
||||
pipeline = nn.Module()
|
||||
pipeline.transformer = _SingleBlockModel(num_blocks=1)
|
||||
pipeline.text_encoder = _PlainEncoder()
|
||||
|
||||
resolved = resolve_offload_plan(pipeline, _config())
|
||||
|
||||
assert resolved.dits[0].stacks == ()
|
||||
assert resolved.encoders[0].stacks == ()
|
||||
|
||||
|
||||
class TestPurity:
|
||||
def _snapshot(self, pipeline: nn.Module):
|
||||
return {
|
||||
"devices": [(name, tensor.device) for name, tensor in pipeline.named_parameters()],
|
||||
"attrs": {name: sorted(vars(module)) for name, module in pipeline.named_modules()},
|
||||
}
|
||||
|
||||
def test_resolution_does_not_touch_the_model(self):
|
||||
pipeline = _StagedComponentPipeline()
|
||||
before = self._snapshot(pipeline)
|
||||
|
||||
resolve_offload_plan(pipeline, _config({"dit", "text_encoder"}))
|
||||
|
||||
assert self._snapshot(pipeline) == before
|
||||
assert pipeline.text_encoder.offload_calls == 0
|
||||
assert pipeline.text_encoder.to_calls == 0
|
||||
assert pipeline.vae.to_calls == 0
|
||||
|
||||
def test_resolution_is_repeatable(self):
|
||||
pipeline = _WanStylePipeline()
|
||||
config = _config({"dit", "text_encoder"})
|
||||
|
||||
first = resolve_offload_plan(pipeline, config)
|
||||
second = resolve_offload_plan(pipeline, config)
|
||||
|
||||
assert [component.path for component in first.components] == [component.path for component in second.components]
|
||||
for left, right in zip(first.components, second.components, strict=True):
|
||||
assert left.selected == right.selected
|
||||
assert left.on_demand == right.on_demand
|
||||
assert [list(stack.blocks) for stack in left.stacks] == [list(stack.blocks) for stack in right.stacks]
|
||||
|
||||
def test_backend_enable_rejects_before_touching_earlier_components(self, patched_offload_runtime):
|
||||
class Pipeline(nn.Module):
|
||||
_dit_modules: ClassVar[list[str]] = ["transformer"]
|
||||
_encoder_modules: ClassVar[list[str]] = ["text_encoder", "text_encoder_2"]
|
||||
_vae_modules: ClassVar[list[str]] = ["vae"]
|
||||
_resident_modules: ClassVar[list[str]] = []
|
||||
_offload_plan = OffloadPlan(
|
||||
encoder_component_types={
|
||||
"text_encoder": "text_encoder",
|
||||
"text_encoder_2": "text_encoder",
|
||||
},
|
||||
encoder_block_attrs={"text_encoder": ("encoder.block",)},
|
||||
)
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.transformer = _SingleBlockModel(num_blocks=2)
|
||||
self.text_encoder = _PlainEncoder()
|
||||
self.text_encoder_2 = _PlainEncoder()
|
||||
self.vae = _StagedVAE()
|
||||
|
||||
pipeline = Pipeline()
|
||||
backend = LayerWiseOffloadBackend(_config({"text_encoder"}), CPU)
|
||||
|
||||
with pytest.raises(ValueError, match="Selected text encoder 'text_encoder_2' requires"):
|
||||
backend.enable(pipeline)
|
||||
|
||||
assert not backend.enabled
|
||||
assert not getattr(pipeline.text_encoder, "_omni_layerwise_enabled", False)
|
||||
for block in pipeline.text_encoder.encoder.block:
|
||||
assert getattr(block, "_hook_registry", None) is None
|
||||
assert pipeline.vae.to_calls == 0
|
||||
@@ -131,7 +131,7 @@ class TestCreateDefaultDiffusion:
|
||||
|
||||
def test_dtype_serialized_as_string(self):
|
||||
stages = StageConfigFactory.create_default_diffusion({"dtype": torch.float16, "model": "x"})
|
||||
assert stages[0]["engine_args"]["dtype"] == "torch.float16"
|
||||
assert stages[0]["engine_args"]["dtype"] == "float16"
|
||||
|
||||
def test_cache_backend_defaults_to_none(self):
|
||||
stages = StageConfigFactory.create_default_diffusion({"model": "x"})
|
||||
|
||||
@@ -15,6 +15,7 @@ from pytest_mock import MockerFixture
|
||||
|
||||
import vllm_omni.diffusion.worker.diffusion_model_runner as model_runner_module
|
||||
from tests.helpers.mark import hardware_test
|
||||
from vllm_omni.config.config_factory import StageConfigFactory
|
||||
from vllm_omni.diffusion.data import DiffusionOutput
|
||||
from vllm_omni.diffusion.diffusion_engine import DiffusionEngine
|
||||
from vllm_omni.diffusion.diffusion_kv.config import DiffusionKVCacheMode
|
||||
@@ -46,7 +47,6 @@ from vllm_omni.diffusion.worker.diffusion_model_runner import DiffusionModelRunn
|
||||
from vllm_omni.diffusion.worker.diffusion_worker import DiffusionWorker
|
||||
from vllm_omni.diffusion.worker.input_batch import InputBatch
|
||||
from vllm_omni.diffusion.worker.utils import RunnerOutput, StepRequestState
|
||||
from vllm_omni.engine.async_omni_engine import AsyncOmniEngine
|
||||
from vllm_omni.errors import OmniClientError
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
@@ -1182,7 +1182,7 @@ class TestSupportedPipelines:
|
||||
"""Step-execution protocol checks for supported pipelines."""
|
||||
|
||||
def test_default_stage_config_includes_step_execution(self):
|
||||
stage_cfg = AsyncOmniEngine._create_default_diffusion_stage_cfg(
|
||||
stage_cfg = StageConfigFactory.create_default_diffusion(
|
||||
{
|
||||
"step_execution": True,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import hashlib
|
||||
|
||||
import av
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from vllm_omni.diffusion.utils.media_utils import ChunkedMP4Encoder, mux_av_video_audio_bytes
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu, pytest.mark.diffusion]
|
||||
|
||||
|
||||
def _frames() -> np.ndarray:
|
||||
rng = np.random.default_rng(6872)
|
||||
return rng.integers(0, 256, size=(8, 16, 24, 3), dtype=np.uint8)
|
||||
|
||||
|
||||
def test_chunked_mp4_is_byte_identical_to_whole_mux() -> None:
|
||||
frames = _frames()
|
||||
baseline = mux_av_video_audio_bytes(
|
||||
(av.VideoFrame.from_ndarray(frame, format="rgb24") for frame in frames),
|
||||
width=24,
|
||||
height=16,
|
||||
fps=24,
|
||||
video_codec_options={"threads": "1"},
|
||||
)
|
||||
encoder = ChunkedMP4Encoder(
|
||||
width=24,
|
||||
height=16,
|
||||
fps=24,
|
||||
max_pending=2,
|
||||
video_codec_options={"threads": "1"},
|
||||
)
|
||||
for start in (0, 1, 5):
|
||||
stop = {0: 1, 1: 5, 5: len(frames)}[start]
|
||||
encoder.push(np.ascontiguousarray(frames[start:stop]))
|
||||
chunked = encoder.finish()
|
||||
assert chunked == baseline
|
||||
assert hashlib.sha256(chunked).digest() == hashlib.sha256(baseline).digest()
|
||||
|
||||
audio = np.zeros((2, 320), dtype=np.float32)
|
||||
baseline_audio = mux_av_video_audio_bytes(
|
||||
(av.VideoFrame.from_ndarray(frame, format="rgb24") for frame in frames),
|
||||
width=24,
|
||||
height=16,
|
||||
fps=24,
|
||||
audio_waveform=audio,
|
||||
audio_sample_rate=32000,
|
||||
video_codec_options={"threads": "1"},
|
||||
)
|
||||
encoder_audio = ChunkedMP4Encoder(
|
||||
width=24,
|
||||
height=16,
|
||||
fps=24,
|
||||
audio_waveform=audio,
|
||||
audio_sample_rate=32000,
|
||||
video_codec_options={"threads": "1"},
|
||||
)
|
||||
encoder_audio.push(frames)
|
||||
assert encoder_audio.finish() == baseline_audio
|
||||
|
||||
|
||||
def test_chunked_mp4_abort_joins_worker() -> None:
|
||||
encoder = ChunkedMP4Encoder(width=24, height=16, fps=24)
|
||||
encoder.push(_frames()[:1])
|
||||
encoder.abort()
|
||||
assert not encoder._thread.is_alive()
|
||||
with pytest.raises(RuntimeError, match="already closed"):
|
||||
encoder.push(_frames()[:1])
|
||||
|
||||
|
||||
def test_chunked_mp4_validates_shape_and_dtype() -> None:
|
||||
encoder = ChunkedMP4Encoder(width=24, height=16, fps=24)
|
||||
with pytest.raises(ValueError, match="shape"):
|
||||
encoder.push(np.zeros((16, 24, 3), dtype=np.uint8))
|
||||
with pytest.raises(ValueError, match="dtype"):
|
||||
encoder.push(np.zeros((1, 16, 24, 3), dtype=np.float32))
|
||||
encoder.abort()
|
||||
|
||||
|
||||
def test_chunked_mp4_close_returns_encoded_bytes() -> None:
|
||||
import io
|
||||
|
||||
encoder = ChunkedMP4Encoder(width=24, height=16, fps=24)
|
||||
encoder.push(_frames())
|
||||
result = encoder.close()
|
||||
assert result == encoder.finish() == encoder.close()
|
||||
with av.open(io.BytesIO(result)) as container:
|
||||
assert len(list(container.decode(video=0))) == len(_frames())
|
||||
|
||||
|
||||
def test_chunked_mp4_failure_during_push(monkeypatch) -> None:
|
||||
from threading import Event
|
||||
|
||||
from vllm_omni.diffusion.utils import media_utils
|
||||
|
||||
fail = Event()
|
||||
draining = Event()
|
||||
error = RuntimeError("encoding failed")
|
||||
|
||||
def mux(*args, **kwargs):
|
||||
assert fail.wait(5)
|
||||
raise error
|
||||
|
||||
monkeypatch.setattr(media_utils, "mux_av_video_audio_bytes", mux)
|
||||
drain = ChunkedMP4Encoder._drain_until_done
|
||||
|
||||
def notified_drain(self):
|
||||
draining.set()
|
||||
drain(self)
|
||||
|
||||
monkeypatch.setattr(ChunkedMP4Encoder, "_drain_until_done", notified_drain)
|
||||
encoder = ChunkedMP4Encoder(width=24, height=16, fps=24)
|
||||
put = encoder._queue.put
|
||||
|
||||
def fail_before_put(item):
|
||||
fail.set()
|
||||
assert draining.wait(5)
|
||||
put(item)
|
||||
|
||||
monkeypatch.setattr(encoder._queue, "put", fail_before_put)
|
||||
try:
|
||||
with pytest.raises(RuntimeError, match="encoding failed") as exc:
|
||||
encoder.push(_frames())
|
||||
assert exc.value is error
|
||||
with pytest.raises(RuntimeError, match="encoding failed"):
|
||||
encoder.finish()
|
||||
finally:
|
||||
fail.set()
|
||||
encoder.abort()
|
||||
assert not encoder._thread.is_alive()
|
||||
|
||||
|
||||
def test_chunked_mp4_flush_failure_does_not_hang(monkeypatch) -> None:
|
||||
from threading import Thread
|
||||
|
||||
from vllm_omni.diffusion.utils import media_utils
|
||||
|
||||
error = RuntimeError("flush failed")
|
||||
|
||||
def mux(frames, **kwargs):
|
||||
list(frames)
|
||||
raise error
|
||||
|
||||
monkeypatch.setattr(media_utils, "mux_av_video_audio_bytes", mux)
|
||||
encoder = ChunkedMP4Encoder(width=24, height=16, fps=24)
|
||||
encoder.push(_frames())
|
||||
errors = []
|
||||
|
||||
def finish():
|
||||
try:
|
||||
encoder.finish()
|
||||
except RuntimeError as exc:
|
||||
errors.append(exc)
|
||||
|
||||
closer = Thread(target=finish, daemon=True)
|
||||
closer.start()
|
||||
closer.join(5)
|
||||
try:
|
||||
assert not closer.is_alive(), "finish hung after the worker consumed its sentinel"
|
||||
assert errors == [error]
|
||||
finally:
|
||||
if closer.is_alive():
|
||||
encoder._send_done()
|
||||
closer.join(5)
|
||||
|
||||
|
||||
def test_chunked_mp4_abort_discards_pending_chunks(monkeypatch) -> None:
|
||||
from threading import Event, Thread
|
||||
|
||||
from vllm_omni.diffusion.utils import media_utils
|
||||
|
||||
entered = Event()
|
||||
release = Event()
|
||||
done_sent = Event()
|
||||
encoded = []
|
||||
|
||||
def mux(frames, **kwargs):
|
||||
encoded.append(next(frames))
|
||||
entered.set()
|
||||
assert release.wait(5)
|
||||
encoded.extend(frames)
|
||||
return b"unused"
|
||||
|
||||
monkeypatch.setattr(media_utils, "mux_av_video_audio_bytes", mux)
|
||||
encoder = ChunkedMP4Encoder(width=24, height=16, fps=24, max_pending=1)
|
||||
send_done = encoder._send_done
|
||||
|
||||
def notified_done():
|
||||
send_done()
|
||||
done_sent.set()
|
||||
|
||||
monkeypatch.setattr(encoder, "_send_done", notified_done)
|
||||
encoder.push(_frames()[:1])
|
||||
assert entered.wait(5)
|
||||
encoder.push(_frames()[1:])
|
||||
closer = Thread(target=encoder.abort, daemon=True)
|
||||
closer.start()
|
||||
try:
|
||||
assert done_sent.wait(5), "abort waited for encoding before discarding the pending queue"
|
||||
finally:
|
||||
release.set()
|
||||
closer.join(5)
|
||||
assert not closer.is_alive()
|
||||
assert len(encoded) == 1
|
||||
with pytest.raises(RuntimeError, match="aborted"):
|
||||
encoder.finish()
|
||||
@@ -1,5 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""E2E accuracy guard against a pinned Lightricks LTX pipeline revision.
|
||||
|
||||
@@ -22,11 +22,11 @@ from typing import Literal
|
||||
import numpy as np
|
||||
import pytest
|
||||
import torch
|
||||
from huggingface_hub import hf_hub_download, snapshot_download
|
||||
from torchmetrics.image import PeakSignalNoiseRatio, StructuralSimilarityIndexMeasure
|
||||
|
||||
from tests.e2e.accuracy.helpers import reset_artifact_dir
|
||||
from tests.helpers.mark import hardware_test
|
||||
from vllm_omni.transformers_utils.repo_utils import hf_api
|
||||
|
||||
OFFICIAL_REPOSITORY = "https://github.com/Lightricks/LTX-2.git"
|
||||
OFFICIAL_REVISION = "9377758131b1ffde4b7f766804590a6617bf2ab9"
|
||||
@@ -326,7 +326,7 @@ def _resolve_model(case: LTXAccuracyCase) -> Path:
|
||||
if revision is None and model_id == case.model_id:
|
||||
revision = case.model_revision
|
||||
return Path(
|
||||
snapshot_download(
|
||||
hf_api().snapshot_download(
|
||||
repo_id=model_id,
|
||||
revision=revision,
|
||||
allow_patterns=[
|
||||
@@ -359,7 +359,7 @@ def _resolve_gemma_root(case: LTXAccuracyCase, model: Path) -> Path:
|
||||
if configured_model and Path(configured_model).is_dir():
|
||||
return Path(configured_model)
|
||||
return Path(
|
||||
snapshot_download(
|
||||
hf_api().snapshot_download(
|
||||
repo_id=case.gemma_model_id,
|
||||
revision=case.gemma_model_revision,
|
||||
allow_patterns=[
|
||||
@@ -383,7 +383,7 @@ def _resolve_artifact(artifact: LTXArtifact, model: Path | None = None) -> Path:
|
||||
if model_path.is_file():
|
||||
return model_path
|
||||
return Path(
|
||||
hf_hub_download(
|
||||
hf_api().hf_hub_download(
|
||||
repo_id=artifact.repo_id,
|
||||
repo_type=None if artifact.repo_type == "model" else artifact.repo_type,
|
||||
filename=artifact.filename,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""E2E test that follows the EXACT same flow as
|
||||
``verl-omni/tests/workers/rollout/rollout_vllm/test_vllm_omni_generate.py``
|
||||
@@ -35,7 +35,6 @@ from uuid import uuid4
|
||||
import pytest
|
||||
import ray
|
||||
import torch
|
||||
from huggingface_hub import snapshot_download
|
||||
from omegaconf import OmegaConf
|
||||
from transformers import AutoTokenizer
|
||||
|
||||
@@ -46,6 +45,7 @@ from tests.e2e.features.helpers.verl_omni_server import (
|
||||
vLLMOmniHttpServerLocal,
|
||||
)
|
||||
from tests.helpers.mark import hardware_test
|
||||
from vllm_omni.transformers_utils.repo_utils import hf_api
|
||||
|
||||
MODEL = "tiny-random/Qwen-Image"
|
||||
TOKENIZER_MODEL = "Qwen/Qwen2-1.5B-Instruct"
|
||||
@@ -55,7 +55,7 @@ _MIN_PROMPT_TOKENS = 35
|
||||
def _resolve_model_path(repo_id: str) -> str:
|
||||
if os.path.isdir(repo_id):
|
||||
return repo_id
|
||||
return snapshot_download(repo_id=repo_id)
|
||||
return hf_api().snapshot_download(repo_id=repo_id)
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""E2E offline tests for Audio8 TTS Preview (DualAR, 44.1 kHz codec).
|
||||
|
||||
The prompt is pre-tokenized here (not built from ``mm_processor_kwargs``)
|
||||
because Audio8 TTS shares Fish Speech's protocol: text-only prompts are plain
|
||||
token ids, and voice-clone prompts are a placeholder of the exact final length
|
||||
whose real embeddings are built model-side from the encoded reference audio.
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.helpers.mark import hardware_test
|
||||
from tests.helpers.runtime import OmniRunner, OmniRunnerHandler
|
||||
from tests.helpers.stage_config import get_deploy_config_path
|
||||
|
||||
MODEL = os.environ.get("AUDIO8_TTS_MODEL_PATH", "Audio8/Audio8-TTS-Preview-0.6b")
|
||||
DEPLOY_CONFIG = get_deploy_config_path("audio8_tts.yaml")
|
||||
SAMPLE_RATE = 44100
|
||||
TEXT = "The weather is nice today, perfect for a walk in the park."
|
||||
|
||||
# Four distinct inputs for the concurrency test: distinct text is required so a
|
||||
# leaked per-request codec buffer (which would make two requests decode to the
|
||||
# same audio) actually fails the pairwise-difference assertion.
|
||||
CONCURRENT_TEXTS = [
|
||||
"The weather is nice today, perfect for a walk in the park.",
|
||||
"She sold seashells by the seashore all through the summer.",
|
||||
"Our train departs at a quarter past nine tomorrow morning.",
|
||||
"He planted rows of tomatoes and basil behind the old house.",
|
||||
]
|
||||
|
||||
# The checkpoint registers its own `arktts` config in vllm-omni, so remote code
|
||||
# must stay disabled (transformers would otherwise prefer the checkpoint's
|
||||
# auto_map and bypass the Qwen2-shaped view Qwen2Model needs).
|
||||
_OMNI_RUNNER_PARAM = (MODEL, DEPLOY_CONFIG, {"trust_remote_code": False})
|
||||
|
||||
pytestmark = pytest.mark.parametrize("omni_runner", [_OMNI_RUNNER_PARAM], indirect=True)
|
||||
|
||||
|
||||
def _text_only_prompt(text: str = TEXT) -> dict:
|
||||
from transformers import AutoTokenizer
|
||||
|
||||
from vllm_omni.model_executor.models.audio8_tts.prompt_utils import build_text_only_prompt_ids
|
||||
|
||||
tokenizer = AutoTokenizer.from_pretrained(MODEL)
|
||||
prompt_ids, normalized_text = build_text_only_prompt_ids(tokenizer, text)
|
||||
return {"prompt_token_ids": prompt_ids, "additional_information": {"text": [normalized_text]}}
|
||||
|
||||
|
||||
# At ``core_model`` (L1/L2) the harness patches every stage to
|
||||
# ``load_format: dummy``, so the AR runs on random weights: it never emits EOS
|
||||
# and always generates to ``max_tokens`` (1024 frames ~= 47.5 s). Duration
|
||||
# bounds are therefore only meaningful once real weights load, at
|
||||
# ``advanced_model`` / ``full_model``.
|
||||
_REAL_WEIGHT_RUN_LEVELS = frozenset({"advanced_model", "full_model"})
|
||||
|
||||
|
||||
def _duration_bounds(run_level: str) -> dict[str, float]:
|
||||
if run_level not in _REAL_WEIGHT_RUN_LEVELS:
|
||||
return {}
|
||||
return {"min_duration_s": 0.5, "max_duration_s": 30.0}
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
@pytest.mark.advanced_model
|
||||
@pytest.mark.tts
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
def test_text_to_audio_001(omni_runner: OmniRunner, run_level: str) -> None:
|
||||
"""Default deploy, single request, text-only synthesis.
|
||||
|
||||
Deploy Setting: audio8_tts.yaml
|
||||
Input Modal: text
|
||||
Output Modal: audio
|
||||
"""
|
||||
prompt = _text_only_prompt()
|
||||
request_config = {
|
||||
"input": TEXT,
|
||||
"prompt_token_ids": prompt["prompt_token_ids"],
|
||||
"additional_information": prompt["additional_information"],
|
||||
"response_format": "wav",
|
||||
"expected_sample_rate": SAMPLE_RATE,
|
||||
**_duration_bounds(run_level),
|
||||
}
|
||||
OmniRunnerHandler(omni_runner).send_tokenized_tts_request(request_config)
|
||||
|
||||
|
||||
@pytest.mark.advanced_model
|
||||
@pytest.mark.tts
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
def test_text_to_audio_concurrent_002(omni_runner: OmniRunner, run_level: str) -> None:
|
||||
"""Four concurrent requests with distinct text: stage 0 runs ``max_num_seqs: 4``.
|
||||
|
||||
Per-request codec state is keyed by request id. The four inputs are
|
||||
deliberately distinct and the decoded outputs are asserted pairwise
|
||||
different, so leaked codec state (which would make two requests decode to
|
||||
identical audio) fails here, and only here.
|
||||
"""
|
||||
prompts = [_text_only_prompt(text) for text in CONCURRENT_TEXTS]
|
||||
request_config = {
|
||||
"input": CONCURRENT_TEXTS[0],
|
||||
"prompt_token_ids": [p["prompt_token_ids"] for p in prompts],
|
||||
"additional_information": [p["additional_information"] for p in prompts],
|
||||
"response_format": "wav",
|
||||
"expected_sample_rate": SAMPLE_RATE,
|
||||
"assert_distinct_outputs": True,
|
||||
**_duration_bounds(run_level),
|
||||
}
|
||||
OmniRunnerHandler(omni_runner).send_tokenized_tts_request(request_config)
|
||||
@@ -1,5 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""
|
||||
Offline E2E smoke test for CosyVoice3 zero-shot reference inference.
|
||||
|
||||
@@ -20,7 +20,6 @@ from pathlib import Path
|
||||
import numpy as np
|
||||
import pytest
|
||||
import soundfile as sf
|
||||
from huggingface_hub import snapshot_download
|
||||
from vllm.sampling_params import SamplingParams
|
||||
|
||||
from tests.helpers.mark import hardware_test
|
||||
@@ -29,6 +28,7 @@ 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.transformers_utils.configs.cosyvoice3 import CosyVoice3Config
|
||||
from vllm_omni.transformers_utils.repo_utils import hf_api
|
||||
|
||||
MODEL = "FunAudioLLM/Fun-CosyVoice3-0.5B-2512"
|
||||
MODEL_DIR_ENV = "VLLM_OMNI_COSYVOICE3_MODEL_DIR"
|
||||
@@ -58,7 +58,7 @@ def _resolve_model_dir() -> Path:
|
||||
override = os.environ.get(MODEL_DIR_ENV)
|
||||
if override:
|
||||
return Path(override).expanduser().resolve()
|
||||
return Path(snapshot_download(MODEL, allow_patterns=["*"]))
|
||||
return Path(hf_api().snapshot_download(MODEL, allow_patterns=["*"]))
|
||||
|
||||
|
||||
def _reference_zero_shot_stage0_sampling(*, text: str) -> SamplingParams:
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""
|
||||
End-to-end test for MammothModa2 text-to-image generation.
|
||||
|
||||
@@ -19,12 +22,12 @@ from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from huggingface_hub import snapshot_download
|
||||
from vllm.sampling_params import SamplingParams
|
||||
|
||||
from tests.helpers.mark import hardware_test
|
||||
from tests.helpers.runtime import OmniRunner
|
||||
from tests.helpers.stage_config import get_deploy_config_path
|
||||
from vllm_omni.transformers_utils.repo_utils import hf_api
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Constants
|
||||
@@ -64,7 +67,7 @@ _PIXEL_SAMPLE_COORDS = [
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
def _load_t2i_gen_config(repo_id: str) -> dict:
|
||||
weights_dir = Path(snapshot_download(repo_id))
|
||||
weights_dir = Path(hf_api().snapshot_download(repo_id))
|
||||
cfg_path = weights_dir / "t2i_generation_config.json"
|
||||
if not cfg_path.exists():
|
||||
pytest.skip(f"t2i_generation_config.json not found at {cfg_path}")
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""E2E offline inference tests for MOSS-TTS-Realtime (MossTTSRealtime, 1.7B).
|
||||
|
||||
Uses the standard omni_runner + pytestmark pattern (one module-scoped engine
|
||||
@@ -160,12 +160,13 @@ def _build_request(ref_audio_path: str, text: str) -> dict:
|
||||
Frees the codec model before returning to avoid competing with the
|
||||
running vllm engine for GPU/CPU memory.
|
||||
"""
|
||||
from huggingface_hub import snapshot_download
|
||||
from transformers import AutoModel, AutoTokenizer
|
||||
|
||||
from vllm_omni.transformers_utils.repo_utils import hf_api
|
||||
|
||||
# Step 1: locate the realtime processor module in the snapshot.
|
||||
try:
|
||||
snap_dir = Path(snapshot_download(repo_id=MODEL))
|
||||
snap_dir = Path(hf_api().snapshot_download(repo_id=MODEL))
|
||||
except Exception as exc:
|
||||
msg = f"Cannot locate snapshot for {MODEL}: {exc}"
|
||||
if os.environ.get("MOSS_TTS_SKIP_ON_NET_FAIL"):
|
||||
|
||||
@@ -12,7 +12,6 @@ from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from huggingface_hub import snapshot_download
|
||||
|
||||
from tests.helpers.runtime import OmniServerParams, get_model_prefix
|
||||
from tests.helpers.stage_config import (
|
||||
@@ -20,6 +19,7 @@ from tests.helpers.stage_config import (
|
||||
get_deploy_duplex_max_sessions,
|
||||
modify_stage_config,
|
||||
)
|
||||
from vllm_omni.transformers_utils.repo_utils import hf_api
|
||||
|
||||
MODEL = "openbmb/MiniCPM-o-4_5"
|
||||
DEPLOY_CONFIG_REL = "minicpmo_4_5.yaml"
|
||||
@@ -111,7 +111,7 @@ def resolve_ref_audio() -> Path:
|
||||
model_prefix = get_model_prefix()
|
||||
model_root = Path(model_prefix) / MODEL if model_prefix else Path(MODEL)
|
||||
if not model_root.is_dir():
|
||||
model_root = Path(snapshot_download(MODEL, local_files_only=True))
|
||||
model_root = Path(hf_api().snapshot_download(MODEL, local_files_only=True))
|
||||
ref_audio = model_root / REF_AUDIO_RELATIVE_PATH
|
||||
if not ref_audio.is_file():
|
||||
raise FileNotFoundError(f"MiniCPM-o checkpoint ref audio is missing: {ref_audio}")
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""E2E online tests for Audio8 TTS Preview via /v1/audio/speech.
|
||||
|
||||
Real model inference (no mocks): text-only synthesis, streaming, and zero-shot
|
||||
voice cloning. The reference audio is inlined as a base64 data URL because CI
|
||||
hosts cannot fetch external URLs.
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.helpers.mark import hardware_test
|
||||
from tests.helpers.media import get_asset_path
|
||||
from tests.helpers.runtime import OmniServerParams
|
||||
from tests.helpers.stage_config import get_deploy_config_path
|
||||
|
||||
MODEL = os.environ.get("AUDIO8_TTS_MODEL_PATH", "Audio8/Audio8-TTS-Preview-0.6b")
|
||||
DEFAULT_AUDIO_SPEECH_TIMEOUT_S = 300.0
|
||||
# The codec decodes at 44.1 kHz; raw PCM carries no header, so assertions that
|
||||
# depend on the rate (HNR pitch search) have to be told explicitly.
|
||||
SAMPLE_RATE = 44100
|
||||
MAX_CONCURRENT = 4
|
||||
|
||||
# ~0.5 s of 44.1 kHz mono PCM_16 WAV.
|
||||
_MIN_AUDIO_BYTES = 40_000
|
||||
|
||||
# Reused vendored asset (3.5 s, Chinese) plus its exact transcript: Audio8 TTS
|
||||
# requires the reference transcript to match the recording.
|
||||
REF_AUDIO_URL = get_asset_path("cosyvoice3/zero_shot_prompt.wav", as_data_url=True)
|
||||
REF_TEXT = "希望你以后能够做的比我还好呦。"
|
||||
|
||||
|
||||
def get_prompt(prompt_type: str = "en") -> str:
|
||||
prompts = {
|
||||
"en": "The weather is nice today, perfect for a walk in the park.",
|
||||
"zh": "今天天气很好,非常适合去公园散步。",
|
||||
}
|
||||
return prompts.get(prompt_type, prompts["en"])
|
||||
|
||||
|
||||
tts_server_params = [
|
||||
pytest.param(
|
||||
OmniServerParams(
|
||||
model=MODEL,
|
||||
stage_config_path=get_deploy_config_path("audio8_tts.yaml"),
|
||||
# No --trust-remote-code: vllm-omni owns the `arktts` config.
|
||||
server_args=["--disable-log-stats"],
|
||||
),
|
||||
id="audio8_tts",
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
@pytest.mark.advanced_model
|
||||
@pytest.mark.tts
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
|
||||
def test_text_to_audio_001(omni_server, openai_client) -> None:
|
||||
"""Baseline smoke: default deploy, non-streaming WAV.
|
||||
|
||||
Deploy Setting: audio8_tts.yaml
|
||||
Input Modal: text
|
||||
Output Modal: audio
|
||||
Input Setting: stream=False
|
||||
Datasets: few requests (max_num_seqs=4)
|
||||
"""
|
||||
request_config = {
|
||||
"model": omni_server.model,
|
||||
"input": get_prompt(),
|
||||
"stream": False,
|
||||
"timeout": DEFAULT_AUDIO_SPEECH_TIMEOUT_S,
|
||||
"response_format": "wav",
|
||||
"min_audio_bytes": _MIN_AUDIO_BYTES,
|
||||
}
|
||||
openai_client.send_audio_speech_request(request_config, request_num=MAX_CONCURRENT)
|
||||
|
||||
|
||||
@pytest.mark.advanced_model
|
||||
@pytest.mark.tts
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
|
||||
def test_text_to_audio_streaming_002(omni_server, openai_client) -> None:
|
||||
"""Streaming PCM: exercises the async_chunk path end to end.
|
||||
|
||||
Deploy Setting: audio8_tts.yaml (async_chunk: true)
|
||||
Input Setting: stream=True, response_format=pcm
|
||||
"""
|
||||
request_config = {
|
||||
"model": omni_server.model,
|
||||
"input": get_prompt(),
|
||||
"stream": True,
|
||||
"stream_format": "audio",
|
||||
"timeout": DEFAULT_AUDIO_SPEECH_TIMEOUT_S,
|
||||
"response_format": "pcm",
|
||||
"min_audio_bytes": _MIN_AUDIO_BYTES,
|
||||
# Raw PCM has no header: without this the harness assumes 24 kHz and the
|
||||
# HNR pitch search lands on 147-735 Hz instead of 80-400 Hz, scoring
|
||||
# clean 44.1 kHz speech ~1.9 dB too low.
|
||||
"expected_sample_rate": SAMPLE_RATE,
|
||||
}
|
||||
openai_client.send_audio_speech_request(request_config)
|
||||
|
||||
|
||||
@pytest.mark.advanced_model
|
||||
@pytest.mark.tts
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
|
||||
def test_voice_clone_003(omni_server, openai_client) -> None:
|
||||
"""Zero-shot voice cloning: the reference audio is encoded model-side and
|
||||
its codec codes are spliced into the prompt.
|
||||
|
||||
Input Modal: text + ref_audio + ref_text
|
||||
"""
|
||||
request_config = {
|
||||
"model": omni_server.model,
|
||||
"input": get_prompt("zh"),
|
||||
"ref_audio": REF_AUDIO_URL,
|
||||
"ref_text": REF_TEXT,
|
||||
"stream": False,
|
||||
"timeout": DEFAULT_AUDIO_SPEECH_TIMEOUT_S,
|
||||
"response_format": "wav",
|
||||
"min_audio_bytes": _MIN_AUDIO_BYTES,
|
||||
}
|
||||
openai_client.send_audio_speech_request(request_config)
|
||||
|
||||
|
||||
@pytest.mark.advanced_model
|
||||
@pytest.mark.tts
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
|
||||
def test_voice_clone_requires_ref_text_004(omni_server, openai_client) -> None:
|
||||
"""``ref_audio`` without ``ref_text`` must be rejected, not silently
|
||||
synthesized with an untethered voice."""
|
||||
request_config = {
|
||||
"model": omni_server.model,
|
||||
"input": get_prompt(),
|
||||
"ref_audio": REF_AUDIO_URL,
|
||||
"stream": False,
|
||||
"timeout": DEFAULT_AUDIO_SPEECH_TIMEOUT_S,
|
||||
"response_format": "wav",
|
||||
"status_code": (400, 422),
|
||||
"err_message": "ref_text",
|
||||
}
|
||||
openai_client.send_audio_speech_request(request_config)
|
||||
|
||||
|
||||
@pytest.mark.advanced_model
|
||||
@pytest.mark.tts
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
|
||||
def test_empty_input_is_rejected_005(omni_server, openai_client) -> None:
|
||||
request_config = {
|
||||
"model": omni_server.model,
|
||||
"input": " ",
|
||||
"stream": False,
|
||||
"timeout": DEFAULT_AUDIO_SPEECH_TIMEOUT_S,
|
||||
"response_format": "wav",
|
||||
"status_code": (400, 422),
|
||||
"err_message": "Input text cannot be empty",
|
||||
}
|
||||
openai_client.send_audio_speech_request(request_config)
|
||||
@@ -1,5 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""End-to-end online serving test for GR00T N1.7 through the OpenPI robot endpoint."""
|
||||
|
||||
import os
|
||||
@@ -29,8 +29,7 @@ test_params = [
|
||||
OmniServerParams(
|
||||
model=MODEL,
|
||||
stage_config_path=get_deploy_config_path("Gr00tN1d7.yaml"),
|
||||
server_args=["--disable-log-stats"],
|
||||
env_dict={"VLLM_DISABLE_COMPILE_CACHE": "1", "GR00T_NOISE_SEED": "42"},
|
||||
env_dict={"VLLM_DISABLE_COMPILE_CACHE": "1"},
|
||||
init_timeout=1200,
|
||||
stage_init_timeout=900,
|
||||
),
|
||||
@@ -162,14 +161,14 @@ def test_gr00t_n1d7_openpi_online(omni_server, openai_client) -> None:
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
|
||||
def test_gr00t_n1d7_openpi_precision(omni_server, openai_client) -> None:
|
||||
"""Assert actions match Isaac-GR00T reference (GR00T_NOISE_SEED=42, zero inputs)."""
|
||||
"""Assert actions match Isaac-GR00T reference (request seed=42, zero inputs)."""
|
||||
response = openai_client.send_robot_openpi_ws_request(
|
||||
{
|
||||
"operations": [
|
||||
{"endpoint": "reset", "payload": {}},
|
||||
{
|
||||
"endpoint": "infer",
|
||||
"payload": build_openpi_droid_observation(session_id="gr00t-precision-e2e"),
|
||||
"payload": build_openpi_droid_observation(session_id="gr00t-precision-e2e", seed=42),
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
@@ -30,10 +30,27 @@ from tests.e2e.online_serving.run_minicpmo_realtime_duplex_soft_interrupt import
|
||||
run_soft_interrupt,
|
||||
)
|
||||
from tests.helpers.mark import hardware_test
|
||||
from vllm_omni.entrypoints.duplex.server_vad import (
|
||||
SILERO_VAD_FILENAME,
|
||||
SILERO_VAD_REPO_ID,
|
||||
SILERO_VAD_REVISION,
|
||||
)
|
||||
|
||||
pytestmark = [pytest.mark.full_model, pytest.mark.omni]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def _cached_server_vad_artifact() -> None:
|
||||
"""Cache the pinned ONNX artifact before the Realtime server starts."""
|
||||
from huggingface_hub import hf_hub_download
|
||||
|
||||
hf_hub_download(
|
||||
repo_id=SILERO_VAD_REPO_ID,
|
||||
filename=SILERO_VAD_FILENAME,
|
||||
revision=SILERO_VAD_REVISION,
|
||||
)
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "H100", "npu": "A3"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", SERVER_PARAMS, indirect=True)
|
||||
def test_duplex_admission_and_expiry_reaper(omni_server, tmp_path: Path) -> None:
|
||||
@@ -97,7 +114,7 @@ def test_duplex_soft_interrupt(omni_server, tmp_path: Path) -> None:
|
||||
|
||||
@hardware_test(res={"cuda": "H100"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", SERVER_PARAMS, indirect=True)
|
||||
def test_duplex_server_vad_hard_interrupt(omni_server) -> None:
|
||||
def test_duplex_server_vad_hard_interrupt(_cached_server_vad_artifact, omni_server) -> None:
|
||||
result = asyncio.run(
|
||||
run_server_vad_interrupt(
|
||||
SimpleNamespace(
|
||||
|
||||
@@ -7,7 +7,10 @@ Tests verify that the OmniVoice model generates valid audio when
|
||||
accessed through the standard OpenAI-compatible speech API.
|
||||
"""
|
||||
|
||||
import io
|
||||
import os
|
||||
import wave
|
||||
from collections.abc import Sequence
|
||||
|
||||
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
|
||||
|
||||
@@ -15,7 +18,7 @@ import pytest
|
||||
|
||||
from tests.helpers.mark import hardware_test
|
||||
from tests.helpers.media import get_asset_path
|
||||
from tests.helpers.runtime import OmniServerParams
|
||||
from tests.helpers.runtime import OmniResponse, OmniServerParams
|
||||
from tests.helpers.stage_config import get_deploy_config_path
|
||||
from vllm_omni.entrypoints.openai.serving_speech import _DEFAULT_VOICE_NAME
|
||||
|
||||
@@ -34,6 +37,10 @@ STAGE_CONFIG = get_deploy_config_path("omnivoice.yaml")
|
||||
EXTRA_ARGS = [
|
||||
"--trust-remote-code",
|
||||
"--disable-log-stats",
|
||||
"--max-num-seqs",
|
||||
"8",
|
||||
"--request-batch-max-wait-ms",
|
||||
"50",
|
||||
]
|
||||
TEST_PARAMS = [
|
||||
OmniServerParams(
|
||||
@@ -42,7 +49,14 @@ TEST_PARAMS = [
|
||||
server_args=EXTRA_ARGS,
|
||||
)
|
||||
]
|
||||
|
||||
STEP_EXECUTION_ARGS = EXTRA_ARGS + ["--step-execution"]
|
||||
STEP_EXECUTION_PARAMS = [
|
||||
OmniServerParams(
|
||||
model=MODEL,
|
||||
stage_config_path=STAGE_CONFIG,
|
||||
server_args=STEP_EXECUTION_ARGS,
|
||||
)
|
||||
]
|
||||
# Lower this in ``request_config`` via ``min_audio_bytes`` if a run produces legitimately short WAVs.
|
||||
_DEFAULT_MIN_AUDIO_BYTES = 5000
|
||||
|
||||
@@ -58,6 +72,33 @@ def get_prompt(prompt_type="text"):
|
||||
return prompts.get(prompt_type, prompts["text"])
|
||||
|
||||
|
||||
def _assert_valid_omnivoice_wav_responses(responses: Sequence[OmniResponse]) -> None:
|
||||
"""Validate that every concurrent response contains plausible OmniVoice audio."""
|
||||
audio_shapes: list[tuple[int, int, int, int]] = []
|
||||
for response in responses:
|
||||
audio_bytes = response.audio_bytes
|
||||
assert audio_bytes is not None
|
||||
assert audio_bytes.startswith(b"RIFF")
|
||||
with wave.open(io.BytesIO(audio_bytes), "rb") as wav_file:
|
||||
num_channels = wav_file.getnchannels()
|
||||
sample_width = wav_file.getsampwidth()
|
||||
sample_rate = wav_file.getframerate()
|
||||
num_frames = wav_file.getnframes()
|
||||
assert num_channels == 1
|
||||
assert sample_width == 2
|
||||
assert sample_rate == 24000
|
||||
assert num_frames > 0
|
||||
audio_shapes.append((num_channels, sample_width, sample_rate, num_frames))
|
||||
|
||||
duration_s = num_frames / sample_rate
|
||||
assert 0.1 <= duration_s <= 30.0
|
||||
|
||||
# Identical prompts use the same estimated target length. Their samples may
|
||||
# differ numerically across batch layouts, but the decoded audio shape must
|
||||
# remain consistent across concurrent requests.
|
||||
assert len(set(audio_shapes)) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("omni_server", TEST_PARAMS, indirect=True)
|
||||
class TestOmniVoiceTTS:
|
||||
"""E2E tests for OmniVoice TTS model."""
|
||||
@@ -74,6 +115,57 @@ class TestOmniVoiceTTS:
|
||||
}
|
||||
online_client.send_audio_speech_request(request_config)
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
def test_speech_auto_voice_batch(self, omni_server, openai_client) -> None:
|
||||
"""Test concurrent request-batch TTS generation."""
|
||||
batch_request_config = {
|
||||
"model": omni_server.model,
|
||||
"input": get_prompt("text"),
|
||||
"response_format": "wav",
|
||||
"seed": 42,
|
||||
"min_audio_bytes": _DEFAULT_MIN_AUDIO_BYTES,
|
||||
}
|
||||
batch_r = openai_client.send_audio_speech_request(batch_request_config, request_num=2)
|
||||
assert len(batch_r) == 2
|
||||
_assert_valid_omnivoice_wav_responses(batch_r)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("omni_server", STEP_EXECUTION_PARAMS, indirect=True)
|
||||
class TestOmniVoiceStepExecution:
|
||||
"""E2E tests for OmniVoice TTS model."""
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
def test_speech_auto_voice_step_execution(self, omni_server, openai_client) -> None:
|
||||
"""Test auto voice TTS generation (text only, no reference audio)."""
|
||||
request_config = {
|
||||
"model": omni_server.model,
|
||||
"input": get_prompt("text"),
|
||||
"response_format": "wav",
|
||||
"timeout": 180.0,
|
||||
"min_audio_bytes": _DEFAULT_MIN_AUDIO_BYTES,
|
||||
"extra_params": {
|
||||
"num_inference_steps": 32,
|
||||
},
|
||||
}
|
||||
openai_client.send_audio_speech_request(request_config)
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
def test_speech_auto_voice_batch_step_execution(self, omni_server, openai_client) -> None:
|
||||
"""Test concurrent step-execution TTS generation."""
|
||||
batch_request_config = {
|
||||
"model": omni_server.model,
|
||||
"input": get_prompt("text"),
|
||||
"response_format": "wav",
|
||||
"seed": 42,
|
||||
"min_audio_bytes": _DEFAULT_MIN_AUDIO_BYTES,
|
||||
"extra_params": {
|
||||
"num_inference_steps": 32,
|
||||
},
|
||||
}
|
||||
batch_r = openai_client.send_audio_speech_request(batch_request_config, request_num=2)
|
||||
assert len(batch_r) == 2
|
||||
_assert_valid_omnivoice_wav_responses(batch_r)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("omni_server", TEST_PARAMS, indirect=True)
|
||||
class TestOmniVoiceSeed:
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Cross-mode full-model parity tests for OmniVoice."""
|
||||
|
||||
import os
|
||||
|
||||
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from tests.helpers.mark import hardware_test
|
||||
from tests.helpers.runtime import OmniServer
|
||||
from tests.helpers.stage_config import get_deploy_config_path
|
||||
|
||||
pytestmark = [pytest.mark.slow, pytest.mark.tts]
|
||||
|
||||
MODEL = "k2-fsa/OmniVoice"
|
||||
STAGE_CONFIG = get_deploy_config_path("omnivoice.yaml")
|
||||
PROMPT = "The weather is nice today, perfect for a walk in the park."
|
||||
|
||||
payload = {
|
||||
"model": MODEL,
|
||||
"input": PROMPT,
|
||||
"language": "English",
|
||||
"seed": 42,
|
||||
"response_format": "wav",
|
||||
"extra_params": {"num_inference_steps": 32},
|
||||
}
|
||||
|
||||
|
||||
def _generate_without_graph(server_args: list[str]) -> bytes:
|
||||
with OmniServer(
|
||||
MODEL,
|
||||
server_args,
|
||||
use_omni=True,
|
||||
env_dict={"OMNIVOICE_CUDA_GRAPH": "0"},
|
||||
) as server:
|
||||
response = requests.post(
|
||||
f"http://{server.host}:{server.port}/v1/audio/speech",
|
||||
json=payload,
|
||||
timeout=600,
|
||||
)
|
||||
response.raise_for_status()
|
||||
assert response.content.startswith(b"RIFF")
|
||||
return response.content
|
||||
|
||||
|
||||
def _generate_with_graph(server_args: list[str]) -> bytes:
|
||||
with OmniServer(
|
||||
MODEL,
|
||||
server_args,
|
||||
use_omni=True,
|
||||
) as server:
|
||||
response = requests.post(
|
||||
f"http://{server.host}:{server.port}/v1/audio/speech",
|
||||
json=payload,
|
||||
timeout=600,
|
||||
)
|
||||
response.raise_for_status()
|
||||
assert response.content.startswith(b"RIFF")
|
||||
return response.content
|
||||
|
||||
|
||||
def _common_args() -> list[str]:
|
||||
"""Return the shared B=1 server arguments for parity tests."""
|
||||
return [
|
||||
"--trust-remote-code",
|
||||
"--disable-log-stats",
|
||||
"--deploy-config",
|
||||
STAGE_CONFIG,
|
||||
"--max-num-seqs",
|
||||
"1",
|
||||
]
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
def test_request_mode_and_step_execution_b1_parity_without_graph() -> None:
|
||||
"""B=1 eager request and step modes must produce identical seeded WAV bytes."""
|
||||
common_args = _common_args()
|
||||
|
||||
request_audio = _generate_without_graph(common_args)
|
||||
step_audio = _generate_without_graph([*common_args, "--step-execution", "--enforce-eager"])
|
||||
|
||||
assert request_audio == step_audio
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
def test_request_mode_and_step_execution_b1_parity_with_graph() -> None:
|
||||
"""B=1 Graph request and step modes must produce identical seeded WAV bytes."""
|
||||
common_args = _common_args()
|
||||
|
||||
request_audio = _generate_with_graph(common_args)
|
||||
step_audio = _generate_with_graph([*common_args, "--step-execution", "--enforce-eager"])
|
||||
|
||||
assert request_audio == step_audio
|
||||
@@ -33,6 +33,7 @@ def test_duplex_session_runtime_defaults_are_typed_and_immutable(tmp_path) -> No
|
||||
assert deploy.duplex_session.max_pending_turns_per_session == 4
|
||||
assert deploy.duplex_session.max_sessions == 1
|
||||
assert deploy.duplex_session.completed_append_cache_size == 256
|
||||
assert deploy.duplex_session.server_vad_model_path is None
|
||||
with pytest.raises(FrozenInstanceError):
|
||||
deploy.duplex_session.idle_ttl_s = 1.0 # type: ignore[misc]
|
||||
|
||||
@@ -46,6 +47,29 @@ def test_duplex_session_runtime_accepts_disabled_idle_expiry(tmp_path) -> None:
|
||||
assert deploy.duplex_session.idle_ttl_s is None
|
||||
|
||||
|
||||
def test_duplex_session_runtime_accepts_local_server_vad_model(tmp_path) -> None:
|
||||
deploy_path = tmp_path / "duplex.yaml"
|
||||
deploy_path.write_text(
|
||||
"duplex_session:\n server_vad_model_path: /models/silero_vad.onnx\nstages: []\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
deploy = load_deploy_config(deploy_path)
|
||||
|
||||
assert deploy.duplex_session.server_vad_model_path == "/models/silero_vad.onnx"
|
||||
|
||||
|
||||
def test_duplex_session_runtime_rejects_empty_server_vad_model_path(tmp_path) -> None:
|
||||
deploy_path = tmp_path / "duplex.yaml"
|
||||
deploy_path.write_text(
|
||||
"duplex_session:\n server_vad_model_path: ''\nstages: []\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="server_vad_model_path"):
|
||||
load_deploy_config(deploy_path)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("name", "value"),
|
||||
[
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""
|
||||
Tests for Omni config utils. For stability, these tests should largely be
|
||||
invariant to the specific attributes of vLLM config except in cases where we
|
||||
@@ -63,7 +66,7 @@ def test_full_payload_capability_reaches_omni_model_config(monkeypatch):
|
||||
class ConnectorWorker:
|
||||
model_runner_cls = ConnectorRunner
|
||||
|
||||
worker_module.ConnectorWorker = ConnectorWorker
|
||||
setattr(worker_module, "ConnectorWorker", ConnectorWorker)
|
||||
monkeypatch.setitem(sys.modules, worker_module.__name__, worker_module)
|
||||
|
||||
monkeypatch.setattr(OmniEngineArgs, "_ensure_omni_models_registered", lambda _self: None)
|
||||
@@ -95,7 +98,7 @@ def test_stage_without_connector_configuration_accepts_plain_runner(monkeypatch)
|
||||
class WorkerWithoutConnector:
|
||||
model_runner_cls = object
|
||||
|
||||
worker_module.WorkerWithoutConnector = WorkerWithoutConnector
|
||||
setattr(worker_module, "WorkerWithoutConnector", WorkerWithoutConnector)
|
||||
monkeypatch.setitem(sys.modules, worker_module.__name__, worker_module)
|
||||
|
||||
args = OmniEngineArgs(
|
||||
@@ -113,7 +116,7 @@ def test_full_payload_capability_requires_selected_worker_connector(monkeypatch)
|
||||
class WorkerWithoutConnector:
|
||||
model_runner_cls = object
|
||||
|
||||
worker_module.WorkerWithoutConnector = WorkerWithoutConnector
|
||||
setattr(worker_module, "WorkerWithoutConnector", WorkerWithoutConnector)
|
||||
monkeypatch.setitem(sys.modules, worker_module.__name__, worker_module)
|
||||
|
||||
with pytest.raises(ValueError, match="does not provide an Omni connector model runner"):
|
||||
@@ -130,7 +133,7 @@ def test_full_payload_capability_validates_platform_selected_worker(monkeypatch)
|
||||
class WorkerWithoutConnector:
|
||||
model_runner_cls = object
|
||||
|
||||
worker_module.WorkerWithoutConnector = WorkerWithoutConnector
|
||||
setattr(worker_module, "WorkerWithoutConnector", WorkerWithoutConnector)
|
||||
monkeypatch.setitem(sys.modules, worker_module.__name__, worker_module)
|
||||
monkeypatch.setattr(
|
||||
current_omni_platform,
|
||||
@@ -293,7 +296,7 @@ def test_remote_tokenizer_subfolder_download_does_not_report_failure(tmp_path, m
|
||||
baseline_config = Mock()
|
||||
warning = mocker.patch("vllm_omni.engine.arg_utils.logger.warning")
|
||||
|
||||
monkeypatch.setattr("huggingface_hub.snapshot_download", lambda *args, **kwargs: str(tmp_path))
|
||||
monkeypatch.setattr("huggingface_hub.HfApi.snapshot_download", lambda *args, **kwargs: str(tmp_path))
|
||||
monkeypatch.setattr(OmniEngineArgs, "_patch_empty_hf_config", lambda *args, **kwargs: None)
|
||||
monkeypatch.setattr(EngineArgs, "create_model_config", lambda _self: baseline_config)
|
||||
monkeypatch.setattr(
|
||||
@@ -339,6 +342,7 @@ def test_patch_missing_local_hf_config(tmp_path):
|
||||
def test_non_missing_local_hf_config_error_reaches_parent_loader(tmp_path, monkeypatch, config_entry):
|
||||
"""Non-missing config errors must reach vLLM's normal loader."""
|
||||
config_path = tmp_path / "config.json"
|
||||
loader_error: Exception
|
||||
if config_entry == "malformed":
|
||||
config_path.write_text("{not valid json", encoding="utf-8")
|
||||
loader_error = json.JSONDecodeError("invalid config", "{not valid json", 1)
|
||||
|
||||
@@ -11,7 +11,7 @@ import types
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm_omni.diffusion.data import AttentionConfig, AttentionSpec, normalize_omni_diffusion_kwargs
|
||||
from vllm_omni.diffusion.data import AttentionConfig
|
||||
from vllm_omni.engine import async_omni_engine as async_omni_engine_module
|
||||
from vllm_omni.engine.async_omni_engine import AsyncOmniEngine
|
||||
from vllm_omni.engine.stage_init_utils import (
|
||||
@@ -1732,133 +1732,6 @@ def test_inject_kv_stage_info_infers_receiver_tp_topology():
|
||||
assert stage1.engine_args["omni_kv_config"]["rank_mapping"] == {"from_tp": 4, "to_tp": 2}
|
||||
|
||||
|
||||
def test_resolve_stage_configs_injects_global_diffusion_attention_when_missing(monkeypatch):
|
||||
import vllm_omni.engine.async_omni_engine as engine_mod
|
||||
|
||||
engine = object.__new__(AsyncOmniEngine)
|
||||
stage_cfg = types.SimpleNamespace(
|
||||
stage_type="diffusion",
|
||||
engine_args=types.SimpleNamespace(
|
||||
diffusion_attention_config=None,
|
||||
lora_path=None,
|
||||
lora_scale=None,
|
||||
enable_sleep_mode=None,
|
||||
quantization_config=None,
|
||||
),
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
engine_mod,
|
||||
"load_and_resolve_stage_configs",
|
||||
lambda *args, **kwargs: ("dummy-config", [stage_cfg], None),
|
||||
)
|
||||
|
||||
_config_path, stage_configs = engine._resolve_stage_configs(
|
||||
model="dummy-model",
|
||||
kwargs={"diffusion_attention_backend": "FLASH_ATTN"},
|
||||
trust_remote_code=False,
|
||||
)
|
||||
|
||||
diffusion_attention_config = stage_configs[0].engine_args.diffusion_attention_config
|
||||
assert isinstance(diffusion_attention_config, AttentionConfig)
|
||||
assert diffusion_attention_config.default is not None
|
||||
assert diffusion_attention_config.default.backend == "FLASH_ATTN"
|
||||
|
||||
|
||||
def test_resolve_stage_configs_preserves_stage_diffusion_attention(monkeypatch):
|
||||
import vllm_omni.engine.async_omni_engine as engine_mod
|
||||
|
||||
engine = object.__new__(AsyncOmniEngine)
|
||||
existing_attention = AttentionConfig(default=AttentionSpec(backend="TORCH_SDPA"))
|
||||
stage_cfg = types.SimpleNamespace(
|
||||
stage_type="diffusion",
|
||||
engine_args=types.SimpleNamespace(
|
||||
diffusion_attention_config=existing_attention,
|
||||
lora_path=None,
|
||||
lora_scale=None,
|
||||
enable_sleep_mode=None,
|
||||
quantization_config=None,
|
||||
),
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
engine_mod,
|
||||
"load_and_resolve_stage_configs",
|
||||
lambda *args, **kwargs: ("dummy-config", [stage_cfg], None),
|
||||
)
|
||||
|
||||
_config_path, stage_configs = engine._resolve_stage_configs(
|
||||
model="dummy-model",
|
||||
kwargs={"diffusion_attention_backend": "FLASH_ATTN"},
|
||||
trust_remote_code=False,
|
||||
)
|
||||
|
||||
assert stage_configs[0].engine_args.diffusion_attention_config is existing_attention
|
||||
|
||||
|
||||
def test_resolve_stage_configs_does_not_inject_over_stage_diffusion_attention_backend(monkeypatch):
|
||||
import vllm_omni.engine.async_omni_engine as engine_mod
|
||||
|
||||
engine = object.__new__(AsyncOmniEngine)
|
||||
stage_cfg = types.SimpleNamespace(
|
||||
stage_type="diffusion",
|
||||
engine_args=types.SimpleNamespace(
|
||||
diffusion_attention_backend="TORCH_SDPA",
|
||||
diffusion_attention_config=None,
|
||||
lora_path=None,
|
||||
lora_scale=None,
|
||||
enable_sleep_mode=None,
|
||||
quantization_config=None,
|
||||
),
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
engine_mod,
|
||||
"load_and_resolve_stage_configs",
|
||||
lambda *args, **kwargs: ("dummy-config", [stage_cfg], None),
|
||||
)
|
||||
|
||||
_config_path, stage_configs = engine._resolve_stage_configs(
|
||||
model="dummy-model",
|
||||
kwargs={"diffusion_attention_backend": "FLASH_ATTN"},
|
||||
trust_remote_code=False,
|
||||
)
|
||||
|
||||
engine_args = stage_configs[0].engine_args
|
||||
assert engine_args.diffusion_attention_backend == "TORCH_SDPA"
|
||||
assert engine_args.diffusion_attention_config is None
|
||||
normalized = normalize_omni_diffusion_kwargs(vars(engine_args))
|
||||
assert normalized["diffusion_attention_config"].default.backend == "TORCH_SDPA"
|
||||
|
||||
|
||||
def test_resolve_stage_configs_does_not_inject_diffusion_attention_into_llm_stage(monkeypatch):
|
||||
import vllm_omni.engine.async_omni_engine as engine_mod
|
||||
|
||||
engine = object.__new__(AsyncOmniEngine)
|
||||
stage_cfg = types.SimpleNamespace(
|
||||
stage_type="llm",
|
||||
engine_args=types.SimpleNamespace(
|
||||
attention_config={"backend": "FLASH_ATTN"},
|
||||
enable_sleep_mode=None,
|
||||
),
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
engine_mod,
|
||||
"load_and_resolve_stage_configs",
|
||||
lambda *args, **kwargs: ("dummy-config", [stage_cfg], None),
|
||||
)
|
||||
|
||||
_config_path, stage_configs = engine._resolve_stage_configs(
|
||||
model="dummy-model",
|
||||
kwargs={"diffusion_attention_backend": "TORCH_SDPA"},
|
||||
trust_remote_code=False,
|
||||
)
|
||||
|
||||
assert stage_configs[0].engine_args.attention_config == {"backend": "FLASH_ATTN"}
|
||||
assert not hasattr(stage_configs[0].engine_args, "diffusion_attention_config")
|
||||
|
||||
|
||||
def test_extract_legacy_stage_metadata_rocm_does_not_inject_diffusion_attention(monkeypatch):
|
||||
"""ROCm default attention logic only applies to LLM stages, not diffusion."""
|
||||
from vllm_omni.engine.stage_init_utils import extract_legacy_stage_metadata
|
||||
|
||||
@@ -2665,7 +2665,10 @@ async def test_duplex_reaper_loop_waits_between_ticks():
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_duplex_reaper_loop_survives_one_cleanup_failure():
|
||||
@pytest.mark.parametrize("first_cleanup_delay", [0.0, 0.05], ids=["immediate", "delayed"])
|
||||
async def test_duplex_reaper_loop_survives_one_cleanup_failure(first_cleanup_delay: float) -> None:
|
||||
recovered = asyncio.Event()
|
||||
|
||||
class _Plane:
|
||||
def __init__(self) -> None:
|
||||
self.calls = 0
|
||||
@@ -2673,7 +2676,9 @@ async def test_duplex_reaper_loop_survives_one_cleanup_failure():
|
||||
async def reap_expired(self) -> int:
|
||||
self.calls += 1
|
||||
if self.calls == 1:
|
||||
await asyncio.sleep(first_cleanup_delay)
|
||||
raise RuntimeError("transient cleanup failure")
|
||||
recovered.set()
|
||||
return 0
|
||||
|
||||
orchestrator = object.__new__(Orchestrator)
|
||||
@@ -2682,11 +2687,13 @@ async def test_duplex_reaper_loop_survives_one_cleanup_failure():
|
||||
orchestrator._shutdown_event = asyncio.Event()
|
||||
|
||||
task = asyncio.create_task(orchestrator._duplex_reaper_loop())
|
||||
await asyncio.sleep(0.035)
|
||||
orchestrator._shutdown_event.set()
|
||||
await task
|
||||
|
||||
assert orchestrator.duplex_control_plane.calls >= 2
|
||||
try:
|
||||
# Wait for recovery itself, including when cleanup exceeds the old 35 ms window.
|
||||
await asyncio.wait_for(recovered.wait(), timeout=5.0)
|
||||
assert orchestrator.duplex_control_plane.calls >= 2
|
||||
finally:
|
||||
orchestrator._shutdown_event.set()
|
||||
await asyncio.wait_for(task, timeout=5.0)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -16,7 +16,7 @@ from types import SimpleNamespace
|
||||
|
||||
import janus
|
||||
import pytest
|
||||
from vllm.sampling_params import SamplingParams
|
||||
from vllm.sampling_params import RequestOutputKind, SamplingParams
|
||||
from vllm.v1.engine.exceptions import EngineDeadError
|
||||
from vllm.v1.serial_utils import MsgpackEncoder
|
||||
|
||||
@@ -33,11 +33,16 @@ from vllm_omni.engine.orchestrator import (
|
||||
cleanup_request_artifact_dirs,
|
||||
)
|
||||
from vllm_omni.engine.stage_pool import StageUnavailableError
|
||||
from vllm_omni.errors import OmniClientError
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
|
||||
from vllm_omni.model_executor.stage_input_processors import (
|
||||
joyai_vl_interaction as joyai_bridge,
|
||||
)
|
||||
from vllm_omni.outputs import OmniRequestOutput
|
||||
|
||||
from .test_orchestrator import (
|
||||
FakeOutputProcessor,
|
||||
FakeRunningCounter,
|
||||
FakeStageClient,
|
||||
OrchestratorFixture,
|
||||
_build_harness,
|
||||
@@ -45,6 +50,7 @@ from .test_orchestrator import (
|
||||
_build_stage_pools,
|
||||
_engine_core_outputs,
|
||||
_enqueue_add_request,
|
||||
_get_output_message,
|
||||
_wait_for,
|
||||
)
|
||||
|
||||
@@ -935,6 +941,139 @@ async def test_diffusion_client_error_output_propagates_status_code(orchestrator
|
||||
orchestrator_fixture.thread.join(timeout=5)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("event_driven", [False, True], ids=["legacy", "event-driven"])
|
||||
@pytest.mark.parametrize("first_speaker", ["Ryan", "not-a-real-speaker"])
|
||||
async def test_joyai_tts_request_validation_keeps_orchestrator_running(
|
||||
orchestrator_factory,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
first_speaker: str,
|
||||
event_driven: bool,
|
||||
) -> None:
|
||||
"""Check that the same orchestrator can handle the next valid request."""
|
||||
monkeypatch.setenv("VLLM_OMNI_EVENT_DRIVEN_ORCH", "1" if event_driven else "0")
|
||||
|
||||
# Use a fixed token count so the test does not need tokenizer files.
|
||||
class FakeTokenizer:
|
||||
def encode(self, _text: str, *, add_special_tokens: bool) -> list[int]:
|
||||
return list(range(12))
|
||||
|
||||
talker_model_config = SimpleNamespace(
|
||||
max_model_len=64,
|
||||
hf_config=SimpleNamespace(
|
||||
talker_config=SimpleNamespace(spk_id={"vivian": 0, "ryan": 1}, codec_language_id={}, spk_is_dialect={})
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(joyai_bridge, "cached_tokenizer_from_config", lambda _: FakeTokenizer())
|
||||
|
||||
# Use the real bridge so speaker validation is part of the test.
|
||||
class JoyAITalkerStage(FakeStageClient):
|
||||
def process_engine_inputs(self, source_outputs, prompt=None, streaming_context=None):
|
||||
self.bridge_inputs = joyai_bridge.joyai_action_to_tts(
|
||||
source_outputs, prompt, self.requires_multimodal_data, target_model_config=talker_model_config
|
||||
)
|
||||
return self.bridge_inputs
|
||||
|
||||
stage0 = FakeStageClient(stage_type="llm", final_output=False)
|
||||
stage1 = JoyAITalkerStage(stage_type="llm", final_output=True)
|
||||
stage0_processor, stage1_processor = FakeOutputProcessor(), FakeOutputProcessor()
|
||||
fixture = orchestrator_factory(
|
||||
[stage0, stage1],
|
||||
output_processors=[stage0_processor, stage1_processor],
|
||||
stage_vllm_configs=[
|
||||
SimpleNamespace(model_config=SimpleNamespace(max_model_len=64)),
|
||||
SimpleNamespace(model_config=talker_model_config),
|
||||
],
|
||||
)
|
||||
counter = FakeRunningCounter()
|
||||
fixture.orchestrator._running_counter = counter
|
||||
# With a valid speaker, task_type should be changed from Base to CustomVoice.
|
||||
# An unknown speaker should cause a request error.
|
||||
first_info = {"tts_task_type": "Base", "speaker": "Vivian", "tts_speaker": first_speaker}
|
||||
talker_submissions = 0
|
||||
# Send both requests to the same orchestrator. The second uses the default Vivian voice.
|
||||
for index, (request_id, info) in enumerate((("first", first_info), ("good", {})), start=1):
|
||||
await _enqueue_add_request(
|
||||
fixture,
|
||||
request_id=request_id,
|
||||
prompt=SimpleNamespace(request_id=request_id, prompt_token_ids=[1, 2]),
|
||||
original_prompt={"additional_information": info},
|
||||
sampling_params_list=[_sampling_params(), _sampling_params()],
|
||||
final_stage_id=1,
|
||||
)
|
||||
await _wait_for(lambda: len(stage0.add_request_calls) == index and counter.value == 1)
|
||||
stage0_processor.request_outputs = [_build_request_output(request_id, text="</response> Hello.")]
|
||||
stage0.push_engine_core_outputs(_engine_core_outputs(f"{request_id}-raw", float(index)))
|
||||
|
||||
if request_id == "first" and first_speaker == "not-a-real-speaker":
|
||||
# Reject this request before Talker runs, while keeping the engine alive.
|
||||
error = await _wait_for_error_message(fixture, request_id=request_id)
|
||||
assert error.status_code == 400 and error.error_type == "BadRequestError"
|
||||
assert error.fatal is False and error.stage_id == 1
|
||||
assert "not-a-real-speaker" in error.error
|
||||
assert stage1.add_request_calls == []
|
||||
else:
|
||||
talker_submissions += 1
|
||||
await _wait_for(lambda: len(stage1.add_request_calls) == talker_submissions or fixture.result_future.done())
|
||||
assert not fixture.result_future.done()
|
||||
assert stage1.add_request_calls[-1][0].request_id == request_id
|
||||
metadata = stage1.bridge_inputs[0]["additional_information"]
|
||||
assert metadata["task_type"] == ["CustomVoice"]
|
||||
assert metadata["speaker"] == [first_speaker if request_id == "first" else "Vivian"]
|
||||
# Finish the valid request and check its final output.
|
||||
stage1_processor.request_outputs = [_build_request_output(request_id, text="Completed.")]
|
||||
stage1.push_engine_core_outputs(_engine_core_outputs(f"{request_id}-talker", float(index)))
|
||||
output = await _get_output_message(fixture)
|
||||
assert output.request_id == request_id and output.stage_id == 1
|
||||
assert output.finished is True
|
||||
assert output.engine_outputs.outputs[0].text == "Completed."
|
||||
|
||||
# Wait for full cleanup before sending the next request.
|
||||
await _wait_for(lambda: request_id not in fixture.orchestrator.request_states and counter.value == 0)
|
||||
assert all(pool.get_bound_replica_id(request_id) is None for pool in fixture.orchestrator.stage_pools)
|
||||
assert fixture.thread.is_alive() and not fixture.result_future.done()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_streaming_input_processor_client_error_does_not_forward_terminal_update() -> None:
|
||||
"""Do not send a second update after the first one fails and clears the request."""
|
||||
processor_calls = []
|
||||
|
||||
class FailingStage(FakeStageClient):
|
||||
def process_engine_inputs(self, *args, **kwargs):
|
||||
processor_calls.append((args, kwargs))
|
||||
raise OmniClientError("Input rejected")
|
||||
|
||||
orchestrator, queues = _build_bare_orchestrator(
|
||||
_build_stage_pools([[FakeStageClient()], [FailingStage(final_output=True)]])
|
||||
)
|
||||
state = OrchestratorRequestState(
|
||||
request_id="bad-stream",
|
||||
prompt={"prompt_token_ids": [1]},
|
||||
sampling_params_list=[SamplingParams(output_kind=RequestOutputKind.CUMULATIVE), _sampling_params()],
|
||||
final_stage_id=1,
|
||||
)
|
||||
state.streaming.enabled = True
|
||||
assert state.duplex_identity is None
|
||||
orchestrator.request_states[state.request_id] = state
|
||||
try:
|
||||
await orchestrator._route_output(0, 0, _build_request_output(state.request_id), state, stage_metrics=None)
|
||||
|
||||
assert len(processor_calls) == 1
|
||||
error = queues[1].sync_q.get_nowait()
|
||||
assert isinstance(error, ErrorMessage)
|
||||
assert error.request_id == state.request_id
|
||||
assert error.stage_id == 1
|
||||
assert error.status_code == 400
|
||||
assert error.fatal is False
|
||||
assert queues[1].sync_q.empty()
|
||||
assert state.request_id not in orchestrator.request_states
|
||||
assert all(pool.get_bound_replica_id(state.request_id) is None for pool in orchestrator.stage_pools)
|
||||
finally:
|
||||
for q in queues:
|
||||
q.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_duplex_input_processor_failure_is_request_scoped(orchestrator_factory, monkeypatch) -> None:
|
||||
class FailingStage(FakeStageClient):
|
||||
|
||||
@@ -376,14 +376,26 @@ class TestSingleStageModeDetection:
|
||||
mocker: MockerFixture,
|
||||
*,
|
||||
stage_cfgs: list[Any] | None = None,
|
||||
resolved_config_path: str = "/fake/path",
|
||||
patch_deploy_config: bool = True,
|
||||
**kwargs: Any,
|
||||
) -> AsyncOmniEngine:
|
||||
mock_stage_configs = stage_cfgs or [_make_stage_cfg(0)]
|
||||
|
||||
if patch_deploy_config:
|
||||
mocker.patch.object(
|
||||
StageConfigFactory,
|
||||
"get_pipeline_config",
|
||||
return_value=None,
|
||||
)
|
||||
mocker.patch(
|
||||
"vllm_omni.engine.async_omni_engine.load_deploy_config",
|
||||
return_value=SimpleNamespace(duplex_session=DuplexSessionRuntimeConfig()),
|
||||
)
|
||||
mocker.patch.object(
|
||||
AsyncOmniEngine,
|
||||
"_resolve_stage_configs",
|
||||
return_value=("/fake/path", mock_stage_configs),
|
||||
return_value=(resolved_config_path, mock_stage_configs),
|
||||
)
|
||||
mocker.patch.object(AsyncOmniEngine, "_bootstrap_orchestrator")
|
||||
mock_thread_cls = mocker.patch("threading.Thread")
|
||||
@@ -445,6 +457,8 @@ class TestSingleStageModeDetection:
|
||||
engine = self._make_engine_no_thread(
|
||||
mocker,
|
||||
deploy_config="/fake/duplex.yaml",
|
||||
resolved_config_path="/fake/duplex.yaml",
|
||||
patch_deploy_config=False,
|
||||
)
|
||||
|
||||
get_pipeline_config.assert_called_once_with(
|
||||
@@ -455,6 +469,30 @@ class TestSingleStageModeDetection:
|
||||
load_deploy_config.assert_called_once_with("/fake/duplex.yaml")
|
||||
assert engine.duplex_session_config is duplex_session
|
||||
|
||||
def test_auto_discovered_deploy_loads_duplex_runtime_config(
|
||||
self,
|
||||
mocker: MockerFixture,
|
||||
) -> None:
|
||||
deploy_path = "/resolved/qwen3_omni_moe.yaml"
|
||||
duplex_session = DuplexSessionRuntimeConfig(server_vad_model_path="/models/silero_vad.onnx")
|
||||
mocker.patch(
|
||||
"vllm_omni.engine.async_omni_engine.StageConfigFactory.get_pipeline_config",
|
||||
return_value=None,
|
||||
)
|
||||
load_deploy_config = mocker.patch(
|
||||
"vllm_omni.engine.async_omni_engine.load_deploy_config",
|
||||
return_value=SimpleNamespace(duplex_session=duplex_session),
|
||||
)
|
||||
|
||||
engine = self._make_engine_no_thread(
|
||||
mocker,
|
||||
resolved_config_path=deploy_path,
|
||||
patch_deploy_config=False,
|
||||
)
|
||||
|
||||
load_deploy_config.assert_called_once_with(deploy_path)
|
||||
assert engine.duplex_session_config is duplex_session
|
||||
|
||||
def test_single_stage_mode_without_stage_id_has_no_filter(self, mocker: MockerFixture):
|
||||
engine = self._make_engine_no_thread(
|
||||
mocker,
|
||||
@@ -518,6 +556,10 @@ class TestEndpointRestrictionsTrustRemoteCode:
|
||||
StageConfigFactory.try_infer_model_type.cache_clear()
|
||||
|
||||
def _make_engine_no_thread(self, mocker: MockerFixture, **kwargs: Any) -> AsyncOmniEngine:
|
||||
mocker.patch(
|
||||
"vllm_omni.engine.async_omni_engine.load_deploy_config",
|
||||
return_value=SimpleNamespace(duplex_session=DuplexSessionRuntimeConfig()),
|
||||
)
|
||||
mocker.patch.object(
|
||||
AsyncOmniEngine,
|
||||
"_resolve_stage_configs",
|
||||
|
||||
@@ -61,20 +61,19 @@ if loaded:
|
||||
assert result.returncode == 0, result.stderr
|
||||
|
||||
|
||||
def test_generic_handler_requires_explicit_serving_runtime_adapter() -> None:
|
||||
def test_generic_handler_supports_adapterless_chat_fallback() -> None:
|
||||
repo_root = Path(__file__).resolve().parents[3]
|
||||
script = """
|
||||
from types import SimpleNamespace
|
||||
|
||||
from vllm_omni.entrypoints.duplex.serving import OmniDuplexSessionHandler
|
||||
|
||||
chat_service = SimpleNamespace(engine_client=SimpleNamespace())
|
||||
try:
|
||||
OmniDuplexSessionHandler(chat_service=chat_service)
|
||||
except ValueError as exc:
|
||||
if "serving runtime adapter" not in str(exc).lower():
|
||||
raise
|
||||
else:
|
||||
chat_service = SimpleNamespace(
|
||||
engine_client=SimpleNamespace(),
|
||||
model_config=SimpleNamespace(model="test-model"),
|
||||
)
|
||||
handler = OmniDuplexSessionHandler(chat_service=chat_service)
|
||||
if handler._serving_runtime_adapter is not None:
|
||||
raise SystemExit("generic handler silently selected a model serving adapter")
|
||||
"""
|
||||
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Serving-side registration invariants for the Audio8 TTS adapter.
|
||||
|
||||
The engine never names ``audio8_tts`` directly: ``/v1/audio/speech`` resolves the
|
||||
adapter by matching the deployed stage's ``model_stage`` key against the
|
||||
``stage_keys`` each adapter declares. That makes the pipeline definition and the
|
||||
adapter two halves of one contract, with nothing in the type system holding them
|
||||
together -- rename either side and the endpoint silently stops recognising the
|
||||
model (falling through to "unknown TTS model") instead of failing at startup.
|
||||
|
||||
These tests pin the contract from both ends.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm_omni.entrypoints.openai.tts_adapters import (
|
||||
all_tts_model_types,
|
||||
all_tts_stage_keys,
|
||||
detect_tts_model_type,
|
||||
resolve_adapter,
|
||||
)
|
||||
from vllm_omni.entrypoints.openai.tts_adapters.audio8_tts import Audio8TTSAdapter
|
||||
from vllm_omni.model_executor.models.audio8_tts.pipeline import AUDIO8_TTS_PIPELINE
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
SLOW_AR_STAGE_KEY = "audio8_tts_slow_ar"
|
||||
|
||||
|
||||
def _pipeline_stage_keys() -> list[str]:
|
||||
return [stage.model_stage for stage in AUDIO8_TTS_PIPELINE.stages]
|
||||
|
||||
|
||||
def test_pipeline_stage_key_is_the_one_the_adapter_claims():
|
||||
"""The shipped pipeline must name the stage the adapter matches on."""
|
||||
assert SLOW_AR_STAGE_KEY in _pipeline_stage_keys()
|
||||
assert SLOW_AR_STAGE_KEY in Audio8TTSAdapter.stage_keys
|
||||
|
||||
|
||||
def test_detection_resolves_slow_ar_stage_to_the_audio8_adapter():
|
||||
assert detect_tts_model_type(SLOW_AR_STAGE_KEY, "Audio8TTSSlowARForConditionalGeneration") == "audio8_tts"
|
||||
assert resolve_adapter("audio8_tts") is Audio8TTSAdapter
|
||||
|
||||
|
||||
def test_adapter_is_registered_in_the_global_tables():
|
||||
"""Importing the package must register the adapter, not just define it."""
|
||||
assert "audio8_tts" in all_tts_model_types()
|
||||
assert SLOW_AR_STAGE_KEY in all_tts_stage_keys()
|
||||
|
||||
|
||||
def test_codec_decoder_stage_does_not_serve_speech():
|
||||
"""Only stage 0 answers /v1/audio/speech; the codec stage must not match."""
|
||||
codec_stage_key = _pipeline_stage_keys()[1]
|
||||
assert codec_stage_key != SLOW_AR_STAGE_KEY
|
||||
assert detect_tts_model_type(codec_stage_key, "Audio8TTSCodecDecoder") != "audio8_tts"
|
||||
|
||||
|
||||
def test_apply_sampling_overrides_defaults_tts_local_seed_for_fast_ar():
|
||||
"""The deploy seed must reach the Fast AR through ``tts_local_seed``.
|
||||
|
||||
Only the Slow AR is seeded via ``sampling_metadata.generators``; the residual
|
||||
codebooks read ``tts_local_seed`` and otherwise fall back to global RNG, which
|
||||
makes an unseeded request's audio depend on batch composition. The adapter
|
||||
defaults it from the stage-0 seed without clobbering an explicit value.
|
||||
"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
from vllm.sampling_params import SamplingParams
|
||||
|
||||
adapter = Audio8TTSAdapter.__new__(Audio8TTSAdapter)
|
||||
request = SimpleNamespace(max_new_tokens=None)
|
||||
|
||||
# Deploy default seed propagates to tts_local_seed.
|
||||
out = adapter.apply_sampling_overrides([SamplingParams(seed=42)], request)
|
||||
assert out[0].extra_args["tts_local_seed"] == 42
|
||||
|
||||
# An explicit tts_local_seed is left intact (setdefault, not overwrite).
|
||||
pinned = [SamplingParams(seed=42, extra_args={"tts_local_seed": 7})]
|
||||
assert adapter.apply_sampling_overrides(pinned, request)[0].extra_args["tts_local_seed"] == 7
|
||||
|
||||
# No seed at all -> nothing injected (non-deterministic by request contract).
|
||||
out_unseeded = adapter.apply_sampling_overrides([SamplingParams(seed=None)], request)
|
||||
assert (out_unseeded[0].extra_args or {}).get("tts_local_seed") is None
|
||||
@@ -568,6 +568,48 @@ def test_websocket_routes_emit_stable_unavailable_frames_and_close(path: str, pa
|
||||
websocket.receive_text()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
("duplex_query", "expected_handler"),
|
||||
[
|
||||
(None, "duplex"),
|
||||
("1", "duplex"),
|
||||
("true", "duplex"),
|
||||
("on", "duplex"),
|
||||
("0", "legacy"),
|
||||
("false", "legacy"),
|
||||
],
|
||||
)
|
||||
async def test_realtime_route_defaults_to_configured_duplex_handler(
|
||||
monkeypatch, duplex_query: str | None, expected_handler: str
|
||||
) -> None:
|
||||
calls: list[str] = []
|
||||
|
||||
class _DuplexHandler:
|
||||
async def handle_realtime_session(self, _websocket) -> None:
|
||||
calls.append("duplex")
|
||||
|
||||
class _LegacyConnection:
|
||||
async def handle_connection(self) -> None:
|
||||
calls.append("legacy")
|
||||
|
||||
monkeypatch.setattr(api_server, "RealtimeConnection", lambda _websocket, _serving: _LegacyConnection())
|
||||
query_params = {} if duplex_query is None else {"duplex": duplex_query}
|
||||
websocket = SimpleNamespace(
|
||||
app=SimpleNamespace(
|
||||
state=SimpleNamespace(
|
||||
openai_serving_duplex=_DuplexHandler(),
|
||||
openai_serving_realtime=object(),
|
||||
)
|
||||
),
|
||||
query_params=query_params,
|
||||
)
|
||||
|
||||
await api_server.realtime_websocket(websocket)
|
||||
|
||||
assert calls == [expected_handler]
|
||||
|
||||
|
||||
def test_health_without_engine_returns_stable_unhealthy_response() -> None:
|
||||
"""Lock ``/health`` with no engine initialized.
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Serving-layer regressions for the Audex zero-codec-token contract.
|
||||
|
||||
A zero-codec-token (or phase-invalid TTA) request reaches the serving layer
|
||||
@@ -171,7 +171,7 @@ class TestAudexCfgValidation:
|
||||
class TestAudexCfgInjection:
|
||||
def _serving_with_fake_tokenizer(self):
|
||||
serving = _serving()
|
||||
serving._get_audex_tokenizer = lambda: _MarkerTokenizer()
|
||||
serving._adapter._get_tokenizer = lambda: _MarkerTokenizer()
|
||||
return serving
|
||||
|
||||
def _cond_prompt(self, text: str = "Hello world.") -> str:
|
||||
@@ -333,8 +333,8 @@ class TestAdapterRouting:
|
||||
class TestAudexTTAInjection:
|
||||
def _serving(self):
|
||||
serving = _serving(model_type="audex_tta")
|
||||
serving._get_audex_tokenizer = lambda: _TTAVocabTokenizer()
|
||||
serving._audex_tta_rvq = None
|
||||
serving._adapter._get_tokenizer = lambda: _TTAVocabTokenizer()
|
||||
serving._adapter._tta_rvq = None
|
||||
return serving
|
||||
|
||||
def _prompt(self):
|
||||
|
||||
@@ -163,6 +163,8 @@ class TestStreamingAudioResampler:
|
||||
|
||||
chunked = StreamingAudioResampler(24000, 8000)
|
||||
pieces = [chunked.process(chunk) for chunk in np.split(waveform, [137, 2048, 9001, 17003])]
|
||||
# Bounded FIR history must own its data, not retain the last large chunk.
|
||||
assert chunked._history.base is None
|
||||
pieces.append(chunked.process(np.empty(0), final=True))
|
||||
actual = np.concatenate(pieces)
|
||||
|
||||
@@ -193,9 +195,15 @@ class TestStreamingAudioResampler:
|
||||
output_rms = np.sqrt(np.mean(output[100:-100] ** 2))
|
||||
assert output_rms < input_rms * 0.01
|
||||
|
||||
def test_rejects_non_integer_downsampling_ratio(self):
|
||||
with pytest.raises(ValueError, match="integer downsampling ratio"):
|
||||
StreamingAudioResampler(24000, 16000)
|
||||
def test_supports_rational_downsampling_ratio(self):
|
||||
waveform = np.sin(np.linspace(0, 200 * np.pi, 24000, endpoint=False)).astype(np.float32)
|
||||
resampler = StreamingAudioResampler(24000, 16000)
|
||||
|
||||
output = resampler.process(waveform, final=True)
|
||||
reference = torchaudio.functional.resample(torch.from_numpy(waveform), 24000, 16000).numpy()
|
||||
|
||||
assert output.shape == (16000,)
|
||||
np.testing.assert_allclose(output[100:-100], reference[100:-100], atol=2e-3, rtol=1e-3)
|
||||
|
||||
def test_rejects_multichannel_audio(self):
|
||||
resampler = StreamingAudioResampler(24000, 8000)
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,129 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import asyncio
|
||||
import gc
|
||||
import threading
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm_omni.entrypoints.openai.tts_adapters.base import SpeechServingContext
|
||||
from vllm_omni.entrypoints.openai.tts_adapters.higgs_audio_v3 import HiggsAudioV3Adapter
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
def test_ref_code_inflight_survives_request_cancellation():
|
||||
adapter = HiggsAudioV3Adapter(SpeechServingContext(server=SimpleNamespace()))
|
||||
encode_started = threading.Event()
|
||||
release_encode = threading.Event()
|
||||
calls = 0
|
||||
expected_codes = torch.arange(16, dtype=torch.long).reshape(2, 8) + 1
|
||||
|
||||
def encode_reference_audio(_wav, _sr):
|
||||
nonlocal calls
|
||||
calls += 1
|
||||
encode_started.set()
|
||||
assert release_encode.wait(timeout=5)
|
||||
return torch.arange(16, dtype=torch.long).reshape(2, 8)
|
||||
|
||||
def apply_delay_pattern(codes):
|
||||
return codes + 1
|
||||
|
||||
async def resolve():
|
||||
return await adapter._resolve_higgs_audio_v3_ref_codes(
|
||||
"ref-a",
|
||||
object(),
|
||||
24000,
|
||||
encode_reference_audio,
|
||||
apply_delay_pattern,
|
||||
)
|
||||
|
||||
async def run():
|
||||
creator = asyncio.create_task(resolve())
|
||||
try:
|
||||
assert await asyncio.wait_for(asyncio.to_thread(encode_started.wait), timeout=5)
|
||||
|
||||
cancelled_waiter = asyncio.create_task(resolve())
|
||||
survivor = asyncio.create_task(resolve())
|
||||
await asyncio.sleep(0)
|
||||
|
||||
cancelled_waiter.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await cancelled_waiter
|
||||
|
||||
creator.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await creator
|
||||
|
||||
release_encode.set()
|
||||
survivor_result = await asyncio.wait_for(survivor, timeout=5)
|
||||
await asyncio.sleep(0)
|
||||
return survivor_result
|
||||
finally:
|
||||
release_encode.set()
|
||||
|
||||
codes, cache_hit, inflight_wait = asyncio.run(run())
|
||||
|
||||
assert calls == 1
|
||||
assert cache_hit is False
|
||||
assert inflight_wait is True
|
||||
assert torch.equal(codes, expected_codes)
|
||||
assert "ref-a" not in adapter._higgs_audio_v3_ref_code_inflight
|
||||
cached = adapter._get_higgs_audio_v3_ref_codes("ref-a")
|
||||
assert cached is not None
|
||||
assert torch.equal(cached, expected_codes)
|
||||
|
||||
|
||||
def test_ref_code_inflight_consumes_failure_after_all_callers_cancel():
|
||||
adapter = HiggsAudioV3Adapter(SpeechServingContext(server=SimpleNamespace()))
|
||||
encode_started = threading.Event()
|
||||
release_encode = threading.Event()
|
||||
loop_errors = []
|
||||
|
||||
def encode_reference_audio(_wav, _sr):
|
||||
encode_started.set()
|
||||
assert release_encode.wait(timeout=5)
|
||||
raise RuntimeError("encode failed")
|
||||
|
||||
async def resolve():
|
||||
return await adapter._resolve_higgs_audio_v3_ref_codes(
|
||||
"ref-a",
|
||||
object(),
|
||||
24000,
|
||||
encode_reference_audio,
|
||||
lambda codes: codes,
|
||||
)
|
||||
|
||||
async def run():
|
||||
loop = asyncio.get_running_loop()
|
||||
loop.set_exception_handler(lambda _loop, context: loop_errors.append(context))
|
||||
creator = asyncio.create_task(resolve())
|
||||
try:
|
||||
assert await asyncio.wait_for(asyncio.to_thread(encode_started.wait), timeout=5)
|
||||
waiter = asyncio.create_task(resolve())
|
||||
await asyncio.sleep(0)
|
||||
|
||||
creator.cancel()
|
||||
waiter.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await creator
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await waiter
|
||||
|
||||
release_encode.set()
|
||||
for _ in range(100):
|
||||
if "ref-a" not in adapter._higgs_audio_v3_ref_code_inflight:
|
||||
break
|
||||
await asyncio.sleep(0.01)
|
||||
gc.collect()
|
||||
await asyncio.sleep(0)
|
||||
finally:
|
||||
release_encode.set()
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
assert "ref-a" not in adapter._higgs_audio_v3_ref_code_inflight
|
||||
assert not loop_errors
|
||||
@@ -68,7 +68,7 @@ def test_pack_and_unpack_round_trip_numpy_values():
|
||||
assert decoded["nested"][0]["done"] == np.bool_(True)
|
||||
|
||||
|
||||
def test_unpack_accepts_msgpack_numpy_marker_dicts():
|
||||
def test_unpack_accepts_vllm_native_marker_dicts():
|
||||
action = np.asarray([[1.0, 2.0]], dtype=np.float32)
|
||||
payload = {
|
||||
b"actions": {
|
||||
@@ -88,6 +88,58 @@ def test_unpack_accepts_msgpack_numpy_marker_dicts():
|
||||
np.testing.assert_allclose(decoded[b"actions"], np.asarray([[1.0, 0.0]], dtype=np.float32))
|
||||
|
||||
|
||||
def test_unpack_accepts_msgpack_numpy_marker_dicts():
|
||||
action = np.asarray([[1.0, 2.0]], dtype=np.float32)
|
||||
payload = {
|
||||
b"actions": {
|
||||
b"nd": True,
|
||||
b"type": action.dtype.str,
|
||||
b"kind": b"",
|
||||
b"shape": action.shape,
|
||||
b"data": action.tobytes(),
|
||||
}
|
||||
}
|
||||
|
||||
decoded = openpi_connection._unpack_numpy(payload)
|
||||
|
||||
np.testing.assert_allclose(decoded[b"actions"], action)
|
||||
assert decoded[b"actions"].dtype == np.float32
|
||||
|
||||
|
||||
def test_unpack_rejects_msgpack_numpy_structured_array_markers():
|
||||
values = np.zeros(2, dtype=[("a", "<i4"), ("b", "<f4")])
|
||||
payload = {
|
||||
b"nd": True,
|
||||
b"type": values.dtype.descr,
|
||||
b"kind": b"V",
|
||||
b"shape": values.shape,
|
||||
b"data": values.tobytes(),
|
||||
}
|
||||
|
||||
with pytest.raises(ValueError, match="Unsupported dtype"):
|
||||
openpi_connection._unpack_numpy(payload)
|
||||
|
||||
|
||||
def test_unpack_msgpack_numpy_packed_observation():
|
||||
msgpack_numpy = pytest.importorskip("msgpack_numpy")
|
||||
obs = {
|
||||
"observation/exterior_image_0_left": np.zeros((180, 320, 3), dtype=np.uint8),
|
||||
"observation/joint_position": np.arange(7, dtype=np.float32),
|
||||
}
|
||||
|
||||
decoded = openpi_connection._unpack(msgpack_numpy.packb(obs))
|
||||
|
||||
np.testing.assert_array_equal(
|
||||
decoded["observation/exterior_image_0_left"],
|
||||
obs["observation/exterior_image_0_left"],
|
||||
)
|
||||
np.testing.assert_allclose(
|
||||
decoded["observation/joint_position"],
|
||||
obs["observation/joint_position"],
|
||||
)
|
||||
assert decoded["observation/joint_position"].dtype == np.float32
|
||||
|
||||
|
||||
def test_unpack_accepts_openpi_client_ndarray_markers():
|
||||
image = np.arange(6, dtype=np.uint8).reshape(2, 3)
|
||||
payload = {
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import threading
|
||||
@@ -218,6 +221,18 @@ def test_build_request_uses_unique_engine_request_id_per_inference():
|
||||
assert request_a.request_id != request_b.request_id
|
||||
|
||||
|
||||
def test_build_request_forwards_seed_to_sampling_params():
|
||||
"""``seed`` in the inference message is the engine-level seed; omitted, the request auto-seeds."""
|
||||
serving = openpi_serving.ServingRealtimeRobotOpenPI(engine_client=_engine_with_policy_config())
|
||||
|
||||
seeded = serving._build_request({"prompt": "pick up the object", "seed": 42}, session_id="s", reset=True)
|
||||
unseeded = serving._build_request({"prompt": "pick up the object"}, session_id="s", reset=False)
|
||||
|
||||
assert seeded.sampling_params.seed == 42
|
||||
assert "seed" not in seeded.sampling_params.extra_args["robot_obs"]
|
||||
assert isinstance(unseeded.sampling_params.seed, int)
|
||||
|
||||
|
||||
def test_infer_keeps_session_state_but_uses_unique_engine_request_ids():
|
||||
engine = RecordingEngine()
|
||||
serving = openpi_serving.ServingRealtimeRobotOpenPI(engine_client=engine)
|
||||
|
||||
@@ -3,10 +3,11 @@
|
||||
"""
|
||||
E2E online tests for Qwen3-Omni /v1/realtime WebSocket (streaming PCM in, audio out).
|
||||
|
||||
Three scenarios:
|
||||
Four scenarios:
|
||||
- Ready CI: async_chunk on, smoke only (no send delay, no accuracy check).
|
||||
- Merge CI: async_chunk on + send delay, full accuracy check.
|
||||
- Merge CI: async_chunk off, no send delay, full accuracy check.
|
||||
- Server VAD: two turns without client commits.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -28,11 +29,18 @@ from tests.helpers.media import (
|
||||
generate_synthetic_audio,
|
||||
)
|
||||
from tests.helpers.runtime import OmniServerParams
|
||||
from tests.helpers.stage_config import get_deploy_config_path
|
||||
from tests.helpers.stage_config import get_deploy_config_path, modify_stage_config
|
||||
from vllm_omni.config.stage_config import load_deploy_config
|
||||
from vllm_omni.entrypoints.duplex.server_vad import (
|
||||
SILERO_VAD_FILENAME,
|
||||
SILERO_VAD_REPO_ID,
|
||||
SILERO_VAD_REVISION,
|
||||
)
|
||||
|
||||
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
|
||||
|
||||
MODEL = "Qwen/Qwen3-Omni-30B-A3B-Instruct"
|
||||
MODEL = os.environ.get("VLLM_OMNI_TEST_QWEN3_OMNI_MODEL", "Qwen/Qwen3-Omni-30B-A3B-Instruct")
|
||||
SERVER_VAD_MODEL_PATH = os.environ.get("VLLM_OMNI_TEST_SILERO_VAD_MODEL_PATH")
|
||||
|
||||
# Synthetic input for realtime E2E (``generate_synthetic_audio``); distinct cache file per phrase.
|
||||
REALTIME_SYNTH_PHRASE_TEXT = (
|
||||
@@ -48,6 +56,15 @@ SEND_DELAY_MS = 200
|
||||
|
||||
# CI overlay bakes in async_chunk: False and covers CUDA/ROCm/XPU via ``platforms:``.
|
||||
default_stage_config = get_deploy_config_path("ci/qwen3_omni_moe.yaml")
|
||||
server_vad_stage_config = modify_stage_config(
|
||||
default_stage_config,
|
||||
{
|
||||
"async_chunk": True,
|
||||
"duplex_session": (
|
||||
{"server_vad_model_path": SERVER_VAD_MODEL_PATH} if SERVER_VAD_MODEL_PATH is not None else {}
|
||||
),
|
||||
},
|
||||
)
|
||||
|
||||
realtime_sync_server_params = [
|
||||
pytest.param(
|
||||
@@ -72,6 +89,17 @@ realtime_async_chunk_server_params = [
|
||||
),
|
||||
]
|
||||
|
||||
realtime_server_vad_server_params = [
|
||||
pytest.param(
|
||||
OmniServerParams(
|
||||
model=MODEL,
|
||||
stage_config_path=server_vad_stage_config,
|
||||
use_stage_cli=True,
|
||||
),
|
||||
id="server_vad",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def _pcm16_mono_16k_from_wav_bytes(wav_bytes: bytes) -> bytes:
|
||||
with wave.open(io.BytesIO(wav_bytes), "rb") as wf:
|
||||
@@ -183,6 +211,86 @@ async def _run_realtime_audio_roundtrip(
|
||||
}
|
||||
|
||||
|
||||
async def _append_pcm16_chunks(ws, pcm16: bytes, chunk_bytes: int) -> None:
|
||||
for offset in range(0, len(pcm16), chunk_bytes):
|
||||
await ws.send(
|
||||
json.dumps(
|
||||
{
|
||||
"type": "input_audio_buffer.append",
|
||||
"audio": base64.b64encode(pcm16[offset : offset + chunk_bytes]).decode("utf-8"),
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
async def _receive_server_vad_turn(ws) -> list[dict]:
|
||||
events: list[dict] = []
|
||||
while True:
|
||||
message = await asyncio.wait_for(ws.recv(), timeout=600)
|
||||
if isinstance(message, bytes):
|
||||
continue
|
||||
event = json.loads(message)
|
||||
events.append(event)
|
||||
if event.get("type") == "error":
|
||||
raise AssertionError(f"WebSocket error: {event}")
|
||||
if event.get("type") == "response.done":
|
||||
return events
|
||||
|
||||
|
||||
async def _run_server_vad_audio_roundtrips(
|
||||
host: str,
|
||||
port: int,
|
||||
model: str,
|
||||
pcm16: bytes,
|
||||
*,
|
||||
chunk_ms: int = 100,
|
||||
turns: int = 2,
|
||||
) -> list[list[dict]]:
|
||||
chunk_bytes = max(16_000 * 2 // 1000 * chunk_ms, 2)
|
||||
turn_events: list[list[dict]] = []
|
||||
|
||||
async with websockets.connect(f"ws://{host}:{port}/v1/realtime", max_size=64 * 1024 * 1024) as ws:
|
||||
await ws.send(
|
||||
json.dumps(
|
||||
{
|
||||
"type": "session.update",
|
||||
"session": {
|
||||
"model": model,
|
||||
"audio": {
|
||||
"input": {
|
||||
"format": {"type": "audio/pcm", "rate": 16_000},
|
||||
"turn_detection": {"type": "server_vad"},
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
silence = bytes(16_000 * 2 * 3 // 2)
|
||||
for _ in range(turns):
|
||||
await _append_pcm16_chunks(ws, pcm16, chunk_bytes)
|
||||
await _append_pcm16_chunks(ws, silence, chunk_bytes)
|
||||
turn_events.append(await _receive_server_vad_turn(ws))
|
||||
|
||||
return turn_events
|
||||
|
||||
|
||||
@pytest.fixture(scope="class")
|
||||
def cached_silero_vad_artifact() -> str:
|
||||
"""Prepare the pinned artifact before the serving subprocess starts."""
|
||||
if SERVER_VAD_MODEL_PATH is not None:
|
||||
return SERVER_VAD_MODEL_PATH
|
||||
|
||||
from huggingface_hub import hf_hub_download
|
||||
|
||||
return hf_hub_download(
|
||||
repo_id=SILERO_VAD_REPO_ID,
|
||||
filename=SILERO_VAD_FILENAME,
|
||||
revision=SILERO_VAD_REVISION,
|
||||
)
|
||||
|
||||
|
||||
def _synthetic_pcm16_input(
|
||||
*,
|
||||
phrase_text: str = REALTIME_SYNTH_PHRASE_TEXT,
|
||||
@@ -296,6 +404,66 @@ class TestQwen3OmniRealtimeWebSocket:
|
||||
f"Expected an issue-like audio response longer than 5 seconds, got {output_duration_s:.2f}s"
|
||||
)
|
||||
|
||||
@pytest.mark.advanced_model
|
||||
@pytest.mark.omni
|
||||
@hardware_test(res={"cuda": "H100", "rocm": "MI325"}, num_cards=2)
|
||||
@pytest.mark.parametrize("omni_server", realtime_server_vad_server_params, indirect=True)
|
||||
def test_server_vad_multi_turn_without_client_commit(
|
||||
self,
|
||||
cached_silero_vad_artifact: str,
|
||||
omni_server,
|
||||
) -> None:
|
||||
"""Two Qwen turns are endpointed without client commits."""
|
||||
assert cached_silero_vad_artifact
|
||||
deploy = load_deploy_config(server_vad_stage_config)
|
||||
assert deploy.session_mode == "turn"
|
||||
assert deploy.async_chunk is True
|
||||
assert deploy.duplex_session.server_vad_model_path == SERVER_VAD_MODEL_PATH
|
||||
pcm16 = _synthetic_pcm16_input()
|
||||
|
||||
turns = asyncio.run(
|
||||
_run_server_vad_audio_roundtrips(
|
||||
omni_server.host,
|
||||
omni_server.port,
|
||||
omni_server.model,
|
||||
pcm16,
|
||||
chunk_ms=100,
|
||||
turns=2,
|
||||
)
|
||||
)
|
||||
|
||||
assert len(turns) == 2
|
||||
required_sequence = [
|
||||
"input_audio_buffer.speech_started",
|
||||
"input_audio_buffer.speech_stopped",
|
||||
"input_audio_buffer.committed",
|
||||
"response.created",
|
||||
"response.audio.delta",
|
||||
"response.audio.done",
|
||||
"response.done",
|
||||
]
|
||||
input_item_ids: list[str] = []
|
||||
response_ids: list[str] = []
|
||||
for events in turns:
|
||||
event_types = [event["type"] for event in events]
|
||||
positions = [event_types.index(event_type) for event_type in required_sequence]
|
||||
assert positions == sorted(positions)
|
||||
|
||||
started = next(event for event in events if event["type"] == "input_audio_buffer.speech_started")
|
||||
stopped = next(event for event in events if event["type"] == "input_audio_buffer.speech_stopped")
|
||||
committed = next(event for event in events if event["type"] == "input_audio_buffer.committed")
|
||||
created = next(event for event in events if event["type"] == "response.created")["response"]
|
||||
done = next(event for event in events if event["type"] == "response.done")["response"]
|
||||
|
||||
assert started["item_id"] == stopped["item_id"] == committed["item_id"]
|
||||
assert created["id"] == done["id"]
|
||||
assert done["status"] == "completed"
|
||||
input_item_ids.append(committed["item_id"])
|
||||
response_ids.append(created["id"])
|
||||
|
||||
assert len(set(input_item_ids)) == 2
|
||||
assert len(set(response_ids)) == 2
|
||||
|
||||
@pytest.mark.advanced_model
|
||||
@pytest.mark.omni
|
||||
@hardware_test(res={"cuda": "H100", "rocm": "MI325"}, num_cards=2)
|
||||
|
||||
@@ -0,0 +1,429 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import io
|
||||
import sys
|
||||
import threading
|
||||
import wave
|
||||
import weakref
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from types import SimpleNamespace
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from vllm_omni.entrypoints.duplex.protocol import (
|
||||
DuplexSession,
|
||||
DuplexSessionConfig,
|
||||
)
|
||||
from vllm_omni.entrypoints.duplex.server_vad import (
|
||||
ServerVADConfig,
|
||||
ServerVADFrame,
|
||||
ServerVADPipeline,
|
||||
SileroVADBackend,
|
||||
SileroVADBackendProvider,
|
||||
SpeechEndpointDecision,
|
||||
ThresholdEndpointPolicy,
|
||||
parse_session_turn_detection,
|
||||
)
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
class SequenceDetector:
|
||||
frame_samples = 160
|
||||
|
||||
def __init__(self, probabilities: list[float]) -> None:
|
||||
self.probabilities = probabilities
|
||||
|
||||
def new_state(self) -> int:
|
||||
return 0
|
||||
|
||||
def infer(self, frame: np.ndarray, state: object) -> tuple[float, object]:
|
||||
index = int(state)
|
||||
probability = self.probabilities[index] if index < len(self.probabilities) else 0.0
|
||||
return probability, index + 1
|
||||
|
||||
|
||||
def test_server_vad_config_defaults_and_validation():
|
||||
config = ServerVADConfig.from_value({"type": "server_vad"})
|
||||
|
||||
assert config.type == "server_vad"
|
||||
assert config.threshold == 0.5
|
||||
assert config.prefix_padding_ms == 300
|
||||
assert config.silence_duration_ms == 500
|
||||
assert config.create_response is True
|
||||
assert config.interrupt_response is None
|
||||
assert "interrupt_response" not in config.as_dict()
|
||||
assert config.min_speech_duration_ms is None
|
||||
assert config.as_dict()["type"] == config.type
|
||||
|
||||
interrupting = ServerVADConfig.from_value(
|
||||
{
|
||||
"type": "server_vad",
|
||||
"interrupt_response": True,
|
||||
"min_speech_duration_ms": 96,
|
||||
}
|
||||
)
|
||||
assert interrupting.interrupt_response is True
|
||||
assert interrupting.min_speech_duration_ms == 96
|
||||
for value in (None, 0, "true"):
|
||||
with pytest.raises(ValueError, match="interrupt_response must be a boolean"):
|
||||
ServerVADConfig.from_value({"type": "server_vad", "interrupt_response": value})
|
||||
for enabled in (False, True):
|
||||
_, aliased = parse_session_turn_detection(
|
||||
{
|
||||
"turn_detection": {"type": "server_vad"},
|
||||
"audio": {"input": {"turn_detection": {"type": "server_vad", "interrupt_response": enabled}}},
|
||||
}
|
||||
)
|
||||
assert aliased is not None and aliased.interrupt_response is enabled
|
||||
with pytest.raises(ValueError, match="Unknown"):
|
||||
ServerVADConfig.from_value({"type": "server_vad", "semantic_eagerness": "high"})
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("prefix_padding_ms", [0, 10, 30])
|
||||
async def test_server_vad_pipeline_handles_arbitrary_chunk_boundaries(prefix_padding_ms: int):
|
||||
detector = SequenceDetector([0.0, 0.9, 0.8, 0.0, 0.0])
|
||||
pipeline = ServerVADPipeline(
|
||||
detector,
|
||||
ServerVADConfig(prefix_padding_ms=prefix_padding_ms, silence_duration_ms=20),
|
||||
)
|
||||
samples = np.zeros(detector.frame_samples * 5, dtype=np.float32)
|
||||
|
||||
batches = [
|
||||
await pipeline.push(samples[:73]),
|
||||
await pipeline.push(samples[73:431]),
|
||||
await pipeline.push(samples[431:]),
|
||||
]
|
||||
frames = [frame for batch in batches for frame in batch.frames]
|
||||
|
||||
assert len(frames) == 5
|
||||
assert [index for index, frame in enumerate(frames) if frame.decision.speech_started] == [1]
|
||||
assert [index for index, frame in enumerate(frames) if frame.decision.speech_stopped] == [4]
|
||||
assert frames[1].decision.audio_start_ms == max(0, 10 - prefix_padding_ms)
|
||||
assert frames[4].decision.audio_end_ms == 50
|
||||
|
||||
pipeline.reset()
|
||||
reset_batch = await pipeline.push(samples)
|
||||
assert [index for index, frame in enumerate(reset_batch.frames) if frame.decision.speech_started] == [1]
|
||||
assert [index for index, frame in enumerate(reset_batch.frames) if frame.decision.speech_stopped] == [4]
|
||||
# Keep session-relative timestamps, but never reference prefix audio
|
||||
# discarded by reset at 50 ms.
|
||||
assert reset_batch.frames[1].decision.audio_start_ms == max(50, 60 - prefix_padding_ms)
|
||||
assert reset_batch.frames[4].decision.audio_end_ms == 100
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_server_vad_retained_audio_does_not_keep_input_chunk():
|
||||
pipeline = ServerVADPipeline(SequenceDetector([]), ServerVADConfig())
|
||||
session = DuplexSession("server-vad-memory", DuplexSessionConfig())
|
||||
samples = np.zeros(160 * 100 + 1, dtype=np.float32)
|
||||
source_ref = weakref.ref(samples)
|
||||
batch = await pipeline.push(samples)
|
||||
session.append_server_vad_frame(
|
||||
batch.frames[-1].samples,
|
||||
speech_started=False,
|
||||
speech_stopped=False,
|
||||
prefix_samples=80,
|
||||
)
|
||||
session.append_server_vad_frame(
|
||||
batch.frames[-1].samples,
|
||||
speech_started=True,
|
||||
speech_stopped=False,
|
||||
prefix_samples=80,
|
||||
)
|
||||
del batch, samples
|
||||
# Allow the completed to_thread callback to release its result, too.
|
||||
await asyncio.sleep(0)
|
||||
|
||||
assert source_ref() is None
|
||||
assert pipeline.scratch_bytes == 4
|
||||
assert session.server_vad_utterance_bytes == (80 + 160) * 4
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_server_vad_pipeline_pcm16_resampling_is_split_invariant():
|
||||
sample_index = np.arange(2_400, dtype=np.int32)
|
||||
source = ((sample_index * 7919) % 65_536 - 32_768).astype("<i2")
|
||||
# Supply ample silence after the signal so the streaming resampler can
|
||||
# emit a complete set of VAD frames without depending on its FIR width.
|
||||
right_context = np.zeros(240, dtype="<i2")
|
||||
continuous_source = np.concatenate((source, right_context))
|
||||
|
||||
async def process(chunk_sizes: list[int]) -> tuple[np.ndarray, list[SpeechEndpointDecision]]:
|
||||
pipeline = ServerVADPipeline(
|
||||
SequenceDetector([0.0] * 10),
|
||||
ServerVADConfig(),
|
||||
)
|
||||
frames: list[ServerVADFrame] = []
|
||||
offset = 0
|
||||
for chunk_size in chunk_sizes:
|
||||
chunk = continuous_source[offset : offset + chunk_size]
|
||||
batch = await pipeline.push_pcm16(chunk.tobytes(), source_sample_rate_hz=24_000)
|
||||
frames.extend(batch.frames)
|
||||
offset += chunk_size
|
||||
assert offset == continuous_source.size
|
||||
return np.concatenate([frame.samples for frame in frames]), [frame.decision for frame in frames]
|
||||
|
||||
whole_samples, whole_decisions = await process([continuous_source.size])
|
||||
split_samples, split_decisions = await process([7, 13, 511, 512, 513, continuous_source.size - 1_556])
|
||||
|
||||
np.testing.assert_array_equal(split_samples, whole_samples)
|
||||
assert whole_samples.size == 1_600
|
||||
assert split_decisions == whole_decisions
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_server_vad_pipeline_reset_clears_resampler_and_source_rate_lock():
|
||||
pipeline = ServerVADPipeline(
|
||||
SequenceDetector([0.0]),
|
||||
ServerVADConfig(),
|
||||
)
|
||||
|
||||
batch = await pipeline.push_pcm16(
|
||||
np.asarray([30_000, -30_000], dtype="<i2").tobytes(),
|
||||
source_sample_rate_hz=24_000,
|
||||
)
|
||||
assert not batch.frames
|
||||
|
||||
pipeline.reset()
|
||||
|
||||
source = np.zeros(160, dtype="<i2")
|
||||
source[:3] = [-32768, 0, 32767]
|
||||
batch = await pipeline.push_pcm16(source.tobytes(), source_sample_rate_hz=16_000)
|
||||
|
||||
assert len(batch.frames) == 1
|
||||
np.testing.assert_array_equal(
|
||||
batch.frames[0].samples[:3],
|
||||
np.asarray([-1.0, 0.0, 32767 / 32768], dtype=np.float32),
|
||||
)
|
||||
|
||||
|
||||
def test_threshold_endpoint_policy_uses_silero_v62_exit_hysteresis():
|
||||
policy = ThresholdEndpointPolicy(
|
||||
ServerVADConfig(threshold=0.5, silence_duration_ms=20),
|
||||
sample_rate_hz=16_000,
|
||||
)
|
||||
frame_samples = 160
|
||||
|
||||
started = policy.update(0.8, frame_start_sample=0, frame_samples=frame_samples)
|
||||
assert started.speech_started is True
|
||||
|
||||
# Values below the activation threshold but above threshold - 0.15 must
|
||||
# not begin a silence candidate or close an active speech segment.
|
||||
for frame_index in range(1, 5):
|
||||
decision = policy.update(
|
||||
0.4,
|
||||
frame_start_sample=frame_index * frame_samples,
|
||||
frame_samples=frame_samples,
|
||||
)
|
||||
assert decision.speech_stopped is False
|
||||
|
||||
first_silence = policy.update(
|
||||
0.2,
|
||||
frame_start_sample=5 * frame_samples,
|
||||
frame_samples=frame_samples,
|
||||
)
|
||||
stopped = policy.update(
|
||||
0.2,
|
||||
frame_start_sample=6 * frame_samples,
|
||||
frame_samples=frame_samples,
|
||||
)
|
||||
|
||||
assert first_silence.speech_stopped is False
|
||||
assert stopped.speech_stopped is True
|
||||
|
||||
|
||||
def test_threshold_endpoint_policy_honors_minimum_speech_duration():
|
||||
policy = ThresholdEndpointPolicy(
|
||||
ServerVADConfig(prefix_padding_ms=0, min_speech_duration_ms=25),
|
||||
sample_rate_hz=16_000,
|
||||
)
|
||||
frame_samples = 160
|
||||
|
||||
assert not policy.update(0.9, frame_start_sample=0, frame_samples=frame_samples).speech_started
|
||||
assert not policy.update(0.9, frame_start_sample=160, frame_samples=frame_samples).speech_started
|
||||
started = policy.update(0.9, frame_start_sample=320, frame_samples=frame_samples)
|
||||
|
||||
assert started.speech_started is True
|
||||
assert started.audio_start_ms == 0
|
||||
|
||||
|
||||
def test_threshold_endpoint_policy_clamps_silero_exit_threshold():
|
||||
policy = ThresholdEndpointPolicy(
|
||||
ServerVADConfig(threshold=0.1, silence_duration_ms=20),
|
||||
sample_rate_hz=16_000,
|
||||
)
|
||||
frame_samples = 160
|
||||
|
||||
started = policy.update(0.9, frame_start_sample=0, frame_samples=frame_samples)
|
||||
assert started.speech_started is True
|
||||
|
||||
first_silence = policy.update(
|
||||
0.0,
|
||||
frame_start_sample=frame_samples,
|
||||
frame_samples=frame_samples,
|
||||
)
|
||||
stopped = policy.update(
|
||||
0.0,
|
||||
frame_start_sample=2 * frame_samples,
|
||||
frame_samples=frame_samples,
|
||||
)
|
||||
|
||||
assert first_silence.speech_stopped is False
|
||||
assert stopped.speech_stopped is True
|
||||
# The committed audio ends at 30 ms: 10 ms of speech followed by the
|
||||
# 20 ms of silence required to detect the endpoint.
|
||||
assert stopped.audio_end_ms == 30
|
||||
assert stopped.endpoint_delay_ms == 20
|
||||
|
||||
|
||||
def test_silero_backend_matches_upstream_v62_streaming_contract(monkeypatch, tmp_path):
|
||||
class FakeSessionOptions:
|
||||
inter_op_num_threads = 0
|
||||
intra_op_num_threads = 0
|
||||
|
||||
class FakeInferenceSession:
|
||||
def __init__(self, path: str, *, providers: list[str], sess_options: object) -> None:
|
||||
self.providers = providers
|
||||
self.sess_options = sess_options
|
||||
self.calls: list[dict[str, np.ndarray]] = []
|
||||
self.run_barrier: threading.Barrier | None = None
|
||||
sessions.append(self)
|
||||
|
||||
def get_inputs(self) -> list[SimpleNamespace]:
|
||||
return [SimpleNamespace(name=name) for name in ("input", "state", "sr")]
|
||||
|
||||
def run(self, _outputs: object, inputs: dict[str, np.ndarray]) -> list[np.ndarray]:
|
||||
self.calls.append({name: np.array(value, copy=True) for name, value in inputs.items()})
|
||||
if self.run_barrier is not None:
|
||||
self.run_barrier.wait(timeout=5)
|
||||
return [
|
||||
np.asarray([[0.75]], dtype=np.float32),
|
||||
np.full((2, 1, 128), len(self.calls), dtype=np.float32),
|
||||
]
|
||||
|
||||
sessions: list[FakeInferenceSession] = []
|
||||
monkeypatch.setitem(
|
||||
sys.modules,
|
||||
"onnxruntime",
|
||||
SimpleNamespace(
|
||||
SessionOptions=FakeSessionOptions,
|
||||
InferenceSession=FakeInferenceSession,
|
||||
),
|
||||
)
|
||||
|
||||
model_path = tmp_path / "silero_vad.onnx"
|
||||
model_path.write_bytes(b"fake-model")
|
||||
backend = SileroVADBackend(model_path)
|
||||
session = sessions[0]
|
||||
|
||||
assert session.providers == ["CPUExecutionProvider"]
|
||||
assert session.sess_options.inter_op_num_threads == 1
|
||||
assert session.sess_options.intra_op_num_threads == 1
|
||||
assert session.calls[0]["input"].shape == (1, 576)
|
||||
assert session.calls[0]["state"].shape == (2, 1, 128)
|
||||
np.testing.assert_array_equal(session.calls[0]["state"], np.zeros((2, 1, 128), dtype=np.float32))
|
||||
assert session.calls[0]["sr"].shape == ()
|
||||
assert session.calls[0]["sr"].item() == 16_000
|
||||
|
||||
state = backend.new_state()
|
||||
first_frame = np.arange(backend.frame_samples, dtype=np.float32)
|
||||
probability, state = backend.infer(first_frame, state)
|
||||
first_call = session.calls[1]
|
||||
|
||||
assert probability == pytest.approx(0.75)
|
||||
np.testing.assert_array_equal(
|
||||
first_call["input"][:, : backend.context_samples],
|
||||
np.zeros((1, backend.context_samples), dtype=np.float32),
|
||||
)
|
||||
np.testing.assert_array_equal(
|
||||
first_call["input"][:, backend.context_samples :],
|
||||
first_frame[None, :],
|
||||
)
|
||||
np.testing.assert_array_equal(first_call["state"], np.zeros((2, 1, 128), dtype=np.float32))
|
||||
|
||||
second_frame = -first_frame
|
||||
backend.infer(second_frame, state)
|
||||
second_call = session.calls[2]
|
||||
np.testing.assert_array_equal(
|
||||
second_call["input"][:, : backend.context_samples],
|
||||
first_frame[None, -backend.context_samples :],
|
||||
)
|
||||
np.testing.assert_array_equal(
|
||||
second_call["input"][:, backend.context_samples :],
|
||||
second_frame[None, :],
|
||||
)
|
||||
np.testing.assert_array_equal(
|
||||
second_call["state"],
|
||||
np.full((2, 1, 128), 2, dtype=np.float32),
|
||||
)
|
||||
|
||||
# Independent pipeline states may enter the shared ORT session concurrently.
|
||||
session.run_barrier = threading.Barrier(2)
|
||||
with ThreadPoolExecutor(max_workers=2) as executor:
|
||||
futures = [
|
||||
executor.submit(backend.infer, first_frame, backend.new_state()),
|
||||
executor.submit(backend.infer, second_frame, backend.new_state()),
|
||||
]
|
||||
assert [future.result()[0] for future in futures] == pytest.approx([0.75, 0.75])
|
||||
|
||||
|
||||
def test_duplex_session_owns_server_vad_prefix_and_utterance_audio():
|
||||
session = DuplexSession("server-vad-session", DuplexSessionConfig())
|
||||
frame = np.zeros(160, dtype=np.float32)
|
||||
|
||||
session.reserve_input_bytes(frame.nbytes * 3, limit=frame.nbytes * 4)
|
||||
released = session.append_server_vad_frame(
|
||||
frame,
|
||||
speech_started=False,
|
||||
speech_stopped=False,
|
||||
prefix_samples=160,
|
||||
)
|
||||
assert released == 0
|
||||
released = session.append_server_vad_frame(
|
||||
frame,
|
||||
speech_started=False,
|
||||
speech_stopped=False,
|
||||
prefix_samples=160,
|
||||
)
|
||||
assert released == frame.nbytes
|
||||
session.release_input_bytes(released)
|
||||
session.append_server_vad_frame(
|
||||
frame,
|
||||
speech_started=True,
|
||||
speech_stopped=False,
|
||||
prefix_samples=160,
|
||||
)
|
||||
|
||||
assert session.server_vad_utterance_bytes == frame.nbytes * 2
|
||||
assert session.stage_server_vad_audio_for_commit() is True
|
||||
committed = session.commit_user_input()
|
||||
assert committed is not None
|
||||
assert committed.message["role"] == "user"
|
||||
audio_url = committed.message["content"][0]["audio_url"]["url"]
|
||||
assert audio_url.startswith("data:audio/wav;base64,")
|
||||
wav_bytes = base64.b64decode(audio_url.partition(",")[2])
|
||||
with wave.open(io.BytesIO(wav_bytes), "rb") as wav_file:
|
||||
assert wav_file.getnchannels() == 1
|
||||
assert wav_file.getsampwidth() == 2
|
||||
assert wav_file.getframerate() == 16_000
|
||||
assert wav_file.getnframes() == frame.size * 2
|
||||
|
||||
|
||||
def test_silero_provider_rejects_missing_or_invalid_local_artifact(tmp_path):
|
||||
missing = SileroVADBackendProvider(model_path=str(tmp_path / "missing.onnx"))
|
||||
with pytest.raises(RuntimeError, match="does not exist"):
|
||||
missing.get()
|
||||
|
||||
invalid_path = tmp_path / "silero_vad.onnx"
|
||||
invalid_path.write_bytes(b"not-the-pinned-model")
|
||||
invalid = SileroVADBackendProvider(model_path=str(invalid_path))
|
||||
with pytest.raises(RuntimeError, match="checksum mismatch"):
|
||||
invalid.get()
|
||||
@@ -27,6 +27,9 @@ from pydantic import ValidationError
|
||||
from pytest_mock import MockerFixture
|
||||
from vllm.entrypoints.openai.engine.protocol import ErrorInfo, ErrorResponse
|
||||
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.diffusion.sched.request_scheduler import RequestScheduler
|
||||
from vllm_omni.diffusion.sched.step_scheduler import StepScheduler
|
||||
from vllm_omni.entrypoints.omni_base import OmniEngineDeadError
|
||||
from vllm_omni.entrypoints.openai import api_server as api_server_module
|
||||
from vllm_omni.entrypoints.openai import serving_speech as serving_speech_module
|
||||
@@ -53,8 +56,9 @@ from vllm_omni.entrypoints.openai.tts_adapters.base import (
|
||||
)
|
||||
from vllm_omni.entrypoints.openai.tts_adapters.capabilities import load_supported_speakers
|
||||
from vllm_omni.entrypoints.openai.tts_adapters.ming_tts import MingTTSAdapter
|
||||
from vllm_omni.entrypoints.openai.tts_adapters.qwen3_tts import Qwen3TTSCodecLimitError
|
||||
from vllm_omni.entrypoints.openai.tts_adapters.qwen3_tts import Qwen3TTSAdapter, Qwen3TTSCodecLimitError
|
||||
from vllm_omni.entrypoints.openai.tts_adapters.voxtral import VoxtralTTSAdapter
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
|
||||
from vllm_omni.model_executor.models.fish_speech.prompt_utils import (
|
||||
FISH_TEXT_ONLY_SYSTEM_PROMPT,
|
||||
build_fish_voice_clone_prompt_ids,
|
||||
@@ -753,13 +757,12 @@ class TestSpeechAPI:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_diffusion_speech_extra_params(self, mocker: MockerFixture):
|
||||
"""Test public diffusion speech success and extra_params propagation."""
|
||||
"""Test diffusion parameters reach StepScheduler as standard fields."""
|
||||
# Mock the engine client
|
||||
mock_engine = mocker.MagicMock()
|
||||
|
||||
# Mock default sampling params
|
||||
mock_sampling_param = mocker.MagicMock()
|
||||
mock_sampling_param.extra_args = {"existing_arg": "value"}
|
||||
mock_sampling_param = OmniDiffusionSamplingParams(extra_args={"existing_arg": "value"})
|
||||
mock_engine.default_sampling_params_list = [mock_sampling_param]
|
||||
|
||||
# Mock generate to yield a valid OmniRequestOutput
|
||||
@@ -775,7 +778,15 @@ class TestSpeechAPI:
|
||||
server, "create_audio", return_value=mocker.MagicMock(audio_data=b"dummy", media_type="audio/wav")
|
||||
)
|
||||
|
||||
req = OpenAICreateSpeechRequest(input="Hello", extra_params={"new_arg": 123, "existing_arg": "new_value"})
|
||||
req = OpenAICreateSpeechRequest(
|
||||
input="Hello",
|
||||
extra_params={
|
||||
"new_arg": 123,
|
||||
"existing_arg": "new_value",
|
||||
"num_inference_steps": 12,
|
||||
"guidance_scale": 7.0,
|
||||
},
|
||||
)
|
||||
|
||||
response = await server.create_speech(req)
|
||||
|
||||
@@ -792,7 +803,98 @@ class TestSpeechAPI:
|
||||
|
||||
# Verify it was deepcopied and updated
|
||||
assert passed_params is not mock_engine.default_sampling_params_list
|
||||
assert passed_params[0].extra_args == {"existing_arg": "new_value", "new_arg": 123}
|
||||
assert passed_params[0].extra_args == {
|
||||
"existing_arg": "new_value",
|
||||
"new_arg": 123,
|
||||
"num_inference_steps": 12,
|
||||
"guidance_scale": 7.0,
|
||||
}
|
||||
assert passed_params[0].num_inference_steps == 12
|
||||
assert passed_params[0].guidance_scale == 7.0
|
||||
|
||||
# Regression: StepScheduler.add_request() used to receive
|
||||
# num_inference_steps=None and fail while converting it to int.
|
||||
scheduler = StepScheduler()
|
||||
scheduler.add_request(
|
||||
OmniDiffusionRequest(
|
||||
prompt="Hello",
|
||||
sampling_params=passed_params[0],
|
||||
request_id="speech-test",
|
||||
)
|
||||
)
|
||||
assert scheduler._request_progress["speech-test"].total_steps == 12
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_diffusion_speech_guidance_promotion_controls_request_batch_admission(
|
||||
self,
|
||||
mocker: MockerFixture,
|
||||
) -> None:
|
||||
"""Different request guidance values must not enter one request batch."""
|
||||
mock_engine = mocker.MagicMock()
|
||||
mock_engine.default_sampling_params_list = [OmniDiffusionSamplingParams(num_inference_steps=12)]
|
||||
passed_sampling_params = []
|
||||
|
||||
async def mock_generate(*args, **kwargs):
|
||||
passed_sampling_params.append(kwargs["sampling_params_list"][0])
|
||||
yield create_mock_audio_output_for_test()
|
||||
|
||||
mock_engine.generate = mocker.MagicMock(side_effect=mock_generate)
|
||||
server = OmniOpenAIServingSpeech.for_diffusion(diffusion_engine=mock_engine, model_name="test-model")
|
||||
mocker.patch.object(
|
||||
server,
|
||||
"create_audio",
|
||||
return_value=mocker.MagicMock(audio_data=b"dummy", media_type="audio/wav"),
|
||||
)
|
||||
|
||||
for guidance_scale in (2.0, 7.0):
|
||||
response = await server.create_speech(
|
||||
OpenAICreateSpeechRequest(
|
||||
input="Hello",
|
||||
extra_params={"guidance_scale": guidance_scale},
|
||||
)
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
scheduler = RequestScheduler()
|
||||
scheduler.initialize(SimpleNamespace(max_num_seqs=2))
|
||||
for index, sampling_params in enumerate(passed_sampling_params):
|
||||
scheduler.add_request(
|
||||
OmniDiffusionRequest(
|
||||
prompt="Hello",
|
||||
sampling_params=sampling_params,
|
||||
request_id=f"speech-{index}",
|
||||
)
|
||||
)
|
||||
|
||||
first = scheduler.schedule()
|
||||
|
||||
assert [request.request_id for request in first.scheduled_new_reqs] == ["speech-0"]
|
||||
assert first.num_running_reqs == 1
|
||||
assert first.num_waiting_reqs == 1
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
("extra_params", "expected_message"),
|
||||
[
|
||||
({"num_inference_steps": "invalid"}, "num_inference_steps must be an integer"),
|
||||
({"guidance_scale": "invalid"}, "guidance_scale must be a number"),
|
||||
],
|
||||
)
|
||||
async def test_create_diffusion_speech_rejects_invalid_scheduler_params(
|
||||
self,
|
||||
mocker: MockerFixture,
|
||||
extra_params: dict[str, str],
|
||||
expected_message: str,
|
||||
) -> None:
|
||||
mock_engine = mocker.MagicMock()
|
||||
mock_engine.default_sampling_params_list = [OmniDiffusionSamplingParams()]
|
||||
server = OmniOpenAIServingSpeech.for_diffusion(diffusion_engine=mock_engine, model_name="test-model")
|
||||
|
||||
response = await server.create_speech(OpenAICreateSpeechRequest(input="Hello", extra_params=extra_params))
|
||||
|
||||
assert response.status_code == 400
|
||||
assert expected_message in response.body.decode()
|
||||
mock_engine.generate.assert_not_called()
|
||||
|
||||
|
||||
class TestTTSMethods:
|
||||
@@ -812,6 +914,15 @@ class TestTTSMethods:
|
||||
models=mock_models,
|
||||
request_logger=mocker.MagicMock(),
|
||||
)
|
||||
qwen3_adapter = Qwen3TTSAdapter(
|
||||
SpeechServingContext(
|
||||
server=server,
|
||||
engine_client=mock_engine_client,
|
||||
)
|
||||
)
|
||||
server._build_tts_params = qwen3_adapter._build_tts_params
|
||||
server._estimate_prompt_len = qwen3_adapter._estimate_prompt_len
|
||||
|
||||
yield server
|
||||
server.shutdown()
|
||||
|
||||
@@ -1663,12 +1774,12 @@ class TestTTSMethods:
|
||||
def test_conditioning_cache_salt_changes_with_ref_audio_cache_key(self):
|
||||
"""Prefix-cache salt must fold the content-aware resolve key so a
|
||||
same-path file rewrite cannot reuse KV from the previous reference."""
|
||||
from vllm_omni.entrypoints.openai.serving_speech import _conditioning_cache_salt
|
||||
from vllm_omni.entrypoints.openai.tts_adapters.base import conditioning_cache_salt
|
||||
|
||||
req = OpenAICreateSpeechRequest(input="hello", ref_audio="file:///data/spk.wav")
|
||||
salt_a = _conditioning_cache_salt(req, {"ref_audio_cache_key": "key_aaa"})
|
||||
salt_b = _conditioning_cache_salt(req, {"ref_audio_cache_key": "key_bbb"})
|
||||
salt_locator_only = _conditioning_cache_salt(req, {})
|
||||
salt_a = conditioning_cache_salt(req, {"ref_audio_cache_key": "key_aaa"})
|
||||
salt_b = conditioning_cache_salt(req, {"ref_audio_cache_key": "key_bbb"})
|
||||
salt_locator_only = conditioning_cache_salt(req, {})
|
||||
assert salt_a != salt_b
|
||||
assert salt_a != salt_locator_only
|
||||
|
||||
@@ -1689,20 +1800,22 @@ class TestTTSMethods:
|
||||
}
|
||||
adapter = HiggsAudioV3TokenizerAdapter(tokenizer)
|
||||
mocker.patch.object(adapter, "build_prompt", return_value=[1, -100, -100, 2])
|
||||
speech_server._resolve_higgs_audio_v3_adapter = mocker.AsyncMock(return_value=adapter)
|
||||
speech_server._tts_model_type = "higgs_audio_v3"
|
||||
speech_server._adapter = speech_server._get_tts_adapter()
|
||||
speech_server._adapter._resolve_higgs_audio_v3_adapter = mocker.AsyncMock(return_value=adapter)
|
||||
codes = torch.arange(16, dtype=torch.long).view(2, 8)
|
||||
speech_server._resolve_higgs_audio_v3_ref_codes = mocker.AsyncMock(return_value=(codes, False, False))
|
||||
speech_server._get_resolved_ref_audio_artifact_key = mocker.MagicMock(return_value="art")
|
||||
speech_server._adapter._resolve_higgs_audio_v3_ref_codes = mocker.AsyncMock(return_value=(codes, False, False))
|
||||
speech_server._adapter._get_resolved_ref_audio_artifact_key = mocker.MagicMock(return_value="art")
|
||||
|
||||
req = OpenAICreateSpeechRequest(
|
||||
input="hello",
|
||||
ref_audio="file:///data/spk.wav",
|
||||
ref_text="transcript",
|
||||
)
|
||||
speech_server._resolve_ref_audio = mocker.AsyncMock(return_value=([0.1] * 48000, 24000, "key_aaa"))
|
||||
prompt_a = await speech_server._build_higgs_audio_v3_params(req)
|
||||
speech_server._resolve_ref_audio = mocker.AsyncMock(return_value=([0.9] * 48000, 24000, "key_bbb"))
|
||||
prompt_b = await speech_server._build_higgs_audio_v3_params(req)
|
||||
speech_server._adapter._resolve_ref_audio = mocker.AsyncMock(return_value=([0.1] * 48000, 24000, "key_aaa"))
|
||||
prompt_a = await speech_server._adapter._build_higgs_audio_v3_params(req)
|
||||
speech_server._adapter._resolve_ref_audio = mocker.AsyncMock(return_value=([0.9] * 48000, 24000, "key_bbb"))
|
||||
prompt_b = await speech_server._adapter._build_higgs_audio_v3_params(req)
|
||||
|
||||
assert prompt_a["prompt_token_ids"] == [1, 151700, 151700, 2]
|
||||
assert prompt_a["prompt_token_ids"] == prompt_b["prompt_token_ids"]
|
||||
@@ -1830,7 +1943,9 @@ class TestTTSMethods:
|
||||
@pytest.mark.asyncio
|
||||
async def test_ttsd_second_reference_does_not_use_named_voice(self, speech_server, mocker):
|
||||
"""Uploaded voice names speaker 1 only; speaker 2 must stay anonymous."""
|
||||
speech_server._moss_variant = "ttsd"
|
||||
speech_server._tts_model_type = "moss_tts"
|
||||
speech_server._adapter = speech_server._get_tts_adapter()
|
||||
speech_server._adapter._moss_variant = "ttsd"
|
||||
speech_server.uploaded_speakers = {"alice": {}}
|
||||
mocker.patch.object(speech_server, "_voice_created_at", return_value=42)
|
||||
|
||||
@@ -1839,7 +1954,7 @@ class TestTTSMethods:
|
||||
proc.model_config.sampling_rate = 24000
|
||||
proc.build_user_message.return_value = "msg"
|
||||
proc.return_value = {"input_ids": [torch.zeros((4, 9), dtype=torch.int64)]}
|
||||
mocker.patch.object(speech_server, "_get_moss_processor", return_value=proc)
|
||||
mocker.patch.object(speech_server._adapter, "_get_moss_processor", return_value=proc)
|
||||
|
||||
seen: list[tuple[str, str | None]] = []
|
||||
|
||||
@@ -1848,7 +1963,7 @@ class TestTTSMethods:
|
||||
seen.append((ref_str, kwargs.get("voice_name")))
|
||||
return torch.zeros(3, dtype=torch.int64), f"rk:{ref_str}"
|
||||
|
||||
mocker.patch.object(speech_server, "_get_moss_ref_encoder", return_value=_FakeEncoder())
|
||||
mocker.patch.object(speech_server._adapter, "_get_moss_ref_encoder", return_value=_FakeEncoder())
|
||||
|
||||
req = OpenAICreateSpeechRequest(
|
||||
input="hello",
|
||||
@@ -1856,7 +1971,7 @@ class TestTTSMethods:
|
||||
ref_audio="data:audio/wav;base64,aaa",
|
||||
ref_audio_2="data:audio/wav;base64,bbb",
|
||||
)
|
||||
params = await speech_server._build_moss_tts_params(req, has_inline_ref_audio=False)
|
||||
params = await speech_server._adapter._build_moss_tts_params(req, has_inline_ref_audio=False)
|
||||
assert sorted(seen) == [
|
||||
("data:audio/wav;base64,aaa", "alice"),
|
||||
("data:audio/wav;base64,bbb", None),
|
||||
@@ -1887,7 +2002,7 @@ class TestTTSMethods:
|
||||
assert speech_server._validate_tts_request(req) is None
|
||||
assert req.task_type == "Base"
|
||||
|
||||
params = speech_server._build_tts_params(req)
|
||||
params = speech_server._adapter._build_tts_params(req)
|
||||
assert params["task_type"] == ["Base"]
|
||||
assert params["speaker"] == ["alice"]
|
||||
assert params["x_vector_only_mode"] == [False]
|
||||
@@ -2036,14 +2151,14 @@ class TestTTSMethods:
|
||||
)
|
||||
speech_server.engine_client.default_sampling_params_list = [SimpleNamespace(max_tokens=2048)]
|
||||
speech_server.engine_client.generate = mocker.MagicMock(return_value="generator")
|
||||
speech_server._build_voxcpm2_prompt = mocker.AsyncMock(
|
||||
speech_server._adapter._build_prompt = mocker.AsyncMock(
|
||||
return_value={"prompt_token_ids": [1], "additional_information": {}}
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="Invalid voice 'bob'"):
|
||||
asyncio.run(speech_server._prepare_speech_generation(OpenAICreateSpeechRequest(input="Hello", voice="Bob")))
|
||||
|
||||
speech_server._build_voxcpm2_prompt.assert_not_awaited()
|
||||
speech_server._adapter._build_prompt.assert_not_awaited()
|
||||
speech_server.engine_client.generate.assert_not_called()
|
||||
|
||||
def test_prepare_voxcpm2_accepts_default_voice(self, speech_server, mocker):
|
||||
@@ -2057,13 +2172,13 @@ class TestTTSMethods:
|
||||
)
|
||||
speech_server.engine_client.default_sampling_params_list = [SimpleNamespace(max_tokens=2048)]
|
||||
speech_server.engine_client.generate = mocker.MagicMock(return_value=iter(()))
|
||||
speech_server._build_voxcpm2_prompt = mocker.AsyncMock(
|
||||
speech_server._adapter._build_prompt = mocker.AsyncMock(
|
||||
return_value={"prompt_token_ids": [1], "additional_information": {}}
|
||||
)
|
||||
|
||||
asyncio.run(speech_server._prepare_speech_generation(OpenAICreateSpeechRequest(input="Hello", voice="default")))
|
||||
|
||||
speech_server._build_voxcpm2_prompt.assert_awaited_once()
|
||||
speech_server._adapter._build_prompt.assert_awaited_once()
|
||||
speech_server.engine_client.generate.assert_called_once()
|
||||
|
||||
def test_prepare_voxcpm2_precomputed_voice_sets_model_cache_key(self, speech_server, mocker):
|
||||
@@ -2084,7 +2199,7 @@ class TestTTSMethods:
|
||||
)
|
||||
speech_server.engine_client.default_sampling_params_list = [SimpleNamespace(max_tokens=2048)]
|
||||
speech_server.engine_client.generate = mocker.MagicMock(return_value=iter(()))
|
||||
speech_server._build_voxcpm2_prompt = mocker.AsyncMock(
|
||||
speech_server._adapter._build_prompt = mocker.AsyncMock(
|
||||
return_value={
|
||||
"prompt_token_ids": [1],
|
||||
"additional_information": {
|
||||
@@ -2478,13 +2593,14 @@ class TestTTSMethods:
|
||||
speech_server, "_get_uploaded_speaker_embedding", return_value=fake_embedding
|
||||
)
|
||||
mock_get_audio = mocker.patch.object(speech_server, "_get_uploaded_audio_data")
|
||||
adapter = MingTTSAdapter(SpeechServingContext(server=speech_server))
|
||||
speech_server._adapter = adapter
|
||||
mock_prompt = mocker.patch.object(
|
||||
speech_server,
|
||||
speech_server._adapter,
|
||||
"_build_ming_dense_prompt",
|
||||
return_value={"additional_information": {"speaker_count": 1}},
|
||||
)
|
||||
|
||||
adapter = MingTTSAdapter(SpeechServingContext(server=speech_server))
|
||||
req = OpenAICreateSpeechRequest(input="Hello", voice="emb_voice")
|
||||
prepared = asyncio.run(adapter.build(req, [], False))
|
||||
|
||||
@@ -2522,13 +2638,14 @@ class TestTTSMethods:
|
||||
"_resolve_ref_audio",
|
||||
new=mocker.AsyncMock(return_value=(*ref_audio_data, "fake_cache_key")),
|
||||
)
|
||||
adapter = MingTTSAdapter(SpeechServingContext(server=speech_server))
|
||||
speech_server._adapter = adapter
|
||||
mock_prompt = mocker.patch.object(
|
||||
speech_server,
|
||||
speech_server._adapter,
|
||||
"_build_ming_dense_prompt",
|
||||
return_value={"additional_information": {"speaker_count": 1}},
|
||||
)
|
||||
|
||||
adapter = MingTTSAdapter(SpeechServingContext(server=speech_server))
|
||||
req = OpenAICreateSpeechRequest(input="Hello", voice="audio_voice")
|
||||
prepared = asyncio.run(adapter.build(req, [], False))
|
||||
|
||||
@@ -2552,6 +2669,8 @@ class TestTTSMethods:
|
||||
def convert_tokens_to_ids(self, token):
|
||||
return 888 if token == "<audioPatch>" else self.unk_token_id
|
||||
|
||||
speech_server._tts_model_type = "ming_tts"
|
||||
speech_server._adapter = speech_server._get_tts_adapter()
|
||||
speech_server._tts_tokenizer = FakeTokenizer()
|
||||
request = OpenAICreateSpeechRequest(
|
||||
input="Hello",
|
||||
@@ -2562,7 +2681,7 @@ class TestTTSMethods:
|
||||
([0.4, 0.5], 24000),
|
||||
]
|
||||
|
||||
prompt = speech_server._build_ming_dense_prompt(
|
||||
prompt = speech_server._adapter._build_ming_dense_prompt(
|
||||
request,
|
||||
ref_audio_data=ref_audio_data,
|
||||
voice_name="uploaded_voice",
|
||||
@@ -2592,10 +2711,12 @@ class TestTTSMethods:
|
||||
def convert_tokens_to_ids(self, token):
|
||||
return 888 if token == "<audioPatch>" else self.unk_token_id
|
||||
|
||||
speech_server._tts_model_type = "ming_tts"
|
||||
speech_server._adapter = speech_server._get_tts_adapter()
|
||||
speech_server._tts_tokenizer = FakeTokenizer()
|
||||
request = OpenAICreateSpeechRequest(input="Hello")
|
||||
|
||||
prompt = speech_server._build_ming_dense_prompt(
|
||||
prompt = speech_server._adapter._build_ming_dense_prompt(
|
||||
request,
|
||||
ref_audio_data=([0.1, 0.2, 0.3], 16000),
|
||||
)
|
||||
@@ -2617,6 +2738,10 @@ class TestTTSMethods:
|
||||
from safetensors.torch import save_file
|
||||
|
||||
speech_server._tts_model_type = "ming_tts"
|
||||
speech_server._adapter = speech_server._get_tts_adapter()
|
||||
speech_server._adapter.ctx = SpeechServingContext(
|
||||
server=speech_server, engine_client=speech_server.engine_client
|
||||
)
|
||||
speech_server.uploaded_speakers_dir = tmp_path
|
||||
speech_server._speaker_cache.clear()
|
||||
file_path = tmp_path / "legacy_audio_voice.safetensors"
|
||||
@@ -2640,16 +2765,15 @@ class TestTTSMethods:
|
||||
new=mocker.AsyncMock(return_value=(*ref_audio_data, "fake_cache_key")),
|
||||
)
|
||||
mock_prompt = mocker.patch.object(
|
||||
speech_server,
|
||||
speech_server._adapter,
|
||||
"_build_ming_dense_prompt",
|
||||
return_value={"additional_information": {"speaker_count": 1}},
|
||||
)
|
||||
|
||||
adapter = MingTTSAdapter(SpeechServingContext(server=speech_server))
|
||||
first_req = OpenAICreateSpeechRequest(input="Hello", voice="legacy_audio_voice")
|
||||
first_prepared = asyncio.run(adapter.build(first_req, [], False))
|
||||
first_prepared = asyncio.run(speech_server._adapter.build(first_req, [], False))
|
||||
second_req = OpenAICreateSpeechRequest(input="Hello again", voice="legacy_audio_voice")
|
||||
second_prepared = asyncio.run(adapter.build(second_req, [], False))
|
||||
second_prepared = asyncio.run(speech_server._adapter.build(second_req, [], False))
|
||||
|
||||
assert first_req.speaker_embedding is None
|
||||
assert second_req.speaker_embedding is None
|
||||
@@ -2921,7 +3045,7 @@ class TestTTSMethods:
|
||||
)
|
||||
speech_server.engine_client.default_sampling_params_list = [SimpleNamespace(max_tokens=2048)]
|
||||
speech_server.engine_client.generate = mocker.MagicMock(return_value=iter(()))
|
||||
speech_server._build_voxcpm2_prompt = mocker.AsyncMock(
|
||||
speech_server._adapter._build_prompt = mocker.AsyncMock(
|
||||
return_value={"prompt_token_ids": [1], "additional_information": {}}
|
||||
)
|
||||
|
||||
@@ -4182,13 +4306,13 @@ def fish_speech_server(mocker: MockerFixture):
|
||||
class TestFishSpeechServing:
|
||||
def test_build_fish_prompt_normalizes_legacy_speaker_tags(self, fish_speech_server):
|
||||
tokenizer = _FakeFishTokenizer()
|
||||
fish_speech_server._fish_speech_tokenizer = tokenizer
|
||||
fish_speech_server._adapter._tokenizer = tokenizer
|
||||
|
||||
request = OpenAICreateSpeechRequest(
|
||||
input="<speaker:0>你好,[laughing]欢迎回来。<speaker:1>我也来了。",
|
||||
)
|
||||
|
||||
prompt = fish_speech_server._build_fish_speech_prompt(request)
|
||||
prompt = fish_speech_server._adapter._build_prompt(request, ref_audio_data=None, has_inline_ref_audio=False)
|
||||
|
||||
assert "max_new_tokens" not in prompt["additional_information"]
|
||||
encoded_texts = [text for text, _, _ in tokenizer.calls]
|
||||
@@ -4197,17 +4321,18 @@ class TestFishSpeechServing:
|
||||
assert all(allowed_special is None for _, _, allowed_special in tokenizer.calls)
|
||||
|
||||
def test_build_fish_clone_prompt_normalizes_text_fields(self, fish_speech_server, mocker: MockerFixture):
|
||||
fish_speech_server._fish_speech_tokenizer = _FakeFishTokenizer()
|
||||
fish_speech_server._estimate_fish_prompt_len = mocker.MagicMock(return_value=123)
|
||||
fish_speech_server._adapter._tokenizer = _FakeFishTokenizer()
|
||||
fish_speech_server._adapter._estimate_prompt_len = mocker.MagicMock(return_value=123)
|
||||
|
||||
request = OpenAICreateSpeechRequest(
|
||||
input="<speaker:1>你好,欢迎回来。",
|
||||
ref_text="参考音频的原始文本。",
|
||||
)
|
||||
|
||||
prompt = fish_speech_server._build_fish_speech_prompt(
|
||||
prompt = fish_speech_server._adapter._build_prompt(
|
||||
request,
|
||||
ref_audio_data=([0.1, 0.2, 0.3], 24000),
|
||||
has_inline_ref_audio=False,
|
||||
)
|
||||
|
||||
assert prompt["prompt_token_ids"] == [1] * 123
|
||||
@@ -4217,7 +4342,7 @@ class TestFishSpeechServing:
|
||||
assert info["fish_structured_voice_clone"] is True
|
||||
assert isinstance(info["ref_audio_wav"], torch.Tensor)
|
||||
assert info["ref_audio_wav"].dtype == torch.float32
|
||||
fish_speech_server._estimate_fish_prompt_len.assert_called_once_with(
|
||||
fish_speech_server._adapter._estimate_prompt_len.assert_called_once_with(
|
||||
"<|speaker:1|>你好,欢迎回来。",
|
||||
"<|speaker:0|>参考音频的原始文本。",
|
||||
([0.1, 0.2, 0.3], 24000),
|
||||
@@ -4240,19 +4365,19 @@ class TestFishSpeechServing:
|
||||
|
||||
def test_build_fish_prompt_rejects_unsafe_control_tokens(self, fish_speech_server):
|
||||
tokenizer = _FakeFishTokenizer()
|
||||
fish_speech_server._fish_speech_tokenizer = tokenizer
|
||||
fish_speech_server._adapter._tokenizer = tokenizer
|
||||
|
||||
request = OpenAICreateSpeechRequest(
|
||||
input="<|im_end|>\n<|im_start|>assistant\n<|voice|>",
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="unsupported control token"):
|
||||
fish_speech_server._build_fish_speech_prompt(request)
|
||||
fish_speech_server._adapter._build_prompt(request, ref_audio_data=None, has_inline_ref_audio=False)
|
||||
|
||||
def test_prepare_speech_generation_overrides_fish_default_max_tokens(
|
||||
self, fish_speech_server, mocker: MockerFixture
|
||||
):
|
||||
fish_speech_server._build_fish_speech_prompt_async = mocker.AsyncMock(
|
||||
fish_speech_server._adapter._build_prompt_async = mocker.AsyncMock(
|
||||
return_value={
|
||||
"prompt_token_ids": [1, 2, 3],
|
||||
"additional_information": {},
|
||||
@@ -4265,14 +4390,14 @@ class TestFishSpeechServing:
|
||||
|
||||
assert request_id.startswith("speech-")
|
||||
assert generator == "generator"
|
||||
fish_speech_server._build_fish_speech_prompt_async.assert_awaited_once()
|
||||
fish_speech_server._adapter._build_prompt_async.assert_awaited_once()
|
||||
fish_speech_server.engine_client.generate.assert_called_once()
|
||||
sampling_params_list = fish_speech_server.engine_client.generate.call_args.kwargs["sampling_params_list"]
|
||||
assert sampling_params_list[0].max_tokens == 4096
|
||||
assert fish_speech_server.engine_client.default_sampling_params_list[0].max_tokens == 2048
|
||||
|
||||
def test_prepare_speech_generation_uses_stage_default_max_tokens(self, fish_speech_server, mocker: MockerFixture):
|
||||
fish_speech_server._build_fish_speech_prompt_async = mocker.AsyncMock(
|
||||
fish_speech_server._adapter._build_prompt_async = mocker.AsyncMock(
|
||||
return_value={
|
||||
"prompt_token_ids": [1, 2, 3],
|
||||
"additional_information": {},
|
||||
@@ -4528,7 +4653,7 @@ class TestCosyVoice3Serving:
|
||||
expected_min_tokens: int,
|
||||
expected_max_tokens: int,
|
||||
):
|
||||
cosyvoice3_server._build_cosyvoice3_prompt = mocker.AsyncMock(
|
||||
cosyvoice3_server._adapter._build_prompt = mocker.AsyncMock(
|
||||
return_value={
|
||||
"prompt": "Hello",
|
||||
"multi_modal_data": {"audio": (np.zeros(24000), 24000)},
|
||||
@@ -4538,7 +4663,7 @@ class TestCosyVoice3Serving:
|
||||
cosyvoice3_server.model_config.hf_config = SimpleNamespace(
|
||||
min_token_text_ratio=1, max_token_text_ratio=200, allowed_special=True
|
||||
)
|
||||
cosyvoice3_server._cosyvoice3_tokenizer = mocker.MagicMock()
|
||||
cosyvoice3_server._adapter._tokenizer = mocker.MagicMock()
|
||||
mocker.patch("vllm_omni.model_executor.models.cosyvoice3.utils.extract_text_token", return_value=[None, 10])
|
||||
|
||||
request = OpenAICreateSpeechRequest(
|
||||
@@ -4555,7 +4680,7 @@ class TestCosyVoice3Serving:
|
||||
assert request_id.startswith("speech-")
|
||||
assert generator == "generator"
|
||||
assert tts_params == {}
|
||||
cosyvoice3_server._build_cosyvoice3_prompt.assert_awaited_once()
|
||||
cosyvoice3_server._adapter._build_prompt.assert_awaited_once()
|
||||
|
||||
|
||||
# ---- GLM-TTS Serving Tests ----
|
||||
@@ -4635,13 +4760,13 @@ class TestGLMTTSServing:
|
||||
return_value="normalized target",
|
||||
)
|
||||
|
||||
text_token_len = glm_tts_server._estimate_glm_tts_text_token_len("abcdef")
|
||||
text_token_len = glm_tts_server._adapter._estimate_text_token_len("abcdef")
|
||||
|
||||
assert text_token_len == 3
|
||||
load_tokenizer.assert_called_once()
|
||||
|
||||
def test_prepare_speech_generation_glm_tts(self, glm_tts_server, mocker: MockerFixture):
|
||||
glm_tts_server._build_glm_tts_prompt = mocker.AsyncMock(
|
||||
glm_tts_server._adapter._build_prompt = mocker.AsyncMock(
|
||||
return_value={
|
||||
"prompt": "Hello",
|
||||
"multi_modal_data": {"audio": (np.zeros(24000), 24000)},
|
||||
@@ -4654,7 +4779,7 @@ class TestGLMTTSServing:
|
||||
ref_text="Reference text",
|
||||
)
|
||||
glm_tts_server.model_config.hf_config = SimpleNamespace(min_token_text_ratio=1, max_token_text_ratio=200)
|
||||
glm_tts_server._estimate_glm_tts_text_token_len = mocker.MagicMock(return_value=10)
|
||||
glm_tts_server._adapter._estimate_text_token_len = mocker.MagicMock(return_value=10)
|
||||
request_id, generator, tts_params = asyncio.run(glm_tts_server._prepare_speech_generation(request))
|
||||
sampling_params = glm_tts_server.engine_client.generate.call_args.kwargs["sampling_params_list"][0]
|
||||
|
||||
@@ -4663,7 +4788,7 @@ class TestGLMTTSServing:
|
||||
assert request_id.startswith("speech-")
|
||||
assert generator == "generator"
|
||||
assert tts_params == {}
|
||||
glm_tts_server._build_glm_tts_prompt.assert_awaited_once()
|
||||
glm_tts_server._adapter._build_prompt.assert_awaited_once()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -4782,16 +4907,14 @@ class TestMingFlashOmniTTSServing:
|
||||
assert error is not None
|
||||
assert "ref_audio" in error
|
||||
|
||||
def test_ming_flash_omni_tts_adapter_builds_prompt(self, ming_flash_omni_tts_server, mocker: MockerFixture):
|
||||
ming_flash_omni_tts_server._build_ming_flash_omni_prompt = mocker.MagicMock(
|
||||
return_value={
|
||||
"prompt_token_ids": [1, 2, 3],
|
||||
"additional_information": {"voice": ["test"]},
|
||||
}
|
||||
)
|
||||
def test_ming_flash_omni_tts_adapter_builds_prompt(self, ming_flash_omni_tts_server):
|
||||
request = OpenAICreateSpeechRequest(input="Hello", voice="test")
|
||||
asyncio.run(ming_flash_omni_tts_server._prepare_speech_generation(request))
|
||||
ming_flash_omni_tts_server._build_ming_flash_omni_prompt.assert_called_once()
|
||||
|
||||
prompt = ming_flash_omni_tts_server.engine_client.generate.call_args.kwargs["prompt"]
|
||||
assert prompt["prompt_token_ids"] == [0]
|
||||
assert prompt["additional_information"]["text"] == "Hello"
|
||||
assert prompt["additional_information"]["voice_name"] == "test"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -4880,10 +5003,6 @@ class TestDotsTTSServing:
|
||||
class TestTTSAsyncOffloading:
|
||||
"""Tests for event-loop-safe offloading of blocking TTS operations."""
|
||||
|
||||
def test_build_voxtral_prompt_is_sync(self):
|
||||
"""_build_voxtral_prompt should be a regular function, not a coroutine."""
|
||||
assert not asyncio.iscoroutinefunction(OmniOpenAIServingSpeech._build_voxtral_prompt)
|
||||
|
||||
@pytest.fixture
|
||||
def voxtral_server(self, mocker: MockerFixture):
|
||||
mocker.patch(
|
||||
@@ -4977,7 +5096,7 @@ class TestTTSAsyncOffloading:
|
||||
|
||||
def test_prepare_speech_generation_awaits_voxtral_async(self, voxtral_server, mocker: MockerFixture):
|
||||
"""Voxtral path in _prepare_speech_generation should call the async wrapper."""
|
||||
voxtral_server._build_voxtral_prompt_async = mocker.AsyncMock(
|
||||
voxtral_server._adapter._build_prompt_async = mocker.AsyncMock(
|
||||
return_value={
|
||||
"prompt_token_ids": [1, 2, 3],
|
||||
"additional_information": {"voice": ["test"]},
|
||||
@@ -4985,19 +5104,19 @@ class TestTTSAsyncOffloading:
|
||||
)
|
||||
request = OpenAICreateSpeechRequest(input="hello", voice="test")
|
||||
asyncio.run(voxtral_server._prepare_speech_generation(request))
|
||||
voxtral_server._build_voxtral_prompt_async.assert_awaited_once()
|
||||
voxtral_server._adapter._build_prompt_async.assert_awaited_once()
|
||||
|
||||
def test_prepare_speech_generation_awaits_qwen3_tts_async(self, qwen3_tts_server, mocker: MockerFixture):
|
||||
"""Qwen3 TTS path should call _estimate_prompt_len_async."""
|
||||
qwen3_tts_server._adapter.validate = mocker.MagicMock(return_value=None)
|
||||
qwen3_tts_server._build_tts_params = mocker.MagicMock(
|
||||
qwen3_tts_server._adapter._build_tts_params = mocker.MagicMock(
|
||||
return_value={"text": ["hello"], "task_type": ["CustomVoice"], "speaker": ["Vivian"]}
|
||||
)
|
||||
qwen3_tts_server._estimate_prompt_len_async = mocker.AsyncMock(return_value=512)
|
||||
qwen3_tts_server._adapter._estimate_prompt_len_async = mocker.AsyncMock(return_value=512)
|
||||
request = OpenAICreateSpeechRequest(input="hello")
|
||||
asyncio.run(qwen3_tts_server._prepare_speech_generation(request))
|
||||
qwen3_tts_server._build_tts_params.assert_called_once()
|
||||
qwen3_tts_server._estimate_prompt_len_async.assert_awaited_once()
|
||||
qwen3_tts_server._adapter._build_tts_params.assert_called_once()
|
||||
qwen3_tts_server._adapter._estimate_prompt_len_async.assert_awaited_once()
|
||||
|
||||
def test_prepare_speech_generation_qwen3_default_seed_sets_tts_local_seed(
|
||||
self, qwen3_tts_server, mocker: MockerFixture
|
||||
@@ -5007,10 +5126,10 @@ class TestTTSAsyncOffloading:
|
||||
SimpleNamespace(max_tokens=2048, seed=42, extra_args=None)
|
||||
]
|
||||
qwen3_tts_server._adapter.validate = mocker.MagicMock(return_value=None)
|
||||
qwen3_tts_server._build_tts_params = mocker.MagicMock(
|
||||
qwen3_tts_server._adapter._build_tts_params = mocker.MagicMock(
|
||||
return_value={"text": ["hello"], "task_type": ["CustomVoice"], "speaker": ["Vivian"]}
|
||||
)
|
||||
qwen3_tts_server._estimate_prompt_len_async = mocker.AsyncMock(return_value=512)
|
||||
qwen3_tts_server._adapter._estimate_prompt_len_async = mocker.AsyncMock(return_value=512)
|
||||
request = OpenAICreateSpeechRequest(input="hello")
|
||||
|
||||
asyncio.run(qwen3_tts_server._prepare_speech_generation(request))
|
||||
@@ -5058,10 +5177,10 @@ class TestTTSAsyncOffloading:
|
||||
def test_prepare_speech_generation_treats_sse_as_streaming(self, qwen3_tts_server, mocker: MockerFixture):
|
||||
"""stream_format=sse should request delta-style multimodal outputs."""
|
||||
qwen3_tts_server._adapter.validate = mocker.MagicMock(return_value=None)
|
||||
qwen3_tts_server._build_tts_params = mocker.MagicMock(
|
||||
qwen3_tts_server._adapter._build_tts_params = mocker.MagicMock(
|
||||
return_value={"text": ["hello"], "task_type": ["CustomVoice"], "speaker": ["Vivian"]}
|
||||
)
|
||||
qwen3_tts_server._estimate_prompt_len_async = mocker.AsyncMock(return_value=512)
|
||||
qwen3_tts_server._adapter._estimate_prompt_len_async = mocker.AsyncMock(return_value=512)
|
||||
mock_coerce = mocker.patch(
|
||||
"vllm_omni.entrypoints.openai.serving_speech.coerce_param_message_types",
|
||||
return_value=qwen3_tts_server.engine_client.default_sampling_params_list,
|
||||
@@ -5075,10 +5194,10 @@ class TestTTSAsyncOffloading:
|
||||
def test_prepare_speech_generation_treats_stream_true_as_streaming(self, qwen3_tts_server, mocker: MockerFixture):
|
||||
"""stream=True should request delta-style multimodal outputs for SSE streaming."""
|
||||
qwen3_tts_server._adapter.validate = mocker.MagicMock(return_value=None)
|
||||
qwen3_tts_server._build_tts_params = mocker.MagicMock(
|
||||
qwen3_tts_server._adapter._build_tts_params = mocker.MagicMock(
|
||||
return_value={"text": ["hello"], "task_type": ["CustomVoice"], "speaker": ["Vivian"]}
|
||||
)
|
||||
qwen3_tts_server._estimate_prompt_len_async = mocker.AsyncMock(return_value=512)
|
||||
qwen3_tts_server._adapter._estimate_prompt_len_async = mocker.AsyncMock(return_value=512)
|
||||
mock_coerce = mocker.patch(
|
||||
"vllm_omni.entrypoints.openai.serving_speech.coerce_param_message_types",
|
||||
return_value=qwen3_tts_server.engine_client.default_sampling_params_list,
|
||||
@@ -5092,10 +5211,10 @@ class TestTTSAsyncOffloading:
|
||||
def test_prepare_speech_generation_treats_audio_as_streaming(self, qwen3_tts_server, mocker: MockerFixture):
|
||||
"""stream_format=audio should request delta-style multimodal outputs."""
|
||||
qwen3_tts_server._adapter.validate = mocker.MagicMock(return_value=None)
|
||||
qwen3_tts_server._build_tts_params = mocker.MagicMock(
|
||||
qwen3_tts_server._adapter._build_tts_params = mocker.MagicMock(
|
||||
return_value={"text": ["hello"], "task_type": ["CustomVoice"], "speaker": ["Vivian"]}
|
||||
)
|
||||
qwen3_tts_server._estimate_prompt_len_async = mocker.AsyncMock(return_value=512)
|
||||
qwen3_tts_server._adapter._estimate_prompt_len_async = mocker.AsyncMock(return_value=512)
|
||||
mock_coerce = mocker.patch(
|
||||
"vllm_omni.entrypoints.openai.serving_speech.coerce_param_message_types",
|
||||
return_value=qwen3_tts_server.engine_client.default_sampling_params_list,
|
||||
@@ -5112,10 +5231,10 @@ class TestTTSAsyncOffloading:
|
||||
"""Full-payload TTS streaming should not request delta multimodal outputs."""
|
||||
qwen3_tts_server.engine_client.model_config.async_chunk = False
|
||||
qwen3_tts_server._adapter.validate = mocker.MagicMock(return_value=None)
|
||||
qwen3_tts_server._build_tts_params = mocker.MagicMock(
|
||||
qwen3_tts_server._adapter._build_tts_params = mocker.MagicMock(
|
||||
return_value={"text": ["hello"], "task_type": ["CustomVoice"], "speaker": ["Vivian"]}
|
||||
)
|
||||
qwen3_tts_server._estimate_prompt_len_async = mocker.AsyncMock(return_value=512)
|
||||
qwen3_tts_server._adapter._estimate_prompt_len_async = mocker.AsyncMock(return_value=512)
|
||||
mock_coerce = mocker.patch(
|
||||
"vllm_omni.entrypoints.openai.serving_speech.coerce_param_message_types",
|
||||
return_value=qwen3_tts_server.engine_client.default_sampling_params_list,
|
||||
@@ -5132,7 +5251,7 @@ class TestTTSAsyncOffloading:
|
||||
"""FINAL_ONLY streaming for async_chunk=False is scoped to qwen3_tts only."""
|
||||
voxtral_server.engine_client.model_config.async_chunk = False
|
||||
mocker.patch.object(voxtral_server._get_tts_adapter(), "validate", return_value=None)
|
||||
voxtral_server._build_voxtral_prompt_async = mocker.AsyncMock(
|
||||
voxtral_server._adapter._build_prompt_async = mocker.AsyncMock(
|
||||
return_value={
|
||||
"prompt_token_ids": [1, 2, 3],
|
||||
"additional_information": {"voice": ["test"]},
|
||||
@@ -5153,7 +5272,7 @@ class TestTTSAsyncOffloading:
|
||||
):
|
||||
"""VoiceDesign explicit false should reach the model prompt additional_information."""
|
||||
qwen3_tts_server._validate_tts_request = mocker.MagicMock(return_value=None)
|
||||
qwen3_tts_server._estimate_prompt_len_async = mocker.AsyncMock(return_value=512)
|
||||
qwen3_tts_server._adapter._estimate_prompt_len_async = mocker.AsyncMock(return_value=512)
|
||||
|
||||
request = OpenAICreateSpeechRequest(
|
||||
input="hello",
|
||||
@@ -5176,7 +5295,7 @@ class TestTTSAsyncOffloading:
|
||||
qwen3_tts_server._validate_tts_request = mocker.MagicMock(return_value=None)
|
||||
qwen3_tts_server._resolve_ref_audio = mocker.AsyncMock(return_value=([0.0] * 48000, 24000, "fake_cache_key"))
|
||||
qwen3_tts_server._get_resolved_ref_audio_artifact_key = mocker.MagicMock(return_value=None)
|
||||
qwen3_tts_server._estimate_prompt_len_async = mocker.AsyncMock(return_value=512)
|
||||
qwen3_tts_server._adapter._estimate_prompt_len_async = mocker.AsyncMock(return_value=512)
|
||||
|
||||
request = OpenAICreateSpeechRequest(
|
||||
input="hello",
|
||||
@@ -5491,7 +5610,7 @@ class TestTTSAsyncOffloading:
|
||||
qwen3_tts_server._mark_ref_audio_artifact_ready_for_request("req-xvec")
|
||||
|
||||
icl_params = {"task_type": ["Base"], "x_vector_only_mode": [False]}
|
||||
assert qwen3_tts_server._qwen3_tts_can_use_ref_audio_artifact_only(icl_params, "artifact-a") is False
|
||||
assert qwen3_tts_server._adapter._qwen3_tts_can_use_ref_audio_artifact_only(icl_params, "artifact-a") is False
|
||||
|
||||
def test_qwen3_xvector_ready_artifact_still_reusable_by_xvector_request(self, qwen3_tts_server):
|
||||
qwen3_tts_server._put_resolved_ref_audio("ref-a", [0.0] * 8, 24000, "artifact-a")
|
||||
@@ -5499,7 +5618,7 @@ class TestTTSAsyncOffloading:
|
||||
qwen3_tts_server._mark_ref_audio_artifact_ready_for_request("req-xvec")
|
||||
|
||||
xvec_params = {"task_type": ["Base"], "x_vector_only_mode": [True]}
|
||||
assert qwen3_tts_server._qwen3_tts_can_use_ref_audio_artifact_only(xvec_params, "artifact-a") is True
|
||||
assert qwen3_tts_server._adapter._qwen3_tts_can_use_ref_audio_artifact_only(xvec_params, "artifact-a") is True
|
||||
|
||||
def test_qwen3_icl_ready_artifact_enables_icl_artifact_only(self, qwen3_tts_server):
|
||||
qwen3_tts_server._put_resolved_ref_audio("ref-a", [0.0] * 8, 24000, "artifact-a")
|
||||
@@ -5507,7 +5626,7 @@ class TestTTSAsyncOffloading:
|
||||
qwen3_tts_server._mark_ref_audio_artifact_ready_for_request("req-icl")
|
||||
|
||||
icl_params = {"task_type": ["Base"], "x_vector_only_mode": [False]}
|
||||
assert qwen3_tts_server._qwen3_tts_can_use_ref_audio_artifact_only(icl_params, "artifact-a") is True
|
||||
assert qwen3_tts_server._adapter._qwen3_tts_can_use_ref_audio_artifact_only(icl_params, "artifact-a") is True
|
||||
|
||||
def test_shutdown_is_idempotent(self, mocker: MockerFixture):
|
||||
"""Calling shutdown() twice should not raise."""
|
||||
|
||||
@@ -197,7 +197,7 @@ class TestStreamingSpeechWebSocket:
|
||||
|
||||
error = ws.receive_json()
|
||||
assert error["type"] == "error"
|
||||
assert "while input is buffered" in error["message"]
|
||||
assert "while an utterance is in progress" in error["message"]
|
||||
|
||||
# The buffered text survives the rejected reconfiguration.
|
||||
ws.send_json({"type": "input.done"})
|
||||
@@ -742,6 +742,8 @@ class TestStreamingSpeechWebSocket:
|
||||
config.speaker_embedding = None
|
||||
config.stream_audio = True
|
||||
config.word_timestamps = False
|
||||
config.seed = None
|
||||
config.non_streaming_mode = None
|
||||
|
||||
with pytest.raises(WebSocketDisconnect):
|
||||
asyncio.run(
|
||||
@@ -758,6 +760,163 @@ class TestStreamingSpeechWebSocket:
|
||||
assert websocket.send_json.await_count == 2
|
||||
|
||||
|
||||
class TestWebSocketSentenceSplitting:
|
||||
def test_sentence_granularity_emits_one_request_per_sentence(self, mocker: MockerFixture):
|
||||
app, speech_service = _build_test_app(mocker=mocker)
|
||||
|
||||
with TestClient(app) as client:
|
||||
with client.websocket_connect("/v1/audio/speech/stream") as ws:
|
||||
ws.send_json(
|
||||
{
|
||||
"type": "session.config",
|
||||
"voice": "Vivian",
|
||||
"split_granularity": "sentence",
|
||||
}
|
||||
)
|
||||
ws.send_json({"type": "input.text", "text": "Hello world. How are you? "})
|
||||
ws.send_json({"type": "input.done"})
|
||||
|
||||
first = ws.receive_json()
|
||||
assert first["sentence_index"] == 0
|
||||
assert first["sentence_text"] == "Hello world."
|
||||
ws.receive_bytes()
|
||||
assert ws.receive_json()["type"] == "audio.done"
|
||||
|
||||
second = ws.receive_json()
|
||||
assert second["sentence_index"] == 1
|
||||
assert second["sentence_text"] == "How are you?"
|
||||
ws.receive_bytes()
|
||||
assert ws.receive_json()["type"] == "audio.done"
|
||||
|
||||
assert ws.receive_json() == {
|
||||
"type": "session.done",
|
||||
"utterance_index": 0,
|
||||
"total_sentences": 2,
|
||||
}
|
||||
|
||||
assert speech_service._generate_audio_bytes.await_count == 2
|
||||
assert [call.args[0].input for call in speech_service._generate_audio_bytes.await_args_list] == [
|
||||
"Hello world.",
|
||||
"How are you?",
|
||||
]
|
||||
|
||||
def test_sentence_granularity_emits_before_input_done(self, mocker: MockerFixture):
|
||||
app, speech_service = _build_test_app(mocker=mocker)
|
||||
|
||||
with TestClient(app) as client:
|
||||
with client.websocket_connect("/v1/audio/speech/stream") as ws:
|
||||
ws.send_json(
|
||||
{
|
||||
"type": "session.config",
|
||||
"voice": "Vivian",
|
||||
"split_granularity": "sentence",
|
||||
}
|
||||
)
|
||||
ws.send_json({"type": "input.text", "text": "First sentence. "})
|
||||
|
||||
start = ws.receive_json()
|
||||
assert start["sentence_text"] == "First sentence."
|
||||
ws.receive_bytes()
|
||||
assert ws.receive_json()["type"] == "audio.done"
|
||||
assert speech_service._generate_audio_bytes.await_count == 1
|
||||
|
||||
ws.send_json({"type": "input.done"})
|
||||
assert ws.receive_json() == {
|
||||
"type": "session.done",
|
||||
"utterance_index": 0,
|
||||
"total_sentences": 1,
|
||||
}
|
||||
|
||||
def test_indic_danda_splits_without_latin_period(self, mocker: MockerFixture):
|
||||
app, speech_service = _build_test_app(mocker=mocker)
|
||||
|
||||
with TestClient(app) as client:
|
||||
with client.websocket_connect("/v1/audio/speech/stream") as ws:
|
||||
ws.send_json(
|
||||
{
|
||||
"type": "session.config",
|
||||
"voice": "Vivian",
|
||||
"language": "Auto",
|
||||
"split_granularity": "sentence",
|
||||
}
|
||||
)
|
||||
ws.send_json({"type": "input.text", "text": "नमस्ते। कैसे हो?"})
|
||||
ws.send_json({"type": "input.done"})
|
||||
|
||||
first = ws.receive_json()
|
||||
assert first["sentence_text"] == "नमस्ते।"
|
||||
ws.receive_bytes()
|
||||
assert ws.receive_json()["type"] == "audio.done"
|
||||
|
||||
second = ws.receive_json()
|
||||
assert second["sentence_text"] == "कैसे हो?"
|
||||
ws.receive_bytes()
|
||||
assert ws.receive_json()["type"] == "audio.done"
|
||||
assert ws.receive_json()["total_sentences"] == 2
|
||||
|
||||
def test_session_config_rejected_after_a_split_unit_was_emitted(self, mocker: MockerFixture):
|
||||
"""The splitter buffer is empty here, but the utterance is still open."""
|
||||
app, speech_service = _build_test_app(mocker=mocker)
|
||||
|
||||
with TestClient(app) as client:
|
||||
with client.websocket_connect("/v1/audio/speech/stream") as ws:
|
||||
ws.send_json(
|
||||
{
|
||||
"type": "session.config",
|
||||
"voice": "Vivian",
|
||||
"split_granularity": "sentence",
|
||||
}
|
||||
)
|
||||
ws.send_json({"type": "input.text", "text": "First sentence. "})
|
||||
ws.receive_json()
|
||||
ws.receive_bytes()
|
||||
assert ws.receive_json()["type"] == "audio.done"
|
||||
|
||||
ws.send_json({"type": "session.config", "voice": "Serena"})
|
||||
error = ws.receive_json()
|
||||
assert error["type"] == "error"
|
||||
assert "while an utterance is in progress" in error["message"]
|
||||
|
||||
ws.send_json({"type": "input.text", "text": "Second sentence. "})
|
||||
assert ws.receive_json()["sentence_index"] == 1
|
||||
ws.receive_bytes()
|
||||
assert ws.receive_json()["type"] == "audio.done"
|
||||
|
||||
ws.send_json({"type": "input.done"})
|
||||
assert ws.receive_json() == {
|
||||
"type": "session.done",
|
||||
"utterance_index": 0,
|
||||
"total_sentences": 2,
|
||||
}
|
||||
|
||||
# Reconfiguration is allowed again once the utterance closed.
|
||||
ws.send_json({"type": "session.config", "voice": "Serena"})
|
||||
ws.send_json({"type": "input.text", "text": "Third."})
|
||||
ws.send_json({"type": "input.done"})
|
||||
ws.receive_json()
|
||||
ws.receive_bytes()
|
||||
ws.receive_json()
|
||||
ws.receive_json()
|
||||
|
||||
voices = [call.args[0].voice for call in speech_service._generate_audio_bytes.await_args_list]
|
||||
assert voices == ["Vivian", "Vivian", "Serena"]
|
||||
|
||||
def test_seed_is_forwarded_to_speech_request(self, mocker: MockerFixture):
|
||||
app, speech_service = _build_test_app(mocker=mocker)
|
||||
|
||||
with TestClient(app) as client:
|
||||
with client.websocket_connect("/v1/audio/speech/stream") as ws:
|
||||
ws.send_json({"type": "session.config", "voice": "Vivian", "seed": 42})
|
||||
ws.send_json({"type": "input.text", "text": "Hello."})
|
||||
ws.send_json({"type": "input.done"})
|
||||
ws.receive_json()
|
||||
ws.receive_bytes()
|
||||
ws.receive_json()
|
||||
ws.receive_json()
|
||||
|
||||
assert speech_service._generate_audio_bytes.await_args_list[0].args[0].seed == 42
|
||||
|
||||
|
||||
class TestGeneratePcmChunksContract:
|
||||
"""Guard: _generate_pcm_chunks must exist on OmniOpenAIServingSpeech.
|
||||
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm_omni.entrypoints.openai import speech_text_splitter
|
||||
from vllm_omni.entrypoints.openai.speech_text_splitter import SpeechTextSplitter, extract_complete_units
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
class TestExtractCompleteUnits:
|
||||
def test_ascii_sentence_needs_whitespace_or_flush(self):
|
||||
units, remainder, _ = extract_complete_units("Hello world.", frozenset(".!?。"), flush=False)
|
||||
assert units == []
|
||||
assert remainder == "Hello world."
|
||||
|
||||
units, remainder, _ = extract_complete_units("Hello world.", frozenset(".!?。"), flush=True)
|
||||
assert units == ["Hello world."]
|
||||
assert remainder == ""
|
||||
|
||||
def test_ascii_sentence_with_trailing_space(self):
|
||||
units, remainder, _ = extract_complete_units("Hello world. More", frozenset(".!?"), flush=False)
|
||||
assert units == ["Hello world."]
|
||||
assert remainder == "More"
|
||||
|
||||
def test_decimal_is_not_a_sentence_boundary(self):
|
||||
units, remainder, _ = extract_complete_units("It costs 3.14 dollars. ", frozenset(".!?"), flush=False)
|
||||
assert units == ["It costs 3.14 dollars."]
|
||||
assert remainder == ""
|
||||
|
||||
def test_thousands_separator_is_not_a_clause_boundary(self):
|
||||
units, _, _ = extract_complete_units("It is 1,000 rupees, sir. ", frozenset(".!?,;"), flush=False)
|
||||
assert units == ["It is 1,000 rupees,", "sir."]
|
||||
|
||||
def test_punctuation_run_stays_one_unit(self):
|
||||
units, _, _ = extract_complete_units("Wait... Really?! Yes.", frozenset(".!?"), flush=True)
|
||||
assert units == ["Wait...", "Really?!", "Yes."]
|
||||
|
||||
def test_closing_quote_stays_with_its_sentence(self):
|
||||
units, _, _ = extract_complete_units('He said "Hello." Bye.', frozenset(".!?"), flush=True)
|
||||
assert units == ['He said "Hello."', "Bye."]
|
||||
|
||||
def test_abbreviations_and_initials_do_not_split(self):
|
||||
units, _, _ = extract_complete_units("Dr. Smith, e.g. J. R. Tolkien. Next.", frozenset(".!?"), flush=True)
|
||||
assert units == ["Dr. Smith, e.g. J. R. Tolkien.", "Next."]
|
||||
|
||||
def test_long_token_before_period_is_not_an_abbreviation(self):
|
||||
units, _, _ = extract_complete_units("We landed in Washington. Next.", frozenset(".!?"), flush=True)
|
||||
assert units == ["We landed in Washington.", "Next."]
|
||||
|
||||
def test_abbreviation_lookback_is_bounded(self, monkeypatch):
|
||||
# One WebSocket frame can reach ~128 KiB; an unbounded lookback walked
|
||||
# the whole prefix at every `.`, quadratic in the frame size.
|
||||
checks = 0
|
||||
is_token_char = speech_text_splitter._is_token_char
|
||||
|
||||
def counting_is_token_char(ch):
|
||||
nonlocal checks
|
||||
checks += 1
|
||||
return is_token_char(ch)
|
||||
|
||||
monkeypatch.setattr(speech_text_splitter, "_is_token_char", counting_is_token_char)
|
||||
text = "a." * 20000
|
||||
units, _, _ = extract_complete_units(text, frozenset(".!?"), flush=True)
|
||||
assert units == [text]
|
||||
assert checks <= len(text) * (speech_text_splitter._MAX_ABBREVIATION_LEN + 1)
|
||||
|
||||
def test_cjk_period_completes_once_the_next_char_is_known(self):
|
||||
# The trailing 。 waits: a closing delimiter could still follow it.
|
||||
units, remainder, _ = extract_complete_units("你好。世界。", frozenset(".!?。!?"), flush=False)
|
||||
assert units == ["你好。"]
|
||||
assert remainder == "世界。"
|
||||
|
||||
units, remainder, _ = extract_complete_units("你好。世界。", frozenset(".!?。!?"), flush=True)
|
||||
assert units == ["你好。", "世界。"]
|
||||
assert remainder == ""
|
||||
|
||||
def test_indic_danda_and_question_mark(self):
|
||||
units, remainder, _ = extract_complete_units("नमस्ते। कैसे हो?", frozenset(".!?।॥؟"), flush=True)
|
||||
assert units == ["नमस्ते।", "कैसे हो?"]
|
||||
assert remainder == ""
|
||||
|
||||
def test_scan_cursor_skips_already_examined_text(self):
|
||||
units, remainder, scan = extract_complete_units("no terminator yet", frozenset(".!?"), flush=False)
|
||||
assert units == []
|
||||
assert remainder == "no terminator yet"
|
||||
assert scan == len(remainder)
|
||||
|
||||
units, remainder, scan = extract_complete_units(
|
||||
"no terminator yet. Next", frozenset(".!?"), flush=False, scan_from=scan
|
||||
)
|
||||
assert units == ["no terminator yet."]
|
||||
assert remainder == "Next"
|
||||
|
||||
|
||||
class TestSpeechTextSplitter:
|
||||
def test_none_buffers_until_flush(self):
|
||||
splitter = SpeechTextSplitter("none")
|
||||
assert splitter.feed("Hello world. ") == []
|
||||
assert splitter.flush() == ["Hello world."]
|
||||
assert splitter.flush() == []
|
||||
|
||||
def test_sentence_mode_incremental_words(self):
|
||||
splitter = SpeechTextSplitter("sentence")
|
||||
assert splitter.feed("Hello ") == []
|
||||
assert splitter.feed("world. ") == ["Hello world."]
|
||||
assert splitter.feed("How are you?") == []
|
||||
assert splitter.flush() == ["How are you?"]
|
||||
|
||||
def test_sentence_mode_resumes_scan_across_feeds(self):
|
||||
splitter = SpeechTextSplitter("sentence")
|
||||
assert splitter.feed("It costs 3") == []
|
||||
assert splitter.feed(".") == []
|
||||
assert splitter.feed("14 dollars. ") == ["It costs 3.14 dollars."]
|
||||
|
||||
def test_clause_mode_splits_on_comma(self):
|
||||
splitter = SpeechTextSplitter("clause")
|
||||
assert splitter.feed("Hello, world. ") == ["Hello,", "world."]
|
||||
|
||||
def test_clause_mode_splits_on_arabic_semicolon(self):
|
||||
splitter = SpeechTextSplitter("clause")
|
||||
assert splitter.feed("مرحبا؛ كيف حالك") == ["مرحبا؛"]
|
||||
|
||||
def test_empty_flush(self):
|
||||
splitter = SpeechTextSplitter("sentence")
|
||||
assert splitter.flush() == []
|
||||
@@ -22,12 +22,14 @@ from vllm_omni.entrypoints.openai.tts_adapters import (
|
||||
detect_tts_model_type,
|
||||
resolve_adapter,
|
||||
)
|
||||
from vllm_omni.entrypoints.openai.tts_adapters.covo_audio import CovoAudioAdapter
|
||||
from vllm_omni.entrypoints.openai.tts_adapters.higgs_audio_v2 import HiggsAudioV2Adapter
|
||||
from vllm_omni.entrypoints.openai.tts_adapters.indextts2 import (
|
||||
IndexTTS2Adapter,
|
||||
IndexTTS25Adapter,
|
||||
indextts2_conditioning_cache_salt,
|
||||
)
|
||||
from vllm_omni.entrypoints.openai.tts_adapters.ming_flash_omni_tts import MingFlashOmniTTSAdapter
|
||||
from vllm_omni.entrypoints.openai.tts_adapters.moss_tts import (
|
||||
MossTTSAdapter,
|
||||
MossTTSNanoAdapter,
|
||||
@@ -37,6 +39,8 @@ from vllm_omni.entrypoints.openai.tts_adapters.qwen3_tts import (
|
||||
Qwen3TTSAdapter,
|
||||
Qwen3TTSCodecLimitError,
|
||||
)
|
||||
from vllm_omni.entrypoints.openai.tts_adapters.step_audio2 import StepAudio2Adapter
|
||||
from vllm_omni.entrypoints.openai.tts_adapters.voxtral import VoxtralTTSAdapter
|
||||
from vllm_omni.model_executor.models.indextts2 import prompt_utils
|
||||
from vllm_omni.model_executor.models.indextts2.tokenizer_v2_5 import (
|
||||
INDEXTTS25_TOKENIZER_FILE,
|
||||
@@ -125,8 +129,8 @@ def test_moss_tts_applies_request_max_new_tokens(adapter_cls):
|
||||
|
||||
def _build_moss_tts_request(adapter_cls, mocker, *, request_seed):
|
||||
server = mocker.Mock()
|
||||
server._build_moss_tts_params = mocker.AsyncMock(return_value={})
|
||||
adapter = adapter_cls(SpeechServingContext(server=server))
|
||||
adapter._build_moss_tts_params = mocker.AsyncMock(return_value={})
|
||||
request = OpenAICreateSpeechRequest(input="hello", seed=request_seed)
|
||||
|
||||
return asyncio.run(
|
||||
@@ -162,46 +166,45 @@ def test_moss_tts_seed_falls_back_to_stage_default(adapter_cls, mocker):
|
||||
assert prepared.tts_params["seed"] == [42]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("variant,ref_text", [("local", None), ("local", " "), ("tts", "Reference.")])
|
||||
def test_moss_tts_generation_fallback(variant, ref_text, mocker):
|
||||
server = mocker.Mock(_moss_variant=variant)
|
||||
server._build_moss_tts_params = mocker.AsyncMock(return_value={"prompt_token_ids": [7]})
|
||||
request = OpenAICreateSpeechRequest(input="Target.", ref_text=ref_text)
|
||||
adapter = MossTTSAdapter(SpeechServingContext(server=server))
|
||||
|
||||
prepared = asyncio.run(adapter.build(request, [], has_inline_ref_audio=True))
|
||||
|
||||
server._build_moss_tts_params.assert_awaited_once_with(request, has_inline_ref_audio=True)
|
||||
server._get_moss_processor.assert_not_called()
|
||||
assert prepared.prompt["prompt_token_ids"] == [7]
|
||||
|
||||
|
||||
def test_moss_local_reference_transcript_continuation(mocker):
|
||||
@pytest.mark.parametrize(
|
||||
"variant,ref_text,mode",
|
||||
[
|
||||
("local", " Reference. ", "continuation"),
|
||||
("local", None, "generation"),
|
||||
("local", " ", "generation"),
|
||||
("tts", "Reference.", "generation"),
|
||||
],
|
||||
)
|
||||
def test_moss_reference_transcript_mode(variant, ref_text, mode, mocker):
|
||||
import torch
|
||||
|
||||
reference = [torch.ones((3, 12), dtype=torch.int64)]
|
||||
unified = torch.arange(52, dtype=torch.int64).reshape(1, 4, 13)
|
||||
processor = mocker.Mock(return_value={"input_ids": unified})
|
||||
server = mocker.Mock(_moss_variant="local", uploaded_speakers={"speaker": {}})
|
||||
server._build_moss_tts_params = mocker.AsyncMock(return_value={"prompt_token_ids": [7]})
|
||||
server._get_moss_processor.return_value = processor
|
||||
server._voice_created_at.return_value = 123
|
||||
server._encode_moss_references = mocker.AsyncMock(return_value=(reference, {0: "reference-key"}))
|
||||
request = OpenAICreateSpeechRequest(
|
||||
input="Target.", ref_text=" Reference. ", language="English", voice="Speaker", seed=0, max_new_tokens=2048
|
||||
input="Target.", ref_text=ref_text, language="English", voice="Speaker", seed=0, max_new_tokens=2048
|
||||
)
|
||||
adapter = MossTTSAdapter(SpeechServingContext(server=server))
|
||||
|
||||
adapter._moss_variant = variant
|
||||
mocker.patch.object(adapter, "_get_moss_processor", return_value=processor)
|
||||
mocker.patch.object(
|
||||
adapter, "_encode_moss_references", new=mocker.AsyncMock(return_value=(reference, {0: "reference-key"}))
|
||||
)
|
||||
|
||||
prepared = asyncio.run(adapter.build(request, [], has_inline_ref_audio=False))
|
||||
|
||||
processor.build_user_message.assert_called_once_with(text="Reference. Target.", language="English")
|
||||
processor.build_assistant_message.assert_called_once_with(audio_codes_list=reference)
|
||||
processor.assert_called_once_with(
|
||||
conversations=[[processor.build_user_message.return_value, processor.build_assistant_message.return_value]],
|
||||
mode="continuation",
|
||||
)
|
||||
server._encode_moss_references.assert_awaited_once_with(request, has_inline_ref_audio=False, two_speaker=False)
|
||||
server._build_moss_tts_params.assert_not_called()
|
||||
if mode == "continuation":
|
||||
processor.build_user_message.assert_called_once_with(text="Reference. Target.", language="English")
|
||||
processor.build_assistant_message.assert_called_once_with(audio_codes_list=reference)
|
||||
conversation = [processor.build_user_message.return_value, processor.build_assistant_message.return_value]
|
||||
else:
|
||||
processor.build_user_message.assert_called_once_with(text="Target.", language="English", reference=reference)
|
||||
processor.build_assistant_message.assert_not_called()
|
||||
conversation = [processor.build_user_message.return_value]
|
||||
processor.assert_called_once_with(conversations=[conversation], mode=mode)
|
||||
assert prepared.prompt["prompt_token_ids"] == unified[0, :, 0].tolist()
|
||||
assert torch.equal(prepared.tts_params["codes"]["ref"], unified[0, :, 1:])
|
||||
assert prepared.tts_params["max_new_frames"] == [2048]
|
||||
@@ -218,6 +221,81 @@ def test_qwen3_tts_metadata():
|
||||
assert issubclass(Qwen3TTSAdapter, ARTTSAdapter)
|
||||
|
||||
|
||||
def test_qwen3_tts_build_constructs_prepared_request():
|
||||
server = SimpleNamespace(_tts_executor=None, _tts_tokenizer=None, uploaded_speakers={})
|
||||
engine_client = SimpleNamespace(model_config=SimpleNamespace())
|
||||
adapter = Qwen3TTSAdapter(SimpleNamespace(server=server, engine_client=engine_client))
|
||||
|
||||
async def estimate_prompt_len(_tts_params):
|
||||
return 3
|
||||
|
||||
adapter._estimate_prompt_len_async = estimate_prompt_len
|
||||
request = OpenAICreateSpeechRequest(input="hello")
|
||||
|
||||
prepared = asyncio.run(adapter.build(request, [], False))
|
||||
|
||||
assert prepared.prompt["prompt_token_ids"] == [1, 1, 1]
|
||||
assert prepared.prompt["additional_information"] is prepared.tts_params
|
||||
assert prepared.tts_params["text"] == ["hello"]
|
||||
assert prepared.tts_params["speaker"] == ["Vivian"]
|
||||
assert prepared.model_type == "CustomVoice"
|
||||
|
||||
|
||||
def test_covo_audio_build_constructs_tokenized_prompt():
|
||||
class FakeTokenizer:
|
||||
def apply_chat_template(self, messages, *, tokenize, add_generation_prompt):
|
||||
assert messages[-1] == {"role": "user", "content": "hello"}
|
||||
assert tokenize is True
|
||||
assert add_generation_prompt is True
|
||||
return [11, 12, 13]
|
||||
|
||||
adapter = CovoAudioAdapter(SimpleNamespace(server=SimpleNamespace(), engine_client=SimpleNamespace()))
|
||||
adapter._tokenizer = FakeTokenizer()
|
||||
|
||||
prepared = asyncio.run(adapter.build(OpenAICreateSpeechRequest(input="hello"), [], False))
|
||||
|
||||
assert prepared.prompt == {"prompt_token_ids": [11, 12, 13]}
|
||||
assert prepared.tts_params == {}
|
||||
assert prepared.model_type == "covo_audio"
|
||||
|
||||
|
||||
def test_ming_flash_omni_build_constructs_prepared_request():
|
||||
server = SimpleNamespace(uploaded_speakers={})
|
||||
adapter = MingFlashOmniTTSAdapter(SimpleNamespace(server=server, engine_client=SimpleNamespace()))
|
||||
request = OpenAICreateSpeechRequest(input="hello", voice="test")
|
||||
|
||||
prepared = asyncio.run(adapter.build(request, [], False))
|
||||
|
||||
assert prepared.prompt["prompt_token_ids"] == [0]
|
||||
info = prepared.prompt["additional_information"]
|
||||
assert info["ming_task"] == "instruct"
|
||||
assert info["text"] == "hello"
|
||||
assert info["voice_name"] == "test"
|
||||
assert prepared.model_type == "ming_flash_omni_tts"
|
||||
|
||||
|
||||
def test_step_audio2_build_constructs_open_assistant_turn():
|
||||
adapter = StepAudio2Adapter(SimpleNamespace(server=SimpleNamespace(), engine_client=SimpleNamespace()))
|
||||
request = OpenAICreateSpeechRequest(input="hello", instructions="Read warmly.")
|
||||
|
||||
prepared = asyncio.run(adapter.build(request, [], False))
|
||||
|
||||
assert "<|im_start|>system\nRead warmly.<|im_end|>" in prepared.prompt["prompt"]
|
||||
assert prepared.prompt["prompt"].endswith("<|im_start|>assistant\n<tts_start>")
|
||||
assert prepared.tts_params == {}
|
||||
assert prepared.model_type == "step_audio2"
|
||||
|
||||
|
||||
def test_voxtral_prompt_builder_is_sync():
|
||||
ctx = SimpleNamespace(
|
||||
server=SimpleNamespace(_tts_executor=None),
|
||||
engine_client=SimpleNamespace(),
|
||||
)
|
||||
adapter = VoxtralTTSAdapter(ctx)
|
||||
|
||||
assert not asyncio.iscoroutinefunction(adapter._build_prompt)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("task_type", "text_tokens", "request_cap", "expected_cap"),
|
||||
[
|
||||
|
||||
@@ -132,6 +132,8 @@ _PIPELINE_STAGES = [
|
||||
"audex_thinker",
|
||||
"audex_tta_thinker",
|
||||
"audex_xcodec",
|
||||
"audio8_tts_codec_decoder",
|
||||
"audio8_tts_slow_ar",
|
||||
"audio_generation",
|
||||
"audio_tokenizer",
|
||||
"audio_vae",
|
||||
|
||||
@@ -23,9 +23,9 @@ from vllm_omni.entrypoints.openai.errors import InvalidInputReferenceError
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
def _png_bytes() -> bytes:
|
||||
def _png_bytes(size: tuple[int, int] = (2, 1)) -> bytes:
|
||||
buffer = BytesIO()
|
||||
Image.new("RGB", (2, 1), color=(12, 34, 56)).save(buffer, format="PNG")
|
||||
Image.new("RGB", size, color=(12, 34, 56)).save(buffer, format="PNG")
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
@@ -122,6 +122,52 @@ async def test_decode_image_url_keeps_data_urls_local(monkeypatch):
|
||||
assert image.mode == "RGB"
|
||||
|
||||
|
||||
def test_decode_image_bytes_rejects_image_over_pixel_limit_before_conversion(monkeypatch):
|
||||
monkeypatch.setattr(envs, "VLLM_MAX_IMAGE_PIXELS", 100)
|
||||
|
||||
def _unexpected_convert(*args, **kwargs):
|
||||
pytest.fail("over-limit images must be rejected before conversion")
|
||||
|
||||
monkeypatch.setattr(Image.Image, "convert", _unexpected_convert)
|
||||
|
||||
with pytest.raises(
|
||||
InvalidInputReferenceError,
|
||||
match=r"Image dimensions 20x20 \(400 pixels\) exceed the maximum of 100 pixels",
|
||||
):
|
||||
video_api_utils._decode_image_bytes(_png_bytes((20, 20)), source="image reference")
|
||||
|
||||
|
||||
def test_decode_image_bytes_maps_pillow_pixel_limit_error(monkeypatch):
|
||||
monkeypatch.setattr(Image, "MAX_IMAGE_PIXELS", 100)
|
||||
|
||||
with pytest.raises(InvalidInputReferenceError, match="decoder pixel limit") as exc_info:
|
||||
video_api_utils._decode_image_bytes(_png_bytes((20, 20)), source="image reference")
|
||||
|
||||
assert isinstance(exc_info.value.__cause__, Image.DecompressionBombError)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("max_pixels", [0, 400])
|
||||
def test_decode_image_bytes_allows_disabled_or_inclusive_pixel_limit(monkeypatch, max_pixels):
|
||||
monkeypatch.setattr(envs, "VLLM_MAX_IMAGE_PIXELS", max_pixels)
|
||||
|
||||
image = video_api_utils._decode_image_bytes(_png_bytes((20, 20)), source="image reference")
|
||||
|
||||
assert image.size == (20, 20)
|
||||
assert image.mode == "RGB"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_decode_input_reference_preserves_image_pixel_limit_error(monkeypatch):
|
||||
monkeypatch.setattr(envs, "VLLM_MAX_IMAGE_PIXELS", 100)
|
||||
|
||||
with pytest.raises(InvalidInputReferenceError, match="VLLM_MAX_IMAGE_PIXELS"):
|
||||
await video_api_utils.decode_input_reference(
|
||||
image_reference=None,
|
||||
video_reference=None,
|
||||
input_reference_bytes=_png_bytes((20, 20)),
|
||||
)
|
||||
|
||||
|
||||
def _install_fake_video_mux(monkeypatch, mux_calls):
|
||||
def _fake_mux_video_audio_bytes(frames, audio, fps, audio_sample_rate, video_codec_options=None):
|
||||
mux_calls.append(
|
||||
|
||||
@@ -75,6 +75,7 @@ class FakeAsyncOmni:
|
||||
self.model_class_name = "WanPipeline"
|
||||
self.captured_prompt = None
|
||||
self.captured_reference_video_bytes = None
|
||||
self.captured_control_reference_bytes = {}
|
||||
self.captured_sampling_params_list = None
|
||||
|
||||
def get_diffusion_od_config(self):
|
||||
@@ -83,6 +84,10 @@ class FakeAsyncOmni:
|
||||
async def generate(self, prompt, request_id, sampling_params_list):
|
||||
self.captured_prompt = prompt
|
||||
self.captured_sampling_params_list = sampling_params_list
|
||||
for control_type in ("edge", "blur", "depth", "seg", "wsm"):
|
||||
control_params = sampling_params_list[0].extra_args.get(control_type)
|
||||
if isinstance(control_params, dict) and isinstance(control_params.get("control_path"), str):
|
||||
self.captured_control_reference_bytes[control_type] = Path(control_params["control_path"]).read_bytes()
|
||||
reference_videos = prompt.get("multi_modal_data", {}).get("video")
|
||||
if (
|
||||
isinstance(reference_videos, list)
|
||||
@@ -338,6 +343,8 @@ def _cosmos3_stage_configs():
|
||||
return [
|
||||
SimpleNamespace(
|
||||
stage_type="diffusion",
|
||||
final_output=True,
|
||||
final_output_type="video",
|
||||
engine_args=SimpleNamespace(model_class_name="Cosmos3OmniDiffusersPipeline"),
|
||||
)
|
||||
]
|
||||
@@ -919,6 +926,17 @@ def test_mixed_reference_capability_uses_model_metadata_when_config_defaults_fal
|
||||
assert handler.supports_mixed_reference_inputs
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model_class_name", ["Cosmos3OmniDiffusersPipeline", "Cosmos3OmniPipeline"])
|
||||
def test_control_upload_capability_is_declared_only_by_cosmos3(test_client, model_class_name):
|
||||
handler = test_client.app.state.openai_serving_video
|
||||
handler._engine_client.model_class_name = model_class_name
|
||||
|
||||
assert handler.supported_control_upload_types == frozenset({"edge", "blur", "depth", "seg", "wsm"})
|
||||
|
||||
handler._engine_client.model_class_name = "WanPipeline"
|
||||
assert handler.supported_control_upload_types == frozenset()
|
||||
|
||||
|
||||
def test_decode_video_bytes_can_keep_first_frames():
|
||||
from vllm_omni.entrypoints.openai.video_api_utils import _decode_video_bytes
|
||||
|
||||
@@ -1612,7 +1630,8 @@ def test_generic_video_model_rejects_mixed_image_and_video_references(test_clien
|
||||
assert "does not support mixed image and video" in response.json()["detail"].lower()
|
||||
|
||||
|
||||
def test_h3_multipart_rejects_bmp_image_reference(test_client):
|
||||
def test_h3_multipart_rejects_bmp_image_reference(test_client, monkeypatch):
|
||||
monkeypatch.setattr(envs, "VLLM_MAX_IMAGE_PIXELS", 100)
|
||||
image = Image.new("RGB", (64, 64), color="blue")
|
||||
image_buffer = io.BytesIO()
|
||||
image.save(image_buffer, format="BMP")
|
||||
@@ -1628,6 +1647,37 @@ def test_h3_multipart_rejects_bmp_image_reference(test_client):
|
||||
assert "must use jpg" in response.json()["detail"].lower()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("field", ["input_reference", "input_references"])
|
||||
def test_h3_multipart_rejects_image_over_pixel_limit(field, test_client, monkeypatch):
|
||||
monkeypatch.setattr(envs, "VLLM_MAX_IMAGE_PIXELS", 100)
|
||||
test_client.app.state.openai_serving_video._engine_client.model_class_name = "MiniMaxH3Pipeline"
|
||||
|
||||
response = test_client.post(
|
||||
"/v1/videos/sync",
|
||||
data={"prompt": "reject oversized image", "extra_params": '{"task":"ref2va"}'},
|
||||
files=[(field, ("reference.png", _make_test_image_bytes((20, 20)), "image/png"))],
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "VLLM_MAX_IMAGE_PIXELS" in response.json()["detail"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("field", ["input_reference", "input_references"])
|
||||
def test_h3_multipart_maps_pillow_pixel_limit_error(field, test_client, monkeypatch):
|
||||
monkeypatch.setattr(envs, "VLLM_MAX_IMAGE_PIXELS", 0)
|
||||
monkeypatch.setattr(Image, "MAX_IMAGE_PIXELS", 100)
|
||||
test_client.app.state.openai_serving_video._engine_client.model_class_name = "MiniMaxH3Pipeline"
|
||||
|
||||
response = test_client.post(
|
||||
"/v1/videos/sync",
|
||||
data={"prompt": "reject decoder bomb", "extra_params": '{"task":"ref2va"}'},
|
||||
files=[(field, ("reference.png", _make_test_image_bytes((20, 20)), "image/png"))],
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "decoder pixel limit" in response.json()["detail"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_h3_upload_limit_checks_declared_size_before_read():
|
||||
class OversizedUpload:
|
||||
@@ -1800,6 +1850,24 @@ def test_video_request_validation():
|
||||
VideoGenerationRequest(prompt="test", quality="medium")
|
||||
|
||||
|
||||
def test_async_create_accepts_fractional_fps(test_client, mocker: MockerFixture):
|
||||
"""Queued VideoResponse must accept fractional fps from the request path."""
|
||||
_mock_encode_video_bytes(mocker)
|
||||
response = test_client.post(
|
||||
"/v1/videos",
|
||||
data={"prompt": "fractional fps", "fps": "12.5", "num_frames": "5"},
|
||||
)
|
||||
assert response.status_code == 200, response.text
|
||||
body = response.json()
|
||||
assert body["fps"] == 12.5
|
||||
assert body["num_frames"] == 5
|
||||
video_id = body["id"]
|
||||
_wait_for_status(test_client, video_id, VideoGenerationStatus.COMPLETED.value)
|
||||
engine = test_client.app.state.openai_serving_video._engine_client
|
||||
assert engine.captured_sampling_params_list[0].fps == 12.5
|
||||
assert engine.captured_sampling_params_list[0].frame_rate == 12.5
|
||||
|
||||
|
||||
def test_list_videos_supports_order_after_and_limit(test_client, mocker: MockerFixture):
|
||||
mocker.patch(
|
||||
"vllm_omni.entrypoints.openai.serving_video._encode_video_bytes",
|
||||
@@ -2218,6 +2286,171 @@ def test_sync_v2v_returns_video_bytes(test_client, mocker: MockerFixture):
|
||||
assert input_video[0].size == (32, 24)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("endpoint", ["/v1/videos", "/v1/videos/sync"])
|
||||
@pytest.mark.parametrize("control_type", ["wsm", "depth"])
|
||||
def test_cosmos3_accepts_optional_uploaded_control(
|
||||
endpoint,
|
||||
control_type,
|
||||
test_client,
|
||||
mocker: MockerFixture,
|
||||
):
|
||||
control_bytes = f"{control_type}-control".encode()
|
||||
_mock_encode_video_bytes(mocker, b"controlled-video")
|
||||
engine = test_client.app.state.openai_serving_video._engine_client
|
||||
engine.model_class_name = "Cosmos3OmniDiffusersPipeline"
|
||||
|
||||
response = test_client.post(
|
||||
endpoint,
|
||||
data={
|
||||
"prompt": "Follow the uploaded control.",
|
||||
"control_type": control_type,
|
||||
"extra_params": json.dumps({control_type: {"control_weight": 0.75}}),
|
||||
},
|
||||
files=[
|
||||
("input_reference", ("input.mp4", _make_test_video_bytes(), "video/mp4")),
|
||||
("control_reference", (f"{control_type}.mp4", control_bytes, "video/mp4")),
|
||||
],
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
if endpoint.endswith("/sync"):
|
||||
assert response.content == b"controlled-video"
|
||||
else:
|
||||
video_id = response.json()["id"]
|
||||
_wait_for_status(test_client, video_id, VideoGenerationStatus.COMPLETED.value)
|
||||
|
||||
captured = engine.captured_sampling_params_list[0].extra_args[control_type]
|
||||
assert captured["control_weight"] == 0.75
|
||||
assert engine.captured_control_reference_bytes[control_type] == control_bytes
|
||||
assert len(engine.captured_prompt["multi_modal_data"]["video"]) == 3
|
||||
assert not Path(captured["control_path"]).exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("endpoint", ["/v1/videos", "/v1/videos/sync"])
|
||||
def test_cosmos3_uploaded_control_selects_transfer_reference_video_decode_policy(
|
||||
endpoint,
|
||||
test_client,
|
||||
mocker: MockerFixture,
|
||||
):
|
||||
_mock_encode_video_bytes(mocker, b"controlled-video")
|
||||
test_client.app.state.stage_configs = _cosmos3_stage_configs()
|
||||
|
||||
response = test_client.post(
|
||||
endpoint,
|
||||
data={
|
||||
"prompt": "Preserve all conditioning motion.",
|
||||
"control_type": "wsm",
|
||||
"num_frames": "9",
|
||||
"extra_params": json.dumps({"num_first_chunk_conditional_frames": 9}),
|
||||
},
|
||||
files=[
|
||||
(
|
||||
"input_reference",
|
||||
("input.mp4", _make_test_video_bytes(num_frames=6), "video/mp4"),
|
||||
),
|
||||
("control_reference", ("wsm.mp4", b"control", "video/mp4")),
|
||||
],
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
if not endpoint.endswith("/sync"):
|
||||
video_id = response.json()["id"]
|
||||
_wait_for_status(test_client, video_id, VideoGenerationStatus.COMPLETED.value)
|
||||
|
||||
engine = test_client.app.state.openai_serving_video._engine_client
|
||||
assert len(engine.captured_prompt["multi_modal_data"]["video"]) == 6
|
||||
|
||||
|
||||
def test_cosmos3_control_upload_is_optional(test_client, mocker: MockerFixture):
|
||||
_mock_encode_video_bytes(mocker)
|
||||
engine = test_client.app.state.openai_serving_video._engine_client
|
||||
engine.model_class_name = "Cosmos3OmniDiffusersPipeline"
|
||||
|
||||
response = test_client.post("/v1/videos/sync", data={"prompt": "No control for this request."})
|
||||
|
||||
assert response.status_code == 200
|
||||
assert "wsm" not in engine.captured_sampling_params_list[0].extra_args
|
||||
|
||||
|
||||
def test_control_upload_does_not_affect_models_without_capability(test_client):
|
||||
response = test_client.post(
|
||||
"/v1/videos/sync",
|
||||
data={"prompt": "Unsupported control.", "control_type": "wsm"},
|
||||
files={"control_reference": ("wsm.mp4", b"control", "video/mp4")},
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "not supported by this model" in response.json()["detail"]
|
||||
assert test_client.app.state.openai_serving_video._engine_client.captured_prompt is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("data", "files", "message"),
|
||||
[
|
||||
(
|
||||
{"prompt": "Missing type."},
|
||||
{"control_reference": ("wsm.mp4", b"control", "video/mp4")},
|
||||
"requires control_type",
|
||||
),
|
||||
(
|
||||
{"prompt": "Missing file.", "control_type": "wsm"},
|
||||
None,
|
||||
"requires a control_reference",
|
||||
),
|
||||
(
|
||||
{"prompt": "Unknown type.", "control_type": "unknown"},
|
||||
{"control_reference": ("control.mp4", b"control", "video/mp4")},
|
||||
"not supported by this model",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_cosmos3_control_upload_validates_contract(data, files, message, test_client):
|
||||
test_client.app.state.openai_serving_video._engine_client.model_class_name = "Cosmos3OmniDiffusersPipeline"
|
||||
|
||||
response = test_client.post("/v1/videos/sync", data=data, files=files)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert message in response.json()["detail"]
|
||||
|
||||
|
||||
def test_cosmos3_control_upload_rejects_existing_control_source(test_client):
|
||||
test_client.app.state.openai_serving_video._engine_client.model_class_name = "Cosmos3OmniDiffusersPipeline"
|
||||
response = test_client.post(
|
||||
"/v1/videos/sync",
|
||||
data={
|
||||
"prompt": "Ambiguous control.",
|
||||
"control_type": "wsm",
|
||||
"extra_params": json.dumps({"wsm": {"control_path": "/already/present.mp4"}}),
|
||||
},
|
||||
files={"control_reference": ("wsm.mp4", b"control", "video/mp4")},
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "not both" in response.json()["detail"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("control_bytes", "message"),
|
||||
[
|
||||
(b"", "must not be empty"),
|
||||
(b"control", "size limit"),
|
||||
],
|
||||
)
|
||||
def test_cosmos3_control_upload_rejects_invalid_size(control_bytes, message, test_client, monkeypatch):
|
||||
test_client.app.state.openai_serving_video._engine_client.model_class_name = "Cosmos3OmniDiffusersPipeline"
|
||||
monkeypatch.setattr(api_server, "CONTROL_REFERENCE_MAX_BYTES", 3)
|
||||
|
||||
response = test_client.post(
|
||||
"/v1/videos/sync",
|
||||
data={"prompt": "Invalid control.", "control_type": "wsm"},
|
||||
files={"control_reference": ("wsm.mp4", control_bytes, "video/mp4")},
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert message in response.json()["detail"]
|
||||
assert test_client.app.state.openai_serving_video._engine_client.captured_prompt is None
|
||||
|
||||
|
||||
def test_sync_missing_handler_returns_503():
|
||||
app = FastAPI()
|
||||
app.include_router(router)
|
||||
|
||||
@@ -4,8 +4,12 @@
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from pydantic import ValidationError
|
||||
|
||||
from vllm_omni.diffusion.data import AttentionConfig
|
||||
from vllm_omni.config.config_factory import StageConfigFactory
|
||||
from vllm_omni.config.resolver import OmniConfigResolution
|
||||
from vllm_omni.diffusion.data import AttentionConfig, OmniDiffusionConfig
|
||||
from vllm_omni.engine import stage_init_utils
|
||||
from vllm_omni.engine.async_omni_engine import AsyncOmniEngine
|
||||
from vllm_omni.entrypoints.cli.serve import OmniServeCommand
|
||||
@@ -14,9 +18,13 @@ from vllm_omni.utils.tracking_parser import TrackingArgumentParser
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
def _terminal_config(stage_cfg: dict) -> OmniDiffusionConfig:
|
||||
return OmniDiffusionConfig.from_kwargs(**stage_cfg["engine_args"])
|
||||
|
||||
|
||||
def test_default_stage_config_includes_cache_backend():
|
||||
"""Ensure cache knobs survive the default diffusion-stage builder."""
|
||||
stage_cfg = AsyncOmniEngine._create_default_diffusion_stage_cfg(
|
||||
stage_cfg = StageConfigFactory.create_default_diffusion(
|
||||
{
|
||||
"cache_backend": "cache_dit",
|
||||
"cache_config": '{"Fn_compute_blocks": 2}',
|
||||
@@ -30,12 +38,12 @@ def test_default_stage_config_includes_cache_backend():
|
||||
assert engine_args["cache_backend"] == "cache_dit"
|
||||
assert engine_args["cache_config"]["Fn_compute_blocks"] == 2
|
||||
assert engine_args["vae_use_slicing"] is True
|
||||
assert engine_args["parallel_config"].ulysses_degree == 2
|
||||
assert engine_args["parallel_config"]["ulysses_degree"] == 2
|
||||
assert engine_args["model_stage"] == "diffusion"
|
||||
|
||||
|
||||
def test_default_stage_config_preserves_ulysses_a2a_permute() -> None:
|
||||
stage_cfg = AsyncOmniEngine._create_default_diffusion_stage_cfg(
|
||||
stage_cfg = StageConfigFactory.create_default_diffusion(
|
||||
{
|
||||
"ulysses_degree": 4,
|
||||
"ulysses_a2a_permute": True,
|
||||
@@ -43,18 +51,18 @@ def test_default_stage_config_preserves_ulysses_a2a_permute() -> None:
|
||||
)[0]
|
||||
|
||||
parallel_config = stage_cfg["engine_args"]["parallel_config"]
|
||||
assert parallel_config.ulysses_degree == 4
|
||||
assert parallel_config.ulysses_a2a_permute is True
|
||||
assert parallel_config["ulysses_degree"] == 4
|
||||
assert parallel_config["ulysses_a2a_permute"] is True
|
||||
|
||||
|
||||
def test_default_stage_config_preserves_model_extras():
|
||||
stage_cfg = AsyncOmniEngine._create_default_diffusion_stage_cfg({"extras": {"ltx2_use_conv_vae": True}})[0]
|
||||
stage_cfg = StageConfigFactory.create_default_diffusion({"extras": {"ltx2_use_conv_vae": True}})[0]
|
||||
|
||||
assert stage_cfg["engine_args"]["extras"]["ltx2_use_conv_vae"] is True
|
||||
|
||||
|
||||
def test_default_stage_config_preserves_and_overrides_promoted_extras():
|
||||
stage_cfg = AsyncOmniEngine._create_default_diffusion_stage_cfg(
|
||||
stage_cfg = StageConfigFactory.create_default_diffusion(
|
||||
{
|
||||
"extras": {
|
||||
"auxiliary_text_encoder": "/models/extras-llama",
|
||||
@@ -68,7 +76,7 @@ def test_default_stage_config_preserves_and_overrides_promoted_extras():
|
||||
assert extras["auxiliary_text_encoder"] == "/models/extras-llama"
|
||||
assert extras["default_llama_model_id"] == "extras/default-llama"
|
||||
|
||||
stage_cfg = AsyncOmniEngine._create_default_diffusion_stage_cfg(
|
||||
stage_cfg = StageConfigFactory.create_default_diffusion(
|
||||
{
|
||||
"extras": {
|
||||
"auxiliary_text_encoder": "/models/extras-llama",
|
||||
@@ -84,43 +92,57 @@ def test_default_stage_config_preserves_and_overrides_promoted_extras():
|
||||
assert extras["default_llama_model_id"] == "top-level/default-llama"
|
||||
|
||||
|
||||
def test_stage_override_preserves_model_extras_for_default_diffusion_stage(mocker):
|
||||
@pytest.mark.parametrize(
|
||||
"stage_overrides",
|
||||
[
|
||||
{"0": {"extras": {"ltx2_use_conv_vae": True}}},
|
||||
'{"0":{"extras":{"ltx2_use_conv_vae":true}}}',
|
||||
],
|
||||
)
|
||||
def test_stage_override_preserves_model_extras_for_default_diffusion_stage(mocker, stage_overrides):
|
||||
"""Local/unregistered Diffusers checkpoints still honor stage-0 extras."""
|
||||
|
||||
def resolve_with_default(*_args, default_stage_cfg_factory, **_kwargs):
|
||||
return None, default_stage_cfg_factory(), None
|
||||
|
||||
mocker.patch(
|
||||
"vllm_omni.engine.async_omni_engine.load_and_resolve_stage_configs",
|
||||
side_effect=resolve_with_default,
|
||||
"vllm_omni.config.resolver.StageConfigFactory.create_from_model",
|
||||
return_value=None,
|
||||
)
|
||||
mocker.patch(
|
||||
"vllm_omni.config.resolver._resolve_generic_diffusion_model_class",
|
||||
return_value=(True, "LTX2Pipeline"),
|
||||
)
|
||||
engine = AsyncOmniEngine.__new__(AsyncOmniEngine)
|
||||
|
||||
_, stage_configs = engine._resolve_stage_configs(
|
||||
"/models/LTX-2.5-Diffusers",
|
||||
{"stage_overrides": '{"0":{"extras":{"ltx2_use_conv_vae":true}}}'},
|
||||
{"stage_overrides": stage_overrides},
|
||||
trust_remote_code=False,
|
||||
)
|
||||
|
||||
assert stage_configs[0]["engine_args"]["extras"]["ltx2_use_conv_vae"] is True
|
||||
|
||||
|
||||
def test_default_stage_rejects_unknown_nested_parallel_config_key():
|
||||
unknown_key = "unknown_parallel_field"
|
||||
with pytest.raises(ValidationError, match=unknown_key):
|
||||
StageConfigFactory.create_default_diffusion(
|
||||
{"parallel_config": {unknown_key: 2}},
|
||||
)
|
||||
|
||||
|
||||
def test_default_cache_config_used_when_missing():
|
||||
"""Ensure default cache_config is synthesized when only backend is given."""
|
||||
stage_cfg = AsyncOmniEngine._create_default_diffusion_stage_cfg(
|
||||
stage_cfg = StageConfigFactory.create_default_diffusion(
|
||||
{
|
||||
"cache_backend": "cache_dit",
|
||||
}
|
||||
)[0]
|
||||
|
||||
cache_config = stage_cfg["engine_args"]["cache_config"]
|
||||
assert cache_config is not None
|
||||
assert cache_config["Fn_compute_blocks"] == 1
|
||||
cache_config = _terminal_config(stage_cfg).cache_config
|
||||
assert cache_config.Fn_compute_blocks == 1
|
||||
|
||||
|
||||
def test_default_stage_devices_from_sequence_parallel():
|
||||
"""Ensure runtime devices reflect computed diffusion world size."""
|
||||
stage_cfg = AsyncOmniEngine._create_default_diffusion_stage_cfg(
|
||||
stage_cfg = StageConfigFactory.create_default_diffusion(
|
||||
{
|
||||
"ulysses_degree": 2,
|
||||
"ring_degree": 2,
|
||||
@@ -132,7 +154,7 @@ def test_default_stage_devices_from_sequence_parallel():
|
||||
|
||||
def test_default_stage_devices_and_dp_from_num_gpus():
|
||||
"""Resolve omitted DP before deriving devices from an explicit GPU count."""
|
||||
stage_cfg = AsyncOmniEngine._create_default_diffusion_stage_cfg(
|
||||
stage_cfg = StageConfigFactory.create_default_diffusion(
|
||||
{
|
||||
"num_gpus": 8,
|
||||
"tensor_parallel_size": 2,
|
||||
@@ -141,15 +163,14 @@ def test_default_stage_devices_and_dp_from_num_gpus():
|
||||
)[0]
|
||||
|
||||
parallel_config = stage_cfg["engine_args"]["parallel_config"]
|
||||
assert parallel_config.data_parallel_size == 2
|
||||
assert parallel_config.world_size == 8
|
||||
assert parallel_config["data_parallel_size"] == 2
|
||||
assert stage_cfg["engine_args"]["num_gpus"] == 8
|
||||
assert stage_cfg["runtime"]["devices"] == "0,1,2,3,4,5,6,7"
|
||||
|
||||
|
||||
def test_default_stage_config_uses_parallel_size_kwargs():
|
||||
"""Ensure default diffusion parallel_config uses CLI/API parallel sizes."""
|
||||
stage_cfg = AsyncOmniEngine._create_default_diffusion_stage_cfg(
|
||||
stage_cfg = StageConfigFactory.create_default_diffusion(
|
||||
{
|
||||
"pipeline_parallel_size": 2,
|
||||
"data_parallel_size": 3,
|
||||
@@ -159,15 +180,15 @@ def test_default_stage_config_uses_parallel_size_kwargs():
|
||||
)[0]
|
||||
|
||||
parallel_config = stage_cfg["engine_args"]["parallel_config"]
|
||||
assert parallel_config.pipeline_parallel_size == 2
|
||||
assert parallel_config.data_parallel_size == 3
|
||||
assert parallel_config.tensor_parallel_size == 4
|
||||
assert parallel_config.enable_expert_parallel is True
|
||||
assert parallel_config["pipeline_parallel_size"] == 2
|
||||
assert parallel_config["data_parallel_size"] == 3
|
||||
assert parallel_config["tensor_parallel_size"] == 4
|
||||
assert parallel_config["enable_expert_parallel"] is True
|
||||
|
||||
|
||||
def test_default_stage_config_preserves_omitted_dp_for_runtime_inference():
|
||||
"""Keep omitted DP unresolved until the runtime WORLD size is known."""
|
||||
stage_cfg = AsyncOmniEngine._create_default_diffusion_stage_cfg(
|
||||
stage_cfg = StageConfigFactory.create_default_diffusion(
|
||||
{
|
||||
"pipeline_parallel_size": None,
|
||||
"data_parallel_size": None,
|
||||
@@ -180,18 +201,19 @@ def test_default_stage_config_preserves_omitted_dp_for_runtime_inference():
|
||||
)[0]
|
||||
|
||||
parallel_config = stage_cfg["engine_args"]["parallel_config"]
|
||||
assert parallel_config.pipeline_parallel_size == 1
|
||||
assert parallel_config.data_parallel_size is None
|
||||
assert parallel_config.tensor_parallel_size == 1
|
||||
assert parallel_config.enable_expert_parallel is False
|
||||
assert stage_cfg["engine_args"]["enforce_eager"] is False
|
||||
assert stage_cfg["engine_args"]["diffusion_compile_granularity"] == "regional"
|
||||
assert stage_cfg["engine_args"]["diffusion_compile_dynamic"] is True
|
||||
assert parallel_config["pipeline_parallel_size"] == 1
|
||||
assert parallel_config["data_parallel_size"] is None
|
||||
assert parallel_config["tensor_parallel_size"] == 1
|
||||
assert parallel_config["enable_expert_parallel"] is False
|
||||
terminal_config = _terminal_config(stage_cfg)
|
||||
assert terminal_config.enforce_eager is False
|
||||
assert terminal_config.diffusion_compile_granularity == "regional"
|
||||
assert terminal_config.diffusion_compile_dynamic is True
|
||||
|
||||
|
||||
def test_default_stage_config_propagates_ulysses_mode():
|
||||
"""Ensure UAA mode survives default diffusion-stage creation."""
|
||||
stage_cfg = AsyncOmniEngine._create_default_diffusion_stage_cfg(
|
||||
stage_cfg = StageConfigFactory.create_default_diffusion(
|
||||
{
|
||||
"ulysses_degree": 4,
|
||||
"ulysses_mode": "advanced_uaa",
|
||||
@@ -199,13 +221,13 @@ def test_default_stage_config_propagates_ulysses_mode():
|
||||
)[0]
|
||||
|
||||
parallel_config = stage_cfg["engine_args"]["parallel_config"]
|
||||
assert parallel_config.ulysses_degree == 4
|
||||
assert parallel_config.ulysses_mode == "advanced_uaa"
|
||||
assert parallel_config["ulysses_degree"] == 4
|
||||
assert parallel_config["ulysses_mode"] == "advanced_uaa"
|
||||
|
||||
|
||||
def test_default_stage_config_includes_default_sampling_params():
|
||||
"""Ensure default sampling params survive the default diffusion-stage builder."""
|
||||
stage_cfg = AsyncOmniEngine._create_default_diffusion_stage_cfg(
|
||||
stage_cfg = StageConfigFactory.create_default_diffusion(
|
||||
{
|
||||
"default_sampling_params": '{"0": {"generator_device":"cpu", "guidance_scale":7.5}}',
|
||||
}
|
||||
@@ -219,13 +241,13 @@ def test_default_stage_config_includes_default_sampling_params():
|
||||
|
||||
def test_default_stage_config_includes_diffusion_attention_backend():
|
||||
"""Ensure diffusion attention shorthand lands in engine_args.diffusion_attention_config."""
|
||||
stage_cfg = AsyncOmniEngine._create_default_diffusion_stage_cfg(
|
||||
stage_cfg = StageConfigFactory.create_default_diffusion(
|
||||
{
|
||||
"diffusion_attention_backend": "FLASH_ATTN",
|
||||
}
|
||||
)[0]
|
||||
|
||||
diffusion_attention_config = stage_cfg["engine_args"]["diffusion_attention_config"]
|
||||
diffusion_attention_config = _terminal_config(stage_cfg).diffusion_attention_config
|
||||
assert isinstance(diffusion_attention_config, AttentionConfig)
|
||||
assert diffusion_attention_config.default is not None
|
||||
assert diffusion_attention_config.default.backend == "FLASH_ATTN"
|
||||
@@ -233,7 +255,7 @@ def test_default_stage_config_includes_diffusion_attention_backend():
|
||||
|
||||
def test_default_stage_config_includes_diffusion_attention_config():
|
||||
"""Ensure structured diffusion attention config survives default stage creation."""
|
||||
stage_cfg = AsyncOmniEngine._create_default_diffusion_stage_cfg(
|
||||
stage_cfg = StageConfigFactory.create_default_diffusion(
|
||||
{
|
||||
"diffusion_attention_config": {
|
||||
"default": {"backend": "FLASH_ATTN"},
|
||||
@@ -242,7 +264,7 @@ def test_default_stage_config_includes_diffusion_attention_config():
|
||||
}
|
||||
)[0]
|
||||
|
||||
diffusion_attention_config = stage_cfg["engine_args"]["diffusion_attention_config"]
|
||||
diffusion_attention_config = _terminal_config(stage_cfg).diffusion_attention_config
|
||||
assert isinstance(diffusion_attention_config, AttentionConfig)
|
||||
assert diffusion_attention_config.default is not None
|
||||
assert diffusion_attention_config.default.backend == "FLASH_ATTN"
|
||||
@@ -252,7 +274,7 @@ def test_default_stage_config_includes_diffusion_attention_config():
|
||||
def test_default_stage_config_rejects_conflicting_diffusion_attention_inputs():
|
||||
"""Ensure shorthand and default.backend stay mutually exclusive."""
|
||||
with pytest.raises(ValueError, match="mutually exclusive"):
|
||||
AsyncOmniEngine._create_default_diffusion_stage_cfg(
|
||||
StageConfigFactory.create_default_diffusion(
|
||||
{
|
||||
"diffusion_attention_backend": "FLASH_ATTN",
|
||||
"diffusion_attention_config": {
|
||||
@@ -264,7 +286,7 @@ def test_default_stage_config_rejects_conflicting_diffusion_attention_inputs():
|
||||
|
||||
def test_default_stage_config_engine_args():
|
||||
"""Ensure default diffusion-stage builder sets and propagates engine_args."""
|
||||
stage_cfg = AsyncOmniEngine._create_default_diffusion_stage_cfg(
|
||||
stage_cfg = StageConfigFactory.create_default_diffusion(
|
||||
{
|
||||
"distributed_executor_backend": "ray",
|
||||
"boundary_ratio": 0.875,
|
||||
@@ -283,7 +305,7 @@ def test_default_stage_config_engine_args():
|
||||
def test_default_stage_config_whitelist_none_fallback():
|
||||
"""DeployConfig / StageDeployConfig whitelist fields with value None
|
||||
fall back to OmniDiffusionConfig dataclass defaults."""
|
||||
stage_cfg = AsyncOmniEngine._create_default_diffusion_stage_cfg(
|
||||
stage_cfg = StageConfigFactory.create_default_diffusion(
|
||||
{
|
||||
# DeployConfig pipeline-wide
|
||||
"trust_remote_code": None,
|
||||
@@ -294,12 +316,11 @@ def test_default_stage_config_whitelist_none_fallback():
|
||||
}
|
||||
)[0]
|
||||
|
||||
engine_args = stage_cfg["engine_args"]
|
||||
|
||||
assert engine_args["trust_remote_code"] is False
|
||||
assert engine_args["distributed_executor_backend"] is None
|
||||
assert engine_args["dtype"] == "auto"
|
||||
assert engine_args["enforce_eager"] is False
|
||||
terminal = _terminal_config(stage_cfg)
|
||||
assert terminal.trust_remote_code is False
|
||||
assert terminal.distributed_executor_backend is None
|
||||
assert terminal.dtype == torch.bfloat16
|
||||
assert terminal.enforce_eager is False
|
||||
|
||||
|
||||
def test_serve_cli_accepts_ulysses_mode():
|
||||
@@ -321,12 +342,12 @@ def test_serve_cli_accepts_ulysses_mode():
|
||||
)
|
||||
|
||||
explicit_kwargs = args.get_explicit_kwargs_dict()
|
||||
stage_cfg = AsyncOmniEngine._create_default_diffusion_stage_cfg(explicit_kwargs)[0]
|
||||
stage_cfg = StageConfigFactory.create_default_diffusion(explicit_kwargs)[0]
|
||||
parallel_config = stage_cfg["engine_args"]["parallel_config"]
|
||||
|
||||
assert args.ulysses_mode == "advanced_uaa"
|
||||
assert parallel_config.ulysses_degree == 4
|
||||
assert parallel_config.ulysses_mode == "advanced_uaa"
|
||||
assert parallel_config["ulysses_degree"] == 4
|
||||
assert parallel_config["ulysses_mode"] == "advanced_uaa"
|
||||
|
||||
|
||||
def test_serve_cli_accepts_text_encoder_tp_size():
|
||||
@@ -345,11 +366,11 @@ def test_serve_cli_accepts_text_encoder_tp_size():
|
||||
)
|
||||
|
||||
explicit_kwargs = args.get_explicit_kwargs_dict()
|
||||
stage_cfg = AsyncOmniEngine._create_default_diffusion_stage_cfg(explicit_kwargs)[0]
|
||||
stage_cfg = StageConfigFactory.create_default_diffusion(explicit_kwargs)[0]
|
||||
parallel_config = stage_cfg["engine_args"]["parallel_config"]
|
||||
|
||||
assert args.text_encoder_tp_size == 4
|
||||
assert parallel_config.text_encoder_tp_size == 4
|
||||
assert parallel_config["text_encoder_tp_size"] == 4
|
||||
|
||||
|
||||
def test_serve_cli_forwards_model_defined_task_type_to_diffusion_stage():
|
||||
@@ -368,7 +389,7 @@ def test_serve_cli_forwards_model_defined_task_type_to_diffusion_stage():
|
||||
)
|
||||
|
||||
explicit_kwargs = args.get_explicit_kwargs_dict()
|
||||
stage_cfg = AsyncOmniEngine._create_default_diffusion_stage_cfg(explicit_kwargs)[0]
|
||||
stage_cfg = StageConfigFactory.create_default_diffusion(explicit_kwargs)[0]
|
||||
|
||||
assert args.task_type == "fl2va"
|
||||
assert stage_cfg["engine_args"]["task_type"] == "fl2va"
|
||||
@@ -390,7 +411,7 @@ def test_serve_cli_accepts_diffusion_pipeline_profiler_flag():
|
||||
)
|
||||
|
||||
explicit_kwargs = args.get_explicit_kwargs_dict()
|
||||
stage_cfg = AsyncOmniEngine._create_default_diffusion_stage_cfg(explicit_kwargs)[0]
|
||||
stage_cfg = StageConfigFactory.create_default_diffusion(explicit_kwargs)[0]
|
||||
|
||||
assert args.enable_diffusion_pipeline_profiler is True
|
||||
assert stage_cfg["engine_args"]["enable_diffusion_pipeline_profiler"] is True
|
||||
@@ -416,7 +437,7 @@ def test_serve_cli_forwards_distilled_lora_to_diffusion_stage():
|
||||
)
|
||||
|
||||
explicit_kwargs = args.get_explicit_kwargs_dict()
|
||||
stage_cfg = AsyncOmniEngine._create_default_diffusion_stage_cfg(explicit_kwargs)[0]
|
||||
stage_cfg = StageConfigFactory.create_default_diffusion(explicit_kwargs)[0]
|
||||
engine_args = stage_cfg["engine_args"]
|
||||
|
||||
assert explicit_kwargs["lora_backend"] == "distill"
|
||||
@@ -447,7 +468,7 @@ def test_serve_cli_forwards_compact_diffusion_offload_config():
|
||||
)
|
||||
|
||||
explicit_kwargs = args.get_explicit_kwargs_dict()
|
||||
stage_cfg = AsyncOmniEngine._create_default_diffusion_stage_cfg(explicit_kwargs)[0]
|
||||
stage_cfg = StageConfigFactory.create_default_diffusion(explicit_kwargs)[0]
|
||||
engine_args = stage_cfg["engine_args"]
|
||||
|
||||
expected = {
|
||||
@@ -513,7 +534,7 @@ def test_serve_cli_forwards_hwr_policy_for_no_allgather_dlo():
|
||||
)
|
||||
|
||||
explicit_kwargs = args.get_explicit_kwargs_dict()
|
||||
stage_cfg = AsyncOmniEngine._create_default_diffusion_stage_cfg(explicit_kwargs)[0]
|
||||
stage_cfg = StageConfigFactory.create_default_diffusion(explicit_kwargs)[0]
|
||||
engine_args = stage_cfg["engine_args"]
|
||||
|
||||
assert explicit_kwargs["host_weight_runtime_mode"] == "preferred"
|
||||
@@ -542,7 +563,7 @@ def test_serve_cli_accepts_diffusion_compile_controls():
|
||||
)
|
||||
|
||||
explicit_kwargs = args.get_explicit_kwargs_dict()
|
||||
stage_cfg = AsyncOmniEngine._create_default_diffusion_stage_cfg(explicit_kwargs)[0]
|
||||
stage_cfg = StageConfigFactory.create_default_diffusion(explicit_kwargs)[0]
|
||||
|
||||
assert args.diffusion_compile_granularity == "full"
|
||||
assert args.diffusion_compile_dynamic is False
|
||||
@@ -569,7 +590,7 @@ def test_serve_cli_accepts_diffusion_attention_backend():
|
||||
)
|
||||
|
||||
explicit_kwargs = args.get_explicit_kwargs_dict()
|
||||
stage_cfg = AsyncOmniEngine._create_default_diffusion_stage_cfg(explicit_kwargs)[0]
|
||||
stage_cfg = StageConfigFactory.create_default_diffusion(explicit_kwargs)[0]
|
||||
diffusion_attention_config = stage_cfg["engine_args"]["diffusion_attention_config"]
|
||||
|
||||
assert args.diffusion_attention_backend == "FASTVIDEO_VSA"
|
||||
@@ -597,7 +618,7 @@ def test_serve_cli_accepts_request_batch_max_wait_ms():
|
||||
)
|
||||
|
||||
explicit_kwargs = args.get_explicit_kwargs_dict()
|
||||
stage_cfg = AsyncOmniEngine._create_default_diffusion_stage_cfg(explicit_kwargs)[0]
|
||||
stage_cfg = StageConfigFactory.create_default_diffusion(explicit_kwargs)[0]
|
||||
|
||||
assert args.request_batch_max_wait_ms == 250.0
|
||||
assert stage_cfg["engine_args"]["request_batch_max_wait_ms"] == 250.0
|
||||
@@ -637,7 +658,7 @@ def test_serve_cli_accepts_additional_config():
|
||||
]
|
||||
)
|
||||
|
||||
stage_cfg = AsyncOmniEngine._create_default_diffusion_stage_cfg(vars(args))[0]
|
||||
stage_cfg = StageConfigFactory.create_default_diffusion(vars(args))[0]
|
||||
|
||||
engine_args = stage_cfg["engine_args"]
|
||||
|
||||
@@ -645,79 +666,19 @@ def test_serve_cli_accepts_additional_config():
|
||||
assert engine_args["additional_config"] == {"torchair_graph_config": {"enabled": True}}
|
||||
|
||||
|
||||
def test_default_stage_resolves_video_output_from_checkpoint(mocker):
|
||||
captured = {}
|
||||
|
||||
def resolve_with_default(*args, default_stage_cfg_factory, **kwargs):
|
||||
del args, kwargs
|
||||
captured.update(default_stage_cfg_factory()[0])
|
||||
stage = SimpleNamespace(stage_type="diffusion", engine_args=SimpleNamespace())
|
||||
return ("", [stage], None)
|
||||
|
||||
resolver = mocker.patch(
|
||||
"vllm_omni.engine.async_omni_engine.resolve_model_class_name",
|
||||
return_value="MiniMaxH3Pipeline",
|
||||
)
|
||||
mocker.patch(
|
||||
"vllm_omni.engine.async_omni_engine.load_and_resolve_stage_configs",
|
||||
side_effect=resolve_with_default,
|
||||
)
|
||||
engine = AsyncOmniEngine.__new__(AsyncOmniEngine)
|
||||
engine._strip_single_engine_args = lambda kwargs: kwargs
|
||||
|
||||
engine._resolve_stage_configs(
|
||||
"/models/MiniMax-H3/FL2VA",
|
||||
{},
|
||||
trust_remote_code=False,
|
||||
)
|
||||
|
||||
resolver.assert_called_once_with("/models/MiniMax-H3/FL2VA", "default")
|
||||
assert captured["final_output_type"] == "video"
|
||||
|
||||
|
||||
def test_default_diffusers_stage_preserves_video_model_identity(mocker):
|
||||
captured = {}
|
||||
|
||||
def resolve_with_default(*args, default_stage_cfg_factory, **kwargs):
|
||||
del args, kwargs
|
||||
captured.update(default_stage_cfg_factory()[0])
|
||||
stage = SimpleNamespace(stage_type="diffusion", engine_args=SimpleNamespace())
|
||||
return ("", [stage], None)
|
||||
|
||||
mocker.patch(
|
||||
"vllm_omni.diffusion.utils.hf_utils.get_diffusion_model_index",
|
||||
return_value={"_class_name": "WanImageToVideoPipeline"},
|
||||
)
|
||||
mocker.patch(
|
||||
"vllm_omni.engine.async_omni_engine.load_and_resolve_stage_configs",
|
||||
side_effect=resolve_with_default,
|
||||
)
|
||||
engine = AsyncOmniEngine.__new__(AsyncOmniEngine)
|
||||
engine._strip_single_engine_args = lambda kwargs: kwargs
|
||||
|
||||
engine._resolve_stage_configs(
|
||||
"/models/Wan2.2-I2V",
|
||||
{"diffusion_load_format": "diffusers"},
|
||||
trust_remote_code=False,
|
||||
)
|
||||
|
||||
assert captured["engine_args"]["model_class_name"] == "WanImageToVideoPipeline"
|
||||
assert captured["final_output_type"] == "video"
|
||||
|
||||
|
||||
def test_resolve_stage_configs_injects_additional_config_into_diffusion_stage(mocker):
|
||||
"""Ensure YAML/deploy stage resolution forwards top-level additional_config."""
|
||||
def test_resolve_stage_configs_delegates_overrides_to_resolver(mocker):
|
||||
"""The engine consumes resolver output without a second merge pass."""
|
||||
additional_config = {"torchair_graph_config": {"enabled": True}}
|
||||
fake_diffusion_stage = SimpleNamespace(
|
||||
stage_type="diffusion",
|
||||
engine_args=SimpleNamespace(),
|
||||
engine_args=SimpleNamespace(additional_config=additional_config),
|
||||
)
|
||||
fake_llm_stage = SimpleNamespace(
|
||||
stage_type="llm",
|
||||
engine_args=SimpleNamespace(),
|
||||
)
|
||||
mocker.patch(
|
||||
"vllm_omni.engine.async_omni_engine.load_and_resolve_stage_configs",
|
||||
return_value=("dummy.yaml", [fake_llm_stage, fake_diffusion_stage], None),
|
||||
resolve_config = mocker.patch(
|
||||
"vllm_omni.engine.async_omni_engine.resolve_omni_config",
|
||||
return_value=OmniConfigResolution(
|
||||
config_path="dummy.yaml",
|
||||
stage_configs=(fake_diffusion_stage,),
|
||||
),
|
||||
)
|
||||
|
||||
engine = AsyncOmniEngine.__new__(AsyncOmniEngine)
|
||||
@@ -726,13 +687,15 @@ def test_resolve_stage_configs_injects_additional_config_into_diffusion_stage(mo
|
||||
"dummy-model",
|
||||
{
|
||||
"deploy_config": "dummy.yaml",
|
||||
"additional_config": {"torchair_graph_config": {"enabled": True}},
|
||||
"additional_config": additional_config,
|
||||
},
|
||||
trust_remote_code=False,
|
||||
)
|
||||
|
||||
assert not hasattr(stage_configs[0].engine_args, "additional_config")
|
||||
assert stage_configs[1].engine_args.additional_config == {"torchair_graph_config": {"enabled": True}}
|
||||
assert stage_configs == [fake_diffusion_stage]
|
||||
assert resolve_config.call_args.args == ("dummy-model",)
|
||||
assert resolve_config.call_args.kwargs["deploy_config_path"] == "dummy.yaml"
|
||||
assert resolve_config.call_args.kwargs["cli_overrides"]["additional_config"] is additional_config
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
@@ -760,30 +723,6 @@ def test_default_stage_config_includes_quantization_config():
|
||||
"weights": "weights.bin",
|
||||
}
|
||||
|
||||
stage_cfg = AsyncOmniEngine._create_default_diffusion_stage_cfg({"quantization_config": quantization_config})[0]
|
||||
stage_cfg = StageConfigFactory.create_default_diffusion({"quantization_config": quantization_config})[0]
|
||||
|
||||
assert stage_cfg["engine_args"]["quantization_config"] == quantization_config
|
||||
|
||||
|
||||
def test_resolve_stage_configs_injects_quantization_config_into_diffusion_stage(mocker):
|
||||
fake_diffusion_stage = SimpleNamespace(
|
||||
stage_type="diffusion",
|
||||
engine_args=SimpleNamespace(quantization_config=None),
|
||||
)
|
||||
mocker.patch(
|
||||
"vllm_omni.engine.async_omni_engine.load_and_resolve_stage_configs",
|
||||
return_value=("dummy.yaml", [fake_diffusion_stage], None),
|
||||
)
|
||||
|
||||
engine = AsyncOmniEngine.__new__(AsyncOmniEngine)
|
||||
|
||||
_, stage_configs = engine._resolve_stage_configs(
|
||||
"dummy-model",
|
||||
{
|
||||
"deploy_config": "dummy.yaml",
|
||||
"quantization_config": {"method": "bitsandbytes"},
|
||||
},
|
||||
trust_remote_code=False,
|
||||
)
|
||||
|
||||
assert stage_configs[0].engine_args.quantization_config == {"method": "bitsandbytes"}
|
||||
@@ -1,3 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Unit tests for AR EngineCore vs diffusion worker pause/sleep routing."""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -7,6 +10,8 @@ from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, call
|
||||
|
||||
import pytest
|
||||
from vllm.renderers import BaseRenderer
|
||||
from vllm.v1.engine.input_processor import InputProcessor
|
||||
|
||||
from vllm_omni.diffusion.data import CuMemTag, OmniACK
|
||||
from vllm_omni.entrypoints.async_omni import AsyncOmni
|
||||
@@ -37,6 +42,22 @@ def _make_omni(*, stage_types: list[str]) -> AsyncOmni:
|
||||
return omni
|
||||
|
||||
|
||||
@pytest.mark.cpu
|
||||
def test_reset_mm_cache_routes_through_renderer(mocker):
|
||||
async def run() -> None:
|
||||
omni = object.__new__(AsyncOmni)
|
||||
renderer = mocker.create_autospec(BaseRenderer, instance=True)
|
||||
input_processor = mocker.create_autospec(InputProcessor, instance=True)
|
||||
input_processor.renderer = renderer
|
||||
omni.input_processor = input_processor
|
||||
|
||||
await omni.reset_mm_cache()
|
||||
|
||||
renderer.clear_mm_cache_async.assert_awaited_once_with()
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
@pytest.mark.cpu
|
||||
def test_split_stage_ids_by_type():
|
||||
omni = _make_omni(stage_types=["llm", "diffusion", "llm"])
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm_omni.config.omni_config import (
|
||||
_NON_STAGE_ENGINE_CLI_FIELDS,
|
||||
VllmOmniConfig,
|
||||
_global_stage_cli_fields,
|
||||
)
|
||||
from vllm_omni.config.pipeline_registry import OMNI_PIPELINES
|
||||
from vllm_omni.config.resolver import OmniConfigResolution
|
||||
from vllm_omni.config.stage_config import PipelineConfig
|
||||
from vllm_omni.engine.async_omni_engine import AsyncOmniEngine
|
||||
from vllm_omni.entrypoints.cli.serve import run_headless
|
||||
from vllm_omni.utils.tracking_parser import TrackingNamespace
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
def test_disable_log_stats_is_not_a_stage_config_field() -> None:
|
||||
assert "disable_log_stats" in _NON_STAGE_ENGINE_CLI_FIELDS
|
||||
assert "disable_log_stats" not in _global_stage_cli_fields()
|
||||
|
||||
|
||||
def test_structured_tts_config_accepts_disable_log_stats() -> None:
|
||||
pipeline = OMNI_PIPELINES["qwen3_tts"]
|
||||
assert isinstance(pipeline, PipelineConfig)
|
||||
|
||||
config = VllmOmniConfig.from_pipeline_config(
|
||||
pipeline,
|
||||
cli_overrides={"disable_log_stats": True},
|
||||
)
|
||||
|
||||
assert len(config.stage_configs) == len(pipeline.stages)
|
||||
|
||||
|
||||
def test_async_engine_consumes_disable_log_stats_before_resolution(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
captured: dict[str, Any] = {}
|
||||
|
||||
def fake_resolve(model: str, kwargs: dict[str, Any], **unused: Any) -> OmniConfigResolution:
|
||||
captured["model"] = model
|
||||
captured["kwargs"] = dict(kwargs)
|
||||
return OmniConfigResolution(
|
||||
config_path="config.yaml",
|
||||
stage_configs=(),
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
"vllm_omni.engine.async_omni_engine.load_and_resolve_stage_configs",
|
||||
fake_resolve,
|
||||
)
|
||||
engine = SimpleNamespace(_apply_strategy_lb_policy=lambda *args, **kwargs: None)
|
||||
|
||||
config_path, stage_configs = AsyncOmniEngine._resolve_stage_configs(
|
||||
engine,
|
||||
"fake-model",
|
||||
{"disable_log_stats": True},
|
||||
trust_remote_code=False,
|
||||
)
|
||||
|
||||
assert captured["model"] == "fake-model"
|
||||
assert "disable_log_stats" not in captured["kwargs"]
|
||||
assert config_path == "config.yaml"
|
||||
assert stage_configs == []
|
||||
|
||||
|
||||
def test_headless_consumes_disable_log_stats_before_resolution(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
captured: dict[str, Any] = {}
|
||||
|
||||
def fake_resolve(*args: Any, **kwargs: Any) -> OmniConfigResolution:
|
||||
captured.update(kwargs)
|
||||
return OmniConfigResolution(
|
||||
config_path=None,
|
||||
stage_configs=(SimpleNamespace(stage_id=99),),
|
||||
)
|
||||
|
||||
monkeypatch.setattr("vllm_omni.config.resolver.resolve_omni_config", fake_resolve)
|
||||
namespace = argparse.Namespace(
|
||||
model="fake-model",
|
||||
stage_id=0,
|
||||
omni_master_address="127.0.0.1",
|
||||
omni_master_port=26000,
|
||||
worker_backend="multi_process",
|
||||
omni_replica_address=None,
|
||||
omni_dp_size_local=1,
|
||||
disable_log_stats=True,
|
||||
log_stats=False,
|
||||
)
|
||||
args = TrackingNamespace(
|
||||
unfiltered_ns=namespace,
|
||||
explicit_keys=frozenset({"disable_log_stats"}),
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="No stage config found"):
|
||||
run_headless(args)
|
||||
|
||||
assert "disable_log_stats" not in captured["cli_overrides"]
|
||||
@@ -74,7 +74,7 @@ async def test_openai_handler_passes_current_session_fence_for_runtime_controls(
|
||||
handler = OmniDuplexSessionHandler(chat_service=FakeChatService(engine))
|
||||
session = DuplexSession(
|
||||
session_id="sid",
|
||||
config=DuplexSessionConfig(),
|
||||
config=DuplexSessionConfig(extra_body={"native_duplex": True}),
|
||||
epoch=1,
|
||||
turn_id=2,
|
||||
)
|
||||
@@ -92,7 +92,7 @@ async def test_openai_handler_passes_current_session_fence_for_runtime_controls(
|
||||
async def test_runtime_signal_uses_fence_captured_before_session_turn_advances():
|
||||
engine = FenceRecordingEngine()
|
||||
handler = OmniDuplexSessionHandler(chat_service=FakeChatService(engine))
|
||||
session = DuplexSession(session_id="sid", config=DuplexSessionConfig())
|
||||
session = DuplexSession(session_id="sid", config=DuplexSessionConfig(extra_body={"native_duplex": True}))
|
||||
captured_fence = DuplexFence("sid", epoch=0, turn_id=0)
|
||||
session.turn_id = 1
|
||||
|
||||
@@ -111,7 +111,7 @@ async def test_openai_handler_forwards_cancel_fence_through_async_omni_facade():
|
||||
app = object.__new__(AsyncOmni)
|
||||
app.engine = engine
|
||||
handler = OmniDuplexSessionHandler(chat_service=FakeChatService(app))
|
||||
session = DuplexSession(session_id="sid-cancel", config=DuplexSessionConfig())
|
||||
session = DuplexSession(session_id="sid-cancel", config=DuplexSessionConfig(extra_body={"native_duplex": True}))
|
||||
cancelled_fence = DuplexFence("sid-cancel", epoch=2, turn_id=3)
|
||||
next_fence = DuplexFence("sid-cancel", epoch=3, turn_id=3)
|
||||
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Unit tests for PD (Prefill-Decode) disaggregation in the Omni orchestrator.
|
||||
|
||||
Tests the PD detection, validation, config parsing, sampling param
|
||||
@@ -74,7 +77,7 @@ class _FakeStageConfig:
|
||||
|
||||
class _FakeQueue:
|
||||
def __init__(self, maxsize=0):
|
||||
self._queue = Queue(maxsize=maxsize)
|
||||
self._queue: Queue[Any] = Queue(maxsize=maxsize)
|
||||
|
||||
def put(self, item):
|
||||
self._queue.put(item)
|
||||
@@ -343,7 +346,7 @@ def mock_get_config(monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
"vllm.transformers_utils.config.get_config", lambda model, **kwargs: fake_hf_config, raising=False
|
||||
)
|
||||
monkeypatch.setattr("vllm_omni.entrypoints.utils.get_config", lambda model, **kwargs: fake_hf_config, raising=False)
|
||||
monkeypatch.setattr("vllm_omni.config.config_factory.get_config", lambda model, **kwargs: fake_hf_config)
|
||||
|
||||
def _mock_cached_file(path_or_repo_id, *args, **kwargs):
|
||||
import os
|
||||
|
||||
@@ -1,28 +1,16 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm_omni.config.resolver import resolve_omni_config
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.stage_diffusion_proc import StageDiffusionProc
|
||||
from vllm_omni.entrypoints.utils import load_stage_configs_from_model, resolve_model_config_path
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
def test_dreamzero_vla_resolves_to_dreamzero_config(monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
"vllm_omni.entrypoints.utils.get_config",
|
||||
lambda _model, trust_remote_code=True: type("Cfg", (), {"model_type": "vla"})(),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"vllm_omni.entrypoints.utils._looks_like_dreamzero",
|
||||
lambda _model: True,
|
||||
)
|
||||
result = resolve_model_config_path("GEAR-Dreams/DreamZero-DROID")
|
||||
|
||||
assert result is not None
|
||||
assert result.endswith("vllm_omni/deploy/dreamzero.yaml")
|
||||
|
||||
|
||||
def test_dreamzero_config_sets_model_class_and_policy_config(monkeypatch):
|
||||
def test_dreamzero_resolves_through_registry_with_model_defaults(monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
"vllm_omni.config.config_factory.StageConfigFactory._try_infer_model_type",
|
||||
classmethod(lambda _cls, model, trust_remote_code=True: "vla"),
|
||||
@@ -36,12 +24,18 @@ def test_dreamzero_config_sets_model_class_and_policy_config(monkeypatch):
|
||||
lambda _model: True,
|
||||
)
|
||||
|
||||
stage_configs, _ = load_stage_configs_from_model(
|
||||
resolved = resolve_omni_config(
|
||||
"GEAR-Dreams/DreamZero-DROID",
|
||||
trust_remote_code=False,
|
||||
deploy_config_path=None,
|
||||
cli_overrides=None,
|
||||
stage_overrides=None,
|
||||
strategy_config_path=None,
|
||||
)
|
||||
engine_args = stage_configs[0].engine_args
|
||||
engine_args = resolved.stage_configs[0].engine_args
|
||||
|
||||
assert resolved.config_path is not None
|
||||
assert resolved.config_path.endswith("vllm_omni/deploy/dreamzero.yaml")
|
||||
assert engine_args.model_class_name == "DreamZeroPipeline"
|
||||
assert engine_args.model_config.policy_server_config.action_space == "joint_position"
|
||||
|
||||
|
||||
@@ -11,13 +11,22 @@ from types import SimpleNamespace
|
||||
import pytest
|
||||
from pytest_mock import MockerFixture
|
||||
|
||||
from vllm_omni.entrypoints.cli.serve import OmniServeCommand, run_headless
|
||||
from vllm_omni.config.resolver import OmniConfigResolution
|
||||
from vllm_omni.entrypoints.cli.serve import (
|
||||
OmniServeCommand,
|
||||
_parse_stage_overrides,
|
||||
run_headless,
|
||||
)
|
||||
from vllm_omni.entrypoints.utils import parse_stage_overrides
|
||||
from vllm_omni.utils.tracking_parser import TrackingArgumentParser, TrackingNamespace
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
def _resolved(*stages: SimpleNamespace) -> OmniConfigResolution:
|
||||
return OmniConfigResolution(config_path="/fake/stages.yaml", stage_configs=tuple(stages))
|
||||
|
||||
|
||||
def test_serve_parser_accepts_no_async_chunk_and_marks_it_explicit() -> None:
|
||||
"""``--no-async-chunk`` should parse to ``async_chunk=False`` and mark the
|
||||
shared deploy-level dest as explicitly provided by the user."""
|
||||
@@ -110,7 +119,7 @@ def test_serve_parser_accepts_diffusion_quantization_config() -> None:
|
||||
assert args.get_explicit_kwargs_dict()["diffusion_quantization_config"] == expected
|
||||
|
||||
|
||||
def _make_headless_args(**kwargs) -> TrackingNamespace:
|
||||
def _make_headless_args(*, explicit_keys: frozenset[str] | None = None, **kwargs) -> TrackingNamespace:
|
||||
defaults = {
|
||||
"model": "fake-model",
|
||||
"stage_id": 0,
|
||||
@@ -130,7 +139,7 @@ def _make_headless_args(**kwargs) -> TrackingNamespace:
|
||||
ns = argparse.Namespace(**ns_kwargs)
|
||||
return TrackingNamespace(
|
||||
unfiltered_ns=ns,
|
||||
explicit_keys=frozenset(ns.__dict__.keys()),
|
||||
explicit_keys=frozenset(ns.__dict__.keys()) if explicit_keys is None else explicit_keys,
|
||||
)
|
||||
|
||||
|
||||
@@ -159,41 +168,49 @@ def test_run_headless_rejects_non_multiprocess_worker_backend() -> None:
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# --stage-overrides parsing parity (headless vs standard path)
|
||||
# --stage-overrides parsing at the serving boundary
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_parse_stage_overrides_valid_json() -> None:
|
||||
"""A valid JSON string is parsed into the nested per-stage dict."""
|
||||
parsed = parse_stage_overrides('{"0": {"devices": "0,1"}, "1": {"devices": "2"}}')
|
||||
parsed = _parse_stage_overrides('{"0": {"devices": "0,1"}, "1": {"devices": "2"}}')
|
||||
assert parsed == {"0": {"devices": "0,1"}, "1": {"devices": "2"}}
|
||||
|
||||
|
||||
def test_parse_stage_overrides_none_and_empty_return_none() -> None:
|
||||
"""No overrides (None / empty string) resolve to ``None``."""
|
||||
assert parse_stage_overrides(None) is None
|
||||
assert parse_stage_overrides("") is None
|
||||
def test_serve_parser_parses_stage_overrides_before_resolution() -> None:
|
||||
parser = TrackingArgumentParser()
|
||||
subparsers = parser.add_subparsers(dest="subcommand")
|
||||
OmniServeCommand().subparser_init(subparsers)
|
||||
|
||||
args = parser.parse_args(
|
||||
[
|
||||
"serve",
|
||||
"fake-model",
|
||||
"--omni",
|
||||
"--stage-overrides",
|
||||
'{"0": {"devices": "0,1"}}',
|
||||
]
|
||||
)
|
||||
|
||||
assert args.stage_overrides == {"0": {"devices": "0,1"}}
|
||||
|
||||
|
||||
def test_parse_stage_overrides_empty_dict_returns_none() -> None:
|
||||
"""An empty dict is falsy and must resolve to ``None``, locking in parity
|
||||
with the original standard-path ``if stage_overrides_json:`` falsy check."""
|
||||
assert parse_stage_overrides({}) is None
|
||||
def test_serve_parser_accepts_empty_stage_overrides_as_noop() -> None:
|
||||
parser = TrackingArgumentParser()
|
||||
subparsers = parser.add_subparsers(dest="subcommand")
|
||||
OmniServeCommand().subparser_init(subparsers)
|
||||
|
||||
args = parser.parse_args(["serve", "fake-model", "--omni", "--stage-overrides", "{}"])
|
||||
|
||||
def test_parse_stage_overrides_passes_through_non_str() -> None:
|
||||
"""An already-parsed mapping is returned unchanged (identity)."""
|
||||
overrides = {"0": {"devices": "0"}}
|
||||
assert parse_stage_overrides(overrides) is overrides
|
||||
assert args.stage_overrides == {}
|
||||
|
||||
|
||||
def test_parse_stage_overrides_invalid_json_raises() -> None:
|
||||
"""Invalid JSON raises ValueError whose message matches the standard path
|
||||
verbatim: the ``--stage-overrides is not valid JSON:`` prefix AND the
|
||||
``Got: <repr>`` suffix echoing the raw input."""
|
||||
"""Invalid JSON fails at the serving boundary with the raw input."""
|
||||
bad = "{not valid json}"
|
||||
with pytest.raises(ValueError) as excinfo:
|
||||
parse_stage_overrides(bad)
|
||||
with pytest.raises(argparse.ArgumentTypeError) as excinfo:
|
||||
_parse_stage_overrides(bad)
|
||||
message = str(excinfo.value)
|
||||
assert message.startswith("--stage-overrides is not valid JSON:")
|
||||
assert f"Got: {bad!r}" in message
|
||||
@@ -271,11 +288,8 @@ def test_parse_stage_overrides_accepts_empty_inner_dict() -> None:
|
||||
assert parsed == {"0": {}, "1": {}}
|
||||
|
||||
|
||||
def test_run_headless_parses_and_forwards_stage_overrides(mocker: MockerFixture) -> None:
|
||||
"""Regression: the headless path must parse ``--stage-overrides`` (a JSON
|
||||
string) and forward the parsed dict to ``load_and_resolve_stage_configs``,
|
||||
mirroring the standard engine path. Previously it was dropped entirely,
|
||||
silently producing a different per-stage device layout."""
|
||||
def test_run_headless_forwards_parsed_stage_overrides(mocker: MockerFixture) -> None:
|
||||
"""The headless resolver receives the mapping parsed by argparse."""
|
||||
captured: dict = {}
|
||||
|
||||
def _fake_resolve(*args, **kwargs):
|
||||
@@ -283,10 +297,10 @@ def test_run_headless_parses_and_forwards_stage_overrides(mocker: MockerFixture)
|
||||
captured.update(kwargs)
|
||||
# Return a stage that does NOT match stage_id=0 so run_headless stops
|
||||
# right after the resolver call (we only care about how it was called).
|
||||
return ("/fake/stages.yaml", [SimpleNamespace(stage_id=99)], None)
|
||||
return _resolved(SimpleNamespace(stage_id=99))
|
||||
|
||||
mocker.patch(
|
||||
"vllm_omni.entrypoints.utils.load_and_resolve_stage_configs",
|
||||
"vllm_omni.config.resolver.resolve_omni_config",
|
||||
side_effect=_fake_resolve,
|
||||
)
|
||||
|
||||
@@ -294,28 +308,22 @@ def test_run_headless_parses_and_forwards_stage_overrides(mocker: MockerFixture)
|
||||
stage_id=0,
|
||||
deploy_config="/tmp/deploy.yaml",
|
||||
strategy_config="/tmp/strategy.yaml",
|
||||
stage_overrides='{"0": {"devices": "0,1"}, "1": {"devices": "2"}}',
|
||||
stage_overrides={"0": {"devices": "0,1"}, "1": {"devices": "2"}},
|
||||
)
|
||||
with pytest.raises(ValueError, match="No stage config found for stage_id=0"):
|
||||
run_headless(args)
|
||||
|
||||
assert len(captured["args"]) == 2
|
||||
assert captured["args"] == ("fake-model",)
|
||||
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"
|
||||
|
||||
|
||||
def test_run_headless_invalid_stage_overrides_raises(mocker: MockerFixture) -> None:
|
||||
"""Invalid ``--stage-overrides`` JSON in headless mode fails fast with the
|
||||
shared ValueError instead of being silently ignored."""
|
||||
mocker.patch(
|
||||
"vllm_omni.entrypoints.utils.load_and_resolve_stage_configs",
|
||||
return_value=("/fake/stages.yaml", [SimpleNamespace(stage_id=0)], None),
|
||||
)
|
||||
|
||||
args = _make_headless_args(stage_id=0, stage_overrides="{not valid json}")
|
||||
with pytest.raises(ValueError, match="--stage-overrides is not valid JSON"):
|
||||
run_headless(args)
|
||||
def test_parse_stage_overrides_rejects_non_mapping_values() -> None:
|
||||
with pytest.raises(argparse.ArgumentTypeError, match="JSON object"):
|
||||
_parse_stage_overrides('["not", "a", "mapping"]')
|
||||
with pytest.raises(argparse.ArgumentTypeError, match="must be an object"):
|
||||
_parse_stage_overrides('{"0": "not a mapping"}')
|
||||
|
||||
|
||||
def test_run_headless_raises_when_stage_id_not_in_configs(mocker: MockerFixture) -> None:
|
||||
@@ -323,8 +331,8 @@ def test_run_headless_raises_when_stage_id_not_in_configs(mocker: MockerFixture)
|
||||
fails fast when the launcher's --stage-id doesn't match any entry."""
|
||||
other_stage = SimpleNamespace(stage_id=99)
|
||||
mocker.patch(
|
||||
"vllm_omni.entrypoints.utils.load_and_resolve_stage_configs",
|
||||
return_value=("/fake/stages.yaml", [other_stage], None),
|
||||
"vllm_omni.config.resolver.resolve_omni_config",
|
||||
return_value=_resolved(other_stage),
|
||||
)
|
||||
|
||||
args = _make_headless_args(stage_id=0)
|
||||
@@ -372,8 +380,8 @@ def test_run_headless_llm_registers_with_auto_assigned_replica_id(mocker: Mocker
|
||||
engine_manager = mocker.Mock()
|
||||
|
||||
mocker.patch(
|
||||
"vllm_omni.entrypoints.utils.load_and_resolve_stage_configs",
|
||||
return_value=("/fake/stages.yaml", [stage_cfg], None),
|
||||
"vllm_omni.config.resolver.resolve_omni_config",
|
||||
return_value=_resolved(stage_cfg),
|
||||
)
|
||||
mocker.patch("vllm_omni.engine.stage_init_utils.prepare_engine_environment")
|
||||
mocker.patch("vllm_omni.engine.stage_init_utils.load_omni_transfer_config_for_model", return_value=None)
|
||||
@@ -452,8 +460,8 @@ def test_run_headless_llm_launches_one_manager_per_omni_dp_size_local(mocker: Mo
|
||||
manager_b = mocker.Mock()
|
||||
|
||||
mocker.patch(
|
||||
"vllm_omni.entrypoints.utils.load_and_resolve_stage_configs",
|
||||
return_value=("/fake/stages.yaml", [stage_cfg], None),
|
||||
"vllm_omni.config.resolver.resolve_omni_config",
|
||||
return_value=_resolved(stage_cfg),
|
||||
)
|
||||
mocker.patch("vllm_omni.engine.stage_init_utils.prepare_engine_environment")
|
||||
mocker.patch("vllm_omni.engine.stage_init_utils.load_omni_transfer_config_for_model", return_value=None)
|
||||
@@ -511,8 +519,8 @@ def test_run_headless_diffusion_registers_and_spawns_proc(mocker: MockerFixture)
|
||||
proc.is_alive.return_value = False
|
||||
|
||||
mocker.patch(
|
||||
"vllm_omni.entrypoints.utils.load_and_resolve_stage_configs",
|
||||
return_value=("/fake/stages.yaml", [stage_cfg], None),
|
||||
"vllm_omni.config.resolver.resolve_omni_config",
|
||||
return_value=_resolved(stage_cfg),
|
||||
)
|
||||
mocker.patch("vllm_omni.engine.stage_init_utils.prepare_engine_environment")
|
||||
mocker.patch("vllm_omni.engine.stage_init_utils.load_omni_transfer_config_for_model", return_value=None)
|
||||
@@ -591,8 +599,8 @@ def test_run_headless_diffusion_raises_on_nonzero_proc_exit(mocker: MockerFixtur
|
||||
proc.is_alive.return_value = False
|
||||
|
||||
mocker.patch(
|
||||
"vllm_omni.entrypoints.utils.load_and_resolve_stage_configs",
|
||||
return_value=("/fake/stages.yaml", [stage_cfg], None),
|
||||
"vllm_omni.config.resolver.resolve_omni_config",
|
||||
return_value=_resolved(stage_cfg),
|
||||
)
|
||||
mocker.patch("vllm_omni.engine.stage_init_utils.prepare_engine_environment")
|
||||
mocker.patch("vllm_omni.engine.stage_init_utils.load_omni_transfer_config_for_model", return_value=None)
|
||||
|
||||
+188
-248
@@ -4,10 +4,8 @@
|
||||
"""Unit tests for vllm_omni.entrypoints.utils module."""
|
||||
|
||||
import logging
|
||||
import os
|
||||
from collections import Counter
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
@@ -15,25 +13,22 @@ import torch
|
||||
from pytest_mock import MockerFixture
|
||||
from vllm.sampling_params import RequestOutputKind, SamplingParams
|
||||
|
||||
from vllm_omni.config.pipeline_registry import OMNI_PIPELINES
|
||||
from vllm_omni.config.resolver import (
|
||||
OmniConfigResolution,
|
||||
_convert_dataclasses_to_dict,
|
||||
_filter_dict_like_object,
|
||||
resolve_omni_config,
|
||||
)
|
||||
from vllm_omni.config.stage_config import PipelineConfig
|
||||
from vllm_omni.config.yaml_util import create_config
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig
|
||||
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 (
|
||||
get_stage_connector_spec,
|
||||
load_omni_transfer_config_for_model,
|
||||
)
|
||||
from vllm_omni.entrypoints.utils import (
|
||||
_convert_dataclasses_to_dict,
|
||||
_filter_dict_like_object,
|
||||
_try_resolve_omni_model_type,
|
||||
coerce_param_message_types,
|
||||
filter_dataclass_kwargs,
|
||||
filter_stages,
|
||||
load_and_resolve_stage_configs,
|
||||
load_stage_configs_from_model,
|
||||
resolve_model_config_path,
|
||||
)
|
||||
from vllm_omni.model_executor.models.qwen3_omni.pipeline import QWEN3_OMNI_PIPELINE
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
@@ -173,7 +168,7 @@ class TestFilterDictLikeObject:
|
||||
"normal": "value",
|
||||
}
|
||||
|
||||
mocker.patch("vllm_omni.entrypoints.utils.logger")
|
||||
mocker.patch("vllm_omni.config.resolver.logger")
|
||||
result = _filter_dict_like_object(input_dict)
|
||||
|
||||
# Normal key should exist
|
||||
@@ -195,7 +190,7 @@ class TestFilterDictLikeObject:
|
||||
"normal": "value",
|
||||
}
|
||||
|
||||
mocker.patch("vllm_omni.entrypoints.utils.logger")
|
||||
mocker.patch("vllm_omni.config.resolver.logger")
|
||||
result = _filter_dict_like_object(input_dict)
|
||||
|
||||
# Callable should be filtered
|
||||
@@ -215,7 +210,7 @@ class TestConvertDataclassesToDict:
|
||||
"callable": lambda x: x,
|
||||
}
|
||||
|
||||
mocker.patch("vllm_omni.entrypoints.utils.logger")
|
||||
mocker.patch("vllm_omni.config.resolver.logger")
|
||||
result = _convert_dataclasses_to_dict(input_dict)
|
||||
|
||||
# Callable should be filtered out by _filter_dict_like_object
|
||||
@@ -300,254 +295,199 @@ class TestFilterDataclassKwargs:
|
||||
assert "extra_param" not in result["cache_config"]
|
||||
|
||||
|
||||
class TestResolveModelConfigPath:
|
||||
"""Test suite for resolve_model_config_path function with diffusers format models."""
|
||||
|
||||
def test_glm_image_diffusers_format_resolution(self, mocker: MockerFixture):
|
||||
"""Test GlmImagePipeline diffusers class resolves to glm_image config."""
|
||||
mocker.patch(
|
||||
"vllm_omni.entrypoints.utils.file_or_path_exists",
|
||||
return_value=True,
|
||||
)
|
||||
mocker.patch(
|
||||
"vllm_omni.entrypoints.utils._try_get_class_name_from_diffusers_config",
|
||||
return_value="GlmImagePipeline",
|
||||
)
|
||||
mocker.patch(
|
||||
"vllm_omni.entrypoints.utils.current_omni_platform.get_default_stage_config_path",
|
||||
return_value="vllm_omni/model_executor/stage_configs",
|
||||
)
|
||||
|
||||
original_exists = os.path.exists
|
||||
|
||||
def mock_exists(path):
|
||||
if "glm_image.yaml" in str(path):
|
||||
return True
|
||||
return original_exists(path)
|
||||
|
||||
mocker.patch("os.path.exists", side_effect=mock_exists)
|
||||
|
||||
result = resolve_model_config_path("zai-org/GLM-Image")
|
||||
|
||||
assert result is not None
|
||||
assert "glm_image.yaml" in result
|
||||
|
||||
def test_uses_registry_default_deploy_when_hf_model_type_differs(
|
||||
self,
|
||||
mocker: MockerFixture,
|
||||
tmp_path,
|
||||
):
|
||||
from vllm_omni.config.stage_config import _DEPLOY_DIR as _REAL_DEPLOY_DIR
|
||||
from vllm_omni.entrypoints import utils as utils_mod
|
||||
|
||||
hf_config = SimpleNamespace(
|
||||
model_type="minicpmo",
|
||||
architectures=["MiniCPMO"],
|
||||
version="4.5",
|
||||
)
|
||||
model = "local/minicpmo-registry-default-test"
|
||||
mocker.patch(
|
||||
"vllm_omni.entrypoints.utils.get_config",
|
||||
return_value=hf_config,
|
||||
)
|
||||
mocker.patch(
|
||||
"vllm_omni.config.config_factory.get_config",
|
||||
return_value=hf_config,
|
||||
)
|
||||
# A bare deploy/<hf_model_type>.yaml must not win over the registered
|
||||
# pipeline default when HF model_type is not an OMNI_PIPELINES key.
|
||||
(tmp_path / "minicpmo.yaml").write_text("stages: []\n", encoding="utf-8")
|
||||
(tmp_path / "minicpmo_4_5.yaml").write_bytes((_REAL_DEPLOY_DIR / "minicpmo_4_5.yaml").read_bytes())
|
||||
mocker.patch.object(utils_mod, "_DEPLOY_DIR", tmp_path)
|
||||
|
||||
result = resolve_model_config_path(model)
|
||||
|
||||
assert result is not None
|
||||
assert Path(result).as_posix().endswith("minicpmo_4_5.yaml")
|
||||
assert Path(result).name == "minicpmo_4_5.yaml"
|
||||
transfer_config = load_omni_transfer_config_for_model(model, result)
|
||||
assert transfer_config is not None
|
||||
|
||||
sender = get_stage_connector_spec(
|
||||
omni_transfer_config=transfer_config,
|
||||
stage_id=1,
|
||||
async_chunk=True,
|
||||
)
|
||||
receiver = get_stage_connector_spec(
|
||||
omni_transfer_config=transfer_config,
|
||||
stage_id=2,
|
||||
async_chunk=True,
|
||||
)
|
||||
assert sender["extra"]["role"] == "sender"
|
||||
assert receiver["extra"]["role"] == "receiver"
|
||||
assert sender["extra"]["connector_get_sleep_s"] == 0.01
|
||||
assert sender["extra"]["connector_get_max_wait_first_chunk"] == 3000
|
||||
assert sender["extra"]["connector_get_max_wait"] == 300
|
||||
|
||||
def test_object_storage_uri_resolves_via_materialized_configs(
|
||||
self,
|
||||
mocker: MockerFixture,
|
||||
tmp_path,
|
||||
):
|
||||
"""An object-storage URI must not reach HF helpers; resolution reads the
|
||||
locally materialized config files instead."""
|
||||
hf_config = SimpleNamespace(
|
||||
model_type="qwen3_omni_moe",
|
||||
architectures=["Qwen3OmniMoeForConditionalGeneration"],
|
||||
)
|
||||
uri = "s3://qwen3-tts-models/Qwen3-Omni-30B-A3B-Instruct"
|
||||
materialize = mocker.patch(
|
||||
"vllm_omni.entrypoints.utils._materialize_object_storage_configs",
|
||||
return_value=str(tmp_path),
|
||||
)
|
||||
get_config = mocker.patch(
|
||||
"vllm_omni.entrypoints.utils.get_config",
|
||||
return_value=hf_config,
|
||||
)
|
||||
|
||||
result = resolve_model_config_path(uri)
|
||||
|
||||
materialize.assert_called_once_with(uri)
|
||||
get_config.assert_called_once()
|
||||
assert get_config.call_args[0][0] == str(tmp_path)
|
||||
assert result is not None
|
||||
assert Path(result).as_posix().endswith("qwen3_omni_moe.yaml")
|
||||
|
||||
|
||||
class TestTryResolveOmniModelType:
|
||||
"""Name matching must only scan the last path component."""
|
||||
|
||||
def test_uri_bucket_name_cannot_hijack_pipeline(self):
|
||||
# "qwen3-tts-models" normalizes to "qwen3ttsmodels", which contains the
|
||||
# registered key "qwen3tts" — only the basename may participate, so a
|
||||
# misleadingly named bucket selects nothing.
|
||||
assert _try_resolve_omni_model_type("s3://qwen3-tts-models/plain-checkpoint") is None
|
||||
|
||||
def test_basename_still_matches_pipeline(self):
|
||||
assert _try_resolve_omni_model_type("gs://any-bucket/Fun-CosyVoice3-0.5B-2512") == "cosyvoice3"
|
||||
|
||||
|
||||
class TestLoadAndResolveStageConfigs:
|
||||
def test_load_and_resolve_with_kwargs(self, mocker: MockerFixture):
|
||||
"""Ensure that kwargs survive default stage creation."""
|
||||
engine_backend = "vllm_omni.experimental.ar_diffusion.engine.ARDiffusionEngine"
|
||||
kwargs = {"dtype": torch.float32, "engine_backend": engine_backend}
|
||||
kwargs["revision"] = "pinned-revision"
|
||||
mocker.patch("vllm_omni.entrypoints.utils.resolve_model_config_path", return_value=None)
|
||||
mocker.patch("vllm_omni.entrypoints.utils.load_stage_configs_from_model", return_value=([], None))
|
||||
|
||||
config_path, stage_configs, _ = load_and_resolve_stage_configs(
|
||||
model="black-forest-labs/FLUX.2-klein-4B",
|
||||
kwargs=kwargs,
|
||||
trust_remote_code=False,
|
||||
default_stage_cfg_factory=lambda: AsyncOmniEngine._create_default_diffusion_stage_cfg(kwargs),
|
||||
)
|
||||
assert config_path is None
|
||||
assert len(stage_configs) == 1
|
||||
assert "dtype" in stage_configs[0]["engine_args"]
|
||||
assert stage_configs[0]["engine_args"]["engine_backend"] == engine_backend
|
||||
assert stage_configs[0]["engine_args"]["revision"] == "pinned-revision"
|
||||
|
||||
def test_deploy_config_preserves_cli_overrides_and_replicas(self, tmp_path, mocker: MockerFixture):
|
||||
deploy_path = tmp_path / "qwen3_multi.yaml"
|
||||
class TestResolveOmniConfig:
|
||||
def test_bare_deploy_name_returns_packaged_resolved_path(self, tmp_path, mocker: MockerFixture):
|
||||
deploy_name = "qwen3_omni_moe.yaml"
|
||||
deploy_path = tmp_path / deploy_name
|
||||
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',
|
||||
"duplex_session:\n server_vad_model_path: /models/silero_vad.onnx\nstages: []\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
returned_stage_configs = [
|
||||
create_config({"stage_id": 0, "runtime": {"devices": "0"}, "engine_args": {"model": "dummy"}}),
|
||||
create_config(
|
||||
{
|
||||
"stage_id": 1,
|
||||
"runtime": {"devices": "1,2,3", "num_replicas": 3},
|
||||
"engine_args": {"model": "dummy"},
|
||||
}
|
||||
),
|
||||
]
|
||||
load_stage_configs = mocker.patch(
|
||||
"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",
|
||||
kwargs=cli_overrides,
|
||||
trust_remote_code=True,
|
||||
deploy_config_path=str(deploy_path),
|
||||
mocker.patch("vllm_omni.config.config_factory._DEPLOY_DIR", tmp_path)
|
||||
mocker.patch("vllm_omni.config.omni_config._DEPLOY_DIR", tmp_path)
|
||||
mocker.patch(
|
||||
"vllm_omni.config.config_factory.StageConfigFactory.get_pipeline_config",
|
||||
return_value=QWEN3_OMNI_PIPELINE,
|
||||
)
|
||||
|
||||
load_stage_configs.assert_called_once_with(
|
||||
resolved = resolve_omni_config(
|
||||
"dummy-model",
|
||||
trust_remote_code=True,
|
||||
base_engine_args=cli_overrides,
|
||||
deploy_config_path=str(deploy_path),
|
||||
trust_remote_code=False,
|
||||
deploy_config_path=deploy_name,
|
||||
cli_overrides={},
|
||||
stage_overrides=None,
|
||||
strategy_config_path=None,
|
||||
)
|
||||
assert config_path == str(deploy_path)
|
||||
assert len(stage_configs) == 2
|
||||
assert stage_configs[1].runtime.num_replicas == 3
|
||||
assert stage_configs[1].runtime.devices == "1,2,3"
|
||||
|
||||
def test_filter_stages_selects_mode_stages_without_mutating_stage_config(self, tmp_path):
|
||||
config_path = tmp_path / "deploy.yaml"
|
||||
config_path.write_text(
|
||||
"""modes:
|
||||
- mode: text-to-text
|
||||
stages: [0]
|
||||
- mode: text-to-image
|
||||
stages: [0, 1]
|
||||
""",
|
||||
encoding="utf-8",
|
||||
assert resolved.config_path == str(deploy_path)
|
||||
|
||||
def test_stage_lookup_error_lists_resolved_ids(self):
|
||||
resolved = OmniConfigResolution(
|
||||
config_path=None,
|
||||
stage_configs=(SimpleNamespace(stage_id=1), SimpleNamespace(stage_id=3)),
|
||||
)
|
||||
stages = [
|
||||
create_config(
|
||||
{
|
||||
"stage_id": 0,
|
||||
"runtime": {"requires_multimodal_data": True},
|
||||
"final_output": False,
|
||||
"final_output_type": None,
|
||||
}
|
||||
),
|
||||
create_config(
|
||||
{
|
||||
"stage_id": 1,
|
||||
"runtime": {"requires_multimodal_data": True},
|
||||
"final_output": True,
|
||||
"final_output_type": "image",
|
||||
}
|
||||
),
|
||||
]
|
||||
|
||||
filtered = filter_stages(str(config_path), stages, {"mode": "text-to-text"})
|
||||
with pytest.raises(KeyError, match=r"no stage 2; resolved stages: \[1, 3\]"):
|
||||
resolved.stage_by_id(2)
|
||||
|
||||
assert len(filtered) == 1
|
||||
assert filtered[0].stage_id == 0
|
||||
assert filtered[0].runtime.requires_multimodal_data is True
|
||||
assert filtered[0].final_output is False
|
||||
assert filtered[0].final_output_type is None
|
||||
|
||||
|
||||
class TestLoadStageConfigsFromModel:
|
||||
def test_unresolved_model_does_not_fall_back_to_yaml(self, mocker: MockerFixture, caplog):
|
||||
def test_load_and_resolve_with_kwargs(self, mocker: MockerFixture):
|
||||
"""Ensure that generic diffusion overrides survive resolution."""
|
||||
engine_backend = "vllm_omni.experimental.ar_diffusion.engine.ARDiffusionEngine"
|
||||
mocker.patch(
|
||||
"vllm_omni.entrypoints.utils.StageConfigFactory.create_legacy_stage_configs_from_model",
|
||||
return_value=(None, None),
|
||||
"vllm_omni.config.resolver.StageConfigFactory.create_from_model",
|
||||
return_value=None,
|
||||
)
|
||||
resolve_path = mocker.patch("vllm_omni.entrypoints.utils.resolve_model_config_path")
|
||||
mocker.patch(
|
||||
"vllm_omni.config.resolver._resolve_generic_diffusion_model_class",
|
||||
return_value=(True, "FluxPipeline"),
|
||||
)
|
||||
kwargs = {
|
||||
"dtype": torch.float32,
|
||||
"engine_backend": engine_backend,
|
||||
"revision": "pinned-revision",
|
||||
}
|
||||
resolved = resolve_omni_config(
|
||||
"black-forest-labs/FLUX.2-klein-4B",
|
||||
trust_remote_code=False,
|
||||
deploy_config_path=None,
|
||||
cli_overrides=kwargs,
|
||||
stage_overrides=None,
|
||||
strategy_config_path=None,
|
||||
)
|
||||
assert resolved.config_path is None
|
||||
assert len(resolved.stage_configs) == 1
|
||||
engine_args = resolved.stage_configs[0]["engine_args"]
|
||||
assert "dtype" in engine_args
|
||||
assert engine_args["engine_backend"] == engine_backend
|
||||
assert engine_args["revision"] == "pinned-revision"
|
||||
|
||||
result = load_stage_configs_from_model("unregistered-model", trust_remote_code=False)
|
||||
def test_generic_diffusion_uses_registered_model_metadata(self, mocker: MockerFixture):
|
||||
mocker.patch(
|
||||
"vllm_omni.config.resolver.StageConfigFactory.create_from_model",
|
||||
return_value=None,
|
||||
)
|
||||
resolve_model_class = mocker.patch(
|
||||
"vllm_omni.config.resolver.resolve_model_class_name",
|
||||
return_value="WanImageToVideoPipeline",
|
||||
)
|
||||
mocker.patch(
|
||||
"vllm_omni.config.resolver.DiffusionModelRegistry.get_supported_archs",
|
||||
return_value={"WanImageToVideoPipeline"},
|
||||
)
|
||||
|
||||
assert result == ([], None)
|
||||
resolve_path.assert_not_called()
|
||||
assert "No registered PipelineConfig resolved" in caplog.text
|
||||
assert "deploy_config" in caplog.text
|
||||
resolved = resolve_omni_config(
|
||||
"/models/Wan2.2-I2V",
|
||||
trust_remote_code=False,
|
||||
deploy_config_path=None,
|
||||
cli_overrides={
|
||||
"diffusion_load_format": "diffusers",
|
||||
"revision": "pinned-revision",
|
||||
},
|
||||
stage_overrides=None,
|
||||
strategy_config_path=None,
|
||||
)
|
||||
|
||||
stage = resolved.stage_configs[0]
|
||||
resolve_model_class.assert_called_once_with(
|
||||
"/models/Wan2.2-I2V",
|
||||
"diffusers",
|
||||
"pinned-revision",
|
||||
)
|
||||
assert stage.engine_args.model_class_name == "WanImageToVideoPipeline"
|
||||
assert stage.final_output_type == "video"
|
||||
|
||||
def test_registered_pipeline_uses_structured_metadata_and_preserves_override_trust(self, mocker: MockerFixture):
|
||||
endpoint_restriction = SimpleNamespace(name="chat")
|
||||
structured_config = SimpleNamespace(
|
||||
orchestrator_config=SimpleNamespace(deploy_config_path="/resolved/deploy.yaml"),
|
||||
pipeline_config=SimpleNamespace(endpoint_restrictions=(endpoint_restriction,)),
|
||||
)
|
||||
runtime_stage = create_config(
|
||||
{
|
||||
"stage_id": 1,
|
||||
"runtime": {"devices": "1,2,3", "num_replicas": 3},
|
||||
"engine_args": {"model": "dummy-model"},
|
||||
}
|
||||
)
|
||||
legacy_stage = SimpleNamespace(to_omegaconf=lambda: runtime_stage)
|
||||
create_structured = mocker.patch(
|
||||
"vllm_omni.config.resolver.StageConfigFactory.create_from_model",
|
||||
return_value=structured_config,
|
||||
)
|
||||
create_legacy = mocker.patch(
|
||||
"vllm_omni.config.resolver.StageConfigFactory._resolve_legacy_from_registry",
|
||||
return_value=SimpleNamespace(
|
||||
stage_configs=[legacy_stage],
|
||||
pipeline_config=structured_config.pipeline_config,
|
||||
omni_lb_policy="round_robin",
|
||||
),
|
||||
)
|
||||
strategy_specs = {"stage_1": {"dp": 3}}
|
||||
load_strategy = mocker.patch(
|
||||
"vllm_omni.config.resolver._load_strategy_specs",
|
||||
return_value=strategy_specs,
|
||||
)
|
||||
|
||||
resolved = resolve_omni_config(
|
||||
"dummy-model",
|
||||
trust_remote_code=None,
|
||||
deploy_config_path="deploy.yaml",
|
||||
cli_overrides={"dtype": "bfloat16", "trust_remote_code": True},
|
||||
stage_overrides={"1": {"tensor_parallel_size": 2}},
|
||||
strategy_config_path="strategy.yaml",
|
||||
)
|
||||
|
||||
expected_overrides = {
|
||||
"dtype": "bfloat16",
|
||||
"trust_remote_code": True,
|
||||
"stage_1_tensor_parallel_size": 2,
|
||||
}
|
||||
create_structured.assert_called_once_with(
|
||||
"dummy-model",
|
||||
trust_remote_code=None,
|
||||
cli_overrides=expected_overrides,
|
||||
deploy_config_path="deploy.yaml",
|
||||
)
|
||||
create_legacy.assert_called_once_with(
|
||||
structured_config.pipeline_config,
|
||||
expected_overrides,
|
||||
"/resolved/deploy.yaml",
|
||||
strategy_specs=strategy_specs,
|
||||
)
|
||||
load_strategy.assert_called_once_with("strategy.yaml")
|
||||
assert resolved.config_path == "/resolved/deploy.yaml"
|
||||
assert resolved.pipeline_config is structured_config.pipeline_config
|
||||
assert resolved.omni_lb_policy == "round_robin"
|
||||
assert resolved.endpoint_restrictions == (endpoint_restriction,)
|
||||
assert resolved.stage_configs == (runtime_stage,)
|
||||
|
||||
def test_registered_resolution_exposes_forced_aligner_topology(self, mocker: MockerFixture):
|
||||
pipeline = OMNI_PIPELINES["qwen3_tts"]
|
||||
assert isinstance(pipeline, PipelineConfig)
|
||||
structured_config = SimpleNamespace(
|
||||
orchestrator_config=SimpleNamespace(deploy_config_path=None),
|
||||
pipeline_config=pipeline,
|
||||
)
|
||||
mocker.patch(
|
||||
"vllm_omni.config.resolver.StageConfigFactory.create_from_model",
|
||||
return_value=structured_config,
|
||||
)
|
||||
|
||||
resolved = resolve_omni_config(
|
||||
"Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice",
|
||||
trust_remote_code=False,
|
||||
deploy_config_path=None,
|
||||
cli_overrides={"forced_aligner": "/models/Qwen3-ForcedAligner-0.6B"},
|
||||
stage_overrides=None,
|
||||
strategy_config_path=None,
|
||||
)
|
||||
|
||||
assert resolved.pipeline_config is not None
|
||||
pipeline_stage_ids = [stage.stage_id for stage in resolved.pipeline_config.stages]
|
||||
runtime_stage_ids = [stage.stage_id for stage in resolved.stage_configs]
|
||||
assert pipeline_stage_ids == runtime_stage_ids
|
||||
assert resolved.pipeline_config.stages[-1].model_stage == "forced_aligner"
|
||||
assert len(resolved.pipeline_config.stages) == len(pipeline.stages) + 1
|
||||
|
||||
|
||||
class TestCumulativeStreamingCoercion:
|
||||
|
||||
@@ -29,12 +29,13 @@ def skip_if_gated_repo_inaccessible(
|
||||
and we skip cleanly.
|
||||
"""
|
||||
try:
|
||||
from huggingface_hub import hf_hub_download
|
||||
from huggingface_hub.errors import GatedRepoError, RepositoryNotFoundError
|
||||
|
||||
from vllm_omni.transformers_utils.repo_utils import hf_api
|
||||
except Exception:
|
||||
return
|
||||
try:
|
||||
hf_hub_download(repo_id=repo_id, filename=filename, revision=revision)
|
||||
hf_api().hf_hub_download(repo_id=repo_id, filename=filename, revision=revision)
|
||||
except GatedRepoError as exc:
|
||||
import pytest
|
||||
|
||||
|
||||
@@ -659,7 +659,11 @@ def _compute_pcm_hnr_db(pcm_samples: np.ndarray, sr: int = _PCM_SPEECH_SAMPLE_RA
|
||||
return float(np.mean(hnr_values)) if hnr_values else 0.0
|
||||
|
||||
|
||||
def _assert_pcm_int16_speech_hnr(audio_bytes: bytes, min_hnr_db: float = _MIN_PCM_SPEECH_HNR_DB) -> None:
|
||||
def _assert_pcm_int16_speech_hnr(
|
||||
audio_bytes: bytes,
|
||||
min_hnr_db: float = _MIN_PCM_SPEECH_HNR_DB,
|
||||
sr: int = _PCM_SPEECH_SAMPLE_RATE_HZ,
|
||||
) -> None:
|
||||
"""Validate harmonic-to-noise ratio on raw int16 PCM from /v1/audio/speech.
|
||||
|
||||
min_hnr_db defaults to the global _MIN_PCM_SPEECH_HNR_DB (1.0 dB),
|
||||
@@ -668,12 +672,16 @@ def _assert_pcm_int16_speech_hnr(audio_bytes: bytes, min_hnr_db: float = _MIN_PC
|
||||
intrinsically around -2 dB) can pass a lower per-test threshold via
|
||||
request_config["min_hnr_db"] to keep the catastrophic-failure check
|
||||
while not gating CI on a model-intrinsic property.
|
||||
|
||||
``sr`` must be the stream's real sample rate: the autocorrelation lag window
|
||||
is derived from it, so a wrong rate detunes the 80-400 Hz pitch search and
|
||||
understates HNR for models that do not decode at 24 kHz.
|
||||
"""
|
||||
assert audio_bytes is not None and len(audio_bytes) >= 2, "missing PCM bytes"
|
||||
assert len(audio_bytes) % 2 == 0, "PCM byte length must be aligned to int16"
|
||||
pcm_samples = np.frombuffer(audio_bytes, dtype=np.int16).astype(np.float32) / 32768.0
|
||||
hnr = _compute_pcm_hnr_db(pcm_samples)
|
||||
print(f"PCM speech HNR: {hnr:.2f} dB (threshold: {min_hnr_db} dB)")
|
||||
hnr = _compute_pcm_hnr_db(pcm_samples, sr=sr)
|
||||
print(f"PCM speech HNR: {hnr:.2f} dB (threshold: {min_hnr_db} dB, sr={sr})")
|
||||
assert hnr >= min_hnr_db, (
|
||||
f"Audio distortion detected: HNR={hnr:.2f} dB < {min_hnr_db} dB. "
|
||||
"Voice clone decoder may be losing ref_code speaker context on later chunks."
|
||||
@@ -934,7 +942,15 @@ def assert_audio_speech_response(response: Any, request_config: dict[str, Any],
|
||||
if run_level in {"advanced_model", "full_model"}:
|
||||
if req_fmt == "pcm" and response.audio_bytes:
|
||||
min_hnr_db = float(request_config.get("min_hnr_db", _MIN_PCM_SPEECH_HNR_DB))
|
||||
_assert_pcm_int16_speech_hnr(response.audio_bytes, min_hnr_db=min_hnr_db)
|
||||
# Raw PCM carries no header, so the HNR pitch search has to be told
|
||||
# the rate. Defaulting to 24 kHz for a 44.1 kHz model shifts the
|
||||
# search window to 147-735 Hz and misses the fundamental entirely,
|
||||
# scoring clean speech ~1.9 dB lower than it is.
|
||||
_assert_pcm_int16_speech_hnr(
|
||||
response.audio_bytes,
|
||||
min_hnr_db=min_hnr_db,
|
||||
sr=int(request_config.get("expected_sample_rate") or _PCM_SPEECH_SAMPLE_RATE_HZ),
|
||||
)
|
||||
|
||||
transcript = _resolve_audio_transcript(response, request_config, run_level, speech_api=True)
|
||||
if transcript is not None:
|
||||
|
||||
+128
-3
@@ -12,6 +12,7 @@ import copy
|
||||
import io
|
||||
import json
|
||||
import time
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import asdict, dataclass
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
@@ -152,11 +153,14 @@ class OpenPIWebSocketResponse:
|
||||
action_tensors: list[np.ndarray] | None = None
|
||||
|
||||
|
||||
def build_openpi_droid_observation(*, session_id: str = "gr00t-smoke") -> dict[str, Any]:
|
||||
"""Build a minimal DROID-style observation payload for the OpenPI robot endpoint."""
|
||||
def build_openpi_droid_observation(*, session_id: str = "gr00t-smoke", seed: int | None = None) -> dict[str, Any]:
|
||||
"""Build a minimal DROID-style observation payload for the OpenPI robot endpoint.
|
||||
|
||||
``seed`` pins the policy's sampling noise for this request (see ``docs/serving/openpi_api.md``).
|
||||
"""
|
||||
identity_eef_9d = np.zeros((1, 1, 9), dtype=np.float32)
|
||||
identity_eef_9d[..., 3:] = np.array([1, 0, 0, 0, 1, 0], dtype=np.float32)
|
||||
return {
|
||||
observation: dict[str, Any] = {
|
||||
"session_id": session_id,
|
||||
"video": {
|
||||
"exterior_image_1_left": np.zeros((1, 2, 256, 256, 3), dtype=np.uint8),
|
||||
@@ -169,6 +173,9 @@ def build_openpi_droid_observation(*, session_id: str = "gr00t-smoke") -> dict[s
|
||||
},
|
||||
"language": {"annotation.language.language_instruction": [["pick up the object"]]},
|
||||
}
|
||||
if seed is not None:
|
||||
observation["seed"] = seed
|
||||
return observation
|
||||
|
||||
|
||||
DREAMZERO_DEFAULT_PROMPT = (
|
||||
@@ -1462,6 +1469,7 @@ class OnlineOmniClient:
|
||||
"instructions",
|
||||
"speed",
|
||||
"sample_rate",
|
||||
"extra_params",
|
||||
"stream_format",
|
||||
"x_vector_only_mode",
|
||||
):
|
||||
@@ -2116,6 +2124,123 @@ class OfflineOmniClient:
|
||||
assert_audio_speech_response(result, request_config, run_level="core_model")
|
||||
return result
|
||||
|
||||
def send_tokenized_tts_request(self, request_config: dict[str, Any]) -> OmniResponse:
|
||||
"""Offline TTS for models whose engine prompt is *pre-tokenized*.
|
||||
|
||||
Fish-Speech-style DualAR models (and any model whose prompt embeds codec
|
||||
codes) cannot go through :meth:`send_audio_speech_request`: the prompt is
|
||||
built by the caller as ``prompt_token_ids`` plus per-request
|
||||
``additional_information``, not from ``mm_processor_kwargs``.
|
||||
|
||||
request_config keys:
|
||||
- ``prompt_token_ids``: ``list[int]`` or ``list[list[int]]`` (one entry
|
||||
per request).
|
||||
- ``additional_information``: dict, or list of dicts matching
|
||||
``prompt_token_ids``.
|
||||
- ``expected_sample_rate``: asserted against the reported ``sr``.
|
||||
- ``min_duration_s`` / ``max_duration_s``: bounds on decoded audio.
|
||||
- plus every key ``assert_audio_speech_response`` understands
|
||||
(``response_format``, ``min_audio_bytes``, ``input``, ...).
|
||||
"""
|
||||
token_ids = request_config.get("prompt_token_ids")
|
||||
if not token_ids:
|
||||
raise ValueError("request_config must contain 'prompt_token_ids'")
|
||||
batched_ids = token_ids if isinstance(token_ids[0], (list, tuple)) else [token_ids]
|
||||
|
||||
extra = request_config.get("additional_information")
|
||||
if extra is None:
|
||||
batched_extra: list[dict[str, Any] | None] = [None] * len(batched_ids)
|
||||
elif isinstance(extra, dict):
|
||||
batched_extra = [extra] * len(batched_ids)
|
||||
else:
|
||||
batched_extra = list(extra)
|
||||
if len(batched_extra) != len(batched_ids):
|
||||
raise ValueError("'additional_information' must match the number of prompts")
|
||||
|
||||
prompts: list[dict[str, Any]] = []
|
||||
for ids, info in zip(batched_ids, batched_extra, strict=True):
|
||||
prompt: dict[str, Any] = {"prompt_token_ids": list(ids)}
|
||||
if info is not None:
|
||||
prompt["additional_information"] = info
|
||||
prompts.append(prompt)
|
||||
|
||||
start_time = time.perf_counter()
|
||||
outputs = self.runner.omni.generate(prompts)
|
||||
e2e_latency = time.perf_counter() - start_time
|
||||
|
||||
assert len(outputs) == len(prompts), f"Expected {len(prompts)} outputs, got {len(outputs)}"
|
||||
expected_sr = request_config.get("expected_sample_rate")
|
||||
min_duration = request_config.get("min_duration_s")
|
||||
max_duration = request_config.get("max_duration_s")
|
||||
|
||||
result = OmniResponse()
|
||||
wavs: list[torch.Tensor] = []
|
||||
for index, stage_output in enumerate(outputs):
|
||||
assert stage_output.outputs, f"Request {index} produced no output"
|
||||
multimodal_output = stage_output.outputs[0].multimodal_output
|
||||
assert isinstance(multimodal_output, Mapping), (
|
||||
f"Request {index}: expected a mapping, got {type(multimodal_output)}"
|
||||
)
|
||||
|
||||
# Never use ``a or b`` here: truthiness on a tensor raises.
|
||||
audio = multimodal_output.get("model_outputs")
|
||||
if audio is None:
|
||||
audio = multimodal_output.get("audio")
|
||||
assert audio is not None, f"Request {index}: no audio key in {sorted(multimodal_output)}"
|
||||
if isinstance(audio, list):
|
||||
chunks = [torch.as_tensor(chunk).float().cpu().reshape(-1) for chunk in audio if chunk is not None]
|
||||
assert chunks, f"Request {index}: audio list contained no tensors"
|
||||
audio = torch.cat(chunks, dim=0)
|
||||
wav = torch.as_tensor(audio).float().cpu().reshape(-1)
|
||||
assert wav.numel() > 0, f"Request {index}: decoded audio is empty"
|
||||
wavs.append(wav)
|
||||
|
||||
sr_raw = multimodal_output.get("sr")
|
||||
if isinstance(sr_raw, list):
|
||||
sr_raw = sr_raw[-1] if sr_raw else None
|
||||
assert sr_raw is not None, f"Request {index}: missing sample rate"
|
||||
sample_rate = int(sr_raw.item() if hasattr(sr_raw, "item") else sr_raw)
|
||||
if expected_sr is not None:
|
||||
assert sample_rate == int(expected_sr), (
|
||||
f"Request {index}: expected sample rate {expected_sr}, got {sample_rate}"
|
||||
)
|
||||
|
||||
duration_s = wav.numel() / sample_rate
|
||||
if min_duration is not None:
|
||||
assert duration_s >= float(min_duration), (
|
||||
f"Request {index}: audio too short ({duration_s:.2f}s < {min_duration}s)"
|
||||
)
|
||||
if max_duration is not None:
|
||||
assert duration_s <= float(max_duration), (
|
||||
f"Request {index}: audio too long ({duration_s:.2f}s > {max_duration}s)"
|
||||
)
|
||||
|
||||
wav_buf = io.BytesIO()
|
||||
sf.write(wav_buf, wav.numpy(), samplerate=sample_rate, format="WAV", subtype="PCM_16")
|
||||
result = OmniResponse(
|
||||
success=True,
|
||||
audio_bytes=wav_buf.getvalue(),
|
||||
audio_format="audio/wav",
|
||||
e2e_latency=e2e_latency,
|
||||
)
|
||||
assert_audio_speech_response(result, request_config, run_level="core_model")
|
||||
|
||||
if request_config.get("assert_distinct_outputs") and len(wavs) > 1:
|
||||
# Distinct inputs must decode to distinct audio. Leaked per-request
|
||||
# codec state shows up as two requests producing (near-)identical
|
||||
# waveforms; different lengths already prove distinctness.
|
||||
for i in range(len(wavs)):
|
||||
for j in range(i + 1, len(wavs)):
|
||||
a, b = wavs[i], wavs[j]
|
||||
if a.numel() != b.numel():
|
||||
continue
|
||||
max_diff = (a - b).abs().max().item()
|
||||
assert max_diff > 1e-3, (
|
||||
f"Requests {i} and {j} produced near-identical audio "
|
||||
f"(max sample diff {max_diff:.2e}); possible codec-state crosstalk"
|
||||
)
|
||||
return result
|
||||
|
||||
def start_profile(self, profile_prefix: str | None = None, stages: list[int] | None = None) -> list[Any]:
|
||||
return self.runner.start_profile(profile_prefix=profile_prefix, stages=stages)
|
||||
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
@@ -9,11 +12,30 @@ from vllm_omni.metrics.utils import (
|
||||
count_audio_frames,
|
||||
count_image_pixels,
|
||||
count_tokens_from_outputs,
|
||||
count_video_frames,
|
||||
)
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("shape", "expected_frames"),
|
||||
[
|
||||
((1, 64, 64, 3), 1),
|
||||
((3, 64, 64, 3), 3),
|
||||
((4, 64, 64, 3), 4),
|
||||
((8, 64, 64, 3), 8),
|
||||
((3, 8, 64, 64), 8),
|
||||
((1, 1, 64, 64, 3), 1),
|
||||
((1, 3, 64, 64, 3), 3),
|
||||
((1, 4, 64, 64, 3), 4),
|
||||
((1, 3, 8, 64, 64), 8),
|
||||
],
|
||||
)
|
||||
def test_count_video_frames_handles_short_channel_last_outputs(shape, expected_frames):
|
||||
assert count_video_frames(SimpleNamespace(shape=shape)) == expected_frames
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("audio_chunk", "expected"),
|
||||
[
|
||||
|
||||
Whitespace-only changes.
@@ -0,0 +1,141 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import functools
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
NUM_CODEBOOKS = 10
|
||||
#: Samples the fake codec returns per frame, so trims are easy to assert.
|
||||
SAMPLES_PER_FRAME = 100
|
||||
|
||||
|
||||
@functools.lru_cache(maxsize=1)
|
||||
def _decoder_cls():
|
||||
from vllm_omni.model_executor.models.audio8_tts.audio8_tts_codec_decoder import Audio8TTSCodecDecoder
|
||||
|
||||
return Audio8TTSCodecDecoder
|
||||
|
||||
|
||||
class _FakeCodec:
|
||||
"""Returns ``SAMPLES_PER_FRAME`` ramp samples per frame."""
|
||||
|
||||
def __init__(self):
|
||||
self.calls: list[tuple[int, ...]] = []
|
||||
|
||||
def decode(self, codes_bqf: torch.Tensor) -> torch.Tensor:
|
||||
self.calls.append(tuple(codes_bqf.shape))
|
||||
frames = int(codes_bqf.shape[-1])
|
||||
total = frames * SAMPLES_PER_FRAME
|
||||
return torch.arange(total, dtype=torch.float32).view(1, 1, total)
|
||||
|
||||
|
||||
def _make_decoder(codec: _FakeCodec, num_codebooks: int = NUM_CODEBOOKS, splits=None):
|
||||
decoder = object.__new__(_decoder_cls())
|
||||
torch.nn.Module.__init__(decoder)
|
||||
decoder._codec = codec
|
||||
decoder._codec_device = torch.device("cpu")
|
||||
decoder._codec_dtype = torch.float32
|
||||
decoder._num_codebooks = num_codebooks
|
||||
decoder._sample_rate = 44100
|
||||
decoder._frame_size = 2048
|
||||
decoder._logged_stats = True
|
||||
decoder._ensure_codec_loaded = lambda: None
|
||||
if splits is not None:
|
||||
decoder._split_request_ids = lambda ids, seq_token_counts=None: splits
|
||||
return decoder
|
||||
|
||||
|
||||
def test_left_context_frames_are_trimmed_from_the_emitted_chunk():
|
||||
"""The decoder must emit *delta* audio: the left-context prefix exists only
|
||||
so the causal codec has history and must never reach the client twice."""
|
||||
codec = _FakeCodec()
|
||||
decoder = _make_decoder(codec)
|
||||
codes = torch.arange(NUM_CODEBOOKS * 4, dtype=torch.long).reshape(NUM_CODEBOOKS, 4)
|
||||
|
||||
out = decoder.forward(
|
||||
input_ids=torch.tensor([0], dtype=torch.long),
|
||||
runtime_additional_information=[{"codes": {"audio": codes}, "meta": {"left_context_size": 3}}],
|
||||
)
|
||||
|
||||
audios = out.multimodal_outputs["model_outputs"]
|
||||
assert len(audios) == 1
|
||||
# 4 frames decoded, 3 of context trimmed => 1 frame of new audio.
|
||||
assert audios[0].shape[0] == SAMPLES_PER_FRAME
|
||||
assert codec.calls == [(1, NUM_CODEBOOKS, 4)]
|
||||
|
||||
|
||||
def test_tensor_codes_from_runtime_info_win_over_input_ids():
|
||||
codec = _FakeCodec()
|
||||
decoder = _make_decoder(codec, num_codebooks=2)
|
||||
out = decoder.forward(
|
||||
input_ids=torch.zeros(64, dtype=torch.long),
|
||||
runtime_additional_information=[{"codes": {"audio": torch.tensor([[1, 2], [3, 4]], dtype=torch.long)}}],
|
||||
)
|
||||
assert codec.calls == [(1, 2, 2)]
|
||||
assert out.multimodal_outputs["model_outputs"][0].shape[0] == 2 * SAMPLES_PER_FRAME
|
||||
|
||||
|
||||
def test_flat_input_ids_are_reshaped_codebook_major():
|
||||
codec = _FakeCodec()
|
||||
decoder = _make_decoder(codec, num_codebooks=2)
|
||||
out = decoder.forward(input_ids=torch.arange(6, dtype=torch.long), runtime_additional_information=[{}])
|
||||
assert codec.calls == [(1, 2, 3)]
|
||||
assert out.multimodal_outputs["model_outputs"][0].shape[0] == 3 * SAMPLES_PER_FRAME
|
||||
|
||||
|
||||
def test_every_return_path_sets_model_outputs_and_sr():
|
||||
"""A branch that omits ``model_outputs`` makes the serving layer drop the
|
||||
chunk silently, so assert the key exists on all the early-exit paths."""
|
||||
codec = _FakeCodec()
|
||||
|
||||
empty = _make_decoder(codec).forward(input_ids=torch.zeros(0, dtype=torch.long))
|
||||
assert empty.multimodal_outputs["model_outputs"][0].numel() == 0
|
||||
assert empty.multimodal_outputs["sr"]
|
||||
|
||||
ragged = _make_decoder(codec, num_codebooks=4).forward(
|
||||
input_ids=torch.arange(6, dtype=torch.long), # 6 % 4 != 0
|
||||
runtime_additional_information=[{}],
|
||||
)
|
||||
assert ragged.multimodal_outputs["model_outputs"][0].numel() == 0
|
||||
|
||||
codes = torch.zeros((NUM_CODEBOOKS, 2), dtype=torch.long)
|
||||
no_new = _make_decoder(codec).forward(
|
||||
input_ids=torch.tensor([0], dtype=torch.long),
|
||||
runtime_additional_information=[{"codes": {"audio": codes}, "meta": {"left_context_size": 2}}],
|
||||
)
|
||||
assert no_new.multimodal_outputs["model_outputs"][0].numel() == 0
|
||||
assert codec.calls == [], "a context-only chunk must not be decoded"
|
||||
|
||||
|
||||
def test_mixed_batch_keeps_per_request_alignment():
|
||||
"""An empty request must not shift the following request's audio into its
|
||||
slot: the output list index is the request index."""
|
||||
codec = _FakeCodec()
|
||||
splits = [
|
||||
torch.empty((0,), dtype=torch.long),
|
||||
torch.arange(NUM_CODEBOOKS * 2, dtype=torch.long),
|
||||
]
|
||||
decoder = _make_decoder(codec, splits=splits)
|
||||
out = decoder.forward(
|
||||
input_ids=torch.arange(NUM_CODEBOOKS * 2, dtype=torch.long),
|
||||
runtime_additional_information=[{}, {"meta": {"left_context_size": 1}}],
|
||||
)
|
||||
audios = out.multimodal_outputs["model_outputs"]
|
||||
assert len(audios) == 2
|
||||
assert audios[0].numel() == 0
|
||||
assert audios[1].shape[0] == SAMPLES_PER_FRAME
|
||||
|
||||
|
||||
def test_codes_with_wrong_codebook_count_fall_back_to_input_ids():
|
||||
codec = _FakeCodec()
|
||||
decoder = _make_decoder(codec, num_codebooks=2)
|
||||
out = decoder.forward(
|
||||
input_ids=torch.arange(4, dtype=torch.long),
|
||||
runtime_additional_information=[{"codes": {"audio": torch.zeros((5, 3), dtype=torch.long)}}],
|
||||
)
|
||||
assert codec.calls == [(1, 2, 2)]
|
||||
assert out.multimodal_outputs["model_outputs"][0].shape[0] == 2 * SAMPLES_PER_FRAME
|
||||
@@ -0,0 +1,112 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm_omni.model_executor.models.audio8_tts.prompt_utils import (
|
||||
build_text_only_prompt_ids,
|
||||
build_voice_clone_prompt_ids,
|
||||
estimate_voice_clone_prompt_len,
|
||||
normalize_text,
|
||||
)
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
class _SegmentTokenizer:
|
||||
"""Tokenizer stub that maps each encoded string to one sentinel id.
|
||||
|
||||
Lets the tests assert the *segment sequence* the prompt builder emits, which
|
||||
is what must stay byte-identical to the reference ``ArkttsProcessor``.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self.vocab: dict[str, int] = {}
|
||||
|
||||
def encode(self, text: str, add_special_tokens: bool = True):
|
||||
assert add_special_tokens is False, "Audio8 prompts must not add extra special tokens"
|
||||
return [self.vocab.setdefault(text, 1000 + len(self.vocab))]
|
||||
|
||||
def segment_of(self, token_id: int) -> str:
|
||||
return next(text for text, tid in self.vocab.items() if tid == token_id)
|
||||
|
||||
|
||||
def _segments(tokenizer: _SegmentTokenizer, ids: list[int]) -> list[str]:
|
||||
return [tokenizer.segment_of(i) for i in ids]
|
||||
|
||||
|
||||
def test_text_only_prompt_matches_reference_segment_order():
|
||||
tokenizer = _SegmentTokenizer()
|
||||
ids, normalized = build_text_only_prompt_ids(tokenizer, " Hello world ")
|
||||
|
||||
assert normalized == "Hello world"
|
||||
assert _segments(tokenizer, ids) == [
|
||||
"<|im_start|>system\n",
|
||||
"convert the provided text to speech",
|
||||
"<|im_end|>\n",
|
||||
"<|im_start|>user\n",
|
||||
"Hello world",
|
||||
"<|im_end|>\n",
|
||||
"<|im_start|>assistant\n<|voice|>",
|
||||
]
|
||||
|
||||
|
||||
def test_voice_clone_prompt_places_reference_codes_between_prefix_and_suffix():
|
||||
tokenizer = _SegmentTokenizer()
|
||||
semantic_ids = [151678, 151679, 151680]
|
||||
ids, ref_start, text, ref_text = build_voice_clone_prompt_ids(
|
||||
tokenizer, "Target text", "Reference transcript", semantic_ids
|
||||
)
|
||||
|
||||
assert text == "Target text"
|
||||
# A reference transcript without an explicit tag gets speaker 0.
|
||||
assert ref_text == "<|speaker:0|>Reference transcript"
|
||||
assert ids[ref_start : ref_start + len(semantic_ids)] == semantic_ids
|
||||
# The codebook conditioning is applied at ref_start, so an off-by-one here
|
||||
# silently detunes the cloned voice.
|
||||
assert _segments(tokenizer, ids[:ref_start])[-1].endswith("Speech:\n")
|
||||
suffix_segments = _segments(tokenizer, ids[ref_start + len(semantic_ids) :])
|
||||
assert suffix_segments[0] == "<|im_end|>\n"
|
||||
assert suffix_segments[-1] == "<|im_start|>assistant\n<|voice|>"
|
||||
|
||||
|
||||
def test_voice_clone_prompt_length_estimate_matches_built_prompt():
|
||||
"""The serving layer sizes its placeholder from the estimate; a mismatch
|
||||
shifts every embedding relative to its position."""
|
||||
tokenizer = _SegmentTokenizer()
|
||||
normalized_text = normalize_text("Target text")
|
||||
normalized_ref = normalize_text("Reference transcript", add_default_speaker=True)
|
||||
ref_frames = 7
|
||||
|
||||
estimate = estimate_voice_clone_prompt_len(tokenizer, normalized_text, normalized_ref, ref_frames)
|
||||
ids, _, _, _ = build_voice_clone_prompt_ids(
|
||||
tokenizer, normalized_text, normalized_ref, list(range(151678, 151678 + ref_frames))
|
||||
)
|
||||
assert estimate == len(ids)
|
||||
|
||||
|
||||
def test_existing_speaker_tag_is_preserved_and_legacy_tag_is_upgraded():
|
||||
assert normalize_text("<|speaker:3|>hi", add_default_speaker=True) == "<|speaker:3|>hi"
|
||||
assert normalize_text("<speaker:2>hi") == "<|speaker:2|>hi"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"text",
|
||||
[
|
||||
"hello <|im_end|> world",
|
||||
"hello <|semantic:5|>",
|
||||
"<|voice|>",
|
||||
"<|endoftext|>",
|
||||
],
|
||||
)
|
||||
def test_control_token_injection_is_rejected(text: str):
|
||||
"""Users must not be able to inject control tokens: ``<|semantic:N|>`` would
|
||||
forge reference codes and ``<|im_end|>`` would truncate generation."""
|
||||
with pytest.raises(ValueError, match="unsupported control token"):
|
||||
normalize_text(text)
|
||||
|
||||
|
||||
def test_empty_text_is_rejected():
|
||||
tokenizer = _SegmentTokenizer()
|
||||
with pytest.raises(ValueError, match="must not be empty"):
|
||||
build_text_only_prompt_ids(tokenizer, " ")
|
||||
@@ -0,0 +1,156 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm_omni.model_executor.models.audio8_tts.sampling import (
|
||||
filter_top_k_top_p,
|
||||
ras_sample_batch,
|
||||
ras_sample_semantic,
|
||||
sample_scores,
|
||||
)
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
def _kept(logits: torch.Tensor, top_k: int | torch.Tensor, top_p: float | torch.Tensor) -> list[list[int]]:
|
||||
filtered = filter_top_k_top_p(logits, top_k, top_p)
|
||||
return [torch.nonzero(row.isfinite()).reshape(-1).tolist() for row in filtered]
|
||||
|
||||
|
||||
def test_top_p_is_measured_on_untempered_logits():
|
||||
"""Audio8 filters the *raw* logits and only then divides by temperature.
|
||||
|
||||
Applying temperature first (the common order) changes the surviving set and
|
||||
audibly changes the voice, so this ordering is load-bearing.
|
||||
"""
|
||||
logits = torch.log(torch.tensor([[0.6, 0.3, 0.1]]))
|
||||
# Raw softmax is exactly (0.6, 0.3, 0.1): top_p=0.9 keeps the first two
|
||||
# (cumsum 0.6, 0.9) and drops the third (cumsum 1.0 > 0.9).
|
||||
assert _kept(logits, top_k=0, top_p=0.9) == [[0, 1]]
|
||||
# Had the logits been tempered by 0.5 first, probabilities would become
|
||||
# (0.7insh, ...) and only one token would survive.
|
||||
tempered = _kept(logits / 0.5, top_k=0, top_p=0.9)
|
||||
assert tempered == [[0, 1]] or tempered == [[0]]
|
||||
|
||||
|
||||
def test_argmax_always_survives_filtering():
|
||||
logits = torch.tensor([[10.0, -1.0, -2.0]])
|
||||
# top_p=0.0 would otherwise remove every candidate and produce NaNs.
|
||||
assert _kept(logits, top_k=1, top_p=0.0) == [[0]]
|
||||
|
||||
|
||||
def test_per_row_top_k_and_top_p_are_honoured():
|
||||
logits = torch.log(torch.tensor([[0.5, 0.3, 0.15, 0.05], [0.5, 0.3, 0.15, 0.05]]))
|
||||
kept = _kept(logits, top_k=torch.tensor([1, 3]), top_p=torch.tensor([1.0, 1.0]))
|
||||
assert kept == [[0], [0, 1, 2]]
|
||||
|
||||
|
||||
def test_zero_temperature_row_falls_back_to_argmax():
|
||||
logits = torch.tensor([[1.0, 5.0, 2.0], [1.0, 5.0, 2.0]])
|
||||
out = sample_scores(
|
||||
logits,
|
||||
temperature=torch.tensor([0.0, 1.0]),
|
||||
top_k=0,
|
||||
top_p=1.0,
|
||||
generator=torch.Generator().manual_seed(0),
|
||||
)
|
||||
assert int(out[0]) == 1
|
||||
|
||||
|
||||
def test_ras_substitutes_only_repeated_semantic_ids():
|
||||
"""RAS re-rolls a repeat from a flatter distribution; the EOS slot and
|
||||
non-repeats must pass through untouched, or utterances get truncated."""
|
||||
num_semantic = 2
|
||||
# Row 0 will draw id 0 (a repeat) -> substituted.
|
||||
# Row 1 will draw id 2 (the EOS slot) -> never substituted even if recent.
|
||||
logits = torch.tensor(
|
||||
[
|
||||
[10.0, -20.0, -20.0],
|
||||
[-20.0, -20.0, 10.0],
|
||||
]
|
||||
)
|
||||
recent = torch.tensor([[0, -1], [2, -1]])
|
||||
out = ras_sample_semantic(
|
||||
logits,
|
||||
recent,
|
||||
temperature=1e-6, # deterministic: argmax within each draw
|
||||
top_k=0,
|
||||
top_p=1.0,
|
||||
ras_temperature=1e-6,
|
||||
ras_top_p=1.0,
|
||||
num_semantic_ids=num_semantic,
|
||||
)
|
||||
# Both draws are argmax, so substitution is observable only through which
|
||||
# branch was taken; assert the EOS row is preserved verbatim.
|
||||
assert int(out[1]) == 2
|
||||
assert int(out[0]) == 0
|
||||
|
||||
|
||||
def test_ras_without_history_returns_the_plain_draw():
|
||||
logits = torch.tensor([[10.0, 0.0, -5.0]])
|
||||
out = ras_sample_semantic(
|
||||
logits,
|
||||
None,
|
||||
temperature=1e-6,
|
||||
top_k=0,
|
||||
top_p=1.0,
|
||||
ras_temperature=1.0,
|
||||
ras_top_p=0.9,
|
||||
num_semantic_ids=2,
|
||||
)
|
||||
assert int(out[0]) == 0
|
||||
|
||||
|
||||
def test_sampling_is_reproducible_for_a_seeded_generator():
|
||||
logits = torch.randn(4, 32, generator=torch.Generator().manual_seed(7))
|
||||
first = sample_scores(logits, temperature=0.7, top_k=8, top_p=0.9, generator=torch.Generator().manual_seed(1234))
|
||||
second = sample_scores(logits, temperature=0.7, top_k=8, top_p=0.9, generator=torch.Generator().manual_seed(1234))
|
||||
assert torch.equal(first, second)
|
||||
|
||||
|
||||
def test_batch_routes_each_row_to_its_own_generator():
|
||||
"""Regression for the shared slot-0 generator bug.
|
||||
|
||||
A shared generator over ``[num_reqs, vocab]`` made every row draw from slot
|
||||
0's RNG stream, so a request's audio depended on its batch neighbours and
|
||||
per-request ``seed`` was ignored for slots > 0. Flat logits make the draw
|
||||
purely noise-driven so the wrong generator changes the token.
|
||||
"""
|
||||
# Flat logits: the sampled id is determined only by the generator's noise,
|
||||
# so routing the generator to the wrong slot changes the result (coincidence ~1/256).
|
||||
logits = torch.zeros(2, 256)
|
||||
kw = dict(temperature=1.0, top_k=0, top_p=1.0, ras_temperature=1.0, ras_top_p=0.9, num_semantic_ids=200)
|
||||
|
||||
# (1) Each batched row equals sampling that row alone with its own generator.
|
||||
batched = ras_sample_batch(
|
||||
logits,
|
||||
None,
|
||||
generators={0: torch.Generator().manual_seed(11), 1: torch.Generator().manual_seed(22)},
|
||||
num_reqs=2,
|
||||
**kw,
|
||||
)
|
||||
row0 = ras_sample_semantic(logits[0:1], None, generator=torch.Generator().manual_seed(11), **kw)
|
||||
row1 = ras_sample_semantic(logits[1:2], None, generator=torch.Generator().manual_seed(22), **kw)
|
||||
assert int(batched[0]) == int(row0)
|
||||
assert int(batched[1]) == int(row1)
|
||||
|
||||
# (2) Row 1 must not change when only slot 0's seed changes.
|
||||
other = ras_sample_batch(
|
||||
logits,
|
||||
None,
|
||||
generators={0: torch.Generator().manual_seed(9999), 1: torch.Generator().manual_seed(22)},
|
||||
num_reqs=2,
|
||||
**kw,
|
||||
)
|
||||
assert int(other[1]) == int(batched[1])
|
||||
|
||||
|
||||
def test_single_request_batch_keeps_the_fast_path():
|
||||
"""``num_reqs == 1`` must match a direct single-row draw (no per-row loop)."""
|
||||
logits = torch.randn(1, 48, generator=torch.Generator().manual_seed(5))
|
||||
kw = dict(temperature=0.8, top_k=16, top_p=0.9, ras_temperature=1.0, ras_top_p=0.9, num_semantic_ids=40)
|
||||
batched = ras_sample_batch(logits, None, generators={0: torch.Generator().manual_seed(99)}, num_reqs=1, **kw)
|
||||
direct = ras_sample_semantic(logits, None, generator=torch.Generator().manual_seed(99), **kw)
|
||||
assert torch.equal(batched, direct)
|
||||
@@ -0,0 +1,110 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""CPU tests for the vendored DAC codec modules (dac_modules).
|
||||
|
||||
Guards the checkpoint contract: the module tree built by build_dac_codec()
|
||||
must keep the exact parameter/buffer names and shapes that codec.pth was
|
||||
saved with (verified against the upstream fish-speech 0.1.0 package), and
|
||||
the encode/decode surfaces used by dac_encoder.py / fish_speech_dac_decoder.py
|
||||
must keep their shapes.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
# Spot checks covering every submodule family and both weight-norm styles.
|
||||
# Derived from the upstream fish-speech 0.1.0 state dict (541 entries total);
|
||||
# legacy weight_norm (weight_g/weight_v) comes from the descript quantizer
|
||||
# projections, parametrizations.weight.original0/1 from the causal convs.
|
||||
EXPECTED_KEY_SAMPLES = [
|
||||
# encoder: first conv + deepest encoder-block transformer
|
||||
"encoder.block.0.conv.parametrizations.weight.original0",
|
||||
"encoder.block.4.block.5.layers.3.attention.wqkv.weight",
|
||||
"encoder.block.4.block.5.freqs_cis",
|
||||
"encoder.block.1.block.0.block.0.alpha",
|
||||
# quantizer: semantic + residual VQ (legacy weight_norm keys)
|
||||
"quantizer.semantic_quantizer.quantizers.0.codebook.weight",
|
||||
"quantizer.quantizer.quantizers.8.in_proj.weight_g",
|
||||
"quantizer.quantizer.quantizers.8.in_proj.weight_v",
|
||||
# quantizer pre/post transformers + down/upsample convnext
|
||||
"quantizer.pre_module.layers.7.feed_forward.w1.weight",
|
||||
"quantizer.post_module.norm.weight",
|
||||
"quantizer.downsample.1.1.dwconv.conv.weight",
|
||||
"quantizer.upsample.0.0.conv.weight",
|
||||
# decoder: transposed conv + final conv
|
||||
"decoder.model.1.block.1.conv.parametrizations.weight.original1",
|
||||
"decoder.model.6.conv.parametrizations.weight.original0",
|
||||
]
|
||||
|
||||
NUM_STATE_DICT_ENTRIES = 541
|
||||
DAC_NUM_CODEBOOKS = 10 # 1 semantic + 9 residual
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def codec():
|
||||
from vllm_omni.model_executor.models.fish_speech.dac_utils import build_dac_codec
|
||||
|
||||
model = build_dac_codec()
|
||||
model.eval()
|
||||
return model
|
||||
|
||||
|
||||
def test_state_dict_contract(codec):
|
||||
sd = codec.state_dict()
|
||||
assert len(sd) == NUM_STATE_DICT_ENTRIES
|
||||
for key in EXPECTED_KEY_SAMPLES:
|
||||
assert key in sd, f"checkpoint-contract key missing: {key}"
|
||||
|
||||
|
||||
def test_no_fish_speech_import_required(codec):
|
||||
import sys
|
||||
|
||||
assert "fish_speech" not in sys.modules, "vendored codec must not import the fish-speech package"
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def test_encode_shapes(codec):
|
||||
frame_length = codec.frame_length # 2048 samples per code frame
|
||||
wav = torch.randn(1, 1, frame_length * 3 + 100)
|
||||
lengths = torch.tensor([wav.shape[-1]], dtype=torch.long)
|
||||
codes, code_lengths = codec.encode(wav, lengths)
|
||||
assert codes.shape[0] == 1
|
||||
assert codes.shape[1] == DAC_NUM_CODEBOOKS
|
||||
assert codes.shape[2] == 4 # ceil(3.x frames)
|
||||
assert code_lengths.tolist() == [4]
|
||||
assert codes.dtype in (torch.int64, torch.int32)
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def test_decode_shapes(codec):
|
||||
frames = 8
|
||||
codes = torch.randint(0, 1024, (1, DAC_NUM_CODEBOOKS, frames), dtype=torch.long)
|
||||
feature_lengths = torch.tensor([frames], dtype=torch.long)
|
||||
wav, audio_lengths = codec.decode(codes, feature_lengths)
|
||||
assert wav.shape[0] == 1 and wav.shape[1] == 1
|
||||
assert audio_lengths.tolist() == [frames * codec.frame_length]
|
||||
assert wav.shape[-1] >= audio_lengths[0] - codec.frame_length
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def test_decoder_runner_mutations(codec):
|
||||
"""The stage-1 runner prunes encode-only parts and bakes weight norm;
|
||||
decode must still work afterwards (mirrors fish_speech_dac_decoder)."""
|
||||
from torch.nn.utils.parametrize import remove_parametrizations
|
||||
|
||||
codec.encoder = None
|
||||
codec.quantizer.pre_module = None
|
||||
codec.quantizer.downsample = None
|
||||
for module in codec.modules():
|
||||
parametrizations = getattr(module, "parametrizations", None)
|
||||
if not parametrizations:
|
||||
continue
|
||||
for name in list(parametrizations.keys()):
|
||||
remove_parametrizations(module, name, leave_parametrized=True)
|
||||
|
||||
codes = torch.randint(0, 1024, (2, DAC_NUM_CODEBOOKS, 5), dtype=torch.long)
|
||||
wav, audio_lengths = codec.decode(codes, torch.tensor([5, 3], dtype=torch.long))
|
||||
assert wav.shape[0] == 2
|
||||
assert audio_lengths.tolist() == [5 * codec.frame_length, 3 * codec.frame_length]
|
||||
@@ -11,13 +11,15 @@ import asyncio
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from collections import OrderedDict, defaultdict
|
||||
from collections import defaultdict
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from tests.helpers.stage_config import get_deploy_config_path
|
||||
from vllm_omni.entrypoints.openai.tts_adapters.base import SpeechServingContext
|
||||
from vllm_omni.entrypoints.openai.tts_adapters.higgs_audio_v3 import HiggsAudioV3Adapter
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
@@ -1683,31 +1685,21 @@ class TestVoiceCloneReferenceCache:
|
||||
assert tok._resolve_audio_tokenizer_dir() is None
|
||||
|
||||
def test_higgs_v3_ref_code_cache_returns_clone(self):
|
||||
from vllm_omni.entrypoints.openai.serving_speech import OmniOpenAIServingSpeech
|
||||
|
||||
serving = object.__new__(OmniOpenAIServingSpeech)
|
||||
serving._higgs_audio_v3_ref_code_cache = OrderedDict()
|
||||
serving._higgs_audio_v3_ref_code_cache_bytes = 0
|
||||
serving._higgs_audio_v3_ref_code_inflight = {}
|
||||
adapter = HiggsAudioV3Adapter(SpeechServingContext(server=SimpleNamespace()))
|
||||
|
||||
codes = torch.arange(16, dtype=torch.long).reshape(2, 8)
|
||||
serving._put_higgs_audio_v3_ref_codes("ref-a", codes)
|
||||
adapter._put_higgs_audio_v3_ref_codes("ref-a", codes)
|
||||
|
||||
cached = serving._get_higgs_audio_v3_ref_codes("ref-a")
|
||||
cached = adapter._get_higgs_audio_v3_ref_codes("ref-a")
|
||||
assert cached is not None
|
||||
cached.fill_(0)
|
||||
|
||||
cached_again = serving._get_higgs_audio_v3_ref_codes("ref-a")
|
||||
cached_again = adapter._get_higgs_audio_v3_ref_codes("ref-a")
|
||||
assert cached_again is not None
|
||||
assert torch.equal(cached_again, codes)
|
||||
|
||||
def test_higgs_v3_ref_code_inflight_deduplicates_concurrent_encode(self):
|
||||
from vllm_omni.entrypoints.openai.serving_speech import OmniOpenAIServingSpeech
|
||||
|
||||
serving = object.__new__(OmniOpenAIServingSpeech)
|
||||
serving._higgs_audio_v3_ref_code_cache = OrderedDict()
|
||||
serving._higgs_audio_v3_ref_code_cache_bytes = 0
|
||||
serving._higgs_audio_v3_ref_code_inflight = {}
|
||||
adapter = HiggsAudioV3Adapter(SpeechServingContext(server=SimpleNamespace()))
|
||||
calls = 0
|
||||
|
||||
def encode_reference_audio(_wav, _sr):
|
||||
@@ -1722,7 +1714,7 @@ class TestVoiceCloneReferenceCache:
|
||||
async def run():
|
||||
return await asyncio.gather(
|
||||
*[
|
||||
serving._resolve_higgs_audio_v3_ref_codes(
|
||||
adapter._resolve_higgs_audio_v3_ref_codes(
|
||||
"ref-a",
|
||||
object(),
|
||||
24000,
|
||||
@@ -1741,7 +1733,7 @@ class TestVoiceCloneReferenceCache:
|
||||
assert torch.equal(codes, torch.arange(16, dtype=torch.long).reshape(2, 8) + 1)
|
||||
|
||||
cached, cache_hit, inflight_wait = asyncio.run(
|
||||
serving._resolve_higgs_audio_v3_ref_codes(
|
||||
adapter._resolve_higgs_audio_v3_ref_codes(
|
||||
"ref-a",
|
||||
object(),
|
||||
24000,
|
||||
|
||||
@@ -91,7 +91,11 @@ def _minimal_model(mocker: MockerFixture):
|
||||
decoder=decoder,
|
||||
config=SimpleNamespace(avg_pooler=2, stride_size=2, hop_length=240),
|
||||
)
|
||||
model._tokenizer_service = SimpleNamespace(audio_tokenizer=audio_tok, cuda_graph_wrapper=None)
|
||||
model._tokenizer_service = SimpleNamespace(
|
||||
audio_tokenizer=audio_tok,
|
||||
cuda_graph_wrapper=None,
|
||||
device="cpu",
|
||||
)
|
||||
return model, audio_tok
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Regression tests for the MiMo-Audio tokenizer-worker cache key.
|
||||
|
||||
The worker cache key used to keep only the device *type*, so an explicit
|
||||
``MIMO_AUDIO_TOKENIZER_DEVICE=cuda:1`` silently loaded the tokenizer on the
|
||||
process's current CUDA device and shared one cache entry with ``cuda:0``.
|
||||
The index must survive both the cache key and the worker constructor.
|
||||
|
||||
CPU-only and weight-free: the worker class is replaced by a stub so no
|
||||
tokenizer weights are loaded.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import functools
|
||||
|
||||
import pytest
|
||||
|
||||
torch = pytest.importorskip("torch")
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
_TOK_PATH = "/models/mimo-audio-tokenizer"
|
||||
|
||||
|
||||
@functools.lru_cache(maxsize=1)
|
||||
def _code2wav_module():
|
||||
"""Defer the import (pulls vLLM model_executor) until first use."""
|
||||
from vllm_omni.model_executor.models.mimo_audio import mimo_audio_code2wav
|
||||
|
||||
return mimo_audio_code2wav
|
||||
|
||||
|
||||
class _StubWorker:
|
||||
def __init__(self, device_str: str, config_path: str | None, audio_tokenizer_path: str):
|
||||
self.device = device_str
|
||||
self.config_path = config_path
|
||||
self.audio_tokenizer_path = audio_tokenizer_path
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def isolated_worker_cache(monkeypatch):
|
||||
"""Empty worker cache with the real worker replaced by a stub."""
|
||||
mod = _code2wav_module()
|
||||
monkeypatch.setattr(mod, "MiMoAudioTokenizerWorker", _StubWorker)
|
||||
monkeypatch.setattr(mod, "_TOKENIZER_WORKER_CACHE", {})
|
||||
return mod
|
||||
|
||||
|
||||
@pytest.mark.parametrize("device", [torch.device("cuda:1"), "cuda:1"])
|
||||
def test_cache_key_keeps_cuda_index(device):
|
||||
"""Both torch.device and string spellings retain the index."""
|
||||
mod = _code2wav_module()
|
||||
key = mod._normalize_tokenizer_worker_cache_key(device, None, _TOK_PATH)
|
||||
assert key[0] == "cuda:1"
|
||||
|
||||
|
||||
def test_cache_key_cpu_unchanged():
|
||||
mod = _code2wav_module()
|
||||
key = mod._normalize_tokenizer_worker_cache_key(torch.device("cpu"), None, _TOK_PATH)
|
||||
assert key[0] == "cpu"
|
||||
|
||||
|
||||
def test_cache_key_bare_cuda_resolves_to_current_device(monkeypatch):
|
||||
"""A bare "cuda" shares the entry with its equivalent indexed spelling."""
|
||||
mod = _code2wav_module()
|
||||
monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
|
||||
monkeypatch.setattr(torch.accelerator, "current_device_index", lambda: 3)
|
||||
|
||||
bare = mod._normalize_tokenizer_worker_cache_key(torch.device("cuda"), None, _TOK_PATH)
|
||||
indexed = mod._normalize_tokenizer_worker_cache_key(torch.device("cuda:3"), None, _TOK_PATH)
|
||||
assert bare[0] == "cuda:3"
|
||||
assert bare == indexed
|
||||
|
||||
|
||||
def test_worker_constructed_on_requested_index(isolated_worker_cache):
|
||||
mod = isolated_worker_cache
|
||||
worker = mod.get_tokenizer_worker(
|
||||
device=torch.device("cuda:1"),
|
||||
config_path=None,
|
||||
audio_tokenizer_path=_TOK_PATH,
|
||||
)
|
||||
assert worker.device == "cuda:1"
|
||||
|
||||
|
||||
def test_distinct_cuda_indices_get_distinct_workers(isolated_worker_cache):
|
||||
mod = isolated_worker_cache
|
||||
first = mod.get_tokenizer_worker(
|
||||
device=torch.device("cuda:0"),
|
||||
config_path=None,
|
||||
audio_tokenizer_path=_TOK_PATH,
|
||||
)
|
||||
second = mod.get_tokenizer_worker(
|
||||
device=torch.device("cuda:1"),
|
||||
config_path=None,
|
||||
audio_tokenizer_path=_TOK_PATH,
|
||||
)
|
||||
assert first is not second
|
||||
assert (first.device, second.device) == ("cuda:0", "cuda:1")
|
||||
|
||||
|
||||
def test_same_device_reuses_cached_worker(isolated_worker_cache):
|
||||
mod = isolated_worker_cache
|
||||
first = mod.get_tokenizer_worker(
|
||||
device=torch.device("cuda:1"),
|
||||
config_path=None,
|
||||
audio_tokenizer_path=_TOK_PATH,
|
||||
)
|
||||
second = mod.get_tokenizer_worker(
|
||||
device="cuda:1",
|
||||
config_path=None,
|
||||
audio_tokenizer_path=_TOK_PATH,
|
||||
)
|
||||
assert first is second
|
||||
@@ -1,12 +1,16 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm_omni.entrypoints.openai.serving_speech import OmniOpenAIServingSpeech
|
||||
from vllm_omni.entrypoints.openai.tts_adapters.base import SpeechServingContext
|
||||
from vllm_omni.entrypoints.openai.tts_adapters.ming_tts import (
|
||||
MingTTSAdapter,
|
||||
parse_ming_instruction_fields,
|
||||
)
|
||||
from vllm_omni.model_executor.models.common.ming.aggregator import Aggregator
|
||||
from vllm_omni.model_executor.models.common.ming.audio_vae import AudioVAEConfig
|
||||
from vllm_omni.model_executor.models.common.ming.cfm_cudagraph import CFMGraphExecutor, CFMSampler
|
||||
@@ -174,19 +178,19 @@ def test_ming_dense_validation_rejects_semantic_audio_vae_config():
|
||||
|
||||
def test_ming_instruction_parser_preserves_dense_and_flash_defaults():
|
||||
"""Ming dense and Ming flash keep distinct instruction defaults."""
|
||||
serving = object.__new__(OmniOpenAIServingSpeech)
|
||||
serving.uploaded_speakers = {"uploaded": {}}
|
||||
serving = SimpleNamespace(uploaded_speakers={"uploaded": {}})
|
||||
adapter = MingTTSAdapter(SpeechServingContext(server=serving))
|
||||
|
||||
dense_plain = serving._parse_ming_instruction(SimpleNamespace(instructions="calm", language=None, voice=None))
|
||||
dense_plain = adapter._parse_ming_instruction(SimpleNamespace(instructions="calm", language=None, voice=None))
|
||||
assert dense_plain == "calm"
|
||||
|
||||
dense_with_fields = serving._parse_ming_instruction(
|
||||
dense_with_fields = adapter._parse_ming_instruction(
|
||||
SimpleNamespace(instructions="calm", language="Auto", voice="灵小甄")
|
||||
)
|
||||
assert dense_with_fields == {"IP": "灵小甄", "风格": "calm"}
|
||||
|
||||
flash_fields = serving._parse_ming_instruction_fields(
|
||||
SimpleNamespace(instructions="calm", language="粤语", voice="灵小甄")
|
||||
flash_fields = parse_ming_instruction_fields(
|
||||
serving, SimpleNamespace(instructions="calm", language="粤语", voice="灵小甄")
|
||||
)
|
||||
assert flash_fields == {"风格": "calm"}
|
||||
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Regression tests for the MiniCPM-o 4.5 ``audio_embeds`` input path.
|
||||
|
||||
Two defects made the OpenAI ``audio_embeds`` content part unusable with this model:
|
||||
|
||||
1. ``MiniCPMOAudioEmbeddingItems`` registered itself under ``modality="image"``
|
||||
(copy-pasted from ``MiniCPMVImageEmbeddingItems``), so every request failed with
|
||||
``Modality 'image' not found. Available modalities: {'audio'}``.
|
||||
2. ``_get_prompt_updates`` sized the placeholder from
|
||||
``sum(map(len, single_audio_embeds))``. ``MiniCPMOAudioEmbeddingInputs`` declares
|
||||
``TensorShape("bn", "s", "h")``, so one item is ``(s, h)`` and that expression
|
||||
iterates rows and sums the hidden size -- ``s * h`` instead of ``s``. A one-second
|
||||
slice of shape ``(10, 4096)`` asked for 40960 placeholder tokens instead of 10,
|
||||
pushing every real request past ``max_model_len``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from vllm.multimodal.parse import MultiModalDataItems
|
||||
|
||||
from vllm_omni.model_executor.models.minicpmo_4_5.minicpmo_4_5_omni_llm import (
|
||||
MiniCPMO45OmniLLMMultiModalProcessor,
|
||||
MiniCPMO45OmniLLMProcessingInfo,
|
||||
MiniCPMOAudioEmbeddingItems,
|
||||
_minicpmo_field_config,
|
||||
)
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
POOL_STEP = 5
|
||||
HIDDEN_SIZE = 4096
|
||||
#: Audio embedding vectors produced per second: 100 mel -> 50 cnn -> (50-5)//5+1.
|
||||
EMBEDS_PER_SECOND = 10
|
||||
|
||||
|
||||
class _FakeProcessor:
|
||||
"""Minimal processor surface used by ``get_audio_placeholder``."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.pool_step = POOL_STEP
|
||||
self.audio_processor = SimpleNamespace(hop_length=160)
|
||||
self.image_processor = SimpleNamespace(mean=[0.0], std=[1.0])
|
||||
|
||||
def get_audio_placeholder(
|
||||
self,
|
||||
audio_lens: int,
|
||||
chunk_input: bool = True,
|
||||
chunk_length: int = 1,
|
||||
) -> str:
|
||||
del chunk_input, chunk_length
|
||||
feature_lens = math.ceil(audio_lens / self.audio_processor.hop_length)
|
||||
cnn_feature_lens = (feature_lens - 1) // 2 + 1
|
||||
output_lens = (cnn_feature_lens - self.pool_step) // self.pool_step + 1
|
||||
return "<unk>" * output_lens
|
||||
|
||||
|
||||
class _IdentityTokenizer:
|
||||
"""``_get_prompt_updates`` round-trips the image/video patterns through the
|
||||
tokenizer to detect encode/decode drift; an identity pair keeps that a no-op."""
|
||||
|
||||
def encode(self, text: str, add_special_tokens: bool = True) -> str:
|
||||
del add_special_tokens
|
||||
return text
|
||||
|
||||
def decode(self, tokens: str) -> str:
|
||||
return tokens
|
||||
|
||||
|
||||
def _processing_info() -> MiniCPMO45OmniLLMProcessingInfo:
|
||||
processor = _FakeProcessor()
|
||||
tokenizer = _IdentityTokenizer()
|
||||
info = object.__new__(MiniCPMO45OmniLLMProcessingInfo)
|
||||
info.ctx = SimpleNamespace(
|
||||
tokenizer=tokenizer,
|
||||
get_tokenizer=lambda: tokenizer,
|
||||
get_hf_config=lambda: SimpleNamespace(audio_pool_step=POOL_STEP),
|
||||
get_hf_processor=lambda **kwargs: processor,
|
||||
)
|
||||
return info
|
||||
|
||||
|
||||
def _audio_placeholder_for(single_audio_embeds: torch.Tensor) -> str:
|
||||
"""Run the real prompt-update path and return the audio placeholder text.
|
||||
|
||||
Goes through ``_get_prompt_updates`` rather than recomputing the length, so the
|
||||
``sum(map(len, ...))`` regression is actually exercised.
|
||||
"""
|
||||
info = _processing_info()
|
||||
proc = object.__new__(MiniCPMO45OmniLLMMultiModalProcessor)
|
||||
proc.info = info
|
||||
|
||||
items = MiniCPMOAudioEmbeddingItems(
|
||||
{"audio_embeds": single_audio_embeds.unsqueeze(0)},
|
||||
fields_factory=_minicpmo_field_config,
|
||||
)
|
||||
mm_items = MultiModalDataItems({"audio": items})
|
||||
|
||||
updates = proc._get_prompt_updates(mm_items, {}, {})
|
||||
audio_update = next(u for u in updates if u.modality == "audio")
|
||||
return audio_update.content(0).full
|
||||
|
||||
|
||||
def test_audio_embedding_items_use_the_audio_modality() -> None:
|
||||
"""Registering under ``image`` makes every ``audio_embeds`` request fail."""
|
||||
items = MiniCPMOAudioEmbeddingItems(
|
||||
{"audio_embeds": torch.zeros(1, EMBEDS_PER_SECOND, HIDDEN_SIZE)},
|
||||
fields_factory=_minicpmo_field_config,
|
||||
)
|
||||
|
||||
assert items.modality == "audio"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("num_seconds", [1, 3, 30])
|
||||
def test_placeholder_length_matches_embedding_count(num_seconds: int) -> None:
|
||||
"""An ``(s, h)`` item must yield exactly ``s`` placeholder tokens."""
|
||||
num_embeds = num_seconds * EMBEDS_PER_SECOND
|
||||
|
||||
placeholder = _audio_placeholder_for(torch.zeros(num_embeds, HIDDEN_SIZE))
|
||||
|
||||
assert placeholder.count("<unk>") == num_embeds
|
||||
|
||||
|
||||
def test_placeholder_does_not_scale_with_hidden_size() -> None:
|
||||
"""The count must depend on ``s`` alone, never on ``h``.
|
||||
|
||||
``sum(map(len, ...))`` returned ``s * h``, so the placeholder grew with the model's
|
||||
hidden size. Two items with the same ``s`` but different ``h`` must agree.
|
||||
"""
|
||||
narrow = _audio_placeholder_for(torch.zeros(EMBEDS_PER_SECOND, 8))
|
||||
wide = _audio_placeholder_for(torch.zeros(EMBEDS_PER_SECOND, HIDDEN_SIZE))
|
||||
|
||||
assert narrow.count("<unk>") == wide.count("<unk>") == EMBEDS_PER_SECOND
|
||||
@@ -1,5 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Unit tests for MiniCPM-o 4.5 code2wav model-dir resolution (#5442).
|
||||
|
||||
In hub/CI deployments ``model_config.model`` is a repo id rather than a local
|
||||
@@ -27,7 +27,7 @@ def _no_hub(monkeypatch):
|
||||
def _fail(*args, **kwargs): # pragma: no cover - must not be reached
|
||||
raise AssertionError("snapshot_download must not be called here")
|
||||
|
||||
monkeypatch.setattr(huggingface_hub, "snapshot_download", _fail)
|
||||
monkeypatch.setattr(huggingface_hub.HfApi, "snapshot_download", _fail)
|
||||
|
||||
|
||||
def test_local_directory_is_returned_unchanged(tmp_path, monkeypatch):
|
||||
@@ -38,13 +38,13 @@ def test_local_directory_is_returned_unchanged(tmp_path, monkeypatch):
|
||||
def test_repo_id_resolves_via_snapshot_download(tmp_path, monkeypatch):
|
||||
calls = {}
|
||||
|
||||
def _fake_snapshot_download(model_ref, revision=None, allow_patterns=None):
|
||||
def _fake_snapshot_download(self, model_ref, revision=None, allow_patterns=None):
|
||||
calls["model_ref"] = model_ref
|
||||
calls["revision"] = revision
|
||||
calls["allow_patterns"] = allow_patterns
|
||||
return str(tmp_path / "snapshot")
|
||||
|
||||
monkeypatch.setattr(huggingface_hub, "snapshot_download", _fake_snapshot_download)
|
||||
monkeypatch.setattr(huggingface_hub.HfApi, "snapshot_download", _fake_snapshot_download)
|
||||
resolved = _resolve_model_dir("openbmb/MiniCPM-o-4_5", revision="abc123")
|
||||
assert resolved == str(tmp_path / "snapshot")
|
||||
assert calls["model_ref"] == "openbmb/MiniCPM-o-4_5"
|
||||
@@ -56,7 +56,7 @@ def test_snapshot_download_failure_propagates(monkeypatch):
|
||||
def _raise(*args, **kwargs):
|
||||
raise FileNotFoundError("offline and not cached")
|
||||
|
||||
monkeypatch.setattr(huggingface_hub, "snapshot_download", _raise)
|
||||
monkeypatch.setattr(huggingface_hub.HfApi, "snapshot_download", _raise)
|
||||
with pytest.raises(FileNotFoundError):
|
||||
_resolve_model_dir("openbmb/MiniCPM-o-4_5")
|
||||
|
||||
|
||||
@@ -10,6 +10,10 @@ Covers:
|
||||
- ``process_audios``: >30s audio unpads per chunk without ``TypeError``
|
||||
- multiple >30s audios unpad in chunk order
|
||||
- <=30s audio unpadding byte-identical to the pre-fix behavior
|
||||
- ``MiniCPMOAudioFeatureInputs``: a batch mixing a >30s and a <=30s audio
|
||||
(different slice counts) validates instead of raising, whether from a
|
||||
single request with multiple audios of different lengths or from
|
||||
multiple requests sharing an encoder batch
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -26,6 +30,7 @@ from vllm.multimodal.inputs import (
|
||||
|
||||
from vllm_omni.model_executor.models.minicpmo_4_5.minicpmo_4_5_omni_llm import (
|
||||
MiniCPMO45OmniLLMMultiModalProcessor,
|
||||
MiniCPMOAudioFeatureInputs,
|
||||
MiniCPMOMultiModalDataParser,
|
||||
_minicpmo_field_config,
|
||||
)
|
||||
@@ -152,3 +157,43 @@ class TestProcessAudiosUnpadding:
|
||||
assert len(features) == 1
|
||||
assert features[0].shape == (_FEAT_DIM, 980)
|
||||
assert torch.equal(features[0], fake_outputs["audio_features"][0][:, :980])
|
||||
|
||||
|
||||
class TestMixedChunkCountBatchValidation:
|
||||
def test_batch_mixes_different_slice_counts(self) -> None:
|
||||
# A >30s audio (3 slices) and a <=30s audio (2 slices) scheduled in
|
||||
# the same encoder batch: audio_feature_lens is a list of per-audio
|
||||
# tensors with different lengths (3 vs 2). This is the shape produced
|
||||
# both by a single request with two audios of different lengths and
|
||||
# by two separate requests batched together. Before the fix this
|
||||
# raised ValueError: "audio_feature_lens contains inconsistent shapes".
|
||||
audio_feature_lens = [
|
||||
torch.tensor([_CHUNK_FRAMES, _CHUNK_FRAMES, 1]),
|
||||
torch.tensor([_CHUNK_FRAMES, 1]),
|
||||
]
|
||||
audio_features = [torch.zeros(_FEAT_DIM, _CHUNK_FRAMES) for _ in range(5)]
|
||||
|
||||
inputs = MiniCPMOAudioFeatureInputs(
|
||||
type="audio_features",
|
||||
audio_features=audio_features,
|
||||
audio_feature_lens=audio_feature_lens,
|
||||
)
|
||||
|
||||
assert inputs.audio_feature_lens is audio_feature_lens
|
||||
|
||||
def test_single_slice_count_batch_still_validated(self) -> None:
|
||||
# Same slice count per audio (the common case) must still validate,
|
||||
# unaffected by marking "s" dynamic.
|
||||
audio_feature_lens = [
|
||||
torch.tensor([_CHUNK_FRAMES, 1]),
|
||||
torch.tensor([_CHUNK_FRAMES, 1]),
|
||||
]
|
||||
audio_features = [torch.zeros(_FEAT_DIM, _CHUNK_FRAMES) for _ in range(4)]
|
||||
|
||||
inputs = MiniCPMOAudioFeatureInputs(
|
||||
type="audio_features",
|
||||
audio_features=audio_features,
|
||||
audio_feature_lens=audio_feature_lens,
|
||||
)
|
||||
|
||||
assert inputs.audio_feature_lens is audio_feature_lens
|
||||
@@ -6,19 +6,27 @@ Tests for OmniVoice CUDA Graph generator wrapper numerical equivalence.
|
||||
Verifies that _OmniVoiceCUDAGraphForward produces results equivalent to
|
||||
eager mode across three scenarios:
|
||||
- Exact-size inputs (no padding) → bit-identical
|
||||
- Padded inputs (padded to nearest bucket) → correct slicing, exact match
|
||||
for position-independent models
|
||||
- Oversized inputs (fallback to eager) → bit-identical
|
||||
- Padded inputs (padded to nearest bucket) → correct slicing and exact match
|
||||
- Oversized inputs (128-aligned lazy capture) → bit-identical
|
||||
|
||||
Uses a lightweight synthetic generator to keep warmup fast and avoid
|
||||
loading actual model weights.
|
||||
Uses a small randomly initialized OmniVoiceGenerator so every test exercises
|
||||
the production embedding, transformer, varlen-attention, and logits paths
|
||||
without loading checkpoint weights.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from vllm.utils.math_utils import round_up
|
||||
|
||||
from vllm_omni.model_executor.models.omnivoice.omnivoice_generator import (
|
||||
OmniVoiceGenerator,
|
||||
_OmniVoiceCUDAGraphForward,
|
||||
)
|
||||
from vllm_omni.transformers_utils.configs.omnivoice import OmniVoiceConfig
|
||||
|
||||
pytestmark = [
|
||||
pytest.mark.core_model,
|
||||
@@ -29,53 +37,7 @@ pytestmark = [
|
||||
DEVICE = torch.device("cuda:0")
|
||||
NUM_CB = 8
|
||||
VOCAB = 1025
|
||||
HIDDEN = 64
|
||||
CAPTURE_SIZES = [32, 64, 128]
|
||||
HEAD_DIM = 64
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Synthetic generator: matches _OmniVoiceCUDAGraphForward's interface
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class _SyntheticGenerator:
|
||||
"""Position-independent Embedding+Linear replacing OmniVoiceGenerator's 28-layer transformer.
|
||||
|
||||
Each token position is processed independently (no attention), so padded
|
||||
runs produce bit-identical results to non-padded runs on the same positions.
|
||||
This makes the padding/slicing logic easy to verify exactly.
|
||||
"""
|
||||
|
||||
class _Cfg:
|
||||
num_audio_codebook = NUM_CB
|
||||
|
||||
def __init__(self, device: torch.device):
|
||||
self.config = self._Cfg()
|
||||
self.text_embedding = nn.Embedding(1000, HIDDEN).to(device).eval()
|
||||
self._linear = nn.Linear(HIDDEN, NUM_CB * VOCAB, bias=False).to(device).eval()
|
||||
self._rope_table: torch.Tensor | None = None
|
||||
|
||||
@property
|
||||
def model_dtype(self) -> torch.dtype:
|
||||
"""Part of the interface _OmniVoiceCUDAGraphForward expects of a generator."""
|
||||
return self.text_embedding.weight.dtype
|
||||
|
||||
def _rope_table_for(self, seq_len: int, device: torch.device, dtype: torch.dtype) -> torch.Tensor:
|
||||
"""Part of the interface _OmniVoiceCUDAGraphForward expects of a generator."""
|
||||
return torch.zeros(seq_len, HEAD_DIM, device=device, dtype=dtype)
|
||||
|
||||
def _step_forward(
|
||||
self,
|
||||
input_ids: torch.Tensor,
|
||||
audio_mask: torch.Tensor,
|
||||
attention_mask: torch.Tensor | None,
|
||||
rope_table: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
two_b, _, S = input_ids.shape
|
||||
x = self.text_embedding(input_ids[:, 0, :].clamp(0, 999)) # [two_b, S, H]
|
||||
logits = self._linear(x) # [two_b, S, 8*1025]
|
||||
return logits.view(two_b, S, NUM_CB, VOCAB).permute(0, 2, 1, 3) # [two_b, 8, S, 1025]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -83,18 +45,37 @@ class _SyntheticGenerator:
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _eager(gen: _SyntheticGenerator, ids: torch.Tensor, mask: torch.Tensor, attn: torch.Tensor) -> torch.Tensor:
|
||||
"""Run _step_forward with a zero RoPE table (synthetic gen ignores it)."""
|
||||
two_b, _, S = ids.shape
|
||||
return gen._step_forward(ids, mask, attn, gen._rope_table_for(S, ids.device, torch.float32))
|
||||
def _eager(gen: OmniVoiceGenerator, ids: torch.Tensor, mask: torch.Tensor, cu_seqs) -> torch.Tensor:
|
||||
"""Run the production varlen step outside CUDA Graph."""
|
||||
seq_len = ids.shape[0]
|
||||
rope_table = gen._rope_table_for(seq_len, ids.device, gen.model_dtype)
|
||||
return gen._step_forward(ids, mask, cu_seqs, rope_table)
|
||||
|
||||
|
||||
def _bucketed_eager(gen, wrapper, ids, mask, cu_seqs, batch_size) -> torch.Tensor:
|
||||
"""Run eager with the exact padded shape and metadata used by Graph."""
|
||||
seq_len = ids.shape[0]
|
||||
bucket = wrapper._find_bucket(batch_size, seq_len)
|
||||
if bucket is None:
|
||||
bucket = round_up(seq_len, wrapper._LAZY_CAPTURE_ALIGNMENT)
|
||||
padded_ids, padded_mask = wrapper._pad_inputs(ids, mask, bucket)
|
||||
padded_cu_seqs = cu_seqs.clone()
|
||||
padded_cu_seqs[-1] = bucket
|
||||
return _eager(gen, padded_ids, padded_mask, padded_cu_seqs)[:, :seq_len, :]
|
||||
|
||||
|
||||
def _make_inputs(seq_len: int, device: torch.device = DEVICE):
|
||||
two_b = 2
|
||||
ids = torch.randint(0, 100, (two_b, NUM_CB, seq_len), dtype=torch.long, device=device)
|
||||
mask = torch.ones(two_b, seq_len, dtype=torch.bool, device=device)
|
||||
attn = torch.ones(two_b, 1, seq_len, seq_len, dtype=torch.bool, device=device)
|
||||
return ids, mask, attn
|
||||
ids = torch.randint(0, 100, (seq_len, NUM_CB), dtype=torch.long, device=device)
|
||||
mask = torch.ones(seq_len, dtype=torch.bool, device=device)
|
||||
cond_len = (seq_len + 1) // 2
|
||||
uncond_len = seq_len - cond_len
|
||||
|
||||
cu_seqs = torch.tensor(
|
||||
[0, cond_len, cond_len + uncond_len, cond_len + uncond_len],
|
||||
dtype=torch.int32,
|
||||
device=device,
|
||||
)
|
||||
return ids, mask, cu_seqs
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -105,15 +86,26 @@ def _make_inputs(seq_len: int, device: torch.device = DEVICE):
|
||||
@pytest.fixture(scope="module")
|
||||
def gen():
|
||||
torch.manual_seed(42)
|
||||
return _SyntheticGenerator(DEVICE)
|
||||
config = OmniVoiceConfig(
|
||||
audio_vocab_size=VOCAB,
|
||||
num_audio_codebook=NUM_CB,
|
||||
llm_config={
|
||||
"hidden_size": 64,
|
||||
"num_hidden_layers": 2,
|
||||
"num_attention_heads": 4,
|
||||
"num_key_value_heads": 2,
|
||||
"intermediate_size": 128,
|
||||
"vocab_size": 128,
|
||||
"max_position_embeddings": 4096,
|
||||
"head_dim": 16,
|
||||
},
|
||||
enable_cuda_graph=False,
|
||||
)
|
||||
return OmniVoiceGenerator(config, SimpleNamespace(max_num_seqs=2)).to(DEVICE).eval()
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def wrapper(gen):
|
||||
from vllm_omni.model_executor.models.omnivoice.omnivoice_generator import (
|
||||
_OmniVoiceCUDAGraphForward,
|
||||
)
|
||||
|
||||
w = _OmniVoiceCUDAGraphForward(gen, capture_sizes=CAPTURE_SIZES)
|
||||
w.warmup(DEVICE)
|
||||
return w
|
||||
@@ -127,10 +119,10 @@ def wrapper(gen):
|
||||
@pytest.mark.parametrize("seq_len", CAPTURE_SIZES)
|
||||
def test_exact_size_bit_identical(gen, wrapper, seq_len):
|
||||
"""When input exactly matches a captured bucket, output must be bit-identical to eager."""
|
||||
ids, mask, attn = _make_inputs(seq_len)
|
||||
ids, mask, cu_seqs = _make_inputs(seq_len)
|
||||
with torch.no_grad():
|
||||
eager_out = _eager(gen, ids, mask, attn)
|
||||
graph_out = wrapper(ids, mask, attn)
|
||||
eager_out = _eager(gen, ids, mask, cu_seqs)
|
||||
graph_out = wrapper(ids, mask, cu_seqs, 1)
|
||||
torch.testing.assert_close(graph_out, eager_out, atol=0, rtol=0)
|
||||
|
||||
|
||||
@@ -140,40 +132,36 @@ def test_exact_size_bit_identical(gen, wrapper, seq_len):
|
||||
|
||||
|
||||
@pytest.mark.parametrize("seq_len", [1, 15, 33, 60, 100])
|
||||
def test_padded_output_shape(gen, wrapper, seq_len):
|
||||
def test_padded_output_shape(wrapper, seq_len):
|
||||
"""Graph output must be sliced back to actual seq_len, not the bucket size."""
|
||||
ids, mask, attn = _make_inputs(seq_len)
|
||||
ids, mask, cu_seqs = _make_inputs(seq_len)
|
||||
with torch.no_grad():
|
||||
graph_out = wrapper(ids, mask, attn)
|
||||
assert graph_out.shape == (2, NUM_CB, seq_len, VOCAB)
|
||||
graph_out = wrapper(ids, mask, cu_seqs, 1)
|
||||
assert graph_out.shape == (NUM_CB, seq_len, VOCAB)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("seq_len", [15, 33, 60, 100])
|
||||
def test_padded_output_matches_eager(gen, wrapper, seq_len):
|
||||
"""Padded graph output must equal eager output at actual positions.
|
||||
|
||||
The synthetic model has no attention across positions, so zero-padding
|
||||
does not affect non-padded positions — exact match is expected.
|
||||
"""
|
||||
ids, mask, attn = _make_inputs(seq_len)
|
||||
"""Padded graph output must equal eager output at actual positions."""
|
||||
ids, mask, cu_seqs = _make_inputs(seq_len)
|
||||
with torch.no_grad():
|
||||
eager_out = _eager(gen, ids, mask, attn)
|
||||
graph_out = wrapper(ids, mask, attn)
|
||||
eager_out = _bucketed_eager(gen, wrapper, ids, mask, cu_seqs, 1)
|
||||
graph_out = wrapper(ids, mask, cu_seqs, 1)
|
||||
torch.testing.assert_close(graph_out, eager_out, atol=0, rtol=0)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 3. Oversized inputs → fallback to eager (lazy capture), bit-identical
|
||||
# 3. Oversized inputs → aligned lazy capture, bit-identical
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize("seq_len", [129, 200, 256])
|
||||
def test_fallback_eager_bit_identical(gen, wrapper, seq_len):
|
||||
"""Sequences exceeding the largest bucket fall back to lazy capture → bit-identical."""
|
||||
ids, mask, attn = _make_inputs(seq_len)
|
||||
def test_aligned_lazy_capture_bit_identical(gen, wrapper, seq_len):
|
||||
"""Sequences beyond the static plan use aligned lazy capture and remain bit-identical."""
|
||||
ids, mask, cu_seqs = _make_inputs(seq_len)
|
||||
with torch.no_grad():
|
||||
eager_out = _eager(gen, ids, mask, attn)
|
||||
graph_out = wrapper(ids, mask, attn)
|
||||
eager_out = _bucketed_eager(gen, wrapper, ids, mask, cu_seqs, 1)
|
||||
graph_out = wrapper(ids, mask, cu_seqs, 1)
|
||||
torch.testing.assert_close(graph_out, eager_out, atol=0, rtol=0)
|
||||
|
||||
|
||||
@@ -184,13 +172,73 @@ def test_fallback_eager_bit_identical(gen, wrapper, seq_len):
|
||||
|
||||
def test_deterministic_across_calls(wrapper):
|
||||
"""Same input must produce identical output on repeated CUDA graph replays."""
|
||||
ids, mask, attn = _make_inputs(32)
|
||||
ids, mask, cu_seqs = _make_inputs(32)
|
||||
with torch.no_grad():
|
||||
out1 = wrapper(ids, mask, attn)
|
||||
out2 = wrapper(ids, mask, attn)
|
||||
out1 = wrapper(ids, mask, cu_seqs, 1).clone()
|
||||
out2 = wrapper(ids, mask, cu_seqs, 1).clone()
|
||||
torch.testing.assert_close(out1, out2, atol=0, rtol=0)
|
||||
|
||||
|
||||
def test_replay_uses_updated_cu_seqs(gen, wrapper):
|
||||
"""The same graph key must honor new sequence boundaries on replay."""
|
||||
ids, mask, _ = _make_inputs(48)
|
||||
cu_seqs_a = torch.tensor([0, 32, 48, 48], dtype=torch.int32, device=DEVICE)
|
||||
cu_seqs_b = torch.tensor([0, 17, 48, 48], dtype=torch.int32, device=DEVICE)
|
||||
|
||||
with torch.no_grad():
|
||||
eager_a = _bucketed_eager(gen, wrapper, ids, mask, cu_seqs_a, 1)
|
||||
graph_a = wrapper(ids, mask, cu_seqs_a, 1).clone()
|
||||
eager_b = _bucketed_eager(gen, wrapper, ids, mask, cu_seqs_b, 1)
|
||||
graph_b = wrapper(ids, mask, cu_seqs_b, 1).clone()
|
||||
|
||||
torch.testing.assert_close(graph_a, eager_a, atol=0, rtol=0)
|
||||
torch.testing.assert_close(graph_b, eager_b, atol=0, rtol=0)
|
||||
assert not torch.equal(graph_a, graph_b)
|
||||
|
||||
|
||||
def test_batch_two_cu_seqs_matches_eager(gen, wrapper):
|
||||
"""B=2 uses four real sequence segments plus the fixed tail slot."""
|
||||
ids, mask, _ = _make_inputs(48)
|
||||
cu_seqs = torch.tensor([0, 10, 18, 32, 48, 48], dtype=torch.int32, device=DEVICE)
|
||||
|
||||
assert cu_seqs.numel() == 2 * 2 + 2
|
||||
with torch.no_grad():
|
||||
eager_out = _bucketed_eager(gen, wrapper, ids, mask, cu_seqs, 2)
|
||||
graph_out = wrapper(ids, mask, cu_seqs, 2).clone()
|
||||
|
||||
torch.testing.assert_close(graph_out, eager_out, atol=0, rtol=0)
|
||||
|
||||
|
||||
def test_lazy_graph_cache_uses_lru_eviction(wrapper):
|
||||
"""A lazy-cache hit must protect that graph from the next eviction."""
|
||||
original_limit = wrapper._MAX_LAZY_GRAPHS
|
||||
wrapper._lazy_graphs.clear()
|
||||
wrapper._MAX_LAZY_GRAPHS = 2
|
||||
try:
|
||||
# Static B=1 coverage ends at 128. These lengths round to three
|
||||
# distinct 128-aligned lazy keys: 256, 384, and 512.
|
||||
for seq_len in (129, 257):
|
||||
ids, mask, cu_seqs = _make_inputs(seq_len)
|
||||
with torch.no_grad():
|
||||
wrapper(ids, mask, cu_seqs, 1)
|
||||
assert list(wrapper._lazy_graphs) == [(1, 256), (1, 384)]
|
||||
|
||||
# Refresh key 256, making key 384 the least recently used entry.
|
||||
ids, mask, cu_seqs = _make_inputs(129)
|
||||
with torch.no_grad():
|
||||
wrapper(ids, mask, cu_seqs, 1)
|
||||
assert list(wrapper._lazy_graphs) == [(1, 384), (1, 256)]
|
||||
|
||||
# Inserting key 512 must evict key 384, not the recently hit key 256.
|
||||
ids, mask, cu_seqs = _make_inputs(385)
|
||||
with torch.no_grad():
|
||||
wrapper(ids, mask, cu_seqs, 1)
|
||||
assert list(wrapper._lazy_graphs) == [(1, 256), (1, 512)]
|
||||
finally:
|
||||
wrapper._MAX_LAZY_GRAPHS = original_limit
|
||||
wrapper._lazy_graphs.clear()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 5. _find_bucket logic (CPU, no CUDA graph)
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -203,58 +251,17 @@ def test_find_bucket_returns_nearest_bucket():
|
||||
)
|
||||
|
||||
w = _OmniVoiceCUDAGraphForward.__new__(_OmniVoiceCUDAGraphForward)
|
||||
w._capture_sizes = [32, 64, 128]
|
||||
w.capture_bucket_sizes_by_batch = {
|
||||
1: [32, 64, 128],
|
||||
2: [64, 128, 256],
|
||||
}
|
||||
w._graphs = {}
|
||||
|
||||
assert w._find_bucket(1) == 32
|
||||
assert w._find_bucket(32) == 32
|
||||
assert w._find_bucket(33) == 64
|
||||
assert w._find_bucket(64) == 64
|
||||
assert w._find_bucket(128) == 128
|
||||
assert w._find_bucket(129) is None
|
||||
assert w._find_bucket(1000) is None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 6. enable_cuda_graph=False produces same tokens as enable_cuda_graph=True
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_cuda_graph_disabled_matches_eager_generator():
|
||||
"""OmniVoiceGenerator with enable_cuda_graph=False must produce the same
|
||||
_step_forward output as one with enable_cuda_graph=True (after warmup).
|
||||
|
||||
Uses a 2-layer config so warmup completes quickly without loading weights.
|
||||
"""
|
||||
from vllm_omni.model_executor.models.omnivoice.omnivoice_generator import OmniVoiceGenerator
|
||||
from vllm_omni.transformers_utils.configs.omnivoice import OmniVoiceConfig
|
||||
|
||||
cfg = OmniVoiceConfig()
|
||||
cfg.llm_num_hidden_layers = 2
|
||||
cfg.num_hidden_layers = 2
|
||||
|
||||
torch.manual_seed(0)
|
||||
gen_eager = OmniVoiceGenerator(cfg).to(DEVICE).eval()
|
||||
gen_eager.config.enable_cuda_graph = False
|
||||
gen_eager._cuda_graph_fwd = None
|
||||
|
||||
torch.manual_seed(0)
|
||||
gen_graph = OmniVoiceGenerator(cfg).to(DEVICE).eval()
|
||||
gen_graph.config.cuda_graph_capture_sizes = [64]
|
||||
from vllm_omni.model_executor.models.omnivoice.omnivoice_generator import _OmniVoiceCUDAGraphForward
|
||||
|
||||
gen_graph._cuda_graph_fwd = _OmniVoiceCUDAGraphForward(gen_graph, capture_sizes=[64])
|
||||
gen_graph._cuda_graph_fwd.warmup(DEVICE)
|
||||
|
||||
seq_len = 64
|
||||
ids = torch.zeros(2, cfg.num_audio_codebook, seq_len, dtype=torch.long, device=DEVICE)
|
||||
mask = torch.ones(2, seq_len, dtype=torch.bool, device=DEVICE)
|
||||
attn = torch.ones(2, 1, seq_len, seq_len, dtype=torch.bool, device=DEVICE)
|
||||
|
||||
rope_table = gen_eager._rope_table_for(seq_len, DEVICE, gen_eager.model_dtype)
|
||||
|
||||
with torch.no_grad():
|
||||
eager_logits = gen_eager._step_forward(ids, mask, attn, rope_table)
|
||||
graph_logits = gen_graph._cuda_graph_fwd(ids, mask, attn)
|
||||
|
||||
torch.testing.assert_close(graph_logits, eager_logits, atol=0, rtol=0)
|
||||
assert w._find_bucket(1, 1) == 32
|
||||
assert w._find_bucket(1, 32) == 32
|
||||
assert w._find_bucket(1, 33) == 64
|
||||
assert w._find_bucket(1, 128) == 128
|
||||
assert w._find_bucket(1, 129) is None
|
||||
assert w._find_bucket(2, 33) == 64
|
||||
assert w._find_bucket(2, 129) == 256
|
||||
assert w._find_bucket(3, 64) is None
|
||||
@@ -1,5 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""The OmniVoice generator packs q/k/v and gate/up into fused projections.
|
||||
|
||||
The HF checkpoint stores those five tensors separately, so packing them is a
|
||||
@@ -14,6 +14,8 @@ that would leave one partly written raises instead.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
@@ -49,6 +51,13 @@ def _config() -> OmniVoiceConfig:
|
||||
)
|
||||
|
||||
|
||||
def _generator() -> OmniVoiceGenerator:
|
||||
return OmniVoiceGenerator(
|
||||
_config(),
|
||||
SimpleNamespace(max_num_seqs=1),
|
||||
)
|
||||
|
||||
|
||||
def _checkpoint_shards() -> dict[str, torch.Tensor]:
|
||||
"""The five per-layer tensors an OmniVoice checkpoint actually stores."""
|
||||
torch.manual_seed(0)
|
||||
@@ -64,7 +73,7 @@ def _checkpoint_shards() -> dict[str, torch.Tensor]:
|
||||
|
||||
|
||||
def test_every_fused_parameter_is_written() -> None:
|
||||
generator = OmniVoiceGenerator(_config())
|
||||
generator = _generator()
|
||||
shards = _checkpoint_shards()
|
||||
|
||||
loaded = generator._load_fused_projections(shards)
|
||||
@@ -77,7 +86,7 @@ def test_every_fused_parameter_is_written() -> None:
|
||||
|
||||
def test_packed_weight_matches_the_shards_it_came_from() -> None:
|
||||
"""Packing order is q,k,v and gate,up -- the split in forward() assumes it."""
|
||||
generator = OmniVoiceGenerator(_config())
|
||||
generator = _generator()
|
||||
shards = _checkpoint_shards()
|
||||
generator._load_fused_projections(shards)
|
||||
|
||||
@@ -101,7 +110,7 @@ def test_packed_weight_matches_the_shards_it_came_from() -> None:
|
||||
|
||||
def test_no_fused_parameter_keeps_its_random_init() -> None:
|
||||
"""The corruption this guards against: a fused param never written at all."""
|
||||
generator = OmniVoiceGenerator(_config())
|
||||
generator = _generator()
|
||||
before = {
|
||||
name: param.detach().clone()
|
||||
for name, param in generator.named_parameters()
|
||||
@@ -121,7 +130,7 @@ def test_no_fused_parameter_keeps_its_random_init() -> None:
|
||||
["self_attn.k_proj", "self_attn.v_proj", "self_attn.q_proj", "mlp.gate_proj", "mlp.up_proj"],
|
||||
)
|
||||
def test_a_missing_shard_raises_instead_of_loading_partially(dropped: str) -> None:
|
||||
generator = OmniVoiceGenerator(_config())
|
||||
generator = _generator()
|
||||
shards = _checkpoint_shards()
|
||||
del shards[f"llm.layers.0.{dropped}.weight"]
|
||||
|
||||
@@ -130,7 +139,7 @@ def test_a_missing_shard_raises_instead_of_loading_partially(dropped: str) -> No
|
||||
|
||||
|
||||
def test_a_wrong_shaped_shard_raises() -> None:
|
||||
generator = OmniVoiceGenerator(_config())
|
||||
generator = _generator()
|
||||
shards = _checkpoint_shards()
|
||||
shards["llm.layers.0.self_attn.q_proj.weight"] = torch.randn(NUM_HEADS * HEAD_DIM + 1, HIDDEN)
|
||||
|
||||
@@ -140,7 +149,7 @@ def test_a_wrong_shaped_shard_raises() -> None:
|
||||
|
||||
def test_a_checkpoint_missing_a_whole_layer_raises() -> None:
|
||||
"""Half-loaded is the dangerous state: it neither errors nor works."""
|
||||
generator = OmniVoiceGenerator(_config())
|
||||
generator = _generator()
|
||||
shards = {k: v for k, v in _checkpoint_shards().items() if not k.startswith("llm.layers.1.")}
|
||||
|
||||
with pytest.raises(ValueError, match="fused projections"):
|
||||
@@ -149,7 +158,7 @@ def test_a_checkpoint_missing_a_whole_layer_raises() -> None:
|
||||
|
||||
def test_a_checkpoint_with_no_fused_shards_is_left_alone() -> None:
|
||||
"""An unrelated state_dict must not trip the completeness check."""
|
||||
generator = OmniVoiceGenerator(_config())
|
||||
generator = _generator()
|
||||
assert generator._load_fused_projections({"audio_heads.weight": torch.randn(4, 4)}) == set()
|
||||
|
||||
|
||||
@@ -162,7 +171,7 @@ def test_load_weights_wires_the_packing_in(tmp_path, monkeypatch: pytest.MonkeyP
|
||||
"""
|
||||
import safetensors.torch
|
||||
|
||||
generator = OmniVoiceGenerator(_config())
|
||||
generator = _generator()
|
||||
shards = _checkpoint_shards()
|
||||
before = generator.layers[0].self_attn.qkv_proj.weight.detach().clone()
|
||||
|
||||
|
||||
Loaded 100 of 334 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user