Merge vLLM-Omni v0.29.0rc1 into edge-infer/omni-0.29.0

The pair for vLLM v0.29.0: rc1's docs pin vllm==0.29.0 and a static scan of
rc1's vllm.* imports against the v0.29.0 tree finds nothing missing, while
our 0.28-based tree needs seven modules v0.29.0 no longer has
(vllm.inputs.preprocess, entrypoints.launcher, openai.cli_args,
openai.engine.protocol, serve.utils.server_utils, layers.batch_invariant,
models.hunyuan_v1).

Ten files conflicted. Upstream's structure is the base everywhere; the
fork's features are re-attached to it:
- deploy_profile / apply_deploy_profile run before rc1's resolve_omni_config
  pops deploy_config (async_omni_engine, cli/serve); the deploy-profile
  selector and the resolve_model_config_path chain it needs stay in
  entrypoints/utils.py; stage_overrides takes rc1's dict type.
- config_factory keeps the lazy diffusion output-type import; the diffusion
  registry import in rc1's new config/resolver.py is made lazy for the same
  WP6 reason (TTS path must not load diffusion).
- requirements: our core/media split kept; rc1's transformers>=5.13 floor
  and kernels==0.16.1 applied in core.txt / media.txt.
- TTS: rc1's split_granularity and bounded seed plus our output_mode=
  codec_tokens, _SessionInbox cancel handling and codec DELTA accumulation;
  our private _conditioning_cache_salt is superseded by rc1's public
  tts_adapters/base.py::conditioning_cache_salt.
- stage_runtime: rc1's single ExitStack G2 path (lock released before READY)
  replaces our two-path block, with the four worker_phase names the init
  profiler consumes still emitted; _cpu_placed / host admission kept.

