numbmelon commited on
Commit
c7094eb
1 Parent(s): aab9828

Upload modeling_phi3.py with huggingface_hub

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