[Model] Add GLM-TTS text-to-speech model support (#3141)

Signed-off-by: BeatSeat <wendavid552@gmail.com>
Signed-off-by: Yueqian Lin <70319226+linyueqian@users.noreply.github.com>
Co-authored-by: Yueqian Lin <70319226+linyueqian@users.noreply.github.com>
This commit is contained in:
BeatSeatandYueqian Lin authored and GitHub committed 2026-05-24 05:42:26 +08:00
1 parent 748470c1fb
commit 28ce618f0e
38 files changed
+7568 -7

No files matched your search

@@ -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
@@ -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
@@ -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]
@@ -129,6 +129,12 @@ _OMNI_MODELS = {
"glm_image_ar",
"GlmImageForConditionalGeneration",
),
## glm_tts
"GLMTTSForConditionalGeneration": (
"glm_tts",
"glm_tts",
"GLMTTSForConditionalGeneration",
),
"OmniBagelForConditionalGeneration": (
"bagel",
"bagel",