[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
@@ -53,6 +53,32 @@ _OMNI_MODELS = {
|
||||
"qwen3_omni_code2wav",
|
||||
"Qwen3OmniMoeCode2Wav",
|
||||
),
|
||||
# Step-Audio2 models
|
||||
"StepAudio2ForCausalLM": (
|
||||
"step_audio2",
|
||||
"step_audio2",
|
||||
"StepAudio2ForConditionalGeneration",
|
||||
),
|
||||
"StepAudio2ForConditionalGeneration": (
|
||||
"step_audio2",
|
||||
"step_audio2",
|
||||
"StepAudio2ForConditionalGeneration",
|
||||
),
|
||||
"StepAudio2ThinkerForConditionalGeneration": (
|
||||
"step_audio2",
|
||||
"step_audio2_thinker",
|
||||
"StepAudio2ThinkerForConditionalGeneration",
|
||||
),
|
||||
"StepAudio2Token2WavModel": (
|
||||
"step_audio2",
|
||||
"step_audio2_token2wav",
|
||||
"StepAudio2Token2WavForConditionalGeneration",
|
||||
),
|
||||
"StepAudio2Token2WavForConditionalGeneration": (
|
||||
"step_audio2",
|
||||
"step_audio2_token2wav",
|
||||
"StepAudio2Token2WavForConditionalGeneration",
|
||||
),
|
||||
"CosyVoice3Model": (
|
||||
"cosyvoice3",
|
||||
"cosyvoice3",
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
from .step_audio2 import StepAudio2ForConditionalGeneration
|
||||
|
||||
__all__ = ["StepAudio2ForConditionalGeneration"]
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,195 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.models.interfaces import SupportsMultiModal, SupportsPP
|
||||
from vllm.model_executor.models.utils import init_vllm_registered_model, maybe_prefix
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.sequence import IntermediateTensors
|
||||
|
||||
from .step_audio2_thinker import (
|
||||
StepAudio2DummyInputsBuilder,
|
||||
StepAudio2MultiModalProcessor,
|
||||
StepAudio2ProcessingInfo,
|
||||
)
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
@MULTIMODAL_REGISTRY.register_processor(
|
||||
StepAudio2MultiModalProcessor,
|
||||
info=StepAudio2ProcessingInfo,
|
||||
dummy_inputs=StepAudio2DummyInputsBuilder,
|
||||
)
|
||||
class StepAudio2ForConditionalGeneration(nn.Module, SupportsMultiModal, SupportsPP):
|
||||
"""
|
||||
Step-Audio2 Main Controller
|
||||
|
||||
Manages two-stage inference pipeline:
|
||||
- Stage 1 (Thinker): Audio understanding and token generation
|
||||
- Stage 2 (Token2Wav): Audio token to waveform synthesis
|
||||
|
||||
Usage:
|
||||
# Stage 1: Thinker
|
||||
model = StepAudio2ForConditionalGeneration(
|
||||
vllm_config=config,
|
||||
model_stage="thinker"
|
||||
)
|
||||
|
||||
# Stage 2: Token2Wav
|
||||
model = StepAudio2ForConditionalGeneration(
|
||||
vllm_config=config,
|
||||
model_stage="token2wav"
|
||||
)
|
||||
"""
|
||||
|
||||
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
|
||||
super().__init__()
|
||||
self.have_multimodal_outputs = True
|
||||
|
||||
config = vllm_config.model_config.hf_config
|
||||
multimodal_config = vllm_config.model_config.multimodal_config
|
||||
|
||||
self.config = config
|
||||
self.multimodal_config = multimodal_config
|
||||
self.vllm_config = vllm_config
|
||||
|
||||
raw_model_stage = vllm_config.model_config.model_stage
|
||||
# Normalise: "step_audio2_thinker" → "thinker"
|
||||
self.model_stage = "thinker" if raw_model_stage in ("thinker", "step_audio2_thinker") else raw_model_stage
|
||||
|
||||
if self.model_stage == "thinker":
|
||||
self.thinker = init_vllm_registered_model(
|
||||
vllm_config=vllm_config,
|
||||
prefix=maybe_prefix(prefix, "thinker"),
|
||||
hf_config=config,
|
||||
architectures=["StepAudio2ThinkerForConditionalGeneration"],
|
||||
)
|
||||
self.model = self.thinker
|
||||
self.token2wav = None
|
||||
|
||||
logger.info("Initialized Step-Audio2 Thinker (Stage 0)")
|
||||
|
||||
elif self.model_stage == "token2wav":
|
||||
self.thinker = None
|
||||
self.token2wav = init_vllm_registered_model(
|
||||
vllm_config=vllm_config,
|
||||
prefix=maybe_prefix(prefix, "token2wav"),
|
||||
hf_config=config,
|
||||
architectures=["StepAudio2Token2WavForConditionalGeneration"],
|
||||
)
|
||||
self.model = self.token2wav
|
||||
|
||||
logger.info("Initialized Step-Audio2 Token2Wav (Stage 1)")
|
||||
|
||||
else:
|
||||
raise ValueError(
|
||||
f"Invalid model_stage: {self.model_stage}. Must be 'thinker'/'step_audio2_thinker' or 'token2wav'"
|
||||
)
|
||||
|
||||
self.make_empty_intermediate_tensors = (
|
||||
self.thinker.make_empty_intermediate_tensors if self.model_stage == "thinker" else lambda: None
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def get_placeholder_str(cls, modality: str, i: int) -> str | None:
|
||||
"""Get placeholder string for a modality
|
||||
|
||||
Returns:
|
||||
For audio: "<audio_patch>" (matches processor's audio_token)
|
||||
"""
|
||||
if modality == "audio":
|
||||
return "<audio_patch>"
|
||||
return None
|
||||
|
||||
def get_language_model(self) -> nn.Module:
|
||||
"""Get the underlying language model."""
|
||||
if self.model_stage == "thinker":
|
||||
return self.thinker.get_language_model()
|
||||
# Token2Wav is not a real language model. Return the wrapper itself so
|
||||
# vLLM interface helpers resolve embed_input_ids() on the adapter layer.
|
||||
return self.token2wav
|
||||
|
||||
def get_multimodal_embeddings(self, **kwargs):
|
||||
"""Get multimodal embeddings - only used in Thinker stage."""
|
||||
if self.model_stage == "thinker":
|
||||
return self.thinker.get_multimodal_embeddings(**kwargs)
|
||||
return None
|
||||
|
||||
def get_input_embeddings(self, input_ids: torch.Tensor) -> torch.Tensor:
|
||||
"""Compatibility helper used by older call sites."""
|
||||
if self.model_stage == "thinker":
|
||||
return self.model.get_input_embeddings(input_ids)
|
||||
return self.model.embed_input_ids(input_ids)
|
||||
|
||||
def embed_input_ids(
|
||||
self,
|
||||
input_ids: torch.Tensor,
|
||||
multimodal_embeddings=None,
|
||||
is_multimodal=None,
|
||||
) -> torch.Tensor:
|
||||
"""Explicit vLLM embedding hook for both stages."""
|
||||
if self.model_stage == "token2wav":
|
||||
return self.model.embed_input_ids(input_ids)
|
||||
return self.model.get_input_embeddings(input_ids, multimodal_embeddings)
|
||||
|
||||
def embed_multimodal(self, **kwargs):
|
||||
"""Delegate multimodal embedding to thinker stage only."""
|
||||
if self.model_stage == "thinker":
|
||||
return self.model.embed_multimodal(**kwargs)
|
||||
return None
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
intermediate_tensors: IntermediateTensors | None = None,
|
||||
inputs_embeds: torch.Tensor | None = None,
|
||||
**kwargs,
|
||||
):
|
||||
"""
|
||||
Forward pass through the model
|
||||
|
||||
For Thinker:
|
||||
Returns hidden states/logits
|
||||
For Token2Wav:
|
||||
Returns waveform
|
||||
"""
|
||||
return self.model.forward(
|
||||
input_ids=input_ids,
|
||||
positions=positions,
|
||||
intermediate_tensors=intermediate_tensors,
|
||||
inputs_embeds=inputs_embeds,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def compute_logits(self, hidden_states: torch.Tensor) -> torch.Tensor | None:
|
||||
"""Compute logits from hidden states"""
|
||||
return self.model.compute_logits(hidden_states)
|
||||
|
||||
def load_weights(self, weights):
|
||||
"""Load weights"""
|
||||
return self.model.load_weights(weights)
|
||||
|
||||
def move_submodules_to_devices(
|
||||
self,
|
||||
*,
|
||||
thinker_device: str | torch.device | None = None,
|
||||
token2wav_device: str | torch.device | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
Optionally move thinker/token2wav to different devices
|
||||
|
||||
Example:
|
||||
model.move_submodules_to_devices(
|
||||
thinker_device='cuda:0',
|
||||
token2wav_device='cuda:1',
|
||||
)
|
||||
"""
|
||||
if thinker_device is not None and self.thinker is not None:
|
||||
self.thinker.to(torch.device(thinker_device))
|
||||
logger.info(f"Moved Thinker to {thinker_device}")
|
||||
|
||||
if token2wav_device is not None and self.token2wav is not None:
|
||||
self.token2wav.to(torch.device(token2wav_device))
|
||||
logger.info(f"Moved Token2Wav to {token2wav_device}")
|
||||
@@ -0,0 +1,181 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""Step-Audio2 configuration constants - Single Source of Truth."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StepAudio2TokenConfig:
|
||||
"""
|
||||
Step-Audio2 token ID ranges and vocabulary configuration.
|
||||
|
||||
Token ID Layout (based on vocab_size=158720):
|
||||
- Text tokens: 0 - 151688 (standard Qwen tokenizer)
|
||||
- Special tokens: 151689 - 151695 (reserved)
|
||||
- Audio tokens: 151696 - 158257 (vocab size 6562)
|
||||
|
||||
These values are architecture constants for Step-Audio2 and do not
|
||||
change between model variants (mini/7B).
|
||||
"""
|
||||
|
||||
# Text token range
|
||||
text_max: int = 151688
|
||||
"""Maximum text token ID (inclusive)"""
|
||||
|
||||
# Audio token range (absolute IDs in full vocabulary)
|
||||
audio_start: int = 151696
|
||||
"""First audio token ID in absolute vocabulary"""
|
||||
|
||||
audio_vocab_size: int = 6562
|
||||
"""Total number of audio tokens"""
|
||||
|
||||
audio_eos: int = 6561
|
||||
"""Audio EOS token ID (relative to audio_start, used for padding)"""
|
||||
|
||||
# Special tokens
|
||||
audio_patch_token_id: int = 151690
|
||||
"""<audio_patch> placeholder token ID"""
|
||||
|
||||
@property
|
||||
def audio_end(self) -> int:
|
||||
"""Last audio token ID in absolute vocabulary"""
|
||||
return self.audio_start + self.audio_vocab_size - 1
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StepAudio2EncoderConfig:
|
||||
"""
|
||||
Step-Audio2 audio encoder architecture configuration.
|
||||
|
||||
These values define the encoder structure and should match your model weights.
|
||||
"""
|
||||
|
||||
# Mel spectrogram parameters
|
||||
n_mels: int = 128
|
||||
"""Number of mel frequency bins"""
|
||||
|
||||
# Encoder architecture
|
||||
n_audio_ctx: int = 1500
|
||||
"""Audio context length (max sequence length)"""
|
||||
|
||||
n_audio_state: int = 512
|
||||
"""Audio encoder hidden state dimension"""
|
||||
|
||||
n_audio_head: int = 8
|
||||
"""Number of attention heads in encoder"""
|
||||
|
||||
n_audio_layer: int = 6
|
||||
"""Number of encoder layers"""
|
||||
|
||||
# Adapter parameters
|
||||
kernel_size: int = 3
|
||||
"""Convolution kernel size for adapter"""
|
||||
|
||||
adapter_stride: int = 2
|
||||
"""Stride for adapter convolution (downsampling factor)"""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StepAudio2Token2WavConfig:
|
||||
"""Token2Wav synthesis configuration."""
|
||||
|
||||
n_timesteps: int = 10
|
||||
"""Number of diffusion timesteps for flow model inference"""
|
||||
|
||||
sample_rate: int = 24000
|
||||
"""Output audio sample rate"""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StepAudio2StreamConfig:
|
||||
"""Streaming (chunked) inference configuration for Token2Wav."""
|
||||
|
||||
chunk_size: int = 25
|
||||
"""Number of audio tokens consumed per chunk."""
|
||||
|
||||
pre_lookahead_len: int = 3
|
||||
"""Conformer encoder lookahead tokens beyond the chunk boundary."""
|
||||
|
||||
up_rate: int = 2
|
||||
"""Token-to-mel upsampling rate inside the flow model."""
|
||||
|
||||
mel_cache_len: int = 8
|
||||
"""HiFT overlap mel frames (160 ms at 50 Hz mel rate)."""
|
||||
|
||||
n_timesteps: int = 10
|
||||
"""Flow model ODE solver steps."""
|
||||
|
||||
estimator_cache_keep: int = 100
|
||||
"""Attention-cache pruning window for the flow estimator."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StepAudio2ModelConfig:
|
||||
"""
|
||||
Step-Audio2 complete model configuration - Single Source of Truth.
|
||||
|
||||
All architecture constants are defined here. The stage YAML and model config.json
|
||||
can override these values if needed, but this serves as the default.
|
||||
"""
|
||||
|
||||
# LLM configuration (Qwen2)
|
||||
hidden_size: int = 4096
|
||||
"""LLM hidden dimension (Qwen2-7B: 4096, Qwen2-1.5B: 1536, Qwen2-0.5B: 896)"""
|
||||
|
||||
# Token configuration
|
||||
text_max: int = 151688
|
||||
audio_start: int = 151696
|
||||
audio_vocab_size: int = 6562
|
||||
audio_eos: int = 6561
|
||||
audio_patch_token_id: int = 151690
|
||||
|
||||
# Encoder configuration
|
||||
n_mels: int = 128
|
||||
n_audio_ctx: int = 1500
|
||||
n_audio_state: int = 512
|
||||
n_audio_head: int = 8
|
||||
n_audio_layer: int = 6
|
||||
kernel_size: int = 3
|
||||
adapter_stride: int = 2
|
||||
|
||||
|
||||
# Default configuration instances
|
||||
DEFAULT_TOKEN_CONFIG = StepAudio2TokenConfig()
|
||||
DEFAULT_ENCODER_CONFIG = StepAudio2EncoderConfig()
|
||||
DEFAULT_TOKEN2WAV_CONFIG = StepAudio2Token2WavConfig()
|
||||
DEFAULT_STREAM_CONFIG = StepAudio2StreamConfig()
|
||||
DEFAULT_MODEL_CONFIG = StepAudio2ModelConfig()
|
||||
|
||||
STREAM_SOURCE_CACHE_LEN = DEFAULT_STREAM_CONFIG.mel_cache_len * 480 # 3840 samples
|
||||
|
||||
# Export constants for backward compatibility
|
||||
STEP_AUDIO2_TEXT_MAX = DEFAULT_TOKEN_CONFIG.text_max
|
||||
STEP_AUDIO2_AUDIO_START = DEFAULT_TOKEN_CONFIG.audio_start
|
||||
STEP_AUDIO2_AUDIO_VOCAB_SIZE = DEFAULT_TOKEN_CONFIG.audio_vocab_size
|
||||
STEP_AUDIO2_AUDIO_EOS = DEFAULT_TOKEN_CONFIG.audio_eos
|
||||
STEP_AUDIO2_AUDIO_PATCH_TOKEN_ID = DEFAULT_TOKEN_CONFIG.audio_patch_token_id
|
||||
STEP_AUDIO2_AUDIO_END = DEFAULT_TOKEN_CONFIG.audio_end
|
||||
|
||||
# Default prompt wav path for Token2Wav (can be overridden by env var)
|
||||
STEP_AUDIO2_DEFAULT_PROMPT_WAV = "default_female.wav"
|
||||
|
||||
|
||||
__all__ = [
|
||||
"StepAudio2TokenConfig",
|
||||
"StepAudio2EncoderConfig",
|
||||
"StepAudio2Token2WavConfig",
|
||||
"StepAudio2StreamConfig",
|
||||
"StepAudio2ModelConfig",
|
||||
"DEFAULT_TOKEN_CONFIG",
|
||||
"DEFAULT_ENCODER_CONFIG",
|
||||
"DEFAULT_TOKEN2WAV_CONFIG",
|
||||
"DEFAULT_STREAM_CONFIG",
|
||||
"DEFAULT_MODEL_CONFIG",
|
||||
"STREAM_SOURCE_CACHE_LEN",
|
||||
"STEP_AUDIO2_TEXT_MAX",
|
||||
"STEP_AUDIO2_AUDIO_START",
|
||||
"STEP_AUDIO2_AUDIO_VOCAB_SIZE",
|
||||
"STEP_AUDIO2_AUDIO_EOS",
|
||||
"STEP_AUDIO2_AUDIO_PATCH_TOKEN_ID",
|
||||
"STEP_AUDIO2_AUDIO_END",
|
||||
]
|
||||
@@ -0,0 +1,898 @@
|
||||
"""
|
||||
Step-Audio2 Thinker - Stage 1 LLM for Audio Understanding
|
||||
|
||||
This file contains:
|
||||
- Audio encoder components (AudioEncoder, Adaptor)
|
||||
- Audio preprocessing utilities (mel-spectrogram extraction)
|
||||
- Multi-modal processing (StepAudio2MultiModalProcessor)
|
||||
- Main thinker model (StepAudio2ThinkerForConditionalGeneration)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable, Mapping, Sequence
|
||||
from typing import TYPE_CHECKING, Any, TypedDict
|
||||
|
||||
import librosa # noqa: TID251
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
from torch.nn.utils.rnn import pad_sequence
|
||||
from transformers import AutoTokenizer
|
||||
from transformers.processing_utils import ProcessorMixin
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.inputs import MultiModalDataDict
|
||||
from vllm.model_executor.models.interfaces import SupportsMultiModal, SupportsPP
|
||||
from vllm.model_executor.models.utils import (
|
||||
_merge_multimodal_embeddings,
|
||||
flatten_bn,
|
||||
init_vllm_registered_model,
|
||||
maybe_prefix,
|
||||
)
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.multimodal.inputs import (
|
||||
MultiModalFieldConfig,
|
||||
MultiModalKwargsItems,
|
||||
NestedTensors,
|
||||
)
|
||||
from vllm.multimodal.parse import MultiModalDataItems, MultiModalDataParser
|
||||
from vllm.multimodal.processing import (
|
||||
BaseDummyInputsBuilder,
|
||||
BaseMultiModalProcessor,
|
||||
BaseProcessingInfo,
|
||||
PromptReplacement,
|
||||
PromptUpdate,
|
||||
)
|
||||
from vllm.sequence import IntermediateTensors
|
||||
|
||||
from vllm_omni.model_executor.models.output_templates import OmniOutput
|
||||
from vllm_omni.model_executor.models.step_audio2.step_audio2_constants import (
|
||||
DEFAULT_MODEL_CONFIG,
|
||||
DEFAULT_TOKEN_CONFIG,
|
||||
STEP_AUDIO2_AUDIO_PATCH_TOKEN_ID,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
pass
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Audio Preprocessing Utilities
|
||||
# ============================================================================
|
||||
|
||||
|
||||
def _mel_filters(n_mels: int) -> torch.Tensor:
|
||||
"""Generate mel filter banks"""
|
||||
assert n_mels in {80, 128}, f"Unsupported n_mels: {n_mels}"
|
||||
return torch.from_numpy(librosa.filters.mel(sr=16000, n_fft=400, n_mels=n_mels))
|
||||
|
||||
|
||||
def _normalize_audio(audio: Any) -> torch.Tensor:
|
||||
"""Normalize audio to torch.Tensor"""
|
||||
if isinstance(audio, tuple):
|
||||
audio = audio[0]
|
||||
if isinstance(audio, np.ndarray):
|
||||
audio = torch.from_numpy(audio)
|
||||
elif not torch.is_tensor(audio):
|
||||
audio = torch.tensor(audio, dtype=torch.float32)
|
||||
return audio.float()
|
||||
|
||||
|
||||
def log_mel_spectrogram(audio: Any, n_mels: int = 128, padding: int = 479) -> torch.Tensor:
|
||||
"""
|
||||
Convert audio to log mel-spectrogram
|
||||
|
||||
Args:
|
||||
audio: Audio waveform (any format)
|
||||
n_mels: Number of mel frequency bins (default: 128)
|
||||
padding: Right padding for STFT (default: 479)
|
||||
|
||||
Returns:
|
||||
Log mel-spectrogram tensor of shape (n_mels, T)
|
||||
"""
|
||||
audio = _normalize_audio(audio)
|
||||
if padding > 0:
|
||||
audio = F.pad(audio, (0, padding))
|
||||
window = torch.hann_window(400, device=audio.device)
|
||||
stft = torch.stft(audio, 400, 160, window=window, return_complex=True)
|
||||
magnitudes = stft[..., :-1].abs() ** 2
|
||||
filters = _mel_filters(n_mels).to(audio.device)
|
||||
mel_spec = filters @ magnitudes
|
||||
|
||||
log_spec = torch.clamp(mel_spec, min=1e-10).log10()
|
||||
log_spec = torch.maximum(log_spec, log_spec.max() - 8.0)
|
||||
log_spec = (log_spec + 4.0) / 4.0
|
||||
return log_spec
|
||||
|
||||
|
||||
def padding_mels(data: list[torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""
|
||||
Pad mel spectrograms to same length
|
||||
|
||||
Args:
|
||||
data: List of mel spectrograms, each of shape (n_mels, T)
|
||||
|
||||
Returns:
|
||||
padded_feats: Padded tensor of shape (batch, n_mels, max_T)
|
||||
feats_lengths: Lengths of each sequence
|
||||
"""
|
||||
feats_lengths = torch.tensor([s.size(1) - 2 for s in data], dtype=torch.int32)
|
||||
feats = [s.t() for s in data]
|
||||
padded_feats = pad_sequence(feats, batch_first=True, padding_value=0)
|
||||
return padded_feats.transpose(1, 2), feats_lengths
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Encoder Utilities
|
||||
# ============================================================================
|
||||
|
||||
|
||||
def make_non_pad_mask(lengths: torch.Tensor, max_len: int = 0) -> torch.Tensor:
|
||||
"""Create non-padding mask from lengths"""
|
||||
batch_size = lengths.size(0)
|
||||
max_len = max_len if max_len > 0 else lengths.max().item()
|
||||
seq_range = torch.arange(0, max_len, dtype=torch.int64, device=lengths.device)
|
||||
seq_range_expand = seq_range.unsqueeze(0).expand(batch_size, max_len)
|
||||
seq_length_expand = lengths.unsqueeze(-1)
|
||||
mask = seq_range_expand >= seq_length_expand
|
||||
return ~mask
|
||||
|
||||
|
||||
def mask_to_bias(mask: torch.Tensor, dtype: torch.dtype) -> torch.Tensor:
|
||||
"""Convert mask to attention bias"""
|
||||
assert mask.dtype == torch.bool
|
||||
assert dtype in [torch.float32, torch.bfloat16, torch.float16]
|
||||
mask = mask.to(dtype)
|
||||
mask = (1.0 - mask) * -1.0e10
|
||||
return mask
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Audio Encoder Components
|
||||
# ============================================================================
|
||||
|
||||
|
||||
class MultiHeadAttention(nn.Module):
|
||||
"""Multi-head attention for audio encoder"""
|
||||
|
||||
def __init__(self, n_state: int, n_head: int):
|
||||
super().__init__()
|
||||
self.n_head = n_head
|
||||
self.query = nn.Linear(n_state, n_state)
|
||||
self.key = nn.Linear(n_state, n_state, bias=False)
|
||||
self.value = nn.Linear(n_state, n_state)
|
||||
self.out = nn.Linear(n_state, n_state)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
mask: torch.Tensor | None = None,
|
||||
):
|
||||
q = self.query(x)
|
||||
k = self.key(x)
|
||||
v = self.value(x)
|
||||
|
||||
wv, qk = self.qkv_attention(q, k, v, mask)
|
||||
return self.out(wv), qk
|
||||
|
||||
def qkv_attention(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, mask: torch.Tensor | None = None):
|
||||
B, T, D = q.shape
|
||||
head_dim = D // self.n_head
|
||||
|
||||
# Reshape: (B, T, D) -> (B, n_head, T, head_dim)
|
||||
q = q.view(B, T, self.n_head, head_dim).transpose(1, 2)
|
||||
k = k.view(B, T, self.n_head, head_dim).transpose(1, 2)
|
||||
v = v.view(B, T, self.n_head, head_dim).transpose(1, 2)
|
||||
|
||||
# Use F.scaled_dot_product_attention
|
||||
# mask is additive bias (0 or -1e10), pass directly as attn_mask
|
||||
out = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)
|
||||
|
||||
# Reshape back: (B, n_head, T, head_dim) -> (B, T, D)
|
||||
out = out.transpose(1, 2).reshape(B, T, D)
|
||||
return out, None
|
||||
|
||||
|
||||
class ResidualAttentionBlock(nn.Module):
|
||||
"""Residual attention block for audio encoder"""
|
||||
|
||||
def __init__(self, n_state: int, n_head: int):
|
||||
super().__init__()
|
||||
|
||||
self.attn = MultiHeadAttention(n_state, n_head)
|
||||
self.attn_ln = nn.LayerNorm(n_state)
|
||||
|
||||
n_mlp = n_state * 4
|
||||
self.mlp = nn.Sequential(nn.Linear(n_state, n_mlp), nn.GELU(), nn.Linear(n_mlp, n_state))
|
||||
self.mlp_ln = nn.LayerNorm(n_state)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
mask: torch.Tensor | None = None,
|
||||
):
|
||||
x = x + self.attn(self.attn_ln(x), mask=mask)[0]
|
||||
x = x + self.mlp(self.mlp_ln(x))
|
||||
return x
|
||||
|
||||
|
||||
class AudioEncoder(nn.Module):
|
||||
"""
|
||||
Step-Audio2 Audio Encoder
|
||||
|
||||
Lightweight audio encoder (6 layers, 512 hidden)
|
||||
Optimized for 25s audio chunks at 25Hz
|
||||
"""
|
||||
|
||||
def __init__(self, n_mels: int, n_ctx: int, n_state: int, n_head: int, n_layer: int):
|
||||
super().__init__()
|
||||
self.conv1 = nn.Conv1d(n_mels, n_state, kernel_size=3, padding=1)
|
||||
self.conv2 = nn.Conv1d(n_state, n_state, kernel_size=3, stride=2, padding=1)
|
||||
self.positional_embedding = nn.Embedding(n_ctx, n_state)
|
||||
|
||||
self.blocks: Iterable[ResidualAttentionBlock] = nn.ModuleList(
|
||||
[ResidualAttentionBlock(n_state, n_head) for _ in range(n_layer)]
|
||||
)
|
||||
self.avg_pooler = nn.AvgPool1d(2, stride=2)
|
||||
self.after_norm = nn.LayerNorm(n_state)
|
||||
|
||||
def forward(self, x: torch.Tensor, x_len: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""
|
||||
Args:
|
||||
x: mel spectrogram, shape (batch_size, n_mels, T)
|
||||
x_len: length of each audio, shape (batch_size,)
|
||||
|
||||
Returns:
|
||||
x: encoded features, shape (batch_size, T//4, n_state)
|
||||
x_len: updated lengths, shape (batch_size,)
|
||||
"""
|
||||
T = x.size(-1)
|
||||
x = F.gelu(self.conv1(x))
|
||||
x = F.gelu(self.conv2(x))
|
||||
x = x.permute(0, 2, 1) # (B, T // 2, n_state)
|
||||
|
||||
# Create attention mask
|
||||
mask = make_non_pad_mask(x_len, T).unsqueeze(1) # (B, 1, T)
|
||||
mask = mask_to_bias(mask[:, :, (T + 1) % 2 :: 2], x.dtype) # (B, 1, T // 2)
|
||||
|
||||
# Add positional embedding
|
||||
x = (x + self.positional_embedding.weight[: x.shape[1], :]).to(x.dtype).contiguous()
|
||||
|
||||
# Apply attention blocks
|
||||
for block in self.blocks:
|
||||
x = block(x, mask.unsqueeze(1))
|
||||
|
||||
# Pool and normalize
|
||||
x = x.permute(0, 2, 1)
|
||||
x = self.avg_pooler(x)
|
||||
x = x.permute(0, 2, 1)
|
||||
x_len = (x_len + 1) // 2 // 2
|
||||
x = self.after_norm(x)
|
||||
|
||||
return x, x_len
|
||||
|
||||
|
||||
class Adaptor(nn.Module):
|
||||
"""
|
||||
Adaptor to project audio features to LLM dimension
|
||||
|
||||
Maps from n_state (512) to n_hidden (LLM dimension, e.g., 4096)
|
||||
with optional downsampling via convolution
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self, n_state: int = 512, n_hidden: int = 4096, kernel_size: int = 3, stride: int = 2, adapter_state: int = 2048
|
||||
):
|
||||
super().__init__()
|
||||
self.stride = stride
|
||||
|
||||
if self.stride != -1:
|
||||
self.conv = nn.Conv1d(n_state, n_state, kernel_size, stride, padding=1)
|
||||
|
||||
self.linear1 = nn.Linear(n_state, adapter_state)
|
||||
self.relu = nn.ReLU()
|
||||
self.linear2 = nn.Linear(adapter_state, n_hidden)
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
"""
|
||||
Args:
|
||||
x: audio features, shape (batch_size, T, n_state)
|
||||
|
||||
Returns:
|
||||
x: projected features, shape (batch_size, T//stride, n_hidden)
|
||||
"""
|
||||
if self.stride != -1:
|
||||
x = x.permute(0, 2, 1) # (B, n_state, T)
|
||||
x = F.gelu(self.conv(x))
|
||||
x = x.permute(0, 2, 1) # (B, T//stride, n_state)
|
||||
|
||||
x = self.linear1(x)
|
||||
x = self.relu(x)
|
||||
x = self.linear2(x)
|
||||
|
||||
return x
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Feature Length Calculation Utility
|
||||
# ============================================================================
|
||||
|
||||
|
||||
def calculate_audio_feature_length(mel_length: int) -> int:
|
||||
"""
|
||||
Calculate output feature length after encoder + adapter processing.
|
||||
|
||||
Processing chain:
|
||||
1. Mel spectrogram input: length = mel_length
|
||||
2. Encoder (AudioEncoder):
|
||||
- conv1: kernel=3, padding=1, stride=1 → no change
|
||||
- conv2: kernel=3, padding=1, stride=2 → T // 2
|
||||
- avg_pool: kernel=2, stride=2 → T // 4
|
||||
- Output length: (mel_length + 1) // 2 // 2 ≈ mel_length // 4
|
||||
3. Adapter (Adaptor):
|
||||
- conv: kernel=3, padding=1, stride=2 → T // 2
|
||||
- Output length: (encoder_output - 1) // 2 + 1
|
||||
|
||||
Args:
|
||||
mel_length: Length of mel spectrogram (time steps)
|
||||
|
||||
Returns:
|
||||
Final feature length after encoder + adapter
|
||||
|
||||
Example:
|
||||
>>> calculate_audio_feature_length(1000)
|
||||
125
|
||||
"""
|
||||
encoder_output_len = (mel_length + 1) // 4
|
||||
|
||||
adapter_output_len = (encoder_output_len - 1) // 2 + 1
|
||||
|
||||
return max(1, adapter_output_len)
|
||||
|
||||
|
||||
class StepAudio2Processor(ProcessorMixin):
|
||||
"""Processor for Step-Audio2 that handles text tokenization and audio mel-spectrograms."""
|
||||
|
||||
attributes = ["tokenizer"]
|
||||
attribute_class = {"tokenizer": "PreTrainedTokenizerBase"}
|
||||
|
||||
def __init__(self, tokenizer):
|
||||
self.tokenizer = tokenizer
|
||||
self.audio_token = "<audio_patch>"
|
||||
|
||||
def __call__(self, text=None, audio=None, **kwargs):
|
||||
"""Process text and audio inputs."""
|
||||
if text is None:
|
||||
text = ""
|
||||
|
||||
allowed = {
|
||||
"padding",
|
||||
"truncation",
|
||||
"max_length",
|
||||
"return_tensors",
|
||||
"add_special_tokens",
|
||||
"pad_to_multiple_of",
|
||||
"stride",
|
||||
"return_attention_mask",
|
||||
"return_token_type_ids",
|
||||
"return_overflowing_tokens",
|
||||
"return_offsets_mapping",
|
||||
"return_special_tokens_mask",
|
||||
"verbose",
|
||||
"is_split_into_words",
|
||||
}
|
||||
tok_kwargs = {k: v for k, v in kwargs.items() if k in allowed}
|
||||
if "return_tensors" not in tok_kwargs:
|
||||
tok_kwargs["return_tensors"] = "pt"
|
||||
|
||||
encoded = self.tokenizer(text, **tok_kwargs)
|
||||
|
||||
if audio is None:
|
||||
encoded["audio_mels"] = torch.empty((0, 128, 0))
|
||||
encoded["audio_lens"] = torch.tensor([], dtype=torch.int32)
|
||||
return encoded
|
||||
|
||||
audio_list = list(audio) if isinstance(audio, (list, tuple)) else [audio]
|
||||
|
||||
mels = [log_mel_spectrogram(a) for a in audio_list]
|
||||
audio_mels, audio_lens = padding_mels(mels)
|
||||
|
||||
encoded["audio_mels"] = audio_mels
|
||||
encoded["audio_lens"] = audio_lens
|
||||
return encoded
|
||||
|
||||
|
||||
class StepAudio2AudioInputs(TypedDict):
|
||||
"""Audio inputs for Step-Audio2"""
|
||||
|
||||
audio_mels: torch.Tensor
|
||||
"""Shape: (batch, num_mel_bins, time_steps)"""
|
||||
|
||||
audio_lens: list[int]
|
||||
"""Shape: (batch,) - length of each audio in time steps"""
|
||||
|
||||
|
||||
class StepAudio2ProcessingInfo(BaseProcessingInfo):
|
||||
"""Processing info for Step-Audio2"""
|
||||
|
||||
def get_tokenizer(self, **kwargs):
|
||||
return AutoTokenizer.from_pretrained(
|
||||
self.ctx.model_config.model,
|
||||
trust_remote_code=True,
|
||||
fix_mistral_regex=True,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def get_hf_processor(self, **kwargs: object):
|
||||
return StepAudio2Processor(self.get_tokenizer())
|
||||
|
||||
def build_data_parser(self) -> MultiModalDataParser:
|
||||
return MultiModalDataParser(target_sr=16000)
|
||||
|
||||
# Backward/branch compatibility:
|
||||
# some code paths still call get_data_parser() on ProcessingInfo.
|
||||
def get_data_parser(self) -> MultiModalDataParser:
|
||||
return MultiModalDataParser(target_sr=16000)
|
||||
|
||||
def get_supported_mm_limits(self) -> Mapping[str, int | None]:
|
||||
return {"audio": None}
|
||||
|
||||
def get_mm_max_tokens_per_item(
|
||||
self,
|
||||
seq_len: int,
|
||||
mm_counts: Mapping[str, int],
|
||||
) -> Mapping[str, int]:
|
||||
max_audio_tokens = 250
|
||||
return {"audio": max_audio_tokens}
|
||||
|
||||
|
||||
class StepAudio2DummyInputsBuilder(BaseDummyInputsBuilder[StepAudio2ProcessingInfo]):
|
||||
"""Dummy inputs builder for Step-Audio2"""
|
||||
|
||||
def get_dummy_text(self, mm_counts: Mapping[str, int]) -> str:
|
||||
num_audios = mm_counts.get("audio", 0)
|
||||
return "<audio_patch>" * num_audios
|
||||
|
||||
def get_dummy_mm_data(
|
||||
self,
|
||||
seq_len: int,
|
||||
mm_counts: Mapping[str, int],
|
||||
mm_options: Mapping[str, object] | None = None,
|
||||
) -> MultiModalDataDict:
|
||||
audio_len = 16000 * 25
|
||||
num_audios = mm_counts.get("audio", 0)
|
||||
return {"audio": self._get_dummy_audios(length=audio_len, num_audios=num_audios)}
|
||||
|
||||
|
||||
class StepAudio2MultiModalProcessor(BaseMultiModalProcessor[StepAudio2ProcessingInfo]):
|
||||
"""Multi-modal processor for Step-Audio2"""
|
||||
|
||||
def _get_mm_fields_config(
|
||||
self,
|
||||
hf_inputs,
|
||||
hf_processor_mm_kwargs: Mapping[str, object],
|
||||
) -> Mapping[str, MultiModalFieldConfig]:
|
||||
"""Map processor outputs to vLLM multimodal fields.
|
||||
|
||||
audio_mels is a padded 3D tensor per audio item with matching audio_lens.
|
||||
Use flat_from_sizes to keep one mm item per audio, so downstream mm_kwargs
|
||||
alignment does not collapse to a single item.
|
||||
"""
|
||||
audio_lens = hf_inputs.get("audio_lens", torch.empty(0))
|
||||
if isinstance(audio_lens, torch.Tensor):
|
||||
lens_tensor = audio_lens.flatten()
|
||||
elif audio_lens is None:
|
||||
lens_tensor = torch.empty(0, dtype=torch.int32)
|
||||
else:
|
||||
lens_tensor = torch.tensor(
|
||||
list(audio_lens) if hasattr(audio_lens, "__iter__") else [int(audio_lens)], dtype=torch.int32
|
||||
)
|
||||
|
||||
return dict(
|
||||
audio_mels=MultiModalFieldConfig.flat_from_sizes("audio", lens_tensor),
|
||||
audio_lens=MultiModalFieldConfig.batched("audio"),
|
||||
)
|
||||
|
||||
def _get_prompt_updates(
|
||||
self,
|
||||
mm_items: MultiModalDataItems,
|
||||
hf_processor_mm_kwargs: Mapping[str, object],
|
||||
out_mm_kwargs: MultiModalKwargsItems,
|
||||
) -> Sequence[PromptUpdate]:
|
||||
processor = self.info.get_hf_processor(**hf_processor_mm_kwargs)
|
||||
|
||||
audio_token = getattr(processor, "audio_token", "<audio_patch>")
|
||||
|
||||
audio_items = mm_items.get("audio", [])
|
||||
num_audio_items = len(audio_items) if audio_items else 0
|
||||
|
||||
out_mm_data = out_mm_kwargs.get_data()
|
||||
audio_lens = out_mm_data.get("audio_lens")
|
||||
|
||||
feature_lens = []
|
||||
if audio_lens is not None:
|
||||
if isinstance(audio_lens, torch.Tensor):
|
||||
audio_lens_list = audio_lens.tolist()
|
||||
else:
|
||||
audio_lens_list = list(audio_lens) if hasattr(audio_lens, "__iter__") else [audio_lens]
|
||||
|
||||
for length in audio_lens_list:
|
||||
if length > 0:
|
||||
feature_len = calculate_audio_feature_length(int(length))
|
||||
feature_lens.append(feature_len)
|
||||
|
||||
# CRITICAL: Align feature_lens with mm_items['audio'] count
|
||||
if num_audio_items > 0:
|
||||
if len(feature_lens) < num_audio_items:
|
||||
default_feature_len = 250
|
||||
pad_count = num_audio_items - len(feature_lens)
|
||||
feature_lens.extend([default_feature_len] * pad_count)
|
||||
elif len(feature_lens) > num_audio_items:
|
||||
feature_lens = feature_lens[:num_audio_items]
|
||||
elif not feature_lens:
|
||||
feature_lens = [250]
|
||||
|
||||
def get_replacement_audio(item_idx: int):
|
||||
"""Generate replacement tokens for audio placeholder.
|
||||
|
||||
Following Qwen2.5-Omni pattern: returns list[int] of token IDs.
|
||||
"""
|
||||
if item_idx >= len(feature_lens):
|
||||
num_features = 1
|
||||
else:
|
||||
num_features = feature_lens[item_idx]
|
||||
|
||||
return [STEP_AUDIO2_AUDIO_PATCH_TOKEN_ID] * num_features
|
||||
|
||||
return [
|
||||
PromptReplacement(
|
||||
modality="audio",
|
||||
target=audio_token,
|
||||
replacement=get_replacement_audio,
|
||||
)
|
||||
]
|
||||
|
||||
def _call_hf_processor(
|
||||
self,
|
||||
prompt: str,
|
||||
mm_data: Mapping[str, object],
|
||||
mm_kwargs: Mapping[str, object] | None = None,
|
||||
tok_kwargs: Mapping[str, object] | None = None,
|
||||
**_: object,
|
||||
):
|
||||
"""Call HF processor and post-process outputs"""
|
||||
mm_data = dict(mm_data)
|
||||
audios = mm_data.pop("audios", [])
|
||||
|
||||
mm_kwargs = mm_kwargs or {}
|
||||
tok_kwargs = tok_kwargs or {}
|
||||
|
||||
# CRITICAL: Ensure audios is ALWAYS a list to prevent string iteration
|
||||
if audios:
|
||||
if isinstance(audios, str):
|
||||
mm_data["audio"] = [audios]
|
||||
elif isinstance(audios, (list, tuple)):
|
||||
mm_data["audio"] = audios
|
||||
else:
|
||||
mm_data["audio"] = [audios]
|
||||
|
||||
hf_inputs = super()._call_hf_processor(
|
||||
prompt=prompt,
|
||||
mm_data=mm_data,
|
||||
mm_kwargs=mm_kwargs,
|
||||
tok_kwargs=tok_kwargs,
|
||||
)
|
||||
|
||||
if "audio_mels" not in hf_inputs:
|
||||
hf_inputs["audio_mels"] = torch.empty((0, 128, 0))
|
||||
if "audio_lens" not in hf_inputs:
|
||||
hf_inputs["audio_lens"] = torch.tensor([], dtype=torch.int32)
|
||||
|
||||
return hf_inputs
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Main Thinker Model
|
||||
# ============================================================================
|
||||
|
||||
|
||||
@MULTIMODAL_REGISTRY.register_processor(
|
||||
StepAudio2MultiModalProcessor,
|
||||
info=StepAudio2ProcessingInfo,
|
||||
dummy_inputs=StepAudio2DummyInputsBuilder,
|
||||
)
|
||||
class StepAudio2ThinkerForConditionalGeneration(nn.Module, SupportsMultiModal, SupportsPP):
|
||||
"""
|
||||
Step-Audio2 Thinker - Stage 1 LLM
|
||||
|
||||
Architecture:
|
||||
AudioEncoder (6 layers, 512 hidden) →
|
||||
Adaptor (512 → LLM dim) →
|
||||
Qwen2 LLM (vocab=64012)
|
||||
"""
|
||||
|
||||
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
|
||||
super().__init__()
|
||||
self.have_multimodal_outputs = True
|
||||
|
||||
config = vllm_config.model_config.hf_config
|
||||
multimodal_config = vllm_config.model_config.multimodal_config
|
||||
|
||||
self.config = config
|
||||
self.multimodal_config = multimodal_config
|
||||
|
||||
audio_enc_cfg = getattr(config, "audio_encoder_config", {})
|
||||
|
||||
def _get_config_value(cfg, attr_name: str, default_value):
|
||||
"""Get value from config object or dict"""
|
||||
if isinstance(cfg, dict):
|
||||
return cfg.get(attr_name, default_value)
|
||||
else:
|
||||
return getattr(cfg, attr_name, default_value)
|
||||
|
||||
n_mels = _get_config_value(audio_enc_cfg, "n_mels", DEFAULT_MODEL_CONFIG.n_mels)
|
||||
n_audio_ctx = _get_config_value(audio_enc_cfg, "n_audio_ctx", DEFAULT_MODEL_CONFIG.n_audio_ctx)
|
||||
n_audio_state = _get_config_value(audio_enc_cfg, "n_audio_state", DEFAULT_MODEL_CONFIG.n_audio_state)
|
||||
n_audio_head = _get_config_value(audio_enc_cfg, "n_audio_head", DEFAULT_MODEL_CONFIG.n_audio_head)
|
||||
n_audio_layer = _get_config_value(audio_enc_cfg, "n_audio_layer", DEFAULT_MODEL_CONFIG.n_audio_layer)
|
||||
kernel_size = _get_config_value(audio_enc_cfg, "kernel_size", DEFAULT_MODEL_CONFIG.kernel_size)
|
||||
adapter_stride = _get_config_value(audio_enc_cfg, "adapter_stride", DEFAULT_MODEL_CONFIG.adapter_stride)
|
||||
|
||||
n_hidden = None
|
||||
|
||||
if audio_enc_cfg:
|
||||
n_hidden = _get_config_value(audio_enc_cfg, "llm_dim", None)
|
||||
|
||||
if n_hidden is None:
|
||||
text_config = getattr(config, "text_config", None)
|
||||
if text_config is not None:
|
||||
n_hidden = _get_config_value(text_config, "hidden_size", None)
|
||||
|
||||
if n_hidden is None:
|
||||
n_hidden = _get_config_value(config, "hidden_size", None)
|
||||
|
||||
if n_hidden is None:
|
||||
n_hidden = DEFAULT_MODEL_CONFIG.hidden_size
|
||||
|
||||
self.encoder = AudioEncoder(
|
||||
n_mels=n_mels,
|
||||
n_ctx=n_audio_ctx,
|
||||
n_state=n_audio_state,
|
||||
n_head=n_audio_head,
|
||||
n_layer=n_audio_layer,
|
||||
)
|
||||
|
||||
self.adapter = Adaptor(
|
||||
n_state=n_audio_state,
|
||||
n_hidden=n_hidden,
|
||||
kernel_size=kernel_size,
|
||||
stride=adapter_stride,
|
||||
)
|
||||
|
||||
from transformers import PretrainedConfig
|
||||
|
||||
text_config = getattr(config, "text_config", None)
|
||||
lm_config = text_config if isinstance(text_config, PretrainedConfig) else config
|
||||
architectures = getattr(lm_config, "architectures", None) or getattr(config, "architectures", None)
|
||||
if not architectures:
|
||||
model_type = getattr(lm_config, "model_type", None) or getattr(config, "model_type", None)
|
||||
model_type_to_arch = {
|
||||
"qwen2": "Qwen2ForCausalLM",
|
||||
"qwen2_5": "Qwen2_5ForCausalLM",
|
||||
}
|
||||
arch = model_type_to_arch.get(model_type)
|
||||
architectures = [arch] if arch else ["Qwen2ForCausalLM"]
|
||||
lm_vllm_config = vllm_config.with_hf_config(lm_config, architectures=architectures)
|
||||
self.language_model = init_vllm_registered_model(
|
||||
vllm_config=lm_vllm_config, hf_config=lm_config, prefix=maybe_prefix(prefix, "language_model")
|
||||
)
|
||||
|
||||
self.make_empty_intermediate_tensors = self.language_model.make_empty_intermediate_tensors
|
||||
|
||||
@classmethod
|
||||
def get_placeholder_str(cls, modality: str, i: int) -> str | None:
|
||||
if modality.startswith("audio"):
|
||||
return "<audio_patch>"
|
||||
raise ValueError("Only audio modality is supported")
|
||||
|
||||
@property
|
||||
def device(self):
|
||||
return next(self.parameters()).device
|
||||
|
||||
@property
|
||||
def dtype(self):
|
||||
return next(self.parameters()).dtype
|
||||
|
||||
def _parse_and_validate_audio_input(self, **kwargs: object) -> StepAudio2AudioInputs | None:
|
||||
"""Parse audio inputs from kwargs"""
|
||||
audio_mels = kwargs.get("audio_mels", None)
|
||||
audio_lens = kwargs.get("audio_lens", None)
|
||||
|
||||
if audio_mels is None:
|
||||
return None
|
||||
|
||||
if isinstance(audio_mels, torch.Tensor):
|
||||
if audio_mels.dim() >= 4:
|
||||
audio_mels = audio_mels.flatten(0, 1)
|
||||
elif audio_mels.dim() == 3:
|
||||
# Already (B, n_mels, T)
|
||||
pass
|
||||
elif audio_mels.dim() == 2:
|
||||
audio_mels = audio_mels.unsqueeze(0)
|
||||
else:
|
||||
return None
|
||||
else:
|
||||
audio_mels = flatten_bn(audio_mels, concat=True)
|
||||
|
||||
if isinstance(audio_lens, torch.Tensor):
|
||||
if audio_lens.dim() >= 2:
|
||||
audio_lens = audio_lens.flatten(0, 1)
|
||||
elif audio_lens.dim() == 0:
|
||||
audio_lens = audio_lens.unsqueeze(0)
|
||||
# dim == 1 is already fine
|
||||
else:
|
||||
audio_lens = flatten_bn(audio_lens, concat=True)
|
||||
|
||||
expected_n_mels = 128
|
||||
if audio_mels.ndim == 3 and audio_mels.size(1) != expected_n_mels:
|
||||
return None
|
||||
|
||||
return StepAudio2AudioInputs(
|
||||
audio_mels=audio_mels.to(self.dtype).to(self.device),
|
||||
audio_lens=audio_lens,
|
||||
)
|
||||
|
||||
def _process_audio_input(self, audio_input: StepAudio2AudioInputs) -> tuple[torch.Tensor, ...]:
|
||||
"""Process audio mels through encoder and adapter"""
|
||||
audio_mels = audio_input["audio_mels"]
|
||||
audio_lens = audio_input["audio_lens"]
|
||||
if not isinstance(audio_lens, torch.Tensor):
|
||||
audio_lens = torch.tensor(audio_lens, device=self.device)
|
||||
else:
|
||||
audio_lens = audio_lens.to(self.device)
|
||||
|
||||
audio_features, audio_lens = self.encoder(audio_mels, audio_lens)
|
||||
|
||||
audio_features = self.adapter(audio_features)
|
||||
|
||||
audio_feature_lens = (audio_lens - 1) // 2 + 1
|
||||
|
||||
audio_feature_list = [audio_features[i, : audio_feature_lens[i]] for i in range(audio_features.size(0))]
|
||||
|
||||
return audio_feature_list
|
||||
|
||||
def get_multimodal_embeddings(self, **kwargs) -> NestedTensors | None:
|
||||
"""Get multimodal embeddings"""
|
||||
audio_input = self._parse_and_validate_audio_input(**kwargs)
|
||||
if audio_input is None:
|
||||
return None
|
||||
else:
|
||||
audio_embeddings = self._process_audio_input(audio_input)
|
||||
return audio_embeddings
|
||||
|
||||
def embed_multimodal(self, **kwargs: object) -> NestedTensors:
|
||||
"""vLLM multimodal encoder entrypoint."""
|
||||
audio_embeddings = self.get_multimodal_embeddings(**kwargs)
|
||||
if audio_embeddings is None:
|
||||
return []
|
||||
return audio_embeddings
|
||||
|
||||
def get_input_embeddings(
|
||||
self,
|
||||
input_ids: torch.Tensor,
|
||||
multimodal_embeddings: NestedTensors | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Get input embeddings with multimodal fusion"""
|
||||
# Under newer vLLM versions the registered LM wrapper exposes
|
||||
# get_input_embeddings(), while the inner `.model` may be a bare
|
||||
# Qwen2Model without that compatibility method.
|
||||
inputs_embeds = self.language_model.embed_input_ids(input_ids)
|
||||
if multimodal_embeddings is not None:
|
||||
inputs_embeds = _merge_multimodal_embeddings(
|
||||
input_ids, inputs_embeds, multimodal_embeddings, STEP_AUDIO2_AUDIO_PATCH_TOKEN_ID
|
||||
)
|
||||
return inputs_embeds
|
||||
|
||||
def get_language_model(self) -> nn.Module:
|
||||
return self.language_model
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
intermediate_tensors: IntermediateTensors | None = None,
|
||||
inputs_embeds: torch.Tensor | None = None,
|
||||
**kwargs: object,
|
||||
):
|
||||
"""Forward pass - returns OmniOutput for multi-stage pipeline"""
|
||||
if intermediate_tensors is not None:
|
||||
inputs_embeds = None
|
||||
elif inputs_embeds is None:
|
||||
audio_embeddings = self.get_multimodal_embeddings(**kwargs)
|
||||
inputs_embeds = self.get_input_embeddings(input_ids, audio_embeddings)
|
||||
input_ids = None
|
||||
|
||||
hidden_states = self.language_model(
|
||||
input_ids,
|
||||
positions,
|
||||
intermediate_tensors,
|
||||
inputs_embeds=inputs_embeds,
|
||||
)
|
||||
|
||||
return OmniOutput(
|
||||
text_hidden_states=hidden_states,
|
||||
multimodal_outputs={},
|
||||
)
|
||||
|
||||
def compute_logits(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
) -> torch.Tensor | None:
|
||||
return self.language_model.compute_logits(hidden_states)
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
"""Load weights with name mapping from HuggingFace to vLLM structure"""
|
||||
from vllm.model_executor.models.utils import AutoWeightsLoader
|
||||
|
||||
# Map HuggingFace weight names to our model structure
|
||||
# HF: model.*, lm_head.* → Our: language_model.model.*, language_model.lm_head.*
|
||||
# HF: encoder.*, adapter.* → Our: encoder.*, adapter.* (no change)
|
||||
def weight_mapper(name: str) -> str:
|
||||
if name.startswith("lm_head."):
|
||||
return name.replace("lm_head.", "language_model.lm_head.")
|
||||
elif name.startswith("model."):
|
||||
return name.replace("model.", "language_model.model.")
|
||||
else:
|
||||
# encoder.* and adapter.* remain unchanged
|
||||
return name
|
||||
|
||||
# Apply mapping to weights
|
||||
mapped_weights = [(weight_mapper(name), tensor) for name, tensor in weights]
|
||||
|
||||
loader = AutoWeightsLoader(self)
|
||||
return loader.load_weights(mapped_weights)
|
||||
|
||||
@staticmethod
|
||||
def separate_tokens(
|
||||
token_ids: list[int],
|
||||
text_max: int = DEFAULT_TOKEN_CONFIG.text_max,
|
||||
audio_start: int = DEFAULT_TOKEN_CONFIG.audio_start,
|
||||
) -> tuple[list[int], list[int]]:
|
||||
"""Separate generated tokens into text and audio tokens"""
|
||||
text_tokens = [tid for tid in token_ids if tid < text_max]
|
||||
audio_tokens = [tid - audio_start for tid in token_ids if tid >= audio_start]
|
||||
return text_tokens, audio_tokens
|
||||
|
||||
@staticmethod
|
||||
def has_audio_output(token_ids: list[int], audio_start: int = DEFAULT_TOKEN_CONFIG.audio_start) -> bool:
|
||||
"""Check if generated tokens contain audio tokens"""
|
||||
return any(tid >= audio_start for tid in token_ids)
|
||||
|
||||
|
||||
class StepAudio2OutputProcessor:
|
||||
"""Helper class to process Step-Audio2 outputs"""
|
||||
|
||||
@staticmethod
|
||||
def process_output(output_ids: torch.Tensor, tokenizer, remove_audio_padding: bool = True) -> dict:
|
||||
"""Process model output and separate text/audio tokens"""
|
||||
if isinstance(output_ids, torch.Tensor):
|
||||
output_ids = output_ids.squeeze().tolist()
|
||||
|
||||
# Separate tokens
|
||||
text_tokens, audio_tokens = StepAudio2ThinkerForConditionalGeneration.separate_tokens(output_ids)
|
||||
|
||||
# Remove audio padding if requested
|
||||
if remove_audio_padding and audio_tokens:
|
||||
audio_tokens = [t for t in audio_tokens if t < DEFAULT_TOKEN_CONFIG.audio_eos]
|
||||
|
||||
# Decode text
|
||||
text = tokenizer.decode(text_tokens, skip_special_tokens=False)
|
||||
|
||||
return {
|
||||
"text": text,
|
||||
"text_tokens": text_tokens,
|
||||
"audio_tokens": audio_tokens,
|
||||
"has_audio": len(audio_tokens) > 0,
|
||||
"all_tokens": output_ids,
|
||||
}
|
||||
@@ -0,0 +1,759 @@
|
||||
import io
|
||||
import os
|
||||
from collections.abc import Iterable
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
import librosa # noqa: TID251
|
||||
import numpy as np
|
||||
import onnxruntime
|
||||
import s3tokenizer
|
||||
import soundfile as sf
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torchaudio
|
||||
import torchaudio.compliance.kaldi as kaldi
|
||||
from flashcosyvoice.modules.hifigan import HiFTGenerator
|
||||
from flashcosyvoice.utils.audio import mel_spectrogram
|
||||
from hyperpyyaml import load_hyperpyyaml
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.models.interfaces import SupportsPP
|
||||
from vllm.model_executor.models.utils import WeightsMapper
|
||||
from vllm.sequence import IntermediateTensors
|
||||
from vllm.v1.outputs import SamplerOutput
|
||||
from vllm.v1.sample.metadata import SamplingMetadata
|
||||
from vllm.v1.sample.sampler import Sampler
|
||||
|
||||
from vllm_omni.model_executor.models.output_templates import OmniOutput
|
||||
from vllm_omni.model_executor.models.step_audio2.step_audio2_constants import (
|
||||
DEFAULT_STREAM_CONFIG,
|
||||
DEFAULT_TOKEN2WAV_CONFIG,
|
||||
STEP_AUDIO2_DEFAULT_PROMPT_WAV,
|
||||
STREAM_SOURCE_CACHE_LEN,
|
||||
)
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def fade_in_out(
|
||||
fade_in_mel: torch.Tensor,
|
||||
fade_out_mel: torch.Tensor,
|
||||
window: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
"""Cross-fade two overlapping waveform segments using a Hamming window.
|
||||
|
||||
The window is split in half: the first half ramps *up* (fade-in) and
|
||||
the second half ramps *down* (fade-out). The overlap region of
|
||||
``fade_in_mel`` is blended with the tail of ``fade_out_mel``.
|
||||
"""
|
||||
mel_overlap_len = int(window.shape[0] / 2)
|
||||
fade_in_mel = fade_in_mel.clone()
|
||||
fade_in_mel[..., :mel_overlap_len] = (
|
||||
fade_in_mel[..., :mel_overlap_len] * window[:mel_overlap_len]
|
||||
+ fade_out_mel[..., -mel_overlap_len:] * window[mel_overlap_len:]
|
||||
)
|
||||
return fade_in_mel
|
||||
|
||||
|
||||
@dataclass
|
||||
class _StreamState:
|
||||
"""Per-request streaming state for concurrent Token2Wav sessions."""
|
||||
|
||||
setup_done: bool = False
|
||||
stream_cache: dict | None = None
|
||||
hift_cache_dict: dict = field(default_factory=dict)
|
||||
finished: bool = False
|
||||
|
||||
|
||||
class StepAudio2Token2WavCore(nn.Module):
|
||||
"""Core Token2Wav model - handles token to waveform conversion"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
model_path: str,
|
||||
float16: bool = False,
|
||||
device: str = "cuda",
|
||||
n_timesteps: int = DEFAULT_TOKEN2WAV_CONFIG.n_timesteps,
|
||||
):
|
||||
super().__init__()
|
||||
self.model_path = model_path
|
||||
self.float16 = float16
|
||||
self.device = torch.device(device)
|
||||
self.n_timesteps = n_timesteps
|
||||
|
||||
self._models_loaded = False
|
||||
self._audio_tokenizer = None
|
||||
self._spk_model = None
|
||||
self._flow = None
|
||||
self._hift = None
|
||||
|
||||
self.cache = {}
|
||||
|
||||
# Streaming state (constants from centralised config)
|
||||
self.mel_cache_len = DEFAULT_STREAM_CONFIG.mel_cache_len
|
||||
self.source_cache_len = STREAM_SOURCE_CACHE_LEN
|
||||
self.speech_window: torch.Tensor | None = None # created lazily on device
|
||||
self.stream_cache: dict | None = None # flow model causal cache
|
||||
self.hift_cache_dict: dict = {} # HiFT vocoder overlap cache
|
||||
|
||||
def _ensure_models_loaded(self):
|
||||
"""Lazy load models on first use"""
|
||||
if self._models_loaded:
|
||||
return
|
||||
|
||||
from vllm.logger import init_logger
|
||||
|
||||
logger = init_logger(__name__)
|
||||
logger.info(f"Loading Token2Wav models from: {self.model_path}")
|
||||
|
||||
self._audio_tokenizer = (
|
||||
s3tokenizer.load_model(f"{self.model_path}/speech_tokenizer_v2_25hz.onnx").to(self.device).eval()
|
||||
)
|
||||
|
||||
option = onnxruntime.SessionOptions()
|
||||
option.graph_optimization_level = onnxruntime.GraphOptimizationLevel.ORT_ENABLE_ALL
|
||||
option.intra_op_num_threads = 1
|
||||
self._spk_model = onnxruntime.InferenceSession(
|
||||
f"{self.model_path}/campplus.onnx", sess_options=option, providers=["CPUExecutionProvider"]
|
||||
)
|
||||
|
||||
with open(f"{self.model_path}/flow.yaml") as f:
|
||||
configs = load_hyperpyyaml(f)
|
||||
self._flow = configs["flow"]
|
||||
if self.float16:
|
||||
self._flow.half()
|
||||
self._flow.load_state_dict(
|
||||
torch.load(f"{self.model_path}/flow.pt", map_location="cpu", weights_only=True), strict=True
|
||||
)
|
||||
self._flow.to(self.device).eval()
|
||||
|
||||
self._hift = HiFTGenerator()
|
||||
hift_state_dict = {
|
||||
k.replace("generator.", ""): v
|
||||
for k, v in torch.load(f"{self.model_path}/hift.pt", map_location="cpu", weights_only=True).items()
|
||||
}
|
||||
self._hift.load_state_dict(hift_state_dict, strict=True)
|
||||
self._hift.to(self.device).eval()
|
||||
|
||||
self._models_loaded = True
|
||||
logger.info("Token2Wav models loaded successfully")
|
||||
|
||||
@property
|
||||
def audio_tokenizer(self):
|
||||
"""Lazy-loaded audio tokenizer"""
|
||||
self._ensure_models_loaded()
|
||||
return self._audio_tokenizer
|
||||
|
||||
@property
|
||||
def spk_model(self):
|
||||
"""Lazy-loaded speaker model"""
|
||||
self._ensure_models_loaded()
|
||||
return self._spk_model
|
||||
|
||||
@property
|
||||
def flow(self):
|
||||
"""Lazy-loaded flow model"""
|
||||
self._ensure_models_loaded()
|
||||
return self._flow
|
||||
|
||||
@property
|
||||
def hift(self):
|
||||
"""Lazy-loaded HiFT vocoder"""
|
||||
self._ensure_models_loaded()
|
||||
return self._hift
|
||||
|
||||
def _prepare_prompt(self, prompt_wav: str):
|
||||
"""Prepare prompt audio for conditioning"""
|
||||
# Prefer soundfile/librosa path to avoid torchaudio->torchcodec runtime coupling.
|
||||
try:
|
||||
audio_np_raw, sample_rate = sf.read(prompt_wav, dtype="float32", always_2d=False)
|
||||
except Exception:
|
||||
audio_np_raw, sample_rate = librosa.load(prompt_wav, sr=None, mono=True)
|
||||
if isinstance(audio_np_raw, np.ndarray) and audio_np_raw.ndim > 1:
|
||||
audio_np_raw = np.mean(audio_np_raw, axis=-1)
|
||||
sample_rate = int(sample_rate)
|
||||
|
||||
# 16 kHz branch: s3tokenizer + speaker embedding
|
||||
audio_16k = audio_np_raw.astype(np.float32)
|
||||
if sample_rate != 16000:
|
||||
audio_16k = librosa.resample(y=audio_16k, orig_sr=sample_rate, target_sr=16000)
|
||||
audio = torch.from_numpy(audio_16k)
|
||||
mels = s3tokenizer.log_mel_spectrogram(audio)
|
||||
mels, mels_lens = s3tokenizer.padding([mels])
|
||||
prompt_speech_tokens, prompt_speech_tokens_lens = self.audio_tokenizer.quantize(
|
||||
mels.to(self.device), mels_lens.to(self.device)
|
||||
)
|
||||
|
||||
spk_feat = kaldi.fbank(audio.unsqueeze(0), num_mel_bins=80, dither=0, sample_frequency=16000)
|
||||
spk_feat = spk_feat - spk_feat.mean(dim=0, keepdim=True)
|
||||
spk_emb = torch.tensor(
|
||||
self.spk_model.run(None, {self.spk_model.get_inputs()[0].name: spk_feat.unsqueeze(dim=0).cpu().numpy()})[0],
|
||||
device=self.device,
|
||||
)
|
||||
|
||||
# 24 kHz branch: mel spectrogram for flow model conditioning
|
||||
# Must resample from the ORIGINAL audio, not the 16 kHz version.
|
||||
audio_24k = audio_np_raw.astype(np.float32)
|
||||
if sample_rate != 24000:
|
||||
audio_24k = librosa.resample(y=audio_24k, orig_sr=sample_rate, target_sr=24000)
|
||||
audio_24k_t = torch.from_numpy(audio_24k).unsqueeze(0) # [1, T]
|
||||
prompt_mel = mel_spectrogram(audio_24k_t).transpose(1, 2).squeeze(0) # [T, num_mels]
|
||||
prompt_mels = prompt_mel.unsqueeze(0).to(self.device)
|
||||
prompt_mels_lens = torch.tensor([prompt_mels.shape[1]], dtype=torch.int32, device=self.device)
|
||||
prompt_mels = torch.nn.functional.pad(
|
||||
prompt_mels,
|
||||
(0, 0, 0, prompt_speech_tokens.shape[1] * self.flow.up_rate - prompt_mels.shape[1]),
|
||||
mode="replicate",
|
||||
)
|
||||
|
||||
return prompt_speech_tokens, prompt_speech_tokens_lens, spk_emb, prompt_mels, prompt_mels_lens
|
||||
|
||||
def forward(
|
||||
self, generated_speech_tokens: list, prompt_wav: str, return_bytes: bool = True
|
||||
) -> torch.Tensor | bytes:
|
||||
"""
|
||||
Convert audio tokens to waveform
|
||||
|
||||
Args:
|
||||
generated_speech_tokens: List of audio token IDs (0-6560)
|
||||
prompt_wav: Path to prompt wav file for speaker conditioning
|
||||
return_bytes: If True, return WAV bytes; else return tensor
|
||||
|
||||
Returns:
|
||||
Audio waveform as bytes or tensor
|
||||
"""
|
||||
if prompt_wav not in self.cache:
|
||||
self.cache[prompt_wav] = self._prepare_prompt(prompt_wav)
|
||||
prompt_speech_tokens, prompt_speech_tokens_lens, spk_emb, prompt_mels, prompt_mels_lens = self.cache[prompt_wav]
|
||||
|
||||
generated_speech_tokens = torch.tensor([generated_speech_tokens], dtype=torch.int32, device=self.device)
|
||||
generated_speech_tokens_lens = torch.tensor(
|
||||
[generated_speech_tokens.shape[1]], dtype=torch.int32, device=self.device
|
||||
)
|
||||
|
||||
with torch.amp.autocast(str(self.device.type), dtype=torch.float16 if self.float16 else torch.float32):
|
||||
mel = self.flow.inference(
|
||||
generated_speech_tokens,
|
||||
generated_speech_tokens_lens,
|
||||
prompt_speech_tokens,
|
||||
prompt_speech_tokens_lens,
|
||||
prompt_mels,
|
||||
prompt_mels_lens,
|
||||
spk_emb,
|
||||
self.n_timesteps,
|
||||
)
|
||||
|
||||
wav, _ = self.hift(speech_feat=mel)
|
||||
|
||||
if return_bytes:
|
||||
output = io.BytesIO()
|
||||
torchaudio.save(output, wav.cpu(), sample_rate=DEFAULT_TOKEN2WAV_CONFIG.sample_rate, format="wav")
|
||||
return output.getvalue()
|
||||
else:
|
||||
return wav
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Streaming (chunked) inference
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def setup_stream(self, prompt_wav: str) -> None:
|
||||
"""Initialize flow + HiFT caches for chunked streaming inference.
|
||||
|
||||
Must be called once before the first ``stream_chunk()`` call for a
|
||||
given utterance.
|
||||
"""
|
||||
if prompt_wav not in self.cache:
|
||||
self.cache[prompt_wav] = self._prepare_prompt(prompt_wav)
|
||||
(
|
||||
prompt_speech_tokens,
|
||||
_,
|
||||
spk_emb,
|
||||
prompt_mels,
|
||||
_,
|
||||
) = self.cache[prompt_wav]
|
||||
|
||||
# Lazily create the Hamming window on the correct device
|
||||
if self.speech_window is None or self.speech_window.device != self.device:
|
||||
self.speech_window = torch.from_numpy(np.hamming(2 * self.source_cache_len)).to(
|
||||
device=self.device, dtype=torch.float32
|
||||
)
|
||||
|
||||
# Flow model: setup causal cache with prompt tokens + lookahead
|
||||
pre_lookahead = DEFAULT_STREAM_CONFIG.pre_lookahead_len
|
||||
self.stream_cache = self.flow.setup_cache(
|
||||
torch.cat([prompt_speech_tokens, prompt_speech_tokens[:, :pre_lookahead]], dim=1),
|
||||
prompt_mels,
|
||||
spk_emb,
|
||||
n_timesteps=self.n_timesteps,
|
||||
)
|
||||
|
||||
# HiFT vocoder: empty overlap buffers
|
||||
self.hift_cache_dict = {
|
||||
"mel": torch.zeros(1, prompt_mels.shape[2], 0, device=self.device),
|
||||
"source": torch.zeros(1, 1, 0, device=self.device),
|
||||
"speech": torch.zeros(1, 0, device=self.device),
|
||||
}
|
||||
|
||||
def stream_chunk(
|
||||
self,
|
||||
audio_tokens: list[int],
|
||||
prompt_wav: str,
|
||||
last_chunk: bool = False,
|
||||
) -> torch.Tensor:
|
||||
"""Process one chunk of audio tokens and return a waveform segment.
|
||||
|
||||
Args:
|
||||
audio_tokens: Token IDs for this chunk (includes lookahead for
|
||||
non-last chunks).
|
||||
prompt_wav: Path to the prompt wav (for cached speaker embeddings).
|
||||
last_chunk: Whether this is the final chunk of the utterance.
|
||||
|
||||
Returns:
|
||||
1-D float tensor of audio samples (24 kHz).
|
||||
"""
|
||||
if self.stream_cache is None:
|
||||
raise ValueError("stream_cache not initialised – call setup_stream() first")
|
||||
|
||||
if prompt_wav not in self.cache:
|
||||
self.cache[prompt_wav] = self._prepare_prompt(prompt_wav)
|
||||
_, _, spk_emb, prompt_mels, _ = self.cache[prompt_wav]
|
||||
|
||||
token_tensor = torch.tensor([audio_tokens], dtype=torch.int32, device=self.device)
|
||||
|
||||
with torch.amp.autocast(
|
||||
str(self.device.type),
|
||||
dtype=torch.float16 if self.float16 else torch.float32,
|
||||
):
|
||||
chunk_mel, self.stream_cache = self.flow.inference_chunk(
|
||||
token=token_tensor,
|
||||
spk=spk_emb,
|
||||
cache=self.stream_cache,
|
||||
last_chunk=last_chunk,
|
||||
n_timesteps=self.n_timesteps,
|
||||
)
|
||||
|
||||
# Trim estimator attention cache to avoid unbounded growth
|
||||
keep = DEFAULT_STREAM_CONFIG.estimator_cache_keep
|
||||
est_att = self.stream_cache.get("estimator_att_cache")
|
||||
if est_att is not None and est_att.shape[4] > (prompt_mels.shape[1] + keep):
|
||||
self.stream_cache["estimator_att_cache"] = torch.cat(
|
||||
[est_att[:, :, :, :, : prompt_mels.shape[1]], est_att[:, :, :, :, -keep:]],
|
||||
dim=4,
|
||||
)
|
||||
|
||||
# ---- HiFT vocoder with overlap-add ----
|
||||
hift_cache_mel = self.hift_cache_dict["mel"]
|
||||
hift_cache_source = self.hift_cache_dict["source"]
|
||||
hift_cache_speech = self.hift_cache_dict["speech"]
|
||||
|
||||
mel = torch.cat([hift_cache_mel, chunk_mel], dim=2)
|
||||
speech, source = self.hift(mel, hift_cache_source)
|
||||
|
||||
# Cross-fade overlap region for smooth concatenation
|
||||
if hift_cache_speech.shape[-1] > 0:
|
||||
speech = fade_in_out(speech, hift_cache_speech, self.speech_window)
|
||||
|
||||
# Update vocoder cache for the next chunk
|
||||
self.hift_cache_dict = {
|
||||
"mel": mel[..., -self.mel_cache_len :].clone().detach(),
|
||||
"source": source[:, :, -self.source_cache_len :].clone().detach(),
|
||||
"speech": speech[:, -self.source_cache_len :].clone().detach(),
|
||||
}
|
||||
|
||||
# For non-last chunks, trim the tail that will be re-synthesised
|
||||
if not last_chunk:
|
||||
speech = speech[:, : -self.source_cache_len]
|
||||
|
||||
return speech.squeeze(0) # [samples]
|
||||
|
||||
def reset_stream(self) -> None:
|
||||
"""Clear all streaming state after an utterance is complete."""
|
||||
self.stream_cache = None
|
||||
self.hift_cache_dict = {}
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Per-request streaming (does NOT mutate self – uses external state)
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def setup_stream_for(self, prompt_wav: str, state: _StreamState) -> None:
|
||||
"""Initialise flow + HiFT caches into *state* (no self mutation)."""
|
||||
if prompt_wav not in self.cache:
|
||||
self.cache[prompt_wav] = self._prepare_prompt(prompt_wav)
|
||||
prompt_speech_tokens, _, spk_emb, prompt_mels, _ = self.cache[prompt_wav]
|
||||
|
||||
if self.speech_window is None or self.speech_window.device != self.device:
|
||||
self.speech_window = torch.from_numpy(np.hamming(2 * self.source_cache_len)).to(
|
||||
device=self.device, dtype=torch.float32
|
||||
)
|
||||
|
||||
pre_lookahead = DEFAULT_STREAM_CONFIG.pre_lookahead_len
|
||||
state.stream_cache = self.flow.setup_cache(
|
||||
torch.cat(
|
||||
[prompt_speech_tokens, prompt_speech_tokens[:, :pre_lookahead]],
|
||||
dim=1,
|
||||
),
|
||||
prompt_mels,
|
||||
spk_emb,
|
||||
n_timesteps=self.n_timesteps,
|
||||
)
|
||||
state.hift_cache_dict = {
|
||||
"mel": torch.zeros(1, prompt_mels.shape[2], 0, device=self.device),
|
||||
"source": torch.zeros(1, 1, 0, device=self.device),
|
||||
"speech": torch.zeros(1, 0, device=self.device),
|
||||
}
|
||||
state.setup_done = True
|
||||
|
||||
def stream_chunk_for(
|
||||
self,
|
||||
audio_tokens: list[int],
|
||||
prompt_wav: str,
|
||||
last_chunk: bool,
|
||||
state: _StreamState,
|
||||
) -> torch.Tensor:
|
||||
"""Process one chunk using *state* (no self mutation except speech_window)."""
|
||||
if state.stream_cache is None:
|
||||
raise ValueError("stream_cache not initialised – call setup_stream_for() first")
|
||||
|
||||
if prompt_wav not in self.cache:
|
||||
self.cache[prompt_wav] = self._prepare_prompt(prompt_wav)
|
||||
_, _, spk_emb, prompt_mels, _ = self.cache[prompt_wav]
|
||||
|
||||
token_tensor = torch.tensor([audio_tokens], dtype=torch.int32, device=self.device)
|
||||
|
||||
with torch.amp.autocast(
|
||||
str(self.device.type),
|
||||
dtype=torch.float16 if self.float16 else torch.float32,
|
||||
):
|
||||
chunk_mel, state.stream_cache = self.flow.inference_chunk(
|
||||
token=token_tensor,
|
||||
spk=spk_emb,
|
||||
cache=state.stream_cache,
|
||||
last_chunk=last_chunk,
|
||||
n_timesteps=self.n_timesteps,
|
||||
)
|
||||
|
||||
# Trim estimator attention cache to avoid unbounded growth
|
||||
keep = DEFAULT_STREAM_CONFIG.estimator_cache_keep
|
||||
est_att = state.stream_cache.get("estimator_att_cache")
|
||||
if est_att is not None and est_att.shape[4] > (prompt_mels.shape[1] + keep):
|
||||
state.stream_cache["estimator_att_cache"] = torch.cat(
|
||||
[
|
||||
est_att[:, :, :, :, : prompt_mels.shape[1]],
|
||||
est_att[:, :, :, :, -keep:],
|
||||
],
|
||||
dim=4,
|
||||
)
|
||||
|
||||
# ---- HiFT vocoder with overlap-add ----
|
||||
hift_cache_mel = state.hift_cache_dict["mel"]
|
||||
hift_cache_source = state.hift_cache_dict["source"]
|
||||
hift_cache_speech = state.hift_cache_dict["speech"]
|
||||
|
||||
mel = torch.cat([hift_cache_mel, chunk_mel], dim=2)
|
||||
speech, source = self.hift(mel, hift_cache_source)
|
||||
|
||||
if hift_cache_speech.shape[-1] > 0:
|
||||
speech = fade_in_out(speech, hift_cache_speech, self.speech_window)
|
||||
|
||||
state.hift_cache_dict = {
|
||||
"mel": mel[..., -self.mel_cache_len :].clone().detach(),
|
||||
"source": source[:, :, -self.source_cache_len :].clone().detach(),
|
||||
"speech": speech[:, -self.source_cache_len :].clone().detach(),
|
||||
}
|
||||
|
||||
if not last_chunk:
|
||||
speech = speech[:, : -self.source_cache_len]
|
||||
|
||||
return speech.squeeze(0)
|
||||
|
||||
@staticmethod
|
||||
def reset_stream_for(state: _StreamState) -> None:
|
||||
"""Clear streaming caches for the given state."""
|
||||
state.stream_cache = None
|
||||
state.hift_cache_dict = {}
|
||||
state.setup_done = False
|
||||
state.finished = True
|
||||
|
||||
|
||||
class StepAudio2Token2WavForConditionalGeneration(nn.Module, SupportsPP):
|
||||
"""vLLM-compatible wrapper for Step-Audio2 Token2Wav"""
|
||||
|
||||
hf_to_vllm_mapper = WeightsMapper(
|
||||
orig_to_new_prefix={
|
||||
"model.": "token2wav.",
|
||||
}
|
||||
)
|
||||
|
||||
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
|
||||
super().__init__()
|
||||
self.vllm_config = vllm_config
|
||||
self.config = vllm_config.model_config.hf_config
|
||||
|
||||
model_path = getattr(self.config, "token2wav_path", None)
|
||||
model_name_or_path = vllm_config.model_config.model
|
||||
if model_path is None:
|
||||
# Resolve HF repo names to local cache path
|
||||
if not os.path.isdir(model_name_or_path):
|
||||
from huggingface_hub import snapshot_download
|
||||
|
||||
model_name_or_path = snapshot_download(model_name_or_path)
|
||||
model_path = f"{model_name_or_path}/token2wav"
|
||||
|
||||
float16 = getattr(self.config, "token2wav_float16", False)
|
||||
|
||||
device = "cuda"
|
||||
if hasattr(vllm_config, "device_config") and vllm_config.device_config:
|
||||
device = str(vllm_config.device_config.device)
|
||||
|
||||
self.token2wav = StepAudio2Token2WavCore(model_path=model_path, float16=float16, device=device)
|
||||
|
||||
self.have_multimodal_outputs = True
|
||||
# Required for the runner to pass async_chunk info via
|
||||
# runtime_additional_information on every forward step.
|
||||
self.enable_update_additional_information = True
|
||||
|
||||
# Per-request streaming states (ordered list matching batch order).
|
||||
self._stream_states: list[_StreamState] = []
|
||||
|
||||
# Resolve default prompt wav path from model directory.
|
||||
# Priority: env var > {model_dir}/assets/default_female.wav > bare filename (cwd)
|
||||
self._default_prompt_wav = self._resolve_prompt_wav(model_name_or_path)
|
||||
|
||||
self.make_empty_intermediate_tensors = lambda: None
|
||||
|
||||
@staticmethod
|
||||
def _resolve_prompt_wav(model_root: str) -> str:
|
||||
"""Find the default prompt wav, searching model assets directory."""
|
||||
env_val = os.environ.get("STEP_AUDIO2_DEFAULT_PROMPT_WAV")
|
||||
if env_val and os.path.exists(env_val):
|
||||
return env_val
|
||||
# Search common locations: model dir, then bundled assets in this package
|
||||
pkg_dir = os.path.dirname(__file__)
|
||||
candidates = [
|
||||
os.path.join(model_root, "assets", STEP_AUDIO2_DEFAULT_PROMPT_WAV),
|
||||
os.path.join(model_root, STEP_AUDIO2_DEFAULT_PROMPT_WAV),
|
||||
os.path.join(pkg_dir, "assets", STEP_AUDIO2_DEFAULT_PROMPT_WAV),
|
||||
os.path.join(pkg_dir, STEP_AUDIO2_DEFAULT_PROMPT_WAV),
|
||||
STEP_AUDIO2_DEFAULT_PROMPT_WAV,
|
||||
]
|
||||
for path in candidates:
|
||||
if os.path.exists(path):
|
||||
return path
|
||||
# Return the env var (even if not found) or the bare filename as fallback
|
||||
return env_val or STEP_AUDIO2_DEFAULT_PROMPT_WAV
|
||||
|
||||
def get_language_model(self) -> torch.nn.Module:
|
||||
# Return the wrapper so vLLM interface helpers resolve
|
||||
# embed_input_ids() on this adapter instead of the bare core model.
|
||||
return self
|
||||
|
||||
@property
|
||||
def sampler(self):
|
||||
return Sampler()
|
||||
|
||||
def embed_input_ids(
|
||||
self,
|
||||
input_ids: torch.Tensor,
|
||||
multimodal_embeddings=None,
|
||||
is_multimodal=None,
|
||||
) -> torch.Tensor:
|
||||
hidden_size = self.vllm_config.model_config.get_hidden_size()
|
||||
return torch.zeros_like(input_ids).reshape(-1, 1).repeat(1, hidden_size)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
intermediate_tensors: IntermediateTensors | None = None,
|
||||
inputs_embeds: torch.Tensor | None = None,
|
||||
additional: dict | None = None,
|
||||
runtime_additional_information: list[dict[str, Any]] | None = None,
|
||||
**kwargs: Any,
|
||||
) -> torch.Tensor | bytes:
|
||||
"""
|
||||
Forward pass for Token2Wav
|
||||
|
||||
Args:
|
||||
input_ids: Audio token IDs (from stage input processor)
|
||||
positions: Position IDs (unused)
|
||||
intermediate_tensors: Intermediate tensors (unused)
|
||||
inputs_embeds: Input embeddings (unused)
|
||||
additional: Additional information dict (deprecated)
|
||||
runtime_additional_information: Per-request dicts from the
|
||||
async_chunk processor. Each dict contains ``audio_tokens``
|
||||
(list[int]) and ``last_chunk`` (bool).
|
||||
**kwargs: Other kwargs
|
||||
|
||||
Returns:
|
||||
OmniOutput with waveform tensor
|
||||
"""
|
||||
# ----- async_chunk streaming path -----
|
||||
# Only enter when at least one entry carries ``left_context_size``
|
||||
# (the field the framework forwards from the async_chunk payload).
|
||||
# The runner always passes runtime_additional_information (possibly
|
||||
# [{}]), so a bare truthiness check would incorrectly enter this
|
||||
# branch in synchronous mode.
|
||||
if runtime_additional_information and any(
|
||||
"left_context_size" in info for info in runtime_additional_information
|
||||
):
|
||||
return self._forward_async_chunk(input_ids, runtime_additional_information, **kwargs)
|
||||
|
||||
# ----- profiling / warmup guard -----
|
||||
# Profile/warmup passes use all-zero token IDs. Real audio tokens
|
||||
# are non-zero, so check sum == 0 rather than a length threshold
|
||||
# (short utterances may have fewer than 50 tokens).
|
||||
if isinstance(input_ids, torch.Tensor):
|
||||
is_profile_mode = input_ids.numel() == 0 or input_ids.sum().item() == 0
|
||||
else:
|
||||
is_profile_mode = not input_ids if not hasattr(input_ids, "__len__") else len(input_ids) == 0
|
||||
|
||||
if is_profile_mode:
|
||||
device = torch.device("cpu")
|
||||
if isinstance(inputs_embeds, torch.Tensor) and inputs_embeds.numel() > 0:
|
||||
device = inputs_embeds.device
|
||||
elif isinstance(input_ids, torch.Tensor) and input_ids.numel() > 0:
|
||||
device = input_ids.device
|
||||
|
||||
dummy_audio = torch.zeros(1000, device=device, dtype=torch.float32)
|
||||
return OmniOutput(
|
||||
text_hidden_states=None,
|
||||
multimodal_outputs={"model_outputs": [dummy_audio]},
|
||||
)
|
||||
|
||||
# ----- synchronous (full-sequence) path -----
|
||||
if isinstance(input_ids, torch.Tensor):
|
||||
if input_ids.dim() == 1:
|
||||
input_ids_list = input_ids.cpu().tolist()
|
||||
else:
|
||||
input_ids_list = input_ids[0].cpu().tolist()
|
||||
else:
|
||||
input_ids_list = input_ids if isinstance(input_ids, list) else [input_ids]
|
||||
|
||||
prompt_wav = self._default_prompt_wav
|
||||
|
||||
if not os.path.exists(prompt_wav):
|
||||
raise FileNotFoundError(f"Token2Wav: prompt_wav file not found: {prompt_wav}")
|
||||
|
||||
waveform_tensor = self.token2wav(input_ids_list, prompt_wav=prompt_wav, return_bytes=False)
|
||||
|
||||
if waveform_tensor.dim() == 2 and waveform_tensor.shape[0] == 1:
|
||||
waveform_tensor = waveform_tensor.squeeze(0)
|
||||
|
||||
waveform_tensor_cpu = waveform_tensor.detach().cpu().contiguous()
|
||||
|
||||
return OmniOutput(
|
||||
text_hidden_states=None,
|
||||
multimodal_outputs={"model_outputs": [waveform_tensor_cpu]},
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Async-chunk streaming forward
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _forward_async_chunk(
|
||||
self,
|
||||
input_ids: torch.Tensor,
|
||||
runtime_additional_information: list[dict[str, Any]],
|
||||
**kwargs: Any,
|
||||
) -> OmniOutput:
|
||||
"""Handle one async_chunk forward step (batch=1).
|
||||
|
||||
The end-of-stream flag is encoded as ``left_context_size == 1``
|
||||
(the only field the framework transparently forwards from the
|
||||
async_chunk payload to ``request.additional_information``).
|
||||
"""
|
||||
# --- batch=1 guard ---
|
||||
batch_size = sum(1 for info in runtime_additional_information if "left_context_size" in info)
|
||||
if batch_size != 1:
|
||||
raise RuntimeError(
|
||||
f"Token2Wav async_chunk only supports batch=1, got {batch_size}. "
|
||||
"Batch>1 requires framework support for batch_req_ids."
|
||||
)
|
||||
|
||||
info = next(info for info in runtime_additional_information if "left_context_size" in info)
|
||||
last_chunk = info.get("left_context_size", 0) == 1
|
||||
|
||||
# --- Manage single stream state ---
|
||||
# If the previous request was preempted (setup_done but not finished),
|
||||
# its stale caches must be discarded before we start a new session.
|
||||
if self._stream_states and not self._stream_states[0].finished:
|
||||
state = self._stream_states[0]
|
||||
if state.setup_done and not last_chunk:
|
||||
# Heuristic: a non-last chunk arriving into an already-active
|
||||
# state that we did NOT set up this call means a new request
|
||||
# reused the slot. For a genuinely continuing request the
|
||||
# state is fine; we cannot distinguish without request IDs,
|
||||
# so we only forcibly reset on an explicit new-session signal
|
||||
# (setup_done=True but stream_cache already consumed all
|
||||
# previous data -- detected below when stream_chunk fails).
|
||||
pass
|
||||
if not self._stream_states or self._stream_states[0].finished:
|
||||
self._stream_states = [_StreamState()]
|
||||
state = self._stream_states[0]
|
||||
|
||||
# --- Extract audio tokens ---
|
||||
audio_tokens = input_ids.flatten().cpu().tolist()
|
||||
|
||||
# Empty chunk (e.g. EOF with no audio tokens)
|
||||
if not audio_tokens:
|
||||
if state.setup_done:
|
||||
self.token2wav.reset_stream_for(state)
|
||||
else:
|
||||
state.finished = True
|
||||
return OmniOutput(
|
||||
text_hidden_states=None,
|
||||
multimodal_outputs={"model_outputs": [torch.zeros(1, dtype=torch.float32)]},
|
||||
)
|
||||
|
||||
prompt_wav = self._default_prompt_wav
|
||||
if not os.path.exists(prompt_wav):
|
||||
raise FileNotFoundError(f"Token2Wav: prompt_wav file not found: {prompt_wav}")
|
||||
|
||||
try:
|
||||
if not state.setup_done:
|
||||
logger.info("Token2Wav: initialising streaming caches")
|
||||
self.token2wav.setup_stream_for(prompt_wav, state)
|
||||
|
||||
waveform = self.token2wav.stream_chunk_for(
|
||||
audio_tokens,
|
||||
prompt_wav=prompt_wav,
|
||||
last_chunk=last_chunk,
|
||||
state=state,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Token2Wav: stream error, resetting state")
|
||||
self.token2wav.reset_stream_for(state)
|
||||
raise
|
||||
|
||||
if last_chunk:
|
||||
self.token2wav.reset_stream_for(state)
|
||||
|
||||
return OmniOutput(
|
||||
text_hidden_states=None,
|
||||
multimodal_outputs={"model_outputs": [waveform.detach().cpu().contiguous()]},
|
||||
)
|
||||
|
||||
def compute_logits(self, hidden_states: torch.Tensor) -> torch.Tensor | None:
|
||||
return hidden_states
|
||||
|
||||
def sample(
|
||||
self,
|
||||
logits: torch.Tensor,
|
||||
sampling_metadata: SamplingMetadata,
|
||||
) -> SamplerOutput | None:
|
||||
return None
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
loaded_params = set()
|
||||
for name, _ in self.token2wav.named_parameters():
|
||||
loaded_params.add(f"token2wav.{name}")
|
||||
for name, _ in self.token2wav.named_buffers():
|
||||
loaded_params.add(f"token2wav.{name}")
|
||||
return loaded_params
|
||||
|
||||
def load_weights_without_buffers(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
loaded_params = set()
|
||||
for name, _ in self.token2wav.named_parameters():
|
||||
loaded_params.add(f"token2wav.{name}")
|
||||
return loaded_params
|
||||
Reference in new issue
Block a user