Merge branch 'main' into lance-model-support; drop lance.yaml

Resolves conflicts in:
- vllm_omni/diffusion/registry.py: keep both LancePipeline (HEAD)
  and MingImagePipeline (main) entries.
- vllm_omni/diffusion/models/bagel/bagel_transformer.py: take main's
  simpler cfg_batched payload; HEAD referenced undefined locals.

Also strips vllm_omni/deploy/lance.yaml -- Lance is single-stage
diffusion, so its engine knobs (pipeline=lance, enforce_eager,
trust_remote_code, max_num_seqs=1, ...) flow directly to Omni(...)
/ vllm-omni serve instead of through a deploy YAML.
create_default_diffusion builds the stage config from those kwargs.

Touched: examples/offline_inference/lance/{end2end,gradio_demo}.py,
tests/e2e/online_serving/test_lance.py, tests/helpers/stage_config.py.

Signed-off-by: lishunyang12 <lishunyang12@163.com>
This commit is contained in:
lishunyang12 committed 2026-05-31 11:50:21 +00:00
commit c15f51a2f6
419 files changed
+46193 -5592

No files matched your search

@@ -0,0 +1,243 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Alias-free activation for BigVGAN-style speech decoders.
Provides anti-aliased activation (upsample → activation → downsample) with
Kaiser-windowed sinc filters. Includes NPU bf16 workarounds for platforms
where F.pad(mode='replicate') does not support bfloat16.
Used by: Qwen2.5-Omni, Qwen3-TTS v1, CoVo-Audio, and future BigVGAN vocoders.
"""
from __future__ import annotations
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from vllm.logger import init_logger
from vllm_omni.platforms import current_omni_platform
logger = init_logger(__name__)
# ---------------------------------------------------------------------------
# Helper utilities
# ---------------------------------------------------------------------------
def kaiser_sinc_filter1d(cutoff: float, half_width: float, kernel_size: int) -> torch.Tensor:
"""Generate a 1-D Kaiser-windowed sinc low-pass filter.
Args:
cutoff: Normalized cutoff frequency (0 to 0.5).
half_width: Transition bandwidth.
kernel_size: Number of filter taps.
Returns:
Filter tensor of shape ``(1, 1, kernel_size)``.
"""
is_even = kernel_size % 2 == 0
half_size = kernel_size // 2
delta_f = 4 * half_width
attenuation = 2.285 * (half_size - 1) * math.pi * delta_f + 7.95
if attenuation > 50.0:
beta = 0.1102 * (attenuation - 8.7)
elif attenuation >= 21.0:
beta = 0.5842 * (attenuation - 21) ** 0.4 + 0.07886 * (attenuation - 21.0)
else:
beta = 0.0
# torch.kaiser_window is not supported on NPU / XPU — compute on CPU.
if current_omni_platform.is_npu():
kaiser_window = torch.kaiser_window(
kernel_size, beta=beta, periodic=False, dtype=torch.float32, device="cpu"
).to("npu")
elif current_omni_platform.is_xpu():
kaiser_window = torch.kaiser_window(
kernel_size, beta=beta, periodic=False, dtype=torch.float32, device="cpu"
).to("xpu")
else:
kaiser_window = torch.kaiser_window(kernel_size, beta=beta, periodic=False, dtype=torch.float32)
if is_even:
time_indices = torch.arange(-half_size, half_size) + 0.5
else:
time_indices = torch.arange(kernel_size) - half_size
if cutoff == 0:
return torch.zeros((1, 1, kernel_size), dtype=torch.float32)
sinc_filter = torch.sinc(2 * cutoff * time_indices)
normalized_filter = 2 * cutoff * kaiser_window * sinc_filter
normalized_filter /= normalized_filter.sum()
return normalized_filter.view(1, 1, kernel_size)
def replication_pad_1d(hidden_states: torch.Tensor, pad_left: int, pad_right: int) -> torch.Tensor:
"""Manual replicate padding for NPU bf16 compatibility.
``F.pad(mode='replicate')`` does not support bfloat16 on NPU (and older
CUDA). This expand+cat fallback produces identical results.
TODO: Remove when upstream PyTorch fixes replication_pad1d for bf16.
"""
if pad_left == 0 and pad_right == 0:
return hidden_states
segments = []
if pad_left > 0:
left = hidden_states[..., :1].expand(*hidden_states.shape[:-1], pad_left)
segments.append(left)
segments.append(hidden_states)
if pad_right > 0:
right = hidden_states[..., -1:].expand(*hidden_states.shape[:-1], pad_right)
segments.append(right)
return torch.cat(segments, dim=-1)
# ---------------------------------------------------------------------------
# Up / Down sampling with Kaiser sinc filters
# ---------------------------------------------------------------------------
class UpSample1d(nn.Module):
"""Kaiser-sinc interpolation upsample (default: 2x, 12-tap filter)."""
def __init__(self, ratio: int = 2, kernel_size: int | None = None):
super().__init__()
self.ratio = ratio
self.kernel_size = int(6 * ratio // 2) * 2 if kernel_size is None else kernel_size
self.stride = ratio
self.pad = self.kernel_size // ratio - 1
self.pad_left = self.pad * self.stride + (self.kernel_size - self.stride) // 2
self.pad_right = self.pad * self.stride + (self.kernel_size - self.stride + 1) // 2
filt = kaiser_sinc_filter1d(cutoff=0.5 / ratio, half_width=0.6 / ratio, kernel_size=self.kernel_size)
self.register_buffer("filter", filt, persistent=False)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
channels = hidden_states.shape[1]
if current_omni_platform.is_npu():
input_dtype = hidden_states.dtype
hidden_states = replication_pad_1d(hidden_states.to(self.filter.dtype), self.pad, self.pad)
hidden_states = self.ratio * F.conv_transpose1d(
hidden_states,
self.filter.expand(channels, -1, -1),
stride=self.stride,
groups=channels,
).to(input_dtype)
else:
input_dtype = hidden_states.dtype
hidden_states = F.pad(hidden_states, (self.pad, self.pad), mode="replicate").to(self.filter.dtype)
hidden_states = self.ratio * F.conv_transpose1d(
hidden_states,
self.filter.expand(channels, -1, -1),
stride=self.stride,
groups=channels,
).to(input_dtype)
hidden_states = hidden_states[..., self.pad_left : -self.pad_right]
return hidden_states
class DownSample1d(nn.Module):
"""Kaiser-sinc anti-aliasing downsample (default: 2x, 12-tap filter)."""
def __init__(self, ratio: int = 2, kernel_size: int | None = None):
super().__init__()
if kernel_size is None:
kernel_size = int(6 * ratio // 2) * 2
cutoff = 0.5 / ratio
half_width = 0.6 / ratio
if cutoff < 0.0:
raise ValueError("Minimum cutoff must be larger than zero.")
if cutoff > 0.5:
raise ValueError("A cutoff above 0.5 does not make sense.")
self.even = kernel_size % 2 == 0
self.pad_left = kernel_size // 2 - int(self.even)
self.pad_right = kernel_size // 2
self.stride = ratio
filt = kaiser_sinc_filter1d(cutoff, half_width, kernel_size)
self.register_buffer("filter", filt, persistent=False)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
channels = hidden_states.shape[1]
if current_omni_platform.is_npu():
input_dtype = hidden_states.dtype
hidden_states = replication_pad_1d(hidden_states.to(self.filter.dtype), self.pad_left, self.pad_right)
out = F.conv1d(
hidden_states,
self.filter.to(device=hidden_states.device, dtype=hidden_states.dtype).expand(channels, -1, -1),
stride=self.stride,
groups=channels,
).to(input_dtype)
else:
input_dtype = hidden_states.dtype
hidden_states = F.pad(hidden_states, (self.pad_left, self.pad_right), mode="replicate").to(
self.filter.dtype
)
out = F.conv1d(
hidden_states,
self.filter.expand(channels, -1, -1),
stride=self.stride,
groups=channels,
).to(input_dtype)
return out
# ---------------------------------------------------------------------------
# Alias-free activation: upsample → activation → downsample
# ---------------------------------------------------------------------------
class AliasFreeActivation1d(nn.Module):
"""Anti-aliased activation following BigVGAN (ICLR 2023).
Upsamples the signal, applies a pointwise activation (typically SnakeBeta),
then downsamples with a low-pass filter to suppress aliasing from the
high-frequency components introduced by the activation function.
The ``activation`` should be an ``nn.Module`` instance — typically
``SnakeBeta`` from ``common.snake_activation``, which already dispatches
between Triton and eager PyTorch internally.
Args:
activation: Pointwise activation module (e.g. ``SnakeBeta(channels)``).
up_ratio: Upsample factor before activation.
down_ratio: Downsample factor after activation.
up_kernel_size: Kaiser sinc filter taps for upsampling.
down_kernel_size: Kaiser sinc filter taps for downsampling.
"""
def __init__(
self,
activation: nn.Module,
up_ratio: int = 2,
down_ratio: int = 2,
up_kernel_size: int = 12,
down_kernel_size: int = 12,
):
super().__init__()
if not callable(activation):
raise TypeError("Activation function must be callable")
self.act = activation
self.upsample = UpSample1d(up_ratio, up_kernel_size)
self.downsample = DownSample1d(down_ratio, down_kernel_size)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
hidden_states = self.upsample(hidden_states)
hidden_states = self.act(hidden_states)
hidden_states = self.downsample(hidden_states)
return hidden_states
@@ -0,0 +1,118 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Shared TTS sampling primitives: nucleus (top-p/top-k) and RAS.
Used by CosyVoice3 and GLM-TTS (and any future TTS model with RAS).
"""
from __future__ import annotations
from collections.abc import Sequence
import torch
def multinomial_sample(
probs: torch.Tensor,
generator: torch.Generator | None = None,
) -> torch.Tensor:
"""Draw one sample from a categorical distribution."""
return torch.multinomial(probs, 1, replacement=True, generator=generator).reshape(())
def nucleus_sample_one(
weighted_scores: torch.Tensor,
*,
top_p: float,
top_k: int,
generator: torch.Generator | None = None,
) -> int:
"""Sample one token using nucleus (top-p + top-k) filtering.
``weighted_scores`` should be log-softmax-ed logits (for RAS callers)
or raw logits (softmax is applied internally).
Vectorized via ``torch.cumsum`` — no Python loop over the vocabulary.
"""
# Apply top-k before sort. GLM-TTS and CosyVoice3 usually run with
# top_k=25, so sorting the whole audio vocabulary on every AR step is
# avoidable work in the hottest path. Keep probabilities normalized over
# the full vocabulary so the top-p cumulative mass matches the old path.
if top_k > 0 and int(top_k) < int(weighted_scores.numel()):
top_scores, sorted_idx = torch.topk(
weighted_scores,
k=int(top_k),
dim=0,
largest=True,
sorted=True,
)
sorted_prob = (top_scores - torch.logsumexp(top_scores, dim=0)).exp()
else:
probs = weighted_scores.softmax(dim=0)
sorted_prob, sorted_idx = probs.sort(descending=True, stable=True)
# Apply top-p (nucleus) filtering: keep the smallest prefix whose
# cumulative probability exceeds top_p, always including the first token.
# Use float32 for cumulative sum to match the original Python float64
# accumulation loop. Low-precision (fp16/bf16) cumsum over ~32K vocab
# causes rounding drift that shifts the top-p boundary, changing which
# tokens are kept and ultimately producing different AR sequences.
sorted_prob_f32 = sorted_prob.float()
cum_prob = sorted_prob_f32.cumsum(dim=0)
# Mask: include tokens where cumsum *before* this token is still < top_p
mask = (cum_prob - sorted_prob_f32) < top_p
# Safety: ensure top token is always kept. With sorted descending
# probabilities, mask[0] is always True when top_p > 0 (since the
# cumsum-before-self of the first element is 0 < top_p). Setting it
# unconditionally avoids a GPU→CPU sync from the old `mask.any()` check.
mask[0] = True
kept_probs = torch.nan_to_num(sorted_prob[mask], nan=0.0, posinf=0.0, neginf=0.0).clamp_min_(0.0)
kept_indices = sorted_idx[mask]
# ``torch.multinomial`` accepts unnormalized weights, but not an all-zero
# vector. Handle the extreme underflow case on-device by forcing the top
# retained token to be selectable without adding another CPU sync.
kept_probs[0] = torch.where(
kept_probs.sum() > 0,
kept_probs[0],
torch.ones_like(kept_probs[0]),
)
sample_pos = multinomial_sample(kept_probs, generator=generator)
return int(kept_indices[sample_pos].item())
def ras_sample_one(
weighted_scores: torch.Tensor,
decoded_tokens: Sequence[int],
*,
top_p: float,
top_k: int,
win_size: int,
tau_r: float,
generator: torch.Generator | None = None,
) -> int:
"""Repetition-Aware Sampling following GLM-TTS/CosyVoice.
If the nucleus-sampled token appears too often in the recent window,
upstream samples once from the original full distribution instead of
masking the repeated token. This matters for GLM-TTS because masking the
dominant repeated token can artificially raise EOA probability right after
the minimum length guard is lifted.
"""
def _random_sample_one() -> int:
return int(multinomial_sample(weighted_scores.softmax(dim=0), generator=generator).item())
top_id = nucleus_sample_one(
weighted_scores,
top_p=top_p,
top_k=top_k,
generator=generator,
)
if win_size > 0 and decoded_tokens:
recent = decoded_tokens[-win_size:]
rep_num = sum(1 for token in recent if int(token) == top_id)
if rep_num >= win_size * tau_r:
top_id = _random_sample_one()
return top_id
@@ -1,7 +1,10 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Copyright 2025 The Qwen team.
"""Shared SnakeBeta activation for speech decoders (Qwen3-TTS, Qwen3-Omni Code2Wav)."""
"""Shared Snake/SnakeBeta activations for speech decoders.
Used by: Qwen3-TTS, Qwen3-Omni Code2Wav, Qwen2.5-Omni, CoVo-Audio, CosyVoice3.
"""
import torch
from torch import nn
@@ -70,12 +73,17 @@ class SnakeBeta(nn.Module):
SnakeBeta._triton_kernel = _kernel
return True
def __init__(self, in_features, alpha=1.0):
def __init__(self, in_features, alpha=1.0, alpha_logscale=True):
super().__init__()
self.in_features = in_features
self.alpha_logscale = alpha_logscale
self.alpha = Parameter(torch.zeros(in_features) * alpha)
self.beta = Parameter(torch.zeros(in_features) * alpha)
if alpha_logscale:
self.alpha = Parameter(torch.zeros(in_features) * alpha)
self.beta = Parameter(torch.zeros(in_features) * alpha)
else:
self.alpha = Parameter(torch.ones(in_features) * alpha)
self.beta = Parameter(torch.ones(in_features) * alpha)
self.no_div_by_zero = 0.000000001
@@ -86,8 +94,12 @@ class SnakeBeta(nn.Module):
def precompute_exp_cache(self):
"""Materialize exp(alpha) and 1/(exp(beta)+eps) as frozen buffers."""
with torch.no_grad():
self._exp_alpha = torch.exp(self.alpha).contiguous()
self._inv_beta = (1.0 / (torch.exp(self.beta) + self.no_div_by_zero)).contiguous()
if self.alpha_logscale:
self._exp_alpha = torch.exp(self.alpha).contiguous()
self._inv_beta = (1.0 / (torch.exp(self.beta) + self.no_div_by_zero)).contiguous()
else:
self._exp_alpha = self.alpha.contiguous()
self._inv_beta = (1.0 / (self.beta + self.no_div_by_zero)).contiguous()
@property
def _cached(self):
@@ -104,12 +116,10 @@ class SnakeBeta(nn.Module):
return self._eager_forward(hidden_states)
def _eager_forward(self, hidden_states):
if self._cached:
exp_alpha = self._exp_alpha.unsqueeze(0).unsqueeze(-1)
inv_beta = self._inv_beta.unsqueeze(0).unsqueeze(-1)
else:
exp_alpha = torch.exp(self.alpha).unsqueeze(0).unsqueeze(-1)
inv_beta = (1.0 / (torch.exp(self.beta) + self.no_div_by_zero)).unsqueeze(0).unsqueeze(-1)
if not self._cached:
self.precompute_exp_cache()
exp_alpha = self._exp_alpha.unsqueeze(0).unsqueeze(-1)
inv_beta = self._inv_beta.unsqueeze(0).unsqueeze(-1)
hidden_states = hidden_states + inv_beta * torch.pow(torch.sin(hidden_states * exp_alpha), 2)
return hidden_states
@@ -134,3 +144,33 @@ class SnakeBeta(nn.Module):
block_t=block_t,
)
return out
class Snake(SnakeBeta):
"""Original Snake activation with a single parameter: x + 1/α * sin²(αx).
Unlike SnakeBeta which has separate alpha (frequency) and beta (magnitude)
parameters, Snake uses alpha for both. Only ``alpha`` appears in the
state_dict — ``beta`` is absent, keeping checkpoint compatibility with
CosyVoice3's HiFi-GAN.
The Triton kernel and precomputed-cache path from SnakeBeta are reused;
``precompute_exp_cache`` derives ``_inv_beta`` from ``alpha`` so the
forward path is identical.
"""
def __init__(self, in_features, alpha=1.0, alpha_logscale=False):
# Initialise SnakeBeta — creates both alpha and beta Parameters.
super().__init__(in_features, alpha=alpha, alpha_logscale=alpha_logscale)
# Drop beta as a Parameter so it won't appear in state_dict.
del self.beta
def precompute_exp_cache(self):
"""Derive both exp_alpha and inv_beta from the single alpha parameter."""
with torch.no_grad():
if self.alpha_logscale:
self._exp_alpha = torch.exp(self.alpha).contiguous()
self._inv_beta = (1.0 / (torch.exp(self.alpha) + self.no_div_by_zero)).contiguous()
else:
self._exp_alpha = self.alpha.contiguous()
self._inv_beta = (1.0 / (self.alpha + self.no_div_by_zero)).contiguous()
@@ -0,0 +1,291 @@
# Copyright 2022 The OpenAI Authors and The HuggingFace Inc. team. All rights reserved.
# 2025 Zhipu AI Inc (authors: CogAudio Group Members)
# SPDX-License-Identifier: Apache-2.0
"""WhisperVQEncoder: HF WhisperEncoder + VQ codebook + inter-layer pooling.
Built on standard ``WhisperConfig``. VQ-specific parameters are patched onto
the config object after ``from_pretrained`` so that callers never need a
separate config class. GLM-TTS (and future VQ-based TTS models) only need::
from transformers import WhisperConfig
from vllm_omni.model_executor.models.common.whisper_vq import WhisperVQEncoder
cfg = WhisperConfig.from_pretrained(checkpoint_dir)
cfg.pooling_kernel_size = None # passed through from checkpoint
cfg.pooling_type = "max" # or set by caller
cfg.pooling_position = 0
cfg.quantize_vocab_size = 32768
cfg.quantize_position = 16
cfg.quantize_encoder_only = True
model = WhisperVQEncoder(cfg)
"""
from __future__ import annotations
import math
import re
from dataclasses import dataclass
from typing import Any
import torch
import torch.nn.functional as F
from torch import Tensor, nn
from transformers import WhisperConfig
from transformers.modeling_outputs import BaseModelOutput
from transformers.models.whisper.modeling_whisper import WhisperEncoder
# ---------------------------------------------------------------------------
# helpers
# ---------------------------------------------------------------------------
@dataclass
class QuantizedBaseModelOutput(BaseModelOutput):
quantized_token_ids: torch.LongTensor | None = None
def vector_quantize(inputs: Tensor, codebook: Tensor) -> tuple[Tensor, Tensor, Tensor]:
"""Nearest-neighbour codebook lookup."""
embedding_size = codebook.size(1)
inputs_flatten = inputs.reshape(-1, embedding_size)
codebook_sqr = torch.sum(codebook**2, dim=1)
inputs_sqr = torch.sum(inputs_flatten**2, dim=1, keepdim=True)
distances = torch.addmm(
codebook_sqr + inputs_sqr,
inputs_flatten,
codebook.t(),
alpha=-2.0,
beta=1.0,
)
_, indices_flatten = torch.min(distances, dim=1)
codes_flatten = torch.index_select(codebook, dim=0, index=indices_flatten)
codes = codes_flatten.view_as(inputs)
return codes, indices_flatten, distances
_LEGACY_LAYER_REMAP = (
(re.compile(r"^layers\.(\d+)\.attn\.query\."), r"layers.\1.self_attn.q_proj."),
(re.compile(r"^layers\.(\d+)\.attn\.key\."), r"layers.\1.self_attn.k_proj."),
(re.compile(r"^layers\.(\d+)\.attn\.value\."), r"layers.\1.self_attn.v_proj."),
(re.compile(r"^layers\.(\d+)\.attn\.out\."), r"layers.\1.self_attn.out_proj."),
(re.compile(r"^layers\.(\d+)\.attn_ln\."), r"layers.\1.self_attn_layer_norm."),
(re.compile(r"^layers\.(\d+)\.mlp_ln\."), r"layers.\1.final_layer_norm."),
(re.compile(r"^layers\.(\d+)\.mlp\.0\."), r"layers.\1.fc1."),
(re.compile(r"^layers\.(\d+)\.mlp\.2\."), r"layers.\1.fc2."),
)
def remap_legacy_whisper_vq_state_dict(state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
"""Map CogAudio/GLM-TTS fork parameter names onto HF WhisperEncoder names."""
remapped: dict[str, Tensor] = {}
for name, tensor in state_dict.items():
new_name = name
if new_name == "embed_positions":
new_name = "embed_positions.weight"
for pattern, replacement in _LEGACY_LAYER_REMAP:
new_name = pattern.sub(replacement, new_name)
remapped[new_name] = tensor
return remapped
# ---------------------------------------------------------------------------
# main encoder class
# ---------------------------------------------------------------------------
class WhisperVQEncoder(WhisperEncoder):
"""HF Whisper encoder with optional VQ codebook and pooling.
Uses a standard ``WhisperConfig`` with the following VQ-specific attrs
patched on by the caller (or loaded from the checkpoint's config.json):
* ``pooling_kernel_size`` -- int | None
* ``pooling_type`` -- "max" | "avg"
* ``pooling_position`` -- int (0-based layer index)
* ``quantize_vocab_size`` -- int | None
* ``quantize_position`` -- int (0-based layer index)
* ``quantize_encoder_only`` -- bool
"""
def __init__(self, config: WhisperConfig):
super().__init__(config)
embed_dim = config.d_model
max_source_positions = config.max_source_positions
# Truncate layers when quantize_encoder_only is set.
qpos = int(getattr(config, "quantize_position", 0) or 0)
if getattr(config, "quantize_encoder_only", False):
self.layers = nn.ModuleList(list(self.layers[:qpos]))
self.layer_norm = None
else:
qpos = max(qpos, int(config.encoder_layers)) # never exceed total
# Optional inter-layer pooling.
self.pooling_layer: nn.Module | None = None
ksize = getattr(config, "pooling_kernel_size", None)
if ksize is not None:
ptype = str(getattr(config, "pooling_type", "max") or "max")
self.pooling_layer = {
"max": nn.MaxPool1d(kernel_size=int(ksize)),
"avg": nn.AvgPool1d(kernel_size=int(ksize)),
}[ptype]
# Optional vector-quantization codebook.
self.codebook: nn.Embedding | None = None
self.embed_positions2: nn.Embedding | None = None
vq_sz = getattr(config, "quantize_vocab_size", None)
if vq_sz is not None:
self.codebook = nn.Embedding(int(vq_sz), embed_dim)
pos2_len = max_source_positions
if ksize is not None:
pos2_len = math.ceil(max_source_positions / int(ksize))
self.embed_positions2 = nn.Embedding(pos2_len, embed_dim)
# cached for forward()
self._pooling_position = int(getattr(config, "pooling_position", 0) or 0)
self._quantize_position = qpos if vq_sz is not None else -1
# ------------------------------------------------------------------
# forward / helpers
# ------------------------------------------------------------------
@property
def device(self) -> torch.device: # type: ignore[override]
return self.conv1.weight.device
@property
def dtype(self) -> torch.dtype: # type: ignore[override]
return self.conv1.weight.dtype
def load_state_dict(
self,
state_dict: dict[str, Tensor],
strict: bool = True,
assign: bool = False,
): # type: ignore[override]
remapped = remap_legacy_whisper_vq_state_dict(state_dict)
try:
return super().load_state_dict(remapped, strict=strict, assign=assign)
except TypeError:
return super().load_state_dict(remapped, strict=strict)
def forward(
self,
input_features: Tensor,
attention_mask: Tensor | None = None,
**_: Any,
) -> QuantizedBaseModelOutput:
batch_size, _, _ = input_features.shape
hidden_states = F.gelu(self.conv1(input_features))
hidden_states = F.gelu(self.conv2(hidden_states))
hidden_states = hidden_states.permute(0, 2, 1)
seq_len = int(hidden_states.shape[1])
pos_embed = self._position_embeddings(seq_len, hidden_states.device, hidden_states.dtype)
hidden_states = hidden_states + pos_embed
valid_mask = self._downsample_attention_mask(attention_mask, batch_size, seq_len, hidden_states.device)
hidden_states = hidden_states.masked_fill(~valid_mask.unsqueeze(-1), 0)
quantized_token_ids = None
for idx, layer in enumerate(self.layers):
layer_mask = self._make_layer_attention_mask(valid_mask, hidden_states.dtype)
layer_outputs = layer(
hidden_states,
attention_mask=layer_mask,
layer_head_mask=None,
output_attentions=False,
)
hidden_states = layer_outputs[0] if isinstance(layer_outputs, tuple) else layer_outputs
hidden_states = hidden_states.masked_fill(~valid_mask.unsqueeze(-1), 0)
if idx + 1 == self._pooling_position and self.pooling_layer is not None:
hidden_states, valid_mask = self._apply_pooling(hidden_states, valid_mask)
if idx + 1 == self._quantize_position and self.codebook is not None:
hidden_states, quantized_token_ids = self._apply_vq(hidden_states, valid_mask)
if self.layer_norm is not None:
hidden_states = self.layer_norm(hidden_states)
hidden_states = hidden_states.masked_fill(~valid_mask.unsqueeze(-1), 0)
return QuantizedBaseModelOutput(
last_hidden_state=hidden_states,
quantized_token_ids=quantized_token_ids,
)
def _position_embeddings(self, seq_len: int, device: torch.device, dtype: torch.dtype) -> Tensor:
ep = self.embed_positions
if isinstance(ep, nn.Embedding):
positions = torch.arange(seq_len, device=device)
return ep(positions).to(dtype=dtype).unsqueeze(0)
return ep[:seq_len].to(device=device, dtype=dtype).unsqueeze(0)
def _downsample_attention_mask(
self,
attention_mask: Tensor | None,
batch_size: int,
seq_len: int,
device: torch.device,
) -> Tensor:
if attention_mask is None:
return torch.ones(batch_size, seq_len, dtype=torch.bool, device=device)
conv_stride = int(self.conv1.stride[0]) * int(self.conv2.stride[0])
downsampled = attention_mask[:, ::conv_stride].to(device=device, dtype=torch.bool)
if downsampled.shape[1] < seq_len:
pad = seq_len - int(downsampled.shape[1])
downsampled = F.pad(downsampled, (0, pad), value=False)
return downsampled[:, :seq_len]
@staticmethod
def _make_layer_attention_mask(valid_mask: Tensor, dtype: torch.dtype) -> Tensor:
min_value = torch.finfo(dtype).min
additive = torch.zeros(valid_mask.shape, dtype=dtype, device=valid_mask.device)
additive = additive.masked_fill(~valid_mask, min_value)
return additive[:, None, None, :]
def _apply_pooling(self, hidden_states: Tensor, valid_mask: Tensor) -> tuple[Tensor, Tensor]:
k = int(self.config.pooling_kernel_size) # type: ignore[attr-defined]
pooled_segments: list[Tensor] = []
pooled_masks: list[Tensor] = []
for batch_idx in range(int(hidden_states.shape[0])):
length = int(valid_mask[batch_idx].sum().item())
segment = hidden_states[batch_idx, :length]
if segment.numel() == 0:
pooled = hidden_states.new_zeros((0, hidden_states.shape[-1]))
else:
segment_t = segment.unsqueeze(0).transpose(1, 2)
if int(segment_t.shape[-1]) % k != 0:
segment_t = F.pad(segment_t, (0, k - int(segment_t.shape[-1]) % k))
pooled = self.pooling_layer(segment_t).transpose(1, 2).squeeze(0) # type: ignore[misc]
pooled_segments.append(pooled)
pooled_masks.append(torch.ones(pooled.shape[0], dtype=torch.bool, device=hidden_states.device))
max_len = max((int(seg.shape[0]) for seg in pooled_segments), default=0)
output = hidden_states.new_zeros((hidden_states.shape[0], max_len, hidden_states.shape[-1]))
output_mask = torch.zeros(hidden_states.shape[0], max_len, dtype=torch.bool, device=hidden_states.device)
for i, segment in enumerate(pooled_segments):
if segment.shape[0] > 0:
output[i, : segment.shape[0]] = segment
output_mask[i, : segment.shape[0]] = pooled_masks[i]
return output, output_mask
def _apply_vq(self, hidden_states: Tensor, valid_mask: Tensor) -> tuple[Tensor, Tensor | None]:
output = hidden_states.clone()
token_ids = torch.full(
(hidden_states.shape[0], hidden_states.shape[1]),
-1,
dtype=torch.long,
device=hidden_states.device,
)
for batch_idx in range(int(hidden_states.shape[0])):
length = int(valid_mask[batch_idx].sum().item())
if length <= 0:
continue
segment = hidden_states[batch_idx : batch_idx + 1, :length]
quantized, indices, _ = vector_quantize(segment, self.codebook.weight) # type: ignore[union-attr]
if self.embed_positions2 is not None:
quantized = quantized + self.embed_positions2.weight[:length].to(dtype=quantized.dtype).unsqueeze(0)
output[batch_idx, :length] = quantized.squeeze(0)
token_ids[batch_idx, :length] = indices.reshape(-1)
return output.masked_fill(~valid_mask.unsqueeze(-1), 0), token_ids
@@ -11,7 +11,6 @@ import torch
import torch.nn as nn
import torch.nn.functional as F
from scipy.signal import get_window
from torch import pow, sin
from torch.nn import Conv1d, ConvTranspose1d
from torch.nn.utils import remove_weight_norm
@@ -20,64 +19,8 @@ try:
except ImportError:
from torch.nn.utils import weight_norm
from torch.distributions.uniform import Uniform
from torch.nn import Parameter
# Implementation adapted from https://github.com/EdwardDixon/snake under the MIT license.
# LICENSE is in incl_licenses directory.
class Snake(nn.Module):
"""
Implementation of a sine-based periodic activation function
Shape:
- Input: (B, C, T)
- Output: (B, C, T), same shape as the input
Parameters:
- alpha - trainable parameter
References:
- This activation function is from this paper by Liu Ziyin, Tilman Hartwig, Masahito Ueda:
https://arxiv.org/abs/2006.08195
Examples:
>>> a1 = snake(256)
>>> x = torch.randn(256)
>>> x = a1(x)
"""
def __init__(self, in_features, alpha=1.0, alpha_trainable=True, alpha_logscale=False):
"""
Initialization.
INPUT:
- in_features: shape of the input
- alpha: trainable parameter
alpha is initialized to 1 by default, higher values = higher-frequency.
alpha will be trained along with the rest of your model.
"""
super().__init__()
self.in_features = in_features
# initialize alpha
self.alpha_logscale = alpha_logscale
if self.alpha_logscale: # log scale alphas initialized to zeros
self.alpha = Parameter(torch.zeros(in_features) * alpha)
else: # linear scale alphas initialized to ones
self.alpha = Parameter(torch.ones(in_features) * alpha)
self.alpha.requires_grad = alpha_trainable
self.no_div_by_zero = 0.000000001
def forward(self, x):
"""
Forward pass of the function.
Applies the function to the input elementwise.
Snake ∶= x + 1/a * sin^2 (xa)
"""
alpha = self.alpha.unsqueeze(0).unsqueeze(-1) # line up with x to [B, C, T]
if self.alpha_logscale:
alpha = torch.exp(alpha)
x = x + (1.0 / (alpha + self.no_div_by_zero)) * pow(sin(x * alpha), 2)
return x
from vllm_omni.model_executor.models.common.snake_activation import Snake
"""hifigan based generator implementation.
@@ -784,12 +784,14 @@ class CosyVoice3Model(
else:
self._stream_vocoder_cache_by_req[req_id] = new_cache_state
else:
token_offset = max(0, meta.talker_prefill_offset or 0) if meta else 0
tts_speech = self.code2wav.forward(
token=token.unsqueeze(0),
prompt_token=speech_token[:1],
prompt_feat=speech_feat[:1],
embedding=embedding[:1],
n_timesteps=10,
token_offset_tokens=token_offset,
)
audio = tts_speech.reshape(-1).to(dtype=torch.float32)
@@ -292,6 +292,7 @@ class CosyVoice3Code2Wav(nn.Module):
prompt_feat: torch.Tensor,
embedding: torch.Tensor,
n_timesteps: int = 10,
token_offset_tokens: int = 0,
) -> torch.Tensor:
"""Generate audio waveform from speech tokens."""
feat = self._forward_mel(
@@ -300,7 +301,7 @@ class CosyVoice3Code2Wav(nn.Module):
prompt_feat=prompt_feat,
embedding=embedding,
n_timesteps=n_timesteps,
token_offset_tokens=0,
token_offset_tokens=token_offset_tokens,
streaming=False,
finalize=True,
)
@@ -31,6 +31,7 @@ COSYVOICE3_PIPELINE = PipelineConfig(
owns_tokenizer=True,
engine_output_type="latent",
async_chunk_process_next_stage_input_func=(f"{_PROC}.talker2code2wav_async_chunk"),
custom_process_next_stage_input_func=f"{_PROC}.text2flow_full_payload",
sampling_constraints={
# merged speech stop token (logsumexp of all 200 stop logits)
"stop_token_ids": [6562],
@@ -44,7 +45,8 @@ COSYVOICE3_PIPELINE = PipelineConfig(
final_output=True,
final_output_type="audio",
engine_output_type="latent",
sync_process_input_func=f"{_PROC}.text2flow",
custom_process_input_func=f"{_PROC}.text2flow",
sync_process_input_func=f"{_PROC}.text2flow_token_only",
),
),
)
@@ -29,6 +29,7 @@ COVO_AUDIO_PIPELINE = PipelineConfig(
owns_tokenizer=True,
requires_multimodal_data=True,
engine_output_type="latent",
custom_process_next_stage_input_func=f"{_PROC}.llm2code2wav_full_payload",
sampling_constraints={
"detokenize": True,
"stop_token_ids": [151645],
@@ -44,6 +45,7 @@ COVO_AUDIO_PIPELINE = PipelineConfig(
final_output_type="audio",
engine_output_type="audio",
custom_process_input_func=f"{_PROC}.llm2code2wav",
sync_process_input_func=f"{_PROC}.llm2code2wav_token_only",
sampling_constraints={"detokenize": False},
),
),
@@ -10,10 +10,11 @@ import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from torch import pow, sin
from torch.nn import Parameter
from torch.nn.utils import weight_norm
from vllm_omni.model_executor.models.common.alias_free_activation import AliasFreeActivation1d
from vllm_omni.model_executor.models.common.snake_activation import SnakeBeta
# --------------- Utilities ---------------
@@ -93,41 +94,7 @@ def apply_rotary_pos_emb(pos, t):
return t * pos.cos() + rotate_half(t) * pos.sin()
if "sinc" in dir(torch):
sinc = torch.sinc
else:
def sinc(x: torch.Tensor):
return torch.where(
x == 0, torch.tensor(1.0, device=x.device, dtype=x.dtype), torch.sin(math.pi * x) / math.pi / x
)
def kaiser_sinc_filter1d(cutoff, half_width, kernel_size):
even = kernel_size % 2 == 0
half_size = kernel_size // 2
delta_f = 4 * half_width
A = 2.285 * (half_size - 1) * math.pi * delta_f + 7.95
if A > 50.0:
beta = 0.1102 * (A - 8.7)
elif A >= 21.0:
beta = 0.5842 * (A - 21) ** 0.4 + 0.07886 * (A - 21.0)
else:
beta = 0.0
window = torch.kaiser_window(kernel_size, beta=beta, periodic=False)
if even:
time = torch.arange(-half_size, half_size) + 0.5
else:
time = torch.arange(kernel_size) - half_size
if cutoff == 0:
filter_ = torch.zeros_like(time)
else:
filter_ = 2 * cutoff * window * sinc(2 * cutoff * time)
filter_ /= filter_.sum()
return filter_.view(1, 1, kernel_size)
# sinc, kaiser_sinc_filter1d removed — now in common.alias_free_activation
# --------------- Basic Layers ---------------
@@ -320,116 +287,14 @@ class ConvPositionEmbed(nn.Module):
# --------------- Anti-aliasing (BigVGAN) ---------------
class LowPassFilter1d(nn.Module):
def __init__(
self,
cutoff=0.5,
half_width=0.6,
stride: int = 1,
padding: bool = True,
padding_mode: str = "replicate",
kernel_size: int = 12,
):
super().__init__()
if cutoff < -0.0:
raise ValueError("Minimum cutoff must be larger than zero.")
if cutoff > 0.5:
raise ValueError("A cutoff above 0.5 does not make sense.")
self.kernel_size = kernel_size
self.even = kernel_size % 2 == 0
self.pad_left = kernel_size // 2 - int(self.even)
self.pad_right = kernel_size // 2
self.stride = stride
self.padding = padding
self.padding_mode = padding_mode
filter = kaiser_sinc_filter1d(cutoff, half_width, kernel_size)
self.register_buffer("filter", filter)
def forward(self, x):
_, C, _ = x.shape
if self.padding:
x = F.pad(x, (self.pad_left, self.pad_right), mode=self.padding_mode)
out = F.conv1d(x, self.filter.expand(C, -1, -1), stride=self.stride, groups=C)
return out
class UpSample1d(nn.Module):
def __init__(self, ratio=2, kernel_size=None):
super().__init__()
self.ratio = ratio
self.kernel_size = int(6 * ratio // 2) * 2 if kernel_size is None else kernel_size
self.stride = ratio
self.pad = self.kernel_size // ratio - 1
self.pad_left = self.pad * self.stride + (self.kernel_size - self.stride) // 2
self.pad_right = self.pad * self.stride + (self.kernel_size - self.stride + 1) // 2
filter = kaiser_sinc_filter1d(cutoff=0.5 / ratio, half_width=0.6 / ratio, kernel_size=self.kernel_size)
self.register_buffer("filter", filter)
def forward(self, x):
_, C, _ = x.shape
x = F.pad(x, (self.pad, self.pad), mode="replicate")
x = self.ratio * F.conv_transpose1d(x, self.filter.expand(C, -1, -1), stride=self.stride, groups=C)
x = x[..., self.pad_left : -self.pad_right]
return x
class DownSample1d(nn.Module):
def __init__(self, ratio=2, kernel_size=None):
super().__init__()
self.ratio = ratio
self.kernel_size = int(6 * ratio // 2) * 2 if kernel_size is None else kernel_size
self.lowpass = LowPassFilter1d(
cutoff=0.5 / ratio, half_width=0.6 / ratio, stride=ratio, kernel_size=self.kernel_size
)
def forward(self, x):
return self.lowpass(x)
class Activation1d(nn.Module):
def __init__(
self, activation, up_ratio: int = 2, down_ratio: int = 2, up_kernel_size: int = 12, down_kernel_size: int = 12
):
super().__init__()
self.up_ratio = up_ratio
self.down_ratio = down_ratio
self.act = activation
self.upsample = UpSample1d(up_ratio, up_kernel_size)
self.downsample = DownSample1d(down_ratio, down_kernel_size)
def forward(self, x):
x = self.upsample(x)
x = self.act(x)
x = self.downsample(x)
return x
# LowPassFilter1d, UpSample1d, DownSample1d, Activation1d removed —
# now provided by common.alias_free_activation.AliasFreeActivation1d
# --------------- Activations ---------------
class SnakeBeta(nn.Module):
def __init__(self, in_features, alpha=1.0, alpha_trainable=True, alpha_logscale=False):
super().__init__()
self.in_features = in_features
self.alpha_logscale = alpha_logscale
if self.alpha_logscale:
self.alpha = Parameter(torch.zeros(in_features) * alpha)
self.beta = Parameter(torch.zeros(in_features) * alpha)
else:
self.alpha = Parameter(torch.ones(in_features) * alpha)
self.beta = Parameter(torch.ones(in_features) * alpha)
self.alpha.requires_grad = alpha_trainable
self.beta.requires_grad = alpha_trainable
self.no_div_by_zero = 0.000000001
def forward(self, x):
alpha = self.alpha.unsqueeze(0).unsqueeze(-1)
beta = self.beta.unsqueeze(0).unsqueeze(-1)
if self.alpha_logscale:
alpha = torch.exp(alpha)
beta = torch.exp(beta)
x = x + (1.0 / (beta + self.no_div_by_zero)) * pow(sin(x * alpha), 2)
return x
# SnakeBeta removed — now in common.snake_activation (with alpha_logscale support)
# --------------- Attention ---------------
@@ -828,7 +693,7 @@ class AMPBlock1(torch.nn.Module):
self.activations = nn.ModuleList(
[
Activation1d(activation=SnakeBeta(channels, alpha_logscale=h.snake_logscale))
AliasFreeActivation1d(activation=SnakeBeta(channels, alpha_logscale=h.snake_logscale))
for _ in range(self.num_layers)
]
)
@@ -882,7 +747,7 @@ class BigVGANFlowVAE(nn.Module):
self.resblocks.append(AMPBlock1(h, ch, k, d, causal=causal))
activation_post = SnakeBeta(ch, alpha_logscale=h.snake_logscale)
self.activation_post = Activation1d(activation=activation_post)
self.activation_post = AliasFreeActivation1d(activation=activation_post)
self.conv_post = weight_norm(Conv1d(ch, 1, 7, 1, causal=causal))
@@ -11,6 +11,7 @@ Install with: ``pip install fish-speech``
from __future__ import annotations
import inspect
import os
from collections.abc import Iterable
from typing import Any
@@ -33,6 +34,41 @@ from vllm_omni.model_executor.models.output_templates import OmniOutput
logger = init_logger(__name__)
def _connector_extra_config(vllm_config: VllmConfig) -> dict[str, Any]:
model_config = getattr(vllm_config, "model_config", None)
connector_cfg = getattr(model_config, "stage_connector_config", None)
if isinstance(connector_cfg, dict):
return connector_cfg.get("extra", connector_cfg)
extra = getattr(connector_cfg, "extra", None)
return extra if isinstance(extra, dict) else {}
def _get_int_config(extra_cfg: dict[str, Any], default: int, *names: str) -> int:
value = None
for name in names:
if name in extra_cfg:
value = extra_cfg[name]
break
if value is None:
return default
try:
return max(0, int(value))
except (TypeError, ValueError) as exc:
raise ValueError(f"Invalid Fish Speech DAC integer config {names[0]}={value!r}") from exc
def _get_dac_dtype(extra_cfg: dict[str, Any]) -> torch.dtype:
value = extra_cfg.get("fish_speech_dac_dtype", "float32")
value = str(value).strip().lower()
if value in {"fp16", "float16", "half"}:
return torch.float16
if value in {"bf16", "bfloat16"}:
return torch.bfloat16
if value in {"fp32", "float32", ""}:
return torch.float32
raise ValueError(f"Invalid Fish Speech DAC dtype: {value!r}")
class FishSpeechDACDecoder(nn.Module):
"""Stage-1 DAC decoder for Fish Speech S2 Pro (GenerationModelRunner).
@@ -58,6 +94,43 @@ class FishSpeechDACDecoder(nn.Module):
self._output_sample_rate: int = DAC_SAMPLE_RATE
self._hop_length: int = DAC_HOP_LENGTH
self._logged_codec_stats = False
self._codec_decode_takes_lengths: bool | None = None
extra_cfg = _connector_extra_config(vllm_config)
self._dac_dtype = _get_dac_dtype(extra_cfg)
self._decode_batch_max_padded_frames = _get_int_config(
extra_cfg,
0,
"fish_speech_dac_max_padded_frames",
"dac_max_padded_frames",
)
self._decode_batch_max_batch = _get_int_config(
extra_cfg,
0,
"fish_speech_dac_max_batch",
"dac_max_batch",
)
def _decode_codes(
self,
codes_bqf: torch.Tensor,
feature_lengths: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
assert self._codec is not None
if self._codec_decode_takes_lengths:
return self._codec.decode(codes_bqf, feature_lengths)
if hasattr(self._codec, "from_indices"):
wav_batch = self._codec.from_indices(codes_bqf)
else:
wav_batch = self._codec.decode(codes_bqf)
max_frames = max(int(codes_bqf.shape[-1]), 1)
scale = wav_batch.shape[-1] / max_frames
audio_lengths = torch.clamp(
torch.round(feature_lengths.to(torch.float32) * scale).to(torch.long),
min=0,
max=wav_batch.shape[-1],
)
return wav_batch, audio_lengths
def _bake_weight_norm(self, codec: nn.Module) -> None:
baked = 0
@@ -149,14 +222,16 @@ class FishSpeechDACDecoder(nn.Module):
codec.quantizer.downsample = None
device = self.vllm_config.device_config.device
codec = codec.to(device=device, dtype=torch.float32)
codec = codec.to(device=device, dtype=self._dac_dtype)
codec.eval()
self._codec = codec
self._codec_decode_takes_lengths = len(inspect.signature(codec.decode).parameters) >= 2
logger.info(
"Fish Speech DAC codec loaded from %s (device=%s, sample_rate=%d)",
"Fish Speech DAC codec loaded from %s (device=%s, dtype=%s, sample_rate=%d)",
codec_path,
device,
self._dac_dtype,
self._output_sample_rate,
)
@@ -188,6 +263,28 @@ class FishSpeechDACDecoder(nn.Module):
return [ids[boundaries[i] : boundaries[i + 1]] for i in range(len(boundaries) - 1)]
return [ids]
def _codes_from_runtime_info(
self,
info: dict[str, Any] | None,
device: torch.device,
) -> torch.Tensor | None:
if not isinstance(info, dict):
return None
codes = info.get("codes", {}).get("audio")
if not isinstance(codes, torch.Tensor) or codes.numel() == 0:
return None
q = self._num_codebooks
codes = codes.to(device=device, dtype=torch.long, non_blocking=True).contiguous()
if codes.ndim != 2 or codes.shape[0] != q:
logger.warning(
"DAC tensor codes must have shape [num_codebooks, frames], got %s for num_codebooks=%d.",
tuple(codes.shape),
q,
)
return None
return codes
@torch.no_grad()
def forward(
self,
@@ -203,14 +300,14 @@ class FishSpeechDACDecoder(nn.Module):
input_ids layout per request: flat codes [num_codebooks * num_frames].
Codes are codebook-major: [cb0_f0, cb0_f1, ..., cb0_fN, cb1_f0, ...].
"""
self._ensure_codec_loaded()
assert self._codec is not None
q = self._num_codebooks
sr_val = self._output_sample_rate
sr_tensor = torch.tensor(sr_val, dtype=torch.int32)
empty = torch.zeros((0,), dtype=torch.float32)
self._ensure_codec_loaded()
assert self._codec is not None
if input_ids is None or input_ids.numel() == 0:
return OmniOutput(
text_hidden_states=None,
@@ -235,9 +332,22 @@ class FishSpeechDACDecoder(nn.Module):
left_context_size[i] = meta["left_context_size"]
for i, req_ids in enumerate(request_ids_list):
ctx_frames = left_context_size[i]
runtime_codes = (
self._codes_from_runtime_info(runtime_additional_information[i], ids.device)
if runtime_additional_information is not None and i < len(runtime_additional_information)
else None
)
if runtime_codes is not None:
frames = runtime_codes.shape[1]
parsed_ctx_frames[i] = ctx_frames
parsed_total_frames[i] = frames
valid_codes_qf.append(runtime_codes)
valid_indices.append(i)
continue
if req_ids.numel() < 1:
continue
ctx_frames = left_context_size[i]
flat = req_ids
n = flat.numel()
if n == 0 or n % q != 0:
@@ -279,25 +389,61 @@ class FishSpeechDACDecoder(nn.Module):
except Exception:
pass
feature_lengths = torch.tensor(
[codes_qf.shape[1] for codes_qf in valid_codes_qf],
device=valid_codes_qf[0].device,
dtype=torch.long,
)
max_frames = int(feature_lengths.max().item())
batch_size = len(valid_codes_qf)
wav_tensors: list[torch.Tensor | None] = [None] * len(valid_codes_qf)
codes_bqf = torch.zeros(
(batch_size, q, max_frames),
device=valid_codes_qf[0].device,
dtype=torch.long,
)
for i, codes_qf in enumerate(valid_codes_qf):
frame_count = int(feature_lengths[i].item())
codes_bqf[i, :, :frame_count] = codes_qf
def _iter_bounded_groups(group: list[tuple[int, torch.Tensor]]) -> Iterable[list[tuple[int, torch.Tensor]]]:
max_padded_frames = int(getattr(self, "_decode_batch_max_padded_frames", 0))
max_batch = int(getattr(self, "_decode_batch_max_batch", 0))
if max_padded_frames <= 0 and max_batch <= 0:
yield group
return
with torch.amp.autocast("cuda", enabled=False):
wav_batch, audio_lengths = self._codec.decode(codes_bqf, feature_lengths)
current: list[tuple[int, torch.Tensor]] = []
current_max_frames = 0
for item in sorted(group, key=lambda pair: int(pair[1].shape[1])):
frames = int(item[1].shape[1])
next_max_frames = max(current_max_frames, frames)
next_batch_size = len(current) + 1
exceeds_batch = max_batch > 0 and next_batch_size > max_batch
exceeds_work = max_padded_frames > 0 and next_batch_size * next_max_frames > max_padded_frames
if current and (exceeds_batch or exceeds_work):
yield current
current = [item]
current_max_frames = frames
else:
current.append(item)
current_max_frames = next_max_frames
if current:
yield current
def _decode_group(group: list[tuple[int, torch.Tensor]]) -> None:
actual_frames = [int(codes_qf.shape[1]) for _, codes_qf in group]
target_frames = max(actual_frames)
batch_size = len(group)
first_codes = group[0][1]
feature_lengths = torch.tensor(actual_frames, device=first_codes.device, dtype=torch.long)
codes_bqf = torch.zeros(
(batch_size, q, target_frames),
device=first_codes.device,
dtype=torch.long,
)
for row, (_, codes_qf) in enumerate(group):
frame_count = int(codes_qf.shape[1])
codes_bqf[row, :, :frame_count] = codes_qf
with torch.amp.autocast("cuda", enabled=False):
wav_batch, audio_lengths = self._decode_codes(codes_bqf, feature_lengths)
audio_lengths_list = (
audio_lengths.detach().to(device="cpu", dtype=torch.long).reshape(-1).tolist()
if audio_lengths.numel() > 0
else []
)
for row, (j, _) in enumerate(group):
audio_len = int(audio_lengths_list[row]) if len(audio_lengths_list) > row else int(wav_batch.shape[-1])
wav_tensors[j] = wav_batch[row, 0, :audio_len]
for bounded_group in _iter_bounded_groups(list(enumerate(valid_codes_qf))):
_decode_group(bounded_group)
audios: list[torch.Tensor] = [empty] * num_req
srs = [sr_tensor] * num_req
@@ -305,8 +451,8 @@ class FishSpeechDACDecoder(nn.Module):
for j, idx in enumerate(valid_indices):
ctx_frames = parsed_ctx_frames[idx]
total_frames = parsed_total_frames[idx]
audio_len = int(audio_lengths[j].item()) if audio_lengths.numel() > j else int(wav_batch.shape[-1])
wav = wav_batch[j, 0, :audio_len]
wav = wav_tensors[j]
assert wav is not None
# Trim context frames (left overlap for streaming).
if ctx_frames > 0:
# Decode length may deviate from (frames * hop_length) due to model
@@ -4,14 +4,13 @@
autoregressively after each Slow AR step. Analogous to Qwen3 TTS's
CodePredictor but with its own embedding table, RoPE, and output head.
Uses re-prefill (no KV cache): each AR step forwards the full growing
sequence through the 4-layer transformer. This trades ~O(T^2) attention
FLOPs (negligible for T=10, 4 layers) for zero KV cache management.
Uses a tiny per-call KV cache: each AR step forwards one codebook token while
reusing the previous Fast AR keys/values.
Optimisations:
- torch.compile on model forward (kernel fusion)
- Pre-allocated projection / embedding buffer
- Pre-allocated position_ids
- Pre-allocated per-layer KV cache for the short codebook loop
- Inline sampling
"""
@@ -51,7 +50,8 @@ logger = init_logger(__name__)
class _FastARAttention(nn.Module):
"""Multi-head attention using F.scaled_dot_product_attention (SDPA).
Supports fused QKV, RoPE, optional q/k normalization, and native GQA.
Supports fused QKV, RoPE, optional q/k normalization, native GQA, and a
small one-token decode path for the residual codebook loop.
Input: [B, seq_len, hidden_size].
"""
@@ -124,6 +124,43 @@ class _FastARAttention(nn.Module):
output, _ = self.o_proj(attn_out)
return output.view(bsz, seq_len, -1)
def forward_one(
self,
hidden_states: torch.Tensor,
position_ids: torch.Tensor,
k_cache: torch.Tensor,
v_cache: torch.Tensor,
cache_pos: int,
) -> torch.Tensor:
bsz = int(hidden_states.shape[0])
qkv, _ = self.qkv_proj(hidden_states.reshape(bsz, -1))
q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
if self.q_norm is not None:
q = self.q_norm(q.view(-1, self.num_heads, self.head_dim)).view(q.shape)
k = self.k_norm(k.view(-1, self.num_kv_heads, self.head_dim)).view(k.shape)
q, k = self.rotary_emb(position_ids.reshape(-1), q, k)
q = q.view(bsz, self.num_heads, self.head_dim).unsqueeze(2)
k = k.view(bsz, self.num_kv_heads, self.head_dim)
v = v.view(bsz, self.num_kv_heads, self.head_dim)
k_cache[:bsz, :, cache_pos, :] = k
v_cache[:bsz, :, cache_pos, :] = v
attn_out = F.scaled_dot_product_attention(
q,
k_cache[:bsz, :, : cache_pos + 1, :],
v_cache[:bsz, :, : cache_pos + 1, :],
scale=self.scaling,
is_causal=False,
enable_gqa=self._use_gqa,
)
attn_out = attn_out.transpose(1, 2).reshape(bsz, -1)
output, _ = self.o_proj(attn_out)
return output
class _FastARMLP(nn.Module):
"""SiLU-gated MLP, matching Qwen3/LLaMA MLP structure."""
@@ -175,6 +212,25 @@ class _FastARDecoderLayer(nn.Module):
hidden_states = residual + hidden_states
return hidden_states
def forward_one(
self,
hidden_states: torch.Tensor,
position_ids: torch.Tensor,
k_cache: torch.Tensor,
v_cache: torch.Tensor,
cache_pos: int,
) -> torch.Tensor:
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
hidden_states = self.self_attn.forward_one(hidden_states, position_ids, k_cache, v_cache, cache_pos)
hidden_states = residual + hidden_states
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
# ===================================================================
# Fast AR Transformer Model
@@ -199,6 +255,25 @@ class FishSpeechFastARModel(nn.Module):
hidden_states = layer(hidden_states, position_ids)
return hidden_states
def forward_one(
self,
input_embed: torch.Tensor,
position_ids: torch.Tensor,
k_caches: torch.Tensor,
v_caches: torch.Tensor,
cache_pos: int,
) -> torch.Tensor:
hidden_states = input_embed
for layer_idx, layer in enumerate(self.layers):
hidden_states = layer.forward_one(
hidden_states,
position_ids,
k_caches[layer_idx],
v_caches[layer_idx],
cache_pos,
)
return hidden_states
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
stacked_params_mapping = [
("qkv_proj", "q_proj", "q"),
@@ -259,13 +334,13 @@ class FishSpeechFastARModel(nn.Module):
class FishSpeechFastAR(nn.Module):
"""vLLM-native Fast AR for Fish Speech (residual codebooks).
Re-prefill approach: each AR step forwards the full growing sequence
through the 4-layer transformer. No KV cache needed.
Decode approach: each residual-codebook step forwards one token through
the 4-layer transformer with a per-call KV cache.
Optimisations over baseline:
1. torch.compile on model forward -- kernel fusion.
2. Pre-allocated embedding buffer [B, max_seq, H].
3. Pre-allocated position_ids.
1. Pre-allocated embedding buffer [B, max_seq, H].
2. Pre-allocated position_ids.
3. Per-call KV cache for the short residual-codebook loop.
4. Inline sampling.
"""
@@ -307,6 +382,8 @@ class FishSpeechFastAR(nn.Module):
# Pre-allocated buffers (lazily initialised on first forward).
self._embed_buf: torch.Tensor | None = None
self._pos_ids: torch.Tensor | None = None
self._k_cache: torch.Tensor | None = None
self._v_cache: torch.Tensor | None = None
self._compiled_model_fwd: object | None = None
self._compile_attempted = False
self._compile_failed = False
@@ -316,13 +393,27 @@ class FishSpeechFastAR(nn.Module):
max_seq = self._num_codebooks + 1 # hidden_state + num_codebooks codes
if (
self._embed_buf is not None
and self._pos_ids is not None
and self._k_cache is not None
and self._v_cache is not None
and self._embed_buf.shape[0] >= bsz
and self._embed_buf.device == device
and self._embed_buf.dtype == dtype
and self._pos_ids.shape[0] >= bsz
and self._pos_ids.shape[1] == max_seq
and self._pos_ids.device == device
and self._k_cache.shape[1] >= bsz
and self._k_cache.device == device
and self._k_cache.dtype == dtype
):
return
self._embed_buf = torch.zeros(bsz, max_seq, self._fast_dim, dtype=dtype, device=device)
self._pos_ids = torch.arange(max_seq, dtype=torch.long, device=device)
self._pos_ids = torch.arange(max_seq, dtype=torch.long, device=device).unsqueeze(0).expand(bsz, -1).contiguous()
num_layers = self.config.num_hidden_layers
num_kv_heads = self.config.num_key_value_heads
head_dim = self.config.head_dim
self._k_cache = torch.empty(num_layers, bsz, num_kv_heads, max_seq, head_dim, dtype=dtype, device=device)
self._v_cache = torch.empty_like(self._k_cache)
def _setup_compile(self) -> None:
if self._compile_attempted:
@@ -375,20 +466,10 @@ class FishSpeechFastAR(nn.Module):
torch.accelerator.synchronize(device)
@torch.inference_mode()
def _run_model(self, step_input: torch.Tensor, step_pos_ids: torch.Tensor, bsz: int) -> torch.Tensor:
if self._disable_compile_for_graph:
model_fwd = self._compiled_model_fwd or self.model.forward
else:
model_fwd = self._compiled_model_fwd if bsz == 1 else self.model.forward
try:
return model_fwd(step_input, step_pos_ids)
except Exception as exc:
if model_fwd is self.model.forward or self._compile_failed:
raise
self._compile_failed = True
self._compiled_model_fwd = self.model.forward
logger.warning("Fish Speech Fast AR torch.compile fallback to eager after runtime failure: %s", exc)
return self.model.forward(step_input, step_pos_ids)
def _run_model_one(self, input_embed: torch.Tensor, step_pos_ids: torch.Tensor, cache_pos: int) -> torch.Tensor:
assert self._k_cache is not None
assert self._v_cache is not None
return self.model.forward_one(input_embed, step_pos_ids, self._k_cache, self._v_cache, cache_pos)
@torch.inference_mode()
def forward(
@@ -401,6 +482,7 @@ class FishSpeechFastAR(nn.Module):
top_k: int = 30,
top_p: float = 0.9,
seed: int | None = None,
generator: torch.Generator | None = None,
) -> torch.Tensor:
"""Predict residual codebook codes 0..num_codebooks-1 autoregressively.
@@ -428,7 +510,6 @@ class FishSpeechFastAR(nn.Module):
all_codes[:, 0] = semantic_code
self._ensure_buffers(bsz, device, dtype)
self._setup_compile()
embed_buf = self._embed_buf
pos_ids = self._pos_ids
@@ -445,8 +526,7 @@ class FishSpeechFastAR(nn.Module):
inv_temperature = 1.0 / max(temperature, 1e-6) if use_sampling else 0.0
# Create a seeded generator for deterministic residual codebook sampling.
generator = None
if seed is not None and use_sampling:
if generator is None and seed is not None and use_sampling:
generator = torch.Generator(device=device)
generator.manual_seed(seed)
@@ -455,15 +535,11 @@ class FishSpeechFastAR(nn.Module):
# codebooks only have 1024 entries. Truncate logits for steps > 0.
residual_codebook_size = 1024
for step in range(1, num_cb):
seq_len = step + 1
step_input = embed_buf[:bsz, :seq_len, :]
# Use a dense 2D position tensor for every batch size; stride-0
# views from expand() were fragile under compiled execution.
step_pos_ids = pos_ids[:seq_len].unsqueeze(0).repeat(bsz, 1)
self._run_model_one(embed_buf[:bsz, 0, :], pos_ids[:bsz, 0], 0)
hidden_out = self._run_model(step_input, step_pos_ids, bsz)
logits = self.fast_output(self.fast_norm(hidden_out[:, -1, :]))
for step in range(1, num_cb):
hidden_out = self._run_model_one(embed_buf[:bsz, step, :], pos_ids[:bsz, step], step)
logits = self.fast_output(self.fast_norm(hidden_out))
# Residual codebooks (step >= 1) only have 1024 entries.
if step >= 1:
@@ -199,6 +199,12 @@ class FishSpeechSlowARForConditionalGeneration(nn.Module):
# Qwen3 transformer backbone.
self.model = Qwen3Model(vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model"))
from vllm_omni.attention.fish_kvcache_attn import is_fish_kvcache_attn_enabled
if is_fish_kvcache_attn_enabled():
from vllm_omni.attention.fish_kvcache_backend import install_fish_kvcache_attn_backend
install_fish_kvcache_attn_backend(self.model)
# Fish Speech uses interleaved (GPT-J) RoPE, not NeoX style.
# vLLM's Qwen3Attention defaults to NeoX (is_neox_style=True).
@@ -672,14 +678,19 @@ class FishSpeechSlowARForConditionalGeneration(nn.Module):
past_hidden = last_talker_hidden.reshape(bsz, -1).to(dtype=torch.bfloat16, device=dev)
# Run Fast AR to predict all num_codebooks codes.
do_sample = kwargs.get("do_sample")
temperature = kwargs.get("temperature")
top_k = kwargs.get("top_k")
top_p = kwargs.get("top_p")
audio_codes = self.fast_ar(
slow_ar_hidden=past_hidden,
semantic_token_id=input_ids.reshape(bsz),
do_sample=True,
temperature=0.8,
top_k=30,
top_p=0.9,
do_sample=True if do_sample is None else bool(do_sample),
temperature=0.8 if temperature is None else float(temperature),
top_k=30 if top_k is None else int(top_k),
top_p=0.9 if top_p is None else float(top_p),
seed=seed,
generator=kwargs.get("generator"),
) # [B, num_codebooks]
# Add codebook embeddings to the input embedding (from preprocess).
@@ -0,0 +1,18 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""GLM-TTS model support for vLLM-Omni.
GLM-TTS is a two-stage text-to-speech system:
- Stage 0 (LLM): Llama-based AR model generates speech tokens from text
- Stage 1 (DiT): Flow matching model converts speech tokens to mel-spectrogram
Reference: https://github.com/zai-org/GLM-TTS
"""
from vllm_omni.model_executor.models.glm_tts.glm_tts import (
GLMTTSForConditionalGeneration,
)
__all__ = [
"GLMTTSForConditionalGeneration",
]
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,650 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""GLM-TTS DiT (Diffusion Transformer) Model.
Flow Matching model that converts speech tokens to mel-spectrogram.
Ported from: https://github.com/zai-org/GLM-TTS/blob/main/flow/dit.py
"""
from __future__ import annotations
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from x_transformers.x_transformers import RotaryEmbedding, apply_rotary_pos_emb
from vllm_omni.diffusion.attention.layer import Attention as DiffusionAttention
def precompute_freqs_cis(dim: int, end: int, theta: float = 10000.0, theta_rescale_factor: float = 1.0):
"""Precompute Rotary Positional Embeddings (RoPE)."""
theta *= theta_rescale_factor ** (dim / (dim - 2))
freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
t = torch.arange(end, device=freqs.device)
freqs = torch.outer(t, freqs).float()
freqs_cos = torch.cos(freqs)
freqs_sin = torch.sin(freqs)
return torch.cat([freqs_cos, freqs_sin], dim=-1)
def get_pos_embed_indices(start, length, max_pos, scale=1.0):
"""Get position embedding indices."""
scale = scale * torch.ones_like(start, dtype=torch.float32)
pos = (
start.unsqueeze(1)
+ (torch.arange(length, device=start.device, dtype=torch.float32).unsqueeze(0) * scale.unsqueeze(1)).long()
)
pos = torch.where(pos < max_pos, pos, max_pos - 1)
return pos
class SinusPositionEmbedding(nn.Module):
"""Sinusoidal position embedding for timesteps."""
def __init__(self, dim: int):
super().__init__()
self.dim = dim
def forward(self, x: torch.Tensor, scale: float = 1000) -> torch.Tensor:
device = x.device
half_dim = self.dim // 2
emb = math.log(10000) / (half_dim - 1)
emb = torch.exp(torch.arange(half_dim, device=device).float() * -emb)
emb = scale * x.unsqueeze(1) * emb.unsqueeze(0)
emb = torch.cat((emb.sin(), emb.cos()), dim=-1)
return emb
class TimestepEmbedding(nn.Module):
"""Timestep embedding with MLP."""
def __init__(self, dim: int, freq_embed_dim: int = 256):
super().__init__()
self.time_embed = SinusPositionEmbedding(freq_embed_dim)
self.time_mlp = nn.Sequential(nn.Linear(freq_embed_dim, dim), nn.SiLU(), nn.Linear(dim, dim))
def forward(self, timestep: torch.Tensor) -> torch.Tensor:
time_hidden = self.time_embed(timestep)
# Cast to model weight dtype (bfloat16) not input dtype (may be float32)
weight_dtype = self.time_mlp[0].weight.dtype
time_hidden = time_hidden.to(weight_dtype)
return self.time_mlp(time_hidden)
class GRN(nn.Module):
"""Global Response Normalization layer."""
def __init__(self, dim: int):
super().__init__()
self.gamma = nn.Parameter(torch.zeros(1, 1, dim))
self.beta = nn.Parameter(torch.zeros(1, 1, dim))
def forward(self, x: torch.Tensor) -> torch.Tensor:
gx = torch.norm(x, p=2, dim=1, keepdim=True)
nx = gx / (gx.mean(dim=-1, keepdim=True) + 1e-6)
return self.gamma * (x * nx) + self.beta + x
class ConvNeXtV2Block(nn.Module):
"""ConvNeXt-V2 Block for text embedding."""
def __init__(self, dim: int, intermediate_dim: int, dilation: int = 1):
super().__init__()
padding = (dilation * (7 - 1)) // 2
self.dwconv = nn.Conv1d(dim, dim, kernel_size=7, padding=padding, groups=dim, dilation=dilation)
self.norm = nn.LayerNorm(dim, eps=1e-6)
self.pwconv1 = nn.Linear(dim, intermediate_dim)
self.act = nn.GELU()
self.grn = GRN(intermediate_dim)
self.pwconv2 = nn.Linear(intermediate_dim, dim)
def forward(self, x: torch.Tensor) -> torch.Tensor:
residual = x
x = x.transpose(1, 2)
x = self.dwconv(x)
x = x.transpose(1, 2)
x = self.norm(x)
x = self.pwconv1(x)
x = self.act(x)
x = self.grn(x)
x = self.pwconv2(x)
return residual + x
class ConvPositionEmbedding(nn.Module):
"""Convolutional position embedding."""
def __init__(self, dim: int, kernel_size: int = 31, groups: int = 16):
super().__init__()
if kernel_size % 2 == 0:
raise ValueError(f"kernel_size must be odd, got {kernel_size}")
self.conv1d = nn.Sequential(
nn.Conv1d(dim, dim, kernel_size, groups=groups, padding=kernel_size // 2),
nn.Mish(),
nn.Conv1d(dim, dim, kernel_size, groups=groups, padding=kernel_size // 2),
nn.Mish(),
)
def forward(self, x: torch.Tensor, mask: torch.Tensor | None = None) -> torch.Tensor:
if mask is not None:
mask = mask[..., None]
x = x.masked_fill(~mask, 0.0)
x = rearrange(x, "b n d -> b d n")
x = self.conv1d(x)
out = rearrange(x, "b d n -> b n d")
if mask is not None:
out = out.masked_fill(~mask, 0.0)
return out
class TextEmbedding(nn.Module):
"""Text/speech token embedding with optional ConvNeXt modeling."""
def __init__(
self,
text_num_embeds: int,
output_dim: int,
conv_layers: int = 0,
conv_mult: int = 2,
length_align: str = "fill",
):
super().__init__()
self.pad_id = int(text_num_embeds)
self.text_embed = nn.Embedding(text_num_embeds + 1, output_dim, padding_idx=self.pad_id)
self.length_align = length_align
if conv_layers > 0:
self.extra_modeling = True
self.precompute_max_pos = 4096
self.register_buffer(
"freqs_cis", precompute_freqs_cis(output_dim, self.precompute_max_pos), persistent=False
)
self.text_blocks = nn.Sequential(
*[ConvNeXtV2Block(output_dim, output_dim * conv_mult) for _ in range(conv_layers)]
)
else:
self.extra_modeling = False
def forward(
self,
text: torch.Tensor,
aim_seq_len: int,
text_lens: torch.Tensor | None = None,
) -> torch.Tensor:
batch, text_len = text.shape[0], text.shape[1]
if self.length_align == "fill":
text = text[:, :aim_seq_len]
text = F.pad(text, (0, aim_seq_len - min(text_len, aim_seq_len)), value=self.pad_id)
elif self.length_align == "interpolate_token":
if text_lens is None:
text = (
F.interpolate(
text.unsqueeze(1).float(),
size=aim_seq_len,
mode="nearest",
)
.squeeze(1)
.long()
)
else:
text_lens = text_lens.to(device=text.device, dtype=torch.long)
text_lens = torch.clamp(text_lens, min=1, max=text_len)
positions = torch.arange(aim_seq_len, device=text.device, dtype=torch.long)
src_idx = positions.unsqueeze(0) * text_lens.unsqueeze(1) // int(aim_seq_len)
src_idx = torch.minimum(src_idx, (text_lens - 1).unsqueeze(1))
text = torch.gather(text, dim=1, index=src_idx)
elif self.length_align != "interpolate_feature":
raise ValueError(f"Unsupported length_align={self.length_align!r}")
hidden = self.text_embed(text)
if self.length_align == "interpolate_feature":
hidden = F.interpolate(
hidden.permute(0, 2, 1),
size=aim_seq_len,
mode="nearest",
).permute(0, 2, 1)
if self.extra_modeling:
# Get model dtype from text_blocks weights
model_dtype = self.text_blocks[0].dwconv.weight.dtype
hidden = hidden.to(model_dtype)
batch_start = torch.zeros((batch,), dtype=torch.long, device=text.device)
pos_idx = get_pos_embed_indices(batch_start, aim_seq_len, max_pos=self.precompute_max_pos)
text_pos_embed = self.freqs_cis[pos_idx].to(model_dtype)
hidden = hidden + text_pos_embed
hidden = self.text_blocks(hidden)
return hidden
class EmbeddingConcater(nn.Module):
"""Concatenates and projects noisy audio, condition, and text embeddings."""
def __init__(self, in_dim: int, out_dim: int):
super().__init__()
self.proj = nn.Linear(in_dim, out_dim)
self.conv_pos_embed = ConvPositionEmbedding(dim=out_dim)
def forward(
self,
x: torch.Tensor,
cond: torch.Tensor,
text_embed: torch.Tensor,
drop_audio_cond: bool = False,
) -> torch.Tensor:
if drop_audio_cond:
cond = torch.zeros_like(cond)
x = self.proj(torch.cat((x, cond, text_embed), dim=-1))
x = self.conv_pos_embed(x) + x
return x
class AdaLayerNormZero(nn.Module):
"""Adaptive LayerNorm with modulation from time/condition embedding."""
def __init__(self, dim: int, additional_dim: int = 0):
super().__init__()
self.silu = nn.SiLU()
self.linear = nn.Linear(dim + additional_dim, dim * 6)
self.norm = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
def forward(self, x: torch.Tensor, emb: torch.Tensor):
emb = self.linear(self.silu(emb))
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = torch.chunk(emb, 6, dim=1)
x = self.norm(x) * (1 + scale_msa[:, None]) + shift_msa[:, None]
return x, gate_msa, shift_mlp, scale_mlp, gate_mlp
class AdaLayerNormZeroFinal(nn.Module):
"""Adaptive LayerNorm for final layer."""
def __init__(self, dim: int, additional_dim: int = 0):
super().__init__()
self.silu = nn.SiLU()
self.linear = nn.Linear(dim + additional_dim, dim * 2)
self.norm = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
def forward(self, x: torch.Tensor, emb: torch.Tensor) -> torch.Tensor:
emb = self.linear(self.silu(emb))
scale, shift = torch.chunk(emb, 2, dim=1)
x = self.norm(x) * (1 + scale)[:, None, :] + shift[:, None, :]
return x
class FeedForward(nn.Module):
"""Feed-forward network with GELU activation.
Matches original GLM-TTS structure with nested Sequential for checkpoint compatibility.
Weight paths: ff.ff.0.0.* (first Linear), ff.ff.2.* (second Linear)
"""
def __init__(self, dim: int, dim_out: int | None = None, mult: int = 4, dropout: float = 0.0):
super().__init__()
inner_dim = int(dim * mult)
dim_out = dim_out if dim_out is not None else dim
# Nested structure to match original checkpoint paths
project_in = nn.Sequential(
nn.Linear(dim, inner_dim),
nn.GELU(approximate="tanh"),
)
self.ff = nn.Sequential(
project_in,
nn.Dropout(dropout),
nn.Linear(inner_dim, dim_out),
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.ff(x)
class DiTAttention(nn.Module):
"""Attention module using diffusion infrastructure."""
def __init__(self, dim: int, heads: int = 8, dim_head: int = 64, dropout: float = 0.0):
super().__init__()
self.dim = dim
self.heads = heads
self.dim_head = dim_head
self.inner_dim = dim_head * heads
self.scale = 1.0 / math.sqrt(dim_head)
self.to_q = nn.Linear(dim, self.inner_dim)
self.to_k = nn.Linear(dim, self.inner_dim)
self.to_v = nn.Linear(dim, self.inner_dim)
self.to_out = nn.Sequential(nn.Linear(self.inner_dim, dim), nn.Dropout(dropout))
self.attn = DiffusionAttention(
num_heads=heads,
head_size=dim_head,
softmax_scale=self.scale,
causal=False,
)
def forward(
self,
x: torch.Tensor,
padding_mask: torch.Tensor | None = None,
rope=None,
attn_mask: torch.Tensor | None = None,
) -> torch.Tensor:
batch_size, seq_len = x.shape[0], x.shape[1]
query = self.to_q(x)
key = self.to_k(x)
value = self.to_v(x)
# Apply RoPE
if rope is not None:
freqs, xpos_scale = rope
q_xpos_scale, k_xpos_scale = (xpos_scale, xpos_scale**-1.0) if xpos_scale is not None else (1.0, 1.0)
query = apply_rotary_pos_emb(query, freqs, q_xpos_scale)
key = apply_rotary_pos_emb(key, freqs, k_xpos_scale)
# Reshape for attention
query = query.view(batch_size, seq_len, self.heads, self.dim_head)
key = key.view(batch_size, seq_len, self.heads, self.dim_head)
value = value.view(batch_size, seq_len, self.heads, self.dim_head)
# Block-causal mask requires arbitrary 2D attention mask which
# FlashAttention does not support. Fall back to PyTorch SDPA
# (matches official GLM-TTS flow/modules.py:272).
if attn_mask is not None:
q = query.permute(0, 2, 1, 3) # [B, H, T, D]
k = key.permute(0, 2, 1, 3)
v = value.permute(0, 2, 1, 3)
out = F.scaled_dot_product_attention(
q,
k,
v,
attn_mask=attn_mask,
dropout_p=0.0,
is_causal=False,
)
out = out.permute(0, 2, 1, 3) # [B, T, H, D]
else:
out = self.attn(query, key, value, attn_metadata=None)
out = out.view(batch_size, seq_len, self.inner_dim)
out = out.to(query.dtype)
out = self.to_out(out)
# Apply padding mask
if padding_mask is not None:
padding_mask = rearrange(padding_mask, "b 1 n -> b n 1").bool()
out = out.masked_fill(~padding_mask, 0.0)
return out
class DiTBlock(nn.Module):
"""DiT block with AdaLayerNorm modulation."""
def __init__(
self,
dim: int,
heads: int,
dim_head: int,
ff_mult: int = 4,
dropout: float = 0.1,
additional_condition_dim: int = 0,
):
super().__init__()
self.attn_norm = AdaLayerNormZero(dim, additional_condition_dim)
self.attn = DiTAttention(dim=dim, heads=heads, dim_head=dim_head, dropout=dropout)
self.ff_norm = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
self.ff = FeedForward(dim=dim, mult=ff_mult, dropout=dropout)
def forward(
self,
x: torch.Tensor,
t: torch.Tensor,
padding_mask: torch.Tensor | None = None,
rope=None,
attn_mask: torch.Tensor | None = None,
) -> torch.Tensor:
# Pre-norm & modulation for attention
norm, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.attn_norm(x, emb=t)
# Attention
attn_output = self.attn(x=norm, padding_mask=padding_mask, rope=rope, attn_mask=attn_mask)
x = x + gate_msa.unsqueeze(1) * attn_output
# FeedForward
norm = self.ff_norm(x) * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
ff_output = self.ff(norm)
x = x + gate_mlp.unsqueeze(1) * ff_output
return x
class GLMTTSDiT(nn.Module):
"""GLM-TTS Diffusion Transformer.
Converts speech tokens to mel-spectrogram via flow matching.
"""
_repeated_blocks = ["DiTBlock"]
_layerwise_offload_blocks_attrs = ["transformer_blocks"]
def __init__(
self,
*,
trans_dim: int = 768,
depth: int = 18,
heads: int = 12,
dim_head: int = 64,
ff_mult: int = 2,
dropout: float = 0.1,
mel_dim: int = 80,
text_vocab_size: int = 100000,
text_emb_dim: int = 512,
conv_layers: int = 4,
condition_dim: int = 160, # mel_dim + spk_embed_dim
spkr_emb_adaln: bool = False,
spkr_dim: int = 192,
use_wavlm_emb: bool = False,
long_skip_connection: bool = False,
):
super().__init__()
self.time_embed = TimestepEmbedding(trans_dim)
self.text_emb_layer = TextEmbedding(
text_vocab_size,
text_emb_dim,
conv_layers=conv_layers,
length_align="interpolate_token",
)
in_dim = mel_dim + text_emb_dim + condition_dim
self.emb_concator = EmbeddingConcater(in_dim, trans_dim)
self.rotary_embed = RotaryEmbedding(dim_head)
self.dim = trans_dim
self.depth = depth
self.num_heads = heads
self.spkr_emb_adaln = spkr_emb_adaln
# Frame rates for block-causal mask token→mel conversion
self._input_frame_rate: float = 25.0
self._mel_framerate: float = 50.0
# Speaker embedding dimension for AdaLN
if spkr_emb_adaln:
additional_dim = spkr_dim + 256 if use_wavlm_emb else spkr_dim
else:
additional_dim = 0
self.transformer_blocks = nn.ModuleList(
[
DiTBlock(
dim=trans_dim,
heads=heads,
dim_head=dim_head,
ff_mult=ff_mult,
dropout=dropout,
additional_condition_dim=additional_dim,
)
for _ in range(depth)
]
)
self.long_skip_connection = nn.Linear(trans_dim * 2, trans_dim, bias=False) if long_skip_connection else None
self.norm_out = AdaLayerNormZeroFinal(trans_dim, additional_dim=additional_dim)
self.proj_out = nn.Linear(trans_dim, mel_dim)
# ------------------------------------------------------------------
# Block-causal attention mask (ported from GLM-TTS block_mask_util)
# ------------------------------------------------------------------
def _token_to_mel_size(self, token_count: int) -> int:
"""Convert token block size to mel-frame block size for streaming mask.
Matches upstream GLM-TTS ``flow/dit.py`` block-mask conversion.
This is intentionally separate from normal ``feat_len`` calculation,
which still follows ``input_frame_rate`` and ``mel_framerate``.
"""
return int(token_count / 12.5 * 22050 / 256)
def _create_block_causal_mask(
self,
block_pattern: list[int],
seq_len: int,
device: torch.device,
dtype: torch.dtype,
) -> torch.Tensor:
"""Build block-causal attention mask [1, 1, T, T].
Ported from GLM-TTS utils/block_mask_util.py ``create()``.
Each position can attend to its own block plus a look-ahead into
the next block (50% for small blocks, 66% for large blocks).
Vectorized via ``torch.searchsorted`` — no Python loop over T.
"""
import itertools
mel_blocks = [self._token_to_mel_size(b) for b in block_pattern]
# Extend with copies of the last block (enough for any seq_len)
extended = mel_blocks + [mel_blocks[-1]] * ((seq_len // max(mel_blocks[-1], 1)) + 2)
accum = list(itertools.accumulate(extended))
# Vectorized: map each position to its block index via searchsorted
accum_t = torch.tensor(accum, dtype=torch.long)
extended_t = torch.tensor(extended, dtype=torch.long)
positions = torch.arange(seq_len, dtype=torch.long)
# searchsorted(accum, positions, right=True) gives the block index
# for each position (accum is strictly increasing).
block_idx = torch.searchsorted(accum_t, positions, right=True)
# Per-position: block start, block size, position within block
block_start = torch.where(block_idx > 0, accum_t[block_idx - 1], torch.zeros_like(block_idx))
cur_block_size = extended_t[block_idx]
idx_in_block = positions - block_start
# Look-ahead: positions near the end of a block can see into the next
look_future = cur_block_size - 1 - idx_in_block
min_future = torch.where(
cur_block_size <= 172,
cur_block_size // 2,
(cur_block_size.float() / 1.5).long(),
)
delta = torch.clamp(min_future - look_future, min=0)
aim_len = torch.clamp(block_start + cur_block_size + delta, max=seq_len)
# Build mask: position i can attend to columns [0, aim_len[i])
col_idx = torch.arange(seq_len, device=device)
mask = col_idx.unsqueeze(0) < aim_len.unsqueeze(1).to(device)
# [1, 1, T, T] for broadcast across batch and heads
return mask.unsqueeze(0).unsqueeze(0)
def forward(
self,
middle_point: torch.Tensor,
condition: torch.Tensor,
text: torch.Tensor,
time_step: torch.Tensor,
padding_mask: torch.Tensor,
spkr_emb: torch.Tensor | None = None,
text_lens: torch.Tensor | None = None,
is_causal: bool = False,
attn_mask: torch.Tensor | None = None,
block_pattern: list[int] | None = None,
) -> torch.Tensor:
"""Forward pass.
Args:
middle_point: Noised audio tensor [B, T, mel_dim]
condition: Masked audio condition [B, T, condition_dim]
text: Speech token tensor [B, T_text]
time_step: Timestep tensor [B]
padding_mask: Padding mask [B, T]
spkr_emb: Speaker embedding [B, spkr_dim]
is_causal: Use block-causal attention
attn_mask: Custom attention mask (overrides is_causal)
block_pattern: Token-level block sizes for block-causal mask
Returns:
Predicted mel-spectrogram [B, T, mel_dim]
"""
# Cast floating inputs to model dtype (weights may be bfloat16)
model_dtype = self.proj_out.weight.dtype
middle_point = middle_point.to(model_dtype)
condition = condition.to(model_dtype)
time_step = time_step.to(model_dtype)
if spkr_emb is not None:
spkr_emb = spkr_emb.to(model_dtype)
_, seq_len = middle_point.shape[0], middle_point.shape[1]
# Time embedding
time_emb = self.time_embed(time_step)
# Concatenate speaker embedding if using AdaLN
if self.spkr_emb_adaln and spkr_emb is not None:
time_emb = torch.cat([time_emb, spkr_emb], dim=-1)
# Text embedding - ensure cast to model dtype
text_embed = self.text_emb_layer(text, seq_len, text_lens=text_lens).to(model_dtype)
# Input projection
x = self.emb_concator(middle_point, condition, text_embed, drop_audio_cond=False)
# Rotary embeddings
rope = self.rotary_embed.forward_from_seq_len(seq_len)
# Build block-causal mask when is_causal and no explicit attn_mask
if attn_mask is None and is_causal and block_pattern is not None:
attn_mask = self._create_block_causal_mask(
block_pattern,
seq_len,
middle_point.device,
model_dtype,
)
# Long skip connection
if self.long_skip_connection is not None:
residual = x
# Transformer blocks
for block in self.transformer_blocks:
x = block(x, time_emb, padding_mask=padding_mask.unsqueeze(1), rope=rope, attn_mask=attn_mask)
# Long skip connection
if self.long_skip_connection is not None:
x = self.long_skip_connection(torch.cat((x, residual), dim=-1))
# Output projection
x = self.norm_out(x, time_emb)
output = self.proj_out(x)
return output
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,46 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""GLM-TTS pipeline: Stage 0 (AR) → Stage 1 (DiT)."""
from vllm_omni.config.stage_config import (
PipelineConfig,
StageExecutionType,
StagePipelineConfig,
)
_PROC = "vllm_omni.model_executor.stage_input_processors.glm_tts"
GLM_TTS_PIPELINE = PipelineConfig(
model_type="glm_tts",
model_arch="GLMTTSForConditionalGeneration",
stages=(
StagePipelineConfig(
stage_id=0,
model_stage="glm_tts",
execution_type=StageExecutionType.LLM_AR,
input_sources=(),
owns_tokenizer=True,
engine_output_type="latent",
async_chunk_process_next_stage_input_func=(f"{_PROC}.ar_to_dit_async_chunk"),
sampling_constraints={
# GLM-TTS uses 👂 (token string "👂", ID 59253) as
# end-of-audio marker. The ID is resolved dynamically by
# GLMTTSForConditionalGeneration.__init__ from the tokenizer and
# validated at runtime against this hardcoded value. If the
# upstream checkpoint changes the mapping, the model will log a
# warning so the constant here can be updated.
"stop_token_ids": [59253],
},
),
StagePipelineConfig(
stage_id=1,
model_stage="glm_tts_dit",
execution_type=StageExecutionType.LLM_GENERATION,
input_sources=(0,),
final_output=True,
final_output_type="audio",
engine_output_type="latent",
sync_process_input_func=f"{_PROC}.ar_to_dit",
),
),
)
@@ -0,0 +1,393 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Lightweight text frontend aligned with the official GLM-TTS preprocessing."""
from __future__ import annotations
import json
import os
import re
try:
import emoji
except ImportError:
emoji = None # type: ignore[assignment]
try:
import inflect
except ImportError:
inflect = None # type: ignore[assignment]
try:
from tn.chinese.normalizer import Normalizer as ZhNormalizer
except ImportError:
ZhNormalizer = None
try:
from tn.english.normalizer import Normalizer as EnNormalizer
except ImportError:
EnNormalizer = None
CHINESE_CHAR_PATTERN = re.compile(r"[\u4e00-\u9fff]+")
PUNCTUATION_CHARS = r"。?!;:、.?!;:,,"
def contains_chinese(text: str) -> bool:
return bool(CHINESE_CHAR_PATTERN.search(text))
def markdown_norm(markdown_text: str) -> str:
markdown_text = re.sub(r"^(\d+)\. ", r"\1。", markdown_text)
return markdown_text.replace("\\n", "\n")
def multi_line_process(plain_text: str) -> str:
lines: list[str] = []
for line in plain_text.split("\n"):
line = line.strip()
if not line:
continue
if line[-1] not in {".", "!", "?", ";", ":", ":", "。", "!", "?", ";", ","}:
line = f"{line}{'。' if contains_chinese(line) else '. '}"
lines.append(line)
return "".join(lines) if contains_chinese("".join(lines)) else " ".join(lines)
def remove_bracket(text: str, lang: str = "zh") -> str:
brackets_to_remove = [
("(", ")"),
("(", ")"),
("【", "】"),
("「", "」"),
("`", "`"),
("《", "》"),
("『", "』"),
("{", "}"),
("[", "]"),
]
if lang != "en":
brackets_to_remove.append(("‘", "’"))
for left, right in brackets_to_remove:
text = text.replace(left, "").replace(right, "")
return text
def number_to_chinese(number: int | float | str) -> str:
units = ["", "十", "百", "千", "万", "十万", "百万", "千万", "亿", "十亿", "百亿", "千亿"]
nums = "零一二三四五六七八九"
if isinstance(number, (float, str)):
str_num = str(float(number))
if "." in str_num:
int_part, decimal_part = str_num.split(".")
if decimal_part.strip("0") == "":
return number_to_chinese(int(int_part))
chinese_int = number_to_chinese(int(int_part)) if int(int_part) != 0 else "零"
chinese_decimal = "".join(nums[int(d)] for d in decimal_part)
return f"{chinese_int}点{chinese_decimal}"
number = int(number)
if number == 0:
return "零"
if number < 0:
return "负" + number_to_chinese(abs(number))
result: list[str] = []
unit_position = 0
zero_flag = False
last_unit = ""
while number > 0:
num = number % 10
current_unit = units[unit_position] if unit_position < len(units) else ""
if num == 0:
if not zero_flag and result and last_unit not in ["万", "亿"]:
result.append(nums[num])
zero_flag = True
else:
if current_unit:
result.append(current_unit)
result.append(nums[num])
zero_flag = False
last_unit = current_unit
unit_position += 1
number //= 10
result.reverse()
text = "".join(result)
text = re.sub(r"^一十", "十", text)
text = re.sub(r"零+", "零", text)
text = re.sub(r"零$", "", text)
return text
def tn_scientific_notation(text: str) -> str:
pattern = re.compile(r"(.*?)(-?\d+(?:\.\d+)?)[*x×](\d+(?:\.\d+)?)\^(-?\d+(?:\.\d+)?)(.*?)$")
match = pattern.match(text)
if not match:
return text
prefix, base, multiplier, exponent, suffix = match.groups()
description = f"{number_to_chinese(base)}乘{number_to_chinese(multiplier)}的{number_to_chinese(exponent)}次方"
return f"{prefix}{description}{suffix}"
def replace_asterisk_with_multiply(text: str, lang: str) -> str:
if lang == "en":
replace_name = "multiply"
replace_number = "0-9"
else:
replace_name = "乘"
replace_number = "一二三四五六七八九十百千万亿"
rule0 = rf"(?<=[{replace_number}a-zA-Z])\s*\*\s*(?=[{replace_number}a-zA-Z])"
rule1 = rf"(?<=[{replace_number}a-zA-Z]\))\s*\*\s*(?=[{replace_number}a-zA-Z])"
rule2 = rf"(?<=[{replace_number}a-zA-Z])\s*\*\s*(?=\([{replace_number}a-zA-Z])"
rule3 = rf"(?<=[{replace_number}a-zA-Z]\))\s*\*\s*(?=\([{replace_number}a-zA-Z])"
return re.sub(f"{rule0}|{rule1}|{rule2}|{rule3}", replace_name, text).replace("*", "")
def special_replace(text: str) -> str:
text = text.replace("\\", "")
text = f" {text} "
text = re.sub(r"(?<=\W)额(?=\W)", "呃", text)
text = re.sub(r"[~~]+", "。", text)
text = replace_asterisk_with_multiply(text, "zh")
return text.strip()
def spell_out_number(text: str, inflect_parser: object | None) -> str:
if inflect_parser is None:
return text
new_text: list[str] = []
start = None
for idx, char in enumerate(text):
if not char.isdigit():
if start is not None:
new_text.append(inflect_parser.number_to_words(text[start:idx]))
start = None
new_text.append(char)
elif start is None:
start = idx
if start is not None and start < len(text):
new_text.append(inflect_parser.number_to_words(text[start:]))
return "".join(new_text)
def replace_space(text: str) -> str:
alphanumeric_pattern = r"[a-zA-Z0-9]"
punctuation_pattern = r"[.,!?;:]"
text = re.sub(r" +", " ", text)
result = ""
idx = 0
while idx < len(text):
current_char = text[idx]
if current_char != " ":
result += current_char
idx += 1
continue
prev_char = text[idx - 1] if idx > 0 else ""
next_char = text[idx + 1] if idx + 1 < len(text) else ""
if re.match(alphanumeric_pattern, prev_char) and re.match(alphanumeric_pattern, next_char):
result += " "
elif re.match(punctuation_pattern, prev_char) and re.match(alphanumeric_pattern, next_char):
result += " "
idx += 1
return result
def normalize_punctuation(text: str, punctuation_chars: str) -> str:
text = replace_space(text)
text = re.sub(rf"([{punctuation_chars}])\1+", r"\1", text)
text = re.sub(rf"([{punctuation_chars}])(?=[{punctuation_chars}])", "", text)
text = text.replace("#", "")
text = text.replace("!", "。")
text = text.replace("!", ".")
return text
def ensure_proper_ending(text: str) -> str:
if not text:
return text
if text[-1] in "??":
return text
if text[-1] in PUNCTUATION_CHARS:
return f"{text[:-1]}{'。' if contains_chinese(text) else '.'}"
return f"{text}{'。' if contains_chinese(text) else '.'}"
class GLMTTSTextFrontend:
"""Subset of the official GLM-TTS text frontend used by the adapter."""
def __init__(self) -> None:
self.inflect_parser = inflect.engine() if inflect is not None else None
self.zh_tn_model = (
ZhNormalizer(
remove_erhua=False,
full_to_half=True,
remove_interjections=False,
overwrite_cache=True,
)
if ZhNormalizer is not None
else None
)
self.en_tn_model = EnNormalizer() if EnNormalizer is not None else None
self._custom_replacements = self._load_custom_replacements()
@staticmethod
def _load_custom_replacements() -> list[tuple[str, str]]:
custom_replace_path = os.path.join(os.path.dirname(__file__), "configs", "custom_replace.jsonl")
if not os.path.exists(custom_replace_path):
return []
replacements: list[tuple[str, str]] = []
with open(custom_replace_path, encoding="utf-8") as f:
for line in f:
if not line.strip():
continue
item = json.loads(line)
replacements.append((item["origin"], item["new"]))
return replacements
def pre_replace(self, sentence: str) -> str:
sentence = tn_scientific_notation(sentence)
sentence = re.sub(r"(?<=\d)\s*-\s*(?=\d)", "减", sentence)
sentence = sentence.replace("-", "")
sentence = re.sub(r"咯([" + re.escape(PUNCTUATION_CHARS) + r"])", r"喽\1", sentence)
for origin, new in self._custom_replacements:
sentence = sentence.replace(origin, new)
return sentence
def post_replace(self, sentence: str) -> str:
sentence = remove_bracket(sentence)
sentence = sentence.replace(" - ", ",")
sentence = sentence.replace("——", ",")
sentence = re.sub(r"[,::;;、]+", ",", sentence)
sentence = re.sub(r"[.…]+", "。", sentence)
sentence = re.sub(r"[_·]+", "", sentence)
sentence = re.sub(r"""['"‘’“”|]+""", "", sentence)
symbol_map = {
"†": ",",
"²": "平方",
"³": "立方",
"/": "每",
"~": "到",
"~": "到",
"①": "一",
"②": "二",
"③": "三",
"④": "四",
"⑤": "五",
"⑥": "六",
"⑦": "七",
"⑧": "八",
"⑨": "九",
"⑩": "十",
"α": "阿尔法",
"β": "贝塔",
"γ": "伽玛",
"Γ": "伽玛",
"δ": "德尔塔",
"Δ": "德尔塔",
"△": "德尔塔",
"ε": "艾普西龙",
"ζ": "捷塔",
"η": "依塔",
"θ": "西塔",
"Θ": "西塔",
"ι": "艾欧塔",
"κ": "喀帕",
"λ": "拉姆达",
"Λ": "拉姆达",
"μ": "缪",
"ν": "拗",
"ξ": "克西",
"Ξ": "克西",
"ο": "欧米克伦",
"π": "派",
"Π": "派",
"ρ": "肉",
"ς": "西格玛",
"Σ": "西格玛",
"σ": "西格玛",
"τ": "套",
"υ": "宇普西龙",
"φ": "服艾",
"Φ": "服艾",
"χ": "器",
"ψ": "普赛",
"Ψ": "普赛",
"ω": "欧米伽",
"Ω": "欧米伽",
"□": "方框",
">": "大于",
"<": "小于",
"∈": "属于",
"∉": "不属于",
"∪": "并",
"∩": "交",
"⊥": "垂直",
"∥": "平行",
"≠": "不等于",
"∵": "因为",
"∴": "所以",
"∅": "空集",
"⊂": "真包含于",
"⊃": "包含",
"⊆": "包含于",
"⊇": "真包含",
"⊄": "不属于",
"⊅": "非超集",
"⊈": "不属于",
"⊉": "非超集",
}
for old, new in symbol_map.items():
sentence = sentence.replace(old, new)
return sentence
def text_normalize(self, text: str | None) -> str | None:
if text is None:
return None
text = self._preprocess_text(text)
if contains_chinese(text):
text = self._normalize_chinese_text(text).lower()
else:
text = self._normalize_english_text(text)
text = normalize_punctuation(text, PUNCTUATION_CHARS)
return ensure_proper_ending(text)
def _preprocess_text(self, text: str) -> str:
text = markdown_norm(text)
text = multi_line_process(text)
if emoji is not None:
text = emoji.replace_emoji(text, replace="")
return re.sub(r"(?<=[a-zA-Z])-(?=[a-zA-Z])", " ", text)
def _normalize_chinese_text(self, text: str) -> str:
text = self.pre_replace(text)
if self.zh_tn_model is not None:
text = self.zh_tn_model.normalize(text)
text = special_replace(text)
return self.post_replace(text).strip()
def _normalize_english_text(self, text: str) -> str:
text = text.replace("'", "’")
if self.en_tn_model is not None:
text = self.en_tn_model.normalize(text)
text = remove_bracket(text, "en")
text = replace_asterisk_with_multiply(text, "en")
text = text.replace("—", " ")
text = text.replace("’", "'")
text = spell_out_number(text, self.inflect_parser)
text = re.sub(r"\s+", " ", text)
keep_punctuation = r"\.,!\?'\:;"
pattern = rf"[^\w\s{keep_punctuation}]"
text = re.sub(pattern, "", text)
text = text.lower()
text = re.sub(r"\.+", ".", text)
text = re.sub(r"\,+", ",", text)
text = re.sub(r"!+", "!", text)
text = re.sub(r"\?+", "?", text)
text = re.sub(r"'+", "'", text)
text = re.sub(r":+", ":", text)
text = re.sub(r";+", ";", text)
text = re.sub(r"\s*([.,?!':;])\s*", r"\1 ", text)
return text.strip()
@@ -0,0 +1,228 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Vocoder loading and mel-to-audio conversion for GLM-TTS.
Supports:
- HiFT (24kHz) — reuses CosyVoice3's vendored HiFTGenerator
- Vocos2D JIT (32kHz) from TorchScript checkpoint
Extracted from glm_tts_dit_wrapper.py to keep file sizes under 800 lines.
"""
from __future__ import annotations
import os
from typing import Any
import torch
import torch.nn as nn
from vllm.logger import init_logger
try:
from torch.nn.utils.parametrizations import weight_norm
except ImportError:
from torch.nn.utils import weight_norm
logger = init_logger(__name__)
# ---------------------------------------------------------------------------
# HiFT vocoder (24kHz) — reuses CosyVoice3's vendored HiFTGenerator
# ---------------------------------------------------------------------------
class ConvRNNF0Predictor(nn.Module):
"""Non-causal F0 predictor for GLM-TTS HiFT vocoder.
GLM-TTS ships a non-causal HiFT checkpoint whose F0 predictor uses
standard ``nn.Conv1d`` layers (kernel_size=3, padding=1). CosyVoice3's
vendored hifigan only includes the *causal* variant
(``CausalConvRNNF0Predictor``), so we provide the non-causal version
here. The network structure and state_dict keys are identical to the
original ``cosyvoice.hifigan_cosy2.f0_predictor.ConvRNNF0Predictor``.
"""
def __init__(
self,
num_class: int = 1,
in_channels: int = 80,
cond_channels: int = 512,
):
super().__init__()
self.num_class = num_class
self.condnet = nn.Sequential(
weight_norm(nn.Conv1d(in_channels, cond_channels, kernel_size=3, padding=1)),
nn.ELU(),
weight_norm(nn.Conv1d(cond_channels, cond_channels, kernel_size=3, padding=1)),
nn.ELU(),
weight_norm(nn.Conv1d(cond_channels, cond_channels, kernel_size=3, padding=1)),
nn.ELU(),
weight_norm(nn.Conv1d(cond_channels, cond_channels, kernel_size=3, padding=1)),
nn.ELU(),
weight_norm(nn.Conv1d(cond_channels, cond_channels, kernel_size=3, padding=1)),
nn.ELU(),
)
self.classifier = nn.Linear(in_features=cond_channels, out_features=self.num_class)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.condnet(x)
x = x.transpose(1, 2)
return torch.abs(self.classifier(x).squeeze(-1))
class HiFTWrapper:
"""Thin wrapper around CosyVoice3's vendored HiFTGenerator."""
def __init__(self, state_dict: dict[str, Any], device: torch.device):
self.device = device
self.sample_rate = 24000
from vllm_omni.model_executor.models.cosyvoice3.code2wav_core.hifigan import (
HiFTGenerator,
)
f0_predictor = ConvRNNF0Predictor(num_class=1, in_channels=80, cond_channels=512)
self.model = HiFTGenerator(
in_channels=80,
base_channels=512,
nb_harmonics=8,
sampling_rate=24000,
nsf_alpha=0.1,
nsf_sigma=0.003,
nsf_voiced_threshold=10,
upsample_rates=[8, 5, 3],
upsample_kernel_sizes=[16, 11, 7],
istft_params={"n_fft": 16, "hop_len": 4},
resblock_kernel_sizes=[3, 7, 11],
resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5], [1, 3, 5]],
source_resblock_kernel_sizes=[7, 7, 11],
source_resblock_dilation_sizes=[
[1, 3, 5],
[1, 3, 5],
[1, 3, 5],
],
lrelu_slope=0.1,
audio_limit=0.99,
f0_predictor=f0_predictor,
).to(device)
self.model.load_state_dict(state_dict)
self.model.eval()
self.model.float()
def __call__(self, mel: torch.Tensor) -> torch.Tensor:
mel = mel.to(self.device)
with torch.no_grad():
audio, _ = self.model.inference(mel)
return audio
def load_hift(ckpt_path: str, device: torch.device) -> HiFTWrapper:
"""Load HiFT vocoder from checkpoint."""
state_dict = torch.load(ckpt_path, map_location=device, weights_only=True)
if isinstance(state_dict, dict):
for key in ("state_dict", "model", "generator"):
nested = state_dict.get(key)
if isinstance(nested, dict):
state_dict = nested
break
return HiFTWrapper(state_dict, device)
# ---------------------------------------------------------------------------
# Vocos2D JIT vocoder (32kHz)
# ---------------------------------------------------------------------------
_MEL_LOGDIFF = -7.847762537473608
class Vocos2DWrapper:
"""Thin wrapper around Vocos2D TorchScript model."""
def __init__(self, ckpt_path: str, device: torch.device):
self.device = device
self.gen_model = torch.jit.load(ckpt_path, map_location=device)
self.gen_model.eval()
self._mel_logdiff = _MEL_LOGDIFF
def __call__(self, mel: torch.Tensor) -> torch.Tensor:
if mel.size(-1) == 1:
mel = torch.cat([mel, mel], dim=-1)
xs_mel = mel.transpose(-1, -2) + self._mel_logdiff
xs = self.gen_model(xs_mel.to(self.device))
if xs.ndim == 2:
xs = xs.unsqueeze(1)
return xs
def load_vocos2d_jit(ckpt_path: str, device: torch.device) -> Vocos2DWrapper:
"""Load Vocos2D JIT vocoder from TorchScript checkpoint."""
return Vocos2DWrapper(ckpt_path, device)
# ---------------------------------------------------------------------------
# Unified loader
# ---------------------------------------------------------------------------
def load_vocoder(
model_root: str,
device: torch.device,
sample_rate: int = 24000,
) -> tuple[Any | None, int]:
"""Try to load the best available vocoder.
Returns:
(vocoder, actual_sample_rate) or (None, sample_rate) on failure.
"""
# Try HiFT first for 24kHz
if sample_rate == 24000:
hift_path = os.path.join(model_root, "hift", "hift.pt")
if os.path.isfile(hift_path):
try:
vocoder = load_hift(hift_path, device)
logger.info("Loaded HiFT vocoder from %s", hift_path)
return vocoder, 24000
except Exception as e:
logger.warning("Failed to load HiFT: %s", e)
# Try Vocos2D JIT
vocos_jit_path = os.path.join(model_root, "vocos2d", "generator_jit.ckpt")
if os.path.isfile(vocos_jit_path):
try:
vocoder = load_vocos2d_jit(vocos_jit_path, device)
logger.info("Loaded Vocos2D JIT vocoder (32kHz)")
return vocoder, 32000
except Exception as e:
logger.warning("Failed to load Vocos2D JIT: %s", e)
logger.warning("No vocoder available")
return None, sample_rate
def mel_to_audio(
vocoder: Any | None,
mel: torch.Tensor,
) -> torch.Tensor:
"""Convert mel-spectrogram to audio waveform.
Args:
vocoder: Vocoder instance (HiFTWrapper, Vocos2DWrapper, or None).
mel: Mel-spectrogram [B, T, mel_dim].
Returns:
Audio waveform [B, 1, samples].
"""
# Transpose to [B, mel_dim, T] for vocoder.
# HiFT / Vocos2D are precision-sensitive; always feed float32.
mel = mel.to(torch.float32).transpose(1, 2)
if vocoder is not None:
if callable(vocoder) and not hasattr(vocoder, "decode"):
audio = vocoder(mel)
else:
audio = vocoder.decode(mel)
if audio.ndim == 2:
audio = audio.unsqueeze(1)
else:
raise RuntimeError("GLM-TTS vocoder is not loaded.")
return audio
@@ -0,0 +1,299 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""GLM-TTS voice cloning frontend: speech tokenizer, speaker embedding, mel features.
Lazy-loads external models (WhisperVQ, CampPlus ONNX) and provides extraction
helpers consumed by the GLM-TTS multimodal processor.
"""
from __future__ import annotations
import os
import torch
import torchaudio.compliance.kaldi as kaldi
import torchaudio.transforms as T
from vllm.logger import init_logger
logger = init_logger(__name__)
_MEL_BASIS_CACHE: dict[tuple[int, int, int, int, int, str], torch.Tensor] = {}
_HANN_WINDOW_CACHE: dict[tuple[int, str], torch.Tensor] = {}
def _spectral_normalize_torch(magnitudes: torch.Tensor) -> torch.Tensor:
return torch.log(torch.clamp(magnitudes, min=1e-5))
def _get_glm_tts_mel_basis(
*,
device: torch.device,
sample_rate: int,
n_fft: int,
n_mels: int,
f_min: int,
f_max: int,
) -> torch.Tensor:
"""Compute or retrieve cached GLM-TTS mel filter bank.
Uses torchaudio melscale_fbanks with Slaney parameters (norm="slaney",
mel_scale="slaney") to match the official GLM-TTS ``utils/audio.py``
librosa.filters.mel output. The previous HTK / norm=None config
produced a numerically different filter bank that shifted the
prompt_feat distribution and degraded voice-clone conditioning.
"""
cache_key = (sample_rate, n_fft, n_mels, f_min, f_max, str(device))
mel_basis = _MEL_BASIS_CACHE.get(cache_key)
if mel_basis is not None:
return mel_basis
import torchaudio.functional as AF
mel_basis = (
AF.melscale_fbanks(
n_freqs=(n_fft // 2) + 1,
f_min=float(f_min),
f_max=float(f_max),
n_mels=n_mels,
sample_rate=sample_rate,
norm="slaney",
mel_scale="slaney",
)
.transpose(0, 1)
.contiguous()
.float()
.to(device)
)
_MEL_BASIS_CACHE[cache_key] = mel_basis
return mel_basis
def _extract_glm_tts_mel_feature(
audio: torch.Tensor,
*,
sample_rate: int,
n_fft: int,
win_length: int,
hop_length: int,
n_mels: int,
f_min: int,
f_max: int,
) -> torch.Tensor:
"""Extract time-major log-mel spectrogram features from audio waveform."""
device = audio.device
mel_basis = _get_glm_tts_mel_basis(
device=device,
sample_rate=sample_rate,
n_fft=n_fft,
n_mels=n_mels,
f_min=f_min,
f_max=f_max,
)
hann_key = (win_length, str(device))
window = _HANN_WINDOW_CACHE.get(hann_key)
if window is None:
window = torch.hann_window(win_length, device=device)
_HANN_WINDOW_CACHE[hann_key] = window
if audio.ndim == 1:
audio = audio.unsqueeze(0)
pad = int((n_fft - hop_length) / 2)
audio = torch.nn.functional.pad(
audio.unsqueeze(1),
(pad, pad),
mode="reflect",
).squeeze(1)
spec = torch.stft(
audio,
n_fft,
hop_length=hop_length,
win_length=win_length,
window=window,
center=False,
pad_mode="reflect",
normalized=False,
onesided=True,
return_complex=True,
)
spec = torch.sqrt(spec.real.pow(2) + spec.imag.pow(2) + 1e-9)
spec = torch.matmul(mel_basis, spec)
spec = _spectral_normalize_torch(spec)
return spec.squeeze(0).transpose(0, 1).contiguous()
def load_voice_clone_frontend(
model_root: str,
model_device: torch.device,
*,
speech_tokenizer_cache: tuple | None,
campplus_cache: object | None,
campplus_path: str | None = None,
) -> tuple[tuple | None, object | None]:
"""Lazy-load voice cloning frontend models.
Args:
campplus_path: Pre-resolved path to ``campplus.onnx``. When provided
this takes priority over the default ``model_root/frontend/``
lookup. The caller (``GLMTTSForConditionalGeneration``) resolves
the path via ``transformers.utils.hub.cached_file`` during
``__init__`` so the file is already downloaded.
Returns:
``(speech_tokenizer, campplus_session)`` — guaranteed non-None
on success. Raises ``RuntimeError`` when a required component
cannot be loaded.
"""
speech_tokenizer = speech_tokenizer_cache
campplus_session = campplus_cache
if speech_tokenizer is None:
speech_tokenizer_paths = (
os.path.join(model_root, "speech_tokenizer"),
os.path.join(model_root, "ckpt", "speech_tokenizer"),
)
speech_tokenizer_path = next((path for path in speech_tokenizer_paths if os.path.isdir(path)), None)
if speech_tokenizer_path is None:
raise RuntimeError(
f"GLM-TTS speech tokenizer directory not found at {speech_tokenizer_paths[0]} "
f"or {speech_tokenizer_paths[1]}. Voice cloning requires the WhisperVQ "
f"speech tokenizer from the model snapshot."
)
try:
from safetensors.torch import load_file
from transformers import AutoFeatureExtractor, WhisperConfig
from vllm_omni.model_executor.models.common.whisper_vq import (
WhisperVQEncoder,
)
_config = WhisperConfig.from_pretrained(speech_tokenizer_path)
_config.quantize_encoder_only = True
_model = WhisperVQEncoder(_config)
_sd = load_file(os.path.join(speech_tokenizer_path, "model.safetensors"))
_prefix, _cleaned = "model.encoder.", {}
for k, v in _sd.items():
_cleaned[k[len(_prefix) :] if k.startswith(_prefix) else k] = v
_model.load_state_dict(_cleaned, strict=False)
_model = _model.to(model_device).eval()
_fe = AutoFeatureExtractor.from_pretrained(speech_tokenizer_path)
speech_tokenizer = (_model, _fe)
logger.info("Loaded GLM-TTS speech tokenizer from %s", speech_tokenizer_path)
except Exception as exc:
raise RuntimeError(f"Failed to load GLM-TTS speech tokenizer from {speech_tokenizer_path}") from exc
if campplus_session is None:
cp = campplus_path or os.path.join(model_root, "frontend", "campplus.onnx")
if not os.path.isfile(cp):
raise RuntimeError(
f"GLM-TTS campplus.onnx not found at {cp}. "
f"Voice cloning requires the CampPlus speaker embedding model."
)
try:
import onnxruntime
cuda_avail = "CUDAExecutionProvider" in onnxruntime.get_available_providers()
cuda_ok = model_device.type == "cuda" and cuda_avail
providers = (["CUDAExecutionProvider"] if cuda_ok else []) + ["CPUExecutionProvider"]
campplus_session = onnxruntime.InferenceSession(cp, providers=providers)
logger.info("Loaded GLM-TTS campplus ONNX from %s", cp)
except Exception as exc:
raise RuntimeError(f"Failed to load GLM-TTS campplus ONNX from {cp}") from exc
return speech_tokenizer, campplus_session
def extract_prompt_speech_token(
ref_audio_wav: torch.Tensor,
ref_audio_sr: int,
speech_tokenizer: tuple,
) -> list[int] | None:
"""Extract prompt speech tokens from reference audio using WhisperVQ."""
model, feature_extractor = speech_tokenizer
device = model.device
audio = ref_audio_wav.float().to(device)
if ref_audio_sr != 16000:
resampler = T.Resample(orig_freq=ref_audio_sr, new_freq=16000).to(device)
audio = resampler(audio)
if audio.ndim > 1:
audio = audio[0]
audio_np = audio.cpu().numpy()
pooling_kernel_size = getattr(model.config, "pooling_kernel_size", 1)
stride = model.conv1.stride[0] * model.conv2.stride[0] * pooling_kernel_size * feature_extractor.hop_length
all_tokens: list[int] = []
time_step = 0
while time_step * 16000 < audio_np.shape[0]:
segment = audio_np[time_step * 16000 : (time_step + 30) * 16000]
features = feature_extractor(
[segment],
sampling_rate=16000,
return_attention_mask=True,
return_tensors="pt",
padding="longest",
pad_to_multiple_of=stride,
).to(device)
with torch.no_grad():
outputs = model(**features)
tokens = outputs.quantized_token_ids
attn = features.attention_mask[:, :: model.conv1.stride[0] * model.conv2.stride[0]][:, ::pooling_kernel_size]
all_tokens.extend(tokens[0][attn[0].bool()].tolist())
time_step += 30
return all_tokens if all_tokens else None
def extract_spk_embedding(
ref_audio_wav: torch.Tensor,
ref_audio_sr: int,
campplus_session: object,
) -> list[float] | None:
"""Extract speaker embedding from reference audio using CampPlus ONNX."""
audio = ref_audio_wav.float().cpu()
if ref_audio_sr != 16000:
resampler = T.Resample(orig_freq=ref_audio_sr, new_freq=16000)
audio = resampler(audio)
if audio.ndim > 1:
audio = audio[0]
feat = kaldi.fbank(audio.unsqueeze(0), num_mel_bins=80, dither=0, sample_frequency=16000)
feat = feat - feat.mean(dim=0, keepdim=True)
input_name = campplus_session.get_inputs()[0].name
embedding = campplus_session.run(None, {input_name: feat.unsqueeze(dim=0).cpu().numpy()})[0].flatten().tolist()
return embedding
def extract_prompt_feat(
ref_audio_wav: torch.Tensor,
ref_audio_sr: int,
model_device: torch.device,
) -> torch.Tensor | None:
"""Extract mel features from reference audio for DiT conditioning."""
audio = ref_audio_wav.float().to(model_device)
if ref_audio_sr != 24000:
resampler = T.Resample(orig_freq=ref_audio_sr, new_freq=24000).to(model_device)
audio = resampler(audio)
if audio.ndim > 1:
audio = audio[0]
with torch.no_grad():
feat = _extract_glm_tts_mel_feature(
audio,
sample_rate=24000,
n_fft=1920,
win_length=1920,
hop_length=480,
n_mels=80,
f_min=0,
f_max=8000,
)
return feat # [T_mel, mel_dim]
@@ -0,0 +1,9 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""vllm-omni integration for boson-ai's higgs-audio v2 (two-stage TTS)."""
from vllm_omni.model_executor.models.higgs_audio_v2.configuration_higgs_audio_v2 import (
HiggsAudioV2Config,
)
__all__ = ["HiggsAudioV2Config"]
@@ -0,0 +1,169 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Configuration class for higgs-audio v2 in vllm-omni.
Mirrors `bosonai/higgs-audio-v2-generation-3B-base/config.json` and exposes the
Stage-1 codec decoder reference (sample rate, codebook layout, stream-special
token ids) so the rest of the integration can read a single typed object.
The text-LM backbone constants match `Llama-3.2-3B` (hidden=3072, 28 layers,
GQA 24Q/8KV, head_dim=128, vocab=128256, max_position_embeddings=2048, RoPE
``llama3`` scaling with factor=32). The audio side adds 8 codebooks of size
1026 (real codes ``[0..1023]``, stream specials ``audio_stream_bos_id=1024``
and ``audio_stream_eos_id=1025``) plus the DualFFN audio expert.
"""
from __future__ import annotations
from typing import Any
from transformers import PretrainedConfig
__all__ = ["HiggsAudioV2Config"]
class HiggsAudioV2Config(PretrainedConfig):
"""Typed wrapper around the upstream `higgs_audio_v2` config.
The field set here is a strict subset of the upstream
``transformers.models.higgs_audio_v2.HiggsAudioV2Config``: only the
knobs that vllm-omni reads directly are surfaced. Anything extra coming
from the HF config dict is preserved via ``PretrainedConfig`` so
``AutoConfig.from_pretrained(...)`` round-trips correctly.
"""
model_type: str = "higgs_audio_v2"
keys_to_ignore_at_inference = ("past_key_values",)
# Architecture identifier persisted in config.json and used by both
# vllm_omni.config.pipeline_registry and vllm_omni.model_executor.models.registry.
DEFAULT_ARCHITECTURES = ("HiggsAudioV2ForConditionalGeneration",)
def __init__(
self,
# --- Text LM (Llama-3.2-3B) ---
vocab_size: int = 128256,
hidden_size: int = 3072,
intermediate_size: int = 8192,
num_hidden_layers: int = 28,
num_attention_heads: int = 24,
num_key_value_heads: int = 8,
head_dim: int = 128,
hidden_act: str = "silu",
max_position_embeddings: int = 2048,
rms_norm_eps: float = 1e-5,
rope_parameters: dict[str, Any] | None = None,
initializer_range: float = 0.02,
attention_bias: bool = False,
attention_dropout: float = 0.0,
mlp_bias: bool = False,
tie_word_embeddings: bool = False,
pretraining_tp: int = 1,
# --- Audio side ---
num_codebooks: int = 8,
codebook_size: int = 1026,
audio_token_id: int = 128016,
audio_bos_token_id: int = 128013,
audio_eos_token_id: int = 128012,
audio_delay_token_id: int = 128014,
audio_stream_bos_id: int = 1024,
audio_stream_eos_id: int = 1025,
sample_rate: int = 24000,
frame_rate: int = 25,
# --- Standard LM specials ---
bos_token_id: int = 1,
eos_token_id: int = 128009,
pad_token_id: int = 128001,
# --- DualFFN ---
# Upstream `HiggsAudioV2DecoderLayer` always carries a parallel `audio_mlp`
# expert; this flag is kept for forward-compat in case a future config
# disables it (no-op for the boson-ai checkpoint).
use_audio_dual_ffn: bool = True,
# --- Stage-1 tokenizer / codec decoder ---
# Path to the audio-tokenizer subdir (relative to the model directory).
# Empty string means the model_dir itself contains config.json +
# model.safetensors (the layout used by the standalone
# ``bosonai/higgs-audio-v2-tokenizer`` HF repo). Non-empty means the
# tokenizer files live in ``<model_dir>/<subdir>/`` (the layout used by
# the 3B Stage-0 checkpoint which bundles its tokenizer under
# ``audio_tokenizer/``).
audio_tokenizer_subdir: str = "",
# HF repo id (or local path) of a STANDALONE audio tokenizer. When set,
# Stage-1 resolves this via ``huggingface_hub.snapshot_download`` and
# loads the codec from there, ignoring ``audio_tokenizer_subdir``. This
# matches the boson-ai release layout where the codec lives in a
# separate repo (``bosonai/higgs-audio-v2-tokenizer``).
audio_tokenizer_id: str | None = "bosonai/higgs-audio-v2-tokenizer",
# --- Misc ---
use_cache: bool = True,
**kwargs: Any,
) -> None:
if rope_parameters is None:
rope_parameters = {
"factor": 32.0,
"high_freq_factor": 0.5,
"low_freq_factor": 0.125,
"original_max_position_embeddings": 1024,
"rope_theta": 500000.0,
"rope_type": "llama3",
}
super().__init__(
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.vocab_size = vocab_size
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.hidden_act = hidden_act
self.max_position_embeddings = max_position_embeddings
self.rms_norm_eps = rms_norm_eps
self.rope_parameters = dict(rope_parameters)
self.initializer_range = initializer_range
self.attention_bias = attention_bias
self.attention_dropout = attention_dropout
self.mlp_bias = mlp_bias
self.pretraining_tp = pretraining_tp
self.num_codebooks = num_codebooks
self.codebook_size = codebook_size
self.audio_token_id = audio_token_id
self.audio_bos_token_id = audio_bos_token_id
self.audio_eos_token_id = audio_eos_token_id
self.audio_delay_token_id = audio_delay_token_id
self.audio_stream_bos_id = audio_stream_bos_id
self.audio_stream_eos_id = audio_stream_eos_id
self.sample_rate = sample_rate
self.frame_rate = frame_rate
self.use_audio_dual_ffn = use_audio_dual_ffn
self.audio_tokenizer_subdir = audio_tokenizer_subdir
self.audio_tokenizer_id = audio_tokenizer_id
self.use_cache = use_cache
# Codes [0..codebook_size-1] include 2 stream specials at indices
# `audio_stream_bos_id` and `audio_stream_eos_id`. Real codes ready for the
# codec decoder are the strict prefix [0..audio_stream_bos_id).
@property
def num_real_codes(self) -> int:
return self.audio_stream_bos_id # i.e. 1024 for the boson-ai checkpoint
# The full vocab size of each per-codebook output head.
@property
def codebook_output_size(self) -> int:
return self.codebook_size # i.e. 1026 for the boson-ai checkpoint
# Canonical MusicGen-style delay pattern used by
# `HiggsAudioV2DelayPatternLogitsProcessor`: codebook k starts emitting
# real codes only after k frames. Kept as a function so subclasses can
# override if upstream ever publishes a different convention.
def default_delay_pattern(self) -> list[int]:
return list(range(self.num_codebooks))
@@ -0,0 +1,471 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""HiggsAudio codec decoder kernel for higgs-audio v2.
This module hosts the parameter-side building blocks for the higgs-audio-v2
audio tokenizer's decoder path:
audio_codes [B, 8, T]
-> RVQ codebook lookup + project_out -> sum -> [B, hidden_size, T]
-> fc2 Linear(hidden_size, 256) -> [B, 256, T]
-> DAC acoustic decoder (conv-transpose upsampling) -> [B, 1, T*960]
-> 24 kHz waveform (25 fps x 960 samples/frame)
"""
from __future__ import annotations
import json
import os
from typing import Any
import torch
import torch.nn as nn
__all__ = [
"HiggsAudioVQLayer",
"HiggsAudioRVQ",
"adjust_conv_transpose_output_padding",
"build_higgs_audio_acoustic_decoder",
"BosonDacDecoder",
"build_boson_dac_decoder",
"load_higgs_audio_codec",
"_remap_boson_model_pth_state_dict", # exported for unit-testing the mapper
]
class HiggsAudioVQLayer(nn.Module):
"""Single VQ layer: codebook lookup + project_out."""
def __init__(self, codebook_size: int = 1024, codebook_dim: int = 64, hidden_size: int = 1024):
super().__init__()
self.codebook = nn.Embedding(codebook_size, codebook_dim)
self.project_out = nn.Linear(codebook_dim, hidden_size)
def decode(self, indices: torch.Tensor) -> torch.Tensor:
"""indices: [B, T] -> [B, hidden_size, T]."""
quantized = self.codebook(indices)
quantized = self.project_out(quantized)
return quantized.permute(0, 2, 1)
class HiggsAudioRVQ(nn.Module):
"""Residual Vector Quantizer with ``num_quantizers`` codebook layers."""
def __init__(
self,
num_quantizers: int = 8,
codebook_size: int = 1024,
codebook_dim: int = 64,
hidden_size: int = 1024,
):
super().__init__()
self.quantizers = nn.ModuleList(
[HiggsAudioVQLayer(codebook_size, codebook_dim, hidden_size) for _ in range(num_quantizers)]
)
def decode(self, codes: torch.Tensor) -> torch.Tensor:
"""codes: [num_quantizers, B, T] -> [B, hidden_size, T]."""
result = torch.zeros(
codes.shape[1],
self.quantizers[0].project_out.out_features,
codes.shape[2],
device=codes.device,
dtype=torch.float32,
)
for i, quantizer in enumerate(self.quantizers):
result = result + quantizer.decode(codes[i])
return result
@torch.jit.script
def _snake(x: torch.Tensor, alpha: torch.Tensor) -> torch.Tensor:
shape = x.shape
x = x.reshape(shape[0], shape[1], -1)
x = x + (alpha + 1e-9).reciprocal() * torch.sin(alpha * x).pow(2)
return x.reshape(shape)
class _Snake1d(nn.Module):
"""Snake activation (per-channel learnable alpha). Mirrors the boson-ai DAC
Snake1d implementation byte-for-byte so the boson ``model.pth`` state-dict
loads directly into ``self.alpha``.
"""
def __init__(self, channels: int):
super().__init__()
self.alpha = nn.Parameter(torch.ones(1, channels, 1))
def forward(self, x: torch.Tensor) -> torch.Tensor:
return _snake(x, self.alpha)
def _wn_conv1d(*args: Any, **kwargs: Any) -> nn.Module:
from torch.nn.utils import weight_norm
return weight_norm(nn.Conv1d(*args, **kwargs))
def _wn_conv_transpose1d(*args: Any, **kwargs: Any) -> nn.Module:
from torch.nn.utils import weight_norm
return weight_norm(nn.ConvTranspose1d(*args, **kwargs))
class _BosonResidualUnit(nn.Module):
def __init__(self, dim: int, dilation: int = 1):
super().__init__()
pad = ((7 - 1) * dilation) // 2
self.block = nn.Sequential(
_Snake1d(dim),
_wn_conv1d(dim, dim, kernel_size=7, dilation=dilation, padding=pad),
_Snake1d(dim),
_wn_conv1d(dim, dim, kernel_size=1),
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
y = self.block(x)
pad = (x.shape[-1] - y.shape[-1]) // 2
if pad > 0:
x = x[..., pad:-pad]
return x + y
class _BosonDecoderBlock(nn.Module):
def __init__(self, input_dim: int, output_dim: int, stride: int):
super().__init__()
import math
self.block = nn.Sequential(
_Snake1d(input_dim),
_wn_conv_transpose1d(
input_dim,
output_dim,
kernel_size=2 * stride,
stride=stride,
padding=math.ceil(stride / 2),
output_padding=stride % 2,
),
_BosonResidualUnit(output_dim, dilation=1),
_BosonResidualUnit(output_dim, dilation=3),
_BosonResidualUnit(output_dim, dilation=9),
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.block(x)
class BosonDacDecoder(nn.Module):
"""Vendored copy of ``boson_multimodal``'s standalone DAC decoder, with the
exact ``decoder_2.model.<i>.{...}`` key layout the boson-ai
``bosonai/higgs-audio-v2-tokenizer`` checkpoint expects.
See ``boson_multimodal/audio_processing/descriptaudiocodec/dac/model/dac.py``
(``class Decoder``) in the upstream package for the reference implementation
we mirror.
Architecture for the v2 24 kHz tokenizer:
input_channel=256, channels=1024, rates=[8, 5, 4, 2, 3], d_out=1
Cumulative upsample factor is ``prod(rates) = 960`` (25 fps -> 24 kHz).
"""
def __init__(
self,
input_channel: int = 256,
channels: int = 1024,
rates: tuple[int, ...] = (8, 5, 4, 2, 3),
d_out: int = 1,
):
super().__init__()
layers: list[nn.Module] = [_wn_conv1d(input_channel, channels, kernel_size=7, padding=3)]
last_dim = channels
for i, stride in enumerate(rates):
input_dim = channels // 2**i
output_dim = channels // 2 ** (i + 1)
layers.append(_BosonDecoderBlock(input_dim, output_dim, stride))
last_dim = output_dim
layers.append(_Snake1d(last_dim))
layers.append(_wn_conv1d(last_dim, d_out, kernel_size=7, padding=3))
self.model = nn.Sequential(*layers)
# Cache hop length (= prod(rates)) so callers don't need to recompute it.
hop = 1
for s in rates:
hop *= int(s)
self._hop_length = hop
@property
def hop_length(self) -> int:
return self._hop_length
# Expose conv1 with a ``.in_channels`` attribute so the existing fc2
# fallback shape inference (acoustic_decoder.conv1.in_channels) works
# unchanged for the boson decoder too.
@property
def conv1(self) -> nn.Module:
return self.model[0]
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.model(x)
def build_boson_dac_decoder(device: torch.device) -> BosonDacDecoder:
"""Construct the vendored boson DAC decoder on ``device``.
The architectural constants (input_channel=256, channels=1024,
rates=[8,5,4,2,3], d_out=1) are baked in because they're invariant for the
v2 24 kHz tokenizer ``bosonai/higgs-audio-v2-tokenizer`` checkpoint we
target. Other channel counts are not supported until we encounter a
different boson checkpoint in the wild.
"""
return BosonDacDecoder().to(device)
def adjust_conv_transpose_output_padding(decoder: nn.Module) -> None:
"""Set ConvTranspose1d output_padding = stride % 2 (HiggsAudioV2 modification).
The vanilla DAC decoder ships with the default output_padding (0); the
boson-ai checkpoint expects ``stride % 2`` instead. This is a no-op for
even strides and adds a single sample for odd strides.
"""
for module in decoder.modules():
if isinstance(module, nn.ConvTranspose1d):
stride = module.stride[0] if isinstance(module.stride, tuple) else module.stride
module.output_padding = (stride % 2,)
def build_higgs_audio_acoustic_decoder(
tokenizer_config: dict[str, Any],
device: torch.device,
) -> nn.Module:
"""Build the DAC acoustic decoder used by the HiggsAudioV2 tokenizer.
Returns the decoder sub-module of ``transformers.DacModel`` with the
HiggsAudioV2 output-padding fix already applied. The tanh activation is
replaced with ``Identity`` so the network matches the boson-ai checkpoint.
Weights are NOT loaded here; the caller is responsible for copying them in.
"""
from transformers import DacConfig, DacModel
dac_cfg = DacConfig(**tokenizer_config["acoustic_model_config"])
dac_model = DacModel(dac_cfg)
decoder = dac_model.decoder.to(device)
adjust_conv_transpose_output_padding(decoder)
if hasattr(decoder, "tanh"):
decoder.tanh = nn.Identity()
return decoder
def _load_higgs_audio_state_dict(audio_tokenizer_dir: str, device: torch.device) -> dict[str, torch.Tensor]:
"""Load the codec state dict from either layout used in the wild.
Tries layouts in order:
1. ``<dir>/model.safetensors`` (OmniVoice-bundled layout used by
``k2-fsa/OmniVoice/audio_tokenizer/``).
2. ``<dir>/model.pth`` (boson-ai standalone ``bosonai/higgs-audio-v2-tokenizer``
layout). The state-dict keys differ structurally
(``quantizer.vq.layers.<i>._codebook.embed`` etc.) and are remapped to
the OmniVoice-style names this kernel expects via
:func:`_remap_boson_model_pth_state_dict`.
"""
safetensors_path = os.path.join(audio_tokenizer_dir, "model.safetensors")
pth_path = os.path.join(audio_tokenizer_dir, "model.pth")
# Preference order: try model.pth first when present (boson-ai standalone
# ships the codec there; its model.safetensors is a different artefact).
# Fall back to model.safetensors (the OmniVoice-bundled layout).
sd: dict[str, torch.Tensor]
if os.path.exists(pth_path):
sd = torch.load(pth_path, map_location=device, weights_only=False)
elif os.path.exists(safetensors_path):
from safetensors.torch import load_file
sd = load_file(safetensors_path, device=str(device))
else:
raise FileNotFoundError(f"Audio tokenizer weights not found at {pth_path} or {safetensors_path}")
# Run the boson-layout remap if needed; for the OmniVoice-bundled layout
# it is a no-op (no ``quantizer.vq.layers.*`` keys to rewrite).
if any(k.startswith("quantizer.vq.layers.") for k in sd):
sd = _remap_boson_model_pth_state_dict(sd)
return sd
def _remap_boson_model_pth_state_dict(sd: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]:
"""Translate boson-ai's standalone ``model.pth`` keys into OmniVoice-style names
that the shared kernel's RVQ + fc2 + DAC sites consume.
Best-effort: only the RVQ-side keys map cleanly. The boson-ai decoder
uses ``decoder_2.model.<i>.weight_g/weight_v`` (DAC with weight-norm +
Snake activations) rather than the OmniVoice DAC layout; that side
requires either vendoring the upstream decoder module or rewriting the
DAC builder to consume weight-normed tensors. This function returns the
mapped RVQ keys plus any acoustic_decoder.* / fc2.* / fc.* tensors that
happen to share the OmniVoice names, and leaves the decoder-2 keys
untouched (the caller will see them as MISSING when copying into the
OmniVoice DAC decoder).
Mapping (RVQ side only):
quantizer.vq.layers.<i>._codebook.embed -> quantizer.quantizers.<i>.codebook.embed
quantizer.vq.layers.<i>.project_out.weight -> quantizer.quantizers.<i>.project_out.weight
quantizer.vq.layers.<i>.project_out.bias -> quantizer.quantizers.<i>.project_out.bias
"""
if not isinstance(sd, dict):
raise TypeError(f"expected a state dict, got {type(sd)!r}")
remapped: dict[str, torch.Tensor] = {}
for key, tensor in sd.items():
if not isinstance(tensor, torch.Tensor):
continue
# Quantizer rewrite: vq.layers.<i>._codebook.embed -> quantizers.<i>.codebook.embed
if key.startswith("quantizer.vq.layers."):
parts = key.split(".")
# parts[3] is the layer index, parts[4]+ is the tail
if len(parts) >= 5:
idx = parts[3]
tail = ".".join(parts[4:])
# The actual codebook centroids the decode path uses live at
# ``_codebook.embed`` (a [codebook_size, codebook_dim] buffer).
# ``_codebook.embed_avg`` is the un-normalised EMA accumulator
# used during training (~cluster_size x bigger); MATCHING IT
# HERE produces a 4-5x amplified codebook and unintelligible
# PCM downstream. Use an EXACT-match check, not startswith.
if tail == "_codebook.embed":
new_key = f"quantizer.quantizers.{idx}.codebook.embed"
remapped[new_key] = tensor
continue
if tail.startswith("project_out."):
new_key = f"quantizer.quantizers.{idx}.{tail}"
remapped[new_key] = tensor
continue
# project_in / _codebook.cluster_size / _codebook.embed_avg / inited
# are encoder-side or training-only state that the decode path
# does not need; drop them.
continue
# boson decoder + fc_post2 -> our vendored kernel names.
if key.startswith("decoder_2."):
# decoder_2.model.<i>.{...} -> acoustic_decoder.model.<i>.{...}
new_key = "acoustic_decoder." + key[len("decoder_2.") :]
remapped[new_key] = tensor
continue
if key.startswith("fc_post2."):
# fc_post2.{weight,bias} -> fc2.{weight,bias}
new_key = "fc2." + key[len("fc_post2.") :]
remapped[new_key] = tensor
continue
# Anything else (acoustic_decoder.*, fc2.*, fc.*, fc_post*.*, decoder_2.*,
# decoder_semantic.*, semantic_model.*) passes through unchanged so
# the caller's lookup is unambiguous.
remapped[key] = tensor
return remapped
def load_higgs_audio_codec(
audio_tokenizer_dir: str,
device: torch.device,
) -> tuple[HiggsAudioRVQ, nn.Linear, nn.Module, dict[str, Any]]:
"""Load the HiggsAudioV2 RVQ + fc2 + DAC decoder from a checkpoint folder.
Accepts both layouts: ``<dir>/model.safetensors`` (OmniVoice-bundled) and
``<dir>/model.pth`` (boson-ai standalone). The standalone path remaps
quantizer keys before consumption; structural decoder differences
(boson uses Snake + weight-norm) still leave some DAC parameters missing
when loading the standalone path -- those entries log warnings but the
RVQ side completes successfully.
Args:
audio_tokenizer_dir: Path to a directory containing ``config.json``
and EITHER ``model.safetensors`` (OmniVoice layout) OR
``model.pth`` (boson-ai standalone layout).
device: Device to place the loaded modules and state dict on.
Returns:
(quantizer, fc2, acoustic_decoder, tokenizer_config)
- quantizer: ``HiggsAudioRVQ`` with ``num_quantizers`` discovered from
the state dict (defaults to 8 for boson-ai checkpoints).
- fc2: ``nn.Linear`` projecting RVQ output (1024) into the DAC's
hidden dimension (typically 256). May be uninitialized when loaded
from the boson-ai standalone layout (no ``fc2.*`` keys present).
- acoustic_decoder: DAC decoder with HiggsAudioV2 output-padding fix
and tanh-replaced-by-Identity. Fully initialized for the OmniVoice
layout; partially initialized for boson-ai standalone (missing
``decoder_2.*`` -> ``acoustic_decoder.*`` mapping is not yet
implemented; full upstream-decoder vendoring is the next step).
- tokenizer_config: The loaded ``config.json`` dict; useful for
callers that need ``sample_rate`` or other tokenizer metadata.
"""
config_path = os.path.join(audio_tokenizer_dir, "config.json")
with open(config_path) as f:
tokenizer_config: dict[str, Any] = json.load(f)
state_dict = _load_higgs_audio_state_dict(audio_tokenizer_dir, device)
codebook_dim = tokenizer_config.get("codebook_dim", 64)
codebook_size = tokenizer_config.get("codebook_size", 1024)
# Discover hidden_size and num_quantizers from the (possibly remapped) state dict.
if "quantizer.quantizers.0.project_out.weight" not in state_dict:
raise KeyError(
"Codec state dict is missing 'quantizer.quantizers.0.project_out.weight'. "
"If you loaded a boson-ai standalone tokenizer, ensure the model.pth "
"remap fired (see _remap_boson_model_pth_state_dict)."
)
hidden_size = state_dict["quantizer.quantizers.0.project_out.weight"].shape[0]
num_quantizers = sum(
1 for k in state_dict if k.startswith("quantizer.quantizers.") and k.endswith(".codebook.embed")
)
quantizer = HiggsAudioRVQ(
num_quantizers=num_quantizers,
codebook_size=codebook_size,
codebook_dim=codebook_dim,
hidden_size=hidden_size,
).to(device)
for i in range(num_quantizers):
prefix = f"quantizer.quantizers.{i}"
embed_key = f"{prefix}.codebook.embed"
if embed_key in state_dict:
quantizer.quantizers[i].codebook.weight.data.copy_(state_dict[embed_key])
proj_out_w = f"{prefix}.project_out.weight"
proj_out_b = f"{prefix}.project_out.bias"
if proj_out_w in state_dict:
quantizer.quantizers[i].project_out.weight.data.copy_(state_dict[proj_out_w])
if proj_out_b in state_dict:
quantizer.quantizers[i].project_out.bias.data.copy_(state_dict[proj_out_b])
# Decide which acoustic decoder we need. A boson-layout state dict (after
# _remap_boson_model_pth_state_dict) carries ``acoustic_decoder.model.0.weight_v``
# (the WNConv first conv) which the OmniVoice DacModel doesn't have; the
# OmniVoice layout carries ``acoustic_decoder.block.0.*`` instead.
is_boson_layout = "acoustic_decoder.model.0.weight_v" in state_dict
if is_boson_layout:
acoustic_decoder = build_boson_dac_decoder(device)
boson_sd = {
k[len("acoustic_decoder.") :]: v for k, v in state_dict.items() if k.startswith("acoustic_decoder.")
}
load_report = acoustic_decoder.load_state_dict(boson_sd, strict=False)
if load_report.missing_keys:
raise RuntimeError(
"Boson DAC decoder is missing keys after load: "
f"{load_report.missing_keys[:5]}... ({len(load_report.missing_keys)} total)"
)
# ``unexpected_keys`` is informational only.
else:
acoustic_decoder = build_higgs_audio_acoustic_decoder(tokenizer_config, device)
for name, param in acoustic_decoder.named_parameters():
higgs_name = f"acoustic_decoder.{name}"
if higgs_name in state_dict:
param.data.copy_(state_dict[higgs_name])
acoustic_decoder.eval()
if "fc2.weight" in state_dict and "fc2.bias" in state_dict:
fc2_w = state_dict["fc2.weight"]
fc2_b = state_dict["fc2.bias"]
fc2 = nn.Linear(fc2_w.shape[1], fc2_w.shape[0]).to(device)
fc2.weight.data.copy_(fc2_w)
fc2.bias.data.copy_(fc2_b)
else:
# Last-resort fallback: shape fc2 from the decoder's first conv input
# channels so the matmul produces compatible shapes. Weights stay
# uninitialised — PCM quality will be noise on this path.
first_conv = getattr(acoustic_decoder, "conv1", None)
if first_conv is None or not hasattr(first_conv, "in_channels"):
raise RuntimeError("acoustic_decoder has no conv1.in_channels; cannot size fc2 fallback")
fc2 = nn.Linear(hidden_size, int(first_conv.in_channels)).to(device)
return quantizer, fc2, acoustic_decoder, tokenizer_config
@@ -0,0 +1,413 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Stage 1 (codec decoder) for higgs-audio v2.
Two surfaces exposed:
1. **Direct decode API** (kept for offline / unit tests):
``decode_codes(audio_codes: [B, num_codebooks=8, T])`` -> ``[B, 1, T*hop]`` PCM.
``forward_chunk(audio_codes, *, left_context_size, hop_length=960)``
trims overlap from streamed PCM. ``forward(audio_codes)`` retains the same
single-tensor signature for backward compatibility with code that imports
the class directly.
2. **vLLM stage runtime API** (used by the engine):
``__init__(*, vllm_config, prefix)``, ``embed_input_ids``,
``compute_logits=None``, plus a runtime ``forward(input_ids=..., positions=...,
runtime_additional_information=...)`` that takes flat codebook-major
``input_ids`` (``[Q * num_frames]``) per request and returns an
:class:`vllm_omni.model_executor.models.output_templates.OmniOutput`.
The kernel is the HiggsAudio codec helper in
``vllm_omni/model_executor/models/higgs_audio_v2/higgs_audio_decoder.py``; both
surfaces share the same RVQ + DAC weights.
"""
from __future__ import annotations
import os
from typing import Any
import torch
import torch.nn as nn
from vllm.config import VllmConfig
from vllm.logger import init_logger
from vllm_omni.model_executor.models.higgs_audio_v2.configuration_higgs_audio_v2 import (
HiggsAudioV2Config,
)
from vllm_omni.model_executor.models.higgs_audio_v2.higgs_audio_decoder import (
HiggsAudioRVQ,
load_higgs_audio_codec,
)
from vllm_omni.model_executor.models.output_templates import OmniOutput
__all__ = [
"HiggsAudioV2Code2Wav",
"HiggsAudioV2Code2WavForConditionalGeneration",
]
logger = init_logger(__name__)
class HiggsAudioV2Code2Wav(nn.Module):
"""Stage-1 codec decoder for higgs-audio v2.
Constructor accepts either the vLLM-runtime signature (``*, vllm_config,
prefix``) or the direct config-object form (``HiggsAudioV2Code2Wav(config)``)
so both engine-side and unit-test callers work. When the runtime form is
used we read the higgs_audio_v2 config out of ``vllm_config.model_config.hf_config``
and the model_path off ``vllm_config.model_config.model`` so the codec can
be loaded directly from disk.
"""
input_modalities = "audio"
def __init__(
self,
config: HiggsAudioV2Config | None = None,
*,
vllm_config: VllmConfig | None = None,
prefix: str = "",
):
super().__init__()
# Resolve config from either positional (unit-test) or kwarg (engine) form.
if vllm_config is not None:
hf_config = vllm_config.model_config.hf_config
if isinstance(hf_config, HiggsAudioV2Config):
self.config = hf_config
else:
self.config = HiggsAudioV2Config(**hf_config.to_dict())
self._model_path: str | None = vllm_config.model_config.model
self.vllm_config: VllmConfig | None = vllm_config
else:
if config is None:
raise TypeError(
"HiggsAudioV2Code2Wav: provide either positional `config` "
"(HiggsAudioV2Config) or keyword `vllm_config` (VllmConfig)."
)
self.config = config
self._model_path = None
self.vllm_config = None
self.sample_rate: int = int(self.config.sample_rate)
self.num_codebooks: int = int(self.config.num_codebooks)
self.num_real_codes: int = int(self.config.num_real_codes)
# Each codec frame upsamples to 960 24 kHz samples (= 25 fps * 960 = 24000).
self.hop_length: int = 960
# Engine-runner hooks (Stage 1 has no token sampling).
self.have_multimodal_outputs = True
self.has_preprocess = False
self.has_postprocess = False
self.enable_update_additional_information = True
self.requires_raw_input_tokens = True
# Populated by load_weights().
self.quantizer: HiggsAudioRVQ | None = None
self.fc2: nn.Linear | None = None
self.acoustic_decoder: nn.Module | None = None
self._loaded: bool = False
# When constructed via the engine path, eagerly load codec weights from
# the model directory. The engine's subsequent ``load_weights(weights)``
# call (with the Stage-0 safetensors iterator) is then a cheap no-op.
if self._model_path is not None:
try:
self.load_codec_from_disk(self._model_path)
except FileNotFoundError as exc:
logger.warning("HiggsAudioV2Code2Wav: eager codec load deferred (%s)", exc)
# ------------------------------------------------------------- engine hooks
def embed_input_ids(self, input_ids: torch.Tensor, **_: Any) -> torch.Tensor:
"""Stage 1 ignores embeddings; vLLM's runner still needs a stable shape."""
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: Any, sampling_metadata: Any = None) -> None:
return None
# ------------------------------------------------------------------ load
def load_weights(self, weights_or_model_dir, device: torch.device | None = None):
"""Dual-signature load:
- ``load_weights(weights_iterator)`` -- the vLLM engine path. The iterator
yields ``(name, tensor)`` pairs from the Stage-0 safetensors which DO NOT
contain codec weights, so we ignore them and eagerly load the codec from
``self._model_path``. Returns the set of all our params as "initialized"
so the engine's loader passes its sanity check.
- ``load_weights(model_dir: str)`` -- the legacy file-based call used by
offline unit tests and ``end2end.py --mode stage1_only``. Returns ``None``.
"""
if not isinstance(weights_or_model_dir, (str, bytes, os.PathLike)):
# Engine call: consume the iterator (we don't need it) and eagerly
# load the codec from disk.
try:
for _ in weights_or_model_dir:
pass
except TypeError:
pass
if self._model_path is None:
raise RuntimeError(
"HiggsAudioV2Code2Wav.load_weights called via the engine path but "
"no model directory is known. Construct with vllm_config so the "
"constructor caches vllm_config.model_config.model."
)
self.load_codec_from_disk(self._model_path, device=device)
return {name for name, _ in self.named_parameters()}
# Legacy file-based call.
self.load_codec_from_disk(weights_or_model_dir, device=device)
return None
def load_codec_from_disk(self, model_dir: str, device: torch.device | None = None) -> None:
"""Load codec weights from disk (RVQ + fc2 + DAC decoder).
Resolution order for the codec directory:
1. If :attr:`HiggsAudioV2Config.audio_tokenizer_id` is set, treat it as
either a local path (if it exists on disk) or an HF repo id that we
resolve via ``huggingface_hub.snapshot_download``. This is the
default for the boson-ai release (codec in a separate repo).
2. Otherwise fall back to ``<model_dir>/<audio_tokenizer_subdir>``.
"""
if device is None:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
audio_tokenizer_path = self._resolve_audio_tokenizer_path(model_dir)
quantizer, fc2, acoustic_decoder, _tokenizer_config = load_higgs_audio_codec(audio_tokenizer_path, device)
if len(quantizer.quantizers) != self.num_codebooks:
raise ValueError(
f"checkpoint has {len(quantizer.quantizers)} quantizers but config.num_codebooks={self.num_codebooks}"
)
self.quantizer = quantizer
self.fc2 = fc2
self.acoustic_decoder = acoustic_decoder
self._loaded = True
logger.info(
"Loaded HiggsAudioV2Code2Wav: %d quantizers, fc2(%d->%d), sample_rate=%d",
len(self.quantizer.quantizers),
self.fc2.in_features,
self.fc2.out_features,
self.sample_rate,
)
def _resolve_audio_tokenizer_path(self, model_dir: str) -> str:
"""Return a local filesystem path containing ``config.json`` + codec
weights. See :meth:`load_codec_from_disk` for the resolution rules."""
tokenizer_id = getattr(self.config, "audio_tokenizer_id", None)
if tokenizer_id:
if os.path.isdir(tokenizer_id):
return tokenizer_id
return self._resolve_hf_id_to_local(tokenizer_id)
subdir = self.config.audio_tokenizer_subdir or ""
if os.path.isdir(model_dir):
return os.path.join(model_dir, subdir) if subdir else model_dir
local = self._resolve_hf_id_to_local(model_dir)
return os.path.join(local, subdir) if subdir else local
@staticmethod
def _resolve_hf_id_to_local(repo_id: str) -> str:
"""Resolve a HF repo id to a local snapshot directory.
Prefers a read-only cache lookup (no write locks) so a quota-constrained
Lustre cache can still serve already-downloaded weights. Falls back to
``snapshot_download`` only when nothing is cached locally.
"""
from huggingface_hub import try_to_load_from_cache
cached = try_to_load_from_cache(repo_id=repo_id, filename="config.json")
if isinstance(cached, str) and os.path.isfile(cached):
return os.path.dirname(cached)
from huggingface_hub.constants import HF_HUB_CACHE
safe = repo_id.replace("/", "--")
snapshots_dir = os.path.join(HF_HUB_CACHE, f"models--{safe}", "snapshots")
if os.path.isdir(snapshots_dir):
for rev in os.listdir(snapshots_dir):
candidate = os.path.join(snapshots_dir, rev)
if os.path.isfile(os.path.join(candidate, "config.json")):
return candidate
from huggingface_hub import snapshot_download
return snapshot_download(repo_id=repo_id)
# ------------------------------------------------------ direct decode API
@torch.inference_mode()
def decode_codes(self, audio_codes: torch.Tensor) -> torch.Tensor:
"""Decode a ``[B, num_codebooks=8, T]`` code tensor to PCM ``[B, 1, T*hop]``."""
if not self._loaded:
raise RuntimeError("HiggsAudioV2Code2Wav not loaded. Call load_weights() first.")
codes = self._validate_codes(audio_codes)
device = codes.device
rvq_codes = codes.transpose(0, 1).long() # [num_codebooks, B, T]
quantized = self.quantizer.decode(rvq_codes) # [B, hidden, T]
# Match fc2's parameter dtype — vLLM may auto-cast the codec to the
# stage's model dtype (e.g. bf16), while the quantizer's RVQ codebooks
# often stay in float32 because they're embedded lookups. A defensive
# cast keeps the matmul homogeneous.
quantized = quantized.to(dtype=self.fc2.weight.dtype)
quantized = self.fc2(quantized.transpose(1, 2)).transpose(1, 2)
# Acoustic decoder may have parameters in yet another dtype — match
# its first parameter so the linear/conv ops stay consistent.
first_param = next(self.acoustic_decoder.parameters(), None)
if first_param is not None and quantized.dtype != first_param.dtype:
quantized = quantized.to(dtype=first_param.dtype)
audio = self.acoustic_decoder(quantized)
if audio.dim() == 2:
audio = audio.unsqueeze(1)
return audio.to(device)
@torch.inference_mode()
def forward_chunk(
self,
audio_codes: torch.Tensor,
*,
left_context_size: int = 0,
hop_length: int | None = None,
) -> torch.Tensor:
"""Chunked decode that trims ``left_context_size * hop_length`` samples
off the leading edge of the upsampled PCM. Mirrors the qwen3_tts
``talker2code2wav_async_chunk`` overlap contract.
"""
if left_context_size < 0:
raise ValueError(f"left_context_size must be >= 0; got {left_context_size}")
hop = int(hop_length) if hop_length is not None else self.hop_length
if hop <= 0:
raise ValueError(f"hop_length must be > 0; got {hop}")
pcm = self.decode_codes(audio_codes)
if left_context_size == 0:
return pcm
trim = left_context_size * hop
if pcm.shape[-1] <= trim:
return pcm[..., :0]
return pcm[..., trim:]
# ---------------------------------------------------- vLLM runtime forward
@torch.no_grad()
def forward(
self,
input_ids: torch.Tensor | None = None,
positions: torch.Tensor | None = None,
intermediate_tensors: Any = None,
inputs_embeds: torch.Tensor | None = None,
runtime_additional_information: list[dict[str, Any]] | None = None,
**kwargs: Any,
) -> torch.Tensor | OmniOutput:
"""Dual-mode forward.
- When ``input_ids`` is a 3-D ``[B, num_codebooks, T]`` tensor we treat
this as a direct decode call (legacy API) and return raw PCM.
- When ``input_ids`` is a flat 1-D / 2-D tensor we treat it as the
engine runtime payload (codebook-major flat per request) and return
an :class:`OmniOutput` carrying multimodal audio.
"""
# Legacy direct-decode signature: caller passed a 3-D code tensor as input_ids.
if isinstance(input_ids, torch.Tensor) and input_ids.ndim == 3:
return self.decode_codes(input_ids)
sr_val = int(self.sample_rate)
sr_tensor = torch.tensor(sr_val, dtype=torch.int32)
empty = torch.zeros((0,), dtype=torch.float32)
if input_ids is None or input_ids.numel() == 0:
return OmniOutput(
text_hidden_states=None,
multimodal_outputs={"model_outputs": [empty], "sr": [sr_tensor]},
)
ids = input_ids.reshape(-1).to(dtype=torch.long)
request_ids_list = self._split_request_ids(ids, kwargs.get("seq_token_counts"))
left_context_size = [0] * len(request_ids_list)
if runtime_additional_information is not None:
for i, info in enumerate(runtime_additional_information):
if i >= len(left_context_size):
break
meta = info.get("meta", {}) if isinstance(info, dict) else {}
if "left_context_size" in meta:
left_context_size[i] = int(meta["left_context_size"])
wavs: list[torch.Tensor] = []
for i, req_ids in enumerate(request_ids_list):
n = int(req_ids.numel())
if n == 0:
wavs.append(empty)
continue
if n % self.num_codebooks != 0:
logger.warning(
"HiggsAudioV2Code2Wav: flat code length %d not divisible by num_codebooks=%d; dropping",
n,
self.num_codebooks,
)
wavs.append(empty)
continue
frames = n // self.num_codebooks
codes_qf = req_ids.reshape(self.num_codebooks, frames)
codes_bqf = codes_qf.unsqueeze(0)
try:
pcm = self.forward_chunk(
codes_bqf,
left_context_size=left_context_size[i],
hop_length=self.hop_length,
)
except ValueError as exc:
logger.warning("HiggsAudioV2Code2Wav: decode skipped (%s)", exc)
wavs.append(empty)
continue
wavs.append(pcm.squeeze(0).squeeze(0).to(torch.float32).cpu())
return OmniOutput(
text_hidden_states=None,
multimodal_outputs={
"model_outputs": wavs,
"sr": [sr_tensor] * len(wavs),
},
)
# --------------------------------------------------------------- helpers
def _validate_codes(self, audio_codes: torch.Tensor) -> torch.Tensor:
"""Ensure shape and value range; reject stream specials with ValueError."""
if not isinstance(audio_codes, torch.Tensor):
raise TypeError(f"audio_codes must be a torch.Tensor, got {type(audio_codes)!r}")
if audio_codes.ndim != 3:
raise ValueError(
f"audio_codes must have shape [B, num_codebooks={self.num_codebooks}, T]; "
f"got shape {tuple(audio_codes.shape)}"
)
if int(audio_codes.shape[1]) != self.num_codebooks:
raise ValueError(
f"audio_codes second dim must equal num_codebooks={self.num_codebooks}; got {int(audio_codes.shape[1])}"
)
if audio_codes.numel() > 0:
max_val = int(audio_codes.max().item())
min_val = int(audio_codes.min().item())
if max_val >= self.num_real_codes or min_val < 0:
raise ValueError(
"audio_codes contains stream-special or out-of-range IDs: "
f"min={min_val}, max={max_val}; real code range is "
f"[0, {self.num_real_codes - 1}]. Filter audio_stream_bos_id="
f"{self.config.audio_stream_bos_id} and audio_stream_eos_id="
f"{self.config.audio_stream_eos_id} (and anything above) at "
"Stage 0 before sending codes to the codec decoder."
)
return audio_codes
@staticmethod
def _split_request_ids(ids: torch.Tensor, seq_token_counts: list[int] | None = None) -> list[torch.Tensor]:
"""Split a concatenated flat-codes tensor into per-request segments."""
if seq_token_counts is not None and len(seq_token_counts) > 1:
boundaries = [0]
for count in seq_token_counts:
boundaries.append(boundaries[-1] + int(count))
n = int(ids.numel())
return [ids[boundaries[i] : min(boundaries[i + 1], n)] for i in range(len(seq_token_counts))]
return [ids]
# Engine-side architecture identifier alias (mirrors Qwen3TTSCode2Wav usage).
HiggsAudioV2Code2WavForConditionalGeneration = HiggsAudioV2Code2Wav
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,332 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""TTS prompt builder + scope validators for higgs-audio v2.
vllm-omni's higgs path supports two request shapes:
* **Plain text -> 24 kHz speech.** :func:`build_plain_text_prompt` runs the
upstream HF processor with a bare ``"Generate audio following instruction."``
system prompt; the emitted ``input_ids`` are byte-identical to upstream.
* **Voice clone (shallow).** :func:`build_voice_clone_prompt` runs the
upstream HF processor with both a target text turn and a reference
``(ref_audio, ref_text)`` ICL turn; the processor returns ``input_ids``
pre-expanded with audio placeholders plus an ``audio_input_ids`` tensor
carrying the encoded reference codes (HF tokenizer encodes audio on the
spot — no encoder vendored in vllm-omni).
Still out of scope and rejected with explicit 4xx: multi-speaker
``[SPEAKERn]`` dialogue, ``profile:`` text-only speaker descriptions, the
``ref_audio_in_system_message`` system-block variant, and chunked long-form
generation.
"""
from __future__ import annotations
import os
import re
from typing import Any
import numpy as np
import torch
__all__ = [
"UnsupportedInputError",
"MULTI_SPEAKER_TAG_PATTERN",
"validate_plain_text_input",
"build_plain_text_conversation",
"build_plain_text_prompt",
"build_voice_clone_conversation",
"build_voice_clone_prompt",
"input_ids_to_python_list",
]
class UnsupportedInputError(ValueError):
"""Raised when a request asks for an out-of-scope higgs_audio_v2 feature."""
# Matches the upstream multi-speaker SPEAKERn tag, e.g. [SPEAKER0], [SPEAKER12].
MULTI_SPEAKER_TAG_PATTERN = re.compile(r"\[SPEAKER\d+\]", re.IGNORECASE)
def validate_plain_text_input(text: str) -> None:
"""Reject multi-speaker tags inside the user text body.
Phase-1 explicitly does NOT support multi-speaker dialogue. Catching the
pattern here means the rejection happens at the tokenizer boundary and is
visible to both offline (`pipeline.py`) and online (`serving_speech.py`)
code paths.
"""
if not isinstance(text, str):
raise UnsupportedInputError(f"higgs_audio_v2 expects plain text input; got {type(text).__name__}")
if MULTI_SPEAKER_TAG_PATTERN.search(text):
raise UnsupportedInputError(
"higgs_audio_v2 v1 does not support multi-speaker [SPEAKERn] tags; received text contains a speaker tag"
)
def build_plain_text_conversation(text: str) -> list[dict[str, Any]]:
"""Build the canonical single-speaker plain-text conversation.
Uses the bare system prompt ``"Generate audio following instruction."``
that matches the upstream HF reference's input formatting; this exact
wording is required for input-token parity with the upstream processor.
"""
validate_plain_text_input(text)
system_prompt = "Generate audio following instruction."
return [
{
"role": "system",
"content": [{"type": "text", "text": system_prompt}],
},
{
"role": "user",
"content": [{"type": "text", "text": text}],
},
]
def build_plain_text_prompt(
processor: Any,
text: str,
*,
sampling_rate: int = 24000,
return_tensors: str | None = "pt",
) -> dict[str, Any]:
"""Run the upstream processor's chat template on a plain-text input.
Returns the processor output dict (``input_ids`` plus any auxiliary tensors
such as ``attention_mask``). The serving layer passes ``input_ids`` to
Stage 0 as ``prompt_token_ids`` after a ``.tolist()``.
Using the upstream processor verbatim (no system-prompt rewriting) is
what preserves input-token parity with the HF reference.
"""
conversation = build_plain_text_conversation(text)
inputs = processor.apply_chat_template(
conversation,
add_generation_prompt=True,
tokenize=True,
return_dict=True,
sampling_rate=sampling_rate,
return_tensors=return_tensors,
)
if "input_ids" not in inputs:
raise RuntimeError(f"HiggsAudioV2 processor returned no input_ids; got keys {list(inputs.keys())!r}")
return inputs
def input_ids_to_python_list(inputs: dict[str, Any]) -> list[int]:
"""Convenience: pull a flat ``list[int]`` of token IDs from a processor output."""
ids = inputs["input_ids"]
if isinstance(ids, torch.Tensor):
if ids.ndim == 2 and int(ids.shape[0]) != 1:
raise ValueError(f"expected batch=1 prompt; got input_ids shape {tuple(ids.shape)}")
return ids.reshape(-1).tolist()
return list(ids)
_AUDIO_OUT_TOKEN = "<|AUDIO_OUT|>"
_AUDIO_OUT_BOS_TOKEN = "<|audio_out_bos|>"
_AUDIO_EOS_TOKEN = "<|audio_eos|>"
_AUDIO_DELAY_TOKEN = "<|reserved_special_token_6|>"
_AUDIO_STREAM_BOS_ID = 1024
_AUDIO_STREAM_EOS_ID = 1025
def _build_delay_pattern(codes: torch.Tensor) -> torch.Tensor:
"""Apply the upstream delay-pattern wrap to a ``[num_codebooks, T]`` code tensor.
Mirrors ``HiggsAudioV2Processor.build_delay_pattern``: prepend BOS, append
EOS, then arrange in a triangular pattern that stretches the sequence by
``num_codebooks - 1`` frames so codebook k starts emitting real codes at
frame k.
"""
num_codebooks, seq_len = codes.shape
bos = codes.new_full((num_codebooks, 1), _AUDIO_STREAM_BOS_ID)
eos = codes.new_full((num_codebooks, 1), _AUDIO_STREAM_EOS_ID)
wrapped = torch.cat([bos, codes, eos], dim=1)
wrapped_len = wrapped.shape[1]
new_seq_len = wrapped_len + num_codebooks - 1
output = torch.ones((1, num_codebooks, new_seq_len), dtype=codes.dtype, device=codes.device)
bos_mask = torch.tril(output, -1) > 0
eos_mask = torch.triu(output, wrapped_len) > 0
data_mask = ~(bos_mask | eos_mask)
output[bos_mask] = _AUDIO_STREAM_BOS_ID
output[data_mask] = wrapped.reshape(-1)
output[eos_mask] = _AUDIO_STREAM_EOS_ID
return output[0]
_ENCODER_CACHE: Any | None = None
_K2_OMNIVOICE_REPO = "k2-fsa/OmniVoice"
_K2_OMNIVOICE_SUBDIR = "audio_tokenizer"
def _load_audio_tokenizer():
"""Load the higgs-audio v2 codec via HF ``HiggsAudioV2TokenizerModel``.
The boson-ai standalone tokenizer repo (``bosonai/higgs-audio-v2-tokenizer``)
ships a ``model.safetensors`` that is actually a copy of the 3B talker LM,
not the codec — pointing HF's ``from_pretrained`` at it yields an
encoder/decoder with randomly initialized structural weights, producing
noise codes at encode time. The k2-fsa OmniVoice repo bundles the same
codec weights repackaged under
``audio_tokenizer/{config.json,model.safetensors,preprocessor_config.json}``
with key naming aligned to ``HiggsAudioV2TokenizerModel``'s class layout
(``acoustic_encoder.*`` / ``acoustic_decoder.*`` / ``quantizer.quantizers.*``
/ ``fc/fc2`` / ``semantic_model.*``), so HF can load it directly.
Only the ``audio_tokenizer/`` subdirectory (~806 MB) is downloaded.
"""
from huggingface_hub import snapshot_download
from transformers import HiggsAudioV2TokenizerModel
repo_path = snapshot_download(
_K2_OMNIVOICE_REPO,
allow_patterns=[f"{_K2_OMNIVOICE_SUBDIR}/*"],
)
audio_tokenizer_dir = os.path.join(repo_path, _K2_OMNIVOICE_SUBDIR)
device = "cuda" if torch.cuda.is_available() else "cpu"
model = HiggsAudioV2TokenizerModel.from_pretrained(audio_tokenizer_dir).to(device)
return model.eval()
def _encode_ref_audio_codes(
wav: np.ndarray,
sr: int,
) -> torch.Tensor:
"""Encode a single ref clip to codec codes via HF ``HiggsAudioV2TokenizerModel``.
Returns shape ``[num_codebooks, T_raw]`` (before BOS/EOS + delay-pattern wrap).
"""
import torchaudio
global _ENCODER_CACHE
if _ENCODER_CACHE is None:
try:
_ENCODER_CACHE = _load_audio_tokenizer()
except ImportError as exc:
raise RuntimeError(
"higgs_audio_v2 voice clone needs `transformers>=5.3.0` "
"(which ships the HiggsAudioV2TokenizerModel class). "
"Install via `pip install -U 'transformers>=5.3.0'`."
) from exc
target_sr = int(getattr(_ENCODER_CACHE.config, "sample_rate", 24000))
wav_t = torch.as_tensor(wav, dtype=torch.float32).reshape(-1)
if sr and sr != target_sr:
wav_t = torchaudio.functional.resample(wav_t, sr, target_sr)
# HF encode() expects (batch=1, channels=1, num_samples).
input_values = wav_t.unsqueeze(0).unsqueeze(0).to(_ENCODER_CACHE.device)
with torch.inference_mode():
codes = _ENCODER_CACHE.encode(input_values, return_dict=False)
# codes shape: (batch=1, num_quantizers, codes_length) -> (num_quantizers, T).
if codes.dim() == 3:
codes = codes.squeeze(0)
return codes.detach().to("cpu").long()
def build_voice_clone_conversation(
text: str,
ref_text: str,
) -> list[dict[str, Any]]:
"""ChatML conversation for voice clone (HF jinja-template-compatible).
The assistant turn is a list with a single ``{"type": "audio"}`` content
block — no ``"audio"``/``"url"``/``"path"`` key, so ``apply_chat_template``
won't try to extract audio data (that path would collide with our explicit
audio encoder). The template renders the assistant block as the literal
``<|audio_out_bos|><|AUDIO_OUT|><|audio_eos|>``; we expand the single
``<|AUDIO_OUT|>`` token to ``N × audio_token + (num_codebooks-1) × delay_token``
in :func:`build_voice_clone_prompt` to match the reference clip's frame count.
"""
validate_plain_text_input(text)
validate_plain_text_input(ref_text)
return [
{"role": "system", "content": "Generate audio following instruction."},
{"role": "user", "content": ref_text},
{"role": "assistant", "content": [{"type": "audio"}]},
{"role": "user", "content": text},
]
def build_voice_clone_prompt(
processor: Any,
text: str,
ref_audio_wav: np.ndarray | torch.Tensor,
ref_audio_sr: int,
ref_text: str,
*,
return_tensors: str | None = "pt",
) -> dict[str, Any]:
"""Build a voice-clone prompt using the upstream boson audio tokenizer.
Returns a dict carrying:
- ``prompt_token_ids``: ``list[int]`` — input_ids with the ref-audio
``<|AUDIO_OUT|>`` + ``<|reserved_special_token_6|>`` placeholders
already expanded to match the encoded reference clip's frame count.
- ``audio_input_ids``: ``Tensor[T_frames, num_codebooks]`` — encoded
reference codes with BOS/EOS + delay pattern, transposed to ``[T, Q]``
for parity with the HF processor output shape.
- ``audio_input_ids_mask``: ``Tensor[T_frames]`` — all-True bool mask.
"""
if isinstance(ref_audio_wav, torch.Tensor):
wav = ref_audio_wav.detach().to("cpu").float().reshape(-1).numpy()
else:
wav = np.asarray(ref_audio_wav, dtype=np.float32).reshape(-1)
# 1. Encode via the upstream boson tokenizer (real weights from model.pth).
codes_qt = _encode_ref_audio_codes(wav, ref_audio_sr) # [num_codebooks, T_raw]
if codes_qt.ndim == 3:
codes_qt = codes_qt[0]
num_codebooks = int(codes_qt.shape[0])
# 2. Apply BOS/EOS + delay-pattern wrap.
audio_input_ids = _build_delay_pattern(codes_qt) # [num_codebooks, T_full]
T_full = int(audio_input_ids.shape[1])
# 3. Render the chat template, then expand the single <|AUDIO_OUT|> marker
# in the assistant turn into the full placeholder block. After expansion
# the text contains exactly T_full audio-mask positions, matching the
# audio_input_ids time axis.
conversation = build_voice_clone_conversation(text, ref_text)
rendered = processor.tokenizer.apply_chat_template(
conversation,
add_generation_prompt=True,
tokenize=False,
)
n_delay = num_codebooks - 1
n_audio = T_full - n_delay
if n_audio < 0:
raise RuntimeError(f"ref clip too short ({T_full} frames) for delay pattern with num_codebooks={num_codebooks}")
placeholders = _AUDIO_OUT_TOKEN * n_audio + _AUDIO_DELAY_TOKEN * n_delay
expanded_assistant = f"{_AUDIO_OUT_BOS_TOKEN}{placeholders}{_AUDIO_EOS_TOKEN}"
if _AUDIO_OUT_TOKEN not in rendered:
raise RuntimeError(
f"Voice-clone chat-template render is missing the assistant "
f"audio placeholder marker. conversation={conversation!r}"
)
rendered = rendered.replace(_AUDIO_OUT_TOKEN, expanded_assistant, 1)
# 4. Tokenize the rendered prompt. ``apply_chat_template`` already emits
# ``<|begin_of_text|>``, so disable add_special_tokens.
encoded = processor.tokenizer(
rendered,
add_special_tokens=False,
return_tensors=return_tensors,
)
prompt_token_ids = encoded["input_ids"]
if isinstance(prompt_token_ids, torch.Tensor):
prompt_token_ids = prompt_token_ids.reshape(-1).tolist()
# 5. Transpose codes to [T_full, num_codebooks] for HF parity.
audio_input_ids_t = audio_input_ids.transpose(0, 1).contiguous().to(torch.long)
audio_input_ids_mask = torch.ones(T_full, dtype=torch.bool)
return {
"prompt_token_ids": prompt_token_ids,
"audio_input_ids": audio_input_ids_t,
"audio_input_ids_mask": audio_input_ids_mask,
}
@@ -0,0 +1,49 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""higgs-audio v2 pipeline: Talker (text -> 8-codebook codec) -> Code2Wav (codec -> 24 kHz PCM)."""
from vllm_omni.config.stage_config import (
PipelineConfig,
StageExecutionType,
StagePipelineConfig,
)
_PROC = "vllm_omni.model_executor.stage_input_processors.higgs_audio_v2"
HIGGS_AUDIO_V2_PIPELINE = PipelineConfig(
model_type="higgs_audio_v2",
model_arch="HiggsAudioV2ForConditionalGeneration",
hf_architectures=("HiggsAudioV2ForConditionalGeneration",),
stages=(
StagePipelineConfig(
stage_id=0,
model_stage="higgs_audio_v2",
execution_type=StageExecutionType.LLM_AR,
input_sources=(),
owns_tokenizer=True,
engine_output_type="latent",
async_chunk_process_next_stage_input_func=(f"{_PROC}.talker2code2wav_async_chunk"),
sampling_constraints={
"detokenize": False,
# Two stop signals for Stage-0:
# * 128009 = standard LM eos_token_id (sequence-level stop)
# * 128012 = audio_eos_token_id (forced by the talker's
# _apply_audio_mode_bias at audio-ramp completion; matches
# upstream HiggsAudioModel._sample_audio_tokens override).
"stop_token_ids": [128009, 128012],
},
),
StagePipelineConfig(
stage_id=1,
model_stage="code2wav",
execution_type=StageExecutionType.LLM_GENERATION,
input_sources=(0,),
final_output=True,
final_output_type="audio",
engine_output_type="audio",
model_arch="HiggsAudioV2Code2WavForConditionalGeneration",
sync_process_input_func=f"{_PROC}.talker2code2wav",
sampling_constraints={"detokenize": True},
),
),
)
@@ -84,7 +84,7 @@ from vllm.multimodal.processing import (
PromptUpdateDetails,
)
from vllm.sequence import IntermediateTensors
from vllm.transformers_utils.tokenizer import get_tokenizer
from vllm.tokenizers import get_tokenizer
from vllm.utils.tensor_schema import TensorSchema
from vllm.v1.outputs import SamplerOutput
from vllm.v1.sample.metadata import SamplingMetadata
@@ -549,13 +549,17 @@ class MiMoAudioLLMForConditionalGeneration(nn.Module, SupportsMultiModal, Suppor
# do_sample=True here without also routing vLLM's sampled token back into
# this gate check would cause the two to diverge and corrupt KV-cache state.
self.global_sampler = MiMoSampler(do_sample=False, temperature=0.6, top_p=0.95)
# local_sampler drives audio-code generation inside local_forward. It is
# entirely internal and NOT subject to vLLM's SamplingParams, so stochastic
# sampling is safe here and is required to produce natural, varied speech.
# Setting do_sample=True also disables the CUDA-graph path (use_cg gate in
# local_forward checks `do_sample is False`), preventing MiMoLocalSamplerTensor
# from silently forcing argmax even when temperature > 0.
self.local_sampler = MiMoSampler(do_sample=True, temperature=0.9, top_p=0.95)
# local_sampler drives audio-code generation inside local_forward. Keep
# it greedy (do_sample=False) so the CUDA-graph path (use_cg gate in
# local_forward) stays active AND so the audio codes — and therefore the
# `new_audio_emb` written into `_cached_new_audio_emb_by_req` — are
# deterministic. That cache is fed back into `inputs_embeds` on the next
# decode step (see `_prepare_multimodal_embeddings_with_cache`), so any
# stochasticity here propagates into subsequent *text* logits via the
# audio-embedding feedback path and destabilises text continuations even
# though `global_sampler` is greedy. Voice diversity must be tackled in
# the codec/vocoder path (stage-1), not by randomising local_sampler.
self.local_sampler = MiMoSampler(do_sample=False, temperature=0.9, top_p=0.95)
self.removed_tokens = None
self.speech_vocab_sizes = config.parsed_speech_vocab_sizes()
@@ -818,7 +822,7 @@ class MiMoAudioLLMForConditionalGeneration(nn.Module, SupportsMultiModal, Suppor
device=tokens_device,
)
if local_sampler is None:
local_sampler = MiMoSampler(do_sample=True, temperature=0.9, top_p=0.95)
local_sampler = MiMoSampler(do_sample=False, temperature=0.9, top_p=0.95)
past_key_values = DynamicCache()
for t in range(delay_iters):
@@ -864,7 +868,7 @@ class MiMoAudioLLMForConditionalGeneration(nn.Module, SupportsMultiModal, Suppor
local_sampler: MiMoSampler | None = None,
):
if local_sampler is None:
local_sampler = MiMoSampler(do_sample=True, temperature=0.9, top_p=0.95)
local_sampler = MiMoSampler(do_sample=False, temperature=0.9, top_p=0.95)
b = int(local_embeds.shape[0])
use_cg = (local_sampler.do_sample is None or local_sampler.do_sample is False) and bool(
@@ -39,6 +39,7 @@ MIMO_AUDIO_PIPELINE = PipelineConfig(
owns_tokenizer=True,
engine_output_type="latent",
async_chunk_process_next_stage_input_func=(f"{_PROC}.llm2code2wav_async_chunk"),
custom_process_next_stage_input_func=f"{_PROC}.llm2code2wav_full_payload",
sampling_constraints={
"detokenize": True,
# Stop once the speech/text interleaved span ends. Code2Wav
@@ -55,7 +56,8 @@ MIMO_AUDIO_PIPELINE = PipelineConfig(
final_output=True,
final_output_type="audio",
engine_output_type="audio",
sync_process_input_func=f"{_PROC}.llm2code2wav",
custom_process_input_func=f"{_PROC}.llm2code2wav",
sync_process_input_func=f"{_PROC}.llm2code2wav_token_only",
sampling_constraints={"detokenize": False},
),
),
@@ -126,15 +126,21 @@ class MingFlashOmniForConditionalGeneration(
self.make_empty_intermediate_tensors = self.thinker.make_empty_intermediate_tensors
elif self.model_stage == "imagegen":
# TODO: Implement image generator stage
# Image generation is a separate diffusion stage; it does not run
# through this AR wrapper. See
# `vllm_omni/diffusion/models/ming_flash_omni/pipeline_ming_imagegen.py`
# and `model_arch: MingImagePipeline` in the deploy YAML.
raise NotImplementedError(
"Image generation stage is not yet implemented. Please use model_stage='thinker' for now."
"Image generation stage is not implemented in this AR wrapper. "
"Use the DIFFUSION execution_type with model_arch: MingImagePipeline "
"for the imagegen stage (see vllm_omni/deploy/ming_flash_omni_image.yaml)."
)
else:
raise ValueError(
f"Invalid model_stage: {self.model_stage!r}. Must be one of: 'thinker', 'imagegen'. "
f"For the talker stage, use MingFlashOmniTalkerForConditionalGeneration directly."
f"For the talker stage, use MingFlashOmniTalkerForConditionalGeneration directly. "
f"For image generation use stage_type: diffusion with model_arch: MingImagePipeline."
)
def forward(
@@ -177,9 +183,43 @@ class MingFlashOmniForConditionalGeneration(
raise NotImplementedError("get_mrope_input_positions not available on current stage")
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
stripped = ((name.removeprefix("thinker."), value) for name, value in weights)
thinker_loaded = self.thinker.load_weights(stripped)
return add_prefix_to_loaded_weights(thinker_loaded, "thinker")
loaded_weights: set[str] = set()
thinker_weights: list[tuple[str, torch.Tensor]] = []
for name, value in weights:
if name.startswith("thinker."):
thinker_weights.append((name, value))
elif name.startswith("imagegen."):
# Imagegen weights are loaded by MingImagePipeline (diffusion
# stage) from its own checkpoint subfolders; silently drop
# them here so the AR wrapper does not try to load them.
continue
elif name.startswith("talker."):
# Talker weights are loaded by
# MingFlashOmniTalkerForConditionalGeneration directly; drop.
continue
else:
# Weights without prefix go to thinker by default
thinker_weights.append((name, value))
if self.model_stage == "thinker" and thinker_weights:
stripped = ((name.removeprefix("thinker."), value) for name, value in thinker_weights)
thinker_loaded = self.thinker.load_weights(stripped)
thinker_loaded = add_prefix_to_loaded_weights(thinker_loaded, "thinker")
loaded_weights.update(thinker_loaded)
# ``query_tokens_dict.*`` parameters are pre-loaded inside
# ``MingFlashOmniThinker.__init__`` from
# ``<model>/mlp/model.safetensors`` (not the main shard index),
# so vllm's default loader does not see them via the standard
# ``load_weights`` path. Report them as loaded here to satisfy the
# post-load completeness check.
query_tokens_module = getattr(self.thinker, "query_tokens_dict", None)
if query_tokens_module is not None:
for scale_name, _param in query_tokens_module.items():
loaded_weights.add(f"thinker.query_tokens_dict.{scale_name}")
return loaded_weights
def get_mm_mapping(self) -> MultiModelKeys:
return MultiModelKeys.from_string_field(
@@ -6,6 +6,7 @@
"""Ming-flash-omni-2.0 Thinker stage implementation (multimodal understanding)."""
import os
from collections.abc import Iterable, Iterator, Mapping, Sequence
from typing import Annotated, Any
@@ -113,7 +114,9 @@ class MingFlashOmniThinkerProcessingInfo(Qwen2VLProcessingInfo):
return 1
def get_supported_mm_limits(self) -> Mapping[str, int | None]:
return {"image": None, "video": None, "audio": None}
# ``img2img`` is the serving-layer alias for a reference image in the
# image-gen path; treated as a regular image by ``_MingMultiModalDataParser``.
return {"image": None, "video": None, "audio": None, "img2img": 1}
def get_mm_max_tokens_per_item(
self,
@@ -137,7 +140,14 @@ class MingFlashOmniThinkerProcessingInfo(Qwen2VLProcessingInfo):
return mm_max_tokens
def get_feature_extractor(self, **kwargs: object) -> MingWhisperFeatureExtractor:
def get_feature_extractor(self, **kwargs: object):
"""Return the audio feature extractor from the processor.
The processor may be loaded via trust_remote_code paths that return
a stock transformers ``WhisperFeatureExtractor`` rather than
vllm-omni's subclass ``MingWhisperFeatureExtractor``. We accept both
as long as the caller-needed attributes (``sampling_rate``) exist.
"""
hf_processor = self.get_hf_processor(**kwargs)
feature_extractor = hf_processor.audio_processor
assert isinstance(feature_extractor, MingWhisperFeatureExtractor)
@@ -145,13 +155,56 @@ class MingFlashOmniThinkerProcessingInfo(Qwen2VLProcessingInfo):
def get_data_parser(self):
feature_extractor = self.get_feature_extractor()
return MultiModalDataParser(
return _MingMultiModalDataParser(
target_sr=feature_extractor.sampling_rate,
target_channels=self.get_target_channels(),
expected_hidden_size=self._get_expected_hidden_size(),
)
class _MingMultiModalDataParser(MultiModalDataParser):
"""Rewrite ``img2img`` → ``image`` in-place so the thinker embeds the ref.
Matches Ming's upstream (``processing_bailingmm2.py::__call__``): when
``images`` is provided the image_processor runs → pixel_values + image_grid_thw,
and ``_expand_image_tokens`` expands ``<IMAGE>`` placeholders in the text
to ``<imagePatch>*N``. The same PIL then ALSO goes to the diffusion stage
as ``image_gen_pixel_values_reference``.
On vllm-omni's serving path serving_chat emits
``multi_modal_data={"img2img": PIL}`` (Bagel convention). We mutate the
caller's mm_data dict here — moving the PIL from the ``img2img`` key into
the ``image`` key — so that:
* vLLM's renderer validator sees consistent keys in
``mm_data`` and the parser output (``mm_data_items["image"]``)
* The thinker-side image path (``_call_hf_processor`` reads
``mm_data["images"]``, ``_get_prompt_updates`` replaces ``<IMAGE>``
placeholders, ``_get_mm_fields_config`` declares image field layout)
all run normally with the ref PIL acting as a regular image input
* ``thinker2imagegen`` still finds the ref PIL — but now under
``multi_modal_data["image"]`` rather than ``["img2img"]``.
A companion prepend in ``_apply_hf_processor_main`` ensures the prompt
text carries a matching ``<IMAGE>`` placeholder when needed.
"""
def parse_mm_data(self, mm_data):
if "img2img" in mm_data:
img2img = mm_data.pop("img2img")
if not isinstance(img2img, list):
img2img = [img2img]
existing = mm_data.get("image")
if existing is None:
existing_list: list[Any] = []
elif isinstance(existing, list):
existing_list = list(existing)
else:
existing_list = [existing]
mm_data["image"] = existing_list + img2img
return super().parse_mm_data(mm_data)
class MingFlashOmniThinkerDummyInputsBuilder(BaseDummyInputsBuilder[MingFlashOmniThinkerProcessingInfo]):
def get_dummy_text(self, mm_counts: Mapping[str, int]) -> str:
num_images = mm_counts.get("image", 0)
@@ -185,6 +238,8 @@ class MingFlashOmniThinkerDummyInputsBuilder(BaseDummyInputsBuilder[MingFlashOmn
audio_length = int(audio_duration * sample_rate)
num_img2img = mm_counts.get("img2img", 0)
mm_data: MultiModalDataDict = {
"image": self._get_dummy_images(
width=image_width,
@@ -200,6 +255,13 @@ class MingFlashOmniThinkerDummyInputsBuilder(BaseDummyInputsBuilder[MingFlashOmn
"audio": [(np.random.randn(audio_length).astype(np.float32), sample_rate) for _ in range(num_audios)],
}
if num_img2img > 0:
mm_data["img2img"] = self._get_dummy_images(
width=image_width,
height=image_height,
num_images=num_img2img,
)
return mm_data
@@ -396,6 +458,61 @@ class MingFlashOmniThinkerMultiModalProcessor(BaseMultiModalProcessor[MingFlashO
) -> bool:
return False
def _apply_hf_processor_main(
self,
prompt: str | list[int],
mm_items: MultiModalDataItems,
hf_processor_mm_kwargs: Mapping[str, object],
tokenization_kwargs: Mapping[str, object],
*,
enable_hf_prompt_update: bool,
):
"""Apply Ming-specific prompt rewrites before delegating to vllm's
default text / multimodal processing pipeline.
This is the single point in the base MM-processor call graph where we
still have BOTH the full prompt and the request-level
``hf_processor_mm_kwargs`` together. Downstream, vllm's MM caching
design splits the work into
:meth:`_apply_hf_processor_text_only` (prompt, empty kwargs) and
:meth:`_apply_hf_processor_mm_only` (dummy text, real kwargs), so a
per-request flag like ``modalities`` cannot reach the real
tokenization from inside :meth:`_call_hf_processor`.
For Ming-flash-omni-2.0, image-generation requests carry
``mm_processor_kwargs["modalities"]`` set to ``["image"]`` (t2i) or
``["img2img"]`` (image edit). We expand the prompt here with the
``<image><imagePatch>*N</image>`` query-token block so the expanded
form flows through both the tokenization and (eventual) MM paths.
For img2img, we also prepend ``<IMAGE>`` so the thinker-side prompt
replacement can locate the reference-image placeholder.
"""
modalities = hf_processor_mm_kwargs.get("modalities") or []
is_image_gen = "image" in modalities or "img2img" in modalities
if isinstance(prompt, str) and is_image_gen:
from vllm_omni.model_executor.models.ming_flash_omni.prompt_utils import (
DEFAULT_NUM_QUERY_TOKENS,
maybe_expand_image_gen_prompt,
)
# img2img: prepend ``<IMAGE>`` so the ref-image placeholder survives
# MM caching (when the ref image is cache-warm, the thinker sees 0
# missing items and cannot inject the placeholder itself).
if "img2img" in modalities:
prompt = "<IMAGE>" + prompt
ig = getattr(self.info.ctx.model_config.hf_config, "image_gen_config", None)
num_query_tokens = getattr(ig, "num_query_tokens", DEFAULT_NUM_QUERY_TOKENS)
prompt = maybe_expand_image_gen_prompt(prompt, num_query_tokens=int(num_query_tokens))
return super()._apply_hf_processor_main(
prompt=prompt,
mm_items=mm_items,
hf_processor_mm_kwargs=hf_processor_mm_kwargs,
tokenization_kwargs=tokenization_kwargs,
enable_hf_prompt_update=enable_hf_prompt_update,
)
def _call_hf_processor(
self,
prompt: str,
@@ -408,6 +525,11 @@ class MingFlashOmniThinkerMultiModalProcessor(BaseMultiModalProcessor[MingFlashO
We call the image/audio sub-processors directly (instead of going
through `MingFlashOmniProcessor.__call__`) so that the high-level
placeholder tokens remain **unexpanded** in the tokenized output.
NOTE: Image-gen prompt expansion is handled in
:meth:`_apply_hf_processor_main` — by the time we get here, vllm's
MM caching has already split text/mm processing and ``mm_kwargs``
is empty on the text-only branch.
"""
hf_processor = self.info.get_hf_processor()
tokenizer = self.info.get_tokenizer()
@@ -425,6 +547,8 @@ class MingFlashOmniThinkerMultiModalProcessor(BaseMultiModalProcessor[MingFlashO
videos = mm_data.get("videos", None)
if videos is not None:
# TODO: ``videos=`` on image_processor is deprecated since
# transformers v4.57 (removed in v5); migrate to Qwen2VLVideoProcessor.
video_outputs = hf_processor.image_processor(
images=None,
videos=videos,
@@ -487,8 +611,13 @@ class MingFlashOmniThinkerForConditionalGeneration(
return "<VIDEO>"
elif modality.startswith("audio"):
return "<AUDIO>"
elif modality == "img2img":
# Ming's img2img ref image is consumed only by the diffusion stage
# (``thinker2imagegen`` reads the raw PIL). No text-side placeholder
# is emitted for the thinker.
return None
raise ValueError("Only image, video, or audio modality is supported")
raise ValueError("Only image, video, audio, or img2img modality is supported")
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
super().__init__()
@@ -548,10 +677,79 @@ class MingFlashOmniThinkerForConditionalGeneration(
)
logger.info("Initialized WhisperAudioEncoder and AudioProjector")
# Image-generation learnable query tokens. Stored as a ParameterDict
# keyed by scale name (e.g. "16x16" -> [256, hidden_size]) to mirror
# the upstream Ming layout in ``mlp/query_tokens_dict.<scale>``. These
# are substituted in at ``<imagePatch>`` token positions during
# text-to-image requests; image-comprehension requests continue to
# fill those positions with vision features as before.
self.query_tokens_dict = nn.ParameterDict()
self._load_image_gen_query_tokens(vllm_config.model_config.model)
# Expose interfaces
self.make_empty_intermediate_tensors = self.language_model.make_empty_intermediate_tensors
logger.info("MingFlashOmniThinker initialized with vision and audio towers")
logger.info(
f"MingFlashOmniThinker initialized with: "
f"vision={'yes' if self.vision else 'no'}, "
f"audio={'yes' if self.audio else 'no'}, "
f"image_gen_scales={list(self.query_tokens_dict.keys())}"
)
def _load_image_gen_query_tokens(self, model_path: str) -> None:
"""Load learnable query tokens used for image generation.
Expected layout (observed on inclusionAI/Ming-flash-omni-2.0):
<model_path>/mlp/model.safetensors
key ``query_tokens_dict.<scale>`` -> [num_tokens, hidden_size]
e.g. ``query_tokens_dict.16x16`` -> [256, 4096]
Missing files are logged as a warning and image-gen is disabled
(text-only inference still works).
"""
from pathlib import Path
p = Path(model_path) / "mlp" / "model.safetensors"
if not p.exists() and not os.path.exists(model_path):
from vllm_omni.model_executor.model_loader.weight_utils import (
download_weights_from_hf_specific,
)
try:
local_path = download_weights_from_hf_specific(model_path, None, ["mlp/*"])
p = Path(local_path) / "mlp" / "model.safetensors"
except Exception:
logger.exception("[MingFlashOmniThinker] failed to download mlp/ from %s", model_path)
if not p.exists():
logger.warning(
"[MingFlashOmniThinker] mlp/model.safetensors not found at %s; "
"text-to-image will be disabled (text-only inference still works).",
p,
)
return
try:
from safetensors.torch import load_file # type: ignore
state = load_file(str(p))
except Exception:
logger.exception("[MingFlashOmniThinker] failed to read %s", p)
return
loaded = 0
for key, tensor in state.items():
if not key.startswith("query_tokens_dict."):
continue
scale_name = key.split(".", 1)[1]
param = nn.Parameter(tensor.clone(), requires_grad=False)
self.query_tokens_dict[scale_name] = param
loaded += 1
logger.info(
"[MingFlashOmniThinker] loaded query_tokens_dict[%s] shape=%s dtype=%s",
scale_name,
tuple(tensor.shape),
tensor.dtype,
)
if loaded == 0:
logger.warning("[MingFlashOmniThinker] no query_tokens_dict.* keys in mlp/model.safetensors")
def extract_image_feature(self, pixel_values: torch.Tensor, grid_thw: torch.Tensor) -> torch.Tensor:
"""Extract and project image features.
@@ -732,14 +930,86 @@ class MingFlashOmniThinkerForConditionalGeneration(
) -> torch.Tensor:
inputs_embeds = self.language_model.model.word_embeddings(input_ids)
if multimodal_embeddings is None or len(multimodal_embeddings) == 0:
return inputs_embeds
# Step 1: if vision/audio features were extracted, merge them into
# inputs_embeds at their <patch> positions first. This fills ref-image
# and other normal vision-input positions with real features.
if multimodal_embeddings is not None and len(multimodal_embeddings) > 0:
assert is_multimodal is not None, "`is_multimodal` mask required when `multimodal_embeddings` provided"
inputs_embeds = _merge_multimodal_embeddings(
inputs_embeds=inputs_embeds,
multimodal_embeddings=multimodal_embeddings,
is_multimodal=is_multimodal,
)
assert is_multimodal is not None, "`is_multimodal` mask required when `multimodal_embeddings` provided"
return _merge_multimodal_embeddings(
inputs_embeds=inputs_embeds,
multimodal_embeddings=multimodal_embeddings,
is_multimodal=is_multimodal,
# Step 2: image-gen query tokens are appended at the tail of the prompt
# as a contiguous block of ``<imagePatch>`` tokens. Inject the learnable
# ``query_tokens_dict`` entries at those positions. Running AFTER step 1
# is safe because the query-token block is disjoint from ref-image
# patch positions (ref patches are earlier in the prompt, filled by
# step 1; query tokens occupy the trailing block and get overwritten
# here). Injecting always — including when multimodal embeddings are
# present — matches Ming's img2img-edit flow where BOTH a real image
# input AND the learnable query tokens need to reach the LLM.
if len(self.query_tokens_dict) > 0:
self._maybe_inject_image_gen_query_embeds(input_ids, inputs_embeds)
return inputs_embeds
def _maybe_inject_image_gen_query_embeds(
self,
input_ids: torch.Tensor,
inputs_embeds: torch.Tensor,
) -> None:
"""Overwrite the trailing ``<imagePatch>`` block with learnable query tokens.
The image-gen query-token block is appended at the tail of the prompt
by ``maybe_expand_image_gen_prompt`` as literal text
``<image><imagePatch>*N</image>``. After tokenization:
... <image_start_token> <imagePatch>*N <image_end_token>
is the exact trailing pattern. We verify that signature before
injecting — without the check, a pure vision-understanding request
whose final ref-image block ends in N or more ``<imagePatch>`` tokens
would be misidentified as image-gen and its vision features silently
overwritten. Decode-phase calls (``input_ids`` is one next-token)
naturally fail the signature check and return early.
"""
if input_ids.numel() == 0:
return
patch_token_id = self.config.image_patch_token
image_end_token_id = getattr(self.config, "image_end_token", None)
if image_end_token_id is None:
return
scale_items = list(self.query_tokens_dict.items())
if not scale_items:
return
scale_name, query_param = scale_items[-1]
num_query_tokens = int(query_param.shape[0])
flat = input_ids.view(-1)
L = int(flat.numel())
# Need at least num_query_tokens patch tokens + 1 <image_end> token.
if L < num_query_tokens + 1:
return
# Signature: the prompt must end with <image_end_token>, and the
# N positions immediately before it must all be <imagePatch>.
if int(flat[-1].item()) != image_end_token_id:
return
tail_start = L - 1 - num_query_tokens
tail_end = L - 1 # exclusive — last index is <image_end_token>
if not (flat[tail_start:tail_end] == patch_token_id).all():
return
query_embeds = query_param.to(dtype=inputs_embeds.dtype, device=inputs_embeds.device)
inputs_embeds[tail_start:tail_end] = query_embeds
logger.debug(
"[MingFlashOmniThinker] injected %d image-gen query embeddings (scale=%s) at positions [%d, %d)",
num_query_tokens,
scale_name,
tail_start,
tail_end,
)
def forward(
@@ -58,6 +58,7 @@ MING_FLASH_OMNI_PIPELINE = PipelineConfig(
engine_output_type="audio",
tokenizer_subdir="talker/llm",
custom_process_input_func=f"{_PROC}.thinker2talker",
sync_process_input_func=f"{_PROC}.thinker2talker_token_only",
),
),
)
@@ -104,3 +105,37 @@ MING_FLASH_OMNI_THINKER_ONLY_PIPELINE = PipelineConfig(
),
),
)
# Thinker + image-generation (diffusion) variant: text-to-image / img2img.
MING_FLASH_OMNI_IMAGE_PIPELINE = PipelineConfig(
model_type="ming_flash_omni_image",
model_arch="MingFlashOmniForConditionalGeneration",
stages=(
StagePipelineConfig(
stage_id=0,
model_stage="thinker",
execution_type=StageExecutionType.LLM_AR,
input_sources=(),
final_output=False,
owns_tokenizer=True,
requires_multimodal_data=True,
hf_config_name="thinker_config",
engine_output_type="latent",
prompt_expand_func=f"{_PROC}.expand_cfg_prompts",
sampling_constraints={"detokenize": False},
),
StagePipelineConfig(
stage_id=1,
model_stage="dit",
# Resolved in vllm_omni/diffusion/registry.py.
model_arch="MingImagePipeline",
execution_type=StageExecutionType.DIFFUSION,
input_sources=(0,),
final_output=True,
final_output_type="image",
hf_config_name="image_gen_config",
custom_process_input_func=f"{_PROC}.thinker2imagegen",
),
),
)
@@ -3,12 +3,86 @@
# Copyright (c) Ant Group. All rights reserved.
# Adapted from Ming repo's usage cookbook:
# https://github.com/inclusionAI/Ming/blob/3954fcb880ff5e61ff128bcf7f1ec344d46a6fe3/cookbook.ipynb
"""Shared prompt-building helpers for Ming-flash-omni standalone talker."""
"""Ming-flash-omni-2.0 prompt utilities.
Two unrelated families of helpers live in the same file because they
both belong to the Ming module and are tightly coupled to Ming-specific
prompt conventions:
1. **Image-gen query-token expansion** — string-level helpers used by
the thinker stage to mark the ``<image><imagePatch>*N</image>`` block
that gets substituted with learnable ``query_tokens_dict`` embeddings
during forward.
2. **TTS / talker caption builder** — JSON caption template for the
Ming-flash-omni standalone talker (TTS) stage.
"""
from __future__ import annotations
import copy
import json
from typing import Any
# ============================================================
# Image-gen query-token block (thinker stage)
# ============================================================
# Ming's thinker uses these tokens to mark a learnable image-generation
# query block inside the text prompt. The thinker substitutes its
# ``query_tokens_dict`` embeddings at each ``<imagePatch>`` position
# during forward; see
# ``MingFlashOmniThinker._maybe_inject_image_gen_query_embeds``.
_IMAGE_OPEN_TOKEN = "<image>"
_IMAGE_CLOSE_TOKEN = "</image>"
IMAGE_PATCH_TOKEN = "<imagePatch>"
# Default query-token count matches ``MingImageGenConfig(img_gen_scales=[16])``
# (16 * 16 = 256), which is what the released inclusionAI/Ming-flash-omni-2.0
# checkpoint ships.
DEFAULT_NUM_QUERY_TOKENS = 256
def maybe_expand_image_gen_prompt(
prompt: str,
num_query_tokens: int = DEFAULT_NUM_QUERY_TOKENS,
) -> str:
"""Append the ``<image><imagePatch>*N</image>`` suffix for text-to-image.
The thinker expects image-generation requests to end with an N-wide
block of ``<imagePatch>`` tokens (wrapped in ``<image>``/``</image>``)
— those positions get substituted with learnable
``query_tokens_dict`` embeddings during forward.
This helper is a no-op (returns the input unchanged) when:
* ``prompt`` is not a non-empty string, or
* the prompt already contains an ``<imagePatch>`` block (avoids
double expansion for tests / manual calls that pre-format the
prompt).
Args:
prompt: Raw user prompt text.
num_query_tokens: Total number of query tokens to emit. Defaults
to 256 (the released checkpoint's ``img_gen_scales=[16]``).
Returns:
The (possibly expanded) prompt text.
"""
if not isinstance(prompt, str) or not prompt:
return prompt
if IMAGE_PATCH_TOKEN in prompt:
return prompt
# TODO(multi-scale): single-block emission assumes img_gen_scales=[16].
suffix = _IMAGE_OPEN_TOKEN + (IMAGE_PATCH_TOKEN * num_query_tokens) + _IMAGE_CLOSE_TOKEN
return prompt + suffix
# ============================================================
# TTS / talker caption builder
# ============================================================
DEFAULT_PROMPT = "Please generate speech based on the following description.\n"
BASE_CAPTION_TEMPLATE: dict[str, Any] = {
@@ -48,3 +122,13 @@ def create_instruction(user_input: dict[str, Any]) -> str:
if key in item:
item[key] = value
return json.dumps(caption, ensure_ascii=False)
__all__ = [
"IMAGE_PATCH_TOKEN",
"DEFAULT_NUM_QUERY_TOKENS",
"maybe_expand_image_gen_prompt",
"DEFAULT_PROMPT",
"BASE_CAPTION_TEMPLATE",
"create_instruction",
]
@@ -108,7 +108,10 @@ class OmniVoiceDecoder(nn.Module):
quantized = self.quantizer.decode(codes)
# Project: [B, 1024, T] → fc2 → [B, 256, T]
quantized = self.fc2(quantized.transpose(1, 2)).transpose(1, 2)
# Cast to fc2 weight dtype (may be fp16 when checkpoint stores weights as fp16),
# then upcast back to float32 — acoustic decoder ConvTranspose1d upsampling
# produces intermediate values that exceed the fp16 range (~65504), causing NaN.
quantized = self.fc2(quantized.transpose(1, 2).to(self.fc2.weight.dtype)).transpose(1, 2).float()
# Acoustic decoder: [B, 256, T] → [B, 1, T*960]
audio = self.acoustic_decoder(quantized)
@@ -192,6 +195,11 @@ class OmniVoiceDecoder(nn.Module):
param.data.copy_(state_dict[higgs_name])
loaded += 1
# Checkpoint weights may be fp16; force float32 so ConvTranspose1d
# upsampling doesn't overflow (fp16 max ~65504 is too small for
# intermediate activations in the DAC upsampling chain).
self.acoustic_decoder.float()
# Apply HiggsAudioV2 output padding adjustment
self._adjust_output_padding(self.acoustic_decoder)
@@ -13,6 +13,9 @@ via FlashAttention/SageAttention/SDPA backends.
from __future__ import annotations
import math
import random
import threading
from collections import OrderedDict
import torch
import torch.nn as nn
@@ -24,6 +27,184 @@ from vllm_omni.transformers_utils.configs.omnivoice import OmniVoiceConfig
logger = init_logger(__name__)
# ---------------------------------------------------------------------------
# Triton kernels (inference-only; graceful fallback when triton is absent)
# ---------------------------------------------------------------------------
_TRITON_AVAILABLE = False
try:
import triton
import triton.language as tl
try:
from triton.language.extra.libdevice import rsqrt # noqa: F401
except ModuleNotFoundError:
from triton.language.extra.cuda.libdevice import rsqrt # noqa: F401
def _calculate_settings(n: int) -> tuple[int, int]:
MAX_FUSED_SIZE = 65536
BLOCK_SIZE = triton.next_power_of_2(n)
if BLOCK_SIZE > MAX_FUSED_SIZE:
raise RuntimeError(f"n={n} exceeds max Triton block size {MAX_FUSED_SIZE}")
num_warps = 4
if BLOCK_SIZE >= 32768:
num_warps = 32
elif BLOCK_SIZE >= 8192:
num_warps = 16
elif BLOCK_SIZE >= 2048:
num_warps = 8
return BLOCK_SIZE, num_warps
@triton.jit
def _rms_norm_fwd_kernel(
Y_ptr, # noqa: N803
Y_stride, # noqa: N803
X_ptr, # noqa: N803
X_stride, # noqa: N803
W_ptr, # noqa: N803
n_cols,
eps,
BLOCK_SIZE: tl.constexpr, # noqa: N803
):
row = tl.program_id(0).to(tl.int64)
cols = tl.arange(0, BLOCK_SIZE)
mask = cols < n_cols
x = tl.load(X_ptr + row * X_stride + cols, mask=mask, other=0.0)
w = tl.load(W_ptr + cols, mask=mask, other=0.0)
x_f32 = x.to(tl.float32)
ms = tl.sum(x_f32 * x_f32, axis=0) / n_cols
rstd = rsqrt(ms + eps)
y = (x_f32 * rstd).to(x.dtype) * w
tl.store(Y_ptr + row * Y_stride + cols, y, mask=mask)
def triton_rms_norm(x: torch.Tensor, weight: torch.Tensor, eps: float) -> torch.Tensor:
shape = x.shape
n_cols = shape[-1]
x2d = x.contiguous().view(-1, n_cols)
w = weight.contiguous()
BLOCK_SIZE, num_warps = _calculate_settings(n_cols)
y = torch.empty_like(x2d)
_rms_norm_fwd_kernel[(x2d.shape[0],)](
y,
y.stride(0),
x2d,
x2d.stride(0),
w,
n_cols,
eps,
BLOCK_SIZE=BLOCK_SIZE,
num_warps=num_warps,
)
return y.view(*shape)
@triton.jit
def _swiglu_fwd_kernel(
gate_ptr,
up_ptr,
out_ptr,
stride,
n_cols: tl.constexpr,
BLOCK_SIZE: tl.constexpr, # noqa: N803
):
pid = tl.program_id(0).to(tl.int64)
gate_ptr += pid * stride
up_ptr += pid * stride
out_ptr += pid * stride
cols = tl.arange(0, BLOCK_SIZE)
mask = cols < n_cols
gate = tl.load(gate_ptr + cols, mask=mask, other=0).to(tl.float32)
up = tl.load(up_ptr + cols, mask=mask, other=0)
silu_gate = gate * tl.sigmoid(gate)
out = silu_gate.cast(up.dtype) * up
tl.store(out_ptr + cols, out, mask=mask)
def triton_swiglu(gate: torch.Tensor, up: torch.Tensor) -> torch.Tensor:
gate = gate.contiguous()
up = up.contiguous()
shape = gate.shape
n_cols = shape[-1]
g2d = gate.view(-1, n_cols)
u2d = up.view(-1, n_cols)
out = torch.empty_like(g2d)
BLOCK_SIZE, num_warps = _calculate_settings(n_cols)
_swiglu_fwd_kernel[(g2d.shape[0],)](
g2d,
u2d,
out,
out.stride(0),
n_cols=n_cols,
BLOCK_SIZE=BLOCK_SIZE,
num_warps=num_warps,
)
return out.view(*shape)
@triton.jit
def _fused_add_rms_norm_fwd_kernel(
Y_ptr, # noqa: N803
Y_stride, # noqa: N803
S_ptr, # noqa: N803
S_stride, # noqa: N803
X_ptr, # noqa: N803
X_stride, # noqa: N803
R_ptr, # noqa: N803
R_stride, # noqa: N803
W_ptr, # noqa: N803
n_cols,
eps,
BLOCK_SIZE: tl.constexpr, # noqa: N803
):
row = tl.program_id(0).to(tl.int64)
cols = tl.arange(0, BLOCK_SIZE)
mask = cols < n_cols
x = tl.load(X_ptr + row * X_stride + cols, mask=mask, other=0.0)
r = tl.load(R_ptr + row * R_stride + cols, mask=mask, other=0.0)
dtype = x.dtype
s_f32 = x.to(tl.float32) + r.to(tl.float32)
s = s_f32.to(dtype)
tl.store(S_ptr + row * S_stride + cols, s, mask=mask)
w = tl.load(W_ptr + cols, mask=mask, other=0.0)
ms = tl.sum(s_f32 * s_f32, axis=0) / n_cols
rstd = rsqrt(ms + eps)
y = (s_f32 * rstd).to(dtype) * w
tl.store(Y_ptr + row * Y_stride + cols, y, mask=mask)
def triton_fused_add_rms_norm(
x: torch.Tensor,
residual: torch.Tensor,
weight: torch.Tensor,
eps: float,
) -> tuple[torch.Tensor, torch.Tensor]:
shape = x.shape
n_cols = shape[-1]
x2d = x.contiguous().view(-1, n_cols)
r2d = residual.contiguous().view(-1, n_cols)
w = weight.contiguous()
BLOCK_SIZE, num_warps = _calculate_settings(n_cols)
y = torch.empty_like(x2d)
s = torch.empty_like(x2d)
_fused_add_rms_norm_fwd_kernel[(x2d.shape[0],)](
y,
y.stride(0),
s,
s.stride(0),
x2d,
x2d.stride(0),
r2d,
r2d.stride(0),
w,
n_cols,
eps,
BLOCK_SIZE=BLOCK_SIZE,
num_warps=num_warps,
)
return y.view(*shape), s.view(*shape)
_TRITON_AVAILABLE = True
logger.debug("OmniVoice Triton kernels loaded")
except Exception:
logger.debug("Triton not available; using PyTorch fallback for OmniVoice kernels")
# ---------------------------------------------------------------------------
# Unmasking schedule helpers
# ---------------------------------------------------------------------------
@@ -45,9 +226,13 @@ def _get_time_steps(
return shifted
def _gumbel_sample(logits: torch.Tensor, temperature: float) -> torch.Tensor:
def _gumbel_sample(logits: torch.Tensor, temperature: float, generator: torch.Generator) -> torch.Tensor:
"""Add Gumbel noise for stochastic position selection."""
noise = -torch.log(-torch.log(torch.rand_like(logits).clamp(min=1e-8)))
noise = -torch.log(
-torch.log(
torch.rand(logits.shape, generator=generator, device=logits.device, dtype=logits.dtype).clamp(min=1e-8)
)
)
return logits / max(temperature, 1e-8) + noise
@@ -63,6 +248,8 @@ class OmniVoiceRMSNorm(nn.Module):
self.eps = eps
def forward(self, x: torch.Tensor) -> torch.Tensor:
if _TRITON_AVAILABLE:
return triton_rms_norm(x, self.weight, self.eps)
variance = x.to(torch.float32).pow(2).mean(-1, keepdim=True)
x = x * torch.rsqrt(variance + self.eps)
return self.weight * x.to(self.weight.dtype)
@@ -158,6 +345,8 @@ class OmniVoiceMLP(nn.Module):
self.down_proj = nn.Linear(config.llm_intermediate_size, config.llm_hidden_size, bias=False)
def forward(self, x: torch.Tensor) -> torch.Tensor:
if _TRITON_AVAILABLE:
return self.down_proj(triton_swiglu(self.gate_proj(x), self.up_proj(x)))
return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))
@@ -181,13 +370,22 @@ class OmniVoiceTransformerBlock(nn.Module):
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
hidden_states = self.self_attn(hidden_states, attention_mask=attention_mask, cos=cos, sin=sin)
hidden_states = residual + hidden_states
residual = hidden_states
hidden_states = self.post_attention_layernorm(hidden_states)
if _TRITON_AVAILABLE:
# Fused: (attn_out + residual) + RMSNorm in one kernel
hidden_states, residual = triton_fused_add_rms_norm(
hidden_states,
residual,
self.post_attention_layernorm.weight,
self.post_attention_layernorm.eps,
)
else:
hidden_states = residual + hidden_states
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
@@ -222,6 +420,214 @@ def _apply_rotary_pos_emb(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor)
return x * torch.cat([cos, cos], dim=-1) + rotated * torch.cat([sin, sin], dim=-1)
# ---------------------------------------------------------------------------
# CUDA Graph wrapper
# ---------------------------------------------------------------------------
class _OmniVoiceCUDAGraphForward:
"""Pre-captures CUDA graphs for predefined sequence-length buckets.
Memory layout: all graphs share a single per-instance pool handle, which
isolates OmniVoice CUDA memory from other vllm modules. Sequential replay
(one step at a time) means pool sharing is safe.
"""
# Default bucket count is 10; 16 gives modest headroom for edge cases
# (seq_len > max bucket or non-CFG batch) without unbounded GPU growth.
_MAX_LAZY_GRAPHS: int = 16
def __init__(self, generator: OmniVoiceGenerator, capture_sizes: list[int]) -> None:
self._gen = generator
self._capture_sizes = sorted(capture_sizes)
# Pre-warmed graphs keyed by (two_b, bucket); fixed set, never evicted.
self._graphs: dict[tuple[int, int], dict] = {}
# Lazy-captured graphs for oversized / non-CFG shapes; capped via LRU.
self._lazy_graphs: OrderedDict[tuple[int, int], dict] = OrderedDict()
self._lock = threading.Lock()
# Per-instance pool handle: isolates OmniVoice CUDA memory from other
# vllm modules while still allowing safe re-use across sequential replays.
self._pool_handle: int | None = None
def _find_bucket(self, seq_len: int) -> int | None:
for bucket in self._capture_sizes:
if bucket >= seq_len:
return bucket
return None
def _pad_inputs(
self,
input_ids: torch.Tensor,
audio_mask: torch.Tensor,
attention_mask: torch.Tensor | None,
bucket: int,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]:
S = input_ids.shape[-1]
if S == bucket:
return input_ids, audio_mask, attention_mask
two_b = input_ids.shape[0]
num_cb = input_ids.shape[1]
ids_padded = torch.zeros(two_b, num_cb, bucket, dtype=input_ids.dtype, device=input_ids.device)
ids_padded[:, :, :S] = input_ids
mask_padded = torch.zeros(two_b, bucket, dtype=torch.bool, device=audio_mask.device)
mask_padded[:, :S] = audio_mask
if attention_mask is not None:
attn_padded = torch.zeros(
two_b,
1,
bucket,
bucket,
dtype=attention_mask.dtype,
device=attention_mask.device,
)
attn_padded[:, :, :S, :S] = attention_mask
else:
attn_padded = None
return ids_padded, mask_padded, attn_padded
def _capture_for_key(
self,
key: tuple[int, int],
input_ids: torch.Tensor,
audio_mask: torch.Tensor,
attention_mask: torch.Tensor | None,
) -> dict:
_, bucket = key
device = input_ids.device
self._gen._ensure_rope(bucket, device)
model_dtype = self._gen.text_embedding.weight.dtype
static_cos = self._gen._rope_cos[:bucket].to(device=device, dtype=model_dtype).contiguous()
static_sin = self._gen._rope_sin[:bucket].to(device=device, dtype=model_dtype).contiguous()
static_input_ids = input_ids.clone()
static_audio_mask = audio_mask.clone()
static_attn_mask = attention_mask.clone() if attention_mask is not None else None
with torch.no_grad():
_ = self._gen._step_forward(
static_input_ids,
static_audio_mask,
static_attn_mask,
static_cos,
static_sin,
)
torch.accelerator.synchronize(device)
# Lazy-init per-instance pool handle: isolates OmniVoice CUDA Graph
# memory from other vllm modules (unlike get_global_graph_pool which
# shares a single pool across all captured graphs and can cause memory
# aliasing when two graphs replay concurrently).
if self._pool_handle is None:
self._pool_handle = torch.cuda.graph_pool_handle()
graph = torch.cuda.CUDAGraph()
with torch.no_grad():
with torch.cuda.graph(graph, pool=self._pool_handle):
static_output = self._gen._step_forward(
static_input_ids,
static_audio_mask,
static_attn_mask,
static_cos,
static_sin,
)
entry = {
"graph": graph,
"static_input_ids": static_input_ids,
"static_audio_mask": static_audio_mask,
"static_attn_mask": static_attn_mask,
"static_cos": static_cos,
"static_sin": static_sin,
"static_output": static_output,
}
logger.info("OmniVoice CUDA Graph captured for key %s", key)
return entry
def warmup(self, device: torch.device) -> None:
"""Pre-capture graphs for all bucket sizes with B=1 (two_b=2 for CFG)."""
if not torch.cuda.is_available():
return
logger.info(
"OmniVoice CUDA Graph warmup: capturing %d bucket sizes %s",
len(self._capture_sizes),
self._capture_sizes,
)
two_b = 2
num_cb = self._gen.config.num_audio_codebook
for bucket in self._capture_sizes:
key = (two_b, bucket)
dummy_ids = torch.zeros(two_b, num_cb, bucket, dtype=torch.long, device=device)
dummy_mask = torch.zeros(two_b, bucket, dtype=torch.bool, device=device)
dummy_attn = torch.ones(two_b, 1, bucket, bucket, dtype=torch.bool, device=device)
self._graphs[key] = self._capture_for_key(key, dummy_ids, dummy_mask, dummy_attn)
logger.info("OmniVoice CUDA Graph warmup complete (%d graphs)", len(self._graphs))
def __call__(
self,
input_ids: torch.Tensor,
audio_mask: torch.Tensor,
attention_mask: torch.Tensor | None,
) -> torch.Tensor:
if torch.cuda.is_current_stream_capturing():
seq_len = input_ids.shape[-1]
self._gen._ensure_rope(seq_len, input_ids.device)
dtype = self._gen.text_embedding.weight.dtype
cos = self._gen._rope_cos[:seq_len].to(device=input_ids.device, dtype=dtype)
sin = self._gen._rope_sin[:seq_len].to(device=input_ids.device, dtype=dtype)
return self._gen._step_forward(input_ids, audio_mask, attention_mask, cos, sin)
seq_len = input_ids.shape[-1]
two_b = input_ids.shape[0]
bucket = self._find_bucket(seq_len) if two_b == 2 else None
if bucket is None:
# Lazy capture: oversized sequence or non-unit batch (no pre-warmed bucket).
# Lock prevents concurrent threads from double-capturing the same key.
# _lazy_graphs is capped at _MAX_LAZY_GRAPHS with LRU eviction to
# prevent unbounded GPU memory growth when seq_len varies widely.
key = (two_b, seq_len)
ids_in, mask_in, attn_in = input_ids, audio_mask, attention_mask
with self._lock:
entry = self._lazy_graphs.get(key)
if entry is None:
entry = self._capture_for_key(key, ids_in, mask_in, attn_in)
if len(self._lazy_graphs) >= self._MAX_LAZY_GRAPHS:
evicted_key, _ = self._lazy_graphs.popitem(last=False)
logger.warning("OmniVoice CUDA Graph lazy cache full; evicted key %s", evicted_key)
self._lazy_graphs[key] = entry
else:
key = (two_b, bucket)
ids_in, mask_in, attn_in = self._pad_inputs(input_ids, audio_mask, attention_mask, bucket)
with self._lock:
entry = self._graphs.get(key)
if entry is None:
entry = self._capture_for_key(key, ids_in, mask_in, attn_in)
self._graphs[key] = entry
entry["static_input_ids"].copy_(ids_in)
entry["static_audio_mask"].copy_(mask_in)
if attn_in is not None and entry["static_attn_mask"] is not None:
entry["static_attn_mask"].copy_(attn_in)
entry["graph"].replay()
output = entry["static_output"]
if bucket is not None and bucket != seq_len:
output = output[:, :, :seq_len, :]
return output
def clear(self) -> None:
with self._lock:
self._graphs.clear()
self._lazy_graphs.clear()
# ---------------------------------------------------------------------------
# Generator model
# ---------------------------------------------------------------------------
@@ -278,6 +684,11 @@ class OmniVoiceGenerator(nn.Module):
self._rope_cos = None
self._rope_sin = None
# CUDA Graph (bucket-size pre-capture; lazy fallback for oversized shapes)
self._cuda_graph_fwd: _OmniVoiceCUDAGraphForward | None = (
_OmniVoiceCUDAGraphForward(self, config.cuda_graph_capture_sizes) if config.enable_cuda_graph else None
)
def _ensure_rope(self, seq_len: int, device: torch.device) -> None:
"""Lazily compute RoPE cos/sin if needed."""
if self._rope_cos is None or self._rope_cos.shape[0] < seq_len:
@@ -364,6 +775,20 @@ class OmniVoiceGenerator(nn.Module):
self.config.audio_vocab_size,
).permute(0, 2, 1, 3) # [B, 8, S, 1025]
def _step_forward(
self,
input_ids: torch.Tensor,
audio_mask: torch.Tensor,
attention_mask: torch.Tensor | None,
cos: torch.Tensor,
sin: torch.Tensor,
) -> torch.Tensor:
"""Single unmasking-step forward using pre-cast RoPE tensors (CUDA graph safe)."""
hidden_states = self._prepare_embeddings(input_ids, audio_mask)
for layer in self.layers:
hidden_states = layer(hidden_states, attention_mask=attention_mask, cos=cos, sin=sin)
return self._get_logits(self.norm(hidden_states))
@torch.inference_mode()
def forward(
self,
@@ -371,6 +796,7 @@ class OmniVoiceGenerator(nn.Module):
audio_mask: torch.Tensor,
attention_mask: torch.Tensor,
target_lens: list[int],
seed: int | None = None,
num_step: int = 32,
guidance_scale: float = 2.0,
t_shift: float = 0.1,
@@ -400,6 +826,9 @@ class OmniVoiceGenerator(nn.Module):
max_target_len = max(target_lens)
mask_id = self.config.audio_mask_id
num_codebooks = self.config.num_audio_codebook
if seed is None:
seed = random.randint(0, 2**63 - 1)
generator = torch.Generator(device=device).manual_seed(seed)
# Initialize all target tokens as [MASK]
tokens = torch.full(
@@ -440,10 +869,12 @@ class OmniVoiceGenerator(nn.Module):
# Main iterative loop
for step in range(num_step):
# Prepare embeddings and run transformer
inputs_embeds = self._prepare_embeddings(input_ids, audio_mask)
hidden_states = self._transformer_forward(inputs_embeds, attention_mask)
batch_logits = self._get_logits(hidden_states).to(torch.float32)
if self._cuda_graph_fwd is not None and input_ids.is_cuda:
batch_logits = self._cuda_graph_fwd(input_ids, audio_mask, attention_mask).to(torch.float32)
else:
inputs_embeds = self._prepare_embeddings(input_ids, audio_mask)
hidden_states = self._transformer_forward(inputs_embeds, attention_mask)
batch_logits = self._get_logits(hidden_states).to(torch.float32)
# batch_logits: [2*B, 8, S, 1025]
for i in range(B):
@@ -474,7 +905,7 @@ class OmniVoiceGenerator(nn.Module):
# Token prediction
if class_temperature > 0.0:
pred_tokens = _gumbel_sample(log_probs, class_temperature).argmax(dim=-1)
pred_tokens = _gumbel_sample(log_probs, class_temperature, generator).argmax(dim=-1)
else:
pred_tokens = log_probs.argmax(dim=-1) # [1, 8, T]
@@ -486,7 +917,7 @@ class OmniVoiceGenerator(nn.Module):
# Gumbel noise for position selection
if position_temperature > 0.0:
scores = _gumbel_sample(scores, position_temperature)
scores = _gumbel_sample(scores, position_temperature, generator)
# Mask out already unmasked positions
sample_tokens = tokens[i : i + 1, :, :t_len]
@@ -586,3 +1017,6 @@ class OmniVoiceGenerator(nn.Module):
)
else:
logger.info("Generator: all %d weights loaded", len(loaded_keys))
if self._cuda_graph_fwd is not None:
self._cuda_graph_fwd.warmup(device)
@@ -30,6 +30,7 @@ QWEN2_5_OMNI_PIPELINE = PipelineConfig(
requires_multimodal_data=True,
engine_output_type="latent",
sampling_constraints={"detokenize": True},
custom_process_next_stage_input_func=f"{_PROC}.thinker2talker_full_payload",
),
StagePipelineConfig(
stage_id=1,
@@ -38,6 +39,8 @@ QWEN2_5_OMNI_PIPELINE = PipelineConfig(
input_sources=(0,),
engine_output_type="latent",
custom_process_input_func=f"{_PROC}.thinker2talker",
sync_process_input_func=f"{_PROC}.thinker2talker_token_only",
custom_process_next_stage_input_func=f"{_PROC}.talker2code2wav_full_payload",
sampling_constraints={
"detokenize": True,
"stop_token_ids": [8294],
@@ -52,6 +55,7 @@ QWEN2_5_OMNI_PIPELINE = PipelineConfig(
final_output_type="audio",
engine_output_type="audio",
custom_process_input_func=f"{_PROC}.talker2code2wav",
sync_process_input_func=f"{_PROC}.talker2code2wav_token_only",
sampling_constraints={"detokenize": True},
),
),
@@ -74,6 +78,7 @@ QWEN2_5_OMNI_THINKER_ONLY_PIPELINE = PipelineConfig(
requires_multimodal_data=True,
engine_output_type="latent",
sampling_constraints={"detokenize": True},
custom_process_next_stage_input_func=f"{_PROC}.thinker2talker_full_payload",
),
),
)
@@ -2,14 +2,12 @@
# Start Token2Wav #
############################
import math
from collections.abc import Iterable
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Parameter
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS
from transformers.models.qwen2_5_omni.configuration_qwen2_5_omni import (
Qwen2_5OmniBigVGANConfig,
@@ -35,8 +33,9 @@ from vllm.v1.sample.metadata import SamplingMetadata
from vllm.v1.sample.sampler import Sampler
from vllm_omni.model_executor.layers.timestep_embedding import DiTTimestepEmbedding
from vllm_omni.model_executor.models.common.alias_free_activation import AliasFreeActivation1d
from vllm_omni.model_executor.models.common.snake_activation import SnakeBeta
from vllm_omni.model_executor.models.qwen2_5_omni.audio_length import cap_and_align_mel_length, resolve_max_mel_frames
from vllm_omni.platforms import current_omni_platform
# Provide a no-op auto_docstring decorator to satisfy annotations if missing
@@ -634,238 +633,9 @@ class DiTDecoderLayer(nn.Module):
return hidden_states
class SnakeBeta(nn.Module):
"""
A modified Snake function which uses separate parameters for the magnitude
of the periodic components
Shape:
- Input: (B, C, T)
- Output: (B, C, T), same shape as the input
Parameters:
- alpha - trainable parameter that controls frequency
- beta - trainable parameter that controls magnitude
References:
- This activation function is a modified version based on this paper
by Liu Ziyin, Tilman Hartwig, Masahito Ueda:
https://huggingface.co/papers/2006.08195
"""
def __init__(self, in_features, alpha=1.0):
super().__init__()
self.in_features = in_features
# initialize alpha
self.alpha = Parameter(torch.zeros(in_features) * alpha)
self.beta = Parameter(torch.zeros(in_features) * alpha)
self.no_div_by_zero = 0.000000001
def forward(self, hidden_states):
"""
Forward pass of the function.
Applies the function to the input elementwise.
SnakeBeta ∶= x + 1/b * sin^2 (xa)
"""
alpha = self.alpha.unsqueeze(0).unsqueeze(-1) # line up with x to [B, C, T]
beta = self.beta.unsqueeze(0).unsqueeze(-1)
alpha = torch.exp(alpha)
beta = torch.exp(beta)
hidden_states = hidden_states + (1.0 / (beta + self.no_div_by_zero)) * torch.pow(
torch.sin(hidden_states * alpha), 2
)
return hidden_states
def kaiser_sinc_filter1d(cutoff: float, half_width: float, kernel_size: int) -> torch.Tensor:
"""Generates a 1D Kaiser-windowed sinc filter.
Args:
cutoff (float): Normalized cutoff frequency (0 to 0.5).
half_width (float): Transition bandwidth.
kernel_size (int): Number of filter taps.
Returns:
torch.Tensor: A tensor of shape (1, 1, kernel_size) representing the filter.
"""
is_even = kernel_size % 2 == 0
half_size = kernel_size // 2
# Compute Kaiser window parameters
delta_f = 4 * half_width
attenuation = 2.285 * (half_size - 1) * math.pi * delta_f + 7.95
if attenuation > 50.0:
beta = 0.1102 * (attenuation - 8.7)
elif attenuation >= 21.0:
beta = 0.5842 * (attenuation - 21) ** 0.4 + 0.07886 * (attenuation - 21.0)
else:
beta = 0.0
# TODO: When torch.kaiser_window supports NPU, remove the device="cpu" argument
if current_omni_platform.is_npu():
kaiser_window = torch.kaiser_window(
kernel_size, beta=beta, periodic=False, dtype=torch.float32, device="cpu"
).to("npu")
elif current_omni_platform.is_xpu():
kaiser_window = torch.kaiser_window(
kernel_size, beta=beta, periodic=False, dtype=torch.float32, device="cpu"
).to("xpu")
else:
kaiser_window = torch.kaiser_window(kernel_size, beta=beta, periodic=False, dtype=torch.float32)
# Compute time indices
if is_even:
time_indices = torch.arange(-half_size, half_size) + 0.5
else:
time_indices = torch.arange(kernel_size) - half_size
# Compute sinc filter
if cutoff == 0:
return torch.zeros((1, 1, kernel_size), dtype=torch.float32)
sinc_filter = torch.sinc(2 * cutoff * time_indices)
normalized_filter = 2 * cutoff * kaiser_window * sinc_filter
# Normalize to ensure sum = 1 (avoid leakage of constant component)
normalized_filter /= normalized_filter.sum()
return normalized_filter.view(1, 1, kernel_size)
def replication_pad_1d(hidden_states: torch.Tensor, pad_left: int, pad_right: int) -> torch.Tensor:
"""
Manual replicate padding to avoid replication_pad1d kernel limits on NPU.
TODO: remove when F.pad supports replicate mode on NPU.
"""
# NOTE: a immature implementation for running in NPU. Need to discuss.
if pad_left == 0 and pad_right == 0:
return hidden_states
segments = []
if pad_left > 0:
left = hidden_states[..., :1].expand(*hidden_states.shape[:-1], pad_left)
segments.append(left)
segments.append(hidden_states)
if pad_right > 0:
right = hidden_states[..., -1:].expand(*hidden_states.shape[:-1], pad_right)
segments.append(right)
return torch.cat(segments, dim=-1)
class UpSample1d(nn.Module):
def __init__(self, ratio=2, kernel_size=None):
super().__init__()
self.ratio = ratio
self.kernel_size = int(6 * ratio // 2) * 2 if kernel_size is None else kernel_size
self.stride = ratio
self.pad = self.kernel_size // ratio - 1
self.pad_left = self.pad * self.stride + (self.kernel_size - self.stride) // 2
self.pad_right = self.pad * self.stride + (self.kernel_size - self.stride + 1) // 2
filter = kaiser_sinc_filter1d(cutoff=0.5 / ratio, half_width=0.6 / ratio, kernel_size=self.kernel_size)
self.register_buffer("filter", filter, persistent=False)
def forward(self, hidden_states):
channels = hidden_states.shape[1]
if current_omni_platform.is_npu():
# TODO: When F.pad supports replicate mode on NPU, remove this branch
input_dtype = hidden_states.dtype
# F.pad in NPU doesn't support BF16 when mode is replicate.
# To ensure the accuracy, manually pad the input tensor.
hidden_states = replication_pad_1d(hidden_states.to(self.filter.dtype), self.pad, self.pad)
filter_convert_dtype = self.filter.to(hidden_states.dtype)
hidden_states = self.ratio * F.conv_transpose1d(
hidden_states,
filter_convert_dtype.expand(channels, -1, -1),
stride=self.stride,
groups=channels,
).to(input_dtype)
else:
hidden_states_dtype = hidden_states.dtype
hidden_states = F.pad(hidden_states, (self.pad, self.pad), mode="replicate").to(self.filter.dtype)
hidden_states = self.ratio * F.conv_transpose1d(
hidden_states,
self.filter.expand(channels, -1, -1),
stride=self.stride,
groups=channels,
).to(hidden_states_dtype)
hidden_states = hidden_states[..., self.pad_left : -self.pad_right]
return hidden_states
class DownSample1d(nn.Module):
def __init__(self, ratio=2, kernel_size=None):
super().__init__()
cutoff = 0.5 / ratio
half_width = 0.6 / ratio
if cutoff < 0.0:
raise ValueError("Minimum cutoff must be larger than zero.")
if cutoff > 0.5:
raise ValueError("A cutoff above 0.5 does not make sense.")
self.even = kernel_size % 2 == 0
self.pad_left = kernel_size // 2 - int(self.even)
self.pad_right = kernel_size // 2
self.stride = ratio
filter = kaiser_sinc_filter1d(cutoff, half_width, kernel_size)
self.register_buffer("filter", filter, persistent=False)
def forward(self, hidden_states):
channels = hidden_states.shape[1]
if current_omni_platform.is_npu():
input_dtype = hidden_states.dtype
# F.pad in NPU doesn't support BF16 when mode is replicate.
# To ensure the accuracy, manually pad the input tensor.
hidden_states = replication_pad_1d(hidden_states.to(self.filter.dtype), self.pad_left, self.pad_right)
filter_on_device = self.filter.to(device=hidden_states.device, dtype=hidden_states.dtype)
out = F.conv1d(
hidden_states,
filter_on_device.expand(channels, -1, -1),
stride=self.stride,
groups=channels,
).to(input_dtype)
else:
hidden_states_dtype = hidden_states.dtype
hidden_states = F.pad(hidden_states, (self.pad_left, self.pad_right), mode="replicate").to(
self.filter.dtype
)
out = F.conv1d(
hidden_states,
self.filter.expand(channels, -1, -1),
stride=self.stride,
groups=channels,
).to(hidden_states_dtype)
return out
class TorchActivation1d(nn.Module):
def __init__(
self,
activation,
up_ratio: int = 2,
down_ratio: int = 2,
up_kernel_size: int = 12,
down_kernel_size: int = 12,
):
super().__init__()
if not callable(activation):
raise TypeError("Activation function must be callable")
self.act = activation
self.upsample = UpSample1d(up_ratio, up_kernel_size)
self.downsample = DownSample1d(down_ratio, down_kernel_size)
def forward(self, hidden_states):
hidden_states = self.upsample(hidden_states)
hidden_states = self.act(hidden_states)
hidden_states = self.downsample(hidden_states)
return hidden_states
# SnakeBeta, UpSample1d, DownSample1d, AliasFreeActivation1d (formerly
# TorchActivation1d) are now provided by the shared ``common`` modules.
# See: vllm_omni/model_executor/models/common/{snake_activation,alias_free_activation}.py
class AMPBlock(torch.nn.Module):
@@ -938,7 +708,7 @@ class AMPBlock(torch.nn.Module):
self.num_layers = len(self.convs1) + len(self.convs2) # total number of conv layers
self.activations = nn.ModuleList(
[TorchActivation1d(activation=SnakeBeta(channels)) for _ in range(self.num_layers)]
[AliasFreeActivation1d(activation=SnakeBeta(channels)) for _ in range(self.num_layers)]
)
def _get_padding(self, kernel_size, dilation=1):
@@ -1002,7 +772,7 @@ class Qwen2_5OmniToken2WavBigVGANModel(Qwen2_5OmniPreTrainedModel):
]
)
self.activation_post = TorchActivation1d(
self.activation_post = AliasFreeActivation1d(
activation=SnakeBeta(config.upsample_initial_channel // (2**self.num_upsample_layers))
)
self.conv_post = nn.Conv1d(
@@ -20,7 +20,6 @@ from transformers.models.qwen3_omni_moe.configuration_qwen3_omni_moe import (
from vllm.config import ModelConfig, VllmConfig
from vllm.inputs import PromptType, TokensPrompt
from vllm.logger import init_logger
from vllm.model_executor.layers.rotary_embedding import MRotaryEmbedding
from vllm.model_executor.models.interfaces import SupportsMRoPE, SupportsMultiModal, SupportsPP, SupportsRealtime
from vllm.model_executor.models.qwen3_asr_realtime import Qwen3ASRRealtimeBuffer
from vllm.model_executor.models.qwen3_omni_moe_thinker import (
@@ -180,11 +179,9 @@ class Qwen3OmniMoeForConditionalGeneration(
("hidden_states", "last"),
("hidden_states", "trailing_text"),
("embed", "tts_pad_projected"),
}
# Keys that need to be accumulated across streaming inputs
self.streaming_accumulated_keys: set[tuple[str, str]] = {
("embed", "prefill"),
("hidden_states", "output"),
# talker MTP codec codes must stay on GPU to avoid a per-step D2H
# sync stall; build_mm_cpu handles the eventual D2H at payload time.
("codes", "audio"),
}
elif self.model_stage == "code2wav":
@@ -323,7 +320,12 @@ class Qwen3OmniMoeForConditionalGeneration(
msg = "Qwen3 Omni thinker get_mrope_input_positions requires mm_features"
raise ValueError(msg)
return self.thinker.get_mrope_input_positions(input_tokens, mm_features)
return MRotaryEmbedding.get_input_positions_tensor(input_tokens, **kwargs)
# Talker/code2wav stages are text/codec-only and do not need
# multimodal M-RoPE position computation. Return a cheap linear
# position tensor to avoid unnecessary per-request M-RoPE work.
seq_len = len(input_tokens)
linear = torch.arange(seq_len, dtype=torch.long).unsqueeze(0).expand(3, seq_len)
return linear, 0
def forward(
self,
@@ -420,13 +422,16 @@ class Qwen3OmniMoeForConditionalGeneration(
else:
codes = input_ids.reshape(1, 16, -1)
else:
logger.warning(
(
"Input_ids length: %s is not divisible by 16, padding "
"with zeros. This should only happen in warm up."
),
input_ids.shape[0],
)
if seq_token_counts is None:
logger.debug(
"Code2Wav warmup input length %s is not divisible by 16; padding with zeros.",
input_ids.shape[0],
)
else:
logger.warning_once(
"Code2Wav input length is not divisible by 16; padding with zeros. "
"This is expected only during cudagraph warmup."
)
input_ids_flatten = input_ids.reshape(-1)
input_ids_flatten = torch.cat(
[
@@ -670,8 +675,14 @@ class Qwen3OmniMoeForConditionalGeneration(
span_len = input_ids.shape[0]
update_dict: OmniPayload = {}
if span_len > 1:
# prefill
# Prefix caching can reduce a new request's remaining prefill span to a
# single token. Use the runner-provided phase flag instead of span_len.
is_prefill = bool(payload.get("_omni_is_prefill", span_len > 1))
if is_prefill:
num_computed_tokens = payload.get("_omni_num_computed_tokens")
request_resumable = meta.get("resumable", False)
if num_computed_tokens is not None and not request_resumable:
meta["num_processed_tokens"] = int(num_computed_tokens)
input_ids, input_embeds, update_dict = self.talker_preprocess_prefill(input_ids, input_embeds, payload)
code_predictor_codes = torch.zeros(
(input_embeds.shape[0], self.talker.num_code_groups),
@@ -1245,7 +1256,7 @@ class Qwen3OmniMoeForConditionalGeneration(
if (
getattr(self, "model_stage", None) == "talker"
and sampling_metadata is not None
and (sampling_metadata.temperature is None or (sampling_metadata.temperature <= 0).any())
and (sampling_metadata.temperature is None)
):
self._warn_talker_sampling_temperature(sampling_metadata)
@@ -1283,6 +1294,22 @@ class Qwen3OmniMoeForConditionalGeneration(
left_frames = int(extra.get("codec_left_context_frames", 0) or 0)
return chunk_frames, left_frames
def _maybe_enable_code2wav_cudagraph(self) -> None:
"""Enable the inner Code2Wav CUDA graph unless this stage runs in eager mode."""
if not self.code2wav or not hasattr(self.code2wav, "enable_cudagraph"):
return
model_cfg = getattr(self.vllm_config, "model_config", None)
if getattr(model_cfg, "enforce_eager", False):
logger.info("Code2Wav CUDA Graph disabled because enforce_eager is set")
return
chunk_frames, left_frames = self._get_codec_frame_config()
self.code2wav.enable_cudagraph(
codec_chunk_frames=chunk_frames,
codec_left_context_frames=left_frames,
)
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
"""Load weights for all components of the omni model."""
loaded_weights = set()
@@ -1319,15 +1346,11 @@ class Qwen3OmniMoeForConditionalGeneration(
code2wav_loaded = add_prefix_to_loaded_weights(code2wav_loaded, "code2wav")
loaded_weights.update(code2wav_loaded)
# Precompute SnakeBeta caches and enable CUDA graph for Code2Wav decoder
# Precompute SnakeBeta caches; Code2Wav CUDA graph follows the stage's
# enforce_eager setting, the same switch vLLM uses for outer graphs.
try:
self.code2wav.precompute_snake_caches()
if hasattr(self.code2wav, "enable_cudagraph"):
chunk_frames, left_frames = self._get_codec_frame_config()
self.code2wav.enable_cudagraph(
codec_chunk_frames=chunk_frames,
codec_left_context_frames=left_frames,
)
self._maybe_enable_code2wav_cudagraph()
except Exception:
logger.warning(
"Failed to enable CUDA Graph for Code2Wav; falling back to eager.",
@@ -297,9 +297,9 @@ class Qwen3OmniMoeCode2Wav(nn.Module):
single tensor with shape ``[1, waveform_len]``.
"""
if not (left_context_size and seq_token_counts and len(left_context_size) == len(seq_token_counts)):
logger.warning(
logger.warning_once(
"chunked_decode_streaming: missing/invalid left_context_size or seq_token_counts; "
"defaulting to left_context_size=zeros(len=codes.shape[0])."
"defaulting to left_context_size=zeros(len(codes)). This is expected during cudagraph warmup."
)
left_context_size = [0] * codes.shape[0]
# Decode chunk
@@ -1205,11 +1205,8 @@ class Qwen3OmniMoeThinkerForConditionalGeneration(
) -> IntermediateTensors | None:
if not getattr(self, "deepstack_input_embeds", None):
return None # If vision tower is skipped
if getattr(self, "deepstack_input_embeds_num_tokens", 0) == 0:
return None
buf = self.deepstack_input_embeds[0].size(0)
if num_tokens > buf:
raise ValueError(f"Requested more deepstack tokens than buffer capacity: {num_tokens=} > {buf=}")
if num_tokens > self.deepstack_input_embeds[0].size(0):
self._resize_deepstack_input_embeds(num_tokens)
n_valid = self.deepstack_input_embeds_num_tokens
# embed_input_ids runs on unpadded length; forward uses padded num_tokens
# (vLLM gpu_model_runner). Tail positions have no vision deepstack and must
@@ -1226,6 +1223,17 @@ class Qwen3OmniMoeThinkerForConditionalGeneration(
}
)
def _resize_deepstack_input_embeds(self, num_tokens: int) -> None:
self.deepstack_input_embeds = [
torch.zeros(
num_tokens,
self.config.text_config.hidden_size,
device=self.deepstack_input_embeds[0].device,
dtype=self.deepstack_input_embeds[0].dtype,
)
for _ in range(self.deepstack_num_level)
]
def _set_deepstack_input_embeds(self, deepstack_input_embeds: torch.Tensor) -> None:
if not getattr(self, "deepstack_input_embeds", None):
return
@@ -1233,15 +1241,7 @@ class Qwen3OmniMoeThinkerForConditionalGeneration(
# set deepstack_input_embeds to buffer
num_tokens = deepstack_input_embeds.size(1)
if num_tokens > self.deepstack_input_embeds[0].size(0):
self.deepstack_input_embeds = [
torch.zeros(
num_tokens,
self.config.text_config.hidden_size,
device=self.deepstack_input_embeds[0].device,
dtype=self.deepstack_input_embeds[0].dtype,
)
for _ in range(self.deepstack_num_level)
]
self._resize_deepstack_input_embeds(num_tokens)
for idx in range(self.deepstack_num_level):
self.deepstack_input_embeds[idx][:num_tokens].copy_(deepstack_input_embeds[idx])
self.deepstack_input_embeds_num_tokens = num_tokens
@@ -26,6 +26,7 @@ QWEN3_TTS_PIPELINE = PipelineConfig(
owns_tokenizer=True,
engine_output_type="latent",
async_chunk_process_next_stage_input_func=(f"{_PROC}.talker2code2wav_async_chunk"),
custom_process_next_stage_input_func=f"{_PROC}.talker2code2wav_full_payload",
sampling_constraints={
"detokenize": False,
"stop_token_ids": [2150],
@@ -40,7 +41,14 @@ QWEN3_TTS_PIPELINE = PipelineConfig(
final_output_type="audio",
engine_output_type="audio",
model_arch="Qwen3TTSCode2Wav",
sync_process_input_func=f"{_PROC}.talker2code2wav",
# ``sync_process_input_func`` is the only input-proc override for
# this stage in sync (non-async-chunk) mode: a length-only
# ``_token_only`` placeholder. The bulk codec payload itself
# ships via the worker connector from stage 0's
# ``talker2code2wav_full_payload`` producer. Under async_chunk
# mode no pre-stage processing is needed -- chunks deliver
# directly to the consumer.
sync_process_input_func=f"{_PROC}.talker2code2wav_token_only",
sampling_constraints={"detokenize": True},
extras={"tts_args": {"max_instructions_length": 500}},
),
File diff suppressed because it is too large. Load diff
@@ -25,6 +25,27 @@ from .tokenizer_12hz.modeling_qwen3_tts_tokenizer_v2 import (
logger = init_logger(__name__)
def _codec_ids_from_payload_or_input(
input_ids: torch.Tensor,
runtime_info: dict[str, Any] | None,
) -> torch.Tensor:
"""Prefer connector-delivered codec ids over token placeholders.
In non-async full-payload mode, the scheduler only needs placeholder
token ids for allocation. The real codec sequence is delivered through
model_intermediate_buffer as ``codes.audio``.
"""
if isinstance(runtime_info, dict):
codes = runtime_info.get("codes")
if isinstance(codes, dict):
audio = codes.get("audio")
if isinstance(audio, torch.Tensor) and audio.numel() > 0:
return audio.reshape(-1).to(device=input_ids.device, dtype=torch.long)
if isinstance(audio, (list, tuple)) and audio:
return torch.as_tensor(audio, device=input_ids.device, dtype=torch.long).reshape(-1)
return input_ids.reshape(-1).to(dtype=torch.long)
class Qwen3TTSCode2Wav(nn.Module):
"""Stage-1 code2wav model for Qwen3-TTS (GenerationModelRunner).
Consumes frame-aligned codec tokens from input_ids and decodes waveform
@@ -111,6 +132,56 @@ class Qwen3TTSCode2Wav(nn.Module):
return [ids[boundaries[i] : boundaries[i + 1]] for i in range(len(boundaries) - 1)]
return [ids]
def _maybe_enable_decoder_cudagraph(
self,
*,
device: torch.device,
codec_chunk_frames: int,
codec_left_context_frames: int,
decode_cudagraph_capture_sizes: list[int] | None,
decode_cudagraph_batch_sizes: list[int] | None,
decode_cudagraph_extra_capture_shapes: list[tuple[int, int]] | None,
decode_compile_shapes: list[tuple[int, int]] | None,
) -> None:
"""Enable inner Code2Wav CUDA graph unless stage is enforce_eager."""
if not hasattr(self.decoder, "enable_cudagraph") or device.type != "cuda":
return
model_cfg = getattr(self.vllm_config, "model_config", None)
if getattr(model_cfg, "enforce_eager", False):
logger.info("Qwen3-TTS Code2Wav CUDA Graph disabled because enforce_eager is set")
return
if (
codec_chunk_frames > 0
and codec_left_context_frames > 0
and self._decoder_sliding_window
and codec_left_context_frames < self._decoder_sliding_window
):
logger.warning(
"Qwen3-TTS streaming codec_left_context_frames=%d "
"is smaller than decoder sliding_window=%d; "
"chunk-boundary distortion may occur. "
"Increase codec_left_context_frames to at least "
"%d for streaming.",
codec_left_context_frames,
self._decoder_sliding_window,
self._decoder_sliding_window,
)
self.decoder.enable_cudagraph(
capture_sizes=decode_cudagraph_capture_sizes,
capture_batch_sizes=decode_cudagraph_batch_sizes,
extra_capture_shapes=decode_cudagraph_extra_capture_shapes,
compile_shapes=decode_compile_shapes,
device=device,
codec_chunk_frames=codec_chunk_frames,
codec_left_context_frames=codec_left_context_frames,
decode_chunk_size=self._decode_chunk_frames,
decode_left_context=self._decode_left_context_frames,
)
logger.info("Code2Wav decoder CUDA Graph enabled")
def _get_decode_batch_bucket_frames(self, actual_frames: int) -> int:
for bucket_frames in self._decode_batch_bucket_frames:
if actual_frames <= bucket_frames:
@@ -189,6 +260,7 @@ class Qwen3TTSCode2Wav(nn.Module):
multimodal_outputs={"model_outputs": [empty], "sr": [sr_tensor]},
)
runtime_infos = runtime_additional_information or []
ids = input_ids.reshape(-1).to(dtype=torch.long)
request_ids_list = self._split_request_ids(ids, kwargs.get("seq_token_counts"))
@@ -196,14 +268,18 @@ class Qwen3TTSCode2Wav(nn.Module):
valid_codes_qf: list[torch.Tensor] = []
valid_indices: list[int] = []
left_context_size = [0] * len(request_ids_list)
if runtime_additional_information is not None:
for i, info in enumerate(runtime_additional_information):
if runtime_infos:
for i, info in enumerate(runtime_infos):
if i >= len(left_context_size):
break
if not isinstance(info, dict):
continue
meta = info.get("meta", {})
if "left_context_size" in meta:
left_context_size[i] = meta["left_context_size"]
for i, req_ids in enumerate(request_ids_list):
runtime_info = runtime_infos[i] if i < len(runtime_infos) else None
req_ids = _codec_ids_from_payload_or_input(req_ids, runtime_info)
if req_ids.numel() < 1:
parsed.append((0, 0))
continue
@@ -581,35 +657,15 @@ class Qwen3TTSCode2Wav(nn.Module):
if hasattr(self.decoder, "enable_cudagraph") and device.type == "cuda":
try:
if (
codec_chunk_frames > 0
and codec_left_context_frames > 0
and self._decoder_sliding_window
and codec_left_context_frames < self._decoder_sliding_window
):
logger.warning(
"Qwen3-TTS streaming codec_left_context_frames=%d "
"is smaller than decoder sliding_window=%d; "
"chunk-boundary distortion may occur. "
"Increase codec_left_context_frames to at least "
"%d for streaming.",
codec_left_context_frames,
self._decoder_sliding_window,
self._decoder_sliding_window,
)
self.decoder.enable_cudagraph(
capture_sizes=decode_cudagraph_capture_sizes,
capture_batch_sizes=decode_cudagraph_batch_sizes,
extra_capture_shapes=decode_cudagraph_extra_capture_shapes,
compile_shapes=decode_compile_shapes,
self._maybe_enable_decoder_cudagraph(
device=device,
codec_chunk_frames=codec_chunk_frames,
codec_left_context_frames=codec_left_context_frames,
decode_chunk_size=self._decode_chunk_frames,
decode_left_context=self._decode_left_context_frames,
decode_cudagraph_capture_sizes=decode_cudagraph_capture_sizes,
decode_cudagraph_batch_sizes=decode_cudagraph_batch_sizes,
decode_cudagraph_extra_capture_shapes=decode_cudagraph_extra_capture_shapes,
decode_compile_shapes=decode_compile_shapes,
)
logger.info("Code2Wav decoder CUDA Graph enabled")
except Exception:
logger.warning(
"Failed to enable CUDA Graph for Code2Wav decoder",
File diff suppressed because it is too large. Load diff
@@ -13,6 +13,7 @@
# limitations under the License.
"""PyTorch Qwen3TTSTokenizerV2 model."""
import inspect
import math
from collections.abc import Callable
from dataclasses import dataclass
@@ -565,12 +566,17 @@ class Qwen3TTSTokenizerV2DecoderTransformerModel(Qwen3TTSTokenizerV2DecoderPreTr
# Prepare mask arguments
mask_kwargs = {
"config": self.config,
"input_embeds": inputs_embeds,
"attention_mask": attention_mask,
"cache_position": cache_position,
"past_key_values": past_key_values,
"position_ids": position_ids,
}
# Handle API changes across transformers versions
sig = inspect.signature(create_causal_mask)
if "input_embeds" in sig.parameters:
mask_kwargs["input_embeds"] = inputs_embeds
mask_kwargs["cache_position"] = cache_position
else:
mask_kwargs["inputs_embeds"] = inputs_embeds
# Create the masks
causal_mask_mapping = {
"full_attention": create_causal_mask(**mask_kwargs),
@@ -13,13 +13,11 @@
# limitations under the License.
"""PyTorch Qwen3TTSTokenizerV1 model."""
import math
from dataclasses import dataclass
import numpy as np
import torch
from torch import nn
from torch.nn import Parameter
from torch.nn import functional as F
from torch.nn.utils.rnn import pad_sequence
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
@@ -27,6 +25,8 @@ from transformers.utils import ModelOutput, auto_docstring, logging
from transformers.utils.hub import cached_file
from vllm_omni.model_executor.layers.timestep_embedding import DiTTimestepEmbedding
from vllm_omni.model_executor.models.common.alias_free_activation import AliasFreeActivation1d
from vllm_omni.model_executor.models.common.snake_activation import SnakeBeta
from .configuration_qwen3_tts_tokenizer_v1 import (
Qwen3TTSTokenizerV1Config,
@@ -663,166 +663,9 @@ class DiTDecoderLayer(nn.Module):
return hidden_states
class SnakeBeta(nn.Module):
"""
A modified Snake function which uses separate parameters for the magnitude of the periodic components
Shape:
- Input: (B, C, T)
- Output: (B, C, T), same shape as the input
Parameters:
- alpha - trainable parameter that controls frequency
- beta - trainable parameter that controls magnitude
References:
- This activation function is a modified version based on this paper
by Liu Ziyin, Tilman Hartwig, Masahito Ueda:
https://huggingface.co/papers/2006.08195
"""
def __init__(self, in_features, alpha=1.0):
super().__init__()
self.in_features = in_features
# initialize alpha
self.alpha = Parameter(torch.zeros(in_features) * alpha)
self.beta = Parameter(torch.zeros(in_features) * alpha)
self.no_div_by_zero = 0.000000001
def forward(self, hidden_states):
"""
Forward pass of the function.
Applies the function to the input elementwise.
SnakeBeta ∶= x + 1/b * sin^2 (xa)
"""
alpha = self.alpha.unsqueeze(0).unsqueeze(-1) # line up with x to [B, C, T]
beta = self.beta.unsqueeze(0).unsqueeze(-1)
alpha = torch.exp(alpha)
beta = torch.exp(beta)
hidden_states = hidden_states + (1.0 / (beta + self.no_div_by_zero)) * torch.pow(
torch.sin(hidden_states * alpha), 2
)
return hidden_states
def kaiser_sinc_filter1d(cutoff, half_width, kernel_size) -> torch.Tensor:
"""Generates a 1D Kaiser-windowed sinc filter.
Args:
cutoff (float): Normalized cutoff frequency (0 to 0.5).
half_width (float): Transition bandwidth.
kernel_size (int): Number of filter taps.
Returns:
torch.Tensor: A tensor of shape (1, 1, kernel_size) representing the filter.
"""
is_even = kernel_size % 2 == 0
half_size = kernel_size // 2
# Compute Kaiser window parameters
delta_f = 4 * half_width
attenuation = 2.285 * (half_size - 1) * math.pi * delta_f + 7.95
if attenuation > 50.0:
beta = 0.1102 * (attenuation - 8.7)
elif attenuation >= 21.0:
beta = 0.5842 * (attenuation - 21) ** 0.4 + 0.07886 * (attenuation - 21.0)
else:
beta = 0.0
kaiser_window = torch.kaiser_window(kernel_size, beta=beta, periodic=False, dtype=torch.float32)
# Compute time indices
if is_even:
time_indices = torch.arange(-half_size, half_size) + 0.5
else:
time_indices = torch.arange(kernel_size) - half_size
# Compute sinc filter
if cutoff == 0:
return torch.zeros((1, 1, kernel_size), dtype=torch.float32) # Ensures correct shape
sinc_filter = torch.sinc(2 * cutoff * time_indices)
normalized_filter = 2 * cutoff * kaiser_window * sinc_filter
# Normalize to ensure sum = 1 (avoid leakage of constant component)
normalized_filter /= normalized_filter.sum()
return normalized_filter.view(1, 1, kernel_size)
class UpSample1d(nn.Module):
def __init__(self, ratio=2, kernel_size=None):
super().__init__()
self.ratio = ratio
self.kernel_size = int(6 * ratio // 2) * 2 if kernel_size is None else kernel_size
self.stride = ratio
self.pad = self.kernel_size // ratio - 1
self.pad_left = self.pad * self.stride + (self.kernel_size - self.stride) // 2
self.pad_right = self.pad * self.stride + (self.kernel_size - self.stride + 1) // 2
filter = kaiser_sinc_filter1d(cutoff=0.5 / ratio, half_width=0.6 / ratio, kernel_size=self.kernel_size)
self.register_buffer("filter", filter, persistent=False)
def forward(self, hidden_states):
channels = hidden_states.shape[1]
hidden_states = F.pad(hidden_states, (self.pad, self.pad), mode="replicate")
hidden_states = self.ratio * F.conv_transpose1d(
hidden_states, self.filter.expand(channels, -1, -1), stride=self.stride, groups=channels
)
hidden_states = hidden_states[..., self.pad_left : -self.pad_right]
return hidden_states
class DownSample1d(nn.Module):
def __init__(self, ratio=2, kernel_size=None):
super().__init__()
cutoff = 0.5 / ratio
half_width = 0.6 / ratio
if cutoff < 0.0:
raise ValueError("Minimum cutoff must be larger than zero.")
if cutoff > 0.5:
raise ValueError("A cutoff above 0.5 does not make sense.")
self.even = kernel_size % 2 == 0
self.pad_left = kernel_size // 2 - int(self.even)
self.pad_right = kernel_size // 2
self.stride = ratio
filter = kaiser_sinc_filter1d(cutoff, half_width, kernel_size)
self.register_buffer("filter", filter, persistent=False)
def forward(self, hidden_states):
channels = hidden_states.shape[1]
hidden_states = F.pad(hidden_states, (self.pad_left, self.pad_right), mode="replicate")
out = F.conv1d(hidden_states, self.filter.expand(channels, -1, -1), stride=self.stride, groups=channels)
return out
class TorchActivation1d(nn.Module):
def __init__(
self,
activation,
up_ratio: int = 2,
down_ratio: int = 2,
up_kernel_size: int = 12,
down_kernel_size: int = 12,
):
super().__init__()
if not callable(activation):
raise TypeError("Activation function must be callable")
self.act = activation
self.upsample = UpSample1d(up_ratio, up_kernel_size)
self.downsample = DownSample1d(down_ratio, down_kernel_size)
def forward(self, hidden_states):
hidden_states = self.upsample(hidden_states)
hidden_states = self.act(hidden_states)
hidden_states = self.downsample(hidden_states)
return hidden_states
# SnakeBeta, UpSample1d, DownSample1d, AliasFreeActivation1d (formerly
# TorchActivation1d) are now provided by the shared ``common`` modules.
# See: vllm_omni/model_executor/models/common/{snake_activation,alias_free_activation}.py
class CausalConv1d(nn.Conv1d):
@@ -929,7 +772,7 @@ class AMPBlock(torch.nn.Module):
self.num_layers = len(self.convs1) + len(self.convs2) # total number of conv layers
self.activations = nn.ModuleList(
[TorchActivation1d(activation=SnakeBeta(channels)) for _ in range(self.num_layers)]
[AliasFreeActivation1d(activation=SnakeBeta(channels)) for _ in range(self.num_layers)]
)
if causal_type == "2":
@@ -940,7 +783,7 @@ class AMPBlock(torch.nn.Module):
stride=1,
padding=self._get_padding(kernel_size, 1),
)
self.pre_act = TorchActivation1d(activation=SnakeBeta(channels))
self.pre_act = AliasFreeActivation1d(activation=SnakeBeta(channels))
else:
self.pre_conv = nn.Identity()
self.pre_act = nn.Identity()
@@ -1002,7 +845,7 @@ class Qwen3TTSTokenizerV1DecoderBigVGANModel(Qwen3TTSTokenizerV1DecoderPreTraine
]
)
self.activation_post = TorchActivation1d(
self.activation_post = AliasFreeActivation1d(
activation=SnakeBeta(config.upsample_initial_channel // (2**self.num_upsample_layers))
)
self.conv_post = nn.Conv1d(
@@ -102,6 +102,22 @@ _OMNI_MODELS = {
"qwen3_tts_code2wav",
"Qwen3TTSCode2Wav",
),
## higgs-audio v2
"HiggsAudioV2ForConditionalGeneration": (
"higgs_audio_v2",
"higgs_audio_v2_talker",
"HiggsAudioV2TalkerForConditionalGeneration",
),
"HiggsAudioV2TalkerForConditionalGeneration": (
"higgs_audio_v2",
"higgs_audio_v2_talker",
"HiggsAudioV2TalkerForConditionalGeneration",
),
"HiggsAudioV2Code2WavForConditionalGeneration": (
"higgs_audio_v2",
"higgs_audio_v2_code2wav",
"HiggsAudioV2Code2WavForConditionalGeneration",
),
## mimo_audio
"MiMoAudioModel": (
"mimo_audio",
@@ -129,6 +145,12 @@ _OMNI_MODELS = {
"glm_image_ar",
"GlmImageForConditionalGeneration",
),
## glm_tts
"GLMTTSForConditionalGeneration": (
"glm_tts",
"glm_tts",
"GLMTTSForConditionalGeneration",
),
"OmniBagelForConditionalGeneration": (
"bagel",
"bagel",