BoostedJonP commited on
Commit
a6b0356
·
1 Parent(s): 63ac085

added modeling_phi3.py

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