[Model] Add Breeze-TTS-2 two-stage AR TTS support (talker + codec, streaming) (#7084)

Signed-off-by: noname <liuzhiwei08@kuaishou.com>
Signed-off-by: noname <133508552+lzwnoname@users.noreply.github.com>
Signed-off-by: Yueqian Lin <linyueqian@outlook.com>
Co-authored-by: noname <liuzhiwei08@kuaishou.com>
Co-authored-by: Yueqian Lin <linyueqian@outlook.com>
This commit is contained in:
authored and GitHub committed 2026-09-14 09:55:53 -07:00
1 parent e0c4f97f32
commit ea1a416a17
46 files changed
+6067 -4

No files matched your search

Whitespace-only changes.
@@ -0,0 +1,149 @@
# 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,366 @@
# 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,404 @@
# 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]] = []
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))
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]] = []
valid_indices: list[int] = []
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)
valid_indices.append(row)
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())
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"]
@@ -0,0 +1,523 @@
# 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",
]
@@ -0,0 +1,618 @@
# 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 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`` runs immediately before this hook. It records
# requests whose previous hidden state selected EOS or reached the
# frame budget, so the scheduler receives a real stop token instead
# of depending on an arbitrary deploy-level max_tokens timeout.
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]),
):
if state.get("breeze_force_eos", False):
row = logits[row_start:row_end]
row.fill_(float("-inf"))
row[:, self.codebook_vocab_size] = 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] = []
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))
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)
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)
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"]
@@ -0,0 +1,350 @@
# 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"]
@@ -0,0 +1,51 @@
# 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"
BREEZE_TTS_2_PIPELINE = PipelineConfig(
model_type="breeze",
default_deploy_config_name="breeze_tts_2.yaml",
model_arch="BreezeForConditionalGeneration",
hf_architectures=("BreezeForConditionalGeneration",),
stages=(
StagePipelineConfig(
stage_id=0,
model_stage="breeze_tts_2",
execution_type=StageExecutionType.LLM_AR,
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,
"stop_token_ids": [2051],
},
),
StagePipelineConfig(
stage_id=1,
model_stage="breeze_tts_2_codec",
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,
),
),
)
__all__ = ["BREEZE_TTS_2_PIPELINE"]
@@ -0,0 +1,336 @@
# 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"]
@@ -492,6 +492,16 @@ _OMNI_MODELS = {
"acoustic",
"MiniMaxMusic3AcousticForConditionalGeneration",
),
"BreezeForConditionalGeneration": (
"breeze_tts_2",
"modeling_breeze_tts_2_talker",
"BreezeTTS2TalkerForGeneration",
),
"BreezeTTS2MimiCodec": (
"breeze_tts_2",
"modeling_breeze_tts_2_codec",
"BreezeTTS2MimiCodec",
),
}