g-h-chen commited on
Commit
41f653e
1 Parent(s): 3c151b7

upload modeling_phi3.py

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