[Feature] Speech batch entrypoint (#1701)

Signed-off-by: dsinghvi <divyanshsinghvi@gmail.com>
Signed-off-by: Divyansh Singhvi <divyanshsinghvi@gmail.com>
This commit is contained in:
dsinghvi authored and GitHub committed 2026-03-24 10:52:01 -04:00
1 parent 7f112041da
commit e7e05a55cf
8 files changed
+1094 -8

No files matched your search

@@ -0,0 +1,433 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
E2E tests for the /v1/audio/speech/batch endpoint.
Validates bulk synthesis via the batch API with actual model inference.
"""
import os
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
os.environ["VLLM_TEST_CLEAN_GPU_MEMORY"] = "0"
import base64
import shutil
import struct
import tempfile
import time
from pathlib import Path
import httpx
import pytest
import yaml
from tests.conftest import (
OmniServer,
convert_audio_file_to_text,
cosine_similarity_text,
)
from tests.utils import hardware_test
MODEL = "Qwen/Qwen3-TTS-12Hz-0.6B-CustomVoice"
def get_stage_config(name: str = "qwen3_tts.yaml"):
return str(Path(__file__).parent.parent.parent.parent / "vllm_omni" / "model_executor" / "stage_configs" / name)
@pytest.fixture(scope="module")
def omni_server():
"""Start vLLM-Omni server with CustomVoice model."""
stage_config_path = get_stage_config()
with OmniServer(
MODEL,
[
"--stage-configs-path",
stage_config_path,
"--stage-init-timeout",
"120",
"--trust-remote-code",
"--enforce-eager",
"--disable-log-stats",
],
) as server:
yield server
def make_batch_request(
host: str,
port: int,
items: list[dict],
voice: str | None = "vivian",
language: str | None = "English",
response_format: str = "wav",
timeout: float = 300.0,
**kwargs,
) -> httpx.Response:
"""Make a request to the /v1/audio/speech/batch endpoint."""
url = f"http://{host}:{port}/v1/audio/speech/batch"
payload: dict = {
"items": items,
"response_format": response_format,
}
if voice is not None:
payload["voice"] = voice
if language is not None:
payload["language"] = language
payload.update(kwargs)
with httpx.Client(timeout=timeout) as client:
return client.post(url, json=payload)
def verify_wav_bytes(audio_bytes: bytes) -> bool:
"""Verify decoded audio bytes form a valid WAV."""
if len(audio_bytes) < 44:
return False
return audio_bytes[:4] == b"RIFF" and audio_bytes[8:12] == b"WAVE"
def assert_not_silence(pcm_bytes: bytes):
"""Assert PCM16 samples are not all identical."""
samples = struct.unpack(f"<{len(pcm_bytes) // 2}h", pcm_bytes)
unique = set(samples)
assert len(unique) > 1, f"All-silence: {len(samples)} samples, unique={unique}"
MIN_AUDIO_BYTES = 10000
class TestSpeechBatchE2E:
"""E2E tests for /v1/audio/speech/batch endpoint."""
@pytest.mark.core_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100"}, num_cards=1)
def test_batch_basic_two_items(self, omni_server) -> None:
"""Batch with two items returns two successful base64-encoded results."""
items = [
{"input": "Hello, how are you today?"},
{"input": "The weather is nice outside."},
]
response = make_batch_request(
host=omni_server.host,
port=omni_server.port,
items=items,
)
assert response.status_code == 200, f"Request failed: {response.text}"
data = response.json()
assert data["total"] == 2
assert data["succeeded"] == 2
assert data["failed"] == 0
assert data["id"].startswith("speech-batch-")
assert len(data["results"]) == 2
for i, result in enumerate(data["results"]):
assert result["index"] == i
assert result["status"] == "success"
assert result["audio_data"] is not None
assert result["error"] is None
audio_bytes = base64.b64decode(result["audio_data"])
assert verify_wav_bytes(audio_bytes), f"Item {i}: invalid WAV"
assert len(audio_bytes) > MIN_AUDIO_BYTES, f"Item {i}: audio too small ({len(audio_bytes)} bytes)"
@pytest.mark.core_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100"}, num_cards=1)
def test_batch_single_item(self, omni_server) -> None:
"""Batch with a single item works correctly."""
items = [{"input": "Single item batch test."}]
response = make_batch_request(
host=omni_server.host,
port=omni_server.port,
items=items,
)
assert response.status_code == 200, f"Request failed: {response.text}"
data = response.json()
assert data["total"] == 1
assert data["succeeded"] == 1
assert data["failed"] == 0
assert len(data["results"]) == 1
assert data["results"][0]["status"] == "success"
@pytest.mark.core_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100"}, num_cards=1)
def test_batch_per_item_voice_override(self, omni_server) -> None:
"""Per-item voice overrides the batch-level default."""
items = [
{"input": "First item with default voice."},
{"input": "Second item with ryan voice.", "voice": "ryan"},
]
response = make_batch_request(
host=omni_server.host,
port=omni_server.port,
items=items,
voice="vivian",
)
assert response.status_code == 200, f"Request failed: {response.text}"
data = response.json()
assert data["total"] == 2
assert data["succeeded"] == 2
# Both items should produce valid audio
for result in data["results"]:
assert result["status"] == "success"
audio_bytes = base64.b64decode(result["audio_data"])
assert verify_wav_bytes(audio_bytes)
@pytest.mark.core_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100"}, num_cards=1)
def test_batch_multiple_languages(self, omni_server) -> None:
"""Batch items with different languages per item."""
items = [
{"input": "Hello, nice to meet you.", "language": "English"},
{"input": "你好,很高兴认识你。", "language": "Chinese"},
]
response = make_batch_request(
host=omni_server.host,
port=omni_server.port,
items=items,
)
assert response.status_code == 200, f"Request failed: {response.text}"
data = response.json()
assert data["succeeded"] == 2
for result in data["results"]:
assert result["status"] == "success"
audio_bytes = base64.b64decode(result["audio_data"])
assert len(audio_bytes) > MIN_AUDIO_BYTES
@pytest.mark.core_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100"}, num_cards=1)
def test_batch_whisper_transcription(self, omni_server) -> None:
"""Whisper transcription of batch output matches input text."""
input_text = "Good morning, welcome to the speech synthesis test."
items = [{"input": input_text}]
response = make_batch_request(
host=omni_server.host,
port=omni_server.port,
items=items,
)
assert response.status_code == 200, f"Request failed: {response.text}"
data = response.json()
assert data["succeeded"] == 1
audio_bytes = base64.b64decode(data["results"][0]["audio_data"])
assert verify_wav_bytes(audio_bytes)
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as f:
f.write(audio_bytes)
wav_path = f.name
try:
transcript = convert_audio_file_to_text(wav_path)
print(f"Whisper transcript: {transcript}")
assert len(transcript.strip()) > 0, "Empty transcript — likely silence"
similarity = cosine_similarity_text(transcript.lower(), input_text.lower())
print(f"Cosine similarity: {similarity:.3f}")
assert similarity > 0.7, f"Transcript mismatch: similarity={similarity:.2f}, transcript='{transcript}'"
finally:
os.unlink(wav_path)
@pytest.mark.core_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100"}, num_cards=1)
def test_batch_result_indices_ordered(self, omni_server) -> None:
"""Result indices match the input item order."""
items = [
{"input": "First sentence."},
{"input": "Second sentence."},
{"input": "Third sentence."},
]
response = make_batch_request(
host=omni_server.host,
port=omni_server.port,
items=items,
)
assert response.status_code == 200, f"Request failed: {response.text}"
data = response.json()
indices = [r["index"] for r in data["results"]]
assert indices == [0, 1, 2]
class TestSpeechBatchValidation:
"""Validation / error-handling tests for the batch endpoint."""
@pytest.mark.core_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100"}, num_cards=1)
def test_batch_empty_items_rejected(self, omni_server) -> None:
"""Empty items list returns a 4xx error."""
url = f"http://{omni_server.host}:{omni_server.port}/v1/audio/speech/batch"
payload = {"items": [], "voice": "vivian"}
with httpx.Client(timeout=30.0) as client:
response = client.post(url, json=payload)
assert response.status_code in (400, 422)
@pytest.mark.core_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100"}, num_cards=1)
def test_batch_exceeds_max_items(self, omni_server) -> None:
"""Batch exceeding 32 items returns 400 error."""
items = [{"input": f"Item {i}"} for i in range(33)]
response = make_batch_request(
host=omni_server.host,
port=omni_server.port,
items=items,
)
assert response.status_code == 400
def _make_batch2_stage_config() -> str:
"""Create a temporary stage config with max_batch_size=2 for both stages."""
src = Path(get_stage_config("qwen3_tts_batch.yaml"))
with open(src) as f:
cfg = yaml.safe_load(f)
for stage in cfg["stage_args"]:
stage["runtime"]["max_batch_size"] = 2
tmp_dir = tempfile.mkdtemp(prefix="tts_batch2_")
dst = Path(tmp_dir) / "qwen3_tts_batch2.yaml"
with open(dst, "w") as f:
yaml.dump(cfg, f)
return str(dst), tmp_dir
def make_single_request(
host: str,
port: int,
text: str,
voice: str = "vivian",
language: str = "English",
timeout: float = 300.0,
) -> httpx.Response:
"""Make a request to the single /v1/audio/speech endpoint."""
url = f"http://{host}:{port}/v1/audio/speech"
payload = {"input": text, "voice": voice, "language": language}
with httpx.Client(timeout=timeout) as client:
return client.post(url, json=payload)
@pytest.fixture(scope="module")
def omni_server_batch2():
"""Start vLLM-Omni server with max_batch_size=2 config."""
config_path, tmp_dir = _make_batch2_stage_config()
with OmniServer(
MODEL,
[
"--stage-configs-path",
config_path,
"--stage-init-timeout",
"120",
"--trust-remote-code",
"--enforce-eager",
"--disable-log-stats",
],
) as server:
yield server
shutil.rmtree(tmp_dir, ignore_errors=True)
class TestSpeechBatchSize2:
"""E2E tests with max_batch_size=2 to verify true batched inference."""
@pytest.mark.core_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100"}, num_cards=1)
def test_batch2_produces_valid_audio(self, omni_server_batch2) -> None:
"""Batch of 2 items with batched engine produces valid audio."""
items = [
{"input": "Hello, this is the first sentence."},
{"input": "And this is the second sentence."},
]
response = make_batch_request(
host=omni_server_batch2.host,
port=omni_server_batch2.port,
items=items,
)
assert response.status_code == 200, f"Request failed: {response.text}"
data = response.json()
assert data["total"] == 2
assert data["succeeded"] == 2
assert data["failed"] == 0
# Save audio files for inspection
output_dir = Path(tempfile.mkdtemp(prefix="tts_batch2_output_"))
for result in data["results"]:
assert result["status"] == "success"
audio_bytes = base64.b64decode(result["audio_data"])
assert verify_wav_bytes(audio_bytes), f"Item {result['index']}: invalid WAV"
assert len(audio_bytes) > MIN_AUDIO_BYTES
wav_path = output_dir / f"batch_item_{result['index']}.wav"
wav_path.write_bytes(audio_bytes)
print(f" Item {result['index']}: {len(audio_bytes)} bytes -> {wav_path}")
print(f"\nBatch audio saved to: {output_dir}")
@pytest.mark.core_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100"}, num_cards=1)
def test_batch2_vs_sequential_timing(self, omni_server_batch2) -> None:
"""Compare batch-of-2 vs 2 sequential single requests.
With max_batch_size=2 the engine can process both items
concurrently, so the batch call should be faster than two
sequential single calls (or at least comparable).
"""
text_a = "The quick brown fox jumps over the lazy dog."
text_b = "A journey of a thousand miles begins with a single step."
host = omni_server_batch2.host
port = omni_server_batch2.port
# --- Sequential: 2 single /v1/audio/speech calls ---
t0 = time.perf_counter()
resp_a = make_single_request(host, port, text_a)
resp_b = make_single_request(host, port, text_b)
sequential_time = time.perf_counter() - t0
assert resp_a.status_code == 200, f"Single A failed: {resp_a.text}"
assert resp_b.status_code == 200, f"Single B failed: {resp_b.text}"
# --- Batch: 1 /v1/audio/speech/batch call with 2 items ---
items = [{"input": text_a}, {"input": text_b}]
t0 = time.perf_counter()
resp_batch = make_batch_request(host, port, items)
batch_time = time.perf_counter() - t0
assert resp_batch.status_code == 200, f"Batch failed: {resp_batch.text}"
batch_data = resp_batch.json()
assert batch_data["succeeded"] == 2
# Verify both produced valid audio
for result in batch_data["results"]:
audio_bytes = base64.b64decode(result["audio_data"])
assert verify_wav_bytes(audio_bytes)
assert len(audio_bytes) > MIN_AUDIO_BYTES
print(f"\n Sequential (2 singles): {sequential_time:.2f}s")
print(f" Batch (2 items): {batch_time:.2f}s")
print(f" Speedup: {sequential_time / batch_time:.2f}x")
@@ -20,7 +20,12 @@ from vllm.entrypoints.openai.engine.protocol import ErrorInfo, ErrorResponse
from vllm_omni.entrypoints.openai import api_server as api_server_module
from vllm_omni.entrypoints.openai.audio_utils_mixin import AudioMixin
from vllm_omni.entrypoints.openai.protocol.audio import CreateAudio, OpenAICreateSpeechRequest
from vllm_omni.entrypoints.openai.protocol.audio import (
BatchSpeechRequest,
CreateAudio,
OpenAICreateSpeechRequest,
SpeechBatchItem,
)
from vllm_omni.entrypoints.openai.serving_speech import (
OmniOpenAIServingSpeech,
_create_wav_header,
@@ -181,6 +186,7 @@ def test_app(mocker: MockerFixture):
mock_engine_client.generate = mocker.MagicMock(side_effect=mock_generate_fn)
mock_engine_client.default_sampling_params_list = [{}]
mock_engine_client.tts_batch_max_items = 32
# Mock models to have an is_base_model method
mock_models = mocker.MagicMock()
@@ -194,6 +200,9 @@ def test_app(mocker: MockerFixture):
request_logger=mock_request_logger,
)
# Skip TTS validation in tests (mock doesn't set up supported_speakers)
speech_server._validate_tts_request = mocker.MagicMock(return_value=None)
# Patch the signature of create_speech to remove 'raw_request' for FastAPI route introspection
original_create_speech = speech_server.create_speech
_ = mocker.MagicMock(side_effect=original_create_speech)
@@ -231,6 +240,7 @@ def test_app(mocker: MockerFixture):
return {"voices": speakers, "uploaded_voices": uploaded_voices}
app.add_api_route("/v1/audio/voices", list_voices, methods=["GET"])
app.add_api_route("/v1/audio/speech/batch", speech_server.create_speech_batch, methods=["POST"])
# Add upload_voice endpoint
async def upload_voice(audio_sample: UploadFile = File(...), consent: str = Form(...), name: str = Form(...)):
@@ -923,7 +933,7 @@ class TestStreamingProtocolValidation:
def test_stream_validation_errors(self):
"""stream=True requires response_format not in ('pcm', 'wav') and speed=1.0."""
with pytest.raises(ValidationError, match="requires response_format not in \\('pcm', 'wav'\\)"):
with pytest.raises(ValidationError, match="requires response_format='pcm' or 'wav'"):
OpenAICreateSpeechRequest(input="Hello", stream=True, response_format="mp3")
with pytest.raises(ValidationError, match="Speed adjustment is not supported"):
OpenAICreateSpeechRequest(input="Hello", stream=True, response_format="pcm", speed=2.0)
@@ -1028,6 +1038,139 @@ class TestStreamingResponse:
assert "audio/wav" in response.headers["content-type"]
class TestSpeechBatchAPI:
"""Tests for the /v1/audio/speech/batch endpoint."""
def test_batch_success(self, client):
"""Batch with two items should return two successful results with base64 audio."""
payload = {
"items": [
{"input": "Hello world"},
{"input": "Goodbye world"},
],
"response_format": "wav",
}
response = client.post("/v1/audio/speech/batch", json=payload)
assert response.status_code == 200
body = response.json()
assert body["total"] == 2
assert body["succeeded"] == 2
assert body["failed"] == 0
assert all(r["status"] == "success" for r in body["results"])
assert all(r["audio_data"] is not None for r in body["results"])
# Verify audio_data is valid base64
import base64
for r in body["results"]:
decoded = base64.b64decode(r["audio_data"])
assert len(decoded) > 0
def test_batch_single_item(self, client):
"""Batch with a single item should work."""
payload = {"items": [{"input": "Solo"}]}
response = client.post("/v1/audio/speech/batch", json=payload)
assert response.status_code == 200
body = response.json()
assert body["total"] == 1
assert body["succeeded"] == 1
def test_batch_empty_items_rejected(self, client):
"""Empty items list should be rejected by Pydantic validation."""
response = client.post("/v1/audio/speech/batch", json={"items": []})
assert response.status_code == 422
def test_batch_too_many_items(self, client):
"""Exceeding the batch max items limit (default 32) should be rejected."""
payload = {"items": [{"input": f"text {i}"} for i in range(33)]}
with pytest.raises(ValueError, match="exceeding the maximum"):
client.post("/v1/audio/speech/batch", json=payload)
def test_batch_max_items_allowed(self, client):
"""Exactly 32 items should be accepted."""
payload = {"items": [{"input": f"text {i}"} for i in range(32)]}
response = client.post("/v1/audio/speech/batch", json=payload)
assert response.status_code == 200
body = response.json()
assert body["total"] == 32
assert body["succeeded"] == 32
def test_batch_results_have_correct_indices(self, client):
"""Each result should have an index matching its position."""
payload = {"items": [{"input": f"text {i}"} for i in range(3)]}
response = client.post("/v1/audio/speech/batch", json=payload)
body = response.json()
indices = [r["index"] for r in body["results"]]
assert indices == [0, 1, 2]
def test_batch_response_has_id(self, client):
"""Batch response should have a unique id starting with 'speech-batch-'."""
payload = {"items": [{"input": "Hello"}]}
response = client.post("/v1/audio/speech/batch", json=payload)
body = response.json()
assert body["id"].startswith("speech-batch-")
class TestMergeBatchItem:
"""Tests for the _merge_batch_item static method."""
def test_item_override_wins(self):
"""Per-item voice should override batch-level voice."""
batch = BatchSpeechRequest(
items=[SpeechBatchItem(input="hi", voice="Ryan")],
voice="Vivian",
)
merged = OmniOpenAIServingSpeech._merge_batch_item(batch, batch.items[0])
assert merged.voice == "Ryan"
def test_batch_default_used(self):
"""Batch-level voice should be used when item doesn't specify one."""
batch = BatchSpeechRequest(
items=[SpeechBatchItem(input="hi")],
voice="Vivian",
)
merged = OmniOpenAIServingSpeech._merge_batch_item(batch, batch.items[0])
assert merged.voice == "Vivian"
def test_response_format_override(self):
"""Per-item response_format should override batch default."""
batch = BatchSpeechRequest(
items=[SpeechBatchItem(input="hi", response_format="mp3")],
response_format="wav",
)
merged = OmniOpenAIServingSpeech._merge_batch_item(batch, batch.items[0])
assert merged.response_format == "mp3"
def test_stream_always_false(self):
"""Merged requests should always have stream=False."""
batch = BatchSpeechRequest(items=[SpeechBatchItem(input="hi")])
merged = OmniOpenAIServingSpeech._merge_batch_item(batch, batch.items[0])
assert merged.stream is False
def test_all_fields_merge(self):
"""All overridable fields should merge correctly."""
batch = BatchSpeechRequest(
items=[
SpeechBatchItem(
input="hello",
voice="Ryan",
language="English",
speed=1.5,
task_type="CustomVoice",
max_new_tokens=512,
)
],
voice="Vivian",
language="Chinese",
speed=1.0,
)
merged = OmniOpenAIServingSpeech._merge_batch_item(batch, batch.items[0])
assert merged.voice == "Ryan"
assert merged.language == "English"
assert merged.speed == 1.5
assert merged.task_type == "CustomVoice"
assert merged.max_new_tokens == 512
class TestAsyncOmniSupportedTasks:
"""Test that AsyncOmni reports correct supported tasks based on output modalities."""