Q-bert commited on
Commit
0c5c972
·
1 Parent(s): 4177a0d

Create modeling_xglm.py

Browse files
Files changed (1) hide show
  1. modeling_xglm.py +948 -0
modeling_xglm.py ADDED
@@ -0,0 +1,948 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Fairseq Authors 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
+ """ PyTorch XGLM model."""
16
+
17
+
18
+ import math
19
+ from typing import List, Optional, Tuple, Union
20
+
21
+ import torch
22
+ import torch.utils.checkpoint
23
+ from torch import nn
24
+ from torch.nn import CrossEntropyLoss
25
+
26
+ from transformers.activations import ACT2FN
27
+ from transformers.modeling_attn_mask_utils import _prepare_4d_attention_mask, _prepare_4d_causal_attention_mask
28
+ from transformers.modeling_outputs import BaseModelOutputWithPastAndCrossAttentions, CausalLMOutputWithCrossAttentions ,SequenceClassifierOutputWithPast
29
+ from transformers.modeling_utils import PreTrainedModel
30
+ from transformers.utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
31
+ from transformers.configuration_xglm import XGLMConfig
32
+
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+ _CHECKPOINT_FOR_DOC = "facebook/xglm-564M"
37
+ _CONFIG_FOR_DOC = "XGLMConfig"
38
+
39
+
40
+ XGLM_PRETRAINED_MODEL_ARCHIVE_LIST = [
41
+ "facebook/xglm-564M",
42
+ # See all XGLM models at https://huggingface.co/models?filter=xglm
43
+ ]
44
+
45
+ XGLM_START_DOCSTRING = r"""
46
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
47
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
48
+ etc.)
49
+
50
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
51
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
52
+ and behavior.
53
+
54
+ Parameters:
55
+ config ([`XGLMConfig`]):
56
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
57
+ load the weights associated with the model, only the configuration. Check out the
58
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
59
+ """
60
+
61
+ XGLM_INPUTS_DOCSTRING = r"""
62
+ Args:
63
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
64
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
65
+ it.
66
+
67
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
68
+ [`PreTrainedTokenizer.__call__`] for details.
69
+
70
+ [What are input IDs?](../glossary#input-ids)
71
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
72
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
73
+
74
+ - 1 for tokens that are **not masked**,
75
+ - 0 for tokens that are **masked**.
76
+
77
+ [What are attention masks?](../glossary#attention-mask)
78
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
79
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
80
+ config.max_position_embeddings - 1]`.
81
+
82
+ [What are position IDs?](../glossary#position-ids)
83
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
84
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention of
85
+ the decoder.
86
+ encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
87
+ Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
88
+ selected in `[0, 1]`:
89
+
90
+ - 1 for tokens that are **not masked**,
91
+ - 0 for tokens that are **masked**.
92
+
93
+ [What are attention masks?](../glossary#attention-mask)
94
+ head_mask (`torch.Tensor` of shape `(num_layers, attention_heads)`, *optional*):
95
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
96
+
97
+ - 1 indicates the head is **not masked**,
98
+ - 0 indicates the head is **masked**.
99
+
100
+ cross_attn_head_mask (`torch.Tensor` of shape `(num_layers, attention_heads)`, *optional*):
101
+ Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
102
+
103
+ - 1 indicates the head is **not masked**,
104
+ - 0 indicates the head is **masked**.
105
+
106
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
107
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
108
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
109
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
110
+
111
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
112
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
113
+
114
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
115
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
116
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`. inputs_embeds (`torch.FloatTensor` of shape
117
+ `(batch_size, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing `input_ids` you
118
+ can choose to directly pass an embedded representation. This is useful if you want more control over how to
119
+ convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix.
120
+ output_attentions (`bool`, *optional*):
121
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
122
+ tensors for more detail.
123
+ output_hidden_states (`bool`, *optional*):
124
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
125
+ more detail.
126
+ return_dict (`bool`, *optional*):
127
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
128
+ """
129
+
130
+
131
+ class XGLMSinusoidalPositionalEmbedding(nn.Module):
132
+ """This module produces sinusoidal positional embeddings of any length."""
133
+
134
+ def __init__(self, num_positions: int, embedding_dim: int, padding_idx: Optional[int] = None):
135
+ super().__init__()
136
+ self.offset = 2
137
+ self.embedding_dim = embedding_dim
138
+ self.padding_idx = padding_idx
139
+ self.make_weights(num_positions + self.offset, embedding_dim, padding_idx)
140
+
141
+ def make_weights(self, num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None):
142
+ emb_weights = self.get_embedding(num_embeddings, embedding_dim, padding_idx)
143
+ if hasattr(self, "weights"):
144
+ # in forward put the weights on the correct dtype and device of the param
145
+ emb_weights = emb_weights.to(dtype=self.weights.dtype, device=self.weights.device)
146
+
147
+ self.register_buffer("weights", emb_weights, persistent=False)
148
+
149
+ @staticmethod
150
+ def get_embedding(num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None):
151
+ """
152
+ Build sinusoidal embeddings.
153
+
154
+ This matches the implementation in tensor2tensor, but differs slightly from the description in Section 3.5 of
155
+ "Attention Is All You Need".
156
+ """
157
+ half_dim = embedding_dim // 2
158
+ emb = math.log(10000) / (half_dim - 1)
159
+ emb = torch.exp(torch.arange(half_dim, dtype=torch.float) * -emb)
160
+ emb = torch.arange(num_embeddings, dtype=torch.float).unsqueeze(1) * emb.unsqueeze(0)
161
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1).view(num_embeddings, -1)
162
+ if embedding_dim % 2 == 1:
163
+ # zero pad
164
+ emb = torch.cat([emb, torch.zeros(num_embeddings, 1)], dim=1)
165
+ if padding_idx is not None:
166
+ emb[padding_idx, :] = 0
167
+
168
+ return emb.to(torch.get_default_dtype())
169
+
170
+ @torch.no_grad()
171
+ def forward(self, position_ids: torch.Tensor = None, past_key_values_length: int = 0):
172
+ bsz, seq_len = position_ids.size()
173
+ position_ids += self.offset
174
+
175
+ # Expand embeddings if needed. `position_ids.max()` is NOT used to keep torch.fx compatibility.
176
+ max_pos = 2 + seq_len + past_key_values_length
177
+ if max_pos > self.weights.size(0):
178
+ self.make_weights(max_pos, self.embedding_dim, self.padding_idx)
179
+
180
+ return self.weights.index_select(0, position_ids.view(-1)).view(bsz, seq_len, self.weights.shape[-1]).detach()
181
+
182
+
183
+ class XGLMAttention(nn.Module):
184
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
185
+
186
+ def __init__(
187
+ self,
188
+ embed_dim: int,
189
+ num_heads: int,
190
+ dropout: float = 0.0,
191
+ is_decoder: bool = False,
192
+ bias: bool = True,
193
+ ):
194
+ super().__init__()
195
+ self.embed_dim = embed_dim
196
+ self.num_heads = num_heads
197
+ self.dropout = dropout
198
+ self.head_dim = embed_dim // num_heads
199
+
200
+ if (self.head_dim * num_heads) != self.embed_dim:
201
+ raise ValueError(
202
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
203
+ f" and `num_heads`: {num_heads})."
204
+ )
205
+ self.scaling = self.head_dim**-0.5
206
+ self.is_decoder = is_decoder
207
+
208
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
209
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
210
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
211
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
212
+
213
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
214
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
215
+
216
+ def forward(
217
+ self,
218
+ hidden_states: torch.Tensor,
219
+ key_value_states: Optional[torch.Tensor] = None,
220
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
221
+ attention_mask: Optional[torch.Tensor] = None,
222
+ layer_head_mask: Optional[torch.Tensor] = None,
223
+ output_attentions: bool = False,
224
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
225
+ """Input shape: Batch x Time x Channel"""
226
+
227
+ # if key_value_states are provided this layer is used as a cross-attention layer
228
+ # for the decoder
229
+ is_cross_attention = key_value_states is not None
230
+
231
+ bsz, tgt_len, _ = hidden_states.size()
232
+
233
+ # get query proj
234
+ query_states = self.q_proj(hidden_states) * self.scaling
235
+ # get key, value proj
236
+ if is_cross_attention and past_key_value is not None:
237
+ # reuse k,v, cross_attentions
238
+ key_states = past_key_value[0]
239
+ value_states = past_key_value[1]
240
+ elif is_cross_attention:
241
+ # cross_attentions
242
+ key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
243
+ value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
244
+ elif past_key_value is not None:
245
+ # reuse k, v, self_attention
246
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
247
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
248
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
249
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
250
+ else:
251
+ # self_attention
252
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
253
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
254
+
255
+ if self.is_decoder:
256
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
257
+ # Further calls to cross_attention layer can then reuse all cross-attention
258
+ # key/value_states (first "if" case)
259
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
260
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
261
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
262
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
263
+ past_key_value = (key_states, value_states)
264
+
265
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
266
+ query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
267
+ key_states = key_states.view(*proj_shape)
268
+ value_states = value_states.view(*proj_shape)
269
+
270
+ src_len = key_states.size(1)
271
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
272
+
273
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
274
+ raise ValueError(
275
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
276
+ f" {attn_weights.size()}"
277
+ )
278
+
279
+ if attention_mask is not None:
280
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
281
+ raise ValueError(
282
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
283
+ )
284
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
285
+ attn_weights = torch.max(
286
+ attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min, device=attn_weights.device)
287
+ )
288
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
289
+
290
+ # upcast to fp32 if the weights are in fp16. Please see https://github.com/huggingface/transformers/pull/17437
291
+ if attn_weights.dtype == torch.float16:
292
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(torch.float16)
293
+ else:
294
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
295
+
296
+ if layer_head_mask is not None:
297
+ if layer_head_mask.size() != (self.num_heads,):
298
+ raise ValueError(
299
+ f"Head mask for a single layer should be of size {(self.num_heads,)}, but is"
300
+ f" {layer_head_mask.size()}"
301
+ )
302
+ attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
303
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
304
+
305
+ if output_attentions:
306
+ # this operation is a bit awkward, but it's required to
307
+ # make sure that attn_weights keeps its gradient.
308
+ # In order to do so, attn_weights have to be reshaped
309
+ # twice and have to be reused in the following
310
+ attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
311
+ attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
312
+ else:
313
+ attn_weights_reshaped = None
314
+
315
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
316
+
317
+ attn_output = torch.bmm(attn_probs, value_states)
318
+
319
+ if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
320
+ raise ValueError(
321
+ f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
322
+ f" {attn_output.size()}"
323
+ )
324
+
325
+ attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
326
+ attn_output = attn_output.transpose(1, 2)
327
+
328
+ # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
329
+ # partitioned aross GPUs when using tensor-parallelism.
330
+ attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
331
+
332
+ attn_output = self.out_proj(attn_output)
333
+
334
+ return attn_output, attn_weights_reshaped, past_key_value
335
+
336
+
337
+ class XGLMDecoderLayer(nn.Module):
338
+ def __init__(self, config: XGLMConfig):
339
+ super().__init__()
340
+ self.embed_dim = config.d_model
341
+
342
+ self.self_attn = XGLMAttention(
343
+ embed_dim=self.embed_dim,
344
+ num_heads=config.attention_heads,
345
+ dropout=config.attention_dropout,
346
+ is_decoder=True,
347
+ )
348
+ self.dropout = config.dropout
349
+ self.activation_fn = ACT2FN[config.activation_function]
350
+ self.activation_dropout = config.activation_dropout
351
+
352
+ if config.add_cross_attention:
353
+ self.encoder_attn = XGLMAttention(
354
+ embed_dim=self.embed_dim,
355
+ num_heads=config.attention_heads,
356
+ dropout=config.attention_dropout,
357
+ is_decoder=True,
358
+ )
359
+ self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
360
+
361
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
362
+ self.fc1 = nn.Linear(self.embed_dim, config.ffn_dim)
363
+ self.fc2 = nn.Linear(config.ffn_dim, self.embed_dim)
364
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
365
+
366
+ # Copied from transformers.models.mbart.modeling_mbart.MBartDecoderLayer.forward
367
+ def forward(
368
+ self,
369
+ hidden_states: torch.Tensor,
370
+ attention_mask: Optional[torch.Tensor] = None,
371
+ encoder_hidden_states: Optional[torch.Tensor] = None,
372
+ encoder_attention_mask: Optional[torch.Tensor] = None,
373
+ layer_head_mask: Optional[torch.Tensor] = None,
374
+ cross_attn_layer_head_mask: Optional[torch.Tensor] = None,
375
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
376
+ output_attentions: Optional[bool] = False,
377
+ use_cache: Optional[bool] = True,
378
+ ) -> torch.Tensor:
379
+ """
380
+ Args:
381
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
382
+ attention_mask (`torch.FloatTensor`): attention mask of size
383
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
384
+ encoder_hidden_states (`torch.FloatTensor`):
385
+ cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
386
+ encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
387
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
388
+ layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
389
+ `(encoder_attention_heads,)`.
390
+ cross_attn_layer_head_mask (`torch.FloatTensor`): mask for cross-attention heads in a given layer of
391
+ size `(decoder_attention_heads,)`.
392
+ past_key_value (`Tuple(torch.FloatTensor)`): cached past key and value projection states
393
+ output_attentions (`bool`, *optional*):
394
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
395
+ returned tensors for more detail.
396
+ """
397
+ residual = hidden_states
398
+ hidden_states = self.self_attn_layer_norm(hidden_states)
399
+
400
+ # Self Attention
401
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
402
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
403
+ # add present self-attn cache to positions 1,2 of present_key_value tuple
404
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
405
+ hidden_states=hidden_states,
406
+ past_key_value=self_attn_past_key_value,
407
+ attention_mask=attention_mask,
408
+ layer_head_mask=layer_head_mask,
409
+ output_attentions=output_attentions,
410
+ )
411
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
412
+ hidden_states = residual + hidden_states
413
+
414
+ # Cross-Attention Block
415
+ cross_attn_present_key_value = None
416
+ cross_attn_weights = None
417
+ if encoder_hidden_states is not None:
418
+ residual = hidden_states
419
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
420
+
421
+ # cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
422
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
423
+ hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn(
424
+ hidden_states=hidden_states,
425
+ key_value_states=encoder_hidden_states,
426
+ attention_mask=encoder_attention_mask,
427
+ layer_head_mask=cross_attn_layer_head_mask,
428
+ past_key_value=cross_attn_past_key_value,
429
+ output_attentions=output_attentions,
430
+ )
431
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
432
+ hidden_states = residual + hidden_states
433
+
434
+ # add cross-attn to positions 3,4 of present_key_value tuple
435
+ present_key_value = present_key_value + cross_attn_present_key_value
436
+
437
+ # Fully Connected
438
+ residual = hidden_states
439
+ hidden_states = self.final_layer_norm(hidden_states)
440
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
441
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
442
+ hidden_states = self.fc2(hidden_states)
443
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
444
+ hidden_states = residual + hidden_states
445
+
446
+ outputs = (hidden_states,)
447
+
448
+ if output_attentions:
449
+ outputs += (self_attn_weights, cross_attn_weights)
450
+
451
+ if use_cache:
452
+ outputs += (present_key_value,)
453
+
454
+ return outputs
455
+
456
+
457
+ class XGLMPreTrainedModel(PreTrainedModel):
458
+ config_class = XGLMConfig
459
+ base_model_prefix = "model"
460
+ supports_gradient_checkpointing = True
461
+ _no_split_modules = ["XGLMDecoderLayer"]
462
+
463
+ def _init_weights(self, module):
464
+ std = self.config.init_std
465
+ if isinstance(module, nn.Linear):
466
+ module.weight.data.normal_(mean=0.0, std=std)
467
+ if module.bias is not None:
468
+ module.bias.data.zero_()
469
+ elif isinstance(module, nn.Embedding):
470
+ module.weight.data.normal_(mean=0.0, std=std)
471
+ if module.padding_idx is not None:
472
+ module.weight.data[module.padding_idx].zero_()
473
+
474
+
475
+ @add_start_docstrings(
476
+ "The bare XGLM Model transformer outputting raw hidden-states without any specific head on top.",
477
+ XGLM_START_DOCSTRING,
478
+ )
479
+ class XGLMModel(XGLMPreTrainedModel):
480
+ """
481
+ Transformer decoder consisting of *config.num_layers* layers. Each layer is a [`XGLMDecoderLayer`]
482
+
483
+ Args:
484
+ config: XGLMConfig
485
+ embed_tokens (nn.Embedding): output embedding
486
+ """
487
+
488
+ def __init__(self, config: XGLMConfig, embed_tokens: Optional[nn.Embedding] = None):
489
+ super().__init__(config)
490
+ self.dropout = config.dropout
491
+ self.layerdrop = config.layerdrop
492
+ self.padding_idx = config.pad_token_id
493
+ self.max_target_positions = config.max_position_embeddings
494
+ self.embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
495
+
496
+ if embed_tokens is not None:
497
+ self.embed_tokens = embed_tokens
498
+ else:
499
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model, self.padding_idx)
500
+
501
+ self.embed_positions = XGLMSinusoidalPositionalEmbedding(
502
+ config.max_position_embeddings,
503
+ config.d_model,
504
+ config.pad_token_id,
505
+ )
506
+ self.layers = nn.ModuleList([XGLMDecoderLayer(config) for _ in range(config.num_layers)])
507
+ self.layer_norm = nn.LayerNorm(config.d_model)
508
+
509
+ self.gradient_checkpointing = False
510
+ # Initialize weights and apply final processing
511
+ self.post_init()
512
+
513
+ def get_input_embeddings(self):
514
+ return self.embed_tokens
515
+
516
+ def set_input_embeddings(self, value):
517
+ self.embed_tokens = value
518
+
519
+ @add_start_docstrings_to_model_forward(XGLM_INPUTS_DOCSTRING)
520
+ @add_code_sample_docstrings(
521
+ checkpoint=_CHECKPOINT_FOR_DOC,
522
+ output_type=BaseModelOutputWithPastAndCrossAttentions,
523
+ config_class=_CONFIG_FOR_DOC,
524
+ )
525
+ def forward(
526
+ self,
527
+ input_ids: Optional[torch.Tensor] = None,
528
+ attention_mask: Optional[torch.Tensor] = None,
529
+ position_ids: Optional[torch.Tensor] = None,
530
+ encoder_hidden_states: Optional[torch.Tensor] = None,
531
+ encoder_attention_mask: Optional[torch.Tensor] = None,
532
+ head_mask: Optional[torch.Tensor] = None,
533
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
534
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
535
+ inputs_embeds: Optional[torch.Tensor] = None,
536
+ use_cache: Optional[bool] = None,
537
+ output_attentions: Optional[bool] = None,
538
+ output_hidden_states: Optional[bool] = None,
539
+ return_dict: Optional[bool] = None,
540
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
541
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
542
+ output_hidden_states = (
543
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
544
+ )
545
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
546
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
547
+
548
+ # retrieve input_ids and inputs_embeds
549
+ if input_ids is not None and inputs_embeds is not None:
550
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
551
+ elif input_ids is not None:
552
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
553
+ input_shape = input_ids.size()
554
+ input_ids = input_ids.view(-1, input_shape[-1])
555
+ elif inputs_embeds is not None:
556
+ input_shape = inputs_embeds.size()[:-1]
557
+ else:
558
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
559
+
560
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
561
+
562
+ if position_ids is None:
563
+ position_ids = torch.arange(
564
+ past_key_values_length,
565
+ input_shape[-1] + past_key_values_length,
566
+ dtype=torch.long,
567
+ device=input_ids.device if input_ids is not None else inputs_embeds.device,
568
+ )
569
+ position_ids = position_ids.unsqueeze(0)
570
+
571
+ if inputs_embeds is None:
572
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
573
+
574
+ attention_mask = _prepare_4d_causal_attention_mask(
575
+ attention_mask, input_shape, inputs_embeds, past_key_values_length
576
+ )
577
+
578
+ # expand encoder attention mask
579
+ if encoder_hidden_states is not None and encoder_attention_mask is not None:
580
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
581
+ encoder_attention_mask = _prepare_4d_attention_mask(
582
+ encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
583
+ )
584
+
585
+ hidden_states = inputs_embeds + self.embed_positions(position_ids, past_key_values_length)
586
+ hidden_states = nn.functional.dropout(hidden_states, p=float(self.dropout), training=self.training)
587
+
588
+ if self.gradient_checkpointing and self.training:
589
+ if use_cache:
590
+ logger.warning_once(
591
+ "`use_cache = True` is incompatible with gradient checkpointing`. Setting `use_cache ="
592
+ " False`..."
593
+ )
594
+ use_cache = False
595
+
596
+ # decoder layers
597
+ all_hidden_states = () if output_hidden_states else None
598
+ all_self_attns = () if output_attentions else None
599
+ all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
600
+ next_decoder_cache = () if use_cache else None
601
+
602
+ # check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired
603
+ for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]):
604
+ if attn_mask is not None:
605
+ if attn_mask.size()[0] != len(self.layers):
606
+ raise ValueError(
607
+ f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for"
608
+ f" {head_mask.size()[0]}."
609
+ )
610
+ for idx, decoder_layer in enumerate(self.layers):
611
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
612
+ if output_hidden_states:
613
+ all_hidden_states += (hidden_states,)
614
+ if self.training:
615
+ dropout_probability = torch.rand([])
616
+ if dropout_probability < self.layerdrop:
617
+ continue
618
+
619
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
620
+
621
+ if self.gradient_checkpointing and self.training:
622
+ layer_outputs = self._gradient_checkpointing_func(
623
+ decoder_layer.__call__,
624
+ hidden_states,
625
+ attention_mask,
626
+ encoder_hidden_states,
627
+ encoder_attention_mask,
628
+ head_mask[idx] if head_mask is not None else None,
629
+ cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None,
630
+ None,
631
+ output_attentions,
632
+ use_cache,
633
+ )
634
+ else:
635
+ layer_outputs = decoder_layer(
636
+ hidden_states,
637
+ attention_mask=attention_mask,
638
+ encoder_hidden_states=encoder_hidden_states,
639
+ encoder_attention_mask=encoder_attention_mask,
640
+ layer_head_mask=(head_mask[idx] if head_mask is not None else None),
641
+ cross_attn_layer_head_mask=(
642
+ cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None
643
+ ),
644
+ past_key_value=past_key_value,
645
+ output_attentions=output_attentions,
646
+ use_cache=use_cache,
647
+ )
648
+ hidden_states = layer_outputs[0]
649
+
650
+ if use_cache:
651
+ next_decoder_cache += (layer_outputs[3 if output_attentions else 1],)
652
+
653
+ if output_attentions:
654
+ all_self_attns += (layer_outputs[1],)
655
+
656
+ if encoder_hidden_states is not None:
657
+ all_cross_attentions += (layer_outputs[2],)
658
+
659
+ hidden_states = self.layer_norm(hidden_states)
660
+
661
+ # add hidden states from the last decoder layer
662
+ if output_hidden_states:
663
+ all_hidden_states += (hidden_states,)
664
+
665
+ next_cache = next_decoder_cache if use_cache else None
666
+ if not return_dict:
667
+ return tuple(
668
+ v
669
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_cross_attentions]
670
+ if v is not None
671
+ )
672
+ return BaseModelOutputWithPastAndCrossAttentions(
673
+ last_hidden_state=hidden_states,
674
+ past_key_values=next_cache,
675
+ hidden_states=all_hidden_states,
676
+ attentions=all_self_attns,
677
+ cross_attentions=all_cross_attentions,
678
+ )
679
+
680
+
681
+ @add_start_docstrings(
682
+ """
683
+ The XGLM Model transformer with a language modeling head on top (linear layer with weights tied to the input
684
+ embeddings).
685
+ """,
686
+ XGLM_START_DOCSTRING,
687
+ )
688
+ class XGLMForCausalLM(XGLMPreTrainedModel):
689
+ base_model_prefix = "model"
690
+ _tied_weights_keys = ["lm_head.weight"]
691
+
692
+ def __init__(self, config):
693
+ super().__init__(config)
694
+ self.model = XGLMModel(config)
695
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
696
+
697
+ # Initialize weights and apply final processing
698
+ self.post_init()
699
+
700
+ def get_input_embeddings(self):
701
+ return self.model.embed_tokens
702
+
703
+ def set_input_embeddings(self, value):
704
+ self.model.embed_tokens = value
705
+
706
+ def get_output_embeddings(self):
707
+ return self.lm_head
708
+
709
+ def set_output_embeddings(self, new_embeddings):
710
+ self.lm_head = new_embeddings
711
+
712
+ @add_start_docstrings_to_model_forward(XGLM_INPUTS_DOCSTRING)
713
+ @add_code_sample_docstrings(
714
+ checkpoint=_CHECKPOINT_FOR_DOC,
715
+ output_type=CausalLMOutputWithCrossAttentions,
716
+ config_class=_CONFIG_FOR_DOC,
717
+ )
718
+ def forward(
719
+ self,
720
+ input_ids: Optional[torch.Tensor] = None,
721
+ attention_mask: Optional[torch.Tensor] = None,
722
+ position_ids: Optional[torch.Tensor] = None,
723
+ encoder_hidden_states: Optional[torch.Tensor] = None,
724
+ encoder_attention_mask: Optional[torch.Tensor] = None,
725
+ head_mask: Optional[torch.Tensor] = None,
726
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
727
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
728
+ inputs_embeds: Optional[torch.Tensor] = None,
729
+ labels: Optional[torch.Tensor] = None,
730
+ use_cache: Optional[bool] = None,
731
+ output_attentions: Optional[bool] = None,
732
+ output_hidden_states: Optional[bool] = None,
733
+ return_dict: Optional[bool] = None,
734
+ ) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
735
+ r"""
736
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
737
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
738
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
739
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
740
+ """
741
+
742
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
743
+ output_hidden_states = (
744
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
745
+ )
746
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
747
+
748
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
749
+ outputs = self.model(
750
+ input_ids=input_ids,
751
+ attention_mask=attention_mask,
752
+ position_ids=position_ids,
753
+ encoder_hidden_states=encoder_hidden_states,
754
+ encoder_attention_mask=encoder_attention_mask,
755
+ head_mask=head_mask,
756
+ cross_attn_head_mask=cross_attn_head_mask,
757
+ past_key_values=past_key_values,
758
+ inputs_embeds=inputs_embeds,
759
+ use_cache=use_cache,
760
+ output_attentions=output_attentions,
761
+ output_hidden_states=output_hidden_states,
762
+ return_dict=return_dict,
763
+ )
764
+
765
+ logits = self.lm_head(outputs[0])
766
+
767
+ loss = None
768
+ if labels is not None:
769
+ # shift labels and add a pad token to the end
770
+ shift_labels = labels.new_zeros(labels.shape)
771
+ shift_labels[:, :-1] = labels[:, 1:].clone()
772
+ shift_labels[:, -1] = self.config.pad_token_id
773
+
774
+ loss_fct = CrossEntropyLoss()
775
+ loss = loss_fct(logits.view(-1, self.config.vocab_size), shift_labels.view(-1))
776
+
777
+ if not return_dict:
778
+ output = (logits,) + outputs[1:]
779
+ return (loss,) + output if loss is not None else output
780
+
781
+ return CausalLMOutputWithCrossAttentions(
782
+ loss=loss,
783
+ logits=logits,
784
+ past_key_values=outputs.past_key_values,
785
+ hidden_states=outputs.hidden_states,
786
+ attentions=outputs.attentions,
787
+ cross_attentions=outputs.cross_attentions,
788
+ )
789
+
790
+ def prepare_inputs_for_generation(
791
+ self, input_ids, past_key_values=None, attention_mask=None, use_cache=None, **kwargs
792
+ ):
793
+ if past_key_values is not None:
794
+ past_length = past_key_values[0][0].shape[2]
795
+
796
+ # Some generation methods already pass only the last input ID
797
+ if input_ids.shape[1] > past_length:
798
+ remove_prefix_length = past_length
799
+ else:
800
+ # Default to old behavior: keep only final ID
801
+ remove_prefix_length = input_ids.shape[1] - 1
802
+
803
+ input_ids = input_ids[:, remove_prefix_length:]
804
+
805
+ position_ids = kwargs.get("position_ids", None)
806
+ if attention_mask is not None and position_ids is None:
807
+ # create position_ids on the fly for batch generation
808
+ position_ids = attention_mask.long().cumsum(-1) - 1
809
+ position_ids.masked_fill_(attention_mask == 0, 1)
810
+ if past_key_values:
811
+ position_ids = position_ids[:, -input_ids.shape[1] :]
812
+ else:
813
+ position_ids = None
814
+ # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
815
+ if attention_mask is None:
816
+ attention_mask = input_ids.new_ones(input_ids.shape)
817
+ # first step, decoder_cached_states are empty
818
+ return {
819
+ "input_ids": input_ids, # encoder_outputs is defined. input_ids not needed
820
+ "attention_mask": attention_mask,
821
+ "position_ids": position_ids,
822
+ "past_key_values": past_key_values,
823
+ "use_cache": use_cache,
824
+ }
825
+
826
+ @staticmethod
827
+ def _reorder_cache(past_key_values, beam_idx):
828
+ reordered_past = ()
829
+ for layer_past in past_key_values:
830
+ reordered_past += (
831
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
832
+ )
833
+ return reordered_past
834
+
835
+
836
+ class XGLMForSequenceClassification(XGLMPreTrainedModel):
837
+ def __init__(self, config):
838
+ super().__init__(config)
839
+ self.num_labels = config.num_labels
840
+ self.transformer = XGLMModel(config)
841
+ self.score = nn.Linear(config.n_embd, self.num_labels, bias=False)
842
+ self.model_parallel = False
843
+ self.device_map = None
844
+
845
+
846
+ self.post_init()
847
+ @add_start_docstrings_to_model_forward(XGLM_INPUTS_DOCSTRING)
848
+ @add_code_sample_docstrings(
849
+ checkpoint=_CHECKPOINT_FOR_DOC,
850
+ output_type=SequenceClassifierOutputWithPast,
851
+ config_class=_CONFIG_FOR_DOC,
852
+ )
853
+ def forward(
854
+ self,
855
+ input_ids: Optional[torch.LongTensor] = None,
856
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
857
+ attention_mask: Optional[torch.FloatTensor] = None,
858
+ token_type_ids: Optional[torch.LongTensor] = None,
859
+ position_ids: Optional[torch.LongTensor] = None,
860
+ head_mask: Optional[torch.FloatTensor] = None,
861
+ inputs_embeds: Optional[torch.FloatTensor] = None,
862
+ labels: Optional[torch.LongTensor] = None,
863
+ use_cache: Optional[bool] = None,
864
+ output_attentions: Optional[bool] = None,
865
+ output_hidden_states: Optional[bool] = None,
866
+ return_dict: Optional[bool] = None,
867
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
868
+ r"""
869
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
870
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
871
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
872
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
873
+ """
874
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
875
+
876
+ transformer_outputs = self.transformer(
877
+ input_ids,
878
+ past_key_values=past_key_values,
879
+ attention_mask=attention_mask,
880
+ token_type_ids=token_type_ids,
881
+ position_ids=position_ids,
882
+ head_mask=head_mask,
883
+ inputs_embeds=inputs_embeds,
884
+ use_cache=use_cache,
885
+ output_attentions=output_attentions,
886
+ output_hidden_states=output_hidden_states,
887
+ return_dict=return_dict,
888
+ )
889
+ hidden_states = transformer_outputs[0]
890
+ logits = self.score(hidden_states)
891
+
892
+ if input_ids is not None:
893
+ batch_size, sequence_length = input_ids.shape[:2]
894
+ else:
895
+ batch_size, sequence_length = inputs_embeds.shape[:2]
896
+
897
+ assert (
898
+ self.config.pad_token_id is not None or batch_size == 1
899
+ ), "Cannot handle batch sizes > 1 if no padding token is defined."
900
+ if self.config.pad_token_id is None:
901
+ sequence_lengths = -1
902
+ else:
903
+ if input_ids is not None:
904
+ sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1).to(
905
+ logits.device
906
+ )
907
+ else:
908
+ sequence_lengths = -1
909
+ logger.warning(
910
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
911
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
912
+ )
913
+
914
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
915
+
916
+ loss = None
917
+ if labels is not None:
918
+ if self.config.problem_type is None:
919
+ if self.num_labels == 1:
920
+ self.config.problem_type = "regression"
921
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
922
+ self.config.problem_type = "single_label_classification"
923
+ else:
924
+ self.config.problem_type = "multi_label_classification"
925
+
926
+ if self.config.problem_type == "regression":
927
+ loss_fct = MSELoss()
928
+ if self.num_labels == 1:
929
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
930
+ else:
931
+ loss = loss_fct(pooled_logits, labels)
932
+ elif self.config.problem_type == "single_label_classification":
933
+ loss_fct = CrossEntropyLoss()
934
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
935
+ elif self.config.problem_type == "multi_label_classification":
936
+ loss_fct = BCEWithLogitsLoss()
937
+ loss = loss_fct(pooled_logits, labels)
938
+ if not return_dict:
939
+ output = (pooled_logits,) + transformer_outputs[1:]
940
+ return ((loss,) + output) if loss is not None else output
941
+
942
+ return SequenceClassifierOutputWithPast(
943
+ loss=loss,
944
+ logits=pooled_logits,
945
+ past_key_values=transformer_outputs.past_key_values,
946
+ hidden_states=transformer_outputs.hidden_states,
947
+ attentions=transformer_outputs.attentions,
948
+ )