rkumar1999 commited on
Commit
d8df462
·
verified ·
1 Parent(s): d8fdac7

Create configuration_slimmoe.py.

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