damerajee commited on
Commit
f966943
·
verified ·
1 Parent(s): b3ab435

Create modeling_gpt2.py

Browse files
Files changed (1) hide show
  1. modeling_gpt2.py +1376 -0
modeling_gpt2.py ADDED
@@ -0,0 +1,1376 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The OpenAI Team Authors and HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """PyTorch OpenAI GPT-2 model."""
17
+
18
+ import math
19
+ import os
20
+ import warnings
21
+ from dataclasses import dataclass
22
+ from typing import Optional, Tuple, Union
23
+
24
+ import torch
25
+ import torch.utils.checkpoint
26
+ from packaging import version
27
+ from torch import nn
28
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
29
+
30
+ from transformers.activations import ACT2FN
31
+ from transformers.modeling_attn_mask_utils import _prepare_4d_attention_mask_for_sdpa, _prepare_4d_causal_attention_mask_for_sdpa
32
+ from transformers.modeling_outputs import (
33
+ BaseModelOutputWithPastAndCrossAttentions,
34
+ CausalLMOutputWithCrossAttentions,
35
+ QuestionAnsweringModelOutput,
36
+ SequenceClassifierOutputWithPast,
37
+ TokenClassifierOutput,
38
+ )
39
+ from transformers.modeling_utils import PreTrainedModel, SequenceSummary
40
+ from transformers.pytorch_utils import Conv1D, find_pruneable_heads_and_indices, prune_conv1d_layer
41
+ from transformers.utils import (
42
+ ModelOutput,
43
+ add_code_sample_docstrings,
44
+ add_start_docstrings,
45
+ add_start_docstrings_to_model_forward,
46
+ get_torch_version,
47
+ is_flash_attn_2_available,
48
+ is_flash_attn_greater_or_equal_2_10,
49
+ logging,
50
+ replace_return_docstrings,
51
+ )
52
+ from transformers.utils.model_parallel_utils import assert_device_map, get_device_map
53
+ from .configuration_gpt2vision import GPT2Config
54
+
55
+
56
+ if is_flash_attn_2_available():
57
+ from transformers.modeling_flash_attention_utils import _flash_attention_forward
58
+
59
+
60
+ logger = logging.get_logger(__name__)
61
+
62
+ _CHECKPOINT_FOR_DOC = "openai-community/gpt2"
63
+ _CONFIG_FOR_DOC = "GPT2Config"
64
+
65
+
66
+ def load_tf_weights_in_gpt2(model, config, gpt2_checkpoint_path):
67
+ """Load tf checkpoints in a pytorch model"""
68
+ try:
69
+ import re
70
+
71
+ import tensorflow as tf
72
+ except ImportError:
73
+ logger.error(
74
+ "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
75
+ "https://www.tensorflow.org/install/ for installation instructions."
76
+ )
77
+ raise
78
+ tf_path = os.path.abspath(gpt2_checkpoint_path)
79
+ logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
80
+ # Load weights from TF model
81
+ init_vars = tf.train.list_variables(tf_path)
82
+ names = []
83
+ arrays = []
84
+ for name, shape in init_vars:
85
+ logger.info(f"Loading TF weight {name} with shape {shape}")
86
+ array = tf.train.load_variable(tf_path, name)
87
+ names.append(name)
88
+ arrays.append(array.squeeze())
89
+
90
+ for name, array in zip(names, arrays):
91
+ name = name[6:] # skip "model/"
92
+ name = name.split("/")
93
+ pointer = model
94
+ for m_name in name:
95
+ if re.fullmatch(r"[A-Za-z]+\d+", m_name):
96
+ scope_names = re.split(r"(\d+)", m_name)
97
+ else:
98
+ scope_names = [m_name]
99
+ if scope_names[0] == "w" or scope_names[0] == "g":
100
+ pointer = getattr(pointer, "weight")
101
+ elif scope_names[0] == "b":
102
+ pointer = getattr(pointer, "bias")
103
+ elif scope_names[0] == "wpe" or scope_names[0] == "wte":
104
+ pointer = getattr(pointer, scope_names[0])
105
+ pointer = getattr(pointer, "weight")
106
+ else:
107
+ pointer = getattr(pointer, scope_names[0])
108
+ if len(scope_names) >= 2:
109
+ num = int(scope_names[1])
110
+ pointer = pointer[num]
111
+ try:
112
+ if pointer.shape != array.shape:
113
+ raise ValueError(f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched")
114
+ except ValueError as e:
115
+ e.args += (pointer.shape, array.shape)
116
+ raise
117
+ logger.info(f"Initialize PyTorch weight {name}")
118
+ pointer.data = torch.from_numpy(array)
119
+ return model
120
+
121
+
122
+ class GPT2Attention(nn.Module):
123
+ def __init__(self, config, is_cross_attention=False, layer_idx=None):
124
+ super().__init__()
125
+ self.config = config
126
+ max_positions = config.max_position_embeddings
127
+ self.register_buffer(
128
+ "bias",
129
+ torch.tril(torch.ones((max_positions, max_positions), dtype=torch.bool)).view(
130
+ 1, 1, max_positions, max_positions
131
+ ),
132
+ persistent=False,
133
+ )
134
+ self.register_buffer("masked_bias", torch.tensor(-1e4), persistent=False)
135
+
136
+ self.embed_dim = config.hidden_size
137
+ self.num_heads = config.num_attention_heads
138
+ self.head_dim = self.embed_dim // self.num_heads
139
+ self.split_size = self.embed_dim
140
+ if self.head_dim * self.num_heads != self.embed_dim:
141
+ raise ValueError(
142
+ f"`embed_dim` must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
143
+ f" {self.num_heads})."
144
+ )
145
+
146
+ self.scale_attn_weights = config.scale_attn_weights
147
+ self.is_cross_attention = is_cross_attention
148
+
149
+ # Layer-wise attention scaling, reordering, and upcasting
150
+ self.scale_attn_by_inverse_layer_idx = config.scale_attn_by_inverse_layer_idx
151
+ self.layer_idx = layer_idx
152
+ self.reorder_and_upcast_attn = config.reorder_and_upcast_attn
153
+
154
+ if self.is_cross_attention:
155
+ self.c_attn = Conv1D(2 * self.embed_dim, self.embed_dim)
156
+ self.q_attn = Conv1D(self.embed_dim, self.embed_dim)
157
+ else:
158
+ self.c_attn = Conv1D(3 * self.embed_dim, self.embed_dim)
159
+ self.c_proj = Conv1D(self.embed_dim, self.embed_dim)
160
+
161
+ self.attn_dropout = nn.Dropout(config.attn_pdrop)
162
+ self.resid_dropout = nn.Dropout(config.resid_pdrop)
163
+ self.is_causal = True
164
+
165
+ self.pruned_heads = set()
166
+
167
+ def prune_heads(self, heads):
168
+ if len(heads) == 0:
169
+ return
170
+ heads, index = find_pruneable_heads_and_indices(heads, self.num_heads, self.head_dim, self.pruned_heads)
171
+ index_attn = torch.cat([index, index + self.split_size, index + (2 * self.split_size)])
172
+
173
+ # Prune conv1d layers
174
+ self.c_attn = prune_conv1d_layer(self.c_attn, index_attn, dim=1)
175
+ self.c_proj = prune_conv1d_layer(self.c_proj, index, dim=0)
176
+
177
+ # Update hyper params
178
+ self.split_size = (self.split_size // self.num_heads) * (self.num_heads - len(heads))
179
+ self.num_heads = self.num_heads - len(heads)
180
+ self.pruned_heads = self.pruned_heads.union(heads)
181
+
182
+ def _attn(self, query, key, value, attention_mask=None, head_mask=None):
183
+ attn_weights = torch.matmul(query, key.transpose(-1, -2))
184
+
185
+ if self.scale_attn_weights:
186
+ attn_weights = attn_weights / torch.full(
187
+ [], value.size(-1) ** 0.5, dtype=attn_weights.dtype, device=attn_weights.device
188
+ )
189
+
190
+ # Layer-wise attention scaling
191
+ if self.scale_attn_by_inverse_layer_idx:
192
+ attn_weights = attn_weights / float(self.layer_idx + 1)
193
+
194
+ if not self.is_cross_attention:
195
+ # if only "normal" attention layer implements causal mask
196
+ query_length, key_length = query.size(-2), key.size(-2)
197
+ causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length]
198
+ mask_value = torch.finfo(attn_weights.dtype).min
199
+ # Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`.
200
+ # Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device`
201
+ mask_value = torch.full([], mask_value, dtype=attn_weights.dtype, device=attn_weights.device)
202
+ attn_weights = torch.where(causal_mask, attn_weights.to(attn_weights.dtype), mask_value)
203
+
204
+ if attention_mask is not None:
205
+ # Apply the attention mask
206
+ attn_weights = attn_weights + attention_mask
207
+
208
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
209
+
210
+ # Downcast (if necessary) back to V's dtype (if in mixed-precision) -- No-Op otherwise
211
+ attn_weights = attn_weights.type(value.dtype)
212
+ attn_weights = self.attn_dropout(attn_weights)
213
+
214
+ # Mask heads if we want to
215
+ if head_mask is not None:
216
+ attn_weights = attn_weights * head_mask
217
+
218
+ attn_output = torch.matmul(attn_weights, value)
219
+
220
+ return attn_output, attn_weights
221
+
222
+ def _upcast_and_reordered_attn(self, query, key, value, attention_mask=None, head_mask=None):
223
+ # Use `torch.baddbmm` (a bit more efficient w/ alpha param for scaling -- from Megatron-LM)
224
+ bsz, num_heads, q_seq_len, dk = query.size()
225
+ _, _, k_seq_len, _ = key.size()
226
+
227
+ # Preallocate attn_weights for `baddbmm`
228
+ attn_weights = torch.empty(bsz * num_heads, q_seq_len, k_seq_len, dtype=torch.float32, device=query.device)
229
+
230
+ # Compute Scale Factor
231
+ scale_factor = 1.0
232
+ if self.scale_attn_weights:
233
+ scale_factor /= float(value.size(-1)) ** 0.5
234
+
235
+ if self.scale_attn_by_inverse_layer_idx:
236
+ scale_factor /= float(self.layer_idx + 1)
237
+
238
+ # Upcast (turn off autocast) and reorder (Scale K by 1 / root(dk))
239
+ with torch.amp.autocast(query.device.type, enabled=False):
240
+ q, k = query.reshape(-1, q_seq_len, dk), key.transpose(-1, -2).reshape(-1, dk, k_seq_len)
241
+ attn_weights = torch.baddbmm(attn_weights, q.float(), k.float(), beta=0, alpha=scale_factor)
242
+ attn_weights = attn_weights.reshape(bsz, num_heads, q_seq_len, k_seq_len)
243
+
244
+ if not self.is_cross_attention:
245
+ # if only "normal" attention layer implements causal mask
246
+ query_length, key_length = query.size(-2), key.size(-2)
247
+ causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length]
248
+ mask_value = torch.finfo(attn_weights.dtype).min
249
+ # Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`.
250
+ # Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device`
251
+ mask_value = torch.tensor(mask_value, dtype=attn_weights.dtype).to(attn_weights.device)
252
+ attn_weights = torch.where(causal_mask, attn_weights, mask_value)
253
+
254
+ if attention_mask is not None:
255
+ # Apply the attention mask
256
+ attn_weights = attn_weights + attention_mask
257
+
258
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
259
+
260
+ # Downcast (if necessary) back to V's dtype (if in mixed-precision) -- No-Op if otherwise
261
+ if attn_weights.dtype != torch.float32:
262
+ raise RuntimeError("Error with upcasting, attn_weights does not have dtype torch.float32")
263
+ attn_weights = attn_weights.type(value.dtype)
264
+ attn_weights = self.attn_dropout(attn_weights)
265
+
266
+ # Mask heads if we want to
267
+ if head_mask is not None:
268
+ attn_weights = attn_weights * head_mask
269
+
270
+ attn_output = torch.matmul(attn_weights, value)
271
+
272
+ return attn_output, attn_weights
273
+
274
+ def _split_heads(self, tensor, num_heads, attn_head_size):
275
+ """
276
+ Splits hidden_size dim into attn_head_size and num_heads
277
+ """
278
+ new_shape = tensor.size()[:-1] + (num_heads, attn_head_size)
279
+ tensor = tensor.view(new_shape)
280
+ return tensor.permute(0, 2, 1, 3) # (batch, head, seq_length, head_features)
281
+
282
+ def _merge_heads(self, tensor, num_heads, attn_head_size):
283
+ """
284
+ Merges attn_head_size dim and num_attn_heads dim into hidden_size
285
+ """
286
+ tensor = tensor.permute(0, 2, 1, 3).contiguous()
287
+ new_shape = tensor.size()[:-2] + (num_heads * attn_head_size,)
288
+ return tensor.view(new_shape)
289
+
290
+ def forward(
291
+ self,
292
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
293
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
294
+ attention_mask: Optional[torch.FloatTensor] = None,
295
+ head_mask: Optional[torch.FloatTensor] = None,
296
+ encoder_hidden_states: Optional[torch.Tensor] = None,
297
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
298
+ use_cache: Optional[bool] = False,
299
+ output_attentions: Optional[bool] = False,
300
+ ) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]], ...]:
301
+ if encoder_hidden_states is not None:
302
+ if not hasattr(self, "q_attn"):
303
+ raise ValueError(
304
+ "If class is used as cross attention, the weights `q_attn` have to be defined. "
305
+ "Please make sure to instantiate class with `GPT2Attention(..., is_cross_attention=True)`."
306
+ )
307
+
308
+ query = self.q_attn(hidden_states)
309
+ key, value = self.c_attn(encoder_hidden_states).split(self.split_size, dim=2)
310
+ attention_mask = encoder_attention_mask
311
+ else:
312
+ query, key, value = self.c_attn(hidden_states).split(self.split_size, dim=2)
313
+
314
+ query = self._split_heads(query, self.num_heads, self.head_dim)
315
+ key = self._split_heads(key, self.num_heads, self.head_dim)
316
+ value = self._split_heads(value, self.num_heads, self.head_dim)
317
+
318
+ if layer_past is not None:
319
+ past_key, past_value = layer_past
320
+ key = torch.cat((past_key, key), dim=-2)
321
+ value = torch.cat((past_value, value), dim=-2)
322
+
323
+ if use_cache is True:
324
+ present = (key, value)
325
+ else:
326
+ present = None
327
+
328
+ if self.reorder_and_upcast_attn:
329
+ attn_output, attn_weights = self._upcast_and_reordered_attn(query, key, value, attention_mask, head_mask)
330
+ else:
331
+ attn_output, attn_weights = self._attn(query, key, value, attention_mask, head_mask)
332
+
333
+ attn_output = self._merge_heads(attn_output, self.num_heads, self.head_dim)
334
+ attn_output = self.c_proj(attn_output)
335
+ attn_output = self.resid_dropout(attn_output)
336
+
337
+ outputs = (attn_output, present)
338
+ if output_attentions:
339
+ outputs += (attn_weights,)
340
+
341
+ return outputs # a, present, (attentions)
342
+
343
+
344
+ class GPT2FlashAttention2(GPT2Attention):
345
+ """
346
+ GPT2 flash attention module. This module inherits from `GPT2Attention` as the weights of the module stays
347
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
348
+ flash attention and deal with padding tokens in case the input contains any of them.
349
+ """
350
+
351
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
352
+ def __init__(self, *args, **kwargs):
353
+ super().__init__(*args, **kwargs)
354
+
355
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
356
+ # 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.
357
+ # 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).
358
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
359
+
360
+ def forward(
361
+ self,
362
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
363
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
364
+ attention_mask: Optional[torch.FloatTensor] = None,
365
+ head_mask: Optional[torch.FloatTensor] = None,
366
+ encoder_hidden_states: Optional[torch.Tensor] = None,
367
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
368
+ use_cache: Optional[bool] = False,
369
+ output_attentions: Optional[bool] = False,
370
+ ) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]], ...]:
371
+ bsz, _, _ = hidden_states.size()
372
+ if encoder_hidden_states is not None:
373
+ if not hasattr(self, "q_attn"):
374
+ raise ValueError(
375
+ "If class is used as cross attention, the weights `q_attn` have to be defined. "
376
+ "Please make sure to instantiate class with `GPT2Attention(..., is_cross_attention=True)`."
377
+ )
378
+
379
+ query = self.q_attn(hidden_states)
380
+ key, value = self.c_attn(encoder_hidden_states).split(self.split_size, dim=2)
381
+ attention_mask = encoder_attention_mask
382
+ else:
383
+ query, key, value = self.c_attn(hidden_states).split(self.split_size, dim=2)
384
+
385
+ query = self._split_heads(query, self.num_heads, self.head_dim)
386
+ key = self._split_heads(key, self.num_heads, self.head_dim)
387
+ value = self._split_heads(value, self.num_heads, self.head_dim)
388
+
389
+ if layer_past is not None:
390
+ past_key = layer_past[0]
391
+ past_value = layer_past[1]
392
+ key = torch.cat((past_key, key), dim=-2)
393
+ value = torch.cat((past_value, value), dim=-2)
394
+
395
+ present = None
396
+ if use_cache is True:
397
+ present = (key, value)
398
+
399
+ query_length = query.shape[2]
400
+ tgt_len = key.shape[2]
401
+
402
+ # Flash attention requires the input to have the shape
403
+ # batch_size x seq_length x head_dim x hidden_dim
404
+ query = query.transpose(1, 2).view(bsz, query_length, self.num_heads, self.head_dim)
405
+ key = key.transpose(1, 2).view(bsz, tgt_len, self.num_heads, self.head_dim)
406
+ value = value.transpose(1, 2).view(bsz, tgt_len, self.num_heads, self.head_dim)
407
+
408
+ attn_dropout = self.attn_dropout.p if self.training else 0.0
409
+
410
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
411
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
412
+ # cast them back in the correct dtype just to be sure everything works as expected.
413
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
414
+ # in fp32. (LlamaRMSNorm handles it correctly)
415
+
416
+ if query.dtype == torch.float32:
417
+ if torch.is_autocast_enabled():
418
+ target_dtype = torch.get_autocast_gpu_dtype()
419
+ # Handle the case where the model is quantized
420
+ elif hasattr(self.config, "_pre_quantization_dtype"):
421
+ target_dtype = self.config._pre_quantization_dtype
422
+ else:
423
+ target_dtype = self.c_proj.weight.dtype
424
+
425
+ logger.warning_once(
426
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
427
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
428
+ f" {target_dtype}."
429
+ )
430
+
431
+ query = query.to(target_dtype)
432
+ key = key.to(target_dtype)
433
+ value = value.to(target_dtype)
434
+
435
+ attn_output = _flash_attention_forward(
436
+ query,
437
+ key,
438
+ value,
439
+ attention_mask,
440
+ query_length,
441
+ dropout=attn_dropout,
442
+ is_causal=self.is_causal,
443
+ use_top_left_mask=self._flash_attn_uses_top_left_mask,
444
+ )
445
+
446
+ attn_weights_reshaped = attn_output.reshape(bsz, query_length, self.num_heads * self.head_dim)
447
+ attn_output = self.c_proj(attn_weights_reshaped)
448
+ attn_output = self.resid_dropout(attn_output)
449
+
450
+ outputs = (attn_output, present)
451
+ if output_attentions:
452
+ outputs += (attn_weights_reshaped,)
453
+
454
+ return outputs
455
+
456
+
457
+ class GPT2SdpaAttention(GPT2Attention):
458
+ """
459
+ GPT2 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
460
+ `GPT2Attention` as the weights of the module stays untouched. The only changes are on the forward pass
461
+ to adapt to the SDPA API.
462
+ """
463
+
464
+ def __init__(self, *args, **kwargs):
465
+ super().__init__(*args, **kwargs)
466
+
467
+ # Idea adapted from transformers.models.bert.modeling_bert.BertSdpaSelfAttention.__init__
468
+ # SDPA with memory-efficient backend is broken in torch==2.1.2 when using non-contiguous inputs and a custom
469
+ # attn_mask, so we need to call `.contiguous()`. This was fixed in torch==2.2.0.
470
+ # Reference: https://github.com/pytorch/pytorch/issues/112577
471
+ self.require_contiguous_qkv = version.parse(get_torch_version()) < version.parse("2.2.0")
472
+
473
+ def forward(
474
+ self,
475
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
476
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
477
+ attention_mask: Optional[torch.FloatTensor] = None,
478
+ head_mask: Optional[torch.FloatTensor] = None,
479
+ encoder_hidden_states: Optional[torch.Tensor] = None,
480
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
481
+ use_cache: Optional[bool] = False,
482
+ output_attentions: Optional[bool] = False,
483
+ ) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]], ...]:
484
+ if output_attentions or head_mask is not None:
485
+ logger.warning_once(
486
+ "`GPT2SdpaAttention` is used but `torch.nn.functional.scaled_dot_product_attention` does not support "
487
+ "`output_attentions=True` or `head_mask`. Falling back to the manual attention implementation, but "
488
+ "specifying the manual implementation will be required from Transformers version v5.0.0 onwards. "
489
+ 'This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
490
+ )
491
+ return super().forward(
492
+ hidden_states=hidden_states,
493
+ layer_past=layer_past,
494
+ attention_mask=attention_mask,
495
+ head_mask=head_mask,
496
+ encoder_hidden_states=encoder_hidden_states,
497
+ encoder_attention_mask=encoder_attention_mask,
498
+ use_cache=use_cache,
499
+ output_attentions=output_attentions,
500
+ )
501
+
502
+ bsz, q_len, _ = hidden_states.size()
503
+
504
+ # Initial attention projections
505
+ is_cross_attention = encoder_hidden_states is not None
506
+ if is_cross_attention:
507
+ if not hasattr(self, "q_attn"):
508
+ raise ValueError(
509
+ "If class is used as cross attention, the weights `q_attn` have to be defined. "
510
+ "Please make sure to instantiate class with `GPT2SdpaAttention(..., is_cross_attention=True)`."
511
+ )
512
+
513
+ query = self.q_attn(hidden_states)
514
+ key, value = self.c_attn(encoder_hidden_states).split(self.split_size, dim=2)
515
+ attention_mask = encoder_attention_mask
516
+ else:
517
+ query, key, value = self.c_attn(hidden_states).split(self.split_size, dim=2)
518
+
519
+ query = self._split_heads(query, self.num_heads, self.head_dim)
520
+ key = self._split_heads(key, self.num_heads, self.head_dim)
521
+ value = self._split_heads(value, self.num_heads, self.head_dim)
522
+
523
+ # Optional kv caching
524
+ if layer_past is not None:
525
+ past_key = layer_past[0]
526
+ past_value = layer_past[1]
527
+ key = torch.cat((past_key, key), dim=-2)
528
+ value = torch.cat((past_value, value), dim=-2)
529
+
530
+ present = None
531
+ if use_cache is True:
532
+ present = (key, value)
533
+
534
+ # Avoid torch==2.1.2 specific bug for the memory-efficient backend in SDPA
535
+ if self.require_contiguous_qkv and query.device.type == "cuda" and attention_mask is not None:
536
+ query = query.contiguous()
537
+ key = key.contiguous()
538
+ value = value.contiguous()
539
+
540
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
541
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
542
+ is_causal = True if attention_mask is None and q_len > 1 and not is_cross_attention else False
543
+
544
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
545
+ query,
546
+ key,
547
+ value,
548
+ attn_mask=attention_mask,
549
+ dropout_p=self.attn_dropout.p if self.training else 0.0,
550
+ is_causal=is_causal,
551
+ )
552
+
553
+ # Reshape outputs
554
+ attn_output = attn_output.transpose(1, 2).contiguous()
555
+ attn_output = attn_output.view(bsz, q_len, self.embed_dim)
556
+
557
+ # Final projection
558
+ attn_output = self.c_proj(attn_output)
559
+ attn_output = self.resid_dropout(attn_output)
560
+
561
+ return attn_output, present, None
562
+
563
+
564
+ class GPT2MLP(nn.Module):
565
+ def __init__(self, intermediate_size, config):
566
+ super().__init__()
567
+ embed_dim = config.hidden_size
568
+ self.c_fc = Conv1D(intermediate_size, embed_dim)
569
+ self.c_proj = Conv1D(embed_dim, intermediate_size)
570
+ self.act = ACT2FN[config.activation_function]
571
+ self.dropout = nn.Dropout(config.resid_pdrop)
572
+
573
+ def forward(self, hidden_states: Optional[Tuple[torch.FloatTensor]]) -> torch.FloatTensor:
574
+ hidden_states = self.c_fc(hidden_states)
575
+ hidden_states = self.act(hidden_states)
576
+ hidden_states = self.c_proj(hidden_states)
577
+ hidden_states = self.dropout(hidden_states)
578
+ return hidden_states
579
+
580
+
581
+ GPT2_ATTENTION_CLASSES = {"eager": GPT2Attention, "flash_attention_2": GPT2FlashAttention2, "sdpa": GPT2SdpaAttention}
582
+
583
+
584
+ class GPT2Block(nn.Module):
585
+ def __init__(self, config, layer_idx=None):
586
+ super().__init__()
587
+ hidden_size = config.hidden_size
588
+ inner_dim = config.n_inner if config.n_inner is not None else 4 * hidden_size
589
+ attention_class = GPT2_ATTENTION_CLASSES[config._attn_implementation]
590
+
591
+ self.ln_1 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
592
+ self.attn = attention_class(config=config, layer_idx=layer_idx)
593
+ self.ln_2 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
594
+
595
+ if config.add_cross_attention:
596
+ self.crossattention = attention_class(config=config, is_cross_attention=True, layer_idx=layer_idx)
597
+ self.ln_cross_attn = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
598
+
599
+ self.mlp = GPT2MLP(inner_dim, config)
600
+
601
+ def forward(
602
+ self,
603
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
604
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
605
+ attention_mask: Optional[torch.FloatTensor] = None,
606
+ head_mask: Optional[torch.FloatTensor] = None,
607
+ encoder_hidden_states: Optional[torch.Tensor] = None,
608
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
609
+ use_cache: Optional[bool] = False,
610
+ output_attentions: Optional[bool] = False,
611
+ ) -> Union[Tuple[torch.Tensor], Optional[Tuple[torch.Tensor, Tuple[torch.FloatTensor, ...]]]]:
612
+ residual = hidden_states
613
+ hidden_states = self.ln_1(hidden_states)
614
+ attn_outputs = self.attn(
615
+ hidden_states,
616
+ layer_past=layer_past,
617
+ attention_mask=attention_mask,
618
+ head_mask=head_mask,
619
+ use_cache=use_cache,
620
+ output_attentions=output_attentions,
621
+ )
622
+ attn_output = attn_outputs[0] # output_attn: a, present, (attentions)
623
+ outputs = attn_outputs[1:]
624
+ # residual connection
625
+ hidden_states = attn_output + residual
626
+
627
+ if encoder_hidden_states is not None:
628
+ # add one self-attention block for cross-attention
629
+ if not hasattr(self, "crossattention"):
630
+ raise ValueError(
631
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with "
632
+ "cross-attention layers by setting `config.add_cross_attention=True`"
633
+ )
634
+ residual = hidden_states
635
+ hidden_states = self.ln_cross_attn(hidden_states)
636
+ cross_attn_outputs = self.crossattention(
637
+ hidden_states,
638
+ attention_mask=attention_mask,
639
+ head_mask=head_mask,
640
+ encoder_hidden_states=encoder_hidden_states,
641
+ encoder_attention_mask=encoder_attention_mask,
642
+ output_attentions=output_attentions,
643
+ )
644
+ attn_output = cross_attn_outputs[0]
645
+ # residual connection
646
+ hidden_states = residual + attn_output
647
+ outputs = outputs + cross_attn_outputs[2:] # add cross attentions if we output attention weights
648
+
649
+ residual = hidden_states
650
+ hidden_states = self.ln_2(hidden_states)
651
+ feed_forward_hidden_states = self.mlp(hidden_states)
652
+ # residual connection
653
+ hidden_states = residual + feed_forward_hidden_states
654
+
655
+ if use_cache:
656
+ outputs = (hidden_states,) + outputs
657
+ else:
658
+ outputs = (hidden_states,) + outputs[1:]
659
+
660
+ return outputs # hidden_states, present, (attentions, cross_attentions)
661
+
662
+
663
+ class GPT2PreTrainedModel(PreTrainedModel):
664
+ """
665
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
666
+ models.
667
+ """
668
+
669
+ config_class = GPT2Config
670
+ load_tf_weights = load_tf_weights_in_gpt2
671
+ base_model_prefix = "transformer"
672
+ is_parallelizable = True
673
+ supports_gradient_checkpointing = True
674
+ _no_split_modules = ["GPT2Block"]
675
+ _skip_keys_device_placement = "past_key_values"
676
+ _supports_flash_attn_2 = True
677
+ _supports_sdpa = True
678
+
679
+ def __init__(self, *inputs, **kwargs):
680
+ super().__init__(*inputs, **kwargs)
681
+
682
+ def _init_weights(self, module):
683
+ """Initialize the weights."""
684
+ if isinstance(module, (nn.Linear, Conv1D)):
685
+ # Slightly different from the TF version which uses truncated_normal for initialization
686
+ # cf https://github.com/pytorch/pytorch/pull/5617
687
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
688
+ if module.bias is not None:
689
+ module.bias.data.zero_()
690
+ elif isinstance(module, nn.Embedding):
691
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
692
+ if module.padding_idx is not None:
693
+ module.weight.data[module.padding_idx].zero_()
694
+ elif isinstance(module, nn.LayerNorm):
695
+ module.bias.data.zero_()
696
+ module.weight.data.fill_(1.0)
697
+
698
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
699
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
700
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
701
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
702
+ #
703
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
704
+ for name, p in module.named_parameters():
705
+ if name == "c_proj.weight":
706
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
707
+ p.data.normal_(mean=0.0, std=(self.config.initializer_range / math.sqrt(2 * self.config.n_layer)))
708
+
709
+
710
+ @dataclass
711
+ class GPT2DoubleHeadsModelOutput(ModelOutput):
712
+ """
713
+ Base class for outputs of models predicting if two sentences are consecutive or not.
714
+
715
+ Args:
716
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
717
+ Language modeling loss.
718
+ mc_loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `mc_labels` is provided):
719
+ Multiple choice classification loss.
720
+ logits (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, config.vocab_size)`):
721
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
722
+ mc_logits (`torch.FloatTensor` of shape `(batch_size, num_choices)`):
723
+ Prediction scores of the multiple choice classification head (scores for each choice before SoftMax).
724
+ past_key_values (`Tuple[Tuple[torch.Tensor]]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
725
+ Tuple of length `config.n_layers`, containing tuples of tensors of shape `(batch_size, num_heads,
726
+ sequence_length, embed_size_per_head)`).
727
+
728
+ Contains pre-computed hidden-states (key and values in the attention blocks) that can be used (see
729
+ `past_key_values` input) to speed up sequential decoding.
730
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
731
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
732
+ shape `(batch_size, sequence_length, hidden_size)`.
733
+
734
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
735
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
736
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
737
+ sequence_length)`.
738
+
739
+ GPT2Attentions weights after the attention softmax, used to compute the weighted average in the
740
+ self-attention heads.
741
+ """
742
+
743
+ loss: Optional[torch.FloatTensor] = None
744
+ mc_loss: Optional[torch.FloatTensor] = None
745
+ logits: torch.FloatTensor = None
746
+ mc_logits: torch.FloatTensor = None
747
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
748
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
749
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
750
+
751
+
752
+ GPT2_START_DOCSTRING = r"""
753
+
754
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
755
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
756
+ etc.)
757
+
758
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
759
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
760
+ and behavior.
761
+
762
+ Parameters:
763
+ config ([`GPT2Config`]): Model configuration class with all the parameters of the model.
764
+ Initializing with a config file does not load the weights associated with the model, only the
765
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
766
+ """
767
+
768
+ GPT2_INPUTS_DOCSTRING = r"""
769
+ Args:
770
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
771
+ `input_ids_length` = `sequence_length` if `past_key_values` is `None` else
772
+ `past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input
773
+ sequence tokens in the vocabulary.
774
+
775
+ If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
776
+ `input_ids`.
777
+
778
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
779
+ [`PreTrainedTokenizer.__call__`] for details.
780
+
781
+ [What are input IDs?](../glossary#input-ids)
782
+ past_key_values (`Tuple[Tuple[torch.Tensor]]` of length `config.n_layers`):
783
+ Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
784
+ `past_key_values` output below). Can be used to speed up sequential decoding. The `input_ids` which have
785
+ their past given to this model should not be passed as `input_ids` as they have already been computed.
786
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
787
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
788
+
789
+ - 1 for tokens that are **not masked**,
790
+ - 0 for tokens that are **masked**.
791
+
792
+ If `past_key_values` is used, `attention_mask` needs to contain the masking strategy that was used for
793
+ `past_key_values`. In other words, the `attention_mask` always has to have the length:
794
+ `len(past_key_values) + len(input_ids)`
795
+
796
+ [What are attention masks?](../glossary#attention-mask)
797
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`, *optional*):
798
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
799
+ 1]`:
800
+
801
+ - 0 corresponds to a *sentence A* token,
802
+ - 1 corresponds to a *sentence B* token.
803
+
804
+ [What are token type IDs?](../glossary#token-type-ids)
805
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
806
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
807
+ config.max_position_embeddings - 1]`.
808
+
809
+ [What are position IDs?](../glossary#position-ids)
810
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
811
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
812
+
813
+ - 1 indicates the head is **not masked**,
814
+ - 0 indicates the head is **masked**.
815
+
816
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
817
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
818
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
819
+ model's internal embedding lookup matrix.
820
+
821
+ If `past_key_values` is used, optionally only the last `inputs_embeds` have to be input (see
822
+ `past_key_values`).
823
+ use_cache (`bool`, *optional*):
824
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
825
+ `past_key_values`).
826
+ output_attentions (`bool`, *optional*):
827
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
828
+ tensors for more detail.
829
+ output_hidden_states (`bool`, *optional*):
830
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
831
+ more detail.
832
+ return_dict (`bool`, *optional*):
833
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
834
+ """
835
+ PARALLELIZE_DOCSTRING = r"""
836
+ This is an experimental feature and is a subject to change at a moment's notice.
837
+
838
+ Uses a device map to distribute attention modules of the model across several devices. If no device map is given,
839
+ it will evenly distribute blocks across all devices.
840
+
841
+ Args:
842
+ device_map (`Dict[int, list]`, optional, defaults to None):
843
+ A dictionary that maps attention modules to devices. Note that the embedding module and LMHead are always
844
+ automatically mapped to the first device (for esoteric reasons). That means that the first device should
845
+ have fewer attention modules mapped to it than other devices. For reference, the gpt2 models have the
846
+ following number of attention modules:
847
+
848
+ - openai-community/gpt2: 12
849
+ - openai-community/gpt2-medium: 24
850
+ - openai-community/gpt2-large: 36
851
+ - openai-community/gpt2-xl: 48
852
+
853
+ Example:
854
+
855
+ ```python
856
+ # Here is an example of a device map on a machine with 4 GPUs using gpt2-xl, which has a total of 48 attention modules:
857
+ model = GPT2LMHeadModel.from_pretrained("openai-community/gpt2-xl")
858
+ device_map = {
859
+ 0: [0, 1, 2, 3, 4, 5, 6, 7, 8],
860
+ 1: [9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21],
861
+ 2: [22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34],
862
+ 3: [35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47],
863
+ }
864
+ model.parallelize(device_map)
865
+ ```
866
+ """
867
+ DEPARALLELIZE_DOCSTRING = r"""
868
+ Moves the model to cpu from a model parallel state.
869
+
870
+ Example:
871
+
872
+ ```python
873
+ # On a 4 GPU machine with openai-community/gpt2-large:
874
+ model = GPT2LMHeadModel.from_pretrained("openai-community/gpt2-large")
875
+ device_map = {
876
+ 0: [0, 1, 2, 3, 4, 5, 6, 7],
877
+ 1: [8, 9, 10, 11, 12, 13, 14, 15],
878
+ 2: [16, 17, 18, 19, 20, 21, 22, 23],
879
+ 3: [24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35],
880
+ }
881
+ model.parallelize(device_map) # Splits the model across several devices
882
+ model.deparallelize() # Put the model back on cpu and cleans memory by calling torch.cuda.empty_cache()
883
+ ```
884
+ """
885
+
886
+
887
+ @add_start_docstrings(
888
+ "The bare GPT2 Model transformer outputting raw hidden-states without any specific head on top.",
889
+ GPT2_START_DOCSTRING,
890
+ )
891
+ class GPT2Model(GPT2PreTrainedModel):
892
+ def __init__(self, config):
893
+ super().__init__(config)
894
+
895
+ self.embed_dim = config.hidden_size
896
+
897
+ self.wte = nn.Embedding(config.vocab_size, self.embed_dim)
898
+ self.wpe = nn.Embedding(config.max_position_embeddings, self.embed_dim)
899
+
900
+ self.drop = nn.Dropout(config.embd_pdrop)
901
+ self.h = nn.ModuleList([GPT2Block(config, layer_idx=i) for i in range(config.num_hidden_layers)])
902
+ self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
903
+
904
+ # Model parallel
905
+ self.model_parallel = False
906
+ self.device_map = None
907
+ self.gradient_checkpointing = False
908
+ self._attn_implementation = config._attn_implementation
909
+
910
+ # Initialize weights and apply final processing
911
+ self.post_init()
912
+
913
+ @add_start_docstrings(PARALLELIZE_DOCSTRING)
914
+ def parallelize(self, device_map=None):
915
+ # Check validity of device_map
916
+ warnings.warn(
917
+ "`GPT2Model.parallelize` is deprecated and will be removed in v5 of Transformers, you should load your"
918
+ " model with `device_map='balanced'` in the call to `from_pretrained`. You can also provide your own"
919
+ " `device_map` but it needs to be a dictionary module_name to device, so for instance {'h.0': 0, 'h.1': 1,"
920
+ " ...}",
921
+ FutureWarning,
922
+ )
923
+ self.device_map = (
924
+ get_device_map(len(self.h), range(torch.cuda.device_count())) if device_map is None else device_map
925
+ )
926
+ assert_device_map(self.device_map, len(self.h))
927
+ self.model_parallel = True
928
+ self.first_device = "cpu" if "cpu" in self.device_map.keys() else "cuda:" + str(min(self.device_map.keys()))
929
+ self.last_device = "cuda:" + str(max(self.device_map.keys()))
930
+ self.wte = self.wte.to(self.first_device)
931
+ self.wpe = self.wpe.to(self.first_device)
932
+ # Load onto devices
933
+ for k, v in self.device_map.items():
934
+ for block in v:
935
+ cuda_device = "cuda:" + str(k)
936
+ self.h[block] = self.h[block].to(cuda_device)
937
+ # ln_f to last
938
+ self.ln_f = self.ln_f.to(self.last_device)
939
+
940
+ @add_start_docstrings(DEPARALLELIZE_DOCSTRING)
941
+ def deparallelize(self):
942
+ warnings.warn(
943
+ "Like `parallelize`, `deparallelize` is deprecated and will be removed in v5 of Transformers.",
944
+ FutureWarning,
945
+ )
946
+ self.model_parallel = False
947
+ self.device_map = None
948
+ self.first_device = "cpu"
949
+ self.last_device = "cpu"
950
+ self.wte = self.wte.to("cpu")
951
+ self.wpe = self.wpe.to("cpu")
952
+ for index in range(len(self.h)):
953
+ self.h[index] = self.h[index].to("cpu")
954
+ self.ln_f = self.ln_f.to("cpu")
955
+ torch.cuda.empty_cache()
956
+
957
+ def get_input_embeddings(self):
958
+ return self.wte
959
+
960
+ def set_input_embeddings(self, new_embeddings):
961
+ self.wte = new_embeddings
962
+
963
+ def _prune_heads(self, heads_to_prune):
964
+ """
965
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer}
966
+ """
967
+ for layer, heads in heads_to_prune.items():
968
+ self.h[layer].attn.prune_heads(heads)
969
+
970
+ @add_start_docstrings_to_model_forward(GPT2_INPUTS_DOCSTRING)
971
+ @add_code_sample_docstrings(
972
+ checkpoint=_CHECKPOINT_FOR_DOC,
973
+ output_type=BaseModelOutputWithPastAndCrossAttentions,
974
+ config_class=_CONFIG_FOR_DOC,
975
+ )
976
+ def forward(
977
+ self,
978
+ input_ids: Optional[torch.LongTensor] = None,
979
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
980
+ attention_mask: Optional[torch.FloatTensor] = None,
981
+ token_type_ids: Optional[torch.LongTensor] = None,
982
+ position_ids: Optional[torch.LongTensor] = None,
983
+ head_mask: Optional[torch.FloatTensor] = None,
984
+ inputs_embeds: Optional[torch.FloatTensor] = None,
985
+ encoder_hidden_states: Optional[torch.Tensor] = None,
986
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
987
+ use_cache: Optional[bool] = None,
988
+ output_attentions: Optional[bool] = None,
989
+ output_hidden_states: Optional[bool] = None,
990
+ return_dict: Optional[bool] = None,
991
+ ) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]:
992
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
993
+ output_hidden_states = (
994
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
995
+ )
996
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
997
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
998
+
999
+ if input_ids is not None and inputs_embeds is not None:
1000
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1001
+ elif input_ids is not None:
1002
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
1003
+ input_shape = input_ids.size()
1004
+ input_ids = input_ids.view(-1, input_shape[-1])
1005
+ batch_size = input_ids.shape[0]
1006
+ elif inputs_embeds is not None:
1007
+ input_shape = inputs_embeds.size()[:-1]
1008
+ batch_size = inputs_embeds.shape[0]
1009
+ else:
1010
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1011
+
1012
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1013
+
1014
+ if token_type_ids is not None:
1015
+ token_type_ids = token_type_ids.view(-1, input_shape[-1])
1016
+
1017
+ if past_key_values is None:
1018
+ past_length = 0
1019
+ past_key_values = tuple([None] * len(self.h))
1020
+ else:
1021
+ past_length = past_key_values[0][0].size(-2)
1022
+ if position_ids is None:
1023
+ position_ids = torch.arange(past_length, input_shape[-1] + past_length, dtype=torch.long, device=device)
1024
+ position_ids = position_ids.unsqueeze(0)
1025
+
1026
+ if inputs_embeds is None:
1027
+ inputs_embeds = self.wte(input_ids)
1028
+ position_embeds = self.wpe(position_ids)
1029
+ hidden_states = inputs_embeds + position_embeds
1030
+
1031
+ # Attention mask.
1032
+ _use_sdpa = self._attn_implementation == "sdpa" and output_attentions is False and head_mask is None
1033
+ if attention_mask is not None:
1034
+ attention_mask = attention_mask.view(batch_size, -1)
1035
+ if self._attn_implementation == "flash_attention_2":
1036
+ attention_mask = attention_mask if 0 in attention_mask else None
1037
+ elif _use_sdpa:
1038
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1039
+ attention_mask=attention_mask,
1040
+ input_shape=(batch_size, input_shape[-1]),
1041
+ inputs_embeds=inputs_embeds,
1042
+ past_key_values_length=past_length,
1043
+ )
1044
+ else:
1045
+ # We create a 3D attention mask from a 2D tensor mask.
1046
+ # Sizes are [batch_size, 1, 1, to_seq_length]
1047
+ # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
1048
+ # this attention mask is more simple than the triangular masking of causal attention
1049
+ # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
1050
+ attention_mask = attention_mask[:, None, None, :]
1051
+
1052
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
1053
+ # masked positions, this operation will create a tensor which is 0.0 for
1054
+ # positions we want to attend and the dtype's smallest value for masked positions.
1055
+ # Since we are adding it to the raw scores before the softmax, this is
1056
+ # effectively the same as removing these entirely.
1057
+ attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility
1058
+ attention_mask = (1.0 - attention_mask) * torch.finfo(self.dtype).min
1059
+
1060
+ # If a 2D or 3D attention mask is provided for the cross-attention
1061
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
1062
+ if self.config.add_cross_attention and encoder_hidden_states is not None:
1063
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
1064
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
1065
+ if encoder_attention_mask is None:
1066
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
1067
+ if _use_sdpa:
1068
+ encoder_attention_mask = _prepare_4d_attention_mask_for_sdpa(
1069
+ mask=encoder_attention_mask, dtype=inputs_embeds.dtype, tgt_len=input_shape[-1]
1070
+ )
1071
+ elif not self._attn_implementation == "flash_attention_2":
1072
+ encoder_attention_mask = self.invert_attention_mask(encoder_attention_mask)
1073
+ else:
1074
+ encoder_attention_mask = None
1075
+
1076
+ # Prepare head mask if needed
1077
+ # 1.0 in head_mask indicate we keep the head
1078
+ # attention_probs has shape bsz x n_heads x N x N
1079
+ # head_mask has shape n_layer x batch x n_heads x N x N
1080
+ head_mask = self.get_head_mask(head_mask, self.config.n_layer)
1081
+
1082
+ if token_type_ids is not None:
1083
+ token_type_embeds = self.wte(token_type_ids)
1084
+ hidden_states = hidden_states + token_type_embeds
1085
+
1086
+ hidden_states = self.drop(hidden_states)
1087
+
1088
+ output_shape = (-1,) + input_shape[1:] + (hidden_states.size(-1),)
1089
+
1090
+ if self.gradient_checkpointing and self.training:
1091
+ if use_cache:
1092
+ logger.warning_once(
1093
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1094
+ )
1095
+ use_cache = False
1096
+
1097
+ presents = () if use_cache else None
1098
+ all_self_attentions = () if output_attentions else None
1099
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
1100
+ all_hidden_states = () if output_hidden_states else None
1101
+ for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
1102
+ # Model parallel
1103
+ if self.model_parallel:
1104
+ torch.cuda.set_device(hidden_states.device)
1105
+ # Ensure layer_past is on same device as hidden_states (might not be correct)
1106
+ if layer_past is not None:
1107
+ layer_past = tuple(past_state.to(hidden_states.device) for past_state in layer_past)
1108
+ # Ensure that attention_mask is always on the same device as hidden_states
1109
+ if attention_mask is not None:
1110
+ attention_mask = attention_mask.to(hidden_states.device)
1111
+ if isinstance(head_mask, torch.Tensor):
1112
+ head_mask = head_mask.to(hidden_states.device)
1113
+ if output_hidden_states:
1114
+ all_hidden_states = all_hidden_states + (hidden_states,)
1115
+
1116
+ if self.gradient_checkpointing and self.training:
1117
+ outputs = self._gradient_checkpointing_func(
1118
+ block.__call__,
1119
+ hidden_states,
1120
+ None,
1121
+ attention_mask,
1122
+ head_mask[i],
1123
+ encoder_hidden_states,
1124
+ encoder_attention_mask,
1125
+ use_cache,
1126
+ output_attentions,
1127
+ )
1128
+ else:
1129
+ outputs = block(
1130
+ hidden_states,
1131
+ layer_past=layer_past,
1132
+ attention_mask=attention_mask,
1133
+ head_mask=head_mask[i],
1134
+ encoder_hidden_states=encoder_hidden_states,
1135
+ encoder_attention_mask=encoder_attention_mask,
1136
+ use_cache=use_cache,
1137
+ output_attentions=output_attentions,
1138
+ )
1139
+
1140
+ hidden_states = outputs[0]
1141
+ if use_cache is True:
1142
+ presents = presents + (outputs[1],)
1143
+
1144
+ if output_attentions:
1145
+ all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
1146
+ if self.config.add_cross_attention:
1147
+ all_cross_attentions = all_cross_attentions + (outputs[3 if use_cache else 2],)
1148
+
1149
+ # Model Parallel: If it's the last layer for that device, put things on the next device
1150
+ if self.model_parallel:
1151
+ for k, v in self.device_map.items():
1152
+ if i == v[-1] and "cuda:" + str(k) != self.last_device:
1153
+ hidden_states = hidden_states.to("cuda:" + str(k + 1))
1154
+
1155
+ hidden_states = self.ln_f(hidden_states)
1156
+
1157
+ hidden_states = hidden_states.view(output_shape)
1158
+ # Add last hidden state
1159
+ if output_hidden_states:
1160
+ all_hidden_states = all_hidden_states + (hidden_states,)
1161
+
1162
+ if not return_dict:
1163
+ return tuple(
1164
+ v
1165
+ for v in [hidden_states, presents, all_hidden_states, all_self_attentions, all_cross_attentions]
1166
+ if v is not None
1167
+ )
1168
+
1169
+ return BaseModelOutputWithPastAndCrossAttentions(
1170
+ last_hidden_state=hidden_states,
1171
+ past_key_values=presents,
1172
+ hidden_states=all_hidden_states,
1173
+ attentions=all_self_attentions,
1174
+ cross_attentions=all_cross_attentions,
1175
+ )
1176
+
1177
+
1178
+ @add_start_docstrings(
1179
+ """
1180
+ The GPT2 Model transformer with a language modeling head on top (linear layer with weights tied to the input
1181
+ embeddings).
1182
+ """,
1183
+ GPT2_START_DOCSTRING,
1184
+ )
1185
+ class GPT2LMHeadModel(GPT2PreTrainedModel):
1186
+ _tied_weights_keys = ["lm_head.weight"]
1187
+
1188
+ def __init__(self, config):
1189
+ super().__init__(config)
1190
+ self.transformer = GPT2Model(config)
1191
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
1192
+
1193
+ # Model parallel
1194
+ self.model_parallel = False
1195
+ self.device_map = None
1196
+
1197
+ # Initialize weights and apply final processing
1198
+ self.post_init()
1199
+
1200
+ @add_start_docstrings(PARALLELIZE_DOCSTRING)
1201
+ def parallelize(self, device_map=None):
1202
+ warnings.warn(
1203
+ "`GPT2LMHeadModel.parallelize` is deprecated and will be removed in v5 of Transformers, you should load"
1204
+ " your model with `device_map='balanced'` in the call to `from_pretrained`. You can also provide your own"
1205
+ " `device_map` but it needs to be a dictionary module_name to device, so for instance {'transformer.h.0':"
1206
+ " 0, 'transformer.h.1': 1, ...}",
1207
+ FutureWarning,
1208
+ )
1209
+ self.device_map = (
1210
+ get_device_map(len(self.transformer.h), range(torch.cuda.device_count()))
1211
+ if device_map is None
1212
+ else device_map
1213
+ )
1214
+ assert_device_map(self.device_map, len(self.transformer.h))
1215
+ self.transformer.parallelize(self.device_map)
1216
+ self.lm_head = self.lm_head.to(self.transformer.first_device)
1217
+ self.model_parallel = True
1218
+
1219
+ @add_start_docstrings(DEPARALLELIZE_DOCSTRING)
1220
+ def deparallelize(self):
1221
+ warnings.warn(
1222
+ "Like `parallelize`, `deparallelize` is deprecated and will be removed in v5 of Transformers.",
1223
+ FutureWarning,
1224
+ )
1225
+ self.transformer.deparallelize()
1226
+ self.transformer = self.transformer.to("cpu")
1227
+ self.lm_head = self.lm_head.to("cpu")
1228
+ self.model_parallel = False
1229
+ torch.cuda.empty_cache()
1230
+
1231
+ def get_output_embeddings(self):
1232
+ return self.lm_head
1233
+
1234
+ def set_output_embeddings(self, new_embeddings):
1235
+ self.lm_head = new_embeddings
1236
+
1237
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
1238
+ token_type_ids = kwargs.get("token_type_ids", None)
1239
+ # Omit tokens covered by past_key_values
1240
+ if past_key_values:
1241
+ past_length = past_key_values[0][0].shape[2]
1242
+
1243
+ # Some generation methods already pass only the last input ID
1244
+ if input_ids.shape[1] > past_length:
1245
+ remove_prefix_length = past_length
1246
+ else:
1247
+ # Default to old behavior: keep only final ID
1248
+ remove_prefix_length = input_ids.shape[1] - 1
1249
+
1250
+ input_ids = input_ids[:, remove_prefix_length:]
1251
+ if token_type_ids is not None:
1252
+ token_type_ids = token_type_ids[:, -input_ids.shape[1] :]
1253
+
1254
+ attention_mask = kwargs.get("attention_mask", None)
1255
+ position_ids = kwargs.get("position_ids", None)
1256
+
1257
+ if attention_mask is not None and position_ids is None:
1258
+ # create position_ids on the fly for batch generation
1259
+ position_ids = attention_mask.long().cumsum(-1) - 1
1260
+ position_ids.masked_fill_(attention_mask == 0, 1)
1261
+ if past_key_values:
1262
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1263
+ else:
1264
+ position_ids = None
1265
+
1266
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1267
+ if inputs_embeds is not None and past_key_values is None:
1268
+ model_inputs = {"inputs_embeds": inputs_embeds}
1269
+ else:
1270
+ model_inputs = {"input_ids": input_ids}
1271
+
1272
+ model_inputs.update(
1273
+ {
1274
+ "past_key_values": past_key_values,
1275
+ "use_cache": kwargs.get("use_cache"),
1276
+ "position_ids": position_ids,
1277
+ "attention_mask": attention_mask,
1278
+ "token_type_ids": token_type_ids,
1279
+ }
1280
+ )
1281
+
1282
+ return model_inputs
1283
+
1284
+ @add_start_docstrings_to_model_forward(GPT2_INPUTS_DOCSTRING)
1285
+ @add_code_sample_docstrings(
1286
+ checkpoint=_CHECKPOINT_FOR_DOC,
1287
+ output_type=CausalLMOutputWithCrossAttentions,
1288
+ config_class=_CONFIG_FOR_DOC,
1289
+ )
1290
+ def forward(
1291
+ self,
1292
+ input_ids: Optional[torch.LongTensor] = None,
1293
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1294
+ attention_mask: Optional[torch.FloatTensor] = None,
1295
+ token_type_ids: Optional[torch.LongTensor] = None,
1296
+ position_ids: Optional[torch.LongTensor] = None,
1297
+ head_mask: Optional[torch.FloatTensor] = None,
1298
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1299
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1300
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
1301
+ labels: Optional[torch.LongTensor] = None,
1302
+ use_cache: Optional[bool] = None,
1303
+ output_attentions: Optional[bool] = None,
1304
+ output_hidden_states: Optional[bool] = None,
1305
+ return_dict: Optional[bool] = None,
1306
+ ) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
1307
+ r"""
1308
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1309
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
1310
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
1311
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
1312
+ """
1313
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1314
+
1315
+ transformer_outputs = self.transformer(
1316
+ input_ids,
1317
+ past_key_values=past_key_values,
1318
+ attention_mask=attention_mask,
1319
+ token_type_ids=token_type_ids,
1320
+ position_ids=position_ids,
1321
+ head_mask=head_mask,
1322
+ inputs_embeds=inputs_embeds,
1323
+ encoder_hidden_states=encoder_hidden_states,
1324
+ encoder_attention_mask=encoder_attention_mask,
1325
+ use_cache=use_cache,
1326
+ output_attentions=output_attentions,
1327
+ output_hidden_states=output_hidden_states,
1328
+ return_dict=return_dict,
1329
+ )
1330
+ hidden_states = transformer_outputs[0]
1331
+
1332
+ # Set device for model parallelism
1333
+ if self.model_parallel:
1334
+ torch.cuda.set_device(self.transformer.first_device)
1335
+ hidden_states = hidden_states.to(self.lm_head.weight.device)
1336
+
1337
+ lm_logits = self.lm_head(hidden_states)
1338
+
1339
+ loss = None
1340
+ if labels is not None:
1341
+ # move labels to correct device to enable model parallelism
1342
+ labels = labels.to(lm_logits.device)
1343
+ # Shift so that tokens < n predict n
1344
+ shift_logits = lm_logits[..., :-1, :].contiguous()
1345
+ shift_labels = labels[..., 1:].contiguous()
1346
+ # Flatten the tokens
1347
+ loss_fct = CrossEntropyLoss()
1348
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
1349
+
1350
+ if not return_dict:
1351
+ output = (lm_logits,) + transformer_outputs[1:]
1352
+ return ((loss,) + output) if loss is not None else output
1353
+
1354
+ return CausalLMOutputWithCrossAttentions(
1355
+ loss=loss,
1356
+ logits=lm_logits,
1357
+ past_key_values=transformer_outputs.past_key_values,
1358
+ hidden_states=transformer_outputs.hidden_states,
1359
+ attentions=transformer_outputs.attentions,
1360
+ cross_attentions=transformer_outputs.cross_attentions,
1361
+ )
1362
+
1363
+ @staticmethod
1364
+ def _reorder_cache(
1365
+ past_key_values: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor
1366
+ ) -> Tuple[Tuple[torch.Tensor]]:
1367
+ """
1368
+ This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
1369
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
1370
+ beam_idx at every generation step.
1371
+ """
1372
+ return tuple(
1373
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past)
1374
+ for layer_past in past_key_values
1375
+ )
1376
+