[Rebase] Rebase to vllm 0.20.0 (#3232)

Signed-off-by: tzhouam <tzhouam@connect.ust.hk>
Signed-off-by: Zhou Taichang <tzhouam@connect.ust.hk>
Signed-off-by: Yuanheng Zhao <jonathan.zhaoyh@gmail.com>
Co-authored-by: Yuanheng Zhao <54058983+yuanheng-zhao@users.noreply.github.com>
This commit is contained in:
Zhou TaichangandYuanheng Zhao authored and GitHub committed 2026-04-30 09:56:59 +12:00
1 parent dd0fa02547
commit 7f2b1e9386
70 files changed
+1191 -273

No files matched your search

+20 -5
View File
@@ -53,19 +53,34 @@ from vllm_omni.diffusion.models.bagel.pipeline_bagel import default_ae_params
class OmniBagelProcessor(BagelProcessor):
# transformers>=5.0 ProcessorMixin.get_attributes() only scans the leaf
# class's __dict__ for ``<attribute>_class`` hints; redeclare them here
# so from_pretrained() correctly sets ``self.image_processor`` and
# ``self.tokenizer`` on the OmniBagelProcessor instance.
image_processor_class = "SiglipImageProcessor"
tokenizer_class = "AutoTokenizer"
def __call__(self, text=None, images=None, **kwargs):
is_img2img = kwargs.pop("is_img2img", False)
if is_img2img and images is not None:
image_kwargs = kwargs.copy()
# transformers>=5.0 enforces strict kwarg typing on image
# processors, so split generic kwargs into text/image buckets
# via the standard ProcessorMixin helper before dispatch.
from vllm.transformers_utils.processors.bagel import BagelProcessorKwargs
output_kwargs = self._merge_kwargs(
BagelProcessorKwargs,
tokenizer_init_kwargs=self.tokenizer.init_kwargs,
**kwargs,
)
image_kwargs = dict(output_kwargs["images_kwargs"])
image_kwargs["do_resize"] = False
image_kwargs["do_rescale"] = True
if "return_tensors" not in image_kwargs:
image_kwargs["return_tensors"] = "pt"
image_kwargs.setdefault("return_tensors", "pt")
pixel_values = self.image_processor(images, **image_kwargs)
text_inputs = self.tokenizer(text, **kwargs) if text is not None else None
text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"]) if text is not None else None
if pixel_values is not None and text_inputs is not None:
combined = dict(text_inputs)
@@ -30,6 +30,41 @@ def _get_hf_token() -> str | None:
return os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACE_HUB_TOKEN")
def _ensure_transformers_tied_weights_compat() -> None:
"""Provide the transformers>=5 tied-weight attr expected during loading.
The DYNIN audio detokenizer uses Hugging Face remote code that still only
defines the older ``_tied_weights_keys`` attribute. transformers 5.x now
reads ``all_tied_weights_keys`` inside ``from_pretrained`` before the model
instance is returned, so patching the loaded object is too late.
"""
try:
from transformers import PreTrainedModel
except Exception:
return
if hasattr(PreTrainedModel, "all_tied_weights_keys"):
return
def all_tied_weights_keys(self: Any) -> dict[str, Any]:
keys: dict[str, Any] = {}
for attr_name in ("_tied_weights_keys", "_dynamic_tied_weights_keys"):
raw_keys = getattr(self, attr_name, None)
if raw_keys is None:
continue
if isinstance(raw_keys, dict):
keys.update({str(k): v for k, v in raw_keys.items()})
continue
if isinstance(raw_keys, str):
keys[raw_keys] = None
continue
for key in raw_keys:
keys[str(key)] = None
return keys
PreTrainedModel.all_tied_weights_keys = property(all_tied_weights_keys) # type: ignore[attr-defined]
def _ensure_remote_s2u_vendor_root(
*,
repo_id: str,
@@ -232,6 +267,7 @@ class DyninOmniToken2Audio(DyninOmniStageBase):
"transformers is required to load EMOVASpeechTokenizer remote code from Hugging Face."
) from e
_ensure_transformers_tied_weights_compat()
try:
self._vq_audio = AutoModel.from_pretrained(
model_path,
@@ -209,6 +209,66 @@ class DyninOmniToken2Text(DyninOmniStageBase):
def _load_text_model(model_path: str, *, local_files_only: bool = False) -> Any:
try:
dynin_model_cls = get_dynin_modeling_attr("DyninOmniModelLM")
# Remote Dynin `DyninOmniConfig` may omit `use_cache`, but bundled
# `modeling_llada.forward` reads `self.config.use_cache` like a
# standard HF causal LM config (see kernel warmup / mmu_generate).
dynin_config_cls = get_dynin_modeling_attr("DyninOmniConfig")
if not getattr(dynin_config_cls, "_dynin_use_cache_shim_applied", False):
_orig_cfg_init = dynin_config_cls.__init__
def _cfg_init_shim(self, *args, **kwargs):
_orig_cfg_init(self, *args, **kwargs)
if not hasattr(self, "use_cache"):
setattr(self, "use_cache", True)
dynin_config_cls.__init__ = _cfg_init_shim # type: ignore[method-assign]
dynin_config_cls._dynin_use_cache_shim_applied = True
# transformers>=5.0 renamed the weight-tying manifest accessor from
# `_tied_weights_keys` (a class attribute) to `all_tied_weights_keys`
# (a property returning a {module_path: [tied_keys]} mapping) and
# invokes it during `from_pretrained -> caching_allocator_warmup
# -> get_total_byte_count`. Remote Dynin code pre-dates the rename,
# so patch a minimal shim onto the class if it's missing. Keeping
# the mapping empty is safe here — the root module has no weight
# tying; the real tied-weights (if any) live on nested submodules
# that transformers discovers via their own `_tied_weights_keys`.
if not hasattr(dynin_model_cls, "all_tied_weights_keys"):
dynin_model_cls.all_tied_weights_keys = property(lambda self: {})
# transformers>=5.0 also calls `get_total_byte_count` which does
# `len(model._tp_plan)`; PreTrainedModel's class default for
# `_tp_plan` is `None`, and unless `self.config.base_model_tp_plan`
# was populated during __init__ (via `post_init`) the instance
# attribute remains None, crashing with
# `TypeError: object of type 'NoneType' has no len()`. The remote
# Dynin model class bypasses that path, so shim an empty dict at
# the class level as a safe fallback (PreTrainedModel sets the
# instance attribute when the config actually carries a plan).
if getattr(dynin_model_cls, "_tp_plan", None) is None:
dynin_model_cls._tp_plan = {}
# transformers>=5.0 `_finalize_model_loading` calls
# `model.tie_weights(missing_keys=..., recompute_mapping=...)` while
# the remote Dynin code still defines `tie_weights(self)` with no
# keyword arguments, raising
# `TypeError: LLaDAModelLM.tie_weights() got an unexpected keyword
# argument 'missing_keys'`. Wrap the method once to silently drop
# the new kwargs; the remote implementation is a no-op w.r.t. the
# missing-keys bookkeeping transformers would otherwise perform.
_orig_tie_weights = dynin_model_cls.tie_weights
if not getattr(_orig_tie_weights, "_dynin_accepts_v5_kwargs", False):
_tie_sig = inspect.signature(_orig_tie_weights)
_tie_accepts_var_kw = any(p.kind is inspect.Parameter.VAR_KEYWORD for p in _tie_sig.parameters.values())
_tie_accepts_new_kwargs = _tie_accepts_var_kw or (
"missing_keys" in _tie_sig.parameters and "recompute_mapping" in _tie_sig.parameters
)
if not _tie_accepts_new_kwargs:
def _tie_weights_shim(self, *args, **kwargs):
kwargs.pop("missing_keys", None)
kwargs.pop("recompute_mapping", None)
return _orig_tie_weights(self, *args, **kwargs)
_tie_weights_shim._dynin_accepts_v5_kwargs = True # type: ignore[attr-defined]
dynin_model_cls.tie_weights = _tie_weights_shim
try:
return dynin_model_cls.from_pretrained(
model_path,
@@ -22,7 +22,7 @@ from vllm.config.multimodal import BaseDummyOptions
from vllm.distributed import get_pp_group
from vllm.inputs import MultiModalDataDict
from vllm.logger import init_logger
from vllm.model_executor.layers.fused_moe import SharedFusedMoE
from vllm.model_executor.layers.fused_moe import fused_moe_make_expert_params_mapping
from vllm.model_executor.layers.linear import (
ColumnParallelLinear,
RowParallelLinear,
@@ -113,8 +113,8 @@ class HunyuanModel(HunYuanModel):
if _is_moe(self.config):
# Params for weights, fp8 weight scales, fp8 activation scales
# (param_name, weight_name, expert_id, shard_id)
fused_moe_expert_mapping = SharedFusedMoE.make_expert_params_mapping(
model=self,
fused_moe_expert_mapping = fused_moe_make_expert_params_mapping(
self,
ckpt_gate_proj_name="gate_proj",
ckpt_down_proj_name="down_proj",
ckpt_up_proj_name="up_proj",
@@ -519,13 +519,18 @@ class MiMoAudioLLMForConditionalGeneration(nn.Module, SupportsMultiModal, Suppor
vllm_config.model_config.hf_config = self.config
# Configure MRoPE parameters for multimodal rotary embeddings
# Configure MRoPE parameters for multimodal rotary embeddings.
# NOTE: In transformers >=5.x, `rope_scaling` is a property alias whose setter *replaces*
# `rope_parameters` wholesale. If we assign `rope_scaling = mrope_config` first, any
# pre-existing `rope_theta` key inside `rope_parameters` (standardized from the checkpoint's
# top-level `rope_theta`) is silently dropped, which breaks `Qwen2RotaryEmbedding`'s
# `compute_default_rope_parameters` (it reads `config.rope_parameters["rope_theta"]`).
# Update `rope_parameters` in-place instead so the standardized `rope_theta` is preserved.
mrope_config = {
"mrope_section": [16, 24, 24],
"rope_type": "default",
"type": "default",
}
setattr(vllm_config.model_config.hf_config, "rope_scaling", mrope_config)
vllm_config.model_config.hf_config.rope_parameters.update(mrope_config)
self.model = init_vllm_registered_model(
@@ -293,16 +293,55 @@ class ISTFTHead(nn.Module):
class RotaryEmbedding(nn.Module):
inv_freq: torch.Tensor
def __init__(self, base, dim, max_seq_len, rope_type="default", device=None):
super().__init__()
self.max_seq_len = max_seq_len
self.rope_type = rope_type
# Cache base/dim so we can reconstruct `inv_freq` from scratch during transformers >=5.x's
# `PreTrainedModel._init_weights` reinit path (which calls
# `module.compute_default_rope_parameters(module.config)` and then `init.copy_` the result
# into `inv_freq` / `original_inv_freq`). Our class does not carry an HF config, so we
# ignore it and rely on these cached values.
self._rope_base = base
self._rope_dim = dim
# transformers 5.x `_init_weights` reads `module.config` for modules whose class name
# contains "RotaryEmbedding" (see `PreTrainedModel._init_weights`). Provide a placeholder
# so that attribute access works; the value is unused by our
# `compute_default_rope_parameters` below.
self.config = None
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
inv_freq, self.attention_scaling = self.rope_init_fn(device=device, base=base, dim=dim)
self.register_buffer("inv_freq", inv_freq, persistent=False)
self.original_inv_freq = self.inv_freq
# Register `original_inv_freq` as a proper buffer (rather than a plain attribute alias of
# `self.inv_freq`). In transformers >=5.x `from_pretrained` builds the model on a meta
# device, then `_move_missing_keys_from_meta_to_device` iterates `named_buffers()` and
# replaces each non-persistent buffer with an `empty_like` on the real device. A plain
# attribute alias is invisible to `named_buffers()`, so it would be left pointing at the
# stale meta tensor and `init.copy_(module.original_inv_freq, ...)` inside `_init_weights`
# would then fail / operate on a wrong-device tensor.
self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
def compute_default_rope_parameters(
self,
config=None,
device: "torch.device | None" = None,
seq_len: int | None = None,
) -> tuple[torch.Tensor, float]:
"""Recompute `inv_freq` for transformers >=5.x's `_init_weights` reinit path.
transformers calls this as `module.compute_default_rope_parameters(module.config)` and then
`init.copy_` the returned tensor into `inv_freq` / `original_inv_freq`. Our RotaryEmbedding
does not carry an HF config, so we ignore the `config` arg and reuse the `base`/`dim`
captured at construction time. This is critical: with `transformers>=5.x`, models are
built on meta device and the non-persistent `inv_freq` buffer is replaced by uninitialized
memory during `_move_missing_keys_from_meta_to_device`, so we MUST let `_init_weights`
refill it (hence why we do not set `_is_hf_initialized = True` here).
"""
return self.rope_init_fn(device=device, base=self._rope_base, dim=self._rope_dim)
@torch.no_grad()
@dynamic_rope_update
@@ -820,8 +859,22 @@ class AudioDecoder(nn.Module):
class MiMoAudioTokenizer(PreTrainedModel):
config_class = MiMoAudioTokenizerConfig
@property
def all_tied_weights_keys(self) -> dict[str, list[str]]:
# Transformers `from_pretrained` -> `caching_allocator_warmup` -> `get_total_byte_count`
# accesses this on the root module; some PreTrainedModel versions omit the property for
# custom subclasses. MiMo-Audio tokenizer has no weight tying at the root.
return {}
def __init__(self, config: MiMoAudioTokenizerConfig):
super().__init__(config)
# Transformers `caching_allocator_warmup` / `get_total_byte_count` calls `len(model._tp_plan)`
# on the root module. The base `PreTrainedModel` class default is `None`, and this subclass
# does not invoke `self.post_init()` where `_tp_plan` would otherwise be initialized to `{}`.
# Set it explicitly to avoid `TypeError: object of type 'NoneType' has no len()`.
self._tp_plan = {}
self._pp_plan = {}
self._ep_plan = {}
self.config = config
self.sampling_rate = config.sampling_rate
self.encoder = AudioEncoder(config=config)
@@ -16,8 +16,10 @@ from vllm_omni.config.stage_config import (
StageExecutionType,
StagePipelineConfig,
)
from vllm_omni.model_executor.models.mimo_audio.config_mimo_audio import NO_INTERLEAVE_NEXT_TOKEN_ID
_PROC = "vllm_omni.model_executor.stage_input_processors.mimo_audio"
_IM_END_TOKEN_ID = 151645
MIMO_AUDIO_PIPELINE = PipelineConfig(
model_type="mimo_audio",
@@ -37,7 +39,13 @@ MIMO_AUDIO_PIPELINE = PipelineConfig(
owns_tokenizer=True,
engine_output_type="latent",
async_chunk_process_next_stage_input_func=(f"{_PROC}.llm2code2wav_async_chunk"),
sampling_constraints={"detokenize": True},
sampling_constraints={
"detokenize": True,
# Stop once the speech/text interleaved span ends. Code2Wav
# also treats this token as the audio boundary; without this
# the text stream can continue after audio has already ended.
"stop_token_ids": [NO_INTERLEAVE_NEXT_TOKEN_ID, _IM_END_TOKEN_ID],
},
),
StagePipelineConfig(
stage_id=1,
@@ -32,7 +32,7 @@ from vllm.distributed import get_pp_group, get_tensor_model_parallel_world_size
from vllm.logger import init_logger
from vllm.model_executor.layers.activation import SiluAndMul
from vllm.model_executor.layers.attention import Attention
from vllm.model_executor.layers.fused_moe import FusedMoE, SharedFusedMoE
from vllm.model_executor.layers.fused_moe import FusedMoE
from vllm.model_executor.layers.layernorm import RMSNorm
from vllm.model_executor.layers.linear import (
MergedColumnParallelLinear,
@@ -329,7 +329,7 @@ class BailingMoeV2SparseMoeBlock(nn.Module):
else:
self.shared_experts = None
self.experts = SharedFusedMoE(
self.experts = FusedMoE(
shared_experts=self.shared_experts,
num_experts=config.num_experts,
top_k=config.num_experts_per_tok,
@@ -337,7 +337,6 @@ class BailingMoeV2SparseMoeBlock(nn.Module):
intermediate_size=config.moe_intermediate_size,
custom_routing_function=_unpack_multi_routing,
renormalize=False, # we handle normalization in the gate
reduce_results=True,
quant_config=quant_config,
prefix=f"{prefix}.experts",
)
@@ -417,16 +416,9 @@ class BailingMoeV2SparseMoeBlock(nn.Module):
dim=-1,
)
# SharedFusedMoE expects 2D hidden_states
# FusedMoE expects 2D hidden_states.
hidden_states_2d = hidden_states.view(-1, h)
result = self.experts(hidden_states_2d, packed_routing)
if self.shared_experts is not None:
shared_output, fused_out = result
else:
shared_output, fused_out = None, result
final_hidden_states = fused_out + shared_output if shared_output is not None else fused_out
final_hidden_states = self.experts(hidden_states_2d, packed_routing)
final_hidden_states = final_hidden_states.view(bsz, seq_len, h)
@@ -19,9 +19,9 @@ import torchaudio
from transformers.feature_extraction_utils import BatchFeature
from vllm.config import VllmConfig
from vllm.config.multimodal import BaseDummyOptions
from vllm.inputs.llm import MultiModalDataDict
from vllm.logger import init_logger
from vllm.multimodal.inputs import (
MultiModalDataDict,
MultiModalFieldConfig,
MultiModalKwargsItems,
)
@@ -272,8 +272,6 @@ class Qwen2_5OmniConditionalGenerationMixin(Qwen2_5OmniConditionalGenerationMixi
def _process_video_input(
self,
video_input: Qwen2_5_VLVideoInputs,
video_hashes: list[str] = None,
cached_video_embeds: torch.Tensor = None,
) -> torch.Tensor:
if video_input["type"] == "video_embeds":
return video_input["video_embeds"].type(self.visual.dtype)
@@ -621,11 +619,14 @@ class Qwen2_5OmniThinkerForConditionalGeneration(
# Check for audio-in-video: interleaved video and audio tokens
# in the multimodal region. Only use the interleaved path when
# needed; otherwise fall back to the default parent implementation.
# vLLM's _gather_mm_embeddings builds is_multimodal on CPU for merge
# indexing; bitwise ops with input_ids require the same device.
is_mm_device = is_multimodal.to(device=input_ids.device, non_blocking=True)
video_token_id = self.config.video_token_index
audio_token_id = self.config.audio_token_index
is_video = is_multimodal & (input_ids == video_token_id)
is_audio = is_multimodal & (input_ids == audio_token_id)
is_video = is_mm_device & (input_ids == video_token_id)
is_audio = is_mm_device & (input_ids == audio_token_id)
num_video = is_video.sum().item()
num_audio = is_audio.sum().item()
@@ -641,7 +642,7 @@ class Qwen2_5OmniThinkerForConditionalGeneration(
multimodal_embeddings,
is_video,
is_audio,
is_multimodal,
is_mm_device,
num_video,
num_audio,
)
@@ -25,7 +25,7 @@
from collections.abc import Iterable, Iterator, Mapping, Sequence
from dataclasses import replace
from functools import partial
from typing import Any, Literal, cast
from typing import Any, cast
import numpy as np
import torch
@@ -45,6 +45,7 @@ from transformers.models.qwen3_omni_moe.processing_qwen3_omni_moe import (
from transformers.models.whisper import WhisperFeatureExtractor
from vllm.compilation.decorators import support_torch_compile
from vllm.config import ModelConfig, SpeechToTextConfig, VllmConfig
from vllm.config.speech_to_text import SpeechToTextParams
from vllm.distributed import get_pp_group, get_tensor_model_parallel_world_size
from vllm.inputs import PromptType
from vllm.logger import init_logger
@@ -1046,8 +1047,6 @@ class Qwen3OmniMoeConditionalGenerationMixin(Qwen2_5OmniConditionalGenerationMix
def _process_audio_input(
self,
audio_input: Qwen2_5OmniAudioFeatureInputs,
audio_hashes: list[str] | None = None,
cached_audio_features: torch.Tensor | None = None,
) -> tuple[torch.Tensor, ...]:
input_features = audio_input["input_features"]
audio_feature_lengths = audio_input["audio_feature_lengths"]
@@ -1184,6 +1183,7 @@ class Qwen3OmniMoeThinkerForConditionalGeneration(
)
for _ in range(self.deepstack_num_level)
]
self.deepstack_input_embeds_num_tokens = 0
with self._mark_language_model(vllm_config):
lm_vllm_config = vllm_config.with_hf_config(
@@ -1205,6 +1205,18 @@ class Qwen3OmniMoeThinkerForConditionalGeneration(
) -> IntermediateTensors | None:
if not getattr(self, "deepstack_input_embeds", None):
return None # If vision tower is skipped
if getattr(self, "deepstack_input_embeds_num_tokens", 0) == 0:
return None
buf = self.deepstack_input_embeds[0].size(0)
if num_tokens > buf:
raise ValueError(f"Requested more deepstack tokens than buffer capacity: {num_tokens=} > {buf=}")
n_valid = self.deepstack_input_embeds_num_tokens
# embed_input_ids runs on unpadded length; forward uses padded num_tokens
# (vLLM gpu_model_runner). Tail positions have no vision deepstack and must
# be zero so we do not add stale buffer values or fail the old strict check.
if num_tokens > n_valid:
for idx in range(self.deepstack_num_level):
self.deepstack_input_embeds[idx][n_valid:num_tokens].zero_()
# get deepstack_input_embeds from buffer, and clear the buffer
return IntermediateTensors(
@@ -1232,15 +1244,21 @@ class Qwen3OmniMoeThinkerForConditionalGeneration(
]
for idx in range(self.deepstack_num_level):
self.deepstack_input_embeds[idx][:num_tokens].copy_(deepstack_input_embeds[idx])
self.deepstack_input_embeds_num_tokens = num_tokens
def _clear_deepstack_input_embeds(self, num_tokens: int) -> None:
if not getattr(self, "deepstack_input_embeds", None):
return
if getattr(self, "deepstack_input_embeds_num_tokens", 0) == 0:
return
# clear deepstack_input_embeds in buffer
# clear deepstack_input_embeds in buffer (may clear past n_valid for padding)
if num_tokens > 0:
buf = self.deepstack_input_embeds[0].size(0)
clear_len = min(num_tokens, buf)
for idx in range(self.deepstack_num_level):
self.deepstack_input_embeds[idx][:num_tokens].zero_()
self.deepstack_input_embeds[idx][:clear_len].zero_()
self.deepstack_input_embeds_num_tokens = 0
def _parse_and_validate_multimodal_inputs(self, **kwargs: object) -> dict:
mm_input_by_modality = {}
@@ -1301,10 +1319,12 @@ class Qwen3OmniMoeThinkerForConditionalGeneration(
# Detect interleaved audio-in-video early, since it affects
# both the deepstack path and the final embedding merge.
# is_multimodal from the worker may be CPU; bitwise ops need input_ids' device.
is_mm_device = is_multimodal.to(device=input_ids.device, non_blocking=True)
video_token_id = self.config.video_token_id
audio_token_id = self.config.audio_token_id
is_video = is_multimodal & (input_ids == video_token_id)
is_audio = is_multimodal & (input_ids == audio_token_id)
is_video = is_mm_device & (input_ids == video_token_id)
is_audio = is_mm_device & (input_ids == audio_token_id)
num_video = is_video.sum().item()
num_audio = is_audio.sum().item()
@@ -1372,7 +1392,7 @@ class Qwen3OmniMoeThinkerForConditionalGeneration(
multimodal_embeddings,
is_video,
is_audio,
is_multimodal,
is_mm_device,
num_video,
num_audio,
)
@@ -1583,19 +1603,17 @@ class Qwen3OmniMoeThinkerForConditionalGeneration(
)
@classmethod
def get_generation_prompt(
cls,
audio: np.ndarray,
stt_config: SpeechToTextConfig,
model_config: ModelConfig,
language: str | None,
task_type: Literal["transcribe", "translate"],
request_prompt: str,
to_language: str | None,
) -> PromptType:
def get_generation_prompt(cls, stt_params: SpeechToTextParams) -> PromptType:
"""
Construct a transcription/translation prompt for Qwen3-Omni.
"""
audio = stt_params.audio
stt_config = stt_params.stt_config
model_config = stt_params.model_config
language = stt_params.language
task_type = stt_params.task_type
to_language = stt_params.to_language
request_prompt = stt_params.request_prompt
# Transcribe this audio [into <language>] | for transcription
# Translate this audio [from <language> into <to_language>] | for translation
instruction = "Transcribe" if task_type == "transcribe" else "Translate"
@@ -42,6 +42,8 @@ class Qwen3TTSCode2Wav(nn.Module):
self._output_sample_rate: int | None = None
self._total_upsample: int | None = None
self._decoder_sliding_window: int | None = None
self._decode_chunk_frames = 300
self._decode_left_context_frames = 25
self._logged_codec_stats = False
@staticmethod
@@ -113,37 +115,40 @@ class Qwen3TTSCode2Wav(nn.Module):
if hasattr(decoder, "precompute_snake_caches"):
decoder.precompute_snake_caches()
chunk_frames = 0
left_frames = 0
model_cfg = getattr(self.vllm_config, "model_config", None)
connector_cfg = getattr(model_cfg, "stage_connector_config", None)
extra_cfg = (
connector_cfg.get("extra", connector_cfg)
if isinstance(connector_cfg, dict)
else getattr(connector_cfg, "extra", None)
)
if isinstance(extra_cfg, dict):
chunk_frames = int(extra_cfg.get("codec_chunk_frames") or 0)
left_frames = int(extra_cfg.get("codec_left_context_frames") or 0)
if getattr(model_cfg, "async_chunk", False) and chunk_frames > 0:
self._decode_chunk_frames = chunk_frames
self._decode_left_context_frames = left_frames if left_frames > 0 else 0
if hasattr(decoder, "enable_cudagraph"):
device = self._module_device(decoder)
if device.type == "cuda":
try:
chunk_frames = 0
left_frames = 0
model_cfg = getattr(self.vllm_config, "model_config", None)
connector_cfg = getattr(model_cfg, "stage_connector_config", None)
extra_cfg = (
connector_cfg.get("extra", connector_cfg)
if isinstance(connector_cfg, dict)
else getattr(connector_cfg, "extra", None)
)
if isinstance(extra_cfg, dict):
chunk_frames = int(extra_cfg.get("codec_chunk_frames") or 0)
left_frames = int(extra_cfg.get("codec_left_context_frames") or 0)
if (
chunk_frames > 0
and left_frames > 0
and self._decoder_sliding_window
and left_frames < self._decoder_sliding_window
):
logger.warning(
"Qwen3-TTS streaming codec_left_context_frames=%d is smaller than "
"decoder sliding_window=%d; chunk-boundary distortion may occur. "
"Increase codec_left_context_frames to at least %d for streaming.",
left_frames,
self._decoder_sliding_window,
self._decoder_sliding_window,
)
if (
chunk_frames > 0
and left_frames > 0
and self._decoder_sliding_window
and left_frames < self._decoder_sliding_window
):
logger.warning(
"Qwen3-TTS streaming codec_left_context_frames=%d is smaller than "
"decoder sliding_window=%d; chunk-boundary distortion may occur. "
"Increase codec_left_context_frames to at least %d for streaming.",
left_frames,
self._decoder_sliding_window,
self._decoder_sliding_window,
)
decoder.enable_cudagraph(
device=device,
@@ -297,7 +302,16 @@ class Qwen3TTSCode2Wav(nn.Module):
wav_tensors: list[torch.Tensor] = []
for codes_qf in valid_codes_qf:
codes_bqf = codes_qf.unsqueeze(0) # [1, Q, F]
wav = decoder.chunked_decode(codes_bqf) # [1, 1, wav_len]
try:
wav = decoder.chunked_decode(
codes_bqf,
chunk_size=self._decode_chunk_frames,
left_context_size=self._decode_left_context_frames,
) # [1, 1, wav_len]
except TypeError:
# Unit-test fakes and older decoder shims may not accept the
# explicit chunk kwargs; production Qwen3-TTS decoders do.
wav = decoder.chunked_decode(codes_bqf) # [1, 1, wav_len]
wav_tensors.append(wav.squeeze(0).squeeze(0)) # [wav_len]
audios: list[torch.Tensor] = [empty] * num_req