[Model] Accelerate Breeze-TTS-2 non-streaming inference (#7752)
This commit is contained in:
1 parent
d2aa07159c
commit
3f473a358b
84 files changed
+8191
-5622
No files matched your search
@@ -0,0 +1,7 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from .code2wav import BreezeCode2Wav
|
||||
from .modeling_breeze import BreezeForConditionalGeneration
|
||||
|
||||
__all__ = ["BreezeCode2Wav", "BreezeForConditionalGeneration"]
|
||||
@@ -1,149 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Reference-audio encoding helpers for Breeze-TTS-2.
|
||||
|
||||
The Breeze prompt uses a Qwen3-TTS tokenizer only for reference audio. This
|
||||
module deliberately does not contain text tokenization or waveform decoding;
|
||||
the latter belongs to the pipeline's codec stage.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
|
||||
def resolve_audio_tokenizer_path(model_path: str) -> Path | None:
|
||||
"""Resolve the bundled ``audio_tokenizer`` dir for a local path or HF repo id.
|
||||
|
||||
Local directories (dev checkouts) resolve directly: present returns the
|
||||
subdirectory, absent returns ``None`` so callers can fall back. Repo ids
|
||||
resolve through the vLLM-tagged HF helpers: an already-complete cached
|
||||
snapshot is preferred (offline deployments keep working), and a partial
|
||||
cache falls through to a targeted online fetch restricted to the bundled
|
||||
tokenizer subtree. Returns ``None`` when the checkpoint carries no
|
||||
``audio_tokenizer`` subdirectory.
|
||||
"""
|
||||
root = Path(model_path)
|
||||
if root.is_dir():
|
||||
bundled = root / "audio_tokenizer"
|
||||
return bundled if bundled.is_dir() else None
|
||||
|
||||
from vllm.transformers_utils.repo_utils import hf_api
|
||||
|
||||
kwargs: dict[str, object] = {"allow_patterns": ["audio_tokenizer/*"]}
|
||||
try:
|
||||
cached = Path(hf_api().snapshot_download(model_path, local_files_only=True, **kwargs))
|
||||
except Exception:
|
||||
cached = None
|
||||
if cached is not None and (cached / "audio_tokenizer").is_dir():
|
||||
return cached / "audio_tokenizer"
|
||||
online = Path(hf_api().snapshot_download(model_path, **kwargs))
|
||||
bundled = online / "audio_tokenizer"
|
||||
return bundled if bundled.is_dir() else None
|
||||
|
||||
|
||||
class BreezeReferenceAudioTokenizer:
|
||||
"""Small adapter that normalizes Qwen3-TTS encoder output to ``(T, Q)``.
|
||||
|
||||
The underlying tokenizer is created once per serving worker and is reused
|
||||
for all requests. Keeping this wrapper independent from the
|
||||
prompt builder makes it straightforward to inject a fake encoder in tests
|
||||
and to replace the upstream Qwen3 implementation later.
|
||||
"""
|
||||
|
||||
def __init__(self, tokenizer: Any, *, num_codebooks: int = 16, codebook_size: int = 2048) -> None:
|
||||
self.tokenizer = tokenizer
|
||||
self.num_codebooks = int(num_codebooks)
|
||||
self.codebook_size = int(codebook_size)
|
||||
if self.num_codebooks <= 0 or self.codebook_size <= 0:
|
||||
raise ValueError("num_codebooks and codebook_size must be positive")
|
||||
|
||||
@classmethod
|
||||
def from_pretrained(
|
||||
cls,
|
||||
model_path: str,
|
||||
*,
|
||||
num_codebooks: int = 16,
|
||||
codebook_size: int = 2048,
|
||||
**kwargs: Any,
|
||||
) -> BreezeReferenceAudioTokenizer:
|
||||
"""Load the bundled ``audio_tokenizer`` with the existing Qwen wrapper."""
|
||||
from vllm_omni.model_executor.models.qwen3_tts.qwen3_tts_tokenizer import (
|
||||
Qwen3TTSTokenizer,
|
||||
)
|
||||
|
||||
resolved = resolve_audio_tokenizer_path(model_path)
|
||||
if resolved is None:
|
||||
raise FileNotFoundError(
|
||||
"Breeze reference audio tokenizer was not found for "
|
||||
f"{model_path} (expected an audio_tokenizer/ subdirectory)"
|
||||
)
|
||||
tokenizer = Qwen3TTSTokenizer.from_pretrained(str(resolved), **kwargs)
|
||||
return cls(tokenizer, num_codebooks=num_codebooks, codebook_size=codebook_size)
|
||||
|
||||
@torch.inference_mode()
|
||||
def encode(self, audio: Any, sample_rate: int | None = None) -> torch.Tensor:
|
||||
"""Encode one waveform or audio source into ``(T, Q)`` codes."""
|
||||
if isinstance(audio, torch.Tensor):
|
||||
audio = audio.detach().cpu().numpy()
|
||||
elif isinstance(audio, list) and audio and all(isinstance(x, (int, float)) for x in audio):
|
||||
audio = np.asarray(audio, dtype=np.float32)
|
||||
if isinstance(audio, np.ndarray) and audio.ndim > 1:
|
||||
# Accept both common layouts: (samples, channels) and
|
||||
# (channels, samples). Qwen3TTSTokenizer expects one 1-D clip.
|
||||
channel_first = audio.shape[0] <= 8 and audio.shape[-1] > audio.shape[0]
|
||||
audio = audio.mean(axis=0 if channel_first else -1)
|
||||
|
||||
if isinstance(audio, np.ndarray) and sample_rate is None:
|
||||
raise ValueError("sample_rate is required when ref_audio is a numpy waveform")
|
||||
|
||||
encoded = self.tokenizer.encode(audio, sr=sample_rate)
|
||||
return self._normalize_codes(encoded)
|
||||
|
||||
def _normalize_codes(self, encoded: Any) -> torch.Tensor:
|
||||
codes = getattr(encoded, "audio_codes", None)
|
||||
if codes is None and isinstance(encoded, Mapping):
|
||||
codes = encoded.get("audio_codes")
|
||||
if codes is None and isinstance(encoded, (tuple, list)):
|
||||
codes = encoded[0] if encoded else None
|
||||
if codes is None:
|
||||
raise ValueError("reference audio tokenizer returned no audio_codes")
|
||||
|
||||
if isinstance(codes, (tuple, list)) and codes:
|
||||
# Qwen3TTSTokenizer returns one tensor per input waveform.
|
||||
if len(codes) != 1:
|
||||
raise ValueError(f"only one reference waveform is supported, got {len(codes)}")
|
||||
codes = codes[0]
|
||||
codes = torch.as_tensor(codes)
|
||||
if codes.ndim == 3:
|
||||
if codes.shape[0] != 1:
|
||||
raise ValueError(f"only one reference waveform is supported, got {tuple(codes.shape)}")
|
||||
codes = codes[0]
|
||||
if codes.ndim != 2:
|
||||
raise ValueError(f"reference audio codes must be 2D, got {tuple(codes.shape)}")
|
||||
if codes.shape[0] == 0:
|
||||
raise ValueError("reference audio tokenizer returned no frames")
|
||||
if codes.shape[-1] != self.num_codebooks:
|
||||
if codes.shape[0] == self.num_codebooks:
|
||||
codes = codes.transpose(0, 1)
|
||||
else:
|
||||
raise ValueError(
|
||||
f"reference audio codes must have {self.num_codebooks} codebooks, got {tuple(codes.shape)}"
|
||||
)
|
||||
codes = codes.to(device="cpu", dtype=torch.long).contiguous()
|
||||
if codes.numel() and (int(codes.min()) < 0 or int(codes.max()) >= self.codebook_size):
|
||||
raise ValueError(
|
||||
f"reference audio code outside [0, {self.codebook_size}): "
|
||||
f"min={int(codes.min())}, max={int(codes.max())}"
|
||||
)
|
||||
# int16 is enough for Mimi/Qwen3-TTS codes and halves IPC/cache memory.
|
||||
return codes.to(dtype=torch.int16)
|
||||
|
||||
|
||||
__all__ = ["BreezeReferenceAudioTokenizer", "resolve_audio_tokenizer_path"]
|
||||
@@ -0,0 +1,13 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from vllm_omni.model_executor.models.qwen3_tts.qwen3_tts_code2wav import Qwen3TTSCode2Wav
|
||||
|
||||
|
||||
class BreezeCode2Wav(Qwen3TTSCode2Wav):
|
||||
"""Breeze bundles the same Qwen3 codec under audio_tokenizer/."""
|
||||
|
||||
tokenizer_subfolder = "audio_tokenizer"
|
||||
# Reference conditioning is consumed by the AR stage. The codec receives
|
||||
# generated codes only, so it never decodes an ICL reference prefix.
|
||||
decoder_cudagraph_modes = ("xvec",)
|
||||
@@ -0,0 +1,47 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Configuration for the released Breeze-TTS-2 checkpoint."""
|
||||
|
||||
from transformers import LlamaConfig, PretrainedConfig, Qwen3Config
|
||||
from transformers.models.t5gemma2.configuration_t5gemma2 import T5Gemma2TextConfig
|
||||
|
||||
|
||||
class BreezeConfig(PretrainedConfig):
|
||||
model_type = "breeze"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
backbone_config: dict | None = None,
|
||||
depth_decoder_config: dict | None = None,
|
||||
text_encoder_config: dict | None = None,
|
||||
num_codebooks: int = 16,
|
||||
audio_vocab_size: int = 2051,
|
||||
audio_embed_size: int = 2048,
|
||||
max_position_embeddings: int = 2048,
|
||||
rope_scaling: dict | None = None,
|
||||
rope_theta: float = 500000.0,
|
||||
**kwargs: object,
|
||||
) -> None:
|
||||
self.max_position_embeddings = max_position_embeddings
|
||||
self.rope_parameters = {"rope_theta": rope_theta, **(rope_scaling or {"rope_type": "default"})}
|
||||
self.num_codebooks = num_codebooks
|
||||
self.audio_vocab_size = audio_vocab_size
|
||||
self.audio_embed_size = audio_embed_size
|
||||
self.backbone_config = Qwen3Config(**(backbone_config or {}))
|
||||
self.depth_decoder_config = LlamaConfig(**(depth_decoder_config or {}))
|
||||
self.text_encoder_config = T5Gemma2TextConfig(**(text_encoder_config or {}))
|
||||
# The scheduler samples continuation/EOS tokens. Text encoder IDs are
|
||||
# carried in the prompt payload and are outside this vocabulary.
|
||||
self.vocab_size = audio_vocab_size + 1
|
||||
self.eos_token_id = audio_vocab_size
|
||||
self.backbone_config.vocab_size = self.vocab_size
|
||||
self.backbone_config.bos_token_id = 0
|
||||
self.backbone_config.pad_token_id = 0
|
||||
self.backbone_config.eos_token_id = self.eos_token_id
|
||||
self.backbone_config.tie_word_embeddings = False
|
||||
super().__init__(**kwargs)
|
||||
self.vocab_size = audio_vocab_size + 1
|
||||
self.eos_token_id = audio_vocab_size
|
||||
|
||||
def get_text_config(self, decoder: bool = False) -> Qwen3Config:
|
||||
return self.backbone_config
|
||||
@@ -1,366 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Configuration classes for Breeze-TTS-2."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from transformers import AutoConfig
|
||||
from transformers.configuration_utils import PretrainedConfig
|
||||
from transformers.models.qwen3 import Qwen3Config
|
||||
|
||||
|
||||
class BreezeTTS2Config(PretrainedConfig):
|
||||
"""Configuration for ``BreezeForConditionalGeneration``."""
|
||||
|
||||
model_type = "breeze"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
backbone_config: dict | Qwen3Config | None = None,
|
||||
text_encoder_config: dict | BreezeTTS2TextEncoderConfig | None = None,
|
||||
depth_decoder_config: dict | BreezeTTS2DepthDecoderConfig | None = None,
|
||||
codec_config: dict | None = None,
|
||||
architectures: list[str] | None = None,
|
||||
attention_bias: bool = False,
|
||||
attention_dropout: float = 0.0,
|
||||
audio_embed_size: int = 2048,
|
||||
audio_eos_token_id: int = 262145,
|
||||
audio_num_codebooks: int = 16,
|
||||
audio_token_id: int = 262144,
|
||||
audio_vocab_size: int = 2051,
|
||||
backbone_flavor: str = "llama-1B",
|
||||
backbone_model_name_or_path: str | None = None,
|
||||
backbone_model_type: str = "qwen3",
|
||||
bos_token_id: int = 2,
|
||||
codebook_eos_token_id: int = 0,
|
||||
codebook_pad_token_id: int = 2050,
|
||||
decoder_flavor: str = "llama-100M",
|
||||
depth_header_loss_weight: float = 1.0,
|
||||
dtype: str = "bfloat16",
|
||||
eos_token_id: int = 1,
|
||||
head_dim: int = 128,
|
||||
hidden_act: str = "silu",
|
||||
hidden_size: int = 2048,
|
||||
initializer_range: float = 0.02,
|
||||
intermediate_size: int = 6144,
|
||||
max_position_embeddings: int = 2048,
|
||||
mlp_bias: bool = False,
|
||||
num_attention_heads: int = 16,
|
||||
num_codebooks: int = 16,
|
||||
num_hidden_layers: int = 28,
|
||||
num_key_value_heads: int = 8,
|
||||
pad_token_id: int = 0,
|
||||
rms_norm_eps: float = 1e-5,
|
||||
rope_scaling: dict | None = None,
|
||||
rope_theta: float = 500_000.0,
|
||||
text_encoder_bucket_max_length_ratio: float = 4.0,
|
||||
text_encoder_lora_config: dict | None = None,
|
||||
text_encoder_proj_type: str = "linear",
|
||||
text_encoder_special_tokens_config: dict | None = None,
|
||||
text_vocab_size: int = 262158,
|
||||
tie_codebooks_embeddings: bool = True,
|
||||
tie_word_embeddings: bool = False,
|
||||
use_cache: bool = True,
|
||||
vocab_size: int = 2051,
|
||||
sampling_rate: int = 24000,
|
||||
codec_model_name_or_path: str = "kyutai/mimi",
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
serialized_rope_parameters = kwargs.pop("rope_parameters", None)
|
||||
if rope_scaling is None and serialized_rope_parameters is not None:
|
||||
rope_scaling = serialized_rope_parameters
|
||||
# Breeze stores the Qwen3 backbone in backbone_config. This follows the
|
||||
# MOSS-TTS pattern and deliberately does not declare sub_configs.
|
||||
if backbone_config is None:
|
||||
backbone_config = {}
|
||||
if isinstance(backbone_config, dict):
|
||||
backbone_config = dict(backbone_config)
|
||||
backbone_config.pop("model_type", None)
|
||||
self.backbone_config = Qwen3Config(**backbone_config)
|
||||
else:
|
||||
self.backbone_config = backbone_config
|
||||
|
||||
if text_encoder_config is None:
|
||||
text_encoder_config = {}
|
||||
if isinstance(text_encoder_config, dict):
|
||||
text_encoder_config = dict(text_encoder_config)
|
||||
text_encoder_config.pop("model_type", None)
|
||||
self.text_encoder_config = BreezeTTS2TextEncoderConfig(**text_encoder_config)
|
||||
else:
|
||||
self.text_encoder_config = text_encoder_config
|
||||
|
||||
if depth_decoder_config is None:
|
||||
depth_decoder_config = {}
|
||||
if isinstance(depth_decoder_config, dict):
|
||||
depth_decoder_config = dict(depth_decoder_config)
|
||||
depth_decoder_config.pop("model_type", None)
|
||||
self.depth_decoder_config = BreezeTTS2DepthDecoderConfig(**depth_decoder_config)
|
||||
else:
|
||||
self.depth_decoder_config = depth_decoder_config
|
||||
|
||||
# Nested configs must exist before the parent constructor: Transformers
|
||||
# 5.x may call get_text_config() during config validation.
|
||||
super().__init__(
|
||||
architectures=architectures,
|
||||
bos_token_id=bos_token_id,
|
||||
eos_token_id=eos_token_id,
|
||||
pad_token_id=pad_token_id,
|
||||
tie_word_embeddings=tie_word_embeddings,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
self.attention_bias = attention_bias
|
||||
self.attention_dropout = attention_dropout
|
||||
self.audio_embed_size = audio_embed_size
|
||||
self.audio_eos_token_id = audio_eos_token_id
|
||||
self.audio_num_codebooks = audio_num_codebooks
|
||||
self.audio_token_id = audio_token_id
|
||||
self.audio_vocab_size = audio_vocab_size
|
||||
# Keep Mimi's nested config as a plain checkpoint dictionary. Stage 1
|
||||
# owns codec construction; stage 0 only needs codebook_size here.
|
||||
self.codec_config = codec_config
|
||||
self.backbone_flavor = backbone_flavor
|
||||
self.backbone_model_name_or_path = backbone_model_name_or_path
|
||||
self.backbone_model_type = backbone_model_type
|
||||
self.codebook_eos_token_id = codebook_eos_token_id
|
||||
self.codebook_pad_token_id = codebook_pad_token_id
|
||||
self.decoder_flavor = decoder_flavor
|
||||
self.depth_header_loss_weight = depth_header_loss_weight
|
||||
self.dtype = dtype
|
||||
self.head_dim = head_dim
|
||||
self.hidden_act = hidden_act
|
||||
self.hidden_size = hidden_size
|
||||
self.initializer_range = initializer_range
|
||||
self.intermediate_size = intermediate_size
|
||||
self.max_position_embeddings = max_position_embeddings
|
||||
self.mlp_bias = mlp_bias
|
||||
self.num_attention_heads = num_attention_heads
|
||||
self.num_codebooks = num_codebooks
|
||||
self.num_hidden_layers = num_hidden_layers
|
||||
self.num_key_value_heads = num_key_value_heads
|
||||
self.rms_norm_eps = rms_norm_eps
|
||||
if rope_scaling is not None:
|
||||
# Preserve the upstream legacy field while also satisfying the
|
||||
# normalized ``rope_parameters`` validation added in Transformers 5.
|
||||
rope_scaling = dict(rope_scaling)
|
||||
rope_scaling.setdefault("rope_type", rope_scaling.get("type", "default"))
|
||||
rope_scaling.setdefault("rope_theta", rope_theta)
|
||||
self.rope_scaling = rope_scaling
|
||||
self.rope_theta = rope_theta
|
||||
self.text_encoder_bucket_max_length_ratio = text_encoder_bucket_max_length_ratio
|
||||
self.text_encoder_lora_config = text_encoder_lora_config or {}
|
||||
self.text_encoder_proj_type = text_encoder_proj_type
|
||||
self.text_encoder_special_tokens_config = text_encoder_special_tokens_config or {}
|
||||
self.text_vocab_size = text_vocab_size
|
||||
self.tie_codebooks_embeddings = tie_codebooks_embeddings
|
||||
self.use_cache = use_cache
|
||||
self.vocab_size = vocab_size
|
||||
self.sampling_rate = sampling_rate
|
||||
self.codec_model_name_or_path = codec_model_name_or_path
|
||||
|
||||
if not getattr(self, "architectures", None):
|
||||
self.architectures = ["BreezeForConditionalGeneration"]
|
||||
|
||||
def get_text_config(self, **_: Any) -> Qwen3Config:
|
||||
return self.backbone_config
|
||||
|
||||
|
||||
class BreezeTTS2TextEncoderConfig(PretrainedConfig):
|
||||
"""Configuration for Breeze's T5Gemma2 text encoder."""
|
||||
|
||||
model_type = "t5gemma2_text"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
hidden_size: int = 1152,
|
||||
intermediate_size: int = 6912,
|
||||
num_hidden_layers: int = 26,
|
||||
num_attention_heads: int = 4,
|
||||
num_key_value_heads: int = 1,
|
||||
head_dim: int = 256,
|
||||
max_position_embeddings: int = 32768,
|
||||
hidden_activation: str = "gelu_pytorch_tanh",
|
||||
rms_norm_eps: float = 1e-6,
|
||||
rope_theta: float = 10_000.0,
|
||||
sliding_window: int = 512,
|
||||
query_pre_attn_scalar: int = 256,
|
||||
eoi_token_index: int = 256000,
|
||||
vocab_size: int = 262158,
|
||||
layer_types: list[str] | None = None,
|
||||
rope_parameters: dict | None = None,
|
||||
attention_bias: bool = False,
|
||||
attention_dropout: float = 0.0,
|
||||
dropout_rate: float = 0.0,
|
||||
initializer_range: float = 0.02,
|
||||
tie_word_embeddings: bool = True,
|
||||
use_bidirectional_attention: bool = False,
|
||||
use_cache: bool = True,
|
||||
requires_grad: bool = False,
|
||||
preferred_attn_implementation: str = "flash_attention_2",
|
||||
dtype: str = "bfloat16",
|
||||
is_encoder_decoder: bool = False,
|
||||
bos_token_id: int = 2,
|
||||
eos_token_id: int = 1,
|
||||
pad_token_id: int = 0,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
kwargs.pop("model_type", None)
|
||||
|
||||
super().__init__(
|
||||
bos_token_id=bos_token_id,
|
||||
eos_token_id=eos_token_id,
|
||||
pad_token_id=pad_token_id,
|
||||
is_encoder_decoder=is_encoder_decoder,
|
||||
tie_word_embeddings=tie_word_embeddings,
|
||||
**kwargs,
|
||||
)
|
||||
self.hidden_size = hidden_size
|
||||
self.intermediate_size = intermediate_size
|
||||
self.num_hidden_layers = num_hidden_layers
|
||||
self.num_attention_heads = num_attention_heads
|
||||
self.num_key_value_heads = num_key_value_heads
|
||||
self.head_dim = head_dim
|
||||
self.max_position_embeddings = max_position_embeddings
|
||||
self.hidden_activation = hidden_activation
|
||||
self.hidden_act = hidden_activation
|
||||
self.rms_norm_eps = rms_norm_eps
|
||||
self.rope_theta = rope_theta
|
||||
self.sliding_window = sliding_window
|
||||
self.query_pre_attn_scalar = query_pre_attn_scalar
|
||||
self.eoi_token_index = eoi_token_index
|
||||
self.vocab_size = vocab_size
|
||||
if layer_types is None:
|
||||
# T5Gemma2 uses sliding attention except every sixth layer.
|
||||
layer_types = [
|
||||
"full_attention" if (index + 1) % 6 == 0 else "sliding_attention" for index in range(num_hidden_layers)
|
||||
]
|
||||
self.layer_types = list(layer_types)
|
||||
if rope_parameters is None:
|
||||
rope_parameters = {
|
||||
"full_attention": {
|
||||
"factor": 8.0,
|
||||
"rope_theta": 1_000_000.0,
|
||||
"rope_type": "linear",
|
||||
},
|
||||
"sliding_attention": {
|
||||
"rope_theta": 10_000.0,
|
||||
"rope_type": "default",
|
||||
},
|
||||
}
|
||||
self.rope_parameters = dict(rope_parameters)
|
||||
self.attention_bias = attention_bias
|
||||
self.attention_dropout = attention_dropout
|
||||
self.dropout_rate = dropout_rate
|
||||
self.initializer_range = initializer_range
|
||||
self.use_bidirectional_attention = use_bidirectional_attention
|
||||
self.use_cache = use_cache
|
||||
self.requires_grad = requires_grad
|
||||
self.preferred_attn_implementation = preferred_attn_implementation
|
||||
self.dtype = dtype
|
||||
|
||||
|
||||
class BreezeTTS2DepthDecoderConfig(PretrainedConfig):
|
||||
"""Configuration for Breeze's per-frame depth decoder."""
|
||||
|
||||
model_type = "breeze_depth_decoder_model"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
hidden_size: int = 1024,
|
||||
backbone_hidden_size: int = 2048,
|
||||
audio_embed_size: int = 2048,
|
||||
intermediate_size: int = 8192,
|
||||
num_hidden_layers: int = 12,
|
||||
num_attention_heads: int = 8,
|
||||
num_key_value_heads: int = 2,
|
||||
head_dim: int = 128,
|
||||
max_position_embeddings: int = 33,
|
||||
hidden_act: str = "silu",
|
||||
rms_norm_eps: float = 1e-5,
|
||||
rope_theta: float = 500_000.0,
|
||||
rope_scaling: dict | None = None,
|
||||
attention_bias: bool = False,
|
||||
attention_dropout: float = 0.0,
|
||||
mlp_bias: bool = False,
|
||||
initializer_range: float = 0.02,
|
||||
use_cache: bool = True,
|
||||
num_codebooks: int = 16,
|
||||
vocab_size: int = 2051,
|
||||
codebook_loss_weights: list[int] | None = None,
|
||||
dtype: str = "bfloat16",
|
||||
tie_word_embeddings: bool = False,
|
||||
pad_token_id: int | None = 0,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
kwargs.pop("model_type", None)
|
||||
# Transformers 5 serializes the normalized field as
|
||||
# ``rope_parameters`` while the upstream Breeze checkpoint calls it
|
||||
# ``rope_scaling``. Normalize before ``PretrainedConfig`` validates
|
||||
# so ``to_dict() -> BreezeTTS2DepthDecoderConfig(**dict)`` round-trips.
|
||||
serialized_rope_parameters = kwargs.pop("rope_parameters", None)
|
||||
if rope_scaling is None:
|
||||
rope_scaling = {
|
||||
"factor": 32.0,
|
||||
"high_freq_factor": 0.0078125,
|
||||
"low_freq_factor": 0.001953125,
|
||||
"original_max_position_embeddings": 16,
|
||||
"rope_type": "llama3",
|
||||
}
|
||||
if codebook_loss_weights is None:
|
||||
codebook_loss_weights = [3]
|
||||
if num_codebooks <= 0 or vocab_size <= 0:
|
||||
raise ValueError("num_codebooks and vocab_size must be positive")
|
||||
rope_parameters = dict(serialized_rope_parameters or rope_scaling)
|
||||
rope_parameters.setdefault("rope_type", rope_parameters.get("type", "default"))
|
||||
rope_parameters.setdefault("rope_theta", rope_theta)
|
||||
|
||||
super().__init__(
|
||||
vocab_size=vocab_size,
|
||||
tie_word_embeddings=tie_word_embeddings,
|
||||
pad_token_id=pad_token_id,
|
||||
**kwargs,
|
||||
)
|
||||
# The vLLM depth decoder is a plain ``nn.Module``, so it does not get
|
||||
# Transformers' PreTrainedModel default attention initialization.
|
||||
self._attn_implementation = getattr(self, "_attn_implementation", None) or "eager"
|
||||
self.hidden_size = hidden_size
|
||||
self.backbone_hidden_size = backbone_hidden_size
|
||||
self.audio_embed_size = audio_embed_size
|
||||
self.intermediate_size = intermediate_size
|
||||
self.num_hidden_layers = num_hidden_layers
|
||||
self.num_attention_heads = num_attention_heads
|
||||
self.num_key_value_heads = num_key_value_heads
|
||||
self.head_dim = head_dim
|
||||
self.max_position_embeddings = max_position_embeddings
|
||||
self.hidden_act = hidden_act
|
||||
self.rms_norm_eps = rms_norm_eps
|
||||
self.rope_theta = rope_theta
|
||||
self.rope_parameters = dict(getattr(self, "rope_parameters", None) or rope_parameters)
|
||||
self.rope_parameters.setdefault("rope_theta", rope_theta)
|
||||
# Transformers 4 exposes this as a plain attribute; Transformers 5
|
||||
# implements ``rope_scaling`` as a property backed by rope_parameters.
|
||||
if not hasattr(type(self), "rope_scaling"):
|
||||
self.rope_scaling = self.rope_parameters
|
||||
self.rope_type = rope_scaling.get("rope_type", "default")
|
||||
self.attention_bias = attention_bias
|
||||
self.attention_dropout = attention_dropout
|
||||
self.mlp_bias = mlp_bias
|
||||
self.initializer_range = initializer_range
|
||||
self.use_cache = use_cache
|
||||
self.num_codebooks = num_codebooks
|
||||
self.vocab_size = vocab_size
|
||||
self.codebook_loss_weights = list(codebook_loss_weights)
|
||||
self.dtype = dtype
|
||||
|
||||
|
||||
AutoConfig.register("breeze", BreezeTTS2Config, exist_ok=True)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"BreezeTTS2Config",
|
||||
"BreezeTTS2DepthDecoderConfig",
|
||||
"BreezeTTS2TextEncoderConfig",
|
||||
]
|
||||
@@ -0,0 +1,409 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Breeze's within-frame transformer, with frame-local KV state.
|
||||
|
||||
Attention follows the reference BF16 matmul / FP32 softmax ordering. Each
|
||||
frame overwrites its causal cache before reading it. Captured workspaces
|
||||
belong to their graphs; generated frames and RNG state belong to requests.
|
||||
"""
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import nn
|
||||
from transformers import PretrainedConfig
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
|
||||
def sample_logits(
|
||||
logits: torch.Tensor,
|
||||
temperature: float,
|
||||
top_k: int,
|
||||
top_p: float,
|
||||
generator: torch.Generator,
|
||||
noise: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Sample using scalar parameters, optionally with pre-drawn noise.
|
||||
|
||||
Keep the filtering contract aligned with ``sample_graph_logits``: scale
|
||||
in FP32, retain top-k ties, and remove nucleus candidates only when the
|
||||
cumulative mass before them is >= top_p. Temperature zero selects argmax
|
||||
without drawing RNG. The parity tests cover ties and exact boundaries.
|
||||
"""
|
||||
if temperature == 0:
|
||||
return logits.argmax(-1)
|
||||
scores = logits.float() / temperature
|
||||
if top_k > 0:
|
||||
threshold = scores.topk(min(top_k, scores.shape[-1]), dim=-1).values[..., -1:]
|
||||
scores = scores.masked_fill(scores < threshold, -torch.inf)
|
||||
if top_p < 1:
|
||||
values, indices = scores.sort(dim=-1, descending=True)
|
||||
probabilities = values.softmax(-1)
|
||||
cumulative = probabilities.cumsum(-1)
|
||||
# Keep the first candidate crossing the nucleus boundary as in HF.
|
||||
remove = cumulative - probabilities >= top_p
|
||||
scores = scores.scatter(-1, indices, values.masked_fill(remove, -torch.inf))
|
||||
probabilities = scores.softmax(-1)
|
||||
if noise is not None:
|
||||
return (probabilities / noise).argmax(-1)
|
||||
return torch.multinomial(probabilities, 1, generator=generator).squeeze(-1)
|
||||
|
||||
|
||||
def sample_graph_logits(logits: torch.Tensor, parameters: torch.Tensor, noise: torch.Tensor) -> torch.Tensor:
|
||||
"""Sample with mutable GPU parameters and a request-owned RNG draw.
|
||||
|
||||
Sorting once supplies both the top-k threshold and the nucleus order.
|
||||
Filtering keeps ties at the top-k threshold, and keeps the first token
|
||||
crossing the nucleus boundary. The three reserved codec IDs remain in
|
||||
the RNG workspace, with zero probability, as in the reference sampler.
|
||||
|
||||
Replay can change parameters, so selection uses tensor operations rather
|
||||
than ``sample_logits``' Python branches on scalar parameters. Keep their
|
||||
FP32 scaling and top-k/top-p boundaries aligned without sharing that
|
||||
control flow. This path consumes supplied noise; its caller owns RNG
|
||||
advancement and must avoid advancing request RNG for greedy decoding.
|
||||
"""
|
||||
temperature, top_k, top_p = parameters.unbind()
|
||||
scaled = logits.float() / torch.where(temperature > 0, temperature, 1.0)
|
||||
values, indices = scaled.sort(dim=-1, descending=True)
|
||||
cutoff = torch.where(top_k > 0, top_k, logits.shape[-1]).long().clamp(1, logits.shape[-1]) - 1
|
||||
threshold = values.gather(-1, cutoff.expand(values.shape[0], 1))
|
||||
values = values.masked_fill(values < threshold, -torch.inf)
|
||||
probabilities = values.softmax(-1)
|
||||
cumulative = probabilities.cumsum(-1)
|
||||
# Use the same boundary and arithmetic as the eager sampler, including
|
||||
# an exactly representable cumulative probability equal to top_p.
|
||||
remove = (cumulative - probabilities >= top_p) & (top_p < 1)
|
||||
values = values.masked_fill(remove, -torch.inf)
|
||||
# Argmax of p / Exp(1) is the single-sample multinomial algorithm.
|
||||
selected = (values.softmax(-1) / noise.gather(-1, indices)).argmax(-1, keepdim=True)
|
||||
sampled = indices.gather(-1, selected).squeeze(-1)
|
||||
return torch.where(temperature > 0, sampled, logits.argmax(-1))
|
||||
|
||||
|
||||
class BreezeRMSNorm(nn.Module):
|
||||
def __init__(self, size: int, eps: float) -> None:
|
||||
super().__init__()
|
||||
self.weight = nn.Parameter(torch.ones(size))
|
||||
self.eps = eps
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
y = x.float()
|
||||
y = y * torch.rsqrt(y.square().mean(-1, keepdim=True) + self.eps)
|
||||
return self.weight * y.to(x.dtype)
|
||||
|
||||
|
||||
class BreezeDepthLayer(nn.Module):
|
||||
def __init__(self, config: PretrainedConfig) -> None:
|
||||
super().__init__()
|
||||
self.heads = config.num_attention_heads
|
||||
self.kv_heads = config.num_key_value_heads
|
||||
self.dim = config.head_dim
|
||||
self.q_size = self.heads * self.dim
|
||||
self.kv_size = self.kv_heads * self.dim
|
||||
self.qkv = nn.Linear(config.hidden_size, self.q_size + 2 * self.kv_size, bias=False)
|
||||
self.o_proj = nn.Linear(self.q_size, config.hidden_size, bias=False)
|
||||
self.gate_up = nn.Linear(config.hidden_size, 2 * config.intermediate_size, bias=False)
|
||||
self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
|
||||
self.input_layernorm = BreezeRMSNorm(config.hidden_size, config.rms_norm_eps)
|
||||
self.post_attention_layernorm = BreezeRMSNorm(config.hidden_size, config.rms_norm_eps)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
cache: tuple[torch.Tensor, torch.Tensor],
|
||||
mask: torch.Tensor,
|
||||
cos: torch.Tensor,
|
||||
sin: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
batch, length, _ = x.shape
|
||||
residual = x
|
||||
q, k, v = self.qkv(self.input_layernorm(x)).split([self.q_size, self.kv_size, self.kv_size], -1)
|
||||
q = q.view(batch, length, self.heads, self.dim).transpose(1, 2)
|
||||
k = k.view(batch, length, self.kv_heads, self.dim).transpose(1, 2)
|
||||
v = v.view(batch, length, self.kv_heads, self.dim).transpose(1, 2)
|
||||
q1, q2 = q.chunk(2, -1)
|
||||
k1, k2 = k.chunk(2, -1)
|
||||
q = q * cos + torch.cat((-q2, q1), -1) * sin
|
||||
k = k * cos + torch.cat((-k2, k1), -1) * sin
|
||||
cache[0].index_copy_(2, positions, k)
|
||||
cache[1].index_copy_(2, positions, v)
|
||||
# Fold query heads sharing one KV head into its query dimension.
|
||||
# This avoids materializing repeated keys/values for grouped-query
|
||||
# attention while preserving BF16 matmul and FP32 softmax ordering.
|
||||
grouped_q = q.reshape(batch, self.kv_heads, self.heads // self.kv_heads * length, self.dim)
|
||||
scores = (
|
||||
torch.matmul(grouped_q, cache[0].transpose(-1, -2)).reshape(batch, self.heads, length, cache[0].shape[2])
|
||||
* self.dim**-0.5
|
||||
)
|
||||
scores = scores.masked_fill(~mask, torch.finfo(q.dtype).min)
|
||||
probabilities = scores.softmax(-1, dtype=torch.float32).to(q.dtype)
|
||||
grouped_probabilities = probabilities.reshape(batch, self.kv_heads, -1, cache[0].shape[2])
|
||||
y = torch.matmul(grouped_probabilities, cache[1]).reshape(batch, self.heads, length, self.dim)
|
||||
y = y.transpose(1, 2).reshape(batch, length, self.q_size)
|
||||
x = residual + self.o_proj(y)
|
||||
gate, up = self.gate_up(self.post_attention_layernorm(x)).chunk(2, -1)
|
||||
return x + self.down_proj(F.silu(gate) * up)
|
||||
|
||||
|
||||
class BreezeDepthDecoder(nn.Module):
|
||||
def __init__(self, config: PretrainedConfig) -> None:
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.num_codebooks = config.num_codebooks
|
||||
self.vocab_size = config.vocab_size
|
||||
self.embed_tokens = nn.Embedding(self.num_codebooks * self.vocab_size, config.audio_embed_size)
|
||||
self.inputs_embeds_projector = nn.Linear(config.audio_embed_size, config.hidden_size, bias=False)
|
||||
self.layers = nn.ModuleList([BreezeDepthLayer(config) for _ in range(config.num_hidden_layers)])
|
||||
self.norm = BreezeRMSNorm(config.hidden_size, config.rms_norm_eps)
|
||||
self.codebooks_head = nn.Parameter(
|
||||
torch.empty(self.num_codebooks - 1, config.hidden_size, self.vocab_size, dtype=torch.float32)
|
||||
)
|
||||
rope = config.rope_parameters
|
||||
inv = 1.0 / (rope["rope_theta"] ** (torch.arange(0, config.head_dim, 2).float() / config.head_dim))
|
||||
wavelength = 2 * torch.pi / inv
|
||||
low = rope["original_max_position_embeddings"] / rope["low_freq_factor"]
|
||||
high = rope["original_max_position_embeddings"] / rope["high_freq_factor"]
|
||||
smooth = (rope["original_max_position_embeddings"] / wavelength - rope["low_freq_factor"]) / (
|
||||
rope["high_freq_factor"] - rope["low_freq_factor"]
|
||||
)
|
||||
scaled = (1 - smooth) * inv / rope["factor"] + smooth * inv
|
||||
inv = torch.where(wavelength > low, inv / rope["factor"], torch.where(wavelength < high, inv, scaled))
|
||||
angles = torch.outer(torch.arange(self.num_codebooks).float(), inv)
|
||||
angles = torch.cat((angles, angles), -1)
|
||||
self.register_buffer("rope_cos", angles.cos(), persistent=False)
|
||||
self.register_buffer("rope_sin", angles.sin(), persistent=False)
|
||||
self.register_buffer("positions", torch.arange(self.num_codebooks), persistent=False)
|
||||
self.register_buffer(
|
||||
"causal_mask",
|
||||
torch.arange(self.num_codebooks)[None, :] <= torch.arange(self.num_codebooks)[:, None],
|
||||
persistent=False,
|
||||
)
|
||||
self._graphs: dict[tuple[int, int, bool], BreezeDepthGraph] = {}
|
||||
self._compiled_layer = None
|
||||
self._compiled_sampler = None
|
||||
|
||||
def _allocate_cache(self, hidden: torch.Tensor) -> list[tuple[torch.Tensor, torch.Tensor]]:
|
||||
shape = (hidden.shape[0], self.config.num_key_value_heads, self.num_codebooks, self.config.head_dim)
|
||||
# Masked future positions still participate in the value matmul.
|
||||
# Initialize them to finite values so zero probabilities cannot meet NaN.
|
||||
return [(hidden.new_zeros(shape), hidden.new_zeros(shape)) for _ in self.layers]
|
||||
|
||||
def generate_frame(
|
||||
self,
|
||||
hidden: torch.Tensor,
|
||||
first: torch.Tensor,
|
||||
*,
|
||||
temperature: float,
|
||||
top_k: int,
|
||||
top_p: float,
|
||||
generator: torch.Generator,
|
||||
) -> torch.Tensor:
|
||||
return self._generate_frame(hidden, first, self._allocate_cache(hidden), temperature, top_k, top_p, generator)
|
||||
|
||||
def _generate_frame(
|
||||
self,
|
||||
hidden: torch.Tensor,
|
||||
first: torch.Tensor,
|
||||
caches: list[tuple[torch.Tensor, torch.Tensor]],
|
||||
temperature: float,
|
||||
top_k: int,
|
||||
top_p: float,
|
||||
generator: torch.Generator,
|
||||
noise: torch.Tensor | None = None,
|
||||
guidance_scale: float | torch.Tensor | None = None,
|
||||
sampling_parameters: torch.Tensor | None = None,
|
||||
greedy: bool = False,
|
||||
) -> torch.Tensor:
|
||||
batch = hidden.shape[0]
|
||||
branches = 2 if guidance_scale is not None else 1
|
||||
branch_first = first.repeat(branches)
|
||||
x = torch.cat((hidden.unsqueeze(1), self.embed_tokens(branch_first.reshape(batch, 1))), 1)
|
||||
frames = [first]
|
||||
start = 0
|
||||
for codebook in range(self.num_codebooks - 1):
|
||||
x = self.inputs_embeds_projector(x)
|
||||
end = start + x.shape[1]
|
||||
cos = self.rope_cos[start:end].to(x.dtype)[None, None]
|
||||
sin = self.rope_sin[start:end].to(x.dtype)[None, None]
|
||||
for layer, cache in zip(self.layers, caches, strict=True):
|
||||
args = (x, self.positions[start:end], cache, self.causal_mask[start:end][None, None], cos, sin)
|
||||
if noise is None and not greedy:
|
||||
x = layer(*args)
|
||||
else:
|
||||
x = self._compiled_layer(layer, *args)
|
||||
logits = F.linear(self.norm(x[:, -1]).float(), self.codebooks_head[codebook].T.float())
|
||||
if guidance_scale is not None:
|
||||
cond, uncond = logits.chunk(2, dim=0)
|
||||
logits = uncond + guidance_scale * (cond - uncond)
|
||||
logits[:, self.vocab_size - 3 :] = -torch.inf
|
||||
if greedy:
|
||||
token = logits.argmax(-1)
|
||||
elif noise is None:
|
||||
token = sample_logits(logits, temperature, top_k, top_p, generator)
|
||||
else:
|
||||
token = self._compiled_sampler(logits, sampling_parameters, noise[:, codebook])
|
||||
frames.append(token)
|
||||
x = self.embed_tokens((token.repeat(branches) + (codebook + 1) * self.vocab_size).reshape(batch, 1))
|
||||
start = end
|
||||
return torch.stack(frames, -1)
|
||||
|
||||
def generate_frames(
|
||||
self,
|
||||
hidden: torch.Tensor,
|
||||
first: torch.Tensor,
|
||||
*,
|
||||
temperature: float,
|
||||
top_k: int,
|
||||
top_p: float,
|
||||
generators: list[torch.Generator],
|
||||
guidance_scale: float = 1.0,
|
||||
) -> torch.Tensor:
|
||||
batch = hidden.shape[0]
|
||||
branches = 2 if guidance_scale != 1.0 else 1
|
||||
requests = first.shape[0]
|
||||
if batch != requests * branches or len(generators) != requests:
|
||||
raise ValueError("Depth generation requires one token and generator per request and aligned CFG branches")
|
||||
if requests == 0:
|
||||
return first.new_empty((0, self.num_codebooks))
|
||||
# Buckets bound captured workspace shapes as live requests arrive and
|
||||
# finish. Compiled layers share code across those batch dimensions.
|
||||
request_bucket = 1 << (requests - 1).bit_length()
|
||||
batch_bucket = request_bucket * branches
|
||||
# Greedy decoding needs no sorting, probability filtering, or RNG
|
||||
# workspace. Capture it separately from the mutable sampled path.
|
||||
key = (batch_bucket, branches, temperature == 0)
|
||||
parameters = (temperature, top_k, top_p)
|
||||
entry = self._graphs.get(key)
|
||||
if entry is None:
|
||||
if self._compiled_layer is None:
|
||||
self._compiled_layer = torch.compile(
|
||||
BreezeDepthLayer.forward,
|
||||
fullgraph=True,
|
||||
dynamic=True,
|
||||
options={"epilogue_fusion": False, "max_autotune": True},
|
||||
)
|
||||
self._compiled_sampler = torch.compile(sample_graph_logits, fullgraph=True, dynamic=False)
|
||||
entry = BreezeDepthGraph(
|
||||
self,
|
||||
hidden.new_empty((batch_bucket, hidden.shape[-1])),
|
||||
first.new_empty((request_bucket,)),
|
||||
parameters,
|
||||
guidance_scale,
|
||||
)
|
||||
self._graphs[key] = entry
|
||||
if entry.parameter_values != parameters:
|
||||
entry.parameters.copy_(entry.parameters.new_tensor(parameters))
|
||||
entry.parameter_values = parameters
|
||||
if batch == batch_bucket:
|
||||
entry.hidden.copy_(hidden)
|
||||
else:
|
||||
# CFG graphs keep all conditioned rows before all unconditional
|
||||
# rows. Pad each branch separately so matching rows stay paired.
|
||||
for branch in range(branches):
|
||||
entry.hidden[branch * request_bucket : branch * request_bucket + requests].copy_(
|
||||
hidden[branch * requests : (branch + 1) * requests]
|
||||
)
|
||||
entry.first[:requests].copy_(first)
|
||||
if entry.guidance_scale is not None and entry.guidance_value != guidance_scale:
|
||||
entry.guidance_scale.fill_(guidance_scale)
|
||||
entry.guidance_value = guidance_scale
|
||||
if entry.noise_generators is not None:
|
||||
# Graphs retain placeholder generator states. Copy each live
|
||||
# request's seed and post-codebook-0 offset into its current row;
|
||||
# replacing a generator state would invalidate the captured RNG.
|
||||
for placeholder, generator in zip(entry.noise_generators, generators):
|
||||
placeholder.manual_seed(generator.initial_seed())
|
||||
placeholder.set_offset(generator.get_offset())
|
||||
elif temperature > 0:
|
||||
assert entry.noise is not None
|
||||
for row, generator in enumerate(generators):
|
||||
# Match the 15 independent exponential draws used by
|
||||
# torch.multinomial(..., num_samples=1), preserving each
|
||||
# request's RNG stream even when requests are batched.
|
||||
for codebook in range(self.num_codebooks - 1):
|
||||
entry.noise[row, codebook].exponential_(generator=generator)
|
||||
entry.graph.replay()
|
||||
if entry.noise_generators is not None:
|
||||
# Replay advances host offsets without synchronizing the device.
|
||||
# Padded rows have no request state to update.
|
||||
for placeholder, generator in zip(entry.noise_generators, generators):
|
||||
generator.set_offset(placeholder.get_offset())
|
||||
# The tiny RVQ result outlives this replay in request state and the
|
||||
# transfer queue. The graph owns and overwrites its output workspace.
|
||||
return entry.output[:requests].clone()
|
||||
|
||||
|
||||
class BreezeDepthGraph:
|
||||
def __init__(
|
||||
self,
|
||||
model: BreezeDepthDecoder,
|
||||
hidden: torch.Tensor,
|
||||
first: torch.Tensor,
|
||||
parameters: tuple[float, int, float],
|
||||
guidance_scale: float = 1.0,
|
||||
) -> None:
|
||||
self.parameter_values = parameters
|
||||
self.greedy = parameters[0] == 0
|
||||
self.parameters = hidden.new_tensor(parameters, dtype=torch.float32)
|
||||
self.guidance_value = guidance_scale
|
||||
self.guidance_scale = hidden.new_tensor(guidance_scale, dtype=torch.float32) if guidance_scale != 1.0 else None
|
||||
self.hidden = torch.zeros_like(hidden)
|
||||
self.first = torch.zeros_like(first)
|
||||
self.noise = (
|
||||
None
|
||||
if self.greedy
|
||||
else hidden.new_ones((first.shape[0], model.num_codebooks - 1, model.vocab_size), dtype=torch.float32)
|
||||
)
|
||||
self.noise_generators: list[torch.Generator] | None = None
|
||||
if not self.greedy and current_platform.is_cuda() and hasattr(torch.cuda.CUDAGraph, "register_generator_state"):
|
||||
self.noise_generators = [torch.Generator(device=hidden.device) for _ in range(first.shape[0])]
|
||||
# Materialize the distribution kernel before graph capture.
|
||||
self._fill_noise()
|
||||
# Captured kernels retain addresses, not the Python tensors allocated
|
||||
# before capture. Keep every KV allocation alive with its graph.
|
||||
self.caches = model._allocate_cache(hidden)
|
||||
generator = torch.Generator(device=hidden.device)
|
||||
for _ in range(3):
|
||||
model._generate_frame(
|
||||
self.hidden,
|
||||
self.first,
|
||||
self.caches,
|
||||
*parameters,
|
||||
generator,
|
||||
self.noise,
|
||||
self.guidance_scale,
|
||||
self.parameters,
|
||||
greedy=self.greedy,
|
||||
)
|
||||
current_omni_platform.synchronize()
|
||||
self.graph = torch.cuda.CUDAGraph()
|
||||
if self.noise_generators is not None:
|
||||
for generator in self.noise_generators:
|
||||
self.graph.register_generator_state(generator)
|
||||
with torch.cuda.graph(
|
||||
self.graph, pool=current_platform.get_global_graph_pool(), capture_error_mode="thread_local"
|
||||
):
|
||||
if self.noise_generators is not None:
|
||||
self._fill_noise()
|
||||
self.output = model._generate_frame(
|
||||
self.hidden,
|
||||
self.first,
|
||||
self.caches,
|
||||
*parameters,
|
||||
generator,
|
||||
self.noise,
|
||||
self.guidance_scale,
|
||||
self.parameters,
|
||||
greedy=self.greedy,
|
||||
)
|
||||
|
||||
def _fill_noise(self) -> None:
|
||||
assert self.noise is not None and self.noise_generators is not None
|
||||
for row, generator in enumerate(self.noise_generators):
|
||||
# Preserve the shape and ordering of independent multinomial
|
||||
# draws; one larger draw would consume a different RNG stream.
|
||||
for codebook in range(self.noise.shape[1]):
|
||||
self.noise[row, codebook].exponential_(generator=generator)
|
||||
@@ -0,0 +1,102 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Capture first-code sampling while preserving each request's RNG stream."""
|
||||
|
||||
import torch
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
from vllm_omni.model_executor.models.breeze_tts_2.depth_decoder import sample_logits
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
|
||||
class BreezeFirstCodeSampler:
|
||||
def __init__(self) -> None:
|
||||
self._graphs: dict[tuple[torch.device, int, int, tuple[float, int, float]], _SamplerGraph] = {}
|
||||
|
||||
def sample(
|
||||
self,
|
||||
logits: list[torch.Tensor],
|
||||
parameters: tuple[float, int, float],
|
||||
generators: list[torch.Generator],
|
||||
) -> list[torch.Tensor]:
|
||||
if len(logits) != len(generators):
|
||||
raise ValueError("First-code sampling requires one generator per logit row")
|
||||
if not logits:
|
||||
return []
|
||||
first = logits[0]
|
||||
for row, generator in zip(logits, generators, strict=True):
|
||||
if (
|
||||
row.ndim != 2
|
||||
or row.shape[0] != 1
|
||||
or row.shape[1] == 0
|
||||
or row.shape != first.shape
|
||||
or row.dtype != torch.float32
|
||||
or row.device != first.device
|
||||
or generator.device.type != row.device.type
|
||||
or (generator.device.index is not None and generator.device.index != row.device.index)
|
||||
):
|
||||
raise ValueError("First-code sampling requires aligned FP32 [1, vocab] rows and generators")
|
||||
capture = (
|
||||
parameters[0] > 0
|
||||
and first.is_cuda
|
||||
and current_platform.is_cuda()
|
||||
and hasattr(torch.cuda.CUDAGraph, "register_generator_state")
|
||||
and len({id(generator) for generator in generators}) == len(generators)
|
||||
)
|
||||
if capture:
|
||||
bucket = 1 << (len(logits) - 1).bit_length()
|
||||
key = (first.device, first.shape[1], bucket, parameters)
|
||||
entry = self._graphs.get(key)
|
||||
# Sampling parameters are static graph branches. Bound their cache
|
||||
# without evicting buffers retained by existing captured graphs.
|
||||
with torch.accelerator.device_index(first.device.index):
|
||||
if entry is None and len(self._graphs) < 32:
|
||||
entry = _SamplerGraph(first, bucket, parameters)
|
||||
self._graphs[key] = entry
|
||||
if entry is not None:
|
||||
return entry.replay(logits, generators)
|
||||
# Shared generators must retain sequential draw ordering, including
|
||||
# when a matching graph is already cached for independent requests.
|
||||
return [sample_logits(row, *parameters, generator) for row, generator in zip(logits, generators, strict=True)]
|
||||
|
||||
|
||||
class _SamplerGraph:
|
||||
def __init__(self, row: torch.Tensor, bucket: int, parameters: tuple[float, int, float]) -> None:
|
||||
self.logits = row.new_zeros((bucket, row.shape[1]))
|
||||
self.generators = [torch.Generator(device=row.device) for _ in range(bucket)]
|
||||
|
||||
def sample_rows() -> torch.Tensor:
|
||||
# Keep the original one-row softmax, filtering, multinomial
|
||||
# validation and RNG draw geometry; batched reductions can change
|
||||
# seeded output trajectories even when probabilities are close.
|
||||
return torch.cat(
|
||||
[
|
||||
sample_logits(self.logits[index : index + 1], *parameters, generator)
|
||||
for index, generator in enumerate(self.generators)
|
||||
]
|
||||
)
|
||||
|
||||
for _ in range(3):
|
||||
sample_rows()
|
||||
current_omni_platform.synchronize()
|
||||
self.graph = torch.cuda.CUDAGraph()
|
||||
self.capture_stream = torch.cuda.Stream(device=row.device)
|
||||
for generator in self.generators:
|
||||
self.graph.register_generator_state(generator)
|
||||
with torch.cuda.graph(self.graph, stream=self.capture_stream):
|
||||
self.output = sample_rows()
|
||||
|
||||
def replay(self, logits: list[torch.Tensor], generators: list[torch.Generator]) -> list[torch.Tensor]:
|
||||
live = len(logits)
|
||||
self.logits[:live].copy_(torch.cat(logits))
|
||||
# Captures retain the placeholder state objects. Update their values
|
||||
# rather than replacing those objects with request-owned RNG states.
|
||||
for placeholder, request in zip(self.generators[:live], generators, strict=True):
|
||||
placeholder.manual_seed(request.initial_seed())
|
||||
placeholder.set_offset(request.get_offset())
|
||||
self.graph.replay()
|
||||
for placeholder, request in zip(self.generators[:live], generators, strict=True):
|
||||
request.set_offset(placeholder.get_offset())
|
||||
# Padded rows have valid logits but no request state to advance. Clone
|
||||
# the live results so later replays cannot overwrite a returned token.
|
||||
return list(self.output[:live].clone().split(1))
|
||||
@@ -0,0 +1,407 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Breeze-TTS-2: T5Gemma2 prompt encoding, paged Qwen3, and RVQ decoding."""
|
||||
|
||||
from collections.abc import Iterable
|
||||
from typing import Any, TypedDict, cast
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import nn
|
||||
from transformers.models.t5gemma2.modeling_t5gemma2 import T5Gemma2TextEncoder
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
|
||||
from vllm.model_executor.models.qwen3 import Qwen3Model
|
||||
from vllm.sequence import IntermediateTensors
|
||||
from vllm.v1.sample.metadata import SamplingMetadata
|
||||
from vllm.v1.utils import record_function_or_nullcontext
|
||||
|
||||
from vllm_omni.config.model import OmniModelConfig
|
||||
from vllm_omni.model_executor.models.breeze_tts_2.configuration_breeze import BreezeConfig
|
||||
from vllm_omni.model_executor.models.breeze_tts_2.depth_decoder import BreezeDepthDecoder
|
||||
from vllm_omni.model_executor.models.breeze_tts_2.first_code_sampler import BreezeFirstCodeSampler
|
||||
from vllm_omni.model_executor.models.breeze_tts_2.prompt import CFG_UNCOND_SUFFIX
|
||||
from vllm_omni.model_executor.models.breeze_tts_2.reference_encoder import BreezeReferenceEncoder
|
||||
from vllm_omni.model_executor.models.breeze_tts_2.text_encoder_graph import (
|
||||
BreezeTextEncoderCompiled,
|
||||
BreezeTextEncoderGraph,
|
||||
)
|
||||
from vllm_omni.model_executor.models.output_templates import OmniOutput
|
||||
|
||||
|
||||
class BreezeSampling(TypedDict):
|
||||
temperature: float
|
||||
top_k: int
|
||||
top_p: float
|
||||
repetition_penalty: float
|
||||
|
||||
|
||||
class BreezeState(TypedDict):
|
||||
generator: torch.Generator
|
||||
history: torch.Tensor
|
||||
current: torch.Tensor
|
||||
|
||||
|
||||
class BreezeForConditionalGeneration(nn.Module):
|
||||
have_multimodal_outputs = True
|
||||
has_preprocess = True
|
||||
has_postprocess = False
|
||||
requires_full_prefix_cached_hidden_states = False
|
||||
omni_pooler_payload_include_hidden = False
|
||||
use_async_omni_output = True
|
||||
|
||||
def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None:
|
||||
super().__init__()
|
||||
self.vllm_config = vllm_config
|
||||
self.config = cast(BreezeConfig, vllm_config.model_config.hf_config)
|
||||
parallel = vllm_config.parallel_config
|
||||
if parallel.tensor_parallel_size != 1 or parallel.pipeline_parallel_size != 1:
|
||||
raise ValueError("Breeze-TTS-2 currently supports TP=1 and PP=1")
|
||||
if vllm_config.cache_config.enable_prefix_caching:
|
||||
raise ValueError("Breeze prompt placeholders require enable_prefix_caching=False")
|
||||
if vllm_config.scheduler_config.enable_chunked_prefill:
|
||||
raise ValueError("Breeze text encoding requires enable_chunked_prefill=False")
|
||||
if not cast(OmniModelConfig, vllm_config.model_config).async_chunk:
|
||||
raise ValueError("Breeze requires async_chunk=True for its stateful codec stage")
|
||||
if vllm_config.model_config.quantization is not None:
|
||||
raise ValueError("The initial Breeze integration does not support quantization")
|
||||
if self.config.backbone_model_type != "qwen3" or self.config.text_encoder_proj_type != "linear":
|
||||
raise ValueError("This integration supports the Breeze-TTS-2 Qwen3/linear checkpoint")
|
||||
if self.config.num_codebooks != 16 or self.config.audio_vocab_size != 2051:
|
||||
raise ValueError("Breeze-TTS-2 requires 16 codebooks with 2048 audio codes and 3 reserved IDs")
|
||||
self.num_codebooks = self.config.num_codebooks
|
||||
self.codebook_size = self.config.audio_vocab_size - 3
|
||||
self.hidden_size = self.config.backbone_config.hidden_size
|
||||
backbone_config = vllm_config.with_hf_config(self.config.backbone_config, architectures=["Qwen3ForCausalLM"])
|
||||
backbone_config.model_config.hf_text_config = backbone_config.model_config.hf_config
|
||||
self.model = Qwen3Model(vllm_config=backbone_config, prefix=f"{prefix}.model".strip("."))
|
||||
# Breeze replaces the backbone token embedding with summed RVQ embeddings.
|
||||
self.model.embed_tokens = nn.Identity()
|
||||
text_config = self.config.text_encoder_config
|
||||
text_config._attn_implementation = "sdpa"
|
||||
self.text_encoder = T5Gemma2TextEncoder(text_config)
|
||||
self.text_encoder_proj = nn.Linear(text_config.hidden_size, self.hidden_size, bias=False)
|
||||
self._long_text_encoder = BreezeTextEncoderCompiled(self.text_encoder, self.text_encoder_proj)
|
||||
self.reference_encoder = BreezeReferenceEncoder(vllm_config)
|
||||
self.depth_decoder = BreezeDepthDecoder(self.config.depth_decoder_config)
|
||||
self._first_code_sampler = BreezeFirstCodeSampler()
|
||||
self.lm_head = nn.Linear(self.hidden_size, self.config.vocab_size, bias=False, dtype=torch.float32)
|
||||
self.register_buffer(
|
||||
"offsets", torch.arange(self.num_codebooks) * self.config.audio_vocab_size, persistent=False
|
||||
)
|
||||
self.gpu_resident_buffer_keys = {
|
||||
("breeze_state", "current"),
|
||||
("breeze_state", "history"),
|
||||
("breeze_prepared", "embeds"),
|
||||
}
|
||||
self._next_tokens: torch.Tensor | None = None
|
||||
self._text_graphs: dict[tuple[int, int], BreezeTextEncoderGraph] = {}
|
||||
|
||||
@torch.inference_mode()
|
||||
def preprocess_batch(
|
||||
self, *, req_ids: list[str], model_intermediate_buffer: dict[str, dict[str, Any]], device: torch.device
|
||||
) -> None:
|
||||
pending = [
|
||||
model_intermediate_buffer[rid] for rid in req_ids if "breeze_state" not in model_intermediate_buffer[rid]
|
||||
]
|
||||
if not pending:
|
||||
return
|
||||
segment_ids: dict[tuple[int, ...], None] = {}
|
||||
references: dict[str, dict[str, Any]] = {}
|
||||
reference_keys: dict[str, str] = {}
|
||||
for info in pending:
|
||||
conditioning = info["breeze_prompt"]
|
||||
segment_ids[tuple(conditioning["target_ids"])] = None
|
||||
if "reference_waveform" in info:
|
||||
segment_ids[tuple(conditioning["reference_ids"])] = None
|
||||
request_id = info["global_request_id"][0]
|
||||
key = request_id.removesuffix(CFG_UNCOND_SUFFIX) if conditioning["role"] == "uncond" else request_id
|
||||
reference_keys[request_id] = key
|
||||
references.setdefault(key, info)
|
||||
if not self._text_graphs:
|
||||
# The serving warmup pays these captures before accepting speech
|
||||
# requests. Cover the default two-row deployment's distinct text
|
||||
# segments, including two independent reference recordings.
|
||||
for batch in range(1, min(4, 2 * self.vllm_config.scheduler_config.max_num_seqs) + 1):
|
||||
for size in (32, 64, 128):
|
||||
self._text_graphs[(batch, size)] = BreezeTextEncoderGraph(
|
||||
self.text_encoder, self.text_encoder_proj, size, batch_size=batch
|
||||
)
|
||||
self.reference_encoder.warmup(min(2, self.vllm_config.scheduler_config.max_num_seqs))
|
||||
self._long_text_encoder.warmup(min(4, 2 * self.vllm_config.scheduler_config.max_num_seqs))
|
||||
length = max(len(ids) for ids in segment_ids)
|
||||
bucket = max(32, 1 << (length - 1).bit_length())
|
||||
with record_function_or_nullcontext("breeze:text_encoder"):
|
||||
prompts = [torch.tensor(ids, device="cpu", dtype=torch.long) for ids in segment_ids]
|
||||
if bucket > 128:
|
||||
encoded = self._long_text_encoder.run_batch(prompts)
|
||||
# Large prefill activations must not raise the decoder graph
|
||||
# pool's permanent high-water mark. Return free prefill
|
||||
# workspace to the device before starting streamed decode.
|
||||
torch.accelerator.empty_cache()
|
||||
else:
|
||||
graph_key = (len(segment_ids), bucket)
|
||||
if graph_key not in self._text_graphs:
|
||||
self._text_graphs[graph_key] = BreezeTextEncoderGraph(
|
||||
self.text_encoder, self.text_encoder_proj, bucket, batch_size=len(segment_ids)
|
||||
)
|
||||
encoded = self._text_graphs[graph_key].run_batch(prompts)
|
||||
segments = dict(zip(segment_ids, encoded, strict=True))
|
||||
reference_embeds: dict[str, torch.Tensor] = {}
|
||||
if references:
|
||||
with record_function_or_nullcontext("breeze:reference_encoder"):
|
||||
codes = self.reference_encoder.encode_batch(
|
||||
[info["reference_waveform"] for info in references.values()],
|
||||
[info["breeze_prompt"]["reference_frames"] for info in references.values()],
|
||||
)
|
||||
for key, code in zip(references, codes, strict=True):
|
||||
# Audio EOS is a zero RVQ frame, distinct from generation EOS.
|
||||
eos = code.new_full((1, self.num_codebooks), self.config.codebook_eos_token_id)
|
||||
audio = self.depth_decoder.embed_tokens(torch.cat((code, eos)) + self.offsets).sum(1)
|
||||
reference_ids = tuple(references[key]["breeze_prompt"]["reference_ids"])
|
||||
reference_embeds[key] = torch.cat((segments[reference_ids], audio), dim=0)
|
||||
for info in pending:
|
||||
embeds = segments[tuple(info["breeze_prompt"]["target_ids"])]
|
||||
request_id = info["global_request_id"][0]
|
||||
if request_id in reference_keys:
|
||||
embeds = torch.cat((reference_embeds[reference_keys[request_id]], embeds), dim=0)
|
||||
info["breeze_prepared"] = {"embeds": embeds}
|
||||
|
||||
def embed_input_ids(self, input_ids: torch.Tensor, **_: object) -> torch.Tensor:
|
||||
# vLLM's memory profiling does not have a request payload.
|
||||
return self.lm_head.weight.new_zeros((input_ids.numel(), self.hidden_size), dtype=self.model.norm.weight.dtype)
|
||||
|
||||
def preprocess(
|
||||
self,
|
||||
input_ids: torch.Tensor,
|
||||
input_embeds: torch.Tensor | None,
|
||||
*,
|
||||
breeze_prompt: dict[str, Any],
|
||||
breeze_sampling: BreezeSampling,
|
||||
global_request_id: list[str],
|
||||
breeze_prepared: dict[str, torch.Tensor] | None = None,
|
||||
breeze_state: BreezeState | None = None,
|
||||
_omni_is_prefill: bool,
|
||||
_omni_seed: int | None = None,
|
||||
**_: object,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, dict[str, object]]:
|
||||
if _omni_is_prefill:
|
||||
if breeze_prepared is None:
|
||||
raise RuntimeError("Breeze prefill requires the runner's batch preprocessing hook")
|
||||
embeds = breeze_prepared.pop("embeds")
|
||||
if embeds.shape[0] != input_ids.numel():
|
||||
raise ValueError("Breeze prompt payload and scheduled token count differ")
|
||||
generator = torch.Generator(device=input_ids.device)
|
||||
if _omni_seed is None:
|
||||
generator.seed()
|
||||
else:
|
||||
generator.manual_seed(_omni_seed)
|
||||
state: BreezeState = {
|
||||
"generator": generator,
|
||||
"history": input_ids.new_empty((1, 0)),
|
||||
"current": input_ids.new_empty((1, self.num_codebooks)),
|
||||
}
|
||||
return input_ids, embeds, {"breeze_state": state}
|
||||
if breeze_state is None or input_ids.numel() != 1:
|
||||
raise ValueError("Breeze decode requires initialized per-request state and one token")
|
||||
embeds = self.depth_decoder.embed_tokens(breeze_state["current"] + self.offsets).sum(1)
|
||||
return input_ids, embeds, {}
|
||||
|
||||
def preprocess_decode_batch(
|
||||
self,
|
||||
*,
|
||||
input_ids: torch.Tensor,
|
||||
req_infos: list[dict[str, Any]],
|
||||
) -> tuple[torch.Tensor, torch.Tensor, list[dict[str, Any]]]:
|
||||
"""Embed one current RVQ frame per physical decode row, including CFG."""
|
||||
if input_ids.numel() != len(req_infos):
|
||||
raise ValueError("Breeze decode requires one token per request")
|
||||
frames: list[torch.Tensor] = []
|
||||
for info in req_infos:
|
||||
state = info.get("breeze_state")
|
||||
if info.get("_omni_is_prefill") or state is None:
|
||||
raise ValueError("Breeze decode requires initialized per-request state")
|
||||
current = state["current"]
|
||||
if current.shape != (1, self.num_codebooks):
|
||||
raise ValueError("Breeze decode requires one RVQ frame per request")
|
||||
frames.append(current)
|
||||
if not frames:
|
||||
embeds = self.depth_decoder.embed_tokens.weight.new_empty((0, self.hidden_size))
|
||||
else:
|
||||
current = torch.cat(frames, dim=0)
|
||||
embeds = self.depth_decoder.embed_tokens(current + self.offsets).sum(1)
|
||||
return input_ids, embeds, [{} for _ in req_infos]
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
intermediate_tensors: IntermediateTensors | None = None,
|
||||
inputs_embeds: torch.Tensor | None = None,
|
||||
**_: object,
|
||||
) -> torch.Tensor | IntermediateTensors:
|
||||
return self.model(None, positions, intermediate_tensors, inputs_embeds)
|
||||
|
||||
def compute_logits(
|
||||
self, hidden_states: torch.Tensor, sampling_metadata: SamplingMetadata | None = None
|
||||
) -> torch.Tensor:
|
||||
logits = hidden_states.new_full((hidden_states.shape[0], self.config.vocab_size), -torch.inf)
|
||||
if self._next_tokens is None:
|
||||
logits[:, 0] = 0
|
||||
else:
|
||||
if self._next_tokens.numel() != hidden_states.shape[0]:
|
||||
raise RuntimeError("Breeze sampled rows do not match the current request batch")
|
||||
logits.scatter_(1, self._next_tokens[:, None], 0)
|
||||
return logits
|
||||
|
||||
def make_omni_output(
|
||||
self,
|
||||
model_outputs: torch.Tensor,
|
||||
*,
|
||||
model_intermediate_buffer: list[dict[str, object]] | None = None,
|
||||
request_token_spans: list[tuple[int, int]] | None = None,
|
||||
**_: object,
|
||||
) -> OmniOutput:
|
||||
if not model_intermediate_buffer:
|
||||
self._next_tokens = None
|
||||
return OmniOutput(text_hidden_states=model_outputs, multimodal_outputs={})
|
||||
if request_token_spans is None or len(request_token_spans) != len(model_intermediate_buffer):
|
||||
raise RuntimeError("Breeze requires one hidden-state span per request")
|
||||
self._next_tokens = torch.zeros(len(model_intermediate_buffer), device=model_outputs.device, dtype=torch.long)
|
||||
output_codes = [
|
||||
torch.empty((0, self.num_codebooks), device=model_outputs.device, dtype=torch.long)
|
||||
for _ in model_intermediate_buffer
|
||||
]
|
||||
infos = model_intermediate_buffer
|
||||
request_rows = {cast(list[str], info["global_request_id"])[0]: index for index, info in enumerate(infos)}
|
||||
prepared_rows: list[tuple[list[int], torch.Tensor, torch.Tensor, tuple[float, int, float, float]]] = []
|
||||
for index, (info, (start, end)) in enumerate(zip(infos, request_token_spans, strict=True)):
|
||||
if not 0 <= start < end <= model_outputs.shape[0]:
|
||||
raise RuntimeError("Invalid Breeze request span")
|
||||
conditioning = cast(dict[str, Any], info["breeze_prompt"])
|
||||
if conditioning["role"] == "uncond":
|
||||
parent = cast(list[str], info["global_request_id"])[0].removesuffix(CFG_UNCOND_SUFFIX)
|
||||
if parent not in request_rows:
|
||||
raise RuntimeError("Breeze CFG companion was scheduled without its conditioned branch")
|
||||
continue
|
||||
hidden = model_outputs[end - 1 : end]
|
||||
state = cast(BreezeState, info["breeze_state"])
|
||||
sampling = cast(BreezeSampling, info["breeze_sampling"])
|
||||
logits = F.linear(hidden.float(), self.lm_head.weight)
|
||||
indices = [index]
|
||||
guidance_scale = float(conditioning["guidance_scale"])
|
||||
if guidance_scale != 1.0:
|
||||
request_id = cast(list[str], info["global_request_id"])[0]
|
||||
companion = request_rows.get(request_id + CFG_UNCOND_SUFFIX)
|
||||
if companion is None:
|
||||
raise RuntimeError("Breeze CFG request was scheduled without its unconditional branch")
|
||||
if infos[companion]["breeze_sampling"] != sampling:
|
||||
raise RuntimeError("Breeze CFG branches have different sampling parameters")
|
||||
_, companion_end = request_token_spans[companion]
|
||||
uncond = model_outputs[companion_end - 1 : companion_end]
|
||||
uncond_logits = F.linear(uncond.float(), self.lm_head.weight)
|
||||
logits = uncond_logits + guidance_scale * (logits - uncond_logits)
|
||||
hidden = torch.cat((hidden, uncond))
|
||||
indices.append(companion)
|
||||
logits[:, self.codebook_size : self.config.eos_token_id] = -torch.inf
|
||||
history = state["history"]
|
||||
if history.numel():
|
||||
selected = logits.gather(1, history)
|
||||
penalty = sampling["repetition_penalty"]
|
||||
logits.scatter_(1, history, torch.where(selected < 0, selected * penalty, selected / penalty))
|
||||
parameters = (sampling["temperature"], sampling["top_k"], sampling["top_p"], guidance_scale)
|
||||
prepared_rows.append((indices, hidden, logits, parameters))
|
||||
|
||||
generators = [cast(BreezeState, infos[row[0][0]]["breeze_state"])["generator"] for row in prepared_rows]
|
||||
sampling_groups: dict[tuple[float, int, float], list[int]] = {}
|
||||
for position, (_, _, _, (temperature, top_k, top_p, _)) in enumerate(prepared_rows):
|
||||
sampling_groups.setdefault((temperature, top_k, top_p), []).append(position)
|
||||
positions_by_group = list(sampling_groups.values())
|
||||
if len({id(generator) for generator in generators}) != len(generators):
|
||||
# Normally each request owns a generator. Preserve sequential draw
|
||||
# ordering even if callers supply shared state across parameter groups.
|
||||
positions_by_group = [[position] for position in range(len(prepared_rows))]
|
||||
first_codes: dict[int, torch.Tensor] = {}
|
||||
for positions in positions_by_group:
|
||||
temperature, top_k, top_p, _ = prepared_rows[positions[0]][3]
|
||||
first = self._first_code_sampler.sample(
|
||||
[prepared_rows[position][2] for position in positions],
|
||||
(temperature, top_k, top_p),
|
||||
[generators[position] for position in positions],
|
||||
)
|
||||
first_codes.update(zip(positions, first, strict=True))
|
||||
sampled_rows = [
|
||||
(indices, hidden, first_codes[position], parameters)
|
||||
for position, (indices, hidden, _, parameters) in enumerate(prepared_rows)
|
||||
]
|
||||
# Read back EOS once after all first-code samples. Restore request order
|
||||
# before grouping depth work so its RNG and CFG ordering stay unchanged.
|
||||
first_ids = torch.cat([row[2] for row in sampled_rows]).to("cpu").tolist() if sampled_rows else []
|
||||
groups: dict[tuple[float, int, float, float], list[tuple[list[int], torch.Tensor, torch.Tensor]]] = {}
|
||||
for (indices, hidden, first, parameters), first_id in zip(sampled_rows, first_ids, strict=True):
|
||||
if first_id == self.config.eos_token_id:
|
||||
self._next_tokens[indices] = self.config.eos_token_id
|
||||
continue
|
||||
state = cast(BreezeState, infos[indices[0]]["breeze_state"])
|
||||
state["history"] = torch.cat((state["history"], first[:, None]), dim=1)
|
||||
groups.setdefault(parameters, []).append((indices, hidden, first))
|
||||
for (temperature, top_k, top_p, guidance_scale), rows in groups.items():
|
||||
# Depth batches place every conditioned row before every
|
||||
# unconditional row. Both branches consume the same sampled codes.
|
||||
hidden = torch.stack([row[1] for row in rows]).transpose(0, 1).reshape(-1, self.hidden_size)
|
||||
with record_function_or_nullcontext("breeze:depth_decoder"):
|
||||
frames = self.depth_decoder.generate_frames(
|
||||
hidden,
|
||||
torch.cat([row[2] for row in rows]),
|
||||
temperature=temperature,
|
||||
top_k=top_k,
|
||||
top_p=top_p,
|
||||
generators=[cast(BreezeState, infos[row[0][0]]["breeze_state"])["generator"] for row in rows],
|
||||
guidance_scale=guidance_scale,
|
||||
)
|
||||
for offset, (indices, _, _) in enumerate(rows):
|
||||
frame = frames[offset : offset + 1]
|
||||
for index in indices:
|
||||
cast(BreezeState, infos[index]["breeze_state"])["current"] = frame
|
||||
output_codes[indices[0]] = frame
|
||||
return OmniOutput(text_hidden_states=model_outputs, multimodal_outputs={"codes": {"audio": output_codes}})
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
backbone: list[tuple[str, torch.Tensor]] = []
|
||||
depth: dict[str, torch.Tensor] = {}
|
||||
loaded: set[str] = set()
|
||||
params = dict(self.named_parameters())
|
||||
for name, value in weights:
|
||||
if name.startswith(("backbone_model.layers.", "backbone_model.norm.")):
|
||||
backbone.append((name.removeprefix("backbone_model."), value))
|
||||
elif name.startswith("depth_decoder."):
|
||||
depth[name] = value
|
||||
elif name.startswith(("text_encoder.", "text_encoder_proj.", "lm_head.")):
|
||||
default_weight_loader(params[name], value)
|
||||
loaded.add(name)
|
||||
elif not name.startswith(("codec_model.", "backbone_model.embed_tokens.", "embed_text_tokens.")):
|
||||
raise ValueError(f"Unexpected Breeze checkpoint parameter: {name}")
|
||||
loaded.update("model." + name for name in self.model.load_weights(backbone))
|
||||
for target, parameter in self.depth_decoder.named_parameters():
|
||||
if target == "codebooks_head":
|
||||
value = depth["depth_decoder.codebooks_head.weight"]
|
||||
elif target.endswith("qkv.weight"):
|
||||
layer = target.split(".")[1]
|
||||
value = torch.cat(
|
||||
[depth[f"depth_decoder.model.layers.{layer}.self_attn.{p}_proj.weight"] for p in ("q", "k", "v")]
|
||||
)
|
||||
elif target.endswith("gate_up.weight"):
|
||||
layer = target.split(".")[1]
|
||||
value = torch.cat(
|
||||
[depth[f"depth_decoder.model.layers.{layer}.mlp.{p}_proj.weight"] for p in ("gate", "up")]
|
||||
)
|
||||
else:
|
||||
source = target.replace(".o_proj.", ".self_attn.o_proj.").replace(".down_proj.", ".mlp.down_proj.")
|
||||
value = depth["depth_decoder.model." + source]
|
||||
default_weight_loader(parameter, value)
|
||||
loaded.add("depth_decoder." + target)
|
||||
loaded.update("reference_encoder." + name for name in self.reference_encoder.load_weights(self.vllm_config))
|
||||
missing = set(params) - loaded
|
||||
if missing:
|
||||
raise ValueError(f"Uninitialized Breeze parameters: {sorted(missing)}")
|
||||
return loaded
|
||||
@@ -1,425 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Breeze-TTS-2 stage-1 codec (codec codes -> waveform).
|
||||
|
||||
The talker emits a frame-major ``(T, 16)`` matrix. The stage input
|
||||
processor flattens it codebook-major; this module restores the ``(T, 16)``
|
||||
layout and delegates decoding to Breeze's bundled Qwen3-TTS tokenizer. A
|
||||
Mimi fallback remains available for checkpoints that omit ``audio_tokenizer``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable, Mapping
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
from vllm.config import VllmConfig
|
||||
|
||||
from vllm_omni.model_executor.models.breeze_tts_2.audio_tokenizer import (
|
||||
resolve_audio_tokenizer_path,
|
||||
)
|
||||
from vllm_omni.model_executor.models.output_templates import OmniOutput
|
||||
|
||||
|
||||
def _split_flat_ids(ids: torch.Tensor, counts: list[int] | None) -> list[torch.Tensor]:
|
||||
if counts is None or len(counts) <= 1:
|
||||
return [ids]
|
||||
boundaries = [0]
|
||||
for count in counts:
|
||||
boundaries.append(boundaries[-1] + int(count))
|
||||
return [ids[boundaries[i] : boundaries[i + 1]] for i in range(len(counts))]
|
||||
|
||||
|
||||
class BreezeTTS2MimiCodec(nn.Module):
|
||||
"""Synchronous Breeze codec stage used by ``GenerationModelRunner``."""
|
||||
|
||||
input_modalities = "audio"
|
||||
requires_raw_input_tokens = True
|
||||
# Stateful chunk decoding needs the scheduler-side request id, which is
|
||||
# also used by on_requests_finished to release decoder state.
|
||||
requires_request_ids = True
|
||||
have_multimodal_outputs = True
|
||||
has_preprocess = False
|
||||
has_postprocess = False
|
||||
enable_update_additional_information = True
|
||||
|
||||
def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None:
|
||||
super().__init__()
|
||||
del prefix
|
||||
self.vllm_config = vllm_config
|
||||
self.config = vllm_config.model_config.hf_config
|
||||
self.model_path = vllm_config.model_config.model
|
||||
self._async_chunk = bool(getattr(vllm_config.model_config, "async_chunk", False))
|
||||
# Resolve once: a local directory works directly, an HF repo id
|
||||
# resolves to its cached snapshot. ``None`` means the checkpoint has
|
||||
# no bundled tokenizer and the Mimi fallback applies.
|
||||
self._tokenizer_path = resolve_audio_tokenizer_path(self.model_path)
|
||||
if self._async_chunk and self._tokenizer_path is None:
|
||||
raise RuntimeError(
|
||||
"Breeze-TTS-2 async_chunk requires the bundled Qwen3-TTS audio_tokenizer; "
|
||||
"the stateless Mimi fallback cannot preserve chunk decoder state"
|
||||
)
|
||||
|
||||
self._audio_tokenizer = None
|
||||
codec_config = getattr(self.config, "codec_config", None)
|
||||
if isinstance(codec_config, Mapping):
|
||||
codec_kwargs = dict(codec_config)
|
||||
elif codec_config is not None:
|
||||
codec_kwargs = codec_config.to_dict()
|
||||
else:
|
||||
codec_kwargs = {}
|
||||
codec_kwargs.pop("model_type", None)
|
||||
codec_kwargs.pop("architectures", None)
|
||||
|
||||
# Breeze checkpoints normally carry a Qwen3-TTS decoder in this
|
||||
# subdirectory. Avoid constructing a second, unused Mimi network in
|
||||
# that case; this saves both startup time and worker memory.
|
||||
self._codec = None
|
||||
if self._tokenizer_path is None:
|
||||
# Import lazily: stage 0 does not need the Mimi implementation.
|
||||
from transformers import MimiConfig, MimiModel
|
||||
|
||||
self._codec = MimiModel(MimiConfig(**codec_kwargs)).eval()
|
||||
for parameter in self._codec.parameters():
|
||||
parameter.requires_grad_(False)
|
||||
|
||||
self._num_codebooks = int(getattr(self.config, "num_codebooks", 16))
|
||||
self._codebook_size = int(codec_kwargs.get("codebook_size", 2048))
|
||||
self._sample_rate = int(codec_kwargs.get("sampling_rate", getattr(self.config, "sampling_rate", 24000)))
|
||||
self._decoder_state_cache: dict[str, dict[str, Any]] = {}
|
||||
|
||||
def embed_input_ids(self, input_ids: torch.Tensor, **_: Any) -> torch.Tensor:
|
||||
"""Return stable dummy embeddings; this stage never samples."""
|
||||
if input_ids.numel() == 0:
|
||||
return torch.empty((0, 1), device=input_ids.device, dtype=torch.float32)
|
||||
return torch.zeros((input_ids.shape[0], 1), device=input_ids.device, dtype=torch.float32)
|
||||
|
||||
def compute_logits(
|
||||
self,
|
||||
hidden_states: torch.Tensor | OmniOutput,
|
||||
sampling_metadata: Any = None,
|
||||
) -> None:
|
||||
del hidden_states, sampling_metadata
|
||||
return None
|
||||
|
||||
@torch.inference_mode()
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.Tensor | None = None,
|
||||
runtime_additional_information: list[dict[str, Any]] | None = None,
|
||||
**kwargs: Any,
|
||||
) -> OmniOutput:
|
||||
empty = torch.empty(0, dtype=torch.float32)
|
||||
sr = torch.tensor(self._sample_rate, dtype=torch.int32)
|
||||
if input_ids is None or input_ids.numel() == 0:
|
||||
return OmniOutput(
|
||||
text_hidden_states=None,
|
||||
multimodal_outputs={"model_outputs": [empty], "sr": [sr]},
|
||||
)
|
||||
# The generation runner's profiling/dummy invocation has no request ids
|
||||
# or runtime payload. Real requests always provide both.
|
||||
if runtime_additional_information is None and kwargs.get("request_ids") is None:
|
||||
return OmniOutput(
|
||||
text_hidden_states=None,
|
||||
multimodal_outputs={"model_outputs": [empty], "sr": [sr]},
|
||||
)
|
||||
|
||||
ids = input_ids.reshape(-1).to(dtype=torch.long)
|
||||
counts = kwargs.get("seq_token_counts")
|
||||
if counts is not None:
|
||||
counts = [int(item) for item in counts]
|
||||
requests = _split_flat_ids(ids, counts)
|
||||
waveforms: list[torch.Tensor] = []
|
||||
sample_rates: list[torch.Tensor] = []
|
||||
if self._async_chunk:
|
||||
return self._forward_stateful_chunks(
|
||||
ids=ids,
|
||||
requests=requests,
|
||||
runtime_additional_information=runtime_additional_information,
|
||||
empty=empty,
|
||||
sr=sr,
|
||||
**kwargs,
|
||||
)
|
||||
for index, request_ids in enumerate(requests):
|
||||
runtime_info = (
|
||||
runtime_additional_information[index]
|
||||
if runtime_additional_information is not None and index < len(runtime_additional_information)
|
||||
else None
|
||||
)
|
||||
flat = self._payload_codes(request_ids, runtime_info)
|
||||
if flat.numel() == 0:
|
||||
waveforms.append(empty.to(device=ids.device))
|
||||
sample_rates.append(sr)
|
||||
continue
|
||||
if flat.numel() % self._num_codebooks != 0:
|
||||
raise ValueError(
|
||||
f"Breeze codec input length {int(flat.numel())} is not divisible by "
|
||||
f"num_codebooks {self._num_codebooks}"
|
||||
)
|
||||
if int(flat.min()) < 0 or int(flat.max()) >= self._codebook_size:
|
||||
raise ValueError(
|
||||
f"Breeze codec id outside [0, {self._codebook_size}): min={int(flat.min())}, max={int(flat.max())}"
|
||||
)
|
||||
frames = flat.numel() // self._num_codebooks
|
||||
codes = flat.reshape(self._num_codebooks, frames).unsqueeze(0)
|
||||
waveform = self._decode_codes(codes)
|
||||
if waveform.ndim == 3:
|
||||
waveform = waveform[0, 0]
|
||||
elif waveform.ndim == 2:
|
||||
waveform = waveform[0]
|
||||
if waveform.ndim != 1:
|
||||
raise ValueError(f"Breeze Mimi waveform must be 1D, got {tuple(waveform.shape)}")
|
||||
# Serving/output serialization consumes CPU tensors. Move only
|
||||
# the final waveform off the worker device; codec inference itself
|
||||
# remains on the accelerator.
|
||||
waveforms.append(waveform.detach().to(device="cpu", dtype=torch.float32).contiguous())
|
||||
sample_rates.append(sr)
|
||||
|
||||
return OmniOutput(
|
||||
text_hidden_states=None,
|
||||
multimodal_outputs={"model_outputs": waveforms, "sr": sample_rates},
|
||||
)
|
||||
|
||||
def _forward_stateful_chunks(
|
||||
self,
|
||||
*,
|
||||
ids: torch.Tensor,
|
||||
requests: list[torch.Tensor],
|
||||
runtime_additional_information: list[dict[str, Any]] | None,
|
||||
empty: torch.Tensor,
|
||||
sr: torch.Tensor,
|
||||
**kwargs: Any,
|
||||
) -> OmniOutput:
|
||||
"""Decode incremental codebook-major chunks with per-request state."""
|
||||
decoder = self._audio_tokenizer.model.decoder
|
||||
scheduler_request_ids = kwargs.get("request_ids")
|
||||
if scheduler_request_ids is None:
|
||||
raise ValueError("Breeze async_chunk codec inputs require scheduler request_ids")
|
||||
request_ids = [str(request_id) for request_id in scheduler_request_ids]
|
||||
if len(request_ids) != len(requests):
|
||||
raise ValueError(
|
||||
f"Breeze codec request id count {len(request_ids)} does not match input request count {len(requests)}"
|
||||
)
|
||||
valid: list[tuple[str, torch.Tensor, bool]] = []
|
||||
valid_indices: list[int] = []
|
||||
for index, request_ids_tensor in enumerate(requests):
|
||||
runtime_info = (
|
||||
runtime_additional_information[index]
|
||||
if runtime_additional_information is not None and index < len(runtime_additional_information)
|
||||
else {}
|
||||
)
|
||||
state_id = request_ids[index]
|
||||
# The connector receiver strips ``meta.finished`` while merging
|
||||
# runtime metadata, so the stream-terminated signal arrives on
|
||||
# the model-visible ``stream_finished`` field (the same contract
|
||||
# CosyVoice3 / Audex use). Fall back to ``finished`` for direct
|
||||
# in-process callers that still set only the transport flag.
|
||||
finished = self._meta_bool(runtime_info, "stream_finished") or self._meta_bool(runtime_info, "finished")
|
||||
flat = self._payload_codes(request_ids_tensor, runtime_info)
|
||||
if flat.numel() == 0:
|
||||
# Terminal marker: the stage-0 processor sends an empty
|
||||
# payload with ``finished=True`` once generation ends.
|
||||
self._decoder_state_cache.pop(state_id, None)
|
||||
continue
|
||||
if flat.numel() % self._num_codebooks != 0:
|
||||
# A partial frame means the transport payload is corrupt.
|
||||
# Silently resetting decoder state would corrupt the rest of
|
||||
# the stream; fail loudly instead. The scheduler aborts the
|
||||
# request and ``on_requests_finished`` releases the state.
|
||||
raise ValueError(
|
||||
f"Breeze codec chunk length {int(flat.numel())} is not divisible by "
|
||||
f"num_codebooks {self._num_codebooks}"
|
||||
)
|
||||
if int(flat.min()) < 0 or int(flat.max()) >= self._codebook_size:
|
||||
raise ValueError(
|
||||
f"Breeze codec id outside [0, {self._codebook_size}): min={int(flat.min())}, max={int(flat.max())}"
|
||||
)
|
||||
frames = int(flat.numel()) // self._num_codebooks
|
||||
valid.append((state_id, flat.reshape(self._num_codebooks, frames), finished))
|
||||
valid_indices.append(index)
|
||||
|
||||
waveforms = [empty.to(device=ids.device)] * len(requests)
|
||||
sample_rates = [sr] * len(requests)
|
||||
if not valid:
|
||||
return OmniOutput(
|
||||
text_hidden_states=None,
|
||||
multimodal_outputs={"model_outputs": waveforms, "sr": sample_rates},
|
||||
)
|
||||
states: list[dict[str, Any]] = []
|
||||
max_frames = max(codes.shape[-1] for _, codes, _ in valid)
|
||||
batched_codes = valid[0][1].new_zeros((len(valid), self._num_codebooks, max_frames))
|
||||
for row, (state_id, row_codes, _) in enumerate(valid):
|
||||
batched_codes[row, :, : row_codes.shape[-1]].copy_(row_codes)
|
||||
state = self._decoder_state_cache.get(state_id)
|
||||
if state is None:
|
||||
state = {}
|
||||
self._decoder_state_cache[state_id] = state
|
||||
state.setdefault("prefix_frames", 0)
|
||||
states.append(state)
|
||||
|
||||
decoded = decoder.batched_chunked_decode(
|
||||
batched_codes,
|
||||
[int(codes.shape[-1]) for _, codes, _ in valid],
|
||||
caches=states,
|
||||
chunk_size=300,
|
||||
left_context_size=25,
|
||||
)
|
||||
if len(decoded) != len(valid):
|
||||
raise RuntimeError(f"Breeze codec returned {len(decoded)} chunks for {len(valid)} requests")
|
||||
for request_index, waveform in zip(valid_indices, decoded, strict=True):
|
||||
if waveform.ndim == 2 and waveform.shape[0] == 1:
|
||||
waveform = waveform[0]
|
||||
elif waveform.ndim != 1:
|
||||
waveform = waveform.reshape(-1)
|
||||
waveforms[request_index] = waveform.detach().to(device="cpu", dtype=torch.float32).contiguous()
|
||||
|
||||
for state_id, _, finished in valid:
|
||||
if finished:
|
||||
self._decoder_state_cache.pop(state_id, None)
|
||||
|
||||
return OmniOutput(
|
||||
text_hidden_states=None,
|
||||
multimodal_outputs={"model_outputs": waveforms, "sr": sample_rates},
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _meta_bool(info: Mapping[str, Any] | None, key: str) -> bool:
|
||||
if not isinstance(info, Mapping):
|
||||
return False
|
||||
meta = info.get("meta", {})
|
||||
if not isinstance(meta, Mapping):
|
||||
return False
|
||||
value = meta.get(key, False)
|
||||
if isinstance(value, torch.Tensor):
|
||||
return bool(value.reshape(-1)[0].item()) if value.numel() else False
|
||||
return bool(value)
|
||||
|
||||
def on_requests_finished(self, finished_req_ids: Iterable[str]) -> None:
|
||||
for request_id in finished_req_ids:
|
||||
self._decoder_state_cache.pop(str(request_id), None)
|
||||
|
||||
def _decode_codes(self, codes: torch.Tensor) -> torch.Tensor:
|
||||
"""Decode one ``(1, Q, T)`` sequence using Breeze's bundled codec."""
|
||||
if self._audio_tokenizer is not None:
|
||||
wavs, sample_rate = self._audio_tokenizer.decode({"audio_codes": [codes[0].transpose(0, 1).contiguous()]})
|
||||
self._sample_rate = int(sample_rate)
|
||||
if not wavs:
|
||||
raise RuntimeError("Breeze Qwen3-TTS tokenizer returned no waveform")
|
||||
return torch.as_tensor(wavs[0], device=codes.device, dtype=torch.float32).reshape(-1)
|
||||
|
||||
if self._codec is None:
|
||||
raise RuntimeError("Breeze codec is not initialized; load_weights() was not completed")
|
||||
decoded = self._codec.decode(codes)
|
||||
waveform = getattr(decoded, "audio_values", decoded)
|
||||
if isinstance(waveform, Mapping):
|
||||
waveform = waveform.get("audio_values")
|
||||
if waveform is None:
|
||||
raise RuntimeError("MimiModel.decode returned no audio_values")
|
||||
return torch.as_tensor(waveform, device=codes.device, dtype=torch.float32)
|
||||
|
||||
@staticmethod
|
||||
def _payload_codes(input_ids: torch.Tensor, runtime_info: Mapping[str, Any] | None) -> torch.Tensor:
|
||||
if isinstance(runtime_info, Mapping):
|
||||
codes = runtime_info.get("codes")
|
||||
if isinstance(codes, Mapping):
|
||||
audio = codes.get("audio")
|
||||
if audio is not None:
|
||||
return torch.as_tensor(audio, device=input_ids.device, dtype=torch.long).reshape(-1)
|
||||
# Full-payload transport may flatten nested OmniPayload keys at
|
||||
# the wire boundary and restore them only after this hook runs.
|
||||
audio = runtime_info.get("codes.audio")
|
||||
if audio is not None:
|
||||
return torch.as_tensor(audio, device=input_ids.device, dtype=torch.long).reshape(-1)
|
||||
return input_ids
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
"""Load Breeze's bundled Qwen3-TTS codec, or fallback Mimi weights."""
|
||||
if self._tokenizer_path is not None:
|
||||
# The root checkpoint contains both the talker weights and a Mimi
|
||||
# ``codec_model.*`` fallback. When the bundled Qwen3-TTS tokenizer
|
||||
# is present, it owns decoding; consume the root iterator without
|
||||
# copying the unused fallback into worker memory.
|
||||
if self._audio_tokenizer is None:
|
||||
from vllm_omni.model_executor.models.qwen3_tts.qwen3_tts_tokenizer import (
|
||||
Qwen3TTSTokenizer,
|
||||
)
|
||||
|
||||
device = self.vllm_config.device_config.device
|
||||
self._audio_tokenizer = Qwen3TTSTokenizer.from_pretrained(
|
||||
str(self._tokenizer_path),
|
||||
device_map=str(device),
|
||||
)
|
||||
self._sample_rate = int(self._audio_tokenizer.model.get_output_sample_rate())
|
||||
if self._async_chunk:
|
||||
connector_config = getattr(self.vllm_config.model_config, "stage_connector_config", None)
|
||||
extra = (
|
||||
connector_config.get("extra", connector_config)
|
||||
if isinstance(connector_config, Mapping)
|
||||
else getattr(connector_config, "extra", None)
|
||||
)
|
||||
value = extra.get("breeze_codec_chunk_frames") if isinstance(extra, Mapping) else None
|
||||
try:
|
||||
chunk_frames = int(value) if value is not None else 8
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValueError(f"Invalid Breeze codec_chunk_frames={value!r}") from exc
|
||||
if chunk_frames <= 0:
|
||||
raise ValueError(f"Breeze codec_chunk_frames must be positive, got {chunk_frames}")
|
||||
# Qwen treats chunks shorter than its configured window as
|
||||
# terminal tails and does not advance their rolling cache.
|
||||
# Match the producer's chunk size instead of its default 25.
|
||||
decoder = self._audio_tokenizer.model.decoder
|
||||
decoder._initial_codec_chunk_frames = chunk_frames
|
||||
decoder._incremental_chunk_frames = chunk_frames
|
||||
decoder._incremental_chunk_ramp = []
|
||||
for _ in weights:
|
||||
pass
|
||||
tokenizer_module = getattr(self._audio_tokenizer, "model", None)
|
||||
named_parameters = getattr(tokenizer_module, "named_parameters", None)
|
||||
if callable(named_parameters):
|
||||
return {f"_audio_tokenizer.model.{name}" for name, _ in named_parameters()}
|
||||
return set()
|
||||
|
||||
params = dict(self._codec.named_parameters()) if self._codec is not None else {}
|
||||
loaded: set[str] = set()
|
||||
for name, tensor in weights:
|
||||
if name.startswith("codec_model."):
|
||||
target_name = name[len("codec_model.") :]
|
||||
else:
|
||||
continue
|
||||
parameter = params.get(target_name)
|
||||
if parameter is None:
|
||||
raise ValueError(f"Unknown Breeze Mimi weight: {target_name}")
|
||||
loader = getattr(parameter, "weight_loader", None)
|
||||
if loader is None:
|
||||
parameter.data.copy_(tensor.to(device=parameter.device, dtype=parameter.dtype))
|
||||
else:
|
||||
loader(parameter, tensor)
|
||||
loaded.add(target_name)
|
||||
|
||||
if loaded:
|
||||
return {f"_codec.{name}" for name in loaded}
|
||||
|
||||
# Breeze inference uses the bundled Qwen3-TTS tokenizer for both
|
||||
# reference encoding and generated-code decoding. Load it once per
|
||||
# Stage-1 worker; unlike the request-side wrapper this instance is
|
||||
# placed on the worker device and reused for the entire batch.
|
||||
# A few Breeze distributions omit codec tensors and point to the
|
||||
# standalone kyutai/mimi repository instead. Load it once, never per
|
||||
# request, and fail loudly if it cannot be resolved.
|
||||
codec_name = getattr(self.config, "codec_model_name_or_path", None) or "kyutai/mimi"
|
||||
from transformers import AutoModel
|
||||
|
||||
self._codec = AutoModel.from_pretrained(codec_name).eval()
|
||||
for parameter in self._codec.parameters():
|
||||
parameter.requires_grad_(False)
|
||||
self._sample_rate = int(getattr(self._codec.config, "sampling_rate", self._sample_rate))
|
||||
self._codebook_size = int(
|
||||
getattr(getattr(self._codec.config, "quantizer", None), "cardinality", self._codebook_size)
|
||||
)
|
||||
return {f"_codec.{name}" for name, _ in self._codec.named_parameters()}
|
||||
|
||||
|
||||
__all__ = ["BreezeTTS2MimiCodec"]
|
||||
@@ -1,523 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from inspect import signature
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
from transformers.activations import ACT2FN
|
||||
from transformers.cache_utils import Cache, DynamicCache
|
||||
from transformers.integrations import use_kernel_forward_from_hub
|
||||
from transformers.masking_utils import create_causal_mask
|
||||
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
||||
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
|
||||
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS
|
||||
from transformers.processing_utils import Unpack
|
||||
from transformers.utils import TransformersKwargs, logging
|
||||
from transformers.utils.deprecation import deprecate_kwarg
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
|
||||
|
||||
def _create_depth_causal_mask(
|
||||
*,
|
||||
config: Any,
|
||||
inputs_embeds: torch.Tensor,
|
||||
attention_mask: torch.Tensor | None,
|
||||
past_key_values: Cache | None,
|
||||
position_ids: torch.LongTensor | None,
|
||||
cache_position: torch.LongTensor,
|
||||
) -> torch.Tensor | None:
|
||||
"""Bridge Transformers 4.57 and 5.x ``create_causal_mask`` contracts."""
|
||||
parameters = signature(create_causal_mask).parameters
|
||||
kwargs: dict[str, Any] = {
|
||||
"config": config,
|
||||
"attention_mask": attention_mask,
|
||||
"past_key_values": past_key_values,
|
||||
"position_ids": position_ids,
|
||||
}
|
||||
if "inputs_embeds" in parameters:
|
||||
kwargs["inputs_embeds"] = inputs_embeds
|
||||
else:
|
||||
kwargs["input_embeds"] = inputs_embeds
|
||||
kwargs["cache_position"] = cache_position
|
||||
return create_causal_mask(**kwargs)
|
||||
|
||||
|
||||
class BreezeDepthDecoderModel(nn.Module):
|
||||
def __init__(self, config):
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.padding_idx = config.pad_token_id
|
||||
self.vocab_size = config.vocab_size
|
||||
if hasattr(config, "audio_embed_size") and config.audio_embed_size:
|
||||
self.audio_embed_size = config.audio_embed_size
|
||||
else:
|
||||
self.audio_embed_size = config.backbone_hidden_size
|
||||
self.embed_tokens = nn.Embedding((config.num_codebooks * config.vocab_size), self.audio_embed_size)
|
||||
self.layers = nn.ModuleList(
|
||||
[BreezeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
||||
)
|
||||
self.norm = BreezeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
self.rotary_emb = BreezeRotaryEmbedding(config=config)
|
||||
self.gradient_checkpointing = False
|
||||
self.inputs_embeds_projector = nn.Linear(self.audio_embed_size, config.hidden_size, bias=False)
|
||||
|
||||
if config.backbone_hidden_size != self.audio_embed_size:
|
||||
self.backbone_hidden_state_projector = nn.Linear(
|
||||
config.backbone_hidden_size, self.audio_embed_size, bias=False
|
||||
)
|
||||
else:
|
||||
self.backbone_hidden_state_projector = None
|
||||
|
||||
# Weights are loaded from the Breeze checkpoint by the parent talker.
|
||||
# Avoid PreTrainedModel.post_init here because this module is a plain
|
||||
# nn.Module used for eager per-frame inference.
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.LongTensor = None,
|
||||
backbone_last_hidden_state: torch.FloatTensor | None = None,
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
position_ids: torch.LongTensor | None = None,
|
||||
past_key_values: Cache | None = None,
|
||||
inputs_embeds: torch.FloatTensor | None = None,
|
||||
use_cache: bool | None = None,
|
||||
cache_position: torch.LongTensor | None = None,
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> tuple | BaseModelOutputWithPast:
|
||||
r"""
|
||||
backbone_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, backbone_hidden_size)`, *optional*):
|
||||
The last hidden state of the backbone model. This is required when
|
||||
the first codebook token (generated by the backbone model) is
|
||||
provided in the `input_ids` argument.
|
||||
"""
|
||||
if position_ids is not None and not torch.compiler.is_compiling():
|
||||
logger.warning_once(
|
||||
"Custom `position_ids` were provided but will be ignored. "
|
||||
"Breeze depth decoder derives them from `cache_position`; "
|
||||
"they must be identical across the batch."
|
||||
)
|
||||
position_ids = None
|
||||
if (input_ids is None) ^ (inputs_embeds is not None):
|
||||
raise ValueError("You must specify exactly one of input_ids or inputs_embeds.")
|
||||
|
||||
if use_cache and past_key_values is None:
|
||||
past_key_values = DynamicCache(config=self.config)
|
||||
|
||||
if cache_position is None:
|
||||
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
||||
inputs_seq_length = inputs_embeds.shape[1] if inputs_embeds is not None else input_ids.shape[1]
|
||||
device = inputs_embeds.device if inputs_embeds is not None else input_ids.device
|
||||
cache_position = torch.arange(past_seen_tokens, past_seen_tokens + inputs_seq_length, device=device)
|
||||
|
||||
if inputs_embeds is None:
|
||||
codebook_idxs = torch.clamp(cache_position - 1, min=0)
|
||||
offset = codebook_idxs * self.vocab_size
|
||||
inputs_embeds = self.embed_tokens(input_ids + offset)
|
||||
|
||||
input_ids_are_first_codebook = cache_position[0] == 0
|
||||
if backbone_last_hidden_state is not None:
|
||||
if self.backbone_hidden_state_projector is not None:
|
||||
inputs_embeds[:, 0] = self.backbone_hidden_state_projector(backbone_last_hidden_state)
|
||||
else:
|
||||
inputs_embeds[:, 0] = backbone_last_hidden_state
|
||||
else:
|
||||
if not torch.compiler.is_compiling() and input_ids_are_first_codebook:
|
||||
logger.warning(
|
||||
"When the first codebook token is provided, "
|
||||
"`backbone_last_hidden_state` is required for correct inference."
|
||||
)
|
||||
|
||||
inputs_embeds = self.inputs_embeds_projector(inputs_embeds)
|
||||
|
||||
causal_mask = _create_depth_causal_mask(
|
||||
config=self.config,
|
||||
inputs_embeds=inputs_embeds,
|
||||
attention_mask=attention_mask,
|
||||
past_key_values=past_key_values,
|
||||
position_ids=position_ids,
|
||||
cache_position=cache_position,
|
||||
)
|
||||
|
||||
hidden_states = inputs_embeds
|
||||
|
||||
# create position embeddings to be shared across the decoder layers
|
||||
position_ids = cache_position.unsqueeze(0)
|
||||
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
||||
|
||||
for decoder_layer in self.layers[: self.config.num_hidden_layers]:
|
||||
hidden_states = decoder_layer(
|
||||
hidden_states,
|
||||
attention_mask=causal_mask,
|
||||
position_ids=position_ids,
|
||||
past_key_values=past_key_values,
|
||||
use_cache=use_cache,
|
||||
cache_position=cache_position,
|
||||
position_embeddings=position_embeddings,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
hidden_states = self.norm(hidden_states)
|
||||
return BaseModelOutputWithPast(
|
||||
last_hidden_state=hidden_states,
|
||||
past_key_values=past_key_values if use_cache else None,
|
||||
)
|
||||
|
||||
|
||||
@use_kernel_forward_from_hub("RMSNorm")
|
||||
class BreezeRMSNorm(nn.Module):
|
||||
def __init__(self, hidden_size, eps=1e-6):
|
||||
"""
|
||||
BreezeRMSNorm is equivalent to T5LayerNorm
|
||||
"""
|
||||
super().__init__()
|
||||
self.weight = nn.Parameter(torch.ones(hidden_size))
|
||||
self.variance_epsilon = eps
|
||||
|
||||
def forward(self, hidden_states):
|
||||
input_dtype = hidden_states.dtype
|
||||
hidden_states = hidden_states.to(torch.float32)
|
||||
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
||||
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
||||
return self.weight * hidden_states.to(input_dtype)
|
||||
|
||||
def extra_repr(self):
|
||||
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
||||
|
||||
|
||||
class BreezeRotaryEmbedding(nn.Module):
|
||||
inv_freq: torch.Tensor # fix linting for `register_buffer`
|
||||
|
||||
def __init__(self, config, device=None):
|
||||
super().__init__()
|
||||
# BC: "rope_type" was originally "type"
|
||||
if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
|
||||
self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
|
||||
else:
|
||||
self.rope_type = "default"
|
||||
self.max_seq_len_cached = config.max_position_embeddings
|
||||
self.original_max_seq_len = config.max_position_embeddings
|
||||
|
||||
self.config = config
|
||||
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
||||
|
||||
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
|
||||
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
||||
self.original_inv_freq = self.inv_freq
|
||||
|
||||
@torch.no_grad()
|
||||
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
|
||||
def forward(self, x, position_ids):
|
||||
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
|
||||
position_ids_expanded = position_ids[:, None, :].float()
|
||||
|
||||
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
|
||||
with torch.autocast(device_type=device_type, enabled=False): # Force float32
|
||||
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
||||
emb = torch.cat((freqs, freqs), dim=-1)
|
||||
cos = emb.cos() * self.attention_scaling
|
||||
sin = emb.sin() * self.attention_scaling
|
||||
|
||||
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
||||
|
||||
|
||||
class BreezeMLP(nn.Module):
|
||||
def __init__(self, config):
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.hidden_size = config.hidden_size
|
||||
self.intermediate_size = config.intermediate_size
|
||||
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
|
||||
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
|
||||
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
|
||||
self.act_fn = ACT2FN[config.hidden_act]
|
||||
|
||||
def forward(self, x):
|
||||
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
||||
return down_proj
|
||||
|
||||
|
||||
def rotate_half(x):
|
||||
"""Rotates half the hidden dims of the input."""
|
||||
x1 = x[..., : x.shape[-1] // 2]
|
||||
x2 = x[..., x.shape[-1] // 2 :]
|
||||
return torch.cat((-x2, x1), dim=-1)
|
||||
|
||||
|
||||
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
||||
"""Applies Rotary Position Embedding to the query and key tensors.
|
||||
|
||||
Args:
|
||||
q (`torch.Tensor`): The query tensor.
|
||||
k (`torch.Tensor`): The key tensor.
|
||||
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
||||
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
||||
position_ids (`torch.Tensor`, *optional*):
|
||||
Deprecated and unused.
|
||||
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
||||
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
||||
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
||||
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
||||
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
||||
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
||||
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
||||
Returns:
|
||||
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
||||
"""
|
||||
cos = cos.unsqueeze(unsqueeze_dim)
|
||||
sin = sin.unsqueeze(unsqueeze_dim)
|
||||
q_embed = (q * cos) + (rotate_half(q) * sin)
|
||||
k_embed = (k * cos) + (rotate_half(k) * sin)
|
||||
return q_embed, k_embed
|
||||
|
||||
|
||||
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
||||
"""
|
||||
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
||||
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
||||
"""
|
||||
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
||||
if n_rep == 1:
|
||||
return hidden_states
|
||||
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
||||
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
||||
|
||||
|
||||
def eager_attention_forward(
|
||||
module: nn.Module,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
attention_mask: torch.Tensor | None,
|
||||
scaling: float,
|
||||
dropout: float = 0.0,
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
):
|
||||
key_states = repeat_kv(key, module.num_key_value_groups)
|
||||
value_states = repeat_kv(value, module.num_key_value_groups)
|
||||
|
||||
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
||||
if attention_mask is not None:
|
||||
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
||||
attn_weights = attn_weights + causal_mask
|
||||
|
||||
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
||||
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
||||
attn_output = torch.matmul(attn_weights, value_states)
|
||||
attn_output = attn_output.transpose(1, 2).contiguous()
|
||||
|
||||
return attn_output, attn_weights
|
||||
|
||||
|
||||
class BreezeAttention(nn.Module):
|
||||
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
||||
|
||||
def __init__(self, config, layer_idx: int):
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.layer_idx = layer_idx
|
||||
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
||||
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
||||
self.scaling = self.head_dim**-0.5
|
||||
self.attention_dropout = config.attention_dropout
|
||||
self.is_causal = True
|
||||
|
||||
self.q_proj = nn.Linear(
|
||||
config.hidden_size,
|
||||
config.num_attention_heads * self.head_dim,
|
||||
bias=config.attention_bias,
|
||||
)
|
||||
self.k_proj = nn.Linear(
|
||||
config.hidden_size,
|
||||
config.num_key_value_heads * self.head_dim,
|
||||
bias=config.attention_bias,
|
||||
)
|
||||
self.v_proj = nn.Linear(
|
||||
config.hidden_size,
|
||||
config.num_key_value_heads * self.head_dim,
|
||||
bias=config.attention_bias,
|
||||
)
|
||||
self.o_proj = nn.Linear(
|
||||
config.num_attention_heads * self.head_dim,
|
||||
config.hidden_size,
|
||||
bias=config.attention_bias,
|
||||
)
|
||||
|
||||
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
||||
attention_mask: torch.Tensor | None,
|
||||
past_key_values: Cache | None = None,
|
||||
cache_position: torch.LongTensor | None = None,
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
input_shape = hidden_states.shape[:-1]
|
||||
hidden_shape = (*input_shape, -1, self.head_dim)
|
||||
|
||||
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
||||
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
||||
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
||||
|
||||
cos, sin = position_embeddings
|
||||
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
||||
|
||||
if past_key_values is not None:
|
||||
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
||||
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
||||
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
||||
|
||||
attention_interface: Callable = eager_attention_forward
|
||||
if self.config._attn_implementation != "eager":
|
||||
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
||||
|
||||
attn_output, attn_weights = attention_interface(
|
||||
self,
|
||||
query_states,
|
||||
key_states,
|
||||
value_states,
|
||||
attention_mask,
|
||||
dropout=0.0 if not self.training else self.attention_dropout,
|
||||
scaling=self.scaling,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
||||
attn_output = self.o_proj(attn_output)
|
||||
return attn_output, attn_weights
|
||||
|
||||
|
||||
class BreezeDecoderLayer(nn.Module):
|
||||
def __init__(self, config, layer_idx: int):
|
||||
super().__init__()
|
||||
self.hidden_size = config.hidden_size
|
||||
|
||||
self.self_attn = BreezeAttention(config=config, layer_idx=layer_idx)
|
||||
|
||||
self.mlp = BreezeMLP(config)
|
||||
self.input_layernorm = BreezeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
self.post_attention_layernorm = BreezeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
|
||||
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
position_ids: torch.LongTensor | None = None,
|
||||
past_key_values: Cache | None = None,
|
||||
use_cache: bool | None = False,
|
||||
cache_position: torch.LongTensor | None = None,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, # necessary, but kept here for BC
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> torch.Tensor:
|
||||
residual = hidden_states
|
||||
hidden_states = self.input_layernorm(hidden_states)
|
||||
# Self Attention
|
||||
hidden_states, _ = self.self_attn(
|
||||
hidden_states=hidden_states,
|
||||
attention_mask=attention_mask,
|
||||
position_ids=position_ids,
|
||||
past_key_values=past_key_values,
|
||||
use_cache=use_cache,
|
||||
cache_position=cache_position,
|
||||
position_embeddings=position_embeddings,
|
||||
**kwargs,
|
||||
)
|
||||
hidden_states = residual + hidden_states
|
||||
|
||||
# Fully Connected
|
||||
residual = hidden_states
|
||||
hidden_states = self.post_attention_layernorm(hidden_states)
|
||||
hidden_states = self.mlp(hidden_states)
|
||||
hidden_states = residual + hidden_states
|
||||
return hidden_states
|
||||
|
||||
|
||||
class BreezeCodebooksHead(nn.Module):
|
||||
"""Position-specific heads for codebooks 1..15."""
|
||||
|
||||
def __init__(self, hidden_size: int, num_codebooks: int, vocab_size: int) -> None:
|
||||
super().__init__()
|
||||
self.num_codebooks = int(num_codebooks)
|
||||
self.weight = nn.Parameter(torch.empty(self.num_codebooks - 1, hidden_size, vocab_size))
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
# ``hidden_states`` contains the placeholder at position 0 followed
|
||||
# by codebook-0..N tokens. Return logits for codebook-1..N.
|
||||
depth_states = hidden_states[:, 1 : self.num_codebooks, :]
|
||||
if depth_states.shape[1] > self.num_codebooks - 1:
|
||||
raise ValueError(f"depth decoder received too many input positions: {hidden_states.shape[1]}")
|
||||
return torch.einsum("bkh,khv->bkv", depth_states, self.weight[: depth_states.shape[1]])
|
||||
|
||||
|
||||
class BreezeDepthDecoderForCausalLM(nn.Module):
|
||||
"""Eager depth decoder used by the vLLM stage-0 talker."""
|
||||
|
||||
def __init__(self, config) -> None:
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.model = BreezeDepthDecoderModel(config)
|
||||
self.codebooks_head = BreezeCodebooksHead(
|
||||
config.hidden_size,
|
||||
config.num_codebooks,
|
||||
config.vocab_size,
|
||||
)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.Tensor,
|
||||
backbone_last_hidden_state: torch.Tensor,
|
||||
*,
|
||||
use_cache: bool = False,
|
||||
**kwargs,
|
||||
) -> CausalLMOutputWithPast:
|
||||
outputs = self.model(
|
||||
input_ids=input_ids,
|
||||
backbone_last_hidden_state=backbone_last_hidden_state,
|
||||
use_cache=use_cache,
|
||||
**kwargs,
|
||||
)
|
||||
logits = self.codebooks_head(outputs.last_hidden_state)
|
||||
return CausalLMOutputWithPast(
|
||||
logits=logits,
|
||||
past_key_values=outputs.past_key_values,
|
||||
hidden_states=getattr(outputs, "hidden_states", None),
|
||||
attentions=getattr(outputs, "attentions", None),
|
||||
)
|
||||
|
||||
def load_weights(self, weights):
|
||||
params_dict = dict(self.named_parameters())
|
||||
loaded: set[str] = set()
|
||||
for name, tensor in weights:
|
||||
param = params_dict.get(name)
|
||||
if param is None:
|
||||
continue
|
||||
if name == "codebooks_head.weight":
|
||||
expected = (
|
||||
int(self.config.num_codebooks) - 1,
|
||||
int(self.config.hidden_size),
|
||||
int(self.config.vocab_size),
|
||||
)
|
||||
actual = tuple(int(dim) for dim in tensor.shape)
|
||||
if actual != expected:
|
||||
raise ValueError(f"Breeze depth weight {name!r} has shape {actual}, expected {expected}")
|
||||
loader = getattr(param, "weight_loader", None)
|
||||
if loader is None:
|
||||
param.data.copy_(tensor.to(device=param.device, dtype=param.dtype))
|
||||
else:
|
||||
loader(param, tensor)
|
||||
loaded.add(name)
|
||||
return loaded
|
||||
|
||||
|
||||
__all__ = [
|
||||
"BreezeCodebooksHead",
|
||||
"BreezeDepthDecoderForCausalLM",
|
||||
"BreezeDepthDecoderModel",
|
||||
]
|
||||
@@ -1,641 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Breeze-TTS-2 stage-0 talker for vLLM-Omni.
|
||||
|
||||
The scheduler samples Breeze codebook-0 tokens one at a time. The other 15
|
||||
codebooks are kept in the request-local Omni buffer: after each backbone step,
|
||||
the eager depth decoder completes the frame and the next backbone step
|
||||
consumes the summed 16-codebook embedding. This preserves the upstream Breeze
|
||||
generation order without importing HuggingFace GenerationMixin.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import math
|
||||
import os
|
||||
from collections.abc import Iterable, Mapping, Sequence
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
from torch.nn.utils.rnn import pad_sequence
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.model_executor.layers.logits_processor import LogitsProcessor
|
||||
from vllm.model_executor.layers.vocab_parallel_embedding import ParallelLMHead
|
||||
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
|
||||
from vllm.model_executor.models.qwen3 import Qwen3Model
|
||||
from vllm.sequence import IntermediateTensors
|
||||
from vllm.v1.sample.metadata import SamplingMetadata
|
||||
|
||||
from vllm_omni.model_executor.models.breeze_tts_2.configuration_breeze_tts_2 import (
|
||||
BreezeTTS2Config,
|
||||
)
|
||||
from vllm_omni.model_executor.models.breeze_tts_2.modeling_breeze_tts_2_depth import (
|
||||
BreezeDepthDecoderForCausalLM,
|
||||
)
|
||||
from vllm_omni.model_executor.models.breeze_tts_2.modeling_breeze_tts_2_text import (
|
||||
BreezeTTS2TextEncoder,
|
||||
)
|
||||
from vllm_omni.model_executor.models.output_templates import OmniOutput
|
||||
|
||||
|
||||
def _prefixed(prefix: str, name: str) -> str:
|
||||
return f"{prefix}.{name}" if prefix else name
|
||||
|
||||
|
||||
def _normalize_request_infos(infos: Any) -> list[dict[str, Any]] | None:
|
||||
"""Normalize runner metadata to one mutable dict per request."""
|
||||
if not isinstance(infos, Sequence) or isinstance(infos, (str, bytes, bytearray)):
|
||||
return None
|
||||
if not all(isinstance(info, dict) for info in infos):
|
||||
return None
|
||||
return infos
|
||||
|
||||
|
||||
def _iter_request_rows(
|
||||
states: Sequence[dict[str, Any]],
|
||||
spans: Sequence[tuple[int, int]] | None,
|
||||
num_rows: int,
|
||||
) -> Iterable[tuple[dict[str, Any], int, int]]:
|
||||
"""Map request state to logits rows for full or sampled hidden layouts."""
|
||||
if num_rows <= 0 or not states:
|
||||
return
|
||||
if spans is not None and len(spans) == len(states):
|
||||
if all(0 <= int(start) <= int(end) <= num_rows for start, end in spans):
|
||||
for state, (start, end) in zip(states, spans, strict=True):
|
||||
if int(start) < int(end):
|
||||
yield state, int(start), int(end)
|
||||
return
|
||||
# The runner passes full-sequence spans to make_omni_output but only
|
||||
# one sampled row per request to compute_logits.
|
||||
if num_rows == len(states):
|
||||
for index, state in enumerate(states):
|
||||
yield state, index, index + 1
|
||||
return
|
||||
if num_rows == len(states):
|
||||
for index, state in enumerate(states):
|
||||
yield state, index, index + 1
|
||||
return
|
||||
raise RuntimeError(
|
||||
"Breeze talker cannot align request state with logits rows: "
|
||||
f"states={len(states)}, rows={num_rows}, spans={spans}"
|
||||
)
|
||||
|
||||
|
||||
def _check_weight_shape(name: str, tensor: torch.Tensor, expected: tuple[int, ...]) -> None:
|
||||
"""Fail early for Breeze-owned, non-sharded checkpoint tensors."""
|
||||
actual = tuple(int(dim) for dim in tensor.shape)
|
||||
if actual != expected:
|
||||
raise ValueError(f"Breeze weight {name!r} has shape {actual}, expected {expected}")
|
||||
|
||||
|
||||
class BreezeTTS2TalkerForGeneration(nn.Module):
|
||||
"""Stage-0 Breeze talker: text/audio conditioning -> codec frames."""
|
||||
|
||||
have_multimodal_outputs = True
|
||||
has_preprocess = True
|
||||
has_postprocess = True
|
||||
# Stage 0 emits a tiny per-frame codec payload. Let the AR runner snapshot
|
||||
# it through the async-output path instead of the final-only client path.
|
||||
use_async_omni_output = True
|
||||
eager_omni_postprocess_before_async_output = True
|
||||
omni_pooler_payload_include_hidden = False
|
||||
input_modalities = "text"
|
||||
gpu_resident_buffer_keys: set[tuple[str, str]] = {
|
||||
("hidden_states", "last"),
|
||||
}
|
||||
|
||||
def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None:
|
||||
super().__init__()
|
||||
self.vllm_config = vllm_config
|
||||
self.config: BreezeTTS2Config = vllm_config.model_config.hf_config
|
||||
self._async_chunk = bool(vllm_config.model_config.async_chunk)
|
||||
self._golden_dump_dir = os.environ.get("VLLM_OMNI_BREEZE_GOLDEN_DIR")
|
||||
|
||||
backbone_config = self.config.backbone_config
|
||||
backbone_vllm_config = vllm_config.with_hf_config(
|
||||
backbone_config,
|
||||
architectures=["Qwen3ForCausalLM"],
|
||||
)
|
||||
backbone_vllm_config.model_config.hf_text_config = backbone_config
|
||||
self.model = Qwen3Model(
|
||||
vllm_config=backbone_vllm_config,
|
||||
prefix=_prefixed(prefix, "model"),
|
||||
)
|
||||
# Upstream's Qwen3 adapter keeps only decoder layers/norm/RoPE and
|
||||
# replaces the standard text embedding with Breeze's summed audio/text
|
||||
# tables. Breeze always supplies ``inputs_embeds`` through preprocess,
|
||||
# so remove the unused Qwen embedding instead of allocating and then
|
||||
# reporting an uninitialized 151936x2048 parameter at load time.
|
||||
self.model.embed_tokens = nn.Identity()
|
||||
|
||||
self.hidden_size = int(backbone_config.hidden_size)
|
||||
self.num_codebooks = int(self.config.num_codebooks)
|
||||
self.codebook_vocab_size = int(self.config.vocab_size)
|
||||
codec_config = self.config.codec_config
|
||||
self.codebook_size = (
|
||||
int(codec_config.get("codebook_size", self.codebook_vocab_size))
|
||||
if isinstance(codec_config, Mapping)
|
||||
else self.codebook_vocab_size
|
||||
)
|
||||
self.codebook_eos_token_id = int(self.config.codebook_eos_token_id)
|
||||
self.audio_token_id = int(self.config.audio_token_id)
|
||||
self.audio_eos_token_id = int(self.config.audio_eos_token_id)
|
||||
self.text_pad_token_id = int(self.config.pad_token_id)
|
||||
|
||||
self.lm_head = ParallelLMHead(
|
||||
self.codebook_vocab_size + 1,
|
||||
self.hidden_size,
|
||||
bias=False,
|
||||
prefix=_prefixed(prefix, "lm_head"),
|
||||
)
|
||||
self.logits_processor = LogitsProcessor(self.codebook_vocab_size + 1)
|
||||
|
||||
# Upstream Breeze uses embedding(code_i + i * vocab_size) and sums
|
||||
# over codebooks before entering the Qwen3 backbone.
|
||||
self.embed_audio_tokens = nn.Embedding(
|
||||
self.num_codebooks * self.codebook_vocab_size,
|
||||
self.hidden_size,
|
||||
)
|
||||
# Keep Breeze's standalone text table even though the normal path
|
||||
# uses T5Gemma2 outputs. It is part of the checkpoint contract and is
|
||||
# also the correct fallback when a checkpoint omits text_encoder.
|
||||
self.embed_text_tokens = nn.Embedding(int(self.config.text_vocab_size), self.hidden_size)
|
||||
self.register_buffer(
|
||||
"audio_token_offsets",
|
||||
torch.arange(self.num_codebooks, dtype=torch.long) * self.codebook_vocab_size,
|
||||
persistent=False,
|
||||
)
|
||||
|
||||
self.text_encoder = BreezeTTS2TextEncoder(self.config.text_encoder_config)
|
||||
self.text_encoder_proj = nn.Linear(
|
||||
int(self.config.text_encoder_config.hidden_size),
|
||||
self.hidden_size,
|
||||
bias=False,
|
||||
)
|
||||
self.depth_decoder = BreezeDepthDecoderForCausalLM(self.config.depth_decoder_config)
|
||||
if bool(self.config.tie_codebooks_embeddings):
|
||||
# The upstream HF model ties these tables. Sharing the Parameter
|
||||
# also prevents a tied checkpoint from leaving the depth input
|
||||
# embedding randomly initialized when only one key is serialized.
|
||||
self.depth_decoder.model.embed_tokens.weight = self.embed_audio_tokens.weight
|
||||
|
||||
self._codec_disallowed_mask: torch.Tensor | None = None
|
||||
self._batch_state: list[dict[str, Any]] | None = None
|
||||
self._batch_state_spans: Sequence[tuple[int, int]] | None = None
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Embedding and backbone hooks
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def embed_input_ids(self, input_ids: torch.Tensor, **_: Any) -> torch.Tensor:
|
||||
"""Embed complete generated codec frames; scalar ids are invalid."""
|
||||
if input_ids.ndim < 1 or input_ids.shape[-1] != self.num_codebooks:
|
||||
raise ValueError(
|
||||
"Breeze embed_input_ids requires complete codec frames with shape "
|
||||
f"(..., {self.num_codebooks}), got {tuple(input_ids.shape)}"
|
||||
)
|
||||
codes = input_ids.to(dtype=torch.long)
|
||||
offsets = self.audio_token_offsets.to(device=codes.device)
|
||||
ids = codes.clamp(0, self.codebook_vocab_size - 1) + offsets
|
||||
return self.embed_audio_tokens(ids).sum(dim=-2)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
intermediate_tensors: IntermediateTensors | None = None,
|
||||
inputs_embeds: torch.Tensor | None = None,
|
||||
**_: Any,
|
||||
) -> torch.Tensor | IntermediateTensors:
|
||||
return self.model(
|
||||
input_ids=input_ids,
|
||||
positions=positions,
|
||||
intermediate_tensors=intermediate_tensors,
|
||||
inputs_embeds=inputs_embeds,
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Prompt/text conditioning
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _encode_text_segments(
|
||||
self,
|
||||
input_ids: torch.Tensor,
|
||||
text_mask: torch.Tensor,
|
||||
text_lengths: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
text_ids = input_ids[text_mask.to(device=input_ids.device, dtype=torch.bool)].to(torch.long)
|
||||
lengths = [int(x) for x in text_lengths.reshape(-1).tolist() if int(x) > 0]
|
||||
if int(text_ids.numel()) != sum(lengths):
|
||||
raise ValueError(f"Breeze text mask/length mismatch: {text_ids.numel()} != {sum(lengths)}")
|
||||
if not lengths:
|
||||
return input_ids.new_empty((0, self.hidden_size), dtype=self.text_encoder.dtype)
|
||||
segments = list(torch.split(text_ids, lengths))
|
||||
padded = pad_sequence(segments, batch_first=True, padding_value=0)
|
||||
attn = torch.zeros_like(padded, dtype=torch.bool)
|
||||
for row, length in enumerate(lengths):
|
||||
attn[row, :length] = True
|
||||
hidden = self.text_encoder(padded, attention_mask=attn)
|
||||
projected = self.text_encoder_proj(hidden)
|
||||
return torch.cat([projected[row, :length] for row, length in enumerate(lengths)], dim=0)
|
||||
|
||||
def _build_prompt_embeddings(self, prompt_ids: torch.Tensor, info: Mapping[str, Any]) -> torch.Tensor:
|
||||
device = next(self.parameters()).device
|
||||
prompt_ids = prompt_ids.reshape(-1).to(device=device, dtype=torch.long)
|
||||
text_mask = torch.as_tensor(info.get("text_ids_mask"), device=device, dtype=torch.bool).reshape(-1)
|
||||
text_lengths = torch.as_tensor(info.get("text_ids_len"), device=device, dtype=torch.long)
|
||||
if text_mask.numel() != prompt_ids.numel():
|
||||
raise ValueError("Breeze text_ids_mask length does not match prompt length")
|
||||
output = torch.zeros(
|
||||
(prompt_ids.numel(), self.hidden_size),
|
||||
device=device,
|
||||
dtype=self.embed_text_tokens.weight.dtype,
|
||||
)
|
||||
text_embeds = self._encode_text_segments(prompt_ids, text_mask, text_lengths)
|
||||
output[text_mask] = text_embeds.to(dtype=output.dtype)
|
||||
|
||||
audio_mask = prompt_ids == self.audio_token_id
|
||||
input_values = info.get("input_values")
|
||||
if bool(audio_mask.any()):
|
||||
if input_values is None:
|
||||
raise ValueError("Breeze audio placeholders require input_values")
|
||||
codes = torch.as_tensor(input_values, device=device, dtype=torch.long)
|
||||
if codes.ndim != 2 or codes.shape[-1] != self.num_codebooks:
|
||||
raise ValueError(f"Breeze input_values must be (T, {self.num_codebooks})")
|
||||
if int(codes.shape[0]) != int(audio_mask.sum()):
|
||||
raise ValueError("Breeze reference code count does not match audio placeholders")
|
||||
output[audio_mask] = self.embed_input_ids(codes).to(dtype=output.dtype)
|
||||
|
||||
eos_mask = prompt_ids == self.audio_eos_token_id
|
||||
if bool(eos_mask.any()):
|
||||
eos_codes = torch.full(
|
||||
(1, self.num_codebooks),
|
||||
self.codebook_eos_token_id,
|
||||
dtype=torch.long,
|
||||
device=device,
|
||||
)
|
||||
output[eos_mask] = self.embed_input_ids(eos_codes).expand(int(eos_mask.sum()), -1)
|
||||
return output
|
||||
|
||||
def preprocess(
|
||||
self,
|
||||
input_ids: torch.Tensor,
|
||||
input_embeds: torch.Tensor | None,
|
||||
**info_dict: Any,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, dict[str, Any]]:
|
||||
"""Build prefill embeddings and consume one completed frame per decode."""
|
||||
del input_embeds
|
||||
info = dict(info_dict)
|
||||
span_len = int(input_ids.shape[0])
|
||||
is_prefill = bool(info.get("_omni_is_prefill", span_len > 1))
|
||||
if is_prefill:
|
||||
full_ids = info.get("prompt_ids")
|
||||
if not isinstance(full_ids, torch.Tensor):
|
||||
raise RuntimeError("Breeze prefill is missing prompt_ids")
|
||||
full_embeds = info.get("breeze_prompt_embeds")
|
||||
if not isinstance(full_embeds, torch.Tensor):
|
||||
full_embeds = self._build_prompt_embeddings(full_ids, info).detach().cpu().contiguous()
|
||||
offset = int(info.get("breeze_prefill_offset", info.get("_omni_num_computed_tokens", 0)) or 0)
|
||||
take = full_embeds[offset : offset + span_len].to(device=input_ids.device)
|
||||
if take.shape[0] != span_len:
|
||||
raise RuntimeError("Breeze prompt embedding slice is shorter than scheduled span")
|
||||
return (
|
||||
torch.full_like(input_ids, self.text_pad_token_id),
|
||||
take,
|
||||
{
|
||||
"breeze_prompt_embeds": full_embeds,
|
||||
"breeze_prefill_offset": offset + span_len,
|
||||
"breeze_generated_frames": int(info.get("breeze_generated_frames", 0) or 0),
|
||||
"breeze_max_new_frames": int(info.get("breeze_max_new_frames", -1)),
|
||||
},
|
||||
)
|
||||
|
||||
frame = info.get("breeze_current_frame")
|
||||
if isinstance(frame, torch.Tensor) and frame.numel() == self.num_codebooks:
|
||||
frame = frame.to(device=input_ids.device, dtype=torch.long).reshape(1, 1, -1)
|
||||
embeds = self.embed_input_ids(frame).reshape(1, -1)
|
||||
safe_id = frame[..., 0].reshape_as(input_ids).to(dtype=input_ids.dtype)
|
||||
return safe_id, embeds, {}
|
||||
has_breeze_state = any(
|
||||
key in info
|
||||
for key in (
|
||||
"breeze_current_frame",
|
||||
"breeze_audio_codes",
|
||||
"breeze_generated_frames",
|
||||
"breeze_prompt_embeds",
|
||||
)
|
||||
)
|
||||
if has_breeze_state:
|
||||
# A real decode must consume the full frame produced from the
|
||||
# preceding backbone hidden state. A scalar fallback would silently
|
||||
# fill codebooks 1..15 with EOS and corrupt AR state.
|
||||
raise RuntimeError(
|
||||
"Breeze decode is missing breeze_current_frame; refusing scalar fallback "
|
||||
"because it would fill codebooks 1..15 with EOS"
|
||||
)
|
||||
# Runner-only dummy execution has no Breeze codec state. It must not
|
||||
# invent a semantically invalid audio frame; a stable zero embedding is
|
||||
# sufficient for shape/profiling warmup.
|
||||
dummy_embeds = torch.zeros(
|
||||
(*input_ids.shape, self.hidden_size),
|
||||
device=input_ids.device,
|
||||
dtype=self.embed_audio_tokens.weight.dtype,
|
||||
)
|
||||
return input_ids, dummy_embeds, {}
|
||||
|
||||
def postprocess(self, hidden_states: torch.Tensor, **_: Any) -> dict[str, Any]:
|
||||
if hidden_states.numel() == 0:
|
||||
return {}
|
||||
return {"hidden_states": {"last": hidden_states[-1].detach()}}
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Main head, depth decoder and Omni output
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def compute_logits(
|
||||
self,
|
||||
hidden_states: torch.Tensor | OmniOutput,
|
||||
sampling_metadata: SamplingMetadata | None = None,
|
||||
) -> torch.Tensor | None:
|
||||
del sampling_metadata
|
||||
if isinstance(hidden_states, OmniOutput):
|
||||
hidden_states = hidden_states.text_hidden_states
|
||||
if hidden_states is None:
|
||||
return None
|
||||
logits = self._main_head_logits(hidden_states)
|
||||
|
||||
# ``make_omni_output`` already selected codebook 0 and completed its
|
||||
# frame. Return that same decision to the scheduler, including EOS.
|
||||
# A finite zero survives the sampler's repetition/temperature passes
|
||||
# without applying the repetition penalty twice or changing the frame.
|
||||
# These logits describe deterministic codec selection, not model
|
||||
# confidence; sampled-token logprobs are consequently zero.
|
||||
states = self._batch_state or []
|
||||
if states:
|
||||
for state, row_start, row_end in _iter_request_rows(
|
||||
states,
|
||||
getattr(self, "_batch_state_spans", None),
|
||||
int(logits.shape[0]),
|
||||
):
|
||||
selected_code0 = state.get("breeze_selected_code0")
|
||||
if selected_code0 is not None:
|
||||
row = logits[row_start:row_end]
|
||||
row.fill_(float("-inf"))
|
||||
row[:, int(selected_code0)] = 0.0
|
||||
return logits
|
||||
|
||||
def _main_head_logits(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
logits = self.logits_processor(self.lm_head, hidden_states)
|
||||
if logits is None:
|
||||
raise RuntimeError("Breeze main head returned no logits")
|
||||
if self._codec_disallowed_mask is None or self._codec_disallowed_mask.device != logits.device:
|
||||
mask = torch.zeros(logits.shape[-1], dtype=torch.bool, device=logits.device)
|
||||
if self.codebook_size < self.codebook_vocab_size:
|
||||
mask[self.codebook_size : self.codebook_vocab_size] = True
|
||||
self._codec_disallowed_mask = mask
|
||||
return logits.masked_fill(self._codec_disallowed_mask, float("-inf"))
|
||||
|
||||
@torch.no_grad()
|
||||
def _generate_depth_codes(self, backbone_hidden: torch.Tensor, code0: int) -> torch.Tensor:
|
||||
sequence = torch.tensor([[0, code0]], dtype=torch.long, device=backbone_hidden.device)
|
||||
generated = [int(code0)]
|
||||
for _ in range(self.num_codebooks - 1):
|
||||
depth_out = self.depth_decoder(
|
||||
input_ids=sequence,
|
||||
backbone_last_hidden_state=backbone_hidden.reshape(1, -1),
|
||||
use_cache=False,
|
||||
)
|
||||
logits = depth_out.logits[:, -1, :].clone()
|
||||
if self.codebook_size < logits.shape[-1]:
|
||||
logits[:, self.codebook_size :] = float("-inf")
|
||||
next_code = int(torch.argmax(logits, dim=-1).item())
|
||||
generated.append(next_code)
|
||||
sequence = torch.cat([sequence, torch.tensor([[next_code]], device=sequence.device)], dim=1)
|
||||
return torch.tensor(generated, dtype=torch.long, device=backbone_hidden.device).unsqueeze(0)
|
||||
|
||||
@staticmethod
|
||||
def _accumulate_codes(info: dict[str, Any], frame: torch.Tensor) -> torch.Tensor:
|
||||
"""Append one ``(1, Q)`` frame to the request's cumulative codes."""
|
||||
accumulated = info.get("breeze_audio_codes")
|
||||
accumulated = (
|
||||
torch.cat([accumulated.to(frame.device), frame], dim=0)
|
||||
if isinstance(accumulated, torch.Tensor) and accumulated.numel()
|
||||
else frame
|
||||
)
|
||||
info["breeze_audio_codes"] = accumulated
|
||||
return accumulated
|
||||
|
||||
def make_omni_output(self, model_outputs: torch.Tensor | OmniOutput, **kwargs: Any) -> OmniOutput:
|
||||
if isinstance(model_outputs, OmniOutput):
|
||||
self._batch_state = None
|
||||
self._batch_state_spans = None
|
||||
return model_outputs
|
||||
hidden = model_outputs
|
||||
infos = kwargs.get("model_intermediate_buffer", [])
|
||||
spans = kwargs.get("request_token_spans")
|
||||
info_items = _normalize_request_infos(infos)
|
||||
if info_items is None:
|
||||
self._batch_state = None
|
||||
self._batch_state_spans = None
|
||||
return OmniOutput(text_hidden_states=hidden, multimodal_outputs={})
|
||||
# The runner invokes compute_logits after this method, so retain the
|
||||
# same request ordering and spans for per-request EOS masking.
|
||||
self._batch_state = info_items
|
||||
self._batch_state_spans = spans
|
||||
per_request_codes: list[torch.Tensor] = []
|
||||
# The runner passes the same per-request sampling metadata to this
|
||||
# hook and compute_logits, including offline SamplingParams overrides.
|
||||
# When no_penalties is true vLLM does not initialize this GPU buffer.
|
||||
sampling_metadata = kwargs.get("sampling_metadata")
|
||||
repetition_penalties = None
|
||||
if sampling_metadata is not None and not sampling_metadata.no_penalties:
|
||||
repetition_penalties = sampling_metadata.repetition_penalties.tolist()
|
||||
|
||||
for index, info in enumerate(info_items):
|
||||
if spans is not None and index < len(spans):
|
||||
row_start = max(0, int(spans[index][0]))
|
||||
row_end = min(int(spans[index][1]), int(hidden.shape[0]))
|
||||
elif len(info_items) == 1:
|
||||
row_start, row_end = 0, int(hidden.shape[0])
|
||||
else:
|
||||
raise RuntimeError("Breeze make_omni_output requires request_token_spans for batched decode")
|
||||
if row_end <= row_start:
|
||||
per_request_codes.append(hidden.new_empty((0, self.num_codebooks), dtype=torch.long))
|
||||
continue
|
||||
row_hidden = hidden[row_end - 1]
|
||||
if self._golden_dump_dir and bool(info.get("_omni_is_prefill", False)):
|
||||
self._dump_golden_prefill(info, row_hidden)
|
||||
main_logits = self._main_head_logits(row_hidden.reshape(1, -1)).float()
|
||||
penalty = float(repetition_penalties[index]) if repetition_penalties is not None else 1.0
|
||||
if not math.isfinite(penalty) or penalty <= 0:
|
||||
raise ValueError("Breeze repetition_penalty must be finite and positive")
|
||||
# Match upstream: penalize each previously generated codebook-0
|
||||
# id once, excluding the text prompt and reference audio codes.
|
||||
history = info.setdefault("breeze_generated_code0_ids", [])
|
||||
if penalty != 1.0 and history:
|
||||
history_ids = torch.tensor(history, device=main_logits.device, dtype=torch.long)
|
||||
scores = main_logits[0, history_ids]
|
||||
main_logits[0, history_ids] = torch.where(scores < 0, scores * penalty, scores / penalty)
|
||||
code0 = int(torch.argmax(main_logits, dim=-1).item())
|
||||
generated_frames = int(info.get("breeze_generated_frames", 0) or 0)
|
||||
max_new_frames = int(info.get("breeze_max_new_frames", -1))
|
||||
terminal = code0 == self.codebook_vocab_size or (max_new_frames > 0 and generated_frames >= max_new_frames)
|
||||
info["breeze_selected_code0"] = self.codebook_vocab_size if terminal else code0
|
||||
if terminal:
|
||||
info["breeze_force_eos"] = True
|
||||
existing = info.get("breeze_audio_codes")
|
||||
per_request_codes.append(
|
||||
existing
|
||||
if isinstance(existing, torch.Tensor) and existing.numel() and not self._async_chunk
|
||||
else hidden.new_empty((0, self.num_codebooks), dtype=torch.long)
|
||||
)
|
||||
continue
|
||||
if code0 < 0 or code0 >= self.codebook_size:
|
||||
raise RuntimeError(f"Breeze main head produced invalid codec id {code0}")
|
||||
|
||||
frame = self._generate_depth_codes(row_hidden, code0)
|
||||
history.append(code0)
|
||||
info["breeze_current_frame"] = frame[0].detach()
|
||||
info["breeze_generated_frames"] = generated_frames + 1
|
||||
info["breeze_force_eos"] = False
|
||||
if self._async_chunk:
|
||||
# Streaming consumers only ever read the per-frame tail. The
|
||||
# cumulative buffer exists for full-payload transport and the
|
||||
# opt-in golden dump; maintaining it here would also cost an
|
||||
# O(T^2) tensor-cat per request.
|
||||
if self._golden_dump_dir:
|
||||
self._accumulate_codes(info, frame)
|
||||
per_request_codes.append(frame)
|
||||
else:
|
||||
per_request_codes.append(self._accumulate_codes(info, frame))
|
||||
if self._golden_dump_dir:
|
||||
for info in info_items:
|
||||
self._dump_golden_frames(info)
|
||||
return OmniOutput(text_hidden_states=hidden, multimodal_outputs={"codes": {"audio": per_request_codes}})
|
||||
|
||||
def _dump_golden_frames(self, info: dict[str, Any]) -> None:
|
||||
"""Write terminal codec frames for opt-in golden-parity diagnostics."""
|
||||
codes = info.get("breeze_audio_codes")
|
||||
if not info.get("breeze_force_eos", False) or not isinstance(codes, torch.Tensor) or codes.numel() == 0:
|
||||
return
|
||||
prompt_ids = info.get("prompt_ids")
|
||||
if not isinstance(prompt_ids, torch.Tensor):
|
||||
raise RuntimeError("Breeze golden dump is missing prompt_ids")
|
||||
digest = hashlib.sha256(prompt_ids.detach().cpu().numpy().tobytes()).hexdigest()[:16]
|
||||
output_dir = Path(self._golden_dump_dir) # type: ignore[arg-type]
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
torch.save(
|
||||
{
|
||||
"template": info.get("template"),
|
||||
"prompt_ids": prompt_ids.cpu(),
|
||||
"codes": codes.detach().cpu().to(torch.long).contiguous(),
|
||||
"generated_frames": int(info.get("breeze_generated_frames", 0) or 0),
|
||||
"finished": True,
|
||||
},
|
||||
output_dir / f"breeze_{digest}.pt",
|
||||
)
|
||||
|
||||
def _dump_golden_prefill(self, info: dict[str, Any], hidden: torch.Tensor) -> None:
|
||||
"""Write the terminal-prompt hidden row for opt-in parity diagnostics."""
|
||||
prompt_ids = info.get("prompt_ids")
|
||||
if not isinstance(prompt_ids, torch.Tensor):
|
||||
raise RuntimeError("Breeze golden dump is missing prompt_ids")
|
||||
digest = hashlib.sha256(prompt_ids.detach().cpu().numpy().tobytes()).hexdigest()[:16]
|
||||
output_dir = Path(self._golden_dump_dir) # type: ignore[arg-type]
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
torch.save(
|
||||
{
|
||||
"template": info.get("template"),
|
||||
"prompt_ids": prompt_ids.cpu(),
|
||||
"hidden": hidden.detach().reshape(-1).cpu().to(torch.float32).contiguous(),
|
||||
},
|
||||
output_dir / f"prefill_{digest}.pt",
|
||||
)
|
||||
|
||||
def on_requests_finished(self, finished_req_ids: Iterable[str]) -> None:
|
||||
"""Drop cross-step references retained for the finished AR requests."""
|
||||
del finished_req_ids
|
||||
# Codec/frame state lives in request-local additional_information and is
|
||||
# freed with the Request. Only the short logits-to-state mapping is
|
||||
# model-owned and must not leak into the next micro-batch.
|
||||
self._batch_state = None
|
||||
self._batch_state_spans = None
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Weight loading
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
loaded: set[str] = set()
|
||||
params = dict(self.named_parameters())
|
||||
backbone_weights: list[tuple[str, torch.Tensor]] = []
|
||||
text_weights: list[tuple[str, torch.Tensor]] = []
|
||||
depth_weights: list[tuple[str, torch.Tensor]] = []
|
||||
for name, tensor in weights:
|
||||
# This table belongs to Breeze's custom audio embedding module,
|
||||
# although its checkpoint key is nested under backbone_model.
|
||||
# Handle it before forwarding the remaining backbone weights to
|
||||
# Qwen3Model.
|
||||
if name == "backbone_model.embed_tokens.embed_audio_tokens.weight":
|
||||
target = "embed_audio_tokens.weight"
|
||||
param = params.get(target)
|
||||
if param is None:
|
||||
raise ValueError(f"Missing Breeze parameter: {target}")
|
||||
_check_weight_shape(name, tensor, tuple(param.shape))
|
||||
default_weight_loader(param, tensor)
|
||||
loaded.add(target)
|
||||
continue
|
||||
if name.startswith("backbone_model."):
|
||||
# Qwen3Model.load_weights() is called on the nested module and
|
||||
# therefore expects names relative to that module (the same
|
||||
# convention used by MOSS-TTS), not the outer ``model.``
|
||||
# namespace used by ``named_parameters()``.
|
||||
backbone_weights.append((name[len("backbone_model.") :], tensor))
|
||||
continue
|
||||
if name.startswith("text_encoder."):
|
||||
text_name = name[len("text_encoder.") :]
|
||||
text_weights.append((text_name, tensor))
|
||||
continue
|
||||
if name.startswith("depth_decoder."):
|
||||
depth_weights.append((name[len("depth_decoder.") :], tensor))
|
||||
continue
|
||||
if name in {"lm_head.weight", "embed_text_tokens.weight"} or name.startswith("text_encoder_proj."):
|
||||
target = name
|
||||
else:
|
||||
continue
|
||||
param = params.get(target)
|
||||
if param is None:
|
||||
continue
|
||||
# ParallelLMHead stores a TP-local shard while checkpoint tensors
|
||||
# are global; validate against the global Breeze head shape.
|
||||
expected_shape = (
|
||||
(self.codebook_vocab_size + 1, self.hidden_size) if name == "lm_head.weight" else tuple(param.shape)
|
||||
)
|
||||
_check_weight_shape(name, tensor, expected_shape)
|
||||
loader = getattr(param, "weight_loader", default_weight_loader)
|
||||
loader(param, tensor)
|
||||
loaded.add(target)
|
||||
|
||||
if backbone_weights:
|
||||
loaded.update("model." + key for key in self.model.load_weights(backbone_weights))
|
||||
if text_weights:
|
||||
loaded.update("text_encoder." + key for key in self.text_encoder.load_weights(text_weights))
|
||||
if depth_weights:
|
||||
loaded.update("depth_decoder." + key for key in self.depth_decoder.load_weights(depth_weights))
|
||||
if bool(getattr(self.config, "tie_codebooks_embeddings", False)):
|
||||
# The checkpoint serializes only one side of the tied table.
|
||||
# ``named_parameters(remove_duplicate=True)`` exposes it as the
|
||||
# talker-owned ``embed_audio_tokens.weight``, so report both
|
||||
# aliases to the strict weight tracker.
|
||||
if "depth_decoder.model.embed_tokens.weight" in loaded:
|
||||
loaded.add("embed_audio_tokens.weight")
|
||||
if "embed_audio_tokens.weight" in loaded:
|
||||
loaded.add("depth_decoder.model.embed_tokens.weight")
|
||||
return loaded
|
||||
|
||||
|
||||
__all__ = ["BreezeTTS2TalkerForGeneration"]
|
||||
@@ -1,350 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Breeze T5Gemma2 text encoder.
|
||||
|
||||
The Breeze checkpoint contains a T5Gemma2 encoder, not the older T5Gemma
|
||||
implementation used by some diffusion models. This module keeps the encoder
|
||||
local to Breeze so checkpoint names and attention semantics stay explicit,
|
||||
while using vLLM tensor-parallel layers for the expensive projections.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import nn
|
||||
from vllm.distributed import get_tensor_model_parallel_world_size
|
||||
from vllm.model_executor.layers.activation import get_act_fn
|
||||
from vllm.model_executor.layers.linear import (
|
||||
MergedColumnParallelLinear,
|
||||
QKVParallelLinear,
|
||||
RowParallelLinear,
|
||||
)
|
||||
from vllm.model_executor.layers.vocab_parallel_embedding import VocabParallelEmbedding
|
||||
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
|
||||
|
||||
|
||||
class _RMSNorm(nn.Module):
|
||||
"""T5Gemma2 RMSNorm, whose checkpoint stores a zero-centered weight."""
|
||||
|
||||
def __init__(self, dim: int, eps: float) -> None:
|
||||
super().__init__()
|
||||
self.weight = nn.Parameter(torch.zeros(dim))
|
||||
self.eps = float(eps)
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
normalized = hidden_states.float() * torch.rsqrt(
|
||||
hidden_states.float().pow(2).mean(dim=-1, keepdim=True) + self.eps
|
||||
)
|
||||
return (normalized * (1.0 + self.weight.float())).to(hidden_states.dtype)
|
||||
|
||||
|
||||
class _RotaryEmbedding(nn.Module):
|
||||
def __init__(self, config: Any) -> None:
|
||||
super().__init__()
|
||||
self.config = config
|
||||
for layer_type in dict.fromkeys(config.layer_types):
|
||||
params = dict(config.rope_parameters.get(layer_type, {}))
|
||||
base = float(params.get("rope_theta", 10_000.0))
|
||||
factor = float(params.get("factor", 1.0))
|
||||
dim = int(config.head_dim)
|
||||
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim))
|
||||
if params.get("rope_type") == "linear":
|
||||
inv_freq = inv_freq / factor
|
||||
elif params.get("rope_type", "default") != "default":
|
||||
raise ValueError(f"Unsupported T5Gemma2 rope type: {params.get('rope_type')!r}")
|
||||
self.register_buffer(f"{layer_type}_inv_freq", inv_freq, persistent=False)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_ids: torch.Tensor,
|
||||
layer_type: str,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
inv_freq = getattr(self, f"{layer_type}_inv_freq")
|
||||
expanded = inv_freq[None, :, None].to(device=hidden_states.device)
|
||||
positions = position_ids[:, None, :].float()
|
||||
freqs = (expanded.float() @ positions).transpose(1, 2)
|
||||
emb = torch.cat((freqs, freqs), dim=-1)
|
||||
return emb.cos().to(hidden_states.dtype), emb.sin().to(hidden_states.dtype)
|
||||
|
||||
|
||||
def _rotate_half(value: torch.Tensor) -> torch.Tensor:
|
||||
first, second = value[..., : value.shape[-1] // 2], value[..., value.shape[-1] // 2 :]
|
||||
return torch.cat((-second, first), dim=-1)
|
||||
|
||||
|
||||
def _apply_rotary(
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
cos: torch.Tensor,
|
||||
sin: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
cos = cos.unsqueeze(1)
|
||||
sin = sin.unsqueeze(1)
|
||||
return (query * cos) + (_rotate_half(query) * sin), (key * cos) + (_rotate_half(key) * sin)
|
||||
|
||||
|
||||
def _repeat_kv(hidden_states: torch.Tensor, repeats: int) -> torch.Tensor:
|
||||
if repeats == 1:
|
||||
return hidden_states
|
||||
batch, heads, seq_len, head_dim = hidden_states.shape
|
||||
return (
|
||||
hidden_states[:, :, None, :, :]
|
||||
.expand(batch, heads, repeats, seq_len, head_dim)
|
||||
.reshape(batch, heads * repeats, seq_len, head_dim)
|
||||
)
|
||||
|
||||
|
||||
def _attention_mask(
|
||||
padding_mask: torch.Tensor | None,
|
||||
*,
|
||||
batch_size: int,
|
||||
seq_len: int,
|
||||
layer_type: str,
|
||||
sliding_window: int | None,
|
||||
dtype: torch.dtype,
|
||||
device: torch.device,
|
||||
) -> torch.Tensor | None:
|
||||
if layer_type == "full_attention" and padding_mask is None:
|
||||
return None
|
||||
valid = (
|
||||
torch.ones((batch_size, seq_len), device=device, dtype=torch.bool)
|
||||
if padding_mask is None
|
||||
else padding_mask.to(device=device, dtype=torch.bool)
|
||||
)
|
||||
allowed = valid[:, None, None, :].expand(batch_size, 1, seq_len, seq_len)
|
||||
if layer_type == "sliding_attention":
|
||||
if sliding_window is None:
|
||||
raise ValueError("T5Gemma2 sliding_attention requires sliding_window")
|
||||
q_idx = torch.arange(seq_len, device=device)[:, None]
|
||||
kv_idx = torch.arange(seq_len, device=device)[None, :]
|
||||
left = (int(sliding_window) + 1) // 2
|
||||
right = int(sliding_window) // 2 + 1
|
||||
distance = q_idx - kv_idx
|
||||
local = ((distance >= 0) & (distance < left)) | ((distance < 0) & (-distance < right))
|
||||
allowed = allowed & local[None, None, :, :]
|
||||
mask = torch.zeros((batch_size, 1, seq_len, seq_len), device=device, dtype=dtype)
|
||||
mask.masked_fill_(~allowed, torch.finfo(dtype).min)
|
||||
return mask
|
||||
|
||||
|
||||
class _SelfAttention(nn.Module):
|
||||
def __init__(self, config: Any) -> None:
|
||||
super().__init__()
|
||||
tp_size = get_tensor_model_parallel_world_size()
|
||||
if config.num_attention_heads % tp_size != 0:
|
||||
raise ValueError("T5Gemma2 attention heads must be divisible by tensor parallel size")
|
||||
self.layer_type = config.layer_type
|
||||
self.head_dim = int(config.head_dim)
|
||||
self.num_heads = int(config.num_attention_heads) // tp_size
|
||||
self.num_kv_heads = max(1, int(config.num_key_value_heads) // tp_size)
|
||||
self.num_key_value_groups = self.num_heads // self.num_kv_heads
|
||||
self.scaling = float(config.query_pre_attn_scalar) ** -0.5
|
||||
self.qkv_proj = QKVParallelLinear(
|
||||
hidden_size=config.hidden_size,
|
||||
head_size=self.head_dim,
|
||||
total_num_heads=config.num_attention_heads,
|
||||
total_num_kv_heads=config.num_key_value_heads,
|
||||
bias=config.attention_bias,
|
||||
)
|
||||
self.o_proj = RowParallelLinear(
|
||||
input_size=config.num_attention_heads * self.head_dim,
|
||||
output_size=config.hidden_size,
|
||||
bias=config.attention_bias,
|
||||
input_is_parallel=True,
|
||||
)
|
||||
self.q_norm = _RMSNorm(self.head_dim, config.rms_norm_eps)
|
||||
self.k_norm = _RMSNorm(self.head_dim, config.rms_norm_eps)
|
||||
self.sliding_window = config.sliding_window if self.layer_type == "sliding_attention" else None
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
||||
attention_mask: torch.Tensor | None,
|
||||
) -> torch.Tensor:
|
||||
qkv, _ = self.qkv_proj(hidden_states)
|
||||
q_size = self.num_heads * self.head_dim
|
||||
kv_size = self.num_kv_heads * self.head_dim
|
||||
query, key, value = qkv.split((q_size, kv_size, kv_size), dim=-1)
|
||||
shape = (*hidden_states.shape[:-1], -1, self.head_dim)
|
||||
query = self.q_norm(query.view(shape).transpose(1, 2))
|
||||
key = self.k_norm(key.view(shape).transpose(1, 2))
|
||||
value = value.view(shape).transpose(1, 2)
|
||||
query, key = _apply_rotary(query, key, *position_embeddings)
|
||||
key = _repeat_kv(key, self.num_key_value_groups)
|
||||
value = _repeat_kv(value, self.num_key_value_groups)
|
||||
# SDPA scales by head_dim**-0.5; adjust Q to T5Gemma2's scalar.
|
||||
query = query * (self.scaling / (self.head_dim**-0.5))
|
||||
output = F.scaled_dot_product_attention(
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
attn_mask=attention_mask,
|
||||
dropout_p=0.0,
|
||||
)
|
||||
output = output.transpose(1, 2).contiguous().reshape(*hidden_states.shape[:-1], -1)
|
||||
output, _ = self.o_proj(output)
|
||||
return output
|
||||
|
||||
|
||||
class _MLP(nn.Module):
|
||||
def __init__(self, config: Any) -> None:
|
||||
super().__init__()
|
||||
self.gate_up_proj = MergedColumnParallelLinear(
|
||||
input_size=config.hidden_size,
|
||||
output_sizes=[config.intermediate_size, config.intermediate_size],
|
||||
bias=False,
|
||||
)
|
||||
self.down_proj = RowParallelLinear(
|
||||
input_size=config.intermediate_size,
|
||||
output_size=config.hidden_size,
|
||||
bias=False,
|
||||
input_is_parallel=True,
|
||||
)
|
||||
self.act_fn = get_act_fn(config.hidden_activation)
|
||||
self.dropout = nn.Dropout(float(config.dropout_rate))
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
gate_up, _ = self.gate_up_proj(hidden_states)
|
||||
gate, up = gate_up.chunk(2, dim=-1)
|
||||
output, _ = self.down_proj(self.dropout(self.act_fn(gate) * up))
|
||||
return output
|
||||
|
||||
|
||||
class _EncoderLayer(nn.Module):
|
||||
def __init__(self, config: Any, layer_idx: int) -> None:
|
||||
super().__init__()
|
||||
layer_config = type("LayerConfig", (), dict(vars(config)))()
|
||||
layer_config.layer_type = config.layer_types[layer_idx]
|
||||
self.attention_type = layer_config.layer_type
|
||||
self.pre_self_attn_layernorm = _RMSNorm(config.hidden_size, config.rms_norm_eps)
|
||||
self.self_attn = _SelfAttention(layer_config)
|
||||
self.post_self_attn_layernorm = _RMSNorm(config.hidden_size, config.rms_norm_eps)
|
||||
self.pre_feedforward_layernorm = _RMSNorm(config.hidden_size, config.rms_norm_eps)
|
||||
self.mlp = _MLP(config)
|
||||
self.post_feedforward_layernorm = _RMSNorm(config.hidden_size, config.rms_norm_eps)
|
||||
self.dropout = nn.Dropout(float(config.dropout_rate))
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
||||
attention_mask: torch.Tensor | None,
|
||||
) -> torch.Tensor:
|
||||
residual = hidden_states
|
||||
hidden_states = self.pre_self_attn_layernorm(hidden_states)
|
||||
hidden_states = self.self_attn(hidden_states, position_embeddings, attention_mask)
|
||||
hidden_states = residual + self.dropout(self.post_self_attn_layernorm(hidden_states))
|
||||
residual = hidden_states
|
||||
hidden_states = self.pre_feedforward_layernorm(hidden_states)
|
||||
hidden_states = self.mlp(hidden_states)
|
||||
hidden_states = residual + self.dropout(self.post_feedforward_layernorm(hidden_states))
|
||||
return hidden_states
|
||||
|
||||
|
||||
class BreezeTTS2TextEncoder(nn.Module):
|
||||
"""Frozen T5Gemma2 encoder returning ``(B, S, hidden_size)`` states."""
|
||||
|
||||
def __init__(self, config: Any) -> None:
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.embed_tokens = VocabParallelEmbedding(config.vocab_size, config.hidden_size)
|
||||
self.embed_scale = float(config.hidden_size**0.5)
|
||||
self.eoi_token_index = int(getattr(config, "eoi_token_index", 256000))
|
||||
# T5Gemma2 stores this learned replacement vector under the input
|
||||
# embedding module (``embed_tokens.eoi_embedding``), so keep the same
|
||||
# parameter path for checkpoint loading and tied-weight inspection.
|
||||
self.embed_tokens.eoi_embedding = nn.Parameter(torch.zeros(config.hidden_size))
|
||||
self.layers = nn.ModuleList([_EncoderLayer(config, i) for i in range(config.num_hidden_layers)])
|
||||
self.norm = _RMSNorm(config.hidden_size, config.rms_norm_eps)
|
||||
self.rotary_emb = _RotaryEmbedding(config)
|
||||
self.dropout = nn.Dropout(float(config.dropout_rate))
|
||||
|
||||
@property
|
||||
def dtype(self) -> torch.dtype:
|
||||
return next(self.parameters()).dtype
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.Tensor,
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
if input_ids.ndim != 2:
|
||||
raise ValueError(f"Breeze text encoder expects 2D input_ids, got {tuple(input_ids.shape)}")
|
||||
if attention_mask is not None and attention_mask.shape != input_ids.shape:
|
||||
raise ValueError(
|
||||
"Breeze text encoder attention_mask must match input_ids: "
|
||||
f"{tuple(attention_mask.shape)} != {tuple(input_ids.shape)}"
|
||||
)
|
||||
hidden_states = self.embed_tokens(input_ids) * self.embed_scale
|
||||
eoi_mask = input_ids == self.eoi_token_index
|
||||
if bool(eoi_mask.any()):
|
||||
hidden_states = torch.where(
|
||||
eoi_mask.unsqueeze(-1),
|
||||
self.embed_tokens.eoi_embedding.to(dtype=hidden_states.dtype),
|
||||
hidden_states,
|
||||
)
|
||||
hidden_states = self.dropout(hidden_states)
|
||||
positions = torch.arange(input_ids.shape[1], device=input_ids.device, dtype=torch.long).unsqueeze(0)
|
||||
position_embeddings = {
|
||||
layer_type: self.rotary_emb(hidden_states, positions, layer_type)
|
||||
for layer_type in set(self.config.layer_types)
|
||||
}
|
||||
masks = {
|
||||
layer_type: _attention_mask(
|
||||
attention_mask,
|
||||
batch_size=input_ids.shape[0],
|
||||
seq_len=input_ids.shape[1],
|
||||
layer_type=layer_type,
|
||||
sliding_window=self.config.sliding_window,
|
||||
dtype=hidden_states.dtype,
|
||||
device=input_ids.device,
|
||||
)
|
||||
for layer_type in set(self.config.layer_types)
|
||||
}
|
||||
for layer in self.layers:
|
||||
hidden_states = layer(
|
||||
hidden_states,
|
||||
position_embeddings[layer.attention_type],
|
||||
masks[layer.attention_type],
|
||||
)
|
||||
return self.dropout(self.norm(hidden_states))
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
stacked_params_mapping = (
|
||||
("qkv_proj", "q_proj", "q"),
|
||||
("qkv_proj", "k_proj", "k"),
|
||||
("qkv_proj", "v_proj", "v"),
|
||||
("gate_up_proj", "gate_proj", 0),
|
||||
("gate_up_proj", "up_proj", 1),
|
||||
)
|
||||
params = dict(self.named_parameters())
|
||||
loaded: set[str] = set()
|
||||
for name, tensor in weights:
|
||||
target = name
|
||||
shard_id: str | int | None = None
|
||||
for packed_name, source_name, source_id in stacked_params_mapping:
|
||||
marker = f".{source_name}."
|
||||
if marker in name:
|
||||
target = name.replace(marker, f".{packed_name}.")
|
||||
shard_id = source_id
|
||||
break
|
||||
parameter = params.get(target)
|
||||
if parameter is None:
|
||||
continue
|
||||
loader = getattr(parameter, "weight_loader", default_weight_loader)
|
||||
if shard_id is None:
|
||||
loader(parameter, tensor)
|
||||
else:
|
||||
loader(parameter, tensor, shard_id)
|
||||
loaded.add(target)
|
||||
return loaded
|
||||
|
||||
|
||||
__all__ = ["BreezeTTS2TextEncoder"]
|
||||
@@ -1,21 +1,12 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Synchronous Breeze-TTS-2 pipeline: talker -> Mimi codec."""
|
||||
|
||||
from vllm_omni.config.stage_config import (
|
||||
PipelineConfig,
|
||||
StageExecutionType,
|
||||
StagePipelineConfig,
|
||||
)
|
||||
|
||||
_PROC = "vllm_omni.model_executor.stage_input_processors.breeze_tts_2"
|
||||
from vllm_omni.config.stage_config import PipelineConfig, StageExecutionType, StagePipelineConfig
|
||||
|
||||
BREEZE_TTS_2_PIPELINE = PipelineConfig(
|
||||
model_type="breeze",
|
||||
default_deploy_config_name="breeze_tts_2.yaml",
|
||||
model_arch="BreezeForConditionalGeneration",
|
||||
hf_architectures=("BreezeForConditionalGeneration",),
|
||||
default_deploy_config_name="breeze_tts_2.yaml",
|
||||
stages=(
|
||||
StagePipelineConfig(
|
||||
stage_id=0,
|
||||
@@ -24,34 +15,24 @@ BREEZE_TTS_2_PIPELINE = PipelineConfig(
|
||||
input_sources=(),
|
||||
owns_tokenizer=True,
|
||||
engine_output_type="latent",
|
||||
async_chunk_process_next_stage_input_func=f"{_PROC}.talker2codec_async_chunk",
|
||||
custom_process_next_stage_input_func=f"{_PROC}.talker2codec_full_payload",
|
||||
sampling_constraints={
|
||||
"detokenize": False,
|
||||
# Text EOS 1 is a valid codec token; only the backbone's
|
||||
# explicit codec EOS below may terminate audio generation.
|
||||
"ignore_eos": True,
|
||||
# The talker has already selected the emitted frame's token;
|
||||
# min_tokens must not mask that token in the sampler.
|
||||
"min_tokens": 0,
|
||||
"stop_token_ids": [2051],
|
||||
},
|
||||
scheduler_cls="vllm_omni.core.sched.omni_cfg_ar_scheduler.OmniCFGARScheduler",
|
||||
prompt_expand_func="vllm_omni.model_executor.stage_input_processors.breeze_tts_2.expand_cfg_prompts",
|
||||
async_chunk_process_next_stage_input_func=(
|
||||
"vllm_omni.model_executor.stage_input_processors.breeze_tts_2.talker2code2wav_async_chunk"
|
||||
),
|
||||
sampling_constraints={"detokenize": False, "stop_token_ids": [2051], "ignore_eos": True, "min_tokens": 0},
|
||||
),
|
||||
StagePipelineConfig(
|
||||
stage_id=1,
|
||||
model_stage="breeze_tts_2_codec",
|
||||
model_arch="BreezeCode2Wav",
|
||||
execution_type=StageExecutionType.LLM_GENERATION,
|
||||
input_sources=(0,),
|
||||
final_output=True,
|
||||
final_output_type="audio",
|
||||
engine_output_type="audio",
|
||||
model_arch="BreezeTTS2MimiCodec",
|
||||
sync_process_input_func=f"{_PROC}.talker2codec",
|
||||
sampling_constraints={"detokenize": True},
|
||||
requires_full_payload_input=True,
|
||||
retains_state_across_chunks=True,
|
||||
sampling_constraints={"detokenize": True},
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
__all__ = ["BREEZE_TTS_2_PIPELINE"]
|
||||
@@ -0,0 +1,95 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Breeze's instruction and reference-audio templates for both public APIs."""
|
||||
|
||||
import math
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from transformers import PreTrainedTokenizerBase
|
||||
from vllm.inputs import TokensPrompt, tokens_input
|
||||
from vllm.multimodal.audio import AudioResampler
|
||||
|
||||
DEFAULT_INSTRUCTION = "Speak clearly and naturally."
|
||||
SAMPLE_RATE = 24000
|
||||
ENCODE_DOWNSAMPLE_RATE = 1920
|
||||
CFG_UNCOND_SUFFIX = "__cfg_uncond"
|
||||
|
||||
|
||||
def build_breeze_prompt(
|
||||
tokenizer: PreTrainedTokenizerBase,
|
||||
text: str,
|
||||
instructions: str = DEFAULT_INSTRUCTION,
|
||||
*,
|
||||
speaker: str = "S0",
|
||||
ref_audio: tuple[np.ndarray, int] | None = None,
|
||||
ref_text: str | None = None,
|
||||
guidance_scale: float = 1.0,
|
||||
temperature: float = 0.9,
|
||||
top_k: int = 50,
|
||||
top_p: float = 1.0,
|
||||
repetition_penalty: float = 1.1,
|
||||
) -> TokensPrompt:
|
||||
if not text.strip():
|
||||
raise ValueError("Breeze input text cannot be empty")
|
||||
if not math.isfinite(guidance_scale) or guidance_scale <= 0:
|
||||
raise ValueError("Breeze guidance_scale must be finite and positive")
|
||||
if top_k == -1:
|
||||
top_k = 0
|
||||
if (
|
||||
not all(math.isfinite(value) for value in (temperature, top_p, repetition_penalty))
|
||||
or temperature < 0
|
||||
or top_k < 0
|
||||
or not 0 < top_p <= 1
|
||||
or repetition_penalty <= 0
|
||||
):
|
||||
raise ValueError("Invalid Breeze sampling parameters")
|
||||
if (ref_audio is None) != (ref_text is None):
|
||||
raise ValueError("Breeze voice cloning requires both ref_audio and ref_text")
|
||||
speaker_tag = speaker if speaker.startswith("[") and speaker.endswith("]") else f"[{speaker}]"
|
||||
target = tokenizer.encode(f"{speaker_tag}<ins_bos>{instructions}<ins_eos>{text}", add_special_tokens=True)
|
||||
conditioning: dict[str, Any] = {"target_ids": target, "guidance_scale": guidance_scale, "role": "cond"}
|
||||
prefix_length = 0
|
||||
if ref_audio is not None:
|
||||
if not ref_text or not ref_text.strip():
|
||||
raise ValueError("Breeze reference transcript cannot be empty")
|
||||
waveform, sample_rate = ref_audio
|
||||
waveform = np.asarray(waveform, dtype=np.float32)
|
||||
if waveform.ndim == 2:
|
||||
# Public waveform input follows soundfile: (samples, channels).
|
||||
waveform = waveform.mean(axis=1)
|
||||
if waveform.ndim != 1 or not waveform.size or not np.isfinite(waveform).all() or sample_rate <= 0:
|
||||
raise ValueError("Breeze reference audio must contain finite samples at a positive sample rate")
|
||||
if sample_rate != SAMPLE_RATE:
|
||||
# Match the released tokenizer's librosa/soxr_hq resampling,
|
||||
# including ceil-length handling for non-integral rate ratios.
|
||||
length = math.ceil(waveform.size * SAMPLE_RATE / sample_rate)
|
||||
waveform = AudioResampler(target_sr=SAMPLE_RATE, method="soxr").resample(waveform, orig_sr=sample_rate)
|
||||
waveform = np.pad(waveform, (0, max(0, length - waveform.size)))[:length]
|
||||
reference_ids = tokenizer.encode(f"{speaker_tag}{ref_text}", add_special_tokens=True)
|
||||
frames = math.ceil(waveform.size / ENCODE_DOWNSAMPLE_RATE)
|
||||
conditioning.update(
|
||||
reference_ids=reference_ids,
|
||||
reference_frames=frames,
|
||||
)
|
||||
prefix_length = len(reference_ids) + frames + 1
|
||||
if guidance_scale != 1.0:
|
||||
conditioning["negative_ids"] = tokenizer.encode(f"{speaker_tag}{text}", add_special_tokens=True)
|
||||
prompt = tokens_input(prompt_token_ids=[0] * (prefix_length + len(target)))
|
||||
prompt["additional_information"] = {
|
||||
"breeze_prompt": conditioning,
|
||||
"breeze_sampling": {
|
||||
"temperature": temperature,
|
||||
"top_k": top_k,
|
||||
"top_p": top_p,
|
||||
"repetition_penalty": repetition_penalty,
|
||||
},
|
||||
}
|
||||
if ref_audio is not None:
|
||||
# Tensor payloads belong at the transport root (or in a declared
|
||||
# tensor namespace), rather than inside JSON-valued model metadata.
|
||||
prompt["additional_information"]["reference_waveform"] = torch.from_numpy(np.ascontiguousarray(waveform))
|
||||
if guidance_scale != 1.0:
|
||||
prompt["additional_information"]["cfg_group"] = {"role": "cond", "uncond_suffix": CFG_UNCOND_SUFFIX}
|
||||
return prompt
|
||||
@@ -1,336 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Breeze-TTS-2 request-to-prompt conversion.
|
||||
|
||||
This module is intentionally limited to request preparation. It creates the
|
||||
real prompt token ids needed by the scheduler and stores the text/audio masks
|
||||
and reference codes in ``additional_information``. The stage-0 model later
|
||||
turns those values into embeddings; this keeps tokenization independent from
|
||||
the Qwen3/text-encoder implementation and avoids changing sequence length in
|
||||
the model ``preprocess`` hook.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from transformers import AutoTokenizer
|
||||
|
||||
from vllm_omni.inputs.data import OmniTokensPrompt
|
||||
|
||||
from .audio_tokenizer import BreezeReferenceAudioTokenizer
|
||||
|
||||
AUDIO_TAG = "<|AUDIO|>"
|
||||
AUDIO_EOS = "<|audio_eos|>"
|
||||
INSTRUCTION_BOS = "<ins_bos>"
|
||||
INSTRUCTION_EOS = "<ins_eos>"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _TextSegment:
|
||||
text: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _AudioSegment:
|
||||
source: Any
|
||||
sample_rate: int | None
|
||||
|
||||
|
||||
class BreezeTTS2PromptBuilder:
|
||||
"""Build one Breeze prompt without depending on model modules.
|
||||
|
||||
``tokenizer`` is a normal HuggingFace tokenizer. ``reference_audio_encoder``
|
||||
is injected so the builder can use the serving worker's cached audio
|
||||
encoder and never reload it per request. The returned ``OmniTokensPrompt``
|
||||
contains scheduler token ids and compact CPU metadata for stage-0
|
||||
``preprocess``.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer: Any,
|
||||
config: Any,
|
||||
reference_audio_encoder: BreezeReferenceAudioTokenizer | None = None,
|
||||
) -> None:
|
||||
self.tokenizer = tokenizer
|
||||
self.audio_encoder = reference_audio_encoder
|
||||
self.audio_token_id = int(config.audio_token_id)
|
||||
self.audio_eos_token_id = int(config.audio_eos_token_id)
|
||||
# The Breeze tokenizer vocabulary is larger than the Qwen3 backbone
|
||||
# vocabulary. ``prompt_token_ids`` are scheduler bookkeeping only, so
|
||||
# keep them in the backbone vocabulary and retain the real Breeze ids
|
||||
# in ``additional_information['prompt_ids']`` for the talker.
|
||||
self.scheduler_token_id = int(config.pad_token_id)
|
||||
scheduler_vocab_size = int(config.backbone_config.vocab_size)
|
||||
if self.scheduler_token_id >= scheduler_vocab_size:
|
||||
raise ValueError(
|
||||
"prompt_pad_token_id must be smaller than the backbone vocabulary: "
|
||||
f"{self.scheduler_token_id} >= {scheduler_vocab_size}"
|
||||
)
|
||||
self.num_codebooks = int(config.num_codebooks)
|
||||
codec_config = getattr(config, "codec_config", None)
|
||||
if isinstance(codec_config, Mapping):
|
||||
self.codebook_size = int(codec_config.get("codebook_size", 2048))
|
||||
elif codec_config is not None:
|
||||
self.codebook_size = int(getattr(codec_config, "codebook_size", 2048))
|
||||
else:
|
||||
# ``codec_config`` is optional in BreezeTTS2Config; a minimal
|
||||
# checkpoint may omit it. Breeze's codec uses 2048-entry
|
||||
# codebooks, the same fallback the talker and codec stages apply.
|
||||
self.codebook_size = 2048
|
||||
if self.num_codebooks <= 0 or self.codebook_size <= 0:
|
||||
raise ValueError("num_codebooks and codec codebook_size must be positive")
|
||||
self._validate_audio_special_tokens()
|
||||
|
||||
@classmethod
|
||||
def from_pretrained(
|
||||
cls,
|
||||
model_path: str,
|
||||
config: Any,
|
||||
*,
|
||||
reference_audio_encoder: BreezeReferenceAudioTokenizer | None = None,
|
||||
tokenizer_kwargs: Mapping[str, Any] | None = None,
|
||||
) -> BreezeTTS2PromptBuilder:
|
||||
"""Load the text tokenizer once and construct a reusable builder."""
|
||||
kwargs = dict(tokenizer_kwargs or {})
|
||||
kwargs.setdefault("use_fast", True)
|
||||
kwargs.setdefault("trust_remote_code", True)
|
||||
tokenizer = AutoTokenizer.from_pretrained(model_path, **kwargs)
|
||||
return cls(tokenizer, config, reference_audio_encoder)
|
||||
|
||||
def build(
|
||||
self,
|
||||
request: Mapping[str, Any],
|
||||
*,
|
||||
template: str | None = None,
|
||||
) -> OmniTokensPrompt:
|
||||
"""Convert one request to a vLLM-Omni token prompt.
|
||||
|
||||
Supported templates are ``tts_plain``, ``tts_instruction``,
|
||||
``ref_clone_tata`` and ``ref_edit_tata``. When omitted, the template
|
||||
is inferred from the presence of instruction/reference fields.
|
||||
"""
|
||||
template_name = template or request.get("template")
|
||||
if not isinstance(template_name, str) or not template_name:
|
||||
template_name = _infer_template(request)
|
||||
segments = self._build_segments(template_name, request)
|
||||
|
||||
# Breeze's reference implementation first adds tokenizer special
|
||||
# tokens to every text segment, decodes those segments back to text,
|
||||
# inserts the audio placeholders, and tokenizes the complete string
|
||||
# once. This matters at segment boundaries: tokenizing each raw text
|
||||
# fragment independently can produce different boundary tokens.
|
||||
rendered_segments: list[tuple[str, bool, int]] = []
|
||||
reference_codes: list[torch.Tensor] = []
|
||||
|
||||
for segment in segments:
|
||||
if isinstance(segment, _TextSegment):
|
||||
ids = self._encode_one_text(segment.text, add_special_tokens=True)
|
||||
if not ids:
|
||||
raise ValueError("Breeze text tokenizer returned an empty segment")
|
||||
rendered = str(self.tokenizer.decode(ids, skip_special_tokens=False))
|
||||
rendered_segments.append((rendered, True, 0))
|
||||
continue
|
||||
|
||||
codes = self._resolve_reference_codes(segment)
|
||||
reference_codes.append(codes)
|
||||
audio_text = AUDIO_TAG * int(codes.shape[0]) + AUDIO_EOS
|
||||
rendered_segments.append((audio_text, False, int(codes.shape[0]) + 1))
|
||||
|
||||
prompt_ids: list[int] = []
|
||||
text_mask: list[bool] = []
|
||||
text_lengths: list[int] = []
|
||||
rendered_prompt = "".join(item[0] for item in rendered_segments)
|
||||
prompt_ids = self._encode_one_text(rendered_prompt, add_special_tokens=False)
|
||||
offset = 0
|
||||
for rendered, is_text, expected_len in rendered_segments:
|
||||
segment_ids = self._encode_one_text(rendered, add_special_tokens=False)
|
||||
actual_len = len(segment_ids)
|
||||
if not is_text and actual_len != expected_len:
|
||||
raise ValueError(
|
||||
"Breeze audio placeholder token length changed after rendering: "
|
||||
f"expected {expected_len}, got {actual_len}"
|
||||
)
|
||||
if not is_text and segment_ids != [
|
||||
*([self.audio_token_id] * (expected_len - 1)),
|
||||
self.audio_eos_token_id,
|
||||
]:
|
||||
raise ValueError("Breeze tokenizer did not preserve audio placeholder ids")
|
||||
text_mask.extend([is_text] * actual_len)
|
||||
if is_text:
|
||||
text_lengths.append(actual_len)
|
||||
offset += actual_len
|
||||
if offset != len(prompt_ids) or len(text_mask) != len(prompt_ids):
|
||||
raise RuntimeError("Breeze rendered prompt length accounting error")
|
||||
if not prompt_ids:
|
||||
raise ValueError("Breeze prompt is empty")
|
||||
|
||||
input_values = torch.cat(reference_codes, dim=0) if reference_codes else None
|
||||
if input_values is not None and int(input_values.shape[0]) != prompt_ids.count(self.audio_token_id):
|
||||
raise RuntimeError("reference code count does not match audio placeholder count")
|
||||
|
||||
additional_information: dict[str, Any] = {
|
||||
# The model runner may invoke preprocess on a chunk of a long
|
||||
# prompt. Keep one compact CPU copy so the talker can reconstruct
|
||||
# the full embedding buffer before slicing that chunk.
|
||||
"prompt_ids": torch.tensor(prompt_ids, dtype=torch.long),
|
||||
"attention_mask": torch.ones(len(prompt_ids), dtype=torch.bool),
|
||||
"text_ids_mask": torch.tensor(text_mask, dtype=torch.bool),
|
||||
"text_ids_len": torch.tensor(text_lengths, dtype=torch.long),
|
||||
"template": template_name,
|
||||
}
|
||||
if input_values is not None:
|
||||
# ``input_values`` is the name used by the upstream Breeze model.
|
||||
# Keep the tensor unbatched here: Omni transports one request at a
|
||||
# time and the talker adds the batch dimension after collation.
|
||||
additional_information["input_values"] = input_values
|
||||
additional_information["ref_code_len"] = int(input_values.shape[0])
|
||||
|
||||
if self.scheduler_token_id < 0:
|
||||
raise ValueError("prompt_pad_token_id must be non-negative")
|
||||
|
||||
return OmniTokensPrompt(
|
||||
# Never expose Breeze's high text/audio ids to the Qwen3 scheduler
|
||||
# or its token-range validation. The real ids remain available in
|
||||
# additional_information and are consumed by ``preprocess``.
|
||||
prompt_token_ids=[self.scheduler_token_id] * len(prompt_ids),
|
||||
additional_information=additional_information,
|
||||
)
|
||||
|
||||
def _build_segments(self, template: str, request: Mapping[str, Any]) -> list[_TextSegment | _AudioSegment]:
|
||||
speaker = _speaker_prefix(request.get("speaker", "S0"))
|
||||
text = _required_text(request, "text")
|
||||
instruction = request.get("instruction")
|
||||
ref_text = request.get("ref_text")
|
||||
|
||||
if template == "tts_plain":
|
||||
return [_TextSegment(f"{speaker}{text}")]
|
||||
if template == "tts_instruction":
|
||||
if not isinstance(instruction, str) or not instruction:
|
||||
raise ValueError("tts_instruction requires a non-empty instruction")
|
||||
return [_TextSegment(f"{speaker}{INSTRUCTION_BOS}{instruction}{INSTRUCTION_EOS}{text}")]
|
||||
if template in ("ref_clone_tata", "ref_edit_tata"):
|
||||
if not isinstance(ref_text, str) or not ref_text:
|
||||
raise ValueError(f"{template} requires a non-empty ref_text")
|
||||
audio = self._audio_segment(request)
|
||||
if template == "ref_clone_tata":
|
||||
return [_TextSegment(f"{speaker}{ref_text}"), audio, _TextSegment(f"{speaker}{text}")]
|
||||
if not isinstance(instruction, str) or not instruction:
|
||||
raise ValueError("ref_edit_tata requires a non-empty instruction")
|
||||
return [
|
||||
_TextSegment(f"{speaker}{ref_text}"),
|
||||
audio,
|
||||
_TextSegment(f"{speaker}{INSTRUCTION_BOS}{instruction}{INSTRUCTION_EOS}{text}"),
|
||||
]
|
||||
raise ValueError(
|
||||
f"unknown Breeze template {template!r}; expected tts_plain, tts_instruction, "
|
||||
"ref_clone_tata or ref_edit_tata"
|
||||
)
|
||||
|
||||
def _audio_segment(self, request: Mapping[str, Any]) -> _AudioSegment:
|
||||
source = request.get("ref_audio")
|
||||
if source is None:
|
||||
source = request.get("ref_audio_codes")
|
||||
if source is None:
|
||||
raw_codes = request.get("codes")
|
||||
source = raw_codes.get("ref") if isinstance(raw_codes, Mapping) else None
|
||||
if source is None:
|
||||
raise ValueError("reference template requires ref_audio or ref_audio_codes")
|
||||
sample_rate = request.get("ref_audio_sample_rate")
|
||||
return _AudioSegment(source, int(sample_rate) if sample_rate is not None else None)
|
||||
|
||||
def _resolve_reference_codes(self, segment: _AudioSegment) -> torch.Tensor:
|
||||
source = segment.source
|
||||
if _looks_like_codes(source, self.num_codebooks):
|
||||
codes = torch.as_tensor(source)
|
||||
return _normalize_codes(codes, self.num_codebooks, self.codebook_size)
|
||||
if self.audio_encoder is None:
|
||||
raise RuntimeError("reference audio was provided but no reference_audio_encoder is configured")
|
||||
codes = self.audio_encoder.encode(source, segment.sample_rate)
|
||||
return _normalize_codes(codes, self.num_codebooks, self.codebook_size)
|
||||
|
||||
def _encode_one_text(self, text: str, *, add_special_tokens: bool) -> list[int]:
|
||||
encoded = self.tokenizer(text, add_special_tokens=add_special_tokens, padding=False)
|
||||
ids = encoded["input_ids"] if isinstance(encoded, Mapping) else encoded.input_ids
|
||||
if isinstance(ids, torch.Tensor):
|
||||
ids = ids.tolist()
|
||||
return _as_int_list(ids)
|
||||
|
||||
def _validate_audio_special_tokens(self) -> None:
|
||||
convert = self.tokenizer.convert_tokens_to_ids
|
||||
for token, expected in ((AUDIO_TAG, self.audio_token_id), (AUDIO_EOS, self.audio_eos_token_id)):
|
||||
actual = convert(token)
|
||||
unk = getattr(self.tokenizer, "unk_token_id", None)
|
||||
if actual is None or (unk is not None and actual == unk) or int(actual) != expected:
|
||||
raise ValueError(f"tokenizer id for {token!r} is {actual}, expected config value {expected}")
|
||||
|
||||
|
||||
def _infer_template(request: Mapping[str, Any]) -> str:
|
||||
has_ref = (
|
||||
request.get("ref_audio") is not None
|
||||
or request.get("ref_audio_codes") is not None
|
||||
or bool(request.get("ref_text"))
|
||||
)
|
||||
has_instruction = bool(request.get("instruction"))
|
||||
if has_ref and has_instruction:
|
||||
return "ref_edit_tata"
|
||||
if has_ref:
|
||||
return "ref_clone_tata"
|
||||
return "tts_instruction" if has_instruction else "tts_plain"
|
||||
|
||||
|
||||
def _required_text(request: Mapping[str, Any], key: str) -> str:
|
||||
value = request.get(key)
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
raise ValueError(f"Breeze request requires non-empty {key}")
|
||||
return value
|
||||
|
||||
|
||||
def _speaker_prefix(value: Any) -> str:
|
||||
if value in (None, ""):
|
||||
return ""
|
||||
value = str(value)
|
||||
return value if value.startswith("[") and value.endswith("]") else f"[{value}]"
|
||||
|
||||
|
||||
def _as_int_list(value: Any) -> list[int]:
|
||||
if isinstance(value, torch.Tensor):
|
||||
value = value.tolist()
|
||||
elif isinstance(value, np.ndarray):
|
||||
value = value.tolist()
|
||||
if not isinstance(value, list):
|
||||
raise ValueError("tokenizer input_ids must be a list")
|
||||
if value and isinstance(value[0], (list, tuple, np.ndarray, torch.Tensor)):
|
||||
if len(value) != 1:
|
||||
raise ValueError("tokenizer input_ids contains multiple sequences")
|
||||
return _as_int_list(value[0])
|
||||
return [int(item) for item in value]
|
||||
|
||||
|
||||
def _looks_like_codes(value: Any, num_codebooks: int) -> bool:
|
||||
if isinstance(value, (torch.Tensor, np.ndarray)):
|
||||
return value.ndim == 2 and value.shape[-1] == num_codebooks
|
||||
return False
|
||||
|
||||
|
||||
def _normalize_codes(codes: Any, num_codebooks: int, codebook_size: int) -> torch.Tensor:
|
||||
codes = torch.as_tensor(codes)
|
||||
if codes.ndim != 2:
|
||||
raise ValueError(f"reference audio codes must be 2D, got {tuple(codes.shape)}")
|
||||
if codes.shape[0] == 0:
|
||||
raise ValueError("reference audio codes must contain at least one frame")
|
||||
if codes.shape[-1] != num_codebooks:
|
||||
raise ValueError(f"expected {num_codebooks} codebooks, got {tuple(codes.shape)}")
|
||||
codes = codes.to(device="cpu", dtype=torch.long).contiguous()
|
||||
if int(codes.min()) < 0 or int(codes.max()) >= codebook_size:
|
||||
raise ValueError(f"reference code outside [0, {codebook_size})")
|
||||
return codes.to(dtype=torch.int16)
|
||||
|
||||
|
||||
__all__ = ["BreezeTTS2PromptBuilder"]
|
||||
@@ -0,0 +1,165 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""The bundled Qwen3 codec encoder used by Breeze voice cloning."""
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
from transformers.models.mimi.modeling_mimi import MimiConv1d
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.model_executor.model_loader.default_loader import DefaultModelLoader
|
||||
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
|
||||
|
||||
from vllm_omni.model_executor.models.qwen3_tts.tokenizer_12hz.configuration_qwen3_tts_tokenizer_v2 import (
|
||||
Qwen3TTSTokenizerV2Config,
|
||||
)
|
||||
from vllm_omni.model_executor.models.qwen3_tts.tokenizer_12hz.modeling_qwen3_tts_tokenizer_v2 import (
|
||||
Qwen3TTSTokenizerV2Encoder,
|
||||
)
|
||||
|
||||
|
||||
class BreezeReferenceEncoder(nn.Module):
|
||||
def __init__(self, vllm_config: VllmConfig) -> None:
|
||||
super().__init__()
|
||||
config = Qwen3TTSTokenizerV2Config.from_pretrained(
|
||||
vllm_config.model_config.model,
|
||||
subfolder="audio_tokenizer",
|
||||
revision=vllm_config.model_config.revision,
|
||||
)
|
||||
if config.input_sample_rate != 24000 or config.encode_downsample_rate != 1920:
|
||||
raise ValueError("Breeze requires the bundled 24 kHz, 12.5 Hz Qwen3 codec")
|
||||
config.encoder_config._attn_implementation = "sdpa"
|
||||
# The released Breeze runtime encodes references in FP32. Quantizer
|
||||
# boundaries affect speaker conditioning, so preserve that precision.
|
||||
self.encoder = Qwen3TTSTokenizerV2Encoder._from_config(config.encoder_config, dtype=torch.float32).eval()
|
||||
self._convolutions: list[BreezeReferenceConv] = []
|
||||
hop = 1
|
||||
for name, module in list(self.encoder.named_modules()):
|
||||
if isinstance(module, MimiConv1d):
|
||||
hop *= module.conv.stride[0]
|
||||
convolution = BreezeReferenceConv(module, hop)
|
||||
self._convolutions.append(convolution)
|
||||
parent, _, attribute = name.rpartition(".")
|
||||
self.encoder.get_submodule(parent).add_module(attribute, convolution)
|
||||
if hop != config.encode_downsample_rate:
|
||||
raise ValueError("Breeze reference convolution strides do not match the codec frame rate")
|
||||
self.num_quantizers = config.encoder_valid_num_quantizers
|
||||
# Reference convolutions have large temporary workspaces. Compile
|
||||
# without a graph's permanently reserved workspace for every length.
|
||||
self._compiled_encode = torch.compile(
|
||||
self._encode_impl,
|
||||
fullgraph=True,
|
||||
dynamic=True,
|
||||
options={"triton.cudagraphs": False, "epilogue_fusion": False},
|
||||
)
|
||||
|
||||
def forward(self, waveform: torch.Tensor, frames: int) -> torch.Tensor:
|
||||
return self.encode_batch([waveform], [frames])[0]
|
||||
|
||||
def encode_batch(self, waveforms: list[torch.Tensor], frame_counts: list[int]) -> list[torch.Tensor]:
|
||||
device = next(self.encoder.parameters()).device
|
||||
waveform = nn.utils.rnn.pad_sequence(waveforms, batch_first=True)
|
||||
waveform = nn.functional.pad(waveform, (0, -waveform.shape[1] % 1920))
|
||||
waveform_frames = waveform.reshape(len(waveforms), -1, 1920).to(device=device, dtype=torch.float32)
|
||||
lengths = torch.tensor([waveform.numel() for waveform in waveforms], device=device, dtype=torch.long)
|
||||
with torch.backends.cudnn.flags(allow_tf32=False):
|
||||
encoded = self._compiled_encode(waveform_frames, lengths)
|
||||
return [
|
||||
encoded[row, :, :frames].transpose(0, 1).clone(memory_format=torch.contiguous_format)
|
||||
for row, frames in enumerate(frame_counts)
|
||||
]
|
||||
|
||||
def warmup(self, max_batch_size: int) -> None:
|
||||
device = next(self.encoder.parameters()).device
|
||||
with torch.backends.cudnn.flags(allow_tf32=False):
|
||||
for batch in range(1, max_batch_size + 1):
|
||||
waveform_frames = torch.zeros((batch, 32, 1920), device=device, dtype=torch.float32)
|
||||
lengths = torch.full((batch,), 32 * 1920, device=device, dtype=torch.long)
|
||||
# Initialize the codec's normalized codebooks before tracing.
|
||||
self._encode_impl(waveform_frames, lengths)
|
||||
self._compiled_encode(waveform_frames, lengths)
|
||||
torch.accelerator.empty_cache()
|
||||
|
||||
def _encode_impl(self, waveform_frames: torch.Tensor, sample_lengths: torch.Tensor) -> torch.Tensor:
|
||||
# Expose the complete 1920-sample stride product to the compiler.
|
||||
# Nested ceil/mod expressions for arbitrary waveform lengths otherwise
|
||||
# cause expensive symbolic simplification during kernel tiling. Every
|
||||
# convolution below masks the true per-recording boundary, so aligning
|
||||
# the storage to full frames preserves partial final-frame semantics.
|
||||
torch._dynamo.mark_static(waveform_frames, 2)
|
||||
waveform = waveform_frames.flatten(1)
|
||||
# The released Breeze reference encoder uses full causal attention
|
||||
# during offline encoding. Recent Transformers Mimi defaults to a
|
||||
# sliding mask, which changes references longer than ten seconds.
|
||||
# Supply the actual reference mask rather than changing the checkpoint
|
||||
# configuration or relying on a Transformers-version default.
|
||||
for convolution in self._convolutions:
|
||||
convolution.sample_lengths = sample_lengths
|
||||
hidden = self.encoder.encoder(waveform.unsqueeze(1)).transpose(1, 2)
|
||||
length = hidden.shape[1]
|
||||
causal_mask = torch.ones((length, length), device=hidden.device, dtype=torch.bool).tril()[None, None]
|
||||
hidden = self.encoder.encoder_transformer(
|
||||
hidden, attention_mask=causal_mask, use_cache=False, return_dict=True
|
||||
).last_hidden_state
|
||||
hidden = self.encoder.downsample(hidden.transpose(1, 2))
|
||||
return self.encoder.quantizer.encode(hidden, self.num_quantizers).transpose(0, 1)
|
||||
|
||||
def load_weights(self, vllm_config: VllmConfig) -> set[str]:
|
||||
loader = DefaultModelLoader(vllm_config.load_config)
|
||||
source = DefaultModelLoader.Source(
|
||||
model_or_path=vllm_config.model_config.model,
|
||||
revision=vllm_config.model_config.revision,
|
||||
subfolder="audio_tokenizer",
|
||||
)
|
||||
parameters = dict(self.named_parameters())
|
||||
buffers = dict(self.named_buffers())
|
||||
loaded: set[str] = set()
|
||||
for name, value in loader._get_weights_iterator(source):
|
||||
if name.startswith("decoder."):
|
||||
continue
|
||||
if name in parameters:
|
||||
default_weight_loader(parameters[name], value)
|
||||
elif name in buffers:
|
||||
buffers[name].copy_(value)
|
||||
else:
|
||||
raise ValueError(f"Unexpected reference codec weight: {name}")
|
||||
loaded.add(name)
|
||||
required = set(parameters) | {name for name in buffers if ".quantizer." in name}
|
||||
missing = required - loaded
|
||||
if missing:
|
||||
raise ValueError(f"Uninitialized reference codec weights or codebooks: {sorted(missing)}")
|
||||
return loaded
|
||||
|
||||
|
||||
class BreezeReferenceConv(nn.Module):
|
||||
"""Offline Mimi convolution with padding derived from static shape metadata."""
|
||||
|
||||
def __init__(self, source: MimiConv1d, output_hop: int) -> None:
|
||||
super().__init__()
|
||||
if not source.causal or source.pad_mode not in ("constant", "replicate"):
|
||||
raise ValueError("Breeze reference encoding requires causal zero/replicate-padded convolutions")
|
||||
self.conv = source.conv
|
||||
self.pad_mode = source.pad_mode
|
||||
self.stride = self.conv.stride[0]
|
||||
self.padding = (self.conv.kernel_size[0] - 1) * self.conv.dilation[0] + 1 - self.stride
|
||||
self.output_hop = output_hop
|
||||
self.sample_lengths: torch.Tensor | None = None
|
||||
|
||||
def forward(self, hidden: torch.Tensor) -> torch.Tensor:
|
||||
# HF stores these integers in GPU tensors, introducing a device sync
|
||||
# when F.pad converts them back to integers. Shapes determine padding.
|
||||
if self.sample_lengths is None:
|
||||
raise RuntimeError("Reference convolution requires the batch's input lengths")
|
||||
if self.pad_mode == "replicate":
|
||||
# Mimi's final downsampler repeats the actual last encoder state
|
||||
# for a partial frame. Each row has its own boundary in a bucket.
|
||||
input_hop = self.output_hop // self.stride
|
||||
lengths = (self.sample_lengths + input_hop - 1) // input_hop
|
||||
indices = torch.arange(hidden.shape[-1], device=hidden.device)[None, :]
|
||||
indices = torch.minimum(indices, lengths[:, None] - 1)
|
||||
hidden = hidden.gather(2, indices[:, None, :].expand(-1, hidden.shape[1], -1))
|
||||
right = -hidden.shape[-1] % self.stride
|
||||
hidden = nn.functional.pad(hidden, (self.padding, right), mode=self.pad_mode)
|
||||
hidden = self.conv(hidden)
|
||||
lengths = (self.sample_lengths + self.output_hop - 1) // self.output_hop
|
||||
invalid = torch.arange(hidden.shape[-1], device=hidden.device)[None, :] >= lengths[:, None]
|
||||
return hidden.masked_fill(invalid[:, None, :], 0)
|
||||
@@ -0,0 +1,122 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Padded T5Gemma2 prefill graphs with explicit bidirectional masks."""
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import nn
|
||||
from transformers.models.t5gemma2.modeling_t5gemma2 import (
|
||||
T5Gemma2EncoderLayer,
|
||||
T5Gemma2TextEncoder,
|
||||
sliding_window_mask_function,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
|
||||
class BreezeTextEncoderCompiled:
|
||||
"""Compiled prefill layers without retaining large activation graph pools."""
|
||||
|
||||
def __init__(self, encoder: T5Gemma2TextEncoder, projection: nn.Linear) -> None:
|
||||
self.encoder = encoder
|
||||
self.projection = projection
|
||||
self._layer = torch.compile(
|
||||
T5Gemma2EncoderLayer.forward,
|
||||
fullgraph=True,
|
||||
dynamic=True,
|
||||
options={"triton.cudagraphs": False, "epilogue_fusion": False},
|
||||
)
|
||||
|
||||
def run_batch(self, prompts: list[torch.Tensor]) -> list[torch.Tensor]:
|
||||
encoder = self.encoder
|
||||
device = self.projection.weight.device
|
||||
dtype = self.projection.weight.dtype
|
||||
lengths = [prompt.numel() for prompt in prompts]
|
||||
ids = nn.utils.rnn.pad_sequence(prompts, batch_first=True).to(device)
|
||||
positions = torch.arange(ids.shape[1], device=device)[None]
|
||||
invalid = positions >= torch.tensor(lengths, device=device)[:, None]
|
||||
mask = torch.zeros((len(prompts), 1, ids.shape[1], ids.shape[1]), device=device, dtype=dtype)
|
||||
mask.masked_fill_(invalid[:, None, None, :], torch.finfo(dtype).min)
|
||||
mask_function = sliding_window_mask_function(encoder.config.sliding_window, is_causal=False)
|
||||
allowed = mask_function(0, 0, positions[:, :, None], positions[:, None, :])
|
||||
local_mask = mask.masked_fill(~allowed[:, None], torch.finfo(dtype).min)
|
||||
masks = {"full_attention": mask, "sliding_attention": local_mask}
|
||||
embedding = encoder.embed_tokens
|
||||
hidden = F.embedding(ids, embedding.weight) * embedding.embed_scale.to(dtype)
|
||||
hidden = torch.where(
|
||||
(ids == embedding.eoi_token_index).unsqueeze(-1), embedding.eoi_embedding.to(dtype), hidden
|
||||
)
|
||||
position_embeddings = {
|
||||
kind: encoder.rotary_emb(hidden, positions, kind) for kind in set(encoder.config.layer_types)
|
||||
}
|
||||
for layer in encoder.layers:
|
||||
kind = layer.attention_type
|
||||
hidden = self._layer(layer, hidden, position_embeddings[kind], masks[kind], positions)
|
||||
output = self.projection(encoder.norm(hidden))
|
||||
return [output[row, :length].clone() for row, length in enumerate(lengths)]
|
||||
|
||||
def warmup(self, max_batch_size: int) -> None:
|
||||
# Dynamo specializes size-one dimensions; a second batch exercises
|
||||
# the general batch dimension used by paired and reference prompts.
|
||||
for batch in sorted({1, max_batch_size}):
|
||||
self.run_batch([torch.zeros(256, dtype=torch.long) for _ in range(batch)])
|
||||
torch.accelerator.empty_cache()
|
||||
|
||||
|
||||
class BreezeTextEncoderGraph:
|
||||
def __init__(self, encoder: T5Gemma2TextEncoder, projection: nn.Linear, size: int, batch_size: int = 1) -> None:
|
||||
device = projection.weight.device
|
||||
dtype = projection.weight.dtype
|
||||
self.ids = torch.zeros((batch_size, size), device=device, dtype=torch.long)
|
||||
self.positions = torch.arange(size, device=device).unsqueeze(0)
|
||||
self.full_mask = torch.zeros((batch_size, 1, size, size), device=device, dtype=dtype)
|
||||
mask_function = sliding_window_mask_function(encoder.config.sliding_window, is_causal=False)
|
||||
allowed = mask_function(0, 0, self.positions[:, :, None], self.positions[:, None, :])
|
||||
self.local_mask_base = torch.zeros_like(self.full_mask).masked_fill_(~allowed[:, None], torch.finfo(dtype).min)
|
||||
self.local_mask = self.local_mask_base.clone()
|
||||
self.masks = {"full_attention": self.full_mask, "sliding_attention": self.local_mask}
|
||||
for _ in range(3):
|
||||
self._encode(encoder, projection)
|
||||
current_omni_platform.synchronize()
|
||||
self.graph = torch.cuda.CUDAGraph()
|
||||
with torch.cuda.graph(
|
||||
self.graph, pool=current_platform.get_global_graph_pool(), capture_error_mode="thread_local"
|
||||
):
|
||||
self.output = self._encode(encoder, projection)
|
||||
|
||||
def _encode(self, encoder: T5Gemma2TextEncoder, projection: nn.Linear) -> torch.Tensor:
|
||||
embedding = encoder.embed_tokens
|
||||
hidden = F.embedding(self.ids, embedding.weight) * embedding.embed_scale.to(embedding.weight.dtype)
|
||||
# HF's boolean-index assignment materializes a data-dependent index
|
||||
# list. Express the same EOI substitution with a fixed-shape select.
|
||||
hidden = torch.where(
|
||||
(self.ids == embedding.eoi_token_index).unsqueeze(-1),
|
||||
embedding.eoi_embedding.to(hidden.dtype),
|
||||
hidden,
|
||||
)
|
||||
encoded = encoder(inputs_embeds=hidden, attention_mask=self.masks, position_ids=self.positions)
|
||||
return projection(encoded.last_hidden_state)
|
||||
|
||||
def run(self, prompt: torch.Tensor) -> torch.Tensor:
|
||||
return self.run_batch([prompt[0]])[0]
|
||||
|
||||
def run_batch(self, prompts: list[torch.Tensor]) -> list[torch.Tensor]:
|
||||
if len(prompts) != self.ids.shape[0]:
|
||||
raise ValueError("Breeze text batch differs from the captured graph size")
|
||||
lengths = [prompt.numel() for prompt in prompts]
|
||||
if not all(0 < length <= self.ids.shape[1] for length in lengths):
|
||||
raise ValueError("Breeze text segment does not fit its graph bucket")
|
||||
self.ids.zero_()
|
||||
for row, (prompt, length) in enumerate(zip(prompts, lengths, strict=True)):
|
||||
self.ids[row, :length].copy_(prompt)
|
||||
invalid = self.positions >= torch.tensor(lengths, device=self.ids.device)[:, None]
|
||||
invalid = invalid[:, None, None, :]
|
||||
self.full_mask.zero_()
|
||||
self.full_mask.masked_fill_(invalid, torch.finfo(self.full_mask.dtype).min)
|
||||
self.local_mask.copy_(self.local_mask_base)
|
||||
self.local_mask.masked_fill_(invalid, torch.finfo(self.local_mask.dtype).min)
|
||||
self.graph.replay()
|
||||
# Subsequent prefills and backbone/depth graphs reuse graph storage.
|
||||
# The runner must receive independently owned prompt embeddings.
|
||||
return [self.output[row, :length].clone() for row, length in enumerate(lengths)]
|
||||
@@ -58,6 +58,8 @@ class Qwen3TTSCode2Wav(nn.Module):
|
||||
via the SpeechTokenizer decoder directly (bypassing HF wrapper overhead)."""
|
||||
|
||||
input_modalities = "audio"
|
||||
tokenizer_subfolder = "speech_tokenizer"
|
||||
decoder_cudagraph_modes: tuple[str, ...] = ("icl", "xvec")
|
||||
|
||||
# Ask the model runner for the scheduler-side request IDs. Stateful
|
||||
# decoder caches must use the same IDs delivered by on_requests_finished;
|
||||
@@ -105,7 +107,7 @@ class Qwen3TTSCode2Wav(nn.Module):
|
||||
# load_weights().
|
||||
tok_config = Qwen3TTSTokenizerV2Config.from_pretrained(
|
||||
self.model_path,
|
||||
subfolder="speech_tokenizer",
|
||||
subfolder=self.tokenizer_subfolder,
|
||||
)
|
||||
dec_config = tok_config.decoder_config
|
||||
self.decoder = Qwen3TTSTokenizerV2Decoder._from_config(dec_config)
|
||||
@@ -194,6 +196,7 @@ class Qwen3TTSCode2Wav(nn.Module):
|
||||
)
|
||||
|
||||
self.decoder.enable_cudagraph(
|
||||
capture_modes=self.decoder_cudagraph_modes,
|
||||
capture_batch_sizes=decode_cudagraph_batch_sizes,
|
||||
stateless_capture_sizes=decode_cudagraph_capture_sizes,
|
||||
device=device,
|
||||
@@ -566,7 +569,7 @@ class Qwen3TTSCode2Wav(nn.Module):
|
||||
source = DefaultModelLoader.Source(
|
||||
model_or_path=self.model_path,
|
||||
revision=self.vllm_config.model_config.revision,
|
||||
subfolder="speech_tokenizer",
|
||||
subfolder=self.tokenizer_subfolder,
|
||||
)
|
||||
subfolder_weights = model_loader._get_weights_iterator(source)
|
||||
loaded = AutoWeightsLoader(self).load_weights(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
# Copyright 2026 The Alibaba Qwen team.
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""
|
||||
CUDA Graph wrapper for Qwen3TTSTokenizerV2Decoder.
|
||||
|
||||
@@ -45,6 +46,7 @@ class CUDAGraphDecoderWrapper:
|
||||
def __init__(
|
||||
self,
|
||||
decoder: torch.nn.Module,
|
||||
capture_modes: tuple[str, ...] = ("icl", "xvec"),
|
||||
capture_batch_sizes: list[int] | None = None,
|
||||
stateless_capture_sizes: list[int] | None = None,
|
||||
num_quantizers: int = 8,
|
||||
@@ -57,6 +59,9 @@ class CUDAGraphDecoderWrapper:
|
||||
decode_left_context: int = 25,
|
||||
):
|
||||
self.decoder = decoder
|
||||
if not capture_modes or set(capture_modes) - {"icl", "xvec"}:
|
||||
raise ValueError("capture_modes must contain icl and/or xvec")
|
||||
self.capture_modes = capture_modes
|
||||
self.capture_batch_sizes = sorted(set(capture_batch_sizes or [1]))
|
||||
self.num_quantizers = num_quantizers
|
||||
self.enabled = enabled
|
||||
@@ -407,16 +412,18 @@ class CUDAGraphDecoderWrapper:
|
||||
icl_capture_shapes = self._get_icl_capture_shapes()
|
||||
|
||||
for batch_size in self.capture_batch_sizes:
|
||||
try:
|
||||
self._capture_icl_prefix(batch_size, device, dtype)
|
||||
logger.info("Captured ICL prefix CUDA Graph for batch=%d", batch_size)
|
||||
except Exception:
|
||||
logger.warning("Failed to capture ICL prefix CUDA Graph for batch=%d", batch_size, exc_info=True)
|
||||
try:
|
||||
self._capture_xvec_prefix(batch_size, device, dtype)
|
||||
logger.info("Captured xvec prefix CUDA Graph for batch=%d", batch_size)
|
||||
except Exception:
|
||||
logger.warning("Failed to capture xvec prefix CUDA Graph for batch=%d", batch_size, exc_info=True)
|
||||
if "icl" in self.capture_modes:
|
||||
try:
|
||||
self._capture_icl_prefix(batch_size, device, dtype)
|
||||
logger.info("Captured ICL prefix CUDA Graph for batch=%d", batch_size)
|
||||
except Exception:
|
||||
logger.warning("Failed to capture ICL prefix CUDA Graph for batch=%d", batch_size, exc_info=True)
|
||||
if "xvec" in self.capture_modes:
|
||||
try:
|
||||
self._capture_xvec_prefix(batch_size, device, dtype)
|
||||
logger.info("Captured xvec prefix CUDA Graph for batch=%d", batch_size)
|
||||
except Exception:
|
||||
logger.warning("Failed to capture xvec prefix CUDA Graph for batch=%d", batch_size, exc_info=True)
|
||||
|
||||
logger.info(
|
||||
"Starting CUDA Graph warmup for %d shapes: batch_sizes=%s seq_lens=%s",
|
||||
@@ -425,7 +432,7 @@ class CUDAGraphDecoderWrapper:
|
||||
self.icl_capture_sizes,
|
||||
)
|
||||
|
||||
for batch_size, size in icl_capture_shapes:
|
||||
for batch_size, size in icl_capture_shapes if "icl" in self.capture_modes else ():
|
||||
try:
|
||||
caches = self._make_dummy_icl_cache(batch_size, device, next(self.decoder.parameters()).dtype)
|
||||
self._capture_combined_suffix("icl", batch_size, size, caches, device, dtype)
|
||||
@@ -439,7 +446,7 @@ class CUDAGraphDecoderWrapper:
|
||||
)
|
||||
|
||||
model_dtype = next(self.decoder.parameters()).dtype
|
||||
for batch_size in self.capture_batch_sizes:
|
||||
for batch_size in self.capture_batch_sizes if "xvec" in self.capture_modes else ():
|
||||
for size, previous_frames in self._xvec_previous_frames_by_target.items():
|
||||
try:
|
||||
caches = self._make_dummy_xvec_cache(batch_size, device, model_dtype)
|
||||
|
||||
+2
@@ -999,6 +999,7 @@ class Qwen3TTSTokenizerV2Decoder(Qwen3TTSTokenizerV2DecoderPreTrainedModel):
|
||||
|
||||
def enable_cudagraph(
|
||||
self,
|
||||
capture_modes: tuple[str, ...] = ("icl", "xvec"),
|
||||
capture_batch_sizes: list[int] | None = None,
|
||||
stateless_capture_sizes: list[int] | None = None,
|
||||
device: torch.device | None = None,
|
||||
@@ -1021,6 +1022,7 @@ class Qwen3TTSTokenizerV2Decoder(Qwen3TTSTokenizerV2DecoderPreTrainedModel):
|
||||
|
||||
self._cudagraph_wrapper = CUDAGraphDecoderWrapper(
|
||||
decoder=self,
|
||||
capture_modes=capture_modes,
|
||||
capture_batch_sizes=capture_batch_sizes,
|
||||
stateless_capture_sizes=stateless_capture_sizes,
|
||||
num_quantizers=self.config.num_quantizers,
|
||||
|
||||
@@ -9,6 +9,8 @@ from vllm.model_executor.models.registry import (
|
||||
)
|
||||
|
||||
_OMNI_MODELS = {
|
||||
"BreezeForConditionalGeneration": ("breeze_tts_2", "modeling_breeze", "BreezeForConditionalGeneration"),
|
||||
"BreezeCode2Wav": ("breeze_tts_2", "code2wav", "BreezeCode2Wav"),
|
||||
"Qwen2_5OmniForConditionalGeneration": (
|
||||
"qwen2_5_omni",
|
||||
"qwen2_5_omni",
|
||||
@@ -476,16 +478,6 @@ _OMNI_MODELS = {
|
||||
"acoustic",
|
||||
"MiniMaxMusic3AcousticForConditionalGeneration",
|
||||
),
|
||||
"BreezeForConditionalGeneration": (
|
||||
"breeze_tts_2",
|
||||
"modeling_breeze_tts_2_talker",
|
||||
"BreezeTTS2TalkerForGeneration",
|
||||
),
|
||||
"BreezeTTS2MimiCodec": (
|
||||
"breeze_tts_2",
|
||||
"modeling_breeze_tts_2_codec",
|
||||
"BreezeTTS2MimiCodec",
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user