Merge origin/main into dev/vllm-align
Resolved conflicts: - vllm_omni/inputs/preprocess.py: took origin/main's elif mm_processor_kwargs branch, fixed undefined mm_uuids reference - vllm_omni/model_executor/models/qwen3_tts/qwen3_tts_code_predictor_vllm.py: took origin/main's NPU support Made-with: Cursor Signed-off-by: tzhouam <tzhouam@connect.ust.hk>
This commit is contained in:
commit
26744bcb35
240 files changed
+25869
-3091
No files matched your search
@@ -0,0 +1,3 @@
|
||||
from .glm_image_ar import GlmImageForConditionalGeneration
|
||||
|
||||
__all__ = ["GlmImageForConditionalGeneration"]
|
||||
File diff suppressed because it is too large.
Load diff
Whitespace-only changes.
@@ -0,0 +1,206 @@
|
||||
# Copyright 2025 Xiaomi Corporation.
|
||||
import copy
|
||||
from dataclasses import dataclass
|
||||
|
||||
from transformers import PretrainedConfig, Qwen2Config
|
||||
|
||||
SPAN_CODEC_START_TOKEN_ID = 151670
|
||||
SPAN_CODEC_END_TOKEN_ID = 151672
|
||||
TALKER_CODEC_PAD_TOKEN_ID = 151667
|
||||
TEXT_GROUP_SIZE = 5
|
||||
PAD_GROUP_SIZE = 5
|
||||
NO_INTERLEAVE_NEXT_TOKEN_ID = 151671
|
||||
|
||||
|
||||
@dataclass
|
||||
class MiMoAudioConfig(Qwen2Config):
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
speech_vocab_size: str | int = "1025-1025-129-129-129-129-129-129",
|
||||
speech_zeroemb_idx: str | int = "1024-1024-128-128-128-128-128-128",
|
||||
delay_pattern: str = "0-1-2-3-4-5-6-7",
|
||||
head_dim: int = 128,
|
||||
group_size: int = 4,
|
||||
audio_channels: int = 8,
|
||||
local_dim: int = 1024,
|
||||
local_layers: int = 16,
|
||||
local_attn_heads: int = 64,
|
||||
local_ffn_dim: int = 4096,
|
||||
local_attn_dropout: float = 0.1,
|
||||
input_local_layers: int = 6,
|
||||
input_local_dim: int | None = None,
|
||||
input_full_attention: bool | None = None,
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__(
|
||||
**kwargs,
|
||||
)
|
||||
self.speech_vocab_size = speech_vocab_size
|
||||
self.speech_zeroemb_idx = speech_zeroemb_idx
|
||||
self.delay_pattern = delay_pattern
|
||||
|
||||
self.head_dim = head_dim
|
||||
|
||||
self.group_size = group_size
|
||||
self.audio_channels = audio_channels
|
||||
|
||||
self.local_dim = local_dim
|
||||
self.local_layers = local_layers
|
||||
self.local_attn_heads = local_attn_heads
|
||||
self.local_ffn_dim = local_ffn_dim
|
||||
self.local_attn_dropout = local_attn_dropout
|
||||
|
||||
self.input_local_layers = input_local_layers
|
||||
self.input_local_dim = input_local_dim or local_dim
|
||||
|
||||
self.input_full_attention = input_full_attention
|
||||
|
||||
def _parse_maybe_list(self, value: str | int, length: int) -> list[int]:
|
||||
if isinstance(value, str) and "-" in value:
|
||||
return [int(s) for s in value.split("-")]
|
||||
return [int(value)] * length
|
||||
|
||||
def parsed_speech_empty_ids(self):
|
||||
return self._parse_maybe_list(self.speech_zeroemb_idx, self.audio_channels)
|
||||
|
||||
def parsed_speech_vocab_sizes(self):
|
||||
return self._parse_maybe_list(self.speech_vocab_size, self.audio_channels)
|
||||
|
||||
def parsed_delay_pattern(self):
|
||||
return self._parse_maybe_list(self.delay_pattern, self.audio_channels)
|
||||
|
||||
def local_config(self):
|
||||
config = copy.deepcopy(self)
|
||||
|
||||
config.hidden_size = self.local_dim
|
||||
config.num_hidden_layers = self.local_layers
|
||||
config.num_attention_heads = self.local_attn_heads
|
||||
config.num_key_value_heads = self.local_attn_heads
|
||||
config.head_dim = config.hidden_size // self.local_attn_heads
|
||||
config.intermediate_size = self.local_ffn_dim
|
||||
config.attention_dropout = self.local_attn_dropout
|
||||
|
||||
return config
|
||||
|
||||
def input_local_config(self):
|
||||
config = copy.deepcopy(self)
|
||||
|
||||
config.hidden_size = self.input_local_dim
|
||||
config.num_hidden_layers = self.input_local_layers
|
||||
config.num_attention_heads = self.local_attn_heads
|
||||
config.num_key_value_heads = self.local_attn_heads
|
||||
config.head_dim = config.hidden_size // self.local_attn_heads
|
||||
config.intermediate_size = config.hidden_size * 4
|
||||
config.attention_dropout = self.local_attn_dropout
|
||||
|
||||
return config
|
||||
|
||||
def __repr__(self):
|
||||
return (
|
||||
f"{self.__class__.__name__}("
|
||||
f"speech_vocab_size={self.speech_vocab_size!r}, "
|
||||
f"speech_zeroemb_idx={self.speech_zeroemb_idx!r}, "
|
||||
f"delay_pattern={self.delay_pattern!r}, "
|
||||
f"head_dim={self.head_dim}, "
|
||||
f"group_size={self.group_size}, "
|
||||
f"audio_channels={self.audio_channels}, "
|
||||
f"local_dim={self.local_dim}, "
|
||||
f"local_layers={self.local_layers}, "
|
||||
f"local_attn_heads={self.local_attn_heads}, "
|
||||
f"local_ffn_dim={self.local_ffn_dim}, "
|
||||
f"local_attn_dropout={self.local_attn_dropout}, "
|
||||
f"input_local_layers={self.input_local_layers}, "
|
||||
f"input_local_dim={self.input_local_dim}, "
|
||||
f"input_full_attention={self.input_full_attention})"
|
||||
)
|
||||
|
||||
|
||||
class MiMoAudioTokenizerConfig(PretrainedConfig):
|
||||
model_type = "mimo_audio_tokenizer"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
max_audio_seconds: int = 1800,
|
||||
stride_size: int = 2,
|
||||
avg_pooler: int = 1,
|
||||
d_model: int = 768,
|
||||
scale_embedding: bool = True,
|
||||
kernel_size: int = 3,
|
||||
activation_function: str = "gelu",
|
||||
encoder_layers: int = 8,
|
||||
encoder_skip_layer_id: int = None,
|
||||
encoder_attention_heads: int = 12,
|
||||
encoder_ffn_dim: int = 3072,
|
||||
encoder_causal: bool = False,
|
||||
encoder_attn_window_size: list[int] = None,
|
||||
decoder_layers: int = 8,
|
||||
decoder_attention_heads: int = 12,
|
||||
decoder_ffn_dim: int = 3072,
|
||||
decoder_kernel_size: int = 3,
|
||||
decoder_stride_size: int = 2,
|
||||
decoder_causal: bool = True,
|
||||
decoder_attn_window_size: list[int] = None,
|
||||
nfft: int = 1024,
|
||||
vocoder_dim: int = 512,
|
||||
vocoder_intermediate_dim: int = 4096,
|
||||
vocoder_num_layers: int = 30,
|
||||
n_mels: int = 80,
|
||||
sampling_rate: int = 24000,
|
||||
hop_length: int = 240,
|
||||
window_size: int = 1024,
|
||||
vocoder_padding: str = "same",
|
||||
fmin: int = 0,
|
||||
fmax: int = None,
|
||||
num_quantizers: int = 12,
|
||||
codebook_size: list[int] = None,
|
||||
threshold_ema_dead_code: int = 10,
|
||||
position_embedding_type: str = "rope",
|
||||
rope_theta: int = 10000,
|
||||
rope_type: str = "default",
|
||||
ln_type: str = "LayerNorm",
|
||||
vocoder_attention_heads: int = 4,
|
||||
vocoder_attn_window_size: list[int] = None,
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__(**kwargs)
|
||||
self.max_audio_seconds = max_audio_seconds
|
||||
self.stride_size = stride_size
|
||||
self.avg_pooler = avg_pooler
|
||||
self.d_model = d_model
|
||||
self.scale_embedding = scale_embedding
|
||||
self.kernel_size = kernel_size
|
||||
self.activation_function = activation_function
|
||||
self.encoder_layers = encoder_layers
|
||||
self.encoder_skip_layer_id = encoder_skip_layer_id
|
||||
self.encoder_attention_heads = encoder_attention_heads
|
||||
self.encoder_ffn_dim = encoder_ffn_dim
|
||||
self.encoder_causal = encoder_causal
|
||||
self.encoder_attn_window_size = encoder_attn_window_size if encoder_attn_window_size is not None else [-1, -1]
|
||||
self.decoder_layers = decoder_layers
|
||||
self.decoder_attention_heads = decoder_attention_heads
|
||||
self.decoder_ffn_dim = decoder_ffn_dim
|
||||
self.decoder_kernel_size = decoder_kernel_size
|
||||
self.decoder_stride_size = decoder_stride_size
|
||||
self.decoder_causal = decoder_causal
|
||||
self.decoder_attn_window_size = decoder_attn_window_size if decoder_attn_window_size is not None else [-1, -1]
|
||||
self.nfft = nfft
|
||||
self.vocoder_dim = vocoder_dim
|
||||
self.vocoder_intermediate_dim = vocoder_intermediate_dim
|
||||
self.vocoder_num_layers = vocoder_num_layers
|
||||
self.n_mels = n_mels
|
||||
self.sampling_rate = sampling_rate
|
||||
self.hop_length = hop_length
|
||||
self.window_size = window_size
|
||||
self.vocoder_padding = vocoder_padding
|
||||
self.fmin = fmin
|
||||
self.fmax = fmax
|
||||
self.num_quantizers = num_quantizers
|
||||
self.codebook_size = codebook_size if codebook_size is not None else [1024]
|
||||
self.threshold_ema_dead_code = threshold_ema_dead_code
|
||||
self.position_embedding_type = position_embedding_type
|
||||
self.rope_theta = rope_theta
|
||||
self.rope_type = rope_type
|
||||
self.ln_type = ln_type
|
||||
self.vocoder_attention_heads = vocoder_attention_heads
|
||||
self.vocoder_attn_window_size = vocoder_attn_window_size if vocoder_attn_window_size is not None else [40, 10]
|
||||
@@ -0,0 +1,914 @@
|
||||
# Copyright 2025 Xiaomi Corporation.
|
||||
import os
|
||||
from collections.abc import Iterable, Mapping, Sequence
|
||||
from functools import cached_property
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from torch import nn
|
||||
from transformers import BatchFeature, Qwen2Config
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.config.multimodal import BaseDummyOptions
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.logits_processor import LogitsProcessor
|
||||
from vllm.model_executor.models import SupportsPP
|
||||
from vllm.model_executor.models.interfaces import SupportsMultiModal
|
||||
from vllm.model_executor.models.utils import init_vllm_registered_model
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.multimodal.inputs import (
|
||||
AudioItem,
|
||||
ModalityData,
|
||||
MultiModalBatchedField,
|
||||
MultiModalDataDict,
|
||||
MultiModalFieldConfig,
|
||||
MultiModalFieldElem,
|
||||
MultiModalKwargsItem,
|
||||
)
|
||||
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.sequence import IntermediateTensors
|
||||
from vllm.utils.cache import LRUCache
|
||||
from vllm.utils.collection_utils import is_list_of
|
||||
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.model_executor.custom_process_mixin import CustomProcessMixin
|
||||
from vllm_omni.model_executor.models.mimo_audio.config_mimo_audio import (
|
||||
NO_INTERLEAVE_NEXT_TOKEN_ID,
|
||||
PAD_GROUP_SIZE,
|
||||
SPAN_CODEC_END_TOKEN_ID,
|
||||
SPAN_CODEC_START_TOKEN_ID,
|
||||
TALKER_CODEC_PAD_TOKEN_ID,
|
||||
TEXT_GROUP_SIZE,
|
||||
MiMoAudioConfig,
|
||||
)
|
||||
from vllm_omni.model_executor.models.mimo_audio.mimo_audio_code2wav import get_tokenizer_worker
|
||||
from vllm_omni.model_executor.models.qwen2_5_omni.qwen2_5_omni import OmniOutput
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def interleave_5_and_5_in_span(
|
||||
input_ids: list[int],
|
||||
*,
|
||||
span_start_token: int = SPAN_CODEC_START_TOKEN_ID,
|
||||
span_end_token: int = SPAN_CODEC_END_TOKEN_ID,
|
||||
pad_token_id: int = TALKER_CODEC_PAD_TOKEN_ID,
|
||||
text_group_size: int = TEXT_GROUP_SIZE,
|
||||
pad_group_size: int = PAD_GROUP_SIZE,
|
||||
no_interleave_next_token: int = NO_INTERLEAVE_NEXT_TOKEN_ID,
|
||||
) -> list[int]:
|
||||
"""
|
||||
Interleave text tokens and padding tokens within spans marked by special tokens.
|
||||
|
||||
Finds spans delimited by span_start_token and span_end_token, then reorganizes
|
||||
tokens inside each span by grouping text tokens (excluding padding) into groups
|
||||
of text_group_size, followed by pad_group_size padding tokens. Interleaving is
|
||||
skipped if the token after span_end_token is no_interleave_next_token.
|
||||
|
||||
Args:
|
||||
input_ids: Input token ID list
|
||||
span_start_token: Token marking span start (default: 151670)
|
||||
span_end_token: Token marking span end (default: 151672)
|
||||
pad_token_id: Padding token ID (default: 151667)
|
||||
text_group_size: Number of text tokens per group (default: 5)
|
||||
pad_group_size: Number of padding tokens per group (default: 5)
|
||||
no_interleave_next_token: Skip interleaving if this token follows span_end (default: 151671)
|
||||
|
||||
Returns:
|
||||
Processed token list with same length as input
|
||||
"""
|
||||
if not input_ids:
|
||||
return input_ids
|
||||
|
||||
original_len = len(input_ids)
|
||||
output_ids: list[int] = []
|
||||
cursor = 0
|
||||
|
||||
while cursor < original_len:
|
||||
# Non-span starting point: Copy as is
|
||||
if input_ids[cursor] != span_start_token:
|
||||
output_ids.append(input_ids[cursor])
|
||||
cursor += 1
|
||||
continue
|
||||
|
||||
# ===== Enter span processing =====
|
||||
output_ids.append(input_ids[cursor])
|
||||
cursor += 1
|
||||
|
||||
span_end_pos = cursor
|
||||
while span_end_pos < original_len and input_ids[span_end_pos] != span_end_token:
|
||||
span_end_pos += 1
|
||||
|
||||
# If span_end_token is not found: Output the remaining as is and end
|
||||
if span_end_pos >= original_len:
|
||||
output_ids.extend(input_ids[cursor:])
|
||||
break
|
||||
|
||||
next_pos = span_end_pos + 1
|
||||
next_token = input_ids[next_pos] if next_pos < original_len else None
|
||||
|
||||
# Rule:
|
||||
# After "-end" is 151667(PAD) -> for interlacing
|
||||
# After "-end" is 151671 -> Do not interlace
|
||||
do_interleave = next_token == pad_token_id
|
||||
if next_token == no_interleave_next_token:
|
||||
do_interleave = False
|
||||
|
||||
if not do_interleave:
|
||||
output_ids.extend(input_ids[cursor:span_end_pos])
|
||||
output_ids.append(span_end_token)
|
||||
cursor = span_end_pos + 1
|
||||
continue
|
||||
|
||||
span_content = input_ids[cursor:span_end_pos]
|
||||
span_original_len = len(span_content)
|
||||
span_text_tokens = [t for t in span_content if t != pad_token_id]
|
||||
|
||||
rebuilt_span: list[int] = []
|
||||
text_cursor = 0
|
||||
total_text = len(span_text_tokens)
|
||||
|
||||
while text_cursor < total_text:
|
||||
take_text = min(text_group_size, total_text - text_cursor)
|
||||
rebuilt_span.extend(span_text_tokens[text_cursor : text_cursor + take_text])
|
||||
text_cursor += take_text
|
||||
|
||||
if text_cursor < total_text:
|
||||
rebuilt_span.extend([pad_token_id] * pad_group_size)
|
||||
|
||||
output_ids.extend(rebuilt_span)
|
||||
output_ids.append(span_end_token)
|
||||
|
||||
extra_tokens_added = len(rebuilt_span) - span_original_len
|
||||
cursor = span_end_pos + 1
|
||||
|
||||
while extra_tokens_added > 0 and cursor < original_len:
|
||||
if input_ids[cursor] == pad_token_id:
|
||||
extra_tokens_added -= 1
|
||||
cursor += 1
|
||||
else:
|
||||
output_ids.append(input_ids[cursor])
|
||||
cursor += 1
|
||||
|
||||
if extra_tokens_added > 0:
|
||||
return output_ids[:original_len]
|
||||
|
||||
if len(output_ids) > original_len:
|
||||
output_ids = output_ids[:original_len]
|
||||
elif len(output_ids) < original_len:
|
||||
output_ids.extend([pad_token_id] * (original_len - len(output_ids)))
|
||||
|
||||
return output_ids
|
||||
|
||||
|
||||
class MiMoAudioLLMProcessingInfo(
|
||||
BaseProcessingInfo,
|
||||
):
|
||||
def get_hf_config(self):
|
||||
return self.ctx.get_hf_config(Qwen2Config)
|
||||
|
||||
def get_hf_processor(
|
||||
self,
|
||||
*,
|
||||
# Ignored in initialization
|
||||
sampling_rate: int | None = None,
|
||||
**kwargs: object,
|
||||
):
|
||||
# MiMoAudio doesn't use a standard HF processor like Qwen2Audio
|
||||
# Instead it uses MiMoAudioTokenizer directly
|
||||
# This method may return None or a dummy processor
|
||||
# depending on the actual implementation requirements
|
||||
return None
|
||||
|
||||
def get_data_parser(self) -> MultiModalDataParser:
|
||||
sampling_rate = 24000
|
||||
return MiMoAudioDataParser(target_sr=sampling_rate)
|
||||
|
||||
def get_feature_extractor(
|
||||
self,
|
||||
*,
|
||||
# Ignored in initialization
|
||||
sampling_rate: int | None = None,
|
||||
):
|
||||
# MiMoAudio uses MiMoAudioTokenizer instead of WhisperFeatureExtractor
|
||||
# This method may need to return the tokenizer or None
|
||||
# depending on the actual implementation requirements
|
||||
return None
|
||||
|
||||
def get_supported_mm_limits(self) -> Mapping[str, int | None]:
|
||||
return {"audio": None}
|
||||
|
||||
def get_mm_max_tokens_per_item(
|
||||
self,
|
||||
seq_len: int,
|
||||
mm_counts: Mapping[str, int],
|
||||
) -> Mapping[str, int]:
|
||||
# MiMoAudio has different tokenization than Qwen2Audio
|
||||
# This is a placeholder - adjust based on actual MiMoAudio tokenizer limits
|
||||
# For now, return a large value or None
|
||||
# This should be adjusted based on MiMoAudio's actual constraints
|
||||
return {"audio": 1}
|
||||
|
||||
|
||||
class MiMoAudioLLMDummyInputsBuilder(BaseDummyInputsBuilder[MiMoAudioLLMProcessingInfo]):
|
||||
_processor_inputs_cache: LRUCache = LRUCache(capacity=1024)
|
||||
|
||||
def get_dummy_text(self, mm_counts: Mapping[str, int]) -> str:
|
||||
num_audios = mm_counts.get("audio", 0)
|
||||
return (" <|empty|>" * num_audios).strip()
|
||||
|
||||
def get_dummy_mm_data(
|
||||
self, seq_len: int, mm_counts: Mapping[str, int], mm_options: Mapping[str, BaseDummyOptions] | None = None
|
||||
) -> MultiModalDataDict:
|
||||
num_audios = mm_counts.get("audio", 0)
|
||||
if num_audios == 0:
|
||||
return {}
|
||||
# Return dummy raw audio data (not encoded codes)
|
||||
# This will be processed by _parse_audio_data like real audio
|
||||
# Use 1 second of audio at target_sr (24000 Hz)
|
||||
dummy_audio_length = mm_options.get("audio").length if mm_options else 24000 # 1 second at 24kHz
|
||||
dummy_audio = np.zeros((dummy_audio_length,), dtype=np.float32)
|
||||
return {"audio": [(dummy_audio, 24000)] * num_audios}
|
||||
|
||||
def get_dummy_processor_inputs(
|
||||
self,
|
||||
seq_len: int,
|
||||
mm_counts: Mapping[str, int],
|
||||
mm_options: Mapping[str, BaseDummyOptions] | None = None,
|
||||
) -> ProcessorInputs:
|
||||
dummy_text = self.get_dummy_text(mm_counts)
|
||||
dummy_mm_data = self.get_dummy_mm_data(seq_len, mm_counts, mm_options)
|
||||
|
||||
dummy_mm_items = self.info.parse_mm_data(dummy_mm_data)
|
||||
|
||||
dummy_processor_inputs = ProcessorInputs(
|
||||
prompt=dummy_text,
|
||||
mm_items=dummy_mm_items,
|
||||
)
|
||||
|
||||
return dummy_processor_inputs
|
||||
|
||||
|
||||
class MiMoAudioDataParser(MultiModalDataParser):
|
||||
def __init__(self, target_sr: int, use_mono_channel: bool = True):
|
||||
super().__init__(target_sr=target_sr)
|
||||
self.use_mono_channel = use_mono_channel
|
||||
self.target_sr = target_sr
|
||||
|
||||
tokenizer_device = os.environ.get("MIMO_AUDIO_TOKENIZER_DEVICE", None)
|
||||
|
||||
if tokenizer_device:
|
||||
if tokenizer_device.lower() == "cpu":
|
||||
self.device = torch.device("cpu")
|
||||
else:
|
||||
# Support formats like "cuda", "cuda:0", "cuda:6", etc.
|
||||
self.device = torch.device(tokenizer_device)
|
||||
else:
|
||||
# Default to cuda (will use current GPU)
|
||||
self.device = torch.device(f"cuda:{torch.cuda.current_device()}" if torch.cuda.is_available() else "cpu")
|
||||
|
||||
self.audio_tokenizer_path = os.environ.get("MIMO_AUDIO_TOKENIZER_PATH", None)
|
||||
if not self.audio_tokenizer_path:
|
||||
raise ValueError(
|
||||
"Audio tokenizer path is not set. Provide "
|
||||
"`model_config.audio_tokenizer_path` in the stage config "
|
||||
"or export MIMO_AUDIO_TOKENIZER_PATH."
|
||||
)
|
||||
|
||||
if not os.path.exists(self.audio_tokenizer_path):
|
||||
raise ValueError(
|
||||
"Audio tokenizer not exists. Provide "
|
||||
"`model_config.audio_tokenizer_path` in the stage config "
|
||||
"or export MIMO_AUDIO_TOKENIZER_PATH."
|
||||
)
|
||||
|
||||
self.tokenizer_config_path = os.environ.get("MIMO_AUDIO_TOKENIZER_PATH", None)
|
||||
|
||||
self.mimo_tokenizer = get_tokenizer_worker(
|
||||
device=self.device,
|
||||
config_path=self.tokenizer_config_path,
|
||||
audio_tokenizer_path=self.audio_tokenizer_path,
|
||||
)
|
||||
|
||||
def _parse_audio_data(
|
||||
self,
|
||||
data: ModalityData[AudioItem],
|
||||
):
|
||||
if data is None:
|
||||
return AudioProcessorItems(None)
|
||||
|
||||
# also check single audio item with sampling rate
|
||||
if self._is_empty(data) or (isinstance(data, tuple) and self._is_empty(data[0])):
|
||||
return None
|
||||
|
||||
if (
|
||||
is_list_of(data, float)
|
||||
or isinstance(data, (np.ndarray, torch.Tensor))
|
||||
and data.ndim == 1
|
||||
or isinstance(data, tuple)
|
||||
):
|
||||
data_items = [data]
|
||||
elif isinstance(data, (np.ndarray, torch.Tensor)):
|
||||
data_items = [elem for elem in data]
|
||||
else:
|
||||
data_items = data
|
||||
|
||||
new_audios = list[np.ndarray]()
|
||||
for data_item in data_items:
|
||||
if not isinstance(data_item, tuple) or not isinstance(data_item[0], np.ndarray):
|
||||
new_audios.append(data_item)
|
||||
continue
|
||||
|
||||
audio, orig_sr = self._get_audio_with_sr(data_item)
|
||||
if orig_sr is None:
|
||||
new_audio = audio
|
||||
else:
|
||||
new_audio = self.audio_resampler.resample(audio, orig_sr=orig_sr)
|
||||
wav_tensor = torch.from_numpy(new_audio.astype(np.float32))
|
||||
if wav_tensor.dim() == 1:
|
||||
wav_tensor = wav_tensor.unsqueeze(0)
|
||||
if self.use_mono_channel:
|
||||
if wav_tensor.size(0) > 1:
|
||||
wav_mono = wav_tensor.mean(dim=0) # [samples]
|
||||
else:
|
||||
wav_mono = wav_tensor[0]
|
||||
audio_codes = self.mimo_tokenizer.encode(audio=(wav_mono, self.target_sr))
|
||||
new_audio = audio_codes.detach().cpu().numpy().astype(np.int64).tolist()
|
||||
new_audios.append(new_audio)
|
||||
|
||||
return AudioProcessorItems(new_audios)
|
||||
|
||||
|
||||
class MiMoAudioLLMMultiModalProcessor(BaseMultiModalProcessor[MiMoAudioLLMProcessingInfo]):
|
||||
def _call_hf_processor(
|
||||
self,
|
||||
prompt: str,
|
||||
mm_data: Mapping[str, object],
|
||||
mm_kwargs: Mapping[str, Any],
|
||||
tok_kwargs: Mapping[str, object],
|
||||
) -> BatchFeature:
|
||||
sampling_rate = 24000
|
||||
audios = mm_data.pop("audios", [])
|
||||
tokenizer = self.info.get_tokenizer()
|
||||
if audios:
|
||||
mm_data["audio"] = audios
|
||||
|
||||
if isinstance(prompt, str):
|
||||
prompt_ids = tokenizer.encode(prompt)
|
||||
else:
|
||||
prompt_ids = prompt
|
||||
|
||||
# Text-only input not supported in composite processor
|
||||
if not mm_data.get("audio", []):
|
||||
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=sampling_rate,
|
||||
)
|
||||
|
||||
audio_lengths = [len(x) for x in audios]
|
||||
if all(audio_length == 8 for audio_length in audio_lengths):
|
||||
audio_lengths = [len(x[0]) for x in audios]
|
||||
|
||||
return BatchFeature(
|
||||
data={
|
||||
"input_ids": torch.tensor([prompt_ids], dtype=torch.int64),
|
||||
"audio_embeds": audios,
|
||||
"audio_lengths": audio_lengths,
|
||||
"mm_data": mm_data,
|
||||
"mm_kwargs": mm_kwargs,
|
||||
"tok_kwargs": tok_kwargs,
|
||||
},
|
||||
tensor_type=None,
|
||||
)
|
||||
|
||||
def _get_mm_fields_config(
|
||||
self,
|
||||
hf_inputs: BatchFeature,
|
||||
hf_processor_mm_kwargs: Mapping[str, object],
|
||||
) -> Mapping[str, MultiModalFieldConfig]:
|
||||
# MiMoAudio may have different field names than Qwen2Audio
|
||||
# Adjust based on actual MiMoAudio model requirements
|
||||
# For now, return empty dict or adjust based on actual needs
|
||||
return {
|
||||
"audio_embeds": MultiModalFieldConfig.batched("audio"),
|
||||
"audio_lengths": MultiModalFieldConfig.batched("audio"),
|
||||
}
|
||||
|
||||
def _get_prompt_updates(
|
||||
self,
|
||||
mm_items: MultiModalDataItems,
|
||||
hf_processor_mm_kwargs: Mapping[str, object],
|
||||
out_mm_kwargs,
|
||||
) -> Sequence[PromptUpdate]:
|
||||
# MiMoAudio doesn't use a standard HF processor like Qwen2Audio
|
||||
# Get tokenizer and vocabulary directly
|
||||
tokenizer = self.info.get_tokenizer()
|
||||
vocab = tokenizer.get_vocab()
|
||||
|
||||
# MiMoAudio may use different audio tokens
|
||||
# Adjust these based on actual tokenizer vocabulary
|
||||
# Common tokens in MiMoAudio might be different from Qwen2Audio
|
||||
audio_token = "<|empty|>"
|
||||
|
||||
audio_bos_id = None
|
||||
audio_eos_id = None
|
||||
audio_token_id = vocab.get(audio_token, None)
|
||||
|
||||
# If tokens don't exist, try alternative tokens or use None
|
||||
if audio_token_id is None:
|
||||
# Try alternative token names or skip audio token replacement
|
||||
return []
|
||||
|
||||
audio_kwargs = out_mm_kwargs.get("audio", [])
|
||||
# feature_attention_mask = out_mm_kwargs.get("feature_attention_mask", None)
|
||||
|
||||
if audio_kwargs:
|
||||
audio_output_lengths = [item["audio_lengths"].data for item in audio_kwargs]
|
||||
else:
|
||||
audio_output_lengths = []
|
||||
if mm_items and "audio" in mm_items:
|
||||
try:
|
||||
audios = mm_items.get_items("audio", AudioProcessorItems)
|
||||
if audios is not None:
|
||||
num_audios = audios.get_count()
|
||||
audio_output_lengths = [audios.get_audio_length(i) for i in range(num_audios)]
|
||||
except Exception as e:
|
||||
logger.error(f"_get_prompt_updates failed: {e}")
|
||||
|
||||
def get_replacement_mimo_audio(item_idx: int):
|
||||
if item_idx >= len(audio_output_lengths):
|
||||
# If no length info, use a default or skip
|
||||
return PromptUpdateDetails.select_token_id(
|
||||
[audio_token_id],
|
||||
embed_token_id=audio_token_id,
|
||||
)
|
||||
|
||||
num_features = audio_output_lengths[item_idx] // 4
|
||||
if num_features == 0:
|
||||
try:
|
||||
audios = mm_items.get_items("audio", AudioProcessorItems)
|
||||
audio_len = audios.get_audio_length(item_idx)
|
||||
raise ValueError(f"The audio (len={audio_len}) is too short to be represented inside the model")
|
||||
except (AttributeError, KeyError):
|
||||
# If AudioProcessorItems is not available, use default
|
||||
num_features = 1
|
||||
|
||||
audio_tokens = [audio_token_id] * num_features
|
||||
|
||||
# Build replacement tokens following Qwen2Audio pattern
|
||||
# [audio_bos_id] + audio_tokens + [audio_eos_id]
|
||||
replacement_tokens = []
|
||||
if audio_bos_id is not None:
|
||||
replacement_tokens.append(audio_bos_id)
|
||||
replacement_tokens.extend(audio_tokens)
|
||||
if audio_eos_id is not None:
|
||||
replacement_tokens.append(audio_eos_id)
|
||||
|
||||
# If no bos/eos tokens, just use audio tokens
|
||||
if not replacement_tokens:
|
||||
replacement_tokens = audio_tokens
|
||||
|
||||
return PromptUpdateDetails.select_token_id(
|
||||
replacement_tokens,
|
||||
embed_token_id=audio_token_id,
|
||||
)
|
||||
|
||||
return [
|
||||
PromptReplacement(
|
||||
modality="audio",
|
||||
target=audio_token,
|
||||
replacement=get_replacement_mimo_audio,
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
@MULTIMODAL_REGISTRY.register_processor(
|
||||
MiMoAudioLLMMultiModalProcessor,
|
||||
info=MiMoAudioLLMProcessingInfo,
|
||||
dummy_inputs=MiMoAudioLLMDummyInputsBuilder,
|
||||
)
|
||||
class MiMoAudioForConditionalGeneration(
|
||||
nn.Module,
|
||||
SupportsPP,
|
||||
SupportsMultiModal,
|
||||
CustomProcessMixin,
|
||||
):
|
||||
packed_modules_mapping = {
|
||||
"qkv_proj": [
|
||||
"q_proj",
|
||||
"k_proj",
|
||||
"v_proj",
|
||||
],
|
||||
"gate_up_proj": [
|
||||
"gate_proj",
|
||||
"up_proj",
|
||||
],
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def get_placeholder_str(cls, modality: str, i: int) -> str | None:
|
||||
if modality.startswith("image"):
|
||||
return "<|vision_start|><|IMAGE|><|vision_end|>"
|
||||
if modality.startswith("video"):
|
||||
return "<|vision_start|><|VIDEO|><|vision_end|>"
|
||||
if modality.startswith("audio"):
|
||||
return "<|sosp|><|empty|><|eosp|>"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vllm_config: VllmConfig,
|
||||
prefix: str = "",
|
||||
):
|
||||
super().__init__()
|
||||
self.has_preprocess = False
|
||||
self.have_multimodal_outputs = True
|
||||
self.requires_raw_input_tokens = True
|
||||
config = vllm_config.model_config.hf_config
|
||||
config = MiMoAudioConfig(**vars(config)) if isinstance(config, Qwen2Config) else config
|
||||
quant_config = vllm_config.quant_config
|
||||
lora_config = vllm_config.lora_config
|
||||
|
||||
self.logits_processor = LogitsProcessor(config.vocab_size)
|
||||
|
||||
self.config = config
|
||||
self.lora_config = lora_config
|
||||
|
||||
self.quant_config = quant_config
|
||||
self.vllm_config = vllm_config
|
||||
|
||||
self.llm_prev_hidden_state = None
|
||||
self.device = vllm_config.device_config.device
|
||||
self.pin_memory = is_pin_memory_available()
|
||||
|
||||
if "model_stage" in os.environ:
|
||||
self.model_stage = os.environ["model_stage"]
|
||||
else:
|
||||
self.model_stage = vllm_config.model_config.model_stage
|
||||
|
||||
if self.model_stage == "fused_thinker_talker":
|
||||
self.has_preprocess = True
|
||||
self.set_custom_preprocess(self.fused_thinker_talker_preprocess)
|
||||
# Initialize fused_thinker_talker llm model (multimodal processing)
|
||||
self.fused_thinker_talker = init_vllm_registered_model(
|
||||
vllm_config=vllm_config,
|
||||
# prefix=maybe_prefix(prefix, "model"),
|
||||
hf_config=vllm_config.model_config.hf_config,
|
||||
# Use registry architecture key
|
||||
architectures=["MiMoAudioLLMModel"],
|
||||
)
|
||||
self.token2wav = None
|
||||
self.model = self.fused_thinker_talker
|
||||
|
||||
elif self.model_stage == "code2wav":
|
||||
self.fused_thinker_talker = None
|
||||
# Initialize token2wav (code->mel->wav) like thinker/talker
|
||||
self.token2wav = init_vllm_registered_model(
|
||||
vllm_config=vllm_config,
|
||||
# prefix=maybe_prefix(prefix, "token2wav"),
|
||||
# hf_config=self.token2wav_config,
|
||||
architectures=["MiMoAudioToken2WavModel"],
|
||||
)
|
||||
|
||||
self.model = self.token2wav
|
||||
else:
|
||||
raise ValueError("Invalid model stage")
|
||||
|
||||
# Set up intermediate tensors
|
||||
self.make_empty_intermediate_tensors = (
|
||||
(self.fused_thinker_talker.make_empty_intermediate_tensors)
|
||||
if self.model_stage == "fused_thinker_talker"
|
||||
else lambda: None
|
||||
)
|
||||
|
||||
def fused_thinker_talker_preprocess(self, input_ids: torch.Tensor, input_embeds: torch.Tensor, **info_dict: dict):
|
||||
# Mixed-mode support: In a single step, both Prefill*n and Decode*n are supported.
|
||||
|
||||
# Ensure we have base embeddings when only ids are provided
|
||||
if input_embeds is None and input_ids is not None:
|
||||
input_embeds = self.fused_thinker_talker.embed_input_ids(input_ids)
|
||||
|
||||
span_len = input_ids.shape[0]
|
||||
|
||||
if span_len > 1:
|
||||
# prefill
|
||||
return self.fused_thinker_talker_prefill(input_ids, input_embeds, **info_dict)
|
||||
else:
|
||||
# decode
|
||||
return input_ids, input_embeds, info_dict
|
||||
|
||||
def fused_thinker_talker_prefill(self, input_ids: torch.Tensor, input_embeds: torch.Tensor, **info_dict: dict):
|
||||
empty_token_id = self.fused_thinker_talker.empty_token_id
|
||||
|
||||
mm_kwargs = list[tuple[str, MultiModalKwargsItem]]()
|
||||
mm_features = info_dict.get("mm_features", [])
|
||||
mm_embeddings = []
|
||||
prompt_ids = torch.tensor(
|
||||
interleave_5_and_5_in_span(input_ids.tolist()),
|
||||
dtype=torch.int64,
|
||||
device=input_ids.device,
|
||||
)
|
||||
|
||||
for mm_feature in mm_features:
|
||||
mm_item = mm_feature.data
|
||||
|
||||
if mm_item is not None:
|
||||
mm_item["mm_offset"] = MultiModalFieldElem(
|
||||
data=mm_feature.mm_position.offset,
|
||||
field=MultiModalBatchedField(),
|
||||
)
|
||||
mm_kwargs.append((mm_feature.modality, mm_item))
|
||||
|
||||
for modality, num_items, mm_kwargs_group in group_mm_kwargs_by_modality(
|
||||
mm_kwargs,
|
||||
device=self.device,
|
||||
pin_memory=self.pin_memory,
|
||||
):
|
||||
# MiMoAudio is only supported audio modality
|
||||
mm_kwargs_group["prompt_ids"] = prompt_ids
|
||||
mm_kwargs_group["modality_preprocess"] = True
|
||||
mm_kwargs_group["mm_offset"] = torch.tensor(
|
||||
mm_kwargs_group["mm_offset"], dtype=torch.long, device=self.device
|
||||
)
|
||||
mm_embeddings = self.fused_thinker_talker.embed_multimodal(**mm_kwargs_group)
|
||||
|
||||
input_embeds = self.fused_thinker_talker.embed_input_ids(
|
||||
prompt_ids, multimodal_embeddings=mm_embeddings, is_multimodal=(prompt_ids == empty_token_id)
|
||||
)
|
||||
|
||||
return prompt_ids, input_embeds, info_dict
|
||||
|
||||
@staticmethod
|
||||
def _module_device(module: nn.Module) -> torch.device:
|
||||
try:
|
||||
return next(module.parameters()).device
|
||||
except StopIteration:
|
||||
# No parameters; fall back to buffers or cpu
|
||||
for _, buf in module.named_buffers(recurse=True):
|
||||
return buf.device
|
||||
return torch.device("cpu")
|
||||
|
||||
def move_submodules_to_devices(
|
||||
self,
|
||||
*,
|
||||
llm_device: str | torch.device | None = None,
|
||||
token2wav_device: str | torch.device | None = None,
|
||||
) -> None:
|
||||
"""Optionally move thinker/talker/token2wav to different devices.
|
||||
|
||||
Example:
|
||||
model.move_submodules_to_devices(
|
||||
thinker_device='cuda:0',
|
||||
talker_device='cuda:1',
|
||||
token2wav_device='cpu',
|
||||
)
|
||||
"""
|
||||
if llm_device is not None and self.fused_thinker_talker is not None:
|
||||
self.fused_thinker_talker.to(llm_device)
|
||||
if token2wav_device is not None and self.token2wav is not None:
|
||||
self.token2wav.to(token2wav_device)
|
||||
|
||||
@cached_property
|
||||
def sampler(self):
|
||||
if hasattr(self.model, "sampler"):
|
||||
return self.model.sampler
|
||||
return Sampler()
|
||||
|
||||
def embed_input_ids(
|
||||
self,
|
||||
input_ids: torch.Tensor,
|
||||
multimodal_embeddings=None,
|
||||
is_multimodal: bool = False,
|
||||
) -> torch.Tensor:
|
||||
if self.model_stage == "code2wav":
|
||||
return torch.zeros_like(input_ids).reshape(-1, 1).repeat(1, self.vllm_config.model_config.get_hidden_size())
|
||||
return self.model.embed_input_ids(input_ids, multimodal_embeddings, is_multimodal=is_multimodal)
|
||||
|
||||
def embed_multimodal(self, **kwargs):
|
||||
# Delegate to thinker model for multimodal processing
|
||||
return self.model.embed_multimodal(**kwargs)
|
||||
|
||||
def last_index_of(self, list, value):
|
||||
return len(list) - 1 - list[::-1].index(value)
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> None:
|
||||
"""Load weights for all components of the omni model."""
|
||||
loaded_weights = set()
|
||||
llm_weights = []
|
||||
token2wav_weights = []
|
||||
for k, v in weights:
|
||||
if (
|
||||
k.startswith("model.")
|
||||
or k.startswith("lm_head.")
|
||||
or k.startswith("input_local_transformer.")
|
||||
or k.startswith("hidden_states_downcast.")
|
||||
or k.startswith("local_transformer")
|
||||
or k.startswith("speech_embeddings")
|
||||
or k.startswith("speech_group_downcast")
|
||||
):
|
||||
if self.fused_thinker_talker:
|
||||
llm_weights.append((k, v))
|
||||
elif k.startswith("mel_transform."):
|
||||
if self.token2wav:
|
||||
token2wav_weights.append((k, v))
|
||||
else:
|
||||
pass
|
||||
|
||||
# Load fused_thinker_talker llm weights
|
||||
if self.fused_thinker_talker:
|
||||
if llm_weights:
|
||||
llm_loaded = self.fused_thinker_talker.load_weights(llm_weights)
|
||||
else:
|
||||
llm_loaded = set([k for k, v in llm_weights])
|
||||
# thinker_loaded = add_prefix_to_loaded_weights(thinker_loaded, "thinker")
|
||||
loaded_weights.update(llm_loaded)
|
||||
|
||||
## load code2wav
|
||||
if self.token2wav:
|
||||
token2wav_loaded = self.token2wav.load_weights(
|
||||
token2wav_weights,
|
||||
os.environ["MIMO_AUDIO_TOKENIZER_PATH"],
|
||||
)
|
||||
|
||||
loaded_weights.update(token2wav_loaded)
|
||||
|
||||
@staticmethod
|
||||
def insert_between(input_ids: torch.Tensor, group_size: int, value: int = -100):
|
||||
if group_size < 0:
|
||||
raise ValueError("group_size must be non-negative")
|
||||
|
||||
if not isinstance(input_ids, torch.Tensor):
|
||||
input_ids = torch.tensor(input_ids)
|
||||
if input_ids.dim() != 1:
|
||||
raise ValueError("input_ids must be 1-D tensor or list")
|
||||
|
||||
L = input_ids.numel()
|
||||
if group_size == 0 or L == 0:
|
||||
return input_ids.clone()
|
||||
|
||||
new_len = L * (group_size + 1)
|
||||
# Create output tensor filled with value, dtype & device consistent with input_ids
|
||||
out = input_ids.new_full((new_len,), value)
|
||||
|
||||
# Place original elements at the first position of each block: 0, group_size+1, 2*(group_size+1), ...
|
||||
positions = torch.arange(L, dtype=torch.long, device=input_ids.device) * (group_size + 1)
|
||||
out[positions] = input_ids
|
||||
|
||||
return out
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
intermediate_tensors: IntermediateTensors | None = None,
|
||||
inputs_embeds: torch.Tensor | None = None,
|
||||
generate_audio: bool = True,
|
||||
codec: torch.Tensor | None = None,
|
||||
sampling_metadata: SamplingMetadata | None = None,
|
||||
logits_index: int | None = None,
|
||||
sampler=None,
|
||||
additional_information: dict[str, object] | None = None,
|
||||
**kwargs: object,
|
||||
) -> torch.Tensor | IntermediateTensors | OmniOutput:
|
||||
"""
|
||||
Workflow:
|
||||
1) llm: multimodal understanding → text hidden states.
|
||||
2) If audio requested and codec not provided, use talker to derive codec.
|
||||
3) If audio requested (or codec provided), use token2wav to synthesize waveform.
|
||||
4) Return text hidden states (and audio when applicable).
|
||||
"""
|
||||
if self.model_stage == "fused_thinker_talker":
|
||||
next_speech_tokens, text_hidden_states = self.generate_codes(
|
||||
input_ids=input_ids,
|
||||
positions=positions,
|
||||
inputs_embeds=inputs_embeds,
|
||||
intermediate_tensors=intermediate_tensors,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
return OmniOutput(
|
||||
text_hidden_states=text_hidden_states.reshape(-1, text_hidden_states.shape[-1]),
|
||||
multimodal_outputs={"code_predictor_codes": next_speech_tokens},
|
||||
)
|
||||
|
||||
if self.model_stage == "code2wav":
|
||||
code = (
|
||||
input_ids # tensor [seq_len]
|
||||
if input_ids is not None
|
||||
else torch.zeros(
|
||||
inputs_embeds.shape[0],
|
||||
dtype=torch.long,
|
||||
device=inputs_embeds.device,
|
||||
)
|
||||
)
|
||||
|
||||
audio_tensor = self.generate_audio(code)
|
||||
return OmniOutput(
|
||||
text_hidden_states=None,
|
||||
multimodal_outputs={
|
||||
"model_outputs": audio_tensor.reshape(1, -1) if audio_tensor is not None else audio_tensor
|
||||
},
|
||||
)
|
||||
|
||||
def generate_codes(
|
||||
self,
|
||||
input_ids: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
inputs_embeds: torch.Tensor,
|
||||
intermediate_tensors: IntermediateTensors | None = None,
|
||||
**kwargs: object,
|
||||
):
|
||||
llm_dev = self._module_device(self.fused_thinker_talker)
|
||||
|
||||
# if input_ids is None, set it to a zero tensor, in the length of the
|
||||
# same as the embedding seq length
|
||||
if input_ids is None:
|
||||
input_ids = torch.zeros(inputs_embeds.shape[1], dtype=torch.long, device=llm_dev).unsqueeze(0) # (1, 0)
|
||||
|
||||
# 1) Thinker (ensure inputs on thinker's device)
|
||||
if input_ids is not None and input_ids.device != llm_dev:
|
||||
input_ids = input_ids.to(llm_dev)
|
||||
if positions is not None and positions.device != llm_dev:
|
||||
positions = positions.to(llm_dev)
|
||||
if inputs_embeds is not None and inputs_embeds.device != llm_dev:
|
||||
inputs_embeds = inputs_embeds.to(llm_dev)
|
||||
|
||||
# Run llm
|
||||
llm_output = self.fused_thinker_talker(
|
||||
input_ids=input_ids,
|
||||
positions=positions,
|
||||
intermediate_tensors=intermediate_tensors,
|
||||
inputs_embeds=inputs_embeds,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
next_speech_tokens = None
|
||||
if isinstance(llm_output, tuple):
|
||||
if len(llm_output) == 2:
|
||||
next_speech_tokens, text_hidden_states = llm_output
|
||||
elif len(llm_output) == 3:
|
||||
ids, next_speech_tokens, text_hidden_states = llm_output
|
||||
else:
|
||||
text_hidden_states = llm_output
|
||||
|
||||
return next_speech_tokens, text_hidden_states
|
||||
|
||||
def generate_audio(self, code: torch.Tensor):
|
||||
token2wav_dev = self._module_device(self.token2wav)
|
||||
# Check if in CUDA graph capture phase
|
||||
is_capturing = torch.cuda.is_current_stream_capturing()
|
||||
|
||||
if isinstance(code, torch.Tensor):
|
||||
if is_capturing:
|
||||
# During CUDA graph capture, avoid device movement operations
|
||||
# Assume tensor is already on the correct device, only convert dtype
|
||||
code_tensor = code.to(dtype=torch.long)
|
||||
else:
|
||||
# During non-capture phase, normally perform device movement and type conversion
|
||||
code_tensor = code.to(dtype=torch.long, device=token2wav_dev)
|
||||
else:
|
||||
# If code is not a Tensor, should avoid creating new tensors during capture
|
||||
# This case should be rare during capture, as code usually comes from input_ids
|
||||
if is_capturing:
|
||||
# During capture, if code is not a Tensor, try to use current stream device
|
||||
# But this case should theoretically not happen
|
||||
code_tensor = torch.as_tensor(code, dtype=torch.long)
|
||||
else:
|
||||
code_tensor = torch.as_tensor(code, dtype=torch.long, device=token2wav_dev)
|
||||
if code_tensor.ndim == 2 and code_tensor.shape[0] == 1:
|
||||
code_tensor = code_tensor.squeeze(0)
|
||||
|
||||
with torch.inference_mode():
|
||||
audio_tensor = self.token2wav(codes=code_tensor) # code_tensor tensor [seq_len]
|
||||
|
||||
return audio_tensor
|
||||
|
||||
def compute_logits(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
sampling_metadata: SamplingMetadata | None = None,
|
||||
) -> torch.Tensor | None:
|
||||
# logits = self.logits_processor(self.lm_head, hidden_states,
|
||||
# sampling_metadata)
|
||||
# Handle OmniOutput type
|
||||
if isinstance(hidden_states, OmniOutput):
|
||||
hidden_states = hidden_states.text_hidden_states
|
||||
|
||||
# Use thinker model for logits computation
|
||||
return self.model.compute_logits(hidden_states)
|
||||
@@ -0,0 +1,647 @@
|
||||
# Copyright 2025 Xiaomi Corporation.
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from collections.abc import Iterable
|
||||
from dataclasses import dataclass
|
||||
|
||||
import torch
|
||||
import torchaudio
|
||||
from torch import nn
|
||||
from torchaudio.transforms import MelSpectrogram
|
||||
from transformers import AutoTokenizer, Qwen2Config
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.model_executor.layers.logits_processor import LogitsProcessor
|
||||
from vllm.model_executor.models import SupportsPP
|
||||
from vllm.sequence import IntermediateTensors
|
||||
from vllm.v1.outputs import SamplerOutput
|
||||
from vllm.v1.sample.metadata import SamplingMetadata
|
||||
from vllm.v1.sample.sampler import Sampler
|
||||
|
||||
from vllm_omni.model_executor.models.mimo_audio.config_mimo_audio import TALKER_CODEC_PAD_TOKEN_ID, MiMoAudioConfig
|
||||
from vllm_omni.model_executor.models.mimo_audio.modeling_audio_tokenizer import MiMoAudioTokenizer
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
DUMMY_CODE_SHAPE = 36
|
||||
|
||||
|
||||
class MiMoAudioTokenizerWorker:
|
||||
def __init__(
|
||||
self,
|
||||
device_str: str,
|
||||
config_path: str,
|
||||
audio_tokenizer_path: str,
|
||||
):
|
||||
self.device = device_str
|
||||
logger.info("[tokenizer worker] Loading MiMoAudioConfig from %s", config_path)
|
||||
load_cfg_start = time.monotonic()
|
||||
self.config: MiMoAudioConfig = MiMoAudioConfig.from_pretrained(config_path)
|
||||
logger.info(
|
||||
"[tokenizer worker] Config loaded in %.2fs",
|
||||
time.monotonic() - load_cfg_start,
|
||||
)
|
||||
|
||||
if device_str == "cpu":
|
||||
model_dtype = torch.float32 # CPU must use float32
|
||||
else:
|
||||
model_dtype = torch.bfloat16 # GPU uses bfloat16
|
||||
|
||||
logger.info(
|
||||
"[tokenizer worker] Loading MiMo-Audio Tokenizer from %s (device=%s, dtype=%s)",
|
||||
audio_tokenizer_path,
|
||||
self.device,
|
||||
model_dtype,
|
||||
)
|
||||
start_loading_slm_tokenizer_time = time.monotonic()
|
||||
logger.info(f"MiMoAudioTokenizer,device:{self.device}")
|
||||
self.audio_tokenizer = MiMoAudioTokenizer.from_pretrained(
|
||||
audio_tokenizer_path,
|
||||
dtype=model_dtype,
|
||||
device_map={"": self.device},
|
||||
)
|
||||
# Move to target device and only cast to bfloat16 on non-CPU devices.
|
||||
self.audio_tokenizer.to(self.device)
|
||||
if self.device != "cpu" and model_dtype == torch.bfloat16:
|
||||
self.audio_tokenizer.to(dtype=torch.bfloat16)
|
||||
self.audio_tokenizer.eval()
|
||||
|
||||
logger.info(
|
||||
f"Audio Tokenizers loaded in "
|
||||
f"{time.monotonic() - start_loading_slm_tokenizer_time:.2f} seconds, "
|
||||
f"device: {self.device}"
|
||||
)
|
||||
|
||||
logger.info(
|
||||
"[tokenizer worker] Building MelSpectrogram transform (sr=%s, n_fft=%s)",
|
||||
self.audio_tokenizer.config.sampling_rate,
|
||||
self.audio_tokenizer.config.nfft,
|
||||
)
|
||||
mel_start = time.monotonic()
|
||||
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,
|
||||
win_length=self.audio_tokenizer.config.window_size,
|
||||
f_min=self.audio_tokenizer.config.fmin,
|
||||
f_max=self.audio_tokenizer.config.fmax,
|
||||
n_mels=self.audio_tokenizer.config.n_mels,
|
||||
power=1.0,
|
||||
center=True,
|
||||
)
|
||||
.to(self.device)
|
||||
.to(torch.float32)
|
||||
)
|
||||
logger.info(
|
||||
"[tokenizer worker] MelSpectrogram ready in %.2fs",
|
||||
time.monotonic() - mel_start,
|
||||
)
|
||||
|
||||
self.group_size = self.config.group_size
|
||||
self.audio_channels = self.config.audio_channels
|
||||
self.sample_rate = self.audio_tokenizer.config.sampling_rate
|
||||
|
||||
# Warmup (skip for CPU due to potential shape mismatch issues)
|
||||
if device_str != "cpu":
|
||||
logger.info("[tokenizer worker] Running warmup encode/decode...")
|
||||
warmup_start = time.monotonic()
|
||||
warmup_dtype = torch.float32 if device_str == "cpu" else torch.bfloat16
|
||||
try:
|
||||
self.encode_wav_base(torch.zeros(self.sample_rate, dtype=warmup_dtype))
|
||||
self.decode(torch.zeros(self.audio_channels, self.group_size, dtype=torch.long))
|
||||
logger.info(
|
||||
"[tokenizer worker] Warmup finished in %.2fs",
|
||||
time.monotonic() - warmup_start,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning("[tokenizer worker] Warmup failed (non-critical): %s", str(e))
|
||||
else:
|
||||
logger.info("[tokenizer worker] Skipping warmup for CPU device")
|
||||
|
||||
def resample_audio_if_needed(self, wav_tensor: torch.Tensor, original_sr: int):
|
||||
"""Resample audio if sample rate doesn't match config"""
|
||||
target_sr = self.sample_rate
|
||||
if original_sr != target_sr:
|
||||
wav_tensor = torchaudio.functional.resample(wav_tensor, original_sr, target_sr)
|
||||
return wav_tensor
|
||||
|
||||
def wav2mel(self, wav: torch.Tensor):
|
||||
"""Convert waveform to mel spectrogram using consistent processing"""
|
||||
wav = wav.to(torch.float32)
|
||||
spec = self.mel_transform(wav[None, :])
|
||||
return torch.log(torch.clip(spec, min=1e-7)).squeeze()
|
||||
|
||||
def group_by_length(self, features: torch.Tensor, lengths: torch.Tensor, max_length: int):
|
||||
if features.size(0) != lengths.sum().item():
|
||||
raise ValueError(f"Feature size mismatch: {features.size(0)} vs {lengths.sum().item()}")
|
||||
|
||||
split_points = []
|
||||
current_sum = 0
|
||||
|
||||
for i, seq_len in enumerate(lengths):
|
||||
if current_sum + seq_len > max_length and current_sum > 0:
|
||||
split_points.append(i)
|
||||
current_sum = seq_len.item()
|
||||
else:
|
||||
current_sum += seq_len.item()
|
||||
|
||||
# Convert split points to group sizes
|
||||
group_sizes = []
|
||||
prev = 0
|
||||
for point in split_points:
|
||||
group_sizes.append(point - prev)
|
||||
prev = point
|
||||
if prev < len(lengths):
|
||||
group_sizes.append(len(lengths) - prev)
|
||||
|
||||
len_groups = torch.split(lengths, group_sizes)
|
||||
feature_sizes = [group.sum().item() for group in len_groups]
|
||||
feature_groups = torch.split(features, feature_sizes)
|
||||
|
||||
return feature_groups, len_groups
|
||||
|
||||
@torch.inference_mode()
|
||||
def encode_batch_base(
|
||||
self,
|
||||
feature_groups: list[torch.Tensor],
|
||||
len_groups: list[torch.Tensor],
|
||||
) -> torch.Tensor:
|
||||
"""Run this in cuda stream if available"""
|
||||
encoded_parts = []
|
||||
for features, lengths in zip(feature_groups, len_groups):
|
||||
codes, _ = self.audio_tokenizer.encoder.encode(
|
||||
input_features=features.to(self.device),
|
||||
input_lens=lengths.to(self.device),
|
||||
return_codes_only=True,
|
||||
)
|
||||
encoded_parts.append(codes)
|
||||
codes_packed = torch.cat(encoded_parts, dim=1)
|
||||
|
||||
codes = codes_packed.transpose(0, 1).detach()
|
||||
audio_codes = codes[:, : self.audio_channels]
|
||||
|
||||
# Pad the sequence to be a multiple of group_size by repeating the last frame
|
||||
T = audio_codes.shape[0]
|
||||
if T % self.group_size != 0:
|
||||
pad = self.group_size - (T % self.group_size)
|
||||
last_tokens = audio_codes[-1, :] # Keep dim for repeat
|
||||
padding_tokens = last_tokens.expand(pad, -1)
|
||||
audio_codes = torch.cat([audio_codes, padding_tokens], dim=0)
|
||||
|
||||
audio_codes = audio_codes.transpose(0, 1).cpu()
|
||||
|
||||
return audio_codes # [audio_channels, T] cpu
|
||||
|
||||
@torch.inference_mode()
|
||||
def encode(self, audio: tuple[torch.Tensor, int], max_length: float | None = 256000) -> torch.Tensor:
|
||||
"""wav: [samples] cpu, sample_rate = 24000"""
|
||||
wav, original_sr = audio
|
||||
wav = self.resample_audio_if_needed(wav, original_sr)
|
||||
wav = wav.to(self.device)
|
||||
|
||||
mel = self.wav2mel(wav).transpose(0, 1) # (seq_len, n_mels)
|
||||
input_len = mel.size(0)
|
||||
input_features = mel
|
||||
segment_size = 6000
|
||||
input_len_seg = [segment_size] * (input_len // segment_size)
|
||||
|
||||
if input_len % segment_size > 0:
|
||||
input_len_seg.append(input_len % segment_size)
|
||||
|
||||
input_lens = torch.tensor(input_len_seg, device=self.device)
|
||||
|
||||
feature_groups, len_groups = self.group_by_length(input_features, input_lens, max_length)
|
||||
|
||||
audio_codes = self.encode_batch_base(feature_groups, len_groups)
|
||||
return audio_codes # [audio_channels, T] cpu
|
||||
|
||||
@torch.inference_mode()
|
||||
def encode_wav_base(
|
||||
self,
|
||||
wav: torch.Tensor, # [samples] cpu
|
||||
) -> torch.Tensor:
|
||||
"""Run this in cuda stream if available"""
|
||||
wav = wav.to(self.device)
|
||||
|
||||
mel = self.wav2mel(wav).transpose(0, 1) # (seq_len, n_mels)
|
||||
input_features = mel # [seq_len, n_mels]
|
||||
input_lens = torch.tensor([mel.shape[0]], device=self.device)
|
||||
codes_packed, _ = self.audio_tokenizer.encoder.encode(
|
||||
input_features=input_features,
|
||||
input_lens=input_lens,
|
||||
return_codes_only=True,
|
||||
)
|
||||
codes = codes_packed.transpose(0, 1).detach()
|
||||
audio_codes = codes[:, : self.audio_channels]
|
||||
|
||||
# Pad the sequence to be a multiple of group_size by repeating the last frame
|
||||
T = audio_codes.shape[0]
|
||||
if T % self.group_size != 0:
|
||||
pad = self.group_size - (T % self.group_size)
|
||||
last_tokens = audio_codes[-1, :] # Keep dim for repeat
|
||||
padding_tokens = last_tokens.expand(pad, -1)
|
||||
audio_codes = torch.cat([audio_codes, padding_tokens], dim=0)
|
||||
|
||||
audio_codes = audio_codes.transpose(0, 1).cpu()
|
||||
|
||||
return audio_codes # [audio_channels, T] cpu
|
||||
|
||||
@torch.inference_mode()
|
||||
def decode(
|
||||
self,
|
||||
tokens: torch.Tensor, # [audio_channels, T] cpu
|
||||
) -> torch.Tensor:
|
||||
"""Decode audio tokens to waveform using the tokenizer's decoder"""
|
||||
tokens = tokens.to(self.device)
|
||||
with torch.no_grad():
|
||||
decoded_audio: torch.Tensor = self.audio_tokenizer.decode(tokens)
|
||||
decoded_audio = decoded_audio.float().reshape(-1).detach().cpu()
|
||||
return decoded_audio # [samples] cpu
|
||||
|
||||
|
||||
@dataclass
|
||||
class AudioStreamerConfig:
|
||||
group_size: int
|
||||
audio_channels: int
|
||||
|
||||
|
||||
@dataclass
|
||||
class MiMoAudioCodes:
|
||||
sosp: int
|
||||
eosp: int
|
||||
sostm: int
|
||||
eostm: int
|
||||
im_end: int
|
||||
pad: int
|
||||
eot: int
|
||||
empty: int
|
||||
|
||||
@classmethod
|
||||
def from_tokenizer(cls, tokenizer: AutoTokenizer) -> "MiMoAudioCodes":
|
||||
def idx(token: str) -> int:
|
||||
token_id = tokenizer.convert_tokens_to_ids(token)
|
||||
if not isinstance(token_id, int):
|
||||
raise ValueError(f"Token {token} is not mapped to a single id.")
|
||||
return token_id
|
||||
|
||||
return cls(
|
||||
sosp=idx("<|sosp|>"),
|
||||
eosp=idx("<|eosp|>"),
|
||||
sostm=idx("<|sostm|>"),
|
||||
eostm=idx("<|eostm|>"),
|
||||
im_end=idx("<|im_end|>"),
|
||||
pad=idx("<|endoftext|>"),
|
||||
eot=idx("<|eot|>"),
|
||||
empty=idx("<|empty|>"),
|
||||
)
|
||||
|
||||
|
||||
def extract_audio_code_tensor(
|
||||
flat_codes: torch.Tensor,
|
||||
group_size: int,
|
||||
audio_channels: int,
|
||||
codes: MiMoAudioCodes,
|
||||
) -> torch.Tensor | None:
|
||||
"""Convert flattened talker output into [audio_channels, T] codes."""
|
||||
if flat_codes.numel() == 0:
|
||||
return None
|
||||
|
||||
group_width = group_size * (audio_channels + 1)
|
||||
usable = (flat_codes.numel() // group_width) * group_width
|
||||
if usable == 0:
|
||||
return None
|
||||
|
||||
groups = flat_codes[:usable].view(-1, group_size, audio_channels + 1)
|
||||
audio_buffer: list[torch.Tensor] = []
|
||||
|
||||
for group in groups:
|
||||
text_token = int(group[0, 0].item())
|
||||
if text_token == codes.empty:
|
||||
audio_buffer.append(group[:, 1:])
|
||||
elif text_token == codes.eostm:
|
||||
break
|
||||
|
||||
if not audio_buffer:
|
||||
return None
|
||||
|
||||
audio_tokens = torch.cat(audio_buffer, dim=0).transpose(0, 1).contiguous()
|
||||
return audio_tokens # [audio_channels, T]
|
||||
|
||||
|
||||
def _normalize_tokenizer_worker_cache_key(
|
||||
device: torch.device,
|
||||
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]
|
||||
# Use realpath so symlinks / trailing slash don't create duplicate entries
|
||||
ap = audio_tokenizer_path or ""
|
||||
if ap and os.path.exists(ap):
|
||||
ap = os.path.realpath(ap)
|
||||
cp = config_path or ""
|
||||
if cp and os.path.exists(cp):
|
||||
cp = os.path.realpath(cp)
|
||||
|
||||
if not cp and ap:
|
||||
cp = os.path.dirname(ap)
|
||||
return (device_type, cp, ap)
|
||||
|
||||
|
||||
_TOKENIZER_WORKER_CACHE: dict[tuple[str, str, str], MiMoAudioTokenizerWorker] = {}
|
||||
|
||||
|
||||
def get_tokenizer_worker(
|
||||
device: torch.device,
|
||||
config_path: str,
|
||||
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,
|
||||
config_path=config_path,
|
||||
audio_tokenizer_path=audio_tokenizer_path,
|
||||
)
|
||||
logger.info(
|
||||
"[tokenizer cache worker] cache size=%s pid=%s",
|
||||
len(_TOKENIZER_WORKER_CACHE),
|
||||
os.getpid(),
|
||||
)
|
||||
return _TOKENIZER_WORKER_CACHE[key]
|
||||
|
||||
|
||||
class MiMoAudioToken2WavForConditionalGenerationVLLM(nn.Module, SupportsPP):
|
||||
"""Decode MiMo audio codes to waveform for the code2wav stage."""
|
||||
|
||||
def __init__(self, vllm_config: VllmConfig, prefix: str = ""):
|
||||
super().__init__()
|
||||
|
||||
config = vllm_config.model_config.hf_config
|
||||
config = MiMoAudioConfig(**vars(config)) if isinstance(config, Qwen2Config) else config
|
||||
self.config = config
|
||||
self.vllm_config = vllm_config
|
||||
self.quant_config = vllm_config.quant_config
|
||||
self.lora_config = vllm_config.lora_config
|
||||
|
||||
self.logits_processor = LogitsProcessor(config.vocab_size)
|
||||
|
||||
device_str = "cuda" if torch.cuda.is_available() else "cpu"
|
||||
self.device = torch.device(device_str)
|
||||
self.sample_rate = getattr(config, "audio_sample_rate", 24000)
|
||||
|
||||
self.tokenizer = AutoTokenizer.from_pretrained(self.config.name_or_path, trust_remote_code=True)
|
||||
self.codes = MiMoAudioCodes.from_tokenizer(self.tokenizer)
|
||||
self.streamer_config = AudioStreamerConfig(
|
||||
group_size=self.config.group_size,
|
||||
audio_channels=self.config.audio_channels,
|
||||
)
|
||||
|
||||
self.audio_tokenizer_path = getattr(vllm_config.model_config, "audio_tokenizer_path", None) or os.environ.get(
|
||||
"MIMO_AUDIO_TOKENIZER_PATH"
|
||||
)
|
||||
if not self.audio_tokenizer_path:
|
||||
raise ValueError(
|
||||
"Audio tokenizer path is not set. Provide "
|
||||
"`model_config.audio_tokenizer_path` in the stage config "
|
||||
"or export MIMO_AUDIO_TOKENIZER_PATH."
|
||||
)
|
||||
|
||||
self.tokenizer_config_path = (
|
||||
getattr(vllm_config.model_config, "audio_tokenizer_config_path", None)
|
||||
or os.environ.get("MIMO_AUDIO_TOKENIZER_PATH")
|
||||
or self.config.name_or_path
|
||||
)
|
||||
|
||||
self._tokenizer_service: MiMoAudioTokenizerWorker | None = get_tokenizer_worker(
|
||||
device=self.device,
|
||||
config_path=self.tokenizer_config_path,
|
||||
audio_tokenizer_path=self.audio_tokenizer_path,
|
||||
)
|
||||
# samples per codec frame for streaming context strip (same as tokenizer frames_per_token)
|
||||
audio_tokenizer_config = self._tokenizer_service.audio_tokenizer.config
|
||||
self.total_upsample = (
|
||||
getattr(audio_tokenizer_config, "avg_pooler", 2)
|
||||
* getattr(audio_tokenizer_config, "stride_size", 2)
|
||||
* getattr(audio_tokenizer_config, "hop_length", 240)
|
||||
) * self.config.group_size
|
||||
|
||||
def load_weights(
|
||||
self,
|
||||
weights: Iterable[tuple[str, torch.Tensor]],
|
||||
audio__dict_path: str | None = None,
|
||||
**kwargs,
|
||||
) -> set[str]:
|
||||
# Decoder has no trainable weights to load in this stage.
|
||||
return set()
|
||||
|
||||
def chunked_decode_streaming(
|
||||
self,
|
||||
codes: torch.Tensor,
|
||||
chunk_size: int = 10,
|
||||
left_context_size: int = 10,
|
||||
) -> torch.Tensor:
|
||||
"""
|
||||
Decode one chunk of codes and return waveform with left context removed.
|
||||
|
||||
Used when async_chunk is True: each chunk is decoded and we strip
|
||||
context_size * total_upsample samples from the start (left context).
|
||||
"""
|
||||
wav_chunk = self._decode_waveform_from_codes(codes)
|
||||
if wav_chunk.numel() == 0:
|
||||
return wav_chunk
|
||||
# Infer number of codec frames: flat format has 36 elements per frame (9*4 with prepend)
|
||||
num_flat = codes.numel() if codes.ndim == 1 else codes.shape[-1]
|
||||
num_chunks = num_flat // 36
|
||||
if num_chunks <= chunk_size:
|
||||
context_size = 0
|
||||
else:
|
||||
context_size = left_context_size
|
||||
drop = context_size * self.total_upsample
|
||||
if drop >= wav_chunk.numel():
|
||||
return wav_chunk[:0].clone()
|
||||
return wav_chunk[drop:].contiguous()
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.Tensor | None = None,
|
||||
codes: torch.Tensor | None = None,
|
||||
**kwargs,
|
||||
) -> torch.Tensor | IntermediateTensors:
|
||||
# Support both input_ids (from vLLM) and codes (from mimo_audio.py)
|
||||
code_tensor = codes if codes is not None else input_ids
|
||||
|
||||
if code_tensor is None:
|
||||
raise ValueError("Either input_ids or codes must be provided")
|
||||
|
||||
if code_tensor.numel() == 0:
|
||||
raise ValueError("code_tensor is empty.")
|
||||
|
||||
if getattr(self.vllm_config.model_config, "async_chunk", False):
|
||||
waveform = self.chunked_decode_streaming(code_tensor, chunk_size=10, left_context_size=10)
|
||||
else:
|
||||
waveform = self._decode_waveform_from_codes(code_tensor)
|
||||
|
||||
# For warmup/dummy run: if waveform is empty, return dummy hidden_states
|
||||
# _dummy_run expects a tensor that can be processed by extract_multimodal_outputs
|
||||
if waveform.numel() == 0:
|
||||
# Return dummy hidden_states with shape [seq_len, hidden_size]
|
||||
# This is needed for warmup to avoid NoneType errors
|
||||
hidden_size = getattr(self.config, "hidden_size", None)
|
||||
if hidden_size is None:
|
||||
# Fallback: try to get from vllm_config.model_config
|
||||
hidden_size = getattr(
|
||||
self.vllm_config.model_config,
|
||||
"hidden_size",
|
||||
4096, # Default fallback
|
||||
)
|
||||
|
||||
# Return [seq_len=1, hidden_size] tensor for warmup
|
||||
dummy_hidden = torch.zeros(
|
||||
(1, hidden_size),
|
||||
dtype=torch.bfloat16,
|
||||
device=self.device,
|
||||
)
|
||||
|
||||
return dummy_hidden
|
||||
|
||||
if waveform.numel() == 1 and waveform.item() == 0:
|
||||
# Designed for Text output only
|
||||
return None
|
||||
|
||||
return waveform
|
||||
|
||||
def _get_full_code_sequence(
|
||||
self,
|
||||
code_tensor: torch.Tensor | None,
|
||||
kwargs: dict,
|
||||
) -> torch.Tensor | None:
|
||||
"""Gather the full prompt token ids (code sequence) if available."""
|
||||
if code_tensor is not None and code_tensor.numel() > 1:
|
||||
return code_tensor
|
||||
|
||||
sampling_metadata = kwargs.get("sampling_metadata")
|
||||
prompt_token_ids = getattr(sampling_metadata, "prompt_token_ids", None) if sampling_metadata else None
|
||||
|
||||
if prompt_token_ids is None:
|
||||
return code_tensor
|
||||
|
||||
if isinstance(prompt_token_ids, torch.Tensor):
|
||||
return prompt_token_ids.detach().to(torch.long).view(-1)
|
||||
|
||||
if isinstance(prompt_token_ids, list):
|
||||
if len(prompt_token_ids) == 0:
|
||||
return code_tensor
|
||||
if isinstance(prompt_token_ids[0], list):
|
||||
flat = prompt_token_ids[0]
|
||||
else:
|
||||
flat = prompt_token_ids
|
||||
if len(flat) == 0:
|
||||
return code_tensor
|
||||
return torch.tensor(flat, dtype=torch.long)
|
||||
|
||||
return code_tensor
|
||||
|
||||
def _check_dummy_code_tensor(self, code_tensor: torch.Tensor) -> bool:
|
||||
if code_tensor is not None and code_tensor.numel() == DUMMY_CODE_SHAPE:
|
||||
code_groups = code_tensor.view(self.config.group_size, self.config.audio_channels + 1)
|
||||
return (
|
||||
(code_groups[:, 0] == TALKER_CODEC_PAD_TOKEN_ID).all() and (code_groups[:, 1:].sum() == 0).all()
|
||||
).item()
|
||||
return False
|
||||
|
||||
def _decode_waveform_from_codes(self, code_tensor: torch.Tensor) -> torch.Tensor:
|
||||
# Check if in CUDA graph capture phase
|
||||
is_capturing = torch.cuda.is_current_stream_capturing()
|
||||
|
||||
# During CUDA graph capture, return dummy tensor to avoid operations like .cpu() which are not allowed
|
||||
if is_capturing:
|
||||
# Return an empty dummy tensor with shape and dtype consistent with normal output
|
||||
return torch.zeros(0, dtype=torch.float32, device=self.device)
|
||||
|
||||
if code_tensor is None or code_tensor.numel() == 0:
|
||||
return torch.zeros(0, dtype=torch.float32, device=self.device)
|
||||
|
||||
if self._check_dummy_code_tensor(code_tensor):
|
||||
return torch.zeros(1, dtype=torch.float32, device=self.device)
|
||||
|
||||
if code_tensor.ndim > 1:
|
||||
if code_tensor.shape[0] == 1:
|
||||
code_tensor = code_tensor.squeeze(0)
|
||||
|
||||
elif code_tensor.shape[0] == self.streamer_config.audio_channels + 1:
|
||||
code_tensor = code_tensor.transpose(0, 1).contiguous().view(-1)
|
||||
|
||||
else:
|
||||
raise ValueError(
|
||||
f"code2wav expects shape [L], [1, L] or [audio_channels+1, T], got {code_tensor.shape}"
|
||||
)
|
||||
|
||||
flat_codes = code_tensor.detach().to(torch.long).cpu()
|
||||
|
||||
audio_codes = extract_audio_code_tensor(
|
||||
flat_codes,
|
||||
self.streamer_config.group_size,
|
||||
self.streamer_config.audio_channels,
|
||||
self.codes,
|
||||
)
|
||||
|
||||
if audio_codes is None or audio_codes.numel() == 0:
|
||||
return torch.zeros(0, dtype=torch.float32, device=self.device)
|
||||
|
||||
decoded_audio = self._tokenizer_service.decode(audio_codes)
|
||||
|
||||
result = decoded_audio.to(self.device)
|
||||
|
||||
return result
|
||||
|
||||
def embed_input_ids(
|
||||
self,
|
||||
input_ids: torch.Tensor,
|
||||
multimodal_embeddings=None,
|
||||
is_multimodal: bool = False,
|
||||
) -> torch.Tensor:
|
||||
return torch.zeros_like(input_ids).reshape(-1, 1).repeat(1, self.vllm_config.model_config.get_hidden_size())
|
||||
|
||||
def compute_logits(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
) -> torch.Tensor | None:
|
||||
# code2wav stage does not need actual logits, but needs to return a valid tensor
|
||||
# Return a dummy logits tensor with shape [batch_size, vocab_size]
|
||||
if hidden_states.numel() == 0:
|
||||
return None
|
||||
|
||||
batch_size = hidden_states.shape[0] if hidden_states.ndim > 0 else 1
|
||||
vocab_size = self.config.vocab_size
|
||||
|
||||
# Create an all-zero logits tensor (sampler will choose the first token, usually pad token)
|
||||
# This is safe for the code2wav stage as we do not rely on sampling results
|
||||
dummy_logits = torch.zeros(
|
||||
(batch_size, vocab_size),
|
||||
dtype=hidden_states.dtype,
|
||||
device=self.device,
|
||||
)
|
||||
return dummy_logits
|
||||
|
||||
def sample(
|
||||
self,
|
||||
logits: torch.Tensor,
|
||||
sampling_metadata: SamplingMetadata,
|
||||
) -> SamplerOutput | None:
|
||||
# code2wav stage does not need sampling, but needs to return a valid SamplerOutput to avoid CUDA errors
|
||||
# Use Sampler to handle sampling, even though the result will not be used
|
||||
if logits is None or logits.numel() == 0:
|
||||
return None
|
||||
|
||||
# Use Sampler for sampling (although the result will not be used)
|
||||
# This ensures the sampling process can complete normally and avoids CUDA errors
|
||||
sampler = Sampler()
|
||||
sampler_output = sampler(
|
||||
logits=logits,
|
||||
sampling_metadata=sampling_metadata,
|
||||
)
|
||||
return sampler_output
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,824 @@
|
||||
# Copyright 2025 Xiaomi Corporation.
|
||||
import math
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.nn import functional as F
|
||||
from transformers.activations import ACT2FN
|
||||
from transformers.modeling_utils import PreTrainedModel
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from .config_mimo_audio import MiMoAudioTokenizerConfig
|
||||
from .modeling_rope_utils import ROPE_INIT_FUNCTIONS, apply_rotary_pos_emb, dynamic_rope_update
|
||||
from .quantization import ResidualVectorQuantizer
|
||||
|
||||
logger = init_logger(__name__)
|
||||
is_flash_atth_available = False
|
||||
try:
|
||||
from flash_attn import flash_attn_varlen_func
|
||||
|
||||
is_flash_atth_available = True
|
||||
except Exception:
|
||||
logger.warning("flash_attn not installed")
|
||||
|
||||
|
||||
def get_sequence_mask(inputs, inputs_length):
|
||||
if inputs.dim() == 3:
|
||||
bsz, tgt_len, _ = inputs.size()
|
||||
else:
|
||||
bsz, tgt_len = inputs_length.shape[0], torch.max(inputs_length)
|
||||
sequence_mask = torch.arange(0, tgt_len).to(inputs.device)
|
||||
sequence_mask = torch.lt(sequence_mask, inputs_length.reshape(bsz, 1)).view(bsz, tgt_len, 1)
|
||||
unpacking_index = torch.cumsum(sequence_mask.to(torch.int64).view(-1), dim=0) - 1
|
||||
return sequence_mask, unpacking_index
|
||||
|
||||
|
||||
def unpack_hidden_states(hidden_states, lengths, sequence_mask=None, unpacking_index=None):
|
||||
bsz = lengths.shape[0]
|
||||
if sequence_mask is None or unpacking_index is None:
|
||||
sequence_mask, unpacking_index = get_sequence_mask(hidden_states, lengths)
|
||||
hidden_states = torch.index_select(hidden_states, 0, unpacking_index).view(
|
||||
bsz, torch.max(lengths), hidden_states.shape[-1]
|
||||
)
|
||||
hidden_states = torch.where(sequence_mask, hidden_states, 0)
|
||||
return hidden_states
|
||||
|
||||
|
||||
def get_position_ids(lengths):
|
||||
total_len = lengths.sum()
|
||||
offset = torch.cat([torch.zeros(1).to(lengths), lengths[:-1].cumsum(dim=0)])
|
||||
offset = torch.repeat_interleave(offset, lengths)
|
||||
position_ids = torch.arange(0, total_len).to(offset) - offset
|
||||
return position_ids
|
||||
|
||||
|
||||
@dataclass
|
||||
class StreamingConfig:
|
||||
seg_point: int = field(default=60 * 25)
|
||||
process_seg_point: bool = field(default=True)
|
||||
left_overlap: int = field(default=10 * 25)
|
||||
right_overlap: int = field(default=40)
|
||||
seg_point_left_overlap: int = field(default=0)
|
||||
|
||||
|
||||
@dataclass
|
||||
class StreamingCache:
|
||||
hidden_states: list[torch.Tensor] = field(default=None)
|
||||
processed_lengths: list[int] = field(default=None)
|
||||
|
||||
|
||||
class ISTFT(nn.Module):
|
||||
"""
|
||||
Custom implementation of ISTFT since torch.istft doesn't allow custom padding (other than `center=True`) with
|
||||
windowing. This is because the NOLA (Nonzero Overlap Add) check fails at the edges.
|
||||
See issue: https://github.com/pytorch/pytorch/issues/62323
|
||||
Specifically, in the context of neural vocoding we are interested in "same" padding analogous to CNNs.
|
||||
The NOLA constraint is met as we trim padded samples anyway.
|
||||
|
||||
Args:
|
||||
n_fft (int): Size of Fourier transform.
|
||||
hop_length (int): The distance between neighboring sliding window frames.
|
||||
win_length (int): The size of window frame and STFT filter.
|
||||
padding (str, optional): Type of padding. Options are "center" or "same". Defaults to "same".
|
||||
"""
|
||||
|
||||
def __init__(self, n_fft: int, hop_length: int, win_length: int, padding: str = "same"):
|
||||
super().__init__()
|
||||
if padding not in ["center", "same"]:
|
||||
raise ValueError("Padding must be 'center' or 'same'.")
|
||||
self.padding = padding
|
||||
self.n_fft = n_fft
|
||||
self.hop_length = hop_length
|
||||
self.win_length = win_length
|
||||
window = torch.hann_window(win_length)
|
||||
self.register_buffer("window", window)
|
||||
|
||||
def forward(self, spec: torch.Tensor) -> torch.Tensor:
|
||||
"""
|
||||
Compute the Inverse Short Time Fourier Transform (ISTFT) of a complex spectrogram.
|
||||
|
||||
Args:
|
||||
spec (Tensor): Input complex spectrogram of shape (B, N, T), where B is the batch size,
|
||||
N is the number of frequency bins, and T is the number of time frames.
|
||||
|
||||
Returns:
|
||||
Tensor: Reconstructed time-domain signal of shape (B, L), where L is the length of the output signal.
|
||||
"""
|
||||
if self.padding == "center":
|
||||
# Fallback to pytorch native implementation
|
||||
return torch.istft(
|
||||
spec,
|
||||
self.n_fft,
|
||||
self.hop_length,
|
||||
self.win_length,
|
||||
self.window,
|
||||
center=True,
|
||||
)
|
||||
elif self.padding == "same":
|
||||
pad = (self.win_length - self.hop_length) // 2
|
||||
else:
|
||||
raise ValueError("Padding must be 'center' or 'same'.")
|
||||
|
||||
assert spec.dim() == 3, "Expected a 3D tensor as input"
|
||||
B, N, T = spec.shape
|
||||
|
||||
# Inverse FFT
|
||||
ifft = torch.fft.irfft(spec, self.n_fft, dim=1, norm="backward")
|
||||
ifft = ifft * self.window[None, :, None]
|
||||
|
||||
# Overlap and Add
|
||||
output_size = (T - 1) * self.hop_length + self.win_length
|
||||
y = torch.nn.functional.fold(
|
||||
ifft,
|
||||
output_size=(1, output_size),
|
||||
kernel_size=(1, self.win_length),
|
||||
stride=(1, self.hop_length),
|
||||
)[:, 0, 0, pad:-pad]
|
||||
|
||||
# Window envelope
|
||||
window_sq = self.window.square().expand(1, T, -1).transpose(1, 2)
|
||||
window_envelope = torch.nn.functional.fold(
|
||||
window_sq,
|
||||
output_size=(1, output_size),
|
||||
kernel_size=(1, self.win_length),
|
||||
stride=(1, self.hop_length),
|
||||
).squeeze()[pad:-pad]
|
||||
|
||||
# Normalize
|
||||
assert (window_envelope > 1e-11).all()
|
||||
y = y / window_envelope
|
||||
|
||||
return y
|
||||
|
||||
|
||||
class ISTFTHead(nn.Module):
|
||||
"""
|
||||
ISTFT Head module for predicting STFT complex coefficients.
|
||||
|
||||
Args:
|
||||
dim (int): Hidden dimension of the model.
|
||||
n_fft (int): Size of Fourier transform.
|
||||
hop_length (int): The distance between neighboring sliding window frames, which should align with
|
||||
the resolution of the input features.
|
||||
padding (str, optional): Type of padding. Options are "center" or "same". Defaults to "same".
|
||||
"""
|
||||
|
||||
def __init__(self, dim: int, n_fft: int, hop_length: int, padding: str = "same"):
|
||||
super().__init__()
|
||||
out_dim = n_fft + 2
|
||||
self.out = torch.nn.Linear(dim, out_dim)
|
||||
self.istft = ISTFT(n_fft=n_fft, hop_length=hop_length, win_length=n_fft, padding=padding)
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
"""
|
||||
Forward pass of the ISTFTHead module.
|
||||
|
||||
Args:
|
||||
x (Tensor): Input tensor of shape (B, L, H), where B is the batch size,
|
||||
L is the sequence length, and H denotes the model dimension.
|
||||
|
||||
Returns:
|
||||
Tensor: Reconstructed time-domain audio signal of shape (B, T), where T is the length of the output signal.
|
||||
"""
|
||||
x = self.out(x).transpose(1, 2)
|
||||
mag, p = x.chunk(2, dim=1)
|
||||
mag = torch.exp(mag)
|
||||
mag = torch.clip(mag, max=1e2) # safeguard to prevent excessively large magnitudes
|
||||
# wrapping happens here. These two lines produce real and imaginary value
|
||||
x = torch.cos(p)
|
||||
y = torch.sin(p)
|
||||
# recalculating phase here does not produce anything new
|
||||
# only costs time
|
||||
# phase = torch.atan2(y, x)
|
||||
# S = mag * torch.exp(phase * 1j)
|
||||
# better directly produce the complex value
|
||||
original_dtype = x.dtype
|
||||
S = mag.float() * (x.float() + 1j * y.float())
|
||||
audio = self.istft(S)
|
||||
audio = audio.to(original_dtype)
|
||||
return audio
|
||||
|
||||
|
||||
class RotaryEmbedding(nn.Module):
|
||||
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
|
||||
|
||||
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
|
||||
|
||||
@torch.no_grad()
|
||||
@dynamic_rope_update
|
||||
def forward(self, x, position_ids):
|
||||
inv_freq_expanded = self.inv_freq[:, None].float().expand(-1, 1).to(x.device)
|
||||
position_ids_expanded = position_ids[None, :].float()
|
||||
|
||||
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
|
||||
with torch.autocast(device_type=device_type, enabled=False): # Force float32
|
||||
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(0, 1)
|
||||
emb = torch.cat((freqs, freqs), dim=-1)
|
||||
cos = emb.cos() * self.attention_scaling
|
||||
sin = emb.sin() * self.attention_scaling
|
||||
|
||||
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
||||
|
||||
|
||||
class RMSNorm(nn.Module):
|
||||
def __init__(self, hidden_size, eps=1e-6):
|
||||
"""
|
||||
RMSNorm is equivalent to T5LayerNorm
|
||||
"""
|
||||
super().__init__()
|
||||
self.weight = nn.Parameter(torch.ones(hidden_size))
|
||||
self.variance_epsilon = eps
|
||||
|
||||
def forward(self, hidden_states):
|
||||
variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
|
||||
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
||||
|
||||
if self.weight.dtype in [torch.float16, torch.bfloat16]:
|
||||
hidden_states = hidden_states.to(self.weight.dtype)
|
||||
|
||||
return self.weight * hidden_states
|
||||
|
||||
|
||||
LAYER_NORM = {"LayerNorm": nn.LayerNorm, "RMSNorm": RMSNorm}
|
||||
|
||||
|
||||
class Attention(nn.Module):
|
||||
def __init__(self, embed_dim, num_heads, window_size=(-1, -1), causal=False):
|
||||
super().__init__()
|
||||
self.embed_dim = embed_dim
|
||||
self.num_heads = num_heads
|
||||
self.head_dim = embed_dim // num_heads
|
||||
self.window_size = window_size
|
||||
|
||||
self.k_proj = nn.Linear(embed_dim, embed_dim, bias=False)
|
||||
self.v_proj = nn.Linear(embed_dim, embed_dim, bias=True)
|
||||
self.q_proj = nn.Linear(embed_dim, embed_dim, bias=True)
|
||||
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=True)
|
||||
|
||||
self.causal = causal
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
seq_len: torch.Tensor,
|
||||
rope_position_embeddings=None,
|
||||
):
|
||||
total_seq_len, _ = hidden_states.size()
|
||||
|
||||
query_states = self.q_proj(hidden_states).view(total_seq_len, self.num_heads, self.head_dim)
|
||||
key_states = self.k_proj(hidden_states).view(total_seq_len, self.num_heads, self.head_dim)
|
||||
value_states = self.v_proj(hidden_states).view(total_seq_len, self.num_heads, self.head_dim)
|
||||
|
||||
if rope_position_embeddings is not None:
|
||||
cos, sin = rope_position_embeddings
|
||||
query_states = apply_rotary_pos_emb(query_states, cos, sin)
|
||||
key_states = apply_rotary_pos_emb(key_states, cos, sin)
|
||||
|
||||
if hidden_states.is_cuda and is_flash_atth_available is True:
|
||||
# === Use flash-attn in GPU mode ===
|
||||
cu_len = F.pad(torch.cumsum(seq_len, dim=0), (1, 0), "constant", 0).to(torch.int32)
|
||||
max_seqlen = torch.max(seq_len).to(torch.int32).detach()
|
||||
attn_output = flash_attn_varlen_func(
|
||||
query_states,
|
||||
key_states,
|
||||
value_states,
|
||||
cu_len,
|
||||
cu_len,
|
||||
max_seqlen,
|
||||
max_seqlen,
|
||||
causal=self.causal,
|
||||
window_size=self.window_size,
|
||||
)
|
||||
attn_output = attn_output.reshape(total_seq_len, self.embed_dim)
|
||||
|
||||
else:
|
||||
# === Fallback implementation in CPU / Eager mode ===
|
||||
cu_len = F.pad(torch.cumsum(seq_len, dim=0), (1, 0), "constant", 0).to(torch.long)
|
||||
attn_output = torch.zeros_like(hidden_states)
|
||||
|
||||
for i, slen in enumerate(seq_len.tolist()):
|
||||
start_idx = cu_len[i].item()
|
||||
end_idx = cu_len[i + 1].item()
|
||||
|
||||
q = query_states[start_idx:end_idx] # [slen, num_heads, head_dim]
|
||||
k = key_states[start_idx:end_idx]
|
||||
v = value_states[start_idx:end_idx]
|
||||
|
||||
q = q.transpose(0, 1) # [num_heads, slen, head_dim]
|
||||
k = k.transpose(0, 1)
|
||||
v = v.transpose(0, 1)
|
||||
|
||||
attn_scores = torch.matmul(q, k.transpose(-1, -2)) / (self.head_dim**0.5)
|
||||
if self.causal:
|
||||
mask = torch.tril(torch.ones_like(attn_scores))
|
||||
attn_scores = attn_scores.masked_fill(mask == 0, float("-inf"))
|
||||
attn_probs = F.softmax(attn_scores, dim=-1)
|
||||
attn_out = torch.matmul(attn_probs, v) # [num_heads, slen, head_dim]
|
||||
|
||||
attn_out = attn_out.transpose(0, 1).reshape(slen, self.embed_dim)
|
||||
attn_output[start_idx:end_idx] = attn_out
|
||||
|
||||
attn_output = self.out_proj(attn_output)
|
||||
return attn_output
|
||||
|
||||
|
||||
class TransformerLayer(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
act,
|
||||
d_model,
|
||||
encoder_attention_heads,
|
||||
encoder_ffn_dim,
|
||||
causal,
|
||||
ln_type="LayerNorm",
|
||||
attn_window_size=(-1, -1),
|
||||
):
|
||||
super().__init__()
|
||||
self.embed_dim = d_model
|
||||
self.self_attn = Attention(self.embed_dim, encoder_attention_heads, attn_window_size, causal)
|
||||
|
||||
self.self_attn_layer_norm = LAYER_NORM[ln_type](self.embed_dim)
|
||||
|
||||
self.activation_fn = act
|
||||
self.fc1 = nn.Linear(self.embed_dim, encoder_ffn_dim)
|
||||
self.fc2 = nn.Linear(encoder_ffn_dim, self.embed_dim)
|
||||
|
||||
self.final_layer_norm = LAYER_NORM[ln_type](self.embed_dim)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
seq_len: torch.Tensor,
|
||||
rope_position_embeddings: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
residual = hidden_states
|
||||
hidden_states = self.self_attn_layer_norm(hidden_states)
|
||||
hidden_states = self.self_attn(hidden_states, seq_len, rope_position_embeddings=rope_position_embeddings)
|
||||
hidden_states = residual + hidden_states
|
||||
residual = hidden_states
|
||||
hidden_states = self.final_layer_norm(hidden_states)
|
||||
hidden_states = self.activation_fn(self.fc1(hidden_states))
|
||||
hidden_states = self.fc2(hidden_states)
|
||||
hidden_states = residual + hidden_states
|
||||
|
||||
if (hidden_states.dtype == torch.float16 or hidden_states.dtype == torch.bfloat16) and (
|
||||
torch.isinf(hidden_states).any() or torch.isnan(hidden_states).any()
|
||||
):
|
||||
clamp_value = torch.finfo(hidden_states.dtype).max - 1000
|
||||
hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
|
||||
return hidden_states
|
||||
|
||||
|
||||
class TransformerVocos(nn.Module):
|
||||
def __init__(self, config: MiMoAudioTokenizerConfig):
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.max_source_positions = self.config.max_audio_seconds * self.config.sampling_rate // self.config.hop_length
|
||||
self.embeddings = nn.Linear(config.n_mels, config.vocoder_dim, bias=False)
|
||||
|
||||
self.position_embedding = RotaryEmbedding(
|
||||
config.rope_theta,
|
||||
config.vocoder_dim // config.vocoder_attention_heads,
|
||||
self.max_source_positions,
|
||||
self.config.rope_type,
|
||||
)
|
||||
|
||||
self.layers = nn.ModuleList(
|
||||
[
|
||||
TransformerLayer(
|
||||
ACT2FN[self.config.activation_function],
|
||||
self.config.vocoder_dim,
|
||||
self.config.vocoder_attention_heads,
|
||||
self.config.vocoder_intermediate_dim,
|
||||
causal=False,
|
||||
ln_type=self.config.ln_type,
|
||||
attn_window_size=self.config.vocoder_attn_window_size,
|
||||
)
|
||||
for _ in range(self.config.vocoder_num_layers)
|
||||
]
|
||||
)
|
||||
|
||||
self.layer_norm = LAYER_NORM[self.config.ln_type](self.config.vocoder_dim)
|
||||
self.hop_size = self.config.hop_length
|
||||
self.head = ISTFTHead(
|
||||
self.config.vocoder_dim,
|
||||
self.config.nfft,
|
||||
self.config.hop_length,
|
||||
self.config.vocoder_padding,
|
||||
)
|
||||
|
||||
def forward(self, x: torch.Tensor, input_length):
|
||||
x = x.transpose(1, 2)
|
||||
attention_mask, unpacking_index = get_sequence_mask(x, input_length)
|
||||
x = torch.masked_select(x, attention_mask).view(torch.sum(input_length), self.config.n_mels)
|
||||
x = self.embeddings(x)
|
||||
position_ids = torch.arange(0, x.size(0), device=x.device, dtype=torch.long)
|
||||
rope_position_embeddings = self.position_embedding(x, position_ids)
|
||||
for idx, layer in enumerate(self.layers):
|
||||
x = layer(x, input_length, rope_position_embeddings=rope_position_embeddings)
|
||||
|
||||
x = self.layer_norm(x)
|
||||
x = unpack_hidden_states(x, input_length, attention_mask, unpacking_index)
|
||||
x = self.head(x)
|
||||
output_length = input_length * self.hop_size
|
||||
return x[:, None, :], output_length
|
||||
|
||||
|
||||
class AudioEncoder(nn.Module):
|
||||
def __init__(self, config: MiMoAudioTokenizerConfig):
|
||||
super().__init__()
|
||||
config._attn_implementation = "flash_attention_2"
|
||||
self.config = config
|
||||
self.max_source_positions = (
|
||||
config.max_audio_seconds * config.sampling_rate // config.hop_length
|
||||
) // config.stride_size
|
||||
self.embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
|
||||
|
||||
self.skip_layer_idx = config.encoder_skip_layer_id
|
||||
self.conv1 = nn.Conv1d(config.n_mels, config.d_model, kernel_size=config.kernel_size, padding=1)
|
||||
self.conv2 = nn.Conv1d(
|
||||
config.d_model,
|
||||
config.d_model,
|
||||
kernel_size=config.kernel_size,
|
||||
stride=config.stride_size,
|
||||
padding=1,
|
||||
)
|
||||
|
||||
self.position_embedding = RotaryEmbedding(
|
||||
config.rope_theta,
|
||||
config.d_model // config.encoder_attention_heads,
|
||||
self.max_source_positions,
|
||||
config.rope_type,
|
||||
)
|
||||
|
||||
self.layers = nn.ModuleList(
|
||||
[
|
||||
TransformerLayer(
|
||||
ACT2FN[config.activation_function],
|
||||
config.d_model,
|
||||
config.encoder_attention_heads,
|
||||
config.encoder_ffn_dim,
|
||||
causal=self.config.encoder_causal,
|
||||
ln_type=self.config.ln_type,
|
||||
attn_window_size=self.config.encoder_attn_window_size,
|
||||
)
|
||||
for _ in range(config.encoder_layers)
|
||||
]
|
||||
)
|
||||
|
||||
self.layer_norm = LAYER_NORM[config.ln_type](config.d_model)
|
||||
|
||||
if self.config.avg_pooler != 1:
|
||||
self.down_sample_layer = nn.Sequential(
|
||||
nn.Conv1d(
|
||||
config.d_model,
|
||||
config.d_model,
|
||||
config.avg_pooler,
|
||||
config.avg_pooler,
|
||||
bias=False,
|
||||
),
|
||||
nn.GELU(),
|
||||
)
|
||||
self.down_sample_norm = LAYER_NORM[config.ln_type](config.d_model)
|
||||
else:
|
||||
self.down_sample_layer = None
|
||||
|
||||
if self.config.num_quantizers != 0:
|
||||
self.quantizer = ResidualVectorQuantizer(
|
||||
dimension=self.config.d_model,
|
||||
n_q=self.config.num_quantizers,
|
||||
bins=self.config.codebook_size,
|
||||
threshold_ema_dead_code=self.config.threshold_ema_dead_code,
|
||||
)
|
||||
else:
|
||||
self.quantizer = None
|
||||
|
||||
def get_features(self, input_features, output_length):
|
||||
input_features = input_features.to(self.conv1.weight)
|
||||
inputs_embeds = nn.functional.gelu(self.conv1(input_features))
|
||||
inputs_embeds = nn.functional.gelu(self.conv2(inputs_embeds))
|
||||
inputs_embeds = inputs_embeds.permute(0, 2, 1)
|
||||
bsz, tgt_len, _ = inputs_embeds.size()
|
||||
|
||||
hidden_states = inputs_embeds
|
||||
|
||||
position_ids = get_position_ids(output_length).long().to(input_features.device)
|
||||
rope_position_embeddings = self.position_embedding(input_features, position_ids)
|
||||
|
||||
attention_mask, unpacking_index = get_sequence_mask(hidden_states, output_length)
|
||||
|
||||
hidden_states = torch.masked_select(hidden_states, attention_mask).view(
|
||||
torch.sum(output_length), self.config.d_model
|
||||
)
|
||||
|
||||
skip_connect_hidden_states = 0.0
|
||||
for idx, encoder_layer in enumerate(self.layers):
|
||||
hidden_states = encoder_layer(
|
||||
hidden_states,
|
||||
output_length,
|
||||
rope_position_embeddings=rope_position_embeddings,
|
||||
)
|
||||
if (self.skip_layer_idx is not None) and idx == self.skip_layer_idx - 1:
|
||||
skip_connect_hidden_states = hidden_states.clone()
|
||||
|
||||
hidden_states += skip_connect_hidden_states
|
||||
hidden_states = self.layer_norm(hidden_states)
|
||||
|
||||
if self.down_sample_layer is not None:
|
||||
hidden_states = torch.index_select(hidden_states, 0, unpacking_index).view(
|
||||
bsz, tgt_len, self.config.d_model
|
||||
)
|
||||
if hidden_states.size(1) % self.config.avg_pooler:
|
||||
pad_len = self.config.avg_pooler - hidden_states.size(1) % self.config.avg_pooler
|
||||
hidden_states = torch.nn.functional.pad(hidden_states, (0, 0, 0, pad_len), mode="constant", value=0.0)
|
||||
tgt_len += pad_len
|
||||
tgt_len = tgt_len // self.config.avg_pooler
|
||||
hidden_states = self.down_sample_layer(hidden_states.transpose(1, 2))
|
||||
output_length = (
|
||||
output_length // self.config.avg_pooler + (output_length % self.config.avg_pooler != 0).int()
|
||||
)
|
||||
hidden_states = hidden_states.transpose(1, 2)
|
||||
attention_mask, unpacking_index = get_sequence_mask(hidden_states, output_length)
|
||||
hidden_states = torch.masked_select(hidden_states, attention_mask).view(
|
||||
torch.sum(output_length), self.config.d_model
|
||||
)
|
||||
hidden_states = self.down_sample_norm(hidden_states)
|
||||
|
||||
return (
|
||||
hidden_states,
|
||||
output_length,
|
||||
attention_mask,
|
||||
unpacking_index,
|
||||
tgt_len,
|
||||
bsz,
|
||||
)
|
||||
|
||||
def get_output_length(self, mel_len):
|
||||
tgt_len = mel_len + 3 - self.config.kernel_size
|
||||
return (tgt_len + 2 - self.config.kernel_size) // self.config.stride_size + 1
|
||||
|
||||
@torch.no_grad()
|
||||
def encode(
|
||||
self,
|
||||
input_features,
|
||||
input_lens=None,
|
||||
output_length=None,
|
||||
return_codes_only=False,
|
||||
n_q=None,
|
||||
use_quantizer=True,
|
||||
):
|
||||
if output_length is None:
|
||||
output_length = self.get_output_length(input_lens)
|
||||
input_features = unpack_hidden_states(input_features, input_lens)
|
||||
hidden_states, output_length, attention_mask, unpacking_index, tgt_len, bsz = self.get_features(
|
||||
input_features=input_features.transpose(1, 2),
|
||||
output_length=output_length,
|
||||
)
|
||||
|
||||
dtype = hidden_states.dtype
|
||||
|
||||
if use_quantizer and self.quantizer is not None:
|
||||
self.quantizer.float()
|
||||
|
||||
codes = self.quantizer.encode(hidden_states.float(), n_q=n_q)
|
||||
if return_codes_only:
|
||||
return codes, output_length
|
||||
hidden_states = self.quantizer.decode(codes)
|
||||
hidden_states = hidden_states.to(dtype)
|
||||
else:
|
||||
codes = None
|
||||
|
||||
hidden_states_packed = hidden_states.clone()
|
||||
|
||||
# unpacking
|
||||
hidden_states = torch.index_select(hidden_states, 0, unpacking_index).view(bsz, tgt_len, self.config.d_model)
|
||||
hidden_states = torch.where(attention_mask, hidden_states, 0)
|
||||
return hidden_states, hidden_states_packed, output_length, codes
|
||||
|
||||
@torch.no_grad()
|
||||
def decode_vq(self, codes):
|
||||
self.quantizer.float()
|
||||
hidden_states = self.quantizer.decode(codes)
|
||||
|
||||
return hidden_states
|
||||
|
||||
|
||||
class CausalConvTranspose1d(nn.Module):
|
||||
def __init__(self, in_channels, out_channels, kernel_size, stride):
|
||||
super().__init__()
|
||||
self.conv = nn.ConvTranspose1d(in_channels, out_channels, kernel_size, stride)
|
||||
self.norm = nn.GroupNorm(1, out_channels)
|
||||
self.in_channels = in_channels
|
||||
self.out_channels = out_channels
|
||||
|
||||
def forward(self, hidden_states, input_length, output_dim=None):
|
||||
kernel_size = self.conv.kernel_size[0]
|
||||
stride = self.conv.stride[0]
|
||||
bsz = input_length.shape[0]
|
||||
|
||||
if output_dim is None:
|
||||
output_dim = hidden_states.dim()
|
||||
if hidden_states.dim() <= 2: # unpack sequence to 3d
|
||||
sequence_mask, unpacking_index = get_sequence_mask(hidden_states, input_length)
|
||||
hidden_states = torch.index_select(hidden_states, 0, unpacking_index).view(
|
||||
bsz, torch.max(input_length), self.in_channels
|
||||
)
|
||||
hidden_states = torch.where(sequence_mask, hidden_states, 0)
|
||||
|
||||
hidden_states = hidden_states.transpose(2, 1) # (N, L, C) -> (N, C, L)
|
||||
hidden_states = self.conv(hidden_states)
|
||||
hidden_states = self.norm(hidden_states)
|
||||
hidden_states = hidden_states.transpose(2, 1) # (N, C, L) -> (N, L, C)
|
||||
|
||||
casual_padding_right = max(0, kernel_size - stride)
|
||||
hidden_states = hidden_states[:, : hidden_states.shape[1] - casual_padding_right, :]
|
||||
output_length = (input_length - 1) * stride + kernel_size - casual_padding_right
|
||||
sequence_mask, _ = get_sequence_mask(hidden_states, output_length)
|
||||
if output_dim <= 2:
|
||||
hidden_states = torch.masked_select(hidden_states, sequence_mask).view(-1, self.out_channels)
|
||||
else:
|
||||
hidden_states = torch.where(sequence_mask, hidden_states, 0)
|
||||
hidden_states = hidden_states[:, : torch.max(output_length), :]
|
||||
return hidden_states, output_length
|
||||
|
||||
|
||||
class AudioDecoder(nn.Module):
|
||||
def __init__(self, config: MiMoAudioTokenizerConfig):
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.max_source_positions = self.config.max_audio_seconds * self.config.sampling_rate // self.config.hop_length
|
||||
|
||||
if self.config.avg_pooler != 1:
|
||||
self.dconv1 = CausalConvTranspose1d(
|
||||
self.config.d_model,
|
||||
self.config.d_model,
|
||||
self.config.avg_pooler,
|
||||
self.config.avg_pooler,
|
||||
)
|
||||
else:
|
||||
self.dconv1 = None
|
||||
|
||||
self.position_embedding = RotaryEmbedding(
|
||||
config.rope_theta,
|
||||
config.d_model // config.decoder_attention_heads,
|
||||
self.max_source_positions,
|
||||
config.rope_type,
|
||||
)
|
||||
|
||||
self.layers = nn.ModuleList(
|
||||
[
|
||||
TransformerLayer(
|
||||
ACT2FN[self.config.activation_function],
|
||||
self.config.d_model,
|
||||
self.config.decoder_attention_heads,
|
||||
self.config.decoder_ffn_dim,
|
||||
causal=self.config.decoder_causal,
|
||||
ln_type=self.config.ln_type,
|
||||
attn_window_size=self.config.decoder_attn_window_size,
|
||||
)
|
||||
for _ in range(self.config.decoder_layers)
|
||||
]
|
||||
)
|
||||
self.layer_norm = LAYER_NORM[config.ln_type](self.config.d_model)
|
||||
self.dconv2 = CausalConvTranspose1d(
|
||||
self.config.d_model,
|
||||
self.config.n_mels,
|
||||
self.config.decoder_kernel_size,
|
||||
self.config.decoder_stride_size,
|
||||
)
|
||||
self.vocoder = TransformerVocos(config)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
audio_embed,
|
||||
input_length,
|
||||
):
|
||||
assert audio_embed.shape[-1] == self.config.d_model
|
||||
audio_embed = audio_embed.to(self.layer_norm.weight)
|
||||
|
||||
if self.dconv1 is not None:
|
||||
audio_embed, output_length = self.dconv1(audio_embed, input_length, output_dim=3)
|
||||
else:
|
||||
output_length = input_length
|
||||
|
||||
hidden_states = audio_embed
|
||||
|
||||
position_ids = get_position_ids(output_length).long().to(hidden_states.device)
|
||||
rope_position_embeddings = self.position_embedding(hidden_states, position_ids)
|
||||
|
||||
# packing hidden states
|
||||
attention_mask, _ = get_sequence_mask(hidden_states, output_length)
|
||||
hidden_states = torch.masked_select(hidden_states, attention_mask).view(
|
||||
torch.sum(output_length), self.config.d_model
|
||||
)
|
||||
|
||||
for idx, encoder_layer in enumerate(self.layers):
|
||||
hidden_states = encoder_layer(
|
||||
hidden_states,
|
||||
output_length,
|
||||
rope_position_embeddings=rope_position_embeddings,
|
||||
)
|
||||
|
||||
hidden_states = self.layer_norm(hidden_states)
|
||||
|
||||
coarse_mel, output_length = self.dconv2(hidden_states, output_length, output_dim=3)
|
||||
|
||||
recon_wav, wav_length = self.vocoder(
|
||||
x=coarse_mel.transpose(1, 2),
|
||||
input_length=output_length,
|
||||
)
|
||||
|
||||
return recon_wav
|
||||
|
||||
|
||||
class MiMoAudioTokenizer(PreTrainedModel):
|
||||
config_class = MiMoAudioTokenizerConfig
|
||||
|
||||
def __init__(self, config: MiMoAudioTokenizerConfig):
|
||||
super().__init__(config)
|
||||
self.config = config
|
||||
self.sampling_rate = config.sampling_rate
|
||||
self.encoder = AudioEncoder(config=config)
|
||||
self.decoder = AudioDecoder(config=config)
|
||||
self.downsample_rate = int(self.config.hop_length * 2 * self.config.avg_pooler)
|
||||
|
||||
def get_output_length(self, mel_len):
|
||||
tgt_len = mel_len + 3 - self.config.kernel_size
|
||||
return (tgt_len + 2 - self.config.kernel_size) // self.config.stride_size + 1
|
||||
|
||||
@torch.no_grad()
|
||||
def encode(self, mels, input_lens, use_quantizer=True):
|
||||
input_features = mels
|
||||
hidden_states, hidden_states_packed, encoder_output_length, codes = self.encoder.encode(
|
||||
input_features, input_lens=input_lens, use_quantizer=use_quantizer
|
||||
)
|
||||
return hidden_states, hidden_states_packed, encoder_output_length, codes
|
||||
|
||||
@torch.no_grad()
|
||||
def decode(self, codes):
|
||||
hidden_states = self.encoder.decode_vq(codes)
|
||||
output = self.decoder(
|
||||
hidden_states,
|
||||
torch.tensor([hidden_states.size(0)], device=hidden_states.device),
|
||||
)
|
||||
return output
|
||||
|
||||
@torch.no_grad()
|
||||
def streaming_decode(
|
||||
self,
|
||||
codes_chunks,
|
||||
chunk_input_lengths,
|
||||
history_cache=StreamingCache(),
|
||||
streaming_config=StreamingConfig(),
|
||||
last_chunk=False,
|
||||
):
|
||||
hidden_states = self.encoder.decode_vq(codes_chunks)
|
||||
input_lengths = []
|
||||
input_hidden_states = []
|
||||
start_idx = 0
|
||||
cache_hidden_states = []
|
||||
for i, input_length in enumerate(chunk_input_lengths):
|
||||
sample_hidden_states = hidden_states[start_idx : start_idx + input_length]
|
||||
start_idx += input_length
|
||||
if history_cache.hidden_states is not None:
|
||||
sample_hidden_states = torch.cat([history_cache.hidden_states[i], sample_hidden_states], dim=0)
|
||||
input_length += history_cache.hidden_states[i].size(0)
|
||||
input_hidden_states.append(sample_hidden_states)
|
||||
cache_hidden_states.append(sample_hidden_states.clone())
|
||||
input_lengths.append(input_length)
|
||||
input_hidden_states = torch.cat(input_hidden_states, dim=0)
|
||||
input_lengths = torch.tensor(input_lengths, device=hidden_states.device)
|
||||
output = self.decoder(input_hidden_states, input_lengths)
|
||||
return_wavs = []
|
||||
frames_per_token = self.config.avg_pooler * self.config.stride_size * self.config.hop_length
|
||||
processed_lengths = []
|
||||
for i, wav in enumerate(output):
|
||||
wav = wav.float().detach().cpu()
|
||||
start_idx = history_cache.processed_lengths[i] if history_cache.processed_lengths is not None else 0
|
||||
if last_chunk:
|
||||
return_wavs.append(wav[:, start_idx * frames_per_token :])
|
||||
new_processed_length = input_lengths[i].item()
|
||||
elif input_lengths[i].item() <= streaming_config.right_overlap:
|
||||
return_wavs.append(None)
|
||||
new_processed_length = 0
|
||||
else:
|
||||
end_idx = input_lengths[i].item() - streaming_config.right_overlap
|
||||
wav = wav[:, start_idx * frames_per_token : end_idx * frames_per_token]
|
||||
return_wavs.append(wav)
|
||||
new_processed_length = end_idx
|
||||
if input_lengths[i].item() > streaming_config.left_overlap:
|
||||
cache_hidden_states[i] = cache_hidden_states[i][-streaming_config.left_overlap :]
|
||||
new_processed_length -= input_lengths[i].item() - streaming_config.left_overlap
|
||||
processed_lengths.append(new_processed_length)
|
||||
history_cache.hidden_states = cache_hidden_states
|
||||
history_cache.processed_lengths = processed_lengths
|
||||
|
||||
return return_wavs, history_cache
|
||||
@@ -0,0 +1,703 @@
|
||||
# Copyright 2025 Xiaomi Corporation.
|
||||
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import math
|
||||
from collections.abc import Callable
|
||||
from functools import wraps
|
||||
from typing import Optional
|
||||
|
||||
from transformers.configuration_utils import PretrainedConfig
|
||||
from transformers.utils import is_torch_available, logging
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
|
||||
|
||||
if is_torch_available():
|
||||
import torch
|
||||
|
||||
|
||||
def dynamic_rope_update(rope_forward: Callable) -> Callable:
|
||||
"""
|
||||
Decorator function to update the RoPE parameters in the forward pass, if the model is using a dynamic RoPE
|
||||
(i.e. a RoPE implementation that may recompute its frequencies in the forward pass).
|
||||
|
||||
Args:
|
||||
rope_forward (Callable):
|
||||
The forward pass of the RoPE implementation.
|
||||
|
||||
Returns:
|
||||
The decorated forward pass.
|
||||
"""
|
||||
|
||||
def longrope_frequency_update(self, position_ids, device):
|
||||
"""Longrope uses long factor if sequence is larger than original pretraining length, short otherwise."""
|
||||
seq_len = torch.max(position_ids) + 1
|
||||
if hasattr(self.config, "original_max_position_embeddings"):
|
||||
original_max_position_embeddings = self.config.original_max_position_embeddings
|
||||
else:
|
||||
original_max_position_embeddings = self.config.max_position_embeddings
|
||||
if seq_len > original_max_position_embeddings:
|
||||
if not hasattr(self, "long_inv_freq"):
|
||||
self.long_inv_freq, _ = self.rope_init_fn(
|
||||
self.config, device, seq_len=original_max_position_embeddings + 1
|
||||
)
|
||||
self.register_buffer("inv_freq", self.long_inv_freq, persistent=False)
|
||||
else:
|
||||
# This .to() is needed if the model has been moved to a device after being initialized (because
|
||||
# the buffer is automatically moved, but not the original copy)
|
||||
self.original_inv_freq = self.original_inv_freq.to(device)
|
||||
self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
|
||||
|
||||
def dynamic_frequency_update(self, position_ids, device):
|
||||
"""
|
||||
dynamic RoPE layers should recompute `inv_freq` in the following situations:
|
||||
1 - growing beyond the cached sequence length (allow scaling)
|
||||
2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
|
||||
"""
|
||||
seq_len = torch.max(position_ids) + 1
|
||||
if seq_len > self.max_seq_len_cached: # growth
|
||||
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
|
||||
self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
|
||||
self.max_seq_len_cached = seq_len
|
||||
|
||||
if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
|
||||
# This .to() is needed if the model has been moved to a device after being initialized (because
|
||||
# the buffer is automatically moved, but not the original copy)
|
||||
self.original_inv_freq = self.original_inv_freq.to(device)
|
||||
self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
|
||||
self.max_seq_len_cached = self.original_max_seq_len
|
||||
|
||||
@wraps(rope_forward)
|
||||
def wrapper(self, x, position_ids):
|
||||
if "dynamic" in self.rope_type:
|
||||
dynamic_frequency_update(self, position_ids, device=x.device)
|
||||
elif self.rope_type == "longrope":
|
||||
longrope_frequency_update(self, position_ids, device=x.device)
|
||||
return rope_forward(self, x, position_ids)
|
||||
|
||||
return wrapper
|
||||
|
||||
|
||||
def _compute_default_rope_parameters(
|
||||
config: PretrainedConfig | None = None,
|
||||
device: Optional["torch.device"] = None,
|
||||
seq_len: int | None = None,
|
||||
**rope_kwargs,
|
||||
) -> tuple["torch.Tensor", float]:
|
||||
"""
|
||||
Computes the inverse frequencies according to the original RoPE implementation
|
||||
Args:
|
||||
config ([`~transformers.PretrainedConfig`]):
|
||||
The model configuration.
|
||||
device (`torch.device`):
|
||||
The device to use for initialization of the inverse frequencies.
|
||||
seq_len (`int`, *optional*):
|
||||
The current sequence length. Unused for this type of RoPE.
|
||||
rope_kwargs (`Dict`, *optional*):
|
||||
BC compatibility with the previous RoPE class instantiation, will be removed in v4.45.
|
||||
Returns:
|
||||
Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
|
||||
post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
|
||||
"""
|
||||
if config is not None and len(rope_kwargs) > 0:
|
||||
raise ValueError(
|
||||
"Unexpected arguments: `**rope_kwargs` and `config` are mutually exclusive in "
|
||||
f"`_compute_default_rope_parameters`, got `rope_kwargs`={rope_kwargs} and `config`={config}"
|
||||
)
|
||||
if len(rope_kwargs) > 0:
|
||||
base = rope_kwargs["base"]
|
||||
dim = rope_kwargs["dim"]
|
||||
elif config is not None:
|
||||
base = config.rope_theta
|
||||
partial_rotary_factor = config.partial_rotary_factor if hasattr(config, "partial_rotary_factor") else 1.0
|
||||
head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
|
||||
dim = int(head_dim * partial_rotary_factor)
|
||||
|
||||
attention_factor = 1.0 # Unused in this type of RoPE
|
||||
|
||||
# Compute the inverse frequencies
|
||||
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim))
|
||||
return inv_freq, attention_factor
|
||||
|
||||
|
||||
def _compute_linear_scaling_rope_parameters(
|
||||
config: PretrainedConfig | None = None,
|
||||
device: Optional["torch.device"] = None,
|
||||
seq_len: int | None = None,
|
||||
**rope_kwargs,
|
||||
) -> tuple["torch.Tensor", float]:
|
||||
"""
|
||||
Computes the inverse frequencies with linear scaling. Credits to the Reddit user /u/kaiokendev
|
||||
Args:
|
||||
config ([`~transformers.PretrainedConfig`]):
|
||||
The model configuration.
|
||||
device (`torch.device`):
|
||||
The device to use for initialization of the inverse frequencies.
|
||||
seq_len (`int`, *optional*):
|
||||
The current sequence length. Unused for this type of RoPE.
|
||||
rope_kwargs (`Dict`, *optional*):
|
||||
BC compatibility with the previous RoPE class instantiation, will be removed in v4.45.
|
||||
Returns:
|
||||
Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
|
||||
post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
|
||||
"""
|
||||
if config is not None and len(rope_kwargs) > 0:
|
||||
raise ValueError(
|
||||
"Unexpected arguments: `**rope_kwargs` and `config` are mutually exclusive in "
|
||||
f"`_compute_linear_scaling_rope_parameters`, got `rope_kwargs`={rope_kwargs} and `config`={config}"
|
||||
)
|
||||
if len(rope_kwargs) > 0:
|
||||
factor = rope_kwargs["factor"]
|
||||
elif config is not None:
|
||||
factor = config.rope_scaling["factor"]
|
||||
|
||||
# Gets the default RoPE parameters
|
||||
inv_freq, attention_factor = _compute_default_rope_parameters(config, device, seq_len, **rope_kwargs)
|
||||
|
||||
# Then applies linear scaling to the frequencies.
|
||||
# NOTE: originally, scaling was applied to the position_ids. However, we get `embs = inv_freq @ position_ids`, so
|
||||
# applying scaling to the inverse frequencies is equivalent.
|
||||
inv_freq /= factor
|
||||
return inv_freq, attention_factor
|
||||
|
||||
|
||||
def _compute_dynamic_ntk_parameters(
|
||||
config: PretrainedConfig | None = None,
|
||||
device: Optional["torch.device"] = None,
|
||||
seq_len: int | None = None,
|
||||
**rope_kwargs,
|
||||
) -> tuple["torch.Tensor", float]:
|
||||
"""
|
||||
Computes the inverse frequencies with NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla
|
||||
Args:
|
||||
config ([`~transformers.PretrainedConfig`]):
|
||||
The model configuration.
|
||||
device (`torch.device`):
|
||||
The device to use for initialization of the inverse frequencies.
|
||||
seq_len (`int`, *optional*):
|
||||
The current sequence length, used to update the dynamic RoPE at inference time.
|
||||
rope_kwargs (`Dict`, *optional*):
|
||||
BC compatibility with the previous RoPE class instantiation, will be removed in v4.45.
|
||||
Returns:
|
||||
Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
|
||||
post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
|
||||
"""
|
||||
# TODO (joao): use the new `original_max_position_embeddings` from rope_scaling
|
||||
if config is not None and len(rope_kwargs) > 0:
|
||||
raise ValueError(
|
||||
"Unexpected arguments: `**rope_kwargs` and `config` are mutually exclusive in "
|
||||
f"`_compute_dynamic_ntk_parameters`, got `rope_kwargs`={rope_kwargs} and `config`={config}"
|
||||
)
|
||||
if len(rope_kwargs) > 0:
|
||||
base = rope_kwargs["base"]
|
||||
dim = rope_kwargs["dim"]
|
||||
max_position_embeddings = rope_kwargs["max_position_embeddings"]
|
||||
factor = rope_kwargs["factor"]
|
||||
elif config is not None:
|
||||
base = config.rope_theta
|
||||
partial_rotary_factor = config.partial_rotary_factor if hasattr(config, "partial_rotary_factor") else 1.0
|
||||
head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
||||
dim = int(head_dim * partial_rotary_factor)
|
||||
max_position_embeddings = config.max_position_embeddings
|
||||
factor = config.rope_scaling["factor"]
|
||||
|
||||
attention_factor = 1.0 # Unused in this type of RoPE
|
||||
|
||||
# seq_len: default to max_position_embeddings, e.g. at init time
|
||||
seq_len = seq_len if seq_len is not None and seq_len > max_position_embeddings else max_position_embeddings
|
||||
|
||||
# Compute the inverse frequencies
|
||||
base = base * ((factor * seq_len / max_position_embeddings) - (factor - 1)) ** (dim / (dim - 2))
|
||||
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim))
|
||||
return inv_freq, attention_factor
|
||||
|
||||
|
||||
def _compute_yarn_parameters(
|
||||
config: PretrainedConfig,
|
||||
device: "torch.device",
|
||||
seq_len: int | None = None,
|
||||
**rope_kwargs,
|
||||
) -> tuple["torch.Tensor", float]:
|
||||
"""
|
||||
Computes the inverse frequencies with NTK scaling. Please refer to the
|
||||
[original paper](https://huggingface.co/papers/2309.00071)
|
||||
Args:
|
||||
config ([`~transformers.PretrainedConfig`]):
|
||||
The model configuration.
|
||||
device (`torch.device`):
|
||||
The device to use for initialization of the inverse frequencies.
|
||||
seq_len (`int`, *optional*):
|
||||
The current sequence length. Unused for this type of RoPE.
|
||||
rope_kwargs (`Dict`, *optional*):
|
||||
BC compatibility with the previous RoPE class instantiation, will be removed in v4.45.
|
||||
Returns:
|
||||
Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
|
||||
post-processing scaling factor applied to the computed cos/sin.
|
||||
"""
|
||||
# No need to keep BC with yarn, unreleased when this new pattern was created.
|
||||
if len(rope_kwargs) > 0:
|
||||
raise ValueError(
|
||||
f"Unexpected arguments: `**rope_kwargs` should be unset in `_compute_yarn_parameters`, got {rope_kwargs}"
|
||||
)
|
||||
|
||||
base = config.rope_theta
|
||||
partial_rotary_factor = config.partial_rotary_factor if hasattr(config, "partial_rotary_factor") else 1.0
|
||||
head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
||||
dim = int(head_dim * partial_rotary_factor)
|
||||
factor = config.rope_scaling["factor"]
|
||||
attention_factor = config.rope_scaling.get("attention_factor")
|
||||
mscale = config.rope_scaling.get("mscale")
|
||||
mscale_all_dim = config.rope_scaling.get("mscale_all_dim")
|
||||
|
||||
# NOTE: DeekSeek-V3 (and potentially other models) modify `max_position_embeddings` and have a
|
||||
# `original_max_position_embeddings` field containing the pretrained value. They use the ratio between these two
|
||||
# values to compute the default attention scaling factor, instead of using `factor`.
|
||||
if "original_max_position_embeddings" in config.rope_scaling:
|
||||
original_max_position_embeddings = config.rope_scaling["original_max_position_embeddings"]
|
||||
factor = config.max_position_embeddings / original_max_position_embeddings
|
||||
else:
|
||||
original_max_position_embeddings = config.max_position_embeddings
|
||||
|
||||
def get_mscale(scale, mscale=1):
|
||||
if scale <= 1:
|
||||
return 1.0
|
||||
return 0.1 * mscale * math.log(scale) + 1.0
|
||||
|
||||
# Sets the attention factor as suggested in the paper
|
||||
if attention_factor is None:
|
||||
if mscale and mscale_all_dim:
|
||||
attention_factor = float(get_mscale(factor, mscale) / get_mscale(factor, mscale_all_dim))
|
||||
else:
|
||||
attention_factor = get_mscale(factor)
|
||||
|
||||
# Optional config options
|
||||
# beta_fast/beta_slow: as suggested in the paper, default to 32/1 (correspondingly)
|
||||
beta_fast = config.rope_scaling.get("beta_fast") or 32
|
||||
beta_slow = config.rope_scaling.get("beta_slow") or 1
|
||||
|
||||
# Compute the inverse frequencies
|
||||
def find_correction_dim(num_rotations, dim, base, max_position_embeddings):
|
||||
"""Inverse dimension formula to find the dimension based on the number of rotations"""
|
||||
return (dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))) / (2 * math.log(base))
|
||||
|
||||
def find_correction_range(low_rot, high_rot, dim, base, max_position_embeddings):
|
||||
"""Find dimension range bounds based on rotations"""
|
||||
low = math.floor(find_correction_dim(low_rot, dim, base, max_position_embeddings))
|
||||
high = math.ceil(find_correction_dim(high_rot, dim, base, max_position_embeddings))
|
||||
return max(low, 0), min(high, dim - 1)
|
||||
|
||||
def linear_ramp_factor(min, max, dim):
|
||||
if min == max:
|
||||
max += 0.001 # Prevent singularity
|
||||
|
||||
linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
|
||||
ramp_func = torch.clamp(linear_func, 0, 1)
|
||||
return ramp_func
|
||||
|
||||
# Note on variable naming: "interpolation" comes from the original technique, where we interpolate the position IDs
|
||||
# to expand the possible context length. In other words, interpolation = apply scaling factor.
|
||||
pos_freqs = base ** (torch.arange(0, dim, 2).to(device=device, dtype=torch.float) / dim)
|
||||
inv_freq_extrapolation = 1.0 / pos_freqs
|
||||
inv_freq_interpolation = 1.0 / (factor * pos_freqs)
|
||||
|
||||
low, high = find_correction_range(beta_fast, beta_slow, dim, base, original_max_position_embeddings)
|
||||
|
||||
# Get n-dimensional rotational scaling corrected for extrapolation
|
||||
inv_freq_extrapolation_factor = 1 - linear_ramp_factor(low, high, dim // 2).to(device=device, dtype=torch.float)
|
||||
inv_freq = (
|
||||
inv_freq_interpolation * (1 - inv_freq_extrapolation_factor)
|
||||
+ inv_freq_extrapolation * inv_freq_extrapolation_factor
|
||||
)
|
||||
return inv_freq, attention_factor
|
||||
|
||||
|
||||
def _compute_longrope_parameters(
|
||||
config: PretrainedConfig,
|
||||
device: "torch.device",
|
||||
seq_len: int | None = None,
|
||||
**rope_kwargs,
|
||||
) -> tuple["torch.Tensor", float]:
|
||||
"""
|
||||
Computes the inverse frequencies with LongRoPE scaling. Please refer to the
|
||||
[original implementation](https://github.com/microsoft/LongRoPE)
|
||||
Args:
|
||||
config ([`~transformers.PretrainedConfig`]):
|
||||
The model configuration.
|
||||
device (`torch.device`):
|
||||
The device to use for initialization of the inverse frequencies.
|
||||
seq_len (`int`, *optional*):
|
||||
The current sequence length.
|
||||
rope_kwargs (`Dict`, *optional*):
|
||||
BC compatibility with the previous RoPE class instantiation, will be removed in v4.45.
|
||||
Returns:
|
||||
Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
|
||||
post-processing scaling factor applied to the computed cos/sin.
|
||||
"""
|
||||
# TODO (joao): use the new `original_max_position_embeddings` from rope_scaling
|
||||
# No need to keep BC with longrope, unreleased when this new pattern was created.
|
||||
if len(rope_kwargs) > 0:
|
||||
raise ValueError(
|
||||
"Unexpected arguments: `**rope_kwargs` should be unset in `_compute_longrope_parameters`, got "
|
||||
f"{rope_kwargs}"
|
||||
)
|
||||
|
||||
base = config.rope_theta
|
||||
partial_rotary_factor = config.partial_rotary_factor if hasattr(config, "partial_rotary_factor") else 1.0
|
||||
head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
||||
dim = int(head_dim * partial_rotary_factor)
|
||||
long_factor = config.rope_scaling["long_factor"]
|
||||
short_factor = config.rope_scaling["short_factor"]
|
||||
factor = config.rope_scaling.get("factor")
|
||||
attention_factor = config.rope_scaling.get("attention_factor")
|
||||
|
||||
# NOTE: Phi3 (and potentially other models) modify `max_position_embeddings` and have a
|
||||
# `original_max_position_embeddings` field containing the pretrained value. They use the ratio between these two
|
||||
# values to compute the default attention scaling factor, instead of using `factor`.
|
||||
if hasattr(config, "original_max_position_embeddings"):
|
||||
original_max_position_embeddings = config.original_max_position_embeddings
|
||||
factor = config.max_position_embeddings / config.original_max_position_embeddings
|
||||
else:
|
||||
original_max_position_embeddings = config.max_position_embeddings
|
||||
|
||||
# Sets the attention factor as suggested in the paper
|
||||
if attention_factor is None:
|
||||
if factor <= 1.0:
|
||||
attention_factor = 1.0
|
||||
else:
|
||||
attention_factor = math.sqrt(1 + math.log(factor) / math.log(original_max_position_embeddings))
|
||||
|
||||
# Compute the inverse frequencies -- scaled based on the target sequence length
|
||||
if seq_len and seq_len > original_max_position_embeddings:
|
||||
ext_factors = torch.tensor(long_factor, dtype=torch.float32, device=device)
|
||||
else:
|
||||
ext_factors = torch.tensor(short_factor, dtype=torch.float32, device=device)
|
||||
inv_freq_shape = torch.arange(0, dim, 2, dtype=torch.int64, device=device).float() / dim
|
||||
inv_freq = 1.0 / (ext_factors * base**inv_freq_shape)
|
||||
|
||||
return inv_freq, attention_factor
|
||||
|
||||
|
||||
def _compute_llama3_parameters(
|
||||
config: PretrainedConfig,
|
||||
device: "torch.device",
|
||||
seq_len: int | None = None,
|
||||
**rope_kwargs,
|
||||
) -> tuple["torch.Tensor", float]:
|
||||
"""
|
||||
Computes the inverse frequencies for llama 3.1.
|
||||
|
||||
Args:
|
||||
config ([`~transformers.PretrainedConfig`]):
|
||||
The model configuration.
|
||||
device (`torch.device`):
|
||||
The device to use for initialization of the inverse frequencies.
|
||||
seq_len (`int`, *optional*):
|
||||
The current sequence length. Unused for this type of RoPE.
|
||||
rope_kwargs (`Dict`, *optional*):
|
||||
BC compatibility with the previous RoPE class instantiation, will be removed in v4.45.
|
||||
Returns:
|
||||
Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
|
||||
post-processing scaling factor applied to the computed cos/sin.
|
||||
"""
|
||||
# Gets the default RoPE parameters
|
||||
inv_freq, attention_factor = _compute_default_rope_parameters(config, device, seq_len, **rope_kwargs)
|
||||
|
||||
factor = config.rope_scaling["factor"] # `8` in the original implementation
|
||||
low_freq_factor = config.rope_scaling["low_freq_factor"] # `1` in the original implementation
|
||||
high_freq_factor = config.rope_scaling["high_freq_factor"] # `4` in the original implementation
|
||||
old_context_len = config.rope_scaling["original_max_position_embeddings"] # `8192` in the original implementation
|
||||
|
||||
low_freq_wavelen = old_context_len / low_freq_factor
|
||||
high_freq_wavelen = old_context_len / high_freq_factor
|
||||
|
||||
wavelen = 2 * math.pi / inv_freq
|
||||
# wavelen < high_freq_wavelen: do nothing
|
||||
# wavelen > low_freq_wavelen: divide by factor
|
||||
inv_freq_llama = torch.where(wavelen > low_freq_wavelen, inv_freq / factor, inv_freq)
|
||||
# otherwise: interpolate between the two, using a smooth factor
|
||||
smooth_factor = (old_context_len / wavelen - low_freq_factor) / (high_freq_factor - low_freq_factor)
|
||||
smoothed_inv_freq = (1 - smooth_factor) * inv_freq_llama / factor + smooth_factor * inv_freq_llama
|
||||
is_medium_freq = ~(wavelen < high_freq_wavelen) * ~(wavelen > low_freq_wavelen)
|
||||
inv_freq_llama = torch.where(is_medium_freq, smoothed_inv_freq, inv_freq_llama)
|
||||
|
||||
return inv_freq_llama, attention_factor
|
||||
|
||||
|
||||
# This maps the "rope_type" string field in rope config to the corresponding function to compute the RoPE parameters
|
||||
# from the model config. You can append new {'rope_type': callable} pairs to this dictionary to enable custom RoPE
|
||||
# parameterizations, as long as the callable has the same signature.
|
||||
ROPE_INIT_FUNCTIONS = {
|
||||
"default": _compute_default_rope_parameters,
|
||||
"linear": _compute_linear_scaling_rope_parameters,
|
||||
"dynamic": _compute_dynamic_ntk_parameters,
|
||||
"yarn": _compute_yarn_parameters,
|
||||
"longrope": _compute_longrope_parameters,
|
||||
"llama3": _compute_llama3_parameters,
|
||||
}
|
||||
|
||||
|
||||
def _check_received_keys(
|
||||
rope_type: str,
|
||||
received_keys: set,
|
||||
required_keys: set,
|
||||
optional_keys: set | None = None,
|
||||
ignore_keys: set | None = None,
|
||||
):
|
||||
"""Compare the received keys in `config.rope_scaling` against the expected and optional keys"""
|
||||
# BC: "rope_type" was originally "type" -- let's check for "rope_type" when "type" is present
|
||||
if "type" in received_keys:
|
||||
received_keys -= {"type"}
|
||||
required_keys.add("rope_type")
|
||||
|
||||
# Some models need to store model-specific keys, and we don't want to throw warning at them
|
||||
if ignore_keys is not None:
|
||||
received_keys -= ignore_keys
|
||||
|
||||
missing_keys = required_keys - received_keys
|
||||
if missing_keys:
|
||||
raise KeyError(f"Missing required keys in `rope_scaling` for 'rope_type'='{rope_type}': {missing_keys}")
|
||||
|
||||
if optional_keys is not None:
|
||||
unused_keys = received_keys - required_keys - optional_keys
|
||||
else:
|
||||
unused_keys = received_keys - required_keys
|
||||
if unused_keys:
|
||||
logger.warning(f"Unrecognized keys in `rope_scaling` for 'rope_type'='{rope_type}': {unused_keys}")
|
||||
|
||||
|
||||
def _validate_default_rope_parameters(config: PretrainedConfig, ignore_keys: set | None = None):
|
||||
rope_scaling = config.rope_scaling
|
||||
rope_type = rope_scaling.get("rope_type", rope_scaling.get("type", None)) # BC: "rope_type" was originally "type"
|
||||
required_keys = {"rope_type"}
|
||||
received_keys = set(rope_scaling.keys())
|
||||
_check_received_keys(rope_type, received_keys, required_keys, ignore_keys=ignore_keys)
|
||||
|
||||
|
||||
def _validate_linear_scaling_rope_parameters(config: PretrainedConfig, ignore_keys: set | None = None):
|
||||
rope_scaling = config.rope_scaling
|
||||
rope_type = rope_scaling.get("rope_type", rope_scaling.get("type", None)) # BC: "rope_type" was originally "type"
|
||||
required_keys = {"rope_type", "factor"}
|
||||
received_keys = set(rope_scaling.keys())
|
||||
_check_received_keys(rope_type, received_keys, required_keys, ignore_keys=ignore_keys)
|
||||
|
||||
factor = rope_scaling["factor"]
|
||||
if factor is None or not isinstance(factor, float) or factor < 1.0:
|
||||
logger.warning(f"`rope_scaling`'s factor field must be a float >= 1, got {factor}")
|
||||
|
||||
|
||||
def _validate_dynamic_scaling_rope_parameters(config: PretrainedConfig, ignore_keys: set | None = None):
|
||||
rope_scaling = config.rope_scaling
|
||||
rope_type = rope_scaling.get("rope_type", rope_scaling.get("type", None)) # BC: "rope_type" was originally "type"
|
||||
required_keys = {"rope_type", "factor"}
|
||||
# TODO (joao): update logic for the inclusion of `original_max_position_embeddings`
|
||||
optional_keys = {"original_max_position_embeddings"}
|
||||
received_keys = set(rope_scaling.keys())
|
||||
_check_received_keys(rope_type, received_keys, required_keys, optional_keys, ignore_keys=ignore_keys)
|
||||
|
||||
factor = rope_scaling["factor"]
|
||||
if factor is None or not isinstance(factor, float) or factor < 1.0:
|
||||
logger.warning(f"`rope_scaling`'s factor field must be a float >= 1, got {factor}")
|
||||
|
||||
|
||||
def _validate_yarn_parameters(config: PretrainedConfig, ignore_keys: set | None = None):
|
||||
rope_scaling = config.rope_scaling
|
||||
rope_type = rope_scaling.get("rope_type", rope_scaling.get("type", None)) # BC: "rope_type" was originally "type"
|
||||
required_keys = {"rope_type", "factor"}
|
||||
optional_keys = {
|
||||
"attention_factor",
|
||||
"beta_fast",
|
||||
"beta_slow",
|
||||
"original_max_position_embeddings",
|
||||
"mscale",
|
||||
"mscale_all_dim",
|
||||
}
|
||||
received_keys = set(rope_scaling.keys())
|
||||
_check_received_keys(rope_type, received_keys, required_keys, optional_keys, ignore_keys=ignore_keys)
|
||||
|
||||
factor = rope_scaling["factor"]
|
||||
if factor is None or not isinstance(factor, float) or factor < 1.0:
|
||||
logger.warning(f"`rope_scaling`'s factor field must be a float >= 1, got {factor}")
|
||||
|
||||
attention_factor = rope_scaling.get("attention_factor")
|
||||
if attention_factor is not None and (not isinstance(attention_factor, float) or attention_factor < 0):
|
||||
logger.warning(
|
||||
f"`rope_scaling`'s attention_factor field must be a float greater than 0, got {attention_factor}"
|
||||
)
|
||||
beta_fast = rope_scaling.get("beta_fast")
|
||||
if beta_fast is not None and not isinstance(beta_fast, float):
|
||||
logger.warning(f"`rope_scaling`'s beta_fast field must be a float, got {beta_fast}")
|
||||
beta_slow = rope_scaling.get("beta_slow")
|
||||
if beta_slow is not None and not isinstance(beta_slow, float):
|
||||
logger.warning(f"`rope_scaling`'s beta_slow field must be a float, got {beta_slow}")
|
||||
|
||||
if (beta_fast or 32) < (beta_slow or 1):
|
||||
logger.warning(
|
||||
f"`rope_scaling`'s beta_fast field must be greater than beta_slow, got beta_fast={beta_fast} "
|
||||
f"(defaults to 32 if None) and beta_slow={beta_slow} (defaults to 1 if None)"
|
||||
)
|
||||
|
||||
|
||||
def _validate_longrope_parameters(config: PretrainedConfig, ignore_keys: set | None = None):
|
||||
rope_scaling = config.rope_scaling
|
||||
rope_type = rope_scaling.get("rope_type", rope_scaling.get("type", None)) # BC: "rope_type" was originally "type"
|
||||
required_keys = {"rope_type", "short_factor", "long_factor"}
|
||||
# TODO (joao): update logic for the inclusion of `original_max_position_embeddings`
|
||||
optional_keys = {"attention_factor", "factor", "original_max_position_embeddings"}
|
||||
received_keys = set(rope_scaling.keys())
|
||||
_check_received_keys(rope_type, received_keys, required_keys, optional_keys, ignore_keys=ignore_keys)
|
||||
|
||||
partial_rotary_factor = config.partial_rotary_factor if hasattr(config, "partial_rotary_factor") else 1.0
|
||||
head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
||||
dim = int(head_dim * partial_rotary_factor)
|
||||
|
||||
short_factor = rope_scaling.get("short_factor")
|
||||
if not isinstance(short_factor, list) and all(isinstance(x, (int, float)) for x in short_factor):
|
||||
logger.warning(f"`rope_scaling`'s short_factor field must be a list of numbers, got {short_factor}")
|
||||
if not len(short_factor) == dim // 2:
|
||||
logger.warning(f"`rope_scaling`'s short_factor field must have length {dim // 2}, got {len(short_factor)}")
|
||||
|
||||
long_factor = rope_scaling.get("long_factor")
|
||||
if not isinstance(long_factor, list) and all(isinstance(x, (int, float)) for x in long_factor):
|
||||
logger.warning(f"`rope_scaling`'s long_factor field must be a list of numbers, got {long_factor}")
|
||||
if not len(long_factor) == dim // 2:
|
||||
logger.warning(f"`rope_scaling`'s long_factor field must have length {dim // 2}, got {len(long_factor)}")
|
||||
|
||||
# Handle Phi3 divergence: prefer the use of `attention_factor` and/or `factor` over
|
||||
# `original_max_position_embeddings` to compute internal variables. The latter lives outside `rope_scaling` and is
|
||||
# unique to longrope (= undesirable)
|
||||
if hasattr(config, "original_max_position_embeddings"):
|
||||
logger.warning_once(
|
||||
"This model has set a `original_max_position_embeddings` field, to be used together with "
|
||||
"`max_position_embeddings` to determine a scaling factor. Please set the `factor` field of `rope_scaling`"
|
||||
"with this ratio instead -- we recommend the use of this field over `original_max_position_embeddings`, "
|
||||
"as it is compatible with most model architectures."
|
||||
)
|
||||
else:
|
||||
factor = rope_scaling.get("factor")
|
||||
if factor is None:
|
||||
logger.warning("Missing required keys in `rope_scaling`: 'factor'")
|
||||
elif not isinstance(factor, float) or factor < 1.0:
|
||||
logger.warning(f"`rope_scaling`'s factor field must be a float >= 1, got {factor}")
|
||||
|
||||
attention_factor = rope_scaling.get("attention_factor")
|
||||
if attention_factor is not None:
|
||||
if not isinstance(attention_factor, float) or attention_factor < 0.0:
|
||||
logger.warning(
|
||||
f"`rope_scaling`'s attention_factor field must be a float greater than 0, got {attention_factor}"
|
||||
)
|
||||
|
||||
|
||||
def _validate_llama3_parameters(config: PretrainedConfig, ignore_keys: set | None = None):
|
||||
rope_scaling = config.rope_scaling
|
||||
rope_type = rope_scaling.get("rope_type", rope_scaling.get("type", None)) # BC: "rope_type" was originally "type"
|
||||
required_keys = {
|
||||
"rope_type",
|
||||
"factor",
|
||||
"original_max_position_embeddings",
|
||||
"low_freq_factor",
|
||||
"high_freq_factor",
|
||||
}
|
||||
received_keys = set(rope_scaling.keys())
|
||||
_check_received_keys(rope_type, received_keys, required_keys, ignore_keys=ignore_keys)
|
||||
|
||||
factor = rope_scaling["factor"]
|
||||
if factor is None or not isinstance(factor, float) or factor < 1.0:
|
||||
logger.warning(f"`rope_scaling`'s factor field must be a float >= 1, got {factor}")
|
||||
|
||||
low_freq_factor = rope_scaling["low_freq_factor"]
|
||||
high_freq_factor = rope_scaling["high_freq_factor"]
|
||||
if low_freq_factor is None or not isinstance(low_freq_factor, float):
|
||||
logger.warning(f"`rope_scaling`'s low_freq_factor field must be a float, got {low_freq_factor}")
|
||||
if high_freq_factor is None or not isinstance(high_freq_factor, float):
|
||||
logger.warning(f"`rope_scaling`'s high_freq_factor field must be a float, got {high_freq_factor}")
|
||||
if high_freq_factor <= low_freq_factor:
|
||||
logger.warning(
|
||||
"`rope_scaling`'s high_freq_factor field must be greater than low_freq_factor, got high_freq_factor="
|
||||
f"{high_freq_factor} and low_freq_factor={low_freq_factor}"
|
||||
)
|
||||
|
||||
original_max_position_embeddings = rope_scaling["original_max_position_embeddings"]
|
||||
if original_max_position_embeddings is None or not isinstance(original_max_position_embeddings, int):
|
||||
logger.warning(
|
||||
"`rope_scaling`'s original_max_position_embeddings field must be an integer, got "
|
||||
f"{original_max_position_embeddings}"
|
||||
)
|
||||
if original_max_position_embeddings >= config.max_position_embeddings:
|
||||
logger.warning(
|
||||
"`rope_scaling`'s original_max_position_embeddings field must be less than max_position_embeddings, got "
|
||||
f"{original_max_position_embeddings} and max_position_embeddings={config.max_position_embeddings}"
|
||||
)
|
||||
|
||||
|
||||
# Like `ROPE_INIT_FUNCTIONS`, this validation function mapping can be dynamically updated for custom RoPE types.
|
||||
ROPE_VALIDATION_FUNCTIONS = {
|
||||
"default": _validate_default_rope_parameters,
|
||||
"linear": _validate_linear_scaling_rope_parameters,
|
||||
"dynamic": _validate_dynamic_scaling_rope_parameters,
|
||||
"yarn": _validate_yarn_parameters,
|
||||
"longrope": _validate_longrope_parameters,
|
||||
"llama3": _validate_llama3_parameters,
|
||||
}
|
||||
|
||||
|
||||
def rope_config_validation(config: PretrainedConfig, ignore_keys: set | None = None):
|
||||
"""
|
||||
Validate the RoPE config arguments, given a `PretrainedConfig` object
|
||||
"""
|
||||
rope_scaling = getattr(config, "rope_scaling", None) # not a default parameter in `PretrainedConfig`
|
||||
if rope_scaling is None:
|
||||
return
|
||||
|
||||
# BC: "rope_type" was originally "type"
|
||||
rope_type = rope_scaling.get("rope_type", rope_scaling.get("type", "default"))
|
||||
validation_fn = ROPE_VALIDATION_FUNCTIONS.get(rope_type)
|
||||
if validation_fn is not None:
|
||||
validation_fn(config, ignore_keys=ignore_keys)
|
||||
else:
|
||||
logger.warning(
|
||||
f"Missing validation function mapping in `ROPE_VALIDATION_FUNCTIONS` for 'rope_type'='{rope_type}'"
|
||||
)
|
||||
|
||||
|
||||
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(x, cos, sin, position_ids=None, unsqueeze_dim=1):
|
||||
"""Applies Rotary Position Embedding to the query and key tensors.
|
||||
|
||||
Args:
|
||||
x (`torch.Tensor`): The input 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)
|
||||
x_embed = (x * cos) + (rotate_half(x) * sin)
|
||||
return x_embed
|
||||
@@ -0,0 +1,450 @@
|
||||
# Copyright 2025 Xiaomi Corporation.
|
||||
import typing as tp
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
import torch.nn.functional as F
|
||||
from einops import rearrange, repeat
|
||||
from torch import nn
|
||||
|
||||
|
||||
def rank():
|
||||
if dist.is_initialized():
|
||||
return dist.get_rank()
|
||||
else:
|
||||
return 0
|
||||
|
||||
|
||||
def world_size():
|
||||
if dist.is_initialized():
|
||||
return dist.get_world_size()
|
||||
else:
|
||||
return 1
|
||||
|
||||
|
||||
def default(val: tp.Any, d: tp.Any) -> tp.Any:
|
||||
return val if val is not None else d
|
||||
|
||||
|
||||
def ema_inplace(moving_avg, new, decay: float):
|
||||
if dist.is_initialized():
|
||||
dist.all_reduce(new, op=dist.ReduceOp.SUM)
|
||||
moving_avg.data.mul_(decay).add_(new, alpha=(1 - decay))
|
||||
|
||||
|
||||
def laplace_smoothing(x, n_categories: int, epsilon: float = 1e-5):
|
||||
return (x + epsilon) / (x.sum() + n_categories * epsilon)
|
||||
|
||||
|
||||
def uniform_init(*shape: int):
|
||||
t = torch.empty(shape)
|
||||
nn.init.kaiming_uniform_(t)
|
||||
return t
|
||||
|
||||
|
||||
def sample_vectors(samples, num: int):
|
||||
num_samples, device = samples.shape[0], samples.device
|
||||
|
||||
if num_samples >= num:
|
||||
indices = torch.randperm(num_samples, device=device)[:num]
|
||||
else:
|
||||
indices = torch.randint(0, num_samples, (num,), device=device)
|
||||
|
||||
selected_samples = samples[indices]
|
||||
|
||||
if dist.is_initialized():
|
||||
dist.broadcast(selected_samples, src=0)
|
||||
|
||||
return selected_samples
|
||||
|
||||
|
||||
def kmeans(samples, num_clusters: int, num_iters: int = 10):
|
||||
dim, dtype = samples.shape[-1], samples.dtype
|
||||
|
||||
means = sample_vectors(samples, num_clusters)
|
||||
|
||||
for _ in range(num_iters):
|
||||
dists = -(samples.pow(2).sum(1, keepdim=True) - 2 * samples @ means.t() + means.t().pow(2).sum(0, keepdim=True))
|
||||
|
||||
buckets = dists.max(dim=-1).indices
|
||||
bins = torch.bincount(buckets, minlength=num_clusters)
|
||||
|
||||
new_means = buckets.new_zeros(num_clusters, dim, dtype=dtype)
|
||||
new_means = new_means.scatter_add_(0, repeat(buckets, "n -> n d", d=dim), samples)
|
||||
|
||||
if dist.is_initialized():
|
||||
dist.all_reduce(bins, op=dist.ReduceOp.SUM)
|
||||
dist.all_reduce(new_means, op=dist.ReduceOp.SUM)
|
||||
|
||||
zero_mask = bins == 0
|
||||
bins_min_clamped = bins.masked_fill(zero_mask, 1)
|
||||
|
||||
new_means = new_means / bins_min_clamped[..., None]
|
||||
|
||||
means = torch.where(zero_mask[..., None], means, new_means)
|
||||
|
||||
return means, bins
|
||||
|
||||
|
||||
class EuclideanCodebook(nn.Module):
|
||||
"""Codebook with Euclidean distance.
|
||||
Args:
|
||||
dim (int): Dimension.
|
||||
codebook_size (int): Codebook size.
|
||||
kmeans_init (bool): Whether to use k-means to initialize the codebooks.
|
||||
If set to true, run the k-means algorithm on the first training batch and use
|
||||
the learned centroids as initialization.
|
||||
kmeans_iters (int): Number of iterations used for k-means algorithm at initialization.
|
||||
decay (float): Decay for exponential moving average over the codebooks.
|
||||
epsilon (float): Epsilon value for numerical stability.
|
||||
threshold_ema_dead_code (int): Threshold for dead code expiration. Replace any codes
|
||||
that have an exponential moving average cluster size less than the specified threshold with
|
||||
randomly selected vector from the current batch.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
dim: int,
|
||||
codebook_size: int,
|
||||
kmeans_init: int = False,
|
||||
kmeans_iters: int = 10,
|
||||
decay: float = 0.99,
|
||||
epsilon: float = 1e-5,
|
||||
threshold_ema_dead_code: int = 2,
|
||||
):
|
||||
super().__init__()
|
||||
self.decay = decay
|
||||
init_fn: tp.Callable[..., torch.Tensor] | tp.Any = uniform_init if not kmeans_init else torch.zeros
|
||||
embed = init_fn(codebook_size, dim)
|
||||
|
||||
self.codebook_size = codebook_size
|
||||
|
||||
self.kmeans_iters = kmeans_iters
|
||||
self.epsilon = epsilon
|
||||
self.threshold_ema_dead_code = threshold_ema_dead_code
|
||||
|
||||
self.register_buffer("inited", torch.Tensor([not kmeans_init]))
|
||||
self.register_buffer("cluster_size", torch.zeros(codebook_size))
|
||||
self.register_buffer("embed", embed)
|
||||
self.register_buffer("embed_avg", embed.clone())
|
||||
|
||||
@torch.jit.ignore
|
||||
def init_embed_(self, data):
|
||||
if self.inited:
|
||||
return
|
||||
|
||||
embed, cluster_size = kmeans(data, self.codebook_size, self.kmeans_iters)
|
||||
self.embed.data.copy_(embed)
|
||||
self.embed_avg.data.copy_(embed.clone())
|
||||
self.cluster_size.data.copy_(cluster_size)
|
||||
self.inited.data.copy_(torch.Tensor([True]))
|
||||
|
||||
def replace_(self, samples, mask):
|
||||
# modified_codebook = torch.where(
|
||||
# mask[..., None], sample_vectors(samples, self.codebook_size), self.embed
|
||||
# )
|
||||
replace_num = mask.sum()
|
||||
modified_codebook = self.embed.clone()
|
||||
modified_codebook[mask] = sample_vectors(samples, replace_num)
|
||||
self.embed.data.copy_(modified_codebook)
|
||||
|
||||
def expire_codes_(self, batch_samples):
|
||||
if self.threshold_ema_dead_code == 0:
|
||||
return
|
||||
|
||||
expired_codes = self.cluster_size < self.threshold_ema_dead_code
|
||||
if not torch.any(expired_codes):
|
||||
return
|
||||
|
||||
batch_samples = rearrange(batch_samples, "... d -> (...) d")
|
||||
self.replace_(batch_samples, mask=expired_codes)
|
||||
|
||||
def preprocess(self, x):
|
||||
x = rearrange(x, "... d -> (...) d")
|
||||
return x
|
||||
|
||||
def quantize(self, x):
|
||||
embed = self.embed.t()
|
||||
dist = -(x.pow(2).sum(1, keepdim=True) - 2 * x @ embed + embed.pow(2).sum(0, keepdim=True))
|
||||
embed_ind = dist.max(dim=-1).indices
|
||||
return embed_ind
|
||||
|
||||
def postprocess_emb(self, embed_ind, shape):
|
||||
return embed_ind.view(*shape[:-1])
|
||||
|
||||
def dequantize(self, embed_ind):
|
||||
quantize = F.embedding(embed_ind, self.embed)
|
||||
return quantize
|
||||
|
||||
def encode(self, x):
|
||||
shape = x.shape
|
||||
# pre-process
|
||||
x = self.preprocess(x)
|
||||
# quantize
|
||||
embed_ind = self.quantize(x)
|
||||
# post-process
|
||||
embed_ind = self.postprocess_emb(embed_ind, shape)
|
||||
return embed_ind
|
||||
|
||||
def decode(self, embed_ind):
|
||||
quantize = self.dequantize(embed_ind)
|
||||
return quantize
|
||||
|
||||
def forward(self, x):
|
||||
shape, dtype = x.shape, x.dtype
|
||||
x = self.preprocess(x)
|
||||
|
||||
self.init_embed_(x)
|
||||
|
||||
embed_ind = self.quantize(x)
|
||||
embed_onehot = F.one_hot(embed_ind, self.codebook_size).type(dtype)
|
||||
embed_ind = self.postprocess_emb(embed_ind, shape)
|
||||
quantize = self.dequantize(embed_ind)
|
||||
|
||||
if self.training:
|
||||
# We do the expiry of code at that point as buffers are in sync
|
||||
# and all the workers will take the same decision.
|
||||
self.expire_codes_(x)
|
||||
ema_inplace(self.cluster_size, embed_onehot.sum(0), self.decay)
|
||||
embed_sum = x.t() @ embed_onehot
|
||||
ema_inplace(self.embed_avg, embed_sum.t().contiguous(), self.decay)
|
||||
cluster_size = (
|
||||
laplace_smoothing(self.cluster_size, self.codebook_size, self.epsilon) * self.cluster_size.sum()
|
||||
)
|
||||
embed_normalized = self.embed_avg / cluster_size.unsqueeze(1)
|
||||
self.embed.data.copy_(embed_normalized)
|
||||
|
||||
return quantize, embed_ind
|
||||
|
||||
|
||||
class VectorQuantization(nn.Module):
|
||||
"""Vector quantization implementation.
|
||||
Currently supports only euclidean distance.
|
||||
Args:
|
||||
dim (int): Dimension
|
||||
codebook_size (int): Codebook size
|
||||
codebook_dim (int): Codebook dimension. If not defined, uses the specified dimension in dim.
|
||||
decay (float): Decay for exponential moving average over the codebooks.
|
||||
epsilon (float): Epsilon value for numerical stability.
|
||||
kmeans_init (bool): Whether to use kmeans to initialize the codebooks.
|
||||
kmeans_iters (int): Number of iterations used for kmeans initialization.
|
||||
threshold_ema_dead_code (int): Threshold for dead code expiration. Replace any codes
|
||||
that have an exponential moving average cluster size less than the specified threshold with
|
||||
randomly selected vector from the current batch.
|
||||
commitment_weight (float): Weight for commitment loss.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
dim: int,
|
||||
codebook_size: int,
|
||||
codebook_dim: int | None = None,
|
||||
decay: float = 0.99,
|
||||
epsilon: float = 1e-5,
|
||||
kmeans_init: bool = True,
|
||||
kmeans_iters: int = 50,
|
||||
threshold_ema_dead_code: int = 2,
|
||||
commitment_weight: float = 1.0,
|
||||
):
|
||||
super().__init__()
|
||||
_codebook_dim: int = default(codebook_dim, dim)
|
||||
|
||||
requires_projection = _codebook_dim != dim
|
||||
self.project_in = nn.Linear(dim, _codebook_dim) if requires_projection else nn.Identity()
|
||||
self.project_out = nn.Linear(_codebook_dim, dim) if requires_projection else nn.Identity()
|
||||
|
||||
self.epsilon = epsilon
|
||||
self.commitment_weight = commitment_weight
|
||||
|
||||
self._codebook = EuclideanCodebook(
|
||||
dim=_codebook_dim,
|
||||
codebook_size=codebook_size,
|
||||
kmeans_init=kmeans_init,
|
||||
kmeans_iters=kmeans_iters,
|
||||
decay=decay,
|
||||
epsilon=epsilon,
|
||||
threshold_ema_dead_code=threshold_ema_dead_code,
|
||||
)
|
||||
self.codebook_size = codebook_size
|
||||
|
||||
@property
|
||||
def codebook(self):
|
||||
return self._codebook.embed
|
||||
|
||||
def encode(self, x):
|
||||
# x = rearrange(x, "b d n -> b n d")
|
||||
x = self.project_in(x)
|
||||
embed_in = self._codebook.encode(x)
|
||||
return embed_in
|
||||
|
||||
def decode(self, embed_ind):
|
||||
quantize = self._codebook.decode(embed_ind)
|
||||
quantize = self.project_out(quantize)
|
||||
# quantize = rearrange(quantize, "b n d -> b d n")
|
||||
return quantize
|
||||
|
||||
def forward(self, x):
|
||||
device = x.device
|
||||
x = self.project_in(x)
|
||||
|
||||
quantize, embed_ind = self._codebook(x)
|
||||
|
||||
if self.training:
|
||||
quantize = x + (quantize - x).detach()
|
||||
|
||||
loss = torch.tensor([0.0], device=device, requires_grad=self.training)
|
||||
|
||||
if self.training:
|
||||
if self.commitment_weight > 0:
|
||||
commit_loss = F.mse_loss(quantize.detach(), x)
|
||||
loss = loss + commit_loss * self.commitment_weight
|
||||
|
||||
quantize = self.project_out(quantize)
|
||||
# quantize = rearrange(quantize, "b n d -> b d n")
|
||||
return quantize, embed_ind, loss
|
||||
|
||||
|
||||
class ResidualVectorQuantization(nn.Module):
|
||||
"""Residual vector quantization implementation.
|
||||
Follows Algorithm 1. in https://arxiv.org/pdf/2107.03312.pdf
|
||||
"""
|
||||
|
||||
def __init__(self, *, num_quantizers, codebook_size, **kwargs):
|
||||
super().__init__()
|
||||
if isinstance(codebook_size, int):
|
||||
codebook_size = [codebook_size] * num_quantizers
|
||||
elif len(codebook_size) < num_quantizers:
|
||||
codebook_size += [codebook_size[-1]] * (num_quantizers - len(codebook_size))
|
||||
self.layers = nn.ModuleList(
|
||||
[VectorQuantization(codebook_size=codebook_size[i], **kwargs) for i in range(num_quantizers)]
|
||||
)
|
||||
|
||||
def forward(self, x, n_q: int | None = None, layers: list | None = None):
|
||||
quantized_out = 0.0
|
||||
residual = x
|
||||
|
||||
all_losses = []
|
||||
all_indices = []
|
||||
out_quantized = []
|
||||
|
||||
n_q = n_q or len(self.layers)
|
||||
|
||||
for i, layer in enumerate(self.layers[:n_q]):
|
||||
quantized, indices, loss = layer(residual)
|
||||
residual = residual - quantized
|
||||
quantized_out = quantized_out + quantized
|
||||
|
||||
all_indices.append(indices)
|
||||
all_losses.append(loss)
|
||||
if layers and i in layers:
|
||||
out_quantized.append(quantized_out)
|
||||
|
||||
out_losses, out_indices = map(torch.stack, (all_losses, all_indices))
|
||||
return quantized_out, out_indices, out_losses, out_quantized
|
||||
|
||||
def encode(self, x: torch.Tensor, n_q: int | None = None, st: int | None = None) -> torch.Tensor:
|
||||
residual = x
|
||||
all_indices = []
|
||||
n_q = len(self.layers) if n_q is None else n_q
|
||||
st = 0 if st is None else st
|
||||
for layer in self.layers[st:n_q]:
|
||||
indices = layer.encode(residual)
|
||||
quantized = layer.decode(indices)
|
||||
residual = residual - quantized
|
||||
all_indices.append(indices)
|
||||
out_indices = torch.stack(all_indices)
|
||||
return out_indices
|
||||
|
||||
def decode(self, q_indices: torch.Tensor, st: int = 0) -> torch.Tensor:
|
||||
quantized_out = torch.tensor(0.0, device=q_indices.device)
|
||||
for i, indices in enumerate(q_indices):
|
||||
layer = self.layers[st + i]
|
||||
quantized = layer.decode(indices)
|
||||
quantized_out = quantized_out + quantized
|
||||
return quantized_out
|
||||
|
||||
|
||||
class ResidualVectorQuantizer(nn.Module):
|
||||
"""Residual Vector Quantizer.
|
||||
Args:
|
||||
dimension (int): Dimension of the codebooks.
|
||||
n_q (int): Number of residual vector quantizers used.
|
||||
bins (int): Codebook size.
|
||||
decay (float): Decay for exponential moving average over the codebooks.
|
||||
kmeans_init (bool): Whether to use kmeans to initialize the codebooks.
|
||||
kmeans_iters (int): Number of iterations used for kmeans initialization.
|
||||
threshold_ema_dead_code (int): Threshold for dead code expiration. Replace any codes
|
||||
that have an exponential moving average cluster size less than the specified threshold with
|
||||
randomly selected vector from the current batch.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
dimension: int = 256,
|
||||
n_q: int = 8,
|
||||
bins: int | list = 1024,
|
||||
decay: float = 0.99,
|
||||
kmeans_init: bool = True,
|
||||
kmeans_iters: int = 50,
|
||||
threshold_ema_dead_code: int = 2,
|
||||
):
|
||||
super().__init__()
|
||||
self.n_q = n_q
|
||||
self.dimension = dimension
|
||||
self.bins = bins
|
||||
self.decay = decay
|
||||
self.kmeans_init = kmeans_init
|
||||
self.kmeans_iters = kmeans_iters
|
||||
self.threshold_ema_dead_code = threshold_ema_dead_code
|
||||
self.vq = ResidualVectorQuantization(
|
||||
dim=self.dimension,
|
||||
codebook_size=self.bins,
|
||||
num_quantizers=self.n_q,
|
||||
decay=self.decay,
|
||||
kmeans_init=self.kmeans_init,
|
||||
kmeans_iters=self.kmeans_iters,
|
||||
threshold_ema_dead_code=self.threshold_ema_dead_code,
|
||||
)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
n_q: int | None = None,
|
||||
layers: list | None = None,
|
||||
):
|
||||
"""Residual vector quantization on the given input tensor.
|
||||
Args:
|
||||
x (torch.Tensor): Input tensor.
|
||||
n_q (int): Number of quantizer used to quantize. Default: All quantizers.
|
||||
layers (list): Layer that need to return quantized. Default: None.
|
||||
Returns:
|
||||
QuantizedResult:
|
||||
The quantized (or approximately quantized) representation with
|
||||
the associated number quantizers and layer quantized required to return.
|
||||
"""
|
||||
n_q = n_q if n_q else self.n_q
|
||||
quantized, codes, commit_loss, quantized_list = self.vq(x, n_q=n_q, layers=layers)
|
||||
return quantized, codes, torch.mean(commit_loss), quantized_list
|
||||
|
||||
def encode(self, x: torch.Tensor, n_q: int | None = None, st: int | None = None) -> torch.Tensor:
|
||||
"""Encode a given input tensor with the specified sample rate at the given bandwidth.
|
||||
The RVQ encode method sets the appropriate number of quantizer to use
|
||||
and returns indices for each quantizer.
|
||||
Args:
|
||||
x (torch.Tensor): Input tensor.
|
||||
n_q (int): Number of quantizer used to quantize. Default: All quantizers.
|
||||
st (int): Start to encode input from which layers. Default: 0.
|
||||
"""
|
||||
n_q = n_q if n_q else self.n_q
|
||||
st = st or 0
|
||||
codes = self.vq.encode(x, n_q=n_q, st=st)
|
||||
return codes
|
||||
|
||||
def decode(self, codes: torch.Tensor, st: int = 0) -> torch.Tensor:
|
||||
"""Decode the given codes to the quantized representation.
|
||||
Args:
|
||||
codes (torch.Tensor): Input indices for each quantizer.
|
||||
st (int): Start to decode input codes from which layers. Default: 0.
|
||||
"""
|
||||
quantized = self.vq.decode(codes, st=st)
|
||||
return quantized
|
||||
@@ -628,7 +628,7 @@ class Qwen2_5OmniForConditionalGeneration(
|
||||
return set(["thinker_embedding.weight", "talker_embedding.weight"])
|
||||
|
||||
def _get_embed_text_spk_token(self, voice_type: str):
|
||||
if voice_type not in self.embed_text_spk_tokens:
|
||||
if not hasattr(self, "embed_text_spk_tokens") or voice_type not in self.embed_text_spk_tokens:
|
||||
return self.embed_text_bos_token
|
||||
return self.embed_text_spk_tokens[voice_type]
|
||||
|
||||
|
||||
@@ -47,7 +47,6 @@ from vllm.model_executor.models.qwen2_5_vl import (
|
||||
from vllm.model_executor.models.utils import (
|
||||
AutoWeightsLoader,
|
||||
WeightsMapper,
|
||||
_merge_multimodal_embeddings,
|
||||
init_vllm_registered_model,
|
||||
maybe_prefix,
|
||||
split_list_into_ranges,
|
||||
@@ -589,22 +588,12 @@ class Qwen2_5OmniThinkerForConditionalGeneration(
|
||||
is_multimodal: torch.Tensor | None = None,
|
||||
handle_oov_mm_token: bool = False,
|
||||
) -> torch.Tensor:
|
||||
# This is to satisfy the type checker for each overload
|
||||
if multimodal_embeddings is None or is_multimodal is None:
|
||||
return super().embed_input_ids(input_ids)
|
||||
|
||||
inputs_embeds = self._embed_text_input_ids(
|
||||
input_ids,
|
||||
self.get_language_model().embed_input_ids,
|
||||
is_multimodal=is_multimodal,
|
||||
handle_oov_mm_token=handle_oov_mm_token,
|
||||
)
|
||||
|
||||
if len(multimodal_embeddings) == 0:
|
||||
return inputs_embeds
|
||||
|
||||
# Check for audio-in-video: interleaved video and audio tokens
|
||||
# in the multimodal region.
|
||||
# in the multimodal region. Only use the interleaved path when
|
||||
# needed; otherwise fall back to the default parent implementation.
|
||||
video_token_id = self.config.video_token_index
|
||||
audio_token_id = self.config.audio_token_index
|
||||
|
||||
@@ -615,6 +604,12 @@ class Qwen2_5OmniThinkerForConditionalGeneration(
|
||||
num_audio = is_audio.sum().item()
|
||||
|
||||
if check_interleaved_audio_video(is_video, is_audio, num_video, num_audio):
|
||||
inputs_embeds = self._embed_text_input_ids(
|
||||
input_ids,
|
||||
self.get_language_model().embed_input_ids,
|
||||
is_multimodal=is_multimodal,
|
||||
handle_oov_mm_token=handle_oov_mm_token,
|
||||
)
|
||||
return merge_interleaved_embeddings(
|
||||
inputs_embeds,
|
||||
multimodal_embeddings,
|
||||
@@ -625,8 +620,13 @@ class Qwen2_5OmniThinkerForConditionalGeneration(
|
||||
num_audio,
|
||||
)
|
||||
|
||||
# Default: standard merge (no interleaving)
|
||||
return _merge_multimodal_embeddings(inputs_embeds, multimodal_embeddings, is_multimodal)
|
||||
# Default: standard merge (no interleaving), same as parent class
|
||||
return super().embed_input_ids(
|
||||
input_ids,
|
||||
multimodal_embeddings=multimodal_embeddings,
|
||||
is_multimodal=is_multimodal,
|
||||
handle_oov_mm_token=handle_oov_mm_token,
|
||||
)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
|
||||
@@ -155,6 +155,8 @@ class Qwen3OmniMoeForConditionalGeneration(
|
||||
|
||||
# for CI: Initialize special tokens embeddings early to avoid AttributeError when loading dummy weights
|
||||
self._init_special_tokens_embeddings()
|
||||
# suppress tokens by setting their probability to ~1e-9 (finite very small)
|
||||
self.suppressed_tokens = self._get_talker_suppressed_tokens()
|
||||
self.requires_raw_input_tokens = True
|
||||
|
||||
elif self.model_stage == "code2wav":
|
||||
@@ -1067,18 +1069,16 @@ class Qwen3OmniMoeForConditionalGeneration(
|
||||
# implemented by assigning their logits to log(1e-9).
|
||||
|
||||
if getattr(self, "model_stage", None) == "talker" and isinstance(logits, torch.Tensor):
|
||||
# suppress tokens by setting their probability to ~1e-9 (finite very small)
|
||||
suppressed_tokens = self._get_talker_suppressed_tokens()
|
||||
try:
|
||||
logits_cpu = logits.cpu()
|
||||
logits_cpu[:, suppressed_tokens] = -1e9
|
||||
logits_cpu[:, self.suppressed_tokens] = -1e9
|
||||
logits = logits_cpu.to(logits.device)
|
||||
except Exception as e:
|
||||
print(f"Error in logits suppression: {e}")
|
||||
print(f"logits.shape: {logits.shape}")
|
||||
print(f"suppressed_tokens: {suppressed_tokens}")
|
||||
print(f"self.suppressed_tokens: {self.suppressed_tokens}")
|
||||
raise e
|
||||
logits[:, suppressed_tokens] = -1e9
|
||||
logits[:, self.suppressed_tokens] = -1e9
|
||||
return logits
|
||||
|
||||
def sample(
|
||||
|
||||
@@ -99,8 +99,8 @@ class Qwen3OmniMoeTalkerForConditionalGeneration(
|
||||
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
|
||||
super().__init__()
|
||||
talker_config: Qwen3OmniMoeTalkerConfig = vllm_config.model_config.hf_config
|
||||
# rope_scaling already contains rope_theta, just assign it to rope_parameters
|
||||
talker_config.text_config.rope_parameters = talker_config.text_config.rope_scaling
|
||||
talker_config.text_config.rope_parameters["rope_theta"] = talker_config.text_config.rope_theta
|
||||
self.quant_config = vllm_config.quant_config
|
||||
self.prefix = prefix
|
||||
self.vllm_config = vllm_config
|
||||
|
||||
@@ -936,15 +936,17 @@ class Qwen3OmniMoeThinkerForConditionalGeneration(
|
||||
num_audio,
|
||||
)
|
||||
|
||||
# Default: standard merge (no interleaving)
|
||||
inputs_embeds = _merge_multimodal_embeddings(
|
||||
inputs_embeds=inputs_embeds,
|
||||
# Default: standard merge (no interleaving), same as parent class.
|
||||
# multimodal_embeddings may have been updated above (deepstack
|
||||
# main-scale). Use super() to stay consistent with the parent
|
||||
# implementation and avoid issues seen in Qwen2.5-Omni (#34506).
|
||||
return super().embed_input_ids(
|
||||
input_ids,
|
||||
multimodal_embeddings=multimodal_embeddings,
|
||||
is_multimodal=is_multimodal,
|
||||
handle_oov_mm_token=handle_oov_mm_token,
|
||||
)
|
||||
|
||||
return inputs_embeds
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.Tensor,
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
# Copyright 2026 The Alibaba Qwen team.
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""
|
||||
CUDA Graph wrapper for Qwen3TTSTokenizerV2Decoder.
|
||||
|
||||
This module provides CUDA Graph acceleration for the speech tokenizer decoder,
|
||||
reducing kernel launch overhead during inference.
|
||||
"""
|
||||
|
||||
import torch
|
||||
from torch.cuda import CUDAGraph
|
||||
from vllm.logger import init_logger
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class CUDAGraphDecoderWrapper:
|
||||
"""
|
||||
CUDA Graph wrapper for Qwen3TTSTokenizerV2Decoder.
|
||||
|
||||
This wrapper captures the decoder forward pass for fixed input sizes
|
||||
and replays them during inference to reduce kernel launch overhead.
|
||||
|
||||
Usage:
|
||||
wrapper = CUDAGraphDecoderWrapper(decoder, capture_sizes=[25, 50, 100, 200, 300])
|
||||
wrapper.warmup(device)
|
||||
|
||||
# During inference:
|
||||
output = wrapper.decode(codes) # Automatically uses CUDA graph if possible
|
||||
"""
|
||||
|
||||
DEFAULT_CAPTURE_SIZES = [25, 50, 100, 150, 200, 250, 300]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
decoder: torch.nn.Module,
|
||||
capture_sizes: list[int] | None = None,
|
||||
num_quantizers: int = 8,
|
||||
enabled: bool = True,
|
||||
):
|
||||
self.decoder = decoder
|
||||
self.capture_sizes = capture_sizes or self.DEFAULT_CAPTURE_SIZES
|
||||
self.num_quantizers = num_quantizers
|
||||
self.enabled = enabled
|
||||
|
||||
self.graphs: dict[int, CUDAGraph] = {}
|
||||
self.static_inputs: dict[int, torch.Tensor] = {}
|
||||
self.static_outputs: dict[int, torch.Tensor] = {}
|
||||
|
||||
self._warmed_up = False
|
||||
self._device = None
|
||||
|
||||
def _get_padded_size(self, actual_size: int) -> int | None:
|
||||
for size in self.capture_sizes:
|
||||
if actual_size <= size:
|
||||
return size
|
||||
return None
|
||||
|
||||
def warmup(self, device: torch.device, dtype: torch.dtype = torch.long):
|
||||
if device.type != "cuda":
|
||||
logger.info("CUDA Graph warmup skipped: device %s is not CUDA", device)
|
||||
return
|
||||
|
||||
if not self.enabled:
|
||||
logger.info("CUDA Graph is disabled, skipping warmup")
|
||||
return
|
||||
|
||||
if self._warmed_up:
|
||||
logger.warning("CUDA Graph already warmed up, skipping")
|
||||
return
|
||||
|
||||
self._device = device
|
||||
self.decoder.eval()
|
||||
|
||||
logger.info("Starting CUDA Graph warmup for %d sizes: %s", len(self.capture_sizes), self.capture_sizes)
|
||||
|
||||
# Warmup runs to ensure CUDA memory is allocated
|
||||
for size in self.capture_sizes:
|
||||
dummy_codes = torch.zeros(
|
||||
1,
|
||||
self.num_quantizers,
|
||||
size,
|
||||
dtype=dtype,
|
||||
device=device,
|
||||
)
|
||||
with torch.no_grad():
|
||||
_ = self.decoder(dummy_codes)
|
||||
|
||||
torch.cuda.synchronize(device)
|
||||
|
||||
for size in self.capture_sizes:
|
||||
try:
|
||||
self._capture_graph_for_size(size, device, dtype)
|
||||
logger.info(" Captured CUDA Graph for size=%d", size)
|
||||
except Exception:
|
||||
logger.warning(" Failed to capture CUDA Graph for size=%d", size, exc_info=True)
|
||||
|
||||
self._warmed_up = True
|
||||
logger.info("CUDA Graph warmup complete. Captured %d graphs.", len(self.graphs))
|
||||
|
||||
def _capture_graph_for_size(self, size: int, device: torch.device, dtype: torch.dtype):
|
||||
static_input = torch.zeros(
|
||||
1,
|
||||
self.num_quantizers,
|
||||
size,
|
||||
dtype=dtype,
|
||||
device=device,
|
||||
)
|
||||
|
||||
with torch.no_grad():
|
||||
_ = self.decoder(static_input)
|
||||
|
||||
torch.cuda.synchronize(device)
|
||||
|
||||
graph = CUDAGraph()
|
||||
with torch.no_grad():
|
||||
with torch.cuda.graph(graph):
|
||||
static_output = self.decoder(static_input)
|
||||
|
||||
self.graphs[size] = graph
|
||||
self.static_inputs[size] = static_input
|
||||
self.static_outputs[size] = static_output
|
||||
|
||||
def decode(self, codes: torch.Tensor) -> torch.Tensor:
|
||||
if not self.enabled or not self._warmed_up:
|
||||
return self.decoder(codes)
|
||||
|
||||
if codes.shape[0] != 1:
|
||||
return self.decoder(codes)
|
||||
|
||||
actual_size = codes.shape[-1]
|
||||
padded_size = self._get_padded_size(actual_size)
|
||||
|
||||
if padded_size is None or padded_size not in self.graphs:
|
||||
return self.decoder(codes)
|
||||
|
||||
self.static_inputs[padded_size].zero_()
|
||||
self.static_inputs[padded_size][:, :, :actual_size] = codes
|
||||
|
||||
self.graphs[padded_size].replay()
|
||||
|
||||
output = self.static_outputs[padded_size]
|
||||
total_upsample = self.decoder.total_upsample
|
||||
actual_output_len = actual_size * total_upsample
|
||||
|
||||
return output[..., :actual_output_len].clone()
|
||||
|
||||
def chunked_decode_with_cudagraph(
|
||||
self,
|
||||
codes: torch.Tensor,
|
||||
chunk_size: int = 300,
|
||||
left_context_size: int = 25,
|
||||
) -> torch.Tensor:
|
||||
wavs = []
|
||||
start_index = 0
|
||||
total_len = codes.shape[-1]
|
||||
total_upsample = self.decoder.total_upsample
|
||||
|
||||
while start_index < total_len:
|
||||
end_index = min(start_index + chunk_size, total_len)
|
||||
context_size = left_context_size if start_index - left_context_size > 0 else start_index
|
||||
|
||||
codes_chunk = codes[..., start_index - context_size : end_index]
|
||||
wav_chunk = self.decode(codes_chunk)
|
||||
|
||||
wavs.append(wav_chunk[..., context_size * total_upsample :])
|
||||
start_index = end_index
|
||||
|
||||
return torch.cat(wavs, dim=-1)
|
||||
@@ -100,6 +100,33 @@ class Qwen3TTSModelForGeneration(nn.Module):
|
||||
# Store vllm_config for potential future use
|
||||
self.vllm_config = vllm_config
|
||||
|
||||
# Enable CUDA Graph for decoder
|
||||
self._enable_decoder_cudagraph()
|
||||
|
||||
def _enable_decoder_cudagraph(self):
|
||||
# Respect --enforce-eager flag
|
||||
model_cfg = getattr(self.vllm_config, "model_config", None)
|
||||
if model_cfg and getattr(model_cfg, "enforce_eager", False):
|
||||
logger.info("CUDA Graph not enabled: --enforce-eager is set")
|
||||
return
|
||||
try:
|
||||
inner_model = getattr(self.model, "model", None)
|
||||
if inner_model is None or not hasattr(inner_model, "speech_tokenizer"):
|
||||
return
|
||||
tokenizer = inner_model.speech_tokenizer
|
||||
if not (hasattr(tokenizer, "model") and hasattr(tokenizer.model, "decoder")):
|
||||
return
|
||||
decoder = tokenizer.model.decoder
|
||||
device = next(decoder.parameters()).device
|
||||
if device.type != "cuda":
|
||||
logger.info("CUDA Graph not enabled: decoder is on %s", device)
|
||||
return
|
||||
if hasattr(decoder, "enable_cudagraph"):
|
||||
decoder.enable_cudagraph()
|
||||
logger.info("CUDA Graph enabled for speech tokenizer decoder")
|
||||
except Exception:
|
||||
logger.warning("Failed to enable CUDA Graph for decoder", exc_info=True)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.Tensor | None = None,
|
||||
|
||||
@@ -18,6 +18,8 @@ from vllm.model_executor.models.utils import is_pp_missing_parameter
|
||||
from vllm.v1.kv_cache_interface import KVCacheConfig, KVCacheGroupSpec, KVCacheSpec, KVCacheTensor
|
||||
from vllm.v1.worker.gpu import attn_utils
|
||||
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
from .configuration_qwen3_tts import Qwen3TTSTalkerCodePredictorConfig, Qwen3TTSTalkerConfig
|
||||
|
||||
|
||||
@@ -149,19 +151,37 @@ class _LocalPredictorKVCache:
|
||||
block_table = self._block_table[:num_reqs].contiguous()
|
||||
slot_mapping_gpu = slot_mapping.to(device=self.device)
|
||||
|
||||
attn_metadata = attn_utils.build_attn_metadata(
|
||||
self.attn_metadata_builders,
|
||||
num_reqs=num_reqs,
|
||||
num_tokens=num_tokens,
|
||||
query_start_loc_gpu=query_start_loc_gpu,
|
||||
query_start_loc_cpu=qsl,
|
||||
max_query_len=max_query_len,
|
||||
seq_lens=seq_lens_gpu,
|
||||
max_seq_len=max_seq_len,
|
||||
block_tables=[block_table],
|
||||
slot_mappings=[slot_mapping_gpu],
|
||||
kv_cache_config=self.kv_cache_config,
|
||||
)
|
||||
if current_omni_platform.is_npu():
|
||||
from vllm_ascend.worker.v2 import attn_utils as attn_utils_npu
|
||||
|
||||
max_query_len = int(query_lens_i32[:num_reqs].max().item())
|
||||
slot_mappings_tensor = slot_mapping_gpu.unsqueeze(0)
|
||||
attn_metadata = attn_utils_npu.build_attn_metadata(
|
||||
attn_metadata_builders=self.attn_metadata_builders,
|
||||
num_reqs=num_reqs,
|
||||
num_tokens=num_tokens,
|
||||
query_start_loc_gpu=query_start_loc_gpu,
|
||||
query_start_loc_cpu=qsl,
|
||||
max_query_len=max_query_len,
|
||||
seq_lens=seq_lens_gpu,
|
||||
max_seq_len=max_seq_len,
|
||||
block_tables=[block_table],
|
||||
slot_mappings=slot_mappings_tensor,
|
||||
kv_cache_config=self.kv_cache_config,
|
||||
)
|
||||
else:
|
||||
attn_metadata = attn_utils.build_attn_metadata(
|
||||
self.attn_metadata_builders,
|
||||
num_reqs=num_reqs,
|
||||
num_tokens=num_tokens,
|
||||
query_start_loc_gpu=query_start_loc_gpu,
|
||||
query_start_loc_cpu=qsl,
|
||||
seq_lens=seq_lens_gpu,
|
||||
max_seq_len=max_seq_len,
|
||||
block_tables=[block_table],
|
||||
slot_mappings=[slot_mapping_gpu],
|
||||
kv_cache_config=self.kv_cache_config,
|
||||
)
|
||||
|
||||
# Build slot_mappings_by_layer for set_forward_context.
|
||||
# Fix for vllm 0.15.0
|
||||
|
||||
@@ -328,7 +328,7 @@ class Qwen3TTSTokenizer:
|
||||
else:
|
||||
# List[Tensor/np]
|
||||
audio_codes_list = [_to_tensor(c, dtype=torch.long) for c in audio_codes_list]
|
||||
audio_codes_padded = pad_sequence(audio_codes_list, batch_first=True, padding_value=0).to(self.device)
|
||||
audio_codes_padded = pad_sequence(audio_codes_list, batch_first=True, padding_value=-1).to(self.device)
|
||||
|
||||
with torch.inference_mode():
|
||||
if model_type == "qwen3_tts_tokenizer_25hz":
|
||||
|
||||
+39
-1
@@ -848,6 +848,38 @@ class Qwen3TTSTokenizerV2Decoder(Qwen3TTSTokenizerV2DecoderPreTrainedModel):
|
||||
|
||||
self.post_init()
|
||||
|
||||
# CUDA Graph support
|
||||
self._cudagraph_enabled = False
|
||||
self._cudagraph_wrapper = None
|
||||
|
||||
def enable_cudagraph(
|
||||
self,
|
||||
capture_sizes: list[int] | None = None,
|
||||
device: torch.device | None = None,
|
||||
):
|
||||
from ..cuda_graph_decoder_wrapper import CUDAGraphDecoderWrapper
|
||||
|
||||
if device is None:
|
||||
device = next(self.parameters()).device
|
||||
if device.type != "cuda":
|
||||
logger.warning("Cannot enable CUDA Graph: decoder is not on a CUDA device (got %s)", device)
|
||||
return
|
||||
self._cudagraph_wrapper = CUDAGraphDecoderWrapper(
|
||||
decoder=self,
|
||||
capture_sizes=capture_sizes,
|
||||
num_quantizers=self.config.num_quantizers,
|
||||
enabled=True,
|
||||
)
|
||||
self._cudagraph_wrapper.warmup(device, dtype=torch.long)
|
||||
self._cudagraph_enabled = True
|
||||
sizes = self._cudagraph_wrapper.capture_sizes
|
||||
logger.info("CUDA Graph enabled for decoder with sizes: %s", sizes)
|
||||
|
||||
def disable_cudagraph(self):
|
||||
self._cudagraph_enabled = False
|
||||
self._cudagraph_wrapper = None
|
||||
logger.info("CUDA Graph disabled for decoder")
|
||||
|
||||
def forward(self, codes):
|
||||
if codes.shape[1] != self.config.num_quantizers:
|
||||
raise ValueError(f"Expected {self.config.num_quantizers} layer of codes, got {codes.shape[1]}")
|
||||
@@ -866,6 +898,11 @@ class Qwen3TTSTokenizerV2Decoder(Qwen3TTSTokenizerV2DecoderPreTrainedModel):
|
||||
return wav.clamp(min=-1, max=1)
|
||||
|
||||
def chunked_decode(self, codes, chunk_size=300, left_context_size=25):
|
||||
# Use CUDA graph if enabled
|
||||
if self._cudagraph_enabled and self._cudagraph_wrapper is not None:
|
||||
return self._cudagraph_wrapper.chunked_decode_with_cudagraph(codes, chunk_size, left_context_size)
|
||||
|
||||
# Original implementation (eager mode)
|
||||
wavs = []
|
||||
start_index = 0
|
||||
while start_index < codes.shape[-1]:
|
||||
@@ -991,10 +1028,11 @@ class Qwen3TTSTokenizerV2Model(Qwen3TTSTokenizerV2PreTrainedModel):
|
||||
|
||||
"""
|
||||
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
||||
audio_lengths = (audio_codes[..., 0] > -1).sum(1) * self.decode_upsample_rate
|
||||
|
||||
audio_codes = torch.clamp(audio_codes, min=0)
|
||||
audio_values = self.decoder.chunked_decode(audio_codes.transpose(1, 2)).squeeze(1)
|
||||
|
||||
audio_lengths = (audio_codes[..., 0] > 0).sum(1) * self.decode_upsample_rate
|
||||
audio_values = [a[:length] for a, length in zip(audio_values, audio_lengths)]
|
||||
|
||||
if not return_dict:
|
||||
|
||||
+2
-1
@@ -1508,10 +1508,11 @@ class Qwen3TTSTokenizerV1Model(Qwen3TTSTokenizerV1PreTrainedModel):
|
||||
|
||||
"""
|
||||
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
||||
audio_lengths = (audio_codes > -1).sum(1) * self.decode_upsample_rate
|
||||
|
||||
audio_codes = torch.clamp(audio_codes, min=0)
|
||||
audio_values = self.decoder(code=audio_codes, reference_mel=ref_mels, conditioning=xvectors)
|
||||
|
||||
audio_lengths = (audio_codes > 0).sum(1) * self.decode_upsample_rate
|
||||
audio_values = [a[:length] for a, length in zip(audio_values, audio_lengths)]
|
||||
|
||||
if not return_dict:
|
||||
|
||||
@@ -63,6 +63,28 @@ _OMNI_MODELS = {
|
||||
"qwen3_tts_code2wav",
|
||||
"Qwen3TTSCode2Wav",
|
||||
),
|
||||
## mimo_audio
|
||||
"MiMoAudioModel": (
|
||||
"mimo_audio",
|
||||
"mimo_audio",
|
||||
"MiMoAudioForConditionalGeneration",
|
||||
),
|
||||
"MiMoAudioLLMModel": (
|
||||
"mimo_audio",
|
||||
"mimo_audio_llm",
|
||||
"MiMoAudioLLMForConditionalGeneration",
|
||||
),
|
||||
"MiMoAudioToken2WavModel": (
|
||||
"mimo_audio",
|
||||
"mimo_audio_code2wav",
|
||||
"MiMoAudioToken2WavForConditionalGenerationVLLM",
|
||||
),
|
||||
## glm_image
|
||||
"GlmImageForConditionalGeneration": (
|
||||
"glm_image",
|
||||
"glm_image_ar",
|
||||
"GlmImageForConditionalGeneration",
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user