# Copyright 2024 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. """Qwen2VL model configuration""" import inspect from huggingface_hub.dataclasses import strict from ...configuration_utils import PreTrainedConfig from ...modeling_rope_utils import RopeParameters from ...utils import auto_docstring @auto_docstring(checkpoint="Qwen/Qwen2-VL-7B-Instruct") @strict class Qwen2VLVisionConfig(PreTrainedConfig): model_type = "qwen2_vl_vision" base_config_key = "vision_config" depth: int = 32 embed_dim: int = 1280 hidden_size: int = 3584 hidden_act: str = "quick_gelu" mlp_ratio: int = 4 num_heads: int = 16 in_channels: int = 3 patch_size: int | list[int] | tuple[int, int] = 14 spatial_merge_size: int = 2 temporal_patch_size: int | list[int] | tuple[int, int] = 2 initializer_range: float = 0.02 @auto_docstring(checkpoint="Qwen/Qwen2-VL-7B-Instruct") @strict class Qwen2VLTextConfig(PreTrainedConfig): r""" ```python >>> from transformers import Qwen2VLTextModel, Qwen2VLConfig >>> # Initializing a Qwen2VL style configuration >>> configuration = Qwen2VLConfig() >>> # Initializing a model from the Qwen2-VL-7B style configuration >>> model = Qwen2VLTextModel(configuration) >>> # Accessing the model configuration >>> configuration = model.config ``` """ model_type = "qwen2_vl_text" base_config_key = "text_config" keys_to_ignore_at_inference = ["past_key_values"] default_theta = 1000000.0 # Default tensor parallel plan for base model `Qwen2VL` base_model_tp_plan = { "layers.*.self_attn.q_proj": "colwise", "layers.*.self_attn.k_proj": "colwise", "layers.*.self_attn.v_proj": "colwise", "layers.*.self_attn.o_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"]), } ignore_keys_at_rope_validation = {"mrope_section"} vocab_size: int = 152064 hidden_size: int = 8192 intermediate_size: int = 29568 num_hidden_layers: int = 80 num_attention_heads: int = 64 num_key_value_heads: int | None = 8 hidden_act: str = "silu" max_position_embeddings: int = 32768 initializer_range: float = 0.02 rms_norm_eps: float = 1e-05 use_cache: bool = True use_sliding_window: bool | None = False sliding_window: int | None = 4096 max_window_layers: int | None = 80 layer_types: list[str] | None = None attention_dropout: float | int | None = 0.0 rope_parameters: RopeParameters | dict | None = None bos_token_id: int | None = 151643 eos_token_id: int | list[int] | None = 151645 pad_token_id: int | None = None def __post_init__(self, **kwargs): self.sliding_window = self.sliding_window if self.use_sliding_window else None # for backward compatibility if self.num_key_value_heads is None: self.num_key_value_heads = self.num_attention_heads if self.layer_types is None: self.layer_types = [ "sliding_attention" if self.sliding_window is not None and i >= self.max_window_layers else "full_attention" for i in range(self.num_hidden_layers) ] super().__post_init__(**kwargs) def convert_rope_params_to_dict(self, **kwargs): rope_scaling = kwargs.pop("rope_scaling", None) self.rope_parameters = rope_scaling or self.rope_parameters self.rope_parameters = self.rope_parameters if self.rope_parameters is not None else {} # Standardize and validate the correctness of rotary position embeddings parameters self.rope_parameters.setdefault("rope_theta", kwargs.pop("rope_theta", self.default_theta)) if self.rope_parameters.get("rope_type", self.rope_parameters.get("type")) == "mrope": self.rope_parameters["rope_type"] = "default" self.standardize_rope_params() return kwargs @auto_docstring(checkpoint="Qwen/Qwen2-VL-7B-Instruct") @strict class Qwen2VLConfig(PreTrainedConfig): r""" Example: ```python >>> from transformers import Qwen2VLForConditionalGeneration, Qwen2VLConfig >>> # Initializing a Qwen2VL style configuration >>> configuration = Qwen2VLConfig() >>> # Initializing a model from the Qwen2-VL-7B style configuration >>> model = Qwen2VLForConditionalGeneration(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" model_type = "qwen2_vl" sub_configs = {"vision_config": Qwen2VLVisionConfig, "text_config": Qwen2VLTextConfig} keys_to_ignore_at_inference = ["past_key_values"] text_config: dict | PreTrainedConfig | None = None vision_config: dict | PreTrainedConfig | 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 def __post_init__(self, **kwargs): if isinstance(self.vision_config, dict): self.vision_config = self.sub_configs["vision_config"](**self.vision_config) elif self.vision_config is None: self.vision_config = self.sub_configs["vision_config"]() # Hub configs are saved as flat dicts so we pop some of kwargs to init `TextConfig` text_params = inspect.signature(self.sub_configs["text_config"].__init__).parameters.keys() text_params = list(text_params) + ["rope_parameters", "rope_scaling", "rope_theta"] text_kwargs = {key: kwargs.pop(key) for key in text_params if key in kwargs} if isinstance(self.text_config, dict): self.text_config = self.sub_configs["text_config"](**self.text_config) elif self.text_config is None: # Hub configs are saved as flat dicts so we pop some of kwargs to init `TextConfig` text_kwargs["dtype"] = kwargs.get("torch_dtype", kwargs.get("dtype")) # don't pop the dtype self.text_config = self.sub_configs["text_config"](**text_kwargs) # BC: pre-v5 saves placed `tie_word_embeddings` inside text_config. Forward it to the outer # config (where v5's tying logic looks) when the root value is the default. Checked after # text_config init so it also covers a text config passed as an already-initialized instance. if not self.tie_word_embeddings and getattr(self.text_config, "tie_word_embeddings", False): self.tie_word_embeddings = True super().__post_init__(**kwargs) __all__ = ["Qwen2VLConfig", "Qwen2VLTextConfig", "Qwen2VLVisionConfig"]