Pearush commited on
Commit
762a986
1 Parent(s): 3bd1874

Upload configuration_phimoe.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. configuration_phimoe.py +244 -0
configuration_phimoe.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 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
+ """ PyTorch Phi-MoE model."""
17
+
18
+
19
+ from transformers.configuration_utils import PretrainedConfig
20
+ from transformers.utils import logging
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+
26
+ PHIMOE_PRETRAINED_CONFIG_ARCHIVE_MAP = {
27
+ "microsoft/Phi-3.5-MoE-instruct": "https://huggingface.co/microsoft/Phi-3.5-MoE-instruct/resolve/main/config.json",
28
+ }
29
+
30
+ class PhiMoEConfig(PretrainedConfig):
31
+ r"""
32
+ This is the configuration class to store the configuration of a [`PhiMoEModel`]. It is used to instantiate a Phi-MoE
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
35
+ [microsoft/Phi-3.5-MoE-instruct](https://huggingface.co/microsoft/Phi-3.5-MoE-instruct).
36
+
37
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
38
+ documentation from [`PretrainedConfig`] for more information.
39
+
40
+
41
+ Args:
42
+ vocab_size (`int`, *optional*, defaults to 32064):
43
+ Vocabulary size of the PhiMoE model. Defines the number of different tokens that can be represented by the
44
+ `inputs_ids` passed when calling [`PhiMoEModel`]
45
+ hidden_size (`int`, *optional*, defaults to 4096):
46
+ Dimension of the hidden representations.
47
+ intermediate_size (`int`, *optional*, defaults to 6400):
48
+ Dimension of the MLP representations.
49
+ num_hidden_layers (`int`, *optional*, defaults to 32):
50
+ Number of hidden layers in the Transformer encoder.
51
+ num_attention_heads (`int`, *optional*, defaults to 32):
52
+ Number of attention heads for each attention layer in the Transformer encoder.
53
+ num_key_value_heads (`int`, *optional*, defaults to 8):
54
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
55
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
56
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
57
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
58
+ by meanpooling all the original heads within that group. For more details checkout [this
59
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `8`.
60
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
61
+ The non-linear activation function (function or string) in the decoder.
62
+ max_position_embeddings (`int`, *optional*, defaults to `4096*32`):
63
+ The maximum sequence length that this model might ever be used with. Mixtral's sliding window attention
64
+ allows sequence of up to 4096*32 tokens.
65
+ initializer_range (`float`, *optional*, defaults to 0.02):
66
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
67
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
68
+ The epsilon used by the rms normalization layers.
69
+ use_cache (`bool`, *optional*, defaults to `True`):
70
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
71
+ relevant if `config.is_decoder=True`.
72
+ pad_token_id (`int`, *optional*):
73
+ The id of the padding token.
74
+ bos_token_id (`int`, *optional*, defaults to 1):
75
+ The id of the "beginning-of-sequence" token.
76
+ eos_token_id (`int`, *optional*, defaults to 2):
77
+ The id of the "end-of-sequence" token.
78
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
79
+ Whether the model's input and output word embeddings should be tied.
80
+ rope_theta (`float`, *optional*, defaults to 10000.0):
81
+ The base period of the RoPE embeddings.
82
+ rope_scaling (`dict`, *optional*):
83
+ The scaling strategy for the RoPE embeddings. If `None`, no scaling is applied. If a dictionary, it must
84
+ contain the following keys: `type`, `short_factor`, `long_factor`, `short_mscale`, `long_mscale` and
85
+ `original_max_position_embeddings`. The `type` must be `longrope`, the `short_mscale` and `long_scale` must
86
+ be numbers, the `short_factor` and `long_factor` must be lists of numbers with the same length as half of
87
+ the attention head size and the `original_max_position_embeddings` must be an integer.
88
+ sliding_window (`int`, *optional*):
89
+ Sliding window attention window size. If not specified, will default to `262144`.
90
+ attention_dropout (`float`, *optional*, defaults to 0.0):
91
+ The dropout ratio for the attention probabilities.
92
+ num_experts_per_tok (`int`, *optional*, defaults to 2):
93
+ The number of experts to root per-token, can be also interpreted as the `top-p` routing
94
+ parameter
95
+ num_local_experts (`int`, *optional*, defaults to 16):
96
+ Number of experts per Sparse MLP layer.
97
+ output_router_logits (`bool`, *optional*, defaults to `False`):
98
+ Whether or not the router logits should be returned by the model. Enabeling this will also
99
+ allow the model to output the auxiliary loss. See [here]() for more details
100
+ router_aux_loss_coef (`float`, *optional*, defaults to 0.0):
101
+ The aux loss factor for the total loss.
102
+ router_jitter_noise (`float`, *optional*, defaults to 0.01):
103
+ Amount of noise to add to the router.
104
+
105
+ ```python
106
+ >>> from transformers import PhiMoEModel, PhiMoEConfig
107
+
108
+ >>> # Initializing a Phi-3 style configuration
109
+ >>> configuration = PhiMoEConfig.from_pretrained("microsoft/Phi-3.5-MoE-instruct")
110
+
111
+ >>> # Initializing a model from the configuration
112
+ >>> model = PhiMoEModel(configuration)
113
+
114
+ >>> # Accessing the model configuration
115
+ >>> configuration = model.config
116
+ ```"""
117
+
118
+ model_type = "phimoe"
119
+ keys_to_ignore_at_inference = ["past_key_values"]
120
+
121
+ def __init__(
122
+ self,
123
+ vocab_size=32064,
124
+ hidden_size=4096,
125
+ intermediate_size=6400,
126
+ num_hidden_layers=32,
127
+ num_attention_heads=32,
128
+ num_key_value_heads=8,
129
+ hidden_act="silu",
130
+ max_position_embeddings=4096 * 32,
131
+ initializer_range=0.02,
132
+ rms_norm_eps=1e-5,
133
+ use_cache=True,
134
+ pad_token_id=None,
135
+ bos_token_id=1,
136
+ eos_token_id=2,
137
+ tie_word_embeddings=False,
138
+ rope_theta=1e6,
139
+ rope_scaling=None,
140
+ sliding_window=None,
141
+ attention_dropout=0.0,
142
+ num_experts_per_tok=2,
143
+ num_local_experts=16,
144
+ output_router_logits=False,
145
+ router_aux_loss_coef=0.001,
146
+ router_jitter_noise=0.01,
147
+ input_jitter_noise=0.0,
148
+ attention_bias = False,
149
+ lm_head_bias = False,
150
+ **kwargs,
151
+ ):
152
+ self.vocab_size = vocab_size
153
+ self.max_position_embeddings = max_position_embeddings
154
+ self.hidden_size = hidden_size
155
+ self.intermediate_size = intermediate_size
156
+ self.num_hidden_layers = num_hidden_layers
157
+ self.num_attention_heads = num_attention_heads
158
+ self.sliding_window = sliding_window
159
+ self.attention_bias = attention_bias
160
+ self.lm_head_bias = lm_head_bias
161
+ # for backward compatibility
162
+ if num_key_value_heads is None:
163
+ num_key_value_heads = num_attention_heads
164
+
165
+ self.num_key_value_heads = num_key_value_heads
166
+ self.hidden_act = hidden_act
167
+ self.initializer_range = initializer_range
168
+ self.rms_norm_eps = rms_norm_eps
169
+ self.use_cache = use_cache
170
+ self.rope_theta = rope_theta
171
+ self.attention_dropout = attention_dropout
172
+
173
+ self.num_experts_per_tok = num_experts_per_tok
174
+ self.num_local_experts = num_local_experts
175
+ self.output_router_logits = output_router_logits
176
+ self.router_aux_loss_coef = router_aux_loss_coef
177
+ self.router_jitter_noise = router_jitter_noise
178
+ self.input_jitter_noise = input_jitter_noise
179
+
180
+ self.rope_scaling = rope_scaling
181
+ self._rope_scaling_validation()
182
+
183
+ super().__init__(
184
+ pad_token_id=pad_token_id,
185
+ bos_token_id=bos_token_id,
186
+ eos_token_id=eos_token_id,
187
+ tie_word_embeddings=tie_word_embeddings,
188
+ **kwargs,
189
+ )
190
+
191
+ def _rope_scaling_validation(self):
192
+ """
193
+ Validate the `rope_scaling` configuration.
194
+ """
195
+ if self.rope_scaling is None:
196
+ return
197
+
198
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 6:
199
+ raise ValueError(
200
+ "`rope_scaling` must be a dictionary with three fields, `type`, `short_factor`, `long_factor`, "
201
+ f"`short_mscale`, `long_mscale` and `original_max_position_embeddings`, got {self.rope_scaling}"
202
+ )
203
+ rope_scaling_type = self.rope_scaling.get("type", None)
204
+ rope_scaling_short_factor = self.rope_scaling.get("short_factor", None)
205
+ rope_scaling_long_factor = self.rope_scaling.get("long_factor", None)
206
+ rope_scaling_short_mscale = self.rope_scaling.get("short_mscale", None)
207
+ rope_scaling_long_mscale = self.rope_scaling.get("long_mscale", None)
208
+ original_max_position_embeddings = self.rope_scaling.get("original_max_position_embeddings", None)
209
+ if rope_scaling_type is None or rope_scaling_type not in ["longrope"]:
210
+ raise ValueError(f"`rope_scaling`'s type field must be one of ['longrope'], got {rope_scaling_type}")
211
+ if not (
212
+ isinstance(rope_scaling_short_factor, list)
213
+ and all(isinstance(x, (int, float)) for x in rope_scaling_short_factor)
214
+ ):
215
+ raise ValueError(
216
+ f"`rope_scaling`'s short_factor field must be a list of numbers, got {rope_scaling_short_factor}"
217
+ )
218
+ if not len(rope_scaling_short_factor) == self.hidden_size // self.num_attention_heads // 2:
219
+ raise ValueError(
220
+ f"`rope_scaling`'s short_factor field must have length {self.hidden_size // self.num_attention_heads // 2}, got {len(rope_scaling_short_factor)}"
221
+ )
222
+ if not (
223
+ isinstance(rope_scaling_long_factor, list)
224
+ and all(isinstance(x, (int, float)) for x in rope_scaling_long_factor)
225
+ ):
226
+ raise ValueError(
227
+ f"`rope_scaling`'s long_factor field must be a list of numbers, got {rope_scaling_long_factor}"
228
+ )
229
+ if not len(rope_scaling_long_factor) == self.hidden_size // self.num_attention_heads // 2:
230
+ raise ValueError(
231
+ f"`rope_scaling`'s long_factor field must have length {self.hidden_size // self.num_attention_heads // 2}, got {len(rope_scaling_long_factor)}"
232
+ )
233
+ if not isinstance(rope_scaling_short_mscale, (int, float)):
234
+ raise ValueError(
235
+ f"`rope_scaling`'s short_mscale field must be a number, got {rope_scaling_short_mscale}"
236
+ )
237
+ if not isinstance(rope_scaling_long_mscale, (int, float)):
238
+ raise ValueError(
239
+ f"`rope_scaling`'s long_mscale field must be a number, got {rope_scaling_long_mscale}"
240
+ )
241
+ if not isinstance(original_max_position_embeddings, int):
242
+ raise ValueError(
243
+ f"`rope_scaling`'s original_max_position_embeddings field must be an integer, got {original_max_position_embeddings}"
244
+ )