Merge vLLM-Omni v0.29.0rc1 into edge-infer/omni-0.29.0
The pair for vLLM v0.29.0: rc1's docs pin vllm==0.29.0 and a static scan of rc1's vllm.* imports against the v0.29.0 tree finds nothing missing, while our 0.28-based tree needs seven modules v0.29.0 no longer has (vllm.inputs.preprocess, entrypoints.launcher, openai.cli_args, openai.engine.protocol, serve.utils.server_utils, layers.batch_invariant, models.hunyuan_v1). Ten files conflicted. Upstream's structure is the base everywhere; the fork's features are re-attached to it: - deploy_profile / apply_deploy_profile run before rc1's resolve_omni_config pops deploy_config (async_omni_engine, cli/serve); the deploy-profile selector and the resolve_model_config_path chain it needs stay in entrypoints/utils.py; stage_overrides takes rc1's dict type. - config_factory keeps the lazy diffusion output-type import; the diffusion registry import in rc1's new config/resolver.py is made lazy for the same WP6 reason (TTS path must not load diffusion). - requirements: our core/media split kept; rc1's transformers>=5.13 floor and kernels==0.16.1 applied in core.txt / media.txt. - TTS: rc1's split_granularity and bounded seed plus our output_mode= codec_tokens, _SessionInbox cancel handling and codec DELTA accumulation; our private _conditioning_cache_salt is superseded by rc1's public tts_adapters/base.py::conditioning_cache_salt. - stage_runtime: rc1's single ExitStack G2 path (lock released before READY) replaces our two-path block, with the four worker_phase names the init profiler consumes still emitted; _cpu_placed / host admission kept. Not yet run against vLLM 0.29.0: the tests listed in the W6 record. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
commit
33de5d8629
513 files changed
+35146
-10927
No files matched your search
@@ -1,5 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
@@ -214,11 +214,20 @@ def test_fish_kvcache_backend_wraps_only_model_instance(monkeypatch):
|
||||
assert fish_kvcache_backend.get_fish_kvcache_attn_stats()["small_hit_count"] == 1
|
||||
|
||||
|
||||
def _vllm_kv_cache_shape(num_blocks, block_size, num_kv_heads, head_size):
|
||||
def _vllm_kv_cache_shape(num_blocks, block_size, num_kv_heads, head_size, dtype=torch.float16):
|
||||
# Source of truth for the paged KV cache layout the backend must unpack.
|
||||
from vllm.v1.attention.backends.flash_attn import FlashAttentionBackend
|
||||
# vLLM 0.29 removed AttentionBackend.get_kv_cache_shape; the per-layer shape
|
||||
# now comes from the spec, with the content dim expressed in bytes.
|
||||
from vllm.v1.kv_cache_interface import FullAttentionSpec, compute_layer_kv_cache_shape_bytes
|
||||
|
||||
return FlashAttentionBackend.get_kv_cache_shape(num_blocks, block_size, num_kv_heads, head_size)
|
||||
spec = FullAttentionSpec(
|
||||
block_size=block_size,
|
||||
num_kv_heads=num_kv_heads,
|
||||
head_size=head_size,
|
||||
dtype=dtype,
|
||||
)
|
||||
num_pages, num_heads, num_states, content_bytes = compute_layer_kv_cache_shape_bytes(spec, num_blocks)
|
||||
return (num_pages, num_heads, num_states, content_bytes // dtype.itemsize)
|
||||
|
||||
|
||||
def test_fish_kvcache_backend_unbinds_kv_on_vllm_cache_layout(monkeypatch):
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -26,6 +26,7 @@ _MODULE_NAME = "vllm_omni.benchmarks.data_modules.seed_tts_dataset"
|
||||
|
||||
if _MODULE_NAME not in sys.modules:
|
||||
_spec = importlib.util.spec_from_file_location(_MODULE_NAME, _MODULE_PATH)
|
||||
assert _spec is not None and _spec.loader is not None
|
||||
_mod = importlib.util.module_from_spec(_spec)
|
||||
sys.modules[_MODULE_NAME] = _mod
|
||||
_spec.loader.exec_module(_mod)
|
||||
@@ -237,7 +238,8 @@ def test_seed_tts_design_dataset_rejects_missing_description(seed_tts_design_roo
|
||||
assert req.seed_tts_utterance_id == "ok"
|
||||
|
||||
|
||||
def test_seed_tts_whisper_transcribe_passes_attention_mask(monkeypatch):
|
||||
@pytest.mark.parametrize("audio_seconds", [0.1, 61])
|
||||
def test_seed_tts_whisper_transcribe_passes_attention_mask(monkeypatch, audio_seconds):
|
||||
from vllm_omni.benchmarks.data_modules import seed_tts_eval
|
||||
|
||||
calls = {}
|
||||
@@ -252,8 +254,9 @@ def test_seed_tts_whisper_transcribe_passes_attention_mask(monkeypatch):
|
||||
return self
|
||||
|
||||
class FakeProcessor:
|
||||
def __call__(self, wav, *, sampling_rate, return_tensors, return_attention_mask=False):
|
||||
def __call__(self, wav, *, sampling_rate, return_tensors, return_attention_mask=False, **kwargs):
|
||||
calls["return_attention_mask"] = return_attention_mask
|
||||
calls["processor_kwargs"] = kwargs
|
||||
assert sampling_rate == 16000
|
||||
assert return_tensors == "pt"
|
||||
assert len(wav) > 0
|
||||
@@ -262,9 +265,10 @@ def test_seed_tts_whisper_transcribe_passes_attention_mask(monkeypatch):
|
||||
attention_mask=FakeTensor("mask") if return_attention_mask else None,
|
||||
)
|
||||
|
||||
def get_decoder_prompt_ids(self, *, language, task):
|
||||
def get_decoder_prompt_ids(self, *, language, task, no_timestamps=True):
|
||||
assert language == "english"
|
||||
assert task == "transcribe"
|
||||
calls["no_timestamps"] = no_timestamps
|
||||
return [(1, 2)]
|
||||
|
||||
def batch_decode(self, predicted_ids, *, skip_special_tokens):
|
||||
@@ -283,10 +287,18 @@ def test_seed_tts_whisper_transcribe_passes_attention_mask(monkeypatch):
|
||||
monkeypatch.setattr(seed_tts_eval, "_en_model", FakeModel())
|
||||
monkeypatch.setattr(seed_tts_eval, "_device", "cuda:1")
|
||||
|
||||
text = seed_tts_eval._transcribe_en_f32_16k(np.ones(1600, dtype=np.float32))
|
||||
text = seed_tts_eval._transcribe_en_f32_16k(np.ones(int(audio_seconds * 16000), dtype=np.float32))
|
||||
|
||||
assert text == "hello"
|
||||
assert calls["return_attention_mask"] is True
|
||||
assert calls["input_features"].device == "cuda:1"
|
||||
assert calls["generate_kwargs"]["attention_mask"].device == "cuda:1"
|
||||
assert calls["generate_kwargs"]["forced_decoder_ids"] == [(1, 2)]
|
||||
if audio_seconds > 30:
|
||||
assert calls["processor_kwargs"] == {"truncation": False, "padding": "longest"}
|
||||
assert calls["generate_kwargs"]["return_timestamps"] is True
|
||||
assert calls["no_timestamps"] is False
|
||||
else:
|
||||
assert calls["processor_kwargs"] == {}
|
||||
assert "return_timestamps" not in calls["generate_kwargs"]
|
||||
assert calls["no_timestamps"] is True
|
||||
@@ -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
|
||||
@@ -0,0 +1,156 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
BOOTSTRAP_PATH = REPO_ROOT / ".buildkite/amd/scripts/bootstrap-amd-omni.sh"
|
||||
|
||||
|
||||
def _run_bootstrap(
|
||||
tmp_path: Path,
|
||||
*,
|
||||
debug_test_yaml: str | None = None,
|
||||
curl_status: int = 0,
|
||||
jq_status: int = 0,
|
||||
labels: tuple[str, ...] = (),
|
||||
pull_request: bool = True,
|
||||
) -> subprocess.CompletedProcess[str]:
|
||||
for relative_path in (
|
||||
".buildkite/common/scripts/resolve_skip_ci.sh",
|
||||
".buildkite/amd/scripts/select_test_suites.py",
|
||||
):
|
||||
destination = tmp_path / relative_path
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(REPO_ROOT / relative_path, destination)
|
||||
|
||||
# Stop after real suite selection, before rendering or uploading a pipeline.
|
||||
(tmp_path / ".buildkite/common/scripts/skip_ci.py").write_text("print('test-skip')\n", encoding="utf-8")
|
||||
env = {
|
||||
"PATH": os.environ["PATH"],
|
||||
"BUILDKITE_PULL_REQUEST": "123" if pull_request else "false",
|
||||
"BUILDKITE_BRANCH": "feature" if pull_request else "main",
|
||||
"TEST_PYTHON": sys.executable,
|
||||
"TEST_CURL_STATUS": str(curl_status),
|
||||
"TEST_JQ_STATUS": str(jq_status),
|
||||
"TEST_PR_LABELS": "\n".join(labels),
|
||||
}
|
||||
if debug_test_yaml is not None:
|
||||
env["DEBUG_TEST_YAML"] = debug_test_yaml
|
||||
|
||||
# Source the unmodified bootstrap with subprocess-local command doubles.
|
||||
script = r"""
|
||||
curl() {
|
||||
echo 'curl called' >&2
|
||||
return "$TEST_CURL_STATUS"
|
||||
}
|
||||
jq() {
|
||||
echo 'jq called' >&2
|
||||
printf '%s\n' "$TEST_PR_LABELS"
|
||||
return "$TEST_JQ_STATUS"
|
||||
}
|
||||
git() { :; }
|
||||
python3() { "$TEST_PYTHON" "$@"; }
|
||||
source "$1"
|
||||
"""
|
||||
return subprocess.run(
|
||||
["bash", "-c", script, "test-amd-bootstrap", str(BOOTSTRAP_PATH)],
|
||||
cwd=tmp_path,
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=10,
|
||||
check=False,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("curl_status", "jq_status"), [(22, 0), (0, 4)], ids=["request-failure", "parse-failure"])
|
||||
@pytest.mark.parametrize(
|
||||
("debug_test_yaml", "expected_levels"),
|
||||
[
|
||||
("ready", ["l2"]),
|
||||
("merge", ["l3"]),
|
||||
("ready,merge", ["l2", "l3"]),
|
||||
(" MERGE, ready,", ["l3", "l2"]),
|
||||
],
|
||||
)
|
||||
def test_debug_override_skips_label_lookup(tmp_path, debug_test_yaml, expected_levels, curl_status, jq_status):
|
||||
result = _run_bootstrap(
|
||||
tmp_path,
|
||||
debug_test_yaml=debug_test_yaml,
|
||||
curl_status=curl_status,
|
||||
jq_status=jq_status,
|
||||
)
|
||||
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert "curl called" not in result.stderr
|
||||
assert "jq called" not in result.stderr
|
||||
assert "legacy ready-suite fallback" not in result.stderr
|
||||
assert [
|
||||
line.split()[2] for line in result.stdout.splitlines() if line.startswith("Skipping AMD ")
|
||||
] == expected_levels
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("curl_status", "jq_status"), [(22, 0), (0, 4)], ids=["request-failure", "parse-failure"])
|
||||
@pytest.mark.parametrize("debug_test_yaml", [None, ""], ids=["unset", "empty"])
|
||||
def test_label_lookup_failure_without_override(tmp_path, debug_test_yaml, curl_status, jq_status):
|
||||
result = _run_bootstrap(
|
||||
tmp_path,
|
||||
debug_test_yaml=debug_test_yaml,
|
||||
curl_status=curl_status,
|
||||
jq_status=jq_status,
|
||||
)
|
||||
|
||||
assert result.returncode == 1
|
||||
assert "Could not read PR labels" in result.stderr
|
||||
assert "Skipping AMD " not in result.stdout
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("labels", "expected_levels"),
|
||||
[
|
||||
(("ready",), ["l2"]),
|
||||
(("merge-test",), ["l3"]),
|
||||
(("ready", "merge-test"), ["l2", "l3"]),
|
||||
((), ["l2"]),
|
||||
],
|
||||
)
|
||||
def test_label_lookup_selects_tiers(tmp_path, labels, expected_levels):
|
||||
result = _run_bootstrap(tmp_path, labels=labels)
|
||||
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert "curl called" in result.stderr
|
||||
assert "jq called" in result.stderr
|
||||
assert [
|
||||
line.split()[2] for line in result.stdout.splitlines() if line.startswith("Skipping AMD ")
|
||||
] == expected_levels
|
||||
|
||||
|
||||
@pytest.mark.parametrize("debug_test_yaml", ["ready,ready", "nightly", ", ,", " \t"])
|
||||
def test_invalid_debug_override_fails_without_label_lookup(tmp_path, debug_test_yaml):
|
||||
result = _run_bootstrap(tmp_path, debug_test_yaml=debug_test_yaml, curl_status=22)
|
||||
|
||||
assert result.returncode == 1
|
||||
assert "DEBUG_TEST_YAML" in result.stderr
|
||||
assert "curl called" not in result.stderr
|
||||
assert "jq called" not in result.stderr
|
||||
assert "Skipping AMD " not in result.stdout
|
||||
|
||||
|
||||
def test_main_does_not_lookup_labels(tmp_path):
|
||||
result = _run_bootstrap(tmp_path, pull_request=False, curl_status=22, jq_status=4)
|
||||
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert "curl called" not in result.stderr
|
||||
assert "jq called" not in result.stderr
|
||||
assert "Skipping AMD l3 suite" in result.stdout
|
||||
@@ -0,0 +1,61 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
SELECTOR_PATH = Path(".buildkite/amd/scripts/select_test_suites.py")
|
||||
SPEC = importlib.util.spec_from_file_location("select_test_suites", SELECTOR_PATH)
|
||||
assert SPEC is not None and SPEC.loader is not None
|
||||
SELECTOR = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(SELECTOR)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("branch", "labels", "expected"),
|
||||
[
|
||||
("main", (), ("merge",)),
|
||||
("feature", ("ready",), ("ready",)),
|
||||
("feature", ("merge-test",), ("merge",)),
|
||||
("feature", ("merge-test", "ready"), ("ready", "merge")),
|
||||
("feature", ("amd-test",), ("ready",)),
|
||||
("feature", ("amd-test", "merge-test"), ("merge",)),
|
||||
("feature", ("amd-test", "ready", "merge-test"), ("ready", "merge")),
|
||||
("feature", ("nightly-test",), ("ready",)),
|
||||
("feature", ("not-ready", "merge-test-extra"), ("ready",)),
|
||||
],
|
||||
)
|
||||
def test_label_suite_selection(branch, labels, expected):
|
||||
assert SELECTOR.select_amd_test_suites(branch=branch, labels=labels) == expected
|
||||
|
||||
|
||||
def test_debug_override_takes_precedence_and_normalizes_input():
|
||||
assert SELECTOR.select_amd_test_suites(
|
||||
branch="main",
|
||||
labels=("ready",),
|
||||
debug_test_yaml=" MERGE, ready,",
|
||||
) == ("merge", "ready")
|
||||
|
||||
|
||||
def test_empty_debug_override_uses_normal_selection():
|
||||
assert SELECTOR.select_amd_test_suites(
|
||||
branch="feature",
|
||||
labels=("merge-test",),
|
||||
debug_test_yaml="",
|
||||
) == ("merge",)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", ["ready,ready", "nightly", ", ,", " \t"])
|
||||
def test_invalid_debug_override(value):
|
||||
with pytest.raises(ValueError):
|
||||
SELECTOR.select_amd_test_suites(
|
||||
branch="feature",
|
||||
labels=(),
|
||||
debug_test_yaml=value,
|
||||
)
|
||||
@@ -12,6 +12,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[2] / ".buildkite" / "com
|
||||
|
||||
from skip_ci import resolve_ci_decision # noqa: E402
|
||||
from upload_pipeline import ( # noqa: E402
|
||||
CUDA_HF_TOKEN_EXPORT,
|
||||
_expand_mirror_hardwares,
|
||||
_get_mirror_hw_selector,
|
||||
_load_bootstrap_steps,
|
||||
@@ -143,6 +144,10 @@ def test_mirror_hardwares_l4_1_expands_to_agents_and_plugins(monkeypatch: pytest
|
||||
container = step["plugins"][0]["kubernetes"]["podSpec"]["containers"][0]
|
||||
assert container["image"].endswith("$BUILDKITE_COMMIT")
|
||||
assert container["resources"]["limits"]["nvidia.com/gpu"] == 1
|
||||
env_names = {item["name"] for item in container["env"]}
|
||||
assert "VLLM_CI_HF_TOKEN" in env_names
|
||||
assert "HF_TOKEN" not in env_names
|
||||
assert step["commands"] == [CUDA_HF_TOKEN_EXPORT, "pytest -sv tests/example"]
|
||||
|
||||
|
||||
def test_mirror_hardwares_l4_preserves_explicit_retry() -> None:
|
||||
@@ -182,6 +187,33 @@ def test_mirror_hardwares_a2b3_npu_4_expands_agents_image_and_plugins() -> None:
|
||||
assert step["plugins"][0]["kubernetes"]["podSpecPatch"]["imagePullSecrets"] == [
|
||||
{"name": "swr-secret"},
|
||||
]
|
||||
assert step["commands"] == ["pytest -sv tests/example"]
|
||||
|
||||
|
||||
def test_all_cuda_mirror_hardwares_restore_hf_token_at_runtime() -> None:
|
||||
for name in (
|
||||
"l4_1",
|
||||
"l4_2",
|
||||
"l4_3",
|
||||
"l4_4",
|
||||
"h100_1",
|
||||
"h100_2",
|
||||
"h100_3",
|
||||
"h100_4",
|
||||
"b200_1",
|
||||
"b200_2",
|
||||
"b200_3",
|
||||
"b200_4",
|
||||
):
|
||||
step = _expand_mirror_hardwares(
|
||||
{"label": name, "mirror_hardwares": name, "commands": ["pytest -sv tests/example"]},
|
||||
)
|
||||
assert step is not None
|
||||
container = step["plugins"][0]["kubernetes"]["podSpec"]["containers"][0]
|
||||
env_names = {item["name"] for item in container["env"]}
|
||||
assert "VLLM_CI_HF_TOKEN" in env_names
|
||||
assert "HF_TOKEN" not in env_names
|
||||
assert step["commands"][0] == CUDA_HF_TOKEN_EXPORT
|
||||
|
||||
|
||||
def _gpu_limit(step: dict) -> int:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -170,7 +170,7 @@ def test_inventory_matches_reviewed_snapshot_counts():
|
||||
EnvironmentVariableCategory.PUBLIC_OMNI: 32,
|
||||
EnvironmentVariableCategory.INHERITED_VLLM: 20,
|
||||
EnvironmentVariableCategory.PLATFORM_EXTERNAL: 27,
|
||||
EnvironmentVariableCategory.MODEL_SPECIFIC: 62,
|
||||
EnvironmentVariableCategory.MODEL_SPECIFIC: 61,
|
||||
EnvironmentVariableCategory.BENCHMARK_TRANSITIONAL: 20,
|
||||
EnvironmentVariableCategory.INTERNAL: 4,
|
||||
}
|
||||
@@ -182,7 +182,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,
|
||||
|
||||
@@ -215,6 +215,16 @@ def test_from_pipeline_config_normalizes_stage_engine_extras_without_expanding_s
|
||||
assert stage.diffusion_config.model_config["default_robot_embodiment"] == "roboarena"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("disabled", [True, False])
|
||||
def test_frontend_log_stats_flag_is_not_an_unowned_stage_argument(disabled):
|
||||
from vllm_omni.engine.stage_init_utils import build_engine_args_dict_from_omni_stage_config
|
||||
|
||||
config = _from_pipeline_key("dots_tts", cli_overrides={"disable_log_stats": disabled})
|
||||
assert config.stage_configs
|
||||
engine_args = build_engine_args_dict_from_omni_stage_config(config.stage_by_id(0), model="test-model")
|
||||
assert "disable_log_stats" not in engine_args
|
||||
|
||||
|
||||
def test_from_pipeline_config_applies_cli_overrides_without_stage_config_runtime_bridge():
|
||||
omni_config = _from_pipeline_key(
|
||||
"qwen3_tts",
|
||||
@@ -261,6 +271,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 +593,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 +631,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 +1326,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
|
||||
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""The omni scheduler must stay on the v1 model runner, like every omni worker.
|
||||
|
||||
vLLM 0.28 resolved this config to v1; 0.29 ends its fallback chain with v2. When
|
||||
only the workers forced v1, the scheduler took its v2 fast path -- which omits
|
||||
resumed-request token ids -- while the v1 runner still read them, so resuming a
|
||||
request raised ``KeyError: <req_id>`` in ``_update_states`` and killed the engine
|
||||
core (Multi-Replica Startup Test).
|
||||
|
||||
The default is upstream's to change, so this pins Omni's side of the contract
|
||||
rather than the default itself.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm_omni.core.sched.omni_scheduler_mixin import OmniSchedulerMixin
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
class _Scheduler(OmniSchedulerMixin):
|
||||
"""Minimal carrier for the shared init hook both omni schedulers call."""
|
||||
|
||||
def __init__(self, *, use_v2_model_runner: bool) -> None:
|
||||
self.use_v2_model_runner = use_v2_model_runner
|
||||
self.vllm_config = SimpleNamespace(
|
||||
model_config=SimpleNamespace(
|
||||
async_chunk=False,
|
||||
stage_id=0,
|
||||
pooling_output_decoder=None,
|
||||
)
|
||||
)
|
||||
self._init_omni_io_scheduling_state()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("initial", [True, False])
|
||||
def test_scheduler_ends_on_v1_model_runner(initial: bool) -> None:
|
||||
"""Whatever upstream resolves, the omni scheduler runs v1."""
|
||||
assert _Scheduler(use_v2_model_runner=initial).use_v2_model_runner is False
|
||||
|
||||
|
||||
def test_v2_default_does_not_reach_the_resumed_request_fast_path() -> None:
|
||||
"""The v2 fast path is what dropped resumed-request token ids.
|
||||
|
||||
``OmniGenerationScheduler`` branches on ``use_v2_model_runner`` when it
|
||||
assembles SchedulerOutput; forcing it false keeps the v1 assembly that
|
||||
carries ``all_token_ids`` for resumed requests, which the v1 runner reads.
|
||||
"""
|
||||
scheduler = _Scheduler(use_v2_model_runner=True)
|
||||
|
||||
assert not scheduler.use_v2_model_runner, (
|
||||
"scheduler would take the v2 fast path while omni workers run v1; "
|
||||
"resumed requests then KeyError in _update_states"
|
||||
)
|
||||
@@ -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:
|
||||
|
||||
@@ -13,9 +13,6 @@ from tests.helpers.runtime import OmniServer, OmniServerParams, OnlineOmniClient
|
||||
|
||||
pytestmark = [pytest.mark.slow, pytest.mark.diffusion]
|
||||
|
||||
# https://github.com/vllm-project/vllm-omni/issues/3649 — invalid inputs still HTTP 200 / timeout / missing validation.
|
||||
_SKIP_ISSUE_3649 = pytest.mark.skip(reason="https://github.com/vllm-project/vllm-omni/issues/3649")
|
||||
|
||||
_PARAMS = [
|
||||
pytest.param(
|
||||
OmniServerParams(
|
||||
@@ -36,10 +33,8 @@ _PARAMS = [
|
||||
@pytest.mark.parametrize(
|
||||
"overrides, err_message",
|
||||
[
|
||||
pytest.param({"input": ""}, ("cannot be empty", "input"), id="input_empty", marks=_SKIP_ISSUE_3649),
|
||||
pytest.param(
|
||||
{"input": " "}, ("cannot be empty", "input"), id="input_whitespace_only", marks=_SKIP_ISSUE_3649
|
||||
),
|
||||
pytest.param({"input": ""}, ("cannot be empty", "input"), id="input_empty"),
|
||||
pytest.param({"input": " "}, ("cannot be empty", "input"), id="input_whitespace_only"),
|
||||
pytest.param({"input": 123}, ("input", "a valid string"), id="input_wrong_type"),
|
||||
pytest.param(
|
||||
{"response_format": "mpeg"},
|
||||
@@ -54,10 +49,8 @@ _PARAMS = [
|
||||
("sse", "stream_format", "value_error", "not a supported stream_format"),
|
||||
id="stream_format_sse_blocked",
|
||||
),
|
||||
pytest.param(
|
||||
{"audio_length": -1.0}, ("audio_end_in_s", "higher than", "audio_start_in_s"), id="audio_length_negative"
|
||||
),
|
||||
pytest.param({"audio_length": 0}, "audio_length", id="audio_length_zero", marks=_SKIP_ISSUE_3649),
|
||||
pytest.param({"audio_length": -1.0}, ("audio_length", "greater_than", "0"), id="audio_length_negative"),
|
||||
pytest.param({"audio_length": 0}, ("audio_length", "greater_than", "0"), id="audio_length_zero"),
|
||||
# ``OmniOpenAIServingAudioGenerate`` only forwards ``audio_start`` when ``audio_length`` is set.
|
||||
pytest.param(
|
||||
{"audio_start": -0.5, "audio_length": 5.0},
|
||||
@@ -67,26 +60,30 @@ _PARAMS = [
|
||||
pytest.param(
|
||||
{"negative_prompt": ["noise"]}, ("negative_prompt", "a valid string"), id="negative_prompt_wrong_type"
|
||||
),
|
||||
pytest.param({"guidance_scale": -1.0}, "guidance_scale", id="guidance_scale_negative", marks=_SKIP_ISSUE_3649),
|
||||
pytest.param({"guidance_scale": 0}, "guidance_scale", id="guidance_scale_zero", marks=_SKIP_ISSUE_3649),
|
||||
pytest.param(
|
||||
{"guidance_scale": -1.0},
|
||||
("guidance_scale", "greater_than_equal", "0"),
|
||||
id="guidance_scale_negative",
|
||||
),
|
||||
pytest.param(
|
||||
{"num_inference_steps": 0},
|
||||
("num_inference_steps", "greater than or equal to 1"),
|
||||
("num_inference_steps", "greater_than_equal", "1"),
|
||||
id="num_inference_steps_zero",
|
||||
),
|
||||
pytest.param(
|
||||
{"num_inference_steps": -1},
|
||||
("num_inference_steps", "greater than or equal to 1"),
|
||||
("num_inference_steps", "greater_than_equal", "1"),
|
||||
id="num_inference_steps_negative",
|
||||
),
|
||||
pytest.param(
|
||||
{"num_inference_steps": 6000},
|
||||
"num_inference_steps",
|
||||
("num_inference_steps", "less_than_equal", "1000"),
|
||||
id="num_inference_steps_above_max",
|
||||
marks=_SKIP_ISSUE_3649,
|
||||
),
|
||||
pytest.param(
|
||||
{"guidance_scale": 1001.0}, "guidance_scale", id="guidance_scale_above_max", marks=_SKIP_ISSUE_3649
|
||||
{"guidance_scale": 1001.0},
|
||||
("guidance_scale", "less_than_equal", "1000"),
|
||||
id="guidance_scale_above_max",
|
||||
),
|
||||
pytest.param(
|
||||
{"audio_length": 86401.0}, ("Requested audio length", "exceeds maximum"), id="audio_length_above_max"
|
||||
|
||||
@@ -13,6 +13,12 @@ from vllm_omni.diffusion.attention.backends.sdpa import SDPAImpl
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
|
||||
def _clear_hub_module_cache(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
from vllm_omni.diffusion.attention.backends import flash_attn_hub
|
||||
|
||||
monkeypatch.setattr(flash_attn_hub, "_hub_modules", {})
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
@pytest.mark.cpu
|
||||
def test_explicit_kernels_hub_selection_does_not_fallback(monkeypatch: pytest.MonkeyPatch):
|
||||
@@ -54,6 +60,74 @@ def test_explicit_kernels_hub_selection_does_not_fallback(monkeypatch: pytest.Mo
|
||||
CudaOmniPlatform.get_diffusion_attn_backend_cls("FLASH_ATTN_3_HUB", head_size=64)
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
@pytest.mark.cpu
|
||||
def test_explicit_kernels_hub_variant_miss_does_not_fallback(monkeypatch: pytest.MonkeyPatch):
|
||||
"""Explicit Hub backends must fail loudly when no build variant resolves (#6971)."""
|
||||
from vllm.platforms.interface import DeviceCapability
|
||||
|
||||
from vllm_omni.diffusion.envs import PACKAGES_CHECKER
|
||||
from vllm_omni.platforms.cuda.platform import CudaOmniPlatform
|
||||
|
||||
monkeypatch.setattr(
|
||||
CudaOmniPlatform,
|
||||
"get_device_capability",
|
||||
classmethod(lambda cls, device_id=0: DeviceCapability(9, 0)),
|
||||
)
|
||||
monkeypatch.setattr(PACKAGES_CHECKER, "get_packages_info", lambda: {"has_flash_attn": True})
|
||||
_clear_hub_module_cache(monkeypatch)
|
||||
|
||||
kernels_module = types.ModuleType("kernels")
|
||||
|
||||
def _missing_variant(repo_id, version=None, **kwargs):
|
||||
raise FileNotFoundError(f"Cannot find a build variant for this system in {repo_id}")
|
||||
|
||||
kernels_module.get_kernel = _missing_variant # type: ignore[attr-defined]
|
||||
monkeypatch.setitem(sys.modules, "kernels", kernels_module)
|
||||
|
||||
with pytest.raises(RuntimeError, match="no compatible build"):
|
||||
CudaOmniPlatform.get_diffusion_attn_backend_cls("FLASH_ATTN_3_HUB", head_size=64)
|
||||
with pytest.raises(RuntimeError, match="no compatible build"):
|
||||
CudaOmniPlatform.get_diffusion_attn_backend_cls("FLASH_ATTN_HUB", head_size=64)
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
@pytest.mark.cpu
|
||||
def test_explicit_kernels_hub_preflight_uses_v2_when_v1_misses(monkeypatch: pytest.MonkeyPatch):
|
||||
"""Preflight must share _load_hub_module's (1, 2) policy, not pin version=1."""
|
||||
from vllm.platforms.interface import DeviceCapability
|
||||
|
||||
from vllm_omni.diffusion.attention.backends.registry import DiffusionAttentionBackendEnum
|
||||
from vllm_omni.diffusion.envs import PACKAGES_CHECKER
|
||||
from vllm_omni.platforms.cuda.platform import CudaOmniPlatform
|
||||
|
||||
monkeypatch.setattr(
|
||||
CudaOmniPlatform,
|
||||
"get_device_capability",
|
||||
classmethod(lambda cls, device_id=0: DeviceCapability(9, 0)),
|
||||
)
|
||||
monkeypatch.setattr(PACKAGES_CHECKER, "get_packages_info", lambda: {"has_flash_attn": True})
|
||||
_clear_hub_module_cache(monkeypatch)
|
||||
|
||||
kernels_module = types.ModuleType("kernels")
|
||||
versions_tried: list[int | None] = []
|
||||
|
||||
def _v1_miss_v2_hit(repo_id, version=None, **kwargs):
|
||||
versions_tried.append(version)
|
||||
if version == 1:
|
||||
raise FileNotFoundError(f"Cannot find a build variant for this system in {repo_id}")
|
||||
return types.SimpleNamespace(name=f"{repo_id}@v{version}")
|
||||
|
||||
kernels_module.get_kernel = _v1_miss_v2_hit # type: ignore[attr-defined]
|
||||
monkeypatch.setitem(sys.modules, "kernels", kernels_module)
|
||||
|
||||
fa3_path = CudaOmniPlatform.get_diffusion_attn_backend_cls("FLASH_ATTN_3_HUB", head_size=64)
|
||||
assert fa3_path == DiffusionAttentionBackendEnum.FLASH_ATTN_3_HUB.get_path()
|
||||
fa2_path = CudaOmniPlatform.get_diffusion_attn_backend_cls("FLASH_ATTN_HUB", head_size=64)
|
||||
assert fa2_path == DiffusionAttentionBackendEnum.FLASH_ATTN_HUB.get_path()
|
||||
assert versions_tried == [1, 2, 1, 2]
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
@pytest.mark.cpu
|
||||
def test_explicit_flash_attention_unavailable_does_not_fallback(monkeypatch: pytest.MonkeyPatch):
|
||||
|
||||
@@ -279,17 +279,17 @@ def _install_native_modules(monkeypatch: pytest.MonkeyPatch, events: list[tuple]
|
||||
group = SimpleNamespace(get_metadata_builder=lambda _index: SimpleNamespace(reorder_batch_threshold=None))
|
||||
return [[group], [group]], "cg-support", [4, 8]
|
||||
|
||||
# vLLM 0.29 dropped attn_groups and cache_dtype from init_kv_cache: the
|
||||
# layout now rides on the resolved CacheConfig.kv_cache_layout instead.
|
||||
def init_cache(
|
||||
runner_kv_caches,
|
||||
forward_context,
|
||||
kv_cache_config,
|
||||
attn_groups,
|
||||
device,
|
||||
cache_dtype,
|
||||
kernel_block_sizes,
|
||||
vllm_config,
|
||||
):
|
||||
events.append(("cache", kv_cache_config, attn_groups, kernel_block_sizes))
|
||||
events.append(("cache", kv_cache_config, kernel_block_sizes))
|
||||
runner_kv_caches.extend(["cache-0", "cache-1"])
|
||||
return {"layer-0": "tensor-0", "layer-1": "tensor-1"}
|
||||
|
||||
|
||||
@@ -299,8 +299,10 @@ def test_minus_one_max_model_len_is_auto_fitted_by_native_cache_sizing() -> None
|
||||
)
|
||||
|
||||
assert vllm_config.model_config.original_max_model_len == -1
|
||||
# Sixteen physical pages provide ``16 * block_size`` tokens. The native
|
||||
# backend chooses the block geometry, so keep this assertion backend
|
||||
# Sixteen physical pages provide ``(16 - 1) * block_size`` tokens: vLLM 0.29
|
||||
# subtracts the null block that BlockPool permanently holds back before
|
||||
# sizing (check_enough_kv_cache_memory), so only 15 pages are usable. The
|
||||
# native backend chooses the block geometry, so keep this assertion backend
|
||||
# independent instead of assuming the generic 16-token block size.
|
||||
expected_max_model_len = min(model_limit, spec.block_size * 16)
|
||||
expected_max_model_len = min(model_limit, spec.block_size * (16 - 1))
|
||||
assert vllm_config.model_config.max_model_len == expected_max_model_len
|
||||
@@ -0,0 +1,147 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Physical KV cache layout selection and propagation for the Diffusion cache."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from vllm.config import CacheConfig
|
||||
from vllm.v1.kv_cache_interface import FullAttentionSpec
|
||||
from vllm.v1.kv_cache_layout import KVCacheLayout
|
||||
|
||||
from vllm_omni.diffusion.diffusion_kv.layout import (
|
||||
DEFAULT_DIFFUSION_KV_CACHE_LAYOUT,
|
||||
adopt_kv_cache_layout,
|
||||
assert_backend_layout_supported,
|
||||
build_kv_cache_tensor,
|
||||
resolve_diffusion_kv_cache_layout,
|
||||
)
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu, pytest.mark.diffusion]
|
||||
|
||||
|
||||
def _config():
|
||||
return SimpleNamespace(cache_config=CacheConfig())
|
||||
|
||||
|
||||
class _DenseBackend:
|
||||
@classmethod
|
||||
def indexes_kv_by_block_stride(cls) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
class _BlockStrideBackend:
|
||||
@classmethod
|
||||
def indexes_kv_by_block_stride(cls) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
def test_default_layout_is_not_block_outermost() -> None:
|
||||
"""The default reproduces the pre-0.29 indexes_kv_by_block_stride=False."""
|
||||
vllm_config = _config()
|
||||
layout = resolve_diffusion_kv_cache_layout(vllm_config)
|
||||
|
||||
assert layout is DEFAULT_DIFFUSION_KV_CACHE_LAYOUT
|
||||
assert layout.is_block_outermost is False
|
||||
assert vllm_config.cache_config.get_resolved_kv_cache_layout() is layout
|
||||
|
||||
|
||||
def test_block_stride_backend_selects_block_outermost_layout() -> None:
|
||||
layout = resolve_diffusion_kv_cache_layout(_config(), indexes_kv_by_block_stride=True)
|
||||
|
||||
assert layout.is_block_outermost is True
|
||||
|
||||
|
||||
def test_resolution_is_idempotent() -> None:
|
||||
vllm_config = _config()
|
||||
|
||||
assert resolve_diffusion_kv_cache_layout(vllm_config) is resolve_diffusion_kv_cache_layout(vllm_config)
|
||||
|
||||
|
||||
def test_contradicting_requirement_raises_instead_of_misaddressing() -> None:
|
||||
vllm_config = _config()
|
||||
resolve_diffusion_kv_cache_layout(vllm_config)
|
||||
|
||||
with pytest.raises(ValueError, match="contradicts the attention"):
|
||||
resolve_diffusion_kv_cache_layout(vllm_config, indexes_kv_by_block_stride=True)
|
||||
|
||||
|
||||
def test_preset_layout_is_honoured() -> None:
|
||||
vllm_config = _config()
|
||||
vllm_config.cache_config.kv_cache_layout = KVCacheLayout.BLNHC.name
|
||||
|
||||
layout = resolve_diffusion_kv_cache_layout(vllm_config, indexes_kv_by_block_stride=True)
|
||||
|
||||
assert layout is KVCacheLayout.BLNHC
|
||||
|
||||
|
||||
def test_backend_assertion_is_quiet_until_the_layout_is_resolved() -> None:
|
||||
"""Workers collect specs before the control plane hands them the layout."""
|
||||
vllm_config = _config()
|
||||
|
||||
assert_backend_layout_supported(vllm_config, _BlockStrideBackend) # unresolved: nothing to check
|
||||
|
||||
resolve_diffusion_kv_cache_layout(vllm_config)
|
||||
assert_backend_layout_supported(vllm_config, _DenseBackend)
|
||||
assert_backend_layout_supported(vllm_config, None)
|
||||
with pytest.raises(ValueError, match="contradicts the attention"):
|
||||
assert_backend_layout_supported(vllm_config, _BlockStrideBackend)
|
||||
|
||||
|
||||
def test_worker_adopts_the_layout_carried_on_the_kv_cache_config() -> None:
|
||||
"""Diffusion workers receive only a KVCacheConfig, so the name rides on it."""
|
||||
worker = _config()
|
||||
shipped = SimpleNamespace(kv_cache_layout=KVCacheLayout.BLNHC.name)
|
||||
|
||||
assert adopt_kv_cache_layout(worker, shipped) is KVCacheLayout.BLNHC
|
||||
assert worker.cache_config.get_resolved_kv_cache_layout() is KVCacheLayout.BLNHC
|
||||
|
||||
|
||||
def test_worker_without_a_carried_layout_falls_back_to_the_same_default() -> None:
|
||||
worker = _config()
|
||||
|
||||
assert adopt_kv_cache_layout(worker, SimpleNamespace(kv_cache_layout=None)) is DEFAULT_DIFFUSION_KV_CACHE_LAYOUT
|
||||
|
||||
|
||||
def test_worker_disagreeing_with_the_control_plane_raises() -> None:
|
||||
worker = _config()
|
||||
resolve_diffusion_kv_cache_layout(worker)
|
||||
|
||||
with pytest.raises(ValueError, match="disagrees with the layout"):
|
||||
adopt_kv_cache_layout(worker, SimpleNamespace(kv_cache_layout=KVCacheLayout.BLNHC.name))
|
||||
|
||||
|
||||
def test_block_stride_requirement_propagates_control_plane_to_worker() -> None:
|
||||
"""A block-stride backend must reach the worker as a block-outermost layout.
|
||||
|
||||
Covers the whole seam: the control plane resolves with the requirement, the
|
||||
name rides on each rank-local KVCacheConfig, the worker adopts it, and the
|
||||
backend contract check then passes instead of raising.
|
||||
"""
|
||||
control_plane = _config()
|
||||
layout = resolve_diffusion_kv_cache_layout(control_plane, indexes_kv_by_block_stride=True)
|
||||
assert layout.is_block_outermost is True
|
||||
|
||||
shipped = SimpleNamespace(kv_cache_layout=layout.name)
|
||||
|
||||
worker = _config()
|
||||
assert adopt_kv_cache_layout(worker, shipped) is layout
|
||||
# The worker's own backend requirement now agrees with what it was handed.
|
||||
assert_backend_layout_supported(worker, _BlockStrideBackend)
|
||||
with pytest.raises(ValueError, match="contradicts the attention"):
|
||||
assert_backend_layout_supported(worker, _DenseBackend)
|
||||
|
||||
|
||||
def test_tensor_strides_come_from_the_upstream_derivation() -> None:
|
||||
spec = FullAttentionSpec(block_size=16, num_kv_heads=2, head_size=8, dtype=torch.bfloat16)
|
||||
|
||||
tensor = build_kv_cache_tensor(spec, 4, ["layer0", "layer1"])
|
||||
|
||||
assert tensor.layers == ["layer0", "layer1"]
|
||||
assert tensor.size == spec.page_size_bytes * 2 * 4
|
||||
# Layer-outermost: each layer owns a contiguous run of its own blocks.
|
||||
assert tensor.layer_stride == spec.page_size_bytes * 4
|
||||
assert tensor.block_stride == spec.page_size_bytes
|
||||
@@ -1,11 +1,12 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
import vllm.v1.core.single_type_kv_cache_manager as native_kv_managers
|
||||
from vllm.v1.kv_cache_interface import FullAttentionSpec, KVCacheConfig, KVCacheGroupSpec, KVCacheTensor
|
||||
from vllm.v1.kv_cache_interface import FullAttentionSpec, KVCacheConfig, KVCacheGroupSpec
|
||||
|
||||
from tests.helpers.kv_layout import build_kv_cache_tensor
|
||||
from vllm_omni.diffusion.diffusion_kv.manager import DiffusionKVAdmissionError, DiffusionKVCacheManager
|
||||
from vllm_omni.diffusion.diffusion_kv.request import DiffusionKVContext, DiffusionKVRequest
|
||||
|
||||
@@ -24,7 +25,7 @@ def _config(num_blocks: int) -> KVCacheConfig:
|
||||
)
|
||||
return KVCacheConfig(
|
||||
num_blocks=num_blocks,
|
||||
kv_cache_tensors=[KVCacheTensor(size=spec.page_size_bytes * num_blocks, shared_by=["layer0"])],
|
||||
kv_cache_tensors=[build_kv_cache_tensor(spec, num_blocks, ["layer0"])],
|
||||
kv_cache_groups=[KVCacheGroupSpec(layer_names=["layer0"], kv_cache_spec=spec)],
|
||||
)
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ import torch
|
||||
from torch import nn
|
||||
from vllm.v1.kv_cache_interface import FullAttentionSpec
|
||||
|
||||
from tests.helpers.kv_layout import layout_for_backend
|
||||
from vllm_omni.diffusion.attention.backends.flash_attn import FlashAttentionImpl
|
||||
from vllm_omni.diffusion.attention.layer import Attention
|
||||
from vllm_omni.diffusion.diffusion_kv import paged_attention_adapter as adapter_module
|
||||
@@ -1239,7 +1240,8 @@ def test_layer_adapter_accepts_platform_native_backend_and_uses_rank_local_heads
|
||||
assert native_layer.num_heads == 4
|
||||
assert native_layer.num_kv_heads == 2
|
||||
assert native_layer.spec.num_kv_heads == 2
|
||||
assert native_layer.spec.indexes_kv_by_block_stride is True
|
||||
# 0.29: the flag no longer rides on the spec, it selects the layout.
|
||||
assert layout_for_backend(native_layer.attn_backend).is_block_outermost is True
|
||||
assert native_layer._q_scale_float == 1.0
|
||||
assert native_layer._k_scale_float == 1.0
|
||||
assert native_layer._v_scale_float == 1.0
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -10,12 +10,14 @@ import torch
|
||||
from torch import nn
|
||||
from torch.nn import functional as F
|
||||
from vllm.config import AttentionConfig, CacheConfig, VllmConfig, set_current_vllm_config
|
||||
from vllm.v1.kv_cache_interface import FullAttentionSpec, KVCacheConfig, KVCacheGroupSpec, KVCacheTensor
|
||||
from vllm.v1.kv_cache_interface import FullAttentionSpec, KVCacheConfig, KVCacheGroupSpec
|
||||
from vllm.v1.worker.gpu.attn_utils import init_attn_backend, init_kv_cache
|
||||
from vllm.v1.worker.gpu.block_table import BlockTables
|
||||
|
||||
from tests.helpers.kv_layout import build_kv_cache_tensor
|
||||
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
|
||||
from vllm_omni.diffusion.attention.backends.flash_attn import FlashAttentionImpl
|
||||
from vllm_omni.diffusion.diffusion_kv.layout import resolve_diffusion_kv_cache_layout
|
||||
from vllm_omni.diffusion.diffusion_kv.paged_attention_adapter import (
|
||||
DiffusionPagedAttentionAdapter,
|
||||
DiffusionPagedAttentionLayerAdapter,
|
||||
@@ -88,12 +90,7 @@ def test_adapter_executes_native_paged_attention_on_non_contiguous_blocks() -> N
|
||||
canonical_spec = native_layer.spec
|
||||
kv_cache_config = KVCacheConfig(
|
||||
num_blocks=4,
|
||||
kv_cache_tensors=[
|
||||
KVCacheTensor(
|
||||
size=canonical_spec.page_size_bytes * 4,
|
||||
shared_by=[_LAYER_NAME],
|
||||
)
|
||||
],
|
||||
kv_cache_tensors=[build_kv_cache_tensor(canonical_spec, 4, [_LAYER_NAME])],
|
||||
kv_cache_groups=[
|
||||
KVCacheGroupSpec(
|
||||
layer_names=[_LAYER_NAME],
|
||||
@@ -101,6 +98,9 @@ def test_adapter_executes_native_paged_attention_on_non_contiguous_blocks() -> N
|
||||
)
|
||||
],
|
||||
)
|
||||
# 0.29 reads the resolved physical layout when allocating; the diffusion
|
||||
# control plane pins it, so this standalone harness must too.
|
||||
resolve_diffusion_kv_cache_layout(vllm_config)
|
||||
with set_current_vllm_config(vllm_config):
|
||||
attn_groups, _, kernel_block_sizes = init_attn_backend(
|
||||
kv_cache_config,
|
||||
@@ -108,13 +108,13 @@ def test_adapter_executes_native_paged_attention_on_non_contiguous_blocks() -> N
|
||||
device,
|
||||
)
|
||||
runner_kv_caches: list[torch.Tensor | list[torch.Tensor]] = []
|
||||
# vLLM 0.29 dropped attn_groups and cache_dtype here: the layout now
|
||||
# comes from the resolved CacheConfig.kv_cache_layout inside the call.
|
||||
init_kv_cache(
|
||||
runner_kv_caches,
|
||||
vllm_config.compilation_config.static_forward_context,
|
||||
kv_cache_config,
|
||||
attn_groups,
|
||||
device,
|
||||
vllm_config.cache_config.cache_dtype,
|
||||
kernel_block_sizes,
|
||||
vllm_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
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
@@ -10,10 +10,10 @@ from vllm.v1.kv_cache_interface import (
|
||||
FullAttentionSpec,
|
||||
KVCacheConfig,
|
||||
KVCacheGroupSpec,
|
||||
KVCacheTensor,
|
||||
)
|
||||
from vllm.v1.request import RequestStatus
|
||||
|
||||
from tests.helpers.kv_layout import build_kv_cache_tensor
|
||||
from vllm_omni.diffusion.diffusion_kv.request import DiffusionKVContext, DiffusionKVRequest
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu, pytest.mark.diffusion]
|
||||
@@ -119,7 +119,7 @@ def _manager(*, enable_caching: bool) -> KVCacheManager:
|
||||
group = KVCacheGroupSpec(layer_names=["layer0"], kv_cache_spec=spec)
|
||||
config = KVCacheConfig(
|
||||
num_blocks=8,
|
||||
kv_cache_tensors=[KVCacheTensor(size=spec.page_size_bytes * 8, shared_by=["layer0"])],
|
||||
kv_cache_tensors=[build_kv_cache_tensor(spec, 8, ["layer0"])],
|
||||
kv_cache_groups=[group],
|
||||
)
|
||||
return KVCacheManager(
|
||||
|
||||
@@ -8,9 +8,10 @@ from unittest.mock import Mock
|
||||
import pytest
|
||||
import torch
|
||||
from torch import nn
|
||||
from vllm.v1.kv_cache_interface import FullAttentionSpec, KVCacheConfig, KVCacheGroupSpec, KVCacheTensor
|
||||
from vllm.v1.kv_cache_interface import FullAttentionSpec, KVCacheConfig, KVCacheGroupSpec
|
||||
|
||||
import vllm_omni.diffusion.worker.diffusion_worker as diffusion_worker_module
|
||||
from tests.helpers.kv_layout import build_kv_cache_tensor, layout_for_backend
|
||||
from vllm_omni.diffusion.attention.layer import Attention
|
||||
from vllm_omni.diffusion.diffusion_kv.config import DiffusionKVCacheMode
|
||||
from vllm_omni.diffusion.worker.diffusion_model_runner import DiffusionModelRunner
|
||||
@@ -79,7 +80,9 @@ def test_runner_discovers_native_spec_from_loaded_attention() -> None:
|
||||
assert spec.num_kv_heads == 2
|
||||
assert spec.head_size == 8
|
||||
assert spec.dtype is torch.bfloat16
|
||||
assert spec.indexes_kv_by_block_stride is True
|
||||
# vLLM 0.29 moved the block-stride decision off the spec onto the resolved
|
||||
# physical layout; the backend's declaration must still select one.
|
||||
assert layout_for_backend(_Backend).is_block_outermost is True
|
||||
assert spec.non_causal is True
|
||||
|
||||
|
||||
@@ -112,7 +115,7 @@ def test_runner_retains_matching_rank_local_config() -> None:
|
||||
spec = runner.get_kv_cache_spec()["image_attention"]
|
||||
config = KVCacheConfig(
|
||||
num_blocks=8,
|
||||
kv_cache_tensors=[KVCacheTensor(size=spec.page_size_bytes * 8, shared_by=["image_attention"])],
|
||||
kv_cache_tensors=[build_kv_cache_tensor(spec, 8, ["image_attention"])],
|
||||
kv_cache_groups=[KVCacheGroupSpec(layer_names=["image_attention"], kv_cache_spec=spec)],
|
||||
)
|
||||
|
||||
@@ -126,7 +129,7 @@ def test_runner_rejects_rank_local_config_for_different_layers() -> None:
|
||||
spec = runner.get_kv_cache_spec()["image_attention"]
|
||||
config = KVCacheConfig(
|
||||
num_blocks=8,
|
||||
kv_cache_tensors=[KVCacheTensor(size=spec.page_size_bytes * 8, shared_by=["other_attention"])],
|
||||
kv_cache_tensors=[build_kv_cache_tensor(spec, 8, ["other_attention"])],
|
||||
kv_cache_groups=[KVCacheGroupSpec(layer_names=["other_attention"], kv_cache_spec=spec)],
|
||||
)
|
||||
|
||||
|
||||
@@ -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
|
||||
)
|
||||
@@ -5,7 +5,7 @@ import pytest
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
from tests.helpers.mark import hardware_test
|
||||
from tests.helpers.mark import hardware_marks
|
||||
from vllm_omni.diffusion.layers.activation import SiluAndMul
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.diffusion]
|
||||
@@ -19,9 +19,17 @@ def test_silu_and_mul_native_matches_packed_reference() -> None:
|
||||
torch.testing.assert_close(SiluAndMul().forward_native(packed), F.silu(gate) * up)
|
||||
|
||||
|
||||
@hardware_test(res={"npu": "A3"}, num_cards=1)
|
||||
def test_silu_and_mul_npu_matches_packed_reference() -> None:
|
||||
packed = torch.randn(257, 256, device="npu", dtype=torch.bfloat16)
|
||||
@pytest.mark.parametrize(
|
||||
"dtype",
|
||||
[
|
||||
pytest.param(torch.bfloat16, marks=hardware_marks(res={"npu": "A2"}, num_cards=1), id="A2-bf16"),
|
||||
pytest.param(torch.bfloat16, marks=hardware_marks(res={"npu": "A3"}, num_cards=1), id="A3-bf16"),
|
||||
pytest.param(torch.bfloat16, marks=hardware_marks(res={"npu": "A5"}, num_cards=1), id="A5-bf16"),
|
||||
pytest.param(torch.float16, marks=hardware_marks(res={"npu": "310P"}, num_cards=1), id="310P-fp16"),
|
||||
],
|
||||
)
|
||||
def test_silu_and_mul_npu_matches_packed_reference(dtype: torch.dtype) -> None:
|
||||
packed = torch.randn(257, 256, device="npu", dtype=dtype)
|
||||
gate, up = packed.chunk(2, dim=-1)
|
||||
|
||||
torch.testing.assert_close(
|
||||
|
||||
@@ -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 shared AdaLayerNorm layers used by FLUX and other models."""
|
||||
|
||||
import os
|
||||
@@ -46,7 +46,7 @@ def _force_default_gemm(monkeypatch):
|
||||
|
||||
monkeypatch.setattr(
|
||||
"vllm.model_executor.layers.linear.dispatch_unquantized_gemm",
|
||||
lambda: default_unquantized_gemm,
|
||||
lambda *_args, **_kwargs: default_unquantized_gemm,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
"""
|
||||
Shape broadcasting regression tests for RotaryEmbedding.forward_native.
|
||||
|
||||
@@ -16,7 +16,11 @@ import types
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm_omni.diffusion.layers.rope import RotaryEmbedding, apply_rotary_emb_mindiesd
|
||||
from vllm_omni.diffusion.layers.rope import (
|
||||
RotaryEmbedding,
|
||||
RotaryEmbeddingWan,
|
||||
apply_rotary_emb_mindiesd,
|
||||
)
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
@@ -239,6 +243,25 @@ class TestRotaryEmbeddingNativeShapeRegression:
|
||||
assert not torch.isnan(output).any()
|
||||
|
||||
|
||||
def test_cuda_paths_fall_back_without_vendored_rotary_kernel() -> None:
|
||||
"""Source/CPU installs need not contain the wheel-vendored CUDA kernel."""
|
||||
x = torch.randn(1, 5, 2, 8)
|
||||
|
||||
rope = RotaryEmbedding(is_neox_style=True)
|
||||
rope.apply_rotary_emb_vllm_flash_attn = None
|
||||
output = rope.forward_cuda(x, torch.randn(5, 4), torch.randn(5, 4))
|
||||
assert output.shape == x.shape
|
||||
|
||||
wan_rope = RotaryEmbeddingWan(is_neox_style=False, half_head_dim=True)
|
||||
wan_rope.apply_rotary_emb_vllm_flash_attn = None
|
||||
output = wan_rope.forward_cuda(
|
||||
x,
|
||||
torch.randn(1, 5, 1, 4),
|
||||
torch.randn(1, 5, 1, 4),
|
||||
)
|
||||
assert output.shape == x.shape
|
||||
|
||||
|
||||
def test_mindie_full_dim_rope_keeps_h3_cos_sin_layout(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""H3 passes complete rotary dims to MindIE instead of the CUDA half-dim layout."""
|
||||
captured: dict[str, object] = {}
|
||||
|
||||
@@ -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
|
||||
@@ -59,7 +59,7 @@ def _force_default_gemm(monkeypatch):
|
||||
|
||||
monkeypatch.setattr(
|
||||
"vllm.model_executor.layers.linear.dispatch_unquantized_gemm",
|
||||
lambda: default_unquantized_gemm,
|
||||
lambda *_args, **_kwargs: default_unquantized_gemm,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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
|
||||
|
||||
"""Equivalence test for DreamZero self-attn QKV fusion.
|
||||
|
||||
@@ -52,7 +52,7 @@ def _force_default_gemm(monkeypatch):
|
||||
|
||||
monkeypatch.setattr(
|
||||
"vllm.model_executor.layers.linear.dispatch_unquantized_gemm",
|
||||
lambda: default_unquantized_gemm,
|
||||
lambda *_args, **_kwargs: default_unquantized_gemm,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -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 GLM-Image quantization support (W4A16/AutoRound).
|
||||
|
||||
These tests verify that the GLM-Image DiT transformer correctly accepts and uses
|
||||
@@ -69,7 +69,7 @@ def _force_default_gemm(monkeypatch):
|
||||
|
||||
monkeypatch.setattr(
|
||||
"vllm.model_executor.layers.linear.dispatch_unquantized_gemm",
|
||||
lambda: default_unquantized_gemm,
|
||||
lambda *_args, **_kwargs: default_unquantized_gemm,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -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)
|
||||
@@ -186,7 +186,7 @@ def test_ltx25_missing_gemma4_recommends_supported_transformers_range(monkeypatc
|
||||
ltx2_components.initialize_pipeline_components(pipe, od_config)
|
||||
|
||||
assert str(exc_info.value) == (
|
||||
"LTX-2.5 requires Gemma4UnifiedForConditionalGeneration; install transformers>=5.10.1,<5.15."
|
||||
"LTX-2.5 requires Gemma4UnifiedForConditionalGeneration; install transformers>=5.13.0,<5.15."
|
||||
)
|
||||
|
||||
|
||||
@@ -387,7 +387,7 @@ def test_ltx25_natten_failure_has_actionable_omni_remedy(monkeypatch):
|
||||
MissingNattenProcessor,
|
||||
)
|
||||
|
||||
with pytest.raises(RuntimeError, match=r"kernels==0\.15\.2.*supported GPU.*allow Hub access"):
|
||||
with pytest.raises(RuntimeError, match=r"kernels==0\.16\.1.*supported GPU.*allow Hub access"):
|
||||
ltx2_components._create_ltx25_natten_processor()
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Native FNA against an independent, test-only explicit neighborhood mask."""
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from torch.nn.attention import SDPBackend, sdpa_kernel
|
||||
|
||||
from vllm_omni.diffusion.models.ltx2.ops import resolve_ltx2_vae_operators
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cuda, pytest.mark.diffusion]
|
||||
|
||||
|
||||
def _selected_fna():
|
||||
if not current_omni_platform.is_available():
|
||||
pytest.skip("No accelerator is available")
|
||||
operators = resolve_ltx2_vae_operators(current_omni_platform.get_torch_device())
|
||||
if operators is None or operators.fna is None:
|
||||
pytest.skip("LTX DiffVAE FNA is unavailable for this device or installation")
|
||||
return operators.fna
|
||||
|
||||
|
||||
def _load_fna_ops():
|
||||
return pytest.importorskip("vllm_omni.diffusion.models.ltx2.ops.fna", exc_type=ImportError)
|
||||
|
||||
|
||||
def _pack(x, tile):
|
||||
b, t, h, w, heads, dim = x.shape
|
||||
tt, th, tw = tile
|
||||
nt, nh, nw = (t + tt - 1) // tt, (h + th - 1) // th, (w + tw - 1) // tw
|
||||
padded = x.new_zeros((b, nt * tt, nh * th, nw * tw, heads, dim))
|
||||
padded[:, :t, :h, :w] = x
|
||||
# Outer and inner spatial tiles both flatten in W,H,T order.
|
||||
return (
|
||||
padded.view(b, nt, tt, nh, th, nw, tw, heads, dim)
|
||||
.permute(0, 5, 3, 1, 6, 4, 2, 7, 8)
|
||||
.reshape(b, nt * nh * nw * tt * th * tw, heads, dim)
|
||||
)
|
||||
|
||||
|
||||
def _unpack(x, shape):
|
||||
t, h, w = shape
|
||||
b, _, heads, dim = x.shape
|
||||
nt, nh, nw = ((n + 3) // 4 for n in shape)
|
||||
return (
|
||||
x.view(b, nw, nh, nt, 4, 4, 4, heads, dim)
|
||||
.permute(0, 3, 6, 2, 5, 1, 4, 7, 8)
|
||||
.reshape(b, nt * 4, nh * 4, nw * 4, heads, dim)[:, :t, :h, :w]
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("batch,shape", [(1, (11, 11, 11)), (2, (13, 12, 17))])
|
||||
@torch.inference_mode()
|
||||
def test_fna_matches_explicit_inward_shift_mask(batch, shape):
|
||||
fna = _selected_fna()
|
||||
generator = torch.Generator(device="cuda").manual_seed(42)
|
||||
q, k, v = [
|
||||
torch.randn(batch, *shape, 4, 64, device="cuda", dtype=torch.bfloat16, generator=generator) for _ in range(3)
|
||||
]
|
||||
q = q * 0.125
|
||||
coordinates = torch.stack(
|
||||
torch.meshgrid(*(torch.arange(n, device="cuda") for n in shape), indexing="ij"), dim=-1
|
||||
).reshape(-1, 3)
|
||||
start = (coordinates - 5).clamp_min(0).minimum(torch.tensor(shape, device="cuda") - 11)
|
||||
mask = ((coordinates[None] >= start[:, None]) & (coordinates[None] < start[:, None] + 11)).all(-1)
|
||||
with sdpa_kernel(SDPBackend.MATH):
|
||||
expected = (
|
||||
torch.nn.functional.scaled_dot_product_attention(
|
||||
*(x.flatten(1, 3).transpose(1, 2).float() for x in (q, k, v)), attn_mask=mask, scale=1.0
|
||||
)
|
||||
.transpose(1, 2)
|
||||
.reshape(q.shape)
|
||||
)
|
||||
actual = _unpack(
|
||||
fna(_pack(q, (4, 4, 4)), _pack(k, (4, 4, 8)), _pack(v, (4, 4, 8)), shape=shape, window=(11, 11, 11)),
|
||||
shape,
|
||||
).float()
|
||||
assert actual.isfinite().all()
|
||||
assert float((actual - expected).norm() / expected.norm()) < 0.005
|
||||
torch.testing.assert_close(actual, expected, atol=0.008, rtol=0.025)
|
||||
|
||||
|
||||
def test_fna_rejects_cpu_without_fallback():
|
||||
fna_ops = _load_fna_ops()
|
||||
x = torch.zeros(1, 64, 4, 64, dtype=torch.bfloat16)
|
||||
with pytest.raises(ValueError, match="CUDA BF16"):
|
||||
fna_ops.fna3d_tilelang(x, x, x, shape=(11, 11, 11), window=(11, 11, 11))
|
||||
@@ -0,0 +1,409 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm_omni.diffusion.models.ltx2.ops import qk_rms_norm as qk_rms_norm_ops
|
||||
from vllm_omni.diffusion.models.ltx2.ops import residual_adaln as residual_adaln_ops
|
||||
from vllm_omni.diffusion.models.ltx2.ops import resolve_ltx2_vae_operators
|
||||
from vllm_omni.diffusion.models.ltx2.ops import swiglu as swiglu_ops
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cuda, pytest.mark.diffusion]
|
||||
|
||||
_DIM_SPLIT = (16, 24, 24)
|
||||
|
||||
|
||||
def _selected_operators():
|
||||
if not current_omni_platform.is_available():
|
||||
pytest.skip("No accelerator is available")
|
||||
operators = resolve_ltx2_vae_operators(current_omni_platform.get_torch_device())
|
||||
if operators is None:
|
||||
pytest.skip("No LTX DiffVAE operators are available for this device")
|
||||
return operators
|
||||
|
||||
|
||||
def _selected_fna():
|
||||
operators = _selected_operators()
|
||||
if operators.fna is None:
|
||||
pytest.skip("LTX DiffVAE FNA is unavailable for this device or installation")
|
||||
return operators.fna
|
||||
|
||||
|
||||
def _load_fna_ops():
|
||||
return pytest.importorskip("vllm_omni.diffusion.models.ltx2.ops.fna", exc_type=ImportError)
|
||||
|
||||
|
||||
def test_diffvae_model_and_tests_do_not_import_tilelang_backend() -> None:
|
||||
# Use a fresh interpreter: reloading the model in this process would leave
|
||||
# already-imported distributed subclasses pointing at the old base class.
|
||||
result = subprocess.run(
|
||||
[
|
||||
sys.executable,
|
||||
"-c",
|
||||
"import sys; "
|
||||
"sys.modules['vllm_omni.diffusion.models.ltx2.ops.fna'] = None; "
|
||||
"sys.modules['vllm.tilelang_utils'] = None; "
|
||||
"from vllm_omni.diffusion.models.ltx2.vae.decoder import LTX2VideoDiffusionDecoderModel; "
|
||||
"import tests.diffusion.models.ltx2.test_ltx2_diffvae_attention; "
|
||||
"import tests.diffusion.models.ltx2.test_ltx2_diffvae_ops",
|
||||
],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=60,
|
||||
)
|
||||
assert result.returncode == 0, result.stdout + result.stderr
|
||||
|
||||
|
||||
def test_diffvae_fna_tile_map_covers_exact_neighborhood() -> None:
|
||||
fna_ops = _load_fna_ops()
|
||||
problem = fna_ops.Problem(13, 14, 17, (11, 11, 11))
|
||||
indices, counts = fna_ops.build_kv_tile_map(problem)
|
||||
q_grid_t, q_grid_h, _ = problem.q_grid
|
||||
kv_grid_t, kv_grid_h, _ = problem.kv_grid
|
||||
|
||||
for q_block in range(indices.shape[0]):
|
||||
selected = set(indices[q_block, : counts[q_block]].tolist())
|
||||
q_outer_t = q_block % q_grid_t
|
||||
q_outer_h = (q_block // q_grid_t) % q_grid_h
|
||||
q_outer_w = q_block // (q_grid_t * q_grid_h)
|
||||
for q_inner in range(fna_ops.Q_TOKENS):
|
||||
query = (
|
||||
q_outer_t * 4 + q_inner % 4,
|
||||
q_outer_h * 4 + (q_inner // 4) % 4,
|
||||
q_outer_w * 4 + q_inner // 16,
|
||||
)
|
||||
if any(index >= length for index, length in zip(query, problem.shape, strict=True)):
|
||||
continue
|
||||
starts = tuple(
|
||||
fna_ops._window_start(index, window, length)
|
||||
for index, window, length in zip(query, problem.window, problem.shape, strict=True)
|
||||
)
|
||||
for key_t in range(starts[0], starts[0] + problem.window[0]):
|
||||
for key_h in range(starts[1], starts[1] + problem.window[1]):
|
||||
for key_w in range(starts[2], starts[2] + problem.window[2]):
|
||||
key_block = ((key_w // 8) * kv_grid_h + key_h // 4) * kv_grid_t + key_t // 4
|
||||
assert key_block in selected
|
||||
|
||||
|
||||
def test_diffvae_fna_metadata_uses_static_kernel_shapes() -> None:
|
||||
fna_ops = _load_fna_ops()
|
||||
for shape in ((11, 11, 11), (13, 14, 17), (66, 96, 128), (79, 192, 192)):
|
||||
problem = fna_ops.Problem(*shape, (11, 11, 11))
|
||||
_, t_patterns, h_patterns, w_patterns = fna_ops.build_kv_tile_metadata(problem)
|
||||
assert {table.numel() for table in (t_patterns, h_patterns, w_patterns)} == {fna_ops.PATTERN_TABLE_SIZE}
|
||||
assert {limit for _, _, limit in fna_ops.build_kv_tile_buckets(problem)} <= set(fna_ops.KV_BUCKET_LIMITS)
|
||||
for ids, metadata, limit in fna_ops.build_kv_tile_buckets(problem):
|
||||
assert metadata.shape == (ids.numel(), limit)
|
||||
|
||||
|
||||
def test_diffvae_fna_rejects_oversized_packed_tile_grid() -> None:
|
||||
fna_ops = _load_fna_ops()
|
||||
with pytest.raises(ValueError, match="15-bit metadata"):
|
||||
fna_ops.Problem(128, 256, 256, (11, 11, 11))
|
||||
|
||||
|
||||
def test_diffvae_fna_propagates_launch_failures(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
fna_ops = _load_fna_ops()
|
||||
fna = _selected_fna()
|
||||
problem = fna_ops.Problem(11, 11, 11, (11, 11, 11))
|
||||
query = torch.randn(1, problem.q_length, fna_ops.HEADS, 64, device="cuda", dtype=torch.bfloat16)
|
||||
key = torch.randn(1, problem.kv_length, fna_ops.HEADS, 64, device="cuda", dtype=torch.bfloat16)
|
||||
value = torch.randn_like(key)
|
||||
calls = 0
|
||||
|
||||
def fail_launch(*args, **kwargs):
|
||||
nonlocal calls
|
||||
calls += 1
|
||||
raise RuntimeError("injected launch failure")
|
||||
|
||||
monkeypatch.setattr(fna_ops, "_fna3d_tilelang", fail_launch)
|
||||
with torch.inference_mode():
|
||||
for _ in range(2):
|
||||
with pytest.raises(RuntimeError, match="injected launch failure"):
|
||||
fna(
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
shape=problem.shape,
|
||||
window=problem.window,
|
||||
)
|
||||
assert calls == 2
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def isolated_runtime_state():
|
||||
targets = (
|
||||
(qk_rms_norm_ops, "_FAILED_ROPE_KEYS"),
|
||||
(qk_rms_norm_ops, "_VERIFIED_ROPE_KEYS"),
|
||||
(swiglu_ops, "_FAILED_KEYS"),
|
||||
(swiglu_ops, "_VERIFIED_KEYS"),
|
||||
(residual_adaln_ops, "_FAILED_ADALN_KEYS"),
|
||||
(residual_adaln_ops, "_VERIFIED_ADALN_KEYS"),
|
||||
(residual_adaln_ops, "_FAILED_ADD_DEVICES"),
|
||||
(residual_adaln_ops, "_VERIFIED_ADD_DEVICES"),
|
||||
)
|
||||
saved = [set(getattr(module, name)) for module, name in targets]
|
||||
for module, name in targets:
|
||||
getattr(module, name).clear()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
for (module, name), state in zip(targets, saved, strict=True):
|
||||
target = getattr(module, name)
|
||||
target.clear()
|
||||
target.update(state)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("dim", "rows"),
|
||||
[
|
||||
(256, 257),
|
||||
(256, 16385),
|
||||
(256, 131075),
|
||||
(512, 65539),
|
||||
(1024, 32771),
|
||||
(2048, 16387),
|
||||
],
|
||||
)
|
||||
def test_diffvae_swiglu_tiled_is_bit_exact(dim: int, rows: int, isolated_runtime_state) -> None:
|
||||
from diffusers.models.autoencoders.ltx2_diffusion_decoder import LTX2VideoVaeSwiGLU
|
||||
|
||||
operators = _selected_operators()
|
||||
generator = torch.Generator(device="cuda").manual_seed(20260829)
|
||||
hidden_states = torch.randn((1, 1, 1, rows, dim), device="cuda", dtype=torch.bfloat16, generator=generator)
|
||||
gate_weight = torch.randn((4 * dim, dim), device="cuda", dtype=torch.bfloat16, generator=generator)
|
||||
up_weight = torch.randn_like(gate_weight)
|
||||
down_weight = torch.randn((dim, 4 * dim), device="cuda", dtype=torch.bfloat16, generator=generator)
|
||||
with torch.device("meta"):
|
||||
reference = LTX2VideoVaeSwiGLU(dim, 4 * dim)
|
||||
reference.w_gate.weight = torch.nn.Parameter(gate_weight, requires_grad=False)
|
||||
reference.w_up.weight = torch.nn.Parameter(up_weight, requires_grad=False)
|
||||
reference.w_down.weight = torch.nn.Parameter(down_weight, requires_grad=False)
|
||||
|
||||
with torch.inference_mode():
|
||||
expected = reference(hidden_states)
|
||||
actual = operators.swiglu(hidden_states, gate_weight, up_weight, down_weight)
|
||||
|
||||
assert actual is not None
|
||||
assert torch.equal(actual, expected)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("dim", "expected_rows"),
|
||||
[(256, 131072), (512, 65536), (1024, 32768), (2048, 16384)],
|
||||
)
|
||||
def test_diffvae_swiglu_tile_rows_keep_a_constant_hidden_budget(dim: int, expected_rows: int) -> None:
|
||||
assert swiglu_ops._tile_rows(1_000_000, 4 * dim) == expected_rows
|
||||
|
||||
|
||||
def test_diffvae_swiglu_tiled_permanently_falls_back_after_failure(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
isolated_runtime_state,
|
||||
) -> None:
|
||||
operators = _selected_operators()
|
||||
hidden_states = torch.randn(1, 1, 1, 17, 256, device="cuda", dtype=torch.bfloat16)
|
||||
gate_weight = torch.randn(1024, 256, device="cuda", dtype=torch.bfloat16)
|
||||
up_weight = torch.randn_like(gate_weight)
|
||||
down_weight = torch.randn(256, 1024, device="cuda", dtype=torch.bfloat16)
|
||||
calls = 0
|
||||
|
||||
def fail_launch(*args, **kwargs):
|
||||
nonlocal calls
|
||||
calls += 1
|
||||
raise RuntimeError("injected launch failure")
|
||||
|
||||
monkeypatch.setattr(swiglu_ops, "_launch", fail_launch)
|
||||
with torch.inference_mode():
|
||||
assert operators.swiglu(hidden_states, gate_weight, up_weight, down_weight) is None
|
||||
assert operators.swiglu(hidden_states, gate_weight, up_weight, down_weight) is None
|
||||
|
||||
assert calls == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("residual_count", [1, 2])
|
||||
def test_diffvae_residual_rms_norm_modulate_is_bit_exact(
|
||||
residual_count: int,
|
||||
isolated_runtime_state,
|
||||
) -> None:
|
||||
operators = _selected_operators()
|
||||
generator = torch.Generator(device="cuda").manual_seed(20260829)
|
||||
shape = (2, 3, 7, 7, 256)
|
||||
x = torch.randn(shape, device="cuda", dtype=torch.bfloat16, generator=generator)
|
||||
residual_a = torch.randn_like(x)
|
||||
residual_b = torch.randn_like(x) if residual_count == 2 else None
|
||||
norm_weight = torch.randn((256,), device="cuda", dtype=torch.bfloat16, generator=generator)
|
||||
scale = torch.randn((2, 1, 1, 1, 256), device="cuda", dtype=torch.bfloat16, generator=generator)
|
||||
shift = torch.randn_like(scale)
|
||||
hidden_states = x + residual_a
|
||||
if residual_b is not None:
|
||||
hidden_states = hidden_states + residual_b
|
||||
expected = torch.nn.functional.rms_norm(hidden_states, (256,), norm_weight, eps=1e-6) * (1 + scale) + shift
|
||||
|
||||
with torch.inference_mode():
|
||||
actual = operators.residual_norm(
|
||||
x,
|
||||
residual_a,
|
||||
residual_b,
|
||||
norm_weight,
|
||||
scale,
|
||||
shift,
|
||||
1e-6,
|
||||
)
|
||||
|
||||
assert actual is not None
|
||||
assert torch.equal(actual, expected)
|
||||
|
||||
|
||||
def test_diffvae_residual_add3_is_bit_exact(isolated_runtime_state) -> None:
|
||||
operators = _selected_operators()
|
||||
generator = torch.Generator(device="cuda").manual_seed(20260829)
|
||||
tensors = [
|
||||
torch.randn((2, 3, 7, 7, 256), device="cuda", dtype=torch.bfloat16, generator=generator) for _ in range(4)
|
||||
]
|
||||
expected = tensors[0] + tensors[1]
|
||||
expected = expected + tensors[2]
|
||||
expected = expected + tensors[3]
|
||||
|
||||
with torch.inference_mode():
|
||||
actual = operators.residual_add(*tensors)
|
||||
|
||||
assert actual is not None
|
||||
assert torch.equal(actual, expected)
|
||||
|
||||
|
||||
def test_diffvae_residual_adaln_permanently_falls_back_after_failure(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
isolated_runtime_state,
|
||||
) -> None:
|
||||
operators = _selected_operators()
|
||||
shape = (1, 3, 7, 7, 256)
|
||||
x = torch.randn(shape, device="cuda", dtype=torch.bfloat16)
|
||||
residual = torch.randn_like(x)
|
||||
weight = torch.randn(256, device="cuda", dtype=torch.bfloat16)
|
||||
scale = torch.randn(1, 1, 1, 1, 256, device="cuda", dtype=torch.bfloat16)
|
||||
shift = torch.randn_like(scale)
|
||||
calls = 0
|
||||
|
||||
def fail_launch(*args, **kwargs):
|
||||
nonlocal calls
|
||||
calls += 1
|
||||
raise RuntimeError("injected launch failure")
|
||||
|
||||
monkeypatch.setattr(residual_adaln_ops, "_launch_adaln", fail_launch)
|
||||
with torch.inference_mode():
|
||||
for _ in range(2):
|
||||
assert operators.residual_norm(x, residual, None, weight, scale, shift, 1e-6) is None
|
||||
|
||||
assert calls == 1
|
||||
|
||||
|
||||
def _tables(
|
||||
frames: int,
|
||||
height: int,
|
||||
width: int,
|
||||
dim_split: tuple[int, int, int] = _DIM_SPLIT,
|
||||
base: float = 10000.0,
|
||||
) -> tuple[tuple[torch.Tensor, torch.Tensor], ...]:
|
||||
tables = []
|
||||
for length, dim in zip((frames, height, width), dim_split, strict=True):
|
||||
exponents = torch.arange(0, dim, 2, dtype=torch.float64, device="cuda") / dim
|
||||
inv_freqs = (1.0 / base**exponents).to(torch.float32)
|
||||
positions = torch.arange(length, dtype=torch.float32, device="cuda")
|
||||
angles = positions[:, None] * inv_freqs[None, :]
|
||||
tables.append((angles.cos(), angles.sin()))
|
||||
return tuple(tables)
|
||||
|
||||
|
||||
def _apply_rope_reference(
|
||||
hidden_states: torch.Tensor,
|
||||
tables: tuple[tuple[torch.Tensor, torch.Tensor], ...],
|
||||
dim_split: tuple[int, int, int] = _DIM_SPLIT,
|
||||
) -> torch.Tensor:
|
||||
outputs = []
|
||||
offset = 0
|
||||
for axis, (dim, (cos, sin)) in enumerate(zip(dim_split, tables, strict=True), 1):
|
||||
chunk = hidden_states[..., offset : offset + dim]
|
||||
pairs = chunk.reshape(*chunk.shape[:-1], dim // 2, 2)
|
||||
even = pairs[..., 0].float()
|
||||
odd = pairs[..., 1].float()
|
||||
shape = [1, 1, 1, 1, 1, dim // 2]
|
||||
shape[axis] = cos.shape[0]
|
||||
cos = cos.reshape(shape)
|
||||
sin = sin.reshape(shape)
|
||||
rotated = torch.stack([even * cos - odd * sin, even * sin + odd * cos], dim=-1)
|
||||
outputs.append(rotated.reshape(chunk.shape).to(hidden_states.dtype))
|
||||
offset += dim
|
||||
return torch.cat(outputs, dim=-1)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("frames", "height", "width", "heads"),
|
||||
[(3, 7, 7, 1), (31, 136, 192, 4)],
|
||||
)
|
||||
def test_diffvae_qk_rms_norm_scale_rope_3d_is_bit_exact(
|
||||
frames: int,
|
||||
height: int,
|
||||
width: int,
|
||||
heads: int,
|
||||
isolated_runtime_state,
|
||||
) -> None:
|
||||
operators = _selected_operators()
|
||||
generator = torch.Generator(device="cuda").manual_seed(20260829)
|
||||
shape = (1, frames, height, width, heads, 64)
|
||||
query = torch.randn(shape, device="cuda", dtype=torch.bfloat16, generator=generator)
|
||||
key = torch.randn_like(query)
|
||||
query_weight = torch.randn((64,), device="cuda", dtype=torch.bfloat16, generator=generator)
|
||||
key_weight = torch.randn((64,), device="cuda", dtype=torch.bfloat16, generator=generator)
|
||||
tables = _tables(frames, height, width)
|
||||
expected = (
|
||||
_apply_rope_reference(torch.nn.functional.rms_norm(query, (64,), query_weight, 1e-6) * 0.125, tables),
|
||||
_apply_rope_reference(torch.nn.functional.rms_norm(key, (64,), key_weight, 1e-6), tables),
|
||||
)
|
||||
|
||||
with torch.inference_mode():
|
||||
actual = operators.qk_norm_rope(
|
||||
query,
|
||||
key,
|
||||
query_weight,
|
||||
key_weight,
|
||||
1e-6,
|
||||
0.125,
|
||||
_DIM_SPLIT,
|
||||
10000.0,
|
||||
)
|
||||
|
||||
assert actual is not None
|
||||
assert torch.equal(actual[0], expected[0])
|
||||
assert torch.equal(actual[1], expected[1])
|
||||
|
||||
|
||||
def test_diffvae_qk_rms_norm_scale_rope_3d_permanently_falls_back_after_failure(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
isolated_runtime_state,
|
||||
) -> None:
|
||||
operators = _selected_operators()
|
||||
query = torch.randn(1, 3, 7, 7, 1, 64, device="cuda", dtype=torch.bfloat16)
|
||||
key = torch.randn_like(query)
|
||||
weight = torch.ones(64, device="cuda", dtype=torch.bfloat16)
|
||||
calls = 0
|
||||
|
||||
def fail_launch(*args, **kwargs):
|
||||
nonlocal calls
|
||||
calls += 1
|
||||
raise RuntimeError("injected launch failure")
|
||||
|
||||
monkeypatch.setattr(qk_rms_norm_ops, "_launch_combined", fail_launch)
|
||||
with torch.inference_mode():
|
||||
for _ in range(2):
|
||||
assert operators.qk_norm_rope(query, key, weight, weight, 1e-6, 0.125, _DIM_SPLIT, 10000.0) is None
|
||||
|
||||
assert calls == 1
|
||||
@@ -0,0 +1,125 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from vllm.platforms.interface import DeviceCapability
|
||||
|
||||
from vllm_omni.diffusion.models.ltx2 import ops as ltx2_platform
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _TensorProbe:
|
||||
is_cuda: bool
|
||||
device: torch.device
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clear_platform_cache():
|
||||
ltx2_platform._cuda_compute_capability.cache_clear()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
ltx2_platform._cuda_compute_capability.cache_clear()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("capability", "triton", "tilelang", "fusion_expected", "fna_expected"),
|
||||
[
|
||||
(80, True, True, False, False),
|
||||
(90, True, True, True, True),
|
||||
(90, True, False, True, False),
|
||||
(90, False, True, False, False),
|
||||
(100, True, True, True, False),
|
||||
(100, True, False, True, False),
|
||||
(103, True, True, True, False),
|
||||
(103, True, False, True, False),
|
||||
(110, True, True, False, False),
|
||||
(120, True, True, False, False),
|
||||
(121, True, True, False, False),
|
||||
],
|
||||
)
|
||||
def test_production_resolver_and_tensor_eligibility_agree(
|
||||
monkeypatch, capability, triton, tilelang, fusion_expected, fna_expected
|
||||
):
|
||||
monkeypatch.setattr(ltx2_platform, "HAS_TRITON", triton)
|
||||
monkeypatch.setattr(ltx2_platform, "has_tilelang", lambda: tilelang)
|
||||
monkeypatch.setattr(ltx2_platform.current_omni_platform, "is_cuda", lambda: True)
|
||||
monkeypatch.setattr(ltx2_platform.current_omni_platform, "is_available", lambda: True)
|
||||
monkeypatch.setattr(
|
||||
ltx2_platform.current_omni_platform,
|
||||
"get_device_capability",
|
||||
lambda device_id=0: DeviceCapability(major=capability // 10, minor=capability % 10),
|
||||
)
|
||||
# Resolution must be lazy even when FNA is selected.
|
||||
monkeypatch.setitem(sys.modules, "vllm_omni.diffusion.models.ltx2.ops.fna", None)
|
||||
monkeypatch.setattr(torch.compiler, "is_compiling", lambda: False)
|
||||
device = torch.device("cuda:0")
|
||||
operators = ltx2_platform.resolve_ltx2_vae_operators(device)
|
||||
assert (operators is not None) is fusion_expected
|
||||
assert (operators is not None and operators.fna is not None) is fna_expected
|
||||
if operators is not None:
|
||||
from vllm_omni.diffusion.models.ltx2.ops import qk_rms_norm, residual_adaln, swiglu
|
||||
|
||||
assert operators.qk_norm_rope is qk_rms_norm.try_qk_rms_norm_scale_rope_3d_exact
|
||||
assert operators.residual_norm is residual_adaln.try_residual_rms_norm_modulate_exact
|
||||
assert operators.residual_add is residual_adaln.try_residual_add3_exact
|
||||
assert operators.swiglu is swiglu.try_swiglu_tiled_exact
|
||||
|
||||
tensor = _TensorProbe(is_cuda=True, device=device)
|
||||
with torch.inference_mode():
|
||||
assert ltx2_platform.is_ltx2_fusion_eligible(tensor) is fusion_expected
|
||||
assert ltx2_platform.is_ltx2_fna_eligible(tensor) is fna_expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("device", "is_cuda", "available"),
|
||||
[("cpu", True, True), ("cuda:0", False, True), ("cuda:0", True, False)],
|
||||
)
|
||||
def test_resolver_rejects_unsupported_platform_before_capability_lookup(monkeypatch, device, is_cuda, available):
|
||||
monkeypatch.setattr(ltx2_platform.current_omni_platform, "is_cuda", lambda: is_cuda)
|
||||
monkeypatch.setattr(ltx2_platform.current_omni_platform, "is_available", lambda: available)
|
||||
|
||||
def unexpected_lookup(_index):
|
||||
raise AssertionError("Unsupported platforms must not query CUDA capability")
|
||||
|
||||
monkeypatch.setattr(ltx2_platform, "_cuda_compute_capability", unexpected_lookup)
|
||||
assert ltx2_platform.resolve_ltx2_vae_operators(torch.device(device)) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("compiling", "grad_enabled"), [(True, False), (False, True)])
|
||||
def test_runtime_guards_bypass_operator_resolution(monkeypatch, compiling, grad_enabled):
|
||||
monkeypatch.setattr(torch.compiler, "is_compiling", lambda: compiling)
|
||||
monkeypatch.setattr(torch, "is_grad_enabled", lambda: grad_enabled)
|
||||
|
||||
def unexpected_resolve(_device):
|
||||
raise AssertionError("Ineligible runtime must not select eager operators")
|
||||
|
||||
monkeypatch.setattr(ltx2_platform, "resolve_ltx2_vae_operators", unexpected_resolve)
|
||||
tensor = _TensorProbe(is_cuda=True, device=torch.device("cuda:0"))
|
||||
assert not ltx2_platform.is_ltx2_fusion_eligible(tensor)
|
||||
assert not ltx2_platform.is_ltx2_fna_eligible(tensor)
|
||||
|
||||
|
||||
def test_device_capability_is_cached(monkeypatch):
|
||||
calls = 0
|
||||
monkeypatch.setattr(ltx2_platform, "HAS_TRITON", True)
|
||||
|
||||
def get_device_capability(device_id=0):
|
||||
nonlocal calls
|
||||
calls += 1
|
||||
return DeviceCapability(major=9, minor=0)
|
||||
|
||||
monkeypatch.setattr(ltx2_platform.current_omni_platform, "is_cuda", lambda: True)
|
||||
monkeypatch.setattr(ltx2_platform.current_omni_platform, "is_available", lambda: True)
|
||||
monkeypatch.setattr(ltx2_platform.current_omni_platform, "get_device_capability", get_device_capability)
|
||||
assert ltx2_platform._cuda_compute_capability(0) == 90
|
||||
assert ltx2_platform._cuda_compute_capability(0) == 90
|
||||
assert calls == 1
|
||||
@@ -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
|
||||
@@ -302,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(
|
||||
@@ -331,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),
|
||||
@@ -345,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(
|
||||
|
||||
@@ -156,10 +156,14 @@ def _run_transformer_parity(rank: int, world_size: int, master_port: int) -> Non
|
||||
|
||||
|
||||
@pytest.mark.full_model
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=2)
|
||||
@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),
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
|
||||
"""Unit tests for LTX video VAE tiling and distributed decode behavior."""
|
||||
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
@@ -12,6 +14,45 @@ import torch
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("initial_deterministic", [False, True])
|
||||
@pytest.mark.parametrize("fail", [False, True])
|
||||
def test_ltx_vocoder_deterministic_context(monkeypatch, initial_deterministic, fail):
|
||||
from vllm_omni.diffusion.models.ltx2.ltx2_runtime import _deterministic_ltx_vocoder
|
||||
|
||||
monkeypatch.setattr(torch.backends.cudnn, "deterministic", initial_deterministic)
|
||||
if torch.backends.cudnn.is_available():
|
||||
monkeypatch.setattr(torch.backends.cudnn, "benchmark_limit", 17)
|
||||
settings = {
|
||||
name: getattr(torch.backends.cudnn, name) for name in ("enabled", "benchmark", "benchmark_limit", "allow_tf32")
|
||||
}
|
||||
try:
|
||||
with _deterministic_ltx_vocoder():
|
||||
assert torch.backends.cudnn.deterministic
|
||||
assert {name: getattr(torch.backends.cudnn, name) for name in settings} == settings
|
||||
if fail:
|
||||
raise RuntimeError("injected failure")
|
||||
except RuntimeError as exc:
|
||||
assert fail and str(exc) == "injected failure"
|
||||
assert torch.backends.cudnn.deterministic == initial_deterministic
|
||||
assert {name: getattr(torch.backends.cudnn, name) for name in settings} == settings
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _OperatorSetProbe:
|
||||
fna: Callable[..., torch.Tensor] | None
|
||||
|
||||
|
||||
@dataclass
|
||||
class _AttentionProbe:
|
||||
kernel_size: tuple[int, int, int]
|
||||
head_dim: int
|
||||
to_out: tuple[torch.nn.Module, ...]
|
||||
projected: torch.Tensor
|
||||
|
||||
def project_qkv(self, _hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
return self.projected, self.projected, self.projected
|
||||
|
||||
|
||||
def test_ltx_base_vocoder_keeps_native_dtype(monkeypatch):
|
||||
import vllm_omni.diffusion.models.ltx2.ltx2_runtime as ltx_runtime
|
||||
|
||||
@@ -38,9 +79,164 @@ def test_ltx_base_vocoder_keeps_native_dtype(monkeypatch):
|
||||
|
||||
|
||||
class TestLTXDiffusionDecoder:
|
||||
def test_diffusion_decoder_reuses_diffusers_with_scoped_overrides(self, monkeypatch):
|
||||
from diffusers.models.autoencoders.ltx2_diffusion_decoder import (
|
||||
LTX2VideoDiffusionDecoderModel as DiffusersModel,
|
||||
)
|
||||
|
||||
from vllm_omni.diffusion.models.ltx2.vae.decoder import (
|
||||
LTX2VideoDiffusionDecoderModel,
|
||||
LTX2VideoVaeDiffusionNABlock,
|
||||
LTX2VideoVaeNeighborhoodAttention,
|
||||
LTX2VideoVaeSwiGLU,
|
||||
)
|
||||
|
||||
original_init = DiffusersModel.__init__
|
||||
original_parameters = {}
|
||||
|
||||
def capture_parameters(self, *args, **kwargs):
|
||||
original_init(self, *args, **kwargs)
|
||||
original_parameters.update(self.named_parameters())
|
||||
|
||||
with torch.device("meta"):
|
||||
reference = DiffusersModel()
|
||||
monkeypatch.setattr(DiffusersModel, "__init__", capture_parameters)
|
||||
model = LTX2VideoDiffusionDecoderModel()
|
||||
assert isinstance(model, DiffusersModel)
|
||||
assert all(parameter is original_parameters[name] for name, parameter in model.named_parameters())
|
||||
assert {name: tensor.shape for name, tensor in model.state_dict().items()} == {
|
||||
name: tensor.shape for name, tensor in reference.state_dict().items()
|
||||
}
|
||||
|
||||
modules = tuple(model.decoder.modules())
|
||||
expected_blocks = sum(model.config.decoder_stage_depths)
|
||||
assert sum(isinstance(module, LTX2VideoVaeNeighborhoodAttention) for module in modules) == expected_blocks
|
||||
assert sum(isinstance(module, LTX2VideoVaeSwiGLU) for module in modules) == expected_blocks
|
||||
assert (
|
||||
sum(isinstance(module, LTX2VideoVaeDiffusionNABlock) for module in modules)
|
||||
== model.config.decoder_stage_depths[-1]
|
||||
)
|
||||
|
||||
assert type(model.decoder).__module__.startswith("vllm_omni.")
|
||||
assert model.tiled_decode.__func__ is DiffusersModel.tiled_decode
|
||||
assert type(reference.decoder) is type(model.decoder).__bases__[0]
|
||||
|
||||
def test_natten_processor_routes_stage5_through_tilelang_fna(self, monkeypatch):
|
||||
from vllm_omni.diffusion.models.ltx2.vae import decoder as diffvae_modules
|
||||
|
||||
processor = object.__new__(diffvae_modules.LTX2VideoVaeNeighborhoodNattenProcessor)
|
||||
processor.backend = None
|
||||
fallback_calls = []
|
||||
processor._na3d = lambda *args, **kwargs: fallback_calls.append((args, kwargs))
|
||||
|
||||
hidden_states = torch.randn(1, 11, 11, 11, 256, dtype=torch.bfloat16)
|
||||
projected = hidden_states.view(1, 11, 11, 11, 4, 64)
|
||||
|
||||
class FakeAttention:
|
||||
kernel_size = (11, 11, 11)
|
||||
head_dim = 64
|
||||
to_out = (torch.nn.Identity(),)
|
||||
|
||||
@staticmethod
|
||||
def project_qkv(_hidden_states):
|
||||
return projected, projected, projected
|
||||
|
||||
def token_permute(value, _tile, *, flip_tiled_dims):
|
||||
assert flip_tiled_dims
|
||||
return value, value.shape, None
|
||||
|
||||
def token_unpermute(value, *, token_layout_shape, tile_shape, flip_tiled_dims):
|
||||
assert token_layout_shape == projected.shape
|
||||
assert tile_shape == (4, 4, 4)
|
||||
assert flip_tiled_dims
|
||||
return value
|
||||
|
||||
fast_path_calls = []
|
||||
|
||||
def fast_path(query, key, value, *, shape, window):
|
||||
fast_path_calls.append((query, key, value, shape, window))
|
||||
return query
|
||||
|
||||
monkeypatch.setattr(diffvae_modules, "is_ltx2_fna_eligible", lambda _tensor: True)
|
||||
monkeypatch.setattr(
|
||||
diffvae_modules, "resolve_ltx2_vae_operators", lambda _device: _OperatorSetProbe(fna=fast_path)
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
diffvae_modules,
|
||||
"_load_natten_token_permutation",
|
||||
lambda: (token_permute, token_unpermute),
|
||||
)
|
||||
|
||||
output = processor(FakeAttention(), hidden_states)
|
||||
|
||||
assert torch.equal(output, hidden_states)
|
||||
assert len(fast_path_calls) == 1
|
||||
assert fast_path_calls[0][3:] == ((11, 11, 11), (11, 11, 11))
|
||||
assert not fallback_calls
|
||||
|
||||
@pytest.mark.parametrize("reason", ["device", "head_dim", "channels", "dtype", "tilelang_missing", "kernel"])
|
||||
def test_natten_processor_keeps_natten_when_fast_path_does_not_apply(self, monkeypatch, reason):
|
||||
from vllm_omni.diffusion.models.ltx2.vae import decoder as ops
|
||||
|
||||
processor = object.__new__(ops.LTX2VideoVaeNeighborhoodNattenProcessor)
|
||||
processor.backend = None
|
||||
channels = 128 if reason == "channels" else 256
|
||||
head_dim = 32 if reason == "head_dim" else 64
|
||||
x = torch.zeros(1, 11, 11, 11, channels, dtype=torch.float32 if reason == "dtype" else torch.bfloat16)
|
||||
projected = x.view(1, 11, 11, 11, channels // head_dim, head_dim)
|
||||
attn = _AttentionProbe(
|
||||
kernel_size=(3, 5, 5) if reason == "kernel" else (11, 11, 11),
|
||||
head_dim=head_dim,
|
||||
to_out=(torch.nn.Identity(),),
|
||||
projected=projected,
|
||||
)
|
||||
calls = []
|
||||
|
||||
def natten(q, k, v, **kwargs):
|
||||
calls.append(kwargs)
|
||||
return q
|
||||
|
||||
def unexpected_native_load(*_args, **_kwargs):
|
||||
raise AssertionError("Native FNA must not be loaded for an unsupported configuration")
|
||||
|
||||
processor._na3d = natten
|
||||
monkeypatch.setattr(ops, "is_ltx2_fna_eligible", lambda _tensor: reason != "device")
|
||||
monkeypatch.setattr(
|
||||
ops,
|
||||
"resolve_ltx2_vae_operators",
|
||||
lambda _device: _OperatorSetProbe(fna=None if reason == "tilelang_missing" else unexpected_native_load),
|
||||
)
|
||||
assert torch.equal(processor(attn, x), x)
|
||||
assert calls == [{"kernel_size": attn.kernel_size, "scale": 1.0, "backend": None}]
|
||||
|
||||
def test_diffusion_decoder_noneligible_block_uses_diffusers_forward(self, monkeypatch):
|
||||
from vllm_omni.diffusion.models.ltx2.vae import decoder as diffvae_modules
|
||||
|
||||
block = object.__new__(diffvae_modules.LTX2VideoVaeDiffusionNABlock)
|
||||
torch.nn.Module.__init__(block)
|
||||
expected = torch.randn(1, 1, 1, 1, 1)
|
||||
calls = []
|
||||
|
||||
def upstream_forward(_self, hidden_states, latent_context, modulation, block_mask):
|
||||
assert block_mask is None
|
||||
calls.append((hidden_states, latent_context, modulation))
|
||||
return expected
|
||||
|
||||
monkeypatch.setattr(
|
||||
diffvae_modules.diffusers_decoder.LTX2VideoVaeDiffusionNABlock,
|
||||
"forward",
|
||||
upstream_forward,
|
||||
)
|
||||
hidden_states = torch.randn(1, 1, 1, 1, 1)
|
||||
latent_context = torch.randn_like(hidden_states)
|
||||
modulation = (torch.randn_like(hidden_states),)
|
||||
|
||||
assert block.forward(hidden_states, latent_context, modulation) is expected
|
||||
assert calls == [(hidden_states, latent_context, modulation)]
|
||||
|
||||
@pytest.mark.parametrize("mode", ["spatial_shard_height", "spatial_shard_width"])
|
||||
def test_distributed_diffusion_decoder_rejects_non_tile_parallel_modes(self, mode):
|
||||
from vllm_omni.diffusion.models.ltx2.ltx2_diffusion_decoder_distributed import (
|
||||
from vllm_omni.diffusion.models.ltx2.vae.distributed import (
|
||||
DistributedLTX2VideoDiffusionDecoderModel,
|
||||
)
|
||||
|
||||
@@ -52,7 +248,7 @@ class TestLTXDiffusionDecoder:
|
||||
model.set_parallel_size(2, mode=mode)
|
||||
|
||||
def test_distributed_diffusion_decoder_accepts_tile_parallel_mode(self):
|
||||
from vllm_omni.diffusion.models.ltx2.ltx2_diffusion_decoder_distributed import (
|
||||
from vllm_omni.diffusion.models.ltx2.vae.distributed import (
|
||||
DistributedLTX2VideoDiffusionDecoderModel,
|
||||
)
|
||||
|
||||
@@ -68,7 +264,7 @@ class TestLTXDiffusionDecoder:
|
||||
assert calls == [(4, "tile")]
|
||||
|
||||
def test_short_clip_keeps_stage5_temporal_context_then_crops_output(self):
|
||||
from vllm_omni.diffusion.models.ltx2.ltx2_diffusion_decoder import (
|
||||
from vllm_omni.diffusion.models.ltx2.vae.decoder import (
|
||||
LTX2VideoDiffusionDecoder3d,
|
||||
LTX2VideoDiffusionDecoderModel,
|
||||
)
|
||||
@@ -143,7 +339,7 @@ class TestLTXDiffusionDecoder:
|
||||
_ltx2_use_diffusion_decoder(SimpleNamespace(extras={"ltx2_use_conv_vae": "true"}), "2.5")
|
||||
|
||||
def test_native_diffusion_decoder_conversion_splits_qkv_and_folds_gates(self):
|
||||
from vllm_omni.diffusion.models.ltx2.ltx2_diffusion_decoder import (
|
||||
from vllm_omni.diffusion.models.ltx2.vae.decoder import (
|
||||
convert_ltx25_native_diffusion_decoder_state_dict,
|
||||
)
|
||||
|
||||
@@ -190,7 +386,7 @@ class TestLTXDiffusionDecoder:
|
||||
assert not any("type_emb" in key or "coarse" in key or "gate_msa" in key for key in converted)
|
||||
|
||||
def test_native_diffusion_decoder_conversion_rejects_invalid_fused_qkv(self):
|
||||
from vllm_omni.diffusion.models.ltx2.ltx2_diffusion_decoder import (
|
||||
from vllm_omni.diffusion.models.ltx2.vae.decoder import (
|
||||
convert_ltx25_native_diffusion_decoder_state_dict,
|
||||
)
|
||||
|
||||
@@ -388,8 +584,8 @@ class TestLTXDiffusionDecoder:
|
||||
assert output.output[1].numel() == 0
|
||||
|
||||
def test_diffusion_decoder_patch_parallel_size_one_uses_native_tiling(self, monkeypatch):
|
||||
from vllm_omni.diffusion.models.ltx2.ltx2_diffusion_decoder import LTX2VideoDiffusionDecoderModel
|
||||
from vllm_omni.diffusion.models.ltx2.ltx2_diffusion_decoder_distributed import (
|
||||
from vllm_omni.diffusion.models.ltx2.vae.decoder import LTX2VideoDiffusionDecoderModel
|
||||
from vllm_omni.diffusion.models.ltx2.vae.distributed import (
|
||||
DistributedLTX2VideoDiffusionDecoderModel,
|
||||
)
|
||||
|
||||
@@ -424,7 +620,7 @@ class TestLTXDiffusionDecoder:
|
||||
def test_distributed_diffusion_tiles_preserve_serial_noise_order(self, monkeypatch):
|
||||
from diffusers.utils.torch_utils import randn_tensor
|
||||
|
||||
from vllm_omni.diffusion.models.ltx2.ltx2_diffusion_decoder_distributed import (
|
||||
from vllm_omni.diffusion.models.ltx2.vae.distributed import (
|
||||
DistributedLTX2VideoDiffusionDecoderModel,
|
||||
)
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""CUDA regression tests for LTX-2 BWE vocoder precision."""
|
||||
"""GPU regression tests for LTX-2 BWE vocoder precision."""
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
@@ -14,10 +14,13 @@ pytestmark = [pytest.mark.core_model, pytest.mark.diffusion]
|
||||
class _BWEConvVocoder(torch.nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
# Match the production LTX vocoder's conv_pre geometry. The previous
|
||||
# single-channel 1x1 probe intermittently had no MIOpen algorithm.
|
||||
self.conv = torch.nn.Conv1d(
|
||||
1,
|
||||
1,
|
||||
kernel_size=1,
|
||||
128,
|
||||
1024,
|
||||
kernel_size=7,
|
||||
padding=3,
|
||||
bias=False,
|
||||
device="cuda",
|
||||
dtype=torch.bfloat16,
|
||||
@@ -33,12 +36,12 @@ class _BWEConvVocoder(torch.nn.Module):
|
||||
return output
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@hardware_test(res={"cuda": "L4", "rocm": "MI325"}, num_cards=1)
|
||||
def test_ltx_bwe_vocoder_runs_real_cuda_autocast_in_fp32():
|
||||
from vllm_omni.diffusion.models.ltx2.ltx2_runtime import _run_ltx_vocoder
|
||||
|
||||
vocoder = _BWEConvVocoder()
|
||||
generated_mel = torch.ones((1, 1, 4), device="cuda", dtype=torch.bfloat16)
|
||||
generated_mel = torch.ones((1, 128, 64), device="cuda", dtype=torch.bfloat16)
|
||||
|
||||
output = _run_ltx_vocoder(vocoder, generated_mel)
|
||||
|
||||
|
||||
@@ -177,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(
|
||||
@@ -193,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()
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -13,12 +13,14 @@ from PIL import Image
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu, pytest.mark.diffusion]
|
||||
|
||||
|
||||
def test_h3_profiler_targets_cover_aggregate_reference_encoders():
|
||||
def test_h3_profiler_targets_cover_reference_encoders_and_vae_decoders():
|
||||
from vllm_omni.diffusion.models.minimax_h3 import MiniMaxH3Pipeline
|
||||
|
||||
targets = MiniMaxH3Pipeline._PROFILER_TARGETS
|
||||
assert "_encode_visual_conditions" in targets
|
||||
assert "_encode_reference_audio_conditions" in targets
|
||||
assert "video_vae.decode_latent" in targets
|
||||
assert "audio_vae.decode_latent" in targets
|
||||
assert "_encode_video_conditions" not in targets
|
||||
assert "_encode_video_audio_conditions" not in targets
|
||||
assert "_encode_audio_conditions" not in targets
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,357 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import gc
|
||||
import tempfile
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
|
||||
from vllm_omni.diffusion.models.minimax_h3.chunked_decode import decode_h3_chunks
|
||||
from vllm_omni.diffusion.models.minimax_h3.temporal_chunks import decode_temporal_chunks
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu, pytest.mark.diffusion]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def cpu_process_group():
|
||||
if dist.is_initialized():
|
||||
yield dist.group.WORLD
|
||||
return
|
||||
|
||||
with tempfile.NamedTemporaryFile(prefix="h3_chunk_dist_") as rendezvous:
|
||||
init_method = f"file://{rendezvous.name}"
|
||||
dist.init_process_group("gloo", rank=0, world_size=1, init_method=init_method)
|
||||
try:
|
||||
yield dist.group.WORLD
|
||||
finally:
|
||||
dist.destroy_process_group()
|
||||
gc.collect()
|
||||
|
||||
|
||||
class _FakeTemporalModel:
|
||||
use_3d_conv = True
|
||||
token_drop = 3
|
||||
tokens_chunk_size = 5
|
||||
token_overlap = 2
|
||||
vae_ratio_t = 4
|
||||
frame_pre_padding = 3
|
||||
frame_overlap = 5
|
||||
isolated_first_frame = False
|
||||
isolated_last_frame = False
|
||||
|
||||
def _decode_temporal_output_frame_plan(self, z, z_head, z_tail, num_chunks, pad_tokens):
|
||||
del z, z_head, z_tail, num_chunks, pad_tokens
|
||||
return 35, 0, 35
|
||||
|
||||
def _adaptive_decode(self, clip):
|
||||
value = float(clip[:, :, 0].mean())
|
||||
return torch.full((1, 1, 24, 2, 2), value)
|
||||
|
||||
@staticmethod
|
||||
def blend(overlap, part, frame_overlap, dim):
|
||||
del overlap, frame_overlap, dim
|
||||
return part
|
||||
|
||||
|
||||
class _FakeHost:
|
||||
def __init__(self):
|
||||
self.model = _FakeTemporalModel()
|
||||
|
||||
@staticmethod
|
||||
def _denormalize_latent(latent):
|
||||
return latent
|
||||
|
||||
@staticmethod
|
||||
def _normalize_decoded_frames(frames):
|
||||
return frames.float()
|
||||
|
||||
|
||||
def test_temporal_chunks_emit_ordered_frames_and_collect_when_unconsumed():
|
||||
model = _FakeTemporalModel()
|
||||
latent = torch.arange(8, dtype=torch.float32).view(1, 1, 8, 1, 1)
|
||||
chunks = []
|
||||
marker = decode_temporal_chunks(model, latent, chunks.append)
|
||||
|
||||
assert marker.shape == (0,)
|
||||
assert [chunk.shape[2] for chunk in chunks] == [17, 17, 1]
|
||||
assert torch.equal(torch.cat(chunks, dim=2), decode_temporal_chunks(model, latent, None))
|
||||
|
||||
|
||||
def test_h3_callback_failure_is_deferred_until_temporal_decode_finishes():
|
||||
host = _FakeHost()
|
||||
latent = torch.zeros(1, 1, 8, 1, 1)
|
||||
seen = []
|
||||
|
||||
def fail_once(frames):
|
||||
seen.append(frames.shape[2])
|
||||
raise RuntimeError("sink failed")
|
||||
|
||||
with pytest.raises(RuntimeError, match="sink failed"):
|
||||
decode_h3_chunks(host, latent, fail_once, group=None)
|
||||
assert seen == [17]
|
||||
|
||||
|
||||
def test_h3_without_callback_is_a_plain_full_decode_on_a_vae_group(cpu_process_group):
|
||||
host = _FakeHost()
|
||||
latent = torch.arange(8, dtype=torch.float32).view(1, 1, 8, 1, 1)
|
||||
|
||||
full = decode_h3_chunks(host, latent, None, group=cpu_process_group)
|
||||
|
||||
chunks = []
|
||||
decode_h3_chunks(host, latent, chunks.append, group=cpu_process_group)
|
||||
assert torch.equal(torch.cat(chunks, dim=2), full)
|
||||
|
||||
|
||||
class _SimulatedGroup:
|
||||
"""Stand in for a VAE group so one process can check every rank's verdict.
|
||||
|
||||
``all_reduce`` is replaced with the sum the real collective would produce
|
||||
for a group of ``world_size`` ranks, ``supplied`` of which handed in a
|
||||
callback. That sum is what makes a rank-local verdict observable from a
|
||||
single process.
|
||||
"""
|
||||
|
||||
def __init__(self, world_size: int, supplied: int):
|
||||
self.world_size = world_size
|
||||
self.supplied = supplied
|
||||
|
||||
|
||||
def _patch_simulated_ranks(monkeypatch, simulated: _SimulatedGroup, rank: int) -> None:
|
||||
from vllm_omni.diffusion.models.minimax_h3 import chunked_decode as mod
|
||||
|
||||
def fake_all_reduce(tensor, group=None):
|
||||
del group # the simulated census below stands in for the real reduction
|
||||
tensor.copy_(torch.tensor([simulated.supplied], dtype=tensor.dtype))
|
||||
|
||||
monkeypatch.setattr(mod.dist, "get_rank", lambda _group: rank)
|
||||
monkeypatch.setattr(mod.dist, "get_world_size", lambda _group: simulated.world_size)
|
||||
monkeypatch.setattr(mod.dist, "all_reduce", fake_all_reduce)
|
||||
monkeypatch.setattr(mod.dist, "broadcast", lambda tensor, src=0, group=None: None)
|
||||
monkeypatch.setattr(mod.dist, "get_global_rank", lambda _group, _rank: 0)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rank", [0, 1, 2])
|
||||
def test_h3_every_rank_rejects_a_partially_supplied_callback(monkeypatch, rank):
|
||||
"""Ranks that disagree must all refuse, not let one decode alone.
|
||||
|
||||
A rank-local verdict let a peer fall through into the decoder collectives
|
||||
while its peers raised, hanging the stage instead of failing it.
|
||||
"""
|
||||
host = _FakeHost()
|
||||
latent = torch.zeros(1, 1, 8, 1, 1)
|
||||
# Two ranks of three handed in a callback.
|
||||
group = _SimulatedGroup(world_size=3, supplied=2)
|
||||
_patch_simulated_ranks(monkeypatch, group, rank)
|
||||
|
||||
with pytest.raises(ValueError, match="every rank"):
|
||||
decode_h3_chunks(host, latent, lambda _frames: None, group=object())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rank", [0, 1, 2])
|
||||
def test_h3_only_rank_zero_publishes_when_every_rank_supplies(monkeypatch, rank):
|
||||
"""Ownership is positional: all ranks stream, rank 0 publishes."""
|
||||
host = _FakeHost()
|
||||
latent = torch.zeros(1, 1, 8, 1, 1)
|
||||
group = _SimulatedGroup(world_size=3, supplied=3)
|
||||
_patch_simulated_ranks(monkeypatch, group, rank)
|
||||
|
||||
seen: list[int] = []
|
||||
decode_h3_chunks(host, latent, lambda f: seen.append(int(f.shape[2])), group=object())
|
||||
|
||||
# Peers run the loop to stay in the collectives but publish nothing.
|
||||
assert (seen != []) is (rank == 0)
|
||||
|
||||
|
||||
def _stub_video_vae(*, parallel_size: int, tile_count: int):
|
||||
"""A MiniMaxH3VideoVAE with only the pieces the decode entry points read."""
|
||||
from contextlib import contextmanager
|
||||
|
||||
from vllm_omni.diffusion.models.minimax_h3.vae import MiniMaxH3VideoVAE
|
||||
|
||||
vae = object.__new__(MiniMaxH3VideoVAE)
|
||||
vae.parallel_size = parallel_size
|
||||
vae.model = SimpleNamespace(_adaptive_decode=lambda clip: clip)
|
||||
vae.entered_rank_local = False
|
||||
|
||||
@contextmanager
|
||||
def rank_local():
|
||||
vae.entered_rank_local = True
|
||||
yield
|
||||
|
||||
vae._decoder_tile_count = lambda latent: tile_count
|
||||
vae._rank_local_tiling = rank_local
|
||||
vae.is_distributed_enabled = lambda: False
|
||||
return vae
|
||||
|
||||
|
||||
def test_chunked_decode_falls_back_when_tiles_are_fewer_than_ranks(monkeypatch):
|
||||
"""Without the fallback, tileless ranks raise while their peers block."""
|
||||
from vllm_omni.diffusion.models.minimax_h3 import vae as vae_mod
|
||||
|
||||
vae = _stub_video_vae(parallel_size=4, tile_count=1)
|
||||
monkeypatch.setattr(vae_mod, "decode_h3_chunks", lambda *args, **kwargs: torch.zeros(1))
|
||||
|
||||
vae.decode_with_chunks(torch.zeros(1, 1, 8, 1, 1), on_chunk=lambda _frames: None)
|
||||
|
||||
assert vae.entered_rank_local, "chunked decode must share decode_latent's too-few-tiles fallback"
|
||||
|
||||
|
||||
def test_chunked_decode_keeps_shared_tiling_when_every_rank_has_a_tile(monkeypatch):
|
||||
from vllm_omni.diffusion.models.minimax_h3 import vae as vae_mod
|
||||
|
||||
vae = _stub_video_vae(parallel_size=4, tile_count=8)
|
||||
monkeypatch.setattr(vae_mod, "decode_h3_chunks", lambda *args, **kwargs: torch.zeros(1))
|
||||
|
||||
vae.decode_with_chunks(torch.zeros(1, 1, 8, 1, 1), on_chunk=lambda _frames: None)
|
||||
|
||||
assert not vae.entered_rank_local
|
||||
|
||||
|
||||
def test_h3_vae_declares_the_chunked_decode_capability():
|
||||
"""A consumer must be able to detect the capability and the pixel range."""
|
||||
from vllm_omni.diffusion.models.interface import supports_chunked_vae_decode
|
||||
from vllm_omni.diffusion.models.minimax_h3.vae import MiniMaxH3VideoVAE
|
||||
|
||||
vae = object.__new__(MiniMaxH3VideoVAE)
|
||||
|
||||
assert supports_chunked_vae_decode(vae)
|
||||
# H3 reverts through the checkpoint's processor, which lands in [0, 1];
|
||||
# a Wan VAE publishes [-1, 1], so the range cannot be assumed.
|
||||
assert vae.chunk_value_range == (0.0, 1.0)
|
||||
|
||||
|
||||
def _native_decode_temporal_streaming(model, z, z_head, z_tail, num_chunks, pad_tokens):
|
||||
"""The released ``_decode_temporal_streaming`` loop, as the parity oracle.
|
||||
|
||||
Transcribed from the checkpoint's ``AutoencoderKLLegacy`` so the fork can be
|
||||
compared against the control flow it mirrors, including the isolated
|
||||
head/tail extraction.
|
||||
"""
|
||||
total_frames, pad_frames, output_frames = model._decode_temporal_output_frame_plan(
|
||||
z, z_head, z_tail, num_chunks, pad_tokens
|
||||
)
|
||||
chunk_dec = model.tokens_chunk_size * model.vae_ratio_t
|
||||
split_count = int(model.token_drop > 0) + 1
|
||||
dec = None
|
||||
dec_overlap = None
|
||||
write_pos = 0
|
||||
|
||||
def write_part(part):
|
||||
nonlocal dec, write_pos
|
||||
part_frames = int(part.shape[2])
|
||||
if part_frames <= 0:
|
||||
return
|
||||
if dec is None:
|
||||
out_shape = list(part.shape)
|
||||
out_shape[2] = output_frames
|
||||
dec = torch.empty(out_shape, dtype=part.dtype, device=part.device)
|
||||
remaining = int(dec.shape[2]) - write_pos
|
||||
copy_frames = min(part_frames, max(0, remaining))
|
||||
if copy_frames > 0:
|
||||
dec[:, :, write_pos : write_pos + copy_frames].copy_(part[:, :, :copy_frames])
|
||||
write_pos += copy_frames
|
||||
|
||||
for i in range(num_chunks):
|
||||
t_start = i * model.tokens_chunk_size
|
||||
clip_z = z[:, :, t_start : t_start + model.tokens_chunk_size + model.token_overlap]
|
||||
if i == 0 and z_head is not None:
|
||||
clip_z = torch.cat([z_head, clip_z], dim=2)
|
||||
if i == num_chunks - 1 and z_tail is not None:
|
||||
clip_z = torch.cat([clip_z, z_tail], dim=2)
|
||||
|
||||
clip_dec = model._adaptive_decode(clip_z)
|
||||
|
||||
dec_tail = None
|
||||
if i == 0 and z_head is not None:
|
||||
write_part(clip_dec[:, :, model.vae_ratio_t - 1 : model.vae_ratio_t])
|
||||
clip_dec = clip_dec[:, :, model.vae_ratio_t :]
|
||||
if i == num_chunks - 1 and z_tail is not None:
|
||||
dec_tail = clip_dec[:, :, -1:]
|
||||
clip_dec = clip_dec[:, :, : -model.vae_ratio_t]
|
||||
|
||||
for j in range(split_count):
|
||||
f_start = j * chunk_dec
|
||||
f_end = min(f_start + chunk_dec, clip_dec.shape[2])
|
||||
chunk = clip_dec[:, :, f_start:f_end][:, :, model.frame_pre_padding :]
|
||||
if j == 0:
|
||||
if dec_overlap is not None:
|
||||
chunk = model.blend(dec_overlap, chunk, model.frame_overlap, dim=-3)
|
||||
dec_overlap = None
|
||||
write_part(chunk)
|
||||
else:
|
||||
dec_overlap = chunk.contiguous()
|
||||
|
||||
if i == num_chunks - 1:
|
||||
if dec_overlap is not None:
|
||||
write_part(dec_overlap)
|
||||
dec_overlap = None
|
||||
if dec_tail is not None:
|
||||
write_part(dec_tail)
|
||||
|
||||
return dec
|
||||
|
||||
|
||||
class _IsolatedFrameModel(_FakeTemporalModel):
|
||||
"""Fake decoder with the isolated boundaries the released config can set."""
|
||||
|
||||
frame_pre_padding = 0
|
||||
|
||||
def __init__(self, *, first: bool, last: bool):
|
||||
self.isolated_first_frame = first
|
||||
self.isolated_last_frame = last
|
||||
|
||||
def _decode_temporal_output_frame_plan(self, z, z_head, z_tail, num_chunks, pad_tokens):
|
||||
del pad_tokens
|
||||
frames = num_chunks * self.tokens_chunk_size * self.vae_ratio_t
|
||||
frames += int(z_head is not None) + int(z_tail is not None)
|
||||
del z
|
||||
return frames, 0, frames
|
||||
|
||||
def _adaptive_decode(self, clip):
|
||||
# Every latent token decodes to a distinct, ordered block, so a shifted
|
||||
# or reordered emission is visible in the values themselves.
|
||||
base = float(clip[:, :, 0].mean())
|
||||
frames = int(clip.shape[2]) * self.vae_ratio_t
|
||||
return torch.arange(frames, dtype=torch.float32).view(1, 1, frames, 1, 1) + base
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("first", "last"),
|
||||
[(True, False), (False, True), (True, True)],
|
||||
)
|
||||
def test_temporal_chunks_match_the_native_loop_at_isolated_boundaries(first, last):
|
||||
"""The fork must extract the isolated head/tail the way the native loop does."""
|
||||
model = _IsolatedFrameModel(first=first, last=last)
|
||||
latent = torch.arange(12, dtype=torch.float32).view(1, 1, 12, 1, 1)
|
||||
|
||||
chunks: list[torch.Tensor] = []
|
||||
decode_temporal_chunks(model, latent, chunks.append)
|
||||
streamed = torch.cat(chunks, dim=2)
|
||||
|
||||
# Feed the oracle exactly what the released ``decode_temporal`` would:
|
||||
# split the isolated tokens off, then pad the remainder to a whole chunk.
|
||||
isolated = int(first) + int(last)
|
||||
pseudo_tokens = int(latent.shape[2]) - isolated + model.token_drop
|
||||
remainder = pseudo_tokens % model.tokens_chunk_size
|
||||
pad_tokens = (model.tokens_chunk_size - remainder) if remainder else 0
|
||||
num_chunks = (pseudo_tokens + pad_tokens) // model.tokens_chunk_size - int(model.token_drop > 0)
|
||||
|
||||
body = latent
|
||||
z_head = None
|
||||
if first:
|
||||
z_head = body[:, :, :1]
|
||||
body = body[:, :, 1:]
|
||||
z_tail = None
|
||||
if last:
|
||||
z_tail = body[:, :, -1:]
|
||||
body = body[:, :, :-1]
|
||||
if pad_tokens:
|
||||
body = torch.cat([body, body[:, :, -1:].repeat(1, 1, pad_tokens, 1, 1)], dim=2)
|
||||
|
||||
expected = _native_decode_temporal_streaming(model, body, z_head, z_tail, num_chunks, pad_tokens)
|
||||
|
||||
assert streamed.shape == expected.shape
|
||||
assert torch.equal(streamed, expected)
|
||||
@@ -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 types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
@@ -64,6 +64,13 @@ def setup_tp_group(monkeypatch, mocker):
|
||||
lambda: 0,
|
||||
)
|
||||
|
||||
# vLLM 0.29 added a CUDA-only fused embedding kernel that engages whenever
|
||||
# tp_size > 1; these tests drive CPU tensors, so keep the portable masked path.
|
||||
monkeypatch.setattr(
|
||||
"vllm.model_executor.layers.vocab_parallel_embedding.current_platform.is_cuda",
|
||||
lambda: False,
|
||||
)
|
||||
|
||||
mock_tp_group = mocker.MagicMock()
|
||||
mock_tp_group.world_size = 2
|
||||
mocker.patch("vllm.distributed.parallel_state.get_tp_group", return_value=mock_tp_group)
|
||||
@@ -94,7 +101,7 @@ def setup_tp_group(monkeypatch, mocker):
|
||||
|
||||
monkeypatch.setattr(
|
||||
"vllm.model_executor.layers.linear.dispatch_unquantized_gemm",
|
||||
lambda: default_unquantized_gemm,
|
||||
lambda *_args, **_kwargs: default_unquantized_gemm,
|
||||
)
|
||||
|
||||
with set_current_vllm_config(VllmConfig(device_config=device_config)):
|
||||
|
||||
@@ -1,12 +1,39 @@
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm_omni.diffusion.models.qwen_image.qwen_image_transformer import QwenEmbedRope
|
||||
from vllm_omni.diffusion.models.qwen_image.qwen_image_transformer import (
|
||||
QwenEmbedRope,
|
||||
_apply_qwen_image_rotary_emb,
|
||||
)
|
||||
from vllm_omni.diffusion.models.qwen_image.rope_utils import txt_seq_lens_from_embeds
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.bfloat16])
|
||||
@pytest.mark.parametrize("noncontiguous", [False, True])
|
||||
def test_qwen_rotary_preserves_frequency_precision(dtype, noncontiguous):
|
||||
from diffusers.models.transformers.transformer_qwenimage import apply_rotary_emb_qwen
|
||||
|
||||
generator = torch.Generator().manual_seed(42)
|
||||
x = torch.randn(2, 17, 3, 128, generator=generator).to(dtype)
|
||||
if noncontiguous:
|
||||
x = x.transpose(1, 2).contiguous().transpose(1, 2)
|
||||
angles = torch.randn(17, 64, generator=generator)
|
||||
freqs = torch.polar(torch.ones_like(angles), angles)
|
||||
expected = apply_rotary_emb_qwen(x, freqs, use_real=False)
|
||||
actual = _apply_qwen_image_rotary_emb(x, freqs)
|
||||
assert actual.dtype == dtype
|
||||
assert actual.shape == x.shape
|
||||
torch.testing.assert_close(actual, expected, rtol=0, atol=0)
|
||||
|
||||
if dtype == torch.bfloat16:
|
||||
# A regression to early BF16 frequency rounding must be observable.
|
||||
rounded_freqs = torch.complex(freqs.real.to(dtype).float(), freqs.imag.to(dtype).float())
|
||||
rounded = _apply_qwen_image_rotary_emb(x, rounded_freqs)
|
||||
assert not torch.equal(actual, rounded)
|
||||
|
||||
|
||||
def test_txt_seq_lens_from_embeds_uses_padded_width_not_valid_token_count():
|
||||
prompt_embeds = torch.zeros(2, 64, 8)
|
||||
prompt_embeds_mask = torch.zeros(2, 64, dtype=torch.bool)
|
||||
|
||||
@@ -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 os
|
||||
|
||||
@@ -22,7 +22,7 @@ def _init_distributed(monkeypatch):
|
||||
|
||||
monkeypatch.setattr(
|
||||
"vllm.model_executor.layers.linear.dispatch_unquantized_gemm",
|
||||
lambda: default_unquantized_gemm,
|
||||
lambda *_args, **_kwargs: default_unquantized_gemm,
|
||||
)
|
||||
os.environ.setdefault("MASTER_ADDR", "localhost")
|
||||
os.environ.setdefault("MASTER_PORT", "29501")
|
||||
|
||||
@@ -41,8 +41,8 @@ def tp1_group():
|
||||
|
||||
os.environ.setdefault("MASTER_ADDR", "localhost")
|
||||
os.environ.setdefault("MASTER_PORT", "29501")
|
||||
init_distributed_environment(world_size=1, rank=0, local_rank=0, distributed_init_method="env://")
|
||||
initialize_model_parallel()
|
||||
init_distributed_environment(world_size=1, rank=0, local_rank=0, distributed_init_method="env://", backend="gloo")
|
||||
initialize_model_parallel(backend="gloo")
|
||||
yield
|
||||
cleanup_dist_env_and_memory()
|
||||
|
||||
@@ -54,7 +54,7 @@ def force_default_gemm(monkeypatch):
|
||||
|
||||
monkeypatch.setattr(
|
||||
"vllm.model_executor.layers.linear.dispatch_unquantized_gemm",
|
||||
lambda: default_unquantized_gemm,
|
||||
lambda *_args, **_kwargs: default_unquantized_gemm,
|
||||
)
|
||||
|
||||
|
||||
@@ -482,8 +482,12 @@ class _LockstepP2PDist:
|
||||
def test_tiny_transformer_sp2_lockstep_matches_dense(tp1_group, force_default_gemm, mocker, task) -> None:
|
||||
"""Two lockstep rank threads over uneven frame shards must reproduce the
|
||||
dense tiny-transformer output, and must actually have sharded the work."""
|
||||
from vllm_omni.diffusion.attention.backends.sdpa import SDPABackend
|
||||
from vllm_omni.diffusion.models.sana_video import SanaVideoTransformer3DModel
|
||||
|
||||
# These CPU tensor tests must not probe a CUDA device during construction.
|
||||
mocker.patch("vllm_omni.diffusion.attention.selector._cached_get_backend_cls", return_value=SDPABackend)
|
||||
|
||||
torch.manual_seed(3)
|
||||
model = SanaVideoTransformer3DModel(**_TINY_SP_CONFIG).eval()
|
||||
for _, param in sorted(model.named_parameters()):
|
||||
|
||||
@@ -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
|
||||
|
||||
"""TP unit tests for SANA-Video: distributed RMSNorm, sharded attention and
|
||||
sharded GLUMB temporal conv.
|
||||
@@ -51,7 +51,7 @@ def force_default_gemm(monkeypatch):
|
||||
|
||||
monkeypatch.setattr(
|
||||
"vllm.model_executor.layers.linear.dispatch_unquantized_gemm",
|
||||
lambda: default_unquantized_gemm,
|
||||
lambda *_args, **_kwargs: default_unquantized_gemm,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ import torch
|
||||
from vllm.lora.layers import BaseLayerWithLoRA
|
||||
|
||||
import vllm_omni.diffusion.models.sensenova_u1.paged_decode as paged_decode
|
||||
from tests.helpers.mark import hardware_test
|
||||
from vllm_omni.diffusion.models.sensenova_u1.paged_decode import (
|
||||
BLOCK_SIZE,
|
||||
BUCKETS,
|
||||
@@ -169,7 +170,8 @@ def test_length_lives_in_device_tensors():
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# The capture contract. These need CUDA and the bundled flash-attention kernel.
|
||||
# The capture contract. Graph tests need a torch.cuda-compatible accelerator;
|
||||
# paged-attention equivalence also needs the bundled kernel's paged API.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
cuda_only = pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required")
|
||||
@@ -181,8 +183,7 @@ vllm_flash_attn_only = pytest.mark.skipif(
|
||||
|
||||
@cuda_only
|
||||
@vllm_flash_attn_only
|
||||
@pytest.mark.cuda
|
||||
@pytest.mark.L4
|
||||
@hardware_test(res={"cuda": "L4", "rocm": "MI325"})
|
||||
def test_paged_attention_matches_sdpa_over_the_same_buffer():
|
||||
import torch.nn.functional as F
|
||||
|
||||
@@ -223,8 +224,7 @@ def test_paged_attention_matches_sdpa_over_the_same_buffer():
|
||||
|
||||
@cuda_only
|
||||
@vllm_flash_attn_only
|
||||
@pytest.mark.cuda
|
||||
@pytest.mark.L4
|
||||
@hardware_test(res={"cuda": "L4", "rocm": "MI325"})
|
||||
def test_a_captured_graph_follows_a_later_length():
|
||||
"""One capture has to serve every length in the bucket.
|
||||
|
||||
@@ -285,8 +285,7 @@ def test_a_captured_graph_follows_a_later_length():
|
||||
|
||||
@cuda_only
|
||||
@vllm_flash_attn_only
|
||||
@pytest.mark.cuda
|
||||
@pytest.mark.L4
|
||||
@hardware_test(res={"cuda": "L4", "rocm": "MI325"})
|
||||
def test_a_captured_graph_writes_each_step_to_its_own_slot():
|
||||
"""The write slot has to be a device tensor, not a Python index.
|
||||
|
||||
@@ -347,8 +346,7 @@ def test_a_captured_graph_writes_each_step_to_its_own_slot():
|
||||
|
||||
@cuda_only
|
||||
@vllm_flash_attn_only
|
||||
@pytest.mark.cuda
|
||||
@pytest.mark.L4
|
||||
@hardware_test(res={"cuda": "L4", "rocm": "MI325"})
|
||||
def test_a_whole_decode_loop_matches_the_unpaged_path():
|
||||
"""Per-step kernel equivalence is not loop equivalence.
|
||||
|
||||
@@ -413,8 +411,7 @@ class _StubLM(torch.nn.Module):
|
||||
|
||||
|
||||
@cuda_only
|
||||
@pytest.mark.cuda
|
||||
@pytest.mark.L4
|
||||
@hardware_test(res={"cuda": "L4", "rocm": "MI325"})
|
||||
def test_the_decode_graph_captures_into_the_shared_platform_pool(monkeypatch):
|
||||
"""``_decode_context`` builds a runner per request, so a private capture pool
|
||||
hands every request its own arena and never gives it back. Measured on a
|
||||
@@ -556,10 +553,12 @@ def test_a_kernel_missing_any_kwarg_we_pass_is_not_supported(monkeypatch):
|
||||
def test_only_q_k_and_v_reach_the_kernel_positionally(monkeypatch):
|
||||
"""A positional standard argument binds to whatever a future wheel puts in
|
||||
that slot, and the probe above only checks that the names exist."""
|
||||
seen = {}
|
||||
seen_args: tuple[object, ...] = ()
|
||||
seen_kwargs: dict[str, object] = {}
|
||||
|
||||
def recorder(*args, **kwargs):
|
||||
seen["args"], seen["kwargs"] = args, kwargs
|
||||
def recorder(*args: object, **kwargs: object):
|
||||
nonlocal seen_args, seen_kwargs
|
||||
seen_args, seen_kwargs = args, kwargs
|
||||
return torch.zeros(1, N_HEADS, HEAD_DIM)
|
||||
|
||||
monkeypatch.setattr(paged_decode, "_flash_varlen", lambda: recorder)
|
||||
@@ -572,8 +571,8 @@ def test_only_q_k_and_v_reach_the_kernel_positionally(monkeypatch):
|
||||
torch.zeros(1, KV_HEADS, 1, HEAD_DIM),
|
||||
1.0,
|
||||
)
|
||||
assert len(seen["args"]) == 3, "only q, k and v may be positional"
|
||||
assert set(seen["kwargs"]) == {
|
||||
assert len(seen_args) == 3, "only q, k and v may be positional"
|
||||
assert set(seen_kwargs) == {
|
||||
"max_seqlen_q",
|
||||
"cu_seqlens_q",
|
||||
"max_seqlen_k",
|
||||
@@ -694,8 +693,7 @@ def test_no_capture_crosses_a_request_once_lora_wrappers_are_installed(monkeypat
|
||||
|
||||
|
||||
@cuda_only
|
||||
@pytest.mark.cuda
|
||||
@pytest.mark.L4
|
||||
@hardware_test(res={"cuda": "L4", "rocm": "MI325"})
|
||||
def test_a_second_request_replays_the_first_capture(monkeypatch):
|
||||
"""Reuse is only worth anything if the capture survives it."""
|
||||
dev = torch.device("cuda")
|
||||
|
||||
@@ -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 pytest
|
||||
import torch
|
||||
from transformers import T5Config
|
||||
@@ -54,6 +54,13 @@ def setup_tp_group(monkeypatch, mocker):
|
||||
lambda: 0,
|
||||
)
|
||||
|
||||
# vLLM 0.29 added a CUDA-only fused embedding kernel that engages whenever
|
||||
# tp_size > 1; these tests drive CPU tensors, so keep the portable masked path.
|
||||
monkeypatch.setattr(
|
||||
"vllm.model_executor.layers.vocab_parallel_embedding.current_platform.is_cuda",
|
||||
lambda: False,
|
||||
)
|
||||
|
||||
# TP group
|
||||
mock_tp_group = mocker.MagicMock()
|
||||
mock_tp_group.world_size = 2
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
"""Tests for component routing for quantization."""
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
@@ -372,7 +372,8 @@ class TestComponentApplyVllmMapper:
|
||||
"thinker.model": "thinker.language_model.model",
|
||||
"talker.model": "talker.language_model.model",
|
||||
}
|
||||
).get_unstacked_mapper()
|
||||
# vLLM 0.29 renamed get_unstacked_mapper to get_rename_mapper.
|
||||
).get_rename_mapper()
|
||||
|
||||
config.apply_vllm_mapper(mapper)
|
||||
|
||||
|
||||
@@ -300,7 +300,8 @@ def test_single_stage_zimage_fp8_uses_less_memory():
|
||||
assert mem_fp8 < mem_bf16, f"FP8 ({mem_fp8:.2f} GiB) should use less memory than BF16 ({mem_bf16:.2f} GiB)"
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"})
|
||||
@hardware_test(res={"cuda": "L4", "xpu": "B60"})
|
||||
@pytest.mark.advanced_model
|
||||
def test_single_stage_qwen_image_fp8():
|
||||
"""Qwen-Image (random weights) with FP8 generates valid images."""
|
||||
model = "riverclouds/qwen_image_random"
|
||||
|
||||
@@ -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"})
|
||||
|
||||
@@ -140,6 +140,7 @@ class TestMetricKeys:
|
||||
raise AssertionError("diffusion_engine_total_time_ms should be attached in step_streaming()")
|
||||
|
||||
assert '"diffusion_engine_exec_time_ms": exec_total_time * 1000' in step_streaming_source
|
||||
assert '"output_ready_wait_time_ms": output_ready_wait_time * 1000' in step_streaming_source
|
||||
# step_total_ms is no longer emitted as a metric (no family consumes
|
||||
# it); it lives only in the debug log breakdown below.
|
||||
assert '"diffusion_engine_total_time_ms"' not in step_streaming_source
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import asyncio
|
||||
import queue
|
||||
@@ -10,8 +10,9 @@ import pytest
|
||||
import torch
|
||||
import vllm.v1.core.single_type_kv_cache_manager as native_kv_managers
|
||||
from pytest_mock import MockerFixture
|
||||
from vllm.v1.kv_cache_interface import FullAttentionSpec, KVCacheConfig, KVCacheGroupSpec, KVCacheTensor
|
||||
from vllm.v1.kv_cache_interface import FullAttentionSpec, KVCacheConfig, KVCacheGroupSpec
|
||||
|
||||
from tests.helpers.kv_layout import build_kv_cache_tensor
|
||||
from vllm_omni.diffusion.data import DiffusionOutput, DiffusionRequestAbortedError
|
||||
from vllm_omni.diffusion.diffusion_engine import DiffusionEngine, DiffusionExecutionMode
|
||||
from vllm_omni.diffusion.diffusion_kv.config import DiffusionKVCacheMode
|
||||
@@ -104,7 +105,7 @@ def _initialize_paged_scheduler(
|
||||
)
|
||||
config = KVCacheConfig(
|
||||
num_blocks=num_blocks,
|
||||
kv_cache_tensors=[KVCacheTensor(size=spec.page_size_bytes * num_blocks, shared_by=["layer0"])],
|
||||
kv_cache_tensors=[build_kv_cache_tensor(spec, num_blocks, ["layer0"])],
|
||||
kv_cache_groups=[KVCacheGroupSpec(layer_names=["layer0"], kv_cache_spec=spec)],
|
||||
)
|
||||
scheduler.initialize(
|
||||
|
||||
@@ -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
|
||||
|
||||
"""Generate raw LTX video and audio outputs with the official or Omni runtime."""
|
||||
|
||||
@@ -114,6 +114,29 @@ def _insert_official_paths(official_root: Path) -> None:
|
||||
sys.path.insert(0, path)
|
||||
|
||||
|
||||
def _configure_official_vocoder_determinism() -> None:
|
||||
"""Make the pinned official LTX-2.5 vocoder a stable reference."""
|
||||
from ltx_core.model.audio_vae.vocoder import VocoderWithBWE
|
||||
|
||||
original_forward = VocoderWithBWE.forward
|
||||
if getattr(original_forward, "_vllm_omni_deterministic", False):
|
||||
return
|
||||
|
||||
def deterministic_forward(self: Any, mel_spec: torch.Tensor) -> torch.Tensor:
|
||||
device_type = mel_spec.device.type
|
||||
if device_type != "cuda":
|
||||
return original_forward(self, mel_spec)
|
||||
previous = torch.backends.cudnn.deterministic
|
||||
try:
|
||||
torch.backends.cudnn.deterministic = True
|
||||
return original_forward(self, mel_spec)
|
||||
finally:
|
||||
torch.backends.cudnn.deterministic = previous
|
||||
|
||||
setattr(deterministic_forward, "_vllm_omni_deterministic", True)
|
||||
setattr(VocoderWithBWE, "forward", deterministic_forward)
|
||||
|
||||
|
||||
def _configure_official_sdpa(pipeline: Any) -> None:
|
||||
"""Pin official connector and denoiser attention to cuDNN, with MATH fallback."""
|
||||
from ltx_core.loader.attention_ops import set_attention_module_op
|
||||
@@ -187,6 +210,7 @@ def _run_official(args: argparse.Namespace, request: dict[str, Any]) -> None:
|
||||
if args.official_root is None:
|
||||
raise ValueError("Official backend requires --official-root")
|
||||
_insert_official_paths(args.official_root)
|
||||
_configure_official_vocoder_determinism()
|
||||
# Keep Gemma on the same SDPA path in both subprocesses. DiT attention is
|
||||
# still pinned independently to the explicit cuDNN backend below.
|
||||
torch.backends.cuda.enable_cudnn_sdp(False)
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -164,6 +164,7 @@ def _run_diffusers_wan22_i2v(*, model: str, output_path: Path, conditioning_imag
|
||||
)
|
||||
pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config, flow_shift=FLOW_SHIFT)
|
||||
pipe.to("cuda")
|
||||
_set_matched_attention_backend(pipe)
|
||||
|
||||
_diffusers_dummy_run(pipe)
|
||||
|
||||
|
||||
@@ -34,11 +34,7 @@ TRUE_CFG_SCALE = 4.0
|
||||
SEED = 42
|
||||
SSIM_THRESHOLD = 0.94
|
||||
# With --fa-deterministic, H100 nightlies stably land near SSIM 0.958 / PSNR 27.8
|
||||
# vs Diffusers (see #5734 / #5963), so the primary gates are 0.94 / 27.0.
|
||||
# The SDPA-matched fallback (hub kernel unavailable for the image's torch)
|
||||
# landed at SSIM 0.9687 in build 2954 — keep a slightly tighter SSIM gate for
|
||||
# that path only.
|
||||
SSIM_THRESHOLD_SDPA_FALLBACK = 0.96
|
||||
# vs Diffusers on the FA3 hub path (see #5734 / #5963 / #6971).
|
||||
PSNR_THRESHOLD = 27.0
|
||||
|
||||
MODEL_2512_ID = "Qwen/Qwen-Image-2512"
|
||||
@@ -65,44 +61,6 @@ MEAN_ABS_DIFF_THRESHOLD_2512 = 3e-2
|
||||
P99_ABS_DIFF_THRESHOLD_2512 = 4e-1
|
||||
|
||||
|
||||
_FLASH_ATTN3_HUB_AVAILABLE: bool | None = None
|
||||
|
||||
|
||||
def _flash_attn3_hub_available() -> bool:
|
||||
"""Whether kernels-community/flash-attn3 has a build for this torch/CUDA.
|
||||
|
||||
The hub repo only ships prebuilt variants for specific torch versions;
|
||||
a base-image torch bump can outrun it (build 2952 failed with "Cannot
|
||||
find a build variant for this system"). When it is unavailable, both
|
||||
sides of the comparison fall back to torch SDPA together — the test
|
||||
compares implementations, so the attention math must stay matched.
|
||||
"""
|
||||
global _FLASH_ATTN3_HUB_AVAILABLE
|
||||
if _FLASH_ATTN3_HUB_AVAILABLE is None:
|
||||
try:
|
||||
from kernels import get_kernel
|
||||
|
||||
get_kernel("kernels-community/flash-attn3")
|
||||
_FLASH_ATTN3_HUB_AVAILABLE = True
|
||||
except Exception as exc:
|
||||
print(f"kernels-community/flash-attn3 unavailable ({exc}); using matched torch SDPA on both sides.")
|
||||
_FLASH_ATTN3_HUB_AVAILABLE = False
|
||||
return _FLASH_ATTN3_HUB_AVAILABLE
|
||||
|
||||
|
||||
def _omni_server_env() -> dict[str, str] | None:
|
||||
if _flash_attn3_hub_available():
|
||||
return None
|
||||
return {"DIFFUSION_ATTENTION_BACKEND": "TORCH_SDPA"}
|
||||
|
||||
|
||||
def _set_reference_attention_backend(pipe: DiffusionPipeline) -> None:
|
||||
if _flash_attn3_hub_available():
|
||||
pipe.transformer.set_attention_backend("_flash_3_hub")
|
||||
else:
|
||||
pipe.transformer.set_attention_backend("native")
|
||||
|
||||
|
||||
def _model_name() -> str:
|
||||
return os.environ.get(MODEL_ENV_VAR, MODEL_ID)
|
||||
|
||||
@@ -115,7 +73,22 @@ def _local_files_only(model: str) -> bool:
|
||||
return Path(model).exists()
|
||||
|
||||
|
||||
_OMNI_FA3_HUB_BACKEND = "FLASH_ATTN_3_HUB"
|
||||
_OMNI_FA3_HUB_ENV = {"DIFFUSION_ATTENTION_BACKEND": _OMNI_FA3_HUB_BACKEND}
|
||||
|
||||
|
||||
def _assert_omni_fa3_hub_resolves() -> None:
|
||||
from vllm_omni.diffusion.attention.backends.registry import DiffusionAttentionBackendEnum
|
||||
from vllm_omni.platforms.cuda.platform import CudaOmniPlatform
|
||||
|
||||
path = CudaOmniPlatform.get_diffusion_attn_backend_cls(_OMNI_FA3_HUB_BACKEND, head_size=128)
|
||||
expected = DiffusionAttentionBackendEnum.FLASH_ATTN_3_HUB.get_path()
|
||||
assert path == expected, path
|
||||
print(f"Resolved Omni attention backend: {_OMNI_FA3_HUB_BACKEND} -> {path}")
|
||||
|
||||
|
||||
def _run_vllm_omni_qwen_image(*, model: str, output_path: Path) -> Image.Image:
|
||||
_assert_omni_fa3_hub_resolves()
|
||||
server_args = [
|
||||
"--num-gpus",
|
||||
"1",
|
||||
@@ -124,8 +97,10 @@ def _run_vllm_omni_qwen_image(*, model: str, output_path: Path) -> Image.Image:
|
||||
"--init-timeout",
|
||||
"900",
|
||||
"--fa-deterministic",
|
||||
"--diffusion-attention-backend",
|
||||
_OMNI_FA3_HUB_BACKEND,
|
||||
]
|
||||
with OmniServer(model, server_args, use_omni=True, env_dict=_omni_server_env()) as omni_server:
|
||||
with OmniServer(model, server_args, use_omni=True, env_dict=_OMNI_FA3_HUB_ENV) as omni_server:
|
||||
response = requests.post(
|
||||
f"http://{omni_server.host}:{omni_server.port}/v1/images/generations",
|
||||
json={
|
||||
@@ -161,7 +136,7 @@ def _run_diffusers_qwen_image(*, model: str, output_path: Path) -> Image.Image:
|
||||
trust_remote_code=True,
|
||||
local_files_only=_local_files_only(model),
|
||||
).to("cuda")
|
||||
_set_reference_attention_backend(pipe)
|
||||
pipe.transformer.set_attention_backend("_flash_3_hub")
|
||||
generator = torch.Generator(device="cuda").manual_seed(SEED)
|
||||
result = pipe( # pyright: ignore[reportCallIssue]
|
||||
prompt=PROMPT,
|
||||
@@ -186,8 +161,18 @@ def _run_diffusers_qwen_image(*, model: str, output_path: Path) -> Image.Image:
|
||||
|
||||
|
||||
def _run_vllm_omni_qwen_image_2512(*, model: str, output_path: Path) -> Image.Image:
|
||||
server_args = ["--num-gpus", "1", "--stage-init-timeout", "300", "--init-timeout", "900"]
|
||||
with OmniServer(model, server_args, use_omni=True, env_dict=_omni_server_env()) as omni_server:
|
||||
_assert_omni_fa3_hub_resolves()
|
||||
server_args = [
|
||||
"--num-gpus",
|
||||
"1",
|
||||
"--stage-init-timeout",
|
||||
"300",
|
||||
"--init-timeout",
|
||||
"900",
|
||||
"--diffusion-attention-backend",
|
||||
_OMNI_FA3_HUB_BACKEND,
|
||||
]
|
||||
with OmniServer(model, server_args, use_omni=True, env_dict=_OMNI_FA3_HUB_ENV) as omni_server:
|
||||
response = requests.post(
|
||||
f"http://{omni_server.host}:{omni_server.port}/v1/images/generations",
|
||||
json={
|
||||
@@ -223,7 +208,7 @@ def _run_diffusers_qwen_image_2512(*, model: str, output_path: Path) -> Image.Im
|
||||
trust_remote_code=True,
|
||||
local_files_only=_local_files_only(model),
|
||||
).to("cuda")
|
||||
_set_reference_attention_backend(pipe)
|
||||
pipe.transformer.set_attention_backend("_flash_3_hub")
|
||||
generator = torch.Generator(device="cuda").manual_seed(SEED_2512)
|
||||
result = pipe( # pyright: ignore[reportCallIssue]
|
||||
prompt=PROMPT_2512,
|
||||
@@ -262,7 +247,7 @@ def test_qwen_image_matches_diffusers(accuracy_artifact_root: Path) -> None:
|
||||
diffusers_image=diffusers_output,
|
||||
width=WIDTH,
|
||||
height=HEIGHT,
|
||||
ssim_threshold=SSIM_THRESHOLD if _flash_attn3_hub_available() else SSIM_THRESHOLD_SDPA_FALLBACK,
|
||||
ssim_threshold=SSIM_THRESHOLD,
|
||||
psnr_threshold=PSNR_THRESHOLD,
|
||||
)
|
||||
|
||||
|
||||
@@ -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"):
|
||||
|
||||
@@ -65,7 +65,12 @@ def _stage_config():
|
||||
# gains enough VRAM headroom for a no-eager run, add a companion test.
|
||||
return modify_stage_config(
|
||||
_CI_DEPLOY,
|
||||
updates={"stages": {0: {"enforce_eager": True}, 1: {"enforce_eager": True}}},
|
||||
updates={
|
||||
"stages": {
|
||||
0: {"enforce_eager": True, "moe_backend": "auto"},
|
||||
1: {"enforce_eager": True},
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -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)
|
||||
@@ -85,5 +85,7 @@ def test_text_only_nonstreaming_pcm_001(omni_server, openai_client) -> None:
|
||||
"voice": "default",
|
||||
"min_audio_bytes": _MIN_AUDIO_BYTES,
|
||||
"min_hnr_db": -2.0,
|
||||
# dots.tts-soar emits native 48 kHz PCM, which has no rate header.
|
||||
"expected_sample_rate": 48_000,
|
||||
}
|
||||
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),
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
@@ -24,6 +24,9 @@ from tests.helpers.stage_config import get_deploy_config_path, modify_stage_conf
|
||||
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
|
||||
|
||||
_MODEL = "openbmb/MiniCPM-o-4_5"
|
||||
_NATIVE_CHAT_TEMPLATE = (
|
||||
Path(__file__).resolve().parents[3] / "vllm_omni/transformers_utils/chat_templates/minicpmo45_native.jinja"
|
||||
)
|
||||
_CI_DEPLOY = modify_stage_config(
|
||||
get_deploy_config_path("minicpmo_4_5.yaml"),
|
||||
updates={
|
||||
@@ -63,7 +66,14 @@ test_params = [
|
||||
model=_MODEL,
|
||||
stage_config_path=_CI_DEPLOY,
|
||||
use_stage_cli=False,
|
||||
server_args=["--trust-remote-code", "--async-chunk"],
|
||||
server_args=[
|
||||
"--trust-remote-code",
|
||||
"--async-chunk",
|
||||
"--chat-template",
|
||||
str(_NATIVE_CHAT_TEMPLATE),
|
||||
"--chat-template-content-format",
|
||||
"openai",
|
||||
],
|
||||
env_dict={
|
||||
"VLLM_CONFIGURE_LOGGING": "1",
|
||||
"VLLM_LOGGING_CONFIG_PATH": str(_PROMPT_LOGGING_CONFIG_PATH),
|
||||
@@ -265,11 +275,18 @@ def test_image_to_text_audio_001(omni_server, openai_client) -> None:
|
||||
Input Setting: stream=True
|
||||
"""
|
||||
image_data_url = f"data:image/jpeg;base64,{generate_synthetic_image(24, 24)['base64']}"
|
||||
messages = dummy_messages_from_mix_data(
|
||||
system_prompt=get_system_prompt(),
|
||||
image_data_url=image_data_url,
|
||||
content_text=get_prompt("text_image"),
|
||||
)
|
||||
# Match the native image-chat layout explicitly; do not rely on the
|
||||
# renderer moving media placeholders ahead of text.
|
||||
messages = [
|
||||
get_system_prompt(),
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"type": "image_url", "image_url": {"url": image_data_url}},
|
||||
{"type": "text", "text": get_prompt("text_image")},
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
request_config = {
|
||||
"model": omni_server.model,
|
||||
|
||||
@@ -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 (
|
||||
@@ -926,10 +926,7 @@ def test_remote_replicas_use_distinct_init_group_keys():
|
||||
replica.launch_mode = "remote"
|
||||
replica.metadata.runtime_cfg = None
|
||||
|
||||
assert [runtime._replica_init_group_key(replica) for replica in plan.replicas] == [
|
||||
"remote:1:0",
|
||||
"remote:1:1",
|
||||
]
|
||||
assert runtime._init_group_keys(plan.replicas) == ["remote:1:0", "remote:1:1"]
|
||||
|
||||
|
||||
def test_initialize_stages_cleans_up_successful_replicas_after_partial_multi_replica_failure(monkeypatch):
|
||||
@@ -1596,73 +1593,58 @@ def test_model_path_resolver_is_generic_and_model_owned(tmp_path):
|
||||
assert "model_path_resolver" not in engine_args
|
||||
|
||||
|
||||
def test_build_stage0_input_processor_uses_omni_input_preprocessor(monkeypatch):
|
||||
def test_build_stage0_input_processor_uses_omni_renderer_subclass(monkeypatch):
|
||||
from vllm.renderers import BaseRenderer
|
||||
|
||||
import vllm_omni.engine.stage_init_utils as init_mod
|
||||
from vllm_omni.inputs.preprocess import OmniRenderer, omni_renderer_cls
|
||||
|
||||
class DummyInputProcessor:
|
||||
def __init__(self, vllm_config, renderer=None):
|
||||
self.vllm_config = vllm_config
|
||||
self.renderer = renderer or object()
|
||||
self.input_preprocessor = None
|
||||
class _Base(BaseRenderer):
|
||||
def __init__(self, config, tokenizer):
|
||||
self.config, self.tokenizer = config, tokenizer
|
||||
|
||||
class DummyOmniInputPreprocessor:
|
||||
def __init__(self, vllm_config, renderer=None):
|
||||
self.vllm_config = vllm_config
|
||||
self.renderer = renderer
|
||||
def render_messages(self, messages, params): # pragma: no cover - abstract stub
|
||||
raise NotImplementedError
|
||||
|
||||
monkeypatch.setattr(init_mod, "InputProcessor", DummyInputProcessor)
|
||||
monkeypatch.setattr(init_mod, "OmniInputPreprocessor", DummyOmniInputPreprocessor)
|
||||
|
||||
input_processor = build_stage0_input_processor(
|
||||
types.SimpleNamespace(model_config=types.SimpleNamespace(try_get_generation_config=lambda: {}))
|
||||
)
|
||||
|
||||
assert isinstance(input_processor.input_preprocessor, DummyOmniInputPreprocessor)
|
||||
assert input_processor.input_preprocessor.renderer is input_processor.renderer
|
||||
|
||||
|
||||
def test_build_stage0_input_processor_does_not_resolve_tokenizer_when_skipped(
|
||||
monkeypatch,
|
||||
):
|
||||
import vllm_omni.engine.stage_init_utils as init_mod
|
||||
|
||||
token_only_renderer = object()
|
||||
config = types.SimpleNamespace(model_config=types.SimpleNamespace(try_get_generation_config=lambda: {}))
|
||||
built = omni_renderer_cls(_Base)(config, "tok")
|
||||
seen = {}
|
||||
|
||||
class DummyInputProcessor:
|
||||
def __init__(self, vllm_config, renderer=None):
|
||||
if renderer is None:
|
||||
raise AssertionError("skip_tokenizer_init must supply a renderer")
|
||||
seen["renderer"] = renderer
|
||||
self.renderer = renderer
|
||||
self.input_preprocessor = None
|
||||
|
||||
class DummyOmniInputPreprocessor:
|
||||
def __init__(self, vllm_config, renderer=None):
|
||||
seen["preprocessor_renderer"] = renderer
|
||||
|
||||
monkeypatch.setattr(init_mod, "InputProcessor", DummyInputProcessor)
|
||||
monkeypatch.setattr(
|
||||
init_mod,
|
||||
"_build_token_only_renderer",
|
||||
lambda _config: token_only_renderer,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
init_mod,
|
||||
"OmniInputPreprocessor",
|
||||
DummyOmniInputPreprocessor,
|
||||
)
|
||||
monkeypatch.setattr(init_mod, "build_omni_renderer", lambda cfg: built if cfg is config else None)
|
||||
processor = build_stage0_input_processor(config)
|
||||
assert seen["renderer"] is built
|
||||
assert isinstance(processor.renderer, OmniRenderer)
|
||||
assert isinstance(processor.renderer, _Base)
|
||||
assert not hasattr(processor, "input_preprocessor")
|
||||
|
||||
|
||||
def test_build_stage0_input_processor_does_not_resolve_tokenizer_when_skipped(monkeypatch):
|
||||
import vllm_omni.engine.stage_init_utils as init_mod
|
||||
|
||||
original = object()
|
||||
|
||||
class DummyInputProcessor:
|
||||
def __init__(self, vllm_config, renderer=None):
|
||||
assert renderer is original
|
||||
self.renderer = renderer
|
||||
|
||||
def _must_not_resolve(_cfg):
|
||||
raise AssertionError("tokenizer must not be resolved when skip_tokenizer_init=True")
|
||||
|
||||
monkeypatch.setattr(init_mod, "InputProcessor", DummyInputProcessor)
|
||||
monkeypatch.setattr(init_mod, "_build_token_only_renderer", lambda _: original)
|
||||
monkeypatch.setattr(init_mod, "build_omni_renderer", _must_not_resolve)
|
||||
config = types.SimpleNamespace(
|
||||
model_config=types.SimpleNamespace(
|
||||
skip_tokenizer_init=True,
|
||||
try_get_generation_config=lambda: {},
|
||||
)
|
||||
model_config=types.SimpleNamespace(skip_tokenizer_init=True, try_get_generation_config=lambda: {})
|
||||
)
|
||||
build_stage0_input_processor(config)
|
||||
|
||||
assert seen["renderer"] is token_only_renderer
|
||||
assert seen["preprocessor_renderer"] is token_only_renderer
|
||||
processor = build_stage0_input_processor(config)
|
||||
assert processor.renderer is original
|
||||
|
||||
|
||||
def test_inject_kv_stage_info_infers_sender_tp_topology():
|
||||
@@ -1732,133 +1714,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):
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Unit tests for parallel stage initialization (CPU-only).
|
||||
|
||||
Covers the pure/lock logic added for ``parallel_stage_init``:
|
||||
* init-group device keying (resolved physical set; parallel unique keys),
|
||||
* init-group device keying (overlap components; parallel unique keys),
|
||||
* admission control arithmetic + graph reserve,
|
||||
* SH/EX device phase locks (real flock on a temp dir),
|
||||
* the phase-locked executor wrapper ordering,
|
||||
@@ -18,6 +21,7 @@ import inspect
|
||||
import os
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import types
|
||||
from pathlib import Path
|
||||
|
||||
@@ -37,7 +41,9 @@ from vllm_omni.engine.stage_init_utils import (
|
||||
LogicalStageInitPlan,
|
||||
ReplicaInitPlan,
|
||||
device_init_lock_path,
|
||||
device_overlap_group_keys,
|
||||
open_device_lock_file,
|
||||
parse_physical_device_ids,
|
||||
)
|
||||
from vllm_omni.engine.stage_phase_lock import (
|
||||
DeviceLockTimeoutError,
|
||||
@@ -46,6 +52,7 @@ from vllm_omni.engine.stage_phase_lock import (
|
||||
wrap_executor_with_phase_locks,
|
||||
)
|
||||
from vllm_omni.engine.stage_runtime import StageRuntime
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
@@ -104,49 +111,114 @@ def _fake_vllm_config(util: float, *, model="m", dtype="bf16", cudagraph_mode="F
|
||||
# --------------------------------------------------------------------------- #
|
||||
# A1: init-group device key
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_init_group_key_resolves_physical_devices_serial():
|
||||
@pytest.mark.parametrize(
|
||||
("devices", "expected"),
|
||||
[
|
||||
("0", {0}),
|
||||
("1,0,1", {0, 1}),
|
||||
(" 2, 3 ", {2, 3}),
|
||||
(None, None),
|
||||
("", None),
|
||||
("GPU-uuid", None),
|
||||
],
|
||||
)
|
||||
def test_parse_physical_device_ids(devices, expected):
|
||||
assert parse_physical_device_ids(devices) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("device_sets", "expected"),
|
||||
[
|
||||
# equal / disjoint
|
||||
([{0}, {1}, {0}], ["device-group:0", "device-group:1", "device-group:0"]),
|
||||
# unequal overlap, canonical order
|
||||
([{0, 1}, {0}, {2}], ["device-group:0,1", "device-group:0,1", "device-group:2"]),
|
||||
# transitive: {0,1} ~ {1,2} ~ {2}
|
||||
([{0, 1}, {1, 2}, {2}], ["device-group:0,1,2"] * 3),
|
||||
# unresolved may touch any GPU -> everything serial
|
||||
([{0}, None, {1}], ["device-group:*"] * 3),
|
||||
([], []),
|
||||
],
|
||||
)
|
||||
def test_device_overlap_group_keys(device_sets, expected):
|
||||
sets = [None if s is None else frozenset(s) for s in device_sets]
|
||||
assert device_overlap_group_keys(sets) == expected
|
||||
|
||||
|
||||
def test_init_group_keys_serial_groups_by_device_overlap():
|
||||
runtime = _runtime(parallel_stage_init=False)
|
||||
runtime._init_visible_devices_baseline = None # no CUDA_VISIBLE_DEVICES mapping
|
||||
r0 = _llm_replica(0, 0, "0")
|
||||
r1 = _llm_replica(1, 0, "1")
|
||||
r0b = _llm_replica(2, 0, "0")
|
||||
|
||||
k0 = runtime._replica_init_group_key(r0)
|
||||
k1 = runtime._replica_init_group_key(r1)
|
||||
k0b = runtime._replica_init_group_key(r0b)
|
||||
keys = runtime._init_group_keys(
|
||||
[_llm_replica(0, 0, "0,1"), _llm_replica(1, 0, "0"), _llm_replica(2, 0, "2"), _llm_replica(3, 0, "1,0")]
|
||||
)
|
||||
|
||||
assert k0 == "device:0"
|
||||
assert k1 == "device:1"
|
||||
# Different physical devices -> different groups (parallel).
|
||||
assert k0 != k1
|
||||
# Same physical device -> same group (serialized under LOCK_EX).
|
||||
assert k0 == k0b
|
||||
assert keys == ["device-group:0,1", "device-group:0,1", "device-group:2", "device-group:0,1"]
|
||||
|
||||
|
||||
def test_init_group_key_parallel_is_unique_per_replica():
|
||||
runtime = _runtime(parallel_stage_init=True)
|
||||
runtime._init_visible_devices_baseline = None
|
||||
# Both on the SAME device, but parallel mode must give distinct keys so they
|
||||
# run concurrently, coordinated by the child SH/EX locks + admission.
|
||||
keys = [
|
||||
runtime._replica_init_group_key(_llm_replica(0, 0, "0")),
|
||||
runtime._replica_init_group_key(_llm_replica(0, 1, "0")),
|
||||
runtime._replica_init_group_key(_llm_replica(1, 0, "0")),
|
||||
]
|
||||
assert keys == ["parallel:0:0", "parallel:0:1", "parallel:1:0"]
|
||||
assert len(set(keys)) == 3
|
||||
|
||||
|
||||
def test_init_group_key_remote_and_diffusion_unchanged():
|
||||
def test_init_group_keys_fixed_for_parallel_remote_and_diffusion():
|
||||
runtime = _runtime(parallel_stage_init=True)
|
||||
remote = _llm_replica(1, 0, "0")
|
||||
remote.launch_mode = "remote"
|
||||
remote.metadata.runtime_cfg = None
|
||||
assert runtime._replica_init_group_key(remote) == "remote:1:0"
|
||||
|
||||
diffusion = _llm_replica(2, 0, "0")
|
||||
diffusion.metadata.stage_type = "diffusion"
|
||||
assert runtime._replica_init_group_key(diffusion) == "inline:diffusion"
|
||||
|
||||
# Same device everywhere; parallel mode still keys per replica (child SH/EX locks coordinate).
|
||||
keys = runtime._init_group_keys([_llm_replica(0, 0, "0"), _llm_replica(0, 1, "0"), remote, diffusion])
|
||||
|
||||
assert keys == ["parallel:0:0", "parallel:0:1", "remote:1:0", "inline:diffusion"]
|
||||
|
||||
|
||||
def test_unresolved_devices_collapse_serial_groups_and_warn(caplog):
|
||||
runtime = _runtime(parallel_stage_init=False)
|
||||
with caplog.at_level("WARNING"):
|
||||
keys = runtime._init_group_keys([_llm_replica(0, 0, "0"), _llm_replica(1, 0, "GPU-uuid")])
|
||||
|
||||
assert keys == ["device-group:*", "device-group:*"]
|
||||
assert "Stage-1 replica 0" in caplog.text
|
||||
assert "GPU-uuid" in caplog.text
|
||||
|
||||
|
||||
def _stage_plans(*devices: str) -> list[LogicalStageInitPlan]:
|
||||
return [
|
||||
LogicalStageInitPlan(stage_idx=i, stage_id=i, replicas=[_llm_replica(i, 0, dev)])
|
||||
for i, dev in enumerate(devices)
|
||||
]
|
||||
|
||||
|
||||
def test_overlapping_device_stages_initialize_sequentially(monkeypatch):
|
||||
monkeypatch.delenv(current_omni_platform.device_control_env_var, raising=False)
|
||||
runtime = _runtime(parallel_stage_init=False)
|
||||
in_flight, peak = 0, 0
|
||||
guard = threading.Lock()
|
||||
|
||||
def _initialize_replica(plan, _timeout):
|
||||
nonlocal in_flight, peak
|
||||
with guard:
|
||||
in_flight += 1
|
||||
peak = max(peak, in_flight)
|
||||
time.sleep(0.05)
|
||||
with guard:
|
||||
in_flight -= 1
|
||||
return object()
|
||||
|
||||
monkeypatch.setattr(runtime, "_initialize_replica", _initialize_replica)
|
||||
runtime._initialize_stage_replicas(_stage_plans("0,1", "0"), stage_init_timeout=5)
|
||||
|
||||
assert peak == 1
|
||||
|
||||
|
||||
def test_disjoint_device_stages_initialize_in_parallel(monkeypatch):
|
||||
monkeypatch.delenv(current_omni_platform.device_control_env_var, raising=False)
|
||||
runtime = _runtime(parallel_stage_init=False)
|
||||
barrier = threading.Barrier(2, timeout=2) # breaks unless both inits are in flight together
|
||||
|
||||
def _initialize_replica(_plan, _timeout):
|
||||
barrier.wait()
|
||||
return object()
|
||||
|
||||
monkeypatch.setattr(runtime, "_initialize_replica", _initialize_replica)
|
||||
runtime._initialize_stage_replicas(_stage_plans("0", "1"), stage_init_timeout=5)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -11,6 +11,7 @@ from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from pydantic.fields import FieldInfo
|
||||
from transformers import Qwen3OmniMoeConfig
|
||||
from vllm.config import CacheConfig as VllmCacheConfig
|
||||
from vllm.config import CompilationConfig as VllmCompilationConfig
|
||||
from vllm.config import LoadConfig as VllmLoadConfig
|
||||
@@ -19,6 +20,7 @@ from vllm.config import ProfilerConfig as VllmProfilerConfig
|
||||
from vllm.config import SchedulerConfig as VllmSchedulerConfig
|
||||
from vllm.engine.arg_utils import EngineArgs
|
||||
|
||||
from tests.helpers.stage_config import get_deploy_config_path, modify_stage_config
|
||||
from vllm_omni.config.omni_config import (
|
||||
_LLM_STAGE_ENGINE_FIELDS,
|
||||
OmniStageCacheConfig,
|
||||
@@ -155,6 +157,44 @@ def test_qwen3_omni_preserves_explicit_moe_backend():
|
||||
assert engine_args["moe_backend"] == "flashinfer"
|
||||
|
||||
|
||||
def test_qwen3_omni_preserves_explicit_auto_moe_backend():
|
||||
engine_args = {
|
||||
"model_arch": "Qwen3OmniMoeForConditionalGeneration",
|
||||
"moe_backend": "auto",
|
||||
}
|
||||
|
||||
stage_init_utils._maybe_set_qwen3_omni_moe_backend(engine_args)
|
||||
|
||||
assert engine_args["moe_backend"] == "auto"
|
||||
|
||||
|
||||
def test_qwen3_omni_nvfp4_ci_config_preserves_auto_moe_backend(tmp_path):
|
||||
"""The NVFP4 CI deploy opts stage 0 into vLLM's auto backend selection."""
|
||||
hf_config = Qwen3OmniMoeConfig(enable_audio_output=True)
|
||||
pipeline = resolve_pipeline_config("qwen3_omni_moe", hf_config)
|
||||
assert pipeline is not None
|
||||
nvfp4_deploy = modify_stage_config(
|
||||
get_deploy_config_path("ci/qwen3_omni_moe.yaml"),
|
||||
updates={"stages": {0: {"moe_backend": "auto"}}},
|
||||
)
|
||||
deploy = load_deploy_config(nvfp4_deploy)
|
||||
legacy_stages = merge_pipeline_deploy(pipeline, copy.deepcopy(deploy))
|
||||
omni_config = VllmOmniConfig.from_pipeline_config(
|
||||
pipeline,
|
||||
user_deploy_config=copy.deepcopy(deploy),
|
||||
cli_overrides={"model": str(tmp_path)},
|
||||
)
|
||||
|
||||
for stage_id, expected_backend in ((0, "auto"), (1, "triton")):
|
||||
legacy_stage = next(stage for stage in legacy_stages if stage.stage_id == stage_id)
|
||||
typed_stage = omni_config.stage_by_id(stage_id)
|
||||
for engine_args in (
|
||||
build_engine_args_dict(legacy_stage.to_omegaconf(), str(tmp_path)),
|
||||
build_engine_args_dict_from_omni_stage_config(typed_stage, str(tmp_path)),
|
||||
):
|
||||
assert engine_args["moe_backend"] == expected_backend
|
||||
|
||||
|
||||
def _engine_arg_inputs(tmp_path: Path) -> tuple[PipelineConfig, DeployConfig, str]:
|
||||
parent_model = tmp_path / "parent-model"
|
||||
stage_model = tmp_path / "stage-model"
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Check replica startup ordering without model-loading timing assumptions."""
|
||||
|
||||
import contextlib
|
||||
import fcntl
|
||||
import os
|
||||
import threading
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from pytest_mock import MockerFixture
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.sampling_params import SamplingParams
|
||||
from vllm.v1.engine.utils import CoreEngineProcManager, EngineZmqAddresses
|
||||
|
||||
from vllm_omni.config.stage_config import StageConfig
|
||||
from vllm_omni.engine import stage_init_utils, stage_runtime
|
||||
from vllm_omni.engine.stage_engine_startup import StageReplicaResources
|
||||
from vllm_omni.engine.stage_init_utils import LogicalStageInitPlan, ReplicaInitPlan, StageMetadata
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def launch_runtime(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, mocker: MockerFixture
|
||||
) -> Iterator[stage_runtime.StageRuntime]:
|
||||
runtime = stage_runtime.StageRuntime(
|
||||
stage_configs=[],
|
||||
model="dummy-model",
|
||||
config_path="dummy-config",
|
||||
stage_init_timeout=5,
|
||||
async_chunk=False,
|
||||
)
|
||||
# These are virtual device IDs: only the real per-device file locking and
|
||||
# scheduling run. No model, CUDA context, or engine process is created.
|
||||
monkeypatch.setattr(runtime, "_resolve_replica_physical_devices", lambda _stage, cfg: cfg["devices"])
|
||||
monkeypatch.setattr(
|
||||
stage_init_utils, "device_init_lock_path", lambda device: str(tmp_path / f"device-{device}.lock")
|
||||
)
|
||||
mocker.patch.object(
|
||||
stage_runtime.StageEngineCoreClientBase,
|
||||
"make_async_mp_client",
|
||||
return_value=mocker.Mock(spec=stage_runtime.StageClient),
|
||||
)
|
||||
monkeypatch.setenv("VLLM_OMNI_TEST_LAUNCH_ENV", "parent")
|
||||
yield runtime
|
||||
if runtime._stage_init_executor is not None:
|
||||
runtime._stage_init_executor.shutdown(wait=True)
|
||||
|
||||
|
||||
def _plan(stage_id: int, device: str) -> LogicalStageInitPlan:
|
||||
metadata = StageMetadata(
|
||||
stage_id=stage_id,
|
||||
stage_type="llm",
|
||||
engine_output_type="text",
|
||||
is_comprehension=False,
|
||||
requires_multimodal_data=False,
|
||||
engine_input_source=[],
|
||||
final_output=False,
|
||||
final_output_type=None,
|
||||
default_sampling_params=SamplingParams(),
|
||||
custom_process_input_func=None,
|
||||
model_stage="dummy",
|
||||
runtime_cfg={"devices": device, "env": {"VLLM_OMNI_TEST_LAUNCH_ENV": str(stage_id)}},
|
||||
)
|
||||
replica = ReplicaInitPlan(
|
||||
replica_id=0,
|
||||
num_replicas=1,
|
||||
launch_mode="local",
|
||||
stage_cfg=StageConfig(stage_id=stage_id, model_stage="dummy", yaml_runtime=metadata.runtime_cfg),
|
||||
metadata=metadata,
|
||||
stage_connector_spec={},
|
||||
omni_kv_connector=(None, None, None),
|
||||
stage_vllm_config=VllmConfig(),
|
||||
executor_class=object,
|
||||
engine_args_dict={},
|
||||
)
|
||||
return LogicalStageInitPlan(stage_idx=stage_id, stage_id=stage_id, replicas=[replica])
|
||||
|
||||
|
||||
def _resources(mocker: MockerFixture) -> StageReplicaResources:
|
||||
return StageReplicaResources(
|
||||
manager=mocker.Mock(spec=CoreEngineProcManager),
|
||||
addresses=EngineZmqAddresses(inputs=["unused-input"], outputs=["unused-output"]),
|
||||
)
|
||||
|
||||
|
||||
def test_distinct_devices_spawn_before_either_is_ready(
|
||||
launch_runtime: stage_runtime.StageRuntime, monkeypatch: pytest.MonkeyPatch, mocker: MockerFixture
|
||||
) -> None:
|
||||
spawned = [threading.Event(), threading.Event()]
|
||||
|
||||
@contextlib.contextmanager
|
||||
def launch(*, stage_id: int, stage_visible_devices: str, **_kwargs: object) -> Iterator[StageReplicaResources]:
|
||||
assert os.environ["VLLM_OMNI_TEST_LAUNCH_ENV"] == str(stage_id)
|
||||
spawned[stage_id].set()
|
||||
yield _resources(mocker)
|
||||
# The device remains exclusively locked throughout loading/profiling,
|
||||
# even though another device's replica must be able to start.
|
||||
with open(stage_init_utils.device_init_lock_path(int(stage_visible_devices)), "r+") as lock:
|
||||
with pytest.raises(BlockingIOError):
|
||||
fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
assert spawned[1 - stage_id].wait(5), "A different device's spawn was blocked by the READY wait"
|
||||
|
||||
monkeypatch.setattr(stage_runtime, "launch_stage_replica", launch)
|
||||
clients = launch_runtime._initialize_stage_replicas([_plan(0, "0"), _plan(1, "1")], 5)
|
||||
assert all(clients[stage][0] is not None for stage in (0, 1))
|
||||
assert os.environ["VLLM_OMNI_TEST_LAUNCH_ENV"] == "parent"
|
||||
|
||||
|
||||
def test_same_device_waits_for_ready_before_next_spawn(
|
||||
launch_runtime: stage_runtime.StageRuntime, monkeypatch: pytest.MonkeyPatch, mocker: MockerFixture
|
||||
) -> None:
|
||||
events: list[tuple[int, str]] = []
|
||||
|
||||
@contextlib.contextmanager
|
||||
def launch(*, stage_id: int, **_kwargs: object) -> Iterator[StageReplicaResources]:
|
||||
events.append((stage_id, "spawn"))
|
||||
yield _resources(mocker)
|
||||
events.append((stage_id, "ready"))
|
||||
|
||||
monkeypatch.setattr(stage_runtime, "launch_stage_replica", launch)
|
||||
launch_runtime._initialize_stage_replicas([_plan(0, "0"), _plan(1, "0")], 5)
|
||||
assert events == [(0, "spawn"), (0, "ready"), (1, "spawn"), (1, "ready")]
|
||||
assert os.environ["VLLM_OMNI_TEST_LAUNCH_ENV"] == "parent"
|
||||
|
||||
|
||||
def test_ready_failure_cleans_up_resources_and_releases_device(
|
||||
launch_runtime: stage_runtime.StageRuntime, monkeypatch: pytest.MonkeyPatch, mocker: MockerFixture
|
||||
) -> None:
|
||||
manager = mocker.Mock(spec=CoreEngineProcManager)
|
||||
resources = StageReplicaResources(manager=manager, addresses=EngineZmqAddresses(inputs=[], outputs=[]))
|
||||
|
||||
@contextlib.contextmanager
|
||||
def launch(**_kwargs: object) -> Iterator[StageReplicaResources]:
|
||||
yield resources
|
||||
raise RuntimeError("READY handshake failed")
|
||||
|
||||
monkeypatch.setattr(stage_runtime, "launch_stage_replica", launch)
|
||||
with pytest.raises(RuntimeError, match="READY handshake failed"):
|
||||
launch_runtime._initialize_local_llm_replica(_plan(0, "0").replicas[0], 5)
|
||||
|
||||
manager.shutdown.assert_called_once_with()
|
||||
assert os.environ["VLLM_OMNI_TEST_LAUNCH_ENV"] == "parent"
|
||||
with open(stage_init_utils.device_init_lock_path(0), "r+") as lock:
|
||||
fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
@@ -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
|
||||
@@ -1,3 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import asyncio
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
@@ -12,7 +15,7 @@ from vllm.entrypoints.openai.chat_completion.protocol import (
|
||||
ChatCompletionResponseChoice,
|
||||
ChatMessage,
|
||||
)
|
||||
from vllm.entrypoints.openai.engine.protocol import ErrorResponse, UsageInfo
|
||||
from vllm.entrypoints.serve.engine.protocol import ErrorResponse, UsageInfo
|
||||
|
||||
from vllm_omni.entrypoints.openai.batch_serving import OmniOpenAIServingChatBatch
|
||||
|
||||
|
||||
Loaded 100 of 513 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user