IlyasMoutawwakil HF Staff commited on
Commit
8b07c96
·
verified ·
1 Parent(s): 71410ec

Mirror from katuni4ka/phi-3.5-moe-tiny-random

Browse files
README.md ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ pipeline_tag: text-generation
4
+ ---
added_tokens.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "<|assistant|>": 32001,
3
+ "<|endoftext|>": 32000,
4
+ "<|end|>": 32007,
5
+ "<|placeholder1|>": 32002,
6
+ "<|placeholder2|>": 32003,
7
+ "<|placeholder3|>": 32004,
8
+ "<|placeholder4|>": 32005,
9
+ "<|placeholder5|>": 32008,
10
+ "<|placeholder6|>": 32009,
11
+ "<|system|>": 32006,
12
+ "<|user|>": 32010
13
+ }
config.json ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "microsoft/Phi-3.5-MoE-instruct",
3
+ "architectures": [
4
+ "PhiMoEForCausalLM"
5
+ ],
6
+ "attention_bias": true,
7
+ "attention_dropout": 0.0,
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_phimoe.PhiMoEConfig",
10
+ "AutoModelForCausalLM": "modeling_phimoe.PhiMoEForCausalLM"
11
+ },
12
+ "bos_token_id": 1,
13
+ "eos_token_id": 32000,
14
+ "hidden_act": "silu",
15
+ "hidden_dropout": 0.0,
16
+ "hidden_size": 16,
17
+ "initializer_range": 0.02,
18
+ "input_jitter_noise": 0.01,
19
+ "intermediate_size": 32,
20
+ "lm_head_bias": true,
21
+ "max_position_embeddings": 131072,
22
+ "model_type": "phimoe",
23
+ "num_attention_heads": 4,
24
+ "num_experts_per_tok": 2,
25
+ "num_hidden_layers": 2,
26
+ "num_key_value_heads": 4,
27
+ "num_local_experts": 16,
28
+ "original_max_position_embeddings": 4096,
29
+ "output_router_logits": false,
30
+ "rms_norm_eps": 1e-05,
31
+ "rope_scaling": {
32
+ "long_factor": [
33
+ 1.0299,
34
+ 1.0499
35
+ ],
36
+ "long_mscale": 1.243163121016122,
37
+ "original_max_position_embeddings": 4096,
38
+ "short_factor": [
39
+ 1.05,
40
+ 1.05
41
+ ],
42
+ "short_mscale": 1.243163121016122,
43
+ "type": "longrope"
44
+ },
45
+ "rope_theta": 10000.0,
46
+ "router_aux_loss_coef": 0.0,
47
+ "router_jitter_noise": 0.01,
48
+ "sliding_window": 131072,
49
+ "tie_word_embeddings": false,
50
+ "torch_dtype": "bfloat16",
51
+ "transformers_version": "4.44.0",
52
+ "use_cache": true,
53
+ "vocab_size": 32064
54
+ }
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
+ )
generation_config.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": [
5
+ 32000,
6
+ 32001,
7
+ 32007
8
+ ],
9
+ "pad_token_id": 32000,
10
+ "transformers_version": "4.44.0"
11
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:274d3c66b5dde81a176acc899de3ec6a63e93d14b1c4c5bd8ff9f694c1a4d9f3
3
+ size 2234992
modeling_phimoe.py ADDED
@@ -0,0 +1,1807 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 PhiMoE model."""
17
+ import inspect
18
+ import math
19
+ import warnings
20
+ from typing import List, Optional, Tuple, Union
21
+
22
+ import torch
23
+ import torch.nn.functional as F
24
+ import torch.utils.checkpoint
25
+ from torch import nn
26
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
27
+
28
+ from transformers.activations import ACT2FN
29
+ from transformers.cache_utils import Cache, DynamicCache
30
+ from transformers.modeling_attn_mask_utils import (
31
+ _prepare_4d_causal_attention_mask,
32
+ _prepare_4d_causal_attention_mask_for_sdpa,
33
+ )
34
+ from transformers.modeling_outputs import (
35
+ MoeCausalLMOutputWithPast,
36
+ MoeModelOutputWithPast,
37
+ SequenceClassifierOutputWithPast,
38
+ )
39
+ from transformers.modeling_utils import PreTrainedModel
40
+ from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_13
41
+ from transformers.utils import (
42
+ add_start_docstrings,
43
+ add_start_docstrings_to_model_forward,
44
+ is_flash_attn_2_available,
45
+ is_flash_attn_greater_or_equal_2_10,
46
+ logging,
47
+ replace_return_docstrings,
48
+ )
49
+ from transformers.utils.import_utils import is_torch_fx_available
50
+ from .configuration_phimoe import PhiMoEConfig
51
+
52
+ from einops import rearrange
53
+
54
+ logger = logging.get_logger(__name__)
55
+ try:
56
+ from flash_attn.layers.rotary import RotaryEmbedding as FlashRotaryEmbedding
57
+
58
+
59
+ if is_flash_attn_2_available():
60
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
61
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
62
+
63
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
64
+ except ImportError as error:
65
+ logger.warning(
66
+ f"`flash-attention` package not found, consider installing for better performance: {error}."
67
+ )
68
+
69
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
70
+ # It means that the function will not be traced through and simply appear as a node in the graph.
71
+ if is_torch_fx_available():
72
+ if not is_torch_greater_or_equal_than_1_13:
73
+ import torch.fx
74
+
75
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
76
+
77
+
78
+
79
+
80
+ _CONFIG_FOR_DOC = "PhiMoEConfig"
81
+
82
+
83
+ def load_balancing_loss_func(
84
+ gate_logits: torch.Tensor, num_experts: torch.Tensor = None, top_k=2, attention_mask: Optional[torch.Tensor] = None
85
+ ) -> float:
86
+ r"""
87
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
88
+
89
+ See Switch Transformer (https://arxiv.org/abs/2101.03961) for more details. This function implements the loss
90
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
91
+ experts is too unbalanced.
92
+
93
+ Args:
94
+ gate_logits (Union[`torch.Tensor`, Tuple[torch.Tensor]):
95
+ Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
96
+ shape [batch_size X sequence_length, num_experts].
97
+ attention_mask (`torch.Tensor`, None):
98
+ The attention_mask used in forward function
99
+ shape [batch_size X sequence_length] if not None.
100
+ num_experts (`int`, *optional*):
101
+ Number of experts
102
+
103
+ Returns:
104
+ The auxiliary loss.
105
+ """
106
+ if gate_logits is None or not isinstance(gate_logits, tuple):
107
+ return 0
108
+
109
+ if isinstance(gate_logits, tuple):
110
+ compute_device = gate_logits[0].device
111
+ concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
112
+
113
+ routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
114
+
115
+ _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
116
+
117
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
118
+
119
+ if attention_mask is None:
120
+ # Compute the percentage of tokens routed to each experts
121
+ tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
122
+
123
+ # Compute the average probability of routing to these experts
124
+ router_prob_per_expert = torch.mean(routing_weights, dim=0)
125
+ else:
126
+ batch_size, sequence_length = attention_mask.shape
127
+ num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
128
+
129
+ # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
130
+ expert_attention_mask = (
131
+ attention_mask[None, :, :, None, None]
132
+ .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
133
+ .reshape(-1, top_k, num_experts)
134
+ .to(compute_device)
135
+ )
136
+
137
+ # Compute the percentage of tokens routed to each experts
138
+ tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
139
+ expert_attention_mask, dim=0
140
+ )
141
+
142
+ # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
143
+ router_per_expert_attention_mask = (
144
+ attention_mask[None, :, :, None]
145
+ .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
146
+ .reshape(-1, num_experts)
147
+ .to(compute_device)
148
+ )
149
+
150
+ # Compute the average probability of routing to these experts
151
+ router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
152
+ router_per_expert_attention_mask, dim=0
153
+ )
154
+
155
+ overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
156
+ return overall_loss * num_experts
157
+
158
+
159
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
160
+ def _get_unpad_data(attention_mask):
161
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
162
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
163
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
164
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
165
+ return (
166
+ indices,
167
+ cu_seqlens,
168
+ max_seqlen_in_batch,
169
+ )
170
+
171
+
172
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->PhiMoE
173
+ ##https://dl.acm.org/doi/pdf/10.5555/3454287.3455397 The following is the implementation of layernorm
174
+
175
+
176
+ class PhiMoERotaryEmbedding(nn.Module):
177
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
178
+ super().__init__()
179
+
180
+ self.dim = dim
181
+ self.max_position_embeddings = max_position_embeddings
182
+ self.base = base
183
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
184
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
185
+
186
+ # Build here to make `torch.jit.trace` work.
187
+ self._set_cos_sin_cache(
188
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
189
+ )
190
+
191
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
192
+ self.max_seq_len_cached = seq_len
193
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
194
+
195
+ freqs = torch.outer(t, self.inv_freq)
196
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
197
+ emb = torch.cat((freqs, freqs), dim=-1)
198
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
199
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
200
+
201
+ def forward(self, x, seq_len=None):
202
+ # x: [bs, num_attention_heads, seq_len, head_size]
203
+ if seq_len > self.max_seq_len_cached:
204
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
205
+
206
+ return (
207
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
208
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
209
+ )
210
+
211
+
212
+ class Phi3LongRoPEScaledRotaryEmbedding(nn.Module):
213
+
214
+ def __init__(self, dim, config):
215
+ super().__init__()
216
+ self.dim = dim
217
+ self.max_position_embeddings = config.max_position_embeddings
218
+ self.base = config.rope_theta
219
+ self.short_factor = config.rope_scaling["short_factor"]
220
+ self.long_factor = config.rope_scaling["long_factor"]
221
+ self.short_mscale = config.rope_scaling["short_mscale"]
222
+ self.long_mscale = config.rope_scaling["long_mscale"]
223
+ self.original_max_position_embeddings = config.rope_scaling["original_max_position_embeddings"]
224
+
225
+ def forward(self, x, seq_len=None):
226
+ if seq_len is None:
227
+ seq_len = x.shape[-2]
228
+
229
+ if seq_len > self.original_max_position_embeddings:
230
+ rescale_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=x.device)
231
+ mscale = self.long_mscale
232
+ else:
233
+ rescale_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=x.device)
234
+ mscale = self.short_mscale
235
+ assert rescale_factors.shape == (self.dim // 2, ), \
236
+ f"misaligned shape for LongRoPE rescale factors: {rescale_factors.shape}"
237
+
238
+ inv_freq = 1.0 / (rescale_factors * (self.base ** (torch.arange(0, self.dim, 2).float().to(x.device) / self.dim)))
239
+
240
+ t = torch.arange(seq_len, device=x.device, dtype=torch.float32)
241
+ freqs = torch.outer(t, inv_freq)
242
+
243
+ emb = torch.cat((freqs, freqs), dim=-1)
244
+ return (emb.cos() * mscale).to(x.dtype), (emb.sin() * mscale).to(x.dtype)
245
+
246
+
247
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
248
+ def rotate_half(x):
249
+ """Rotates half the hidden dims of the input."""
250
+ x1 = x[..., : x.shape[-1] // 2]
251
+ x2 = x[..., x.shape[-1] // 2 :]
252
+ return torch.cat((-x2, x1), dim=-1)
253
+
254
+
255
+
256
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
257
+ """Applies Rotary Position Embedding to the query and key tensors.
258
+
259
+ Args:
260
+ q (`torch.Tensor`): The query tensor.
261
+ k (`torch.Tensor`): The key tensor.
262
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
263
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
264
+ position_ids (`torch.Tensor`):
265
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
266
+ used to pass offsetted position ids when working with a KV-cache.
267
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
268
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
269
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
270
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
271
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
272
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
273
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
274
+ Returns:
275
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
276
+ """
277
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
278
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
279
+ q_embed = (q * cos) + (rotate_half(q) * sin)
280
+ k_embed = (k * cos) + (rotate_half(k) * sin)
281
+ return q_embed, k_embed
282
+
283
+
284
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
285
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
286
+ """
287
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
288
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
289
+ """
290
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
291
+ if n_rep == 1:
292
+ return hidden_states
293
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
294
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
295
+
296
+
297
+
298
+ class PhiMoEAttention(nn.Module):
299
+ """
300
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
301
+ and "Generating Long Sequences with Sparse Transformers".
302
+ """
303
+
304
+ def __init__(self, config: PhiMoEConfig, layer_idx: Optional[int] = None):
305
+ super().__init__()
306
+ self.config = config
307
+ self.layer_idx = layer_idx
308
+ if layer_idx is None:
309
+ logger.warning_once(
310
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
311
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
312
+ "when creating this class."
313
+ )
314
+
315
+ self.hidden_size = config.hidden_size
316
+ self.num_heads = config.num_attention_heads
317
+ self.head_dim = self.hidden_size // self.num_heads
318
+ self.num_key_value_heads = config.num_key_value_heads
319
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
320
+ self.max_position_embeddings = config.max_position_embeddings
321
+ self.rope_theta = config.rope_theta
322
+ self.is_causal = True
323
+ self.attention_dropout = config.attention_dropout
324
+
325
+ if (self.head_dim * self.num_heads) != self.hidden_size:
326
+ raise ValueError(
327
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
328
+ f" and `num_heads`: {self.num_heads})."
329
+ )
330
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=self.config.attention_bias)
331
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=self.config.attention_bias)
332
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=self.config.attention_bias)
333
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=self.config.attention_bias)
334
+
335
+ if getattr(config, 'rope_scaling', None) is None:
336
+ self.rotary_emb = PhiMoERotaryEmbedding(
337
+ self.head_dim,
338
+ max_position_embeddings=self.max_position_embeddings,
339
+ base=self.rope_theta,
340
+ )
341
+ else:
342
+ scaling_type = self.config.rope_scaling["type"]
343
+ if scaling_type == "longrope":
344
+ self.rotary_emb = Phi3LongRoPEScaledRotaryEmbedding(self.head_dim, self.config)
345
+ else:
346
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
347
+
348
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
349
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
350
+
351
+ def forward(
352
+ self,
353
+ hidden_states: torch.Tensor,
354
+ attention_mask: Optional[torch.Tensor] = None,
355
+ position_ids: Optional[torch.LongTensor] = None,
356
+ past_key_value: Optional[Cache] = None,
357
+ output_attentions: bool = False,
358
+ use_cache: bool = False,
359
+ **kwargs,
360
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
361
+ if "padding_mask" in kwargs:
362
+ warnings.warn(
363
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
364
+ )
365
+ bsz, q_len, _ = hidden_states.size()
366
+
367
+ query_states = self.q_proj(hidden_states)
368
+ key_states = self.k_proj(hidden_states)
369
+ value_states = self.v_proj(hidden_states)
370
+
371
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
372
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
373
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
374
+
375
+ kv_seq_len = key_states.shape[-2]
376
+ if past_key_value is not None:
377
+ if self.layer_idx is None:
378
+ raise ValueError(
379
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
380
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
381
+ "with a layer index."
382
+ )
383
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
384
+
385
+ # print ("before apply rotary pos_emb", len(kv_seq_len),torch.norm(value_states).items(),\
386
+ # torch.norm(query_states).items(), torch.norm(key_states).items(), position_ids)
387
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
388
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
389
+
390
+ # print ('after pos emb', torch.norm(query_states).item(), torch.norm(key_states).items())
391
+ if past_key_value is not None:
392
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
393
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
394
+
395
+ # repeat k/v heads if n_kv_heads < n_heads
396
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
397
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
398
+
399
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
400
+
401
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
402
+ raise ValueError(
403
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
404
+ f" {attn_weights.size()}"
405
+ )
406
+
407
+ if attention_mask is not None:
408
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
409
+ raise ValueError(
410
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
411
+ )
412
+
413
+ attn_weights = attn_weights + attention_mask
414
+
415
+ # upcast attention to fp32
416
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
417
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
418
+ attn_output = torch.matmul(attn_weights, value_states)
419
+
420
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
421
+ raise ValueError(
422
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
423
+ f" {attn_output.size()}"
424
+ )
425
+
426
+ attn_output = attn_output.transpose(1, 2).contiguous()
427
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
428
+
429
+ attn_output = self.o_proj(attn_output)
430
+
431
+ if not output_attentions:
432
+ attn_weights = None
433
+
434
+ return attn_output, attn_weights, past_key_value
435
+
436
+
437
+
438
+ class PhiMoEFlashAttention2(PhiMoEAttention):
439
+ """
440
+ PhiMoE flash attention module. This module inherits from `PhiMoEAttention` as the weights of the module stays
441
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
442
+ flash attention and deal with padding tokens in case the input contains any of them.
443
+ """
444
+
445
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
446
+ def __init__(self, *args, **kwargs):
447
+ super().__init__(*args, **kwargs)
448
+
449
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
450
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
451
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
452
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
453
+
454
+ def forward(
455
+ self,
456
+ hidden_states: torch.Tensor,
457
+ attention_mask: Optional[torch.Tensor] = None,
458
+ position_ids: Optional[torch.LongTensor] = None,
459
+ past_key_value: Optional[Cache] = None,
460
+ output_attentions: bool = False,
461
+ use_cache: bool = False,
462
+ **kwargs,
463
+ ):
464
+ if "padding_mask" in kwargs:
465
+ warnings.warn(
466
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
467
+ )
468
+
469
+ # overwrite attention_mask with padding_mask
470
+ attention_mask = kwargs.pop("padding_mask")
471
+ bsz, q_len, _ = hidden_states.size()
472
+
473
+ query_states = self.q_proj(hidden_states)
474
+ key_states = self.k_proj(hidden_states)
475
+ value_states = self.v_proj(hidden_states)
476
+
477
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
478
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
479
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
480
+
481
+ kv_seq_len = key_states.shape[-2]
482
+ if past_key_value is not None:
483
+ if self.layer_idx is None:
484
+ raise ValueError(
485
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
486
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
487
+ "with a layer index."
488
+ )
489
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
490
+
491
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
492
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item() + 1)
493
+ cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
494
+
495
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
496
+
497
+ use_sliding_windows = (
498
+ _flash_supports_window_size
499
+ and getattr(self.config, "sliding_window", None) is not None
500
+ and kv_seq_len > self.config.sliding_window
501
+ )
502
+
503
+ if not _flash_supports_window_size:
504
+ logger.warning_once(
505
+ "The current flash attention version does not support sliding window attention, for a more memory efficient implementation"
506
+ " make sure to upgrade flash-attn library."
507
+ )
508
+
509
+ if past_key_value is not None:
510
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
511
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
512
+ if (
513
+ getattr(self.config, "sliding_window", None) is not None
514
+ and kv_seq_len > self.config.sliding_window
515
+ and cache_has_contents
516
+ ):
517
+ slicing_tokens = 1 - self.config.sliding_window
518
+
519
+ past_key = past_key_value[self.layer_idx][0]
520
+ past_value = past_key_value[self.layer_idx][1]
521
+
522
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
523
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
524
+
525
+ if past_key.shape[-2] != self.config.sliding_window - 1:
526
+ raise ValueError(
527
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
528
+ f" {past_key.shape}"
529
+ )
530
+
531
+ if attention_mask is not None:
532
+ attention_mask = attention_mask[:, slicing_tokens:]
533
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
534
+
535
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
536
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
537
+
538
+ # repeat k/v heads if n_kv_heads < n_heads
539
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
540
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
541
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
542
+
543
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
544
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
545
+ # cast them back in float16 just to be sure everything works as expected.
546
+ input_dtype = query_states.dtype
547
+ if input_dtype == torch.float32:
548
+ if torch.is_autocast_enabled():
549
+ target_dtype = torch.get_autocast_gpu_dtype()
550
+ # Handle the case where the model is quantized
551
+ elif hasattr(self.config, "_pre_quantization_dtype"):
552
+ target_dtype = self.config._pre_quantization_dtype
553
+ else:
554
+ target_dtype = self.q_proj.weight.dtype
555
+
556
+ logger.warning_once(
557
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
558
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
559
+ f" {target_dtype}."
560
+ )
561
+
562
+ query_states = query_states.to(target_dtype)
563
+ key_states = key_states.to(target_dtype)
564
+ value_states = value_states.to(target_dtype)
565
+
566
+ # Reashape to the expected shape for Flash Attention
567
+ query_states = query_states.transpose(1, 2)
568
+ key_states = key_states.transpose(1, 2)
569
+ value_states = value_states.transpose(1, 2)
570
+
571
+ attn_output = self._flash_attention_forward(
572
+ query_states,
573
+ key_states,
574
+ value_states,
575
+ attention_mask,
576
+ q_len,
577
+ dropout=dropout_rate,
578
+ use_sliding_windows=use_sliding_windows,
579
+ )
580
+
581
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
582
+ attn_output = self.o_proj(attn_output)
583
+
584
+ if not output_attentions:
585
+ attn_weights = None
586
+
587
+ return attn_output, attn_weights, past_key_value
588
+
589
+ def _flash_attention_forward(
590
+ self,
591
+ query_states,
592
+ key_states,
593
+ value_states,
594
+ attention_mask,
595
+ query_length,
596
+ dropout=0.0,
597
+ softmax_scale=None,
598
+ use_sliding_windows=False,
599
+ ):
600
+ """
601
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
602
+ first unpad the input, then computes the attention scores and pad the final attention scores.
603
+
604
+ Args:
605
+ query_states (`torch.Tensor`):
606
+ Input query states to be passed to Flash Attention API
607
+ key_states (`torch.Tensor`):
608
+ Input key states to be passed to Flash Attention API
609
+ value_states (`torch.Tensor`):
610
+ Input value states to be passed to Flash Attention API
611
+ attention_mask (`torch.Tensor`):
612
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
613
+ position of padding tokens and 1 for the position of non-padding tokens.
614
+ dropout (`float`):
615
+ Attention dropout
616
+ softmax_scale (`float`, *optional*):
617
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
618
+ use_sliding_windows (`bool`, *optional*):
619
+ Whether to activate sliding window attention.
620
+ """
621
+ if not self._flash_attn_uses_top_left_mask:
622
+ causal = self.is_causal
623
+ else:
624
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
625
+ causal = self.is_causal and query_length != 1
626
+
627
+ # Contains at least one padding token in the sequence
628
+ if attention_mask is not None:
629
+ batch_size = query_states.shape[0]
630
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
631
+ query_states, key_states, value_states, attention_mask, query_length
632
+ )
633
+
634
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
635
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
636
+
637
+ if not use_sliding_windows:
638
+ attn_output_unpad = flash_attn_varlen_func(
639
+ query_states,
640
+ key_states,
641
+ value_states,
642
+ cu_seqlens_q=cu_seqlens_q,
643
+ cu_seqlens_k=cu_seqlens_k,
644
+ max_seqlen_q=max_seqlen_in_batch_q,
645
+ max_seqlen_k=max_seqlen_in_batch_k,
646
+ dropout_p=dropout,
647
+ softmax_scale=softmax_scale,
648
+ causal=causal,
649
+ )
650
+ else:
651
+ attn_output_unpad = flash_attn_varlen_func(
652
+ query_states,
653
+ key_states,
654
+ value_states,
655
+ cu_seqlens_q=cu_seqlens_q,
656
+ cu_seqlens_k=cu_seqlens_k,
657
+ max_seqlen_q=max_seqlen_in_batch_q,
658
+ max_seqlen_k=max_seqlen_in_batch_k,
659
+ dropout_p=dropout,
660
+ softmax_scale=softmax_scale,
661
+ causal=causal,
662
+ window_size=(self.config.sliding_window, 0),
663
+ )
664
+
665
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
666
+ else:
667
+ if not use_sliding_windows:
668
+ attn_output = flash_attn_func(
669
+ query_states,
670
+ key_states,
671
+ value_states,
672
+ dropout,
673
+ softmax_scale=softmax_scale,
674
+ causal=causal,
675
+ )
676
+ else:
677
+ attn_output = flash_attn_func(
678
+ query_states,
679
+ key_states,
680
+ value_states,
681
+ dropout,
682
+ softmax_scale=softmax_scale,
683
+ causal=causal,
684
+ window_size=(self.config.sliding_window, 0),
685
+ )
686
+
687
+ return attn_output
688
+
689
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
690
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
691
+
692
+ # On the first iteration we need to properly re-create the padding mask
693
+ # by slicing it on the proper place
694
+ if kv_seq_len != attention_mask.shape[-1]:
695
+ attention_mask_num_tokens = attention_mask.shape[-1]
696
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
697
+
698
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
699
+
700
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
701
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
702
+
703
+ if query_length == kv_seq_len:
704
+ query_layer = index_first_axis(
705
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
706
+ )
707
+ cu_seqlens_q = cu_seqlens_k
708
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
709
+ indices_q = indices_k
710
+ elif query_length == 1:
711
+ max_seqlen_in_batch_q = 1
712
+ cu_seqlens_q = torch.arange(
713
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
714
+ ) # There is a memcpy here, that is very bad.
715
+ indices_q = cu_seqlens_q[:-1]
716
+ query_layer = query_layer.squeeze(1)
717
+ else:
718
+ # The -q_len: slice assumes left padding.
719
+ attention_mask = attention_mask[:, -query_length:]
720
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
721
+
722
+ return (
723
+ query_layer,
724
+ key_layer,
725
+ value_layer,
726
+ indices_q,
727
+ (cu_seqlens_q, cu_seqlens_k),
728
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
729
+ )
730
+
731
+
732
+
733
+ class PhiMoESdpaAttention(PhiMoEAttention):
734
+ """
735
+ PhiMoE attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
736
+ `PhiMoEAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
737
+ SDPA API.
738
+ """
739
+
740
+ # Adapted from PhiMoEAttention.forward
741
+ def forward(
742
+ self,
743
+ hidden_states: torch.Tensor,
744
+ attention_mask: Optional[torch.Tensor] = None,
745
+ position_ids: Optional[torch.LongTensor] = None,
746
+ past_key_value: Optional[Cache] = None,
747
+ output_attentions: bool = False,
748
+ use_cache: bool = False,
749
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
750
+ if output_attentions:
751
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
752
+ logger.warning_once(
753
+ "PhiMoEModel is using PhiMoESdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
754
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
755
+ )
756
+ return super().forward(
757
+ hidden_states=hidden_states,
758
+ attention_mask=attention_mask,
759
+ position_ids=position_ids,
760
+ past_key_value=past_key_value,
761
+ output_attentions=output_attentions,
762
+ use_cache=use_cache,
763
+ )
764
+
765
+ bsz, q_len, _ = hidden_states.size()
766
+
767
+ query_states = self.q_proj(hidden_states)
768
+ key_states = self.k_proj(hidden_states)
769
+ value_states = self.v_proj(hidden_states)
770
+
771
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
772
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
773
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
774
+
775
+ kv_seq_len = key_states.shape[-2]
776
+ if past_key_value is not None:
777
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
778
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
779
+
780
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
781
+
782
+ if past_key_value is not None:
783
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
784
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
785
+
786
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
787
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
788
+
789
+ if attention_mask is not None:
790
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
791
+ raise ValueError(
792
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
793
+ )
794
+
795
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
796
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
797
+ if query_states.device.type == "cuda" and attention_mask is not None:
798
+ query_states = query_states.contiguous()
799
+ key_states = key_states.contiguous()
800
+ value_states = value_states.contiguous()
801
+
802
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
803
+ query_states,
804
+ key_states,
805
+ value_states,
806
+ attn_mask=attention_mask,
807
+ dropout_p=self.attention_dropout if self.training else 0.0,
808
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
809
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
810
+ )
811
+
812
+ attn_output = attn_output.transpose(1, 2).contiguous()
813
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
814
+
815
+ attn_output = self.o_proj(attn_output)
816
+
817
+ return attn_output, None, past_key_value
818
+
819
+
820
+ PHIMOE_ATTENTION_CLASSES = {
821
+ "eager": PhiMoEAttention,
822
+ "flash_attention_2": PhiMoEFlashAttention2,
823
+ "sdpa": PhiMoESdpaAttention,
824
+ }
825
+
826
+
827
+ class PhiMoEBlockSparseTop2MLP(nn.Module):
828
+ def __init__(self, config: PhiMoEConfig):
829
+ super().__init__()
830
+ self.ffn_dim = config.intermediate_size
831
+ self.hidden_dim = config.hidden_size
832
+
833
+ self.w1 = nn.Linear(self.hidden_dim, self.ffn_dim, bias=False)
834
+ self.w2 = nn.Linear(self.ffn_dim, self.hidden_dim, bias=False)
835
+ self.w3 = nn.Linear(self.hidden_dim, self.ffn_dim, bias=False)
836
+
837
+ self.act_fn = ACT2FN[config.hidden_act]
838
+
839
+ def forward(self, hidden_states):
840
+ current_hidden_states = self.act_fn(self.w1(hidden_states)) * self.w3(hidden_states)
841
+ current_hidden_states = self.w2(current_hidden_states)
842
+ return current_hidden_states
843
+
844
+
845
+ class PhiMoEBLockSparseTop2MLP(PhiMoEBlockSparseTop2MLP):
846
+ def __init__(self, *args, **kwargs):
847
+ logger.warning_once(
848
+ "PhiMoEBLockSparseTop2MLP is deprecated by PhiMoEBlockSparseTop2MLP and will be removed in v4.40."
849
+ )
850
+ super().__init__(*args, **kwargs)
851
+
852
+
853
+ class mp(torch.autograd.Function):
854
+ @staticmethod
855
+ def forward(
856
+ ctx,
857
+ scores: torch.Tensor,
858
+ multiplier: torch.Tensor,
859
+ selected_experts: torch.Tensor,
860
+ masked_gates: torch.Tensor,
861
+ mask_for_one: torch.Tensor,
862
+ ):
863
+ ctx.save_for_backward(multiplier, selected_experts, masked_gates)
864
+ return multiplier * mask_for_one
865
+
866
+ @staticmethod
867
+ def backward(
868
+ ctx,
869
+ grad_at_output: torch.Tensor,
870
+ ):
871
+ multiplier, selected_experts, masked_gates = ctx.saved_tensors
872
+
873
+ grad_at_output = grad_at_output * multiplier
874
+
875
+ grad_at_scores_expaned = masked_gates * grad_at_output.mul(-1)
876
+ grad_at_scores_expaned.scatter_add_(
877
+ dim=-1,
878
+ index=selected_experts,
879
+ src=grad_at_output,
880
+ )
881
+
882
+ return (
883
+ grad_at_scores_expaned,
884
+ None,
885
+ None,
886
+ None,
887
+ None,
888
+ )
889
+
890
+ def sparsemixer(scores, top_k, jitter_eps, training):
891
+ assert top_k == 2
892
+
893
+ ################ first expert ################
894
+
895
+ with torch.no_grad():
896
+ # compute mask for sparsity
897
+ mask_logits_threshold, max_ind = scores.max(dim=-1, keepdim=True)
898
+ factor = scores.abs().clamp(min=mask_logits_threshold)
899
+ mask_logits_threshold = (
900
+ (mask_logits_threshold - scores) / factor
901
+ ) > (2 * jitter_eps)
902
+
903
+ # apply mask
904
+ masked_gates = scores.masked_fill(mask_logits_threshold, float('-inf'))
905
+ if training:
906
+ selected_experts = (
907
+ masked_gates - torch.empty_like(masked_gates, memory_format=torch.legacy_contiguous_format).exponential_().log()
908
+ ).max(dim=-1)[1].unsqueeze(-1) # gumbel sampling, more robust than than the multinomial method
909
+ else:
910
+ selected_experts = max_ind
911
+
912
+ # compute scores for gradients
913
+ masked_gates = torch.softmax(masked_gates, dim=-1)
914
+ multiplier_o = masked_gates.gather(dim=-1, index=selected_experts)
915
+
916
+ if training:
917
+ # compute midpoint mask
918
+ max_scores, max_ind = masked_gates.max(dim=-1, keepdim=True)
919
+ mask_for_one = torch.logical_or(
920
+ selected_experts == max_ind,
921
+ torch.rand_like(max_scores) > 0.75 # Heun's third-order method: f(x) - f(0) = .25 f'(x) + .75 f'(x/3.)
922
+ )
923
+ # 1 -> 1.0 & 0 -> 1./3: lambda x: (x + 0.5) / 1.5
924
+ mask_for_one = torch.add(0.3333, mask_for_one, alpha=0.6667).type_as(masked_gates)
925
+
926
+ multiplier = mp.apply(
927
+ scores,
928
+ multiplier_o,
929
+ selected_experts,
930
+ masked_gates,
931
+ mask_for_one,
932
+ )
933
+ else:
934
+ multiplier = multiplier_o
935
+
936
+ # masked out first expert
937
+ masked_scores = torch.scatter(
938
+ scores,
939
+ -1,
940
+ selected_experts,
941
+ float('-inf'),
942
+ )
943
+ with torch.no_grad():
944
+ # compute mask for sparsity
945
+ mask_logits_threshold, max_ind = masked_scores.max(dim=-1, keepdim=True)
946
+ factor = scores.abs().clamp(min=mask_logits_threshold)
947
+ mask_logits_threshold = (
948
+ (mask_logits_threshold - scores) / factor
949
+ ) > (2 * jitter_eps)
950
+
951
+ # apply mask
952
+ masked_gates_top2 = masked_scores.masked_fill(mask_logits_threshold, float('-inf'))
953
+ if training:
954
+ selected_experts_top2 = (
955
+ masked_gates_top2 - torch.empty_like(masked_gates_top2, memory_format=torch.legacy_contiguous_format).exponential_().log()
956
+ ).max(dim=-1)[1].unsqueeze(-1) # gumbel sampling, more robust than than the multinomial method
957
+ else:
958
+ selected_experts_top2 = max_ind
959
+ # compute scores for gradients
960
+ masked_gates_top2 = torch.softmax(masked_gates_top2, dim=-1)
961
+ multiplier_top2_o = masked_gates_top2.gather(dim=-1, index=selected_experts_top2)
962
+
963
+ if training:
964
+ # compute midpoint mask
965
+ max_scores, max_ind = masked_gates_top2.max(dim=-1, keepdim=True)
966
+ mask_for_one_top2 = torch.logical_or(
967
+ selected_experts_top2 == max_ind,
968
+ torch.rand_like(max_scores).uniform_() > 0.75 # Heun's third-order method: f(x) - f(0) = .25 f'(x) + .75 f'(x/3.)
969
+ )
970
+ # 1 -> 1.0 & 0 -> 1./3: lambda x: (x + 0.5) / 1.5
971
+ mask_for_one_top2 = torch.add(0.3333, mask_for_one_top2, alpha=0.6667).type_as(masked_gates_top2)
972
+
973
+ multiplier_top2 = mp.apply(
974
+ scores,
975
+ multiplier_top2_o,
976
+ selected_experts_top2,
977
+ masked_gates_top2,
978
+ mask_for_one_top2,
979
+ )
980
+ else:
981
+ multiplier_top2 = multiplier_top2_o
982
+
983
+ multiplier = torch.concat((multiplier, multiplier_top2), dim=-1)
984
+ selected_experts = torch.concat((selected_experts, selected_experts_top2), dim=-1)
985
+
986
+ return (
987
+ multiplier,
988
+ selected_experts,
989
+ )
990
+
991
+ iterations = 0
992
+ class PhiMoESparseMoeBlock(nn.Module):
993
+ """
994
+ This implementation is
995
+ strictly equivalent to standard MoE with full capacity (no
996
+ dropped tokens). It's faster since it formulates MoE operations
997
+ in terms of block-sparse operations to accomodate imbalanced
998
+ assignments of tokens to experts, whereas standard MoE either
999
+ (1) drop tokens at the cost of reduced performance or (2) set
1000
+ capacity factor to number of experts and thus waste computation
1001
+ and memory on padding.
1002
+ """
1003
+
1004
+ def __init__(self, config):
1005
+ super().__init__()
1006
+ self.hidden_dim = config.hidden_size
1007
+ self.ffn_dim = config.intermediate_size
1008
+ self.num_experts = config.num_local_experts
1009
+ self.top_k = config.num_experts_per_tok
1010
+ global iterations
1011
+ iterations +=1
1012
+ self.iter = iterations
1013
+ # gating
1014
+ self.gate = nn.Linear(self.hidden_dim, self.num_experts, bias=False)
1015
+
1016
+ self.experts = nn.ModuleList([PhiMoEBlockSparseTop2MLP(config) for _ in range(self.num_experts)])
1017
+
1018
+ # Jitter parameters
1019
+ self.router_jitter_noise = config.router_jitter_noise
1020
+ self.input_jitter_noise = config.input_jitter_noise
1021
+
1022
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
1023
+ """ """
1024
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
1025
+ if self.training and self.input_jitter_noise > 0:
1026
+ hidden_states *= torch.empty_like(hidden_states).uniform_(1.0 - self.input_jitter_noise, 1.0 + self.input_jitter_noise)
1027
+ hidden_states = hidden_states.view(-1, hidden_dim)
1028
+ # router_logits: (batch * sequence_length, n_experts)
1029
+ # print ( 'moe', self.iter, torch.norm(hidden_states).item())
1030
+ router_logits = self.gate(hidden_states)
1031
+
1032
+ routing_weights, selected_experts = sparsemixer(
1033
+ router_logits,
1034
+ top_k=2,
1035
+ jitter_eps=self.router_jitter_noise,
1036
+ training=self.training,
1037
+ )
1038
+
1039
+ final_hidden_states = torch.zeros(
1040
+ (batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
1041
+ )
1042
+
1043
+ # One hot encode the selected experts to create an expert mask
1044
+ # this will be used to easily index which expert is going to be sollicitated
1045
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_experts).permute(2, 1, 0)
1046
+
1047
+ # Loop over all available experts in the model and perform the computation on each expert
1048
+ for expert_idx in range(self.num_experts):
1049
+ expert_layer = self.experts[expert_idx]
1050
+ idx, top_x = torch.where(expert_mask[expert_idx])
1051
+
1052
+ if top_x.shape[0] == 0:
1053
+ continue
1054
+
1055
+ # in torch it is faster to index using lists than torch tensors
1056
+ top_x_list = top_x.tolist()
1057
+ idx_list = idx.tolist()
1058
+
1059
+ # Index the correct hidden states and compute the expert hidden state for
1060
+ # the current expert. We need to make sure to multiply the output hidden
1061
+ # states by `routing_weights` on the corresponding tokens (top-1 and top-2)
1062
+ current_state = hidden_states[None, top_x_list].reshape(-1, hidden_dim)
1063
+ current_hidden_states = expert_layer(current_state) * routing_weights[top_x_list, idx_list, None]
1064
+
1065
+ # However `index_add_` only support torch tensors for indexing so we'll use
1066
+ # the `top_x` tensor here.
1067
+ final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
1068
+ final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
1069
+ # print ( 'moe', self.iter, torch.norm(final_hidden_states).item())
1070
+ return final_hidden_states, router_logits
1071
+
1072
+
1073
+ class PhiMoEDecoderLayer(nn.Module):
1074
+ def __init__(self, config: PhiMoEConfig, layer_idx: int):
1075
+ super().__init__()
1076
+ self.hidden_size = config.hidden_size
1077
+
1078
+ self.self_attn = PHIMOE_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
1079
+
1080
+ self.block_sparse_moe = PhiMoESparseMoeBlock(config)
1081
+ self.input_layernorm = nn.LayerNorm(config.hidden_size, eps=config.rms_norm_eps, elementwise_affine=True)
1082
+ self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, eps=config.rms_norm_eps, elementwise_affine=True)
1083
+
1084
+ def forward(
1085
+ self,
1086
+ hidden_states: torch.Tensor,
1087
+ attention_mask: Optional[torch.Tensor] = None,
1088
+ position_ids: Optional[torch.LongTensor] = None,
1089
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1090
+ output_attentions: Optional[bool] = False,
1091
+ output_router_logits: Optional[bool] = False,
1092
+ use_cache: Optional[bool] = False,
1093
+ **kwargs,
1094
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
1095
+ if "padding_mask" in kwargs:
1096
+ warnings.warn(
1097
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1098
+ )
1099
+ """
1100
+ Args:
1101
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
1102
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
1103
+ `(batch, sequence_length)` where padding elements are indicated by 0.
1104
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
1105
+ output_attentions (`bool`, *optional*):
1106
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1107
+ returned tensors for more detail.
1108
+ output_router_logits (`bool`, *optional*):
1109
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
1110
+ should not be returned during inference.
1111
+ use_cache (`bool`, *optional*):
1112
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1113
+ (see `past_key_values`).
1114
+ """
1115
+
1116
+ residual = hidden_states
1117
+
1118
+ hidden_states = self.input_layernorm(hidden_states)
1119
+
1120
+ # Self Attention
1121
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
1122
+ hidden_states=hidden_states,
1123
+ attention_mask=attention_mask,
1124
+ position_ids=position_ids,
1125
+ past_key_value=past_key_value,
1126
+ output_attentions=output_attentions,
1127
+ use_cache=use_cache,
1128
+ )
1129
+ hidden_states = residual + hidden_states
1130
+
1131
+ # Fully Connected
1132
+ residual = hidden_states
1133
+ hidden_states = self.post_attention_layernorm(hidden_states)
1134
+ hidden_states, router_logits = self.block_sparse_moe(hidden_states)
1135
+ hidden_states = residual + hidden_states
1136
+
1137
+ outputs = (hidden_states,)
1138
+
1139
+ if output_attentions:
1140
+ outputs += (self_attn_weights,)
1141
+
1142
+ if use_cache:
1143
+ outputs += (present_key_value,)
1144
+
1145
+ if output_router_logits:
1146
+ outputs += (router_logits,)
1147
+
1148
+ return outputs
1149
+
1150
+
1151
+ PHIMOE_START_DOCSTRING = r"""
1152
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1153
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1154
+ etc.)
1155
+
1156
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1157
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1158
+ and behavior.
1159
+
1160
+ Parameters:
1161
+ config ([`PhiMoEConfig`]):
1162
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1163
+ load the weights associated with the model, only the configuration. Check out the
1164
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1165
+ """
1166
+
1167
+
1168
+ @add_start_docstrings(
1169
+ "The bare PhiMoE Model outputting raw hidden-states without any specific head on top.",
1170
+ PHIMOE_START_DOCSTRING,
1171
+ )
1172
+
1173
+ class PhiMoEPreTrainedModel(PreTrainedModel):
1174
+ config_class = PhiMoEConfig
1175
+ base_model_prefix = "model"
1176
+ supports_gradient_checkpointing = True
1177
+ _no_split_modules = ["PhiMoEDecoderLayer"]
1178
+ _skip_keys_device_placement = "past_key_values"
1179
+ _supports_flash_attn_2 = True
1180
+ _supports_sdpa = True
1181
+ _supports_cache_class = True
1182
+
1183
+ def _init_weights(self, module):
1184
+ pass
1185
+ # std = self.config.initializer_range
1186
+ # if isinstance(module, nn.Linear):
1187
+ # module.weight.data.normal_(mean=0.0, std=std)
1188
+ # if module.bias is not None:
1189
+ # module.bias.data.zero_()
1190
+ # elif isinstance(module, nn.Embedding):
1191
+ # module.weight.data.normal_(mean=0.0, std=std)
1192
+ # if module.padding_idx is not None:
1193
+ # module.weight.data[module.padding_idx].zero_()
1194
+
1195
+
1196
+ PHIMOE_INPUTS_DOCSTRING = r"""
1197
+ Args:
1198
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1199
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1200
+ it.
1201
+
1202
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1203
+ [`PreTrainedTokenizer.__call__`] for details.
1204
+
1205
+ [What are input IDs?](../glossary#input-ids)
1206
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1207
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1208
+
1209
+ - 1 for tokens that are **not masked**,
1210
+ - 0 for tokens that are **masked**.
1211
+
1212
+ [What are attention masks?](../glossary#attention-mask)
1213
+
1214
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1215
+ [`PreTrainedTokenizer.__call__`] for details.
1216
+
1217
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
1218
+ `past_key_values`).
1219
+
1220
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1221
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1222
+ information on the default strategy.
1223
+
1224
+ - 1 indicates the head is **not masked**,
1225
+ - 0 indicates the head is **masked**.
1226
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1227
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1228
+ config.n_positions - 1]`.
1229
+
1230
+ [What are position IDs?](../glossary#position-ids)
1231
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
1232
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
1233
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
1234
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
1235
+
1236
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1237
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
1238
+
1239
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
1240
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
1241
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1242
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1243
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1244
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1245
+ model's internal embedding lookup matrix.
1246
+ use_cache (`bool`, *optional*):
1247
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1248
+ `past_key_values`).
1249
+ output_attentions (`bool`, *optional*):
1250
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1251
+ tensors for more detail.
1252
+ output_hidden_states (`bool`, *optional*):
1253
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1254
+ more detail.
1255
+ output_router_logits (`bool`, *optional*):
1256
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
1257
+ should not be returned during inference.
1258
+ return_dict (`bool`, *optional*):
1259
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1260
+ """
1261
+
1262
+
1263
+ @add_start_docstrings(
1264
+ "The bare PhiMoE Model outputting raw hidden-states without any specific head on top.",
1265
+ PHIMOE_START_DOCSTRING,
1266
+ )
1267
+
1268
+ class PhiMoEModel(PhiMoEPreTrainedModel):
1269
+ """
1270
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`PhiMoEDecoderLayer`]
1271
+
1272
+ Args:
1273
+ config: PhiMoEConfig
1274
+ """
1275
+
1276
+ def __init__(self, config: PhiMoEConfig):
1277
+ super().__init__(config)
1278
+ self.padding_idx = config.pad_token_id
1279
+ self.vocab_size = config.vocab_size
1280
+
1281
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1282
+ self.layers = nn.ModuleList(
1283
+ [PhiMoEDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1284
+ )
1285
+ self._attn_implementation = config._attn_implementation
1286
+ self.norm = nn.LayerNorm(config.hidden_size, eps=config.rms_norm_eps, elementwise_affine=True)
1287
+
1288
+ self.gradient_checkpointing = False
1289
+ # Initialize weights and apply final processing
1290
+ self.post_init()
1291
+
1292
+ def get_input_embeddings(self):
1293
+ return self.embed_tokens
1294
+
1295
+ def set_input_embeddings(self, value):
1296
+ self.embed_tokens = value
1297
+
1298
+ # Ignore copy
1299
+ @add_start_docstrings_to_model_forward(PHIMOE_INPUTS_DOCSTRING)
1300
+ def forward(
1301
+ self,
1302
+ input_ids: torch.LongTensor = None,
1303
+ attention_mask: Optional[torch.Tensor] = None,
1304
+ position_ids: Optional[torch.LongTensor] = None,
1305
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1306
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1307
+ use_cache: Optional[bool] = None,
1308
+ output_attentions: Optional[bool] = None,
1309
+ output_hidden_states: Optional[bool] = None,
1310
+ output_router_logits: Optional[bool] = None,
1311
+ return_dict: Optional[bool] = None,
1312
+ ) -> Union[Tuple, MoeModelOutputWithPast]:
1313
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1314
+ output_router_logits = (
1315
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
1316
+ )
1317
+ output_hidden_states = (
1318
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1319
+ )
1320
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1321
+
1322
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1323
+
1324
+ # retrieve input_ids and inputs_embeds
1325
+ if input_ids is not None and inputs_embeds is not None:
1326
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
1327
+ elif input_ids is not None:
1328
+ batch_size, seq_length = input_ids.shape
1329
+ elif inputs_embeds is not None:
1330
+ batch_size, seq_length, _ = inputs_embeds.shape
1331
+ else:
1332
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
1333
+
1334
+ past_key_values_length = 0
1335
+
1336
+ if self.gradient_checkpointing and self.training:
1337
+ if use_cache:
1338
+ logger.warning_once(
1339
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`transformers."
1340
+ )
1341
+ use_cache = False
1342
+
1343
+ if use_cache:
1344
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1345
+ if use_legacy_cache:
1346
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1347
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1348
+
1349
+ if position_ids is None:
1350
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1351
+ position_ids = torch.arange(
1352
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1353
+ )
1354
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
1355
+ else:
1356
+ position_ids = position_ids.view(-1, seq_length).long()
1357
+
1358
+ if inputs_embeds is None:
1359
+ inputs_embeds = self.embed_tokens(input_ids)
1360
+
1361
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
1362
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
1363
+ if is_padding_right:
1364
+ raise ValueError(
1365
+ "You are attempting to perform batched generation with padding_side='right'"
1366
+ " this may lead to unexpected behaviour for Flash Attention version of PhiMoE. Make sure to "
1367
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1368
+ )
1369
+
1370
+ if self._attn_implementation == "flash_attention_2":
1371
+ # 2d mask is passed through the layers
1372
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1373
+ elif self._attn_implementation == "sdpa" and not output_attentions:
1374
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1375
+ # the manual implementation that requires a 4D causal mask in all cases.
1376
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1377
+ attention_mask,
1378
+ (batch_size, seq_length),
1379
+ inputs_embeds,
1380
+ past_key_values_length,
1381
+ )
1382
+ else:
1383
+ # 4d mask is passed through the layers
1384
+ attention_mask = _prepare_4d_causal_attention_mask(
1385
+ attention_mask,
1386
+ (batch_size, seq_length),
1387
+ inputs_embeds,
1388
+ past_key_values_length,
1389
+ sliding_window=self.config.sliding_window,
1390
+ )
1391
+
1392
+ hidden_states = inputs_embeds
1393
+
1394
+ # decoder layers
1395
+ all_hidden_states = () if output_hidden_states else None
1396
+ all_self_attns = () if output_attentions else None
1397
+ all_router_logits = () if output_router_logits else None
1398
+ next_decoder_cache = None
1399
+
1400
+ for decoder_layer in self.layers:
1401
+ if output_hidden_states:
1402
+ all_hidden_states += (hidden_states,)
1403
+
1404
+ if self.gradient_checkpointing and self.training:
1405
+ layer_outputs = self._gradient_checkpointing_func(
1406
+ decoder_layer.__call__,
1407
+ hidden_states,
1408
+ attention_mask,
1409
+ position_ids,
1410
+ past_key_values,
1411
+ output_attentions,
1412
+ output_router_logits,
1413
+ use_cache,
1414
+ )
1415
+ else:
1416
+ layer_outputs = decoder_layer(
1417
+ hidden_states,
1418
+ attention_mask=attention_mask,
1419
+ position_ids=position_ids,
1420
+ past_key_value=past_key_values,
1421
+ output_attentions=output_attentions,
1422
+ output_router_logits=output_router_logits,
1423
+ use_cache=use_cache,
1424
+ )
1425
+
1426
+ hidden_states = layer_outputs[0]
1427
+
1428
+ if use_cache:
1429
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1430
+
1431
+ if output_attentions:
1432
+ all_self_attns += (layer_outputs[1],)
1433
+
1434
+ if output_router_logits:
1435
+ all_router_logits += (layer_outputs[-1],)
1436
+
1437
+ hidden_states = self.norm(hidden_states)
1438
+
1439
+ # add hidden states from the last decoder layer
1440
+ if output_hidden_states:
1441
+ all_hidden_states += (hidden_states,)
1442
+
1443
+ next_cache = None
1444
+ if use_cache:
1445
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1446
+
1447
+ if not return_dict:
1448
+ return tuple(
1449
+ v
1450
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_router_logits]
1451
+ if v is not None
1452
+ )
1453
+ return MoeModelOutputWithPast(
1454
+ last_hidden_state=hidden_states,
1455
+ past_key_values=next_cache,
1456
+ hidden_states=all_hidden_states,
1457
+ attentions=all_self_attns,
1458
+ router_logits=all_router_logits,
1459
+ )
1460
+
1461
+
1462
+ class PhiMoEForCausalLM(PhiMoEPreTrainedModel):
1463
+ _tied_weights_keys = ["lm_head.weight"]
1464
+
1465
+ def __init__(self, config):
1466
+ super().__init__(config)
1467
+ self.model = PhiMoEModel(config)
1468
+ self.vocab_size = config.vocab_size
1469
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=self.config.lm_head_bias)
1470
+ self.router_aux_loss_coef = config.router_aux_loss_coef
1471
+ self.num_experts = config.num_local_experts
1472
+ self.num_experts_per_tok = config.num_experts_per_tok
1473
+ # Initialize weights and apply final processing
1474
+ self.post_init()
1475
+
1476
+ def get_input_embeddings(self):
1477
+ return self.model.embed_tokens
1478
+
1479
+ def set_input_embeddings(self, value):
1480
+ self.model.embed_tokens = value
1481
+
1482
+ def get_output_embeddings(self):
1483
+ return self.lm_head
1484
+
1485
+ def set_output_embeddings(self, new_embeddings):
1486
+ self.lm_head = new_embeddings
1487
+
1488
+ def set_decoder(self, decoder):
1489
+ self.model = decoder
1490
+
1491
+ def get_decoder(self):
1492
+ return self.model
1493
+
1494
+ @add_start_docstrings_to_model_forward(PHIMOE_INPUTS_DOCSTRING)
1495
+ @replace_return_docstrings(output_type=MoeCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1496
+ # Ignore copy
1497
+ def forward(
1498
+ self,
1499
+ input_ids: torch.LongTensor = None,
1500
+ attention_mask: Optional[torch.Tensor] = None,
1501
+ position_ids: Optional[torch.LongTensor] = None,
1502
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1503
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1504
+ labels: Optional[torch.LongTensor] = None,
1505
+ use_cache: Optional[bool] = None,
1506
+ output_attentions: Optional[bool] = None,
1507
+ output_hidden_states: Optional[bool] = None,
1508
+ output_router_logits: Optional[bool] = None,
1509
+ return_dict: Optional[bool] = None,
1510
+ ) -> Union[Tuple, MoeCausalLMOutputWithPast]:
1511
+ r"""
1512
+ Args:
1513
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1514
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, transformers.,
1515
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1516
+ (masked), the loss is only computed for the tokens with labels in `[0, transformers., config.vocab_size]`.
1517
+
1518
+ Returns:
1519
+
1520
+ Example:
1521
+
1522
+ ```python
1523
+ >>> from transformers import AutoTokenizer, PhiMoEForCausalLM
1524
+
1525
+ >>> model = PhiMoEForCausalLM.from_pretrained("microsoft/Phi-3.5-moe-instruct")
1526
+ >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/Phi-3.5-moe-instruct")
1527
+
1528
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1529
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1530
+
1531
+ >>> # Generate
1532
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1533
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1534
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1535
+ ```"""
1536
+
1537
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1538
+ output_router_logits = (
1539
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
1540
+ )
1541
+
1542
+ output_hidden_states = (
1543
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1544
+ )
1545
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1546
+
1547
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1548
+ outputs = self.model(
1549
+ input_ids=input_ids,
1550
+ attention_mask=attention_mask,
1551
+ position_ids=position_ids,
1552
+ past_key_values=past_key_values,
1553
+ inputs_embeds=inputs_embeds,
1554
+ use_cache=use_cache,
1555
+ output_attentions=output_attentions,
1556
+ output_hidden_states=output_hidden_states,
1557
+ output_router_logits=output_router_logits,
1558
+ return_dict=return_dict,
1559
+ )
1560
+
1561
+ hidden_states = outputs[0]
1562
+ logits = self.lm_head(hidden_states)
1563
+ logits = logits.float()
1564
+
1565
+ loss = None
1566
+ if labels is not None:
1567
+ # Shift so that tokens < n predict n
1568
+ shift_logits = logits[..., :-1, :].contiguous()
1569
+ shift_labels = labels[..., 1:].contiguous()
1570
+ # Flatten the tokens
1571
+ loss_fct = CrossEntropyLoss()
1572
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1573
+ shift_labels = shift_labels.view(-1)
1574
+ # Enable model parallelism
1575
+ shift_labels = shift_labels.to(shift_logits.device)
1576
+ loss = loss_fct(shift_logits, shift_labels)
1577
+
1578
+ aux_loss = None
1579
+ if output_router_logits:
1580
+ aux_loss = load_balancing_loss_func(
1581
+ outputs.router_logits if return_dict else outputs[-1],
1582
+ self.num_experts,
1583
+ self.num_experts_per_tok,
1584
+ attention_mask,
1585
+ )
1586
+ if labels is not None:
1587
+ loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
1588
+
1589
+ if not return_dict:
1590
+ output = (logits,) + outputs[1:]
1591
+ if output_router_logits:
1592
+ output = (aux_loss,) + output
1593
+ return (loss,) + output if loss is not None else output
1594
+
1595
+ return MoeCausalLMOutputWithPast(
1596
+ loss=loss,
1597
+ aux_loss=aux_loss,
1598
+ logits=logits,
1599
+ past_key_values=outputs.past_key_values,
1600
+ hidden_states=outputs.hidden_states,
1601
+ attentions=outputs.attentions,
1602
+ router_logits=outputs.router_logits,
1603
+ )
1604
+
1605
+ def prepare_inputs_for_generation(
1606
+ self,
1607
+ input_ids,
1608
+ past_key_values=None,
1609
+ attention_mask=None,
1610
+ inputs_embeds=None,
1611
+ output_router_logits=False,
1612
+ **kwargs,
1613
+ ):
1614
+ # When the first time input length reached long and short factor switching point, enforce re-compute cache
1615
+ # It will cause downside of slower at this single token position, however, better than current failure.
1616
+ if past_key_values and self.config.rope_scaling and input_ids.shape[1] >= self.config.original_max_position_embeddings + 1:
1617
+ past_length = past_key_values.seen_tokens if isinstance(past_key_values, Cache) else past_key_values[0][0].shape[2]
1618
+ if past_length <= self.config.original_max_position_embeddings:
1619
+ past_key_values = None
1620
+
1621
+ # Omit tokens covered by past_key_values
1622
+ if past_key_values is not None:
1623
+ if isinstance(past_key_values, Cache):
1624
+ cache_length = past_key_values.get_seq_length()
1625
+ past_length = past_key_values.seen_tokens
1626
+ max_cache_length = past_key_values.get_max_length() if hasattr(past_key_values, "get_max_length") else past_key_values.get_max_cache_shape()
1627
+ else:
1628
+ cache_length = past_length = past_key_values[0][0].shape[2]
1629
+ max_cache_length = None
1630
+
1631
+ # Keep only the unprocessed tokens:
1632
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1633
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1634
+ # input)
1635
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1636
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1637
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1638
+ # input_ids based on the past_length.
1639
+ elif past_length < input_ids.shape[1]:
1640
+ input_ids = input_ids[:, past_length:]
1641
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1642
+
1643
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1644
+ if (
1645
+ max_cache_length is not None
1646
+ and attention_mask is not None
1647
+ and cache_length + input_ids.shape[1] > max_cache_length
1648
+ ):
1649
+ attention_mask = attention_mask[:, -max_cache_length:]
1650
+
1651
+ position_ids = kwargs.get("position_ids", None)
1652
+ if attention_mask is not None and position_ids is None:
1653
+ # create position_ids on the fly for batch generation
1654
+ position_ids = attention_mask.long().cumsum(-1) - 1
1655
+ position_ids.masked_fill_(attention_mask == 0, 1)
1656
+ if past_key_values:
1657
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1658
+
1659
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1660
+ if inputs_embeds is not None and past_key_values is None:
1661
+ model_inputs = {"inputs_embeds": inputs_embeds}
1662
+ else:
1663
+ model_inputs = {"input_ids": input_ids}
1664
+
1665
+ model_inputs.update(
1666
+ {
1667
+ "position_ids": position_ids,
1668
+ "past_key_values": past_key_values,
1669
+ "use_cache": kwargs.get("use_cache"),
1670
+ "attention_mask": attention_mask,
1671
+ "output_router_logits": output_router_logits,
1672
+ }
1673
+ )
1674
+ return model_inputs
1675
+
1676
+ @staticmethod
1677
+ def _reorder_cache(past_key_values, beam_idx):
1678
+ reordered_past = ()
1679
+ for layer_past in past_key_values:
1680
+ reordered_past += (
1681
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1682
+ )
1683
+ return reordered_past
1684
+
1685
+
1686
+ @add_start_docstrings(
1687
+ """
1688
+ The PhiMoE Model transformer with a sequence classification head on top (linear layer).
1689
+
1690
+ [`PhiMoEForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1691
+ (e.g. GPT-2) do.
1692
+
1693
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1694
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1695
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1696
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1697
+ each row of the batch).
1698
+ """,
1699
+ PHIMOE_START_DOCSTRING,
1700
+ )
1701
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->PhiMoE, LLAMA->PHIMOE
1702
+ class PhiMoEForSequenceClassification(PhiMoEPreTrainedModel):
1703
+ def __init__(self, config):
1704
+ super().__init__(config)
1705
+ self.num_labels = config.num_labels
1706
+ self.model = PhiMoEModel(config)
1707
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1708
+
1709
+ # Initialize weights and apply final processing
1710
+ self.post_init()
1711
+
1712
+ def get_input_embeddings(self):
1713
+ return self.model.embed_tokens
1714
+
1715
+ def set_input_embeddings(self, value):
1716
+ self.model.embed_tokens = value
1717
+
1718
+ @add_start_docstrings_to_model_forward(PHIMOE_INPUTS_DOCSTRING)
1719
+ def forward(
1720
+ self,
1721
+ input_ids: torch.LongTensor = None,
1722
+ attention_mask: Optional[torch.Tensor] = None,
1723
+ position_ids: Optional[torch.LongTensor] = None,
1724
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1725
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1726
+ labels: Optional[torch.LongTensor] = None,
1727
+ use_cache: Optional[bool] = None,
1728
+ output_attentions: Optional[bool] = None,
1729
+ output_hidden_states: Optional[bool] = None,
1730
+ return_dict: Optional[bool] = None,
1731
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1732
+ r"""
1733
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1734
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, transformers.,
1735
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1736
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1737
+ """
1738
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1739
+
1740
+ transformer_outputs = self.model(
1741
+ input_ids,
1742
+ attention_mask=attention_mask,
1743
+ position_ids=position_ids,
1744
+ past_key_values=past_key_values,
1745
+ inputs_embeds=inputs_embeds,
1746
+ use_cache=use_cache,
1747
+ output_attentions=output_attentions,
1748
+ output_hidden_states=output_hidden_states,
1749
+ return_dict=return_dict,
1750
+ )
1751
+ hidden_states = transformer_outputs[0]
1752
+ logits = self.score(hidden_states)
1753
+
1754
+ if input_ids is not None:
1755
+ batch_size = input_ids.shape[0]
1756
+ else:
1757
+ batch_size = inputs_embeds.shape[0]
1758
+
1759
+ if self.config.pad_token_id is None and batch_size != 1:
1760
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1761
+ if self.config.pad_token_id is None:
1762
+ sequence_lengths = -1
1763
+ else:
1764
+ if input_ids is not None:
1765
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1766
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1767
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1768
+ sequence_lengths = sequence_lengths.to(logits.device)
1769
+ else:
1770
+ sequence_lengths = -1
1771
+
1772
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1773
+
1774
+ loss = None
1775
+ if labels is not None:
1776
+ labels = labels.to(logits.device)
1777
+ if self.config.problem_type is None:
1778
+ if self.num_labels == 1:
1779
+ self.config.problem_type = "regression"
1780
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1781
+ self.config.problem_type = "single_label_classification"
1782
+ else:
1783
+ self.config.problem_type = "multi_label_classification"
1784
+
1785
+ if self.config.problem_type == "regression":
1786
+ loss_fct = MSELoss()
1787
+ if self.num_labels == 1:
1788
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1789
+ else:
1790
+ loss = loss_fct(pooled_logits, labels)
1791
+ elif self.config.problem_type == "single_label_classification":
1792
+ loss_fct = CrossEntropyLoss()
1793
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1794
+ elif self.config.problem_type == "multi_label_classification":
1795
+ loss_fct = BCEWithLogitsLoss()
1796
+ loss = loss_fct(pooled_logits, labels)
1797
+ if not return_dict:
1798
+ output = (pooled_logits,) + transformer_outputs[1:]
1799
+ return ((loss,) + output) if loss is not None else output
1800
+
1801
+ return SequenceClassifierOutputWithPast(
1802
+ loss=loss,
1803
+ logits=pooled_logits,
1804
+ past_key_values=transformer_outputs.past_key_values,
1805
+ hidden_states=transformer_outputs.hidden_states,
1806
+ attentions=transformer_outputs.attentions,
1807
+ )
special_tokens_map.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|endoftext|>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "<|endoftext|>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "unk_token": {
24
+ "content": "<unk>",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ }
30
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9e556afd44213b6bd1be2b850ebbbd98f5481437a8021afaf58ee7fb1818d347
3
+ size 499723
tokenizer_config.json ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": null,
5
+ "added_tokens_decoder": {
6
+ "0": {
7
+ "content": "<unk>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "1": {
15
+ "content": "<s>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "2": {
23
+ "content": "</s>",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": true,
27
+ "single_word": false,
28
+ "special": false
29
+ },
30
+ "32000": {
31
+ "content": "<|endoftext|>",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false,
36
+ "special": true
37
+ },
38
+ "32001": {
39
+ "content": "<|assistant|>",
40
+ "lstrip": false,
41
+ "normalized": false,
42
+ "rstrip": true,
43
+ "single_word": false,
44
+ "special": true
45
+ },
46
+ "32002": {
47
+ "content": "<|placeholder1|>",
48
+ "lstrip": false,
49
+ "normalized": false,
50
+ "rstrip": true,
51
+ "single_word": false,
52
+ "special": true
53
+ },
54
+ "32003": {
55
+ "content": "<|placeholder2|>",
56
+ "lstrip": false,
57
+ "normalized": false,
58
+ "rstrip": true,
59
+ "single_word": false,
60
+ "special": true
61
+ },
62
+ "32004": {
63
+ "content": "<|placeholder3|>",
64
+ "lstrip": false,
65
+ "normalized": false,
66
+ "rstrip": true,
67
+ "single_word": false,
68
+ "special": true
69
+ },
70
+ "32005": {
71
+ "content": "<|placeholder4|>",
72
+ "lstrip": false,
73
+ "normalized": false,
74
+ "rstrip": true,
75
+ "single_word": false,
76
+ "special": true
77
+ },
78
+ "32006": {
79
+ "content": "<|system|>",
80
+ "lstrip": false,
81
+ "normalized": false,
82
+ "rstrip": true,
83
+ "single_word": false,
84
+ "special": true
85
+ },
86
+ "32007": {
87
+ "content": "<|end|>",
88
+ "lstrip": false,
89
+ "normalized": false,
90
+ "rstrip": true,
91
+ "single_word": false,
92
+ "special": true
93
+ },
94
+ "32008": {
95
+ "content": "<|placeholder5|>",
96
+ "lstrip": false,
97
+ "normalized": false,
98
+ "rstrip": true,
99
+ "single_word": false,
100
+ "special": true
101
+ },
102
+ "32009": {
103
+ "content": "<|placeholder6|>",
104
+ "lstrip": false,
105
+ "normalized": false,
106
+ "rstrip": true,
107
+ "single_word": false,
108
+ "special": true
109
+ },
110
+ "32010": {
111
+ "content": "<|user|>",
112
+ "lstrip": false,
113
+ "normalized": false,
114
+ "rstrip": true,
115
+ "single_word": false,
116
+ "special": true
117
+ }
118
+ },
119
+ "bos_token": "<s>",
120
+ "chat_template": "{% for message in messages %}{% if message['role'] == 'system' and message['content'] %}{{'<|system|>\n' + message['content'] + '<|end|>\n'}}{% elif message['role'] == 'user' %}{{'<|user|>\n' + message['content'] + '<|end|>\n'}}{% elif message['role'] == 'assistant' %}{{'<|assistant|>\n' + message['content'] + '<|end|>\n'}}{% endif %}{% endfor %}{% if add_generation_prompt %}{{ '<|assistant|>\n' }}{% else %}{{ eos_token }}{% endif %}",
121
+ "clean_up_tokenization_spaces": false,
122
+ "eos_token": "<|endoftext|>",
123
+ "legacy": false,
124
+ "model_max_length": 131072,
125
+ "pad_token": "<|endoftext|>",
126
+ "padding_side": "left",
127
+ "sp_model_kwargs": {},
128
+ "tokenizer_class": "LlamaTokenizer",
129
+ "unk_token": "<unk>",
130
+ "use_default_system_prompt": false
131
+ }