Karroyan commited on
Commit
1a23202
·
verified ·
1 Parent(s): 4639414

Upload configuration_keye.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. configuration_keye.py +243 -0
configuration_keye.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from transformers.configuration_utils import PretrainedConfig
15
+ from transformers.modeling_rope_utils import rope_config_validation
16
+
17
+
18
+ class KeyeVisionConfig(PretrainedConfig):
19
+ model_type = "Keye"
20
+ base_config_key = "vision_config"
21
+
22
+ def __init__(
23
+ self,
24
+ hidden_size=768,
25
+ intermediate_size=3072,
26
+ num_hidden_layers=12,
27
+ num_attention_heads=12,
28
+ num_channels=3,
29
+ image_size=224,
30
+ patch_size=14,
31
+ hidden_act="gelu_pytorch_tanh",
32
+ layer_norm_eps=1e-6,
33
+ attention_dropout=0.0,
34
+ spatial_merge_size=2,
35
+ temporal_patch_size=2,
36
+ tokens_per_second=2,
37
+ **kwargs,
38
+ ):
39
+ super().__init__(**kwargs)
40
+
41
+ self.hidden_size = hidden_size
42
+ self.intermediate_size = intermediate_size
43
+ self.num_hidden_layers = num_hidden_layers
44
+ self.num_attention_heads = num_attention_heads
45
+ self.num_channels = num_channels
46
+ self.patch_size = patch_size
47
+ self.image_size = image_size
48
+ self.attention_dropout = attention_dropout
49
+ self.layer_norm_eps = layer_norm_eps
50
+ self.hidden_act = hidden_act
51
+ self.spatial_merge_size = spatial_merge_size
52
+ self.temporal_patch_size = temporal_patch_size
53
+ self.tokens_per_second = tokens_per_second
54
+
55
+
56
+ class KeyeConfig(PretrainedConfig):
57
+ r"""
58
+ This is the configuration class to store the configuration of a [`KeyeForConditionalGeneration`].
59
+
60
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
61
+ documentation from [`PretrainedConfig`] for more information.
62
+
63
+
64
+ Args:
65
+ vocab_size (`int`, *optional*, defaults to 152064):
66
+ Vocabulary size of the Keye model. Defines the number of different tokens that can be represented by the
67
+ `inputs_ids` passed when calling [`KeyeForConditionalGeneration`]
68
+ hidden_size (`int`, *optional*, defaults to 8192):
69
+ Dimension of the hidden representations.
70
+ intermediate_size (`int`, *optional*, defaults to 29568):
71
+ Dimension of the MLP representations.
72
+ num_hidden_layers (`int`, *optional*, defaults to 80):
73
+ Number of hidden layers in the Transformer encoder.
74
+ num_attention_heads (`int`, *optional*, defaults to 64):
75
+ Number of attention heads for each attention layer in the Transformer encoder.
76
+ num_key_value_heads (`int`, *optional*, defaults to 8):
77
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
78
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
79
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
80
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
81
+ by meanpooling all the original heads within that group. For more details checkout [this
82
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
83
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
84
+ The non-linear activation function (function or string) in the decoder.
85
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
86
+ The maximum sequence length that this model might ever be used with.
87
+ initializer_range (`float`, *optional*, defaults to 0.02):
88
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
89
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
90
+ The epsilon used by the rms normalization layers.
91
+ use_cache (`bool`, *optional*, defaults to `True`):
92
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
93
+ relevant if `config.is_decoder=True`.
94
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
95
+ Whether the model's input and output word embeddings should be tied.
96
+ rope_theta (`float`, *optional*, defaults to 1000000.0):
97
+ The base period of the RoPE embeddings.
98
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
99
+ Whether to use sliding window attention.
100
+ sliding_window (`int`, *optional*, defaults to 4096):
101
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
102
+ max_window_layers (`int`, *optional*, defaults to 80):
103
+ The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
104
+ attention_dropout (`float`, *optional*, defaults to 0.0):
105
+ The dropout ratio for the attention probabilities.
106
+ vision_config (`Dict`, *optional*):
107
+ The config for the visual encoder initialization.
108
+ rope_scaling (`Dict`, *optional*):
109
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
110
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
111
+ accordingly.
112
+ Expected contents:
113
+ `rope_type` (`str`):
114
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
115
+ 'llama3'], with 'default' being the original RoPE implementation.
116
+ `factor` (`float`, *optional*):
117
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
118
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
119
+ original maximum pre-trained length.
120
+ `original_max_position_embeddings` (`int`, *optional*):
121
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
122
+ pretraining.
123
+ `attention_factor` (`float`, *optional*):
124
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
125
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
126
+ `factor` field to infer the suggested value.
127
+ `beta_fast` (`float`, *optional*):
128
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
129
+ ramp function. If unspecified, it defaults to 32.
130
+ `beta_slow` (`float`, *optional*):
131
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
132
+ ramp function. If unspecified, it defaults to 1.
133
+ `short_factor` (`List[float]`, *optional*):
134
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
135
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
136
+ size divided by the number of attention heads divided by 2
137
+ `long_factor` (`List[float]`, *optional*):
138
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
139
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
140
+ size divided by the number of attention heads divided by 2
141
+ `low_freq_factor` (`float`, *optional*):
142
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
143
+ `high_freq_factor` (`float`, *optional*):
144
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
145
+
146
+ ```python
147
+ >>> from transformers import KeyeForConditionalGeneration, KeyeConfig
148
+
149
+ >>> # Initializing a Keye style configuration
150
+ >>> configuration = KeyeConfig()
151
+
152
+ >>> # Initializing a model from the Keye style configuration
153
+ >>> model = KeyeForConditionalGeneration(configuration)
154
+
155
+ >>> # Accessing the model configuration
156
+ >>> configuration = model.config
157
+ ```"""
158
+
159
+ model_type = "Keye"
160
+ sub_configs = {"vision_config": KeyeVisionConfig}
161
+ keys_to_ignore_at_inference = ["past_key_values"]
162
+ # Default tensor parallel plan for base model `Keye`
163
+ base_model_tp_plan = {
164
+ "layers.*.self_attn.q_proj": "colwise",
165
+ "layers.*.self_attn.k_proj": "colwise",
166
+ "layers.*.self_attn.v_proj": "colwise",
167
+ "layers.*.self_attn.o_proj": "rowwise",
168
+ "layers.*.mlp.gate_proj": "colwise",
169
+ "layers.*.mlp.up_proj": "colwise",
170
+ "layers.*.mlp.down_proj": "rowwise",
171
+ }
172
+ base_model_pp_plan = {
173
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
174
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
175
+ "norm": (["hidden_states"], ["hidden_states"]),
176
+ }
177
+
178
+ def __init__(
179
+ self,
180
+ vocab_size=152064,
181
+ hidden_size=8192,
182
+ intermediate_size=29568,
183
+ num_hidden_layers=80,
184
+ num_attention_heads=64,
185
+ num_key_value_heads=8,
186
+ hidden_act="silu",
187
+ max_position_embeddings=32768,
188
+ initializer_range=0.02,
189
+ rms_norm_eps=1e-05,
190
+ use_cache=True,
191
+ tie_word_embeddings=False,
192
+ rope_theta=1000000.0,
193
+ use_sliding_window=False,
194
+ sliding_window=4096,
195
+ max_window_layers=80,
196
+ attention_dropout=0.0,
197
+ vision_config=None,
198
+ rope_scaling=None,
199
+ **kwargs,
200
+ ):
201
+ if isinstance(vision_config, dict):
202
+ self.vision_config = self.sub_configs["vision_config"](**vision_config)
203
+ elif vision_config is None:
204
+ self.vision_config = self.sub_configs["vision_config"]()
205
+
206
+ self.vocab_size = vocab_size
207
+ self.max_position_embeddings = max_position_embeddings
208
+ self.hidden_size = hidden_size
209
+ self.intermediate_size = intermediate_size
210
+ self.num_hidden_layers = num_hidden_layers
211
+ self.num_attention_heads = num_attention_heads
212
+ self.use_sliding_window = use_sliding_window
213
+ self.sliding_window = sliding_window
214
+ self.max_window_layers = max_window_layers
215
+
216
+ # for backward compatibility
217
+ if num_key_value_heads is None:
218
+ num_key_value_heads = num_attention_heads
219
+
220
+ self.num_key_value_heads = num_key_value_heads
221
+ self.hidden_act = hidden_act
222
+ self.initializer_range = initializer_range
223
+ self.rms_norm_eps = rms_norm_eps
224
+ self.use_cache = use_cache
225
+ self.rope_theta = rope_theta
226
+ self.attention_dropout = attention_dropout
227
+ self.rope_scaling = rope_scaling
228
+
229
+ # Validate the correctness of rotary position embeddings parameters
230
+ # BC: if there is a 'type' field, move it to 'rope_type'.
231
+ # and change type from 'mrope' to 'default' because `mrope` does default RoPE calculations
232
+ # one can set it to "linear"/"dynamic" etc. to have scaled RoPE
233
+ # TODO: @raushan update config in the hub
234
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
235
+ if self.rope_scaling["type"] == "mrope":
236
+ self.rope_scaling["type"] = "default"
237
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
238
+ rope_config_validation(self, ignore_keys={"mrope_section"})
239
+
240
+ super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
241
+
242
+
243
+ __all__ = ["KeyeConfig"]