merge from main

This commit is contained in:
yinpeiqi committed 2025-11-30 14:17:26 +07:00
commit 0e808ac42a
147 files changed
+14497 -1341

No files matched your search

@@ -1 +1,4 @@
from .qwen3_omni import Qwen3OmniMoeForConditionalGeneration
from .registry import OmniModelRegistry # noqa: F401
__all__ = ["Qwen3OmniMoeForConditionalGeneration"]
@@ -0,0 +1,13 @@
from typing import NamedTuple, Optional
import torch
from vllm.sequence import IntermediateTensors
class OmniOutput(NamedTuple):
"""Output from the merged Omni model containing both text and audio."""
text_hidden_states: torch.Tensor
multimodal_outputs: Optional[dict] = None
intermediate_tensors: Optional[IntermediateTensors] = None
next_token_id: Optional[torch.Tensor] = None
@@ -2,7 +2,7 @@ import glob
import os
from collections.abc import Iterable
from functools import cached_property
from typing import NamedTuple, Optional, Union
from typing import Optional, Union
import numpy as np
import torch
@@ -26,6 +26,7 @@ from vllm.v1.sample.metadata import SamplingMetadata
from vllm.v1.sample.sampler import Sampler
from vllm_omni.model_executor.model_loader.weight_utils import download_weights_from_hf_specific
from vllm_omni.model_executor.models.output_templates import OmniOutput
from vllm_omni.model_executor.models.qwen2_5_omni.qwen2_5_omni_thinker import (
Qwen2_5OmniConditionalGenerationMixin,
Qwen2_5OmniThinkerDummyInputsBuilder,
@@ -40,14 +41,6 @@ TALKER_CODEC_EOS_TOKEN_ID = 8294
TALKER_CODEC_BOS_TOKEN_ID = 8293
class OmniOutput(NamedTuple):
"""Output from the merged Omni model containing both text and audio."""
text_hidden_states: torch.Tensor
multimodal_outputs: dict = {}
intermediate_tensors: Optional[IntermediateTensors] = None
logger = init_logger(__name__)
@@ -304,7 +297,7 @@ class Qwen2_5OmniForConditionalGeneration(
code = code[1:] if code[0] == TALKER_CODEC_BOS_TOKEN_ID else code
audio_tensor = self.generate_audio(code, voice_type)
return OmniOutput(text_hidden_states=None, multimodal_outputs={"audio": audio_tensor})
return OmniOutput(text_hidden_states=None, multimodal_outputs={"model_outputs": audio_tensor})
return OmniOutput(
text_hidden_states=torch.cat(
@@ -0,0 +1,3 @@
from .qwen3_omni import Qwen3OmniMoeForConditionalGeneration
__all__ = ["Qwen3OmniMoeForConditionalGeneration"]
@@ -0,0 +1,173 @@
from __future__ import annotations
import torch
import torch.nn.functional as F
from torch import nn
from vllm.config import VllmConfig
from vllm.logger import init_logger
from vllm.model_executor.layers.fused_moe import FusedMoE
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_moe import (
Qwen3MoeDecoderLayer,
Qwen3MoeMLP,
Qwen3MoeModel, # as _BaseQwen3MoeModel,
)
from vllm.model_executor.models.qwen3_moe import (
Qwen3MoeForCausalLM as _BaseQwen3MoeForCausalLM,
)
from vllm.model_executor.models.utils import (
PPMissingLayer,
maybe_prefix,
)
logger = init_logger(__name__)
# Individual expert MoE block using Qwen3MoeMLP instead of FusedMoE
class Qwen3OmniMoeSparseMoeBlock(nn.Module):
"""Sparse MoE block using individual Qwen3MoeMLP experts instead of FusedMoE."""
def __init__(
self,
vllm_config: VllmConfig,
prefix: str = "",
):
super().__init__()
config = vllm_config.model_config.hf_text_config
quant_config = vllm_config.quant_config
self.num_experts = config.num_experts
self.top_k = config.num_experts_per_tok
self.norm_topk_prob = config.norm_topk_prob
self.hidden_size = config.hidden_size
# Create individual expert MLPs
self.experts = nn.ModuleList(
[
Qwen3MoeMLP(
hidden_size=config.hidden_size,
intermediate_size=config.moe_intermediate_size,
hidden_act=config.hidden_act,
quant_config=quant_config,
reduce_results=False,
prefix=f"{prefix}.experts.{i}",
)
for i in range(self.num_experts)
]
)
# Router for expert selection
from vllm.model_executor.layers.linear import ReplicatedLinear
self.gate = ReplicatedLinear(
config.hidden_size, config.num_experts, bias=False, quant_config=quant_config, prefix=f"{prefix}.gate"
)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
"""Forward pass using individual experts."""
# Handle 3D inputs (batch, seq_len, hidden_size) by reshaping to 2D
orig_shape = hidden_states.shape
if hidden_states.dim() == 3:
batch_size, seq_len, hidden_dim = hidden_states.shape
hidden_states = hidden_states.view(-1, hidden_dim)
elif hidden_states.dim() == 2:
num_tokens, hidden_dim = hidden_states.shape
elif hidden_states.dim() == 1:
hidden_states = hidden_states.unsqueeze(0)
num_tokens, hidden_dim = hidden_states.shape
else:
raise ValueError(
f"Qwen3OmniMoeSparseMoeBlock only supports 1D, 2D, or 3D inputs, got {hidden_states.dim()}D"
)
is_input_1d = len(orig_shape) == 1
hidden_states = hidden_states.view(-1, hidden_dim)
# Get router logits and select experts (matching transformers)
router_logits, _ = self.gate(hidden_states)
selected_experts, routing_weights = self._route_tokens(router_logits)
# Forward through individual experts
final_hidden_states = self._forward_experts(hidden_states, selected_experts, routing_weights)
# Reshape back to original shape
if is_input_1d:
return final_hidden_states.squeeze(0)
elif len(orig_shape) == 3:
# Reshape back to 3D (batch, seq_len, hidden_dim)
return final_hidden_states.view(orig_shape)
else:
return final_hidden_states
def _route_tokens(self, router_logits: torch.Tensor):
"""Route tokens to experts using top-k selection (matching transformers)."""
routing_weights = F.softmax(router_logits, dim=-1, dtype=torch.float)
routing_weights, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1)
if self.norm_topk_prob:
routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
routing_weights = routing_weights.to(router_logits.dtype)
return selected_experts, routing_weights
def _forward_experts(
self, hidden_states: torch.Tensor, selected_experts: torch.Tensor, routing_weights: torch.Tensor
):
"""Forward through individual experts (matching transformers implementation)."""
final_hidden_states = torch.zeros_like(hidden_states)
expert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_experts).permute(2, 1, 0)
expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
for expert_idx in expert_hit:
idx, top_x = torch.where(expert_mask[expert_idx].squeeze(0))
current_state = hidden_states[None, top_x].reshape(-1, hidden_states.shape[-1])
current_hidden_states = self.experts[expert_idx](current_state) * routing_weights[top_x, idx, None]
final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
return final_hidden_states
class Qwen3MoeForCausalLM(_BaseQwen3MoeForCausalLM):
"""Thin wrapper to swap in the patched `Qwen3MoeModel`."""
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
# Don't call super().__init__() to avoid duplicate layer registration.
nn.Module.__init__(self)
config = vllm_config.model_config.hf_text_config
quant_config = vllm_config.quant_config
self.config = config
self.quant_config = quant_config
self.model = Qwen3MoeModel(vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model"))
self.lm_head = ParallelLMHead(
config.vocab_size, config.hidden_size, quant_config=quant_config, prefix=maybe_prefix(prefix, "lm_head")
)
if self.config.tie_word_embeddings:
self.lm_head.weight = self.model.embed_tokens.weight
self.logits_processor = LogitsProcessor(config.vocab_size)
self.make_empty_intermediate_tensors = self.model.make_empty_intermediate_tensors
# Set MoE hyperparameters for individual experts
self.expert_weights = []
self.moe_layers: list[FusedMoE] = []
example_layer = None
for layer in self.model.layers:
if isinstance(layer, PPMissingLayer):
continue
assert isinstance(layer, Qwen3MoeDecoderLayer)
if isinstance(layer.mlp, FusedMoE):
example_layer = layer.mlp
self.moe_layers.append(layer.mlp)
if example_layer is None:
raise RuntimeError("No Qwen3OmniMoe layer found in the model.layers.")
self.num_moe_layers = len(self.moe_layers)
self.num_expert_groups = 1
self.num_shared_experts = 0
self.num_logical_experts = example_layer.n_logical_experts
self.num_physical_experts = example_layer.n_physical_experts
self.num_local_physical_experts = example_layer.n_local_physical_experts
self.num_routed_experts = example_layer.n_routed_experts
self.num_redundant_experts = example_layer.n_redundant_experts
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,224 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Copyright 2025 The Qwen team.
"""Inference-only Qwen3-Omni-Moe Code2Wav model."""
from __future__ import annotations
from collections.abc import Iterable
import numpy as np
import torch
import torch.nn as nn
from transformers.models.qwen3_omni_moe.configuration_qwen3_omni_moe import (
Qwen3OmniMoeCode2WavConfig,
)
from transformers.models.qwen3_omni_moe.modeling_qwen3_omni_moe import (
Qwen3OmniMoeCausalConvNet,
Qwen3OmniMoeCausalTransConvNet,
Qwen3OmniMoeCode2WavDecoderBlock,
Qwen3OmniMoeCode2WavTransformerModel,
Qwen3OmniMoeConvNeXtBlock,
SnakeBeta,
)
from vllm.config import VllmConfig # type: ignore
from vllm.logger import init_logger # type: ignore
from vllm.model_executor.models.utils import ( # type: ignore
AutoWeightsLoader,
WeightsMapper,
)
logger = init_logger(__name__)
class Qwen3OmniMoeCode2Wav(nn.Module):
"""
Qwen3 Omni MoE Code2Wav - Converts num_quantizers-layer RVQ codec codes to audio waveform.
Architecture:
1. Code Embedding: Embed and average num_quantizers RVQ layers
2. Pre-Transformer: Add temporal context via sliding-window attention
3. Upsampling: Progressive upsampling with ConvNeXt blocks
4. Decoder: Multi-stage upsampling + residual units → waveform
Input: [batch, num_quantizers, seq_len] - num_quantizers-layer RVQ codes
Output: [batch, 1, waveform_len] - Audio waveform [-1, 1]
Total upsampling factor: ~1280x
Example: 100 codec frames → 128,000 audio samples (8 seconds at 16kHz)
"""
input_modalities = "audio"
# Weight mapper
hf_to_vllm_mapper = WeightsMapper(
orig_to_new_prefix={
"code2wav.pre_transformer.": "pre_transformer.",
"code2wav.code_embedding.": "code_embedding.",
"code2wav.upsample.": "upsample.",
"code2wav.decoder.": "decoder.",
"code2wav.": "",
}
)
def __init__(
self,
*,
vllm_config: VllmConfig | None = None,
prefix: str = "",
):
super().__init__()
self.config: Qwen3OmniMoeCode2WavConfig = vllm_config.model_config.hf_config
# Calculate total upsampling factor
self.total_upsample = np.prod(self.config.upsample_rates + self.config.upsampling_ratios)
# Pre-transformer
self.pre_transformer = Qwen3OmniMoeCode2WavTransformerModel._from_config(self.config)
# Code embedding: Single embedding table for all RVQ layers
self.code_embedding = nn.Embedding(
self.config.codebook_size * self.config.num_quantizers, self.config.hidden_size
)
# Offset for each RVQ layer (layer 0: 0-1023, layer 1: 1024-2047, etc.)
self.register_buffer(
"code_offset",
torch.arange(self.config.num_quantizers).view(1, -1, 1) * self.config.codebook_size,
persistent=False,
)
# Upsampling blocks (e.g., 2x, 2x)
upsample = []
for factor in self.config.upsampling_ratios:
upsample.append(
nn.ModuleList(
[
Qwen3OmniMoeCausalTransConvNet(
self.config.hidden_size, self.config.hidden_size, factor, factor
),
Qwen3OmniMoeConvNeXtBlock(self.config.hidden_size),
]
)
)
self.upsample = nn.ModuleList(upsample)
# Decoder: Initial projection + progressive upsampling blocks
decoder = [Qwen3OmniMoeCausalConvNet(self.config.hidden_size, self.config.decoder_dim, kernel_size=7)]
# Add decoder blocks (each upsamples and reduces channels)
for i in range(len(self.config.upsample_rates)):
decoder.append(Qwen3OmniMoeCode2WavDecoderBlock(self.config, i))
# Final projection to waveform
output_dim = self.config.decoder_dim // 2 ** len(self.config.upsample_rates)
decoder += [
SnakeBeta(output_dim),
Qwen3OmniMoeCausalConvNet(output_dim, 1, kernel_size=7),
]
self.decoder = nn.ModuleList(decoder)
def forward(self, codes: torch.Tensor) -> torch.Tensor:
"""
Convert num_quantizers-layer RVQ codes to audio waveform.
Args:
codes: [batch, num_quantizers, seq_len] - num_quantizers-layer RVQ codec codes
Returns:
waveform: [batch, 1, waveform_len] - Audio waveform clipped to [-1, 1]
"""
if codes.shape[1] != self.config.num_quantizers:
raise ValueError(f"Expected {self.config.num_quantizers} layers of codes, got {codes.shape[1]}")
# Stage 1: Code Embedding
# Add offset to separate layer vocabularies, then embed and average
hidden = self.code_embedding(codes + self.code_offset).mean(1)
# Shape: [batch, seq_len, hidden_size]
# Stage 2: Pre-Transformer (add temporal context)
hidden = self.pre_transformer(inputs_embeds=hidden).last_hidden_state
# Shape: [batch, seq_len, hidden_size]
# Stage 3: Upsampling
hidden = hidden.permute(0, 2, 1) # [batch, hidden_size, seq_len]
for blocks in self.upsample:
for block in blocks:
hidden = block(hidden)
# Shape: [batch, hidden_size, seq_len * upsample_factor]
# Stage 4: Decoder (progressive upsampling to waveform)
wav = hidden
for block in self.decoder:
wav = block(wav)
# Shape: [batch, 1, waveform_len]
# Clamp to valid audio range
return wav.clamp(min=-1.0, max=1.0)
def chunked_decode(
self,
codes: torch.Tensor,
chunk_size: int = 300,
left_context_size: int = 25,
) -> torch.Tensor:
"""
Decode long sequences in chunks to avoid OOM.
Uses overlapping chunks with left context to avoid boundary artifacts.
Args:
codes: [batch, num_quantizers, seq_len] - num_quantizers-layer RVQ codes
chunk_size: Number of codec frames per chunk
left_context_size: Number of overlapping frames for context
Returns:
waveform: [batch, 1, waveform_len] - Complete waveform
"""
wavs = []
start_index = 0
while start_index < codes.shape[-1]:
end_index = min(start_index + chunk_size, codes.shape[-1])
context_size = left_context_size if start_index >= left_context_size else start_index
# Extract chunk with left context
codes_chunk = codes[..., start_index - context_size : end_index]
# Decode chunk
wav_chunk = self(codes_chunk)
# Remove context from output (context_size * total_upsample samples)
wavs.append(wav_chunk[..., context_size * self.total_upsample :])
start_index = end_index
return torch.cat(wavs, dim=-1)
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
)
loaded = loader.load_weights(weights, mapper=self.hf_to_vllm_mapper)
# Log load summary
try:
total_bytes = 0
for name, param in self.named_parameters():
if param is not None and param.data is not None:
total_bytes += param.data.numel() * param.data.element_size()
device = next(self.parameters()).device
logger.info(
"[Model Loaded] name=%s, success=%s, size=%.2f MB, device=%s",
self.__class__.__name__,
True,
total_bytes / (1024**2),
str(device),
)
except Exception:
pass
return loaded
@@ -0,0 +1,491 @@
"""Qwen3-Omni Code Predictor with MTP (Multi-Token Prediction) support.
This module implements the code predictor component for Qwen3-Omni talker models.
The code predictor generates residual RVQ (Residual Vector Quantization) codes
autoregressively, predicting layers 1 to N based on layer-0 codes from the talker.
"""
from typing import Any, Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import Cache, PretrainedConfig
from transformers.models.qwen3_omni_moe.modeling_qwen3_omni_moe import Qwen3OmniMoeRotaryEmbedding
from vllm.config import CacheConfig, ModelConfig, VllmConfig
from vllm.logger import init_logger
from vllm.model_executor.layers.layernorm import RMSNorm
from vllm.model_executor.layers.quantization import QuantizationConfig
from vllm.model_executor.layers.vocab_parallel_embedding import VocabParallelEmbedding
logger = init_logger(__name__)
# ============================================================================
# Rotary Embeddings and Helper Functions
# ============================================================================
class Qwen3OmniCodePredictorRotaryEmbedding(nn.Module):
"""Rotary positional embeddings for the code predictor."""
def __init__(self, dim, max_position_embeddings=2048, base=10000):
super().__init__()
self.dim = dim
self.max_position_embeddings = max_position_embeddings
self.base = base
inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float() / self.dim))
self.register_buffer("inv_freq", inv_freq, persistent=False)
def forward(self, x: torch.Tensor, position_ids: torch.LongTensor) -> tuple[torch.Tensor, torch.Tensor]:
inv_freq = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
position = position_ids[:, None, :].float()
freqs = (inv_freq @ position).transpose(1, 2)
emb = torch.cat((freqs, freqs), dim=-1)
cos = emb.cos().to(x.dtype)
sin = emb.sin().to(x.dtype)
return cos, sin
def rotate_half(x):
"""Rotates half the hidden dims of the input."""
x1 = x[..., : x.shape[-1] // 2]
x2 = x[..., x.shape[-1] // 2 :]
return torch.cat((-x2, x1), dim=-1)
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
"""Applies Rotary Position Embedding to the query and key tensors.
Args:
q (`torch.Tensor`): The query tensor.
k (`torch.Tensor`): The key tensor.
cos (`torch.Tensor`): The cosine part of the rotary embedding.
sin (`torch.Tensor`): The sine part of the rotary embedding.
position_ids (`torch.Tensor`, *optional*):
Deprecated and unused.
unsqueeze_dim (`int`, *optional*, defaults to 1):
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
Returns:
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
"""
cos = cos.unsqueeze(unsqueeze_dim)
sin = sin.unsqueeze(unsqueeze_dim)
q_embed = (q * cos) + (rotate_half(q) * sin)
k_embed = (k * cos) + (rotate_half(k) * sin)
return q_embed, k_embed
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
"""Repeat key/value heads for grouped query attention."""
if n_rep == 1:
return hidden_states
bsz, num_kv_heads, seq_len, head_dim = hidden_states.shape
hidden_states = hidden_states[:, :, None, :, :].expand(bsz, num_kv_heads, n_rep, seq_len, head_dim)
return hidden_states.reshape(bsz, num_kv_heads * n_rep, seq_len, head_dim)
# ============================================================================
# Code Predictor Attention Layer
# ============================================================================
class Qwen3OmniCodePredictorAttention(nn.Module):
"""Multi-head self-attention for code predictor with vLLM optimization."""
def __init__(self, config, layer_idx: int, vllm_config: VllmConfig = None):
super().__init__()
self.num_heads = config.code_predictor_config.num_attention_heads
self.num_key_value_heads = config.code_predictor_config.num_key_value_heads
self.head_dim = getattr(
config.code_predictor_config,
"head_dim",
config.code_predictor_config.hidden_size // config.code_predictor_config.num_attention_heads,
)
self.hidden_size = config.code_predictor_config.hidden_size
if self.num_heads % self.num_key_value_heads != 0:
raise ValueError("num_attention_heads must be divisible by num_key_value_heads")
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
# Projection layers
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
# Query/Key normalization
self.q_norm = RMSNorm(self.head_dim, eps=config.code_predictor_config.rms_norm_eps)
self.k_norm = RMSNorm(self.head_dim, eps=config.code_predictor_config.rms_norm_eps)
self.is_causal = True
self.config = config
def forward(
self,
hidden_states: torch.Tensor,
causal_mask: torch.Tensor,
cos: torch.Tensor,
sin: torch.Tensor,
past_key_values: Optional[Cache] = None,
cache_position: Optional[torch.LongTensor] = None,
use_cache: bool = False,
position_ids: Optional[torch.LongTensor] = None,
) -> torch.Tensor:
bsz, seq_len, _ = hidden_states.shape
# Project to Q, K, V
q = self.q_proj(hidden_states).view(bsz, seq_len, self.num_heads, self.head_dim)
k = self.k_proj(hidden_states).view(bsz, seq_len, self.num_key_value_heads, self.head_dim)
v = self.v_proj(hidden_states).view(bsz, seq_len, self.num_key_value_heads, self.head_dim)
# Apply normalization
q = self.q_norm(q)
k = self.k_norm(k)
# Apply RoPE
q_heads = q.transpose(1, 2).contiguous()
k_heads = k.transpose(1, 2).contiguous()
q_heads, k_heads = apply_rotary_pos_emb(q_heads, k_heads, cos, sin)
v_heads = v.transpose(1, 2).contiguous()
if past_key_values is not None:
# sin and cos are specific to RoPE models; cache_position needed for the static cache
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
k_heads, v_heads = past_key_values.update(k_heads, v_heads, self.layer_idx, cache_kwargs)
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS
attention_interface = ALL_ATTENTION_FUNCTIONS["flash_attention_2"]
attn_output, _ = attention_interface(
self,
q_heads,
k_heads,
v_heads,
None,
dropout=0.0 if not self.training else self.attention_dropout,
scaling=self.head_dim**-0.5,
sliding_window=None,
use_cache=use_cache,
position_ids=position_ids,
output_hidden_states=True,
output_attentions=False,
)
attn_output = attn_output.reshape(*(hidden_states.shape[:-1]), -1).contiguous()
attn_output = self.o_proj(attn_output)
return attn_output
# ============================================================================
# Code Predictor MLP Layer
# ============================================================================
class Qwen3OmniCodePredictorMLP(nn.Module):
"""Feed-forward network for code predictor."""
def __init__(self, config):
super().__init__()
self.gate_proj = nn.Linear(
config.code_predictor_config.hidden_size, config.code_predictor_config.intermediate_size, bias=False
)
self.up_proj = nn.Linear(
config.code_predictor_config.hidden_size, config.code_predictor_config.intermediate_size, bias=False
)
self.down_proj = nn.Linear(
config.code_predictor_config.intermediate_size, config.code_predictor_config.hidden_size, bias=False
)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
gate = F.silu(self.gate_proj(hidden_states))
up = self.up_proj(hidden_states)
return self.down_proj(gate * up)
# ============================================================================
# MTP Layer (Multi-Token Prediction Layer)
# ============================================================================
class Qwen3OmniCodePredictorMTPLayer(nn.Module):
"""MTP layer for speculative decoding - predicts next residual code layer."""
def __init__(
self,
config: PretrainedConfig,
prefix: str,
model_config: ModelConfig,
layer_idx: int,
cache_config: Optional[CacheConfig] = None,
quant_config: Optional[QuantizationConfig] = None,
) -> None:
super().__init__()
self.layer_idx = layer_idx
self.config = config
# Qwen3OmniCodePredictorDecoderLayer
self.self_attn = Qwen3OmniCodePredictorAttention(
config,
layer_idx,
vllm_config=type(
"VllmConfig",
(),
{"cache_config": cache_config, "quant_config": quant_config, "model_config": model_config},
)(),
)
self.mlp = Qwen3OmniCodePredictorMLP(config)
self.input_layernorm = RMSNorm(
config.code_predictor_config.hidden_size, eps=config.code_predictor_config.rms_norm_eps
)
self.post_attention_layernorm = RMSNorm(
config.code_predictor_config.hidden_size, eps=config.code_predictor_config.rms_norm_eps
)
def mtp_block(
self,
hidden_states: torch.Tensor,
causal_mask: torch.Tensor,
cos: torch.Tensor,
sin: torch.Tensor,
past_key_values: Optional[Cache] = None,
cache_position: Optional[torch.LongTensor] = None,
use_cache: bool = False,
position_ids: Optional[torch.LongTensor] = None,
) -> torch.Tensor:
# Self-attention with residual
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
hidden_states = self.self_attn(
hidden_states, causal_mask, cos, sin, past_key_values, cache_position, use_cache, position_ids
)
hidden_states = residual + hidden_states
# MLP with residual
residual = hidden_states
hidden_states = self.post_attention_layernorm(hidden_states)
hidden_states = self.mlp(hidden_states)
hidden_states = residual + hidden_states
return hidden_states
def forward(
self,
input_ids: torch.Tensor,
positions: torch.Tensor,
previous_hidden_states: torch.Tensor,
inputs_embeds: Optional[torch.Tensor] = None,
spec_step_index: int = 0,
) -> torch.Tensor:
assert inputs_embeds is not None, "inputs_embeds required for MTP"
# Mask position 0 (not needed for MTP)
inputs_embeds[positions == 0] = 0
hidden_states = torch.cat([inputs_embeds, previous_hidden_states], dim=-1)
# Get position info for RoPE
batch_size, seq_len, _ = hidden_states.shape
device = hidden_states.device
position_ids = torch.arange(seq_len, dtype=torch.long, device=device).unsqueeze(0).expand(batch_size, -1)
# Get RoPE embeddings
head_dim = self.self_attn.head_dim
rotary_emb = Qwen3OmniCodePredictorRotaryEmbedding(
head_dim, max_position_embeddings=self.config.code_predictor_config.max_position_embeddings
)
rotary_emb = Qwen3OmniMoeRotaryEmbedding(self.config)
cos, sin = rotary_emb(hidden_states, position_ids)
# Create causal mask
causal_mask = (
torch.triu(torch.ones(seq_len, seq_len, dtype=torch.bool, device=device), diagonal=1)
.unsqueeze(0)
.unsqueeze(0)
)
causal_mask = causal_mask.masked_fill(causal_mask, float("-inf"))
# Forward through MTP block
hidden_states = self.mtp_block(hidden_states, causal_mask, cos, sin)
return hidden_states
class Qwen3OmniCodePredictorBaseModel(nn.Module):
"""
Base model for code predictor - matches HF Qwen3OmniMoeTalkerCodePredictorModel structure.
This is a simple transformer that processes inputs_embeds and outputs hidden states.
"""
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
super().__init__()
config = vllm_config.model_config.hf_config.code_predictor_config
self.config = config
self.vocab_size = config.vocab_size
self.num_code_groups = config.num_code_groups
# Codec embeddings (for layers 1-num_code_groups-1)
self.codec_embedding = nn.ModuleList(
[
VocabParallelEmbedding(
config.vocab_size,
config.hidden_size,
)
for _ in range(config.num_code_groups - 1)
]
)
# Decoder layers
self.layers = nn.ModuleList(
[
Qwen3OmniCodePredictorMTPLayer(
vllm_config.model_config.hf_config,
f"{prefix}.layers.{idx}",
model_config=vllm_config.model_config,
layer_idx=idx,
cache_config=vllm_config.cache_config,
quant_config=vllm_config.quant_config,
)
for idx in range(config.num_hidden_layers)
]
)
self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
# RoPE
self.rotary_emb = Qwen3OmniMoeRotaryEmbedding(config=config)
def forward(
self,
inputs_embeds: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Any] = None,
use_cache: Optional[bool] = False,
cache_position: Optional[torch.LongTensor] = None,
**kwargs,
):
"""
Forward pass matching HF structure.
Args:
inputs_embeds: [batch, seq_len, hidden_size]
Returns:
Object with .last_hidden_state attribute
"""
batch_size, seq_len, _ = inputs_embeds.shape
# Create positions tensor if not provided
# positions must be [num_tokens] or [batch_size, seq_len]
if position_ids is None:
if cache_position is not None:
position_ids = cache_position # [num_tokens]
else:
position_ids = torch.arange(seq_len, device=inputs_embeds.device).unsqueeze(0) # [1, seq_len]
else:
position_ids = position_ids.flatten() # Ensure [num_tokens]
# Extract cos/sin from rotary_emb cache
# The cos_sin_cache is [max_pos, rotary_dim * 2]
cos, sin = self.rotary_emb(inputs_embeds, position_ids)
# Create causal mask
device = inputs_embeds.device
causal_mask = (
torch.triu(torch.ones(seq_len, seq_len, dtype=torch.bool, device=device), diagonal=1)
.unsqueeze(0)
.unsqueeze(0)
)
causal_mask = causal_mask.masked_fill(causal_mask, float("-inf"))
# Forward through decoder layers
hidden_states = inputs_embeds
for layer in self.layers:
hidden_states = layer.mtp_block(
hidden_states, causal_mask, cos, sin, past_key_values, cache_position, use_cache, position_ids
)
# Final norm
hidden_states = self.norm(hidden_states)
# Return in HF-compatible format
from collections import namedtuple
Output = namedtuple("Output", ["last_hidden_state", "past_key_values"])
return Output(last_hidden_state=hidden_states, past_key_values=None) # [batch, num_code_groups-1, hidden_size]
def get_input_embeddings(self):
"""Return codec embeddings for HF compatibility."""
return self.codec_embedding
class Qwen3OmniMoeTalkerCodePredictor(nn.Module):
"""
Code predictor wrapper matching HF structure.
Structure:
- self.model: Qwen3OmniCodePredictorBaseModel (transformer)
- self.lm_head: ModuleList of output heads
"""
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
super().__init__()
talker_code_predictor_config = vllm_config.model_config.hf_config
self.quant_config = vllm_config.quant_config
self.prefix = prefix
self.config = talker_code_predictor_config
self.vocab_size = self.config.code_predictor_config.vocab_size
self.num_code_groups = self.config.code_predictor_config.num_code_groups
# Base transformer model (matches HF structure)
self.model = Qwen3OmniCodePredictorBaseModel(vllm_config=vllm_config, prefix=prefix)
# Output heads for each residual layer (1-num_layers-1)
self.lm_head = nn.ModuleList(
[
nn.Linear(
self.config.code_predictor_config.hidden_size,
self.config.code_predictor_config.vocab_size,
bias=False,
)
for _ in range(self.num_code_groups - 1)
]
)
def forward(
self,
inputs_embeds: torch.Tensor, # [batch, seq_len, hidden_size]
layer_idx: int, # Which layer to predict (0-num_layers-2 for layers 1-num_layers-1)
) -> tuple[torch.Tensor, torch.Tensor]:
"""
Forward pass for code predictor.
Args:
inputs_embeds: Input embeddings [batch_size, seq_len, hidden_size]
layer_idx: Which residual layer to predict (0-num_layers-2 for layers 1-num_layers-1)
Returns:
logits: Predicted logits [batch_size, seq_len, vocab_size]
hidden_states: Output hidden states [batch_size, seq_len, hidden_size]
"""
# Pass through base model
hidden_states = self.model(inputs_embeds)
# Get logits from corresponding head
logits = self.lm_head[layer_idx](hidden_states)
return logits, hidden_states
@@ -0,0 +1,703 @@
from collections.abc import Iterable
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers.models.qwen3_omni_moe.configuration_qwen3_omni_moe import (
Qwen3OmniMoeTalkerConfig,
)
from transformers.models.qwen3_omni_moe.modeling_qwen3_omni_moe import (
Qwen3OmniMoeAudioEncoder,
)
from vllm.config import VllmConfig
from vllm.logger import init_logger
from vllm.model_executor.layers.activation import _ACTIVATION_REGISTRY
from vllm.model_executor.layers.linear import ReplicatedLinear
from vllm.model_executor.models.interfaces import (
MultiModalEmbeddings,
SupportsMultiModal,
SupportsPP,
)
from vllm.model_executor.models.qwen2_5_omni_thinker import (
Qwen2_5OmniThinkerDummyInputsBuilder,
)
from vllm.model_executor.models.qwen3_moe import Qwen3MoeMLP
from vllm.model_executor.models.utils import (
AutoWeightsLoader,
WeightsMapper,
maybe_prefix,
sequence_parallel_chunk,
)
from vllm.multimodal import MULTIMODAL_REGISTRY
from vllm.sequence import IntermediateTensors
from vllm.v1.sample.metadata import SamplingMetadata
from vllm_omni.model_executor.models.qwen3_omni.qwen3_omni_moe_code_predictor_mtp import (
Qwen3OmniMoeTalkerCodePredictor,
)
from vllm_omni.model_executor.models.qwen3_omni.qwen3_omni_moe_thinker import (
Qwen3MoeLLMForCausalLM,
Qwen3Omni_VisionTransformer,
Qwen3OmniMoeConditionalGenerationMixin,
Qwen3OmniMoeThinkerMultiModalProcessor,
Qwen3OmniMoeThinkerProcessingInfo,
)
try:
import flash_attn
except (ImportError, ModuleNotFoundError):
flash_attn = None
from vllm_omni.model_executor.models.utils import safe_tensor_reshape
logger = init_logger(__name__)
Qwen3OmniMoeThinkerDummyInputsBuilder = Qwen2_5OmniThinkerDummyInputsBuilder
@MULTIMODAL_REGISTRY.register_processor(
Qwen3OmniMoeThinkerMultiModalProcessor,
info=Qwen3OmniMoeThinkerProcessingInfo,
dummy_inputs=Qwen3OmniMoeThinkerDummyInputsBuilder,
)
class Qwen3OmniMoeTalkerForConditionalGeneration(
nn.Module,
SupportsMultiModal,
SupportsPP,
Qwen3OmniMoeConditionalGenerationMixin,
):
"""
Qwen3 Omni MoE Talker - Converts text to audio codec codes.
The talker is the second stage of Qwen3 Omni MoE's TTS pipeline:
1. Thinker: Generates text response + hidden states
2. Talker: Converts those to 8-layer audio codec codes
3. Code2Wav: Converts codes to waveform
## Key Components:
- text_projection: Projects thinker text embeddings → talker dimension
- hidden_projection: Projects thinker hidden states → talker dimension
- language_model: Main MoE transformer (generates layer 0)
- codec_head: Projects to codec vocabulary (layer 0 logits)
- code_predictor: Small transformer for layers 1-num_layers-1
"""
logger = init_logger(__name__)
# Weight mapping from HuggingFace to vLLM naming convention
hf_to_vllm_mapper = WeightsMapper(
orig_to_new_prefix={
# Main MoE transformer model
"talker.model.": "language_model.model.",
# Codec head remains separate (outputs audio codes, not text)
"talker.codec_head.": "codec_head.",
# Code predictor: Now matches HF structure exactly (has .model sub-module)
# e.g., "talker.code_predictor.model.codec_embedding.0" → "code_predictor.model.codec_embedding.0"
"talker.code_predictor.": "code_predictor.",
# Projection layers
"talker.text_projection.": "text_projection.",
"talker.hidden_projection.": "hidden_projection.",
# Fallback: strip talker prefix
"talker.": "",
}
)
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
super().__init__()
talker_config: Qwen3OmniMoeTalkerConfig = vllm_config.model_config.hf_config
self.quant_config = vllm_config.quant_config
self.prefix = prefix
self.config = talker_config
self.vocab_size = talker_config.text_config.vocab_size
self.router_aux_loss_coef = talker_config.text_config.router_aux_loss_coef
self.num_experts = talker_config.text_config.num_experts
self.num_experts_per_tok = talker_config.text_config.num_experts_per_tok
# thinker projection components for talker
self.text_projection = Qwen3OmniMoeTalkerResizeMLP(self.config)
self.hidden_projection = Qwen3OmniMoeTalkerResizeMLP(self.config)
self.codec_head = nn.Linear(self.config.text_config.hidden_size, self.config.text_config.vocab_size, bias=False)
self.rope_deltas = None
self.spatial_merge_size = self.config.spatial_merge_size
self.vocab_size = self.config.code_predictor_config.vocab_size
self.num_code_groups = self.config.code_predictor_config.num_code_groups
self.language_model = Qwen3OmniMoeModel(
vllm_config=vllm_config,
talker_config=self.config,
prefix=maybe_prefix(prefix, "language_model"),
)
self.code_predictor = Qwen3OmniMoeTalkerCodePredictor(
vllm_config=vllm_config, prefix=maybe_prefix(prefix, "code_predictor")
)
def code_predictor_forward(
self,
input_ids: torch.Tensor,
inputs_embeds: torch.Tensor | None = None,
*,
temperature: float = 1.0,
top_k: int = 50, # Match transformers default
top_p: float = 0.8, # Match transformers default
generation_steps: int | None = None,
last_talker_hidden: torch.Tensor | None = None,
**_: object,
) -> tuple[torch.Tensor, torch.Tensor]:
"""
Generate full RVQ codec codes for the provided sequence.
The code predictor consumes the layer-0 codec codes produced by the talker
alongside the talker's hidden states, and autoregressively predicts the remaining
residual layers (to num_codec_groups).
Returns:
tuple containing:
- residual_codes: A tensor of shape [batch, num_code_groups, seq_len] containing
the complete set of codec codes
- summed_embeddings: A tensor of shape [batch, seq_len, hidden_size]
Sum of all layer embeddings at each position (like Transformers)
"""
if input_ids is None:
raise ValueError("`input_ids` containing layer-0 codec codes must be provided.")
if inputs_embeds is None:
raise ValueError("`inputs_embeds` containing talker hidden states must be provided.")
if inputs_embeds.ndim == 2:
inputs_embeds = inputs_embeds.unsqueeze(0)
if input_ids.ndim == 1:
input_ids = input_ids.unsqueeze(0)
# Ensure the tensors are contiguous for the autoregressive sampling loop
inputs_embeds = inputs_embeds.contiguous()
input_ids = input_ids.contiguous()
# Generate full codec codes using MTP
# This will be the parallel prediction implementation
batch_size, seq_len = input_ids.shape
# For now, use sequential generation (TODO: implement parallel)
# Result will be [batch, num_code_groups, seq_len]
# - all_codes_per_position will collect [batch, num_code_groups, 1] for each position
all_codes_per_position = []
middle_hidden_states = [] # Collect hidden states for each position
# Generate residual layers for each position
for pos in range(seq_len):
layer0_code = input_ids[:, pos : pos + 1] # [batch, 1]
# Predict all residual layers (layers 1 to num_code_groups-1) autoregressively
pos_codes = [layer0_code] # Start with layer 0: [batch, 1]
# Initial input: [last_talker_hidden, layer0_embed]
layer0_embed = self.get_input_embeddings(layer0_code)
prev_embed = layer0_embed # Track previous layer embedding
try:
current_input = torch.cat([last_talker_hidden, prev_embed], dim=1) # [batch, 2, hidden_size]
except Exception as e:
print(f"Error in current_input: {e}")
print(f"last_talker_hidden shape: {last_talker_hidden.shape}")
print(f"prev_embed shape: {prev_embed.shape}")
raise e
for layer_idx in range(self.num_code_groups - 1):
# Input for this layer: [last_talker_hidden, prev_layer_embed]
# Forward through code_predictor model
outputs = self.code_predictor.model(
inputs_embeds=current_input,
attention_mask=None,
position_ids=None,
past_key_values=None,
use_cache=False,
cache_position=None,
)
hidden_state = outputs.last_hidden_state # [batch, 2, hidden_size]
# Use the corresponding lm_head for this layer
logits = self.code_predictor.lm_head[layer_idx](hidden_state[:, -1:, :]) # [batch, 1, vocab_size]
from transformers.generation.logits_process import (
LogitsProcessorList,
TopKLogitsWarper,
TopPLogitsWarper,
)
logits_processors = LogitsProcessorList(
[
TopKLogitsWarper(top_k=top_k),
TopPLogitsWarper(top_p=top_p),
]
)
input_ids_for_logits_processors = torch.tensor([pos_codes[1:]]).to(logits.device, dtype=torch.long)
logits = logits_processors(input_ids_for_logits_processors, logits.squeeze(0)).unsqueeze(0)
# Sample from the filtered distribution
probs = F.softmax(logits, dim=-1)
code = torch.multinomial(probs.squeeze(1), num_samples=1) # [batch, 1]
pos_codes.append(code)
# Update prev_embed for next layer (if not last layer)
# layer_idx=0 predicts layer 1, embed with codec_embedding[1]
new_embed = self.code_predictor.model.codec_embedding[layer_idx](code) # [batch, 1, hidden_size]
current_input = torch.cat([current_input, new_embed], dim=1) # [batch, 3~n, hidden_size]
# Stack all layers for this position: [batch, num_code_groups, 1]
pos_all_layers = torch.stack(pos_codes, dim=1) # [batch, num_code_groups, 1]
all_codes_per_position.append(pos_all_layers)
middle_hidden_states.append(current_input[:, 2:-1, :])
# Concatenate across positions: [batch, num_code_groups, seq_len]
result_codes = torch.cat(all_codes_per_position, dim=2)
# Build summed embeddings for each position (like Transformers)
# This combines layer-0 embed, mid layers hidden states, and last layer embed
all_summed_embeddings = []
for pos in range(seq_len):
# Layer 0 embedding
layer0_code = result_codes[:, 0, pos : pos + 1] # [batch, 1]
layer0_embed = self.get_input_embeddings(layer0_code) # [batch, 1, hidden_size]
# mid layers hidden states (from CodePredictor)
mid_residual_hiddens = middle_hidden_states[pos] # [batch, num_code_groups-2, hidden_size]
mid_list = list(mid_residual_hiddens.split(1, dim=1))
# last layer embedding
last_layer_code = result_codes[:, -1, pos : pos + 1] # [batch, 1]
last_residual_hidden = self.code_predictor.model.codec_embedding[-1](last_layer_code)
# Concatenate all layers: [batch, num_code_groups, hidden_size]
pos_codec_hiddens = torch.cat(
[layer0_embed] + mid_list + [last_residual_hidden],
dim=1,
)
# Sum across layers: [batch, 1, hidden_size] (like Transformers)
pos_summed = pos_codec_hiddens.sum(dim=1, keepdim=True)
all_summed_embeddings.append(pos_summed)
# Concatenate across positions: [batch, seq_len, hidden_size]
summed_embeddings = torch.cat(all_summed_embeddings, dim=1)
return result_codes, summed_embeddings
def init_multi_modal(self, thinker_config):
"""
Initialize multimodal components from the thinker.
Unlike Qwen2.5 Omni which creates audio_tower and visual encoders here,
Qwen3 Omni MoE has a cleaner separation: the thinker is the ONLY module
that processes raw multimodal inputs. The talker only handles text-to-audio
conversion using pre-processed embeddings from the thinker.
This method exists for API compatibility and stores the thinker config
for reference. The actual multimodal processing components (audio_tower,
visual) are ONLY in the thinker, not duplicated in the talker.
Args:
thinker_config: Configuration from the thinker model (for reference only)
"""
self.audio_tower = Qwen3OmniMoeAudioEncoder(thinker_config.audio_config)
self.visual = Qwen3Omni_VisionTransformer(
vision_config=thinker_config.vision_config,
norm_eps=getattr(thinker_config.text_config, "rms_norm_eps", 1e-6),
quant_config=self.quant_config,
prefix=maybe_prefix(self.prefix, "visual"),
# attn_backend_override=attn_backend_override,
)
def project_thinker_outputs(
self,
thinker_embeds: torch.Tensor | None = None,
thinker_hidden_states: torch.Tensor | None = None,
is_multimodal_mask: torch.Tensor | None = None,
) -> torch.Tensor:
"""
Project thinker outputs to talker's hidden dimension.
The talker has a different hidden size than the thinker, so we need
to project the inputs appropriately:
- Text embeddings (from thinker's embedding layer) → text_projection
- Hidden states (from thinker's last layer, for multimodal) → hidden_projection
Args:
thinker_embeds: Text embeddings from thinker [batch, seq, thinker_hidden]
thinker_hidden_states: Hidden states from thinker's last layer [batch, seq, thinker_hidden]
is_multimodal_mask: Boolean mask indicating multimodal positions [batch, seq]
Returns:
projected_embeds: [batch, seq, talker_hidden]
"""
if thinker_embeds is None and thinker_hidden_states is None:
raise ValueError("Either thinker_embeds or thinker_hidden_states must be provided")
# If only embeddings provided, project all as text
if thinker_hidden_states is None or is_multimodal_mask is None:
return self.text_projection(thinker_embeds)
# If only hidden states provided, project all as hidden
if thinker_embeds is None:
return self.hidden_projection(thinker_hidden_states)
# Mixed case: use mask to decide which projection
batch_size, seq_len, _ = thinker_embeds.shape
output = torch.empty(
(batch_size, seq_len, self.config.text_config.hidden_size),
device=thinker_embeds.device,
dtype=thinker_embeds.dtype,
)
# Project multimodal regions using hidden states
if is_multimodal_mask.any():
mm_hidden = thinker_hidden_states[is_multimodal_mask]
projected_mm = self.hidden_projection(mm_hidden)
output[is_multimodal_mask] = projected_mm
# Project text regions using embeddings
if (~is_multimodal_mask).any():
text_embeds = thinker_embeds[~is_multimodal_mask]
projected_text = self.text_projection(text_embeds)
output[~is_multimodal_mask] = projected_text
return output
def forward(
self,
batched_talker_inputs: dict,
intermediate_tensors: IntermediateTensors | None = None,
**kwargs: object,
) -> torch.Tensor | IntermediateTensors:
"""Forward pass through the talker model.
For inference, the talker receives inputs_embeds that should already be
projected to talker's hidden dimension. If receiving raw thinker outputs,
use project_thinker_outputs() first.
"""
# If intermediate_tensors is provided (pipeline parallel),
# inputs_embeds should be None
batched_input_ids = []
batched_positions = []
batched_input_embeds = []
batched_code_predictor_codes = []
if intermediate_tensors is not None:
inputs_embeds = None
for rid in batched_talker_inputs:
input_ids = safe_tensor_reshape(batched_talker_inputs[rid]["input_ids"], (1, -1))
positions = batched_talker_inputs[rid]["positions"]
inputs_embeds = safe_tensor_reshape(
batched_talker_inputs[rid]["inputs_embeds"], (-1, self.config.text_config.hidden_size)
)
text_step = safe_tensor_reshape(batched_talker_inputs[rid]["text_step"], (1, -1))
last_talker_hidden = safe_tensor_reshape(
batched_talker_inputs[rid]["last_talker_hidden"], (1, 1, self.config.text_config.hidden_size)
)
# for profiling
if inputs_embeds.shape[-1] == 2048:
inputs_embeds = self.text_projection(inputs_embeds)
if inputs_embeds.shape[0] == 1:
code_predictor_codes, summed_embeddings = self.code_predictor_forward(
input_ids, inputs_embeds.clone(), last_talker_hidden=last_talker_hidden
)
inputs_embeds = summed_embeddings.clone()
else:
code_predictor_codes = torch.zeros((0, self.num_code_groups), dtype=torch.long)
batched_input_ids.append(input_ids.reshape(-1))
batched_positions.append(positions)
batched_input_embeds.append((inputs_embeds + text_step).reshape(-1, self.config.text_config.hidden_size))
batched_code_predictor_codes.append(code_predictor_codes.squeeze(-1).detach().to("cpu").contiguous())
try:
talker_input_ids = torch.cat(batched_input_ids, dim=0)
talker_positions = torch.cat(batched_positions, dim=0)
talker_input_embeds = torch.cat(batched_input_embeds, dim=0)
except Exception as e:
print(f"Error in talker_input_embeds: {e}")
print(f"talker_input_embeds shape: {[tensor.shape for tensor in batched_input_embeds]}")
print(f"talker_input_ids shape: {[tensor.shape for tensor in batched_input_ids]}")
print(f"talker_positions shape: {[tensor.shape for tensor in batched_positions]}")
raise e
talker_hidden_states, _ = self.language_model.model(
talker_input_ids,
talker_positions,
intermediate_tensors,
inputs_embeds=talker_input_embeds,
**kwargs,
)
# Pass talker hidden states to code predictor
# Returns: (residual_codes, summed_embeddings=sum of all layer embeddings at each position)
# Return both talker hidden states and code predictor results
# code_predictor_codes: [batch, num_code_groups, seq_len]
# summed_embeddings: [batch, seq_len, hidden_size]
# - Sum of all layer embeddings at each position (like Transformers)
return talker_hidden_states, batched_code_predictor_codes
def compute_logits(
self,
hidden_states: torch.Tensor,
sampling_metadata: SamplingMetadata = None,
) -> torch.Tensor | None:
"""Compute logits for audio codec codes (layer 0 of RVQ).
This projects the hidden states to the codec vocabulary space.
For full audio generation, layers except 0 would be predicted by
the code_predictor after sampling.
"""
logits = self.codec_head(hidden_states)
return logits
def make_empty_intermediate_tensors(
self, batch_size: int, dtype: torch.dtype, device: torch.device
) -> IntermediateTensors:
"""Create empty intermediate tensors for pipeline parallelism."""
return self.language_model.make_empty_intermediate_tensors(batch_size, dtype, device)
def _parse_and_validate_multimodal_inputs(self, **kwargs: object) -> dict:
mm_input_by_modality = {}
# Preserve the order of modalities if there are multiple of them
# from the order of kwargs.
for input_key in kwargs:
if input_key in ("pixel_values", "image_embeds") and "image" not in mm_input_by_modality:
mm_input_by_modality["image"] = self._parse_and_validate_image_input(**kwargs)
if input_key in ("pixel_values_videos", "video_embeds") and "video" not in mm_input_by_modality:
mm_input_by_modality["video"] = self._parse_and_validate_video_input(**kwargs)
if input_key in ("input_audio_features") and "audio" not in mm_input_by_modality:
mm_input_by_modality["audio"] = self._parse_and_validate_audio_input(**kwargs)
return mm_input_by_modality
def get_multimodal_embeddings(self, **kwargs: object) -> MultiModalEmbeddings | None:
mm_input_by_modality = self._parse_and_validate_multimodal_inputs(**kwargs)
if not mm_input_by_modality:
return []
# The result multimodal_embeddings is tuple of tensors, with each
# tensor correspoending to a multimodal data item (image or video).
multimodal_embeddings: tuple[torch.Tensor, ...] = ()
# NOTE: It is important to iterate over the keys in this dictionary
# to preserve the order of the modalities.
# TODO: do projection for all multimodel
for modality in mm_input_by_modality:
multimodal_input = mm_input_by_modality[modality]
if modality == "image":
image_embeddings = self._process_image_input(multimodal_input)
image_embeddings = self.hidden_projection(image_embeddings)
multimodal_embeddings += tuple(image_embeddings)
if modality == "video":
video_embeddings = self._process_video_input(multimodal_input)
video_video_embeddings_project = ()
for video_embed in video_embeddings:
proj = nn.Linear(8192, 2048).to(device=video_embed.device, dtype=torch.bfloat16)
video_embed = proj(video_embed)
video_embed_project = self.hidden_projection(video_embed)
video_video_embeddings_project += (video_embed_project,)
multimodal_embeddings += tuple(video_video_embeddings_project)
if modality == "audio":
audio_embeddings = self._process_audio_input(multimodal_input)
audio_embeddings = self.hidden_projection(audio_embeddings)
multimodal_embeddings += tuple(audio_embeddings)
return multimodal_embeddings
def get_input_embeddings(self, input_ids: torch.Tensor, multimodal_embeddings: MultiModalEmbeddings | None = None):
"""Get the input embedding layer (for codec tokens)."""
return self.language_model.get_input_embeddings(input_ids, multimodal_embeddings)
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
"""Load weights for the talker model.
The weight mapping translates from HuggingFace naming convention
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."],
)
# Don't apply mapper again since we already did it
loaded = loader.load_weights(weights, mapper=self.hf_to_vllm_mapper)
# Log load summary
try:
total_bytes = 0
for name, param in self.named_parameters():
if param is not None and param.data is not None:
total_bytes += param.data.numel() * param.data.element_size()
device = next(self.parameters()).device
logger.info(
"[Model Loaded] name=%s, success=%s, size=%.2f MB, device=%s",
self.__class__.__name__,
True,
total_bytes / (1024**2),
str(device),
)
except Exception:
pass
multi_model_weights = set()
for name, param in self.visual.named_parameters():
multi_model_weights.add("visual." + name)
for name, param in self.audio_tower.named_parameters():
multi_model_weights.add("audio_tower." + name)
loaded.update(multi_model_weights)
return loaded
class Qwen3OmniMoeTalkerResizeMLP(nn.Module):
"""
MLP for projecting between thinker and talker hidden dimensions.
The thinker and talker have different hidden sizes:
- Thinker: config.thinker_hidden_size (e.g., 3584)
- Talker: config.text_config.hidden_size (e.g., 2048)
This MLP projects from thinker → talker dimension.
Two instances are used:
- text_projection: For text embeddings from thinker's embedding layer
- hidden_projection: For hidden states from thinker's last transformer layer
"""
def __init__(self, config: Qwen3OmniMoeTalkerConfig):
super().__init__()
self.linear_fc1 = nn.Linear(config.thinker_hidden_size, config.text_config.intermediate_size, bias=True)
self.linear_fc2 = nn.Linear(config.text_config.intermediate_size, config.text_config.hidden_size, bias=True)
self.act_fn = _ACTIVATION_REGISTRY[config.text_config.hidden_act] # silu
def forward(self, hidden_state):
return self.linear_fc2(self.act_fn(self.linear_fc1(hidden_state)))
class Qwen3OmniMoeModel(Qwen3MoeLLMForCausalLM):
def __init__(self, vllm_config, talker_config, prefix):
talker_vllm_config = vllm_config.with_hf_config(
talker_config.text_config, architectures=["Qwen3MoeForCausalLM"]
)
talker_vllm_config.model_config.hf_text_config = talker_vllm_config.model_config.hf_config
super().__init__(
vllm_config=talker_vllm_config,
prefix=prefix,
)
self.config = talker_config
# Remove the inherited LM head so the talker only exposes codec outputs.
if hasattr(self, "lm_head"):
del self.lm_head
# Replace the base embed tokens with codec embedding (defined below).
if hasattr(self.model, "embed_tokens"):
del self.model.embed_tokens
# Codec embedding for RVQ code generation
self.model.codec_embedding = nn.Embedding(
talker_config.text_config.vocab_size, talker_config.text_config.hidden_size
)
# Add shared expert to each MoE layer and patch the forward method
layer_idx = 0
for layer in self.model.layers:
# add shared expert to Qwen3OmniMoeSparseMoeBlock layers
if hasattr(layer.mlp, "experts"): # Check if it's a SparseMoeBlock
# Shared expert is a regular gated MLP (SwiGLU)
layer.mlp.shared_expert = Qwen3MoeMLP(
hidden_size=self.config.text_config.hidden_size,
intermediate_size=self.config.text_config.shared_expert_intermediate_size,
hidden_act=self.config.text_config.hidden_act,
quant_config=talker_vllm_config.quant_config,
reduce_results=False, # Don't reduce since we'll add it manually
prefix=f"{prefix}.layers.{layer_idx}.mlp.shared_expert",
)
# Shared expert gate outputs a single scalar per token
layer.mlp.shared_expert_gate = ReplicatedLinear(
self.config.text_config.hidden_size,
1, # Output single scalar per token
bias=False,
quant_config=None,
prefix=f"{prefix}.layers.{layer_idx}.mlp.shared_expert_gate",
)
# Store MoE config values for router computation
layer.mlp.top_k = self.config.text_config.num_experts_per_tok
layer.mlp.norm_topk_prob = self.config.text_config.norm_topk_prob
layer.mlp.num_experts = self.config.text_config.num_experts
# Monkey-patch the forward method to use shared expert
layer.mlp.forward = self._create_moe_forward_with_shared_expert(layer.mlp)
layer_idx += 1
def _create_moe_forward_with_shared_expert(self, moe_layer):
"""Create a forward method that includes shared expert computation.
This matches the Transformers implementation where:
1. Compute shared expert output (regular MLP)
2. Gate it with sigmoid(shared_expert_gate(x))
3. Apply softmax BEFORE top-k selection (matches Transformers router)
4. Add to routed expert outputs
"""
def forward_with_shared_expert(hidden_states: torch.Tensor, layer_idx: int = 0) -> torch.Tensor:
# Save original shape
orig_shape = hidden_states.shape
hidden_dim = hidden_states.shape[-1]
hidden_states = hidden_states.view(-1, hidden_dim)
# handle sequence parallel if needed
if hasattr(moe_layer, "is_sequence_parallel") and moe_layer.is_sequence_parallel:
hidden_states = sequence_parallel_chunk(hidden_states)
# Compute shared expert output
# The shared expert is a regular MLP, not a routed MoE
shared_output = None
if hasattr(moe_layer, "shared_expert") and moe_layer.shared_expert is not None:
# Forward through shared expert MLP
shared_output = moe_layer.shared_expert(hidden_states)
# Apply gating with sigmoid: sigmoid(gate(x)) * shared_expert(x)
if hasattr(moe_layer, "shared_expert_gate") and moe_layer.shared_expert_gate is not None:
gate_logits, _ = moe_layer.shared_expert_gate(hidden_states)
gate_values = F.sigmoid(gate_logits) # [batch, 1]
shared_output = gate_values * shared_output # Broadcasting: [batch, 1] * [batch, hidden]
# Compute experts results
# router_logits: (num_tokens, n_experts)
router_logits, _ = moe_layer.gate(hidden_states)
experts_output = moe_layer.experts(hidden_states=hidden_states, router_logits=router_logits)
# combine experts and shared expert results
if shared_output is not None:
final_hidden_states = experts_output + shared_output
# Handle sequence parallel if needed
if hasattr(moe_layer, "is_sequence_parallel") and moe_layer.is_sequence_parallel:
from vllm.distributed import tensor_model_parallel_all_gather
num_tokens = orig_shape[0] if len(orig_shape) > 1 else 1
final_hidden_states = tensor_model_parallel_all_gather(final_hidden_states, 0)
final_hidden_states = final_hidden_states[:num_tokens]
try:
final_hidden_states.view(orig_shape)
except Exception as e:
print(f"Error viewing final hidden states: {e}")
print(f"final_hidden_states.shape: {final_hidden_states.shape}")
print(f"orig_shape: {orig_shape}")
raise e
# Return with original shape
return final_hidden_states.view(orig_shape)
return forward_with_shared_expert
def get_input_embeddings(
self,
input_ids: torch.Tensor,
multimodal_embeddings: MultiModalEmbeddings | None = None,
generation_steps=None,
) -> torch.Tensor:
return self.model.codec_embedding(input_ids)
File diff suppressed because it is too large. Load diff
@@ -27,6 +27,27 @@ _OMNI_MODELS = {
"Qwen2_5OmniToken2WavModel",
),
"Qwen2ForCausalLM_old": ("qwen2_5_omni", "qwen2_old", "Qwen2ForCausalLM"), # need to discuss
# Qwen3 Omni MoE models
"Qwen3OmniMoeForConditionalGeneration": (
"qwen3_omni",
"qwen3_omni",
"Qwen3OmniMoeForConditionalGeneration",
),
"Qwen3OmniMoeThinkerForConditionalGeneration": (
"qwen3_omni",
"qwen3_omni_moe_thinker",
"Qwen3OmniMoeThinkerForConditionalGeneration",
),
"Qwen3OmniMoeTalkerForConditionalGeneration": (
"qwen3_omni",
"qwen3_omni_moe_talker",
"Qwen3OmniMoeTalkerForConditionalGeneration",
),
"Qwen3OmniMoeCode2Wav": (
"qwen3_omni",
"qwen3_omni_code2wav",
"Qwen3OmniMoeCode2Wav",
),
}
_VLLM_OMNI_MODELS = {
+9
View File
@@ -28,3 +28,12 @@ def split_list_into_ranges(lst: torch.Tensor, interval: int) -> list[list[int]]:
ranges[index].append(num)
return ranges
def safe_tensor_reshape(tensor: torch.Tensor, shape: tuple) -> torch.Tensor:
"""
Reshape a tensor safely.
"""
if tensor is None:
return None
return tensor.reshape(shape)