Merge remote-tracking branch 'origin/main' into qwen-image-2.1
# Conflicts: # vllm_omni/diffusion/executor/multiproc_executor.py # vllm_omni/diffusion/offloader/sequential_backend.py
This commit is contained in:
commit
9174554e40
1332 files changed
+160051
-60504
No files matched your search
@@ -71,15 +71,8 @@ from vllm_omni.experimental.fullduplex.video_stacking import ( # noqa: E402
|
||||
from vllm_omni.metrics.definitions import compute_audio_rtf # noqa: E402
|
||||
|
||||
|
||||
def _url_with_model(url, model, *, autostart=None, session_id=None):
|
||||
# This driver speaks the MiniCPM-o native duplex wire contract.
|
||||
return build_realtime_url(
|
||||
url,
|
||||
model,
|
||||
autostart=autostart,
|
||||
session_id=session_id,
|
||||
extra_query={"native_duplex": "1"},
|
||||
)
|
||||
def _url_with_model(url, model, *, autostart=None):
|
||||
return build_realtime_url(url, model, autostart=autostart)
|
||||
|
||||
|
||||
_read_wav_pcm16 = read_pcm16_wav
|
||||
@@ -213,7 +206,7 @@ class DemoState:
|
||||
item_id = item.get("id")
|
||||
if isinstance(item_id, str) and item_id not in self.assistant_item_ids:
|
||||
self.assistant_item_ids.append(item_id)
|
||||
elif event_type == "response.audio.delta":
|
||||
elif event_type == "response.output_audio.delta":
|
||||
delta = event.get("delta") or event.get("audio")
|
||||
if isinstance(delta, str) and delta:
|
||||
try:
|
||||
@@ -386,8 +379,8 @@ class DemoState:
|
||||
"response.output_item.added",
|
||||
"response.content_part.added",
|
||||
"response.speak",
|
||||
"response.audio.delta",
|
||||
"response.audio.done",
|
||||
"response.output_audio.delta",
|
||||
"response.output_audio.done",
|
||||
"response.content_part.done",
|
||||
"response.output_item.done",
|
||||
"response.done",
|
||||
@@ -402,8 +395,8 @@ class DemoState:
|
||||
)
|
||||
if index is None and event_type not in {
|
||||
"response.speak",
|
||||
"response.audio.delta",
|
||||
"response.audio.done",
|
||||
"response.output_audio.delta",
|
||||
"response.output_audio.done",
|
||||
}:
|
||||
return {}
|
||||
if index is not None:
|
||||
@@ -451,13 +444,13 @@ class DemoState:
|
||||
"response.output_item.added",
|
||||
"response.content_part.added",
|
||||
"response.speak",
|
||||
"response.audio.delta",
|
||||
"response.audio.done",
|
||||
"response.output_audio.delta",
|
||||
"response.output_audio.done",
|
||||
"response.content_part.done",
|
||||
"response.output_item.done",
|
||||
"response.done",
|
||||
]
|
||||
if "response.audio.delta" not in indices_by_type:
|
||||
if "response.output_audio.delta" not in indices_by_type:
|
||||
listen_index = self.first_index(
|
||||
"response.listen",
|
||||
lambda event: (
|
||||
@@ -515,7 +508,7 @@ class DemoState:
|
||||
|
||||
def model_speak_before_audio_ok(self) -> bool:
|
||||
speak_index = self.first_index("response.speak")
|
||||
audio_index = self.first_index("response.audio.delta")
|
||||
audio_index = self.first_index("response.output_audio.delta")
|
||||
return speak_index is not None and audio_index is not None and speak_index < audio_index
|
||||
|
||||
def response_done(self, response_id: str | None) -> bool:
|
||||
@@ -532,7 +525,7 @@ class DemoState:
|
||||
return sum(
|
||||
1
|
||||
for event in self.events
|
||||
if event.get("type") == "response.audio.delta" and self._event_response_id(event) == response_id
|
||||
if event.get("type") == "response.output_audio.delta" and self._event_response_id(event) == response_id
|
||||
)
|
||||
|
||||
def response_playback_sent_ms(self, response_id: str | None) -> int:
|
||||
@@ -565,14 +558,16 @@ class DemoState:
|
||||
return "".join(
|
||||
str(event.get("delta", ""))
|
||||
for event in self.events
|
||||
if event.get("type") == "response.audio_transcript.delta" and self._event_response_id(event) == response_id
|
||||
if event.get("type") == "response.output_audio_transcript.delta"
|
||||
and self._event_response_id(event) == response_id
|
||||
)
|
||||
|
||||
def response_transcript_done(self, response_id: str) -> list[str]:
|
||||
return [
|
||||
str(event.get("transcript", ""))
|
||||
for event in self.events
|
||||
if event.get("type") == "response.audio_transcript.done" and self._event_response_id(event) == response_id
|
||||
if event.get("type") == "response.output_audio_transcript.done"
|
||||
and self._event_response_id(event) == response_id
|
||||
]
|
||||
|
||||
def completed_response_ids(self) -> list[str]:
|
||||
@@ -603,7 +598,7 @@ class DemoState:
|
||||
return 0
|
||||
stale = 0
|
||||
for index, event in enumerate(self.events):
|
||||
if event.get("type") != "response.audio.delta":
|
||||
if event.get("type") != "response.output_audio.delta":
|
||||
continue
|
||||
metadata = event.get("metadata")
|
||||
if not isinstance(metadata, dict):
|
||||
@@ -628,7 +623,6 @@ def _session_update_event(args: DemoArgs) -> dict[str, object]:
|
||||
"playback_commit_policy": "ack_only",
|
||||
"extra_body": {
|
||||
"auto_response": True,
|
||||
"native_duplex": True,
|
||||
"force_listen_count": 0,
|
||||
},
|
||||
}
|
||||
@@ -644,9 +638,6 @@ def _session_update_event(args: DemoArgs) -> dict[str, object]:
|
||||
"type": "session.update",
|
||||
"session": session_payload,
|
||||
}
|
||||
session_id = getattr(args, "session_id", None)
|
||||
if session_id:
|
||||
session_payload["session_id"] = session_id
|
||||
return event
|
||||
|
||||
|
||||
@@ -1126,7 +1117,7 @@ async def _send_clean_turn(
|
||||
state,
|
||||
lambda: state.response_audio_delta_count(response_id) > 0,
|
||||
timeout_s=timeout_s,
|
||||
label=f"{transcript} response.audio.delta",
|
||||
label=f"{transcript} response.output_audio.delta",
|
||||
)
|
||||
await _wait_for(
|
||||
state,
|
||||
@@ -1341,7 +1332,7 @@ async def _send_listen_only_overlap_pair(
|
||||
state,
|
||||
lambda: state.response_audio_delta_count(first_response_id) > 0,
|
||||
timeout_s=timeout_s,
|
||||
label=f"{transcripts[0]} response.audio.delta",
|
||||
label=f"{transcripts[0]} response.output_audio.delta",
|
||||
)
|
||||
if state.response_done(first_response_id):
|
||||
raise RuntimeError("first response completed before overlap input could start")
|
||||
@@ -1460,7 +1451,6 @@ async def run_demo(args: DemoArgs) -> dict[str, object]:
|
||||
args.url,
|
||||
args.model,
|
||||
autostart=False if getattr(args, "ref_audio", None) else None,
|
||||
session_id=getattr(args, "session_id", None),
|
||||
)
|
||||
state = DemoState()
|
||||
stop = asyncio.Event()
|
||||
@@ -1600,7 +1590,9 @@ async def run_demo(args: DemoArgs) -> dict[str, object]:
|
||||
transcript_hints_enabled=transcript_hints_enabled and not continuous_input,
|
||||
)
|
||||
model_speak_event_ok = state.model_speak_before_audio_ok()
|
||||
realtime_audio_lifecycle_ok = state.count("response.audio.delta") > 0 and state.count("response.audio.done") > 0
|
||||
realtime_audio_lifecycle_ok = (
|
||||
state.count("response.output_audio.delta") > 0 and state.count("response.output_audio.done") > 0
|
||||
)
|
||||
completed_response_ids = state.completed_response_ids()
|
||||
observed_turn_response_ids = [response_id for response_id in turn_response_ids if isinstance(response_id, str)]
|
||||
expected_empty_response_ids = {
|
||||
@@ -1625,7 +1617,7 @@ async def run_demo(args: DemoArgs) -> dict[str, object]:
|
||||
state.count("response.created") == state.count("response.done")
|
||||
and len(state.response_ids) == len(completed_response_ids)
|
||||
and len(completed_response_ids) == len(set(completed_response_ids))
|
||||
and state.count("response.audio.done") <= state.count("response.done")
|
||||
and state.count("response.output_audio.done") <= state.count("response.done")
|
||||
and _response_cardinality_ok(
|
||||
completed_response_ids,
|
||||
expected_turns=expected_turns,
|
||||
@@ -1670,6 +1662,10 @@ async def run_demo(args: DemoArgs) -> dict[str, object]:
|
||||
)
|
||||
unexpected_error_events = _unexpected_error_events(state)
|
||||
continuous_input_ok = not continuous_input or state.count("input_audio_buffer.committed") == 0
|
||||
# The server allocates every session id; label metrics with the one it announced.
|
||||
created = state.events[0] if state.events else {}
|
||||
created_session = created.get("session") if isinstance(created, dict) else None
|
||||
server_session_id = created_session.get("id") if isinstance(created_session, dict) else None
|
||||
result = {
|
||||
"ok": terminal_activity_ok
|
||||
and state.count("session.closed") > 0
|
||||
@@ -1707,8 +1703,8 @@ async def run_demo(args: DemoArgs) -> dict[str, object]:
|
||||
"input_transcription_ok": input_transcription_ok,
|
||||
"completed_response_ids": completed_response_ids,
|
||||
"response_timings": state.response_timing_summaries(),
|
||||
"request_metrics": state.session_request_metrics(session_id=args.session_id),
|
||||
"session_metrics": state.session_metric_summary(session_id=args.session_id),
|
||||
"request_metrics": state.session_request_metrics(session_id=server_session_id),
|
||||
"session_metrics": state.session_metric_summary(session_id=server_session_id),
|
||||
"lifecycle_counts_ok": lifecycle_counts_ok,
|
||||
"validation_mode": validation_mode,
|
||||
"scenario": scenario,
|
||||
@@ -1769,7 +1765,6 @@ def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--url", default="ws://localhost:8099/v1/realtime?duplex=1")
|
||||
parser.add_argument("--model", default="openbmb/MiniCPM-o-4_5")
|
||||
parser.add_argument("--session-id", help="Use an explicit public session ID, including for close/reopen tests.")
|
||||
parser.add_argument("--input-wav", required=True)
|
||||
parser.add_argument("--ref-audio", help="Optional WAV used as the MiniCPM-o voice prompt.")
|
||||
parser.add_argument(
|
||||
|
||||
@@ -12,7 +12,7 @@ from tests.helpers.runtime import OmniServer, OpenAIClientHandler
|
||||
|
||||
from ._common import assert_h3_video, dlo_params, run_dlo_wave, run_fl2va
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.advanced_model, pytest.mark.diffusion, pytest.mark.slow]
|
||||
pytestmark = [pytest.mark.advanced_model, pytest.mark.diffusion]
|
||||
H100_TWO_CARD_MARKS = hardware_marks(res={"cuda": "H100"}, num_cards=2)
|
||||
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ from tests.helpers.runtime import OmniServer, OpenAIClientHandler
|
||||
|
||||
from ._common import assert_h3_video, dlo_params, run_dlo_wave, run_ref2va
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.advanced_model, pytest.mark.diffusion, pytest.mark.slow]
|
||||
pytestmark = [pytest.mark.advanced_model, pytest.mark.diffusion]
|
||||
H100_TWO_CARD_MARKS = hardware_marks(res={"cuda": "H100"}, num_cards=2)
|
||||
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ from ._common import (
|
||||
post_sync,
|
||||
)
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.advanced_model, pytest.mark.diffusion, pytest.mark.slow]
|
||||
pytestmark = [pytest.mark.advanced_model, pytest.mark.diffusion]
|
||||
H100_TWO_CARD_MARKS = hardware_marks(res={"cuda": "H100"}, num_cards=2)
|
||||
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ from ._common import (
|
||||
turbo_params,
|
||||
)
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.advanced_model, pytest.mark.diffusion, pytest.mark.slow]
|
||||
pytestmark = [pytest.mark.advanced_model, pytest.mark.diffusion]
|
||||
H100_TWO_CARD_MARKS = hardware_marks(res={"cuda": "H100"}, num_cards=2)
|
||||
|
||||
|
||||
|
||||
@@ -215,7 +215,7 @@ async def run(args: argparse.Namespace) -> dict[str, object]:
|
||||
client.events.count("response.function_call_arguments.done") > 0
|
||||
if args.expect_function_call
|
||||
else (
|
||||
client.events.count("response.audio.delta") >= args.minimum_audio_chunks
|
||||
client.events.count("response.output_audio.delta") >= args.minimum_audio_chunks
|
||||
and (
|
||||
args.allow_incomplete_response
|
||||
or client.events.count("response.done") > completed_responses_at_commit
|
||||
@@ -279,10 +279,10 @@ async def run(args: argparse.Namespace) -> dict[str, object]:
|
||||
transcript = "".join(
|
||||
str(event.get("delta", ""))
|
||||
for event in later
|
||||
if event.get("type") == "response.audio_transcript.delta"
|
||||
if event.get("type") == "response.output_audio_transcript.delta"
|
||||
).lower()
|
||||
return (
|
||||
any(event.get("type") == "response.audio.delta" for event in later)
|
||||
any(event.get("type") == "response.output_audio.delta" for event in later)
|
||||
and any(event.get("type") == "response.done" for event in later)
|
||||
and (args.expected_post_tool_text is None or args.expected_post_tool_text.lower() in transcript)
|
||||
)
|
||||
@@ -297,7 +297,7 @@ async def run(args: argparse.Namespace) -> dict[str, object]:
|
||||
await asyncio.sleep(args.drain_s)
|
||||
|
||||
audio = client.events.audio_bytes()
|
||||
audio_events = _events(client, "response.audio.delta")
|
||||
audio_events = _events(client, "response.output_audio.delta")
|
||||
rates = {event.get("sample_rate_hz") for event in audio_events}
|
||||
if not args.expect_function_call and audio and rates != {OUTPUT_SAMPLE_RATE_HZ}:
|
||||
raise AssertionError(f"unexpected output sample rates: {rates}")
|
||||
|
||||
@@ -10,24 +10,24 @@ import base64
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import time
|
||||
import uuid
|
||||
import wave
|
||||
from collections.abc import Sequence
|
||||
from collections.abc import Awaitable, Callable, Sequence
|
||||
from pathlib import Path
|
||||
from typing import Protocol
|
||||
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
|
||||
|
||||
import numpy as np
|
||||
|
||||
try:
|
||||
import websockets
|
||||
from websockets.exceptions import ConnectionClosed
|
||||
from websockets.exceptions import ConnectionClosed, WebSocketException
|
||||
except ImportError as exc: # pragma: no cover - driver dependency.
|
||||
raise SystemExit("Install websockets first: pip install websockets") from exc
|
||||
|
||||
from vllm_omni.clients.duplex import (
|
||||
EventCollector,
|
||||
write_pcm16_wav,
|
||||
)
|
||||
from vllm_omni.benchmarks.audio_continuity import compute_continuity_stats
|
||||
from vllm_omni.clients.duplex import EventCollector, write_pcm16_wav
|
||||
from vllm_omni.clients.duplex import (
|
||||
wait_for_condition as wait_for,
|
||||
)
|
||||
@@ -35,6 +35,24 @@ from vllm_omni.clients.duplex import (
|
||||
SAMPLE_RATE_HZ = 24_000
|
||||
FRAME_SAMPLES = 1_920
|
||||
FRAME_PERIOD_S = FRAME_SAMPLES / SAMPLE_RATE_HZ
|
||||
AUDIO_DELTA_EVENT_TYPES = frozenset({"response.audio.delta", "response.output_audio.delta"})
|
||||
|
||||
|
||||
class _AudioAcceptanceError(AssertionError):
|
||||
"""A local acceptance failure with numeric diagnostics safe to report."""
|
||||
|
||||
def __init__(self, check: str, message: str, stats: dict[str, object]) -> None:
|
||||
super().__init__(message)
|
||||
self.check = check
|
||||
self.stats = dict(stats)
|
||||
|
||||
|
||||
class _ProbeTransport(Protocol):
|
||||
async def recv(self) -> str | bytes: ...
|
||||
|
||||
async def send(self, message: str) -> None: ...
|
||||
|
||||
async def close(self) -> None: ...
|
||||
|
||||
|
||||
class RawRealtimeProbe:
|
||||
@@ -46,29 +64,33 @@ class RawRealtimeProbe:
|
||||
keeps a transport-only client and reads everything from ``.events``.
|
||||
"""
|
||||
|
||||
def __init__(self, url: str, *, max_size: int = 64 * 1024 * 1024) -> None:
|
||||
def __init__(self, url: str, *, max_size: int = 64 * 1024 * 1024, close_timeout_s: float = 10.0) -> None:
|
||||
self.url = url
|
||||
self.max_size = max_size
|
||||
self.close_timeout_s = close_timeout_s
|
||||
self.events = EventCollector()
|
||||
self._ws = None
|
||||
self._ws: _ProbeTransport | None = None
|
||||
self._reader_task: asyncio.Task[None] | None = None
|
||||
|
||||
async def __aenter__(self) -> RawRealtimeProbe:
|
||||
self._ws = await websockets.connect(self.url, max_size=self.max_size)
|
||||
self._ws = await websockets.connect(self.url, max_size=self.max_size, close_timeout=self.close_timeout_s)
|
||||
self._reader_task = asyncio.create_task(self._read_events())
|
||||
return self
|
||||
|
||||
async def __aexit__(self, exc_type, exc, traceback) -> None:
|
||||
if self._ws is not None:
|
||||
await self._ws.close()
|
||||
if self._reader_task is not None:
|
||||
self._reader_task.cancel()
|
||||
try:
|
||||
await self._reader_task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
try:
|
||||
if self._ws is not None:
|
||||
await self._ws.close()
|
||||
finally:
|
||||
if self._reader_task is not None:
|
||||
self._reader_task.cancel()
|
||||
try:
|
||||
await self._reader_task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
async def _read_events(self) -> None:
|
||||
assert self._ws is not None
|
||||
try:
|
||||
while True:
|
||||
raw = await self._ws.recv()
|
||||
@@ -81,6 +103,7 @@ class RawRealtimeProbe:
|
||||
return
|
||||
|
||||
async def send(self, event: dict[str, object]) -> None:
|
||||
assert self._ws is not None
|
||||
await self._ws.send(json.dumps(event))
|
||||
|
||||
|
||||
@@ -142,6 +165,38 @@ def _events(client: RawRealtimeProbe, event_type: str) -> list[dict[str, object]
|
||||
return [event for event in client.events.events if event.get("type") == event_type]
|
||||
|
||||
|
||||
def _audio_events(client: RawRealtimeProbe) -> list[dict[str, object]]:
|
||||
"""Return audio deltas from both current and legacy Realtime event names."""
|
||||
return [event for event in client.events.events if event.get("type") in AUDIO_DELTA_EVENT_TYPES]
|
||||
|
||||
|
||||
def _validated_audio_event(event: dict[str, object]) -> bytes:
|
||||
"""Decode one wire audio delta without depending on client event aliases."""
|
||||
encoded = event.get("delta")
|
||||
if not isinstance(encoded, str):
|
||||
raise ValueError("missing_audio_delta")
|
||||
try:
|
||||
chunk = base64.b64decode(encoded, validate=True)
|
||||
except ValueError:
|
||||
raise ValueError("invalid_audio_base64") from None
|
||||
if chunk:
|
||||
if len(chunk) % 2:
|
||||
raise ValueError("unaligned_pcm16_packet")
|
||||
if event.get("sample_rate_hz") != SAMPLE_RATE_HZ:
|
||||
raise ValueError("invalid_audio_sample_rate")
|
||||
if not isinstance(event.get("response_id"), str) or not event.get("response_id"):
|
||||
raise ValueError("missing_audio_response_id")
|
||||
return chunk
|
||||
|
||||
|
||||
def _validated_audio_chunks(client: RawRealtimeProbe) -> list[tuple[dict[str, object], bytes]]:
|
||||
return [(event, _validated_audio_event(event)) for event in _audio_events(client)]
|
||||
|
||||
|
||||
def _audio_bytes(client: RawRealtimeProbe) -> bytes:
|
||||
return b"".join(chunk for _, chunk in _validated_audio_chunks(client) if chunk)
|
||||
|
||||
|
||||
async def _open_session(
|
||||
args: argparse.Namespace,
|
||||
*,
|
||||
@@ -151,22 +206,7 @@ async def _open_session(
|
||||
) -> tuple[RawRealtimeProbe, dict[str, object]]:
|
||||
client = RawRealtimeProbe(_realtime_url(args.url, args.model, session_id))
|
||||
await client.__aenter__()
|
||||
await client.send(
|
||||
{
|
||||
"type": "session.update",
|
||||
"session": {
|
||||
"session_id": session_id,
|
||||
"model": args.model,
|
||||
"modalities": ["audio", "text"],
|
||||
"input_audio_format": "pcm_f32le",
|
||||
"output_audio_format": "pcm16",
|
||||
"voice": args.voice,
|
||||
"instructions": persona,
|
||||
"turn_detection": None,
|
||||
"extra_body": {"auto_response": True},
|
||||
},
|
||||
}
|
||||
)
|
||||
await client.send(_session_update(args, session_id=session_id, persona=persona))
|
||||
event_type = "error" if expect_error else "session.created"
|
||||
await wait_for(
|
||||
lambda: client.events.count(event_type) > 0,
|
||||
@@ -176,6 +216,23 @@ async def _open_session(
|
||||
return client, _events(client, event_type)[-1]
|
||||
|
||||
|
||||
def _session_update(args: argparse.Namespace, *, session_id: str, persona: str) -> dict[str, object]:
|
||||
return {
|
||||
"type": "session.update",
|
||||
"session": {
|
||||
"session_id": session_id,
|
||||
"model": args.model,
|
||||
"modalities": ["audio", "text"],
|
||||
"input_audio_format": "pcm_f32le",
|
||||
"output_audio_format": "pcm16",
|
||||
"voice": args.voice,
|
||||
"instructions": persona,
|
||||
"turn_detection": None,
|
||||
"extra_body": {"auto_response": True},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
async def _close_session(client: RawRealtimeProbe, *, timeout_s: float) -> None:
|
||||
await client.send({"type": "session.close"})
|
||||
await wait_for(
|
||||
@@ -200,23 +257,24 @@ async def _stream_frames(
|
||||
frame_count = min(frame_count, max_frames)
|
||||
for seq in range(frame_count):
|
||||
frame = pcm[seq * FRAME_SAMPLES : (seq + 1) * FRAME_SAMPLES]
|
||||
frame = np.pad(frame, (0, FRAME_SAMPLES - frame.size))
|
||||
frame = np.ascontiguousarray(frame, dtype="<f4")
|
||||
await client.send(
|
||||
{
|
||||
"type": "input_audio_buffer.append",
|
||||
"audio": base64.b64encode(frame).decode("ascii"),
|
||||
"format": "pcm_f32le",
|
||||
"sample_rate_hz": SAMPLE_RATE_HZ,
|
||||
"duration_ms": 80,
|
||||
"audio_end_ms": (seq + 1) * 80,
|
||||
"is_speech": bool(np.sqrt(np.mean(np.square(frame))) >= 1e-4),
|
||||
}
|
||||
)
|
||||
await client.send(_frame_event(frame, seq))
|
||||
await asyncio.sleep(FRAME_PERIOD_S)
|
||||
return frame_count
|
||||
|
||||
|
||||
def _frame_event(frame: np.ndarray, seq: int) -> dict[str, object]:
|
||||
frame = np.ascontiguousarray(np.pad(frame, (0, FRAME_SAMPLES - frame.size)), dtype="<f4")
|
||||
return {
|
||||
"type": "input_audio_buffer.append",
|
||||
"audio": base64.b64encode(frame).decode("ascii"),
|
||||
"format": "pcm_f32le",
|
||||
"sample_rate_hz": SAMPLE_RATE_HZ,
|
||||
"duration_ms": 80,
|
||||
"audio_end_ms": (seq + 1) * 80,
|
||||
"is_speech": bool(np.sqrt(np.mean(np.square(frame))) >= 1e-4),
|
||||
}
|
||||
|
||||
|
||||
def _audio_frame_stats(
|
||||
raw: bytes,
|
||||
*,
|
||||
@@ -242,11 +300,7 @@ def _audio_frame_stats(
|
||||
|
||||
|
||||
def _response_ids(client: RawRealtimeProbe) -> set[str]:
|
||||
return {
|
||||
str(event["response_id"])
|
||||
for event in _events(client, "response.audio.delta")
|
||||
if isinstance(event.get("response_id"), str)
|
||||
}
|
||||
return {str(event["response_id"]) for event in _audio_events(client) if isinstance(event.get("response_id"), str)}
|
||||
|
||||
|
||||
def _session_result(
|
||||
@@ -256,40 +310,66 @@ def _session_result(
|
||||
args: argparse.Namespace,
|
||||
minimum_chunks: int,
|
||||
) -> tuple[bytes, set[str], dict[str, object]]:
|
||||
chunks = sum(len(items) for items in client.events.response_audio.values())
|
||||
raw = client.events.audio_bytes()
|
||||
if chunks < minimum_chunks or not raw or len(raw) % 2:
|
||||
raise AssertionError(f"invalid PCM16 output: chunks={chunks}, bytes={len(raw)}")
|
||||
if isinstance(client, RawRealtimeProbe):
|
||||
audio_chunks = _validated_audio_chunks(client)
|
||||
chunks = sum(bool(chunk) for _, chunk in audio_chunks)
|
||||
raw = b"".join(chunk for _, chunk in audio_chunks if chunk)
|
||||
else:
|
||||
# Unit fixtures may provide an already-decoded EventCollector without
|
||||
# retaining the base64 wire field. Real websocket probes always take
|
||||
# the strict wire-validation path above.
|
||||
chunks = sum(len(items) for items in client.events.response_audio.values())
|
||||
raw = client.events.audio_bytes()
|
||||
stats: dict[str, object] = {"audio_chunks": chunks, "audio_samples": len(raw) // 2}
|
||||
if not raw or len(raw) % 2:
|
||||
raise _AudioAcceptanceError("pcm16_output", f"invalid PCM16 output: chunks={chunks}, bytes={len(raw)}", stats)
|
||||
pcm = np.frombuffer(raw, dtype="<i2").astype(np.float32) / 32768.0
|
||||
rms = float(np.sqrt(np.mean(np.square(pcm))))
|
||||
stats["audio_rms"] = rms
|
||||
# This low floor only catches corrupt, non-finite, or effectively zero PCM.
|
||||
# Audible speech is checked per frame below with the higher 1e-3 default.
|
||||
if not np.isfinite(pcm).all() or rms <= 1e-5:
|
||||
raise AssertionError(f"output audio is non-finite or silent: samples={pcm.size}, rms={rms}")
|
||||
rates = {
|
||||
int(event["sample_rate_hz"])
|
||||
for event in _events(client, "response.audio.delta")
|
||||
if isinstance(event.get("sample_rate_hz"), int)
|
||||
}
|
||||
raise _AudioAcceptanceError(
|
||||
"audio_rms", f"output audio is non-finite or silent: samples={pcm.size}, rms={rms}", stats
|
||||
)
|
||||
rates = {rate for event in _audio_events(client) if isinstance(rate := event.get("sample_rate_hz"), int)}
|
||||
if rates != {SAMPLE_RATE_HZ}:
|
||||
raise AssertionError(f"unexpected output sample rates: {sorted(rates)}")
|
||||
stats = _audio_frame_stats(
|
||||
raw,
|
||||
input_frames=input_frames,
|
||||
voiced_frame_rms_threshold=args.voiced_frame_rms_threshold,
|
||||
)
|
||||
if not 0 <= int(stats["frame_deficit"]) <= args.max_frame_deficit:
|
||||
raise AssertionError(f"invalid synchronous frame accounting: input={input_frames}, stats={stats}")
|
||||
raise _AudioAcceptanceError("sample_rate", f"unexpected output sample rates: {sorted(rates)}", stats)
|
||||
if input_frames < 1:
|
||||
raise _AudioAcceptanceError("input_frames", f"audio received without input frames: input={input_frames}", stats)
|
||||
try:
|
||||
frame_stats = _audio_frame_stats(
|
||||
raw,
|
||||
input_frames=input_frames,
|
||||
voiced_frame_rms_threshold=args.voiced_frame_rms_threshold,
|
||||
)
|
||||
except AssertionError as exc:
|
||||
# _audio_frame_stats only formats local sample counts, not wire data.
|
||||
raise _AudioAcceptanceError("whole_codec_frames", str(exc), stats) from exc
|
||||
stats.update(frame_stats)
|
||||
if chunks < minimum_chunks:
|
||||
raise _AudioAcceptanceError(
|
||||
"audio_chunks", f"insufficient audio chunks: chunks={chunks}, minimum={minimum_chunks}", stats
|
||||
)
|
||||
if not 0 <= int(frame_stats["frame_deficit"]) <= args.max_frame_deficit:
|
||||
raise _AudioAcceptanceError(
|
||||
"frame_deficit",
|
||||
f"invalid synchronous frame accounting: input={input_frames}, maximum_deficit={args.max_frame_deficit}, "
|
||||
f"stats={stats}",
|
||||
stats,
|
||||
)
|
||||
min_voiced_frames = int(args.min_voiced_frames)
|
||||
if min_voiced_frames < 1:
|
||||
raise ValueError(f"min_voiced_frames must be positive, got {min_voiced_frames}")
|
||||
if int(stats["voiced_frames"]) < min_voiced_frames:
|
||||
raise AssertionError(
|
||||
f"output contained insufficient audible speech: minimum_voiced_frames={min_voiced_frames}, stats={stats}"
|
||||
if int(frame_stats["voiced_frames"]) < min_voiced_frames:
|
||||
raise _AudioAcceptanceError(
|
||||
"voiced_frames",
|
||||
f"output contained insufficient audible speech: minimum_voiced_frames={min_voiced_frames}, stats={stats}",
|
||||
stats,
|
||||
)
|
||||
runtime_metadata = [
|
||||
metadata["vllm_omni"]
|
||||
for event in _events(client, "response.audio.delta")
|
||||
for event in _audio_events(client)
|
||||
if isinstance((metadata := event.get("metadata")), dict) and isinstance(metadata.get("vllm_omni"), dict)
|
||||
]
|
||||
if not any(
|
||||
@@ -298,18 +378,19 @@ def _session_result(
|
||||
and item.get("runner_kv_backed") is True
|
||||
for item in runtime_metadata
|
||||
):
|
||||
raise AssertionError(f"audio events did not prove the scheduler data plane: {runtime_metadata}")
|
||||
raise _AudioAcceptanceError(
|
||||
"scheduler_data_plane", "audio events did not prove the scheduler data plane", stats
|
||||
)
|
||||
response_ids = _response_ids(client)
|
||||
if len(response_ids) != 1:
|
||||
raise AssertionError(f"continuous stream used multiple responses: {sorted(response_ids)}")
|
||||
raise _AudioAcceptanceError(
|
||||
"response_identity", f"continuous stream requires one response: count={len(response_ids)}", stats
|
||||
)
|
||||
return (
|
||||
raw,
|
||||
response_ids,
|
||||
{
|
||||
**stats,
|
||||
"audio_chunks": chunks,
|
||||
"audio_samples": len(raw) // 2,
|
||||
"audio_rms": rms,
|
||||
"response_ids": sorted(response_ids),
|
||||
},
|
||||
)
|
||||
@@ -332,6 +413,8 @@ def _save(output_dir: Path, name: str, client: RawRealtimeProbe, raw: bytes) ->
|
||||
|
||||
|
||||
async def run(args: argparse.Namespace) -> dict[str, object]:
|
||||
if getattr(args, "sessions", None) is not None:
|
||||
return await run_load(args)
|
||||
input_path = Path(args.input_wav)
|
||||
input_identity = _input_identity(
|
||||
input_path,
|
||||
@@ -381,14 +464,12 @@ async def run(args: argparse.Namespace) -> dict[str, object]:
|
||||
)
|
||||
await asyncio.gather(
|
||||
wait_for(
|
||||
lambda: len(primary.events.audio_bytes()) // (2 * FRAME_SAMPLES) >= primary_frames - args.max_frame_deficit,
|
||||
lambda: len(_audio_bytes(primary)) // (2 * FRAME_SAMPLES) >= primary_frames - args.max_frame_deficit,
|
||||
timeout_s=args.timeout_s,
|
||||
label="primary frame coverage",
|
||||
),
|
||||
wait_for(
|
||||
lambda: (
|
||||
len(secondary.events.audio_bytes()) // (2 * FRAME_SAMPLES) >= secondary_frames - args.max_frame_deficit
|
||||
),
|
||||
lambda: (len(_audio_bytes(secondary)) // (2 * FRAME_SAMPLES) >= secondary_frames - args.max_frame_deficit),
|
||||
timeout_s=args.timeout_s,
|
||||
label="secondary frame coverage",
|
||||
),
|
||||
@@ -426,16 +507,14 @@ async def run(args: argparse.Namespace) -> dict[str, object]:
|
||||
await asyncio.gather(
|
||||
wait_for(
|
||||
lambda: (
|
||||
len(secondary.events.audio_bytes()) // (2 * FRAME_SAMPLES)
|
||||
>= secondary_total_frames - args.max_frame_deficit
|
||||
len(_audio_bytes(secondary)) // (2 * FRAME_SAMPLES) >= secondary_total_frames - args.max_frame_deficit
|
||||
),
|
||||
timeout_s=args.timeout_s,
|
||||
label="survivor frame coverage after slot recycle",
|
||||
),
|
||||
wait_for(
|
||||
lambda: (
|
||||
len(replacement.events.audio_bytes()) // (2 * FRAME_SAMPLES)
|
||||
>= replacement_frames - args.max_frame_deficit
|
||||
len(_audio_bytes(replacement)) // (2 * FRAME_SAMPLES) >= replacement_frames - args.max_frame_deficit
|
||||
),
|
||||
timeout_s=args.timeout_s,
|
||||
label="replacement frame coverage",
|
||||
@@ -493,6 +572,284 @@ async def run(args: argparse.Namespace) -> dict[str, object]:
|
||||
return result
|
||||
|
||||
|
||||
def _distribution(values: list[float]) -> dict[str, int | float | None]:
|
||||
if not values:
|
||||
return {"count": 0, "median": None, "p99": None, "max": None, "argmax_index": None}
|
||||
return {
|
||||
"count": len(values),
|
||||
"median": float(np.median(values)),
|
||||
"p99": float(np.quantile(values, 0.99)),
|
||||
"max": max(values),
|
||||
"argmax_index": int(np.argmax(values)),
|
||||
}
|
||||
|
||||
|
||||
def _load_metrics(client: RawRealtimeProbe, sends: list[tuple[float, float, float]]) -> dict[str, object]:
|
||||
# Use the collector's local clock, never a timestamp supplied by the server.
|
||||
packets: list[dict[str, object]] = []
|
||||
response_ids: set[str] = set()
|
||||
packet_times: list[float] = []
|
||||
packet_bytes: list[int] = []
|
||||
invalid_packets: list[dict[str, object]] = []
|
||||
samples = 0
|
||||
for index, (raw, received) in enumerate(zip(client.events.events, client.events.event_received_at_s, strict=True)):
|
||||
if raw.get("type") not in AUDIO_DELTA_EVENT_TYPES:
|
||||
continue
|
||||
try:
|
||||
chunk = _validated_audio_event(raw)
|
||||
except ValueError as exc:
|
||||
# Only fixed diagnostic codes from the validator are exported,
|
||||
# never audio payloads or details from the remote endpoint.
|
||||
invalid_packets.append({"event_index": index, "received_at_s": received, "code": str(exc)})
|
||||
continue
|
||||
if chunk:
|
||||
samples += len(chunk) // 2
|
||||
packet_times.append(received)
|
||||
packet_bytes.append(len(chunk))
|
||||
response_id = raw.get("response_id")
|
||||
packets.append({"received_at_s": received, "samples": len(chunk) // 2, "response_id": response_id})
|
||||
if isinstance(response_id, str) and response_id:
|
||||
response_ids.add(response_id)
|
||||
intervals = [(b - a) * 1000 for a, b in zip(packet_times, packet_times[1:])]
|
||||
first_send = sends[0][1] if sends else None
|
||||
audio_duration = samples / SAMPLE_RATE_HZ
|
||||
first_audio_ms = (packet_times[0] - first_send) * 1000 if packet_times and first_send is not None else None
|
||||
client_rtf = (packet_times[-1] - first_send) / audio_duration if audio_duration and first_send is not None else None
|
||||
continuity = compute_continuity_stats(packet_times, packet_bytes, SAMPLE_RATE_HZ) if packet_times else None
|
||||
lateness = _distribution([max(0.0, sent - planned) * 1000 for planned, sent, _ in sends])
|
||||
p99_lateness = lateness["p99"]
|
||||
return {
|
||||
"input_frames": len(sends),
|
||||
"output_samples": samples,
|
||||
# Populate frame accounting from _session_result, including on failure.
|
||||
"frame_deficit": None,
|
||||
"response_ids": sorted(response_ids),
|
||||
"client_first_audio_after_stream_start_ms": first_audio_ms,
|
||||
"client_stream_rtf": client_rtf,
|
||||
"client_audio_packet_interval_ms": _distribution(intervals),
|
||||
"client_send_lateness_ms": lateness,
|
||||
"client_pacing_warning": isinstance(p99_lateness, float) and p99_lateness > FRAME_PERIOD_S * 1000,
|
||||
"audio_underrun_s": continuity.max_underrun_s if continuity else None,
|
||||
"audio_underrun_event_count": continuity.underrun_event_count if continuity else None,
|
||||
"audio_continuity_ok": continuity.is_continuous if continuity else None,
|
||||
"input_timeline": [
|
||||
{"frame_index": i, "planned_at_s": planned, "send_started_at_s": sent, "send_completed_at_s": completed}
|
||||
for i, (planned, sent, completed) in enumerate(sends)
|
||||
],
|
||||
"audio_packet_timeline": packets,
|
||||
"invalid_audio_packets": invalid_packets,
|
||||
}
|
||||
|
||||
|
||||
def _check_load_connection(client: RawRealtimeProbe) -> None:
|
||||
if client.events.errors():
|
||||
raise RuntimeError("server emitted a Realtime error (see the session error count)")
|
||||
if client._reader_task is not None and client._reader_task.done():
|
||||
client._reader_task.result() # Propagate malformed JSON/reader failures.
|
||||
raise RuntimeError("connection closed before session completion")
|
||||
|
||||
|
||||
async def _wait_load_event(client: RawRealtimeProbe, event_type: str, timeout_s: float) -> None:
|
||||
def received() -> bool:
|
||||
if client.events.count(event_type):
|
||||
return True
|
||||
_check_load_connection(client)
|
||||
return False
|
||||
|
||||
await wait_for(received, timeout_s=timeout_s, label=event_type)
|
||||
|
||||
|
||||
async def _paced_load_frames(
|
||||
client: RawRealtimeProbe,
|
||||
pcm: np.ndarray,
|
||||
*,
|
||||
epoch: float,
|
||||
timeout_s: float,
|
||||
sends: list[tuple[float, float, float]],
|
||||
clock: Callable[[], float] = time.monotonic,
|
||||
sleep: Callable[[float], Awaitable[None]] = asyncio.sleep,
|
||||
) -> None:
|
||||
next_send = epoch
|
||||
for seq in range(math.ceil(pcm.size / FRAME_SAMPLES)):
|
||||
await sleep(max(0.0, next_send - clock()))
|
||||
_check_load_connection(client)
|
||||
event = _frame_event(pcm[seq * FRAME_SAMPLES : (seq + 1) * FRAME_SAMPLES], seq)
|
||||
started = clock()
|
||||
await asyncio.wait_for(client.send(event), timeout=timeout_s)
|
||||
completed = clock()
|
||||
sends.append((epoch + seq * FRAME_PERIOD_S, started, completed))
|
||||
# Do not burst to catch up after a stalled send; report accumulated lag.
|
||||
next_send = max(epoch + (seq + 1) * FRAME_PERIOD_S, completed + FRAME_PERIOD_S)
|
||||
|
||||
|
||||
async def _request_load_close(client: RawRealtimeProbe, timeout_s: float) -> None:
|
||||
await client.send({"type": "session.close"})
|
||||
await _wait_load_event(client, "session.closed", timeout_s)
|
||||
|
||||
|
||||
async def _run_load_session(
|
||||
args: argparse.Namespace,
|
||||
pcm: np.ndarray,
|
||||
index: int,
|
||||
ready: asyncio.Future[None],
|
||||
start: asyncio.Future[float],
|
||||
) -> dict[str, object]:
|
||||
session_id = f"personaplex-load-{index}-{uuid.uuid4().hex}"
|
||||
client = RawRealtimeProbe(_realtime_url(args.url, args.model, session_id), close_timeout_s=args.cleanup_timeout_s)
|
||||
sends: list[tuple[float, float, float]] = []
|
||||
error: str | None = None
|
||||
cleanup_error: str | None = None
|
||||
metrics: dict[str, object] | None = None
|
||||
session_stats: dict[str, object] = {}
|
||||
acceptance_check: str | None = None
|
||||
phase = "admission"
|
||||
try:
|
||||
async with client:
|
||||
try:
|
||||
await asyncio.wait_for(
|
||||
client.send(_session_update(args, session_id=session_id, persona=args.persona)), args.timeout_s
|
||||
)
|
||||
await _wait_load_event(client, "session.created", args.timeout_s)
|
||||
capabilities = _capabilities(_events(client, "session.created")[-1])
|
||||
if (
|
||||
capabilities.get("chunk_period_ms") != 80
|
||||
or capabilities.get("supports_multi_session_same_replica") is not True
|
||||
):
|
||||
raise AssertionError("server did not advertise PersonaPlex multi-session capabilities")
|
||||
ready.set_result(None)
|
||||
phase = "stream"
|
||||
epoch = await asyncio.shield(start)
|
||||
await _paced_load_frames(client, pcm, epoch=epoch, timeout_s=args.timeout_s, sends=sends)
|
||||
phase = "drain"
|
||||
# Fixed, reported observation window. Closing must not extend
|
||||
# it and let a slow session pass by flushing after the cutoff.
|
||||
await asyncio.sleep(args.drain_s)
|
||||
_check_load_connection(client)
|
||||
_, _, session_stats = _session_result(
|
||||
client, input_frames=len(sends), args=args, minimum_chunks=args.minimum_audio_chunks
|
||||
)
|
||||
finally:
|
||||
metrics = _load_metrics(client, sends)
|
||||
if client.events.count("session.created") and not client.events.count("session.closed"):
|
||||
try:
|
||||
# Send and acknowledgement share one short cleanup budget,
|
||||
# independent of the potentially long inference timeout.
|
||||
await asyncio.wait_for(
|
||||
_request_load_close(client, args.cleanup_timeout_s), args.cleanup_timeout_s
|
||||
)
|
||||
except (OSError, asyncio.TimeoutError, ValueError, RuntimeError, WebSocketException) as exc:
|
||||
cleanup_error = f"cleanup: {type(exc).__name__}"
|
||||
except (OSError, asyncio.TimeoutError, ValueError, RuntimeError, AssertionError, WebSocketException) as exc:
|
||||
if isinstance(exc, _AudioAcceptanceError):
|
||||
acceptance_check = exc.check
|
||||
session_stats = exc.stats
|
||||
error = f"{phase}: AssertionError: {exc}"
|
||||
else:
|
||||
# Other assertions/errors may embed handshake credentials or wire
|
||||
# metadata. Only our local numeric acceptance diagnostics are safe.
|
||||
error = f"{phase}: {type(exc).__name__}"
|
||||
finally:
|
||||
# Admission failure must not leave the other sessions at the barrier.
|
||||
if not ready.done():
|
||||
ready.set_result(None)
|
||||
if metrics is None:
|
||||
metrics = _load_metrics(client, sends)
|
||||
if cleanup_error:
|
||||
error = f"{error}; {cleanup_error}" if error else cleanup_error
|
||||
if client.events.errors():
|
||||
error = error or "server emitted a Realtime error"
|
||||
if metrics["invalid_audio_packets"]:
|
||||
error = error or "invalid audio packets"
|
||||
first_audio = metrics["client_first_audio_after_stream_start_ms"]
|
||||
if isinstance(first_audio, float) and first_audio < 0:
|
||||
error = error or "audio arrived before the first input frame"
|
||||
rtf = metrics["client_stream_rtf"]
|
||||
if args.max_client_rtf is not None and isinstance(rtf, float) and rtf > args.max_client_rtf:
|
||||
error = error or f"client_stream_rtf exceeds {args.max_client_rtf}"
|
||||
return {
|
||||
"index": index,
|
||||
"session_id": session_id,
|
||||
"ok": error is None,
|
||||
"error": error,
|
||||
"acceptance_check": acceptance_check,
|
||||
"server_error_count": len(client.events.errors()),
|
||||
"server_error_codes": [
|
||||
str(body.get("code", "unknown")) if isinstance(body := event.get("error"), dict) else "unknown"
|
||||
for event in client.events.errors()
|
||||
],
|
||||
**metrics,
|
||||
**session_stats,
|
||||
}
|
||||
|
||||
|
||||
async def run_load(args: argparse.Namespace) -> dict[str, object]:
|
||||
input_path = Path(args.input_wav)
|
||||
identity = _input_identity(input_path, expected_sha256=args.expected_input_sha256)
|
||||
pcm = _read_wav_as_float32(input_path)
|
||||
if args.tail_s:
|
||||
pcm = np.concatenate([pcm, np.zeros(round(args.tail_s * SAMPLE_RATE_HZ), dtype=np.float32)])
|
||||
pcm = pcm[: args.load_frames * FRAME_SAMPLES]
|
||||
output_dir = Path(args.output_dir)
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
# Refuse to silently overwrite evidence from a previous sweep.
|
||||
result_path = output_dir / "load-result.json"
|
||||
if result_path.exists():
|
||||
raise FileExistsError(result_path)
|
||||
loop = asyncio.get_running_loop()
|
||||
start: asyncio.Future[float] = loop.create_future()
|
||||
ready: list[asyncio.Future[None]] = [loop.create_future() for _ in range(args.sessions)]
|
||||
tasks = [asyncio.create_task(_run_load_session(args, pcm, i, r, start)) for i, r in enumerate(ready)]
|
||||
try:
|
||||
await asyncio.gather(*ready)
|
||||
start.set_result(time.monotonic())
|
||||
rows = await asyncio.gather(*tasks)
|
||||
finally:
|
||||
for task in tasks:
|
||||
if not task.done():
|
||||
task.cancel()
|
||||
await asyncio.gather(*tasks, return_exceptions=True)
|
||||
seen: set[str] = set()
|
||||
shared: set[str] = set()
|
||||
for row in rows:
|
||||
assert isinstance(row["response_ids"], list)
|
||||
response_ids = set(row["response_ids"])
|
||||
shared.update(seen & response_ids)
|
||||
seen.update(response_ids)
|
||||
for row in rows:
|
||||
assert isinstance(row["response_ids"], list)
|
||||
if shared.intersection(row["response_ids"]):
|
||||
row.update(ok=False, error="concurrent sessions shared a response id")
|
||||
result = {
|
||||
"schema_version": 1,
|
||||
"mode": "paced_multi_session",
|
||||
"model": args.model,
|
||||
"requested_sessions": args.sessions,
|
||||
"passed_sessions": sum(row["ok"] is True for row in rows),
|
||||
"ok": all(row["ok"] is True for row in rows),
|
||||
"input": {**identity, "tail_s": args.tail_s, "load_frames": args.load_frames},
|
||||
"frame_period_s": FRAME_PERIOD_S,
|
||||
"drain_s": args.drain_s,
|
||||
"cleanup_timeout_s": args.cleanup_timeout_s,
|
||||
"client_pacing_warning_threshold_ms": FRAME_PERIOD_S * 1000,
|
||||
"client_pacing_warning_sessions": [row["index"] for row in rows if row["client_pacing_warning"]],
|
||||
"max_client_rtf": args.max_client_rtf,
|
||||
"acceptance": {
|
||||
"max_frame_deficit": args.max_frame_deficit,
|
||||
"min_voiced_frames": args.min_voiced_frames,
|
||||
"minimum_audio_chunks": args.minimum_audio_chunks,
|
||||
"voiced_frame_rms_threshold": args.voiced_frame_rms_threshold,
|
||||
},
|
||||
"shared_response_ids": sorted(shared),
|
||||
"sessions": rows,
|
||||
"reported_server": {"revision": args.server_revision, "hardware": args.server_hardware},
|
||||
"measurement_origin": "client monotonic clock; admission excluded; streaming and drain retained",
|
||||
"interval_definition": "nonempty audio packet arrivals, not server ticks or per-frame inference latency",
|
||||
}
|
||||
with result_path.open("x", encoding="utf-8") as stream:
|
||||
json.dump(result, stream, ensure_ascii=False, indent=2, allow_nan=False)
|
||||
return result
|
||||
|
||||
|
||||
def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--url", default="ws://127.0.0.1:8099/v1/realtime?duplex=1")
|
||||
@@ -510,6 +867,12 @@ def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
|
||||
parser.add_argument("--tail-s", type=float, default=2.0)
|
||||
parser.add_argument("--drain-s", type=float, default=2.0)
|
||||
parser.add_argument("--timeout-s", type=float, default=180.0)
|
||||
parser.add_argument(
|
||||
"--cleanup-timeout-s",
|
||||
type=float,
|
||||
default=5.0,
|
||||
help="Load mode: shared session-close/ack budget; also bounds the websocket close handshake.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--max-frame-deficit",
|
||||
type=int,
|
||||
@@ -536,11 +899,39 @@ def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
|
||||
default=0,
|
||||
help="Frames sent after slot reuse; 0 replays the full input so the replacement must produce audible output.",
|
||||
)
|
||||
return parser.parse_args(argv)
|
||||
parser.add_argument(
|
||||
"--sessions", type=int, help="Opt into paced load mode with N sessions; omit for the lifecycle test."
|
||||
)
|
||||
parser.add_argument(
|
||||
"--load-frames", type=int, default=1000, help="Maximum input frames per load session (no repetition)."
|
||||
)
|
||||
parser.add_argument("--max-client-rtf", type=float, help="Optional client stream-window RTF acceptance ceiling.")
|
||||
parser.add_argument("--server-revision", help="User-reported server commit/version; not verified by this client.")
|
||||
parser.add_argument(
|
||||
"--server-hardware", help="User-reported server hardware; not inferred from the client machine."
|
||||
)
|
||||
args = parser.parse_args(argv)
|
||||
if args.sessions is not None:
|
||||
if not 1 <= args.sessions <= 64 or not 1 <= args.load_frames <= 10000:
|
||||
parser.error("load mode requires sessions in [1,64] and load-frames in [1,10000]")
|
||||
for name in ("timeout_s", "cleanup_timeout_s", "drain_s", "tail_s"):
|
||||
value = getattr(args, name)
|
||||
if not math.isfinite(value) or value < 0 or (name in ("timeout_s", "cleanup_timeout_s") and value == 0):
|
||||
parser.error(f"{name} must be finite and non-negative (timeout must be positive)")
|
||||
if args.max_client_rtf is not None and (not math.isfinite(args.max_client_rtf) or args.max_client_rtf <= 0):
|
||||
parser.error("max-client-rtf must be finite and positive")
|
||||
if args.max_frame_deficit < 0 or args.min_voiced_frames < 1 or args.minimum_audio_chunks < 1:
|
||||
parser.error("frame-deficit must be non-negative; voiced frames and audio chunks must be positive")
|
||||
if not math.isfinite(args.voiced_frame_rms_threshold) or args.voiced_frame_rms_threshold < 0:
|
||||
parser.error("voiced-frame-rms-threshold must be finite and non-negative")
|
||||
return args
|
||||
|
||||
|
||||
def main() -> None:
|
||||
print(json.dumps(asyncio.run(run(parse_args())), ensure_ascii=False, indent=2))
|
||||
result = asyncio.run(run(parse_args()))
|
||||
print(json.dumps(result, ensure_ascii=False, indent=2, allow_nan=False))
|
||||
if result.get("mode") == "paced_multi_session" and not result["ok"]:
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Run two MiniCPM-o Realtime duplex demo processes concurrently.
|
||||
|
||||
This E2E driver covers the same process boundary users exercise manually:
|
||||
@@ -14,13 +17,12 @@ import hashlib
|
||||
import io
|
||||
import json
|
||||
import sys
|
||||
import uuid
|
||||
import wave
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[3]
|
||||
DEMO_PATH = REPO_ROOT / "examples/online_serving/minicpmo/realtime_duplex_demo.py"
|
||||
AUDIO_DELTA_EVENTS = {"response.audio.delta", "response.output_audio.delta"}
|
||||
AUDIO_DELTA_EVENTS = {"response.output_audio.delta"}
|
||||
|
||||
|
||||
def _canonical_path(path: str) -> Path:
|
||||
@@ -263,8 +265,6 @@ async def _run_demo_process(
|
||||
str(args.chunk_ms),
|
||||
"--timeout-s",
|
||||
str(args.timeout_s),
|
||||
"--session-id",
|
||||
f"duplex-pair-{label}-{uuid.uuid4().hex}",
|
||||
]
|
||||
if args.no_realtime_pacing:
|
||||
command.append("--no-realtime-pacing")
|
||||
|
||||
@@ -21,7 +21,7 @@ from websockets.asyncio.client import ClientConnection
|
||||
from websockets.exceptions import ConnectionClosed
|
||||
|
||||
SCRIPT_DIR = Path(__file__).resolve().parent
|
||||
REPO_ROOT = SCRIPT_DIR.parents[3]
|
||||
REPO_ROOT = SCRIPT_DIR.parents[2]
|
||||
if str(REPO_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(REPO_ROOT))
|
||||
|
||||
@@ -42,6 +42,15 @@ def _url_with_model(*args, **kwargs) -> str:
|
||||
return _scenario_module()._url_with_model(*args, **kwargs)
|
||||
|
||||
|
||||
def _created_session_id(created: dict[str, object]) -> str:
|
||||
"""The server-allocated session id announced by ``session.created``."""
|
||||
session = created.get("session")
|
||||
session_id = session.get("id") if isinstance(session, dict) else None
|
||||
if not isinstance(session_id, str) or not session_id:
|
||||
raise RuntimeError("session.created omitted the server-allocated session id")
|
||||
return session_id
|
||||
|
||||
|
||||
async def run_demo(args):
|
||||
return await _scenario_module().run_demo(args)
|
||||
|
||||
@@ -217,7 +226,6 @@ async def _open_admission_session(
|
||||
args.url,
|
||||
args.model,
|
||||
autostart=False if getattr(args, "ref_audio", None) else None,
|
||||
session_id=session_id,
|
||||
)
|
||||
ws = await websockets.connect(url, max_size=64 * 1024 * 1024)
|
||||
await ws.send(
|
||||
@@ -225,10 +233,8 @@ async def _open_admission_session(
|
||||
{
|
||||
"type": "session.update",
|
||||
"session": {
|
||||
"session_id": session_id,
|
||||
"model": args.model,
|
||||
"modalities": ["audio", "text"],
|
||||
"extra_body": {"native_duplex": True},
|
||||
**({"ref_audio": _ref_audio_data_url(args.ref_audio)} if getattr(args, "ref_audio", None) else {}),
|
||||
},
|
||||
}
|
||||
@@ -255,12 +261,10 @@ async def _admission_probe(args: argparse.Namespace, *, limit: int) -> dict[str,
|
||||
for index in range(limit):
|
||||
accepted.append(await _open_admission_session(args, f"{prefix}-accepted-{index}"))
|
||||
|
||||
overflow_id = f"{prefix}-overflow"
|
||||
overflow_url = _url_with_model(
|
||||
args.url,
|
||||
args.model,
|
||||
autostart=False if getattr(args, "ref_audio", None) else None,
|
||||
session_id=overflow_id,
|
||||
)
|
||||
async with websockets.connect(overflow_url, max_size=64 * 1024 * 1024) as overflow:
|
||||
await overflow.send(
|
||||
@@ -268,10 +272,8 @@ async def _admission_probe(args: argparse.Namespace, *, limit: int) -> dict[str,
|
||||
{
|
||||
"type": "session.update",
|
||||
"session": {
|
||||
"session_id": overflow_id,
|
||||
"model": args.model,
|
||||
"modalities": ["audio", "text"],
|
||||
"extra_body": {"native_duplex": True},
|
||||
**(
|
||||
{"ref_audio": _ref_audio_data_url(args.ref_audio)}
|
||||
if getattr(args, "ref_audio", None)
|
||||
@@ -326,7 +328,6 @@ async def _resume_probe(
|
||||
args.url,
|
||||
args.model,
|
||||
autostart=False if getattr(args, "ref_audio", None) else None,
|
||||
session_id=session_id,
|
||||
)
|
||||
async with websockets.connect(url, max_size=64 * 1024 * 1024) as first:
|
||||
await first.send(
|
||||
@@ -334,10 +335,8 @@ async def _resume_probe(
|
||||
{
|
||||
"type": "session.update",
|
||||
"session": {
|
||||
"session_id": session_id,
|
||||
"model": args.model,
|
||||
"modalities": ["audio", "text"],
|
||||
"extra_body": {"native_duplex": True},
|
||||
**(
|
||||
{"ref_audio": _ref_audio_data_url(args.ref_audio)}
|
||||
if getattr(args, "ref_audio", None)
|
||||
@@ -348,10 +347,10 @@ async def _resume_probe(
|
||||
)
|
||||
)
|
||||
created, first_events = await _receive_until(first, "session.created", timeout_s=args.timeout_s)
|
||||
session_id = _created_session_id(created)
|
||||
token = created.get("resume_token")
|
||||
incarnation = created.get("incarnation")
|
||||
generation = created.get("attachment_generation")
|
||||
if not isinstance(token, str) or not isinstance(incarnation, int):
|
||||
if not isinstance(token, str):
|
||||
raise RuntimeError("session.created omitted resumable credentials")
|
||||
last_seq = max(_server_event_sequences(first_events), default=0)
|
||||
|
||||
@@ -366,7 +365,6 @@ async def _resume_probe(
|
||||
{
|
||||
"type": "session.resume",
|
||||
"session_id": session_id,
|
||||
"incarnation": incarnation,
|
||||
"resume_token": token,
|
||||
"last_received_server_event_seq": last_seq,
|
||||
}
|
||||
@@ -429,7 +427,6 @@ async def _takeover_probe(
|
||||
args.url,
|
||||
args.model,
|
||||
autostart=False if getattr(args, "ref_audio", None) else None,
|
||||
session_id=session_id,
|
||||
)
|
||||
first = await websockets.connect(url, max_size=64 * 1024 * 1024)
|
||||
second = None
|
||||
@@ -439,10 +436,8 @@ async def _takeover_probe(
|
||||
{
|
||||
"type": "session.update",
|
||||
"session": {
|
||||
"session_id": session_id,
|
||||
"model": args.model,
|
||||
"modalities": ["audio", "text"],
|
||||
"extra_body": {"native_duplex": True},
|
||||
**(
|
||||
{"ref_audio": _ref_audio_data_url(args.ref_audio)}
|
||||
if getattr(args, "ref_audio", None)
|
||||
@@ -453,10 +448,10 @@ async def _takeover_probe(
|
||||
)
|
||||
)
|
||||
created, first_events = await _receive_until(first, "session.created", timeout_s=args.timeout_s)
|
||||
session_id = _created_session_id(created)
|
||||
token = created.get("resume_token")
|
||||
incarnation = created.get("incarnation")
|
||||
generation = created.get("attachment_generation")
|
||||
if not isinstance(token, str) or not isinstance(incarnation, int) or not isinstance(generation, int):
|
||||
if not isinstance(token, str) or not isinstance(generation, int):
|
||||
raise RuntimeError("session.created omitted takeover credentials")
|
||||
last_seq = max(_server_event_sequences(first_events), default=0)
|
||||
|
||||
@@ -466,7 +461,6 @@ async def _takeover_probe(
|
||||
{
|
||||
"type": "session.resume",
|
||||
"session_id": session_id,
|
||||
"incarnation": incarnation,
|
||||
"resume_token": token,
|
||||
"last_received_server_event_seq": last_seq,
|
||||
}
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import base64
|
||||
from pathlib import Path
|
||||
|
||||
@@ -41,7 +44,10 @@ async def run_server_vad_interrupt(args) -> dict[str, object]:
|
||||
next(e for e in client.events.events if e.get("type") == "response.created")
|
||||
)
|
||||
assert target_id
|
||||
await until(lambda: _events(client.events.events, target_id, "response.audio.delta"), "response.audio.delta")
|
||||
await until(
|
||||
lambda: _events(client.events.events, target_id, "response.output_audio.delta"),
|
||||
"response.output_audio.delta",
|
||||
)
|
||||
cursor = len(client.events.events)
|
||||
await client.stream_pcm16(interrupt + bytes(16_000 * 2 * 800 // 1000), chunk_ms=args.chunk_ms, realtime=True)
|
||||
await until(lambda: _events(client.events.events, target_id, "response.done"), "cancelled response.done")
|
||||
@@ -64,10 +70,11 @@ async def run_server_vad_interrupt(args) -> dict[str, object]:
|
||||
terminal = done[0] if len(done) == 1 else None
|
||||
trailing = events[events.index(terminal) + 1 :] if terminal is not None else events
|
||||
stale = any(
|
||||
e.get("type") == "response.audio.delta" and RealtimeEventCollector.response_id(e) == target_id for e in trailing
|
||||
e.get("type") == "response.output_audio.delta" and RealtimeEventCollector.response_id(e) == target_id
|
||||
for e in trailing
|
||||
)
|
||||
followup_audio = any(
|
||||
e.get("type") == "response.audio.delta" and RealtimeEventCollector.response_id(e) != target_id
|
||||
e.get("type") == "response.output_audio.delta" and RealtimeEventCollector.response_id(e) != target_id
|
||||
for e in events[cursor:]
|
||||
)
|
||||
ok = (
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Validate MiniCPM-o Realtime duplex soft-interrupt delta streaming.
|
||||
|
||||
This E2E driver runs the public ``realtime_duplex_demo.py`` against a live
|
||||
@@ -15,15 +18,14 @@ import hashlib
|
||||
import io
|
||||
import json
|
||||
import sys
|
||||
import uuid
|
||||
import wave
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[3]
|
||||
DEMO_PATH = REPO_ROOT / "examples/online_serving/minicpmo/realtime_duplex_demo.py"
|
||||
AUDIO_DELTA_EVENTS = {"response.audio.delta", "response.output_audio.delta"}
|
||||
AUDIO_DELTA_EVENTS = {"response.output_audio.delta"}
|
||||
TRANSCRIPT_DELTA_EVENTS = {
|
||||
"response.audio_transcript.delta",
|
||||
"response.output_audio_transcript.delta",
|
||||
"response.output_text.delta",
|
||||
}
|
||||
|
||||
@@ -409,8 +411,6 @@ async def run_soft_interrupt(args: argparse.Namespace) -> dict[str, object]:
|
||||
str(args.chunk_ms),
|
||||
"--timeout-s",
|
||||
str(args.timeout_s),
|
||||
"--session-id",
|
||||
f"duplex-soft-interrupt-{uuid.uuid4().hex}",
|
||||
]
|
||||
command.extend(["--ref-audio", str(_canonical_path(args.ref_audio))])
|
||||
temperature = getattr(args, "temperature", None)
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Online e2e smoke test for native Anima single-file checkpoints."""
|
||||
|
||||
import json
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.helpers.mark import hardware_test
|
||||
from tests.helpers.runtime import OmniServer, OpenAIClientHandler, dummy_messages_from_mix_data
|
||||
|
||||
CHECKPOINT_ENV = "ANIMA_CHECKPOINT_PATH"
|
||||
COMPONENTS_ENV = "ANIMA_COMPONENTS_PATH"
|
||||
CHECKPOINT_REPO = "circlestone-labs/Anima"
|
||||
CHECKPOINT_FILENAME = "split_files/diffusion_models/anima-base-v1.0.safetensors"
|
||||
COMPONENTS_REPO = "circlestone-labs/Anima-Base-v1.0-Diffusers"
|
||||
PROMPT = "A cinematic close-up of a glass teapot on a wooden table."
|
||||
|
||||
|
||||
def _resolve_anima_assets() -> tuple[str, str]:
|
||||
checkpoint = os.environ.get(CHECKPOINT_ENV)
|
||||
components = os.environ.get(COMPONENTS_ENV)
|
||||
if checkpoint and components:
|
||||
return checkpoint, components
|
||||
|
||||
from huggingface_hub import hf_hub_download, snapshot_download
|
||||
|
||||
if checkpoint is None:
|
||||
checkpoint = hf_hub_download(
|
||||
repo_id=CHECKPOINT_REPO,
|
||||
filename=CHECKPOINT_FILENAME,
|
||||
)
|
||||
if components is None:
|
||||
components = snapshot_download(repo_id=COMPONENTS_REPO)
|
||||
return checkpoint, components
|
||||
|
||||
|
||||
@pytest.mark.full_model
|
||||
@pytest.mark.diffusion
|
||||
@hardware_test(res={"cuda": "L4", "rocm": "MI325"}, num_cards=1)
|
||||
@pytest.mark.parametrize("guidance_scale", [1.0, 4.0])
|
||||
def test_anima_text_to_image(guidance_scale):
|
||||
checkpoint, components = _resolve_anima_assets()
|
||||
server_args = [
|
||||
"--model-class-name",
|
||||
"AnimaPipeline",
|
||||
"--custom-pipeline-args",
|
||||
json.dumps({"components_path": components}),
|
||||
]
|
||||
with OmniServer(checkpoint, server_args) as omni_server:
|
||||
openai_client = OpenAIClientHandler(
|
||||
host=omni_server.host,
|
||||
port=omni_server.port,
|
||||
api_key="EMPTY",
|
||||
run_level="full_model",
|
||||
log_stats=omni_server.log_stats,
|
||||
)
|
||||
_send_text_to_image_request(omni_server, openai_client, guidance_scale)
|
||||
|
||||
|
||||
def _send_text_to_image_request(omni_server: OmniServer, openai_client: OpenAIClientHandler, guidance_scale: float):
|
||||
messages = dummy_messages_from_mix_data(content_text=PROMPT)
|
||||
request_config = {
|
||||
"model": omni_server.model,
|
||||
"messages": messages,
|
||||
"extra_body": {
|
||||
"height": 256,
|
||||
"width": 256,
|
||||
"num_inference_steps": 1,
|
||||
"guidance_scale": guidance_scale,
|
||||
"seed": 42,
|
||||
},
|
||||
}
|
||||
|
||||
openai_client.send_diffusion_request(request_config)
|
||||
+51
-42
@@ -1,28 +1,34 @@
|
||||
# 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 expansion tests for dots.tts(text-only).
|
||||
E2E Online tests for Breeze-TTS-2 with text input and audio output.
|
||||
|
||||
These tests verify the /v1/audio/speech endpoint works correctly with
|
||||
actual model inference, not mocks. Breeze-TTS-2 plain mode needs only
|
||||
``input`` and a speaker tag (``voice`` defaults to ``S0``); reference
|
||||
cloning requires ``ref_audio`` + ``ref_text`` and is not exercised here.
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.helpers.mark import hardware_test
|
||||
from tests.helpers.runtime import OmniServerParams
|
||||
from tests.helpers.stage_config import get_deploy_config_path
|
||||
|
||||
pytestmark = [pytest.mark.full_model, pytest.mark.tts]
|
||||
|
||||
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
|
||||
|
||||
MODEL = "dots-studio/dots.tts-soar"
|
||||
MODEL = "BreezeBlue/Breeze-TTS-2"
|
||||
DEFAULT_AUDIO_SPEECH_TIMEOUT_S = 300.0
|
||||
_MIN_AUDIO_BYTES = 40_000
|
||||
MAX_CONCURRENT = 4
|
||||
|
||||
# ~0.5 s of 24 kHz mono PCM_16 in WAV (~24k payload + header).
|
||||
_MIN_AUDIO_BYTES = 40_000
|
||||
|
||||
|
||||
def get_prompt(prompt_type="text"):
|
||||
"""English prompt for zero-shot TTS."""
|
||||
prompts = {
|
||||
"text": "The weather is nice today, perfect for a walk in the park.",
|
||||
}
|
||||
@@ -33,24 +39,52 @@ tts_server_params = [
|
||||
pytest.param(
|
||||
OmniServerParams(
|
||||
model=MODEL,
|
||||
stage_config_path=get_deploy_config_path("dots_tts.yaml"),
|
||||
stage_config_path=get_deploy_config_path("breeze_tts_2.yaml"),
|
||||
server_args=["--trust-remote-code", "--disable-log-stats"],
|
||||
),
|
||||
id="dots_tts",
|
||||
id="breeze_tts_2",
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.slow
|
||||
@pytest.mark.tts
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
|
||||
def test_text_only_streaming_001(omni_server, openai_client) -> None:
|
||||
def test_text_to_audio_001(omni_server, online_client) -> None:
|
||||
"""
|
||||
Test text-only text-to-audio via OpenAI API.
|
||||
Deploy Setting: dots_tts.yaml
|
||||
Test plain text-to-audio via OpenAI API.
|
||||
Deploy Setting: breeze_tts_2.yaml
|
||||
Input Modal: text
|
||||
Output Modal: audio
|
||||
Input Setting: stream=False
|
||||
Datasets: few requests (max_num_seqs=8)
|
||||
"""
|
||||
request_config = {
|
||||
"model": omni_server.model,
|
||||
"input": get_prompt(),
|
||||
"stream": False,
|
||||
"timeout": DEFAULT_AUDIO_SPEECH_TIMEOUT_S,
|
||||
"response_format": "wav",
|
||||
"voice": "S0",
|
||||
"sample_rate": 24000,
|
||||
"min_audio_bytes": _MIN_AUDIO_BYTES,
|
||||
}
|
||||
online_client.send_audio_speech_request(request_config, request_num=MAX_CONCURRENT)
|
||||
|
||||
|
||||
@pytest.mark.slow
|
||||
@pytest.mark.tts
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
|
||||
def test_text_to_audio_002(omni_server, online_client) -> None:
|
||||
"""
|
||||
Test streaming text-to-audio via OpenAI API (async-chunk SSE deltas).
|
||||
Deploy Setting: breeze_tts_2.yaml
|
||||
Input Modal: text
|
||||
Output Modal: audio
|
||||
Input Setting: stream=True
|
||||
Datasets: few requests (max_num_seqs=4)
|
||||
Datasets: single request
|
||||
"""
|
||||
request_config = {
|
||||
"model": omni_server.model,
|
||||
@@ -59,33 +93,8 @@ def test_text_only_streaming_001(omni_server, openai_client) -> None:
|
||||
"stream_format": "audio",
|
||||
"timeout": DEFAULT_AUDIO_SPEECH_TIMEOUT_S,
|
||||
"response_format": "wav",
|
||||
"voice": "default",
|
||||
"voice": "S0",
|
||||
"sample_rate": 24000,
|
||||
"min_audio_bytes": _MIN_AUDIO_BYTES,
|
||||
}
|
||||
openai_client.send_audio_speech_request(request_config, request_num=MAX_CONCURRENT)
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
|
||||
def test_text_only_nonstreaming_pcm_001(omni_server, openai_client) -> None:
|
||||
"""
|
||||
Test text-only non-stream PCM output via OpenAI API.
|
||||
Deploy Setting: dots_tts.yaml
|
||||
Input Modal: text
|
||||
Output Modal: audio (pcm)
|
||||
Input Setting: stream=False
|
||||
Datasets: single request
|
||||
"""
|
||||
request_config = {
|
||||
"model": omni_server.model,
|
||||
"input": get_prompt(),
|
||||
"response_format": "pcm",
|
||||
"stream": False,
|
||||
"timeout": DEFAULT_AUDIO_SPEECH_TIMEOUT_S,
|
||||
"voice": "default",
|
||||
"min_audio_bytes": _MIN_AUDIO_BYTES,
|
||||
"min_hnr_db": -2.0,
|
||||
# dots.tts-soar emits native 48 kHz PCM, which has no rate header.
|
||||
"expected_sample_rate": 48_000,
|
||||
}
|
||||
openai_client.send_audio_speech_request(request_config)
|
||||
online_client.send_audio_speech_request(request_config)
|
||||
@@ -12,7 +12,6 @@ incremental playback acks, a forced transport drop recovered by automatic
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
@@ -47,7 +46,6 @@ async def _run_live_session(*, url: str, model: str, ref_audio: Path, input_wav:
|
||||
url,
|
||||
model=model,
|
||||
config=config,
|
||||
session_id=f"duplex-client-live-{uuid.uuid4().hex}",
|
||||
reconnect=ReconnectPolicy(max_attempts=5, backoff_s=(0.25, 1.0)),
|
||||
# Short interval so the periodic heartbeat path runs during the
|
||||
# session — including across the forced transport drop below.
|
||||
|
||||
@@ -1,99 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""
|
||||
Example online tests for Dynin-Omni model.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import os
|
||||
from io import BytesIO
|
||||
|
||||
import pytest
|
||||
from vllm.assets.image import ImageAsset
|
||||
|
||||
from tests.helpers.mark import hardware_test
|
||||
from tests.helpers.runtime import OmniServerParams
|
||||
from tests.helpers.stage_config import get_deploy_config_path
|
||||
|
||||
pytestmark = [pytest.mark.slow, pytest.mark.omni]
|
||||
|
||||
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
|
||||
|
||||
MODEL = "snu-aidas/Dynin-Omni"
|
||||
STAGE_CONFIG = get_deploy_config_path("dynin_omni_ci.yaml")
|
||||
|
||||
T2I_PROMPT = "A high quality detailed living room interior photo."
|
||||
T2S_PROMPT = "Please read this sentence naturally: Hello from online serving."
|
||||
I2I_PROMPT = "Transform this outdoor nature boardwalk scene into a painting style with vivid colors."
|
||||
|
||||
TEST_PARAMS = [
|
||||
OmniServerParams(
|
||||
model=MODEL,
|
||||
stage_config_path=STAGE_CONFIG,
|
||||
stage_init_timeout=600,
|
||||
server_args=["--trust-remote-code"],
|
||||
)
|
||||
]
|
||||
_STAGE_COUNT = 3
|
||||
_I2I_STAGE_SAMPLING = {"max_tokens": 1, "temperature": 0.0, "top_p": 1.0, "detokenize": False}
|
||||
|
||||
|
||||
def _build_t2i_messages(prompt: str) -> list[dict]:
|
||||
return [{"role": "user", "content": [{"type": "text", "text": f"<|t2i|> {prompt}"}]}]
|
||||
|
||||
|
||||
def _build_t2s_messages(prompt: str) -> list[dict]:
|
||||
return [{"role": "user", "content": [{"type": "text", "text": f"<|t2s|> {prompt}"}]}]
|
||||
|
||||
|
||||
def _build_i2i_messages(prompt: str) -> list[dict]:
|
||||
input_image = ImageAsset("2560px-Gfp-wisconsin-madison-the-nature-boardwalk").pil_image.convert("RGB")
|
||||
buffer = BytesIO()
|
||||
input_image.save(buffer, format="JPEG")
|
||||
image_b64 = base64.b64encode(buffer.getvalue()).decode("utf-8")
|
||||
return [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"type": "text", "text": f"<|i2i|> {prompt}"},
|
||||
{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{image_b64}"}},
|
||||
],
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "H100", "rocm": "MI325"})
|
||||
@pytest.mark.parametrize("omni_server", TEST_PARAMS, indirect=True)
|
||||
def test_send_i2i_request_001(omni_server, online_client) -> None:
|
||||
request_config = {
|
||||
"model": omni_server.model,
|
||||
"messages": _build_i2i_messages(I2I_PROMPT),
|
||||
"modalities": ["image"],
|
||||
"extra_body": {
|
||||
"sampling_params_list": [dict(_I2I_STAGE_SAMPLING) for _ in range(_STAGE_COUNT)],
|
||||
},
|
||||
}
|
||||
online_client.send_diffusion_request(request_config)
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "H100", "rocm": "MI325"})
|
||||
@pytest.mark.parametrize("omni_server", TEST_PARAMS, indirect=True)
|
||||
def test_send_t2i_request_001(omni_server, online_client) -> None:
|
||||
request_config = {
|
||||
"model": omni_server.model,
|
||||
"messages": _build_t2i_messages(T2I_PROMPT),
|
||||
"modalities": ["image"],
|
||||
}
|
||||
online_client.send_diffusion_request(request_config)
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "H100", "rocm": "MI325"})
|
||||
@pytest.mark.parametrize("omni_server", TEST_PARAMS, indirect=True)
|
||||
def test_send_t2s_request_001(omni_server, online_client) -> None:
|
||||
request_config = {
|
||||
"model": omni_server.model,
|
||||
"messages": _build_t2s_messages(T2S_PROMPT),
|
||||
"modalities": ["audio"],
|
||||
"audio_ref_text": T2S_PROMPT,
|
||||
}
|
||||
online_client.send_omni_request(request_config)
|
||||
@@ -0,0 +1,524 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""E2E online serving tests for Gepard-1.0 via ``/v1/audio/speech``.
|
||||
|
||||
Zero-shot default voice. Needs a GPU and the NeMo NanoCodec; the weekly
|
||||
``TTS · Gepard-1.0 · L4`` step installs NeMo then runs this file.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import array
|
||||
import os
|
||||
import statistics
|
||||
import struct
|
||||
import time
|
||||
import wave
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from dataclasses import dataclass
|
||||
from io import BytesIO
|
||||
|
||||
os.environ.setdefault("VLLM_WORKER_MULTIPROC_METHOD", "spawn")
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
import soundfile as sf
|
||||
|
||||
from tests.helpers.mark import hardware_test
|
||||
from tests.helpers.media import convert_audio_bytes_to_text
|
||||
from tests.helpers.runtime import OmniServerParams
|
||||
from tests.helpers.stage_config import get_deploy_config_path
|
||||
|
||||
pytest.importorskip("nemo.collections.tts.models")
|
||||
|
||||
pytestmark = [pytest.mark.slow, pytest.mark.tts]
|
||||
|
||||
MODEL = "nineninesix/gepard-1.0"
|
||||
SAMPLE_RATE = 22050
|
||||
SAMPLES_PER_FRAME = 1024
|
||||
PCM16_BYTES_PER_FRAME = SAMPLES_PER_FRAME * 2
|
||||
DEFAULT_TIMEOUT_S = 180.0
|
||||
|
||||
_DISTINGUISHABLE_PROMPTS = {
|
||||
"He drinks coffee every morning.": "coffee",
|
||||
"Machine learning is interesting.": "learning",
|
||||
"Please close the window before leaving.": "window",
|
||||
"My favorite color is purple.": "purple",
|
||||
}
|
||||
|
||||
tts_server_params = [
|
||||
pytest.param(
|
||||
OmniServerParams(
|
||||
model=MODEL,
|
||||
stage_config_path=get_deploy_config_path("gepard.yaml"),
|
||||
server_args=["--trust-remote-code", "--disable-log-stats"],
|
||||
stage_init_timeout=900,
|
||||
),
|
||||
id="gepard",
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
def _base_config(omni_server, text: str, **extra) -> dict:
|
||||
cfg = {
|
||||
"model": omni_server.model,
|
||||
"input": text,
|
||||
"voice": "default",
|
||||
"timeout": DEFAULT_TIMEOUT_S,
|
||||
"seed": 7,
|
||||
# NanoCodec is quieter than the 24 kHz models the PCM HNR helper was
|
||||
# calibrated on; keep the catastrophic-failure check, not a quality gate.
|
||||
"min_hnr_db": -2.0,
|
||||
"transcript_escalation_model": "large-v3",
|
||||
}
|
||||
cfg.update(extra)
|
||||
return cfg
|
||||
|
||||
|
||||
def _wav_sample_rate(wav_bytes: bytes) -> int:
|
||||
return struct.unpack_from("<I", wav_bytes, 24)[0]
|
||||
|
||||
|
||||
def _wav_pcm_payload_len(wav_bytes: bytes) -> int:
|
||||
data, _sr = sf.read(BytesIO(wav_bytes), dtype="int16")
|
||||
return int(data.size) * 2
|
||||
|
||||
|
||||
def _pcm16le_to_wav(pcm: bytes, sample_rate: int = SAMPLE_RATE) -> bytes:
|
||||
"""Whisper helpers expect a container; streamed speech is raw s16le."""
|
||||
buf = BytesIO()
|
||||
with wave.open(buf, "wb") as wf:
|
||||
wf.setnchannels(1)
|
||||
wf.setsampwidth(2)
|
||||
wf.setframerate(sample_rate)
|
||||
wf.writeframes(pcm)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def _pcm16_samples(pcm: bytes) -> array.array:
|
||||
samples = array.array("h")
|
||||
samples.frombytes(pcm)
|
||||
return samples
|
||||
|
||||
|
||||
def _pcm16_diag(label: str, left: bytes, right: bytes) -> None:
|
||||
extra_frames = (len(left) - len(right)) // PCM16_BYTES_PER_FRAME
|
||||
overlap = min(len(left), len(right))
|
||||
first_frame_match = (
|
||||
overlap >= PCM16_BYTES_PER_FRAME and left[:PCM16_BYTES_PER_FRAME] == right[:PCM16_BYTES_PER_FRAME]
|
||||
)
|
||||
worst = None
|
||||
corr = None
|
||||
first_diff_sample = None
|
||||
if overlap >= 2 and overlap % 2 == 0:
|
||||
a = _pcm16_samples(left[:overlap])
|
||||
b = _pcm16_samples(right[:overlap])
|
||||
worst = max(abs(x - y) for x, y in zip(a, b, strict=True))
|
||||
for i, (x, y) in enumerate(zip(a, b, strict=True)):
|
||||
if x != y:
|
||||
first_diff_sample = i
|
||||
break
|
||||
try:
|
||||
corr = round(statistics.correlation(a, b), 6)
|
||||
except statistics.StatisticsError:
|
||||
corr = None
|
||||
print(
|
||||
f"[Gepard pcm-diag] {label} left={len(left)} right={len(right)} "
|
||||
f"extra_frames={extra_frames} first_frame_match={first_frame_match} "
|
||||
f"first_diff_sample={first_diff_sample} max_abs={worst} corr={corr}"
|
||||
)
|
||||
|
||||
|
||||
def _scan_logs_for_preemption(omni_server) -> None:
|
||||
log_paths = getattr(omni_server, "_stage_log_paths", {}) or {}
|
||||
hits: list[str] = []
|
||||
for path in log_paths.values():
|
||||
if path is None or not path.exists():
|
||||
continue
|
||||
text = path.read_text(encoding="utf-8", errors="replace").lower()
|
||||
if "preempt" in text:
|
||||
hits.append(str(path))
|
||||
assert not hits, f"preemption mentioned in stage logs: {hits}"
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
|
||||
@pytest.mark.parametrize("response_format", ["wav", "pcm"])
|
||||
def test_text_to_audio_basic(omni_server, online_client, response_format: str, run_level: str) -> None:
|
||||
text = "Hello, this is Gepard speaking."
|
||||
# whisper-small/large-v3 mishear 22.05 kHz WAV of this prompt as
|
||||
# "Jeb Ard" / "Jeff Bard" (cosine 0.80 / 0.75). Offline uses keyword
|
||||
# containment; the PCM twin below still goes through the 0.9 ASR gate.
|
||||
if response_format == "wav":
|
||||
url = f"http://{omni_server.host}:{omni_server.port}/v1/audio/speech"
|
||||
payload = {
|
||||
"model": omni_server.model,
|
||||
"input": text,
|
||||
"voice": "default",
|
||||
"seed": 7,
|
||||
"stream": False,
|
||||
"response_format": "wav",
|
||||
}
|
||||
r = requests.post(url, json=payload, timeout=DEFAULT_TIMEOUT_S)
|
||||
r.raise_for_status()
|
||||
audio = r.content
|
||||
assert _wav_sample_rate(audio) == SAMPLE_RATE
|
||||
pcm_len = _wav_pcm_payload_len(audio)
|
||||
else:
|
||||
[resp] = online_client.send_audio_speech_request(
|
||||
_base_config(omni_server, text, stream=False, response_format=response_format)
|
||||
)
|
||||
assert resp.audio_bytes
|
||||
pcm_len = len(resp.audio_bytes)
|
||||
assert pcm_len % PCM16_BYTES_PER_FRAME == 0
|
||||
if run_level in {"advanced_model", "full_model"}:
|
||||
duration = pcm_len / 2 / SAMPLE_RATE
|
||||
assert 0.5 < duration < 30.0, f"implausible duration {duration:.2f}s"
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
|
||||
def test_seed_determinism(omni_server, online_client) -> None:
|
||||
text = "Hello, this is Gepard speaking."
|
||||
[a] = online_client.send_audio_speech_request(_base_config(omni_server, text, seed=7, response_format="pcm"))
|
||||
[b] = online_client.send_audio_speech_request(_base_config(omni_server, text, seed=7, response_format="pcm"))
|
||||
[c] = online_client.send_audio_speech_request(_base_config(omni_server, text, seed=11, response_format="pcm"))
|
||||
assert a.audio_bytes == b.audio_bytes
|
||||
assert a.audio_bytes != c.audio_bytes
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
|
||||
def test_streaming_pcm_incremental(omni_server, online_client) -> None:
|
||||
text = "Hello, this is Gepard speaking."
|
||||
url = f"http://{omni_server.host}:{omni_server.port}/v1/audio/speech"
|
||||
payload = {
|
||||
"model": omni_server.model,
|
||||
"input": text,
|
||||
"voice": "default",
|
||||
"seed": 7,
|
||||
"stream": True,
|
||||
"stream_format": "audio",
|
||||
"response_format": "pcm",
|
||||
}
|
||||
start = time.perf_counter()
|
||||
arrivals: list[tuple[float, int]] = []
|
||||
streamed = bytearray()
|
||||
with requests.post(url, json=payload, stream=True, timeout=DEFAULT_TIMEOUT_S) as resp:
|
||||
resp.raise_for_status()
|
||||
content_type = resp.headers.get("content-type") or ""
|
||||
assert "pcm" in content_type or "octet-stream" in content_type
|
||||
for chunk in resp.iter_content(chunk_size=None):
|
||||
if not chunk:
|
||||
continue
|
||||
arrivals.append((time.perf_counter(), len(chunk)))
|
||||
streamed.extend(chunk)
|
||||
assert len(arrivals) >= 2, f"expected incremental chunks, got {len(arrivals)}"
|
||||
assert arrivals[1][0] > arrivals[0][0]
|
||||
ttfa_ms = (arrivals[0][0] - start) * 1000.0
|
||||
cadence_ms = [(arrivals[i][0] - arrivals[i - 1][0]) * 1000.0 for i in range(1, len(arrivals))]
|
||||
print(f"[Gepard streaming] TTFA_ms={ttfa_ms:.1f} chunk_cadence_ms={cadence_ms}")
|
||||
|
||||
[non_stream] = online_client.send_audio_speech_request(
|
||||
_base_config(omni_server, text, seed=7, stream=False, response_format="pcm")
|
||||
)
|
||||
assert bytes(streamed) == non_stream.audio_bytes
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
|
||||
def test_seeded_streaming_stops(omni_server) -> None:
|
||||
url = f"http://{omni_server.host}:{omni_server.port}/v1/audio/speech"
|
||||
payload = {
|
||||
"model": omni_server.model,
|
||||
"input": "Hello, this is Gepard speaking.",
|
||||
"voice": "default",
|
||||
"seed": 7,
|
||||
"stream": True,
|
||||
"stream_format": "audio",
|
||||
"response_format": "pcm",
|
||||
}
|
||||
with requests.post(url, json=payload, stream=True, timeout=DEFAULT_TIMEOUT_S) as resp:
|
||||
resp.raise_for_status()
|
||||
audio = b"".join(chunk for chunk in resp.iter_content(chunk_size=None) if chunk)
|
||||
duration = len(audio) / 2 / SAMPLE_RATE
|
||||
assert duration < 30.0, f"seeded stream ran {duration:.1f}s — stop constraint dropped?"
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
|
||||
def test_sse_stream_emits_delta_then_done(omni_server) -> None:
|
||||
url = f"http://{omni_server.host}:{omni_server.port}/v1/audio/speech"
|
||||
payload = {
|
||||
"model": omni_server.model,
|
||||
"input": "Hello, this is Gepard speaking.",
|
||||
"voice": "default",
|
||||
"seed": 7,
|
||||
"stream": True,
|
||||
"stream_format": "sse",
|
||||
"response_format": "pcm",
|
||||
}
|
||||
with requests.post(url, json=payload, stream=True, timeout=DEFAULT_TIMEOUT_S) as resp:
|
||||
resp.raise_for_status()
|
||||
assert resp.headers.get("content-type", "").startswith("text/event-stream")
|
||||
body = b"".join(resp.iter_content(chunk_size=None)).decode("utf-8", errors="replace")
|
||||
assert "speech.audio.delta" in body
|
||||
assert "speech.audio.done" in body
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
|
||||
def test_concurrent_requests_stay_isolated(omni_server, online_client, run_level: str) -> None:
|
||||
def _one(text: str):
|
||||
return online_client.send_audio_speech_request(_base_config(omni_server, text, seed=7, response_format="wav"))[
|
||||
0
|
||||
]
|
||||
|
||||
texts = list(_DISTINGUISHABLE_PROMPTS)
|
||||
with ThreadPoolExecutor(max_workers=4) as pool:
|
||||
responses = list(pool.map(_one, texts))
|
||||
|
||||
assert all(r.success for r in responses)
|
||||
for i in range(len(responses)):
|
||||
for j in range(i + 1, len(responses)):
|
||||
assert responses[i].audio_bytes != responses[j].audio_bytes
|
||||
|
||||
if run_level in {"advanced_model", "full_model"}:
|
||||
for text, resp in zip(texts, responses, strict=True):
|
||||
keyword = _DISTINGUISHABLE_PROMPTS[text]
|
||||
transcript = convert_audio_bytes_to_text(resp.audio_bytes, language="en").lower()
|
||||
assert keyword in transcript, f"expected {keyword!r} in {transcript!r} for {text!r}"
|
||||
|
||||
_scan_logs_for_preemption(omni_server)
|
||||
|
||||
|
||||
def _speech_url(omni_server) -> str:
|
||||
return f"http://{omni_server.host}:{omni_server.port}/v1/audio/speech"
|
||||
|
||||
|
||||
def _stream_payload(omni_server, text: str, **extra) -> dict:
|
||||
payload = {
|
||||
"model": omni_server.model,
|
||||
"input": text,
|
||||
"voice": "default",
|
||||
"seed": 7,
|
||||
"stream": True,
|
||||
"stream_format": "audio",
|
||||
"response_format": "pcm",
|
||||
}
|
||||
payload.update(extra)
|
||||
return payload
|
||||
|
||||
|
||||
@dataclass
|
||||
class _StreamCapture:
|
||||
pcm: bytes
|
||||
arrivals: list[tuple[float, int]]
|
||||
|
||||
@property
|
||||
def duration_s(self) -> float:
|
||||
return len(self.pcm) / 2 / SAMPLE_RATE
|
||||
|
||||
|
||||
def _capture_stream(
|
||||
url: str,
|
||||
payload: dict,
|
||||
timeout_s: float,
|
||||
*,
|
||||
sleep_after_first_s: float = 0.0,
|
||||
) -> _StreamCapture:
|
||||
start = time.perf_counter()
|
||||
arrivals: list[tuple[float, int]] = []
|
||||
pcm = bytearray()
|
||||
with requests.post(url, json=payload, stream=True, timeout=timeout_s) as resp:
|
||||
resp.raise_for_status()
|
||||
first = True
|
||||
for chunk in resp.iter_content(chunk_size=None):
|
||||
if not chunk:
|
||||
continue
|
||||
arrivals.append((time.perf_counter() - start, len(chunk)))
|
||||
pcm.extend(chunk)
|
||||
if first and sleep_after_first_s > 0:
|
||||
time.sleep(sleep_after_first_s)
|
||||
first = False
|
||||
return _StreamCapture(bytes(pcm), arrivals)
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
|
||||
def test_concurrent_streaming_stays_isolated(omni_server, run_level: str) -> None:
|
||||
url = _speech_url(omni_server)
|
||||
texts = list(_DISTINGUISHABLE_PROMPTS)
|
||||
|
||||
def _one(text: str) -> tuple[str, _StreamCapture]:
|
||||
return text, _capture_stream(url, _stream_payload(omni_server, text), DEFAULT_TIMEOUT_S)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=4) as pool:
|
||||
results = list(pool.map(_one, texts))
|
||||
|
||||
captures = [cap for _, cap in results]
|
||||
assert all(len(c.arrivals) >= 2 for c in captures)
|
||||
for i in range(len(captures)):
|
||||
for j in range(i + 1, len(captures)):
|
||||
assert captures[i].pcm != captures[j].pcm
|
||||
|
||||
if run_level in {"advanced_model", "full_model"}:
|
||||
for text, cap in results:
|
||||
keyword = _DISTINGUISHABLE_PROMPTS[text]
|
||||
transcript = convert_audio_bytes_to_text(_pcm16le_to_wav(cap.pcm), language="en").lower()
|
||||
assert keyword in transcript, f"expected {keyword!r} in {transcript!r} for {text!r}"
|
||||
|
||||
_scan_logs_for_preemption(omni_server)
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
|
||||
def test_slow_client_still_completes(omni_server, online_client) -> None:
|
||||
"""Slow reader must finish, and seed=7 must match a prior non-stream.
|
||||
|
||||
Runs before ``test_client_disconnect_releases_capacity`` so an abort
|
||||
storm cannot contaminate this comparison. Prints overlap diagnostics
|
||||
before the bit-exact asserts.
|
||||
"""
|
||||
text = "Hello, this is Gepard speaking."
|
||||
[baseline] = online_client.send_audio_speech_request(
|
||||
_base_config(omni_server, text, seed=7, stream=False, response_format="pcm")
|
||||
)
|
||||
cap = _capture_stream(
|
||||
url=_speech_url(omni_server),
|
||||
payload=_stream_payload(omni_server, text),
|
||||
timeout_s=DEFAULT_TIMEOUT_S,
|
||||
sleep_after_first_s=3.0,
|
||||
)
|
||||
assert len(cap.arrivals) >= 2
|
||||
assert len(cap.pcm) % PCM16_BYTES_PER_FRAME == 0
|
||||
assert 0.5 < cap.duration_s < 30.0
|
||||
print(f"[Gepard slow-client] chunks={len(cap.arrivals)} duration_s={cap.duration_s:.3f}")
|
||||
_pcm16_diag("slow-vs-prior-nonstream", cap.pcm, baseline.audio_bytes)
|
||||
[after] = online_client.send_audio_speech_request(
|
||||
_base_config(omni_server, text, seed=7, stream=False, response_format="pcm")
|
||||
)
|
||||
_pcm16_diag("after-nonstream-vs-prior", after.audio_bytes, baseline.audio_bytes)
|
||||
assert cap.pcm == baseline.audio_bytes
|
||||
assert after.audio_bytes == baseline.audio_bytes
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
|
||||
def test_client_disconnect_releases_capacity(omni_server, online_client) -> None:
|
||||
"""A follow-up request must complete after in-flight streams are closed.
|
||||
|
||||
Logs PCM diagnostics against a pre-abort ``seed=7`` baseline. Bit-exact
|
||||
equality after abort is not asserted here: a dying stream can still share
|
||||
a GPU batch with the next generate after ``abort()`` returns, and Gepard's
|
||||
in-model stop head / bf16 GEMM are not row-stable in that batch.
|
||||
"""
|
||||
url = _speech_url(omni_server)
|
||||
text = "Hello, this is Gepard speaking."
|
||||
[baseline] = online_client.send_audio_speech_request(
|
||||
_base_config(omni_server, text, seed=7, stream=False, response_format="pcm")
|
||||
)
|
||||
long_payload = _stream_payload(
|
||||
omni_server,
|
||||
"Please keep talking about the weather, the window, coffee, and purple flowers.",
|
||||
max_new_tokens=80,
|
||||
)
|
||||
for _ in range(4):
|
||||
resp = requests.post(url, json=long_payload, stream=True, timeout=DEFAULT_TIMEOUT_S)
|
||||
resp.raise_for_status()
|
||||
try:
|
||||
chunk = next(c for c in resp.iter_content(chunk_size=None) if c)
|
||||
assert chunk
|
||||
finally:
|
||||
resp.close()
|
||||
|
||||
t0 = time.perf_counter()
|
||||
follow = requests.post(
|
||||
url,
|
||||
json={
|
||||
"model": omni_server.model,
|
||||
"input": text,
|
||||
"voice": "default",
|
||||
"seed": 7,
|
||||
"stream": False,
|
||||
"response_format": "pcm",
|
||||
},
|
||||
timeout=DEFAULT_TIMEOUT_S,
|
||||
)
|
||||
follow.raise_for_status()
|
||||
elapsed = time.perf_counter() - t0
|
||||
pcm_len = len(follow.content)
|
||||
assert pcm_len % PCM16_BYTES_PER_FRAME == 0
|
||||
print(f"[Gepard disconnect] followup_s={elapsed:.2f} pcm_bytes={pcm_len}")
|
||||
_pcm16_diag("disconnect-followup-vs-prior", follow.content, baseline.audio_bytes)
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
|
||||
def test_mixed_stream_and_nonstream_isolated(omni_server, online_client, run_level: str) -> None:
|
||||
url = _speech_url(omni_server)
|
||||
stream_text = "He drinks coffee every morning."
|
||||
nonstream_text = "My favorite color is purple."
|
||||
|
||||
def _stream():
|
||||
return _capture_stream(url, _stream_payload(omni_server, stream_text), DEFAULT_TIMEOUT_S)
|
||||
|
||||
def _nonstream():
|
||||
return online_client.send_audio_speech_request(
|
||||
_base_config(omni_server, nonstream_text, seed=7, response_format="wav")
|
||||
)[0]
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
stream_future = pool.submit(_stream)
|
||||
nonstream_future = pool.submit(_nonstream)
|
||||
streamed = stream_future.result()
|
||||
nonstream = nonstream_future.result()
|
||||
|
||||
assert streamed.pcm
|
||||
assert nonstream.success
|
||||
assert streamed.pcm != nonstream.audio_bytes
|
||||
if run_level in {"advanced_model", "full_model"}:
|
||||
stream_tr = convert_audio_bytes_to_text(_pcm16le_to_wav(streamed.pcm), language="en").lower()
|
||||
nonstream_tr = convert_audio_bytes_to_text(nonstream.audio_bytes, language="en").lower()
|
||||
assert "coffee" in stream_tr, stream_tr
|
||||
assert "purple" in nonstream_tr, nonstream_tr
|
||||
_scan_logs_for_preemption(omni_server)
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
|
||||
def test_max_new_tokens_caps_whole_frames(omni_server) -> None:
|
||||
frames = 16
|
||||
url = _speech_url(omni_server)
|
||||
r = requests.post(
|
||||
url,
|
||||
json={
|
||||
"model": omni_server.model,
|
||||
"input": "Hello, this is Gepard speaking.",
|
||||
"voice": "default",
|
||||
"seed": 7,
|
||||
"stream": False,
|
||||
"response_format": "pcm",
|
||||
"max_new_tokens": frames,
|
||||
},
|
||||
timeout=DEFAULT_TIMEOUT_S,
|
||||
)
|
||||
assert r.status_code == 200, r.text
|
||||
pcm_len = len(r.content)
|
||||
assert pcm_len % PCM16_BYTES_PER_FRAME == 0
|
||||
assert pcm_len == frames * PCM16_BYTES_PER_FRAME, f"got {pcm_len} bytes, want {frames} frames"
|
||||
duration = pcm_len / 2 / SAMPLE_RATE
|
||||
assert duration < 1.0, f"budget cap should stop near 16 frames, got {duration:.2f}s"
|
||||
|
||||
over = requests.post(
|
||||
url,
|
||||
json={
|
||||
"model": omni_server.model,
|
||||
"input": "Hello, this is Gepard speaking.",
|
||||
"voice": "default",
|
||||
"max_new_tokens": 4097,
|
||||
},
|
||||
timeout=DEFAULT_TIMEOUT_S,
|
||||
)
|
||||
assert over.status_code == 400
|
||||
assert "max_new_tokens" in over.text
|
||||
@@ -49,7 +49,7 @@ def _get_hidream_i1_image_feature_cases(model: str):
|
||||
_get_hidream_i1_image_feature_cases(MODEL),
|
||||
indirect=True,
|
||||
)
|
||||
@pytest.mark.skip(reason="https://github.com/vllm-project/vllm-omni/issues/4662")
|
||||
@pytest.mark.skip(reason="https://github.com/vllm-project/vllm-omni/issues/7753")
|
||||
def test_hidream_i1_image(
|
||||
omni_server: OmniServer,
|
||||
online_client: OnlineOmniClient,
|
||||
|
||||
@@ -4,14 +4,15 @@
|
||||
Tests of common diffusion feature combinations in online serving mode
|
||||
for HunyuanVideo-1.5-T2V (480p).
|
||||
|
||||
Coverage (H100, since model cannot fit L4):
|
||||
- CPU offloading (1 GPU) — ``core_model`` + ``advanced_model``
|
||||
- CacheDiT + Layerwise CPU offloading (1 GPU) — ``full_model``
|
||||
- CacheDiT + TP=2 + VAE patch parallel=2 (2 GPUs) — ``full_model``
|
||||
Coverage:
|
||||
- Default single-card deployment (H100, B200, or Ascend A2) — ``full_model``
|
||||
- CPU offloading (1 H100 or Ascend A2) — ``core_model`` + ``advanced_model``
|
||||
- CacheDiT + Layerwise CPU offloading (1 H100, B200, or Ascend A2) — ``full_model``
|
||||
- CacheDiT + TP=2 + VAE patch parallel=2 (2 H100s, B200s, or Ascend A2s) — ``full_model``
|
||||
|
||||
HunyuanVideo-1.5 is a high-priority model, so only the most basic single-card deployment
|
||||
row runs on every PR (L2) and on merge (L3). The heavyweight feature combinations stay
|
||||
nightly-only (L4), together with the video similarity suites in
|
||||
HunyuanVideo-1.5 is a high-priority model. The CPU-offload row runs in the existing
|
||||
CUDA PR (L2) and merge (L3) lanes. The shared default and CacheDiT / parallel rows
|
||||
carry ``full_model`` (L4) marks, together with the video similarity suites in
|
||||
``tests/e2e/accuracy/hunyuanvideo15_{t2v,i2v}/``.
|
||||
|
||||
From ``tests/``::
|
||||
@@ -23,8 +24,9 @@ From ``tests/``::
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.helpers.mark import hardware_marks
|
||||
from tests.helpers.mark import hardware_marks, hardware_test
|
||||
from tests.helpers.runtime import OmniServer, OmniServerParams, OnlineOmniClient
|
||||
from tests.helpers.stage_config import get_deploy_config_path
|
||||
|
||||
pytestmark = [pytest.mark.diffusion]
|
||||
|
||||
@@ -32,23 +34,25 @@ PROMPT = "A cat walking across a sunlit garden, cinematic lighting, slow motion.
|
||||
NEGATIVE_PROMPT = "low quality, blurry, distorted"
|
||||
|
||||
MODEL = "hunyuanvideo-community/HunyuanVideo-1.5-Diffusers-480p_t2v"
|
||||
DEPLOY_CONFIG = get_deploy_config_path("hunyuan_video_15.yaml")
|
||||
|
||||
SINGLE_CARD_MARKS = hardware_marks(res={"cuda": "H100"})
|
||||
PARALLEL_MARKS = hardware_marks(res={"cuda": "H100"}, num_cards=2)
|
||||
|
||||
# Only the most basic single-card deployment row is cheap enough for PR (L2) / merge (L3)
|
||||
# CI; the CacheDiT / parallel feature combinations run nightly (L4).
|
||||
_CORE_MARKS = [pytest.mark.core_model, pytest.mark.advanced_model]
|
||||
_FULL_MARKS = [pytest.mark.full_model]
|
||||
DEFAULT_TEST_PARAMS = [
|
||||
pytest.param(
|
||||
OmniServerParams(model=MODEL, stage_config_path=DEPLOY_CONFIG),
|
||||
id="default",
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
def _get_diffusion_feature_cases(model: str):
|
||||
"""Return diffusion feature cases for HunyuanVideo-1.5.
|
||||
|
||||
Designed for 2x H100 environment per issue #1832.
|
||||
Designed for up to two accelerators per issue #1832.
|
||||
Only the CPU-offload row is cheap enough for PR (L2) / merge (L3);
|
||||
CacheDiT / parallel combinations run nightly (L4).
|
||||
"""
|
||||
return [
|
||||
# (1 GPU) CPU offload
|
||||
# (1 accelerator) CPU offload
|
||||
pytest.param(
|
||||
OmniServerParams(
|
||||
model=model,
|
||||
@@ -57,9 +61,13 @@ def _get_diffusion_feature_cases(model: str):
|
||||
],
|
||||
),
|
||||
id="single_card_cpu_offload",
|
||||
marks=SINGLE_CARD_MARKS + _CORE_MARKS,
|
||||
marks=[
|
||||
*hardware_marks(res={"cuda": "H100", "npu": "A2"}),
|
||||
pytest.mark.core_model,
|
||||
pytest.mark.advanced_model,
|
||||
],
|
||||
),
|
||||
# (1 GPU) CacheDiT + Layerwise CPU offloading
|
||||
# (1 accelerator) CacheDiT + Layerwise CPU offloading
|
||||
pytest.param(
|
||||
OmniServerParams(
|
||||
model=model,
|
||||
@@ -70,9 +78,12 @@ def _get_diffusion_feature_cases(model: str):
|
||||
],
|
||||
),
|
||||
id="single_card_cachedit_layerwise",
|
||||
marks=SINGLE_CARD_MARKS + _FULL_MARKS,
|
||||
marks=[
|
||||
*hardware_marks(res={"cuda": ["H100", "B200"], "npu": "A2"}),
|
||||
pytest.mark.full_model,
|
||||
],
|
||||
),
|
||||
# (2 GPUs) CacheDiT + TP=2 + VAE patch parallel=2
|
||||
# (2 accelerators) CacheDiT + TP=2 + VAE patch parallel=2
|
||||
pytest.param(
|
||||
OmniServerParams(
|
||||
model=model,
|
||||
@@ -87,21 +98,18 @@ def _get_diffusion_feature_cases(model: str):
|
||||
],
|
||||
),
|
||||
id="parallel_cachedit_tp2_vae2",
|
||||
marks=PARALLEL_MARKS + _FULL_MARKS,
|
||||
marks=[
|
||||
*hardware_marks(res={"cuda": ["H100", "B200"], "npu": "A2"}, num_cards=2),
|
||||
pytest.mark.full_model,
|
||||
],
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"omni_server",
|
||||
_get_diffusion_feature_cases(MODEL),
|
||||
indirect=True,
|
||||
)
|
||||
def test_hunyuan_video_15_t2v(
|
||||
def _run_hunyuan_video_15_t2v(
|
||||
omni_server: OmniServer,
|
||||
online_client: OnlineOmniClient,
|
||||
):
|
||||
"""Diffusion feature coverage for HunyuanVideo-1.5-T2V on H100."""
|
||||
) -> None:
|
||||
form_data = {
|
||||
"prompt": PROMPT,
|
||||
"negative_prompt": NEGATIVE_PROMPT,
|
||||
@@ -119,3 +127,27 @@ def test_hunyuan_video_15_t2v(
|
||||
}
|
||||
|
||||
online_client.send_video_diffusion_request(request_config)
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": ["H100", "B200"], "npu": "A2"}, num_cards=1)
|
||||
@pytest.mark.full_model
|
||||
@pytest.mark.parametrize("omni_server", DEFAULT_TEST_PARAMS, indirect=True)
|
||||
def test_hunyuan_video_15_t2v_default(
|
||||
omni_server: OmniServer,
|
||||
online_client: OnlineOmniClient,
|
||||
) -> None:
|
||||
"""Generate a short video with the shared default GPU/NPU configuration."""
|
||||
_run_hunyuan_video_15_t2v(omni_server, online_client)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"omni_server",
|
||||
_get_diffusion_feature_cases(MODEL),
|
||||
indirect=True,
|
||||
)
|
||||
def test_hunyuan_video_15_t2v_features(
|
||||
omni_server: OmniServer,
|
||||
online_client: OnlineOmniClient,
|
||||
) -> None:
|
||||
"""Exercise shared diffusion features for HunyuanVideo-1.5-T2V."""
|
||||
_run_hunyuan_video_15_t2v(omni_server, online_client)
|
||||
@@ -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
|
||||
|
||||
"""Online serving smoke coverage for the dense LingBot-Video checkpoint."""
|
||||
|
||||
@@ -20,7 +20,7 @@ PROMPT = "a robotic arm picks up a red block"
|
||||
NEGATIVE_PROMPT = "low quality, blurry, watermark, text"
|
||||
DEFAULT_SAMPLING_PARAMS = '{"0":{"num_frames":81,"num_inference_steps":40,"guidance_scale":6.0}}'
|
||||
|
||||
SINGLE_CARD_FEATURE_MARKS = hardware_marks(res={"cuda": "H100"})
|
||||
SINGLE_CARD_FEATURE_MARKS = hardware_marks(res={"cuda": ["H100", "B200"]})
|
||||
|
||||
|
||||
def _get_diffusion_feature_cases(model: str):
|
||||
@@ -41,7 +41,7 @@ def _get_diffusion_feature_cases(model: str):
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.slow
|
||||
@pytest.mark.full_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 +63,7 @@ def test_text_to_image_001(omni_server: OmniServer, openai_client: OpenAIClientH
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.slow
|
||||
@pytest.mark.full_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:
|
||||
|
||||
@@ -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
|
||||
|
||||
"""
|
||||
L4 expansion coverage for ``robbyant/lingbot-video-dense-1.3b``.
|
||||
@@ -26,7 +26,7 @@ MODEL = "robbyant/lingbot-video-dense-1.3b"
|
||||
PROMPT = "a robotic arm picks up a red block"
|
||||
NEGATIVE_PROMPT = "low quality, blurry, watermark, text"
|
||||
|
||||
SINGLE_CARD_FEATURE_MARKS = hardware_marks(res={"cuda": "H100"})
|
||||
SINGLE_CARD_FEATURE_MARKS = hardware_marks(res={"cuda": ["H100", "B200"]})
|
||||
|
||||
|
||||
def _get_diffusion_feature_cases(model: str):
|
||||
|
||||
@@ -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
|
||||
|
||||
"""Single-GPU serving smoke for ``robbyant/lingbot-video-moe-30b-a3b``."""
|
||||
|
||||
@@ -20,7 +20,7 @@ PROMPT = "a robotic arm picks up a red block"
|
||||
NEGATIVE_PROMPT = "low quality, blurry, watermark, text"
|
||||
SMOKE_DEFAULT_SAMPLING_PARAMS = '{"0":{"num_frames":81,"num_inference_steps":2,"guidance_scale":3.0}}'
|
||||
|
||||
SINGLE_CARD_MARKS = hardware_marks(res={"cuda": "H100"})
|
||||
SINGLE_CARD_MARKS = hardware_marks(res={"cuda": ["H100", "B200"]})
|
||||
|
||||
|
||||
def _get_server_cases(model: str):
|
||||
@@ -41,7 +41,7 @@ def _get_server_cases(model: str):
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.slow
|
||||
@pytest.mark.full_model
|
||||
@pytest.mark.diffusion
|
||||
@pytest.mark.parametrize("omni_server", _get_server_cases(MODEL), indirect=True)
|
||||
def test_text_to_image_moe(omni_server: OmniServer, openai_client: OpenAIClientHandler) -> None:
|
||||
@@ -63,7 +63,7 @@ def test_text_to_image_moe(omni_server: OmniServer, openai_client: OpenAIClientH
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.slow
|
||||
@pytest.mark.full_model
|
||||
@pytest.mark.diffusion
|
||||
@pytest.mark.parametrize("omni_server", _get_server_cases(MODEL), indirect=True)
|
||||
def test_video_generation_modes_moe(omni_server: OmniServer, openai_client: OpenAIClientHandler) -> None:
|
||||
|
||||
@@ -8,7 +8,7 @@ It exercises the recommended resident SP4 topology through ``/v1/videos``.
|
||||
|
||||
From ``tests/``::
|
||||
|
||||
pytest -s -v e2e/online_serving/test_magi2.py -m "advanced_model and diffusion" --run-level=advanced_model
|
||||
pytest -s -v e2e/online_serving/test_magi2.py -m "slow and diffusion" --run-level=full_model
|
||||
"""
|
||||
|
||||
import json
|
||||
@@ -27,8 +27,7 @@ PROMPT = "A red fox walks through fresh snow while wind moves the pine branches.
|
||||
FOUR_CARD_MARKS = hardware_marks(res={"cuda": "H100"}, num_cards=4)
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
@pytest.mark.advanced_model
|
||||
@pytest.mark.slow
|
||||
@pytest.mark.diffusion
|
||||
@pytest.mark.parametrize(
|
||||
"omni_server",
|
||||
|
||||
@@ -83,6 +83,25 @@ test_params = [
|
||||
),
|
||||
]
|
||||
|
||||
turn_test_params = [
|
||||
pytest.param(
|
||||
OmniServerParams(
|
||||
model=_MODEL,
|
||||
stage_config_path=modify_stage_config(_CI_DEPLOY, updates={"session_mode": "turn"}),
|
||||
use_stage_cli=False,
|
||||
server_args=[
|
||||
"--trust-remote-code",
|
||||
"--async-chunk",
|
||||
"--chat-template",
|
||||
str(_NATIVE_CHAT_TEMPLATE),
|
||||
"--chat-template-content-format",
|
||||
"openai",
|
||||
],
|
||||
),
|
||||
id="turn_async_chunk",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def get_system_prompt():
|
||||
return {
|
||||
@@ -138,7 +157,7 @@ def _read_prompt_selection_log(offset: int) -> str:
|
||||
@pytest.mark.advanced_model
|
||||
@pytest.mark.omni
|
||||
@hardware_test(res={"cuda": "H100", "npu": "A3"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
|
||||
@pytest.mark.parametrize("omni_server", test_params + turn_test_params, indirect=True)
|
||||
def test_text_to_text_001(omni_server, openai_client) -> None:
|
||||
"""
|
||||
Test text-only input generating text output via OpenAI API.
|
||||
@@ -163,7 +182,7 @@ def test_text_to_text_001(omni_server, openai_client) -> None:
|
||||
@pytest.mark.full_model
|
||||
@pytest.mark.omni
|
||||
@hardware_test(res={"cuda": ["H100", "B200"], "npu": "A3"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
|
||||
@pytest.mark.parametrize("omni_server", test_params + turn_test_params, indirect=True)
|
||||
def test_text_to_audio_001(omni_server, openai_client) -> None:
|
||||
"""
|
||||
Test text-only input generating text + audio output via OpenAI API.
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import json
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
@@ -30,7 +30,7 @@ from tests.e2e.online_serving.run_minicpmo_realtime_duplex_multi_session import
|
||||
run_multi_session,
|
||||
)
|
||||
from tests.helpers.mark import hardware_test
|
||||
from vllm_omni.clients.duplex import build_realtime_url
|
||||
from vllm_omni.clients.duplex import build_realtime_url, metric_mean
|
||||
from vllm_omni.experimental.fullduplex.video_stacking import concat_frames_b64
|
||||
|
||||
pytestmark = pytest.mark.omni
|
||||
@@ -59,9 +59,12 @@ def _assert_session_metrics(metrics: object, *, expected_count: int) -> None:
|
||||
assert isinstance(metrics, dict)
|
||||
assert isinstance(metrics["session_id"], str)
|
||||
assert metrics["audio_turn_count"] == expected_count
|
||||
assert metrics["mean_ttft_ms"] is not None and metrics["mean_ttft_ms"] >= 0
|
||||
assert metrics["mean_ttfp_ms"] is not None and metrics["mean_ttfp_ms"] >= 0
|
||||
assert metrics["mean_rtf"] is not None and metrics["mean_rtf"] >= 0
|
||||
ttft_ms = metric_mean(metrics["ttft_ms"])
|
||||
ttfp_ms = metric_mean(metrics["ttfp_ms"])
|
||||
rtf = metric_mean(metrics["rtf"])
|
||||
assert ttft_ms is not None and ttft_ms >= 0
|
||||
assert ttfp_ms is not None and ttfp_ms >= 0
|
||||
assert rtf is not None and rtf >= 0
|
||||
|
||||
|
||||
async def _receive_protocol_events(ws, required_types: set[str], *, timeout_s: float) -> list[dict[str, object]]:
|
||||
@@ -87,25 +90,16 @@ async def _receive_protocol_events(ws, required_types: set[str], *, timeout_s: f
|
||||
|
||||
|
||||
async def _run_protocol_smoke(*, url: str, model: str, ref_audio: Path) -> list[dict[str, object]]:
|
||||
session_id = f"duplex-ci-protocol-{uuid.uuid4().hex}"
|
||||
websocket_url = build_realtime_url(
|
||||
url,
|
||||
model,
|
||||
autostart=False,
|
||||
session_id=session_id,
|
||||
extra_query={"native_duplex": "1"},
|
||||
)
|
||||
websocket_url = build_realtime_url(url, model, autostart=False)
|
||||
async with websockets.connect(websocket_url, max_size=64 * 1024 * 1024) as ws:
|
||||
await ws.send(
|
||||
json.dumps(
|
||||
{
|
||||
"type": "session.update",
|
||||
"session": {
|
||||
"session_id": session_id,
|
||||
"model": model,
|
||||
"modalities": ["audio", "text"],
|
||||
"ref_audio": _ref_audio_data_url(str(ref_audio)),
|
||||
"extra_body": {"native_duplex": True},
|
||||
},
|
||||
}
|
||||
)
|
||||
@@ -120,6 +114,170 @@ async def _run_protocol_smoke(*, url: str, model: str, ref_audio: Path) -> list[
|
||||
return events
|
||||
|
||||
|
||||
async def _run_text_only_response_create(
|
||||
*,
|
||||
url: str,
|
||||
model: str,
|
||||
ref_audio: Path,
|
||||
text: str,
|
||||
timeout_s: float = 120.0,
|
||||
) -> dict[str, object]:
|
||||
"""Drive a text prompt with no audio and return the server's answer.
|
||||
|
||||
A Realtime client asks for speech from text with a user message item
|
||||
followed by ``response.create``. A model-native duplex session generates
|
||||
from audio units, so this returns whatever the server answers rather than
|
||||
assuming a response.
|
||||
"""
|
||||
websocket_url = build_realtime_url(url, model, autostart=False)
|
||||
async with websockets.connect(websocket_url, max_size=64 * 1024 * 1024) as ws:
|
||||
await ws.send(
|
||||
json.dumps(
|
||||
{
|
||||
"type": "session.update",
|
||||
"session": {
|
||||
"model": model,
|
||||
"modalities": ["audio", "text"],
|
||||
"output_audio_format": "pcm16",
|
||||
"turn_detection": None,
|
||||
"temperature": 0.0,
|
||||
"ref_audio": _ref_audio_data_url(str(ref_audio)),
|
||||
"extra_body": {"auto_response": False},
|
||||
},
|
||||
}
|
||||
)
|
||||
)
|
||||
await _receive_protocol_events(ws, {"session.created", "session.updated"}, timeout_s=60)
|
||||
await ws.send(
|
||||
json.dumps(
|
||||
{
|
||||
"type": "conversation.item.create",
|
||||
"item": {
|
||||
"type": "message",
|
||||
"role": "user",
|
||||
"content": [{"type": "input_text", "text": text}],
|
||||
},
|
||||
}
|
||||
)
|
||||
)
|
||||
await ws.send(json.dumps({"type": "response.create"}))
|
||||
|
||||
async def receive_outcome() -> dict[str, object]:
|
||||
while True:
|
||||
raw = await ws.recv()
|
||||
if not isinstance(raw, str):
|
||||
continue
|
||||
event = json.loads(raw)
|
||||
if isinstance(event, dict) and event.get("type") in {"error", "response.done"}:
|
||||
return event
|
||||
|
||||
return await asyncio.wait_for(receive_outcome(), timeout=timeout_s)
|
||||
|
||||
|
||||
async def _run_seeded_text_to_audio(
|
||||
*,
|
||||
url: str,
|
||||
model: str,
|
||||
ref_audio: Path | None,
|
||||
text: str,
|
||||
modalities: tuple[str, ...] = ("audio", "text"),
|
||||
silence_seconds: float = 12.0,
|
||||
timeout_s: float = 180.0,
|
||||
) -> dict[str, object]:
|
||||
"""Speak a seeded text: the duplex route's text-to-speech shape.
|
||||
|
||||
A model-native session takes its text once, in the session context
|
||||
(``duplex_initial_user_text``), and then generates per audio unit. Silence
|
||||
carries no content of its own, so it only advances the clock and lets the
|
||||
model answer the seeded turn.
|
||||
"""
|
||||
websocket_url = build_realtime_url(url, model, autostart=False)
|
||||
audio_bytes = 0
|
||||
transcript: list[str] = []
|
||||
output_text: list[str] = []
|
||||
seen: list[str] = []
|
||||
session_payload: dict[str, object] = {
|
||||
"model": model,
|
||||
"modalities": list(modalities),
|
||||
"input_audio_format": "pcm16",
|
||||
"output_audio_format": "pcm16",
|
||||
"turn_detection": None,
|
||||
"temperature": 0.0,
|
||||
"extra_body": {
|
||||
"auto_response": True,
|
||||
"force_listen_count": 0,
|
||||
"duplex_initial_user_text": text,
|
||||
},
|
||||
}
|
||||
if ref_audio is not None:
|
||||
session_payload["ref_audio"] = _ref_audio_data_url(str(ref_audio))
|
||||
async with websockets.connect(websocket_url, max_size=64 * 1024 * 1024) as ws:
|
||||
await ws.send(json.dumps({"type": "session.update", "session": session_payload}))
|
||||
|
||||
async def reader() -> None:
|
||||
nonlocal audio_bytes
|
||||
while True:
|
||||
raw = await ws.recv()
|
||||
if not isinstance(raw, str):
|
||||
continue
|
||||
event = json.loads(raw)
|
||||
if not isinstance(event, dict):
|
||||
continue
|
||||
event_type = event.get("type")
|
||||
if isinstance(event_type, str):
|
||||
seen.append(event_type)
|
||||
delta = event.get("delta")
|
||||
if event_type == "response.output_audio.delta" and isinstance(delta, str):
|
||||
audio_bytes += len(base64.b64decode(delta))
|
||||
elif event_type == "response.output_audio_transcript.delta" and isinstance(delta, str):
|
||||
transcript.append(delta)
|
||||
elif event_type == "response.output_text.delta" and isinstance(delta, str):
|
||||
output_text.append(delta)
|
||||
elif event_type == "error":
|
||||
raise AssertionError(f"seeded text turn received an error: {event}")
|
||||
|
||||
reader_task = asyncio.create_task(reader())
|
||||
silence = bytes(2 * 16_000 * 200 // 1000)
|
||||
sent_ms = 0
|
||||
try:
|
||||
while sent_ms < silence_seconds * 1000 and "response.done" not in seen:
|
||||
sent_ms += 200
|
||||
await ws.send(
|
||||
json.dumps(
|
||||
{
|
||||
"type": "input_audio_buffer.append",
|
||||
"audio": base64.b64encode(silence).decode("ascii"),
|
||||
"input_audio_format": "pcm16",
|
||||
"sample_rate_hz": 16_000,
|
||||
"duration_ms": 200,
|
||||
"audio_end_ms": sent_ms,
|
||||
}
|
||||
)
|
||||
)
|
||||
await asyncio.sleep(0.2)
|
||||
loop = asyncio.get_running_loop()
|
||||
deadline = loop.time() + timeout_s
|
||||
while loop.time() < deadline and "response.done" not in seen:
|
||||
await asyncio.sleep(0.5)
|
||||
if reader_task.done():
|
||||
await reader_task
|
||||
# Close explicitly. Dropping the socket parks the session in its
|
||||
# disconnect grace, where it keeps holding an admission slot and
|
||||
# starves the tests that follow.
|
||||
await ws.send(json.dumps({"type": "session.close"}))
|
||||
deadline = loop.time() + 30
|
||||
while loop.time() < deadline and "session.closed" not in seen:
|
||||
await asyncio.sleep(0.25)
|
||||
finally:
|
||||
reader_task.cancel()
|
||||
return {
|
||||
"audio_bytes": audio_bytes,
|
||||
"transcript": "".join(transcript),
|
||||
"output_text": "".join(output_text),
|
||||
"event_types": seen,
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
@hardware_test(res={"cuda": "H100", "npu": "A3"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", SERVER_PARAMS, indirect=True)
|
||||
@@ -202,6 +360,215 @@ def test_duplex_single_session_video_input(omni_server, tmp_path: Path) -> None:
|
||||
_assert_session_metrics(result["session_metrics"], expected_count=2)
|
||||
|
||||
|
||||
@pytest.mark.advanced_model
|
||||
@hardware_test(res={"cuda": "H100", "npu": "A3"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", SERVER_PARAMS, indirect=True)
|
||||
@pytest.mark.parametrize(
|
||||
("locale", "text"),
|
||||
[
|
||||
("en", "Please say exactly: the quick brown fox jumps over the lazy dog."),
|
||||
("zh", "请朗读:今天天气很好,我们一起去公园散步。"),
|
||||
],
|
||||
)
|
||||
def test_duplex_seeded_text_to_audio(omni_server, locale: str, text: str) -> None:
|
||||
"""text -> audio over the duplex route, in both locales.
|
||||
|
||||
This is the case the deleted turn-based ``text -> audio`` tests covered.
|
||||
It is also the shape the Seed-TTS Realtime backend uses, so it guards the
|
||||
benchmark path as well as the modality.
|
||||
"""
|
||||
result = asyncio.run(
|
||||
_run_seeded_text_to_audio(
|
||||
url=realtime_url(omni_server),
|
||||
model=omni_server.model,
|
||||
ref_audio=resolve_ref_audio(),
|
||||
text=text,
|
||||
)
|
||||
)
|
||||
|
||||
assert "response.done" in result["event_types"], result["event_types"]
|
||||
assert int(result["audio_bytes"]) > 0, f"{locale} seeded text produced no audio"
|
||||
assert str(result["transcript"]).strip(), f"{locale} seeded text produced audio with no transcript"
|
||||
|
||||
|
||||
@pytest.mark.advanced_model
|
||||
@hardware_test(res={"cuda": "H100", "npu": "A3"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", SERVER_PARAMS, indirect=True)
|
||||
def test_duplex_seeded_text_to_text_needs_no_reference_voice(omni_server) -> None:
|
||||
"""text -> text, the one duplex session that opens without a reference voice.
|
||||
|
||||
``ref_audio`` is required only when the session asks for audio output, so a
|
||||
``modalities: ["text"]`` session is the duplex equivalent of the deleted
|
||||
turn-based ``text -> text`` case. The model is model-native and still
|
||||
speaks its answer, so this asserts the text side and the absence of the
|
||||
``ref_audio_required`` rejection, not the absence of audio.
|
||||
"""
|
||||
result = asyncio.run(
|
||||
_run_seeded_text_to_audio(
|
||||
url=realtime_url(omni_server),
|
||||
model=omni_server.model,
|
||||
ref_audio=None,
|
||||
text="What is the capital of France? Answer in one short sentence.",
|
||||
modalities=("text",),
|
||||
)
|
||||
)
|
||||
|
||||
assert "response.done" in result["event_types"], result["event_types"]
|
||||
produced_text = str(result["output_text"]) or str(result["transcript"])
|
||||
assert produced_text.strip(), f"text-only session produced nothing: {result['event_types']}"
|
||||
|
||||
|
||||
@pytest.mark.advanced_model
|
||||
@hardware_test(res={"cuda": "H100", "npu": "A3"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", SERVER_PARAMS, indirect=True)
|
||||
def test_duplex_seeded_text_to_long_audio_output(omni_server) -> None:
|
||||
"""A longer answer, so Code2Wav runs across many frames rather than one.
|
||||
|
||||
Replaces the deleted ``text_to_audio_long_output`` case. The assertion is
|
||||
on the amount of audio rather than its content: the point is that a long
|
||||
answer streams to completion, not that the model says any given word.
|
||||
"""
|
||||
result = asyncio.run(
|
||||
_run_seeded_text_to_audio(
|
||||
url=realtime_url(omni_server),
|
||||
model=omni_server.model,
|
||||
ref_audio=resolve_ref_audio(),
|
||||
text="What is the capital of China? Answer in about 40 words.",
|
||||
silence_seconds=30.0,
|
||||
timeout_s=240.0,
|
||||
)
|
||||
)
|
||||
|
||||
assert "response.done" in result["event_types"], result["event_types"]
|
||||
# 24 kHz mono pcm16: 2 s of speech is 96000 bytes, comfortably more than a
|
||||
# single Code2Wav frame and well under a 40-word answer.
|
||||
assert int(result["audio_bytes"]) > 96_000, f"expected a long answer, got {result['audio_bytes']} bytes"
|
||||
assert str(result["transcript"]).strip()
|
||||
|
||||
|
||||
@pytest.mark.advanced_model
|
||||
@hardware_test(res={"cuda": "H100", "npu": "A3"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", SERVER_PARAMS, indirect=True)
|
||||
def test_duplex_seeded_long_form_generation(omni_server) -> None:
|
||||
"""Long-form Chinese generation, replacing the deleted long-form case."""
|
||||
result = asyncio.run(
|
||||
_run_seeded_text_to_audio(
|
||||
url=realtime_url(omni_server),
|
||||
model=omni_server.model,
|
||||
ref_audio=resolve_ref_audio(),
|
||||
text="帮我讲一个100字的故事。",
|
||||
silence_seconds=30.0,
|
||||
timeout_s=240.0,
|
||||
)
|
||||
)
|
||||
|
||||
assert "response.done" in result["event_types"], result["event_types"]
|
||||
assert int(result["audio_bytes"]) > 96_000, f"expected long-form audio, got {result['audio_bytes']} bytes"
|
||||
assert str(result["transcript"]).strip()
|
||||
|
||||
|
||||
@pytest.mark.advanced_model
|
||||
@hardware_test(res={"cuda": "H100", "npu": "A3"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", SERVER_PARAMS, indirect=True)
|
||||
def test_duplex_sequential_sessions_are_independent(omni_server) -> None:
|
||||
"""A second session must answer its own prompt, not replay the first one.
|
||||
|
||||
Replaces the deleted ``sequential_requests_independent`` case. Sessions are
|
||||
engine-resident now, so this is the check that one session's context does
|
||||
not leak into the next one on the same stages.
|
||||
"""
|
||||
first = asyncio.run(
|
||||
_run_seeded_text_to_audio(
|
||||
url=realtime_url(omni_server),
|
||||
model=omni_server.model,
|
||||
ref_audio=resolve_ref_audio(),
|
||||
text="What is the capital of France? Answer in one short sentence.",
|
||||
)
|
||||
)
|
||||
second = asyncio.run(
|
||||
_run_seeded_text_to_audio(
|
||||
url=realtime_url(omni_server),
|
||||
model=omni_server.model,
|
||||
ref_audio=resolve_ref_audio(),
|
||||
text="What is the capital of China? Answer in one short sentence.",
|
||||
)
|
||||
)
|
||||
|
||||
for result in (first, second):
|
||||
assert "response.done" in result["event_types"], result["event_types"]
|
||||
assert int(result["audio_bytes"]) > 0
|
||||
assert str(result["transcript"]).strip()
|
||||
|
||||
# Different prompts must not produce the same answer: that would mean the
|
||||
# second session inherited the first one's context.
|
||||
assert str(first["transcript"]).strip() != str(second["transcript"]).strip()
|
||||
|
||||
|
||||
@pytest.mark.advanced_model
|
||||
@hardware_test(res={"cuda": "H100", "npu": "A3"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", SERVER_PARAMS, indirect=True)
|
||||
def test_duplex_text_only_response_create_is_rejected(omni_server) -> None:
|
||||
"""A duplex session generates from audio: a text-only prompt is refused, not ignored.
|
||||
|
||||
Every session on this route is model-native, and such a model decides per
|
||||
audio unit whether to speak: conversation items are context, not a turn.
|
||||
Refusing is the point -- opening a response the model never fills costs the
|
||||
caller the session's whole idle timeout to discover. A text prompt reaches
|
||||
the model through the session's seeded opening turn
|
||||
(``initial_user_text``) instead, which is what ``/v1/chat/completions``
|
||||
uses and what the Seed-TTS Realtime backend has to be ported to.
|
||||
"""
|
||||
outcome = asyncio.run(
|
||||
_run_text_only_response_create(
|
||||
url=realtime_url(omni_server),
|
||||
model=omni_server.model,
|
||||
ref_audio=resolve_ref_audio(),
|
||||
text="Please say: the quick brown fox jumps over the lazy dog.",
|
||||
)
|
||||
)
|
||||
|
||||
assert outcome.get("type") == "error", outcome
|
||||
error = outcome.get("error")
|
||||
assert isinstance(error, dict), outcome
|
||||
assert error.get("code") == "text_only_turn_unsupported", outcome
|
||||
assert error.get("type") == "invalid_request_error", outcome
|
||||
|
||||
|
||||
@pytest.mark.advanced_model
|
||||
@hardware_test(res={"cuda": "H100", "npu": "A3"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", SERVER_PARAMS, indirect=True)
|
||||
def test_duplex_single_session_still_image_input(omni_server, tmp_path: Path) -> None:
|
||||
"""A spoken turn with one still image attached.
|
||||
|
||||
The still-image case is a one-element frame list, which the client repeats
|
||||
on every unit of the turn: unlike the camera track it never advances, so
|
||||
this covers the image path the turn-based ``image -> text + audio`` request
|
||||
used to cover.
|
||||
"""
|
||||
args = demo_args(
|
||||
omni_server=omni_server,
|
||||
input_wav=validated_input_wav(),
|
||||
ref_audio=resolve_ref_audio(),
|
||||
output_dir=tmp_path / "still_image",
|
||||
)
|
||||
args.turns = 2
|
||||
args.turn_duration_ms = [args.first_turn_ms] * args.turns
|
||||
args.video_frames_b64 = duplex_camera_frames(seconds=1, cache_dir=tmp_path / "still")[:1]
|
||||
|
||||
result = asyncio.run(run_demo(args))
|
||||
|
||||
assert result["ok"] is True
|
||||
assert result["video_frame_count"] == 1
|
||||
assert result["video_stacked_frame_count"] == 0
|
||||
_assert_positive_int(result["audio_delta_count"])
|
||||
assert result["done_count"] == 2
|
||||
assert result["error_count"] == 0
|
||||
assert result["all_audio_responses_have_transcript"] is True
|
||||
assert result["transcript_delta_done_ok"] is True
|
||||
_assert_request_metrics(result["request_metrics"], expected_count=2)
|
||||
_assert_session_metrics(result["session_metrics"], expected_count=2)
|
||||
|
||||
|
||||
@pytest.mark.advanced_model
|
||||
@hardware_test(res={"cuda": "H100", "npu": "A3"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", SERVER_PARAMS, indirect=True)
|
||||
|
||||
@@ -30,7 +30,7 @@ from tests.e2e.online_serving.run_minicpmo_realtime_duplex_soft_interrupt import
|
||||
run_soft_interrupt,
|
||||
)
|
||||
from tests.helpers.mark import hardware_test
|
||||
from vllm_omni.entrypoints.duplex.server_vad import (
|
||||
from vllm_omni.engine.duplex.vad import (
|
||||
SILERO_VAD_FILENAME,
|
||||
SILERO_VAD_REPO_ID,
|
||||
SILERO_VAD_REVISION,
|
||||
@@ -51,7 +51,7 @@ def _cached_server_vad_artifact() -> None:
|
||||
)
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "H100", "npu": "A3"}, num_cards=1)
|
||||
@hardware_test(res={"cuda": ["H100", "B200"], "npu": "A3"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", SERVER_PARAMS, indirect=True)
|
||||
def test_duplex_admission_and_expiry_reaper(omni_server, tmp_path: Path) -> None:
|
||||
args = multi_session_args(
|
||||
@@ -79,7 +79,7 @@ def test_duplex_admission_and_expiry_reaper(omni_server, tmp_path: Path) -> None
|
||||
# still talking, which only holds when the duplex pipeline sustains real-time
|
||||
# throughput. The current NPU stack runs several times slower than real time,
|
||||
# so it never reaches a mid-stream decision point.
|
||||
@hardware_test(res={"cuda": "H100"}, num_cards=1)
|
||||
@hardware_test(res={"cuda": ["H100", "B200"]}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", SERVER_PARAMS, indirect=True)
|
||||
def test_duplex_soft_interrupt(omni_server, tmp_path: Path) -> None:
|
||||
input_wav = validated_soft_interrupt_wav()
|
||||
@@ -112,7 +112,7 @@ def test_duplex_soft_interrupt(omni_server, tmp_path: Path) -> None:
|
||||
assert result["followup_response_transcript_ok"] is True
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "H100"}, num_cards=1)
|
||||
@hardware_test(res={"cuda": ["H100", "B200"]}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", SERVER_PARAMS, indirect=True)
|
||||
def test_duplex_server_vad_hard_interrupt(_cached_server_vad_artifact, omni_server) -> None:
|
||||
result = asyncio.run(
|
||||
|
||||
@@ -152,7 +152,6 @@ def test_realtime_duplex_demo_pair_launches_demo_processes_concurrently(tmp_path
|
||||
"parser.add_argument('--output-dir')",
|
||||
"parser.add_argument('--chunk-ms')",
|
||||
"parser.add_argument('--timeout-s')",
|
||||
"parser.add_argument('--session-id')",
|
||||
"parser.add_argument('--ref-audio')",
|
||||
"parser.add_argument('--require-audio', action='store_true')",
|
||||
"parser.add_argument('--no-realtime-pacing', action='store_true')",
|
||||
@@ -168,9 +167,9 @@ def test_realtime_duplex_demo_pair_launches_demo_processes_concurrently(tmp_path
|
||||
"events = [",
|
||||
" {'type': 'session.created'},",
|
||||
" {'type': 'response.created', 'response': {'id': response_id}},",
|
||||
" {'type': 'response.audio.delta', 'response_id': response_id, "
|
||||
" {'type': 'response.output_audio.delta', 'response_id': response_id, "
|
||||
"'delta': 'AAAA', 'sample_rate_hz': 24000, '_client_received_at_s': 10.1},",
|
||||
" {'type': 'response.audio.delta', 'response_id': response_id, "
|
||||
" {'type': 'response.output_audio.delta', 'response_id': response_id, "
|
||||
"'delta': 'AAAA', 'sample_rate_hz': 24000, '_client_received_at_s': 10.6},",
|
||||
" {'type': 'response.done', 'response_id': response_id},",
|
||||
" {'type': 'session.closed'},",
|
||||
@@ -237,8 +236,8 @@ def test_realtime_duplex_demo_pair_rejects_false_green_audio_contract(tmp_path):
|
||||
response_id = "resp-a"
|
||||
events = [
|
||||
{"type": "response.created", "response": {"id": response_id}},
|
||||
{"type": "response.audio.delta", "response_id": response_id, "delta": "AAAA", "sample_rate_hz": 24000},
|
||||
{"type": "response.audio.delta", "response_id": "resp-other", "delta": "AAAA", "sample_rate_hz": 24000},
|
||||
{"type": "response.output_audio.delta", "response_id": response_id, "delta": "AAAA", "sample_rate_hz": 24000},
|
||||
{"type": "response.output_audio.delta", "response_id": "resp-other", "delta": "AAAA", "sample_rate_hz": 24000},
|
||||
{"type": "response.done", "response_id": response_id},
|
||||
]
|
||||
(output / "events.jsonl").write_text(
|
||||
@@ -459,25 +458,25 @@ def test_realtime_duplex_soft_interrupt_accepts_multi_delta_handoff_sequence(tmp
|
||||
{"type": "response.created", "response": {"id": first_response_id}, "_client_received_at_s": 2.0},
|
||||
{"type": "response.speak", "response_id": first_response_id, "_client_received_at_s": 2.0},
|
||||
{
|
||||
"type": "response.audio.delta",
|
||||
"type": "response.output_audio.delta",
|
||||
"response_id": first_response_id,
|
||||
"delta": "AAAA",
|
||||
"_client_received_at_s": 2.1,
|
||||
},
|
||||
{
|
||||
"type": "response.audio_transcript.delta",
|
||||
"type": "response.output_audio_transcript.delta",
|
||||
"response_id": first_response_id,
|
||||
"delta": "中国古代四大发明",
|
||||
"_client_received_at_s": 2.1,
|
||||
},
|
||||
{
|
||||
"type": "response.audio.delta",
|
||||
"type": "response.output_audio.delta",
|
||||
"response_id": first_response_id,
|
||||
"delta": "AAAA",
|
||||
"_client_received_at_s": 2.6,
|
||||
},
|
||||
{
|
||||
"type": "response.audio_transcript.delta",
|
||||
"type": "response.output_audio_transcript.delta",
|
||||
"response_id": first_response_id,
|
||||
"delta": "是造纸术。",
|
||||
"_client_received_at_s": 2.6,
|
||||
@@ -486,25 +485,25 @@ def test_realtime_duplex_soft_interrupt_accepts_multi_delta_handoff_sequence(tmp
|
||||
{"type": "response.created", "response": {"id": second_response_id}, "_client_received_at_s": 4.0},
|
||||
{"type": "response.speak", "response_id": second_response_id, "_client_received_at_s": 4.0},
|
||||
{
|
||||
"type": "response.audio.delta",
|
||||
"type": "response.output_audio.delta",
|
||||
"response_id": second_response_id,
|
||||
"delta": "AAAA",
|
||||
"_client_received_at_s": 4.1,
|
||||
},
|
||||
{
|
||||
"type": "response.audio_transcript.delta",
|
||||
"type": "response.output_audio_transcript.delta",
|
||||
"response_id": second_response_id,
|
||||
"delta": "一加一等于",
|
||||
"_client_received_at_s": 4.1,
|
||||
},
|
||||
{
|
||||
"type": "response.audio.delta",
|
||||
"type": "response.output_audio.delta",
|
||||
"response_id": second_response_id,
|
||||
"delta": "AAAA",
|
||||
"_client_received_at_s": 4.6,
|
||||
},
|
||||
{
|
||||
"type": "response.audio_transcript.delta",
|
||||
"type": "response.output_audio_transcript.delta",
|
||||
"response_id": second_response_id,
|
||||
"delta": "二。",
|
||||
"_client_received_at_s": 4.6,
|
||||
@@ -561,25 +560,25 @@ def test_realtime_duplex_soft_interrupt_accepts_followup_done_after_commit(tmp_p
|
||||
{"type": "response.created", "response": {"id": first_response_id}, "_client_received_at_s": 2.0},
|
||||
{"type": "response.speak", "response_id": first_response_id, "_client_received_at_s": 2.0},
|
||||
{
|
||||
"type": "response.audio.delta",
|
||||
"type": "response.output_audio.delta",
|
||||
"response_id": first_response_id,
|
||||
"delta": "AAAA",
|
||||
"_client_received_at_s": 2.1,
|
||||
},
|
||||
{
|
||||
"type": "response.audio_transcript.delta",
|
||||
"type": "response.output_audio_transcript.delta",
|
||||
"response_id": first_response_id,
|
||||
"delta": "中国古代四大发明",
|
||||
"_client_received_at_s": 2.1,
|
||||
},
|
||||
{
|
||||
"type": "response.audio.delta",
|
||||
"type": "response.output_audio.delta",
|
||||
"response_id": first_response_id,
|
||||
"delta": "AAAA",
|
||||
"_client_received_at_s": 2.6,
|
||||
},
|
||||
{
|
||||
"type": "response.audio_transcript.delta",
|
||||
"type": "response.output_audio_transcript.delta",
|
||||
"response_id": first_response_id,
|
||||
"delta": "是造纸术。",
|
||||
"_client_received_at_s": 2.6,
|
||||
@@ -589,25 +588,25 @@ def test_realtime_duplex_soft_interrupt_accepts_followup_done_after_commit(tmp_p
|
||||
{"type": "response.created", "response": {"id": second_response_id}, "_client_received_at_s": 3.5},
|
||||
{"type": "response.speak", "response_id": second_response_id, "_client_received_at_s": 3.5},
|
||||
{
|
||||
"type": "response.audio.delta",
|
||||
"type": "response.output_audio.delta",
|
||||
"response_id": second_response_id,
|
||||
"delta": "AAAA",
|
||||
"_client_received_at_s": 3.6,
|
||||
},
|
||||
{
|
||||
"type": "response.audio_transcript.delta",
|
||||
"type": "response.output_audio_transcript.delta",
|
||||
"response_id": second_response_id,
|
||||
"delta": "一加一等于",
|
||||
"_client_received_at_s": 3.6,
|
||||
},
|
||||
{
|
||||
"type": "response.audio.delta",
|
||||
"type": "response.output_audio.delta",
|
||||
"response_id": second_response_id,
|
||||
"delta": "AAAA",
|
||||
"_client_received_at_s": 3.7,
|
||||
},
|
||||
{
|
||||
"type": "response.audio_transcript.delta",
|
||||
"type": "response.output_audio_transcript.delta",
|
||||
"response_id": second_response_id,
|
||||
"delta": "二。",
|
||||
"_client_received_at_s": 3.7,
|
||||
@@ -653,8 +652,18 @@ def test_realtime_duplex_soft_interrupt_model_policy_accepts_single_response(tmp
|
||||
events = [
|
||||
{"type": "response.listen", "_client_received_at_s": 1.0},
|
||||
{"type": "response.created", "response": {"id": response_id}, "_client_received_at_s": 2.0},
|
||||
{"type": "response.audio.delta", "response_id": response_id, "delta": "AAAA", "_client_received_at_s": 2.1},
|
||||
{"type": "response.audio.delta", "response_id": response_id, "delta": "AAAA", "_client_received_at_s": 2.15},
|
||||
{
|
||||
"type": "response.output_audio.delta",
|
||||
"response_id": response_id,
|
||||
"delta": "AAAA",
|
||||
"_client_received_at_s": 2.1,
|
||||
},
|
||||
{
|
||||
"type": "response.output_audio.delta",
|
||||
"response_id": response_id,
|
||||
"delta": "AAAA",
|
||||
"_client_received_at_s": 2.15,
|
||||
},
|
||||
{"type": "response.done", "response_id": response_id, "_client_received_at_s": 2.2},
|
||||
{"type": "response.listen", "_client_received_at_s": 2.3},
|
||||
{"type": "input_audio_buffer.committed", "_client_received_at_s": 3.0},
|
||||
@@ -692,10 +701,25 @@ def test_realtime_duplex_soft_interrupt_model_policy_accepts_commit_during_speak
|
||||
events = [
|
||||
{"type": "response.listen", "_client_received_at_s": 1.0},
|
||||
{"type": "response.created", "response": {"id": response_id}, "_client_received_at_s": 2.0},
|
||||
{"type": "response.audio.delta", "response_id": response_id, "delta": "AAAA", "_client_received_at_s": 2.1},
|
||||
{"type": "response.audio.delta", "response_id": response_id, "delta": "AAAA", "_client_received_at_s": 2.2},
|
||||
{
|
||||
"type": "response.output_audio.delta",
|
||||
"response_id": response_id,
|
||||
"delta": "AAAA",
|
||||
"_client_received_at_s": 2.1,
|
||||
},
|
||||
{
|
||||
"type": "response.output_audio.delta",
|
||||
"response_id": response_id,
|
||||
"delta": "AAAA",
|
||||
"_client_received_at_s": 2.2,
|
||||
},
|
||||
{"type": "input_audio_buffer.committed", "_client_received_at_s": 3.0},
|
||||
{"type": "response.audio.delta", "response_id": response_id, "delta": "AAAA", "_client_received_at_s": 4.0},
|
||||
{
|
||||
"type": "response.output_audio.delta",
|
||||
"response_id": response_id,
|
||||
"delta": "AAAA",
|
||||
"_client_received_at_s": 4.0,
|
||||
},
|
||||
{"type": "response.done", "response_id": response_id, "_client_received_at_s": 5.0},
|
||||
]
|
||||
(output / "events.jsonl").write_text(
|
||||
@@ -729,8 +753,18 @@ def test_realtime_duplex_soft_interrupt_response_required_rejects_single_respons
|
||||
events = [
|
||||
{"type": "response.listen", "_client_received_at_s": 1.0},
|
||||
{"type": "response.created", "response": {"id": response_id}, "_client_received_at_s": 2.0},
|
||||
{"type": "response.audio.delta", "response_id": response_id, "delta": "AAAA", "_client_received_at_s": 2.1},
|
||||
{"type": "response.audio.delta", "response_id": response_id, "delta": "AAAA", "_client_received_at_s": 2.15},
|
||||
{
|
||||
"type": "response.output_audio.delta",
|
||||
"response_id": response_id,
|
||||
"delta": "AAAA",
|
||||
"_client_received_at_s": 2.1,
|
||||
},
|
||||
{
|
||||
"type": "response.output_audio.delta",
|
||||
"response_id": response_id,
|
||||
"delta": "AAAA",
|
||||
"_client_received_at_s": 2.15,
|
||||
},
|
||||
{"type": "response.done", "response_id": response_id, "_client_received_at_s": 2.2},
|
||||
{"type": "response.listen", "_client_received_at_s": 2.3},
|
||||
{"type": "input_audio_buffer.committed", "_client_received_at_s": 3.0},
|
||||
@@ -767,19 +801,19 @@ def test_realtime_duplex_soft_interrupt_reports_text_expectation_without_gating(
|
||||
{"type": "response.listen", "_client_received_at_s": 1.0},
|
||||
{"type": "response.created", "response": {"id": first_response_id}, "_client_received_at_s": 2.0},
|
||||
{
|
||||
"type": "response.audio.delta",
|
||||
"type": "response.output_audio.delta",
|
||||
"response_id": first_response_id,
|
||||
"delta": "AAAA",
|
||||
"_client_received_at_s": 2.1,
|
||||
},
|
||||
{
|
||||
"type": "response.audio.delta",
|
||||
"type": "response.output_audio.delta",
|
||||
"response_id": first_response_id,
|
||||
"delta": "AAAA",
|
||||
"_client_received_at_s": 2.2,
|
||||
},
|
||||
{
|
||||
"type": "response.audio_transcript.delta",
|
||||
"type": "response.output_audio_transcript.delta",
|
||||
"response_id": first_response_id,
|
||||
"delta": "一加一等于二",
|
||||
"_client_received_at_s": 2.2,
|
||||
@@ -788,19 +822,19 @@ def test_realtime_duplex_soft_interrupt_reports_text_expectation_without_gating(
|
||||
{"type": "response.listen", "_client_received_at_s": 2.4},
|
||||
{"type": "response.created", "response": {"id": second_response_id}, "_client_received_at_s": 3.0},
|
||||
{
|
||||
"type": "response.audio.delta",
|
||||
"type": "response.output_audio.delta",
|
||||
"response_id": second_response_id,
|
||||
"delta": "AAAA",
|
||||
"_client_received_at_s": 3.1,
|
||||
},
|
||||
{
|
||||
"type": "response.audio.delta",
|
||||
"type": "response.output_audio.delta",
|
||||
"response_id": second_response_id,
|
||||
"delta": "AAAA",
|
||||
"_client_received_at_s": 3.2,
|
||||
},
|
||||
{
|
||||
"type": "response.audio_transcript.delta",
|
||||
"type": "response.output_audio_transcript.delta",
|
||||
"response_id": second_response_id,
|
||||
"delta": "不知道",
|
||||
"_client_received_at_s": 3.2,
|
||||
@@ -834,7 +868,7 @@ def test_realtime_duplex_soft_interrupt_reports_text_expectation_without_gating(
|
||||
events = [
|
||||
event
|
||||
for event in events
|
||||
if event.get("response_id") != second_response_id or event["type"] != "response.audio_transcript.delta"
|
||||
if event.get("response_id") != second_response_id or event["type"] != "response.output_audio_transcript.delta"
|
||||
]
|
||||
(output / "events.jsonl").write_text(
|
||||
"".join(demo.json.dumps(event) + "\n" for event in events),
|
||||
@@ -992,7 +1026,7 @@ def test_realtime_duplex_demo_resolves_distinct_turn_inputs():
|
||||
demo._turn_input_paths(primary, ["second.wav"], turns=3)
|
||||
|
||||
|
||||
def test_realtime_duplex_demo_explicitly_enables_native_runtime_before_connect():
|
||||
def test_realtime_duplex_demo_url_carries_no_model_opt_in_or_session_id():
|
||||
demo = _load_demo_module()
|
||||
|
||||
url = demo._url_with_model(
|
||||
@@ -1001,23 +1035,12 @@ def test_realtime_duplex_demo_explicitly_enables_native_runtime_before_connect()
|
||||
)
|
||||
|
||||
query = parse_qs(urlsplit(url).query)
|
||||
assert query["native_duplex"] == ["1"]
|
||||
assert query["duplex"] == ["1"]
|
||||
assert "native_duplex" not in query
|
||||
assert "session_id" not in query
|
||||
|
||||
|
||||
def test_realtime_duplex_demo_explicit_session_id_reaches_autostart_query():
|
||||
demo = _load_demo_module()
|
||||
|
||||
url = demo._url_with_model(
|
||||
"ws://localhost:8099/v1/realtime?duplex=1",
|
||||
"openbmb/MiniCPM-o-4_5",
|
||||
session_id="reopen-e2e",
|
||||
)
|
||||
|
||||
query = parse_qs(urlsplit(url).query)
|
||||
assert query["session_id"] == ["reopen-e2e"]
|
||||
|
||||
|
||||
def test_realtime_duplex_demo_session_update_uses_explicit_session_id():
|
||||
def test_realtime_duplex_demo_session_update_leaves_session_id_to_the_server():
|
||||
demo = _load_demo_module()
|
||||
|
||||
event = demo._session_update_event(
|
||||
@@ -1031,8 +1054,8 @@ def test_realtime_duplex_demo_session_update_uses_explicit_session_id():
|
||||
|
||||
assert event["type"] == "session.update"
|
||||
assert "session_id" not in event
|
||||
assert event["session"]["session_id"] == "reopen-e2e"
|
||||
assert event["session"]["extra_body"]["native_duplex"] is True
|
||||
assert "session_id" not in event["session"]
|
||||
assert "native_duplex" not in event["session"]["extra_body"]
|
||||
|
||||
|
||||
def test_realtime_duplex_demo_response_required_uses_deterministic_sampling():
|
||||
@@ -1123,7 +1146,7 @@ def test_realtime_duplex_demo_partitions_timing_by_response_identity():
|
||||
)
|
||||
state.add(
|
||||
{
|
||||
"type": "response.audio.delta",
|
||||
"type": "response.output_audio.delta",
|
||||
"response_id": response_id,
|
||||
"delta": base64.b64encode(b"audio").decode("ascii"),
|
||||
"metadata": {
|
||||
@@ -1142,7 +1165,7 @@ def test_realtime_duplex_demo_partitions_timing_by_response_identity():
|
||||
)
|
||||
state.add(
|
||||
{
|
||||
"type": "response.audio_transcript.delta",
|
||||
"type": "response.output_audio_transcript.delta",
|
||||
"response_id": response_id,
|
||||
"delta": "audio",
|
||||
},
|
||||
@@ -1174,7 +1197,9 @@ def test_realtime_duplex_demo_partitions_timing_by_response_identity():
|
||||
"ttft": "input_audio_buffer.commit client send to first non-empty text delta",
|
||||
"ttfp": "input_audio_buffer.commit client send to first audio packet",
|
||||
"rtf": "commit-to-last-audio receive time divided by emitted audio duration",
|
||||
"tpot": "Stage-0 engine mean time per output token",
|
||||
},
|
||||
"tpot_ms": None,
|
||||
},
|
||||
{
|
||||
"session_id": "seed-tts-session",
|
||||
@@ -1190,15 +1215,17 @@ def test_realtime_duplex_demo_partitions_timing_by_response_identity():
|
||||
"ttft": "input_audio_buffer.commit client send to first non-empty text delta",
|
||||
"ttfp": "input_audio_buffer.commit client send to first audio packet",
|
||||
"rtf": "commit-to-last-audio receive time divided by emitted audio duration",
|
||||
"tpot": "Stage-0 engine mean time per output token",
|
||||
},
|
||||
"tpot_ms": None,
|
||||
},
|
||||
]
|
||||
assert session_metrics == {
|
||||
"session_id": "seed-tts-session",
|
||||
"audio_turn_count": 2,
|
||||
"mean_ttft_ms": 150.0,
|
||||
"mean_ttfp_ms": 250.0,
|
||||
"mean_rtf": 3.125,
|
||||
"ttft_ms": {"count": 2, "mean": 150.0, "p50": 150.0, "p99": 150.0},
|
||||
"ttfp_ms": {"count": 2, "mean": 250.0, "p50": 200.0, "p99": 300.0},
|
||||
"rtf": {"count": 2, "mean": 3.125, "p50": 2.5, "p99": 3.75},
|
||||
}
|
||||
|
||||
|
||||
@@ -1251,8 +1278,8 @@ def test_realtime_duplex_demo_distinguishes_late_and_missing_commit():
|
||||
{"type": "response.output_item.added", "response_id": response_id},
|
||||
{"type": "response.content_part.added", "response_id": response_id},
|
||||
{"type": "response.speak", "response_id": response_id},
|
||||
{"type": "response.audio.delta", "response_id": response_id, "delta": "AAAA"},
|
||||
{"type": "response.audio.done", "response_id": response_id},
|
||||
{"type": "response.output_audio.delta", "response_id": response_id, "delta": "AAAA"},
|
||||
{"type": "response.output_audio.done", "response_id": response_id},
|
||||
{"type": "response.content_part.done", "response_id": response_id},
|
||||
{"type": "response.output_item.done", "response_id": response_id},
|
||||
{"type": "response.done", "response_id": response_id},
|
||||
@@ -1314,7 +1341,7 @@ def test_realtime_duplex_demo_distinct_inputs_compare_audio_content():
|
||||
def _add_response_transcript(state, response_id, *, transcript, audio=True):
|
||||
state.add(
|
||||
{
|
||||
"type": "response.audio.delta",
|
||||
"type": "response.output_audio.delta",
|
||||
"response_id": response_id,
|
||||
"delta": "YQ==" if audio else "",
|
||||
}
|
||||
@@ -1322,14 +1349,14 @@ def _add_response_transcript(state, response_id, *, transcript, audio=True):
|
||||
if transcript:
|
||||
state.add(
|
||||
{
|
||||
"type": "response.audio_transcript.delta",
|
||||
"type": "response.output_audio_transcript.delta",
|
||||
"response_id": response_id,
|
||||
"delta": transcript,
|
||||
}
|
||||
)
|
||||
state.add(
|
||||
{
|
||||
"type": "response.audio_transcript.done",
|
||||
"type": "response.output_audio_transcript.done",
|
||||
"response_id": response_id,
|
||||
"transcript": transcript,
|
||||
}
|
||||
@@ -1404,7 +1431,7 @@ def test_realtime_duplex_demo_speak_gate_rejects_text_channel():
|
||||
{
|
||||
"type": "response.speak",
|
||||
"response_id": "resp-1",
|
||||
"text": "must be emitted through response.audio_transcript.delta",
|
||||
"text": "must be emitted through response.output_audio_transcript.delta",
|
||||
}
|
||||
)
|
||||
|
||||
@@ -1450,7 +1477,7 @@ def test_realtime_duplex_demo_gate_rejects_delta_done_mismatch():
|
||||
demo = _load_demo_module()
|
||||
state = demo.DemoState()
|
||||
_add_response_transcript(state, "resp-1", transcript="delta文本")
|
||||
done = next(event for event in state.events if event.get("type") == "response.audio_transcript.done")
|
||||
done = next(event for event in state.events if event.get("type") == "response.output_audio_transcript.done")
|
||||
done["transcript"] = "另一个done文本"
|
||||
|
||||
result = demo._evaluate_transcript_integrity(
|
||||
@@ -2180,7 +2207,7 @@ def test_realtime_duplex_demo_listen_only_overlap_accepts_silence_unit_before_fi
|
||||
state.add({"type": "response.created", "response": {"id": "resp-first"}})
|
||||
state.add(
|
||||
{
|
||||
"type": "response.audio.delta",
|
||||
"type": "response.output_audio.delta",
|
||||
"response_id": "resp-first",
|
||||
"delta": "YQ==",
|
||||
}
|
||||
@@ -2290,7 +2317,7 @@ def test_realtime_duplex_demo_writes_audio_per_response(tmp_path):
|
||||
state.add({"type": "response.created", "response": {"id": response_id}})
|
||||
state.add(
|
||||
{
|
||||
"type": "response.audio.delta",
|
||||
"type": "response.output_audio.delta",
|
||||
"response_id": response_id,
|
||||
"delta": demo.base64.b64encode(payload).decode(),
|
||||
"sample_rate_hz": 24000,
|
||||
|
||||
@@ -111,7 +111,6 @@ def _run_t2va_request(client: OpenAIClientHandler, seed: int) -> bytes:
|
||||
@pytest.mark.core_model
|
||||
@pytest.mark.advanced_model
|
||||
@pytest.mark.diffusion
|
||||
@pytest.mark.slow
|
||||
@pytest.mark.parametrize(
|
||||
"omni_server",
|
||||
[
|
||||
|
||||
@@ -30,20 +30,16 @@ from tests.helpers.mark import hardware_test
|
||||
from tests.helpers.runtime import OmniServerParams
|
||||
from tests.helpers.stage_config import get_deploy_config_path
|
||||
|
||||
_SKIP_ISSUE_6417 = pytest.mark.skip(
|
||||
reason="https://github.com/vllm-project/vllm-omni/issues/6417",
|
||||
)
|
||||
|
||||
pytestmark = [
|
||||
pytest.mark.advanced_model,
|
||||
pytest.mark.slow,
|
||||
pytest.mark.tts,
|
||||
_SKIP_ISSUE_6417,
|
||||
]
|
||||
|
||||
MODEL = "OpenMOSS-Team/MOSS-TTS-Realtime"
|
||||
REF_AUDIO_URL = "https://raw.githubusercontent.com/OpenMOSS/MOSS-TTS/HEAD/assets/audio/reference_zh_1.wav"
|
||||
# Voice-clone output is not reliably transcribed by the Whisper check used at
|
||||
# full_model run_level; assert non-trivial WAV payload size instead.
|
||||
# Reject a response that contains only a header or a very short audio payload.
|
||||
# Advanced and full runs also validate the transcript.
|
||||
_MIN_AUDIO_BYTES = 10_000
|
||||
|
||||
|
||||
@@ -77,7 +73,9 @@ def get_prompt(prompt_type: str = "text") -> str:
|
||||
"""
|
||||
prompts = {
|
||||
"text": "Hello, this is a real-time voice cloning demo for testing.",
|
||||
"chinese": "你好,这是一段实时语音合成测试。",
|
||||
# Match the offline test prompt. Whisper-small can transcribe "一段"
|
||||
# as "一本", which makes this short sample fail the similarity check.
|
||||
"chinese": "你好,这是语音合成测试。",
|
||||
}
|
||||
return prompts.get(prompt_type, prompts["text"])
|
||||
|
||||
@@ -94,7 +92,7 @@ tts_server_params = [
|
||||
]
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@hardware_test(res={"cuda": "L4", "rocm": "MI325"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
|
||||
def test_text_to_audio_001(omni_server, online_client, ref_audio_data_url) -> None:
|
||||
"""
|
||||
@@ -105,9 +103,8 @@ def test_text_to_audio_001(omni_server, online_client, ref_audio_data_url) -> No
|
||||
Input Setting: stream=False
|
||||
Datasets: single request
|
||||
|
||||
NOTE: ``min_audio_bytes`` skips Whisper transcript similarity — cloned
|
||||
voice output is often empty or mismatched under ASR without indicating a
|
||||
real serving regression.
|
||||
``min_audio_bytes`` adds a payload-size check. It does not disable the
|
||||
transcript check used by advanced and full runs.
|
||||
"""
|
||||
request_config = {
|
||||
"model": omni_server.model,
|
||||
@@ -121,7 +118,7 @@ def test_text_to_audio_001(omni_server, online_client, ref_audio_data_url) -> No
|
||||
online_client.send_audio_speech_request(request_config)
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@hardware_test(res={"cuda": "L4", "rocm": "MI325"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
|
||||
def test_text_to_audio_002_streaming(omni_server, online_client, ref_audio_data_url) -> None:
|
||||
"""
|
||||
@@ -150,7 +147,7 @@ def test_text_to_audio_002_streaming(omni_server, online_client, ref_audio_data_
|
||||
online_client.send_audio_speech_request(request_config)
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@hardware_test(res={"cuda": "L4", "rocm": "MI325"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
|
||||
def test_text_to_audio_003_chinese(omni_server, online_client, ref_audio_data_url) -> None:
|
||||
"""
|
||||
@@ -161,7 +158,8 @@ def test_text_to_audio_003_chinese(omni_server, online_client, ref_audio_data_ur
|
||||
Input Setting: stream=False
|
||||
Datasets: single request
|
||||
|
||||
NOTE: same ``min_audio_bytes`` rationale as test_text_to_audio_001.
|
||||
``min_audio_bytes`` adds a payload-size check. It does not disable the
|
||||
transcript check used by advanced and full runs.
|
||||
"""
|
||||
request_config = {
|
||||
"model": omni_server.model,
|
||||
|
||||
@@ -84,7 +84,7 @@ tts_server_params = [
|
||||
]
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@hardware_test(res={"cuda": "L4", "npu": "A2"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
|
||||
def test_text_to_audio_001(omni_server, online_client, ref_audio_data_url) -> None:
|
||||
"""
|
||||
@@ -106,7 +106,7 @@ def test_text_to_audio_001(omni_server, online_client, ref_audio_data_url) -> No
|
||||
online_client.send_audio_speech_request(request_config)
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@hardware_test(res={"cuda": "L4", "npu": "A2"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
|
||||
def test_text_to_audio_002(omni_server, online_client, ref_audio_data_url) -> None:
|
||||
"""
|
||||
@@ -138,7 +138,7 @@ def test_text_to_audio_002(omni_server, online_client, ref_audio_data_url) -> No
|
||||
online_client.send_audio_speech_request(request_config)
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@hardware_test(res={"cuda": "L4", "npu": "A2"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
|
||||
def test_text_to_audio_003(omni_server, online_client, ref_audio_data_url) -> None:
|
||||
"""
|
||||
@@ -160,7 +160,7 @@ def test_text_to_audio_003(omni_server, online_client, ref_audio_data_url) -> No
|
||||
online_client.send_audio_speech_request(request_config)
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@hardware_test(res={"cuda": "L4", "npu": "A2"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
|
||||
def test_text_to_audio_004_ref_text_ignored(omni_server, online_client, ref_audio_data_url) -> None:
|
||||
"""
|
||||
@@ -181,3 +181,23 @@ def test_text_to_audio_004_ref_text_ignored(omni_server, online_client, ref_audi
|
||||
}
|
||||
|
||||
online_client.send_audio_speech_request(request_config)
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4", "npu": "A2"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
|
||||
def test_text_to_audio_005_concurrent_requests_are_serialized(omni_server, online_client, ref_audio_data_url) -> None:
|
||||
"""Concurrent clients produce identical audio when generation is serialized."""
|
||||
request_config = {
|
||||
"model": omni_server.model,
|
||||
"input": "Concurrent clients should receive clean and deterministic speech.",
|
||||
"stream": False,
|
||||
"response_format": "wav",
|
||||
"ref_audio": ref_audio_data_url,
|
||||
"seed": 42,
|
||||
}
|
||||
|
||||
responses = online_client.send_audio_speech_request(request_config, request_num=2)
|
||||
|
||||
assert len(responses) == 2
|
||||
assert responses[0].audio_bytes
|
||||
assert responses[0].audio_bytes == responses[1].audio_bytes
|
||||
@@ -29,7 +29,16 @@ _SERVER_ENV: dict[str, str] = {"VLLM_OMNI_INPUT_WAIT_TIMEOUT_S": str(SERVER_INPU
|
||||
if TOKENIZER:
|
||||
_SERVER_ENV["NEMOTRON_VOICECHAT_LLM_PATH"] = TOKENIZER
|
||||
|
||||
pytestmark = [pytest.mark.full_model, pytest.mark.omni]
|
||||
pytestmark = [
|
||||
pytest.mark.full_model,
|
||||
pytest.mark.omni,
|
||||
# Since #7413 a duplex-capable model is served by the duplex engine only when
|
||||
# its pipeline declares a duplex_plugin. The Nemotron VoiceChat pipeline does
|
||||
# not, so the server starts the turn engine and the /v1/realtime websocket
|
||||
# falls through to vllm's speech-to-text realtime handler, which rejects the
|
||||
# native duplex client's session.update ("Missing required field: model").
|
||||
pytest.mark.skip(reason="Nemotron VoiceChat is not served by the duplex engine yet (no duplex_plugin)"),
|
||||
]
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": ["H100", "B200"]}, num_cards=1)
|
||||
|
||||
@@ -0,0 +1,568 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import json
|
||||
import wave
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import TypedDict
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
import websockets
|
||||
|
||||
from tests.e2e.online_serving import personaplex_realtime_duplex as driver
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
class _ServerState(TypedDict):
|
||||
index: int
|
||||
closed: bool
|
||||
frames: int
|
||||
close_requested: bool
|
||||
|
||||
|
||||
def _args(tmp_path, *extra):
|
||||
wav_path = tmp_path / "input.wav"
|
||||
with wave.open(str(wav_path), "wb") as stream:
|
||||
stream.setnchannels(1)
|
||||
stream.setsampwidth(2)
|
||||
stream.setframerate(driver.SAMPLE_RATE_HZ)
|
||||
stream.writeframes(np.full(driver.FRAME_SAMPLES * 2, 2000, dtype="<i2").tobytes())
|
||||
return driver.parse_args(
|
||||
[
|
||||
"--model",
|
||||
"fixture-only",
|
||||
"--input-wav",
|
||||
str(wav_path),
|
||||
"--output-dir",
|
||||
str(tmp_path / "out"),
|
||||
"--sessions",
|
||||
"2",
|
||||
"--load-frames",
|
||||
"2",
|
||||
"--tail-s",
|
||||
"0",
|
||||
"--drain-s",
|
||||
"0.04",
|
||||
"--timeout-s",
|
||||
"3",
|
||||
"--cleanup-timeout-s",
|
||||
"1",
|
||||
"--min-voiced-frames",
|
||||
"1",
|
||||
"--minimum-audio-chunks",
|
||||
"1",
|
||||
"--max-frame-deficit",
|
||||
"0",
|
||||
*extra,
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def _audio(response_id="r", samples=1920, event_type="response.output_audio.delta"):
|
||||
return {
|
||||
"type": event_type,
|
||||
"response_id": response_id,
|
||||
"delta": base64.b64encode(np.full(samples, 2000, dtype="<i2").tobytes()).decode("ascii"),
|
||||
"sample_rate_hz": driver.SAMPLE_RATE_HZ,
|
||||
"metadata": {
|
||||
"vllm_omni": {
|
||||
"runtime_impl": "scheduler_data_plane",
|
||||
"uses_model_runner_scheduler": True,
|
||||
"runner_kv_backed": True,
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def _server(mode="success"):
|
||||
states: list[_ServerState] = []
|
||||
|
||||
async def handle(ws):
|
||||
index = len(states)
|
||||
state: _ServerState = {"index": index, "closed": False, "frames": 0, "close_requested": False}
|
||||
states.append(state)
|
||||
response_id = "shared" if mode == "shared_response" else f"r-{index}"
|
||||
try:
|
||||
async for raw in ws:
|
||||
message = json.loads(raw)
|
||||
if message["type"] == "session.update":
|
||||
if mode == "reject_second" and index == 1:
|
||||
await ws.send(json.dumps({"type": "error", "error": {"code": "resource_exhausted"}}))
|
||||
continue
|
||||
if mode == "missing_capabilities":
|
||||
await ws.send(
|
||||
json.dumps(
|
||||
{
|
||||
"type": "session.created",
|
||||
"session": {"resume_token": "must-not-be-exported"},
|
||||
}
|
||||
)
|
||||
)
|
||||
continue
|
||||
await ws.send(
|
||||
json.dumps(
|
||||
{
|
||||
"type": "session.created",
|
||||
"session": {
|
||||
"resume_token": "must-not-be-exported",
|
||||
"capabilities": {
|
||||
"chunk_period_ms": 80,
|
||||
"supports_multi_session_same_replica": True,
|
||||
},
|
||||
},
|
||||
}
|
||||
)
|
||||
)
|
||||
await ws.send(json.dumps({"type": "response.created", "response": {"id": response_id}}))
|
||||
elif message["type"] == "input_audio_buffer.append":
|
||||
state["frames"] += 1
|
||||
if mode == "short_audio" and state["frames"] == 2:
|
||||
continue
|
||||
if mode == "disconnect":
|
||||
await ws.close()
|
||||
return
|
||||
if mode == "bad_json":
|
||||
await ws.send("{")
|
||||
elif mode not in ("silent", "late_on_close"):
|
||||
event_type = (
|
||||
"response.audio.delta" if mode == "legacy_audio_event" else "response.output_audio.delta"
|
||||
)
|
||||
packet = _audio(response_id, event_type=event_type)
|
||||
if mode == "private_metadata":
|
||||
packet["metadata"] = {"vllm_omni": {"private": "remote-detail-must-not-be-exported"}}
|
||||
if mode == "odd_packet":
|
||||
raw_audio = base64.b64decode(packet["delta"])
|
||||
raw_audio = raw_audio + b"\x00" if state["frames"] == 1 else raw_audio[:-1]
|
||||
packet["delta"] = base64.b64encode(raw_audio).decode("ascii")
|
||||
if state["frames"] == 2:
|
||||
if mode == "missing_packet_rate":
|
||||
packet.pop("sample_rate_hz")
|
||||
elif mode == "string_packet_rate":
|
||||
packet["sample_rate_hz"] = "24000"
|
||||
elif mode == "invalid_base64":
|
||||
packet["delta"] = "!" + packet["delta"]
|
||||
elif mode == "orphan_audio":
|
||||
orphan = _audio(response_id)
|
||||
orphan.pop("response_id")
|
||||
await ws.send(json.dumps(orphan))
|
||||
await ws.send(json.dumps(packet))
|
||||
elif message["type"] == "session.close":
|
||||
state["close_requested"] = True
|
||||
if mode == "late_on_close":
|
||||
await ws.send(json.dumps(_audio(response_id, samples=driver.FRAME_SAMPLES * state["frames"])))
|
||||
if mode == "error_on_close":
|
||||
await ws.send(json.dumps({"type": "error", "error": {"code": "cleanup_failed"}}))
|
||||
if mode != "no_close_ack":
|
||||
await ws.send(json.dumps({"type": "session.closed"}))
|
||||
finally:
|
||||
state["closed"] = True
|
||||
|
||||
async with websockets.serve(handle, "127.0.0.1", 0) as server:
|
||||
port = server.sockets[0].getsockname()[1]
|
||||
yield f"ws://127.0.0.1:{port}/v1/realtime", states
|
||||
|
||||
|
||||
def test_omitted_sessions_preserves_lifecycle_mode():
|
||||
args = driver.parse_args(["--model", "unused", "--input-wav", "unused.wav"])
|
||||
assert args.sessions is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"options",
|
||||
[
|
||||
["--sessions", "0"],
|
||||
["--sessions", "65"],
|
||||
["--load-frames", "0"],
|
||||
["--load-frames", "10001"],
|
||||
["--drain-s", "nan"],
|
||||
["--tail-s", "-1"],
|
||||
["--timeout-s", "0"],
|
||||
["--timeout-s", "inf"],
|
||||
["--cleanup-timeout-s", "0"],
|
||||
["--cleanup-timeout-s", "nan"],
|
||||
["--max-client-rtf", "-1"],
|
||||
["--max-frame-deficit", "-1"],
|
||||
["--minimum-audio-chunks", "0"],
|
||||
["--min-voiced-frames", "0"],
|
||||
["--voiced-frame-rms-threshold", "nan"],
|
||||
],
|
||||
)
|
||||
def test_load_rejects_invalid_configuration(tmp_path, options):
|
||||
with pytest.raises(SystemExit):
|
||||
_args(tmp_path, *options)
|
||||
|
||||
|
||||
def test_metric_clock_and_packet_frame_distinction():
|
||||
client = driver.RawRealtimeProbe("ws://unused")
|
||||
client.events.add({"type": "session.created", "session": {"resume_token": "secret"}}, received_at_s=7)
|
||||
for when in (10.4, 10.8, 11.6):
|
||||
event = _audio(samples=driver.FRAME_SAMPLES * 5)
|
||||
event["_client_received_at_s"] = -999.0
|
||||
client.events.add(event, received_at_s=when)
|
||||
report = driver._load_metrics(client, [(10, 10, 10.01)])
|
||||
intervals = report["client_audio_packet_interval_ms"]
|
||||
assert isinstance(intervals, dict)
|
||||
assert intervals["count"] == 2
|
||||
assert intervals["median"] == pytest.approx(600)
|
||||
assert intervals["p99"] == pytest.approx(796)
|
||||
assert intervals["max"] == pytest.approx(800)
|
||||
assert intervals["argmax_index"] == 1
|
||||
assert report["client_first_audio_after_stream_start_ms"] == pytest.approx(400)
|
||||
assert report["output_samples"] == 15 * driver.FRAME_SAMPLES
|
||||
assert report["audio_underrun_s"] == pytest.approx(0.4)
|
||||
assert report["audio_continuity_ok"] is False
|
||||
underruns = report["audio_underrun_event_count"]
|
||||
assert isinstance(underruns, int) and underruns >= 1
|
||||
assert report["client_pacing_warning"] is False
|
||||
assert "secret" not in json.dumps(report)
|
||||
assert "-999" not in json.dumps(report)
|
||||
|
||||
|
||||
def test_empty_output_has_missing_not_zero_latency():
|
||||
report = driver._load_metrics(driver.RawRealtimeProbe("ws://unused"), [])
|
||||
assert report["client_stream_rtf"] is None
|
||||
assert report["audio_continuity_ok"] is None
|
||||
assert report["audio_underrun_s"] is None
|
||||
intervals = report["client_audio_packet_interval_ms"]
|
||||
assert isinstance(intervals, dict)
|
||||
assert intervals["p99"] is None
|
||||
|
||||
|
||||
def test_failed_acceptance_retains_frame_counts_without_remote_data():
|
||||
client = driver.RawRealtimeProbe("ws://unused")
|
||||
client.events.add(_audio(), received_at_s=1.0)
|
||||
args = driver.parse_args(
|
||||
["--model", "unused", "--input-wav", "unused.wav", "--max-frame-deficit", "0", "--min-voiced-frames", "1"]
|
||||
)
|
||||
with pytest.raises(AssertionError) as raised:
|
||||
driver._session_result(client, input_frames=2, args=args, minimum_chunks=1)
|
||||
assert getattr(raised.value, "check", None) == "frame_deficit"
|
||||
stats = getattr(raised.value, "stats", {})
|
||||
assert stats["frame_deficit"] == 1 and type(stats["frame_deficit"]) is int
|
||||
assert stats["output_frames"] == stats["voiced_frames"] == 1
|
||||
assert stats["frame_coverage_ratio"] == 0.5
|
||||
|
||||
|
||||
@pytest.mark.parametrize("event_type", sorted(driver.AUDIO_DELTA_EVENT_TYPES))
|
||||
def test_session_result_accepts_current_and_legacy_audio_event_names(tmp_path, event_type):
|
||||
client = driver.RawRealtimeProbe("ws://unused")
|
||||
client.events.add(_audio(samples=driver.FRAME_SAMPLES, event_type=event_type), received_at_s=1.0)
|
||||
raw, response_ids, stats = driver._session_result(
|
||||
client,
|
||||
input_frames=1,
|
||||
args=_args(tmp_path, "--sessions", "1"),
|
||||
minimum_chunks=1,
|
||||
)
|
||||
assert len(raw) == driver.FRAME_SAMPLES * 2
|
||||
assert response_ids == {"r"}
|
||||
assert stats["frame_deficit"] == 0
|
||||
|
||||
|
||||
def test_legacy_audio_event_name_contributes_load_metrics():
|
||||
client = driver.RawRealtimeProbe("ws://unused")
|
||||
client.events.add(_audio(samples=driver.FRAME_SAMPLES * 5, event_type="response.audio.delta"), received_at_s=10.4)
|
||||
report = driver._load_metrics(client, [(10.0, 10.0, 10.01)])
|
||||
assert report["output_samples"] == driver.FRAME_SAMPLES * 5
|
||||
assert report["response_ids"] == ["r"]
|
||||
assert report["invalid_audio_packets"] == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("sessions", [1, 2, 4])
|
||||
async def test_real_websocket_load_success(tmp_path, sessions):
|
||||
args = _args(tmp_path, "--sessions", str(sessions))
|
||||
async with _server() as (url, states):
|
||||
args.url = url
|
||||
result = await driver.run(args)
|
||||
assert result["ok"] is True
|
||||
assert result["passed_sessions"] == sessions
|
||||
rows = result["sessions"]
|
||||
assert isinstance(rows, list)
|
||||
assert len(rows) == sessions
|
||||
assert all(row["frame_deficit"] == 0 for row in rows)
|
||||
for row in rows:
|
||||
assert type(row["frame_deficit"]) is int
|
||||
assert row["output_frames"] == row["voiced_frames"] == row["audio_chunks"] == 2
|
||||
assert row["silent_frames"] == 0
|
||||
assert row["frame_coverage_ratio"] == 1.0
|
||||
assert row["audio_rms"] == pytest.approx(2000 / 32768)
|
||||
assert row["acceptance_check"] is None
|
||||
assert isinstance(row["audio_continuity_ok"], bool)
|
||||
assert all(s["closed"] and s["close_requested"] for s in states)
|
||||
assert "must-not-be-exported" not in json.dumps(result)
|
||||
saved = json.loads((tmp_path / "out/load-result.json").read_text())
|
||||
assert saved == result
|
||||
origins = [row["input_timeline"][0]["planned_at_s"] for row in rows]
|
||||
assert len(set(origins)) == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_real_websocket_load_accepts_legacy_audio_event_name(tmp_path):
|
||||
args = _args(tmp_path, "--sessions", "2")
|
||||
async with _server("legacy_audio_event") as (url, states):
|
||||
args.url = url
|
||||
result = await driver.run(args)
|
||||
assert result["ok"] is True
|
||||
assert result["passed_sessions"] == 2
|
||||
assert result["shared_response_ids"] == []
|
||||
assert all(s["closed"] and s["close_requested"] for s in states)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"mode",
|
||||
[
|
||||
"reject_second",
|
||||
"silent",
|
||||
"disconnect",
|
||||
"no_close_ack",
|
||||
"shared_response",
|
||||
"late_on_close",
|
||||
"error_on_close",
|
||||
"bad_json",
|
||||
"missing_capabilities",
|
||||
],
|
||||
)
|
||||
async def test_real_websocket_failures_remain_in_results(tmp_path, mode):
|
||||
args = _args(tmp_path)
|
||||
async with _server(mode) as (url, states):
|
||||
args.url = url
|
||||
result = await asyncio.wait_for(driver.run(args), timeout=4)
|
||||
assert result["ok"] is False
|
||||
assert "must-not-be-exported" not in json.dumps(result)
|
||||
assert result["requested_sessions"] == 2
|
||||
rows = result["sessions"]
|
||||
assert isinstance(rows, list)
|
||||
assert len(rows) == 2
|
||||
assert all(s["closed"] for s in states)
|
||||
if mode == "reject_second":
|
||||
assert result["passed_sessions"] == 1
|
||||
rejected = next(row for row in rows if not row["ok"])
|
||||
assert rejected["input_frames"] == 0
|
||||
assert rejected["client_stream_rtf"] is None
|
||||
assert rejected["server_error_codes"] == ["resource_exhausted"]
|
||||
if mode == "silent":
|
||||
# A failed measurement must still release its admitted session.
|
||||
assert all(s["close_requested"] for s in states)
|
||||
if mode == "late_on_close":
|
||||
assert all(row["output_samples"] == 0 for row in rows)
|
||||
if mode == "shared_response":
|
||||
assert result["passed_sessions"] == 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_existing_report_is_not_overwritten(tmp_path):
|
||||
args = _args(tmp_path)
|
||||
path = tmp_path / "out/load-result.json"
|
||||
path.parent.mkdir()
|
||||
path.write_text("previous measurement")
|
||||
with pytest.raises(FileExistsError):
|
||||
await driver.run(args)
|
||||
assert path.read_text() == "previous measurement"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("mode", ["success", "no_close_ack"])
|
||||
async def test_cancellation_closes_all_connections(tmp_path, mode):
|
||||
args = _args(tmp_path, "--drain-s", "10", "--timeout-s", "30")
|
||||
async with _server(mode) as (url, states):
|
||||
args.url = url
|
||||
task = asyncio.create_task(driver.run(args))
|
||||
|
||||
async def started():
|
||||
while len(states) < 2 or not all(state["frames"] for state in states):
|
||||
await asyncio.sleep(0.01)
|
||||
|
||||
await asyncio.wait_for(started(), timeout=3)
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await asyncio.wait_for(task, timeout=3)
|
||||
assert all(s["closed"] for s in states)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_client_rtf_ceiling_marks_slow_sessions_failed(tmp_path):
|
||||
args = _args(tmp_path, "--max-client-rtf", "0.001")
|
||||
async with _server() as (url, _):
|
||||
args.url = url
|
||||
result = await driver.run(args)
|
||||
assert result["passed_sessions"] == 0
|
||||
rows = result["sessions"]
|
||||
assert isinstance(rows, list)
|
||||
assert all("client_stream_rtf exceeds" in row["error"] for row in rows)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stalled_send_does_not_cause_catchup_burst():
|
||||
class Clock:
|
||||
now = 10.0
|
||||
|
||||
def monotonic(self):
|
||||
return self.now
|
||||
|
||||
async def sleep(self, delay):
|
||||
self.now += delay
|
||||
|
||||
class Client(driver.RawRealtimeProbe):
|
||||
async def send(self, event):
|
||||
if event["audio_end_ms"] == 80:
|
||||
clock.now += 0.25
|
||||
|
||||
clock = Clock()
|
||||
sends: list[tuple[float, float, float]] = []
|
||||
await driver._paced_load_frames(
|
||||
Client("ws://unused"),
|
||||
np.zeros(driver.FRAME_SAMPLES * 3, dtype="<f4"),
|
||||
epoch=10.0,
|
||||
timeout_s=1.0,
|
||||
sends=sends,
|
||||
clock=clock.monotonic,
|
||||
sleep=clock.sleep,
|
||||
)
|
||||
assert len(sends) == 3
|
||||
assert sends[1][1] >= sends[0][2] + driver.FRAME_PERIOD_S
|
||||
assert sends[1][1] - sends[1][0] == pytest.approx(0.25)
|
||||
assert sends[2][1] >= sends[1][2] + driver.FRAME_PERIOD_S
|
||||
metrics = driver._load_metrics(Client("ws://unused"), sends)
|
||||
assert metrics["client_pacing_warning"] is True
|
||||
assert asyncio.sleep != clock.sleep
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_failed_frame_acceptance_preserves_numeric_diagnostics(tmp_path):
|
||||
args = _args(tmp_path, "--sessions", "1")
|
||||
async with _server("short_audio") as (url, states):
|
||||
args.url = url
|
||||
result = await driver.run(args)
|
||||
rows = result["sessions"]
|
||||
assert isinstance(rows, list)
|
||||
row = rows[0]
|
||||
assert row["ok"] is False
|
||||
assert row["acceptance_check"] == "frame_deficit"
|
||||
assert row["frame_deficit"] == 1 and type(row["frame_deficit"]) is int
|
||||
assert row["output_frames"] == row["voiced_frames"] == row["audio_chunks"] == 1
|
||||
assert row["frame_coverage_ratio"] == 0.5
|
||||
assert row["audio_rms"] == pytest.approx(2000 / 32768)
|
||||
assert "input=2" in row["error"] and "maximum_deficit=0" in row["error"]
|
||||
assert all(state["closed"] and state["close_requested"] for state in states)
|
||||
assert json.loads((tmp_path / "out/load-result.json").read_text()) == result
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_acceptance_failure_does_not_export_remote_metadata(tmp_path):
|
||||
args = _args(tmp_path, "--sessions", "1")
|
||||
async with _server("private_metadata") as (url, _):
|
||||
args.url = url
|
||||
result = await driver.run(args)
|
||||
rows = result["sessions"]
|
||||
assert isinstance(rows, list)
|
||||
row = rows[0]
|
||||
assert row["ok"] is False
|
||||
assert row["acceptance_check"] == "scheduler_data_plane"
|
||||
assert "remote-detail" not in json.dumps(result)
|
||||
assert "must-not-be-exported" not in json.dumps(result)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ok", [True, False])
|
||||
def test_load_main_exit_status(tmp_path, monkeypatch, ok):
|
||||
args = _args(tmp_path)
|
||||
|
||||
async def completed(_args):
|
||||
return {"mode": "paced_multi_session", "ok": ok}
|
||||
|
||||
monkeypatch.setattr(driver, "parse_args", lambda: args)
|
||||
monkeypatch.setattr(driver, "run", completed)
|
||||
if ok:
|
||||
driver.main()
|
||||
else:
|
||||
with pytest.raises(SystemExit) as exc:
|
||||
driver.main()
|
||||
assert exc.value.code == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_handshake_rejection_is_retained_without_server_details(tmp_path, monkeypatch):
|
||||
from websockets.exceptions import InvalidHandshake
|
||||
|
||||
async def rejected(_self):
|
||||
raise InvalidHandshake("credentials-in-remote-handshake-detail")
|
||||
|
||||
monkeypatch.setattr(driver.RawRealtimeProbe, "__aenter__", rejected)
|
||||
result = await asyncio.wait_for(driver.run(_args(tmp_path)), timeout=3)
|
||||
assert result["ok"] is False
|
||||
rows = result["sessions"]
|
||||
assert isinstance(rows, list) and len(rows) == 2
|
||||
assert all(row["error"] == "admission: InvalidHandshake" for row in rows)
|
||||
assert "credentials-in-remote-handshake-detail" not in json.dumps(result)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("sessions", [1, 2])
|
||||
@pytest.mark.parametrize(
|
||||
"mode",
|
||||
[
|
||||
"missing_packet_rate",
|
||||
"string_packet_rate",
|
||||
"invalid_base64",
|
||||
"orphan_audio",
|
||||
"odd_packet",
|
||||
],
|
||||
)
|
||||
async def test_load_rejects_invalid_individual_audio_packets(tmp_path, sessions, mode):
|
||||
# The concatenated PCM can still meet coverage/voicing thresholds, so the
|
||||
# validator must also check each packet before accepting the whole run.
|
||||
args = _args(tmp_path, "--sessions", str(sessions))
|
||||
async with _server(mode) as (url, states):
|
||||
args.url = url
|
||||
result = await asyncio.wait_for(driver.run(args), timeout=4)
|
||||
assert result["ok"] is False
|
||||
assert result["passed_sessions"] == 0
|
||||
rows = result["sessions"]
|
||||
assert isinstance(rows, list) and len(rows) == sessions
|
||||
assert all(row["error"] is not None for row in rows)
|
||||
expected_code = {
|
||||
"missing_packet_rate": "invalid_audio_sample_rate",
|
||||
"string_packet_rate": "invalid_audio_sample_rate",
|
||||
"invalid_base64": "invalid_audio_base64",
|
||||
"orphan_audio": "missing_audio_response_id",
|
||||
"odd_packet": "unaligned_pcm16_packet",
|
||||
}[mode]
|
||||
assert all({packet["code"] for packet in row["invalid_audio_packets"]} == {expected_code} for row in rows)
|
||||
assert all(
|
||||
sum(packet["samples"] for packet in row["audio_packet_timeline"]) == row["output_samples"] for row in rows
|
||||
)
|
||||
assert all(state["closed"] and state["close_requested"] for state in states)
|
||||
assert json.loads((tmp_path / "out/load-result.json").read_text()) == result
|
||||
|
||||
|
||||
def test_load_allows_empty_and_multi_frame_audio_packets():
|
||||
client = driver.RawRealtimeProbe("ws://unused")
|
||||
client.events.add(_audio(samples=0), received_at_s=1.0)
|
||||
client.events.add(_audio(samples=driver.FRAME_SAMPLES * 5), received_at_s=1.4)
|
||||
metrics = driver._load_metrics(client, [(1.0, 1.0, 1.001)])
|
||||
assert metrics["invalid_audio_packets"] == []
|
||||
assert metrics["output_samples"] == driver.FRAME_SAMPLES * 5
|
||||
packets = metrics["audio_packet_timeline"]
|
||||
assert isinstance(packets, list) and len(packets) == 1
|
||||
|
||||
|
||||
def test_load_packet_diagnostics_do_not_copy_remote_payload():
|
||||
client = driver.RawRealtimeProbe("ws://unused")
|
||||
event = _audio()
|
||||
event["delta"] = "private-remote-payload!"
|
||||
client.events.add(event, received_at_s=1.4)
|
||||
metrics = driver._load_metrics(client, [])
|
||||
assert metrics["output_samples"] == 0
|
||||
assert metrics["invalid_audio_packets"] == [
|
||||
{
|
||||
"event_index": 0,
|
||||
"received_at_s": 1.4,
|
||||
"code": "invalid_audio_base64",
|
||||
}
|
||||
]
|
||||
assert "private-remote-payload" not in json.dumps(metrics)
|
||||
@@ -0,0 +1,86 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""E2E online serving test for π0.5 OpenPI websocket serving.
|
||||
|
||||
Boots ``vllm serve --omni --deploy-config pi05.yaml`` and drives the real OpenPI
|
||||
websocket (``/v1/realtime/robot/openpi``) — the same wire path a robot uses
|
||||
(handshake metadata → send observation → receive action chunk). Mirrors
|
||||
``tests/e2e/online_serving/test_pi0_expansion.py``. Needs one H100 and the full
|
||||
π0.5 checkpoint.
|
||||
|
||||
The ``pi0_openpi_*`` helpers are protocol-level (handshake, send obs, receive
|
||||
chunk) and not π0-specific, so π0.5 reuses them; only the deploy config and the
|
||||
expected metadata differ. This file is selected explicitly by the nightly H100
|
||||
robot-policy job.
|
||||
|
||||
The in-process LeRobot parity oracle lives separately in
|
||||
``tests/diffusion/models/pi05/test_pi05_parity.py``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.helpers.mark import hardware_test
|
||||
from tests.helpers.runtime import (
|
||||
OmniServerParams,
|
||||
get_open_port,
|
||||
pi0_openpi_require_dependencies,
|
||||
pi0_openpi_run_policy_session,
|
||||
pi0_openpi_validate_session_result,
|
||||
)
|
||||
|
||||
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
|
||||
os.environ["VLLM_TEST_CLEAN_GPU_MEMORY"] = "0"
|
||||
|
||||
MODEL = "lerobot/pi05_base"
|
||||
|
||||
|
||||
test_params = [
|
||||
OmniServerParams(
|
||||
model=MODEL,
|
||||
port=8093,
|
||||
server_args=[
|
||||
"--deploy-config",
|
||||
"vllm_omni/deploy/pi05.yaml",
|
||||
"--enforce-eager",
|
||||
"--disable-log-stats",
|
||||
],
|
||||
env_dict={
|
||||
"ATTENTION_BACKEND": "torch",
|
||||
"DIFFUSION_ATTENTION_BACKEND": "TORCH_SDPA",
|
||||
"VLLM_DISABLE_COMPILE_CACHE": "1",
|
||||
"MASTER_PORT": str(get_open_port()),
|
||||
},
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.full_model
|
||||
@pytest.mark.diffusion
|
||||
@hardware_test(res={"cuda": "H100"})
|
||||
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
|
||||
def test_pi05_openpi_online(omni_server):
|
||||
pi0_openpi_require_dependencies()
|
||||
|
||||
result = pi0_openpi_run_policy_session(
|
||||
host=omni_server.host,
|
||||
port=omni_server.port,
|
||||
prompt="pick up the red block and place it in the bin",
|
||||
session_id="pi05-online-e2e",
|
||||
num_steps=2,
|
||||
num_inference_steps=2,
|
||||
)
|
||||
|
||||
# Asserts every returned chunk is [50, 32] + finite, and the handshake
|
||||
# metadata matches pi05.yaml's policy_server_config.
|
||||
pi0_openpi_validate_session_result(result)
|
||||
|
||||
metadata = result["metadata"]
|
||||
assert tuple(metadata["image_resolution"]) == (224, 224)
|
||||
assert metadata["needs_wrist_camera"] is True
|
||||
assert metadata["needs_session_id"] is False
|
||||
assert metadata["action_space"] == "joint_position"
|
||||
@@ -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 π0 (Pi-Zero) OpenPI websocket serving.
|
||||
|
||||
@@ -58,7 +58,7 @@ test_params = [
|
||||
|
||||
@pytest.mark.full_model
|
||||
@pytest.mark.diffusion
|
||||
@hardware_test(res={"cuda": "H100"})
|
||||
@hardware_test(res={"cuda": ["H100", "B200"]})
|
||||
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
|
||||
def test_pi0_openpi_online(omni_server):
|
||||
try:
|
||||
|
||||
@@ -96,6 +96,32 @@ def test_mix_to_text_audio_001(omni_server, online_client) -> None:
|
||||
online_client.send_omni_request(request_config)
|
||||
|
||||
|
||||
@pytest.mark.slow
|
||||
@pytest.mark.omni
|
||||
@hardware_test(res={"cuda": "L4", "rocm": "MI325"}, num_cards=2)
|
||||
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
|
||||
@pytest.mark.parametrize("stream", [False, True])
|
||||
def test_audio_in_video_boundaries(omni_server, online_client, stream: bool) -> None:
|
||||
"""Interleaved video/audio input must not treat audio boundaries as image placeholders."""
|
||||
# More than two seconds exercises multiple interleaved video/audio chunks.
|
||||
video_data_url = f"data:video/mp4;base64,{generate_synthetic_video(224, 224, 128, embed_audio=True)['base64']}"
|
||||
messages = dummy_messages_from_mix_data(
|
||||
system_prompt=get_system_prompt(),
|
||||
video_data_url=video_data_url,
|
||||
content_text="Describe what you see and hear in this video in one sentence.",
|
||||
)
|
||||
responses = online_client.send_omni_request(
|
||||
{
|
||||
"model": omni_server.model,
|
||||
"messages": messages,
|
||||
"stream": stream,
|
||||
"modalities": ["text"],
|
||||
"use_audio_in_video": True,
|
||||
}
|
||||
)
|
||||
assert responses[0].text_content
|
||||
|
||||
|
||||
@pytest.mark.slow
|
||||
@pytest.mark.omni
|
||||
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
|
||||
|
||||
@@ -24,29 +24,40 @@ _MODEL = "Qwen/Qwen3-Omni-30B-A3B-Instruct"
|
||||
_CI_DEPLOY = get_deploy_config_path("ci/qwen3_omni_moe.yaml")
|
||||
|
||||
|
||||
# For prefix caching checks against we enable it on the thinker and talker via CLI override
|
||||
# and enable prompt token details so that we can determine if any tokens were cached.
|
||||
# We also explicitly set block size so that we can make sure the cached token counts are a
|
||||
# multiple of the block size.
|
||||
# Prefix cache is opt-in on the deploy YAML. CI overlay also pins
|
||||
# ``async_chunk: False``; the existing server keeps ``--no-async-chunk``.
|
||||
# Production Qwen YAML is ``async_chunk: true``, so a sibling server boots
|
||||
# with ``--async-chunk`` and the same cache overrides (async output builder).
|
||||
BLOCK_SIZE = 16
|
||||
_PREFIX_CACHE_SERVER_ARGS = [
|
||||
"--block-size",
|
||||
str(BLOCK_SIZE),
|
||||
"--stage-overrides",
|
||||
'{"0": {"enable_prefix_caching": true}, "1": {"enable_prefix_caching": true}}',
|
||||
"--enable-prompt-tokens-details",
|
||||
]
|
||||
test_params = [
|
||||
pytest.param(
|
||||
OmniServerParams(
|
||||
model=_MODEL,
|
||||
stage_config_path=_CI_DEPLOY,
|
||||
use_stage_cli=True,
|
||||
server_args=[
|
||||
"--no-async-chunk",
|
||||
"--block-size",
|
||||
str(BLOCK_SIZE),
|
||||
"--stage-overrides",
|
||||
'{"0": {"enable_prefix_caching": true}, "1": {"enable_prefix_caching": true}}',
|
||||
"--enable-prompt-tokens-details",
|
||||
],
|
||||
server_args=["--no-async-chunk", *_PREFIX_CACHE_SERVER_ARGS],
|
||||
),
|
||||
id="default",
|
||||
)
|
||||
]
|
||||
prefix_cache_async_chunk_params = [
|
||||
pytest.param(
|
||||
OmniServerParams(
|
||||
model=_MODEL,
|
||||
stage_config_path=_CI_DEPLOY,
|
||||
use_stage_cli=True,
|
||||
server_args=["--async-chunk", *_PREFIX_CACHE_SERVER_ARGS],
|
||||
),
|
||||
id="prefix_cache_async_chunk",
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
def get_system_prompt():
|
||||
@@ -245,6 +256,83 @@ def test_thinker_prefix_caching_audio_output(omni_server, online_client) -> None
|
||||
_run_prefix_cache_check(online_client, request_config)
|
||||
|
||||
|
||||
def _assert_omni_payload_complete(resp) -> None:
|
||||
"""Async-chunk + prefix-cache must still deliver a full downstream payload."""
|
||||
assert resp.success
|
||||
assert resp.text_content
|
||||
has_audio = bool(resp.audio_bytes) or bool(resp.audio_data)
|
||||
assert has_audio
|
||||
|
||||
|
||||
@pytest.mark.advanced_model
|
||||
@pytest.mark.core_model
|
||||
@pytest.mark.omni
|
||||
@hardware_test(res={"cuda": "H100", "rocm": "MI325"}, num_cards=2)
|
||||
@pytest.mark.parametrize("omni_server", prefix_cache_async_chunk_params, indirect=True)
|
||||
def test_thinker_prefix_caching_async_chunk_identical(omni_server, online_client) -> None:
|
||||
"""Production path: ``async_chunk: true`` plus thinker/talker prefix cache.
|
||||
|
||||
Two identical streaming requests. The second must report a block-aligned
|
||||
cache hit and still produce text + audio (async output builder).
|
||||
"""
|
||||
messages = dummy_messages_from_mix_data(
|
||||
system_prompt=get_system_prompt(),
|
||||
content_text=get_prompt(),
|
||||
)
|
||||
request_config = {
|
||||
"model": omni_server.model,
|
||||
"messages": messages,
|
||||
"stream": True,
|
||||
"stream_options": {"include_usage": True},
|
||||
}
|
||||
first_response, cached_response = _run_prefix_cache_check(online_client, request_config)
|
||||
_assert_omni_payload_complete(first_response)
|
||||
_assert_omni_payload_complete(cached_response)
|
||||
|
||||
|
||||
@pytest.mark.advanced_model
|
||||
@pytest.mark.core_model
|
||||
@pytest.mark.omni
|
||||
@hardware_test(res={"cuda": "H100", "rocm": "MI325"}, num_cards=2)
|
||||
@pytest.mark.parametrize("omni_server", prefix_cache_async_chunk_params, indirect=True)
|
||||
def test_thinker_prefix_caching_async_chunk_shared_image_prefix(omni_server, online_client) -> None:
|
||||
"""Shared image / system prefix, different user text — not a full-prompt replay.
|
||||
|
||||
The second request must still hit cached tokens (block-aligned, less than
|
||||
its prompt). A merge that only works when ``hit_upto == prompt_len`` would
|
||||
fail this.
|
||||
"""
|
||||
image_data_url = f"data:image/jpeg;base64,{generate_synthetic_image(224, 224)['base64']}"
|
||||
first_messages = dummy_messages_from_mix_data(
|
||||
system_prompt=get_system_prompt(),
|
||||
image_data_url=image_data_url,
|
||||
content_text=get_prompt("text_image"),
|
||||
)
|
||||
second_messages = dummy_messages_from_mix_data(
|
||||
system_prompt=get_system_prompt(),
|
||||
image_data_url=image_data_url,
|
||||
content_text="How many squares are in this image? Answer in 20 words.",
|
||||
)
|
||||
first_cfg = {
|
||||
"model": omni_server.model,
|
||||
"messages": first_messages,
|
||||
"stream": True,
|
||||
"stream_options": {"include_usage": True},
|
||||
"modalities": ["text"],
|
||||
}
|
||||
second_cfg = {**first_cfg, "messages": second_messages}
|
||||
first_response = online_client.send_omni_request(first_cfg, request_num=1)[0]
|
||||
cached_response = online_client.send_omni_request(second_cfg, request_num=1)[0]
|
||||
assert first_response.success and cached_response.success
|
||||
assert first_response.text_content and cached_response.text_content
|
||||
num_cached = cached_response.cached_tokens
|
||||
num_prompt = cached_response.prompt_tokens
|
||||
assert num_cached is not None and num_prompt is not None
|
||||
assert num_cached > 0
|
||||
assert num_cached % BLOCK_SIZE == 0
|
||||
assert num_cached < num_prompt
|
||||
|
||||
|
||||
@pytest.mark.advanced_model
|
||||
@pytest.mark.core_model
|
||||
@pytest.mark.omni
|
||||
|
||||
@@ -91,7 +91,7 @@ def _assert_audio_outputs(responses: list[OmniResponse], *, expect_text: bool) -
|
||||
|
||||
@pytest.mark.full_model
|
||||
@pytest.mark.omni
|
||||
@hardware_test(res={"cuda": "H100"}, num_cards=4)
|
||||
@hardware_test(res={"cuda": ["H100", "B200"]}, num_cards=4)
|
||||
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
|
||||
def test_text_only_batch_uses_multi_replica_talker(omni_server, online_client) -> None:
|
||||
request_config = {
|
||||
@@ -108,7 +108,7 @@ def test_text_only_batch_uses_multi_replica_talker(omni_server, online_client) -
|
||||
|
||||
@pytest.mark.full_model
|
||||
@pytest.mark.omni
|
||||
@hardware_test(res={"cuda": "H100"}, num_cards=4)
|
||||
@hardware_test(res={"cuda": ["H100", "B200"]}, num_cards=4)
|
||||
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
|
||||
def test_text_to_audio_stream_batch_uses_multi_replica_vocoder(omni_server, online_client) -> None:
|
||||
request_config = {
|
||||
@@ -125,7 +125,7 @@ def test_text_to_audio_stream_batch_uses_multi_replica_vocoder(omni_server, onli
|
||||
|
||||
@pytest.mark.full_model
|
||||
@pytest.mark.omni
|
||||
@hardware_test(res={"cuda": "H100"}, num_cards=4)
|
||||
@hardware_test(res={"cuda": ["H100", "B200"]}, num_cards=4)
|
||||
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
|
||||
def test_mixed_modal_stream_batch_generates_text_and_audio(omni_server, online_client) -> None:
|
||||
request_config = {
|
||||
|
||||
@@ -12,6 +12,7 @@ import os
|
||||
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
|
||||
|
||||
import pytest
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
from tests.helpers.mark import hardware_test
|
||||
from tests.helpers.media import get_asset_path
|
||||
@@ -50,7 +51,16 @@ tts_server_params = [
|
||||
server_args=["--trust-remote-code"],
|
||||
),
|
||||
id="async_chunk",
|
||||
)
|
||||
),
|
||||
pytest.param(
|
||||
OmniServerParams(
|
||||
model=MODEL,
|
||||
stage_config_path=get_deploy_config_path("qwen3_tts_mrv2.yaml"),
|
||||
server_args=["--trust-remote-code"],
|
||||
),
|
||||
id="async_chunk_mrv2",
|
||||
marks=pytest.mark.skipif(not current_platform.is_cuda(), reason="MRV2 validation is CUDA-only"),
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -69,7 +69,7 @@ tts_no_async_chunk_server_params = [
|
||||
DEFAULT_AUDIO_SPEECH_TIMEOUT_S = 180.0
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@hardware_test(res={"cuda": ["L4", "B200"]}, num_cards=1)
|
||||
@pytest.mark.parametrize(
|
||||
"omni_server",
|
||||
tts_async_chunk_server_params + tts_no_async_chunk_server_params,
|
||||
@@ -99,7 +99,7 @@ def test_voice_clone_streaming_001(omni_server, online_client) -> None:
|
||||
online_client.send_audio_speech_request(request_config, request_num=get_max_batch_size("few"))
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@hardware_test(res={"cuda": ["L4", "B200"]}, num_cards=1)
|
||||
@pytest.mark.parametrize(
|
||||
"omni_server",
|
||||
tts_async_chunk_server_params + tts_no_async_chunk_server_params,
|
||||
@@ -127,7 +127,7 @@ def test_response_format_001(omni_server, online_client) -> None:
|
||||
online_client.send_audio_speech_request(request_config)
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@hardware_test(res={"cuda": ["L4", "B200"]}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_async_chunk_server_params, indirect=True)
|
||||
def test_xvector_then_icl_same_ref_audio_keeps_engine_alive(omni_server, online_client) -> None:
|
||||
"""Regression for #5049: x-vector-only then ICL on the same ``ref_audio``.
|
||||
|
||||
@@ -60,7 +60,7 @@ tts_server_params = [
|
||||
]
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@hardware_test(res={"cuda": ["L4", "B200"]}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
|
||||
def test_voice_001(omni_server, online_client) -> None:
|
||||
"""
|
||||
@@ -92,7 +92,7 @@ def test_voice_001(omni_server, online_client) -> None:
|
||||
raise
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@hardware_test(res={"cuda": ["L4", "B200"]}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
|
||||
def test_voice_002(omni_server, online_client) -> None:
|
||||
"""
|
||||
@@ -115,7 +115,7 @@ def test_voice_002(omni_server, online_client) -> None:
|
||||
online_client.send_audio_speech_request(request_config)
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@hardware_test(res={"cuda": ["L4", "B200"]}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
|
||||
def test_voice_003(omni_server, online_client) -> None:
|
||||
"""
|
||||
@@ -138,7 +138,7 @@ def test_voice_003(omni_server, online_client) -> None:
|
||||
online_client.send_audio_speech_request(request_config)
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@hardware_test(res={"cuda": ["L4", "B200"]}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
|
||||
def test_sample_rate_001(omni_server, online_client) -> None:
|
||||
"""The speech API resamples Qwen3-TTS output from native 24 kHz to 8 kHz."""
|
||||
@@ -155,7 +155,7 @@ def test_sample_rate_001(omni_server, online_client) -> None:
|
||||
online_client.send_audio_speech_request(request_config)
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@hardware_test(res={"cuda": ["L4", "B200"]}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
|
||||
def test_language_001(omni_server, online_client) -> None:
|
||||
"""
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import base64
|
||||
import json
|
||||
|
||||
import pytest
|
||||
from websockets.sync.client import connect
|
||||
|
||||
from tests.helpers.mark import hardware_test
|
||||
from tests.helpers.runtime import OmniServerParams
|
||||
from tests.helpers.stage_config import get_deploy_config_path, modify_stage_config
|
||||
|
||||
pytestmark = [pytest.mark.slow, pytest.mark.tts]
|
||||
|
||||
_DEPLOY = modify_stage_config(
|
||||
get_deploy_config_path("qwen3_tts.yaml"),
|
||||
updates={
|
||||
"stages": {
|
||||
0: {
|
||||
"max_num_seqs": 4,
|
||||
"max_num_batched_tokens": 2048,
|
||||
"max_model_len": 2048,
|
||||
"gpu_memory_utilization": 0.45,
|
||||
"compilation_config.cudagraph_capture_sizes": [1, 2, 4],
|
||||
"default_sampling_params.max_tokens": 256,
|
||||
},
|
||||
1: {
|
||||
"max_num_seqs": 4,
|
||||
"max_num_batched_tokens": 4096,
|
||||
"max_model_len": 8192,
|
||||
"gpu_memory_utilization": 0.15,
|
||||
},
|
||||
}
|
||||
},
|
||||
)
|
||||
_PARAMS = [
|
||||
OmniServerParams(
|
||||
model="Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice",
|
||||
stage_config_path=_DEPLOY,
|
||||
server_args=[
|
||||
"--trust-remote-code",
|
||||
"--forced-aligner",
|
||||
"Qwen/Qwen3-ForcedAligner-0.6B",
|
||||
"--kv-cache-memory-bytes",
|
||||
str(512 * 1024**2),
|
||||
"--max-num-seqs",
|
||||
"4",
|
||||
"--max-num-batched-tokens",
|
||||
"2048",
|
||||
],
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", _PARAMS, indirect=True)
|
||||
def test_async_chunk_word_timestamps(omni_server, online_client):
|
||||
online_client.send_audio_speech_request(
|
||||
{
|
||||
"model": omni_server.model,
|
||||
"input": "The weather is nice today, perfect for a walk in the park.",
|
||||
"voice": "vivian",
|
||||
"language": "English",
|
||||
"word_timestamps": True,
|
||||
"response_format": "wav",
|
||||
"min_audio_bytes": 40_000,
|
||||
"timeout": 120,
|
||||
},
|
||||
request_num=2,
|
||||
)
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", _PARAMS, indirect=True)
|
||||
def test_async_chunk_speech_without_timestamps(omni_server, online_client):
|
||||
online_client.send_audio_speech_request(
|
||||
{
|
||||
"model": omni_server.model,
|
||||
"input": "The weather is nice today, perfect for a walk in the park.",
|
||||
"voice": "vivian",
|
||||
"language": "English",
|
||||
"stream": True,
|
||||
"stream_format": "audio",
|
||||
"response_format": "wav",
|
||||
"min_audio_bytes": 40_000,
|
||||
"timeout": 120,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", _PARAMS, indirect=True)
|
||||
def test_async_chunk_streaming_word_timestamps(omni_server):
|
||||
text = "The weather is nice today, perfect for a walk in the park."
|
||||
chunks = []
|
||||
timestamps = None
|
||||
with connect(f"ws://{omni_server.host}:{omni_server.port}/v1/audio/speech/stream") as ws:
|
||||
ws.send(
|
||||
json.dumps(
|
||||
{
|
||||
"type": "session.config",
|
||||
"voice": "vivian",
|
||||
"language": "English",
|
||||
"stream_audio": True,
|
||||
"response_format": "pcm",
|
||||
"word_timestamps": True,
|
||||
}
|
||||
)
|
||||
)
|
||||
ws.send(json.dumps({"type": "input.text", "text": text}))
|
||||
ws.send(json.dumps({"type": "input.done"}))
|
||||
while True:
|
||||
message = json.loads(ws.recv(timeout=120))
|
||||
assert message["type"] != "error", message
|
||||
if message["type"] == "audio.chunk":
|
||||
if message["audio_b64"]:
|
||||
chunks.append(base64.b64decode(message["audio_b64"]))
|
||||
if message["timestamps"] is not None:
|
||||
timestamps = message["timestamps"]
|
||||
sample_rate = message["sample_rate"]
|
||||
elif message["type"] == "audio.done":
|
||||
assert not message["error"], message
|
||||
assert message["total_bytes"] == sum(map(len, chunks))
|
||||
elif message["type"] == "session.done":
|
||||
break
|
||||
|
||||
assert len(chunks) > 1
|
||||
assert timestamps
|
||||
assert len(timestamps) == len(text.split())
|
||||
duration_ms = sum(map(len, chunks)) / (2 * sample_rate) * 1000
|
||||
final_chunk_ms = len(chunks[-1]) / (2 * sample_rate) * 1000
|
||||
assert timestamps[-1]["end_ms"] > max(duration_ms / 2, final_chunk_ms)
|
||||
previous_end = 0
|
||||
for timestamp in timestamps:
|
||||
assert previous_end <= timestamp["start_ms"] <= timestamp["end_ms"] <= duration_ms + 1
|
||||
previous_end = timestamp["end_ms"]
|
||||
@@ -21,8 +21,8 @@ pytestmark = [pytest.mark.diffusion, pytest.mark.full_model]
|
||||
|
||||
T2I_PROMPT = "A photo of a cat sitting on a laptop keyboard, digital art style."
|
||||
NEGATIVE_PROMPT = "blurry, low quality"
|
||||
SINGLE_CARD_FEATURE_MARKS = hardware_marks(res={"cuda": "H100"})
|
||||
PARALLEL_FEATURE_MARKS = hardware_marks(res={"cuda": "H100"}, num_cards=2)
|
||||
SINGLE_CARD_FEATURE_MARKS = hardware_marks(res={"cuda": ["H100", "B200"]})
|
||||
PARALLEL_FEATURE_MARKS = hardware_marks(res={"cuda": ["H100", "B200"]}, num_cards=2)
|
||||
|
||||
MODEL_IMAGE = "Qwen/Qwen-Image"
|
||||
MODEL_2512 = "Qwen/Qwen-Image-2512"
|
||||
|
||||
@@ -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
|
||||
|
||||
"""
|
||||
Online serving smoke for SANA-WM image-to-video (first-frame I2V via ``/v1/videos``).
|
||||
|
||||
@@ -18,7 +18,7 @@ from tests.helpers.mark import hardware_test
|
||||
from tests.helpers.runtime import OmniServerParams
|
||||
from tests.helpers.stage_config import get_deploy_config_path
|
||||
|
||||
MODEL = "openbmb/VoxCPM2"
|
||||
MODEL = os.environ.get("VOXCPM2_MODEL", "openbmb/VoxCPM2")
|
||||
DEFAULT_AUDIO_SPEECH_TIMEOUT_S = 300.0
|
||||
MAX_CONCURRENT = 4
|
||||
|
||||
@@ -48,7 +48,7 @@ tts_server_params = [
|
||||
|
||||
@pytest.mark.slow
|
||||
@pytest.mark.tts
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@hardware_test(res={"cuda": "L4", "npu": "A2"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
|
||||
def test_text_to_audio_001(omni_server, online_client) -> None:
|
||||
"""
|
||||
@@ -73,7 +73,7 @@ def test_text_to_audio_001(omni_server, online_client) -> None:
|
||||
|
||||
@pytest.mark.slow
|
||||
@pytest.mark.tts
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@hardware_test(res={"cuda": "L4", "npu": "A2"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
|
||||
def test_text_to_audio_002(omni_server, online_client) -> None:
|
||||
"""
|
||||
|
||||
@@ -20,7 +20,7 @@ pytestmark = [pytest.mark.slow, pytest.mark.tts]
|
||||
|
||||
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
|
||||
|
||||
MODEL = "openbmb/VoxCPM2"
|
||||
MODEL = os.environ.get("VOXCPM2_MODEL", "openbmb/VoxCPM2")
|
||||
DEFAULT_AUDIO_SPEECH_TIMEOUT_S = 300.0
|
||||
_MIN_AUDIO_BYTES = 40_000
|
||||
MAX_CONCURRENT = 4
|
||||
@@ -47,7 +47,7 @@ tts_server_params = [
|
||||
]
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@hardware_test(res={"cuda": "L4", "npu": "A2"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
|
||||
def test_voice_clone_streaming_001(omni_server, online_client) -> None:
|
||||
"""
|
||||
@@ -72,7 +72,7 @@ def test_voice_clone_streaming_001(omni_server, online_client) -> None:
|
||||
online_client.send_audio_speech_request(request_config, request_num=MAX_CONCURRENT)
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@hardware_test(res={"cuda": "L4", "npu": "A2"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
|
||||
def test_response_format_001(omni_server, online_client) -> None:
|
||||
"""
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Serve a native VoxCPM2 adapter through the speech API."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
import yaml
|
||||
from huggingface_hub import hf_hub_download
|
||||
from safetensors import safe_open
|
||||
from safetensors.torch import save_file
|
||||
|
||||
from tests.helpers.fixtures.runtime import omni_fixture_lock
|
||||
from tests.helpers.mark import hardware_test
|
||||
from tests.helpers.runtime import OmniServerParams, get_model_prefix, iter_omni_server
|
||||
from tests.helpers.stage_config import get_deploy_config_path
|
||||
|
||||
pytestmark = [pytest.mark.slow, pytest.mark.tts]
|
||||
MODEL = "openbmb/VoxCPM2"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def omni_server(request, run_level, tmp_path_factory):
|
||||
directory = tmp_path_factory.mktemp("voxcpm2-lora")
|
||||
model = get_model_prefix() + MODEL
|
||||
weights = Path(model) / "model.safetensors"
|
||||
if not weights.is_file():
|
||||
weights = Path(hf_hub_download(MODEL, "model.safetensors"))
|
||||
projections = ["enc_to_lm_proj", "lm_to_dit_proj", "res_to_dit_proj", "fusion_concat_proj"]
|
||||
generator = torch.Generator().manual_seed(42)
|
||||
tensors = {}
|
||||
with safe_open(weights, framework="pt", device="cpu") as checkpoint:
|
||||
for key in checkpoint.keys():
|
||||
if not key.endswith(".weight"):
|
||||
continue
|
||||
name = key.removesuffix(".weight")
|
||||
attention = name.startswith(("base_lm.", "residual_lm.", "feat_decoder.estimator.")) and name.rsplit(
|
||||
".", 1
|
||||
)[-1] in {"q_proj", "k_proj", "v_proj", "o_proj"}
|
||||
if not attention and name not in projections:
|
||||
continue
|
||||
out_features, in_features = checkpoint.get_slice(key).get_shape()
|
||||
# Small nonzero deltas exercise every group without retraining a voice.
|
||||
tensors[f"{name}.lora_A"] = torch.randn(2, in_features, generator=generator) * 0.001
|
||||
tensors[f"{name}.lora_B"] = torch.randn(out_features, 2, generator=generator) * 0.001
|
||||
assert tensors
|
||||
save_file(tensors, str(directory / "lora_weights.safetensors"))
|
||||
(directory / "lora_config.json").write_text(
|
||||
json.dumps({"lora_config": {"r": 2, "alpha": 2, "enable_lm": True, "enable_dit": True, "enable_proj": True}})
|
||||
)
|
||||
|
||||
with open(get_deploy_config_path("voxcpm2.yaml")) as stream:
|
||||
config = yaml.safe_load(stream)
|
||||
stage = config["stages"][0]
|
||||
stage.update(
|
||||
max_num_seqs=4,
|
||||
kv_cache_memory_bytes=1024**3,
|
||||
gpu_memory_utilization=0.65,
|
||||
max_model_len=2048,
|
||||
max_num_batched_tokens=2048,
|
||||
)
|
||||
stage["default_sampling_params"]["max_tokens"] = 256
|
||||
runtime = stage["engine_extras"]["hf_overrides"]["voxcpm2_runtime_config"]
|
||||
runtime.update(startup_lora_path=str(directory), unified_decode_graph_max_batch_size=4)
|
||||
deploy_path = directory / "deploy.yaml"
|
||||
deploy_path.write_text(yaml.safe_dump(config))
|
||||
request.param = OmniServerParams(
|
||||
model=MODEL,
|
||||
stage_config_path=str(deploy_path),
|
||||
server_args=["--trust-remote-code", "--disable-log-stats"],
|
||||
)
|
||||
yield from iter_omni_server(request, run_level, omni_fixture_lock)
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
def test_startup_lora_concurrent_speech(omni_server, online_client):
|
||||
online_client.send_audio_speech_request(
|
||||
{
|
||||
"model": omni_server.model,
|
||||
"input": "The weather is nice today, perfect for a walk in the park.",
|
||||
"voice": "default",
|
||||
"response_format": "wav",
|
||||
"stream": False,
|
||||
"timeout": 300,
|
||||
"min_audio_bytes": 40_000,
|
||||
},
|
||||
request_num=4,
|
||||
)
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
def test_startup_lora_streaming_speech(omni_server, online_client):
|
||||
online_client.send_audio_speech_request(
|
||||
{
|
||||
"model": omni_server.model,
|
||||
"input": "The weather is nice today, perfect for a walk in the park.",
|
||||
"voice": "default",
|
||||
"response_format": "wav",
|
||||
"stream": True,
|
||||
"stream_format": "audio",
|
||||
"timeout": 300,
|
||||
"min_audio_bytes": 40_000,
|
||||
}
|
||||
)
|
||||
@@ -12,11 +12,14 @@ import os
|
||||
os.environ.setdefault("VLLM_WORKER_MULTIPROC_METHOD", "spawn")
|
||||
|
||||
import pytest
|
||||
from openai import BadRequestError as OpenAIBadRequestError
|
||||
|
||||
from tests.helpers.mark import hardware_test
|
||||
from tests.helpers.media import generate_synthetic_audio
|
||||
from tests.helpers.runtime import OmniServerParams
|
||||
from tests.helpers.stage_config import get_deploy_config_path
|
||||
|
||||
# Note this model is the public checkpoint without the encoder weights required for voice cloning
|
||||
MODEL = "mistralai/Voxtral-4B-TTS-2603"
|
||||
STAGE_CONFIG = get_deploy_config_path("voxtral_tts.yaml")
|
||||
EXTRA_ARGS = ["--trust-remote-code", "--enforce-eager", "--disable-log-stats"]
|
||||
@@ -173,3 +176,21 @@ def test_speech_batches(omni_server, online_client) -> None:
|
||||
"timeout": 120.0,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
def test_speech_ref_audio(omni_server, online_client) -> None:
|
||||
"""Test ref_audio failure is handled as a BadRequest instead of a RuntimeError"""
|
||||
audio_data = f"data:audio/wav;base64,{generate_synthetic_audio(5, 1)['base64']}"
|
||||
with pytest.raises(OpenAIBadRequestError) as exc_info:
|
||||
online_client.send_audio_speech_request(
|
||||
{
|
||||
"model": omni_server.model,
|
||||
"input": "how are you",
|
||||
"ref_audio": audio_data,
|
||||
"language": "English",
|
||||
"response_format": "wav",
|
||||
}
|
||||
)
|
||||
|
||||
assert exc_info.value.status_code == 400
|
||||
@@ -30,8 +30,8 @@ PROMPT = "Two anthropomorphic cats in comfy boxing gear and bright gloves fight
|
||||
NEGATIVE_PROMPT = "low quality, blurry, distorted face, extra limbs, bad anatomy, watermark, logo, text, ugly, deformed, mutated, jpeg artifacts"
|
||||
|
||||
# CUDA marks (original matrix, unchanged)
|
||||
CUDA_SINGLE_CARD_MARKS = hardware_marks(res={"cuda": "H100"})
|
||||
CUDA_PARALLEL_MARKS = hardware_marks(res={"cuda": "H100"}, num_cards=2)
|
||||
CUDA_SINGLE_CARD_MARKS = hardware_marks(res={"cuda": ["H100", "B200"]})
|
||||
CUDA_PARALLEL_MARKS = hardware_marks(res={"cuda": ["H100", "B200"]}, num_cards=2)
|
||||
|
||||
# NPU marks
|
||||
NPU_TWO_CARD_MARKS = hardware_marks(res={"npu": "A2"}, num_cards=2)
|
||||
|
||||
@@ -19,7 +19,7 @@ import pytest
|
||||
from tests.helpers.mark import hardware_marks
|
||||
from tests.helpers.runtime import OmniServer, OmniServerParams, OnlineOmniClient
|
||||
|
||||
pytestmark = [pytest.mark.diffusion, pytest.mark.full_model]
|
||||
pytestmark = [pytest.mark.diffusion, pytest.mark.slow]
|
||||
|
||||
MODEL = "Tongyi-MAI/Z-Image-Turbo"
|
||||
PROMPT = "A high-detail studio photo of an orange tabby cat sitting on a laptop keyboard."
|
||||
|
||||
Reference in new issue
Block a user