[Mini-VLLM] Cut dead subsystems across serving, connectors, parsers
- Remove P/D transfer connectors: nixl, nixl_chat, mooncake x2, hf3fs, moriio, hisparse, example and hidden-states connectors - Reduce weight_transfer to the base API used by model loading - Remove kv_offload tiering, simple_kv_offload, ec cpu/example, snapshot command, engine snapshot server - Remove transformers model fallback, dsv4 tokenizers, dead platforms cpu/tpu/xpu, flashmla third_party, dsa, megamoe/flydsl, dead attn ops, dead layers (short_conv, fused_embed_norm, indexer_topk, relu2 gemma_ar, lightning_attn, minimax_rms_norm), gemm_rs_ar - Keep MoE LoRA op (imported eagerly by punica_gpu); drop fp8 variant - Rebuild parser hubs around Qwen3 adapters only (36 dead adapters) - Remove dead tests with the code they covered Co-authored-by: Hinata <hinata@idihore.id> Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
@@ -14,71 +14,11 @@ from __future__ import annotations
|
||||
import importlib
|
||||
|
||||
_CLASS_TO_MODULE: dict[str, str] = {
|
||||
"BagelConfig": "vllm.transformers_utils.configs.bagel",
|
||||
"BailingMoeV3TextConfig": "vllm.transformers_utils.configs.bailing_moe_v3_vl",
|
||||
"BailingMoeV3VisionConfig": "vllm.transformers_utils.configs.bailing_moe_v3_vl",
|
||||
"BailingMoeV3VLConfig": "vllm.transformers_utils.configs.bailing_moe_v3_vl",
|
||||
"ChatGLMConfig": "vllm.transformers_utils.configs.chatglm",
|
||||
"ColModernVBertConfig": "vllm.transformers_utils.configs.colmodernvbert",
|
||||
"ColPaliConfig": "vllm.transformers_utils.configs.colpali",
|
||||
"ColQwen3Config": "vllm.transformers_utils.configs.colqwen3",
|
||||
"OpsColQwen3Config": "vllm.transformers_utils.configs.colqwen3",
|
||||
"Qwen3VLNemotronEmbedConfig": "vllm.transformers_utils.configs.colqwen3",
|
||||
"Cosmos3EdgeConfig": "vllm.transformers_utils.configs.cosmos3_edge",
|
||||
"Cosmos3EdgeProjectorConfig": "vllm.transformers_utils.configs.cosmos3_edge",
|
||||
"Cosmos3EdgeTextConfig": "vllm.transformers_utils.configs.cosmos3_edge",
|
||||
"Cosmos3EdgeVisionConfig": "vllm.transformers_utils.configs.cosmos3_edge",
|
||||
"DeepseekVLV2Config": "vllm.transformers_utils.configs.deepseek_vl2",
|
||||
"DeepseekV41Config": "vllm.transformers_utils.configs.deepseek_v41",
|
||||
"Dots3NoteConfig": "vllm.transformers_utils.configs.dots3_note",
|
||||
"K3DSparkConfig": "vllm.transformers_utils.configs.k3_dspark",
|
||||
"DotsOCRConfig": "vllm.transformers_utils.configs.dotsocr",
|
||||
"EAGLEConfig": "vllm.transformers_utils.configs.eagle",
|
||||
"FunAudioChatConfig": "vllm.transformers_utils.configs.funaudiochat",
|
||||
"FunAudioChatAudioEncoderConfig": "vllm.transformers_utils.configs.funaudiochat",
|
||||
"HYV4Config": "vllm.transformers_utils.configs.hy_v4",
|
||||
"IsaacConfig": "vllm.transformers_utils.configs.isaac",
|
||||
# RWConfig is for the original tiiuae/falcon-40b(-instruct) and
|
||||
# tiiuae/falcon-7b(-instruct) models. Newer Falcon models will use the
|
||||
# `FalconConfig` class from the official HuggingFace transformers library.
|
||||
"RWConfig": "vllm.transformers_utils.configs.falcon",
|
||||
"MiDashengLMConfig": "vllm.transformers_utils.configs.midashenglm",
|
||||
"MiniMaxM3Config": "vllm.transformers_utils.configs.minimax_m3",
|
||||
"MiniMaxM3MTPConfig": "vllm.transformers_utils.configs.minimax_m3",
|
||||
"MiniMaxM3TextConfig": "vllm.transformers_utils.configs.minimax_m3",
|
||||
"Moondream3Config": "vllm.transformers_utils.configs.moondream3",
|
||||
"Moondream3TextConfig": "vllm.transformers_utils.configs.moondream3",
|
||||
"Moondream3VisionConfig": "vllm.transformers_utils.configs.moondream3",
|
||||
"MossTranscribeDiarizeConfig": (
|
||||
"vllm.transformers_utils.configs.moss_transcribe_diarize"
|
||||
),
|
||||
"MoonViTConfig": "vllm.transformers_utils.configs.moonvit",
|
||||
"KimiLinearConfig": "vllm.transformers_utils.configs.kimi_linear",
|
||||
"KimiVLConfig": "vllm.transformers_utils.configs.kimi_vl",
|
||||
"MuseGlimmerConfig": "vllm.transformers_utils.configs.muse_glimmer",
|
||||
"MuseGlimmerTextConfig": "vllm.transformers_utils.configs.muse_glimmer",
|
||||
"MuseGlimmerVisionConfig": "vllm.transformers_utils.configs.muse_glimmer",
|
||||
"MuseGlimmerAssistantConfig": "vllm.transformers_utils.configs.muse_glimmer",
|
||||
"KimiK3Config": "vllm.transformers_utils.configs.kimi_k3",
|
||||
"KimiK3VisionConfig": "vllm.transformers_utils.configs.kimi_k3",
|
||||
"OpenVLAConfig": "vllm.transformers_utils.configs.openvla",
|
||||
"OvisConfig": "vllm.transformers_utils.configs.ovis",
|
||||
"PixelShuffleSiglip2VisionConfig": "vllm.transformers_utils.configs.isaac",
|
||||
"RadioConfig": "vllm.transformers_utils.configs.radio",
|
||||
"SpeculatorsConfig": "vllm.transformers_utils.configs.speculators",
|
||||
"UltravoxConfig": "vllm.transformers_utils.configs.ultravox",
|
||||
"UnlimitedOCRConfig": "vllm.transformers_utils.configs.unlimited_ocr",
|
||||
"Step3VLConfig": "vllm.transformers_utils.configs.step3_vl",
|
||||
"Step3VisionEncoderConfig": "vllm.transformers_utils.configs.step3_vl",
|
||||
"Step3TextConfig": "vllm.transformers_utils.configs.step3_vl",
|
||||
"Step3p5Config": "vllm.transformers_utils.configs.step3p5",
|
||||
"QianfanOCRConfig": "vllm.transformers_utils.configs.qianfan_ocr",
|
||||
"QianfanOCRVisionConfig": "vllm.transformers_utils.configs.qianfan_ocr",
|
||||
"Qwen3ASRConfig": "vllm.transformers_utils.configs.qwen3_asr",
|
||||
"InklingModelConfig": "vllm.models.inkling.configs",
|
||||
"InklingAudioConfig": "vllm.models.inkling.configs",
|
||||
"InklingVisionConfig": "vllm.models.inkling.configs",
|
||||
"InklingMMConfig": "vllm.models.inkling.configs",
|
||||
"MossTranscribeDiarizeConfig": (),
|
||||
# Upstream Transformers classes registered in _CONFIG_REGISTRY
|
||||
"DeepseekV3Config": "transformers",
|
||||
"HyperCLOVAXConfig": "transformers",
|
||||
|
||||
@@ -1,345 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# Copyright 2025 Antgroup and The HuggingFace Inc. team. All rights reserved.
|
||||
# Adapted from
|
||||
# https://huggingface.co/inclusionAI/Ling-3.0-flash/blob/51fd444268df5267074ef0b289de0e1c4cb9b381/configuration_bailing_moe_v3.py
|
||||
"""Bailing V3 vision-language model configuration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from transformers.configuration_utils import PreTrainedConfig
|
||||
|
||||
|
||||
def _normalize_mrope_parameters(
|
||||
config: PreTrainedConfig,
|
||||
mrope_section: list[int],
|
||||
) -> None:
|
||||
"""Add the top-level Bailing M-RoPE split to a text config."""
|
||||
rope_parameters = dict(getattr(config, "rope_parameters", None) or {})
|
||||
text_mrope_section = rope_parameters.get("mrope_section")
|
||||
if text_mrope_section is not None and list(text_mrope_section) != mrope_section:
|
||||
raise ValueError(
|
||||
"Bailing V3 VL has conflicting M-RoPE sections: "
|
||||
f"text={text_mrope_section}, top-level={mrope_section}"
|
||||
)
|
||||
|
||||
if "rope_type" not in rope_parameters and "type" not in rope_parameters:
|
||||
rope_parameters["rope_type"] = "default"
|
||||
rope_parameters.setdefault("rope_theta", getattr(config, "rope_theta", 10_000))
|
||||
rope_parameters["mrope_section"] = list(mrope_section)
|
||||
config.rope_parameters = rope_parameters
|
||||
|
||||
|
||||
def _build_layer_types(
|
||||
num_hidden_layers: int,
|
||||
layer_group_size: int,
|
||||
) -> list[str]:
|
||||
if layer_group_size <= 0:
|
||||
raise ValueError(
|
||||
f"Bailing V3 VL layer_group_size must be positive, got {layer_group_size}"
|
||||
)
|
||||
|
||||
grouped_layers = num_hidden_layers // layer_group_size * layer_group_size
|
||||
return [
|
||||
"linear_attention"
|
||||
if ((layer_idx + 1) % layer_group_size != 0 and layer_idx < grouped_layers)
|
||||
else "full_attention"
|
||||
for layer_idx in range(num_hidden_layers)
|
||||
]
|
||||
|
||||
|
||||
class BailingMoeV3TextConfig(PreTrainedConfig):
|
||||
model_type = "bailing_hybrid"
|
||||
base_config_key = "text_config"
|
||||
keys_to_ignore_at_inference = ["past_key_values"]
|
||||
ignore_keys_at_rope_validation = {"mrope_section"}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
vocab_size: int = 157184,
|
||||
hidden_size: int = 2048,
|
||||
intermediate_size: int = 5120,
|
||||
num_hidden_layers: int = 20,
|
||||
num_attention_heads: int = 16,
|
||||
num_key_value_heads: int = 4,
|
||||
hidden_act: str = "silu",
|
||||
use_qkv_bias: bool = False,
|
||||
use_bias: bool = False,
|
||||
rms_norm_eps: float = 1e-6,
|
||||
tie_word_embeddings: bool = False,
|
||||
embedding_dropout: float = 0.0,
|
||||
attention_dropout: float = 0.0,
|
||||
output_dropout: float = 0.0,
|
||||
initializer_range: float = 0.02,
|
||||
max_position_embeddings: int = 32768,
|
||||
rope_theta: float = 600000.0,
|
||||
rope_parameters: dict[str, Any] | None = None,
|
||||
rope_scaling: dict[str, Any] | None = None,
|
||||
partial_rotary_factor: float | None = None,
|
||||
mrope_section: list[int] | tuple[int, ...] | None = None,
|
||||
use_cache: bool = True,
|
||||
max_window_layers: int = 20,
|
||||
pad_token_id: int = 156892,
|
||||
eos_token_id: int = 156892,
|
||||
num_experts: int = 256,
|
||||
num_shared_experts: int = 1,
|
||||
num_experts_per_tok: int = 8,
|
||||
n_group: int = 8,
|
||||
topk_group: int = 4,
|
||||
moe_intermediate_size: int = 512,
|
||||
moe_shared_expert_intermediate_size: int = 512,
|
||||
first_k_dense_replace: int = 1,
|
||||
head_dim: int | None = 128,
|
||||
output_router_logits: bool = False,
|
||||
use_qk_norm: bool = True,
|
||||
num_nextn_predict_layers: int = 0,
|
||||
mtp_loss_scaling_factor: float = 0,
|
||||
moe_router_enable_expert_bias: bool = True,
|
||||
routed_scaling_factor: float = 1.0,
|
||||
layer_group_size: int = 5,
|
||||
layer_types: list[str] | None = None,
|
||||
layers_block_type: list[str] | None = None,
|
||||
kv_lora_rank: int = 512,
|
||||
q_lora_rank: int | None = None,
|
||||
qk_rope_head_dim: int = 64,
|
||||
v_head_dim: int = 128,
|
||||
qk_nope_head_dim: int = 128,
|
||||
rope_interleave: bool = True,
|
||||
score_function: str = "sigmoid",
|
||||
scoring_func: str = "sigmoid",
|
||||
seq_aux: bool = True,
|
||||
topk_method: str = "noaux_tc",
|
||||
router_dtype: str = "fp32",
|
||||
gated_attention_proj_granularity_type: str | None = None,
|
||||
no_kda_lora: bool = False,
|
||||
kda_safe_gate: bool = False,
|
||||
kda_lower_bound: float | None = None,
|
||||
short_conv_kernel_size: int = 4,
|
||||
architectures: list[str] | None = None,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
kwargs.pop("model_type", None)
|
||||
if architectures is None:
|
||||
architectures = ["BailingMoeV3ForCausalLM"]
|
||||
|
||||
if rope_parameters is not None:
|
||||
self.rope_parameters = dict(rope_parameters)
|
||||
elif rope_scaling is not None:
|
||||
self.rope_parameters = dict(rope_scaling)
|
||||
else:
|
||||
self.rope_parameters = {}
|
||||
if (
|
||||
"rope_type" not in self.rope_parameters
|
||||
and "type" not in self.rope_parameters
|
||||
):
|
||||
self.rope_parameters["rope_type"] = "default"
|
||||
self.rope_parameters.setdefault("rope_theta", rope_theta)
|
||||
if mrope_section is not None:
|
||||
_normalize_mrope_parameters(self, list(mrope_section))
|
||||
|
||||
self.vocab_size = vocab_size
|
||||
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.num_key_value_heads = num_key_value_heads
|
||||
self.hidden_act = hidden_act
|
||||
self.use_qkv_bias = use_qkv_bias
|
||||
self.use_bias = use_bias
|
||||
self.rms_norm_eps = rms_norm_eps
|
||||
self.embedding_dropout = embedding_dropout
|
||||
self.attention_dropout = attention_dropout
|
||||
self.output_dropout = output_dropout
|
||||
self.initializer_range = initializer_range
|
||||
self.max_position_embeddings = max_position_embeddings
|
||||
self.rope_theta = rope_theta
|
||||
self.partial_rotary_factor = partial_rotary_factor
|
||||
self.use_cache = use_cache
|
||||
self.max_window_layers = max_window_layers
|
||||
self.num_experts = num_experts
|
||||
self.num_shared_experts = num_shared_experts
|
||||
self.num_experts_per_tok = num_experts_per_tok
|
||||
self.n_group = n_group
|
||||
self.topk_group = topk_group
|
||||
self.moe_intermediate_size = moe_intermediate_size
|
||||
self.moe_shared_expert_intermediate_size = moe_shared_expert_intermediate_size
|
||||
self.first_k_dense_replace = first_k_dense_replace
|
||||
self.head_dim = head_dim or hidden_size // num_attention_heads
|
||||
self.output_router_logits = output_router_logits
|
||||
self.use_qk_norm = use_qk_norm
|
||||
self.num_nextn_predict_layers = num_nextn_predict_layers
|
||||
self.mtp_loss_scaling_factor = mtp_loss_scaling_factor
|
||||
self.moe_router_enable_expert_bias = moe_router_enable_expert_bias
|
||||
self.routed_scaling_factor = routed_scaling_factor
|
||||
self.layer_group_size = layer_group_size
|
||||
self.kv_lora_rank = kv_lora_rank
|
||||
self.q_lora_rank = q_lora_rank
|
||||
self.qk_rope_head_dim = qk_rope_head_dim
|
||||
self.v_head_dim = v_head_dim
|
||||
self.qk_nope_head_dim = qk_nope_head_dim
|
||||
self.qk_head_dim = qk_nope_head_dim + qk_rope_head_dim
|
||||
self.rope_interleave = rope_interleave
|
||||
self.score_function = score_function
|
||||
self.scoring_func = scoring_func
|
||||
self.seq_aux = seq_aux
|
||||
self.topk_method = topk_method
|
||||
self.router_dtype = router_dtype
|
||||
self.gated_attention_proj_granularity_type = (
|
||||
gated_attention_proj_granularity_type
|
||||
)
|
||||
self.no_kda_lora = no_kda_lora
|
||||
self.kda_safe_gate = kda_safe_gate
|
||||
self.kda_lower_bound = kda_lower_bound
|
||||
self.short_conv_kernel_size = short_conv_kernel_size
|
||||
|
||||
expected_layer_types = _build_layer_types(
|
||||
num_hidden_layers,
|
||||
layer_group_size,
|
||||
)
|
||||
if layers_block_type is not None:
|
||||
legacy_type_mapping = {
|
||||
"attention": "full_attention",
|
||||
"mamba": "linear_attention",
|
||||
"conv": "linear_attention",
|
||||
}
|
||||
normalized_block_types = [
|
||||
legacy_type_mapping.get(layer_type, layer_type)
|
||||
for layer_type in layers_block_type
|
||||
]
|
||||
if layer_types is not None and layer_types != normalized_block_types:
|
||||
raise ValueError(
|
||||
"Bailing V3 VL has conflicting layer_types and layers_block_type"
|
||||
)
|
||||
layer_types = normalized_block_types
|
||||
if layer_types is not None and layer_types != expected_layer_types:
|
||||
raise ValueError(
|
||||
"Bailing V3 VL layer_types must match the layer_group_size schedule"
|
||||
)
|
||||
self.layer_types = expected_layer_types
|
||||
|
||||
super().__init__(
|
||||
architectures=architectures,
|
||||
pad_token_id=pad_token_id,
|
||||
eos_token_id=eos_token_id,
|
||||
tie_word_embeddings=tie_word_embeddings,
|
||||
**kwargs,
|
||||
)
|
||||
self.validate_layer_type()
|
||||
|
||||
|
||||
class BailingMoeV3VisionConfig(PreTrainedConfig):
|
||||
model_type = "qwen3_moe_vit"
|
||||
base_config_key = "vision_config"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
depth: int = 27,
|
||||
hidden_size: int = 1152,
|
||||
hidden_act: str = "gelu_pytorch_tanh",
|
||||
intermediate_size: int = 4304,
|
||||
num_heads: int = 16,
|
||||
in_channels: int = 3,
|
||||
patch_size: int = 16,
|
||||
spatial_merge_size: int = 2,
|
||||
temporal_patch_size: int = 2,
|
||||
out_hidden_size: int = 3584,
|
||||
num_position_embeddings: int = 2304,
|
||||
deepstack_visual_indexes: list[int] | None = None,
|
||||
initializer_range: float = 0.02,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
kwargs.pop("model_type", None)
|
||||
super().__init__(**kwargs)
|
||||
self.depth = depth
|
||||
self.hidden_size = hidden_size
|
||||
self.hidden_act = hidden_act
|
||||
self.intermediate_size = intermediate_size
|
||||
self.num_heads = num_heads
|
||||
self.in_channels = in_channels
|
||||
self.patch_size = patch_size
|
||||
self.spatial_merge_size = spatial_merge_size
|
||||
self.temporal_patch_size = temporal_patch_size
|
||||
self.out_hidden_size = out_hidden_size
|
||||
self.num_position_embeddings = num_position_embeddings
|
||||
self.deepstack_visual_indexes = (
|
||||
[8, 16, 24]
|
||||
if deepstack_visual_indexes is None
|
||||
else deepstack_visual_indexes
|
||||
)
|
||||
self.initializer_range = initializer_range
|
||||
|
||||
|
||||
class BailingMoeV3VLConfig(PreTrainedConfig):
|
||||
model_type = "bailing_moe_v3_vl"
|
||||
keys_to_ignore_at_inference = ["past_key_values"]
|
||||
sub_configs = {
|
||||
"text_config": BailingMoeV3TextConfig,
|
||||
"vision_config": BailingMoeV3VisionConfig,
|
||||
}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
text_config: BailingMoeV3TextConfig | dict[str, Any] | None = None,
|
||||
vision_config: BailingMoeV3VisionConfig | dict[str, Any] | None = None,
|
||||
image_token_id: int = 151655,
|
||||
video_token_id: int = 151656,
|
||||
vision_start_token_id: int = 151652,
|
||||
vision_end_token_id: int = 151653,
|
||||
tie_word_embeddings: bool = False,
|
||||
mrope_section: list[int] | tuple[int, ...] | None = None,
|
||||
architectures: list[str] | None = None,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
kwargs.pop("model_type", None)
|
||||
if mrope_section is None:
|
||||
mrope_section = [12, 10, 10]
|
||||
self.mrope_section = list(mrope_section)
|
||||
|
||||
if text_config is None:
|
||||
text_config = BailingMoeV3TextConfig()
|
||||
elif isinstance(text_config, dict):
|
||||
text_config = dict(text_config)
|
||||
nested_mrope_section = text_config.pop("mrope_section", None)
|
||||
if (
|
||||
nested_mrope_section is not None
|
||||
and list(nested_mrope_section) != self.mrope_section
|
||||
):
|
||||
raise ValueError(
|
||||
"Bailing V3 VL has conflicting M-RoPE sections: "
|
||||
f"text={nested_mrope_section}, "
|
||||
f"top-level={self.mrope_section}"
|
||||
)
|
||||
text_config = BailingMoeV3TextConfig(**text_config)
|
||||
self.text_config = text_config
|
||||
_normalize_mrope_parameters(self.text_config, self.mrope_section)
|
||||
|
||||
if vision_config is None:
|
||||
vision_config = BailingMoeV3VisionConfig()
|
||||
elif isinstance(vision_config, dict):
|
||||
vision_config = BailingMoeV3VisionConfig(**vision_config)
|
||||
self.vision_config = vision_config
|
||||
|
||||
self.image_token_id = image_token_id
|
||||
self.video_token_id = video_token_id
|
||||
self.vision_start_token_id = vision_start_token_id
|
||||
self.vision_end_token_id = vision_end_token_id
|
||||
if architectures is None:
|
||||
architectures = ["BailingMoeV3VLForConditionalGeneration"]
|
||||
|
||||
super().__init__(
|
||||
architectures=architectures,
|
||||
tie_word_embeddings=tie_word_embeddings,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"BailingMoeV3TextConfig",
|
||||
"BailingMoeV3VisionConfig",
|
||||
"BailingMoeV3VLConfig",
|
||||
]
|
||||
@@ -1,75 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
# Adapted from
|
||||
# https://github.com/zai-org/ChatGLM2-6B
|
||||
from transformers import PreTrainedConfig
|
||||
|
||||
|
||||
class ChatGLMConfig(PreTrainedConfig):
|
||||
model_type = "chatglm"
|
||||
attribute_map = {
|
||||
"num_hidden_layers": "num_layers",
|
||||
"n_head_kv": "multi_query_group_num",
|
||||
}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
num_layers=28,
|
||||
padded_vocab_size=65024,
|
||||
hidden_size=4096,
|
||||
ffn_hidden_size=13696,
|
||||
kv_channels=128,
|
||||
num_attention_heads=32,
|
||||
seq_length=2048,
|
||||
hidden_dropout=0.0,
|
||||
attention_dropout=0.0,
|
||||
layernorm_epsilon=1e-5,
|
||||
rmsnorm=True,
|
||||
apply_residual_connection_post_layernorm=False,
|
||||
post_layer_norm=True,
|
||||
add_bias_linear=False,
|
||||
add_qkv_bias=False,
|
||||
interleaved_qkv=False,
|
||||
bias_dropout_fusion=True,
|
||||
multi_query_attention=False,
|
||||
multi_query_group_num=1,
|
||||
apply_query_key_layer_scaling=True,
|
||||
attention_softmax_in_fp32=True,
|
||||
fp32_residual_connection=False,
|
||||
quantization_bit=0,
|
||||
pre_seq_len=None,
|
||||
prefix_projection=False,
|
||||
**kwargs,
|
||||
):
|
||||
self.num_layers = num_layers
|
||||
self.vocab_size = padded_vocab_size
|
||||
self.padded_vocab_size = padded_vocab_size
|
||||
self.hidden_size = hidden_size
|
||||
self.ffn_hidden_size = ffn_hidden_size
|
||||
self.kv_channels = kv_channels
|
||||
self.num_attention_heads = num_attention_heads
|
||||
self.seq_length = seq_length
|
||||
# It is to be compatible with long lora.
|
||||
self.max_position_embeddings = seq_length
|
||||
self.hidden_dropout = hidden_dropout
|
||||
self.attention_dropout = attention_dropout
|
||||
self.layernorm_epsilon = layernorm_epsilon
|
||||
self.rmsnorm = rmsnorm
|
||||
self.apply_residual_connection_post_layernorm = (
|
||||
apply_residual_connection_post_layernorm
|
||||
)
|
||||
self.post_layer_norm = post_layer_norm
|
||||
self.add_bias_linear = add_bias_linear
|
||||
self.add_qkv_bias = add_qkv_bias
|
||||
self.bias_dropout_fusion = bias_dropout_fusion
|
||||
self.multi_query_attention = multi_query_attention
|
||||
self.multi_query_group_num = multi_query_group_num
|
||||
self.apply_query_key_layer_scaling = apply_query_key_layer_scaling
|
||||
self.attention_softmax_in_fp32 = attention_softmax_in_fp32
|
||||
self.fp32_residual_connection = fp32_residual_connection
|
||||
self.quantization_bit = quantization_bit
|
||||
self.pre_seq_len = pre_seq_len
|
||||
self.prefix_projection = prefix_projection
|
||||
self.interleaved_qkv = interleaved_qkv
|
||||
super().__init__(**kwargs)
|
||||
@@ -1,63 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Configuration for ColModernVBERT visual document retrieval model.
|
||||
|
||||
ColModernVBERT combines SigLIP vision encoder + ModernBERT text encoder
|
||||
with a pixel shuffle connector and ColBERT-style 128-dim per-token embeddings.
|
||||
|
||||
Reference: https://huggingface.co/ModernVBERT/colmodernvbert-merged
|
||||
"""
|
||||
|
||||
from transformers import ModernBertConfig, PreTrainedConfig, SiglipVisionConfig
|
||||
|
||||
|
||||
class ColModernVBertConfig(PreTrainedConfig):
|
||||
model_type = "colmodernvbert"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
embedding_dim: int = 128,
|
||||
image_token_id: int = 50407,
|
||||
pixel_shuffle_factor: int = 4,
|
||||
text_config: dict | None = None,
|
||||
vision_config: dict | None = None,
|
||||
**kwargs,
|
||||
):
|
||||
self.embedding_dim = embedding_dim
|
||||
self.image_token_id = image_token_id
|
||||
self.pixel_shuffle_factor = pixel_shuffle_factor
|
||||
|
||||
text_config = text_config or {}
|
||||
self.hidden_size = text_config.get("hidden_size", 768)
|
||||
|
||||
self.text_config = ModernBertConfig(
|
||||
vocab_size=text_config.get("vocab_size", 50408),
|
||||
hidden_size=text_config.get("hidden_size", 768),
|
||||
intermediate_size=text_config.get("intermediate_size", 1152),
|
||||
num_hidden_layers=text_config.get("num_hidden_layers", 22),
|
||||
num_attention_heads=text_config.get("num_attention_heads", 12),
|
||||
mlp_bias=text_config.get("mlp_bias", False),
|
||||
max_position_embeddings=text_config.get("max_position_embeddings", 8192),
|
||||
)
|
||||
|
||||
vision_config = vision_config or {}
|
||||
self.vision_config = SiglipVisionConfig(
|
||||
hidden_size=vision_config.get("hidden_size", 768),
|
||||
image_size=vision_config.get("image_size", 512),
|
||||
patch_size=vision_config.get("patch_size", 16),
|
||||
num_hidden_layers=vision_config.get("num_hidden_layers", 12),
|
||||
intermediate_size=vision_config.get("intermediate_size", 3072),
|
||||
num_attention_heads=vision_config.get("num_attention_heads", 12),
|
||||
)
|
||||
|
||||
# Ensure architectures is set so vLLM routes to our model class
|
||||
kwargs.setdefault("architectures", ["ColModernVBertForRetrieval"])
|
||||
super().__init__(**kwargs)
|
||||
|
||||
@property
|
||||
def image_seq_len(self) -> int:
|
||||
ps = self.vision_config.image_size // self.vision_config.patch_size
|
||||
return (ps * ps) // (self.pixel_shuffle_factor**2)
|
||||
|
||||
def get_text_config(self, **kwargs):
|
||||
return self.text_config
|
||||
@@ -1,56 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""ColPali configuration that extends PaliGemmaConfig with embedding projection
|
||||
fields. This allows ColPali models to be loaded without trust_remote_code
|
||||
by mapping their custom model_type (colpali) to a standard config class
|
||||
that vLLM understands.
|
||||
|
||||
Supported model_types:
|
||||
- colpali (vidore/colpali-v1.3-hf)
|
||||
"""
|
||||
|
||||
from transformers import PaliGemmaConfig
|
||||
|
||||
|
||||
class ColPaliConfig(PaliGemmaConfig):
|
||||
"""Configuration class for ColPali models.
|
||||
|
||||
Extends PaliGemmaConfig with additional fields used by ColPali variants
|
||||
for the embedding projection layer.
|
||||
"""
|
||||
|
||||
model_type = "colpali"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
embedding_dim: int | None = None,
|
||||
embed_dim: int | None = None,
|
||||
dim: int | None = None,
|
||||
colbert_dim: int | None = None,
|
||||
pooling: str | None = None,
|
||||
vlm_config: dict | None = None,
|
||||
**kwargs,
|
||||
):
|
||||
# Store embedding projection config fields
|
||||
self.embedding_dim = embedding_dim
|
||||
self.embed_dim = embed_dim
|
||||
self.dim = dim
|
||||
self.colbert_dim = colbert_dim
|
||||
self.pooling = pooling
|
||||
|
||||
# The HF checkpoint nests PaliGemma config inside "vlm_config".
|
||||
# Flatten it so PaliGemmaConfig receives vision_config, text_config,
|
||||
# image_token_index, etc. directly.
|
||||
# Use setdefault to avoid overwriting keys already set (e.g.
|
||||
# model_type="colpali" would be clobbered by "paligemma" from
|
||||
# vlm_config).
|
||||
if vlm_config is not None:
|
||||
vlm_dict = (
|
||||
vlm_config if isinstance(vlm_config, dict) else vlm_config.to_dict()
|
||||
)
|
||||
_conflicting = {"model_type", "_name_or_path"}
|
||||
for key, value in vlm_dict.items():
|
||||
if key not in _conflicting:
|
||||
kwargs.setdefault(key, value)
|
||||
|
||||
super().__init__(**kwargs)
|
||||
@@ -1,147 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from transformers import NemotronHConfig
|
||||
from transformers.configuration_utils import PreTrainedConfig
|
||||
from transformers.models.siglip2.configuration_siglip2 import Siglip2VisionConfig
|
||||
|
||||
|
||||
def _normalize_mrope_parameters(config: NemotronHConfig) -> None:
|
||||
"""Normalize the checkpoint's mRoPE configuration for vLLM."""
|
||||
rope_parameters = dict(getattr(config, "rope_parameters", None) or {})
|
||||
mrope_section = rope_parameters.get("mrope_section")
|
||||
if mrope_section is None:
|
||||
return
|
||||
|
||||
rope_parameters["mrope_section"] = list(mrope_section)
|
||||
rope_parameters.setdefault("mrope_interleaved", True)
|
||||
config.rope_parameters = rope_parameters
|
||||
|
||||
|
||||
class Cosmos3EdgeTextConfig(NemotronHConfig):
|
||||
"""Dense Cosmos3 Edge text config backed by Nemotron-H layers."""
|
||||
|
||||
model_type = "cosmos3_edge_text"
|
||||
has_no_defaults_at_init = True
|
||||
ignore_keys_at_rope_validation = {"mrope_section", "mrope_interleaved"}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
num_hidden_layers: int = 28,
|
||||
hidden_act: str = "relu2",
|
||||
rms_norm_eps: float = 1e-5,
|
||||
layers_block_type: list[str] | None = None,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
# Each decoder block is an attention layer followed by an MLP layer
|
||||
if layers_block_type is None:
|
||||
layers_block_type = ["full_attention", "mlp"] * num_hidden_layers
|
||||
super().__init__(
|
||||
layers_block_type=layers_block_type,
|
||||
mlp_hidden_act=hidden_act,
|
||||
layer_norm_epsilon=rms_norm_eps,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
config_dict = super().to_dict()
|
||||
config_dict["num_hidden_layers"] = self.num_hidden_layers // 2
|
||||
config_dict["hidden_act"] = config_dict.pop("mlp_hidden_act")
|
||||
config_dict["rms_norm_eps"] = config_dict.pop("layer_norm_epsilon")
|
||||
return config_dict
|
||||
|
||||
|
||||
class Cosmos3EdgeProjectorConfig(PreTrainedConfig):
|
||||
model_type = "cosmos3_edge_projector"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
input_hidden_size: int = 1024,
|
||||
use_postshuffle_norm: bool = False,
|
||||
spatial_merge_size: int = 2,
|
||||
merger_intermediate_size: int = 11520,
|
||||
out_hidden_size: int = 1024,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
super().__init__(**kwargs)
|
||||
self.input_hidden_size = input_hidden_size
|
||||
self.use_postshuffle_norm = use_postshuffle_norm
|
||||
self.spatial_merge_size = spatial_merge_size
|
||||
self.merger_intermediate_size = merger_intermediate_size
|
||||
self.out_hidden_size = out_hidden_size
|
||||
|
||||
|
||||
class Cosmos3EdgeVisionConfig(Siglip2VisionConfig):
|
||||
model_type = "cosmos3_edge_vision"
|
||||
|
||||
|
||||
class Cosmos3EdgeConfig(PreTrainedConfig):
|
||||
model_type = "cosmos3_edge"
|
||||
keys_to_ignore_at_inference = ["past_key_values"]
|
||||
has_no_defaults_at_init = True
|
||||
sub_configs = {
|
||||
"vision_config": Cosmos3EdgeVisionConfig,
|
||||
"projector_config": Cosmos3EdgeProjectorConfig,
|
||||
"text_config": Cosmos3EdgeTextConfig,
|
||||
}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
text_config: Cosmos3EdgeTextConfig | dict | None = None,
|
||||
vision_config: Cosmos3EdgeVisionConfig | dict | None = None,
|
||||
projector_config: Cosmos3EdgeProjectorConfig | dict | None = None,
|
||||
image_token_id: int = 19,
|
||||
video_token_id: int = 18,
|
||||
vision_start_token_id: int = 20,
|
||||
vision_end_token_id: int = 21,
|
||||
tie_word_embeddings: bool = False,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
if text_config is None:
|
||||
text_config = {}
|
||||
if vision_config is None:
|
||||
vision_config = {}
|
||||
if projector_config is None:
|
||||
projector_config = {}
|
||||
|
||||
self.text_config = (
|
||||
Cosmos3EdgeTextConfig(**text_config)
|
||||
if isinstance(text_config, dict)
|
||||
else text_config
|
||||
)
|
||||
_normalize_mrope_parameters(self.text_config)
|
||||
|
||||
self.vision_config = (
|
||||
Cosmos3EdgeVisionConfig(**vision_config)
|
||||
if isinstance(vision_config, dict)
|
||||
else vision_config
|
||||
)
|
||||
self.projector_config = (
|
||||
Cosmos3EdgeProjectorConfig(**projector_config)
|
||||
if isinstance(projector_config, dict)
|
||||
else projector_config
|
||||
)
|
||||
|
||||
# Qwen3-VL processing and M-RoPE read these attributes from the
|
||||
# vision config, while this checkpoint stores them in projector config.
|
||||
self.vision_config.spatial_merge_size = self.projector_config.spatial_merge_size
|
||||
self.vision_config.temporal_patch_size = 1
|
||||
self.vision_config.out_hidden_size = self.projector_config.out_hidden_size
|
||||
|
||||
self.image_token_id = image_token_id
|
||||
self.video_token_id = video_token_id
|
||||
self.vision_start_token_id = vision_start_token_id
|
||||
self.vision_end_token_id = vision_end_token_id
|
||||
|
||||
super().__init__(
|
||||
tie_word_embeddings=tie_word_embeddings,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"Cosmos3EdgeConfig",
|
||||
"Cosmos3EdgeProjectorConfig",
|
||||
"Cosmos3EdgeTextConfig",
|
||||
"Cosmos3EdgeVisionConfig",
|
||||
]
|
||||
@@ -1,62 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from typing import Any
|
||||
|
||||
from transformers import PreTrainedConfig
|
||||
|
||||
|
||||
class DeepseekV41Config(PreTrainedConfig):
|
||||
"""DeepSeek V4.1 config.
|
||||
|
||||
The HF config nests the text model under ``text_config`` and the vision
|
||||
tower under ``vision_config``. The vLLM model code (ported from
|
||||
``deepseek_v4``) reads flat attributes, so both sub-configs are flattened
|
||||
onto the top level here: text fields are exposed as-is, vision fields
|
||||
with the ``vision_*`` naming used by ``deepseek_v41.common.vision``.
|
||||
"""
|
||||
|
||||
model_type = "deepseek_v41"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
text_config: dict[str, Any] | None = None,
|
||||
vision_config: dict[str, Any] | None = None,
|
||||
**kwargs,
|
||||
):
|
||||
text_config = dict(text_config or {})
|
||||
vision_config = dict(vision_config or {})
|
||||
|
||||
# ``rope_scaling`` is a property in Transformers v5 (backed by
|
||||
# ``rope_parameters``); capture it here and restore after
|
||||
# super().__init__, which re-standardizes rope params.
|
||||
rope_scaling = text_config.pop("rope_scaling", None)
|
||||
|
||||
for key, value in text_config.items():
|
||||
if key == "model_type":
|
||||
continue
|
||||
# Don't clobber PreTrainedConfig properties (e.g. is_encoder_decoder).
|
||||
if isinstance(getattr(type(self), key, None), property):
|
||||
continue
|
||||
setattr(self, key, value)
|
||||
|
||||
super().__init__(**kwargs)
|
||||
if rope_scaling is not None:
|
||||
self.rope_parameters = rope_scaling
|
||||
|
||||
# The v4.1 quantization_config carries the expert dtype; the model
|
||||
# code reads it from the top-level hf_config.
|
||||
quant_cfg = getattr(self, "quantization_config", None) or {}
|
||||
if not hasattr(self, "expert_dtype") and "expert_dtype" in quant_cfg:
|
||||
self.expert_dtype = quant_cfg["expert_dtype"]
|
||||
|
||||
vision_n_layers = vision_config.get("num_hidden_layers", 0)
|
||||
self.vision_n_layers = vision_n_layers
|
||||
self.vision_dim = vision_config.get("hidden_size", 1024)
|
||||
self.vision_n_heads = vision_config.get("num_attention_heads", 16)
|
||||
self.vision_inter_dim = vision_config.get("intermediate_size", 2816)
|
||||
self.vision_patch_size = vision_config.get("patch_size", 14)
|
||||
self.vision_rope_theta = vision_config.get("rope_theta", 10000.0)
|
||||
self.vision_downsample_ratio = vision_config.get("downsample_ratio", 3)
|
||||
self.vision_max_n_token = vision_config.get("max_image_tokens", 1024)
|
||||
self.vision_min_pixels = vision_config.get("min_pixels", 295936)
|
||||
self.vision_max_wh_ratio = vision_config.get("max_wh_ratio")
|
||||
@@ -1,126 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
# adapted from https://github.com/deepseek-ai/DeepSeek-VL2/blob/faf18023f24b962b32d9f0a2d89e402a8d383a78/deepseek_vl2/models/modeling_deepseek_vl_v2.py#L115-L268
|
||||
|
||||
from huggingface_hub.dataclasses import strict
|
||||
from transformers import DeepseekV2Config, PreTrainedConfig
|
||||
|
||||
|
||||
class VisionEncoderConfig(PreTrainedConfig):
|
||||
model_type: str = "vision"
|
||||
|
||||
model_name: str = "vit_so400m_patch14_siglip_384.webli"
|
||||
image_size: int = 384
|
||||
patch_size: int = 16
|
||||
width: int = 1024
|
||||
layers: int = 24
|
||||
heads: int = 16
|
||||
mlp_ratio: int = 4
|
||||
global_pool: str = "map"
|
||||
ignore_head: bool = True
|
||||
class_token: bool = False
|
||||
num_classes: int = 0
|
||||
use_checkpoint: bool = False
|
||||
weight_init: str = "skip"
|
||||
deterministic: bool = False
|
||||
num_recomputing_layers: int = 0
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
model_name: str = "vit_so400m_patch14_siglip_384.webli",
|
||||
image_size: int = 384,
|
||||
patch_size: int = 16,
|
||||
width: int = 1024,
|
||||
layers: int = 24,
|
||||
heads: int = 16,
|
||||
mlp_ratio: int = 4,
|
||||
global_pool: str = "map",
|
||||
ignore_head: bool = True,
|
||||
class_token: bool = False,
|
||||
num_classes: int = 0,
|
||||
use_checkpoint: bool = False,
|
||||
**kwargs,
|
||||
):
|
||||
self.model_name = model_name
|
||||
self.image_size = image_size
|
||||
self.patch_size = patch_size
|
||||
self.width = width
|
||||
self.layers = layers
|
||||
self.heads = heads
|
||||
self.mlp_ratio = mlp_ratio
|
||||
self.global_pool = global_pool
|
||||
self.ignore_head = ignore_head
|
||||
self.class_token = class_token
|
||||
self.num_classes = num_classes
|
||||
self.use_checkpoint = use_checkpoint
|
||||
|
||||
super().__init__(**kwargs)
|
||||
|
||||
|
||||
class MlpProjectorConfig(PreTrainedConfig):
|
||||
model_type = "mlp_projector"
|
||||
projector_type: str = "downsample_mlp_gelu"
|
||||
input_dim: int = 1152
|
||||
n_embed: int = 2048
|
||||
depth: int = 2
|
||||
mlp_ratio: int = 1
|
||||
downsample_ratio: int = 2
|
||||
token_pooling: bool = False
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
projector_type: str = "downsample_mlp_gelu",
|
||||
input_dim: int = 1152,
|
||||
n_embed: int = 2048,
|
||||
depth: int = 2,
|
||||
mlp_ratio: int = 1,
|
||||
downsample_ratio: int = 2,
|
||||
**kwargs,
|
||||
):
|
||||
self.projector_type = projector_type
|
||||
self.input_dim = input_dim
|
||||
self.n_embed = n_embed
|
||||
self.depth = depth
|
||||
self.mlp_ratio = mlp_ratio
|
||||
self.downsample_ratio = downsample_ratio
|
||||
|
||||
super().__init__(**kwargs)
|
||||
|
||||
|
||||
@strict
|
||||
class DeepseekVLV2TextConfig(DeepseekV2Config):
|
||||
kv_lora_rank: int | None = DeepseekV2Config.kv_lora_rank
|
||||
|
||||
|
||||
class DeepseekVLV2Config(PreTrainedConfig):
|
||||
model_type = "deepseek_vl_v2"
|
||||
|
||||
tile_tag: str = "2D"
|
||||
global_view_pos: str = "head"
|
||||
candidate_resolutions: tuple[tuple[int, int]] = ((384, 384),)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
tile_tag: str = "tile_tag",
|
||||
global_view_pos: str = "head",
|
||||
candidate_resolutions: tuple[tuple[int, int]] = ((384, 384),),
|
||||
**kwargs,
|
||||
):
|
||||
architectures = kwargs.setdefault("architectures", ["DeepseekVLV2ForCausalLM"])
|
||||
|
||||
self.vision_config = VisionEncoderConfig(**kwargs.pop("vision_config", {}))
|
||||
self.projector_config = MlpProjectorConfig(**kwargs.pop("projector_config", {}))
|
||||
self.text_config = DeepseekVLV2TextConfig(**kwargs.pop("language_config", {}))
|
||||
|
||||
self.tile_tag = tile_tag
|
||||
self.global_view_pos = global_view_pos
|
||||
self.candidate_resolutions = candidate_resolutions
|
||||
self.vocab_size = self.text_config.vocab_size
|
||||
|
||||
# update model_type for OCR models
|
||||
if "DeepseekOCRForCausalLM" in architectures:
|
||||
kwargs["model_type"] = "deepseek_ocr"
|
||||
elif "DeepseekOCR2ForCausalLM" in architectures:
|
||||
kwargs["model_type"] = "deepseek_ocr2"
|
||||
super().__init__(**kwargs)
|
||||
@@ -1,25 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from transformers import DeepseekV3Config
|
||||
|
||||
|
||||
class Dots3NoteConfig(DeepseekV3Config):
|
||||
"""Configuration for the Dots3Note hybrid DSA/SWA model."""
|
||||
|
||||
model_type = "dots3_note"
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
# These fields are absent from existing Note config.json files. Do
|
||||
# not inherit DeepSeek-V3's 8-group/4-group router defaults: Note was
|
||||
# trained with an ungrouped (1/1) noaux_tc router, as defined by the
|
||||
# reference Dots3Config in SGLang haimain. A different grouping
|
||||
# changes the selected experts at every MoE layer.
|
||||
kwargs.setdefault("n_group", 1)
|
||||
kwargs.setdefault("topk_group", 1)
|
||||
# Dots3 projects the indexer RoPE coordinates in adjacent (GPT-J)
|
||||
# pairs. DeepSeek-V3.2 defaults to the split-half NeoX layout when
|
||||
# this flag is absent, which rotates different learned coordinates.
|
||||
kwargs.setdefault("indexer_rope_interleave", True)
|
||||
kwargs.setdefault("num_nextn_predict_layers", 1)
|
||||
super().__init__(**kwargs)
|
||||
@@ -1,89 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
# Adapted from
|
||||
# https://huggingface.co/tiiuae/falcon-7b/blob/main/configuration_RW.py
|
||||
# Copyright 2023 The vLLM team.
|
||||
# Copyright 2022 the Big Science Workshop and HuggingFace Inc. 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.
|
||||
"""Falcon configuration."""
|
||||
|
||||
from transformers.configuration_utils import PreTrainedConfig
|
||||
|
||||
|
||||
class RWConfig(PreTrainedConfig):
|
||||
model_type = "falcon"
|
||||
keys_to_ignore_at_inference = ["past_key_values"]
|
||||
attribute_map = {
|
||||
"num_hidden_layers": "n_layer",
|
||||
"num_attention_heads": "n_head",
|
||||
"num_kv_heads": "n_head_kv",
|
||||
}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vocab_size=250880,
|
||||
hidden_size=64,
|
||||
n_layer=2,
|
||||
n_head=8,
|
||||
layer_norm_epsilon=1e-5,
|
||||
initializer_range=0.02,
|
||||
use_cache=True,
|
||||
bos_token_id=1,
|
||||
eos_token_id=2,
|
||||
hidden_dropout=0.0,
|
||||
attention_dropout=0.0,
|
||||
multi_query=True,
|
||||
n_head_kv=None,
|
||||
alibi=False,
|
||||
bias=False,
|
||||
parallel_attn=False,
|
||||
new_decoder_architecture=False,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
self.vocab_size = vocab_size
|
||||
# Backward compatibility with n_embed kwarg
|
||||
n_embed = kwargs.pop("n_embed", None)
|
||||
self.hidden_size = hidden_size if n_embed is None else n_embed
|
||||
self.n_layer = n_layer
|
||||
self.n_head = n_head
|
||||
self.layer_norm_epsilon = layer_norm_epsilon
|
||||
self.initializer_range = initializer_range
|
||||
self.use_cache = use_cache
|
||||
self.hidden_dropout = hidden_dropout
|
||||
self.attention_dropout = attention_dropout
|
||||
|
||||
self.bos_token_id = bos_token_id
|
||||
self.eos_token_id = eos_token_id
|
||||
self.multi_query = multi_query
|
||||
self.n_head_kv = 1 if n_head_kv is None else n_head_kv
|
||||
self.alibi = alibi
|
||||
self.bias = bias
|
||||
self.parallel_attn = parallel_attn
|
||||
self.new_decoder_architecture = new_decoder_architecture
|
||||
|
||||
if self.hidden_size == 8192:
|
||||
# Hack for falcon-40b
|
||||
self.new_decoder_architecture = True
|
||||
|
||||
super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
|
||||
|
||||
@property
|
||||
def head_dim(self):
|
||||
return self.hidden_size // self.n_head
|
||||
|
||||
@property
|
||||
def rotary(self):
|
||||
return not self.alibi
|
||||
@@ -1,120 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from transformers import CONFIG_MAPPING, PreTrainedConfig
|
||||
|
||||
# NOTE: Temporary shim for FunAudioChat checkpoints.
|
||||
# These checkpoints use `model_type="funaudiochat"`, which is not currently
|
||||
# recognized by released Transformers, and the public checkpoint does not
|
||||
# provide an `auto_map` to enable `trust_remote_code=True`.
|
||||
# Remove this file once Transformers adds native support (or the checkpoint
|
||||
# provides an `auto_map`) and vLLM can rely on `AutoConfig.from_pretrained()`.
|
||||
|
||||
|
||||
class FunAudioChatAudioEncoderConfig(PreTrainedConfig):
|
||||
model_type = "funaudiochat_audio_encoder"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
_attn_implementation: str | None = None,
|
||||
num_mel_bins: int = 128,
|
||||
encoder_layers: int = 32,
|
||||
encoder_attention_heads: int = 20,
|
||||
encoder_ffn_dim: int = 5120,
|
||||
d_model: int = 1280,
|
||||
dropout: float = 0.0,
|
||||
attention_dropout: float = 0.0,
|
||||
activation_function: str = "gelu",
|
||||
activation_dropout: float = 0.0,
|
||||
scale_embedding: bool = False,
|
||||
initializer_range: float = 0.02,
|
||||
max_source_positions: int = 1500,
|
||||
n_window: int = 100,
|
||||
output_dim: int = 3584,
|
||||
bos_token_id: int | None = None,
|
||||
codebook_size: int | None = None,
|
||||
continuous_features_mode: str = "replace",
|
||||
crq_transformer_config: dict | None = None,
|
||||
eos_token_id: int | None = None,
|
||||
group_size: int = 5,
|
||||
enable_audio_invert_tower: bool = True,
|
||||
pad_token_id: int | None = None,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
attn_impl = kwargs.pop("_attn_implementation", None) or _attn_implementation
|
||||
super().__init__(**kwargs)
|
||||
# Match HF default for attention implementation selection.
|
||||
self._attn_implementation = attn_impl or "sdpa"
|
||||
|
||||
self.num_mel_bins = num_mel_bins
|
||||
self.d_model = d_model
|
||||
self.encoder_layers = encoder_layers
|
||||
self.encoder_attention_heads = encoder_attention_heads
|
||||
self.encoder_ffn_dim = encoder_ffn_dim
|
||||
self.dropout = dropout
|
||||
self.attention_dropout = attention_dropout
|
||||
self.activation_function = activation_function
|
||||
self.activation_dropout = activation_dropout
|
||||
self.num_hidden_layers = encoder_layers
|
||||
self.initializer_range = initializer_range
|
||||
self.scale_embedding = scale_embedding
|
||||
self.max_source_positions = max_source_positions
|
||||
self.n_window = n_window
|
||||
self.output_dim = output_dim
|
||||
|
||||
self.bos_token_id = bos_token_id
|
||||
self.codebook_size = codebook_size
|
||||
self.continuous_features_mode = continuous_features_mode
|
||||
self.crq_transformer_config = crq_transformer_config
|
||||
self.eos_token_id = eos_token_id
|
||||
self.group_size = group_size
|
||||
self.enable_audio_invert_tower = enable_audio_invert_tower
|
||||
self.pad_token_id = pad_token_id
|
||||
|
||||
|
||||
class FunAudioChatConfig(PreTrainedConfig):
|
||||
model_type = "funaudiochat"
|
||||
attribute_map = {
|
||||
"audio_token_id": "audio_token_index",
|
||||
}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
audio_config: PreTrainedConfig | dict | None = None,
|
||||
text_config: PreTrainedConfig | dict | None = None,
|
||||
audio_token_index: int = 151646,
|
||||
ignore_index: int = -100,
|
||||
hidden_size: int | None = None,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
self.audio_token_index = audio_token_index
|
||||
self.ignore_index = ignore_index
|
||||
|
||||
if audio_config is None:
|
||||
self.audio_config = FunAudioChatAudioEncoderConfig()
|
||||
elif isinstance(audio_config, dict):
|
||||
default_model_type = FunAudioChatAudioEncoderConfig.model_type
|
||||
audio_config.setdefault("model_type", default_model_type)
|
||||
self.audio_config = FunAudioChatAudioEncoderConfig(**audio_config)
|
||||
else:
|
||||
self.audio_config = audio_config
|
||||
|
||||
if text_config is None:
|
||||
self.text_config = CONFIG_MAPPING["qwen2"]()
|
||||
elif isinstance(text_config, dict):
|
||||
# Default to qwen2 for backwards compatibility; FunAudioChat uses
|
||||
# qwen3 in practice for recent checkpoints.
|
||||
text_config.setdefault("model_type", "qwen2")
|
||||
self.text_config = CONFIG_MAPPING[text_config["model_type"]](**text_config)
|
||||
else:
|
||||
self.text_config = text_config
|
||||
|
||||
self.hidden_size = (
|
||||
int(self.text_config.hidden_size)
|
||||
if hidden_size is None
|
||||
else int(hidden_size)
|
||||
)
|
||||
|
||||
super().__init__(**kwargs)
|
||||
@@ -1,173 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from huggingface_hub.dataclasses import strict
|
||||
from transformers.configuration_utils import PreTrainedConfig
|
||||
from transformers.modeling_rope_utils import RopeParameters
|
||||
|
||||
|
||||
@strict
|
||||
class HYV4Config(PreTrainedConfig):
|
||||
r"""Configuration class for the HY V4 (`HYV4ForCausalLM`) model.
|
||||
|
||||
Kept field-for-field in sync with
|
||||
`transformers.models.hy_v4.configuration_hy_v4.HYV4Config` so that a
|
||||
checkpoint resolves to the same values through either class. Registering it
|
||||
in vLLM's `_CONFIG_REGISTRY` lets the architecture load without
|
||||
`trust_remote_code` and without an `auto_map` module next to the weights.
|
||||
|
||||
HYV4 is a mixture-of-experts causal language model using Multi-head Latent
|
||||
Attention (MLA), DeepSeek-style sparse attention (DSA), gated MLA,
|
||||
learnable attention sinks, and independent Hyper-Connections (iHC).
|
||||
|
||||
The `layer_types`, `num_nextn_predict_layers` and `mtp_loss_factor` fields
|
||||
below are vLLM-only additions: upstream leaves them to `**kwargs`, but
|
||||
vLLM reads them directly (sparse-attention selection and MTP speculative
|
||||
decoding), so they are declared to give checkpoints that omit them a
|
||||
working default instead of a `None`.
|
||||
|
||||
Args:
|
||||
mlp_layer_types: Per-layer MLP kind, `"dense"` or `"sparse"`. Defaults
|
||||
to one dense layer followed by sparse MoE layers.
|
||||
layer_types: Per-layer attention kind, e.g. `"full_attention"` or
|
||||
`"deepseek_sparse_attention"`.
|
||||
indexer_types: Per-layer DSA indexer kind, `"full"` or `"shared"`. A
|
||||
shared layer reuses the most recent full indexer in the same
|
||||
forward request.
|
||||
index_topk: Maximum number of key positions selected by each DSA query.
|
||||
index_head_dim: Hidden dimension of each DSA indexer head.
|
||||
index_n_heads: Number of DSA indexer heads.
|
||||
enable_lm_head_fp32: Whether the language-model head emits float32
|
||||
logits. Surfaced as ``head_dtype`` so `LogitsProcessor` accumulates
|
||||
the projection into fp32 while the weight stays in the model dtype.
|
||||
enable_ihc: Whether independent Hyper-Connections are enabled.
|
||||
hc_mult: Number of hidden-state channels maintained by iHC.
|
||||
hc_magnitude: Scale applied to the iHC post-gating branch.
|
||||
hc_eps: Numerical epsilon added to iHC sigmoid gates.
|
||||
gated_mla: Whether to gate the MLA output.
|
||||
gating_type: MLA gate granularity, `"elementwise"` or `"headwise"`.
|
||||
learnable_sink: Whether to add a learned per-head attention sink.
|
||||
learnable_sink_init: Initial value of each learned attention-sink
|
||||
logit.
|
||||
swiglu_limit: Magnitude of the routed-expert SwiGLU clamp. Values at or
|
||||
below zero disable the clamp.
|
||||
num_nextn_predict_layers: Number of MTP layers in the checkpoint.
|
||||
mtp_loss_factor: Training-time MTP loss weight (unused at inference).
|
||||
|
||||
"""
|
||||
|
||||
model_type = "hy_v4"
|
||||
keys_to_ignore_at_inference = ["past_key_values"]
|
||||
attribute_map = {
|
||||
"num_local_experts": "n_routed_experts",
|
||||
}
|
||||
base_model_tp_plan = {
|
||||
"layers.*.self_attn.q_b_proj": "colwise",
|
||||
"layers.*.self_attn.kv_a_proj_with_mqa": "mla_kv_a_proj",
|
||||
"layers.*.self_attn.kv_b_proj": "colwise",
|
||||
"layers.*.self_attn.o_proj": "rowwise",
|
||||
"layers.*.self_attn.linear_gate": "colwise",
|
||||
"layers.*.mlp.experts.gate_up_proj": "packed_colwise",
|
||||
"layers.*.mlp.experts.down_proj": "rowwise",
|
||||
"layers.*.mlp.experts": "moe_tp_experts",
|
||||
"layers.*.mlp.shared_experts.gate_proj": "colwise",
|
||||
"layers.*.mlp.shared_experts.up_proj": "colwise",
|
||||
"layers.*.mlp.shared_experts.down_proj": "rowwise",
|
||||
"layers.*.mlp.gate_proj": "colwise",
|
||||
"layers.*.mlp.up_proj": "colwise",
|
||||
"layers.*.mlp.down_proj": "rowwise",
|
||||
}
|
||||
base_model_pp_plan = {
|
||||
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
|
||||
"layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
|
||||
"norm": (["hidden_states"], ["hidden_states"]),
|
||||
}
|
||||
|
||||
vocab_size: int = 120832
|
||||
hidden_size: int = 2816
|
||||
intermediate_size: int = 6912
|
||||
moe_intermediate_size: int = 768
|
||||
num_hidden_layers: int = 34
|
||||
num_attention_heads: int = 32
|
||||
num_key_value_heads: int = 32
|
||||
head_dim: int = 256
|
||||
hidden_act: str = "silu"
|
||||
max_position_embeddings: int = 262144
|
||||
initializer_range: float = 0.006
|
||||
rms_norm_eps: float = 1e-5
|
||||
use_cache: bool = True
|
||||
pad_token_id: int | None = 120002
|
||||
bos_token_id: int | None = 120000
|
||||
eos_token_id: int | list[int] | None = 120025
|
||||
tie_word_embeddings: bool = False
|
||||
attention_bias: bool = False
|
||||
attention_dropout: float = 0.0
|
||||
n_routed_experts: int = 256
|
||||
n_shared_experts: int = 1
|
||||
num_experts_per_tok: int = 8
|
||||
routed_scaling_factor: float = 2.827
|
||||
norm_topk_prob: bool = True
|
||||
q_lora_rank: int = 1536
|
||||
kv_lora_rank: int = 512
|
||||
qk_nope_head_dim: int = 192
|
||||
qk_rope_head_dim: int = 64
|
||||
v_head_dim: int = 256
|
||||
mlp_layer_types: list[str] | None = None
|
||||
layer_types: list[str] | None = None
|
||||
index_topk: int = 2048
|
||||
index_head_dim: int = 128
|
||||
index_n_heads: int = 16
|
||||
indexer_types: list[str] | None = None
|
||||
enable_lm_head_fp32: bool = True
|
||||
enable_ihc: bool = True
|
||||
hc_mult: int = 4
|
||||
hc_magnitude: float = 2.0
|
||||
hc_eps: float = 1e-6
|
||||
gated_mla: bool = True
|
||||
gating_type: str = "elementwise"
|
||||
learnable_sink: bool = True
|
||||
learnable_sink_init: float = 0.0
|
||||
swiglu_limit: float = 10.0
|
||||
rope_parameters: RopeParameters | dict | None = None
|
||||
num_nextn_predict_layers: int = 1
|
||||
mtp_loss_factor: float = 0.1
|
||||
|
||||
def __post_init__(self, **kwargs):
|
||||
self.qk_head_dim = self.qk_nope_head_dim + self.qk_rope_head_dim
|
||||
# RoPE applies only to the rope slice, so point `head_dim` at it: the
|
||||
# inherited rotary embedding reads `config.head_dim` and then computes
|
||||
# the right frequencies with no override.
|
||||
self.head_dim = self.qk_rope_head_dim
|
||||
|
||||
if self.mlp_layer_types is None:
|
||||
self.mlp_layer_types = ["dense"] * min(1, self.num_hidden_layers) + [
|
||||
"sparse"
|
||||
] * max(self.num_hidden_layers - 1, 0)
|
||||
if self.indexer_types is None:
|
||||
self.indexer_types = [
|
||||
"full" if layer_idx == 0 or (layer_idx - 1) % 4 == 0 else "shared"
|
||||
for layer_idx in range(self.num_hidden_layers)
|
||||
]
|
||||
# `PreTrainedConfig` validates `layer_types` against a fixed allow-list
|
||||
# in which "deepseek_sparse_attention" is the only accepted spelling of
|
||||
# a DSA layer. The model treats "sparse_attention" and "sparse" as
|
||||
# equivalent, so fold them in before the base class validates.
|
||||
if self.layer_types is not None:
|
||||
self.layer_types = [
|
||||
"deepseek_sparse_attention"
|
||||
if lt in ("sparse_attention", "sparse")
|
||||
else lt
|
||||
for lt in self.layer_types
|
||||
]
|
||||
|
||||
# `ModelConfig.head_dtype` reads this off the HF config, so an fp32 head
|
||||
# needs no model-side dtype juggling: LogitsProcessor picks the
|
||||
# `torch.mm(out_dtype=float32)` path and leaves the weight in the model
|
||||
# dtype. Only fill it in when the checkpoint (or --hf-overrides) has not
|
||||
# already pinned a value.
|
||||
if self.enable_lm_head_fp32 and getattr(self, "head_dtype", None) is None:
|
||||
self.head_dtype = "float32"
|
||||
|
||||
super().__post_init__(**kwargs)
|
||||
|
||||
|
||||
__all__ = ["HYV4Config"]
|
||||
@@ -1,99 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from __future__ import annotations
|
||||
|
||||
from transformers import Qwen3Config
|
||||
from transformers.models.siglip2.configuration_siglip2 import Siglip2VisionConfig
|
||||
|
||||
|
||||
class PixelShuffleSiglip2VisionConfig(Siglip2VisionConfig):
|
||||
"""Vision configuration for Isaac with Pixel Shuffle support.
|
||||
|
||||
Extends Siglip2VisionConfig with additional fields for pixel shuffle.
|
||||
"""
|
||||
|
||||
model_type = "pixel_shuffle_siglip2"
|
||||
base_config_key = "vision_config"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
pixel_shuffle_scale_factor: int = 1,
|
||||
num_patches: int = 256,
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__(**kwargs)
|
||||
|
||||
# Add our custom fields
|
||||
self.pixel_shuffle_scale_factor = pixel_shuffle_scale_factor
|
||||
self.num_patches = num_patches
|
||||
|
||||
|
||||
class IsaacConfig(Qwen3Config):
|
||||
"""Configuration class for Isaac multimodal model."""
|
||||
|
||||
model_type = "isaac"
|
||||
sub_configs = {
|
||||
"vision_config": PixelShuffleSiglip2VisionConfig,
|
||||
"text_config": Qwen3Config,
|
||||
}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
text_config=None,
|
||||
vision_config=None,
|
||||
vision_patch_size: int = 16,
|
||||
vision_max_num_patches: int = 256,
|
||||
vision_min_num_patches: int | None = None,
|
||||
pixel_shuffle_scale: int = 1,
|
||||
max_sequence_length: int = 16384,
|
||||
vision_token: str = "<image>",
|
||||
vision_attn_implementation: str | None = None,
|
||||
**kwargs,
|
||||
):
|
||||
if isinstance(text_config, dict):
|
||||
# from HF config
|
||||
self.text_config = self.sub_configs["text_config"](**text_config)
|
||||
elif text_config is None:
|
||||
# For BC use all kwargs to init text config.
|
||||
self.text_config = self.sub_configs["text_config"](**kwargs)
|
||||
else:
|
||||
# from Qwen3Config
|
||||
self.text_config = text_config
|
||||
|
||||
# EventStreamProcessor parameters (for backward compatibility)
|
||||
self.video_patch_size = vision_patch_size
|
||||
self.vision_max_num_patches = vision_max_num_patches
|
||||
self.vision_min_num_patches = vision_min_num_patches
|
||||
self.pixel_shuffle_scale = pixel_shuffle_scale
|
||||
|
||||
# Processing parameters
|
||||
self.max_sequence_length = max_sequence_length
|
||||
self.vision_token = vision_token
|
||||
|
||||
# Handle vision config - PixelShuffleSiglip2VisionConfig instance
|
||||
if isinstance(vision_config, dict):
|
||||
self.vision_config = PixelShuffleSiglip2VisionConfig(**vision_config)
|
||||
elif vision_config is None:
|
||||
self.vision_config = PixelShuffleSiglip2VisionConfig()
|
||||
else:
|
||||
self.vision_config = vision_config
|
||||
|
||||
# Ensure compatibility with pretrained checkpoints
|
||||
self.vision_config.pixel_shuffle_scale_factor = getattr(
|
||||
self.vision_config,
|
||||
"pixel_shuffle_scale_factor",
|
||||
pixel_shuffle_scale,
|
||||
)
|
||||
self.vision_config.num_patches = getattr(
|
||||
self.vision_config,
|
||||
"num_patches",
|
||||
vision_max_num_patches,
|
||||
)
|
||||
self.vision_attn_implementation = vision_attn_implementation
|
||||
super().__init__(**kwargs)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"IsaacConfig",
|
||||
"PixelShuffleSiglip2VisionConfig",
|
||||
]
|
||||
@@ -1,77 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from transformers import DeepseekV3Config
|
||||
|
||||
|
||||
class K3DSparkConfig(DeepseekV3Config):
|
||||
"""Configuration for a dense MLA DSpark draft model."""
|
||||
|
||||
model_type = "k3_dspark"
|
||||
has_no_defaults_at_init = True
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
mla_use_nope: bool = False,
|
||||
mla_use_output_gate: bool = False,
|
||||
mla_use_qk_norm: bool = False,
|
||||
rope_theta: float = 50000.0,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
# DeepseekV3Config defaults to a MoE topology. Zero these fields so
|
||||
# generic vLLM config logic also recognizes this draft as dense.
|
||||
kwargs.setdefault("n_routed_experts", 0)
|
||||
kwargs.setdefault("n_shared_experts", 0)
|
||||
kwargs.setdefault("num_experts_per_tok", 0)
|
||||
|
||||
rope_parameters = kwargs.get("rope_parameters")
|
||||
if rope_parameters is None:
|
||||
kwargs["rope_parameters"] = {
|
||||
"rope_type": "default",
|
||||
"rope_theta": rope_theta,
|
||||
}
|
||||
else:
|
||||
rope_parameters = dict(rope_parameters)
|
||||
rope_parameters.setdefault("rope_type", "default")
|
||||
rope_parameters.setdefault("rope_theta", rope_theta)
|
||||
kwargs["rope_parameters"] = rope_parameters
|
||||
|
||||
super().__init__(**kwargs)
|
||||
self.mla_use_nope = mla_use_nope
|
||||
self.mla_use_output_gate = mla_use_output_gate
|
||||
self.mla_use_qk_norm = mla_use_qk_norm
|
||||
|
||||
unsupported = [
|
||||
name
|
||||
for name in (
|
||||
"mla_use_nope",
|
||||
"mla_use_output_gate",
|
||||
"mla_use_qk_norm",
|
||||
"dspark_bonus_anchor",
|
||||
)
|
||||
if getattr(self, name, False)
|
||||
]
|
||||
if self.q_lora_rank is None:
|
||||
unsupported.append("q_lora_rank=None")
|
||||
if unsupported:
|
||||
raise ValueError(
|
||||
"MLA DSpark does not support " + ", ".join(unsupported) + "."
|
||||
)
|
||||
|
||||
self.draft_vocab_size = (
|
||||
getattr(self, "draft_vocab_size", None) or self.vocab_size
|
||||
)
|
||||
if self.draft_vocab_size != self.vocab_size:
|
||||
raise ValueError(
|
||||
"MLA DSpark requires draft_vocab_size to equal vocab_size when "
|
||||
"sharing the target embedding and LM head."
|
||||
)
|
||||
|
||||
target_layer_ids = getattr(self, "target_layer_ids", None)
|
||||
if not target_layer_ids or getattr(self, "num_target_layers", None) != len(
|
||||
target_layer_ids
|
||||
):
|
||||
raise ValueError(
|
||||
"MLA DSpark requires non-empty target_layer_ids and a matching "
|
||||
"num_target_layers."
|
||||
)
|
||||
@@ -1,139 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Kimi-K3 multimodal configuration."""
|
||||
|
||||
from transformers.configuration_utils import PreTrainedConfig
|
||||
|
||||
from vllm.logger import init_logger
|
||||
from vllm.transformers_utils.configs.kimi_linear import KimiLinearConfig
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class KimiK3VisionConfig(PreTrainedConfig):
|
||||
model_type = "kimi_k3_vision"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
patch_size: int = 14,
|
||||
init_pos_emb_height: int = 64,
|
||||
init_pos_emb_width: int = 64,
|
||||
init_pos_emb_time: int = 4,
|
||||
pos_emb_type: str = "divided_fixed",
|
||||
vt_num_attention_heads: int = 12,
|
||||
vt_num_hidden_layers: int = 27,
|
||||
vt_hidden_size: int = 1024,
|
||||
vt_intermediate_size: int = 4096,
|
||||
merge_kernel_size: tuple[int, int] = (2, 2),
|
||||
video_attn_type: str = "spatial_temporal",
|
||||
merge_type: str = "sd2_tpool",
|
||||
_attn_implementation: str = "flash_attention_2",
|
||||
mm_projector_type: str = "patchmergerv2",
|
||||
mm_hidden_size: int | None = None,
|
||||
projector_hidden_act: str = "gelu",
|
||||
projector_ln_eps: float = 1e-5,
|
||||
qkv_hidden_size: int = 1536,
|
||||
norm_type: str = "rmsnorm",
|
||||
attn_bias: bool = False,
|
||||
patch_embed_proj_bias: bool = False,
|
||||
mlp_type: str = "mlp2",
|
||||
linear_bias: bool = False,
|
||||
activation_func: str = "gelu_pytorch_tanh",
|
||||
pos_emb_interpolation_mode: str = "bilinear",
|
||||
text_hidden_size: int = 2304,
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__(**kwargs)
|
||||
|
||||
self.patch_size = patch_size
|
||||
self.init_pos_emb_height = init_pos_emb_height
|
||||
self.init_pos_emb_width = init_pos_emb_width
|
||||
self.init_pos_emb_time = init_pos_emb_time
|
||||
self.pos_emb_type = pos_emb_type
|
||||
self.vt_num_attention_heads = vt_num_attention_heads
|
||||
self.vt_num_hidden_layers = vt_num_hidden_layers
|
||||
self.vt_hidden_size = vt_hidden_size
|
||||
self.vt_intermediate_size = vt_intermediate_size
|
||||
self.merge_kernel_size = tuple(merge_kernel_size)
|
||||
self.video_attn_type = video_attn_type
|
||||
self.merge_type = merge_type
|
||||
self._attn_implementation = _attn_implementation
|
||||
|
||||
self.mm_projector_type = mm_projector_type
|
||||
self.mm_hidden_size = (
|
||||
mm_hidden_size if mm_hidden_size is not None else vt_hidden_size
|
||||
)
|
||||
self.projector_hidden_act = projector_hidden_act
|
||||
self.projector_ln_eps = projector_ln_eps
|
||||
self.text_hidden_size = text_hidden_size
|
||||
|
||||
self.qkv_hidden_size = qkv_hidden_size
|
||||
self.norm_type = norm_type
|
||||
self.attn_bias = attn_bias
|
||||
self.patch_embed_proj_bias = patch_embed_proj_bias
|
||||
self.mlp_type = mlp_type
|
||||
self.linear_bias = linear_bias
|
||||
self.activation_func = activation_func
|
||||
self.pos_emb_interpolation_mode = pos_emb_interpolation_mode
|
||||
|
||||
# Aliases consumed by the Kimi-K2.5 vision implementation.
|
||||
self.num_attention_heads = vt_num_attention_heads
|
||||
self.num_hidden_layers = vt_num_hidden_layers
|
||||
self.hidden_size = vt_hidden_size
|
||||
self.intermediate_size = vt_intermediate_size
|
||||
|
||||
|
||||
class KimiK3Config(PreTrainedConfig):
|
||||
model_type = "kimi_k3"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
text_config: dict | KimiLinearConfig | None = None,
|
||||
vision_config: dict | KimiK3VisionConfig | None = None,
|
||||
ignore_index: int = -100,
|
||||
media_placeholder_token_id: int = 163605,
|
||||
pad_token_id: int = 0,
|
||||
image_placeholder: str = "<|kimi_image_placeholder|>",
|
||||
**kwargs,
|
||||
):
|
||||
if text_config is None:
|
||||
self.text_config = KimiLinearConfig()
|
||||
elif isinstance(text_config, dict):
|
||||
self.text_config = KimiLinearConfig(**text_config)
|
||||
else:
|
||||
self.text_config = text_config
|
||||
|
||||
if vision_config is None:
|
||||
self.vision_config = KimiK3VisionConfig()
|
||||
elif isinstance(vision_config, dict):
|
||||
self.vision_config = KimiK3VisionConfig(**vision_config)
|
||||
else:
|
||||
self.vision_config = vision_config
|
||||
|
||||
# K3's vision projector output must match the text model's hidden size.
|
||||
# Override any value provided in vision_config for safety.
|
||||
if self.vision_config.text_hidden_size != self.text_config.hidden_size:
|
||||
logger.info(
|
||||
"Overriding vision_config.text_hidden_size from %s to %s "
|
||||
"to match text_config.hidden_size",
|
||||
self.vision_config.text_hidden_size,
|
||||
self.text_config.hidden_size,
|
||||
)
|
||||
self.vision_config.text_hidden_size = self.text_config.hidden_size
|
||||
|
||||
self.ignore_index = ignore_index
|
||||
self.media_placeholder_token_id = media_placeholder_token_id
|
||||
self.image_placeholder = image_placeholder
|
||||
|
||||
if getattr(self.text_config, "quantization_config", None) is not None:
|
||||
self.quantization_config = self.text_config.quantization_config
|
||||
|
||||
super().__init__(pad_token_id=pad_token_id, **kwargs)
|
||||
|
||||
@property
|
||||
def hidden_size(self) -> int:
|
||||
return self.text_config.hidden_size
|
||||
|
||||
@property
|
||||
def vocab_size(self) -> int:
|
||||
return self.text_config.vocab_size
|
||||
@@ -1,161 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from transformers.configuration_utils import PreTrainedConfig
|
||||
|
||||
|
||||
class KimiLinearConfig(PreTrainedConfig):
|
||||
model_type = "kimi_linear"
|
||||
keys_to_ignore_at_inference = ["past_key_values"]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
model_type="kimi_linear",
|
||||
vocab_size=163840,
|
||||
hidden_size=4096,
|
||||
head_dim=None,
|
||||
intermediate_size=11008,
|
||||
num_hidden_layers=32,
|
||||
num_attention_heads=32,
|
||||
num_key_value_heads=None,
|
||||
hidden_act="silu",
|
||||
initializer_range=0.02,
|
||||
rms_norm_eps=1e-6,
|
||||
use_cache=True,
|
||||
pad_token_id=0,
|
||||
bos_token_id=1,
|
||||
eos_token_id=2,
|
||||
rope_parameters=None,
|
||||
tie_word_embeddings=False,
|
||||
moe_intermediate_size: int | None = None,
|
||||
moe_renormalize: bool = True,
|
||||
moe_router_activation_func: str = "sigmoid",
|
||||
num_experts: int | None = None,
|
||||
num_experts_per_token: int | None = None,
|
||||
num_shared_experts: int = 0,
|
||||
routed_scaling_factor: float = 1.0,
|
||||
first_k_dense_replace: int = 0,
|
||||
moe_layer_freq: int = 1,
|
||||
use_grouped_topk: bool = True,
|
||||
num_expert_group: int = 1,
|
||||
topk_group: int = 1,
|
||||
q_lora_rank: int | None = None,
|
||||
kv_lora_rank: int | None = None,
|
||||
qk_nope_head_dim: int | None = None,
|
||||
qk_rope_head_dim: int | None = None,
|
||||
v_head_dim: int | None = None,
|
||||
mla_use_nope: bool | None = False,
|
||||
mla_use_output_gate: bool | None = False,
|
||||
num_nextn_predict_layers: int = 0,
|
||||
linear_attn_config: dict | None = None,
|
||||
attn_res_block_size: int | None = None,
|
||||
latent_moe_use_norm: bool = False,
|
||||
activation_situ_beta: float | None = None,
|
||||
activation_situ_linear_beta: float | None = None,
|
||||
max_position_embeddings: int = 4096,
|
||||
routed_expert_hidden_size: int | None = None,
|
||||
topk_method: str = "noaux_tc",
|
||||
**kwargs,
|
||||
):
|
||||
self.model_type = model_type
|
||||
self.vocab_size = vocab_size
|
||||
self.hidden_size = hidden_size
|
||||
self.head_dim = (
|
||||
head_dim if head_dim is not None else hidden_size // num_attention_heads
|
||||
)
|
||||
self.intermediate_size = intermediate_size
|
||||
self.num_hidden_layers = num_hidden_layers
|
||||
self.num_attention_heads = num_attention_heads
|
||||
|
||||
# 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
|
||||
# Try to set `rope_scaling` if available, otherwise use `rope_parameters`
|
||||
rope_scaling = kwargs.pop("rope_scaling", None)
|
||||
rope_parameters = rope_scaling or rope_parameters or {"rope_type": "default"}
|
||||
rope_theta = kwargs.pop("rope_theta", 10000.0)
|
||||
if "rope_theta" not in rope_parameters:
|
||||
rope_parameters["rope_theta"] = rope_theta
|
||||
self.rope_parameters = rope_parameters
|
||||
|
||||
self.q_lora_rank = q_lora_rank
|
||||
self.kv_lora_rank = kv_lora_rank
|
||||
self.qk_nope_head_dim = qk_nope_head_dim
|
||||
self.qk_rope_head_dim = qk_rope_head_dim
|
||||
self.v_head_dim = v_head_dim
|
||||
self.mla_use_nope = mla_use_nope
|
||||
self.mla_use_output_gate = mla_use_output_gate
|
||||
# moe config
|
||||
self.num_experts = num_experts
|
||||
self.num_experts_per_token = num_experts_per_token
|
||||
self.moe_renormalize = moe_renormalize
|
||||
self.num_shared_experts = num_shared_experts
|
||||
self.routed_scaling_factor = routed_scaling_factor
|
||||
self.moe_router_activation_func = moe_router_activation_func
|
||||
assert self.moe_router_activation_func in ("softmax", "sigmoid")
|
||||
self.moe_intermediate_size = moe_intermediate_size
|
||||
self.first_k_dense_replace = first_k_dense_replace
|
||||
self.moe_layer_freq = moe_layer_freq
|
||||
self.use_grouped_topk = use_grouped_topk
|
||||
self.num_expert_group = num_expert_group
|
||||
self.topk_group = topk_group
|
||||
self.num_nextn_predict_layers = num_nextn_predict_layers
|
||||
|
||||
self.attn_res_block_size = attn_res_block_size
|
||||
self.latent_moe_use_norm = latent_moe_use_norm
|
||||
self.activation_situ_beta = activation_situ_beta
|
||||
self.activation_situ_linear_beta = activation_situ_linear_beta
|
||||
self.max_position_embeddings = max_position_embeddings
|
||||
self.routed_expert_hidden_size = routed_expert_hidden_size
|
||||
self.topk_method = topk_method
|
||||
|
||||
if linear_attn_config is not None:
|
||||
assert linear_attn_config["kda_layers"] is not None
|
||||
assert linear_attn_config["full_attn_layers"] is not None
|
||||
self.linear_attn_config = linear_attn_config
|
||||
|
||||
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,
|
||||
)
|
||||
|
||||
@property
|
||||
def is_mla(self):
|
||||
return (
|
||||
self.q_lora_rank is not None
|
||||
or self.kv_lora_rank is not None
|
||||
or self.qk_nope_head_dim is not None
|
||||
or self.qk_rope_head_dim is not None
|
||||
or self.v_head_dim is not None
|
||||
or self.mla_use_nope is True
|
||||
)
|
||||
|
||||
@property
|
||||
def is_moe(self):
|
||||
return self.num_experts is not None
|
||||
|
||||
@property
|
||||
def is_linear_attn(self) -> bool:
|
||||
return not (
|
||||
self.linear_attn_config is None
|
||||
or (
|
||||
isinstance(self.linear_attn_config, dict)
|
||||
and self.linear_attn_config["kda_layers"] is not None
|
||||
and len(self.linear_attn_config["kda_layers"]) == 0
|
||||
)
|
||||
)
|
||||
|
||||
def is_kda_layer(self, layer_idx: int):
|
||||
return (
|
||||
self.linear_attn_config is not None
|
||||
and (layer_idx + 1) in self.linear_attn_config["kda_layers"]
|
||||
)
|
||||
@@ -1,38 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# Adapted from https://huggingface.co/moonshotai/Kimi-VL-A3B-Instruct/blob/main/configuration_kimi_vl.py
|
||||
|
||||
from transformers import DeepseekV2Config
|
||||
from transformers.configuration_utils import PreTrainedConfig
|
||||
|
||||
from vllm.transformers_utils.configs.moonvit import MoonViTConfig
|
||||
|
||||
|
||||
class KimiVLConfig(PreTrainedConfig):
|
||||
model_type = "kimi_vl"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vision_config: dict | MoonViTConfig | None = None,
|
||||
text_config: dict | DeepseekV2Config | None = None,
|
||||
ignore_index: int = -100,
|
||||
media_placeholder_token_id: int = 163605,
|
||||
pad_token_id: int = 0,
|
||||
**kwargs,
|
||||
):
|
||||
if vision_config is None:
|
||||
vision_config = MoonViTConfig()
|
||||
elif isinstance(vision_config, dict):
|
||||
vision_config = MoonViTConfig(**vision_config)
|
||||
self.vision_config = vision_config
|
||||
|
||||
if text_config is None:
|
||||
text_config = DeepseekV2Config()
|
||||
elif isinstance(text_config, dict):
|
||||
text_config = DeepseekV2Config(**text_config)
|
||||
self.text_config: DeepseekV2Config = text_config
|
||||
|
||||
self.ignore_index = ignore_index
|
||||
self.media_placeholder_token_id = media_placeholder_token_id
|
||||
|
||||
super().__init__(pad_token_id=pad_token_id, **kwargs)
|
||||
@@ -1,103 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# Copyright 2025 Horizon team, Xiaomi MiLM Plus.
|
||||
# Copyright 2024 The Qwen team.
|
||||
# Copyright 2023 The vLLM team.
|
||||
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
|
||||
#
|
||||
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
||||
# and OPT implementations in this library. It has been modified from its
|
||||
# original forms to accommodate minor architectural differences compared
|
||||
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
||||
#
|
||||
# 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.
|
||||
|
||||
from transformers import PreTrainedConfig
|
||||
from transformers.models.qwen2_5_omni.configuration_qwen2_5_omni import (
|
||||
Qwen2_5OmniTextConfig,
|
||||
)
|
||||
|
||||
|
||||
class DashengConfig(PreTrainedConfig):
|
||||
model_type = "midashenglm_dasheng_encoder"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
embed_dim: int = 768,
|
||||
outputdim: int = 527,
|
||||
patch_size: int | tuple[int, int] = 16,
|
||||
patch_stride: int | tuple[int, int] = 16,
|
||||
input_channels: int = 1,
|
||||
target_length: int = 1012,
|
||||
depth: int = 12,
|
||||
num_heads: int = 12,
|
||||
mlp_ratio: float = 4.0,
|
||||
qkv_bias: bool = True,
|
||||
init_values: float | None = None,
|
||||
drop_rate: float = 0.0,
|
||||
attn_drop_rate: float = 0.0,
|
||||
f_min: float = 0.0,
|
||||
f_max: float = 8000.0,
|
||||
center: bool = True,
|
||||
win_length: int = 512,
|
||||
hop_length: int = 160,
|
||||
sample_rate: int = 16000,
|
||||
n_fft: int = 512,
|
||||
n_mels: int = 64,
|
||||
**kwargs,
|
||||
):
|
||||
self.embed_dim = embed_dim
|
||||
self.outputdim = outputdim
|
||||
self.patch_size = patch_size
|
||||
self.patch_stride = patch_stride
|
||||
self.input_channels = input_channels
|
||||
self.target_length = target_length
|
||||
self.depth = depth
|
||||
self.num_heads = num_heads
|
||||
self.mlp_ratio = mlp_ratio
|
||||
self.qkv_bias = qkv_bias
|
||||
self.init_values = init_values
|
||||
self.drop_rate = drop_rate
|
||||
self.attn_drop_rate = attn_drop_rate
|
||||
self.f_min = f_min
|
||||
self.f_max = f_max
|
||||
self.center = center
|
||||
self.win_length = win_length
|
||||
self.hop_length = hop_length
|
||||
self.sample_rate = sample_rate
|
||||
self.n_fft = n_fft
|
||||
self.n_mels = n_mels
|
||||
super().__init__(**kwargs)
|
||||
|
||||
|
||||
class MiDashengLMConfig(PreTrainedConfig):
|
||||
model_type = "midashenglm"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
audio_encoder_config: dict | None = None,
|
||||
subsample_factor: int = 5,
|
||||
text_config: dict | None = None,
|
||||
audio_token_id: int | None = None,
|
||||
**kwargs,
|
||||
):
|
||||
self.audio_encoder_config = DashengConfig(**(audio_encoder_config or {}))
|
||||
self.subsample_factor = subsample_factor
|
||||
self.text_config = (
|
||||
Qwen2_5OmniTextConfig(**text_config)
|
||||
if text_config
|
||||
else Qwen2_5OmniTextConfig()
|
||||
)
|
||||
self.text_config.rope_parameters = None # uses_mrope is false
|
||||
self.audio_token_id = audio_token_id
|
||||
super().__init__(**kwargs)
|
||||
@@ -1,149 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from typing import Any
|
||||
|
||||
from transformers import PreTrainedConfig
|
||||
|
||||
|
||||
class MiniMaxM3TextConfig(PreTrainedConfig):
|
||||
"""Config for the MiniMax M3 text backbone (MiniMaxM3SparseForCausalLM).
|
||||
|
||||
Defaults mirror the ``text_config`` of the MiniMax-M3-preview checkpoint.
|
||||
"""
|
||||
|
||||
model_type = "minimax_m3_text"
|
||||
architectures = ["MiniMaxM3SparseForCausalLM"]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vocab_size: int = 200064,
|
||||
hidden_size: int = 6144,
|
||||
intermediate_size: int = 3072,
|
||||
dense_intermediate_size: int = 12288,
|
||||
shared_intermediate_size: int = 3072,
|
||||
num_hidden_layers: int = 60,
|
||||
num_attention_heads: int = 64,
|
||||
num_key_value_heads: int = 4,
|
||||
head_dim: int = 128,
|
||||
max_position_embeddings: int = 524288,
|
||||
rms_norm_eps: float = 1e-6,
|
||||
use_gemma_norm: bool = True,
|
||||
attention_output_gate: bool = False,
|
||||
rope_theta: float = 5000000,
|
||||
rotary_dim: int = 64,
|
||||
partial_rotary_factor: float = 0.5,
|
||||
hidden_act: str = "swigluoai",
|
||||
swiglu_alpha: float = 1.702,
|
||||
# SwiGLU-OAI uses the (up + 1) bias, i.e. beta=1.0 (matches the
|
||||
# reference: gate * sigmoid(gate * alpha) * (up + 1)). The checkpoint
|
||||
# config omits swiglu_beta, so this default must stay 1.0.
|
||||
swiglu_beta: float = 1.0,
|
||||
swiglu_limit: float = 7.0,
|
||||
use_qk_norm: bool = True,
|
||||
qk_norm_type: str = "per_head",
|
||||
num_local_experts: int = 128,
|
||||
num_experts_per_tok: int = 4,
|
||||
n_shared_experts: int = 1,
|
||||
scoring_func: str = "sigmoid",
|
||||
use_routing_bias: bool = True,
|
||||
routed_scaling_factor: float = 2.0,
|
||||
num_mtp_modules: int = 1,
|
||||
moe_layer_freq: list[int] | None = None,
|
||||
sparse_attention_config: dict[str, Any] | None = None,
|
||||
tie_word_embeddings: bool = False,
|
||||
**kwargs,
|
||||
):
|
||||
self.vocab_size = vocab_size
|
||||
self.hidden_size = hidden_size
|
||||
self.intermediate_size = intermediate_size
|
||||
self.dense_intermediate_size = dense_intermediate_size
|
||||
self.shared_intermediate_size = shared_intermediate_size
|
||||
self.num_hidden_layers = num_hidden_layers
|
||||
self.num_attention_heads = num_attention_heads
|
||||
self.num_key_value_heads = num_key_value_heads
|
||||
self.head_dim = head_dim
|
||||
self.max_position_embeddings = max_position_embeddings
|
||||
self.rms_norm_eps = rms_norm_eps
|
||||
self.use_gemma_norm = use_gemma_norm
|
||||
self.attention_output_gate = attention_output_gate
|
||||
self.rope_theta = rope_theta
|
||||
self.rotary_dim = rotary_dim
|
||||
self.partial_rotary_factor = partial_rotary_factor
|
||||
self.hidden_act = hidden_act
|
||||
self.swiglu_alpha = swiglu_alpha
|
||||
self.swiglu_beta = swiglu_beta
|
||||
self.swiglu_limit = swiglu_limit
|
||||
self.use_qk_norm = use_qk_norm
|
||||
self.qk_norm_type = qk_norm_type
|
||||
self.num_local_experts = num_local_experts
|
||||
self.num_experts_per_tok = num_experts_per_tok
|
||||
self.n_shared_experts = n_shared_experts
|
||||
self.scoring_func = scoring_func
|
||||
self.use_routing_bias = use_routing_bias
|
||||
self.routed_scaling_factor = routed_scaling_factor
|
||||
self.num_mtp_modules = num_mtp_modules
|
||||
# First 3 layers are dense; the remaining 57 are sparse MoE.
|
||||
self.moe_layer_freq = (
|
||||
moe_layer_freq if moe_layer_freq is not None else [0] * 3 + [1] * 57
|
||||
)
|
||||
self.sparse_attention_config = (
|
||||
sparse_attention_config
|
||||
if sparse_attention_config is not None
|
||||
else {
|
||||
"use_sparse_attention": True,
|
||||
"sparse_index_dim": 128,
|
||||
"sparse_num_index_heads": 4,
|
||||
"sparse_topk_blocks": 16,
|
||||
"sparse_block_size": 128,
|
||||
"sparse_disable_index_value": [0] * 3 + [1] * 57,
|
||||
"sparse_score_type": "max",
|
||||
"sparse_init_block": 0,
|
||||
"sparse_local_block": 1,
|
||||
"sparse_attention_freq": [0] * 3 + [1] * 57,
|
||||
}
|
||||
)
|
||||
super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
|
||||
|
||||
|
||||
class MiniMaxM3MTPConfig(MiniMaxM3TextConfig):
|
||||
"""Config for a standalone MiniMax M3 MTP (multi-token prediction) head.
|
||||
|
||||
The MTP transformer layer is structurally a single MiniMax M3 decoder
|
||||
layer, so this reuses the text backbone schema. Standalone MTP checkpoints
|
||||
use ``model_type='minimax_m3_mtp'`` and a single hidden layer.
|
||||
"""
|
||||
|
||||
model_type = "minimax_m3_mtp"
|
||||
architectures = ["MiniMaxM3MTP"]
|
||||
|
||||
def __init__(self, num_hidden_layers: int = 1, **kwargs):
|
||||
super().__init__(num_hidden_layers=num_hidden_layers, **kwargs)
|
||||
|
||||
|
||||
class MiniMaxM3Config(PreTrainedConfig):
|
||||
"""Top-level MiniMax M3 (VL) config.
|
||||
|
||||
Holds the text backbone as ``text_config`` so that
|
||||
``config.get_text_config()`` extracts the MiniMaxM3SparseForCausalLM
|
||||
backbone. Vision components are kept as a raw dict passthrough and are
|
||||
not modeled here.
|
||||
"""
|
||||
|
||||
model_type = "minimax_m3_vl"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
text_config: dict | MiniMaxM3TextConfig | None = None,
|
||||
vision_config: dict | None = None,
|
||||
**kwargs,
|
||||
):
|
||||
if text_config is None:
|
||||
text_config = MiniMaxM3TextConfig()
|
||||
elif isinstance(text_config, dict):
|
||||
text_config = MiniMaxM3TextConfig(**text_config)
|
||||
self.text_config = text_config
|
||||
self.vision_config = vision_config
|
||||
|
||||
self.hidden_size = text_config.hidden_size
|
||||
|
||||
super().__init__(**kwargs)
|
||||
@@ -1,153 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Configuration for Moondream3 model."""
|
||||
|
||||
from transformers import PreTrainedConfig
|
||||
|
||||
|
||||
class Moondream3VisionConfig(PreTrainedConfig):
|
||||
"""Vision encoder configuration for Moondream3."""
|
||||
|
||||
model_type = "moondream3_vision"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
enc_dim: int = 1152,
|
||||
enc_patch_size: int = 14,
|
||||
enc_n_layers: int = 27,
|
||||
enc_ff_dim: int = 4304,
|
||||
enc_n_heads: int = 16,
|
||||
proj_inner_dim: int = 8192,
|
||||
crop_size: int = 378,
|
||||
max_crops: int = 12,
|
||||
overlap_margin: int = 4,
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__(**kwargs)
|
||||
self.enc_dim = enc_dim
|
||||
self.enc_patch_size = enc_patch_size
|
||||
self.enc_n_layers = enc_n_layers
|
||||
self.enc_ff_dim = enc_ff_dim
|
||||
self.enc_n_heads = enc_n_heads
|
||||
self.proj_inner_dim = proj_inner_dim
|
||||
self.crop_size = crop_size
|
||||
self.max_crops = max_crops
|
||||
self.overlap_margin = overlap_margin
|
||||
|
||||
# Standard HuggingFace attributes for vision config
|
||||
self.hidden_size = enc_dim
|
||||
self.num_attention_heads = enc_n_heads
|
||||
self.num_hidden_layers = enc_n_layers
|
||||
self.intermediate_size = enc_ff_dim
|
||||
self.patch_size = enc_patch_size
|
||||
self.image_size = crop_size
|
||||
|
||||
|
||||
class Moondream3TextConfig(PreTrainedConfig):
|
||||
"""Text decoder configuration for Moondream3."""
|
||||
|
||||
model_type = "moondream3_text"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
dim: int = 2048,
|
||||
ff_dim: int = 8192,
|
||||
n_layers: int = 24,
|
||||
vocab_size: int = 51200,
|
||||
max_context: int = 4096,
|
||||
n_heads: int = 32,
|
||||
n_kv_heads: int = 32,
|
||||
prefix_attn: int = 730,
|
||||
rope_theta: float = 1500000.0,
|
||||
moe: dict | None = None,
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__(**kwargs)
|
||||
|
||||
# Store original moondream3 config names
|
||||
self.dim = dim
|
||||
self.ff_dim = ff_dim
|
||||
self.n_layers = n_layers
|
||||
self.n_heads = n_heads
|
||||
self.n_kv_heads = n_kv_heads
|
||||
self.prefix_attn = prefix_attn
|
||||
self.max_context = max_context
|
||||
self.rope_theta = rope_theta
|
||||
|
||||
# MoE config
|
||||
moe = moe or {}
|
||||
self.moe_start_layer = moe.get("start_layer", 4)
|
||||
self.moe_num_experts = moe.get("n_experts", 64)
|
||||
self.moe_experts_per_token = moe.get("n_experts_per_tok", 8)
|
||||
self.moe_expert_inner_dim = moe.get("expert_inner_dim", 1024)
|
||||
|
||||
# Standard HuggingFace attributes (required by vLLM)
|
||||
self.hidden_size = dim
|
||||
self.num_attention_heads = n_heads
|
||||
self.num_key_value_heads = n_kv_heads
|
||||
self.num_hidden_layers = n_layers
|
||||
self.intermediate_size = ff_dim
|
||||
self.vocab_size = vocab_size
|
||||
self.max_position_embeddings = max_context
|
||||
|
||||
# Moondream3 uses token 0 (<|endoftext|>) as both BOS and EOS.
|
||||
# Token 3 (<|md_reserved_2|>) is an answer delimiter that the model
|
||||
# implementation suppresses during generation.
|
||||
self.bos_token_id = 0
|
||||
self.eos_token_id = 0
|
||||
|
||||
# MoE standard attributes
|
||||
self.num_local_experts = self.moe_num_experts
|
||||
self.num_experts_per_tok = self.moe_experts_per_token
|
||||
|
||||
|
||||
class Moondream3Config(PreTrainedConfig):
|
||||
"""Combined configuration for Moondream3 multimodal model."""
|
||||
|
||||
model_type = "moondream3"
|
||||
is_composition = True
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: dict | None = None,
|
||||
**kwargs,
|
||||
):
|
||||
config = config or {}
|
||||
|
||||
# Parse text config
|
||||
text_config = config.get("text", {})
|
||||
self.text_config: Moondream3TextConfig = Moondream3TextConfig(**text_config)
|
||||
|
||||
# Parse vision config
|
||||
vision_config = config.get("vision", {})
|
||||
self.vision_config = Moondream3VisionConfig(**vision_config)
|
||||
|
||||
# Store the original config dict for model access
|
||||
self.config = config
|
||||
tokenizer_config = config.get("tokenizer", {})
|
||||
self.answer_token_id = tokenizer_config.get("answer_id", 3)
|
||||
|
||||
super().__init__(**kwargs)
|
||||
|
||||
# Expose key attributes at top level for vLLM compatibility
|
||||
self.hidden_size = self.text_config.hidden_size
|
||||
self.num_attention_heads = self.text_config.num_attention_heads
|
||||
self.num_key_value_heads = self.text_config.num_key_value_heads
|
||||
self.num_hidden_layers = self.text_config.num_hidden_layers
|
||||
self.vocab_size = self.text_config.vocab_size
|
||||
self.intermediate_size = self.text_config.intermediate_size
|
||||
|
||||
# Moondream3 uses token 0 (<|endoftext|>) as both BOS and EOS.
|
||||
# Token 3 (<|md_reserved_2|>) is an answer delimiter that the model
|
||||
# implementation suppresses during generation.
|
||||
self.bos_token_id = 0
|
||||
self.eos_token_id = 0
|
||||
|
||||
def get_text_config(self, decoder: bool = False) -> "Moondream3TextConfig":
|
||||
"""Return the text config for vLLM's text_config detection.
|
||||
|
||||
Args:
|
||||
decoder: Ignored. Only used for encoder-decoder models.
|
||||
|
||||
"""
|
||||
return self.text_config
|
||||
@@ -1,33 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# Adapted from https://huggingface.co/moonshotai/Kimi-VL-A3B-Instruct/blob/main/configuration_kimi_vl.py
|
||||
from transformers.configuration_utils import PreTrainedConfig
|
||||
|
||||
|
||||
class MoonViTConfig(PreTrainedConfig):
|
||||
model_type = "moonvit"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
patch_size: int = 14,
|
||||
init_pos_emb_height: int = 64,
|
||||
init_pos_emb_width: int = 64,
|
||||
num_attention_heads: int = 16,
|
||||
num_hidden_layers: int = 27,
|
||||
hidden_size: int = 1152,
|
||||
intermediate_size: int = 4304,
|
||||
merge_kernel_size: tuple[int, int] = (2, 2),
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__(**kwargs)
|
||||
self.patch_size = patch_size
|
||||
# Positional embedding config
|
||||
self.init_pos_emb_height = init_pos_emb_height
|
||||
self.init_pos_emb_width = init_pos_emb_width
|
||||
# Transformer config
|
||||
self.num_hidden_layers = num_hidden_layers
|
||||
self.num_attention_heads = num_attention_heads
|
||||
self.hidden_size = hidden_size
|
||||
self.intermediate_size = intermediate_size
|
||||
# Patch merger config
|
||||
self.merge_kernel_size = merge_kernel_size
|
||||
@@ -1,108 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from typing import Any
|
||||
|
||||
from transformers import PreTrainedConfig, Qwen3Config
|
||||
from transformers.models.whisper.configuration_whisper import WhisperConfig
|
||||
|
||||
|
||||
class MossTranscribeDiarizeConfig(PreTrainedConfig):
|
||||
"""Configuration for MOSS-Transcribe-Diarize."""
|
||||
|
||||
model_type = "moss_transcribe_diarize"
|
||||
sub_configs = {"text_config": Qwen3Config, "audio_config": WhisperConfig}
|
||||
keys_to_ignore_at_inference = ["past_key_values"]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
text_config: dict[str, Any] | Qwen3Config | None = None,
|
||||
audio_config: dict[str, Any] | WhisperConfig | None = None,
|
||||
audio_token_id: int = 151671,
|
||||
audio_merge_size: int = 4,
|
||||
adaptor_input_dim: int | None = None,
|
||||
tie_word_embeddings: bool = True,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
text_config_obj: Qwen3Config
|
||||
if text_config is None:
|
||||
text_config_obj = Qwen3Config(
|
||||
vocab_size=151936,
|
||||
hidden_size=1024,
|
||||
intermediate_size=3072,
|
||||
num_hidden_layers=28,
|
||||
num_attention_heads=16,
|
||||
num_key_value_heads=8,
|
||||
head_dim=128,
|
||||
max_position_embeddings=40960,
|
||||
tie_word_embeddings=tie_word_embeddings,
|
||||
rope_theta=1_000_000.0,
|
||||
layer_types=["full_attention"] * 28,
|
||||
)
|
||||
elif isinstance(text_config, dict):
|
||||
text_config_obj = Qwen3Config(**text_config)
|
||||
else:
|
||||
text_config_obj = text_config
|
||||
|
||||
audio_config_obj: WhisperConfig
|
||||
if audio_config is None:
|
||||
audio_config_obj = WhisperConfig(
|
||||
num_mel_bins=80,
|
||||
d_model=1024,
|
||||
encoder_layers=24,
|
||||
encoder_attention_heads=16,
|
||||
encoder_ffn_dim=4096,
|
||||
max_source_positions=1500,
|
||||
dropout=0.0,
|
||||
attention_dropout=0.0,
|
||||
activation_dropout=0.0,
|
||||
activation_function="gelu",
|
||||
encoder_layerdrop=0.0,
|
||||
scale_embedding=False,
|
||||
)
|
||||
elif isinstance(audio_config, dict):
|
||||
audio_config_obj = WhisperConfig(**audio_config)
|
||||
else:
|
||||
audio_config_obj = audio_config
|
||||
|
||||
text_config_obj.tie_word_embeddings = tie_word_embeddings
|
||||
if not getattr(text_config_obj, "layer_types", None):
|
||||
text_config_obj.layer_types = [
|
||||
"full_attention"
|
||||
] * text_config_obj.num_hidden_layers
|
||||
|
||||
super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
|
||||
|
||||
self.text_config = text_config_obj
|
||||
self.audio_config = audio_config_obj
|
||||
self.audio_token_id = int(audio_token_id)
|
||||
self.audio_merge_size = int(audio_merge_size)
|
||||
self.adaptor_input_dim = (
|
||||
int(adaptor_input_dim)
|
||||
if adaptor_input_dim is not None
|
||||
else int(audio_config_obj.d_model) * int(audio_merge_size)
|
||||
)
|
||||
|
||||
self.vocab_size = int(text_config_obj.vocab_size)
|
||||
self.hidden_size = int(text_config_obj.hidden_size)
|
||||
self.intermediate_size = int(text_config_obj.intermediate_size)
|
||||
self.num_hidden_layers = int(text_config_obj.num_hidden_layers)
|
||||
self.num_attention_heads = int(text_config_obj.num_attention_heads)
|
||||
self.num_key_value_heads = int(text_config_obj.num_key_value_heads)
|
||||
self.head_dim = int(text_config_obj.head_dim)
|
||||
self.hidden_act = text_config_obj.hidden_act
|
||||
self.max_position_embeddings = int(text_config_obj.max_position_embeddings)
|
||||
self.rms_norm_eps = float(text_config_obj.rms_norm_eps)
|
||||
rope_parameters = getattr(text_config_obj, "rope_parameters", None)
|
||||
rope_theta = float(getattr(text_config_obj, "rope_theta", 1_000_000.0))
|
||||
if rope_parameters is None:
|
||||
rope_parameters = {
|
||||
"rope_type": "default",
|
||||
"rope_theta": rope_theta,
|
||||
}
|
||||
text_config_obj.rope_parameters = rope_parameters
|
||||
self.rope_parameters = rope_parameters
|
||||
self.rope_theta = float(rope_parameters.get("rope_theta", rope_theta))
|
||||
self.attention_bias = bool(text_config_obj.attention_bias)
|
||||
self.attention_dropout = float(text_config_obj.attention_dropout)
|
||||
self.is_causal = True
|
||||
@@ -1,389 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""MuseGlimmer model configuration for vLLM.
|
||||
|
||||
Native vLLM copy of the MuseGlimmer HuggingFace configs
|
||||
(``configuration_muse_glimmer.py``). MuseGlimmer's
|
||||
``model_type`` is not yet registered in released transformers, so vLLM ships
|
||||
this config so partners can serve MuseGlimmer checkpoints *without* trust_remote_code.
|
||||
|
||||
The field set and defaults are kept byte-for-byte in sync with the HF reference
|
||||
so a checkpoint's ``config.json`` deserializes identically here. Both the text
|
||||
and vision configs are consumed by the native multimodal serving path.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from transformers import Qwen3Config
|
||||
from transformers.configuration_utils import PreTrainedConfig
|
||||
|
||||
|
||||
def _default_no_rope_layers(num_hidden_layers: int) -> list[int]:
|
||||
# iRoPE mask: NoPE every 4 layers, counted backward from the last layer.
|
||||
stride = 4
|
||||
return [
|
||||
0 if (num_hidden_layers - 1 - i) % stride == 0 else 1
|
||||
for i in range(num_hidden_layers)
|
||||
]
|
||||
|
||||
|
||||
class MuseGlimmerTextConfig(PreTrainedConfig):
|
||||
model_type = "muse_glimmer_text"
|
||||
keys_to_ignore_at_inference = ["past_key_values"]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vocab_size: int = 202_048,
|
||||
hidden_size: int = 6656,
|
||||
intermediate_size: int = 19968,
|
||||
num_hidden_layers: int = 52,
|
||||
num_attention_heads: int = 32,
|
||||
num_key_value_heads: int = 2,
|
||||
head_dim: int = 128,
|
||||
hidden_activation: str = "silu",
|
||||
max_position_embeddings: int = 16_384,
|
||||
initializer_range: float = 0.02,
|
||||
rms_norm_eps: float = 1e-5,
|
||||
use_cache: bool = True,
|
||||
pad_token_id: int | None = None,
|
||||
eos_token_id: int | list[int] | None = 200_001,
|
||||
bos_token_id: int | None = 200_000,
|
||||
tie_word_embeddings: bool = False,
|
||||
rope_parameters: dict | None = None,
|
||||
rope_theta: float | None = None,
|
||||
attention_bias: bool = False,
|
||||
attention_dropout: float = 0.0,
|
||||
query_pre_attn_scalar: int = 256,
|
||||
sliding_window: int | None = 2048,
|
||||
layer_types: list[str] | None = None,
|
||||
final_logit_softcapping: float | None = 20.0,
|
||||
attn_logit_softcapping: float | None = None,
|
||||
use_bidirectional_attention: bool | None = None,
|
||||
# MuseGlimmer-specific
|
||||
qk_scale_factor: float = 43.7840518911,
|
||||
use_qk_norm: bool = True,
|
||||
use_attn_output_gate: bool = True,
|
||||
output_multiplier: float = 0.19611613513818404,
|
||||
normalize_tok_embeddings: bool = True,
|
||||
post_norm_eps: float = 1e-8,
|
||||
no_rope_layers: list[int] | None = None,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
self.vocab_size = vocab_size
|
||||
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.num_key_value_heads = num_key_value_heads
|
||||
self.head_dim = head_dim
|
||||
self.hidden_activation = hidden_activation
|
||||
self.max_position_embeddings = max_position_embeddings
|
||||
self.initializer_range = initializer_range
|
||||
self.rms_norm_eps = rms_norm_eps
|
||||
self.use_cache = use_cache
|
||||
self.attention_bias = attention_bias
|
||||
self.attention_dropout = attention_dropout
|
||||
self.query_pre_attn_scalar = query_pre_attn_scalar
|
||||
self.sliding_window = sliding_window
|
||||
self.final_logit_softcapping = final_logit_softcapping
|
||||
self.attn_logit_softcapping = attn_logit_softcapping
|
||||
self.use_bidirectional_attention = use_bidirectional_attention
|
||||
|
||||
# RoPE: accept either an explicit rope_parameters dict (HF 5.x) or a
|
||||
# bare rope_theta; normalize to rope_parameters for vLLM's get_rope.
|
||||
if rope_parameters is None:
|
||||
theta = rope_theta if rope_theta is not None else 500_000.0
|
||||
rope_parameters = {"rope_type": "default", "rope_theta": theta}
|
||||
self.rope_parameters = rope_parameters
|
||||
# vLLM reads rope_theta off the config in some codepaths.
|
||||
self.rope_theta = rope_parameters.get("rope_theta", 500_000.0)
|
||||
|
||||
# MuseGlimmer-specific fields
|
||||
self.qk_scale_factor = qk_scale_factor
|
||||
self.use_qk_norm = use_qk_norm
|
||||
self.use_attn_output_gate = use_attn_output_gate
|
||||
self.output_multiplier = output_multiplier
|
||||
self.normalize_tok_embeddings = normalize_tok_embeddings
|
||||
self.post_norm_eps = post_norm_eps
|
||||
|
||||
self.no_rope_layers = (
|
||||
no_rope_layers
|
||||
if no_rope_layers is not None
|
||||
else _default_no_rope_layers(num_hidden_layers)
|
||||
)
|
||||
if layer_types is None:
|
||||
layer_types = [
|
||||
"full_attention" if self.no_rope_layers[i] == 0 else "sliding_attention"
|
||||
for i in range(num_hidden_layers)
|
||||
]
|
||||
self.layer_types = layer_types
|
||||
|
||||
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,
|
||||
)
|
||||
|
||||
|
||||
class MuseGlimmerVisionConfig(PreTrainedConfig):
|
||||
model_type = "muse_glimmer_vision"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
patch_size: int = 14,
|
||||
pos_emb_height: int = 32,
|
||||
pos_emb_width: int = 32,
|
||||
num_attention_heads: int = 16,
|
||||
num_hidden_layers: int = 50,
|
||||
hidden_size: int = 1536,
|
||||
intermediate_size: int = 8960,
|
||||
hidden_act: str = "gelu",
|
||||
merge_kernel_size: int = 2,
|
||||
rope_parameters: dict | None = None,
|
||||
max_position_embeddings: int = 32 * 32,
|
||||
output_dim: int = 6144,
|
||||
patch_temporal: int = 2,
|
||||
adapter_dim: int = 4096,
|
||||
layer_norm_eps: float = 1e-5,
|
||||
layer_types: list[str] | None = None,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
super().__init__(**kwargs)
|
||||
self.patch_size = patch_size
|
||||
self.pos_emb_height = pos_emb_height
|
||||
self.pos_emb_width = pos_emb_width
|
||||
self.num_attention_heads = num_attention_heads
|
||||
self.num_hidden_layers = num_hidden_layers
|
||||
self.hidden_size = hidden_size
|
||||
self.intermediate_size = intermediate_size
|
||||
self.hidden_act = hidden_act
|
||||
self.merge_kernel_size = merge_kernel_size
|
||||
self.rope_parameters = rope_parameters
|
||||
self.max_position_embeddings = max_position_embeddings
|
||||
self.output_dim = output_dim
|
||||
self.patch_temporal = patch_temporal
|
||||
self.adapter_dim = adapter_dim
|
||||
self.layer_norm_eps = layer_norm_eps
|
||||
if layer_types is None:
|
||||
stride = 4
|
||||
layer_types = [
|
||||
"full_attention"
|
||||
if (i + 1) % stride == 0 or i == num_hidden_layers - 1
|
||||
else "sliding_attention"
|
||||
for i in range(num_hidden_layers)
|
||||
]
|
||||
self.layer_types = layer_types
|
||||
|
||||
|
||||
class MuseGlimmerConfig(PreTrainedConfig):
|
||||
model_type = "muse_glimmer"
|
||||
sub_configs = {
|
||||
"text_config": MuseGlimmerTextConfig,
|
||||
"vision_config": MuseGlimmerVisionConfig,
|
||||
}
|
||||
|
||||
# --- Flat (legacy-converter) -> canonical normalization -------------------
|
||||
# MuseGlimmer checkpoints exist in two config layouts in the wild:
|
||||
#
|
||||
# * CANONICAL (current HF converter, transformers 5.15): nested
|
||||
# ``text_config`` / ``vision_config`` sub-dicts with canonical field
|
||||
# names (``hidden_activation``, ``final_logit_softcapping``,
|
||||
# ``rope_parameters``, ``vision_config.hidden_size`` ...).
|
||||
#
|
||||
# * FLAT (older converter, e.g. Ruan's ``rl_v1/hf``, transformers 5.9):
|
||||
# every field is a top-level key, with different names
|
||||
# (``hidden_act``, ``output_soft_cap_temp``, ``rope_theta``,
|
||||
# ``vision_latent_dim`` ...) and NO ``text_config`` nesting.
|
||||
#
|
||||
# Without normalization a flat config silently deserializes to an
|
||||
# ALL-DEFAULT text config (every checkpoint value ignored) — a dangerous
|
||||
# correctness bug: a checkpoint whose arch differs from the defaults would
|
||||
# load into a wrong-shaped model with no error. So when we detect a flat
|
||||
# config we hoist the flat fields into ``text_config`` / ``vision_config``
|
||||
# and rename them to canonical names.
|
||||
|
||||
# flat text field name -> canonical MuseGlimmerTextConfig field name
|
||||
_FLAT_TEXT_RENAMES = {
|
||||
"hidden_act": "hidden_activation",
|
||||
"output_soft_cap_temp": "final_logit_softcapping",
|
||||
}
|
||||
# canonical MuseGlimmerTextConfig constructor params that may appear flat
|
||||
_FLAT_TEXT_KEYS = frozenset(
|
||||
{
|
||||
"vocab_size",
|
||||
"hidden_size",
|
||||
"intermediate_size",
|
||||
"num_hidden_layers",
|
||||
"num_attention_heads",
|
||||
"num_key_value_heads",
|
||||
"head_dim",
|
||||
"hidden_activation",
|
||||
"hidden_act",
|
||||
"max_position_embeddings",
|
||||
"initializer_range",
|
||||
"rms_norm_eps",
|
||||
"use_cache",
|
||||
"tie_word_embeddings",
|
||||
"rope_parameters",
|
||||
"rope_theta",
|
||||
"attention_bias",
|
||||
"attention_dropout",
|
||||
"query_pre_attn_scalar",
|
||||
"sliding_window",
|
||||
"layer_types",
|
||||
"final_logit_softcapping",
|
||||
"output_soft_cap_temp",
|
||||
"attn_logit_softcapping",
|
||||
"use_bidirectional_attention",
|
||||
"qk_scale_factor",
|
||||
"use_qk_norm",
|
||||
"use_attn_output_gate",
|
||||
"output_multiplier",
|
||||
"normalize_tok_embeddings",
|
||||
"post_norm_eps",
|
||||
"no_rope_layers",
|
||||
}
|
||||
)
|
||||
# flat vision field name -> canonical MuseGlimmerVisionConfig field name
|
||||
_FLAT_VISION_RENAMES = {
|
||||
"vision_latent_dim": "hidden_size",
|
||||
"vision_heads": "num_attention_heads",
|
||||
"vision_layers": "num_hidden_layers",
|
||||
"vision_output_dim": "output_dim",
|
||||
"vision_patch_size": "patch_size",
|
||||
"vision_patch_temporal": "patch_temporal",
|
||||
"vision_adapter_dim": "adapter_dim",
|
||||
"vision_pos_emb_grid_h": "pos_emb_height",
|
||||
"vision_pos_emb_grid_w": "pos_emb_width",
|
||||
"vision_downsample_factor": "merge_kernel_size",
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def _looks_flat(cls, kwargs: dict) -> bool:
|
||||
# Flat if there is no explicit text_config but there ARE text-level
|
||||
# fields at the top level (e.g. hidden_size / num_hidden_layers).
|
||||
if kwargs.get("text_config") is not None:
|
||||
return False
|
||||
return any(k in kwargs for k in ("hidden_size", "num_hidden_layers"))
|
||||
|
||||
@classmethod
|
||||
def _normalize_flat(cls, kwargs: dict) -> dict:
|
||||
kwargs = dict(kwargs)
|
||||
text: dict = {}
|
||||
for key in list(kwargs.keys()):
|
||||
if key in cls._FLAT_TEXT_KEYS:
|
||||
canon = cls._FLAT_TEXT_RENAMES.get(key, key)
|
||||
text.setdefault(canon, kwargs.pop(key))
|
||||
|
||||
vision_mlp_ratio = kwargs.pop("vision_mlp_ratio", None)
|
||||
sparse_factor = kwargs.pop("vision_sparse_attention_factor", None)
|
||||
vision: dict = {}
|
||||
for key in list(kwargs.keys()):
|
||||
if key in cls._FLAT_VISION_RENAMES:
|
||||
vision.setdefault(cls._FLAT_VISION_RENAMES[key], kwargs.pop(key))
|
||||
|
||||
if vision_mlp_ratio is not None:
|
||||
hidden_size = vision.get("hidden_size", 1536)
|
||||
vision["intermediate_size"] = int(vision_mlp_ratio * hidden_size)
|
||||
if sparse_factor is not None:
|
||||
sparse_factor = int(sparse_factor)
|
||||
if sparse_factor <= 0:
|
||||
raise ValueError("vision_sparse_attention_factor must be positive")
|
||||
num_layers = vision.get("num_hidden_layers", 50)
|
||||
vision["layer_types"] = [
|
||||
"full_attention"
|
||||
if (layer_idx + 1) % sparse_factor == 0 or layer_idx == num_layers - 1
|
||||
else "sliding_attention"
|
||||
for layer_idx in range(num_layers)
|
||||
]
|
||||
|
||||
if text:
|
||||
kwargs["text_config"] = text
|
||||
if vision:
|
||||
kwargs["vision_config"] = vision
|
||||
return kwargs
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
text_config: dict | MuseGlimmerTextConfig | None = None,
|
||||
vision_config: dict | MuseGlimmerVisionConfig | None = None,
|
||||
image_token_id: int = 200092,
|
||||
video_token_id: int = 200091,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
# Detect + fold a flat config into nested text/vision before building
|
||||
# the sub-configs. (image/video token ids are handled below; a flat
|
||||
# ``patch_token_id`` alias is mapped too.)
|
||||
if text_config is None and self._looks_flat(kwargs):
|
||||
kwargs = self._normalize_flat(kwargs)
|
||||
text_config = kwargs.pop("text_config", None)
|
||||
vision_config = kwargs.pop("vision_config", vision_config)
|
||||
# flat image-token alias
|
||||
if "patch_token_id" in kwargs and "image_token_id" not in kwargs:
|
||||
image_token_id = kwargs.pop("patch_token_id")
|
||||
|
||||
if text_config is None:
|
||||
self.text_config = MuseGlimmerTextConfig()
|
||||
elif isinstance(text_config, dict):
|
||||
self.text_config = MuseGlimmerTextConfig(**text_config)
|
||||
else:
|
||||
self.text_config = text_config
|
||||
|
||||
if vision_config is None:
|
||||
self.vision_config = MuseGlimmerVisionConfig()
|
||||
elif isinstance(vision_config, dict):
|
||||
self.vision_config = MuseGlimmerVisionConfig(**vision_config)
|
||||
else:
|
||||
self.vision_config = vision_config
|
||||
|
||||
self.image_token_id = image_token_id
|
||||
self.video_token_id = video_token_id
|
||||
self.patch_token_id = image_token_id
|
||||
super().__init__(**kwargs)
|
||||
|
||||
|
||||
class MuseGlimmerAssistantConfig(Qwen3Config):
|
||||
"""Config for the Muse Glimmer DFlash draft head.
|
||||
|
||||
The head is Qwen3-shaped and runs on vLLM's generic ``qwen3_dflash``
|
||||
implementation, so this derives from ``Qwen3Config``. It cannot BE
|
||||
``Qwen3Config``, because two of the checkpoint's values do not survive that
|
||||
class:
|
||||
|
||||
* ``sliding_window`` is gated behind ``use_sliding_window``, which defaults
|
||||
to False -- ``Qwen3Config(sliding_window=2048).sliding_window`` is None.
|
||||
The checkpoint declares ``sliding_window: 2048`` and five
|
||||
``sliding_attention`` layers, so the window silently disappears and the
|
||||
DFlash path then raises "sliding attention requires a window size".
|
||||
* ``vocab_size`` is absent from the checkpoint, so Qwen3's default of
|
||||
151936 applies instead of Muse Glimmer's 202048. That one is *silent*: it
|
||||
builds an all-zero ``draft_id_to_target_id`` remap, and also puts
|
||||
pad/bos/eos/mask token ids out of range.
|
||||
|
||||
Both defaults are set here so an unmodified checkpoint loads correctly.
|
||||
"""
|
||||
|
||||
model_type = "muse_glimmer_assistant"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vocab_size: int = 202048,
|
||||
use_sliding_window: bool = True,
|
||||
dflash_config: dict | None = None,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
super().__init__(
|
||||
vocab_size=vocab_size, use_sliding_window=use_sliding_window, **kwargs
|
||||
)
|
||||
# muse_glimmer_assistant uses non-causal attention.
|
||||
self.dflash_config = {"causal": False} | (dflash_config or {})
|
||||
|
||||
|
||||
__all__ = [
|
||||
"MuseGlimmerTextConfig",
|
||||
"MuseGlimmerVisionConfig",
|
||||
"MuseGlimmerConfig",
|
||||
"MuseGlimmerAssistantConfig",
|
||||
]
|
||||
@@ -1,50 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""OpenVLA configuration support.
|
||||
|
||||
OpenVLA checkpoints use a custom ``model_type`` and nest the language model
|
||||
configuration under ``text_config``. This shim lets vLLM load the checkpoint
|
||||
configuration without executing Hugging Face remote code.
|
||||
"""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from transformers import LlamaConfig, PreTrainedConfig
|
||||
|
||||
|
||||
class OpenVLAConfig(PreTrainedConfig):
|
||||
"""Configuration class for OpenVLA models."""
|
||||
|
||||
model_type = "openvla"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
timm_model_ids: list[str] | None = None,
|
||||
timm_override_act_layers: list[str | None] | None = None,
|
||||
image_sizes: list[int] | None = None,
|
||||
use_fused_vision_backbone: bool = True,
|
||||
image_token_index: int = 32000,
|
||||
n_action_bins: int = 256,
|
||||
text_config: dict[str, Any] | LlamaConfig | None = None,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
kwargs.setdefault("architectures", ["OpenVLAForActionPrediction"])
|
||||
super().__init__(**kwargs)
|
||||
|
||||
self.timm_model_ids = timm_model_ids or [
|
||||
"vit_large_patch14_reg4_dinov2.lvd142m",
|
||||
"vit_so400m_patch14_siglip_224",
|
||||
]
|
||||
self.timm_override_act_layers = timm_override_act_layers or [None, None]
|
||||
self.image_sizes = image_sizes or [224, 224]
|
||||
self.use_fused_vision_backbone = use_fused_vision_backbone
|
||||
self.image_token_index = image_token_index
|
||||
self.n_action_bins = n_action_bins
|
||||
|
||||
if text_config is None:
|
||||
text_config = LlamaConfig(architectures=["LlamaForCausalLM"])
|
||||
elif isinstance(text_config, dict):
|
||||
text_config = text_config.copy()
|
||||
text_config.setdefault("architectures", ["LlamaForCausalLM"])
|
||||
text_config = LlamaConfig(**text_config)
|
||||
self.text_config = text_config
|
||||
@@ -1,124 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
# ruff: noqa: E501
|
||||
# adapted from https://huggingface.co/AIDC-AI/Ovis2-1B/blob/main/configuration_ovis.py
|
||||
from typing import Any
|
||||
|
||||
from transformers import Aimv2VisionConfig, AutoConfig, PreTrainedConfig
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# Visual Tokenizer Configuration
|
||||
# ----------------------------------------------------------------------
|
||||
class BaseVisualTokenizerConfig(PreTrainedConfig):
|
||||
def __init__(
|
||||
self,
|
||||
vocab_size=16384,
|
||||
tokenize_function="softmax",
|
||||
tau=1.0,
|
||||
depths=None,
|
||||
drop_cls_token=False,
|
||||
backbone_config: PreTrainedConfig | dict | None = None,
|
||||
hidden_stride: int = 1,
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__(**kwargs)
|
||||
self.vocab_size = vocab_size
|
||||
self.tokenize_function = tokenize_function
|
||||
self.tau = tau
|
||||
if isinstance(depths, str):
|
||||
depths = [int(x) for x in depths.split("|")]
|
||||
self.depths = depths
|
||||
self.backbone_kwargs = dict[str, Any]()
|
||||
self.drop_cls_token = drop_cls_token
|
||||
if backbone_config is not None:
|
||||
assert isinstance(backbone_config, (PreTrainedConfig, dict)), (
|
||||
f"expect `backbone_config` to be instance of PreTrainedConfig or dict, but got {type(backbone_config)} type"
|
||||
)
|
||||
if not isinstance(backbone_config, PreTrainedConfig):
|
||||
model_type = backbone_config.pop("model_type")
|
||||
if model_type == "aimv2":
|
||||
backbone_config = Aimv2VisionConfig(**backbone_config)
|
||||
else:
|
||||
backbone_config = AutoConfig.for_model(
|
||||
model_type, **backbone_config
|
||||
)
|
||||
self.backbone_config = backbone_config
|
||||
self.hidden_stride = hidden_stride
|
||||
|
||||
|
||||
class Aimv2VisualTokenizerConfig(BaseVisualTokenizerConfig):
|
||||
model_type = "aimv2_visual_tokenizer"
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
if self.drop_cls_token:
|
||||
self.drop_cls_token = False
|
||||
if self.depths:
|
||||
assert len(self.depths) == 1
|
||||
self.backbone_kwargs["num_hidden_layers"] = self.depths[0]
|
||||
|
||||
|
||||
class SiglipVisualTokenizerConfig(BaseVisualTokenizerConfig):
|
||||
model_type = "siglip_visual_tokenizer"
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
if self.drop_cls_token:
|
||||
self.drop_cls_token = False
|
||||
if self.depths:
|
||||
assert len(self.depths) == 1
|
||||
self.backbone_kwargs["num_hidden_layers"] = self.depths[0]
|
||||
|
||||
|
||||
AutoConfig.register("siglip_visual_tokenizer", SiglipVisualTokenizerConfig)
|
||||
AutoConfig.register("aimv2_visual_tokenizer", Aimv2VisualTokenizerConfig)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# Ovis Configuration
|
||||
# ----------------------------------------------------------------------
|
||||
class OvisConfig(PreTrainedConfig):
|
||||
model_type = "ovis"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
llm_config: PreTrainedConfig | dict | None = None,
|
||||
visual_tokenizer_config: PreTrainedConfig | dict | None = None,
|
||||
multimodal_max_length=8192,
|
||||
hidden_size=None,
|
||||
conversation_formatter_class=None,
|
||||
llm_attn_implementation=None,
|
||||
disable_tie_weight=False,
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__(**kwargs)
|
||||
if llm_config is not None:
|
||||
assert isinstance(llm_config, (PreTrainedConfig, dict)), (
|
||||
f"expect `llm_config` to be instance of PreTrainedConfig or dict, but got {type(llm_config)} type"
|
||||
)
|
||||
if not isinstance(llm_config, PreTrainedConfig):
|
||||
model_type = llm_config["model_type"]
|
||||
llm_config.pop("model_type")
|
||||
llm_config = AutoConfig.for_model(model_type, **llm_config)
|
||||
|
||||
# map llm_config to text_config
|
||||
self.text_config = llm_config
|
||||
if visual_tokenizer_config is not None:
|
||||
assert isinstance(visual_tokenizer_config, (PreTrainedConfig, dict)), (
|
||||
f"expect `visual_tokenizer_config` to be instance of PreTrainedConfig or dict, but got {type(visual_tokenizer_config)} type"
|
||||
)
|
||||
if not isinstance(visual_tokenizer_config, PreTrainedConfig):
|
||||
model_type = visual_tokenizer_config["model_type"]
|
||||
visual_tokenizer_config.pop("model_type")
|
||||
visual_tokenizer_config = AutoConfig.for_model(
|
||||
model_type, **visual_tokenizer_config
|
||||
)
|
||||
|
||||
self.visual_tokenizer_config = visual_tokenizer_config
|
||||
self.multimodal_max_length = multimodal_max_length
|
||||
self.hidden_size = hidden_size
|
||||
self.conversation_formatter_class = conversation_formatter_class
|
||||
self.llm_attn_implementation = llm_attn_implementation
|
||||
self.disable_tie_weight = disable_tie_weight
|
||||
@@ -1,105 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from typing import Any
|
||||
|
||||
from transformers import PreTrainedConfig
|
||||
from transformers.models.auto import CONFIG_MAPPING
|
||||
|
||||
|
||||
class QianfanOCRVisionConfig(PreTrainedConfig):
|
||||
model_type = "qianfan_ocr_vision"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
hidden_size: int = 1024,
|
||||
intermediate_size: int = 4096,
|
||||
num_hidden_layers: int = 24,
|
||||
num_attention_heads: int = 16,
|
||||
num_channels: int = 3,
|
||||
image_size: int = 448,
|
||||
patch_size: int = 14,
|
||||
hidden_act: str = "gelu",
|
||||
layer_norm_eps: float = 1e-6,
|
||||
attention_dropout: float = 0.0,
|
||||
drop_path_rate: float = 0.1,
|
||||
qkv_bias: bool = True,
|
||||
qk_normalization: bool = False,
|
||||
norm_type: str = "layer_norm",
|
||||
initializer_range: float = 0.02,
|
||||
initializer_factor: float = 0.1,
|
||||
use_mask_token: bool = False,
|
||||
use_mean_pooling: bool = True,
|
||||
**kwargs: Any,
|
||||
):
|
||||
super().__init__(**kwargs)
|
||||
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.num_channels = num_channels
|
||||
self.image_size = image_size
|
||||
self.patch_size = patch_size
|
||||
self.hidden_act = hidden_act
|
||||
self.layer_norm_eps = layer_norm_eps
|
||||
self.attention_dropout = attention_dropout
|
||||
self.drop_path_rate = drop_path_rate
|
||||
self.qkv_bias = qkv_bias
|
||||
self.qk_normalization = qk_normalization
|
||||
self.norm_type = norm_type
|
||||
self.initializer_range = initializer_range
|
||||
self.initializer_factor = initializer_factor
|
||||
self.use_mask_token = use_mask_token
|
||||
self.use_mean_pooling = use_mean_pooling
|
||||
|
||||
|
||||
class QianfanOCRConfig(PreTrainedConfig):
|
||||
model_type = "qianfan_ocr"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vision_config: dict | None = None,
|
||||
text_config: dict | None = None,
|
||||
downsample_ratio: float = 0.5,
|
||||
dynamic_image_size: bool = True,
|
||||
force_image_size: int = 448,
|
||||
image_token_id: int = 151671,
|
||||
max_dynamic_patch: int = 12,
|
||||
min_dynamic_patch: int = 1,
|
||||
pad2square: bool = False,
|
||||
ps_version: str = "v2",
|
||||
select_layer: int = -1,
|
||||
template: str = "internvl2_5",
|
||||
use_thumbnail: bool = True,
|
||||
tie_word_embeddings: bool = False,
|
||||
**kwargs: Any,
|
||||
):
|
||||
super().__init__(**kwargs)
|
||||
|
||||
if isinstance(vision_config, dict):
|
||||
self.vision_config = QianfanOCRVisionConfig(**vision_config)
|
||||
elif vision_config is None:
|
||||
self.vision_config = QianfanOCRVisionConfig()
|
||||
else:
|
||||
self.vision_config = vision_config
|
||||
|
||||
if isinstance(text_config, dict):
|
||||
model_type = text_config.get("model_type", "qwen3")
|
||||
self.text_config = CONFIG_MAPPING[model_type](**text_config)
|
||||
elif text_config is None:
|
||||
self.text_config = CONFIG_MAPPING["qwen3"]()
|
||||
else:
|
||||
self.text_config = text_config
|
||||
|
||||
self.downsample_ratio = downsample_ratio
|
||||
self.dynamic_image_size = dynamic_image_size
|
||||
self.force_image_size = force_image_size
|
||||
self.image_token_id = image_token_id
|
||||
self.max_dynamic_patch = max_dynamic_patch
|
||||
self.min_dynamic_patch = min_dynamic_patch
|
||||
self.pad2square = pad2square
|
||||
self.ps_version = ps_version
|
||||
self.select_layer = select_layer
|
||||
self.template = template
|
||||
self.use_thumbnail = use_thumbnail
|
||||
self.tie_word_embeddings = tie_word_embeddings
|
||||
@@ -1,455 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
# ruff: noqa
|
||||
# mypy: ignore-errors
|
||||
# coding=utf-8
|
||||
# Copyright 2026 The Qwen team, Alibaba Group and the HuggingFace Inc. 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.
|
||||
from transformers.configuration_utils import PreTrainedConfig
|
||||
from transformers.modeling_rope_utils import rope_config_validation
|
||||
from transformers.utils import logging
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
|
||||
|
||||
class Qwen3ASRAudioEncoderConfig(PreTrainedConfig):
|
||||
r"""
|
||||
This is the configuration class to store the configuration of a [`Qwen3ASRAudioEncoder`]. It is used to instantiate a
|
||||
Qwen3-ASR audio encoder according to the specified arguments, defining the model architecture. Instantiating a
|
||||
configuration with the defaults will yield a similar configuration to that of the audio encoder of the Qwen2-Audio
|
||||
architecture.
|
||||
|
||||
e.g. [Qwen/Qwen3-ASR-1.7B](https://huggingface.co/Qwen/Qwen3-ASR-1.7B)
|
||||
|
||||
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
|
||||
documentation from [`PreTrainedConfig`] for more information.
|
||||
|
||||
Args:
|
||||
num_mel_bins (`int`, *optional*, defaults to 128):
|
||||
Number of mel features used per input features. Should correspond to the value used in the
|
||||
`Qwen3ASRProcessor` class.
|
||||
encoder_layers (`int`, *optional*, defaults to 32):
|
||||
Number of encoder layers.
|
||||
encoder_attention_heads (`int`, *optional*, defaults to 20):
|
||||
Number of attention heads for each attention layer in the Transformer encoder.
|
||||
encoder_ffn_dim (`int`, *optional*, defaults to 5120):
|
||||
Dimensionality of the "intermediate" (often named feed-forward) layer in encoder.
|
||||
d_model (`int`, *optional*, defaults to 1280):
|
||||
Dimensionality of the layers.
|
||||
dropout (`float`, *optional*, defaults to 0.0):
|
||||
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
||||
attention_dropout (`float`, *optional*, defaults to 0.0):
|
||||
The dropout ratio for the attention probabilities.
|
||||
activation_function (`str`, *optional*, defaults to `"gelu"`):
|
||||
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
||||
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
||||
activation_dropout (`float`, *optional*, defaults to 0.0):
|
||||
The dropout ratio for activations inside the fully connected layer.
|
||||
scale_embedding (`bool`, *optional*, defaults to `False`):
|
||||
Scale embeddings by diving by sqrt(d_model).
|
||||
initializer_range (`float`, *optional*, defaults to 0.02):
|
||||
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
||||
max_source_positions (`int`, *optional*, defaults to 1500):
|
||||
The maximum sequence length of log-mel filter-bank features that this model might ever be used with.
|
||||
n_window (`int`, *optional*, defaults to 100):
|
||||
The chunk for conv and flash attn in AudioEncoder.
|
||||
output_dim (`int`, *optional*, defaults to 3584):
|
||||
The output dimension of AudioEncoder.
|
||||
|
||||
Example:
|
||||
|
||||
```python
|
||||
>>> from transformers import Qwen3ASRAudioEncoderConfig, Qwen3ASRAudioEncoder
|
||||
|
||||
>>> # Initializing a Qwen3ASRAudioEncoderConfig
|
||||
>>> configuration = Qwen3ASRAudioEncoderConfig()
|
||||
|
||||
>>> # Initializing a Qwen3ASRAudioEncoder (with random weights)
|
||||
>>> model = Qwen3ASRAudioEncoder(configuration)
|
||||
|
||||
>>> # Accessing the model configuration
|
||||
>>> configuration = model.config
|
||||
```"""
|
||||
|
||||
model_type = "qwen3_asr_audio_encoder"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
num_mel_bins=128,
|
||||
encoder_layers=32,
|
||||
encoder_attention_heads=20,
|
||||
encoder_ffn_dim=5120,
|
||||
d_model=1280,
|
||||
dropout=0,
|
||||
attention_dropout=0,
|
||||
activation_function="gelu",
|
||||
activation_dropout=0,
|
||||
scale_embedding=False,
|
||||
initializer_range=0.02,
|
||||
max_source_positions=1500,
|
||||
n_window=100,
|
||||
output_dim=3584,
|
||||
n_window_infer=400,
|
||||
conv_chunksize=500,
|
||||
downsample_hidden_size=480,
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__(**kwargs)
|
||||
|
||||
self.num_mel_bins = num_mel_bins
|
||||
self.d_model = d_model
|
||||
self.encoder_layers = encoder_layers
|
||||
self.encoder_attention_heads = encoder_attention_heads
|
||||
self.encoder_ffn_dim = encoder_ffn_dim
|
||||
self.dropout = dropout
|
||||
self.attention_dropout = attention_dropout
|
||||
self.activation_function = activation_function
|
||||
self.activation_dropout = activation_dropout
|
||||
self.num_hidden_layers = encoder_layers
|
||||
self.initializer_range = initializer_range
|
||||
self.scale_embedding = (
|
||||
scale_embedding # scale factor will be sqrt(d_model) if True
|
||||
)
|
||||
self.max_source_positions = max_source_positions
|
||||
self.n_window = n_window
|
||||
self.output_dim = output_dim
|
||||
self.n_window_infer = n_window_infer
|
||||
self.conv_chunksize = conv_chunksize
|
||||
self.downsample_hidden_size = downsample_hidden_size
|
||||
|
||||
|
||||
class Qwen3ASRTextConfig(PreTrainedConfig):
|
||||
r"""
|
||||
This is the configuration class to store the configuration of a [`Qwen3ASRTextModel`]. It is used to instantiate a
|
||||
Qwen3-ASR model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
||||
with the defaults will yield a similar configuration to that of
|
||||
Qwen3-ASR-1.7B [Qwen/Qwen3-ASR-1.7B](https://huggingface.co/Qwen/Qwen3-ASR-1.7B)
|
||||
|
||||
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 151936):
|
||||
Vocabulary size of the Qwen3ASR model. Defines the number of different tokens that can be represented by the
|
||||
`inputs_ids` passed when calling [`Qwen3ASRModel`]
|
||||
hidden_size (`int`, *optional*, defaults to 4096):
|
||||
Dimension of the hidden representations.
|
||||
intermediate_size (`int`, *optional*, defaults to 22016):
|
||||
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 32):
|
||||
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, check out [this
|
||||
paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `32`.
|
||||
head_dim (`int`, *optional*, defaults to 128):
|
||||
The dimension of the head. If not specified, will default to `hidden_size // num_attention_heads`.
|
||||
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 128000):
|
||||
The maximum sequence length that this model might ever be used with.
|
||||
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-06):
|
||||
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`.
|
||||
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
||||
Whether the model's input and output word embeddings should be tied.
|
||||
rope_theta (`float`, *optional*, defaults to 5000000.0):
|
||||
The base period of the RoPE embeddings.
|
||||
rope_scaling (`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_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.
|
||||
`factor` (`float`, *optional*):
|
||||
Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
|
||||
most scaling types, a `factor` of x will enable the model to handle sequences of length x *
|
||||
original maximum pre-trained length.
|
||||
`original_max_position_embeddings` (`int`, *optional*):
|
||||
Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
|
||||
pretraining.
|
||||
`attention_factor` (`float`, *optional*):
|
||||
Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
|
||||
computation. If unspecified, it defaults to value recommended by the implementation, using the
|
||||
`factor` field to infer the suggested value.
|
||||
`beta_fast` (`float`, *optional*):
|
||||
Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
|
||||
ramp function. If unspecified, it defaults to 32.
|
||||
`beta_slow` (`float`, *optional*):
|
||||
Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
|
||||
ramp function. If unspecified, it defaults to 1.
|
||||
`short_factor` (`list[float]`, *optional*):
|
||||
Only used with 'longrope'. The scaling factor to be applied to short contexts (<
|
||||
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
||||
size divided by the number of attention heads divided by 2
|
||||
`long_factor` (`list[float]`, *optional*):
|
||||
Only used with 'longrope'. The scaling factor to be applied to long contexts (<
|
||||
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
||||
size divided by the number of attention heads divided by 2
|
||||
`low_freq_factor` (`float`, *optional*):
|
||||
Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
|
||||
`high_freq_factor` (`float`, *optional*):
|
||||
Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
|
||||
attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
|
||||
Whether to use a bias in the query, key, value and output projection layers during self-attention.
|
||||
attention_dropout (`float`, *optional*, defaults to 0.0):
|
||||
The dropout ratio for the attention probabilities.
|
||||
|
||||
```python
|
||||
>>> from transformers import Qwen3ASRTextModel, Qwen3ASRTextConfig
|
||||
|
||||
>>> # Initializing a Qwen3ASR style configuration
|
||||
>>> configuration = Qwen3ASRTextConfig()
|
||||
|
||||
>>> # Initializing a model from the Qwen3-VL-7B style configuration
|
||||
>>> model = Qwen3ASRTextModel(configuration)
|
||||
|
||||
>>> # Accessing the model configuration
|
||||
>>> configuration = model.config
|
||||
```"""
|
||||
|
||||
model_type = "qwen3_asr_text"
|
||||
base_config_key = "text_config"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vocab_size=151936,
|
||||
hidden_size=4096,
|
||||
intermediate_size=22016,
|
||||
num_hidden_layers=32,
|
||||
num_attention_heads=32,
|
||||
num_key_value_heads=32,
|
||||
head_dim=128,
|
||||
hidden_act="silu",
|
||||
max_position_embeddings=128000,
|
||||
initializer_range=0.02,
|
||||
rms_norm_eps=1e-6,
|
||||
use_cache=True,
|
||||
tie_word_embeddings=False,
|
||||
rope_theta=5000000.0,
|
||||
rope_scaling=None,
|
||||
attention_bias=False,
|
||||
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
|
||||
|
||||
# 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.head_dim = head_dim
|
||||
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_bias = attention_bias
|
||||
self.attention_dropout = attention_dropout
|
||||
# Validate the correctness of rotary position embeddings parameters
|
||||
# BC: if there is a 'type' field, move it to 'rope_type'.
|
||||
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)
|
||||
|
||||
super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
|
||||
|
||||
|
||||
class Qwen3ASRThinkerConfig(PreTrainedConfig):
|
||||
r"""
|
||||
This is the configuration class to store the configuration of a [`Qwen3ASRThinker`]. It is used to instantiate a
|
||||
Qwen3-ASR-Thinker 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 thinker component of the Qwen3-Omni
|
||||
architecture.
|
||||
|
||||
e.g. [Qwen/Qwen3-ASR-1.7B](https://huggingface.co/Qwen/Qwen3-ASR-1.7B)
|
||||
|
||||
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
|
||||
documentation from [`PreTrainedConfig`] for more information.
|
||||
|
||||
Args:
|
||||
audio_config (`dict`, *optional*):
|
||||
The config dictionary of the audio backbone.
|
||||
text_config (`dict`, *optional*):
|
||||
The config dictionary of the text backbone.
|
||||
audio_token_id (`int`, *optional*, defaults to 151646):
|
||||
The audio token id to encode the audio prompt.
|
||||
audio_start_token_id (`int`, *optional*, defaults to 151647):
|
||||
The audio start token id to encode the audio prompt.
|
||||
user_token_id (`int`, *optional*, defaults to 872):
|
||||
The user token id to encode the user token.
|
||||
initializer_range (`float`, *optional*, defaults to 0.02):
|
||||
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
||||
|
||||
Example:
|
||||
|
||||
```python
|
||||
>>> from transformers import Qwen3ASRThinkerModel, Qwen3ASRThinkerConfig
|
||||
|
||||
>>> # Initializing a default Qwen3ASRThinkerConfig
|
||||
>>> configuration = Qwen3ASRThinkerConfig()
|
||||
|
||||
>>> # Initializing a model (with random weights) from the default configuration
|
||||
>>> model = Qwen3ASRThinkerModel(configuration)
|
||||
|
||||
>>> # Accessing the model configuration
|
||||
>>> configuration = model.config
|
||||
```"""
|
||||
|
||||
model_type = "qwen3_asr_thinker"
|
||||
|
||||
attribute_map = {}
|
||||
sub_configs = {
|
||||
"audio_config": Qwen3ASRAudioEncoderConfig,
|
||||
"text_config": Qwen3ASRTextConfig,
|
||||
}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
audio_config=None,
|
||||
text_config=None,
|
||||
audio_token_id=151646,
|
||||
audio_start_token_id=151647,
|
||||
user_token_id=872,
|
||||
initializer_range=0.02,
|
||||
classify_num=None,
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__(**kwargs)
|
||||
self.user_token_id = user_token_id
|
||||
self.audio_start_token_id = audio_start_token_id
|
||||
self.initializer_range = initializer_range
|
||||
self.classify_num = classify_num
|
||||
|
||||
if isinstance(audio_config, dict):
|
||||
audio_config = Qwen3ASRAudioEncoderConfig(**audio_config)
|
||||
elif audio_config is None:
|
||||
audio_config = Qwen3ASRAudioEncoderConfig()
|
||||
self.audio_config = audio_config
|
||||
|
||||
if isinstance(text_config, dict):
|
||||
text_config = Qwen3ASRTextConfig(**text_config)
|
||||
elif text_config is None:
|
||||
text_config = Qwen3ASRTextConfig()
|
||||
self.text_config = text_config
|
||||
self.audio_token_id = audio_token_id
|
||||
|
||||
|
||||
class Qwen3ASRConfig(PreTrainedConfig):
|
||||
"""
|
||||
This is the configuration class to store the configuration of a [`Qwen3ASRForConditionalGeneration`]. It is used to instantiate a Qwen3ASR
|
||||
model according to the specified sub-models configurations, defining the model architecture.
|
||||
|
||||
Instantiating a configuration with the defaults will yield a similar configuration to that of the
|
||||
[Qwen/Qwen3-ASR-1.7B](https://huggingface.co/Qwen/Qwen3-ASR-1.7B) architecture.
|
||||
|
||||
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
|
||||
documentation from [`PreTrainedConfig`] for more information.
|
||||
|
||||
Args:
|
||||
thinker_config (`dict`, *optional*): Configuration of the underlying thinker sub-model.
|
||||
support_languages (`List[str]`, *optional*): The languages supported by the model.
|
||||
|
||||
Example:
|
||||
|
||||
```python
|
||||
>>> from transformers import (
|
||||
... Qwen3ASRThinkerConfig,
|
||||
... Qwen3ASRForConditionalGeneration,
|
||||
... Qwen3ASRConfig,
|
||||
... )
|
||||
|
||||
>>> # Initializing a Qwen3ASR style configuration
|
||||
>>> configuration = Qwen3ASRConfig()
|
||||
|
||||
>>> # Initializing a model from the configuration
|
||||
>>> model = Qwen3ASRForConditionalGeneration(configuration)
|
||||
|
||||
>>> # Accessing the model configuration
|
||||
>>> configuration = model.config
|
||||
```"""
|
||||
|
||||
model_type = "qwen3_asr"
|
||||
sub_configs = {
|
||||
"thinker_config": Qwen3ASRThinkerConfig,
|
||||
}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
thinker_config=None,
|
||||
audio_config=None,
|
||||
text_config=None,
|
||||
audio_token_id=None,
|
||||
support_languages=None,
|
||||
timestamp_token_id=None,
|
||||
timestamp_segment_time=None,
|
||||
**kwargs,
|
||||
):
|
||||
if thinker_config is None:
|
||||
thinker_config = {
|
||||
key: value
|
||||
for key, value in (
|
||||
("audio_config", audio_config),
|
||||
("text_config", text_config),
|
||||
("audio_token_id", audio_token_id),
|
||||
)
|
||||
if value is not None
|
||||
}
|
||||
if not thinker_config:
|
||||
logger.info(
|
||||
"thinker_config is None. Initializing thinker model with "
|
||||
"default values"
|
||||
)
|
||||
|
||||
self.thinker_config = Qwen3ASRThinkerConfig(**thinker_config)
|
||||
self.support_languages = support_languages
|
||||
self.timestamp_token_id = timestamp_token_id
|
||||
self.timestamp_segment_time = timestamp_segment_time
|
||||
super().__init__(**kwargs)
|
||||
|
||||
def get_text_config(self, decoder=False) -> "PreTrainedConfig":
|
||||
"""
|
||||
Returns the config that is meant to be used with text IO. On most models, it is the original config instance
|
||||
itself. On specific composite models, it is under a set of valid names.
|
||||
|
||||
Args:
|
||||
decoder (`Optional[bool]`, *optional*, defaults to `False`):
|
||||
If set to `True`, then only search for decoder config names.
|
||||
"""
|
||||
# Overridden for deeply nested config like Qwen2.5-Omni. We don't have any omni model
|
||||
# except for Qwen yet. This has to be generalized if more deeply nested configs are
|
||||
# added. NOTE: currently method used only by vLLM
|
||||
return self.thinker_config.get_text_config()
|
||||
|
||||
|
||||
__all__ = ["Qwen3ASRConfig", "Qwen3ASRThinkerConfig", "Qwen3ASRAudioEncoderConfig"]
|
||||
@@ -1,110 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Radio vision model configuration."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from transformers.configuration_utils import PreTrainedConfig
|
||||
from transformers.utils import logging
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
|
||||
VIT_TIMM_DIM_BY_NAME: dict[str, tuple[int, int, int, int]] = {
|
||||
"vit_small_patch16_224": (384, 12, 6, 1536),
|
||||
"vit_base_patch16_224": (768, 12, 12, 3072),
|
||||
"vit_large_patch16_224": (1024, 24, 16, 4096),
|
||||
"vit_huge_patch16_224": (1280, 32, 16, 5120),
|
||||
}
|
||||
|
||||
OPENAI_CLIP_MEAN = (0.48145466, 0.4578275, 0.40821073)
|
||||
OPENAI_CLIP_STD = (0.26862954, 0.26130258, 0.27577711)
|
||||
|
||||
|
||||
class RadioConfig(PreTrainedConfig):
|
||||
r"""This is the configuration class to store the configuration of a Radio
|
||||
vision model. It is used to instantiate a Radio model according to the
|
||||
specified arguments, defining the model architecture.
|
||||
|
||||
Args:
|
||||
model_name: Name of the vision transformer model
|
||||
(e.g., "vit_base_patch16_224"). Used to determine architecture
|
||||
dimensions from `VIT_TIMM_DIM_BY_NAME`.
|
||||
image_size: The size (resolution) of each image.
|
||||
patch_size: The size (resolution) of each patch.
|
||||
qkv_bias: Whether to add a bias to the queries, keys and values.
|
||||
qk_normalization: Whether to apply normalization to queries and keys.
|
||||
norm_type: The normalization type to use.
|
||||
layer_norm_eps: The epsilon used by the layer normalization layers.
|
||||
initializer_factor: A factor for initializing all weight matrices.
|
||||
hidden_act: The non-linear activation function in the encoder.
|
||||
cpe_max_size: Maximum image size for position embeddings.
|
||||
norm_mean: Mean values for image normalization (RGB channels).
|
||||
Defaults to (0.48145466, 0.4578275, 0.40821073)).
|
||||
norm_std: Standard deviation values for image normalization
|
||||
(RGB channels). Defaults to (0.26862954, 0.26130258, 0.27577711)).
|
||||
register_multiple: Number of register tokens to use.
|
||||
teachers: A list of teacher model configurations. Each teacher configuration is
|
||||
a dict with keys like "name" and some may have "use_summary".
|
||||
cls_token_per_teacher: Whether to use a separate CLS token for each teacher.
|
||||
video_temporal_patch_size: Number of consecutive video frames grouped into
|
||||
a single tubelet for temporal compression. Default 1 (no compression).
|
||||
When > 1, a dedicated video_embedder (3*T*P*P -> hidden) is created
|
||||
alongside the image embedder (3*P*P -> hidden).
|
||||
separate_video_embedder: When True and video_temporal_patch_size > 1, use a
|
||||
dedicated video patch embedder (3*T*P*P -> hidden) separate from the
|
||||
image embedder (3*P*P -> hidden). When False, a single embedder with
|
||||
input size 3*T*P*P is used for both (images are duplicated T times).
|
||||
|
||||
"""
|
||||
|
||||
model_type = "radio"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
model_name: str,
|
||||
image_size: int = 224,
|
||||
patch_size: int = 16,
|
||||
qkv_bias: bool = True,
|
||||
qk_normalization: bool = False,
|
||||
norm_type: str = "layer_norm",
|
||||
layer_norm_eps: float = 1e-6,
|
||||
initializer_factor: float = 1.0,
|
||||
hidden_act: str = "gelu",
|
||||
cpe_max_size: int = 2048,
|
||||
norm_mean: tuple[float, float, float] | list = OPENAI_CLIP_MEAN,
|
||||
norm_std: tuple[float, float, float] | list = OPENAI_CLIP_STD,
|
||||
register_multiple: int | None = None,
|
||||
teachers: list[dict[str, Any]] | None = None,
|
||||
cls_token_per_teacher: bool = False,
|
||||
video_temporal_patch_size: int = 1,
|
||||
separate_video_embedder: bool = True,
|
||||
**kwargs,
|
||||
):
|
||||
self.model_name = model_name
|
||||
(
|
||||
self.hidden_size,
|
||||
self.num_hidden_layers,
|
||||
self.num_attention_heads,
|
||||
self.intermediate_size,
|
||||
) = VIT_TIMM_DIM_BY_NAME[model_name]
|
||||
self.image_size = image_size
|
||||
self.patch_size = patch_size
|
||||
self.qkv_bias = qkv_bias
|
||||
self.qk_normalization = qk_normalization
|
||||
self.norm_type = norm_type
|
||||
self.layer_norm_eps = layer_norm_eps
|
||||
self.initializer_factor = initializer_factor
|
||||
self.hidden_act = hidden_act
|
||||
self.cpe_max_size = cpe_max_size
|
||||
self.norm_mean = (
|
||||
list(norm_mean) if isinstance(norm_mean, (tuple, list)) else norm_mean
|
||||
)
|
||||
self.norm_std = (
|
||||
list(norm_std) if isinstance(norm_std, (tuple, list)) else norm_std
|
||||
)
|
||||
self.register_multiple = register_multiple
|
||||
self.teachers = teachers if teachers is not None else []
|
||||
self.cls_token_per_teacher = cls_token_per_teacher
|
||||
self.video_temporal_patch_size = video_temporal_patch_size
|
||||
self.separate_video_embedder = separate_video_embedder
|
||||
super().__init__(**kwargs)
|
||||
@@ -1,178 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from typing import Any
|
||||
|
||||
from transformers.configuration_utils import PreTrainedConfig
|
||||
|
||||
|
||||
class Step3VisionEncoderConfig(PreTrainedConfig):
|
||||
model_type = "step3_vision_encoder"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
hidden_size=1792,
|
||||
intermediate_size=3072,
|
||||
output_hidden_size=4096,
|
||||
num_hidden_layers=63,
|
||||
num_attention_heads=16,
|
||||
num_channels=3,
|
||||
image_size=728,
|
||||
patch_size=14,
|
||||
hidden_act="quick_gelu",
|
||||
layer_norm_eps=1e-5,
|
||||
**kwargs,
|
||||
):
|
||||
self.hidden_size = hidden_size
|
||||
self.intermediate_size = intermediate_size
|
||||
self.output_hidden_size = output_hidden_size
|
||||
self.num_hidden_layers = num_hidden_layers
|
||||
self.num_attention_heads = num_attention_heads
|
||||
self.num_channels = num_channels
|
||||
self.patch_size = patch_size
|
||||
self.image_size = image_size
|
||||
self.layer_norm_eps = layer_norm_eps
|
||||
self.hidden_act = hidden_act
|
||||
super().__init__(**kwargs)
|
||||
|
||||
|
||||
class Step3TextConfig(PreTrainedConfig):
|
||||
model_type = "step3_text"
|
||||
architectures = ["Step3TextForCausalLM"]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
hidden_size: int = 7168,
|
||||
intermediate_size: int = 18432,
|
||||
num_attention_heads: int = 64,
|
||||
num_attention_groups: int = 1,
|
||||
num_hidden_layers: int = 61,
|
||||
max_seq_len: int = 65536,
|
||||
vocab_size: int = 128815,
|
||||
rms_norm_eps: float = 1e-5,
|
||||
moe_intermediate_size: int = 5120,
|
||||
moe_num_experts: int = 48,
|
||||
moe_top_k: int = 3,
|
||||
rope_parameters: dict[str, Any] | None = None,
|
||||
max_position_embedding: int = 65536,
|
||||
share_expert_dim: int = 5120,
|
||||
share_q_dim: int = 2048,
|
||||
head_dim: int = 256,
|
||||
norm_expert_weight: bool = False,
|
||||
moe_layers_enum: tuple[int, ...] = (
|
||||
4,
|
||||
5,
|
||||
6,
|
||||
7,
|
||||
8,
|
||||
9,
|
||||
10,
|
||||
11,
|
||||
12,
|
||||
13,
|
||||
14,
|
||||
15,
|
||||
16,
|
||||
17,
|
||||
18,
|
||||
19,
|
||||
20,
|
||||
21,
|
||||
22,
|
||||
23,
|
||||
24,
|
||||
25,
|
||||
26,
|
||||
27,
|
||||
28,
|
||||
29,
|
||||
30,
|
||||
31,
|
||||
32,
|
||||
33,
|
||||
34,
|
||||
35,
|
||||
36,
|
||||
37,
|
||||
38,
|
||||
39,
|
||||
40,
|
||||
41,
|
||||
42,
|
||||
43,
|
||||
44,
|
||||
45,
|
||||
46,
|
||||
47,
|
||||
48,
|
||||
49,
|
||||
50,
|
||||
51,
|
||||
52,
|
||||
53,
|
||||
54,
|
||||
55,
|
||||
56,
|
||||
57,
|
||||
58,
|
||||
59,
|
||||
),
|
||||
**kwargs,
|
||||
) -> None:
|
||||
self.hidden_size = hidden_size
|
||||
self.intermediate_size = intermediate_size
|
||||
self.num_attention_heads = num_attention_heads
|
||||
self.num_attention_groups = num_attention_groups
|
||||
self.num_hidden_layers = num_hidden_layers
|
||||
self.max_seq_len = max_seq_len
|
||||
self.vocab_size = vocab_size
|
||||
self.rms_norm_eps = rms_norm_eps
|
||||
self.moe_intermediate_size = moe_intermediate_size
|
||||
self.moe_num_experts = moe_num_experts
|
||||
self.moe_top_k = moe_top_k
|
||||
# Try to set `rope_scaling` if available, otherwise use `rope_parameters`
|
||||
rope_scaling = kwargs.pop("rope_scaling", None)
|
||||
rope_parameters = rope_scaling or rope_parameters or {"rope_type": "default"}
|
||||
rope_theta = kwargs.pop("rope_theta", 500000.0)
|
||||
if "rope_theta" not in rope_parameters:
|
||||
rope_parameters["rope_theta"] = rope_theta
|
||||
self.rope_parameters = rope_parameters
|
||||
self.max_position_embedding = max_position_embedding
|
||||
self.share_expert_dim = share_expert_dim
|
||||
self.share_q_dim = share_q_dim
|
||||
self.head_dim = head_dim
|
||||
self.norm_expert_weight = norm_expert_weight
|
||||
self.moe_layers_enum = moe_layers_enum
|
||||
|
||||
super().__init__(**kwargs)
|
||||
|
||||
|
||||
class Step3VLConfig(PreTrainedConfig):
|
||||
model_type = "step3_vl"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vision_config: dict | Step3VisionEncoderConfig | None = None,
|
||||
text_config: dict | Step3TextConfig | None = None,
|
||||
understand_projector_stride: int = 1,
|
||||
projector_bias: bool = True,
|
||||
image_token_id: int = 128001,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
if vision_config is None:
|
||||
vision_config = Step3VisionEncoderConfig()
|
||||
elif isinstance(vision_config, dict):
|
||||
vision_config = Step3VisionEncoderConfig(**vision_config)
|
||||
self.vision_config = vision_config
|
||||
|
||||
if text_config is None:
|
||||
text_config = Step3TextConfig()
|
||||
elif isinstance(text_config, dict):
|
||||
text_config = Step3TextConfig(**text_config)
|
||||
self.text_config = text_config
|
||||
|
||||
self.understand_projector_stride = understand_projector_stride
|
||||
self.projector_bias = projector_bias
|
||||
self.hidden_size = text_config.hidden_size
|
||||
self.image_token_id = image_token_id
|
||||
|
||||
super().__init__(**kwargs)
|
||||
@@ -1,103 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from typing import Any
|
||||
|
||||
from transformers.configuration_utils import PreTrainedConfig
|
||||
|
||||
|
||||
class Step3p5Config(PreTrainedConfig):
|
||||
model_type = "step3p5"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
hidden_size: int = 5120,
|
||||
intermediate_size: int = 13312,
|
||||
num_attention_heads: int = 40,
|
||||
num_attention_groups: int = 8,
|
||||
num_hidden_layers: int = 48,
|
||||
max_seq_len: int = 4096,
|
||||
vocab_size: int = 65536,
|
||||
rms_norm_eps: float = 1e-5,
|
||||
moe_every_n_layer: int = 2,
|
||||
use_moe: bool = False,
|
||||
moe_intermediate_size: int = 10240,
|
||||
moe_num_experts: int = 16,
|
||||
moe_top_k: int = 4,
|
||||
moe_layer_offset: int = 0,
|
||||
rope_theta: float | list[float] | None = 500000,
|
||||
rope_scaling: dict[str, Any] | None = None,
|
||||
head_dim: int | None = None,
|
||||
share_expert_dim: int | None = None,
|
||||
norm_expert_weight: bool = True,
|
||||
bos_token_id: list[int] | int | None = None,
|
||||
eos_token_id: list[int] | int | None = None,
|
||||
moe_router_activation: str = "softmax",
|
||||
moe_router_scaling_factor: float = 1.0,
|
||||
att_impl_type: str = "GQA",
|
||||
use_head_wise_attn_gate: bool = False,
|
||||
use_moe_router_bias: bool = True,
|
||||
need_fp32_gate: bool = True,
|
||||
layer_types: list[str] | None = None,
|
||||
use_rope_layers: list[bool] | None = None,
|
||||
yarn_only_types: list[str] | None = None,
|
||||
attention_other_setting: dict[str, Any] | None = None,
|
||||
num_nextn_predict_layers: int = 0,
|
||||
swiglu_limits: list[float] | None = None,
|
||||
swiglu_limits_shared: list[float] | None = None,
|
||||
max_position_embeddings: int | None = None,
|
||||
**kwargs,
|
||||
):
|
||||
self.hidden_size = hidden_size
|
||||
self.intermediate_size = intermediate_size
|
||||
self.num_attention_heads = num_attention_heads
|
||||
self.num_attention_groups = num_attention_groups
|
||||
self.num_hidden_layers = num_hidden_layers
|
||||
self.max_seq_len = max_seq_len
|
||||
self.vocab_size = vocab_size
|
||||
self.rms_norm_eps = rms_norm_eps
|
||||
self.use_moe = use_moe
|
||||
self.moe_intermediate_size = moe_intermediate_size
|
||||
self.moe_every_n_layer = moe_every_n_layer
|
||||
self.moe_num_experts = moe_num_experts
|
||||
self.num_experts_per_tok = moe_top_k
|
||||
self.moe_top_k = moe_top_k
|
||||
self.moe_layer_offset = moe_layer_offset
|
||||
|
||||
self.rope_theta = rope_theta
|
||||
self.rope_scaling = rope_scaling
|
||||
self.head_dim = head_dim
|
||||
if share_expert_dim is None:
|
||||
self.share_expert_dim = self.moe_intermediate_size * self.moe_top_k
|
||||
else:
|
||||
self.share_expert_dim = share_expert_dim
|
||||
self.norm_expert_weight = norm_expert_weight
|
||||
|
||||
self.max_position_embeddings = max_position_embeddings
|
||||
self.moe_router_activation = moe_router_activation
|
||||
self.moe_router_scaling_factor = moe_router_scaling_factor
|
||||
self.use_moe_router_bias = use_moe_router_bias
|
||||
self.need_fp32_gate = need_fp32_gate
|
||||
|
||||
self.att_impl_type = att_impl_type
|
||||
self.use_head_wise_attn_gate = use_head_wise_attn_gate
|
||||
# For some reason the checkpoint has longer layer_types than num_hidden_layers
|
||||
if layer_types is not None:
|
||||
layer_types = layer_types[: self.num_hidden_layers]
|
||||
self.layer_types = layer_types
|
||||
self.use_rope_layers = use_rope_layers
|
||||
self.yarn_only_types = yarn_only_types
|
||||
self.attention_other_setting = attention_other_setting
|
||||
self.num_nextn_predict_layers = num_nextn_predict_layers
|
||||
self.swiglu_limits = swiglu_limits
|
||||
self.swiglu_limits_shared = swiglu_limits_shared
|
||||
|
||||
resolved_bos_token_id = 1 if bos_token_id is None else bos_token_id
|
||||
resolved_eos_token_id = [2, 3] if eos_token_id is None else eos_token_id
|
||||
self.bos_token_id = resolved_bos_token_id
|
||||
self.eos_token_id = resolved_eos_token_id
|
||||
|
||||
super().__init__(
|
||||
bos_token_id=resolved_bos_token_id,
|
||||
eos_token_id=resolved_eos_token_id,
|
||||
**kwargs,
|
||||
)
|
||||
@@ -1,120 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
# Adapted from https://github.com/fixie-ai/ultravox/blob/ecd58c4041030bae2ad15aa6bcf04ab43199ea02/ultravox/model/ultravox_config.py
|
||||
from typing import Any
|
||||
|
||||
import transformers
|
||||
|
||||
|
||||
class UltravoxConfig(transformers.PreTrainedConfig):
|
||||
r"""This is the configuration class to store the configuration of a
|
||||
[`UltravoxForConditionalGeneration`]. It is used to instantiate an
|
||||
Ultravox model according to the specified arguments, defining the model
|
||||
architecture.
|
||||
|
||||
Configuration objects inherit from [`PreTrainedConfig`] and can be used to
|
||||
control the model outputs. Read the documentation from [`PreTrainedConfig`]
|
||||
for more information.
|
||||
|
||||
Args:
|
||||
audio_config (`Union[AutoConfig, dict]`, *optional*):
|
||||
Custom audio config or dict.
|
||||
text_config (`Union[AutoConfig, dict]`, *optional*):
|
||||
The config object of the text backbone.
|
||||
audio_model_id (`str`, *optional*):
|
||||
The model ID of the audio backbone.
|
||||
text_model_id (`str`, *optional*):
|
||||
The model ID of the text backbone.
|
||||
ignore_index (`int`, *optional*, defaults to -100):
|
||||
The ignore index for the loss function.
|
||||
audio_token_index (`int`, *optional*, defaults to 32000):
|
||||
The audio token index to encode the audio prompt.
|
||||
stack_factor (`int`, *optional*, defaults to 8):
|
||||
Audio downsampling factor for the multimodal projector.
|
||||
norm_init (`float`, *optional*, defaults to 0.4):
|
||||
The initialization value for the layer normalization.
|
||||
projector_act (`str`, *optional*, defaults to `"swiglu"`):
|
||||
The activation function used by the multimodal projector.
|
||||
projector_ln_mid (`bool`, *optional*, defaults to `False`):
|
||||
Whether to apply layer normalization at the middle of the
|
||||
projector or at the end. Versions v0.4.1 and below
|
||||
use `False`, but v0.5 and above use `True`.
|
||||
|
||||
"""
|
||||
|
||||
model_type = "ultravox"
|
||||
audio_token = "<|audio|>"
|
||||
is_composition = False
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
audio_config: dict[str, Any] | None = None,
|
||||
text_config: dict[str, Any] | None = None,
|
||||
audio_model_id: str | None = None,
|
||||
text_model_id: str | None = None,
|
||||
ignore_index: int = -100,
|
||||
audio_token_index: int = 32000,
|
||||
hidden_size: int = 4096,
|
||||
stack_factor: int = 8,
|
||||
norm_init: float = 0.4,
|
||||
projector_act: str = "swiglu",
|
||||
projector_ln_mid: bool = False,
|
||||
num_projector_layers: int = 0,
|
||||
**kwargs,
|
||||
):
|
||||
self.ignore_index = ignore_index
|
||||
self.audio_token_index = audio_token_index
|
||||
|
||||
self.hidden_size = hidden_size
|
||||
self.stack_factor = stack_factor
|
||||
self.norm_init = norm_init
|
||||
self.projector_act = projector_act
|
||||
self.projector_ln_mid = projector_ln_mid
|
||||
self.num_projector_layers = num_projector_layers
|
||||
|
||||
# N.B. May set the wrapped_model_config below.
|
||||
self.wrapped_model_config: transformers.PreTrainedConfig
|
||||
self.text_model_id = text_model_id
|
||||
if text_model_id is None:
|
||||
text_config = text_config or {}
|
||||
self.wrapped_model_config = transformers.CONFIG_MAPPING[
|
||||
text_config.get("model_type", "llama")
|
||||
](**text_config)
|
||||
|
||||
# N.B. May set the audio_config below.
|
||||
self.audio_model_id = audio_model_id
|
||||
if audio_model_id is None:
|
||||
self.audio_model_id = None
|
||||
audio_config = audio_config or {}
|
||||
self.audio_config = transformers.CONFIG_MAPPING[
|
||||
audio_config.get("model_type", "whisper")
|
||||
](**audio_config)
|
||||
|
||||
super().__init__(**kwargs)
|
||||
|
||||
def __setattr__(self, key, value):
|
||||
# Since --hf-overrides are applied _after_ the UltravoxConfig is
|
||||
# instantiated, load the configs implicitly when assigning text_model_id
|
||||
# or audio_model_id. This allows:
|
||||
#
|
||||
# --hf-overrides.text_model_id=<quantized variant>
|
||||
#
|
||||
# to behave as intended.
|
||||
if key == "text_model_id" and value is not None:
|
||||
from vllm.transformers_utils.config import get_config
|
||||
|
||||
self.wrapped_model_config = get_config(value, trust_remote_code=False)
|
||||
elif key == "audio_model_id" and value is not None:
|
||||
from vllm.transformers_utils.config import get_config
|
||||
|
||||
self.audio_config = get_config(value, trust_remote_code=False)
|
||||
|
||||
return super().__setattr__(key, value)
|
||||
|
||||
@property
|
||||
def text_config(self) -> transformers.PreTrainedConfig:
|
||||
# When Ultravox wraps a multi-modal model (e.g. Gemma), we instantiate
|
||||
# the full model, but the text config is the text config of the inner
|
||||
# model.
|
||||
return self.wrapped_model_config.get_text_config()
|
||||
@@ -1,35 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
# Unlimited-OCR (baidu/Unlimited-OCR) reuses
|
||||
# the DeepSeek-OCR multimodal layout (DeepEncoder = SAM-ViT-B + CLIP-L, a linear
|
||||
# MLP projector and a DeepSeek-V2 text backbone). The only architectural
|
||||
# difference is the language model, which is a DeepSeek-V2 *MoE* with plain
|
||||
# multi-head attention (``use_mla=False``) instead of the dense MLA backbone.
|
||||
# We therefore reuse ``DeepseekVLV2Config`` for parsing the nested config.
|
||||
|
||||
from vllm.transformers_utils.configs.deepseek_vl2 import DeepseekVLV2Config
|
||||
|
||||
|
||||
class UnlimitedOCRConfig(DeepseekVLV2Config):
|
||||
model_type = "unlimited-ocr"
|
||||
|
||||
# An explicit ``__init__`` is required: Transformers v5 processes each
|
||||
# concrete config class' ``__init__`` signature to build nested sub-configs,
|
||||
# and an empty subclass (only overriding ``model_type``) would skip
|
||||
# ``DeepseekVLV2Config.__init__``, leaving ``text_config`` unset.
|
||||
def __init__(
|
||||
self,
|
||||
tile_tag: str = "2D",
|
||||
global_view_pos: str = "head",
|
||||
candidate_resolutions: tuple[tuple[int, int]] = ((384, 384),),
|
||||
rswa_window: int = 128,
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__(
|
||||
tile_tag=tile_tag,
|
||||
global_view_pos=global_view_pos,
|
||||
candidate_resolutions=candidate_resolutions,
|
||||
**kwargs,
|
||||
)
|
||||
self.rswa_window = rswa_window
|
||||
Reference in New Issue
Block a user