[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,375 @@
|
||||
# Step-Audio2 Offline Inference Examples
|
||||
|
||||
This directory contains examples for running offline inference with Step-Audio2 using vLLM-Omni.
|
||||
|
||||
## Model Overview
|
||||
|
||||
Step-Audio2 is a two-stage audio model:
|
||||
|
||||
- **Stage 0 (Thinker)**: Audio understanding → Text + Audio tokens
|
||||
- Input: Audio (16kHz)
|
||||
- Output: Text transcription + Audio tokens for synthesis
|
||||
|
||||
- **Stage 1 (Token2Wav)**: Audio synthesis
|
||||
- Input: Audio tokens + Speaker prompt wav
|
||||
- Output: Synthesized audio waveform (24kHz)
|
||||
|
||||
## Hardware Requirements
|
||||
|
||||
| Mode | GPU Configuration | VRAM Required |
|
||||
|------|-------------------|---------------|
|
||||
| ASR (S2T) | 1x GPU | ~20-25GB |
|
||||
| TTS/S2ST (single GPU) | 1x GPU | ~40-50GB |
|
||||
| TTS/S2ST (multi GPU) | 2x GPU | GPU0: ~28GB, GPU1: ~22GB |
|
||||
|
||||
**Tested on:**
|
||||
- 1x NVIDIA H100 80GB (single-card S2ST)
|
||||
- 2x NVIDIA A10 40GB (multi-card S2ST)
|
||||
|
||||
**Notes:**
|
||||
- Single GPU mode requires high VRAM due to both stages sharing memory
|
||||
- Multi GPU mode separates Stage 0 (Thinker) and Stage 1 (Token2Wav) across GPUs
|
||||
- VRAM usage can be adjusted via `gpu_memory_utilization` in stage config
|
||||
|
||||
## Performance Benchmark
|
||||
|
||||
### vLLM-Omni vs Official Step-Audio2
|
||||
|
||||
Single request latency comparison between vLLM-Omni and official Step-Audio2 implementation.
|
||||
|
||||
| Task | Tokens | vllm-omni | Step-Audio2 | Speedup |
|
||||
|------|--------|-----------|-------------|---------|
|
||||
| S2ST | ~85 | 5.45s | 7.36s | **1.35x** |
|
||||
| S2ST | ~160 | 6.67s | 13.92s | **2.09x** |
|
||||
| S2ST | ~315 | 9.42s | 31.50s | **3.34x** |
|
||||
| TTS | ~1024 | 16.65s | ~87s | **~5.2x** |
|
||||
|
||||
**Key observations:**
|
||||
- Speedup increases with sequence length due to vLLM's efficient KV cache management
|
||||
- TTS (pure generation) shows the largest speedup (~5x)
|
||||
- S2ST benefits from optimized multi-stage pipeline
|
||||
|
||||
**Benchmark environment:**
|
||||
- GPU: NVIDIA H100 80GB (single card)
|
||||
- Model: Step-Audio2-mini
|
||||
- Warmup: 1 run, Measured: 3 runs (averaged)
|
||||
|
||||
### Async Chunk Streaming Performance
|
||||
|
||||
Comparison between sequential (non-async) and async chunk modes via `/v1/audio/speech` TTS endpoint.
|
||||
|
||||
| Mode | Mean TTFP | Mean E2E | Mean RTF | Audio Throughput |
|
||||
|------|-----------|----------|----------|-----------------|
|
||||
| Sequential | 4316ms | 4316ms | 0.938 | 1.07x realtime |
|
||||
| **Async Chunk** | **1437ms** | 4362ms | 0.949 | 1.06x realtime |
|
||||
| **Improvement** | **-67% (3x faster)** | ~same | ~same | ~same |
|
||||
|
||||
**Key observations:**
|
||||
- Async chunk reduces **time-to-first-audio (TTFP) by 67%** (4.3s → 1.4s)
|
||||
- E2E latency remains comparable — async chunk overlaps Thinker decode with Token2Wav synthesis
|
||||
- RTF < 1 in both modes (real-time capable)
|
||||
- Sequential mode: TTFP ≈ E2E (must wait for all audio tokens before synthesis starts)
|
||||
- Async chunk mode: Token2Wav starts after first 28 tokens (chunk_size=25 + lookahead=3)
|
||||
|
||||
**Benchmark environment:**
|
||||
- GPU: 4x NVIDIA RTX 3090 24GB (TP=2 for Thinker, 1 GPU for Token2Wav)
|
||||
- Model: Step-Audio2-mini
|
||||
- Endpoint: `/v1/audio/speech` (10 prompts, concurrency=1)
|
||||
- Measured via `bench_tts_serve.py`
|
||||
|
||||
## Installation
|
||||
|
||||
Make sure you have installed vLLM-Omni and all required dependencies:
|
||||
|
||||
```bash
|
||||
# Install vLLM-Omni
|
||||
pip install vllm-omni
|
||||
|
||||
# Install Step-Audio2 (REQUIRED for Token2Wav stage)
|
||||
pip install step-audio2
|
||||
```
|
||||
|
||||
## Model Setup
|
||||
|
||||
### Option 1: Auto-download from HuggingFace (Recommended)
|
||||
|
||||
The script will **automatically download** the model on first run:
|
||||
|
||||
```bash
|
||||
# Just run without specifying --model, it will auto-download stepfun-ai/Step-Audio2-mini
|
||||
python end2end.py --query-type audio_to_text
|
||||
|
||||
# Or explicitly specify the HuggingFace model
|
||||
python end2end.py --query-type audio_to_text --model stepfun-ai/Step-Audio2-mini
|
||||
```
|
||||
|
||||
Models will be cached in `~/.cache/huggingface/hub/` for future use.
|
||||
|
||||
**Available models**:
|
||||
- `stepfun-ai/Step-Audio2-mini` (smaller, faster)
|
||||
- `stepfun-ai/Step-Audio2-7B` (larger, better quality)
|
||||
|
||||
### Option 2: Manual Download (for offline use)
|
||||
|
||||
Download and use locally:
|
||||
|
||||
```bash
|
||||
# Download from HuggingFace
|
||||
huggingface-cli download stepfun-ai/Step-Audio2-mini --local-dir ./models/Step-Audio2-mini
|
||||
|
||||
# Then use the local path
|
||||
python end2end.py --query-type audio_to_text --model ./models/Step-Audio2-mini
|
||||
```
|
||||
|
||||
Ensure the model directory contains:
|
||||
```
|
||||
Step-Audio2-mini/
|
||||
├── config.json
|
||||
├── model.safetensors (or pytorch_model.bin)
|
||||
├── tokenizer.json
|
||||
├── tokenizer_config.json
|
||||
└── token2wav/ # Token2Wav models (REQUIRED)
|
||||
├── speech_tokenizer_v2_25hz.onnx # Audio tokenizer
|
||||
├── campplus.onnx # Speaker encoder
|
||||
├── flow.yaml # Flow model config
|
||||
├── flow.pt # Flow model weights
|
||||
└── hift.pt # HiFT vocoder weights
|
||||
```
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### 1. Audio to Text (ASR - Speech Recognition)
|
||||
|
||||
Transcribe audio to text:
|
||||
|
||||
```bash
|
||||
# Quick start - Using default model and test audio
|
||||
python end2end.py --query-type audio_to_text
|
||||
|
||||
# Using your own audio file (model will auto-download)
|
||||
python end2end.py --query-type audio_to_text \
|
||||
--audio-path /path/to/input.wav
|
||||
|
||||
# With specific model
|
||||
python end2end.py --query-type audio_to_text \
|
||||
--audio-path /path/to/input.wav \
|
||||
--model stepfun-ai/Step-Audio2-7B
|
||||
|
||||
# With custom question
|
||||
python end2end.py --query-type audio_to_text \
|
||||
--audio-path input.wav \
|
||||
--question "What is the speaker saying?"
|
||||
```
|
||||
|
||||
**Output**: Text transcription saved to `output_step_audio2/00000_text.txt`
|
||||
|
||||
### 2. Text to Audio (TTS - Speech Synthesis)
|
||||
|
||||
Convert text to speech:
|
||||
|
||||
```bash
|
||||
# Basic TTS (model auto-downloads)
|
||||
python end2end.py --query-type text_to_audio \
|
||||
--text "Hello, this is a test of Step Audio 2 synthesis."
|
||||
|
||||
# With specific model
|
||||
python end2end.py --query-type text_to_audio \
|
||||
--text "Hello, this is a test." \
|
||||
--model stepfun-ai/Step-Audio2-7B
|
||||
```
|
||||
|
||||
**Note**: Speaker voice is controlled by the `STEP_AUDIO2_DEFAULT_PROMPT_WAV` environment variable or the default prompt wav bundled with the model.
|
||||
|
||||
**Output**:
|
||||
- Text: `output_step_audio2/00000_text.txt`
|
||||
- Audio: `output_step_audio2/00000_output.wav` (24kHz)
|
||||
|
||||
### 3. Audio to Audio (Voice Conversion)
|
||||
|
||||
Process input audio and generate output audio:
|
||||
|
||||
```bash
|
||||
# Basic voice conversion (model auto-downloads)
|
||||
python end2end.py --query-type audio_to_audio \
|
||||
--audio-path /path/to/source_audio.wav
|
||||
|
||||
# With specific model
|
||||
python end2end.py --query-type audio_to_audio \
|
||||
--audio-path source.wav \
|
||||
--model stepfun-ai/Step-Audio2-7B
|
||||
```
|
||||
|
||||
This mode:
|
||||
1. Understands the content in `--audio-path` (source)
|
||||
2. Generates audio output with the default voice
|
||||
|
||||
**Note**: To use a custom speaker voice, set the `STEP_AUDIO2_DEFAULT_PROMPT_WAV` environment variable.
|
||||
|
||||
### Advanced Options
|
||||
|
||||
```bash
|
||||
# Use custom stage configuration
|
||||
python end2end.py --query-type audio_to_text \
|
||||
--stage-configs-path /path/to/custom_config.yaml
|
||||
|
||||
# Multiple prompts (for batch testing)
|
||||
python end2end.py --query-type audio_to_text \
|
||||
--audio-path input.wav \
|
||||
--num-prompts 5
|
||||
|
||||
# Custom output directory
|
||||
python end2end.py --query-type text_to_audio \
|
||||
--text "Test synthesis" \
|
||||
--output-dir ./my_outputs
|
||||
|
||||
# Enable detailed logging
|
||||
python end2end.py --query-type audio_to_text \
|
||||
--audio-path input.wav \
|
||||
--enable-stats
|
||||
|
||||
# Adjust generation parameters
|
||||
python end2end.py --query-type audio_to_text \
|
||||
--audio-path input.wav \
|
||||
--max-tokens 2048
|
||||
|
||||
# Use custom speaker voice via environment variable
|
||||
STEP_AUDIO2_DEFAULT_PROMPT_WAV=/path/to/speaker.wav python end2end.py \
|
||||
--query-type text_to_audio \
|
||||
--text "Hello world"
|
||||
|
||||
# Use Ray backend for distributed processing
|
||||
python end2end.py --query-type text_to_audio \
|
||||
--text "Hello world" \
|
||||
--worker-backend ray \
|
||||
--ray-address "auto"
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
### Stage Configuration
|
||||
|
||||
The default configuration (`step_audio_2.yaml`) uses:
|
||||
|
||||
- **Stage 0 (Thinker)**: GPU 0, 80% memory
|
||||
- **Stage 1 (Token2Wav)**: GPU 1, 30% memory
|
||||
|
||||
For **single GPU** setup, edit the config to use `devices: "0"` for both stages.
|
||||
|
||||
### Sampling Parameters
|
||||
|
||||
- **Thinker (Stage 0)**:
|
||||
- Temperature: 0.7 (balanced creativity)
|
||||
- Top-p: 0.9
|
||||
- Max tokens: 1024 (configurable)
|
||||
|
||||
- **Token2Wav (Stage 1)**:
|
||||
- Temperature: 0.0 (deterministic)
|
||||
- Operates in generation mode (not sampling)
|
||||
|
||||
## Common Issues
|
||||
|
||||
### 1. ImportError: No module named 's3tokenizer'
|
||||
|
||||
**Solution**: Install Step-Audio2 package:
|
||||
```bash
|
||||
pip install step-audio2
|
||||
```
|
||||
|
||||
### 2. FileNotFoundError: prompt_wav file not found
|
||||
|
||||
**Solution**: Set the `STEP_AUDIO2_DEFAULT_PROMPT_WAV` environment variable to a valid audio file:
|
||||
```bash
|
||||
export STEP_AUDIO2_DEFAULT_PROMPT_WAV=/path/to/speaker.wav
|
||||
python end2end.py --query-type text_to_audio --text "Hello"
|
||||
```
|
||||
Or ensure the default prompt wav (`default_female.wav`) exists in your model directory.
|
||||
|
||||
### 3. FileNotFoundError: token2wav models not found
|
||||
|
||||
**Solution**: Ensure your model directory has the complete `token2wav/` subdirectory with all ONNX and PyTorch models.
|
||||
|
||||
### 4. CUDA Out of Memory
|
||||
|
||||
**Solutions**:
|
||||
- Use single GPU mode (set both stages to `devices: "0"`)
|
||||
- Reduce `gpu_memory_utilization` in config
|
||||
- Reduce `max_num_batched_tokens`
|
||||
- Process fewer prompts at once
|
||||
|
||||
### 5. Model not found in registry
|
||||
|
||||
**Solution**: Ensure you're using vLLM-Omni's entry point with `--omni` flag or install vllm-omni properly:
|
||||
```bash
|
||||
pip install vllm-omni
|
||||
```
|
||||
|
||||
## Output Files
|
||||
|
||||
The script generates files in the output directory (default: `output_step_audio2/`):
|
||||
|
||||
```
|
||||
output_step_audio2/
|
||||
├── 00000_text.txt # Text output from Thinker stage
|
||||
├── 00000_output.wav # Audio output from Token2Wav stage (24kHz)
|
||||
├── 00001_text.txt # (if multiple prompts)
|
||||
└── 00001_output.wav
|
||||
```
|
||||
|
||||
## Performance Tips
|
||||
|
||||
1. **First run is slow**: Stage initialization takes 20-60 seconds
|
||||
2. **Single GPU**: Set both stages to `devices: "0"` in config
|
||||
3. **Multiple prompts**: Use `--num-prompts N` for batch testing
|
||||
4. **Ray backend**: For multi-node or advanced scheduling
|
||||
5. **Logging**: Use `--enable-stats` to debug performance issues
|
||||
|
||||
## Speaker Voice Configuration
|
||||
|
||||
The Token2Wav stage requires a speaker prompt wav for voice conditioning. It is automatically resolved in this order:
|
||||
|
||||
1. `STEP_AUDIO2_DEFAULT_PROMPT_WAV` environment variable (if set)
|
||||
2. `{model_dir}/assets/default_female.wav`
|
||||
3. `{model_dir}/default_female.wav`
|
||||
|
||||
If none are found, set the environment variable explicitly:
|
||||
```bash
|
||||
export STEP_AUDIO2_DEFAULT_PROMPT_WAV=/path/to/speaker.wav
|
||||
```
|
||||
|
||||
**Guidelines for custom speaker prompt:**
|
||||
|
||||
- **Duration**: 3-10 seconds recommended
|
||||
- **Quality**: Clean audio, minimal background noise
|
||||
- **Format**: WAV, MP3, FLAC (will be resampled internally)
|
||||
- **Content**: Clear speech, representative of target voice
|
||||
|
||||
## Example Workflow
|
||||
|
||||
Complete example from audio to final output:
|
||||
|
||||
```bash
|
||||
# 1. ASR: Transcribe audio
|
||||
python end2end.py --query-type audio_to_text \
|
||||
--audio-path interview.wav \
|
||||
--model ./models/Step-Audio2-7B \
|
||||
--output-dir ./outputs
|
||||
|
||||
# 2. Check the transcription
|
||||
cat ./outputs/00000_text.txt
|
||||
|
||||
# 3. TTS: Synthesize new speech (with custom voice)
|
||||
STEP_AUDIO2_DEFAULT_PROMPT_WAV=./speaker_samples/female_voice.wav \
|
||||
python end2end.py --query-type text_to_audio \
|
||||
--text "The quick brown fox jumps over the lazy dog" \
|
||||
--model ./models/Step-Audio2-7B \
|
||||
--output-dir ./outputs
|
||||
|
||||
# 4. Listen to the result
|
||||
# Audio saved to: ./outputs/00000_output.wav
|
||||
```
|
||||
|
||||
## References
|
||||
|
||||
- [Step-Audio2 Paper](https://arxiv.org/abs/2507.16632)
|
||||
- [vLLM-Omni Documentation](https://vllm-omni.readthedocs.io)
|
||||
- [Model on HuggingFace](https://huggingface.co/stepfun-ai/Step-Audio-2-mini)
|
||||
@@ -0,0 +1,527 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
This example shows how to use vLLM-Omni for running offline inference
|
||||
with Step-Audio2 model for audio understanding and generation.
|
||||
|
||||
Step-Audio2 is a two-stage model:
|
||||
- Stage 0 (Thinker): Audio understanding → Text + Audio tokens
|
||||
- Stage 1 (Token2Wav): Audio tokens → Waveform (24kHz)
|
||||
|
||||
Usage examples:
|
||||
# Audio to text (ASR)
|
||||
python end2end.py --query-type audio_to_text --audio-path input.wav --model-path "$MODEL_PATH"
|
||||
|
||||
# Text to audio (TTS with default voice)
|
||||
python end2end.py --query-type text_to_audio --model-path "$MODEL_PATH"
|
||||
|
||||
# Audio to audio (Voice conversion with default voice)
|
||||
python end2end.py --query-type audio_to_audio --audio-path input.wav --model-path "$MODEL_PATH"
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import NamedTuple
|
||||
|
||||
import librosa # noqa: TID251
|
||||
import numpy as np
|
||||
import soundfile as sf
|
||||
import torch
|
||||
from vllm.assets.audio import AudioAsset
|
||||
from vllm.sampling_params import SamplingParams
|
||||
from vllm.utils.argparse_utils import FlexibleArgumentParser
|
||||
|
||||
from vllm_omni.entrypoints.omni import Omni
|
||||
|
||||
SEED = 42
|
||||
|
||||
|
||||
class QueryResult(NamedTuple):
|
||||
inputs: dict
|
||||
limit_mm_per_prompt: dict[str, int]
|
||||
|
||||
|
||||
def get_audio_to_text_query(
|
||||
audio_path: str | None = None,
|
||||
question: str | None = None,
|
||||
sampling_rate: int = 16000,
|
||||
) -> QueryResult:
|
||||
"""
|
||||
Audio Speech Recognition (ASR) - Convert audio to text.
|
||||
|
||||
Args:
|
||||
audio_path: Path to audio file
|
||||
question: Question about the audio (optional)
|
||||
sampling_rate: Target sampling rate (16kHz for Step-Audio2)
|
||||
|
||||
Returns:
|
||||
QueryResult with prompt and audio data
|
||||
"""
|
||||
if question is None:
|
||||
question = "请记录下你所听到的语音内容。"
|
||||
|
||||
prompt = (
|
||||
f"<|im_start|>system\n{question}<|im_end|>\n<|im_start|>user\n<audio_patch><|im_end|>\n<|im_start|>assistant\n"
|
||||
)
|
||||
|
||||
# Load audio
|
||||
if audio_path:
|
||||
if not os.path.exists(audio_path):
|
||||
raise FileNotFoundError(f"Audio file not found: {audio_path}")
|
||||
audio_signal, sr = librosa.load(audio_path, sr=sampling_rate)
|
||||
audio_data = (audio_signal.astype(np.float32), sr)
|
||||
else:
|
||||
# Use default test audio
|
||||
audio_data = AudioAsset("mary_had_lamb").audio_and_sample_rate
|
||||
# Resample to 16kHz if needed
|
||||
if audio_data[1] != sampling_rate:
|
||||
audio_signal = librosa.resample(audio_data[0], orig_sr=audio_data[1], target_sr=sampling_rate)
|
||||
audio_data = (audio_signal.astype(np.float32), sampling_rate)
|
||||
|
||||
return QueryResult(
|
||||
inputs={
|
||||
"prompt": prompt,
|
||||
"multi_modal_data": {
|
||||
"audio": audio_data,
|
||||
},
|
||||
},
|
||||
limit_mm_per_prompt={"audio": 1},
|
||||
)
|
||||
|
||||
|
||||
def get_text_to_audio_query(
|
||||
text: str | None = None,
|
||||
sampling_rate: int = 16000,
|
||||
) -> QueryResult:
|
||||
"""
|
||||
Text-to-Speech (TTS) - Convert text to audio.
|
||||
|
||||
Args:
|
||||
text: Text to synthesize
|
||||
sampling_rate: Target sampling rate (16kHz for Step-Audio2)
|
||||
|
||||
Returns:
|
||||
QueryResult with text prompt and speaker wav path
|
||||
|
||||
Note:
|
||||
For audio generation, the prompt must end with "<tts_start>"
|
||||
to signal the model to generate audio tokens instead of just text.
|
||||
"""
|
||||
if text is None:
|
||||
text = "Hello, this is a test of Step Audio 2 text to speech synthesis."
|
||||
|
||||
prompt = (
|
||||
"<|im_start|>system\n"
|
||||
"请逐字朗读用户提供的文本,不要改写或补充。<|im_end|>\n"
|
||||
"<|im_start|>user\n"
|
||||
f"{text}<|im_end|>\n"
|
||||
"<|im_start|>assistant\n"
|
||||
"<tts_start>"
|
||||
)
|
||||
|
||||
inputs = {
|
||||
"prompt": prompt,
|
||||
}
|
||||
|
||||
return QueryResult(
|
||||
inputs=inputs,
|
||||
limit_mm_per_prompt={},
|
||||
)
|
||||
|
||||
|
||||
def get_audio_to_audio_query(
|
||||
audio_path: str | None = None,
|
||||
question: str | None = None,
|
||||
sampling_rate: int = 16000,
|
||||
) -> QueryResult:
|
||||
"""
|
||||
Audio-to-Audio - Voice conversion/cloning.
|
||||
|
||||
Args:
|
||||
audio_path: Path to source audio file
|
||||
question: Question/instruction about the audio
|
||||
sampling_rate: Target sampling rate (16kHz for Step-Audio2)
|
||||
|
||||
Returns:
|
||||
QueryResult with audio input
|
||||
|
||||
Note:
|
||||
This mode processes input audio and generates output audio.
|
||||
Speaker voice is controlled by STEP_AUDIO2_DEFAULT_PROMPT_WAV env var.
|
||||
"""
|
||||
if question is None:
|
||||
question = "请仔细聆听这段语音,然后复述其内容。"
|
||||
|
||||
prompt = (
|
||||
"<|im_start|>system\n"
|
||||
f"{question}<|im_end|>\n"
|
||||
"<|im_start|>user\n"
|
||||
"<audio_patch><|im_end|>\n"
|
||||
"<|im_start|>assistant\n"
|
||||
"<tts_start>"
|
||||
)
|
||||
|
||||
# Load source audio
|
||||
if audio_path:
|
||||
if not os.path.exists(audio_path):
|
||||
raise FileNotFoundError(f"Audio file not found: {audio_path}")
|
||||
audio_signal, sr = librosa.load(audio_path, sr=sampling_rate)
|
||||
audio_data = (audio_signal.astype(np.float32), sr)
|
||||
|
||||
else:
|
||||
audio_data = AudioAsset("mary_had_lamb").audio_and_sample_rate
|
||||
if audio_data[1] != sampling_rate:
|
||||
audio_signal = librosa.resample(audio_data[0], orig_sr=audio_data[1], target_sr=sampling_rate)
|
||||
audio_data = (audio_signal.astype(np.float32), sampling_rate)
|
||||
|
||||
return QueryResult(
|
||||
inputs={
|
||||
"prompt": prompt,
|
||||
"multi_modal_data": {
|
||||
"audio": audio_data,
|
||||
},
|
||||
},
|
||||
limit_mm_per_prompt={"audio": 1},
|
||||
)
|
||||
|
||||
|
||||
query_map = {
|
||||
"audio_to_text": get_audio_to_text_query,
|
||||
"text_to_audio": get_text_to_audio_query,
|
||||
"audio_to_audio": get_audio_to_audio_query,
|
||||
}
|
||||
|
||||
|
||||
def main(args):
|
||||
# Use local model path or HuggingFace model name
|
||||
if not args.model:
|
||||
sys.exit(1)
|
||||
|
||||
model_name = args.model
|
||||
|
||||
# Check if it's a local path
|
||||
if os.path.isdir(model_name):
|
||||
# Verify essential files exist
|
||||
config_path = os.path.join(model_name, "config.json")
|
||||
if not os.path.exists(config_path):
|
||||
sys.exit(1)
|
||||
|
||||
# Get query configuration
|
||||
query_func = query_map[args.query_type]
|
||||
|
||||
# Build query based on type
|
||||
if args.query_type == "audio_to_text":
|
||||
query_result = query_func(
|
||||
audio_path=args.audio_path,
|
||||
question=args.question,
|
||||
sampling_rate=args.sampling_rate,
|
||||
)
|
||||
elif args.query_type == "text_to_audio":
|
||||
query_result = query_func(
|
||||
text=args.text,
|
||||
sampling_rate=args.sampling_rate,
|
||||
)
|
||||
elif args.query_type == "audio_to_audio":
|
||||
query_result = query_func(
|
||||
audio_path=args.audio_path,
|
||||
question=args.question,
|
||||
sampling_rate=args.sampling_rate,
|
||||
)
|
||||
else:
|
||||
raise ValueError(f"Unknown query type: {args.query_type}")
|
||||
|
||||
# Initialize vLLM-Omni with Step-Audio2
|
||||
# Resolve stage config path
|
||||
if args.stage_configs_path:
|
||||
stage_config_path = args.stage_configs_path
|
||||
else:
|
||||
configs_dir = Path(__file__).parent.parent.parent.parent / "vllm_omni/model_executor/stage_configs"
|
||||
if args.query_type == "audio_to_text":
|
||||
# ASR only needs Thinker (Stage 0), no Token2Wav
|
||||
stage_config_path = str(configs_dir / "step_audio_2_asr.yaml")
|
||||
if not os.path.exists(stage_config_path):
|
||||
stage_config_path = str(configs_dir / "step_audio_2.yaml")
|
||||
else:
|
||||
# TTS/S2ST need both stages
|
||||
stage_config_path = str(configs_dir / "step_audio_2.yaml")
|
||||
|
||||
omni_llm = Omni(
|
||||
model=model_name,
|
||||
log_stats=args.enable_stats,
|
||||
log_file=("step_audio2_pipeline.log" if args.enable_stats else None),
|
||||
init_sleep_seconds=args.init_sleep_seconds,
|
||||
batch_timeout=args.batch_timeout,
|
||||
init_timeout=args.init_timeout,
|
||||
shm_threshold_bytes=args.shm_threshold_bytes,
|
||||
stage_configs_path=stage_config_path,
|
||||
worker_backend=args.worker_backend,
|
||||
ray_address=args.ray_address,
|
||||
)
|
||||
|
||||
# Configure sampling parameters for each stage
|
||||
# Stage 0 (Thinker): Generate text and audio tokens
|
||||
# Note: For audio generation tasks, we need to allow the model to generate audio tokens
|
||||
# Audio tokens are in range [151696, 158257], so we should not stop too early
|
||||
# Qwen EOS token is typically 151645 (<|im_end|>), but we want to allow audio generation
|
||||
# So we don't set stop_token_ids for audio tasks, but we do set it for text-only tasks
|
||||
stop_token_ids = None
|
||||
if args.query_type == "audio_to_text":
|
||||
# For ASR, stop at EOS token
|
||||
stop_token_ids = [151645] # Qwen EOS token <|im_end|>
|
||||
|
||||
# Adjust sampling parameters based on query type
|
||||
# For audio generation tasks, we need higher repetition_penalty to avoid text loops
|
||||
# and allow the model to transition to audio token generation
|
||||
repetition_penalty = 1.1 if args.query_type in ["text_to_audio", "audio_to_audio"] else 1.05
|
||||
|
||||
thinker_sampling_params = SamplingParams(
|
||||
temperature=0.7,
|
||||
top_p=0.9,
|
||||
top_k=-1,
|
||||
max_tokens=args.max_tokens,
|
||||
seed=SEED,
|
||||
detokenize=True,
|
||||
repetition_penalty=repetition_penalty,
|
||||
stop_token_ids=stop_token_ids,
|
||||
)
|
||||
|
||||
# Stage 1 (Token2Wav): Convert audio tokens to waveform
|
||||
# Note: This stage doesn't actually sample, it's deterministic generation
|
||||
token2wav_sampling_params = SamplingParams(
|
||||
temperature=0.0,
|
||||
top_p=1.0,
|
||||
top_k=-1,
|
||||
max_tokens=1,
|
||||
seed=SEED,
|
||||
detokenize=False,
|
||||
)
|
||||
|
||||
if args.query_type == "audio_to_text":
|
||||
# ASR: single stage, only Thinker
|
||||
sampling_params_list = [thinker_sampling_params]
|
||||
else:
|
||||
# TTS/S2ST: two stages
|
||||
sampling_params_list = [thinker_sampling_params, token2wav_sampling_params]
|
||||
|
||||
# Prepare prompts
|
||||
if args.num_prompts > 1:
|
||||
prompts = [query_result.inputs for _ in range(args.num_prompts)]
|
||||
else:
|
||||
prompts = [query_result.inputs]
|
||||
|
||||
# Run inference
|
||||
omni_outputs = omni_llm.generate(prompts, sampling_params_list)
|
||||
|
||||
# Create output directory
|
||||
output_dir = args.output_dir
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
|
||||
def _get_request_index(req_id: str, fallback: int) -> int:
|
||||
"""Parse request index from vLLM request_id.
|
||||
|
||||
vLLM may return IDs like "0_<uuid>". Use the leading integer if present,
|
||||
otherwise fall back to the loop index.
|
||||
"""
|
||||
try:
|
||||
return int(req_id)
|
||||
except (TypeError, ValueError):
|
||||
if isinstance(req_id, str):
|
||||
head = req_id.split("_", 1)[0]
|
||||
if head.isdigit():
|
||||
return int(head)
|
||||
return fallback
|
||||
|
||||
# Process outputs from each stage
|
||||
for stage_idx, stage_outputs in enumerate(omni_outputs):
|
||||
# request_output may be a single object or a list
|
||||
raw_output = stage_outputs.request_output
|
||||
outputs_list = raw_output if isinstance(raw_output, list) else [raw_output]
|
||||
|
||||
if stage_outputs.final_output_type == "text":
|
||||
# Stage 0 (Thinker) text output
|
||||
for i, output in enumerate(outputs_list):
|
||||
request_id = _get_request_index(output.request_id, i)
|
||||
text_output = output.outputs[0].text
|
||||
|
||||
# Save to file
|
||||
out_txt = os.path.join(output_dir, f"{request_id:05d}_text.txt")
|
||||
with open(out_txt, "w", encoding="utf-8") as f:
|
||||
f.write(f"Prompt:\n{prompts[request_id]['prompt']}\n\n")
|
||||
f.write(f"Output:\n{text_output}\n")
|
||||
print(f"Text output saved to: {out_txt}")
|
||||
print(f"Text: {text_output[:200]}")
|
||||
|
||||
elif stage_outputs.final_output_type == "audio":
|
||||
# Stage 1 (Token2Wav) audio output
|
||||
for i, output in enumerate(outputs_list):
|
||||
request_id = _get_request_index(output.request_id, i)
|
||||
|
||||
# Get audio tensor (24kHz)
|
||||
mm_out = {}
|
||||
if hasattr(output, "multimodal_output") and output.multimodal_output:
|
||||
mm_out = output.multimodal_output
|
||||
elif output.outputs and hasattr(output.outputs[0], "multimodal_output"):
|
||||
mm_out = output.outputs[0].multimodal_output or {}
|
||||
audio_tensor = None
|
||||
for key in ("audio", "wav", "waveform", "audio_pcm", "pcm", "model_outputs"):
|
||||
if key in mm_out and mm_out[key] is not None:
|
||||
audio_tensor = mm_out[key]
|
||||
break
|
||||
|
||||
if audio_tensor is not None:
|
||||
# Save audio file
|
||||
output_wav = os.path.join(output_dir, f"{request_id:05d}_output.wav")
|
||||
if isinstance(audio_tensor, list):
|
||||
chunks = []
|
||||
for chunk in audio_tensor:
|
||||
if chunk is None:
|
||||
continue
|
||||
if isinstance(chunk, torch.Tensor):
|
||||
chunk_np = chunk.detach().cpu().numpy()
|
||||
else:
|
||||
chunk_np = np.asarray(chunk)
|
||||
if chunk_np.size > 0:
|
||||
chunks.append(chunk_np)
|
||||
if not chunks:
|
||||
continue
|
||||
audio_numpy = np.concatenate(chunks, axis=-1)
|
||||
elif isinstance(audio_tensor, torch.Tensor):
|
||||
audio_numpy = audio_tensor.detach().cpu().numpy()
|
||||
else:
|
||||
audio_numpy = np.asarray(audio_tensor)
|
||||
sf.write(output_wav, audio_numpy, samplerate=24000)
|
||||
|
||||
|
||||
def parse_args():
|
||||
parser = FlexibleArgumentParser(description="Demo on using vLLM-Omni for offline inference with Step-Audio2")
|
||||
|
||||
# Model and config
|
||||
parser.add_argument(
|
||||
"--model",
|
||||
"-m",
|
||||
type=str,
|
||||
required=True,
|
||||
help=(
|
||||
"Model path (required). Can be:\n"
|
||||
" - Local path: /path/to/step-audio-2\n"
|
||||
" - HuggingFace ID: stepfun-ai/Step-Audio2-mini"
|
||||
),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--stage-configs-path",
|
||||
type=str,
|
||||
default=None,
|
||||
help="Path to stage config YAML file (default: use built-in step_audio_2.yaml)",
|
||||
)
|
||||
|
||||
# Query configuration
|
||||
parser.add_argument(
|
||||
"--query-type",
|
||||
"-q",
|
||||
type=str,
|
||||
default="audio_to_text",
|
||||
choices=query_map.keys(),
|
||||
help="Query type: audio_to_text (ASR), text_to_audio (TTS), audio_to_audio (voice conversion)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--audio-path",
|
||||
"-a",
|
||||
type=str,
|
||||
default=None,
|
||||
help="Path to input audio file (for audio_to_text and audio_to_audio)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--text",
|
||||
"-t",
|
||||
type=str,
|
||||
default=None,
|
||||
help="Text to synthesize (for text_to_audio mode)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--question",
|
||||
type=str,
|
||||
default=None,
|
||||
help="Question/instruction about the audio",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--sampling-rate",
|
||||
type=int,
|
||||
default=16000,
|
||||
help="Audio sampling rate for input (default: 16000 Hz)",
|
||||
)
|
||||
|
||||
# Generation parameters
|
||||
parser.add_argument(
|
||||
"--max-tokens",
|
||||
type=int,
|
||||
default=1024,
|
||||
help="Maximum tokens to generate in Thinker stage (default: 1024)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--num-prompts",
|
||||
type=int,
|
||||
default=1,
|
||||
help="Number of times to repeat the prompt (for testing)",
|
||||
)
|
||||
|
||||
# System configuration
|
||||
parser.add_argument(
|
||||
"--enable-stats",
|
||||
action="store_true",
|
||||
default=False,
|
||||
help="Enable detailed statistics logging",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--init-sleep-seconds",
|
||||
type=int,
|
||||
default=20,
|
||||
help="Sleep seconds after starting each stage (default: 20)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--batch-timeout",
|
||||
type=int,
|
||||
default=5,
|
||||
help="Batch timeout in seconds (default: 5)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--init-timeout",
|
||||
type=int,
|
||||
default=300,
|
||||
help="Initialization timeout in seconds (default: 300)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--shm-threshold-bytes",
|
||||
type=int,
|
||||
default=65536,
|
||||
help="Shared memory threshold in bytes (default: 65536)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--worker-backend",
|
||||
type=str,
|
||||
default="multi_process",
|
||||
choices=["multi_process", "ray"],
|
||||
help="Worker backend (default: multi_process)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--ray-address",
|
||||
type=str,
|
||||
default=None,
|
||||
help="Ray cluster address (for ray backend)",
|
||||
)
|
||||
|
||||
# Output
|
||||
parser.add_argument(
|
||||
"--output-dir",
|
||||
"-o",
|
||||
type=str,
|
||||
default="output_step_audio2",
|
||||
help="Output directory for generated files (default: output_step_audio2)",
|
||||
)
|
||||
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
args = parse_args()
|
||||
main(args)
|
||||
@@ -0,0 +1,193 @@
|
||||
# Step-Audio2 Online Serving
|
||||
|
||||
This directory contains examples for running Step-Audio2 with vLLM-Omni's online serving API.
|
||||
|
||||
## Installation
|
||||
|
||||
Please refer to [README.md](../../../README.md)
|
||||
|
||||
## Launch the Server
|
||||
|
||||
```bash
|
||||
# Async chunk mode (recommended — lower first-packet latency for TTS)
|
||||
vllm serve stepfun-ai/Step-Audio2-mini --omni --port 8092 \
|
||||
--stage-configs-path vllm_omni/model_executor/stage_configs/step_audio_2_async_chunk.yaml \
|
||||
--trust-remote-code --enforce-eager
|
||||
```
|
||||
|
||||
Sequential mode:
|
||||
```bash
|
||||
vllm serve stepfun-ai/Step-Audio2-mini --omni --port 8092 \
|
||||
--stage-configs-path vllm_omni/model_executor/stage_configs/step_audio_2.yaml \
|
||||
--trust-remote-code --enforce-eager
|
||||
```
|
||||
|
||||
With local model:
|
||||
```bash
|
||||
vllm serve /path/to/Step-Audio-2-mini --omni --port 8092 \
|
||||
--trust-remote-code --enforce-eager
|
||||
```
|
||||
|
||||
## Send Requests
|
||||
|
||||
### TTS via `/v1/audio/speech` (Recommended)
|
||||
|
||||
```bash
|
||||
cd examples/online_serving/step_audio2
|
||||
|
||||
# Python client
|
||||
python openai_speech_client.py --text "你好世界"
|
||||
|
||||
# With custom system prompt
|
||||
python openai_speech_client.py --text "Hello, how are you?" \
|
||||
--instructions "You are a friendly assistant."
|
||||
|
||||
# Save to specific file
|
||||
python openai_speech_client.py --text "你好世界" -o output.wav
|
||||
```
|
||||
|
||||
Or via curl:
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:8092/v1/audio/speech \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"model":"stepfun-ai/Step-Audio2-mini","input":"你好世界","voice":"default"}' \
|
||||
--output output.wav
|
||||
```
|
||||
|
||||
This endpoint bypasses the chat template and directly triggers TTS mode. It supports async chunk streaming for low first-packet latency.
|
||||
|
||||
**Note**: Speaker voice is controlled by `STEP_AUDIO2_DEFAULT_PROMPT_WAV` env var on the server side.
|
||||
|
||||
### Chat Completions (ASR / S2ST)
|
||||
|
||||
```bash
|
||||
# Audio to Text (ASR)
|
||||
python openai_chat_completion_client.py --query-type audio_to_text
|
||||
|
||||
# Audio to Audio (S2ST)
|
||||
python openai_chat_completion_client.py --query-type audio_to_audio --audio-path /path/to/input.wav
|
||||
```
|
||||
|
||||
| Argument | Description |
|
||||
|----------|-------------|
|
||||
| `--query-type`, `-q` | Query type: `audio_to_text`, `text_to_audio`, `audio_to_audio` |
|
||||
| `--audio-path`, `-a` | Path to input audio file (local or URL) |
|
||||
| `--text`, `-t` | Text to synthesize (for TTS mode) |
|
||||
| `--prompt`, `-p` | Custom prompt/question |
|
||||
| `--output-dir`, `-o` | Output directory for audio files (default: `output_online`) |
|
||||
| `--api-base` | API base URL (default: `http://localhost:8092/v1`) |
|
||||
|
||||
### Curl (Chat Completions)
|
||||
|
||||
```bash
|
||||
# Audio to Text
|
||||
bash run_curl.sh audio_to_text
|
||||
|
||||
# Text to Audio
|
||||
bash run_curl.sh text_to_audio
|
||||
|
||||
# Audio to Audio
|
||||
bash run_curl.sh audio_to_audio
|
||||
```
|
||||
|
||||
## Query Types
|
||||
|
||||
### 1. Audio to Text (ASR)
|
||||
|
||||
Transcribe audio to text.
|
||||
|
||||
```bash
|
||||
python openai_chat_completion_client.py \
|
||||
--query-type audio_to_text \
|
||||
--audio-path /path/to/speech.wav \
|
||||
--prompt "Transcribe this audio."
|
||||
```
|
||||
|
||||
### 2. Text to Audio (TTS)
|
||||
|
||||
Convert text to speech:
|
||||
|
||||
```bash
|
||||
# Via speech endpoint (recommended, returns WAV directly)
|
||||
python openai_speech_client.py --text "Hello, welcome to Step-Audio2."
|
||||
|
||||
# Via chat completions
|
||||
python openai_chat_completion_client.py \
|
||||
--query-type text_to_audio \
|
||||
--text "Hello, welcome to Step-Audio2."
|
||||
```
|
||||
|
||||
### 3. Audio to Audio (S2ST)
|
||||
|
||||
Process input audio and generate text transcription + audio output.
|
||||
|
||||
```bash
|
||||
python openai_chat_completion_client.py \
|
||||
--query-type audio_to_audio \
|
||||
--audio-path /path/to/source.wav
|
||||
```
|
||||
|
||||
## Output
|
||||
|
||||
- **Text output**: Printed to console
|
||||
- **Audio output**: Saved to `output_online/audio_0.wav` (24kHz WAV)
|
||||
|
||||
## API Format
|
||||
|
||||
Step-Audio2 uses the OpenAI-compatible chat completions API:
|
||||
|
||||
```json
|
||||
{
|
||||
"model": "stepfun-ai/Step-Audio2-mini",
|
||||
"messages": [
|
||||
{
|
||||
"role": "system",
|
||||
"content": [{"type": "text", "text": "Transcribe the audio."}]
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"type": "audio_url", "audio_url": {"url": "..."}},
|
||||
{"type": "text", "text": "Please transcribe."}
|
||||
]
|
||||
}
|
||||
],
|
||||
"sampling_params_list": [
|
||||
{"temperature": 0.7, "max_tokens": 1024},
|
||||
{"temperature": 0.0, "max_tokens": 1}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Performance
|
||||
|
||||
### Async Chunk vs Sequential
|
||||
|
||||
Benchmark via `/v1/audio/speech` (4x RTX 3090, 10 prompts, concurrency=1):
|
||||
|
||||
| Mode | Mean TTFP | Mean E2E | Mean RTF |
|
||||
|------|-----------|----------|----------|
|
||||
| Sequential | 4316ms | 4316ms | 0.938 |
|
||||
| **Async Chunk** | **1437ms** | 4362ms | 0.949 |
|
||||
|
||||
Async chunk reduces TTFP by **67%** by streaming audio token chunks from Thinker to Token2Wav as they are generated. RTF < 1 in both modes (real-time capable).
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Server not responding
|
||||
- Check if the server is running: `curl http://localhost:8092/v1/models`
|
||||
- Verify the port number matches
|
||||
|
||||
### FileNotFoundError: prompt_wav file not found
|
||||
- Ensure `default_female.wav` exists at `{model_dir}/assets/default_female.wav`
|
||||
- Or set `STEP_AUDIO2_DEFAULT_PROMPT_WAV` environment variable when launching the server
|
||||
|
||||
### Audio not generated
|
||||
- For TTS, use the `/v1/audio/speech` endpoint (recommended) or `openai_speech_client.py`
|
||||
- For chat completions TTS, ensure the prompt ends with `<tts_start>`
|
||||
- Check server logs for errors
|
||||
|
||||
### Out of memory
|
||||
- Reduce `gpu_memory_utilization` in stage configs
|
||||
- Use a smaller batch size
|
||||
@@ -0,0 +1,342 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
OpenAI-compatible client for Step-Audio2 online serving.
|
||||
|
||||
Step-Audio2 is a two-stage model:
|
||||
- Stage 0 (Thinker): Audio understanding -> Text + Audio tokens
|
||||
- Stage 1 (Token2Wav): Audio tokens -> Waveform (24kHz)
|
||||
|
||||
Usage examples:
|
||||
# Start server first:
|
||||
vllm serve stepfun-ai/Step-Audio2-mini --omni --port 8092
|
||||
|
||||
# Audio to text (ASR)
|
||||
python openai_chat_completion_client.py --query-type audio_to_text
|
||||
|
||||
# Text to audio (TTS)
|
||||
python openai_chat_completion_client.py --query-type text_to_audio --text "Hello world"
|
||||
|
||||
# Audio to audio (Voice conversion)
|
||||
python openai_chat_completion_client.py --query-type audio_to_audio --audio-path input.wav
|
||||
"""
|
||||
|
||||
import base64
|
||||
import logging
|
||||
import os
|
||||
|
||||
import requests
|
||||
from openai import OpenAI
|
||||
from vllm.assets.audio import AudioAsset
|
||||
from vllm.utils.argparse_utils import FlexibleArgumentParser
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
SEED = 42
|
||||
|
||||
|
||||
def encode_base64_content_from_file(file_path: str) -> str:
|
||||
"""Encode a local file to base64 format."""
|
||||
with open(file_path, "rb") as f:
|
||||
return base64.b64encode(f.read()).decode("utf-8")
|
||||
|
||||
|
||||
def encode_base64_content_from_url(url: str) -> str:
|
||||
"""Encode content from URL to base64 format."""
|
||||
with requests.get(url) as response:
|
||||
response.raise_for_status()
|
||||
return base64.b64encode(response.content).decode("utf-8")
|
||||
|
||||
|
||||
def get_audio_url(audio_path: str | None = None) -> str:
|
||||
"""Convert audio path to URL format for the API.
|
||||
|
||||
Args:
|
||||
audio_path: Local file path or URL. If None, uses default test audio.
|
||||
|
||||
Returns:
|
||||
Audio URL (either original URL or base64 data URL)
|
||||
"""
|
||||
if not audio_path:
|
||||
return AudioAsset("mary_had_lamb").url
|
||||
|
||||
if audio_path.startswith(("http://", "https://")):
|
||||
return audio_path
|
||||
|
||||
if not os.path.exists(audio_path):
|
||||
raise FileNotFoundError(f"Audio file not found: {audio_path}")
|
||||
|
||||
# Detect MIME type
|
||||
audio_path_lower = audio_path.lower()
|
||||
if audio_path_lower.endswith(".wav"):
|
||||
mime_type = "audio/wav"
|
||||
elif audio_path_lower.endswith((".mp3", ".mpeg")):
|
||||
mime_type = "audio/mpeg"
|
||||
elif audio_path_lower.endswith(".ogg"):
|
||||
mime_type = "audio/ogg"
|
||||
elif audio_path_lower.endswith(".flac"):
|
||||
mime_type = "audio/flac"
|
||||
else:
|
||||
mime_type = "audio/wav"
|
||||
|
||||
audio_base64 = encode_base64_content_from_file(audio_path)
|
||||
return f"data:{mime_type};base64,{audio_base64}"
|
||||
|
||||
|
||||
def get_audio_to_text_query(
|
||||
audio_path: str | None = None,
|
||||
custom_prompt: str | None = None,
|
||||
) -> dict:
|
||||
"""Build query for Audio-to-Text (ASR) mode."""
|
||||
question = custom_prompt or "Please transcribe the audio content."
|
||||
audio_url = get_audio_url(audio_path)
|
||||
|
||||
return {
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"type": "audio_url", "audio_url": {"url": audio_url}},
|
||||
{"type": "text", "text": question},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def get_text_to_audio_query(
|
||||
text: str | None = None,
|
||||
custom_prompt: str | None = None,
|
||||
) -> dict:
|
||||
"""Build query for Text-to-Audio (TTS) mode.
|
||||
|
||||
Returns a list of messages: user message + assistant message with <tts_start>.
|
||||
The assistant message triggers TTS mode and must be used with
|
||||
continue_final_message=True so the chat template does not append <|im_end|>.
|
||||
"""
|
||||
text_to_speak = text or "Hello, this is a test of Step Audio 2 text to speech."
|
||||
|
||||
return [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [{"type": "text", "text": text_to_speak}],
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "<tts_start>",
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def get_audio_to_audio_query(
|
||||
audio_path: str | None = None,
|
||||
custom_prompt: str | None = None,
|
||||
) -> dict:
|
||||
"""Build query for Audio-to-Audio (S2ST) mode.
|
||||
|
||||
Returns a list of messages: user message (with audio) + assistant message
|
||||
with <tts_start>. Must be used with continue_final_message=True.
|
||||
"""
|
||||
question = custom_prompt or "Please listen to this audio and repeat its content."
|
||||
audio_url = get_audio_url(audio_path)
|
||||
|
||||
return [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"type": "audio_url", "audio_url": {"url": audio_url}},
|
||||
{"type": "text", "text": question},
|
||||
],
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "<tts_start>",
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def get_system_prompt(query_type: str) -> dict:
|
||||
"""Get system prompt based on query type."""
|
||||
if query_type == "audio_to_text":
|
||||
system_text = "You are a speech recognition assistant. Transcribe the audio accurately."
|
||||
elif query_type == "text_to_audio":
|
||||
system_text = "You are a text-to-speech assistant. Read the text aloud exactly as provided."
|
||||
else: # audio_to_audio
|
||||
system_text = "You are an audio processing assistant. Listen and repeat the audio content."
|
||||
|
||||
return {
|
||||
"role": "system",
|
||||
"content": [{"type": "text", "text": system_text}],
|
||||
}
|
||||
|
||||
|
||||
QUERY_MAP = {
|
||||
"audio_to_text": get_audio_to_text_query,
|
||||
"text_to_audio": get_text_to_audio_query,
|
||||
"audio_to_audio": get_audio_to_audio_query,
|
||||
}
|
||||
|
||||
|
||||
def run_step_audio2(args) -> None:
|
||||
"""Run Step-Audio2 inference via OpenAI-compatible API."""
|
||||
|
||||
# Initialize OpenAI client
|
||||
client = OpenAI(
|
||||
api_key="EMPTY",
|
||||
base_url=args.api_base,
|
||||
)
|
||||
|
||||
model_name = args.model
|
||||
|
||||
# Sampling parameters for each stage
|
||||
thinker_sampling_params = {
|
||||
"temperature": 0.7,
|
||||
"top_p": 0.9,
|
||||
"top_k": -1,
|
||||
"max_tokens": args.max_tokens,
|
||||
"seed": SEED,
|
||||
"detokenize": True,
|
||||
"repetition_penalty": 1.1 if args.query_type != "audio_to_text" else 1.05,
|
||||
}
|
||||
|
||||
# For ASR, stop at EOS token
|
||||
if args.query_type == "audio_to_text":
|
||||
thinker_sampling_params["stop_token_ids"] = [151645]
|
||||
|
||||
token2wav_sampling_params = {
|
||||
"temperature": 0.0,
|
||||
"top_p": 1.0,
|
||||
"top_k": -1,
|
||||
"max_tokens": 1,
|
||||
"seed": SEED,
|
||||
"detokenize": False,
|
||||
}
|
||||
|
||||
sampling_params_list = [
|
||||
thinker_sampling_params,
|
||||
token2wav_sampling_params,
|
||||
]
|
||||
|
||||
# Build query based on type
|
||||
query_func = QUERY_MAP[args.query_type]
|
||||
if args.query_type == "audio_to_text":
|
||||
user_message = query_func(audio_path=args.audio_path, custom_prompt=args.prompt)
|
||||
elif args.query_type == "text_to_audio":
|
||||
user_message = query_func(text=args.text, custom_prompt=args.prompt)
|
||||
else: # audio_to_audio
|
||||
user_message = query_func(audio_path=args.audio_path, custom_prompt=args.prompt)
|
||||
|
||||
system_message = get_system_prompt(args.query_type)
|
||||
|
||||
logger.info(f"Query type: {args.query_type}")
|
||||
logger.info(f"Model: {model_name}")
|
||||
logger.info("Sending request to server...")
|
||||
|
||||
# Build messages list.
|
||||
# TTS and S2ST return a list of messages (user + assistant with <tts_start>);
|
||||
# ASR returns a single user message dict.
|
||||
if isinstance(user_message, list):
|
||||
messages = [system_message] + user_message
|
||||
else:
|
||||
messages = [system_message, user_message]
|
||||
|
||||
# For TTS/S2ST, use continue_final_message so <tts_start> in the
|
||||
# assistant turn is not followed by <|im_end|>.
|
||||
extra_body: dict = {"sampling_params_list": sampling_params_list}
|
||||
if args.query_type in ("text_to_audio", "audio_to_audio"):
|
||||
extra_body["continue_final_message"] = True
|
||||
extra_body["add_generation_prompt"] = False
|
||||
|
||||
# Send request
|
||||
chat_completion = client.chat.completions.create(
|
||||
messages=messages,
|
||||
model=model_name,
|
||||
extra_body=extra_body,
|
||||
)
|
||||
|
||||
# Process response
|
||||
os.makedirs(args.output_dir, exist_ok=True)
|
||||
|
||||
audio_count = 0
|
||||
for choice in chat_completion.choices:
|
||||
if choice.message.audio:
|
||||
# Audio response
|
||||
audio_data = base64.b64decode(choice.message.audio.data)
|
||||
audio_file = os.path.join(args.output_dir, f"audio_{audio_count}.wav")
|
||||
with open(audio_file, "wb") as f:
|
||||
f.write(audio_data)
|
||||
logger.info(f"Audio saved to: {audio_file}")
|
||||
audio_count += 1
|
||||
|
||||
if choice.message.content:
|
||||
# Text response
|
||||
logger.info(f"Text output: {choice.message.content}")
|
||||
|
||||
if audio_count == 0 and args.query_type != "audio_to_text":
|
||||
logger.warning("No audio output received. Check server logs for details.")
|
||||
|
||||
logger.info("Done!")
|
||||
|
||||
|
||||
def parse_args():
|
||||
parser = FlexibleArgumentParser(description="OpenAI-compatible client for Step-Audio2 online serving")
|
||||
|
||||
parser.add_argument(
|
||||
"--query-type",
|
||||
"-q",
|
||||
type=str,
|
||||
default="audio_to_text",
|
||||
choices=QUERY_MAP.keys(),
|
||||
help="Query type: audio_to_text (ASR), text_to_audio (TTS), audio_to_audio",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--audio-path",
|
||||
"-a",
|
||||
type=str,
|
||||
default=None,
|
||||
help="Path to input audio file (local path or URL)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--text",
|
||||
"-t",
|
||||
type=str,
|
||||
default=None,
|
||||
help="Text to synthesize (for text_to_audio mode)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--prompt",
|
||||
"-p",
|
||||
type=str,
|
||||
default=None,
|
||||
help="Custom prompt/question",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--model",
|
||||
"-m",
|
||||
type=str,
|
||||
default="stepfun-ai/Step-Audio2-mini",
|
||||
help="Model name",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--api-base",
|
||||
type=str,
|
||||
default="http://localhost:8092/v1",
|
||||
help="API base URL",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--max-tokens",
|
||||
type=int,
|
||||
default=1024,
|
||||
help="Maximum tokens for Thinker stage",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output-dir",
|
||||
"-o",
|
||||
type=str,
|
||||
default="output_online",
|
||||
help="Output directory for audio files",
|
||||
)
|
||||
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
args = parse_args()
|
||||
run_step_audio2(args)
|
||||
@@ -0,0 +1,130 @@
|
||||
"""OpenAI-compatible client for Step-Audio2 TTS via /v1/audio/speech endpoint.
|
||||
|
||||
Examples:
|
||||
# Basic TTS
|
||||
python openai_speech_client.py --text "你好世界"
|
||||
|
||||
# With custom system prompt
|
||||
python openai_speech_client.py --text "Hello, how are you?" \
|
||||
--instructions "You are a friendly assistant."
|
||||
|
||||
# Save to specific file
|
||||
python openai_speech_client.py --text "你好世界" -o output.wav
|
||||
"""
|
||||
|
||||
import argparse
|
||||
|
||||
import httpx
|
||||
|
||||
DEFAULT_API_BASE = "http://localhost:8092"
|
||||
DEFAULT_API_KEY = "EMPTY"
|
||||
|
||||
|
||||
def run_tts_generation(args) -> None:
|
||||
"""Run TTS generation via /v1/audio/speech API."""
|
||||
payload = {
|
||||
"model": args.model,
|
||||
"input": args.text,
|
||||
"voice": args.voice,
|
||||
"response_format": args.response_format,
|
||||
}
|
||||
|
||||
if args.instructions:
|
||||
payload["instructions"] = args.instructions
|
||||
|
||||
print(f"Model: {args.model}")
|
||||
print(f"Text: {args.text}")
|
||||
print(f"Voice: {args.voice}")
|
||||
print("Generating audio...")
|
||||
|
||||
api_url = f"{args.api_base}/v1/audio/speech"
|
||||
headers = {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": f"Bearer {args.api_key}",
|
||||
}
|
||||
|
||||
with httpx.Client(timeout=300.0) as client:
|
||||
response = client.post(api_url, json=payload, headers=headers)
|
||||
|
||||
if response.status_code != 200:
|
||||
print(f"Error: {response.status_code}")
|
||||
print(response.text)
|
||||
return
|
||||
|
||||
try:
|
||||
text = response.content.decode("utf-8")
|
||||
if text.startswith('{"error"'):
|
||||
print(f"Error: {text}")
|
||||
return
|
||||
except UnicodeDecodeError:
|
||||
pass
|
||||
|
||||
output_path = args.output or "tts_output.wav"
|
||||
with open(output_path, "wb") as f:
|
||||
f.write(response.content)
|
||||
print(f"Audio saved to: {output_path}")
|
||||
|
||||
|
||||
def parse_args():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Step-Audio2 TTS client via /v1/audio/speech",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
epilog=__doc__,
|
||||
)
|
||||
parser.add_argument(
|
||||
"--api-base",
|
||||
type=str,
|
||||
default=DEFAULT_API_BASE,
|
||||
help=f"API base URL (default: {DEFAULT_API_BASE})",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--api-key",
|
||||
type=str,
|
||||
default=DEFAULT_API_KEY,
|
||||
help="API key (default: EMPTY)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--model",
|
||||
"-m",
|
||||
type=str,
|
||||
default="stepfun-ai/Step-Audio2-mini",
|
||||
help="Model name/path",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--text",
|
||||
type=str,
|
||||
required=True,
|
||||
help="Text to synthesize",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--voice",
|
||||
type=str,
|
||||
default="default",
|
||||
help="Voice name (default: default)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--instructions",
|
||||
type=str,
|
||||
default=None,
|
||||
help="System prompt for the Thinker stage",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--response-format",
|
||||
type=str,
|
||||
default="wav",
|
||||
choices=["wav", "pcm"],
|
||||
help="Audio output format (default: wav)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output",
|
||||
"-o",
|
||||
type=str,
|
||||
default=None,
|
||||
help="Output audio file path (default: tts_output.wav)",
|
||||
)
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
args = parse_args()
|
||||
run_tts_generation(args)
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# Step-Audio2 curl client for online serving
|
||||
# Usage: bash run_curl.sh [audio_to_text|text_to_audio|audio_to_audio]
|
||||
|
||||
QUERY_TYPE="${1:-audio_to_text}"
|
||||
API_BASE="${API_BASE:-http://localhost:8092}"
|
||||
|
||||
# Validate query type
|
||||
if [[ ! "$QUERY_TYPE" =~ ^(audio_to_text|text_to_audio|audio_to_audio)$ ]]; then
|
||||
echo "Error: Invalid query type '$QUERY_TYPE'"
|
||||
echo "Usage: $0 [audio_to_text|text_to_audio|audio_to_audio]"
|
||||
echo " audio_to_text: Speech recognition (ASR)"
|
||||
echo " text_to_audio: Text-to-speech (TTS)"
|
||||
echo " audio_to_audio: Voice conversion"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
SEED=42
|
||||
|
||||
# Default test audio URL
|
||||
MARY_HAD_LAMB_URL="https://vllm-public-assets.s3.us-west-2.amazonaws.com/multimodal_asset/mary_had_lamb.ogg"
|
||||
|
||||
# Sampling parameters for Thinker stage
|
||||
thinker_sampling_params='{
|
||||
"temperature": 0.7,
|
||||
"top_p": 0.9,
|
||||
"top_k": -1,
|
||||
"max_tokens": 1024,
|
||||
"seed": 42,
|
||||
"detokenize": true,
|
||||
"repetition_penalty": 1.05
|
||||
}'
|
||||
|
||||
# Sampling parameters for Token2Wav stage
|
||||
token2wav_sampling_params='{
|
||||
"temperature": 0.0,
|
||||
"top_p": 1.0,
|
||||
"top_k": -1,
|
||||
"max_tokens": 1,
|
||||
"seed": 42,
|
||||
"detokenize": false
|
||||
}'
|
||||
|
||||
# Build request based on query type
|
||||
case "$QUERY_TYPE" in
|
||||
audio_to_text)
|
||||
system_content='[{"type": "text", "text": "You are a speech recognition assistant. Transcribe the audio accurately."}]'
|
||||
user_content='[
|
||||
{"type": "audio_url", "audio_url": {"url": "'"$MARY_HAD_LAMB_URL"'"}},
|
||||
{"type": "text", "text": "Please transcribe this audio."}
|
||||
]'
|
||||
# Add stop token for ASR
|
||||
thinker_sampling_params='{
|
||||
"temperature": 0.7,
|
||||
"top_p": 0.9,
|
||||
"top_k": -1,
|
||||
"max_tokens": 1024,
|
||||
"seed": 42,
|
||||
"detokenize": true,
|
||||
"repetition_penalty": 1.05,
|
||||
"stop_token_ids": [151645]
|
||||
}'
|
||||
;;
|
||||
text_to_audio)
|
||||
system_content='[{"type": "text", "text": "You are a text-to-speech assistant. Read the text aloud exactly as provided."}]'
|
||||
user_content='[
|
||||
{"type": "text", "text": "Hello, this is a test of Step Audio 2 text to speech synthesis.<tts_start>"}
|
||||
]'
|
||||
thinker_sampling_params='{
|
||||
"temperature": 0.7,
|
||||
"top_p": 0.9,
|
||||
"top_k": -1,
|
||||
"max_tokens": 1024,
|
||||
"seed": 42,
|
||||
"detokenize": true,
|
||||
"repetition_penalty": 1.1
|
||||
}'
|
||||
;;
|
||||
audio_to_audio)
|
||||
system_content='[{"type": "text", "text": "You are an audio processing assistant. Listen and repeat the audio content."}]'
|
||||
user_content='[
|
||||
{"type": "audio_url", "audio_url": {"url": "'"$MARY_HAD_LAMB_URL"'"}},
|
||||
{"type": "text", "text": "Please listen to this audio and repeat its content.<tts_start>"}
|
||||
]'
|
||||
thinker_sampling_params='{
|
||||
"temperature": 0.7,
|
||||
"top_p": 0.9,
|
||||
"top_k": -1,
|
||||
"max_tokens": 1024,
|
||||
"seed": 42,
|
||||
"detokenize": true,
|
||||
"repetition_penalty": 1.1
|
||||
}'
|
||||
;;
|
||||
esac
|
||||
|
||||
sampling_params_list='[
|
||||
'"$thinker_sampling_params"',
|
||||
'"$token2wav_sampling_params"'
|
||||
]'
|
||||
|
||||
echo "Query type: $QUERY_TYPE"
|
||||
echo "API base: $API_BASE"
|
||||
echo "Sending request..."
|
||||
echo ""
|
||||
|
||||
output=$(curl -sS -X POST "${API_BASE}/v1/chat/completions" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d @- <<EOF
|
||||
{
|
||||
"model": "stepfun-ai/Step-Audio2-mini",
|
||||
"sampling_params_list": $sampling_params_list,
|
||||
"messages": [
|
||||
{
|
||||
"role": "system",
|
||||
"content": $system_content
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": $user_content
|
||||
}
|
||||
]
|
||||
}
|
||||
EOF
|
||||
)
|
||||
|
||||
# Extract and display text content
|
||||
text_content=$(echo "$output" | jq -r '.choices[0].message.content // empty')
|
||||
if [[ -n "$text_content" ]]; then
|
||||
echo "Text output: $text_content"
|
||||
fi
|
||||
|
||||
# Check for audio content
|
||||
audio_data=$(echo "$output" | jq -r '.choices[0].message.audio.data // empty')
|
||||
if [[ -n "$audio_data" ]]; then
|
||||
echo "Audio output received (base64 encoded)"
|
||||
echo "To save audio, use the Python client or decode the base64 data"
|
||||
fi
|
||||
|
||||
# Check for errors
|
||||
error=$(echo "$output" | jq -r '.error // empty')
|
||||
if [[ -n "$error" ]]; then
|
||||
echo "Error: $error"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "Done!"
|
||||
Reference in new issue
Block a user