huu-ontocord commited on
Commit
b392992
·
verified ·
1 Parent(s): d9e503f

Create modeling_phi3_v.py

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