[Maintenance] Refresh MOSS-TTS optimization on main

Signed-off-by: Sy03 <1370724210@qq.com>
This commit is contained in:
Sy03 committed 2026-09-09 12:46:57 +08:00
commit 28dd49a541
334 files changed
+24909 -6187

No files matched your search

@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Audex checkpoint layout preparation.
The nvidia/Nemotron-Labs-Audex-2B repo deduplicates weights: the
@@ -57,12 +57,12 @@ def _download_audiogen_index(model: str) -> str:
metadata round trip per stage-engine boot; a cache miss falls back to
the network.
"""
from huggingface_hub import hf_hub_download
from vllm_omni.transformers_utils.repo_utils import hf_api
try:
return hf_hub_download(model, _AUDIOGEN_INDEX_FILE, local_files_only=True)
return hf_api().hf_hub_download(model, _AUDIOGEN_INDEX_FILE, local_files_only=True)
except Exception:
return hf_hub_download(model, _AUDIOGEN_INDEX_FILE)
return hf_api().hf_hub_download(model, _AUDIOGEN_INDEX_FILE)
def _dedup_shard_patterns(model: str) -> list[str]:
@@ -111,13 +111,13 @@ def ensure_audex_snapshot(model: str, profile: str = "tts") -> str:
if profile in ("tts", "tta"):
patterns += _dedup_shard_patterns(model)
from huggingface_hub import snapshot_download
from vllm_omni.transformers_utils.repo_utils import hf_api
try:
return snapshot_download(model, allow_patterns=patterns)
return hf_api().snapshot_download(model, allow_patterns=patterns)
except Exception as download_exc:
try:
return snapshot_download(model, allow_patterns=patterns, local_files_only=True)
return hf_api().snapshot_download(model, allow_patterns=patterns, local_files_only=True)
except Exception:
raise RuntimeError(
f"Could not resolve the Audex repo {model!r} (profile {profile!r}): the download "
@@ -135,13 +135,13 @@ def ensure_xcodec1_snapshot(model: str | None) -> str:
if os.path.isdir(model):
return model
from huggingface_hub import snapshot_download
from vllm_omni.transformers_utils.repo_utils import hf_api
try:
return snapshot_download(model)
return hf_api().snapshot_download(model)
except Exception as download_exc:
try:
return snapshot_download(model, local_files_only=True)
return hf_api().snapshot_download(model, local_files_only=True)
except Exception:
raise RuntimeError(
f"Could not resolve the XCodec1 checkpoint {model!r}: the download failed and "
@@ -0,0 +1,3 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Audio8 TTS Preview (DualAR, 44.1 kHz codec) model implementation."""
@@ -0,0 +1,284 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Audio8 TTS Preview -- codec decoder (Stage 1).
Consumes frames of ``num_codebooks`` codec codes and decodes them to a 44.1 kHz
waveform. Streaming contract is delta: with ``async_chunk`` on, each chunk is
``[left_context | new_frames]``; the whole window is decoded so the causal
codec keeps continuous context, then only the new tail is returned.
"""
from __future__ import annotations
from collections.abc import Iterable
from typing import Any
import torch
import torch.nn as nn
from vllm.config import VllmConfig
from vllm.forward_context import get_forward_context, is_forward_context_available
from vllm.logger import init_logger
from vllm_omni.model_executor.models.audio8_tts.codec_utils import load_arktts_codec
from vllm_omni.model_executor.models.audio8_tts.configuration_audio8_tts import (
ARKTTS_CODEC_FRAME_SIZE,
ARKTTS_CODEC_SAMPLE_RATE,
)
from vllm_omni.model_executor.models.output_templates import OmniOutput
logger = init_logger(__name__)
_DTYPES = {
"fp16": torch.float16,
"float16": torch.float16,
"half": torch.float16,
"bf16": torch.bfloat16,
"bfloat16": torch.bfloat16,
"fp32": torch.float32,
"float32": torch.float32,
"": torch.float32,
}
def _connector_extra_config(vllm_config: VllmConfig) -> dict[str, Any]:
model_config = getattr(vllm_config, "model_config", None)
connector_cfg = getattr(model_config, "stage_connector_config", None)
if isinstance(connector_cfg, dict):
return connector_cfg.get("extra", connector_cfg)
extra = getattr(connector_cfg, "extra", None)
return extra if isinstance(extra, dict) else {}
def _resolve_dtype(extra_cfg: dict[str, Any]) -> torch.dtype:
raw = str(extra_cfg.get("audio8_tts_codec_dtype", "float32")).strip().lower()
if raw not in _DTYPES:
raise ValueError(f"Invalid Audio8 TTS codec dtype: {raw!r}")
return _DTYPES[raw]
class Audio8TTSCodecDecoder(nn.Module):
"""Stage 1: codec codes -> waveform (runs under the generation runner)."""
input_modalities = "audio"
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
super().__init__()
del prefix
self.vllm_config = vllm_config
self.model_path = vllm_config.model_config.model
config = vllm_config.model_config.hf_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._num_codebooks = int(getattr(config, "num_codebooks", 10))
self._sample_rate = int(getattr(config, "codec_sample_rate", ARKTTS_CODEC_SAMPLE_RATE))
self._frame_size = int(getattr(config, "codec_frame_size", ARKTTS_CODEC_FRAME_SIZE))
self._codec_kwargs = {
"post_n_layer": int(getattr(config, "codec_post_n_layer", 8)),
"post_n_head": int(getattr(config, "codec_post_n_head", 16)),
"post_n_local_heads": int(getattr(config, "codec_post_n_local_heads", 8)),
"post_intermediate_size": int(getattr(config, "codec_post_intermediate_size", 1216)),
}
# float32 by default: the codec's Snake activations and weight-normed
# convs lose audible headroom in bf16.
self._codec_dtype = _resolve_dtype(_connector_extra_config(vllm_config))
self._codec: nn.Module | None = None
self._codec_device: torch.device | None = None
self._logged_stats = False
# -------------------- codec --------------------
def _ensure_codec_loaded(self) -> None:
if self._codec is not None:
return
device = self.vllm_config.device_config.device
self._codec = load_arktts_codec(
self.model_path,
device=device,
dtype=self._codec_dtype,
role="decode",
**self._codec_kwargs,
)
self._codec_device = torch.device(device)
# -------------------- vLLM 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: torch.Tensor | OmniOutput, sampling_metadata: Any = None) -> None:
return None
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
"""No-op: the codec comes from ``codec.pth``, not the main checkpoint."""
del weights
return set()
# -------------------- request splitting --------------------
def _split_request_ids(
self,
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] + count)
total = ids.numel()
return [ids[boundaries[i] : min(boundaries[i + 1], total)] for i in range(len(seq_token_counts))]
if is_forward_context_available():
slices = get_forward_context().ubatch_slices
if slices is not None and len(slices) > 1 and not any(hasattr(s, "token_slice") for s in slices):
boundaries = [0]
for size in slices:
boundaries.append(boundaries[-1] + size)
return [ids[boundaries[i] : boundaries[i + 1]] for i in range(len(boundaries) - 1)]
return [ids]
def _codes_from_runtime_info(
self,
info: dict[str, Any] | None,
device: torch.device,
) -> torch.Tensor | None:
"""Prefer the tensor payload the connector carried over input_ids."""
if not isinstance(info, dict):
return None
codes = info.get("codes", {}).get("audio")
if not isinstance(codes, torch.Tensor) or codes.numel() == 0:
return None
codes = codes.to(device=device, dtype=torch.long, non_blocking=True).contiguous()
if codes.ndim != 2 or int(codes.shape[0]) != self._num_codebooks:
logger.warning(
"Audio8 TTS codec decoder expected codes of shape [%d, frames], got %s",
self._num_codebooks,
tuple(codes.shape),
)
return None
return codes
# -------------------- decode --------------------
@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,
) -> OmniOutput:
"""Decode one chunk per request.
``input_ids`` is codebook-major flat codes
(``[cb0_f0 ... cb0_fN, cb1_f0 ...]``); tensor codes on the connector
win over ``input_ids``. Every return path must set ``model_outputs`` or
the serving layer silently drops a chunk of audio.
"""
del positions, intermediate_tensors, inputs_embeds
sr_tensor = torch.tensor(self._sample_rate, dtype=torch.int32)
empty = torch.zeros((0,), dtype=torch.float32)
self._ensure_codec_loaded()
codec = self._codec
assert codec is not None
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)
per_request_ids = self._split_request_ids(ids, kwargs.get("seq_token_counts"))
num_req = len(per_request_ids)
context_frames = [0] * num_req
if runtime_additional_information is not None:
for index, info in enumerate(runtime_additional_information[:num_req]):
meta = info.get("meta", {}) if isinstance(info, dict) else {}
context_frames[index] = int(meta.get("left_context_size", 0) or 0)
audios: list[torch.Tensor] = [empty] * num_req
for index, request_ids in enumerate(per_request_ids):
codes_qf = (
self._codes_from_runtime_info(runtime_additional_information[index], ids.device)
if runtime_additional_information is not None and index < len(runtime_additional_information)
else None
)
if codes_qf is None:
if request_ids.numel() < self._num_codebooks:
continue
if int(request_ids.numel()) % self._num_codebooks != 0:
logger.warning(
"Audio8 TTS codec decoder got %d ids, not divisible by num_codebooks=%d; skipping request",
int(request_ids.numel()),
self._num_codebooks,
)
continue
codes_qf = request_ids.reshape(self._num_codebooks, -1)
total_frames = int(codes_qf.shape[1])
if total_frames <= 0:
continue
new_frames = total_frames - context_frames[index]
if new_frames <= 0:
logger.warning(
"Audio8 TTS codec decoder chunk has no new frames (total=%d, context=%d)",
total_frames,
context_frames[index],
)
continue
if not self._logged_stats:
self._logged_stats = True
logger.info(
"Audio8 TTS codec decoder: frames=%d codebooks=%d dtype=%s sr=%d",
total_frames,
self._num_codebooks,
self._codec_dtype,
self._sample_rate,
)
with torch.amp.autocast("cuda", enabled=False):
# Move codes to the codec's device explicitly: a mismatch here
# silently falls back to CPU or raises deep inside the decoder.
waveform = codec.decode(codes_qf.unsqueeze(0).to(device=self._codec_device))
waveform = waveform.reshape(-1).to(dtype=torch.float32)
# Trim the left-context prefix proportionally: the codec's padding /
# rounding means the decoded length is not exactly
# frames * frame_size.
if context_frames[index] > 0:
cut = int(round(context_frames[index] / total_frames * int(waveform.shape[0])))
cut = max(0, min(cut, int(waveform.shape[0])))
waveform = waveform[cut:]
if waveform.numel() > 0:
audios[index] = waveform.contiguous()
return OmniOutput(
text_hidden_states=None,
multimodal_outputs={"model_outputs": audios, "sr": [sr_tensor] * num_req},
)
def make_omni_output(self, model_outputs: torch.Tensor | OmniOutput, **kwargs: Any) -> OmniOutput:
del kwargs
if isinstance(model_outputs, OmniOutput):
return model_outputs
if not (isinstance(model_outputs, tuple) and len(model_outputs) == 2):
raise TypeError(f"Audio8TTSCodecDecoder expected (audio_tensor, sr), got {type(model_outputs)}")
audio_tensor, sample_rate = model_outputs
return OmniOutput(
text_hidden_states=None,
multimodal_outputs={"model_outputs": audio_tensor, "sr": sample_rate},
)
__all__ = ["Audio8TTSCodecDecoder"]
@@ -0,0 +1,346 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Audio8 TTS Fast AR: the residual-codebook predictor.
Runs once per Slow AR step over ``num_codebooks + 1`` positions: position 0 is
the projected Slow AR hidden state (primes the KV cache, logits discarded),
position 1 is the sampled semantic code (not predicted, only fed in), positions
2.. are the previously sampled residual codes; only codes 1..num_codebooks-1
are sampled here.
Not paged: at most 10 tokens per call, SDPA over a per-call pre-allocated KV
cache. Matches the reference ``ArkttsModel._generate_codebooks``.
"""
from __future__ import annotations
from collections.abc import Iterable
import torch
import torch.nn as nn
import torch.nn.functional as F
from vllm.config import VllmConfig
from vllm.config.vllm import set_current_vllm_config
from vllm.logger import init_logger
from vllm.model_executor.layers.layernorm import RMSNorm
from vllm.model_executor.layers.linear import (
MergedColumnParallelLinear,
QKVParallelLinear,
RowParallelLinear,
)
from vllm.model_executor.layers.rotary_embedding import get_rope
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
from .configuration_audio8_tts import Audio8TTSFastARConfig, Audio8TTSSlowARConfig
from .sampling import sample_scores
logger = init_logger(__name__)
class _FastARAttention(nn.Module):
"""GQA self-attention over the short codebook sequence.
``forward_one`` decodes a single position against a caller-owned KV cache;
there is no batched-prefill path because the codebook loop is inherently
sequential.
"""
def __init__(self, config: Audio8TTSFastARConfig, *, prefix: str = "") -> None:
super().__init__()
self.hidden_size = config.hidden_size
self.num_heads = config.num_attention_heads
self.num_kv_heads = config.num_key_value_heads
self.head_dim = config.head_dim
self.q_size = self.num_heads * self.head_dim
self.kv_size = self.num_kv_heads * self.head_dim
self.scaling = self.head_dim**-0.5
self._use_gqa = self.num_kv_heads != self.num_heads
self.qkv_proj = QKVParallelLinear(
hidden_size=self.hidden_size,
head_size=self.head_dim,
total_num_heads=self.num_heads,
total_num_kv_heads=self.num_kv_heads,
bias=config.attention_qkv_bias,
prefix=f"{prefix}.qkv_proj",
disable_tp=True,
)
self.o_proj = RowParallelLinear(
input_size=self.num_heads * self.head_dim,
output_size=self.hidden_size,
bias=False,
prefix=f"{prefix}.o_proj",
disable_tp=True,
)
self.rotary_emb = get_rope(
self.head_dim,
max_position=config.max_position_embeddings,
# Audio8 TTS uses interleaved (GPT-J) RoPE, not NeoX.
is_neox_style=False,
rope_parameters={"rope_theta": config.rope_theta, "rope_type": "default"},
)
if config.attention_qk_norm:
self.q_norm = RMSNorm(self.head_dim, eps=config.rms_norm_eps)
self.k_norm = RMSNorm(self.head_dim, eps=config.rms_norm_eps)
else:
self.q_norm = None
self.k_norm = None
def forward_one(
self,
hidden_states: torch.Tensor,
position_ids: torch.Tensor,
k_cache: torch.Tensor,
v_cache: torch.Tensor,
cache_pos: int,
) -> torch.Tensor:
bsz = int(hidden_states.shape[0])
qkv, _ = self.qkv_proj(hidden_states.reshape(bsz, -1))
q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
if self.q_norm is not None:
q = self.q_norm(q.view(-1, self.num_heads, self.head_dim)).view(q.shape)
k = self.k_norm(k.view(-1, self.num_kv_heads, self.head_dim)).view(k.shape)
q, k = self.rotary_emb(position_ids.reshape(-1), q, k)
q = q.view(bsz, self.num_heads, self.head_dim).unsqueeze(2)
k_cache[:bsz, :, cache_pos, :] = k.view(bsz, self.num_kv_heads, self.head_dim)
v_cache[:bsz, :, cache_pos, :] = v.view(bsz, self.num_kv_heads, self.head_dim)
attn_out = F.scaled_dot_product_attention(
q,
k_cache[:bsz, :, : cache_pos + 1, :],
v_cache[:bsz, :, : cache_pos + 1, :],
scale=self.scaling,
is_causal=False,
enable_gqa=self._use_gqa,
)
attn_out = attn_out.transpose(1, 2).reshape(bsz, -1)
output, _ = self.o_proj(attn_out)
return output
class _FastARMLP(nn.Module):
"""SiLU-gated MLP (``w1``/``w3`` gate-up, ``w2`` down)."""
def __init__(self, config: Audio8TTSFastARConfig, *, prefix: str = "") -> None:
super().__init__()
self.gate_up_proj = MergedColumnParallelLinear(
input_size=config.hidden_size,
output_sizes=[config.intermediate_size] * 2,
bias=False,
prefix=f"{prefix}.gate_up_proj",
disable_tp=True,
)
self.down_proj = RowParallelLinear(
input_size=config.intermediate_size,
output_size=config.hidden_size,
bias=False,
prefix=f"{prefix}.down_proj",
disable_tp=True,
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
gate_up, _ = self.gate_up_proj(x)
gate, up = gate_up.chunk(2, dim=-1)
x, _ = self.down_proj(F.silu(gate) * up)
return x
class _FastARDecoderLayer(nn.Module):
def __init__(self, config: Audio8TTSFastARConfig, *, prefix: str = "") -> None:
super().__init__()
self.self_attn = _FastARAttention(config, prefix=f"{prefix}.self_attn")
self.mlp = _FastARMLP(config, prefix=f"{prefix}.mlp")
self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.post_attention_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
def forward_one(
self,
hidden_states: torch.Tensor,
position_ids: torch.Tensor,
k_cache: torch.Tensor,
v_cache: torch.Tensor,
cache_pos: int,
) -> torch.Tensor:
hidden_states = hidden_states + self.self_attn.forward_one(
self.input_layernorm(hidden_states), position_ids, k_cache, v_cache, cache_pos
)
return hidden_states + self.mlp(self.post_attention_layernorm(hidden_states))
class Audio8TTSFastAR(nn.Module):
"""Residual-codebook predictor for Audio8 TTS.
``forward`` returns all ``num_codebooks`` codes for one frame, with code 0
copied from the already-sampled semantic token.
"""
def __init__(
self,
*,
vllm_config: VllmConfig,
config: Audio8TTSFastARConfig,
slow_ar_config: Audio8TTSSlowARConfig,
prefix: str = "fast_ar",
) -> None:
super().__init__()
self._vllm_config = vllm_config
self.config = config
self.slow_ar_config = slow_ar_config
self.layers = nn.ModuleList(
[_FastARDecoderLayer(config, prefix=f"{prefix}.layers.{i}") for i in range(config.num_hidden_layers)]
)
self.fast_embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
self.fast_output = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
self.fast_norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
if slow_ar_config.hidden_size != config.hidden_size:
self.fast_project_in = nn.Linear(slow_ar_config.hidden_size, config.hidden_size, bias=True)
else:
# 0.6b: dim == fast_dim == 896, and the checkpoint has no
# fast_project_in tensor.
self.fast_project_in = nn.Identity()
self._num_codebooks = int(config.num_codebooks)
self._fast_dim = int(config.hidden_size)
self._k_cache: torch.Tensor | None = None
self._v_cache: torch.Tensor | None = None
self._pos_ids: torch.Tensor | None = None
def _ensure_buffers(self, bsz: int, device: torch.device, dtype: torch.dtype) -> None:
max_seq = self._num_codebooks + 1
if (
self._k_cache is not None
and self._pos_ids is not None
and self._k_cache.shape[1] >= bsz
and self._k_cache.device == device
and self._k_cache.dtype == dtype
and self._pos_ids.shape[0] >= bsz
):
return
self._k_cache = torch.empty(
self.config.num_hidden_layers,
bsz,
self.config.num_key_value_heads,
max_seq,
self.config.head_dim,
dtype=dtype,
device=device,
)
self._v_cache = torch.empty_like(self._k_cache)
self._pos_ids = torch.arange(max_seq, dtype=torch.long, device=device).unsqueeze(0).expand(bsz, -1).contiguous()
def _forward_one(self, embed: torch.Tensor, position_ids: torch.Tensor, cache_pos: int) -> torch.Tensor:
assert self._k_cache is not None and self._v_cache is not None
hidden = embed
for layer_idx, layer in enumerate(self.layers):
hidden = layer.forward_one(
hidden,
position_ids,
self._k_cache[layer_idx],
self._v_cache[layer_idx],
cache_pos,
)
return hidden
@torch.inference_mode()
def forward(
self,
slow_ar_hidden: torch.Tensor,
semantic_token_id: torch.Tensor,
*,
do_sample: bool = True,
temperature: float = 0.7,
top_k: int = 50,
top_p: float = 0.9,
generator: torch.Generator | None = None,
) -> torch.Tensor:
"""Predict one frame of codec codes.
``slow_ar_hidden`` must already be post-final-norm when
``norm_fastlayer_input`` is set (it is for the released checkpoint) --
vLLM's Qwen2Model returns exactly that. Returns ``[B, num_codebooks]``
int64 codes; code 0 is the semantic code, codes 1.. come from this module.
"""
bsz = int(slow_ar_hidden.shape[0])
num_cb = self._num_codebooks
device = slow_ar_hidden.device
dtype = slow_ar_hidden.dtype
semantic_begin = int(self.slow_ar_config.semantic_begin_id)
codebook_size = int(self.slow_ar_config.codebook_size)
# Non-semantic tokens (EOS) clamp to code 0; those frames are dropped
# downstream because the request finishes on that token.
semantic_code = (semantic_token_id.reshape(bsz) - semantic_begin).clamp(min=0, max=codebook_size - 1)
codes = torch.empty(bsz, num_cb, dtype=torch.long, device=device)
codes[:, 0] = semantic_code
self._ensure_buffers(bsz, device, dtype)
pos_ids = self._pos_ids
assert pos_ids is not None
# Position 0 primes the cache; its logits are unused.
projected = self.fast_project_in(slow_ar_hidden.reshape(bsz, -1))
self._forward_one(projected, pos_ids[:bsz, 0], 0)
embed = self.fast_embeddings(semantic_code)
for step in range(1, num_cb):
hidden = self._forward_one(embed, pos_ids[:bsz, step], step)
logits = self.fast_output(self.fast_norm(hidden)).float()
next_ids = sample_scores(
logits,
temperature=temperature,
top_k=top_k,
top_p=top_p,
do_sample=do_sample,
generator=generator,
)
codes[:, step] = next_ids
if step < num_cb - 1:
embed = self.fast_embeddings(next_ids)
return codes
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
"""Load already-remapped Fast AR weights (see the Slow AR remapper)."""
with set_current_vllm_config(self._vllm_config):
params_dict = dict(self.named_parameters(remove_duplicate=False))
loaded: set[str] = set()
stacked_params_mapping = [
("qkv_proj", "q_proj", "q"),
("qkv_proj", "k_proj", "k"),
("qkv_proj", "v_proj", "v"),
("gate_up_proj", "gate_proj", 0),
("gate_up_proj", "up_proj", 1),
]
for name, loaded_weight in weights:
handled = False
for param_name, weight_name, shard_id in stacked_params_mapping:
if weight_name not in name:
continue
mapped = name.replace(weight_name, param_name)
if mapped not in params_dict:
continue
param = params_dict[mapped]
weight_loader = getattr(param, "weight_loader", default_weight_loader)
if weight_loader == default_weight_loader:
weight_loader(param, loaded_weight)
else:
weight_loader(param, loaded_weight, shard_id)
loaded.add(mapped)
handled = True
break
if handled or name not in params_dict:
continue
param = params_dict[name]
weight_loader = getattr(param, "weight_loader", default_weight_loader)
weight_loader(param, loaded_weight)
loaded.add(name)
return loaded
__all__ = ["Audio8TTSFastAR"]
@@ -0,0 +1,755 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Audio8 TTS Preview -- Slow AR model (Stage 0).
Text (+ optional reference voice) -> one semantic token per codec frame; the
frame's remaining 9 codebooks are produced by the nested Fast AR.
Backbone is vLLM's ``Qwen2Model`` (qkv bias, no q/k norm), with three
adjustments: interleaved (GPT-J) RoPE, multi-codebook input embedding at
semantic positions (summed, unlike Fish Speech's ``1/sqrt(Q+1)`` rescale), and
logits masked to the semantic range + ``<|im_end|>`` then Repetition-Aware
sampled.
Streaming contract is delta: each decode step appends one frame of
``num_codebooks`` codes to ``codes.audio``.
"""
from __future__ import annotations
import copy
from collections.abc import Iterable
from typing import Any
import numpy as np
import torch
import torch.nn as nn
from transformers import AutoTokenizer
from vllm.config import VllmConfig
from vllm.distributed import get_pp_group
from vllm.logger import init_logger
from vllm.model_executor.layers.logits_processor import LogitsProcessor
from vllm.model_executor.layers.vocab_parallel_embedding import ParallelLMHead
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
from vllm.model_executor.models.qwen2 import Qwen2Model
from vllm.model_executor.models.utils import PPMissingLayer, maybe_prefix
from vllm.sequence import IntermediateTensors
from vllm.v1.outputs import SamplerOutput
from vllm_omni.model_executor.models.output_templates import OmniOutput
from vllm_omni.utils.speaker_cache import get_speaker_cache
from .audio8_tts_fast_ar import Audio8TTSFastAR
from .codec_utils import encode_reference_audio_codes
from .configuration_audio8_tts import (
Audio8TTSConfig,
Audio8TTSFastARConfig,
Audio8TTSSlowARConfig,
)
from .prompt_utils import build_voice_clone_prompt_ids
from .sampling import SAMPLING_EPS, ras_sample_batch
logger = init_logger(__name__)
#: Defaults from ``generation_config.json`` of the released checkpoint.
DEFAULT_TEMPERATURE = 0.7
DEFAULT_TOP_K = 50
DEFAULT_TOP_P = 0.9
def _remap_audio8_tts_weights(
weights: Iterable[tuple[str, torch.Tensor]],
*,
q_size: int,
kv_size: int,
fast_q_size: int,
fast_kv_size: int,
) -> Iterable[tuple[str, torch.Tensor]]:
"""Rename Audio8 checkpoint tensors to vLLM / Qwen2 names.
The checkpoint is flat (no ``text_model.`` prefix). Slow AR tensors move
under ``model.``, Fast AR tensors under ``fast_ar.``, and ``wqkv`` splits
into ``{q,k,v}_proj``. See the body for the exact mapping table.
"""
def rewrite_block(suffix: str) -> str:
for old, new in (
(".attention.wo.", ".self_attn.o_proj."),
(".attention.q_norm.", ".self_attn.q_norm."),
(".attention.k_norm.", ".self_attn.k_norm."),
(".attention_norm.", ".input_layernorm."),
(".feed_forward.w1.", ".mlp.gate_proj."),
(".feed_forward.w3.", ".mlp.up_proj."),
(".feed_forward.w2.", ".mlp.down_proj."),
(".ffn_norm.", ".post_attention_layernorm."),
):
suffix = suffix.replace(old, new)
return suffix
for name, tensor in weights:
# RoPE tables are recomputed by vLLM.
if name.endswith(("freqs_cis", "fast_freqs_cis")) or "rotary_emb.inv_freq" in name:
continue
if name.startswith("fast_layers."):
suffix = name[len("fast_layers.") :]
if ".attention.wqkv." in suffix:
layer_prefix, _, param = suffix.partition(".attention.wqkv.")
yield f"fast_ar.layers.{layer_prefix}.self_attn.q_proj.{param}", tensor[:fast_q_size]
yield (
f"fast_ar.layers.{layer_prefix}.self_attn.k_proj.{param}",
tensor[fast_q_size : fast_q_size + fast_kv_size],
)
yield (
f"fast_ar.layers.{layer_prefix}.self_attn.v_proj.{param}",
tensor[fast_q_size + fast_kv_size :],
)
continue
yield f"fast_ar.layers.{rewrite_block(suffix)}", tensor
continue
if name.startswith(("fast_embeddings.", "fast_output.", "fast_norm.", "fast_project_in.")):
yield f"fast_ar.{name}", tensor
continue
if name.startswith("layers."):
suffix = name[len("layers.") :]
if ".attention.wqkv." in suffix:
layer_prefix, _, param = suffix.partition(".attention.wqkv.")
yield f"model.layers.{layer_prefix}.self_attn.q_proj.{param}", tensor[:q_size]
yield (
f"model.layers.{layer_prefix}.self_attn.k_proj.{param}",
tensor[q_size : q_size + kv_size],
)
yield f"model.layers.{layer_prefix}.self_attn.v_proj.{param}", tensor[q_size + kv_size :]
continue
yield f"model.layers.{rewrite_block(suffix)}", tensor
continue
if name == "embeddings.weight":
yield "model.embed_tokens.weight", tensor
continue
if name == "norm.weight":
yield "model.norm.weight", tensor
continue
yield name, tensor
class Audio8TTSSlowARForConditionalGeneration(nn.Module):
"""Stage 0: text -> semantic tokens + residual codec codes."""
prefer_model_sampler = True
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
super().__init__()
self.vllm_config = vllm_config
self.model_path = vllm_config.model_config.model
config: Audio8TTSConfig = vllm_config.model_config.hf_config # type: ignore[assignment]
self.config = config
self.text_config: Audio8TTSSlowARConfig = config.get_text_config()
self.fast_ar_config: Audio8TTSFastARConfig = config.fast_ar_config
self._semantic_begin_id = int(self.text_config.semantic_begin_id)
self._semantic_end_id = int(self.text_config.semantic_end_id)
self._num_semantic_ids = self._semantic_end_id - self._semantic_begin_id + 1
self._eos_token_id = int(self.text_config.eos_token_id)
self._pad_token_id = int(self.text_config.pad_token_id)
self._codebook_size = int(self.text_config.codebook_size)
self._num_codebooks = int(self.text_config.num_codebooks)
self._ras_window_size = int(config.ras_window_size)
self._ras_temperature = float(config.ras_temperature)
self._ras_top_p = float(config.ras_top_p)
self.have_multimodal_outputs = True
self.has_preprocess = True
self.has_postprocess = True
self.mtp_hidden_size = int(self.text_config.hidden_size)
self.talker_mtp_output_key = ("codes", "audio")
self.gpu_resident_buffer_keys: set[tuple[str, str]] = {("hidden_states", "last")}
self.talker_mtp_graph_safe = True
self.model = Qwen2Model(vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model"))
self._fix_rope_style()
if get_pp_group().is_last_rank:
self.lm_head = ParallelLMHead(
self.text_config.vocab_size,
self.text_config.hidden_size,
quant_config=vllm_config.quant_config,
prefix=maybe_prefix(prefix, "lm_head"),
)
else:
self.lm_head = PPMissingLayer()
self.logits_processor = LogitsProcessor(self.text_config.vocab_size)
self.make_empty_intermediate_tensors = self.model.make_empty_intermediate_tensors
# Summed multi-codebook input embedding table.
self.codebook_embeddings = nn.Embedding(
self._codebook_size * self._num_codebooks,
self.text_config.hidden_size,
)
# Fast AR shares the parent's VllmConfig but must not share the
# compilation context: see the Fish Speech note on why this is
# copy.copy and not dataclasses.replace (pydantic validators re-run and
# reject an already-rebound compilation backend).
fast_ar_compilation = copy.copy(vllm_config.compilation_config)
fast_ar_compilation.static_forward_context = {}
self._fast_ar_vllm_config = copy.copy(vllm_config)
self._fast_ar_vllm_config.compilation_config = fast_ar_compilation
from vllm.config.vllm import set_current_vllm_config
with set_current_vllm_config(self._fast_ar_vllm_config):
self.fast_ar = Audio8TTSFastAR(
vllm_config=self._fast_ar_vllm_config,
config=self.fast_ar_config,
slow_ar_config=self.text_config,
prefix="fast_ar",
)
# Constant logits mask: semantic codes plus <|im_end|>. Safe as a
# non-persistent buffer under vLLM (module built on the target device),
# unlike under ``PreTrainedModel.from_pretrained`` on transformers >= 5,
# which meta-inits and then empty_like's every non-persistent buffer.
vocab = int(self.text_config.vocab_size)
allowed = torch.zeros((vocab,), dtype=torch.bool)
allowed[self._semantic_begin_id : min(self._semantic_end_id + 1, vocab)] = True
if self._eos_token_id < vocab:
allowed[self._eos_token_id] = True
self.register_buffer("_semantic_allowed_mask", allowed, persistent=False)
self._speaker_cache = get_speaker_cache()
self._tokenizer = None
def _fix_rope_style(self) -> None:
"""Rebuild RoPE as interleaved (GPT-J); vLLM's Qwen2 defaults to NeoX.
This also replaces the reference implementation's ``freqs_cis`` table
entirely: ``get_rope`` computes its cos/sin cache in the constructor, so
there is no checkpoint-absent buffer for a loader to leave uninitialised.
"""
from vllm.model_executor.layers.rotary_embedding import get_rope
rope_parameters = dict(self.text_config.rope_parameters or {})
rope_parameters.setdefault("rope_type", "default")
for layer in self.model.layers:
attn = layer.self_attn
attn.rotary_emb = get_rope(
head_size=attn.head_dim,
max_position=self.text_config.max_position_embeddings,
is_neox_style=False,
rope_parameters=rope_parameters,
)
logger.info("Audio8 TTS: switched %d layers to interleaved RoPE", len(self.model.layers))
# -------------------- vLLM hooks --------------------
def embed_input_ids(self, input_ids: torch.Tensor, **_: Any) -> torch.Tensor:
return self.model.embed_input_ids(input_ids)
def forward(
self,
input_ids: torch.Tensor,
positions: torch.Tensor,
intermediate_tensors: IntermediateTensors | None = None,
inputs_embeds: torch.Tensor | None = None,
**_: Any,
) -> torch.Tensor | IntermediateTensors:
return self.model(input_ids, positions, intermediate_tensors, inputs_embeds)
def compute_logits(
self,
hidden_states: torch.Tensor | OmniOutput,
sampling_metadata: Any = None,
) -> torch.Tensor | None:
if isinstance(hidden_states, OmniOutput):
hidden_states = hidden_states.text_hidden_states
if hidden_states is None:
return None
logits = self.logits_processor(self.lm_head, hidden_states)
if logits is None:
return None
return logits.masked_fill(~self._semantic_allowed_mask, float("-inf"))
# -------------------- Repetition-Aware Sampling --------------------
def _compact_semantic_logits(self, logits: torch.Tensor) -> torch.Tensor:
"""Slice the allowed vocabulary into ``[B, num_semantic_ids + 1]``.
Local ids ``0..num_semantic_ids-1`` are semantic codes; the last column
is ``<|im_end|>``. Sorting 4097 columns instead of the full 155776
vocabulary is the difference between a cheap and an expensive AR step,
and is exactly equivalent because everything else is already ``-inf``.
"""
semantic = logits[:, self._semantic_begin_id : self._semantic_end_id + 1]
eos = logits[:, self._eos_token_id : self._eos_token_id + 1]
return torch.cat((semantic, eos), dim=-1)
def _local_to_token_id(self, local_ids: torch.Tensor) -> torch.Tensor:
is_eos = local_ids >= self._num_semantic_ids
return torch.where(is_eos, torch.full_like(local_ids, self._eos_token_id), local_ids + self._semantic_begin_id)
def _recent_local_ids(self, output_token_ids: list[list[int]], num_reqs: int, device: torch.device):
"""Build the ``[B, W]`` RAS window in compact id space.
Reads the host-side decoded-token history the AR runner already
materialised, so this costs one small H2D copy and never syncs the GPU.
Returns ``None`` when no request has history yet.
"""
window = self._ras_window_size
if window <= 0:
return None
rows: list[list[int]] = []
any_history = False
for req_idx in range(num_reqs):
history = output_token_ids[req_idx] if req_idx < len(output_token_ids) else []
recent = [int(token) for token in history[-window:]]
local = [
token - self._semantic_begin_id if self._semantic_begin_id <= token <= self._semantic_end_id else -1
for token in recent
]
any_history = any_history or bool(local)
rows.append([-1] * (window - len(local)) + local)
if not any_history:
return None
return torch.tensor(rows, dtype=torch.long, device=device)
def sample(self, logits: torch.Tensor, sampling_metadata: Any) -> SamplerOutput | None:
"""Sample the semantic token with the reference filter order + RAS.
Returns ``None`` to fall back to vLLM's sampler when the request mix
needs features RAS does not model (logprobs, penalties, bad words).
"""
if logits is None or logits.numel() == 0:
return None
if sampling_metadata.max_num_logprobs is not None:
return None
if not sampling_metadata.no_penalties:
return None
if sampling_metadata.bad_words_token_ids:
return None
logits = logits.to(torch.float32)
if sampling_metadata.allowed_token_ids_mask is not None:
num_reqs = int(logits.shape[0])
logits.masked_fill_(sampling_metadata.allowed_token_ids_mask[:num_reqs], float("-inf"))
for processor in sampling_metadata.logitsprocs.non_argmax_invariant:
logits = processor.apply(logits)
compact = self._compact_semantic_logits(logits)
num_reqs = int(compact.shape[0])
device = compact.device
temperature = sampling_metadata.temperature
if sampling_metadata.all_greedy or temperature is None:
local_ids = compact.argmax(dim=-1)
else:
temperature = temperature[:num_reqs]
top_p = DEFAULT_TOP_P if sampling_metadata.top_p is None else sampling_metadata.top_p[:num_reqs]
top_k = DEFAULT_TOP_K if sampling_metadata.top_k is None else sampling_metadata.top_k[:num_reqs]
recent = self._recent_local_ids(sampling_metadata.output_token_ids, num_reqs, device)
local_ids = ras_sample_batch(
compact,
recent,
temperature=temperature,
top_k=top_k,
top_p=top_p,
ras_temperature=self._ras_temperature,
ras_top_p=self._ras_top_p,
num_semantic_ids=self._num_semantic_ids,
generators=sampling_metadata.generators,
num_reqs=num_reqs,
)
token_ids = self._local_to_token_id(local_ids).to(dtype=torch.int32)
return SamplerOutput(sampled_token_ids=token_ids.unsqueeze(-1), logprobs_tensors=None)
# -------------------- Omni multimodal plumbing --------------------
def make_omni_output(self, model_outputs: torch.Tensor | OmniOutput, **kwargs: Any) -> OmniOutput:
if isinstance(model_outputs, OmniOutput):
return model_outputs
hidden = model_outputs
info_dicts = kwargs.get("model_intermediate_buffer")
if info_dicts is None:
info_dicts = kwargs.get("runtime_additional_information") or []
audio_codes_list: list[torch.Tensor] = []
for info in info_dicts:
if not isinstance(info, dict):
continue
codes = info.get("codes", {}).get("audio")
if isinstance(codes, torch.Tensor):
audio_codes_list.append(codes)
if not audio_codes_list:
return OmniOutput(text_hidden_states=hidden, multimodal_outputs={})
audio_codes = torch.cat(audio_codes_list, dim=0)
hidden = hidden[: int(audio_codes.shape[0])]
return OmniOutput(text_hidden_states=hidden, multimodal_outputs={"audio_codes": audio_codes})
# -------------------- preprocess / postprocess --------------------
def preprocess(
self,
input_ids: torch.Tensor,
input_embeds: torch.Tensor | None,
**info_dict: Any,
) -> tuple[torch.Tensor, torch.Tensor, dict[str, Any]]:
additional_information = info_dict.get("additional_information")
if isinstance(additional_information, dict):
merged: dict[str, Any] = {k: v for k, v in info_dict.items() if k != "additional_information"}
for key, value in additional_information.items():
merged.setdefault(key, value)
info_dict = merged
span_len = int(input_ids.shape[0])
if span_len <= 0:
embeds = input_embeds if input_embeds is not None else self.embed_input_ids(input_ids)
return input_ids, embeds, {}
if span_len > 1:
return self._preprocess_prefill(input_ids, info_dict, span_len)
return self._preprocess_decode(input_ids, info_dict)
def _prefill_chunk(
self,
prompt_embeds_buf: torch.Tensor,
start: int,
span_len: int,
device: torch.device,
) -> torch.Tensor:
"""Slice ``span_len`` rows out of the pinned CPU prompt-embed buffer."""
total = int(prompt_embeds_buf.shape[0])
begin = max(0, min(start, total))
end = max(0, min(start + span_len, total))
take = prompt_embeds_buf[begin:end]
if int(take.shape[0]) < span_len:
pad_rows = span_len - int(take.shape[0])
pad_embed = self.embed_input_ids(
torch.tensor([self._pad_token_id], device=device, dtype=torch.long)
).reshape(1, -1)
take = torch.cat([take.to(device=device, dtype=torch.bfloat16), pad_embed.expand(pad_rows, -1)], dim=0)
return take.to(dtype=torch.bfloat16)
return take.to(device=device, dtype=torch.bfloat16, non_blocking=True)
def _preprocess_prefill(
self,
input_ids: torch.Tensor,
info_dict: dict[str, Any],
span_len: int,
) -> tuple[torch.Tensor, torch.Tensor, dict[str, Any]]:
device = input_ids.device
embed = info_dict.get("embed", {})
prompt_embeds_buf = embed.get("prefill")
is_first_chunk = not isinstance(prompt_embeds_buf, torch.Tensor) or prompt_embeds_buf.ndim != 2
if is_first_chunk:
if bool(info_dict.get("audio8_structured_voice_clone", False)):
prompt_embeds = self._build_voice_clone_prefill_embeds(info_dict)
else:
prompt_embeds = self.embed_input_ids(input_ids.reshape(1, -1).to(torch.long)).squeeze(0)
prompt_embeds_buf = prompt_embeds.detach().to("cpu", dtype=torch.bfloat16).contiguous()
if not prompt_embeds_buf.is_pinned():
prompt_embeds_buf = prompt_embeds_buf.pin_memory()
offset = 0
else:
offset = int(info_dict.get("meta", {}).get("prefill_offset", 0) or 0)
total_prompt_len = int(prompt_embeds_buf.shape[0])
chunk = self._prefill_chunk(prompt_embeds_buf, offset, span_len, device)
next_offset = min(offset + span_len, total_prompt_len)
# No codes are emitted during prefill; a zero frame per position keeps
# the codes buffer aligned with the hidden-state span.
zeros = torch.zeros((chunk.shape[0], self._num_codebooks), device=device, dtype=torch.long)
info_update = {
"embed": {"prefill": prompt_embeds_buf if next_offset < total_prompt_len else None},
"meta": {"prefill_offset": next_offset},
"codes": {"audio": zeros},
}
return torch.full_like(input_ids, self._pad_token_id), chunk, info_update
def _preprocess_decode(
self,
input_ids: torch.Tensor,
info_dict: dict[str, Any],
) -> tuple[torch.Tensor, torch.Tensor, dict[str, Any]]:
device = input_ids.device
token_embed = self.embed_input_ids(input_ids.reshape(1, 1).to(torch.long)).to(
device=device, dtype=torch.bfloat16
)
last_hidden = info_dict.get("hidden_states", {}).get("last")
if not isinstance(last_hidden, torch.Tensor):
# First decode step right after prefill: no Fast AR input yet.
logger.warning("Audio8 TTS preprocess: hidden_states.last missing; emitting text-only embedding")
return input_ids, token_embed.reshape(1, -1), {}
# Codebook embeddings are added in talker_mtp, using this step's Fast AR
# output; adding them here would use the previous step's codes.
info_update = {
"mtp_inputs": (
last_hidden.to(device=device, dtype=torch.bfloat16).reshape(1, -1),
torch.zeros(1, self.text_config.hidden_size, device=device, dtype=torch.bfloat16),
),
}
return input_ids, token_embed.reshape(1, -1), info_update
def postprocess(self, hidden_states: torch.Tensor, **_: Any) -> dict[str, Any]:
if hidden_states.numel() == 0:
return {}
return {"hidden_states": {"last": hidden_states[-1, :].detach().contiguous()}}
# -------------------- voice cloning --------------------
def _get_tokenizer(self):
if self._tokenizer is None:
self._tokenizer = AutoTokenizer.from_pretrained(self.model_path)
return self._tokenizer
def _codec_kwargs(self) -> dict[str, int]:
return {
"post_n_layer": int(self.config.codec_post_n_layer),
"post_n_head": int(self.config.codec_post_n_head),
"post_n_local_heads": int(self.config.codec_post_n_local_heads),
"post_intermediate_size": int(self.config.codec_post_intermediate_size),
}
def _build_voice_clone_prefill_embeds(self, info_dict: dict[str, Any]) -> torch.Tensor:
"""Encode the reference audio, build the clone prompt, embed the codes."""
text = info_dict.get("text")
ref_text = info_dict.get("ref_text")
if not isinstance(text, str) or not isinstance(ref_text, str):
raise ValueError("Audio8 TTS voice cloning requires string 'text' and 'ref_text'")
device = self.codebook_embeddings.weight.device
cache_key = None
voice_name = info_dict.get("voice_name")
if isinstance(voice_name, str) and voice_name:
cache_key = self._speaker_cache.make_cache_key(
voice_name,
model_type="audio8_tts",
created_at=int(info_dict.get("voice_created_at") or 0),
)
cached = self._speaker_cache.get(cache_key)
if cached is not None:
logger.debug("Speaker cache HIT for Audio8 TTS speaker '%s'", voice_name)
return self._embed_voice_clone_prompt(
text, ref_text, cached["ref_codes_fq"].to(device=device, dtype=torch.long)
)
ref_audio_sr = info_dict.get("ref_audio_sr")
if not isinstance(ref_audio_sr, int):
raise ValueError("Audio8 TTS voice cloning requires integer 'ref_audio_sr'")
ref_audio_wav = info_dict.get("ref_audio_wav")
if ref_audio_wav is None:
raise ValueError("Audio8 TTS voice cloning requires 'ref_audio_wav'")
if not isinstance(ref_audio_wav, torch.Tensor):
ref_audio_wav = torch.from_numpy(np.asarray(ref_audio_wav, dtype=np.float32))
ref_codes_fq = encode_reference_audio_codes(
self.model_path,
ref_audio_wav,
ref_audio_sr,
device=device,
**self._codec_kwargs(),
)
if cache_key is not None:
self._speaker_cache.put(cache_key, {"ref_codes_fq": ref_codes_fq.detach().cpu()})
logger.debug("Speaker cache STORE for Audio8 TTS speaker '%s'", voice_name)
return self._embed_voice_clone_prompt(text, ref_text, ref_codes_fq)
def _embed_voice_clone_prompt(
self,
text: str,
ref_text: str,
ref_codes_fq: torch.Tensor,
) -> torch.Tensor:
"""Embed the clone prompt, summing codebooks over the reference frames.
Args:
ref_codes_fq: ``[frames, num_codebooks]`` reference codec codes.
"""
device = self.codebook_embeddings.weight.device
ref_codes_fq = ref_codes_fq.to(device=device, dtype=torch.long)
semantic_token_ids = (ref_codes_fq[:, 0] + self._semantic_begin_id).tolist()
prompt_ids, ref_start, _, _ = build_voice_clone_prompt_ids(
self._get_tokenizer(), text, ref_text, semantic_token_ids
)
prompt = torch.tensor(prompt_ids, dtype=torch.long, device=device)
embeds = self.embed_input_ids(prompt.unsqueeze(0)).squeeze(0).to(dtype=torch.bfloat16)
frames = int(ref_codes_fq.shape[0])
if frames <= 0:
return embeds
codebooks = min(int(ref_codes_fq.shape[1]), self._num_codebooks)
offsets = (torch.arange(codebooks, device=device, dtype=torch.long) * self._codebook_size).unsqueeze(0)
codes = ref_codes_fq[:, :codebooks].clamp(min=0, max=self._codebook_size - 1) + offsets
codebook_sum = self.codebook_embeddings(codes).sum(dim=1).to(dtype=embeds.dtype)
result = embeds.clone()
# Audio8 TTS sums the embeddings directly -- no 1/sqrt(Q+1) rescale.
result[ref_start : ref_start + frames] += codebook_sum
return result.to(dtype=torch.bfloat16)
# -------------------- GPU-side Fast AR fast path --------------------
@torch.inference_mode()
def talker_mtp(
self,
input_ids: torch.Tensor,
input_embeds: torch.Tensor,
last_talker_hidden: torch.Tensor,
text_step: torch.Tensor,
seed: int | None = None,
**kwargs: Any,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Run the Fast AR and fold its codes into this step's input embedding.
Returns:
``(inputs_embeds, audio_codes)`` where ``audio_codes`` is
``[B, num_codebooks]``.
"""
del text_step
bsz = int(input_ids.shape[0])
device = input_embeds.device
token_ids = input_ids.reshape(bsz).to(dtype=torch.long, device=device)
past_hidden = last_talker_hidden.reshape(bsz, -1).to(dtype=torch.bfloat16, device=device)
temperature = kwargs.get("temperature")
temperature = DEFAULT_TEMPERATURE if temperature is None else float(temperature)
do_sample = kwargs.get("do_sample")
generator = kwargs.get("generator")
if generator is None and seed is not None:
generator = torch.Generator(device=device)
generator.manual_seed(int(seed))
_top_k = kwargs.get("top_k")
_top_p = kwargs.get("top_p")
audio_codes = self.fast_ar(
slow_ar_hidden=past_hidden,
semantic_token_id=token_ids,
do_sample=(temperature >= SAMPLING_EPS) if do_sample is None else bool(do_sample),
temperature=temperature,
top_k=int(DEFAULT_TOP_K if _top_k is None else _top_k),
top_p=float(DEFAULT_TOP_P if _top_p is None else _top_p),
generator=generator,
)
embeds = input_embeds.reshape(bsz, -1)
offsets = (torch.arange(self._num_codebooks, device=device, dtype=torch.long) * self._codebook_size).unsqueeze(
0
)
codebook_sum = self.codebook_embeddings(audio_codes + offsets).sum(dim=1).to(dtype=embeds.dtype)
is_semantic = (token_ids >= self._semantic_begin_id) & (token_ids <= self._semantic_end_id)
embeds = torch.where(is_semantic.unsqueeze(-1), embeds + codebook_sum, embeds)
return embeds, audio_codes.to(dtype=torch.long)
# -------------------- prompt length estimation --------------------
@staticmethod
def estimate_prompt_len_from_additional_information(
additional_information: dict[str, Any] | None,
**kwargs: Any,
) -> int:
"""Upper-bound the text-only prompt length for placeholder allocation."""
del kwargs
info = additional_information or {}
text = info.get("text", "")
if isinstance(text, list):
text = text[0] if text else ""
# ~1 token per character is a safe bound for CJK; +64 covers the
# chat-template scaffolding.
return max(2, len(str(text)) + 64)
# -------------------- weight loading --------------------
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
text_config = self.text_config
fast_config = self.fast_ar_config
remapped = _remap_audio8_tts_weights(
weights,
q_size=text_config.num_attention_heads * text_config.head_dim,
kv_size=text_config.num_key_value_heads * text_config.head_dim,
fast_q_size=fast_config.num_attention_heads * fast_config.head_dim,
fast_kv_size=fast_config.num_key_value_heads * fast_config.head_dim,
)
stacked_params_mapping = [
("qkv_proj", "q_proj", "q"),
("qkv_proj", "k_proj", "k"),
("qkv_proj", "v_proj", "v"),
("gate_up_proj", "gate_proj", 0),
("gate_up_proj", "up_proj", 1),
]
params_dict = dict(self.named_parameters(remove_duplicate=False))
loaded_params: set[str] = set()
unexpected: list[str] = []
for name, loaded_weight in remapped:
if name == "model.embed_tokens.weight" and self.text_config.tie_word_embeddings:
lm_key = "lm_head.weight"
if lm_key in params_dict:
param = params_dict[lm_key]
loader = getattr(param, "weight_loader", default_weight_loader)
loader(param, loaded_weight)
loaded_params.add(lm_key)
handled = False
for param_name, weight_name, shard_id in stacked_params_mapping:
if weight_name not in name:
continue
mapped = name.replace(weight_name, param_name)
if mapped not in params_dict:
continue
param = params_dict[mapped]
loader = getattr(param, "weight_loader", default_weight_loader)
if loader == default_weight_loader:
loader(param, loaded_weight)
else:
loader(param, loaded_weight, shard_id)
loaded_params.add(mapped)
handled = True
break
if handled:
continue
if name in params_dict:
param = params_dict[name]
loader = getattr(param, "weight_loader", default_weight_loader)
loader(param, loaded_weight)
loaded_params.add(name)
else:
unexpected.append(name)
if unexpected:
raise ValueError(
f"Audio8 TTS Slow AR received {len(unexpected)} unmapped checkpoint tensors, "
f"e.g. {sorted(unexpected)[:5]}. The weight remapper is out of sync with the checkpoint."
)
missing = sorted(set(params_dict) - loaded_params)
if missing:
raise ValueError(f"Audio8 TTS Slow AR is missing weights for {missing[:5]} ({len(missing)} total)")
logger.info("Loaded %d weights for Audio8TTSSlowARForConditionalGeneration", len(loaded_params))
# The reference precomputes RoPE in bf16; keeping fp32 cos/sin here
# shifts the logits enough to trigger early EOS (same failure mode as
# Fish Speech).
truncated = 0
for module in self.modules():
cache = getattr(module, "cos_sin_cache", None)
if isinstance(cache, torch.Tensor):
module.cos_sin_cache = cache.to(torch.bfloat16).to(cache.dtype)
truncated += 1
if truncated:
logger.info("Audio8 TTS: truncated %d RoPE cos_sin_cache buffers to bf16", truncated)
return loaded_params
__all__ = ["Audio8TTSSlowARForConditionalGeneration"]
@@ -0,0 +1,600 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Audio8 TTS neural audio codec (44.1 kHz, 10 codebooks).
Vendored from the reference ``modeling_arktts_codec.py`` shipped with
``Audio8/Audio8-TTS-Preview-0.6b`` (Apache-2.0). The module tree and attribute
names are reproduced verbatim so ``codec.pth`` loads under ``strict=True``.
Inference-only deviations: no ``torch.jit.script`` on Snake (it fights
``torch.compile`` / CUDA graphs), RoPE cached in a plain dict instead of a
non-persistent buffer (the pattern that leaves the reference LM with
uninitialised RoPE under ``from_pretrained`` on transformers >= 5), and
:func:`build_arktts_codec` prunes the unused encoder or decoder half per stage.
"""
from __future__ import annotations
import math
from typing import Any
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
from torch.nn.utils import weight_norm as legacy_weight_norm
from torch.nn.utils.parametrizations import weight_norm
# The codec's own transformer blocks always use base 10000, independent of the
# 1e6 rope_base of the DualAR language model.
_CODEC_ROPE_BASE = 10000.0
def _rope_table(length: int, head_dim: int, base: float, device: torch.device) -> Tensor:
frequencies = 1.0 / (base ** (torch.arange(0, head_dim, 2, device=device).float() / head_dim))
phases = torch.outer(torch.arange(length, device=device), frequencies)
values = torch.polar(torch.ones_like(phases), phases)
return torch.stack((values.real, values.imag), dim=-1).to(torch.bfloat16)
def _apply_rope(x: Tensor, values: Tensor) -> Tensor:
shaped = x.float().reshape(*x.shape[:-1], -1, 2)
values = values.view(1, shaped.shape[1], 1, shaped.shape[3], 2)
output = torch.stack(
(
shaped[..., 0] * values[..., 0] - shaped[..., 1] * values[..., 1],
shaped[..., 1] * values[..., 0] + shaped[..., 0] * values[..., 1],
),
dim=-1,
)
return output.flatten(3).to(x.dtype)
class ArkttsCodecRMSNorm(nn.Module):
def __init__(self, dim: int, eps: float = 1e-5) -> None:
super().__init__()
self.eps = float(eps)
self.weight = nn.Parameter(torch.ones(dim))
def forward(self, x: Tensor) -> Tensor:
output = x.float() * torch.rsqrt(x.float().pow(2).mean(-1, keepdim=True) + self.eps)
return output.to(x.dtype) * self.weight
class ArkttsCodecLayerScale(nn.Module):
def __init__(self, dim: int, init_values: float = 1e-2) -> None:
super().__init__()
self.gamma = nn.Parameter(init_values * torch.ones(dim))
def forward(self, x: Tensor) -> Tensor:
return x * self.gamma
class ArkttsCodecTransformerConfig:
"""Plain option holder for the codec's transformer blocks.
Deliberately not a dataclass / msgspec Struct: it mirrors a reference
dataclass whose only job is to carry constructor arguments, and it is
instantiated from Python literals inside this module only.
"""
def __init__(
self,
n_layer: int,
n_head: int,
dim: int,
intermediate_size: int,
n_local_heads: int = -1,
head_dim: int = 64,
rope_base: float = _CODEC_ROPE_BASE,
norm_eps: float = 1e-5,
channels_first: bool = True,
) -> None:
self.n_layer = int(n_layer)
self.n_head = int(n_head)
self.dim = int(dim)
self.intermediate_size = int(intermediate_size)
self.n_local_heads = int(n_head) if n_local_heads == -1 else int(n_local_heads)
self.head_dim = int(head_dim)
self.rope_base = float(rope_base)
self.norm_eps = float(norm_eps)
self.channels_first = bool(channels_first)
class ArkttsCodecAttention(nn.Module):
def __init__(self, config: ArkttsCodecTransformerConfig) -> None:
super().__init__()
total = (config.n_head + 2 * config.n_local_heads) * config.head_dim
self.wqkv = nn.Linear(config.dim, total, bias=False)
self.wo = nn.Linear(config.head_dim * config.n_head, config.dim, bias=False)
self.n_head = config.n_head
self.n_local_heads = config.n_local_heads
self.head_dim = config.head_dim
def forward(self, x: Tensor, rope_values: Tensor, mask: Tensor) -> Tensor:
batch, length, _ = x.shape
query_size = self.n_head * self.head_dim
kv_size = self.n_local_heads * self.head_dim
query, key, value = self.wqkv(x).split((query_size, kv_size, kv_size), dim=-1)
query = query.view(batch, length, self.n_head, self.head_dim)
key = key.view(batch, length, self.n_local_heads, self.head_dim)
value = value.view(batch, length, self.n_local_heads, self.head_dim)
query = _apply_rope(query, rope_values).transpose(1, 2)
key = _apply_rope(key, rope_values).transpose(1, 2)
value = value.transpose(1, 2)
output = F.scaled_dot_product_attention(
query,
key,
value,
attn_mask=mask,
enable_gqa=self.n_local_heads != self.n_head,
)
output = output.transpose(1, 2).contiguous().view(batch, length, query_size)
return self.wo(output)
class ArkttsCodecFeedForward(nn.Module):
def __init__(self, config: ArkttsCodecTransformerConfig) -> None:
super().__init__()
self.w1 = nn.Linear(config.dim, config.intermediate_size, bias=False)
self.w3 = nn.Linear(config.dim, config.intermediate_size, bias=False)
self.w2 = nn.Linear(config.intermediate_size, config.dim, bias=False)
def forward(self, x: Tensor) -> Tensor:
return self.w2(F.silu(self.w1(x)) * self.w3(x))
class ArkttsCodecTransformerBlock(nn.Module):
def __init__(self, config: ArkttsCodecTransformerConfig) -> None:
super().__init__()
self.attention = ArkttsCodecAttention(config)
self.feed_forward = ArkttsCodecFeedForward(config)
self.ffn_norm = ArkttsCodecRMSNorm(config.dim, config.norm_eps)
self.attention_norm = ArkttsCodecRMSNorm(config.dim, config.norm_eps)
self.attention_layer_scale = ArkttsCodecLayerScale(config.dim)
self.ffn_layer_scale = ArkttsCodecLayerScale(config.dim)
def forward(self, x: Tensor, rope_values: Tensor, mask: Tensor) -> Tensor:
hidden = x + self.attention_layer_scale(self.attention(self.attention_norm(x), rope_values, mask))
return hidden + self.ffn_layer_scale(self.feed_forward(self.ffn_norm(hidden)))
class ArkttsCodecWindowTransformer(nn.Module):
"""Causal transformer with a sliding attention window."""
def __init__(
self,
config: ArkttsCodecTransformerConfig,
input_dim: int,
window_size: int | None,
) -> None:
super().__init__()
self.layers = nn.ModuleList([ArkttsCodecTransformerBlock(config) for _ in range(config.n_layer)])
self.norm = ArkttsCodecRMSNorm(config.dim, config.norm_eps)
self.window_size = window_size
self.channels_first = config.channels_first
self.input_proj = nn.Linear(input_dim, config.dim) if input_dim != config.dim else nn.Identity()
self.output_proj = nn.Linear(config.dim, input_dim) if input_dim != config.dim else nn.Identity()
self.look_ahead_conv = nn.Identity()
self.head_dim = config.head_dim
self.rope_base = config.rope_base
self._mask_cache: dict[tuple[int, str], Tensor] = {}
self._rope_cache: dict[tuple[int, str], Tensor] = {}
def _mask(self, length: int, device: torch.device) -> Tensor:
key = (length, str(device))
cached = self._mask_cache.get(key)
if cached is not None:
return cached
row = torch.arange(length, device=device)[:, None]
column = torch.arange(length, device=device)[None, :]
mask = column <= row
if self.window_size is not None:
mask &= column >= (row - self.window_size + 1).clamp_min(0)
mask = mask[None, None]
self._mask_cache[key] = mask
return mask
def _rope(self, length: int, device: torch.device) -> Tensor:
key = (length, str(device))
cached = self._rope_cache.get(key)
if cached is not None:
return cached
values = _rope_table(length, self.head_dim, self.rope_base, device)
self._rope_cache[key] = values
return values
def forward(self, x: Tensor) -> Tensor:
if self.channels_first:
x = x.transpose(1, 2)
x = self.look_ahead_conv(self.input_proj(x))
length = int(x.shape[1])
mask = self._mask(length, x.device)
rope_values = self._rope(length, x.device)
for layer in self.layers:
x = layer(x, rope_values, mask)
x = self.output_proj(self.norm(x))
return x.transpose(1, 2) if self.channels_first else x
def _extra_padding(x: Tensor, kernel_size: int, stride: int, padding_total: int = 0) -> int:
length = x.shape[-1]
frames = (length - kernel_size + padding_total) / stride + 1
ideal = (math.ceil(frames) - 1) * stride + kernel_size - padding_total
return ideal - length
class ArkttsCausalConv1d(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size: int,
dilation: int = 1,
stride: int = 1,
groups: int = 1,
) -> None:
super().__init__()
self.conv = nn.Conv1d(in_channels, out_channels, kernel_size, stride=stride, dilation=dilation, groups=groups)
self.stride = stride
self.kernel_size = (kernel_size - 1) * dilation + 1
self.padding = self.kernel_size - self.stride
def forward(self, x: Tensor) -> Tensor:
right = _extra_padding(x, self.kernel_size, self.stride, self.padding)
return self.conv(F.pad(x, (self.padding, right))).contiguous()
def apply_weight_norm(self) -> ArkttsCausalConv1d:
self.conv = weight_norm(self.conv)
return self
class ArkttsCausalConvTranspose1d(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size: int,
stride: int = 1,
dilation: int = 1,
) -> None:
super().__init__()
self.conv = nn.ConvTranspose1d(in_channels, out_channels, kernel_size, stride=stride, dilation=dilation)
self.stride = stride
self.kernel_size = kernel_size
def forward(self, x: Tensor) -> Tensor:
x = self.conv(x)
crop = self.kernel_size - self.stride
return x[..., : x.shape[-1] - crop].contiguous() if crop else x.contiguous()
def apply_weight_norm(self) -> ArkttsCausalConvTranspose1d:
self.conv = weight_norm(self.conv)
return self
def _causal_wn_conv(*args: Any, **kwargs: Any) -> ArkttsCausalConv1d:
return ArkttsCausalConv1d(*args, **kwargs).apply_weight_norm()
def _causal_wn_transpose(*args: Any, **kwargs: Any) -> ArkttsCausalConvTranspose1d:
return ArkttsCausalConvTranspose1d(*args, **kwargs).apply_weight_norm()
class ArkttsSnake1d(nn.Module):
def __init__(self, channels: int) -> None:
super().__init__()
self.alpha = nn.Parameter(torch.ones(1, channels, 1))
def forward(self, x: Tensor) -> Tensor:
shape = x.shape
x = x.reshape(shape[0], shape[1], -1)
x = x + (self.alpha + 1e-9).reciprocal() * torch.sin(self.alpha * x).pow(2)
return x.reshape(shape)
class ArkttsResidualUnit(nn.Module):
def __init__(self, dim: int, dilation: int) -> None:
super().__init__()
self.block = nn.Sequential(
ArkttsSnake1d(dim),
_causal_wn_conv(dim, dim, kernel_size=7, dilation=dilation),
ArkttsSnake1d(dim),
_causal_wn_conv(dim, dim, kernel_size=1),
)
def forward(self, x: Tensor) -> Tensor:
output = self.block(x)
difference = x.shape[-1] - output.shape[-1]
if difference > 0:
x = x[..., :-difference]
return x + output
class ArkttsEncoderBlock(nn.Module):
def __init__(self, dim: int, stride: int, transformer_layers: int) -> None:
super().__init__()
modules: list[nn.Module] = [
ArkttsResidualUnit(dim // 2, 1),
ArkttsResidualUnit(dim // 2, 3),
ArkttsResidualUnit(dim // 2, 9),
ArkttsSnake1d(dim // 2),
_causal_wn_conv(dim // 2, dim, kernel_size=2 * stride, stride=stride),
]
if transformer_layers:
config = ArkttsCodecTransformerConfig(
n_layer=transformer_layers,
n_head=dim // 64,
dim=dim,
intermediate_size=dim * 3,
)
modules.append(ArkttsCodecWindowTransformer(config, dim, window_size=512))
else:
modules.append(nn.Identity())
self.block = nn.Sequential(*modules)
def forward(self, x: Tensor) -> Tensor:
return self.block(x)
class ArkttsEncoder(nn.Module):
def __init__(self) -> None:
super().__init__()
dim = 64
modules: list[nn.Module] = [_causal_wn_conv(1, dim, kernel_size=7)]
for stride, transformer_layers in zip((2, 4, 8, 8), (0, 0, 0, 4), strict=True):
dim *= 2
modules.append(ArkttsEncoderBlock(dim, stride, transformer_layers))
modules.extend((ArkttsSnake1d(dim), _causal_wn_conv(dim, 1024, kernel_size=3)))
self.block = nn.Sequential(*modules)
def forward(self, x: Tensor) -> Tensor:
return self.block(x)
class ArkttsDecoderBlock(nn.Module):
def __init__(self, input_dim: int, output_dim: int, stride: int) -> None:
super().__init__()
self.block = nn.Sequential(
ArkttsSnake1d(input_dim),
_causal_wn_transpose(input_dim, output_dim, kernel_size=2 * stride, stride=stride),
ArkttsResidualUnit(output_dim, 1),
ArkttsResidualUnit(output_dim, 3),
ArkttsResidualUnit(output_dim, 9),
)
def forward(self, x: Tensor) -> Tensor:
return self.block(x)
class ArkttsDecoder(nn.Module):
def __init__(self) -> None:
super().__init__()
channels = 1536
modules: list[nn.Module] = [_causal_wn_conv(1024, channels, kernel_size=7)]
output_dim = channels
for index, stride in enumerate((8, 8, 4, 2)):
input_dim = channels // (2**index)
output_dim = channels // (2 ** (index + 1))
modules.append(ArkttsDecoderBlock(input_dim, output_dim, stride))
modules.extend(
(
ArkttsSnake1d(output_dim),
_causal_wn_conv(output_dim, 1, kernel_size=7),
nn.Tanh(),
)
)
self.model = nn.Sequential(*modules)
def forward(self, x: Tensor) -> Tensor:
return self.model(x)
class ArkttsVectorQuantizer(nn.Module):
def __init__(self, input_dim: int, codebook_size: int, codebook_dim: int) -> None:
super().__init__()
self.codebook_size = int(codebook_size)
self.codebook_dim = int(codebook_dim)
self.in_proj = legacy_weight_norm(nn.Conv1d(input_dim, codebook_dim, kernel_size=1))
self.out_proj = legacy_weight_norm(nn.Conv1d(codebook_dim, input_dim, kernel_size=1))
self.codebook = nn.Embedding(codebook_size, codebook_dim)
def decode_code(self, indices: Tensor) -> Tensor:
return F.embedding(indices, self.codebook.weight).transpose(1, 2)
def decode_latents(self, latents: Tensor) -> tuple[Tensor, Tensor]:
batch, _, length = latents.shape
flattened = F.normalize(latents.transpose(1, 2).reshape(batch * length, -1))
codebook = F.normalize(self.codebook.weight)
distances = (
flattened.pow(2).sum(1, keepdim=True)
- 2 * flattened @ codebook.t()
+ codebook.pow(2).sum(1, keepdim=True).t()
)
indices = (-distances).argmax(1).view(batch, length)
return self.decode_code(indices), indices
def forward(self, z: Tensor) -> tuple[Tensor, Tensor]:
projected = self.in_proj(z)
quantized, indices = self.decode_latents(projected)
return self.out_proj(quantized), indices
class ArkttsResidualQuantizer(nn.Module):
def __init__(self, input_dim: int, n_codebooks: int, codebook_size: int, codebook_dim: int) -> None:
super().__init__()
self.n_codebooks = int(n_codebooks)
self.codebook_size = int(codebook_size)
self.quantizers = nn.ModuleList(
[ArkttsVectorQuantizer(input_dim, codebook_size, codebook_dim) for _ in range(n_codebooks)]
)
def forward(self, z: Tensor) -> tuple[Tensor, Tensor]:
quantized_sum: Tensor | float = 0.0
residual = z
codes: list[Tensor] = []
for quantizer in self.quantizers:
quantized, indices = quantizer(residual)
quantized_sum = quantized_sum + quantized
residual = residual - quantized
codes.append(indices)
return quantized_sum, torch.stack(codes, dim=1)
def from_codes(self, codes: Tensor) -> Tensor:
output: Tensor | float = 0.0
for index in range(codes.shape[1]):
projected = self.quantizers[index].decode_code(codes[:, index])
output = output + self.quantizers[index].out_proj(projected)
return output
class ArkttsConvNeXtBlock(nn.Module):
def __init__(self, dim: int) -> None:
super().__init__()
self.dwconv = ArkttsCausalConv1d(dim, dim, kernel_size=7, groups=dim)
self.norm = nn.LayerNorm(dim, eps=1e-6)
self.pwconv1 = nn.Linear(dim, 4 * dim)
self.act = nn.GELU()
self.pwconv2 = nn.Linear(4 * dim, dim)
self.gamma = nn.Parameter(1e-6 * torch.ones(dim))
def forward(self, x: Tensor) -> Tensor:
residual = x
x = self.dwconv(x).permute(0, 2, 1)
x = self.pwconv2(self.act(self.pwconv1(self.norm(x))))
x = (self.gamma * x).permute(0, 2, 1)
return residual + x
class ArkttsDownsampleQuantizer(nn.Module):
"""1 semantic codebook (4096) + 9 residual codebooks (1024), 4x downsampled."""
def __init__(
self,
post_n_layer: int = 8,
post_n_head: int = 16,
post_n_local_heads: int = 8,
post_intermediate_size: int = 1216,
) -> None:
super().__init__()
self.semantic_quantizer = ArkttsResidualQuantizer(1024, 1, 4096, 8)
self.quantizer = ArkttsResidualQuantizer(1024, 9, 1024, 8)
self.downsample = nn.Sequential(
nn.Sequential(ArkttsCausalConv1d(1024, 1024, kernel_size=2, stride=2), ArkttsConvNeXtBlock(1024)),
nn.Sequential(ArkttsCausalConv1d(1024, 1024, kernel_size=2, stride=2), ArkttsConvNeXtBlock(1024)),
)
self.upsample = nn.Sequential(
nn.Sequential(ArkttsCausalConvTranspose1d(1024, 1024, kernel_size=2, stride=2), ArkttsConvNeXtBlock(1024)),
nn.Sequential(ArkttsCausalConvTranspose1d(1024, 1024, kernel_size=2, stride=2), ArkttsConvNeXtBlock(1024)),
)
self.pre_module = ArkttsCodecWindowTransformer(
ArkttsCodecTransformerConfig(n_layer=8, n_head=16, dim=1024, intermediate_size=3072),
1024,
window_size=128,
)
self.post_module = ArkttsCodecWindowTransformer(
ArkttsCodecTransformerConfig(
n_layer=post_n_layer,
n_head=post_n_head,
n_local_heads=post_n_local_heads,
dim=1024,
intermediate_size=post_intermediate_size,
),
1024,
window_size=128,
)
self.semantic_predictor_module = nn.Identity()
def forward(self, z: Tensor) -> tuple[Tensor, Tensor]:
original_length = z.shape[-1]
z = self.pre_module(self.downsample(z))
semantic, semantic_codes = self.semantic_quantizer(z)
residual, residual_codes = self.quantizer(z - semantic)
z = self.upsample(self.post_module(semantic + residual))
difference = original_length - z.shape[-1]
if difference > 0:
z = F.pad(z, (difference, 0))
elif difference < 0:
z = z[..., -difference:]
return z, torch.cat((semantic_codes, residual_codes), dim=1)
def decode(self, indices: Tensor) -> Tensor:
# Cloned because the clamps below are in-place and this is the caller's
# codes buffer; once per decode chunk, not per AR step.
indices = indices.clone()
indices[:, 0].clamp_(0, self.semantic_quantizer.codebook_size - 1)
indices[:, 1:].clamp_(0, self.quantizer.codebook_size - 1)
semantic = self.semantic_quantizer.from_codes(indices[:, :1])
residual = self.quantizer.from_codes(indices[:, 1:])
return self.upsample(self.post_module(semantic + residual))
class ArkttsCodec(nn.Module):
"""Audio8 TTS codec: waveform <-> 10 codebooks at ~21.5 frames/s."""
sample_rate = 44100
frame_length = 2048
def __init__(
self,
post_n_layer: int = 8,
post_n_head: int = 16,
post_n_local_heads: int = 8,
post_intermediate_size: int = 1216,
) -> None:
super().__init__()
self.encoder = ArkttsEncoder()
self.quantizer = ArkttsDownsampleQuantizer(
post_n_layer=post_n_layer,
post_n_head=post_n_head,
post_n_local_heads=post_n_local_heads,
post_intermediate_size=post_intermediate_size,
)
self.decoder = ArkttsDecoder()
@torch.inference_mode()
def encode(self, audio: Tensor, audio_lengths: Tensor | None = None) -> tuple[Tensor, Tensor]:
"""Encode ``[B, 1, samples]`` (or ``[B, samples]``) to ``[B, 10, frames]``."""
if audio.ndim == 2:
audio = audio[:, None]
if audio.ndim != 3 or audio.shape[1] != 1:
raise ValueError(f"audio must have shape [B, 1, samples], got {tuple(audio.shape)}")
original_length = int(audio.shape[-1])
right = math.ceil(original_length / self.frame_length) * self.frame_length - original_length
if right:
audio = F.pad(audio, (0, right))
if audio_lengths is None:
audio_lengths = torch.full((audio.shape[0],), original_length, device=audio.device, dtype=torch.long)
_, codes = self.quantizer(self.encoder(audio))
code_lengths = torch.ceil(audio_lengths.float() / self.frame_length).long()
max_codes = int(codes.shape[-1])
code_lengths = code_lengths.clamp_max(max_codes)
frame_index = torch.arange(max_codes, device=codes.device)
valid = frame_index[None, None, :] < code_lengths[:, None, None]
return torch.where(valid, codes, torch.full_like(codes, -1)), code_lengths
@torch.inference_mode()
def decode(self, codes: Tensor) -> Tensor:
"""Decode ``[B, 10, frames]`` to ``[B, 1, samples]``."""
return self.decoder(self.quantizer.decode(codes.long()))
def build_arktts_codec(
*,
post_n_layer: int = 8,
post_n_head: int = 16,
post_n_local_heads: int = 8,
post_intermediate_size: int = 1216,
) -> ArkttsCodec:
"""Construct the codec with uninitialised weights, on CPU, in eval mode."""
codec = ArkttsCodec(
post_n_layer=post_n_layer,
post_n_head=post_n_head,
post_n_local_heads=post_n_local_heads,
post_intermediate_size=post_intermediate_size,
)
codec.eval()
return codec
__all__ = ["ArkttsCodec", "build_arktts_codec"]
@@ -0,0 +1,224 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Loading / caching helpers for the Audio8 TTS ``codec.pth`` checkpoint.
Both stages need the codec but for opposite halves: Stage 0 encodes reference
audio for zero-shot voice cloning, Stage 1 decodes generated codes to waveform.
The unused half is pruned before the module is moved to the device so a stage
never pays GPU memory for weights it cannot reach.
"""
from __future__ import annotations
import os
from functools import lru_cache
import numpy as np
import torch
import torch.nn as nn
from torch.nn.utils.parametrize import remove_parametrizations
from vllm.logger import init_logger
from vllm_omni.model_executor.models.audio8_tts.codec import ArkttsCodec, build_arktts_codec
from vllm_omni.model_executor.models.audio8_tts.configuration_audio8_tts import (
ARKTTS_CODEC_FRAME_SIZE,
ARKTTS_CODEC_SAMPLE_RATE,
)
logger = init_logger(__name__)
CODEC_FILENAME = "codec.pth"
_codec_cache: dict[tuple[str, str, str, str], ArkttsCodec] = {}
def resolve_codec_path(model_path: str, filename: str = CODEC_FILENAME) -> str:
"""Return a local path to ``filename``, downloading from the Hub if needed."""
local = os.path.join(model_path, filename)
if os.path.exists(local):
return local
from transformers.utils.hub import cached_file
cached = cached_file(model_path, filename)
if cached is None or not os.path.exists(cached):
raise FileNotFoundError(
f"{filename} not found for {model_path}; the Audio8 TTS checkpoint must ship its neural audio codec."
)
return cached
def bake_weight_norm(module: nn.Module) -> int:
"""Fold weight-norm parametrisations into plain weights (inference only)."""
baked = 0
for submodule in module.modules():
parametrizations = getattr(submodule, "parametrizations", None)
if not parametrizations:
continue
for name in list(parametrizations.keys()):
remove_parametrizations(submodule, name, leave_parametrized=True)
baked += 1
return baked
def load_arktts_codec(
model_path: str,
*,
device: torch.device | str = "cpu",
dtype: torch.dtype = torch.float32,
role: str = "decode",
post_n_layer: int = 8,
post_n_head: int = 16,
post_n_local_heads: int = 8,
post_intermediate_size: int = 1216,
) -> ArkttsCodec:
"""Load ``codec.pth`` for ``role`` in {"encode", "decode", "both"}.
Instances are cached per (path, device, dtype, role) because both the Stage-0
voice-clone path and the Stage-1 decoder may ask for the same codec many
times per request.
"""
if role not in {"encode", "decode", "both"}:
raise ValueError(f"role must be encode/decode/both, got {role!r}")
device = torch.device(device)
cache_key = (model_path, str(device), str(dtype), role)
cached_codec = _codec_cache.get(cache_key)
if cached_codec is not None:
return cached_codec
codec_path = resolve_codec_path(model_path)
codec = build_arktts_codec(
post_n_layer=post_n_layer,
post_n_head=post_n_head,
post_n_local_heads=post_n_local_heads,
post_intermediate_size=post_intermediate_size,
)
state = torch.load(codec_path, map_location="cpu", weights_only=True)
if "state_dict" in state:
state = state["state_dict"]
if any("generator." in key for key in state):
state = {key.replace("generator.", ""): value for key, value in state.items() if "generator." in key}
state = {key: value for key, value in state.items() if not key.endswith(("freqs_cis", "causal_mask"))}
codec.load_state_dict(state, strict=True)
baked = bake_weight_norm(codec)
if role == "encode":
codec.decoder = None
elif role == "decode":
codec.encoder = None
codec.quantizer.pre_module = None
codec.quantizer.downsample = None
codec = codec.to(device=device, dtype=dtype)
codec.eval()
_codec_cache[cache_key] = codec
logger.info(
"Loaded Audio8 TTS codec from %s (role=%s, device=%s, dtype=%s, baked_weight_norms=%d)",
codec_path,
role,
device,
dtype,
baked,
)
return codec
@lru_cache(maxsize=8)
def _resample_transform(source_sr: int, target_sr: int, device: torch.device, dtype: torch.dtype):
import torchaudio
return torchaudio.transforms.Resample(source_sr, target_sr).to(device=device, dtype=dtype)
def prepare_reference_waveform(
wav_samples: list[float] | np.ndarray | torch.Tensor,
sample_rate: int,
*,
device: torch.device,
dtype: torch.dtype = torch.float32,
) -> torch.Tensor:
"""Down-mix to mono and resample reference audio to the codec's rate.
Returns a 1-D waveform tensor.
"""
if isinstance(wav_samples, torch.Tensor):
wav = wav_samples.detach()
else:
wav = torch.as_tensor(np.asarray(wav_samples))
wav = wav.to(device=device, dtype=dtype)
if wav.ndim == 2:
# Accept [channels, samples] and [samples, channels].
if wav.shape[0] <= 8 and wav.shape[1] > wav.shape[0]:
wav = wav.mean(dim=0)
elif wav.shape[-1] <= 8 and wav.shape[0] > wav.shape[-1]:
wav = wav.mean(dim=-1)
else:
wav = wav.mean(dim=0)
elif wav.ndim > 2:
wav = wav.reshape(-1, wav.shape[-1]).mean(dim=0)
wav = wav.reshape(-1)
if wav.numel() == 0:
raise ValueError("Reference audio must not be empty")
if int(sample_rate) <= 0:
raise ValueError(f"Reference audio sample rate must be positive, got {sample_rate}")
if int(sample_rate) != ARKTTS_CODEC_SAMPLE_RATE:
transform = _resample_transform(int(sample_rate), ARKTTS_CODEC_SAMPLE_RATE, wav.device, wav.dtype)
wav = transform(wav.unsqueeze(0)).squeeze(0)
return wav.contiguous()
@torch.no_grad()
def encode_reference_audio_codes(
model_path: str,
wav_samples: list[float] | np.ndarray | torch.Tensor,
sample_rate: int,
*,
device: torch.device | str,
**codec_kwargs: int,
) -> torch.Tensor:
"""Encode reference audio into codec codes.
Returns:
``[frames, num_codebooks]`` int64 codes on ``device``.
"""
device = torch.device(device)
codec = load_arktts_codec(model_path, device=device, dtype=torch.float32, role="encode", **codec_kwargs)
wav = prepare_reference_waveform(wav_samples, sample_rate, device=device)
lengths = torch.tensor([wav.numel()], device=device, dtype=torch.long)
codes, code_lengths = codec.encode(wav.reshape(1, 1, -1), lengths)
frames = int(code_lengths[0].item())
codes_fq = codes[0, :, :frames].transpose(0, 1).to(dtype=torch.long).contiguous()
logger.info(
"Encoded Audio8 TTS reference audio: %d samples @ %d Hz -> frames=%d codebooks=%d",
int(wav.numel()),
int(sample_rate),
int(codes_fq.shape[0]),
int(codes_fq.shape[1]),
)
return codes_fq
def estimate_reference_code_frames(num_samples: int, sample_rate: int) -> int:
"""Frames the codec will emit for ``num_samples`` at ``sample_rate``.
Used by the serving layer to size the prompt placeholder without paying for
a codec encode on the API thread.
"""
if num_samples <= 0 or sample_rate <= 0:
raise ValueError("Reference audio must have a positive length and sample rate")
resampled = max(1, -(-num_samples * ARKTTS_CODEC_SAMPLE_RATE // sample_rate))
return max(1, -(-resampled // ARKTTS_CODEC_FRAME_SIZE))
__all__ = [
"CODEC_FILENAME",
"bake_weight_norm",
"encode_reference_audio_codes",
"estimate_reference_code_frames",
"load_arktts_codec",
"prepare_reference_waveform",
"resolve_codec_path",
]
@@ -0,0 +1,267 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Configuration classes for Audio8 TTS Preview (``model_type = "arktts"``).
Audio8's HuggingFace config is flat and uses DualAR field names (``dim``,
``n_layer``, ``n_head``, ``fast_dim``, ...); this module re-exports them under
Qwen2 attribute names so vLLM's ``Qwen2Model`` consumes the Slow AR half, and
splits the Fast AR half into its own sub-config. The backbone is Qwen2 rather
than Qwen3 (Fish Speech) because Audio8 uses ``qkv_bias=true`` with no q/k
norm -- exactly the Qwen2 attention shape.
"""
from __future__ import annotations
from typing import Any
from transformers import PretrainedConfig
#: Codec frame stride in waveform samples (encoder rates 2*4*8*8 = 512 times the
#: quantizer's 2*2 downsample). 44100 / 2048 ~= 21.5 frames per second.
ARKTTS_CODEC_FRAME_SIZE = 2048
ARKTTS_CODEC_SAMPLE_RATE = 44100
#: Only the first codebook is a 4096-entry semantic codebook; codebooks 1..N-1
#: are 1024-entry residual codebooks (see ``ArkttsDownsampleQuantizer``).
ARKTTS_SEMANTIC_CODEBOOK_SIZE = 4096
ARKTTS_RESIDUAL_CODEBOOK_SIZE = 1024
class Audio8TTSSlowARConfig(PretrainedConfig):
"""Slow AR config exposed with Qwen2-compatible attribute names."""
model_type = "arktts_slow_ar"
def __init__(
self,
vocab_size: int = 155776,
dim: int = 896,
n_head: int = 14,
n_local_heads: int = 2,
head_dim: int = 64,
n_layer: int = 24,
intermediate_size: int = 4864,
max_seq_len: int = 2048,
rope_base: float = 1_000_000.0,
norm_eps: float = 1e-6,
attention_qkv_bias: bool = True,
attention_qk_norm: bool = False,
tie_word_embeddings: bool = True,
codebook_size: int = ARKTTS_SEMANTIC_CODEBOOK_SIZE,
num_codebooks: int = 10,
semantic_begin_id: int = 151678,
semantic_end_id: int = 155773,
eos_token_id: int = 151645,
pad_token_id: int = 151643,
**kwargs: Any,
) -> None:
# Audio8 field names -> standard Transformers / Qwen2 names.
self.hidden_size = int(dim)
self.num_attention_heads = int(n_head)
self.num_key_value_heads = int(n_local_heads)
self.head_dim = int(head_dim)
self.num_hidden_layers = int(n_layer)
self.intermediate_size = int(intermediate_size)
self.max_position_embeddings = int(max_seq_len)
self.rms_norm_eps = float(norm_eps)
self.hidden_act = "silu"
# Qwen2Attention hardcodes qkv bias=True / o_proj bias=False, which is
# what Audio8 TTS ships. Keep the flags so a future checkpoint that
# flips them fails loudly in the model rather than loading silently.
self.attention_qkv_bias = bool(attention_qkv_bias)
self.attention_qk_norm = bool(attention_qk_norm)
# Set explicitly (rather than relying on vLLM's set_default_rope_theta)
# so that a checkpoint with a non-default rope_base is honoured.
self.rope_parameters = {"rope_type": "default", "rope_theta": float(rope_base)}
# Codec / codebook fields.
self.codebook_size = int(codebook_size)
self.num_codebooks = int(num_codebooks)
self.semantic_begin_id = int(semantic_begin_id)
self.semantic_end_id = int(semantic_end_id)
super().__init__(
vocab_size=int(vocab_size),
tie_word_embeddings=bool(tie_word_embeddings),
eos_token_id=int(eos_token_id),
pad_token_id=int(pad_token_id),
**kwargs,
)
class Audio8TTSFastARConfig(PretrainedConfig):
"""Fast AR config: the ``n_fast_layer`` residual-codebook predictor."""
model_type = "arktts_fast_ar"
def __init__(
self,
codebook_size: int = ARKTTS_SEMANTIC_CODEBOOK_SIZE,
num_codebooks: int = 10,
fast_dim: int = 896,
fast_n_head: int = 14,
fast_n_local_heads: int = 2,
fast_head_dim: int = 64,
n_fast_layer: int = 4,
fast_intermediate_size: int = 4864,
fast_attention_qkv_bias: bool = False,
fast_attention_qk_norm: bool = False,
rope_base: float = 1_000_000.0,
norm_eps: float = 1e-6,
**kwargs: Any,
) -> None:
self.hidden_size = int(fast_dim)
self.num_attention_heads = int(fast_n_head)
self.num_key_value_heads = int(fast_n_local_heads)
self.head_dim = int(fast_head_dim)
self.num_hidden_layers = int(n_fast_layer)
self.intermediate_size = int(fast_intermediate_size)
# The Fast AR sequence is [slow hidden state, code_0, ..., code_{N-1}].
self.max_position_embeddings = int(num_codebooks)
self.rms_norm_eps = float(norm_eps)
self.hidden_act = "silu"
self.attention_qkv_bias = bool(fast_attention_qkv_bias)
self.attention_qk_norm = bool(fast_attention_qk_norm)
self.rope_theta = float(rope_base)
self.num_codebooks = int(num_codebooks)
super().__init__(vocab_size=int(codebook_size), **kwargs)
class Audio8TTSConfig(PretrainedConfig):
"""Top-level Audio8 TTS config (``model_type = "arktts"``).
Accepts the flat HF checkpoint fields and derives ``text_config`` (Slow AR)
and ``fast_ar_config`` (Fast AR). ``get_text_config()`` returns the Slow AR
config, which is what ``Qwen2Model`` reads.
"""
model_type = "arktts"
sub_configs = {
"text_config": Audio8TTSSlowARConfig,
"fast_ar_config": Audio8TTSFastARConfig,
}
def __init__(
self,
text_config: dict | Audio8TTSSlowARConfig | None = None,
fast_ar_config: dict | Audio8TTSFastARConfig | None = None,
vocab_size: int = 155776,
dim: int = 896,
n_head: int = 14,
n_local_heads: int = 2,
head_dim: int = 64,
n_layer: int = 24,
intermediate_size: int = 4864,
max_seq_len: int = 2048,
rope_base: float = 1_000_000.0,
norm_eps: float = 1e-6,
attention_qkv_bias: bool = True,
attention_qk_norm: bool = False,
tie_word_embeddings: bool = True,
codebook_size: int = ARKTTS_SEMANTIC_CODEBOOK_SIZE,
num_codebooks: int = 10,
semantic_begin_id: int = 151678,
semantic_end_id: int = 155773,
n_fast_layer: int = 4,
fast_dim: int = 896,
fast_n_head: int = 14,
fast_n_local_heads: int = 2,
fast_head_dim: int = 64,
fast_intermediate_size: int = 4864,
fast_attention_qkv_bias: bool = False,
fast_attention_qk_norm: bool = False,
norm_fastlayer_input: bool = True,
codec_filename: str = "codec.pth",
codec_sample_rate: int = ARKTTS_CODEC_SAMPLE_RATE,
codec_frame_size: int = ARKTTS_CODEC_FRAME_SIZE,
codec_post_n_layer: int = 8,
codec_post_n_head: int = 16,
codec_post_n_local_heads: int = 8,
codec_post_intermediate_size: int = 1216,
ras_window_size: int = 10,
ras_temperature: float = 1.0,
ras_top_p: float = 0.9,
eos_token_id: int = 151645,
pad_token_id: int = 151643,
**kwargs: Any,
) -> None:
if isinstance(text_config, dict):
text_config = Audio8TTSSlowARConfig(**text_config)
if isinstance(fast_ar_config, dict):
fast_ar_config = Audio8TTSFastARConfig(**fast_ar_config)
self.text_config = text_config or Audio8TTSSlowARConfig(
vocab_size=vocab_size,
dim=dim,
n_head=n_head,
n_local_heads=n_local_heads,
head_dim=head_dim,
n_layer=n_layer,
intermediate_size=intermediate_size,
max_seq_len=max_seq_len,
rope_base=rope_base,
norm_eps=norm_eps,
attention_qkv_bias=attention_qkv_bias,
attention_qk_norm=attention_qk_norm,
tie_word_embeddings=tie_word_embeddings,
codebook_size=codebook_size,
num_codebooks=num_codebooks,
semantic_begin_id=semantic_begin_id,
semantic_end_id=semantic_end_id,
eos_token_id=eos_token_id,
pad_token_id=pad_token_id,
)
self.fast_ar_config = fast_ar_config or Audio8TTSFastARConfig(
codebook_size=codebook_size,
num_codebooks=num_codebooks,
fast_dim=fast_dim,
fast_n_head=fast_n_head,
fast_n_local_heads=fast_n_local_heads,
fast_head_dim=fast_head_dim,
n_fast_layer=n_fast_layer,
fast_intermediate_size=fast_intermediate_size,
fast_attention_qkv_bias=fast_attention_qkv_bias,
fast_attention_qk_norm=fast_attention_qk_norm,
rope_base=rope_base,
norm_eps=norm_eps,
)
# Fields the stages read directly off the top-level config.
self.codebook_size = int(codebook_size)
self.num_codebooks = int(num_codebooks)
self.semantic_begin_id = int(semantic_begin_id)
self.semantic_end_id = int(semantic_end_id)
self.norm_fastlayer_input = bool(norm_fastlayer_input)
self.codec_filename = str(codec_filename)
self.codec_sample_rate = int(codec_sample_rate)
self.codec_frame_size = int(codec_frame_size)
self.codec_post_n_layer = int(codec_post_n_layer)
self.codec_post_n_head = int(codec_post_n_head)
self.codec_post_n_local_heads = int(codec_post_n_local_heads)
self.codec_post_intermediate_size = int(codec_post_intermediate_size)
# Repetition-Aware Sampling (RAS): resample a repeated semantic token
# from a flatter distribution instead of masking it.
self.ras_window_size = int(ras_window_size)
self.ras_temperature = float(ras_temperature)
self.ras_top_p = float(ras_top_p)
super().__init__(
eos_token_id=int(eos_token_id),
pad_token_id=int(pad_token_id),
tie_word_embeddings=bool(tie_word_embeddings),
**kwargs,
)
def get_text_config(self, *args: Any, **kwargs: Any) -> Audio8TTSSlowARConfig:
return self.text_config
__all__ = [
"ARKTTS_CODEC_FRAME_SIZE",
"ARKTTS_CODEC_SAMPLE_RATE",
"ARKTTS_RESIDUAL_CODEBOOK_SIZE",
"ARKTTS_SEMANTIC_CODEBOOK_SIZE",
"Audio8TTSConfig",
"Audio8TTSFastARConfig",
"Audio8TTSSlowARConfig",
]
@@ -0,0 +1,50 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Audio8 TTS Preview pipeline topology.
Stage 0: ``audio8_tts_slow_ar`` -- text -> semantic tokens + codec codes.
Stage 1: ``audio8_tts_codec_decoder`` -- codec codes -> 44.1 kHz waveform.
"""
from vllm_omni.config.stage_config import (
PipelineConfig,
StageExecutionType,
StagePipelineConfig,
)
_PROC = "vllm_omni.model_executor.stage_input_processors.audio8_tts"
#: ``<|im_end|>``: the Slow AR ends the utterance with an end-of-turn token.
AUDIO8_TTS_EOS_TOKEN_ID = 151645
AUDIO8_TTS_PIPELINE = PipelineConfig(
model_type="arktts",
default_deploy_config_name="audio8_tts.yaml",
model_arch="Audio8TTSSlowARForConditionalGeneration",
stages=(
StagePipelineConfig(
stage_id=0,
model_stage="audio8_tts_slow_ar",
execution_type=StageExecutionType.LLM_AR,
input_sources=(),
owns_tokenizer=True,
engine_output_type="latent",
async_chunk_process_next_stage_input_func=(f"{_PROC}.slow_ar_to_codec_decoder_async_chunk"),
sampling_constraints={
"detokenize": False,
"stop_token_ids": [AUDIO8_TTS_EOS_TOKEN_ID],
},
),
StagePipelineConfig(
stage_id=1,
model_stage="audio8_tts_codec_decoder",
model_arch="Audio8TTSCodecDecoder",
execution_type=StageExecutionType.LLM_GENERATION,
input_sources=(0,),
final_output=True,
final_output_type="audio",
engine_output_type="audio",
sampling_constraints={"detokenize": True},
),
),
)
@@ -0,0 +1,159 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Audio8 TTS prompt construction.
Reproduces ``ArkttsProcessor._prompt_segments`` from the reference checkpoint,
so tokenisation is byte-identical to HF inference.
"""
from __future__ import annotations
from typing import Any
import regex as re
SYSTEM_PROMPT_TEXT_ONLY = "convert the provided text to speech"
SYSTEM_PROMPT_CLONE_PREFIX = "convert the provided text to speech reference to the following:\n\nText:\n"
SYSTEM_PROMPT_CLONE_SUFFIX = "\n\nSpeech:\n"
_SPEAKER_TAG_PATTERN = re.compile(r"<\|speaker:\d+\|>")
_LEGACY_SPEAKER_TAG_PATTERN = re.compile(r"<speaker:(\d+)>")
_CONTROL_TOKEN_PATTERN = re.compile(r"<\|[^>]+\|>")
def clean_text(text: str) -> str:
"""Collapse all whitespace runs to single spaces (reference ``_clean_text``)."""
return " ".join(str(text).strip().split())
def normalize_text(text: str, *, add_default_speaker: bool = False) -> str:
"""Clean text, normalise speaker tags, reject other control tokens.
``<|speaker:N|>`` is allowed; any other ``<|...|>`` token raises so callers
cannot inject ``<|semantic:...|>`` / ``<|im_end|>`` into a prompt.
"""
normalized = clean_text(_LEGACY_SPEAKER_TAG_PATTERN.sub(r"<|speaker:\1|>", text))
disallowed = [
token for token in _CONTROL_TOKEN_PATTERN.findall(normalized) if not _SPEAKER_TAG_PATTERN.fullmatch(token)
]
if disallowed:
tokens = ", ".join(sorted(set(disallowed)))
raise ValueError(f"Audio8 TTS input contains unsupported control token(s): {tokens}")
if add_default_speaker and not _SPEAKER_TAG_PATTERN.search(normalized):
normalized = f"<|speaker:0|>{normalized}"
return normalized
def _encode(tokenizer: Any, text: str) -> list[int]:
return list(tokenizer.encode(text, add_special_tokens=False))
def _encode_segments(tokenizer: Any, segments: list[str]) -> list[int]:
ids: list[int] = []
for segment in segments:
ids.extend(_encode(tokenizer, segment))
return ids
def build_text_only_prompt_ids(tokenizer: Any, text: str) -> tuple[list[int], str]:
"""Build the no-reference prompt.
Returns:
``(prompt_token_ids, normalized_text)``.
"""
normalized = normalize_text(text)
if not normalized:
raise ValueError("Audio8 TTS input text must not be empty")
ids = _encode_segments(
tokenizer,
[
"<|im_start|>system\n",
SYSTEM_PROMPT_TEXT_ONLY,
"<|im_end|>\n",
"<|im_start|>user\n",
normalized,
"<|im_end|>\n",
"<|im_start|>assistant\n<|voice|>",
],
)
return ids, normalized
def build_voice_clone_prompt_parts(
tokenizer: Any,
text: str,
ref_text: str,
) -> tuple[list[int], list[int], str, str]:
"""Build the clone prompt around the reference-code slot.
Caller splices ``[code + semantic_begin_id for code in ref_codes[:, 0]]``
between the returned prefix and suffix.
"""
normalized = normalize_text(text)
if not normalized:
raise ValueError("Audio8 TTS input text must not be empty")
normalized_ref = normalize_text(ref_text, add_default_speaker=True)
if not normalized_ref:
raise ValueError("Audio8 TTS voice cloning requires a non-empty reference transcript")
prefix = _encode_segments(
tokenizer,
[
"<|im_start|>system\n",
SYSTEM_PROMPT_CLONE_PREFIX,
normalized_ref,
SYSTEM_PROMPT_CLONE_SUFFIX,
],
)
suffix = _encode_segments(
tokenizer,
[
"<|im_end|>\n",
"<|im_start|>user\n",
normalized,
"<|im_end|>\n",
"<|im_start|>assistant\n<|voice|>",
],
)
return prefix, suffix, normalized, normalized_ref
def build_voice_clone_prompt_ids(
tokenizer: Any,
text: str,
ref_text: str,
semantic_token_ids: list[int],
) -> tuple[list[int], int, str, str]:
"""Build the full clone prompt.
``ref_start_index`` is the position of the first reference frame, i.e.
where the residual codebook embeddings must be added.
"""
prefix, suffix, normalized, normalized_ref = build_voice_clone_prompt_parts(tokenizer, text, ref_text)
return prefix + list(semantic_token_ids) + suffix, len(prefix), normalized, normalized_ref
def estimate_voice_clone_prompt_len(
tokenizer: Any,
normalized_text: str,
normalized_ref_text: str,
ref_frames: int,
) -> int:
"""Exact clone prompt length, without encoding the reference audio."""
prefix, suffix, _, _ = build_voice_clone_prompt_parts(tokenizer, normalized_text, normalized_ref_text)
return len(prefix) + max(0, int(ref_frames)) + len(suffix)
__all__ = [
"SYSTEM_PROMPT_CLONE_PREFIX",
"SYSTEM_PROMPT_CLONE_SUFFIX",
"SYSTEM_PROMPT_TEXT_ONLY",
"build_text_only_prompt_ids",
"build_voice_clone_prompt_ids",
"build_voice_clone_prompt_parts",
"clean_text",
"estimate_voice_clone_prompt_len",
"normalize_text",
]
@@ -0,0 +1,227 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Audio8 TTS sampling primitives, ported 1:1 from the reference checkpoint.
Filter (top-k/top-p on **raw** logits) -> divide surviving logits by
temperature -> Gumbel-max draw. This is the reverse of the usual filter order
and is audibly different at ``temperature != 1``, which is why this cannot
reuse ``models/common/nucleus_ras_sampling.py``. Per-row scalars are accepted
so mixed batches run in one shot without a GPU->CPU sync.
"""
from __future__ import annotations
import torch
#: Below this temperature a request is treated as greedy, matching vLLM.
SAMPLING_EPS = 1e-5
def _as_column(
value: float | int | torch.Tensor,
batch_size: int,
device: torch.device,
dtype: torch.dtype,
) -> torch.Tensor:
"""Broadcast a scalar or ``[B]`` tensor to a ``[B, 1]`` tensor."""
if isinstance(value, torch.Tensor):
return value.to(device=device, dtype=dtype).reshape(-1, 1).expand(batch_size, 1)
return torch.full((batch_size, 1), float(value), device=device, dtype=dtype)
def filter_top_k_top_p(
logits: torch.Tensor,
top_k: int | torch.Tensor,
top_p: float | torch.Tensor,
) -> torch.Tensor:
"""Mask candidates outside the top-k / top-p set of the raw logits.
``top_k <= 0`` and ``top_p >= 1`` disable each filter. The highest-scoring
candidate is always kept, so no row can become all ``-inf``.
"""
if logits.ndim != 2:
raise ValueError(f"logits must be 2-D [B, V], got {tuple(logits.shape)}")
batch_size, vocab = logits.shape
scalar_k = not isinstance(top_k, torch.Tensor)
scalar_p = not isinstance(top_p, torch.Tensor)
if scalar_k and scalar_p and (int(top_k) <= 0 or int(top_k) >= vocab) and float(top_p) >= 1.0:
return logits
sorted_scores, sorted_indices = torch.sort(logits, descending=True, dim=-1)
cumulative = torch.cumsum(torch.softmax(sorted_scores, dim=-1), dim=-1)
positions = torch.arange(vocab, device=logits.device).unsqueeze(0)
keep_k = _as_column(top_k, batch_size, logits.device, torch.long)
# top_k <= 0 means "no cut"; represent it as the full vocabulary.
keep_k = torch.where(keep_k <= 0, torch.full_like(keep_k, vocab), keep_k)
threshold_p = _as_column(top_p, batch_size, logits.device, cumulative.dtype)
remove_sorted = (cumulative > threshold_p) | (positions >= keep_k)
# Always keep the argmax so at least one candidate survives.
remove_sorted[:, 0] = False
remove = torch.zeros_like(remove_sorted).scatter(-1, sorted_indices, remove_sorted)
return logits.masked_fill(remove, float("-inf"))
def gumbel_argmax_sample(
scores: torch.Tensor,
generator: torch.Generator | None = None,
) -> torch.Tensor:
"""Draw one index per row via Gumbel-max over ``softmax(scores)``."""
probabilities = torch.softmax(scores, dim=-1)
uniform = torch.rand(
probabilities.shape,
dtype=probabilities.dtype,
device=probabilities.device,
generator=generator,
)
# -log(u) is Exp(1); argmax(p / Exp(1)) samples from p.
noise = -torch.log(uniform.clamp_min(torch.finfo(probabilities.dtype).tiny))
return torch.argmax(probabilities / noise, dim=-1)
def sample_scores(
logits: torch.Tensor,
*,
temperature: float | torch.Tensor,
top_k: int | torch.Tensor,
top_p: float | torch.Tensor,
do_sample: bool = True,
generator: torch.Generator | None = None,
) -> torch.Tensor:
"""Filter -> temper -> draw, in the reference order.
Rows whose temperature is below :data:`SAMPLING_EPS` fall back to argmax.
"""
filtered = filter_top_k_top_p(logits, top_k, top_p)
greedy = filtered.argmax(dim=-1)
if not do_sample:
return greedy
if not isinstance(temperature, torch.Tensor):
if float(temperature) < SAMPLING_EPS:
return greedy
return gumbel_argmax_sample(filtered / float(temperature), generator=generator)
temperature_col = _as_column(temperature, filtered.shape[0], filtered.device, filtered.dtype)
safe_temperature = torch.where(
temperature_col < SAMPLING_EPS,
torch.ones_like(temperature_col),
temperature_col,
)
sampled = gumbel_argmax_sample(filtered / safe_temperature, generator=generator)
return torch.where(temperature_col.reshape(-1) < SAMPLING_EPS, greedy, sampled)
def ras_sample_semantic(
logits: torch.Tensor,
recent_ids: torch.Tensor | None,
*,
temperature: float | torch.Tensor,
top_k: int | torch.Tensor,
top_p: float | torch.Tensor,
ras_temperature: float,
ras_top_p: float,
do_sample: bool = True,
num_semantic_ids: int | None = None,
generator: torch.Generator | None = None,
) -> torch.Tensor:
"""Repetition-Aware Sampling for the semantic (Slow AR) token.
Draws with the request's ``temperature`` / ``top_p``; if the drawn id is
already in ``recent_ids`` (pad with a value that cannot be sampled, e.g.
``-1``), redraws from the flatter RAS distribution instead. The
``num_semantic_ids`` slot and beyond (EOS) are never substituted, so a
repeat EOS still ends the utterance.
DualAR RAS *resamples* repeats rather than masking them — masking the
dominant token inflates EOS probability and truncates the utterance.
"""
normal = sample_scores(
logits,
temperature=temperature,
top_k=top_k,
top_p=top_p,
do_sample=do_sample,
generator=generator,
)
if not do_sample or recent_ids is None or recent_ids.numel() == 0:
return normal
high = sample_scores(
logits,
temperature=ras_temperature,
top_k=top_k,
top_p=ras_top_p,
do_sample=True,
generator=generator,
)
repeated = (recent_ids == normal[:, None]).any(dim=1)
if num_semantic_ids is not None:
repeated &= normal < int(num_semantic_ids)
return torch.where(repeated, high, normal)
def _row_value(value: object, index: int) -> object:
"""Slice a per-row value for request ``index``; scalars pass through."""
return value[index : index + 1] if isinstance(value, torch.Tensor) else value
def ras_sample_batch(
logits: torch.Tensor,
recent_ids: torch.Tensor | None,
*,
temperature: float | torch.Tensor,
top_k: int | torch.Tensor,
top_p: float | torch.Tensor,
ras_temperature: float,
ras_top_p: float,
num_semantic_ids: int | None,
generators: dict,
num_reqs: int,
) -> torch.Tensor:
"""Batched RAS that honors each request's own RNG generator.
vLLM keys ``generators`` by batch slot, so a single shared generator would
leak slot 0's RNG stream to every row and make a prompt's audio depend on
its batch neighbours (undercutting per-request ``seed``). The single-request
case keeps the batched fast path; larger batches loop so each row draws from
its own (possibly unseeded) generator.
"""
common = dict(
ras_temperature=ras_temperature,
ras_top_p=ras_top_p,
num_semantic_ids=num_semantic_ids,
)
if num_reqs == 1:
return ras_sample_semantic(
logits,
recent_ids,
temperature=temperature,
top_k=top_k,
top_p=top_p,
generator=generators.get(0),
**common,
)
rows = [
ras_sample_semantic(
logits[i : i + 1],
None if recent_ids is None else recent_ids[i : i + 1],
temperature=_row_value(temperature, i),
top_k=_row_value(top_k, i),
top_p=_row_value(top_p, i),
generator=generators.get(i),
**common,
)
for i in range(num_reqs)
]
return torch.cat(rows, dim=0)
__all__ = [
"SAMPLING_EPS",
"filter_top_k_top_p",
"gumbel_argmax_sample",
"ras_sample_batch",
"ras_sample_semantic",
"sample_scores",
]
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from collections.abc import Iterable, Mapping, Sequence
from math import isqrt
from typing import Any
@@ -122,9 +125,9 @@ class OmniBagelProcessingInfo(BaseProcessingInfo):
if p.is_dir():
index_path = p / "model.safetensors.index.json"
else:
from huggingface_hub import hf_hub_download
from vllm_omni.transformers_utils.repo_utils import hf_api
index_path = Path(hf_hub_download(model_name, "model.safetensors.index.json"))
index_path = Path(hf_api().hf_hub_download(model_name, "model.safetensors.index.json"))
if not index_path.exists():
return
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Qwen3 Code Predictor -- optimized re-prefill, no KV cache.
Shared by Qwen3-Omni and Qwen3-TTS talker models.
@@ -97,7 +100,11 @@ class _RotaryEmbedding(CustomOp):
"head_dim",
config.hidden_size // config.num_attention_heads,
)
rope_theta = getattr(config, "rope_theta", 10000.0)
rope_parameters = getattr(config, "rope_parameters", None) or {}
rope_theta = rope_parameters.get(
"rope_theta",
getattr(config, "rope_theta", 10000.0),
)
inv_freq = 1.0 / (rope_theta ** (torch.arange(0, head_dim, 2, dtype=torch.float32) / head_dim))
self.register_buffer("inv_freq", inv_freq, persistent=False)
@@ -10,7 +10,6 @@ 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
@@ -52,6 +51,7 @@ from vllm_omni.model_executor.models.cosyvoice3.utils import (
from vllm_omni.model_executor.models.output_templates import OmniOutput
from vllm_omni.platforms import current_omni_platform
from vllm_omni.transformers_utils.configs.cosyvoice3 import CosyVoice3Config
from vllm_omni.transformers_utils.repo_utils import hf_api
from vllm_omni.utils.speaker_cache import get_speaker_cache
logger = init_logger(__name__)
@@ -137,7 +137,7 @@ class CosyVoice3MultiModalProcessor(BaseMultiModalProcessor[CosyVoice3MultiModal
"""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)
model_dir = hf_api().snapshot_download(model_dir)
tokenizer = get_qwen_tokenizer(
token_path=os.path.join(model_dir, config.qwen_pretrain_path),
@@ -463,7 +463,7 @@ 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):
model_dir = snapshot_download(model_dir)
model_dir = hf_api().snapshot_download(model_dir)
self.model_dir = model_dir
self.model = None
if self.model_stage == "cosyvoice3_talker":
@@ -918,7 +918,7 @@ class CosyVoice3Model(
repo = getattr(self.config, "flow_estimator_onnx_repo", None)
if repo:
try:
fetched_dir = snapshot_download(repo, allow_patterns=[fp16_name])
fetched_dir = hf_api().snapshot_download(repo, allow_patterns=[fp16_name])
fetched = os.path.join(fetched_dir, fp16_name)
if os.path.exists(fetched):
return fetched
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
# Copyright 2026 Tencent.
import os
from collections.abc import Iterable
@@ -25,9 +28,9 @@ class CovoAudioCode2WavForConditionalGeneration(nn.Module, SupportsPP):
if os.path.isdir(model_name):
model_path = model_name
else:
from huggingface_hub import snapshot_download
from vllm_omni.transformers_utils.repo_utils import hf_api
model_path = snapshot_download(model_name)
model_path = hf_api().snapshot_download(model_name)
token2wav_path = os.path.join(model_path, "token2wav")
code2wav_config = CovoAudioCode2WavConfig()
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""dots.tts talker — vLLM-native AR base LM + audio side path.
Mirrors upstream rednote-hilab/dots.tts (pinned @ a393d2e):
@@ -516,9 +516,9 @@ class DotsTTSForConditionalGeneration(nn.Module):
if os.path.exists(local):
return local
try:
from huggingface_hub import hf_hub_download
from vllm_omni.transformers_utils.repo_utils import hf_api
return hf_hub_download(
return hf_api().hf_hub_download(
repo_id=model_arg,
filename="latent_stats.pt",
local_files_only=True,
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
import hashlib
@@ -20,9 +23,9 @@ from vllm.logger import init_logger
logger = init_logger(__name__)
try:
from huggingface_hub import snapshot_download
from vllm_omni.transformers_utils.repo_utils import hf_api
except Exception: # pragma: no cover
snapshot_download = None
hf_api = None
class DetokTarget(IntEnum):
@@ -397,13 +400,13 @@ def _find_dynin_config_under_root(root: Path) -> Path | None:
@lru_cache(maxsize=16)
def _resolve_dynin_config_from_hf_repo(repo_id: str) -> str | None:
if not _looks_like_hf_repo_id(repo_id) or snapshot_download is None:
if not _looks_like_hf_repo_id(repo_id) or hf_api is None:
return None
try:
snapshot_dir = (
Path(
snapshot_download(
hf_api().snapshot_download(
repo_id=repo_id,
repo_type="model",
allow_patterns=list(_DYNIN_CONFIG_CANDIDATE_RELPATHS),
@@ -719,7 +722,7 @@ def _resolve_remote_snapshot_dir(
if source_path.is_dir():
return str(source_path.resolve())
if snapshot_download is None:
if hf_api is None:
raise RuntimeError("huggingface_hub is required to load remote code.")
kwargs: dict[str, Any] = {
@@ -732,10 +735,10 @@ def _resolve_remote_snapshot_dir(
kwargs["revision"] = revision
try:
return str(snapshot_download(**kwargs))
return str(hf_api().snapshot_download(**kwargs))
except TypeError:
kwargs.pop("local_files_only", None)
return str(snapshot_download(**kwargs))
return str(hf_api().snapshot_download(**kwargs))
def _ensure_remote_package(snapshot_dir: str) -> str:
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
import os
@@ -80,7 +83,7 @@ def _ensure_remote_s2u_vendor_root(
return str(existing_path)
try:
from huggingface_hub import snapshot_download
from vllm_omni.transformers_utils.repo_utils import hf_api
except Exception as e:
logger.warning("huggingface_hub unavailable; cannot fetch s2u_vendor from %s: %s", repo_id, e)
return None
@@ -91,7 +94,7 @@ def _ensure_remote_s2u_vendor_root(
for revision in revisions:
try:
snapshot_dir = snapshot_download(
snapshot_dir = hf_api().snapshot_download(
repo_id=repo_id,
revision=revision,
allow_patterns=["s2u_vendor/**"],
@@ -99,7 +102,7 @@ def _ensure_remote_s2u_vendor_root(
)
except TypeError:
try:
snapshot_dir = snapshot_download(
snapshot_dir = hf_api().snapshot_download(
repo_id=repo_id,
revision=revision,
allow_patterns=["s2u_vendor/**"],
@@ -0,0 +1,27 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Vendored DAC codec modules for Fish Speech S2 Pro.
Adopted from the ``fish-speech`` 0.1.0 PyPI release
(https://pypi.org/project/fish-speech/0.1.0/, Apache-2.0) and
descript-audio-codec (https://github.com/descriptinc/descript-audio-codec,
MIT), trimmed to inference-only so the codec loads without external model
packages. Module attribute paths and weight-norm styles are kept identical
to upstream so ``codec.pth`` checkpoints load unchanged.
"""
from vllm_omni.model_executor.models.fish_speech.dac_modules.codec import DAC
from vllm_omni.model_executor.models.fish_speech.dac_modules.rvq import (
DownsampleResidualVectorQuantize,
)
from vllm_omni.model_executor.models.fish_speech.dac_modules.transformer import (
ModelArgs,
WindowLimitedTransformer,
)
__all__ = [
"DAC",
"DownsampleResidualVectorQuantize",
"ModelArgs",
"WindowLimitedTransformer",
]
@@ -0,0 +1,335 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Adopted from the fish-speech 0.1.0 PyPI release (Apache-2.0)
# https://pypi.org/project/fish-speech/0.1.0/
# Copyright (c) Fish Audio
"""DAC codec model (encoder / quantizer / decoder).
Differences from upstream ``fish_speech.models.dac.modded_dac.DAC``, none of
which affect the parameter tree or the inference math:
- Base class is plain ``nn.Module`` instead of ``(audiotools BaseModel,
descript CodecMixin)`` -- both bases only add training/CLI conveniences.
- ``self.delay = self.get_delay()`` (a CodecMixin helper) is dropped; nothing
in the inference paths reads it.
- The training-only ``forward``/``preprocess`` methods are dropped; only
``encode`` and ``decode`` are used at inference time.
"""
import math
import torch
from torch import nn
from vllm_omni.model_executor.models.fish_speech.dac_modules.conv import (
CausalWNConv1d,
CausalWNConvTranspose1d,
)
from vllm_omni.model_executor.models.fish_speech.dac_modules.layers import (
Snake1d,
WNConv1d,
WNConvTranspose1d,
)
from vllm_omni.model_executor.models.fish_speech.dac_modules.transformer import (
ModelArgs,
WindowLimitedTransformer,
)
def init_weights(m):
if isinstance(m, nn.Conv1d):
nn.init.trunc_normal_(m.weight, std=0.02)
nn.init.constant_(m.bias, 0)
class ResidualUnit(nn.Module):
def __init__(self, dim: int = 16, dilation: int = 1, causal: bool = False):
super().__init__()
conv_class = CausalWNConv1d if causal else WNConv1d
pad = ((7 - 1) * dilation) // 2
self.block = nn.Sequential(
Snake1d(dim),
conv_class(dim, dim, kernel_size=7, dilation=dilation, padding=pad),
Snake1d(dim),
conv_class(dim, dim, kernel_size=1),
)
self.causal = causal
def forward(self, x):
y = self.block(x)
pad = x.shape[-1] - y.shape[-1]
if pad > 0:
if self.causal:
x = x[..., :-pad]
else:
x = x[..., pad // 2 : -pad // 2]
return x + y
class EncoderBlock(nn.Module):
def __init__(
self,
dim: int = 16,
stride: int = 1,
causal: bool = False,
n_t_layer: int = 0,
transformer_general_config=None,
):
super().__init__()
conv_class = CausalWNConv1d if causal else WNConv1d
transformer_module = (
nn.Identity()
if n_t_layer == 0
else (
WindowLimitedTransformer(
causal=causal,
input_dim=dim,
window_size=512,
config=transformer_general_config(
n_layer=n_t_layer,
n_head=dim // 64,
dim=dim,
intermediate_size=dim * 3,
),
)
)
)
self.block = nn.Sequential(
ResidualUnit(dim // 2, dilation=1, causal=causal),
ResidualUnit(dim // 2, dilation=3, causal=causal),
ResidualUnit(dim // 2, dilation=9, causal=causal),
Snake1d(dim // 2),
conv_class(
dim // 2,
dim,
kernel_size=2 * stride,
stride=stride,
padding=math.ceil(stride / 2),
),
transformer_module,
)
def forward(self, x):
return self.block(x)
class Encoder(nn.Module):
def __init__(
self,
d_model: int = 64,
strides: list = [2, 4, 8, 8],
d_latent: int = 64,
n_transformer_layers: list = [0, 0, 4, 4],
transformer_general_config: ModelArgs = None,
causal: bool = False,
):
super().__init__()
conv_class = CausalWNConv1d if causal else WNConv1d
# Create first convolution
self.block = [conv_class(1, d_model, kernel_size=7, padding=3)]
# Create EncoderBlocks that double channels as they downsample by `stride`
for stride, n_t_layer in zip(strides, n_transformer_layers):
d_model *= 2
self.block += [
EncoderBlock(
d_model,
stride=stride,
causal=causal,
n_t_layer=n_t_layer,
transformer_general_config=transformer_general_config,
)
]
# Create last convolution
self.block += [
Snake1d(d_model),
conv_class(d_model, d_latent, kernel_size=3, padding=1),
]
# Wrap black into nn.Sequential
self.block = nn.Sequential(*self.block)
self.enc_dim = d_model
def forward(self, x):
return self.block(x)
class DecoderBlock(nn.Module):
def __init__(
self,
input_dim: int = 16,
output_dim: int = 8,
stride: int = 1,
causal: bool = False,
n_t_layer: int = 0,
transformer_general_config=None,
):
super().__init__()
conv_trans_class = CausalWNConvTranspose1d if causal else WNConvTranspose1d
# NOTE: upstream constructs a WindowLimitedTransformer from
# ``n_t_layer`` here but never registers it (the line placing it in
# ``self.block`` is commented out upstream), so decoder blocks carry no
# transformer parameters. It is not built here at all -- same module
# tree, without allocating throwaway weights.
del n_t_layer, transformer_general_config
self.block = nn.Sequential(
Snake1d(input_dim),
conv_trans_class(
input_dim,
output_dim,
kernel_size=2 * stride,
stride=stride,
padding=math.ceil(stride / 2),
),
ResidualUnit(output_dim, dilation=1, causal=causal),
ResidualUnit(output_dim, dilation=3, causal=causal),
ResidualUnit(output_dim, dilation=9, causal=causal),
)
def forward(self, x):
return self.block(x)
class Decoder(nn.Module):
def __init__(
self,
input_channel,
channels,
rates,
d_out: int = 1,
causal: bool = False,
n_transformer_layers: list = [0, 0, 0, 0],
transformer_general_config=None,
):
super().__init__()
conv_class = CausalWNConv1d if causal else WNConv1d
# Add first conv layer
layers = [conv_class(input_channel, channels, kernel_size=7, padding=3)]
# Add upsampling + MRF blocks
for i, (stride, n_t_layer) in enumerate(zip(rates, n_transformer_layers)):
input_dim = channels // 2**i
output_dim = channels // 2 ** (i + 1)
layers += [
DecoderBlock(
input_dim,
output_dim,
stride,
causal=causal,
n_t_layer=n_t_layer,
transformer_general_config=transformer_general_config,
)
]
# Add final conv layer
layers += [
Snake1d(output_dim),
conv_class(output_dim, d_out, kernel_size=7, padding=3),
nn.Tanh(),
]
self.model = nn.Sequential(*layers)
def forward(self, x):
return self.model(x)
class DAC(nn.Module):
def __init__(
self,
encoder_dim: int = 64,
encoder_rates: list[int] = [2, 4, 8, 8],
latent_dim: int = None,
decoder_dim: int = 1536,
decoder_rates: list[int] = [8, 8, 4, 2],
quantizer: torch.nn.Module = None,
sample_rate: int = 44100,
causal: bool = True,
encoder_transformer_layers: list[int] = [0, 0, 0, 0],
decoder_transformer_layers: list[int] = [0, 0, 0, 0],
transformer_general_config=None,
):
super().__init__()
self.encoder_dim = encoder_dim
self.encoder_rates = encoder_rates
self.decoder_dim = decoder_dim
self.decoder_rates = decoder_rates
self.sample_rate = sample_rate
if latent_dim is None:
latent_dim = encoder_dim * (2 ** len(encoder_rates))
self.latent_dim = latent_dim
self.hop_length = int(math.prod(encoder_rates))
self.encoder = Encoder(
encoder_dim,
encoder_rates,
latent_dim,
causal=causal,
n_transformer_layers=encoder_transformer_layers,
transformer_general_config=transformer_general_config,
)
self.quantizer = quantizer
self.decoder = Decoder(
latent_dim,
decoder_dim,
decoder_rates,
causal=causal,
n_transformer_layers=decoder_transformer_layers,
transformer_general_config=transformer_general_config,
)
self.sample_rate = sample_rate
self.apply(init_weights)
self.frame_length = self.hop_length * 4
def encode(
self,
audio_data: torch.Tensor,
audio_lengths: torch.Tensor = None,
n_quantizers: int = None,
**kwargs,
):
"""Encode given audio data and return quantized latent codes.
Parameters
----------
audio_data : Tensor[B x 1 x T]
Audio data to encode
audio_lengths : Tensor[B], optional
Valid sample counts per batch entry
n_quantizers : int, optional
Number of quantizers to use, by default None (all quantizers)
Returns
-------
Tuple of (codes Tensor[B x N x F], code lengths Tensor[B]).
"""
# pad to multiple of self.frame_length
if audio_data.ndim == 2:
audio_data = audio_data.unsqueeze(1)
length = audio_data.shape[-1]
right_pad = math.ceil(length / self.frame_length) * self.frame_length - length
audio_data = nn.functional.pad(audio_data, (0, right_pad))
if audio_lengths is None:
audio_lengths = torch.LongTensor([length + right_pad]).to(audio_data.device)
z = self.encoder(audio_data)
vq_results = self.quantizer(z, n_quantizers, **kwargs)
indices = vq_results.codes
indices_lens = torch.ceil(audio_lengths / self.frame_length).long()
return indices, indices_lens
def decode(self, indices: torch.Tensor, feature_lengths):
"""Decode codebook indices [B x N x F] to waveform [B x 1 x T]."""
if indices.ndim == 2:
indices = indices[None]
z = self.quantizer.decode(indices)
audio_lengths = feature_lengths * self.frame_length
return self.decoder(z), audio_lengths
@@ -0,0 +1,194 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Adopted from the fish-speech 0.1.0 PyPI release (Apache-2.0)
# https://pypi.org/project/fish-speech/0.1.0/
# Copyright (c) Fish Audio
"""Causal convolution primitives shared by the DAC encoder/decoder and the
downsample RVQ. Upstream duplicates these between ``modded_dac.py`` and
``rvq.py``; they are consolidated here (the copies are identical)."""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils.parametrizations import weight_norm
from torch.nn.utils.parametrize import remove_parametrizations
def unpad1d(x: torch.Tensor, paddings: tuple[int, int]):
"""Remove padding from x, handling properly zero padding. Only for 1d!"""
padding_left, padding_right = paddings
assert padding_left >= 0 and padding_right >= 0, (padding_left, padding_right)
assert (padding_left + padding_right) <= x.shape[-1]
end = x.shape[-1] - padding_right
return x[..., padding_left:end]
def get_extra_padding_for_conv1d(x: torch.Tensor, kernel_size: int, stride: int, padding_total: int = 0) -> int:
"""See `pad_for_conv1d`."""
length = x.shape[-1]
n_frames = (length - kernel_size + padding_total) / stride + 1
ideal_length = (math.ceil(n_frames) - 1) * stride + (kernel_size - padding_total)
return ideal_length - length
def pad1d(
x: torch.Tensor,
paddings: tuple[int, int],
mode: str = "zeros",
value: float = 0.0,
):
"""Tiny wrapper around F.pad, just to allow for reflect padding on small input.
If this is the case, we insert extra 0 padding to the right
before the reflection happen.
"""
length = x.shape[-1]
padding_left, padding_right = paddings
assert padding_left >= 0 and padding_right >= 0, (padding_left, padding_right)
if mode == "reflect":
max_pad = max(padding_left, padding_right)
extra_pad = 0
if length <= max_pad:
extra_pad = max_pad - length + 1
x = F.pad(x, (0, extra_pad))
padded = F.pad(x, paddings, mode, value)
end = padded.shape[-1] - extra_pad
return padded[..., :end]
else:
return F.pad(x, paddings, mode, value)
class CausalConvNet(nn.Module):
def __init__(
self,
in_channels,
out_channels,
kernel_size,
dilation=1,
stride=1,
groups=1,
padding=None,
):
super().__init__()
self.conv = nn.Conv1d(
in_channels,
out_channels,
kernel_size,
stride=stride,
dilation=dilation,
groups=groups,
)
self.stride = stride
self.kernel_size = (kernel_size - 1) * dilation + 1
self.dilation = dilation
self.padding = self.kernel_size - self.stride
def forward(self, x):
pad = self.padding
extra_padding = get_extra_padding_for_conv1d(x, self.kernel_size, self.stride, pad)
x = pad1d(x, (pad, extra_padding), mode="constant", value=0)
return self.conv(x).contiguous()
def weight_norm(self, name="weight", dim=0):
self.conv = weight_norm(self.conv, name=name, dim=dim)
return self
def remove_weight_norm(self):
self.conv = remove_parametrizations(self.conv)
return self
class CausalTransConvNet(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, dilation=1, stride=1, padding=None):
super().__init__()
self.conv = nn.ConvTranspose1d(in_channels, out_channels, kernel_size, stride=stride, dilation=dilation)
self.stride = stride
self.kernel_size = kernel_size
def forward(self, x):
x = self.conv(x)
pad = self.kernel_size - self.stride
padding_right = math.ceil(pad)
padding_left = pad - padding_right
x = unpad1d(x, (padding_left, padding_right))
return x.contiguous()
def weight_norm(self, name="weight", dim=0):
self.conv = weight_norm(self.conv, name=name, dim=dim)
return self
def remove_weight_norm(self):
self.conv = remove_parametrizations(self.conv)
return self
def CausalWNConv1d(*args, **kwargs):
return CausalConvNet(*args, **kwargs).weight_norm()
def CausalWNConvTranspose1d(*args, **kwargs):
return CausalTransConvNet(*args, **kwargs).weight_norm()
class ConvNeXtBlock(nn.Module):
r"""ConvNeXt Block. There are two equivalent implementations:
(1) DwConv -> LayerNorm (channels_first) -> 1x1 Conv -> GELU -> 1x1 Conv; all in (N, C, H, W)
(2) DwConv -> Permute to (N, H, W, C); LayerNorm (channels_last) -> Linear -> GELU -> Linear; Permute back
We use (2) as we find it slightly faster in PyTorch
Args:
dim (int): Number of input channels.
layer_scale_init_value (float): Init value for Layer Scale. Default: 1e-6.
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.0.
kernel_size (int): Kernel size for depthwise conv. Default: 7.
dilation (int): Dilation for depthwise conv. Default: 1.
""" # noqa: E501
def __init__(
self,
dim: int,
layer_scale_init_value: float = 1e-6,
mlp_ratio: float = 4.0,
kernel_size: int = 7,
dilation: int = 1,
):
super().__init__()
convnet_type = CausalConvNet
self.dwconv = convnet_type(
dim,
dim,
kernel_size=kernel_size,
groups=dim,
dilation=dilation,
) # depthwise conv
self.norm = nn.LayerNorm(dim, eps=1e-6)
# pointwise/1x1 convs, implemented with linear layers
self.pwconv1 = nn.Linear(dim, int(mlp_ratio * dim))
self.act = nn.GELU()
self.pwconv2 = nn.Linear(int(mlp_ratio * dim), dim)
self.gamma = (
nn.Parameter(layer_scale_init_value * torch.ones(dim), requires_grad=True)
if layer_scale_init_value > 0
else None
)
def forward(self, x, apply_residual: bool = True):
input = x
x = self.dwconv(x)
x = x.permute(0, 2, 1) # (N, C, L) -> (N, L, C)
x = self.norm(x)
x = self.pwconv1(x)
x = self.act(x)
x = self.pwconv2(x)
if self.gamma is not None:
x = self.gamma * x
x = x.permute(0, 2, 1) # (N, L, C) -> (N, C, L)
if apply_residual:
x = input + x
return x
@@ -0,0 +1,238 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Adopted from https://github.com/descriptinc/descript-audio-codec (MIT License)
# Copyright (c) 2023-present, Descript
"""Descript audio codec building blocks (Snake activation, weight-normed convs,
vector quantizers).
Uses the legacy ``torch.nn.utils.weight_norm`` (``weight_g``/``weight_v`` keys)
exactly like upstream so quantizer projection weights in ``codec.pth`` load
unchanged. The ``einops.rearrange`` calls are replaced with equivalent
reshape/permute ops; ``from_latents`` (training-only) is dropped.
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils import weight_norm
def WNConv1d(*args, **kwargs):
return weight_norm(nn.Conv1d(*args, **kwargs))
def WNConvTranspose1d(*args, **kwargs):
return weight_norm(nn.ConvTranspose1d(*args, **kwargs))
# Scripting this brings model speed up 1.4x
@torch.jit.script
def snake(x, alpha):
shape = x.shape
x = x.reshape(shape[0], shape[1], -1)
x = x + (alpha + 1e-9).reciprocal() * torch.sin(alpha * x).pow(2)
x = x.reshape(shape)
return x
class Snake1d(nn.Module):
def __init__(self, channels):
super().__init__()
self.alpha = nn.Parameter(torch.ones(1, channels, 1))
def forward(self, x):
return snake(x, self.alpha)
class VectorQuantize(nn.Module):
"""
Implementation of VQ similar to Karpathy's repo:
https://github.com/karpathy/deep-vector-quantization
Additionally uses following tricks from Improved VQGAN
(https://arxiv.org/pdf/2110.04627.pdf):
1. Factorized codes: Perform nearest neighbor lookup in low-dimensional space
for improved codebook usage
2. l2-normalized codes: Converts euclidean distance to cosine similarity which
improves training stability
"""
def __init__(self, input_dim: int, codebook_size: int, codebook_dim: int):
super().__init__()
self.codebook_size = codebook_size
self.codebook_dim = codebook_dim
self.in_proj = WNConv1d(input_dim, codebook_dim, kernel_size=1)
self.out_proj = WNConv1d(codebook_dim, input_dim, kernel_size=1)
self.codebook = nn.Embedding(codebook_size, codebook_dim)
def forward(self, z):
"""Quantized the input tensor using a fixed codebook and returns
the corresponding codebook vectors
Parameters
----------
z : Tensor[B x D x T]
Returns
-------
Tensor[B x D x T]
Quantized continuous representation of input
Tensor[1]
Commitment loss to train encoder to predict vectors closer to codebook
entries
Tensor[1]
Codebook loss to update the codebook
Tensor[B x T]
Codebook indices (quantized discrete representation of input)
Tensor[B x D x T]
Projected latents (continuous representation of input before quantization)
"""
# Factorized codes (ViT-VQGAN) Project input into low-dimensional space
z_e = self.in_proj(z) # z_e : (B x D x T)
z_q, indices = self.decode_latents(z_e)
commitment_loss = F.mse_loss(z_e, z_q.detach(), reduction="none").mean([1, 2])
codebook_loss = F.mse_loss(z_q, z_e.detach(), reduction="none").mean([1, 2])
z_q = z_e + (z_q - z_e).detach() # noop in forward pass, straight-through gradient estimator in backward pass
z_q = self.out_proj(z_q)
return z_q, commitment_loss, codebook_loss, indices, z_e
def embed_code(self, embed_id):
return F.embedding(embed_id, self.codebook.weight)
def decode_code(self, embed_id):
return self.embed_code(embed_id).transpose(1, 2)
def decode_latents(self, latents):
batch, dim, time = latents.shape
# rearrange "b d t -> (b t) d"
encodings = latents.permute(0, 2, 1).reshape(batch * time, dim)
codebook = self.codebook.weight # codebook: (N x D)
# L2 normalize encodings and codebook (ViT-VQGAN)
encodings = F.normalize(encodings)
codebook = F.normalize(codebook)
# Compute euclidean distance with codebook
dist = (
encodings.pow(2).sum(1, keepdim=True)
- 2 * encodings @ codebook.t()
+ codebook.pow(2).sum(1, keepdim=True).t()
)
# rearrange "(b t) -> b t"
indices = (-dist).max(1)[1].reshape(batch, time)
z_q = self.decode_code(indices)
return z_q, indices
class ResidualVectorQuantize(nn.Module):
"""
Introduced in SoundStream: An end2end neural audio codec
https://arxiv.org/abs/2107.03312
"""
def __init__(
self,
input_dim: int = 512,
n_codebooks: int = 9,
codebook_size: int = 1024,
codebook_dim: int | list = 8,
quantizer_dropout: float = 0.0,
):
super().__init__()
if isinstance(codebook_dim, int):
codebook_dim = [codebook_dim for _ in range(n_codebooks)]
self.n_codebooks = n_codebooks
self.codebook_dim = codebook_dim
self.codebook_size = codebook_size
self.quantizers = nn.ModuleList(
[VectorQuantize(input_dim, codebook_size, codebook_dim[i]) for i in range(n_codebooks)]
)
self.quantizer_dropout = quantizer_dropout
def forward(self, z, n_quantizers: int = None):
"""Quantized the input tensor using a fixed set of `n` codebooks and returns
the corresponding codebook vectors
Parameters
----------
z : Tensor[B x D x T]
n_quantizers : int, optional
No. of quantizers to use
(n_quantizers < self.n_codebooks ex: for quantizer dropout)
Note: if `self.quantizer_dropout` is True, this argument is ignored
when in training mode, and a random number of quantizers is used.
Returns
-------
Tuple of (z_q, codes, latents, commitment_loss, codebook_loss).
"""
z_q = 0
residual = z
commitment_loss = 0
codebook_loss = 0
codebook_indices = []
latents = []
if n_quantizers is None:
n_quantizers = self.n_codebooks
if self.training:
n_quantizers = torch.ones((z.shape[0],)) * self.n_codebooks + 1
dropout = torch.randint(1, self.n_codebooks + 1, (z.shape[0],))
n_dropout = int(z.shape[0] * self.quantizer_dropout)
n_quantizers[:n_dropout] = dropout[:n_dropout]
n_quantizers = n_quantizers.to(z.device)
for i, quantizer in enumerate(self.quantizers):
if self.training is False and i >= n_quantizers:
break
z_q_i, commitment_loss_i, codebook_loss_i, indices_i, z_e_i = quantizer(residual)
# Create mask to apply quantizer dropout
mask = torch.full((z.shape[0],), fill_value=i, device=z.device) < n_quantizers
z_q = z_q + z_q_i * mask[:, None, None]
residual = residual - z_q_i
# Sum losses
commitment_loss += (commitment_loss_i * mask).mean()
codebook_loss += (codebook_loss_i * mask).mean()
codebook_indices.append(indices_i)
latents.append(z_e_i)
codes = torch.stack(codebook_indices, dim=1)
latents = torch.cat(latents, dim=1)
return z_q, codes, latents, commitment_loss, codebook_loss
def from_codes(self, codes: torch.Tensor):
"""Given the quantized codes, reconstruct the continuous representation
Parameters
----------
codes : Tensor[B x N x T]
Quantized discrete representation of input
Returns
-------
Tensor[B x D x T]
Quantized continuous representation of input
"""
z_q = 0.0
z_p = []
n_codebooks = codes.shape[1]
for i in range(n_codebooks):
z_p_i = self.quantizers[i].decode_code(codes[:, i, :])
z_p.append(z_p_i)
z_q_i = self.quantizers[i].out_proj(z_p_i)
z_q = z_q + z_q_i
return z_q, torch.cat(z_p, dim=1), codes
@@ -0,0 +1,177 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Adopted from the fish-speech 0.1.0 PyPI release (Apache-2.0)
# https://pypi.org/project/fish-speech/0.1.0/
# Copyright (c) Fish Audio
"""Downsampled residual vector quantizer (1 semantic + N residual codebooks)."""
from dataclasses import dataclass
import torch
import torch.nn as nn
import torch.nn.functional as F
from vllm_omni.model_executor.models.fish_speech.dac_modules.conv import (
CausalConvNet,
CausalTransConvNet,
ConvNeXtBlock,
)
from vllm_omni.model_executor.models.fish_speech.dac_modules.layers import (
ResidualVectorQuantize,
)
@dataclass
class VQResult:
z: torch.Tensor
codes: torch.Tensor
latents: torch.Tensor
codebook_loss: torch.Tensor
commitment_loss: torch.Tensor
semantic_distill_z: torch.Tensor | None = None
class DownsampleResidualVectorQuantize(nn.Module):
def __init__(
self,
input_dim: int = 1024,
n_codebooks: int = 9,
codebook_dim: int = 8,
quantizer_dropout: float = 0.5,
codebook_size: int = 1024,
semantic_codebook_size: int = 4096,
downsample_factor: tuple[int] = (2, 2),
downsample_dims: tuple[int] | None = None,
pre_module: nn.Module | None = None,
post_module: nn.Module | None = None,
semantic_predictor_module: nn.Module | None = None,
):
super().__init__()
if downsample_dims is None:
downsample_dims = [input_dim for _ in range(len(downsample_factor))]
all_dims = (input_dim,) + tuple(downsample_dims)
self.semantic_quantizer = ResidualVectorQuantize(
input_dim=input_dim,
n_codebooks=1,
codebook_size=semantic_codebook_size,
codebook_dim=codebook_dim,
quantizer_dropout=0.0,
)
self.quantizer = ResidualVectorQuantize(
input_dim=input_dim,
n_codebooks=n_codebooks,
codebook_size=codebook_size,
codebook_dim=codebook_dim,
quantizer_dropout=quantizer_dropout,
)
self.downsample_factor = downsample_factor
self.downsample_dims = downsample_dims
convnet_type = CausalConvNet
transconvnet_type = CausalTransConvNet
self.downsample = nn.Sequential(
*[
nn.Sequential(
convnet_type(
all_dims[idx],
all_dims[idx + 1],
kernel_size=factor,
stride=factor,
),
ConvNeXtBlock(dim=all_dims[idx + 1]),
)
for idx, factor in enumerate(downsample_factor)
]
)
self.upsample = nn.Sequential(
*[
nn.Sequential(
transconvnet_type(
all_dims[idx + 1],
all_dims[idx],
kernel_size=factor,
stride=factor,
),
ConvNeXtBlock(dim=all_dims[idx]),
)
for idx, factor in reversed(list(enumerate(downsample_factor)))
]
)
self.apply(self._init_weights)
# leave for transformer, LSTM or Mamba or something else
self.pre_module = pre_module if pre_module is not None else nn.Identity()
self.post_module = post_module if post_module is not None else nn.Identity()
self.semantic_predictor_module = (
semantic_predictor_module if semantic_predictor_module is not None else nn.Identity()
)
def _init_weights(self, m):
if isinstance(m, (nn.Conv1d, nn.Linear)):
nn.init.trunc_normal_(m.weight, std=0.02)
nn.init.constant_(m.bias, 0)
def forward(self, z, n_quantizers: int = None, semantic_len: torch.Tensor = None, **kwargs):
# z: (B, D, T)
original_shape = z.shape
if semantic_len is None:
semantic_len = torch.LongTensor([z.shape[-1]])
z = self.downsample(z)
z = self.pre_module(z) # B, T, D
(
semantic_z,
semantic_codes,
semantic_latents,
semantic_commitment_loss,
semantic_codebook_loss,
) = self.semantic_quantizer(z)
residual_z = z - semantic_z
residual_z, codes, latents, commitment_loss, codebook_loss = self.quantizer(
residual_z, n_quantizers=n_quantizers
)
z = semantic_z + residual_z
commitment_loss = commitment_loss + semantic_commitment_loss
codebook_loss = codebook_loss + semantic_codebook_loss
codes = torch.cat([semantic_codes, codes], dim=1)
latents = torch.cat([semantic_latents, latents], dim=1)
z = self.post_module(z)
z = self.upsample(z)
# z: (B, D, T)
# Pad or crop z to match original shape
diff = original_shape[-1] - z.shape[-1]
right = 0
left = abs(diff) - right
if diff > 0:
z = F.pad(z, (left, right))
elif diff < 0:
z = z[..., left:]
results = VQResult(
z=z,
codes=codes,
latents=latents,
commitment_loss=commitment_loss,
codebook_loss=codebook_loss,
)
return results
def decode(self, indices: torch.Tensor):
new_indices = torch.zeros_like(indices)
new_indices[:, 0] = torch.clamp(indices[:, 0], max=self.semantic_quantizer.codebook_size - 1)
new_indices[:, 1:] = torch.clamp(indices[:, 1:], max=self.quantizer.codebook_size - 1)
z_q_semantic = self.semantic_quantizer.from_codes(new_indices[:, :1])[0]
z_q_residual = self.quantizer.from_codes(new_indices[:, 1:])[0]
z_q = z_q_semantic + z_q_residual
z_q = self.post_module(z_q)
z_q = self.upsample(z_q)
return z_q
@@ -0,0 +1,419 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Adopted from the fish-speech 0.1.0 PyPI release (Apache-2.0)
# https://pypi.org/project/fish-speech/0.1.0/
# Copyright (c) Fish Audio
"""Window-limited transformer used inside the DAC codec (encoder blocks,
decoder blocks, and RVQ pre/post modules)."""
import math
from dataclasses import dataclass
import torch
from torch import Tensor, nn
from torch.nn import functional as F
def find_multiple(n: int, k: int) -> int:
if n % k == 0:
return n
return n + k - (n % k)
@dataclass
class ModelArgs:
block_size: int = 2048
n_layer: int = 8
n_head: int = 8
dim: int = 512
intermediate_size: int = 1536
n_local_heads: int = -1
head_dim: int = 64
rope_base: float = 10000
norm_eps: float = 1e-5
dropout_rate: float = 0.1
attn_dropout_rate: float = 0.1
channels_first: bool = True # to be compatible with conv1d input/output
pos_embed_type: str = "rope" # can be "rope" or "conformer"
max_relative_position: int = 128 # for conformer-style relative position embedding
def __post_init__(self):
if self.n_local_heads == -1:
self.n_local_heads = self.n_head
if self.intermediate_size is None:
hidden_dim = 4 * self.dim
n_hidden = int(2 * hidden_dim / 3)
self.intermediate_size = find_multiple(n_hidden, 256)
assert self.pos_embed_type in [
"rope",
"conformer",
], "pos_embed_type must be either 'rope' or 'conformer'"
class KVCache(nn.Module):
def __init__(self, max_batch_size, max_seq_length, n_heads, head_dim, dtype=torch.bfloat16):
super().__init__()
cache_shape = (max_batch_size, n_heads, max_seq_length, head_dim)
self.register_buffer("k_cache", torch.zeros(cache_shape, dtype=dtype))
self.register_buffer("v_cache", torch.zeros(cache_shape, dtype=dtype))
def update(self, input_pos, k_val, v_val):
# input_pos: [S], k_val: [B, H, S, D]
assert input_pos.shape[0] == k_val.shape[2]
k_out = self.k_cache
v_out = self.v_cache
k_out[:, :, input_pos] = k_val
v_out[:, :, input_pos] = v_val
return (
k_out[:, :, : input_pos.max() + 1, :],
v_out[:, :, : input_pos.max() + 1, :],
)
def clear_cache(self, prompt_len):
self.k_cache[:, :, prompt_len:, :].fill_(0)
self.v_cache[:, :, prompt_len:, :].fill_(0)
class Transformer(nn.Module):
def __init__(self, config: ModelArgs) -> None:
super().__init__()
self.config = config
self.layers = nn.ModuleList(TransformerBlock(config) for _ in range(config.n_layer))
self.norm = RMSNorm(config.dim, eps=config.norm_eps)
# Only compute RoPE frequencies if using RoPE
if config.pos_embed_type == "rope":
freqs_cis = precompute_freqs_cis(self.config.block_size, self.config.head_dim, self.config.rope_base)
self.register_buffer("freqs_cis", freqs_cis)
else:
self.register_buffer("freqs_cis", None)
causal_mask = torch.tril(torch.ones(self.config.block_size, self.config.block_size, dtype=torch.bool))
self.register_buffer("causal_mask", causal_mask)
self.max_batch_size = -1
self.max_seq_length = -1
self.use_kv_cache = False
def setup_caches(self, max_batch_size, max_seq_length):
"""
This method will only be called during inference when using KV cache.
"""
head_dim = self.config.dim // self.config.n_head
max_seq_length = find_multiple(max_seq_length, 8)
self.max_seq_length = max_seq_length
self.max_batch_size = max_batch_size
dtype = self.norm.weight.dtype
device = self.norm.weight.device
for b in self.layers:
b.attention.kv_cache = KVCache(
max_batch_size,
max_seq_length,
self.config.n_local_heads,
head_dim,
dtype,
).to(device)
self.use_kv_cache = True
def forward(
self,
x: Tensor,
input_pos: Tensor | None = None,
mask: Tensor | None = None,
) -> Tensor:
if self.config.pos_embed_type == "rope":
assert self.freqs_cis is not None, "RoPE frequencies must be initialized for RoPE positional embedding"
freqs_cis = self.freqs_cis[input_pos]
else:
freqs_cis = None
if mask is None: # in case of non-causal model
if not self.training and self.use_kv_cache:
mask = self.causal_mask[None, None, input_pos]
mask = mask[..., : input_pos.max() + 1]
else:
mask = self.causal_mask[None, None, input_pos]
mask = mask[..., input_pos]
for i, layer in enumerate(self.layers):
x = layer(x, input_pos, freqs_cis, mask)
x = self.norm(x)
return x
class TransformerBlock(nn.Module):
def __init__(self, config: ModelArgs) -> None:
super().__init__()
self.attention = Attention(config)
self.feed_forward = FeedForward(config)
self.ffn_norm = RMSNorm(config.dim, eps=config.norm_eps)
self.attention_norm = RMSNorm(config.dim, eps=config.norm_eps)
self.attention_layer_scale = LayerScale(config.dim, inplace=True)
self.ffn_layer_scale = LayerScale(config.dim, inplace=True)
def forward(
self,
x: Tensor,
input_pos: Tensor,
freqs_cis: Tensor,
mask: Tensor,
) -> Tensor:
h = x + self.attention_layer_scale(self.attention(self.attention_norm(x), freqs_cis, mask, input_pos))
out = h + self.ffn_layer_scale(self.feed_forward(self.ffn_norm(h)))
return out
class Attention(nn.Module):
def __init__(self, config: ModelArgs):
super().__init__()
assert config.dim % config.n_head == 0
total_head_dim = (config.n_head + 2 * config.n_local_heads) * config.head_dim
# key, query, value projections for all heads, but in a batch
self.wqkv = nn.Linear(config.dim, total_head_dim, bias=False)
self.wo = nn.Linear(config.head_dim * config.n_head, config.dim, bias=False)
self.kv_cache = None
self.n_head = config.n_head
self.head_dim = config.head_dim
self.n_local_heads = config.n_local_heads
self.dim = config.dim
self.attn_dropout_rate = config.attn_dropout_rate
self.pos_embed_type = config.pos_embed_type
# Add relative position embedding for conformer-style
if self.pos_embed_type == "conformer":
self.max_relative_position = config.max_relative_position
num_pos_embeddings = 2 * config.max_relative_position + 1
self.rel_pos_embeddings = nn.Parameter(torch.zeros(num_pos_embeddings, self.head_dim))
nn.init.normal_(self.rel_pos_embeddings, mean=0.0, std=0.02)
def _compute_conformer_pos_scores(self, q: Tensor, seqlen: int) -> Tensor:
# q: [B, H, S, D]
# Returns: [B, H, S, S]
positions = torch.arange(seqlen, device=q.device)
relative_positions = positions.unsqueeze(1) - positions.unsqueeze(0) # [S, S]
relative_positions = torch.clamp(
relative_positions + self.max_relative_position,
0,
2 * self.max_relative_position,
)
rel_embeddings = self.rel_pos_embeddings[relative_positions] # [S, S, D]
# Compute attention scores with relative position embeddings
q = q.transpose(1, 2) # [B, S, H, D]
rel_logits = torch.matmul(q, rel_embeddings.transpose(-2, -1)) # [B, S, H, S]
rel_logits = rel_logits.transpose(1, 2) # [B, H, S, S]
return rel_logits
def forward(
self,
x: Tensor,
freqs_cis: Tensor,
mask: Tensor,
input_pos: Tensor | None = None,
) -> Tensor:
bsz, seqlen, _ = x.shape
kv_size = self.n_local_heads * self.head_dim
q, k, v = self.wqkv(x).split([kv_size, kv_size, kv_size], dim=-1)
context_seqlen = seqlen
q = q.view(bsz, seqlen, self.n_head, self.head_dim)
k = k.view(bsz, context_seqlen, self.n_local_heads, self.head_dim)
v = v.view(bsz, context_seqlen, self.n_local_heads, self.head_dim)
if self.pos_embed_type == "rope":
q = apply_rotary_emb(q, freqs_cis)
k = apply_rotary_emb(k, freqs_cis)
q, k, v = map(lambda x: x.transpose(1, 2), (q, k, v))
if self.kv_cache is not None:
k, v = self.kv_cache.update(input_pos, k, v)
k = k.repeat_interleave(self.n_head // self.n_local_heads, dim=1)
v = v.repeat_interleave(self.n_head // self.n_local_heads, dim=1)
if self.pos_embed_type == "conformer":
# Compute attention scores
scale = 1.0 / math.sqrt(self.head_dim)
scores = torch.matmul(q, k.transpose(-2, -1)) * scale
# Add relative position embeddings for conformer-style
rel_scores = self._compute_conformer_pos_scores(q, seqlen)
scores = scores + rel_scores
# Apply attention
if mask is not None:
scores = scores.masked_fill(~mask, float("-inf"))
attn = F.softmax(scores, dim=-1)
if self.attn_dropout_rate > 0 and self.training:
attn = F.dropout(attn, p=self.attn_dropout_rate)
y = torch.matmul(attn, v)
else:
y = F.scaled_dot_product_attention(
q,
k,
v,
dropout_p=self.attn_dropout_rate if self.training else 0.0,
attn_mask=mask,
)
y = y.transpose(1, 2).contiguous().view(bsz, seqlen, self.head_dim * self.n_head)
y = self.wo(y)
return y
class FeedForward(nn.Module):
def __init__(self, config: ModelArgs) -> None:
super().__init__()
self.w1 = nn.Linear(config.dim, config.intermediate_size, bias=False)
self.w3 = nn.Linear(config.dim, config.intermediate_size, bias=False)
self.w2 = nn.Linear(config.intermediate_size, config.dim, bias=False)
self.dropout = nn.Dropout(config.dropout_rate)
def forward(self, x: Tensor) -> Tensor:
return self.w2(self.dropout(F.silu(self.w1(x)) * self.w3(x)))
class RMSNorm(nn.Module):
def __init__(self, dim: int, eps: float = 1e-5):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim))
def _norm(self, x):
return x * torch.rsqrt(torch.mean(x * x, dim=-1, keepdim=True) + self.eps)
def forward(self, x: Tensor) -> Tensor:
output = self._norm(x.float()).type_as(x)
return output * self.weight
class LayerScale(nn.Module):
def __init__(
self,
dim: int,
init_values: float | Tensor = 1e-2,
inplace: bool = False,
) -> None:
super().__init__()
self.inplace = inplace
self.gamma = nn.Parameter(init_values * torch.ones(dim))
def forward(self, x: Tensor) -> Tensor:
return x.mul_(self.gamma) if self.inplace else x * self.gamma
class WindowLimitedTransformer(Transformer):
"""
Transformer with window limited attention, causal.
"""
def __init__(
self,
config: ModelArgs,
input_dim: int = 512,
window_size: int | None = None,
causal: bool = True,
look_ahead_conv: nn.Module = None,
):
super().__init__(config)
self.window_size = window_size
self.causal = causal
self.channels_first = config.channels_first
self.look_ahead_conv = look_ahead_conv if look_ahead_conv is not None else nn.Identity()
self.input_proj = nn.Linear(input_dim, config.dim) if input_dim != config.dim else nn.Identity()
self.output_proj = nn.Linear(config.dim, input_dim) if input_dim != config.dim else nn.Identity()
def make_window_limited_mask(
self,
max_length: int,
x_lens: Tensor | None = None,
) -> Tensor:
"""
Make mask to form window limited attention.
"""
if self.causal:
mask = torch.tril(torch.ones(max_length, max_length))
row_indices = torch.arange(max_length).view(-1, 1)
window_size = self.window_size or max_length
valid_range = (row_indices - window_size + 1).clamp(min=0)
column_indices = torch.arange(max_length)
mask = (column_indices >= valid_range) & mask.bool()
else:
raise NotImplementedError
mask = mask.bool()[None, None]
return mask
def make_mask(
self,
max_length: int,
x_lens: Tensor | None = None,
) -> Tensor:
"""
Make ordinary mask if window size is not specified.
"""
if self.causal:
mask = torch.tril(torch.ones(max_length, max_length))
else:
mask = torch.ones(max_length, max_length)
mask = mask.bool()[None, None]
for i, x_len in enumerate(x_lens):
mask[:x_len, i] = 0
mask = mask.bool()[None, None]
return mask
def forward(
self,
x: Tensor,
x_lens: Tensor | None = None,
) -> Tensor:
if self.channels_first:
x = x.transpose(1, 2)
x = self.input_proj(x) # (B, T, D)
x = self.look_ahead_conv(x)
input_pos = torch.arange(x.shape[1], device=x.device)
# construct mask to form window limited attention
max_length = x.shape[1]
if self.window_size is not None:
mask = self.make_window_limited_mask(max_length, x_lens)
else:
mask = self.make_mask(max_length, x_lens)
mask = mask.to(x.device)
x = super().forward(x, input_pos, mask)
x = self.output_proj(x) # (B, T, D)
if self.channels_first:
x = x.transpose(1, 2)
return x
def precompute_freqs_cis(seq_len: int, n_elem: int, base: int = 10000, dtype: torch.dtype = torch.bfloat16) -> Tensor:
freqs = 1.0 / (base ** (torch.arange(0, n_elem, 2)[: (n_elem // 2)].float() / n_elem))
t = torch.arange(seq_len, device=freqs.device)
freqs = torch.outer(t, freqs)
freqs_cis = torch.polar(torch.ones_like(freqs), freqs)
cache = torch.stack([freqs_cis.real, freqs_cis.imag], dim=-1)
return cache.to(dtype=dtype)
def apply_rotary_emb(x: Tensor, freqs_cis: Tensor) -> Tensor:
xshaped = x.float().reshape(*x.shape[:-1], -1, 2)
freqs_cis = freqs_cis.view(1, xshaped.size(1), 1, xshaped.size(3), 2)
x_out2 = torch.stack(
[
xshaped[..., 0] * freqs_cis[..., 0] - xshaped[..., 1] * freqs_cis[..., 1],
xshaped[..., 1] * freqs_cis[..., 0] + xshaped[..., 0] * freqs_cis[..., 1],
],
-1,
)
x_out2 = x_out2.flatten(3)
return x_out2.type_as(x)
@@ -19,12 +19,12 @@ def build_dac_codec() -> nn.Module:
Returns the model on CPU in eval mode -- caller is responsible for
loading weights and moving to the target device.
"""
from fish_speech.models.dac.modded_dac import (
from vllm_omni.model_executor.models.fish_speech.dac_modules import (
DAC,
DownsampleResidualVectorQuantize,
ModelArgs,
WindowLimitedTransformer,
)
from fish_speech.models.dac.rvq import DownsampleResidualVectorQuantize
base_transformer_kwargs = dict(
block_size=16384,
@@ -5,8 +5,8 @@ Loads the DAC codec from ``codec.pth`` and decodes codebook indices
Analogous to ``Qwen3TTSCode2Wav`` in qwen3_tts.
Requires the ``fish-speech`` package for the DAC model architecture.
Install with: ``pip install fish-speech``
The DAC model architecture is vendored in ``dac_modules`` -- no external
``fish-speech`` package is required.
"""
from __future__ import annotations
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""GLM-TTS AR Model (Stage 0): Text → Speech Tokens.
Based on Llama architecture, generates speech token sequences from input text.
@@ -113,9 +113,9 @@ def resolve_glm_tts_tokenizer_path(model_name_or_path: Any) -> str:
return candidate
return model_path
from huggingface_hub import snapshot_download
from vllm_omni.transformers_utils.repo_utils import hf_api
local_dir = snapshot_download(
local_dir = hf_api().snapshot_download(
model_path,
allow_patterns=[
f"{_GLM_TTS_TOKENIZER_SUBDIR}/tokenizer*",
@@ -169,9 +169,9 @@ def resolve_glm_tts_model_dir(
except Exception:
pass
from huggingface_hub import snapshot_download
from vllm_omni.transformers_utils.repo_utils import hf_api
return snapshot_download(model_name_or_path)
return hf_api().snapshot_download(model_name_or_path)
def _first_glm_tts_value(value: Any) -> Any:
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Stage 1 (codec decoder) for higgs-audio v2.
Two surfaces exposed:
@@ -231,9 +231,9 @@ class HiggsAudioV2Code2Wav(nn.Module):
if os.path.isfile(os.path.join(candidate, "config.json")):
return candidate
from huggingface_hub import snapshot_download
from vllm_omni.transformers_utils.repo_utils import hf_api
return snapshot_download(repo_id=repo_id)
return hf_api().snapshot_download(repo_id=repo_id)
# ------------------------------------------------------ direct decode API
@torch.inference_mode()
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""TTS prompt builder + scope validators for higgs-audio v2.
vllm-omni's higgs path supports two request shapes:
@@ -248,9 +248,9 @@ def _load_audio_tokenizer():
audio_tokenizer_dir = _resolve_audio_tokenizer_dir()
if audio_tokenizer_dir is None:
from huggingface_hub import snapshot_download
from vllm_omni.transformers_utils.repo_utils import hf_api
repo_path = snapshot_download(
repo_path = hf_api().snapshot_download(
_K2_OMNIVOICE_REPO,
allow_patterns=[f"{_K2_OMNIVOICE_SUBDIR}/*"],
)
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""External model loading, audio I/O, and emotion conditioning for IndexTTS2."""
from __future__ import annotations
@@ -171,9 +171,10 @@ def load_semantic_codec(
codec.load_state_dict(state, strict=False)
else:
import safetensors.torch
from huggingface_hub import hf_hub_download
ckpt_path = hf_hub_download("amphion/MaskGCT", filename="semantic_codec/model.safetensors")
from vllm_omni.transformers_utils.repo_utils import hf_api
ckpt_path = hf_api().hf_hub_download("amphion/MaskGCT", filename="semantic_codec/model.safetensors")
safetensors.torch.load_model(codec, ckpt_path)
_freeze(codec.to(device=device, dtype=torch.float32))
_semantic_codec_cache[cache_key] = codec
@@ -198,9 +199,11 @@ def load_campplus(model_path: str, device: torch.device):
if ckpt_path is not None:
break
if ckpt_path is None:
from huggingface_hub import hf_hub_download
if os.path.isdir(model_path):
raise FileNotFoundError(f"IndexTTS CAMPPlus checkpoint is missing from local bundle {model_path!r}")
from vllm_omni.transformers_utils.repo_utils import hf_api
ckpt_path = hf_hub_download("funasr/campplus", filename="campplus_cn_common.bin")
ckpt_path = hf_api().hf_hub_download("funasr/campplus", filename="campplus_cn_common.bin")
state = torch.load(ckpt_path, map_location="cpu", weights_only=True)
campplus.load_state_dict(state, strict=False)
_freeze(campplus.to(device=device, dtype=torch.float32))
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
# Copyright (c) 2024 NVIDIA CORPORATION.
# Licensed under the MIT license.
@@ -9,13 +12,14 @@ import os
import torch
import torch.nn as nn
from huggingface_hub import PyTorchModelHubMixin, hf_hub_download
from huggingface_hub import PyTorchModelHubMixin
from torch.nn import Conv1d, ConvTranspose1d
from torch.nn.utils import remove_weight_norm, weight_norm
from vllm_omni.model_executor.models.common.alias_free_activation import AliasFreeActivation1d
from vllm_omni.model_executor.models.common.snake_activation import Snake, SnakeBeta
from vllm_omni.model_executor.models.indextts2.s2mel.modules.commons import AttrDict
from vllm_omni.transformers_utils.repo_utils import hf_api
# ---------------------------------------------------------------------------
# Helpers (inlined from env.py / utils.py)
@@ -328,7 +332,7 @@ class BigVGAN(
def _resolve(filename):
if os.path.isdir(model_id):
return os.path.join(model_id, filename)
return hf_hub_download(
return hf_api().hf_hub_download(
repo_id=model_id,
filename=filename,
**{
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""IndexTTS 2.5 multilingual tiktoken vocabulary.
The vocabulary layout mirrors the official IndexTTS 2.5 tokenizer: 58,836
@@ -234,9 +234,9 @@ def resolve_indextts25_tokenizer_file(
return str(model_path)
try:
from huggingface_hub import hf_hub_download
from vllm_omni.transformers_utils.repo_utils import hf_api
return hf_hub_download(repo_id=model_dir, filename=tokenizer_file)
return hf_api().hf_hub_download(repo_id=model_dir, filename=tokenizer_file)
except Exception as exc:
raise FileNotFoundError(
f"Could not resolve IndexTTS 2.5 tokenizer {tokenizer_file!r} from {model_dir!r}"
@@ -0,0 +1,3 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""JoyAI-VL-Interaction native pipeline."""
@@ -0,0 +1,65 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""JoyAI-VL-Interaction -> Qwen3-TTS native all-sync pipeline."""
from vllm_omni.config.stage_config import (
PipelineConfig,
StageExecutionType,
StagePipelineConfig,
)
_JOYAI_INPUT_PROCESSOR = "vllm_omni.model_executor.stage_input_processors.joyai_vl_interaction"
_QWEN3_TTS_INPUT_PROCESSOR = "vllm_omni.model_executor.stage_input_processors.qwen3_tts"
JOYAI_VL_INTERACTION_PIPELINE = PipelineConfig(
model_type="joyai_vl_interaction",
model_arch="Qwen3VLForConditionalGeneration",
default_deploy_config_name="joyai_vl_interaction.yaml",
stages=(
StagePipelineConfig(
stage_id=0,
model_stage="joyvl",
execution_type=StageExecutionType.LLM_AR,
input_sources=(),
final_output=True,
final_output_type="text",
owns_tokenizer=True,
requires_multimodal_data=True,
engine_output_type="text",
sampling_constraints={
"detokenize": True,
"skip_special_tokens": False,
},
),
StagePipelineConfig(
stage_id=1,
model_stage="qwen3_tts",
execution_type=StageExecutionType.LLM_AR,
input_sources=(0,),
owns_tokenizer=True,
engine_output_type="latent",
model_arch="Qwen3TTSTalkerForConditionalGeneration",
custom_process_input_func=f"{_JOYAI_INPUT_PROCESSOR}.joyai_action_to_tts",
custom_process_next_stage_input_func=f"{_QWEN3_TTS_INPUT_PROCESSOR}.talker2code2wav_full_payload",
sampling_constraints={
"detokenize": False,
"stop_token_ids": [2150],
},
),
StagePipelineConfig(
stage_id=2,
model_stage="code2wav",
execution_type=StageExecutionType.LLM_GENERATION,
input_sources=(1,),
final_output=True,
final_output_type="audio",
engine_output_type="audio",
model_arch="Qwen3TTSCode2Wav",
sync_process_input_func=f"{_QWEN3_TTS_INPUT_PROCESSOR}.talker2code2wav_token_only",
requires_full_payload_input=True,
sampling_constraints={"detokenize": True},
extras={"tts_args": {"max_instructions_length": 500}},
),
),
)
@@ -99,8 +99,10 @@ class MiMoAudioTokenizerWorker:
self.audio_tokenizer.config.nfft,
)
mel_start = time.monotonic()
self.mel_transform = (
MelSpectrogram(
# Build on CPU first: torchaudio MelSpectrogram init can mix CPU/CUDA
# tensors on newer PyTorch when default device is CUDA.
with torch.device("cpu"):
self.mel_transform = MelSpectrogram(
sample_rate=self.audio_tokenizer.config.sampling_rate,
n_fft=self.audio_tokenizer.config.nfft,
hop_length=self.audio_tokenizer.config.hop_length,
@@ -110,10 +112,9 @@ class MiMoAudioTokenizerWorker:
n_mels=self.audio_tokenizer.config.n_mels,
power=1.0,
center=True,
)
.to(self.device)
.to(torch.float32)
)
).to(torch.float32)
if self.device != "cpu":
self.mel_transform = self.mel_transform.to(self.device)
logger.info(
"[tokenizer worker] MelSpectrogram ready in %.2fs",
time.monotonic() - mel_start,
@@ -382,12 +383,19 @@ def extract_audio_code_tensor(
def _normalize_tokenizer_worker_cache_key(
device: torch.device,
device: torch.device | str,
config_path: str | None,
audio_tokenizer_path: str,
) -> tuple[str, str, str]:
"""Normalize cache key so that same tokenizer always hits the same cache entry."""
device_type = device.type if isinstance(device, torch.device) else str(device).split(":")[0]
dev = device if isinstance(device, torch.device) else torch.device(str(device))
# Keep the index: an explicit "cuda:1" must not collapse onto the process's
# current CUDA device. Resolve a bare "cuda" so it shares the cache entry
# with the equivalent indexed spelling.
if dev.type == "cuda" and dev.index is None and torch.cuda.is_available():
# Repo bans torch.cuda.current_device; match mimo_audio.py.
dev = torch.device("cuda", torch.accelerator.current_device_index())
device_key = str(dev)
# Use realpath so symlinks / trailing slash don't create duplicate entries
ap = audio_tokenizer_path or ""
if ap and os.path.exists(ap):
@@ -398,22 +406,21 @@ def _normalize_tokenizer_worker_cache_key(
if not cp and ap:
cp = os.path.dirname(ap)
return (device_type, cp, ap)
return (device_key, cp, ap)
_TOKENIZER_WORKER_CACHE: dict[tuple[str, str, str], MiMoAudioTokenizerWorker] = {}
def get_tokenizer_worker(
device: torch.device,
config_path: str,
device: torch.device | str,
config_path: str | None,
audio_tokenizer_path: str,
) -> MiMoAudioTokenizerWorker:
key = _normalize_tokenizer_worker_cache_key(device, config_path, audio_tokenizer_path)
if key not in _TOKENIZER_WORKER_CACHE:
device_type = key[0]
_TOKENIZER_WORKER_CACHE[key] = MiMoAudioTokenizerWorker(
device_str=device_type,
device_str=key[0],
config_path=config_path,
audio_tokenizer_path=audio_tokenizer_path,
)
@@ -469,8 +476,14 @@ class MiMoAudioToken2WavForConditionalGenerationVLLM(nn.Module, SupportsPP):
or self.config.name_or_path
)
_tok_dev = os.environ.get("MIMO_AUDIO_TOKENIZER_DEVICE")
if _tok_dev:
tokenizer_device = torch.device("cpu" if _tok_dev.lower() == "cpu" else _tok_dev)
else:
tokenizer_device = self.device
self._tokenizer_service: MiMoAudioTokenizerWorker | None = get_tokenizer_worker(
device=self.device,
device=tokenizer_device,
config_path=self.tokenizer_config_path,
audio_tokenizer_path=self.audio_tokenizer_path,
)
@@ -723,7 +736,7 @@ class MiMoAudioToken2WavForConditionalGenerationVLLM(nn.Module, SupportsPP):
Instead of calling _decode_waveform_from_codes per request (which incurs
4 GPU↔CPU round-trips each), this method:
1. Extracts audio_codes for all valid requests on CPU (cheap).
2. Runs quantizer.decode_vq (embedding lookup) for each on GPU.
2. Runs quantizer.decode_vq (embedding lookup) on the tokenizer device.
3. Packs all hidden-states into one tensor and calls
decoder(packed_hs, input_lengths) once.
4. Splits the output waveforms back to per-request tensors.
@@ -734,6 +747,9 @@ class MiMoAudioToken2WavForConditionalGenerationVLLM(nn.Module, SupportsPP):
return [empty]
tokenizer = self._tokenizer_service.audio_tokenizer
# Codes/weights must share the tokenizer device (may be CPU via
# MIMO_AUDIO_TOKENIZER_DEVICE), not the stage CUDA device.
tok_device = torch.device(self._tokenizer_service.device)
group_size = self.streamer_config.group_size
audio_channels = self.streamer_config.audio_channels
@@ -768,7 +784,7 @@ class MiMoAudioToken2WavForConditionalGenerationVLLM(nn.Module, SupportsPP):
use_cuda_graph = cg_ready and len(extracted) == 1
if use_cuda_graph:
wav_out = cg_wrapper.decode(extracted[0][1].to(self.device))
wav_out = cg_wrapper.decode(extracted[0][1].to(tok_device))
wav = wav_out.squeeze(0).squeeze(0)
cfg = tokenizer.config
frames_per_token = cfg.avg_pooler * cfg.stride_size * cfg.hop_length
@@ -782,7 +798,7 @@ class MiMoAudioToken2WavForConditionalGenerationVLLM(nn.Module, SupportsPP):
hidden_list: list[torch.Tensor] = []
lengths: list[int] = []
for _, audio_codes in extracted:
hs = tokenizer.encoder.decode_vq(audio_codes.to(self.device))
hs = tokenizer.encoder.decode_vq(audio_codes.to(tok_device))
hidden_list.append(hs)
lengths.append(hs.size(0))
@@ -790,7 +806,7 @@ class MiMoAudioToken2WavForConditionalGenerationVLLM(nn.Module, SupportsPP):
packed_hs = hidden_list[0]
else:
packed_hs = torch.cat(hidden_list, dim=0)
input_lengths = torch.tensor(lengths, device=self.device)
input_lengths = torch.tensor(lengths, device=tok_device)
recon_wav = tokenizer.decoder(packed_hs, input_lengths)
@@ -831,6 +847,9 @@ class MiMoAudioToken2WavForConditionalGenerationVLLM(nn.Module, SupportsPP):
return [empty]
tokenizer = self._tokenizer_service.audio_tokenizer
# Codes/weights must share the tokenizer device (may be CPU via
# MIMO_AUDIO_TOKENIZER_DEVICE), not the stage CUDA device.
tok_device = torch.device(self._tokenizer_service.device)
group_size = self.streamer_config.group_size
audio_channels = self.streamer_config.audio_channels
@@ -886,7 +905,7 @@ class MiMoAudioToken2WavForConditionalGenerationVLLM(nn.Module, SupportsPP):
frames_per_token = cfg.avg_pooler * cfg.stride_size * cfg.hop_length
if use_cuda_graph:
wav_out = cg_wrapper.decode(extracted[0][1].to(self.device))
wav_out = cg_wrapper.decode(extracted[0][1].to(tok_device))
wav = wav_out.squeeze(0).squeeze(0)
valid_len = extracted[0][1].shape[-1] * frames_per_token
if wav.numel() > valid_len:
@@ -903,7 +922,7 @@ class MiMoAudioToken2WavForConditionalGenerationVLLM(nn.Module, SupportsPP):
hidden_list: list[torch.Tensor] = []
lengths: list[int] = []
for _, audio_codes in extracted:
hs = tokenizer.encoder.decode_vq(audio_codes.to(self.device))
hs = tokenizer.encoder.decode_vq(audio_codes.to(tok_device))
hidden_list.append(hs)
lengths.append(hs.size(0))
@@ -911,7 +930,7 @@ class MiMoAudioToken2WavForConditionalGenerationVLLM(nn.Module, SupportsPP):
packed_hs = hidden_list[0]
else:
packed_hs = torch.cat(hidden_list, dim=0)
input_lengths = torch.tensor(lengths, device=self.device)
input_lengths = torch.tensor(lengths, device=tok_device)
recon_wav = tokenizer.decoder(packed_hs, input_lengths)
@@ -39,9 +39,9 @@ def _resolve_model_dir(model_ref: str, revision: str | None = None) -> str:
"""
if Path(model_ref).is_dir():
return model_ref
from huggingface_hub import snapshot_download
from vllm_omni.transformers_utils.repo_utils import hf_api
return snapshot_download(model_ref, revision=revision, allow_patterns=["assets/*"])
return hf_api().snapshot_download(model_ref, revision=revision, allow_patterns=["assets/*"])
def _batch_error(reason: str, **details: Any) -> RuntimeError:
@@ -3310,7 +3310,7 @@ class MiniCPMOAudioEmbeddingItems(DictEmbeddingItems):
) -> None:
super().__init__(
data,
modality="image",
modality="audio",
required_fields={"audio_embeds"},
fields_factory=fields_factory,
)
@@ -3733,7 +3733,8 @@ class MiniCPMO45OmniLLMMultiModalProcessor(BaseMultiModalProcessor[MiniCPMO45Omn
if isinstance(audios, MiniCPMOAudioEmbeddingItems):
single_audio_embeds = audios.get(item_idx)["audio_embeds"]
audio_len = self.info.get_audio_len_by_num_chunks(sum(map(len, single_audio_embeds)))
# One item is ``(s, h)``, so its leading dim is the audio embedding count.
audio_len = self.info.get_audio_len_by_num_chunks(len(single_audio_embeds))
else:
audio_len = audios.get_audio_length(item_idx)
@@ -3796,11 +3797,17 @@ class MiniCPMOAudioFeatureInputs(TensorSchema):
audio_feature_lens: Annotated[
torch.Tensor | list[torch.Tensor],
TensorShape("bn", "s"),
TensorShape("bn", "s", dynamic_dims={"s"}),
]
"""
This should be feature length of each audio slice,
which equals to `audio_features.shape[-1]`
Each audio in the batch may be split into a different number of slices
(e.g. audio >30s splits into multiple slices while shorter audio doesn't),
so `s` must be dynamic: batching audios with different slice counts is a
normal, valid input and is already handled below via `hstack` + per-audio
iteration, not a schema violation.
"""
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""
OmniVoice model for vLLM-Omni two-stage TTS pipeline.
@@ -487,9 +487,9 @@ class OmniVoiceModel(
if os.path.isdir(model_dir):
return model_dir
# HF hub model ID — resolve to local cache
from huggingface_hub import snapshot_download
from vllm_omni.transformers_utils.repo_utils import hf_api
return snapshot_download(model_dir)
return hf_api().snapshot_download(model_dir)
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
try:
@@ -6,9 +6,8 @@ OmniVoice Generator (Stage 0) - Iterative unmasking with Qwen3 backbone.
Generates 8-codebook audio tokens from text via 32-step non-autoregressive
iterative masked prediction with classifier-free guidance.
Uses full bidirectional attention computed directly with PyTorch SDPA
(torch.nn.functional.scaled_dot_product_attention); no auto-selected
FlashAttention/SageAttention/DiffusionAttention backend is used.
Uses backend-dispatched variable-length full bidirectional attention over
packed conditional and unconditional sequences, with an SDPA mask fallback.
"""
from __future__ import annotations
@@ -22,7 +21,11 @@ import torch
import torch.nn as nn
import torch.nn.functional as F
from vllm.logger import init_logger
from vllm.utils.math_utils import round_up
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
from vllm_omni.diffusion.attention.layer import Attention
from vllm_omni.diffusion.data import OmniDiffusionConfig
from vllm_omni.model_executor.models.omnivoice.fused_qkv_rope import fused_qkv_norm_rope
from vllm_omni.transformers_utils.configs.omnivoice import OmniVoiceConfig
@@ -241,7 +244,7 @@ def _gumbel_sample(logits: torch.Tensor, temperature: float, generator: torch.Ge
# ---------------------------------------------------------------------------
# Qwen3-style transformer blocks using PyTorch SDPA
# Qwen3-style transformer blocks using PyTorch variable-length attention
# ---------------------------------------------------------------------------
@@ -261,9 +264,9 @@ class OmniVoiceRMSNorm(nn.Module):
class OmniVoiceAttention(nn.Module):
"""Qwen3-style GQA attention using PyTorch SDPA (full bidirectional)."""
"""Qwen3-style GQA using packed, full-bidirectional varlen attention."""
def __init__(self, config: OmniVoiceConfig):
def __init__(self, config: OmniVoiceConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.llm_hidden_size
self.num_heads = config.llm_num_attention_heads
@@ -282,16 +285,27 @@ class OmniVoiceAttention(nn.Module):
self.k_norm = OmniVoiceRMSNorm(self.head_dim)
self.scale = 1.0 / math.sqrt(self.head_dim)
self.attention_op = Attention(
num_heads=self.num_heads,
num_kv_heads=self.num_heads,
head_size=self.head_dim,
causal=False,
softmax_scale=self.scale,
prefix=f"layers.{layer_idx}.self_attn.attention_op",
qkv_layout="BSND",
skip_sequence_parallel=True,
)
self.use_packed_varlen = self.attention_op.attn_backend.supports_multi_doc_packed_varlen()
def forward(
self,
hidden_states: torch.Tensor,
rope_table: torch.Tensor,
attention_mask: torch.Tensor | None = None,
attn_metadata: AttentionMetadata,
) -> torch.Tensor:
batch_size, seq_len, _ = hidden_states.shape
seq_len, _ = hidden_states.shape
qkv = self.qkv_proj(hidden_states).view(batch_size, seq_len, self.num_qkv_heads, self.head_dim)
qkv = self.qkv_proj(hidden_states).view(1, seq_len, self.num_qkv_heads, self.head_dim)
# One kernel for the whole prologue: split the packed projection, RMSNorm
# Q and K per head, rotate both, broadcast K and V across their query
@@ -306,22 +320,16 @@ class OmniVoiceAttention(nn.Module):
self.num_kv_heads,
)
# Caller passes a float mask; materialize float form if a bool slips through.
sdpa_mask = attention_mask
if sdpa_mask is not None and sdpa_mask.dtype == torch.bool:
sdpa_mask = torch.zeros_like(attention_mask, dtype=q.dtype).masked_fill_(~attention_mask, float("-inf"))
# The fused prologue emits [B, N, S, D]; Omni attention backends use
# [B, S, N, D]. Keep the conversion outside the backend.
q, k, v = (tensor.permute(0, 2, 1, 3).contiguous().to(torch.bfloat16) for tensor in (q, k, v))
if self.use_packed_varlen:
out = self.attention_op(q, k, v, attn_metadata)
else:
out = self.attention_op.sdpa_fallback.forward(q, k, v, attn_metadata)
out = F.scaled_dot_product_attention(
q,
k,
v,
attn_mask=sdpa_mask,
scale=self.scale,
)
# Back to (batch, seq, heads * head_dim)
out = out.permute(0, 2, 1, 3).contiguous()
out = out.view(batch_size, seq_len, self.num_heads * self.head_dim)
out = out.squeeze(0).to(hidden_states.dtype)
out = out.reshape(seq_len, self.num_heads * self.head_dim)
return self.o_proj(out)
@@ -351,19 +359,19 @@ _FUSED_PROJECTIONS: dict[str, tuple[str, ...]] = {
class OmniVoiceTransformerBlock(nn.Module):
"""Single Qwen3 transformer block with PyTorch SDPA attention."""
"""Single Qwen3 transformer block with variable-length attention."""
def __init__(self, config: OmniVoiceConfig):
def __init__(self, config: OmniVoiceConfig, layer_idx: int):
super().__init__()
self.input_layernorm = OmniVoiceRMSNorm(config.llm_hidden_size, eps=config.llm_rms_norm_eps)
self.self_attn = OmniVoiceAttention(config)
self.self_attn = OmniVoiceAttention(config, layer_idx)
self.post_attention_layernorm = OmniVoiceRMSNorm(config.llm_hidden_size, eps=config.llm_rms_norm_eps)
self.mlp = OmniVoiceMLP(config)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: torch.Tensor | None = None,
attn_metadata: AttentionMetadata,
rope_table: torch.Tensor | None = None,
residual: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
@@ -391,7 +399,7 @@ class OmniVoiceTransformerBlock(nn.Module):
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
hidden_states = self.self_attn(hidden_states, rope_table, attention_mask=attention_mask)
hidden_states = self.self_attn(hidden_states, rope_table, attn_metadata)
if _TRITON_AVAILABLE:
# Fused: (attn_out + residual) + RMSNorm in one kernel
@@ -432,6 +440,63 @@ def _precompute_rope_table(
return torch.cat([freqs.cos(), freqs.sin()], dim=-1)
def _position_ids_from_cu_seqs(cu_seqs: torch.Tensor, seq_len: int) -> torch.Tensor:
"""Return each packed token's zero-based position within its sequence."""
token_ids = torch.arange(seq_len, device=cu_seqs.device, dtype=cu_seqs.dtype)
sequence_ids = torch.searchsorted(cu_seqs[1:], token_ids, right=True)
sequence_starts = cu_seqs.index_select(0, sequence_ids.to(torch.long))
return (token_ids - sequence_starts).to(torch.long)
def _attention_metadata_from_cu_seqs(
cu_seqs: torch.Tensor,
seq_len: int,
*,
needs_sdpa_mask: bool,
max_seqlen: int | None = None,
) -> AttentionMetadata:
"""Build packed-varlen metadata and, when needed, an SDPA block mask."""
# Local benchmarks found no measurable performance difference between the
# exact longest segment and the packed total. Eager uses the exact bound;
# CUDA Graph uses the fixed token-bucket maximum.
kernel_max_seqlen = seq_len if max_seqlen is None else max_seqlen
extra = {
"cu_seqlens_q": cu_seqs,
"cu_seqlens_k": cu_seqs,
"max_seqlen_q": kernel_max_seqlen,
"max_seqlen_k": kernel_max_seqlen,
}
if not needs_sdpa_mask:
return AttentionMetadata(extra=extra)
token_ids = torch.arange(seq_len, device=cu_seqs.device, dtype=cu_seqs.dtype)
sequence_ids = torch.searchsorted(cu_seqs[1:], token_ids, right=True)
attn_mask = sequence_ids.view(1, 1, seq_len, 1) == sequence_ids.view(1, 1, 1, seq_len)
return AttentionMetadata(attn_mask=attn_mask, extra=extra)
def _build_cu_seqs(
cond_lens: list[int],
uncond_lens: list[int],
device: torch.device,
*,
tail_end: int | None = None,
) -> torch.Tensor:
"""Build request-major [cond0, uncond0, ...] cumulative offsets."""
if len(cond_lens) != len(uncond_lens):
raise ValueError(f"Mismatched cond/uncond lengths: {len(cond_lens)} != {len(uncond_lens)}.")
offsets = [0]
for cond_len, uncond_len in zip(cond_lens, uncond_lens):
offsets.append(offsets[-1] + cond_len)
offsets.append(offsets[-1] + uncond_len)
if tail_end is None:
tail_end = offsets[-1]
if offsets[-1] > tail_end:
raise ValueError(f"Packed length {offsets[-1]} exceeds tail end {tail_end}.")
offsets.append(tail_end)
return torch.tensor(offsets, device=device, dtype=torch.int32)
# ---------------------------------------------------------------------------
# TF32 opt-in (process-wide; default off)
# ---------------------------------------------------------------------------
@@ -461,23 +526,6 @@ def _maybe_enable_tf32() -> None:
# ---------------------------------------------------------------------------
def _additive_float_mask(mask: torch.Tensor, dtype: torch.dtype) -> torch.Tensor:
"""Convert a boolean attention mask to its additive float form.
``True`` (attend) maps to ``0.0`` and ``False`` (masked) to ``-inf``. A bool
mask must never be copied straight into a float buffer: the implicit cast
maps True/False to 1.0/0.0, which leaves masked positions at 0.0 and so
silently *unmasks* them.
``dtype`` is required rather than defaulting to float32: SDPA rejects an
additive mask whose dtype differs from the query, so the mask has to follow
the model dtype and a default would just hide that coupling.
"""
if mask.dtype != torch.bool:
return mask
return torch.zeros_like(mask, dtype=dtype).masked_fill_(~mask, float("-inf"))
class _OmniVoiceCUDAGraphForward:
"""Pre-captures CUDA graphs for predefined sequence-length buckets.
@@ -486,24 +534,47 @@ class _OmniVoiceCUDAGraphForward:
(one step at a time) means pool sharing is safe.
"""
# Default bucket count is 10; 16 gives modest headroom for edge cases
# (seq_len > max bucket or non-CFG batch) without unbounded GPU growth.
_MAX_LAZY_GRAPHS: int = 16
_MAX_LAZY_GRAPHS = 16
_STATIC_CAPTURE_TOKEN_LIMIT = 1024
_LAZY_CAPTURE_ALIGNMENT = 128
def __init__(self, generator: OmniVoiceGenerator, capture_sizes: list[int]) -> None:
self._gen = generator
self._capture_sizes = sorted(capture_sizes)
# Pre-warmed graphs keyed by (two_b, bucket); fixed set, never evicted.
self.capture_batch_sizes = self._derive_capture_batch_size()
self.capture_bucket_sizes_by_batch = self._derive_capture_bucket_sizes(capture_sizes)
self._graphs: dict[tuple[int, int], dict] = {}
# Lazy-captured graphs for oversized / non-CFG shapes; capped via LRU.
self._lazy_graphs: OrderedDict[tuple[int, int], dict] = OrderedDict()
self._lock = threading.Lock()
# Per-instance pool handle: isolates OmniVoice CUDA memory from other
# vllm modules while still allowing safe re-use across sequential replays.
self._pool_handle: int | None = None
def _find_bucket(self, seq_len: int) -> int | None:
for bucket in self._capture_sizes:
def _derive_capture_batch_size(self) -> list[int]:
return list(range(1, self._gen.od_config.max_num_seqs + 1))
def _derive_capture_bucket_sizes(self, capture_sizes: list[int]) -> dict[int, list[int]]:
"""Build a triangular, batch-aware token-bucket capture plan."""
base_sizes = sorted(set(capture_sizes))
if not base_sizes:
return {batch_size: [] for batch_size in self.capture_batch_sizes}
alignment = base_sizes[0]
single_request_cap = min(base_sizes[-1], 512)
max_graph_tokens = min(base_sizes[-1], self._STATIC_CAPTURE_TOKEN_LIMIT)
growth_per_batch = max(alignment, single_request_cap // 2)
candidates = sorted(set(base_sizes) | set(range(alignment, max_graph_tokens + alignment, alignment)))
return {
batch_size: [
bucket
for bucket in candidates
if alignment * batch_size
<= bucket
<= min(single_request_cap + (batch_size - 1) * growth_per_batch, max_graph_tokens)
]
for batch_size in self.capture_batch_sizes
}
def _find_bucket(self, batch_size: int, seq_len: int) -> int | None:
for bucket in self.capture_bucket_sizes_by_batch.get(batch_size, ()):
if bucket >= seq_len:
return bucket
return None
@@ -512,57 +583,36 @@ class _OmniVoiceCUDAGraphForward:
self,
input_ids: torch.Tensor,
audio_mask: torch.Tensor,
attention_mask: torch.Tensor | None,
bucket: int,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]:
S = input_ids.shape[-1]
if S == bucket:
return input_ids, audio_mask, attention_mask
two_b = input_ids.shape[0]
num_cb = input_ids.shape[1]
ids_padded = torch.zeros(two_b, num_cb, bucket, dtype=input_ids.dtype, device=input_ids.device)
ids_padded[:, :, :S] = input_ids
mask_padded = torch.zeros(two_b, bucket, dtype=torch.bool, device=audio_mask.device)
mask_padded[:, :S] = audio_mask
if attention_mask is not None:
# Callers normalize to the additive float form first, so pad with -inf.
attn_padded = torch.full(
(two_b, 1, bucket, bucket),
float("-inf"),
dtype=attention_mask.dtype,
device=attention_mask.device,
)
attn_padded[:, :, :S, :S] = attention_mask
else:
attn_padded = None
return ids_padded, mask_padded, attn_padded
) -> tuple[torch.Tensor, torch.Tensor]:
seq_len = input_ids.shape[0]
if seq_len == bucket:
return input_ids, audio_mask
return (
F.pad(input_ids, (0, 0, 0, bucket - seq_len), value=0),
F.pad(audio_mask, (0, bucket - seq_len), value=False),
)
def _capture_for_key(
self,
key: tuple[int, int],
input_ids: torch.Tensor,
audio_mask: torch.Tensor,
attention_mask: torch.Tensor | None,
cu_seqs: torch.Tensor,
) -> dict:
_, bucket = key
device = input_ids.device
static_rope_table = self._gen._rope_table_for(bucket, device, self._gen.model_dtype)
static_input_ids = input_ids.clone()
static_audio_mask = audio_mask.clone()
static_attn_mask = attention_mask.clone() if attention_mask is not None else None
static_cu_seqs = cu_seqs.clone()
static_rope_table = self._gen._rope_table_for(bucket, device, self._gen.model_dtype)
with torch.no_grad():
_ = self._gen._step_forward(
static_input_ids,
static_audio_mask,
static_attn_mask,
static_cu_seqs,
static_rope_table,
)
torch.accelerator.synchronize(device)
@@ -580,7 +630,7 @@ class _OmniVoiceCUDAGraphForward:
static_output = self._gen._step_forward(
static_input_ids,
static_audio_mask,
static_attn_mask,
static_cu_seqs,
static_rope_table,
)
@@ -588,87 +638,83 @@ class _OmniVoiceCUDAGraphForward:
"graph": graph,
"static_input_ids": static_input_ids,
"static_audio_mask": static_audio_mask,
"static_attn_mask": static_attn_mask,
"static_cu_seqs": static_cu_seqs,
"static_rope_table": static_rope_table,
"static_output": static_output,
}
logger.info("OmniVoice CUDA Graph captured for key %s", key)
return entry
def make_capture_cu_seq(self, batch_size: int, bucket_size: int, device: torch.device) -> torch.Tensor:
num_real_sequences = 2 * batch_size
base, rem = divmod(bucket_size, num_real_sequences)
lengths = torch.full((num_real_sequences,), base, dtype=torch.int32, device=device)
lengths[:rem] += 1
cu_seq = torch.empty(num_real_sequences + 2, dtype=torch.int32, device=device)
cu_seq[0] = 0
cu_seq[1:-1] = lengths.cumsum(0)
cu_seq[-1] = bucket_size
return cu_seq
def warmup(self, device: torch.device) -> None:
"""Pre-capture graphs for all bucket sizes with B=1 (two_b=2 for CFG)."""
"""Pre-capture common request batch sizes for every token bucket."""
if not torch.cuda.is_available():
return
logger.info(
"OmniVoice CUDA Graph warmup: capturing %d bucket sizes %s",
len(self._capture_sizes),
self._capture_sizes,
"OmniVoice CUDA Graph warmup: batch-aware capture plan %s",
self.capture_bucket_sizes_by_batch,
)
two_b = 2
num_cb = self._gen.config.num_audio_codebook
for bucket in self._capture_sizes:
key = (two_b, bucket)
dummy_ids = torch.zeros(two_b, num_cb, bucket, dtype=torch.long, device=device)
dummy_mask = torch.zeros(two_b, bucket, dtype=torch.bool, device=device)
# Capture with a float mask to match what forward() feeds at replay time,
# in the model dtype so replay can copy_ into it without a cast.
dummy_attn = torch.zeros(two_b, 1, bucket, bucket, dtype=self._gen.model_dtype, device=device)
self._graphs[key] = self._capture_for_key(key, dummy_ids, dummy_mask, dummy_attn)
for batch_size in self.capture_batch_sizes:
for bucket in self.capture_bucket_sizes_by_batch[batch_size]:
key = (batch_size, bucket)
dummy_ids = torch.zeros(bucket, num_cb, dtype=torch.long, device=device)
dummy_mask = torch.zeros(bucket, dtype=torch.bool, device=device)
dummy_cu_seqs = self.make_capture_cu_seq(batch_size, bucket, device)
self._graphs[key] = self._capture_for_key(key, dummy_ids, dummy_mask, dummy_cu_seqs)
logger.info("OmniVoice CUDA Graph warmup complete (%d graphs)", len(self._graphs))
def __call__(
self,
input_ids: torch.Tensor,
audio_mask: torch.Tensor,
attention_mask: torch.Tensor | None,
cu_seqs: torch.Tensor,
batch_size: int,
) -> torch.Tensor:
if torch.cuda.is_current_stream_capturing():
rope_table = self._gen._rope_table_for(input_ids.shape[-1], input_ids.device, self._gen.model_dtype)
return self._gen._step_forward(input_ids, audio_mask, attention_mask, rope_table)
seq_len = input_ids.shape[-1]
two_b = input_ids.shape[0]
bucket = self._find_bucket(seq_len) if two_b == 2 else None
# Graphs are captured with (and their static buffers hold) the additive
# float mask, so normalize here, before padding or any copy_ into them.
if attention_mask is not None:
attention_mask = _additive_float_mask(attention_mask, self._gen.model_dtype)
rope_table = self._gen._rope_table_for(input_ids.shape[0], input_ids.device, self._gen.model_dtype)
return self._gen._step_forward(input_ids, audio_mask, cu_seqs, rope_table)
seq_len = input_ids.shape[0]
bucket = self._find_bucket(batch_size, seq_len)
is_lazy = bucket is None
if bucket is None:
# Lazy capture: oversized sequence or non-unit batch (no pre-warmed bucket).
# Lock prevents concurrent threads from double-capturing the same key.
# _lazy_graphs is capped at _MAX_LAZY_GRAPHS with LRU eviction to
# prevent unbounded GPU memory growth when seq_len varies widely.
key = (two_b, seq_len)
ids_in, mask_in, attn_in = input_ids, audio_mask, attention_mask
with self._lock:
entry = self._lazy_graphs.get(key)
if entry is None:
entry = self._capture_for_key(key, ids_in, mask_in, attn_in)
if len(self._lazy_graphs) >= self._MAX_LAZY_GRAPHS:
evicted_key, _ = self._lazy_graphs.popitem(last=False)
logger.warning("OmniVoice CUDA Graph lazy cache full; evicted key %s", evicted_key)
self._lazy_graphs[key] = entry
else:
key = (two_b, bucket)
ids_in, mask_in, attn_in = self._pad_inputs(input_ids, audio_mask, attention_mask, bucket)
with self._lock:
entry = self._graphs.get(key)
if entry is None:
entry = self._capture_for_key(key, ids_in, mask_in, attn_in)
self._graphs[key] = entry
bucket = round_up(seq_len, self._LAZY_CAPTURE_ALIGNMENT)
ids_in, mask_in = self._pad_inputs(input_ids, audio_mask, bucket)
runtime_cu_seqs = cu_seqs.clone()
runtime_cu_seqs[-1] = bucket
key = (batch_size, bucket)
cache = self._lazy_graphs if is_lazy else self._graphs
with self._lock:
entry = cache.get(key)
if entry is None:
if is_lazy and len(self._lazy_graphs) >= self._MAX_LAZY_GRAPHS:
evicted_key, _ = self._lazy_graphs.popitem(last=False)
logger.info("Evicted OmniVoice lazy CUDA Graph key %s", evicted_key)
entry = self._capture_for_key(key, ids_in, mask_in, runtime_cu_seqs)
cache[key] = entry
elif is_lazy:
self._lazy_graphs.move_to_end(key)
entry["static_input_ids"].copy_(ids_in)
entry["static_audio_mask"].copy_(mask_in)
if attn_in is not None and entry["static_attn_mask"] is not None:
entry["static_attn_mask"].copy_(attn_in)
entry["static_cu_seqs"].copy_(runtime_cu_seqs)
entry["graph"].replay()
output = entry["static_output"]
if bucket is not None and bucket != seq_len:
output = output[:, :, :seq_len, :]
if bucket != seq_len:
output = output[:, :seq_len, :]
return output
def clear(self) -> None:
@@ -692,17 +738,17 @@ class OmniVoiceGenerator(nn.Module):
- 32-step iterative unmasking with classifier-free guidance
Optimizations:
- Full bidirectional attention via PyTorch SDPA (no auto-selected
FlashAttn/SageAttn/DiffusionAttention backend)
- Packed full-bidirectional varlen attention with SDPA fallback
- regionally_compile() compatible for torch.compile on repeated blocks
"""
# For regionally_compile() support
_repeated_blocks = ["layers"]
def __init__(self, config: OmniVoiceConfig):
def __init__(self, config: OmniVoiceConfig, od_config: OmniDiffusionConfig):
super().__init__()
self.config = config
self.od_config = od_config
# Opt-in TF32; must run before any CUDA-graph capture so captured kernels honour it.
if getattr(config, "enable_tf32", False):
@@ -722,7 +768,10 @@ class OmniVoiceGenerator(nn.Module):
)
# Transformer layers
self.layers = nn.ModuleList([OmniVoiceTransformerBlock(config) for _ in range(config.llm_num_hidden_layers)])
self.layers = nn.ModuleList(
[OmniVoiceTransformerBlock(config, layer_idx) for layer_idx in range(config.llm_num_hidden_layers)]
)
self._needs_sdpa_mask = any(not layer.self_attn.use_packed_varlen for layer in self.layers)
self.norm = OmniVoiceRMSNorm(config.llm_hidden_size, eps=config.llm_rms_norm_eps)
# Prediction head: hidden → 8 * 1025
@@ -775,23 +824,23 @@ class OmniVoiceGenerator(nn.Module):
"""Prepare mixed text+audio embeddings.
Args:
input_ids: [B, 8, S] - text tokens replicated across codebooks,
input_ids: [T, 8] - text tokens replicated across codebooks,
audio positions have per-codebook token IDs
audio_mask: [B, S] - True for audio positions, False for text
text_embeds: optional cached [B, S, H] text-position embeddings
audio_mask_3d: optional cached [B, S, 1] audio_mask.unsqueeze(-1)
audio_mask: [T] - True for audio positions, False for text
text_embeds: optional cached [T, H] text-position embeddings
audio_mask_3d: optional cached [T, 1] audio_mask.unsqueeze(-1)
Returns:
embeddings: [B, S, hidden_size]
embeddings: [T, hidden_size]
"""
# Cached across the denoising loop since text ids don't change.
if text_embeds is None:
text_embeds = self.text_embedding(input_ids[:, 0, :])
text_embeds = self.text_embedding(input_ids[:, 0])
if audio_mask_3d is None:
audio_mask_3d = audio_mask.unsqueeze(-1)
# Audio embeddings: offset per codebook, then sum across codebooks
shifted_ids = (input_ids * audio_mask.unsqueeze(1)) + self.codebook_layer_offsets.view(1, -1, 1)
shifted_ids = (input_ids * audio_mask.unsqueeze(1)) + self.codebook_layer_offsets.view(1, -1)
audio_embeds = self.audio_embeddings(shifted_ids).sum(dim=1)
# Merge: audio where audio_mask=True, text elsewhere
@@ -800,35 +849,39 @@ class OmniVoiceGenerator(nn.Module):
def _transformer_forward(
self,
inputs_embeds: torch.Tensor,
attention_mask: torch.Tensor | None = None,
cu_seqs: torch.Tensor,
max_seqlen: int | None = None,
rope_table: torch.Tensor | None = None,
) -> torch.Tensor:
"""Run through transformer layers.
Args:
inputs_embeds: [B, S, hidden_size]
attention_mask: [B, 1, S, S] or None
rope_table: optional precomputed [B * S, head_dim] RoPE table
inputs_embeds: [T, hidden_size]
cu_seqs: cumulative boundaries for packed sequences
rope_table: optional base [T, head_dim] RoPE table
Returns:
hidden_states: [B, S, hidden_size]
hidden_states: [T, hidden_size]
"""
hidden_states = inputs_embeds
if rope_table is None:
rope_table = self._rope_table_for(inputs_embeds.shape[1], inputs_embeds.device, hidden_states.dtype)
# Safety: convert bool mask if caller hasn't (e.g. external paths beyond forward()).
if attention_mask is not None and attention_mask.dtype == torch.bool:
attention_mask = torch.zeros_like(attention_mask, dtype=hidden_states.dtype).masked_fill_(
~attention_mask, float("-inf")
)
rope_table = self._rope_table_for(inputs_embeds.shape[0], inputs_embeds.device, hidden_states.dtype)
seq_len = inputs_embeds.shape[0]
position_ids = _position_ids_from_cu_seqs(cu_seqs, seq_len)
packed_rope_table = rope_table.index_select(0, position_ids).contiguous()
attn_metadata = _attention_metadata_from_cu_seqs(
cu_seqs,
seq_len,
needs_sdpa_mask=self._needs_sdpa_mask,
max_seqlen=max_seqlen,
)
residual = None
for layer in self.layers:
hidden_states, residual = layer(
hidden_states,
attention_mask=attention_mask,
rope_table=rope_table,
attn_metadata=attn_metadata,
rope_table=packed_rope_table,
residual=residual,
)
@@ -838,44 +891,77 @@ class OmniVoiceGenerator(nn.Module):
"""Project hidden states to per-codebook logits.
Args:
hidden_states: [B, S, hidden_size]
hidden_states: [T, hidden_size]
Returns:
logits: [B, 8, S, 1025]
logits: [8, T, 1025]
"""
batch_size, seq_len, _ = hidden_states.shape
logits_flat = self.audio_heads(hidden_states) # [B, S, 8*1025]
seq_len, _ = hidden_states.shape
logits_flat = self.audio_heads(hidden_states) # [T, 8*1025]
return logits_flat.view(
batch_size,
seq_len,
self.config.num_audio_codebook,
self.config.audio_vocab_size,
).permute(0, 2, 1, 3) # [B, 8, S, 1025]
).permute(1, 0, 2) # [8, T, 1025]
def _step_forward(
self,
input_ids: torch.Tensor,
audio_mask: torch.Tensor,
attention_mask: torch.Tensor | None,
cu_seqs: torch.Tensor,
rope_table: torch.Tensor,
) -> torch.Tensor:
"""Single unmasking-step forward using a pre-cast RoPE table (CUDA graph safe)."""
hidden_states = self._prepare_embeddings(input_ids, audio_mask)
residual = None
for layer in self.layers:
hidden_states, residual = layer(
hidden_states, attention_mask=attention_mask, rope_table=rope_table, residual=residual
hidden_states = self._transformer_forward(hidden_states, cu_seqs, rope_table=rope_table)
return self._get_logits(hidden_states)
def _unmask_one_request(
self,
c_logits: torch.Tensor,
u_logits: torch.Tensor,
sample_tokens: torch.Tensor,
*,
num_to_unmask: int | torch.Tensor,
guidance_scale: float,
generator: torch.Generator,
class_temperature: float,
position_temperature: float,
layer_penalty_factor: float,
layer_ids: torch.Tensor,
) -> None:
"""Sample and unmask one request in place from FP32 target logits."""
mask_id = self.config.audio_mask_id
if guidance_scale != 0:
log_probs = F.log_softmax(
(1.0 + guidance_scale) * c_logits - guidance_scale * u_logits,
dim=-1,
)
return self._get_logits(self.norm(hidden_states + residual))
else:
log_probs = F.log_softmax(c_logits, dim=-1)
log_probs[..., mask_id] = -float("inf")
if class_temperature > 0.0:
pred_tokens = _gumbel_sample(log_probs, class_temperature, generator).argmax(dim=-1)
else:
pred_tokens = log_probs.argmax(dim=-1)
scores = log_probs.max(dim=-1)[0]
scores = scores - (layer_ids * layer_penalty_factor)
if position_temperature > 0.0:
scores = _gumbel_sample(scores, position_temperature, generator)
scores.masked_fill_(sample_tokens != mask_id, -float("inf"))
_, topk_idx = torch.topk(scores.flatten(), num_to_unmask)
flat_tokens = sample_tokens.flatten()
flat_tokens[topk_idx] = pred_tokens.flatten()[topk_idx]
sample_tokens.copy_(flat_tokens.view_as(sample_tokens))
@torch.inference_mode()
def forward(
self,
input_ids: torch.Tensor,
audio_mask: torch.Tensor,
attention_mask: torch.Tensor,
cond_lens: list[int],
target_lens: list[int],
seed: int | None = None,
seed: int | list[int | None] | None = None,
num_step: int = 32,
guidance_scale: float = 2.0,
t_shift: float = 0.1,
@@ -886,36 +972,51 @@ class OmniVoiceGenerator(nn.Module):
"""Run the full 32-step iterative unmasking generation.
Args:
input_ids: [2*B, 8, S] - conditional (0:B) + unconditional (B:2B)
audio_mask: [2*B, S] - True for audio positions
attention_mask: [2*B, 1, S, S] - attention mask
target_lens: List of target audio lengths per batch item
num_step: Number of unmasking steps
guidance_scale: CFG scale
t_shift: Time shift for schedule
layer_penalty_factor: Penalty for later codebooks
position_temperature: Gumbel temperature for position selection
class_temperature: Temperature for token prediction (0=greedy)
input_ids: Packed token IDs with shape ``[total_seq_len, 8]`` in
request-major ``[cond0, uncond0, ...]`` order.
audio_mask: Boolean audio-position mask with shape
``[total_seq_len]``.
cond_lens: Conditional sequence length for each request.
target_lens: Target length for each request; also the corresponding
unconditional sequence length.
seed: One seed per request, a shared scalar seed, or ``None``.
num_step: Number of iterative unmasking steps.
guidance_scale: Classifier-free guidance scale.
t_shift: Time shift used to construct the unmasking schedule.
layer_penalty_factor: Penalty applied to later codebooks.
position_temperature: Gumbel temperature for position selection.
class_temperature: Token sampling temperature; zero selects greedy
decoding.
Returns:
tokens: [B, 8, max_target_len] - generated audio tokens
Packed generated audio tokens with shape
``[1, 8, sum(target_lens)]``.
"""
B = len(target_lens)
device = input_ids.device
max_target_len = max(target_lens)
total_target_lens = sum(target_lens)
mask_id = self.config.audio_mask_id
num_codebooks = self.config.num_audio_codebook
if seed is None:
seed = random.randint(0, 2**63 - 1)
generator = torch.Generator(device=device).manual_seed(seed)
seeds = seed if isinstance(seed, list) else [seed] * B
generators = [
torch.Generator(device=device).manual_seed(
request_seed if request_seed is not None else random.randint(0, 2**63 - 1)
)
for request_seed in seeds
]
# Initialize all target tokens as [MASK]
tokens = torch.full(
(B, num_codebooks, max_target_len),
mask_id,
dtype=torch.long,
device=device,
)
tokens = torch.full((1, num_codebooks, total_target_lens), mask_id, dtype=torch.long, device=device)
target_offsets: list[int] = []
target_offset = 0
sequence_offsets: list[int] = []
sequence_offset = 0
for cond_len, target_len in zip(cond_lens, target_lens):
target_offsets.append(target_offset)
target_offset += target_len
sequence_offsets.append(sequence_offset)
sequence_offset += cond_len + target_len
cu_seqs = _build_cu_seqs(cond_lens, target_lens, device)
# Compute unmasking schedule
timesteps = _get_time_steps(0.0, 1.0, num_step + 1, t_shift).tolist()
@@ -939,45 +1040,46 @@ class OmniVoiceGenerator(nn.Module):
layer_ids = torch.arange(num_codebooks, device=device).view(1, -1, 1)
# Single D2H pull for all conditional lengths instead of B per-item .item() syncs.
c_lens = attention_mask[:B, 0, 0].sum(dim=-1).tolist()
# Materialize the SDPA float mask once so the captured graph (and eager path) skip per-layer conversion.
sdpa_attn_mask = _additive_float_mask(attention_mask, self.model_dtype)
use_cuda_graph = self._cuda_graph_fwd is not None and input_ids.is_cuda
if not use_cuda_graph:
# Eager-path-only constants (the cuda-graph captures its own).
text_embeds_cached = self.text_embedding(input_ids[:, 0, :])
text_embeds_cached = self.text_embedding(input_ids[:, 0])
audio_mask_3d = audio_mask.unsqueeze(-1)
rope_table = self._rope_table_for(input_ids.shape[-1], device, text_embeds_cached.dtype)
rope_table = self._rope_table_for(input_ids.shape[0], device, text_embeds_cached.dtype)
# Main iterative loop
for step in range(num_step):
if use_cuda_graph:
# Float mask skips per-layer conversion; fp32 cast deferred to the per-item slices below.
batch_logits = self._cuda_graph_fwd(input_ids, audio_mask, sdpa_attn_mask)
batch_logits = self._cuda_graph_fwd(input_ids, audio_mask, cu_seqs, B)
else:
# Eager fallback reuses hoisted constants (text embeds, sdpa mask, rope table).
inputs_embeds = self._prepare_embeddings(
input_ids, audio_mask, text_embeds=text_embeds_cached, audio_mask_3d=audio_mask_3d
)
hidden_states = self._transformer_forward(inputs_embeds, sdpa_attn_mask, rope_table=rope_table)
hidden_states = self._transformer_forward(
inputs_embeds,
cu_seqs,
max_seqlen=max(cond_lens),
rope_table=rope_table,
)
# fp32 cast deferred to the per-item slices below.
batch_logits = self._get_logits(hidden_states)
# batch_logits: [2*B, 8, S, 1025]
# batch_logits: [8, T, 1025]
for i in range(B):
k = schedules[i][step]
if k <= 0:
continue
c_len = c_lens[i]
c_len = cond_lens[i]
t_len = target_lens[i]
request_start = sequence_offsets[i]
cond_end = request_start + c_len
# Extract logits for target region; upcast only the slices we actually consume.
c_logits = batch_logits[i : i + 1, :, c_len - t_len : c_len, :].to(torch.float32)
u_logits = batch_logits[B + i : B + i + 1, :, :t_len, :].to(torch.float32)
c_logits = batch_logits[:, cond_end - t_len : cond_end, :].unsqueeze(0).to(torch.float32)
u_logits = batch_logits[:, cond_end : cond_end + t_len, :].unsqueeze(0).to(torch.float32)
# Classifier-free guidance. Fuse the chain: the two inner
# log_softmax normalizers are per-position scalars that the final
@@ -996,7 +1098,7 @@ class OmniVoiceGenerator(nn.Module):
# Token prediction
if class_temperature > 0.0:
pred_tokens = _gumbel_sample(log_probs, class_temperature, generator).argmax(dim=-1)
pred_tokens = _gumbel_sample(log_probs, class_temperature, generators[i]).argmax(dim=-1)
else:
pred_tokens = log_probs.argmax(dim=-1) # [1, 8, T]
@@ -1008,10 +1110,11 @@ class OmniVoiceGenerator(nn.Module):
# Gumbel noise for position selection
if position_temperature > 0.0:
scores = _gumbel_sample(scores, position_temperature, generator)
scores = _gumbel_sample(scores, position_temperature, generators[i])
# Mask out already unmasked positions
sample_tokens = tokens[i : i + 1, :, :t_len]
target_start = target_offsets[i]
sample_tokens = tokens[:, :, target_start : target_start + t_len]
scores.masked_fill_(sample_tokens != mask_id, -float("inf"))
# Select top-k positions to unmask. .flatten() on this non-contiguous view already copies.
@@ -1021,8 +1124,9 @@ class OmniVoiceGenerator(nn.Module):
sample_tokens.copy_(flat_tokens.view_as(sample_tokens))
# Mirror update into both cond and uncond input_ids halves for the next step.
input_ids[i, :, c_len - t_len : c_len] = sample_tokens.squeeze(0)
input_ids[B + i, :, :t_len] = sample_tokens.squeeze(0)
packed_sample_tokens = sample_tokens.squeeze(0).transpose(0, 1)
input_ids[cond_end - t_len : cond_end] = packed_sample_tokens
input_ids[cond_end : cond_end + t_len] = packed_sample_tokens
return tokens
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Streaming Mimi codec for PersonaPlex (moshi-free).
Frame-clocked duplex needs a codec that encodes/decodes exactly one 80 ms frame
@@ -288,10 +288,11 @@ class PersonaPlexMimiCodec(nn.Module):
def __init__(self, hf_repo: str = DEFAULT_HF_REPO, checkpoint: str | None = None, device: str = "cuda") -> None:
super().__init__()
from huggingface_hub import hf_hub_download
from safetensors.torch import load_file
from transformers import MimiConfig, MimiModel
from vllm_omni.transformers_utils.repo_utils import hf_api
self.device = torch.device(device)
# The PersonaPlex repo ships the reference mimi checkpoint in the moshi
@@ -300,7 +301,7 @@ class PersonaPlexMimiCodec(nn.Module):
# transformer stacks remain absent because the streaming implementations
# below replace them with the checkpoint's fused QKV layout.
if checkpoint is None:
checkpoint = hf_hub_download(
checkpoint = hf_api().hf_hub_download(
"nvidia/personaplex-7b-v1",
"tokenizer-e351c8d8-checkpoint125.safetensors",
)
@@ -304,6 +304,17 @@ _OMNI_MODELS = {
"gepard_talker",
"GepardTalkerForConditionalGeneration",
),
## audio8_tts (Audio8 TTS Preview 0.6B)
"Audio8TTSSlowARForConditionalGeneration": (
"audio8_tts",
"audio8_tts_slow_ar",
"Audio8TTSSlowARForConditionalGeneration",
),
"Audio8TTSCodecDecoder": (
"audio8_tts",
"audio8_tts_codec_decoder",
"Audio8TTSCodecDecoder",
),
## VoxCPM2
"VoxCPM2TalkerForConditionalGeneration": (
"voxcpm2",
@@ -461,9 +461,9 @@ class StepAudio2Token2WavForConditionalGeneration(nn.Module, SupportsPP):
if model_path is None:
# Resolve HF repo names to local cache path
if not os.path.isdir(model_name_or_path):
from huggingface_hub import snapshot_download
from vllm_omni.transformers_utils.repo_utils import hf_api
model_name_or_path = snapshot_download(model_name_or_path)
model_name_or_path = hf_api().snapshot_download(model_name_or_path)
model_path = f"{model_name_or_path}/token2wav"
float16 = getattr(self.config, "token2wav_float16", False)
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""VoxCPM2 AR talker — PagedAttention pipeline with per-request state.
Architecture:
@@ -158,7 +158,7 @@ def build_voxcpm2_prompt(
"""Build a VoxCPM2 prefill prompt whose ``prompt_token_ids`` length matches
the talker-side prefill length.
Used by both online serving (``serving_speech._build_voxcpm2_prompt``) and
Used by both online serving (``VoxCPM2Adapter._build_prompt``) and
the offline example, so the talker-side length assertion never fires.
"""
ids = split_multichar_chinese(tokenizer.encode(text, add_special_tokens=True), split_map)
@@ -2208,7 +2208,7 @@ class VoxCPM2TalkerForConditionalGeneration(nn.Module):
assert scaffold_len == tts_len, (
f"voxcpm2 prefill length mismatch: scaffold_len={scaffold_len} tts_len={tts_len}; "
"caller must pad prompt_token_ids to the full prefill length "
"(see serving_speech._build_voxcpm2_prompt or the offline example)."
"(see VoxCPM2Adapter._build_prompt or the offline example)."
)
enc_out = base_lm_out.unsqueeze(0)
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from collections.abc import Iterable, Mapping
from dataclasses import replace
from functools import cached_property
@@ -6,7 +9,6 @@ from pathlib import Path
import regex as re
import torch
import torch.nn as nn
from huggingface_hub import hf_hub_download
from vllm.config import VllmConfig
from vllm.logger import init_logger
from vllm.model_executor.models.interfaces import SupportsMultiModal
@@ -28,6 +30,7 @@ from vllm_omni.model_executor.models.voxtral_tts.voxtral_tts_audio_generation im
VoxtralTTSMultiModalProcessor,
VoxtralTTSProcessingInfo,
)
from vllm_omni.transformers_utils.repo_utils import hf_api
logger = init_logger(__name__)
@@ -133,7 +136,7 @@ class VoxtralTTSForConditionalGeneration(
self.voice_to_embedding = {}
for sid in speaker_id:
if self.is_hf_model:
path = hf_hub_download(repo_id=self.repo_id, filename=f"voice_embedding/{sid}.pt")
path = hf_api().hf_hub_download(repo_id=self.repo_id, filename=f"voice_embedding/{sid}.pt")
else:
path = Path(self.repo_id) / "voice_embedding" / f"{sid}.pt"
if Path(path).exists():