[New Model] Step-Audio2 (#464)
Signed-off-by: linyueqian <linyueqian@outlook.com> Signed-off-by: wuli666 <djjpro975@gmail.com> Co-authored-by: linyueqian <linyueqian@outlook.com> Co-authored-by: wuli666 <djjpro975@gmail.com>
This commit is contained in:
26 files changed
+5347
-2
No files matched your search
@@ -0,0 +1,37 @@
|
||||
# Stage config for Step-Audio2 CI tests
|
||||
# Single Thinker stage (audio/text understanding → text). ASR/text-output
|
||||
# tests don't need Token2Wav; a two-stage config would deadlock on stage-1 skip.
|
||||
|
||||
# The following config has been verified on 2x 24GB GPU (L4/RTX3090/RTX4090).
|
||||
stage_args:
|
||||
- stage_id: 0
|
||||
runtime:
|
||||
process: true
|
||||
devices: "0"
|
||||
max_batch_size: 1
|
||||
engine_args:
|
||||
model_stage: thinker
|
||||
model_arch: StepAudio2ThinkerForConditionalGeneration
|
||||
tensor_parallel_size: 1
|
||||
worker_cls: vllm_omni.worker.gpu_ar_worker.GPUARWorker
|
||||
scheduler_cls: vllm_omni.core.sched.omni_ar_scheduler.OmniARScheduler
|
||||
max_model_len: 4096
|
||||
max_num_batched_tokens: 4096
|
||||
max_num_seqs: 1
|
||||
gpu_memory_utilization: 0.8
|
||||
skip_mm_profiling: true
|
||||
enforce_eager: true
|
||||
trust_remote_code: true
|
||||
enable_prefix_caching: false
|
||||
engine_output_type: text # Output text + audio tokens
|
||||
is_comprehension: true
|
||||
final_output: true
|
||||
final_output_type: text
|
||||
default_sampling_params:
|
||||
temperature: 0.7
|
||||
top_p: 0.9
|
||||
top_k: -1
|
||||
max_tokens: 256
|
||||
seed: 42
|
||||
detokenize: true
|
||||
repetition_penalty: 1.05
|
||||
@@ -0,0 +1,303 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
E2E tests for Step-Audio2 model with audio input and audio output.
|
||||
|
||||
These tests verify:
|
||||
1. Processor loads correctly and handles audio input
|
||||
2. Field configuration for vLLM batching (flat_from_sizes)
|
||||
3. Tensor shapes are correct (3D not 4D for profiling)
|
||||
4. Basic E2E inference works with audio input
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from tests.helpers.runtime import OmniRunner
|
||||
|
||||
models = ["stepfun-ai/Step-Audio-2-mini"]
|
||||
|
||||
stage_configs = [str(Path(__file__).parent / "stage_configs" / "step_audio2_ci.yaml")]
|
||||
|
||||
test_params = [(model, stage_config) for model in models for stage_config in stage_configs]
|
||||
|
||||
|
||||
def create_dummy_audio(sample_rate: int = 16000, duration_sec: float = 1.0) -> tuple[np.ndarray, int]:
|
||||
"""Create a dummy audio signal (sine wave) for testing."""
|
||||
t = np.linspace(0, duration_sec, int(sample_rate * duration_sec), dtype=np.float32)
|
||||
audio = 0.5 * np.sin(2 * np.pi * 440 * t)
|
||||
return audio, sample_rate
|
||||
|
||||
|
||||
class StepAudio2OmniRunner(OmniRunner):
|
||||
"""Test runner specialized for Step-Audio2 model."""
|
||||
|
||||
def get_omni_inputs(
|
||||
self,
|
||||
prompts: list[str] | str,
|
||||
system_prompt: str | None = None,
|
||||
audios=None,
|
||||
**kwargs,
|
||||
) -> list[dict]:
|
||||
"""Construct Omni input format for Step-Audio2."""
|
||||
if system_prompt is None:
|
||||
system_prompt = "你是一个语音对话助手,能够理解音频输入并生成语音回复。"
|
||||
|
||||
audio_placeholder = "<audio_patch>"
|
||||
|
||||
if isinstance(prompts, str):
|
||||
prompts = [prompts]
|
||||
|
||||
num_prompts = len(prompts)
|
||||
|
||||
if audios is None:
|
||||
audios_list = [None] * num_prompts
|
||||
elif isinstance(audios, list):
|
||||
audios_list = audios if len(audios) == num_prompts else [audios[0]] * num_prompts
|
||||
else:
|
||||
audios_list = [audios] * num_prompts
|
||||
|
||||
omni_inputs = []
|
||||
for i, prompt_text in enumerate(prompts):
|
||||
user_content = ""
|
||||
multi_modal_data = {}
|
||||
|
||||
audio = audios_list[i]
|
||||
if audio is not None:
|
||||
user_content += audio_placeholder
|
||||
multi_modal_data["audio"] = audio
|
||||
|
||||
user_content += prompt_text
|
||||
|
||||
full_prompt = (
|
||||
f"<|im_start|>system\n{system_prompt}<|im_end|>\n"
|
||||
f"<|im_start|>user\n{user_content}<|im_end|>\n"
|
||||
f"<|im_start|>assistant\n"
|
||||
)
|
||||
|
||||
input_dict = {"prompt": full_prompt}
|
||||
if multi_modal_data:
|
||||
input_dict["multi_modal_data"] = multi_modal_data
|
||||
|
||||
omni_inputs.append(input_dict)
|
||||
|
||||
return omni_inputs
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def step_audio2_runner():
|
||||
return StepAudio2OmniRunner
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
def test_processor_loads_correctly():
|
||||
"""Test that Step-Audio2 processor can be imported and initialized."""
|
||||
from vllm_omni.model_executor.models.step_audio2.step_audio2_thinker import (
|
||||
StepAudio2MultiModalProcessor,
|
||||
StepAudio2ProcessingInfo,
|
||||
StepAudio2Processor,
|
||||
)
|
||||
|
||||
assert StepAudio2MultiModalProcessor is not None
|
||||
assert StepAudio2ProcessingInfo is not None
|
||||
assert StepAudio2Processor is not None
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
def test_audio_preprocessing():
|
||||
"""Test that audio preprocessing produces correct tensor shapes."""
|
||||
from vllm_omni.model_executor.models.step_audio2.step_audio2_thinker import (
|
||||
log_mel_spectrogram,
|
||||
padding_mels,
|
||||
)
|
||||
|
||||
audio, sample_rate = create_dummy_audio(sample_rate=16000, duration_sec=1.0)
|
||||
|
||||
mel = log_mel_spectrogram(audio)
|
||||
|
||||
assert mel.ndim == 2, f"Expected 2D tensor, got {mel.ndim}D"
|
||||
assert mel.shape[0] == 128, f"Expected 128 mel bins, got {mel.shape[0]}"
|
||||
|
||||
mels = [mel, mel]
|
||||
padded_mels, mel_lens = padding_mels(mels)
|
||||
|
||||
assert padded_mels.ndim == 3, f"Expected 3D tensor, got {padded_mels.ndim}D"
|
||||
assert padded_mels.shape[0] == 2, f"Expected batch size 2, got {padded_mels.shape[0]}"
|
||||
assert padded_mels.shape[1] == 128, f"Expected 128 mel bins, got {padded_mels.shape[1]}"
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
def test_feature_length_calculation():
|
||||
"""Test that audio feature length calculation is correct."""
|
||||
from vllm_omni.model_executor.models.step_audio2.step_audio2_thinker import (
|
||||
calculate_audio_feature_length,
|
||||
)
|
||||
|
||||
assert calculate_audio_feature_length(1000) == 125
|
||||
|
||||
assert calculate_audio_feature_length(100) > 0
|
||||
|
||||
assert calculate_audio_feature_length(1) >= 1
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
def test_token_config_constants():
|
||||
"""Test that token configuration constants are set correctly."""
|
||||
from vllm_omni.model_executor.models.step_audio2.step_audio2_constants import (
|
||||
DEFAULT_TOKEN_CONFIG,
|
||||
STEP_AUDIO2_AUDIO_END,
|
||||
STEP_AUDIO2_AUDIO_PATCH_TOKEN_ID,
|
||||
STEP_AUDIO2_AUDIO_START,
|
||||
STEP_AUDIO2_AUDIO_VOCAB_SIZE,
|
||||
STEP_AUDIO2_TEXT_MAX,
|
||||
)
|
||||
|
||||
assert STEP_AUDIO2_TEXT_MAX < STEP_AUDIO2_AUDIO_START, "Text tokens should come before audio tokens"
|
||||
assert STEP_AUDIO2_AUDIO_END == STEP_AUDIO2_AUDIO_START + STEP_AUDIO2_AUDIO_VOCAB_SIZE - 1
|
||||
assert STEP_AUDIO2_AUDIO_PATCH_TOKEN_ID > STEP_AUDIO2_TEXT_MAX
|
||||
assert STEP_AUDIO2_AUDIO_PATCH_TOKEN_ID < STEP_AUDIO2_AUDIO_START
|
||||
|
||||
assert DEFAULT_TOKEN_CONFIG.text_max == STEP_AUDIO2_TEXT_MAX
|
||||
assert DEFAULT_TOKEN_CONFIG.audio_start == STEP_AUDIO2_AUDIO_START
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
def test_mm_field_config_structure():
|
||||
"""Test that multimodal field config is properly structured for vLLM batching."""
|
||||
from vllm.multimodal.inputs import MultiModalFieldConfig
|
||||
|
||||
audio_lens = torch.tensor([100, 200, 150], dtype=torch.int32)
|
||||
|
||||
field_config = MultiModalFieldConfig.flat_from_sizes("audio", audio_lens)
|
||||
|
||||
assert field_config is not None
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
def test_audio_encoder_output_shape():
|
||||
"""Test that audio encoder produces correct output shapes."""
|
||||
from vllm_omni.model_executor.models.step_audio2.step_audio2_thinker import (
|
||||
Adaptor,
|
||||
AudioEncoder,
|
||||
)
|
||||
|
||||
encoder = AudioEncoder(n_mels=128, n_ctx=1500, n_state=512, n_head=8, n_layer=6)
|
||||
|
||||
batch_size = 2
|
||||
n_mels = 128
|
||||
time_steps = 400
|
||||
x = torch.randn(batch_size, n_mels, time_steps)
|
||||
x_len = torch.tensor([time_steps, time_steps // 2], dtype=torch.int32)
|
||||
|
||||
encoded, encoded_lens = encoder(x, x_len)
|
||||
|
||||
assert encoded.ndim == 3, f"Expected 3D tensor, got {encoded.ndim}D"
|
||||
assert encoded.shape[0] == batch_size
|
||||
assert encoded.shape[2] == 512
|
||||
|
||||
adapter = Adaptor(n_state=512, n_hidden=4096, kernel_size=3, stride=2)
|
||||
adapted = adapter(encoded)
|
||||
|
||||
assert adapted.ndim == 3
|
||||
assert adapted.shape[0] == batch_size
|
||||
assert adapted.shape[2] == 4096
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
def test_token_separation():
|
||||
"""Test that token separation works correctly."""
|
||||
from vllm_omni.model_executor.models.step_audio2.step_audio2_thinker import (
|
||||
StepAudio2ThinkerForConditionalGeneration,
|
||||
)
|
||||
|
||||
token_ids = [100, 200, 151700, 300, 151800, 400]
|
||||
|
||||
text_tokens, audio_tokens = StepAudio2ThinkerForConditionalGeneration.separate_tokens(token_ids)
|
||||
|
||||
assert text_tokens == [100, 200, 300, 400]
|
||||
assert audio_tokens == [4, 104]
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
def test_has_audio_output():
|
||||
"""Test detection of audio tokens in output."""
|
||||
from vllm_omni.model_executor.models.step_audio2.step_audio2_thinker import (
|
||||
StepAudio2ThinkerForConditionalGeneration,
|
||||
)
|
||||
|
||||
text_only = [100, 200, 300]
|
||||
assert not StepAudio2ThinkerForConditionalGeneration.has_audio_output(text_only)
|
||||
|
||||
with_audio = [100, 200, 151700, 300]
|
||||
assert StepAudio2ThinkerForConditionalGeneration.has_audio_output(with_audio)
|
||||
|
||||
|
||||
@pytest.mark.advanced_model
|
||||
@pytest.mark.parametrize("test_config", test_params)
|
||||
def test_audio_to_text_and_audio(step_audio2_runner: type[StepAudio2OmniRunner], test_config: tuple[str, str]) -> None:
|
||||
"""Test processing audio input and generating text + audio output."""
|
||||
model, stage_config_path = test_config
|
||||
|
||||
with step_audio2_runner(model, seed=42, stage_configs_path=stage_config_path) as runner:
|
||||
audio = create_dummy_audio(sample_rate=16000, duration_sec=2.0)
|
||||
|
||||
outputs = runner.generate_multimodal(
|
||||
prompts="请复述这段音频的内容。",
|
||||
audios=audio,
|
||||
)
|
||||
|
||||
assert len(outputs) > 0
|
||||
|
||||
text_output = None
|
||||
for stage_output in outputs:
|
||||
if stage_output.final_output_type == "text":
|
||||
text_output = stage_output
|
||||
break
|
||||
|
||||
assert text_output is not None
|
||||
assert text_output.request_output is not None
|
||||
text_content = text_output.request_output.outputs[0].text
|
||||
assert text_content is not None
|
||||
assert len(text_content.strip()) > 0
|
||||
|
||||
audio_output = None
|
||||
for stage_output in outputs:
|
||||
if stage_output.final_output_type == "audio":
|
||||
audio_output = stage_output
|
||||
break
|
||||
|
||||
if audio_output is not None:
|
||||
assert audio_output.request_output is not None
|
||||
audio_tensor = audio_output.request_output.outputs[0].multimodal_output.get("audio")
|
||||
if audio_tensor is not None:
|
||||
assert audio_tensor.numel() > 0
|
||||
|
||||
|
||||
@pytest.mark.advanced_model
|
||||
@pytest.mark.parametrize("test_config", test_params)
|
||||
def test_text_only_input(step_audio2_runner: type[StepAudio2OmniRunner], test_config: tuple[str, str]) -> None:
|
||||
"""Test processing text-only input (no audio)."""
|
||||
model, stage_config_path = test_config
|
||||
|
||||
with step_audio2_runner(model, seed=42, stage_configs_path=stage_config_path) as runner:
|
||||
outputs = runner.generate_multimodal(
|
||||
prompts="你好,请用中文回答。",
|
||||
audios=None,
|
||||
)
|
||||
|
||||
assert len(outputs) > 0
|
||||
|
||||
text_output = None
|
||||
for stage_output in outputs:
|
||||
if stage_output.final_output_type == "text":
|
||||
text_output = stage_output
|
||||
break
|
||||
|
||||
assert text_output is not None
|
||||
assert text_output.request_output is not None
|
||||
text_content = text_output.request_output.outputs[0].text
|
||||
assert text_content is not None
|
||||
assert len(text_content.strip()) > 0
|
||||
@@ -0,0 +1,81 @@
|
||||
# Stage config for Step-Audio2 CI tests
|
||||
# Stage 0: Thinker (audio understanding → text + audio tokens)
|
||||
# Stage 1: Token2Wav (audio tokens → waveform)
|
||||
|
||||
# The following config has been verified on 2x 24GB GPU (L4/RTX3090/RTX4090).
|
||||
stage_args:
|
||||
- stage_id: 0
|
||||
runtime:
|
||||
process: true
|
||||
devices: "0"
|
||||
max_batch_size: 1
|
||||
engine_args:
|
||||
model_stage: thinker
|
||||
model_arch: StepAudio2ThinkerForConditionalGeneration
|
||||
tensor_parallel_size: 1
|
||||
hf_overrides:
|
||||
architectures: ["StepAudio2ThinkerForConditionalGeneration"]
|
||||
|
||||
worker_cls: vllm_omni.worker.gpu_ar_worker.GPUARWorker
|
||||
scheduler_cls: vllm_omni.core.sched.omni_ar_scheduler.OmniARScheduler
|
||||
max_model_len: 1024
|
||||
max_num_batched_tokens: 1024
|
||||
max_num_seqs: 1
|
||||
gpu_memory_utilization: 0.7
|
||||
skip_mm_profiling: true
|
||||
enforce_eager: true
|
||||
trust_remote_code: true
|
||||
enable_prefix_caching: false
|
||||
engine_output_type: text # Output text + audio tokens
|
||||
is_comprehension: true
|
||||
final_output: true
|
||||
final_output_type: text
|
||||
default_sampling_params:
|
||||
temperature: 0.7
|
||||
top_p: 0.9
|
||||
top_k: -1
|
||||
max_tokens: 256
|
||||
seed: 42
|
||||
detokenize: true
|
||||
repetition_penalty: 1.05
|
||||
|
||||
- stage_id: 1
|
||||
runtime:
|
||||
process: true
|
||||
devices: "0"
|
||||
max_batch_size: 1
|
||||
engine_args:
|
||||
|
||||
model_stage: token2wav
|
||||
model_arch: StepAudio2Token2WavModel
|
||||
worker_cls: vllm_omni.worker.gpu_generation_worker.GPUGenerationWorker
|
||||
scheduler_cls: vllm_omni.core.sched.omni_generation_scheduler.OmniGenerationScheduler
|
||||
hf_overrides:
|
||||
architectures: ["StepAudio2Token2WavModel"]
|
||||
gpu_memory_utilization: 0.2
|
||||
enforce_eager: true
|
||||
trust_remote_code: true
|
||||
enable_prefix_caching: false
|
||||
max_num_batched_tokens: 1024
|
||||
engine_output_type: audio # Output waveform
|
||||
engine_input_source: [0]
|
||||
custom_process_input_func: vllm_omni.model_executor.stage_input_processors.step_audio2.thinker2token2wav
|
||||
final_output: true
|
||||
final_output_type: audio
|
||||
default_sampling_params:
|
||||
temperature: 0.0
|
||||
top_p: 1.0
|
||||
top_k: -1
|
||||
max_tokens: 1
|
||||
seed: 42
|
||||
detokenize: false
|
||||
|
||||
runtime:
|
||||
enabled: true
|
||||
defaults:
|
||||
window_size: -1
|
||||
max_inflight: 1
|
||||
edges:
|
||||
- from: 0
|
||||
to: 1
|
||||
window_size: -1
|
||||
@@ -0,0 +1,368 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""
|
||||
E2E tests for Step-Audio2 online serving with concurrent requests.
|
||||
|
||||
Tests:
|
||||
1. Single request via API
|
||||
2. Concurrent throughput (1/2/4/8 concurrent requests)
|
||||
3. Latency percentiles (p50/p95/p99)
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import aiohttp
|
||||
import numpy as np
|
||||
import pytest
|
||||
from vllm.utils.network_utils import get_open_port
|
||||
|
||||
MODEL = "stepfun-ai/Step-Audio-2-mini"
|
||||
STAGE_CONFIG = str(Path(__file__).parent / "stage_configs" / "step_audio2_ci.yaml")
|
||||
|
||||
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
|
||||
|
||||
|
||||
class OmniServer:
|
||||
"""Omniserver for vLLM-Omni tests."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
model: str,
|
||||
serve_args: list[str],
|
||||
*,
|
||||
env_dict: dict[str, str] | None = None,
|
||||
) -> None:
|
||||
self.model = model
|
||||
self.serve_args = serve_args
|
||||
self.env_dict = env_dict
|
||||
self.proc: subprocess.Popen | None = None
|
||||
self.host = "127.0.0.1"
|
||||
self.port = get_open_port()
|
||||
|
||||
def _start_server(self) -> None:
|
||||
"""Start the vLLM-Omni server subprocess."""
|
||||
env = os.environ.copy()
|
||||
env["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
|
||||
if self.env_dict is not None:
|
||||
env.update(self.env_dict)
|
||||
|
||||
cmd = [
|
||||
sys.executable,
|
||||
"-m",
|
||||
"vllm_omni.entrypoints.cli.main",
|
||||
"serve",
|
||||
self.model,
|
||||
"--omni",
|
||||
"--host",
|
||||
self.host,
|
||||
"--port",
|
||||
str(self.port),
|
||||
] + self.serve_args
|
||||
|
||||
print(f"Launching OmniServer with: {' '.join(cmd)}")
|
||||
self.proc = subprocess.Popen(
|
||||
cmd,
|
||||
env=env,
|
||||
cwd=os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
|
||||
)
|
||||
|
||||
max_wait = 600 # 10 minutes
|
||||
start_time = time.time()
|
||||
while time.time() - start_time < max_wait:
|
||||
try:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
||||
sock.settimeout(1)
|
||||
result = sock.connect_ex((self.host, self.port))
|
||||
if result == 0:
|
||||
print(f"Server ready on {self.host}:{self.port}")
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(2)
|
||||
|
||||
raise RuntimeError(f"Server failed to start within {max_wait} seconds")
|
||||
|
||||
def __enter__(self):
|
||||
self._start_server()
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||
if self.proc:
|
||||
self.proc.terminate()
|
||||
try:
|
||||
self.proc.wait(timeout=30)
|
||||
except subprocess.TimeoutExpired:
|
||||
self.proc.kill()
|
||||
self.proc.wait()
|
||||
|
||||
|
||||
def create_dummy_audio_base64(duration_sec: float = 5.0, sample_rate: int = 16000) -> str:
|
||||
"""Create dummy audio as base64."""
|
||||
import base64
|
||||
import io
|
||||
import wave
|
||||
|
||||
num_samples = int(duration_sec * sample_rate)
|
||||
t = np.linspace(0, duration_sec, num_samples, dtype=np.float32)
|
||||
audio = (0.5 * np.sin(2 * np.pi * 440 * t) * 32767).astype(np.int16)
|
||||
|
||||
buffer = io.BytesIO()
|
||||
with wave.open(buffer, "wb") as wav_file:
|
||||
wav_file.setnchannels(1)
|
||||
wav_file.setsampwidth(2)
|
||||
wav_file.setframerate(sample_rate)
|
||||
wav_file.writeframes(audio.tobytes())
|
||||
|
||||
return base64.b64encode(buffer.getvalue()).decode("utf-8")
|
||||
|
||||
|
||||
def create_s2st_request(audio_base64: str) -> dict:
|
||||
"""Create S2ST request payload."""
|
||||
# Use audio_url format with base64 data URL
|
||||
audio_url = f"data:audio/wav;base64,{audio_base64}"
|
||||
return {
|
||||
"model": MODEL,
|
||||
"messages": [
|
||||
{"role": "system", "content": "请仔细聆听这段语音,然后复述其内容。"},
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{
|
||||
"type": "audio_url",
|
||||
"audio_url": {"url": audio_url},
|
||||
},
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<tts_start>",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
"max_tokens": 512,
|
||||
"temperature": 0.7,
|
||||
"top_p": 0.9,
|
||||
}
|
||||
|
||||
|
||||
async def send_request(session: aiohttp.ClientSession, url: str, payload: dict) -> tuple[float, int, str]:
|
||||
"""Send single request and return (latency, num_tokens, response_text)."""
|
||||
start = time.perf_counter()
|
||||
async with session.post(url, json=payload) as response:
|
||||
result = await response.json()
|
||||
latency = time.perf_counter() - start
|
||||
|
||||
if "choices" in result and len(result["choices"]) > 0:
|
||||
text = result["choices"][0].get("message", {}).get("content", "")
|
||||
tokens = result.get("usage", {}).get("completion_tokens", len(text.split()))
|
||||
else:
|
||||
text = str(result)
|
||||
tokens = 0
|
||||
|
||||
return latency, tokens, text
|
||||
|
||||
|
||||
async def benchmark_concurrent(
|
||||
url: str,
|
||||
payload: dict,
|
||||
num_concurrent: int,
|
||||
num_requests: int,
|
||||
warmup: int = 2,
|
||||
) -> dict:
|
||||
"""Run concurrent benchmark with true sustained concurrency.
|
||||
|
||||
Uses semaphore to maintain exactly num_concurrent requests in flight at all times,
|
||||
rather than batch-and-wait approach. Measures real wall clock time.
|
||||
"""
|
||||
semaphore = asyncio.Semaphore(num_concurrent)
|
||||
|
||||
async def bounded_request(session: aiohttp.ClientSession):
|
||||
async with semaphore:
|
||||
return await send_request(session, url, payload)
|
||||
|
||||
async with aiohttp.ClientSession() as session:
|
||||
if warmup > 0:
|
||||
print(f" Warming up ({warmup} requests)...", end=" ", flush=True)
|
||||
for _ in range(warmup):
|
||||
try:
|
||||
await send_request(session, url, payload)
|
||||
except Exception as e:
|
||||
print(f"Warmup failed: {e}")
|
||||
print("done")
|
||||
|
||||
print(f" Running {num_requests} requests with concurrency={num_concurrent}...", end=" ", flush=True)
|
||||
wall_start = time.perf_counter()
|
||||
|
||||
tasks = [bounded_request(session) for _ in range(num_requests)]
|
||||
results = await asyncio.gather(*tasks, return_exceptions=True)
|
||||
|
||||
wall_time = time.perf_counter() - wall_start
|
||||
print(f"done ({wall_time:.2f}s)")
|
||||
|
||||
all_latencies = []
|
||||
all_tokens = []
|
||||
errors = 0
|
||||
|
||||
for result in results:
|
||||
if isinstance(result, Exception):
|
||||
print(f" Request failed: {result}")
|
||||
errors += 1
|
||||
continue
|
||||
latency, tokens, _ = result
|
||||
all_latencies.append(latency)
|
||||
all_tokens.append(tokens)
|
||||
|
||||
if not all_latencies:
|
||||
return {"error": "All requests failed"}
|
||||
|
||||
latencies = np.array(all_latencies)
|
||||
total_tokens = sum(all_tokens)
|
||||
successful_requests = len(all_latencies)
|
||||
|
||||
return {
|
||||
"num_concurrent": num_concurrent,
|
||||
"num_requests": num_requests,
|
||||
"successful_requests": successful_requests,
|
||||
"errors": errors,
|
||||
"wall_time": wall_time,
|
||||
"p50_latency": float(np.percentile(latencies, 50)),
|
||||
"p95_latency": float(np.percentile(latencies, 95)),
|
||||
"p99_latency": float(np.percentile(latencies, 99)),
|
||||
"mean_latency": float(np.mean(latencies)),
|
||||
"min_latency": float(np.min(latencies)),
|
||||
"max_latency": float(np.max(latencies)),
|
||||
"throughput_req_per_sec": successful_requests / wall_time,
|
||||
"throughput_tokens_per_sec": total_tokens / wall_time,
|
||||
}
|
||||
|
||||
|
||||
class TestStepAudio2OnlineServing:
|
||||
"""Online serving tests for Step-Audio2."""
|
||||
|
||||
@pytest.fixture(scope="class")
|
||||
def server(self):
|
||||
"""Start vLLM-Omni server."""
|
||||
with OmniServer(MODEL, ["--stage-configs-path", STAGE_CONFIG]) as omni_server:
|
||||
yield f"http://{omni_server.host}:{omni_server.port}/v1/chat/completions"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_single_request(self, server):
|
||||
"""Test single request works."""
|
||||
audio_base64 = create_dummy_audio_base64(duration_sec=2.0)
|
||||
payload = create_s2st_request(audio_base64)
|
||||
|
||||
async with aiohttp.ClientSession() as session:
|
||||
latency, tokens, text = await send_request(session, server, payload)
|
||||
|
||||
assert latency > 0
|
||||
assert tokens >= 0
|
||||
print(f"Single request: latency={latency:.2f}s, tokens={tokens}")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("num_concurrent", [1, 2, 4])
|
||||
async def test_concurrent_throughput(self, server, num_concurrent):
|
||||
"""Test concurrent throughput at different concurrency levels."""
|
||||
audio_base64 = create_dummy_audio_base64(duration_sec=5.0)
|
||||
payload = create_s2st_request(audio_base64)
|
||||
|
||||
num_requests = num_concurrent * 3
|
||||
|
||||
stats = await benchmark_concurrent(server, payload, num_concurrent, num_requests)
|
||||
|
||||
assert "error" not in stats
|
||||
print(f"\nConcurrency={num_concurrent}:")
|
||||
print(f" p50={stats['p50_latency']:.2f}s, p95={stats['p95_latency']:.2f}s")
|
||||
print(f" throughput={stats['throughput_req_per_sec']:.2f} req/s")
|
||||
|
||||
|
||||
async def run_throughput_benchmark(
|
||||
server_url: str,
|
||||
audio_duration: float = 5.0,
|
||||
concurrency_levels: list[int] = [1, 2, 4, 8],
|
||||
requests_per_level: int = 10,
|
||||
warmup: int = 2,
|
||||
):
|
||||
"""Run full throughput benchmark."""
|
||||
audio_base64 = create_dummy_audio_base64(duration_sec=audio_duration)
|
||||
payload = create_s2st_request(audio_base64)
|
||||
|
||||
print(f"{'=' * 70}")
|
||||
print("Step-Audio2 Online Serving Throughput Benchmark")
|
||||
print(f"{'=' * 70}")
|
||||
print(f"Server: {server_url}")
|
||||
print(f"Audio duration: {audio_duration}s")
|
||||
print(f"Requests per level: {requests_per_level}")
|
||||
print(f"Warmup requests: {warmup}")
|
||||
print(f"Concurrency levels: {concurrency_levels}")
|
||||
print(f"{'=' * 70}")
|
||||
|
||||
results = []
|
||||
for num_concurrent in concurrency_levels:
|
||||
print(f"\n[Concurrency={num_concurrent}]")
|
||||
stats = await benchmark_concurrent(server_url, payload, num_concurrent, requests_per_level, warmup)
|
||||
results.append(stats)
|
||||
|
||||
if "error" not in stats:
|
||||
print(
|
||||
f" Result: p50={stats['p50_latency']:.2f}s, "
|
||||
f"p95={stats['p95_latency']:.2f}s, "
|
||||
f"throughput={stats['throughput_req_per_sec']:.2f} req/s, "
|
||||
f"{stats['throughput_tokens_per_sec']:.1f} tok/s"
|
||||
)
|
||||
|
||||
print(f"\n{'=' * 80}")
|
||||
print("SUMMARY")
|
||||
print(f"{'=' * 80}")
|
||||
print(
|
||||
f"{'Conc':<6} {'Reqs':<6} {'Err':<5} {'Wall(s)':<9} {'p50':<8} {'p95':<8} {'p99':<8} {'Req/s':<8} {'Tok/s':<8}"
|
||||
)
|
||||
print("-" * 80)
|
||||
|
||||
for stats in results:
|
||||
if "error" in stats:
|
||||
print(f"{stats.get('num_concurrent', '?'):<6} ERROR: {stats['error']}")
|
||||
continue
|
||||
print(
|
||||
f"{stats['num_concurrent']:<6} "
|
||||
f"{stats['successful_requests']:<6} "
|
||||
f"{stats['errors']:<5} "
|
||||
f"{stats['wall_time']:<9.2f} "
|
||||
f"{stats['p50_latency']:<8.2f} "
|
||||
f"{stats['p95_latency']:<8.2f} "
|
||||
f"{stats['p99_latency']:<8.2f} "
|
||||
f"{stats['throughput_req_per_sec']:<8.2f} "
|
||||
f"{stats['throughput_tokens_per_sec']:<8.1f}"
|
||||
)
|
||||
|
||||
print("=" * 80)
|
||||
return results
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import argparse
|
||||
|
||||
parser = argparse.ArgumentParser(description="Step-Audio2 Online Serving Benchmark")
|
||||
parser.add_argument(
|
||||
"--server-url", type=str, default="http://localhost:8000/v1/chat/completions", help="vLLM server URL"
|
||||
)
|
||||
parser.add_argument("--audio-duration", type=float, default=5.0, help="Input audio duration in seconds")
|
||||
parser.add_argument("--concurrency", type=str, default="1,2,4,8", help="Comma-separated concurrency levels to test")
|
||||
parser.add_argument("--requests-per-level", type=int, default=10, help="Number of requests per concurrency level")
|
||||
parser.add_argument("--warmup", type=int, default=2, help="Number of warmup requests before each benchmark")
|
||||
|
||||
args = parser.parse_args()
|
||||
concurrency_levels = [int(x) for x in args.concurrency.split(",")]
|
||||
|
||||
asyncio.run(
|
||||
run_throughput_benchmark(
|
||||
args.server_url,
|
||||
args.audio_duration,
|
||||
concurrency_levels,
|
||||
args.requests_per_level,
|
||||
args.warmup,
|
||||
)
|
||||
)
|
||||
Reference in new issue
Block a user