Image-Text-to-Text
Transformers
Safetensors
feature-extraction
conversational
custom_code
Yin-Xie commited on
Commit
16dae6f
·
verified ·
1 Parent(s): c1b093d

Upload configuration_llavaonevision1_5.py with huggingface_hub

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