Merge branch 'main' into fix/omni-weight-snapshot-prefetch

This commit is contained in:
Zhou Taichang authored and GitHub committed 2026-06-12 14:54:29 +08:00
commit 5a7cda40c3
290 files changed
+28064 -3581

No files matched your search

@@ -0,0 +1,2 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
@@ -0,0 +1,209 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Adopted from https://github.com/inclusionAI/Ming-omni-tts/blob/main/audio_tokenizer/istft.py
import torch
import torch.nn as nn
class ISTFT(nn.Module):
"""
Custom implementation of ISTFT since torch.istft doesn't allow custom padding (other than `center=True`) with
windowing. This is because the NOLA (Nonzero Overlap Add) check fails at the edges.
See issue: https://github.com/pytorch/pytorch/issues/62323
Specifically, in the context of neural vocoding we are interested in "same" padding analogous to CNNs.
The NOLA constraint is met as we trim padded samples anyway.
Args:
n_fft (int): Size of Fourier transform.
hop_length (int): The distance between neighboring sliding window frames.
win_length (int): The size of window frame and STFT filter.
padding (str, optional): Type of padding. Options are "center" or "same". Defaults to "same".
"""
def __init__(self, n_fft: int, hop_length: int, win_length: int, padding: str = "same"):
super().__init__()
if padding not in ["center", "same"]:
raise ValueError("Padding must be 'center' or 'same'.")
self.padding = padding
self.n_fft = n_fft
self.hop_length = hop_length
self.win_length = win_length
window = torch.hann_window(win_length)
self.register_buffer("window", window)
self.buffer_len = self.win_length - self.hop_length
def _buffer_process(
self,
x: torch.Tensor,
buffer: torch.Tensor | None,
pad: int,
last_chunk: bool = False,
streaming: bool = False,
) -> tuple[torch.Tensor, torch.Tensor | None]:
if streaming:
if buffer is None:
# first chunk
x = x[:, pad:]
if buffer is not None:
# next chunk
x[:, : self.buffer_len] += buffer
buffer = x[:, -self.buffer_len :]
if not last_chunk:
x = x[:, : -self.buffer_len]
else:
x = x[:, :-pad]
else:
x = x[:, pad:-pad]
return x, buffer
def forward(
self,
spec: torch.Tensor,
audio_buffer: torch.Tensor | None = None,
window_buffer: torch.Tensor | None = None,
streaming: bool = False,
last_chunk: bool = False,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor | None, torch.Tensor | None]:
"""
Compute the Inverse Short Time Fourier Transform (ISTFT) of a complex spectrogram.
Args:
spec (Tensor): Input complex spectrogram of shape (B, N, T), where B is the batch size,
N is the number of frequency bins, and T is the number of time frames.
audio_buffer (Tensor): [Streaming Input/State] The audio overlap buffer from the previous chunk.
Shape: (B, win_length - hop_length)
window_buffer (Tensor): [Streaming Input/State] The window overlap buffer from the previous chunk.
streaming: If `True`, the function operates in streaming mode, processing `spec` as a single chunk.
last_chunk: When `streaming=True` and `last_chunk=True`, the function can perform final "flush" operations
Returns:
Reconstructed signal, plus streaming buffers when `padding="same"`.
"""
if self.padding == "center":
# Fallback to pytorch native implementation
return torch.istft(spec, self.n_fft, self.hop_length, self.win_length, self.window, center=True)
elif self.padding == "same":
pad = (self.win_length - self.hop_length) // 2
else:
raise ValueError("Padding must be 'center' or 'same'.")
if spec.dim() != 3:
raise ValueError(f"Expected spec rank-3 [Batch, Freq, Time], got {tuple(spec.shape)}")
_, _, T = spec.shape
# Inverse FFT
ifft = torch.fft.irfft(spec, self.n_fft, dim=1, norm="backward")
ifft = ifft * self.window[None, :, None]
# Overlap and Add
output_size = (T - 1) * self.hop_length + self.win_length
y = torch.nn.functional.fold(
ifft,
output_size=(1, output_size),
kernel_size=(1, self.win_length),
stride=(1, self.hop_length),
)[:, 0, 0, :]
y, audio_buffer = self._buffer_process(y, audio_buffer, pad, last_chunk=last_chunk, streaming=streaming)
# Window envelope
window_sq = self.window.square().expand(1, T, -1).transpose(1, 2)
window_envelope = (
torch.nn.functional.fold(
window_sq,
output_size=(1, output_size),
kernel_size=(1, self.win_length),
stride=(1, self.hop_length),
)
.squeeze(0)
.squeeze(0)
)
window_envelope, window_buffer = self._buffer_process(
window_envelope, window_buffer, pad, last_chunk=last_chunk, streaming=streaming
)
window_envelope = window_envelope.squeeze()
# Normalize
if not (window_envelope > 1e-11).all():
raise RuntimeError("ISTFT window envelope underflowed; invalid overlap-add state.")
y = y / window_envelope
return y, audio_buffer, window_buffer
class FourierHead(nn.Module):
"""Base class for inverse fourier modules."""
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Args:
x (Tensor): Input tensor of shape (B, L, H), where B is the batch size,
L is the sequence length, and H denotes the model dimension.
Returns:
Tensor: Reconstructed time-domain audio signal of shape (B, T), where T is the length of the output signal.
"""
raise NotImplementedError("Subclasses must implement the forward method.")
class ISTFTHead(FourierHead):
"""
ISTFT Head module for predicting STFT complex coefficients.
Args:
dim (int): Hidden dimension of the model.
n_fft (int): Size of Fourier transform.
hop_length (int): The distance between neighboring sliding window frames, which should align with
the resolution of the input features.
padding (str, optional): Type of padding. Options are "center" or "same". Defaults to "same".
"""
def __init__(self, dim: int, n_fft: int, hop_length: int, padding: str = "same"):
super().__init__()
out_dim = n_fft + 2
self.out = torch.nn.Linear(dim, out_dim)
self.istft = ISTFT(n_fft=n_fft, hop_length=hop_length, win_length=n_fft, padding=padding)
def forward(
self,
x: torch.Tensor,
audio_buffer: torch.Tensor | None = None,
window_buffer: torch.Tensor | None = None,
streaming: bool = False,
last_chunk: bool = False,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None, torch.Tensor | None]:
"""
Forward pass of the ISTFTHead module.
Args:
x (Tensor): Input tensor of shape (B, L, H), where B is the batch size,
L is the sequence length, and H denotes the model dimension.
Returns:
Audio, predicted spectrogram coefficients, and streaming buffers.
"""
x_pred = self.out(x)
x_pred = x_pred.transpose(1, 2)
mag, p = x_pred.chunk(2, dim=1)
mag = torch.exp(mag)
mag = torch.clip(mag, max=1e2) # safeguard to prevent excessively large magnitudes
# wrapping happens here. These two lines produce real and imaginary value
x = torch.cos(p)
y = torch.sin(p)
# recalculating phase here does not produce anything new
# only costs time
# phase = torch.atan2(y, x)
# S = mag * torch.exp(phase * 1j)
# better directly produce the complex value
S = mag * (x + 1j * y)
audio, audio_buffer, window_buffer = self.istft(
S, audio_buffer=audio_buffer, window_buffer=window_buffer, streaming=streaming, last_chunk=last_chunk
)
return audio.unsqueeze(1), x_pred, audio_buffer, window_buffer
__all__ = ["FourierHead", "ISTFT", "ISTFTHead"]
@@ -1,10 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2025 The vLLM-Omni team.
# Copyright (c) Ant Group. All rights reserved.
# Adapted from:
# https://github.com/inclusionAI/Ming/tree/e58533db227031990c5a6864dcf5f08fb53ed0d2/AudioVAE
from __future__ import annotations
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import torch
import torch.nn as nn
@@ -13,6 +8,8 @@ from transformers import PretrainedConfig, PreTrainedModel, Qwen2Config, Qwen2Mo
from transformers.utils import is_flash_attn_2_available
from vllm.logger import init_logger
from .audio_dsp import ISTFTHead
logger = init_logger(__name__)
@@ -21,114 +18,50 @@ class AudioVAEConfig(PretrainedConfig):
def __init__(
self,
sample_rate: int = 44100,
enc_kwargs: dict | None = None,
dec_kwargs: dict | None = None,
init_method: str = "kaiming",
patch_size: int = 4,
sample_rate=44100,
enc_kwargs=None,
semantic_module_kwargs=None,
dec_kwargs=None,
hifi_gan_disc_kwargs=None,
spec_disc_kwargs=None,
lambda_disc=1.0,
lambda_mel_loss=15,
lambda_adv=1.0,
lambda_feat_match_loss=1.0,
lambda_semantic=5.0,
init_method="kaiming",
patch_size=4,
**kwargs,
):
self.sample_rate = sample_rate
self.enc_kwargs = enc_kwargs or {}
self.semantic_module_kwargs = semantic_module_kwargs
self.dec_kwargs = dec_kwargs or {}
self.hifi_gan_disc_kwargs = hifi_gan_disc_kwargs
self.spec_disc_kwargs = spec_disc_kwargs
self.lambda_disc = lambda_disc
self.lambda_mel_loss = lambda_mel_loss
self.lambda_adv = lambda_adv
self.lambda_feat_match_loss = lambda_feat_match_loss
self.lambda_semantic = lambda_semantic
self.init_method = init_method
self.patch_size = patch_size
super().__init__(**kwargs)
class ISTFT(nn.Module):
def __init__(self, n_fft: int, hop_length: int, win_length: int, padding: str = "same"):
super().__init__()
if padding not in ["center", "same"]:
raise ValueError("Padding must be 'center' or 'same'.")
self.padding = padding
self.n_fft = n_fft
self.hop_length = hop_length
self.win_length = win_length
window = torch.hann_window(win_length)
self.register_buffer("window", window)
self.buffer_len = self.win_length - self.hop_length
def _buffer_process(self, x, buffer, pad, last_chunk=False, streaming=False):
if streaming:
if buffer is None:
x = x[:, pad:]
if buffer is not None:
x[:, : self.buffer_len] += buffer
buffer = x[:, -self.buffer_len :]
if not last_chunk:
x = x[:, : -self.buffer_len]
else:
x = x[:, :-pad]
else:
x = x[:, pad:-pad]
return x, buffer
def forward(self, spec, audio_buffer=None, window_buffer=None, streaming=False, last_chunk=False):
if self.padding == "center":
return torch.istft(spec, self.n_fft, self.hop_length, self.win_length, self.window, center=True)
elif self.padding == "same":
pad = (self.win_length - self.hop_length) // 2
else:
raise ValueError("Padding must be 'center' or 'same'.")
B, N, T = spec.shape
ifft = torch.fft.irfft(spec, self.n_fft, dim=1, norm="backward")
ifft = ifft * self.window[None, :, None]
output_size = (T - 1) * self.hop_length + self.win_length
y = torch.nn.functional.fold(
ifft,
output_size=(1, output_size),
kernel_size=(1, self.win_length),
stride=(1, self.hop_length),
)[:, 0, 0, :]
y, audio_buffer = self._buffer_process(y, audio_buffer, pad, last_chunk=last_chunk, streaming=streaming)
window_sq = self.window.square().expand(1, T, -1).transpose(1, 2)
window_envelope = (
torch.nn.functional.fold(
window_sq,
output_size=(1, output_size),
kernel_size=(1, self.win_length),
stride=(1, self.hop_length),
)
.squeeze(0)
.squeeze(0)
)
window_envelope, window_buffer = self._buffer_process(
window_envelope, window_buffer, pad, last_chunk=last_chunk, streaming=streaming
)
window_envelope = window_envelope.squeeze()
assert (window_envelope > 1e-11).all()
y = y / window_envelope
return y, audio_buffer, window_buffer
class ISTFTHead(nn.Module):
def __init__(self, dim: int, n_fft: int, hop_length: int, padding: str = "same"):
super().__init__()
out_dim = n_fft + 2
self.out = nn.Linear(dim, out_dim)
self.istft = ISTFT(n_fft=n_fft, hop_length=hop_length, win_length=n_fft, padding=padding)
def forward(self, x, audio_buffer=None, window_buffer=None, streaming=False, last_chunk=False):
x_pred = self.out(x)
x_pred = x_pred.transpose(1, 2)
mag, p = x_pred.chunk(2, dim=1)
mag = torch.exp(mag)
mag = torch.clip(mag, max=1e2)
x = torch.cos(p)
y = torch.sin(p)
S = mag * (x + 1j * y)
audio, audio_buffer, window_buffer = self.istft(
S, audio_buffer=audio_buffer, window_buffer=window_buffer, streaming=streaming, last_chunk=last_chunk
)
return audio.unsqueeze(1), x_pred, audio_buffer, window_buffer
def _qwen2_config(backbone):
config = Qwen2Config.from_dict(config_dict=backbone)
if (getattr(config, "_attn_implementation", None) or getattr(config, "attn_implementation", None)) not in (
None,
"flash_attention_2",
):
return config
if is_flash_attn_2_available():
config._attn_implementation_autoset = True
config._attn_implementation = "flash_attention_2"
else:
config._attn_implementation = "sdpa"
return config
class StreamingLinearUpsample(nn.Module):
@@ -138,6 +71,8 @@ class StreamingLinearUpsample(nn.Module):
self.upsampler = nn.Upsample(scale_factor=scale_factor, mode="linear", align_corners=False)
def forward(self, x, state=None, is_last=False):
if x is None and is_last and (state is None or state.get("prev_chunk") is None):
raise ValueError("Received end-of-stream without any latent chunk to upsample.")
if state is None:
state = {"prev_chunk": None, "history_last": None, "is_first": True}
@@ -188,16 +123,72 @@ class StreamingLinearUpsample(nn.Module):
return final_out, state
class Encoder(nn.Module):
def __init__(self, encoder_args, input_dim=320, hop_size=320, latent_dim=64, patch_size=-1):
super().__init__()
config = _qwen2_config(encoder_args)
logger.info("AudioVAE Encoder: using attn_implementation=%r", config._attn_implementation)
self.encoder = Qwen2Model(config)
self.input_dim = input_dim
self.hop_size = hop_size
self.latent_dim = latent_dim
self.fc1 = nn.Linear(input_dim, config.hidden_size, bias=False)
self.fc2 = nn.Linear(config.hidden_size, config.hidden_size)
self.fc3 = nn.Linear(config.hidden_size, latent_dim * 2)
self.norm = nn.LayerNorm(config.hidden_size)
self.patch_size = patch_size
if patch_size != -1:
aggregator_config = _qwen2_config({**encoder_args, "num_hidden_layers": 4})
self.aggregator = Qwen2Model(aggregator_config)
self.cls_embed = nn.Parameter(torch.rand(1, 1, config.hidden_size))
self.cls_embed.data.normal_(0, 0.02)
def get_frames(self, x):
num_frames_total = (x.size(-1) + self.hop_size - 1) // self.hop_size
expected_len = (num_frames_total - 1) * self.hop_size + self.input_dim
padding_needed = expected_len - x.size(-1)
waveform = F.pad(x, (0, padding_needed), value=0.0)
frames = waveform.unfold(dimension=-1, size=self.input_dim, step=self.hop_size)
return frames
def pad_patch_insert_cls(self, x):
bsz, _, dim = x.size()
num_frame = x.size(1)
r = num_frame % self.patch_size
pad_num = self.patch_size - r if r else 0
x = F.pad(x, (0, 0, 0, pad_num), value=0.0)
# [Batch, Time, Dimension] -> [Batch*PatchGroups, Patch, Dimension].
x = x.reshape(-1, self.patch_size, dim)
x = torch.cat((x, self.cls_embed.expand(x.size(0), -1, -1)), dim=1)
# [Batch*PatchGroups, Patch+1, Dimension] -> [Batch, Time, Dimension].
x = x.reshape(bsz, -1, dim)
return x
def forward(self, waveform):
x = self.get_frames(waveform)
x = self.fc1(x)
x = self.fc2(x)
x = self.encoder(inputs_embeds=x)
x = x.last_hidden_state
if self.patch_size != -1:
x = self.pad_patch_insert_cls(x)
x = self.aggregator(inputs_embeds=x)
x = x.last_hidden_state
bsz, _, dim = x.size()
# [Batch, Time, Dimension] -> [Batch*PatchGroups, Patch+1, Dimension].
x = x.reshape(-1, self.patch_size + 1, dim)
# [Batch*PatchGroups, 1, Dimension] -> [Batch, PatchGroups, Dimension].
x = x[:, -1:, :].reshape(bsz, -1, dim)
x = self.fc3(x)
return x, waveform.unsqueeze(1)
class Decoder(nn.Module):
def __init__(self, decoder_args, output_dim=320, latent_dim=64, patch_size=-1):
super().__init__()
config = Qwen2Config.from_dict(config_dict=decoder_args)
if is_flash_attn_2_available():
config._attn_implementation_autoset = True
config._attn_implementation = "flash_attention_2"
else:
config._attn_implementation = "sdpa"
config = _qwen2_config(decoder_args)
logger.info("AudioVAE Decoder: using attn_implementation=%r", config._attn_implementation)
self.decoder = Qwen2Model(config)
self.output_dim = output_dim
@@ -211,7 +202,21 @@ class Decoder(nn.Module):
if self.patch_size != -1:
self.upsampling = StreamingLinearUpsample(scale_factor=patch_size)
def forward(self, x):
x = self.fc1(x)
if self.patch_size != -1:
# [Batch, Time, Dimension] -> [Batch, Dimension, Time] -> [Batch, Time, Dimension].
x = self.upsampling.upsampler(x.transpose(1, 2)).transpose(1, 2)
x = self.decoder(inputs_embeds=x)
x = x.last_hidden_state
x, _ = self.head(x)
return x, None
def low_level_reconstruct(self, x, past_key_values=None, use_cache=False, stream_state=None, last_chunk=False):
if stream_state is None:
stream_state = (None, None, None)
upsample_state, audio_buffer, window_buffer = stream_state
bsz, device, dtype = x.size(0), x.device, x.dtype
x = self.fc1(x)
@@ -222,6 +227,7 @@ class Decoder(nn.Module):
stream_state = (upsample_state, audio_buffer, window_buffer)
return torch.empty(bsz, 1, 0, device=device, dtype=dtype), stream_state, past_key_values
else:
# [Batch, Time, Dimension] -> [Batch, Dimension, Time] -> [Batch, Time, Dimension].
x = self.upsampling.upsampler(x.transpose(1, 2)).transpose(1, 2)
hidden_states_list = []
@@ -239,7 +245,6 @@ class Decoder(nn.Module):
past_len = 0
curr_len = x.shape[1]
if past_len < target_len and (past_len + curr_len) >= sw_size:
fill_len = target_len - past_len
x_fill = x[:, :fill_len, :]
@@ -269,86 +274,39 @@ class Decoder(nn.Module):
return x_out, stream_state, past_key_values
class Encoder(nn.Module):
def __init__(self, encoder_args, input_dim=320, hop_size=320, latent_dim=64, patch_size=-1):
super().__init__()
config = Qwen2Config.from_dict(config_dict=encoder_args)
if is_flash_attn_2_available():
config._attn_implementation_autoset = True
config._attn_implementation = "flash_attention_2"
else:
config._attn_implementation = "sdpa"
logger.info("AudioVAE Encoder: using attn_implementation=%r", config._attn_implementation)
self.encoder = Qwen2Model(config)
self.input_dim = input_dim
self.hop_size = hop_size
self.latent_dim = latent_dim
self.fc1 = nn.Linear(input_dim, config.hidden_size, bias=False)
self.fc2 = nn.Linear(config.hidden_size, config.hidden_size)
self.fc3 = nn.Linear(config.hidden_size, latent_dim * 2)
self.norm = nn.LayerNorm(config.hidden_size)
self.patch_size = patch_size
if patch_size != -1:
config.num_hidden_layers = 4
self.aggregator = Qwen2Model(config)
self.cls_embed = nn.Parameter(torch.rand(1, 1, config.hidden_size))
self.cls_embed.data.normal_(0, 0.02)
def get_frames(self, x):
num_frames_total = (x.size(-1) + self.hop_size - 1) // self.hop_size
expected_len = (num_frames_total - 1) * self.hop_size + self.input_dim
padding_needed = expected_len - x.size(-1)
waveform = F.pad(x, (0, padding_needed), value=0.0)
frames = waveform.unfold(dimension=-1, size=self.input_dim, step=self.hop_size)
return frames
def pad_patch_insert_cls(self, x):
bsz, _, dim = x.size()
num_frame = x.size(1)
r = num_frame % self.patch_size
pad_num = self.patch_size - r if r else 0
x = F.pad(x, (0, 0, 0, pad_num), value=0.0)
x = x.reshape(-1, self.patch_size, dim)
x = torch.cat((x, self.cls_embed.expand(x.size(0), -1, -1)), dim=1)
x = x.reshape(bsz, -1, dim)
return x
def forward(self, waveform):
x = self.get_frames(waveform)
x = self.fc1(x)
x = self.fc2(x)
x = self.encoder(inputs_embeds=x)
x = x.last_hidden_state
if self.patch_size != -1:
x = self.pad_patch_insert_cls(x)
x = self.aggregator(inputs_embeds=x)
x = x.last_hidden_state
bsz, _, dim = x.size()
x = x.reshape(-1, self.patch_size + 1, dim)
x = x[:, -1:, :].reshape(bsz, -1, dim)
x = self.fc3(x)
return x, waveform.unsqueeze(1)
class AudioVAE(PreTrainedModel):
config_class = AudioVAEConfig
def __init__(self, config: AudioVAEConfig):
def __init__(self, config):
super().__init__(config)
self.config = config
enc_kwargs = config.enc_kwargs
dec_kwargs = config.dec_kwargs
for key in ("backbone", "input_dim", "latent_dim"):
if key not in enc_kwargs:
raise ValueError(f"AudioVAE.enc_kwargs missing required key: {key}")
for key in ("backbone", "output_dim", "latent_dim"):
if key not in dec_kwargs:
raise ValueError(f"AudioVAE.dec_kwargs missing required key: {key}")
hop_size = enc_kwargs.get("hop_size", enc_kwargs["input_dim"])
if enc_kwargs["input_dim"] != hop_size:
raise ValueError(f"AudioVAE encoder input_dim ({enc_kwargs['input_dim']}) != hop_size ({hop_size}).")
if hop_size != dec_kwargs["output_dim"]:
raise ValueError(
f"AudioVAE encoder hop_size ({hop_size}) != decoder output_dim ({dec_kwargs['output_dim']})."
)
self.encoder = Encoder(
encoder_args=config.enc_kwargs["backbone"],
input_dim=config.enc_kwargs["input_dim"],
hop_size=config.enc_kwargs.get("hop_size", 320),
latent_dim=config.enc_kwargs["latent_dim"],
encoder_args=enc_kwargs["backbone"],
input_dim=enc_kwargs["input_dim"],
hop_size=hop_size,
latent_dim=enc_kwargs["latent_dim"],
patch_size=config.patch_size,
)
self.decoder = Decoder(
decoder_args=config.dec_kwargs["backbone"],
output_dim=config.dec_kwargs["output_dim"],
latent_dim=config.dec_kwargs["latent_dim"],
decoder_args=dec_kwargs["backbone"],
output_dim=dec_kwargs["output_dim"],
latent_dim=dec_kwargs["latent_dim"],
patch_size=config.patch_size,
)
self.post_init()
@@ -367,21 +325,50 @@ class AudioVAE(PreTrainedModel):
if module.padding_idx is not None:
module.weight.data[module.padding_idx].zero_()
@torch.inference_mode()
def encode_latent(self, waveform, waveform_length):
from diffusers.models.autoencoders.autoencoder_oobleck import OobleckDiagonalGaussianDistribution
if waveform.ndim != 2:
raise ValueError(f"Expected waveform rank-2 [Batch, Time], got {tuple(waveform.shape)}")
if waveform_length.ndim != 1:
raise ValueError(f"Expected waveform_length rank-1 [Batch], got {tuple(waveform_length.shape)}")
if waveform.shape[0] != waveform_length.shape[0]:
raise ValueError(
"Batch mismatch: "
f"waveform batch={waveform.shape[0]} vs "
f"waveform_length batch={waveform_length.shape[0]}"
)
if torch.any(waveform_length <= 0):
raise ValueError("waveform_length must be strictly positive.")
frame_num = torch.ceil(waveform_length / self.config.enc_kwargs["input_dim"]).to(torch.int32)
if self.config.patch_size != -1:
frame_num = torch.ceil(frame_num / self.config.patch_size)
h, y = self.encoder(waveform)
h, _ = self.encoder(waveform)
h = h.transpose(1, 2)
posterior = OobleckDiagonalGaussianDistribution(h)
latent = posterior.sample()
mean, logvar = torch.chunk(h, 2, dim=1)
logvar = torch.clamp(logvar, -30.0, 20.0)
std = torch.exp(0.5 * logvar)
latent = mean + std * torch.randn_like(mean)
latent = latent.transpose(1, 2)
return latent, frame_num
@torch.inference_mode()
def decode(self, latent, past_key_values=None, use_cache=False, stream_state=(None, None, None), last_chunk=False):
if latent.dim() != 3:
raise ValueError(f"Expected latent rank-3 [B,T,D], got shape={tuple(latent.shape)}")
if latent.shape[0] <= 0:
raise ValueError("latent batch size must be positive.")
target_dtype = next(self.decoder.parameters()).dtype
target_device = next(self.decoder.parameters()).device
if latent.dtype != target_dtype or latent.device != target_device:
latent = latent.to(device=target_device, dtype=target_dtype)
expected_latent_dim = self.config.dec_kwargs["latent_dim"]
if latent.shape[-1] != expected_latent_dim:
raise ValueError(f"Latent dim mismatch in decode(): got {latent.shape[-1]}, expected {expected_latent_dim}")
waveform, stream_state, past_key_values = self.decoder.low_level_reconstruct(
latent,
past_key_values=past_key_values,
@@ -0,0 +1,193 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import torch
import torch.nn.functional as F
from torch import nn
from x_transformers.x_transformers import apply_rotary_pos_emb
class RMSNorm(nn.Module):
def __init__(self, dim, eps=1e-6):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim))
def forward(self, x):
if self.weight.dtype in [torch.float16, torch.bfloat16]:
x = x.to(self.weight.dtype)
x = F.rms_norm(x, normalized_shape=(x.shape[-1],), weight=self.weight, eps=self.eps)
return x
class FeedForward(nn.Module):
def __init__(self, dim, dim_out=None, mult=4, dropout=0.0, approximate="none"):
super().__init__()
inner_dim = int(dim * mult)
dim_out = dim_out if dim_out is not None else dim
activation = nn.GELU(approximate=approximate)
project_in = nn.Sequential(nn.Linear(dim, inner_dim), activation)
self.ff = nn.Sequential(project_in, nn.Dropout(dropout), nn.Linear(inner_dim, dim_out))
def forward(self, x):
return self.ff(x)
class Attention(nn.Module):
def __init__(
self,
dim,
heads=8,
dim_head=64,
dropout=0.0,
qk_norm=None,
pe_attn_head=None,
attn_mask_enabled=True,
):
super().__init__()
self.dim = dim
self.heads = heads
self.inner_dim = dim_head * heads
self.dropout = dropout
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)
if qk_norm is None:
self.q_norm = None
self.k_norm = None
elif qk_norm == "rms_norm":
self.q_norm = RMSNorm(dim_head)
self.k_norm = RMSNorm(dim_head)
else:
raise ValueError(f"Unimplemented qk_norm: {qk_norm}")
self.to_out = nn.ModuleList([])
self.to_out.append(nn.Linear(self.inner_dim, dim))
self.to_out.append(nn.Dropout(dropout))
self.pe_attn_head = pe_attn_head
self.attn_mask_enabled = attn_mask_enabled
def forward(self, x, mask=None, rope=None):
batch_size = x.shape[0]
query = self.to_q(x)
key = self.to_k(x)
value = self.to_v(x)
inner_dim = key.shape[-1]
head_dim = inner_dim // self.heads
query = query.view(batch_size, -1, self.heads, head_dim).transpose(1, 2)
key = key.view(batch_size, -1, self.heads, head_dim).transpose(1, 2)
value = value.view(batch_size, -1, self.heads, head_dim).transpose(1, 2)
if self.q_norm is not None:
query = self.q_norm(query)
if self.k_norm is not None:
key = self.k_norm(key)
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)
if self.pe_attn_head is not None:
on = self.pe_attn_head
query[:, :on, :, :] = apply_rotary_pos_emb(query[:, :on, :, :], freqs, q_xpos_scale)
key[:, :on, :, :] = apply_rotary_pos_emb(key[:, :on, :, :], freqs, k_xpos_scale)
else:
query = apply_rotary_pos_emb(query, freqs, q_xpos_scale)
key = apply_rotary_pos_emb(key, freqs, k_xpos_scale)
if self.attn_mask_enabled and mask is not None:
valid_sample_indices = mask.any(dim=1)
final_output = torch.zeros_like(query).to(query.device)
attn_mask = mask[valid_sample_indices]
query = query[valid_sample_indices]
key = key[valid_sample_indices]
value = value[valid_sample_indices]
attn_mask = attn_mask.unsqueeze(1).unsqueeze(1)
attn_mask = attn_mask.expand(valid_sample_indices.sum().item(), self.heads, query.shape[-2], key.shape[-2])
else:
attn_mask = None
x = F.scaled_dot_product_attention(query, key, value, attn_mask=attn_mask, dropout_p=0.0, is_causal=False)
if self.attn_mask_enabled and mask is not None:
final_output[valid_sample_indices] = x
x = final_output
x = x.transpose(1, 2).reshape(batch_size, -1, self.heads * head_dim)
x = x.to(query.dtype)
x = self.to_out[0](x)
x = self.to_out[1](x)
if mask is not None:
mask = mask.unsqueeze(-1)
x = x.masked_fill(~mask, 0.0)
return x
class DiTBlock(nn.Module):
def __init__(
self,
hidden_size,
num_heads,
mlp_ratio=4.0,
dropout=0.1,
qk_norm=None,
pe_attn_head=None,
attn_mask_enabled=True,
**kwargs,
):
super().__init__()
self.norm1 = RMSNorm(hidden_size)
self.attn = Attention(
dim=hidden_size,
heads=num_heads,
dim_head=hidden_size // num_heads,
dropout=dropout,
qk_norm=qk_norm,
pe_attn_head=pe_attn_head,
attn_mask_enabled=attn_mask_enabled,
)
self.norm2 = RMSNorm(hidden_size)
self.mlp = FeedForward(dim=hidden_size, mult=mlp_ratio, dropout=dropout, approximate="tanh")
def forward(self, x, mask, rope):
x = x + self.attn(self.norm1(x), mask=mask, rope=rope)
x = x + self.mlp(self.norm2(x))
return x
class FinalLayer(nn.Module):
def __init__(self, hidden_size, out_channels):
super().__init__()
self.norm_final = RMSNorm(hidden_size)
self.linear = nn.Linear(hidden_size, out_channels, bias=True)
def forward(self, x):
x = self.norm_final(x)
x = self.linear(x)
return x
class CondEmbedder(nn.Module):
def __init__(self, input_feature_size, hidden_size):
super().__init__()
self.cond_embedder = nn.Linear(input_feature_size, hidden_size)
def forward(self, llm_cond):
return self.cond_embedder(llm_cond)
def get_epss_timesteps(n, device, dtype):
dt = 1 / 32
predefined_timesteps = {
5: [0, 2, 4, 8, 16, 32],
6: [0, 2, 4, 6, 8, 16, 32],
7: [0, 2, 4, 6, 8, 16, 24, 32],
10: [0, 2, 4, 6, 8, 12, 16, 20, 24, 28, 32],
12: [0, 2, 4, 6, 8, 10, 12, 14, 16, 20, 24, 28, 32],
16: [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32],
}
t = predefined_timesteps.get(n, [])
if not t:
return torch.linspace(0, 1, n + 1, device=device, dtype=dtype)
return dt * torch.tensor(t, device=device, dtype=dtype)
@@ -0,0 +1,68 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import torch
from .dit import get_epss_timesteps
def apply_sway_sampling(t, sway_sampling_coef):
if sway_sampling_coef is None:
return t
return t + sway_sampling_coef * (torch.cos(torch.pi / 2 * t) - 1 + t)
def build_timesteps(steps, device, dtype, use_epss=True, sway_sampling_coef=-1.0):
if steps <= 0:
raise ValueError(f"steps must be positive, got {steps}")
if use_epss:
t = get_epss_timesteps(steps, device=device, dtype=dtype)
else:
t = torch.linspace(0, 1, steps + 1, device=device, dtype=dtype)
return apply_sway_sampling(t, sway_sampling_coef)
class Solver:
def __init__(self, func, y0, sigma=0.25, temperature=1.5) -> None:
self.func = func
self.y0 = y0
self.sigma = sigma
self.temperature = temperature
def integrate(self, t):
solution = torch.empty(len(t), *self.y0.shape, dtype=self.y0.dtype, device=self.y0.device)
solution[0] = self.y0
j = 1
y0 = self.y0
for t0, t1 in zip(t[:-1], t[1:]):
dt = t1 - t0
f0 = self.func(t0, y0)
dy = dt * f0
y1 = y0 + dy
while j < len(t) and t1 >= t[j]:
solution[j] = self._linear_interp(t0, t1, y0, y1, t[j])
j += 1
noise = torch.randn_like(y0)
shift = self.sigma * (self.temperature**0.5) * (abs(dt) ** 0.5) * noise
y0 = y1 + shift
return solution
def _linear_interp(self, t0, t1, y0, y1, t):
if t == t0:
return y0
if t == t1:
return y1
slope = (t - t0) / (t1 - t0)
return y0 + slope * (y1 - y0)
def integrate_cfm_steps(fn, y0, t, sde_args, sde_rnd, steps):
for step in range(steps):
dt = t[step + 1] - t[step]
y0 = y0 + fn(t[step], y0) * dt
y0 = y0 + sde_args[1] * (sde_args[2] ** 0.5) * (dt.abs() ** 0.5) * sde_rnd[step]
return y0
@@ -141,24 +141,37 @@ class ConditionalCFM(BASECFM):
if isinstance(self.estimator, torch.nn.Module):
return self.estimator(x, mask, mu, t, spks, cond)
else:
# TensorRT estimator: bind raw device pointers. The flow runs in
# fp32 but the engine may have fp16 I/O (strongly-typed fp16 engine),
# so cast inputs/output to the engine's dtype at the boundary. Keep
# references to the cast buffers alive until execute completes (a bare
# ``.contiguous().data_ptr()`` could free the temp -> dangling ptr).
io_dtype = getattr(self.estimator, "io_dtype", x.dtype)
[estimator, stream], trt_engine = self.estimator.acquire_estimator()
# NOTE need to synchronize when switching stream
torch.cuda.current_stream().synchronize()
with stream:
estimator.set_input_shape("x", (2, 80, x.size(2)))
estimator.set_input_shape("mask", (2, 1, x.size(2)))
estimator.set_input_shape("mu", (2, 80, x.size(2)))
x_e = x.to(io_dtype).contiguous()
mask_e = mask.to(io_dtype).contiguous()
mu_e = mu.to(io_dtype).contiguous()
t_e = t.to(io_dtype).contiguous()
spks_e = spks.to(io_dtype).contiguous()
cond_e = cond.to(io_dtype).contiguous()
out_e = torch.empty_like(x_e)
estimator.set_input_shape("x", (2, 80, x_e.size(2)))
estimator.set_input_shape("mask", (2, 1, x_e.size(2)))
estimator.set_input_shape("mu", (2, 80, x_e.size(2)))
estimator.set_input_shape("t", (2,))
estimator.set_input_shape("spks", (2, 80))
estimator.set_input_shape("cond", (2, 80, x.size(2)))
estimator.set_input_shape("cond", (2, 80, x_e.size(2)))
data_ptrs = [
x.contiguous().data_ptr(),
mask.contiguous().data_ptr(),
mu.contiguous().data_ptr(),
t.contiguous().data_ptr(),
spks.contiguous().data_ptr(),
cond.contiguous().data_ptr(),
x.data_ptr(),
x_e.data_ptr(),
mask_e.data_ptr(),
mu_e.data_ptr(),
t_e.data_ptr(),
spks_e.data_ptr(),
cond_e.data_ptr(),
out_e.data_ptr(),
]
for i, j in enumerate(data_ptrs):
estimator.set_tensor_address(trt_engine.get_tensor_name(i), j)
@@ -166,7 +179,7 @@ class ConditionalCFM(BASECFM):
assert estimator.execute_async_v3(torch.cuda.current_stream().cuda_stream) is True
torch.cuda.current_stream().synchronize()
self.estimator.release_estimator(estimator, stream)
return x
return out_e.to(x.dtype)
class CausalConditionalCFM(ConditionalCFM):
@@ -3,10 +3,16 @@
import os
from collections.abc import Iterable, Mapping, Sequence
from functools import partial
from math import gcd
from threading import Lock
import numpy as np
import onnxruntime
import torch
import torch.nn as nn
from huggingface_hub import snapshot_download
from scipy.signal import resample_poly
from transformers import Qwen2Config
from transformers.feature_extraction_utils import BatchFeature
from vllm.config import VllmConfig
from vllm.config.multimodal import BaseDummyOptions
@@ -32,12 +38,15 @@ from vllm.v1.sample.metadata import SamplingMetadata
from vllm.v1.sample.sampler import Sampler
from vllm_omni.data_entry_keys import EmbeddingsStruct, OmniPayloadStruct, to_dict, to_struct
from vllm_omni.model_executor.models.cosyvoice3.tokenizer import get_qwen_tokenizer
from vllm_omni.model_executor.models.cosyvoice3.utils import (
concat_text_with_prompt_ids,
extract_speech_feat,
extract_speech_token,
extract_spk_embedding,
extract_spk_embedding_trt,
extract_text_token,
mel_spectrogram,
unpad_prompt_conditioning,
)
from vllm_omni.model_executor.models.output_templates import OmniOutput
from vllm_omni.transformers_utils.configs.cosyvoice3 import CosyVoice3Config
@@ -45,6 +54,23 @@ from vllm_omni.utils.speaker_cache import get_speaker_cache
logger = init_logger(__name__)
# Process-wide cache of per-model mm-processor runtime components (tokenizer,
# feat_extractor, campplus session/engine). The mm processor is re-created per
# request (mm_processor_cache_gb: 0), so this avoids rebuilding them every time.
_RUNTIME_COMPONENTS_CACHE: dict[str, dict] = {}
def _cosyvoice3_trt_enabled() -> bool:
"""COSYVOICE3_TRT env toggle (default on) for the optional TensorRT paths.
Gates both the talker speaker-embedding (campplus) engine and the code2wav
flow-decoder estimator engine. Env-var toggle (cf. mimo_audio's
``MIMO_AUDIO_TOKENIZER_CUDA_GRAPH``) because these run outside the stage
worker, so deploy-yaml ``hf_overrides`` / per-stage ``env`` do not reach
them — export ``COSYVOICE3_TRT=0`` in the launching shell to disable.
"""
return os.environ.get("COSYVOICE3_TRT", "1") not in ("0", "false", "False", "")
class CosyVoice3MultiModalProcessingInfo(BaseProcessingInfo):
def get_hf_config(self):
@@ -73,39 +99,136 @@ class CosyVoice3MultiModalProcessor(BaseMultiModalProcessor[CosyVoice3MultiModal
if cached_model_dir == model_dir:
return
# If model_dir is an HF repo ID (not a local path), resolve to cache
if not os.path.isdir(model_dir):
from huggingface_hub import snapshot_download
# The mm processor is re-created per request (deploy config sets
# ``mm_processor_cache_gb: 0``), so the instance-level guard above never
# hits across requests. Without a process-wide cache, every request
# would re-run ``snapshot_download``, rebuild the Qwen tokenizer and
# create a fresh ONNX campplus session — ~hundreds of ms of pure
# overhead on the TTFP critical path. Build the heavy components once
# per process, keyed by model_dir, and reuse them.
comps = _RUNTIME_COMPONENTS_CACHE.get(model_dir)
if comps is None:
comps = self._build_runtime_components(model_dir, config)
_RUNTIME_COMPONENTS_CACHE[model_dir] = comps
self.tokenizer = comps["tokenizer"]
self.feat_extractor = comps["feat_extractor"]
self.campplus_session = comps["campplus_session"]
self.campplus_trt = comps["campplus_trt"]
self._cached_model_dir = model_dir
self._speaker_cache = get_speaker_cache()
def _build_runtime_components(self, model_dir: str, config: CosyVoice3Config) -> dict:
"""Build the per-model runtime components once (cached process-wide)."""
# If model_dir is an HF repo ID (not a local path), resolve to cache.
if not os.path.isdir(model_dir):
model_dir = snapshot_download(model_dir)
import onnxruntime
from vllm_omni.model_executor.models.cosyvoice3.tokenizer import get_qwen_tokenizer
from vllm_omni.model_executor.models.cosyvoice3.utils import mel_spectrogram
option = onnxruntime.SessionOptions()
option.graph_optimization_level = onnxruntime.GraphOptimizationLevel.ORT_ENABLE_ALL
option.intra_op_num_threads = 1
self.tokenizer = get_qwen_tokenizer(
tokenizer = get_qwen_tokenizer(
token_path=os.path.join(model_dir, config.qwen_pretrain_path),
skip_special_tokens=config.skip_special_tokens,
version=config.version,
)
self.speech_tokenizer = onnxruntime.InferenceSession(
os.path.join(model_dir, config.speech_tokenizer_path),
sess_options=option,
providers=["CUDAExecutionProvider" if torch.cuda.is_available() else "CPUExecutionProvider"],
)
self.feat_extractor = partial(mel_spectrogram, **getattr(config, "feat_extractor", {}))
self.campplus_session = onnxruntime.InferenceSession(
os.path.join(model_dir, config.campplus_onxx_path),
sess_options=option,
providers=["CPUExecutionProvider"],
)
self._cached_model_dir = model_dir
self._speaker_cache = get_speaker_cache()
feat_extractor = partial(mel_spectrogram, **getattr(config, "feat_extractor", {}))
campplus_onnx_path = os.path.join(model_dir, config.campplus_onxx_path)
# TensorRT speaker-embedding path (default on); a prebuilt TRT engine
# runs campplus on GPU. The engine itself is cached process-wide by
# ``get_campplus_trt``.
campplus_trt = None
if self._speaker_embedding_trt_enabled() and torch.cuda.is_available():
try:
from vllm_omni.model_executor.models.cosyvoice3.speaker_embedding_trt import (
get_campplus_trt,
)
campplus_trt = get_campplus_trt(campplus_onnx_path, device="cuda")
logger.info("CosyVoice3: using TensorRT campplus speaker embedding")
except Exception as exc: # pragma: no cover - defensive fallback
logger.warning(
"CosyVoice3: TensorRT campplus build failed (%s); falling back to ONNX-Runtime speaker embedding",
exc,
)
campplus_trt = None
# Only build the CPU ONNX campplus session when TRT is unavailable —
# otherwise it is never used and creating it (ORT_ENABLE_ALL graph
# optimization) costs ~hundreds of ms.
campplus_session = None
if campplus_trt is None:
option = onnxruntime.SessionOptions()
option.graph_optimization_level = onnxruntime.GraphOptimizationLevel.ORT_ENABLE_ALL
option.intra_op_num_threads = 1
campplus_session = onnxruntime.InferenceSession(
campplus_onnx_path,
sess_options=option,
providers=["CPUExecutionProvider"],
)
return {
"tokenizer": tokenizer,
"feat_extractor": feat_extractor,
"campplus_session": campplus_session,
"campplus_trt": campplus_trt,
}
@staticmethod
def _speaker_embedding_trt_enabled() -> bool:
"""Whether to use the TensorRT campplus speaker-embedding path (default on)."""
return _cosyvoice3_trt_enabled()
# Class-level cached s3tokenizer model — loaded once per process on first
# call to ``_extract_speech_token_via_s3`` and shared across all
# processor instances.
_s3_model = None
@classmethod
def _ensure_s3_model(cls):
if cls._s3_model is not None:
return cls._s3_model
# s3tokenizer is imported lazily (kept off the module top level) so
# callers that don't use the CosyVoice3 talker need not install it.
try:
import s3tokenizer as _s3
except ImportError as e:
raise ImportError(
"CosyVoice3 speech-token extraction requires the 's3tokenizer' "
"package; install it with `pip install s3tokenizer`."
) from e
model = _s3.load_model("speech_tokenizer_v3_25hz")
device = "cuda" if torch.cuda.is_available() else "cpu"
model = model.to(device).eval()
cls._s3_model = (model, _s3, device)
return cls._s3_model
def _extract_speech_token_via_s3(self, audio, return_device):
"""Drop-in replacement for ``extract_speech_token`` that uses the
S3Tokenizer PyTorch model on GPU. Returns the same
``(speech_token[1, T], speech_token_len[1])`` int32 tensors as the
ONNX path so the rest of ``_call_hf_processor`` is unchanged.
"""
model, _s3, dev = self._ensure_s3_model()
# audio is a (waveform_ndarray, sr) tuple; resample to 16 kHz mono float32.
wav, sr = audio
wav = np.asarray(wav, dtype=np.float32)
if wav.ndim == 2:
wav = wav.mean(axis=1)
if int(sr) != 16000:
g = gcd(int(sr), 16000)
wav = resample_poly(wav, 16000 // g, int(sr) // g).astype(np.float32)
audio_t = torch.from_numpy(wav)
mel = _s3.log_mel_spectrogram(audio_t)
mels_p, mels_lens = _s3.padding([mel])
with torch.inference_mode():
codes, codes_lens = model.quantize(mels_p.to(dev), mels_lens.to(dev))
n = int(codes_lens[0].item())
speech_token = codes[:1, :n].to(dtype=torch.int32, device=return_device)
speech_token_len = torch.tensor([n], dtype=torch.int32, device=return_device)
return speech_token, speech_token_len
def _call_hf_processor(
self,
@@ -185,7 +308,11 @@ class CosyVoice3MultiModalProcessor(BaseMultiModalProcessor[CosyVoice3MultiModal
)
return ft
speech_token, speech_token_len = extract_speech_token(audio, self.speech_tokenizer, device)
# Speech-token extraction via the S3Tokenizer PyTorch model on GPU
# (~30x faster than the bundled ``speech_tokenizer_v3.onnx`` CPU ONNX
# path in this venv).
speech_token, speech_token_len = self._extract_speech_token_via_s3(audio, device)
speech_feat, speech_feat_len = extract_speech_feat(audio, self.feat_extractor, device)
if config.sample_rate == 24000:
@@ -193,7 +320,10 @@ class CosyVoice3MultiModalProcessor(BaseMultiModalProcessor[CosyVoice3MultiModal
speech_feat, speech_feat_len[:] = speech_feat[:, : 2 * token_len], 2 * token_len
speech_token, speech_token_len[:] = speech_token[:, :token_len], token_len
embedding = extract_spk_embedding(audio, self.campplus_session, device)
if self.campplus_trt is not None:
embedding = extract_spk_embedding_trt(audio, self.campplus_trt, device)
else:
embedding = extract_spk_embedding(audio, self.campplus_session, device)
# Cache the extracted artifacts for named speakers
if cache_key is not None:
@@ -318,8 +448,6 @@ class CosyVoice3Model(
self.model_stage = vllm_config.model_config.model_stage
model_dir = vllm_config.model_config.model
if not os.path.isdir(model_dir):
from huggingface_hub import snapshot_download
model_dir = snapshot_download(model_dir)
self.model_dir = model_dir
self.model = None
@@ -377,8 +505,6 @@ class CosyVoice3Model(
the pretrained model directory. The cache config is inherited from the parent
to enable PagedAttention with the same memory configuration.
"""
from transformers import Qwen2Config
qwen_config_path = os.path.join(self.model_dir, self.config.llm["llm"]["pretrain_path"])
qwen_hf_config = Qwen2Config.from_pretrained(qwen_config_path)
@@ -469,26 +595,32 @@ class CosyVoice3Model(
top_k: int,
generator: torch.Generator | None,
) -> int:
"""Vectorized nucleus + top-k sampling.
Distribution-equivalent to the reference iterative implementation: the
keep-set is identical (token i is kept iff
``cumsum(sorted_probs)[i] - sorted_probs[i] < top_p`` AND ``i < top_k``)
and the renormalized sampling distribution matches, but the exact token
drawn for a given seed is NOT guaranteed to match. The reference draws
via ``multinomial`` over the stacked kept subset while this draws over
the full sorted vector (zeroed outside the keep-set), so the generator
advances over different-sized inputs and may yield a different sample.
The win: no per-token ``.item()`` D2H syncs from the Python loop —
those dominated the sampler CPU time in profiling.
"""
probs = weighted_scores.softmax(dim=0)
sorted_prob, sorted_idx = probs.sort(descending=True, stable=True)
kept_probs: list[torch.Tensor] = []
kept_indices: list[torch.Tensor] = []
cum_prob = 0.0
max_keep = len(sorted_idx) if top_k <= 0 else min(int(top_k), len(sorted_idx))
for i in range(len(sorted_idx)):
if cum_prob < top_p and len(kept_probs) < max_keep:
cum_prob += float(sorted_prob[i].item())
kept_probs.append(sorted_prob[i])
kept_indices.append(sorted_idx[i])
else:
break
if not kept_probs:
return int(sorted_idx[0].item())
sample_probs = torch.stack(kept_probs)
sample_idx = cls._multinomial_sample(sample_probs, generator=generator)
return int(torch.stack(kept_indices)[int(sample_idx.item())].item())
cum_before = sorted_prob.cumsum(dim=0) - sorted_prob
mask = cum_before < top_p
if top_k > 0:
n = sorted_prob.shape[0]
mask = mask & (torch.arange(n, device=mask.device) < min(int(top_k), n))
weights = sorted_prob * mask.to(sorted_prob.dtype)
# First token always passes (cum_before[0] = 0 < top_p for any top_p > 0),
# so ``weights`` is guaranteed to have at least one nonzero entry. The
# final ``.item()`` is the ONLY D2H sync per call.
sample_idx = torch.multinomial(weights, 1, replacement=True, generator=generator)
return int(sorted_idx[sample_idx].item())
@classmethod
def _ras_sample_one(
@@ -627,11 +759,21 @@ class CosyVoice3Model(
else:
raise RuntimeError(f"compute_logits is only valid for {self.model_stage}.")
def embed_multimodal(self, **kwargs: object) -> torch.Tensor:
def embed_multimodal(self, **kwargs: object):
if self.model_stage == "cosyvoice3_talker":
speech_token = kwargs["speech_token"]
speech_token_emb = self.model.speech_embedding(speech_token)
return speech_token_emb
# vLLM's _execute_mm_encoder batches ALL multimodal items scheduled
# in one engine step into a single call, expecting one embedding
# tensor per item back. When >=2 requests prefill in the same step
# (likely once mm preprocessing is fast, e.g. TensorRT speaker
# embedding), speech_token arrives as a list of per-item tensors
# (variable length), so embed it per item and return a list of
# [T_i, emb] tensors. The single-item path keeps returning a
# [1, T, emb] tensor (the caller's extend() iterates dim 0).
if isinstance(speech_token, (list, tuple)):
emb_dim = self.model.speech_embedding.weight.shape[1]
return [self.model.speech_embedding(t).reshape(-1, emb_dim) for t in speech_token]
return self.model.speech_embedding(speech_token)
else:
raise RuntimeError(f"embed_multimodal is only valid for {self.model_stage}.")
@@ -720,6 +862,121 @@ class CosyVoice3Model(
else:
raise RuntimeError(f"embed_input_ids is not valid for {self.model_stage}.")
@staticmethod
def _split_prompt_conditioning(speech_token, speech_feat, embedding, speech_token_len):
"""Split collated prompt conditioning into per-request lists.
Returns ``(speech_token_list, speech_feat_list, embedding_list,
speech_token_len_list)``, one rank-correct tensor per request:
``speech_token`` ``[1, T]`` (possibly right-padded), ``speech_feat``
``[1, 2T, F]``, ``embedding`` ``[1, D]``, ``speech_token_len`` ``[1, 1]``.
This runs inside the talker ``forward`` which may be CUDA-graph
captured, so it must NOT trigger any host<->device sync (no ``.item()``
/ ``.tolist()`` / Python-int slicing by tensor value). Splitting is pure
on-device indexing; right-padding is dropped later in the (eager)
code2wav stage using the per-request ``speech_token_len``. Robust to
inputs arriving as padded ``[B, ...]`` batch tensors or per-request
lists.
"""
def _rows(x, want_dim):
if isinstance(x, (list, tuple)):
items = list(x)
elif isinstance(x, torch.Tensor):
# ``x.shape[0]`` is a static Python int — no device sync.
items = [x[i] for i in range(x.shape[0])]
else:
return None
out = []
for t in items:
if isinstance(t, torch.Tensor):
while t.dim() < want_dim:
t = t.unsqueeze(0)
if t.shape[0] != 1:
t = t[:1]
t = t.contiguous()
out.append(t)
return out
st_out = _rows(speech_token, 2)
sf_out = _rows(speech_feat, 3)
emb_out = _rows(embedding, 2)
stl_out = _rows(speech_token_len, 2)
return st_out, sf_out, emb_out, stl_out
def _resolve_flow_estimator_onnx(self) -> str | None:
"""Locate the flow-decoder estimator ONNX for the TensorRT engine.
Prefers the fp16 (strongly-typed) ONNX → fp16 engine. Order: env
``COSYVOICE3_ESTIMATOR_ONNX`` → ``<model_dir>/<fp16 name>`` → fetched
from ``flow_estimator_onnx_repo`` → bundled fp32 ONNX (fp32+TF32). Each
is checked for existence; returns ``None`` if nothing is found.
"""
env_path = os.environ.get("COSYVOICE3_ESTIMATOR_ONNX")
if env_path and os.path.exists(env_path):
return env_path
fp16_name = getattr(self.config, "flow_estimator_onnx_path", "flow.decoder.estimator.autocast_fp16.onnx")
local_fp16 = os.path.join(self.model_dir, fp16_name)
if os.path.exists(local_fp16):
return local_fp16
repo = getattr(self.config, "flow_estimator_onnx_repo", None)
if repo:
try:
fetched_dir = snapshot_download(repo, allow_patterns=[fp16_name])
fetched = os.path.join(fetched_dir, fp16_name)
if os.path.exists(fetched):
return fetched
except Exception as exc: # pragma: no cover - network/repo issues
logger.warning("CosyVoice3 code2wav: could not fetch fp16 estimator ONNX from %s (%s)", repo, exc)
fp32_name = getattr(self.config, "flow_estimator_onnx_path_fp32", "flow.decoder.estimator.fp32.onnx")
local_fp32 = os.path.join(self.model_dir, fp32_name)
if os.path.exists(local_fp32):
logger.info("CosyVoice3 code2wav: fp16 estimator ONNX unavailable, falling back to fp32 (%s)", local_fp32)
return local_fp32
return None
def _maybe_enable_code2wav_trt(self) -> None:
"""Swap the flow-decoder estimator to a TensorRT engine once (lazy).
Runs on the first code2wav step — after weights are loaded — so the
torch estimator is fully built first and then dropped. No-op unless
``COSYVOICE3_TRT`` is on (default), CUDA is available, and the estimator
ONNX ships with the model. Falls back to the torch estimator on any
failure. The upstream ``CausalConditionalCFM.forward_estimator`` detects
the non-``nn.Module`` estimator and drives the TRT engine.
"""
if getattr(self, "_code2wav_trt_done", False):
return
self._code2wav_trt_done = True
if not (_cosyvoice3_trt_enabled() and torch.cuda.is_available()):
return
onnx_path = self._resolve_flow_estimator_onnx()
if onnx_path is None:
logger.warning("CosyVoice3 code2wav: no flow-estimator ONNX available; keeping torch estimator")
return
try:
from vllm_omni.model_executor.models.cosyvoice3.flow_estimator_trt import (
build_flow_estimator_trt,
)
wrapper = build_flow_estimator_trt(onnx_path, device="cuda")
# ``estimator`` is a registered nn.Module submodule; delete it first
# (frees the torch estimator weights) so the TRT wrapper can be set
# as a plain attribute — nn.Module.__setattr__ rejects non-Modules.
decoder = self.code2wav.flow_model.decoder
del decoder.estimator
decoder.estimator = wrapper
logger.info("CosyVoice3: using TensorRT flow-decoder estimator (code2wav)")
except Exception as exc: # pragma: no cover - defensive fallback
logger.warning(
"CosyVoice3 code2wav: TensorRT estimator build failed (%s); keeping torch estimator",
exc,
)
def forward(
self,
input_ids: torch.Tensor,
@@ -741,18 +998,43 @@ class CosyVoice3Model(
if "speech_token" in kwargs:
# Prompt conditioning tensors for code2wav: live under
# ``embed.*`` per OmniPayloadStruct schema.
#
# vLLM hands these mm fields to forward() as collated, padded
# batch tensors (speech_token [B, maxT], speech_feat
# [B, 2*maxT, F], embedding [B, D]). Emitting them raw makes the
# downstream per-request payload split fragile at batch>1: it
# intermittently de-batches speech_token to 1-D and leaks the
# whole [B, D] embedding to every request, which corrupts voice
# conditioning and crashes code2wav (`prompt_token.shape[1]`).
# Instead, split into an explicit per-request list of unpadded,
# correctly-ranked tensors so ``to_payload_element`` splits them
# deterministically by request index (list[idx]).
speech_token_list, speech_feat_list, embedding_list, speech_token_len_list = (
self._split_prompt_conditioning(
kwargs.get("speech_token"),
kwargs.get("speech_feat"),
kwargs.get("embedding"),
kwargs.get("speech_token_len"),
)
)
multimodal_outputs = to_dict(
OmniPayloadStruct(
embed=EmbeddingsStruct(
speech_token=kwargs.get("speech_token"),
speech_feat=kwargs.get("speech_feat"),
embedding=kwargs.get("embedding"),
speech_token=speech_token_list,
speech_feat=speech_feat_list,
speech_token_len=speech_token_len_list,
embedding=embedding_list,
),
)
)
return OmniOutput(text_hidden_states=hidden_states, multimodal_outputs=multimodal_outputs)
elif self.model_stage == "cosyvoice3_code2wav":
# Lazily swap the flow-decoder estimator to a TensorRT engine on the
# first code2wav step (after weights are loaded), gated by the same
# COSYVOICE3_TRT env toggle as the talker speaker embedding.
self._maybe_enable_code2wav_trt()
runtime_info = kwargs.get("model_intermediate_buffer")
if runtime_info is None:
runtime_info = kwargs.get("runtime_additional_information", [])
@@ -784,6 +1066,11 @@ class CosyVoice3Model(
speech_token = embed.speech_token if embed else None
speech_feat = embed.speech_feat if embed else None
embedding = embed.embedding if embed else None
# Drop any right-padding carried from batched talker emission.
if speech_token is not None and speech_feat is not None:
speech_token, speech_feat = unpad_prompt_conditioning(
speech_token, speech_feat, embed.speech_token_len if embed else None
)
if speech_token is None or speech_feat is None or embedding is None:
if stream_finished and req_id is not None and hasattr(self, "_stream_vocoder_cache_by_req"):
with self._stream_audio_cache_lock:
@@ -0,0 +1,154 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""TensorRT engine for the CosyVoice3 flow-decoder (CFM) DiT estimator.
The estimator is the per-step network the conditional flow-matching ODE solver
calls during code2wav (token -> mel). It dominates code2wav latency; the
upstream ``CausalConditionalCFM.forward_estimator`` already supports running it
through a TensorRT engine (it switches on ``self.estimator`` not being an
``nn.Module`` and drives it via ``acquire_estimator`` / ``execute_async_v3``).
This module builds that engine from the bundled ``flow.decoder.estimator*.onnx``
and wraps it so it can be dropped in for the torch estimator.
The estimator engine has 6 inputs ``x, mask, mu, t, spks, cond`` and one output.
``x/mask/mu/cond`` carry a dynamic time dim; ``t``/``spks`` are fixed, so only
the former need an optimization profile (TRT infers the latter from the ONNX).
Shapes mirror the CosyVoice runtime.
Precision: TensorRT >= 11 dropped the weakly-typed FP16/INT8 builder flags, so
fp16 only comes from a STRONGLY_TYPED network built from an fp16 ONNX
(``*autocast_fp16*``, fp16 I/O). An fp32 ONNX is built fp32 + the TF32 matmul
flag. ``EXPLICIT_BATCH`` is implicit (no flag) and ``ITensor.dtype`` is
read-only, so neither is set here.
"""
from __future__ import annotations
import os
import queue
import torch
from vllm.logger import init_logger
from vllm_omni.model_executor.models.cosyvoice3.speaker_embedding_trt import (
_resolve_plan_path,
_trt_logger,
)
logger = init_logger(__name__)
# Optimization-profile shapes for the dynamic-length inputs (CFG batch dim = 2,
# 80 mel channels, time dim min/opt/max). Matches CosyVoice's token2wav.
_DYNAMIC_INPUTS = ("x", "mask", "mu", "cond")
_MIN_SHAPES = ((2, 80, 4), (2, 1, 4), (2, 80, 4), (2, 80, 4))
_OPT_SHAPES = ((2, 80, 500), (2, 1, 500), (2, 80, 500), (2, 80, 500))
_MAX_SHAPES = ((2, 80, 3000), (2, 1, 3000), (2, 80, 3000), (2, 80, 3000))
def _is_fp16_onnx(onnx_path: str) -> bool:
"""Heuristic: the project's fp16 estimator ONNX is exported strongly-typed
and named ``*autocast_fp16*`` / ``*fp16*`` (vs ``*fp32*``)."""
name = os.path.basename(onnx_path).lower()
return "fp16" in name or "autocast" in name
def _convert_onnx_to_trt(onnx_path: str, plan_path: str, strongly_typed: bool) -> None:
import tensorrt as trt
logger.info(
"Building flow-estimator TensorRT engine from %s (%s) ...",
onnx_path,
"strongly-typed/fp16" if strongly_typed else "fp32+TF32",
)
trt_logger = _trt_logger()
builder = trt.Builder(trt_logger)
# STRONGLY_TYPED takes precision from the ONNX graph (fp16 engine from an
# fp16 ONNX) — this is the only way to get fp16 in TRT>=11, which dropped
# the weakly-typed FP16 BuilderFlag. Otherwise EXPLICIT_BATCH is implicit,
# so create the network with no flags.
if strongly_typed:
network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.STRONGLY_TYPED))
else:
network = builder.create_network(0)
parser = trt.OnnxParser(network, trt_logger)
with open(onnx_path, "rb") as f:
if not parser.parse(f.read()):
errs = "; ".join(str(parser.get_error(i)) for i in range(parser.num_errors))
raise ValueError(f"Failed to parse {onnx_path}: {errs}")
config = builder.create_builder_config()
config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, 1 << 32) # 4 GiB
if not strongly_typed:
# fp32 ONNX: enable the best available reduced-precision matmul flag
# (FP16 on older TRT, else TF32 on Ampere+/Hopper). For a strongly-typed
# network the precision is fixed by the graph, so no flag is set.
for _flag_name in ("FP16", "TF32"):
_flag = getattr(trt.BuilderFlag, _flag_name, None)
if _flag is not None:
config.set_flag(_flag)
break
profile = builder.create_optimization_profile()
for name, mn, op, mx in zip(_DYNAMIC_INPUTS, _MIN_SHAPES, _OPT_SHAPES, _MAX_SHAPES):
profile.set_shape(name, mn, op, mx)
config.add_optimization_profile(profile)
engine_bytes = builder.build_serialized_network(network, config)
if engine_bytes is None:
raise RuntimeError(f"TensorRT failed to build flow-estimator engine from {onnx_path}")
tmp = plan_path + ".tmp"
with open(tmp, "wb") as f:
f.write(engine_bytes)
os.replace(tmp, plan_path)
logger.info("Wrote flow-estimator TensorRT engine to %s", plan_path)
class TrtContextWrapper:
"""Pool of TensorRT execution contexts for the flow estimator.
Exposes the ``acquire_estimator`` / ``release_estimator`` contract that
``CausalConditionalCFM.forward_estimator`` expects.
"""
def __init__(
self, engine, device: str | torch.device, io_dtype: torch.dtype = torch.float32, trt_concurrent: int = 1
):
self.trt_engine = engine
# Engine I/O dtype (fp16 for a strongly-typed fp16 engine). The flow runs
# in fp32, so forward_estimator casts to/from this at the boundary.
self.io_dtype = io_dtype
self._pool: queue.Queue = queue.Queue(maxsize=trt_concurrent)
for _ in range(trt_concurrent):
ctx = engine.create_execution_context()
assert ctx is not None, "failed to create TRT execution context (out of memory?)"
stream = torch.cuda.stream(torch.cuda.Stream(torch.device(device)))
self._pool.put([ctx, stream])
def acquire_estimator(self):
return self._pool.get(), self.trt_engine
def release_estimator(self, context, stream):
self._pool.put([context, stream])
def build_flow_estimator_trt(onnx_path: str, device: str | torch.device) -> TrtContextWrapper:
"""Build/load the flow-estimator TRT engine and return a context-pool wrapper.
An fp16 ONNX (``*autocast_fp16*``) is built as a strongly-typed network (the
only way to get fp16 in TRT>=11); an fp32 ONNX is built fp32 + TF32.
"""
import tensorrt as trt
strongly_typed = _is_fp16_onnx(onnx_path)
plan_path = _resolve_plan_path(onnx_path, prefix="flow_estimator")
if not os.path.exists(plan_path) or os.path.getsize(plan_path) == 0:
_convert_onnx_to_trt(onnx_path, plan_path, strongly_typed=strongly_typed)
runtime = trt.Runtime(_trt_logger())
with open(plan_path, "rb") as f:
engine = runtime.deserialize_cuda_engine(f.read())
if engine is None:
raise RuntimeError(f"Failed to deserialize flow-estimator TensorRT engine {plan_path}")
logger.info("Loaded flow-estimator TensorRT engine (%s)", plan_path)
io_dtype = torch.float16 if strongly_typed else torch.float32
return TrtContextWrapper(engine, device=device, io_dtype=io_dtype)
@@ -0,0 +1,157 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""TensorRT speaker-embedding (campplus) extractor for CosyVoice3.
Drop-in accelerator for the ONNX-Runtime campplus session used in the
multimodal processor. ``campplus.onnx`` maps an fbank feature
``[B, T, 80]`` to a 192-d speaker embedding ``[B, 192]``; on this stack the
ONNX path only has a CPU execution provider, so it dominates per-request
prompt-processing latency. Building a TensorRT engine once and running it on
GPU removes that bottleneck.
The engine is built lazily from ``campplus.onnx`` on first use and cached as
a ``.plan`` file (engines are device/TRT-version specific, so the cache key
includes both). Set ``COSYVOICE3_TRT_CACHE`` to override the cache dir.
Written against TensorRT >= 10/11: ``EXPLICIT_BATCH`` is the implicit default
(create the network with no flags) and ``ITensor.dtype`` is read-only (I/O
dtypes come from the ONNX graph), so neither is set here.
"""
from __future__ import annotations
import hashlib
import os
import threading
import torch
from vllm.logger import init_logger
logger = init_logger(__name__)
# campplus fbank sequence length bounds for the optimization profile.
_MIN_T = 4
_OPT_T = 500
_MAX_T = 3000
_EMBED_DIM = 192
def _trt_logger():
import tensorrt as trt
return trt.Logger(trt.Logger.WARNING)
def _convert_onnx_to_trt(onnx_path: str, plan_path: str) -> None:
import tensorrt as trt
logger.info("Building campplus TensorRT engine from %s ...", onnx_path)
trt_logger = _trt_logger()
builder = trt.Builder(trt_logger)
# EXPLICIT_BATCH is implicit in TRT>=10; create the network with no flags.
network = builder.create_network(0)
parser = trt.OnnxParser(network, trt_logger)
with open(onnx_path, "rb") as f:
if not parser.parse(f.read()):
errs = "; ".join(str(parser.get_error(i)) for i in range(parser.num_errors))
raise ValueError(f"Failed to parse {onnx_path}: {errs}")
config = builder.create_builder_config()
config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, 1 << 31) # 2 GiB
input_name = network.get_input(0).name
profile = builder.create_optimization_profile()
profile.set_shape(
input_name,
(1, _MIN_T, 80),
(1, _OPT_T, 80),
(1, _MAX_T, 80),
)
config.add_optimization_profile(profile)
engine_bytes = builder.build_serialized_network(network, config)
if engine_bytes is None:
raise RuntimeError(f"TensorRT failed to build campplus engine from {onnx_path}")
tmp = plan_path + ".tmp"
with open(tmp, "wb") as f:
f.write(engine_bytes)
os.replace(tmp, plan_path)
logger.info("Wrote campplus TensorRT engine to %s", plan_path)
def _resolve_plan_path(onnx_path: str, prefix: str = "campplus") -> str:
cache_dir = os.environ.get("COSYVOICE3_TRT_CACHE") or os.path.join(
os.path.expanduser("~"), ".cache", "vllm_omni", "cosyvoice3_trt"
)
os.makedirs(cache_dir, exist_ok=True)
try:
# No-arg form targets the current device (avoids the banned
# torch.cuda.current_device per ruff TID251).
dev_name = torch.cuda.get_device_name()
except Exception:
dev_name = "unknown"
import tensorrt as trt
st = os.stat(onnx_path)
key = f"{os.path.abspath(onnx_path)}|{st.st_size}|{int(st.st_mtime)}|{dev_name}|trt{trt.__version__}"
digest = hashlib.sha1(key.encode()).hexdigest()[:16]
return os.path.join(cache_dir, f"{prefix}_{digest}.plan")
class CampplusTRT:
"""Lazily-built TensorRT campplus speaker-embedding extractor."""
def __init__(self, onnx_path: str, device: str | torch.device):
import tensorrt as trt
self.device = torch.device(device)
plan_path = _resolve_plan_path(onnx_path)
if not os.path.exists(plan_path) or os.path.getsize(plan_path) == 0:
_convert_onnx_to_trt(onnx_path, plan_path)
runtime = trt.Runtime(_trt_logger())
with open(plan_path, "rb") as f:
self.engine = runtime.deserialize_cuda_engine(f.read())
if self.engine is None:
raise RuntimeError(f"Failed to deserialize campplus TensorRT engine {plan_path}")
self.context = self.engine.create_execution_context()
self.input_name = self.engine.get_tensor_name(0)
self.output_name = self.engine.get_tensor_name(1)
# TRT execution contexts are not safe for concurrent enqueue; serialize.
self._lock = threading.Lock()
logger.info("Loaded campplus TensorRT engine (%s)", plan_path)
@torch.inference_mode()
def __call__(self, feat: torch.Tensor) -> torch.Tensor:
"""feat: ``[T, 80]`` fbank features. Returns ``[1, 192]`` embedding."""
x = feat.unsqueeze(0).to(self.device, dtype=torch.float32).contiguous()
out = torch.empty((x.shape[0], _EMBED_DIM), device=self.device, dtype=torch.float32)
stream = torch.cuda.current_stream(self.device)
with self._lock:
self.context.set_input_shape(self.input_name, tuple(x.shape))
self.context.set_tensor_address(self.input_name, x.data_ptr())
self.context.set_tensor_address(self.output_name, out.data_ptr())
ok = self.context.execute_async_v3(stream.cuda_stream)
if not ok:
raise RuntimeError("campplus TensorRT execute_async_v3 failed")
stream.synchronize()
return out
# Process-wide cache: the mm processor is re-created per request (the deploy
# config disables the mm-processor object cache), so building a fresh
# CampplusTRT each time would re-deserialize the ~33 MB engine and allocate a
# new execution context on every request — inflating TTFP. Cache by
# (engine path, device) and reuse; the context serializes concurrent enqueues
# via its own lock, so a single shared instance is safe across requests.
_CAMPPLUS_CACHE: dict[tuple[str, str], CampplusTRT] = {}
def get_campplus_trt(onnx_path: str, device: str | torch.device) -> CampplusTRT:
"""Return a process-wide cached :class:`CampplusTRT` (engine + context)."""
key = (os.path.abspath(onnx_path), str(device))
inst = _CAMPPLUS_CACHE.get(key)
if inst is None:
inst = CampplusTRT(onnx_path, device)
_CAMPPLUS_CACHE[key] = inst
return inst
@@ -215,6 +215,44 @@ def extract_spk_embedding(prompt_wav, campplus_session, device):
return embedding
def unpad_prompt_conditioning(speech_token, speech_feat, speech_token_len):
"""Drop right-padding from per-request prompt conditioning.
The talker emits ``speech_token`` ``[1, T]`` possibly right-padded to the
batch max, plus the true ``speech_token_len``; ``speech_feat`` is at the 2:1
mel:token ratio (``[1, 2T, F]``). This trims both to the real length. Called
in the (eager) code2wav stage where a host read of the length is allowed.
Returns ``(speech_token, speech_feat)`` unchanged when length is unavailable.
"""
if not isinstance(speech_token, torch.Tensor) or speech_token_len is None:
return speech_token, speech_feat
try:
token_len = int(torch.as_tensor(speech_token_len).reshape(-1)[0].item())
except (RuntimeError, ValueError, IndexError):
return speech_token, speech_feat
if token_len <= 0 or speech_token.dim() < 2:
return speech_token, speech_feat
token_len = min(token_len, int(speech_token.shape[1]))
speech_token = speech_token[:, :token_len]
if isinstance(speech_feat, torch.Tensor) and speech_feat.dim() >= 2:
speech_feat = speech_feat[:, : 2 * token_len]
return speech_token, speech_feat
def extract_spk_embedding_trt(prompt_wav, campplus_trt, device):
"""TensorRT counterpart of ``extract_spk_embedding``.
Identical fbank front-end; the campplus forward runs on a prebuilt
TensorRT engine (GPU) instead of the CPU ONNX-Runtime session. Returns the
same ``[1, 192]`` embedding tensor on ``device``.
"""
speech = load_wav(prompt_wav, 16000)
feat = kaldi.fbank(speech, num_mel_bins=80, dither=0, sample_frequency=16000)
feat = feat - feat.mean(dim=0, keepdim=True)
embedding = campplus_trt(feat)
return embedding.to(device)
def extract_text_token(text, tokenizer, allowed_special):
text_token = tokenizer.encode(text, allowed_special=allowed_special)
text_token = torch.tensor([text_token], dtype=torch.int32)
@@ -162,6 +162,54 @@ def _build_delay_pattern(codes: torch.Tensor) -> torch.Tensor:
_ENCODER_CACHE: Any | None = None
_K2_OMNIVOICE_REPO = "k2-fsa/OmniVoice"
_K2_OMNIVOICE_SUBDIR = "audio_tokenizer"
_AUDIO_TOKENIZER_PATH_ENVS = (
"HIGGS_AUDIO_TOKENIZER_PATH",
"HIGGS_AUDIO_V2_TOKENIZER_PATH",
)
def _normalize_audio_tokenizer_dir(path: str) -> str | None:
if not path:
return None
expanded = os.path.abspath(os.path.expanduser(path))
if os.path.isfile(os.path.join(expanded, "config.json")):
return expanded
nested = os.path.join(expanded, _K2_OMNIVOICE_SUBDIR)
if os.path.isfile(os.path.join(nested, "config.json")):
return nested
return None
def _resolve_audio_tokenizer_dir() -> str | None:
"""Resolve the Higgs codec encoder dir without requiring online HF access.
Voice cloning runs in the API server process. Production H20 jobs are often
offline, so prefer explicit local directories and already-populated HF cache
before falling back to ``snapshot_download``.
"""
for env_name in _AUDIO_TOKENIZER_PATH_ENVS:
candidate = _normalize_audio_tokenizer_dir(os.getenv(env_name, ""))
if candidate is not None:
return candidate
from huggingface_hub import try_to_load_from_cache
cached_config = try_to_load_from_cache(
repo_id=_K2_OMNIVOICE_REPO,
filename=f"{_K2_OMNIVOICE_SUBDIR}/config.json",
)
if isinstance(cached_config, str) and os.path.isfile(cached_config):
return os.path.dirname(cached_config)
from huggingface_hub.constants import HF_HUB_CACHE
safe = _K2_OMNIVOICE_REPO.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 = _normalize_audio_tokenizer_dir(os.path.join(snapshots_dir, rev))
if candidate is not None:
return candidate
def _load_audio_tokenizer():
@@ -180,14 +228,17 @@ def _load_audio_tokenizer():
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)
audio_tokenizer_dir = _resolve_audio_tokenizer_dir()
if audio_tokenizer_dir is None:
from huggingface_hub import snapshot_download
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()
@@ -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 v3 (two-stage TTS)."""
from vllm_omni.model_executor.models.higgs_audio_v3.configuration_higgs_audio_v3 import (
HiggsAudioV3Config,
)
__all__ = ["HiggsAudioV3Config"]
@@ -0,0 +1,189 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Configuration class for higgs-audio v3 (HiggsMultimodalQwen3) in vllm-omni.
``HiggsAudioV3Config.from_pretrained(model_path)`` returns a config with
``tts_token_id``, ``text_token_id``, ``audio_continuation_id``, and
``eos_token_id`` already resolved from the checkpoint tokenizer. If the
tokenizer is unavailable or missing required specials, the load raises.
"""
from __future__ import annotations
import logging
import os
from typing import Any
import transformers
from transformers import AutoConfig, PretrainedConfig
__all__ = ["HiggsAudioV3Config"]
logger = logging.getLogger(__name__)
_QWEN3_ROPE_THETA = 1_000_000
_REQUIRED_SPECIALS = ("<|tts|>", "<|text|>", "<|audio|>")
def _build_text_config(raw: Any) -> PretrainedConfig:
if isinstance(raw, PretrainedConfig):
return raw
cfg = dict(raw or {})
model_type = cfg.get("model_type", "qwen3")
if model_type == "qwen3" and cfg.get("rope_theta") is None:
cfg["rope_theta"] = _QWEN3_ROPE_THETA
try:
cfg_cls = transformers.CONFIG_MAPPING[model_type]
except KeyError as exc:
raise ValueError(f"Unknown text backbone model_type {model_type!r}") from exc
return cfg_cls(**cfg)
def _resolve_model_dir(pretrained_model_name_or_path: str) -> str | None:
"""Resolve a model name/path to a local directory containing tokenizer files."""
if os.path.isdir(pretrained_model_name_or_path):
return pretrained_model_name_or_path
try:
from huggingface_hub import try_to_load_from_cache
cached = try_to_load_from_cache(repo_id=pretrained_model_name_or_path, filename="tokenizer_config.json")
if isinstance(cached, str) and os.path.isfile(cached):
return os.path.dirname(cached)
except Exception:
pass
try:
from huggingface_hub.constants import HF_HUB_CACHE
safe = pretrained_model_name_or_path.replace("/", "--")
snapshots = os.path.join(HF_HUB_CACHE, f"models--{safe}", "snapshots")
if os.path.isdir(snapshots):
for rev in os.listdir(snapshots):
candidate = os.path.join(snapshots, rev)
if os.path.isfile(os.path.join(candidate, "tokenizer_config.json")):
return candidate
except Exception:
pass
return None
class HiggsAudioV3Config(PretrainedConfig):
"""Typed config for higgs-audio v3 (HiggsMultimodalQwen3).
``from_pretrained()`` automatically resolves ``<|tts|>``, ``<|text|>``,
``<|audio|>`` and ``eos_token_id`` from the checkpoint tokenizer.
"""
model_type: str = "higgs_multimodal_qwen3"
is_composition = True
def __init__(
self,
audio_encoder_config: dict[str, Any] | None = None,
text_config: dict[str, Any] | PretrainedConfig | None = None,
audio_token_id: int = -100,
mel_per_sample: int = 8,
num_codebooks: int = 8,
codebook_size: int = 1026,
audio_stream_bos_id: int = 1024,
audio_stream_eos_id: int = 1025,
sample_rate: int = 24000,
frame_rate: int = 25,
tts_token_id: int | None = None,
text_token_id: int | None = None,
audio_continuation_id: int | None = None,
enable_flashinfer_api_unwrap: bool = True,
enable_mlp_cudagraph: bool = True,
**kwargs: Any,
) -> None:
# Legacy perf knob removed: Higgs v3 scheduler tokens now come from
# SamplerOutput.sampled_token_ids only.
kwargs.pop("enable_cpu_token_override", None)
self.audio_token_id = audio_token_id
self.mel_per_sample = mel_per_sample
if audio_encoder_config is None:
audio_encoder_config = {
"encoder_type": "discrete",
"num_codebooks": num_codebooks,
"vocab_size": codebook_size,
"tie_word_embeddings": True,
}
self.audio_encoder_config = audio_encoder_config
self.num_codebooks = int(audio_encoder_config.get("num_codebooks", num_codebooks))
if self.num_codebooks <= 0:
raise ValueError(f"num_codebooks must be > 0, got {self.num_codebooks}")
self.codebook_size = int(audio_encoder_config.get("vocab_size", codebook_size))
self.tie_modality_embeddings = bool(audio_encoder_config.get("tie_word_embeddings", True))
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.text_config = _build_text_config(text_config)
self.audio_hidden_size = int(audio_encoder_config.get("out_dim", self.text_config.hidden_size))
self.tts_token_id = tts_token_id
self.text_token_id = text_token_id
self.audio_continuation_id = audio_continuation_id
self.enable_flashinfer_api_unwrap = bool(enable_flashinfer_api_unwrap)
self.enable_mlp_cudagraph = bool(enable_mlp_cudagraph)
super().__init__(**kwargs)
@classmethod
def from_pretrained(cls, pretrained_model_name_or_path: str, **kwargs: Any) -> HiggsAudioV3Config:
"""Load config and resolve special token IDs from the checkpoint tokenizer.
Passes the original ``pretrained_model_name_or_path`` (local dir or
HF repo ID) directly to ``AutoTokenizer.from_pretrained()`` so it can
handle cache hits, downloads, and local paths uniformly. Raises if the
tokenizer is missing required specials.
"""
config = super().from_pretrained(pretrained_model_name_or_path, **kwargs)
config.resolve_special_tokens(pretrained_model_name_or_path)
return config
def get_text_config(self, decoder: bool = False) -> PretrainedConfig:
del decoder
return self.text_config
@property
def num_real_codes(self) -> int:
return self.audio_stream_bos_id
@property
def hidden_size(self) -> int:
return self.text_config.hidden_size
def resolve_special_tokens(self, model_path: str) -> None:
"""Resolve <|tts|>, <|text|>, <|audio|> and eos from the HF tokenizer.
Raises ``ValueError`` if any of the 3 required specials is missing
from the tokenizer's added vocabulary.
"""
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
vocab = dict(tokenizer.get_added_vocab())
missing = [t for t in _REQUIRED_SPECIALS if t not in vocab]
if missing:
raise ValueError(
f"Tokenizer at {model_path} is missing required Higgs TTS v3 "
f"special tokens: {missing}. Available added tokens: "
f"{sorted(vocab.keys())[:20]}"
)
self.tts_token_id = vocab["<|tts|>"]
self.text_token_id = vocab["<|text|>"]
self.audio_continuation_id = vocab["<|audio|>"]
if hasattr(tokenizer, "eos_token_id") and tokenizer.eos_token_id is not None:
self.eos_token_id = int(tokenizer.eos_token_id)
AutoConfig.register("higgs_multimodal_qwen3", HiggsAudioV3Config)
@@ -0,0 +1,525 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Stage 1 (codec decoder) for higgs-audio v3.
Reuses higgs-audio-v2's RVQ + DAC codec decoder but loads weights from the
v3 checkpoint's bundled codec (``tied.embedding.modality_embeddings.0.model.*``
prefix) rather than from a standalone tokenizer repo.
"""
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.higgs_audio_decoder import (
HiggsAudioRVQ,
build_boson_dac_decoder,
build_higgs_audio_acoustic_decoder,
load_higgs_audio_codec,
)
from vllm_omni.model_executor.models.higgs_audio_v3.configuration_higgs_audio_v3 import (
HiggsAudioV3Config,
)
from vllm_omni.model_executor.models.output_templates import OmniOutput
__all__ = [
"HiggsAudioV3Code2Wav",
"HiggsAudioV3Code2WavForConditionalGeneration",
]
logger = init_logger(__name__)
# Prefix under which codec weights are stored in the v3 checkpoint.
_CODEC_PREFIX = "tied.embedding.modality_embeddings.0.model."
class HiggsAudioV3Code2Wav(nn.Module):
"""Stage-1 codec decoder for higgs-audio v3.
The codec architecture is identical to v2 (HiggsAudioRVQ + fc2 +
BosonDacDecoder); only the weight loading path differs. V3 bundles
codec weights inside the main checkpoint under a known prefix, while
v2 uses a standalone tokenizer repo.
For backward compatibility and simplicity, we delegate to the v2
``load_higgs_audio_codec`` function when the audio tokenizer repo
is available. When not (or as primary path), we extract codec weights
from the v3 safetensors via the engine's weight iterator.
"""
input_modalities = "audio"
def __init__(
self,
config: HiggsAudioV3Config | None = None,
*,
vllm_config: VllmConfig | None = None,
prefix: str = "",
):
super().__init__()
if vllm_config is not None:
hf_config = vllm_config.model_config.hf_config
if isinstance(hf_config, HiggsAudioV3Config):
self.config = hf_config
else:
self.config = HiggsAudioV3Config(**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("HiggsAudioV3Code2Wav: provide either `config` or `vllm_config`.")
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)
self.hop_length: int = 960
# Engine-runner hooks
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
# Codec modules (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
# Do NOT eagerly load from standalone tokenizer here.
# load_weights() will try bundled V3 codec first, then fall back.
def _load_from_tokenizer_repo(self) -> None:
"""Load codec from the standalone higgs-audio-v2-tokenizer repo."""
tokenizer_id = "bosonai/higgs-audio-v2-tokenizer"
# Try to resolve from HF cache
from huggingface_hub import try_to_load_from_cache
cached = try_to_load_from_cache(repo_id=tokenizer_id, filename="config.json")
if isinstance(cached, str) and os.path.isfile(cached):
tokenizer_dir = os.path.dirname(cached)
else:
from huggingface_hub.constants import HF_HUB_CACHE
safe = tokenizer_id.replace("/", "--")
snapshots_dir = os.path.join(HF_HUB_CACHE, f"models--{safe}", "snapshots")
if os.path.isdir(snapshots_dir):
tokenizer_dir = None
for rev in os.listdir(snapshots_dir):
candidate = os.path.join(snapshots_dir, rev)
if os.path.isfile(os.path.join(candidate, "config.json")):
tokenizer_dir = candidate
break
if tokenizer_dir is None:
raise FileNotFoundError(f"No cached snapshot for {tokenizer_id}")
else:
raise FileNotFoundError(f"No cached snapshot for {tokenizer_id}")
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
quantizer, fc2, acoustic_decoder, _cfg = load_higgs_audio_codec(tokenizer_dir, device)
self.quantizer = quantizer
self.fc2 = fc2
self.acoustic_decoder = acoustic_decoder
self._loaded = True
logger.info("Loaded HiggsAudioV3Code2Wav from standalone tokenizer repo.")
# ------------------------------------------------------------------ engine hooks
def embed_input_ids(self, input_ids: torch.Tensor, **_: Any) -> torch.Tensor:
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):
if self._loaded:
if not isinstance(weights_or_model_dir, (str, bytes, os.PathLike)):
for _ in weights_or_model_dir:
pass
return {name for name, _ in self.named_parameters()}
if not isinstance(weights_or_model_dir, (str, bytes, os.PathLike)):
# Engine path: try to extract V3 bundled codec weights first
codec_state: dict[str, torch.Tensor] = {}
for name, tensor in weights_or_model_dir:
if name.startswith(_CODEC_PREFIX):
stripped = name[len(_CODEC_PREFIX) :]
codec_state[stripped] = tensor
if codec_state:
# Bundled keys found — load strictly, no fallback on error.
self._load_from_bundled_state(codec_state, device)
logger.info(
"Loaded HiggsAudioV3Code2Wav from bundled V3 checkpoint (%d codec keys consumed).",
len(codec_state),
)
return {name for name, _ in self.named_parameters()}
# No bundled keys — fallback to standalone tokenizer repo
if not self._loaded:
try:
self._load_from_tokenizer_repo()
except (FileNotFoundError, OSError) as exc2:
raise RuntimeError(
"HiggsAudioV3Code2Wav: could not load codec weights. "
"Neither V3 bundled codec keys (tied.embedding."
"modality_embeddings.0.model.*) were found in the "
"checkpoint, nor is bosonai/higgs-audio-v2-tokenizer "
f"cached in HF_HOME. Last error: {exc2}"
) from exc2
return {name for name, _ in self.named_parameters()}
# File-based path
if not self._loaded:
self._load_from_tokenizer_repo()
return None
def _load_from_bundled_state(
self,
codec_state: dict[str, torch.Tensor],
device: torch.device | None = None,
) -> None:
"""Load codec from V3 checkpoint's bundled weights.
Keys arrive with the ``tied.embedding.modality_embeddings.0.model.``
prefix already stripped. We remap to the same layout that
``load_higgs_audio_codec`` expects and build the modules.
"""
from vllm_omni.model_executor.models.higgs_audio_v2.higgs_audio_decoder import (
_remap_boson_model_pth_state_dict,
)
if device is None:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# The bundled codec may use boson-ai key naming. Try remapping.
needs_remap = any(k.startswith("quantizer.vq.layers.") for k in codec_state)
if needs_remap:
codec_state = _remap_boson_model_pth_state_dict(codec_state)
# Discover parameters from the state dict
proj_key = "quantizer.quantizers.0.project_out.weight"
if proj_key not in codec_state:
raise KeyError(
f"Bundled codec state dict missing '{proj_key}'. "
f"Available keys (first 10): {list(codec_state.keys())[:10]}"
)
hidden_size = codec_state[proj_key].shape[0]
codebook_dim = 64
codebook_size = 1024
required_quantizers = self.num_codebooks
# Build RVQ — require exactly num_codebooks quantizers
quantizer = HiggsAudioRVQ(
num_quantizers=required_quantizers,
codebook_size=codebook_size,
codebook_dim=codebook_dim,
hidden_size=hidden_size,
).to(device)
for i in range(required_quantizers):
prefix = f"quantizer.quantizers.{i}"
# Require codebook weight
embed_key = None
for key_suffix in [".codebook.embed", ".codebook.weight"]:
candidate = f"{prefix}{key_suffix}"
if candidate in codec_state:
embed_key = candidate
break
if embed_key is None:
raise KeyError(
f"Bundled codec missing codebook weight for quantizer {i}. "
f"Expected {prefix}.codebook.embed or {prefix}.codebook.weight"
)
quantizer.quantizers[i].codebook.weight.data.copy_(codec_state[embed_key].to(device))
# Require projector weights
proj_w = f"{prefix}.project_out.weight"
proj_b = f"{prefix}.project_out.bias"
if proj_w not in codec_state:
raise KeyError(f"Bundled codec missing {proj_w}")
if proj_b not in codec_state:
raise KeyError(f"Bundled codec missing {proj_b}")
quantizer.quantizers[i].project_out.weight.data.copy_(codec_state[proj_w].to(device))
quantizer.quantizers[i].project_out.bias.data.copy_(codec_state[proj_b].to(device))
# Build fc2
fc2_w = codec_state.get("fc2.weight")
fc2_b = codec_state.get("fc2.bias")
if fc2_w is None or fc2_b is None:
raise KeyError(
"Bundled codec state dict missing fc2.weight and/or fc2.bias. "
f"Available keys (first 10): {list(codec_state.keys())[:10]}"
)
fc2 = nn.Linear(fc2_w.shape[1], fc2_w.shape[0]).to(device)
fc2.weight.data.copy_(fc2_w.to(device))
fc2.bias.data.copy_(fc2_b.to(device))
# Build acoustic decoder — detect layout from key names.
# V3 checkpoint uses OmniVoice layout (block.N/conv1/conv2/snake1),
# not boson-ai standalone layout (model.0/model.1).
ad_keys = {
k[len("acoustic_decoder.") :]: v for k, v in codec_state.items() if k.startswith("acoustic_decoder.")
}
is_boson_layout = any(k.startswith("model.") for k in ad_keys)
if is_boson_layout:
acoustic_decoder = build_boson_dac_decoder(device)
else:
# OmniVoice layout — need the v2 tokenizer config for DacConfig
tokenizer_config = {
"acoustic_model_config": {
"codebook_dim": 8,
"codebook_size": 1024,
"decoder_hidden_size": 1024,
"downsampling_ratios": [8, 5, 4, 2, 3],
"encoder_hidden_size": 64,
"hidden_size": 256,
"hop_length": 960,
"model_type": "dac",
"n_codebooks": 9,
"sampling_rate": 16000,
"upsampling_ratios": [8, 5, 4, 2, 3],
}
}
acoustic_decoder = build_higgs_audio_acoustic_decoder(tokenizer_config, device)
if not ad_keys:
raise KeyError(
"Bundled codec state dict has no acoustic_decoder.* keys. "
f"Available keys (first 10): {list(codec_state.keys())[:10]}"
)
load_report = acoustic_decoder.load_state_dict(ad_keys, strict=False)
if load_report.missing_keys:
raise RuntimeError(
f"Bundled DAC decoder missing {len(load_report.missing_keys)} keys: {load_report.missing_keys[:5]}..."
)
if load_report.unexpected_keys:
raise RuntimeError(
f"Bundled DAC decoder has {len(load_report.unexpected_keys)} unexpected keys: "
f"{load_report.unexpected_keys[:5]}..."
)
acoustic_decoder.eval()
# Verify required decoder-side codec keys were consumed. The V3
# checkpoint also bundles encoder-side keys (acoustic_encoder.*,
# encoder_semantic.*, decoder_semantic.*, semantic_model.*, fc.*, fc1.*)
# that the DAC decoder does not need — those are allowed but ignored.
consumed: set[str] = set()
for i in range(required_quantizers):
prefix = f"quantizer.quantizers.{i}"
for suffix in [".codebook.embed", ".codebook.weight"]:
if f"{prefix}{suffix}" in codec_state:
consumed.add(f"{prefix}{suffix}")
consumed.add(f"{prefix}.project_out.weight")
consumed.add(f"{prefix}.project_out.bias")
consumed.add("fc2.weight")
consumed.add("fc2.bias")
for k in codec_state:
if k.startswith("acoustic_decoder."):
consumed.add(k)
# Known unused prefixes: encoder-side modules and quantizer training
# artifacts (cluster_size, embed_avg, inited, project_in) that are
# bundled in the checkpoint but not needed for inference decoding.
_KNOWN_UNUSED_PREFIXES = (
"acoustic_encoder.",
"encoder_semantic.",
"decoder_semantic.",
"semantic_model.",
"fc.",
"fc1.",
)
# Quantizer training-only suffixes (per-codebook)
_QUANTIZER_TRAINING_SUFFIXES = (
".codebook.cluster_size",
".codebook.embed_avg",
".codebook.inited",
".project_in.weight",
".project_in.bias",
)
unconsumed = set()
for k in codec_state:
if k in consumed:
continue
if any(k.startswith(p) for p in _KNOWN_UNUSED_PREFIXES):
continue
if any(k.endswith(s) for s in _QUANTIZER_TRAINING_SUFFIXES):
continue
unconsumed.add(k)
if unconsumed:
raise RuntimeError(
f"Bundled codec has {len(unconsumed)} unexpected decoder-side keys: {sorted(unconsumed)[:10]}..."
)
self.quantizer = quantizer
self.fc2 = fc2
self.acoustic_decoder = acoustic_decoder
self._loaded = True
# ------------------------------------------------------------------ decode
@torch.inference_mode()
def decode_codes(self, audio_codes: torch.Tensor) -> torch.Tensor:
"""Decode [B, num_codebooks=8, T] codes to PCM [B, 1, T*960]."""
if not self._loaded:
raise RuntimeError("HiggsAudioV3Code2Wav not loaded.")
codes = self._validate_codes(audio_codes)
rvq_codes = codes.transpose(0, 1).long()
quantized = self.quantizer.decode(rvq_codes)
quantized = quantized.to(dtype=self.fc2.weight.dtype)
quantized = self.fc2(quantized.transpose(1, 2)).transpose(1, 2)
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(codes.device)
@torch.inference_mode()
def forward_chunk(
self,
audio_codes: torch.Tensor,
*,
left_context_size: int = 0,
right_holdback_size: int = 0,
hop_length: int | None = None,
) -> torch.Tensor:
# ``left_context_size`` frames trimmed off the front (already-emitted
# prefix). ``right_holdback_size`` frames trimmed off the end
# (deferred to the next chunk so the codec has future context for
# the emit region's trailing samples).
hop = int(hop_length) if hop_length is not None else self.hop_length
pcm = self.decode_codes(audio_codes)
right_trim = right_holdback_size * hop
left_trim = left_context_size * hop
if right_trim > 0:
if pcm.shape[-1] <= right_trim:
return pcm[..., :0]
pcm = pcm[..., :-right_trim]
if left_trim == 0:
return pcm
if pcm.shape[-1] <= left_trim:
return pcm[..., :0]
return pcm[..., left_trim:]
# ------------------------------------------------------------------ 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:
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)
right_holdback_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"])
if "right_holdback_size" in meta:
right_holdback_size[i] = int(meta["right_holdback_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(
"HiggsAudioV3Code2Wav: flat code length %d not divisible by %d",
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],
right_holdback_size=right_holdback_size[i],
hop_length=self.hop_length,
)
except ValueError as exc:
logger.warning("HiggsAudioV3Code2Wav: 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:
if audio_codes.ndim != 3:
raise ValueError(
f"audio_codes must have shape [B, {self.num_codebooks}, T]; got {tuple(audio_codes.shape)}"
)
if int(audio_codes.shape[1]) != self.num_codebooks:
raise ValueError(f"dim 1 must equal num_codebooks={self.num_codebooks}; got {int(audio_codes.shape[1])}")
# ``.item()`` triggers a GPU->CPU sync and is illegal inside CUDA-graph
# capture (the dummy run before warmup hits this path). Skip the
# range check while a graph is being captured; the per-step validator
# still fires at real inference time.
if audio_codes.numel() > 0 and not torch.cuda.is_current_stream_capturing():
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(
f"audio_codes out of range: min={min_val}, max={max_val}; expected [0, {self.num_real_codes - 1}]"
)
return audio_codes
@staticmethod
def _split_request_ids(ids: torch.Tensor, seq_token_counts: list[int] | None = None) -> list[torch.Tensor]:
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]
HiggsAudioV3Code2WavForConditionalGeneration = HiggsAudioV3Code2Wav
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,135 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Prompt builder for higgs-audio v3 TTS.
Prompt formats:
Zero-shot:
<|tts|> <|text|> {text tokens} <|audio|>
Voice clone (no ref text):
<|tts|> <|ref_audio|> [-100]×N <|text|> {text tokens} <|audio|>
Voice clone (with ref text):
<|tts|> <|ref_text|> {ref text tokens} <|ref_audio|> [-100]×N <|text|> {text tokens} <|audio|>
-100 placeholders are replaced at prefill time with fused multi-codebook
embeddings of the delay-pattern-encoded reference audio codes.
"""
from __future__ import annotations
from typing import Any
import numpy as np
import torch
__all__ = [
"HiggsAudioV3TokenizerAdapter",
"AUDIO_PLACEHOLDER_ID",
"encode_reference_audio",
"apply_delay_pattern",
]
AUDIO_PLACEHOLDER_ID = -100
_REQUIRED_SPECIALS: tuple[str, ...] = (
"<|tts|>",
"<|text|>",
"<|audio|>",
)
# Codec stream special token IDs (inside the codebook vocab, not the LM vocab)
BOC_ID = 1024
EOC_ID = 1025
def apply_delay_pattern(codes_tn: torch.Tensor) -> torch.Tensor:
"""Apply MusicGen-style delay pattern to raw codes.
Input: [T, N] raw codes (T frames, N codebooks).
Output: [T + N - 1, N] delayed codes with BOC/EOC padding.
Codebook c is delayed by c positions: rows 0..c-1 get BOC,
rows c..c+T-1 get real codes, rows c+T..T+N-2 get EOC.
"""
T, N = codes_tn.shape
L = T + N - 1
delayed = torch.full((L, N), EOC_ID, dtype=codes_tn.dtype)
for c in range(N):
delayed[:c, c] = BOC_ID
delayed[c : c + T, c] = codes_tn[:, c]
return delayed
def encode_reference_audio(
wav: np.ndarray,
sr: int,
) -> torch.Tensor:
"""Encode a reference audio clip to codec codes [T, num_codebooks].
Uses the same HiggsAudioV2TokenizerModel as v2 (same codec).
Returns raw codes before delay pattern application.
"""
from vllm_omni.model_executor.models.higgs_audio_v2.higgs_audio_v2_tokenizer import (
_encode_ref_audio_codes,
)
# _encode_ref_audio_codes returns [num_codebooks, T_raw]
codes_qt = _encode_ref_audio_codes(wav, sr)
# Transpose to [T_raw, num_codebooks]
return codes_qt.transpose(0, 1).contiguous()
class HiggsAudioV3TokenizerAdapter:
"""Wraps the HF tokenizer and builds TTS prompts."""
def __init__(self, tokenizer: Any) -> None:
self._tok = tokenizer
vocab = dict(tokenizer.get_added_vocab())
missing = [t for t in _REQUIRED_SPECIALS if t not in vocab]
if missing:
raise ValueError(f"Tokenizer is missing Higgs TTS v3 specials: {missing}")
self.tts_id: int = vocab["<|tts|>"]
self.text_id: int = vocab["<|text|>"]
self.audio_id: int = vocab["<|audio|>"]
self.ref_audio_id: int | None = vocab.get("<|ref_audio|>")
self.ref_text_id: int | None = vocab.get("<|ref_text|>")
@property
def tokenizer(self) -> Any:
return self._tok
def build_prompt(
self,
text: str,
*,
num_ref_tokens: int = 0,
reference_text: str | None = None,
) -> list[int]:
"""Build a TTS prompt.
Args:
text: Target text to synthesize.
num_ref_tokens: Number of delay-pattern reference code rows.
0 means zero-shot (no voice clone).
reference_text: Optional transcript of the reference audio.
"""
if not text or not text.strip():
raise ValueError("Text input must be non-empty for TTS")
if num_ref_tokens < 0:
raise ValueError(f"num_ref_tokens must be >= 0, got {num_ref_tokens}")
ids: list[int] = [self.tts_id]
# Voice clone: optional ref text + ref audio placeholders
if reference_text and num_ref_tokens > 0 and self.ref_text_id is not None:
ids.append(self.ref_text_id)
ids.extend(self._tok.encode(reference_text, add_special_tokens=False))
if num_ref_tokens > 0:
if self.ref_audio_id is None:
raise ValueError("Tokenizer missing <|ref_audio|> for voice clone")
ids.append(self.ref_audio_id)
ids.extend([AUDIO_PLACEHOLDER_ID] * num_ref_tokens)
ids.append(self.text_id)
ids.extend(self._tok.encode(text, add_special_tokens=False))
ids.append(self.audio_id)
return ids
@@ -0,0 +1,60 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""higgs-audio v3 pipeline: Talker (text -> 8-codebook codec) -> Code2Wav (codec -> 24 kHz PCM).
Two delivery modes are wired here:
* ``sync_process_input_func`` runs when the deploy YAML has
``async_chunk: false``. The orchestrator collects the entire Stage-0 emit,
reverts the delay pattern once, and hands a single payload to Stage 1.
* ``async_chunk_process_next_stage_input_func`` runs when the deploy YAML
has ``async_chunk: true``. Stage 0 dispatches per AR step; the streaming
adapter buffers raw delay-pattern rows, slides a window with left context
and right holdback, and emits codec-ready frames per chunk. Stage 1
trims the overlap on both ends so the client sees a coherent PCM stream.
"""
from vllm_omni.config.stage_config import (
PipelineConfig,
StageExecutionType,
StagePipelineConfig,
)
_PROC = "vllm_omni.model_executor.stage_input_processors.higgs_audio_v3"
HIGGS_AUDIO_V3_PIPELINE = PipelineConfig(
model_type="higgs_multimodal_qwen3",
model_arch="HiggsAudioV3TalkerForConditionalGeneration",
hf_architectures=("HiggsMultimodalQwen3ForConditionalGeneration",),
stages=(
StagePipelineConfig(
stage_id=0,
model_stage="higgs_audio_v3",
execution_type=StageExecutionType.LLM_AR,
input_sources=(),
owns_tokenizer=True,
engine_output_type="latent",
# stop_token_ids: the model-owned sampler forces eos at ramp-down
# completion. Safety stops from the actual V3 checkpoint:
# 151643 = <|endoftext|> (eos_token_id from config.json)
# 151671 = <|audio_end|> (audio generation end marker)
sampling_constraints={
"detokenize": False,
"stop_token_ids": [151643, 151671],
},
async_chunk_process_next_stage_input_func=f"{_PROC}.talker2code2wav_async_chunk",
),
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="HiggsAudioV3Code2WavForConditionalGeneration",
sync_process_input_func=f"{_PROC}.talker2code2wav",
sampling_constraints={"detokenize": True},
),
),
)
@@ -0,0 +1,111 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Bounded LRU cache for Higgs Audio v3 reference-audio codec encoding.
Voice-clone requests that re-send the same ref_audio are otherwise re-encoded
through the DAC encoder on every call. The cache keys by a stable content
hash (size + sample rate + head/mid/tail sentinel bytes) so the same audio
served via different URLs or repeated base64 payloads also hits warm.
Tensors are cloned on get/put so callers and the cache cannot alias storage.
"""
from __future__ import annotations
import hashlib
import threading
from collections import OrderedDict
from collections.abc import Callable
import numpy as np
import torch
__all__ = ["cached_encode_reference_audio", "cache_stats", "clear_cache"]
_DEFAULT_MAX_ENTRIES = 128
_SENTINEL_BYTES = 4096
_cache: OrderedDict[str, torch.Tensor] = OrderedDict()
_cache_lock = threading.Lock()
_hits = 0
_misses = 0
def _content_hash(wav: np.ndarray, sr: int) -> str:
"""Stable content hash. Head/mid/tail sentinel keeps cost O(1)."""
raw = wav.tobytes()
n = len(raw)
h = hashlib.sha256()
h.update(n.to_bytes(8, "little"))
h.update(int(sr).to_bytes(4, "little"))
if n == 0:
return h.hexdigest()
if n <= _SENTINEL_BYTES * 3:
h.update(raw)
return h.hexdigest()
h.update(raw[:_SENTINEL_BYTES])
mid = (n - _SENTINEL_BYTES) // 2
h.update(raw[mid : mid + _SENTINEL_BYTES])
h.update(raw[-_SENTINEL_BYTES:])
return h.hexdigest()
def cached_encode_reference_audio(
wav: np.ndarray,
sr: int,
encode_fn: Callable[[np.ndarray, int], torch.Tensor],
max_entries: int = _DEFAULT_MAX_ENTRIES,
) -> torch.Tensor:
"""LRU-cached wrapper around ``encode_reference_audio``.
``encode_fn`` is the actual codec encoder; passed in so this module
stays decoupled from the tokenizer import (avoids circular imports
during stage-input-processor discovery).
Returns a CPU tensor clone — never the cache's interior storage.
"""
global _hits, _misses
key = _content_hash(wav, sr)
with _cache_lock:
cached = _cache.get(key)
if cached is not None:
_hits += 1
_cache.move_to_end(key)
return cached.clone()
# Miss: encode outside the lock so concurrent misses on different
# refs don't serialize on this single mutex.
codes = encode_fn(wav, sr)
codes_cpu = codes.detach().to("cpu").contiguous()
with _cache_lock:
if key in _cache:
# Concurrent miss winner already stored it; refresh LRU position
# and return that copy to avoid divergent tensors per request.
_cache.move_to_end(key)
_misses += 1 # we still paid the encode cost
return _cache[key].clone()
_cache[key] = codes_cpu
if len(_cache) > max_entries:
_cache.popitem(last=False)
_misses += 1
return codes_cpu.clone()
def cache_stats() -> dict:
"""Return (hits, misses, size, hit_rate) — for /metrics-style reporting."""
with _cache_lock:
total = _hits + _misses
return {
"hits": _hits,
"misses": _misses,
"size": len(_cache),
"hit_rate": (_hits / total) if total > 0 else 0.0,
}
def clear_cache() -> None:
"""Drop all cached entries. Used by tests."""
global _hits, _misses
with _cache_lock:
_cache.clear()
_hits = 0
_misses = 0
+17 -6
View File
@@ -1043,6 +1043,9 @@ class HunyuanImage3MultiModalProcessor(BaseMultiModalProcessor[HunyuanImage3Proc
images = mm_data.get("images", [])
logger.debug(f"process image count: {len(images)}")
batch_feature = image_processor(prompt, images, **tok_kwargs)
vae_generator_seed = mm_kwargs.get("vae_generator_seed")
if vae_generator_seed is not None and images:
batch_feature["vae_generator_seed"] = torch.full((len(images),), int(vae_generator_seed), dtype=torch.long)
return batch_feature
def _hf_processor_applies_updates(
@@ -1080,6 +1083,8 @@ class HunyuanImage3MultiModalProcessor(BaseMultiModalProcessor[HunyuanImage3Proc
config["base_size"] = MultiModalFieldConfig.batched("image")
if "ratio_index" in hf_inputs:
config["ratio_index"] = MultiModalFieldConfig.batched("image")
if "vae_generator_seed" in hf_inputs:
config["vae_generator_seed"] = MultiModalFieldConfig.batched("image")
return config
def _get_prompt_updates(
@@ -1452,6 +1457,7 @@ class HunyuanImage3ForConditionalGeneration(nn.Module, SupportsMultiModal, Suppo
HunyuanImage3Inputs: TypeAlias = HunyuanImage3PixelInputs
prefer_model_sampler = True
logitsprocs_need_output_token_ids = True
# Siglip2 ViT supports data-parallel encoding (mm_encoder_tp_mode="data"):
# weights are replicated and the image batch is sharded across TP ranks.
@@ -1732,6 +1738,7 @@ class HunyuanImage3ForConditionalGeneration(nn.Module, SupportsMultiModal, Suppo
# we reconstruct per-image shapes from vae_token_grid_hw below.
kwargs.pop("vae_pixel_size", None)
vae_token_grid_hw = kwargs.pop("vae_token_grid_hw", None)
vae_generator_seed = kwargs.pop("vae_generator_seed", None)
if vit_pixel_values is None or vae_pixel_values is None:
return None
@@ -1771,6 +1778,7 @@ class HunyuanImage3ForConditionalGeneration(nn.Module, SupportsMultiModal, Suppo
"vit_spatial_shapes": vit_spatial_shapes,
"vae_pixel_values": vae_image_list,
"vae_token_grid_hw": vae_token_grid_hw,
"vae_generator_seed": vae_generator_seed,
},
)
@@ -1778,6 +1786,7 @@ class HunyuanImage3ForConditionalGeneration(nn.Module, SupportsMultiModal, Suppo
self,
images: torch.Tensor,
cfg_factor: int = 1,
generator: torch.Generator | None = None,
) -> tuple[tuple[torch.Tensor, torch.Tensor], ...]:
"""
Encode images through VAE encoder.
@@ -1797,11 +1806,7 @@ class HunyuanImage3ForConditionalGeneration(nn.Module, SupportsMultiModal, Suppo
images = images.to(dtype=self.vae.dtype)
vae_encode_result = self.vae.encode(images)
# Match HunyuanImage-3's cond encode path: sample the posterior, but
# use a fixed generator so online requests do not consume the global
# RNG and drift across a long-running server.
_cond_vae_gen = torch.Generator(device=images.device).manual_seed(0)
latents = vae_encode_result.latent_dist.sample(_cond_vae_gen)
latents = vae_encode_result.latent_dist.sample(generator)
# Apply shift and scaling factors if present
if hasattr(config, "shift_factor") and config.shift_factor:
@@ -1933,6 +1938,12 @@ class HunyuanImage3ForConditionalGeneration(nn.Module, SupportsMultiModal, Suppo
vit_pixel_attention_mask = pixel_values["vit_pixel_attention_mask"]
vit_spatial_shapes = pixel_values["vit_spatial_shapes"]
vae_pixel_values = pixel_values["vae_pixel_values"]
vae_generator_seed = pixel_values.get("vae_generator_seed")
vae_generator = None
if vae_generator_seed is not None and vae_generator_seed.numel() > 0:
vae_generator = torch.Generator(device=vae_pixel_values[0].device).manual_seed(
int(vae_generator_seed.reshape(-1)[0].item())
)
# Perform ViT encoding
vit_embeddings = self._vit_encode(vit_pixel_values, vit_pixel_attention_mask, vit_spatial_shapes)
@@ -1941,7 +1952,7 @@ class HunyuanImage3ForConditionalGeneration(nn.Module, SupportsMultiModal, Suppo
# `reso_group` bucket so shapes are ragged across the image-batch dim.
vae_token_embeddings = []
for vae_image_i in vae_pixel_values:
t_i, latents_i = self._vae_encode(vae_image_i.unsqueeze(0), vae_cfg_factor)
t_i, latents_i = self._vae_encode(vae_image_i.unsqueeze(0), vae_cfg_factor, generator=vae_generator)
t_emb = self.time_embed(t_i[0])
vae_tokens, _, _ = self.patch_embed(latents_i, t_emb)
vae_token_embeddings.append(vae_tokens)
@@ -26,10 +26,10 @@ from vllm.sequence import IntermediateTensors
from vllm_omni.model_executor.custom_process_mixin import CustomProcessMixin
from vllm_omni.model_executor.model_loader.weight_utils import download_weights_from_hf_specific
from vllm_omni.model_executor.models.common.ming.audio_vae import AudioVAE, AudioVAEConfig
from vllm_omni.model_executor.models.output_templates import OmniOutput
from vllm_omni.transformers_utils.configs.ming_flash_omni import MingFlashOmniTalkerConfig
from .audio_vae import AudioVAE, AudioVAEConfig
from .prompt_utils import DEFAULT_PROMPT as MING_DEFAULT_PROMPT
from .talker_module import CFM, Aggregator, DiT, MingAudioGenerator, build_tts_input
from .text_processing import segment_and_normalize
@@ -72,6 +72,7 @@ from vllm_omni.transformers_utils.processors.ming import (
PLACEHOLDER_VIDEO_TOKEN_IN_TEXT,
MingFlashOmniProcessor,
MingWhisperFeatureExtractor,
raise_missing_video_processor,
)
from .audio_encoder import WhisperAudioEncoder
@@ -540,20 +541,20 @@ class MingFlashOmniThinkerMultiModalProcessor(BaseMultiModalProcessor[MingFlashO
if images is not None:
image_outputs = hf_processor.image_processor(
images=images,
videos=None,
return_tensors="pt",
)
data.update(image_outputs)
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,
return_tensors="pt",
)
video_processor = getattr(hf_processor, "video_processor", None)
if video_processor is not None:
video_outputs = video_processor(
videos=videos,
return_tensors="pt",
)
else:
raise_missing_video_processor()
# Rename keys to distinguish from images
if "pixel_values" in video_outputs:
video_outputs["pixel_values_videos"] = video_outputs.pop("pixel_values")
@@ -696,6 +697,9 @@ class MingFlashOmniThinkerForConditionalGeneration(
f"image_gen_scales={list(self.query_tokens_dict.keys())}"
)
def get_language_model(self):
return self.language_model
def _load_image_gen_query_tokens(self, model_path: str) -> None:
"""Load learnable query tokens used for image generation.
@@ -714,6 +714,9 @@ class BailingMoeV2Model(nn.Module):
def get_input_embeddings(self):
return self.word_embeddings
def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
return self.word_embeddings(input_ids)
def forward(
self,
input_ids: torch.Tensor,
@@ -794,6 +797,9 @@ class BailingMoeV2ForCausalLM(nn.Module, CustomProcessMixin):
self.sampler = Sampler()
self.make_empty_intermediate_tensors = self.model.make_empty_intermediate_tensors
def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
return self.model.embed_input_ids(input_ids)
def forward(
self,
input_ids: torch.Tensor,
@@ -818,7 +824,7 @@ class BailingMoeV2ForCausalLM(nn.Module, CustomProcessMixin):
hidden_states: torch.Tensor,
sampling_metadata,
) -> torch.Tensor | None:
logits = self.logits_processor(self.lm_head, hidden_states, sampling_metadata)
logits = self.logits_processor(self.lm_head, hidden_states)
return logits
def sample(
@@ -110,12 +110,18 @@ BASE_CAPTION_TEMPLATE: dict[str, Any] = {
}
def create_instruction(user_input: dict[str, Any]) -> str:
def create_instruction(user_input: Any) -> str | None:
"""Return a JSON caption string for ``audio_sequence[0]``.
Only keys already present on the base template are merged in; unknown
keys are silently ignored to keep the output schema stable.
"""
if user_input is None:
return None
if isinstance(user_input, str):
return user_input
if not isinstance(user_input, dict):
raise ValueError(f"Ming instruction must be str, dict, or None; got {type(user_input).__name__}")
caption = copy.deepcopy(BASE_CAPTION_TEMPLATE)
item = caption["audio_sequence"][0]
for key, value in user_input.items():
@@ -27,223 +27,19 @@ from threading import Lock
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import PreTrainedTokenizerBase, Qwen2Config, Qwen2Model, StaticCache
from vllm.logger import init_logger
from vllm.platforms import current_platform
from x_transformers.x_transformers import RotaryEmbedding, apply_rotary_pos_emb
from x_transformers.x_transformers import RotaryEmbedding
from vllm_omni.model_executor.layers.timestep_embedding import DiTTimestepEmbedding
from .audio_vae import AudioVAE
from vllm_omni.model_executor.models.common.ming.audio_vae import AudioVAE
from vllm_omni.model_executor.models.common.ming.dit import CondEmbedder, DiTBlock, FinalLayer, get_epss_timesteps
from vllm_omni.model_executor.models.common.ming.fm import apply_sway_sampling, integrate_cfm_steps
logger = init_logger(__name__)
########################################################################
# DiT Modules
# Ported from:
# https://github.com/inclusionAI/Ming/blob/e58533db227031990c5a6864dcf5f08fb53ed0d2/talker_module/modules.py
# Ported from:
# https://github.com/inclusionAI/Ming/blob/e58533db227031990c5a6864dcf5f08fb53ed0d2/talker_module/dit.py
########################################################################
class RMSNorm(nn.Module):
def __init__(self, dim: int, eps: float = 1e-6):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim))
def forward(self, x: torch.Tensor) -> torch.Tensor:
if self.weight.dtype in [torch.float16, torch.bfloat16]:
x = x.to(self.weight.dtype)
x = F.rms_norm(x, normalized_shape=(x.shape[-1],), weight=self.weight, eps=self.eps)
return x
class FeedForward(nn.Module):
def __init__(
self, dim: int, dim_out: int | None = None, mult: float = 4, dropout: float = 0.0, approximate: str = "none"
):
super().__init__()
inner_dim = int(dim * mult)
dim_out = dim_out if dim_out is not None else dim
activation = nn.GELU(approximate=approximate)
project_in = nn.Sequential(nn.Linear(dim, inner_dim), activation)
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 Attention(nn.Module):
def __init__(
self,
dim: int,
heads: int = 8,
dim_head: int = 64,
dropout: float = 0.0,
qk_norm: str | None = None,
pe_attn_head: int | None = None,
attn_mask_enabled: bool = True,
):
super().__init__()
self.dim = dim
self.heads = heads
self.inner_dim = dim_head * heads
self.dropout = dropout
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)
if qk_norm is None:
self.q_norm = None
self.k_norm = None
elif qk_norm == "rms_norm":
self.q_norm = RMSNorm(dim_head)
self.k_norm = RMSNorm(dim_head)
else:
raise ValueError(f"Unimplemented qk_norm: {qk_norm}")
self.to_out = nn.ModuleList([])
self.to_out.append(nn.Linear(self.inner_dim, dim))
self.to_out.append(nn.Dropout(dropout))
self.pe_attn_head = pe_attn_head
self.attn_mask_enabled = attn_mask_enabled
def forward(
self,
x: torch.Tensor,
mask: torch.Tensor | None = None,
rope: tuple[torch.Tensor, torch.Tensor | None] | None = None,
) -> torch.Tensor:
batch_size = x.shape[0]
query = self.to_q(x)
key = self.to_k(x)
value = self.to_v(x)
inner_dim = key.shape[-1]
head_dim = inner_dim // self.heads
query = query.view(batch_size, -1, self.heads, head_dim).transpose(1, 2)
key = key.view(batch_size, -1, self.heads, head_dim).transpose(1, 2)
value = value.view(batch_size, -1, self.heads, head_dim).transpose(1, 2)
if self.q_norm is not None:
query = self.q_norm(query)
if self.k_norm is not None:
key = self.k_norm(key)
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)
if self.pe_attn_head is not None:
on = self.pe_attn_head
query[:, :on, :, :] = apply_rotary_pos_emb(query[:, :on, :, :], freqs, q_xpos_scale)
key[:, :on, :, :] = apply_rotary_pos_emb(key[:, :on, :, :], freqs, k_xpos_scale)
else:
query = apply_rotary_pos_emb(query, freqs, q_xpos_scale)
key = apply_rotary_pos_emb(key, freqs, k_xpos_scale)
if self.attn_mask_enabled and mask is not None:
valid_sample_indices = mask.any(dim=1)
final_output = torch.zeros_like(query).to(query.device)
attn_mask = mask[valid_sample_indices]
query = query[valid_sample_indices]
key = key[valid_sample_indices]
value = value[valid_sample_indices]
attn_mask = attn_mask.unsqueeze(1).unsqueeze(1)
attn_mask = attn_mask.expand(valid_sample_indices.sum().item(), self.heads, query.shape[-2], key.shape[-2])
else:
attn_mask = None
x = F.scaled_dot_product_attention(query, key, value, attn_mask=attn_mask, dropout_p=0.0, is_causal=False)
if self.attn_mask_enabled and mask is not None:
final_output[valid_sample_indices] = x
x = final_output
x = x.transpose(1, 2).reshape(batch_size, -1, self.heads * head_dim)
x = x.to(query.dtype)
x = self.to_out[0](x)
x = self.to_out[1](x)
if mask is not None:
mask = mask.unsqueeze(-1)
x = x.masked_fill(~mask, 0.0)
return x
class DiTBlock(nn.Module):
"""A DiT block with pre-norm and residual connections."""
def __init__(
self,
hidden_size: int,
num_heads: int,
mlp_ratio: float = 4.0,
dropout: float = 0.1,
qk_norm: str | None = None,
pe_attn_head: int | None = None,
attn_mask_enabled: bool = True,
**kwargs,
):
super().__init__()
self.norm1 = RMSNorm(hidden_size)
self.attn = Attention(
dim=hidden_size,
heads=num_heads,
dim_head=hidden_size // num_heads,
dropout=dropout,
qk_norm=qk_norm,
pe_attn_head=pe_attn_head,
attn_mask_enabled=attn_mask_enabled,
)
self.norm2 = RMSNorm(hidden_size)
self.mlp = FeedForward(dim=hidden_size, mult=mlp_ratio, dropout=dropout, approximate="tanh")
def forward(
self,
x: torch.Tensor,
mask: torch.Tensor | None,
rope: tuple[torch.Tensor, torch.Tensor | None] | None,
) -> torch.Tensor:
x = x + self.attn(self.norm1(x), mask=mask, rope=rope)
x = x + self.mlp(self.norm2(x))
return x
class FinalLayer(nn.Module):
"""The final layer of DiT."""
def __init__(self, hidden_size: int, out_channels: int):
super().__init__()
self.norm_final = RMSNorm(hidden_size)
self.linear = nn.Linear(hidden_size, out_channels, bias=True)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.norm_final(x)
x = self.linear(x)
return x
class CondEmbedder(nn.Module):
"""Embeds LLM hidden states with optional CFG dropout."""
def __init__(self, input_feature_size: int, hidden_size: int):
super().__init__()
self.cond_embedder = nn.Linear(input_feature_size, hidden_size)
def forward(self, llm_cond: torch.Tensor) -> torch.Tensor:
return self.cond_embedder(llm_cond)
class DiT(nn.Module):
"""Diffusion model with a Transformer backbone for audio latent generation."""
@@ -324,29 +120,6 @@ class DiT(nn.Module):
return model_out[:, -x.shape[1] :, :]
#########################################################################################
# CFM
# Ported from:
# https://github.com/inclusionAI/Ming/blob/e58533db227031990c5a6864dcf5f08fb53ed0d2/talker_module/cfm.py
#########################################################################################
def get_epss_timesteps(n, device, dtype):
dt = 1 / 32
predefined_timesteps = {
5: [0, 2, 4, 8, 16, 32],
6: [0, 2, 4, 6, 8, 16, 32],
7: [0, 2, 4, 6, 8, 16, 24, 32],
10: [0, 2, 4, 6, 8, 12, 16, 20, 24, 28, 32],
12: [0, 2, 4, 6, 8, 10, 12, 14, 16, 20, 24, 28, 32],
16: [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32],
}
t = predefined_timesteps.get(n, [])
if not t:
return torch.linspace(0, 1, n + 1, device=device, dtype=dtype)
return dt * torch.tensor(t, device=device, dtype=dtype)
class CFM(nn.Module):
"""Conditional Flow Matching module for audio latent generation."""
@@ -391,15 +164,8 @@ class CFM(nn.Module):
pred, null_pred = torch.chunk(pred_cfg, 2, dim=0)
return pred + (pred - null_pred) * sde_args[0]
if self.sway_sampling_coef is not None:
t = t + self.sway_sampling_coef * (torch.cos(torch.pi / 2 * t) - 1 + t)
for step in range(self.steps):
dt = t[step + 1] - t[step]
y0 = y0 + fn(t[step], y0) * dt
y0 = y0 + sde_args[1] * (sde_args[2] ** 0.5) * (dt.abs() ** 0.5) * sde_rnd[step]
return y0
t = apply_sway_sampling(t, self.sway_sampling_coef)
return integrate_cfm_steps(fn, y0, t, sde_args, sde_rnd, self.steps)
class CFMGraphExecutor:
@@ -902,6 +668,7 @@ class MingAudioGenerator:
if self._audio_vae is None:
return requested_max_steps
# Transformers >=5.x may expose these config values as 0-d tensors.
sample_rate = float(self._audio_vae.config.sample_rate)
vae_patch_size = float(getattr(self._audio_vae.config, "patch_size", 4))
hop_size = float(getattr(self._audio_vae.decoder, "hop_length", 320))
@@ -1041,7 +808,7 @@ class MingAudioGenerator:
use_cache=True,
)
else:
past_seen_tokens = past_key_values.get_seq_length()
past_seen_tokens = int(past_key_values.get_seq_length())
cache_position = torch.arange(
past_seen_tokens,
past_seen_tokens + inputs_embeds.shape[1],
@@ -22,7 +22,8 @@ from .spk_embedding import SpkembExtractor
from .talker_module import resample
if TYPE_CHECKING:
from .audio_vae import AudioVAE
from vllm_omni.model_executor.models.common.ming.audio_vae import AudioVAE
from .talker_module import Aggregator
logger = init_logger(__name__)
@@ -0,0 +1,13 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from .config_ming_tts import MingDenseConfig
from .ming_tts import MingTTSForConditionalGeneration
from .ming_tts_audio_vae import MingAudioVAEModel
from .ming_tts_llm import MingLLMModel
__all__ = [
"MingDenseConfig",
"MingTTSForConditionalGeneration",
"MingLLMModel",
"MingAudioVAEModel",
]
@@ -0,0 +1,67 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Adopted from https://github.com/inclusionAI/Ming-omni-tts/blob/main/fm/dit.py
from __future__ import annotations
import torch
import torch.nn as nn
from x_transformers.x_transformers import RotaryEmbedding
from vllm_omni.model_executor.models.common.ming.dit import DiTBlock, FinalLayer
class Aggregator(nn.Module):
def __init__(
self,
in_channels=4,
hidden_size=1152,
depth=28,
num_heads=16,
mlp_ratio=4.0,
llm_input_dim=896,
**kwargs,
):
super().__init__()
self.in_channels = in_channels
self.out_channels = in_channels
self.num_heads = num_heads
self.word_embedder = nn.Embedding(1, hidden_size)
self.x_embedder = nn.Linear(in_channels, hidden_size)
self.hidden_size = hidden_size
self.rotary_embed = RotaryEmbedding(hidden_size // num_heads)
self.blocks = nn.ModuleList(
[DiTBlock(hidden_size, num_heads, mlp_ratio=mlp_ratio, **kwargs) for _ in range(depth)]
)
self.final_layer = FinalLayer(hidden_size, llm_input_dim)
def forward(self, x, mask=None):
if x.ndim != 3:
raise ValueError(f"Expected x rank-3 [Batch, Time, Dimension], got {tuple(x.shape)}")
if x.shape[-1] != self.in_channels:
raise ValueError(f"x feature dim mismatch: got {x.shape[-1]}, expected {self.in_channels}")
# [Batch, Time, Dimension] -> [Batch, Time, Hidden].
x = self.x_embedder(x)
cls_embed = self.word_embedder(torch.zeros((x.shape[0], 1), dtype=torch.long, device=x.device))
# Prepend a learned CLS token: [Batch, Time, Hidden] -> [Batch, Time + 1, Hidden].
x = torch.cat([cls_embed, x], dim=1)
rope = self.rotary_embed.forward_from_seq_len(x.shape[1])
if mask is not None:
if mask.ndim != 2:
raise ValueError(f"Expected mask rank-2 [Batch, Time], got {tuple(mask.shape)}")
if mask.shape[0] != x.shape[0] or mask.shape[1] != x.shape[1] - 1:
raise ValueError(
f"Mask shape mismatch: got {tuple(mask.shape)}, expected {(x.shape[0], x.shape[1] - 1)}"
)
mask_pad = mask.clone().detach()[:, :1]
mask = torch.cat([mask_pad, mask], dim=-1)
for block in self.blocks:
x = block(x, mask, rope)
x = self.final_layer(x)
# Keep the CLS projection only: [Batch, Time + 1, Hidden] -> [Batch, 1, Hidden].
return x[:, :1, :]
__all__ = ["Aggregator"]
@@ -0,0 +1,261 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
import math
from io import BytesIO
from typing import Any
import torch
from .config_ming_tts import (
AUDIO_FRAME_HOP,
LATENT_DIM,
PATCH_SIZE,
SAMPLE_RATE,
VAE_PATCH_SIZE,
VISION_START_TOKEN_ID,
MingTTSConfig,
)
def pad_prompt_waveform(
waveform: Any,
*,
patch_size: int = PATCH_SIZE,
sample_rate: int = SAMPLE_RATE,
) -> torch.Tensor:
tensor = coerce_prompt_waveform(waveform)
pad_align = int((float(sample_rate) / 12.5) * int(patch_size))
new_len = ((int(tensor.shape[-1]) + pad_align - 1) // pad_align) * pad_align
if new_len == int(tensor.shape[-1]):
return tensor
padded = torch.zeros((1, new_len), dtype=tensor.dtype, device=tensor.device)
padded[:, : tensor.shape[-1]] = tensor
return padded
def coerce_prompt_waveform(value: Any) -> torch.Tensor:
if value is None:
raise ValueError("prompt waveform cannot be None")
if isinstance(value, torch.Tensor):
tensor = value.detach()
if tensor.ndim == 1:
return tensor.unsqueeze(0).to(torch.float32)
if tensor.ndim == 2:
if tensor.shape[0] != 1:
return tensor.reshape(1, -1).to(torch.float32)
return tensor.to(torch.float32)
raise ValueError(f"Unsupported Ming prompt waveform rank: {tuple(tensor.shape)}")
if isinstance(value, (list, tuple)):
parts = [coerce_prompt_waveform(item) for item in value if item is not None]
if not parts:
raise ValueError("prompt waveform list was empty")
return torch.cat(parts, dim=-1)
return coerce_prompt_waveform(torch.as_tensor(value))
def coerce_speaker_embeddings(value: Any, *, use_zero_spk_emb: bool = False) -> list[torch.Tensor] | None:
if value is None:
return [torch.zeros((192,), dtype=torch.float32)] if use_zero_spk_emb else None
if isinstance(value, torch.Tensor):
tensor = value.detach()
if tensor.ndim == 1:
tensor = tensor.unsqueeze(0)
if tensor.ndim != 2:
raise ValueError(f"Unsupported Ming speaker embedding shape: {tuple(tensor.shape)}")
items = [row.reshape(-1).to(torch.float32).cpu() for row in tensor]
elif isinstance(value, (list, tuple)):
if value and all(not isinstance(item, (list, tuple, torch.Tensor)) for item in value):
items = [torch.as_tensor(value).detach().reshape(-1).to(torch.float32).cpu()]
else:
items = []
for item in value:
if item is None:
continue
if not isinstance(item, torch.Tensor):
item = torch.as_tensor(item)
items.append(item.detach().reshape(-1).to(torch.float32).cpu())
else:
return coerce_speaker_embeddings(torch.as_tensor(value), use_zero_spk_emb=use_zero_spk_emb)
if not items:
return [torch.zeros((192,), dtype=torch.float32)] if use_zero_spk_emb else None
for item in items:
if int(item.numel()) != 192:
raise ValueError(f"Ming speaker embedding must have 192 dims, got {int(item.numel())}")
return items
def count_prompt_latent_patches(
value: Any,
*,
patch_size: int = PATCH_SIZE,
latent_dim: int = LATENT_DIM,
) -> int:
if value is None:
return 0
if not isinstance(value, torch.Tensor):
value = torch.as_tensor(value)
latents = value.detach()
if latents.ndim == 3 and latents.shape[0] == 1:
latents = latents.squeeze(0)
if latents.ndim == 3 and latents.shape[-2:] == (patch_size, latent_dim):
return int(latents.shape[0])
if latents.ndim != 2 or latents.shape[-1] != latent_dim:
raise ValueError(f"Unsupported Ming prompt_latents shape: {tuple(latents.shape)}")
if latents.shape[0] % patch_size != 0:
raise ValueError(
f"Ming prompt_latents frame count must be divisible by patch_size={patch_size}, "
f"got frames={int(latents.shape[0])}"
)
return int(latents.shape[0] // patch_size)
def count_prompt_waveform_patches(
value: Any,
*,
patch_size: int = PATCH_SIZE,
frame_hop: int = AUDIO_FRAME_HOP,
vae_patch_size: int = VAE_PATCH_SIZE,
) -> int:
if value is None:
return 0
waveform = pad_prompt_waveform(value, patch_size=patch_size)
frame_count = int(math.ceil(float(waveform.shape[-1]) / float(frame_hop)))
latent_frames = int(math.ceil(float(frame_count) / float(vae_patch_size)))
if latent_frames % int(patch_size) != 0:
raise ValueError(
f"Ming prompt waveform produced latent frame count not divisible by patch_size={patch_size}: "
f"frames={latent_frames}"
)
return int(latent_frames // int(patch_size))
def _normalize_prompt_waveform(value: Any, *, target_sr: int) -> torch.Tensor:
if isinstance(value, bytes):
import torchaudio
waveform, sr = torchaudio.load(BytesIO(value))
waveform = waveform[:1].to(torch.float32)
if int(sr) != int(target_sr):
from torchaudio.functional import resample as resample_audio
waveform = resample_audio(waveform, int(sr), int(target_sr))
return waveform
if isinstance(value, tuple) and len(value) == 2 and isinstance(value[1], int):
waveform = coerce_prompt_waveform(value[0])
if int(value[1]) != int(target_sr):
from torchaudio.functional import resample as resample_audio
waveform = resample_audio(waveform, int(value[1]), int(target_sr))
return waveform
if isinstance(value, dict):
samples = value.get("samples", value.get("array", value.get("waveform")))
sr = value.get("sample_rate", value.get("sr", target_sr))
return _normalize_prompt_waveform((samples, int(sr)), target_sr=target_sr)
return coerce_prompt_waveform(value)
def _coerce_prompt_latents(
value: Any,
*,
patch_size: int,
latent_dim: int,
) -> dict[str, torch.Tensor] | None:
if value is None:
return None
if not isinstance(value, torch.Tensor):
value = torch.as_tensor(value)
latents = value.detach()
if latents.ndim == 3 and latents.shape[0] == 1:
latents = latents.squeeze(0)
if latents.ndim == 3 and latents.shape[-2:] == (patch_size, latent_dim):
patches = latents
# [Patch, Time, Dimension] -> [Frame, Dimension] for history seeding.
frames = patches.reshape(-1, latent_dim)
return {"patches": patches, "frames": frames}
if latents.ndim != 2 or latents.shape[-1] != latent_dim:
raise ValueError(f"Unsupported prompt latent shape: {tuple(latents.shape)}")
if latents.shape[0] % patch_size != 0:
raise ValueError(
f"Prompt latent frame count must be divisible by patch_size={patch_size}, "
f"got frames={int(latents.shape[0])}"
)
# [Frame, Dimension] -> [Patch, Time, Dimension] for Aggregator prompt slots.
patches = latents.reshape(-1, patch_size, latent_dim) if latents.shape[0] > 0 else None
return {"patches": patches, "frames": latents}
def _initial_history(
frames: torch.Tensor | None,
*,
history_size: int,
latent_dim: int,
device: torch.device,
dtype: torch.dtype,
) -> torch.Tensor:
history = torch.zeros((history_size, latent_dim), device=device, dtype=dtype)
if frames is None or frames.numel() == 0:
return history
frames = frames.to(device=device, dtype=dtype)
take = min(history_size, int(frames.shape[0]))
history[-take:] = frames[-take:]
return history
def _take_scalar(value: Any, idx: int) -> float | None:
if not isinstance(value, torch.Tensor) or value.numel() == 0:
return None
return float(value.reshape(-1)[idx].item())
def _find_audio_placeholder_positions(input_ids: torch.Tensor, cfg: MingTTSConfig) -> torch.Tensor:
dummy_pos = (input_ids == cfg.audio_dummy_token_id).nonzero(as_tuple=True)[0]
if dummy_pos.numel() == 0:
return dummy_pos
audio_start_pos = (input_ids == cfg.audio_start_token_id).nonzero(as_tuple=True)[0]
audio_end_pos = (input_ids == cfg.audio_end_token_id).nonzero(as_tuple=True)[0]
if audio_start_pos.numel() == 0:
return dummy_pos
start = int(audio_start_pos[0].item())
end = int(audio_end_pos[0].item()) if audio_end_pos.numel() > 0 else int(input_ids.shape[0])
keep = (dummy_pos > start) & (dummy_pos < end)
filtered = dummy_pos[keep]
return filtered if filtered.numel() > 0 else dummy_pos
def _find_speaker_placeholder_positions(input_ids: torch.Tensor, hf_config: Any) -> list[int]:
vision_start_token_id = getattr(hf_config, "vision_start_token_id", VISION_START_TOKEN_ID)
vision_start_pos = (input_ids == int(vision_start_token_id)).nonzero(as_tuple=True)[0]
if vision_start_pos.numel() == 0:
return []
slots = []
for pos in vision_start_pos:
slot = int(pos.item()) + 1
if slot < int(input_ids.shape[0]):
slots.append(slot)
return slots
__all__ = [
"coerce_prompt_waveform",
"coerce_speaker_embeddings",
"count_prompt_latent_patches",
"count_prompt_waveform_patches",
"pad_prompt_waveform",
"_coerce_prompt_latents",
"_find_audio_placeholder_positions",
"_find_speaker_placeholder_positions",
"_initial_history",
"_normalize_prompt_waveform",
"_take_scalar",
]
@@ -0,0 +1,209 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Ming dense checkpoint config adapters."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any
from transformers import PretrainedConfig, Qwen2Config
from vllm_omni.model_executor.models.common.ming.audio_vae import AudioVAEConfig
from .constants import (
AGGREGATOR_HIDDEN_SIZE,
AUDIO_DUMMY_TOKEN_ID,
AUDIO_END_TOKEN_ID,
AUDIO_EOS_TOKEN_ID,
AUDIO_FRAME_HOP,
AUDIO_START_TOKEN_ID,
DEFAULT_CFG,
DEFAULT_SIGMA,
DEFAULT_TEMPERATURE,
HISTORY_PATCH_SIZE,
KEY_CFG,
KEY_CHUNK_ID,
KEY_DECODE_STEP,
KEY_LAST_STOP_PROB,
KEY_LATENT_HISTORY,
KEY_MAX_DECODE_STEPS,
KEY_MIN_DECODE_STEPS,
KEY_NEXT_EMBEDS,
KEY_PROMPT_LATENT_TAIL,
KEY_PROMPT_LATENTS,
KEY_REQUEST_ID,
KEY_SIGMA,
KEY_SPEAKER_EMBEDDING,
KEY_TEMPERATURE,
KEY_TEXT_MODE,
LATENT_CHUNK_SIZE,
LATENT_DIM,
LATENT_LEFT_CONTEXT,
LLM_HIDDEN_SIZE,
LLM_VOCAB_SIZE,
MAX_DECODE_STEPS,
PATCH_SIZE,
SAMPLE_RATE,
STOP_HEAD_MIN_STEPS,
STOP_HEAD_THRESHOLD,
TEXT_EOS_TOKEN_ID,
VAE_PATCH_SIZE,
VISION_START_TOKEN_ID,
)
from .validation import _coerce_audio_vae_config, _nested_get, _to_plain_dict, validate_ming_tts_config
def _coerce_qwen2_config(value: Any) -> Qwen2Config:
if isinstance(value, Qwen2Config):
return value
if isinstance(value, PretrainedConfig):
return Qwen2Config.from_dict(value.to_dict())
if isinstance(value, dict):
return Qwen2Config.from_dict(dict(value))
raise TypeError(f"Unsupported llm_config type for Ming dense config: {type(value)!r}")
class MingDenseConfig(PretrainedConfig):
# The upstream checkpoint declares model_type="dense". Keep it for HF
# config compatibility; deploy/ming_tts.yaml selects the vLLM-Omni
# pipeline via pipeline: ming_tts.
model_type = "dense"
def __init__(
self,
llm_config: Qwen2Config | dict[str, Any] | None = None,
ditar_config: dict[str, Any] | None = None,
aggregator_config: dict[str, Any] | None = None,
audio_tokenizer_config: AudioVAEConfig | dict[str, Any] | None = None,
architectures: list[str] | None = None,
**kwargs: Any,
) -> None:
self.llm_config = _coerce_qwen2_config(llm_config or {})
self.ditar_config = dict(ditar_config or {})
self.aggregator_config = dict(aggregator_config or {})
self.audio_tokenizer_config = _coerce_audio_vae_config(audio_tokenizer_config)
super().__init__(architectures=architectures, **kwargs)
def get_text_config(self, decoder: bool = False, **kwargs: Any) -> Qwen2Config:
del decoder, kwargs
return self.llm_config
@dataclass
class MingTTSConfig:
"""Flat config object shared by Stage-1 and Stage-2. Build via from_hf_config()."""
llm_hidden_size: int = LLM_HIDDEN_SIZE
llm_vocab_size: int = LLM_VOCAB_SIZE
llm_config: dict[str, Any] = field(default_factory=dict)
latent_dim: int = LATENT_DIM
patch_size: int = PATCH_SIZE
history_patch_size: int = HISTORY_PATCH_SIZE
ditar_config: dict[str, Any] = field(default_factory=dict)
aggregator_config: dict[str, Any] = field(default_factory=dict)
audio_tokenizer_config: AudioVAEConfig | None = None
vae_patch_size: int = VAE_PATCH_SIZE
sample_rate: int = SAMPLE_RATE
audio_frame_hop: int = AUDIO_FRAME_HOP
cfg: float = DEFAULT_CFG
sigma: float = DEFAULT_SIGMA
temperature: float = DEFAULT_TEMPERATURE
stop_head_min_steps: int = STOP_HEAD_MIN_STEPS
stop_head_threshold: float = STOP_HEAD_THRESHOLD
max_decode_steps: int = MAX_DECODE_STEPS
latent_chunk_size: int = LATENT_CHUNK_SIZE
latent_left_context: int = LATENT_LEFT_CONTEXT
text_eos_token_id: int = TEXT_EOS_TOKEN_ID
audio_dummy_token_id: int = AUDIO_DUMMY_TOKEN_ID
audio_start_token_id: int = AUDIO_START_TOKEN_ID
audio_end_token_id: int = AUDIO_END_TOKEN_ID
audio_eos_token_id: int = AUDIO_EOS_TOKEN_ID
@classmethod
def from_hf_config(cls, hf_config: PretrainedConfig) -> MingTTSConfig:
llm_raw = getattr(hf_config, "llm_config", {}) or {}
ditar_raw = getattr(hf_config, "ditar_config", {}) or {}
agg_raw = getattr(hf_config, "aggregator_config", {}) or {}
atc_raw = getattr(hf_config, "audio_tokenizer_config", None)
llm_dict = _to_plain_dict(llm_raw)
ditar = _to_plain_dict(ditar_raw)
agg = _to_plain_dict(agg_raw)
ditar.setdefault("attn_backend", "torch")
atc = _coerce_audio_vae_config(atc_raw)
atc_enc_latent_dim = _nested_get(atc, "enc_kwargs", "latent_dim", default=LATENT_DIM)
atc_patch_size = _nested_get(atc, "patch_size", default=VAE_PATCH_SIZE)
atc_sample_rate = _nested_get(atc, "sample_rate", default=SAMPLE_RATE)
enc_hop_size = _nested_get(atc, "enc_kwargs", "hop_size", default=AUDIO_FRAME_HOP)
cfg = cls(
llm_hidden_size=llm_dict.get("hidden_size", LLM_HIDDEN_SIZE),
llm_vocab_size=llm_dict.get("vocab_size", LLM_VOCAB_SIZE),
llm_config=llm_dict,
latent_dim=atc_enc_latent_dim,
patch_size=ditar.get("patch_size", PATCH_SIZE),
history_patch_size=ditar.get("history_patch_size", HISTORY_PATCH_SIZE),
ditar_config=ditar,
aggregator_config=agg,
audio_tokenizer_config=atc,
vae_patch_size=atc_patch_size,
sample_rate=atc_sample_rate,
audio_frame_hop=enc_hop_size if enc_hop_size is not None else AUDIO_FRAME_HOP,
)
return cfg
def validate(self) -> None:
validate_ming_tts_config(self)
__all__ = [
"AGGREGATOR_HIDDEN_SIZE",
"AUDIO_DUMMY_TOKEN_ID",
"AUDIO_END_TOKEN_ID",
"AUDIO_EOS_TOKEN_ID",
"AUDIO_FRAME_HOP",
"AUDIO_START_TOKEN_ID",
"DEFAULT_CFG",
"DEFAULT_SIGMA",
"DEFAULT_TEMPERATURE",
"HISTORY_PATCH_SIZE",
"KEY_CFG",
"KEY_CHUNK_ID",
"KEY_DECODE_STEP",
"KEY_LAST_STOP_PROB",
"KEY_LATENT_HISTORY",
"KEY_MAX_DECODE_STEPS",
"KEY_MIN_DECODE_STEPS",
"KEY_NEXT_EMBEDS",
"KEY_PROMPT_LATENT_TAIL",
"KEY_PROMPT_LATENTS",
"KEY_REQUEST_ID",
"KEY_SIGMA",
"KEY_SPEAKER_EMBEDDING",
"KEY_TEMPERATURE",
"KEY_TEXT_MODE",
"LATENT_CHUNK_SIZE",
"LATENT_DIM",
"LATENT_LEFT_CONTEXT",
"LLM_HIDDEN_SIZE",
"LLM_VOCAB_SIZE",
"MAX_DECODE_STEPS",
"MingDenseConfig",
"MingTTSConfig",
"PATCH_SIZE",
"SAMPLE_RATE",
"STOP_HEAD_MIN_STEPS",
"STOP_HEAD_THRESHOLD",
"TEXT_EOS_TOKEN_ID",
"VAE_PATCH_SIZE",
"VISION_START_TOKEN_ID",
]
@@ -0,0 +1,67 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
# ---------------------------------------------------------------------------
# Token IDs (confirmed from tokenizer_config.json)
# ---------------------------------------------------------------------------
AUDIO_DUMMY_TOKEN_ID = 151705 # <audioPatch>
AUDIO_START_TOKEN_ID = 151706 # <audio>
AUDIO_END_TOKEN_ID = 151707 # </audio>
AUDIO_EOS_TOKEN_ID = 151704 # <end_of_audio>
VISION_START_TOKEN_ID = 151652 # <|vision_start|>
TEXT_EOS_TOKEN_ID = 151669 # <text_eos>
# ---------------------------------------------------------------------------
# Architectural constants (confirmed from original config.json)
# ---------------------------------------------------------------------------
LATENT_DIM = 64
PATCH_SIZE = 4
HISTORY_PATCH_SIZE = 32
LLM_HIDDEN_SIZE = 896
LLM_VOCAB_SIZE = 151936
AGGREGATOR_HIDDEN_SIZE = 1024
VAE_PATCH_SIZE = 4
SAMPLE_RATE = 44100
# AudioVAE frame/hop geometry (confirmed)
AUDIO_FRAME_HOP = 882 # enc input_dim / hop_size / dec output_dim
# stop_head defaults
STOP_HEAD_MIN_STEPS = 3
STOP_HEAD_THRESHOLD = 0.5
# FlowLoss sampling defaults
DEFAULT_CFG = 2.0
DEFAULT_SIGMA = 0.25
DEFAULT_TEMPERATURE = 0.0
# Connector / Stage-2 streaming defaults (runtime tuning)
LATENT_CHUNK_SIZE = 25
LATENT_LEFT_CONTEXT = 0
MAX_DECODE_STEPS = 200
# ---------------------------------------------------------------------------
# seq_data.extra_data keys
# ---------------------------------------------------------------------------
KEY_LATENT_HISTORY = "ming_latent_history"
KEY_DECODE_STEP = "ming_decode_step"
KEY_LAST_STOP_PROB = "ming_last_stop_prob"
KEY_NEXT_EMBEDS = "ming_next_embeds"
KEY_PROMPT_LATENTS = "ming_prompt_latents"
KEY_PROMPT_LATENT_TAIL = "ming_prompt_latent_tail"
KEY_SPEAKER_EMBEDDING = "ming_speaker_embedding"
KEY_REQUEST_ID = "ming_request_id"
KEY_CHUNK_ID = "ming_chunk_id"
KEY_CFG = "ming_cfg"
KEY_SIGMA = "ming_sigma"
KEY_TEMPERATURE = "ming_temperature"
KEY_MAX_DECODE_STEPS = "ming_max_decode_steps"
KEY_MIN_DECODE_STEPS = "ming_min_decode_steps"
KEY_TEXT_MODE = "ming_text_mode"
@@ -0,0 +1,63 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Adopted from https://github.com/inclusionAI/Ming-omni-tts/blob/main/fm/flowloss.py
import torch
import torch.nn as nn
from vllm_omni.model_executor.models.common.ming.fm import Solver, build_timesteps
from .fm.dit import DiT
class FlowLoss(nn.Module):
"""Diffusion Loss"""
def __init__(self, z_channels, llm_cond_dim, **kwargs):
super().__init__()
self.z_channels = z_channels
# Preserve checkpoint parameter names under flowloss.cfm.model.* while
# keeping the inference-only CFM sampling logic local to FlowLoss.
self.cfm = nn.Module()
self.cfm.add_module("model", DiT(in_channels=z_channels, llm_cond_dim=llm_cond_dim, **kwargs))
@torch.no_grad()
def sample(self, z, latent_history, cfg=2.0, patch_size=1, sigma=0.25, temperature=0):
# z: [Batch, Time=1, Dimension]
# latent_history: [Batch, History_Time, Dimension]
if z.ndim != 3:
raise ValueError(f"Expected conditioning rank-3 [Batch, Time, Dimension], got {tuple(z.shape)}")
if latent_history.ndim != 3:
raise ValueError(
f"Expected latent_history rank-3 [Batch, Time, Dimension], got {tuple(latent_history.shape)}"
)
if z.shape[0] != latent_history.shape[0]:
raise ValueError(
f"Batch mismatch across conditioning and latent_history: {z.shape[0]}, {latent_history.shape[0]}"
)
dtype = z.dtype
noise = torch.randn(z.shape[0], self.z_channels, patch_size, device=z.device, dtype=torch.float32)
def fn(t, x):
x = x.to(dtype)
t = t.to(dtype)
if cfg < 1e-5:
if t.ndim == 0:
t = t.repeat(x.shape[0])
pred = self.cfm.model(x=x, t=t, c=torch.zeros_like(z), latent_history=latent_history)
return pred[:, -patch_size:, :].float()
pred_cfg = self.cfm.model.forward_with_cfg(
x=x, t=t, c=z, latent_history=latent_history, cfg_scale=cfg, patch_size=patch_size
)
pred, null_pred = torch.chunk(pred_cfg, 2, dim=0)
return (pred + (pred - null_pred) * cfg).float()
t = build_timesteps(
10,
device=noise.device,
dtype=noise.dtype,
use_epss=True,
sway_sampling_coef=-1.0,
)
return Solver(fn, noise.transpose(1, 2), sigma=sigma, temperature=temperature).integrate(t)[-1].to(dtype)
@@ -0,0 +1,2 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
@@ -0,0 +1,98 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Adopted from https://github.com/inclusionAI/Ming-omni-tts/blob/main/fm/dit.py
import torch
import torch.nn as nn
from x_transformers.x_transformers import RotaryEmbedding
from vllm_omni.model_executor.layers.timestep_embedding import DiTTimestepEmbedding
from vllm_omni.model_executor.models.common.ming.dit import CondEmbedder, DiTBlock, FinalLayer
class DiT(nn.Module):
def __init__(
self,
in_channels=4,
hidden_size=1024,
depth=28,
num_heads=16,
mlp_ratio=4.0,
llm_cond_dim=896,
**kwargs,
):
super().__init__()
self.in_channels = in_channels
self.out_channels = in_channels
self.num_heads = num_heads
self.t_embedder = DiTTimestepEmbedding(hidden_size)
self.x_embedder = nn.Linear(in_channels, hidden_size)
self.c_embedder = CondEmbedder(llm_cond_dim, hidden_size)
self.hidden_size = hidden_size
self.rotary_embed = RotaryEmbedding(hidden_size // num_heads)
self.blocks = nn.ModuleList(
[DiTBlock(hidden_size, num_heads, mlp_ratio=mlp_ratio, **kwargs) for _ in range(depth)]
)
self.final_layer = FinalLayer(hidden_size, self.out_channels)
def forward(self, x, t, c, latent_history, mask=None):
if x.ndim != 3:
raise ValueError(f"Expected x rank-3 [Batch, Time, Dimension], got {tuple(x.shape)}")
if latent_history.ndim != 3:
raise ValueError(
f"Expected latent_history rank-3 [Batch, Time, Dimension], got {tuple(latent_history.shape)}"
)
if c.ndim != 3:
raise ValueError(f"Expected conditioning rank-3 [Batch, Time, Dimension], got {tuple(c.shape)}")
if x.shape[0] != latent_history.shape[0] or x.shape[0] != c.shape[0]:
raise ValueError(
"Batch mismatch across x, conditioning, and latent_history: "
f"{x.shape[0]}, {c.shape[0]}, {latent_history.shape[0]}"
)
if x.shape[-1] != self.in_channels:
raise ValueError(f"x feature dim mismatch: got {x.shape[-1]}, expected {self.in_channels}")
if latent_history.shape[-1] != self.in_channels:
raise ValueError(
f"latent_history feature dim mismatch: got {latent_history.shape[-1]}, expected {self.in_channels}"
)
if t.ndim == 0:
t = t.reshape(1)
if t.ndim != 1:
raise ValueError(f"Expected timestep rank-1 [Batch], got {tuple(t.shape)}")
if t.shape[0] != x.shape[0]:
raise ValueError(f"Timestep batch mismatch: got {t.shape[0]}, expected {x.shape[0]}")
t = self.t_embedder(t).unsqueeze(1)
x_now = self.x_embedder(x)
x_history = self.x_embedder(latent_history)
x = torch.cat([x_history, x_now], dim=1)
c = self.c_embedder(c)
y = t + c
x = torch.cat([y, x], dim=1)
rope = self.rotary_embed.forward_from_seq_len(x.shape[1])
if mask is not None:
if mask.ndim != 2:
raise ValueError(f"Expected mask rank-2 [Batch, Time], got {tuple(mask.shape)}")
if mask.shape[0] != x_now.shape[0] or mask.shape[1] != x_now.shape[1]:
raise ValueError(
f"Mask shape mismatch: got {tuple(mask.shape)}, expected {(x_now.shape[0], x_now.shape[1])}"
)
mask_pad = mask.clone().detach()[:, :1].expand(-1, x_history.shape[1] + c.shape[1])
mask = torch.cat([mask_pad, mask], dim=-1)
for block in self.blocks:
x = block(x, mask, rope)
x = self.final_layer(x)
return x
def forward_with_cfg(self, x, t, c, cfg_scale, latent_history, patch_size):
if not cfg_scale == 1:
x = torch.cat([x, x], dim=0)
latent_history = torch.cat([latent_history, latent_history], dim=0)
fake_latent = torch.zeros_like(c)
c = torch.cat([c, fake_latent], dim=0)
if t.ndim == 0:
t = t.repeat(x.shape[0])
model_out = self.forward(x, t, c, latent_history)
return model_out[:, -patch_size:, :]
@@ -0,0 +1,269 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
from collections.abc import Iterable
from functools import cached_property
from typing import Any
import torch
import torch.nn as nn
from vllm.config import VllmConfig
from vllm.model_executor.models import SupportsPP
from vllm.model_executor.models.utils import init_vllm_registered_model
from vllm.v1.sample.sampler import Sampler
from vllm_omni.model_executor.custom_process_mixin import CustomProcessMixin
from .audio_prep import (
_coerce_prompt_latents,
_find_audio_placeholder_positions,
_find_speaker_placeholder_positions,
_initial_history,
_take_scalar,
coerce_speaker_embeddings,
)
from .config_ming_tts import (
AUDIO_START_TOKEN_ID,
KEY_CFG,
KEY_DECODE_STEP,
KEY_LAST_STOP_PROB,
KEY_LATENT_HISTORY,
KEY_MAX_DECODE_STEPS,
KEY_MIN_DECODE_STEPS,
KEY_NEXT_EMBEDS,
KEY_PROMPT_LATENT_TAIL,
KEY_REQUEST_ID,
KEY_SIGMA,
KEY_SPEAKER_EMBEDDING,
KEY_TEMPERATURE,
KEY_TEXT_MODE,
MingTTSConfig,
)
from .patch_emission import MING_STOP_REASON_KEY
from .prompt_encoder import _resolve_prompt_latents
class _ModelSampleAdapter(nn.Module):
def __init__(self, model: nn.Module):
super().__init__()
self.model = model
def forward(self, logits, sampling_metadata):
return self.model.sample(logits, sampling_metadata)
class MingTTSForConditionalGeneration(nn.Module, SupportsPP, CustomProcessMixin):
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
super().__init__()
del prefix
self.vllm_config = vllm_config
self.ming_config = MingTTSConfig.from_hf_config(vllm_config.model_config.hf_config)
self.ming_config.validate()
self.have_multimodal_outputs = True
self.has_preprocess = False
self.has_postprocess = False
self.requires_raw_input_tokens = False
self.model_stage = vllm_config.model_config.model_stage
self._prompt_encoder = None
if self.model_stage == "llm":
self.model = init_vllm_registered_model(vllm_config=vllm_config, architectures=["MingLLMModel"])
self.has_preprocess = True
self.has_postprocess = True
self.set_custom_preprocess(self.preprocess)
self.set_custom_postprocess(self.postprocess)
elif self.model_stage == "audio_vae":
self.model = init_vllm_registered_model(vllm_config=vllm_config, architectures=["MingAudioVAEModel"])
self.requires_raw_input_tokens = True
else:
raise ValueError(f"Invalid Ming model_stage={self.model_stage}")
self.make_empty_intermediate_tensors = getattr(self.model, "make_empty_intermediate_tensors", lambda: None)
@cached_property
def sampler(self):
if hasattr(self.model, "sample"):
return _ModelSampleAdapter(self.model)
if hasattr(self.model, "sampler"):
return self.model.sampler
return Sampler()
def embed_input_ids(self, input_ids: torch.Tensor, **kwargs: Any) -> torch.Tensor:
return self.model.embed_input_ids(input_ids=input_ids, **kwargs)
def forward(self, *args: Any, **kwargs: Any):
return self.model(*args, **kwargs)
def compute_logits(self, hidden_states, sampling_metadata=None):
return self.model.compute_logits(hidden_states, sampling_metadata=sampling_metadata)
def sample(self, logits, sampling_metadata):
return self.model.sample(logits, sampling_metadata) if hasattr(self.model, "sample") else None
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
weights = list(weights)
if self.model_stage == "llm":
allowed = ("model.", "linear_proj_audio.", "flowloss.", "stop_head.", "spk_head.")
llm_weights = [(k, v) for k, v in weights if k.startswith(allowed)]
if not llm_weights:
raise RuntimeError(
"Ming Stage-0 received no loadable checkpoint weights. "
"Expected prefixes: model.*, linear_proj_audio.*, flowloss.*, stop_head.*, spk_head.*"
)
loaded = self.model.load_weights(llm_weights)
return {f"model.{name}" for name in loaded}
audio_weights = [(k, v) for k, v in weights if k.startswith("audio.")]
if not audio_weights:
raise RuntimeError("Ming Stage-1 received no loadable checkpoint weights. Expected prefix: audio.*")
loaded = self.model.load_weights(audio_weights)
return {f"model.{name}" for name in loaded}
def _resolve_prompt_latents(self, info_dict: dict[str, Any]):
return _resolve_prompt_latents(self, info_dict)
def preprocess(self, input_ids: torch.Tensor, input_embeds: torch.Tensor | None, **info_dict: Any):
if self.model_stage != "llm":
return input_ids, input_embeds, {}
input_embeds = self.model.embed_input_ids(input_ids).clone()
return (
self._prefill_preprocess(input_ids, input_embeds, **info_dict)
if int(input_ids.shape[0]) > 1
else self._decode_preprocess(input_ids, input_embeds, **info_dict)
)
def postprocess(self, hidden_states: torch.Tensor, **info_dict: Any) -> dict[str, Any]:
if self.model_stage != "llm" or hidden_states.numel() == 0:
return {}
req_id = info_dict.get(KEY_REQUEST_ID, info_dict.get("request_id"))
pending = self.model.pop_postprocess_update(req_id)
if not pending or not isinstance(pending.get("ming_latent_patch"), torch.Tensor):
return {}
update = {
KEY_LATENT_HISTORY: pending[KEY_LATENT_HISTORY].detach().to("cpu").contiguous(),
KEY_NEXT_EMBEDS: pending[KEY_NEXT_EMBEDS].detach().to("cpu").contiguous(),
KEY_DECODE_STEP: int(info_dict.get(KEY_DECODE_STEP, 0)) + 1,
}
stop_prob = _take_scalar(pending.get("ming_stop_prob"), 0)
if stop_prob is not None:
update[KEY_LAST_STOP_PROB] = stop_prob
stop_reason = pending.get(MING_STOP_REASON_KEY)
if isinstance(stop_reason, str):
update[MING_STOP_REASON_KEY] = stop_reason
if isinstance(req_id, str):
update[KEY_REQUEST_ID] = req_id
return update
def _prefill_preprocess(self, input_ids: torch.Tensor, input_embeds: torch.Tensor, **info_dict: Any):
if bool(info_dict.get(KEY_TEXT_MODE, False)):
update: dict[str, Any] = {KEY_TEXT_MODE: True}
request_id = info_dict.get(KEY_REQUEST_ID, info_dict.get("request_id"))
if request_id is not None:
update[KEY_REQUEST_ID] = request_id
if int(input_ids.shape[0]) > 1 and int(input_ids[-1].item()) == AUDIO_START_TOKEN_ID:
return input_ids[:-1], input_embeds[:-1], update
return input_ids, input_embeds, update
update: dict[str, Any] = {KEY_DECODE_STEP: int(info_dict.get(KEY_DECODE_STEP, 0))}
prompt_latents = _resolve_prompt_latents(self, info_dict)
history = _initial_history(
prompt_latents["frames"] if prompt_latents is not None else None,
history_size=self.ming_config.history_patch_size,
latent_dim=self.ming_config.latent_dim,
device=input_embeds.device,
dtype=torch.float32,
)
update[KEY_LATENT_HISTORY] = history.detach().to("cpu").contiguous()
update[KEY_PROMPT_LATENT_TAIL] = update[KEY_LATENT_HISTORY]
speaker_embedding = info_dict.get(KEY_SPEAKER_EMBEDDING, info_dict.get("speaker_embedding"))
speaker_embeddings = None
if speaker_embedding is not None:
speaker_embeddings = coerce_speaker_embeddings(
speaker_embedding,
use_zero_spk_emb=bool(info_dict.get("use_zero_spk_emb", False)),
)
if speaker_embeddings is not None and len(speaker_embeddings) > 0:
speaker_slots = _find_speaker_placeholder_positions(input_ids, self.vllm_config.model_config.hf_config)
if len(speaker_slots) < len(speaker_embeddings):
raise RuntimeError(
"Could not locate enough speaker placeholder slots: "
f"found {len(speaker_slots)}, need {len(speaker_embeddings)}"
)
for speaker_slot, spk in zip(speaker_slots, speaker_embeddings):
spk_proj = self.model.project_speaker_embedding(
spk.to(device=input_embeds.device, dtype=input_embeds.dtype).unsqueeze(0)
).squeeze(0)
input_embeds[speaker_slot] = spk_proj
if prompt_latents is not None and prompt_latents["patches"] is not None:
prompt_patches = prompt_latents["patches"].to(dtype=getattr(self.model, "fm_dtype", torch.float32))
prompt_embeds = self.model.linear_proj_audio(prompt_patches).squeeze(1)
placeholder_pos = _find_audio_placeholder_positions(input_ids, self.ming_config)
take = min(int(placeholder_pos.numel()), int(prompt_embeds.shape[0]))
if take > 0:
input_embeds[placeholder_pos[:take]] = prompt_embeds[:take].to(dtype=input_embeds.dtype)
request_id = info_dict.get(KEY_REQUEST_ID, info_dict.get("request_id"))
if request_id is not None:
update[KEY_REQUEST_ID] = request_id
_copy_runtime_controls(update, info_dict)
return input_ids, input_embeds, update
def _decode_preprocess(self, input_ids: torch.Tensor, input_embeds: torch.Tensor, **info_dict: Any):
if bool(info_dict.get(KEY_TEXT_MODE, False)):
update: dict[str, Any] = {KEY_TEXT_MODE: True}
request_id = info_dict.get(KEY_REQUEST_ID, info_dict.get("request_id"))
if request_id is not None:
update[KEY_REQUEST_ID] = request_id
return input_ids, input_embeds, update
update: dict[str, Any] = {KEY_DECODE_STEP: int(info_dict.get(KEY_DECODE_STEP, 0))}
history = info_dict.get(KEY_LATENT_HISTORY)
if isinstance(history, torch.Tensor):
update[KEY_LATENT_HISTORY] = history.detach().to("cpu").contiguous()
else:
zero_history = torch.zeros(
(self.ming_config.history_patch_size, self.ming_config.latent_dim),
device=input_embeds.device,
dtype=torch.float32,
)
update[KEY_LATENT_HISTORY] = zero_history.detach().to("cpu").contiguous()
next_embeds = info_dict.get(KEY_NEXT_EMBEDS)
if isinstance(next_embeds, torch.Tensor) and input_ids.numel() == 1:
if not torch.isfinite(next_embeds).all():
raise RuntimeError("Non-finite next_embeds before decode preprocess write.")
input_embeds[0] = (
next_embeds.detach()
.reshape(-1, self.ming_config.llm_hidden_size)[0]
.to(
device=input_embeds.device,
dtype=input_embeds.dtype,
)
)
if not torch.isfinite(input_embeds[0]).all():
raise RuntimeError("Non-finite backbone input_embeds after decode preprocess write.")
request_id = info_dict.get(KEY_REQUEST_ID, info_dict.get("request_id"))
if request_id is not None:
update[KEY_REQUEST_ID] = request_id
_copy_runtime_controls(update, info_dict)
return input_ids, input_embeds, update
def _copy_runtime_controls(update: dict[str, Any], info_dict: dict[str, Any]) -> None:
for key in (KEY_CFG, KEY_SIGMA, KEY_TEMPERATURE, KEY_MAX_DECODE_STEPS, KEY_MIN_DECODE_STEPS):
if key in info_dict:
update[key] = info_dict[key]
__all__ = [
"MingTTSForConditionalGeneration",
"_ModelSampleAdapter",
"_coerce_prompt_latents",
"_find_audio_placeholder_positions",
"_find_speaker_placeholder_positions",
"_initial_history",
]
@@ -0,0 +1,389 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Adopted from https://github.com/inclusionAI/Ming-omni-tts/blob/main/audio_tokenizer/modeling_audio_vae.py
from __future__ import annotations
import os
import time
import warnings
from collections import OrderedDict
from collections.abc import Iterable
from typing import Any
import torch
import torch.nn as nn
from vllm.config import VllmConfig
from vllm.logger import init_logger
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
from vllm_omni.model_executor.models.common.ming.audio_vae import AudioVAE
from vllm_omni.model_executor.models.output_templates import OmniOutput
from .config_ming_tts import KEY_CHUNK_ID, KEY_REQUEST_ID, MingTTSConfig
from .patch_emission import MING_STOP_REASON_KEY
logger = init_logger(__name__)
MING_FINAL_DECODE_STEP_KEY = "ming_final_decode_step"
_STREAM_STATE_TTL_SECONDS = 15 * 60
_MAX_STREAM_STATES = 1024
class MingAudioVAEModel(nn.Module):
input_modalities = "audio"
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
super().__init__()
del prefix
self.vllm_config = vllm_config
self.ming_config = MingTTSConfig.from_hf_config(vllm_config.model_config.hf_config)
if self.ming_config.audio_tokenizer_config is None:
raise ValueError("MingAudioVAEModel requires audio_tokenizer_config")
self.ming_config.validate()
self.audio = AudioVAE(self.ming_config.audio_tokenizer_config)
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
self._past_key_values: dict[str, Any] = {}
self._stream_state: dict[str, tuple[Any, Any, Any]] = {}
self._patch_totals: dict[str, int] = {}
self._sample_totals: dict[str, int] = {}
self._state_access_times: OrderedDict[str, float] = OrderedDict()
def embed_input_ids(self, input_ids: torch.Tensor, **_: Any) -> torch.Tensor:
hidden_size = int(self.ming_config.llm_hidden_size)
if input_ids is None or input_ids.numel() == 0:
return torch.empty((0, hidden_size), device=self.vllm_config.device_config.device, dtype=torch.float32)
return torch.zeros((input_ids.shape[0], hidden_size), device=input_ids.device, dtype=torch.float32)
def compute_logits(self, hidden_states: torch.Tensor | OmniOutput, sampling_metadata: Any = None) -> None:
del hidden_states, sampling_metadata
return None
def chunked_decode_streaming(
self,
latent_chunk: torch.Tensor,
*,
request_id: str,
finished: bool,
) -> tuple[torch.Tensor, Any, Any, bool, bool]:
had_past_key_values = request_id in self._past_key_values
had_stream_state = _has_stream_state(self._stream_state.get(request_id))
stream_state = self._stream_state.get(request_id, (None, None, None))
past_key_values = self._past_key_values.get(request_id)
waveform_parts: list[torch.Tensor] = []
patch_count = int(latent_chunk.shape[0])
for patch_idx in range(patch_count):
# [Batch, Time, Dimension] = [1, patch_size, latent_dim]
latent_patch = latent_chunk[patch_idx : patch_idx + 1]
is_last_patch = finished and patch_idx == patch_count - 1
waveform, stream_state, past_key_values = self.audio.decode(
latent_patch,
past_key_values=past_key_values,
use_cache=True,
stream_state=stream_state,
last_chunk=is_last_patch,
)
waveform_parts.append(waveform.reshape(-1).to(torch.float32))
waveform_flat = (
torch.cat(waveform_parts, dim=0)
if waveform_parts
else torch.zeros((0,), dtype=torch.float32, device=latent_chunk.device)
)
return waveform_flat, stream_state, past_key_values, had_past_key_values, had_stream_state
@torch.inference_mode()
def forward(
self,
input_ids: torch.Tensor | None = None,
positions: torch.Tensor | None = None,
intermediate_tensors: Any = None,
inputs_embeds: torch.Tensor | None = None,
model_intermediate_buffer: list[dict[str, Any]] | None = None,
**kwargs: Any,
) -> OmniOutput:
del input_ids, positions, intermediate_tensors, inputs_embeds
info_list = model_intermediate_buffer if isinstance(model_intermediate_buffer, list) else None
if info_list is None:
runtime_infos = kwargs.get("runtime_additional_information")
info_list = runtime_infos if isinstance(runtime_infos, list) else None
info_list = info_list or [{}]
num_reqs = max(len(info_list), 1)
sr_tensor = torch.tensor(int(self.ming_config.sample_rate), dtype=torch.int32)
empty = torch.zeros((0,), dtype=torch.float32, device=self.vllm_config.device_config.device)
outputs: list[torch.Tensor] = []
srs: list[torch.Tensor] = []
for idx in range(num_reqs):
info = info_list[idx] if idx < len(info_list) and isinstance(info_list[idx], dict) else {}
meta = info.get("meta") or {}
kv_meta = info.get("kv_metadata") or {}
has_ming_context = _has_ming_context(info)
if has_ming_context and KEY_REQUEST_ID not in info and KEY_REQUEST_ID not in kv_meta:
raise RuntimeError(
f"Ming Stage-2 received a payload without {KEY_REQUEST_ID}. keys={sorted(info.keys())}"
)
request_id = _resolve_request_id(info, idx)
self._touch_request_state(request_id)
chunk_id = _coerce_optional_int(_first_present(info.get(KEY_CHUNK_ID), kv_meta.get(KEY_CHUNK_ID)))
finished = _coerce_finished(
_first_present(
meta.get("stream_finished"),
meta.get("finished"),
info.get("stream_finished"),
kv_meta.get("stream_finished"),
torch.tensor(True),
)
)
latent = _first_present(
info.get("latent"),
info.get("ming_latent_patches"),
kv_meta.get("ming_latent_patches"),
)
stripped = bool(
_first_present(
meta.get("_ming_payload_stripped"),
info.get("_ming_payload_stripped"),
kv_meta.get("_ming_payload_stripped"),
False,
)
)
if stripped:
raise RuntimeError(
"Ming Stage-2 payload was stripped before model entry. "
f"request_id={request_id} chunk_id={chunk_id} keys={sorted(info.keys())}"
)
if latent is None:
if has_ming_context and not finished:
raise RuntimeError(
"Ming Stage-2 received no latent chunk for an unfinished request. "
f"request_id={request_id} chunk_id={chunk_id} keys={sorted(info.keys())}"
)
if finished:
self._clear_request_state(request_id)
outputs.append(empty)
srs.append(sr_tensor)
continue
latent_tensor = _coerce_latent_chunk(
latent,
device=self.vllm_config.device_config.device,
dtype=next(self.audio.parameters()).dtype,
latent_dim=self.ming_config.latent_dim,
patch_size=self.ming_config.patch_size,
)
if latent_tensor is None or latent_tensor.numel() == 0:
if not finished:
raise RuntimeError(
"Ming Stage-2 received an empty latent chunk before final flush. "
f"request_id={request_id} chunk_id={chunk_id} latent_shape={_shape_of(latent_tensor)}"
)
if finished:
self._clear_request_state(request_id)
outputs.append(empty)
srs.append(sr_tensor)
continue
patch_count = int(latent_tensor.shape[0])
waveform_flat, stream_state, past_key_values, had_past_key_values, had_stream_state = (
self.chunked_decode_streaming(
latent_tensor,
request_id=request_id,
finished=finished,
)
)
total_patch_count = self._patch_totals.get(request_id, 0) + patch_count
total_waveform_numel = self._sample_totals.get(request_id, 0) + int(waveform_flat.numel())
self._patch_totals[request_id] = total_patch_count
self._sample_totals[request_id] = total_waveform_numel
if (had_past_key_values or had_stream_state) and waveform_flat.numel() == 0 and not finished:
raise RuntimeError(
"Ming Stage-2 produced an empty waveform after cached streaming state already existed. "
f"request_id={request_id} chunk_id={chunk_id} latent_shape={tuple(latent_tensor.shape)} "
f"had_past_key_values={had_past_key_values} had_stream_state={had_stream_state}"
)
if finished:
if os.environ.get("MING_TTS_STAGE1_FINAL_LOG") == "1":
logger.info(
"MING_STAGE1_FINAL %s",
{
"request_id": request_id,
"chunk_id": chunk_id,
"stop_reason": _first_present(
info.get(MING_STOP_REASON_KEY),
kv_meta.get(MING_STOP_REASON_KEY),
),
"final_decode_step": _coerce_optional_int(
_first_present(
info.get(MING_FINAL_DECODE_STEP_KEY),
kv_meta.get(MING_FINAL_DECODE_STEP_KEY),
)
),
"final_chunk_patch_count": patch_count,
"total_patch_count": total_patch_count,
"final_chunk_waveform_numel": int(waveform_flat.numel()),
"total_waveform_numel": total_waveform_numel,
},
)
self._clear_request_state(request_id)
else:
self._past_key_values[request_id] = past_key_values
self._stream_state[request_id] = stream_state
outputs.append(waveform_flat)
srs.append(sr_tensor)
return OmniOutput(
text_hidden_states=None,
multimodal_outputs={
"model_outputs": outputs,
"sr": srs,
},
)
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
weights = list(weights)
if not weights:
raise RuntimeError("MingAudioVAEModel received no checkpoint weights.")
params_dict = dict(self.named_parameters(remove_duplicate=False))
loaded: set[str] = set()
skipped: list[str] = []
for name, loaded_weight in weights:
if name not in params_dict:
skipped.append(name)
continue
param = params_dict[name]
weight_loader = getattr(param, "weight_loader", default_weight_loader)
weight_loader(param, loaded_weight)
loaded.add(name)
missing = {name for name in params_dict if name.startswith("audio.")} - loaded
if missing:
raise RuntimeError(f"MingAudioVAEModel: {len(missing)} params not loaded. First few: {sorted(missing)[:5]}")
if skipped:
warnings.warn(
f"MingAudioVAEModel: skipped {len(skipped)} checkpoint keys during load. First few: {skipped[:8]}",
stacklevel=2,
)
return loaded
def _clear_request_state(self, request_id: str) -> None:
self._past_key_values.pop(request_id, None)
self._stream_state.pop(request_id, None)
self._patch_totals.pop(request_id, None)
self._sample_totals.pop(request_id, None)
self._state_access_times.pop(request_id, None)
def _touch_request_state(self, request_id: str) -> None:
now = time.monotonic()
self._evict_expired_request_states(now)
self._state_access_times[request_id] = now
self._state_access_times.move_to_end(request_id)
while len(self._state_access_times) > _MAX_STREAM_STATES:
evicted_request_id, _ = self._state_access_times.popitem(last=False)
self._clear_request_state(evicted_request_id)
def _evict_expired_request_states(self, now: float) -> None:
cutoff = now - _STREAM_STATE_TTL_SECONDS
while self._state_access_times:
request_id, last_access = next(iter(self._state_access_times.items()))
if last_access >= cutoff:
break
self._clear_request_state(request_id)
def _coerce_finished(value: Any) -> bool:
if isinstance(value, torch.Tensor):
if value.numel() == 0:
return False
return bool(value.reshape(-1)[0].item())
return bool(value)
def _first_present(*values: Any) -> Any:
for value in values:
if value is not None:
return value
return None
def _coerce_optional_int(value: Any, default: int | None = None) -> int | None:
if value is None:
return default
if isinstance(value, list):
value = value[0] if value else default
if isinstance(value, torch.Tensor):
if value.numel() == 0:
return default
return int(value.reshape(-1)[0].item())
try:
return int(value)
except (TypeError, ValueError):
return default
def _resolve_request_id(info: dict[str, Any], idx: int) -> str:
kv_meta = info.get("kv_metadata") or {}
request_id = info.get(KEY_REQUEST_ID) or kv_meta.get(KEY_REQUEST_ID)
if request_id is None:
return str(idx)
if not isinstance(request_id, str) or not request_id:
raise RuntimeError(f"Ming Stage-2 received invalid request id: {request_id!r}")
return request_id
def _has_ming_context(info: dict[str, Any]) -> bool:
kv_meta = info.get("kv_metadata") or {}
keys = (
KEY_REQUEST_ID,
KEY_CHUNK_ID,
"ming_latent_patches",
"_ming_payload_stripped",
)
return any(key in info or key in kv_meta for key in keys) or "latent" in info
def _shape_of(value: Any) -> tuple[int, ...] | None:
if isinstance(value, torch.Tensor):
return tuple(value.shape)
return None
def _has_stream_state(value: Any) -> bool:
if not isinstance(value, tuple):
return False
return any(item is not None for item in value)
def _coerce_latent_chunk(
value: Any,
*,
device: torch.device,
dtype: torch.dtype,
latent_dim: int,
patch_size: int,
) -> torch.Tensor | None:
if not isinstance(value, torch.Tensor):
value = torch.as_tensor(value)
latent = value.detach()
if latent.ndim == 2:
latent = latent.unsqueeze(0)
if latent.ndim != 3:
raise ValueError(f"Expected latent chunk rank-3 [Batch, Time, Dimension], got {tuple(latent.shape)}")
if latent.shape[-2] != patch_size:
raise ValueError(f"Latent patch size mismatch: got {latent.shape[-2]}, expected {patch_size}")
if latent.shape[-1] != latent_dim:
raise ValueError(f"Latent dim mismatch: got {latent.shape[-1]}, expected {latent_dim}")
return latent.to(device=device, dtype=dtype)
@@ -0,0 +1,414 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Adopted from https://github.com/inclusionAI/Ming-omni-tts/blob/main/modeling_bailingmm.py
from __future__ import annotations
import warnings
from collections.abc import Iterable
from typing import Any
import torch
import torch.nn as nn
from vllm.config import VllmConfig
from vllm.logger import init_logger
from vllm.model_executor.models.qwen2 import Qwen2Model
from vllm.model_executor.models.utils import AutoWeightsLoader, WeightsMapper, maybe_prefix
from vllm.sequence import IntermediateTensors
from vllm.v1.outputs import SamplerOutput
from vllm.v1.sample.metadata import SamplingMetadata
from vllm_omni.model_executor.models.output_templates import OmniOutput
from .aggregator import Aggregator
from .config_ming_tts import (
KEY_CFG,
KEY_DECODE_STEP,
KEY_LATENT_HISTORY,
KEY_MAX_DECODE_STEPS,
KEY_MIN_DECODE_STEPS,
KEY_NEXT_EMBEDS,
KEY_REQUEST_ID,
KEY_SIGMA,
KEY_TEMPERATURE,
KEY_TEXT_MODE,
MingTTSConfig,
)
from .flowloss_head import FlowLoss
from .patch_emission import (
MING_STOP_REASON_CODES,
MING_STOP_REASON_CONTINUE,
MING_STOP_REASON_KEY,
MING_STOP_REASON_MAX_DECODE_STEPS,
MING_STOP_REASON_STOP_HEAD,
_coerce_latent_history,
_get_request_token_counts,
_normalize_request_infos,
_resolve_ming_stop_decision,
_resolve_optional_runtime_int,
_resolve_runtime_float,
_resolve_runtime_int,
_validate_ming_decode_window,
)
logger = init_logger(__name__)
class MingLLMModel(nn.Module):
hf_to_vllm_mapper = WeightsMapper(
orig_to_new_prefix={
"model.model.": "model.",
}
)
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
super().__init__()
self.ming_config = MingTTSConfig.from_hf_config(vllm_config.model_config.hf_config)
self.ming_config.validate()
self.vllm_config = vllm_config
self.prefix = prefix
self.fm_dtype = _resolve_ming_runtime_dtype(vllm_config)
self.model = Qwen2Model(vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model"))
self.linear_proj_audio = Aggregator(
in_channels=self.ming_config.latent_dim,
llm_input_dim=self.ming_config.llm_hidden_size,
**self.ming_config.aggregator_config,
)
self.flowloss = FlowLoss(
z_channels=self.ming_config.latent_dim,
llm_cond_dim=self.ming_config.llm_hidden_size,
**self.ming_config.ditar_config,
)
self.stop_head = nn.Linear(self.ming_config.llm_hidden_size, 2, bias=True)
self.spk_head = nn.Linear(192, self.ming_config.llm_hidden_size, bias=True)
self.flowloss.to(dtype=self.fm_dtype)
self.linear_proj_audio.to(dtype=self.fm_dtype)
self.stop_head.to(dtype=self.fm_dtype)
self.spk_head.to(dtype=self.fm_dtype)
self._pending_postprocess_updates: dict[str, dict[str, Any]] = {}
self._last_ming_next_token_ids = None
self._last_text_mode = False
def embed_input_ids(
self, input_ids: torch.Tensor, inputs_embeds: torch.Tensor | None = None, **_: Any
) -> torch.Tensor:
if inputs_embeds is not None:
return inputs_embeds
return self.model.embed_input_ids(input_ids)
def project_speaker_embedding(self, spk_emb: torch.Tensor) -> torch.Tensor:
return self.spk_head(spk_emb)
def forward(
self,
input_ids: torch.Tensor,
positions: torch.Tensor,
intermediate_tensors: IntermediateTensors | None = None,
inputs_embeds: torch.Tensor | None = None,
latent_history: torch.Tensor | None = None,
model_intermediate_buffer: list[dict[str, Any]] | None = None,
seq_token_counts: list[int] | None = None,
**kwargs: object,
) -> OmniOutput | IntermediateTensors | torch.Tensor:
if inputs_embeds is None:
inputs_embeds = self.embed_input_ids(input_ids)
if model_intermediate_buffer is None:
model_intermediate_buffer = kwargs.get("runtime_additional_information")
request_infos = _normalize_request_infos(model_intermediate_buffer)
_validate_ming_decode_window(
request_infos,
min_stop_step=int(self.ming_config.stop_head_min_steps),
default_max_decode_steps=self.ming_config.max_decode_steps,
)
backbone_out = self.model(
input_ids=input_ids,
positions=positions,
intermediate_tensors=intermediate_tensors,
inputs_embeds=inputs_embeds,
)
if isinstance(backbone_out, IntermediateTensors):
self._last_ming_next_token_ids = None
return backbone_out
hidden_states = _extract_hidden_states(backbone_out)
token_counts = _get_request_token_counts(hidden_states, request_infos, seq_token_counts)
text_mode = bool(request_infos) and all(bool(info.get(KEY_TEXT_MODE, False)) for info in request_infos)
if request_infos and any(bool(info.get(KEY_TEXT_MODE, False)) for info in request_infos) and not text_mode:
raise RuntimeError("Mixed Ming text/audio modes in one Stage-0 batch are unsupported.")
if text_mode:
self._last_ming_next_token_ids = None
self._last_text_mode = True
return OmniOutput(
text_hidden_states=hidden_states,
multimodal_outputs={KEY_TEXT_MODE: True},
intermediate_tensors=intermediate_tensors,
)
self._last_text_mode = False
if latent_history is None and not token_counts:
self._last_ming_next_token_ids = None
return OmniOutput(
text_hidden_states=hidden_states, multimodal_outputs=None, intermediate_tensors=intermediate_tensors
)
if latent_history is not None and not token_counts:
token_counts, request_infos = [hidden_states.shape[0]], [{KEY_LATENT_HISTORY: latent_history}]
total_tokens = hidden_states.shape[0]
latent_patch_tokens = next_embed_tokens = new_history_tokens = None
decode_step_tokens = has_patch = stop_reason_code_tokens = None
next_token_ids = []
pending_updates: dict[str, dict[str, Any]] = {}
cursor = 0
any_decode = False
for req_idx, token_count in enumerate(token_counts):
end = min(cursor + token_count, total_tokens)
if end <= cursor:
continue
req_info = request_infos[req_idx] if req_idx < len(request_infos) else {}
req_id = req_info.get(KEY_REQUEST_ID)
req_history = _coerce_latent_history(
req_info.get(KEY_LATENT_HISTORY), device=hidden_states.device, dtype=self.fm_dtype, cfg=self.ming_config
)
if req_history is None:
cursor = end
continue
decode_step = int(req_info.get(KEY_DECODE_STEP, req_info.get("generated_len", 0)))
decode_hidden, output_index = (
(hidden_states[cursor:end], cursor) if token_count == 1 else (hidden_states[end - 1 : end], end - 1)
)
sampled_token_latent, next_embeds, new_history, stop_probs = self._decode_one_step(
hidden_states=decode_hidden,
latent_history=req_history,
cfg_scale=_resolve_runtime_float(req_info, KEY_CFG, self.ming_config.cfg),
sigma=_resolve_runtime_float(req_info, KEY_SIGMA, self.ming_config.sigma),
temperature=_resolve_runtime_float(req_info, KEY_TEMPERATURE, self.ming_config.temperature),
)
req_max_decode_steps = _resolve_runtime_int(
req_info, KEY_MAX_DECODE_STEPS, self.ming_config.max_decode_steps
)
req_min_decode_steps = _resolve_optional_runtime_int(req_info, KEY_MIN_DECODE_STEPS, 0)
if latent_patch_tokens is None:
latent_patch_tokens = sampled_token_latent.new_zeros(
(total_tokens, self.ming_config.patch_size, self.ming_config.latent_dim)
)
next_embed_tokens = next_embeds.new_zeros((total_tokens, 1, self.ming_config.llm_hidden_size))
new_history_tokens = new_history.new_zeros(
(total_tokens, self.ming_config.history_patch_size, self.ming_config.latent_dim)
)
decode_step_tokens = torch.zeros((total_tokens,), dtype=torch.int32, device=hidden_states.device)
has_patch = torch.zeros((total_tokens,), dtype=torch.bool, device=hidden_states.device)
stop_reason_code_tokens = torch.zeros((total_tokens,), dtype=torch.int32, device=hidden_states.device)
latent_patch_tokens[output_index : output_index + 1] = sampled_token_latent
next_embed_tokens[output_index : output_index + 1] = next_embeds
new_history_tokens[output_index : output_index + 1] = new_history
decode_step_tokens[output_index : output_index + 1] = decode_step
has_patch[output_index : output_index + 1] = True
stop_reason, _, _, _, next_token_id = _resolve_ming_stop_decision(
step=decode_step,
stop_prob=float(stop_probs.reshape(-1)[0].item()),
stop_threshold=float(self.ming_config.stop_head_threshold),
min_stop_step=int(self.ming_config.stop_head_min_steps),
min_decode_steps=req_min_decode_steps,
max_decode_steps=req_max_decode_steps,
audio_dummy_token_id=int(self.ming_config.audio_dummy_token_id),
text_eos_token_id=int(self.ming_config.text_eos_token_id),
)
stop_reason_code_tokens[output_index : output_index + 1] = MING_STOP_REASON_CODES[stop_reason]
next_token_ids.append(int(next_token_id))
if isinstance(req_id, str):
pending_updates[req_id] = {
KEY_LATENT_HISTORY: new_history,
KEY_NEXT_EMBEDS: next_embeds,
"ming_latent_patch": sampled_token_latent,
"ming_stop_prob": stop_probs,
MING_STOP_REASON_KEY: stop_reason,
}
any_decode = True
cursor = end
self._pending_postprocess_updates = pending_updates
if not any_decode:
self._last_ming_next_token_ids = None
return OmniOutput(
text_hidden_states=hidden_states, multimodal_outputs=None, intermediate_tensors=intermediate_tensors
)
self._last_ming_next_token_ids = next_token_ids
return OmniOutput(
text_hidden_states=hidden_states,
multimodal_outputs={
"ming_latent_patch": latent_patch_tokens,
"ming_next_embeds": next_embed_tokens,
"ming_new_history": new_history_tokens,
"ming_decode_step": decode_step_tokens,
"ming_has_patch": has_patch,
MING_STOP_REASON_KEY: stop_reason_code_tokens,
},
intermediate_tensors=intermediate_tensors,
)
def pop_postprocess_update(self, req_id: str) -> dict[str, Any]:
return self._pending_postprocess_updates.pop(req_id, {}) if isinstance(req_id, str) else {}
def compute_logits(self, hidden_states: torch.Tensor, sampling_metadata: SamplingMetadata) -> torch.Tensor | None:
del sampling_metadata
if self._last_text_mode:
return (
None
if hidden_states is None or hidden_states.numel() == 0
else self.model.compute_logits(hidden_states)
)
if hidden_states is None or hidden_states.numel() == 0:
return None
if hidden_states.dim() != 2:
raise RuntimeError(
f"Expected hidden_states rank-2 [B,H] in compute_logits, got {tuple(hidden_states.shape)}"
)
batch_size = hidden_states.shape[0]
next_token_ids = self._last_ming_next_token_ids
self._last_ming_next_token_ids = None
if next_token_ids is None:
logger.debug(
"Missing Ming forced next-token ids before compute_logits. "
"Using dummy next-token IDs (likely during a profiling or dummy run)."
)
next_token_ids = [int(self.ming_config.text_eos_token_id)] * batch_size
if len(next_token_ids) != batch_size:
raise RuntimeError(
"Ming forced next-token batch mismatch: "
f"got {len(next_token_ids)} ids for hidden_states batch {batch_size}."
)
logits = torch.full(
(batch_size, self.ming_config.llm_vocab_size),
float("-inf"),
device=hidden_states.device,
dtype=torch.float32,
)
for i, next_token_id in enumerate(next_token_ids):
logits[i, int(next_token_id)] = 0.0
return logits
def sample(self, logits, sampling_metadata):
if logits is None:
return None
if self._last_text_mode:
return self.model.sample(logits, sampling_metadata)
del sampling_metadata
return SamplerOutput(
sampled_token_ids=logits.argmax(dim=-1, keepdim=True).to(dtype=torch.int32),
logprobs_tensors=None,
)
def _decode_one_step(
self,
*,
hidden_states: torch.Tensor,
latent_history: torch.Tensor,
cfg_scale: float,
sigma: float,
temperature: float,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
if hidden_states.dim() != 2:
raise RuntimeError(f"Expected decode hidden_states rank-2 [B,H], got {tuple(hidden_states.shape)}")
if latent_history.dim() != 3:
raise RuntimeError(f"Expected latent_history rank-3 [B,T,D], got {tuple(latent_history.shape)}")
if hidden_states.shape[0] != latent_history.shape[0]:
raise RuntimeError(
"Batch mismatch: "
f"hidden_states B={hidden_states.shape[0]} "
f"vs latent_history B={latent_history.shape[0]}"
)
# [Batch, Hidden] -> [Batch, Time, Hidden] = [B, 1, H] for FlowLoss conditioning.
z_diff_cond = hidden_states.to(dtype=self.fm_dtype).unsqueeze(1)
if not torch.isfinite(z_diff_cond).all():
raise RuntimeError("Non-finite z_diff_cond before FlowLoss.sample().")
sampled_token_latent = self.flowloss.sample(
z=z_diff_cond,
latent_history=latent_history,
cfg=cfg_scale,
patch_size=self.ming_config.patch_size,
sigma=sigma,
temperature=temperature,
)
expected_shape = (hidden_states.shape[0], self.ming_config.patch_size, self.ming_config.latent_dim)
if tuple(sampled_token_latent.shape) != expected_shape:
raise RuntimeError(
f"FlowLoss output shape mismatch: got {tuple(sampled_token_latent.shape)}, expected {expected_shape}"
)
new_history = torch.cat([latent_history[:, self.ming_config.patch_size :, :], sampled_token_latent], dim=1)
# Aggregator expects [Batch, Time, Dimension] = [B, 4, 64] and returns [B, 1, H].
next_embeds = self.linear_proj_audio(sampled_token_latent)
stop_probs = self.stop_head(hidden_states.to(dtype=self.fm_dtype)).softmax(dim=-1)[:, 1]
if not torch.isfinite(sampled_token_latent).all():
raise RuntimeError("Non-finite sampled_token_latent in Ming decode step.")
if not torch.isfinite(next_embeds).all():
raise RuntimeError("Non-finite next_embeds in Ming decode step.")
if not torch.isfinite(stop_probs).all():
raise RuntimeError("Non-finite stop_probs in Ming decode step.")
return sampled_token_latent, next_embeds, new_history, stop_probs
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
params_dict = dict(self.named_parameters(remove_duplicate=False))
loaded_params = AutoWeightsLoader(self).load_weights(weights, mapper=self.hf_to_vllm_mapper)
_warn_missing_prefix("flowloss", params_dict, loaded_params, prefix="flowloss.", fatal=True)
_warn_missing_prefix("linear_proj_audio", params_dict, loaded_params, prefix="linear_proj_audio.", fatal=True)
_warn_missing_prefix("stop_head", params_dict, loaded_params, prefix="stop_head.", fatal=True)
_warn_missing_prefix("spk_head", params_dict, loaded_params, prefix="spk_head.", fatal=True)
return loaded_params
def _extract_hidden_states(backbone_out: object) -> torch.Tensor:
if isinstance(backbone_out, torch.Tensor):
return backbone_out
if hasattr(backbone_out, "last_hidden_state"):
return backbone_out.last_hidden_state
if isinstance(backbone_out, (tuple, list)) and backbone_out and isinstance(backbone_out[0], torch.Tensor):
return backbone_out[0]
raise TypeError(f"Unsupported backbone forward output type: {type(backbone_out)}")
def _resolve_ming_runtime_dtype(vllm_config: VllmConfig) -> torch.dtype:
dtype = getattr(vllm_config.model_config, "dtype", None)
if isinstance(dtype, torch.dtype):
return dtype
if isinstance(dtype, str):
normalized = dtype.strip().lower()
if normalized in ("float16", "half", "torch.float16"):
return torch.float16
if normalized in ("bfloat16", "bf16", "torch.bfloat16"):
return torch.bfloat16
if normalized in ("float32", "fp32", "torch.float32"):
return torch.float32
return torch.float32
def _warn_missing_prefix(
module_name: str,
params_dict: dict[str, nn.Parameter],
loaded_params: set[str],
prefix: str,
fatal: bool = False,
) -> None:
missing = {key for key in params_dict if key.startswith(prefix)} - loaded_params
if not missing:
return
msg = (
f"MingLLMModel: {len(missing)} {module_name} params not loaded "
f"(prefix={prefix}). First few: {sorted(missing)[:5]}"
)
if fatal:
raise RuntimeError(msg)
warnings.warn(msg, stacklevel=3)
__all__ = [
"Aggregator",
"FlowLoss",
"MING_STOP_REASON_CODES",
"MING_STOP_REASON_CONTINUE",
"MING_STOP_REASON_KEY",
"MING_STOP_REASON_MAX_DECODE_STEPS",
"MING_STOP_REASON_STOP_HEAD",
"MingLLMModel",
"_coerce_latent_history",
"_extract_hidden_states",
"_resolve_ming_runtime_dtype",
"_resolve_ming_stop_decision",
"_warn_missing_prefix",
]
@@ -0,0 +1,183 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Adopted from https://github.com/inclusionAI/Ming-omni-tts/blob/main/modeling_bailingmm.py
from __future__ import annotations
from typing import Any
import torch
from vllm.forward_context import get_forward_context, is_forward_context_available
from .config_ming_tts import KEY_MAX_DECODE_STEPS, KEY_MIN_DECODE_STEPS, KEY_REQUEST_ID, KEY_TEXT_MODE, MingTTSConfig
MING_STOP_REASON_CONTINUE = "continue"
MING_STOP_REASON_STOP_HEAD = "stop_head"
MING_STOP_REASON_MAX_DECODE_STEPS = "max_decode_steps"
MING_STOP_REASON_KEY = "ming_stop_reason"
MING_STOP_REASON_CODES = {
MING_STOP_REASON_CONTINUE: 0,
MING_STOP_REASON_STOP_HEAD: 1,
MING_STOP_REASON_MAX_DECODE_STEPS: 2,
}
def _normalize_request_infos(model_intermediate_buffer: object) -> list[dict[str, Any]]:
if not isinstance(model_intermediate_buffer, list):
return []
infos: list[dict[str, Any]] = []
for item in model_intermediate_buffer:
infos.append(item if isinstance(item, dict) else {})
return infos
def _get_request_token_counts(
hidden_states: torch.Tensor,
request_infos: list[dict[str, Any]],
seq_token_counts: list[int] | None,
) -> list[int]:
if seq_token_counts:
return [int(x) for x in seq_token_counts]
if is_forward_context_available():
slices = getattr(get_forward_context(), "ubatch_slices", None)
if slices is not None and len(slices) > 0:
counts: list[int] = []
for item in slices:
if isinstance(item, int):
counts.append(int(item))
elif hasattr(item, "stop") and hasattr(item, "start"):
counts.append(int(item.stop) - int(item.start))
if counts:
return counts
if request_infos:
if len(request_infos) == hidden_states.shape[0]:
return [1] * hidden_states.shape[0]
return [hidden_states.shape[0]]
return []
def _coerce_latent_history(
value: object,
*,
device: torch.device,
dtype: torch.dtype,
cfg: MingTTSConfig,
) -> torch.Tensor | None:
if value is None:
return None
if not isinstance(value, torch.Tensor):
value = torch.as_tensor(value)
history = value.detach()
if history.ndim == 2:
history = history.unsqueeze(0)
if history.ndim != 3:
raise RuntimeError(f"Expected latent_history rank-3 [B,T,D], got {tuple(history.shape)}")
if history.shape[1] != cfg.history_patch_size or history.shape[2] != cfg.latent_dim:
raise RuntimeError(
f"latent_history shape mismatch: got {tuple(history.shape)}, "
f"expected [B,{cfg.history_patch_size},{cfg.latent_dim}]"
)
return history.to(device=device, dtype=dtype)
def _resolve_runtime_float(req_info: dict[str, Any], key: str, default_value: float) -> float:
raw = req_info.get(key, default_value)
try:
value = float(raw)
except (TypeError, ValueError) as exc:
raise RuntimeError(f"Invalid {key}: expected float-like value, got {raw!r}") from exc
if not value >= 0.0:
raise RuntimeError(f"Invalid {key}: expected non-negative value, got {value}")
return value
def _resolve_runtime_int(req_info: dict[str, Any], key: str, default_value: int) -> int:
raw = req_info.get(key, default_value)
try:
value = int(raw)
except (TypeError, ValueError) as exc:
raise RuntimeError(f"Invalid {key}: expected int-like value, got {raw!r}") from exc
if value <= 0:
raise RuntimeError(f"Invalid {key}: expected positive value, got {value}")
return value
def _resolve_optional_runtime_int(req_info: dict[str, Any], key: str, default_value: int) -> int:
raw = req_info.get(key, default_value)
try:
value = int(raw)
except (TypeError, ValueError) as exc:
raise RuntimeError(f"Invalid {key}: expected int-like value, got {raw!r}") from exc
if value < 0:
raise RuntimeError(f"Invalid {key}: expected non-negative value, got {value}")
return value
def _validate_ming_decode_window(
request_infos: list[dict[str, Any]],
*,
min_stop_step: int,
default_max_decode_steps: int,
) -> None:
for i, info in enumerate(request_infos):
if info.get(KEY_TEXT_MODE):
continue
max_steps = _resolve_runtime_int(info, KEY_MAX_DECODE_STEPS, default_max_decode_steps)
min_steps = _resolve_optional_runtime_int(info, KEY_MIN_DECODE_STEPS, 0)
min_required = max(min_stop_step + 1, min_steps)
if max_steps < min_required:
req_id = info.get(KEY_REQUEST_ID, f"idx={i}")
raise ValueError(
f"Ming request {req_id!r}: max_decode_steps={max_steps} < "
f"min_required_decode_steps={min_required} "
f"(min_stop_step={min_stop_step}, min_decode_steps={min_steps})"
)
def _resolve_ming_stop_decision(
*,
step: int,
stop_prob: float,
stop_threshold: float,
min_stop_step: int,
min_decode_steps: int,
max_decode_steps: int,
audio_dummy_token_id: int,
text_eos_token_id: int,
) -> tuple[str, bool, bool, int, int]:
min_required_decode_steps = max(min_stop_step + 1, min_decode_steps)
if max_decode_steps < min_required_decode_steps:
raise RuntimeError(
"Invalid Ming decode window: "
f"max_decode_steps={max_decode_steps} is smaller than "
f"min_required_decode_steps={min_required_decode_steps}"
)
should_force_stop = (step + 1) >= max_decode_steps
should_stop_head = ((step + 1) >= min_required_decode_steps) and stop_prob > stop_threshold
if should_force_stop:
return (
MING_STOP_REASON_MAX_DECODE_STEPS,
True,
True,
min_required_decode_steps,
text_eos_token_id,
)
if should_stop_head:
return (
MING_STOP_REASON_STOP_HEAD,
True,
False,
min_required_decode_steps,
text_eos_token_id,
)
return (
MING_STOP_REASON_CONTINUE,
False,
False,
min_required_decode_steps,
audio_dummy_token_id,
)
@@ -0,0 +1,54 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Ming TTS pipeline: Stage-0 LLM+flow -> Stage-1 audio VAE."""
from vllm_omni.config.stage_config import (
PipelineConfig,
StageExecutionType,
StagePipelineConfig,
)
_PROC = "vllm_omni.model_executor.stage_input_processors.ming_tts"
MING_TTS_PIPELINE = PipelineConfig(
model_type="ming_tts",
model_arch="MingTTSForConditionalGeneration",
hf_architectures=("MingTTSForConditionalGeneration",),
stages=(
StagePipelineConfig(
stage_id=0,
model_stage="llm",
execution_type=StageExecutionType.LLM_AR,
input_sources=(),
owns_tokenizer=True,
hf_config_name="llm_config",
engine_output_type="latent",
async_chunk_process_next_stage_input_func=(f"{_PROC}.llm2audio_vae_async_chunk"),
sampling_constraints={
"temperature": 0.0,
"top_p": 1.0,
"top_k": -1,
"max_tokens": 512,
"detokenize": True,
},
),
StagePipelineConfig(
stage_id=1,
model_stage="audio_vae",
execution_type=StageExecutionType.LLM_GENERATION,
input_sources=(0,),
final_output=True,
final_output_type="audio",
hf_config_name="llm_config",
engine_output_type="audio",
sync_process_input_func=f"{_PROC}.llm2audio_vae",
sampling_constraints={
"temperature": 0.0,
"top_p": 1.0,
"top_k": -1,
"max_tokens": 1,
"detokenize": False,
},
),
),
)
@@ -0,0 +1,274 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
import copy
import json
import math
import re
from typing import Any
import torch
from .audio_prep import (
coerce_speaker_embeddings,
count_prompt_latent_patches,
count_prompt_waveform_patches,
pad_prompt_waveform,
)
from .config_ming_tts import (
AUDIO_FRAME_HOP,
KEY_MAX_DECODE_STEPS,
KEY_MIN_DECODE_STEPS,
KEY_PROMPT_LATENTS,
KEY_REQUEST_ID,
KEY_SPEAKER_EMBEDDING,
LATENT_DIM,
PATCH_SIZE,
SAMPLE_RATE,
VAE_PATCH_SIZE,
)
DEFAULT_PROMPT = "Please generate speech based on the following description.\n"
BASE_CAPTION_TEMPLATE: dict[str, Any] = {
"audio_sequence": [
{
"序号": 1,
"说话人": "speaker_1",
"方言": None,
"风格": None,
"语速": None,
"基频": None,
"音量": None,
"情感": None,
"BGM": {
"Genre": None,
"Mood": None,
"Instrument": None,
"Theme": None,
"ENV": None,
"SNR": None,
},
"IP": None,
}
]
}
_DURATION_SECONDS_RE = re.compile(r"Duration:\s*([0-9]+(?:\.[0-9]+)?)\s*s\b", re.IGNORECASE)
def create_instruction(user_input: Any) -> str | None:
if user_input is None:
return None
if isinstance(user_input, str):
return user_input
if not isinstance(user_input, dict):
raise ValueError(f"Ming instruction must be str, dict, or None; got {type(user_input).__name__}")
caption = copy.deepcopy(BASE_CAPTION_TEMPLATE)
item = caption["audio_sequence"][0]
for key, value in user_input.items():
if key in item:
item[key] = value
return json.dumps(caption, ensure_ascii=False)
def parse_duration_seconds(text: str | None) -> float | None:
if not isinstance(text, str):
return None
match = _DURATION_SECONDS_RE.search(text)
if match is None:
return None
try:
value = float(match.group(1))
except ValueError:
return None
if value <= 0.0:
return None
return value
def estimate_decode_steps_for_duration(
duration_seconds: float,
*,
sample_rate: int = SAMPLE_RATE,
frame_hop: int = AUDIO_FRAME_HOP,
patch_size: int = PATCH_SIZE,
vae_patch_size: int = VAE_PATCH_SIZE,
) -> int:
if duration_seconds <= 0.0:
return 0
samples_per_decode_step = int(frame_hop) * int(patch_size) * int(vae_patch_size)
required_samples = float(duration_seconds) * float(sample_rate)
return max(1, int(math.ceil(required_samples / float(samples_per_decode_step))))
def estimate_decode_step_window_for_duration(duration_seconds: float) -> tuple[int, int]:
target_steps = estimate_decode_steps_for_duration(duration_seconds)
min_steps = max(1, target_steps - 3)
max_steps = max(min_steps, target_steps + 3)
return min_steps, max_steps
def resolve_effective_runtime_controls(
*,
text: str,
runtime_controls: dict[str, Any] | None = None,
) -> dict[str, Any]:
controls = {} if runtime_controls is None else dict(runtime_controls)
has_explicit_min = KEY_MIN_DECODE_STEPS in controls and controls[KEY_MIN_DECODE_STEPS] is not None
has_explicit_max = KEY_MAX_DECODE_STEPS in controls and controls[KEY_MAX_DECODE_STEPS] is not None
if has_explicit_min or has_explicit_max:
return controls
duration_seconds = parse_duration_seconds(text)
if duration_seconds is None:
return controls
min_decode_steps, max_decode_steps = estimate_decode_step_window_for_duration(duration_seconds)
controls[KEY_MIN_DECODE_STEPS] = min_decode_steps
controls[KEY_MAX_DECODE_STEPS] = max_decode_steps
return controls
def build_dense_prompt_token_ids(
tokenizer: Any,
*,
prompt: str,
text: str,
instruction: str | None = None,
prompt_text: str | None = None,
speaker_count: int = 0,
prompt_patch_count: int = 0,
) -> list[int]:
speaker_prompt = []
for idx in range(int(speaker_count)):
speaker_prompt.extend(
tokenizer.encode(f" speaker_{idx + 1}:")
+ tokenizer.encode("<|vision_start|>")
+ tokenizer.encode("<|vision_pad|>")
+ tokenizer.encode("<|vision_end|>\n")
)
instruction_prompt = (
tokenizer.encode(instruction) + tokenizer.encode("<|endoftext|>") if instruction is not None else []
)
prompt_text_tokens = (
tokenizer.encode(prompt_text) if int(prompt_patch_count) > 0 and prompt_text is not None else []
)
audio_patch_token_id = tokenizer.convert_tokens_to_ids("<audioPatch>")
if audio_patch_token_id == tokenizer.unk_token_id:
raise ValueError("Ming tokenizer is missing required <audioPatch> token.")
prompt_latent_tokens = [audio_patch_token_id] * int(prompt_patch_count)
text_input_prefix = (
[]
if all(token in text for token in ("Genre: ", "Mood: ", "Instrument: ", "Theme: ", "Duration: "))
else tokenizer.encode(" Text input:\n")
)
return (
tokenizer.encode("<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n")
+ tokenizer.encode("<|im_start|>user\n")
+ tokenizer.encode(prompt)
+ speaker_prompt
+ text_input_prefix
+ prompt_text_tokens
+ tokenizer.encode(text)
+ tokenizer.encode("<|im_end|>\n")
+ tokenizer.encode("<|im_start|>assistant\n")
+ instruction_prompt
+ tokenizer.encode("<audio>")
+ prompt_latent_tokens
)
def build_ming_dense_prompt(
tokenizer: Any,
*,
prompt: str,
text: str,
runtime_controls: dict[str, Any] | None = None,
instruction: Any = None,
prompt_text: str | None = None,
prompt_waveform: Any = None,
prompt_latents: Any = None,
speaker_embedding: Any = None,
use_zero_spk_emb: bool = False,
request_id: str | None = None,
) -> dict[str, Any]:
instruction_text = create_instruction(instruction)
speaker_embeddings = coerce_speaker_embeddings(speaker_embedding, use_zero_spk_emb=use_zero_spk_emb)
effective_runtime_controls = resolve_effective_runtime_controls(text=text, runtime_controls=runtime_controls)
prompt_waveform_tensor = None
prompt_patch_count = 0
if prompt_waveform is not None:
prompt_waveform_tensor = pad_prompt_waveform(prompt_waveform)
prompt_patch_count = count_prompt_waveform_patches(prompt_waveform_tensor)
if prompt_waveform_tensor is not None and prompt_latents is not None:
raise ValueError(
"Ming waveform cloning request provided both raw prompt_waveform and explicit prompt_latents. "
"Choose exactly one source of truth."
)
prompt_latent_value = None
if prompt_waveform_tensor is not None and prompt_text is None:
raise ValueError(
"Ming prompt_waveform requires prompt_text for prompt-latent conditioning. "
"Use speaker_embedding for reference-audio-only speaker conditioning."
)
if prompt_latents is not None:
prompt_latent_value = torch.as_tensor(prompt_latents)
prompt_patch_count = count_prompt_latent_patches(
prompt_latent_value, patch_size=PATCH_SIZE, latent_dim=LATENT_DIM
)
prompt_token_ids = build_dense_prompt_token_ids(
tokenizer,
prompt=prompt,
text=text,
instruction=instruction_text,
prompt_text=prompt_text if prompt_patch_count > 0 else None,
speaker_count=0 if speaker_embeddings is None else len(speaker_embeddings),
prompt_patch_count=prompt_patch_count,
)
additional_information = {}
for key, value in effective_runtime_controls.items():
if isinstance(value, torch.Tensor):
additional_information[key] = value
elif key in (KEY_MIN_DECODE_STEPS, KEY_MAX_DECODE_STEPS):
additional_information[key] = torch.tensor(int(value), dtype=torch.int32)
else:
additional_information[key] = torch.tensor(float(value), dtype=torch.float32)
if request_id is not None:
additional_information[KEY_REQUEST_ID] = request_id
if instruction_text is not None:
additional_information["instruction"] = instruction_text
if prompt_text is not None:
additional_information["prompt_text"] = prompt_text
if prompt_waveform_tensor is not None:
additional_information["prompt_waveform"] = prompt_waveform_tensor
additional_information["prompt_waveform_length"] = torch.tensor(
[int(prompt_waveform_tensor.shape[-1])], dtype=torch.int32
)
if prompt_latent_value is not None:
additional_information[KEY_PROMPT_LATENTS] = prompt_latent_value
if speaker_embeddings is not None:
additional_information[KEY_SPEAKER_EMBEDDING] = (
speaker_embeddings[0] if len(speaker_embeddings) == 1 else torch.stack(speaker_embeddings, dim=0)
)
if use_zero_spk_emb:
additional_information["use_zero_spk_emb"] = True
return {
"prompt": prompt,
"text": text,
"prompt_token_ids": prompt_token_ids,
"additional_information": additional_information,
}
__all__ = [
"DEFAULT_PROMPT",
"build_dense_prompt_token_ids",
"build_ming_dense_prompt",
"create_instruction",
"estimate_decode_step_window_for_duration",
"estimate_decode_steps_for_duration",
"parse_duration_seconds",
"resolve_effective_runtime_controls",
]
@@ -0,0 +1,174 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
import json
import threading
import time
from pathlib import Path
from typing import Any
import torch
from safetensors import safe_open
from vllm.logger import init_logger
from vllm_omni.engine.stage_init_utils import _resolve_model_to_local_path
from vllm_omni.model_executor.models.common.ming.audio_vae import AudioVAE
from .audio_prep import (
_coerce_prompt_latents,
_normalize_prompt_waveform,
count_prompt_latent_patches,
pad_prompt_waveform,
)
from .config_ming_tts import KEY_PROMPT_LATENTS
logger = init_logger(__name__)
_PROMPT_ENCODER_LOAD_LOCK = threading.Lock()
def _resolve_prompt_latents(wrapper: Any, info_dict: dict[str, Any]) -> dict[str, torch.Tensor] | None:
raw_latents = info_dict.get(KEY_PROMPT_LATENTS, info_dict.get("prompt_latents"))
raw_waveform = info_dict.get("prompt_waveform", info_dict.get("prompt_waveforms"))
if raw_latents is not None and raw_waveform is not None:
raise ValueError(
"Ming waveform cloning request provided both raw prompt_waveform and explicit prompt_latents. "
"Choose exactly one source of truth."
)
direct_latents = _coerce_prompt_latents(
raw_latents,
patch_size=wrapper.ming_config.patch_size,
latent_dim=wrapper.ming_config.latent_dim,
)
if direct_latents is not None:
return direct_latents
if raw_waveform is None:
return None
encode_fn = getattr(wrapper, "_encode_prompt_waveform_to_latents", None)
if callable(encode_fn):
latents = encode_fn(raw_waveform, info_dict.get("prompt_waveform_length"))
else:
latents = _encode_prompt_waveform_to_latents(
wrapper,
raw_waveform,
info_dict.get("prompt_waveform_length"),
)
return _coerce_prompt_latents(
latents,
patch_size=wrapper.ming_config.patch_size,
latent_dim=wrapper.ming_config.latent_dim,
)
def _load_prompt_encoder(wrapper: Any) -> AudioVAE:
if wrapper._prompt_encoder is not None:
return wrapper._prompt_encoder
with _PROMPT_ENCODER_LOAD_LOCK:
if wrapper._prompt_encoder is not None:
return wrapper._prompt_encoder
if wrapper.ming_config.audio_tokenizer_config is None:
raise RuntimeError("Ming Stage-0 requires audio_tokenizer_config to encode prompt audio.")
load_start = time.perf_counter()
encoder = AudioVAE(wrapper.ming_config.audio_tokenizer_config).eval()
state_dict = encoder.state_dict()
loaded = 0
loaded_encoder_params = set()
with torch.no_grad():
for shard_path in _iter_model_safetensors(
_resolve_model_to_local_path(str(wrapper.vllm_config.model_config.model))
):
with safe_open(str(shard_path), framework="pt", device="cpu") as handle:
for key in handle.keys():
if not key.startswith("audio.encoder."):
continue
name = key[len("audio.") :]
if name not in state_dict:
continue
target = state_dict[name]
target.copy_(handle.get_tensor(key).to(device=target.device, dtype=target.dtype))
loaded += 1
loaded_encoder_params.add(name)
if loaded == 0:
raise RuntimeError("Ming prompt encoder received no audio.encoder.* weights from checkpoint.")
expected_encoder_params = {f"encoder.{name}" for name, _ in encoder.encoder.named_parameters()}
missing = expected_encoder_params - loaded_encoder_params
if missing:
raise RuntimeError(
f"Ming prompt encoder: {len(missing)} params not loaded. First few: {sorted(missing)[:5]}"
)
dev = next(wrapper.parameters()).device
try:
del encoder.decoder
encoder.decoder = None
if dev.type != "cpu":
encoder.encoder.to(dev, dtype=getattr(wrapper.model, "fm_dtype", torch.bfloat16))
else:
encoder.encoder.to(dev)
except Exception as exc:
raise RuntimeError(f"Failed to move Ming prompt encoder to {dev}: {exc}") from exc
wrapper._prompt_encoder = encoder
logger.info("Ming prompt encoder cold-loaded in %.3f ms", (time.perf_counter() - load_start) * 1000.0)
return encoder
@torch.inference_mode()
def _encode_prompt_waveform_to_latents(wrapper: Any, waveform: Any, waveform_length: Any = None) -> torch.Tensor:
encoder = _load_prompt_encoder(wrapper)
waveform = _normalize_prompt_waveform(waveform, target_sr=wrapper.ming_config.sample_rate)
waveform = pad_prompt_waveform(
waveform,
patch_size=wrapper.ming_config.patch_size,
sample_rate=wrapper.ming_config.sample_rate,
)
dev = next(encoder.encoder.parameters()).device
waveform = waveform.to(device=dev, dtype=next(encoder.encoder.parameters()).dtype)
if waveform_length is None:
waveform_length = torch.full((waveform.shape[0],), waveform.shape[-1], dtype=torch.int32, device=dev)
elif not isinstance(waveform_length, torch.Tensor):
waveform_length = torch.as_tensor(waveform_length, dtype=torch.int32, device=dev)
else:
waveform_length = waveform_length.to(device=dev, dtype=torch.int32)
latents, _ = encoder.encode_latent(waveform, waveform_length)
if latents.ndim == 3 and latents.shape[0] == 1:
latents = latents.squeeze(0)
count_prompt_latent_patches(
latents,
patch_size=wrapper.ming_config.patch_size,
latent_dim=wrapper.ming_config.latent_dim,
)
return latents.detach().to(dtype=torch.float32).contiguous()
def _iter_model_safetensors(local_model_path: str) -> list[Path]:
model_root = Path(local_model_path)
index_path = model_root / "model.safetensors.index.json"
if index_path.exists():
with index_path.open("r", encoding="utf-8") as handle:
index_data = json.load(handle)
filenames = sorted(set(index_data.get("weight_map", {}).values()))
if not filenames:
raise RuntimeError(f"No checkpoint shards listed in {index_path}")
return [model_root / filename for filename in filenames]
single_file = model_root / "model.safetensors"
if single_file.exists():
return [single_file]
files = sorted(model_root.glob("*.safetensors"))
if not files:
raise RuntimeError(f"No .safetensors checkpoint found under {local_model_path}")
return files
__all__ = [
"_encode_prompt_waveform_to_latents",
"_iter_model_safetensors",
"_load_prompt_encoder",
"_resolve_prompt_latents",
]
@@ -0,0 +1,51 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Adopted from https://github.com/inclusionAI/Ming-omni-tts/blob/main/spkemb_extractor.py
import os
import torch
import torchaudio
from vllm.multimodal.media.audio import load_audio
from vllm_omni.model_executor.models.ming_flash_omni.spk_embedding import SpkembExtractor
def resolve_model_to_local_path(model):
if os.path.isdir(model):
return model
from huggingface_hub import snapshot_download
return snapshot_download(model)
class MingSpeakerEmbeddingExtractor:
def __init__(self, model, target_sr=16000):
local_model_path = resolve_model_to_local_path(model)
campplus_path = os.path.join(local_model_path, "campplus.onnx")
if not os.path.exists(campplus_path):
raise RuntimeError(f"Missing Ming speaker extractor model: {campplus_path}")
self.target_sr = int(target_sr)
self._core = SpkembExtractor(campplus_path, target_sr=self.target_sr)
def extract_from_waveform(self, waveform, sample_rate):
if not isinstance(waveform, torch.Tensor):
waveform = torch.as_tensor(waveform)
tensor = waveform.detach().to(torch.float32)
if tensor.ndim == 1:
tensor = tensor.unsqueeze(0)
if int(sample_rate) != self.target_sr:
tensor = torchaudio.transforms.Resample(orig_freq=int(sample_rate), new_freq=self.target_sr)(tensor)
embedding = self._core._extract_spk_embedding(tensor)
return embedding.squeeze(0).to(dtype=torch.float32)
def extract_from_file(self, audio_path):
audio, sample_rate = load_audio(audio_path, sr=None, mono=False)
waveform = torch.from_numpy(audio).contiguous()
return self.extract_from_waveform(waveform, sample_rate)
def extract_many(self, audio_paths):
return [self.extract_from_file(path) for path in audio_paths]
@@ -0,0 +1,172 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
from typing import Any
from transformers import PretrainedConfig
from vllm_omni.model_executor.models.common.ming.audio_vae import AudioVAEConfig
from .constants import (
AGGREGATOR_HIDDEN_SIZE,
HISTORY_PATCH_SIZE,
LATENT_DIM,
LLM_HIDDEN_SIZE,
LLM_VOCAB_SIZE,
PATCH_SIZE,
SAMPLE_RATE,
)
def _to_plain_dict(obj: Any) -> dict[str, Any]:
"""Normalize nested config objects into plain dicts when possible."""
if obj is None:
return {}
if isinstance(obj, dict):
return dict(obj)
if isinstance(obj, PretrainedConfig):
return obj.to_dict()
if hasattr(obj, "to_dict") and callable(obj.to_dict):
try:
return dict(obj.to_dict())
except Exception:
pass
try:
return dict(vars(obj))
except Exception:
return {}
def _coerce_audio_vae_config(atc_raw: Any) -> AudioVAEConfig | None:
if atc_raw is None:
return None
if isinstance(atc_raw, AudioVAEConfig):
return atc_raw
if isinstance(atc_raw, PretrainedConfig):
atc_dict = atc_raw.to_dict()
elif isinstance(atc_raw, dict):
atc_dict = dict(atc_raw)
elif hasattr(atc_raw, "to_dict") and callable(atc_raw.to_dict):
atc_dict = dict(atc_raw.to_dict())
else:
raise TypeError(f"Unsupported audio_tokenizer_config type for Ming dense config: {type(atc_raw)!r}")
return AudioVAEConfig(**atc_dict)
def _nested_get(obj: Any, *keys: str, default: Any = None) -> Any:
"""Safe nested attribute/key access for dicts and config-like objects."""
cur = obj
for key in keys:
if cur is None:
return default
if isinstance(cur, dict):
cur = cur.get(key)
else:
cur = getattr(cur, key, None)
return cur if cur is not None else default
def validate_ming_tts_config(cfg: Any) -> None:
"""Run before GPU allocation/weight loading. Raises ValueError on mismatches."""
if cfg.audio_dummy_token_id != 151705:
raise ValueError(
f"audio_dummy_token_id={cfg.audio_dummy_token_id}, expected 151705 (<audioPatch>). "
"Wrong tokenizer/checkpoint?"
)
if cfg.audio_eos_token_id != 151704:
raise ValueError(
f"audio_eos_token_id={cfg.audio_eos_token_id}, expected 151704 (<end_of_audio>). "
"Wrong tokenizer/checkpoint?"
)
if cfg.text_eos_token_id != 151669:
raise ValueError(
f"text_eos_token_id={cfg.text_eos_token_id}, expected 151669 (<text_eos>). Wrong tokenizer/checkpoint?"
)
if cfg.audio_tokenizer_config is None:
raise ValueError("audio_tokenizer_config is None. Nested AudioVAE config was not deserialized correctly.")
if cfg.latent_dim != LATENT_DIM:
raise ValueError(
f"latent_dim mismatch: got {cfg.latent_dim}, expected {LATENT_DIM}. "
"Check audio_tokenizer_config.enc_kwargs.latent_dim."
)
if cfg.patch_size != PATCH_SIZE:
raise ValueError(
f"patch_size mismatch: got {cfg.patch_size}, expected {PATCH_SIZE}. Check ditar_config.patch_size."
)
if cfg.history_patch_size != HISTORY_PATCH_SIZE:
raise ValueError(
f"history_patch_size mismatch: got {cfg.history_patch_size}, expected {HISTORY_PATCH_SIZE}. "
"Check ditar_config.history_patch_size."
)
if cfg.llm_hidden_size != LLM_HIDDEN_SIZE:
raise ValueError(
f"llm_hidden_size mismatch: got {cfg.llm_hidden_size}, expected {LLM_HIDDEN_SIZE}. "
"Check llm_config.hidden_size."
)
if cfg.llm_vocab_size != LLM_VOCAB_SIZE:
raise ValueError(f"llm_vocab_size mismatch: got {cfg.llm_vocab_size}, expected {LLM_VOCAB_SIZE}.")
if cfg.sample_rate != SAMPLE_RATE:
raise ValueError(f"sample_rate mismatch: got {cfg.sample_rate}, expected {SAMPLE_RATE}.")
if cfg.vae_patch_size != cfg.patch_size:
raise ValueError(f"VAE patch size ({cfg.vae_patch_size}) != flow/DiT patch size ({cfg.patch_size}).")
llm_hidden_from_cfg = cfg.llm_config.get("hidden_size")
if llm_hidden_from_cfg is not None and llm_hidden_from_cfg != cfg.llm_hidden_size:
raise ValueError(f"llm_hidden_size ({cfg.llm_hidden_size}) != llm_config.hidden_size ({llm_hidden_from_cfg}).")
agg_h = cfg.aggregator_config.get("hidden_size")
dit_h = cfg.ditar_config.get("hidden_size")
if agg_h is not None and dit_h is not None and agg_h != dit_h:
raise ValueError(f"aggregator_config.hidden_size ({agg_h}) != ditar_config.hidden_size ({dit_h}).")
if agg_h is not None and agg_h != AGGREGATOR_HIDDEN_SIZE:
raise ValueError(f"aggregator hidden_size mismatch: got {agg_h}, expected {AGGREGATOR_HIDDEN_SIZE}.")
if dit_h is not None and dit_h != AGGREGATOR_HIDDEN_SIZE:
raise ValueError(f"ditar hidden_size mismatch: got {dit_h}, expected {AGGREGATOR_HIDDEN_SIZE}.")
atc = cfg.audio_tokenizer_config
semantic_module_kwargs = _nested_get(atc, "semantic_module_kwargs", default=None)
if semantic_module_kwargs is not None:
raise ValueError("Ming dense 0.5B expects audio_tokenizer_config.semantic_module_kwargs to be null.")
enc_latent = _nested_get(atc, "enc_kwargs", "latent_dim", default=None)
dec_latent = _nested_get(atc, "dec_kwargs", "latent_dim", default=None)
if enc_latent is not None and enc_latent != cfg.latent_dim:
raise ValueError(f"audio enc latent_dim ({enc_latent}) != Ming latent_dim ({cfg.latent_dim}).")
if dec_latent is not None and dec_latent != cfg.latent_dim:
raise ValueError(f"audio dec latent_dim ({dec_latent}) != Ming latent_dim ({cfg.latent_dim}).")
atc_patch = _nested_get(atc, "patch_size", default=None)
if atc_patch is not None and atc_patch != cfg.vae_patch_size:
raise ValueError(f"audio_tokenizer_config.patch_size ({atc_patch}) != vae_patch_size ({cfg.vae_patch_size}).")
atc_sr = _nested_get(atc, "sample_rate", default=None)
if atc_sr is not None and atc_sr != cfg.sample_rate:
raise ValueError(f"audio_tokenizer_config.sample_rate ({atc_sr}) != sample_rate ({cfg.sample_rate}).")
enc_input_dim = _nested_get(atc, "enc_kwargs", "input_dim", default=None)
enc_hop_size = _nested_get(atc, "enc_kwargs", "hop_size", default=None)
dec_output_dim = _nested_get(atc, "dec_kwargs", "output_dim", default=None)
if enc_input_dim is not None and enc_hop_size is not None and enc_input_dim != enc_hop_size:
raise ValueError(f"AudioVAE encoder input_dim ({enc_input_dim}) != hop_size ({enc_hop_size}).")
if enc_hop_size is not None and dec_output_dim is not None and enc_hop_size != dec_output_dim:
raise ValueError(
f"AudioVAE encoder hop_size ({enc_hop_size}) != decoder output_dim ({dec_output_dim}). "
"Expected 882 in this checkpoint family."
)
if cfg.latent_chunk_size <= 0:
raise ValueError(f"latent_chunk_size must be > 0, got {cfg.latent_chunk_size}.")
if cfg.latent_left_context < 0:
raise ValueError(f"latent_left_context must be >= 0, got {cfg.latent_left_context}.")
if cfg.max_decode_steps <= 0:
raise ValueError(f"max_decode_steps must be > 0, got {cfg.max_decode_steps}.")
if not (0.0 <= cfg.stop_head_threshold <= 1.0):
raise ValueError(f"stop_head_threshold must be in [0,1], got {cfg.stop_head_threshold}.")
if cfg.stop_head_min_steps < 0:
raise ValueError(f"stop_head_min_steps must be >= 0, got {cfg.stop_head_min_steps}.")
@@ -20,6 +20,9 @@ from vllm_omni.model_executor.models.moss_tts.audio_tokenizer import (
MossAudioTokenizerConfig,
MossAudioTokenizerModel,
)
from vllm_omni.model_executor.models.moss_tts.moss_codec_cudagraph import (
MossTTSCUDAGraphCodecWrapper,
)
from vllm_omni.model_executor.models.output_templates import OmniOutput
logger = init_logger(__name__)
@@ -28,15 +31,16 @@ logger = init_logger(__name__)
class MossTTSCodecDecoder(nn.Module):
"""Stage-1 decoder for all MOSS-TTS variants.
Consumes ``(T, NQ)`` audio VQ codes emitted by Stage 0 and decodes them
Consumes ``(NQ, T)`` audio VQ codes emitted by Stage 0 and decodes them
to a 24 kHz mono waveform using the vendored
``MossAudioTokenizerModel``.
All five variants share the same codec checkpoint
``OpenMOSS-Team/MOSS-Audio-Tokenizer``. The number of quantizers
(``n_vq``) is passed as a ``num_quantizers`` argument to ``batch_decode``
so one codec instance handles both ``n_vq=32`` (MOSS-TTS) and ``n_vq=16``
(all other variants) without swapping weights.
(``n_vq``) is read from ``hf_config`` at construction time and fixed for
the lifetime of the instance; the same checkpoint can be configured as
``n_vq=32`` (MOSS-TTS) or ``n_vq=16`` (all other variants) without
swapping weights.
The codec checkpoint path defaults to the value stored in
``vllm_config.model_config.hf_config.codec_model_name_or_path`` but can
@@ -64,6 +68,7 @@ class MossTTSCodecDecoder(nn.Module):
# Resolved at load_weights() time
self._codec: MossAudioTokenizerModel | None = None
self._cuda_graph_wrapper: MossTTSCUDAGraphCodecWrapper | None = None
self._sr_tensor = torch.tensor(self._OUTPUT_SAMPLE_RATE, dtype=torch.int32)
# ------------------------------------------------------------------
@@ -100,10 +105,11 @@ class MossTTSCodecDecoder(nn.Module):
Stage 0 emits flat codebook-major ``[NQ * T_chunk]`` audio codes. The
chunk transfer adapter assigns those to ``request.prompt_token_ids``,
which arrives here as ``input_ids``. Per-request offsets are derived
from ``runtime_additional_information``-attached request metadata; meta
like ``left_context_size`` (overlap context for the causal decoder)
also lives there.
which arrives here as ``input_ids`` concatenated across all requests.
Per-request slice boundaries are computed from
``kwargs["num_scheduled_tokens"]`` (a list of token counts, one per
request). ``runtime_additional_information`` carries per-request
metadata such as ``left_context_size``.
Returns
-------
@@ -163,11 +169,10 @@ class MossTTSCodecDecoder(nn.Module):
continue
t_chunk = int(seg.numel() // self._n_vq)
codes_nq_t = seg.reshape(self._n_vq, t_chunk).to(device=device)
# Clamp out-of-range codes (the talker uses ``audio_pad_code``
# =``codebook_size`` for delay-pattern padding; passing it to the
# codec embedding lookup would be an OOB index. The downstream
# de-delay step is intended to drop those rows, but until that's
# wired we clamp so the kernel does not assert.)
# Clamp out-of-range codes: the talker uses ``audio_pad_code``
# (= ``codebook_size``) for delay-pattern padding. The stage input
# processor de-delays and drops pad rows before forwarding here, but
# clamp as a defensive guard against any edge-case leakage.
codebook_size = self._codec.config.codebook_size
codes_nq_t = codes_nq_t.clamp_(0, int(codebook_size) - 1)
@@ -183,7 +188,10 @@ class MossTTSCodecDecoder(nn.Module):
left_ctx = int(left_ctx.reshape(-1)[0].item()) if left_ctx.numel() else 0
left_ctx = int(left_ctx)
out = self._codec.batch_decode(codes_list=[codes_nq_t], num_quantizers=self._n_vq)
if self._cuda_graph_wrapper is not None:
out = self._cuda_graph_wrapper.decode(codes_nq_t)
else:
out = self._codec.batch_decode(codes_list=[codes_nq_t], num_quantizers=self._n_vq)
if out.audio is None:
continue
@@ -194,7 +202,13 @@ class MossTTSCodecDecoder(nn.Module):
# Trim left-context samples.
if left_ctx > 0:
trim = left_ctx * self._codec.downsample_rate
trim = min(left_ctx * self._codec.downsample_rate, wav.shape[0])
if trim < left_ctx * self._codec.downsample_rate:
logger.warning(
"left_ctx trim (%d samples) exceeds wav length (%d); returning empty audio.",
left_ctx * self._codec.downsample_rate,
wav.shape[0],
)
wav = wav[trim:]
audios[i] = wav
@@ -288,8 +302,7 @@ class MossTTSCodecDecoder(nn.Module):
codec_cfg.num_quantizers,
)
# Move sr_tensor to the same device
self._sr_tensor = self._sr_tensor.to(device=device)
self._maybe_enable_decoder_cudagraph(device)
# vLLM's track_weights_loading() compares the returned set against
# ``self.named_parameters()``. After ``self._codec = codec`` above,
@@ -297,5 +310,42 @@ class MossTTSCodecDecoder(nn.Module):
# mirror that here.
return {f"_codec.{name}" for name, _ in codec.named_parameters()}
def _maybe_enable_decoder_cudagraph(self, device: torch.device) -> None:
"""Capture CUDA Graphs for the codec decoder if enforce_eager is False."""
if getattr(self.vllm_config.model_config, "enforce_eager", True):
return
if self._codec is None:
return
# Read capture sizes from the connector's extra config (same convention
# as Qwen3-TTS), falling back to a sensible default covering common
# codec_chunk_frames values used in moss_tts.yaml.
capture_sizes: list[int] = [4, 8, 16, 25, 32, 50, 64, 100, 128, 200, 256]
model_cfg = getattr(self.vllm_config, "model_config", None)
connector_cfg = getattr(model_cfg, "stage_connector_config", None)
if isinstance(connector_cfg, dict):
extra_cfg: dict | None = connector_cfg.get("extra", connector_cfg)
else:
extra_cfg = getattr(connector_cfg, "extra", None)
if isinstance(extra_cfg, dict):
raw = extra_cfg.get("decode_cudagraph_capture_sizes")
if raw is not None:
if isinstance(raw, (list, tuple)):
parsed = sorted({int(v) for v in raw if int(v) > 0})
elif isinstance(raw, str):
parsed = sorted({int(v.strip()) for v in raw.split(",") if v.strip()})
else:
parsed = [int(raw)]
if parsed:
capture_sizes = parsed
self._cuda_graph_wrapper = MossTTSCUDAGraphCodecWrapper(
model=self._codec,
capture_sizes=capture_sizes,
num_quantizers=self._n_vq,
enabled=True,
)
self._cuda_graph_wrapper.warmup(device)
__all__ = ["MossTTSCodecDecoder"]
@@ -0,0 +1,207 @@
"""CUDA Graph acceleration for the MOSS Audio Tokenizer codec decoder.
Captures MossAudioTokenizerModel._decode for a set of fixed frame-count
bucket sizes, then replays the captured graph at inference time to eliminate
kernel-launch overhead. Inputs that exceed all captured sizes fall back to
eager execution transparently.
"""
from __future__ import annotations
import time
import torch
from torch.cuda import CUDAGraph
from vllm.logger import init_logger
from vllm.platforms import current_platform
from vllm_omni.model_executor.models.moss_tts.audio_tokenizer import (
MossAudioTokenizerDecoderOutput,
MossAudioTokenizerModel,
)
logger = init_logger(__name__)
class MossTTSCUDAGraphCodecWrapper:
"""CUDA Graph wrapper for MossAudioTokenizerModel._decode.
Graphs are keyed by padded_T (int). On each call the actual T is
bucket-matched to the smallest pre-captured size >= T. The static code
buffer [NQ, 1, padded_T] is filled left-aligned (right-zero-padded) and
the graph is replayed. The output audio is sliced to the correct length
by scaling from the captured audio shape (actual_T / padded_T * captured_len),
avoiding any assumption about downsample_rate vs effective decoder upsample.
The slice is cloned before returning so the static buffer can be reused.
Usage::
wrapper = MossTTSCUDAGraphCodecWrapper(codec_model, capture_sizes, nq)
wrapper.warmup(device)
# per-request decode:
out = wrapper.decode(codes_nq_t) # codes_nq_t: [NQ, T]
"""
def __init__(
self,
model: MossAudioTokenizerModel,
capture_sizes: list[int],
num_quantizers: int,
enabled: bool = True,
) -> None:
self.model = model
self.capture_sizes: list[int] = sorted(capture_sizes)
self.num_quantizers = num_quantizers
self.enabled = enabled
# All dicts keyed by padded_T.
self.graphs: dict[int, CUDAGraph] = {}
self.static_codes: dict[int, torch.Tensor] = {} # [NQ, 1, padded_T]
# static_lengths is kept alive here — the captured graph holds a
# reference to the underlying storage and must not be GC'd.
self.static_lengths: dict[int, torch.Tensor] = {} # [1]
self.static_audio: dict[int, torch.Tensor] = {} # [1, 1, padded_T * effective_upsample]
self._warmed_up = False
# ------------------------------------------------------------------
# Size helpers
# ------------------------------------------------------------------
def _get_padded_size(self, actual_t: int) -> int | None:
"""Return the smallest capture size >= actual_t, or None if too large."""
for s in self.capture_sizes:
if actual_t <= s:
return s
return None
# ------------------------------------------------------------------
# Warmup / capture
# ------------------------------------------------------------------
def warmup(self, device: torch.device) -> None:
"""Allocate static buffers and capture CUDA Graphs for all sizes."""
if device.type != "cuda" or not self.enabled or self._warmed_up:
return
nq = self.num_quantizers
logger.info(
"MOSS-TTS codec CUDA Graph warmup: nq=%d capture_sizes=%s",
nq,
self.capture_sizes,
)
t0 = time.perf_counter()
# One eager run per size to let cuDNN / CUDA allocate memory before
# the capture window (graph capture forbids new CUDA allocs during it).
for size in self.capture_sizes:
dummy_codes = torch.zeros(nq, 1, size, dtype=torch.long, device=device)
dummy_lengths = torch.tensor([size], dtype=torch.long, device=device)
with torch.no_grad():
_ = self.model._decode(dummy_codes, dummy_lengths)
torch.accelerator.synchronize(device)
for size in self.capture_sizes:
try:
self._capture(size, device)
logger.info(" Captured CUDA Graph for size=%d", size)
except Exception:
logger.warning(
" Failed to capture CUDA Graph for size=%d; this size will fall back to eager decode",
size,
exc_info=True,
)
self._warmed_up = True
elapsed_ms = (time.perf_counter() - t0) * 1000.0
logger.info(
"MOSS-TTS codec CUDA Graph warmup complete: %d/%d captured in %.1f ms",
len(self.graphs),
len(self.capture_sizes),
elapsed_ms,
)
def _capture(self, size: int, device: torch.device) -> None:
nq = self.num_quantizers
static_codes = torch.zeros(nq, 1, size, dtype=torch.long, device=device)
# lengths holds the number of valid code frames; set to full size at
# capture time so the decoder emits a full-size audio buffer.
static_lengths = torch.tensor([size], dtype=torch.long, device=device)
# Extra eager warmup inside capture to ensure all kernels are compiled.
with torch.no_grad():
_ = self.model._decode(static_codes, static_lengths)
torch.accelerator.synchronize(device)
graph = CUDAGraph()
with torch.no_grad():
with torch.cuda.graph(graph, pool=current_platform.get_global_graph_pool()):
static_out = self.model._decode(static_codes, static_lengths)
self.graphs[size] = graph
self.static_codes[size] = static_codes
self.static_lengths[size] = static_lengths
# static_out.audio is a static buffer reused every replay; hold a
# reference so it is not garbage-collected.
self.static_audio[size] = static_out.audio # [1, 1, size * effective_upsample]
# ------------------------------------------------------------------
# Inference
# ------------------------------------------------------------------
@torch.no_grad()
def decode(self, codes_nq_t: torch.Tensor) -> MossAudioTokenizerDecoderOutput:
"""Decode [NQ, T] codes to waveform using a CUDA Graph when possible.
Falls back to eager batch_decode when:
- CUDA Graph is disabled or not yet warmed up
- an outer CUDA stream capture is active (e.g. vLLM FULL graph mode)
- actual T exceeds all pre-captured sizes
"""
if not self.enabled or not self._warmed_up:
return self.model.batch_decode(codes_list=[codes_nq_t], num_quantizers=self.num_quantizers)
# Replaying a graph inside an active stream capture would corrupt the
# outer graph. Fall back to eager so the caller can complete its capture.
if torch.cuda.is_current_stream_capturing():
return self.model.batch_decode(codes_list=[codes_nq_t], num_quantizers=self.num_quantizers)
actual_t = int(codes_nq_t.shape[-1])
padded_size = self._get_padded_size(actual_t)
if padded_size is None or padded_size not in self.graphs:
return self.model.batch_decode(codes_list=[codes_nq_t], num_quantizers=self.num_quantizers)
# --- Fill static buffers then replay ---
static_codes = self.static_codes[padded_size] # [NQ, 1, padded_size]
if actual_t == padded_size:
# Exact fit: copy the whole buffer at once.
# codes_nq_t is [NQ, T]; unsqueeze(1) → [NQ, 1, T] matching static_codes.
static_codes.copy_(codes_nq_t.unsqueeze(1))
else:
# Smaller input: zero the buffer first (right-zero-pad), then fill
# left-aligned. static_codes[:, 0, :actual_t] is [NQ, actual_t]
# and codes_nq_t is [NQ, actual_t].
static_codes.zero_()
static_codes[:, 0, :actual_t].copy_(codes_nq_t)
self.graphs[padded_size].replay()
# static_audio[padded_size] is the live output buffer of the graph.
# Slice to the real audio length and clone before returning; without
# the clone the next replay would overwrite the caller's tensor.
# Derive the slice length from the captured audio shape rather than
# downsample_rate: the decoder's effective upsample (product of all
# PatchedPretransform patch sizes) can differ from the config attribute.
captured_len = self.static_audio[padded_size].shape[-1]
actual_wav_len = captured_len * actual_t // padded_size
audio = self.static_audio[padded_size][..., :actual_wav_len].clone()
audio_lengths = torch.tensor([actual_wav_len], dtype=torch.long, device=audio.device)
return MossAudioTokenizerDecoderOutput(audio=audio, audio_lengths=audio_lengths)
__all__ = ["MossTTSCUDAGraphCodecWrapper"]
@@ -13,8 +13,10 @@ Streaming is supported via the VoxCPM-style generator pattern:
- compute_logits() emits EOS only when the last chunk has been yielded,
telling the AR scheduler to finish the request.
Weight loading deliberately happens inside load_weights() -- NOT __init__ --
so that vLLM initialises distributed state before any CUDA allocations occur.
The AR LM and audio tokenizer are constructed eagerly in __init__ so that
``load_format: dummy`` works (DummyModelLoader skips ``load_weights``) and
to avoid OOM from vLLM's post-init KV-cache profiling. Mirrors qwen3_tts
(PR #3117).
"""
from __future__ import annotations
@@ -140,9 +142,72 @@ class MossTTSNanoForGeneration(nn.Module):
self.config = vllm_config.model_config.hf_config
self.model_path: str = vllm_config.model_config.model
self._lm: nn.Module | None = None
self._audio_tokenizer: nn.Module | None = None
self._device: torch.device | None = None
# Eager construction (not in load_weights) -- see module docstring.
_patch_torchaudio_load()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self._device: torch.device = device
if device.type == "cuda" and torch.cuda.is_bf16_supported():
tts_dtype = torch.bfloat16
elif device.type == "cuda":
tts_dtype = torch.float16
else:
tts_dtype = torch.float32
logger.info("Loading MOSS-TTS-Nano LM from %s (dtype=%s)", self.model_path, tts_dtype)
from transformers import AutoModelForCausalLM
lm = AutoModelForCausalLM.from_pretrained(
self.model_path,
trust_remote_code=True,
torch_dtype=tts_dtype,
)
if device.type == "cuda":
try:
import flash_attn # noqa: F401
lm._set_attention_implementation("flash_attention_2")
logger.info("MOSS-TTS-Nano using flash_attention_2")
except ImportError:
lm._set_attention_implementation("sdpa")
logger.info("MOSS-TTS-Nano using sdpa (flash_attn not installed)")
lm.to(device=device)
lm.eval()
# ``trust_remote_code`` custom RoPE classes that register
# ``inv_freq`` with ``persistent=False`` and aren't in
# ``ROPE_INIT_FUNCTIONS`` come out of ``from_pretrained``'s
# post-init chain holding garbage (~ -1.7e38 / 9.9e33). The
# very first text-LM forward then emits NaN logits.
# See vllm_omni.model_executor.models.utils.reinit_rotary_inv_freq
# for the full mechanism and reproduction.
n_fixed = reinit_rotary_inv_freq(lm, base=10000.0)
if n_fixed > 0:
logger.info("MOSS-TTS-Nano: re-initialised %d rotary_emb.inv_freq buffers", n_fixed)
self._lm: nn.Module = lm
logger.info("MOSS-TTS-Nano LM loaded on %s", device)
codec_path: str = getattr(
self.config,
"audio_tokenizer_pretrained_name_or_path",
"OpenMOSS-Team/MOSS-Audio-Tokenizer-Nano",
)
logger.info("Loading MOSS-Audio-Tokenizer-Nano from %s", codec_path)
from transformers import AutoModel
audio_tokenizer = AutoModel.from_pretrained(
codec_path,
trust_remote_code=True,
torch_dtype=torch.float32,
)
audio_tokenizer.to(device=device)
audio_tokenizer.eval()
self._audio_tokenizer: nn.Module = audio_tokenizer
logger.info("MOSS-Audio-Tokenizer-Nano loaded on %s", device)
# Kept for API compat; vLLM worker init is single-threaded.
self._lock = threading.Lock()
# Per-request streaming generators (VoxCPM pattern).
@@ -158,82 +223,12 @@ class MossTTSNanoForGeneration(nn.Module):
# ------------------------------------------------------------------
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
with self._lock:
if self._lm is not None:
return None
_patch_torchaudio_load()
try:
device = next(self.parameters()).device
except StopIteration:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self._device = device
if device.type == "cuda" and torch.cuda.is_bf16_supported():
tts_dtype = torch.bfloat16
elif device.type == "cuda":
tts_dtype = torch.float16
else:
tts_dtype = torch.float32
logger.info("Loading MOSS-TTS-Nano LM from %s (dtype=%s)", self.model_path, tts_dtype)
from transformers import AutoModelForCausalLM
lm = AutoModelForCausalLM.from_pretrained(
self.model_path,
trust_remote_code=True,
torch_dtype=tts_dtype,
)
if device.type == "cuda":
try:
import flash_attn # noqa: F401
lm._set_attention_implementation("flash_attention_2")
logger.info("MOSS-TTS-Nano using flash_attention_2")
except ImportError:
lm._set_attention_implementation("sdpa")
logger.info("MOSS-TTS-Nano using sdpa (flash_attn not installed)")
lm.to(device=device)
lm.eval()
# ``trust_remote_code`` custom RoPE classes that register
# ``inv_freq`` with ``persistent=False`` and aren't in
# ``ROPE_INIT_FUNCTIONS`` come out of ``from_pretrained``'s
# post-init chain holding garbage (~ -1.7e38 / 9.9e33). The
# very first text-LM forward then emits NaN logits.
# See vllm_omni.model_executor.models.utils.reinit_rotary_inv_freq
# for the full mechanism and reproduction.
n_fixed = reinit_rotary_inv_freq(lm, base=10000.0)
if n_fixed > 0:
logger.info("MOSS-TTS-Nano: re-initialised %d rotary_emb.inv_freq buffers", n_fixed)
self._lm = lm
logger.info("MOSS-TTS-Nano LM loaded on %s", device)
codec_path: str = getattr(
self.config,
"audio_tokenizer_pretrained_name_or_path",
"OpenMOSS-Team/MOSS-Audio-Tokenizer-Nano",
)
logger.info("Loading MOSS-Audio-Tokenizer-Nano from %s", codec_path)
from transformers import AutoModel
audio_tokenizer = AutoModel.from_pretrained(
codec_path,
trust_remote_code=True,
torch_dtype=torch.float32,
)
audio_tokenizer.to(device=device)
audio_tokenizer.eval()
self._audio_tokenizer = audio_tokenizer
logger.info("MOSS-Audio-Tokenizer-Nano loaded on %s", device)
# MOSS-TTS-Nano loads weights inline via from_pretrained() above;
# vLLM's weight-loading protocol still requires us to exhaust the
# iterator so the underlying stream is closed cleanly.
# Weights are populated in __init__ via from_pretrained; drain the
# iterator and report all params as loaded. Not called under
# load_format=dummy (DummyModelLoader randomises params in place).
for _ in weights:
pass
return None
return {name for name, _ in self.named_parameters()}
# ------------------------------------------------------------------
# Dummy run support
@@ -400,13 +395,6 @@ class MossTTSNanoForGeneration(nn.Module):
runtime_additional_information: list[dict[str, Any]] | None = None,
**kwargs: Any,
) -> OmniOutput:
if self._lm is None or self._audio_tokenizer is None:
# load_weights() loads the real LM from HuggingFace. When
# load_format=dummy the vllm DummyModelLoader skips calling
# model.load_weights(), so we do it lazily on first forward.
# Must happen before _make_dummy_hidden so self._device is set.
self.load_weights([])
sr = getattr(self.config, "audio_tokenizer_sample_rate", 48000)
sr_tensor = torch.tensor(sr, dtype=torch.int32)
empty = torch.zeros((0,), dtype=torch.float32)
@@ -1,8 +1,9 @@
"""Thin Omni wrapper: reuse upstream Qwen2.5-Omni thinker (v0.14) with minimal overrides."""
"""Thin Omni wrapper: reuse upstream Qwen2.5-Omni thinker with minimal overrides."""
from collections.abc import Iterable, Mapping
from collections.abc import Iterable, Iterator, Mapping
from typing import Any
import numpy as np
import torch
from torch import nn
from transformers.models.qwen2_5_omni.configuration_qwen2_5_omni import (
@@ -49,9 +50,7 @@ from vllm.model_executor.models.utils import (
WeightsMapper,
init_vllm_registered_model,
maybe_prefix,
split_list_into_ranges,
)
from vllm.model_executor.models.vision import get_llm_pos_ids_for_vision
from vllm.multimodal import MULTIMODAL_REGISTRY
from vllm.multimodal.inputs import (
MultiModalFeatureSpec,
@@ -92,20 +91,15 @@ class Qwen2_5OmniThinkerMultiModalProcessor(
self._validate_mm_kwargs(mm_kwargs, mm_item_counts)
self._validate_mm_updates(mm_prompt_updates, mm_item_counts)
# Detect use_audio_in_video from mm_kwargs
use_audio_in_video = False
if "video" in mm_kwargs:
non_none_items = [item for item in mm_kwargs["video"] if item is not None]
if non_none_items:
for item in non_none_items:
if item.get("use_audio_in_video"):
uaiv_tensor = item["use_audio_in_video"].data
if uaiv_tensor.numel() > 0:
use_audio_in_video = bool(uaiv_tensor.item())
break
elif "audio" in mm_prompt_updates:
tokenizer = self.info.get_tokenizer()
audio_pad_id = tokenizer.convert_tokens_to_ids("<|audio_pad|>")
use_audio_in_video = audio_pad_id not in prompt_ids
for item in mm_kwargs["video"]:
if item and item.get("use_audio_in_video"):
use_audio_in_video_tensor = item["use_audio_in_video"].data
if use_audio_in_video_tensor.numel() > 0:
use_audio_in_video = bool(use_audio_in_video_tensor.item())
break
# for mutilmodality cache
if any(item is None for item in mm_kwargs["video"]):
video_token_id = self.info.get_hf_config().video_token_id
@@ -421,167 +415,193 @@ class Qwen2_5OmniThinkerForConditionalGeneration(
def get_language_model(self) -> torch.nn.Module:
return self.language_model
def _get_audio_for_video_mapping(self, mm_features: list[MultiModalFeatureSpec]) -> tuple[dict[int, int], set[int]]:
"""
Map video offset -> paired audio_feature_length for use_audio_in_video.
When use_audio_in_video=True, audio is interleaved within video chunks.
The pairing is based on feature order in mm_features.
"""
videos_with_audio = [
f
for f in mm_features
if f.modality == "video" and f.data.get("use_audio_in_video") and f.data["use_audio_in_video"].data.item()
]
audios = [f for f in mm_features if f.modality == "audio"]
mapping: dict[int, int] = {}
paired_audio_offsets: set[int] = set()
for i, video_f in enumerate(videos_with_audio):
if i < len(audios):
audio_len = audios[i].data["audio_feature_lengths"].data.item()
mapping[video_f.mm_position.offset] = audio_len
paired_audio_offsets.add(audios[i].mm_position.offset)
return mapping, paired_audio_offsets
def _compute_audio_token_count(self, audio_feature_length: int) -> int:
return ((audio_feature_length - 1) // 2 + 1 - 2) // 2 + 1
def iter_mm_features(self, mm_features: list[MultiModalFeatureSpec]) -> Iterator[tuple[int, str, dict[str, Any]]]:
thinker_config = self.config
spatial_merge_size = thinker_config.vision_config.spatial_merge_size
tokens_per_second = getattr(thinker_config.vision_config, "tokens_per_second", 25)
sorted_features = sorted(mm_features, key=lambda f: f.mm_position.offset)
audio_for_video, paired_audio_offsets = self._get_audio_for_video_mapping(sorted_features)
for mm_feature in sorted_features:
offset = mm_feature.mm_position.offset
modality = mm_feature.modality
if modality == "image":
t, h, w = mm_feature.data["image_grid_thw"].data.tolist()
yield (
offset,
"image",
{
"grid_t": t,
"grid_h": h // spatial_merge_size,
"grid_w": w // spatial_merge_size,
"t_factor": 1.0 * tokens_per_second,
},
)
elif modality == "video":
t, h, w = mm_feature.data["video_grid_thw"].data.tolist()
second_per_grid_ts = 1.0
if mm_feature.data.get("second_per_grid_ts"):
second_per_grid_ts = mm_feature.data["second_per_grid_ts"].data.item()
use_audio_in_video = False
if mm_feature.data.get("use_audio_in_video"):
use_audio_in_video = bool(mm_feature.data["use_audio_in_video"].data.item())
yield (
offset,
"video",
{
"grid_t": t,
"grid_h": h // spatial_merge_size,
"grid_w": w // spatial_merge_size,
"t_factor": second_per_grid_ts * tokens_per_second,
"use_audio_in_video": use_audio_in_video,
"audio_feature_length": audio_for_video.get(offset),
},
)
elif modality == "audio":
if offset not in paired_audio_offsets:
audio_len = mm_feature.data["audio_feature_lengths"].data.item()
yield offset, "audio", {"audio_feature_length": audio_len}
def _compute_interleaved_positions(self, start_idx: int, data: dict[str, Any]) -> tuple[np.ndarray, int]:
grid_t = data["grid_t"]
grid_h = data["grid_h"]
grid_w = data["grid_w"]
t_factor = data["t_factor"]
audio_len = data["audio_feature_length"]
thinker_config = self.config
tokens_per_second = getattr(thinker_config.vision_config, "tokens_per_second", 25)
seconds_per_chunk = thinker_config.seconds_per_chunk
t_ntoken_per_chunk = int(tokens_per_second * seconds_per_chunk)
t_index = (np.arange(grid_t) * t_factor).astype(np.int64)
t_index_split_chunk: list[list[int]] = [[] for _ in range((int(t_index.max()) // t_ntoken_per_chunk) + 1)]
for t_val in t_index:
idx = int(t_val) // t_ntoken_per_chunk
t_index_split_chunk[idx].append(int(t_val))
pure_audio_len = self._compute_audio_token_count(audio_len)
added_audio_len = 0
pos_ids_list: list[np.ndarray] = []
audio_start_idx = start_idx
for t_chunk in t_index_split_chunk:
if not t_chunk:
continue
chunk_t = len(t_chunk)
h_indices = np.tile(np.arange(grid_h).reshape(1, -1, 1), (chunk_t, 1, grid_w)).flatten()
w_indices = np.tile(np.arange(grid_w).reshape(1, 1, -1), (chunk_t, grid_h, 1)).flatten()
t_indices = np.repeat(np.array(t_chunk), grid_h * grid_w)
vision_pos = np.stack([t_indices, h_indices, w_indices]) + start_idx
pos_ids_list.append(vision_pos)
audio_chunk_size = min(t_ntoken_per_chunk, pure_audio_len - added_audio_len)
if audio_chunk_size > 0:
audio_pos = np.broadcast_to(np.arange(audio_chunk_size), (3, audio_chunk_size)) + audio_start_idx
pos_ids_list.append(audio_pos)
audio_start_idx = audio_start_idx + audio_chunk_size
added_audio_len += audio_chunk_size
if added_audio_len < pure_audio_len:
remaining = pure_audio_len - added_audio_len
remaining_audio_pos = np.broadcast_to(np.arange(remaining), (3, remaining)) + audio_start_idx
pos_ids_list.append(remaining_audio_pos)
vision_tokens = grid_t * grid_h * grid_w
total_tokens = vision_tokens + pure_audio_len
return np.concatenate(pos_ids_list, axis=1), total_tokens
def get_mrope_input_positions(
self,
input_tokens: list[int],
mm_features: list[MultiModalFeatureSpec],
) -> tuple[torch.Tensor, int]:
"""
Example:
llm_pos_ids_list: list[np.ndarray] = []
st = 0
(V_i are vision position ids, A_i are audio position ids)
for offset, modality, data in self.iter_mm_features(mm_features):
text_len = offset - st
st_idx = int(llm_pos_ids_list[-1].max()) + 1 if llm_pos_ids_list else 0
if text_len > 0:
llm_pos_ids_list.append(np.broadcast_to(np.arange(text_len), (3, text_len)) + st_idx)
st_idx += text_len
|V_1 ... V_n|A_1 ... A_n|V_n+1 ... V_2n|A_n+1 ... A_2n|...
|vision chunk 1|audio chunk 1|vision chunk 2|audio chunk 2 |...
"""
kwargs = MultiModalFeatureSpec.gather_kwargs(
mm_features,
{
"image_grid_thw",
"video_grid_thw",
"second_per_grid_ts",
"audio_feature_lengths",
"use_audio_in_video",
},
)
image_grid_thw = kwargs.get("image_grid_thw", [])
video_grid_thw = kwargs.get("video_grid_thw", [])
second_per_grid_ts = kwargs.get("second_per_grid_ts", [])
audio_feature_lengths = kwargs.get("audio_feature_lengths", [])
use_audio_in_video = any(kwargs.get("use_audio_in_video", []))
if modality == "audio":
audio_tokens = self._compute_audio_token_count(data["audio_feature_length"])
llm_pos_ids_list.append(np.broadcast_to(np.arange(audio_tokens), (3, audio_tokens)) + st_idx)
st = offset + audio_tokens
image_grid_thw = (torch.stack if image_grid_thw else torch.tensor)(image_grid_thw)
video_grid_thw = (torch.stack if video_grid_thw else torch.tensor)(video_grid_thw)
elif modality == "image":
grid_t = data["grid_t"]
grid_h = data["grid_h"]
grid_w = data["grid_w"]
t_factor = data["t_factor"]
# TODO(fyabc): refactor and share more code with
# _vl_get_input_positions_tensor.
grid_indices = np.indices((grid_t, grid_h, grid_w))
if t_factor != 1.0:
grid_indices[0] = (grid_indices[0] * t_factor).astype(np.int64)
llm_pos_ids_list.append(grid_indices.reshape(3, -1) + st_idx)
st = offset + grid_t * grid_h * grid_w
thinker_config = self.config
audio_token_id = thinker_config.audio_token_index
image_token_id = thinker_config.image_token_index
video_token_id = thinker_config.video_token_index
audio_start_token_id = thinker_config.audio_start_token_id
audio_end_token_id = thinker_config.audio_end_token_id
vision_start_token_id = thinker_config.vision_start_token_id
vision_end_token_id = thinker_config.vision_end_token_id
seconds_per_chunk = thinker_config.seconds_per_chunk
spatial_merge_size = thinker_config.vision_config.spatial_merge_size
tokens_per_second = getattr(thinker_config.vision_config, "tokens_per_second", 25)
elif modality == "video":
grid_t = data["grid_t"]
grid_h = data["grid_h"]
grid_w = data["grid_w"]
t_factor = data["t_factor"]
src_item = input_tokens
audio_seqlens = audio_feature_lengths
if not second_per_grid_ts:
second_per_grid_ts = [1] * video_grid_thw.shape[0]
audio_idx = 0
video_idx = 0
image_idx = 0
new_src_item: list[int] = []
llm_pos_ids_list: list[torch.Tensor] = []
if not data["use_audio_in_video"]:
grid_indices = np.indices((grid_t, grid_h, grid_w))
if t_factor != 1.0:
grid_indices[0] = (grid_indices[0] * t_factor).astype(np.int64)
llm_pos_ids_list.append(grid_indices.reshape(3, -1) + st_idx)
st = offset + grid_t * grid_h * grid_w
else:
pos_ids, token_count = self._compute_interleaved_positions(st_idx, data)
llm_pos_ids_list.append(pos_ids)
st = offset + token_count
idx = 0
while idx < len(src_item):
new_src_item_len = len(new_src_item)
start_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0
if src_item[idx] not in [audio_token_id, video_token_id, image_token_id]:
if use_audio_in_video and idx > 0:
if src_item[idx] == vision_end_token_id and src_item[idx - 1] == audio_end_token_id:
# processing the <|audio_eos|> before <|vision_eos|>
start_idx -= 1
elif src_item[idx] == audio_start_token_id and src_item[idx - 1] == vision_start_token_id:
# processing the <|audio_bos|> after <|vision_eos|>
start_idx -= 1
new_src_item.append(src_item[idx])
llm_pos_ids = torch.tensor([start_idx], dtype=torch.long).expand(3, -1)
llm_pos_ids_list.append(llm_pos_ids)
elif src_item[idx] == audio_token_id:
assert audio_seqlens is not None
audio_seqlen = audio_seqlens[audio_idx]
place_num = ((audio_seqlen - 1) // 2 + 1 - 2) // 2 + 1
new_src_item.extend([audio_token_id] * place_num)
llm_pos_ids = torch.arange(place_num).expand(3, -1) + start_idx
llm_pos_ids_list.append(llm_pos_ids)
audio_idx += 1
elif src_item[idx] == image_token_id:
grid_t = image_grid_thw[image_idx][0]
grid_hs = image_grid_thw[:, 1]
grid_ws = image_grid_thw[:, 2]
t_index = (torch.arange(grid_t) * 1 * tokens_per_second).long()
llm_pos_ids = get_llm_pos_ids_for_vision(
start_idx, image_idx, spatial_merge_size, t_index, grid_hs, grid_ws
)
llm_pos_ids_list.append(llm_pos_ids)
vision_seqlen = image_grid_thw[image_idx].prod() // (spatial_merge_size**2)
new_src_item.extend([image_token_id] * vision_seqlen)
image_idx += 1
elif src_item[idx] == video_token_id and not use_audio_in_video:
grid_t = video_grid_thw[video_idx][0]
grid_hs = video_grid_thw[:, 1]
grid_ws = video_grid_thw[:, 2]
t_index = (torch.arange(grid_t) * second_per_grid_ts[video_idx] * tokens_per_second).long()
llm_pos_ids = get_llm_pos_ids_for_vision(
start_idx, video_idx, spatial_merge_size, t_index, grid_hs, grid_ws
)
llm_pos_ids_list.append(llm_pos_ids)
vision_seqlen = video_grid_thw[video_idx].prod() // (spatial_merge_size**2)
new_src_item.extend([video_token_id] * vision_seqlen)
video_idx += 1
else:
# read audio from video
assert audio_seqlens is not None
audio_seqlen = audio_seqlens[audio_idx]
vision_seqlen = video_grid_thw[video_idx].prod() // (spatial_merge_size**2)
grid_t = video_grid_thw[video_idx][0]
grid_h = video_grid_thw[video_idx][1]
grid_w = video_grid_thw[video_idx][2]
grid_hs = video_grid_thw[:, 1]
grid_ws = video_grid_thw[:, 2]
t_ntoken_per_chunk = int(tokens_per_second * seconds_per_chunk)
t_index = (torch.arange(grid_t) * second_per_grid_ts[video_idx] * tokens_per_second).long()
t_index_split_chunk = split_list_into_ranges(t_index, t_ntoken_per_chunk)
place_num = (((audio_seqlen - 1) // 2 + 1 - 2) // 2 + 1) + 2
pure_audio_len = place_num - 2
added_audio_len = 0
audio_llm_pos_ids_list: list[torch.Tensor] = []
for t_chunk in t_index_split_chunk:
vision_ntoken_per_chunk = len(t_chunk) * grid_h * grid_w // (spatial_merge_size**2)
new_src_item.extend([video_token_id] * vision_ntoken_per_chunk)
vision_llm_pos_ids_list = get_llm_pos_ids_for_vision(
start_idx,
video_idx,
spatial_merge_size,
t_chunk,
grid_hs,
grid_ws,
).split(1, dim=1)
llm_pos_ids_list.extend(vision_llm_pos_ids_list)
new_src_item.extend(min(t_ntoken_per_chunk, pure_audio_len - added_audio_len) * [audio_token_id])
audio_start_idx = (
start_idx if len(audio_llm_pos_ids_list) == 0 else audio_llm_pos_ids_list[-1][0].item() + 1
)
if min(t_ntoken_per_chunk, pure_audio_len - added_audio_len) > 0:
audio_llm_pos_ids_list = (
torch.arange(min(t_ntoken_per_chunk, pure_audio_len - added_audio_len)).expand(3, -1)
+ audio_start_idx
).split(1, dim=1)
else:
audio_llm_pos_ids_list = []
added_audio_len += min(t_ntoken_per_chunk, pure_audio_len - added_audio_len)
llm_pos_ids_list.extend(audio_llm_pos_ids_list)
if added_audio_len < pure_audio_len:
new_src_item.extend((pure_audio_len - added_audio_len) * [audio_token_id])
audio_llm_pos_ids_list = (
torch.arange(pure_audio_len - added_audio_len).expand(3, -1) + llm_pos_ids_list[-1].max() + 1
).split(1, dim=1)
llm_pos_ids_list.extend(audio_llm_pos_ids_list)
audio_idx += 1
video_idx += 1
# move to the next token
idx += len(new_src_item) - new_src_item_len
if st < len(input_tokens):
st_idx = int(llm_pos_ids_list[-1].max()) + 1 if llm_pos_ids_list else 0
text_len = len(input_tokens) - st
llm_pos_ids_list.append(np.broadcast_to(np.arange(text_len), (3, text_len)) + st_idx)
llm_positions = torch.cat(llm_pos_ids_list, dim=1)
mrope_position_delta = torch.cat(llm_pos_ids_list, dim=1).max() + 1 - len(src_item)
llm_positions = np.concatenate(llm_pos_ids_list, axis=1).reshape(3, -1)
mrope_position_delta = int(llm_positions.max()) + 1 - len(input_tokens)
return llm_positions, mrope_position_delta
return torch.from_numpy(llm_positions), mrope_position_delta
def embed_multimodal(self, **kwargs: object) -> MultiModalEmbeddings:
mm_input_by_modality = self._parse_and_validate_multimodal_inputs(**kwargs)
@@ -629,14 +649,12 @@ class Qwen2_5OmniThinkerForConditionalGeneration(
# Check for audio-in-video: interleaved video and audio tokens
# in the multimodal region. Only use the interleaved path when
# needed; otherwise fall back to the default parent implementation.
# vLLM's _gather_mm_embeddings builds is_multimodal on CPU for merge
# indexing; bitwise ops with input_ids require the same device.
is_mm_device = is_multimodal.to(device=input_ids.device, non_blocking=True)
video_token_id = self.config.video_token_index
audio_token_id = self.config.audio_token_index
is_video = is_mm_device & (input_ids == video_token_id)
is_audio = is_mm_device & (input_ids == audio_token_id)
input_ids_cpu = input_ids.cpu()
is_video = is_multimodal & (input_ids_cpu == video_token_id)
is_audio = is_multimodal & (input_ids_cpu == audio_token_id)
num_video = is_video.sum().item()
num_audio = is_audio.sum().item()
@@ -652,7 +670,7 @@ class Qwen2_5OmniThinkerForConditionalGeneration(
multimodal_embeddings,
is_video,
is_audio,
is_mm_device,
is_multimodal,
num_video,
num_audio,
)
@@ -758,17 +758,11 @@ class Qwen3OmniMoeThinkerMultiModalProcessor(
use_audio_in_video = False
if "video" in mm_kwargs:
non_none_items = [item for item in mm_kwargs["video"] if item is not None]
if non_none_items:
# Normal case: at least one non-cached item, read flag directly
use_audio_in_video = any(item["use_audio_in_video"].data for item in non_none_items)
elif "audio" in mm_prompt_updates:
# All video items are from cache (None); infer from prompt:
# use_audio_in_video=True means the prompt has no <|audio_pad|>
# placeholder (audio is embedded in video tokens instead)
tokenizer = self.info.get_tokenizer()
audio_pad_id = tokenizer.convert_tokens_to_ids("<|audio_pad|>")
use_audio_in_video = audio_pad_id not in prompt_ids
for item in mm_kwargs["video"]:
if item and item["use_audio_in_video"].data:
use_audio_in_video = True
else:
use_audio_in_video = False
# for mutilmodality cache
if any(item is None for item in mm_kwargs["video"]):
video_token_id = self.info.get_hf_config().video_token_id
@@ -7,6 +7,7 @@ This module provides CUDA Graph acceleration for the speech tokenizer decoder,
reducing kernel launch overhead during inference.
"""
import bisect
import os
import time
from collections import Counter
@@ -225,9 +226,11 @@ class CUDAGraphDecoderWrapper:
return sorted(sizes)
def _get_padded_size(self, actual_size: int) -> int | None:
for size in self._bucket_sizes:
if actual_size <= size:
return size
# bisect_left over the pre-sorted _bucket_sizes is O(log n) vs the linear scan;
# this matters because _decode invokes it on every per-chunk replay.
idx = bisect.bisect_left(self._bucket_sizes, actual_size)
if idx < len(self._bucket_sizes):
return self._bucket_sizes[idx]
return None
def _get_capture_shapes(self) -> list[tuple[int, int]]:
@@ -545,7 +545,8 @@ class Qwen3TTSCode2Wav(nn.Module):
continue
wav = wav[start : min(end, wav.shape[0])]
if wav.shape[0] > 0:
audios[idx] = wav.to(dtype=torch.float32).reshape(-1)
# Decoder already runs in fp32, so the .to(float32) is a redundant dispatch.
audios[idx] = (wav if wav.dtype == torch.float32 else wav.to(torch.float32)).reshape(-1)
for req_id, finished in zip(ref_context_request_ids, finished_flags, strict=False):
if req_id is not None and finished:
@@ -368,6 +368,7 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
)
# Constant logit mask: allow only codec ids [1, codebook_vocab_size) plus codec EOS.
# Register the *disallowed* form so compute_logits doesn't recompute ~mask per step.
vocab = int(self.talker_config.vocab_size)
codec_mask = torch.zeros((vocab,), dtype=torch.bool)
lo, hi = 1, min(self._codebook_vocab_size, vocab)
@@ -375,7 +376,7 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
codec_mask[lo:hi] = True
if 0 <= self._codec_eos_token_id < vocab:
codec_mask[self._codec_eos_token_id] = True
self.register_buffer("_codec_allowed_mask", codec_mask, persistent=False)
self.register_buffer("_codec_disallowed_mask", ~codec_mask, persistent=False)
# Keys that should stay on GPU in model_intermediate_buffer to avoid
# CPU-to-GPU round-trips on every decode step.
@@ -513,7 +514,7 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
return None
# Mask out invalid codec ids using the pre-built constant buffer.
logits = logits.masked_fill(~self._codec_allowed_mask, float("-inf"))
logits = logits.masked_fill(self._codec_disallowed_mask, float("-inf"))
if self._eos_logit_bias != 0.0:
eos_id = self._codec_eos_token_id
@@ -198,10 +198,21 @@ class Qwen3TTSTokenizerV2CausalConvNet(nn.Module):
self.padding = self.kernel_size - self.stride
def _get_extra_padding_for_conv1d(self, hidden_state: torch.Tensor) -> int:
# Cache the result per input length — under cudagraph capture the set of lengths
# is fixed, so the LUT converges quickly and replaces the math.ceil call per replay.
length = hidden_state.shape[-1]
cache = self.__dict__.get("_pad_lut")
if cache is None:
cache = {}
self.__dict__["_pad_lut"] = cache
cached = cache.get(length)
if cached is not None:
return cached
n_frames = (length - self.kernel_size + self.padding) / self.stride + 1
ideal_length = (math.ceil(n_frames) - 1) * self.stride + (self.kernel_size - self.padding)
return ideal_length - length
extra_padding = ideal_length - length
cache[length] = extra_padding
return extra_padding
def forward(self, hidden_state):
extra_padding = self._get_extra_padding_for_conv1d(hidden_state)
@@ -119,6 +119,22 @@ _OMNI_MODELS = {
"higgs_audio_v2_code2wav",
"HiggsAudioV2Code2WavForConditionalGeneration",
),
## higgs-audio v3
"HiggsMultimodalQwen3ForConditionalGeneration": (
"higgs_audio_v3",
"higgs_audio_v3_talker",
"HiggsAudioV3TalkerForConditionalGeneration",
),
"HiggsAudioV3TalkerForConditionalGeneration": (
"higgs_audio_v3",
"higgs_audio_v3_talker",
"HiggsAudioV3TalkerForConditionalGeneration",
),
"HiggsAudioV3Code2WavForConditionalGeneration": (
"higgs_audio_v3",
"higgs_audio_v3_code2wav",
"HiggsAudioV3Code2WavForConditionalGeneration",
),
## mimo_audio
"MiMoAudioModel": (
"mimo_audio",
@@ -140,6 +156,22 @@ _OMNI_MODELS = {
"mimo_audio_code2wav",
"MiMoAudioToken2WavForConditionalGenerationVLLM",
),
## ming-tts
"MingTTSForConditionalGeneration": (
"ming_tts",
"ming_tts",
"MingTTSForConditionalGeneration",
),
"MingLLMModel": (
"ming_tts",
"ming_tts_llm",
"MingLLMModel",
),
"MingAudioVAEModel": (
"ming_tts",
"ming_tts_audio_vae",
"MingAudioVAEModel",
),
## glm_image
"GlmImageForConditionalGeneration": (
"glm_image",
@@ -36,6 +36,7 @@ from vllm.platforms import current_platform
from vllm.sequence import IntermediateTensors
from vllm_omni.model_executor.models.output_templates import OmniOutput
from vllm_omni.platforms import current_omni_platform
from vllm_omni.utils.speaker_cache import (
get_speaker_cache,
iter_custom_voice_profiles,
@@ -824,7 +825,7 @@ def _optimized_solve_euler_with_noise(
t = t - dt
if step < len(t_span) - 1:
dt = t - t_span[step + 1]
return x
return x.clone()
# ===================================================================
@@ -863,11 +864,11 @@ class VoxCPM2TalkerForConditionalGeneration(nn.Module):
# the checkpoint download/read cost at construction time; DummyModelLoader
# will then randomize the just-loaded _tts params — this is intended.
model_path = vllm_config.model_config.model
self._device = current_omni_platform.get_torch_device()
VoxCPM = import_voxcpm2_core()
native = VoxCPM.from_pretrained(model_path, load_denoiser=False, optimize=False)
self._tts: nn.Module = native.tts_model.to("cuda")
self._tts: nn.Module = native.tts_model.to(self._device)
self._side_dtype = self._tts.fusion_concat_proj.weight.dtype
self._device = "cuda"
self._patch_size = self._tts.patch_size
self._feat_dim = self._tts.feat_dim
self._sample_rate = getattr(self.config, "sample_rate", 48000)
@@ -888,8 +889,9 @@ class VoxCPM2TalkerForConditionalGeneration(nn.Module):
# for sliding-window streaming decode. 12 matches the nanovllm reference
# implementation and covers the longest VAE decoder receptive field.
self._n_decode_pad_frames = 12
self._enable_torch_compile = True
self._compile_vae = True
use_cuda_graph = current_omni_platform.is_cuda()
self._enable_torch_compile = current_omni_platform.supports_torch_inductor()
self._compile_vae = self._enable_torch_compile
self._max_decode_steps = 2000
self._max_batch_size = getattr(vllm_config.scheduler_config, "max_num_seqs", 4)
@@ -900,15 +902,15 @@ class VoxCPM2TalkerForConditionalGeneration(nn.Module):
self._enable_profiling = self._runtime_config.enable_profiling
self._perf = _PerfTimer(enabled=self._enable_profiling)
self._cfm_buffers: _CFMBufferManager | None = None
self._enable_cuda_graph = True
self._enable_cuda_graph = use_cuda_graph
self._scaffold_graphs: dict[int, _CapturedGraph] = {}
self._residual_graphs: dict[int, _CapturedGraph] = {}
self._decode_graph_capture_policy = self._runtime_config.decode_graph_capture_policy
self._vae_graphs: dict[tuple[int, int], _CapturedVAEGraph] = {}
self._enable_vae_cuda_graph = self._runtime_config.enable_vae_cuda_graph
self._enable_vae_cuda_graph = use_cuda_graph and self._runtime_config.enable_vae_cuda_graph
self._cfm_graphs: dict[int, _CapturedCFMGraph] = {}
self._enable_cfm_cuda_graph = self._runtime_config.enable_cfm_cuda_graph
self._enable_cfm_prealloc_output = self._runtime_config.enable_cfm_prealloc_output
self._enable_cfm_cuda_graph = use_cuda_graph and self._runtime_config.enable_cfm_cuda_graph
self._enable_cfm_prealloc_output = use_cuda_graph and self._runtime_config.enable_cfm_prealloc_output
self._enable_batched_cfm = self._runtime_config.enable_batched_cfm
self._deterministic_cfm_noise = self._runtime_config.deterministic_cfm_noise
self._deterministic_cfm_seed = self._runtime_config.deterministic_cfm_seed
@@ -916,7 +918,7 @@ class VoxCPM2TalkerForConditionalGeneration(nn.Module):
self._audio_emit_every = self._runtime_config.audio_emit_every
self._vae_decode_every = self._runtime_config.vae_decode_every
self._enable_delayed_audio_copy = self._runtime_config.enable_delayed_audio_copy
self._delayed_audio_copy_use_events = self._runtime_config.delayed_audio_copy_use_events
self._delayed_audio_copy_use_events = use_cuda_graph and self._runtime_config.delayed_audio_copy_use_events
self._coalesce_audio_d2h = self._runtime_config.coalesce_audio_d2h
self._enable_batched_vae_decode = self._runtime_config.enable_batched_vae_decode
self._enable_batched_fsq_fusion = self._runtime_config.enable_batched_fsq_fusion
@@ -1382,7 +1384,7 @@ class VoxCPM2TalkerForConditionalGeneration(nn.Module):
return sr_cond
def _run_vae_decode(self, feat: torch.Tensor) -> torch.Tensor:
if not feat.is_cuda:
if feat.device.type != current_omni_platform.device_type:
return self.tts.audio_vae.decode(feat)
sr_cond = self._get_vae_decode_sr_cond(feat.device)
@@ -1817,7 +1819,7 @@ class VoxCPM2TalkerForConditionalGeneration(nn.Module):
def _run_cfm(self, dit_h: torch.Tensor, cond: torch.Tensor) -> torch.Tensor:
with _NvtxRange("voxcpm2.cfm"):
if self._cfm_buffers is not None:
if self._enable_cfm_cuda_graph and dit_h.is_cuda:
if self._enable_cfm_cuda_graph and dit_h.device.type == current_omni_platform.device_type:
return self._run_cfm_cuda_graph(dit_h, cond).transpose(1, 2)
return _optimized_solve_euler(
self.tts.feat_decoder,
@@ -1841,7 +1843,7 @@ class VoxCPM2TalkerForConditionalGeneration(nn.Module):
def _run_cfm_for_state(self, state: _RequestState, dit_h: torch.Tensor, cond: torch.Tensor) -> torch.Tensor:
with _NvtxRange("voxcpm2.cfm"):
if self._cfm_buffers is not None:
if self._enable_cfm_cuda_graph and dit_h.is_cuda:
if self._enable_cfm_cuda_graph and dit_h.device.type == current_omni_platform.device_type:
if self._deterministic_cfm_noise and not self._enable_cfm_prealloc_output:
graph = self._get_cfm_cuda_graph(dit_h, cond)
with _NvtxRange("voxcpm2.cfm.graph_copy_mu"):
@@ -2057,7 +2059,7 @@ class VoxCPM2TalkerForConditionalGeneration(nn.Module):
def _enqueue_delayed_audio_copy(self, state: _RequestState, audio: torch.Tensor) -> None:
src = audio.detach().contiguous()
if not src.is_cuda:
if src.device.type != current_omni_platform.device_type:
state.pending_audio_copies.append(_PendingAudioCopy(host=src.cpu().contiguous()))
return
@@ -2145,7 +2147,7 @@ class VoxCPM2TalkerForConditionalGeneration(nn.Module):
if state.is_stopping or state.precomputed_is_stopping is not None:
continue
stop_logits = state.precomputed_stop_logits
if stop_logits is None or not stop_logits.is_cuda:
if stop_logits is None or stop_logits.device.type != current_omni_platform.device_type:
continue
pending.append((state, stop_logits))
if not pending:
@@ -2426,7 +2428,9 @@ class VoxCPM2TalkerForConditionalGeneration(nn.Module):
if self._uses_sparse_audio_outputs():
ready_req_ids = list(audio_by_req)
chunks = [audio_by_req[req_id].reshape(-1) for req_id in ready_req_ids]
if self._coalesce_audio_d2h and any(chunk.is_cuda for chunk in chunks):
if self._coalesce_audio_d2h and any(
chunk.device.type == current_omni_platform.device_type for chunk in chunks
):
sizes = [int(chunk.numel()) for chunk in chunks]
merged = torch.cat(chunks, dim=0) if len(chunks) > 1 else chunks[0]
merged_cpu = merged.detach().cpu().contiguous()
@@ -2435,7 +2439,9 @@ class VoxCPM2TalkerForConditionalGeneration(nn.Module):
mm["model_outputs"] = chunks
mm["sr"] = [sr for _ in ready_req_ids]
mm["meta"] = {"req_id": ready_req_ids, "sparse_audio": ["1"]}
elif self._coalesce_audio_d2h and any(audio.is_cuda for audio in audio_by_req.values()):
elif self._coalesce_audio_d2h and any(
audio.device.type == current_omni_platform.device_type for audio in audio_by_req.values()
):
ready_req_ids = list(audio_by_req)
chunks = [audio_by_req[req_id].reshape(-1) for req_id in ready_req_ids]
sizes = [int(chunk.numel()) for chunk in chunks]
@@ -0,0 +1,38 @@
# Stage config for running HunyuanVideo-1.5 DiT with ModelOpt FP8 auto-detect.
# Single GPU. Bump `tensor_parallel_size` and `devices` for multi-GPU TP.
#
# Use with a ModelOpt FP8 checkpoint (e.g. produced by
# examples/quantization/quantize_hunyuanvideo_15_modelopt_fp8.py).
stage_args:
- stage_id: 0
stage_type: diffusion
runtime:
devices: "0"
max_batch_size: 1
engine_args:
model_stage: dit
model_class_name: HunyuanVideo15Pipeline
max_num_seqs: 1
enforce_eager: true
trust_remote_code: true
distributed_executor_backend: "mp"
# HunyuanVideo-1.5 peak VRAM is dominated by the single-shot VAE decode of
# the full video (the DiT contributes little), so tiling the decode is the
# main memory lever — far more than FP8 (e.g. 480x832x33: ~117 -> ~47 GiB).
# Default it on here; override with --vae-use-tiling/false if you have headroom.
vae_use_tiling: true
parallel_config:
tensor_parallel_size: 1
final_output: true
final_output_type: video
is_comprehension: false
default_sampling_params:
seed: 42
runtime:
enabled: true
defaults:
window_size: -1
max_inflight: 1
@@ -0,0 +1,41 @@
# Stage config for running Wan2.2 TI2V-5B DiT with ModelOpt FP8 auto-detect.
# Single GPU (TI2V-5B fits 80GB BF16; FP8 drops by ~half).
# For the A14B MoE variants, bump `tensor_parallel_size` and `devices`.
#
# Use with a ModelOpt FP8 checkpoint (e.g. produced by
# examples/quantization/quantize_wan2_2_modelopt_fp8.py).
stage_args:
- stage_id: 0
stage_type: diffusion
runtime:
devices: "0"
max_batch_size: 1
engine_args:
model_stage: dit
# Wan2.2 TI2V-5B is served by the base Wan22Pipeline, which auto-detects
# expand_timesteps (TI2V-5B mode) from model_index.json. (The standalone
# Wan22TI2VPipeline was consolidated into Wan22Pipeline upstream.)
model_class_name: Wan22Pipeline
max_num_seqs: 1
enforce_eager: true
trust_remote_code: true
distributed_executor_backend: "mp"
# Tile the VAE decode by default. Wan2.2's 480p peak is DiT-dominated (so
# FP8 is the main lever here), but tiling adds headroom for higher
# resolutions / longer clips at negligible cost. Override with --vae-use-tiling/false.
vae_use_tiling: true
parallel_config:
tensor_parallel_size: 1
final_output: true
final_output_type: video
is_comprehension: false
default_sampling_params:
seed: 42
runtime:
enabled: true
defaults:
window_size: -1
max_inflight: 1
@@ -16,6 +16,7 @@ from vllm_omni.data_entry_keys import (
OmniPayloadStruct,
)
from vllm_omni.inputs.data import OmniTokensPrompt
from vllm_omni.model_executor.models.cosyvoice3.utils import unpad_prompt_conditioning
logger = init_logger(__name__)
@@ -192,18 +193,31 @@ def talker2code2wav_async_chunk(
info = _decode_additional_information(getattr(request, "additional_information", None))
info_embed = info.get("embed", {}) if isinstance(info, dict) else {}
prompt_payload = {}
for key in ("speech_token", "speech_feat", "embedding"):
cond_keys = ("speech_token", "speech_feat", "embedding", "speech_token_len")
for key in cond_keys:
value = _to_cpu_tensor(info_embed.get(key))
if value is not None:
prompt_payload[key] = value
if isinstance(pooling_output, dict):
po_embed = pooling_output.get("embed", {}) if isinstance(pooling_output.get("embed"), dict) else {}
for key in ("speech_token", "speech_feat", "embedding"):
for key in cond_keys:
if key in prompt_payload:
continue
value = _to_cpu_tensor(po_embed.get(key))
if value is not None:
prompt_payload[key] = value
# Drop any right-padding carried from batched talker emission so
# the chunk-routing math (prompt_token_len) and the conditioning
# sent to code2wav use the true prompt length.
if "speech_token" in prompt_payload:
st_unpad, sf_unpad = unpad_prompt_conditioning(
prompt_payload.get("speech_token"),
prompt_payload.get("speech_feat"),
prompt_payload.pop("speech_token_len", None),
)
prompt_payload["speech_token"] = st_unpad
if sf_unpad is not None:
prompt_payload["speech_feat"] = sf_unpad
prompt_token = prompt_payload.get("speech_token")
prompt_token_len = (
int(prompt_token.shape[1])
@@ -0,0 +1,386 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Stage-input processor for higgs-audio v3: Talker -> Code2Wav.
Two adapters:
* ``talker2code2wav`` is the sync (non-async-chunk) adapter that runs once,
after Stage 0 has finished, collecting every audio frame into a single
``OmniTokensPrompt`` for Stage 1.
* ``talker2code2wav_async_chunk`` is the streaming adapter invoked once per
emitted talker step. It accumulates raw delay-pattern rows per request and
flushes a sliding-window chunk to Stage 1 once enough new frames are
available, holding back ``codec_right_holdback_frames`` trailing frames
so the codec has future context for the emit region's tail samples. Stage 1
trims ``left_context_size * hop`` samples off the front and
``right_holdback_size * hop`` off the end before emitting PCM.
Key difference from v2: BOC/EOC filtering happens AFTER delay pattern reversal
to avoid corrupting valid tail content.
"""
from __future__ import annotations
from typing import Any
import torch
from vllm.logger import init_logger
from vllm_omni.data_entry_keys import (
CodesStruct,
MetaStruct,
OmniPayload,
OmniPayloadStruct,
)
from vllm_omni.inputs.data import OmniTokensPrompt
__all__ = ["talker2code2wav", "talker2code2wav_async_chunk"]
logger = init_logger(__name__)
_NUM_CODEBOOKS = 8
_NUM_REAL_CODES = 1024 # codes in [0, 1023] are real
# Defaults for async_chunk streaming when the deploy YAML connector config
# does not override them. Mirrors the qwen3_tts canonical setting at 25 fps
# codec rate (25 frames = ~1.0 s of audio).
_DEFAULT_CODEC_CHUNK_FRAMES = 25
_DEFAULT_CODEC_LEFT_CONTEXT_FRAMES = 25
_DEFAULT_CODEC_RIGHT_HOLDBACK_FRAMES = 4
def _empty_code2wav_prompt() -> Any:
return OmniTokensPrompt(
prompt_token_ids=[],
multi_modal_data=None,
mm_processor_kwargs=None,
additional_information=None,
)
def _revert_delay_pattern(audio_codes_qt: torch.Tensor) -> torch.Tensor:
"""Reverse the MusicGen-style delay pattern.
Input shape: [num_codebooks, seq_len + num_codebooks - 1].
Output shape: [num_codebooks, seq_len].
For each codebook i, extract delayed[i, i : i + seq_len] to remove
the i leading BOC pads and Q-1-i trailing EOC entries.
"""
if audio_codes_qt.ndim != 2:
raise ValueError(f"_revert_delay_pattern expects [Q, T] input; got {tuple(audio_codes_qt.shape)}")
q, t = audio_codes_qt.shape
if q != _NUM_CODEBOOKS:
raise ValueError(f"Expected exactly {_NUM_CODEBOOKS} codebook rows, got {q}. Input shape: [{q}, {t}]")
if t < q:
raise ValueError(f"Not enough frames to revert delay pattern: T={t} < Q={q}")
seq_len = t - q + 1
out_l = []
for i in range(q):
out_l.append(audio_codes_qt[i : i + 1, i : seq_len + i])
return torch.cat(out_l, dim=0)
def _filter_real_code_frames(audio_codes_qt: torch.Tensor) -> torch.Tensor:
"""Keep only frames where ALL codebook values are in [0, 1023].
Input shape: [num_codebooks, num_frames].
Called AFTER delay pattern reversal.
"""
if audio_codes_qt.numel() == 0:
return audio_codes_qt
# Transpose to [num_frames, num_codebooks] for per-frame filtering
frames = audio_codes_qt.t()
valid = (frames >= 0).all(dim=1) & (frames < _NUM_REAL_CODES).all(dim=1)
return frames[valid].t().contiguous()
def talker2code2wav(
source_outputs: list[Any],
prompt: Any = None,
_requires_multimodal_data: bool = False,
) -> list[Any]:
"""Sync: collect all talker codes, revert delay pattern, filter, pass to code2wav."""
code2wav_inputs: list[Any] = []
for talker_output in source_outputs:
if not talker_output.finished:
continue
output = talker_output.outputs[0]
mm = output.multimodal_output
mm_codes = mm.get("codes", {})
audio_codes = mm_codes.get("audio")
if audio_codes is None or not isinstance(audio_codes, torch.Tensor) or audio_codes.numel() == 0:
code2wav_inputs.append(_empty_code2wav_prompt())
continue
audio_codes = audio_codes.to(torch.long)
if audio_codes.ndim == 1:
if audio_codes.numel() % _NUM_CODEBOOKS != 0:
raise ValueError(
f"flat audio_codes length {audio_codes.numel()} not divisible by num_codebooks={_NUM_CODEBOOKS}"
)
audio_codes = audio_codes.reshape(-1, _NUM_CODEBOOKS)
if audio_codes.ndim != 2:
raise ValueError(f"audio_codes must be 1D or 2D; got shape {tuple(audio_codes.shape)}")
# Validate codebook count
if audio_codes.shape[1] != _NUM_CODEBOOKS:
raise ValueError(
f"Expected {_NUM_CODEBOOKS} codebooks per frame, "
f"got {audio_codes.shape[1]}. Audio codes shape: {tuple(audio_codes.shape)}"
)
# Transpose to [Q, T] for delay pattern reversal
codes_qt = audio_codes.transpose(0, 1).contiguous().cpu()
# Step 1: Revert delay pattern
try:
codes_qt = _revert_delay_pattern(codes_qt)
except ValueError as exc:
logger.warning("Skipping invalid Higgs Audio v3 code sequence for Stage 1: %s", exc)
code2wav_inputs.append(_empty_code2wav_prompt())
continue
# Step 2: Replace out-of-range codes (BOC=1024, EOC=1025, -1) with 0.
# Must use torch.where, NOT clamp: clamp(max=1023) turns 1025→1023
# which is a valid codec code and decodes to audio artifacts.
# Matches sglang's: torch.where(codes >= codec_vocab, 0, codes)
codes_qt = torch.where(
(codes_qt >= _NUM_REAL_CODES) | (codes_qt < 0),
torch.zeros_like(codes_qt),
codes_qt,
)
# Step 3: Trim the last frame. After de-delay, the final frame
# contains residual ramp-down codes (EOC→0 substituted) that
# decode to a brief noise artifact at the end of the audio.
if codes_qt.shape[-1] >= 2:
codes_qt = codes_qt[:, :-1]
if codes_qt.numel() == 0:
code2wav_inputs.append(_empty_code2wav_prompt())
continue
# Code2Wav expects codebook-major flat: [Q * num_frames]
codec_codes = codes_qt.reshape(-1).tolist()
code2wav_inputs.append(
OmniTokensPrompt(
prompt_token_ids=codec_codes,
multi_modal_data=None,
mm_processor_kwargs=None,
additional_information=None,
)
)
return code2wav_inputs
# ---------------------------------------------------------------------------
# Async-chunk streaming adapter (sliding window + holdback).
# ---------------------------------------------------------------------------
def _extract_last_step_row(pooling_output: OmniPayload) -> torch.Tensor | None:
"""Return the talker's emit row for this AR step as a flat ``[Q]`` tensor.
The talker postprocess emits ``codes.audio`` as ``[1, Q]`` (most often) or
``[N, Q]`` for multi-active stages. In the async-chunk path
``pooling_output`` is already request-scoped so the typical shape is
``[1, Q]``. Returns ``None`` if there is no row to append at this step.
Rows may carry BOC=1024 in trailing codebooks during the ramp-up phase
(AR steps 0..Q-2). Those are KEPT verbatim — the de-delay window
operation downstream slices them away by construction.
"""
codes = pooling_output.get("codes", {}) if isinstance(pooling_output, dict) else {}
audio_codes = codes.get("audio") if isinstance(codes, dict) else None
if not isinstance(audio_codes, torch.Tensor) or audio_codes.numel() == 0:
return None
if audio_codes.ndim == 2:
row = audio_codes[-1]
elif audio_codes.ndim == 1:
row = audio_codes
else:
raise ValueError(f"unexpected audio_codes shape for higgs_audio_v3 async_chunk: {tuple(audio_codes.shape)}")
if row.numel() != _NUM_CODEBOOKS:
raise ValueError(
f"talker emit row has {row.numel()} codebooks; expected {_NUM_CODEBOOKS} for higgs_audio_v3 async_chunk."
)
return row.to(torch.long).reshape(-1)
def talker2code2wav_async_chunk(
transfer_manager: Any,
pooling_output: OmniPayload | None,
request: Any,
is_finished: bool = False,
) -> OmniPayloadStruct | None:
"""Streaming adapter: per-step accumulator + sliding-window de-delay flush.
Algorithm:
* Append each step's raw delay-pattern row to a per-request buffer.
* Track ``emitted_frames``: how many de-delayed frames' worth of audio
Stage 1 has already emitted for this request.
* With ``N`` accumulated rows we can recover ``N - Q + 1`` de-delayed
frames (the de-delay drops Q-1 leading BOC pads).
* Hold back the trailing ``H = codec_right_holdback_frames`` de-delayed
frames so the codec has future context for the emit region's last
samples. The emit boundary therefore lives at
``target_emit = max(0, de_delayed_total - H)`` for non-final calls
and ``de_delayed_total`` for the final flush.
* When ``target_emit - emitted_frames >= chunk_size`` (or the request
finishes), build a sliding window spanning
``[emitted_frames - L, target_emit + H]`` de-delayed frames; that
corresponds to AR rows
``[emitted_frames - L, target_emit + H + Q - 1]``. Apply de-delay,
replace out-of-range codes with 0, and emit codebook-major flat.
* Stage 1 honors ``meta.left_context_size = L`` (trim front) and
``meta.right_holdback_size = H`` (trim end). Net new audio per call
is ``(target_emit - emitted_frames) * hop_length`` samples.
"""
request_id = request.external_req_id
finished = bool(is_finished or request.is_finished())
# Per-request rolling state. ``code_prompt_token_ids`` is the
# framework-provided buffer; ``higgs_v3_emitted_frames`` tracks how many
# de-delayed frames we have already flushed for this request.
emitted_frames = getattr(transfer_manager, "higgs_v3_emitted_frames", None)
if emitted_frames is None:
emitted_frames = {}
transfer_manager.higgs_v3_emitted_frames = emitted_frames
if isinstance(pooling_output, dict):
row = _extract_last_step_row(pooling_output)
if row is not None:
transfer_manager.code_prompt_token_ids[request_id].append(row.cpu().tolist())
elif not finished:
return None
connector = getattr(transfer_manager, "connector", None)
raw_cfg = getattr(connector, "config", {}) or {}
cfg = raw_cfg.get("extra", raw_cfg) if isinstance(raw_cfg, dict) else {}
chunk_size = int(cfg.get("codec_chunk_frames", _DEFAULT_CODEC_CHUNK_FRAMES))
left_context_size_config = int(cfg.get("codec_left_context_frames", _DEFAULT_CODEC_LEFT_CONTEXT_FRAMES))
right_holdback_size_config = int(cfg.get("codec_right_holdback_frames", _DEFAULT_CODEC_RIGHT_HOLDBACK_FRAMES))
configured_initial_chunk_size = int(cfg.get("initial_codec_chunk_frames") or 0)
if (
chunk_size <= 0
or left_context_size_config < 0
or right_holdback_size_config < 0
or configured_initial_chunk_size < 0
):
raise ValueError(
f"Invalid codec chunk config: codec_chunk_frames={chunk_size}, "
f"codec_left_context_frames={left_context_size_config}, "
f"codec_right_holdback_frames={right_holdback_size_config}, "
f"initial_codec_chunk_frames={configured_initial_chunk_size}"
)
n_rows = len(transfer_manager.code_prompt_token_ids[request_id])
de_delayed_total = max(0, n_rows - (_NUM_CODEBOOKS - 1))
emitted = int(emitted_frames.get(request_id, 0))
# Hold back the trailing H frames from the emit boundary unless the
# request is finishing - the final chunk needs no future context.
H = 0 if finished else right_holdback_size_config
target_emit = max(0, de_delayed_total - H)
pending = target_emit - emitted
# First-chunk fast path for TTFA.
if emitted == 0 and 0 < configured_initial_chunk_size < chunk_size:
target_chunk = configured_initial_chunk_size
else:
target_chunk = chunk_size
if not finished and pending < target_chunk:
return None
if pending <= 0:
if finished:
emitted_frames.pop(request_id, None)
return OmniPayloadStruct(
codes=CodesStruct(audio=torch.empty(0, dtype=torch.long)),
meta=MetaStruct(finished=torch.tensor(True, dtype=torch.bool)),
)
return None
actual_chunk = pending
desired_left_context = min(left_context_size_config, emitted)
# Window in AR-row space: span the de-delayed frames
# [emitted - L, target_emit + H) which require AR rows
# [emitted - L, target_emit + H + Q - 1).
window_row_start = emitted - desired_left_context
window_row_end_exclusive = target_emit + H + (_NUM_CODEBOOKS - 1)
if window_row_end_exclusive > n_rows:
# Defensive: pending >= 0 was checked above; this should be unreachable
# for non-final calls. On the final call we cap to n_rows.
if not finished:
return None
window_row_end_exclusive = n_rows
window_rows = transfer_manager.code_prompt_token_ids[request_id][window_row_start:window_row_end_exclusive]
if len(window_rows) < _NUM_CODEBOOKS:
if finished:
emitted_frames.pop(request_id, None)
return OmniPayloadStruct(
codes=CodesStruct(audio=torch.empty(0, dtype=torch.long)),
meta=MetaStruct(finished=torch.tensor(True, dtype=torch.bool)),
)
return None
codes_qt = torch.tensor(window_rows, dtype=torch.long).t().contiguous()
try:
de_delayed = _revert_delay_pattern(codes_qt)
except ValueError:
logger.warning(
"async_chunk: insufficient frames for delay pattern reversal "
"(T=%d < Q=%d, request=%s). Returning empty chunk.",
codes_qt.shape[1],
codes_qt.shape[0],
request_id,
)
emitted_frames.pop(request_id, None)
return OmniPayloadStruct(
codes=CodesStruct(audio=torch.empty(0, dtype=torch.long)),
meta=MetaStruct(finished=torch.tensor(True, dtype=torch.bool)),
)
# Replace BOC=1024/EOC=1025 (and any negative pads) with 0; matches the
# sync-path substitution. Clamp would turn 1025 into 1023 which is a
# VALID codec code and decodes to audible artifacts.
de_delayed = torch.where(
(de_delayed >= _NUM_REAL_CODES) | (de_delayed < 0),
torch.zeros_like(de_delayed),
de_delayed,
)
# On the FINAL chunk only: trim the trailing residual frame (the last
# de-delayed frame still carries EOC-substituted codes from ramp-down
# which decode to a brief noise artifact). Mirrors the sync-path trim.
if finished and window_row_end_exclusive == n_rows and de_delayed.shape[-1] >= 2:
de_delayed = de_delayed[:, :-1]
actual_chunk = max(actual_chunk - 1, 0)
codec_codes = de_delayed.reshape(-1)
left_context_emitted = desired_left_context
right_holdback_emitted = H
emitted_frames[request_id] = emitted + actual_chunk
if finished:
emitted_frames.pop(request_id, None)
meta = MetaStruct(
left_context_size=left_context_emitted,
right_holdback_size=right_holdback_emitted,
finished=torch.tensor(finished, dtype=torch.bool),
)
return OmniPayloadStruct(
codes=CodesStruct(audio=codec_codes),
meta=meta,
)
@@ -18,6 +18,11 @@ from typing import Any
from vllm.inputs import TextPrompt
from vllm.logger import init_logger
from vllm_omni.diffusion.models.hunyuan_image3.hunyuan_image3_transformer import (
Resolution,
ResolutionGroup,
get_cached_resolution_group,
)
from vllm_omni.diffusion.models.hunyuan_image3.prompt_utils import (
HUNYUAN_IMAGE3_SPECIAL_TOKEN_IDS,
)
@@ -25,82 +30,6 @@ from vllm_omni.inputs.data import OmniTokensPrompt
logger = init_logger(__name__)
# AR emits `<img_size_BASE><img_ratio_Y>` after `</recaption>` in IT2I/T2I
# (see `HunyuanImage3ForCausalMM.sample` and `_stage_transitions`). The
# ratio_index resolves to a (height, width) bucket via ResolutionGroup, which
# is the official upstream's mechanism for AR-driven output aspect; without
# this lookup the DiT pipeline falls back to the user-provided width/height
# (in the `/v1/images/edits` path that defaults to `pil_images[0].size`,
# i.e. the first reference image's bucket, usually square, see
# api_server.py:1808-1811).
_HUNYUAN_IMAGE3_EXTRA_RESOLUTIONS: tuple[str, ...] = (
"1024x768",
"1280x720",
"768x1024",
"720x1280",
)
class _Resolution:
def __init__(self, size: str | int | tuple[int, int], *args: int):
if isinstance(size, str):
if "x" in size:
h, w = size.split("x")
size = (int(h), int(w))
else:
size = int(size)
if args:
size = (int(size), args[0])
if isinstance(size, int):
size = (size, size)
self.height = int(size[0])
self.width = int(size[1])
self.ratio = self.height / self.width
def _build_resolutions_by_step(base_size: int, align: int = 1) -> list[_Resolution]:
step = base_size // 16
min_height = base_size // 2
min_width = base_size // 2
max_height = base_size * 2
max_width = base_size * 2
resolutions = [_Resolution(base_size, base_size)]
cur_height, cur_width = base_size, base_size
while True:
if cur_height >= max_height and cur_width <= min_width:
break
cur_height = min(cur_height + step, max_height)
cur_width = max(cur_width - step, min_width)
resolutions.append(_Resolution(cur_height // align * align, cur_width // align * align))
cur_height, cur_width = base_size, base_size
while True:
if cur_height <= min_height and cur_width >= max_width:
break
cur_height = max(cur_height - step, min_height)
cur_width = min(cur_width + step, max_width)
resolutions.append(_Resolution(cur_height // align * align, cur_width // align * align))
return sorted(resolutions, key=lambda x: x.ratio)
@lru_cache(maxsize=4)
def _build_ratio_size_table(base_size: int) -> list[tuple[int, int]]:
"""Return `[(height, width)]` indexed by ratio_index for HunyuanImage-3.
Mirrors `HunyuanImage3ImageProcessor.build_image_info`'s
`reso_group[ratio_index]` reverse lookup. Cached because the table
is constant per `base_size`.
"""
resolutions = _build_resolutions_by_step(base_size)
for extra_resolution in (_Resolution(s) for s in _HUNYUAN_IMAGE3_EXTRA_RESOLUTIONS):
if not any(r.ratio == extra_resolution.ratio for r in resolutions):
resolutions.append(extra_resolution)
return [(r.height, r.width) for r in resolutions]
def _truncate_at_cot_end(generated_text: str) -> str:
"""Truncate AR output at first `</recaption>` (or `</think>` fallback).
@@ -185,7 +114,8 @@ def ar2diffusion(
for i, ar_output in enumerate(ar_outputs):
output = ar_output.outputs[0]
generated_token_ids = output.cumulative_token_ids
generated_text = getattr(output, "text", "") or ""
# Prefer cumulative_text, fallback to text if aggregation dropped it
generated_text = getattr(output, "cumulative_text", None) or getattr(output, "text", "") or ""
# Get original prompt info
original_prompt = prompt[i] if i < len(prompt) else {}
@@ -216,16 +146,18 @@ def ar2diffusion(
ar_predicted = False
if ratio_idx is not None:
base_size = int(original_prompt.get("image_base_size", 1024))
size_table = _build_ratio_size_table(base_size)
if 0 <= ratio_idx < len(size_table):
height, width = size_table[ratio_idx]
reso_group: ResolutionGroup = get_cached_resolution_group(base_size=base_size)
try:
reso: Resolution = reso_group[ratio_idx]
height = reso.height
width = reso.width
ar_predicted = True
else:
except IndexError:
logger.warning(
"[ar2diffusion] Request %d: ratio_index=%d out of range [0,%d), keeping prompt size %dx%d",
i,
ratio_idx,
len(size_table),
len(reso_group),
height,
width,
)
@@ -205,18 +205,6 @@ def _resolve_image_patch_token_id(stage: Any) -> int:
return token_id
def _validate_stage_inputs(stage_list, engine_input_source):
if not engine_input_source:
raise ValueError("engine_input_source cannot be empty")
stage_id = engine_input_source[0]
if stage_id >= len(stage_list):
raise IndexError(f"Invalid stage_id: {stage_id}")
stage = stage_list[stage_id]
if stage.engine_outputs is None:
raise RuntimeError(f"Stage {stage_id} has no outputs yet")
return stage, stage.engine_outputs
def _ensure_list(x) -> list[int]:
"""Convert ConstantList / tensor-like to plain list."""
if hasattr(x, "_x"):
@@ -458,20 +446,10 @@ def thinker2imagegen(
return [{"prompt": "", "extra": extra}]
def thinker2talker(
stage_list: list[Any],
engine_input_source: list[int],
def _build_talker_inputs(
source_outputs: list[Any],
prompt: OmniTokensPrompt | TextPrompt | None = None,
requires_multimodal_data: bool = False,
) -> list[OmniTokensPrompt]:
"""Build talker stage inputs from thinker stage outputs.
Extracts the generated text from thinker output and constructs
a talker input prompt with the text and any speaker/instruction info
from the original request.
"""
_, source_outputs = _validate_stage_inputs(stage_list, engine_input_source)
if not isinstance(prompt, list):
prompt = [prompt]
@@ -492,8 +470,6 @@ def thinker2talker(
# the talker's spk_head wants a torch tensor.
spk_emb = additional_info.get("spk_emb", None)
if isinstance(spk_emb, list) and spk_emb and not hasattr(spk_emb[0], "device"):
import torch
spk_emb = torch.tensor(spk_emb, dtype=torch.float32).unsqueeze(0)
# Omni speech path mirrors upstream `omni_audio_generation`:
@@ -535,12 +511,22 @@ def thinker2talker(
return talker_inputs
def thinker2talker(
source_outputs: list[Any],
prompt: OmniTokensPrompt | TextPrompt | None = None,
_requires_multimodal_data: bool = False,
_streaming_context: Any | None = None,
) -> list[OmniTokensPrompt]:
"""Build talker stage inputs from thinker stage outputs."""
return _build_talker_inputs(source_outputs, prompt)
# ming_flash_omni is not in ``_OMNI_CONNECTOR_INIT_ARCHS`` or
# ``_FULL_PAYLOAD_INPUT_STAGES``, so the worker connector is not
# initialised for this arch and the consumer never waits on a connector
# payload. Data flows through ``additional_information`` written by
# ``thinker2talker_token_only`` (wired as ``sync_process_input_func``
# in the pipeline) or the legacy ``thinker2talker`` (wired as
# in the pipeline) or ``thinker2talker`` (wired as
# ``custom_process_input_func``).
@@ -549,55 +535,8 @@ def thinker2talker_token_only(
prompt: OmniTokensPrompt | TextPrompt | None = None,
_requires_multimodal_data: bool = False,
) -> list[OmniTokensPrompt]:
"""Sync-side builder for the non-async-chunk thinker→talker path.
Ports the legacy ``thinker2talker`` body to the new stage-input-processor signature
(``source_outputs`` instead of ``stage_list, engine_input_source``).
Body is otherwise identical: extracts the
generated text from each thinker output and packages it with the
request's voice/speaker additional_information for the talker.
"""
if not isinstance(prompt, list):
prompt = [prompt]
talker_inputs: list[OmniTokensPrompt] = []
for i, source_output in enumerate(source_outputs):
output = source_output.outputs[0]
generated_text = output.text if hasattr(output, "text") and output.text else ""
original_prompt = prompt[i] if i < len(prompt) else None
additional_info: dict[str, Any] = {}
if original_prompt is not None and hasattr(original_prompt, "additional_information"):
additional_info = original_prompt.additional_information or {}
spk_emb = additional_info.get("spk_emb", None)
if isinstance(spk_emb, list) and spk_emb and not hasattr(spk_emb[0], "device"):
import torch
spk_emb = torch.tensor(spk_emb, dtype=torch.float32).unsqueeze(0)
talker_info = {
"ming_task": "omni",
"text": generated_text,
"spk_emb": spk_emb,
"voice_name": additional_info.get("voice_name", "DB30"),
"prompt_text": additional_info.get("prompt_text", None),
"prompt_wav_lat": additional_info.get("prompt_wav_lat", None),
"prompt_wav_emb": additional_info.get("prompt_wav_emb", None),
"max_text_length": additional_info.get("max_text_length", 50),
}
talker_inputs.append(
OmniTokensPrompt(
prompt_token_ids=[0],
additional_information=talker_info,
multi_modal_data=None,
mm_processor_kwargs=None,
)
)
return talker_inputs
"""Sync-side builder for the non-async-chunk thinker→talker path."""
return _build_talker_inputs(source_outputs, prompt)
thinker2talker_token_only._is_sync_input = True
@@ -0,0 +1,296 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
from typing import Any
import torch
from vllm.inputs import TextPrompt
from vllm.logger import init_logger
from vllm_omni.data_entry_keys import CodesStruct, MetaStruct, OmniPayloadStruct
from vllm_omni.inputs.data import OmniTokensPrompt
from vllm_omni.model_executor.models.ming_tts.config_ming_tts import (
KEY_CHUNK_ID,
KEY_REQUEST_ID,
LATENT_CHUNK_SIZE,
LATENT_DIM,
LATENT_LEFT_CONTEXT,
PATCH_SIZE,
)
from vllm_omni.model_executor.models.ming_tts.patch_emission import (
MING_STOP_REASON_CODES,
MING_STOP_REASON_KEY,
)
logger = init_logger(__name__)
MING_EMIT_PATCH_COUNT_KEY = "ming_emit_patch_count"
MING_LATENT_SHAPE_KEY = "ming_latent_shape"
MING_ESTIMATED_BYTES_KEY = "ming_estimated_bytes"
MING_FINAL_FLUSH_KEY = "ming_final_flush"
MING_FINAL_DECODE_STEP_KEY = "ming_final_decode_step"
MING_STOP_REASON_BY_CODE = {code: reason for reason, code in MING_STOP_REASON_CODES.items()}
def _extract_last_patch(pooling_output: dict[str, Any] | None) -> torch.Tensor | None:
if not isinstance(pooling_output, dict):
return None
has_patch = pooling_output.get("ming_has_patch")
patch = pooling_output.get("ming_latent_patch")
if not isinstance(patch, torch.Tensor) or patch.numel() == 0:
return None
if isinstance(has_patch, torch.Tensor) and has_patch.numel() > 0:
active = (has_patch.reshape(-1) > 0).nonzero(as_tuple=True)[0]
if active.numel() == 0:
return None
patch = patch[int(active[-1].item())]
elif patch.ndim == 3:
patch = patch[-1]
if patch.ndim != 2:
raise ValueError(f"Invalid Ming latent patch shape: {tuple(patch.shape)}")
return patch.to(torch.float32).cpu()
def _extract_all_patches(pooling_output: dict[str, Any] | None) -> torch.Tensor | None:
if not isinstance(pooling_output, dict):
return None
has_patch = pooling_output.get("ming_has_patch")
patch = pooling_output.get("ming_latent_patch")
if not isinstance(patch, torch.Tensor) or patch.numel() == 0:
return None
if patch.ndim == 2:
patch = patch.unsqueeze(0)
if patch.ndim != 3:
raise ValueError(f"Invalid Ming latent patch tensor shape: {tuple(patch.shape)}")
if isinstance(has_patch, torch.Tensor) and has_patch.numel() > 0:
active = (has_patch.reshape(-1) > 0).nonzero(as_tuple=True)[0]
if active.numel() == 0:
return None
patch = patch.index_select(0, active.to(device=patch.device))
if patch.numel() == 0:
return None
return patch.to(torch.float32).cpu()
def _extract_last_value(pooling_output: dict[str, Any] | None, key: str) -> Any:
if not isinstance(pooling_output, dict):
return None
value = pooling_output.get(key)
if value is None:
return None
has_patch = pooling_output.get("ming_has_patch")
selected_index = -1
if isinstance(has_patch, torch.Tensor) and has_patch.numel() > 0:
active = (has_patch.reshape(-1) > 0).nonzero(as_tuple=True)[0]
if active.numel() == 0:
return None
selected_index = int(active[-1].item())
if isinstance(value, torch.Tensor):
flat = value.reshape(-1)
if flat.numel() == 0:
return None
return flat[min(selected_index, flat.numel() - 1)].item()
if isinstance(value, (list, tuple)):
if not value:
return None
if selected_index < 0:
return value[-1]
return value[min(selected_index, len(value) - 1)]
return value
def _decode_stop_reason(value: Any) -> str | None:
if value is None:
return None
if isinstance(value, str):
return value
return MING_STOP_REASON_BY_CODE.get(int(value))
def _get_async_chunk_config(transfer_manager: Any) -> tuple[int, int]:
connector = getattr(transfer_manager, "connector", None)
raw_cfg = getattr(connector, "config", {}) or {}
cfg = raw_cfg.get("extra", raw_cfg) if isinstance(raw_cfg, dict) else {}
if "latent_chunk_size" not in cfg:
logger.warning(
"Ming async chunk config missing latent_chunk_size, using fallback value %s",
LATENT_CHUNK_SIZE,
)
if "latent_left_context" not in cfg:
logger.warning(
"Ming async chunk config missing latent_left_context, using fallback value %s",
LATENT_LEFT_CONTEXT,
)
chunk_size = int(cfg.get("latent_chunk_size", LATENT_CHUNK_SIZE))
left_context = int(cfg.get("latent_left_context", LATENT_LEFT_CONTEXT))
if chunk_size <= 0:
raise ValueError(f"Invalid Ming latent_chunk_size={chunk_size}")
# Stage-2 VAE caches past_key_values and stream_state by request_id.
# Replaying left-context latents would double-feed cached decoder state.
if left_context != 0:
raise ValueError(
"Ming async chunk transport does not support latent_left_context replay. "
"Ming boundary continuity is handled by per-request decoder state cache, not "
f"latent replay. Got latent_left_context={left_context}."
)
return chunk_size, left_context
def _build_chunk_observability(
latent_patches: torch.Tensor | None,
*,
final_flush: bool,
) -> dict[str, Any]:
if latent_patches is None:
emit_patch_count = 0
latent_shape = None
estimated_bytes = 0
else:
emit_patch_count = int(latent_patches.shape[0])
latent_shape = tuple(latent_patches.shape)
estimated_bytes = int(latent_patches.numel() * latent_patches.element_size())
return {
MING_EMIT_PATCH_COUNT_KEY: emit_patch_count,
MING_LATENT_SHAPE_KEY: latent_shape,
MING_ESTIMATED_BYTES_KEY: estimated_bytes,
MING_FINAL_FLUSH_KEY: bool(final_flush),
}
def llm2audio_vae_async_chunk(
transfer_manager: Any,
pooling_output: dict[str, Any] | None,
request: Any,
is_finished: bool = False,
) -> OmniPayloadStruct | None:
request_id = request.external_req_id
chunk_id = int(transfer_manager.put_req_chunk[request_id])
finished = bool(is_finished or request.is_finished())
final_decode_step = _extract_last_value(pooling_output, "ming_decode_step")
stop_reason = _decode_stop_reason(_extract_last_value(pooling_output, MING_STOP_REASON_KEY))
request_payload = transfer_manager.request_payload
request_state = request_payload.get(request_id)
if not isinstance(request_state, dict) or "_ming_async_state" not in request_state:
request_state = {
"_ming_async_state": {
"seen_patch_len": 0,
"terminal_sent": False,
}
}
request_payload[request_id] = request_state
state = request_state["_ming_async_state"]
if bool(state.get("terminal_sent", False)):
return None
patch = _extract_last_patch(pooling_output)
if patch is not None:
transfer_manager.code_prompt_token_ids[request_id].append(patch)
chunk_size, _ = _get_async_chunk_config(transfer_manager)
patches = transfer_manager.code_prompt_token_ids[request_id]
seen_patch_len = int(state.get("seen_patch_len", 0))
new_patches = patches[seen_patch_len:] if seen_patch_len < len(patches) else []
length = len(new_patches)
if length <= 0:
if finished and not bool(state.get("terminal_sent", False)):
observability = _build_chunk_observability(None, final_flush=True)
kv_meta = {
KEY_CHUNK_ID: chunk_id,
KEY_REQUEST_ID: request_id,
**observability,
}
if final_decode_step is not None:
kv_meta[MING_FINAL_DECODE_STEP_KEY] = int(final_decode_step)
if stop_reason is not None:
kv_meta[MING_STOP_REASON_KEY] = stop_reason
state["terminal_sent"] = True
return OmniPayloadStruct(
codes=CodesStruct(audio=torch.empty(0, dtype=torch.long)),
meta=MetaStruct(
finished=torch.tensor(True, dtype=torch.bool),
stream_finished=torch.tensor(True, dtype=torch.bool),
),
kv_metadata=kv_meta,
)
return None
chunk_length = length % chunk_size
if chunk_length != 0 and not finished:
return None
emit_count = chunk_length if chunk_length != 0 else chunk_size
emit_patches = list(new_patches[:emit_count])
state["seen_patch_len"] = seen_patch_len + len(emit_patches)
latent_patches = torch.stack(emit_patches, dim=0)
observability = _build_chunk_observability(latent_patches, final_flush=finished)
kv_meta = {
KEY_CHUNK_ID: chunk_id,
KEY_REQUEST_ID: request_id,
**observability,
}
if final_decode_step is not None:
kv_meta[MING_FINAL_DECODE_STEP_KEY] = int(final_decode_step)
if stop_reason is not None:
kv_meta[MING_STOP_REASON_KEY] = stop_reason
if finished:
state["terminal_sent"] = True
return OmniPayloadStruct(
codes=CodesStruct(audio=torch.tensor([0], dtype=torch.long)),
meta=MetaStruct(
finished=torch.tensor(finished, dtype=torch.bool),
stream_finished=torch.tensor(finished, dtype=torch.bool),
),
latent=latent_patches,
kv_metadata=kv_meta,
)
def llm2audio_vae(
source_outputs: list[Any],
prompt: OmniTokensPrompt | TextPrompt | None = None,
requires_multimodal_data: bool = False,
streaming_context: Any = None,
) -> list[OmniTokensPrompt]:
del prompt, requires_multimodal_data, streaming_context
if not source_outputs:
raise ValueError("source_outputs cannot be empty")
outputs = []
for stage_output in source_outputs:
finished = bool(getattr(stage_output, "finished", True))
if not finished:
continue
output = stage_output.outputs[0]
patches = _extract_all_patches(output.multimodal_output)
additional_information = {
"ming_latent_patches": patches
if patches is not None
else torch.zeros((0, PATCH_SIZE, LATENT_DIM), dtype=torch.float32),
KEY_REQUEST_ID: getattr(stage_output, "request_id", None),
"finished": torch.tensor(finished, dtype=torch.bool),
}
final_decode_step = _extract_last_value(output.multimodal_output, "ming_decode_step")
stop_reason = _decode_stop_reason(_extract_last_value(output.multimodal_output, MING_STOP_REASON_KEY))
if final_decode_step is not None:
additional_information[MING_FINAL_DECODE_STEP_KEY] = int(final_decode_step)
if stop_reason is not None:
additional_information[MING_STOP_REASON_KEY] = stop_reason
outputs.append(
OmniTokensPrompt(
prompt_token_ids=[0],
multi_modal_data=None,
mm_processor_kwargs=None,
additional_information=additional_information,
)
)
return outputs