PyTorch
English
Tevatron
phi3_v
vidore
custom_code
MrLight commited on
Commit
65f7e6e
1 Parent(s): 469ddc7

Create modeling_phi3_v.py

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