Felix Marty commited on
Commit
4cb5654
·
1 Parent(s): 7c564bc
Files changed (4) hide show
  1. config.json +43 -0
  2. create_model.py +10 -0
  3. modeling_gpt2.py +1547 -0
  4. pytorch_model.bin +3 -0
config.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "hf-internal-testing/tiny-random-gpt2",
3
+ "activation_function": "gelu_new",
4
+ "architectures": [
5
+ "GPT2CustomLMHeadModel"
6
+ ],
7
+ "attention_probs_dropout_prob": 0.1,
8
+ "attn_pdrop": 0.1,
9
+ "auto_map": {
10
+ "AutoModelForCausalLM": "modeling_gpt2.GPT2CustomLMHeadModel"
11
+ },
12
+ "bos_token_id": 98,
13
+ "embd_pdrop": 0.1,
14
+ "eos_token_id": 98,
15
+ "gradient_checkpointing": false,
16
+ "hidden_act": "gelu",
17
+ "hidden_dropout_prob": 0.1,
18
+ "initializer_range": 0.02,
19
+ "intermediate_size": 37,
20
+ "layer_norm_epsilon": 1e-05,
21
+ "model_type": "gpt2",
22
+ "n_ctx": 512,
23
+ "n_embd": 32,
24
+ "n_head": 4,
25
+ "n_inner": null,
26
+ "n_layer": 5,
27
+ "n_positions": 512,
28
+ "pad_token_id": 98,
29
+ "reorder_and_upcast_attn": false,
30
+ "resid_pdrop": 0.1,
31
+ "scale_attn_by_inverse_layer_idx": false,
32
+ "scale_attn_weights": true,
33
+ "summary_activation": null,
34
+ "summary_first_dropout": 0.1,
35
+ "summary_proj_to_labels": true,
36
+ "summary_type": "cls_index",
37
+ "summary_use_proj": true,
38
+ "torch_dtype": "float32",
39
+ "transformers_version": "4.25.1",
40
+ "type_vocab_size": 16,
41
+ "use_cache": true,
42
+ "vocab_size": 1000
43
+ }
create_model.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoConfig
2
+
3
+ from modeling.modeling_gpt2 import GPT2CustomLMHeadModel
4
+
5
+ cfg = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-gpt2")
6
+
7
+ GPT2CustomLMHeadModel.register_for_auto_class("AutoModelForCausalLM")
8
+
9
+ model = GPT2CustomLMHeadModel(cfg)
10
+ model.save_pretrained("/home/fxmarty/hf_internship/tiny-testing-gpt2-remote-code")
modeling_gpt2.py ADDED
@@ -0,0 +1,1547 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from dataclasses import dataclass
21
+ from typing import Optional, Tuple, Union
22
+
23
+ import torch
24
+ import torch.utils.checkpoint
25
+ from torch import nn
26
+ from torch.cuda.amp import autocast
27
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
28
+
29
+ from transformers.activations import ACT2FN
30
+ from transformers.modeling_outputs import (
31
+ BaseModelOutputWithPastAndCrossAttentions,
32
+ CausalLMOutputWithCrossAttentions,
33
+ SequenceClassifierOutputWithPast,
34
+ TokenClassifierOutput,
35
+ )
36
+ from transformers.modeling_utils import PreTrainedModel, SequenceSummary
37
+ from transformers.pytorch_utils import Conv1D, find_pruneable_heads_and_indices, prune_conv1d_layer
38
+ from transformers.utils import (
39
+ ModelOutput,
40
+ add_code_sample_docstrings,
41
+ add_start_docstrings,
42
+ add_start_docstrings_to_model_forward,
43
+ logging,
44
+ replace_return_docstrings,
45
+ )
46
+ from transformers.utils.model_parallel_utils import assert_device_map, get_device_map
47
+ from transformers import GPT2Config
48
+
49
+
50
+ logger = logging.get_logger(__name__)
51
+
52
+ _CHECKPOINT_FOR_DOC = "gpt2"
53
+ _CONFIG_FOR_DOC = "GPT2Config"
54
+ _TOKENIZER_FOR_DOC = "GPT2Tokenizer"
55
+
56
+ GPT2_PRETRAINED_MODEL_ARCHIVE_LIST = [
57
+ "gpt2",
58
+ "gpt2-medium",
59
+ "gpt2-large",
60
+ "gpt2-xl",
61
+ "distilgpt2",
62
+ # See all GPT-2 models at https://huggingface.co/models?filter=gpt2
63
+ ]
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
+ assert (
113
+ pointer.shape == array.shape
114
+ ), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched"
115
+ except AssertionError as e:
116
+ e.args += (pointer.shape, array.shape)
117
+ raise
118
+ logger.info(f"Initialize PyTorch weight {name}")
119
+ pointer.data = torch.from_numpy(array)
120
+ return model
121
+
122
+
123
+ class GPT2Attention(nn.Module):
124
+ def __init__(self, config, is_cross_attention=False, layer_idx=None):
125
+ super().__init__()
126
+
127
+ max_positions = config.max_position_embeddings
128
+ self.register_buffer(
129
+ "bias",
130
+ torch.tril(torch.ones((max_positions, max_positions), dtype=torch.uint8)).view(
131
+ 1, 1, max_positions, max_positions
132
+ ),
133
+ )
134
+ self.register_buffer("masked_bias", torch.tensor(-1e4))
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
+
164
+ self.pruned_heads = set()
165
+
166
+ def prune_heads(self, heads):
167
+ if len(heads) == 0:
168
+ return
169
+ heads, index = find_pruneable_heads_and_indices(heads, self.num_heads, self.head_dim, self.pruned_heads)
170
+ index_attn = torch.cat([index, index + self.split_size, index + (2 * self.split_size)])
171
+
172
+ # Prune conv1d layers
173
+ self.c_attn = prune_conv1d_layer(self.c_attn, index_attn, dim=1)
174
+ self.c_proj = prune_conv1d_layer(self.c_proj, index, dim=0)
175
+
176
+ # Update hyper params
177
+ self.split_size = (self.split_size // self.num_heads) * (self.num_heads - len(heads))
178
+ self.num_heads = self.num_heads - len(heads)
179
+ self.pruned_heads = self.pruned_heads.union(heads)
180
+
181
+ def _attn(self, query, key, value, attention_mask=None, head_mask=None):
182
+ attn_weights = torch.matmul(query, key.transpose(-1, -2))
183
+
184
+ if self.scale_attn_weights:
185
+ attn_weights = attn_weights / torch.full(
186
+ [], value.size(-1) ** 0.5, dtype=attn_weights.dtype, device=attn_weights.device
187
+ )
188
+
189
+ # Layer-wise attention scaling
190
+ if self.scale_attn_by_inverse_layer_idx:
191
+ attn_weights = attn_weights / float(self.layer_idx + 1)
192
+
193
+ if not self.is_cross_attention:
194
+ # if only "normal" attention layer implements causal mask
195
+ query_length, key_length = query.size(-2), key.size(-2)
196
+ causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length].to(torch.bool)
197
+ mask_value = torch.finfo(attn_weights.dtype).min
198
+ # Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`.
199
+ # Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device`
200
+ mask_value = torch.full([], mask_value, dtype=attn_weights.dtype).to(attn_weights.device)
201
+ attn_weights = torch.where(causal_mask, attn_weights, mask_value)
202
+
203
+ if attention_mask is not None:
204
+ # Apply the attention mask
205
+ attn_weights = attn_weights + attention_mask
206
+
207
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
208
+
209
+ # Downcast (if necessary) back to V's dtype (if in mixed-precision) -- No-Op otherwise
210
+ attn_weights = attn_weights.type(value.dtype)
211
+ attn_weights = self.attn_dropout(attn_weights)
212
+
213
+ # Mask heads if we want to
214
+ if head_mask is not None:
215
+ attn_weights = attn_weights * head_mask
216
+
217
+ attn_output = torch.matmul(attn_weights, value)
218
+
219
+ return attn_output, attn_weights
220
+
221
+ def _upcast_and_reordered_attn(self, query, key, value, attention_mask=None, head_mask=None):
222
+ # Use `torch.baddbmm` (a bit more efficient w/ alpha param for scaling -- from Megatron-LM)
223
+ bsz, num_heads, q_seq_len, dk = query.size()
224
+ _, _, k_seq_len, _ = key.size()
225
+
226
+ # Preallocate attn_weights for `baddbmm`
227
+ attn_weights = torch.empty(bsz * num_heads, q_seq_len, k_seq_len, dtype=torch.float32, device=query.device)
228
+
229
+ # Compute Scale Factor
230
+ scale_factor = 1.0
231
+ if self.scale_attn_weights:
232
+ scale_factor /= float(value.size(-1)) ** 0.5
233
+
234
+ if self.scale_attn_by_inverse_layer_idx:
235
+ scale_factor /= float(self.layer_idx + 1)
236
+
237
+ # Upcast (turn off autocast) and reorder (Scale K by 1 / root(dk))
238
+ with autocast(enabled=False):
239
+ q, k = query.reshape(-1, q_seq_len, dk), key.transpose(-1, -2).reshape(-1, dk, k_seq_len)
240
+ attn_weights = torch.baddbmm(attn_weights, q.float(), k.float(), beta=0, alpha=scale_factor)
241
+ attn_weights = attn_weights.reshape(bsz, num_heads, q_seq_len, k_seq_len)
242
+
243
+ if not self.is_cross_attention:
244
+ # if only "normal" attention layer implements causal mask
245
+ query_length, key_length = query.size(-2), key.size(-2)
246
+ causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length].bool()
247
+ mask_value = torch.finfo(attn_weights.dtype).min
248
+ # Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`.
249
+ # Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device`
250
+ mask_value = torch.tensor(mask_value, dtype=attn_weights.dtype).to(attn_weights.device)
251
+ attn_weights = torch.where(causal_mask, attn_weights, mask_value)
252
+
253
+ if attention_mask is not None:
254
+ # Apply the attention mask
255
+ attn_weights = attn_weights + attention_mask
256
+
257
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
258
+
259
+ # Downcast (if necessary) back to V's dtype (if in mixed-precision) -- No-Op if otherwise
260
+ if attn_weights.dtype != torch.float32:
261
+ raise RuntimeError("Error with upcasting, attn_weights does not have dtype torch.float32")
262
+ attn_weights = attn_weights.type(value.dtype)
263
+ attn_weights = self.attn_dropout(attn_weights)
264
+
265
+ # Mask heads if we want to
266
+ if head_mask is not None:
267
+ attn_weights = attn_weights * head_mask
268
+
269
+ attn_output = torch.matmul(attn_weights, value)
270
+
271
+ return attn_output, attn_weights
272
+
273
+ def _split_heads(self, tensor, num_heads, attn_head_size):
274
+ """
275
+ Splits hidden_size dim into attn_head_size and num_heads
276
+ """
277
+ new_shape = tensor.size()[:-1] + (num_heads, attn_head_size)
278
+ tensor = tensor.view(new_shape)
279
+ return tensor.permute(0, 2, 1, 3) # (batch, head, seq_length, head_features)
280
+
281
+ def _merge_heads(self, tensor, num_heads, attn_head_size):
282
+ """
283
+ Merges attn_head_size dim and num_attn_heads dim into hidden_size
284
+ """
285
+ tensor = tensor.permute(0, 2, 1, 3).contiguous()
286
+ new_shape = tensor.size()[:-2] + (num_heads * attn_head_size,)
287
+ return tensor.view(new_shape)
288
+
289
+ def forward(
290
+ self,
291
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
292
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
293
+ attention_mask: Optional[torch.FloatTensor] = None,
294
+ head_mask: Optional[torch.FloatTensor] = None,
295
+ encoder_hidden_states: Optional[torch.Tensor] = None,
296
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
297
+ use_cache: Optional[bool] = False,
298
+ output_attentions: Optional[bool] = False,
299
+ ) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]], ...]:
300
+ if encoder_hidden_states is not None:
301
+ if not hasattr(self, "q_attn"):
302
+ raise ValueError(
303
+ "If class is used as cross attention, the weights `q_attn` have to be defined. "
304
+ "Please make sure to instantiate class with `GPT2Attention(..., is_cross_attention=True)`."
305
+ )
306
+
307
+ query = self.q_attn(hidden_states)
308
+ key, value = self.c_attn(encoder_hidden_states).split(self.split_size, dim=2)
309
+ attention_mask = encoder_attention_mask
310
+ else:
311
+ query, key, value = self.c_attn(hidden_states).split(self.split_size, dim=2)
312
+
313
+ query = self._split_heads(query, self.num_heads, self.head_dim)
314
+ key = self._split_heads(key, self.num_heads, self.head_dim)
315
+ value = self._split_heads(value, self.num_heads, self.head_dim)
316
+
317
+ value = value + 10
318
+ print("increased value")
319
+
320
+ if layer_past is not None:
321
+ past_key, past_value = layer_past
322
+ key = torch.cat((past_key, key), dim=-2)
323
+ value = torch.cat((past_value, value), dim=-2)
324
+
325
+ if use_cache is True:
326
+ present = (key, value)
327
+ else:
328
+ present = None
329
+
330
+ if self.reorder_and_upcast_attn:
331
+ attn_output, attn_weights = self._upcast_and_reordered_attn(query, key, value, attention_mask, head_mask)
332
+ else:
333
+ attn_output, attn_weights = self._attn(query, key, value, attention_mask, head_mask)
334
+
335
+ attn_output = self._merge_heads(attn_output, self.num_heads, self.head_dim)
336
+ attn_output = self.c_proj(attn_output)
337
+ attn_output = self.resid_dropout(attn_output)
338
+
339
+ outputs = (attn_output, present)
340
+ if output_attentions:
341
+ outputs += (attn_weights,)
342
+
343
+ return outputs # a, present, (attentions)
344
+
345
+
346
+ class GPT2MLP(nn.Module):
347
+ def __init__(self, intermediate_size, config):
348
+ super().__init__()
349
+ embed_dim = config.hidden_size
350
+ self.c_fc = Conv1D(intermediate_size, embed_dim)
351
+ self.c_proj = Conv1D(embed_dim, intermediate_size)
352
+ self.act = ACT2FN[config.activation_function]
353
+ self.dropout = nn.Dropout(config.resid_pdrop)
354
+
355
+ def forward(self, hidden_states: Optional[Tuple[torch.FloatTensor]]) -> torch.FloatTensor:
356
+ hidden_states = self.c_fc(hidden_states)
357
+ hidden_states = self.act(hidden_states)
358
+ hidden_states = self.c_proj(hidden_states)
359
+ hidden_states = self.dropout(hidden_states)
360
+ return hidden_states
361
+
362
+
363
+ class GPT2Block(nn.Module):
364
+ def __init__(self, config, layer_idx=None):
365
+ super().__init__()
366
+ hidden_size = config.hidden_size
367
+ inner_dim = config.n_inner if config.n_inner is not None else 4 * hidden_size
368
+
369
+ self.ln_1 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
370
+ self.attn = GPT2Attention(config, layer_idx=layer_idx)
371
+ self.ln_2 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
372
+
373
+ if config.add_cross_attention:
374
+ self.crossattention = GPT2Attention(config, is_cross_attention=True, layer_idx=layer_idx)
375
+ self.ln_cross_attn = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
376
+
377
+ self.mlp = GPT2MLP(inner_dim, config)
378
+
379
+ def forward(
380
+ self,
381
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
382
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
383
+ attention_mask: Optional[torch.FloatTensor] = None,
384
+ head_mask: Optional[torch.FloatTensor] = None,
385
+ encoder_hidden_states: Optional[torch.Tensor] = None,
386
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
387
+ use_cache: Optional[bool] = False,
388
+ output_attentions: Optional[bool] = False,
389
+ ) -> Union[Tuple[torch.Tensor], Optional[Tuple[torch.Tensor, Tuple[torch.FloatTensor, ...]]]]:
390
+ residual = hidden_states
391
+ hidden_states = self.ln_1(hidden_states)
392
+ attn_outputs = self.attn(
393
+ hidden_states,
394
+ layer_past=layer_past,
395
+ attention_mask=attention_mask,
396
+ head_mask=head_mask,
397
+ use_cache=use_cache,
398
+ output_attentions=output_attentions,
399
+ )
400
+ attn_output = attn_outputs[0] # output_attn: a, present, (attentions)
401
+ outputs = attn_outputs[1:]
402
+ # residual connection
403
+ hidden_states = attn_output + residual
404
+
405
+ if encoder_hidden_states is not None:
406
+ # add one self-attention block for cross-attention
407
+ if not hasattr(self, "crossattention"):
408
+ raise ValueError(
409
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with "
410
+ "cross-attention layers by setting `config.add_cross_attention=True`"
411
+ )
412
+ residual = hidden_states
413
+ hidden_states = self.ln_cross_attn(hidden_states)
414
+ cross_attn_outputs = self.crossattention(
415
+ hidden_states,
416
+ attention_mask=attention_mask,
417
+ head_mask=head_mask,
418
+ encoder_hidden_states=encoder_hidden_states,
419
+ encoder_attention_mask=encoder_attention_mask,
420
+ output_attentions=output_attentions,
421
+ )
422
+ attn_output = cross_attn_outputs[0]
423
+ # residual connection
424
+ hidden_states = residual + attn_output
425
+ outputs = outputs + cross_attn_outputs[2:] # add cross attentions if we output attention weights
426
+
427
+ residual = hidden_states
428
+ hidden_states = self.ln_2(hidden_states)
429
+ feed_forward_hidden_states = self.mlp(hidden_states)
430
+ # residual connection
431
+ hidden_states = residual + feed_forward_hidden_states
432
+
433
+ if use_cache:
434
+ outputs = (hidden_states,) + outputs
435
+ else:
436
+ outputs = (hidden_states,) + outputs[1:]
437
+
438
+ return outputs # hidden_states, present, (attentions, cross_attentions)
439
+
440
+
441
+ class GPT2PreTrainedModel(PreTrainedModel):
442
+ """
443
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
444
+ models.
445
+ """
446
+
447
+ config_class = GPT2Config
448
+ load_tf_weights = load_tf_weights_in_gpt2
449
+ base_model_prefix = "transformer"
450
+ is_parallelizable = True
451
+ supports_gradient_checkpointing = True
452
+ _no_split_modules = ["GPT2Block"]
453
+
454
+ def __init__(self, *inputs, **kwargs):
455
+ super().__init__(*inputs, **kwargs)
456
+
457
+ def _init_weights(self, module):
458
+ """Initialize the weights."""
459
+ if isinstance(module, (nn.Linear, Conv1D)):
460
+ # Slightly different from the TF version which uses truncated_normal for initialization
461
+ # cf https://github.com/pytorch/pytorch/pull/5617
462
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
463
+ if module.bias is not None:
464
+ module.bias.data.zero_()
465
+ elif isinstance(module, nn.Embedding):
466
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
467
+ if module.padding_idx is not None:
468
+ module.weight.data[module.padding_idx].zero_()
469
+ elif isinstance(module, nn.LayerNorm):
470
+ module.bias.data.zero_()
471
+ module.weight.data.fill_(1.0)
472
+
473
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
474
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
475
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
476
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
477
+ #
478
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
479
+ for name, p in module.named_parameters():
480
+ if name == "c_proj.weight":
481
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
482
+ p.data.normal_(mean=0.0, std=(self.config.initializer_range / math.sqrt(2 * self.config.n_layer)))
483
+
484
+ def _set_gradient_checkpointing(self, module, value=False):
485
+ if isinstance(module, GPT2Model):
486
+ module.gradient_checkpointing = value
487
+
488
+
489
+ @dataclass
490
+ class GPT2DoubleHeadsModelOutput(ModelOutput):
491
+ """
492
+ Base class for outputs of models predicting if two sentences are consecutive or not.
493
+
494
+ Args:
495
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
496
+ Language modeling loss.
497
+ mc_loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `mc_labels` is provided):
498
+ Multiple choice classification loss.
499
+ logits (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, config.vocab_size)`):
500
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
501
+ mc_logits (`torch.FloatTensor` of shape `(batch_size, num_choices)`):
502
+ Prediction scores of the multiple choice classification head (scores for each choice before SoftMax).
503
+ past_key_values (`Tuple[Tuple[torch.Tensor]]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
504
+ Tuple of length `config.n_layers`, containing tuples of tensors of shape `(batch_size, num_heads,
505
+ sequence_length, embed_size_per_head)`).
506
+
507
+ Contains pre-computed hidden-states (key and values in the attention blocks) that can be used (see
508
+ `past_key_values` input) to speed up sequential decoding.
509
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
510
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
511
+ shape `(batch_size, sequence_length, hidden_size)`.
512
+
513
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
514
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
515
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
516
+ sequence_length)`.
517
+
518
+ GPT2Attentions weights after the attention softmax, used to compute the weighted average in the
519
+ self-attention heads.
520
+ """
521
+
522
+ loss: Optional[torch.FloatTensor] = None
523
+ mc_loss: Optional[torch.FloatTensor] = None
524
+ logits: torch.FloatTensor = None
525
+ mc_logits: torch.FloatTensor = None
526
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
527
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
528
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
529
+
530
+
531
+ GPT2_START_DOCSTRING = r"""
532
+
533
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
534
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
535
+ etc.)
536
+
537
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
538
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
539
+ and behavior.
540
+
541
+ Parameters:
542
+ config ([`GPT2Config`]): Model configuration class with all the parameters of the model.
543
+ Initializing with a config file does not load the weights associated with the model, only the
544
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
545
+ """
546
+
547
+ GPT2_INPUTS_DOCSTRING = r"""
548
+ Args:
549
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
550
+ `input_ids_length` = `sequence_length` if `past_key_values` is `None` else
551
+ `past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input
552
+ sequence tokens in the vocabulary.
553
+
554
+ If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
555
+ `input_ids`.
556
+
557
+ Indices can be obtained using [`GPT2Tokenizer`]. See [`PreTrainedTokenizer.encode`] and
558
+ [`PreTrainedTokenizer.__call__`] for details.
559
+
560
+ [What are input IDs?](../glossary#input-ids)
561
+ past_key_values (`Tuple[Tuple[torch.Tensor]]` of length `config.n_layers`):
562
+ Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
563
+ `past_key_values` output below). Can be used to speed up sequential decoding. The `input_ids` which have
564
+ their past given to this model should not be passed as `input_ids` as they have already been computed.
565
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
566
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
567
+
568
+ - 1 for tokens that are **not masked**,
569
+ - 0 for tokens that are **masked**.
570
+
571
+ If `past_key_values` is used, `attention_mask` needs to contain the masking strategy that was used for
572
+ `past_key_values`. In other words, the `attention_mask` always has to have the length:
573
+ `len(past_key_values) + len(input_ids)`
574
+
575
+ [What are attention masks?](../glossary#attention-mask)
576
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`, *optional*):
577
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
578
+ 1]`:
579
+
580
+ - 0 corresponds to a *sentence A* token,
581
+ - 1 corresponds to a *sentence B* token.
582
+
583
+ [What are token type IDs?](../glossary#token-type-ids)
584
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
585
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
586
+ config.max_position_embeddings - 1]`.
587
+
588
+ [What are position IDs?](../glossary#position-ids)
589
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
590
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
591
+
592
+ - 1 indicates the head is **not masked**,
593
+ - 0 indicates the head is **masked**.
594
+
595
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
596
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
597
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
598
+ model's internal embedding lookup matrix.
599
+
600
+ If `past_key_values` is used, optionally only the last `inputs_embeds` have to be input (see
601
+ `past_key_values`).
602
+ use_cache (`bool`, *optional*):
603
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
604
+ `past_key_values`).
605
+ output_attentions (`bool`, *optional*):
606
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
607
+ tensors for more detail.
608
+ output_hidden_states (`bool`, *optional*):
609
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
610
+ more detail.
611
+ return_dict (`bool`, *optional*):
612
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
613
+ """
614
+ PARALLELIZE_DOCSTRING = r"""
615
+ This is an experimental feature and is a subject to change at a moment's notice.
616
+
617
+ Uses a device map to distribute attention modules of the model across several devices. If no device map is given,
618
+ it will evenly distribute blocks across all devices.
619
+
620
+ Args:
621
+ device_map (`Dict[int, list]`, optional, defaults to None):
622
+ A dictionary that maps attention modules to devices. Note that the embedding module and LMHead are always
623
+ automatically mapped to the first device (for esoteric reasons). That means that the first device should
624
+ have fewer attention modules mapped to it than other devices. For reference, the gpt2 models have the
625
+ following number of attention modules:
626
+
627
+ - gpt2: 12
628
+ - gpt2-medium: 24
629
+ - gpt2-large: 36
630
+ - gpt2-xl: 48
631
+
632
+ Example:
633
+
634
+ ```python
635
+ # 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:
636
+ model = GPT2LMHeadModel.from_pretrained("gpt2-xl")
637
+ device_map = {
638
+ 0: [0, 1, 2, 3, 4, 5, 6, 7, 8],
639
+ 1: [9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21],
640
+ 2: [22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34],
641
+ 3: [35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47],
642
+ }
643
+ model.parallelize(device_map)
644
+ ```
645
+ """
646
+ DEPARALLELIZE_DOCSTRING = r"""
647
+ Moves the model to cpu from a model parallel state.
648
+
649
+ Example:
650
+
651
+ ```python
652
+ # On a 4 GPU machine with gpt2-large:
653
+ model = GPT2LMHeadModel.from_pretrained("gpt2-large")
654
+ device_map = {
655
+ 0: [0, 1, 2, 3, 4, 5, 6, 7],
656
+ 1: [8, 9, 10, 11, 12, 13, 14, 15],
657
+ 2: [16, 17, 18, 19, 20, 21, 22, 23],
658
+ 3: [24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35],
659
+ }
660
+ model.parallelize(device_map) # Splits the model across several devices
661
+ model.deparallelize() # Put the model back on cpu and cleans memory by calling torch.cuda.empty_cache()
662
+ ```
663
+ """
664
+
665
+
666
+ @add_start_docstrings(
667
+ "The bare GPT2 Model transformer outputting raw hidden-states without any specific head on top.",
668
+ GPT2_START_DOCSTRING,
669
+ )
670
+ class GPT2Model(GPT2PreTrainedModel):
671
+ _keys_to_ignore_on_load_missing = ["attn.masked_bias"]
672
+
673
+ def __init__(self, config):
674
+ super().__init__(config)
675
+
676
+ self.embed_dim = config.hidden_size
677
+
678
+ self.wte = nn.Embedding(config.vocab_size, self.embed_dim)
679
+ self.wpe = nn.Embedding(config.max_position_embeddings, self.embed_dim)
680
+
681
+ self.drop = nn.Dropout(config.embd_pdrop)
682
+ self.h = nn.ModuleList([GPT2Block(config, layer_idx=i) for i in range(config.num_hidden_layers)])
683
+ self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
684
+
685
+ # Model parallel
686
+ self.model_parallel = False
687
+ self.device_map = None
688
+ self.gradient_checkpointing = False
689
+
690
+ # Initialize weights and apply final processing
691
+ self.post_init()
692
+
693
+ @add_start_docstrings(PARALLELIZE_DOCSTRING)
694
+ def parallelize(self, device_map=None):
695
+ # Check validity of device_map
696
+ self.device_map = (
697
+ get_device_map(len(self.h), range(torch.cuda.device_count())) if device_map is None else device_map
698
+ )
699
+ assert_device_map(self.device_map, len(self.h))
700
+ self.model_parallel = True
701
+ self.first_device = "cpu" if "cpu" in self.device_map.keys() else "cuda:" + str(min(self.device_map.keys()))
702
+ self.last_device = "cuda:" + str(max(self.device_map.keys()))
703
+ self.wte = self.wte.to(self.first_device)
704
+ self.wpe = self.wpe.to(self.first_device)
705
+ # Load onto devices
706
+ for k, v in self.device_map.items():
707
+ for block in v:
708
+ cuda_device = "cuda:" + str(k)
709
+ self.h[block] = self.h[block].to(cuda_device)
710
+ # ln_f to last
711
+ self.ln_f = self.ln_f.to(self.last_device)
712
+
713
+ @add_start_docstrings(DEPARALLELIZE_DOCSTRING)
714
+ def deparallelize(self):
715
+ self.model_parallel = False
716
+ self.device_map = None
717
+ self.first_device = "cpu"
718
+ self.last_device = "cpu"
719
+ self.wte = self.wte.to("cpu")
720
+ self.wpe = self.wpe.to("cpu")
721
+ for index in range(len(self.h)):
722
+ self.h[index] = self.h[index].to("cpu")
723
+ self.ln_f = self.ln_f.to("cpu")
724
+ torch.cuda.empty_cache()
725
+
726
+ def get_input_embeddings(self):
727
+ return self.wte
728
+
729
+ def set_input_embeddings(self, new_embeddings):
730
+ self.wte = new_embeddings
731
+
732
+ def _prune_heads(self, heads_to_prune):
733
+ """
734
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer}
735
+ """
736
+ for layer, heads in heads_to_prune.items():
737
+ self.h[layer].attn.prune_heads(heads)
738
+
739
+ @add_start_docstrings_to_model_forward(GPT2_INPUTS_DOCSTRING)
740
+ @add_code_sample_docstrings(
741
+ processor_class=_TOKENIZER_FOR_DOC,
742
+ checkpoint=_CHECKPOINT_FOR_DOC,
743
+ output_type=BaseModelOutputWithPastAndCrossAttentions,
744
+ config_class=_CONFIG_FOR_DOC,
745
+ )
746
+ def forward(
747
+ self,
748
+ input_ids: Optional[torch.LongTensor] = None,
749
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
750
+ attention_mask: Optional[torch.FloatTensor] = None,
751
+ token_type_ids: Optional[torch.LongTensor] = None,
752
+ position_ids: Optional[torch.LongTensor] = None,
753
+ head_mask: Optional[torch.FloatTensor] = None,
754
+ inputs_embeds: Optional[torch.FloatTensor] = None,
755
+ encoder_hidden_states: Optional[torch.Tensor] = None,
756
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
757
+ use_cache: Optional[bool] = None,
758
+ output_attentions: Optional[bool] = None,
759
+ output_hidden_states: Optional[bool] = None,
760
+ return_dict: Optional[bool] = None,
761
+ ) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]:
762
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
763
+ output_hidden_states = (
764
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
765
+ )
766
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
767
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
768
+
769
+ if input_ids is not None and inputs_embeds is not None:
770
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
771
+ elif input_ids is not None:
772
+ input_shape = input_ids.size()
773
+ input_ids = input_ids.view(-1, input_shape[-1])
774
+ batch_size = input_ids.shape[0]
775
+ elif inputs_embeds is not None:
776
+ input_shape = inputs_embeds.size()[:-1]
777
+ batch_size = inputs_embeds.shape[0]
778
+ else:
779
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
780
+
781
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
782
+
783
+ if token_type_ids is not None:
784
+ token_type_ids = token_type_ids.view(-1, input_shape[-1])
785
+ if position_ids is not None:
786
+ position_ids = position_ids.view(-1, input_shape[-1])
787
+
788
+ if past_key_values is None:
789
+ past_length = 0
790
+ past_key_values = tuple([None] * len(self.h))
791
+ else:
792
+ past_length = past_key_values[0][0].size(-2)
793
+ if position_ids is None:
794
+ position_ids = torch.arange(past_length, input_shape[-1] + past_length, dtype=torch.long, device=device)
795
+ position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])
796
+
797
+ # GPT2Attention mask.
798
+ if attention_mask is not None:
799
+ if batch_size <= 0:
800
+ raise ValueError("batch_size has to be defined and > 0")
801
+ attention_mask = attention_mask.view(batch_size, -1)
802
+ # We create a 3D attention mask from a 2D tensor mask.
803
+ # Sizes are [batch_size, 1, 1, to_seq_length]
804
+ # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
805
+ # this attention mask is more simple than the triangular masking of causal attention
806
+ # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
807
+ attention_mask = attention_mask[:, None, None, :]
808
+
809
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
810
+ # masked positions, this operation will create a tensor which is 0.0 for
811
+ # positions we want to attend and the dtype's smallest value for masked positions.
812
+ # Since we are adding it to the raw scores before the softmax, this is
813
+ # effectively the same as removing these entirely.
814
+ attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility
815
+ attention_mask = (1.0 - attention_mask) * torch.finfo(self.dtype).min
816
+
817
+ # If a 2D or 3D attention mask is provided for the cross-attention
818
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
819
+ if self.config.add_cross_attention and encoder_hidden_states is not None:
820
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
821
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
822
+ if encoder_attention_mask is None:
823
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
824
+ encoder_attention_mask = self.invert_attention_mask(encoder_attention_mask)
825
+ else:
826
+ encoder_attention_mask = None
827
+
828
+ # Prepare head mask if needed
829
+ # 1.0 in head_mask indicate we keep the head
830
+ # attention_probs has shape bsz x n_heads x N x N
831
+ # head_mask has shape n_layer x batch x n_heads x N x N
832
+ head_mask = self.get_head_mask(head_mask, self.config.n_layer)
833
+
834
+ if inputs_embeds is None:
835
+ inputs_embeds = self.wte(input_ids)
836
+ position_embeds = self.wpe(position_ids)
837
+ hidden_states = inputs_embeds + position_embeds
838
+
839
+ if token_type_ids is not None:
840
+ token_type_embeds = self.wte(token_type_ids)
841
+ hidden_states = hidden_states + token_type_embeds
842
+
843
+ hidden_states = self.drop(hidden_states)
844
+
845
+ output_shape = input_shape + (hidden_states.size(-1),)
846
+
847
+ presents = () if use_cache else None
848
+ all_self_attentions = () if output_attentions else None
849
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
850
+ all_hidden_states = () if output_hidden_states else None
851
+ for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
852
+
853
+ # Model parallel
854
+ if self.model_parallel:
855
+ torch.cuda.set_device(hidden_states.device)
856
+ # Ensure layer_past is on same device as hidden_states (might not be correct)
857
+ if layer_past is not None:
858
+ layer_past = tuple(past_state.to(hidden_states.device) for past_state in layer_past)
859
+ # Ensure that attention_mask is always on the same device as hidden_states
860
+ if attention_mask is not None:
861
+ attention_mask = attention_mask.to(hidden_states.device)
862
+ if isinstance(head_mask, torch.Tensor):
863
+ head_mask = head_mask.to(hidden_states.device)
864
+ if output_hidden_states:
865
+ all_hidden_states = all_hidden_states + (hidden_states,)
866
+
867
+ if self.gradient_checkpointing and self.training:
868
+
869
+ if use_cache:
870
+ logger.warning(
871
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
872
+ )
873
+ use_cache = False
874
+
875
+ def create_custom_forward(module):
876
+ def custom_forward(*inputs):
877
+ # None for past_key_value
878
+ return module(*inputs, use_cache, output_attentions)
879
+
880
+ return custom_forward
881
+
882
+ outputs = torch.utils.checkpoint.checkpoint(
883
+ create_custom_forward(block),
884
+ hidden_states,
885
+ None,
886
+ attention_mask,
887
+ head_mask[i],
888
+ encoder_hidden_states,
889
+ encoder_attention_mask,
890
+ )
891
+ else:
892
+ outputs = block(
893
+ hidden_states,
894
+ layer_past=layer_past,
895
+ attention_mask=attention_mask,
896
+ head_mask=head_mask[i],
897
+ encoder_hidden_states=encoder_hidden_states,
898
+ encoder_attention_mask=encoder_attention_mask,
899
+ use_cache=use_cache,
900
+ output_attentions=output_attentions,
901
+ )
902
+
903
+ hidden_states = outputs[0]
904
+ if use_cache is True:
905
+ presents = presents + (outputs[1],)
906
+
907
+ if output_attentions:
908
+ all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
909
+ if self.config.add_cross_attention:
910
+ all_cross_attentions = all_cross_attentions + (outputs[3 if use_cache else 2],)
911
+
912
+ # Model Parallel: If it's the last layer for that device, put things on the next device
913
+ if self.model_parallel:
914
+ for k, v in self.device_map.items():
915
+ if i == v[-1] and "cuda:" + str(k) != self.last_device:
916
+ hidden_states = hidden_states.to("cuda:" + str(k + 1))
917
+
918
+ hidden_states = self.ln_f(hidden_states)
919
+
920
+ hidden_states = hidden_states.view(output_shape)
921
+ # Add last hidden state
922
+ if output_hidden_states:
923
+ all_hidden_states = all_hidden_states + (hidden_states,)
924
+
925
+ if not return_dict:
926
+ return tuple(
927
+ v
928
+ for v in [hidden_states, presents, all_hidden_states, all_self_attentions, all_cross_attentions]
929
+ if v is not None
930
+ )
931
+
932
+ return BaseModelOutputWithPastAndCrossAttentions(
933
+ last_hidden_state=hidden_states,
934
+ past_key_values=presents,
935
+ hidden_states=all_hidden_states,
936
+ attentions=all_self_attentions,
937
+ cross_attentions=all_cross_attentions,
938
+ )
939
+
940
+
941
+ @add_start_docstrings(
942
+ """
943
+ The GPT2 Model transformer with a language modeling head on top (linear layer with weights tied to the input
944
+ embeddings).
945
+ """,
946
+ GPT2_START_DOCSTRING,
947
+ )
948
+ class GPT2CustomLMHeadModel(GPT2PreTrainedModel):
949
+ _keys_to_ignore_on_load_missing = [r"attn.masked_bias", r"attn.bias", r"lm_head.weight"]
950
+
951
+ def __init__(self, config):
952
+ super().__init__(config)
953
+ self.transformer = GPT2Model(config)
954
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
955
+
956
+ # Model parallel
957
+ self.model_parallel = False
958
+ self.device_map = None
959
+
960
+ # Initialize weights and apply final processing
961
+ self.post_init()
962
+
963
+ @add_start_docstrings(PARALLELIZE_DOCSTRING)
964
+ def parallelize(self, device_map=None):
965
+ self.device_map = (
966
+ get_device_map(len(self.transformer.h), range(torch.cuda.device_count()))
967
+ if device_map is None
968
+ else device_map
969
+ )
970
+ assert_device_map(self.device_map, len(self.transformer.h))
971
+ self.transformer.parallelize(self.device_map)
972
+ self.lm_head = self.lm_head.to(self.transformer.first_device)
973
+ self.model_parallel = True
974
+
975
+ @add_start_docstrings(DEPARALLELIZE_DOCSTRING)
976
+ def deparallelize(self):
977
+ self.transformer.deparallelize()
978
+ self.transformer = self.transformer.to("cpu")
979
+ self.lm_head = self.lm_head.to("cpu")
980
+ self.model_parallel = False
981
+ torch.cuda.empty_cache()
982
+
983
+ def get_output_embeddings(self):
984
+ return self.lm_head
985
+
986
+ def set_output_embeddings(self, new_embeddings):
987
+ self.lm_head = new_embeddings
988
+
989
+ def prepare_inputs_for_generation(self, input_ids, past=None, **kwargs):
990
+ token_type_ids = kwargs.get("token_type_ids", None)
991
+ # only last token for inputs_ids if past is defined in kwargs
992
+ if past:
993
+ input_ids = input_ids[:, -1].unsqueeze(-1)
994
+ if token_type_ids is not None:
995
+ token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
996
+
997
+ attention_mask = kwargs.get("attention_mask", None)
998
+ position_ids = kwargs.get("position_ids", None)
999
+
1000
+ if attention_mask is not None and position_ids is None:
1001
+ # create position_ids on the fly for batch generation
1002
+ position_ids = attention_mask.long().cumsum(-1) - 1
1003
+ position_ids.masked_fill_(attention_mask == 0, 1)
1004
+ if past:
1005
+ position_ids = position_ids[:, -1].unsqueeze(-1)
1006
+ else:
1007
+ position_ids = None
1008
+ return {
1009
+ "input_ids": input_ids,
1010
+ "past_key_values": past,
1011
+ "use_cache": kwargs.get("use_cache"),
1012
+ "position_ids": position_ids,
1013
+ "attention_mask": attention_mask,
1014
+ "token_type_ids": token_type_ids,
1015
+ }
1016
+
1017
+ @add_start_docstrings_to_model_forward(GPT2_INPUTS_DOCSTRING)
1018
+ @add_code_sample_docstrings(
1019
+ processor_class=_TOKENIZER_FOR_DOC,
1020
+ checkpoint=_CHECKPOINT_FOR_DOC,
1021
+ output_type=CausalLMOutputWithCrossAttentions,
1022
+ config_class=_CONFIG_FOR_DOC,
1023
+ )
1024
+ def forward(
1025
+ self,
1026
+ input_ids: Optional[torch.LongTensor] = None,
1027
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1028
+ attention_mask: Optional[torch.FloatTensor] = None,
1029
+ token_type_ids: Optional[torch.LongTensor] = None,
1030
+ position_ids: Optional[torch.LongTensor] = None,
1031
+ head_mask: Optional[torch.FloatTensor] = None,
1032
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1033
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1034
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
1035
+ labels: Optional[torch.LongTensor] = None,
1036
+ use_cache: Optional[bool] = None,
1037
+ output_attentions: Optional[bool] = None,
1038
+ output_hidden_states: Optional[bool] = None,
1039
+ return_dict: Optional[bool] = None,
1040
+ ) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
1041
+ r"""
1042
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1043
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
1044
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
1045
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
1046
+ """
1047
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1048
+
1049
+ transformer_outputs = self.transformer(
1050
+ input_ids,
1051
+ past_key_values=past_key_values,
1052
+ attention_mask=attention_mask,
1053
+ token_type_ids=token_type_ids,
1054
+ position_ids=position_ids,
1055
+ head_mask=head_mask,
1056
+ inputs_embeds=inputs_embeds,
1057
+ encoder_hidden_states=encoder_hidden_states,
1058
+ encoder_attention_mask=encoder_attention_mask,
1059
+ use_cache=use_cache,
1060
+ output_attentions=output_attentions,
1061
+ output_hidden_states=output_hidden_states,
1062
+ return_dict=return_dict,
1063
+ )
1064
+ hidden_states = transformer_outputs[0]
1065
+
1066
+ # Set device for model parallelism
1067
+ if self.model_parallel:
1068
+ torch.cuda.set_device(self.transformer.first_device)
1069
+ hidden_states = hidden_states.to(self.lm_head.weight.device)
1070
+
1071
+ lm_logits = self.lm_head(hidden_states)
1072
+
1073
+ loss = None
1074
+ if labels is not None:
1075
+ # Shift so that tokens < n predict n
1076
+ shift_logits = lm_logits[..., :-1, :].contiguous()
1077
+ shift_labels = labels[..., 1:].contiguous()
1078
+ # Flatten the tokens
1079
+ loss_fct = CrossEntropyLoss()
1080
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
1081
+
1082
+ if not return_dict:
1083
+ output = (lm_logits,) + transformer_outputs[1:]
1084
+ return ((loss,) + output) if loss is not None else output
1085
+
1086
+ return CausalLMOutputWithCrossAttentions(
1087
+ loss=loss,
1088
+ logits=lm_logits,
1089
+ past_key_values=transformer_outputs.past_key_values,
1090
+ hidden_states=transformer_outputs.hidden_states,
1091
+ attentions=transformer_outputs.attentions,
1092
+ cross_attentions=transformer_outputs.cross_attentions,
1093
+ )
1094
+
1095
+ @staticmethod
1096
+ def _reorder_cache(past: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor) -> Tuple[Tuple[torch.Tensor]]:
1097
+ """
1098
+ This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
1099
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
1100
+ beam_idx at every generation step.
1101
+ """
1102
+ return tuple(
1103
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past)
1104
+ for layer_past in past
1105
+ )
1106
+
1107
+
1108
+ @add_start_docstrings(
1109
+ """
1110
+ The GPT2 Model transformer with a language modeling and a multiple-choice classification head on top e.g. for
1111
+ RocStories/SWAG tasks. The two heads are two linear layers. The language modeling head has its weights tied to the
1112
+ input embeddings, the classification head takes as input the input of a specified classification token index in the
1113
+ input sequence).
1114
+ """,
1115
+ GPT2_START_DOCSTRING,
1116
+ )
1117
+ class GPT2DoubleHeadsModel(GPT2PreTrainedModel):
1118
+ _keys_to_ignore_on_load_missing = [r"attn.masked_bias", r"attn.bias", r"lm_head.weight"]
1119
+
1120
+ def __init__(self, config):
1121
+ super().__init__(config)
1122
+ config.num_labels = 1
1123
+ self.transformer = GPT2Model(config)
1124
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
1125
+ self.multiple_choice_head = SequenceSummary(config)
1126
+
1127
+ # Model parallel
1128
+ self.model_parallel = False
1129
+ self.device_map = None
1130
+
1131
+ # Initialize weights and apply final processing
1132
+ self.post_init()
1133
+
1134
+ @add_start_docstrings(PARALLELIZE_DOCSTRING)
1135
+ def parallelize(self, device_map=None):
1136
+ self.device_map = (
1137
+ get_device_map(len(self.transformer.h), range(torch.cuda.device_count()))
1138
+ if device_map is None
1139
+ else device_map
1140
+ )
1141
+ assert_device_map(self.device_map, len(self.transformer.h))
1142
+ self.transformer.parallelize(self.device_map)
1143
+ self.lm_head = self.lm_head.to(self.transformer.first_device)
1144
+ self.multiple_choice_head = self.multiple_choice_head.to(self.transformer.first_device)
1145
+ self.model_parallel = True
1146
+
1147
+ @add_start_docstrings(DEPARALLELIZE_DOCSTRING)
1148
+ def deparallelize(self):
1149
+ self.transformer.deparallelize()
1150
+ self.transformer = self.transformer.to("cpu")
1151
+ self.lm_head = self.lm_head.to("cpu")
1152
+ self.multiple_choice_head = self.multiple_choice_head.to("cpu")
1153
+ self.model_parallel = False
1154
+ torch.cuda.empty_cache()
1155
+
1156
+ def get_output_embeddings(self):
1157
+ return self.lm_head
1158
+
1159
+ def set_output_embeddings(self, new_embeddings):
1160
+ self.lm_head = new_embeddings
1161
+
1162
+ def prepare_inputs_for_generation(self, input_ids, past=None, **kwargs):
1163
+ token_type_ids = kwargs.get("token_type_ids", None)
1164
+ # only last token for inputs_ids if past is defined in kwargs
1165
+ if past:
1166
+ input_ids = input_ids[:, -1].unsqueeze(-1)
1167
+ if token_type_ids is not None:
1168
+ token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
1169
+
1170
+ attention_mask = kwargs.get("attention_mask", None)
1171
+ position_ids = kwargs.get("position_ids", None)
1172
+
1173
+ if attention_mask is not None and position_ids is None:
1174
+ # create position_ids on the fly for batch generation
1175
+ position_ids = attention_mask.long().cumsum(-1) - 1
1176
+ position_ids.masked_fill_(attention_mask == 0, 1)
1177
+ if past:
1178
+ position_ids = position_ids[:, -1].unsqueeze(-1)
1179
+ else:
1180
+ position_ids = None
1181
+
1182
+ return {
1183
+ "input_ids": input_ids,
1184
+ "past_key_values": past,
1185
+ "use_cache": kwargs.get("use_cache"),
1186
+ "position_ids": position_ids,
1187
+ "attention_mask": attention_mask,
1188
+ "token_type_ids": token_type_ids,
1189
+ }
1190
+
1191
+ @add_start_docstrings_to_model_forward(GPT2_INPUTS_DOCSTRING)
1192
+ @replace_return_docstrings(output_type=GPT2DoubleHeadsModelOutput, config_class=_CONFIG_FOR_DOC)
1193
+ def forward(
1194
+ self,
1195
+ input_ids: Optional[torch.LongTensor] = None,
1196
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1197
+ attention_mask: Optional[torch.FloatTensor] = None,
1198
+ token_type_ids: Optional[torch.LongTensor] = None,
1199
+ position_ids: Optional[torch.LongTensor] = None,
1200
+ head_mask: Optional[torch.FloatTensor] = None,
1201
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1202
+ mc_token_ids: Optional[torch.LongTensor] = None,
1203
+ labels: Optional[torch.LongTensor] = None,
1204
+ mc_labels: Optional[torch.LongTensor] = None,
1205
+ use_cache: Optional[bool] = None,
1206
+ output_attentions: Optional[bool] = None,
1207
+ output_hidden_states: Optional[bool] = None,
1208
+ return_dict: Optional[bool] = None,
1209
+ **kwargs,
1210
+ ) -> Union[Tuple, GPT2DoubleHeadsModelOutput]:
1211
+ r"""
1212
+ mc_token_ids (`torch.LongTensor` of shape `(batch_size, num_choices)`, *optional*, default to index of the last token of the input):
1213
+ Index of the classification token in each input sequence. Selected in the range `[0, input_ids.size(-1) -
1214
+ 1]`.
1215
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1216
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
1217
+ `labels = input_ids`. Indices are selected in `[-100, 0, ..., config.vocab_size - 1]`. All labels set to
1218
+ `-100` are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size - 1]`
1219
+ mc_labels (`torch.LongTensor` of shape `(batch_size)`, *optional*):
1220
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]`
1221
+ where *num_choices* is the size of the second dimension of the input tensors. (see *input_ids* above)
1222
+
1223
+ Return:
1224
+
1225
+ Example:
1226
+
1227
+ ```python
1228
+ >>> import torch
1229
+ >>> from transformers import GPT2Tokenizer, GPT2DoubleHeadsModel
1230
+
1231
+ >>> tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
1232
+ >>> model = GPT2DoubleHeadsModel.from_pretrained("gpt2")
1233
+
1234
+ >>> # Add a [CLS] to the vocabulary (we should train it also!)
1235
+ >>> num_added_tokens = tokenizer.add_special_tokens({"cls_token": "[CLS]"})
1236
+ >>> # Update the model embeddings with the new vocabulary size
1237
+ >>> embedding_layer = model.resize_token_embeddings(len(tokenizer))
1238
+
1239
+ >>> choices = ["Hello, my dog is cute [CLS]", "Hello, my cat is cute [CLS]"]
1240
+ >>> encoded_choices = [tokenizer.encode(s) for s in choices]
1241
+ >>> cls_token_location = [tokens.index(tokenizer.cls_token_id) for tokens in encoded_choices]
1242
+
1243
+ >>> input_ids = torch.tensor(encoded_choices).unsqueeze(0) # Batch size: 1, number of choices: 2
1244
+ >>> mc_token_ids = torch.tensor([cls_token_location]) # Batch size: 1
1245
+
1246
+ >>> outputs = model(input_ids, mc_token_ids=mc_token_ids)
1247
+ >>> lm_logits = outputs.logits
1248
+ >>> mc_logits = outputs.mc_logits
1249
+ ```"""
1250
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1251
+
1252
+ transformer_outputs = self.transformer(
1253
+ input_ids,
1254
+ past_key_values=past_key_values,
1255
+ attention_mask=attention_mask,
1256
+ token_type_ids=token_type_ids,
1257
+ position_ids=position_ids,
1258
+ head_mask=head_mask,
1259
+ inputs_embeds=inputs_embeds,
1260
+ use_cache=use_cache,
1261
+ output_attentions=output_attentions,
1262
+ output_hidden_states=output_hidden_states,
1263
+ return_dict=return_dict,
1264
+ )
1265
+
1266
+ hidden_states = transformer_outputs[0]
1267
+
1268
+ # Set device for model parallelism
1269
+ if self.model_parallel:
1270
+ torch.cuda.set_device(self.transformer.first_device)
1271
+ hidden_states = hidden_states.to(self.lm_head.weight.device)
1272
+
1273
+ lm_logits = self.lm_head(hidden_states)
1274
+ mc_logits = self.multiple_choice_head(hidden_states, mc_token_ids).squeeze(-1)
1275
+
1276
+ mc_loss = None
1277
+ if mc_labels is not None:
1278
+ loss_fct = CrossEntropyLoss()
1279
+ mc_loss = loss_fct(mc_logits.view(-1, mc_logits.size(-1)), mc_labels.view(-1))
1280
+ lm_loss = None
1281
+ if labels is not None:
1282
+ shift_logits = lm_logits[..., :-1, :].contiguous()
1283
+ shift_labels = labels[..., 1:].contiguous()
1284
+ loss_fct = CrossEntropyLoss()
1285
+ lm_loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
1286
+
1287
+ if not return_dict:
1288
+ output = (lm_logits, mc_logits) + transformer_outputs[1:]
1289
+ if mc_loss is not None:
1290
+ output = (mc_loss,) + output
1291
+ return ((lm_loss,) + output) if lm_loss is not None else output
1292
+
1293
+ return GPT2DoubleHeadsModelOutput(
1294
+ loss=lm_loss,
1295
+ mc_loss=mc_loss,
1296
+ logits=lm_logits,
1297
+ mc_logits=mc_logits,
1298
+ past_key_values=transformer_outputs.past_key_values,
1299
+ hidden_states=transformer_outputs.hidden_states,
1300
+ attentions=transformer_outputs.attentions,
1301
+ )
1302
+
1303
+ @staticmethod
1304
+ def _reorder_cache(past: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor) -> Tuple[Tuple[torch.Tensor]]:
1305
+ """
1306
+ This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
1307
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
1308
+ beam_idx at every generation step.
1309
+ """
1310
+ return tuple(
1311
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past)
1312
+ for layer_past in past
1313
+ )
1314
+
1315
+
1316
+ @add_start_docstrings(
1317
+ """
1318
+ The GPT2 Model transformer with a sequence classification head on top (linear layer).
1319
+
1320
+ [`GPT2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1321
+ (e.g. GPT-1) do.
1322
+
1323
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1324
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1325
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1326
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1327
+ each row of the batch).
1328
+ """,
1329
+ GPT2_START_DOCSTRING,
1330
+ )
1331
+ class GPT2ForSequenceClassification(GPT2PreTrainedModel):
1332
+ _keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.masked_bias", r"lm_head.weight"]
1333
+
1334
+ def __init__(self, config):
1335
+ super().__init__(config)
1336
+ self.num_labels = config.num_labels
1337
+ self.transformer = GPT2Model(config)
1338
+ self.score = nn.Linear(config.n_embd, self.num_labels, bias=False)
1339
+
1340
+ # Model parallel
1341
+ self.model_parallel = False
1342
+ self.device_map = None
1343
+
1344
+ # Initialize weights and apply final processing
1345
+ self.post_init()
1346
+
1347
+ @add_start_docstrings_to_model_forward(GPT2_INPUTS_DOCSTRING)
1348
+ @add_code_sample_docstrings(
1349
+ processor_class=_TOKENIZER_FOR_DOC,
1350
+ checkpoint="microsoft/DialogRPT-updown",
1351
+ output_type=SequenceClassifierOutputWithPast,
1352
+ config_class=_CONFIG_FOR_DOC,
1353
+ expected_output="'LABEL_0'",
1354
+ expected_loss=5.28,
1355
+ )
1356
+ def forward(
1357
+ self,
1358
+ input_ids: Optional[torch.LongTensor] = None,
1359
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1360
+ attention_mask: Optional[torch.FloatTensor] = None,
1361
+ token_type_ids: Optional[torch.LongTensor] = None,
1362
+ position_ids: Optional[torch.LongTensor] = None,
1363
+ head_mask: Optional[torch.FloatTensor] = None,
1364
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1365
+ labels: Optional[torch.LongTensor] = None,
1366
+ use_cache: Optional[bool] = None,
1367
+ output_attentions: Optional[bool] = None,
1368
+ output_hidden_states: Optional[bool] = None,
1369
+ return_dict: Optional[bool] = None,
1370
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1371
+ r"""
1372
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1373
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1374
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1375
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1376
+ """
1377
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1378
+
1379
+ transformer_outputs = self.transformer(
1380
+ input_ids,
1381
+ past_key_values=past_key_values,
1382
+ attention_mask=attention_mask,
1383
+ token_type_ids=token_type_ids,
1384
+ position_ids=position_ids,
1385
+ head_mask=head_mask,
1386
+ inputs_embeds=inputs_embeds,
1387
+ use_cache=use_cache,
1388
+ output_attentions=output_attentions,
1389
+ output_hidden_states=output_hidden_states,
1390
+ return_dict=return_dict,
1391
+ )
1392
+ hidden_states = transformer_outputs[0]
1393
+ logits = self.score(hidden_states)
1394
+
1395
+ if input_ids is not None:
1396
+ batch_size, sequence_length = input_ids.shape[:2]
1397
+ else:
1398
+ batch_size, sequence_length = inputs_embeds.shape[:2]
1399
+
1400
+ assert (
1401
+ self.config.pad_token_id is not None or batch_size == 1
1402
+ ), "Cannot handle batch sizes > 1 if no padding token is defined."
1403
+ if self.config.pad_token_id is None:
1404
+ sequence_lengths = -1
1405
+ else:
1406
+ if input_ids is not None:
1407
+ sequence_lengths = torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1
1408
+ else:
1409
+ sequence_lengths = -1
1410
+ logger.warning(
1411
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
1412
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
1413
+ )
1414
+
1415
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1416
+
1417
+ loss = None
1418
+ if labels is not None:
1419
+ if self.config.problem_type is None:
1420
+ if self.num_labels == 1:
1421
+ self.config.problem_type = "regression"
1422
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1423
+ self.config.problem_type = "single_label_classification"
1424
+ else:
1425
+ self.config.problem_type = "multi_label_classification"
1426
+
1427
+ if self.config.problem_type == "regression":
1428
+ loss_fct = MSELoss()
1429
+ if self.num_labels == 1:
1430
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1431
+ else:
1432
+ loss = loss_fct(pooled_logits, labels)
1433
+ elif self.config.problem_type == "single_label_classification":
1434
+ loss_fct = CrossEntropyLoss()
1435
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1436
+ elif self.config.problem_type == "multi_label_classification":
1437
+ loss_fct = BCEWithLogitsLoss()
1438
+ loss = loss_fct(pooled_logits, labels)
1439
+ if not return_dict:
1440
+ output = (pooled_logits,) + transformer_outputs[1:]
1441
+ return ((loss,) + output) if loss is not None else output
1442
+
1443
+ return SequenceClassifierOutputWithPast(
1444
+ loss=loss,
1445
+ logits=pooled_logits,
1446
+ past_key_values=transformer_outputs.past_key_values,
1447
+ hidden_states=transformer_outputs.hidden_states,
1448
+ attentions=transformer_outputs.attentions,
1449
+ )
1450
+
1451
+
1452
+ @add_start_docstrings(
1453
+ """
1454
+ GPT2 Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1455
+ Named-Entity-Recognition (NER) tasks.
1456
+ """,
1457
+ GPT2_START_DOCSTRING,
1458
+ )
1459
+ class GPT2ForTokenClassification(GPT2PreTrainedModel):
1460
+ def __init__(self, config):
1461
+ super().__init__(config)
1462
+ self.num_labels = config.num_labels
1463
+
1464
+ self.transformer = GPT2Model(config)
1465
+ if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
1466
+ classifier_dropout = config.classifier_dropout
1467
+ elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
1468
+ classifier_dropout = config.hidden_dropout
1469
+ else:
1470
+ classifier_dropout = 0.1
1471
+ self.dropout = nn.Dropout(classifier_dropout)
1472
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1473
+
1474
+ # Model parallel
1475
+ self.model_parallel = False
1476
+ self.device_map = None
1477
+
1478
+ # Initialize weights and apply final processing
1479
+ self.post_init()
1480
+
1481
+ @add_start_docstrings_to_model_forward(GPT2_INPUTS_DOCSTRING)
1482
+ # fmt: off
1483
+ @add_code_sample_docstrings(
1484
+ processor_class=_TOKENIZER_FOR_DOC,
1485
+ checkpoint="brad1141/gpt2-finetuned-comp2",
1486
+ output_type=TokenClassifierOutput,
1487
+ config_class=_CONFIG_FOR_DOC,
1488
+ expected_loss=0.25,
1489
+ expected_output=["Lead", "Lead", "Lead", "Position", "Lead", "Lead", "Lead", "Lead", "Lead", "Lead", "Lead", "Lead"],
1490
+ )
1491
+ # fmt: on
1492
+ def forward(
1493
+ self,
1494
+ input_ids: Optional[torch.LongTensor] = None,
1495
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1496
+ attention_mask: Optional[torch.FloatTensor] = None,
1497
+ token_type_ids: Optional[torch.LongTensor] = None,
1498
+ position_ids: Optional[torch.LongTensor] = None,
1499
+ head_mask: Optional[torch.FloatTensor] = None,
1500
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1501
+ labels: Optional[torch.LongTensor] = None,
1502
+ use_cache: Optional[bool] = None,
1503
+ output_attentions: Optional[bool] = None,
1504
+ output_hidden_states: Optional[bool] = None,
1505
+ return_dict: Optional[bool] = None,
1506
+ ) -> Union[Tuple, TokenClassifierOutput]:
1507
+ r"""
1508
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1509
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1510
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1511
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1512
+ """
1513
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1514
+
1515
+ transformer_outputs = self.transformer(
1516
+ input_ids,
1517
+ past_key_values=past_key_values,
1518
+ attention_mask=attention_mask,
1519
+ token_type_ids=token_type_ids,
1520
+ position_ids=position_ids,
1521
+ head_mask=head_mask,
1522
+ inputs_embeds=inputs_embeds,
1523
+ use_cache=use_cache,
1524
+ output_attentions=output_attentions,
1525
+ output_hidden_states=output_hidden_states,
1526
+ return_dict=return_dict,
1527
+ )
1528
+
1529
+ hidden_states = transformer_outputs[0]
1530
+ hidden_states = self.dropout(hidden_states)
1531
+ logits = self.classifier(hidden_states)
1532
+
1533
+ loss = None
1534
+ if labels is not None:
1535
+ loss_fct = CrossEntropyLoss()
1536
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1537
+
1538
+ if not return_dict:
1539
+ output = (logits,) + transformer_outputs[2:]
1540
+ return ((loss,) + output) if loss is not None else output
1541
+
1542
+ return TokenClassifierOutput(
1543
+ loss=loss,
1544
+ logits=logits,
1545
+ hidden_states=transformer_outputs.hidden_states,
1546
+ attentions=transformer_outputs.attentions,
1547
+ )
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:677f711dfade47fe3bb712a5af6dc3b8bfeb1e22967a4f78777df319d2e15909
3
+ size 1781199