iaooo-shivprasad commited on
Commit
8b35b31
·
verified ·
1 Parent(s): c4d07a0

Create configuration_phi.py

Browse files
Files changed (1) hide show
  1. configuration_phi.py +246 -0
configuration_phi.py ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Microsoft 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
+
16
+ """ Phi model configuration"""
17
+
18
+ from transformers.configuration_utils import PretrainedConfig
19
+ from transformers.utils import logging
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+ PHI_PRETRAINED_CONFIG_ARCHIVE_MAP = {
24
+ "microsoft/phi-1": "https://huggingface.co/microsoft/phi-1/resolve/main/config.json",
25
+ "microsoft/phi-1_5": "https://huggingface.co/microsoft/phi-1_5/resolve/main/config.json",
26
+ "microsoft/phi-2": "https://huggingface.co/microsoft/phi-2/resolve/main/config.json",
27
+ }
28
+
29
+
30
+ class PhiConfig(PretrainedConfig):
31
+ r"""
32
+ This is the configuration class to store the configuration of a [`PhiModel`]. It is used to instantiate an Phi
33
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
34
+ defaults will yield a similar configuration to that of the Phi
35
+ [microsoft/phi-1](https://huggingface.co/microsoft/phi-1).
36
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
37
+ documentation from [`PretrainedConfig`] for more information.
38
+ Args:
39
+ vocab_size (`int`, *optional*, defaults to 51200):
40
+ Vocabulary size of the Phi model. Defines the number of different tokens that can be represented by the
41
+ `inputs_ids` passed when calling [`PhiModel`].
42
+ hidden_size (`int`, *optional*, defaults to 2048):
43
+ Dimension of the hidden representations.
44
+ intermediate_size (`int`, *optional*, defaults to 8192):
45
+ Dimension of the MLP representations.
46
+ num_hidden_layers (`int`, *optional*, defaults to 24):
47
+ Number of hidden layers in the Transformer decoder.
48
+ num_attention_heads (`int`, *optional*, defaults to 32):
49
+ Number of attention heads for each attention layer in the Transformer decoder.
50
+ num_key_value_heads (`int`, *optional*):
51
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
52
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
53
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
54
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
55
+ by meanpooling all the original heads within that group. For more details checkout [this
56
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
57
+ `num_attention_heads`.
58
+ resid_pdrop (`float`, *optional*, defaults to 0.0):
59
+ Dropout probability for mlp outputs.
60
+ embd_pdrop (`int`, *optional*, defaults to 0.0):
61
+ The dropout ratio for the embeddings.
62
+ attention_dropout (`float`, *optional*, defaults to 0.0):
63
+ The dropout ratio after computing the attention scores.
64
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu_new"`):
65
+ The non-linear activation function (function or string) in the decoder.
66
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
67
+ The maximum sequence length that this model might ever be used with. Phi-1 and Phi-1.5 supports up to 2048
68
+ tokens.
69
+ initializer_range (`float`, *optional*, defaults to 0.02):
70
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
71
+ layer_norm_eps (`float`, *optional*, defaults to 1e-05):
72
+ The epsilon used by the rms normalization layers.
73
+ use_cache (`bool`, *optional*, defaults to `True`):
74
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
75
+ relevant if `config.is_decoder=True`. Whether to tie weight embeddings or not.
76
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
77
+ Whether to tie weight embeddings
78
+ rope_theta (`float`, *optional*, defaults to 10000.0):
79
+ The base period of the RoPE embeddings.
80
+ rope_scaling (`Dict`, *optional*):
81
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
82
+ strategies: linear and dynamic. Their scaling factor must be an float greater than 1. The expected format
83
+ is `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
84
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
85
+ these scaling strategies behave:
86
+ https://www.reddit.com/r/LocalPersimmon/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This
87
+ is an experimental feature, subject to breaking API changes in future versions.
88
+ partial_rotary_factor (`float`, *optional*, defaults to 0.5):
89
+ Percentage of the query and keys which will have rotary embedding.
90
+ qk_layernorm (`bool`, *optional*, defaults to `False`):
91
+ Whether or not to normalize the Queries and Keys after projecting the hidden states.
92
+ bos_token_id (`int`, *optional*, defaults to 1):
93
+ Denotes beginning of sequences token id.
94
+ eos_token_id (`int`, *optional*, defaults to 2):
95
+ Denotes end of sequences token id.
96
+ Example:
97
+ ```python
98
+ >>> from transformers import PhiModel, PhiConfig
99
+ >>> # Initializing a Phi-1 style configuration
100
+ >>> configuration = PhiConfig.from_pretrained("microsoft/phi-1")
101
+ >>> # Initializing a model from the configuration
102
+ >>> model = PhiModel(configuration)
103
+ >>> # Accessing the model configuration
104
+ >>> configuration = model.config
105
+ ```"""
106
+
107
+ model_type = "phi"
108
+ keys_to_ignore_at_inference = ["past_key_values"]
109
+
110
+ def __init__(
111
+ self,
112
+ vocab_size=51200,
113
+ hidden_size=2048,
114
+ intermediate_size=8192,
115
+ num_hidden_layers=24,
116
+ num_attention_heads=32,
117
+ num_key_value_heads=None,
118
+ resid_pdrop=0.0,
119
+ embd_pdrop=0.0,
120
+ attention_dropout=0.0,
121
+ hidden_act="gelu_new",
122
+ max_position_embeddings=2048,
123
+ initializer_range=0.02,
124
+ layer_norm_eps=1e-5,
125
+ use_cache=True,
126
+ tie_word_embeddings=False,
127
+ rope_theta=10000.0,
128
+ rope_scaling=None,
129
+ partial_rotary_factor=0.5,
130
+ qk_layernorm=False,
131
+ bos_token_id=1,
132
+ eos_token_id=2,
133
+ **kwargs,
134
+ ):
135
+ self.vocab_size = vocab_size
136
+ self.hidden_size = hidden_size
137
+ self.intermediate_size = intermediate_size
138
+ self.num_hidden_layers = num_hidden_layers
139
+ self.num_attention_heads = num_attention_heads
140
+
141
+ if num_key_value_heads is None:
142
+ num_key_value_heads = num_attention_heads
143
+
144
+ self.num_key_value_heads = num_key_value_heads
145
+ self.resid_pdrop = resid_pdrop
146
+ self.embd_pdrop = embd_pdrop
147
+ self.attention_dropout = attention_dropout
148
+ self.hidden_act = hidden_act
149
+ self.max_position_embeddings = max_position_embeddings
150
+ self.initializer_range = initializer_range
151
+ self.layer_norm_eps = layer_norm_eps
152
+ self.use_cache = use_cache
153
+ self.rope_theta = rope_theta
154
+ self.rope_scaling = rope_scaling
155
+ self.partial_rotary_factor = partial_rotary_factor
156
+ self.qk_layernorm = qk_layernorm
157
+ self._rope_scaling_validation()
158
+
159
+ super().__init__(
160
+ bos_token_id=bos_token_id,
161
+ eos_token_id=eos_token_id,
162
+ tie_word_embeddings=tie_word_embeddings,
163
+ **kwargs,
164
+ )
165
+
166
+ # Copied from transformers.models.llama.configuration_llama.LlamaConfig._rope_scaling_validation
167
+ def _rope_scaling_validation(self):
168
+ """
169
+ Validate the `rope_scaling` configuration.
170
+ """
171
+ if self.rope_scaling is None:
172
+ return
173
+
174
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
175
+ raise ValueError(
176
+ "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
177
+ f"got {self.rope_scaling}"
178
+ )
179
+ rope_scaling_type = self.rope_scaling.get("type", None)
180
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
181
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
182
+ raise ValueError(
183
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
184
+ )
185
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
186
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
187
+
188
+
189
+ from typing import Union
190
+ from transformers import PretrainedConfig
191
+ import os
192
+
193
+
194
+ class SigLipVisionConfig(PretrainedConfig):
195
+ model_type = "siglip_vision_model"
196
+
197
+ def __init__(
198
+ self,
199
+ hidden_size=1152,
200
+ image_mean=(0.5, 0.5, 0.5),
201
+ intermediate_size=4304,
202
+ num_hidden_layers=27,
203
+ num_attention_heads=16,
204
+ num_channels=3,
205
+ image_size=384,
206
+ patch_size=14,
207
+ hidden_act="gelu_pytorch_tanh",
208
+ layer_norm_eps=1e-6,
209
+ attention_dropout=0.0,
210
+ **kwargs,
211
+ ):
212
+ super().__init__(**kwargs)
213
+
214
+ self.hidden_size = hidden_size
215
+ self.intermediate_size = intermediate_size
216
+ self.num_hidden_layers = num_hidden_layers
217
+ self.num_attention_heads = num_attention_heads
218
+ self.num_channels = num_channels
219
+ self.patch_size = patch_size
220
+ self.image_size = image_size
221
+ self.attention_dropout = attention_dropout
222
+ self.layer_norm_eps = layer_norm_eps
223
+ self.hidden_act = hidden_act
224
+ self.image_mean = image_mean
225
+
226
+ @classmethod
227
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
228
+ cls._set_token_in_kwargs(kwargs)
229
+
230
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
231
+
232
+ # get the vision config dict if we are loading from SigLipConfig
233
+ if config_dict.get("model_type") == "siglip":
234
+ config_dict = config_dict["vision_config"]
235
+
236
+ if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
237
+ logger.warning(
238
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
239
+ f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
240
+ )
241
+
242
+ return cls.from_dict(config_dict, **kwargs)
243
+
244
+
245
+ class BunnyPhiConfig(PhiConfig):
246
+ model_type = "bunny-phi"