magicgh commited on
Commit
3300a32
·
verified ·
1 Parent(s): f8f14e2

Delete configuration_qwen2_vl.py

Browse files
Files changed (1) hide show
  1. configuration_qwen2_vl.py +0 -262
configuration_qwen2_vl.py DELETED
@@ -1,262 +0,0 @@
1
- # coding=utf-8
2
- # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
- #
4
- # Licensed under the Apache License, Version 2.0 (the "License");
5
- # you may not use this file except in compliance with the License.
6
- # You may obtain a copy of the License at
7
- #
8
- # http://www.apache.org/licenses/LICENSE-2.0
9
- #
10
- # Unless required by applicable law or agreed to in writing, software
11
- # distributed under the License is distributed on an "AS IS" BASIS,
12
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- # See the License for the specific language governing permissions and
14
- # limitations under the License.
15
- """Qwen2VL model configuration"""
16
-
17
- import os
18
- from typing import Union
19
-
20
- from transformers.configuration_utils import PretrainedConfig
21
- from transformers.modeling_rope_utils import rope_config_validation
22
- from transformers.utils import logging
23
-
24
-
25
- logger = logging.get_logger(__name__)
26
-
27
-
28
- class Qwen2VLVisionConfig(PretrainedConfig):
29
- model_type = "qwen2_vl"
30
- base_config_key = "vision_config"
31
-
32
- def __init__(
33
- self,
34
- depth=32,
35
- embed_dim=1280,
36
- hidden_size=3584,
37
- hidden_act="quick_gelu",
38
- mlp_ratio=4,
39
- num_heads=16,
40
- in_channels=3,
41
- patch_size=14,
42
- spatial_merge_size=2,
43
- temporal_patch_size=2,
44
- **kwargs,
45
- ):
46
- super().__init__(**kwargs)
47
-
48
- self.depth = depth
49
- self.embed_dim = embed_dim
50
- self.hidden_size = hidden_size
51
- self.hidden_act = hidden_act
52
- self.mlp_ratio = mlp_ratio
53
- self.num_heads = num_heads
54
- self.in_channels = in_channels
55
- self.patch_size = patch_size
56
- self.spatial_merge_size = spatial_merge_size
57
- self.temporal_patch_size = temporal_patch_size
58
-
59
- @classmethod
60
- def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
61
- cls._set_token_in_kwargs(kwargs)
62
-
63
- config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
64
-
65
- if config_dict.get("model_type") == "qwen2_vl":
66
- config_dict = config_dict["vision_config"]
67
-
68
- if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
69
- logger.warning(
70
- f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
71
- f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
72
- )
73
-
74
- return cls.from_dict(config_dict, **kwargs)
75
-
76
-
77
- class Qwen2VLConfig(PretrainedConfig):
78
- r"""
79
- This is the configuration class to store the configuration of a [`Qwen2VLModel`]. It is used to instantiate a
80
- Qwen2-VL model according to the specified arguments, defining the model architecture. Instantiating a configuration
81
- with the defaults will yield a similar configuration to that of
82
- Qwen2-VL-7B-Instruct [Qwen/Qwen2-VL-7B-Instruct](https://huggingface.co/Qwen/Qwen2-VL-7B-Instruct).
83
-
84
- Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
85
- documentation from [`PretrainedConfig`] for more information.
86
-
87
-
88
- Args:
89
- vocab_size (`int`, *optional*, defaults to 152064):
90
- Vocabulary size of the Qwen2VL model. Defines the number of different tokens that can be represented by the
91
- `inputs_ids` passed when calling [`Qwen2VLModel`]
92
- hidden_size (`int`, *optional*, defaults to 8192):
93
- Dimension of the hidden representations.
94
- intermediate_size (`int`, *optional*, defaults to 29568):
95
- Dimension of the MLP representations.
96
- num_hidden_layers (`int`, *optional*, defaults to 80):
97
- Number of hidden layers in the Transformer encoder.
98
- num_attention_heads (`int`, *optional*, defaults to 64):
99
- Number of attention heads for each attention layer in the Transformer encoder.
100
- num_key_value_heads (`int`, *optional*, defaults to 8):
101
- This is the number of key_value heads that should be used to implement Grouped Query Attention. If
102
- `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
103
- `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
104
- converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
105
- by meanpooling all the original heads within that group. For more details checkout [this
106
- paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
107
- hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
108
- The non-linear activation function (function or string) in the decoder.
109
- max_position_embeddings (`int`, *optional*, defaults to 32768):
110
- The maximum sequence length that this model might ever be used with.
111
- initializer_range (`float`, *optional*, defaults to 0.02):
112
- The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
113
- rms_norm_eps (`float`, *optional*, defaults to 1e-05):
114
- The epsilon used by the rms normalization layers.
115
- use_cache (`bool`, *optional*, defaults to `True`):
116
- Whether or not the model should return the last key/values attentions (not used by all models). Only
117
- relevant if `config.is_decoder=True`.
118
- tie_word_embeddings (`bool`, *optional*, defaults to `False`):
119
- Whether the model's input and output word embeddings should be tied.
120
- rope_theta (`float`, *optional*, defaults to 1000000.0):
121
- The base period of the RoPE embeddings.
122
- use_sliding_window (`bool`, *optional*, defaults to `False`):
123
- Whether to use sliding window attention.
124
- sliding_window (`int`, *optional*, defaults to 4096):
125
- Sliding window attention (SWA) window size. If not specified, will default to `4096`.
126
- max_window_layers (`int`, *optional*, defaults to 80):
127
- The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
128
- attention_dropout (`float`, *optional*, defaults to 0.0):
129
- The dropout ratio for the attention probabilities.
130
- vision_config (`Dict`, *optional*):
131
- The config for the visual encoder initialization.
132
- rope_scaling (`Dict`, *optional*):
133
- Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
134
- and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
135
- accordingly.
136
- Expected contents:
137
- `rope_type` (`str`):
138
- The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
139
- 'llama3'], with 'default' being the original RoPE implementation.
140
- `factor` (`float`, *optional*):
141
- Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
142
- most scaling types, a `factor` of x will enable the model to handle sequences of length x *
143
- original maximum pre-trained length.
144
- `original_max_position_embeddings` (`int`, *optional*):
145
- Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
146
- pretraining.
147
- `attention_factor` (`float`, *optional*):
148
- Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
149
- computation. If unspecified, it defaults to value recommended by the implementation, using the
150
- `factor` field to infer the suggested value.
151
- `beta_fast` (`float`, *optional*):
152
- Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
153
- ramp function. If unspecified, it defaults to 32.
154
- `beta_slow` (`float`, *optional*):
155
- Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
156
- ramp function. If unspecified, it defaults to 1.
157
- `short_factor` (`List[float]`, *optional*):
158
- Only used with 'longrope'. The scaling factor to be applied to short contexts (<
159
- `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
160
- size divided by the number of attention heads divided by 2
161
- `long_factor` (`List[float]`, *optional*):
162
- Only used with 'longrope'. The scaling factor to be applied to long contexts (<
163
- `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
164
- size divided by the number of attention heads divided by 2
165
- `low_freq_factor` (`float`, *optional*):
166
- Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
167
- `high_freq_factor` (`float`, *optional*):
168
- Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
169
-
170
- ```python
171
- >>> from transformers import Qwen2VLForConditionalGeneration, Qwen2VLConfig
172
-
173
- >>> # Initializing a Qwen2VL style configuration
174
- >>> configuration = Qwen2VLConfig()
175
-
176
- >>> # Initializing a model from the Qwen2-VL-7B style configuration
177
- >>> model = Qwen2VLForConditionalGeneration(configuration)
178
-
179
- >>> # Accessing the model configuration
180
- >>> configuration = model.config
181
- ```"""
182
-
183
- model_type = "qwen2_vl"
184
- sub_configs = {"vision_config": Qwen2VLVisionConfig}
185
- keys_to_ignore_at_inference = ["past_key_values"]
186
- # Default tensor parallel plan for base model `Qwen2VL`
187
- base_model_tp_plan = {
188
- "layers.*.self_attn.q_proj": "colwise",
189
- "layers.*.self_attn.k_proj": "colwise",
190
- "layers.*.self_attn.v_proj": "colwise",
191
- "layers.*.self_attn.o_proj": "rowwise",
192
- "layers.*.mlp.gate_proj": "colwise",
193
- "layers.*.mlp.up_proj": "colwise",
194
- "layers.*.mlp.down_proj": "rowwise",
195
- }
196
-
197
- def __init__(
198
- self,
199
- vocab_size=152064,
200
- hidden_size=8192,
201
- intermediate_size=29568,
202
- num_hidden_layers=80,
203
- num_attention_heads=64,
204
- num_key_value_heads=8,
205
- hidden_act="silu",
206
- max_position_embeddings=32768,
207
- initializer_range=0.02,
208
- rms_norm_eps=1e-05,
209
- use_cache=True,
210
- tie_word_embeddings=False,
211
- rope_theta=1000000.0,
212
- use_sliding_window=False,
213
- sliding_window=4096,
214
- max_window_layers=80,
215
- attention_dropout=0.0,
216
- vision_config=None,
217
- rope_scaling=None,
218
- **kwargs,
219
- ):
220
- if isinstance(vision_config, dict):
221
- self.vision_config = self.sub_configs["vision_config"](**vision_config)
222
- elif vision_config is None:
223
- self.vision_config = self.sub_configs["vision_config"]()
224
-
225
- self.vocab_size = vocab_size
226
- self.max_position_embeddings = max_position_embeddings
227
- self.hidden_size = hidden_size
228
- self.intermediate_size = intermediate_size
229
- self.num_hidden_layers = num_hidden_layers
230
- self.num_attention_heads = num_attention_heads
231
- self.use_sliding_window = use_sliding_window
232
- self.sliding_window = sliding_window
233
- self.max_window_layers = max_window_layers
234
-
235
- # for backward compatibility
236
- if num_key_value_heads is None:
237
- num_key_value_heads = num_attention_heads
238
-
239
- self.num_key_value_heads = num_key_value_heads
240
- self.hidden_act = hidden_act
241
- self.initializer_range = initializer_range
242
- self.rms_norm_eps = rms_norm_eps
243
- self.use_cache = use_cache
244
- self.rope_theta = rope_theta
245
- self.attention_dropout = attention_dropout
246
- self.rope_scaling = rope_scaling
247
-
248
- # Validate the correctness of rotary position embeddings parameters
249
- # BC: if there is a 'type' field, move it to 'rope_type'.
250
- # and change type from 'mrope' to 'default' because `mrope` does defeault RoPE calculations
251
- # one can set it to "linear"/"dynamic" etc. to have scaled RoPE
252
- # TODO: @raushan update config in the hub
253
- if self.rope_scaling is not None and "type" in self.rope_scaling:
254
- if self.rope_scaling["type"] == "mrope":
255
- self.rope_scaling["type"] = "default"
256
- self.rope_scaling["rope_type"] = self.rope_scaling["type"]
257
- rope_config_validation(self, ignore_keys={"mrope_section"})
258
-
259
- super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
260
-
261
-
262
- __all__ = ["Qwen2VLConfig"]