Not yet run against vLLM 0.29.0: the tests listed in the W6 record.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
tzhouamandClaude Fable 5.1 committed 2026-09-18 09:57:20 +08:00
commit 33de5d8629
513 files changed
+35146 -10927

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
#
# Adapted from nvidia/Nemotron-Labs-Audex-2B (Apache-2.0):
# inference_scripts_vllm/audioqa_scripts/audex_2b_vllm/audio_features.py
@@ -33,13 +33,14 @@ from vllm.multimodal.inputs import MultiModalFieldConfig, MultiModalKwargsItems
from vllm.multimodal.parse import MultiModalDataItems, MultiModalDataParser
from vllm.multimodal.processing import (
BaseDummyInputsBuilder,
BaseMultiModalProcessor,
BaseProcessingInfo,
PromptReplacement,
PromptUpdate,
PromptUpdateDetails,
)
from vllm_omni.inputs.mm_processor import OmniMultiModalProcessor
SOUND_TOKEN = "<so_embedding>"
SOUND_START_TOKEN = "<so_start>"
SOUND_END_TOKEN = "<so_end>"
@@ -176,7 +177,7 @@ class AudexDummyInputsBuilder(BaseDummyInputsBuilder[AudexProcessingInfo]):
return {"audio": self._get_dummy_audios(length=audio_len, num_audios=num_audios, overrides=overrides)}
class AudexMultiModalProcessor(BaseMultiModalProcessor[AudexProcessingInfo]):
class AudexMultiModalProcessor(OmniMultiModalProcessor[AudexProcessingInfo]):
def _call_hf_processor(
self,
prompt: str,
@@ -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",
]
+70 -68
View File
@@ -1,4 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from collections.abc import Iterable, Mapping, Sequence
from dataclasses import replace
from math import isqrt
from typing import Any
@@ -17,7 +21,7 @@ from vllm.model_executor.model_loader.weight_utils import default_weight_loader
from vllm.model_executor.models.bagel import BagelForConditionalGeneration
from vllm.model_executor.models.interfaces import MultiModalEmbeddings
from vllm.model_executor.models.qwen2 import Qwen2DecoderLayer, Qwen2MLP
from vllm.model_executor.models.utils import AutoWeightsLoader
from vllm.model_executor.models.utils import AutoWeightsLoader, WeightsMapper
from vllm.multimodal import MULTIMODAL_REGISTRY
from vllm.multimodal.inputs import (
MultiModalFieldConfig,
@@ -122,9 +126,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
@@ -218,6 +222,20 @@ class OmniBagelDataParser(MultiModalDataParser):
class OmniBagelMultiModalProcessor(BaseMultiModalProcessor[OmniBagelProcessingInfo]):
IMG2IMG_PLACEHOLDER = "<|fim_middle|>"
def apply(self, inputs, timing_ctx):
num_img2img = inputs.mm_data_items.get_all_counts().get("img2img", 0)
if num_img2img:
token_id = self.info.get_tokenizer().get_vocab().get(self.IMG2IMG_PLACEHOLDER)
if token_id is not None:
prompt_ids = list(inputs.prompt)
missing = num_img2img - prompt_ids.count(token_id)
if missing > 0:
inputs = replace(
inputs,
prompt=[token_id] * missing + prompt_ids,
)
return super().apply(inputs, timing_ctx)
@staticmethod
def _mm_kwargs_for_bagel_img2img_hf(mm_kwargs: Mapping[str, object]) -> dict[str, object]:
# OpenAI / GLM-style serving may pass target_h/target_w for output grid sizing.
@@ -238,69 +256,51 @@ class OmniBagelMultiModalProcessor(BaseMultiModalProcessor[OmniBagelProcessingIn
"pixel_values_img2img": MultiModalFieldConfig.batched("img2img"),
}
def _call_hf_processor(
def _apply_hf_processor_main(
self,
prompt: str,
mm_data: Mapping[str, object],
mm_kwargs: Mapping[str, object],
tok_kwargs: Mapping[str, object],
) -> "BatchFeature":
has_image = "images" in mm_data
has_img2img = "pixel_values_img2img" in mm_data
if has_img2img and self.IMG2IMG_PLACEHOLDER not in prompt:
prompt = f"{self.IMG2IMG_PLACEHOLDER}{prompt}"
if has_image and has_img2img:
outputs = BatchFeature()
img_data = dict(mm_data)
if "pixel_values_img2img" in img_data:
del img_data["pixel_values_img2img"]
kwargs_img = dict(mm_kwargs)
kwargs_img["is_img2img"] = False
out_img = super()._call_hf_processor(prompt, img_data, kwargs_img, tok_kwargs)
if "pixel_values" in out_img:
outputs["pixel_values"] = out_img["pixel_values"]
for k, v in out_img.items():
if k != "pixel_values":
outputs[k] = v
img2img_data = dict(mm_data)
if "images" in img2img_data:
del img2img_data["images"]
img2img_data["images"] = img2img_data.pop("pixel_values_img2img")
kwargs_img2img = self._mm_kwargs_for_bagel_img2img_hf(mm_kwargs)
kwargs_img2img["is_img2img"] = True
out_img2img = super()._call_hf_processor(prompt, img2img_data, kwargs_img2img, tok_kwargs)
if "pixel_values" in out_img2img:
outputs["pixel_values_img2img"] = out_img2img["pixel_values"]
for k, v in out_img2img.items():
if k not in outputs:
outputs[k] = v
return outputs
elif has_img2img:
mm_data = dict(mm_data)
mm_data["images"] = mm_data.pop("pixel_values_img2img")
mm_kwargs = self._mm_kwargs_for_bagel_img2img_hf(mm_kwargs)
mm_kwargs["is_img2img"] = True
outputs = super()._call_hf_processor(prompt, mm_data, mm_kwargs, tok_kwargs)
if "pixel_values" in outputs:
outputs["pixel_values_img2img"] = outputs.pop("pixel_values")
return outputs
return super()._call_hf_processor(prompt, mm_data, mm_kwargs, tok_kwargs)
def _hf_processor_applies_updates(
self,
prompt_text: str,
mm_items: MultiModalDataItems,
hf_processor_mm_kwargs: Mapping[str, object],
tokenization_kwargs: Mapping[str, object],
) -> bool:
return False
) -> BatchFeature:
valid_mm_items = mm_items.select({key for key, count in mm_items.get_all_counts().items() if count > 0})
mm_data, passthrough_data = self._get_hf_mm_data(valid_mm_items)
prompt_text = self.dummy_inputs.get_dummy_text(mm_items.get_all_counts())
processor = self.info.get_hf_processor(**hf_processor_mm_kwargs)
has_image = "images" in mm_data
has_img2img = "pixel_values_img2img" in mm_data
processed_data = BatchFeature()
if has_image:
image_kwargs = {**hf_processor_mm_kwargs, "is_img2img": False}
image_outputs = self.info.ctx.call_hf_processor(
processor,
{"text": prompt_text, "images": mm_data["images"]},
image_kwargs,
)
processed_data.update(image_outputs)
if has_img2img:
img2img_kwargs = self._mm_kwargs_for_bagel_img2img_hf(hf_processor_mm_kwargs)
img2img_kwargs["is_img2img"] = True
img2img_outputs = self.info.ctx.call_hf_processor(
processor,
{
"text": prompt_text,
"images": mm_data["pixel_values_img2img"],
},
img2img_kwargs,
)
pixel_values = img2img_outputs.pop("pixel_values", None)
if pixel_values is not None:
processed_data["pixel_values_img2img"] = pixel_values
for key, value in img2img_outputs.items():
processed_data.setdefault(key, value)
if not has_image and not has_img2img:
processed_data = BatchFeature(dict(passthrough_data))
else:
processed_data.update(passthrough_data)
return processed_data
def _get_prompt_updates(
self,
@@ -369,7 +369,8 @@ class OmniBagelMultiModalProcessor(BaseMultiModalProcessor[OmniBagelProcessingIn
embed_mask = [True] * num_vae_total + [False] + [True] * num_vit_total
return PromptUpdateDetails(
full=tokens,
is_embed=lambda _tok, _seq, _m=embed_mask: torch.tensor(_m, dtype=torch.bool),
# vLLM 0.29 calls is_embed with just the full token list.
is_embed=lambda _full, _m=embed_mask: torch.tensor(_m, dtype=torch.bool),
)
replacements.append(
@@ -1099,11 +1100,12 @@ class OmniBagelForConditionalGeneration(BagelForConditionalGeneration):
filtered_weights.append((mapped_name, tensor))
loader = AutoWeightsLoader(
self,
skip_prefixes=["vit_pos_embed.pos_embed"],
ignore_unexpected_prefixes=["vae.", "latent_pos_embed.", "time_embedder.", "vae2llm."],
self, ignore_unexpected_prefixes=["vae.", "latent_pos_embed.", "time_embedder.", "vae2llm."]
)
loaded = loader.load_weights(
filtered_weights,
mapper=(self.hf_to_vllm_mapper) | WeightsMapper(orig_to_new_prefix={"vit_pos_embed.pos_embed": None}),
)
loaded = loader.load_weights(filtered_weights, mapper=self.hf_to_vllm_mapper)
loaded |= self._load_moe_gen_weights(moe_gen_weights)
@@ -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.
@@ -100,7 +103,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)
@@ -2,6 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
import os
from collections.abc import Iterable, Mapping, Sequence
from dataclasses import replace
from functools import partial
from math import gcd
from threading import Lock
@@ -10,7 +11,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
@@ -25,7 +25,6 @@ from vllm.multimodal.inputs import MultiModalFieldConfig, MultiModalKwargsItems
from vllm.multimodal.parse import MultiModalDataItems, MultiModalDataParser
from vllm.multimodal.processing import (
BaseDummyInputsBuilder,
BaseMultiModalProcessor,
BaseProcessingInfo,
ProcessorInputs,
PromptIndexTargets,
@@ -39,6 +38,7 @@ from vllm.v1.sample.ops.topk_topp_sampler import random_sample
from vllm.v1.sample.sampler import Sampler
from vllm_omni.data_entry_keys import EmbeddingsStruct, OmniPayloadStruct, to_dict, to_struct
from vllm_omni.inputs.mm_processor import OmniMultiModalProcessor
from vllm_omni.model_executor.models.cosyvoice3.tokenizer import get_qwen_tokenizer
from vllm_omni.model_executor.models.cosyvoice3.utils import (
concat_text_with_prompt_ids,
@@ -52,6 +52,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__)
@@ -108,7 +109,45 @@ class CosyVoice3MultiModalProcessingInfo(BaseProcessingInfo):
)
class CosyVoice3MultiModalProcessor(BaseMultiModalProcessor[CosyVoice3MultiModalProcessingInfo]):
class CosyVoice3MultiModalProcessor(OmniMultiModalProcessor[CosyVoice3MultiModalProcessingInfo]):
def apply(self, inputs: ProcessorInputs, timing_ctx):
tokenizer = self.info.get_tokenizer()
prompt_text = tokenizer.decode(inputs.prompt, skip_special_tokens=False)
config = self.info.ctx.get_hf_config()
model_dir = self.info.ctx.model_config.model
self._ensure_cached_runtime_components(model_dir, config)
text_token, text_token_len = extract_text_token(
prompt_text,
self.tokenizer,
config.allowed_special,
)
if inputs.mm_data_items.get_all_counts().get("audio", 0):
reference_text = inputs.hf_processor_mm_kwargs.get("prompt_text")
if not isinstance(reference_text, str):
raise ValueError(f"prompt text is None : {reference_text}")
prompt_text_token, prompt_text_token_len = extract_text_token(
reference_text,
self.tokenizer,
config.allowed_special,
)
text_token, _ = concat_text_with_prompt_ids(
text_token,
text_token_len,
prompt_text_token,
prompt_text_token_len,
)
inputs = replace(
inputs,
prompt=text_token.reshape(-1).tolist(),
hf_processor_mm_kwargs={
**inputs.hf_processor_mm_kwargs,
self._OMNI_PROMPT_TEXT_KEY: prompt_text,
},
)
return super().apply(inputs, timing_ctx)
def _ensure_cached_runtime_components(self, model_dir: str, config: CosyVoice3Config) -> None:
cached_model_dir = getattr(self, "_cached_model_dir", None)
if cached_model_dir == model_dir:
@@ -137,7 +176,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),
@@ -376,15 +415,6 @@ class CosyVoice3MultiModalProcessor(BaseMultiModalProcessor[CosyVoice3MultiModal
"embedding": MultiModalFieldConfig.batched("audio"),
}
def _hf_processor_applies_updates(
self,
prompt_text: str,
mm_items: MultiModalDataItems,
hf_processor_mm_kwargs: Mapping[str, object],
tokenization_kwargs: Mapping[str, object],
) -> bool:
return False
def _get_prompt_updates(
self,
mm_items: MultiModalDataItems,
@@ -463,7 +493,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 +948,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.
from collections.abc import Iterable, Mapping, Sequence
from typing import Any
@@ -17,7 +20,6 @@ from vllm.multimodal.inputs import MultiModalFieldConfig
from vllm.multimodal.parse import MultiModalDataItems, MultiModalDataParser
from vllm.multimodal.processing import (
BaseDummyInputsBuilder,
BaseMultiModalProcessor,
BaseProcessingInfo,
ProcessorInputs,
PromptReplacement,
@@ -26,6 +28,7 @@ from vllm.multimodal.processing import (
from vllm.sequence import IntermediateTensors
from vllm.v1.sample.metadata import SamplingMetadata
from vllm_omni.inputs.mm_processor import OmniMultiModalProcessor
from vllm_omni.model_executor.custom_process_mixin import CustomProcessMixin
from vllm_omni.model_executor.models.output_templates import OmniOutput
from vllm_omni.model_executor.models.utils import add_prefix_to_loaded_weights
@@ -106,10 +109,7 @@ class CovoAudioDummyInputsBuilder(BaseDummyInputsBuilder[CovoAudioProcessingInfo
)
class CovoAudioMultiModalProcessor(BaseMultiModalProcessor[CovoAudioProcessingInfo]):
def _hf_processor_applies_updates(self, prompt_text, mm_items, hf_processor_mm_kwargs, tokenization_kwargs) -> bool:
return False
class CovoAudioMultiModalProcessor(OmniMultiModalProcessor[CovoAudioProcessingInfo]):
def _call_hf_processor(
self, prompt: str, mm_data: Mapping[str, object], mm_kwargs: Mapping[str, Any], tok_kwargs: Mapping[str, object]
) -> BatchFeature:
@@ -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
"""Gepard-1.0 native-AR talker.
Single-stage AR TTS on a vLLM-native Qwen3.5 backbone. Each step samples one
@@ -22,7 +22,7 @@ import torch.nn as nn
from vllm.config import VllmConfig
from vllm.logger import init_logger
from vllm.model_executor.models.qwen3_5 import Qwen3_5ForCausalLM
from vllm.model_executor.models.utils import AutoWeightsLoader, maybe_prefix
from vllm.model_executor.models.utils import AutoWeightsLoader, WeightsMapper, maybe_prefix
from vllm.sequence import IntermediateTensors
from vllm_omni.model_executor.models.gepard.configuration_gepard import GepardConfig
@@ -199,8 +199,10 @@ class GepardTalkerForConditionalGeneration(nn.Module):
# NanoCodec loads lazily on first decode, so load_format=dummy and
# NeMo-less environments never pay for it.
loader = AutoWeightsLoader(self, skip_prefixes=["mtp.", "ref_compressor."])
return loader.load_weights(iter(rest))
loader = AutoWeightsLoader(self)
return loader.load_weights(
iter(rest), mapper=WeightsMapper(orig_to_new_prefix={"mtp.": None, "ref_compressor.": None})
)
def _get_or_create_state(self, request_id: str) -> _GepardState:
st = self._active_states.get(request_id)
@@ -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
# Adapted from
# https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm_image/modeling_glm_image.py
@@ -24,6 +24,7 @@
import math
import os
from collections.abc import Iterable, Mapping, Sequence
from dataclasses import replace
from functools import lru_cache
from typing import Annotated, Literal
@@ -81,7 +82,6 @@ from vllm.multimodal.inputs import (
MultiModalKwargsItems,
)
from vllm.multimodal.parse import (
ImageProcessorItems,
MultiModalDataItems,
MultiModalDataParser,
)
@@ -341,6 +341,30 @@ class GlmImageDummyInputsBuilder(BaseDummyInputsBuilder[GlmImageProcessingInfo])
}
_GLM_IMAGE_GRID_FACTOR = 32
def _build_target_shape_scaffold(processor, *, height: int, width: int, is_text_to_image: bool) -> str:
"""Return the grid scaffold HF appends to a GLM-Image generation prompt.
Mirrors ``GlmImageProcessor._build_prompt_with_target_shape`` (identical in
transformers 5.13 and 5.14) using only the processor's public token
attributes, so this does not depend on a private HF method that a stub or
a future release may not provide.
"""
factor = _GLM_IMAGE_GRID_FACTOR
token_h = (height // factor * factor) // factor
token_w = (width // factor * factor) // factor
grid_bos, grid_eos, bos = processor.grid_bos_token, processor.grid_eos_token, processor.bos_token
scaffold = f"{grid_bos}{token_h} {token_w}{grid_eos}"
if is_text_to_image:
ratio = token_h / token_w
prev_token_h = int(math.sqrt(ratio) * (factor // 2))
prev_token_w = int(math.sqrt(1 / ratio) * (factor // 2))
scaffold += f"{grid_bos}{prev_token_h} {prev_token_w}{grid_eos}"
return scaffold + bos
class GlmImageMultiModalProcessor(BaseMultiModalProcessor[GlmImageProcessingInfo]):
"""
Multimodal processor for GLM-Image.
@@ -358,265 +382,38 @@ class GlmImageMultiModalProcessor(BaseMultiModalProcessor[GlmImageProcessingInfo
return self._apply_hf_processor(inputs, timing_ctx)
return super()._cached_apply_hf_processor(inputs, timing_ctx)
def _call_hf_processor(
self,
prompt: str,
mm_data: Mapping[str, object],
mm_kwargs: Mapping[str, object],
tok_kwargs: Mapping[str, object],
) -> BatchFeature:
"""
Call the HuggingFace processor.
For text-to-image mode (no images), we need to:
1. Build the prompt with target grid dimensions
2. Build the image_grid_thw tensor for M-RoPE position encoding
For image-to-image mode:
1. Process source images through the image processor
2. Build prompt with image placeholders expanded
3. Build image_grid_thw including source and target grids
"""
processor = self.info.get_hf_processor()
# Get target dimensions from mm_kwargs or use defaults
target_h = mm_kwargs.get("target_h", 1024) if mm_kwargs else 1024
target_w = mm_kwargs.get("target_w", 1024) if mm_kwargs else 1024
logger.debug(
f"_call_hf_processor: target dimensions for generation: {target_h}x{target_w}, mm_kwargs={mm_kwargs}"
)
if not mm_data or not mm_data.get("images"):
# Text-to-image mode
if processor is not None:
# Build messages format expected by processor
messages = [{"role": "user", "content": [{"type": "text", "text": prompt}]}]
# Use apply_chat_template which handles target dimensions
hf_inputs = processor.apply_chat_template(
messages,
tokenize=True,
target_h=target_h,
target_w=target_w,
return_dict=True,
return_tensors="pt",
)
return hf_inputs
else:
# Fallback: just tokenize (this won't work properly for generation)
tokenizer = self.info.get_tokenizer()
prompt_ids = tokenizer.encode(prompt)
return BatchFeature(dict(input_ids=[prompt_ids]), tensor_type="pt")
# Image-to-image mode
# NOTE: Use "images" (plural) - this is what vLLM's ImageProcessorItems.get_processor_data() returns
images = mm_data.get("images")
if not isinstance(images, list):
images = [images]
logger.debug(
f"_call_hf_processor i2i: num_images={len(images)}, image_types={[type(img).__name__ for img in images]}"
)
if processor is not None:
# Build messages with image objects directly in content
# This is how GlmImageProcessor expects images - embedded in the content dict
# NOT as a separate images= parameter
#
# IMPORTANT: Remove <|image|> placeholders from prompt since apply_chat_template
# will automatically insert them for each image in content. Having both leads to
# index out of bounds when processing image_grid_thw.
clean_prompt = prompt.replace("<|image|>", "")
content = []
for img in images:
content.append({"type": "image", "image": img})
content.append({"type": "text", "text": clean_prompt})
messages = [{"role": "user", "content": content}]
logger.debug(f"_call_hf_processor: calling apply_chat_template with {len(images)} images in content")
# Use apply_chat_template - processor will process images when they're in content
hf_inputs = processor.apply_chat_template(
messages,
tokenize=True,
target_h=target_h,
target_w=target_w,
return_dict=True,
return_tensors="pt",
def apply(self, inputs, timing_ctx):
"""Add the generation scaffold before upstream expands source images."""
num_images = inputs.mm_data_items.get_all_counts().get("image", 0)
prompt_ids = list(inputs.prompt)
if num_images:
image_token_id = getattr(
self.info.get_hf_config(),
"image_token_id",
167855,
)
missing = num_images - prompt_ids.count(image_token_id)
if missing > 0:
prompt_ids = [image_token_id] * missing + prompt_ids
logger.debug(f"_call_hf_processor: apply_chat_template returned keys: {list(hf_inputs.keys())}")
# IMPORTANT (i2i): vLLM multimodal encoder must see source-only grids
# (matching pixel_values and number of images), but M-RoPE needs full
# grids (source + target) to compute correct decode positions.
image_grid_thw = hf_inputs.get("image_grid_thw")
if image_grid_thw is not None:
# Preserve full grids for M-RoPE.
hf_inputs["mrope_image_grid_thw"] = image_grid_thw
# Expose source-only grids for MM.
# In most i2i requests, we process one prompt at a time here,
# so `len(images)` is the number of source images.
num_source_images = len(images)
if image_grid_thw.shape[0] != num_source_images:
source_grids = image_grid_thw[:num_source_images]
hf_inputs["image_grid_thw"] = source_grids
logger.debug(
"_call_hf_processor: adjusted image_grid_thw for MM from %s to %s (num_source_images=%d)",
tuple(image_grid_thw.shape),
tuple(source_grids.shape),
num_source_images,
)
# Debug: Analyze input_ids for image tokens
input_ids = hf_inputs.get("input_ids")
if input_ids is not None:
if hasattr(input_ids, "tolist"):
ids_list = input_ids.tolist()
if isinstance(ids_list[0], list):
ids_list = ids_list[0] # Unbatch
else:
ids_list = list(input_ids)
# Get image token ID from config
hf_config = self.info.get_hf_config()
image_token_id = getattr(hf_config, "image_token_id", 167855)
# Count image tokens
image_token_count = ids_list.count(image_token_id)
logger.debug(
f"_call_hf_processor: input_ids length={len(ids_list)}, "
f"image_token_id={image_token_id}, "
f"image_token_count={image_token_count}"
)
# Log first/last few tokens to understand structure
logger.debug(f"_call_hf_processor: first 20 tokens: {ids_list[:20]}")
logger.debug(f"_call_hf_processor: last 20 tokens: {ids_list[-20:]}")
# Find positions of image tokens
image_positions = [i for i, t in enumerate(ids_list) if t == image_token_id]
if image_positions:
logger.debug(f"_call_hf_processor: image token positions (first 10): {image_positions[:10]}")
return hf_inputs
else:
# Fallback without processor - this is not ideal but prevents crashes
logger.warning("GlmImageProcessor not available, using fallback for i2i")
tokenizer = self.info.get_tokenizer()
hf_config = self.info.get_hf_config()
# Get image token
image_token_id = getattr(hf_config, "image_token_id", 167855)
try:
image_token = tokenizer.convert_ids_to_tokens(image_token_id)
except Exception:
image_token = "<|image|>"
# Build prompt with image placeholders
image_placeholders = image_token * len(images)
full_prompt = f"{image_placeholders}{prompt}"
prompt_ids = tokenizer.encode(full_prompt)
return BatchFeature(dict(input_ids=[prompt_ids]), tensor_type="pt")
def _apply_hf_processor_mm_only(
self,
mm_items: MultiModalDataItems,
hf_processor_mm_kwargs: Mapping[str, object],
tokenization_kwargs: Mapping[str, object],
) -> BatchFeature:
"""
Apply the HF processor on the multi-modal data only.
GLM-Image requires special handling because apply_chat_template always
adds a target <|image|> placeholder in addition to source image placeholders.
This causes an IndexError when the HF processor tries to find grid info
for the target placeholder (which doesn't exist for source-only processing).
Solution: Call the image processor directly to get pixel_values and
image_grid_thw, bypassing apply_chat_template's target handling.
"""
mm_counts = mm_items.get_all_counts()
num_images = mm_counts.get("image", 0)
if num_images == 0:
# No images - call parent implementation
return super()._apply_hf_processor_mm_only(
mm_items=mm_items,
hf_processor_mm_kwargs=hf_processor_mm_kwargs,
tokenization_kwargs=tokenization_kwargs,
)
# For i2i mode, we need to process images directly with the image processor
# to avoid the apply_chat_template target placeholder issue
processor = self.info.get_hf_processor()
image_processor = processor.image_processor
# Get images from mm_items
images = mm_items.get_items("image", ImageProcessorItems)
image_list = [images.get(i) for i in range(images.get_count())]
logger.debug(f"_apply_hf_processor_mm_only: processing {len(image_list)} images directly")
# Process images directly with image processor
image_inputs = image_processor(
images=image_list,
return_tensors="pt",
)
# Get grid info for source images only (no target)
pixel_values = image_inputs.get("pixel_values")
image_grid_thw = image_inputs.get("image_grid_thw")
if image_grid_thw is not None and image_grid_thw.shape[0] != num_images:
# Be defensive: some processors may include extra target grids.
image_grid_thw = image_grid_thw[:num_images]
image_inputs["image_grid_thw"] = image_grid_thw
logger.debug(
f"_apply_hf_processor_mm_only: pixel_values shape=\
{pixel_values.shape if pixel_values is not None else None}, "
f"image_grid_thw shape={image_grid_thw.shape if image_grid_thw is not None else None}"
)
# Build input_ids with image token placeholders
# The _get_prompt_updates returns PromptReplacement(target=[image_token_id], ...)
# which needs to find image tokens in input_ids to replace them.
# We need to include one image_token_id per image so the replacement can work.
tokenizer = self.info.get_tokenizer()
image_token_id = tokenizer.convert_tokens_to_ids("<|image|>")
# Build input_ids: [image_token] * num_images + tokenized text
# This way _apply_prompt_updates can find the image tokens and replace them
dummy_text = self.dummy_inputs.get_dummy_text(mm_counts)
text_ids = tokenizer.encode(dummy_text, add_special_tokens=False)
input_ids = [image_token_id] * num_images + text_ids
logger.debug(
f"_apply_hf_processor_mm_only: built input_ids with {num_images} image tokens + {len(text_ids)} text tokens"
# Append HF's target-shape scaffold without decoding/re-tokenizing the
# user's tokens. Text-to-image needs both target and preview grids; i2i
# needs only the target. Grid metadata alone does not supply these AR
# tokens.
target_grid = self._build_generation_grids(inputs.hf_processor_mm_kwargs)[0]
suffix = _build_target_shape_scaffold(
processor,
height=int(target_grid[1]) * 32,
width=int(target_grid[2]) * 32,
is_text_to_image=num_images == 0,
)
return BatchFeature(
dict(
input_ids=[input_ids],
pixel_values=pixel_values,
image_grid_thw=image_grid_thw,
),
tensor_type="pt",
)
def _apply_hf_processor_text_only(
self, prompt_text: str, hf_processor_mm_kwargs: Mapping[str, object], tokenization_kwargs: Mapping[str, object]
) -> list[int]:
prompt_ids, _, _ = super()._apply_hf_processor_text_mm(
prompt_text=prompt_text,
mm_items=MultiModalDataItems({}),
hf_processor_mm_kwargs=hf_processor_mm_kwargs,
tokenization_kwargs=tokenization_kwargs,
)
return prompt_ids
suffix_ids = tokenizer.encode(suffix, add_special_tokens=False)
if prompt_ids[-len(suffix_ids) :] != suffix_ids:
prompt_ids.extend(suffix_ids)
inputs = replace(inputs, prompt=prompt_ids)
return super().apply(inputs, timing_ctx)
def _build_generation_grids(self, hf_processor_mm_kwargs: Mapping[str, object]) -> torch.Tensor:
"""Build generation grids for M-RoPE decode positions.
@@ -661,171 +458,39 @@ class GlmImageMultiModalProcessor(BaseMultiModalProcessor[GlmImageProcessingInfo
def _apply_hf_processor_main(
self,
prompt: str | list[int],
mm_items: MultiModalDataItems,
hf_processor_mm_kwargs: Mapping[str, object],
tokenization_kwargs: Mapping[str, object],
*,
enable_hf_prompt_update: bool,
) -> tuple[list[int], BatchFeature, bool]:
"""
Override to handle GLM-Image i2i mode correctly.
Problem: When vLLM processes cached mm items (enable_hf_prompt_update=False),
the base implementation:
1. Gets prompt_ids from _apply_hf_processor_text_only (no image tokens)
2. Gets mm_data from _apply_hf_processor_mm_only
3. Returns is_update_applied=False
This causes _apply_prompt_updates to fail because prompt_ids has no image tokens.
Solution: For i2i mode, we build prompt_ids that include image placeholders,
and return is_update_applied=False so _apply_prompt_updates can expand them.
"""
) -> BatchFeature:
"""Process source images under vLLM's token-only prompt contract."""
mm_counts = mm_items.get_all_counts()
num_images = mm_counts.get("image", 0)
if num_images == 0:
return BatchFeature({"mrope_image_grid_thw": self._build_generation_grids(hf_processor_mm_kwargs)})
logger.debug(f"_apply_hf_processor_main: mm_counts={mm_counts}, num_images={num_images}")
valid_mm_items = mm_items.select({key for key, count in mm_counts.items() if count > 0})
processor_data, passthrough_data = self._get_hf_mm_data(valid_mm_items)
images = processor_data.get("images")
if not images:
return BatchFeature(dict(passthrough_data))
if num_images == 0 and isinstance(prompt, str):
# t2i mode or normal flow - use parent implementation
prompt_ids = self._apply_hf_processor_text_only(
prompt_text=prompt,
hf_processor_mm_kwargs=hf_processor_mm_kwargs,
tokenization_kwargs=tokenization_kwargs,
)
mm_processed_data = self._apply_hf_processor_mm_only(
mm_items=mm_items,
hf_processor_mm_kwargs=hf_processor_mm_kwargs,
tokenization_kwargs=tokenization_kwargs,
)
# t2i has no source images, so mm features cannot provide image_grid_thw.
# Provide explicit generation grids for M-RoPE to avoid fallback token parsing
# (which can degrade high-resolution spatial positions, e.g. 1920x1920).
try:
mrope_grid_thw = self._build_generation_grids(hf_processor_mm_kwargs)
mm_processed_data["mrope_image_grid_thw"] = mrope_grid_thw
logger.debug(
"_apply_hf_processor_main t2i: mrope_image_grid_thw=%s",
mrope_grid_thw.tolist(),
)
except Exception as e:
logger.warning("_apply_hf_processor_main t2i: failed to set mrope_image_grid_thw: %s", e)
return prompt_ids, mm_processed_data, False
# i2i mode: use unified HF processor path only.
# This avoids drift between duplicated manual/HF i2i implementations.
logger.debug(
"_apply_hf_processor_main: i2i mode (enable_hf_prompt_update=%s), num_images=%s",
enable_hf_prompt_update,
num_images,
processor = self.info.get_hf_processor()
image_inputs = processor.image_processor(
images=list(images),
return_tensors="pt",
)
image_grid_thw = image_inputs.get("image_grid_thw")
if image_grid_thw is not None:
source_grid_thw = image_grid_thw[:num_images]
image_inputs["image_grid_thw"] = source_grid_thw
if not isinstance(prompt, str):
# Online OpenAI chat preprocessing can arrive here with tokenized
# prompts (list[int]) before serving_chat replaces engine prompt
# with the clean text prompt. Do not fail the whole request.
logger.warning(
"_apply_hf_processor_main i2i: got tokenized prompt type=%s; "
"using compatibility path for preprocessing",
type(prompt).__name__,
target_grid = self._build_generation_grids(hf_processor_mm_kwargs)[:1].to(dtype=source_grid_thw.dtype)
image_inputs["mrope_image_grid_thw"] = torch.cat(
[source_grid_thw, target_grid],
dim=0,
)
prompt_ids = list(prompt)
mm_processed_data = self._apply_hf_processor_mm_only(
mm_items=mm_items,
hf_processor_mm_kwargs=hf_processor_mm_kwargs,
tokenization_kwargs=tokenization_kwargs,
)
# Preserve full grids for M-RoPE decode (source + target), while
# keeping image_grid_thw source-only for MM batching.
try:
source_grid_thw = mm_processed_data.get("image_grid_thw")
if source_grid_thw is not None and isinstance(source_grid_thw, torch.Tensor):
target_h = (
hf_processor_mm_kwargs.get("target_h")
if isinstance(hf_processor_mm_kwargs.get("target_h"), int)
else None
)
target_w = (
hf_processor_mm_kwargs.get("target_w")
if isinstance(hf_processor_mm_kwargs.get("target_w"), int)
else None
)
if target_h is None or target_w is None:
target_h = (
hf_processor_mm_kwargs.get("height")
if isinstance(hf_processor_mm_kwargs.get("height"), int)
else 1024
)
target_w = (
hf_processor_mm_kwargs.get("width")
if isinstance(hf_processor_mm_kwargs.get("width"), int)
else 1024
)
factor = 32
token_h = max(1, target_h // factor)
token_w = max(1, target_w // factor)
target_grid = torch.tensor([[1, token_h, token_w]], dtype=source_grid_thw.dtype)
mm_processed_data["mrope_image_grid_thw"] = torch.cat([source_grid_thw, target_grid], dim=0)
except Exception:
pass
# Prompt updates will expand image placeholders in this compatibility path.
return prompt_ids, mm_processed_data, False
images = mm_items.get_items("image", ImageProcessorItems)
image_list = [images.get(i) for i in range(images.get_count())]
if not image_list:
raise ValueError("GLM-Image i2i requires at least one source image in mm_items")
hf_inputs = self._call_hf_processor(
prompt=prompt,
mm_data={"images": image_list},
mm_kwargs=hf_processor_mm_kwargs,
tok_kwargs=tokenization_kwargs,
)
input_ids = hf_inputs.get("input_ids")
if input_ids is None:
raise ValueError("HF i2i processor returned no input_ids")
if isinstance(input_ids, torch.Tensor):
prompt_ids = input_ids[0].tolist() if input_ids.dim() > 1 else input_ids.tolist()
else:
prompt_ids = (
input_ids[0]
if isinstance(input_ids, list) and input_ids and isinstance(input_ids[0], list)
else list(input_ids)
)
mm_processed_data = BatchFeature(dict(), tensor_type="pt")
for key in ("pixel_values", "image_grid_thw", "mrope_image_grid_thw"):
value = hf_inputs.get(key)
if value is not None:
mm_processed_data[key] = value
image_grid_thw = mm_processed_data.get("image_grid_thw")
mrope_grid_thw = mm_processed_data.get("mrope_image_grid_thw")
hf_config = self.info.get_hf_config()
image_token_id = getattr(hf_config, "image_token_id", 167855)
image_token_count = prompt_ids.count(image_token_id)
logger.debug(
"_apply_hf_processor_main i2i(HF): num_images=%s, prompt_len=%s, image_token_count=%s, "
"source_grid_shape=%s, mrope_grid_shape=%s",
num_images,
len(prompt_ids),
image_token_count,
tuple(image_grid_thw.shape) if image_grid_thw is not None else None,
tuple(mrope_grid_thw.shape) if mrope_grid_thw is not None else None,
)
# HF processor already expanded image placeholders in input_ids.
return prompt_ids, mm_processed_data, True
image_inputs.update(passthrough_data)
return image_inputs
def _get_mm_fields_config(
self,
@@ -836,7 +501,7 @@ class GlmImageMultiModalProcessor(BaseMultiModalProcessor[GlmImageProcessingInfo
Get the multimodal field configuration.
For GLM-Image i2i mode:
- image_grid_thw has been sliced in _call_hf_processor to only include source images
- image_grid_thw contains only source grids from _apply_hf_processor_main
- pixel_values has shape [total_patches, C, H, W] - only for source images
For t2i mode:
@@ -844,7 +509,7 @@ class GlmImageMultiModalProcessor(BaseMultiModalProcessor[GlmImageProcessingInfo
"""
result = {}
# Get image_grid_thw if present (already sliced in _call_hf_processor)
# Get the source-only image_grid_thw if present.
image_grid_thw = hf_inputs.get("image_grid_thw")
if "pixel_values" in hf_inputs and image_grid_thw is not None:
@@ -861,45 +526,21 @@ class GlmImageMultiModalProcessor(BaseMultiModalProcessor[GlmImageProcessingInfo
result["pixel_values"] = MultiModalFieldConfig.flat_from_sizes("image", image_grid_sizes)
# Register image_grid_thw - it's been sliced in _call_hf_processor
# Register image_grid_thw - it's been sliced in _apply_hf_processor_main
# to only include source image grids, so batching will work correctly
result["image_grid_thw"] = MultiModalFieldConfig.batched("image")
if "mrope_image_grid_thw" in hf_inputs:
result["mrope_image_grid_thw"] = MultiModalFieldConfig.shared(
"image",
num_source_images,
keep_on_cpu=True,
)
logger.debug(f"_get_mm_fields_config: result keys: {list(result.keys())}")
return result
def _hf_processor_applies_updates(
self,
prompt_text: str,
mm_items: MultiModalDataItems,
hf_processor_mm_kwargs: Mapping[str, object],
tokenization_kwargs: Mapping[str, object],
) -> bool:
"""
Return whether the HF processor applies prompt updates.
For GLM-Image i2i mode, the HF processor's apply_chat_template already
expands <|image|> to N tokens (e.g., 4096 for 64x64 grid).
By returning True, we tell vLLM that HF processor DID apply prompt updates,
so vLLM will use _find_mm_placeholders to locate the expanded tokens
instead of trying to apply replacements.
For t2i mode (no images), there are no image placeholders to expand.
"""
# Check if we have images (i2i mode)
num_images = mm_items.get_all_counts().get("image", 0)
if num_images > 0:
logger.debug(
f"_hf_processor_applies_updates: returning True for i2i mode "
f"(num_images={num_images}) - HF processor already expanded tokens"
)
return True
# For t2i mode (no images), use default behavior
return True
def _get_prompt_updates(
self,
mm_items: MultiModalDataItems,
@@ -909,17 +550,8 @@ class GlmImageMultiModalProcessor(BaseMultiModalProcessor[GlmImageProcessingInfo
"""
Get prompt updates for image tokens.
For GLM-Image image-to-image mode, the HF processor's apply_chat_template
already expands each <|image|> placeholder to the correct number of
image tokens (grid_h * grid_w tokens per source image).
The HF processor does:
1. Replace each <|image|> with num_image_tokens copies of <|placeholder|>
2. Replace all <|placeholder|> back to <|image|>
So the tokenized input already has the expanded tokens. We use
target=[image_token_id] to match each occurrence of the image token,
similar to how Qwen2VL handles this pattern.
Expand each source-image placeholder into grid_h * grid_w image tokens
through vLLM's token-based prompt updates.
We use image_grid_thw from out_mm_kwargs to get the actual processed grid
size, following the Qwen2VL pattern. This is critical because the HF processor
@@ -930,8 +562,7 @@ class GlmImageMultiModalProcessor(BaseMultiModalProcessor[GlmImageProcessingInfo
"""
hf_config = self.info.get_hf_config()
# Get image token ID - this is the token that appears multiple times
# in the tokenized input after HF processor expansion
# Match the source-image placeholder in the tokenized input.
image_token_id = getattr(hf_config, "image_token_id", 167855)
# Debug: log mm_items info
@@ -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.
@@ -39,7 +39,6 @@ from vllm.multimodal.inputs import MultiModalFieldConfig, MultiModalKwargsItems
from vllm.multimodal.parse import MultiModalDataItems, MultiModalDataParser
from vllm.multimodal.processing import (
BaseDummyInputsBuilder,
BaseMultiModalProcessor,
BaseProcessingInfo,
ProcessorInputs,
PromptIndexTargets,
@@ -51,6 +50,7 @@ from vllm.v1.outputs import SamplerOutput
from vllm.v1.sample.metadata import SamplingMetadata
from vllm.v1.sample.sampler import Sampler
from vllm_omni.inputs.mm_processor import OmniMultiModalProcessor
from vllm_omni.model_executor.models.common.nucleus_ras_sampling import ras_sample_one as _ras_sample_one
from vllm_omni.model_executor.models.output_templates import OmniOutput
from vllm_omni.platforms import current_omni_platform
@@ -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:
@@ -364,7 +364,7 @@ class GLMTTSMultiModalProcessingInfo(BaseProcessingInfo):
)
class GLMTTSMultiModalProcessor(BaseMultiModalProcessor[GLMTTSMultiModalProcessingInfo]):
class GLMTTSMultiModalProcessor(OmniMultiModalProcessor[GLMTTSMultiModalProcessingInfo]):
"""GLM-TTS voice-clone processor.
Unlike CosyVoice3, GLM-TTS prompt speech tokens are normal Llama vocab IDs
@@ -373,6 +373,53 @@ class GLMTTSMultiModalProcessor(BaseMultiModalProcessor[GLMTTSMultiModalProcessi
handoff.
"""
def apply(self, inputs: ProcessorInputs, timing_ctx):
source_tokenizer = self.info.get_tokenizer()
prompt_text = source_tokenizer.decode(
inputs.prompt,
skip_special_tokens=False,
)
config = self.info.ctx.get_hf_config()
model_dir = self.info.ctx.model_config.model
self._ensure_cached_runtime_components(
model_dir,
config,
load_voice_clone=False,
)
normalized_text = _normalize_glm_tts_processor_text(
self.text_frontend,
prompt_text,
)
text_ids = self._encode_text(normalized_text)
prompt_parts = []
if inputs.mm_data_items.get_all_counts().get("audio", 0):
reference_text = inputs.hf_processor_mm_kwargs.get("prompt_text")
if not isinstance(reference_text, str) or not reference_text.strip():
raise ValueError("GLM-TTS voice cloning requires mm_processor_kwargs['prompt_text'].")
normalized_reference = _normalize_glm_tts_processor_text(
self.text_frontend,
reference_text,
add_trailing_space=True,
)
prompt_parts.append(self._encode_text(normalized_reference))
prompt_parts.extend(
[
text_ids,
torch.tensor([[int(self.special_ids["boa"])]], dtype=torch.long),
]
)
prompt_ids = torch.cat(prompt_parts, dim=1).reshape(-1).tolist()
inputs = replace(
inputs,
prompt=prompt_ids,
hf_processor_mm_kwargs={
**inputs.hf_processor_mm_kwargs,
self._OMNI_PROMPT_TEXT_KEY: prompt_text,
},
)
return super().apply(inputs, timing_ctx)
def _ensure_cached_runtime_components(
self,
model_dir: str,
@@ -599,15 +646,6 @@ class GLMTTSMultiModalProcessor(BaseMultiModalProcessor[GLMTTSMultiModalProcessi
if key in hf_inputs
}
def _hf_processor_applies_updates(
self,
prompt_text: str,
mm_items: MultiModalDataItems,
hf_processor_mm_kwargs: Mapping[str, object],
tokenization_kwargs: Mapping[str, object],
) -> bool:
return False
def _cached_apply_hf_processor(self, inputs: ProcessorInputs, timing_ctx: Any):
# GLM-TTS builds the actual AR prompt from both the request text and
# mm_processor_kwargs["prompt_text"]. The base cache path separates text
@@ -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}/*"],
)
@@ -1669,8 +1669,10 @@ class _BackboneWrapper(nn.Module):
self.config = config
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
from vllm.model_executor.models.utils import AutoWeightsLoader
from vllm.model_executor.models.utils import AutoWeightsLoader, WeightsMapper
skip = ["lm_head."] if getattr(self.config, "tie_word_embeddings", False) else None
loader = AutoWeightsLoader(self, skip_prefixes=skip)
return loader.load_weights(weights)
loader = AutoWeightsLoader(self)
return loader.load_weights(
weights, mapper=WeightsMapper(orig_to_new_prefix={name: None for name in (skip or ())})
)
@@ -0,0 +1,625 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
#
# Vendored from vllm/model_executor/models/hunyuan_v1.py at vllm@2cf0a6915c
# (the upstream base vllm-omni origin/main was rebased against). Upstream
# removed the native HunYuan V1 implementation in #53272 / #53615 (migrated
# to the Transformers modeling backend). vllm-omni's HunyuanImage3 model
# subclasses the removed HunYuanModel / HunYuanSparseMoeBlock / HunYuanMLP,
# so those internals are preserved here to keep the omni diffusion model
# working against current upstream.
# Weight loading, expert mapping, and QKV splitting are owned by Omni's
# HunyuanModel subclass; their unused upstream implementations are omitted.
"""Inference-only HunYuan V1 internals vendored for vllm-omni HunyuanImage3."""
from itertools import islice
import torch
from torch import nn
from transformers import PretrainedConfig
from vllm.compilation.decorators import support_torch_compile
from vllm.config import CacheConfig, VllmConfig, get_current_vllm_config
from vllm.distributed import (
get_ep_group,
get_pp_group,
get_tensor_model_parallel_world_size,
)
from vllm.model_executor.layers.activation import SiluAndMul
from vllm.model_executor.layers.attention import Attention
from vllm.model_executor.layers.fused_moe import (
FusedMoEFactory,
)
from vllm.model_executor.layers.layernorm import RMSNorm
from vllm.model_executor.layers.linear import (
ColumnParallelLinear,
MergedColumnParallelLinear,
QKVParallelLinear,
ReplicatedLinear,
RowParallelLinear,
)
from vllm.model_executor.layers.quantization import QuantizationConfig
from vllm.model_executor.layers.rotary_embedding import get_rope
from vllm.model_executor.layers.vocab_parallel_embedding import (
VocabParallelEmbedding,
)
from vllm.model_executor.models.interfaces import EagleModelMixin
from vllm.model_executor.models.utils import (
PPMissingLayer,
make_layers,
)
from vllm.sequence import IntermediateTensors
from vllm.v1.attention.backend import AttentionType
def _is_moe(config: PretrainedConfig) -> bool:
num_experts = getattr(config, "num_experts", None)
if isinstance(num_experts, int):
return num_experts > 1
if isinstance(num_experts, list) and num_experts:
# Ensure all elements are integers before calling max.
if all(isinstance(e, int) for e in num_experts):
return max(num_experts) > 1
else:
return False
return False
def _get_cla_factor(config: PretrainedConfig) -> int:
if not getattr(config, "use_cla", False):
return 1
return getattr(config, "cla_share_factor", 1)
class HunYuanMLP(nn.Module):
def __init__(
self,
hidden_size: int,
intermediate_size: int,
hidden_act: str,
quant_config: QuantizationConfig | None = None,
bias: bool = False,
prefix: str = "",
reduce_results: bool = True,
) -> None:
super().__init__()
self.gate_up_proj = MergedColumnParallelLinear(
input_size=hidden_size,
output_sizes=[intermediate_size] * 2,
bias=bias,
quant_config=quant_config,
prefix=f"{prefix}.gate_up_proj",
)
self.down_proj = RowParallelLinear(
input_size=intermediate_size,
output_size=hidden_size,
bias=bias,
quant_config=quant_config,
prefix=f"{prefix}.down_proj",
reduce_results=reduce_results,
)
if hidden_act != "silu":
raise ValueError(f"Unsupported activation: {hidden_act}. Only silu is supported for now.")
self.act_fn = SiluAndMul()
def forward(self, x):
gate_up, _ = self.gate_up_proj(x)
x = self.act_fn(gate_up)
x, _ = self.down_proj(x)
return x
class HunYuanAttention(nn.Module):
def __init__(
self,
config: PretrainedConfig,
hidden_size: int,
num_heads: int,
num_kv_heads: int,
max_position_embeddings: int = 8192,
quant_config: QuantizationConfig | None = None,
bias: bool = False,
cache_config: CacheConfig | None = None,
prefix: str = "",
layer_id: int = -1,
) -> None:
super().__init__()
self.hidden_size = hidden_size
tp_size = get_tensor_model_parallel_world_size()
self.total_num_heads = num_heads
assert self.total_num_heads % tp_size == 0
self.num_heads = self.total_num_heads // tp_size
self.total_num_kv_heads = num_kv_heads
if self.total_num_kv_heads >= tp_size:
# Number of KV heads is greater than TP size, so we partition
# the KV heads across multiple tensor parallel GPUs.
assert self.total_num_kv_heads % tp_size == 0
else:
# Number of KV heads is less than TP size, so we replicate
# the KV heads across multiple tensor parallel GPUs.
assert tp_size % self.total_num_kv_heads == 0
self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size)
if hasattr(config, "head_dim") and config.head_dim:
self.head_dim = config.head_dim
elif hasattr(config, "attention_head_dim"):
self.head_dim = config.attention_head_dim
else:
self.head_dim = self.hidden_size // self.total_num_heads
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.max_position_embeddings = max_position_embeddings
self.use_qk_norm = getattr(config, "use_qk_norm", False)
self.layer_id = layer_id
self.qkv_proj = QKVParallelLinear(
hidden_size=hidden_size,
head_size=self.head_dim,
total_num_heads=self.total_num_heads,
total_num_kv_heads=self.total_num_kv_heads,
bias=bias,
quant_config=quant_config,
prefix=f"{prefix}.qkv_proj",
)
self.o_proj = RowParallelLinear(
input_size=self.total_num_heads * self.head_dim,
output_size=hidden_size,
bias=bias,
quant_config=quant_config,
prefix=f"{prefix}.o_proj",
)
self.rotary_emb = get_rope(
self.head_dim,
max_position=max_position_embeddings,
rope_parameters=config.rope_parameters,
is_neox_style=True,
)
self.attn = Attention(
self.num_heads,
self.head_dim,
self.scaling,
num_kv_heads=self.num_kv_heads,
cache_config=cache_config,
quant_config=quant_config,
prefix=f"{prefix}.attn",
)
if self.use_qk_norm:
self.query_layernorm = RMSNorm(self.head_dim, eps=config.rms_norm_eps)
self.key_layernorm = RMSNorm(self.head_dim, eps=config.rms_norm_eps)
def forward(
self,
positions: torch.Tensor,
hidden_states: torch.Tensor,
kv_states: tuple[torch.Tensor] | None = None,
) -> torch.Tensor:
qkv, _ = self.qkv_proj(hidden_states)
q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
q, k = self.rotary_emb(positions, q, k)
ori_k = k
if self.use_qk_norm:
q = self.query_layernorm(
q.view(-1, self.num_heads, self.head_dim),
)
k = self.key_layernorm(
k.view(-1, self.num_kv_heads, self.head_dim),
)
attn_output = self.attn(q, k, v)
# For o_proj
attn_output = attn_output.view(q.shape[0], -1)
output, _ = self.o_proj(attn_output)
return output, (ori_k, v)
class HunYuanCrossAttention(nn.Module):
def __init__(
self,
config: PretrainedConfig,
hidden_size: int,
num_heads: int,
num_kv_heads: int,
max_position_embeddings: int = 8192,
quant_config: QuantizationConfig | None = None,
bias: bool = False,
cache_config: CacheConfig | None = None,
prefix: str = "",
layer_id: int = -1,
) -> None:
super().__init__()
self.hidden_size = hidden_size
tp_size = get_tensor_model_parallel_world_size()
self.total_num_heads = num_heads
assert self.total_num_heads % tp_size == 0
self.num_heads = self.total_num_heads // tp_size
self.total_num_kv_heads = num_kv_heads
if self.total_num_kv_heads >= tp_size:
# Number of KV heads is greater than TP size, so we partition
# the KV heads across multiple tensor parallel GPUs.
assert self.total_num_kv_heads % tp_size == 0
else:
# Number of KV heads is less than TP size, so we replicate
# the KV heads across multiple tensor parallel GPUs.
assert tp_size % self.total_num_kv_heads == 0
self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size)
# MistralConfig has an optional head_dim introduced by Mistral-Nemo
if hasattr(config, "head_dim"):
self.head_dim = config.head_dim
elif hasattr(config, "attention_head_dim"):
self.head_dim = config.attention_head_dim
else:
self.head_dim = self.hidden_size // self.total_num_heads
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.max_position_embeddings = max_position_embeddings
self.use_qk_norm = getattr(config, "use_qk_norm", False)
self.layer_id = layer_id
self.q_proj = ColumnParallelLinear(
hidden_size,
hidden_size,
bias=bias,
quant_config=quant_config,
prefix=f"{prefix}.q_proj",
)
self.o_proj = RowParallelLinear(
input_size=self.total_num_heads * self.head_dim,
output_size=hidden_size,
bias=bias,
quant_config=quant_config,
prefix=f"{prefix}.o_proj",
)
self.rotary_emb = get_rope(
self.head_dim,
max_position=max_position_embeddings,
rope_parameters=config.rope_parameters,
is_neox_style=True,
)
self.attn = Attention(
self.num_heads,
self.head_dim,
self.scaling,
num_kv_heads=self.num_kv_heads,
cache_config=cache_config,
quant_config=quant_config,
prefix=f"{prefix}.attn",
attn_type=AttentionType.ENCODER_DECODER,
)
if self.use_qk_norm:
self.query_layernorm = RMSNorm(self.head_dim, eps=config.rms_norm_eps)
self.key_layernorm = RMSNorm(self.head_dim, eps=config.rms_norm_eps)
def forward(
self,
positions: torch.Tensor,
hidden_states: torch.Tensor,
kv_states: tuple[torch.Tensor] | None = None,
) -> torch.Tensor:
assert kv_states is not None
ori_k, v = kv_states # use last layer kv,
k = ori_k
q, _ = self.q_proj(hidden_states)
k_tmp = torch.empty_like(k) # Todo: reduant rotary embedding
q, _ = self.rotary_emb(positions, q, k_tmp)
if self.use_qk_norm:
q = self.query_layernorm(
q.view(-1, self.num_heads, self.head_dim),
)
k = self.key_layernorm(
k.view(-1, self.num_kv_heads, self.head_dim),
)
attn_output = self.attn(q, k, v)
# For o_proj
attn_output = attn_output.view(q.shape[0], -1)
output, _ = self.o_proj(attn_output)
return output, (ori_k, v)
class HunYuanSparseMoeBlock(nn.Module):
def __init__(
self,
config: PretrainedConfig,
quant_config: QuantizationConfig | None = None,
layer_id: int = -1,
prefix: str = "",
enable_eplb: bool = False,
):
super().__init__()
self.tp_size = get_tensor_model_parallel_world_size()
self.ep_group = get_ep_group().device_group
self.ep_size = self.ep_group.size()
self.n_routed_experts = config.num_experts
if self.tp_size > config.num_experts:
raise ValueError(
f"Tensor parallel size {self.tp_size} is greater than the number of experts {config.num_experts}."
)
# Get layer_id topk if config.moe_topk is a list
if isinstance(config.moe_topk, list):
assert layer_id >= 0
assert len(config.moe_topk) > layer_id
top_k = config.moe_topk[layer_id]
else:
top_k = config.moe_topk
# If it is moe, moe_intermediate_size is preferred
intermediate_size = config.intermediate_size
if config.moe_intermediate_size is not None:
intermediate_size = (
config.moe_intermediate_size
if isinstance(config.moe_intermediate_size, int)
else config.moe_intermediate_size[layer_id]
)
# Load balancing settings.
vllm_config = get_current_vllm_config()
eplb_config = vllm_config.parallel_config.eplb_config
self.enable_eplb = enable_eplb
self.n_logical_experts = self.n_routed_experts
self.n_redundant_experts = eplb_config.num_redundant_experts
self.n_physical_experts = self.n_logical_experts + self.n_redundant_experts
self.n_local_physical_experts = self.n_physical_experts // self.ep_size
self.gate = ReplicatedLinear(
config.hidden_size,
config.num_experts,
bias=False,
quant_config=None,
prefix=f"{prefix}.gate",
)
if config.use_mixed_mlp_moe > 0:
# Get layer_id num_shared_expert if config.num_shared_expert is
# a list.
if isinstance(config.num_shared_expert, list):
assert layer_id >= 0
assert len(config.num_shared_expert) > layer_id
num_shared_expert = config.num_shared_expert[layer_id]
else:
num_shared_expert = config.num_shared_expert
self.shared_mlp = HunYuanMLP(
hidden_size=config.hidden_size,
intermediate_size=config.intermediate_size * num_shared_expert,
hidden_act=config.hidden_act,
quant_config=quant_config,
reduce_results=False,
prefix=f"{prefix}.shared_mlp",
)
else:
self.shared_mlp = None
self.experts = FusedMoEFactory(
shared_experts=self.shared_mlp,
num_experts=self.n_routed_experts,
top_k=top_k,
hidden_size=config.hidden_size,
intermediate_size=intermediate_size,
renormalize=top_k > 1,
quant_config=quant_config,
prefix=f"{prefix}.experts",
enable_eplb=self.enable_eplb,
num_redundant_experts=self.n_redundant_experts,
)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
# NOTE: hidden_states can have either 1D or 2D shape.
orig_shape = hidden_states.shape
hidden_dim = hidden_states.shape[-1]
hidden_states = hidden_states.view(-1, hidden_dim)
# router_logits: (num_tokens, n_experts)
router_logits, _ = self.gate(hidden_states)
final_hidden_states = self.experts(hidden_states=hidden_states, router_logits=router_logits)
return final_hidden_states.view(orig_shape)
class HunYuanDecoderLayer(nn.Module):
def __init__(
self,
config: PretrainedConfig,
cache_config: CacheConfig | None = None,
quant_config: QuantizationConfig | None = None,
prefix: str = "",
layer_id: int = -1,
enable_eplb: bool = False,
) -> None:
super().__init__()
assert layer_id >= 0
self.layer_id = layer_id
self.hidden_size = config.hidden_size
self.intermediate_size = (
config.intermediate_size
if isinstance(config.intermediate_size, int)
else config.intermediate_size[layer_id]
)
max_position_embeddings = getattr(config, "max_position_embeddings", 8192)
attention_bias = getattr(config, "attention_bias", False) or getattr(config, "bias", False)
cla_factor = _get_cla_factor(config)
attention_type = (
AttentionType.ENCODER_DECODER if layer_id >= 0 and layer_id % cla_factor != 0 else AttentionType.DECODER
)
if attention_type == AttentionType.DECODER:
self.self_attn = HunYuanAttention(
config=config,
hidden_size=self.hidden_size,
num_heads=config.num_attention_heads,
num_kv_heads=getattr(config, "num_key_value_heads", config.num_attention_heads),
max_position_embeddings=max_position_embeddings,
quant_config=quant_config,
bias=attention_bias,
cache_config=cache_config,
prefix=f"{prefix}.self_attn",
layer_id=layer_id,
)
elif attention_type == AttentionType.ENCODER_DECODER:
self.self_attn = HunYuanCrossAttention(
config=config,
hidden_size=self.hidden_size,
num_heads=config.num_attention_heads,
num_kv_heads=getattr(config, "num_key_value_heads", config.num_attention_heads),
max_position_embeddings=max_position_embeddings,
quant_config=quant_config,
bias=attention_bias,
cache_config=cache_config,
prefix=f"{prefix}.self_attn",
layer_id=layer_id,
)
else:
raise RuntimeError(f"Unsupported attention type: {attention_type}")
if _is_moe(config):
self.mlp = HunYuanSparseMoeBlock(
config=config,
quant_config=quant_config,
layer_id=layer_id,
prefix=f"{prefix}.mlp",
enable_eplb=enable_eplb,
)
else:
self.mlp = HunYuanMLP(
hidden_size=self.hidden_size,
intermediate_size=self.intermediate_size,
hidden_act=config.hidden_act,
quant_config=quant_config,
bias=getattr(config, "mlp_bias", False),
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(
self,
positions: torch.Tensor,
hidden_states: torch.Tensor,
residual: torch.Tensor | None,
kv_states: tuple[torch.Tensor] | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
# Self Attention
if residual is None:
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
else:
hidden_states, residual = self.input_layernorm(hidden_states, residual)
hidden_states, ori_kv_states = self.self_attn(
positions=positions,
hidden_states=hidden_states,
kv_states=kv_states,
)
# Fully Connected
hidden_states, residual = self.post_attention_layernorm(hidden_states, residual)
hidden_states = self.mlp(hidden_states)
return hidden_states, residual, ori_kv_states
@support_torch_compile(
dynamic_arg_dims={
"input_ids": 0,
# positions is of shape (xd, seq_len) if xdrope is enabled for hunyuan-vl,
# otherwise (seq_len, ).
"positions": -1,
"intermediate_tensors": 0,
"inputs_embeds": 0,
}
)
class HunYuanModel(nn.Module, EagleModelMixin):
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
super().__init__()
config = vllm_config.model_config.hf_config
cache_config = vllm_config.cache_config
quant_config = vllm_config.quant_config
eplb_config = vllm_config.parallel_config.eplb_config
enable_eplb = vllm_config.parallel_config.enable_eplb
self.num_redundant_experts = eplb_config.num_redundant_experts
self.config = config
self.quant_config = quant_config
self.vocab_size = config.vocab_size
if get_pp_group().is_first_rank or (config.tie_word_embeddings and get_pp_group().is_last_rank):
self.embed_tokens = VocabParallelEmbedding(
self.vocab_size,
config.hidden_size,
quant_config=quant_config,
)
else:
self.embed_tokens = PPMissingLayer()
self.start_layer, self.end_layer, self.layers = make_layers(
config.num_hidden_layers,
lambda prefix: HunYuanDecoderLayer(
config=config,
layer_id=int(prefix.split(".")[-1]),
cache_config=cache_config,
quant_config=quant_config,
prefix=prefix,
enable_eplb=enable_eplb,
),
prefix=f"{prefix}.layers",
)
if get_pp_group().is_last_rank:
self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
else:
self.norm = PPMissingLayer()
def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
return self.embed_tokens(input_ids)
def forward(
self,
input_ids: torch.Tensor | None,
positions: torch.Tensor,
intermediate_tensors: IntermediateTensors | None,
inputs_embeds: torch.Tensor | None = None,
) -> torch.Tensor | IntermediateTensors:
if get_pp_group().is_first_rank:
if inputs_embeds is not None:
hidden_states = inputs_embeds
else:
hidden_states = self.embed_input_ids(input_ids)
residual = None
else:
assert intermediate_tensors is not None
hidden_states = intermediate_tensors["hidden_states"]
residual = intermediate_tensors["residual"]
cla_factor = _get_cla_factor(self.config)
prev_kv_states = None
aux_hidden_states = self._maybe_add_hidden_state([], 0, hidden_states, residual)
for i, layer in enumerate(islice(self.layers, self.start_layer, self.end_layer)):
hidden_states, residual, kv_states = layer(
positions,
hidden_states,
residual,
prev_kv_states,
)
if getattr(self.config, "use_cla", False) and i % cla_factor == 0:
prev_kv_states = kv_states
else:
prev_kv_states = None
self._maybe_add_hidden_state(aux_hidden_states, i + 1, hidden_states, residual)
if not get_pp_group().is_last_rank:
return IntermediateTensors({"hidden_states": hidden_states, "residual": residual})
hidden_states, _ = self.norm(hidden_states, residual)
if len(aux_hidden_states) > 0:
return hidden_states, aux_hidden_states
return hidden_states
@@ -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
import gc
import math
import typing
@@ -45,13 +45,6 @@ from vllm.model_executor.model_loader.weight_utils import (
default_weight_loader,
maybe_remap_kv_scale_name,
)
from vllm.model_executor.models.hunyuan_v1 import (
HunYuanMLP,
HunYuanModel,
HunYuanSparseMoeBlock,
_get_cla_factor,
_is_moe,
)
from vllm.model_executor.models.interfaces import (
MultiModalEmbeddings,
SupportsLoRA,
@@ -63,6 +56,7 @@ from vllm.model_executor.models.interfaces import (
from vllm.model_executor.models.utils import (
AutoWeightsLoader,
PPMissingLayer,
WeightsMapper,
_merge_multimodal_embeddings,
is_pp_missing_parameter,
maybe_prefix,
@@ -78,7 +72,6 @@ from vllm.multimodal.parse import (
)
from vllm.multimodal.processing import (
BaseDummyInputsBuilder,
BaseMultiModalProcessor,
BaseProcessingInfo,
PromptReplacement,
PromptUpdate,
@@ -91,6 +84,14 @@ from vllm.v1.outputs import SamplerOutput
from vllm.v1.sample.metadata import SamplingMetadata
from vllm.v1.sample.sampler import Sampler
from vllm_omni.inputs.mm_processor import OmniMultiModalProcessor
from vllm_omni.model_executor.models.hunyuan_image3._hunyuan_v1_vendored import (
HunYuanMLP,
HunYuanModel,
HunYuanSparseMoeBlock,
_get_cla_factor,
_is_moe,
)
from vllm_omni.model_executor.models.hunyuan_image3.autoencoder_kl_3d import AutoencoderKLConv3D
from vllm_omni.model_executor.models.hunyuan_image3.siglip2 import LightProjector, Siglip2VisionTransformer
@@ -1027,7 +1028,7 @@ class HunyuanImage3DummyInputsBuilder(BaseDummyInputsBuilder[HunyuanImage3Proces
}
class HunyuanImage3MultiModalProcessor(BaseMultiModalProcessor[HunyuanImage3ProcessingInfo]):
class HunyuanImage3MultiModalProcessor(OmniMultiModalProcessor[HunyuanImage3ProcessingInfo]):
"""Multimodal processor for HunyuanImage3 model."""
def _call_hf_processor(
@@ -1046,15 +1047,6 @@ class HunyuanImage3MultiModalProcessor(BaseMultiModalProcessor[HunyuanImage3Proc
batch_feature["vae_generator_seed"] = torch.full((len(images),), int(vae_generator_seed), dtype=torch.long)
return batch_feature
def _hf_processor_applies_updates(
self,
prompt_text: str,
mm_items: MultiModalDataItems,
hf_processor_mm_kwargs: Mapping[str, object],
tokenization_kwargs: Mapping[str, object],
) -> bool:
return False
def _get_mm_fields_config(
self,
hf_inputs: BatchFeature,
@@ -2180,12 +2172,11 @@ class HunyuanImage3ForConditionalGeneration(nn.Module, SupportsMultiModal, Suppo
"timestep_r_emb",
]
skip_prefixes.extend(unexpected_keywords)
loader = AutoWeightsLoader(
self,
skip_prefixes=skip_prefixes,
)
loader = AutoWeightsLoader(self)
loaded_params = loader.load_weights(weights)
loaded_params = loader.load_weights(
weights, mapper=WeightsMapper(orig_to_new_prefix={name: None for name in (skip_prefixes or ())})
)
return loaded_params
def get_language_model(self) -> torch.nn.Module:
@@ -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}},
),
),
)
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
# Copyright 2025 Xiaomi Corporation.
import os
from collections.abc import Iterable, Mapping, Sequence
@@ -27,14 +30,13 @@ from vllm.multimodal.inputs import (
from vllm.multimodal.parse import AudioProcessorItems, MultiModalDataItems, MultiModalDataParser
from vllm.multimodal.processing import (
BaseDummyInputsBuilder,
BaseMultiModalProcessor,
BaseProcessingInfo,
ProcessorInputs,
PromptReplacement,
PromptUpdate,
PromptUpdateDetails,
)
from vllm.multimodal.utils import group_mm_kwargs_by_modality
from vllm.multimodal.utils import group_and_batch_mm_kwargs
from vllm.sequence import IntermediateTensors
from vllm.utils.cache import LRUCache
from vllm.utils.collection_utils import is_list_of
@@ -42,6 +44,7 @@ from vllm.utils.platform_utils import is_pin_memory_available
from vllm.v1.sample.metadata import SamplingMetadata
from vllm.v1.sample.sampler import Sampler
from vllm_omni.inputs.mm_processor import OmniMultiModalProcessor
from vllm_omni.model_executor.custom_process_mixin import CustomProcessMixin
from vllm_omni.model_executor.models.mimo_audio.config_mimo_audio import (
NO_INTERLEAVE_NEXT_TOKEN_ID,
@@ -348,7 +351,7 @@ class MiMoAudioDataParser(MultiModalDataParser):
return AudioProcessorItems(new_audios)
class MiMoAudioLLMMultiModalProcessor(BaseMultiModalProcessor[MiMoAudioLLMProcessingInfo]):
class MiMoAudioLLMMultiModalProcessor(OmniMultiModalProcessor[MiMoAudioLLMProcessingInfo]):
def _call_hf_processor(
self,
prompt: str,
@@ -484,7 +487,7 @@ class MiMoAudioLLMMultiModalProcessor(BaseMultiModalProcessor[MiMoAudioLLMProces
return [
PromptReplacement(
modality="audio",
target=audio_token,
target=[audio_token_id],
replacement=get_replacement_mimo_audio,
)
]
@@ -626,7 +629,7 @@ class MiMoAudioForConditionalGeneration(
)
mm_kwargs.append((mm_feature.modality, mm_item))
for modality, num_items, mm_kwargs_group in group_mm_kwargs_by_modality(
for modality, num_items, mm_kwargs_group in group_and_batch_mm_kwargs(
mm_kwargs,
device=self.device,
pin_memory=self.pin_memory,
@@ -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)
@@ -390,35 +390,25 @@ class MimoAudioDummyInputsBuilder(BaseDummyInputsBuilder[MimoAudioProcessingInfo
class MimoAudioMultiModalProcessor(BaseMultiModalProcessor[MimoAudioProcessingInfo]):
def _call_hf_processor(
def _preprocess_hf_mm_data(
self,
prompt: str,
mm_data: Mapping[str, object],
mm_kwargs: Mapping[str, Any],
tok_kwargs: Mapping[str, object],
) -> BatchFeature:
hf_processor_mm_kwargs: Mapping[str, object],
) -> tuple[Mapping[str, object], Mapping[str, object]]:
mm_data, hf_processor_mm_kwargs = super()._preprocess_hf_mm_data(
mm_data,
hf_processor_mm_kwargs,
)
mm_data = dict(mm_data)
audios = mm_data.pop("audios", [])
if audios:
mm_data["audio"] = audios
# Text-only input not supported in composite processor
if not mm_data.get("audio", []):
prompt_ids = self.info.get_tokenizer().encode(prompt)
prompt_ids = self._apply_hf_processor_tokens_only(prompt_ids)
return BatchFeature(dict(input_ids=[prompt_ids]), tensor_type="pt")
feature_extractor = self.info.get_feature_extractor(**mm_kwargs)
mm_kwargs = dict(
**mm_kwargs,
sampling_rate=feature_extractor.sampling_rate,
)
return super()._call_hf_processor(
prompt=prompt,
mm_data=mm_data,
mm_kwargs=mm_kwargs,
tok_kwargs=tok_kwargs,
)
feature_extractor = self.info.get_feature_extractor(**hf_processor_mm_kwargs)
hf_processor_mm_kwargs = {
**hf_processor_mm_kwargs,
"sampling_rate": feature_extractor.sampling_rate,
}
return mm_data, hf_processor_mm_kwargs
def _get_mm_fields_config(
self,
@@ -480,7 +470,7 @@ class MimoAudioMultiModalProcessor(BaseMultiModalProcessor[MimoAudioProcessingIn
return [
PromptReplacement(
modality="audio",
target=audio_token,
target=[audio_token_id],
replacement=get_replacement_mimo_audio,
)
]
@@ -1,4 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
# Copyright 2025 The vLLM-Omni team.
# Copyright (c) Ant Group. All rights reserved.
# Adapted from:
@@ -21,7 +22,7 @@ from transformers import AutoTokenizer, Qwen2Config, Qwen2Model
from transformers.utils.hub import cached_file
from vllm.config import VllmConfig
from vllm.logger import init_logger
from vllm.model_executor.models.utils import AutoWeightsLoader
from vllm.model_executor.models.utils import AutoWeightsLoader, WeightsMapper
from vllm.sequence import IntermediateTensors
from vllm_omni.model_executor.custom_process_mixin import CustomProcessMixin
@@ -509,12 +510,13 @@ class MingFlashOmniTalkerForConditionalGeneration(nn.Module, CustomProcessMixin)
if self._standalone:
weights = self._iter_talker_safetensors()
loader = AutoWeightsLoader(
self,
skip_prefixes=["audio_vae."], # loaded separately
skip_substrs=["rotary_embed.inv_freq"], # non-persistent buffer
loader = AutoWeightsLoader(self)
loaded = loader.load_weights(
weights,
mapper=WeightsMapper(
orig_to_new_prefix={"audio_vae.": None}, orig_to_new_substr={"rotary_embed.inv_freq": None}
),
)
loaded = loader.load_weights(weights)
logger.info("Loaded %d talker weights from checkpoint", len(loaded))
if self.audio_vae is not None and self._vae_weight_source is not None:
@@ -1,4 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
# Copyright 2025 The vLLM-Omni team.
# Copyright 2024 ANT Group and the HuggingFace Inc. team.
# Adapted from Ming repository modeling_bailingmm2.py and processing_bailingmm2.py
@@ -8,6 +9,7 @@
import os
from collections.abc import Iterable, Iterator, Mapping, Sequence
from dataclasses import replace
from typing import Annotated, Any
import numpy as np
@@ -388,7 +390,10 @@ class MingFlashOmniThinkerMultiModalProcessor(BaseMultiModalProcessor[MingFlashO
updates.append(
PromptReplacement(
modality="image",
target=PLACEHOLDER_IMAGE_TOKEN_IN_TEXT,
target=tokenizer.encode(
PLACEHOLDER_IMAGE_TOKEN_IN_TEXT,
add_special_tokens=False,
),
replacement=get_replacement_image,
)
)
@@ -396,7 +401,10 @@ class MingFlashOmniThinkerMultiModalProcessor(BaseMultiModalProcessor[MingFlashO
updates.append(
PromptReplacement(
modality="video",
target=PLACEHOLDER_VIDEO_TOKEN_IN_TEXT,
target=tokenizer.encode(
PLACEHOLDER_VIDEO_TOKEN_IN_TEXT,
add_special_tokens=False,
),
replacement=get_replacement_video,
)
)
@@ -404,7 +412,10 @@ class MingFlashOmniThinkerMultiModalProcessor(BaseMultiModalProcessor[MingFlashO
updates.append(
PromptReplacement(
modality="audio",
target=PLACEHOLDER_AUDIO_TOKEN_IN_TEXT,
target=tokenizer.encode(
PLACEHOLDER_AUDIO_TOKEN_IN_TEXT,
add_special_tokens=False,
),
replacement=get_replacement_audio,
)
)
@@ -451,90 +462,71 @@ class MingFlashOmniThinkerMultiModalProcessor(BaseMultiModalProcessor[MingFlashO
return config
def _hf_processor_applies_updates(
self,
prompt_text: str,
mm_items: MultiModalDataItems,
hf_processor_mm_kwargs: Mapping[str, object],
tokenization_kwargs: Mapping[str, object],
) -> bool:
return False
def apply(self, inputs, timing_ctx):
"""Add Ming image-generation query tokens before prompt updates."""
modalities = inputs.hf_processor_mm_kwargs.get("modalities") or []
if "image" in modalities or "img2img" in modalities:
from vllm_omni.model_executor.models.ming_flash_omni.prompt_utils import (
DEFAULT_NUM_QUERY_TOKENS,
IMAGE_PATCH_TOKEN,
)
tokenizer = self.info.get_tokenizer()
prompt_ids = list(inputs.prompt)
if "img2img" in modalities:
prompt_ids = (
tokenizer.encode(
PLACEHOLDER_IMAGE_TOKEN_IN_TEXT,
add_special_tokens=False,
)
+ prompt_ids
)
image_patch_ids = tokenizer.encode(
IMAGE_PATCH_TOKEN,
add_special_tokens=False,
)
if not image_patch_ids or not any(
prompt_ids[index : index + len(image_patch_ids)] == image_patch_ids
for index in range(len(prompt_ids) - len(image_patch_ids) + 1)
):
image_gen_config = getattr(
self.info.ctx.model_config.hf_config,
"image_gen_config",
None,
)
num_query_tokens = int(
getattr(
image_gen_config,
"num_query_tokens",
DEFAULT_NUM_QUERY_TOKENS,
)
)
suffix = (
tokenizer.encode("<image>", add_special_tokens=False)
+ image_patch_ids * num_query_tokens
+ tokenizer.encode("</image>", add_special_tokens=False)
)
prompt_ids.extend(suffix)
inputs = replace(inputs, prompt=prompt_ids)
return super().apply(inputs, timing_ctx)
def _apply_hf_processor_main(
self,
prompt: str | list[int],
mm_items: MultiModalDataItems,
hf_processor_mm_kwargs: Mapping[str, object],
tokenization_kwargs: Mapping[str, object],
*,
enable_hf_prompt_update: bool,
):
"""Apply Ming-specific prompt rewrites before delegating to vllm's
default text / multimodal processing pipeline.
This is the single point in the base MM-processor call graph where we
still have BOTH the full prompt and the request-level
``hf_processor_mm_kwargs`` together. Downstream, vllm's MM caching
design splits the work into
:meth:`_apply_hf_processor_text_only` (prompt, empty kwargs) and
:meth:`_apply_hf_processor_mm_only` (dummy text, real kwargs), so a
per-request flag like ``modalities`` cannot reach the real
tokenization from inside :meth:`_call_hf_processor`.
For Ming-flash-omni-2.0, image-generation requests carry
``mm_processor_kwargs["modalities"]`` set to ``["image"]`` (t2i) or
``["img2img"]`` (image edit). We expand the prompt here with the
``<image><imagePatch>*N</image>`` query-token block so the expanded
form flows through both the tokenization and (eventual) MM paths.
For img2img, we also prepend ``<IMAGE>`` so the thinker-side prompt
replacement can locate the reference-image placeholder.
"""
modalities = hf_processor_mm_kwargs.get("modalities") or []
is_image_gen = "image" in modalities or "img2img" in modalities
if isinstance(prompt, str) and is_image_gen:
from vllm_omni.model_executor.models.ming_flash_omni.prompt_utils import (
DEFAULT_NUM_QUERY_TOKENS,
maybe_expand_image_gen_prompt,
)
# img2img: prepend ``<IMAGE>`` so the ref-image placeholder survives
# MM caching (when the ref image is cache-warm, the thinker sees 0
# missing items and cannot inject the placeholder itself).
if "img2img" in modalities:
prompt = "<IMAGE>" + prompt
ig = getattr(self.info.ctx.model_config.hf_config, "image_gen_config", None)
num_query_tokens = getattr(ig, "num_query_tokens", DEFAULT_NUM_QUERY_TOKENS)
prompt = maybe_expand_image_gen_prompt(prompt, num_query_tokens=int(num_query_tokens))
return super()._apply_hf_processor_main(
prompt=prompt,
mm_items=mm_items,
hf_processor_mm_kwargs=hf_processor_mm_kwargs,
tokenization_kwargs=tokenization_kwargs,
enable_hf_prompt_update=enable_hf_prompt_update,
)
def _call_hf_processor(
self,
prompt: str,
mm_data: Mapping[str, object],
mm_kwargs: Mapping[str, object],
tok_kwargs: Mapping[str, object],
) -> BatchFeature:
"""Call sub-processors for multimodal inputs and tokenize.
"""Call Ming's modality processors without expanding prompt text.
We call the image/audio sub-processors directly (instead of going
through `MingFlashOmniProcessor.__call__`) so that the high-level
placeholder tokens remain **unexpanded** in the tokenized output.
NOTE: Image-gen prompt expansion is handled in
:meth:`_apply_hf_processor_main` — by the time we get here, vllm's
MM caching has already split text/mm processing and ``mm_kwargs``
is empty on the text-only branch.
placeholder tokens remain under vLLM's prompt-update control.
"""
valid_mm_items = mm_items.select({key for key, count in mm_items.get_all_counts().items() if count > 0})
mm_data, passthrough_data = self._get_hf_mm_data(valid_mm_items)
hf_processor = self.info.get_hf_processor()
tokenizer = self.info.get_tokenizer()
data: dict[str, object] = {}
@@ -577,11 +569,9 @@ class MingFlashOmniThinkerMultiModalProcessor(BaseMultiModalProcessor[MingFlashO
)
data.update(audio_outputs)
# Tokenize text with placeholders still intact
text_outputs = tokenizer(prompt, return_tensors="pt", **tok_kwargs)
data.update(text_outputs)
return BatchFeature(data=data)
processed_data = BatchFeature(data=data)
processed_data.update(passthrough_data)
return processed_data
@MULTIMODAL_REGISTRY.register_processor(
@@ -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:
@@ -21,9 +21,8 @@ import inspect
import math
import os
import warnings
from collections import defaultdict
from collections.abc import Callable, Iterable, Mapping, Sequence
from dataclasses import dataclass
from dataclasses import dataclass, replace
from functools import partial
from typing import Annotated, Any, Literal, TypeAlias
@@ -3310,7 +3309,7 @@ class MiniCPMOAudioEmbeddingItems(DictEmbeddingItems):
) -> None:
super().__init__(
data,
modality="image",
modality="audio",
required_fields={"audio_embeds"},
fields_factory=fields_factory,
)
@@ -3403,84 +3402,46 @@ class MiniCPMOMultiModalDataParser(MultiModalDataParser):
class MiniCPMO45OmniLLMMultiModalProcessor(BaseMultiModalProcessor[MiniCPMO45OmniLLMProcessingInfo]):
"""Multimodal processor for MiniCPM-o thinker stage."""
def _apply_hf_processor_main(
self,
prompt: str | list[int],
mm_items: MultiModalDataItems,
hf_processor_mm_kwargs: Mapping[str, object],
tokenization_kwargs: Mapping[str, object],
*,
enable_hf_prompt_update: bool,
) -> tuple[list[int], BatchFeature, bool]:
"""
MiniCPM-O reimplements this to avoid calling HF processor with text-only
when enable_hf_prompt_update=False. The MiniCPM processor asserts
len(image_tags) == len(image_sizes) and fails if given placeholder text
without corresponding image data (e.g. during profiling/cache-miss path).
"""
use_tts = hf_processor_mm_kwargs.get("use_tts", False)
hf_processor_mm_kwargs = {k: v for k, v in hf_processor_mm_kwargs.items() if k != "use_tts"}
if isinstance(prompt, str):
if use_tts:
prompt = prompt + self._TTS_SUFFIX
if enable_hf_prompt_update:
return self._apply_hf_processor_text_mm(
prompt_text=prompt,
mm_items=mm_items,
hf_processor_mm_kwargs=hf_processor_mm_kwargs,
tokenization_kwargs=tokenization_kwargs,
)
tokenizer = self.info.get_tokenizer()
prompt_ids = _encode_tokens(tokenizer, prompt)
else:
prompt_ids = self._apply_hf_processor_tokens_only(prompt)
if use_tts:
tokenizer = self.info.get_tokenizer()
tts_ids = tokenizer.convert_tokens_to_ids(["<|spk_bos|>", "<|spk|>", "<|spk_eos|>", "<|tts_bos|>"])
prompt_ids = list(prompt_ids) + tts_ids
mm_processed_data = self._apply_hf_processor_mm_only(
mm_items=mm_items,
hf_processor_mm_kwargs=hf_processor_mm_kwargs,
tokenization_kwargs=tokenization_kwargs,
)
return prompt_ids, mm_processed_data, False
_TTS_SUFFIX = "<|spk_bos|><|spk|><|spk_eos|><|tts_bos|>"
def _call_hf_processor(
def apply(self, inputs, timing_ctx):
hf_processor_mm_kwargs = inputs.hf_processor_mm_kwargs
if hf_processor_mm_kwargs.get("use_tts", False):
tokenizer = self.info.get_tokenizer()
tts_ids = tokenizer.convert_tokens_to_ids(["<|spk_bos|>", "<|spk|>", "<|spk_eos|>", "<|tts_bos|>"])
inputs = replace(
inputs,
prompt=[*inputs.prompt, *tts_ids],
hf_processor_mm_kwargs={
key: value for key, value in hf_processor_mm_kwargs.items() if key != "use_tts"
},
)
return super().apply(inputs, timing_ctx)
def _apply_hf_processor_main(
self,
prompt: str,
mm_data: Mapping[str, object],
mm_kwargs: Mapping[str, object],
tok_kwargs: Mapping[str, object],
mm_items: MultiModalDataItems,
hf_processor_mm_kwargs: Mapping[str, object],
) -> BatchFeature:
"""
Process each modality independently because the MiniCPM processor
asserts that image tags and image sizes have matching lengths.
"""
valid_mm_items = mm_items.select({key for key, count in mm_items.get_all_counts().items() if count > 0})
mm_data, passthrough_data = self._get_hf_mm_data(valid_mm_items)
tokenizer = self.info.get_tokenizer()
use_tts = mm_kwargs.get("use_tts", False)
mm_kwargs = {k: v for k, v in mm_kwargs.items() if k != "use_tts"}
if use_tts:
prompt = prompt + self._TTS_SUFFIX
input_ids = torch.tensor([tokenizer.encode(prompt, **tok_kwargs)])
mm_inputs = self.process_mm_inputs(mm_data, mm_kwargs, tok_kwargs)
return BatchFeature(
prompt_text = self.dummy_inputs.get_dummy_text(mm_items.get_all_counts())
input_ids = torch.tensor([tokenizer.encode(prompt_text)])
mm_inputs = self.process_mm_inputs(mm_data, hf_processor_mm_kwargs)
processed_data = BatchFeature(
{
"input_ids": input_ids,
**mm_inputs,
}
)
def _hf_processor_applies_updates(
self,
prompt_text: str,
mm_items: MultiModalDataItems,
hf_processor_mm_kwargs: Mapping[str, object],
tokenization_kwargs: Mapping[str, object],
) -> bool:
return False
processed_data.update(passthrough_data)
return processed_data
def get_image_prompt_texts(
self,
@@ -3528,7 +3489,6 @@ class MiniCPMO45OmniLLMMultiModalProcessor(BaseMultiModalProcessor[MiniCPMO45Omn
self,
mm_data: Mapping[str, object],
mm_kwargs: Mapping[str, object],
tok_kwargs: Mapping[str, object],
) -> Mapping[str, NestedTensors]:
if (audios := mm_data.get("audios")) is None:
return {}
@@ -3540,11 +3500,10 @@ class MiniCPMO45OmniLLMMultiModalProcessor(BaseMultiModalProcessor[MiniCPMO45Omn
if isinstance(parsed_audios, MiniCPMOAudioEmbeddingItems):
audio_inputs = {}
else:
audio_inputs = self._base_call_hf_processor(
audio_inputs = self._call_hf_processor_on_prompts(
prompts=[self.info.audio_pattern] * len(parsed_audios),
mm_data={"audios": [[audio] for audio in parsed_audios]},
mm_kwargs={**mm_kwargs, "chunk_input": True},
tok_kwargs=tok_kwargs,
out_keys={"audio_features", "audio_feature_lens"},
)
@@ -3569,7 +3528,6 @@ class MiniCPMO45OmniLLMMultiModalProcessor(BaseMultiModalProcessor[MiniCPMO45Omn
self,
mm_data: Mapping[str, object],
mm_kwargs: Mapping[str, object],
tok_kwargs: Mapping[str, object],
) -> Mapping[str, NestedTensors]:
if (images := mm_data.get("images")) is None:
return {}
@@ -3581,11 +3539,10 @@ class MiniCPMO45OmniLLMMultiModalProcessor(BaseMultiModalProcessor[MiniCPMO45Omn
if isinstance(parsed_images, MiniCPMVImageEmbeddingItems):
image_inputs = {}
else:
image_inputs = self._base_call_hf_processor(
image_inputs = self._call_hf_processor_on_prompts(
prompts=[self.info.image_pattern] * len(parsed_images),
mm_data={"images": [[image] for image in parsed_images]},
mm_kwargs=mm_kwargs,
tok_kwargs=tok_kwargs,
out_keys={"pixel_values", "image_sizes", "tgt_sizes"},
)
return image_inputs
@@ -3594,7 +3551,6 @@ class MiniCPMO45OmniLLMMultiModalProcessor(BaseMultiModalProcessor[MiniCPMO45Omn
self,
mm_data: Mapping[str, object],
mm_kwargs: Mapping[str, object],
tok_kwargs: Mapping[str, object],
) -> Mapping[str, NestedTensors]:
if (videos := mm_data.get("videos")) is None:
return {}
@@ -3606,14 +3562,13 @@ class MiniCPMO45OmniLLMMultiModalProcessor(BaseMultiModalProcessor[MiniCPMO45Omn
if isinstance(parsed_videos, MiniCPMVVideoEmbeddingItems):
video_inputs = {}
else:
video_inputs = self._base_call_hf_processor(
video_inputs = self._call_hf_processor_on_prompts(
prompts=[self.info.image_pattern * len(video) for video in parsed_videos],
mm_data={"images": list(parsed_videos)},
mm_kwargs={
**mm_kwargs,
"max_slice_nums": self.info.get_video_max_slice_num(),
},
tok_kwargs=tok_kwargs,
out_keys={"pixel_values", "image_sizes", "tgt_sizes"},
)
@@ -3625,48 +3580,30 @@ class MiniCPMO45OmniLLMMultiModalProcessor(BaseMultiModalProcessor[MiniCPMO45Omn
self,
mm_data: Mapping[str, object],
mm_kwargs: Mapping[str, object],
tok_kwargs: Mapping[str, object],
) -> Mapping[str, NestedTensors]:
return {
**self.process_images(mm_data, mm_kwargs, tok_kwargs),
**self.process_videos(mm_data, mm_kwargs, tok_kwargs),
**self.process_audios(mm_data, mm_kwargs, tok_kwargs),
**self.process_images(mm_data, mm_kwargs),
**self.process_videos(mm_data, mm_kwargs),
**self.process_audios(mm_data, mm_kwargs),
}
def _base_call_hf_processor(
def _call_hf_processor_on_prompts(
self,
prompts: list[str],
mm_data: Mapping[str, Sequence[object]],
mm_kwargs: Mapping[str, object],
tok_kwargs: Mapping[str, object],
*,
out_keys: set[str],
) -> dict[str, NestedTensors]:
mm_kwargs = {k: v for k, v in mm_kwargs.items() if k != "use_tts"}
# This processor supports zipping prompt and mm_data together
if self.info.get_model_version() in {(2, 6), (4, 0), (4, 5)}:
inputs = super()._call_hf_processor(
prompt=prompts, # type: ignore
mm_data=mm_data,
mm_kwargs=mm_kwargs,
tok_kwargs=tok_kwargs,
)
else:
inputs = defaultdict[str, list[torch.Tensor]](list)
from vllm.model_executor.models.minicpmv import MiniCPMVMultiModalProcessor
for i, prompt in enumerate(prompts):
inputs_one = super()._call_hf_processor(
prompt=prompt,
mm_data={k: v[i] for k, v in mm_data.items()},
mm_kwargs=mm_kwargs,
tok_kwargs=tok_kwargs,
)
for k, v in inputs_one.items():
assert len(v) == 1, (k, len(v))
inputs[k].append(v[0])
return {k: inputs[k] for k in out_keys}
return MiniCPMVMultiModalProcessor._call_hf_processor_on_prompts(
self,
prompts,
mm_data,
{key: value for key, value in mm_kwargs.items() if key != "use_tts"},
out_keys=out_keys,
)
def _get_prompt_updates(
self,
@@ -3688,6 +3625,17 @@ class MiniCPMO45OmniLLMMultiModalProcessor(BaseMultiModalProcessor[MiniCPMO45Omn
additional_placeholders.append((modality, sub_pattern))
placeholders += additional_placeholders
# vLLM 0.29 removed PromptUpdateDetails.select_text: prompt updates are
# token oriented now, so encode the replacement text and select the unk
# placeholder positions by token id instead of by text.
unk_token_id = tokenizer.convert_tokens_to_ids("<unk>")
def _select_unk_positions(text: str) -> PromptUpdateDetails:
return PromptUpdateDetails.select_token_id(
tokenizer.encode(text, add_special_tokens=False),
unk_token_id,
)
image_max_slice_nums = hf_processor_mm_kwargs.get("max_slice_nums")
image_use_image_id = hf_processor_mm_kwargs.get("use_image_id")
@@ -3696,14 +3644,13 @@ class MiniCPMO45OmniLLMMultiModalProcessor(BaseMultiModalProcessor[MiniCPMO45Omn
image_size = images.get_image_size(item_idx)
return PromptUpdateDetails.select_text(
return _select_unk_positions(
self.get_image_prompt_texts(
image_size,
item_idx,
max_slice_nums=None if image_max_slice_nums is None else int(image_max_slice_nums), # type: ignore[arg-type]
use_image_id=None if image_use_image_id is None else bool(image_use_image_id),
),
"<unk>",
)
)
def get_video_replacement(item_idx: int):
@@ -3712,17 +3659,18 @@ class MiniCPMO45OmniLLMMultiModalProcessor(BaseMultiModalProcessor[MiniCPMO45Omn
frame_size = videos.get_frame_size(item_idx)
num_frames = videos.get_num_frames(item_idx)
return PromptUpdateDetails.select_text(
self.get_video_prompt_texts(frame_size, num_frames),
"<unk>",
)
return _select_unk_positions(self.get_video_prompt_texts(frame_size, num_frames))
get_replacement = {
"image": get_image_replacement,
"video": get_video_replacement,
}
base_updates = [
PromptReplacement(modality=modality, target=pattern, replacement=get_replacement[modality])
PromptReplacement(
modality=modality,
target=tokenizer.encode(pattern, add_special_tokens=False),
replacement=get_replacement[modality],
)
for modality, pattern in placeholders
]
@@ -3733,20 +3681,21 @@ 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)
return PromptUpdateDetails.select_text(
self.get_audio_prompt_texts(audio_len),
"<unk>",
)
return _select_unk_positions(self.get_audio_prompt_texts(audio_len))
return [
*base_updates,
PromptReplacement(
modality="audio",
target=audio_placeholder,
target=tokenizer.encode(
audio_placeholder,
add_special_tokens=False,
),
replacement=get_audio_replacement,
),
]
@@ -3796,11 +3745,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.
"""
@@ -12,6 +12,7 @@ import regex as re
import torch
import torch.nn as nn
from vllm.config import VllmConfig
from vllm.inputs import mm_input
from vllm.model_executor.models.qwen3_vl import (
Qwen3VLDummyInputsBuilder,
Qwen3VLForConditionalGeneration,
@@ -26,10 +27,6 @@ from vllm_omni.model_executor.models.minimax_h3.conditioning import (
MINIMAX_H3_PRESENTATION_TASK_KEY,
)
from vllm_omni.model_executor.models.minimax_h3.preprocessing import (
IMAGE_PAD,
VIDEO_PAD,
VISION_END,
VISION_START,
build_minimax_h3_presentation,
)
from vllm_omni.model_executor.models.output_templates import OmniOutput
@@ -96,58 +93,57 @@ class MiniMaxH3MultiModalProcessor(Qwen3VLMultiModalProcessor):
def _apply_hf_processor_main(
self,
prompt: str | list[int],
mm_items: Any,
hf_processor_mm_kwargs: Mapping[str, object],
tokenization_kwargs: Mapping[str, object],
*,
enable_hf_prompt_update: bool,
):
task_value = hf_processor_mm_kwargs.get(MINIMAX_H3_PRESENTATION_TASK_KEY)
if task_value is None:
return super()._apply_hf_processor_main(
prompt,
mm_items,
hf_processor_mm_kwargs,
tokenization_kwargs,
enable_hf_prompt_update=enable_hf_prompt_update,
)
if not isinstance(prompt, str):
raise ValueError("MiniMax H3 presentation requires the original prompt text")
task = str(task_value)
condition_labels = self._condition_labels(hf_processor_mm_kwargs.get(MINIMAX_H3_CONDITION_LABELS_KEY))
base_kwargs = self._base_processor_kwargs(hf_processor_mm_kwargs)
image_count = sum(kind == "image" for kind, _ in condition_labels)
video_count = sum(kind == "video" for kind, _ in condition_labels)
image_slot = f"{VISION_START}{IMAGE_PAD}{VISION_END}"
hf_processor = self.info.get_hf_processor(**base_kwargs)
video_slot = (
VIDEO_PAD if self._expands_only_video_token(hf_processor) else f"{VISION_START}{VIDEO_PAD}{VISION_END}"
)
processing_prompt = image_slot * image_count + video_slot * video_count
if not processing_prompt:
processing_prompt = prompt
_, processed_data, _ = super()._apply_hf_processor_main(
processing_prompt,
return super()._apply_hf_processor_main(
mm_items,
base_kwargs,
tokenization_kwargs,
enable_hf_prompt_update=enable_hf_prompt_update,
)
def apply(self, inputs: Any, timing_ctx: Any):
task_value = inputs.hf_processor_mm_kwargs.get(MINIMAX_H3_PRESENTATION_TASK_KEY)
if task_value is None:
return super().apply(inputs, timing_ctx)
prompt_ids = self._postprocess_prompt(inputs.prompt)
mm_info = self._cached_apply_hf_processor(inputs, timing_ctx)
base_kwargs = self._base_processor_kwargs(inputs.hf_processor_mm_kwargs)
tokenizer = self.info.get_tokenizer()
prompt_text = tokenizer.decode(prompt_ids, skip_special_tokens=False)
condition_labels = self._condition_labels(inputs.hf_processor_mm_kwargs.get(MINIMAX_H3_CONDITION_LABELS_KEY))
out_mm_data = mm_info.kwargs.get_data()
image_processor = self.info.get_image_processor(**base_kwargs)
ids, _ = _build_minimax_h3_presentation(
self.info.get_tokenizer(),
prompt=prompt,
task=task,
tokenizer,
prompt=prompt_text,
task=str(task_value),
condition_labels=condition_labels,
image_grid_thw=processed_data.get("image_grid_thw"),
video_grid_thw=processed_data.get("video_grid_thw"),
video_timestamps=processed_data.get("timestamps"),
image_grid_thw=out_mm_data.get("image_grid_thw"),
video_grid_thw=out_mm_data.get("video_grid_thw"),
video_timestamps=out_mm_data.get("timestamps"),
merge_size=int(image_processor.merge_size),
)
return ids.tolist(), processed_data, True
prompt_ids = ids.tolist()
mm_item_counts = inputs.mm_data_items.get_all_counts()
self._validate_mm_kwargs(mm_info.kwargs, mm_item_counts)
self._validate_mm_updates(mm_info.prompt_updates, mm_item_counts)
mm_placeholders = self._find_mm_placeholders(
prompt_ids,
mm_info.prompt_updates,
)
self._validate_mm_placeholders(mm_placeholders, mm_item_counts)
mm_placeholder_ranges = {
modality: [item.to_range() for item in placeholders] for modality, placeholders in mm_placeholders.items()
}
return mm_input(
prompt_token_ids=prompt_ids,
mm_kwargs=mm_info.kwargs,
mm_hashes=mm_info.hashes,
mm_placeholders=mm_placeholder_ranges,
)
def _get_prompt_updates(
self,
@@ -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-0 talker for MiniMax Music 3.
A Qwen3 backbone predicts one audio frame per decode step. Each frame is
@@ -37,7 +37,7 @@ 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.models.qwen3 import Qwen3Model
from vllm.model_executor.models.utils import AutoWeightsLoader
from vllm.model_executor.models.utils import AutoWeightsLoader, WeightsMapper
from vllm.v1.outputs import SamplerOutput
from vllm_omni.model_executor.models.output_templates import OmniOutput
@@ -980,8 +980,10 @@ class MiniMaxMusic3TalkerForConditionalGeneration(nn.Module):
through vLLM. The audio embedding table and the depth decoder live in
a separate component of the repo and are loaded explicitly.
"""
loader = AutoWeightsLoader(self, skip_prefixes=["audio_embeddings.", "rvq_decoder."])
loaded = loader.load_weights(weights)
loader = AutoWeightsLoader(self)
loaded = loader.load_weights(
weights, mapper=WeightsMapper(orig_to_new_prefix={"audio_embeddings.": None, "rvq_decoder.": None})
)
loaded |= load_depth_decoder_weights(
self.vllm_config,
audio_embeddings=self.audio_embeddings,
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
# Copyright 2026 OpenMOSS and the HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -801,7 +804,16 @@ class MossAudioTokenizerMultiheadAttention(StreamingModule):
else:
attn_bias = None
x = F.scaled_dot_product_attention(q, k, v, attn_bias, dropout_p=0.0)
streaming_attention = getattr(self, "_streaming_attention", None)
if (
streaming_attention is not None
and attn_bias is not None
and q.dtype == torch.bfloat16
and q.shape[-1] == 64
):
x = streaming_attention(q, k, v, attn_bias)
else:
x = F.scaled_dot_product_attention(q, k, v, attn_bias, dropout_p=0.0)
x = x.transpose(1, 2).reshape(B, T, self.embed_dim)
x = apply_weights_per_step(self.out_projs, self.weights_per_step_schedule, x, offset_cpu)
@@ -145,15 +145,22 @@ class _MossCodecStreamSession:
terminal_slots = terminal_slots or set()
if not terminal_slots.issubset(slot_codes):
raise ValueError("terminal_slots must be a subset of the decode batch slots.")
step_lengths = {int(codes.shape[1]) for codes in slot_codes.values()}
if len(step_lengths) != 1:
raise ValueError(f"MOSS codec streaming step needs uniform T, got {sorted(step_lengths)}")
(step_t,) = step_lengths
step_t = max(int(codes.shape[1]) for codes in slot_codes.values())
if any(int(codes.shape[1]) != step_t and slot not in terminal_slots for slot, codes in slot_codes.items()):
raise ValueError("Only terminal codec rows may be padded to a larger step length")
slots = list(slot_codes)
if any(slot not in self._leased_slots for slot in slots):
raise RuntimeError(f"Streaming decode references an unleased state slot: {slots}")
codes_step = torch.stack(
[slot_codes[slot].to(device=self._device, dtype=torch.long) for slot in slots],
[
torch.nn.functional.pad(
slot_codes[slot].to(device=self._device, dtype=torch.long),
(0, step_t - int(slot_codes[slot].shape[1])),
)
if int(slot_codes[slot].shape[1]) != step_t
else slot_codes[slot].to(device=self._device, dtype=torch.long)
for slot in slots
],
dim=1,
)
state_slot_ids = torch.tensor(slots, device=self._device, dtype=torch.long)
@@ -197,9 +204,9 @@ class _MossCodecStreamSession:
self._reset_slot_ids(terminal_slot_ids)
audio = audio_tensor.detach().to("cpu", torch.float32)
audio_length = step_t * self._samples_per_frame
out: dict[int, torch.Tensor] = {}
for row, slot in enumerate(slots):
audio_length = int(slot_codes[slot].shape[1]) * self._samples_per_frame
out[slot] = audio[row, ..., :audio_length].contiguous()
return out
@@ -518,6 +525,8 @@ class MossTTSCodecDecoder(nn.Module):
outputs: dict[int, torch.Tensor] = {}
grouped: dict[int, list[tuple[int, str, int, torch.Tensor, bool]]] = {}
max_step_frames = max(1, int(self._stream_max_step_frames))
graph = session._cudagraph_wrapper
coalesce_tails = graph is not None and max(graph.batch_sizes, default=0) >= self._stream_state_capacity
for output_index, request_id, codes_nq_t, finished in items:
slot = self._stream_req_slots.get(request_id)
@@ -548,9 +557,13 @@ class MossTTSCodecDecoder(nn.Module):
)
continue
grouped.setdefault(int(codes_nq_t.shape[1]), []).append(
(output_index, request_id, slot, codes_nq_t, finished)
)
frame_count = int(codes_nq_t.shape[1])
# Only combine tails that already used the same padded graph.
# Preserve exact-size graphs (including T=1) and the eager path.
group_frames = frame_count
if coalesce_tails and finished:
group_frames = graph._select_frame_size(frame_count, allow_padding=True) or frame_count
grouped.setdefault(group_frames, []).append((output_index, request_id, slot, codes_nq_t, finished))
for group in grouped.values():
plan = {slot: codes_nq_t for _, _, slot, codes_nq_t, _ in group}
@@ -756,6 +769,17 @@ class MossTTSCodecDecoder(nn.Module):
codec.eval()
if device.type != "cpu":
codec.decoder.to(dtype=torch.bfloat16)
attention_backend = getattr(self.vllm_config.model_config.hf_config, "codec_attention_backend", "sdpa")
if attention_backend != "sdpa":
if attention_backend != "triton" or device.type != "cuda":
raise ValueError(f"Unsupported codec attention backend/device: {attention_backend}/{device.type}")
from vllm_omni.model_executor.models.moss_tts.audio_tokenizer_v2 import MossAudioTokenizerMultiheadAttention
from vllm_omni.model_executor.models.moss_tts.streaming_attention import masked_attention
for module in codec.decoder.modules():
if isinstance(module, MossAudioTokenizerMultiheadAttention):
module._streaming_attention = masked_attention
logger.info("Enabled Triton masked attention for the streaming codec decoder")
build_decode_lut = getattr(codec.quantizer, "build_decode_lut", None)
if callable(build_decode_lut):
lut_dtype = torch.bfloat16 if device.type == "cuda" else torch.float32
@@ -1,3 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
# Copyright 2026 OpenMOSS and the vLLM-Omni team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
@@ -101,8 +103,13 @@ class _MossTTSLocalAttention(nn.Module):
odd = x[..., 1::2]
return torch.stack((-odd, even), dim=-1).reshape_as(x)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
"""``hidden_states``: ``(B, S, H)``. Re-prefills with a fresh causal mask over ``[0, S)`` every call."""
def forward(
self,
hidden_states: torch.Tensor,
kv_cache: tuple[torch.Tensor, torch.Tensor] | None = None,
position: int = 0,
) -> torch.Tensor:
"""Run a causal prefix, or one new token using frame-local K/V."""
batch_size, seq_len, _ = hidden_states.shape
qkv = self.c_attn(hidden_states)
query, key, value = qkv.split(self.embed_dim, dim=-1)
@@ -110,14 +117,22 @@ class _MossTTSLocalAttention(nn.Module):
key = key.view(batch_size, seq_len, self.n_head, self.head_dim)
value = value.view(batch_size, seq_len, self.n_head, self.head_dim)
cos, sin = self._rope_cos_sin(seq_len, hidden_states.device, hidden_states.dtype)
cos, sin = self._rope_cos_sin(position + seq_len, hidden_states.device, hidden_states.dtype)
cos, sin = cos[:, position:], sin[:, position:]
query = query * cos + self._rotate_half(query) * sin
key = key * cos + self._rotate_half(key) * sin
query = query.transpose(1, 2)
key = key.transpose(1, 2)
value = value.transpose(1, 2)
attn_output = F.scaled_dot_product_attention(query, key, value, is_causal=True)
if kv_cache is not None:
assert seq_len == 1, "Cached Local Depth execution consumes one token at a time"
k_cache, v_cache = kv_cache
k_cache[:, :, position : position + 1].copy_(key)
v_cache[:, :, position : position + 1].copy_(value)
key = k_cache[:, :, : position + 1]
value = v_cache[:, :, : position + 1]
attn_output = F.scaled_dot_product_attention(query, key, value, is_causal=kv_cache is None)
attn_output = attn_output.transpose(1, 2).reshape(batch_size, seq_len, self.embed_dim)
return self.c_proj(attn_output)
@@ -141,8 +156,13 @@ class _MossTTSLocalBlock(nn.Module):
self.ln_2 = nn.LayerNorm(hidden_size, eps=eps)
self.mlp = _MossTTSLocalMLP(hidden_size, inner_size)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
hidden_states = hidden_states + self.attn(self.ln_1(hidden_states))
def forward(
self,
hidden_states: torch.Tensor,
kv_cache: tuple[torch.Tensor, torch.Tensor] | None = None,
position: int = 0,
) -> torch.Tensor:
hidden_states = hidden_states + self.attn(self.ln_1(hidden_states), kv_cache, position)
hidden_states = hidden_states + self.mlp(self.ln_2(hidden_states))
return hidden_states
@@ -156,11 +176,9 @@ class MossTTSLocalDepthTransformer(nn.Module):
and codebook-0's head (``audio_lm_heads[0]``) simultaneously.
- codebooks 1..n_vq-1 are sampled sequentially: each sampled code is
re-embedded (``audio_embeddings[c]``) and appended as the next
position, re-prefilling the block over the growing (<=n_vq) sequence
with a fresh causal mask each call -- mathematically identical to
incremental KV-cache decoding since attention is strictly causal and
only the last position is ever read, but avoids any cache plumbing
given the trivially short sequence length.
position. K/V for earlier positions are reused within the frame, so
each position's projections and MLP run once. A new frame overwrites
every cache position before reading it, including CUDA Graph replay.
"""
def __init__(self, gpt2_config, hidden_size: int | None = None) -> None:
@@ -174,11 +192,13 @@ class MossTTSLocalDepthTransformer(nn.Module):
self.ln_f = nn.LayerNorm(self.hidden_size, eps=eps)
self._compiled_forward_prefix = None
def _forward_prefix(self, seq_embeds: torch.Tensor) -> torch.Tensor:
hidden_states = seq_embeds
for block in self.h:
hidden_states = block(hidden_states)
return self.ln_f(hidden_states)
def _forward_prefix(
self,
seq_embeds: torch.Tensor,
kv_cache: tuple[torch.Tensor, torch.Tensor] | None = None,
position: int = 0,
) -> torch.Tensor:
return self.ln_f(self.h[0](seq_embeds, kv_cache, position))
def setup_compile(self) -> None:
if self._compiled_forward_prefix is not None:
@@ -189,14 +209,18 @@ class MossTTSLocalDepthTransformer(nn.Module):
return
self._compiled_forward_prefix = torch.compile(
self._forward_prefix,
dynamic=False,
# Share batch/position shapes instead of exhausting Dynamo's
# recompilation budget while warming request-size graph buckets.
dynamic=True,
options={"epilogue_fusion": False},
)
logger.info("MOSS-TTS local depth prefix enabled with torch.compile")
logger.info("MOSS-TTS local depth frame-local KV execution enabled with torch.compile")
def _run_prefix(self, seq_embeds: torch.Tensor) -> torch.Tensor:
def _run_prefix(
self, seq_embeds: torch.Tensor, kv_cache: tuple[torch.Tensor, torch.Tensor], position: int
) -> torch.Tensor:
forward_prefix = self._compiled_forward_prefix or self._forward_prefix
return forward_prefix(seq_embeds)
return forward_prefix(seq_embeds, kv_cache, position)
@torch.no_grad()
def generate_frame(
@@ -240,9 +264,13 @@ class MossTTSLocalDepthTransformer(nn.Module):
for block in self.h:
block.attn.prepare_rope_cache(n_vq, backbone_last_hidden.device, dtype)
embeds = backbone_last_hidden.new_zeros((batch_size, n_vq, self.hidden_size), dtype=dtype)
embeds[:, 0, :] = backbone_last_hidden.to(dtype)
hidden = self._run_prefix(embeds[:, :1, :])
attn = self.h[0].attn
cache_shape = (batch_size, attn.n_head, n_vq, attn.head_dim)
kv_cache = (
backbone_last_hidden.new_empty(cache_shape, dtype=dtype),
backbone_last_hidden.new_empty(cache_shape, dtype=dtype),
)
hidden = self._run_prefix(backbone_last_hidden[:, None, :].to(dtype), kv_cache, 0)
local_hidden = hidden[:, 0, :]
binary_logits = local_text_lm_head(local_hidden).float()
@@ -292,9 +320,9 @@ class MossTTSLocalDepthTransformer(nn.Module):
codes[:, channel_index] = channel_token
if channel_index + 1 < n_vq:
embeds[:, channel_index + 1, :] = audio_embeddings[channel_index](channel_token).to(dtype)
hidden = self._run_prefix(embeds[:, : channel_index + 2, :])
local_hidden = hidden[:, channel_index + 1, :]
embeds = audio_embeddings[channel_index](channel_token).to(dtype)[:, None, :]
hidden = self._run_prefix(embeds, kv_cache, channel_index + 1)
local_hidden = hidden[:, 0, :]
return should_continue, codes
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
# Copyright 2026 OpenMOSS and the vLLM-Omni team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
@@ -1671,20 +1674,19 @@ class MossTTSLocalTalkerForGeneration(nn.Module):
self._batch_state = [(info["audio_state"] if isinstance(info, dict) else {}) for info in info_dicts]
self._batch_state_spans = kwargs.get("request_token_spans")
should_values: list[torch.Tensor] = []
have_mtp_output = False
should_codes: list[torch.Tensor] = []
should_indices: list[int] = []
per_req_codes: list[torch.Tensor] = []
have_codes = False
for info in info_dicts:
for index, info in enumerate(info_dicts):
audio_codes = (info.get("audio_codes", {}) or {}) if isinstance(info, dict) else {}
current = audio_codes.pop("current", None)
if isinstance(current, torch.Tensor) and current.numel() > 0:
codes = current.to(device=hidden.device, dtype=torch.long)
if codes.dim() == 1:
codes = codes.unsqueeze(0)
should_continue = codes.ne(self.audio_pad_token_id).any(dim=-1)
should_values.append(should_continue.reshape(-1)[:1])
have_mtp_output = True
should_codes.append(codes[:1])
should_indices.append(index)
# Do not boolean-index a CUDA tensor here. Even for the
# common single-row case, ``codes[should_continue]`` must
# discover a dynamic output size on the host and therefore
@@ -1694,9 +1696,19 @@ class MossTTSLocalTalkerForGeneration(nn.Module):
per_req_codes.append(codes)
have_codes = True
else:
should_values.append(torch.ones((1,), device=hidden.device, dtype=torch.bool))
per_req_codes.append(hidden.new_empty((0, self.n_vq), dtype=torch.long))
self._batch_should_continue = torch.cat(should_values, dim=0) if have_mtp_output and should_values else None
self._batch_should_continue = None
if should_codes:
active = torch.cat(should_codes, dim=0).ne(self.audio_pad_token_id).any(dim=-1)
if len(should_codes) == len(info_dicts):
self._batch_should_continue = active
else:
self._batch_should_continue = torch.ones(len(info_dicts), device=hidden.device, dtype=torch.bool)
# Keep mixed prefill/decode output packing asynchronous.
indices = torch.tensor(should_indices, device="cpu", dtype=torch.long).to(
hidden.device, non_blocking=True
)
self._batch_should_continue.index_copy_(0, indices, active)
if not have_codes:
return OmniOutput(text_hidden_states=hidden, multimodal_outputs={})
@@ -1,8 +1,13 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
# Copyright 2026 OpenMOSS and the vLLM-Omni team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
"""Pipeline topology for all MOSS-TTS variants (2-stage: talker → codec)."""
from vllm.sampling_params import RequestOutputKind
from vllm_omni.config.stage_config import (
PipelineConfig,
StageExecutionType,
@@ -100,6 +105,10 @@ MOSS_TTS_LOCAL_PIPELINE = PipelineConfig(
sampling_constraints={
"detokenize": False,
"stop_token_ids": [151645],
# The worker connector streams codes directly to the codec.
# This internal stage only needs to publish its terminal
# result; codec audio output remains incremental.
"output_kind": RequestOutputKind.FINAL_ONLY,
},
),
StagePipelineConfig(
@@ -0,0 +1,119 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Masked streaming attention preserving ring-cache position semantics."""
import torch
from vllm.triton_utils import tl, triton
@triton.jit
def _attention(
q_ptr,
k_ptr,
v_ptr,
mask_ptr,
out_ptr,
qs0: tl.constexpr,
qs1: tl.constexpr,
qs2: tl.constexpr,
qs3: tl.constexpr,
ks0: tl.constexpr,
ks1: tl.constexpr,
ks2: tl.constexpr,
ks3: tl.constexpr,
vs0: tl.constexpr,
vs1: tl.constexpr,
vs2: tl.constexpr,
vs3: tl.constexpr,
ms0: tl.constexpr,
ms2: tl.constexpr,
ms3: tl.constexpr,
num_heads: tl.constexpr,
q_len: tl.constexpr,
kv_len: tl.constexpr,
head_dim: tl.constexpr,
block_m: tl.constexpr,
block_n: tl.constexpr,
):
rows = tl.program_id(0) * block_m + tl.arange(0, block_m)
bh = tl.program_id(1)
batch, head = bh // num_heads, bh % num_heads
dims = tl.arange(0, head_dim)
q = tl.load(
q_ptr + batch * qs0 + head * qs1 + rows[:, None] * qs2 + dims[None, :] * qs3,
mask=rows[:, None] < q_len,
other=0,
)
acc = tl.full((block_m, head_dim), 0.0, tl.float32)
maximum = tl.full((block_m,), -float("inf"), tl.float32)
denominator = tl.full((block_m,), 0.0, tl.float32)
for first in range(tl.cdiv(kv_len, block_n)):
cols = first * block_n + tl.arange(0, block_n)
k = tl.load(
k_ptr + batch * ks0 + head * ks1 + cols[None, :] * ks2 + dims[:, None] * ks3,
mask=cols[None, :] < kv_len,
other=0,
)
allowed = tl.load(
mask_ptr + batch * ms0 + rows[:, None] * ms2 + cols[None, :] * ms3,
mask=(rows[:, None] < q_len) & (cols[None, :] < kv_len),
other=0,
)
score = tl.dot(q, k).to(tl.float32) * (head_dim**-0.5)
score = tl.where(allowed & (cols[None, :] < kv_len), score, -float("inf"))
next_max = tl.maximum(maximum, tl.max(score, axis=1))
safe_max = tl.where(next_max == -float("inf"), 0.0, next_max)
rescale = tl.exp(maximum - safe_max)
p = tl.exp(score - safe_max[:, None])
denominator = denominator * rescale + tl.sum(p, axis=1)
v = tl.load(
v_ptr + batch * vs0 + head * vs1 + cols[:, None] * vs2 + dims[None, :] * vs3,
mask=cols[:, None] < kv_len,
other=0,
)
acc = acc * rescale[:, None] + tl.dot(p.to(v.dtype), v)
maximum = next_max
out = acc / tl.where(denominator > 0, denominator, 1.0)[:, None]
tl.store(
out_ptr + ((batch * num_heads + head) * q_len + rows[:, None]) * head_dim + dims[None, :],
out,
mask=rows[:, None] < q_len,
)
@torch.library.custom_op("moss_streaming::masked_attention", mutates_args=())
def masked_attention(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
b, h, t, d = q.shape
out = torch.empty(q.shape, device=q.device, dtype=q.dtype)
# Small query tiles expose parallelism for short streaming chunks. Larger
# tiles reuse K/V for steady chunks. Keep 64-key softmax blocks to retain
# the same accumulation granularity across both paths.
bm = 16 if t <= 32 else 64
num_warps = 8 if k.shape[2] <= 256 else 4
_attention[(triton.cdiv(t, bm), b * h)](
q,
k,
v,
mask,
out,
*q.stride(),
*k.stride(),
*v.stride(),
mask.stride(0),
mask.stride(2),
mask.stride(3),
h,
t,
k.shape[2],
d,
bm,
64,
num_warps=num_warps,
num_stages=2,
)
return out
@masked_attention.register_fake
def _(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
return torch.empty(q.shape, device=q.device, dtype=q.dtype)
@@ -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.
@@ -11,6 +11,7 @@ from __future__ import annotations
import os
from collections.abc import Iterable, Mapping, Sequence
from dataclasses import replace
import numpy as np
import torch
@@ -28,7 +29,6 @@ from vllm.multimodal.inputs import (
from vllm.multimodal.parse import MultiModalDataItems, MultiModalDataParser
from vllm.multimodal.processing import (
BaseDummyInputsBuilder,
BaseMultiModalProcessor,
BaseProcessingInfo,
ProcessorInputs,
PromptIndexTargets,
@@ -37,6 +37,7 @@ from vllm.multimodal.processing import (
)
from vllm.sequence import IntermediateTensors
from vllm_omni.inputs.mm_processor import OmniMultiModalProcessor
from vllm_omni.model_executor.models.output_templates import OmniOutput
from vllm_omni.platforms import current_omni_platform
from vllm_omni.transformers_utils.configs.omnivoice import OmniVoiceConfig
@@ -63,13 +64,29 @@ class OmniVoiceMultiModalProcessingInfo(BaseProcessingInfo):
)
class OmniVoiceMultiModalProcessor(BaseMultiModalProcessor[OmniVoiceMultiModalProcessingInfo]):
class OmniVoiceMultiModalProcessor(OmniMultiModalProcessor[OmniVoiceMultiModalProcessingInfo]):
"""Processes text + optional reference audio for OmniVoice.
For voice cloning: text + reference audio → tokenized reference
For auto voice: text only
"""
def apply(self, inputs: ProcessorInputs, timing_ctx):
tokenizer = self.info.get_tokenizer()
prompt_text = tokenizer.decode(inputs.prompt, skip_special_tokens=False)
# Tokenize once here; _apply_hf_processor_main below only encodes the
# reference audio, so the media path never re-tokenizes the text.
prompt_ids = self._encode_prompt_text(prompt_text, inputs.hf_processor_mm_kwargs).reshape(-1).tolist()
inputs = replace(
inputs,
prompt=prompt_ids,
hf_processor_mm_kwargs={
**inputs.hf_processor_mm_kwargs,
self._OMNI_PROMPT_TEXT_KEY: prompt_text,
},
)
return super().apply(inputs, timing_ctx)
def _ensure_cached_runtime_components(self, model_dir: str, config: OmniVoiceConfig) -> None:
cached_model_dir = getattr(self, "_cached_model_dir", None)
if cached_model_dir == model_dir:
@@ -97,23 +114,39 @@ class OmniVoiceMultiModalProcessor(BaseMultiModalProcessor[OmniVoiceMultiModalPr
self._cached_model_dir = model_dir
def _call_hf_processor(
def _apply_hf_processor_main(
self,
prompt: str,
mm_data: Mapping[str, object],
mm_kwargs: Mapping[str, object],
tok_kwargs: Mapping[str, object],
mm_items: MultiModalDataItems,
hf_processor_mm_kwargs: Mapping[str, object],
) -> BatchFeature:
"""Encode the reference audio, if any; the prompt was tokenized in apply().
Upstream calls this for every request, including text-only ones and
ones whose audio is already cached (empty ``mm_items``), so it must not
touch the text tokenizer.
"""
valid_items = mm_items.select({key for key, count in mm_items.get_all_counts().items() if count > 0})
mm_data, passthrough = self._get_hf_mm_data(valid_items)
audio = self._get_reference_audio(mm_data)
if audio is None:
return BatchFeature(dict(passthrough))
processed = self._encode_reference_audio(*audio)
processed.update(passthrough)
return processed
def _get_reference_audio(self, mm_data: Mapping[str, object]) -> tuple[object, int] | None:
audio = mm_data.get("audio", None)
if audio is None:
audios = mm_data.get("audios")
if audios is not None:
audio = audios[0], self.info.ctx.get_hf_config().sample_rate
return audio
def _encode_prompt_text(self, prompt: str, mm_kwargs: Mapping[str, object]) -> torch.Tensor:
config = self.info.ctx.get_hf_config()
model_dir = self.info.ctx.model_config.model
self._ensure_cached_runtime_components(model_dir, config)
audio = mm_data.get("audio", None)
if audio is None:
audio = mm_data.get("audios")
if audio is not None:
audio = audio[0], config.sample_rate
# Build text prompt with control tokens
lang = mm_kwargs.get("lang", None)
instruct = mm_kwargs.get("instruct", None)
@@ -136,19 +169,14 @@ class OmniVoiceMultiModalProcessor(BaseMultiModalProcessor[OmniVoiceMultiModalPr
full_text = prompt
text_prompt = f"{style_text}<|text_start|>{full_text}<|text_end|>"
text_tokens = self.text_tokenizer(text_prompt, return_tensors="pt").input_ids.squeeze(0) # [N_text]
return self.text_tokenizer(text_prompt, return_tensors="pt").input_ids.squeeze(0) # [N_text]
if audio is None:
# Text-only path (auto voice mode)
return BatchFeature(
{
"input_ids": text_tokens,
"input_len": [len(text_tokens)],
}
)
def _encode_reference_audio(self, audio_signal: object, sr: int) -> BatchFeature:
"""Voice cloning: encode the reference audio to 8-codebook tokens."""
config = self.info.ctx.get_hf_config()
model_dir = self.info.ctx.model_config.model
self._ensure_cached_runtime_components(model_dir, config)
# Voice cloning: encode reference audio to tokens
audio_signal, sr = audio
if isinstance(audio_signal, np.ndarray):
audio_signal = torch.from_numpy(audio_signal).float()
if audio_signal.dim() == 1:
@@ -169,14 +197,12 @@ class OmniVoiceMultiModalProcessor(BaseMultiModalProcessor[OmniVoiceMultiModalPr
if ref_audio_tokens.dim() == 3:
ref_audio_tokens = ref_audio_tokens.squeeze(0) # [8, T_ref]
ft = BatchFeature(
return BatchFeature(
{
"input_ids": text_tokens,
"ref_audio_tokens": ref_audio_tokens, # [8, T_ref]
"ref_audio_len": [ref_audio_tokens.shape[1]],
}
)
return ft
def _get_mm_fields_config(
self,
@@ -188,15 +214,6 @@ class OmniVoiceMultiModalProcessor(BaseMultiModalProcessor[OmniVoiceMultiModalPr
"ref_audio_len": MultiModalFieldConfig.batched("audio"),
}
def _hf_processor_applies_updates(
self,
prompt_text: str,
mm_items: MultiModalDataItems,
hf_processor_mm_kwargs: Mapping[str, object],
tokenization_kwargs: Mapping[str, object],
) -> bool:
return False
def _get_prompt_updates(
self,
mm_items: MultiModalDataItems,
@@ -487,9 +504,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",
)
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from collections.abc import Iterable
from functools import cached_property
@@ -139,11 +142,11 @@ class Qwen2_5OmniTalkerForConditionalGeneration(
return self.language_model.sample(logits, sampling_metadata)
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
loader = AutoWeightsLoader(
self,
skip_prefixes=["thinker.", "token2wav."],
loader = AutoWeightsLoader(self)
loaded = loader.load_weights(
weights,
mapper=(self.hf_to_vllm_mapper) | WeightsMapper(orig_to_new_prefix={"thinker.": None, "token2wav.": None}),
)
loaded = loader.load_weights(weights, mapper=self.hf_to_vllm_mapper)
# Log load summary
try:
total_bytes = 0
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Thin Omni wrapper: reuse upstream Qwen2.5-Omni thinker with minimal overrides."""
import hashlib
@@ -9,6 +12,7 @@ import numpy as np
import PIL.Image as PILImage
import torch
from torch import nn
from transformers.feature_extraction_utils import BatchFeature
from transformers.models.qwen2_5_omni.configuration_qwen2_5_omni import (
Qwen2_5OmniThinkerConfig,
)
@@ -360,25 +364,40 @@ class Qwen2_5OmniThinkerMultiModalProcessor(
):
"""Override to fix use_audio_in_video detection when mm cache returns None."""
def _call_hf_processor(
def _apply_hf_processor_main(
self,
prompt: str,
mm_data: Mapping[str, object],
mm_kwargs: Mapping[str, object],
tok_kwargs: Mapping[str, object],
):
mm_kwargs = _presampled_videos_hf_kwargs(mm_data, mm_kwargs)
mm_kwargs = _coerce_use_audio_in_video_for_hf_processor(mm_data, mm_kwargs)
hf_inputs = super()._call_hf_processor(
prompt=prompt,
mm_data=mm_data,
mm_kwargs=mm_kwargs,
tok_kwargs=tok_kwargs,
mm_items: MultiModalDataItems,
hf_processor_mm_kwargs: Mapping[str, object],
) -> BatchFeature:
"""Apply omni-specific HF kwargs before the upstream Qwen2.5-Omni
processor runs.
Upstream's ``_apply_hf_processor_main`` is fully custom and no longer
routes through the generic ``_preprocess_hf_mm_data`` /
``_postprocess_hf_mm_data`` hooks, so the omni video pre-sampling and
per-video ``use_audio_in_video`` mask handling have to run here.
"""
valid_mm_items = mm_items.select({k for k, c in mm_items.get_all_counts().items() if c > 0})
processor_data, _ = self._get_hf_mm_data(valid_mm_items)
hf_processor_mm_kwargs = _presampled_videos_hf_kwargs(
processor_data,
hf_processor_mm_kwargs,
)
per_video_mask = mm_kwargs.get(_PER_VIDEO_USE_AUDIO_IN_VIDEO_KEY)
hf_processor_mm_kwargs = _coerce_use_audio_in_video_for_hf_processor(
processor_data,
hf_processor_mm_kwargs,
)
processed_data = super()._apply_hf_processor_main(
mm_items,
hf_processor_mm_kwargs,
)
per_video_mask = hf_processor_mm_kwargs.get(_PER_VIDEO_USE_AUDIO_IN_VIDEO_KEY)
if per_video_mask is not None:
hf_inputs["use_audio_in_video"] = torch.tensor(per_video_mask)
return hf_inputs
processed_data["use_audio_in_video"] = torch.tensor(per_video_mask)
return processed_data
def _get_mm_fields_config(
self,
@@ -530,17 +549,17 @@ class Qwen2_5OmniThinkerMultiModalProcessor(
return [
PromptReplacement(
modality="audio",
target=audio_token,
target=[audio_token_id],
replacement=get_replacement_qwen2_audio,
),
PromptReplacement(
modality="image",
target=image_token,
target=[image_token_id],
replacement=partial(get_replacement_qwen2_vision, modality="image"),
),
PromptReplacement(
modality="video",
target=video_token,
target=[video_token_id],
replacement=get_replacement_qwen2_video,
),
]
@@ -620,7 +639,7 @@ class Qwen2_5OmniThinkerMultiModalProcessor(
self,
inputs: ProcessorInputs,
timing_ctx: TimingContext,
) -> tuple[list[int], MultiModalProcessingInfo, bool]:
) -> MultiModalProcessingInfo:
"""Cache-aware: processes video/audio pairs as units,
using pair-specific cache keys. Falls back to standard cache if no pairs."""
@@ -673,16 +692,9 @@ class Qwen2_5OmniThinkerMultiModalProcessor(
)
with timing_ctx.record("apply_hf_processor"):
(
prompt_ids,
mm_missing_processed_data,
is_update_applied,
) = self._apply_hf_processor_main(
prompt=inputs.prompt,
mm_missing_processed_data = self._apply_hf_processor_main(
mm_items=mm_missing_data_items,
hf_processor_mm_kwargs=hf_processor_mm_kwargs,
tokenization_kwargs=inputs.tokenization_kwargs,
enable_hf_prompt_update=False,
)
mm_missing_kwargs = MultiModalKwargsItems.from_hf_inputs(
@@ -714,7 +726,7 @@ class Qwen2_5OmniThinkerMultiModalProcessor(
prompt_updates=mm_prompt_updates,
)
return prompt_ids, mm_info, is_update_applied
return mm_info
def _derive_audio_from_video_placeholders(
self,
@@ -785,7 +797,6 @@ class Qwen2_5OmniThinkerMultiModalProcessor(
prompt_ids: list[int],
mm_kwargs: MultiModalKwargsItems,
mm_prompt_updates: MultiModalPromptUpdates,
is_update_applied: bool,
) -> tuple[list[int], Mapping[str, list[PlaceholderFeaturesInfo]]]:
mm_item_counts = mm_items.get_all_counts()
self._validate_mm_kwargs(mm_kwargs, mm_item_counts)
@@ -794,37 +805,27 @@ class Qwen2_5OmniThinkerMultiModalProcessor(
video_use_audio_in_video = self._get_video_use_audio_in_video(mm_kwargs, mm_prompt_updates)
use_audio_in_video = any(video_use_audio_in_video)
if is_update_applied:
mm_placeholders = self._find_mm_placeholders(
if use_audio_in_video and "audio" in mm_prompt_updates:
filtered_updates = {k: v for k, v in mm_prompt_updates.items() if k != "audio"}
prompt_ids, mm_placeholders = self._apply_prompt_updates(
prompt_ids,
filtered_updates,
)
mm_placeholders = self._derive_audio_from_video_placeholders(
mm_placeholders,
mm_prompt_updates,
video_use_audio_in_video,
)
else:
prompt_ids, mm_placeholders = self._apply_prompt_updates(
prompt_ids,
mm_prompt_updates,
)
self._validate_mm_placeholders(
mm_placeholders,
mm_item_counts,
)
else:
if use_audio_in_video and "audio" in mm_prompt_updates:
filtered_updates = {k: v for k, v in mm_prompt_updates.items() if k != "audio"}
prompt_ids, mm_placeholders = self._apply_prompt_updates(
prompt_ids,
filtered_updates,
)
mm_placeholders = self._derive_audio_from_video_placeholders(
mm_placeholders,
mm_prompt_updates,
video_use_audio_in_video,
)
else:
prompt_ids, mm_placeholders = self._apply_prompt_updates(
prompt_ids,
mm_prompt_updates,
)
self._validate_mm_placeholders(
mm_placeholders,
mm_item_counts,
)
self._validate_mm_placeholders(
mm_placeholders,
mm_item_counts,
)
return prompt_ids, mm_placeholders
@@ -1397,11 +1398,12 @@ class Qwen2_5OmniThinkerForConditionalGeneration(
if self.visual is None:
skip_prefixes.extend(["visual."])
loader = AutoWeightsLoader(
self,
skip_prefixes=skip_prefixes,
loader = AutoWeightsLoader(self)
loaded_weights = loader.load_weights(
weights,
mapper=(self.hf_to_vllm_mapper)
| WeightsMapper(orig_to_new_prefix={name: None for name in (skip_prefixes or ())}),
)
loaded_weights = loader.load_weights(weights, mapper=self.hf_to_vllm_mapper)
return loaded_weights
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from collections.abc import Iterable
import torch
@@ -20,6 +23,7 @@ from vllm.model_executor.models.interfaces import SupportsLoRA, SupportsPP
from vllm.model_executor.models.utils import (
AutoWeightsLoader,
PPMissingLayer,
WeightsMapper,
is_pp_missing_parameter,
make_empty_intermediate_tensors_factory,
make_layers,
@@ -441,8 +445,8 @@ class Qwen2ForCausalLM(nn.Module, SupportsLoRA, SupportsPP):
return next_tokens
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
loader = AutoWeightsLoader(
self,
skip_prefixes=(["lm_head."] if self.config.tie_word_embeddings else None),
loader = AutoWeightsLoader(self)
return loader.load_weights(
weights,
mapper=WeightsMapper(orig_to_new_prefix={"lm_head.": None} if self.config.tie_word_embeddings else {}),
)
return loader.load_weights(weights)
@@ -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
# Copyright 2025 The Qwen team.
"""Inference-only Qwen3-Omni-Moe Code2Wav model."""
@@ -336,11 +336,11 @@ class Qwen3OmniMoeCode2Wav(nn.Module, Qwen3OmniNestedSupportsQuant):
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
"""Load weights from HuggingFace checkpoint."""
loader = AutoWeightsLoader(
self,
skip_prefixes=["thinker.", "talker."], # Already loaded above
loader = AutoWeightsLoader(self)
loaded = loader.load_weights(
weights,
mapper=(self.hf_to_vllm_mapper) | WeightsMapper(orig_to_new_prefix={"thinker.": None, "talker.": None}),
)
loaded = loader.load_weights(weights, mapper=self.hf_to_vllm_mapper)
# Log load summary
try:
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from collections.abc import Iterable
import torch
@@ -299,13 +302,12 @@ class Qwen3OmniMoeTalkerForConditionalGeneration(
to vLLM's internal structure. Code predictor weights are routed
to its custom loader for vocab extension support.
"""
loader = AutoWeightsLoader(
self,
skip_prefixes=["thinker.", "code2wav."],
# "code_predictor."],
)
loader = AutoWeightsLoader(self)
# Don't apply mapper again since we already did it
loaded = loader.load_weights(weights, mapper=self.hf_to_vllm_mapper)
loaded = loader.load_weights(
weights,
mapper=(self.hf_to_vllm_mapper) | WeightsMapper(orig_to_new_prefix={"thinker.": None, "code2wav.": None}),
)
# Log load summary
try:
@@ -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
# Copyright 2025 The Qwen team.
# Copyright 2023 The vLLM team.
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
@@ -31,10 +31,7 @@ import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from packaging.version import Version
from transformers import PretrainedConfig
from transformers import __version__ as TRANSFORMERS_VERSION
from transformers.feature_extraction_utils import BatchFeature
from transformers.models.qwen3_omni_moe.configuration_qwen3_omni_moe import (
Qwen3OmniMoeConfig,
Qwen3OmniMoeThinkerConfig,
@@ -95,6 +92,9 @@ from vllm.model_executor.models.qwen3_omni_moe_thinker import (
from vllm.model_executor.models.qwen3_omni_moe_thinker import (
Qwen3OmniMoeAudioEncoderLayer as _Qwen3OmniMoeAudioEncoderLayer,
)
from vllm.model_executor.models.qwen3_omni_moe_thinker import (
Qwen3OmniMoeThinkerMultiModalProcessor as _UpstreamQwen3Processor,
)
from vllm.model_executor.models.qwen3_omni_moe_thinker import (
_get_feat_extract_output_lengths,
)
@@ -124,7 +124,6 @@ from vllm_omni.model_executor.models.qwen2_5_omni.qwen2_5_omni_thinker import (
Qwen2_5OmniThinkerMultiModalProcessor,
_get_request_video_use_audio_in_video,
_get_video_second_per_grid_t,
_presampled_videos_hf_kwargs,
)
from vllm_omni.model_executor.models.qwen3_omni.quantization import (
Qwen3OmniNestedSupportsQuant,
@@ -281,7 +280,12 @@ class Qwen3OmniMoeAudioAttention(_Qwen3OmniMoeAudioAttention):
self.scaling = self.head_dim**-0.5
self.qkv = QKVParallelLinear(
# vLLM 0.29 renamed the audio attention projection to ``qkv_proj`` and
# its stacked mapping rewrites checkpoint ``q_proj``/``k_proj``/
# ``v_proj`` onto that name, so the module must match or weight loading
# fails with "no module or parameter named ...self_attn.qkv_proj".
# The inherited forward also calls ``self.qkv_proj``.
self.qkv_proj = QKVParallelLinear(
hidden_size=self.embed_dim,
head_size=self.head_dim,
total_num_heads=self.num_heads,
@@ -289,7 +293,7 @@ class Qwen3OmniMoeAudioAttention(_Qwen3OmniMoeAudioAttention):
bias=True,
disable_tp=disable_tp,
quant_config=quant_config,
prefix=f"{prefix}.qkv",
prefix=f"{prefix}.qkv_proj",
)
self.out_proj = RowParallelLinear(
@@ -696,151 +700,10 @@ Qwen3OmniMoeThinkerDummyInputsBuilder = Qwen2_5OmniThinkerDummyInputsBuilder
class Qwen3OmniMoeThinkerMultiModalProcessor(
Qwen2_5OmniThinkerMultiModalProcessor,
_UpstreamQwen3Processor,
):
def _call_hf_processor(
self,
prompt: str,
mm_data: Mapping[str, object],
mm_kwargs: Mapping[str, object],
tok_kwargs: Mapping[str, object],
) -> BatchFeature:
mm_data = dict(mm_data)
mm_kwargs = dict(_presampled_videos_hf_kwargs(mm_data, mm_kwargs))
audios = mm_data.pop("audios", [])
def pad_to_hop_length(x: np.ndarray, hop_length: int) -> np.ndarray:
length = x.shape[-1]
if length % hop_length != 0:
pad_length = hop_length - (length % hop_length)
x = np.pad(x, (0, pad_length), mode="constant", constant_values=0)
return x
# NOTE: WhisperFeatureExtractor cannot handle empty list of audios
feature_extractor = self.info.get_feature_extractor(**mm_kwargs)
hop_length = feature_extractor.hop_length
if audios:
# NOTE: Qwen3-Omni processor accept "audio"
# To make sure the cache works with padding=True, we pre-padded
# the audio to multiple of hop_length.
mm_data["audio"] = [
pad_to_hop_length(audio, hop_length)
if isinstance(audio, np.ndarray)
else (pad_to_hop_length(audio[0], hop_length), audio[1])
for audio in audios
]
# TODO(Isotr0py): Remove this patch after upstream fix PR
# released and Transformers version update:
# https://github.com/huggingface/transformers/pull/41473
mm_kwargs = dict(mm_kwargs)
tok_kwargs = dict(tok_kwargs)
mm_kwargs["audio_kwargs"] = dict(mm_kwargs.get("audio_kwargs") or {})
mm_kwargs["text_kwargs"] = dict(mm_kwargs.get("text_kwargs") or {})
if Version(TRANSFORMERS_VERSION) < Version("4.58.0"):
# Extract audio_sample_rate before restructuring
audio_sample_rate = mm_kwargs.pop("audio_sample_rate", None)
# move truncation to audio_kwargs level to avoid conflict
# with tok_kwargs
mm_kwargs["audio_kwargs"].setdefault("truncation", mm_kwargs.pop("truncation", False))
mm_kwargs["text_kwargs"].setdefault("truncation", tok_kwargs.pop("truncation", False))
# Validate and conditionally pass audio_sample_rate
# WhisperFeatureExtractor has a fixed sampling rate, and vLLM's
# audio loader already resamples audio to the target rate.
# Only pass the value if it matches to avoid unexpected behavior.
if audio_sample_rate is not None:
expected_sr = feature_extractor.sampling_rate
if audio_sample_rate != expected_sr:
logger.warning(
"[%s] audio_sample_rate mismatch: user provided %dHz "
"but model expects %dHz. Ignoring user value. "
"vLLM's audio loader already resampled to %dHz.",
self.__class__.__name__,
audio_sample_rate,
expected_sr,
expected_sr,
)
else:
# Sample rate matches, safe to pass
mm_kwargs["audio_kwargs"]["audio_sample_rate"] = audio_sample_rate
hf_inputs = super()._call_hf_processor(
prompt=prompt,
mm_data=mm_data,
mm_kwargs=mm_kwargs,
tok_kwargs=tok_kwargs,
)
if (
"audio_feature_lengths" in hf_inputs
and "feature_attention_mask" in hf_inputs
and (audios := mm_data.get("audio", []))
):
audio_num_frames = []
for _, audio in enumerate(audios):
audio_length = len(audio[0]) if isinstance(audio, tuple) else len(audio)
num_frame = (
(audio_length // hop_length) if audio_length % hop_length == 0 else (audio_length // hop_length - 1)
)
if mm_kwargs.get("truncation", False):
num_frame = min(num_frame, feature_extractor.n_samples // hop_length)
audio_num_frames.append(num_frame)
hf_inputs["feature_attention_mask"] = [torch.ones(num_frame) for num_frame in audio_num_frames]
hf_inputs["audio_feature_lengths"] = torch.tensor(audio_num_frames)
return hf_inputs
def _maybe_apply_prompt_updates(
self,
mm_items: MultiModalDataItems,
prompt_ids: list[int],
mm_kwargs: MultiModalKwargsItems,
mm_prompt_updates: MultiModalPromptUpdates,
is_update_applied: bool,
) -> tuple[list[int], str, Mapping[str, list[PlaceholderFeaturesInfo]]]:
"""
Qwen3-Omni reimplements this function to handle `use_audio_in_video`.
"""
mm_item_counts = mm_items.get_all_counts()
self._validate_mm_kwargs(mm_kwargs, mm_item_counts)
video_use_audio_in_video = self._get_video_use_audio_in_video(mm_kwargs, mm_prompt_updates)
use_audio_in_video = any(video_use_audio_in_video)
# normal case with `use_audio_in_video=False`
if is_update_applied:
mm_placeholders = self._find_mm_placeholders(
prompt_ids,
mm_prompt_updates,
)
self._validate_mm_placeholders(
mm_placeholders,
mm_item_counts,
)
else:
if use_audio_in_video and "audio" in mm_prompt_updates:
filtered_updates = {k: v for k, v in mm_prompt_updates.items() if k != "audio"}
prompt_ids, mm_placeholders = self._apply_prompt_updates(
prompt_ids,
filtered_updates,
)
mm_placeholders = self._derive_audio_from_video_placeholders(
mm_placeholders,
mm_prompt_updates,
video_use_audio_in_video,
)
else:
prompt_ids, mm_placeholders = self._apply_prompt_updates(
prompt_ids,
mm_prompt_updates,
)
self._validate_mm_placeholders(
mm_placeholders,
mm_item_counts,
)
return prompt_ids, mm_placeholders
# Preserve Omni's per-video overrides while inheriting upstream Qwen3's
# audio processing through the shared, cooperative Qwen2.5 base.
def get_updates_use_audio_in_video(
self,
@@ -978,17 +841,17 @@ class Qwen3OmniMoeThinkerMultiModalProcessor(
return [
PromptReplacement(
modality="audio",
target=audio_token,
target=[audio_token_id],
replacement=get_replacement_qwen2_audio,
),
PromptReplacement(
modality="image",
target=image_token,
target=[image_token_id],
replacement=partial(get_replacement_qwen2_vision, modality="image"),
),
PromptReplacement(
modality="video",
target=video_token,
target=[video_token_id],
replacement=get_replacement_qwen2_video,
),
]
@@ -1114,7 +977,10 @@ class Qwen3OmniMoeConditionalGenerationMixin(Qwen2_5OmniConditionalGenerationMix
audio_input: Qwen2_5OmniAudioFeatureInputs,
) -> tuple[torch.Tensor, ...]:
input_features = audio_input["input_features"]
audio_feature_lengths = audio_input["audio_feature_lengths"]
# vLLM 0.29 marks audio_feature_lengths keep_on_cpu, and the audio tower
# derives device placement from feature_lens, so move it explicitly.
# Mirrors upstream Qwen3OmniMoeThinker._process_audio_input.
audio_feature_lengths = audio_input["audio_feature_lengths"].to(input_features.device, non_blocking=True)
audio_output_lengths = _get_feat_extract_output_lengths(audio_feature_lengths)
@@ -1540,11 +1406,11 @@ class Qwen3OmniMoeThinkerForConditionalGeneration(
return self.language_model.compute_logits(hidden_states)
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
loader = AutoWeightsLoader(
self,
skip_prefixes=["talker.", "code2wav."],
loader = AutoWeightsLoader(self)
loaded_weights = loader.load_weights(
weights,
mapper=(self.hf_to_vllm_mapper) | WeightsMapper(orig_to_new_prefix={"talker.": None, "code2wav.": None}),
)
loaded_weights = loader.load_weights(weights, mapper=self.hf_to_vllm_mapper)
return loaded_weights
@@ -648,6 +648,10 @@ class Qwen3TTSPromptEmbedsBuilder:
# -------------------- speaker encoder / codec encoder --------------------
# Some NPUs (310P, Ascend 950) do not support torch.stft; builders on
# such devices set this flag to compute the mel spectrogram on CPU.
_mel_spectrogram_on_cpu: bool = False
def extract_speaker_embedding(self, wav: np.ndarray, sr: int) -> torch.Tensor:
# vLLM workers do not automatically move arbitrary torch.nn.Modules to
# CUDA. Ensure the speaker encoder is on the same device/dtype as the
@@ -671,7 +675,9 @@ class Qwen3TTSPromptEmbedsBuilder:
# Follow official implementation: mel_spectrogram expects 24kHz. Move
# the waveform first so STFT/mel computation stays on the model device
# instead of materializing a CPU mel tensor and copying it per request.
wav_tensor = torch.from_numpy(wav).to(device=dev, dtype=torch.float32).unsqueeze(0)
# Devices without torch.stft set _mel_spectrogram_on_cpu instead.
mel_device = torch.device("cpu") if self._mel_spectrogram_on_cpu else dev
wav_tensor = torch.from_numpy(wav).to(device=mel_device, dtype=torch.float32).unsqueeze(0)
mels = mel_spectrogram(
wav_tensor,
n_fft=1024,
@@ -682,7 +688,7 @@ class Qwen3TTSPromptEmbedsBuilder:
fmin=0,
fmax=12000,
).transpose(1, 2)
spk = self._speaker_encoder(mels.to(dtype=dtype))[0]
spk = self._speaker_encoder(mels.to(device=dev, dtype=dtype))[0]
return spk.to(dtype=dtype)
def encode_ref_audio_batch(
@@ -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
@@ -11,7 +14,7 @@ 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.model_executor.model_loader import DefaultModelLoader
from vllm.model_executor.models.utils import AutoWeightsLoader
from vllm.model_executor.models.utils import AutoWeightsLoader, WeightsMapper
from vllm_omni.engine.init_timeline import timed_phase
from vllm_omni.model_executor.models.output_templates import OmniOutput
@@ -554,10 +557,9 @@ class Qwen3TTSCode2Wav(nn.Module):
subfolder="speech_tokenizer",
)
subfolder_weights = model_loader._get_weights_iterator(source)
loaded = AutoWeightsLoader(
self,
skip_prefixes=["encoder."],
).load_weights(subfolder_weights)
loaded = AutoWeightsLoader(self).load_weights(
subfolder_weights, mapper=WeightsMapper(orig_to_new_prefix={"encoder.": None})
)
device = self.vllm_config.device_config.device
self.decoder.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
from __future__ import annotations
import copy
@@ -1157,10 +1160,9 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
subfolder="speech_tokenizer",
)
subfolder_weights = model_loader._get_weights_iterator(source)
enc_loaded = AutoWeightsLoader(
self,
skip_prefixes=["decoder."],
).load_weights(subfolder_weights)
enc_loaded = AutoWeightsLoader(self).load_weights(
subfolder_weights, mapper=WeightsMapper(orig_to_new_prefix={"decoder.": None})
)
loaded |= enc_loaded
# AutoWeightsLoader only loads parameters; the encoder's VQ
@@ -309,6 +309,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",
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""
Step-Audio2 Thinker - Stage 1 LLM for Audio Understanding
@@ -19,6 +22,7 @@ import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils.rnn import pad_sequence
from transformers import AutoTokenizer
from transformers.feature_extraction_utils import BatchFeature
from transformers.processing_utils import ProcessorMixin
from vllm.config import VllmConfig
from vllm.inputs import MultiModalDataDict
@@ -503,6 +507,10 @@ class StepAudio2MultiModalProcessor(BaseMultiModalProcessor[StepAudio2Processing
processor = self.info.get_hf_processor(**hf_processor_mm_kwargs)
audio_token = getattr(processor, "audio_token", "<audio_patch>")
audio_token_ids = self.info.get_tokenizer().encode(
audio_token,
add_special_tokens=False,
)
audio_items = mm_items.get("audio", [])
num_audio_items = len(audio_items) if audio_items else 0
@@ -548,27 +556,22 @@ class StepAudio2MultiModalProcessor(BaseMultiModalProcessor[StepAudio2Processing
return [
PromptReplacement(
modality="audio",
target=audio_token,
target=audio_token_ids,
replacement=get_replacement_audio,
)
]
def _call_hf_processor(
def _preprocess_hf_mm_data(
self,
prompt: str,
mm_data: Mapping[str, object],
mm_kwargs: Mapping[str, object] | None = None,
tok_kwargs: Mapping[str, object] | None = None,
**_: object,
):
"""Call HF processor and post-process outputs"""
hf_processor_mm_kwargs: Mapping[str, object],
) -> tuple[Mapping[str, object], Mapping[str, object]]:
mm_data, hf_processor_mm_kwargs = super()._preprocess_hf_mm_data(
mm_data,
hf_processor_mm_kwargs,
)
mm_data = dict(mm_data)
audios = mm_data.pop("audios", [])
mm_kwargs = mm_kwargs or {}
tok_kwargs = tok_kwargs or {}
# CRITICAL: Ensure audios is ALWAYS a list to prevent string iteration
if audios:
if isinstance(audios, str):
mm_data["audio"] = [audios]
@@ -576,20 +579,24 @@ class StepAudio2MultiModalProcessor(BaseMultiModalProcessor[StepAudio2Processing
mm_data["audio"] = audios
else:
mm_data["audio"] = [audios]
return mm_data, hf_processor_mm_kwargs
hf_inputs = super()._call_hf_processor(
prompt=prompt,
mm_data=mm_data,
mm_kwargs=mm_kwargs,
tok_kwargs=tok_kwargs,
def _postprocess_hf_mm_data(
self,
mm_data: Mapping[str, object],
hf_processor_mm_kwargs: Mapping[str, object],
processed_data: BatchFeature,
) -> BatchFeature:
processed_data = super()._postprocess_hf_mm_data(
mm_data,
hf_processor_mm_kwargs,
processed_data,
)
if "audio_mels" not in hf_inputs:
hf_inputs["audio_mels"] = torch.empty((0, 128, 0))
if "audio_lens" not in hf_inputs:
hf_inputs["audio_lens"] = torch.tensor([], dtype=torch.int32)
return hf_inputs
if "audio_mels" not in processed_data:
processed_data["audio_mels"] = torch.empty((0, 128, 0))
if "audio_lens" not in processed_data:
processed_data["audio_lens"] = torch.tensor([], dtype=torch.int32)
return processed_data
# ============================================================================
@@ -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():
@@ -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
import math
from collections.abc import Iterable, Mapping, Sequence
@@ -48,11 +48,9 @@ from vllm.multimodal.parse import AudioProcessorItems, MultiModalDataItems, Mult
from vllm.multimodal.processing import BaseDummyInputsBuilder, BaseMultiModalProcessor
from vllm.multimodal.processing.processor import (
BaseProcessingInfo,
MultiModalProcessingInfo,
ProcessorInputs,
PromptReplacement,
PromptUpdate,
TimingContext,
)
from vllm.sequence import IntermediateTensors
from vllm.tokenizers import cached_tokenizer_from_config
@@ -871,7 +869,7 @@ class VoxtralTTSMultiModalProcessor(BaseMultiModalProcessor[VoxtralTTSProcessing
return [
PromptReplacement(
modality="audio",
target="", # Never match the prompt (see below note)
target=[audio_id],
replacement=get_replacement,
),
]
@@ -899,15 +897,24 @@ class VoxtralTTSMultiModalProcessor(BaseMultiModalProcessor[VoxtralTTSProcessing
)
return mm_processed_data
def _cached_apply_hf_processor(
def _maybe_apply_prompt_updates(
self,
inputs: ProcessorInputs,
timing_ctx: TimingContext,
) -> tuple[list[int], MultiModalProcessingInfo, bool]:
prompt_ids, mm_info, _ = super()._cached_apply_hf_processor(inputs, timing_ctx)
# NOTE: The tokens are already inserted by the chat template
return prompt_ids, mm_info, True
mm_items: MultiModalDataItems,
prompt_ids: list[int],
mm_kwargs: MultiModalKwargsItems,
mm_prompt_updates,
):
# Voxtral's Mistral chat template has already inserted the complete
# audio-token run, so locate it without applying the replacement again.
mm_item_counts = mm_items.get_all_counts()
self._validate_mm_kwargs(mm_kwargs, mm_item_counts)
self._validate_mm_updates(mm_prompt_updates, mm_item_counts)
mm_placeholders = self._find_mm_placeholders(
prompt_ids,
mm_prompt_updates,
)
self._validate_mm_placeholders(mm_placeholders, mm_item_counts)
return prompt_ids, mm_placeholders
@MULTIMODAL_REGISTRY.register_processor(