[Model] Remove ten deprecated model architectures (#53608)

Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>
Co-authored-by: Xianbao QIAN <xianbao.qian@gmail.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Harry Mellor
2026-08-24 17:06:00 -07:00
committed by GitHub
co-authored by Xianbao QIAN Claude Opus 5
parent a0f1b9ad05
commit 7ca336929c
46 changed files with 49 additions and 6620 deletions
@@ -24,7 +24,6 @@ def _get_minicpmv_chat_template_fallback(tokenizer_name_or_path: str) -> Path |
_MODEL_TYPE_TO_CHAT_TEMPLATE_FALLBACK: dict[str, ChatTemplatePath] = {
"blip-2": CHAT_TEMPLATES_DIR / "template_blip2.jinja",
"chameleon": CHAT_TEMPLATES_DIR / "template_basic.jinja",
"clip": CHAT_TEMPLATES_DIR / "template_basic.jinja",
"colpali": CHAT_TEMPLATES_DIR / "template_basic.jinja",
"deepseek_ocr": CHAT_TEMPLATES_DIR / "template_deepseek_ocr.jinja",
-4
View File
@@ -71,10 +71,8 @@ class LazyConfigDict(dict):
_CONFIG_REGISTRY: dict[str, type[PretrainedConfig]] = LazyConfigDict(
afmoe="AfmoeConfig",
arctic="ArcticConfig",
axk1="AXK1Config",
bagel="BagelConfig",
umm="CheersConfig",
chatglm="ChatGLMConfig",
modernvbert="ColModernVBertConfig",
colpali="ColPaliConfig",
@@ -90,11 +88,9 @@ _CONFIG_REGISTRY: dict[str, type[PretrainedConfig]] = LazyConfigDict(
dots3_note="Dots3NoteConfig",
k3_dspark="K3DSparkConfig",
flex_olmo="FlexOlmoConfig",
fireredlid="FireRedLIDConfig",
funaudiochat="FunAudioChatConfig",
granite4_vision="Granite4VisionConfig",
hyperclovax="HyperCLOVAXConfig",
hyperclovax_vlm="HCXVisionConfig",
hunyuan_vl="HunYuanVLConfig",
hy_v3="HYV3Config",
isaac="IsaacConfig",
@@ -16,10 +16,8 @@ import importlib
_CLASS_TO_MODULE: dict[str, str] = {
"AfmoeConfig": "vllm.transformers_utils.configs.afmoe",
"ArcticConfig": "vllm.transformers_utils.configs.arctic",
"AXK1Config": "vllm.transformers_utils.configs.AXK1",
"BagelConfig": "vllm.transformers_utils.configs.bagel",
"CheersConfig": "vllm.transformers_utils.configs.cheers",
"ChatGLMConfig": "vllm.transformers_utils.configs.chatglm",
"ColModernVBertConfig": "vllm.transformers_utils.configs.colmodernvbert",
"ColPaliConfig": "vllm.transformers_utils.configs.colpali",
@@ -39,7 +37,6 @@ _CLASS_TO_MODULE: dict[str, str] = {
"K3DSparkConfig": "vllm.transformers_utils.configs.k3_dspark",
"DotsOCRConfig": "vllm.transformers_utils.configs.dotsocr",
"EAGLEConfig": "vllm.transformers_utils.configs.eagle",
"FireRedLIDConfig": "vllm.transformers_utils.configs.fireredlid",
"FlexOlmoConfig": "vllm.transformers_utils.configs.flex_olmo",
"FunAudioChatConfig": "vllm.transformers_utils.configs.funaudiochat",
"FunAudioChatAudioEncoderConfig": "vllm.transformers_utils.configs.funaudiochat",
@@ -47,7 +44,6 @@ _CLASS_TO_MODULE: dict[str, str] = {
"HunYuanVLConfig": "vllm.transformers_utils.configs.hunyuan_vl",
"HunYuanVLTextConfig": "vllm.transformers_utils.configs.hunyuan_vl",
"HunYuanVLVisionConfig": "vllm.transformers_utils.configs.hunyuan_vl",
"HCXVisionConfig": "vllm.transformers_utils.configs.hyperclovax",
"HYV3Config": "vllm.transformers_utils.configs.hy_v3",
"HyperCLOVAXConfig": "vllm.transformers_utils.configs.hyperclovax",
"IsaacConfig": "vllm.transformers_utils.configs.isaac",
@@ -112,10 +108,8 @@ _CLASS_TO_MODULE: dict[str, str] = {
__all__ = [
"AfmoeConfig",
"ArcticConfig",
"AXK1Config",
"BagelConfig",
"CheersConfig",
"ChatGLMConfig",
"ColModernVBertConfig",
"ColPaliConfig",
@@ -137,14 +131,12 @@ __all__ = [
"DotsOCRConfig",
"EAGLEConfig",
"FlexOlmoConfig",
"FireRedLIDConfig",
"FunAudioChatConfig",
"FunAudioChatAudioEncoderConfig",
"Granite4VisionConfig",
"HunYuanVLConfig",
"HunYuanVLTextConfig",
"HunYuanVLVisionConfig",
"HCXVisionConfig",
"HYV3Config",
"HyperCLOVAXConfig",
"IsaacConfig",
-216
View File
@@ -1,216 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# ruff: noqa: E501
# coding=utf-8
# Copied from
# https://huggingface.co/Snowflake/snowflake-arctic-instruct/blob/main/configuration_arctic.py
"""Arctic model configuration"""
from dataclasses import asdict, dataclass
from typing import Any
from transformers.configuration_utils import PretrainedConfig
from transformers.utils import logging
logger = logging.get_logger(__name__)
ARCTIC_PRETRAINED_CONFIG_ARCHIVE_MAP = {
"arctic": "https://huggingface.co/Snowflake/snowflake-arctic-instruct/tree/main/config.json",
}
@dataclass
class ArcticLoRAConfig:
lora_r: int = 64
lora_alpha: float = 16
shard_base_weights: bool = False
@dataclass
class ArcticQuantizationConfig:
q_bits: int = 8
rounding: str = "nearest"
mantissa_bits: int = 3
group_size: int = 128
class ArcticConfig(PretrainedConfig):
r"""
This is the configuration class to store the configuration of a [`ArcticModel`]. It is used to instantiate an
Arctic model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar configuration to that of the #TODO(rsamdani): add what model has the default config..
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PretrainedConfig`] for more information.
Args:
vocab_size (`int`, *optional*, defaults to 32000):
Vocabulary size of the Arctic model. Defines the number of different tokens that can be represented by the
`inputs_ids` passed when calling [`ArcticModel`]
hidden_size (`int`, *optional*, defaults to 4096):
Dimension of the hidden representations.
intermediate_size (`int`, *optional*, defaults to 14336):
Dimension of the MLP representations.
num_hidden_layers (`int`, *optional*, defaults to 32):
Number of hidden layers in the Transformer encoder.
num_attention_heads (`int`, *optional*, defaults to 32):
Number of attention heads for each attention layer in the Transformer encoder.
num_key_value_heads (`int`, *optional*, defaults to 8):
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
`num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
by meanpooling all the original heads within that group. For more details checkout [this
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `8`.
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
The non-linear activation function (function or string) in the decoder.
max_position_embeddings (`int`, *optional*, defaults to `4096*32`):
The maximum sequence length that this model might ever be used with. Arctic's sliding window attention
allows sequence of up to 4096*32 tokens.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
rms_norm_eps (`float`, *optional*, defaults to 1e-05):
The epsilon used by the rms normalization layers.
use_cache (`bool`, *optional*, defaults to `True`):
Whether or not the model should return the last key/values attentions (not used by all models). Only
relevant if `config.is_decoder=True`.
pad_token_id (`int`, *optional*):
The id of the padding token.
bos_token_id (`int`, *optional*, defaults to 1):
The id of the "beginning-of-sequence" token.
eos_token_id (`int`, *optional*, defaults to 2):
The id of the "end-of-sequence" token.
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
Whether the model's input and output word embeddings should be tied.
rope_parameters (`dict`, *optional*):
Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
accordingly.
Expected contents:
`rope_theta` (`float`): The base period of the RoPE embeddings.
`rope_type` (`str`):
The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
'llama3'], with 'default' being the original RoPE implementation.
sliding_window (`int`, *optional*):
Sliding window attention window size. If not specified, will default to `4096`.
attention_dropout (`float`, *optional*, defaults to 0.0):
The dropout ratio for the attention probabilities.
num_experts_per_tok (`int`, *optional*, defaults to 2):
The number of experts to root per-token, can be also interpreted as the `top-p` routing
parameter
num_local_experts (`int`, *optional*, defaults to 8):
Number of experts per Sparse MLP layer.
router_aux_loss_coef (`float`, *optional*, defaults to 0.001):
The aux loss factor for the total loss.
```python
>>> from transformers import ArcticModel, ArcticConfig
>>> # Initializing a Arctic 7B style configuration TODO(rsamdani): verify which model does the default configuration correspond to.
>>> configuration = ArcticConfig()
>>> # Initializing a model from the Arctic 7B style configuration
>>> model = ArcticModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "arctic"
keys_to_ignore_at_inference = ["past_key_values"]
def __init__(
self,
vocab_size=32000,
hidden_size=4096,
intermediate_size=14336,
num_hidden_layers=32,
num_attention_heads=32,
num_key_value_heads=None,
hidden_act="silu",
max_position_embeddings=4096,
initializer_range=0.02,
rms_norm_eps=1e-5,
use_cache=True,
pad_token_id=None,
bos_token_id=1,
eos_token_id=2,
tie_word_embeddings=False,
rope_parameters: dict[str, Any] | None = None,
sliding_window=None,
attention_dropout=0.0,
num_experts_per_tok=1,
num_local_experts=8,
router_aux_loss_coef=0.001,
moe_layer_frequency=2,
parallel_attn_mlp_res=False,
moe_train_capacity_factor=1,
moe_eval_capacity_factor=1,
enable_expert_tensor_parallelism=False,
moe_min_capacity=0,
moe_token_dropping=True,
quantization=None,
**kwargs,
):
self.vocab_size = vocab_size
self.max_position_embeddings = max_position_embeddings
self.hidden_size = hidden_size
self.intermediate_size = intermediate_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.sliding_window = sliding_window
# for backward compatibility
if num_key_value_heads is None:
num_key_value_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads
self.hidden_act = hidden_act
self.initializer_range = initializer_range
self.rms_norm_eps = rms_norm_eps
self.use_cache = use_cache
rope_theta = kwargs.pop("rope_theta", 1e6)
if rope_parameters is None:
rope_parameters = {"rope_type": "default", "rope_theta": rope_theta}
self.rope_parameters = rope_parameters
self.attention_dropout = attention_dropout
self.num_experts_per_tok = num_experts_per_tok
self.num_local_experts = num_local_experts
self.router_aux_loss_coef = router_aux_loss_coef
self.moe_layer_frequency = moe_layer_frequency
self.moe_train_capacity_factor = moe_train_capacity_factor
self.moe_eval_capacity_factor = moe_eval_capacity_factor
self.enable_expert_tensor_parallelism = enable_expert_tensor_parallelism
self.moe_min_capacity = moe_min_capacity
self.moe_token_dropping = moe_token_dropping
self.parallel_attn_mlp_res = parallel_attn_mlp_res
if isinstance(quantization, dict):
self.quantization = ArcticQuantizationConfig(**quantization)
else:
self.quantization = quantization
super().__init__(
pad_token_id=pad_token_id,
bos_token_id=bos_token_id,
eos_token_id=eos_token_id,
tie_word_embeddings=tie_word_embeddings,
**kwargs,
)
@classmethod
def from_dict(cls, config_dict: dict[str, Any], **kwargs) -> "ArcticConfig":
result = super().from_dict(config_dict, **kwargs)
config = result[0] if isinstance(result, tuple) else result
if isinstance(config.quantization, dict):
config.quantization = ArcticQuantizationConfig(**config.quantization)
return result
def to_dict(self) -> dict[str, Any]:
ret = super().to_dict()
if isinstance(ret["quantization"], ArcticQuantizationConfig):
ret["quantization"] = asdict(ret["quantization"])
return ret
-109
View File
@@ -1,109 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from transformers import PretrainedConfig, SiglipVisionConfig
from transformers.modeling_rope_utils import rope_config_validation
class CheersTextConfig(PretrainedConfig):
"""Qwen2-based text config with Cheers-specific defaults."""
model_type = "umm"
base_config_key = "text_config"
def __init__(
self,
vocab_size=152064,
hidden_size=3584,
intermediate_size=18944,
num_hidden_layers=28,
num_attention_heads=28,
num_key_value_heads=4,
hidden_act="silu",
max_position_embeddings=131072,
initializer_range=0.02,
rms_norm_eps=1e-6,
use_cache=True,
tie_word_embeddings=False,
rope_theta=1000000.0,
rope_scaling=None,
use_sliding_window=False,
sliding_window=131072,
max_window_layers=28,
layer_types=None,
attention_dropout=0.0,
**kwargs,
):
self.vocab_size = vocab_size
self.max_position_embeddings = max_position_embeddings
self.hidden_size = hidden_size
self.intermediate_size = intermediate_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.use_sliding_window = use_sliding_window
self.sliding_window = sliding_window if self.use_sliding_window else None
self.max_window_layers = max_window_layers
if num_key_value_heads is None:
num_key_value_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads
self.hidden_act = hidden_act
self.initializer_range = initializer_range
self.rms_norm_eps = rms_norm_eps
self.use_cache = use_cache
self.rope_theta = rope_theta
self.rope_scaling = rope_scaling
self.attention_dropout = attention_dropout
if self.rope_scaling is not None and "type" in self.rope_scaling:
self.rope_scaling["rope_type"] = self.rope_scaling["type"]
rope_config_validation(self)
self.layer_types = layer_types
if self.layer_types is None:
self.layer_types = [
"sliding_attention"
if self.sliding_window is not None and i >= self.max_window_layers
else "full_attention"
for i in range(self.num_hidden_layers)
]
super().__init__(
tie_word_embeddings=tie_word_embeddings,
**kwargs,
)
class CheersConfig(PretrainedConfig):
"""Configuration class for Cheers (UMM) model."""
model_type = "umm"
def __init__(
self,
text_config: dict | CheersTextConfig | None = None,
vision_representation_config: dict | SiglipVisionConfig | None = None,
vae_encoder_config: dict | None = None,
vae_decoder_config: dict | None = None,
**kwargs,
):
super().__init__(**kwargs)
if isinstance(text_config, dict):
self.text_config = CheersTextConfig(**text_config)
else:
self.text_config = text_config or CheersTextConfig()
if isinstance(vision_representation_config, dict):
self.vision_representation_config = SiglipVisionConfig(
**vision_representation_config
)
else:
self.vision_representation_config = (
vision_representation_config or SiglipVisionConfig()
)
self.vae_encoder_config = vae_encoder_config or {"resolution": 512}
self.vae_decoder_config = vae_decoder_config or {"resolution": 512}
@property
def hidden_size(self) -> int:
"""Return the hidden size of the language model."""
return self.text_config.hidden_size
@@ -1,73 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
import contextlib
from transformers import AutoConfig
from transformers.configuration_utils import PretrainedConfig
class FireRedLIDConfig(PretrainedConfig):
"""Minimal config class for native vLLM FireRedLID support."""
model_type = "fireredlid"
keys_to_ignore_at_inference = ["past_key_values"]
def __init__(
self,
vocab_size: int = 120,
lid_odim: int = 120,
idim: int = 80,
d_model: int = 1280,
n_head: int = 20,
n_layers_enc: int = 16,
n_layers_lid_dec: int = 6,
kernel_size: int = 33,
residual_dropout: float = 0.05,
dropout_rate: float = 0.05,
pe_maxlen: int = 5000,
pad_token_id: int = 2,
bos_token_id: int = 3,
eos_token_id: int = 4,
decoder_start_token_id: int = 3,
tie_word_embeddings: bool = True,
is_encoder_decoder: bool = True,
architectures: list[str] | None = None,
**kwargs,
):
self.vocab_size = vocab_size
self.lid_odim = lid_odim
self.idim = idim
self.d_model = d_model
self.hidden_size = d_model
self.n_head = n_head
self.num_attention_heads = n_head
self.n_layers_enc = n_layers_enc
self.encoder_layers = n_layers_enc
self.n_layers_lid_dec = n_layers_lid_dec
self.decoder_layers = n_layers_lid_dec
self.num_hidden_layers = n_layers_lid_dec
self.kernel_size = kernel_size
self.residual_dropout = residual_dropout
self.dropout_rate = dropout_rate
self.pe_maxlen = pe_maxlen
self.tie_word_embeddings = tie_word_embeddings
self.is_encoder_decoder = is_encoder_decoder
self.architectures = architectures or ["FireRedLIDForConditionalGeneration"]
super().__init__(
pad_token_id=pad_token_id,
bos_token_id=bos_token_id,
eos_token_id=eos_token_id,
decoder_start_token_id=decoder_start_token_id,
tie_word_embeddings=tie_word_embeddings,
is_encoder_decoder=is_encoder_decoder,
architectures=self.architectures,
**kwargs,
)
with contextlib.suppress(ValueError):
AutoConfig.register(FireRedLIDConfig.model_type, FireRedLIDConfig)
@@ -17,7 +17,6 @@
# limitations under the License.
"""HyperCLOVA X model configuration."""
from transformers import AutoConfig
from transformers.configuration_utils import PretrainedConfig
@@ -276,74 +275,3 @@ class HyperCLOVAXConfig(PretrainedConfig):
auto_map=auto_map,
**kwargs,
)
class HCXVisionConfig(PretrainedConfig):
"""Vendored HyperCLOVAX Vision config with transformers v5 fix.
The original remote code config does not handle empty initialization
(text_config=None), which breaks transformers v5's @strict validation.
TODO: Remove this class once HyperCLOVAX is upstreamed to transformers.
Tracking PR: https://github.com/huggingface/transformers/pull/44956
"""
model_type = "hyperclovax_vlm"
keys_to_ignore_at_inference = ["past_key_values"]
text_config_attribute_map = {
"n_embd": "hidden_size",
"n_positions": "max_position_embeddings",
"n_head": "num_attention_heads",
"n_layer": "num_hidden_layers",
}
def __init__(
self,
text_config=None,
vision_config=None,
use_nth_layer=-2,
img_start_id=100009,
decoder_max_length=4096,
anyres=False,
unpad=False,
max_num_grids=-1,
num_queries_vis_abstractor=-1,
ignore_index=-100,
proj_pos_emb=True,
proj_prenorm=False,
use_1x1_grid=False,
**kwargs,
):
for key, val in self.text_config_attribute_map.items():
if text_config is not None and key in text_config:
text_config[val] = text_config.pop(key)
self.text_config = None
if text_config is not None:
_text_config = AutoConfig.for_model(text_config["model_type"])
self.text_config = _text_config.from_dict(text_config)
self.hidden_size = self.text_config.hidden_size
self.vision_config = None
if vision_config is not None:
_vision_config = AutoConfig.for_model(vision_config["model_type"])
self.vision_config = _vision_config.from_dict(vision_config)
self.use_nth_layer = use_nth_layer
self.decoder_max_length = decoder_max_length
self.anyres = anyres
self.unpad = unpad
self.max_num_grids = max_num_grids
self.num_queries_vis_abstractor = num_queries_vis_abstractor
self.img_start_id = img_start_id
self.ignore_index = ignore_index
self.proj_pos_emb = proj_pos_emb
self.proj_prenorm = proj_prenorm
self.use_1x1_grid = use_1x1_grid
super().__init__(**kwargs)
def get_text_config(self, decoder=False):
if self.text_config is not None:
return self.text_config
return self
@@ -373,7 +373,6 @@ class ModelArchConfigConvertorBase:
"molmo2",
"moondream3",
"paligemma",
"umm",
)
if not hasattr(self.hf_config, "model_type"):
return False
@@ -545,13 +544,6 @@ class FalconModelArchConfigConvertor(ModelArchConfigConvertorBase):
return super().get_total_num_kv_heads()
class MPTModelArchConfigConvertor(ModelArchConfigConvertorBase):
def get_total_num_kv_heads(self) -> int:
if "kv_n_heads" in self.hf_text_config.attn_config:
return self.hf_text_config.attn_config["kv_n_heads"]
return self.hf_text_config.num_attention_heads
class DbrxModelArchConfigConvertor(ModelArchConfigConvertorBase):
def get_total_num_kv_heads(self) -> int:
return getattr(
@@ -792,7 +784,6 @@ MODEL_ARCH_CONFIG_CONVERTORS = {
"mimo_v2_mtp": MimoV2MTPModelArchConfigConvertor,
"mimo_v2_omni_mtp": MimoV2MTPModelArchConfigConvertor,
"moss_audio": MossAudioModelArchConfigConvertor,
"mpt": MPTModelArchConfigConvertor,
"nemotron-nas": NemotronNasModelArchConfigConvertor,
"bailing_hybrid_v3_mtp": BailingHybridV3MTPModelArchConfigConvertor,
"pangu_ultra_moe_mtp": PanguUltraMoeMTPModelArchConfigConvertor,
+1 -3
View File
@@ -37,9 +37,7 @@ def _transformers_v4_compatibility_import():
subset of `ProcessorChatTemplateKwargs` as defined in Transformers v4.
In Transformers v5 these were merged into `ProcessorChatTemplateKwargs` and
`ChatTemplateLoadKwargs` was removed. For backward compatibility, we add an alias
for `ChatTemplateLoadKwargs` if it doesn't exist.
This can be removed if `HCXVisionForCausalLM` is upstreamed to Transformers."""
for `ChatTemplateLoadKwargs` if it doesn't exist."""
old_import = getattr(processing_utils, "ChatTemplateLoadKwargs", None)
new_import = getattr(processing_utils, "ProcessorChatTemplateKwargs", None)
if old_import is None and new_import is not None:
@@ -12,12 +12,10 @@ import importlib
__all__ = [
"BagelProcessor",
"CheersProcessor",
"CohereASRProcessor",
"Cosmos3EdgeProcessor",
"DeepseekVLV2Processor",
"FireRedASR2Processor",
"FireRedLIDProcessor",
"FunASRProcessor",
"GLM4VProcessor",
"Granite4VisionProcessor",
@@ -52,12 +50,10 @@ __all__ = [
_CLASS_TO_MODULE: dict[str, str] = {
"BagelProcessor": "vllm.transformers_utils.processors.bagel",
"CheersProcessor": "vllm.transformers_utils.processors.cheers",
"CohereASRProcessor": "vllm.transformers_utils.processors.cohere_asr",
"Cosmos3EdgeProcessor": "vllm.transformers_utils.processors.cosmos3_edge",
"DeepseekVLV2Processor": "vllm.transformers_utils.processors.deepseek_vl2",
"FireRedASR2Processor": "vllm.transformers_utils.processors.fireredasr2",
"FireRedLIDProcessor": "vllm.transformers_utils.processors.fireredlid",
"FunASRProcessor": "vllm.transformers_utils.processors.funasr",
"GLM4VProcessor": "vllm.transformers_utils.processors.glm4v",
"Granite4VisionProcessor": "vllm.transformers_utils.processors.granite4_vision",
@@ -1,89 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Cheers (UMM) processor for image and text inputs."""
from transformers import AutoProcessor
from transformers.feature_extraction_utils import BatchFeature
from transformers.image_utils import ImageInput
from transformers.processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
from transformers.tokenization_utils_base import PreTokenizedInput, TextInput
class CheersProcessorKwargs(ProcessingKwargs, total=False): # type: ignore[call-arg]
_defaults = {
"images_kwargs": {
"return_tensors": "pt",
},
}
class CheersProcessor(ProcessorMixin):
"""
Constructs a Cheers processor which wraps a
SigLIP image processor and a Qwen2 tokenizer.
"""
attributes = ["image_processor", "tokenizer"]
image_processor_class = "AutoImageProcessor"
tokenizer_class = "AutoTokenizer"
def __call__(
self,
text: TextInput
| PreTokenizedInput
| list[TextInput]
| list[PreTokenizedInput] = None,
images: ImageInput = None,
**kwargs: Unpack[CheersProcessorKwargs],
):
output_kwargs = self._merge_kwargs(
CheersProcessorKwargs,
tokenizer_init_kwargs=self.tokenizer.init_kwargs,
**kwargs,
)
if images is not None:
import torch
if isinstance(images, (list, tuple)):
all_pv = []
all_ghw = []
for img in images:
result = self.image_processor(img, **output_kwargs["images_kwargs"])
all_pv.append(result["pixel_values"])
if "grid_hws" in result:
all_ghw.append(result["grid_hws"])
pixel_values = {
"pixel_values": torch.cat(all_pv, dim=0),
}
if all_ghw:
pixel_values["grid_hws"] = torch.cat(all_ghw, dim=0)
else:
pixel_values = self.image_processor(
images, **output_kwargs["images_kwargs"]
)
else:
pixel_values = {}
text_inputs = (
self.tokenizer(text, **output_kwargs["text_kwargs"])
if text is not None
else {}
)
return BatchFeature(data={**pixel_values, **text_inputs})
def batch_decode(self, *args, **kwargs):
return self.tokenizer.batch_decode(*args, **kwargs)
def decode(self, *args, **kwargs):
return self.tokenizer.decode(*args, **kwargs)
@property
def model_input_names(self):
tokenizer_input_names = self.tokenizer.model_input_names
image_processor_input_names = self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
AutoProcessor.register("CheersProcessor", CheersProcessor)
@@ -1,276 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
FireRedLID feature extractor and processor.
The FeatureExtractor handles:
- Raw waveform → 80-dim log-mel filterbank (via kaldi_native_fbank)
- CMVN normalization (means / inverse_std_variences from preprocessor_config)
- Padding + length tracking
The Processor wraps the FeatureExtractor and a tokenizer.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
import numpy as np
import torch
import torch.nn.functional as F
from transformers import (
AutoFeatureExtractor,
BatchFeature,
)
from transformers.feature_extraction_sequence_utils import SequenceFeatureExtractor
from transformers.processing_utils import ProcessorMixin
from transformers.utils import TensorType
from vllm.logger import init_logger
from vllm.utils.import_utils import LazyLoader
if TYPE_CHECKING:
import kaldi_native_fbank as knf
else:
knf = LazyLoader("knf", globals(), "kaldi_native_fbank")
logger = init_logger(__name__)
# ---------------------------------------------------------------------------
# Helpers (shared with FireRedASR2 processor)
# ---------------------------------------------------------------------------
class CMVN:
def __init__(self, dim, means, inverse_std_variences):
self.dim = dim
self.means = np.array(means)
self.inverse_std_variences = np.array(inverse_std_variences)
def __call__(self, x):
assert x.shape[-1] == self.dim, "CMVN dim mismatch"
out = x - self.means
out = out * self.inverse_std_variences
return out
class KaldifeatFbank:
def __init__(
self,
num_mel_bins: int = 80,
frame_length: int = 25,
frame_shift: int = 10,
dither: float = 0.0,
):
self.dither = dither
opts = knf.FbankOptions()
opts.frame_opts.dither = dither
opts.mel_opts.num_bins = num_mel_bins
opts.frame_opts.snip_edges = True
opts.mel_opts.debug_mel = False
self.opts = opts
def __call__(self, sample_rate, wav_np, is_train=False):
dither = self.dither if is_train else 0.0
self.opts.frame_opts.dither = dither
fbank = knf.OnlineFbank(self.opts)
fbank.accept_waveform(sample_rate, wav_np.tolist())
feat = []
for i in range(fbank.num_frames_ready):
feat.append(fbank.get_frame(i))
if len(feat) == 0:
return np.zeros((0, self.opts.mel_opts.num_bins))
return np.vstack(feat)
# ---------------------------------------------------------------------------
# Feature Extractor
# ---------------------------------------------------------------------------
class FireRedLIDFeatureExtractor(SequenceFeatureExtractor):
"""
Extracts 80-dim log-mel filterbank features from raw waveforms,
applies CMVN, and returns padded feature tensors with lengths.
Also computes ``fake_token_lengths`` — the actual encoder output
length for each audio — so that vLLM can allocate the correct
number of cross-attention KV cache slots.
"""
model_input_names = ["input_features"]
def __init__(
self,
feature_size=80,
sampling_rate=16000,
chunk_length=30,
padding_value=0.0,
return_attention_mask=False,
dim=80,
means=None,
inverse_std_variences=None,
num_mel_bins=80,
frame_length=25,
frame_shift=10,
dither=0.0,
left_context=3,
right_context=3,
**kwargs,
):
super().__init__(
feature_size=feature_size,
sampling_rate=sampling_rate,
padding_value=padding_value,
return_attention_mask=return_attention_mask,
**kwargs,
)
self.chunk_length = chunk_length
self.dim = dim
self.means = means
self.inverse_std_variences = inverse_std_variences
self.num_mel_bins = num_mel_bins
self.frame_length = frame_length
self.frame_shift = frame_shift
self.dither = dither
self.sampling_rate = sampling_rate
self.context = left_context + 1 + right_context
def __call__(
self,
raw_speech: np.ndarray | list[float] | list[np.ndarray] | list[list[float]],
truncation: bool = True,
pad_to_multiple_of: int | None = None,
return_tensors: str | TensorType | None = None,
return_attention_mask: bool | None = None,
padding: str | None = "max_length",
max_length: int | None = None,
sampling_rate: int | None = None,
do_normalize: bool | None = None,
**kwargs,
) -> BatchFeature:
if sampling_rate is not None and sampling_rate != self.sampling_rate:
raise ValueError(
f"FireRedLIDFeatureExtractor expects sampling_rate="
f"{self.sampling_rate}, got {sampling_rate}."
)
# Initialize helpers
cmvn = CMVN(self.dim, self.means, self.inverse_std_variences)
fbank = KaldifeatFbank(
num_mel_bins=self.num_mel_bins,
frame_length=self.frame_length,
frame_shift=self.frame_shift,
dither=self.dither,
)
def padding_position_is_0(padded_input, input_lengths):
N, T = padded_input.size()[:2]
mask = torch.ones((N, T)).to(padded_input.device)
for i in range(N):
mask[i, input_lengths[i] :] = 0
mask = mask.unsqueeze(dim=1)
return mask.to(torch.uint8)
feats = []
speech_lengths = []
fake_token_lengths = []
for speech in raw_speech:
# vLLM loads audio via librosa (float32 in [-1,1]),
# but kaldi_native_fbank expects int16-scale values.
speech_scaled = speech * 32768
feat = fbank(self.sampling_rate, speech_scaled)
feat = cmvn(feat)
feat = torch.from_numpy(feat).float()
length = feat.size(0)
feats.append(feat)
speech_lengths.append(length)
# Compute the actual Conv2dSubsampling output length.
# This mirrors the mask logic in Conv2dSubsampling.forward:
# pad context frames, then mask[:, :, :-2:2][:, :, :-2:2].sum()
padded_input = F.pad(feat, (0, 0, 0, self.context - 1), "constant", 0.0)
src_mask = padding_position_is_0(
padded_input[None, :, :],
torch.tensor([length], dtype=torch.int32),
)
mask = src_mask[:, :, :-2:2][:, :, :-2:2]
enc_len = mask[:, -1, :].sum(dim=-1)
fake_token_len = torch.clamp(enc_len, min=1)
fake_token_lengths.append(fake_token_len)
if len(feats) == 0:
return BatchFeature()
# Pad to uniform length
max_feat_len = max(f.size(0) for f in feats)
padded = feats[0].new_zeros(len(feats), max_feat_len, feats[0].size(1))
for i, feat in enumerate(feats):
padded[i, : feat.size(0)] = feat
result = BatchFeature({"input_features": padded})
if return_tensors is not None:
result = result.convert_to_tensors(return_tensors)
result["speech_lengths"] = torch.tensor(speech_lengths, dtype=torch.long)
result["fake_token_lengths"] = torch.concat(fake_token_lengths)
return result
# ---------------------------------------------------------------------------
# Processor
# ---------------------------------------------------------------------------
class FireRedLIDProcessor(ProcessorMixin):
"""
Wraps FireRedLIDFeatureExtractor + a tokenizer.
"""
feature_extractor_class = "FireRedLIDFeatureExtractor"
tokenizer_class = ("PythonBackend", "TokenizersBackend")
def __init__(self, feature_extractor, tokenizer):
super().__init__(feature_extractor, tokenizer)
self.current_processor = self.feature_extractor
self._in_target_context_manager = False
def __call__(self, *args, **kwargs):
if self._in_target_context_manager:
return self.current_processor(*args, **kwargs)
audio = kwargs.pop("audio", None)
sampling_rate = kwargs.pop("sampling_rate", None)
text = kwargs.pop("text", None)
if len(args) > 0:
audio = args[0]
args = args[1:]
if audio is not None:
inputs = self.feature_extractor(
audio, *args, sampling_rate=sampling_rate, **kwargs
)
else:
inputs = BatchFeature()
if text is not None:
if isinstance(text, str):
text = [text]
encodings = self.tokenizer(text, **kwargs)
if audio is not None:
inputs["labels"] = encodings["input_ids"]
else:
return encodings
return inputs
# ---------------------------------------------------------------------------
# Registration
# ---------------------------------------------------------------------------
AutoFeatureExtractor.register("FireRedLIDFeatureExtractor", FireRedLIDFeatureExtractor)