Merge remote-tracking branch 'origin/main' into qwen-image-2.1
# Conflicts: # tests/entrypoints/openai_api/test_image_server.py # vllm_omni/entrypoints/openai/api_server.py
This commit is contained in:
commit
3e274a0024
220 files changed
+22342
-1079
No files matched your search
@@ -0,0 +1,157 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm_omni.benchmarks.omniinteract import _session_capabilities, _wants_annotation_video_clock
|
||||
from vllm_omni.model_executor.models.aura_omni.benchmarks.omniinteract_clock import (
|
||||
stream_annotation_clock,
|
||||
wants_annotation_video_clock,
|
||||
)
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
class _Events:
|
||||
def __init__(self, events):
|
||||
self.events = events
|
||||
|
||||
|
||||
class _Client:
|
||||
def __init__(self, capabilities):
|
||||
self.events = _Events([{"type": "session.created", "session": {"capabilities": capabilities}}])
|
||||
self._client = None
|
||||
|
||||
|
||||
def test_annotation_clock_follows_capabilities_not_model_name():
|
||||
aura = {"required_input_modalities": ["video"], "supports_turn_commit_only": True}
|
||||
minicpm = {"required_input_modalities": ["audio"], "supports_turn_commit_only": False}
|
||||
audio_commit = {"required_input_modalities": ["audio"], "supports_turn_commit_only": True}
|
||||
assert wants_annotation_video_clock(aura)
|
||||
assert not wants_annotation_video_clock(minicpm)
|
||||
assert not wants_annotation_video_clock(audio_commit)
|
||||
assert not wants_annotation_video_clock(None)
|
||||
assert _wants_annotation_video_clock(_Client(minicpm)) is False
|
||||
assert _wants_annotation_video_clock(_Client(aura)) is True
|
||||
assert _session_capabilities(_Client(aura))["required_input_modalities"] == ["video"]
|
||||
|
||||
|
||||
def test_annotation_clock_commits_only_the_due_wav(monkeypatch, tmp_path: Path):
|
||||
video = tmp_path / "videos" / "0002.mp4"
|
||||
video.parent.mkdir()
|
||||
video.write_bytes(b"")
|
||||
sent = []
|
||||
|
||||
class Client:
|
||||
async def send(self, event):
|
||||
sent.append(event)
|
||||
|
||||
async def commit(self):
|
||||
sent.append({"type": "commit"})
|
||||
|
||||
class Playback:
|
||||
async def acknowledge(self, client):
|
||||
del client
|
||||
|
||||
monkeypatch.setattr(
|
||||
"vllm_omni.model_executor.models.aura_omni.benchmarks.omniinteract_clock.load_annotation_utterances",
|
||||
lambda path: [{"at_sec": 0.0, "pcm": b"\x01\x00" * 160, "sent": False, "qa_index": 0}],
|
||||
)
|
||||
chunks, frames, _, _ = asyncio.run(
|
||||
stream_annotation_clock(
|
||||
Client(),
|
||||
["frame-a", "frame-b"],
|
||||
Playback(),
|
||||
video_path=video,
|
||||
fps=2.0,
|
||||
)
|
||||
)
|
||||
assert (chunks, frames) == (2, 2)
|
||||
assert sent[0]["is_speech"] is True
|
||||
assert sent[0]["video_frames"] == ["frame-a"]
|
||||
assert sent[1] == {"type": "commit"}
|
||||
# The trailing silent frame is one vision turn, committed after the clip.
|
||||
assert sent[2]["is_speech"] is False
|
||||
assert sent[2]["video_frames"] == ["frame-b"]
|
||||
assert sent[3] == {"type": "commit"}
|
||||
assert sent.count({"type": "commit"}) == 2
|
||||
|
||||
|
||||
def test_annotation_clock_commits_silent_frames_in_pairs(monkeypatch, tmp_path: Path):
|
||||
video = tmp_path / "videos" / "0002.mp4"
|
||||
video.parent.mkdir()
|
||||
video.write_bytes(b"")
|
||||
sent = []
|
||||
|
||||
class Client:
|
||||
async def send(self, event):
|
||||
sent.append(event)
|
||||
|
||||
async def commit(self):
|
||||
sent.append({"type": "commit"})
|
||||
|
||||
class Playback:
|
||||
async def acknowledge(self, client):
|
||||
del client
|
||||
|
||||
monkeypatch.setattr(
|
||||
"vllm_omni.model_executor.models.aura_omni.benchmarks.omniinteract_clock.load_annotation_utterances",
|
||||
lambda path: [{"at_sec": 100.0, "pcm": b"\x01\x00" * 160, "sent": False, "qa_index": 0}],
|
||||
)
|
||||
asyncio.run(
|
||||
stream_annotation_clock(
|
||||
Client(),
|
||||
["f1", "f2", "f3", "f4"],
|
||||
Playback(),
|
||||
video_path=video,
|
||||
fps=2.0,
|
||||
)
|
||||
)
|
||||
vision = [event for event in sent if event.get("is_speech") is False]
|
||||
assert [event["video_frames"] for event in vision] == [["f1", "f2"], ["f3", "f4"]]
|
||||
assert sent.count({"type": "commit"}) == 2
|
||||
|
||||
|
||||
def test_annotation_clock_holds_vision_while_a_response_is_open(monkeypatch, tmp_path: Path):
|
||||
video = tmp_path / "videos" / "0002.mp4"
|
||||
video.parent.mkdir()
|
||||
video.write_bytes(b"")
|
||||
sent = []
|
||||
|
||||
class Events:
|
||||
def __init__(self):
|
||||
self.events = [{"type": "response.created", "response": {"id": "resp-open"}}]
|
||||
|
||||
class Client:
|
||||
def __init__(self):
|
||||
self.events = Events()
|
||||
|
||||
async def send(self, event):
|
||||
sent.append(event)
|
||||
|
||||
async def commit(self):
|
||||
sent.append({"type": "commit"})
|
||||
|
||||
class Playback:
|
||||
async def acknowledge(self, client):
|
||||
del client
|
||||
|
||||
monkeypatch.setattr(
|
||||
"vllm_omni.model_executor.models.aura_omni.benchmarks.omniinteract_clock.load_annotation_utterances",
|
||||
lambda path: [{"at_sec": 100.0, "pcm": b"\x01\x00" * 160, "sent": False, "qa_index": 0}],
|
||||
)
|
||||
asyncio.run(
|
||||
stream_annotation_clock(
|
||||
Client(),
|
||||
["f1", "f2", "f3", "f4"],
|
||||
Playback(),
|
||||
video_path=video,
|
||||
fps=2.0,
|
||||
)
|
||||
)
|
||||
assert sent == []
|
||||
@@ -0,0 +1,798 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Unit tests for the LingBot-World realtime streaming benchmark.
|
||||
|
||||
The arithmetic is tested against the server's own formulas rather than against
|
||||
hand-copied expectations, and the protocol handling runs against a real
|
||||
WebSocket server that replays ``/v1/realtime/video`` with scripted delays -- so
|
||||
a benchmark number can be wrong only if the server itself is, not because the
|
||||
client parsed incorrectly an event or timed the wrong edge.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
# ruff: noqa: E402, I001
|
||||
import asyncio
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.diffusion, pytest.mark.cpu]
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
if str(REPO_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(REPO_ROOT))
|
||||
|
||||
from benchmarks.lingbot_world.benchmark_lingbot_world_realtime import (
|
||||
BenchmarkError,
|
||||
build_workload,
|
||||
print_report,
|
||||
endpoint_url,
|
||||
parse_args,
|
||||
resolve_image_reference,
|
||||
run_session,
|
||||
)
|
||||
from benchmarks.lingbot_world.workload import (
|
||||
DEFAULT_WARMUP_CHUNKS,
|
||||
FRAMES_PER_BLOCK,
|
||||
ChunkRecord,
|
||||
PromptUpdate,
|
||||
Workload,
|
||||
aggregate_metrics,
|
||||
build_camera_script,
|
||||
chunks_for_num_frames,
|
||||
compute_metrics,
|
||||
default_workload,
|
||||
load_workload,
|
||||
num_frames_for_chunks,
|
||||
percentile,
|
||||
pixel_frames_in_chunk,
|
||||
simulate_playback,
|
||||
steady_chunk_deadline_ms,
|
||||
)
|
||||
|
||||
_IMAGE = "data:image/png;base64,Zm9v"
|
||||
|
||||
|
||||
def _workload(num_chunks: int = 8, fps: int = 16) -> Workload:
|
||||
return default_workload(image_reference=_IMAGE, num_chunks=num_chunks, fps=fps)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Chunk and frame arithmetic
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
@pytest.mark.parametrize("num_chunks", list(range(1, 33)))
|
||||
def test_frame_count_round_trips_through_the_server_formula(num_chunks: int) -> None:
|
||||
"""``num_frames`` must land on a rollout of exactly the requested chunks.
|
||||
|
||||
The server derives chunk count as ``((num_frames - 1) // 4 + 1) // 3``; if
|
||||
the benchmark's inverse is off by one frame the run silently generates a
|
||||
different number of blocks than it reports.
|
||||
"""
|
||||
assert chunks_for_num_frames(num_frames_for_chunks(num_chunks)) == num_chunks
|
||||
|
||||
|
||||
def test_recipe_frame_counts_match_the_documented_chunk_counts() -> None:
|
||||
# The recipe states three chunks for num_frames 33 and seven for 81.
|
||||
assert chunks_for_num_frames(33) == 3
|
||||
assert chunks_for_num_frames(81) == 7
|
||||
assert num_frames_for_chunks(3) == 33
|
||||
assert num_frames_for_chunks(7) == 81
|
||||
|
||||
|
||||
def test_first_chunk_is_short_because_the_decoder_expands_it_once() -> None:
|
||||
assert pixel_frames_in_chunk(0) == 9
|
||||
assert pixel_frames_in_chunk(1) == 12
|
||||
assert pixel_frames_in_chunk(7) == 12
|
||||
# A whole rollout's frames are the sum of its chunks' frames.
|
||||
assert sum(pixel_frames_in_chunk(index) for index in range(5)) == num_frames_for_chunks(5)
|
||||
|
||||
|
||||
def test_camera_script_holds_one_three_entry_action_list_per_chunk() -> None:
|
||||
script = build_camera_script(4, "orbit")
|
||||
assert len(script) == 4
|
||||
assert all(len(actions) == FRAMES_PER_BLOCK for actions in script)
|
||||
# orbit advances through the action keys so successive chunks differ.
|
||||
assert script[0] != script[1]
|
||||
|
||||
|
||||
def test_unknown_camera_pattern_is_rejected() -> None:
|
||||
with pytest.raises(ValueError, match="Unknown camera pattern"):
|
||||
build_camera_script(2, "sideways")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Workload
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
def test_session_start_payload_matches_the_documented_protocol() -> None:
|
||||
workload = _workload(num_chunks=3)
|
||||
payload = workload.session_start_payload("robbyant/lingbot-world-v2-14b-causal-fast-diffusers")
|
||||
assert payload["type"] == "session.start"
|
||||
assert payload["num_frames"] == 33
|
||||
assert payload["image_reference"] == {"image_url": _IMAGE}
|
||||
assert payload["extra_params"]["flow_shift"] == 5.0
|
||||
assert len(payload["extra_params"]["camera_action_script"]) == 3
|
||||
|
||||
|
||||
def test_workload_rejects_a_camera_script_with_the_wrong_block_width() -> None:
|
||||
with pytest.raises(ValueError, match="exactly 3 action lists"):
|
||||
Workload(prompt="p", image_reference=_IMAGE, camera_script=[[["w"], ["w"]]])
|
||||
|
||||
|
||||
def test_workload_rejects_geometry_the_cache_cannot_serve() -> None:
|
||||
with pytest.raises(ValueError, match="multiples of 16"):
|
||||
Workload(prompt="p", image_reference=_IMAGE, camera_script=build_camera_script(1, "forward"), width=831)
|
||||
|
||||
|
||||
def test_prompt_update_beyond_the_rollout_is_rejected() -> None:
|
||||
with pytest.raises(ValueError, match="never fires"):
|
||||
Workload(
|
||||
prompt="p",
|
||||
image_reference=_IMAGE,
|
||||
camera_script=build_camera_script(2, "forward"),
|
||||
prompt_updates=(PromptUpdate(after_chunk=5, prompt="later"),),
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("from_file", [False, True])
|
||||
def test_duplicate_prompt_update_boundaries_are_rejected(tmp_path: Path, from_file: bool) -> None:
|
||||
updates = [
|
||||
{"after_chunk": 1, "prompt": "Rain begins"},
|
||||
{"after_chunk": 0, "prompt": "Clouds gather"},
|
||||
{"after_chunk": 1, "prompt": "Rain stops"},
|
||||
]
|
||||
with pytest.raises(ValueError, match="Duplicate prompt update after chunk 1"):
|
||||
if from_file:
|
||||
path = tmp_path / "rollout.json"
|
||||
path.write_text(json.dumps({"image": _IMAGE, "num_chunks": 3, "prompt_updates": updates}))
|
||||
build_workload(parse_args(["--workload", str(path)]))
|
||||
else:
|
||||
Workload(
|
||||
prompt="p",
|
||||
image_reference=_IMAGE,
|
||||
camera_script=build_camera_script(3, "forward"),
|
||||
prompt_updates=(
|
||||
PromptUpdate(after_chunk=1, prompt="Rain begins"),
|
||||
PromptUpdate(after_chunk=0, prompt="Clouds gather"),
|
||||
PromptUpdate(after_chunk=1, prompt="Rain stops"),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def test_workload_file_is_loaded_and_cli_overrides_win(tmp_path: Path) -> None:
|
||||
path = tmp_path / "rollout.json"
|
||||
path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"prompt": "A quiet street",
|
||||
"image": "https://example.invalid/frame.png",
|
||||
"num_chunks": 4,
|
||||
"camera_pattern": "hold",
|
||||
"fps": 12,
|
||||
"seed": 7,
|
||||
"prompt_updates": [{"after_chunk": 1, "prompt": "Rain begins", "transition_chunks": 2}],
|
||||
}
|
||||
)
|
||||
)
|
||||
workload = load_workload(path, overrides={"fps": 24, "seed": None})
|
||||
assert workload.prompt == "A quiet street"
|
||||
assert workload.num_chunks == 4
|
||||
assert workload.fps == 24, "an explicit CLI value must beat the file"
|
||||
assert workload.seed == 7, "a None override must leave the file value alone"
|
||||
assert workload.prompt_updates[0].transition_chunks == 2
|
||||
|
||||
|
||||
def test_workload_file_without_a_rollout_length_is_rejected(tmp_path: Path) -> None:
|
||||
path = tmp_path / "rollout.json"
|
||||
path.write_text(json.dumps({"image": "https://example.invalid/frame.png"}))
|
||||
with pytest.raises(ValueError, match="camera_action_script or num_chunks"):
|
||||
load_workload(path)
|
||||
|
||||
|
||||
def test_local_image_is_inlined_as_a_data_url(tmp_path: Path) -> None:
|
||||
image = tmp_path / "frame.png"
|
||||
image.write_bytes(b"\x89PNG\r\n\x1a\n")
|
||||
reference = resolve_image_reference(str(image))
|
||||
assert reference.startswith("data:image/png;base64,")
|
||||
assert resolve_image_reference("https://example.invalid/a.png") == "https://example.invalid/a.png"
|
||||
with pytest.raises(BenchmarkError, match="neither a URL nor a readable file"):
|
||||
resolve_image_reference(str(tmp_path / "missing.png"))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Metric math
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
def test_rtf_is_a_cost_not_a_speed() -> None:
|
||||
"""RTF must match vLLM-Omni's own formula, where lower is better.
|
||||
|
||||
``vllm_omni/metrics/definitions.py::compute_audio_rtf`` is
|
||||
``latency / duration`` with the docstring "SLO red line < 1", and
|
||||
``benchmarks/patch/patch.py`` sets ``video_rtf = generation_s /
|
||||
video_duration``. Emitting the reciprocal under the same field name would
|
||||
silently invert every dashboard that aggregates it, so the direction is
|
||||
pinned here rather than left to a comment.
|
||||
"""
|
||||
# Two chunks, 9 + 12 = 21 frames at 12 fps = 1.75 s of video, generated in 3.5 s.
|
||||
slow = compute_metrics(_records([1.0, 2.5]), fps=12, warmup_chunks=0, session_wall_s=3.5)
|
||||
assert slow["video_seconds"] == pytest.approx(1.75)
|
||||
assert slow["video_rtf"] == pytest.approx(2.0), "twice as slow as real time"
|
||||
assert slow["video_rtfx"] == pytest.approx(0.5)
|
||||
|
||||
fast = compute_metrics(_records([0.4, 0.475]), fps=12, warmup_chunks=0, session_wall_s=0.875)
|
||||
assert fast["video_rtf"] == pytest.approx(0.5), "twice as fast as real time"
|
||||
assert fast["video_rtf"] < 1.0 < slow["video_rtf"]
|
||||
assert fast["video_rtf"] * fast["video_rtfx"] == pytest.approx(1.0)
|
||||
|
||||
|
||||
def test_steady_rtf_is_the_chunk_interval_over_its_deadline() -> None:
|
||||
"""A steady chunk's RTF is just its interval divided by its video duration."""
|
||||
metrics = compute_metrics(_records([1.0] + [1.357] * 15), fps=12, warmup_chunks=6)
|
||||
# 12 frames at 12 fps = 1000 ms of video per steady chunk.
|
||||
assert metrics["chunk_deadline_ms"] == pytest.approx(1000.0)
|
||||
assert metrics["steady_video_rtf"] == pytest.approx(1.357, abs=1e-3)
|
||||
|
||||
|
||||
def test_percentile_interpolates_so_short_runs_still_report_tails() -> None:
|
||||
values = [10.0, 20.0, 30.0, 40.0]
|
||||
assert percentile(values, 0.0) == 10.0
|
||||
assert percentile(values, 1.0) == 40.0
|
||||
assert percentile(values, 0.5) == 25.0
|
||||
assert percentile([5.0], 0.99) == 5.0
|
||||
|
||||
|
||||
def _records(intervals: list[float]) -> list[ChunkRecord]:
|
||||
"""One record per entry; ``intervals[0]`` is the TTFC, the rest are gaps."""
|
||||
records: list[ChunkRecord] = []
|
||||
arrival = 0.0
|
||||
for index, interval in enumerate(intervals):
|
||||
arrival += interval
|
||||
records.append(
|
||||
ChunkRecord(
|
||||
index=index,
|
||||
arrival_s=arrival,
|
||||
inter_arrival_s=interval,
|
||||
byte_length=1000,
|
||||
num_frames=pixel_frames_in_chunk(index),
|
||||
)
|
||||
)
|
||||
return records
|
||||
|
||||
|
||||
def test_steady_state_excludes_the_unsaturated_attention_window() -> None:
|
||||
"""Warmup chunks must not drag the steady-state mean down.
|
||||
|
||||
The first six chunks attend over a growing window, so they are genuinely
|
||||
cheaper. A benchmark that averages them in reports a cadence the session
|
||||
will never sustain.
|
||||
"""
|
||||
intervals = [1.0] + [0.2] * (DEFAULT_WARMUP_CHUNKS - 1) + [0.8] * 4
|
||||
metrics = compute_metrics(_records(intervals), fps=16, warmup_chunks=DEFAULT_WARMUP_CHUNKS)
|
||||
assert metrics["interval_steady"]["count"] == 3
|
||||
assert metrics["interval_steady"]["mean_ms"] == pytest.approx(800.0)
|
||||
assert metrics["interval_all"]["mean_ms"] < metrics["interval_steady"]["mean_ms"]
|
||||
|
||||
|
||||
def test_short_rollouts_report_that_steady_state_was_never_reached() -> None:
|
||||
metrics = compute_metrics(_records([1.0, 0.5, 0.5]), fps=16, warmup_chunks=DEFAULT_WARMUP_CHUNKS)
|
||||
assert metrics["steady_state_reached"] is False
|
||||
assert metrics["interval_steady"] == {}
|
||||
assert "slo_attainment" not in metrics
|
||||
|
||||
|
||||
def test_real_time_factor_and_deadline_use_the_true_frame_counts() -> None:
|
||||
# Eight chunks: 9 + 7*12 = 93 frames at 16 fps = 5.8125 s of video.
|
||||
metrics = compute_metrics(_records([1.0] + [0.5] * 7), fps=16, warmup_chunks=0, session_wall_s=5.8125)
|
||||
assert metrics["total_frames"] == 93
|
||||
assert metrics["video_seconds"] == pytest.approx(5.8125)
|
||||
assert metrics["video_rtf"] == pytest.approx(1.0)
|
||||
assert metrics["video_rtfx"] == pytest.approx(1.0)
|
||||
# A steady chunk carries 12 frames, so real time allows 750 ms at 16 fps.
|
||||
assert metrics["chunk_deadline_ms"] == pytest.approx(750.0)
|
||||
assert steady_chunk_deadline_ms(12) == pytest.approx(1000.0)
|
||||
|
||||
|
||||
def test_slo_attainment_counts_only_steady_chunks() -> None:
|
||||
intervals = [1.0] + [0.1] * 5 + [0.7, 0.9, 0.7, 0.9]
|
||||
metrics = compute_metrics(_records(intervals), fps=16, warmup_chunks=6, slo_ms=750.0)
|
||||
assert metrics["slo_attainment"] == pytest.approx(2 / 3)
|
||||
assert metrics["slo_violations"] == 1
|
||||
|
||||
|
||||
def test_playback_simulation_finds_stalls_a_percentile_would_hide() -> None:
|
||||
"""One late chunk behind a one-chunk buffer is a visible stall."""
|
||||
# 12 frames at 16 fps = 750 ms of playback per chunk; chunk 3 takes 2 s.
|
||||
intervals = [1.0, 0.5, 0.5, 2.0, 0.5]
|
||||
result = simulate_playback(_records(intervals), fps=16, buffer_chunks=1)
|
||||
assert result.underrun_count >= 1
|
||||
assert result.first_underrun_chunk == 3
|
||||
assert result.total_stall_s > 0.0
|
||||
|
||||
|
||||
def test_a_deeper_buffer_absorbs_the_same_jitter() -> None:
|
||||
intervals = [1.0, 0.5, 0.5, 1.4, 0.2, 0.2]
|
||||
fast = simulate_playback(_records(intervals), fps=16, buffer_chunks=1)
|
||||
buffered = simulate_playback(_records(intervals), fps=16, buffer_chunks=3)
|
||||
assert buffered.underrun_count < fast.underrun_count
|
||||
|
||||
|
||||
def test_playback_rejects_a_buffer_deeper_than_the_rollout() -> None:
|
||||
with pytest.raises(ValueError, match="exceeds"):
|
||||
simulate_playback(_records([1.0, 0.5]), fps=16, buffer_chunks=9)
|
||||
|
||||
|
||||
def test_aggregate_pools_sessions_and_reports_spread() -> None:
|
||||
fast = compute_metrics(_records([1.0] + [0.1] * 5 + [0.6] * 4), fps=16, warmup_chunks=6)
|
||||
slow = compute_metrics(_records([1.0] + [0.1] * 5 + [0.9] * 4), fps=16, warmup_chunks=6)
|
||||
aggregate = aggregate_metrics([fast, slow], fps=16)
|
||||
assert aggregate["sessions"] == 2
|
||||
assert aggregate["steady_interval_ms_mean"] == pytest.approx(750.0)
|
||||
assert aggregate["steady_interval_ms_spread"] == pytest.approx(300.0)
|
||||
assert aggregate["video_rtf_best"] <= aggregate["video_rtf_mean"] <= aggregate["video_rtf_worst"]
|
||||
|
||||
|
||||
def test_single_session_aggregate_is_the_session_itself() -> None:
|
||||
metrics = compute_metrics(_records([1.0] + [0.5] * 3), fps=16, warmup_chunks=0)
|
||||
aggregate = aggregate_metrics([metrics], fps=16)
|
||||
assert aggregate["sessions"] == 1
|
||||
assert aggregate["video_rtf"] == metrics["video_rtf"]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# CLI
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
def test_endpoint_url_normalizes_http_and_appends_the_ws_path() -> None:
|
||||
assert endpoint_url(parse_args([])) == "ws://127.0.0.1:8000/v1/realtime/video"
|
||||
assert endpoint_url(parse_args(["--host", "h", "--port", "9"])) == "ws://h:9/v1/realtime/video"
|
||||
args = parse_args(["--base-url", "http://example.invalid:8099"])
|
||||
assert endpoint_url(args) == "ws://example.invalid:8099/v1/realtime/video"
|
||||
args = parse_args(["--base-url", "ws://example.invalid:8099/v1/realtime/video"])
|
||||
assert endpoint_url(args) == "ws://example.invalid:8099/v1/realtime/video"
|
||||
|
||||
|
||||
def test_cli_rejects_a_zero_chunk_buffer() -> None:
|
||||
with pytest.raises(SystemExit):
|
||||
parse_args(["--playback-buffer-chunks", "0"])
|
||||
with pytest.raises(SystemExit):
|
||||
parse_args(["--target-fps", "0"])
|
||||
|
||||
|
||||
def test_the_real_time_basis_is_independent_of_the_mux_label() -> None:
|
||||
"""The checkpoint declares no frame rate, so the basis must be statable.
|
||||
|
||||
The same measured cadence has RTF 1.809 at 16 fps and 1.357 at 12 fps;
|
||||
tying that verdict to the fps sent to the muxer would let a playback label
|
||||
silently decide whether a run passes.
|
||||
"""
|
||||
records = _records([1.0] + [1.357] * 15)
|
||||
at_16 = compute_metrics(records, fps=16, warmup_chunks=6)
|
||||
at_12 = compute_metrics(records, fps=12, warmup_chunks=6)
|
||||
assert at_16["chunk_deadline_ms"] == pytest.approx(750.0)
|
||||
assert at_12["chunk_deadline_ms"] == pytest.approx(1000.0)
|
||||
# RTF is cost, so the harsher 16 fps basis scores WORSE (higher).
|
||||
assert at_16["video_rtf"] > at_12["video_rtf"]
|
||||
# Same wall clock, same bytes: only the basis moved.
|
||||
assert at_16["video_rtf"] / at_12["video_rtf"] == pytest.approx(16 / 12)
|
||||
assert parse_args([]).target_fps is None, "default defers to the workload fps"
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Protocol handling against a scripted server
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
def _serve(script):
|
||||
"""Return an async context manager yielding a ws:// URL for ``script``."""
|
||||
from websockets.asyncio.server import Server, serve
|
||||
|
||||
class _Server:
|
||||
def __init__(self) -> None:
|
||||
self.server: Server | None = None
|
||||
self.start_payloads: list[dict] = []
|
||||
|
||||
async def __aenter__(self) -> str:
|
||||
async def handler(websocket) -> None:
|
||||
self.start_payloads.append(json.loads(await websocket.recv()))
|
||||
await script(websocket, self.start_payloads[-1])
|
||||
|
||||
self.server = await serve(handler, "127.0.0.1", 0)
|
||||
port = next(iter(self.server.sockets)).getsockname()[1]
|
||||
return f"ws://127.0.0.1:{port}/v1/realtime/video"
|
||||
|
||||
async def __aexit__(self, *exc) -> None:
|
||||
assert self.server is not None
|
||||
self.server.close()
|
||||
await self.server.wait_closed()
|
||||
|
||||
return _Server()
|
||||
|
||||
|
||||
async def _emit_rollout(websocket, payload, *, intervals=None, chunks=None, trailer=True) -> None:
|
||||
"""Replay the documented event order: start, metadata+binary per chunk, done."""
|
||||
num_chunks = chunks if chunks is not None else len(payload["extra_params"]["camera_action_script"])
|
||||
await websocket.send(json.dumps({"type": "video.start", "request_id": "req-1", "format": "m4s"}))
|
||||
for index in range(num_chunks):
|
||||
if intervals is not None:
|
||||
await asyncio.sleep(intervals[index])
|
||||
frames = pixel_frames_in_chunk(index)
|
||||
body = bytes([index % 256]) * (100 + index)
|
||||
await websocket.send(
|
||||
json.dumps(
|
||||
{
|
||||
"type": "video.chunk_metadata",
|
||||
"request_id": "req-1",
|
||||
"kind": "media",
|
||||
"num_frames": frames,
|
||||
"byte_length": len(body),
|
||||
"generation_chunk_index": index,
|
||||
}
|
||||
)
|
||||
)
|
||||
await websocket.send(body)
|
||||
if trailer:
|
||||
tail = b"\x00" * 8
|
||||
await websocket.send(
|
||||
json.dumps(
|
||||
{
|
||||
"type": "video.chunk_metadata",
|
||||
"request_id": "req-1",
|
||||
"kind": "trailer",
|
||||
"num_frames": 0,
|
||||
"byte_length": len(tail),
|
||||
"generation_chunk_index": None,
|
||||
}
|
||||
)
|
||||
)
|
||||
await websocket.send(tail)
|
||||
await websocket.send(json.dumps({"type": "session.done", "stopped": False, "chunks": num_chunks}))
|
||||
|
||||
|
||||
def _run(coro):
|
||||
return asyncio.run(asyncio.wait_for(coro, timeout=30))
|
||||
|
||||
|
||||
def test_session_records_one_chunk_per_block_and_ignores_the_trailer() -> None:
|
||||
workload = _workload(num_chunks=4)
|
||||
|
||||
async def scenario() -> None:
|
||||
server = _serve(_emit_rollout)
|
||||
url = await server.__aenter__()
|
||||
try:
|
||||
result = await run_session(
|
||||
url,
|
||||
"model",
|
||||
workload,
|
||||
first_chunk_timeout=10,
|
||||
chunk_timeout=10,
|
||||
ping_interval=0,
|
||||
collect_media=True,
|
||||
print_chunks=False,
|
||||
)
|
||||
finally:
|
||||
await server.__aexit__(None, None, None)
|
||||
|
||||
assert [record.index for record in result.records] == [0, 1, 2, 3]
|
||||
assert [record.num_frames for record in result.records] == [9, 12, 12, 12]
|
||||
assert result.request_id == "req-1"
|
||||
assert result.ttfc_s is not None and result.ttfc_s > 0
|
||||
# The trailer's bytes are kept for remuxing but carry no chunk record.
|
||||
assert len(result.media) == sum(record.byte_length for record in result.records) + 8
|
||||
assert server.start_payloads[0]["num_frames"] == workload.num_frames
|
||||
|
||||
_run(scenario())
|
||||
|
||||
|
||||
def test_measured_intervals_track_the_server_cadence() -> None:
|
||||
workload = _workload(num_chunks=3)
|
||||
|
||||
async def script(websocket, payload) -> None:
|
||||
await _emit_rollout(websocket, payload, intervals=[0.05, 0.30, 0.05])
|
||||
|
||||
async def scenario() -> None:
|
||||
server = _serve(script)
|
||||
url = await server.__aenter__()
|
||||
try:
|
||||
result = await run_session(
|
||||
url,
|
||||
"model",
|
||||
workload,
|
||||
first_chunk_timeout=10,
|
||||
chunk_timeout=10,
|
||||
ping_interval=0,
|
||||
collect_media=False,
|
||||
print_chunks=False,
|
||||
)
|
||||
finally:
|
||||
await server.__aexit__(None, None, None)
|
||||
|
||||
intervals = [record.inter_arrival_s for record in result.records]
|
||||
assert intervals[1] == pytest.approx(0.30, abs=0.15)
|
||||
assert intervals[2] < intervals[1], "a fast chunk must not inherit the slow one's interval"
|
||||
assert result.records[0].arrival_s == pytest.approx(result.ttfc_s)
|
||||
|
||||
_run(scenario())
|
||||
|
||||
|
||||
def test_a_short_rollout_fails_loudly_instead_of_reporting_a_partial_cadence() -> None:
|
||||
workload = _workload(num_chunks=4)
|
||||
|
||||
async def script(websocket, payload) -> None:
|
||||
await _emit_rollout(websocket, payload, chunks=2)
|
||||
|
||||
async def scenario() -> None:
|
||||
server = _serve(script)
|
||||
url = await server.__aenter__()
|
||||
try:
|
||||
with pytest.raises(BenchmarkError, match="Expected 4 chunks"):
|
||||
await run_session(
|
||||
url,
|
||||
"model",
|
||||
workload,
|
||||
first_chunk_timeout=10,
|
||||
chunk_timeout=10,
|
||||
ping_interval=0,
|
||||
collect_media=False,
|
||||
print_chunks=False,
|
||||
)
|
||||
finally:
|
||||
await server.__aexit__(None, None, None)
|
||||
|
||||
_run(scenario())
|
||||
|
||||
|
||||
def test_a_server_error_event_aborts_the_session() -> None:
|
||||
workload = _workload(num_chunks=2)
|
||||
|
||||
async def script(websocket, payload) -> None:
|
||||
await websocket.send(json.dumps({"type": "error", "message": "resolution mismatch"}))
|
||||
|
||||
async def scenario() -> None:
|
||||
server = _serve(script)
|
||||
url = await server.__aenter__()
|
||||
try:
|
||||
with pytest.raises(BenchmarkError, match="resolution mismatch.*requested 2 chunks"):
|
||||
await run_session(
|
||||
url,
|
||||
"model",
|
||||
workload,
|
||||
first_chunk_timeout=10,
|
||||
chunk_timeout=10,
|
||||
ping_interval=0,
|
||||
collect_media=False,
|
||||
print_chunks=False,
|
||||
)
|
||||
finally:
|
||||
await server.__aexit__(None, None, None)
|
||||
|
||||
_run(scenario())
|
||||
|
||||
|
||||
def test_a_stalled_server_times_out_rather_than_hanging() -> None:
|
||||
workload = _workload(num_chunks=2)
|
||||
|
||||
async def script(websocket, payload) -> None:
|
||||
await websocket.send(json.dumps({"type": "video.start", "request_id": "req-1", "format": "m4s"}))
|
||||
await asyncio.sleep(5)
|
||||
|
||||
async def scenario() -> None:
|
||||
server = _serve(script)
|
||||
url = await server.__aenter__()
|
||||
try:
|
||||
with pytest.raises(BenchmarkError, match="No media chunk for"):
|
||||
await run_session(
|
||||
url,
|
||||
"model",
|
||||
workload,
|
||||
first_chunk_timeout=0.4,
|
||||
chunk_timeout=0.4,
|
||||
ping_interval=0,
|
||||
collect_media=False,
|
||||
print_chunks=False,
|
||||
)
|
||||
finally:
|
||||
await server.__aexit__(None, None, None)
|
||||
|
||||
_run(scenario())
|
||||
|
||||
|
||||
def test_keepalive_pings_reach_the_server_during_a_slow_first_chunk() -> None:
|
||||
"""A compiled first block can outlast the server's stall timeout."""
|
||||
workload = _workload(num_chunks=1)
|
||||
seen: list[str] = []
|
||||
|
||||
async def script(websocket, payload) -> None:
|
||||
await websocket.send(json.dumps({"type": "video.start", "request_id": "req-1", "format": "m4s"}))
|
||||
|
||||
async def drain() -> None:
|
||||
async for message in websocket:
|
||||
event = json.loads(message)
|
||||
seen.append(event["type"])
|
||||
if event["type"] == "session.ping":
|
||||
await websocket.send(json.dumps({"type": "session.pong"}))
|
||||
|
||||
drainer = asyncio.create_task(drain())
|
||||
await asyncio.sleep(0.35)
|
||||
await _emit_rollout(websocket, payload, trailer=False)
|
||||
drainer.cancel()
|
||||
|
||||
async def scenario() -> None:
|
||||
server = _serve(script)
|
||||
url = await server.__aenter__()
|
||||
try:
|
||||
result = await run_session(
|
||||
url,
|
||||
"model",
|
||||
workload,
|
||||
first_chunk_timeout=10,
|
||||
chunk_timeout=10,
|
||||
ping_interval=0.1,
|
||||
collect_media=False,
|
||||
print_chunks=False,
|
||||
)
|
||||
finally:
|
||||
await server.__aexit__(None, None, None)
|
||||
assert len(result.records) == 1
|
||||
assert "session.ping" in seen
|
||||
|
||||
_run(scenario())
|
||||
|
||||
|
||||
def test_prompt_updates_are_sent_on_their_chunk_boundary() -> None:
|
||||
workload = Workload(
|
||||
prompt="start",
|
||||
image_reference=_IMAGE,
|
||||
camera_script=build_camera_script(3, "forward"),
|
||||
prompt_updates=(PromptUpdate(after_chunk=0, prompt="Rain begins", transition_chunks=1),),
|
||||
)
|
||||
received: list[dict] = []
|
||||
|
||||
async def script(websocket, payload) -> None:
|
||||
async def drain() -> None:
|
||||
async for message in websocket:
|
||||
received.append(json.loads(message))
|
||||
|
||||
drainer = asyncio.create_task(drain())
|
||||
await _emit_rollout(websocket, payload, intervals=[0.02, 0.15, 0.02], trailer=False)
|
||||
await asyncio.sleep(0.05)
|
||||
drainer.cancel()
|
||||
|
||||
async def scenario() -> None:
|
||||
server = _serve(script)
|
||||
url = await server.__aenter__()
|
||||
try:
|
||||
await run_session(
|
||||
url,
|
||||
"model",
|
||||
workload,
|
||||
first_chunk_timeout=10,
|
||||
chunk_timeout=10,
|
||||
ping_interval=0,
|
||||
collect_media=False,
|
||||
print_chunks=False,
|
||||
)
|
||||
finally:
|
||||
await server.__aexit__(None, None, None)
|
||||
interactions = [event for event in received if event.get("type") == "session.interaction"]
|
||||
assert len(interactions) == 1
|
||||
assert interactions[0]["interaction"]["event"]["prompt"] == "Rain begins"
|
||||
assert interactions[0]["interaction"]["transition_chunks"] == 1
|
||||
|
||||
_run(scenario())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("delivered", [0, 1])
|
||||
def test_pongs_do_not_extend_media_deadlines(delivered) -> None:
|
||||
seen = []
|
||||
|
||||
async def script(websocket, payload) -> None:
|
||||
if delivered:
|
||||
await websocket.send(
|
||||
json.dumps(
|
||||
{
|
||||
"type": "video.chunk_metadata",
|
||||
"kind": "media",
|
||||
"generation_chunk_index": 0,
|
||||
"num_frames": 9,
|
||||
}
|
||||
)
|
||||
)
|
||||
await websocket.send(b"media")
|
||||
async for message in websocket:
|
||||
seen.append(json.loads(message)["type"])
|
||||
await websocket.send(json.dumps({"type": "session.pong"}))
|
||||
|
||||
async def scenario() -> None:
|
||||
async with _serve(script) as url:
|
||||
with pytest.raises(BenchmarkError, match=f"after {delivered} chunk"):
|
||||
await asyncio.wait_for(
|
||||
run_session(
|
||||
url,
|
||||
"model",
|
||||
_workload(num_chunks=2),
|
||||
first_chunk_timeout=0.25,
|
||||
chunk_timeout=0.25,
|
||||
ping_interval=0.03,
|
||||
collect_media=False,
|
||||
print_chunks=False,
|
||||
),
|
||||
timeout=2,
|
||||
)
|
||||
assert "session.ping" in seen
|
||||
|
||||
_run(scenario())
|
||||
|
||||
|
||||
def test_terminal_chunk_is_only_excluded_from_steady_metrics() -> None:
|
||||
records = _records([1.0] + [0.1] * 5 + [1.2, 0.8, 0.1])
|
||||
metrics = compute_metrics(records, fps=12, warmup_chunks=6)
|
||||
assert metrics["steady_chunks"] == 2
|
||||
assert metrics["interval_steady"]["mean_ms"] == pytest.approx(1000)
|
||||
assert metrics["steady_video_rtf"] == pytest.approx(1)
|
||||
assert metrics["slo_attainment"] == pytest.approx(0.5)
|
||||
assert metrics["interval_all"]["count"] == 8
|
||||
assert metrics["total_frames"] == 105
|
||||
assert metrics["wall_seconds"] == pytest.approx(records[-1].arrival_s)
|
||||
assert metrics["playback"]["total_stall_ms"] == pytest.approx(
|
||||
simulate_playback(records, fps=12).total_stall_s * 1000
|
||||
)
|
||||
|
||||
|
||||
def test_terminal_chunk_alone_does_not_establish_steady_state() -> None:
|
||||
metrics = compute_metrics(_records([1.0] * 7), fps=12, warmup_chunks=6)
|
||||
assert not metrics["steady_state_reached"]
|
||||
assert "steady_video_rtf" not in metrics
|
||||
|
||||
|
||||
def test_aggregate_preserves_custom_deadline_and_weights_intervals() -> None:
|
||||
fast = compute_metrics(_records([1.0, 0.5, 0.1]), fps=12, warmup_chunks=0, slo_ms=700)
|
||||
slow = compute_metrics(_records([1.0, 0.9, 0.9, 0.9, 0.1]), fps=12, warmup_chunks=0, slo_ms=700)
|
||||
aggregate = aggregate_metrics([fast, slow], fps=12)
|
||||
assert aggregate["chunk_deadline_ms"] == 700
|
||||
assert aggregate["steady_interval_ms_mean"] == pytest.approx(800)
|
||||
slow["chunk_deadline_ms"] = 800
|
||||
with pytest.raises(ValueError, match="different chunk deadlines"):
|
||||
aggregate_metrics([fast, slow], fps=12)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"flags, expected_shift, expected_negative",
|
||||
[
|
||||
([], 7.0, "file negative"),
|
||||
(["--flow-shift", "5", "--negative-prompt", "CLI negative"], 5.0, "CLI negative"),
|
||||
(["--negative-prompt", ""], 7.0, ""),
|
||||
],
|
||||
)
|
||||
def test_cli_workload_generation_overrides(tmp_path, flags, expected_shift, expected_negative) -> None:
|
||||
path = tmp_path / "workload.json"
|
||||
path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"image": _IMAGE,
|
||||
"num_chunks": 3,
|
||||
"flow_shift": 7.0,
|
||||
"negative_prompt": "file negative",
|
||||
}
|
||||
)
|
||||
)
|
||||
workload = build_workload(parse_args(["--workload", str(path), *flags]))
|
||||
assert workload.flow_shift == expected_shift
|
||||
assert workload.negative_prompt == expected_negative
|
||||
|
||||
|
||||
def test_builtin_workload_keeps_default_flow_shift() -> None:
|
||||
assert build_workload(parse_args(["--image", _IMAGE])).flow_shift == 5.0
|
||||
|
||||
|
||||
def test_short_sample_report_qualifies_tail_percentiles(capsys) -> None:
|
||||
metrics = compute_metrics(_records([1.0] * 16), fps=12)
|
||||
print_report(metrics, workload=_workload(num_chunks=16), endpoint="ws://test", sessions=1, target_fps=12)
|
||||
assert "not reliable tail estimates" in capsys.readouterr().out
|
||||
@@ -13,6 +13,7 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import base64
|
||||
import json
|
||||
import struct
|
||||
import wave
|
||||
from collections.abc import Callable
|
||||
from typing import Any
|
||||
@@ -33,6 +34,7 @@ from vllm_omni.clients.duplex import (
|
||||
ReconnectPolicy,
|
||||
SessionConfig,
|
||||
SessionResumed,
|
||||
SessionUpdated,
|
||||
build_realtime_url,
|
||||
chunk_period_ms,
|
||||
duplex_unit_boundary_ms,
|
||||
@@ -797,6 +799,52 @@ async def test_inline_client_submits_typed_commands_in_order():
|
||||
assert ack.played_ms == 120 and ack.response_id == "resp-1"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("accepted", [True, False])
|
||||
@pytest.mark.parametrize(
|
||||
"patch",
|
||||
[
|
||||
{"input_audio_format": "pcm_f32le", "sample_rate_hz": 24_000},
|
||||
{"audio": {"input": {"format": "pcm_f32le", "sample_rate_hz": 24_000}}},
|
||||
],
|
||||
)
|
||||
async def test_inline_input_defaults_change_only_after_session_updated(accepted, patch):
|
||||
client, omni = make_inline_client()
|
||||
patch = {**patch, "overlap_silence_rms": 0.1}
|
||||
async with client:
|
||||
handle = omni.handles[0]
|
||||
previous_session = dict(client.session_info)
|
||||
await client.send({"type": "session.update", "session": patch})
|
||||
# Sending a patch is not an acknowledgement of its acceptance.
|
||||
assert client.session_info == previous_session
|
||||
assert client._input_defaults().input_sample_rate_hz == 16_000
|
||||
updated_session = {**previous_session, **patch}
|
||||
event: dict[str, object] = (
|
||||
{"type": "session.updated", "session": updated_session}
|
||||
if accepted
|
||||
else {"type": "error", "error": {"code": "invalid_session_update", "message": "rejected"}}
|
||||
)
|
||||
handle.feed(event)
|
||||
received = await client.wait_for("session.updated" if accepted else "error", timeout_s=2.0)
|
||||
assert isinstance(received, SessionUpdated if accepted else ErrorEvent)
|
||||
|
||||
pcm = struct.pack("<f", 0.05) * 16
|
||||
await client.send({"type": "input_audio_buffer.append", "audio": _b64(pcm)})
|
||||
command = handle.commands[-1]
|
||||
assert isinstance(command, duplex_commands.AppendAudio)
|
||||
assert command.format == "pcm_f32le"
|
||||
if accepted:
|
||||
assert client.session_info == updated_session
|
||||
assert command.audio == pcm
|
||||
assert command.sample_rate_hz == 24_000
|
||||
assert command.is_speech is False
|
||||
else:
|
||||
assert client.session_info == previous_session
|
||||
assert len(command.audio) == 2 * len(pcm) # Still decoded as pcm16.
|
||||
assert command.sample_rate_hz == 16_000
|
||||
assert command.is_speech is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_inline_session_close_maps_to_handle_close():
|
||||
client, omni = make_inline_client()
|
||||
|
||||
@@ -167,7 +167,7 @@ def test_inventory_matches_reviewed_snapshot_counts():
|
||||
EnvironmentVariableCategory.PUBLIC_OMNI: 29,
|
||||
EnvironmentVariableCategory.INHERITED_VLLM: 20,
|
||||
EnvironmentVariableCategory.PLATFORM_EXTERNAL: 27,
|
||||
EnvironmentVariableCategory.MODEL_SPECIFIC: 57,
|
||||
EnvironmentVariableCategory.MODEL_SPECIFIC: 59,
|
||||
EnvironmentVariableCategory.BENCHMARK_TRANSITIONAL: 21,
|
||||
EnvironmentVariableCategory.INTERNAL: 2,
|
||||
}
|
||||
@@ -181,7 +181,7 @@ def test_inventory_matches_reviewed_snapshot_counts():
|
||||
ModelEnvironmentVariableDisposition.PROMOTE: 31,
|
||||
ModelEnvironmentVariableDisposition.REQUEST_SCOPE: 5,
|
||||
ModelEnvironmentVariableDisposition.EXTERNAL: 0,
|
||||
ModelEnvironmentVariableDisposition.INTERNALIZE: 14,
|
||||
ModelEnvironmentVariableDisposition.INTERNALIZE: 16,
|
||||
ModelEnvironmentVariableDisposition.DEPRECATE_REMOVE: 7,
|
||||
}
|
||||
|
||||
|
||||
@@ -816,19 +816,25 @@ def test_mrv2_fails_fast_on_platforms_without_native_workers(platform: str):
|
||||
_apply_platform_overrides(DeployConfig(model_runner="v2"), platform=platform)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("default_name", "mrv2_name"),
|
||||
[
|
||||
("qwen3_tts.yaml", "qwen3_tts_mrv2.yaml"),
|
||||
(
|
||||
"qwen3_tts_high_concurrency.yaml",
|
||||
"qwen3_tts_high_concurrency_mrv2.yaml",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_qwen3_mrv2_profiles_are_explicit_opt_in(default_name: str, mrv2_name: str):
|
||||
assert load_deploy_config(_DEPLOY_DIR / default_name).model_runner == "v1"
|
||||
assert load_deploy_config(_DEPLOY_DIR / mrv2_name).model_runner == "v2"
|
||||
def test_qwen3_tts_high_concurrency_mrv2_profile_is_explicit_opt_in():
|
||||
assert load_deploy_config(_DEPLOY_DIR / "qwen3_tts_high_concurrency.yaml").model_runner == "v1"
|
||||
assert load_deploy_config(_DEPLOY_DIR / "qwen3_tts_high_concurrency_mrv2.yaml").model_runner == "v2"
|
||||
|
||||
|
||||
def test_qwen3_tts_default_profile_is_experimental_mrv2_with_v1_platform_fallback():
|
||||
deploy_path = _DEPLOY_DIR / "qwen3_tts.yaml"
|
||||
assert load_deploy_config(deploy_path).model_runner == "v2"
|
||||
|
||||
pipeline = _resolve_pipeline_or_skip("qwen3_tts")
|
||||
stages = merge_pipeline_deploy(pipeline, load_deploy_config(deploy_path))
|
||||
assert all(stage.yaml_engine_args["use_v2_model_runner"] is True for stage in stages)
|
||||
|
||||
assert _apply_platform_overrides(load_deploy_config(deploy_path), platform="cuda").model_runner == "v2"
|
||||
for platform in ("npu", "xpu", "rocm", "musa"):
|
||||
assert _apply_platform_overrides(load_deploy_config(deploy_path), platform=platform).model_runner == "v1"
|
||||
|
||||
# The explicit MRV2 profile resolves to the same runner selection.
|
||||
assert load_deploy_config(_DEPLOY_DIR / "qwen3_tts_mrv2.yaml").model_runner == "v2"
|
||||
|
||||
|
||||
def test_qwen3_tts_mrv2_retunes_do_not_change_default_mrv1_profile():
|
||||
|
||||
+4
-2
@@ -1,3 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""
|
||||
Hunyuan-Image stability: OmniServer (diffusion) + ``diffusion_benchmark_serving.py``.
|
||||
|
||||
@@ -34,8 +37,7 @@ server_to_benchmark_mapping = create_test_parameter_mapping(BENCHMARK_CONFIGS) i
|
||||
benchmark_indices = create_benchmark_indices(BENCHMARK_CONFIGS, server_to_benchmark_mapping)
|
||||
|
||||
|
||||
@pytest.mark.slow
|
||||
@pytest.mark.diffusion
|
||||
# Pytest marks (hardware, local_model, slow, diffusion) come from test_hunyuan_image.json.
|
||||
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
|
||||
@pytest.mark.parametrize("stability_benchmark_params", benchmark_indices, indirect=True)
|
||||
def test_stability_hunyuan_image(omni_server, stability_benchmark_params):
|
||||
@@ -0,0 +1,70 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""
|
||||
HunyuanVideo-1.5 I2V stability: OmniServer (diffusion) + ``diffusion_benchmark_serving.py`` / ``v1/videos``.
|
||||
|
||||
Configuration: ``tests/dfx/stability/tests/test_hunyuanvideo15.json``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.dfx.conftest import (
|
||||
create_benchmark_indices,
|
||||
create_test_parameter_mapping,
|
||||
create_unique_server_pytest_params,
|
||||
load_configs,
|
||||
)
|
||||
from tests.dfx.stability.helpers import _run_one_diffusion_batch, run_stability_benchmark_loop
|
||||
|
||||
STABILITY_DIR = Path(__file__).resolve().parent.parent
|
||||
DEPLOY_CONFIGS_DIR = STABILITY_DIR / "deploy"
|
||||
CONFIG_FILE_PATH = str(STABILITY_DIR / "tests" / "test_hunyuanvideo15.json")
|
||||
DEFAULT_NUM_PROMPTS_PER_BATCH = 50
|
||||
STABILITY_SERVER_TIMEOUT_ARGS = ["--stage-init-timeout", "600", "--init-timeout", "900"]
|
||||
|
||||
try:
|
||||
BENCHMARK_CONFIGS = load_configs(CONFIG_FILE_PATH)
|
||||
except FileNotFoundError:
|
||||
BENCHMARK_CONFIGS = []
|
||||
|
||||
test_params = create_unique_server_pytest_params(BENCHMARK_CONFIGS, DEPLOY_CONFIGS_DIR) if BENCHMARK_CONFIGS else []
|
||||
server_to_benchmark_mapping = create_test_parameter_mapping(BENCHMARK_CONFIGS) if BENCHMARK_CONFIGS else {}
|
||||
benchmark_indices = create_benchmark_indices(BENCHMARK_CONFIGS, server_to_benchmark_mapping)
|
||||
|
||||
|
||||
# Pytest marks (hardware, local_model, slow, diffusion) come from test_hunyuanvideo15.json.
|
||||
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
|
||||
@pytest.mark.parametrize("stability_benchmark_params", benchmark_indices, indirect=True)
|
||||
def test_stability_hunyuanvideo15(omni_server, stability_benchmark_params):
|
||||
test_name = stability_benchmark_params["test_name"]
|
||||
params = stability_benchmark_params["params"]
|
||||
duration_sec = params.get("duration_sec", 300)
|
||||
num_prompts_per_batch = params.get("num_prompts_per_batch", DEFAULT_NUM_PROMPTS_PER_BATCH)
|
||||
request_rate = params.get("request_rate")
|
||||
max_concurrency = params.get("max_concurrency")
|
||||
|
||||
bench_params = {
|
||||
k: v
|
||||
for k, v in params.items()
|
||||
if k not in ("duration_sec", "request_rate", "max_concurrency", "num_prompts_per_batch")
|
||||
}
|
||||
|
||||
result = run_stability_benchmark_loop(
|
||||
host=omni_server.host,
|
||||
port=omni_server.port,
|
||||
model=omni_server.model,
|
||||
duration_sec=duration_sec,
|
||||
params=bench_params,
|
||||
request_rate=request_rate,
|
||||
max_concurrency=max_concurrency,
|
||||
result_dir=str(STABILITY_DIR),
|
||||
num_prompts_per_batch=num_prompts_per_batch,
|
||||
run_one_batch=_run_one_diffusion_batch,
|
||||
)
|
||||
|
||||
assert result.get("failed", 0) == 0, f"[{test_name}] Failed requests detected: {result.get('errors', [])}"
|
||||
assert result.get("completed", 0) > 0, f"[{test_name}] No requests completed"
|
||||
@@ -0,0 +1,71 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""
|
||||
MiniCPM-o-4.5 stability: OmniServer + ``vllm bench serve --omni`` for a fixed duration.
|
||||
|
||||
Configuration: ``tests/dfx/stability/tests/test_minicpmo_4_5.json``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.dfx.conftest import (
|
||||
create_benchmark_indices,
|
||||
create_test_parameter_mapping,
|
||||
create_unique_server_pytest_params,
|
||||
load_configs,
|
||||
)
|
||||
from tests.dfx.stability.helpers import _run_one_vllm_bench_batch, run_stability_benchmark_loop
|
||||
|
||||
STABILITY_DIR = Path(__file__).resolve().parent.parent
|
||||
DEPLOY_CONFIGS_DIR = STABILITY_DIR / "deploy"
|
||||
CONFIG_FILE_PATH = str(STABILITY_DIR / "tests" / "test_minicpmo_4_5.json")
|
||||
DEFAULT_NUM_PROMPTS_PER_BATCH = 20
|
||||
STABILITY_SERVER_TIMEOUT_ARGS = ["--stage-init-timeout", "600"]
|
||||
|
||||
try:
|
||||
BENCHMARK_CONFIGS = load_configs(CONFIG_FILE_PATH)
|
||||
except FileNotFoundError:
|
||||
BENCHMARK_CONFIGS = []
|
||||
|
||||
test_params = create_unique_server_pytest_params(BENCHMARK_CONFIGS, DEPLOY_CONFIGS_DIR) if BENCHMARK_CONFIGS else []
|
||||
server_to_benchmark_mapping = create_test_parameter_mapping(BENCHMARK_CONFIGS) if BENCHMARK_CONFIGS else {}
|
||||
benchmark_indices = create_benchmark_indices(BENCHMARK_CONFIGS, server_to_benchmark_mapping)
|
||||
|
||||
|
||||
# Pytest marks (hardware, local_model, slow, omni) come from test_minicpmo_4_5.json.
|
||||
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
|
||||
@pytest.mark.parametrize("stability_benchmark_params", benchmark_indices, indirect=True)
|
||||
def test_stability_minicpmo_4_5(omni_server, stability_benchmark_params):
|
||||
test_name = stability_benchmark_params["test_name"]
|
||||
params = stability_benchmark_params["params"]
|
||||
duration_sec = params.get("duration_sec", 300)
|
||||
num_prompts_per_batch = params.get("num_prompts_per_batch", DEFAULT_NUM_PROMPTS_PER_BATCH)
|
||||
request_rate = params.get("request_rate")
|
||||
max_concurrency = params.get("max_concurrency")
|
||||
|
||||
bench_params = {
|
||||
k: v
|
||||
for k, v in params.items()
|
||||
if k not in ("duration_sec", "request_rate", "max_concurrency", "num_prompts_per_batch")
|
||||
}
|
||||
|
||||
result = run_stability_benchmark_loop(
|
||||
host=omni_server.host,
|
||||
port=omni_server.port,
|
||||
model=omni_server.model,
|
||||
duration_sec=duration_sec,
|
||||
params=bench_params,
|
||||
request_rate=request_rate,
|
||||
max_concurrency=max_concurrency,
|
||||
result_dir=str(STABILITY_DIR),
|
||||
num_prompts_per_batch=num_prompts_per_batch,
|
||||
run_one_batch=_run_one_vllm_bench_batch,
|
||||
)
|
||||
|
||||
assert result.get("failed", 0) == 0, f"[{test_name}] Failed requests detected: {result.get('errors', [])}"
|
||||
assert result.get("completed", 0) > 0, f"[{test_name}] No requests completed"
|
||||
@@ -0,0 +1,91 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""
|
||||
MiniMax-H3 T2V stability: OmniServer (diffusion) + ``diffusion_benchmark_serving.py`` / ``v1/videos``.
|
||||
|
||||
Configuration: ``tests/dfx/stability/tests/test_minimax_h3.json``.
|
||||
|
||||
``--lora-path`` is resolved like e2e FastH3 / Buildkite ``test-merge.yml``:
|
||||
set ``VLLM_TEST_MINIMAX_H3_FASTH3_LORA`` to the adapter file, or populate the local
|
||||
HF cache for ``FastVideo/FastVideo-FastH3-4-step-Preview-v1-LoRA``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.dfx.conftest import (
|
||||
create_benchmark_indices,
|
||||
create_test_parameter_mapping,
|
||||
create_unique_server_pytest_params,
|
||||
load_configs,
|
||||
)
|
||||
from tests.dfx.stability.helpers import _run_one_diffusion_batch, run_stability_benchmark_loop
|
||||
from tests.e2e.online_serving.minimax_h3._common import FASTH3_LORA
|
||||
|
||||
STABILITY_DIR = Path(__file__).resolve().parent.parent
|
||||
DEPLOY_CONFIGS_DIR = STABILITY_DIR / "deploy"
|
||||
CONFIG_FILE_PATH = str(STABILITY_DIR / "tests" / "test_minimax_h3.json")
|
||||
DEFAULT_NUM_PROMPTS_PER_BATCH = 20
|
||||
STABILITY_SERVER_TIMEOUT_ARGS = ["--stage-init-timeout", "1800", "--init-timeout", "1800"]
|
||||
|
||||
|
||||
def _inject_fasth3_lora_path(configs: list[dict]) -> list[dict]:
|
||||
"""Fill serve_args.lora-path from VLLM_TEST_MINIMAX_H3_FASTH3_LORA / HF cache."""
|
||||
if not FASTH3_LORA:
|
||||
return configs
|
||||
for config in configs:
|
||||
serve_args = config.setdefault("server_params", {}).setdefault("serve_args", {})
|
||||
serve_args["lora-path"] = FASTH3_LORA
|
||||
return configs
|
||||
|
||||
|
||||
try:
|
||||
BENCHMARK_CONFIGS = _inject_fasth3_lora_path(load_configs(CONFIG_FILE_PATH))
|
||||
except FileNotFoundError:
|
||||
BENCHMARK_CONFIGS = []
|
||||
|
||||
test_params = create_unique_server_pytest_params(BENCHMARK_CONFIGS, DEPLOY_CONFIGS_DIR) if BENCHMARK_CONFIGS else []
|
||||
server_to_benchmark_mapping = create_test_parameter_mapping(BENCHMARK_CONFIGS) if BENCHMARK_CONFIGS else {}
|
||||
benchmark_indices = create_benchmark_indices(BENCHMARK_CONFIGS, server_to_benchmark_mapping)
|
||||
|
||||
|
||||
# Pytest marks (hardware, local_model, slow, diffusion) come from test_minimax_h3.json.
|
||||
@pytest.mark.skipif(
|
||||
FASTH3_LORA is None,
|
||||
reason="set VLLM_TEST_MINIMAX_H3_FASTH3_LORA or populate the local HF cache",
|
||||
)
|
||||
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
|
||||
@pytest.mark.parametrize("stability_benchmark_params", benchmark_indices, indirect=True)
|
||||
def test_stability_minimax_h3(omni_server, stability_benchmark_params):
|
||||
test_name = stability_benchmark_params["test_name"]
|
||||
params = stability_benchmark_params["params"]
|
||||
duration_sec = params.get("duration_sec", 300)
|
||||
num_prompts_per_batch = params.get("num_prompts_per_batch", DEFAULT_NUM_PROMPTS_PER_BATCH)
|
||||
request_rate = params.get("request_rate")
|
||||
max_concurrency = params.get("max_concurrency")
|
||||
|
||||
bench_params = {
|
||||
k: v
|
||||
for k, v in params.items()
|
||||
if k not in ("duration_sec", "request_rate", "max_concurrency", "num_prompts_per_batch")
|
||||
}
|
||||
|
||||
result = run_stability_benchmark_loop(
|
||||
host=omni_server.host,
|
||||
port=omni_server.port,
|
||||
model=omni_server.model,
|
||||
duration_sec=duration_sec,
|
||||
params=bench_params,
|
||||
request_rate=request_rate,
|
||||
max_concurrency=max_concurrency,
|
||||
result_dir=str(STABILITY_DIR),
|
||||
num_prompts_per_batch=num_prompts_per_batch,
|
||||
run_one_batch=_run_one_diffusion_batch,
|
||||
)
|
||||
|
||||
assert result.get("failed", 0) == 0, f"[{test_name}] Failed requests detected: {result.get('errors', [])}"
|
||||
assert result.get("completed", 0) > 0, f"[{test_name}] No requests completed"
|
||||
+4
-2
@@ -1,3 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""
|
||||
Qwen3-Omni stability: OmniServer + ``vllm bench serve --omni`` for a fixed duration.
|
||||
|
||||
@@ -34,8 +37,7 @@ server_to_benchmark_mapping = create_test_parameter_mapping(BENCHMARK_CONFIGS) i
|
||||
benchmark_indices = create_benchmark_indices(BENCHMARK_CONFIGS, server_to_benchmark_mapping)
|
||||
|
||||
|
||||
@pytest.mark.slow
|
||||
@pytest.mark.omni
|
||||
# Pytest marks (hardware, local_model, slow, omni) come from test_qwen3_omni.json.
|
||||
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
|
||||
@pytest.mark.parametrize("stability_benchmark_params", benchmark_indices, indirect=True)
|
||||
def test_stability_qwen3_omni(omni_server, stability_benchmark_params):
|
||||
+4
-2
@@ -1,3 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""
|
||||
Qwen3-TTS stability: OmniServer + ``vllm bench serve --omni`` for a fixed duration.
|
||||
|
||||
@@ -34,8 +37,7 @@ server_to_benchmark_mapping = create_test_parameter_mapping(BENCHMARK_CONFIGS) i
|
||||
benchmark_indices = create_benchmark_indices(BENCHMARK_CONFIGS, server_to_benchmark_mapping)
|
||||
|
||||
|
||||
@pytest.mark.slow
|
||||
@pytest.mark.tts
|
||||
# Pytest marks (hardware, local_model, slow, tts) come from test_qwen3_tts.json.
|
||||
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
|
||||
@pytest.mark.parametrize("stability_benchmark_params", benchmark_indices, indirect=True)
|
||||
def test_stability_qwen3_tts(omni_server, stability_benchmark_params):
|
||||
+4
-2
@@ -1,3 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""
|
||||
Qwen-Image stability: OmniServer (diffusion) + ``diffusion_benchmark_serving.py``.
|
||||
|
||||
@@ -34,8 +37,7 @@ server_to_benchmark_mapping = create_test_parameter_mapping(BENCHMARK_CONFIGS) i
|
||||
benchmark_indices = create_benchmark_indices(BENCHMARK_CONFIGS, server_to_benchmark_mapping)
|
||||
|
||||
|
||||
@pytest.mark.slow
|
||||
@pytest.mark.diffusion
|
||||
# Pytest marks (hardware, local_model, slow, diffusion) come from test_qwen_image.json.
|
||||
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
|
||||
@pytest.mark.parametrize("stability_benchmark_params", benchmark_indices, indirect=True)
|
||||
def test_stability_qwen_image(omni_server, stability_benchmark_params):
|
||||
+4
-2
@@ -1,3 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""
|
||||
Wan2.2 T2V stability: OmniServer (diffusion) + ``diffusion_benchmark_serving.py`` / ``v1/videos``.
|
||||
|
||||
@@ -34,8 +37,7 @@ server_to_benchmark_mapping = create_test_parameter_mapping(BENCHMARK_CONFIGS) i
|
||||
benchmark_indices = create_benchmark_indices(BENCHMARK_CONFIGS, server_to_benchmark_mapping)
|
||||
|
||||
|
||||
@pytest.mark.slow
|
||||
@pytest.mark.diffusion
|
||||
# Pytest marks (hardware, local_model, slow, diffusion) come from test_wan22.json.
|
||||
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
|
||||
@pytest.mark.parametrize("stability_benchmark_params", benchmark_indices, indirect=True)
|
||||
def test_stability_wan22(omni_server, stability_benchmark_params):
|
||||
@@ -7,10 +7,11 @@
|
||||
"res": {
|
||||
"cuda": "H800"
|
||||
},
|
||||
"num_cards": 2
|
||||
"num_cards": 4
|
||||
}
|
||||
},
|
||||
"local_model",
|
||||
"slow",
|
||||
"diffusion"
|
||||
],
|
||||
"server_params": {
|
||||
@@ -44,5 +45,53 @@
|
||||
"enable_negative_prompt": true
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"test_name": "test_hunyuan_image_stability_tp2_sp2_a3",
|
||||
"description": "A3: same as perf test_hunyuan_image_tp2_sp2 — DiT-only, TP=2 USP=2, 4 dies, no fp8",
|
||||
"mark": [
|
||||
{
|
||||
"hardware_marks": {
|
||||
"res": {
|
||||
"npu": "A3"
|
||||
},
|
||||
"num_cards": 4
|
||||
}
|
||||
},
|
||||
"local_model",
|
||||
"slow",
|
||||
"diffusion"
|
||||
],
|
||||
"server_params": {
|
||||
"model": "tencent/HunyuanImage-3.0-Instruct",
|
||||
"serve_args": {
|
||||
"deploy-config": "vllm_omni/deploy/hunyuan_image3_dit.yaml",
|
||||
"tensor-parallel-size": 2,
|
||||
"ulysses-degree": 2,
|
||||
"vae-patch-parallel-size": 4,
|
||||
"vae-use-tiling": true,
|
||||
"enable-diffusion-pipeline-profiler": true
|
||||
}
|
||||
},
|
||||
"benchmark_params": [
|
||||
{
|
||||
"dataset": "random",
|
||||
"task": "t2i",
|
||||
"backend": "vllm-omni",
|
||||
"duration_sec": 86400,
|
||||
"max_concurrency": 1,
|
||||
"num_prompts_per_batch": 50,
|
||||
"width": {
|
||||
"min": 512,
|
||||
"max": 1024
|
||||
},
|
||||
"height": {
|
||||
"min": 512,
|
||||
"max": 1024
|
||||
},
|
||||
"num_inference_steps": 50,
|
||||
"enable_negative_prompt": true
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,57 @@
|
||||
[
|
||||
{
|
||||
"test_name": "test_hunyuanvideo15_i2v_cachedit_tp2_vae_patch2_stability",
|
||||
"description": "HunyuanVideo-1.5 I2V 24h: CacheDiT + TP=2 + VAE patch parallel=2 + VAE tiling",
|
||||
"mark": [
|
||||
{
|
||||
"hardware_marks": {
|
||||
"res": {
|
||||
"cuda": ["H800"]
|
||||
},
|
||||
"num_cards": 2
|
||||
}
|
||||
},
|
||||
"local_model",
|
||||
"slow",
|
||||
"diffusion"
|
||||
],
|
||||
"server_params": {
|
||||
"model": "hunyuanvideo-community/HunyuanVideo-1.5-Diffusers-480p_i2v",
|
||||
"serve_args": {
|
||||
"flow-shift": 5.0,
|
||||
"cache-backend": "cache_dit",
|
||||
"tensor-parallel-size": 2,
|
||||
"vae-patch-parallel-size": 2,
|
||||
"vae-use-tiling": true,
|
||||
"enable-diffusion-pipeline-profiler": true
|
||||
}
|
||||
},
|
||||
"benchmark_params": [
|
||||
{
|
||||
"dataset": "random",
|
||||
"task": "i2v",
|
||||
"backend": "v1/videos",
|
||||
"duration_sec": 86400,
|
||||
"max_concurrency": 1,
|
||||
"num_prompts_per_batch": 50,
|
||||
"num_input_images": 1,
|
||||
"seed": 42,
|
||||
"enable_negative_prompt": true,
|
||||
"random_request_config": [
|
||||
{
|
||||
"width": 832,
|
||||
"height": 480,
|
||||
"num_inference_steps": 4,
|
||||
"num_frames": 33,
|
||||
"fps": 24,
|
||||
"weight": 1
|
||||
}
|
||||
],
|
||||
"extra_body": {
|
||||
"guidance_scale": 6.0,
|
||||
"flow_shift": 5.0
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,53 @@
|
||||
[
|
||||
{
|
||||
"test_name": "test_minicpmo_4_5_stability_ready",
|
||||
"description": "MiniCPM-o-4.5 ready deploy + seed-tts chat/audio stability (from perf test_minicpmo_4_5_ready)",
|
||||
"mark": [
|
||||
{
|
||||
"hardware_marks": {
|
||||
"res": {
|
||||
"cuda": "H800"
|
||||
},
|
||||
"num_cards": 1
|
||||
}
|
||||
},
|
||||
"local_model",
|
||||
"slow",
|
||||
"omni"
|
||||
],
|
||||
"server_params": {
|
||||
"model": "openbmb/MiniCPM-o-4_5",
|
||||
"extra_cli_args": [
|
||||
"--deploy-config",
|
||||
"vllm_omni/deploy/minicpmo_4_5.yaml",
|
||||
"--trust-remote-code"
|
||||
]
|
||||
},
|
||||
"benchmark_params": [
|
||||
{
|
||||
"dataset_name": "seed-tts",
|
||||
"dataset_path": "zhaochenyang20/seed-tts-eval",
|
||||
"backend": "openai-chat-omni",
|
||||
"endpoint": "/v1/chat/completions",
|
||||
"duration_sec": 86400,
|
||||
"max_concurrency": 1,
|
||||
"num_prompts_per_batch": 50,
|
||||
"no_oversample": true,
|
||||
"disable_shuffle": true,
|
||||
"trust_remote_code": true,
|
||||
"seed_tts_locale": "en",
|
||||
"extra_body": {
|
||||
"modalities": [
|
||||
"text",
|
||||
"audio"
|
||||
],
|
||||
"chat_template_kwargs": {
|
||||
"enable_thinking": false,
|
||||
"use_tts_template": true
|
||||
}
|
||||
},
|
||||
"percentile-metrics": "ttft,e2el,audio_ttfp,audio_rtf,audio_duration"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,62 @@
|
||||
[
|
||||
{
|
||||
"test_name": "test_minimax_h3_t2v_stability_4gpu",
|
||||
"description": "MiniMax-H3 FastH3 T2VA on 4 GPUs (USP4 + HSDP4, encoder-TP4, VAE-PP4 tile); fused lora-path from VLLM_TEST_MINIMAX_H3_FASTH3_LORA; requests must use num_inference_steps=4",
|
||||
"mark": [
|
||||
{
|
||||
"hardware_marks": {
|
||||
"res": {
|
||||
"cuda": "H800"
|
||||
},
|
||||
"num_cards": 4
|
||||
}
|
||||
},
|
||||
"local_model",
|
||||
"slow",
|
||||
"diffusion"
|
||||
],
|
||||
"server_params": {
|
||||
"model": "MiniMaxAI/MiniMax-H3",
|
||||
"serve_args": {
|
||||
"trust-remote-code": true,
|
||||
"task-type": "fl2va",
|
||||
"num-gpus": 4,
|
||||
"usp": 4,
|
||||
"ring": 1,
|
||||
"use-hsdp": true,
|
||||
"hsdp-shard-size": 4,
|
||||
"text-encoder-tp-size": 4,
|
||||
"vae-patch-parallel-size": 4,
|
||||
"vae-parallel-mode": "tile",
|
||||
"vae-use-tiling": true,
|
||||
"stage-init-timeout": 1800,
|
||||
"init-timeout": 1800
|
||||
}
|
||||
},
|
||||
"benchmark_params": [
|
||||
{
|
||||
"dataset": "random",
|
||||
"task": "t2v",
|
||||
"backend": "v1/videos",
|
||||
"duration_sec": 86400,
|
||||
"max_concurrency": 1,
|
||||
"num_prompts_per_batch": 50,
|
||||
"seed": 42,
|
||||
"random_request_config": [
|
||||
{
|
||||
"width": 1344,
|
||||
"height": 768,
|
||||
"prompt": "Cinematic drone shot pushing through misty mountain ridges at sunrise, golden light catching the clouds, slow and smooth.",
|
||||
"num_inference_steps": 4,
|
||||
"num_frames": 209,
|
||||
"fps": 24,
|
||||
"weight": 1
|
||||
}
|
||||
],
|
||||
"extra_body": {
|
||||
"extra_params": "{\"task\":\"t2va\",\"duration\":8.7,\"aspect_ratio\":\"16:9\"}"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -5,12 +5,14 @@
|
||||
{
|
||||
"hardware_marks": {
|
||||
"res": {
|
||||
"cuda": "H800"
|
||||
"cuda": "H800",
|
||||
"npu": "A3"
|
||||
},
|
||||
"num_cards": 2
|
||||
}
|
||||
},
|
||||
"local_model",
|
||||
"slow",
|
||||
"omni"
|
||||
],
|
||||
"server_params": {
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
}
|
||||
},
|
||||
"local_model",
|
||||
"slow",
|
||||
"tts"
|
||||
],
|
||||
"server_params": {
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
}
|
||||
},
|
||||
"local_model",
|
||||
"slow",
|
||||
"diffusion"
|
||||
],
|
||||
"server_params": {
|
||||
@@ -36,5 +37,44 @@
|
||||
"enable_negative_prompt": true
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"test_name": "test_qwen_image_stability_a3",
|
||||
"mark": [
|
||||
{
|
||||
"hardware_marks": {
|
||||
"res": {
|
||||
"npu": "A3"
|
||||
},
|
||||
"num_cards": 1
|
||||
}
|
||||
},
|
||||
"local_model",
|
||||
"slow",
|
||||
"diffusion"
|
||||
],
|
||||
"server_params": {
|
||||
"model": "Qwen/Qwen-Image"
|
||||
},
|
||||
"benchmark_params": [
|
||||
{
|
||||
"dataset": "random",
|
||||
"task": "t2i",
|
||||
"backend": "vllm-omni",
|
||||
"duration_sec": 86400,
|
||||
"max_concurrency": 1,
|
||||
"num_prompts_per_batch": 50,
|
||||
"width": {
|
||||
"min": 512,
|
||||
"max": 1000
|
||||
},
|
||||
"height": {
|
||||
"min": 512,
|
||||
"max": 1000
|
||||
},
|
||||
"num_inference_steps": 50,
|
||||
"enable_negative_prompt": true
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -12,6 +12,7 @@
|
||||
}
|
||||
},
|
||||
"local_model",
|
||||
"slow",
|
||||
"diffusion"
|
||||
],
|
||||
"server_params": {
|
||||
@@ -54,6 +55,7 @@
|
||||
}
|
||||
},
|
||||
"local_model",
|
||||
"slow",
|
||||
"diffusion"
|
||||
],
|
||||
"server_params": {
|
||||
|
||||
@@ -42,6 +42,14 @@ from vllm_omni.diffusion.data import (
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.diffusion, pytest.mark.cpu]
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clear_inherited_attention_backend(monkeypatch):
|
||||
# Weekly CPU exports DIFFUSION_ATTENTION_BACKEND; OmniDiffusionConfig
|
||||
# treats that as an explicit default so auto-backend cases break.
|
||||
# Tests that setenv the same variable still work: this fixture runs first.
|
||||
monkeypatch.delenv("DIFFUSION_ATTENTION_BACKEND", raising=False)
|
||||
|
||||
|
||||
class TestAttentionSpec:
|
||||
def test_construct_no_skip_softmax(self):
|
||||
spec = AttentionSpec(backend="FLASH_ATTN")
|
||||
@@ -416,13 +424,6 @@ class TestBuildAttentionConfig:
|
||||
class TestOmniDiffusionConfigAttentionParsing:
|
||||
"""Test OmniDiffusionConfig attention shorthand and structured config."""
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clear_diffusion_attention_backend_env(self, monkeypatch):
|
||||
# OmniDiffusionConfig.__post_init__ applies DIFFUSION_ATTENTION_BACKEND via
|
||||
# build_attention_config(); clear it so these tests assert config defaults,
|
||||
# not whatever the process inherited from CI / sibling tests.
|
||||
monkeypatch.delenv("DIFFUSION_ATTENTION_BACKEND", raising=False)
|
||||
|
||||
def test_diffusion_attention_backend_sets_default(self):
|
||||
config = OmniDiffusionConfig.from_kwargs(diffusion_attention_backend="SAGE_ATTN")
|
||||
assert isinstance(config.diffusion_attention_config, AttentionConfig)
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""
|
||||
Two-rank ``pause_generation(mode="keep")``: every rank runs the pause barrier
|
||||
before the ACK, and a barrier failure on a non-zero rank fails the pause
|
||||
without aborting or dropping the running batch.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections import defaultdict
|
||||
from contextlib import ExitStack
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.e2e.features.custom_pipeline.test_diffusion_pause_keep import (
|
||||
CUSTOM_PIPELINE_CLASS,
|
||||
MODEL,
|
||||
WORKER_EXTENSION_CLASS,
|
||||
_generate,
|
||||
_pause_round,
|
||||
_wait_for,
|
||||
)
|
||||
from tests.helpers.mark import hardware_test
|
||||
from vllm_omni.entrypoints.async_omni import AsyncOmni
|
||||
|
||||
|
||||
def _all_true(results) -> bool:
|
||||
flat = []
|
||||
stack = list(results)
|
||||
while stack:
|
||||
item = stack.pop()
|
||||
if isinstance(item, list):
|
||||
stack.extend(item)
|
||||
else:
|
||||
flat.append(item)
|
||||
return bool(flat) and all(item is True for item in flat)
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
@pytest.mark.diffusion
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=2)
|
||||
@pytest.mark.asyncio
|
||||
async def test_keep_pause_two_ranks_ack_and_rank_failure():
|
||||
with ExitStack() as after:
|
||||
engine = AsyncOmni(
|
||||
model=MODEL,
|
||||
custom_pipeline_args={"pipeline_class": CUSTOM_PIPELINE_CLASS},
|
||||
worker_extension_cls=WORKER_EXTENSION_CLASS,
|
||||
enforce_eager=True,
|
||||
enable_sleep_mode=True,
|
||||
num_gpus=2,
|
||||
parallel_config={"ulysses_degree": 2, "ulysses_mode": "advanced_uaa"},
|
||||
)
|
||||
after.callback(engine.shutdown)
|
||||
events: dict[str, dict[str, float]] = defaultdict(dict)
|
||||
assert _all_true(await engine.collective_rpc(method="start_counting_synchronize_device"))
|
||||
|
||||
pause_latencies = [await _pause_round(engine, events, round_index) for round_index in range(3)]
|
||||
# The result is the all-rank AND, so True means both ranks ran the barrier.
|
||||
assert _all_true(await engine.collective_rpc(method="synchronize_device_seen"))
|
||||
|
||||
assert _all_true(await engine.collective_rpc(method="set_synchronize_device_failure", args=(1, True)))
|
||||
a = asyncio.create_task(_generate(engine, "a-fail", events))
|
||||
await _wait_for(lambda: "started" in events["a-fail"])
|
||||
with pytest.raises(RuntimeError, match="pause_scheduler failed"):
|
||||
await engine.pause_generation(mode="keep", clear_cache=False)
|
||||
assert await engine.is_paused()
|
||||
a_output = await asyncio.wait_for(a, 60.0)
|
||||
assert a_output.images, "a failed barrier must not abort the running batch"
|
||||
|
||||
assert _all_true(await engine.collective_rpc(method="set_synchronize_device_failure", args=(1, False)))
|
||||
await engine.resume_generation()
|
||||
assert not await engine.is_paused()
|
||||
recovered = await asyncio.wait_for(_generate(engine, "after-recovery", events), 60.0)
|
||||
assert recovered.images
|
||||
|
||||
assert not engine.request_states
|
||||
print(f"[sp2] rounds=3 pause_latency_s min/max={min(pause_latencies):.3f}/{max(pause_latencies):.3f}")
|
||||
@@ -493,6 +493,84 @@ def test_dist_zero_pad_only_applies_global_width_edges(monkeypatch: pytest.Monke
|
||||
assert last.shape == (1, 1, 2, 3)
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
@pytest.mark.cpu
|
||||
class _PlainDecoder(torch.nn.Module):
|
||||
"""A decoder with nothing to patch, so the install only wraps ``forward``."""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.calls: list[dict] = []
|
||||
|
||||
def forward(self, x, feat_cache=None, feat_idx=None, first_chunk=False):
|
||||
self.calls.append({"feat_cache": feat_cache, "feat_idx": feat_idx, "first_chunk": first_chunk})
|
||||
return x
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
@pytest.mark.cpu
|
||||
@pytest.mark.parametrize("world_size, dst", [(4, -1), (4, 4), (4, 5), (1, 1), (4, 1.5)])
|
||||
def test_install_rejects_invalid_destination_before_mutating_decoder(monkeypatch, world_size, dst):
|
||||
monkeypatch.setattr(wan_spatial_shard, "_rank_world", lambda group: (0, world_size))
|
||||
vae = SimpleNamespace(decoder=torch.nn.Identity())
|
||||
original_forward = vae.decoder.forward
|
||||
|
||||
def unexpected_patch(*args, **kwargs):
|
||||
pytest.fail("invalid destination must fail before patching modules")
|
||||
|
||||
monkeypatch.setattr(wan_spatial_shard, "_patch_decoder_modules", unexpected_patch)
|
||||
with pytest.raises(ValueError, match="dst must be None or an integer"):
|
||||
wan_spatial_shard.install_wan_spatial_shard_decode(vae, object(), dst=dst)
|
||||
assert vae.decoder.forward == original_forward
|
||||
assert not getattr(vae, "_vllm_omni_wan_spatial_shard_installed", False)
|
||||
|
||||
|
||||
def _install_on_plain_decoder(monkeypatch: pytest.MonkeyPatch, *, dst):
|
||||
monkeypatch.setattr(wan_spatial_shard, "_rank_world", lambda group: (1, 2))
|
||||
monkeypatch.setattr(
|
||||
wan_spatial_shard,
|
||||
"split_for_parallel_decode",
|
||||
lambda x, *, upsample_count, split_dim, group: (x, x.shape[wan_spatial_shard._spatial_dim(split_dim)]),
|
||||
)
|
||||
gathers: list[dict] = []
|
||||
|
||||
def gather(x, *, expected_extent, split_dim, group, dst=None):
|
||||
gathers.append({"expected_extent": expected_extent, "split_dim": split_dim, "dst": dst})
|
||||
return x
|
||||
|
||||
monkeypatch.setattr(wan_spatial_shard, "gather_and_trim_extent", gather)
|
||||
vae = SimpleNamespace(decoder=_PlainDecoder())
|
||||
wan_spatial_shard.install_wan_spatial_shard_decode(vae, object(), split_dim="width", dst=dst)
|
||||
return vae, gathers
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
@pytest.mark.cpu
|
||||
@pytest.mark.parametrize("dst", [0, 1, None])
|
||||
def test_install_passes_the_assembling_rank_through_to_the_gather(monkeypatch: pytest.MonkeyPatch, dst):
|
||||
vae, gathers = _install_on_plain_decoder(monkeypatch, dst=dst)
|
||||
cache = [None]
|
||||
|
||||
out = vae.decoder(torch.zeros(1, 3, 1, 4, 6), feat_cache=cache, feat_idx=[0], first_chunk=True)
|
||||
|
||||
assert out.shape == (1, 3, 1, 4, 6)
|
||||
assert gathers == [{"expected_extent": 6, "split_dim": "width", "dst": dst}]
|
||||
# The streaming arguments reach the wrapped decoder untouched.
|
||||
assert vae.decoder.calls == [{"feat_cache": cache, "feat_idx": [0], "first_chunk": True}]
|
||||
assert vae._vllm_omni_wan_spatial_shard_dst == dst
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
@pytest.mark.cpu
|
||||
def test_install_refuses_to_change_the_assembling_rank(monkeypatch: pytest.MonkeyPatch):
|
||||
vae, _ = _install_on_plain_decoder(monkeypatch, dst=None)
|
||||
|
||||
# Same settings again: a no-op, as before.
|
||||
wan_spatial_shard.install_wan_spatial_shard_decode(vae, object(), split_dim="width", dst=None)
|
||||
with pytest.raises(ValueError, match="already patched to assemble on None"):
|
||||
wan_spatial_shard.install_wan_spatial_shard_decode(vae, object(), split_dim="width", dst=0)
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
@pytest.mark.cpu
|
||||
def test_spatial_shard_height_gate_falls_back_for_partial_group(monkeypatch: pytest.MonkeyPatch):
|
||||
@@ -626,6 +704,105 @@ def _spatial_shard_decode_worker(rank: int, split_dim: str, return_dict, master_
|
||||
dist.destroy_process_group()
|
||||
|
||||
|
||||
_STREAMING_SHARD_CHUNKS = 3
|
||||
|
||||
|
||||
def _streaming_shard_worker(rank: int, return_dict, master_port: str) -> None:
|
||||
"""Sharded streaming decode with every rank keeping the frame, against an unsharded streaming reference.
|
||||
|
||||
Two sessions are interleaved chunk by chunk, so the per-session temporal cache
|
||||
and the halo exchange are exercised across successive calls, then one session
|
||||
is reset and must reproduce its opening chunk. Every rank checks every chunk.
|
||||
"""
|
||||
from vllm_omni.diffusion.distributed.parallel_state import (
|
||||
destroy_model_parallel,
|
||||
get_sp_group,
|
||||
init_distributed_environment,
|
||||
initialize_model_parallel,
|
||||
)
|
||||
from vllm_omni.experimental.ar_diffusion.streaming_decode import WanStreamingDecoder
|
||||
|
||||
os.environ["MASTER_ADDR"] = "127.0.0.1"
|
||||
os.environ["MASTER_PORT"] = master_port
|
||||
device = current_omni_platform.get_torch_device(rank)
|
||||
current_omni_platform.set_device(device)
|
||||
dtype = torch.float32
|
||||
backend = current_omni_platform.dist_backend
|
||||
init_distributed_environment(world_size=_SPATIAL_SHARD_WORLD_SIZE, rank=rank, local_rank=rank, backend=backend)
|
||||
initialize_model_parallel(
|
||||
sequence_parallel_size=_SPATIAL_SHARD_WORLD_SIZE, ulysses_degree=_SPATIAL_SHARD_WORLD_SIZE, backend=backend
|
||||
)
|
||||
# VLLM_OMNI_TEST_WAN_VAE may point at a local diffusers checkpoint (with or
|
||||
# without a ``vae`` subfolder) for machines without hub access.
|
||||
model = os.environ.get("VLLM_OMNI_TEST_WAN_VAE", _SPATIAL_SHARD_MODEL)
|
||||
local_vae_only = os.path.isdir(model) and not os.path.isdir(os.path.join(model, "vae"))
|
||||
load = {"torch_dtype": dtype} if local_vae_only else {"subfolder": _SPATIAL_SHARD_SUBFOLDER, "torch_dtype": dtype}
|
||||
try:
|
||||
reference_vae = DistributedAutoencoderKLWan.from_pretrained(model, **load).to(device=device, dtype=dtype).eval()
|
||||
sharded_vae = DistributedAutoencoderKLWan.from_pretrained(model, **load).to(device=device, dtype=dtype).eval()
|
||||
wan_spatial_shard.install_wan_spatial_shard_decode(
|
||||
sharded_vae, get_sp_group().device_group, split_dim="width", dst=None
|
||||
)
|
||||
reference = WanStreamingDecoder(reference_vae, bytes_per_pixel_fp32=1.0)
|
||||
sharded = WanStreamingDecoder(sharded_vae, bytes_per_pixel_fp32=1.0)
|
||||
|
||||
generator = torch.Generator(device=device).manual_seed(0)
|
||||
# Width 104 latents = 832 px: not divisible by two ranks' halo-padded shards without padding.
|
||||
shape = (1, reference_vae.config.z_dim, 1, _SPATIAL_SHARD_LATENT_HEIGHT, _SPATIAL_SHARD_LATENT_WIDTH)
|
||||
chunks = {
|
||||
name: [
|
||||
torch.randn(shape, generator=generator, device=device, dtype=dtype)
|
||||
for _ in range(_STREAMING_SHARD_CHUNKS)
|
||||
]
|
||||
for name in ("a", "b")
|
||||
}
|
||||
max_diff = 0.0
|
||||
with torch.inference_mode():
|
||||
ref_states = {name: reference.new_decode_state(name) for name in chunks}
|
||||
shard_states = {name: sharded.new_decode_state(name) for name in chunks}
|
||||
for index in range(_STREAMING_SHARD_CHUNKS):
|
||||
for name in ("a", "b"):
|
||||
expected = reference.decode_chunk(chunks[name][index], ref_states[name]).float()
|
||||
got = sharded.decode_chunk(chunks[name][index], shard_states[name]).float()
|
||||
if got.shape != expected.shape:
|
||||
raise AssertionError(
|
||||
f"rank {rank} {name}[{index}]: {tuple(got.shape)} != {tuple(expected.shape)}"
|
||||
)
|
||||
max_diff = max(max_diff, (got - expected).abs().max().item())
|
||||
# Reset session a: a fresh state must reproduce its opening chunk, on this rank too.
|
||||
shard_states["a"].release()
|
||||
ref_states["a"].release()
|
||||
shard_states["a"] = sharded.new_decode_state("a")
|
||||
ref_states["a"] = reference.new_decode_state("a")
|
||||
expected = reference.decode_chunk(chunks["a"][0], ref_states["a"]).float()
|
||||
got = sharded.decode_chunk(chunks["a"][0], shard_states["a"]).float()
|
||||
max_diff = max(max_diff, (got - expected).abs().max().item())
|
||||
return_dict[f"max_abs_diff_rank{rank}"] = max_diff
|
||||
return_dict[f"shape_rank{rank}"] = tuple(got.shape)
|
||||
finally:
|
||||
destroy_model_parallel()
|
||||
if dist.is_initialized():
|
||||
dist.destroy_process_group()
|
||||
|
||||
|
||||
@pytest.mark.full_model
|
||||
@pytest.mark.diffusion
|
||||
@pytest.mark.parallel
|
||||
@hardware_test(res={"cuda": ["H100", "B200"]}, num_cards=_SPATIAL_SHARD_WORLD_SIZE)
|
||||
def test_streaming_shard_decode_matches_unsharded_streaming_on_every_rank():
|
||||
manager = mp.get_context("spawn").Manager()
|
||||
return_dict = manager.dict()
|
||||
mp.spawn(_streaming_shard_worker, args=(return_dict, "29510"), nprocs=_SPATIAL_SHARD_WORLD_SIZE, join=True)
|
||||
|
||||
for rank in range(_SPATIAL_SHARD_WORLD_SIZE):
|
||||
assert f"max_abs_diff_rank{rank}" in return_dict, f"rank {rank} did not report"
|
||||
diff = return_dict[f"max_abs_diff_rank{rank}"]
|
||||
shape = return_dict[f"shape_rank{rank}"]
|
||||
print(f"streaming shard rank {rank}: max_abs_diff={diff:.6e} shape={shape}")
|
||||
assert shape[-1] == _SPATIAL_SHARD_LATENT_WIDTH * 8 and shape[-2] == _SPATIAL_SHARD_LATENT_HEIGHT * 8
|
||||
assert diff <= _SPATIAL_SHARD_TOLERANCE, f"rank {rank}: {diff} exceeds {_SPATIAL_SHARD_TOLERANCE}"
|
||||
|
||||
|
||||
@pytest.mark.full_model
|
||||
@pytest.mark.diffusion
|
||||
@pytest.mark.parallel
|
||||
|
||||
@@ -3,21 +3,21 @@
|
||||
|
||||
import contextlib
|
||||
|
||||
import huggingface_hub
|
||||
import pytest
|
||||
|
||||
from tests.helpers.mock import patch_hf_snapshot_download
|
||||
from vllm_omni.diffusion.model_loader import hub_prefetch
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.diffusion, pytest.mark.cpu]
|
||||
|
||||
|
||||
def test_prefetch_subfolders_propagates_revision(monkeypatch):
|
||||
def test_prefetch_subfolders_propagates_revision(monkeypatch, tmp_path):
|
||||
calls = []
|
||||
|
||||
def fake_snapshot_download(self, **kwargs):
|
||||
def fake_snapshot_download(**kwargs):
|
||||
calls.append(kwargs)
|
||||
|
||||
monkeypatch.setattr(huggingface_hub.HfApi, "snapshot_download", fake_snapshot_download)
|
||||
patch_hf_snapshot_download(monkeypatch, fake_snapshot_download, hf_home=tmp_path)
|
||||
monkeypatch.setattr(hub_prefetch, "_repo_prefetch_lock", lambda _model: contextlib.nullcontext())
|
||||
|
||||
hub_prefetch.prefetch_subfolders(
|
||||
|
||||
@@ -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
|
||||
"""Focused CPU tests for BAGEL step execution and packed batching."""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,12 +18,14 @@ from vllm_omni.diffusion.models.bagel.bagel_transformer import Bagel, NaiveCache
|
||||
from vllm_omni.diffusion.models.bagel.pipeline_bagel import (
|
||||
BagelGenParams,
|
||||
BagelPipeline,
|
||||
_bagel_canvas_requested,
|
||||
get_bagel_pre_process_func,
|
||||
)
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.diffusion.sched import StepScheduler
|
||||
from vllm_omni.diffusion.worker.input_batch import InputBatch
|
||||
from vllm_omni.diffusion.worker.utils import StepRequestState
|
||||
from vllm_omni.errors import OmniClientError
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
@@ -118,7 +120,7 @@ def test_bagel_step_preprocessor_separates_incompatible_cfg_settings(first_extra
|
||||
assert first.batch_compatibility_key != second.batch_compatibility_key
|
||||
|
||||
|
||||
def test_bagel_step_preprocessor_buckets_effective_img2img_sizes(tmp_path):
|
||||
def _pre_process_with_stub_checkpoint(tmp_path):
|
||||
(tmp_path / "config.json").write_text(
|
||||
'{"vae_config":{"downsample":8},"latent_patch_size":2,"max_latent_size":32}',
|
||||
encoding="utf-8",
|
||||
@@ -131,9 +133,22 @@ def test_bagel_step_preprocessor_buckets_effective_img2img_sizes(tmp_path):
|
||||
'{"weight_map":{"latent_pos_embed.pos_embed":"ema.safetensors"}}',
|
||||
encoding="utf-8",
|
||||
)
|
||||
pre_process = get_bagel_pre_process_func(
|
||||
types.SimpleNamespace(model=str(tmp_path), revision=None, step_execution=True)
|
||||
return get_bagel_pre_process_func(types.SimpleNamespace(model=str(tmp_path), revision=None, step_execution=True))
|
||||
|
||||
|
||||
def _edit_request(source_size, sampling_params, request_id="req"):
|
||||
return OmniDiffusionRequest(
|
||||
prompt={
|
||||
"prompt": "edit this image",
|
||||
"multi_modal_data": {"image": [Image.new("RGB", source_size)]},
|
||||
},
|
||||
sampling_params=sampling_params,
|
||||
request_id=request_id,
|
||||
)
|
||||
|
||||
|
||||
def test_bagel_step_preprocessor_buckets_effective_img2img_sizes(tmp_path):
|
||||
pre_process = _pre_process_with_stub_checkpoint(tmp_path)
|
||||
requests = [
|
||||
OmniDiffusionRequest(
|
||||
prompt={
|
||||
@@ -163,6 +178,172 @@ def test_bagel_step_preprocessor_buckets_effective_img2img_sizes(tmp_path):
|
||||
assert schedule.num_waiting_reqs == 1
|
||||
|
||||
|
||||
def test_bagel_pre_process_keeps_explicitly_requested_canvas(tmp_path):
|
||||
pre_process = _pre_process_with_stub_checkpoint(tmp_path)
|
||||
request = _edit_request((512, 1024), OmniDiffusionSamplingParams(num_inference_steps=2, height=1024, width=1024))
|
||||
|
||||
pre_process(request)
|
||||
|
||||
assert (request.sampling_params.height, request.sampling_params.width) == (1024, 1024)
|
||||
assert _bagel_canvas_requested(request.sampling_params)
|
||||
|
||||
|
||||
def test_bagel_pre_process_aligns_source_derived_canvas_for_size_auto(tmp_path):
|
||||
pre_process = _pre_process_with_stub_checkpoint(tmp_path)
|
||||
request = _edit_request(
|
||||
(500, 700),
|
||||
OmniDiffusionSamplingParams(
|
||||
num_inference_steps=2,
|
||||
height=700,
|
||||
width=500,
|
||||
height_not_provided=True,
|
||||
width_not_provided=True,
|
||||
),
|
||||
)
|
||||
|
||||
pre_process(request)
|
||||
|
||||
assert (request.sampling_params.height, request.sampling_params.width) == (704, 496)
|
||||
assert not _bagel_canvas_requested(request.sampling_params)
|
||||
|
||||
|
||||
def test_bagel_pre_process_derives_canvas_when_caller_asked_for_none(tmp_path):
|
||||
pre_process = _pre_process_with_stub_checkpoint(tmp_path)
|
||||
request = _edit_request((800, 400), OmniDiffusionSamplingParams(num_inference_steps=2))
|
||||
|
||||
pre_process(request)
|
||||
|
||||
assert (request.sampling_params.height, request.sampling_params.width) == (400, 800)
|
||||
assert (request.sampling_params.height_not_provided, request.sampling_params.width_not_provided) == (True, True)
|
||||
assert not _bagel_canvas_requested(request.sampling_params)
|
||||
|
||||
|
||||
def test_bagel_pre_process_marks_kv_metadata_canvas_as_requested(tmp_path):
|
||||
pre_process = _pre_process_with_stub_checkpoint(tmp_path)
|
||||
request = _edit_request(
|
||||
(500, 700),
|
||||
OmniDiffusionSamplingParams(
|
||||
num_inference_steps=2,
|
||||
height=700,
|
||||
width=500,
|
||||
height_not_provided=True,
|
||||
width_not_provided=True,
|
||||
kv_metadata={"image_shape": (1024, 1024)},
|
||||
),
|
||||
)
|
||||
|
||||
pre_process(request)
|
||||
|
||||
assert (request.sampling_params.height, request.sampling_params.width) == (1024, 1024)
|
||||
assert (request.sampling_params.height_not_provided, request.sampling_params.width_not_provided) == (False, False)
|
||||
assert _bagel_canvas_requested(request.sampling_params)
|
||||
|
||||
|
||||
def test_bagel_pre_process_prefers_explicit_canvas_over_kv_metadata(tmp_path):
|
||||
pre_process = _pre_process_with_stub_checkpoint(tmp_path)
|
||||
request = _edit_request(
|
||||
(1280, 720),
|
||||
OmniDiffusionSamplingParams(
|
||||
num_inference_steps=2,
|
||||
height=1024,
|
||||
width=1024,
|
||||
kv_metadata={"image_shape": (576, 1024)},
|
||||
),
|
||||
)
|
||||
|
||||
pre_process(request)
|
||||
|
||||
assert (request.sampling_params.height, request.sampling_params.width) == (1024, 1024)
|
||||
assert _bagel_canvas_requested(request.sampling_params)
|
||||
|
||||
|
||||
def test_bagel_pre_process_floors_unaligned_explicit_canvas_with_warning(tmp_path):
|
||||
pre_process = _pre_process_with_stub_checkpoint(tmp_path)
|
||||
request = _edit_request(
|
||||
(1280, 720),
|
||||
OmniDiffusionSamplingParams(num_inference_steps=2, height=700, width=1000),
|
||||
)
|
||||
|
||||
with patch("vllm_omni.diffusion.models.bagel.pipeline_bagel.logger.warning") as warning:
|
||||
pre_process(request)
|
||||
|
||||
assert (request.sampling_params.height, request.sampling_params.width) == (688, 992)
|
||||
assert _bagel_canvas_requested(request.sampling_params)
|
||||
warning.assert_called_once()
|
||||
assert "width 1000->992, height 700->688" in warning.call_args.args[-1]
|
||||
|
||||
|
||||
def test_bagel_pre_process_keeps_aligned_explicit_canvas_silent(tmp_path):
|
||||
pre_process = _pre_process_with_stub_checkpoint(tmp_path)
|
||||
request = _edit_request(
|
||||
(1280, 720),
|
||||
OmniDiffusionSamplingParams(num_inference_steps=2, height=512, width=1024),
|
||||
)
|
||||
|
||||
with patch("vllm_omni.diffusion.models.bagel.pipeline_bagel.logger.warning") as warning:
|
||||
pre_process(request)
|
||||
|
||||
assert (request.sampling_params.height, request.sampling_params.width) == (512, 1024)
|
||||
warning.assert_not_called()
|
||||
|
||||
|
||||
def test_bagel_pre_process_rejects_explicit_canvas_over_checkpoint_limit(tmp_path):
|
||||
pre_process = _pre_process_with_stub_checkpoint(tmp_path)
|
||||
request = _edit_request(
|
||||
(1280, 720),
|
||||
OmniDiffusionSamplingParams(num_inference_steps=2, height=512, width=2048),
|
||||
)
|
||||
|
||||
with pytest.raises(OmniClientError, match="width=2048 exceeds the BAGEL checkpoint limit of 1024") as excinfo:
|
||||
pre_process(request)
|
||||
|
||||
assert excinfo.value.status_code == 400
|
||||
|
||||
|
||||
def test_bagel_pre_process_aligns_text2img_canvas_too(tmp_path):
|
||||
pre_process = _pre_process_with_stub_checkpoint(tmp_path)
|
||||
request = OmniDiffusionRequest(
|
||||
prompt="a cat",
|
||||
sampling_params=OmniDiffusionSamplingParams(num_inference_steps=2, height=700, width=1000),
|
||||
request_id="req",
|
||||
)
|
||||
|
||||
pre_process(request)
|
||||
|
||||
assert (request.sampling_params.height, request.sampling_params.width) == (688, 992)
|
||||
|
||||
|
||||
def test_bagel_pre_process_skips_canvas_alignment_for_text_output(tmp_path):
|
||||
pre_process = _pre_process_with_stub_checkpoint(tmp_path)
|
||||
request = OmniDiffusionRequest(
|
||||
prompt={
|
||||
"prompt": "describe this image",
|
||||
"modalities": ["text"],
|
||||
"multi_modal_data": {"image": [Image.new("RGB", (1280, 720))]},
|
||||
},
|
||||
sampling_params=OmniDiffusionSamplingParams(num_inference_steps=2, height=700, width=1000),
|
||||
request_id="req",
|
||||
)
|
||||
|
||||
pre_process(request)
|
||||
|
||||
assert (request.sampling_params.height, request.sampling_params.width) == (700, 1000)
|
||||
assert request.use_step_execution is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("sampling_kwargs", "requested"),
|
||||
[
|
||||
({"height": 1024, "width": 1024}, True),
|
||||
({"height": 1024, "width": 512, "height_not_provided": True, "width_not_provided": True}, False),
|
||||
({}, False),
|
||||
],
|
||||
ids=["explicit_size", "size_auto", "unset"],
|
||||
)
|
||||
def test_bagel_canvas_requested_separates_asked_for_from_derived(sampling_kwargs, requested):
|
||||
assert _bagel_canvas_requested(OmniDiffusionSamplingParams(**sampling_kwargs)) is requested
|
||||
|
||||
|
||||
def _cache(length: int, value: float, num_layers: int = 1) -> NaiveCache:
|
||||
cache = NaiveCache(num_layers)
|
||||
if length:
|
||||
|
||||
@@ -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
|
||||
"""Multi-image input regression for HunyuanImage3 IT2I prompt construction.
|
||||
|
||||
The official HunyuanImage-3.0-Instruct supports up to 3 reference images
|
||||
@@ -41,7 +41,7 @@ pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
class FakeTokenizer:
|
||||
"""Recording fake tokenizer mirroring the one in test_prompt_utils.
|
||||
"""Recording fake tokenizer mirroring the one in test_hunyuan_image3_prompt_utils.
|
||||
|
||||
Special token ids: `<|startoftext|>`=1, `<img>`=2, `<think>`=3,
|
||||
`<recaption>`=4. encode() returns one id per character starting at
|
||||
|
||||
+1
-1
@@ -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
|
||||
|
||||
import ast
|
||||
@@ -134,6 +134,8 @@ def _install_vllm_stubs() -> None:
|
||||
**kwargs,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.quant_config = kwargs.pop("quant_config", None)
|
||||
self.prefix = kwargs.pop("prefix", "")
|
||||
del kwargs
|
||||
self.return_bias = return_bias
|
||||
self.weight = nn.Parameter(torch.empty(output_size, input_size))
|
||||
@@ -164,6 +166,8 @@ def _install_vllm_stubs() -> None:
|
||||
**kwargs,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.quant_config = kwargs.pop("quant_config", None)
|
||||
self.prefix = kwargs.pop("prefix", "")
|
||||
del kwargs
|
||||
self.num_heads = total_num_heads
|
||||
self.num_kv_heads = total_num_kv_heads or total_num_heads
|
||||
|
||||
@@ -35,6 +35,8 @@ def _tiny_model(
|
||||
num_layers: int = 2,
|
||||
num_frames_per_block: int = 1,
|
||||
sliding_window_num_frames: int = 3,
|
||||
quant_config=None,
|
||||
prefix: str = "",
|
||||
attention_head_dim: int = 2,
|
||||
rope_max_seq_len: int = 16,
|
||||
):
|
||||
@@ -55,6 +57,8 @@ def _tiny_model(
|
||||
num_frames_per_block=num_frames_per_block,
|
||||
sliding_window_num_frames=sliding_window_num_frames,
|
||||
local_attn_size=-1,
|
||||
quant_config=quant_config,
|
||||
prefix=prefix,
|
||||
)
|
||||
|
||||
|
||||
@@ -485,11 +489,52 @@ def test_constructor_rejects_non_null_image_embedding_fields(field: str) -> None
|
||||
|
||||
|
||||
@pytest.mark.cpu
|
||||
def test_constructor_rejects_unsupported_quantization_with_runtime_error() -> None:
|
||||
@pytest.mark.parametrize("prefix", ["", "transformer"])
|
||||
@pytest.mark.parametrize("quantized", [False, True])
|
||||
def test_constructor_propagates_quantization_to_parallel_linears(prefix: str, quantized: bool) -> None:
|
||||
module = attention_tests._load_module()
|
||||
quant_config = object() if quantized else None
|
||||
model = _tiny_model(module, num_layers=1, quant_config=quant_config, prefix=prefix)
|
||||
block = model.blocks[0]
|
||||
quantized_linears = [
|
||||
model.c2ws_hidden_states_layer1,
|
||||
model.c2ws_hidden_states_layer2,
|
||||
block.self_attn.qkv,
|
||||
block.self_attn.o,
|
||||
block.cross_attn.q,
|
||||
block.cross_attn.k,
|
||||
block.cross_attn.v,
|
||||
block.cross_attn.o,
|
||||
block.ffn[0],
|
||||
block.ffn[2],
|
||||
block.cam_injector_layer1,
|
||||
block.cam_injector_layer2,
|
||||
]
|
||||
|
||||
with pytest.raises(RuntimeError, match="quant_config.*not supported"):
|
||||
module.CausalLingBotWorldTransformer3DModel(quant_config=object())
|
||||
assert len(quantized_linears) == 12
|
||||
assert all(layer.quant_config is quant_config for layer in quantized_linears)
|
||||
expected_names = {
|
||||
"c2ws_hidden_states_layer1",
|
||||
"c2ws_hidden_states_layer2",
|
||||
*(
|
||||
f"blocks.0.{name}"
|
||||
for name in (
|
||||
"self_attn.qkv",
|
||||
"self_attn.o",
|
||||
"cross_attn.q",
|
||||
"cross_attn.k",
|
||||
"cross_attn.v",
|
||||
"cross_attn.o",
|
||||
"ffn.0",
|
||||
"ffn.2",
|
||||
"cam_injector_layer1",
|
||||
"cam_injector_layer2",
|
||||
)
|
||||
),
|
||||
}
|
||||
assert {layer.prefix for layer in quantized_linears} == {
|
||||
f"{prefix}.{name}" if prefix else name for name in expected_names
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.cpu
|
||||
|
||||
@@ -737,6 +737,99 @@ def test_component_discovery_uses_official_checkpoint_contract() -> None:
|
||||
assert module._loader_state.prefetch_calls == [("checkpoint", ("tokenizer", "text_encoder", "vae"), False)]
|
||||
|
||||
|
||||
def _ulysses_config(size: int):
|
||||
parallel_config = _od_config().parallel_config
|
||||
parallel_config.sequence_parallel_size = size
|
||||
parallel_config.ulysses_degree = size
|
||||
return _od_config(parallel_config=parallel_config)
|
||||
|
||||
|
||||
def _record_shard_install(monkeypatch, module, *, world_size: int):
|
||||
"""Stand in for the Ulysses group and the decoder patch; return what the install was asked for."""
|
||||
installs: list[dict] = []
|
||||
group = object()
|
||||
|
||||
def install(vae, group_arg, split_dim, *, dst):
|
||||
installs.append({"vae": vae, "group": group_arg, "split_dim": split_dim, "dst": dst})
|
||||
|
||||
monkeypatch.setattr(module, "install_wan_spatial_shard_decode", install)
|
||||
monkeypatch.setattr(module.LingBotWorldCausalDMDPipeline, "_vae_shard_group", lambda self: (group, world_size))
|
||||
return installs, group
|
||||
|
||||
|
||||
def test_a_multi_rank_deployment_shards_the_decoder_across_the_ulysses_ranks(monkeypatch) -> None:
|
||||
"""Multi-rank deployments shard decode by default."""
|
||||
module = _load_pipeline_module()
|
||||
installs, group = _record_shard_install(monkeypatch, module, world_size=2)
|
||||
|
||||
pipeline = module.LingBotWorldCausalDMDPipeline(od_config=_ulysses_config(2))
|
||||
|
||||
# Along the width, and assembled on every rank: each rank's post_decode consumes the frame.
|
||||
assert installs == [{"vae": pipeline.vae, "group": group, "split_dim": "width", "dst": None}]
|
||||
assert pipeline._vae_shard_split_dim == "width"
|
||||
|
||||
|
||||
def test_a_single_rank_deployment_leaves_the_decoder_alone(monkeypatch) -> None:
|
||||
module = _load_pipeline_module()
|
||||
installs, _ = _record_shard_install(monkeypatch, module, world_size=1)
|
||||
|
||||
pipeline = module.LingBotWorldCausalDMDPipeline(od_config=_ulysses_config(1))
|
||||
|
||||
assert installs == [] and pipeline._vae_shard_split_dim is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("enabled", [True, False])
|
||||
@pytest.mark.parametrize("width, local_width", [(832, 208), (840, 216)])
|
||||
def test_streaming_decode_reservation_uses_padded_shards(monkeypatch, enabled, width, local_width):
|
||||
module = _load_pipeline_module()
|
||||
installs, _ = _record_shard_install(monkeypatch, module, world_size=4)
|
||||
config = _ulysses_config(4)
|
||||
config.model_config.update(lingbot_vae_spatial_sharding=enabled, ar_diffusion_height=480, ar_diffusion_width=width)
|
||||
pipeline = module.LingBotWorldCausalDMDPipeline(od_config=config)
|
||||
from vllm_omni.experimental.ar_diffusion.streaming_decode import WanStreamingDecoder
|
||||
|
||||
# Exercise the real byte estimator without constructing a checkpoint VAE.
|
||||
decoder = object.__new__(WanStreamingDecoder)
|
||||
decoder._bytes_per_pixel_fp32 = 16.0
|
||||
monkeypatch.setattr(pipeline, "_streaming_decoder", lambda: decoder)
|
||||
expected_width = local_width if enabled else width
|
||||
assert pipeline._streaming_decode_bytes_per_session() == 16 * 480 * expected_width
|
||||
assert len(installs) == int(enabled)
|
||||
assert pipeline._vae_shard_world_size == (4 if enabled else 1)
|
||||
assert config.parallel_config.sequence_parallel_size == config.parallel_config.ulysses_degree == 4
|
||||
|
||||
|
||||
def test_disabling_vae_sharding_does_not_require_a_shard_group(monkeypatch):
|
||||
module = _load_pipeline_module()
|
||||
config = _ulysses_config(4)
|
||||
config.model_config["lingbot_vae_spatial_sharding"] = False
|
||||
|
||||
def unexpected_group(self):
|
||||
pytest.fail("disabled VAE sharding must not access its process group")
|
||||
|
||||
monkeypatch.setattr(module.LingBotWorldCausalDMDPipeline, "_vae_shard_group", unexpected_group)
|
||||
pipeline = module.LingBotWorldCausalDMDPipeline(od_config=config)
|
||||
assert pipeline._vae_shard_split_dim is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", ["false", 0, None])
|
||||
def test_vae_sharding_switch_requires_a_boolean(value):
|
||||
module = _load_pipeline_module()
|
||||
config = _ulysses_config(4)
|
||||
config.model_config["lingbot_vae_spatial_sharding"] = value
|
||||
with pytest.raises(ValueError, match="lingbot_vae_spatial_sharding must be a boolean"):
|
||||
module.LingBotWorldCausalDMDPipeline(od_config=config)
|
||||
|
||||
|
||||
def test_vae_shard_refuses_a_group_of_the_wrong_size(monkeypatch) -> None:
|
||||
module = _load_pipeline_module()
|
||||
installs, _ = _record_shard_install(monkeypatch, module, world_size=4)
|
||||
|
||||
with pytest.raises(RuntimeError, match="sequence_parallel_size=2 but the Ulysses group has 4 ranks"):
|
||||
module.LingBotWorldCausalDMDPipeline(od_config=_ulysses_config(2))
|
||||
assert installs == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("field", "value", "feature"),
|
||||
[
|
||||
@@ -758,8 +851,9 @@ def test_unsupported_parallel_modes_fail_before_component_loading(field: str, va
|
||||
assert module._loader_state.prefetch_calls == []
|
||||
|
||||
|
||||
def test_pure_ulysses_parallel_config_is_supported() -> None:
|
||||
def test_pure_ulysses_parallel_config_is_supported(monkeypatch) -> None:
|
||||
module = _load_pipeline_module()
|
||||
_record_shard_install(monkeypatch, module, world_size=2)
|
||||
parallel_config = _od_config().parallel_config
|
||||
parallel_config.sequence_parallel_size = 2
|
||||
parallel_config.ulysses_degree = 2
|
||||
@@ -795,13 +889,14 @@ def test_unsupported_sp_config_fails_before_component_loading(overrides):
|
||||
assert module._loader_state.prefetch_calls == []
|
||||
|
||||
|
||||
def test_unsupported_quantization_fails_before_component_loading() -> None:
|
||||
def test_quantization_reaches_transformer_factory() -> None:
|
||||
module = _load_pipeline_module()
|
||||
quant_config = object()
|
||||
|
||||
with pytest.raises(NotImplementedError, match="quantization"):
|
||||
module.LingBotWorldCausalDMDPipeline(od_config=_od_config(quantization_config=object()))
|
||||
pipeline = module.LingBotWorldCausalDMDPipeline(od_config=_od_config(quantization_config=quant_config))
|
||||
|
||||
assert module._loader_state.prefetch_calls == []
|
||||
assert pipeline.transformer is not None
|
||||
assert _FakeTransformerFactory.last_call[1:] == (quant_config, "transformer")
|
||||
|
||||
|
||||
def test_official_scheduler_config_matches_fixed_dmd_contract() -> None:
|
||||
@@ -1358,10 +1453,34 @@ def test_first_frame_condition_and_camera_fold_match_transformer_contract() -> N
|
||||
assert expected_camera.shape == (1, 384, 3, 2, 2)
|
||||
|
||||
|
||||
def test_fixed_dmd_transition_and_cache_commit_trace() -> None:
|
||||
@pytest.mark.parametrize("value", ["true", "false", 1, 0, None])
|
||||
def test_reuse_last_step_kv_rejects_non_boolean_config(value: object) -> None:
|
||||
config = _od_config()
|
||||
config.model_config["lingbot_reuse_last_step_kv"] = value
|
||||
with pytest.raises(ValueError, match="lingbot_reuse_last_step_kv must be a bool"):
|
||||
_pipeline(_load_pipeline_module(), od_config=config)
|
||||
|
||||
|
||||
def test_reuse_last_step_kv_is_fixed_per_instance(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setenv("VLLM_OMNI_LINGBOT_REUSE_LAST_STEP_KV", "1")
|
||||
module = _load_pipeline_module()
|
||||
config = _od_config()
|
||||
config.model_config["lingbot_reuse_last_step_kv"] = True
|
||||
reuse = _pipeline(module, od_config=config)
|
||||
default = _pipeline(module)
|
||||
config.model_config["lingbot_reuse_last_step_kv"] = False
|
||||
assert reuse._dmd_blocks.reuse_last_step_kv is True
|
||||
assert default._dmd_blocks.reuse_last_step_kv is False
|
||||
assert reuse._dmd_blocks is reuse._dmd_blocks
|
||||
|
||||
|
||||
@pytest.mark.parametrize("reuse_last_step_kv", [False, True])
|
||||
def test_fixed_dmd_transition_and_cache_commit_trace(reuse_last_step_kv: bool) -> None:
|
||||
module = _load_pipeline_module()
|
||||
transformer = _RecordingTransformer()
|
||||
pipeline = _pipeline(module, transformer=transformer)
|
||||
config = _od_config()
|
||||
config.model_config["lingbot_reuse_last_step_kv"] = reuse_last_step_kv
|
||||
pipeline = _pipeline(module, transformer=transformer, od_config=config)
|
||||
|
||||
result = pipeline(_request())
|
||||
|
||||
@@ -1383,14 +1502,18 @@ def test_fixed_dmd_transition_and_cache_commit_trace() -> None:
|
||||
current = x0
|
||||
torch.testing.assert_close(result.output, current)
|
||||
|
||||
expected_timesteps = [timestep for timestep, _ in warped_schedule]
|
||||
if not reuse_last_step_kv:
|
||||
expected_timesteps.append(0.0)
|
||||
torch.testing.assert_close(
|
||||
torch.cat([call["timestep"] for call in transformer.calls]),
|
||||
torch.tensor([*(timestep for timestep, _ in warped_schedule), 0.0]),
|
||||
torch.cat([call["timestep"] for call in transformer.calls]), torch.tensor(expected_timesteps)
|
||||
)
|
||||
assert [call["update_cache"] for call in transformer.calls] == [False, False, False, False, True]
|
||||
assert [call["start_frame"] for call in transformer.calls] == [0, 0, 0, 0, 0]
|
||||
commit_flags = [False] * (len(expected_timesteps) - 1) + [True]
|
||||
assert [call["update_cache"] for call in transformer.calls] == commit_flags
|
||||
assert [call["start_frame"] for call in transformer.calls] == [0] * len(expected_timesteps)
|
||||
assert len({call["cache_id"] for call in transformer.calls}) == 1
|
||||
torch.testing.assert_close(transformer.calls[-1]["hidden_states"][:, :16], result.output)
|
||||
committed_latent = result.output + warped_schedule[-1][1] if reuse_last_step_kv else result.output
|
||||
torch.testing.assert_close(transformer.calls[-1]["hidden_states"][:, :16], committed_latent)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
@@ -2389,10 +2512,13 @@ def test_forward_rejects_a_stepwise_camera_action_script(extra_args) -> None:
|
||||
pipeline(_request(sampling=sampling))
|
||||
|
||||
|
||||
def test_stepwise_progress_metadata_and_commit_trace() -> None:
|
||||
@pytest.mark.parametrize("reuse_last_step_kv", [False, True])
|
||||
def test_stepwise_progress_metadata_and_commit_trace(reuse_last_step_kv: bool) -> None:
|
||||
module = _load_pipeline_module()
|
||||
transformer = _RecordingTransformer()
|
||||
pipeline = _pipeline(module, transformer=transformer)
|
||||
config = _od_config()
|
||||
config.model_config["lingbot_reuse_last_step_kv"] = reuse_last_step_kv
|
||||
pipeline = _pipeline(module, transformer=transformer, od_config=config)
|
||||
pipeline._ar_height = 16
|
||||
pipeline._ar_width = 16
|
||||
state = _stepwise_state(num_frames=21)
|
||||
@@ -2406,8 +2532,9 @@ def test_stepwise_progress_metadata_and_commit_trace() -> None:
|
||||
assert [output.chunk_index for output in outputs] == [0, 1]
|
||||
assert all(output.total_chunks == 2 for output in outputs)
|
||||
assert outputs[-1].finished is True
|
||||
assert [call["update_cache"] for call in transformer.calls] == [False, False, False, False, True] * 2
|
||||
assert [call["start_frame"] for call in transformer.calls] == [0] * 5 + [3] * 5
|
||||
calls_per_chunk = 4 if reuse_last_step_kv else 5
|
||||
assert [call["update_cache"] for call in transformer.calls] == ([False] * (calls_per_chunk - 1) + [True]) * 2
|
||||
assert [call["start_frame"] for call in transformer.calls] == [0] * calls_per_chunk + [3] * calls_per_chunk
|
||||
assert fake.commits == ["main", "main"]
|
||||
for chunk_index, output in enumerate(outputs):
|
||||
metadata = output.output["metadata"]["ar_diffusion"]
|
||||
|
||||
@@ -171,7 +171,7 @@ def test_huggingface_url_resolves_pinned_snapshot(tmp_path, monkeypatch):
|
||||
else pytest.fail("unexpected snapshot request")
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"vllm.transformers_utils.repo_utils.hf_api",
|
||||
"vllm_omni.transformers_utils.repo_utils.hf_api",
|
||||
lambda: api,
|
||||
)
|
||||
assert _resolve_checkpoint_root(
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
import json
|
||||
import sys
|
||||
from contextlib import contextmanager
|
||||
from contextlib import contextmanager, nullcontext
|
||||
from multiprocessing.reduction import ForkingPickler
|
||||
from types import SimpleNamespace
|
||||
from typing import Any, TypeVar
|
||||
@@ -2837,41 +2837,63 @@ def test_dit_encoder_selection_keeps_vae_resident():
|
||||
component.offload_to_cpu.assert_not_called()
|
||||
|
||||
|
||||
def test_keyframe_encode_pins_and_restores_cudnn_settings():
|
||||
@pytest.mark.parametrize(
|
||||
("capability", "allow_tf32"),
|
||||
[((8, 6), True), ((9, 0), False), ((10, 0), True), ((10, 3), True), (None, True)],
|
||||
)
|
||||
@pytest.mark.parametrize("initial_tf32", [False, True])
|
||||
@pytest.mark.parametrize("fail_encode", [False, True])
|
||||
def test_keyframe_encode_pins_and_restores_cudnn_settings(
|
||||
monkeypatch, capability, allow_tf32, initial_tf32, fail_encode
|
||||
):
|
||||
from vllm.platforms.interface import DeviceCapability
|
||||
|
||||
from vllm_omni.diffusion.models.minimax_h3.vae import (
|
||||
_minimax_h3_keyframe_encode_context,
|
||||
)
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
def get_capability(device_id):
|
||||
assert device_id == 1
|
||||
return DeviceCapability(*capability) if capability is not None else None
|
||||
|
||||
monkeypatch.setattr(current_omni_platform, "is_cuda", lambda: True)
|
||||
monkeypatch.setattr(current_omni_platform, "get_device_capability", get_capability)
|
||||
|
||||
cudnn = torch.backends.cudnn
|
||||
original = (
|
||||
cudnn.enabled,
|
||||
cudnn.benchmark,
|
||||
cudnn.deterministic,
|
||||
cudnn.allow_tf32,
|
||||
)
|
||||
try:
|
||||
cudnn.enabled = False
|
||||
cudnn.benchmark = True
|
||||
cudnn.deterministic = False
|
||||
cudnn.allow_tf32 = False
|
||||
|
||||
with _minimax_h3_keyframe_encode_context(torch.device("cuda")):
|
||||
with cudnn.flags(enabled=False, benchmark=True, deterministic=False, allow_tf32=initial_tf32):
|
||||
error_context = pytest.raises(RuntimeError, match="encode failed") if fail_encode else nullcontext()
|
||||
with error_context, _minimax_h3_keyframe_encode_context(torch.device("cuda:1")):
|
||||
assert cudnn.enabled
|
||||
assert not cudnn.benchmark
|
||||
assert cudnn.deterministic
|
||||
assert cudnn.allow_tf32
|
||||
assert cudnn.allow_tf32 is allow_tf32
|
||||
if fail_encode:
|
||||
raise RuntimeError("encode failed")
|
||||
|
||||
assert not cudnn.enabled
|
||||
assert cudnn.benchmark
|
||||
assert not cudnn.deterministic
|
||||
assert not cudnn.allow_tf32
|
||||
finally:
|
||||
(
|
||||
cudnn.enabled,
|
||||
cudnn.benchmark,
|
||||
cudnn.deterministic,
|
||||
cudnn.allow_tf32,
|
||||
) = original
|
||||
assert cudnn.allow_tf32 is initial_tf32
|
||||
|
||||
|
||||
def test_keyframe_encode_cpu_keeps_cudnn_settings(monkeypatch):
|
||||
from vllm_omni.diffusion.models.minimax_h3.vae import (
|
||||
_minimax_h3_keyframe_encode_context,
|
||||
)
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
def unexpected_capability_query(device_id):
|
||||
pytest.fail("CPU keyframe encode must not query CUDA capability")
|
||||
|
||||
monkeypatch.setattr(current_omni_platform, "get_device_capability", unexpected_capability_query)
|
||||
cudnn = torch.backends.cudnn
|
||||
with cudnn.flags(enabled=False, benchmark=True, deterministic=False, allow_tf32=False):
|
||||
with _minimax_h3_keyframe_encode_context(torch.device("cpu")):
|
||||
assert not cudnn.enabled
|
||||
assert cudnn.benchmark
|
||||
assert not cudnn.deterministic
|
||||
assert not cudnn.allow_tf32
|
||||
|
||||
|
||||
@pytest.mark.parametrize("fail_encode", [False, True])
|
||||
|
||||
@@ -10,7 +10,6 @@ from vllm_omni.diffusion.layers.indexed_modulation import (
|
||||
_MAX_1D_GRID_SIZE,
|
||||
_iter_row_chunks,
|
||||
_launch_row_chunks,
|
||||
_use_hopper_bf16_affine_semantics,
|
||||
indexed_gate,
|
||||
indexed_gate_rms_norm_scale_shift,
|
||||
indexed_scale_shift_,
|
||||
@@ -194,52 +193,28 @@ def test_fused_modulation_preserves_bf16_residual_boundary() -> None:
|
||||
|
||||
|
||||
@pytest.mark.cuda
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required")
|
||||
@pytest.mark.skipif(
|
||||
torch.cuda.is_available() and torch.cuda.get_device_capability()[0] != 9,
|
||||
reason="SM90-specific precision path",
|
||||
)
|
||||
@pytest.mark.skipif(not current_omni_platform.is_cuda(), reason="CUDA required")
|
||||
@pytest.mark.skipif(not HAS_TRITON, reason="Triton required")
|
||||
def test_hopper_fused_modulation_matches_pytorch_reference() -> None:
|
||||
torch.manual_seed(42)
|
||||
rows, hidden_size, conditions = 128, 3072, 4
|
||||
residual = torch.randn(rows, hidden_size, device="cuda", dtype=torch.bfloat16)
|
||||
gate = torch.randn(conditions, hidden_size, device="cuda", dtype=torch.bfloat16)
|
||||
branch = torch.randn(rows, hidden_size, device="cuda", dtype=torch.bfloat16)
|
||||
weight = torch.randn(hidden_size, device="cuda", dtype=torch.bfloat16)
|
||||
shift = torch.randn(conditions, hidden_size, device="cuda", dtype=torch.bfloat16)
|
||||
scale = torch.randn(conditions, hidden_size, device="cuda", dtype=torch.bfloat16)
|
||||
indices = torch.arange(rows, device="cuda") % conditions
|
||||
@pytest.mark.parametrize("fused_gate", [False, True])
|
||||
def test_fused_modulation_keeps_fp32_affine_intermediates(fused_gate: bool) -> None:
|
||||
device = current_omni_platform.get_torch_device()
|
||||
rows, hidden_size = 2, 5376
|
||||
x = torch.ones(rows, hidden_size, device=device, dtype=torch.bfloat16)
|
||||
weight = torch.full((hidden_size,), 1.125, device=device, dtype=x.dtype)
|
||||
shift = torch.zeros(1, hidden_size, device=device, dtype=x.dtype)
|
||||
scale = torch.full_like(shift, 0.09375)
|
||||
indices = torch.zeros(rows, device=device, dtype=torch.int64)
|
||||
eps = 1e-6
|
||||
if fused_gate:
|
||||
residual, actual = indexed_gate_rms_norm_scale_shift(
|
||||
x, torch.zeros_like(shift), x, weight, shift, scale, indices, eps
|
||||
)
|
||||
assert torch.equal(residual, x)
|
||||
else:
|
||||
actual = rms_norm_indexed_scale_shift(x, weight, shift, scale, indices, eps)
|
||||
|
||||
reference_residual = (residual + gate.index_select(0, indices) * branch).to(torch.bfloat16)
|
||||
normalized = reference_residual.float()
|
||||
variance = normalized.pow(2).mean(-1, keepdim=True)
|
||||
normalized = (weight.float() * (normalized * torch.rsqrt(variance + eps))).to(torch.bfloat16)
|
||||
reference_modulated = (normalized * (1.0 + scale.index_select(0, indices)) + shift.index_select(0, indices)).to(
|
||||
torch.bfloat16
|
||||
)
|
||||
|
||||
actual_residual, actual_modulated = indexed_gate_rms_norm_scale_shift(
|
||||
residual,
|
||||
gate,
|
||||
branch,
|
||||
weight,
|
||||
shift,
|
||||
scale,
|
||||
indices,
|
||||
eps,
|
||||
)
|
||||
|
||||
torch.testing.assert_close(actual_residual, reference_residual, atol=5e-2, rtol=5e-2)
|
||||
torch.testing.assert_close(actual_modulated, reference_modulated, atol=5e-2, rtol=5e-2)
|
||||
|
||||
|
||||
@pytest.mark.cuda
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required")
|
||||
def test_hopper_precision_dispatch_is_architecture_scoped(monkeypatch) -> None:
|
||||
tensor = torch.empty(0, device="cuda")
|
||||
monkeypatch.setattr(torch.cuda, "get_device_capability", lambda _device: (9, 0))
|
||||
assert _use_hopper_bf16_affine_semantics(tensor)
|
||||
monkeypatch.setattr(torch.cuda, "get_device_capability", lambda _device: (10, 3))
|
||||
assert not _use_hopper_bf16_affine_semantics(tensor)
|
||||
# Without the RMS epsilon, 1.125 * 1.09375 = 1.23046875 is exactly
|
||||
# halfway between two BF16 values. FP32 normalization keeps the epsilon
|
||||
# and rounds down to 1.2265625. Premature BF16 rounding drops the epsilon
|
||||
# and instead rounds the tie up to 1.234375, changing every output row.
|
||||
assert torch.equal(actual, torch.full_like(x, 1.2265625))
|
||||
@@ -16,6 +16,7 @@ from tests.diffusion.quantization.test_quantization_quality import (
|
||||
_maybe_save_output,
|
||||
)
|
||||
from tests.helpers.mark import hardware_marks
|
||||
from tests.helpers.mock import patch_hf_snapshot_download
|
||||
|
||||
_MINIMAX_H3_REPO = "MiniMaxAI/MiniMax-H3"
|
||||
_MINIMAX_H3_REVISION = "48d93ede732756e404a3b1b2f3b3a9b5a22f6cfc"
|
||||
@@ -258,13 +259,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(self, *, repo_id, revision, allow_patterns):
|
||||
def fake_snapshot_download(*, 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.HfApi.snapshot_download", fake_snapshot_download)
|
||||
patch_hf_snapshot_download(monkeypatch, fake_snapshot_download, hf_home=tmp_path)
|
||||
assert _resolve_fl2va_model_ref() == str(fl2va_root)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from types import MethodType, SimpleNamespace
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm_omni.diffusion.models.nextstep_1_1 import pipeline_nextstep_1_1 as pipeline_module
|
||||
from vllm_omni.diffusion.models.nextstep_1_1.modeling_nextstep import NextStepModel
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu, pytest.mark.diffusion]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("height,width", [(32, 32), (32, 48), (48, 32)])
|
||||
@pytest.mark.parametrize("batch", [1, 2])
|
||||
def test_forward_preserves_latent_grid(monkeypatch, height, width, batch):
|
||||
pipeline = object.__new__(pipeline_module.NextStep11Pipeline)
|
||||
torch.nn.Module.__init__(pipeline)
|
||||
pipeline._NextStep11Pipeline__device = torch.device("cpu")
|
||||
pipeline.config = SimpleNamespace(use_gen_pos_embed=False)
|
||||
pipeline.down_factor = 16
|
||||
pipeline.scaling_factor = 2.0
|
||||
pipeline.shift_factor = 0.25
|
||||
grid = SimpleNamespace(config=SimpleNamespace(latent_channels=2, latent_patch_size=2))
|
||||
expected = torch.arange(batch * 2 * (height // 8) * (width // 8), dtype=torch.float32)
|
||||
expected = expected.reshape(batch, 2, height // 8, width // 8)
|
||||
tokens = NextStepModel.patchify(grid, expected)
|
||||
pipeline.model = Mock(
|
||||
return_value=SimpleNamespace(last_hidden_state=torch.zeros(batch, 1, 4), past_key_values=None)
|
||||
)
|
||||
pipeline.model.forward_model.return_value = pipeline.model.return_value
|
||||
pipeline.model.unpatchify = MethodType(NextStepModel.unpatchify, grid)
|
||||
pipeline.tokenizer = Mock(
|
||||
bos_token=None,
|
||||
return_value=SimpleNamespace(
|
||||
input_ids=torch.ones(batch, 2, dtype=torch.long), attention_mask=torch.ones(batch, 2, dtype=torch.long)
|
||||
),
|
||||
)
|
||||
pipeline._check_input = Mock(return_value=(["teapot"], None))
|
||||
pipeline._build_captions = Mock(return_value=(["teapot"] * batch, None, 1, 1.0))
|
||||
pipeline._add_prefix_ids = lambda _hw, ids, mask: (ids, mask)
|
||||
pipeline.decoding = Mock(return_value=tokens)
|
||||
pipeline.vae = SimpleNamespace(dtype=torch.float32, decode=lambda latent: SimpleNamespace(sample=latent))
|
||||
monkeypatch.setattr(pipeline_module, "StaticCache", lambda **_kwargs: None)
|
||||
params = OmniDiffusionSamplingParams(
|
||||
height=height, width=width, guidance_scale=1.0, num_outputs_per_prompt=batch, seed=None
|
||||
)
|
||||
output = pipeline.forward(SimpleNamespace(prompts=["teapot"], sampling_params=params))
|
||||
torch.testing.assert_close(output.output, expected / 2 + 0.25, rtol=0, atol=0)
|
||||
@@ -497,3 +497,99 @@ class TestWorkerProcShutdown:
|
||||
result_mq.shutdown.assert_called_once_with()
|
||||
assert proc.mq is None
|
||||
assert proc.result_mq is None
|
||||
|
||||
|
||||
class TestSynchronizeDeviceBarrier:
|
||||
"""The pause barrier must not report a quiet device while outputs still pack."""
|
||||
|
||||
@staticmethod
|
||||
def _rpc(timeout):
|
||||
return {
|
||||
"method": "synchronize_device",
|
||||
"args": (),
|
||||
"kwargs": {"timeout": timeout},
|
||||
"output_rank": 0,
|
||||
"exec_all_ranks": False,
|
||||
"collect_rank_status": False,
|
||||
}
|
||||
|
||||
def test_rejects_undrained_output(self, mocker):
|
||||
proc = _make_worker_proc(step_execution=False)
|
||||
proc.worker = MagicMock()
|
||||
mocker.patch.object(proc, "drain_async_outputs", return_value=False)
|
||||
|
||||
with pytest.raises(TimeoutError, match="did not drain"):
|
||||
proc._execute_rpc(self._rpc(0.01))
|
||||
|
||||
proc.worker.execute_method.assert_not_called()
|
||||
|
||||
@pytest.mark.parametrize("timeout", [0.5, None])
|
||||
def test_drains_with_the_call_timeout_then_synchronizes(self, mocker, timeout):
|
||||
proc = _make_worker_proc(step_execution=False)
|
||||
proc.worker = MagicMock()
|
||||
call_order: list = []
|
||||
mocker.patch.object(
|
||||
proc,
|
||||
"drain_async_outputs",
|
||||
side_effect=lambda **kw: call_order.append(("drain", kw)) or True,
|
||||
)
|
||||
proc.worker.execute_method.side_effect = lambda *a, **kw: call_order.append(("sync", a, kw))
|
||||
|
||||
_, should_reply = proc._execute_rpc(self._rpc(timeout))
|
||||
|
||||
assert call_order == [
|
||||
("drain", {"timeout": timeout}),
|
||||
("sync", ("synchronize_device",), {"timeout": timeout}),
|
||||
]
|
||||
assert should_reply is True
|
||||
|
||||
def test_completes_only_after_output_ready_is_published(self, mocker):
|
||||
proc = _make_worker_proc(step_execution=False)
|
||||
proc.worker = MagicMock()
|
||||
|
||||
mock_platform = mocker.MagicMock()
|
||||
mock_platform.record_device_event.return_value = MagicMock()
|
||||
mocker.patch(
|
||||
"vllm_omni.diffusion.worker.diffusion_worker.current_omni_platform",
|
||||
mock_platform,
|
||||
)
|
||||
mock_torch = mocker.MagicMock()
|
||||
mock_torch.accelerator.current_accelerator.return_value.type = "cpu"
|
||||
mocker.patch("vllm_omni.diffusion.worker.diffusion_worker.torch", mock_torch)
|
||||
release = threading.Event()
|
||||
mocker.patch(
|
||||
"vllm_omni.diffusion.worker.diffusion_worker.pack_diffusion_output_shm",
|
||||
side_effect=lambda *a, **kw: release.wait(timeout=5.0),
|
||||
)
|
||||
|
||||
proc._return_result(DiffusionOutput(output="data"), rpc_id="1")
|
||||
loop_thread = threading.Thread(target=proc._async_output_loop, daemon=True)
|
||||
loop_thread.start()
|
||||
|
||||
barrier_done = threading.Event()
|
||||
|
||||
def run_barrier():
|
||||
proc._execute_rpc(self._rpc(5.0))
|
||||
barrier_done.set()
|
||||
|
||||
barrier_thread = threading.Thread(target=run_barrier, daemon=True)
|
||||
barrier_thread.start()
|
||||
try:
|
||||
assert not barrier_done.wait(timeout=0.2)
|
||||
proc.worker.execute_method.assert_not_called()
|
||||
|
||||
release.set()
|
||||
assert barrier_done.wait(timeout=5.0)
|
||||
|
||||
kinds = [
|
||||
call.args[0].kind
|
||||
for call in proc.result_mq.enqueue.call_args_list
|
||||
if isinstance(call.args[0], AsyncDiffusionOutput)
|
||||
]
|
||||
assert kinds == [AsyncOutputKind.COMPUTE_DONE, AsyncOutputKind.OUTPUT_READY]
|
||||
proc.worker.execute_method.assert_called_once_with("synchronize_device", timeout=5.0)
|
||||
finally:
|
||||
release.set()
|
||||
proc._async_output_queue.put(None)
|
||||
loop_thread.join(timeout=2.0)
|
||||
barrier_thread.join(timeout=2.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
|
||||
"""Regression tests for the busy-loop-based RPC routing in DiffusionEngine.
|
||||
|
||||
These tests guard the invariants established when ``collective_rpc`` was
|
||||
@@ -60,6 +60,12 @@ class _ConcurrencyTrackingExecutor:
|
||||
self.is_failed = False
|
||||
self._closed = False
|
||||
self.od_config = SimpleNamespace()
|
||||
# Pause tests: a call whose gate is registered (by request id, or by
|
||||
# method name for ``synchronize_device``) blocks inside the executor
|
||||
# until the gate is set; ``version`` tags each call so a test can tell
|
||||
# which "weights" a request ran on.
|
||||
self.gates: dict[str, threading.Event] = {}
|
||||
self.version = "v1"
|
||||
|
||||
def collective_rpc(
|
||||
self,
|
||||
@@ -81,16 +87,25 @@ class _ConcurrencyTrackingExecutor:
|
||||
"kwargs": kwargs,
|
||||
"unique_reply_rank": unique_reply_rank,
|
||||
"thread": threading.get_ident(),
|
||||
"version": self.version,
|
||||
}
|
||||
)
|
||||
try:
|
||||
if self.rpc_delay:
|
||||
time.sleep(self.rpc_delay)
|
||||
if method == "synchronize_device":
|
||||
gate = self.gates.get(method)
|
||||
if gate is not None:
|
||||
gate.wait(timeout=5.0)
|
||||
return [None]
|
||||
# Distinguish per-request execution from raw RPC by method name.
|
||||
if method in {"execute_model", "execute_stepwise", "generate"}:
|
||||
# args[0] is the request-like object for execute_model.
|
||||
req = args[0] if args else None
|
||||
tag = req.request_id if req is not None and hasattr(req, "request_id") else "unknown"
|
||||
gate = self.gates.get(tag)
|
||||
if gate is not None:
|
||||
gate.wait(timeout=5.0)
|
||||
return DiffusionOutput(error=f"result_for_{tag}", finished=True)
|
||||
tag = args[0] if args else method
|
||||
return DiffusionOutput(error=f"rpc_result_for_{tag}")
|
||||
@@ -133,21 +148,27 @@ def _make_request(tag: str):
|
||||
|
||||
|
||||
def _make_engine_with_loop(
|
||||
loop: asyncio.AbstractEventLoop,
|
||||
loop: asyncio.AbstractEventLoop | None,
|
||||
rpc_delay: float = 0.0,
|
||||
*,
|
||||
scheduler: RequestScheduler | None = None,
|
||||
start_loop: bool = True,
|
||||
):
|
||||
"""Construct a ``DiffusionEngine`` skeleton with a real busy loop.
|
||||
|
||||
The engine is wired with a fake executor that asserts no concurrent
|
||||
calls and a real ``RequestScheduler``.
|
||||
calls and a real ``RequestScheduler``. ``start_loop=False`` leaves the
|
||||
engine in its bootstrap state (no busy-loop thread).
|
||||
"""
|
||||
engine = DiffusionEngine.__new__(DiffusionEngine)
|
||||
engine._closed = False
|
||||
engine.od_config = SimpleNamespace(streaming_output=False)
|
||||
engine.executor = _ConcurrencyTrackingExecutor(rpc_delay=rpc_delay)
|
||||
|
||||
sched = RequestScheduler()
|
||||
sched.initialize(SimpleNamespace(max_num_seqs=1, request_batch_max_wait_ms=0.0))
|
||||
sched = scheduler
|
||||
if sched is None:
|
||||
sched = RequestScheduler()
|
||||
sched.initialize(SimpleNamespace(max_num_seqs=1, request_batch_max_wait_ms=0.0))
|
||||
engine.scheduler = sched
|
||||
engine.step_execution = False
|
||||
engine.supports_request_batch = False
|
||||
@@ -160,9 +181,14 @@ def _make_engine_with_loop(
|
||||
engine._closed = False
|
||||
engine.abort_queue = queue.Queue()
|
||||
engine._rpc_queue = queue.Queue()
|
||||
engine._scheduling_paused = False
|
||||
|
||||
engine.main_loop = loop
|
||||
engine.stop_event = threading.Event()
|
||||
if not start_loop:
|
||||
engine._loop_started = False
|
||||
engine.worker_thread = None
|
||||
return engine
|
||||
engine._loop_started = True
|
||||
engine.worker_thread = threading.Thread(target=engine._busy_loop, daemon=True)
|
||||
engine.worker_thread.start()
|
||||
@@ -170,6 +196,10 @@ def _make_engine_with_loop(
|
||||
|
||||
|
||||
def _stop_engine(engine: DiffusionEngine) -> None:
|
||||
if engine.worker_thread is None:
|
||||
return
|
||||
for gate in engine.executor.gates.values():
|
||||
gate.set()
|
||||
with engine._cv:
|
||||
engine.stop_event.set()
|
||||
engine._cv.notify_all()
|
||||
@@ -565,3 +595,319 @@ async def test_rpc_and_request_results_do_not_swap():
|
||||
assert req_res.error == "result_for_req1"
|
||||
# Belt and braces: never overlapped on the executor.
|
||||
assert engine.executor.max_concurrent == 1
|
||||
|
||||
|
||||
# ───────────────────────── scheduler pause (keep) ─────────────────────────
|
||||
|
||||
|
||||
class _GatedAdmissionScheduler(RequestScheduler):
|
||||
"""Batching wait that only ends when the test opens admission."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
self.admission_open = threading.Event()
|
||||
|
||||
def get_admission_wait_decision(self, *, now: float, dp_concurrent: bool = False):
|
||||
decision = super().get_admission_wait_decision(now=now, dp_concurrent=dp_concurrent)
|
||||
return decision.__class__(should_wait=True, deadline=None, max_batch=self.max_num_running_reqs)
|
||||
|
||||
def should_end_admission_wait(self, decision, *, now: float, stable_since: float) -> bool:
|
||||
return self.admission_open.is_set()
|
||||
|
||||
|
||||
def _pause(engine: DiffusionEngine, timeout: float | None = None):
|
||||
return engine.async_collective_rpc("pause_scheduler", timeout=timeout, kwargs={"mode": "keep"})
|
||||
|
||||
|
||||
def _resume(engine: DiffusionEngine):
|
||||
return engine.async_collective_rpc("resume_scheduler")
|
||||
|
||||
|
||||
def _methods(engine: DiffusionEngine) -> list[str]:
|
||||
return [call["method"] for call in engine.executor.calls]
|
||||
|
||||
|
||||
def _executed(engine: DiffusionEngine) -> list[tuple[str, str]]:
|
||||
return [
|
||||
(call["args"][0].request_id, call["version"])
|
||||
for call in engine.executor.calls
|
||||
if call["method"] == "execute_model"
|
||||
]
|
||||
|
||||
|
||||
def _submit(engine: DiffusionEngine, tag: str) -> asyncio.Task:
|
||||
return asyncio.create_task(_consume_final_output(engine.async_add_req_and_stream_response(_make_request(tag))))
|
||||
|
||||
|
||||
async def _wait_until(predicate, timeout: float = 3.0) -> None:
|
||||
deadline = time.monotonic() + timeout
|
||||
while not predicate():
|
||||
if time.monotonic() > deadline:
|
||||
raise AssertionError("condition not reached in time")
|
||||
await asyncio.sleep(0.005)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_keep_pause_retains_waiting_request_and_serves_control_rpcs():
|
||||
loop = asyncio.get_running_loop()
|
||||
engine = _make_engine_with_loop(loop)
|
||||
try:
|
||||
assert await _pause(engine) is None
|
||||
queued = _submit(engine, "queued")
|
||||
result = await engine.async_collective_rpc("list_loras", unique_reply_rank=0)
|
||||
assert result.error == "rpc_result_for_list_loras"
|
||||
await asyncio.sleep(0.05)
|
||||
assert engine.scheduler.num_waiting_requests() == 1
|
||||
assert _executed(engine) == []
|
||||
assert not queued.done()
|
||||
|
||||
await _resume(engine)
|
||||
assert (await asyncio.wait_for(queued, 3.0)).error == "result_for_queued"
|
||||
assert _methods(engine) == ["synchronize_device", "list_loras", "execute_model"]
|
||||
finally:
|
||||
_stop_engine(engine)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_keep_pause_acks_after_running_batch_and_freezes_queue():
|
||||
loop = asyncio.get_running_loop()
|
||||
engine = _make_engine_with_loop(loop)
|
||||
gate = engine.executor.gates["A"] = threading.Event()
|
||||
try:
|
||||
a = _submit(engine, "A")
|
||||
await _wait_until(lambda: _executed(engine) == [("A", "v1")])
|
||||
b = _submit(engine, "B")
|
||||
await _wait_until(lambda: engine.scheduler.num_waiting_requests() == 1)
|
||||
|
||||
pause = asyncio.create_task(_pause(engine))
|
||||
await asyncio.sleep(0.1)
|
||||
assert not pause.done()
|
||||
|
||||
gate.set()
|
||||
await asyncio.wait_for(pause, 3.0)
|
||||
assert _methods(engine) == ["execute_model", "synchronize_device"]
|
||||
assert (await asyncio.wait_for(a, 3.0)).error == "result_for_A"
|
||||
assert engine.scheduler.num_waiting_requests() == 1
|
||||
assert not b.done()
|
||||
|
||||
engine.executor.version = "v2"
|
||||
await _resume(engine)
|
||||
assert (await asyncio.wait_for(b, 3.0)).error == "result_for_B"
|
||||
assert _executed(engine) == [("A", "v1"), ("B", "v2")]
|
||||
finally:
|
||||
_stop_engine(engine)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_keep_pause_ack_does_not_release_later_rpcs_before_the_batch_is_emitted():
|
||||
"""A pause ACK must not open the queue to RPCs that touch device memory
|
||||
(sleep) before the batch that just ran has been delivered.
|
||||
"""
|
||||
loop = asyncio.get_running_loop()
|
||||
engine = _make_engine_with_loop(loop)
|
||||
barrier_gate = engine.executor.gates["synchronize_device"] = threading.Event()
|
||||
methods_at_emit: list[list[str]] = []
|
||||
emit_outputs = engine._emit_outputs
|
||||
|
||||
def _recording_emit(*args, **kwargs):
|
||||
methods_at_emit.append(_methods(engine))
|
||||
return emit_outputs(*args, **kwargs)
|
||||
|
||||
engine._emit_outputs = _recording_emit
|
||||
try:
|
||||
gate = engine.executor.gates["A"] = threading.Event()
|
||||
a = _submit(engine, "A")
|
||||
await _wait_until(lambda: _executed(engine) == [("A", "v1")])
|
||||
pause = asyncio.create_task(_pause(engine))
|
||||
await _wait_until(lambda: engine._scheduling_paused)
|
||||
gate.set()
|
||||
# The barrier holds the busy loop inside the post-execute RPC drain,
|
||||
# so the sleep is queued before the pause ACK is published.
|
||||
await _wait_until(lambda: "synchronize_device" in _methods(engine))
|
||||
sleep_rpc = asyncio.create_task(engine.async_collective_rpc("handle_sleep_task", args=("t",)))
|
||||
await _wait_until(lambda: not engine._rpc_queue.empty())
|
||||
barrier_gate.set()
|
||||
|
||||
await asyncio.wait_for(pause, 3.0)
|
||||
assert (await asyncio.wait_for(a, 3.0)).error == "result_for_A"
|
||||
assert (await asyncio.wait_for(sleep_rpc, 3.0)).error == "rpc_result_for_t"
|
||||
finally:
|
||||
_stop_engine(engine)
|
||||
|
||||
assert _methods(engine) == ["execute_model", "synchronize_device", "handle_sleep_task"]
|
||||
assert methods_at_emit and "handle_sleep_task" not in methods_at_emit[0]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_timed_out_pause_still_ends_the_drain_before_the_batch_is_emitted():
|
||||
"""A pause whose caller already gave up is still a drain barrier: its
|
||||
cancelled task must not let a later RPC run before the batch is emitted.
|
||||
"""
|
||||
loop = asyncio.get_running_loop()
|
||||
engine = _make_engine_with_loop(loop)
|
||||
methods_at_emit: list[list[str]] = []
|
||||
emit_outputs = engine._emit_outputs
|
||||
|
||||
def _recording_emit(*args, **kwargs):
|
||||
methods_at_emit.append(_methods(engine))
|
||||
return emit_outputs(*args, **kwargs)
|
||||
|
||||
engine._emit_outputs = _recording_emit
|
||||
try:
|
||||
gate = engine.executor.gates["A"] = threading.Event()
|
||||
a = _submit(engine, "A")
|
||||
await _wait_until(lambda: _executed(engine) == [("A", "v1")])
|
||||
|
||||
# The caller times out while A is still executing: the pause future is
|
||||
# cancelled, but its task stays queued ahead of the sleep.
|
||||
with pytest.raises(TimeoutError):
|
||||
await _pause(engine, timeout=0.1)
|
||||
sleep_rpc = asyncio.create_task(engine.async_collective_rpc("handle_sleep_task", args=("t",)))
|
||||
await _wait_until(lambda: engine._rpc_queue.qsize() == 2)
|
||||
gate.set()
|
||||
|
||||
assert (await asyncio.wait_for(a, 3.0)).error == "result_for_A"
|
||||
assert (await asyncio.wait_for(sleep_rpc, 3.0)).error == "rpc_result_for_t"
|
||||
finally:
|
||||
_stop_engine(engine)
|
||||
|
||||
assert _methods(engine) == ["execute_model", "handle_sleep_task"]
|
||||
assert methods_at_emit and "handle_sleep_task" not in methods_at_emit[0]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pause_rejects_unsupported_modes_without_closing_the_gate():
|
||||
loop = asyncio.get_running_loop()
|
||||
engine = _make_engine_with_loop(loop)
|
||||
try:
|
||||
for kwargs in ({"mode": "abort"}, {"mode": "wait"}, {}):
|
||||
with pytest.raises(ValueError):
|
||||
await engine.async_collective_rpc("pause_scheduler", kwargs=kwargs)
|
||||
engine.execution_mode = DiffusionExecutionMode.STEP_BATCH
|
||||
with pytest.raises(NotImplementedError):
|
||||
await _pause(engine)
|
||||
engine.execution_mode = DiffusionExecutionMode.REQUEST_BATCH
|
||||
|
||||
assert (await asyncio.wait_for(_submit(engine, "still-runs"), 3.0)).error == "result_for_still-runs"
|
||||
assert _methods(engine) == ["execute_model"]
|
||||
finally:
|
||||
_stop_engine(engine)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_keep_pause_during_batching_wait_holds_the_batch():
|
||||
loop = asyncio.get_running_loop()
|
||||
sched = _GatedAdmissionScheduler()
|
||||
sched.initialize(SimpleNamespace(max_num_seqs=4, request_batch_max_wait_ms=1000.0))
|
||||
engine = _make_engine_with_loop(loop, scheduler=sched)
|
||||
try:
|
||||
waiting = _submit(engine, "W")
|
||||
await _wait_until(lambda: engine.scheduler.num_waiting_requests() == 1)
|
||||
await asyncio.sleep(0.05)
|
||||
|
||||
await asyncio.wait_for(_pause(engine), 3.0)
|
||||
assert _methods(engine) == ["synchronize_device"]
|
||||
assert engine.scheduler.num_waiting_requests() == 1
|
||||
|
||||
await _resume(engine)
|
||||
await asyncio.sleep(0.05)
|
||||
assert _executed(engine) == []
|
||||
sched.admission_open.set()
|
||||
assert (await asyncio.wait_for(waiting, 3.0)).error == "result_for_W"
|
||||
finally:
|
||||
sched.admission_open.set()
|
||||
_stop_engine(engine)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pause_timeout_leaves_gate_closed_until_explicit_resume():
|
||||
loop = asyncio.get_running_loop()
|
||||
engine = _make_engine_with_loop(loop)
|
||||
gate = engine.executor.gates["A"] = threading.Event()
|
||||
try:
|
||||
a = _submit(engine, "A")
|
||||
await _wait_until(lambda: _executed(engine) == [("A", "v1")])
|
||||
b = _submit(engine, "B")
|
||||
await _wait_until(lambda: engine.scheduler.num_waiting_requests() == 1)
|
||||
|
||||
with pytest.raises(TimeoutError):
|
||||
await _pause(engine, timeout=0.1)
|
||||
gate.set()
|
||||
assert (await asyncio.wait_for(a, 3.0)).error == "result_for_A"
|
||||
await asyncio.sleep(0.1)
|
||||
assert _executed(engine) == [("A", "v1")]
|
||||
assert not b.done()
|
||||
|
||||
await _resume(engine)
|
||||
assert (await asyncio.wait_for(b, 3.0)).error == "result_for_B"
|
||||
assert "synchronize_device" not in _methods(engine)
|
||||
finally:
|
||||
_stop_engine(engine)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_repeated_pause_and_resume_are_idempotent():
|
||||
loop = asyncio.get_running_loop()
|
||||
engine = _make_engine_with_loop(loop)
|
||||
try:
|
||||
await _resume(engine)
|
||||
await _pause(engine)
|
||||
await _pause(engine)
|
||||
queued = _submit(engine, "Q")
|
||||
await asyncio.sleep(0.05)
|
||||
assert _executed(engine) == []
|
||||
await _resume(engine)
|
||||
await _resume(engine)
|
||||
assert (await asyncio.wait_for(queued, 3.0)).error == "result_for_Q"
|
||||
assert _methods(engine) == ["synchronize_device", "synchronize_device", "execute_model"]
|
||||
finally:
|
||||
_stop_engine(engine)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_abort_of_waiting_request_while_paused_delivers_terminal():
|
||||
loop = asyncio.get_running_loop()
|
||||
engine = _make_engine_with_loop(loop)
|
||||
try:
|
||||
await _pause(engine)
|
||||
b = _submit(engine, "B")
|
||||
await _wait_until(lambda: engine.scheduler.num_waiting_requests() == 1)
|
||||
engine.abort("B")
|
||||
|
||||
result = await asyncio.wait_for(b, 3.0)
|
||||
assert result.aborted is True
|
||||
assert engine.scheduler.get_request_state("B") is None
|
||||
assert _executed(engine) == []
|
||||
|
||||
await _resume(engine)
|
||||
assert (await asyncio.wait_for(_submit(engine, "C"), 3.0)).error == "result_for_C"
|
||||
assert _executed(engine) == [("C", "v1")]
|
||||
assert engine.worker_thread.is_alive()
|
||||
finally:
|
||||
_stop_engine(engine)
|
||||
|
||||
|
||||
def test_pause_and_resume_before_loop_starts_use_engine_local_path():
|
||||
engine = _make_engine_with_loop(None, start_loop=False)
|
||||
|
||||
assert engine.collective_rpc("pause_scheduler", kwargs={"mode": "keep"}) is None
|
||||
assert _methods(engine) == ["synchronize_device"]
|
||||
|
||||
assert engine.collective_rpc("resume_scheduler") is None
|
||||
assert engine.add_req_and_wait_for_response(_make_request("X")).error == "result_for_X"
|
||||
assert _executed(engine) == [("X", "v1")]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_requests_without_pause_never_trigger_the_barrier():
|
||||
loop = asyncio.get_running_loop()
|
||||
engine = _make_engine_with_loop(loop)
|
||||
try:
|
||||
first = await asyncio.wait_for(_submit(engine, "r1"), 3.0)
|
||||
await engine.async_collective_rpc("ping", args=("p",), unique_reply_rank=0)
|
||||
second = await asyncio.wait_for(_submit(engine, "r2"), 3.0)
|
||||
finally:
|
||||
_stop_engine(engine)
|
||||
|
||||
assert (first.error, second.error) == ("result_for_r1", "result_for_r2")
|
||||
assert _methods(engine) == ["execute_model", "ping", "execute_model"]
|
||||
@@ -2092,3 +2092,19 @@ class TestStepScheduler:
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
self.scheduler.add_request(request)
|
||||
|
||||
|
||||
class TestPendingFinishedRequestIds:
|
||||
def test_reports_finished_ids_that_still_hold_state_without_clearing_them(self):
|
||||
sched = RequestScheduler()
|
||||
sched.initialize(SimpleNamespace(max_num_seqs=1, request_batch_max_wait_ms=0.0))
|
||||
sched.add_request(_make_request("a"))
|
||||
sched.add_request(_make_request("b"))
|
||||
|
||||
sched.finish_requests("a", DiffusionRequestStatus.FINISHED_ABORTED)
|
||||
assert sched.pending_finished_request_ids() == {"a"}
|
||||
|
||||
sched.pop_request_state("a")
|
||||
assert sched.pending_finished_request_ids() == set()
|
||||
# The next wave still ships the id to the worker for its own cleanup.
|
||||
assert sched.schedule().finished_req_ids == {"a"}
|
||||
@@ -0,0 +1,53 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Unit tests for the device step of the diffusion pause barrier."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm_omni.diffusion.worker.diffusion_worker import DiffusionWorker
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
def _make_worker(runner: object) -> DiffusionWorker:
|
||||
worker = object.__new__(DiffusionWorker)
|
||||
worker.model_runner = runner
|
||||
worker.rank = 0
|
||||
return worker
|
||||
|
||||
|
||||
def test_synchronize_device_waits_for_prefetch_before_device_sync(mocker):
|
||||
platform = mocker.patch("vllm_omni.diffusion.worker.diffusion_worker.current_omni_platform")
|
||||
order: list = []
|
||||
manager = MagicMock()
|
||||
manager.wait_prefetch.side_effect = lambda timeout: order.append(("prefetch", timeout)) or True
|
||||
platform.synchronize.side_effect = lambda: order.append("sync")
|
||||
worker = _make_worker(SimpleNamespace(kv_transfer_manager=manager))
|
||||
|
||||
worker.synchronize_device(timeout=2.5)
|
||||
|
||||
assert order == [("prefetch", 2.5), "sync"]
|
||||
|
||||
|
||||
def test_synchronize_device_fails_when_prefetch_is_still_outstanding(mocker):
|
||||
platform = mocker.patch("vllm_omni.diffusion.worker.diffusion_worker.current_omni_platform")
|
||||
manager = MagicMock()
|
||||
manager.wait_prefetch.return_value = False
|
||||
worker = _make_worker(SimpleNamespace(kv_transfer_manager=manager))
|
||||
|
||||
with pytest.raises(TimeoutError, match="prefetch"):
|
||||
worker.synchronize_device(timeout=0.01)
|
||||
|
||||
platform.synchronize.assert_not_called()
|
||||
|
||||
|
||||
def test_synchronize_device_without_transfer_manager_only_syncs(mocker):
|
||||
platform = mocker.patch("vllm_omni.diffusion.worker.diffusion_worker.current_omni_platform")
|
||||
worker = _make_worker(SimpleNamespace(kv_transfer_manager=None))
|
||||
|
||||
worker.synchronize_device(timeout=None)
|
||||
|
||||
platform.synchronize.assert_called_once_with()
|
||||
@@ -5,6 +5,7 @@ mock connector, dedup, per-call sender_info isolation, role classification, and
|
||||
miss/abort paths. GPU H2D and D2D paths need CUDA (integration tests).
|
||||
"""
|
||||
|
||||
import threading
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
@@ -354,3 +355,41 @@ def test_consume_then_apply_attaches_payload():
|
||||
receiver._record_stream_for_prefetched(data)
|
||||
receiver.apply_kv_cache_to_request(req, data)
|
||||
assert req.past_key_values is not None
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# wait_prefetch: the pause barrier's view of outstanding background loads
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
def test_wait_prefetch_is_true_when_nothing_outstanding():
|
||||
_, receiver, _ = _make_sender_receiver()
|
||||
assert receiver.wait_prefetch(timeout=0.01) is True
|
||||
|
||||
|
||||
def test_wait_prefetch_is_true_when_prefetch_disabled():
|
||||
_, receiver, _ = _make_sender_receiver(async_prefetch=False)
|
||||
assert receiver.wait_prefetch(timeout=0.01) is True
|
||||
|
||||
|
||||
def test_wait_prefetch_reports_a_running_prefetch_and_keeps_its_payload():
|
||||
sender, receiver, connector = _make_sender_receiver()
|
||||
_seed_payload(sender, "rid-w")
|
||||
gate = threading.Event()
|
||||
real_get = connector.get
|
||||
|
||||
def slow_get(*args, **kwargs):
|
||||
gate.wait(timeout=5.0)
|
||||
return real_get(*args, **kwargs)
|
||||
|
||||
connector.get = slow_get
|
||||
receiver.start_prefetch({"request_id": "rid-w", "kv_sender_info": _SENDER_INFO})
|
||||
try:
|
||||
assert receiver.wait_prefetch(timeout=0.05) is False
|
||||
gate.set()
|
||||
assert receiver.wait_prefetch(timeout=5.0) is True
|
||||
data, _ = receiver.consume_prefetched_kv(_req("rid-w"))
|
||||
assert data is not None
|
||||
finally:
|
||||
gate.set()
|
||||
receiver.shutdown_prefetch()
|
||||
@@ -32,7 +32,6 @@ 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 import skip_if_gated_repo_inaccessible
|
||||
from tests.helpers.mark import hardware_test
|
||||
|
||||
OFFICIAL_REPOSITORY = "https://github.com/Lightricks/LTX-2.git"
|
||||
@@ -303,32 +302,6 @@ def _resolve_ltx25_image() -> Path:
|
||||
)
|
||||
|
||||
|
||||
def _require_ltx25_model_access() -> None:
|
||||
configured_omni_model = os.environ.get("VLLM_TEST_LTX25_MODEL")
|
||||
if not (configured_omni_model and Path(configured_omni_model).exists()):
|
||||
omni_model = configured_omni_model or LTX25_OMNI_MODEL_ID
|
||||
omni_revision = os.environ.get("VLLM_TEST_LTX25_MODEL_REVISION")
|
||||
if omni_revision is None and omni_model == LTX25_OMNI_MODEL_ID:
|
||||
omni_revision = LTX25_OMNI_MODEL_REVISION
|
||||
skip_if_gated_repo_inaccessible(
|
||||
omni_model,
|
||||
revision=omni_revision,
|
||||
filename="model_index.json",
|
||||
)
|
||||
|
||||
configured_official_model = os.environ.get("VLLM_TEST_LTX25_OFFICIAL_MODEL")
|
||||
if not (configured_official_model and Path(configured_official_model).exists()):
|
||||
official_model = configured_official_model or LTX25_OFFICIAL_MODEL_ID
|
||||
official_revision = os.environ.get("VLLM_TEST_LTX25_OFFICIAL_MODEL_REVISION")
|
||||
if official_revision is None and official_model == LTX25_OFFICIAL_MODEL_ID:
|
||||
official_revision = LTX25_OFFICIAL_MODEL_REVISION
|
||||
skip_if_gated_repo_inaccessible(
|
||||
official_model,
|
||||
revision=official_revision,
|
||||
filename=LTX25_OFFICIAL_COMMON_FILES["text_encoder"],
|
||||
)
|
||||
|
||||
|
||||
def _ltx25_request(image: Path | None = None) -> dict[str, object]:
|
||||
request: dict[str, object] = {
|
||||
"prompt": LTX25_PROMPT,
|
||||
@@ -475,7 +448,6 @@ def _assert_strict_similarity(
|
||||
@pytest.mark.parametrize("task", ["t2v", "i2v"])
|
||||
def test_ltx25_distilled_two_stage_matches_official(accuracy_artifact_root: Path, task: str) -> None:
|
||||
"""Compare Omni with official canonical DiffVAE and matching connector weights."""
|
||||
_require_ltx25_model_access()
|
||||
artifact_parent = accuracy_artifact_root / "ltx_official"
|
||||
output_root = reset_artifact_dir(artifact_parent / f"ltx2_5_distilled_{task}")
|
||||
official_root, official_revision = _ltx25_official_source(artifact_parent)
|
||||
@@ -600,7 +572,6 @@ def test_ltx25_distilled_two_stage_matches_official(accuracy_artifact_root: Path
|
||||
@pytest.mark.parametrize("pipeline_mode", ["full_one_stage", "full_two_stage"])
|
||||
def test_ltx25_full_matches_official(accuracy_artifact_root: Path, task: str, pipeline_mode: str) -> None:
|
||||
"""Compare raw official Full/SFT and DiffVAE weights with Omni."""
|
||||
_require_ltx25_model_access()
|
||||
artifact_parent = accuracy_artifact_root / "ltx_official"
|
||||
output_root = reset_artifact_dir(artifact_parent / f"ltx2_5_{pipeline_mode}_{task}")
|
||||
model_class_name = {
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Minimal mock of vLLM-Omni's ``/v1/videos`` API for e2e tests.
|
||||
|
||||
Records every received multipart field to ``MOCK_STATE_FILE`` (JSON) so a test
|
||||
can assert exactly what the client serialized, and returns a synthetic MP4.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import uuid
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.responses import Response
|
||||
from starlette.datastructures import UploadFile
|
||||
|
||||
app = FastAPI()
|
||||
_JOBS: dict[str, dict] = {}
|
||||
_STATE_FILE = os.environ.get("MOCK_STATE_FILE")
|
||||
|
||||
|
||||
def _record(fields: dict) -> None:
|
||||
if _STATE_FILE:
|
||||
with open(_STATE_FILE, "w") as f:
|
||||
json.dump(fields, f)
|
||||
|
||||
|
||||
def _synthetic_mp4() -> bytes:
|
||||
return subprocess.run(
|
||||
[
|
||||
"ffmpeg",
|
||||
"-hide_banner",
|
||||
"-loglevel",
|
||||
"error",
|
||||
"-y",
|
||||
"-f",
|
||||
"lavfi",
|
||||
"-i",
|
||||
"testsrc2=size=320x240:rate=24:duration=1",
|
||||
"-f",
|
||||
"lavfi",
|
||||
"-i",
|
||||
"sine=frequency=440:sample_rate=32000:duration=1",
|
||||
"-map",
|
||||
"0:v",
|
||||
"-map",
|
||||
"1:a",
|
||||
"-shortest",
|
||||
"-c:v",
|
||||
"libx264",
|
||||
"-pix_fmt",
|
||||
"yuv420p",
|
||||
"-c:a",
|
||||
"aac",
|
||||
"-ar",
|
||||
"32000",
|
||||
"-ac",
|
||||
"2",
|
||||
"-movflags",
|
||||
"frag_keyframe+empty_moov",
|
||||
"-f",
|
||||
"mp4",
|
||||
"pipe:1",
|
||||
],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
).stdout
|
||||
|
||||
|
||||
@app.post("/v1/videos")
|
||||
async def create_video(request: Request):
|
||||
form = await request.form()
|
||||
fields = {}
|
||||
for key, value in form.items():
|
||||
if isinstance(value, UploadFile):
|
||||
data = await value.read()
|
||||
fields[key] = {
|
||||
"file": True,
|
||||
"size": len(data),
|
||||
"filename": value.filename,
|
||||
"content_type": value.content_type,
|
||||
}
|
||||
if value.content_type == "application/json":
|
||||
fields[key]["json"] = json.loads(data)
|
||||
else:
|
||||
fields[key] = str(value)
|
||||
_record(fields)
|
||||
|
||||
job_id = str(uuid.uuid4())
|
||||
_JOBS[job_id] = {"status": "queued"}
|
||||
return {"id": job_id, "status": "queued"}
|
||||
|
||||
|
||||
@app.get("/v1/videos/{job_id}")
|
||||
async def get_video(job_id: str):
|
||||
if job_id not in _JOBS:
|
||||
return {"status": "failed", "error": "unknown job"}
|
||||
return {"id": job_id, "status": "completed"}
|
||||
|
||||
|
||||
@app.get("/v1/videos/{job_id}/content")
|
||||
async def get_video_content(job_id: str):
|
||||
if job_id not in _JOBS:
|
||||
return Response(status_code=404)
|
||||
mp4 = await asyncio.to_thread(_synthetic_mp4)
|
||||
return Response(content=mp4, media_type="video/mp4")
|
||||
|
||||
|
||||
@app.delete("/v1/videos/{job_id}")
|
||||
async def delete_video(job_id: str):
|
||||
_JOBS.pop(job_id, None)
|
||||
return {"deleted": True}
|
||||
@@ -0,0 +1,80 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Unit tests for latent-mask serialization helpers."""
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from comfyui_vllm_omni.utils.latent_mask import scalar_mask_to_json, video_mask_to_grid_json
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
def test_scalar_mask_to_json():
|
||||
assert scalar_mask_to_json(0.5) == "0.5"
|
||||
assert scalar_mask_to_json(1.0) == "1.0"
|
||||
with pytest.raises(ValueError):
|
||||
scalar_mask_to_json(1.5)
|
||||
with pytest.raises(ValueError):
|
||||
scalar_mask_to_json(-0.1)
|
||||
|
||||
|
||||
def test_video_mask_grid_shape():
|
||||
mask = torch.zeros(256, 448)
|
||||
grid = json.loads(video_mask_to_grid_json(mask, width=448, height=256, num_frames=107))
|
||||
assert len(grid) == 2 + 5 * ((107 - 5) // 17)
|
||||
assert len(grid[0]) == 256 // 16
|
||||
assert len(grid[0][0]) == 448 // 16
|
||||
|
||||
|
||||
def test_video_mask_grid_shape_non_aligned_frames():
|
||||
# 96 snaps up to 107 (17n+5), so Tv == 32, matching the server.
|
||||
grid = json.loads(video_mask_to_grid_json(torch.zeros(256, 448), width=448, height=256, num_frames=96))
|
||||
assert len(grid) == 32
|
||||
|
||||
|
||||
def test_video_mask_grid_shape_short_clip():
|
||||
# num_frames <= 5 -> Tv == 2.
|
||||
grid = json.loads(video_mask_to_grid_json(torch.zeros(64, 64), width=64, height=64, num_frames=1))
|
||||
assert len(grid) == 2
|
||||
|
||||
|
||||
def test_video_mask_grid_shape_unaligned_width():
|
||||
# width=500 floors to 480 (multiple of 32) -> gw == 30, not 31.
|
||||
grid = json.loads(video_mask_to_grid_json(torch.zeros(64, 64), width=500, height=256, num_frames=22))
|
||||
assert len(grid[0][0]) == 30
|
||||
|
||||
|
||||
def test_video_mask_3d_input():
|
||||
grid = json.loads(video_mask_to_grid_json(torch.ones(1, 256, 448), width=448, height=256, num_frames=107))
|
||||
assert grid[0][0][0] == 1.0
|
||||
|
||||
|
||||
def test_video_mask_temporal():
|
||||
# 3D mask: first half 0 (preserve), second half 1 (regenerate).
|
||||
mask = torch.zeros(7, 64, 64)
|
||||
mask[4:] = 1.0
|
||||
grid = json.loads(video_mask_to_grid_json(mask, width=64, height=64, num_frames=22))
|
||||
assert len(grid) == 7
|
||||
assert all(v == 0.0 for row in grid[0] for v in row)
|
||||
assert all(v == 1.0 for row in grid[-1] for v in row)
|
||||
|
||||
|
||||
def test_video_mask_temporal_resize():
|
||||
# 2 temporal slices resize to tv == 7.
|
||||
mask = torch.zeros(2, 64, 64)
|
||||
mask[1] = 1.0
|
||||
grid = json.loads(video_mask_to_grid_json(mask, width=64, height=64, num_frames=22))
|
||||
assert len(grid) == 7
|
||||
|
||||
|
||||
def test_video_mask_uniform_preserved():
|
||||
grid = json.loads(video_mask_to_grid_json(torch.full((64, 64), 0.5), width=64, height=64, num_frames=107))
|
||||
assert all(v == 0.5 for row in grid for cell in row for v in cell)
|
||||
|
||||
|
||||
def test_video_mask_values_in_range():
|
||||
grid = json.loads(video_mask_to_grid_json(torch.rand(128, 128), width=128, height=128, num_frames=22))
|
||||
assert all(0.0 <= v <= 1.0 for row in grid for cell in row for v in cell)
|
||||
@@ -0,0 +1,99 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""End-to-end test for latent-mask editing serialization.
|
||||
|
||||
Exercises ``VLLMOmniClient.generate_video`` with a ``latent_edit`` payload
|
||||
against a mock ``/v1/videos`` server and asserts the multipart fields the
|
||||
client produced. Runs on CPU: the ComfyUI ``comfy_api`` / ``comfy_extras``
|
||||
modules are mocked by this directory's ``conftest.py``.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from comfy_api.input import VideoInput
|
||||
from comfyui_vllm_omni.utils.api_client import VLLMOmniClient
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
_TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
|
||||
def _free_port() -> int:
|
||||
with socket.socket() as s:
|
||||
s.bind(("127.0.0.1", 0))
|
||||
return s.getsockname()[1]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_server(tmp_path):
|
||||
port = _free_port()
|
||||
state_file = tmp_path / "state.json"
|
||||
env = dict(os.environ, MOCK_STATE_FILE=str(state_file))
|
||||
proc = subprocess.Popen(
|
||||
[sys.executable, "-m", "uvicorn", "mock_videos_server:app", "--host", "127.0.0.1", "--port", str(port)],
|
||||
cwd=_TESTS_DIR,
|
||||
env=env,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
try:
|
||||
deadline = time.time() + 30
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
with socket.create_connection(("127.0.0.1", port), timeout=1):
|
||||
break
|
||||
except OSError:
|
||||
time.sleep(0.2)
|
||||
yield f"http://127.0.0.1:{port}/v1", state_file
|
||||
finally:
|
||||
proc.terminate()
|
||||
proc.wait(timeout=10)
|
||||
|
||||
|
||||
def test_latent_edit_serialization(mock_server):
|
||||
base_url, state_file = mock_server
|
||||
|
||||
# A non-trivial video mask requires a source video. The mocked VideoInput
|
||||
# only needs to provide ``save_to`` for the client's multipart upload.
|
||||
source_video = VideoInput(b"mock_source_video")
|
||||
mask = torch.zeros(1, 120, 160)
|
||||
latent_edit = {"source_video": source_video, "video_mask": mask, "audio_mask": 0.5}
|
||||
|
||||
async def run():
|
||||
client = VLLMOmniClient(base_url)
|
||||
return await client.generate_video(
|
||||
model="MiniMaxAI/MiniMax-H3",
|
||||
prompt="restyle the clip",
|
||||
width=160,
|
||||
height=120,
|
||||
num_frames=22,
|
||||
fps=24,
|
||||
latent_edit=latent_edit,
|
||||
)
|
||||
|
||||
out = asyncio.run(run())
|
||||
assert out is not None
|
||||
|
||||
with open(state_file) as f:
|
||||
fields = json.load(f)
|
||||
|
||||
assert fields["source_video"]["file"] is True
|
||||
assert fields["source_video"]["content_type"] == "video/mp4"
|
||||
for name in ("video_noise_mask", "audio_noise_mask"):
|
||||
assert fields[name]["file"] is True
|
||||
assert fields[name]["content_type"] == "application/json"
|
||||
assert fields["audio_noise_mask"]["json"] == 0.5
|
||||
|
||||
video_mask = fields["video_noise_mask"]["json"]
|
||||
assert len(video_mask) == 7 # num_frames=22 aligns to 22 (17n+5) -> Tv = 7
|
||||
assert len(video_mask[0]) == 6 # height 120 floors to 96 (multiple of 32) -> gh 6
|
||||
assert len(video_mask[0][0]) == 10 # width 160 -> gw 10
|
||||
@@ -0,0 +1,183 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""
|
||||
Lifecycle test for ``AsyncOmni.pause_generation(mode="keep")`` on a diffusion stage.
|
||||
|
||||
Per round, request A is started, request B is queued behind it, and the pause
|
||||
is issued while A is still running. The pause must return only after A has
|
||||
been delivered, B must stay queued through ``sleep`` / ``wake_up``, and B may
|
||||
start only after ``resume_generation``.
|
||||
|
||||
A second test follows the order the docs recommend for a weight update: sleep
|
||||
is issued as soon as the pause returns, without awaiting the request that was
|
||||
running, which must still be delivered intact.
|
||||
|
||||
Both single-GPU executor backends are covered explicitly: ``uni`` (in-process
|
||||
worker) and ``mp`` (worker process with the asynchronous D2H output thread).
|
||||
|
||||
Usage:
|
||||
pytest tests/e2e/features/custom_pipeline/test_diffusion_pause_keep.py -v -s
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from contextlib import ExitStack
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.helpers.mark import hardware_test
|
||||
from vllm_omni.diffusion.data import is_diffusion_request_started_output
|
||||
from vllm_omni.entrypoints.async_omni import AsyncOmni
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
|
||||
|
||||
MODEL = "tiny-random/Qwen-Image"
|
||||
CUSTOM_PIPELINE_CLASS = "tests.e2e.features.helpers.custom_pipeline.QwenImagePipelineWithLogProbForTest"
|
||||
WORKER_EXTENSION_CLASS = "tests.e2e.features.helpers.custom_pipeline.vLLMOmniColocateWorkerExtensionForTest"
|
||||
|
||||
# CI runs a couple of rounds; set PAUSE_KEEP_ROUNDS=10 for a soak run.
|
||||
ROUNDS = int(os.environ.get("PAUSE_KEEP_ROUNDS", "2"))
|
||||
# Enough denoising steps that the pause lands while A is still executing.
|
||||
NUM_INFERENCE_STEPS = 40
|
||||
|
||||
|
||||
def _sampling_params() -> OmniDiffusionSamplingParams:
|
||||
return OmniDiffusionSamplingParams(
|
||||
num_inference_steps=NUM_INFERENCE_STEPS,
|
||||
guidance_scale=0.0,
|
||||
height=256,
|
||||
width=256,
|
||||
seed=42,
|
||||
emit_request_lifecycle=True,
|
||||
)
|
||||
|
||||
|
||||
async def _generate(engine: AsyncOmni, request_id: str, events: dict[str, dict[str, float]]):
|
||||
final = None
|
||||
async for output in engine.generate(
|
||||
prompt={"prompt_ids": list(range(50))},
|
||||
request_id=request_id,
|
||||
sampling_params_list=[_sampling_params()],
|
||||
output_modalities=["image"],
|
||||
):
|
||||
if is_diffusion_request_started_output(output):
|
||||
events[request_id]["started"] = time.monotonic()
|
||||
continue
|
||||
final = output
|
||||
events[request_id]["finished"] = time.monotonic()
|
||||
return final
|
||||
|
||||
|
||||
async def _wait_for(predicate, timeout: float = 30.0) -> None:
|
||||
deadline = time.monotonic() + timeout
|
||||
while not predicate():
|
||||
assert time.monotonic() < deadline, "condition not reached in time"
|
||||
await asyncio.sleep(0.005)
|
||||
|
||||
|
||||
async def _pause_round(engine: AsyncOmni, events: dict[str, dict[str, float]], round_index: int) -> float:
|
||||
"""A runs, B queues, keep-pause lands while A runs; B starts only after resume.
|
||||
|
||||
Returns the pause latency.
|
||||
"""
|
||||
a_id, b_id = f"a{round_index}", f"b{round_index}"
|
||||
a = asyncio.create_task(_generate(engine, a_id, events))
|
||||
await _wait_for(lambda: "started" in events[a_id])
|
||||
b = asyncio.create_task(_generate(engine, b_id, events))
|
||||
await asyncio.sleep(0.05)
|
||||
|
||||
assert not a.done(), "A finished before the pause was issued; raise NUM_INFERENCE_STEPS"
|
||||
pause_start = time.monotonic()
|
||||
await engine.pause_generation(mode="keep", clear_cache=False)
|
||||
pause_latency = time.monotonic() - pause_start
|
||||
assert await engine.is_paused()
|
||||
|
||||
a_output = await asyncio.wait_for(a, 60.0)
|
||||
assert a_output.images, "A must be delivered, not aborted, by a keep pause"
|
||||
assert "started" not in events[b_id], "B must not start while paused"
|
||||
|
||||
# Control RPCs and the sleep cycle stay available on the paused stage.
|
||||
assert await engine.list_loras() == []
|
||||
await engine.sleep(level=1)
|
||||
assert await engine.is_sleeping()
|
||||
await engine.wake_up()
|
||||
assert not await engine.is_sleeping()
|
||||
assert await engine.is_paused()
|
||||
assert not b.done() and "started" not in events[b_id]
|
||||
|
||||
resume_at = time.monotonic()
|
||||
await engine.resume_generation()
|
||||
b_output = await asyncio.wait_for(b, 60.0)
|
||||
assert b_output.images, "B must run after resume"
|
||||
assert events[b_id]["started"] >= resume_at
|
||||
return pause_latency
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
@pytest.mark.diffusion
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("backend", ["uni", "mp"])
|
||||
async def test_keep_pause_sleep_wake_resume_lifecycle(backend: str):
|
||||
with ExitStack() as after:
|
||||
engine = AsyncOmni(
|
||||
model=MODEL,
|
||||
custom_pipeline_args={"pipeline_class": CUSTOM_PIPELINE_CLASS},
|
||||
worker_extension_cls=WORKER_EXTENSION_CLASS,
|
||||
enforce_eager=True,
|
||||
enable_sleep_mode=True,
|
||||
distributed_executor_backend=backend,
|
||||
)
|
||||
after.callback(engine.shutdown)
|
||||
events: dict[str, dict[str, float]] = defaultdict(dict)
|
||||
|
||||
pause_latencies = [await _pause_round(engine, events, round_index) for round_index in range(ROUNDS)]
|
||||
|
||||
assert not engine.request_states, "every request must be finalized"
|
||||
print(
|
||||
f"[{backend}] rounds={ROUNDS} steps={NUM_INFERENCE_STEPS} "
|
||||
f"pause_latency_s min/median/max="
|
||||
f"{min(pause_latencies):.3f}/{sorted(pause_latencies)[ROUNDS // 2]:.3f}/{max(pause_latencies):.3f}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
@pytest.mark.diffusion
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("backend", ["uni", "mp"])
|
||||
async def test_sleep_right_after_keep_pause_keeps_the_running_batch(backend: str):
|
||||
"""The documented weight-update order: sleep is issued as soon as the pause
|
||||
returns, with the request that was running still un-awaited.
|
||||
"""
|
||||
with ExitStack() as after:
|
||||
engine = AsyncOmni(
|
||||
model=MODEL,
|
||||
custom_pipeline_args={"pipeline_class": CUSTOM_PIPELINE_CLASS},
|
||||
worker_extension_cls=WORKER_EXTENSION_CLASS,
|
||||
enforce_eager=True,
|
||||
enable_sleep_mode=True,
|
||||
distributed_executor_backend=backend,
|
||||
)
|
||||
after.callback(engine.shutdown)
|
||||
events: dict[str, dict[str, float]] = defaultdict(dict)
|
||||
|
||||
a = asyncio.create_task(_generate(engine, "a", events))
|
||||
await _wait_for(lambda: "started" in events["a"])
|
||||
await asyncio.sleep(0.05)
|
||||
assert not a.done(), "A finished before the pause was issued; raise NUM_INFERENCE_STEPS"
|
||||
|
||||
await engine.pause_generation(mode="keep", clear_cache=False)
|
||||
await engine.sleep(level=1)
|
||||
|
||||
a_output = await asyncio.wait_for(a, 60.0)
|
||||
assert a_output.images, "A must survive a sleep issued right after the pause ACK"
|
||||
|
||||
await engine.wake_up()
|
||||
await engine.resume_generation()
|
||||
b_output = await asyncio.wait_for(_generate(engine, "b", events), 120.0)
|
||||
assert b_output.images, "the stage must generate again after wake and resume"
|
||||
@@ -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
|
||||
|
||||
"""Test doubles for custom-pipeline E2E and RLHF integration.
|
||||
|
||||
@@ -290,6 +290,36 @@ class vLLMOmniColocateWorkerExtensionForTest(CustomPipelineWorkerExtension):
|
||||
"""Return a stable identifier for assertions in unit tests."""
|
||||
return "vllm-omni-colocate-worker-extension-for-test"
|
||||
|
||||
def start_counting_synchronize_device(self) -> bool:
|
||||
"""Count pause-barrier runs on this rank (test-only)."""
|
||||
self._synchronize_device_calls = 0
|
||||
inner = type(self).synchronize_device
|
||||
|
||||
def _counted(timeout=None):
|
||||
self._synchronize_device_calls += 1
|
||||
return inner(self, timeout=timeout)
|
||||
|
||||
self.synchronize_device = _counted
|
||||
return True
|
||||
|
||||
def synchronize_device_seen(self) -> bool:
|
||||
"""True from every rank only when each rank ran the barrier at least once."""
|
||||
return getattr(self, "_synchronize_device_calls", 0) > 0
|
||||
|
||||
def set_synchronize_device_failure(self, rank: int, fail: bool) -> bool:
|
||||
"""Make (or stop making) the pause barrier fail on ``rank`` (test-only)."""
|
||||
if self.rank != rank:
|
||||
return True
|
||||
if fail:
|
||||
|
||||
def _fail(timeout=None):
|
||||
raise RuntimeError(f"injected barrier failure on rank {rank}")
|
||||
|
||||
self.synchronize_device = _fail
|
||||
else:
|
||||
self.__dict__.pop("synchronize_device", None)
|
||||
return True
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Pipeline layer
|
||||
|
||||
@@ -558,7 +558,7 @@ def test_shared_script_ar_path_reaches_generation(
|
||||
# safe against MODEL_NAME's base checkpoint missing the Instruct-only
|
||||
# <img_ratio_33>/<img_ratio_36> tokens. Wiring it here exercises the
|
||||
# real production path (get_ar_tokenizer_validator via the registry),
|
||||
# not just the isolated fake-tokenizer coverage in test_prompt_utils.py
|
||||
# not just the isolated fake-tokenizer coverage in test_hunyuan_image3_prompt_utils.py
|
||||
# / test_shared_script_ar_integration.py.
|
||||
validate_tokenizer=get_ar_tokenizer_validator(model_class_name),
|
||||
)
|
||||
|
||||
@@ -25,9 +25,11 @@ import os
|
||||
from io import BytesIO
|
||||
|
||||
import pytest
|
||||
from PIL import Image
|
||||
from vllm.assets.image import ImageAsset
|
||||
|
||||
from tests.helpers.mark import hardware_test
|
||||
from tests.helpers.media import generate_synthetic_image
|
||||
from tests.helpers.runtime import OmniServerParams
|
||||
from tests.helpers.stage_config import get_deploy_config_path
|
||||
|
||||
@@ -120,3 +122,55 @@ def test_bagel_img2img_online(omni_server, online_client) -> None:
|
||||
}
|
||||
|
||||
online_client.send_diffusion_request(request_config)
|
||||
|
||||
|
||||
EDIT_SOURCE_SIZE = (1280, 720)
|
||||
EDIT_REQUESTED_SIZE = "1024x1024"
|
||||
|
||||
|
||||
def _edit_source_jpeg() -> tuple[str, bytes, str]:
|
||||
synthetic = generate_synthetic_image(*EDIT_SOURCE_SIZE, seed=7287)
|
||||
return ("source.jpg", base64.b64decode(synthetic["base64"]), "image/jpeg")
|
||||
|
||||
|
||||
def _build_edit_request(size: str) -> dict:
|
||||
return {
|
||||
"files": [("image", _edit_source_jpeg())],
|
||||
"data": {
|
||||
"prompt": IMG2IMG_PROMPT,
|
||||
"size": size,
|
||||
"num_inference_steps": 2,
|
||||
"seed": 42,
|
||||
"response_format": "b64_json",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.slow
|
||||
@pytest.mark.diffusion
|
||||
@hardware_test(res={"cuda": "H100"})
|
||||
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
|
||||
def test_bagel_image_edit_honors_explicit_size_two_stage(omni_server, online_client) -> None:
|
||||
"""An explicit ``size`` wins over the AR stage's source-derived KV image shape (#7283)."""
|
||||
(response,) = online_client.send_images_edits_http_request(_build_edit_request(EDIT_REQUESTED_SIZE))
|
||||
|
||||
payload = response.json_body
|
||||
assert isinstance(payload, dict)
|
||||
assert payload["size"] == EDIT_REQUESTED_SIZE
|
||||
image = Image.open(BytesIO(base64.b64decode(payload["data"][0]["b64_json"])))
|
||||
assert image.size == (1024, 1024)
|
||||
|
||||
|
||||
@pytest.mark.slow
|
||||
@pytest.mark.diffusion
|
||||
@hardware_test(res={"cuda": "H100"})
|
||||
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
|
||||
def test_bagel_image_edit_floors_unaligned_size_two_stage(omni_server, online_client) -> None:
|
||||
"""A side that is not a multiple of the latent stride is floored to one (1000x700 -> 992x688)."""
|
||||
(response,) = online_client.send_images_edits_http_request(_build_edit_request("1000x700"))
|
||||
|
||||
payload = response.json_body
|
||||
assert isinstance(payload, dict)
|
||||
assert payload["size"] == "992x688"
|
||||
image = Image.open(BytesIO(base64.b64decode(payload["data"][0]["b64_json"])))
|
||||
assert image.size == (992, 688)
|
||||
@@ -1,7 +1,19 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Online serving smoke coverage for the dense LingBot-Video checkpoint."""
|
||||
"""
|
||||
Online serving smoke for ``robbyant/lingbot-video-dense-1.3b``.
|
||||
|
||||
``test_text_to_image_001`` and ``test_video_generation_modes_001`` are the
|
||||
baseline T2I / T2V+TI2V cases (``core_model`` + ``advanced_model``) shared by
|
||||
ready (L2) and merge (L3). Heavier MoE and World coverage stays on
|
||||
``full_model`` in ``test_lingbot_video_moe.py`` / ``test_lingbot_world_v2.py``.
|
||||
|
||||
From ``tests/``::
|
||||
|
||||
pytest -s -v e2e/online_serving/test_lingbot_video.py -m "core_model and diffusion" --run-level=core_model
|
||||
pytest -s -v e2e/online_serving/test_lingbot_video.py -m "advanced_model and diffusion" --run-level=advanced_model
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
@@ -41,7 +53,8 @@ def _get_diffusion_feature_cases(model: str):
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.full_model
|
||||
@pytest.mark.core_model
|
||||
@pytest.mark.advanced_model
|
||||
@pytest.mark.diffusion
|
||||
@pytest.mark.parametrize("omni_server", _get_diffusion_feature_cases(MODEL), indirect=True)
|
||||
def test_text_to_image_001(omni_server: OmniServer, openai_client: OpenAIClientHandler) -> None:
|
||||
@@ -63,7 +76,8 @@ def test_text_to_image_001(omni_server: OmniServer, openai_client: OpenAIClientH
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.full_model
|
||||
@pytest.mark.core_model
|
||||
@pytest.mark.advanced_model
|
||||
@pytest.mark.diffusion
|
||||
@pytest.mark.parametrize("omni_server", _get_diffusion_feature_cases(MODEL), indirect=True)
|
||||
def test_video_generation_modes_001(omni_server: OmniServer, openai_client: OpenAIClientHandler) -> None:
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
"""
|
||||
L4 expansion coverage for ``robbyant/lingbot-video-dense-1.3b``.
|
||||
|
||||
This file remains dense-only. Basic T2I/T2V/TI2V serving for both dense and MoE
|
||||
checkpoints is covered by ``test_lingbot_video.py`` and
|
||||
``test_lingbot_video_moe.py``. Distributed feature rows belong in follow-up
|
||||
This file remains dense-only. Baseline T2I/T2V/TI2V for the dense checkpoint
|
||||
lives in ``test_lingbot_video.py`` (L2/L3). MoE smoke stays in
|
||||
``test_lingbot_video_moe.py`` (L4). Distributed feature rows belong in follow-up
|
||||
PRs.
|
||||
"""
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@ import os
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.helpers import skip_if_gated_repo_inaccessible
|
||||
from tests.helpers.mark import hardware_marks
|
||||
from tests.helpers.media import generate_synthetic_image
|
||||
from tests.helpers.runtime import OmniServer, OmniServerParams, OpenAIClientHandler
|
||||
@@ -24,16 +23,6 @@ pytestmark = [pytest.mark.diffusion, pytest.mark.slow]
|
||||
SINGLE_CARD_MARKS = hardware_marks(res={"cuda": "H100"})
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def require_ltx25_model_access() -> None:
|
||||
if not os.path.isdir(MODEL):
|
||||
skip_if_gated_repo_inaccessible(
|
||||
MODEL,
|
||||
revision=MODEL_REVISION or None,
|
||||
filename="model_index.json",
|
||||
)
|
||||
|
||||
|
||||
def _server(model_class_name: str) -> OmniServerParams:
|
||||
return OmniServerParams(
|
||||
model=MODEL,
|
||||
|
||||
@@ -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 online serving test for Stable Audio Open text-to-audio diffusion.
|
||||
|
||||
@@ -11,7 +11,6 @@ import os
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.helpers import skip_if_gated_repo_inaccessible
|
||||
from tests.helpers.mark import hardware_marks
|
||||
from tests.helpers.runtime import OmniServer, OmniServerParams, OpenAIClientHandler
|
||||
|
||||
@@ -32,17 +31,10 @@ def _stable_audio_server_cases(model: str):
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def _require_stable_audio_access() -> None:
|
||||
"""Skip cleanly (before the server boots) if the gated checkpoint is inaccessible."""
|
||||
skip_if_gated_repo_inaccessible(STABLE_AUDIO_TEST_MODEL)
|
||||
|
||||
|
||||
@pytest.mark.slow
|
||||
@pytest.mark.diffusion
|
||||
@pytest.mark.parametrize("omni_server", _stable_audio_server_cases(STABLE_AUDIO_TEST_MODEL), indirect=True)
|
||||
def test_stable_audio_t2a_online(
|
||||
_require_stable_audio_access: None,
|
||||
omni_server: OmniServer,
|
||||
openai_client: OpenAIClientHandler,
|
||||
) -> None:
|
||||
|
||||
@@ -0,0 +1,725 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Public duplex hook: resumable defaults True; ephemeral ids when False."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from vllm.sampling_params import SamplingParams
|
||||
|
||||
from vllm_omni.engine.duplex.config import DuplexCapabilities
|
||||
from vllm_omni.engine.duplex.contracts import (
|
||||
DuplexFence,
|
||||
DuplexStageRequestContext,
|
||||
DuplexStageSubmission,
|
||||
duplex_ephemeral_stage_request_id,
|
||||
)
|
||||
from vllm_omni.engine.duplex.session.manager import DuplexSessionManager
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
def test_submission_resumable_default_preserves_minicpm() -> None:
|
||||
ctx = DuplexStageRequestContext(
|
||||
request_id="r",
|
||||
session_id="s",
|
||||
fence=DuplexFence("s"),
|
||||
stage_id=0,
|
||||
final_stage_id=2,
|
||||
config_generation=0,
|
||||
sampling_params=(SamplingParams(max_tokens=1),),
|
||||
)
|
||||
submission = DuplexStageSubmission(
|
||||
context=ctx,
|
||||
prompt={"prompt_token_ids": [1, 2]},
|
||||
already_submitted=False,
|
||||
)
|
||||
assert submission.resumable is True
|
||||
|
||||
|
||||
def test_stage_request_id_respects_resumable_flag() -> None:
|
||||
fence = DuplexFence("sess", epoch=3, turn_id=9)
|
||||
resumable_id = DuplexSessionManager.stage_request_id(fence, stage_id=0, resumable=True)
|
||||
ephemeral_id = DuplexSessionManager.stage_request_id(fence, stage_id=0, resumable=False)
|
||||
assert ephemeral_id == duplex_ephemeral_stage_request_id(fence, stage_id=0)
|
||||
assert resumable_id != ephemeral_id
|
||||
assert ephemeral_id.endswith("stage0-turn9")
|
||||
from vllm_omni.engine.duplex.contracts import duplex_turn_id_from_request_id
|
||||
|
||||
assert duplex_turn_id_from_request_id(ephemeral_id) == 9
|
||||
assert duplex_turn_id_from_request_id(resumable_id) is None
|
||||
|
||||
|
||||
def test_capabilities_expose_concurrent_turn_requests_default_false() -> None:
|
||||
caps = DuplexCapabilities()
|
||||
assert caps.supports_concurrent_turn_requests is False
|
||||
assert caps.allows_video_without_audio() is False
|
||||
assert caps.required_input_modalities == frozenset({"audio"})
|
||||
assert caps.optional_input_modalities == frozenset({"video"})
|
||||
assert caps.supports_core_resumable_request is False
|
||||
payload = caps.as_dict()
|
||||
assert payload["supports_concurrent_turn_requests"] is False
|
||||
assert payload["required_input_modalities"] == ["audio"]
|
||||
assert payload["optional_input_modalities"] == ["video"]
|
||||
|
||||
|
||||
def test_next_commit_allowed_soft_opens_on_r4_release() -> None:
|
||||
from types import SimpleNamespace
|
||||
|
||||
from vllm_omni.engine.duplex.session import helpers
|
||||
|
||||
caps = DuplexCapabilities(supports_concurrent_turn_requests=True)
|
||||
session = SimpleNamespace(active_response_id="resp", capabilities=caps)
|
||||
tasks = SimpleNamespace(
|
||||
active_response_task=None,
|
||||
has_response_bound_append_tasks=lambda: False,
|
||||
)
|
||||
# Monkeypatch assistant_playback_active via response_in_progress path: active_response_id set.
|
||||
assert helpers.response_in_progress(session, tasks) is True
|
||||
assert helpers.next_commit_allowed(session, tasks, concurrent_turn_requests_released=False) is False
|
||||
assert helpers.next_commit_allowed(session, tasks, concurrent_turn_requests_released=True) is True
|
||||
|
||||
caps_off = DuplexCapabilities(supports_concurrent_turn_requests=False)
|
||||
session_off = SimpleNamespace(active_response_id="resp", capabilities=caps_off)
|
||||
assert helpers.next_commit_allowed(session_off, tasks, concurrent_turn_requests_released=True) is False
|
||||
|
||||
|
||||
def test_active_response_accepts_own_turn_when_concurrent_turn_requests() -> None:
|
||||
"""Approach A: each response owns its turn; draining TTS uses request→response map."""
|
||||
from vllm_omni.engine.duplex.config import DuplexCapabilities, DuplexSessionConfig
|
||||
from vllm_omni.engine.duplex.session.engine_session import DuplexEngineSession
|
||||
|
||||
session = DuplexEngineSession(
|
||||
session_id="s",
|
||||
config=DuplexSessionConfig(model="m", modalities=["text"]),
|
||||
capabilities=DuplexCapabilities(supports_concurrent_turn_requests=True),
|
||||
)
|
||||
session.begin_response(turn_id=3)
|
||||
assert session.active_response_accepts_model_turn(3)
|
||||
assert not session.active_response_accepts_model_turn(4)
|
||||
assert not session.active_response_accepts_model_turn(2)
|
||||
session.bind_draining_request("req-old", "resp-old")
|
||||
assert session.response_id_for_request("req-old") == "resp-old"
|
||||
assert session.is_draining_request("req-old")
|
||||
|
||||
# Ending the active response must not wipe older draining bindings.
|
||||
session.bind_draining_request("req-newer-tts", session.active_response_id or "resp-active")
|
||||
ended = session.active_response_id
|
||||
session.end_response(commit_text=False)
|
||||
assert session.is_draining_request("req-old")
|
||||
assert session.response_id_for_request("req-old") == "resp-old"
|
||||
assert not session.is_draining_request("req-newer-tts")
|
||||
session.clear_draining_for_response("resp-old")
|
||||
assert not session.is_draining_request("req-old")
|
||||
del ended
|
||||
|
||||
strict = DuplexEngineSession(
|
||||
session_id="s2",
|
||||
config=DuplexSessionConfig(model="m", modalities=["text"]),
|
||||
capabilities=DuplexCapabilities(supports_concurrent_turn_requests=False),
|
||||
)
|
||||
strict.begin_response(turn_id=3)
|
||||
assert strict.active_response_accepts_model_turn(3)
|
||||
assert not strict.active_response_accepts_model_turn(4)
|
||||
|
||||
|
||||
def test_draining_request_exempt_from_completed_turn_filter() -> None:
|
||||
"""Draining ownership must win over the model_turn_id < turn_id late-audio guard."""
|
||||
from vllm_omni.engine.duplex.config import DuplexCapabilities, DuplexSessionConfig
|
||||
from vllm_omni.engine.duplex.session.engine_session import DuplexEngineSession
|
||||
|
||||
session = DuplexEngineSession(
|
||||
session_id="s-drain",
|
||||
config=DuplexSessionConfig(model="m", modalities=["text", "audio"]),
|
||||
capabilities=DuplexCapabilities(supports_concurrent_turn_requests=True),
|
||||
)
|
||||
session.begin_response(turn_id=1)
|
||||
r1 = session.active_response_id
|
||||
assert r1 is not None
|
||||
session.bind_draining_request("req-r1-tts", r1)
|
||||
# Overlapping R2 becomes active, then finishes — must not wipe R1 draining.
|
||||
session.begin_response(turn_id=2)
|
||||
session.end_response(commit_text=False)
|
||||
session.turn_id = 2
|
||||
assert session.active_response_id is None
|
||||
assert session.is_draining_request("req-r1-tts")
|
||||
assert session.response_id_for_request("req-r1-tts") == r1
|
||||
draining_response_id = session.response_id_for_request("req-r1-tts")
|
||||
model_turn_id = 1
|
||||
drop = (
|
||||
draining_response_id is None
|
||||
and session.active_response_id is None
|
||||
and model_turn_id is not None
|
||||
and model_turn_id < session.turn_id
|
||||
)
|
||||
assert drop is False
|
||||
|
||||
|
||||
def test_ephemeral_turn_id_parser_accepts_stage_turn_ids() -> None:
|
||||
from vllm_omni.engine.duplex.contracts import duplex_turn_id_from_request_id
|
||||
|
||||
assert duplex_turn_id_from_request_id("duplex-s.x.e.0.r.stage0-turn12") == 12
|
||||
assert duplex_turn_id_from_request_id("duplex-s.x.e.0.r.stage2-turn3") == 3
|
||||
assert duplex_turn_id_from_request_id("duplex-s.x.e.0.r.stage0_t9") is None
|
||||
assert duplex_turn_id_from_request_id("duplex-s.x.e.0.r.stage0") is None
|
||||
|
||||
|
||||
def test_same_turn_request_ids_skip_other_turns_and_epochs() -> None:
|
||||
from vllm_omni.engine.duplex.contracts import duplex_same_turn_request_ids
|
||||
|
||||
stage3 = "duplex-s.x.e.0.r.stage3-turn4"
|
||||
found = duplex_same_turn_request_ids(
|
||||
stage3,
|
||||
[
|
||||
"duplex-s.x.e.0.r.stage0-turn4",
|
||||
"duplex-s.x.e.0.r.stage1-turn4",
|
||||
"duplex-s.x.e.0.r.stage2-turn4",
|
||||
stage3,
|
||||
"duplex-s.x.e.0.r.stage2-turn5",
|
||||
"duplex-s.x.e.1.r.stage0-turn4",
|
||||
],
|
||||
)
|
||||
assert found == [
|
||||
"duplex-s.x.e.0.r.stage0-turn4",
|
||||
"duplex-s.x.e.0.r.stage1-turn4",
|
||||
"duplex-s.x.e.0.r.stage2-turn4",
|
||||
]
|
||||
from vllm_omni.engine.duplex.contracts import duplex_session_id_from_request_id
|
||||
|
||||
fence_session = "sess id"
|
||||
import base64
|
||||
|
||||
encoded = base64.urlsafe_b64encode(fence_session.encode()).decode("ascii").rstrip("=")
|
||||
assert duplex_session_id_from_request_id(f"duplex-s.{encoded}.e.0.r.stage1-turn2") == fence_session
|
||||
assert duplex_session_id_from_request_id("not-a-request") is None
|
||||
|
||||
|
||||
def test_stale_keys_skip_already_draining_request_ids() -> None:
|
||||
"""Rebinding must not move an older draining Stage2/3 id onto the newer response."""
|
||||
from vllm_omni.engine.duplex.config import DuplexCapabilities, DuplexSessionConfig
|
||||
from vllm_omni.engine.duplex.session.engine_session import DuplexEngineSession
|
||||
|
||||
session = DuplexEngineSession(
|
||||
session_id="s-stale",
|
||||
config=DuplexSessionConfig(model="m", modalities=["text", "audio"]),
|
||||
capabilities=DuplexCapabilities(supports_concurrent_turn_requests=True),
|
||||
)
|
||||
session.begin_response(turn_id=1)
|
||||
r1 = session.active_response_id
|
||||
assert r1 is not None
|
||||
session.bind_draining_request("req-r1-talker", r1)
|
||||
session.begin_response(turn_id=2)
|
||||
r2 = session.active_response_id
|
||||
assert r2 is not None and r2 != r1
|
||||
# Simulate the concurrent-turn rebind loop: already-draining ids keep R1.
|
||||
for rid in ("req-r1-talker", "req-r2-talker"):
|
||||
if session.is_draining_request(rid):
|
||||
continue
|
||||
session.bind_draining_request(rid, r2)
|
||||
assert session.response_id_for_request("req-r1-talker") == r1
|
||||
assert session.response_id_for_request("req-r2-talker") == r2
|
||||
|
||||
|
||||
def test_end_response_clears_only_own_draining_entries() -> None:
|
||||
from vllm_omni.engine.duplex.config import DuplexCapabilities, DuplexSessionConfig
|
||||
from vllm_omni.engine.duplex.session.engine_session import DuplexEngineSession
|
||||
|
||||
session = DuplexEngineSession(
|
||||
session_id="s-end",
|
||||
config=DuplexSessionConfig(model="m", modalities=["text", "audio"]),
|
||||
capabilities=DuplexCapabilities(supports_concurrent_turn_requests=True),
|
||||
)
|
||||
session.begin_response(turn_id=1)
|
||||
r1 = session.active_response_id
|
||||
session.bind_draining_request("req-r1", r1)
|
||||
session.begin_response(turn_id=2)
|
||||
r2 = session.active_response_id
|
||||
session.bind_draining_request("req-r2", r2)
|
||||
session.end_response(commit_text=False)
|
||||
assert session.is_draining_request("req-r1")
|
||||
assert session.response_id_for_request("req-r1") == r1
|
||||
assert not session.is_draining_request("req-r2")
|
||||
|
||||
|
||||
def test_on_stage_failure_resolves_draining_response_before_active() -> None:
|
||||
"""Mirrors runner.on_stage_failure: draining request_id owns the failed done."""
|
||||
from vllm_omni.engine.duplex.config import DuplexCapabilities, DuplexSessionConfig
|
||||
from vllm_omni.engine.duplex.session.engine_session import DuplexEngineSession
|
||||
|
||||
session = DuplexEngineSession(
|
||||
session_id="s-fail",
|
||||
config=DuplexSessionConfig(model="m", modalities=["text", "audio"]),
|
||||
capabilities=DuplexCapabilities(supports_concurrent_turn_requests=True),
|
||||
)
|
||||
session.begin_response(turn_id=1)
|
||||
r1 = session.active_response_id
|
||||
assert r1 is not None
|
||||
session.bind_draining_request("req-r1-talker", r1)
|
||||
session.begin_response(turn_id=2)
|
||||
r2 = session.active_response_id
|
||||
assert r2 is not None and r2 != r1
|
||||
|
||||
request_id = "req-r1-talker"
|
||||
draining_response_id = (
|
||||
session.response_id_for_request(request_id) if session.is_draining_request(request_id) else None
|
||||
)
|
||||
response_id = draining_response_id or session.active_response_id
|
||||
assert response_id == r1
|
||||
assert response_id != r2
|
||||
session.clear_draining_for_response(r1)
|
||||
assert not session.is_draining_request(request_id)
|
||||
assert session.active_response_id == r2
|
||||
|
||||
|
||||
def test_concurrent_turn_requests_released_resets_when_new_stage0_binds() -> None:
|
||||
"""After R4 release, a new ephemeral Stage0 bind must clear the gate flag."""
|
||||
from types import SimpleNamespace
|
||||
|
||||
run = SimpleNamespace(concurrent_turn_requests_released=True)
|
||||
# Simulate the concurrent-turn rebind arm in model_channel._append_via_data_plane.
|
||||
concurrent_turn = True
|
||||
if concurrent_turn:
|
||||
run.concurrent_turn_requests_released = False
|
||||
assert run.concurrent_turn_requests_released is False
|
||||
|
||||
|
||||
def test_draining_stage_ids_come_from_the_plugin() -> None:
|
||||
from types import SimpleNamespace
|
||||
|
||||
from vllm_omni.engine.duplex.session.model_channel import ModelChannel
|
||||
|
||||
channel = ModelChannel.__new__(ModelChannel)
|
||||
channel._ctx = SimpleNamespace(
|
||||
plugin=SimpleNamespace(draining_stage_ids=lambda *, stage_count: {stage_count - 1}),
|
||||
stage_port=SimpleNamespace(stage_count=5),
|
||||
)
|
||||
assert channel._draining_stage_ids() == frozenset({4})
|
||||
|
||||
channel._ctx.plugin = SimpleNamespace()
|
||||
assert channel._draining_stage_ids() == frozenset()
|
||||
|
||||
|
||||
def test_draining_empty_eos_completes_owning_response_before_shortcut() -> None:
|
||||
"""R2 finishing first must not swallow R1's empty Stage3 EOS."""
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
|
||||
from vllm_omni.engine.duplex.config import DuplexCapabilities, DuplexSessionConfig
|
||||
from vllm_omni.engine.duplex.session.engine_session import DuplexEngineSession
|
||||
from vllm_omni.engine.duplex.session.model_channel import ModelChannel
|
||||
|
||||
session = DuplexEngineSession(
|
||||
session_id="s-empty-eos",
|
||||
config=DuplexSessionConfig(model="m", modalities=["text", "audio"], extra_body={"auto_response": True}),
|
||||
capabilities=DuplexCapabilities(supports_concurrent_turn_requests=True, supports_core_resumable_request=False),
|
||||
)
|
||||
session.begin_response(turn_id=1)
|
||||
r1 = session.active_response_id
|
||||
assert r1 is not None
|
||||
r1_request = "duplex-s.x.e.0.r.stage3-turn1"
|
||||
still_running = "duplex-s.x.e.0.r.stage1-turn2"
|
||||
session.bind_draining_request(r1_request, r1)
|
||||
session.begin_response(turn_id=2)
|
||||
session.end_response(commit_text=False)
|
||||
session.turn_id = 2
|
||||
assert session.active_response_id is None
|
||||
|
||||
class _Plane:
|
||||
def is_terminal(self, request_id: str | None) -> bool:
|
||||
del request_id
|
||||
return False
|
||||
|
||||
def close_stream(self, request_id: str) -> None:
|
||||
del request_id
|
||||
|
||||
def mark_terminal(self, request_id: str) -> None:
|
||||
del request_id
|
||||
|
||||
class _Port:
|
||||
def __init__(self) -> None:
|
||||
self.cleanups: list[list[str]] = []
|
||||
|
||||
async def cleanup(self, request_ids: list[str], *, abort: bool = False) -> None:
|
||||
del abort
|
||||
self.cleanups.append(list(request_ids))
|
||||
|
||||
class _Out:
|
||||
def __init__(self) -> None:
|
||||
self.events: list[dict[str, object]] = []
|
||||
|
||||
def auto_responds(self) -> bool:
|
||||
return True
|
||||
|
||||
def emit(self, payload: dict[str, object]) -> None:
|
||||
self.events.append(payload)
|
||||
|
||||
port = _Port()
|
||||
out = _Out()
|
||||
|
||||
async def _noop(*_args: object, **_kwargs: object) -> None:
|
||||
return None
|
||||
|
||||
async def _schedule(*_args: object, **_kwargs: object) -> bool:
|
||||
return False
|
||||
|
||||
channel = ModelChannel(
|
||||
SimpleNamespace(
|
||||
session=session,
|
||||
plugin=SimpleNamespace(data_plane=_Plane()),
|
||||
stage_port=port,
|
||||
model_state=SimpleNamespace(clear_continuation=lambda: None),
|
||||
services=SimpleNamespace(spawn=lambda *_a, **_k: None),
|
||||
),
|
||||
out,
|
||||
close_from_runtime=_noop,
|
||||
schedule_silence_continuation=_schedule,
|
||||
abort_request=_noop,
|
||||
)
|
||||
asyncio.run(
|
||||
channel._send_one_model_output_event(
|
||||
{
|
||||
"data_plane_request_id": r1_request,
|
||||
"end_of_turn": True,
|
||||
"model_turn_id": 1,
|
||||
"text": "",
|
||||
"stage_role": "tts",
|
||||
}
|
||||
)
|
||||
)
|
||||
done = [event for event in out.events if event.get("type") == "response.done"]
|
||||
assert done and done[-1].get("response_id") == r1
|
||||
assert port.cleanups == [[r1_request]]
|
||||
assert all(still_running not in ids for ids in port.cleanups)
|
||||
assert not session.is_draining_request(r1_request)
|
||||
|
||||
|
||||
def test_draining_completion_drops_finished_response_books_only() -> None:
|
||||
"""R1 drain finish drops R1 books and leaves the live R2 snapshot."""
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
|
||||
from vllm_omni.engine.duplex.config import DuplexCapabilities, DuplexSessionConfig
|
||||
from vllm_omni.engine.duplex.session.engine_session import DuplexEngineSession
|
||||
from vllm_omni.engine.duplex.session.model_channel import ModelChannel
|
||||
|
||||
session = DuplexEngineSession(
|
||||
session_id="s-drain-books",
|
||||
config=DuplexSessionConfig(model="m", modalities=["text", "audio"], extra_body={"auto_response": True}),
|
||||
capabilities=DuplexCapabilities(supports_concurrent_turn_requests=True, supports_core_resumable_request=False),
|
||||
)
|
||||
session.begin_response(turn_id=1)
|
||||
r1 = session.active_response_id
|
||||
assert r1 is not None
|
||||
session.append_assistant_text("from-r1")
|
||||
session.snapshot_active_response_for_drain()
|
||||
r1_request = "duplex-s.x.e.0.r.stage3-turn1"
|
||||
session.bind_draining_request(r1_request, r1)
|
||||
session.begin_response(turn_id=2)
|
||||
r2 = session.active_response_id
|
||||
assert r2 is not None and r2 != r1
|
||||
session.append_assistant_text("from-r2")
|
||||
session.snapshot_active_response_for_drain()
|
||||
|
||||
class _Plane:
|
||||
def is_terminal(self, request_id: str | None) -> bool:
|
||||
del request_id
|
||||
return False
|
||||
|
||||
def close_stream(self, request_id: str) -> None:
|
||||
del request_id
|
||||
|
||||
def mark_terminal(self, request_id: str) -> None:
|
||||
del request_id
|
||||
|
||||
class _Port:
|
||||
async def cleanup(self, request_ids: list[str], *, abort: bool = False) -> None:
|
||||
del request_ids, abort
|
||||
|
||||
class _Out:
|
||||
def __init__(self) -> None:
|
||||
self.events: list[dict[str, object]] = []
|
||||
|
||||
def auto_responds(self) -> bool:
|
||||
return True
|
||||
|
||||
def emit(self, payload: dict[str, object]) -> None:
|
||||
self.events.append(payload)
|
||||
|
||||
out = _Out()
|
||||
|
||||
async def _noop(*_args: object, **_kwargs: object) -> None:
|
||||
return None
|
||||
|
||||
async def _schedule(*_args: object, **_kwargs: object) -> bool:
|
||||
return False
|
||||
|
||||
channel = ModelChannel(
|
||||
SimpleNamespace(
|
||||
session=session,
|
||||
plugin=SimpleNamespace(data_plane=_Plane()),
|
||||
stage_port=_Port(),
|
||||
model_state=SimpleNamespace(clear_continuation=lambda: None),
|
||||
services=SimpleNamespace(spawn=lambda *_a, **_k: None),
|
||||
),
|
||||
out,
|
||||
close_from_runtime=_noop,
|
||||
schedule_silence_continuation=_schedule,
|
||||
abort_request=_noop,
|
||||
)
|
||||
asyncio.run(
|
||||
channel._send_one_model_output_event(
|
||||
{
|
||||
"data_plane_request_id": r1_request,
|
||||
"end_of_turn": True,
|
||||
"model_turn_id": 1,
|
||||
"text": "",
|
||||
"stage_role": "tts",
|
||||
}
|
||||
)
|
||||
)
|
||||
assert r1 not in session._conversation.assistant_response_snapshots
|
||||
assert r1 not in session._playback.by_response
|
||||
assert f"item_{r1}" not in session._conversation.history_item_placeholders
|
||||
assert r2 in session._conversation.assistant_response_snapshots
|
||||
assert session.active_response_id == r2
|
||||
done = [event for event in out.events if event.get("type") == "response.done"]
|
||||
assert done and done[-1].get("response_id") == r1
|
||||
|
||||
|
||||
def test_stale_continue_does_not_close_the_new_response() -> None:
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
|
||||
from vllm_omni.engine.duplex.config import DuplexCapabilities, DuplexSessionConfig
|
||||
from vllm_omni.engine.duplex.session.engine_session import DuplexEngineSession
|
||||
from vllm_omni.engine.duplex.session.model_channel import ModelChannel
|
||||
|
||||
session = DuplexEngineSession(
|
||||
session_id="s-stale-continue",
|
||||
config=DuplexSessionConfig(model="m", modalities=["text", "audio"], extra_body={"auto_response": True}),
|
||||
capabilities=DuplexCapabilities(supports_concurrent_turn_requests=True, supports_core_resumable_request=False),
|
||||
)
|
||||
session.begin_response(turn_id=2)
|
||||
live = session.active_response_id
|
||||
session.epoch = 1
|
||||
|
||||
class _Out:
|
||||
def __init__(self) -> None:
|
||||
self.events: list[dict[str, object]] = []
|
||||
|
||||
def auto_responds(self) -> bool:
|
||||
return True
|
||||
|
||||
def emit(self, payload: dict[str, object]) -> None:
|
||||
self.events.append(payload)
|
||||
|
||||
out = _Out()
|
||||
cleared: list[bool] = []
|
||||
|
||||
async def _noop(*_args: object, **_kwargs: object) -> None:
|
||||
return None
|
||||
|
||||
async def _schedule(*_args: object, **_kwargs: object) -> bool:
|
||||
return False
|
||||
|
||||
channel = ModelChannel(
|
||||
SimpleNamespace(
|
||||
session=session,
|
||||
plugin=SimpleNamespace(data_plane=SimpleNamespace()),
|
||||
stage_port=SimpleNamespace(),
|
||||
model_state=SimpleNamespace(clear_continuation=lambda: cleared.append(True)),
|
||||
services=SimpleNamespace(spawn=lambda *_a, **_k: None),
|
||||
run=SimpleNamespace(closing=False),
|
||||
),
|
||||
out,
|
||||
close_from_runtime=_noop,
|
||||
schedule_silence_continuation=_schedule,
|
||||
abort_request=_noop,
|
||||
)
|
||||
asyncio.run(channel.maybe_continue_response(expected_epoch=0))
|
||||
assert session.active_response_id == live
|
||||
assert out.events == []
|
||||
assert cleared == []
|
||||
|
||||
session.bind_draining_request("duplex-s.x.e.1.r.stage3-turn2", live or "")
|
||||
asyncio.run(channel.maybe_continue_response(expected_epoch=1))
|
||||
assert session.active_response_id == live
|
||||
assert out.events == []
|
||||
|
||||
session.clear_draining_requests()
|
||||
asyncio.run(channel.maybe_continue_response(expected_epoch=1))
|
||||
assert session.active_response_id is None
|
||||
assert [event.get("type") for event in out.events] == ["response.done"]
|
||||
assert out.events[0].get("response_id") == live
|
||||
|
||||
|
||||
def test_silent_listen_with_continuation_releases_ephemeral_request() -> None:
|
||||
import asyncio
|
||||
from collections.abc import Coroutine
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
from vllm_omni.engine.duplex.config import DuplexCapabilities, DuplexSessionConfig
|
||||
from vllm_omni.engine.duplex.session.engine_session import DuplexEngineSession
|
||||
from vllm_omni.engine.duplex.session.model_channel import ModelChannel
|
||||
|
||||
session = DuplexEngineSession(
|
||||
session_id="s-silent-continue",
|
||||
config=DuplexSessionConfig(model="m", modalities=["text", "audio"]),
|
||||
capabilities=DuplexCapabilities(supports_concurrent_turn_requests=True, supports_core_resumable_request=False),
|
||||
)
|
||||
session.begin_response(turn_id=1)
|
||||
response_id = session.active_response_id
|
||||
request_id = "duplex-s.x.e.0.r.stage1-turn1"
|
||||
session.bind_request(request_id)
|
||||
|
||||
class _Plane:
|
||||
def __init__(self) -> None:
|
||||
self.terminal: list[str] = []
|
||||
|
||||
def is_terminal(self, request_id: str | None) -> bool:
|
||||
return request_id in self.terminal
|
||||
|
||||
def mark_terminal(self, request_id: str) -> None:
|
||||
self.terminal.append(request_id)
|
||||
|
||||
class _Port:
|
||||
def __init__(self) -> None:
|
||||
self.cleanups: list[list[str]] = []
|
||||
|
||||
async def cleanup(self, request_ids: list[str], *, abort: bool = False) -> None:
|
||||
del abort
|
||||
self.cleanups.append(list(request_ids))
|
||||
|
||||
class _Out:
|
||||
def __init__(self) -> None:
|
||||
self.events: list[dict[str, object]] = []
|
||||
|
||||
def auto_responds(self) -> bool:
|
||||
return False
|
||||
|
||||
def emit(self, payload: dict[str, object]) -> None:
|
||||
self.events.append(payload)
|
||||
|
||||
port = _Port()
|
||||
out = _Out()
|
||||
spawned: list[Coroutine[Any, Any, None]] = []
|
||||
|
||||
async def _noop(*_args: object, **_kwargs: object) -> None:
|
||||
return None
|
||||
|
||||
async def _schedule(*_args: object, **_kwargs: object) -> bool:
|
||||
return False
|
||||
|
||||
channel = ModelChannel(
|
||||
SimpleNamespace(
|
||||
session=session,
|
||||
plugin=SimpleNamespace(data_plane=_Plane()),
|
||||
stage_port=port,
|
||||
model_state=SimpleNamespace(
|
||||
continuation_owner_id=None, continuation_units=0, clear_continuation=lambda: None
|
||||
),
|
||||
services=SimpleNamespace(spawn=lambda coro, **_k: spawned.append(coro)),
|
||||
run=SimpleNamespace(closing=False),
|
||||
),
|
||||
out,
|
||||
close_from_runtime=_noop,
|
||||
schedule_silence_continuation=_schedule,
|
||||
abort_request=_noop,
|
||||
)
|
||||
asyncio.run(
|
||||
channel._send_one_model_output_event(
|
||||
{
|
||||
"data_plane_request_id": request_id,
|
||||
"is_listen": True,
|
||||
"end_of_turn": True,
|
||||
"model_turn_id": 1,
|
||||
"reason": "model_listen",
|
||||
}
|
||||
)
|
||||
)
|
||||
assert port.cleanups == [[request_id]]
|
||||
assert session.active_request_id is None
|
||||
assert spawned, "silent listen with unused continuation must schedule maybe_continue"
|
||||
asyncio.run(spawned[0])
|
||||
assert port.cleanups == [[request_id]]
|
||||
assert session.active_response_id is None
|
||||
assert [event.get("type") for event in out.events] == ["response.listen", "response.done"]
|
||||
assert out.events[0].get("response_id") == response_id
|
||||
assert out.events[1].get("response_id") == response_id
|
||||
|
||||
|
||||
def test_silent_listen_aborts_data_plane_request_with_full_id() -> None:
|
||||
"""abort_data_plane_request must pass [request_id], not a bare str."""
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
|
||||
from vllm_omni.engine.duplex.config import DuplexCapabilities, DuplexSessionConfig
|
||||
from vllm_omni.engine.duplex.session.engine_session import DuplexEngineSession
|
||||
from vllm_omni.engine.duplex.session.model_channel import ModelChannel
|
||||
|
||||
session = DuplexEngineSession(
|
||||
session_id="s-silent-abort",
|
||||
config=DuplexSessionConfig(model="m", modalities=["text", "audio"]),
|
||||
capabilities=DuplexCapabilities(supports_concurrent_turn_requests=True, supports_core_resumable_request=False),
|
||||
)
|
||||
request_id = "duplex-s.x.e.0.r.stage0-turn7"
|
||||
session.bind_request(request_id)
|
||||
aborts: list[list[str]] = []
|
||||
|
||||
class _Plane:
|
||||
def is_terminal(self, request_id: str | None) -> bool:
|
||||
return False
|
||||
|
||||
def mark_terminal(self, request_id: str) -> None:
|
||||
del request_id
|
||||
|
||||
class _Port:
|
||||
async def cleanup(self, request_ids: list[str], *, abort: bool = False) -> None:
|
||||
del request_ids, abort
|
||||
|
||||
class _Out:
|
||||
def auto_responds(self) -> bool:
|
||||
return True
|
||||
|
||||
def emit(self, payload: dict[str, object]) -> None:
|
||||
del payload
|
||||
|
||||
async def _noop(*_args: object, **_kwargs: object) -> None:
|
||||
return None
|
||||
|
||||
async def _abort(request_ids: list[str], *, notify: bool = False) -> None:
|
||||
del notify
|
||||
aborts.append(list(request_ids))
|
||||
|
||||
channel = ModelChannel(
|
||||
SimpleNamespace(
|
||||
session=session,
|
||||
plugin=SimpleNamespace(data_plane=_Plane()),
|
||||
stage_port=_Port(),
|
||||
model_state=SimpleNamespace(
|
||||
continuation_owner_id=None, continuation_units=0, clear_continuation=lambda: None
|
||||
),
|
||||
services=SimpleNamespace(spawn=lambda coro, **_k: None),
|
||||
run=SimpleNamespace(closing=False),
|
||||
),
|
||||
_Out(),
|
||||
close_from_runtime=_noop,
|
||||
schedule_silence_continuation=_noop,
|
||||
abort_request=_abort,
|
||||
)
|
||||
asyncio.run(
|
||||
channel._send_one_model_output_event(
|
||||
{
|
||||
"data_plane_request_id": request_id,
|
||||
"is_listen": True,
|
||||
"end_of_turn": True,
|
||||
"model_turn_id": 1,
|
||||
"reason": "model_listen",
|
||||
"abort_data_plane_request": True,
|
||||
}
|
||||
)
|
||||
)
|
||||
assert aborts == [[request_id]]
|
||||
assert all(len(item) > 1 for batch in aborts for item in batch), "must not split request id into chars"
|
||||
@@ -242,6 +242,19 @@ def test_history_commit_with_ack_only_policy_defers_unacknowledged_text():
|
||||
assert f"item_{response_id}" in session.pending_history_item_ids
|
||||
|
||||
|
||||
def test_history_commit_with_ack_only_policy_keeps_only_acknowledged_prefix():
|
||||
session = _session(config=DuplexSessionConfig(playback_commit_policy="ack_only"))
|
||||
session.begin_response()
|
||||
session.append_assistant_text("hello world")
|
||||
session.mark_audio_sent(duration_ms=1_000, text_chars=6)
|
||||
session.mark_audio_sent(duration_ms=2_000, text_chars=11)
|
||||
session.acknowledge_playback(played_ms=1_000, committed_ms=1_000)
|
||||
|
||||
committed = session.end_response(commit_text=True)
|
||||
|
||||
assert committed == {"role": "assistant", "content": "hello"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("audio_complete", [False, True])
|
||||
def test_unaligned_response_keeps_empty_turn_before_later_user_input(audio_complete):
|
||||
session = _session(config=DuplexSessionConfig(playback_commit_policy="ack_only"))
|
||||
@@ -469,6 +482,36 @@ def test_cancel_fence_releases_stage_requests_and_advances_identity():
|
||||
session.cancel_fence(DuplexFence("sid-other", epoch=1, turn_id=0), DuplexFence("sid-cancel", epoch=2))
|
||||
|
||||
|
||||
def test_request_resource_keys_are_stage_id_and_request_id():
|
||||
session = _session("sid-keys")
|
||||
session.bind_stage_request(0, "req-a", fence=session.fence)
|
||||
session.bind_stage_request(1, "req-b", fence=session.fence)
|
||||
session.bind_stage_request(2, "req-tts", fence=session.fence)
|
||||
stale_keys = list(session.request_resources.keys())
|
||||
stale_ids = list(dict.fromkeys(rid for _, rid in stale_keys))
|
||||
assert stale_ids == ["req-a", "req-b", "req-tts"]
|
||||
for sid, rid in stale_keys:
|
||||
if sid < 2:
|
||||
session.request_resources.pop((sid, rid), None)
|
||||
assert session.resource_request_ids() == ["req-tts"]
|
||||
with pytest.raises(TypeError, match="unhashable"):
|
||||
dict.fromkeys(rid for _, rid in session.request_resources.items())
|
||||
|
||||
|
||||
def test_release_resources_for_request_ids_keeps_other_ids_on_the_same_fence():
|
||||
session = _session("sid-drain-release")
|
||||
fence = session.fence
|
||||
session.bind_stage_request(2, "drain", fence=fence)
|
||||
session.bind_stage_request(3, "drain", fence=fence)
|
||||
session.bind_stage_request(0, "live", fence=fence)
|
||||
|
||||
released = session.release_resources_for_request_ids(["drain"])
|
||||
|
||||
assert released == ["drain"]
|
||||
assert session.resource_request_ids() == ["live"]
|
||||
assert session.release_resources_for_request_ids([]) == []
|
||||
|
||||
|
||||
# ---- public view ----
|
||||
|
||||
|
||||
@@ -688,3 +731,65 @@ def test_minicpmo_native_capabilities_do_not_overclaim_single_session_deployment
|
||||
|
||||
assert caps["supports_multi_session"] is False
|
||||
assert caps["supports_multi_session_same_replica"] is False
|
||||
|
||||
|
||||
def test_draining_response_stays_ack_admissible_after_next_begin_response() -> None:
|
||||
from vllm_omni.engine.duplex.events import ErrorEvent
|
||||
from vllm_omni.engine.duplex.session.playback_ledger import apply_playback_ack
|
||||
|
||||
session = _session()
|
||||
first = session.begin_response(turn_id=1)
|
||||
session.append_assistant_text("hello")
|
||||
session.mark_audio_sent(400, text_chars=5)
|
||||
session.snapshot_active_response_for_drain()
|
||||
second = session.begin_response(turn_id=2)
|
||||
assert second != first
|
||||
assert session.playback.sent_ms == 0
|
||||
events = apply_playback_ack(
|
||||
session,
|
||||
{
|
||||
"type": "playback.ack",
|
||||
"response_id": first,
|
||||
"item_id": f"item_{first}",
|
||||
"played_ms": 100,
|
||||
"committed_ms": 100,
|
||||
},
|
||||
)
|
||||
assert not any(isinstance(event, ErrorEvent) and event.code == "playback_item_not_found" for event in events)
|
||||
session.mark_audio_sent(900, text_chars=5, response_id=first)
|
||||
assert session.playback_for_response(first).sent_ms == 900
|
||||
assert session.playback.sent_ms == 0
|
||||
|
||||
|
||||
def test_finished_drain_keeps_sent_audio_ackable() -> None:
|
||||
from vllm_omni.engine.duplex.events import ErrorEvent
|
||||
from vllm_omni.engine.duplex.session.playback_ledger import apply_playback_ack
|
||||
|
||||
session = _session()
|
||||
first = session.begin_response(turn_id=1)
|
||||
session.append_assistant_text("hello")
|
||||
session.mark_audio_sent(400, text_chars=5)
|
||||
session.snapshot_active_response_for_drain()
|
||||
second = session.begin_response(turn_id=2)
|
||||
session.release_finished_drain_response(first)
|
||||
assert first in session._conversation.assistant_response_snapshots
|
||||
assert f"item_{first}" in session._conversation.history_item_placeholders
|
||||
events = apply_playback_ack(
|
||||
session,
|
||||
{
|
||||
"type": "playback.ack",
|
||||
"response_id": first,
|
||||
"item_id": f"item_{first}",
|
||||
"played_ms": 400,
|
||||
"committed_ms": 400,
|
||||
},
|
||||
)
|
||||
assert not any(isinstance(event, ErrorEvent) for event in events)
|
||||
assert session.active_response_id == second
|
||||
|
||||
silent = session.begin_response(turn_id=3)
|
||||
session.snapshot_active_response_for_drain()
|
||||
session.begin_response(turn_id=4)
|
||||
session.release_finished_drain_response(silent)
|
||||
assert silent not in session._conversation.assistant_response_snapshots
|
||||
assert f"item_{silent}" not in session._conversation.history_item_placeholders
|
||||
@@ -0,0 +1,49 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm_omni.engine.duplex.realtime_events import (
|
||||
RealtimeProjectionState,
|
||||
project_internal_event,
|
||||
)
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
def test_input_transcribed_is_a_user_transcript_event() -> None:
|
||||
events = project_internal_event(
|
||||
RealtimeProjectionState(session_id="s"),
|
||||
{"type": "input.transcribed", "transcript": " 你好 "},
|
||||
)
|
||||
assert len(events) == 1
|
||||
assert events[0].wire_type == "conversation.item.input_audio_transcription.completed"
|
||||
assert events[0].transcript == "你好"
|
||||
|
||||
|
||||
def test_input_transcribed_updates_the_committed_item() -> None:
|
||||
state = RealtimeProjectionState(session_id="s")
|
||||
project_internal_event(
|
||||
state,
|
||||
{
|
||||
"type": "input.committed",
|
||||
"realtime_item_id": "item_user_1",
|
||||
"is_speech": True,
|
||||
"message": {"role": "user"},
|
||||
},
|
||||
)
|
||||
events = project_internal_event(
|
||||
state,
|
||||
{"type": "input.transcribed", "transcript": "你好", "realtime_item_id": "item_user_1"},
|
||||
)
|
||||
assert events[0].item_id == "item_user_1"
|
||||
item = state.conversation_items["item_user_1"]
|
||||
assert item["content"][0]["transcript"] == "你好"
|
||||
|
||||
|
||||
def test_blank_input_transcribed_emits_nothing() -> None:
|
||||
events = project_internal_event(
|
||||
RealtimeProjectionState(session_id="s"),
|
||||
{"type": "input.transcribed", "transcript": " "},
|
||||
)
|
||||
assert events == []
|
||||
@@ -79,6 +79,39 @@ def test_an_explicit_client_overlap_action_requests_barge_in() -> None:
|
||||
assert decision["reason"] == "client_overlap_action"
|
||||
|
||||
|
||||
def test_turn_mode_keeps_silent_vision_follow_during_overlap() -> None:
|
||||
"""Vision-follow is is_speech=False + a frame; must not drop while TTS plays."""
|
||||
session = _session()
|
||||
session.capabilities = type(session.capabilities)(
|
||||
required_input_modalities=frozenset({"video"}),
|
||||
optional_input_modalities=frozenset({"audio"}),
|
||||
)
|
||||
payload = {"format": "pcm16", "audio": _pcm16(0.0), "video_frames": ["frame"], "is_speech": False}
|
||||
decision = overlap_policy.decide(session, {"is_speech": False}, payload, auto_responds=False)
|
||||
assert decision["action"] == "listen"
|
||||
assert decision["reason"] == "vision_follow"
|
||||
assert decision["buffer_audio"] is True
|
||||
assert decision["defer_runtime_append"] is False
|
||||
assert decision["force_listen"] is False
|
||||
|
||||
|
||||
def test_turn_mode_drops_silent_vision_without_capability() -> None:
|
||||
session = _session()
|
||||
assert session.capabilities.allows_video_without_audio() is False
|
||||
payload = {"format": "pcm16", "audio": _pcm16(0.0), "video_frames": ["frame"], "is_speech": False}
|
||||
decision = overlap_policy.decide(session, {"is_speech": False}, payload, auto_responds=False)
|
||||
assert decision["action"] == "drop"
|
||||
assert decision["reason"] == "silence_or_noise"
|
||||
|
||||
|
||||
def test_turn_mode_still_drops_silent_overlap_without_vision() -> None:
|
||||
session = _session()
|
||||
payload = {"format": "pcm16", "audio": _pcm16(0.0), "is_speech": False}
|
||||
decision = overlap_policy.decide(session, {"is_speech": False}, payload, auto_responds=False)
|
||||
assert decision["action"] == "drop"
|
||||
assert decision["reason"] == "silence_or_noise"
|
||||
|
||||
|
||||
def test_barge_in_is_deferred_when_the_session_cannot_support_it() -> None:
|
||||
session = _session()
|
||||
session.capabilities = type(session.capabilities)(supports_barge_in=False)
|
||||
|
||||
@@ -196,7 +196,11 @@ class FakePlugin(DuplexModelPlugin):
|
||||
|
||||
def capabilities(self, *, max_sessions: int) -> DuplexCapabilities:
|
||||
del max_sessions
|
||||
return DuplexCapabilities(supports_input_append=True, supports_core_resumable_request=True)
|
||||
# Resident Stage0 ids (MiniCPM-shaped); AURA opts out via supports_core_resumable_request=False.
|
||||
return DuplexCapabilities(
|
||||
supports_input_append=True,
|
||||
supports_core_resumable_request=True,
|
||||
)
|
||||
|
||||
def validate_client_extra_body(self, extra_body: object) -> None:
|
||||
pass
|
||||
@@ -409,7 +413,8 @@ async def test_open_answers_with_capabilities_and_emits_session_created() -> Non
|
||||
assert result.session_id == "sid-open"
|
||||
assert result.lease_generation == 0
|
||||
assert result.capabilities == DuplexCapabilities(
|
||||
supports_input_append=True, supports_core_resumable_request=True
|
||||
supports_input_append=True,
|
||||
supports_core_resumable_request=True,
|
||||
)
|
||||
assert result.public_session is not None
|
||||
assert result.public_session["id"] == "sid-open"
|
||||
@@ -1028,6 +1033,40 @@ async def test_append_bytes_are_reserved_at_admission_until_the_runner_dequeues(
|
||||
gate.set()
|
||||
|
||||
|
||||
async def test_append_admission_counts_audio_and_video_frame_bytes() -> None:
|
||||
"""Manager reserves len(audio)+Σlen(frame); video bytes count toward the same limit."""
|
||||
async with Harness.create(max_sessions=1, max_pending_input_bytes_per_session=20) as harness:
|
||||
await harness.open("sid-av")
|
||||
harness.events()
|
||||
session = harness.session("sid-av")
|
||||
runner = harness.manager.runners["sid-av"]
|
||||
gate = asyncio.Event()
|
||||
runner._mailbox.put_nowait(_Internal("wait", {"gate": gate}))
|
||||
runner._on_internal = lambda item: gate.wait() # type: ignore[method-assign]
|
||||
await asyncio.sleep(0)
|
||||
|
||||
# Default caps require audio; attach video to a non-empty audio unit.
|
||||
frame_a = "aaaa"
|
||||
frame_b = "bbbbbb"
|
||||
audio = b"1234"
|
||||
expected = len(audio) + len(frame_a) + len(frame_b)
|
||||
harness.command(
|
||||
"sid-av",
|
||||
AppendAudio(audio=audio, video_frames=(frame_a, frame_b), event_id="evt-av"),
|
||||
)
|
||||
assert session.pending_input_bytes == expected
|
||||
# Second append that would exceed the limit is backpressured.
|
||||
harness.command(
|
||||
"sid-av",
|
||||
AppendAudio(audio=b"x" * 10, video_frames=("yyyyyyyyyy",), event_id="evt-over"),
|
||||
)
|
||||
errors = [event for event in harness.events("sid-av") if isinstance(event, ErrorEvent)]
|
||||
assert [error.code for error in errors] == ["input_backpressure"]
|
||||
assert errors[0].related_event_id == "evt-over"
|
||||
assert session.pending_input_bytes == expected
|
||||
gate.set()
|
||||
|
||||
|
||||
async def test_expired_session_retains_the_admission_slot_until_cleanup_succeeds() -> None:
|
||||
async with Harness.create(max_sessions=1, idle_ttl_s=1.0) as harness:
|
||||
await harness.open("sid-expired")
|
||||
|
||||
@@ -180,7 +180,10 @@ class Harness:
|
||||
segment_token_ids=tuple(segment_token_ids),
|
||||
segment_output_metadata=dict(segment_output_metadata or {}),
|
||||
)
|
||||
return self.runner.on_stage_output(stage_id, output, metrics, request_id=output.request_id, context=context)
|
||||
request_id = getattr(output, "request_id", None)
|
||||
if not isinstance(request_id, str):
|
||||
raise AssertionError("stage output is missing request_id")
|
||||
return self.runner.on_stage_output(stage_id, output, metrics, request_id=request_id, context=context)
|
||||
|
||||
async def deliver_and_settle(self, output: object, **kwargs: Any) -> list[DuplexEvent]:
|
||||
self.deliver(output, **kwargs)
|
||||
@@ -520,6 +523,28 @@ async def test_commit_without_audio_is_rejected() -> None:
|
||||
await close_harness(h)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_empty_silent_commit_acks_without_opening_response() -> None:
|
||||
"""#3: empty is_speech=False commit keeps the silent-ack pair, even auto-respond."""
|
||||
h = await open_harness(auto_response=True)
|
||||
try:
|
||||
# resolve_commit only admits empty silent commits after non-speech was seen.
|
||||
projector = h.runner._require_projector()
|
||||
projector.input_audio_buffer_had_non_speech = True
|
||||
events = await h.run(commands.Commit())
|
||||
assert "error" not in types(events), types(events)
|
||||
assert "input_audio_buffer.committed" in types(events), types(events)
|
||||
assert "response.listen" in types(events), types(events)
|
||||
listen = next(event for event in events if event.type == "response.listen")
|
||||
assert listen.details["reason"] == "silence_or_noise"
|
||||
committed = next(event for event in events if event.type == "input_audio_buffer.committed")
|
||||
assert committed.details.get("empty") is True
|
||||
assert committed.details.get("no_response") is True
|
||||
assert h.port.submissions == []
|
||||
finally:
|
||||
await close_harness(h)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_commit_projects_the_user_item_and_does_not_resubmit_consumed_audio() -> None:
|
||||
h = await open_harness()
|
||||
@@ -674,6 +699,45 @@ async def test_stale_epoch_output_is_dropped_after_barge_in() -> None:
|
||||
await close_harness(h)
|
||||
|
||||
|
||||
async def test_barge_in_aborts_draining_tts_as_well_as_the_active_request() -> None:
|
||||
h = await open_harness()
|
||||
try:
|
||||
await h.run(append_audio())
|
||||
request_id = h.stage0_request_id()
|
||||
await h.deliver_and_settle(tts_output(request_id, samples=24000, text="he"))
|
||||
h.session.bind_draining_request("duplex-drain-tts", "resp-old")
|
||||
# Draining TTS sits on an older turn fence. cancel_fence only drops
|
||||
# the fence being cancelled, so these bindings must be popped by id.
|
||||
from vllm_omni.engine.duplex.contracts import DuplexFence
|
||||
from vllm_omni.engine.duplex.session.engine_session import DuplexRequestResource
|
||||
|
||||
older = DuplexFence(h.session.session_id, epoch=h.session.epoch, turn_id=h.session.turn_id + 5)
|
||||
h.session.request_resources[(2, "duplex-drain-tts")] = DuplexRequestResource(
|
||||
stage_id=2, request_id="duplex-drain-tts", fence=older, submitted=True
|
||||
)
|
||||
h.session.request_resources[(3, "duplex-drain-tts")] = DuplexRequestResource(
|
||||
stage_id=3, request_id="duplex-drain-tts", fence=older, submitted=True
|
||||
)
|
||||
h.session.request_resources[(1, "still-live")] = DuplexRequestResource(
|
||||
stage_id=1, request_id="still-live", fence=older, submitted=True
|
||||
)
|
||||
events = await h.run(commands.BargeIn())
|
||||
assert h.port.aborts == [[request_id, "duplex-drain-tts"]]
|
||||
assert not h.session.is_draining_request("duplex-drain-tts")
|
||||
done_ids = [
|
||||
event.response["id"]
|
||||
for event in events
|
||||
if getattr(event, "wire_type", "") == "response.done" and isinstance(getattr(event, "response", None), dict)
|
||||
]
|
||||
assert "resp-old" in done_ids
|
||||
assert (2, "duplex-drain-tts") not in h.session.request_resources
|
||||
assert (3, "duplex-drain-tts") not in h.session.request_resources
|
||||
assert (0, request_id) not in h.session.request_resources
|
||||
assert (1, "still-live") in h.session.request_resources
|
||||
finally:
|
||||
await close_harness(h)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cancel_response_without_active_response_is_rejected() -> None:
|
||||
h = await open_harness()
|
||||
@@ -778,6 +842,46 @@ async def test_listen_decision_on_a_resumable_request_closes_the_bounded_respons
|
||||
await close_harness(h)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_direct_response_listen_still_emits_response_done_after_continuation_clear() -> None:
|
||||
"""AURA-like silent DIRECT_RESPONSE: after continuation budget is spent, emit response.done.
|
||||
|
||||
Non-resumable turn-commit still closes the active response on a listen/direct
|
||||
decision so the client is not left without a terminal event.
|
||||
"""
|
||||
from dataclasses import replace
|
||||
|
||||
h = await open_harness()
|
||||
try:
|
||||
h.session.capabilities = replace(h.session.capabilities, supports_core_resumable_request=False)
|
||||
await h.run(append_audio())
|
||||
assert h.port.submissions, "ephemeral Stage0 must submit"
|
||||
request_id = h.port.submissions[-1].context.request_id
|
||||
assert "-turn" in request_id
|
||||
await h.deliver_and_settle(tts_output(request_id, samples=24000, text="ok"))
|
||||
response_id = h.session.active_response_id
|
||||
assert response_id is not None
|
||||
model_state = h.runner.model_state
|
||||
model_state.continuation_owner_id = f"response:{response_id}"
|
||||
model_state.continuation_units = h.runner.model._AUTO_RESPONSE_MAX_CONTINUATION_UNITS
|
||||
|
||||
listen = listen_output(request_id)
|
||||
listen.finished = True
|
||||
events = await h.deliver_and_settle(
|
||||
listen,
|
||||
stage_id=0,
|
||||
segment_finished=True,
|
||||
segment_token_ids=[11, 12, LISTEN_TOKEN_ID],
|
||||
segment_output_metadata={"meta.listen_token_id": LISTEN_TOKEN_ID},
|
||||
)
|
||||
assert "response.listen" in types(events)
|
||||
done = find(events, "response.done")
|
||||
assert done.response_id == response_id
|
||||
assert h.session.active_response_id is None
|
||||
finally:
|
||||
await close_harness(h)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_listen_decision_on_a_resumable_request_keeps_the_turn_going() -> None:
|
||||
"""Same unfinished listen, budget left: it must schedule the next unit.
|
||||
@@ -860,6 +964,38 @@ async def test_stage_failure_fails_the_active_response() -> None:
|
||||
await close_harness(h)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stage_failure_on_draining_request_fails_that_response_only() -> None:
|
||||
"""Overlapped: a draining older request failure must not wipe the active response."""
|
||||
from dataclasses import replace
|
||||
|
||||
h = await open_harness()
|
||||
try:
|
||||
h.session.capabilities = replace(h.session.capabilities, supports_concurrent_turn_requests=True)
|
||||
await h.run(append_audio())
|
||||
request_id = h.stage0_request_id()
|
||||
await h.deliver_and_settle(tts_output(request_id, samples=24000, text="hello"))
|
||||
r1 = h.session.active_response_id
|
||||
assert r1 is not None
|
||||
draining_req = "req-r1-talker-drain"
|
||||
h.session.bind_draining_request(draining_req, r1)
|
||||
# Open a newer active response while R1 TTS is still draining.
|
||||
r2 = h.session.begin_response(turn_id=(h.session.turn_id or 0) + 1)
|
||||
assert h.session.active_response_id == r2
|
||||
assert r2 != r1
|
||||
|
||||
h.runner.on_stage_failure(2, RuntimeError("drain-boom"), request_id=draining_req)
|
||||
events = await h.settle()
|
||||
assert types(events)[0] == "error"
|
||||
done = find(events, "response.done")
|
||||
assert done.response_id == r1
|
||||
assert done.status == "failed"
|
||||
assert h.session.active_response_id == r2
|
||||
assert not h.session.is_draining_request(draining_req)
|
||||
finally:
|
||||
await close_harness(h)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Turn mode (no auto response) #
|
||||
# --------------------------------------------------------------------------- #
|
||||
@@ -877,6 +1013,91 @@ async def test_turn_mode_skips_silent_chunks() -> None:
|
||||
await close_harness(h)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_turn_mode_keeps_silent_chunks_with_video_frames() -> None:
|
||||
"""Engine vision-follow buffers silent+frames; MiniCPM commit stays speech-gated."""
|
||||
from dataclasses import replace
|
||||
|
||||
h = await open_harness(auto_response=False)
|
||||
try:
|
||||
h.session.capabilities = replace(
|
||||
h.session.capabilities,
|
||||
required_input_modalities=frozenset({"video"}),
|
||||
optional_input_modalities=frozenset({"audio"}),
|
||||
)
|
||||
# Minimal 1x1 JPEG (base64) — wire validation only checks non-empty str.
|
||||
frame = (
|
||||
"/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkS"
|
||||
"Ew8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJ"
|
||||
"CQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIy"
|
||||
"MjIyMjIyMjIyMjIyMjL/wAARCAABAAEDASIAAhEBAxEB/8QAFQABAQAAAAAAAAAA"
|
||||
"AAAAAAAAAAj/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFQEBAQAAAAAAAAAAAAAA"
|
||||
"AAAAAAD/xAAUEQEAAAAAAAAAAAAAAAAAAAAA/9oADAMBAAIQAxAAAAGfAP/EABQQ"
|
||||
"AQAAAAAAAAAAAAAAAAAAAAD/2gAIAQEAAQUCf//EABQRAQAAAAAAAAAAAAAAAAAA"
|
||||
"AAD/2gAIAQMBAT8Bf//EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQIBAT8Bf//E"
|
||||
"ABQQAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQEABj8Cf//EABQQAQAAAAAAAAAAAAAA"
|
||||
"AAAAAAD/2gAIAQEAAT8hf//Z"
|
||||
)
|
||||
cmd = commands.AppendAudio(
|
||||
audio=pcm_f32(160, value=0.0),
|
||||
format="pcm_f32le",
|
||||
sample_rate_hz=16000,
|
||||
is_speech=False,
|
||||
video_frames=(frame,),
|
||||
)
|
||||
events = await h.run(cmd)
|
||||
assert "response.listen" not in types(events)
|
||||
assert h.runner.model_state.audio_buffer.has_pending()
|
||||
events = await h.run(commands.Commit(create_response=True))
|
||||
# MiniCPM prepare_commit is speech-gated (no frames-only Stage0).
|
||||
assert "input_audio_buffer.committed" in types(events), types(events)
|
||||
assert h.port.submissions == []
|
||||
finally:
|
||||
await close_harness(h)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_turn_mode_keeps_silent_vision_while_response_in_progress() -> None:
|
||||
"""TTS still playing: vision-follow must buffer, not drop as silence_or_noise."""
|
||||
from dataclasses import replace
|
||||
|
||||
h = await open_harness(auto_response=False)
|
||||
try:
|
||||
h.session.capabilities = replace(
|
||||
h.session.capabilities,
|
||||
required_input_modalities=frozenset({"video"}),
|
||||
optional_input_modalities=frozenset({"audio"}),
|
||||
)
|
||||
h.session._response.active_response_id = "resp-tts"
|
||||
frame = (
|
||||
"/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkS"
|
||||
"Ew8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJ"
|
||||
"CQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIy"
|
||||
"MjIyMjIyMjIyMjIyMjL/wAARCAABAAEDASIAAhEBAxEB/8QAFQABAQAAAAAAAAAA"
|
||||
"AAAAAAAAAAj/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFQEBAQAAAAAAAAAAAAAA"
|
||||
"AAAAAAD/xAAUEQEAAAAAAAAAAAAAAAAAAAAA/9oADAMBAAIQAxAAAAGfAP/EABQQ"
|
||||
"AQAAAAAAAAAAAAAAAAAAAAD/2gAIAQMBAT8Bf//EABQRAQAAAAAAAAAAAAAAAAAA"
|
||||
"AAD/2gAIAQIBAT8Bf//EABQQAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQEABj8Cf//E"
|
||||
"ABQQAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQEAAT8hf//Z"
|
||||
)
|
||||
events = await h.run(
|
||||
commands.AppendAudio(
|
||||
audio=pcm_f32(160, value=0.0),
|
||||
format="pcm_f32le",
|
||||
sample_rate_hz=16000,
|
||||
is_speech=False,
|
||||
video_frames=(frame,),
|
||||
)
|
||||
)
|
||||
listen_reasons = [
|
||||
getattr(event, "details", {}) or {} for event in events if getattr(event, "type", None) == "response.listen"
|
||||
]
|
||||
assert all(details.get("reason") != "silence_or_noise" for details in listen_reasons)
|
||||
assert h.runner.model_state.audio_buffer.has_pending()
|
||||
finally:
|
||||
await close_harness(h)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_turn_mode_commit_with_response_create_starts_one_response() -> None:
|
||||
h = await open_harness(auto_response=False)
|
||||
@@ -1033,7 +1254,7 @@ async def test_conversation_items_can_be_injected_and_deleted() -> None:
|
||||
await close_harness(h)
|
||||
|
||||
|
||||
def _stage_metrics_of(event: object) -> dict[str, dict[str, object]]:
|
||||
def _stage_metrics_of(event: DuplexEvent) -> dict[str, dict[str, object]]:
|
||||
"""Per-stage engine metrics as the client reads them off one wire event."""
|
||||
payload = event.to_realtime()
|
||||
metadata = payload.get("metadata")
|
||||
@@ -1081,6 +1302,40 @@ async def test_stage0_metrics_reach_the_response_even_though_its_output_feeds_tt
|
||||
await close_harness(h)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_projected_stage1_metrics_reach_the_spoken_audio_event() -> None:
|
||||
"""Thinker text is projected, but its TTFT/TPOT still have to ride the audio event."""
|
||||
h = await open_harness(stage_count=3)
|
||||
try:
|
||||
plugin = h.runner.model._ctx.plugin
|
||||
|
||||
def project_stage1(*, stage_id: int, output: object, context: object) -> bool:
|
||||
del output, context
|
||||
return stage_id == 1
|
||||
|
||||
plugin.project_intermediate_output = project_stage1
|
||||
await h.run(append_audio())
|
||||
request_id = h.stage0_request_id()
|
||||
thinker = SimpleNamespace(
|
||||
request_id=request_id,
|
||||
finished=True,
|
||||
outputs=[SimpleNamespace(text="hello", token_ids=[7, 8], multimodal_output={})],
|
||||
multimodal_output={},
|
||||
)
|
||||
forwarded = h.deliver(
|
||||
thinker,
|
||||
stage_id=1,
|
||||
segment_finished=False,
|
||||
metrics=stage_stats(stage_id=1, request_id=request_id, num_tokens_out=2, itls_ms=[6.0]),
|
||||
)
|
||||
assert forwarded is False
|
||||
events = await h.deliver_and_settle(tts_output(request_id, samples=24000, text="hello"), stage_id=2)
|
||||
stage_metrics = _stage_metrics_of(find(events, "response.output_audio.delta"))
|
||||
assert stage_metrics["1"]["num_tokens_out"] == 2
|
||||
finally:
|
||||
await close_harness(h)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stage0_metrics_from_several_units_are_summed_into_one_response() -> None:
|
||||
"""Two pass-through segments before the first audio are one response's tokens."""
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""Ephemeral Stage0 bind uses r.stage0-turn{N}, not resumable r.stage0."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from vllm_omni.engine.duplex.contracts import (
|
||||
DuplexFence,
|
||||
duplex_ephemeral_stage_request_id,
|
||||
duplex_resource_request_id,
|
||||
)
|
||||
from vllm_omni.engine.duplex.session.manager import DuplexSessionManager
|
||||
|
||||
|
||||
def test_stage0_request_id_ephemeral_when_not_resumable() -> None:
|
||||
fence = DuplexFence("duplex-test", epoch=0, turn_id=3)
|
||||
rid = DuplexSessionManager.stage_request_id(fence, stage_id=0, resumable=False)
|
||||
expected = duplex_ephemeral_stage_request_id(fence, stage_id=0)
|
||||
assert rid == expected
|
||||
assert rid.endswith(".r.stage0-turn3")
|
||||
assert not rid.endswith(".r.stage0")
|
||||
|
||||
|
||||
def test_stage0_request_id_resumable_keeps_stable_role() -> None:
|
||||
fence = DuplexFence("duplex-test", epoch=1, turn_id=3)
|
||||
rid = DuplexSessionManager.stage_request_id(fence, stage_id=0, resumable=True)
|
||||
expected = duplex_resource_request_id(fence, "stage0")
|
||||
assert rid == expected
|
||||
assert rid.endswith(".r.stage0")
|
||||
@@ -22,6 +22,7 @@ from pydantic import ValidationError
|
||||
from transformers import PretrainedConfig, Qwen3OmniMoeConfig
|
||||
from vllm.engine.arg_utils import EngineArgs
|
||||
|
||||
from tests.helpers.mock import patch_hf_snapshot_download
|
||||
from vllm_omni.config.model import OmniModelConfig
|
||||
from vllm_omni.engine.arg_utils import OmniEngineArgs
|
||||
from vllm_omni.engine.stage_init_utils import build_engine_args_dict
|
||||
@@ -296,7 +297,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.HfApi.snapshot_download", lambda *args, **kwargs: str(tmp_path))
|
||||
patch_hf_snapshot_download(monkeypatch, lambda *args, **kwargs: str(tmp_path), hf_home=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(
|
||||
@@ -543,3 +544,40 @@ def test_tensor_parallel_size_none_is_handled():
|
||||
)
|
||||
assert isinstance(args, dict)
|
||||
assert "tensor_parallel_size" not in args
|
||||
|
||||
|
||||
# For https://github.com/vllm-project/vllm-omni/issues/7564
|
||||
def test_from_cli_args_preserves_text_encoder_tp_size():
|
||||
"""`--text-encoder-tp-size` must survive from_cli_args field filtering.
|
||||
|
||||
Library callers build engine args via ``OmniEngineArgs.from_cli_args``;
|
||||
the dataclass field filter drops any namespace attribute the dataclass
|
||||
does not declare, silently resetting the diffusion text-encoder TP to 1.
|
||||
"""
|
||||
engine_args = OmniEngineArgs.from_cli_args(
|
||||
SimpleNamespace(text_encoder_tp_size=2),
|
||||
)
|
||||
assert engine_args.text_encoder_tp_size == 2
|
||||
|
||||
|
||||
# For https://github.com/vllm-project/vllm-omni/issues/7564
|
||||
def test_text_encoder_tp_size_reaches_default_diffusion_parallel_config():
|
||||
"""The preserved CLI value must land in DiffusionParallelConfig.
|
||||
|
||||
Forward the preserved explicit override to the generic diffusion
|
||||
fallback, which resolves it through
|
||||
``DiffusionParallelConfig.from_stage_overrides``. Serializing all engine
|
||||
defaults would also forward unrelated LLM-only fields to strict diffusion
|
||||
ingress, unlike the explicit-kwargs library entrypoint.
|
||||
"""
|
||||
from vllm_omni.config.config_factory import StageConfigFactory
|
||||
|
||||
engine_args = OmniEngineArgs.from_cli_args(
|
||||
SimpleNamespace(text_encoder_tp_size=2),
|
||||
)
|
||||
stage_cfg = StageConfigFactory.create_default_diffusion(
|
||||
{"text_encoder_tp_size": engine_args.text_encoder_tp_size},
|
||||
)[0]
|
||||
|
||||
parallel_config = stage_cfg["engine_args"]["parallel_config"]
|
||||
assert parallel_config["text_encoder_tp_size"] == 2
|
||||
@@ -14,6 +14,7 @@ import pytest
|
||||
from omegaconf import OmegaConf
|
||||
from vllm.v1.engine.utils import EngineZmqAddresses
|
||||
|
||||
from tests.helpers.mock import patch_hf_snapshot_download
|
||||
from vllm_omni.config.omni_config import OmniStageRuntimeConfig
|
||||
from vllm_omni.diffusion.data import AttentionConfig
|
||||
from vllm_omni.engine import omni_engine_base as async_omni_engine_module
|
||||
@@ -1566,22 +1567,20 @@ def test_build_engine_args_pulls_stage_subdirs_missing_from_cached_snapshot(monk
|
||||
never materialized. Stage init must fetch exactly those subfolders instead
|
||||
of joining onto a path that exists nowhere.
|
||||
"""
|
||||
from huggingface_hub import HfApi
|
||||
|
||||
from vllm_omni.engine.stage_init_utils import build_engine_args_dict
|
||||
|
||||
snapshot = tmp_path / "snapshots" / "deadbeef"
|
||||
_make_snapshot(snapshot, ["tokenizer"])
|
||||
calls = []
|
||||
|
||||
def fake_snapshot_download(self, repo_id, **kwargs):
|
||||
def fake_snapshot_download(repo_id, **kwargs):
|
||||
calls.append(kwargs)
|
||||
if kwargs.get("local_files_only"):
|
||||
return str(snapshot)
|
||||
_make_snapshot(snapshot, ["language_model"])
|
||||
return str(snapshot)
|
||||
|
||||
monkeypatch.setattr(HfApi, "snapshot_download", fake_snapshot_download)
|
||||
patch_hf_snapshot_download(monkeypatch, fake_snapshot_download, hf_home=tmp_path)
|
||||
|
||||
stage_cfg = types.SimpleNamespace(
|
||||
stage_id=0,
|
||||
@@ -1601,18 +1600,16 @@ def test_build_engine_args_pulls_stage_subdirs_missing_from_cached_snapshot(monk
|
||||
|
||||
def test_build_engine_args_skips_hub_call_when_cached_snapshot_is_complete(monkeypatch, tmp_path):
|
||||
"""A warm cache stays offline-friendly: no outgoing Hub request."""
|
||||
from huggingface_hub import HfApi
|
||||
|
||||
from vllm_omni.engine.stage_init_utils import build_engine_args_dict
|
||||
|
||||
snapshot = tmp_path / "snapshots" / "deadbeef"
|
||||
_make_snapshot(snapshot, ["language_model", "tokenizer"])
|
||||
|
||||
def fake_snapshot_download(self, repo_id, **kwargs):
|
||||
def fake_snapshot_download(repo_id, **kwargs):
|
||||
assert kwargs.get("local_files_only"), "warm cache must not reach the Hub"
|
||||
return str(snapshot)
|
||||
|
||||
monkeypatch.setattr(HfApi, "snapshot_download", fake_snapshot_download)
|
||||
patch_hf_snapshot_download(monkeypatch, fake_snapshot_download, hf_home=tmp_path)
|
||||
|
||||
stage_cfg = types.SimpleNamespace(
|
||||
stage_id=0,
|
||||
@@ -1633,8 +1630,6 @@ def test_build_engine_args_redownloads_a_partial_subdir(monkeypatch, tmp_path):
|
||||
that local path leaves vLLM's loader without any fallback for the missing
|
||||
weights.
|
||||
"""
|
||||
from huggingface_hub import HfApi
|
||||
|
||||
from vllm_omni.engine.stage_init_utils import build_engine_args_dict
|
||||
|
||||
snapshot = tmp_path / "snapshots" / "deadbeef"
|
||||
@@ -1644,14 +1639,14 @@ def test_build_engine_args_redownloads_a_partial_subdir(monkeypatch, tmp_path):
|
||||
_make_snapshot(snapshot, ["tokenizer"])
|
||||
calls = []
|
||||
|
||||
def fake_snapshot_download(self, repo_id, **kwargs):
|
||||
def fake_snapshot_download(repo_id, **kwargs):
|
||||
calls.append(kwargs)
|
||||
if kwargs.get("local_files_only"):
|
||||
return str(snapshot)
|
||||
_make_snapshot(snapshot, ["language_model"])
|
||||
return str(snapshot)
|
||||
|
||||
monkeypatch.setattr(HfApi, "snapshot_download", fake_snapshot_download)
|
||||
patch_hf_snapshot_download(monkeypatch, fake_snapshot_download, hf_home=tmp_path)
|
||||
|
||||
stage_cfg = types.SimpleNamespace(
|
||||
stage_id=0,
|
||||
@@ -1672,8 +1667,6 @@ def test_build_engine_args_redownloads_when_index_lists_missing_shards(monkeypat
|
||||
The index downloads early; accepting it as proof of weights converts the
|
||||
Hub ID into a local path vLLM cannot fetch the remaining shards for.
|
||||
"""
|
||||
from huggingface_hub import HfApi
|
||||
|
||||
from vllm_omni.engine.stage_init_utils import build_engine_args_dict
|
||||
|
||||
snapshot = tmp_path / "snapshots" / "deadbeef"
|
||||
@@ -1693,13 +1686,13 @@ def test_build_engine_args_redownloads_when_index_lists_missing_shards(monkeypat
|
||||
_make_snapshot(snapshot, ["tokenizer"])
|
||||
calls = []
|
||||
|
||||
def fake_snapshot_download(self, repo_id, **kwargs):
|
||||
def fake_snapshot_download(repo_id, **kwargs):
|
||||
calls.append(kwargs)
|
||||
if not kwargs.get("local_files_only"):
|
||||
(partial / "model-00002-of-00002.safetensors").write_text("x")
|
||||
return str(snapshot)
|
||||
|
||||
monkeypatch.setattr(HfApi, "snapshot_download", fake_snapshot_download)
|
||||
patch_hf_snapshot_download(monkeypatch, fake_snapshot_download, hf_home=tmp_path)
|
||||
|
||||
stage_cfg = types.SimpleNamespace(
|
||||
stage_id=0,
|
||||
@@ -1716,8 +1709,6 @@ def test_build_engine_args_redownloads_when_index_lists_missing_shards(monkeypat
|
||||
|
||||
def test_build_engine_args_redownloads_shards_without_their_index(monkeypatch, tmp_path):
|
||||
"""Shard-named weights always ship an index; one without it is partial."""
|
||||
from huggingface_hub import HfApi
|
||||
|
||||
from vllm_omni.engine.stage_init_utils import build_engine_args_dict
|
||||
|
||||
snapshot = tmp_path / "snapshots" / "deadbeef"
|
||||
@@ -1727,7 +1718,7 @@ def test_build_engine_args_redownloads_shards_without_their_index(monkeypatch, t
|
||||
_make_snapshot(snapshot, ["tokenizer"])
|
||||
calls = []
|
||||
|
||||
def fake_snapshot_download(self, repo_id, **kwargs):
|
||||
def fake_snapshot_download(repo_id, **kwargs):
|
||||
calls.append(kwargs)
|
||||
if not kwargs.get("local_files_only"):
|
||||
shards = {f"w{i}.weight": f"model-0000{i}-of-00004.safetensors" for i in range(1, 5)}
|
||||
@@ -1736,7 +1727,7 @@ def test_build_engine_args_redownloads_shards_without_their_index(monkeypatch, t
|
||||
(partial / shard).write_text("x")
|
||||
return str(snapshot)
|
||||
|
||||
monkeypatch.setattr(HfApi, "snapshot_download", fake_snapshot_download)
|
||||
patch_hf_snapshot_download(monkeypatch, fake_snapshot_download, hf_home=tmp_path)
|
||||
|
||||
stage_cfg = types.SimpleNamespace(
|
||||
stage_id=0,
|
||||
@@ -1752,8 +1743,6 @@ def test_build_engine_args_redownloads_shards_without_their_index(monkeypatch, t
|
||||
|
||||
def test_build_engine_args_redownloads_a_tokenizer_folder_without_vocabulary(monkeypatch, tmp_path):
|
||||
"""Templates and configs download first; alone they are not a tokenizer."""
|
||||
from huggingface_hub import HfApi
|
||||
|
||||
from vllm_omni.engine.stage_init_utils import build_engine_args_dict
|
||||
|
||||
snapshot = tmp_path / "snapshots" / "deadbeef"
|
||||
@@ -1763,13 +1752,13 @@ def test_build_engine_args_redownloads_a_tokenizer_folder_without_vocabulary(mon
|
||||
(partial / "chat_template.jinja").write_text("{{ messages }}")
|
||||
calls = []
|
||||
|
||||
def fake_snapshot_download(self, repo_id, **kwargs):
|
||||
def fake_snapshot_download(repo_id, **kwargs):
|
||||
calls.append(kwargs)
|
||||
if not kwargs.get("local_files_only"):
|
||||
_make_snapshot(snapshot, ["tokenizer"])
|
||||
return str(snapshot)
|
||||
|
||||
monkeypatch.setattr(HfApi, "snapshot_download", fake_snapshot_download)
|
||||
patch_hf_snapshot_download(monkeypatch, fake_snapshot_download, hf_home=tmp_path)
|
||||
|
||||
stage_cfg = types.SimpleNamespace(
|
||||
stage_id=0,
|
||||
@@ -1787,19 +1776,17 @@ def test_build_engine_args_redownloads_a_tokenizer_folder_without_vocabulary(mon
|
||||
def test_build_engine_args_forwards_revision_and_download_dir(monkeypatch, tmp_path):
|
||||
"""revision/download_dir must shape snapshot selection (they cannot be
|
||||
corrected downstream once the repo ID is a local path)."""
|
||||
from huggingface_hub import HfApi
|
||||
|
||||
from vllm_omni.engine.stage_init_utils import build_engine_args_dict
|
||||
|
||||
snapshot = tmp_path / "snapshots" / "pinned"
|
||||
_make_snapshot(snapshot, ["language_model", "tokenizer"])
|
||||
seen = []
|
||||
|
||||
def fake_snapshot_download(self, repo_id, **kwargs):
|
||||
def fake_snapshot_download(repo_id, **kwargs):
|
||||
seen.append(kwargs)
|
||||
return str(snapshot)
|
||||
|
||||
monkeypatch.setattr(HfApi, "snapshot_download", fake_snapshot_download)
|
||||
patch_hf_snapshot_download(monkeypatch, fake_snapshot_download, hf_home=tmp_path)
|
||||
|
||||
stage_cfg = types.SimpleNamespace(
|
||||
stage_id=0,
|
||||
@@ -1824,8 +1811,6 @@ def test_build_engine_args_forwards_revision_and_download_dir(monkeypatch, tmp_p
|
||||
|
||||
def test_build_engine_args_resolves_tokenizer_revision_separately(monkeypatch, tmp_path):
|
||||
"""A tokenizer pinned to a different revision resolves against its own snapshot."""
|
||||
from huggingface_hub import HfApi
|
||||
|
||||
from vllm_omni.engine.stage_init_utils import build_engine_args_dict
|
||||
|
||||
model_snapshot = tmp_path / "snapshots" / "model-rev"
|
||||
@@ -1833,12 +1818,12 @@ def test_build_engine_args_resolves_tokenizer_revision_separately(monkeypatch, t
|
||||
tokenizer_snapshot = tmp_path / "snapshots" / "tok-rev"
|
||||
_make_snapshot(tokenizer_snapshot, ["tokenizer"])
|
||||
|
||||
def fake_snapshot_download(self, repo_id, **kwargs):
|
||||
def fake_snapshot_download(repo_id, **kwargs):
|
||||
if kwargs.get("revision") == "tok-rev":
|
||||
return str(tokenizer_snapshot)
|
||||
return str(model_snapshot)
|
||||
|
||||
monkeypatch.setattr(HfApi, "snapshot_download", fake_snapshot_download)
|
||||
patch_hf_snapshot_download(monkeypatch, fake_snapshot_download, hf_home=tmp_path)
|
||||
|
||||
stage_cfg = types.SimpleNamespace(
|
||||
stage_id=0,
|
||||
@@ -1861,8 +1846,6 @@ def test_build_engine_args_resolves_tokenizer_revision_separately(monkeypatch, t
|
||||
def test_build_engine_args_resolves_root_tokenizer_revision_separately(monkeypatch, tmp_path):
|
||||
"""An empty tokenizer_subdir targets the snapshot root and still honors
|
||||
its own revision."""
|
||||
from huggingface_hub import HfApi
|
||||
|
||||
from vllm_omni.engine.stage_init_utils import build_engine_args_dict
|
||||
|
||||
model_snapshot = tmp_path / "snapshots" / "model-rev"
|
||||
@@ -1875,12 +1858,12 @@ def test_build_engine_args_resolves_root_tokenizer_revision_separately(monkeypat
|
||||
tokenizer_snapshot.mkdir(parents=True, exist_ok=True)
|
||||
(tokenizer_snapshot / _SUBDIR_ARTIFACT["tokenizer"]).write_text("x")
|
||||
|
||||
def fake_snapshot_download(self, repo_id, **kwargs):
|
||||
def fake_snapshot_download(repo_id, **kwargs):
|
||||
if kwargs.get("revision") == "tok-rev":
|
||||
return str(tokenizer_snapshot)
|
||||
return str(model_snapshot)
|
||||
|
||||
monkeypatch.setattr(HfApi, "snapshot_download", fake_snapshot_download)
|
||||
patch_hf_snapshot_download(monkeypatch, fake_snapshot_download, hf_home=tmp_path)
|
||||
|
||||
stage_cfg = types.SimpleNamespace(
|
||||
stage_id=0,
|
||||
@@ -1902,19 +1885,17 @@ def test_build_engine_args_resolves_root_tokenizer_revision_separately(monkeypat
|
||||
|
||||
def test_build_engine_args_fails_closed_when_subdir_cannot_be_downloaded(monkeypatch, tmp_path):
|
||||
"""An undownloadable subfolder raises here instead of reaching HuggingFace."""
|
||||
from huggingface_hub import HfApi
|
||||
|
||||
from vllm_omni.engine.stage_init_utils import build_engine_args_dict
|
||||
|
||||
snapshot = tmp_path / "snapshots" / "deadbeef"
|
||||
_make_snapshot(snapshot, ["tokenizer"])
|
||||
|
||||
def fake_snapshot_download(self, repo_id, **kwargs):
|
||||
def fake_snapshot_download(repo_id, **kwargs):
|
||||
if kwargs.get("local_files_only"):
|
||||
return str(snapshot)
|
||||
raise OSError("offline")
|
||||
|
||||
monkeypatch.setattr(HfApi, "snapshot_download", fake_snapshot_download)
|
||||
patch_hf_snapshot_download(monkeypatch, fake_snapshot_download, hf_home=tmp_path)
|
||||
|
||||
stage_cfg = types.SimpleNamespace(
|
||||
stage_id=0,
|
||||
@@ -1927,16 +1908,14 @@ def test_build_engine_args_fails_closed_when_subdir_cannot_be_downloaded(monkeyp
|
||||
build_engine_args_dict(stage_cfg, "MiniMaxAI/MiniMax-Music3")
|
||||
|
||||
|
||||
def test_build_engine_args_fails_closed_on_cold_cache_instead_of_joining_repo_id(monkeypatch):
|
||||
def test_build_engine_args_fails_closed_on_cold_cache_instead_of_joining_repo_id(monkeypatch, tmp_path):
|
||||
"""With nothing cached, the stage must not join a subdir onto the repo id."""
|
||||
from huggingface_hub import HfApi
|
||||
|
||||
from vllm_omni.engine.stage_init_utils import build_engine_args_dict
|
||||
|
||||
def fake_snapshot_download(self, repo_id, **kwargs):
|
||||
def fake_snapshot_download(repo_id, **kwargs):
|
||||
raise OSError("offline")
|
||||
|
||||
monkeypatch.setattr(HfApi, "snapshot_download", fake_snapshot_download)
|
||||
patch_hf_snapshot_download(monkeypatch, fake_snapshot_download, hf_home=tmp_path)
|
||||
|
||||
stage_cfg = types.SimpleNamespace(
|
||||
stage_id=0,
|
||||
|
||||
@@ -55,6 +55,7 @@ def _build(
|
||||
stages: int = 1,
|
||||
running_counter: FakeRunningCounter | None = None,
|
||||
runtime_config: DuplexSessionRuntimeConfig | None = None,
|
||||
plugin=None,
|
||||
) -> tuple[DuplexOrchestrator, list[FakeStageClient], asyncio.Queue, asyncio.Queue]:
|
||||
clients = [FakeStageClient(stage_type="llm", final_output=index == stages - 1) for index in range(stages)]
|
||||
pools = _build_stage_pools(
|
||||
@@ -70,7 +71,7 @@ def _build(
|
||||
rpc_async_queue=rpc_q,
|
||||
stage_pools=pools,
|
||||
running_counter=running_counter,
|
||||
plugin=MiniCPMO45DuplexPlugin(_encode_audio),
|
||||
plugin=plugin or MiniCPMO45DuplexPlugin(_encode_audio),
|
||||
duplex_session_config=runtime_config or DuplexSessionRuntimeConfig(reaper_interval_s=0.01),
|
||||
model_config=None,
|
||||
)
|
||||
@@ -197,7 +198,8 @@ async def test_open_preregisters_the_stage0_request_and_close_releases_it() -> N
|
||||
assert request_state.session_owned is True
|
||||
assert request_state.session_id == SESSION_ID
|
||||
assert request_state.fence == DuplexFence(SESSION_ID)
|
||||
assert request_state.streaming.enabled is True
|
||||
# Set on submit from submission.resumable, not again at preregister.
|
||||
assert request_state.streaming.enabled is False
|
||||
# Preregistration reserves the id; nothing is running until an append submits.
|
||||
assert counter.value == 0
|
||||
assert clients[0].add_request_calls == []
|
||||
@@ -211,6 +213,18 @@ async def test_open_preregisters_the_stage0_request_and_close_releases_it() -> N
|
||||
assert orchestrator.session_manager.active_count() == 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_aura_ephemeral_preregister_disables_streaming() -> None:
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.plugin import AuraDuplexPlugin
|
||||
|
||||
orchestrator, _, rpc_q, _ = _build(plugin=AuraDuplexPlugin(_encode_audio))
|
||||
result = await _open(orchestrator, rpc_q)
|
||||
assert result.ok is True
|
||||
request_state = next(iter(orchestrator.request_states.values()))
|
||||
assert request_state.streaming.enabled is False
|
||||
await orchestrator.session_manager.shutdown()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_open_failure_rolls_back_session_and_reserved_request() -> None:
|
||||
orchestrator, _, rpc_q, _ = _build()
|
||||
@@ -275,6 +289,7 @@ async def test_append_submits_the_resumable_stage0_request_and_counts_it_running
|
||||
assert submitted.resumable is True
|
||||
assert submitted.sampling_params.max_tokens == 20
|
||||
request_state = orchestrator.request_states[request_id]
|
||||
assert request_state.streaming.enabled is True
|
||||
assert request_state.stage_fences[0] == DuplexFence(SESSION_ID)
|
||||
assert 0 in request_state.stage_submit_ts
|
||||
assert counter.value == 1
|
||||
@@ -390,6 +405,31 @@ async def test_forward_failure_closes_the_owning_session() -> None:
|
||||
assert types[-1] == "session.expired"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_aura_forward_failure_keeps_the_session() -> None:
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.plugin import AuraDuplexPlugin
|
||||
|
||||
orchestrator, clients, rpc_q, output_q = _build(stages=2, plugin=AuraDuplexPlugin(_encode_audio))
|
||||
await _open(orchestrator, rpc_q)
|
||||
request_id = next(iter(orchestrator.request_states))
|
||||
await _submit(orchestrator, _append_audio())
|
||||
request_state = orchestrator.request_states[request_id]
|
||||
session = orchestrator.session_manager.get(SESSION_ID)
|
||||
assert session is not None
|
||||
|
||||
absorbed = await orchestrator._handle_forward_failure(request_id, 1, request_state, ValueError("stale talker"))
|
||||
await _settle(orchestrator)
|
||||
|
||||
assert absorbed is True
|
||||
assert request_id not in orchestrator.request_states
|
||||
assert SESSION_ID in orchestrator.session_manager.runners
|
||||
assert session.state != DuplexSessionState.CLOSED
|
||||
types = [message.event.type for message in [output_q.get_nowait() for _ in range(output_q.qsize())]]
|
||||
assert "error" in types
|
||||
assert "session.expired" not in types
|
||||
await orchestrator.session_manager.shutdown()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_request_cleanup_failure_is_deferred_and_retried_by_the_reaper(monkeypatch) -> None:
|
||||
orchestrator, clients, rpc_q, _ = _build()
|
||||
@@ -560,3 +600,53 @@ async def test_turn_plugin_processes_multimodal_prompt_before_stage_submission(m
|
||||
assert not orchestrator.request_states[submitted.request_id].streaming.enabled
|
||||
finally:
|
||||
await _close(orchestrator, rpc_q)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_sentence_partial_does_not_legacy_forward_the_full_stage_output() -> None:
|
||||
from vllm_omni.engine.duplex.plugin import PartialStageForward
|
||||
|
||||
orchestrator, *_ = _build(stages=4)
|
||||
forwarded: list[object] = []
|
||||
|
||||
async def record_forward(req_id, stage_id, output, req_state, **kwargs):
|
||||
del req_id, stage_id, req_state, kwargs
|
||||
forwarded.append(output)
|
||||
|
||||
async def no_intercept(*args, **kwargs):
|
||||
del args, kwargs
|
||||
return False
|
||||
|
||||
orchestrator._forward_to_next_stage = record_forward # type: ignore[method-assign]
|
||||
orchestrator._intercept_stage_output = no_intercept # type: ignore[method-assign]
|
||||
orchestrator.async_chunk = True
|
||||
orchestrator._stage_receives_async_chunks = lambda stage_id: False # type: ignore[method-assign]
|
||||
|
||||
full = SimpleNamespace(request_id="r", finished=True, text="FULL")
|
||||
chunk = SimpleNamespace(request_id="r", finished=True, text="CHUNK")
|
||||
req_state = DuplexOrchestratorRequestState(
|
||||
request_id="r",
|
||||
final_stage_id=3,
|
||||
session_owned=True,
|
||||
sampling_params_list=[SimpleNamespace() for _ in range(4)],
|
||||
)
|
||||
orchestrator.plugin.plan_partial_stage_output = lambda *args, **kwargs: PartialStageForward( # type: ignore[method-assign]
|
||||
output=chunk, is_final_update=True
|
||||
)
|
||||
orchestrator.plugin.partial_stage_followup = lambda *args, **kwargs: None # type: ignore[method-assign]
|
||||
|
||||
await orchestrator._route_output(1, 0, full, req_state, None)
|
||||
|
||||
assert forwarded == [chunk]
|
||||
assert req_state.skip_legacy_stage_forward is False
|
||||
|
||||
forwarded.clear()
|
||||
orchestrator.plugin.plan_partial_stage_output = lambda *args, **kwargs: None # type: ignore[method-assign]
|
||||
await orchestrator._route_output(1, 0, full, req_state, None)
|
||||
|
||||
assert forwarded == [full]
|
||||
|
||||
|
||||
def test_default_plugin_declares_no_draining_stages() -> None:
|
||||
plugin = MiniCPMO45DuplexPlugin(_encode_audio)
|
||||
assert plugin.draining_stage_ids(stage_count=4) == frozenset()
|
||||
@@ -13,6 +13,7 @@ import asyncio
|
||||
import queue
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
import janus
|
||||
import pytest
|
||||
@@ -22,6 +23,7 @@ from vllm.v1.serial_utils import MsgpackEncoder
|
||||
|
||||
from vllm_omni.engine.messages import (
|
||||
AddCompanionRequestMessage,
|
||||
CollectiveRPCRequestMessage,
|
||||
EngineQueueMessage,
|
||||
ErrorMessage,
|
||||
ShutdownRequestMessage,
|
||||
@@ -1143,3 +1145,64 @@ async def test_diffusion_client_error_output_propagates_non_400_status(
|
||||
finally:
|
||||
orchestrator_fixture.request_sync_q.put_nowait(ShutdownRequestMessage())
|
||||
orchestrator_fixture.thread.join(timeout=5)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_control_rpc_failure_is_reported_to_the_caller_not_fatal() -> None:
|
||||
"""A control RPC that fails on one replica must come back as that
|
||||
replica's error result instead of raising out of _request_handler.
|
||||
"""
|
||||
|
||||
class _FailingClient(FakeStageClient):
|
||||
async def collective_rpc_async(self, *args, **kwargs):
|
||||
raise TimeoutError("outputs did not drain")
|
||||
|
||||
ok = FakeStageClient(stage_type="diffusion")
|
||||
ok.collective_rpc_async = AsyncMock(return_value=None)
|
||||
orchestrator, queues = _build_bare_orchestrator(
|
||||
_build_stage_pools([[ok], [_FailingClient(stage_type="diffusion")]])
|
||||
)
|
||||
try:
|
||||
await orchestrator._handle_collective_rpc(
|
||||
CollectiveRPCRequestMessage(
|
||||
rpc_id="rpc-1",
|
||||
method="pause_scheduler",
|
||||
args=(),
|
||||
kwargs={"mode": "keep"},
|
||||
stage_ids=[0, 1],
|
||||
)
|
||||
)
|
||||
|
||||
result = queues[2].async_q.get_nowait()
|
||||
assert result.rpc_id == "rpc-1"
|
||||
assert result.stage_ids == [0, 1]
|
||||
assert result.results[0] is None
|
||||
assert result.results[1]["supported"] is False
|
||||
assert "outputs did not drain" in result.results[1]["error"]
|
||||
finally:
|
||||
for q in queues:
|
||||
q.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_rpc_failure_capture_is_limited_to_pause_and_resume() -> None:
|
||||
"""Only pause/resume failures are reported as a result; every other RPC
|
||||
keeps propagating the way it does today.
|
||||
"""
|
||||
orchestrator, queues = _build_bare_orchestrator(_build_stage_pools([[FakeStageClient(stage_type="diffusion")]]))
|
||||
orchestrator.stage_pools[0].collective_rpc = AsyncMock(side_effect=TimeoutError("worker died"))
|
||||
|
||||
def _msg(rpc_id: str, method: str) -> CollectiveRPCRequestMessage:
|
||||
return CollectiveRPCRequestMessage(rpc_id=rpc_id, method=method, args=(), kwargs={}, stage_ids=[0])
|
||||
|
||||
try:
|
||||
await orchestrator._handle_collective_rpc(_msg("rpc-resume", "resume_scheduler"))
|
||||
result = queues[2].async_q.get_nowait()
|
||||
assert result.results[0]["supported"] is False
|
||||
assert "worker died" in result.results[0]["error"]
|
||||
|
||||
with pytest.raises(TimeoutError):
|
||||
await orchestrator._handle_collective_rpc(_msg("rpc-sleep", "sleep"))
|
||||
finally:
|
||||
for q in queues:
|
||||
q.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
|
||||
"""Event-driven orchestration loop (``VLLM_OMNI_EVENT_DRIVEN_ORCH=1``) tests.
|
||||
|
||||
Parity suite: re-runs the legacy orchestration scenarios from
|
||||
@@ -19,7 +19,10 @@ import pytest
|
||||
|
||||
from vllm_omni.engine.async_omni_engine import AsyncOmniEngine
|
||||
from vllm_omni.engine.messages import ShutdownRequestMessage
|
||||
from vllm_omni.engine.orchestrator import _event_driven_orch_enabled
|
||||
from vllm_omni.engine.orchestrator import (
|
||||
_event_driven_orch_default_for_pipeline,
|
||||
_event_driven_orch_enabled,
|
||||
)
|
||||
|
||||
from . import test_orchestrator as legacy
|
||||
from . import test_orchestrator_error_handling as legacy_errors
|
||||
@@ -125,6 +128,19 @@ def test_flag_parsing(monkeypatch) -> None:
|
||||
assert _event_driven_orch_enabled() is False
|
||||
|
||||
|
||||
def test_only_qwen3_tts_has_a_pipeline_default() -> None:
|
||||
assert _event_driven_orch_default_for_pipeline("qwen3_tts") is True
|
||||
for model_type in (None, "qwen3_omni_moe", "minicpmo_4_5", "moss_tts_delay"):
|
||||
assert _event_driven_orch_default_for_pipeline(model_type) is False
|
||||
|
||||
|
||||
def test_explicit_event_driven_value_overrides_pipeline_default(monkeypatch) -> None:
|
||||
monkeypatch.delenv("VLLM_OMNI_EVENT_DRIVEN_ORCH", raising=False)
|
||||
assert _event_driven_orch_enabled(default=True) is True
|
||||
monkeypatch.setenv("VLLM_OMNI_EVENT_DRIVEN_ORCH", "0")
|
||||
assert _event_driven_orch_enabled(default=True) is False
|
||||
|
||||
|
||||
def test_default_is_legacy_loop(monkeypatch) -> None:
|
||||
"""Without the env flag, the harness runs the legacy poll loop."""
|
||||
monkeypatch.delenv("VLLM_OMNI_EVENT_DRIVEN_ORCH", raising=False)
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import json
|
||||
import time
|
||||
|
||||
@@ -45,6 +48,8 @@ def test_note_loop_and_flush_json(tmp_path, monkeypatch):
|
||||
monitor.register_replica(0, 0)
|
||||
|
||||
monitor.note_loop(idle=False)
|
||||
monitor.set_dispatch_queue_size(9)
|
||||
monitor.set_dispatch_queue_size(7)
|
||||
monitor.note_loop(idle=True)
|
||||
|
||||
now[0] = 1.5
|
||||
@@ -54,10 +59,37 @@ def test_note_loop_and_flush_json(tmp_path, monkeypatch):
|
||||
assert payload["configured_window_s"] == monitor_mod._WINDOW_S
|
||||
assert payload["windows"]["loop_idle"] == [1]
|
||||
assert payload["windows"]["loop_active"] == [1]
|
||||
assert payload["windows"]["dispatch_queue_size"] == [7]
|
||||
assert payload["windows"]["dispatch_queue_high_water"] == [9]
|
||||
assert payload["replicas"]["stage=0,replica=0"]["outputs_queue_size"] == [5]
|
||||
assert payload["replicas"]["stage=0,replica=0"]["inflight"] == [10]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("drain", [False, True])
|
||||
def test_dispatch_backlog_carries_across_windows(tmp_path, monkeypatch, drain):
|
||||
out_path = tmp_path / "orch_monitor.json"
|
||||
monkeypatch.setenv("VLLM_OMNI_ORCH_MONITOR_PATH", str(out_path))
|
||||
now = [0.0]
|
||||
monkeypatch.setattr(time, "monotonic", lambda: now[0])
|
||||
monitor = OrchestratorMonitor(replica_sampler=lambda: {})
|
||||
monitor.set_dispatch_queue_size(3)
|
||||
monitor.set_dispatch_queue_size(1)
|
||||
|
||||
now[0] = monitor_mod._WINDOW_S
|
||||
monitor.note_loop(idle=False)
|
||||
if drain:
|
||||
monitor.set_dispatch_queue_size(0)
|
||||
now[0] += monitor_mod._WINDOW_S
|
||||
monitor.note_loop(idle=False)
|
||||
now[0] += monitor_mod._WINDOW_S
|
||||
monitor.flush()
|
||||
|
||||
windows = json.loads(out_path.read_text())["windows"]
|
||||
remaining = 0 if drain else 1
|
||||
assert windows["dispatch_queue_size"] == [1, remaining, remaining]
|
||||
assert windows["dispatch_queue_high_water"] == [3, 1, remaining]
|
||||
|
||||
|
||||
def test_register_replica_backfills_prior_windows(tmp_path, monkeypatch):
|
||||
out_path = tmp_path / "orch_monitor.json"
|
||||
monkeypatch.setenv("VLLM_OMNI_ORCH_MONITOR_PATH", str(out_path))
|
||||
|
||||
@@ -14,6 +14,7 @@ import pytest
|
||||
from vllm.outputs import CompletionOutput, RequestOutput
|
||||
from vllm.sampling_params import SamplingParams
|
||||
|
||||
from vllm_omni.engine.duplex_orchestrator import DuplexOrchestrator
|
||||
from vllm_omni.engine.orchestrator import (
|
||||
Orchestrator,
|
||||
OrchestratorRequestState,
|
||||
@@ -249,6 +250,41 @@ async def test_async_prewarm_skips_outgoing_only_stage(payload_sender_info) -> N
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_prewarm_skips_stage_with_custom_process_input_func() -> None:
|
||||
"""AURA Stage1 has asr2aura: must not be zero-prewarmed under async_chunk.
|
||||
|
||||
The custom-process-input gate lives on DuplexOrchestrator (AURA path), not
|
||||
the turn-based Orchestrator base.
|
||||
"""
|
||||
orchestrator = object.__new__(DuplexOrchestrator)
|
||||
stage0 = FakePrewarmPool("sender")
|
||||
stage1 = FakePrewarmPool("receiver") # would receive chunks if role alone decided
|
||||
stage1.stage_client = SimpleNamespace(custom_process_input_func=lambda *a, **k: None)
|
||||
stage2 = FakePrewarmPool("receiver")
|
||||
orchestrator.stage_pools = [stage0, stage1, stage2]
|
||||
orchestrator._emit_tx_edge = lambda **_kwargs: None
|
||||
orchestrator._on_stage_submitted = MagicMock()
|
||||
req_state = OrchestratorRequestState(
|
||||
request_id="req-prewarm-custom",
|
||||
prompt={"prompt_token_ids": [1, 2]},
|
||||
sampling_params_list=[SamplingParams(max_tokens=1) for _ in range(3)],
|
||||
final_stage_id=2,
|
||||
)
|
||||
|
||||
prewarmed = await orchestrator._prewarm_async_chunk_stages(
|
||||
"req-prewarm-custom",
|
||||
SimpleNamespace(prompt_token_ids=[1, 2], resumable=True),
|
||||
req_state,
|
||||
)
|
||||
|
||||
assert prewarmed is True
|
||||
assert stage1.submitted == []
|
||||
assert len(stage2.submitted) == 1
|
||||
assert 1 not in req_state.stage_submit_ts
|
||||
assert 2 in req_state.stage_submit_ts
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_route_forwards_to_outgoing_only_stage() -> None:
|
||||
orchestrator = object.__new__(Orchestrator)
|
||||
|
||||
@@ -17,7 +17,12 @@ from vllm.v1.engine.utils import EngineZmqAddresses
|
||||
|
||||
from vllm_omni.config.config_factory import StageConfigFactory
|
||||
from vllm_omni.config.omni_config import VllmOmniARStageConfig, VllmOmniDiffusionStageConfig
|
||||
from vllm_omni.config.stage_config import DuplexSessionRuntimeConfig, StageExecutionType, StagePipelineConfig
|
||||
from vllm_omni.config.stage_config import (
|
||||
DuplexSessionRuntimeConfig,
|
||||
PipelineConfig,
|
||||
StageExecutionType,
|
||||
StagePipelineConfig,
|
||||
)
|
||||
from vllm_omni.engine.async_omni_engine import AsyncOmniEngine
|
||||
from vllm_omni.engine.stage_engine_core_client import StageEngineCoreClientBase
|
||||
from vllm_omni.engine.stage_engine_startup import (
|
||||
@@ -393,6 +398,7 @@ class TestSingleStageModeDetection:
|
||||
stage_cfgs: list[Any] | None = None,
|
||||
resolved_config_path: str = "/fake/path",
|
||||
patch_deploy_config: bool = True,
|
||||
resolved_pipeline: PipelineConfig | None = None,
|
||||
**kwargs: Any,
|
||||
) -> AsyncOmniEngine:
|
||||
mock_stage_configs = stage_cfgs or [_make_stage_cfg(0)]
|
||||
@@ -407,10 +413,19 @@ class TestSingleStageModeDetection:
|
||||
"vllm_omni.engine.omni_engine_base.load_deploy_config",
|
||||
return_value=SimpleNamespace(duplex_session=DuplexSessionRuntimeConfig()),
|
||||
)
|
||||
|
||||
def resolve_stage_configs(engine, *args, **kwargs):
|
||||
if resolved_pipeline is not None:
|
||||
engine._config_resolution = SimpleNamespace(
|
||||
pipeline_config=resolved_pipeline, config_path=resolved_config_path
|
||||
)
|
||||
return resolved_config_path, mock_stage_configs
|
||||
|
||||
mocker.patch.object(
|
||||
AsyncOmniEngine,
|
||||
"_resolve_stage_configs",
|
||||
return_value=(resolved_config_path, mock_stage_configs),
|
||||
autospec=True,
|
||||
side_effect=resolve_stage_configs,
|
||||
)
|
||||
mocker.patch.object(AsyncOmniEngine, "_bootstrap_orchestrator")
|
||||
mock_thread_cls = mocker.patch("threading.Thread")
|
||||
@@ -435,6 +450,19 @@ class TestSingleStageModeDetection:
|
||||
)
|
||||
assert engine.single_stage_mode is True
|
||||
|
||||
@pytest.mark.parametrize("model_type, expected", [("qwen3_tts", True), ("qwen3_omni_moe", False)])
|
||||
def test_event_driven_default_uses_resolved_pipeline(self, mocker, model_type, expected):
|
||||
pipeline = PipelineConfig(
|
||||
model_type=model_type,
|
||||
stages=(StagePipelineConfig(stage_id=0, model_stage="a", final_output=True),),
|
||||
)
|
||||
engine = self._make_engine_no_thread(mocker, resolved_pipeline=pipeline)
|
||||
|
||||
StageConfigFactory.get_pipeline_config.assert_called_once_with(
|
||||
model="fake-model", trust_remote_code=False, deploy_config_path=None
|
||||
)
|
||||
assert engine._event_driven_orch_default is expected
|
||||
|
||||
def test_stage_id_kwarg_promotes_to_single_stage_mode(self, mocker: MockerFixture):
|
||||
engine = self._make_engine_no_thread(
|
||||
mocker,
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import pybase64 as base64
|
||||
|
||||
from vllm_omni.engine.duplex.config import DuplexCapabilities
|
||||
from vllm_omni.entrypoints.duplex.warmup import (
|
||||
_WARMUP_AUDIO_SECONDS,
|
||||
_WARMUP_FRAME_HEIGHT,
|
||||
_WARMUP_FRAME_WIDTH,
|
||||
_WARMUP_SAMPLE_RATE_HZ,
|
||||
_short_pcm_f32le_b64,
|
||||
_warmup_jpeg_b64,
|
||||
startup_warmup_kind,
|
||||
)
|
||||
|
||||
|
||||
class _Plugin:
|
||||
def __init__(self, required: frozenset[str]) -> None:
|
||||
self._required = required
|
||||
|
||||
def capabilities(self, *, max_sessions: int) -> DuplexCapabilities:
|
||||
del max_sessions
|
||||
return DuplexCapabilities(required_input_modalities=self._required)
|
||||
|
||||
|
||||
def test_video_required_model_warms_up_one_turn_by_default() -> None:
|
||||
plugin = _Plugin(frozenset({"video"}))
|
||||
assert startup_warmup_kind(plugin, 0) == "video_turn"
|
||||
|
||||
|
||||
def test_negative_warmup_frames_disables_the_video_turn() -> None:
|
||||
plugin = _Plugin(frozenset({"video"}))
|
||||
assert startup_warmup_kind(plugin, -1) is None
|
||||
|
||||
|
||||
def test_audio_primary_model_stays_opt_in() -> None:
|
||||
plugin = _Plugin(frozenset({"audio"}))
|
||||
assert startup_warmup_kind(plugin, 0) is None
|
||||
assert startup_warmup_kind(plugin, 4) == "silent_frames"
|
||||
|
||||
|
||||
def test_startup_turn_audio_is_short_and_not_silent() -> None:
|
||||
raw = base64.b64decode(_short_pcm_f32le_b64())
|
||||
assert len(raw) == int(_WARMUP_SAMPLE_RATE_HZ * _WARMUP_AUDIO_SECONDS) * 4
|
||||
assert any(raw)
|
||||
|
||||
|
||||
def test_startup_turn_frame_is_a_camera_sized_jpeg() -> None:
|
||||
from io import BytesIO
|
||||
|
||||
from PIL import Image
|
||||
|
||||
image = Image.open(BytesIO(base64.b64decode(_warmup_jpeg_b64())))
|
||||
assert image.size == (_WARMUP_FRAME_WIDTH, _WARMUP_FRAME_HEIGHT)
|
||||
assert image.format == "JPEG"
|
||||
@@ -1719,7 +1719,7 @@ def test_image_edit_parameter_pass(async_omni_test_client):
|
||||
img = Image.open(io.BytesIO(img_bytes))
|
||||
assert img.format.lower() == "jpeg"
|
||||
assert data["output_format"] == "jpeg"
|
||||
assert data["size"] == f"{img.width}x{img.height}"
|
||||
assert data["size"] == "64x64"
|
||||
|
||||
|
||||
def test_image_edit_layers_and_resolution(async_omni_test_client):
|
||||
@@ -1896,6 +1896,7 @@ def test_image_edit_parameter_default_single_stage(test_client):
|
||||
|
||||
assert captured_sampling_params.width == 24
|
||||
assert captured_sampling_params.height == 16
|
||||
assert (captured_sampling_params.height_not_provided, captured_sampling_params.width_not_provided) == (True, True)
|
||||
assert captured_sampling_params.num_outputs_per_prompt == 1
|
||||
assert captured_sampling_params.num_inference_steps == 4
|
||||
assert captured_sampling_params.guidance_scale == 7.5
|
||||
@@ -1913,6 +1914,40 @@ def test_image_edit_parameter_default_single_stage(test_client):
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_image_edit_explicit_size_marks_canvas_provided_single_stage(test_client):
|
||||
response = test_client.post(
|
||||
"/v1/images/edits",
|
||||
files=[("image", make_test_image_bytes((24, 16)))],
|
||||
data={"prompt": "hello world.", "size": "16x24"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
sampling = test_client.app.state.engine_client.captured_sampling_params_list[0]
|
||||
assert (sampling.height, sampling.width) == (24, 16)
|
||||
assert (sampling.height_not_provided, sampling.width_not_provided) == (False, False)
|
||||
|
||||
|
||||
def test_image_edit_response_size_reports_generated_image_single_stage(test_client):
|
||||
response = test_client.post(
|
||||
"/v1/images/edits",
|
||||
files=[("image", make_test_image_bytes((24, 16)))],
|
||||
data={"prompt": "hello world.", "size": "16x24"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["size"] == "64x64"
|
||||
|
||||
|
||||
def test_generate_images_response_size_reports_generated_image(test_client):
|
||||
response = test_client.post(
|
||||
"/v1/images/generations",
|
||||
json={"prompt": "a cat", "n": 1, "size": "1024x1024"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["size"] == "64x64"
|
||||
|
||||
|
||||
def test_image_edit_compression_jpeg(test_client):
|
||||
img_bytes_1 = make_test_image_bytes((16, 16))
|
||||
# uploadfile with image key
|
||||
|
||||
@@ -25,6 +25,7 @@ from fastapi.responses import JSONResponse
|
||||
from fastapi.testclient import TestClient
|
||||
from pydantic import ValidationError
|
||||
from pytest_mock import MockerFixture
|
||||
from vllm.entrypoints.serve import create_error_response
|
||||
from vllm.entrypoints.serve.engine.protocol import ErrorInfo, ErrorResponse
|
||||
|
||||
from vllm_omni.config.stage_config import StagePipelineConfig
|
||||
@@ -33,7 +34,6 @@ from vllm_omni.diffusion.sched.request_scheduler import RequestScheduler
|
||||
from vllm_omni.diffusion.sched.step_scheduler import StepScheduler
|
||||
from vllm_omni.entrypoints.omni_base import OmniEngineDeadError
|
||||
from vllm_omni.entrypoints.openai import api_server as api_server_module
|
||||
from vllm_omni.entrypoints.openai import errors as openai_errors
|
||||
from vllm_omni.entrypoints.openai import serving_speech as serving_speech_module
|
||||
from vllm_omni.entrypoints.openai.audio_utils_mixin import AudioMixin
|
||||
from vllm_omni.entrypoints.openai.protocol.audio import (
|
||||
@@ -3875,6 +3875,7 @@ def _make_api_server_request(handler, *, method: str = "POST", path: str = "/v1/
|
||||
app = FastAPI()
|
||||
app.state.openai_serving_speech = handler
|
||||
app.state.api_server_count = 1
|
||||
app.state.serving_tokenization = None
|
||||
scope = {
|
||||
"type": "http",
|
||||
"app": app,
|
||||
@@ -3889,23 +3890,6 @@ def _make_api_server_request(handler, *, method: str = "POST", path: str = "/v1/
|
||||
return Request(scope)
|
||||
|
||||
|
||||
def _patch_api_server_base(mocker: MockerFixture):
|
||||
def _fake_create_error_response(message, err_type="BadRequestError", status_code=400, param=None):
|
||||
return ErrorResponse(
|
||||
error=ErrorInfo(
|
||||
message=message,
|
||||
type=err_type,
|
||||
param=param,
|
||||
code=getattr(status_code, "value", status_code),
|
||||
)
|
||||
)
|
||||
|
||||
fake_base = mocker.MagicMock()
|
||||
fake_base.create_error_response.side_effect = _fake_create_error_response
|
||||
mocker.patch.object(openai_errors, "base", return_value=fake_base)
|
||||
return fake_base
|
||||
|
||||
|
||||
def _assert_openai_error_response(
|
||||
response: JSONResponse,
|
||||
*,
|
||||
@@ -3921,8 +3905,7 @@ def _assert_openai_error_response(
|
||||
assert message in body["error"]["message"]
|
||||
|
||||
|
||||
def test_api_server_list_voices_without_speech_handler_returns_404(mocker: MockerFixture):
|
||||
_patch_api_server_base(mocker)
|
||||
def test_api_server_list_voices_without_speech_handler_returns_404():
|
||||
raw_request = _make_api_server_request(None, method="GET")
|
||||
|
||||
response = asyncio.run(api_server_module.list_voices(raw_request))
|
||||
@@ -3933,7 +3916,6 @@ def test_api_server_list_voices_without_speech_handler_returns_404(mocker: Mocke
|
||||
|
||||
|
||||
def test_api_server_upload_voice_value_error_returns_400(mocker: MockerFixture):
|
||||
_patch_api_server_base(mocker)
|
||||
handler = mocker.MagicMock()
|
||||
handler.upload_voice = mocker.AsyncMock(side_effect=ValueError("Unsupported MIME type: audio/x-m4a"))
|
||||
raw_request = _make_api_server_request(handler)
|
||||
@@ -3951,8 +3933,7 @@ def test_api_server_upload_voice_value_error_returns_400(mocker: MockerFixture):
|
||||
_assert_openai_error_response(response, status_code=400, message="Unsupported MIME type")
|
||||
|
||||
|
||||
def test_api_server_upload_voice_without_speech_handler_returns_404(mocker: MockerFixture):
|
||||
_patch_api_server_base(mocker)
|
||||
def test_api_server_upload_voice_without_speech_handler_returns_404():
|
||||
raw_request = _make_api_server_request(None)
|
||||
|
||||
response = asyncio.run(
|
||||
@@ -3968,8 +3949,50 @@ def test_api_server_upload_voice_without_speech_handler_returns_404(mocker: Mock
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("has_speech_handler", [True, False])
|
||||
@pytest.mark.parametrize("method", ["GET", "POST", "DELETE"])
|
||||
def test_voice_routes_without_tokenization(mocker: MockerFixture, method: str, has_speech_handler: bool):
|
||||
handler = mocker.MagicMock() if has_speech_handler else None
|
||||
if handler is not None:
|
||||
handler._get_available_voices.return_value = []
|
||||
handler.uploaded_speakers = {}
|
||||
handler.delete_voice = mocker.AsyncMock(return_value=False)
|
||||
app = _make_api_server_request(handler).app
|
||||
app.add_api_route("/v1/audio/voices", api_server_module.list_voices, methods=["GET"])
|
||||
app.add_api_route("/v1/audio/voices", api_server_module.upload_voice, methods=["POST"])
|
||||
app.add_api_route("/v1/audio/voices/{name}", api_server_module.delete_voice, methods=["DELETE"])
|
||||
|
||||
with TestClient(app) as client:
|
||||
if method == "POST":
|
||||
response = client.post(
|
||||
"/v1/audio/voices",
|
||||
files={"consent": (None, "cons_test"), "name": (None, "probe")},
|
||||
)
|
||||
elif method == "DELETE":
|
||||
response = client.delete("/v1/audio/voices/missing")
|
||||
else:
|
||||
response = client.get("/v1/audio/voices")
|
||||
|
||||
if not has_speech_handler:
|
||||
status_code, err_type, message = 404, "NotFoundError", "The model does not support Speech API"
|
||||
elif method == "POST":
|
||||
status_code, err_type, message = (
|
||||
400,
|
||||
"BadRequestError",
|
||||
"Either 'audio_sample' or 'speaker_embedding' must be provided",
|
||||
)
|
||||
elif method == "DELETE":
|
||||
status_code, err_type, message = 404, "NotFoundError", "Voice 'missing' not found"
|
||||
else:
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"voices": [], "uploaded_voices": []}
|
||||
return
|
||||
|
||||
assert response.status_code == status_code
|
||||
assert response.json() == {"error": {"message": message, "type": err_type, "param": None, "code": status_code}}
|
||||
|
||||
|
||||
def test_api_server_upload_voice_without_input_returns_400(mocker: MockerFixture):
|
||||
_patch_api_server_base(mocker)
|
||||
raw_request = _make_api_server_request(mocker.MagicMock())
|
||||
|
||||
response = asyncio.run(
|
||||
@@ -3986,7 +4009,6 @@ def test_api_server_upload_voice_without_input_returns_400(mocker: MockerFixture
|
||||
|
||||
|
||||
def test_api_server_upload_voice_with_audio_and_embedding_returns_400(mocker: MockerFixture):
|
||||
_patch_api_server_base(mocker)
|
||||
raw_request = _make_api_server_request(mocker.MagicMock())
|
||||
|
||||
response = asyncio.run(
|
||||
@@ -4003,7 +4025,6 @@ def test_api_server_upload_voice_with_audio_and_embedding_returns_400(mocker: Mo
|
||||
|
||||
|
||||
def test_api_server_upload_voice_exception_returns_500(mocker: MockerFixture):
|
||||
_patch_api_server_base(mocker)
|
||||
handler = mocker.MagicMock()
|
||||
handler.upload_voice = mocker.AsyncMock(side_effect=RuntimeError("disk failed"))
|
||||
raw_request = _make_api_server_request(handler)
|
||||
@@ -4032,7 +4053,6 @@ def test_api_server_upload_voice_with_no_adapter(
|
||||
tmp_path: Path,
|
||||
):
|
||||
monkeypatch.setenv("SPEAKER_SAMPLES_DIR", str(tmp_path))
|
||||
_patch_api_server_base(mocker)
|
||||
engine_client = mocker.MagicMock()
|
||||
engine_client.errored = False
|
||||
engine_client.stage_configs = []
|
||||
@@ -4059,8 +4079,7 @@ def test_api_server_upload_voice_with_no_adapter(
|
||||
assert response.status_code == 200
|
||||
|
||||
|
||||
def test_api_server_delete_voice_without_speech_handler_returns_404(mocker: MockerFixture):
|
||||
_patch_api_server_base(mocker)
|
||||
def test_api_server_delete_voice_without_speech_handler_returns_404():
|
||||
raw_request = _make_api_server_request(None, method="DELETE", path="/v1/audio/voices/probe")
|
||||
|
||||
response = asyncio.run(api_server_module.delete_voice("probe", raw_request))
|
||||
@@ -4071,7 +4090,6 @@ def test_api_server_delete_voice_without_speech_handler_returns_404(mocker: Mock
|
||||
|
||||
|
||||
def test_api_server_delete_voice_value_error_returns_400(mocker: MockerFixture):
|
||||
_patch_api_server_base(mocker)
|
||||
handler = mocker.MagicMock()
|
||||
handler.delete_voice = mocker.AsyncMock(side_effect=ValueError("Invalid voice name"))
|
||||
raw_request = _make_api_server_request(handler, method="DELETE", path="/v1/audio/voices/probe")
|
||||
@@ -4082,7 +4100,6 @@ def test_api_server_delete_voice_value_error_returns_400(mocker: MockerFixture):
|
||||
|
||||
|
||||
def test_api_server_delete_voice_not_found_returns_404(mocker: MockerFixture):
|
||||
_patch_api_server_base(mocker)
|
||||
handler = mocker.MagicMock()
|
||||
handler.delete_voice = mocker.AsyncMock(return_value=False)
|
||||
raw_request = _make_api_server_request(handler, method="DELETE", path="/v1/audio/voices/missing")
|
||||
@@ -4098,7 +4115,6 @@ def test_api_server_delete_voice_not_found_returns_404(mocker: MockerFixture):
|
||||
|
||||
|
||||
def test_api_server_delete_voice_exception_returns_500(mocker: MockerFixture):
|
||||
_patch_api_server_base(mocker)
|
||||
handler = mocker.MagicMock()
|
||||
handler.delete_voice = mocker.AsyncMock(side_effect=RuntimeError("disk failed"))
|
||||
raw_request = _make_api_server_request(handler, method="DELETE", path="/v1/audio/voices/probe")
|
||||
@@ -4113,10 +4129,9 @@ def test_api_server_delete_voice_exception_returns_500(mocker: MockerFixture):
|
||||
)
|
||||
|
||||
|
||||
def test_api_server_create_speech_without_handler_returns_404(mocker: MockerFixture):
|
||||
fake_base = _patch_api_server_base(mocker)
|
||||
def test_api_server_create_speech_without_handler_returns_404():
|
||||
raw_request = _make_api_server_request(None, path="/v1/audio/speech")
|
||||
raw_request.app.state.serving_tokenization = fake_base
|
||||
raw_request.app.state.serving_tokenization = SimpleNamespace(create_error_response=create_error_response)
|
||||
request = OpenAICreateSpeechRequest(input="Hello")
|
||||
|
||||
response = asyncio.run(api_server_module.create_speech(request, raw_request))
|
||||
@@ -4126,10 +4141,9 @@ def test_api_server_create_speech_without_handler_returns_404(mocker: MockerFixt
|
||||
)
|
||||
|
||||
|
||||
def test_api_server_create_speech_batch_without_handler_returns_404(mocker: MockerFixture):
|
||||
fake_base = _patch_api_server_base(mocker)
|
||||
def test_api_server_create_speech_batch_without_handler_returns_404():
|
||||
raw_request = _make_api_server_request(None, path="/v1/audio/speech/batch")
|
||||
raw_request.app.state.serving_tokenization = fake_base
|
||||
raw_request.app.state.serving_tokenization = SimpleNamespace(create_error_response=create_error_response)
|
||||
request = BatchSpeechRequest(items=[SpeechBatchItem(input="hi")])
|
||||
|
||||
response = asyncio.run(api_server_module.create_speech_batch(request, raw_request))
|
||||
@@ -4194,11 +4208,10 @@ def test_api_server_create_speech_batch_omits_null_fields(mocker: MockerFixture)
|
||||
assert errored["error"] == "Input text cannot be empty"
|
||||
|
||||
|
||||
def test_api_server_create_audio_generate_without_handler_returns_404(mocker: MockerFixture):
|
||||
fake_base = _patch_api_server_base(mocker)
|
||||
def test_api_server_create_audio_generate_without_handler_returns_404():
|
||||
raw_request = _make_api_server_request(None, path="/v1/audio/generate")
|
||||
raw_request.app.state.openai_serving_audio_generate = None
|
||||
raw_request.app.state.serving_tokenization = fake_base
|
||||
raw_request.app.state.serving_tokenization = SimpleNamespace(create_error_response=create_error_response)
|
||||
request = OpenAICreateAudioGenerateRequest(input="a bird singing")
|
||||
|
||||
response = asyncio.run(api_server_module.create_audio_generate(request, raw_request))
|
||||
|
||||
@@ -25,6 +25,7 @@ def _make_omni(*, stage_types: list[str]) -> AsyncOmni:
|
||||
omni._paused = False
|
||||
omni._admitting = 0
|
||||
omni._hold_admission_until_resume = False
|
||||
omni._paused_stage_ids = set()
|
||||
omni._sleeping_tags = set()
|
||||
omni._stage_sleeping_tags = {}
|
||||
omni._level2_sleeping = False
|
||||
@@ -460,3 +461,225 @@ def test_partial_wake_does_not_skip_remaining_sleeping_stage():
|
||||
assert not omni._stage_sleeping_tags
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
# ───────────────────── diffusion pause_generation(mode="keep") ─────────────────────
|
||||
|
||||
|
||||
def _rpc_methods(omni: AsyncOmni) -> list[tuple[str, list[int] | None]]:
|
||||
return [(call.kwargs["method"], call.kwargs.get("stage_ids")) for call in omni.collective_rpc.await_args_list]
|
||||
|
||||
|
||||
@pytest.mark.cpu
|
||||
def test_diffusion_keep_routes_to_backend():
|
||||
async def run() -> None:
|
||||
omni = _make_omni(stage_types=["diffusion"])
|
||||
|
||||
await omni.pause_generation(mode="keep", clear_cache=False)
|
||||
|
||||
omni.collective_rpc.assert_awaited_once_with(
|
||||
method="pause_scheduler",
|
||||
args=(),
|
||||
kwargs={"mode": "keep"},
|
||||
stage_ids=[0],
|
||||
)
|
||||
assert await omni.is_paused() is True
|
||||
assert omni._hold_admission_until_resume is True
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
@pytest.mark.cpu
|
||||
@pytest.mark.parametrize(
|
||||
"pause_kwargs",
|
||||
[
|
||||
{},
|
||||
{"mode": "abort"},
|
||||
{"mode": "wait"},
|
||||
{"mode": "keep", "wait_for_inflight_requests": True},
|
||||
],
|
||||
)
|
||||
def test_diffusion_non_keep_modes_pause_frontend_only(pause_kwargs):
|
||||
async def run() -> None:
|
||||
omni = _make_omni(stage_types=["diffusion"])
|
||||
omni.reset_prefix_cache = AsyncMock(return_value=True)
|
||||
omni.reset_mm_cache = AsyncMock()
|
||||
omni.reset_encoder_cache = AsyncMock()
|
||||
|
||||
await omni.pause_generation(**pause_kwargs)
|
||||
assert await omni.is_paused() is True
|
||||
omni.collective_rpc.assert_not_awaited()
|
||||
|
||||
await omni.resume_generation()
|
||||
omni.collective_rpc.assert_not_awaited()
|
||||
assert await omni.is_paused() is False
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
@pytest.mark.cpu
|
||||
def test_mixed_engine_keep_sends_engine_core_and_diffusion_pauses():
|
||||
async def run() -> None:
|
||||
omni = _make_omni(stage_types=["llm", "diffusion"])
|
||||
omni.reset_prefix_cache = AsyncMock(return_value=True)
|
||||
omni.reset_mm_cache = AsyncMock()
|
||||
omni.reset_encoder_cache = AsyncMock()
|
||||
|
||||
await omni.pause_generation(mode="keep", clear_cache=True)
|
||||
|
||||
assert omni.collective_rpc.await_args_list[0].kwargs == {
|
||||
"method": "pause_scheduler",
|
||||
"args": (),
|
||||
"kwargs": {"mode": "keep", "clear_cache": True},
|
||||
"stage_ids": [0],
|
||||
}
|
||||
assert omni.collective_rpc.await_args_list[1].kwargs == {
|
||||
"method": "pause_scheduler",
|
||||
"args": (),
|
||||
"kwargs": {"mode": "keep"},
|
||||
"stage_ids": [1],
|
||||
}
|
||||
# The frontend cache reset still runs after the backend pauses.
|
||||
omni.reset_prefix_cache.assert_awaited_once()
|
||||
|
||||
await omni.resume_generation()
|
||||
assert _rpc_methods(omni)[2:] == [("resume_scheduler", [0]), ("resume_scheduler", [1])]
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
@pytest.mark.cpu
|
||||
def test_keep_targets_only_requested_diffusion_stages():
|
||||
async def run() -> None:
|
||||
omni = _make_omni(stage_types=["diffusion", "diffusion"])
|
||||
|
||||
await omni.pause_generation(mode="keep", clear_cache=False, stage_ids=[1])
|
||||
assert _rpc_methods(omni) == [("pause_scheduler", [1])]
|
||||
|
||||
await omni.resume_generation(stage_ids=[0])
|
||||
assert _rpc_methods(omni) == [("pause_scheduler", [1])]
|
||||
# Stage 1's scheduler is still closed: admission must stay closed too,
|
||||
# otherwise new requests queue on a stage that will not schedule them.
|
||||
assert await omni.is_paused() is True
|
||||
|
||||
await omni.resume_generation(stage_ids=[1])
|
||||
assert _rpc_methods(omni) == [("pause_scheduler", [1]), ("resume_scheduler", [1])]
|
||||
assert await omni.is_paused() is False
|
||||
|
||||
await omni.resume_generation()
|
||||
assert len(_rpc_methods(omni)) == 2
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
@pytest.mark.cpu
|
||||
def test_keep_then_sleep_wake_resume_keeps_admission_paused_until_resume():
|
||||
async def run() -> None:
|
||||
omni = _make_omni(stage_types=["diffusion"])
|
||||
omni.reset_prefix_cache = AsyncMock(return_value=True)
|
||||
omni.reset_encoder_cache = AsyncMock()
|
||||
omni.collective_rpc = AsyncMock(
|
||||
side_effect=lambda **kw: [OmniACK(task_id="t", status="SUCCESS", stage_id=0, rank=0)]
|
||||
if kw["method"] in {"handle_sleep_task", "handle_wake_task"}
|
||||
else [None]
|
||||
)
|
||||
|
||||
await omni.pause_generation(mode="keep", clear_cache=False)
|
||||
await omni.sleep(level=1)
|
||||
await omni.wake_up()
|
||||
assert await omni.is_paused() is True
|
||||
|
||||
await omni.resume_generation()
|
||||
assert await omni.is_paused() is False
|
||||
assert [m for m, _ in _rpc_methods(omni)] == [
|
||||
"pause_scheduler",
|
||||
"handle_sleep_task",
|
||||
"handle_wake_task",
|
||||
"resume_scheduler",
|
||||
]
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
@pytest.mark.cpu
|
||||
@pytest.mark.parametrize(
|
||||
"failure",
|
||||
[
|
||||
AsyncMock(side_effect=NotImplementedError("request-level execution only")),
|
||||
AsyncMock(return_value=[{"supported": False, "error": "TimeoutError: outputs did not drain"}]),
|
||||
],
|
||||
)
|
||||
def test_keep_failure_surfaces_and_leaves_explicit_resume_possible(failure):
|
||||
async def run() -> None:
|
||||
omni = _make_omni(stage_types=["diffusion"])
|
||||
omni.collective_rpc = failure
|
||||
|
||||
with pytest.raises((NotImplementedError, RuntimeError)):
|
||||
await omni.pause_generation(mode="keep", clear_cache=False)
|
||||
|
||||
assert await omni.is_paused() is True
|
||||
assert omni._paused_stage_ids == {0}
|
||||
|
||||
omni.collective_rpc = AsyncMock(return_value=[None])
|
||||
await omni.resume_generation()
|
||||
omni.collective_rpc.assert_awaited_once_with(
|
||||
method="resume_scheduler",
|
||||
args=(),
|
||||
kwargs=None,
|
||||
stage_ids=[0],
|
||||
)
|
||||
assert await omni.is_paused() is False
|
||||
assert omni._paused_stage_ids == set()
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
@pytest.mark.cpu
|
||||
def test_resume_failure_keeps_admission_paused_and_target_recorded():
|
||||
async def run() -> None:
|
||||
omni = _make_omni(stage_types=["diffusion"])
|
||||
await omni.pause_generation(mode="keep", clear_cache=False)
|
||||
|
||||
omni.collective_rpc = AsyncMock(return_value=[{"error": "replica gone"}])
|
||||
with pytest.raises(RuntimeError, match="resume_scheduler failed"):
|
||||
await omni.resume_generation()
|
||||
|
||||
assert await omni.is_paused() is True
|
||||
assert omni._paused_stage_ids == {0}
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
@pytest.mark.cpu
|
||||
@pytest.mark.parametrize("first, second", [([1], [0]), ([0], [1])])
|
||||
def test_mixed_engine_partial_resume_keeps_admission_paused(first, second):
|
||||
async def run() -> None:
|
||||
omni = _make_omni(stage_types=["llm", "diffusion"])
|
||||
await omni.pause_generation(mode="keep", clear_cache=False)
|
||||
|
||||
await omni.resume_generation(stage_ids=first)
|
||||
assert await omni.is_paused() is True
|
||||
|
||||
await omni.resume_generation(stage_ids=second)
|
||||
assert await omni.is_paused() is False
|
||||
assert _rpc_methods(omni)[2:] == [("resume_scheduler", first), ("resume_scheduler", second)]
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
@pytest.mark.cpu
|
||||
def test_two_ar_stages_partial_resume_keeps_admission_paused():
|
||||
async def run() -> None:
|
||||
omni = _make_omni(stage_types=["llm", "llm"])
|
||||
omni.reset_prefix_cache = AsyncMock(return_value=True)
|
||||
omni.reset_mm_cache = AsyncMock()
|
||||
omni.reset_encoder_cache = AsyncMock()
|
||||
await omni.pause_generation(mode="abort")
|
||||
|
||||
await omni.resume_generation(stage_ids=[0])
|
||||
assert await omni.is_paused() is True
|
||||
|
||||
await omni.resume_generation(stage_ids=[1])
|
||||
assert await omni.is_paused() is False
|
||||
|
||||
asyncio.run(run())
|
||||
@@ -15,7 +15,10 @@ import pytest
|
||||
from pytest_mock import MockerFixture
|
||||
from vllm.v1.engine.utils import EngineZmqAddresses
|
||||
|
||||
from vllm_omni.config.omni_config import VllmOmniDiffusionStageConfig
|
||||
from vllm_omni.config.omni_config import (
|
||||
VllmOmniDiffusionStageConfig,
|
||||
normalize_and_validate_diffusion_engine_ingress_kwargs,
|
||||
)
|
||||
from vllm_omni.config.resolver import OmniConfigResolution
|
||||
from vllm_omni.engine.stage_engine_startup import StageReplicaResources
|
||||
from vllm_omni.engine.stage_runtime import StageEngineLaunch
|
||||
@@ -87,6 +90,26 @@ def _parse_serve_args(argv: list[str]) -> TrackingNamespace:
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
def test_no_guardrails_is_only_forwarded_as_model_config(mocker: MockerFixture) -> None:
|
||||
"""The CLI alias must not reach the strict diffusion config validator."""
|
||||
parser = TrackingArgumentParser()
|
||||
subparsers = parser.add_subparsers(dest="subparser")
|
||||
OmniServeCommand().subparser_init(subparsers)
|
||||
args = parser.parse_args(["serve", "fake-model", "--omni", "--no-guardrails"])
|
||||
assert args.get_explicit_kwargs_dict()["no_guardrails"] is True
|
||||
|
||||
# Keep the real CLI parser and config validator, but do not start a server.
|
||||
args.headless = True
|
||||
mocker.patch.dict("os.environ", {"VLLM_DISABLE_LOG_LOGO": "1"})
|
||||
mocker.patch("vllm_omni.entrypoints.cli.serve.run_headless")
|
||||
OmniServeCommand.cmd(args)
|
||||
|
||||
explicit = args.get_explicit_kwargs_dict()
|
||||
normalized = normalize_and_validate_diffusion_engine_ingress_kwargs(explicit, stage_id=0)
|
||||
assert normalized["model_config"]["guardrails"] is False
|
||||
assert "no_guardrails" not in explicit
|
||||
|
||||
|
||||
def test_omni_serve_requires_model_when_none_provided() -> None:
|
||||
"""Regression for https://github.com/vllm-project/vllm-omni/issues/4158:
|
||||
``vllm serve --omni`` with no model must fail fast instead of silently
|
||||
|
||||
@@ -113,12 +113,23 @@ def test_qwen_config_does_not_inject_reference_voice():
|
||||
assert '"profile": "qwen3-turn"' in page
|
||||
assert '"adapter": "vad"' in page
|
||||
assert '"refAudio": null' in page
|
||||
for name in ("common", "minicpm_native", "qwen3_turn"):
|
||||
for name in ("common", "minicpm_native", "qwen3_turn", "aura_ptt"):
|
||||
assert client.get(f"/static/profiles/{name}.js").status_code == 200
|
||||
with pytest.raises(ValueError, match="ref-audio"):
|
||||
build_app(profile="qwen3-turn", ref_audio="unused.wav")
|
||||
|
||||
|
||||
def test_aura_ptt_config_defaults_and_rejects_ref_audio():
|
||||
client = TestClient(build_app(profile="aura-ptt", model="aurateam/AURA"))
|
||||
page = client.get("/").text
|
||||
assert '"profile": "aura-ptt"' in page
|
||||
assert '"refAudio": null' in page
|
||||
assert "aura_ptt.js" in page
|
||||
assert 'id="pttButton"' in page
|
||||
with pytest.raises(ValueError, match="ref-audio"):
|
||||
build_app(profile="aura-ptt", ref_audio="unused.wav")
|
||||
|
||||
|
||||
def test_config_cannot_close_its_script_element():
|
||||
page = TestClient(build_app(model="</script><script>alert(1)</script>")).get("/").text
|
||||
assert "</script><script>alert(1)" not in page
|
||||
|
||||
@@ -240,3 +240,18 @@ def test_playback_worklet_fades_terminal_drain_to_zero():
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
|
||||
|
||||
def test_aura_camera_preview_size_is_not_shared() -> None:
|
||||
aura = (STATIC_ROOT / "profiles" / "aura_ptt.js").read_text(encoding="utf-8")
|
||||
app = (STATIC_ROOT / "app.js").read_text(encoding="utf-8")
|
||||
minicpm = (STATIC_ROOT / "profiles" / "minicpm_native.js").read_text(encoding="utf-8")
|
||||
qwen = (STATIC_ROOT / "profiles" / "qwen3_turn.js").read_text(encoding="utf-8")
|
||||
html = (APP_ROOT / "index.html").read_text(encoding="utf-8")
|
||||
|
||||
assert "cameraPreviewLarge: true" in aura
|
||||
assert "cameraPreviewLarge" not in minicpm
|
||||
assert "cameraPreviewLarge" not in qwen
|
||||
assert "profile.cameraPreviewLarge" in app
|
||||
assert "camera-preview-break" not in app
|
||||
assert "width:96px;height:72px" in html
|
||||
@@ -5,7 +5,7 @@ const path = require('node:path');
|
||||
const vm = require('node:vm');
|
||||
const root = path.resolve(__dirname, '../../examples/online_serving/realtime_web/app/static');
|
||||
const context = vm.createContext({ URL });
|
||||
for (const name of ['common', 'minicpm_native', 'qwen3_turn']) {
|
||||
for (const name of ['common', 'minicpm_native', 'qwen3_turn', 'aura_ptt']) {
|
||||
vm.runInContext(fs.readFileSync(path.join(root, `profiles/${name}.js`), 'utf8'), context);
|
||||
}
|
||||
const profiles = context.OmniRealtimeProfiles;
|
||||
@@ -83,6 +83,7 @@ function shell(profileName, adapter = 'stt', options = {}) {
|
||||
class Element {
|
||||
constructor() { this.style = {}; this.listeners = {}; this.children = []; this.value = ''; this.textContent = ''; this.classList = { add() {}, remove() {}, toggle() {} }; }
|
||||
addEventListener(name, callback) { this.listeners[name] = callback; }
|
||||
closest() { return null; }
|
||||
append(...children) { this.children.push(...children); }
|
||||
appendChild(child) { this.children.push(child); }
|
||||
replaceChildren() { this.children = []; }
|
||||
@@ -149,15 +150,16 @@ function shell(profileName, adapter = 'stt', options = {}) {
|
||||
atob: (value) => Buffer.from(value, 'base64').toString('binary'),
|
||||
});
|
||||
ctx.window = ctx;
|
||||
for (const name of ['common', 'minicpm_native', 'qwen3_turn']) {
|
||||
for (const name of ['common', 'minicpm_native', 'qwen3_turn', 'aura_ptt']) {
|
||||
vm.runInContext(fs.readFileSync(path.join(root, `profiles/${name}.js`), 'utf8'), ctx);
|
||||
}
|
||||
// Expose closure controls only in the test VM; production has no test API.
|
||||
const source = fs.readFileSync(path.join(root, 'app.js'), 'utf8').replace(/\}\)\(\);\s*$/, `
|
||||
globalThis.testUI = { startSession, stopSession, handleEvent, playbackDrained,
|
||||
microphoneUploadEnabled, flushCapture, awaitQueue: () => audioChain,
|
||||
microphoneUploadEnabled, flushCapture, setPttHeld, awaitQueue: () => audioChain,
|
||||
capture() { pendingCapture.push(new Int16Array([100, 200])); },
|
||||
state() { return { running, connectionReady, assistantActive }; }
|
||||
setPendingFrame(frame) { cameraPendingFrame = frame; if (profile.stickyCamera) cameraLastFrame = frame; },
|
||||
state() { return { running, connectionReady, assistantActive, pttHeld }; }
|
||||
};
|
||||
})();`);
|
||||
vm.runInContext(source, ctx);
|
||||
@@ -191,6 +193,7 @@ test('shared shell STT sends final commit and starts a fresh second turn only af
|
||||
assert.equal(app.ui.microphoneUploadEnabled(), true);
|
||||
assert.equal(app.elements.get('cameraButton').hidden, true);
|
||||
assert.equal(app.sockets.flatMap(s => s.sent).some(e => e.type === 'playback.ack'), false);
|
||||
assert.equal(app.elements.get('pttButton').hidden, true);
|
||||
await app.ui.stopSession({ terminal: false });
|
||||
});
|
||||
|
||||
@@ -247,6 +250,8 @@ test('an interrupted response disarms the turn watchdog it left armed', async ()
|
||||
test('MiniCPM retains microphone upload while speaking and acknowledges speaker drain', async () => {
|
||||
const app = shell('minicpm-native');
|
||||
await app.ui.startSession();
|
||||
assert.equal(app.elements.get('pttButton').hidden, true);
|
||||
assert.equal(app.elements.get('sendTurnButton').hidden, true);
|
||||
await app.ui.handleEvent({ type: 'response.speak', response_id: 'native-r1' });
|
||||
assert.equal(app.ui.microphoneUploadEnabled(), true);
|
||||
await app.ui.handleEvent({ type: 'response.output_audio.delta', delta: 'AAAAAA==', response_id: 'native-r1' });
|
||||
@@ -428,6 +433,150 @@ test('the camera retires its oldest image instead of exhausting the session budg
|
||||
assert.equal(plain(p.imageMessages('JPEG')).length, 1);
|
||||
});
|
||||
|
||||
test('AURA PTT profile sets duplex, is_speech append, commit on release, and shell flags', () => {
|
||||
const aura = profiles['aura-ptt']();
|
||||
const url = new URL(aura.url({ ...config, model: 'aurateam/AURA' }, 'http://localhost/'));
|
||||
assert.equal(url.searchParams.get('duplex'), '1');
|
||||
assert.equal(url.searchParams.get('model'), 'aurateam/AURA');
|
||||
assert.equal(aura.pushToTalk, true);
|
||||
assert.equal(aura.clientCommit, false);
|
||||
assert.equal(aura.camera, true);
|
||||
assert.equal(aura.stickyCamera, true);
|
||||
assert.equal(aura.cameraIntervalMs, 500);
|
||||
assert.equal(aura.visionFollowWhileSpeaking, true);
|
||||
assert.equal(aura.halfDuplex, false);
|
||||
assert.equal(aura.playbackAck, true);
|
||||
assert.equal(aura.append('PCM', 'JPEG', { isSpeech: true }).is_speech, true);
|
||||
assert.equal(aura.append('PCM', 'JPEG', { isSpeech: false }).is_speech, false);
|
||||
assert.equal(aura.append('PCM', 'JPEG', { isSpeech: false }).video_frames[0], 'JPEG');
|
||||
assert.deepEqual(plain(aura.commitMessages()), [
|
||||
{ type: 'input_audio_buffer.commit', create_response: true },
|
||||
]);
|
||||
assert.equal(aura.ack('r1', 50).type, 'playback.ack');
|
||||
const [update] = aura.initialMessages({}, 'Be brief');
|
||||
assert.equal(update.session.instructions, 'Be brief');
|
||||
assert.equal(update.session.extra_body.auto_response, true);
|
||||
});
|
||||
|
||||
test('AURA does not open a second bubble for the same sentence after response.done', async () => {
|
||||
const app = shell('aura-ptt');
|
||||
await app.ui.startSession();
|
||||
const sentence = '你好,我看到一个戴眼镜、穿黑T恤的男生正对着镜头说话呢。';
|
||||
await app.ui.handleEvent({
|
||||
type: 'response.output_audio_transcript.delta', response_id: 'r1', delta: sentence,
|
||||
});
|
||||
await app.ui.handleEvent({ type: 'response.done', response_id: 'r1' });
|
||||
await app.ui.handleEvent({
|
||||
type: 'response.output_audio_transcript.done', response_id: 'r2', transcript: sentence,
|
||||
});
|
||||
const turns = [...app.elements.get('conversation').children].filter((row) => row.children.length);
|
||||
assert.equal(turns.length, 1);
|
||||
assert.equal(turns[0].children[1].textContent, sentence);
|
||||
await app.ui.stopSession({ terminal: false });
|
||||
});
|
||||
|
||||
function visionAppends(app) {
|
||||
return app.sockets[0].sent.filter(e => e.type === 'input_audio_buffer.append' && e.is_speech === false);
|
||||
}
|
||||
|
||||
test('AURA shell holds speech until PTT and opens one vision turn per two frames', async () => {
|
||||
const app = shell('aura-ptt');
|
||||
await app.ui.startSession();
|
||||
assert.equal(app.elements.get('pttButton').hidden, false);
|
||||
assert.equal(app.elements.get('sendTurnButton').hidden, true);
|
||||
assert.equal(app.elements.get('cameraButton').hidden, false);
|
||||
assert.equal(app.ui.microphoneUploadEnabled(), false);
|
||||
|
||||
app.ui.capture();
|
||||
app.ui.flushCapture();
|
||||
assert.equal(app.sockets[0].sent.some(e => e.type === 'input_audio_buffer.append'), false);
|
||||
|
||||
app.ui.setPendingFrame('IDLE1');
|
||||
app.ui.flushCapture();
|
||||
assert.equal(visionAppends(app).length, 0, 'one frame must not open a turn');
|
||||
app.ui.setPendingFrame('IDLE2');
|
||||
app.ui.flushCapture();
|
||||
const idle = visionAppends(app).at(-1);
|
||||
assert.equal(idle.is_speech, false);
|
||||
assert.deepEqual(idle.video_frames, ['IDLE1', 'IDLE2'], 'two frames gate the turn and both go out as one clip');
|
||||
assert.equal(app.sockets[0].sent.at(-1).type, 'input_audio_buffer.commit');
|
||||
assert.equal(app.ui.state().assistantActive, false);
|
||||
|
||||
app.ui.setPttHeld(true);
|
||||
assert.equal(app.ui.microphoneUploadEnabled(), true);
|
||||
app.ui.setPendingFrame('FRAME1');
|
||||
app.ui.capture();
|
||||
app.ui.flushCapture();
|
||||
const speech = app.sockets[0].sent.find(e => e.type === 'input_audio_buffer.append' && e.is_speech === true);
|
||||
assert.equal(speech.video_frames[0], 'FRAME1');
|
||||
assert.equal(visionAppends(app).length, 1, 'speech must not wait for a second frame');
|
||||
|
||||
app.ui.setPttHeld(false);
|
||||
assert.equal(app.sockets[0].sent.at(-1).type, 'input_audio_buffer.commit');
|
||||
assert.equal(app.ui.state().pttHeld, false);
|
||||
|
||||
await app.ui.handleEvent({ type: 'response.created', response: { id: 'aura-r1' } });
|
||||
app.ui.setPendingFrame('LOCKED1');
|
||||
app.ui.flushCapture();
|
||||
app.ui.setPendingFrame('LOCKED2');
|
||||
app.ui.flushCapture();
|
||||
assert.equal(visionAppends(app).length, 1, 'open text turn blocks the next vision commit');
|
||||
|
||||
await app.ui.handleEvent({
|
||||
type: 'response.output_audio_transcript.done', response_id: 'aura-r1', transcript: '看到了。',
|
||||
});
|
||||
assert.equal(app.ui.state().assistantActive, true, 'text end must not wait for playback');
|
||||
app.ui.flushCapture();
|
||||
assert.deepEqual(visionAppends(app).at(-1).video_frames, ['LOCKED1', 'LOCKED2']);
|
||||
assert.equal(app.sockets[0].sent.at(-1).type, 'input_audio_buffer.commit');
|
||||
|
||||
await app.ui.handleEvent({ type: 'response.created', response: { id: 'aura-r2' } });
|
||||
app.ui.setPendingFrame('SILENT1');
|
||||
app.ui.flushCapture();
|
||||
app.ui.setPendingFrame('SILENT2');
|
||||
app.ui.flushCapture();
|
||||
assert.equal(visionAppends(app).length, 2);
|
||||
await app.ui.handleEvent({ type: 'response.listen', response_id: 'aura-r2' });
|
||||
app.ui.flushCapture();
|
||||
assert.deepEqual(visionAppends(app).at(-1).video_frames, ['SILENT1', 'SILENT2']);
|
||||
await app.ui.stopSession({ terminal: false });
|
||||
});
|
||||
|
||||
test('AURA hold-to-talk stops local playback and does not cancel the response', async () => {
|
||||
const app = shell('aura-ptt', 'stt', { realPlayback: true });
|
||||
await app.ui.startSession();
|
||||
receive(app, { type: 'response.created', response: { id: 'old' } });
|
||||
receive(app, audioChunk('old'));
|
||||
await app.ui.awaitQueue();
|
||||
const player = app.nodes.find(node => node.name === 'fullduplex-pcm-playback').player;
|
||||
for (let index = 0; index < 75; index++) renderPlayback(player);
|
||||
assert.ok(renderPlayback(player).some(sample => sample !== 0));
|
||||
const sentBefore = app.sockets[0].sent.length;
|
||||
app.ui.setPttHeld(true);
|
||||
assertSilent(player);
|
||||
const extra = app.sockets[0].sent.slice(sentBefore);
|
||||
assert.ok(extra.every(event => event.type === 'playback.ack'), 'hold must not abort the server response');
|
||||
receive(app, audioChunk('old'));
|
||||
await app.ui.awaitQueue();
|
||||
assertSilent(player);
|
||||
await app.ui.stopSession({ terminal: false });
|
||||
});
|
||||
|
||||
test('AURA sticky camera reuses the last frame on speech without a fresh pending', async () => {
|
||||
const app = shell('aura-ptt');
|
||||
await app.ui.startSession();
|
||||
app.ui.setPendingFrame('STICKY');
|
||||
app.ui.setPttHeld(true);
|
||||
app.ui.capture();
|
||||
app.ui.flushCapture();
|
||||
assert.equal(app.sockets[0].sent.at(-1).video_frames[0], 'STICKY');
|
||||
// Pending cleared; sticky last frame still available for the next speech flush.
|
||||
app.ui.capture();
|
||||
app.ui.flushCapture();
|
||||
assert.equal(app.sockets[0].sent.at(-1).video_frames[0], 'STICKY');
|
||||
await app.ui.stopSession({ terminal: false });
|
||||
});
|
||||
|
||||
// Exercise the real WebSocket dispatch queue together with the actual playback
|
||||
// processor: sending a clear message alone does not prove the speaker is silent.
|
||||
function receive(app, event) {
|
||||
|
||||
@@ -3,49 +3,10 @@
|
||||
|
||||
"""Shared, importable test helper utilities.
|
||||
|
||||
Submodules (``assertions``, ``clean``, ``client``, ``media``, ``runtime``, …) are imported
|
||||
Submodules (``assertions``, ``clean``, ``client``, ``media``, ``mock``, ``runtime``, …) are imported
|
||||
explicitly by callers. Unit tests for these helpers live under ``tests/``.
|
||||
Avoid star-importing everything here: that ran before refactor only inside the
|
||||
old monolithic ``conftest``; a greedy ``__init__`` changes import order and can
|
||||
affect in-process Omni (``OmniRunner`` / offline e2e) vs subprocess-based
|
||||
``OmniServer`` tests.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def skip_if_gated_repo_inaccessible(
|
||||
repo_id: str,
|
||||
*,
|
||||
revision: str | None = None,
|
||||
filename: str = "config.json",
|
||||
) -> None:
|
||||
"""Skip the test if a gated HuggingFace repo is not accessible.
|
||||
|
||||
Tries to download ``filename`` via ``hf_hub_download``, which performs an
|
||||
actual file-access check (unlike ``HfApi().model_info()``
|
||||
that only checks metadata). If the token has metadata access but not
|
||||
file-download access, ``hf_hub_download`` will raise ``GatedRepoError``
|
||||
and we skip cleanly.
|
||||
"""
|
||||
try:
|
||||
from huggingface_hub.errors import GatedRepoError, RepositoryNotFoundError
|
||||
|
||||
from vllm_omni.transformers_utils.repo_utils import hf_api
|
||||
except Exception:
|
||||
return
|
||||
try:
|
||||
hf_api().hf_hub_download(repo_id=repo_id, filename=filename, revision=revision)
|
||||
except GatedRepoError as exc:
|
||||
import pytest
|
||||
|
||||
pytest.skip(
|
||||
f"Skipping: gated HF repo {repo_id!r} inaccessible to the current "
|
||||
f"HF_TOKEN ({exc}). See docs/contributing/ci/hf_credentials.md."
|
||||
)
|
||||
except RepositoryNotFoundError as exc:
|
||||
import pytest
|
||||
|
||||
pytest.skip(f"Skipping: HF repo {repo_id!r} not found ({exc}).")
|
||||
except Exception:
|
||||
return
|
||||
@@ -0,0 +1,51 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Shared pytest mocks for unit tests.
|
||||
|
||||
Add reusable ``monkeypatch`` helpers here instead of a new module per target.
|
||||
Callers import explicitly: ``from tests.helpers.mock import ...``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from os import PathLike
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
def patch_hf_snapshot_download(
|
||||
monkeypatch: Any,
|
||||
fake: Callable[..., Any],
|
||||
*,
|
||||
hf_home: str | PathLike[str] | None = None,
|
||||
) -> None:
|
||||
"""Replace ``snapshot_download`` on the cached ``hf_api()`` singleton.
|
||||
|
||||
Production code calls ``hf_api().snapshot_download``. Patching
|
||||
``huggingface_hub.HfApi.snapshot_download`` misses that instance, so
|
||||
weekly CPU jobs talk to the real Hub / ``HF_HOME`` cache.
|
||||
|
||||
``fake`` is installed on the instance, so it is called without ``self``.
|
||||
|
||||
Pass ``hf_home`` (typically pytest ``tmp_path``) to isolate the Hub cache.
|
||||
``repo_utils`` imports ``huggingface_hub`` before tests can ``setenv``, so
|
||||
``constants.HF_HUB_CACHE`` is already frozen from the process environment
|
||||
(weekly: ``/fsx/hf_cache``). Downloads without ``cache_dir`` use that
|
||||
constant, not ``HF_HOME``. Patch both the env and the imported constants
|
||||
so a missed instance mock cannot read the builder cache.
|
||||
"""
|
||||
from huggingface_hub import constants as hub_constants
|
||||
|
||||
from vllm_omni.transformers_utils import repo_utils
|
||||
|
||||
monkeypatch.setattr(repo_utils.hf_api(), "snapshot_download", fake)
|
||||
if hf_home is not None:
|
||||
hf_home_str = str(hf_home)
|
||||
hub_cache = str(Path(hf_home_str) / "hub")
|
||||
monkeypatch.setenv("HF_HOME", hf_home_str)
|
||||
monkeypatch.setenv("HF_HUB_CACHE", hub_cache)
|
||||
monkeypatch.setattr(hub_constants, "HF_HOME", hf_home_str)
|
||||
monkeypatch.setattr(hub_constants, "default_cache_path", hub_cache)
|
||||
monkeypatch.setattr(hub_constants, "HF_HUB_CACHE", hub_cache)
|
||||
monkeypatch.setattr(hub_constants, "HUGGINGFACE_HUB_CACHE", hub_cache)
|
||||
@@ -0,0 +1,93 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.helpers.mock import patch_hf_snapshot_download
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
def test_patch_hf_snapshot_download_binds_instance_without_self(monkeypatch):
|
||||
from vllm_omni.transformers_utils.repo_utils import hf_api
|
||||
|
||||
calls: list[tuple[tuple[object, ...], dict[str, object]]] = []
|
||||
|
||||
def fake(*args, **kwargs):
|
||||
calls.append((args, kwargs))
|
||||
return "ok"
|
||||
|
||||
patch_hf_snapshot_download(monkeypatch, fake)
|
||||
assert hf_api().snapshot_download("org/model", revision="abc") == "ok"
|
||||
assert calls == [(("org/model",), {"revision": "abc"})]
|
||||
|
||||
|
||||
def test_patch_hf_snapshot_download_sets_hf_home(monkeypatch, tmp_path):
|
||||
hf_home = tmp_path / "hf-home"
|
||||
patch_hf_snapshot_download(monkeypatch, lambda *args, **kwargs: "ok", hf_home=hf_home)
|
||||
assert os.environ["HF_HOME"] == str(hf_home)
|
||||
from huggingface_hub import constants
|
||||
|
||||
assert constants.HF_HOME == str(hf_home)
|
||||
assert constants.HF_HUB_CACHE == str(hf_home / "hub")
|
||||
assert constants.HUGGINGFACE_HUB_CACHE == str(hf_home / "hub")
|
||||
assert constants.default_cache_path == str(hf_home / "hub")
|
||||
|
||||
|
||||
def test_patch_hf_snapshot_download_leaves_hf_home_when_omitted(monkeypatch):
|
||||
from huggingface_hub import constants
|
||||
|
||||
monkeypatch.setenv("HF_HOME", "/original-hf-home")
|
||||
original_cache = constants.HF_HUB_CACHE
|
||||
original_default = constants.default_cache_path
|
||||
patch_hf_snapshot_download(monkeypatch, lambda *args, **kwargs: "ok")
|
||||
assert os.environ["HF_HOME"] == "/original-hf-home"
|
||||
assert constants.HF_HUB_CACHE == original_cache
|
||||
assert constants.default_cache_path == original_default
|
||||
|
||||
|
||||
def test_patch_hf_snapshot_download_overrides_preimported_hub_cache(monkeypatch, tmp_path):
|
||||
"""Hub is imported before the helper; ``HF_HOME`` env alone does not move the cache.
|
||||
|
||||
``repo_utils`` / ``huggingface_hub`` compute ``constants.HF_HUB_CACHE`` at
|
||||
import time. Weekly CPU already imported them with ``HF_HOME=/fsx/hf_cache``.
|
||||
A download that bypasses the instance mock uses that constant, not the env.
|
||||
"""
|
||||
from huggingface_hub import constants, snapshot_download
|
||||
from huggingface_hub.errors import LocalEntryNotFoundError
|
||||
|
||||
from vllm_omni.transformers_utils.repo_utils import hf_api
|
||||
|
||||
hf_api()
|
||||
|
||||
poisoned_home = tmp_path / "fsx-hf-cache"
|
||||
poisoned_cache = poisoned_home / "hub"
|
||||
repo_dir = poisoned_cache / "models--org--model"
|
||||
(repo_dir / "refs").mkdir(parents=True)
|
||||
(repo_dir / "refs" / "main").write_text("deadbeef", encoding="utf-8")
|
||||
snapshot = repo_dir / "snapshots" / "deadbeef"
|
||||
snapshot.mkdir(parents=True)
|
||||
(snapshot / "config.json").write_text("{}", encoding="utf-8")
|
||||
|
||||
monkeypatch.setenv("HF_HOME", str(poisoned_home))
|
||||
monkeypatch.setattr(constants, "HF_HOME", str(poisoned_home))
|
||||
monkeypatch.setattr(constants, "HF_HUB_CACHE", str(poisoned_cache))
|
||||
monkeypatch.setattr(constants, "HUGGINGFACE_HUB_CACHE", str(poisoned_cache))
|
||||
|
||||
found = snapshot_download("org/model", local_files_only=True)
|
||||
assert Path(found).resolve() == snapshot.resolve()
|
||||
|
||||
isolated = tmp_path / "isolated-hf-home"
|
||||
patch_hf_snapshot_download(monkeypatch, lambda *args, **kwargs: "mocked", hf_home=isolated)
|
||||
|
||||
assert os.environ["HF_HOME"] == str(isolated)
|
||||
assert os.environ["HF_HUB_CACHE"] == str(isolated / "hub")
|
||||
assert constants.HF_HOME == str(isolated)
|
||||
assert constants.HF_HUB_CACHE == str(isolated / "hub")
|
||||
assert constants.HUGGINGFACE_HUB_CACHE == str(isolated / "hub")
|
||||
assert constants.default_cache_path == str(isolated / "hub")
|
||||
with pytest.raises(LocalEntryNotFoundError):
|
||||
snapshot_download("org/model", local_files_only=True)
|
||||
@@ -0,0 +1,165 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""CPU tests for AuraDataPlaneSession (unwrap runner envelope; do not drop audio)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import numpy as np
|
||||
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.data_plane import AuraDataPlaneSession
|
||||
|
||||
|
||||
def _encode_audio(audio: object, sample_rate: int, fmt: str, speed: float | None) -> str | None:
|
||||
del sample_rate, fmt, speed
|
||||
if audio is None:
|
||||
return None
|
||||
return "encoded-audio"
|
||||
|
||||
|
||||
def test_project_unwraps_data_plane_outputs_and_emits_audio_then_done() -> None:
|
||||
plane = AuraDataPlaneSession(_encode_audio)
|
||||
request_id = "duplex-s.abc.e.0.r.stage0-turn1"
|
||||
plane.begin_request(request_id)
|
||||
audio = np.zeros(16, dtype=np.float32)
|
||||
output = SimpleNamespace(
|
||||
request_id=request_id,
|
||||
finished=True,
|
||||
stage_id=3,
|
||||
outputs=[
|
||||
SimpleNamespace(
|
||||
text="",
|
||||
cumulative_text="",
|
||||
finished=True,
|
||||
multimodal_output={"audio": audio, "sr": 24000},
|
||||
)
|
||||
],
|
||||
multimodal_output={"audio": audio, "sr": 24000},
|
||||
)
|
||||
events = list(plane.project({"data_plane_outputs": [output]}))
|
||||
assert events, "project must not silently drop the runner envelope"
|
||||
assert any(event.get("audio") == "encoded-audio" for event in events)
|
||||
assert events[-1].get("end_of_turn") is True
|
||||
assert events[0].get("data_plane_request_id") == request_id
|
||||
|
||||
|
||||
def test_project_sends_only_the_new_tail_of_a_growing_waveform() -> None:
|
||||
seen: list[int] = []
|
||||
|
||||
def encode(audio: object, sample_rate: int, fmt: str, speed: float | None) -> str:
|
||||
del sample_rate, fmt, speed
|
||||
count = int(np.asarray(audio).reshape(-1).size)
|
||||
seen.append(count)
|
||||
return f"pcm-{count}"
|
||||
|
||||
plane = AuraDataPlaneSession(encode)
|
||||
request_id = "duplex-s.abc.e.0.r.stage3-turn1"
|
||||
plane.begin_request(request_id)
|
||||
|
||||
def chunk(n: int, *, finished: bool) -> SimpleNamespace:
|
||||
audio = np.arange(n, dtype=np.float32)
|
||||
return SimpleNamespace(
|
||||
request_id=request_id,
|
||||
finished=finished,
|
||||
stage_id=3,
|
||||
outputs=[
|
||||
SimpleNamespace(
|
||||
text="",
|
||||
cumulative_text="",
|
||||
finished=False,
|
||||
multimodal_output={"audio": audio, "sr": 24000},
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
first = list(plane.project_output(chunk(8, finished=False)))
|
||||
second = list(plane.project_output(chunk(12, finished=True)))
|
||||
assert seen == [8, 4]
|
||||
assert first[0]["audio_duration_ms"] == round(8 * 1000 / 24000)
|
||||
assert second[0]["audio_duration_ms"] == round(4 * 1000 / 24000)
|
||||
assert second[-1].get("end_of_turn") is True
|
||||
|
||||
|
||||
def test_project_holds_silent_token_prefix() -> None:
|
||||
plane = AuraDataPlaneSession(_encode_audio)
|
||||
request_id = "duplex-s.abc.e.0.r.stage1-turn1"
|
||||
plane.begin_request(request_id)
|
||||
partial = SimpleNamespace(
|
||||
request_id=request_id,
|
||||
finished=False,
|
||||
stage_id=1,
|
||||
outputs=[SimpleNamespace(text="<|sil", cumulative_text="<|sil", finished=False)],
|
||||
)
|
||||
assert list(plane.project({"data_plane_outputs": [partial]})) == []
|
||||
|
||||
|
||||
def test_project_emits_chinese_brackets_immediately() -> None:
|
||||
"""[沉默] is ordinary text — do not hold as a <|silent|> prefix."""
|
||||
plane = AuraDataPlaneSession(_encode_audio)
|
||||
request_id = "duplex-s.abc.e.0.r.stage1_t2"
|
||||
plane.begin_request(request_id)
|
||||
partial = SimpleNamespace(
|
||||
request_id=request_id,
|
||||
finished=False,
|
||||
stage_id=1,
|
||||
outputs=[SimpleNamespace(text="[", cumulative_text="[", finished=False)],
|
||||
)
|
||||
events = list(plane.project({"data_plane_outputs": [partial]}))
|
||||
assert len(events) == 1
|
||||
assert events[0].get("text") == "["
|
||||
|
||||
|
||||
def test_project_flushes_held_silent_prefix_when_text_becomes_speech() -> None:
|
||||
plane = AuraDataPlaneSession(_encode_audio)
|
||||
request_id = "duplex-s.abc.e.0.r.stage1-turn3"
|
||||
plane.begin_request(request_id)
|
||||
partial = SimpleNamespace(
|
||||
request_id=request_id,
|
||||
finished=False,
|
||||
stage_id=1,
|
||||
outputs=[SimpleNamespace(text="<|", cumulative_text="<|", finished=False)],
|
||||
)
|
||||
assert list(plane.project({"data_plane_outputs": [partial]})) == []
|
||||
spoken = SimpleNamespace(
|
||||
request_id=request_id,
|
||||
finished=False,
|
||||
stage_id=1,
|
||||
outputs=[SimpleNamespace(text="<|hello", cumulative_text="<|hello", finished=False)],
|
||||
)
|
||||
events = list(plane.project({"data_plane_outputs": [spoken]}))
|
||||
assert len(events) == 1
|
||||
assert events[0].get("text") == "<|hello"
|
||||
|
||||
|
||||
def test_project_marks_finished_silent_text_as_listen() -> None:
|
||||
plane = AuraDataPlaneSession(_encode_audio)
|
||||
request_id = "duplex-s.abc.e.0.r.stage1_t4"
|
||||
plane.begin_request(request_id)
|
||||
final = SimpleNamespace(
|
||||
request_id=request_id,
|
||||
finished=True,
|
||||
stage_id=1,
|
||||
outputs=[SimpleNamespace(text="<|silent|>", cumulative_text="<|silent|>", finished=True)],
|
||||
)
|
||||
events = list(plane.project({"data_plane_outputs": [final]}))
|
||||
assert any(e.get("silent") and e.get("is_listen") for e in events)
|
||||
assert any(e.get("abort_data_plane_request") is True for e in events)
|
||||
|
||||
|
||||
def test_project_finished_spoken_turn_carries_model_context() -> None:
|
||||
plane = AuraDataPlaneSession(_encode_audio)
|
||||
request_id = "duplex-s.abc.e.0.r.stage1-turn5"
|
||||
plane.begin_request(request_id)
|
||||
final = SimpleNamespace(
|
||||
request_id=request_id,
|
||||
finished=True,
|
||||
stage_id=1,
|
||||
outputs=[SimpleNamespace(text="你好。", cumulative_text="你好。", finished=True)],
|
||||
)
|
||||
events = list(plane.project({"data_plane_outputs": [final]}))
|
||||
context = [event for event in events if event.get("model_context_text")]
|
||||
assert context and context[-1]["model_context_text"] == "你好。"
|
||||
assert context[-1].get("is_listen") is False
|
||||
assert context[-1].get("text") == ""
|
||||
@@ -0,0 +1,115 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""Aura duplex data-plane must surface Code2Wav MultimodalPayload audio."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import torch
|
||||
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.data_plane import (
|
||||
AuraDataPlaneSession,
|
||||
_audio_value,
|
||||
_multimodal,
|
||||
)
|
||||
from vllm_omni.outputs.mm_outputs import MultimodalPayload
|
||||
|
||||
|
||||
def _encode(audio: object, sample_rate: int, fmt: str, speed: float | None) -> str | None:
|
||||
del sample_rate, fmt, speed
|
||||
if audio is None:
|
||||
return None
|
||||
return "encoded-audio"
|
||||
|
||||
|
||||
def test_audio_value_accepts_from_raw_audio_key() -> None:
|
||||
raw = {"model_outputs": [torch.zeros(8)], "sr": [torch.tensor(24000)]}
|
||||
mm = MultimodalPayload.from_raw(raw, "audio")
|
||||
assert mm is not None
|
||||
assert "audio" in mm
|
||||
audio = _audio_value(dict(mm))
|
||||
assert isinstance(audio, torch.Tensor)
|
||||
assert int(audio.numel()) == 8
|
||||
|
||||
|
||||
def test_audio_value_accepts_wrongly_tagged_text_key() -> None:
|
||||
# If stage output_modality is wrong, from_raw remaps model_outputs → "text".
|
||||
raw = {"model_outputs": torch.zeros(4), "sr": torch.tensor(24000)}
|
||||
mm = MultimodalPayload.from_raw(raw, "text")
|
||||
assert mm is not None
|
||||
audio = _audio_value(dict(mm))
|
||||
assert isinstance(audio, torch.Tensor)
|
||||
|
||||
|
||||
def test_multimodal_skips_empty_outer_dict_and_reads_completion() -> None:
|
||||
mm = MultimodalPayload.from_dict({"audio": torch.zeros(3), "sr": torch.tensor(24000)})
|
||||
completion = SimpleNamespace(multimodal_output=mm)
|
||||
# Empty Mapping on the outer object must not hide completion payload.
|
||||
outer = SimpleNamespace(multimodal_output={})
|
||||
got = _multimodal(outer, completion)
|
||||
assert "audio" in got
|
||||
|
||||
|
||||
def test_project_emits_audio_from_multimodal_completion() -> None:
|
||||
plane = AuraDataPlaneSession(_encode)
|
||||
request_id = "duplex-s.test.e.0.r.stage0-turn0"
|
||||
plane.begin_request(request_id)
|
||||
mm = MultimodalPayload.from_raw(
|
||||
{"model_outputs": [torch.zeros(16)], "sr": [torch.tensor(24000)]},
|
||||
"audio",
|
||||
)
|
||||
completion = SimpleNamespace(
|
||||
text="",
|
||||
cumulative_text="",
|
||||
finished=False,
|
||||
multimodal_output=mm,
|
||||
)
|
||||
output = SimpleNamespace(
|
||||
request_id=request_id,
|
||||
finished=False,
|
||||
stage_id=3,
|
||||
outputs=[completion],
|
||||
multimodal_output={},
|
||||
)
|
||||
events = list(plane.project({"data_plane_outputs": [output]}))
|
||||
assert events, "project must emit TTS audio for MultimodalPayload"
|
||||
assert any(event.get("audio") == "encoded-audio" for event in events)
|
||||
|
||||
|
||||
def test_streaming_chunk_completion_finished_is_not_turn_eos() -> None:
|
||||
"""Code2Wav chunks set CompletionOutput.finished; that must not EOT.
|
||||
|
||||
Runner._send_one_model_output_event drops is_terminal request ids before
|
||||
emit. Marking terminal (or end_of_turn) on the first 8-frame chunk made
|
||||
WS response.* never leave the engine.
|
||||
"""
|
||||
plane = AuraDataPlaneSession(_encode)
|
||||
request_id = "duplex-s.test.e.0.r.stage0-turn0"
|
||||
plane.begin_request(request_id)
|
||||
mm = MultimodalPayload.from_raw(
|
||||
{"model_outputs": [torch.zeros(16)], "sr": [torch.tensor(24000)]},
|
||||
"audio",
|
||||
)
|
||||
completion = SimpleNamespace(
|
||||
text="",
|
||||
cumulative_text="",
|
||||
finished=True,
|
||||
multimodal_output=mm,
|
||||
)
|
||||
output = SimpleNamespace(
|
||||
request_id=request_id,
|
||||
finished=False,
|
||||
stage_id=3,
|
||||
outputs=[completion],
|
||||
multimodal_output={},
|
||||
)
|
||||
events: list[dict[str, object]] = []
|
||||
for event in plane.project({"data_plane_outputs": [output]}):
|
||||
assert plane.is_terminal(request_id) is False
|
||||
events.append(event)
|
||||
assert events
|
||||
assert events[0].get("audio") == "encoded-audio"
|
||||
assert events[0].get("end_of_turn") is False
|
||||
assert plane.is_terminal(request_id) is False
|
||||
@@ -0,0 +1,598 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""CPU contract tests for AURA duplex plugin seams."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from types import SimpleNamespace
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
from vllm.sampling_params import SamplingParams
|
||||
|
||||
from vllm_omni.engine.duplex.config import DuplexSessionConfig
|
||||
from vllm_omni.engine.duplex.contracts import (
|
||||
DuplexFence,
|
||||
DuplexStageRequestContext,
|
||||
DuplexStageSubmission,
|
||||
duplex_ephemeral_stage_request_id,
|
||||
duplex_resource_request_id,
|
||||
)
|
||||
from vllm_omni.engine.duplex.plugin import load_duplex_plugin
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.data_plane import (
|
||||
AuraDataPlaneContext,
|
||||
AuraDataPlaneSession,
|
||||
)
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.history import (
|
||||
drop_session_history,
|
||||
get_or_create_session_history,
|
||||
)
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.input import AuraPcmAppendBuffer
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.plugin import (
|
||||
AURA_SILENT_TOKEN_ID,
|
||||
AuraDuplexPlugin,
|
||||
)
|
||||
from vllm_omni.model_executor.stage_input_processors.aura_omni import SILENT_TEXT
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
def _encode_audio(audio: object, sample_rate: int, fmt: str, speed: float | None) -> str | None:
|
||||
del audio, sample_rate, fmt, speed
|
||||
return "ZmFrZQ=="
|
||||
|
||||
|
||||
def test_load_aura_duplex_plugin_and_sampling_arity() -> None:
|
||||
plugin = load_duplex_plugin(
|
||||
"vllm_omni.model_executor.models.aura_omni.duplex.plugin.AuraDuplexPlugin",
|
||||
_encode_audio,
|
||||
)
|
||||
assert isinstance(plugin, AuraDuplexPlugin)
|
||||
assert plugin.plugin_id == "aura"
|
||||
defaults = (
|
||||
SamplingParams(max_tokens=16),
|
||||
SamplingParams(max_tokens=16),
|
||||
SamplingParams(max_tokens=4096),
|
||||
SamplingParams(max_tokens=16),
|
||||
)
|
||||
configured = plugin.configure_sampling_params(runtime_config={}, defaults=defaults)
|
||||
assert len(configured) == 4
|
||||
assert configured[2].stop_token_ids == [2150]
|
||||
assert configured[2].max_tokens == 4096
|
||||
stage1_stops = set(configured[1].stop_token_ids or [])
|
||||
assert {151669, 151645}.issubset(stage1_stops)
|
||||
assert 248070 not in stage1_stops
|
||||
caps = plugin.capabilities(max_sessions=1)
|
||||
assert caps.supports_turn_commit_only is True
|
||||
assert caps.supports_core_resumable_request is False
|
||||
assert caps.supports_concurrent_turn_requests is True
|
||||
assert caps.required_input_modalities == frozenset({"video"})
|
||||
assert caps.optional_input_modalities == frozenset({"audio"})
|
||||
assert caps.allows_video_without_audio() is True
|
||||
assert caps.validate_append_modalities(has_audio=True, has_video=False) == (
|
||||
"This duplex model requires video_frames on input_audio_buffer.append"
|
||||
)
|
||||
assert caps.validate_append_modalities(has_audio=True, has_video=True) is None
|
||||
assert caps.validate_append_modalities(has_audio=False, has_video=True) is None
|
||||
|
||||
|
||||
def test_commit_only_buffer_emits_on_commit() -> None:
|
||||
buf = AuraPcmAppendBuffer()
|
||||
samples = np.zeros(1600, dtype="<f4")
|
||||
payload = {
|
||||
"type": "audio",
|
||||
"format": "pcm_f32le",
|
||||
"sample_rate_hz": 16000,
|
||||
"audio": base64.b64encode(samples.tobytes()).decode("ascii"),
|
||||
"is_speech": True,
|
||||
"video_frames": ["aGVsbG8="],
|
||||
}
|
||||
reservation = buf.prepare_append(
|
||||
payload,
|
||||
operation_id="op1",
|
||||
chunk_period_ms=1000,
|
||||
allow_emit=True,
|
||||
)
|
||||
assert reservation is None
|
||||
assert buf.has_pending()
|
||||
commit = buf.prepare_commit(operation_id="c1", chunk_period_ms=1000)
|
||||
assert commit.payload is not None
|
||||
assert commit.payload.get("final") is True
|
||||
assert commit.payload.get("aura_turn_commit") is True
|
||||
assert commit.payload.get("video_frames") == ["aGVsbG8="]
|
||||
commit.commit()
|
||||
|
||||
|
||||
def test_commit_reservation_includes_video_bytes() -> None:
|
||||
buf = AuraPcmAppendBuffer()
|
||||
pcm = np.zeros(1600, dtype="<f4").tobytes()
|
||||
frames = ["aGVsbG8=", "d29ybGQ="]
|
||||
payload = {
|
||||
"type": "audio",
|
||||
"format": "pcm_f32le",
|
||||
"sample_rate_hz": 16000,
|
||||
"audio": base64.b64encode(pcm).decode("ascii"),
|
||||
"is_speech": True,
|
||||
"video_frames": frames,
|
||||
}
|
||||
assert (
|
||||
buf.prepare_append(
|
||||
payload,
|
||||
operation_id="op1",
|
||||
chunk_period_ms=1000,
|
||||
allow_emit=True,
|
||||
)
|
||||
is None
|
||||
)
|
||||
pending = buf.pending_byte_count
|
||||
assert pending == len(pcm) + sum(len(frame) for frame in frames)
|
||||
commit = buf.prepare_commit(operation_id="c1", chunk_period_ms=1000)
|
||||
assert buf.pending_byte_count == 0
|
||||
assert commit.byte_count == pending
|
||||
commit.commit()
|
||||
assert buf.pending_byte_count == 0
|
||||
assert not buf.has_reserved()
|
||||
|
||||
|
||||
def test_plan_append_commit_builds_stage0_prompt() -> None:
|
||||
plugin = AuraDuplexPlugin(_encode_audio)
|
||||
samples = np.zeros(800, dtype="<f4")
|
||||
payload = {
|
||||
"type": "audio",
|
||||
"format": "pcm_f32le",
|
||||
"sample_rate_hz": 16000,
|
||||
"audio": base64.b64encode(samples.tobytes()).decode("ascii"),
|
||||
"final": True,
|
||||
"aura_turn_commit": True,
|
||||
"is_speech": True,
|
||||
}
|
||||
fence = DuplexFence("sess-1", epoch=2, turn_id=5)
|
||||
plan = plugin.plan_append(
|
||||
request_id="req",
|
||||
fence=fence,
|
||||
session_config={},
|
||||
runtime_config={"aura_system_prompt": "sys"},
|
||||
seq=1,
|
||||
turn_seq=1,
|
||||
payload=payload,
|
||||
final=True,
|
||||
sampling_params=SamplingParams(max_tokens=8),
|
||||
)
|
||||
info = plan.prompt["additional_information"]
|
||||
assert info["aura_duplex"] is True
|
||||
assert info["session_id"] == "sess-1"
|
||||
assert "audio" in plan.prompt["multi_modal_data"]
|
||||
assert "prompt_token_ids" not in plan.prompt
|
||||
|
||||
|
||||
def test_video_frames_to_mm_packs_one_video() -> None:
|
||||
"""Two JPEG frames are one video clip, not two image items."""
|
||||
from io import BytesIO
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.plugin import _video_frames_to_mm
|
||||
|
||||
frames: list[str] = []
|
||||
for color in ((255, 0, 0), (0, 255, 0)):
|
||||
buf = BytesIO()
|
||||
Image.new("RGB", (8, 8), color).save(buf, format="JPEG")
|
||||
frames.append(base64.b64encode(buf.getvalue()).decode("ascii"))
|
||||
mm = _video_frames_to_mm(frames)
|
||||
assert list(mm.keys()) == ["video"]
|
||||
assert len(mm["video"]) == 1
|
||||
video, metadata = mm["video"][0]
|
||||
assert np.asarray(video).shape == (2, 8, 8, 3)
|
||||
assert metadata["total_num_frames"] == 2
|
||||
assert metadata["do_sample_frames"] is False
|
||||
|
||||
|
||||
def test_plan_append_vision_empty_audio_never_leaves_empty_prompt() -> None:
|
||||
"""Frames + empty/near-silent audio must still get a Stage0 ASR pad."""
|
||||
from io import BytesIO
|
||||
|
||||
from PIL import Image
|
||||
|
||||
plugin = AuraDuplexPlugin(_encode_audio)
|
||||
img = Image.new("RGB", (32, 32), (8, 16, 24))
|
||||
buf = BytesIO()
|
||||
img.save(buf, format="JPEG")
|
||||
frame = base64.b64encode(buf.getvalue()).decode("ascii")
|
||||
fence = DuplexFence("sess-v", epoch=0, turn_id=1)
|
||||
near = np.linspace(1e-5, -1e-5, 80, dtype="<f4")
|
||||
cases = [
|
||||
("empty_speech_true", True, ""),
|
||||
("empty_speech_false", False, ""),
|
||||
("near_silent", False, base64.b64encode(near.tobytes()).decode("ascii")),
|
||||
]
|
||||
for name, is_speech, audio in cases:
|
||||
payload = {
|
||||
"type": "audio",
|
||||
"format": "pcm_f32le",
|
||||
"sample_rate_hz": 16000,
|
||||
"audio": audio,
|
||||
"final": True,
|
||||
"aura_turn_commit": True,
|
||||
"is_speech": is_speech,
|
||||
"video_frames": [frame],
|
||||
}
|
||||
plan = plugin.plan_append(
|
||||
request_id="req",
|
||||
fence=fence,
|
||||
session_config={},
|
||||
runtime_config={},
|
||||
seq=1,
|
||||
turn_seq=1,
|
||||
payload=payload,
|
||||
final=True,
|
||||
sampling_params=SamplingParams(max_tokens=8),
|
||||
)
|
||||
assert plan.prompt.get("prompt"), f"{name}: Stage0 prompt must be non-empty"
|
||||
assert "audio" in plan.prompt["multi_modal_data"], f"{name}: padded audio required"
|
||||
assert "deferred_multi_modal_data" in plan.prompt["additional_information"]
|
||||
|
||||
|
||||
def test_project_intermediate_output_targets_stage1_only() -> None:
|
||||
plugin = AuraDuplexPlugin(_encode_audio)
|
||||
assert plugin.project_intermediate_output(stage_id=1, output=object(), context=object()) is True
|
||||
assert plugin.project_intermediate_output(stage_id=0, output=object(), context=object()) is False
|
||||
assert plugin.project_intermediate_output(stage_id=3, output=object(), context=object()) is False
|
||||
|
||||
|
||||
def test_release_concurrent_turn_requests_on_stage1_final() -> None:
|
||||
plugin = AuraDuplexPlugin(_encode_audio)
|
||||
assert plugin.release_concurrent_turn_requests(stage_id=1, segment_finished=True, output=object(), context=object())
|
||||
assert not plugin.release_concurrent_turn_requests(
|
||||
stage_id=1, segment_finished=False, output=object(), context=object()
|
||||
)
|
||||
finished = type("Out", (), {"finished": True})()
|
||||
assert plugin.release_concurrent_turn_requests(
|
||||
stage_id=1, segment_finished=False, output=finished, context=object()
|
||||
)
|
||||
assert not plugin.release_concurrent_turn_requests(
|
||||
stage_id=2, segment_finished=True, output=object(), context=object()
|
||||
)
|
||||
|
||||
|
||||
def test_configure_sampling_keeps_silent_stop_visible() -> None:
|
||||
plugin = AuraDuplexPlugin(_encode_audio)
|
||||
defaults = (
|
||||
SamplingParams(max_tokens=16),
|
||||
SamplingParams(max_tokens=16),
|
||||
SamplingParams(max_tokens=4096),
|
||||
SamplingParams(max_tokens=16),
|
||||
)
|
||||
configured = plugin.configure_sampling_params(runtime_config={}, defaults=defaults)
|
||||
stage1 = configured[1]
|
||||
assert isinstance(stage1, SamplingParams)
|
||||
assert stage1.include_stop_str_in_output is True
|
||||
assert stage1.skip_special_tokens is False
|
||||
assert AURA_SILENT_TOKEN_ID in (stage1.stop_token_ids or [])
|
||||
|
||||
|
||||
def test_configure_sampling_keeps_explicit_talker_limits() -> None:
|
||||
plugin = AuraDuplexPlugin(_encode_audio)
|
||||
defaults = (
|
||||
SamplingParams(max_tokens=16),
|
||||
SamplingParams(max_tokens=16),
|
||||
SamplingParams(max_tokens=500, stop_token_ids=[7]),
|
||||
SamplingParams(max_tokens=16),
|
||||
)
|
||||
configured = plugin.configure_sampling_params(runtime_config={}, defaults=defaults)
|
||||
stage2 = configured[2]
|
||||
assert isinstance(stage2, SamplingParams)
|
||||
assert stage2.max_tokens == 500
|
||||
assert stage2.stop_token_ids == [7]
|
||||
unset = plugin.configure_sampling_params(
|
||||
runtime_config={},
|
||||
defaults=(
|
||||
SamplingParams(max_tokens=16),
|
||||
SamplingParams(max_tokens=16),
|
||||
SamplingParams(max_tokens=None),
|
||||
SamplingParams(max_tokens=16),
|
||||
),
|
||||
)
|
||||
assert unset[2].max_tokens == 240
|
||||
assert unset[2].stop_token_ids == [2150]
|
||||
|
||||
|
||||
def test_decide_output_silent_short_circuits() -> None:
|
||||
plugin = AuraDuplexPlugin(_encode_audio)
|
||||
|
||||
class _Completion:
|
||||
text = SILENT_TEXT
|
||||
token_ids = [AURA_SILENT_TOKEN_ID]
|
||||
finished = True
|
||||
|
||||
class _Output:
|
||||
outputs = [_Completion()]
|
||||
|
||||
decision = plugin.decide_output(
|
||||
stage_id=1,
|
||||
final_stage_id=3,
|
||||
segment_finished=True,
|
||||
segment_token_ids=(AURA_SILENT_TOKEN_ID,),
|
||||
segment_output_metadata={},
|
||||
output=_Output(),
|
||||
)
|
||||
assert decision is not None
|
||||
assert decision.metadata.get("model_listen") is True
|
||||
|
||||
|
||||
def test_decide_output_chinese_silence_is_not_special_token() -> None:
|
||||
plugin = AuraDuplexPlugin(_encode_audio)
|
||||
|
||||
class _Completion:
|
||||
text = "[沉默]"
|
||||
token_ids = [58, 107107, 60]
|
||||
finished = True
|
||||
|
||||
class _Output:
|
||||
outputs = [_Completion()]
|
||||
|
||||
assert (
|
||||
plugin.decide_output(
|
||||
stage_id=1,
|
||||
final_stage_id=3,
|
||||
segment_finished=True,
|
||||
segment_token_ids=(58, 107107, 60),
|
||||
segment_output_metadata={},
|
||||
output=_Output(),
|
||||
)
|
||||
is None
|
||||
)
|
||||
|
||||
|
||||
def test_ephemeral_request_id_includes_turn() -> None:
|
||||
fence = DuplexFence("s", epoch=1, turn_id=7)
|
||||
resumable = duplex_resource_request_id(fence, "stage0")
|
||||
ephemeral = duplex_ephemeral_stage_request_id(fence, stage_id=0)
|
||||
assert ephemeral.endswith("stage0-turn7")
|
||||
assert resumable != ephemeral
|
||||
fence2 = DuplexFence("s", epoch=1, turn_id=8)
|
||||
assert duplex_ephemeral_stage_request_id(fence, stage_id=0) != duplex_ephemeral_stage_request_id(fence2, stage_id=0)
|
||||
|
||||
|
||||
def test_stage_submission_defaults_resumable_true() -> None:
|
||||
ctx = DuplexStageRequestContext(
|
||||
request_id="r",
|
||||
session_id="s",
|
||||
fence=DuplexFence("s"),
|
||||
stage_id=0,
|
||||
final_stage_id=3,
|
||||
config_generation=0,
|
||||
sampling_params=(SamplingParams(max_tokens=1),),
|
||||
)
|
||||
submission = DuplexStageSubmission(
|
||||
context=ctx,
|
||||
prompt={"prompt_token_ids": [0]},
|
||||
already_submitted=False,
|
||||
)
|
||||
assert submission.resumable is True
|
||||
|
||||
|
||||
def test_data_plane_close_session_drops_history() -> None:
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.data_plane import AuraDataPlaneSession
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.history import get_or_create_session_history
|
||||
|
||||
drop_session_history("close-hist")
|
||||
get_or_create_session_history("close-hist").begin_user_turn("hi")
|
||||
AuraDataPlaneSession(encode_audio=_encode_audio).close_session("close-hist")
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.history import _STORE
|
||||
|
||||
assert "close-hist" not in _STORE
|
||||
|
||||
|
||||
def test_session_history_strips_oldest_silent_videos() -> None:
|
||||
drop_session_history("hist-ut")
|
||||
history = get_or_create_session_history("hist-ut")
|
||||
history.max_video_rounds = 2
|
||||
history.video_rounds_to_remove = 1
|
||||
for index in range(3):
|
||||
history.begin_user_turn("", video=(f"clip-{index}",))
|
||||
history.commit_turn(SILENT_TEXT)
|
||||
kept = [message["video"] for message in history.messages if message.get("video") is not None]
|
||||
assert kept == [("clip-1",), ("clip-2",)]
|
||||
assert not any(message.get("video") == ("clip-0",) for message in history.messages)
|
||||
drop_session_history("hist-ut")
|
||||
|
||||
|
||||
def test_pipeline_declares_aura_duplex_plugin() -> None:
|
||||
from vllm_omni.model_executor.models.aura_omni.pipeline import AURA_OMNI_PIPELINE
|
||||
|
||||
assert AURA_OMNI_PIPELINE.duplex_plugin == (
|
||||
"vllm_omni.model_executor.models.aura_omni.duplex.plugin.AuraDuplexPlugin"
|
||||
)
|
||||
|
||||
|
||||
def test_project_output_uses_requested_format_and_chunk_duration() -> None:
|
||||
seen: dict[str, object] = {}
|
||||
|
||||
def encode(audio: object, sample_rate: int, fmt: str, speed: float | None) -> str:
|
||||
seen["fmt"] = fmt
|
||||
seen["rate"] = sample_rate
|
||||
seen["speed"] = speed
|
||||
del audio
|
||||
return "AAAA"
|
||||
|
||||
plane = AuraDataPlaneSession(encode)
|
||||
|
||||
class _Output:
|
||||
request_id = "aura-turn"
|
||||
finished = False
|
||||
stage_id = 3
|
||||
multimodal_output = {"audio": np.zeros(4800, dtype=np.float32), "sr": 24000}
|
||||
|
||||
events = list(plane.project_output(_Output(), context=AuraDataPlaneContext(response_format="pcm16", speed=1.0)))
|
||||
assert seen["fmt"] == "pcm16"
|
||||
assert events[0]["audio_format"] == "pcm16"
|
||||
assert events[0]["audio_duration_ms"] == 200
|
||||
assert events[0]["sample_rate_hz"] == 24000
|
||||
|
||||
def encode_wav(audio: object, sample_rate: int, fmt: str, speed: float | None) -> str:
|
||||
del audio, sample_rate, speed
|
||||
assert fmt == "wav"
|
||||
return "V0FW"
|
||||
|
||||
plane_wav = AuraDataPlaneSession(encode_wav)
|
||||
wav_events = list(plane_wav.project_output(_Output(), context=AuraDataPlaneContext(response_format="wav")))
|
||||
assert wav_events[0]["audio_format"] == "wav"
|
||||
|
||||
|
||||
def test_instructions_update_replaces_effective_prompt() -> None:
|
||||
plugin = AuraDuplexPlugin(_encode_audio)
|
||||
current = {"aura_system_prompt": "creation default", "instructions": "creation default"}
|
||||
updated = plugin.runtime_config_for_update(
|
||||
DuplexSessionConfig(model="aurateam/AURA", instructions="be brief"),
|
||||
current,
|
||||
)
|
||||
assert updated["aura_system_prompt"] == "be brief"
|
||||
assert updated["instructions"] == "be brief"
|
||||
kept = plugin.runtime_config_for_update(
|
||||
DuplexSessionConfig(
|
||||
model="aurateam/AURA",
|
||||
extra_body={"aura_system_prompt": "explicit"},
|
||||
instructions="ignored when explicit",
|
||||
),
|
||||
updated,
|
||||
)
|
||||
assert kept["aura_system_prompt"] == "explicit"
|
||||
|
||||
|
||||
def test_plan_partial_stage_output_hands_a_sentence_to_talker() -> None:
|
||||
def aura2tts() -> None:
|
||||
return None
|
||||
|
||||
class _Pool:
|
||||
stage_client = SimpleNamespace(custom_process_input_func=aura2tts)
|
||||
|
||||
orchestrator = SimpleNamespace(
|
||||
stage_pools={2: _Pool()},
|
||||
_stage_receives_async_chunks=lambda stage_id: False,
|
||||
)
|
||||
req_state = SimpleNamespace(
|
||||
session_owned=True,
|
||||
final_stage_id=3,
|
||||
request_id="req-1",
|
||||
prompt={"additional_information": {}},
|
||||
streaming=SimpleNamespace(bridge_states={}),
|
||||
)
|
||||
sentence = "这是一段用来直接测试句子级语音交接而且长度已经超过三十个字的内容。"
|
||||
output = SimpleNamespace(
|
||||
finished=False,
|
||||
request_id="req-1",
|
||||
outputs=[SimpleNamespace(cumulative_text=sentence)],
|
||||
)
|
||||
|
||||
plan = AuraDuplexPlugin(_encode_audio).plan_partial_stage_output(orchestrator, 1, 0, output, req_state)
|
||||
|
||||
assert plan is not None
|
||||
assert plan.close_only is False
|
||||
assert plan.is_final_update is False
|
||||
assert plan.output.text == sentence.strip()
|
||||
assert req_state.prompt["additional_information"]["aura_tts_partial"] is True
|
||||
assert AuraDuplexPlugin(_encode_audio).plan_partial_stage_output(orchestrator, 0, 0, output, req_state) is None
|
||||
|
||||
|
||||
def _sentence_plan_fixture() -> tuple[SimpleNamespace, SimpleNamespace]:
|
||||
def aura2tts() -> None:
|
||||
return None
|
||||
|
||||
class _Pool:
|
||||
stage_client = SimpleNamespace(custom_process_input_func=aura2tts)
|
||||
|
||||
orchestrator = SimpleNamespace(
|
||||
stage_pools={2: _Pool()},
|
||||
_stage_receives_async_chunks=lambda stage_id: False,
|
||||
)
|
||||
req_state = SimpleNamespace(
|
||||
session_owned=True,
|
||||
final_stage_id=3,
|
||||
request_id="req-1",
|
||||
prompt={"additional_information": {}},
|
||||
streaming=SimpleNamespace(bridge_states={}),
|
||||
)
|
||||
return orchestrator, req_state
|
||||
|
||||
|
||||
def _stage1_output(text: str, *, finished: bool) -> SimpleNamespace:
|
||||
return SimpleNamespace(
|
||||
finished=finished,
|
||||
request_id="req-1",
|
||||
outputs=[SimpleNamespace(cumulative_text=text)],
|
||||
)
|
||||
|
||||
|
||||
def test_finished_remainder_stays_resumable_until_close_sentinel() -> None:
|
||||
"""A second sentence at Stage1 finish must not be the Talker end sentinel.
|
||||
|
||||
The first sentence is already a resumable Talker request. Marking the
|
||||
remainder ``is_final_update`` makes ``StreamingUpdate.from_request``
|
||||
return None, which aborts that in-flight sentence before Code2Wav has a
|
||||
full codec group.
|
||||
"""
|
||||
orchestrator, req_state = _sentence_plan_fixture()
|
||||
plugin = AuraDuplexPlugin(_encode_audio)
|
||||
first = "我看到你身后是一个很明亮的办公室环境,天花板上能看到白色的管道和通风口,"
|
||||
full = first + "远处还有办公桌和绿植。"
|
||||
opened = plugin.plan_partial_stage_output(orchestrator, 1, 0, _stage1_output(first, finished=False), req_state)
|
||||
assert opened is not None
|
||||
assert opened.is_final_update is False
|
||||
assert opened.queue_close_after is False
|
||||
assert req_state.prompt["additional_information"]["aura_tts_close_only"] is False
|
||||
|
||||
tail = plugin.plan_partial_stage_output(orchestrator, 1, 0, _stage1_output(full, finished=True), req_state)
|
||||
assert tail is not None
|
||||
assert tail.close_only is False
|
||||
assert tail.queue_close_after is True
|
||||
assert tail.is_final_update is False
|
||||
assert tail.output.text == "远处还有办公桌和绿植。"
|
||||
assert req_state.prompt["additional_information"]["aura_tts_close_only"] is False
|
||||
|
||||
followup = plugin.partial_stage_followup(tail, req_state)
|
||||
assert followup is not None
|
||||
assert followup.is_final_update is True
|
||||
assert followup.close_only is True
|
||||
assert followup.output.text == ""
|
||||
assert req_state.prompt["additional_information"]["aura_tts_close_only"] is True
|
||||
|
||||
|
||||
def test_single_finished_sentence_is_one_non_resumable_submit() -> None:
|
||||
orchestrator, req_state = _sentence_plan_fixture()
|
||||
plugin = AuraDuplexPlugin(_encode_audio)
|
||||
sentence = "你好,我看到一个戴眼镜、穿黑T恤的男生正对着镜头说话呢。"
|
||||
plan = plugin.plan_partial_stage_output(orchestrator, 1, 0, _stage1_output(sentence, finished=True), req_state)
|
||||
assert plan is not None
|
||||
assert plan.queue_close_after is False
|
||||
assert plan.is_final_update is True
|
||||
assert plan.close_only is False
|
||||
assert plugin.partial_stage_followup(plan, req_state) is None
|
||||
|
||||
|
||||
def test_aura_draining_stages_are_declared_by_the_plugin() -> None:
|
||||
plugin = AuraDuplexPlugin(_encode_audio)
|
||||
assert plugin.draining_stage_ids(stage_count=4) == frozenset({2, 3})
|
||||
assert plugin.draining_stage_ids(stage_count=2) == frozenset()
|
||||
|
||||
|
||||
def test_spoken_stage0_text_is_the_user_transcript() -> None:
|
||||
plugin = AuraDuplexPlugin(_encode_audio)
|
||||
output = SimpleNamespace(
|
||||
finished=True,
|
||||
outputs=[
|
||||
SimpleNamespace(text="language Chinese<asr_text>你好", cumulative_text="language Chinese<asr_text>你好")
|
||||
],
|
||||
)
|
||||
prompt = {"additional_information": {"is_speech": True}}
|
||||
assert plugin.user_transcript(stage_id=0, output=output, prompt=prompt, finished=True) == "你好"
|
||||
|
||||
|
||||
def test_vision_follow_stage0_text_is_not_shown_as_user_speech() -> None:
|
||||
plugin = AuraDuplexPlugin(_encode_audio)
|
||||
output = SimpleNamespace(finished=True, text="嗯")
|
||||
prompt = {"additional_information": {"is_speech": False}}
|
||||
assert plugin.user_transcript(stage_id=0, output=output, prompt=prompt, finished=True) is None
|
||||
assert plugin.user_transcript(stage_id=1, output=output, prompt=prompt, finished=True) is None
|
||||
assert plugin.user_transcript(stage_id=0, output=output, prompt=prompt, finished=False) is None
|
||||
@@ -0,0 +1,62 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Growing Stage1 token ids must decode to the same text as one full decode."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.sentence_tts import decode_growing_token_ids
|
||||
|
||||
|
||||
def _assert_matches_full(decode, ids: list[int]) -> None:
|
||||
cache: dict[str, object] = {}
|
||||
for end in range(1, len(ids) + 1):
|
||||
got = decode_growing_token_ids(decode, ids[:end], cache)
|
||||
assert got == decode(ids[:end])
|
||||
|
||||
|
||||
def test_growing_decode_matches_full_decode_for_concat_pieces() -> None:
|
||||
vocab = {1: "你", 2: "好", 3: "。", 4: "世", 5: "界"}
|
||||
|
||||
def decode(token_ids: list[int], skip_special_tokens: bool = False) -> str:
|
||||
del skip_special_tokens
|
||||
return "".join(vocab[token_id] for token_id in token_ids)
|
||||
|
||||
_assert_matches_full(decode, [1, 2, 3, 4, 5])
|
||||
|
||||
|
||||
def test_growing_decode_matches_full_decode_when_the_previous_piece_changes() -> None:
|
||||
"""Token 9 rewrites the previous character. The tail window must reject a bad splice."""
|
||||
|
||||
def decode(token_ids: list[int], skip_special_tokens: bool = False) -> str:
|
||||
del skip_special_tokens
|
||||
chars: list[str] = []
|
||||
for token_id in token_ids:
|
||||
if token_id == 9:
|
||||
if chars:
|
||||
chars.pop()
|
||||
chars.append("X")
|
||||
else:
|
||||
chars.append(chr(96 + token_id))
|
||||
return "".join(chars)
|
||||
|
||||
_assert_matches_full(decode, [1, 2, 9, 3])
|
||||
|
||||
|
||||
def test_growing_decode_matches_wordpiece_spacing() -> None:
|
||||
vocab = {1: "hello", 2: "##world", 3: "。"}
|
||||
|
||||
def decode(token_ids: list[int], skip_special_tokens: bool = False) -> str:
|
||||
del skip_special_tokens
|
||||
parts: list[str] = []
|
||||
for index, token_id in enumerate(token_ids):
|
||||
piece = vocab[token_id]
|
||||
if piece.startswith("##"):
|
||||
parts.append(piece[2:])
|
||||
else:
|
||||
if index:
|
||||
parts.append(" ")
|
||||
parts.append(piece)
|
||||
return "".join(parts)
|
||||
|
||||
_assert_matches_full(decode, [1, 2, 3, 1])
|
||||
File renamed without changes.
+1
-1
@@ -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 importlib.util
|
||||
from pathlib import Path
|
||||
@@ -12,9 +12,9 @@ from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import huggingface_hub
|
||||
import pytest
|
||||
|
||||
from tests.helpers.mock import patch_hf_snapshot_download
|
||||
from vllm_omni.model_executor.models.minicpmo_4_5.minicpmo_4_5_code2wav import (
|
||||
MiniCPMO45Code2Wav,
|
||||
_resolve_model_dir,
|
||||
@@ -23,28 +23,28 @@ from vllm_omni.model_executor.models.minicpmo_4_5.minicpmo_4_5_code2wav import (
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
def _no_hub(monkeypatch):
|
||||
def _no_hub(monkeypatch, tmp_path):
|
||||
def _fail(*args, **kwargs): # pragma: no cover - must not be reached
|
||||
raise AssertionError("snapshot_download must not be called here")
|
||||
|
||||
monkeypatch.setattr(huggingface_hub.HfApi, "snapshot_download", _fail)
|
||||
patch_hf_snapshot_download(monkeypatch, _fail, hf_home=tmp_path)
|
||||
|
||||
|
||||
def test_local_directory_is_returned_unchanged(tmp_path, monkeypatch):
|
||||
_no_hub(monkeypatch)
|
||||
_no_hub(monkeypatch, tmp_path)
|
||||
assert _resolve_model_dir(str(tmp_path)) == str(tmp_path)
|
||||
|
||||
|
||||
def test_repo_id_resolves_via_snapshot_download(tmp_path, monkeypatch):
|
||||
calls = {}
|
||||
|
||||
def _fake_snapshot_download(self, model_ref, revision=None, allow_patterns=None):
|
||||
def _fake_snapshot_download(model_ref, revision=None, allow_patterns=None):
|
||||
calls["model_ref"] = model_ref
|
||||
calls["revision"] = revision
|
||||
calls["allow_patterns"] = allow_patterns
|
||||
return str(tmp_path / "snapshot")
|
||||
|
||||
monkeypatch.setattr(huggingface_hub.HfApi, "snapshot_download", _fake_snapshot_download)
|
||||
patch_hf_snapshot_download(monkeypatch, _fake_snapshot_download, hf_home=tmp_path)
|
||||
resolved = _resolve_model_dir("openbmb/MiniCPM-o-4_5", revision="abc123")
|
||||
assert resolved == str(tmp_path / "snapshot")
|
||||
assert calls["model_ref"] == "openbmb/MiniCPM-o-4_5"
|
||||
@@ -52,18 +52,18 @@ def test_repo_id_resolves_via_snapshot_download(tmp_path, monkeypatch):
|
||||
assert calls["allow_patterns"] == ["assets/*"]
|
||||
|
||||
|
||||
def test_snapshot_download_failure_propagates(monkeypatch):
|
||||
def test_snapshot_download_failure_propagates(monkeypatch, tmp_path):
|
||||
def _raise(*args, **kwargs):
|
||||
raise FileNotFoundError("offline and not cached")
|
||||
|
||||
monkeypatch.setattr(huggingface_hub.HfApi, "snapshot_download", _raise)
|
||||
patch_hf_snapshot_download(monkeypatch, _raise, hf_home=tmp_path)
|
||||
with pytest.raises(FileNotFoundError):
|
||||
_resolve_model_dir("openbmb/MiniCPM-o-4_5")
|
||||
|
||||
|
||||
def test_init_with_fake_path_does_not_resolve(monkeypatch):
|
||||
def test_init_with_fake_path_does_not_resolve(monkeypatch, tmp_path):
|
||||
"""Mirrors the CPU-test construction: fake model path, no ``revision``."""
|
||||
_no_hub(monkeypatch)
|
||||
_no_hub(monkeypatch, tmp_path)
|
||||
config = SimpleNamespace(
|
||||
model_config=SimpleNamespace(
|
||||
model="/fake/model",
|
||||
@@ -75,8 +75,8 @@ def test_init_with_fake_path_does_not_resolve(monkeypatch):
|
||||
assert model._default_prompt_wav == "/fake/model/assets/HT_ref_audio.wav"
|
||||
|
||||
|
||||
def test_default_prompt_wav_follows_resolved_model_path(monkeypatch):
|
||||
_no_hub(monkeypatch)
|
||||
def test_default_prompt_wav_follows_resolved_model_path(monkeypatch, tmp_path):
|
||||
_no_hub(monkeypatch, tmp_path)
|
||||
config = SimpleNamespace(
|
||||
model_config=SimpleNamespace(
|
||||
model="openbmb/MiniCPM-o-4_5",
|
||||
|
||||
@@ -389,6 +389,38 @@ def test_decode_batch_preprocess_matches_decode_state_updates(mrv2):
|
||||
assert updates[1]["hidden_states"]["trailing_text"].numel() == 0
|
||||
|
||||
|
||||
def test_decode_batch_zero_fills_missing_last_hidden(monkeypatch):
|
||||
tts_pad = torch.full((1, 4), -1.0, dtype=torch.bfloat16)
|
||||
model = _make_minimal_talker(tts_pad_embed=tts_pad)
|
||||
|
||||
def fake_embed_input_ids(input_ids):
|
||||
return input_ids.to(torch.float32).reshape(-1, 1, 1).expand(-1, 1, 4)
|
||||
|
||||
model.embed_input_ids = fake_embed_input_ids
|
||||
warnings: list[tuple[object, ...]] = []
|
||||
monkeypatch.setattr(
|
||||
"vllm_omni.model_executor.models.qwen3_tts.qwen3_tts_talker.logger.warning_once",
|
||||
lambda *args, **kwargs: warnings.append(args),
|
||||
)
|
||||
trailing = torch.arange(8, dtype=torch.float32).reshape(2, 4)
|
||||
|
||||
_, _, past_hidden, _, _ = model.preprocess_decode_batch(
|
||||
input_ids=torch.tensor([101], dtype=torch.long),
|
||||
req_infos=[
|
||||
{
|
||||
"text": ["hello"],
|
||||
"task_type": ["CustomVoice"],
|
||||
"hidden_states": {"trailing_text": trailing},
|
||||
"meta": {"talker_text_offset": 0},
|
||||
}
|
||||
],
|
||||
)
|
||||
|
||||
assert torch.equal(past_hidden.cpu(), torch.zeros((1, 4), dtype=torch.bfloat16))
|
||||
assert len(warnings) == 1
|
||||
assert "zero-filling" in str(warnings[0][0])
|
||||
|
||||
|
||||
def _stub_text_embedding(device_param: torch.nn.Parameter):
|
||||
"""Build a lambda that emulates ``nn.Embedding`` for the ``_device()`` helper.
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.helpers.mock import patch_hf_snapshot_download
|
||||
from vllm_omni.model_executor.models.minimax_music3.weights import (
|
||||
_COMPONENT_WEIGHT_NAME,
|
||||
_REQUIRED_COMPONENTS,
|
||||
@@ -47,16 +48,14 @@ def test_resolve_repo_root_walks_up_from_a_model_subdir(tmp_path):
|
||||
|
||||
def test_resolve_repo_root_resolves_a_hub_id_to_a_local_snapshot(monkeypatch, tmp_path):
|
||||
"""A hub id must resolve through the cache, not against the working directory."""
|
||||
from huggingface_hub import HfApi
|
||||
|
||||
root = _make_root(tmp_path / "snapshots" / "deadbeef")
|
||||
seen = []
|
||||
|
||||
def fake_snapshot_download(self, repo_id, **kwargs):
|
||||
def fake_snapshot_download(repo_id, **kwargs):
|
||||
seen.append(kwargs)
|
||||
return str(root)
|
||||
|
||||
monkeypatch.setattr(HfApi, "snapshot_download", fake_snapshot_download)
|
||||
patch_hf_snapshot_download(monkeypatch, fake_snapshot_download, hf_home=tmp_path)
|
||||
|
||||
assert resolve_repo_root("MiniMaxAI/MiniMax-Music3") == root
|
||||
# Cache-first, and only the component folders.
|
||||
@@ -66,18 +65,16 @@ def test_resolve_repo_root_resolves_a_hub_id_to_a_local_snapshot(monkeypatch, tm
|
||||
|
||||
|
||||
def test_resolve_repo_root_falls_back_to_the_hub_when_the_cache_is_incomplete(monkeypatch, tmp_path):
|
||||
from huggingface_hub import HfApi
|
||||
|
||||
root = _make_root(tmp_path / "snapshots" / "deadbeef")
|
||||
calls = []
|
||||
|
||||
def fake_snapshot_download(self, repo_id, **kwargs):
|
||||
def fake_snapshot_download(repo_id, **kwargs):
|
||||
calls.append(kwargs)
|
||||
if kwargs.get("local_files_only"):
|
||||
raise OSError("incomplete snapshot")
|
||||
return str(root)
|
||||
|
||||
monkeypatch.setattr(HfApi, "snapshot_download", fake_snapshot_download)
|
||||
patch_hf_snapshot_download(monkeypatch, fake_snapshot_download, hf_home=tmp_path)
|
||||
|
||||
assert resolve_repo_root("MiniMaxAI/MiniMax-Music3") == root
|
||||
assert len(calls) == 2
|
||||
@@ -89,19 +86,17 @@ def test_resolve_repo_root_retries_online_when_the_local_lookup_returns_a_partia
|
||||
A returned partial root must fall through to the online call all the same,
|
||||
or startup fails without ever consulting the Hub.
|
||||
"""
|
||||
from huggingface_hub import HfApi
|
||||
|
||||
snapshot = tmp_path / "models--MiniMaxAI--MiniMax-Music3" / "snapshots" / "deadbeef"
|
||||
(snapshot / "language_model").mkdir(parents=True)
|
||||
calls = []
|
||||
|
||||
def fake_snapshot_download(self, repo_id, **kwargs):
|
||||
def fake_snapshot_download(repo_id, **kwargs):
|
||||
calls.append(kwargs)
|
||||
if not kwargs.get("local_files_only"):
|
||||
_make_root(snapshot)
|
||||
return str(snapshot)
|
||||
|
||||
monkeypatch.setattr(HfApi, "snapshot_download", fake_snapshot_download)
|
||||
patch_hf_snapshot_download(monkeypatch, fake_snapshot_download, hf_home=tmp_path)
|
||||
|
||||
assert resolve_repo_root("MiniMaxAI/MiniMax-Music3") == snapshot
|
||||
assert [bool(call.get("local_files_only")) for call in calls] == [True, False]
|
||||
@@ -109,32 +104,28 @@ def test_resolve_repo_root_retries_online_when_the_local_lookup_returns_a_partia
|
||||
|
||||
def test_resolve_repo_root_redownloads_weightless_marker_dirs(monkeypatch, tmp_path):
|
||||
"""Marker folders without their component weights are an interrupted download."""
|
||||
from huggingface_hub import HfApi
|
||||
|
||||
snapshot = tmp_path / "models--MiniMaxAI--MiniMax-Music3" / "snapshots" / "deadbeef"
|
||||
for marker in _ROOT_MARKERS:
|
||||
(snapshot / marker).mkdir(parents=True)
|
||||
calls = []
|
||||
|
||||
def fake_snapshot_download(self, repo_id, **kwargs):
|
||||
def fake_snapshot_download(repo_id, **kwargs):
|
||||
calls.append(kwargs)
|
||||
if not kwargs.get("local_files_only"):
|
||||
_make_root(snapshot)
|
||||
return str(snapshot)
|
||||
|
||||
monkeypatch.setattr(HfApi, "snapshot_download", fake_snapshot_download)
|
||||
patch_hf_snapshot_download(monkeypatch, fake_snapshot_download, hf_home=tmp_path)
|
||||
|
||||
assert resolve_repo_root("MiniMaxAI/MiniMax-Music3") == snapshot
|
||||
assert any(not call.get("local_files_only") for call in calls)
|
||||
|
||||
|
||||
def test_resolve_repo_root_reports_the_original_reference_when_unresolvable(monkeypatch):
|
||||
from huggingface_hub import HfApi
|
||||
|
||||
def fake_snapshot_download(self, repo_id, **kwargs):
|
||||
def test_resolve_repo_root_reports_the_original_reference_when_unresolvable(monkeypatch, tmp_path):
|
||||
def fake_snapshot_download(repo_id, **kwargs):
|
||||
raise OSError("offline")
|
||||
|
||||
monkeypatch.setattr(HfApi, "snapshot_download", fake_snapshot_download)
|
||||
patch_hf_snapshot_download(monkeypatch, fake_snapshot_download, hf_home=tmp_path)
|
||||
|
||||
with pytest.raises(FileNotFoundError, match="MiniMaxAI/MiniMax-Music3"):
|
||||
resolve_repo_root("MiniMaxAI/MiniMax-Music3")
|
||||
@@ -147,19 +138,17 @@ def test_resolve_repo_root_downloads_components_for_a_cold_cache_model_subdir(mo
|
||||
the marker walk fails although the repo id is recoverable from the cache
|
||||
layout and one snapshot_download away from working.
|
||||
"""
|
||||
from huggingface_hub import HfApi
|
||||
|
||||
snapshot = tmp_path / "models--MiniMaxAI--MiniMax-Music3" / "snapshots" / "deadbeef"
|
||||
(snapshot / "language_model").mkdir(parents=True)
|
||||
(snapshot / "tokenizer").mkdir()
|
||||
seen = []
|
||||
|
||||
def fake_snapshot_download(self, repo_id, **kwargs):
|
||||
def fake_snapshot_download(repo_id, **kwargs):
|
||||
seen.append(repo_id)
|
||||
_make_root(snapshot)
|
||||
return str(snapshot)
|
||||
|
||||
monkeypatch.setattr(HfApi, "snapshot_download", fake_snapshot_download)
|
||||
patch_hf_snapshot_download(monkeypatch, fake_snapshot_download, hf_home=tmp_path)
|
||||
|
||||
assert resolve_repo_root(str(snapshot / "language_model")) == snapshot
|
||||
assert seen == ["MiniMaxAI/MiniMax-Music3"]
|
||||
@@ -167,12 +156,11 @@ def test_resolve_repo_root_downloads_components_for_a_cold_cache_model_subdir(mo
|
||||
|
||||
def test_resolve_repo_root_does_not_guess_a_repo_id_for_plain_directories(monkeypatch, tmp_path):
|
||||
"""A directory outside the HF cache has no recoverable repo id."""
|
||||
from huggingface_hub import HfApi
|
||||
|
||||
def fake_snapshot_download(self, repo_id, **kwargs):
|
||||
def fake_snapshot_download(repo_id, **kwargs):
|
||||
raise AssertionError("must not reach the Hub for a plain directory")
|
||||
|
||||
monkeypatch.setattr(HfApi, "snapshot_download", fake_snapshot_download)
|
||||
patch_hf_snapshot_download(monkeypatch, fake_snapshot_download, hf_home=tmp_path)
|
||||
|
||||
plain = tmp_path / "language_model"
|
||||
plain.mkdir()
|
||||
@@ -187,8 +175,6 @@ def test_resolve_repo_root_rejects_a_snapshot_missing_condition_encoder(monkeypa
|
||||
acoustic stage would still fail, so completeness must cover every required
|
||||
component rather than the identification markers alone.
|
||||
"""
|
||||
from huggingface_hub import HfApi
|
||||
|
||||
snapshot = tmp_path / "models--MiniMaxAI--MiniMax-Music3" / "snapshots" / "deadbeef"
|
||||
for marker in _ROOT_MARKERS:
|
||||
folder = snapshot / marker
|
||||
@@ -196,13 +182,13 @@ def test_resolve_repo_root_rejects_a_snapshot_missing_condition_encoder(monkeypa
|
||||
(folder / _COMPONENT_WEIGHT_NAME).write_bytes(b"x")
|
||||
repaired = []
|
||||
|
||||
def fake_snapshot_download(self, repo_id, **kwargs):
|
||||
def fake_snapshot_download(repo_id, **kwargs):
|
||||
if not kwargs.get("local_files_only"):
|
||||
repaired.append(repo_id)
|
||||
_make_root(snapshot)
|
||||
return str(snapshot)
|
||||
|
||||
monkeypatch.setattr(HfApi, "snapshot_download", fake_snapshot_download)
|
||||
patch_hf_snapshot_download(monkeypatch, fake_snapshot_download, hf_home=tmp_path)
|
||||
|
||||
assert resolve_repo_root(str(snapshot)) == snapshot
|
||||
assert repaired == ["MiniMaxAI/MiniMax-Music3"]
|
||||
@@ -210,8 +196,6 @@ def test_resolve_repo_root_rejects_a_snapshot_missing_condition_encoder(monkeypa
|
||||
|
||||
def test_resolve_repo_root_rejects_a_partial_shard_run(monkeypatch, tmp_path):
|
||||
"""One shard of a multi-shard component satisfies a bare glob but cannot load."""
|
||||
from huggingface_hub import HfApi
|
||||
|
||||
stem = _COMPONENT_WEIGHT_NAME.removesuffix(".safetensors")
|
||||
snapshot = tmp_path / "models--MiniMaxAI--MiniMax-Music3" / "snapshots" / "deadbeef"
|
||||
for component in _REQUIRED_COMPONENTS:
|
||||
@@ -223,14 +207,14 @@ def test_resolve_repo_root_rejects_a_partial_shard_run(monkeypatch, tmp_path):
|
||||
(partial / f"{stem}-00001-of-00003.safetensors").write_bytes(b"x")
|
||||
repaired = []
|
||||
|
||||
def fake_snapshot_download(self, repo_id, **kwargs):
|
||||
def fake_snapshot_download(repo_id, **kwargs):
|
||||
if not kwargs.get("local_files_only"):
|
||||
repaired.append(repo_id)
|
||||
for index in (2, 3):
|
||||
(partial / f"{stem}-0000{index}-of-00003.safetensors").write_bytes(b"x")
|
||||
return str(snapshot)
|
||||
|
||||
monkeypatch.setattr(HfApi, "snapshot_download", fake_snapshot_download)
|
||||
patch_hf_snapshot_download(monkeypatch, fake_snapshot_download, hf_home=tmp_path)
|
||||
|
||||
assert resolve_repo_root(str(snapshot)) == snapshot
|
||||
assert repaired == ["MiniMaxAI/MiniMax-Music3"]
|
||||
@@ -242,17 +226,15 @@ def test_resolve_repo_root_threads_revision_and_download_dir(monkeypatch, tmp_pa
|
||||
Resolving components against the default branch while the AR backbone is
|
||||
pinned elsewhere would combine weights from two different commits.
|
||||
"""
|
||||
from huggingface_hub import HfApi
|
||||
|
||||
snapshot = tmp_path / "snapshot"
|
||||
calls = []
|
||||
|
||||
def fake_snapshot_download(self, repo_id, **kwargs):
|
||||
def fake_snapshot_download(repo_id, **kwargs):
|
||||
calls.append(kwargs)
|
||||
_make_root(snapshot)
|
||||
return str(snapshot)
|
||||
|
||||
monkeypatch.setattr(HfApi, "snapshot_download", fake_snapshot_download)
|
||||
patch_hf_snapshot_download(monkeypatch, fake_snapshot_download, hf_home=tmp_path)
|
||||
|
||||
assert resolve_repo_root("MiniMaxAI/MiniMax-Music3", revision="abc123", download_dir="/tmp/hub-cache") == snapshot
|
||||
assert calls
|
||||
@@ -266,18 +248,16 @@ def test_resolve_repo_root_reuses_the_snapshot_revision_from_the_cache_path(monk
|
||||
Re-resolving the repo id alone would fetch the default branch rather than
|
||||
the snapshot the caller is already sitting in.
|
||||
"""
|
||||
from huggingface_hub import HfApi
|
||||
|
||||
snapshot = tmp_path / "models--MiniMaxAI--MiniMax-Music3" / "snapshots" / "cafebabe"
|
||||
(snapshot / "language_model").mkdir(parents=True)
|
||||
calls = []
|
||||
|
||||
def fake_snapshot_download(self, repo_id, **kwargs):
|
||||
def fake_snapshot_download(repo_id, **kwargs):
|
||||
calls.append(kwargs)
|
||||
_make_root(snapshot)
|
||||
return str(snapshot)
|
||||
|
||||
monkeypatch.setattr(HfApi, "snapshot_download", fake_snapshot_download)
|
||||
patch_hf_snapshot_download(monkeypatch, fake_snapshot_download, hf_home=tmp_path)
|
||||
|
||||
assert resolve_repo_root(str(snapshot / "language_model")) == snapshot
|
||||
assert calls
|
||||
@@ -292,8 +272,6 @@ def test_resolve_repo_root_accepts_shard_names_the_loader_can_read(monkeypatch,
|
||||
loadable. Judging it incomplete would force a needless re-download and, with
|
||||
no network, fail on weights that are present and readable.
|
||||
"""
|
||||
from huggingface_hub import HfApi
|
||||
|
||||
stem = _COMPONENT_WEIGHT_NAME.removesuffix(".safetensors")
|
||||
root = tmp_path / "snapshot"
|
||||
for component in _REQUIRED_COMPONENTS:
|
||||
@@ -303,18 +281,16 @@ def test_resolve_repo_root_accepts_shard_names_the_loader_can_read(monkeypatch,
|
||||
(unsharded / _COMPONENT_WEIGHT_NAME).unlink()
|
||||
(unsharded / f"{stem}-fp16.safetensors").write_bytes(b"x")
|
||||
|
||||
def fake_snapshot_download(self, repo_id, **kwargs):
|
||||
def fake_snapshot_download(repo_id, **kwargs):
|
||||
raise AssertionError("must not reach the Hub for readable weights")
|
||||
|
||||
monkeypatch.setattr(HfApi, "snapshot_download", fake_snapshot_download)
|
||||
patch_hf_snapshot_download(monkeypatch, fake_snapshot_download, hf_home=tmp_path)
|
||||
|
||||
assert resolve_repo_root(str(root)) == root
|
||||
|
||||
|
||||
def test_resolve_repo_root_still_rejects_a_partial_run_beside_an_extra_file(monkeypatch, tmp_path):
|
||||
"""An unparsable extra must not mask a genuinely short ``-of-`` run."""
|
||||
from huggingface_hub import HfApi
|
||||
|
||||
stem = _COMPONENT_WEIGHT_NAME.removesuffix(".safetensors")
|
||||
root = tmp_path / "snapshot"
|
||||
for component in _REQUIRED_COMPONENTS:
|
||||
@@ -326,13 +302,13 @@ def test_resolve_repo_root_still_rejects_a_partial_run_beside_an_extra_file(monk
|
||||
(partial / f"{stem}-extra.safetensors").write_bytes(b"x")
|
||||
repaired = []
|
||||
|
||||
def fake_snapshot_download(self, repo_id, **kwargs):
|
||||
def fake_snapshot_download(repo_id, **kwargs):
|
||||
repaired.append(repo_id)
|
||||
for index in (2, 3):
|
||||
(partial / f"{stem}-0000{index}-of-00003.safetensors").write_bytes(b"x")
|
||||
return str(root)
|
||||
|
||||
monkeypatch.setattr(HfApi, "snapshot_download", fake_snapshot_download)
|
||||
patch_hf_snapshot_download(monkeypatch, fake_snapshot_download, hf_home=tmp_path)
|
||||
|
||||
with pytest.raises(FileNotFoundError, match="components are incomplete"):
|
||||
resolve_repo_root(str(root))
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -10,6 +10,9 @@ from vllm_omni.model_executor.models.qwen3_tts.prompt_embeds_builder import (
|
||||
)
|
||||
from vllm_omni.model_executor.stage_input_processors.aura_omni import (
|
||||
SILENT_TEXT,
|
||||
_estimate_tts_prompt_len_from_token_ids,
|
||||
_estimate_tts_prompt_len_official,
|
||||
_normalize_asr_transcript,
|
||||
asr2aura,
|
||||
aura2tts,
|
||||
)
|
||||
@@ -166,7 +169,7 @@ def test_aura2tts_supports_custom_voice_mode():
|
||||
assert tts_input["additional_information"]["task_type"] == ["CustomVoice"]
|
||||
assert tts_input["additional_information"]["speaker"] == ["Vivian"]
|
||||
assert "ref_audio" not in tts_input["additional_information"]
|
||||
assert len(tts_input["prompt_token_ids"]) == 14
|
||||
assert len(tts_input["prompt_token_ids"]) > 0
|
||||
|
||||
|
||||
def test_aura2tts_passes_token_ids_to_qwen3_tts_when_enabled():
|
||||
@@ -196,3 +199,109 @@ def test_aura2tts_passes_token_ids_to_qwen3_tts_when_enabled():
|
||||
|
||||
def test_aura2tts_drops_silent_response():
|
||||
assert aura2tts([_source_output(SILENT_TEXT)]) == []
|
||||
assert aura2tts([_source_output(f"{SILENT_TEXT}<|im_end|>")]) == []
|
||||
|
||||
|
||||
def test_aura2tts_customvoice_uses_official_prompt_len_not_aura_token_count():
|
||||
text = "当然可以,我正看着你呢。"
|
||||
prompt = {
|
||||
"additional_information": {
|
||||
"tts_task_type": ["CustomVoice"],
|
||||
"tts_speaker": ["Vivian"],
|
||||
"tts_language": ["Chinese"],
|
||||
}
|
||||
}
|
||||
aura_token_ids = list(range(80))
|
||||
tts_info = {
|
||||
"task_type": ["CustomVoice"],
|
||||
"language": ["Chinese"],
|
||||
"instruct": [""],
|
||||
"text": [text],
|
||||
"speaker": ["Vivian"],
|
||||
}
|
||||
official = _estimate_tts_prompt_len_official(tts_info, task_type="CustomVoice")
|
||||
if official is None:
|
||||
pytest.skip("Qwen3-TTS tokenizer unavailable for official prompt_len")
|
||||
old_heuristic = _estimate_tts_prompt_len_from_token_ids(
|
||||
aura_token_ids,
|
||||
task_type="CustomVoice",
|
||||
language="Chinese",
|
||||
instruct="",
|
||||
)
|
||||
assert official != old_heuristic
|
||||
|
||||
[tts_input] = aura2tts(
|
||||
[_source_output(text, token_ids=aura_token_ids)],
|
||||
prompt=[prompt],
|
||||
)
|
||||
assert len(tts_input["prompt_token_ids"]) == official
|
||||
assert tts_input["additional_information"]["instruct"] == [""]
|
||||
|
||||
|
||||
def test_aura2tts_strips_im_end_from_spoken_text():
|
||||
prompt = {
|
||||
"additional_information": {
|
||||
"tts_ref_audio": ["ref.wav"],
|
||||
"tts_ref_text": ["Reference transcript sample."],
|
||||
}
|
||||
}
|
||||
[tts_input] = aura2tts([_source_output("你好。<|im_end|>")], prompt=[prompt])
|
||||
assert tts_input["additional_information"]["text"] == ["你好。"]
|
||||
|
||||
|
||||
def test_aura2tts_does_not_treat_chinese_silence_as_special_token():
|
||||
# [沉默] is not <|silent|>; prompt/session must instruct the real token.
|
||||
prompt = {
|
||||
"additional_information": {
|
||||
"tts_ref_audio": ["ref.wav"],
|
||||
"tts_ref_text": ["Reference transcript sample."],
|
||||
}
|
||||
}
|
||||
assert len(aura2tts([_source_output("[沉默]")], prompt=[prompt])) == 1
|
||||
|
||||
|
||||
def test_normalize_asr_transcript_strips_qwen3_asr_markup() -> None:
|
||||
raw = "language Chinese<asr_text>出现《古韵》这本书的时候,提醒我。"
|
||||
assert _normalize_asr_transcript(raw) == "出现《古韵》这本书的时候,提醒我。"
|
||||
assert _normalize_asr_transcript("出现古韵这本书的时候提醒我。") == "出现古韵这本书的时候提醒我。"
|
||||
|
||||
|
||||
def test_next_duplex_sentence_chunk_batches_until_min_chars(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.delenv("VLLM_AURA_SENTENCE_TTS", raising=False)
|
||||
monkeypatch.delenv("VLLM_AURA_SENTENCE_TTS_MIN_CHARS", raising=False)
|
||||
from vllm_omni.model_executor.stage_input_processors.aura_omni import (
|
||||
next_duplex_sentence_chunk,
|
||||
)
|
||||
|
||||
state: dict[str, object] = {}
|
||||
first = "甲" * 12 + "。"
|
||||
assert next_duplex_sentence_chunk(state, first, finished=False) is None
|
||||
second = first + "乙" * 20 + "。"
|
||||
chunk = next_duplex_sentence_chunk(state, second, finished=False)
|
||||
assert chunk is not None
|
||||
assert chunk.startswith("甲" * 12)
|
||||
assert "乙" * 20 in chunk
|
||||
|
||||
|
||||
def test_next_duplex_sentence_chunk_holds_think_silent_and_flushes(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setenv("VLLM_AURA_SENTENCE_TTS", "1")
|
||||
from vllm_omni.model_executor.stage_input_processors.aura_omni import (
|
||||
next_duplex_sentence_chunk,
|
||||
)
|
||||
|
||||
assert next_duplex_sentence_chunk({}, "<think>still thinking", finished=False) is None
|
||||
assert next_duplex_sentence_chunk({}, "<|silent|>", finished=True) is None
|
||||
assert next_duplex_sentence_chunk({}, '<tool_call>{"a":1}</tool_call>', finished=False) is None
|
||||
|
||||
state: dict[str, object] = {}
|
||||
assert next_duplex_sentence_chunk(state, "你好。", finished=False) is None
|
||||
assert next_duplex_sentence_chunk(state, "你好。", finished=True) == "你好。"
|
||||
|
||||
|
||||
def test_next_duplex_sentence_chunk_disabled(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setenv("VLLM_AURA_SENTENCE_TTS", "0")
|
||||
from vllm_omni.model_executor.stage_input_processors.aura_omni import (
|
||||
next_duplex_sentence_chunk,
|
||||
)
|
||||
|
||||
assert next_duplex_sentence_chunk({}, "甲" * 40 + "。", finished=False) is None
|
||||
@@ -0,0 +1,273 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Logic-equivalent checks adapted from AURA_026_p0exp stage processor tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.history import (
|
||||
drop_session_history,
|
||||
get_or_create_session_history,
|
||||
)
|
||||
from vllm_omni.model_executor.stage_input_processors.aura_omni import (
|
||||
SILENT_TEXT,
|
||||
asr2aura,
|
||||
aura2tts,
|
||||
)
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
def _source_output(text: str, request_id: str = "r0") -> SimpleNamespace:
|
||||
return SimpleNamespace(
|
||||
request_id=request_id,
|
||||
outputs=[SimpleNamespace(text=text, token_ids=[1, 2, 3])],
|
||||
)
|
||||
|
||||
|
||||
def test_asr2aura_carries_video_and_transcript() -> None:
|
||||
prompt = {
|
||||
"additional_information": {
|
||||
"aura_system_prompt": "sys",
|
||||
"deferred_multi_modal_data": {"image": ["frame"]},
|
||||
},
|
||||
"multi_modal_data": {},
|
||||
}
|
||||
[next_input] = asr2aura([_source_output("What is happening now?")], prompt=[prompt])
|
||||
assert "What is happening now?" in next_input["prompt"]
|
||||
assert next_input["multi_modal_data"].get("image") == ["frame"]
|
||||
|
||||
|
||||
def test_asr2aura_supports_video_only_observation() -> None:
|
||||
prompt = {
|
||||
"additional_information": {
|
||||
"deferred_multi_modal_data": {"image": ["frame"]},
|
||||
},
|
||||
"multi_modal_data": {},
|
||||
}
|
||||
[next_input] = asr2aura([_source_output("")], prompt=[prompt])
|
||||
assert next_input["multi_modal_data"].get("image") == ["frame"]
|
||||
|
||||
|
||||
def test_asr2aura_duplex_empty_transcript_is_not_a_vision_user_turn() -> None:
|
||||
drop_session_history("duplex-vision")
|
||||
prompt = {
|
||||
"additional_information": {
|
||||
"aura_duplex": True,
|
||||
"session_id": "duplex-vision",
|
||||
"is_speech": False,
|
||||
"deferred_multi_modal_data": {"image": ["frame"]},
|
||||
},
|
||||
"multi_modal_data": {},
|
||||
}
|
||||
[next_input] = asr2aura([_source_output("noise")], prompt=[prompt])
|
||||
assert "[vision]" not in next_input["prompt"]
|
||||
history = get_or_create_session_history("duplex-vision")
|
||||
history.commit_turn("saw a book")
|
||||
assert all(message.get("content") != "[vision]" for message in history.messages)
|
||||
assert [message["role"] for message in history.messages] == ["assistant"]
|
||||
drop_session_history("duplex-vision")
|
||||
|
||||
|
||||
def test_asr2aura_duplex_history_videos_match_prompt_pads() -> None:
|
||||
"""Retained clips then this clip: one <|video_pad|> each, same order as mm data."""
|
||||
drop_session_history("duplex-pads")
|
||||
history = get_or_create_session_history("duplex-pads")
|
||||
history.begin_user_turn("看着手", video=("clip-a", {"fps": 2.0}))
|
||||
history.commit_turn("好的")
|
||||
prompt = {
|
||||
"additional_information": {
|
||||
"aura_duplex": True,
|
||||
"session_id": "duplex-pads",
|
||||
"is_speech": False,
|
||||
"deferred_multi_modal_data": {"video": [("clip-b", {"fps": 2.0})]},
|
||||
},
|
||||
"multi_modal_data": {},
|
||||
}
|
||||
[next_input] = asr2aura([_source_output("")], prompt=[prompt])
|
||||
text = next_input["prompt"]
|
||||
assert text.count("<|video_pad|>") == 2
|
||||
assert "clip-a" not in text and "clip-b" not in text
|
||||
assert next_input["multi_modal_data"]["video"] == [
|
||||
("clip-a", {"fps": 2.0}),
|
||||
("clip-b", {"fps": 2.0}),
|
||||
]
|
||||
assert text.index("<|video_pad|>") < text.rindex("<|im_start|>user")
|
||||
drop_session_history("duplex-pads")
|
||||
|
||||
|
||||
def test_asr2aura_duplex_uses_session_history_prefix() -> None:
|
||||
drop_session_history("duplex-hist")
|
||||
history = get_or_create_session_history("duplex-hist")
|
||||
history.begin_user_turn("prev")
|
||||
history.commit_turn("prev-answer")
|
||||
prompt = {
|
||||
"additional_information": {
|
||||
"aura_duplex": True,
|
||||
"session_id": "duplex-hist",
|
||||
"deferred_multi_modal_data": {"image": ["frame"]},
|
||||
},
|
||||
"multi_modal_data": {},
|
||||
}
|
||||
[next_input] = asr2aura([_source_output("next question")], prompt=[prompt])
|
||||
assert "prev-answer" in next_input["prompt"]
|
||||
assert "next question" in next_input["prompt"]
|
||||
drop_session_history("duplex-hist")
|
||||
|
||||
|
||||
def test_asr2aura_vision_follow_keeps_previous_assistant_in_prefix() -> None:
|
||||
drop_session_history("duplex-watch")
|
||||
history = get_or_create_session_history("duplex-watch")
|
||||
history.begin_user_turn("盯着滑鼠")
|
||||
history.commit_turn("好的,出现的时候我会说")
|
||||
prompt = {
|
||||
"additional_information": {
|
||||
"aura_duplex": True,
|
||||
"session_id": "duplex-watch",
|
||||
"is_speech": False,
|
||||
"deferred_multi_modal_data": {"image": ["frame"]},
|
||||
},
|
||||
"multi_modal_data": {},
|
||||
}
|
||||
[next_input] = asr2aura([_source_output("noise")], prompt=[prompt])
|
||||
assert "好的,出现的时候我会说" in next_input["prompt"]
|
||||
drop_session_history("duplex-watch")
|
||||
|
||||
|
||||
def test_aura2tts_drops_silent_response() -> None:
|
||||
prompt = {"additional_information": {"tts_task_type": "CustomVoice"}}
|
||||
assert aura2tts([_source_output(SILENT_TEXT)], prompt=[prompt]) == []
|
||||
|
||||
|
||||
def test_aura2tts_duplex_does_not_commit_history() -> None:
|
||||
"""Stage1 history has one owner: commit_model_context. aura2tts must not write a second row."""
|
||||
drop_session_history("duplex-silent")
|
||||
history = get_or_create_session_history("duplex-silent")
|
||||
history.begin_user_turn("look")
|
||||
prompt = {
|
||||
"additional_information": {
|
||||
"aura_duplex": True,
|
||||
"session_id": "duplex-silent",
|
||||
"tts_task_type": "CustomVoice",
|
||||
}
|
||||
}
|
||||
assert aura2tts([_source_output(SILENT_TEXT)], prompt=[prompt]) == []
|
||||
assert all(message.get("role") != "assistant" for message in history.messages)
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.plugin import AuraDuplexPlugin
|
||||
|
||||
AuraDuplexPlugin(encode_audio=lambda *_a, **_k: None).commit_model_context(
|
||||
session_id="duplex-silent",
|
||||
assistant_text="只記一次",
|
||||
)
|
||||
assert [message["role"] for message in history.messages] == ["user", "assistant"]
|
||||
assert history.messages[-1]["content"] == "只記一次"
|
||||
drop_session_history("duplex-silent")
|
||||
|
||||
|
||||
def test_aura2tts_skips_history_on_sentence_partial() -> None:
|
||||
drop_session_history("duplex-partial")
|
||||
history = get_or_create_session_history("duplex-partial")
|
||||
history.begin_user_turn("look")
|
||||
prompt = {
|
||||
"additional_information": {
|
||||
"aura_duplex": True,
|
||||
"aura_tts_partial": True,
|
||||
"session_id": "duplex-partial",
|
||||
"tts_task_type": "CustomVoice",
|
||||
"tts_speaker": "Vivian",
|
||||
}
|
||||
}
|
||||
assert len(aura2tts([_source_output("你好,这是一句测试。")], prompt=[prompt])) == 1
|
||||
assert all(message.get("role") != "assistant" for message in history.messages)
|
||||
drop_session_history("duplex-partial")
|
||||
|
||||
|
||||
def test_aura2tts_close_only_does_not_repeat_the_sentence() -> None:
|
||||
prompt = {
|
||||
"additional_information": {
|
||||
"aura_tts_partial": True,
|
||||
"aura_tts_close_only": True,
|
||||
"tts_task_type": "CustomVoice",
|
||||
"tts_speaker": "Vivian",
|
||||
}
|
||||
}
|
||||
[request] = aura2tts([_source_output("上一句不該再送。")], prompt=[prompt])
|
||||
info = request["additional_information"]
|
||||
assert info["text"] == [""]
|
||||
assert info["max_new_tokens"] == [1]
|
||||
assert request["prompt_token_ids"] == [0]
|
||||
|
||||
|
||||
def test_duplex_interception_commits_silent_history_without_aura2tts() -> None:
|
||||
"""Silent Stage1 uses DIRECT_RESPONSE; history must commit on the data-plane path."""
|
||||
from vllm.outputs import CompletionOutput
|
||||
|
||||
from vllm_omni.engine.duplex.contracts import (
|
||||
DuplexFence,
|
||||
DuplexOutputAction,
|
||||
DuplexOutputDecision,
|
||||
duplex_ephemeral_stage_request_id,
|
||||
)
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.data_plane import AuraDataPlaneSession
|
||||
from vllm_omni.outputs import OmniRequestOutput
|
||||
from vllm_omni.outputs.duplex import attach_duplex_output_decision
|
||||
|
||||
drop_session_history("duplex-silent-dp")
|
||||
history = get_or_create_session_history("duplex-silent-dp")
|
||||
history.begin_user_turn("look")
|
||||
fence = DuplexFence("duplex-silent-dp", epoch=0, turn_id=1)
|
||||
request_id = duplex_ephemeral_stage_request_id(fence, stage_id=1)
|
||||
output = OmniRequestOutput(
|
||||
request_id=request_id,
|
||||
finished=True,
|
||||
stage_id=1,
|
||||
outputs=[
|
||||
CompletionOutput(
|
||||
index=0,
|
||||
text=SILENT_TEXT,
|
||||
token_ids=[151669],
|
||||
cumulative_logprob=None,
|
||||
logprobs=None,
|
||||
)
|
||||
],
|
||||
)
|
||||
attach_duplex_output_decision(
|
||||
output,
|
||||
DuplexOutputDecision(
|
||||
action=DuplexOutputAction.DIRECT_RESPONSE,
|
||||
metadata={"model_listen": True, "duplex_direct_response": True},
|
||||
),
|
||||
)
|
||||
plane = AuraDataPlaneSession(encode_audio=lambda *_a, **_k: None)
|
||||
events = list(plane.project_output(output))
|
||||
assert events and events[0].get("silent") is True
|
||||
assert events[0].get("model_context_text") == SILENT_TEXT
|
||||
assert events[0].get("abort_data_plane_request") is True
|
||||
assert history.pending_user == "look"
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.plugin import AuraDuplexPlugin
|
||||
|
||||
AuraDuplexPlugin(encode_audio=lambda *_a, **_k: None).commit_model_context(
|
||||
session_id="duplex-silent-dp",
|
||||
assistant_text=str(events[0]["model_context_text"]),
|
||||
)
|
||||
assert history.pending_user is None
|
||||
assert history.messages[-1]["content"] == SILENT_TEXT
|
||||
drop_session_history("duplex-silent-dp")
|
||||
|
||||
|
||||
def test_proactive_silent_ticks_do_not_evict_a_real_turn() -> None:
|
||||
drop_session_history("duplex-silent-ticks")
|
||||
history = get_or_create_session_history("duplex-silent-ticks")
|
||||
history.begin_user_turn("真正的問題")
|
||||
history.commit_turn("真正的回答")
|
||||
for _ in range(20):
|
||||
history.begin_user_turn("")
|
||||
history.commit_turn("<|silent|>")
|
||||
assert history.messages[0]["content"] == "真正的問題"
|
||||
assert history.messages[1]["content"] == "真正的回答"
|
||||
assert len(history.messages) == 2
|
||||
drop_session_history("duplex-silent-ticks")
|
||||
@@ -11,6 +11,7 @@ which a re-implementation cannot satisfy.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import dataclasses
|
||||
|
||||
import pytest
|
||||
@@ -78,7 +79,9 @@ def test_a_duplex_command_error_is_a_realtime_protocol_error() -> None:
|
||||
|
||||
def test_the_duplex_append_command_is_built_from_the_shared_decoder() -> None:
|
||||
defaults = protocol.RealtimeInputDefaults()
|
||||
event = {"event_id": "event_1", "audio": "", "format": "pcm16", "duration_ms": 40}
|
||||
# Empty ``audio`` is rejected (need bytes and/or video_frames); use silence.
|
||||
silence = base64.b64encode(b"\x00\x00").decode("ascii")
|
||||
event = {"event_id": "event_1", "audio": silence, "format": "pcm16", "duration_ms": 40}
|
||||
|
||||
decoded = protocol.decode_audio_append(event, defaults=defaults)
|
||||
command = duplex_codec.build_append_audio(event, defaults=defaults)
|
||||
|
||||
@@ -239,3 +239,25 @@ def test_wake_up_forwards_tags_to_allocator(monkeypatch):
|
||||
|
||||
assert OmniGPUWorkerBase.wake_up(worker, tags=["weights"]) is True
|
||||
assert calls["tags"] == ["weights"]
|
||||
|
||||
|
||||
def test_cuda_profiler_is_wired_for_omni_worker(monkeypatch):
|
||||
import vllm.profiler.wrapper as profiler_wrapper
|
||||
|
||||
def fake_gpu_worker_init(worker, *args, **kwargs):
|
||||
worker.vllm_config = SimpleNamespace(profiler_config=SimpleNamespace(profiler="cuda"))
|
||||
worker.local_rank = 0
|
||||
worker.rank = 0
|
||||
worker.profiler = None
|
||||
|
||||
class FakeCudaProfiler:
|
||||
def __init__(self, profiler_config):
|
||||
self.profiler_config = profiler_config
|
||||
|
||||
monkeypatch.setattr(base.GPUWorker, "__init__", fake_gpu_worker_init)
|
||||
monkeypatch.setattr(profiler_wrapper, "CudaProfilerWrapper", FakeCudaProfiler)
|
||||
|
||||
worker = OmniGPUWorkerBase()
|
||||
|
||||
assert isinstance(worker.profiler, FakeCudaProfiler)
|
||||
assert worker.profiler.profiler_config.profiler == "cuda"
|
||||
Reference in new issue
Block a user