aksj commited on
Commit
a554754
1 Parent(s): 3a05f4b

Upload modeling_phi3.py

Browse files
Files changed (1) hide show
  1. modeling_phi3.py +1660 -0
modeling_phi3.py ADDED
@@ -0,0 +1,1660 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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-3 model."""
17
+
18
+ import math
19
+ import warnings
20
+ from typing import List, Optional, Tuple, Union
21
+
22
+ import torch
23
+ import torch.utils.checkpoint
24
+ from torch import nn
25
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
26
+
27
+ from ...activations import ACT2FN
28
+ from ...cache_utils import Cache, DynamicCache, StaticCache
29
+ from ...modeling_attn_mask_utils import AttentionMaskConverter
30
+ from ...modeling_outputs import (
31
+ BaseModelOutputWithPast,
32
+ CausalLMOutputWithPast,
33
+ SequenceClassifierOutputWithPast,
34
+ TokenClassifierOutput,
35
+ )
36
+ from ...modeling_utils import PreTrainedModel
37
+ from ...utils import (
38
+ add_code_sample_docstrings,
39
+ add_start_docstrings,
40
+ add_start_docstrings_to_model_forward,
41
+ is_flash_attn_2_available,
42
+ is_flash_attn_greater_or_equal_2_10,
43
+ is_torchdynamo_compiling,
44
+ logging,
45
+ replace_return_docstrings,
46
+ )
47
+ from .configuration_phi3 import Phi3Config
48
+
49
+
50
+ if is_flash_attn_2_available():
51
+ from ...modeling_flash_attention_utils import _flash_attention_forward
52
+
53
+ logger = logging.get_logger(__name__)
54
+
55
+ _CHECKPOINT_FOR_DOC = "microsoft/Phi-3-mini-4k-instruct"
56
+ _CONFIG_FOR_DOC = "Phi3Config"
57
+
58
+
59
+ # Copied from transformers.models.llama.modeling_llama._prepare_4d_causal_attention_mask_with_cache_position
60
+ def _prepare_4d_causal_attention_mask_with_cache_position(
61
+ attention_mask: torch.Tensor,
62
+ sequence_length: int,
63
+ target_length: int,
64
+ dtype: torch.dtype,
65
+ device: torch.device,
66
+ min_dtype: float,
67
+ cache_position: torch.Tensor,
68
+ batch_size: int,
69
+ ):
70
+ """
71
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
72
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
73
+
74
+ Args:
75
+ attention_mask (`torch.Tensor`):
76
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.
77
+ sequence_length (`int`):
78
+ The sequence length being processed.
79
+ target_length (`int`):
80
+ The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.
81
+ dtype (`torch.dtype`):
82
+ The dtype to use for the 4D attention mask.
83
+ device (`torch.device`):
84
+ The device to plcae the 4D attention mask on.
85
+ min_dtype (`float`):
86
+ The minimum value representable with the dtype `dtype`.
87
+ cache_position (`torch.Tensor`):
88
+ Indices depicting the position of the input sequence tokens in the sequence.
89
+ batch_size (`torch.Tensor`):
90
+ Batch size.
91
+ """
92
+ if attention_mask is not None and attention_mask.dim() == 4:
93
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
94
+ causal_mask = attention_mask
95
+ else:
96
+ causal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device)
97
+ if sequence_length != 1:
98
+ causal_mask = torch.triu(causal_mask, diagonal=1)
99
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
100
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
101
+ if attention_mask is not None:
102
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
103
+ mask_length = attention_mask.shape[-1]
104
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
105
+ padding_mask = padding_mask == 0
106
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
107
+ padding_mask, min_dtype
108
+ )
109
+
110
+ return causal_mask
111
+
112
+
113
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Phi3
114
+ class Phi3RMSNorm(nn.Module):
115
+ def __init__(self, hidden_size, eps=1e-6):
116
+ """
117
+ Phi3RMSNorm is equivalent to T5LayerNorm
118
+ """
119
+ super().__init__()
120
+ self.weight = nn.Parameter(torch.ones(hidden_size))
121
+ self.variance_epsilon = eps
122
+
123
+ def forward(self, hidden_states):
124
+ input_dtype = hidden_states.dtype
125
+ hidden_states = hidden_states.to(torch.float32)
126
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
127
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
128
+ return self.weight * hidden_states.to(input_dtype)
129
+
130
+ def extra_repr(self):
131
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
132
+
133
+
134
+ # Copied from transformers.models.gemma.modeling_gemma.GemmaRotaryEmbedding with gemma->phi3, Gemma->Phi3
135
+ class Phi3RotaryEmbedding(nn.Module):
136
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
137
+ super().__init__()
138
+
139
+ self.dim = dim
140
+ self.max_position_embeddings = max_position_embeddings
141
+ self.base = base
142
+
143
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float() / self.dim))
144
+ self.register_buffer("inv_freq", tensor=inv_freq, persistent=False)
145
+
146
+ @torch.no_grad()
147
+ def forward(self, x, position_ids, seq_len=None):
148
+ # x: [bs, num_attention_heads, seq_len, head_size]
149
+ self.inv_freq.to(x.device)
150
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
151
+ position_ids_expanded = position_ids[:, None, :].float()
152
+ # Force float32 since bfloat16 loses precision on long contexts
153
+ # See https://github.com/huggingface/transformers/pull/29285
154
+ device_type = x.device.type
155
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
156
+ with torch.autocast(device_type=device_type, enabled=False):
157
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
158
+ emb = torch.cat((freqs, freqs), dim=-1)
159
+ cos = emb.cos()
160
+ sin = emb.sin()
161
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
162
+
163
+
164
+ class Phi3SuScaledRotaryEmbedding(Phi3RotaryEmbedding):
165
+ def __init__(self, dim, config, device=None):
166
+ warnings.warn(
167
+ "The class Phi3SuScaledRotaryEmbedding is deprecated and will be removed in version 5 of Transformers. Please"
168
+ " use Phi3LongRoPEScaledRotaryEmbedding instead.",
169
+ FutureWarning,
170
+ )
171
+ super().__init__(dim, config.max_position_embeddings, config.rope_theta, device)
172
+
173
+ self.short_factor = config.rope_scaling["short_factor"]
174
+ self.long_factor = config.rope_scaling["long_factor"]
175
+ self.original_max_position_embeddings = config.original_max_position_embeddings
176
+
177
+ @torch.no_grad()
178
+ def forward(self, x, position_ids, seq_len=None):
179
+ seq_len = torch.max(position_ids) + 1
180
+ if seq_len > self.original_max_position_embeddings:
181
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=x.device)
182
+ else:
183
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=x.device)
184
+ inv_freq_shape = torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim
185
+ self.inv_freq = 1.0 / (ext_factors * self.base**inv_freq_shape)
186
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
187
+ position_ids_expanded = position_ids[:, None, :].float()
188
+ # Force float32 since bfloat16 loses precision on long contexts
189
+ # See https://github.com/huggingface/transformers/pull/29285
190
+ device_type = x.device.type
191
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
192
+ with torch.autocast(device_type=device_type, enabled=False):
193
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
194
+ emb = torch.cat((freqs, freqs), dim=-1)
195
+ scale = self.max_position_embeddings / self.original_max_position_embeddings
196
+ if scale <= 1.0:
197
+ scaling_factor = 1.0
198
+ else:
199
+ scaling_factor = math.sqrt(1 + math.log(scale) / math.log(self.original_max_position_embeddings))
200
+ cos = emb.cos() * scaling_factor
201
+ sin = emb.sin() * scaling_factor
202
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
203
+
204
+
205
+ class Phi3YarnScaledRotaryEmbedding(Phi3RotaryEmbedding):
206
+ def __init__(self, dim, config, device=None):
207
+ warnings.warn(
208
+ "The class Phi3YarnScaledRotaryEmbedding is deprecated and will be removed in version 5 of Transformers",
209
+ FutureWarning,
210
+ )
211
+ super().__init__(dim, config.max_position_embeddings, config.rope_theta, device)
212
+
213
+ self.short_factor = config.rope_scaling["short_factor"]
214
+ self.long_factor = config.rope_scaling["long_factor"]
215
+ self.original_max_position_embeddings = config.original_max_position_embeddings
216
+
217
+ @torch.no_grad()
218
+ def forward(self, x, position_ids, seq_len=None):
219
+ seq_len = torch.max(position_ids) + 1
220
+ if seq_len > self.original_max_position_embeddings:
221
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=x.device)
222
+ else:
223
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=x.device)
224
+
225
+ inv_freq_shape = torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim
226
+ self.inv_freq = 1.0 / (ext_factors * self.base**inv_freq_shape)
227
+
228
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
229
+ position_ids_expanded = position_ids[:, None, :].float()
230
+
231
+ # Force float32 since bfloat16 loses precision on long contexts
232
+ # See https://github.com/huggingface/transformers/pull/29285
233
+ device_type = x.device.type
234
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
235
+ with torch.autocast(device_type=device_type, enabled=False):
236
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
237
+ emb = torch.cat((freqs, freqs), dim=-1)
238
+
239
+ scale = self.max_position_embeddings / self.original_max_position_embeddings
240
+ if scale <= 1.0:
241
+ scaling_factor = 1.0
242
+ else:
243
+ scaling_factor = 0.1 * math.log(scale) + 1.0
244
+
245
+ cos = emb.cos() * scaling_factor
246
+ sin = emb.sin() * scaling_factor
247
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
248
+
249
+
250
+ class Phi3LongRoPEScaledRotaryEmbedding(Phi3RotaryEmbedding):
251
+ def __init__(self, dim, config, device=None):
252
+ super().__init__(dim, config.max_position_embeddings, config.rope_theta, device)
253
+
254
+ self.short_factor = config.rope_scaling["short_factor"]
255
+ self.long_factor = config.rope_scaling["long_factor"]
256
+ self.original_max_position_embeddings = config.original_max_position_embeddings
257
+
258
+ @torch.no_grad()
259
+ def forward(self, x, position_ids, seq_len=None):
260
+ seq_len = torch.max(position_ids) + 1
261
+ if seq_len > self.original_max_position_embeddings:
262
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=x.device)
263
+ else:
264
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=x.device)
265
+
266
+ inv_freq_shape = torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim
267
+ self.inv_freq = 1.0 / (ext_factors * self.base**inv_freq_shape)
268
+
269
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
270
+ position_ids_expanded = position_ids[:, None, :].float()
271
+
272
+ # Force float32 since bfloat16 loses precision on long contexts
273
+ # See https://github.com/huggingface/transformers/pull/29285
274
+ device_type = x.device.type
275
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
276
+ with torch.autocast(device_type=device_type, enabled=False):
277
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
278
+ emb = torch.cat((freqs, freqs), dim=-1)
279
+
280
+ scale = self.max_position_embeddings / self.original_max_position_embeddings
281
+ if scale <= 1.0:
282
+ scaling_factor = 1.0
283
+ else:
284
+ scaling_factor = math.sqrt(1 + math.log(scale) / math.log(self.original_max_position_embeddings))
285
+
286
+ cos = emb.cos() * scaling_factor
287
+ sin = emb.sin() * scaling_factor
288
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
289
+
290
+
291
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
292
+ def rotate_half(x):
293
+ """Rotates half the hidden dims of the input."""
294
+ x1 = x[..., : x.shape[-1] // 2]
295
+ x2 = x[..., x.shape[-1] // 2 :]
296
+ return torch.cat((-x2, x1), dim=-1)
297
+
298
+
299
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
300
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
301
+ """Applies Rotary Position Embedding to the query and key tensors.
302
+
303
+ Args:
304
+ q (`torch.Tensor`): The query tensor.
305
+ k (`torch.Tensor`): The key tensor.
306
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
307
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
308
+ position_ids (`torch.Tensor`, *optional*):
309
+ Deprecated and unused.
310
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
311
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
312
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
313
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
314
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
315
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
316
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
317
+ Returns:
318
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
319
+ """
320
+ cos = cos.unsqueeze(unsqueeze_dim)
321
+ sin = sin.unsqueeze(unsqueeze_dim)
322
+ q_embed = (q * cos) + (rotate_half(q) * sin)
323
+ k_embed = (k * cos) + (rotate_half(k) * sin)
324
+ return q_embed, k_embed
325
+
326
+
327
+ class Phi3MLP(nn.Module):
328
+ def __init__(self, config):
329
+ super().__init__()
330
+
331
+ self.config = config
332
+ self.gate_up_proj = nn.Linear(config.hidden_size, 2 * config.intermediate_size, bias=False)
333
+ self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
334
+
335
+ self.activation_fn = ACT2FN[config.hidden_act]
336
+
337
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
338
+ up_states = self.gate_up_proj(hidden_states)
339
+
340
+ gate, up_states = up_states.chunk(2, dim=-1)
341
+ up_states = up_states * self.activation_fn(gate)
342
+
343
+ return self.down_proj(up_states)
344
+
345
+
346
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv with llama->phi
347
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
348
+ """
349
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
350
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
351
+ """
352
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
353
+ if n_rep == 1:
354
+ return hidden_states
355
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
356
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
357
+
358
+
359
+ class Phi3Attention(nn.Module):
360
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
361
+
362
+ def __init__(self, config: Phi3Config, layer_idx: Optional[int] = None):
363
+ super().__init__()
364
+ self.config = config
365
+ self.layer_idx = layer_idx
366
+ if layer_idx is None:
367
+ logger.warning_once(
368
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
369
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
370
+ "when creating this class."
371
+ )
372
+
373
+ self.attention_dropout = config.attention_dropout
374
+ self.hidden_size = config.hidden_size
375
+ self.num_heads = config.num_attention_heads
376
+ self.head_dim = self.hidden_size // self.num_heads
377
+ self.num_key_value_heads = config.num_key_value_heads
378
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
379
+ self.max_position_embeddings = config.max_position_embeddings
380
+ self.original_max_position_embeddings = config.original_max_position_embeddings
381
+ self.rope_theta = config.rope_theta
382
+ self.rope_scaling = config.rope_scaling
383
+ self.is_causal = True
384
+
385
+ if (self.head_dim * self.num_heads) != self.hidden_size:
386
+ raise ValueError(
387
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
388
+ f" and `num_heads`: {self.num_heads})."
389
+ )
390
+
391
+ op_size = self.num_heads * self.head_dim + 2 * (self.num_key_value_heads * self.head_dim)
392
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
393
+ self.qkv_proj = nn.Linear(self.hidden_size, op_size, bias=False)
394
+ self._init_rope()
395
+
396
+ def _init_rope(self):
397
+ if self.rope_scaling is None:
398
+ self.rotary_emb = Phi3RotaryEmbedding(
399
+ self.head_dim,
400
+ max_position_embeddings=self.max_position_embeddings,
401
+ base=self.rope_theta,
402
+ )
403
+ else:
404
+ scaling_type = self.config.rope_scaling["type"]
405
+ if scaling_type == "longrope":
406
+ self.rotary_emb = Phi3LongRoPEScaledRotaryEmbedding(self.head_dim, self.config)
407
+ else:
408
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
409
+
410
+ def forward(
411
+ self,
412
+ hidden_states: torch.Tensor,
413
+ attention_mask: Optional[torch.Tensor] = None,
414
+ position_ids: Optional[torch.LongTensor] = None,
415
+ past_key_value: Optional[Cache] = None,
416
+ output_attentions: bool = False,
417
+ use_cache: bool = False,
418
+ cache_position: Optional[torch.LongTensor] = None,
419
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
420
+ logger.warning_once("You are not running the flash-attention implementation, expect numerical differences.")
421
+
422
+ bsz, q_len, _ = hidden_states.size()
423
+
424
+ qkv = self.qkv_proj(hidden_states)
425
+ query_pos = self.num_heads * self.head_dim
426
+ query_states = qkv[..., :query_pos]
427
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
428
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
429
+
430
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
431
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
432
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
433
+
434
+ kv_seq_len = key_states.shape[-2]
435
+ if past_key_value is not None:
436
+ if self.layer_idx is None:
437
+ raise ValueError(
438
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
439
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
440
+ "with a layer index."
441
+ )
442
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
443
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=kv_seq_len)
444
+
445
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
446
+
447
+ if past_key_value is not None:
448
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
449
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
450
+
451
+ # repeat k/v heads if n_kv_heads < n_heads
452
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
453
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
454
+
455
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
456
+
457
+ if attention_mask is not None:
458
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
459
+ attn_weights += causal_mask
460
+
461
+ # upcast attention to fp32
462
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(value_states.dtype)
463
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
464
+
465
+ attn_output = torch.matmul(attn_weights, value_states)
466
+
467
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
468
+ raise ValueError(
469
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
470
+ f" {attn_output.size()}"
471
+ )
472
+
473
+ attn_output = attn_output.transpose(1, 2).contiguous()
474
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
475
+
476
+ attn_output = self.o_proj(attn_output)
477
+
478
+ if not output_attentions:
479
+ attn_weights = None
480
+
481
+ return attn_output, attn_weights, past_key_value
482
+
483
+
484
+ class Phi3FlashAttention2(Phi3Attention):
485
+ """
486
+ Phi-3 flash attention module. This module inherits from `Phi3Attention` as the weights of the module stays
487
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
488
+ flash attention and deal with padding tokens in case the input contains any of them.
489
+ """
490
+
491
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
492
+ def __init__(self, *args, **kwargs):
493
+ super().__init__(*args, **kwargs)
494
+
495
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
496
+ # 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.
497
+ # 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).
498
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
499
+
500
+ def forward(
501
+ self,
502
+ hidden_states: torch.Tensor,
503
+ attention_mask: Optional[torch.LongTensor] = None,
504
+ position_ids: Optional[torch.LongTensor] = None,
505
+ past_key_value: Optional[Cache] = None,
506
+ output_attentions: bool = False,
507
+ use_cache: bool = False,
508
+ cache_position: Optional[torch.LongTensor] = None,
509
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
510
+ # Phi3FlashAttention2 attention does not support output_attentions
511
+
512
+ output_attentions = False
513
+
514
+ bsz, q_len, _ = hidden_states.size()
515
+
516
+ qkv = self.qkv_proj(hidden_states)
517
+ query_pos = self.num_heads * self.head_dim
518
+ query_states = qkv[..., :query_pos]
519
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
520
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
521
+
522
+ # Flash attention requires the input to have the shape
523
+ # batch_size x seq_length x head_dim x hidden_dim
524
+ # therefore we just need to keep the original shape
525
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
526
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
527
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
528
+
529
+ kv_seq_len = key_states.shape[-2]
530
+ if past_key_value is not None:
531
+ if self.layer_idx is None:
532
+ raise ValueError(
533
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
534
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
535
+ "with a layer index."
536
+ )
537
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
538
+
539
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
540
+ rotary_seq_len = (
541
+ max(kv_seq_len, position_ids[:, -1].max().item() + 1) if position_ids is not None else kv_seq_len
542
+ )
543
+
544
+ cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len, position_ids=position_ids)
545
+
546
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
547
+
548
+ if past_key_value is not None:
549
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
550
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
551
+ if (
552
+ getattr(self.config, "sliding_window", None) is not None
553
+ and kv_seq_len > self.config.sliding_window
554
+ and cache_has_contents
555
+ ):
556
+ slicing_tokens = 1 - self.config.sliding_window
557
+
558
+ past_key = past_key_value[self.layer_idx][0]
559
+ past_value = past_key_value[self.layer_idx][1]
560
+
561
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
562
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
563
+
564
+ if past_key.shape[-2] != self.config.sliding_window - 1:
565
+ raise ValueError(
566
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
567
+ f" {past_key.shape}"
568
+ )
569
+
570
+ if attention_mask is not None:
571
+ attention_mask = attention_mask[:, slicing_tokens:]
572
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
573
+
574
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
575
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
576
+
577
+ # repeat k/v heads if n_kv_heads < n_heads
578
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
579
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
580
+
581
+ attn_dropout = self.attention_dropout if self.training else 0.0
582
+
583
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
584
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
585
+ # cast them back in the correct dtype just to be sure everything works as expected.
586
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
587
+ # in fp32.
588
+
589
+ if query_states.dtype == torch.float32:
590
+ if torch.is_autocast_enabled():
591
+ target_dtype = torch.get_autocast_gpu_dtype()
592
+ # Handle the case where the model is quantized
593
+ elif hasattr(self.config, "_pre_quantization_dtype"):
594
+ target_dtype = self.config._pre_quantization_dtype
595
+ else:
596
+ target_dtype = self.qkv_proj.weight.dtype
597
+
598
+ logger.warning_once(
599
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
600
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
601
+ f" {target_dtype}."
602
+ )
603
+
604
+ query_states = query_states.to(target_dtype)
605
+ key_states = key_states.to(target_dtype)
606
+ value_states = value_states.to(target_dtype)
607
+
608
+ # Reashape to the expected shape for Flash Attention
609
+ query_states = query_states.transpose(1, 2)
610
+ key_states = key_states.transpose(1, 2)
611
+ value_states = value_states.transpose(1, 2)
612
+
613
+ attn_output = _flash_attention_forward(
614
+ query_states,
615
+ key_states,
616
+ value_states,
617
+ attention_mask,
618
+ q_len,
619
+ position_ids=position_ids,
620
+ dropout=attn_dropout,
621
+ sliding_window=getattr(self.config, "sliding_window", None),
622
+ use_top_left_mask=self._flash_attn_uses_top_left_mask,
623
+ is_causal=self.is_causal,
624
+ )
625
+
626
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
627
+ attn_output = self.o_proj(attn_output)
628
+
629
+ if not output_attentions:
630
+ attn_weights = None
631
+
632
+ return attn_output, attn_weights, past_key_value
633
+
634
+ class Phi3ALiBiAttention(Phi3Attention):
635
+ def __init__(self, config: Phi3Config, layer_idx: Optional[int] = None):
636
+ super().__init__(config, layer_idx)
637
+ self.alibi_slopes = self._get_alibi_slopes(config.num_attention_heads)
638
+
639
+ def _get_alibi_slopes(self, num_heads):
640
+ # Generate slopes for ALiBi
641
+ closest_power_of_2 = 2 ** math.floor(math.log2(num_heads))
642
+ base_slopes = torch.pow(2.0, -8.0 / closest_power_of_2 * torch.arange(1, closest_power_of_2 + 1))
643
+ if closest_power_of_2 < num_heads:
644
+ extra_slopes = torch.pow(2.0, -4.0 / closest_power_of_2 * torch.arange(1, 2 * (num_heads - closest_power_of_2) + 1, 2))
645
+ slopes = torch.cat([base_slopes, extra_slopes])
646
+ else:
647
+ slopes = base_slopes
648
+ return slopes
649
+
650
+ def forward(
651
+ self,
652
+ hidden_states: torch.Tensor,
653
+ attention_mask: Optional[torch.Tensor] = None,
654
+ position_ids: Optional[torch.LongTensor] = None,
655
+ past_key_value: Optional[Cache] = None,
656
+ output_attentions: bool = False,
657
+ use_cache: bool = False,
658
+ cache_position: Optional[torch.LongTensor] = None,
659
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
660
+ bsz, q_len, _ = hidden_states.size()
661
+
662
+ qkv = self.qkv_proj(hidden_states)
663
+ query_pos = self.num_heads * self.head_dim
664
+ query_states = qkv[..., :query_pos]
665
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
666
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
667
+
668
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
669
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
670
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
671
+
672
+ kv_seq_len = key_states.shape[-2]
673
+ if past_key_value is not None:
674
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
675
+
676
+ # Apply ALiBi bias
677
+ alibi = self.alibi_slopes.to(key_states.device)[:, None, None] * torch.arange(kv_seq_len, device=key_states.device)[None, None, :]
678
+ alibi = alibi.expand(bsz, -1, -1, -1)
679
+
680
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
681
+ attn_weights += alibi
682
+
683
+ if attention_mask is not None:
684
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
685
+ attn_weights += causal_mask
686
+
687
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(value_states.dtype)
688
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
689
+
690
+ attn_output = torch.matmul(attn_weights, value_states)
691
+
692
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
693
+ raise ValueError(
694
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
695
+ f" {attn_output.size()}"
696
+ )
697
+
698
+ attn_output = attn_output.transpose(1, 2).contiguous()
699
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
700
+
701
+ attn_output = self.o_proj(attn_output)
702
+
703
+ if not output_attentions:
704
+ attn_weights = None
705
+
706
+ return attn_output, attn_weights, past_key_value
707
+
708
+ # copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->Phi3
709
+ # TODO @Arthur no longer copied from LLama after static cache
710
+ class Phi3SdpaAttention(Phi3Attention):
711
+ """
712
+ Phi3 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
713
+ `Phi3Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
714
+ SDPA API.
715
+ """
716
+
717
+ # Adapted from Phi3Attention.forward
718
+ def forward(
719
+ self,
720
+ hidden_states: torch.Tensor,
721
+ attention_mask: Optional[torch.Tensor] = None,
722
+ position_ids: Optional[torch.LongTensor] = None,
723
+ past_key_value: Optional[Cache] = None,
724
+ output_attentions: bool = False,
725
+ use_cache: bool = False,
726
+ cache_position: Optional[torch.LongTensor] = None,
727
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
728
+ if output_attentions:
729
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
730
+ logger.warning_once(
731
+ "Phi3Model is using Phi3SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
732
+ '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.'
733
+ )
734
+ return super().forward(
735
+ hidden_states=hidden_states,
736
+ attention_mask=attention_mask,
737
+ position_ids=position_ids,
738
+ past_key_value=past_key_value,
739
+ output_attentions=output_attentions,
740
+ use_cache=use_cache,
741
+ )
742
+
743
+ bsz, q_len, _ = hidden_states.size()
744
+
745
+ qkv = self.qkv_proj(hidden_states)
746
+ query_pos = self.num_heads * self.head_dim
747
+ query_states = qkv[..., :query_pos]
748
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
749
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
750
+
751
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
752
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
753
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
754
+
755
+ kv_seq_len = key_states.shape[-2]
756
+ if past_key_value is not None:
757
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
758
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=kv_seq_len)
759
+
760
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
761
+
762
+ if past_key_value is not None:
763
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
764
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
765
+
766
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
767
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
768
+
769
+ causal_mask = attention_mask
770
+ if attention_mask is not None:
771
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
772
+
773
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
774
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
775
+ if query_states.device.type == "cuda" and attention_mask is not None:
776
+ query_states = query_states.contiguous()
777
+ key_states = key_states.contiguous()
778
+ value_states = value_states.contiguous()
779
+
780
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
781
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
782
+ # 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.
783
+ is_causal = True if causal_mask is None and q_len > 1 else False
784
+
785
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
786
+ query_states,
787
+ key_states,
788
+ value_states,
789
+ attn_mask=causal_mask,
790
+ dropout_p=self.attention_dropout if self.training else 0.0,
791
+ is_causal=is_causal,
792
+ )
793
+
794
+ attn_output = attn_output.transpose(1, 2).contiguous()
795
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
796
+
797
+ attn_output = self.o_proj(attn_output)
798
+
799
+ return attn_output, None, past_key_value
800
+
801
+
802
+ PHI3_ATTENTION_CLASSES = {
803
+ "eager": Phi3ALiBiAttention,
804
+ "flash_attention_2": Phi3FlashAttention2,
805
+ "sdpa": Phi3SdpaAttention,
806
+ }
807
+
808
+
809
+ class Phi3DecoderLayer(nn.Module):
810
+ def __init__(self, config: Phi3Config, layer_idx: int):
811
+ super().__init__()
812
+
813
+ self.config = config
814
+ self.self_attn = PHI3_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)
815
+
816
+ self.mlp = Phi3MLP(config)
817
+ self.input_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
818
+
819
+ self.resid_attn_dropout = nn.Dropout(config.resid_pdrop)
820
+ self.resid_mlp_dropout = nn.Dropout(config.resid_pdrop)
821
+ self.post_attention_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
822
+
823
+ def forward(
824
+ self,
825
+ hidden_states: torch.Tensor,
826
+ attention_mask: Optional[torch.Tensor] = None,
827
+ position_ids: Optional[torch.LongTensor] = None,
828
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
829
+ output_attentions: Optional[bool] = False,
830
+ use_cache: Optional[bool] = False,
831
+ cache_position: Optional[torch.LongTensor] = None,
832
+ **kwargs,
833
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
834
+ """
835
+ Args:
836
+ hidden_states (`torch.FloatTensor`):
837
+ input to the layer of shape `(batch, seq_len, embed_dim)`
838
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
839
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
840
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
841
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
842
+ `[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
843
+ output_attentions (`bool`, *optional*):
844
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
845
+ returned tensors for more detail.
846
+ use_cache (`bool`, *optional*):
847
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
848
+ (see `past_key_values`).
849
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
850
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
851
+ Indices depicting the position of the input sequence tokens in the sequence
852
+ kwargs (`dict`, *optional*):
853
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
854
+ into the model
855
+ """
856
+
857
+ residual = hidden_states
858
+
859
+ hidden_states = self.input_layernorm(hidden_states)
860
+
861
+ # Self Attention
862
+ attn_outputs, self_attn_weights, present_key_value = self.self_attn(
863
+ hidden_states=hidden_states,
864
+ attention_mask=attention_mask,
865
+ position_ids=position_ids,
866
+ past_key_value=past_key_value,
867
+ output_attentions=output_attentions,
868
+ use_cache=use_cache,
869
+ cache_position=cache_position,
870
+ )
871
+
872
+ hidden_states = residual + self.resid_attn_dropout(attn_outputs)
873
+
874
+ residual = hidden_states
875
+ hidden_states = self.post_attention_layernorm(hidden_states)
876
+ hidden_states = self.mlp(hidden_states)
877
+ hidden_states = residual + self.resid_mlp_dropout(hidden_states)
878
+
879
+ outputs = (hidden_states,)
880
+
881
+ if output_attentions:
882
+ outputs += (self_attn_weights,)
883
+
884
+ if use_cache:
885
+ outputs += (present_key_value,)
886
+
887
+ return outputs
888
+
889
+
890
+ PHI3_START_DOCSTRING = r"""
891
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
892
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
893
+ etc.)
894
+
895
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
896
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
897
+ and behavior.
898
+
899
+ Parameters:
900
+ config ([`Phi3Config`]):
901
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
902
+ load the weights associated with the model, only the configuration. Check out the
903
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
904
+ """
905
+
906
+
907
+ @add_start_docstrings(
908
+ "The bare Phi-3 model outputting raw hidden-states without any specific head on top.",
909
+ PHI3_START_DOCSTRING,
910
+ )
911
+ class Phi3PreTrainedModel(PreTrainedModel):
912
+ config_class = Phi3Config
913
+ base_model_prefix = "model"
914
+ supports_gradient_checkpointing = True
915
+ _no_split_modules = ["Phi3DecoderLayer"]
916
+ _skip_keys_device_placement = "past_key_values"
917
+ _supports_flash_attn_2 = True
918
+ _supports_sdpa = True
919
+ _supports_cache_class = True
920
+
921
+ _version = "0.0.5"
922
+
923
+ def _init_weights(self, module):
924
+ std = self.config.initializer_range
925
+ if isinstance(module, nn.Linear):
926
+ module.weight.data.normal_(mean=0.0, std=std)
927
+ if module.bias is not None:
928
+ module.bias.data.zero_()
929
+ elif isinstance(module, nn.Embedding):
930
+ module.weight.data.normal_(mean=0.0, std=std)
931
+ if module.padding_idx is not None:
932
+ module.weight.data[module.padding_idx].zero_()
933
+
934
+
935
+ PHI3_INPUTS_DOCSTRING = r"""
936
+ Args:
937
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
938
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
939
+ it.
940
+
941
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
942
+ [`PreTrainedTokenizer.__call__`] for details.
943
+
944
+ [What are input IDs?](../glossary#input-ids)
945
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
946
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
947
+
948
+ - 1 for tokens that are **not masked**,
949
+ - 0 for tokens that are **masked**.
950
+
951
+ [What are attention masks?](../glossary#attention-mask)
952
+
953
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
954
+ [`PreTrainedTokenizer.__call__`] for details.
955
+
956
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
957
+ `past_key_values`).
958
+
959
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
960
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
961
+ information on the default strategy.
962
+
963
+ - 1 indicates the head is **not masked**,
964
+ - 0 indicates the head is **masked**.
965
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
966
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
967
+ config.n_positions - 1]`.
968
+
969
+ [What are position IDs?](../glossary#position-ids)
970
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
971
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
972
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
973
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
974
+
975
+ Two formats are allowed:
976
+ - a [`~cache_utils.Cache`] instance;
977
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
978
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
979
+ cache format.
980
+
981
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
982
+ legacy cache format will be returned.
983
+
984
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
985
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
986
+ of shape `(batch_size, sequence_length)`.
987
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
988
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
989
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
990
+ model's internal embedding lookup matrix.
991
+ use_cache (`bool`, *optional*):
992
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
993
+ `past_key_values`).
994
+ output_attentions (`bool`, *optional*):
995
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
996
+ tensors for more detail.
997
+ output_hidden_states (`bool`, *optional*):
998
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
999
+ more detail.
1000
+ return_dict (`bool`, *optional*):
1001
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1002
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
1003
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
1004
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
1005
+ the complete sequence length.
1006
+ """
1007
+
1008
+
1009
+ @add_start_docstrings(
1010
+ "The bare Phi-3 model outputting raw hidden-states without any specific head on top.",
1011
+ PHI3_START_DOCSTRING,
1012
+ )
1013
+ class Phi3Model(Phi3PreTrainedModel):
1014
+ """
1015
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Phi3DecoderLayer`]
1016
+
1017
+ Args:
1018
+ config: Phi3Config
1019
+ """
1020
+
1021
+ def __init__(self, config: Phi3Config):
1022
+ super().__init__(config)
1023
+ self.padding_idx = config.pad_token_id
1024
+ self.vocab_size = config.vocab_size
1025
+
1026
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1027
+ self.embed_dropout = nn.Dropout(config.embd_pdrop)
1028
+ self.layers = nn.ModuleList(
1029
+ [Phi3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1030
+ )
1031
+ self._attn_implementation = config._attn_implementation
1032
+ self.norm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1033
+
1034
+ self.gradient_checkpointing = False
1035
+ # Initialize weights and apply final processing
1036
+ self.post_init()
1037
+
1038
+ def get_input_embeddings(self):
1039
+ return self.embed_tokens
1040
+
1041
+ def set_input_embeddings(self, value):
1042
+ self.embed_tokens = value
1043
+
1044
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1045
+ def forward(
1046
+ self,
1047
+ input_ids: torch.LongTensor = None,
1048
+ attention_mask: Optional[torch.Tensor] = None,
1049
+ position_ids: Optional[torch.LongTensor] = None,
1050
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1051
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1052
+ use_cache: Optional[bool] = None,
1053
+ output_attentions: Optional[bool] = None,
1054
+ output_hidden_states: Optional[bool] = None,
1055
+ return_dict: Optional[bool] = None,
1056
+ cache_position: Optional[torch.LongTensor] = None,
1057
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1058
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1059
+ output_hidden_states = (
1060
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1061
+ )
1062
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1063
+
1064
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1065
+
1066
+ if (input_ids is None) ^ (inputs_embeds is not None):
1067
+ raise ValueError(
1068
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
1069
+ )
1070
+
1071
+ if self.gradient_checkpointing and self.training:
1072
+ if use_cache:
1073
+ logger.warning_once(
1074
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1075
+ )
1076
+ use_cache = False
1077
+
1078
+ use_legacy_cache = False
1079
+ if use_cache and not isinstance(past_key_values, Cache) and not self.training:
1080
+ use_legacy_cache = True
1081
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1082
+ logger.warning_once(
1083
+ "We detected that you are passing `past_key_values` as a tuple and this is deprecated and will be removed in v4.43. "
1084
+ "Please use an appropriate `Cache` class (https://huggingface.co/docs/transformers/internal/generation_utils#transformers.Cache)"
1085
+ )
1086
+
1087
+ if inputs_embeds is None:
1088
+ inputs_embeds = self.embed_tokens(input_ids)
1089
+
1090
+ if cache_position is None:
1091
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1092
+ cache_position = torch.arange(
1093
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
1094
+ )
1095
+ if position_ids is None:
1096
+ position_ids = cache_position.unsqueeze(0)
1097
+
1098
+ causal_mask = self._update_causal_mask(
1099
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
1100
+ )
1101
+
1102
+ hidden_states = inputs_embeds
1103
+
1104
+ # decoder layers
1105
+ all_hidden_states = () if output_hidden_states else None
1106
+ all_self_attns = () if output_attentions else None
1107
+ next_decoder_cache = None
1108
+
1109
+ for decoder_layer in self.layers:
1110
+ if output_hidden_states:
1111
+ all_hidden_states += (hidden_states,)
1112
+
1113
+ if self.gradient_checkpointing and self.training:
1114
+ layer_outputs = self._gradient_checkpointing_func(
1115
+ decoder_layer.__call__,
1116
+ hidden_states,
1117
+ causal_mask,
1118
+ position_ids,
1119
+ past_key_values,
1120
+ output_attentions,
1121
+ use_cache,
1122
+ cache_position,
1123
+ )
1124
+ else:
1125
+ layer_outputs = decoder_layer(
1126
+ hidden_states,
1127
+ attention_mask=causal_mask,
1128
+ position_ids=position_ids,
1129
+ past_key_value=past_key_values,
1130
+ output_attentions=output_attentions,
1131
+ use_cache=use_cache,
1132
+ cache_position=cache_position,
1133
+ )
1134
+
1135
+ hidden_states = layer_outputs[0]
1136
+
1137
+ if use_cache:
1138
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1139
+
1140
+ if output_attentions:
1141
+ all_self_attns += (layer_outputs[1],)
1142
+
1143
+ hidden_states = self.norm(hidden_states)
1144
+
1145
+ # add hidden states from the last decoder layer
1146
+ if output_hidden_states:
1147
+ all_hidden_states += (hidden_states,)
1148
+
1149
+ next_cache = None
1150
+ if use_cache:
1151
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1152
+ if not return_dict:
1153
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1154
+ return BaseModelOutputWithPast(
1155
+ last_hidden_state=hidden_states,
1156
+ past_key_values=next_cache,
1157
+ hidden_states=all_hidden_states,
1158
+ attentions=all_self_attns,
1159
+ )
1160
+
1161
+ # Copied from transformers.models.llama.modeling_llama.LlamaModel._update_causal_mask
1162
+ def _update_causal_mask(
1163
+ self,
1164
+ attention_mask: torch.Tensor,
1165
+ input_tensor: torch.Tensor,
1166
+ cache_position: torch.Tensor,
1167
+ past_key_values: Cache,
1168
+ output_attentions: bool,
1169
+ ):
1170
+ # TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length even when the static
1171
+ # KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
1172
+ # (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
1173
+ # `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
1174
+
1175
+ if self.config._attn_implementation == "flash_attention_2":
1176
+ if attention_mask is not None and 0.0 in attention_mask:
1177
+ return attention_mask
1178
+ return None
1179
+
1180
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
1181
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
1182
+ # to infer the attention mask.
1183
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1184
+ using_static_cache = isinstance(past_key_values, StaticCache)
1185
+
1186
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
1187
+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
1188
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
1189
+ attention_mask,
1190
+ inputs_embeds=input_tensor,
1191
+ past_key_values_length=past_seen_tokens,
1192
+ is_training=self.training,
1193
+ ):
1194
+ return None
1195
+
1196
+ dtype, device = input_tensor.dtype, input_tensor.device
1197
+ min_dtype = torch.finfo(dtype).min
1198
+ sequence_length = input_tensor.shape[1]
1199
+ if using_static_cache:
1200
+ target_length = past_key_values.get_max_length()
1201
+ else:
1202
+ target_length = (
1203
+ attention_mask.shape[-1]
1204
+ if isinstance(attention_mask, torch.Tensor)
1205
+ else past_seen_tokens + sequence_length + 1
1206
+ )
1207
+
1208
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
1209
+ causal_mask = _prepare_4d_causal_attention_mask_with_cache_position(
1210
+ attention_mask,
1211
+ sequence_length=sequence_length,
1212
+ target_length=target_length,
1213
+ dtype=dtype,
1214
+ device=device,
1215
+ min_dtype=min_dtype,
1216
+ cache_position=cache_position,
1217
+ batch_size=input_tensor.shape[0],
1218
+ )
1219
+
1220
+ if (
1221
+ self.config._attn_implementation == "sdpa"
1222
+ and attention_mask is not None
1223
+ and attention_mask.device.type == "cuda"
1224
+ and not output_attentions
1225
+ ):
1226
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1227
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1228
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1229
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1230
+
1231
+ return causal_mask
1232
+
1233
+
1234
+ class Phi3ForCausalLM(Phi3PreTrainedModel):
1235
+ _tied_weights_keys = ["lm_head.weight"]
1236
+
1237
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.__init__ with Llama->Phi3
1238
+ def __init__(self, config):
1239
+ super().__init__(config)
1240
+ self.model = Phi3Model(config)
1241
+ self.vocab_size = config.vocab_size
1242
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1243
+
1244
+ # Initialize weights and apply final processing
1245
+ self.post_init()
1246
+
1247
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_input_embeddings
1248
+ def get_input_embeddings(self):
1249
+ return self.model.embed_tokens
1250
+
1251
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_input_embeddings
1252
+ def set_input_embeddings(self, value):
1253
+ self.model.embed_tokens = value
1254
+
1255
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_output_embeddings
1256
+ def get_output_embeddings(self):
1257
+ return self.lm_head
1258
+
1259
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_output_embeddings
1260
+ def set_output_embeddings(self, new_embeddings):
1261
+ self.lm_head = new_embeddings
1262
+
1263
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_decoder
1264
+ def set_decoder(self, decoder):
1265
+ self.model = decoder
1266
+
1267
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_decoder
1268
+ def get_decoder(self):
1269
+ return self.model
1270
+
1271
+ # Ignore copy
1272
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1273
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
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
+ labels: Optional[torch.LongTensor] = None,
1282
+ use_cache: Optional[bool] = None,
1283
+ output_attentions: Optional[bool] = None,
1284
+ output_hidden_states: Optional[bool] = None,
1285
+ return_dict: Optional[bool] = None,
1286
+ cache_position: Optional[torch.LongTensor] = None,
1287
+ num_logits_to_keep: int = 0,
1288
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1289
+ r"""
1290
+ Args:
1291
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1292
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1293
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1294
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1295
+
1296
+ num_logits_to_keep (`int`, *optional*):
1297
+ Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
1298
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
1299
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
1300
+
1301
+ Returns:
1302
+
1303
+ Example:
1304
+
1305
+ ```python
1306
+ >>> from transformers import AutoTokenizer, Phi3ForCausalLM
1307
+
1308
+ >>> model = Phi3ForCausalLM.from_pretrained("microsoft/phi-3-mini-4k-instruct")
1309
+ >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-3-mini-4k-instruct")
1310
+
1311
+ >>> prompt = "This is an example script ."
1312
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1313
+
1314
+ >>> # Generate
1315
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1316
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1317
+ 'This is an example script .\n Certainly! Below is a sample script that demonstrates a simple task, such as calculating the sum'
1318
+ ```"""
1319
+
1320
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1321
+ output_hidden_states = (
1322
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1323
+ )
1324
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1325
+
1326
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1327
+ outputs = self.model(
1328
+ input_ids=input_ids,
1329
+ attention_mask=attention_mask,
1330
+ position_ids=position_ids,
1331
+ past_key_values=past_key_values,
1332
+ inputs_embeds=inputs_embeds,
1333
+ use_cache=use_cache,
1334
+ output_attentions=output_attentions,
1335
+ output_hidden_states=output_hidden_states,
1336
+ return_dict=return_dict,
1337
+ )
1338
+
1339
+ hidden_states = outputs[0]
1340
+ if labels is None and not is_torchdynamo_compiling():
1341
+ logger.warning_once(
1342
+ "Starting from v4.46, the `logits` model output will have the same type as the model (except at train time, where it will always be FP32)"
1343
+ )
1344
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1345
+ # TODO: remove the float() operation in v4.46
1346
+ logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :]).float()
1347
+
1348
+ loss = None
1349
+ if labels is not None:
1350
+ # Upcast to float if we need to compute the loss to avoid potential precision issues
1351
+ logits = logits.float()
1352
+ # Shift so that tokens < n predict n
1353
+ shift_logits = logits[..., :-1, :].contiguous()
1354
+ shift_labels = labels[..., 1:].contiguous()
1355
+ # Flatten the tokens
1356
+ loss_fct = CrossEntropyLoss()
1357
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1358
+ shift_labels = shift_labels.view(-1)
1359
+ # Enable model parallelism
1360
+ shift_labels = shift_labels.to(shift_logits.device)
1361
+ loss = loss_fct(shift_logits, shift_labels)
1362
+
1363
+ if not return_dict:
1364
+ output = (logits,) + outputs[1:]
1365
+ return (loss,) + output if loss is not None else output
1366
+
1367
+ return CausalLMOutputWithPast(
1368
+ loss=loss,
1369
+ logits=logits,
1370
+ past_key_values=outputs.past_key_values,
1371
+ hidden_states=outputs.hidden_states,
1372
+ attentions=outputs.attentions,
1373
+ )
1374
+
1375
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.prepare_inputs_for_generation
1376
+ def prepare_inputs_for_generation(
1377
+ self,
1378
+ input_ids,
1379
+ past_key_values=None,
1380
+ attention_mask=None,
1381
+ inputs_embeds=None,
1382
+ cache_position=None,
1383
+ position_ids=None,
1384
+ use_cache=True,
1385
+ num_logits_to_keep=0,
1386
+ **kwargs,
1387
+ ):
1388
+ # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
1389
+ # Exception 1: when passing input_embeds, input_ids may be missing entries
1390
+ # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
1391
+ if past_key_values is not None:
1392
+ if inputs_embeds is not None: # Exception 1
1393
+ input_ids = input_ids[:, -cache_position.shape[0] :]
1394
+ elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
1395
+ input_ids = input_ids[:, cache_position]
1396
+
1397
+ if attention_mask is not None and position_ids is None:
1398
+ # create position_ids on the fly for batch generation
1399
+ position_ids = attention_mask.long().cumsum(-1) - 1
1400
+ position_ids.masked_fill_(attention_mask == 0, 1)
1401
+ if past_key_values:
1402
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1403
+
1404
+ # This `clone` call is needed to avoid recapturing cuda graphs with `torch.compile`'s `mode="reduce-overhead`, as otherwise the input `position_ids` would have various stride during the decoding. Here, simply using `.contiguous()` is not sufficient as in the batch size = 1 case, `position_ids` is already contiguous but with varying stride which retriggers a capture.
1405
+ position_ids = position_ids.clone(memory_format=torch.contiguous_format)
1406
+
1407
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1408
+ if inputs_embeds is not None and cache_position[0] == 0:
1409
+ model_inputs = {"inputs_embeds": inputs_embeds, "input_ids": None}
1410
+ else:
1411
+ # The clone here is for the same reason as for `position_ids`.
1412
+ model_inputs = {"input_ids": input_ids.clone(memory_format=torch.contiguous_format), "inputs_embeds": None}
1413
+
1414
+ if isinstance(past_key_values, StaticCache) and attention_mask.ndim == 2:
1415
+ if model_inputs["inputs_embeds"] is not None:
1416
+ batch_size, sequence_length, _ = model_inputs["inputs_embeds"].shape
1417
+ device = model_inputs["inputs_embeds"].device
1418
+ else:
1419
+ batch_size, sequence_length = model_inputs["input_ids"].shape
1420
+ device = model_inputs["input_ids"].device
1421
+
1422
+ dtype = self.lm_head.weight.dtype
1423
+ min_dtype = torch.finfo(dtype).min
1424
+
1425
+ attention_mask = _prepare_4d_causal_attention_mask_with_cache_position(
1426
+ attention_mask,
1427
+ sequence_length=sequence_length,
1428
+ target_length=past_key_values.get_max_length(),
1429
+ dtype=dtype,
1430
+ device=device,
1431
+ min_dtype=min_dtype,
1432
+ cache_position=cache_position,
1433
+ batch_size=batch_size,
1434
+ )
1435
+
1436
+ model_inputs.update(
1437
+ {
1438
+ "position_ids": position_ids,
1439
+ "cache_position": cache_position,
1440
+ "past_key_values": past_key_values,
1441
+ "use_cache": use_cache,
1442
+ "attention_mask": attention_mask,
1443
+ "num_logits_to_keep": num_logits_to_keep,
1444
+ }
1445
+ )
1446
+ return model_inputs
1447
+
1448
+
1449
+ @add_start_docstrings(
1450
+ """
1451
+ The [`Phi3Model`] with a sequence classification head on top (linear layer).
1452
+
1453
+ [`Phi3ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1454
+ (e.g. GPT-2) do.
1455
+
1456
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1457
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1458
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1459
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1460
+ each row of the batch).
1461
+ """,
1462
+ PHI3_START_DOCSTRING,
1463
+ )
1464
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->Phi3, LLAMA->PHI3, self.transformer->self.model, transformer_outputs->model_outputs
1465
+ class Phi3ForSequenceClassification(Phi3PreTrainedModel):
1466
+ def __init__(self, config):
1467
+ super().__init__(config)
1468
+ self.num_labels = config.num_labels
1469
+ self.model = Phi3Model(config)
1470
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1471
+
1472
+ # Initialize weights and apply final processing
1473
+ self.post_init()
1474
+
1475
+ def get_input_embeddings(self):
1476
+ return self.model.embed_tokens
1477
+
1478
+ def set_input_embeddings(self, value):
1479
+ self.model.embed_tokens = value
1480
+
1481
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1482
+ def forward(
1483
+ self,
1484
+ input_ids: Optional[torch.LongTensor] = None,
1485
+ attention_mask: Optional[torch.Tensor] = None,
1486
+ position_ids: Optional[torch.LongTensor] = None,
1487
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1488
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1489
+ labels: Optional[torch.LongTensor] = None,
1490
+ use_cache: Optional[bool] = None,
1491
+ output_attentions: Optional[bool] = None,
1492
+ output_hidden_states: Optional[bool] = None,
1493
+ return_dict: Optional[bool] = None,
1494
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1495
+ r"""
1496
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1497
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1498
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1499
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1500
+ """
1501
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1502
+
1503
+ model_outputs = self.model(
1504
+ input_ids,
1505
+ attention_mask=attention_mask,
1506
+ position_ids=position_ids,
1507
+ past_key_values=past_key_values,
1508
+ inputs_embeds=inputs_embeds,
1509
+ use_cache=use_cache,
1510
+ output_attentions=output_attentions,
1511
+ output_hidden_states=output_hidden_states,
1512
+ return_dict=return_dict,
1513
+ )
1514
+ hidden_states = model_outputs[0]
1515
+ logits = self.score(hidden_states)
1516
+
1517
+ if input_ids is not None:
1518
+ batch_size = input_ids.shape[0]
1519
+ else:
1520
+ batch_size = inputs_embeds.shape[0]
1521
+
1522
+ if self.config.pad_token_id is None and batch_size != 1:
1523
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1524
+ if self.config.pad_token_id is None:
1525
+ sequence_lengths = -1
1526
+ else:
1527
+ if input_ids is not None:
1528
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1529
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1530
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1531
+ sequence_lengths = sequence_lengths.to(logits.device)
1532
+ else:
1533
+ sequence_lengths = -1
1534
+
1535
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1536
+
1537
+ loss = None
1538
+ if labels is not None:
1539
+ labels = labels.to(logits.device)
1540
+ if self.config.problem_type is None:
1541
+ if self.num_labels == 1:
1542
+ self.config.problem_type = "regression"
1543
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1544
+ self.config.problem_type = "single_label_classification"
1545
+ else:
1546
+ self.config.problem_type = "multi_label_classification"
1547
+
1548
+ if self.config.problem_type == "regression":
1549
+ loss_fct = MSELoss()
1550
+ if self.num_labels == 1:
1551
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1552
+ else:
1553
+ loss = loss_fct(pooled_logits, labels)
1554
+ elif self.config.problem_type == "single_label_classification":
1555
+ loss_fct = CrossEntropyLoss()
1556
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1557
+ elif self.config.problem_type == "multi_label_classification":
1558
+ loss_fct = BCEWithLogitsLoss()
1559
+ loss = loss_fct(pooled_logits, labels)
1560
+ if not return_dict:
1561
+ output = (pooled_logits,) + model_outputs[1:]
1562
+ return ((loss,) + output) if loss is not None else output
1563
+
1564
+ return SequenceClassifierOutputWithPast(
1565
+ loss=loss,
1566
+ logits=pooled_logits,
1567
+ past_key_values=model_outputs.past_key_values,
1568
+ hidden_states=model_outputs.hidden_states,
1569
+ attentions=model_outputs.attentions,
1570
+ )
1571
+
1572
+
1573
+ @add_start_docstrings(
1574
+ """
1575
+ [`Phi3Model`] with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1576
+ Named-Entity-Recognition (NER) tasks.
1577
+ """,
1578
+ PHI3_START_DOCSTRING,
1579
+ )
1580
+ # Copied from transformers.models.mpt.modeling_mpt.MptForTokenClassification with Mpt->Phi3,MPT->PHI3,self.transformer->self.model,transformer_outputs->model_outputs
1581
+ class Phi3ForTokenClassification(Phi3PreTrainedModel):
1582
+ def __init__(self, config: Phi3Config):
1583
+ super().__init__(config)
1584
+ self.num_labels = config.num_labels
1585
+
1586
+ self.model = Phi3Model(config)
1587
+ if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
1588
+ classifier_dropout = config.classifier_dropout
1589
+ elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
1590
+ classifier_dropout = config.hidden_dropout
1591
+ else:
1592
+ classifier_dropout = 0.1
1593
+ self.dropout = nn.Dropout(classifier_dropout)
1594
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1595
+
1596
+ # Initialize weights and apply final processing
1597
+ self.post_init()
1598
+
1599
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1600
+ @add_code_sample_docstrings(
1601
+ checkpoint=_CHECKPOINT_FOR_DOC,
1602
+ output_type=TokenClassifierOutput,
1603
+ config_class=_CONFIG_FOR_DOC,
1604
+ )
1605
+ def forward(
1606
+ self,
1607
+ input_ids: Optional[torch.LongTensor] = None,
1608
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1609
+ attention_mask: Optional[torch.Tensor] = None,
1610
+ inputs_embeds: Optional[torch.Tensor] = None,
1611
+ labels: Optional[torch.Tensor] = None,
1612
+ use_cache: Optional[bool] = None,
1613
+ output_attentions: Optional[bool] = None,
1614
+ output_hidden_states: Optional[bool] = None,
1615
+ return_dict: Optional[bool] = None,
1616
+ **deprecated_arguments,
1617
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
1618
+ r"""
1619
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1620
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1621
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1622
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1623
+ """
1624
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1625
+
1626
+ model_outputs = self.model(
1627
+ input_ids,
1628
+ past_key_values=past_key_values,
1629
+ attention_mask=attention_mask,
1630
+ inputs_embeds=inputs_embeds,
1631
+ use_cache=use_cache,
1632
+ output_attentions=output_attentions,
1633
+ output_hidden_states=output_hidden_states,
1634
+ return_dict=return_dict,
1635
+ )
1636
+
1637
+ hidden_states = model_outputs[0]
1638
+ hidden_states = self.dropout(hidden_states)
1639
+ logits = self.classifier(hidden_states)
1640
+
1641
+ loss = None
1642
+ if labels is not None:
1643
+ # move labels to correct device to enable model parallelism
1644
+ labels = labels.to(logits.device)
1645
+ batch_size, seq_length = labels.shape
1646
+ loss_fct = CrossEntropyLoss()
1647
+ loss = loss_fct(
1648
+ logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length)
1649
+ )
1650
+
1651
+ if not return_dict:
1652
+ output = (logits,) + model_outputs[2:]
1653
+ return ((loss,) + output) if loss is not None else output
1654
+
1655
+ return TokenClassifierOutput(
1656
+ loss=loss,
1657
+ logits=logits,
1658
+ hidden_states=model_outputs.hidden_states,
1659
+ attentions=model_outputs.attentions,
1660
+ )