Text Generation
Transformers
Safetensors
English
llava_phi
custom_code
g-h-chen commited on
Commit
b00a908
1 Parent(s): 1b16704

upload modeling_phi.py

Browse files
Files changed (1) hide show
  1. modeling_phi.py +1383 -0
modeling_phi.py ADDED
@@ -0,0 +1,1383 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 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 model."""
17
+
18
+
19
+ import math
20
+ from typing import List, Optional, Tuple, Union
21
+
22
+ import torch
23
+ import torch.nn.functional as F
24
+ import torch.utils.checkpoint
25
+ from torch import nn
26
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
27
+
28
+ from transformers.activations import ACT2FN
29
+ # try:
30
+ from transformers.cache_utils import Cache, DynamicCache
31
+ # except:
32
+ # Cache, DynamicCache = None, None
33
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
34
+ from transformers.modeling_outputs import (
35
+ BaseModelOutputWithPast,
36
+ CausalLMOutputWithPast,
37
+ SequenceClassifierOutputWithPast,
38
+ TokenClassifierOutput,
39
+ )
40
+ from transformers.modeling_utils import PreTrainedModel
41
+ from transformers.utils import (
42
+ add_code_sample_docstrings,
43
+ add_start_docstrings,
44
+ add_start_docstrings_to_model_forward,
45
+ is_flash_attn_2_available,
46
+ is_flash_attn_greater_or_equal_2_10, # dbg
47
+ logging,
48
+ replace_return_docstrings,
49
+ )
50
+
51
+ # is_flash_attn_greater_or_equal_2_10 = lambda:True # dbg
52
+
53
+ try:
54
+ from configuration_phi import PhiConfig
55
+ except:
56
+ from .configuration_phi import PhiConfig
57
+
58
+ try:
59
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
60
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
61
+ except:
62
+ pass
63
+
64
+ import pdb
65
+
66
+ logger = logging.get_logger(__name__)
67
+
68
+ _CHECKPOINT_FOR_DOC = "microsoft/phi-2"
69
+ _CONFIG_FOR_DOC = "PhiConfig"
70
+
71
+ PHI_PRETRAINED_MODEL_ARCHIVE_LIST = [
72
+ "microsoft/phi-2",
73
+ # See all Phi models at https://huggingface.co/models?filter=phi
74
+ ]
75
+
76
+
77
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
78
+ def _get_unpad_data(attention_mask):
79
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
80
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
81
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
82
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
83
+ return (
84
+ indices,
85
+ cu_seqlens,
86
+ max_seqlen_in_batch,
87
+ )
88
+
89
+
90
+ # Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->Phi
91
+ class PhiRotaryEmbedding(nn.Module):
92
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
93
+ super().__init__()
94
+
95
+ self.dim = dim
96
+ self.max_position_embeddings = max_position_embeddings
97
+ self.base = base
98
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
99
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
100
+
101
+ # Build here to make `torch.jit.trace` work.
102
+ self._set_cos_sin_cache(
103
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
104
+ )
105
+
106
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
107
+ self.max_seq_len_cached = seq_len
108
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
109
+
110
+ freqs = torch.outer(t, self.inv_freq)
111
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
112
+ emb = torch.cat((freqs, freqs), dim=-1)
113
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
114
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
115
+
116
+ def forward(self, x, seq_len=None):
117
+ # x: [bs, num_attention_heads, seq_len, head_size]
118
+ if seq_len > self.max_seq_len_cached:
119
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
120
+
121
+ return (
122
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
123
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
124
+ )
125
+
126
+
127
+ # Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->Phi
128
+ class PhiLinearScalingRotaryEmbedding(PhiRotaryEmbedding):
129
+ """PhiRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
130
+
131
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
132
+ self.scaling_factor = scaling_factor
133
+ super().__init__(dim, max_position_embeddings, base, device)
134
+
135
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
136
+ self.max_seq_len_cached = seq_len
137
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
138
+ t = t / self.scaling_factor
139
+
140
+ freqs = torch.outer(t, self.inv_freq)
141
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
142
+ emb = torch.cat((freqs, freqs), dim=-1)
143
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
144
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
145
+
146
+
147
+ # Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->Phi
148
+ class PhiDynamicNTKScalingRotaryEmbedding(PhiRotaryEmbedding):
149
+ """PhiRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
150
+
151
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
152
+ self.scaling_factor = scaling_factor
153
+ super().__init__(dim, max_position_embeddings, base, device)
154
+
155
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
156
+ self.max_seq_len_cached = seq_len
157
+
158
+ if seq_len > self.max_position_embeddings:
159
+ base = self.base * (
160
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
161
+ ) ** (self.dim / (self.dim - 2))
162
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
163
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
164
+
165
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
166
+
167
+ freqs = torch.outer(t, self.inv_freq)
168
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
169
+ emb = torch.cat((freqs, freqs), dim=-1)
170
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
171
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
172
+
173
+
174
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
175
+ def rotate_half(x):
176
+ """Rotates half the hidden dims of the input."""
177
+ x1 = x[..., : x.shape[-1] // 2]
178
+ x2 = x[..., x.shape[-1] // 2 :]
179
+ return torch.cat((-x2, x1), dim=-1)
180
+
181
+
182
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
183
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
184
+ """Applies Rotary Position Embedding to the query and key tensors.
185
+
186
+ Args:
187
+ q (`torch.Tensor`): The query tensor.
188
+ k (`torch.Tensor`): The key tensor.
189
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
190
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
191
+ position_ids (`torch.Tensor`):
192
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
193
+ used to pass offsetted position ids when working with a KV-cache.
194
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
195
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
196
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
197
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
198
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
199
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
200
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
201
+ Returns:
202
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
203
+ """
204
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
205
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
206
+ q_embed = (q * cos) + (rotate_half(q) * sin)
207
+ k_embed = (k * cos) + (rotate_half(k) * sin)
208
+ return q_embed, k_embed
209
+
210
+
211
+ # Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->Phi
212
+ class PhiMLP(nn.Module):
213
+ def __init__(self, config):
214
+ super().__init__()
215
+ self.config = config
216
+ self.activation_fn = ACT2FN[config.hidden_act]
217
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
218
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
219
+
220
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
221
+ hidden_states = self.fc1(hidden_states)
222
+ hidden_states = self.activation_fn(hidden_states)
223
+ hidden_states = self.fc2(hidden_states)
224
+ return hidden_states
225
+
226
+
227
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv with llama->phi
228
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
229
+ """
230
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
231
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
232
+ """
233
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
234
+ if n_rep == 1:
235
+ return hidden_states
236
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
237
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
238
+
239
+
240
+ class PhiAttention(nn.Module):
241
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
242
+
243
+ def __init__(self, config: PhiConfig, layer_idx: Optional[int] = None):
244
+ super().__init__()
245
+ self.config = config
246
+ self.layer_idx = layer_idx
247
+ if layer_idx is None:
248
+ logger.warning_once(
249
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
250
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
251
+ "when creating this class."
252
+ )
253
+
254
+ self.attention_dropout = config.attention_dropout
255
+ self.hidden_size = config.hidden_size
256
+ self.num_heads = config.num_attention_heads
257
+ self.head_dim = self.hidden_size // self.num_heads
258
+ self.num_key_value_heads = config.num_key_value_heads
259
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
260
+ self.max_position_embeddings = config.max_position_embeddings
261
+ self.rope_theta = config.rope_theta
262
+ self.partial_rotary_factor = config.partial_rotary_factor
263
+ self.is_causal = True
264
+
265
+ if (self.head_dim * self.num_heads) != self.hidden_size:
266
+ raise ValueError(
267
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
268
+ f" and `num_heads`: {self.num_heads})."
269
+ )
270
+
271
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
272
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
273
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
274
+ self.dense = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=True)
275
+
276
+ self.qk_layernorm = config.qk_layernorm
277
+ if self.qk_layernorm:
278
+ self.q_layernorm = nn.LayerNorm(
279
+ config.hidden_size // self.num_heads, eps=config.layer_norm_eps, elementwise_affine=True
280
+ )
281
+ self.k_layernorm = nn.LayerNorm(
282
+ config.hidden_size // self.num_heads, eps=config.layer_norm_eps, elementwise_affine=True
283
+ )
284
+
285
+ self._init_rope()
286
+
287
+ def _init_rope(self):
288
+ if self.config.rope_scaling is None:
289
+ self.rotary_emb = PhiRotaryEmbedding(
290
+ int(self.partial_rotary_factor * self.head_dim),
291
+ max_position_embeddings=self.max_position_embeddings,
292
+ base=self.rope_theta,
293
+ )
294
+ else:
295
+ scaling_type = self.config.rope_scaling["type"]
296
+ scaling_factor = self.config.rope_scaling["factor"]
297
+ if scaling_type == "linear":
298
+ self.rotary_emb = PhiLinearScalingRotaryEmbedding(
299
+ int(self.partial_rotary_factor * self.head_dim),
300
+ max_position_embeddings=self.max_position_embeddings,
301
+ scaling_factor=scaling_factor,
302
+ base=self.rope_theta,
303
+ )
304
+ elif scaling_type == "dynamic":
305
+ self.rotary_emb = PhiDynamicNTKScalingRotaryEmbedding(
306
+ int(self.partial_rotary_factor * self.head_dim),
307
+ max_position_embeddings=self.max_position_embeddings,
308
+ scaling_factor=scaling_factor,
309
+ base=self.rope_theta,
310
+ )
311
+ else:
312
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
313
+
314
+ # Phi-2 has an attention overflow issue (with FP16) and requires autocast to be disabled
315
+ @torch.autocast("cpu", enabled=False)
316
+ @torch.autocast("cuda", enabled=False)
317
+ def forward(
318
+ self,
319
+ hidden_states: torch.Tensor,
320
+ attention_mask: Optional[torch.Tensor] = None,
321
+ position_ids: Optional[torch.LongTensor] = None,
322
+ past_key_value: Optional[Cache] = None,
323
+ output_attentions: bool = False,
324
+ use_cache: bool = False,
325
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
326
+ bsz, q_len, _ = hidden_states.size()
327
+
328
+ query_states = self.q_proj(hidden_states)
329
+ key_states = self.k_proj(hidden_states)
330
+ value_states = self.v_proj(hidden_states)
331
+
332
+ if self.qk_layernorm:
333
+ query_states = self.q_layernorm(query_states)
334
+ key_states = self.k_layernorm(key_states)
335
+
336
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
337
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
338
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
339
+
340
+ kv_seq_len = key_states.shape[-2]
341
+ if past_key_value is not None:
342
+ if self.layer_idx is None:
343
+ raise ValueError(
344
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
345
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
346
+ "with a layer index."
347
+ )
348
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
349
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
350
+
351
+ # Partial rotary embedding
352
+ query_rot, query_pass = (
353
+ query_states[..., : self.rotary_emb.dim],
354
+ query_states[..., self.rotary_emb.dim :],
355
+ )
356
+ key_rot, key_pass = (
357
+ key_states[..., : self.rotary_emb.dim],
358
+ key_states[..., self.rotary_emb.dim :],
359
+ )
360
+ # [batch_size, seq_length, num_heads, head_dim // config.partial_rotary_factor]
361
+ query_rot, key_rot = apply_rotary_pos_emb(query_rot, key_rot, cos, sin, position_ids)
362
+
363
+ # [batch_size, seq_length, num_heads, head_dim]
364
+ query_states = torch.cat((query_rot, query_pass), dim=-1)
365
+ key_states = torch.cat((key_rot, key_pass), dim=-1)
366
+
367
+ if past_key_value is not None:
368
+ cache_kwargs = {"sin": sin, "cos": cos, "partial_rotation_size": self.rotary_emb.dim}
369
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
370
+
371
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
372
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
373
+
374
+ # Queries and keys upcast to fp32 is required by Phi-2 to avoid overflow
375
+ attn_weights = torch.matmul(
376
+ query_states.to(torch.float32), key_states.to(torch.float32).transpose(2, 3)
377
+ ) / 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.dense(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 PhiFlashAttention2(PhiAttention):
416
+ """
417
+ Phi flash attention module. This module inherits from `PhiAttention` 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
+ # PhiFlashAttention2 attention does not support output_attentions
442
+
443
+ output_attentions = False
444
+
445
+ bsz, q_len, _ = hidden_states.size()
446
+
447
+ query_states = self.q_proj(hidden_states)
448
+ key_states = self.k_proj(hidden_states)
449
+ value_states = self.v_proj(hidden_states)
450
+
451
+ if self.qk_layernorm:
452
+ query_states = self.q_layernorm(query_states)
453
+ key_states = self.k_layernorm(key_states)
454
+
455
+ # Flash attention requires the input to have the shape
456
+ # batch_size x seq_length x head_dim x hidden_dim
457
+ # therefore we just need to keep the original shape
458
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
459
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
460
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
461
+
462
+ kv_seq_len = key_states.shape[-2]
463
+ if past_key_value is not None:
464
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
465
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
466
+
467
+ # Partial rotary embedding
468
+ query_rot, query_pass = (
469
+ query_states[..., : self.rotary_emb.dim],
470
+ query_states[..., self.rotary_emb.dim :],
471
+ )
472
+ key_rot, key_pass = (
473
+ key_states[..., : self.rotary_emb.dim],
474
+ key_states[..., self.rotary_emb.dim :],
475
+ )
476
+ # [batch_size, seq_length, num_heads, head_dim // config.partial_rotary_factor]
477
+ query_rot, key_rot = apply_rotary_pos_emb(query_rot, key_rot, cos, sin, position_ids)
478
+
479
+ # [batch_size, seq_length, num_heads, head_dim]
480
+ query_states = torch.cat((query_rot, query_pass), dim=-1)
481
+ key_states = torch.cat((key_rot, key_pass), dim=-1)
482
+
483
+ if past_key_value is not None:
484
+ cache_kwargs = {"sin": sin, "cos": cos, "partial_rotation_size": self.rotary_emb.dim}
485
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
486
+
487
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
488
+ # to be able to avoid many of these transpose/reshape/view.
489
+ query_states = query_states.transpose(1, 2)
490
+ key_states = key_states.transpose(1, 2)
491
+ value_states = value_states.transpose(1, 2)
492
+
493
+ attn_dropout = self.attention_dropout if self.training else 0.0
494
+
495
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
496
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
497
+ # cast them back in the correct dtype just to be sure everything works as expected.
498
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
499
+ # in fp32.
500
+
501
+ if query_states.dtype == torch.float32:
502
+ if torch.is_autocast_enabled():
503
+ target_dtype = torch.get_autocast_gpu_dtype()
504
+ # Handle the case where the model is quantized
505
+ elif hasattr(self.config, "_pre_quantization_dtype"):
506
+ target_dtype = self.config._pre_quantization_dtype
507
+ else:
508
+ target_dtype = self.q_proj.weight.dtype
509
+
510
+ logger.warning_once(
511
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
512
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
513
+ f" {target_dtype}."
514
+ )
515
+
516
+ query_states = query_states.to(target_dtype)
517
+ key_states = key_states.to(target_dtype)
518
+ value_states = value_states.to(target_dtype)
519
+
520
+ attn_output = self._flash_attention_forward(
521
+ query_states, key_states, value_states, attention_mask, q_len, dropout=attn_dropout, softmax_scale=None
522
+ )
523
+
524
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
525
+ attn_output = self.dense(attn_output)
526
+
527
+ if not output_attentions:
528
+ attn_weights = None
529
+
530
+ return attn_output, attn_weights, past_key_value
531
+
532
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._flash_attention_forward
533
+ def _flash_attention_forward(
534
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
535
+ ):
536
+ """
537
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
538
+ first unpad the input, then computes the attention scores and pad the final attention scores.
539
+
540
+ Args:
541
+ query_states (`torch.Tensor`):
542
+ Input query states to be passed to Flash Attention API
543
+ key_states (`torch.Tensor`):
544
+ Input key states to be passed to Flash Attention API
545
+ value_states (`torch.Tensor`):
546
+ Input value states to be passed to Flash Attention API
547
+ attention_mask (`torch.Tensor`):
548
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
549
+ position of padding tokens and 1 for the position of non-padding tokens.
550
+ dropout (`int`, *optional*):
551
+ Attention dropout
552
+ softmax_scale (`float`, *optional*):
553
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
554
+ """
555
+ if not self._flash_attn_uses_top_left_mask:
556
+ causal = self.is_causal
557
+ else:
558
+ # 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__.
559
+ causal = self.is_causal and query_length != 1
560
+
561
+ # Contains at least one padding token in the sequence
562
+ if attention_mask is not None:
563
+ batch_size = query_states.shape[0]
564
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
565
+ query_states, key_states, value_states, attention_mask, query_length
566
+ )
567
+
568
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
569
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
570
+
571
+ attn_output_unpad = flash_attn_varlen_func(
572
+ query_states,
573
+ key_states,
574
+ value_states,
575
+ cu_seqlens_q=cu_seqlens_q,
576
+ cu_seqlens_k=cu_seqlens_k,
577
+ max_seqlen_q=max_seqlen_in_batch_q,
578
+ max_seqlen_k=max_seqlen_in_batch_k,
579
+ dropout_p=dropout,
580
+ softmax_scale=softmax_scale,
581
+ causal=causal,
582
+ )
583
+
584
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
585
+ else:
586
+ attn_output = flash_attn_func(
587
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
588
+ )
589
+
590
+ return attn_output
591
+
592
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._upad_input
593
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
594
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
595
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
596
+
597
+ key_layer = index_first_axis(
598
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
599
+ )
600
+ value_layer = index_first_axis(
601
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
602
+ )
603
+ if query_length == kv_seq_len:
604
+ query_layer = index_first_axis(
605
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
606
+ )
607
+ cu_seqlens_q = cu_seqlens_k
608
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
609
+ indices_q = indices_k
610
+ elif query_length == 1:
611
+ max_seqlen_in_batch_q = 1
612
+ cu_seqlens_q = torch.arange(
613
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
614
+ ) # There is a memcpy here, that is very bad.
615
+ indices_q = cu_seqlens_q[:-1]
616
+ query_layer = query_layer.squeeze(1)
617
+ else:
618
+ # The -q_len: slice assumes left padding.
619
+ attention_mask = attention_mask[:, -query_length:]
620
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
621
+
622
+ return (
623
+ query_layer,
624
+ key_layer,
625
+ value_layer,
626
+ indices_q,
627
+ (cu_seqlens_q, cu_seqlens_k),
628
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
629
+ )
630
+
631
+
632
+ PHI_ATTENTION_CLASSES = {
633
+ "eager": PhiAttention,
634
+ "flash_attention_2": PhiFlashAttention2,
635
+ }
636
+
637
+
638
+ class PhiDecoderLayer(nn.Module):
639
+ def __init__(self, config: PhiConfig, layer_idx: int):
640
+ super().__init__()
641
+ self.self_attn = PHI_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)
642
+ self.mlp = PhiMLP(config)
643
+ self.input_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
644
+ self.resid_dropout = nn.Dropout(config.resid_pdrop)
645
+
646
+ def forward(
647
+ self,
648
+ hidden_states: torch.Tensor,
649
+ attention_mask: Optional[torch.Tensor] = None,
650
+ position_ids: Optional[torch.LongTensor] = None,
651
+ output_attentions: Optional[bool] = False,
652
+ use_cache: Optional[bool] = False,
653
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
654
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
655
+ """
656
+ Args:
657
+ hidden_states (`torch.FloatTensor`):
658
+ input to the layer of shape `(batch, seq_len, embed_dim)`
659
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
660
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
661
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
662
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
663
+ `[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
664
+ output_attentions (`bool`, *optional*):
665
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
666
+ returned tensors for more detail.
667
+ use_cache (`bool`, *optional*):
668
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
669
+ (see `past_key_values`).
670
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
671
+ """
672
+
673
+ residual = hidden_states
674
+
675
+ hidden_states = self.input_layernorm(hidden_states)
676
+
677
+ # Self Attention
678
+ attn_outputs, self_attn_weights, present_key_value = self.self_attn(
679
+ hidden_states=hidden_states,
680
+ attention_mask=attention_mask,
681
+ position_ids=position_ids,
682
+ past_key_value=past_key_value,
683
+ output_attentions=output_attentions,
684
+ use_cache=use_cache,
685
+ )
686
+ attn_outputs = self.resid_dropout(attn_outputs)
687
+
688
+ feed_forward_hidden_states = self.resid_dropout(self.mlp(hidden_states))
689
+ hidden_states = attn_outputs + feed_forward_hidden_states + residual
690
+ outputs = (hidden_states,)
691
+
692
+ if output_attentions:
693
+ outputs += (self_attn_weights,)
694
+
695
+ if use_cache:
696
+ outputs += (present_key_value,)
697
+
698
+ return outputs
699
+
700
+
701
+ PHI_START_DOCSTRING = r"""
702
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
703
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
704
+ etc.)
705
+
706
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
707
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
708
+ and behavior.
709
+
710
+ Parameters:
711
+ config ([`PhiConfig`]):
712
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
713
+ load the weights associated with the model, only the configuration. Check out the
714
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
715
+ """
716
+
717
+
718
+ @add_start_docstrings(
719
+ "The bare Phi Model outputting raw hidden-states without any specific head on top.",
720
+ PHI_START_DOCSTRING,
721
+ )
722
+ class PhiPreTrainedModel(PreTrainedModel):
723
+ config_class = PhiConfig
724
+ base_model_prefix = "model"
725
+ supports_gradient_checkpointing = True
726
+ _no_split_modules = ["PhiDecoderLayer"]
727
+ _skip_keys_device_placement = "past_key_values"
728
+ _supports_flash_attn_2 = True
729
+ _supports_cache_class = True
730
+
731
+ def _init_weights(self, module):
732
+ std = self.config.initializer_range
733
+ if isinstance(module, nn.Linear):
734
+ module.weight.data.normal_(mean=0.0, std=std)
735
+ if module.bias is not None:
736
+ module.bias.data.zero_()
737
+ elif isinstance(module, nn.Embedding):
738
+ module.weight.data.normal_(mean=0.0, std=std)
739
+ if module.padding_idx is not None:
740
+ module.weight.data[module.padding_idx].zero_()
741
+
742
+
743
+ PHI_INPUTS_DOCSTRING = r"""
744
+ Args:
745
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
746
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
747
+ it.
748
+
749
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
750
+ [`PreTrainedTokenizer.__call__`] for details.
751
+
752
+ [What are input IDs?](../glossary#input-ids)
753
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
754
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
755
+
756
+ - 1 for tokens that are **not masked**,
757
+ - 0 for tokens that are **masked**.
758
+
759
+ [What are attention masks?](../glossary#attention-mask)
760
+
761
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
762
+ [`PreTrainedTokenizer.__call__`] for details.
763
+
764
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
765
+ `past_key_values`).
766
+
767
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
768
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
769
+ information on the default strategy.
770
+
771
+ - 1 indicates the head is **not masked**,
772
+ - 0 indicates the head is **masked**.
773
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
774
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
775
+ config.n_positions - 1]`.
776
+
777
+ [What are position IDs?](../glossary#position-ids)
778
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
779
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
780
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
781
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
782
+
783
+ Two formats are allowed:
784
+ - a [`~cache_utils.Cache`] instance;
785
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
786
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
787
+ cache format.
788
+
789
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
790
+ legacy cache format will be returned.
791
+
792
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
793
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
794
+ of shape `(batch_size, sequence_length)`.
795
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
796
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
797
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
798
+ model's internal embedding lookup matrix.
799
+ use_cache (`bool`, *optional*):
800
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
801
+ `past_key_values`).
802
+ output_attentions (`bool`, *optional*):
803
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
804
+ tensors for more detail.
805
+ output_hidden_states (`bool`, *optional*):
806
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
807
+ more detail.
808
+ return_dict (`bool`, *optional*):
809
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
810
+ """
811
+
812
+
813
+ @add_start_docstrings(
814
+ "The bare Phi Model outputting raw hidden-states without any specific head on top.",
815
+ PHI_START_DOCSTRING,
816
+ )
817
+ class PhiModel(PhiPreTrainedModel):
818
+ """
819
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`PhiDecoderLayer`]
820
+
821
+ Args:
822
+ config: PhiConfig
823
+ """
824
+
825
+ def __init__(self, config: PhiConfig):
826
+ super().__init__(config)
827
+ self.padding_idx = config.pad_token_id
828
+ self.vocab_size = config.vocab_size
829
+
830
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
831
+ self.embed_dropout = nn.Dropout(config.embd_pdrop)
832
+ self.layers = nn.ModuleList(
833
+ [PhiDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
834
+ )
835
+ self.final_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
836
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
837
+
838
+ self.gradient_checkpointing = False
839
+ # Initialize weights and apply final processing
840
+ self.post_init()
841
+
842
+ def get_input_embeddings(self):
843
+ return self.embed_tokens
844
+
845
+ def set_input_embeddings(self, value):
846
+ self.embed_tokens = value
847
+
848
+ @add_start_docstrings_to_model_forward(PHI_INPUTS_DOCSTRING)
849
+ def forward(
850
+ self,
851
+ input_ids: torch.LongTensor = None,
852
+ attention_mask: Optional[torch.Tensor] = None,
853
+ position_ids: Optional[torch.LongTensor] = None,
854
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
855
+ inputs_embeds: Optional[torch.FloatTensor] = None,
856
+ use_cache: Optional[bool] = None,
857
+ output_attentions: Optional[bool] = None,
858
+ output_hidden_states: Optional[bool] = None,
859
+ return_dict: Optional[bool] = None,
860
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
861
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
862
+ output_hidden_states = (
863
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
864
+ )
865
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
866
+
867
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
868
+
869
+ # retrieve input_ids and inputs_embeds
870
+ if input_ids is not None and inputs_embeds is not None:
871
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
872
+ elif input_ids is not None:
873
+ batch_size, seq_length = input_ids.shape[:2]
874
+ elif inputs_embeds is not None:
875
+ batch_size, seq_length = inputs_embeds.shape[:2]
876
+ else:
877
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
878
+
879
+ past_key_values_length = 0
880
+
881
+ if self.gradient_checkpointing and self.training:
882
+ if use_cache:
883
+ logger.warning_once(
884
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
885
+ )
886
+ use_cache = False
887
+
888
+ if use_cache:
889
+ # dbg: uncomment is original
890
+ use_legacy_cache = not isinstance(past_key_values, Cache)
891
+ if use_legacy_cache:
892
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
893
+
894
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
895
+
896
+ if position_ids is None:
897
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
898
+ position_ids = torch.arange(
899
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
900
+ )
901
+ position_ids = position_ids.unsqueeze(0)
902
+
903
+ if inputs_embeds is None:
904
+ inputs_embeds = self.embed_tokens(input_ids)
905
+
906
+ inputs_embeds = self.embed_dropout(inputs_embeds)
907
+
908
+ # Attention mask.
909
+ if self._use_flash_attention_2:
910
+ # 2d mask is passed through the layers
911
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
912
+ else:
913
+ # 4d mask is passed through the layers
914
+ attention_mask = _prepare_4d_causal_attention_mask(
915
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
916
+ )
917
+
918
+ hidden_states = inputs_embeds
919
+
920
+ # decoder layers
921
+ all_hidden_states = () if output_hidden_states else None
922
+ all_self_attns = () if output_attentions else None
923
+ next_decoder_cache = None
924
+
925
+ for decoder_layer in self.layers:
926
+ if output_hidden_states:
927
+ all_hidden_states += (hidden_states,)
928
+
929
+ if self.gradient_checkpointing and self.training:
930
+ layer_outputs = self._gradient_checkpointing_func(
931
+ decoder_layer.__call__,
932
+ hidden_states,
933
+ attention_mask,
934
+ position_ids,
935
+ past_key_values,
936
+ output_attentions,
937
+ )
938
+ else:
939
+ layer_outputs = decoder_layer(
940
+ hidden_states,
941
+ attention_mask=attention_mask,
942
+ position_ids=position_ids,
943
+ past_key_value=past_key_values,
944
+ output_attentions=output_attentions,
945
+ use_cache=use_cache,
946
+ )
947
+
948
+ hidden_states = layer_outputs[0]
949
+
950
+ if use_cache:
951
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
952
+
953
+ if output_attentions:
954
+ all_self_attns += (layer_outputs[1],)
955
+
956
+ hidden_states = self.final_layernorm(hidden_states)
957
+
958
+ # add hidden states from the last decoder layer
959
+ if output_hidden_states:
960
+ all_hidden_states += (hidden_states,)
961
+
962
+ next_cache = None
963
+ if use_cache:
964
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
965
+ if not return_dict:
966
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
967
+ return BaseModelOutputWithPast(
968
+ last_hidden_state=hidden_states,
969
+ past_key_values=next_cache,
970
+ hidden_states=all_hidden_states,
971
+ attentions=all_self_attns,
972
+ )
973
+
974
+
975
+ class PhiForCausalLM(PhiPreTrainedModel):
976
+ _tied_weights_keys = ["lm_head.weight"]
977
+
978
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.__init__ with Llama->Phi,bias=False->bias=True
979
+ def __init__(self, config):
980
+ super().__init__(config)
981
+ self.model = PhiModel(config)
982
+ self.vocab_size = config.vocab_size
983
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=True)
984
+
985
+ # Initialize weights and apply final processing
986
+ self.post_init()
987
+
988
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_input_embeddings
989
+ def get_input_embeddings(self):
990
+ return self.model.embed_tokens
991
+
992
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_input_embeddings
993
+ def set_input_embeddings(self, value):
994
+ self.model.embed_tokens = value
995
+
996
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_output_embeddings
997
+ def get_output_embeddings(self):
998
+ return self.lm_head
999
+
1000
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_output_embeddings
1001
+ def set_output_embeddings(self, new_embeddings):
1002
+ self.lm_head = new_embeddings
1003
+
1004
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_decoder
1005
+ def set_decoder(self, decoder):
1006
+ self.model = decoder
1007
+
1008
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_decoder
1009
+ def get_decoder(self):
1010
+ return self.model
1011
+
1012
+ @add_start_docstrings_to_model_forward(PHI_INPUTS_DOCSTRING)
1013
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1014
+ def forward(
1015
+ self,
1016
+ input_ids: torch.LongTensor = None,
1017
+ attention_mask: Optional[torch.Tensor] = None,
1018
+ position_ids: Optional[torch.LongTensor] = None,
1019
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1020
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1021
+ labels: Optional[torch.LongTensor] = None,
1022
+ use_cache: Optional[bool] = None,
1023
+ output_attentions: Optional[bool] = None,
1024
+ output_hidden_states: Optional[bool] = None,
1025
+ return_dict: Optional[bool] = None,
1026
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1027
+ r"""
1028
+ Args:
1029
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1030
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1031
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1032
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1033
+
1034
+ Returns:
1035
+
1036
+ Example:
1037
+
1038
+ ```python
1039
+ >>> from transformers import AutoTokenizer, PhiForCausalLM
1040
+
1041
+ >>> model = PhiForCausalLM.from_pretrained("microsoft/phi-1")
1042
+ >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-1")
1043
+
1044
+ >>> prompt = "This is an example script ."
1045
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1046
+
1047
+ >>> # Generate
1048
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1049
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1050
+ 'This is an example script .\n\n\n\nfrom typing import List\n\ndef find_most_common_letter(words: List[str'
1051
+ ```"""
1052
+
1053
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1054
+ output_hidden_states = (
1055
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1056
+ )
1057
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1058
+
1059
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1060
+ outputs = self.model(
1061
+ input_ids=input_ids,
1062
+ attention_mask=attention_mask,
1063
+ position_ids=position_ids,
1064
+ past_key_values=past_key_values,
1065
+ inputs_embeds=inputs_embeds,
1066
+ use_cache=use_cache,
1067
+ output_attentions=output_attentions,
1068
+ output_hidden_states=output_hidden_states,
1069
+ return_dict=return_dict,
1070
+ )
1071
+
1072
+
1073
+ # concat the feature back?
1074
+
1075
+ hidden_states = outputs[0]
1076
+ logits = self.lm_head(hidden_states)
1077
+ logits = logits.float()
1078
+
1079
+ loss = None
1080
+ if labels is not None:
1081
+ # Shift so that tokens < n predict n
1082
+ shift_logits = logits[..., :-1, :].contiguous()
1083
+ shift_labels = labels[..., 1:].contiguous()
1084
+ # Flatten the tokens
1085
+ loss_fct = CrossEntropyLoss()
1086
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1087
+ shift_labels = shift_labels.view(-1)
1088
+ # Enable model parallelism
1089
+ shift_labels = shift_labels.to(shift_logits.device)
1090
+ loss = loss_fct(shift_logits, shift_labels)
1091
+
1092
+ if not return_dict:
1093
+ output = (logits,) + outputs[1:]
1094
+ return (loss,) + output if loss is not None else output
1095
+
1096
+ return CausalLMOutputWithPast(
1097
+ loss=loss,
1098
+ logits=logits,
1099
+ past_key_values=outputs.past_key_values,
1100
+ hidden_states=outputs.hidden_states,
1101
+ attentions=outputs.attentions,
1102
+ )
1103
+
1104
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.prepare_inputs_for_generation
1105
+ def prepare_inputs_for_generation(
1106
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1107
+ ):
1108
+ if past_key_values is not None:
1109
+ if isinstance(past_key_values, Cache):
1110
+ cache_length = past_key_values.get_seq_length()
1111
+ past_length = past_key_values.seen_tokens
1112
+ max_cache_length = past_key_values.get_max_length()
1113
+ else:
1114
+ cache_length = past_length = past_key_values[0][0].shape[2]
1115
+ max_cache_length = None
1116
+
1117
+ # Keep only the unprocessed tokens:
1118
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1119
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1120
+ # input)
1121
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1122
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1123
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1124
+ # input_ids based on the past_length.
1125
+ elif past_length < input_ids.shape[1]:
1126
+ input_ids = input_ids[:, past_length:]
1127
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1128
+
1129
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1130
+ if (
1131
+ max_cache_length is not None
1132
+ and attention_mask is not None
1133
+ and cache_length + input_ids.shape[1] > max_cache_length
1134
+ ):
1135
+ attention_mask = attention_mask[:, -max_cache_length:]
1136
+
1137
+ position_ids = kwargs.get("position_ids", None)
1138
+ if attention_mask is not None and position_ids is None:
1139
+ # create position_ids on the fly for batch generation
1140
+ position_ids = attention_mask.long().cumsum(-1) - 1
1141
+ position_ids.masked_fill_(attention_mask == 0, 1)
1142
+ if past_key_values:
1143
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1144
+
1145
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1146
+ if inputs_embeds is not None and past_key_values is None:
1147
+ model_inputs = {"inputs_embeds": inputs_embeds}
1148
+ else:
1149
+ model_inputs = {"input_ids": input_ids}
1150
+
1151
+ model_inputs.update(
1152
+ {
1153
+ "position_ids": position_ids,
1154
+ "past_key_values": past_key_values,
1155
+ "use_cache": kwargs.get("use_cache"),
1156
+ "attention_mask": attention_mask,
1157
+ }
1158
+ )
1159
+ return model_inputs
1160
+
1161
+ @staticmethod
1162
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM._reorder_cache
1163
+ def _reorder_cache(past_key_values, beam_idx):
1164
+ reordered_past = ()
1165
+ for layer_past in past_key_values:
1166
+ reordered_past += (
1167
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1168
+ )
1169
+ return reordered_past
1170
+
1171
+
1172
+ @add_start_docstrings(
1173
+ """
1174
+ The PhiModel with a sequence classification head on top (linear layer).
1175
+
1176
+ [`PhiForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1177
+ (e.g. GPT-2) do.
1178
+
1179
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1180
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1181
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1182
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1183
+ each row of the batch).
1184
+ """,
1185
+ PHI_START_DOCSTRING,
1186
+ )
1187
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with LLAMA->PHI,Llama->Phi with self.transformer->self.model, transformer_outputs->model_outputs
1188
+ class PhiForSequenceClassification(PhiPreTrainedModel):
1189
+ def __init__(self, config):
1190
+ super().__init__(config)
1191
+ self.num_labels = config.num_labels
1192
+ self.model = PhiModel(config)
1193
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1194
+
1195
+ # Initialize weights and apply final processing
1196
+ self.post_init()
1197
+
1198
+ def get_input_embeddings(self):
1199
+ return self.model.embed_tokens
1200
+
1201
+ def set_input_embeddings(self, value):
1202
+ self.model.embed_tokens = value
1203
+
1204
+ @add_start_docstrings_to_model_forward(PHI_INPUTS_DOCSTRING)
1205
+ def forward(
1206
+ self,
1207
+ input_ids: torch.LongTensor = None,
1208
+ attention_mask: Optional[torch.Tensor] = None,
1209
+ position_ids: Optional[torch.LongTensor] = None,
1210
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1211
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1212
+ labels: Optional[torch.LongTensor] = None,
1213
+ use_cache: Optional[bool] = None,
1214
+ output_attentions: Optional[bool] = None,
1215
+ output_hidden_states: Optional[bool] = None,
1216
+ return_dict: Optional[bool] = None,
1217
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1218
+ r"""
1219
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1220
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1221
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1222
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1223
+ """
1224
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1225
+
1226
+ model_outputs = self.model(
1227
+ input_ids,
1228
+ attention_mask=attention_mask,
1229
+ position_ids=position_ids,
1230
+ past_key_values=past_key_values,
1231
+ inputs_embeds=inputs_embeds,
1232
+ use_cache=use_cache,
1233
+ output_attentions=output_attentions,
1234
+ output_hidden_states=output_hidden_states,
1235
+ return_dict=return_dict,
1236
+ )
1237
+ hidden_states = model_outputs[0]
1238
+ logits = self.score(hidden_states)
1239
+
1240
+ if input_ids is not None:
1241
+ batch_size = input_ids.shape[0]
1242
+ else:
1243
+ batch_size = inputs_embeds.shape[0]
1244
+
1245
+ if self.config.pad_token_id is None and batch_size != 1:
1246
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1247
+ if self.config.pad_token_id is None:
1248
+ sequence_lengths = -1
1249
+ else:
1250
+ if input_ids is not None:
1251
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1252
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1253
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1254
+ sequence_lengths = sequence_lengths.to(logits.device)
1255
+ else:
1256
+ sequence_lengths = -1
1257
+
1258
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1259
+
1260
+ loss = None
1261
+ if labels is not None:
1262
+ labels = labels.to(logits.device)
1263
+ if self.config.problem_type is None:
1264
+ if self.num_labels == 1:
1265
+ self.config.problem_type = "regression"
1266
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1267
+ self.config.problem_type = "single_label_classification"
1268
+ else:
1269
+ self.config.problem_type = "multi_label_classification"
1270
+
1271
+ if self.config.problem_type == "regression":
1272
+ loss_fct = MSELoss()
1273
+ if self.num_labels == 1:
1274
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1275
+ else:
1276
+ loss = loss_fct(pooled_logits, labels)
1277
+ elif self.config.problem_type == "single_label_classification":
1278
+ loss_fct = CrossEntropyLoss()
1279
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1280
+ elif self.config.problem_type == "multi_label_classification":
1281
+ loss_fct = BCEWithLogitsLoss()
1282
+ loss = loss_fct(pooled_logits, labels)
1283
+ if not return_dict:
1284
+ output = (pooled_logits,) + model_outputs[1:]
1285
+ return ((loss,) + output) if loss is not None else output
1286
+
1287
+ return SequenceClassifierOutputWithPast(
1288
+ loss=loss,
1289
+ logits=pooled_logits,
1290
+ past_key_values=model_outputs.past_key_values,
1291
+ hidden_states=model_outputs.hidden_states,
1292
+ attentions=model_outputs.attentions,
1293
+ )
1294
+
1295
+
1296
+ @add_start_docstrings(
1297
+ """
1298
+ PhiModel with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1299
+ Named-Entity-Recognition (NER) tasks.
1300
+ """,
1301
+ PHI_START_DOCSTRING,
1302
+ )
1303
+ # Copied from transformers.models.mpt.modeling_mpt.MptForTokenClassification with MPT->PHI,Mpt->Phi,self.transformer->self.model,transformer_outputs->model_outputs
1304
+ class PhiForTokenClassification(PhiPreTrainedModel):
1305
+ def __init__(self, config: PhiConfig):
1306
+ super().__init__(config)
1307
+ self.num_labels = config.num_labels
1308
+
1309
+ self.model = PhiModel(config)
1310
+ if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
1311
+ classifier_dropout = config.classifier_dropout
1312
+ elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
1313
+ classifier_dropout = config.hidden_dropout
1314
+ else:
1315
+ classifier_dropout = 0.1
1316
+ self.dropout = nn.Dropout(classifier_dropout)
1317
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1318
+
1319
+ # Initialize weights and apply final processing
1320
+ self.post_init()
1321
+
1322
+ @add_start_docstrings_to_model_forward(PHI_INPUTS_DOCSTRING)
1323
+ @add_code_sample_docstrings(
1324
+ checkpoint=_CHECKPOINT_FOR_DOC,
1325
+ output_type=TokenClassifierOutput,
1326
+ config_class=_CONFIG_FOR_DOC,
1327
+ )
1328
+ def forward(
1329
+ self,
1330
+ input_ids: Optional[torch.LongTensor] = None,
1331
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1332
+ attention_mask: Optional[torch.Tensor] = None,
1333
+ inputs_embeds: Optional[torch.Tensor] = None,
1334
+ labels: Optional[torch.Tensor] = None,
1335
+ use_cache: Optional[bool] = None,
1336
+ output_attentions: Optional[bool] = None,
1337
+ output_hidden_states: Optional[bool] = None,
1338
+ return_dict: Optional[bool] = None,
1339
+ **deprecated_arguments,
1340
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
1341
+ r"""
1342
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1343
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1344
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1345
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1346
+ """
1347
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1348
+
1349
+ model_outputs = self.model(
1350
+ input_ids,
1351
+ past_key_values=past_key_values,
1352
+ attention_mask=attention_mask,
1353
+ inputs_embeds=inputs_embeds,
1354
+ use_cache=use_cache,
1355
+ output_attentions=output_attentions,
1356
+ output_hidden_states=output_hidden_states,
1357
+ return_dict=return_dict,
1358
+ )
1359
+
1360
+ hidden_states = model_outputs[0]
1361
+ hidden_states = self.dropout(hidden_states)
1362
+ logits = self.classifier(hidden_states)
1363
+
1364
+ loss = None
1365
+ if labels is not None:
1366
+ # move labels to correct device to enable model parallelism
1367
+ labels = labels.to(logits.device)
1368
+ batch_size, seq_length = labels.shape
1369
+ loss_fct = CrossEntropyLoss()
1370
+ loss = loss_fct(
1371
+ logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length)
1372
+ )
1373
+
1374
+ if not return_dict:
1375
+ output = (logits,) + model_outputs[2:]
1376
+ return ((loss,) + output) if loss is not None else output
1377
+
1378
+ return TokenClassifierOutput(
1379
+ loss=loss,
1380
+ logits=logits,
1381
+ hidden_states=model_outputs.hidden_states,
1382
+ attentions=model_outputs.attentions,
1383
+ )