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

Create modeling_slimmoe.py

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