crumb commited on
Commit
33f1c93
·
1 Parent(s): 365cbb0

Upload model

Browse files
config.json ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "outputs/checkpoint-8000",
3
+ "activation_function": "gelu_new",
4
+ "architectures": [
5
+ "GPT2ALMHeadModel"
6
+ ],
7
+ "attn_bias": false,
8
+ "attn_pdrop": 0.0,
9
+ "auto_map": {
10
+ "AutoConfig": "configuration_gpt2a.GPT2AConfig",
11
+ "AutoModelForCausalLM": "modeling_gpt2a.GPT2ALMHeadModel"
12
+ },
13
+ "bos_token_id": 50256,
14
+ "embd_pdrop": 0.0,
15
+ "eos_token_id": 50256,
16
+ "initializer_range": 0.02,
17
+ "layer_norm_epsilon": 1e-06,
18
+ "mlp_bias": false,
19
+ "model_type": "gpt2a",
20
+ "n_ctx": 1536,
21
+ "n_embd": 1536,
22
+ "n_head": 16,
23
+ "n_inner": 12288,
24
+ "n_layer": 6,
25
+ "n_positions": 4096,
26
+ "reorder_and_upcast_attn": false,
27
+ "resid_pdrop": 0.0,
28
+ "scale_attn_by_inverse_layer_idx": false,
29
+ "scale_attn_weights": true,
30
+ "summary_activation": null,
31
+ "summary_first_dropout": 0.1,
32
+ "summary_proj_to_labels": true,
33
+ "summary_type": "cls_index",
34
+ "summary_use_proj": true,
35
+ "torch_dtype": "float32",
36
+ "transformers_version": "4.34.0.dev0",
37
+ "use_cache": false,
38
+ "vocab_size": 50277
39
+ }
configuration_gpt2a.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """ OpenAI GPT-2 configuration"""
17
+ from collections import OrderedDict
18
+ from typing import Any, List, Mapping, Optional
19
+
20
+ from transformers import PreTrainedTokenizer, TensorType, is_torch_available
21
+ from transformers.configuration_utils import PretrainedConfig
22
+ from transformers.onnx import OnnxConfigWithPast, PatchingSpec
23
+ from transformers.utils import logging
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+ GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP = {
29
+ "gpt2": "https://huggingface.co/gpt2/resolve/main/config.json",
30
+ "gpt2-medium": "https://huggingface.co/gpt2-medium/resolve/main/config.json",
31
+ "gpt2-large": "https://huggingface.co/gpt2-large/resolve/main/config.json",
32
+ "gpt2-xl": "https://huggingface.co/gpt2-xl/resolve/main/config.json",
33
+ "distilgpt2": "https://huggingface.co/distilgpt2/resolve/main/config.json",
34
+ }
35
+
36
+
37
+ class GPT2AConfig(PretrainedConfig):
38
+ """
39
+ This is the configuration class to store the configuration of a [`GPT2Model`] or a [`TFGPT2Model`]. It is used to
40
+ instantiate a GPT-2 model according to the specified arguments, defining the model architecture. Instantiating a
41
+ configuration with the defaults will yield a similar configuration to that of the GPT-2
42
+ [gpt2](https://huggingface.co/gpt2) architecture.
43
+
44
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
45
+ documentation from [`PretrainedConfig`] for more information.
46
+
47
+
48
+ Args:
49
+ vocab_size (`int`, *optional*, defaults to 50257):
50
+ Vocabulary size of the GPT-2 model. Defines the number of different tokens that can be represented by the
51
+ `inputs_ids` passed when calling [`GPT2Model`] or [`TFGPT2Model`].
52
+ n_positions (`int`, *optional*, defaults to 1024):
53
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
54
+ just in case (e.g., 512 or 1024 or 2048).
55
+ n_embd (`int`, *optional*, defaults to 768):
56
+ Dimensionality of the embeddings and hidden states.
57
+ n_layer (`int`, *optional*, defaults to 12):
58
+ Number of hidden layers in the Transformer encoder.
59
+ n_head (`int`, *optional*, defaults to 12):
60
+ Number of attention heads for each attention layer in the Transformer encoder.
61
+ n_inner (`int`, *optional*, defaults to None):
62
+ Dimensionality of the inner feed-forward layers. `None` will set it to 4 times n_embd
63
+ activation_function (`str`, *optional*, defaults to `"gelu_new"`):
64
+ Activation function, to be selected in the list `["relu", "silu", "gelu", "tanh", "gelu_new"]`.
65
+ resid_pdrop (`float`, *optional*, defaults to 0.1):
66
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
67
+ embd_pdrop (`float`, *optional*, defaults to 0.1):
68
+ The dropout ratio for the embeddings.
69
+ attn_pdrop (`float`, *optional*, defaults to 0.1):
70
+ The dropout ratio for the attention.
71
+ layer_norm_epsilon (`float`, *optional*, defaults to 1e-5):
72
+ The epsilon to use in the layer normalization layers.
73
+ initializer_range (`float`, *optional*, defaults to 0.02):
74
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
75
+ summary_type (`string`, *optional*, defaults to `"cls_index"`):
76
+ Argument used when doing sequence summary, used in the models [`GPT2DoubleHeadsModel`] and
77
+ [`TFGPT2DoubleHeadsModel`].
78
+
79
+ Has to be one of the following options:
80
+
81
+ - `"last"`: Take the last token hidden state (like XLNet).
82
+ - `"first"`: Take the first token hidden state (like BERT).
83
+ - `"mean"`: Take the mean of all tokens hidden states.
84
+ - `"cls_index"`: Supply a Tensor of classification token position (like GPT/GPT-2).
85
+ - `"attn"`: Not implemented now, use multi-head attention.
86
+ summary_use_proj (`bool`, *optional*, defaults to `True`):
87
+ Argument used when doing sequence summary, used in the models [`GPT2DoubleHeadsModel`] and
88
+ [`TFGPT2DoubleHeadsModel`].
89
+
90
+ Whether or not to add a projection after the vector extraction.
91
+ summary_activation (`str`, *optional*):
92
+ Argument used when doing sequence summary. Used in for the multiple choice head in
93
+ [`GPT2DoubleHeadsModel`].
94
+
95
+ Pass `"tanh"` for a tanh activation to the output, any other value will result in no activation.
96
+ summary_proj_to_labels (`bool`, *optional*, defaults to `True`):
97
+ Argument used when doing sequence summary, used in the models [`GPT2DoubleHeadsModel`] and
98
+ [`TFGPT2DoubleHeadsModel`].
99
+
100
+ Whether the projection outputs should have `config.num_labels` or `config.hidden_size` classes.
101
+ summary_first_dropout (`float`, *optional*, defaults to 0.1):
102
+ Argument used when doing sequence summary, used in the models [`GPT2DoubleHeadsModel`] and
103
+ [`TFGPT2DoubleHeadsModel`].
104
+
105
+ The dropout ratio to be used after the projection and activation.
106
+ scale_attn_weights (`bool`, *optional*, defaults to `True`):
107
+ Scale attention weights by dividing by sqrt(hidden_size)..
108
+ use_cache (`bool`, *optional*, defaults to `True`):
109
+ Whether or not the model should return the last key/values attentions (not used by all models).
110
+ scale_attn_by_inverse_layer_idx (`bool`, *optional*, defaults to `False`):
111
+ Whether to additionally scale attention weights by `1 / layer_idx + 1`.
112
+ reorder_and_upcast_attn (`bool`, *optional*, defaults to `False`):
113
+ Whether to scale keys (K) prior to computing attention (dot-product) and upcast attention
114
+ dot-product/softmax to float() when training with mixed precision.
115
+
116
+ Example:
117
+
118
+ ```python
119
+ >>> from transformers import GPT2Config, GPT2Model
120
+
121
+ >>> # Initializing a GPT2 configuration
122
+ >>> configuration = GPT2Config()
123
+
124
+ >>> # Initializing a model (with random weights) from the configuration
125
+ >>> model = GPT2Model(configuration)
126
+
127
+ >>> # Accessing the model configuration
128
+ >>> configuration = model.config
129
+ ```"""
130
+
131
+ model_type = "gpt2a"
132
+ keys_to_ignore_at_inference = ["past_key_values"]
133
+ attribute_map = {
134
+ "hidden_size": "n_embd",
135
+ "max_position_embeddings": "n_positions",
136
+ "num_attention_heads": "n_head",
137
+ "num_hidden_layers": "n_layer",
138
+ }
139
+
140
+ def __init__(
141
+ self,
142
+ vocab_size=50257,
143
+ n_positions=1024,
144
+ n_embd=768,
145
+ n_layer=12,
146
+ n_head=12,
147
+ n_inner=None,
148
+ activation_function="gelu_new",
149
+ resid_pdrop=0.1,
150
+ embd_pdrop=0.1,
151
+ attn_pdrop=0.1,
152
+ layer_norm_epsilon=1e-6,
153
+ initializer_range=0.02,
154
+ summary_type="cls_index",
155
+ summary_use_proj=True,
156
+ summary_activation=None,
157
+ summary_proj_to_labels=True,
158
+ summary_first_dropout=0.1,
159
+ scale_attn_weights=True,
160
+ use_cache=True,
161
+ bos_token_id=50256,
162
+ eos_token_id=50256,
163
+ scale_attn_by_inverse_layer_idx=False,
164
+ reorder_and_upcast_attn=False,
165
+
166
+ mlp_bias = True,
167
+ attn_bias = True,
168
+ **kwargs,
169
+ ):
170
+ self.mlp_bias = mlp_bias
171
+ self.attn_bias = attn_bias
172
+
173
+ self.vocab_size = vocab_size
174
+ self.n_positions = n_positions
175
+ self.n_embd = n_embd
176
+ self.n_layer = n_layer
177
+ self.n_head = n_head
178
+ self.n_inner = n_inner
179
+ self.activation_function = activation_function
180
+ self.resid_pdrop = resid_pdrop
181
+ self.embd_pdrop = embd_pdrop
182
+ self.attn_pdrop = attn_pdrop
183
+ self.layer_norm_epsilon = layer_norm_epsilon
184
+ self.initializer_range = initializer_range
185
+ self.summary_type = summary_type
186
+ self.summary_use_proj = summary_use_proj
187
+ self.summary_activation = summary_activation
188
+ self.summary_first_dropout = summary_first_dropout
189
+ self.summary_proj_to_labels = summary_proj_to_labels
190
+ self.scale_attn_weights = scale_attn_weights
191
+ self.use_cache = use_cache
192
+ self.scale_attn_by_inverse_layer_idx = scale_attn_by_inverse_layer_idx
193
+ self.reorder_and_upcast_attn = reorder_and_upcast_attn
194
+
195
+ self.bos_token_id = bos_token_id
196
+ self.eos_token_id = eos_token_id
197
+
198
+ super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
199
+
200
+
201
+ class GPT2OnnxConfig(OnnxConfigWithPast):
202
+ def __init__(
203
+ self,
204
+ config: PretrainedConfig,
205
+ task: str = "default",
206
+ patching_specs: List[PatchingSpec] = None,
207
+ use_past: bool = False,
208
+ ):
209
+ super().__init__(config, task=task, patching_specs=patching_specs, use_past=use_past)
210
+ if not getattr(self._config, "pad_token_id", None):
211
+ # TODO: how to do that better?
212
+ self._config.pad_token_id = 0
213
+
214
+ @property
215
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
216
+ common_inputs = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}})
217
+ if self.use_past:
218
+ self.fill_with_past_key_values_(common_inputs, direction="inputs")
219
+ common_inputs["attention_mask"] = {0: "batch", 1: "past_sequence + sequence"}
220
+ else:
221
+ common_inputs["attention_mask"] = {0: "batch", 1: "sequence"}
222
+
223
+ return common_inputs
224
+
225
+ @property
226
+ def num_layers(self) -> int:
227
+ return self._config.n_layer
228
+
229
+ @property
230
+ def num_attention_heads(self) -> int:
231
+ return self._config.n_head
232
+
233
+ def generate_dummy_inputs(
234
+ self,
235
+ tokenizer: PreTrainedTokenizer,
236
+ batch_size: int = -1,
237
+ seq_length: int = -1,
238
+ is_pair: bool = False,
239
+ framework: Optional[TensorType] = None,
240
+ ) -> Mapping[str, Any]:
241
+ common_inputs = super(OnnxConfigWithPast, self).generate_dummy_inputs(
242
+ tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
243
+ )
244
+
245
+ # We need to order the input in the way they appears in the forward()
246
+ ordered_inputs = OrderedDict({"input_ids": common_inputs["input_ids"]})
247
+
248
+ # Need to add the past_keys
249
+ if self.use_past:
250
+ if not is_torch_available():
251
+ raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
252
+ else:
253
+ import torch
254
+
255
+ batch, seqlen = common_inputs["input_ids"].shape
256
+ # Not using the same length for past_key_values
257
+ past_key_values_length = seqlen + 2
258
+ past_shape = (
259
+ batch,
260
+ self.num_attention_heads,
261
+ past_key_values_length,
262
+ self._config.hidden_size // self.num_attention_heads,
263
+ )
264
+ ordered_inputs["past_key_values"] = [
265
+ (torch.zeros(past_shape), torch.zeros(past_shape)) for _ in range(self.num_layers)
266
+ ]
267
+
268
+ ordered_inputs["attention_mask"] = common_inputs["attention_mask"]
269
+ if self.use_past:
270
+ mask_dtype = ordered_inputs["attention_mask"].dtype
271
+ ordered_inputs["attention_mask"] = torch.cat(
272
+ [ordered_inputs["attention_mask"], torch.ones(batch, past_key_values_length, dtype=mask_dtype)], dim=1
273
+ )
274
+
275
+ return ordered_inputs
276
+
277
+ @property
278
+ def default_onnx_opset(self) -> int:
279
+ return 13
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 50256,
4
+ "eos_token_id": 50256,
5
+ "transformers_version": "4.34.0.dev0"
6
+ }
modeling_gpt2a.py ADDED
@@ -0,0 +1,1790 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 torch import nn
27
+ from torch.cuda.amp import autocast
28
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
29
+
30
+ from transformers.activations import ACT2FN
31
+ from transformers.modeling_outputs import (
32
+ BaseModelOutputWithPastAndCrossAttentions,
33
+ CausalLMOutputWithCrossAttentions,
34
+ QuestionAnsweringModelOutput,
35
+ SequenceClassifierOutputWithPast,
36
+ TokenClassifierOutput,
37
+ )
38
+ from transformers.modeling_utils import PreTrainedModel, SequenceSummary
39
+ from transformers.pytorch_utils import find_pruneable_heads_and_indices, prune_conv1d_layer
40
+ from transformers.utils import (
41
+ ModelOutput,
42
+ add_code_sample_docstrings,
43
+ add_start_docstrings,
44
+ add_start_docstrings_to_model_forward,
45
+ logging,
46
+ replace_return_docstrings,
47
+ )
48
+ from transformers.utils.model_parallel_utils import assert_device_map, get_device_map
49
+ from .configuration_gpt2a import GPT2AConfig
50
+
51
+ class Conv1D(nn.Module):
52
+ """
53
+ 1D-convolutional layer as defined by Radford et al. for OpenAI GPT (and also used in GPT-2).
54
+
55
+ Basically works like a linear layer but the weights are transposed.
56
+
57
+ Args:
58
+ nf (`int`): The number of output features.
59
+ nx (`int`): The number of input features.
60
+ """
61
+
62
+ def __init__(self, nf, nx, bias=True):
63
+ super().__init__()
64
+ self.nf = nf
65
+ self.weight = nn.Parameter(torch.empty(nx, nf))
66
+ self.bias = nn.Parameter(torch.zeros(nf)) if bias else None
67
+ nn.init.normal_(self.weight, std=0.02)
68
+
69
+ def forward(self, x):
70
+ size_out = x.size()[:-1] + (self.nf,)
71
+ # i think this is right?
72
+ if self.bias is not None:
73
+ x = torch.addmm(self.bias, x.view(-1, x.size(-1)), self.weight)
74
+ else:
75
+ x = torch.mm(x.view(-1, x.size(-1)),self.weight)
76
+ x = x.view(size_out)
77
+ return x
78
+
79
+ logger = logging.get_logger(__name__)
80
+
81
+ _CHECKPOINT_FOR_DOC = "gpt2"
82
+ _CONFIG_FOR_DOC = "GPT2AConfig"
83
+
84
+ GPT2_PRETRAINED_MODEL_ARCHIVE_LIST = [
85
+ "gpt2",
86
+ "gpt2-medium",
87
+ "gpt2-large",
88
+ "gpt2-xl",
89
+ "distilgpt2",
90
+ # See all GPT-2 models at https://huggingface.co/models?filter=gpt2
91
+ ]
92
+
93
+ import torch
94
+ import math
95
+
96
+ from typing import Tuple
97
+ from einops import repeat
98
+
99
+ # module partially stolen from pytorch examples:
100
+ class SinusoidalPositional(torch.nn.Module):
101
+ r"""Inject some information about the relative or absolute position of the tokens
102
+ in the sequence. The positional encodings have the same dimension as
103
+ the embeddings, so that the two can be summed. Here, we use sine and cosine
104
+ functions of different frequencies.
105
+ """
106
+
107
+ def __init__(self, embedding_dim, max_seq_length=5000):
108
+ super().__init__()
109
+
110
+ pe = torch.zeros(max_seq_length, embedding_dim)
111
+ position = torch.arange(0, max_seq_length, dtype=torch.float).unsqueeze(1)
112
+ div_term = torch.exp(torch.arange(0, embedding_dim, 2).float() * (-math.log(10000.0) / embedding_dim))
113
+ pe[:, 0::2] = torch.sin(position * div_term)
114
+ pe[:, 1::2] = torch.cos(position * div_term)
115
+
116
+ pe = pe.unsqueeze(0)
117
+ self.register_buffer("pe", pe, persistent=False)
118
+
119
+ def forward(self, input_ids):
120
+ r"""Inputs of forward function
121
+ Args:
122
+ x: the sequence fed to the positional encoder model (required).
123
+ Shape:
124
+ x: [batch size, sequence length, embed dim]
125
+ output: [batch size, sequence length, embed dim]
126
+ Examples:
127
+ >>> output = pos_encoder(x)
128
+ """
129
+ return self.pe[:, : input_ids.shape[1], :]
130
+
131
+
132
+ class ScaledSinusoidal(SinusoidalPositional):
133
+ """Sinusoidal with scaling (see FLASH paper)."""
134
+
135
+ def __init__(self, embedding_dim, max_seq_length):
136
+ super().__init__(embedding_dim, max_seq_length)
137
+ self.scale_factor = torch.nn.Parameter(torch.tensor([1.0 / embedding_dim**0.5]))
138
+
139
+ def forward(self, input_ids):
140
+ r"""Inputs of forward function
141
+ Args:
142
+ x: the sequence fed to the positional encoder model (required).
143
+ Shape:
144
+ x: [batch size, sequence length, embed dim]
145
+ output: [batch size, sequence length, embed dim]
146
+ Examples:
147
+ >>> output = pos_encoder(x)
148
+ """
149
+ return self.scale_factor * self.pe[:, : input_ids.shape[1], :]
150
+
151
+
152
+ def load_tf_weights_in_gpt2(model, config, gpt2_checkpoint_path):
153
+ """Load tf checkpoints in a pytorch model"""
154
+ try:
155
+ import re
156
+
157
+ import tensorflow as tf
158
+ except ImportError:
159
+ logger.error(
160
+ "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
161
+ "https://www.tensorflow.org/install/ for installation instructions."
162
+ )
163
+ raise
164
+ tf_path = os.path.abspath(gpt2_checkpoint_path)
165
+ logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
166
+ # Load weights from TF model
167
+ init_vars = tf.train.list_variables(tf_path)
168
+ names = []
169
+ arrays = []
170
+ for name, shape in init_vars:
171
+ logger.info(f"Loading TF weight {name} with shape {shape}")
172
+ array = tf.train.load_variable(tf_path, name)
173
+ names.append(name)
174
+ arrays.append(array.squeeze())
175
+
176
+ for name, array in zip(names, arrays):
177
+ name = name[6:] # skip "model/"
178
+ name = name.split("/")
179
+ pointer = model
180
+ for m_name in name:
181
+ if re.fullmatch(r"[A-Za-z]+\d+", m_name):
182
+ scope_names = re.split(r"(\d+)", m_name)
183
+ else:
184
+ scope_names = [m_name]
185
+ if scope_names[0] == "w" or scope_names[0] == "g":
186
+ pointer = getattr(pointer, "weight")
187
+ elif scope_names[0] == "b":
188
+ pointer = getattr(pointer, "bias")
189
+ elif scope_names[0] == "wpe" or scope_names[0] == "wte":
190
+ pointer = getattr(pointer, scope_names[0])
191
+ pointer = getattr(pointer, "weight")
192
+ else:
193
+ pointer = getattr(pointer, scope_names[0])
194
+ if len(scope_names) >= 2:
195
+ num = int(scope_names[1])
196
+ pointer = pointer[num]
197
+ try:
198
+ if pointer.shape != array.shape:
199
+ raise ValueError(f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched")
200
+ except ValueError as e:
201
+ e.args += (pointer.shape, array.shape)
202
+ raise
203
+ logger.info(f"Initialize PyTorch weight {name}")
204
+ pointer.data = torch.from_numpy(array)
205
+ return model
206
+
207
+
208
+ class GPT2AAttention(nn.Module):
209
+ def __init__(self, config, is_cross_attention=False, layer_idx=None):
210
+ super().__init__()
211
+
212
+ max_positions = config.max_position_embeddings
213
+ self.register_buffer(
214
+ "bias",
215
+ torch.tril(torch.ones((max_positions, max_positions), dtype=torch.bool)).view(
216
+ 1, 1, max_positions, max_positions
217
+ ),
218
+ persistent=False,
219
+ )
220
+ self.register_buffer("masked_bias", torch.tensor(-1e4), persistent=False)
221
+
222
+ self.embed_dim = config.hidden_size
223
+ self.num_heads = config.num_attention_heads
224
+ self.head_dim = self.embed_dim // self.num_heads
225
+ self.split_size = self.embed_dim
226
+ if self.head_dim * self.num_heads != self.embed_dim:
227
+ raise ValueError(
228
+ f"`embed_dim` must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
229
+ f" {self.num_heads})."
230
+ )
231
+
232
+ self.scale_attn_weights = config.scale_attn_weights
233
+ self.is_cross_attention = is_cross_attention
234
+
235
+ # Layer-wise attention scaling, reordering, and upcasting
236
+ self.scale_attn_by_inverse_layer_idx = config.scale_attn_by_inverse_layer_idx
237
+ self.layer_idx = layer_idx
238
+ self.reorder_and_upcast_attn = config.reorder_and_upcast_attn
239
+
240
+ if self.is_cross_attention:
241
+ self.c_attn = Conv1D(2 * self.embed_dim, self.embed_dim, bias=config.attn_bias)
242
+ self.q_attn = Conv1D(self.embed_dim, self.embed_dim, bias=config.attn_bias)
243
+ else:
244
+ self.c_attn = Conv1D(3 * self.embed_dim, self.embed_dim, bias=config.attn_bias)
245
+ self.c_proj = Conv1D(self.embed_dim, self.embed_dim, bias=config.attn_bias)
246
+
247
+ self.attn_dropout = nn.Dropout(config.attn_pdrop)
248
+ self.resid_dropout = nn.Dropout(config.resid_pdrop)
249
+
250
+ self.pruned_heads = set()
251
+
252
+ def prune_heads(self, heads):
253
+ if len(heads) == 0:
254
+ return
255
+ heads, index = find_pruneable_heads_and_indices(heads, self.num_heads, self.head_dim, self.pruned_heads)
256
+ index_attn = torch.cat([index, index + self.split_size, index + (2 * self.split_size)])
257
+
258
+ # Prune conv1d layers
259
+ self.c_attn = prune_conv1d_layer(self.c_attn, index_attn, dim=1)
260
+ self.c_proj = prune_conv1d_layer(self.c_proj, index, dim=0)
261
+
262
+ # Update hyper params
263
+ self.split_size = (self.split_size // self.num_heads) * (self.num_heads - len(heads))
264
+ self.num_heads = self.num_heads - len(heads)
265
+ self.pruned_heads = self.pruned_heads.union(heads)
266
+
267
+ def _attn(self, query, key, value, attention_mask=None, head_mask=None):
268
+ attn_weights = torch.matmul(query, key.transpose(-1, -2))
269
+
270
+ if self.scale_attn_weights:
271
+ attn_weights = attn_weights / torch.full(
272
+ [], value.size(-1) ** 0.5, dtype=attn_weights.dtype, device=attn_weights.device
273
+ )
274
+
275
+ # Layer-wise attention scaling
276
+ if self.scale_attn_by_inverse_layer_idx:
277
+ attn_weights = attn_weights / float(self.layer_idx + 1)
278
+
279
+ if not self.is_cross_attention:
280
+ # if only "normal" attention layer implements causal mask
281
+ query_length, key_length = query.size(-2), key.size(-2)
282
+ causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length]
283
+ mask_value = torch.finfo(attn_weights.dtype).min
284
+ # Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`.
285
+ # Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device`
286
+ mask_value = torch.full([], mask_value, dtype=attn_weights.dtype).to(attn_weights.device)
287
+ attn_weights = torch.where(causal_mask, attn_weights.to(attn_weights.dtype), mask_value)
288
+
289
+ if attention_mask is not None:
290
+ # Apply the attention mask
291
+ attn_weights = attn_weights + attention_mask
292
+
293
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
294
+
295
+ # Downcast (if necessary) back to V's dtype (if in mixed-precision) -- No-Op otherwise
296
+ attn_weights = attn_weights.type(value.dtype)
297
+ attn_weights = self.attn_dropout(attn_weights)
298
+
299
+ # Mask heads if we want to
300
+ if head_mask is not None:
301
+ attn_weights = attn_weights * head_mask
302
+
303
+ attn_output = torch.matmul(attn_weights, value)
304
+
305
+ return attn_output, attn_weights
306
+
307
+ def _upcast_and_reordered_attn(self, query, key, value, attention_mask=None, head_mask=None):
308
+ # Use `torch.baddbmm` (a bit more efficient w/ alpha param for scaling -- from Megatron-LM)
309
+ bsz, num_heads, q_seq_len, dk = query.size()
310
+ _, _, k_seq_len, _ = key.size()
311
+
312
+ # Preallocate attn_weights for `baddbmm`
313
+ attn_weights = torch.empty(bsz * num_heads, q_seq_len, k_seq_len, dtype=torch.float32, device=query.device)
314
+
315
+ # Compute Scale Factor
316
+ scale_factor = 1.0
317
+ if self.scale_attn_weights:
318
+ scale_factor /= float(value.size(-1)) ** 0.5
319
+
320
+ if self.scale_attn_by_inverse_layer_idx:
321
+ scale_factor /= float(self.layer_idx + 1)
322
+
323
+ # Upcast (turn off autocast) and reorder (Scale K by 1 / root(dk))
324
+ with autocast(enabled=False):
325
+ q, k = query.reshape(-1, q_seq_len, dk), key.transpose(-1, -2).reshape(-1, dk, k_seq_len)
326
+ attn_weights = torch.baddbmm(attn_weights, q.float(), k.float(), beta=0, alpha=scale_factor)
327
+ attn_weights = attn_weights.reshape(bsz, num_heads, q_seq_len, k_seq_len)
328
+
329
+ if not self.is_cross_attention:
330
+ # if only "normal" attention layer implements causal mask
331
+ query_length, key_length = query.size(-2), key.size(-2)
332
+ causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length]
333
+ mask_value = torch.finfo(attn_weights.dtype).min
334
+ # Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`.
335
+ # Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device`
336
+ mask_value = torch.tensor(mask_value, dtype=attn_weights.dtype).to(attn_weights.device)
337
+ attn_weights = torch.where(causal_mask, attn_weights, mask_value)
338
+
339
+ if attention_mask is not None:
340
+ # Apply the attention mask
341
+ attn_weights = attn_weights + attention_mask
342
+
343
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
344
+
345
+ # Downcast (if necessary) back to V's dtype (if in mixed-precision) -- No-Op if otherwise
346
+ if attn_weights.dtype != torch.float32:
347
+ raise RuntimeError("Error with upcasting, attn_weights does not have dtype torch.float32")
348
+ attn_weights = attn_weights.type(value.dtype)
349
+ attn_weights = self.attn_dropout(attn_weights)
350
+
351
+ # Mask heads if we want to
352
+ if head_mask is not None:
353
+ attn_weights = attn_weights * head_mask
354
+
355
+ attn_output = torch.matmul(attn_weights, value)
356
+
357
+ return attn_output, attn_weights
358
+
359
+ def _split_heads(self, tensor, num_heads, attn_head_size):
360
+ """
361
+ Splits hidden_size dim into attn_head_size and num_heads
362
+ """
363
+ new_shape = tensor.size()[:-1] + (num_heads, attn_head_size)
364
+ tensor = tensor.view(new_shape)
365
+ return tensor.permute(0, 2, 1, 3) # (batch, head, seq_length, head_features)
366
+
367
+ def _merge_heads(self, tensor, num_heads, attn_head_size):
368
+ """
369
+ Merges attn_head_size dim and num_attn_heads dim into hidden_size
370
+ """
371
+ tensor = tensor.permute(0, 2, 1, 3).contiguous()
372
+ new_shape = tensor.size()[:-2] + (num_heads * attn_head_size,)
373
+ return tensor.view(new_shape)
374
+
375
+ def forward(
376
+ self,
377
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
378
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
379
+ attention_mask: Optional[torch.FloatTensor] = None,
380
+ head_mask: Optional[torch.FloatTensor] = None,
381
+ encoder_hidden_states: Optional[torch.Tensor] = None,
382
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
383
+ use_cache: Optional[bool] = False,
384
+ output_attentions: Optional[bool] = False,
385
+ ) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]], ...]:
386
+ if encoder_hidden_states is not None:
387
+ if not hasattr(self, "q_attn"):
388
+ raise ValueError(
389
+ "If class is used as cross attention, the weights `q_attn` have to be defined. "
390
+ "Please make sure to instantiate class with `GPT2Attention(..., is_cross_attention=True)`."
391
+ )
392
+
393
+ query = self.q_attn(hidden_states)
394
+ key, value = self.c_attn(encoder_hidden_states).split(self.split_size, dim=2)
395
+ attention_mask = encoder_attention_mask
396
+ else:
397
+ query, key, value = self.c_attn(hidden_states).split(self.split_size, dim=2)
398
+
399
+ query = self._split_heads(query, self.num_heads, self.head_dim)
400
+ key = self._split_heads(key, self.num_heads, self.head_dim)
401
+ value = self._split_heads(value, self.num_heads, self.head_dim)
402
+
403
+ if layer_past is not None:
404
+ past_key, past_value = layer_past
405
+ key = torch.cat((past_key, key), dim=-2)
406
+ value = torch.cat((past_value, value), dim=-2)
407
+
408
+ if use_cache is True:
409
+ present = (key, value)
410
+ else:
411
+ present = None
412
+
413
+ if self.reorder_and_upcast_attn:
414
+ attn_output, attn_weights = self._upcast_and_reordered_attn(query, key, value, attention_mask, head_mask)
415
+ else:
416
+ attn_output, attn_weights = self._attn(query, key, value, attention_mask, head_mask)
417
+
418
+ attn_output = self._merge_heads(attn_output, self.num_heads, self.head_dim)
419
+ attn_output = self.c_proj(attn_output)
420
+ attn_output = self.resid_dropout(attn_output)
421
+
422
+ outputs = (attn_output, present)
423
+ if output_attentions:
424
+ outputs += (attn_weights,)
425
+
426
+ return outputs # a, present, (attentions)
427
+
428
+
429
+ class GPT2AMLP(nn.Module):
430
+ def __init__(self, intermediate_size, config):
431
+ super().__init__()
432
+ embed_dim = config.hidden_size
433
+ self.c_fc = Conv1D(intermediate_size, embed_dim, bias=config.mlp_bias)
434
+ self.c_proj = Conv1D(embed_dim, intermediate_size, bias=config.mlp_bias)
435
+ self.act = ACT2FN[config.activation_function]
436
+ self.dropout = nn.Dropout(config.resid_pdrop)
437
+
438
+ def forward(self, hidden_states: Optional[Tuple[torch.FloatTensor]]) -> torch.FloatTensor:
439
+ hidden_states = self.c_fc(hidden_states)
440
+ hidden_states = self.act(hidden_states)
441
+ hidden_states = self.c_proj(hidden_states)
442
+ hidden_states = self.dropout(hidden_states)
443
+ return hidden_states
444
+
445
+
446
+ class GPT2ABlock(nn.Module):
447
+ def __init__(self, config, mlp_src, layer_idx=None):
448
+ super().__init__()
449
+ hidden_size = config.hidden_size
450
+ inner_dim = config.n_inner if config.n_inner is not None else 4 * hidden_size
451
+
452
+ self.ln_1 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
453
+ self.attn = GPT2AAttention(config, layer_idx=layer_idx)
454
+ self.ln_2 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
455
+
456
+ if config.add_cross_attention:
457
+ self.crossattention = GPT2AAttention(config, is_cross_attention=True, layer_idx=layer_idx)
458
+ self.ln_cross_attn = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
459
+
460
+ # self.mlp = GPT2AMLP(inner_dim, config)
461
+ self.mlp = mlp_src.mlp
462
+ def forward(
463
+ self,
464
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
465
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
466
+ attention_mask: Optional[torch.FloatTensor] = None,
467
+ head_mask: Optional[torch.FloatTensor] = None,
468
+ encoder_hidden_states: Optional[torch.Tensor] = None,
469
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
470
+ use_cache: Optional[bool] = False,
471
+ output_attentions: Optional[bool] = False,
472
+ ) -> Union[Tuple[torch.Tensor], Optional[Tuple[torch.Tensor, Tuple[torch.FloatTensor, ...]]]]:
473
+ residual = hidden_states
474
+ hidden_states = self.ln_1(hidden_states)
475
+ attn_outputs = self.attn(
476
+ hidden_states,
477
+ layer_past=layer_past,
478
+ attention_mask=attention_mask,
479
+ head_mask=head_mask,
480
+ use_cache=use_cache,
481
+ output_attentions=output_attentions,
482
+ )
483
+ attn_output = attn_outputs[0] # output_attn: a, present, (attentions)
484
+ outputs = attn_outputs[1:]
485
+ # residual connection
486
+ hidden_states = attn_output + residual
487
+
488
+ if encoder_hidden_states is not None:
489
+ # add one self-attention block for cross-attention
490
+ if not hasattr(self, "crossattention"):
491
+ raise ValueError(
492
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with "
493
+ "cross-attention layers by setting `config.add_cross_attention=True`"
494
+ )
495
+ residual = hidden_states
496
+ hidden_states = self.ln_cross_attn(hidden_states)
497
+ cross_attn_outputs = self.crossattention(
498
+ hidden_states,
499
+ attention_mask=attention_mask,
500
+ head_mask=head_mask,
501
+ encoder_hidden_states=encoder_hidden_states,
502
+ encoder_attention_mask=encoder_attention_mask,
503
+ output_attentions=output_attentions,
504
+ )
505
+ attn_output = cross_attn_outputs[0]
506
+ # residual connection
507
+ hidden_states = residual + attn_output
508
+ outputs = outputs + cross_attn_outputs[2:] # add cross attentions if we output attention weights
509
+
510
+ residual = hidden_states
511
+ hidden_states = self.ln_2(hidden_states)
512
+ feed_forward_hidden_states = self.mlp(hidden_states)
513
+ # residual connection
514
+ hidden_states = residual + feed_forward_hidden_states
515
+
516
+ if use_cache:
517
+ outputs = (hidden_states,) + outputs
518
+ else:
519
+ outputs = (hidden_states,) + outputs[1:]
520
+
521
+ return outputs # hidden_states, present, (attentions, cross_attentions)
522
+
523
+
524
+ class GPT2APreTrainedModel(PreTrainedModel):
525
+ """
526
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
527
+ models.
528
+ """
529
+
530
+ config_class = GPT2AConfig
531
+ load_tf_weights = load_tf_weights_in_gpt2
532
+ base_model_prefix = "transformer"
533
+ is_parallelizable = True
534
+ supports_gradient_checkpointing = True
535
+ _no_split_modules = ["GPT2ABlock"]
536
+ _skip_keys_device_placement = "past_key_values"
537
+
538
+ def __init__(self, *inputs, **kwargs):
539
+ super().__init__(*inputs, **kwargs)
540
+
541
+ def _init_weights(self, module):
542
+ """Initialize the weights."""
543
+ if isinstance(module, (nn.Linear, Conv1D)):
544
+ # Slightly different from the TF version which uses truncated_normal for initialization
545
+ # cf https://github.com/pytorch/pytorch/pull/5617
546
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
547
+ if module.bias is not None:
548
+ module.bias.data.zero_()
549
+ elif isinstance(module, nn.Embedding):
550
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
551
+ if module.padding_idx is not None:
552
+ module.weight.data[module.padding_idx].zero_()
553
+ elif isinstance(module, nn.LayerNorm):
554
+ module.bias.data.zero_()
555
+ module.weight.data.fill_(1.0)
556
+
557
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
558
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
559
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
560
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
561
+ #
562
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
563
+ for name, p in module.named_parameters():
564
+ if name == "c_proj.weight":
565
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
566
+ p.data.normal_(mean=0.0, std=(self.config.initializer_range / math.sqrt(2 * self.config.n_layer)))
567
+
568
+ def _set_gradient_checkpointing(self, module, value=False):
569
+ if isinstance(module, GPT2AModel):
570
+ module.gradient_checkpointing = value
571
+
572
+
573
+ @dataclass
574
+ class GPT2ADoubleHeadsModelOutput(ModelOutput):
575
+ """
576
+ Base class for outputs of models predicting if two sentences are consecutive or not.
577
+
578
+ Args:
579
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
580
+ Language modeling loss.
581
+ mc_loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `mc_labels` is provided):
582
+ Multiple choice classification loss.
583
+ logits (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, config.vocab_size)`):
584
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
585
+ mc_logits (`torch.FloatTensor` of shape `(batch_size, num_choices)`):
586
+ Prediction scores of the multiple choice classification head (scores for each choice before SoftMax).
587
+ past_key_values (`Tuple[Tuple[torch.Tensor]]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
588
+ Tuple of length `config.n_layers`, containing tuples of tensors of shape `(batch_size, num_heads,
589
+ sequence_length, embed_size_per_head)`).
590
+
591
+ Contains pre-computed hidden-states (key and values in the attention blocks) that can be used (see
592
+ `past_key_values` input) to speed up sequential decoding.
593
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
594
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
595
+ shape `(batch_size, sequence_length, hidden_size)`.
596
+
597
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
598
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
599
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
600
+ sequence_length)`.
601
+
602
+ GPT2Attentions weights after the attention softmax, used to compute the weighted average in the
603
+ self-attention heads.
604
+ """
605
+
606
+ loss: Optional[torch.FloatTensor] = None
607
+ mc_loss: Optional[torch.FloatTensor] = None
608
+ logits: torch.FloatTensor = None
609
+ mc_logits: torch.FloatTensor = None
610
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
611
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
612
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
613
+
614
+
615
+ GPT2_START_DOCSTRING = r"""
616
+
617
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
618
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
619
+ etc.)
620
+
621
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
622
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
623
+ and behavior.
624
+
625
+ Parameters:
626
+ config ([`GPT2Config`]): Model configuration class with all the parameters of the model.
627
+ Initializing with a config file does not load the weights associated with the model, only the
628
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
629
+ """
630
+
631
+ GPT2_INPUTS_DOCSTRING = r"""
632
+ Args:
633
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
634
+ `input_ids_length` = `sequence_length` if `past_key_values` is `None` else
635
+ `past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input
636
+ sequence tokens in the vocabulary.
637
+
638
+ If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
639
+ `input_ids`.
640
+
641
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
642
+ [`PreTrainedTokenizer.__call__`] for details.
643
+
644
+ [What are input IDs?](../glossary#input-ids)
645
+ past_key_values (`Tuple[Tuple[torch.Tensor]]` of length `config.n_layers`):
646
+ Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
647
+ `past_key_values` output below). Can be used to speed up sequential decoding. The `input_ids` which have
648
+ their past given to this model should not be passed as `input_ids` as they have already been computed.
649
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
650
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
651
+
652
+ - 1 for tokens that are **not masked**,
653
+ - 0 for tokens that are **masked**.
654
+
655
+ If `past_key_values` is used, `attention_mask` needs to contain the masking strategy that was used for
656
+ `past_key_values`. In other words, the `attention_mask` always has to have the length:
657
+ `len(past_key_values) + len(input_ids)`
658
+
659
+ [What are attention masks?](../glossary#attention-mask)
660
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`, *optional*):
661
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
662
+ 1]`:
663
+
664
+ - 0 corresponds to a *sentence A* token,
665
+ - 1 corresponds to a *sentence B* token.
666
+
667
+ [What are token type IDs?](../glossary#token-type-ids)
668
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
669
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
670
+ config.max_position_embeddings - 1]`.
671
+
672
+ [What are position IDs?](../glossary#position-ids)
673
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
674
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
675
+
676
+ - 1 indicates the head is **not masked**,
677
+ - 0 indicates the head is **masked**.
678
+
679
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
680
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
681
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
682
+ model's internal embedding lookup matrix.
683
+
684
+ If `past_key_values` is used, optionally only the last `inputs_embeds` have to be input (see
685
+ `past_key_values`).
686
+ use_cache (`bool`, *optional*):
687
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
688
+ `past_key_values`).
689
+ output_attentions (`bool`, *optional*):
690
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
691
+ tensors for more detail.
692
+ output_hidden_states (`bool`, *optional*):
693
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
694
+ more detail.
695
+ return_dict (`bool`, *optional*):
696
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
697
+ """
698
+ PARALLELIZE_DOCSTRING = r"""
699
+ This is an experimental feature and is a subject to change at a moment's notice.
700
+
701
+ Uses a device map to distribute attention modules of the model across several devices. If no device map is given,
702
+ it will evenly distribute blocks across all devices.
703
+
704
+ Args:
705
+ device_map (`Dict[int, list]`, optional, defaults to None):
706
+ A dictionary that maps attention modules to devices. Note that the embedding module and LMHead are always
707
+ automatically mapped to the first device (for esoteric reasons). That means that the first device should
708
+ have fewer attention modules mapped to it than other devices. For reference, the gpt2 models have the
709
+ following number of attention modules:
710
+
711
+ - gpt2: 12
712
+ - gpt2-medium: 24
713
+ - gpt2-large: 36
714
+ - gpt2-xl: 48
715
+
716
+ Example:
717
+
718
+ ```python
719
+ # 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:
720
+ model = GPT2LMHeadModel.from_pretrained("gpt2-xl")
721
+ device_map = {
722
+ 0: [0, 1, 2, 3, 4, 5, 6, 7, 8],
723
+ 1: [9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21],
724
+ 2: [22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34],
725
+ 3: [35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47],
726
+ }
727
+ model.parallelize(device_map)
728
+ ```
729
+ """
730
+ DEPARALLELIZE_DOCSTRING = r"""
731
+ Moves the model to cpu from a model parallel state.
732
+
733
+ Example:
734
+
735
+ ```python
736
+ # On a 4 GPU machine with gpt2-large:
737
+ model = GPT2LMHeadModel.from_pretrained("gpt2-large")
738
+ device_map = {
739
+ 0: [0, 1, 2, 3, 4, 5, 6, 7],
740
+ 1: [8, 9, 10, 11, 12, 13, 14, 15],
741
+ 2: [16, 17, 18, 19, 20, 21, 22, 23],
742
+ 3: [24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35],
743
+ }
744
+ model.parallelize(device_map) # Splits the model across several devices
745
+ model.deparallelize() # Put the model back on cpu and cleans memory by calling torch.cuda.empty_cache()
746
+ ```
747
+ """
748
+
749
+
750
+ @add_start_docstrings(
751
+ "The bare GPT2 Model transformer outputting raw hidden-states without any specific head on top.",
752
+ GPT2_START_DOCSTRING,
753
+ )
754
+ class GPT2AModel(GPT2APreTrainedModel):
755
+ def __init__(self, config):
756
+ super().__init__(config)
757
+
758
+ self.embed_dim = config.hidden_size
759
+
760
+ self.wte = nn.Embedding(config.vocab_size, self.embed_dim)
761
+ self.wpe = ScaledSinusoidal(self.embed_dim, config.max_position_embeddings)
762
+ self.wln = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
763
+
764
+ self.drop = nn.Dropout(config.embd_pdrop)
765
+
766
+ self.mlp = GPT2AMLP(config.n_inner, config)
767
+
768
+ self.h = nn.ModuleList([GPT2ABlock(config, self, layer_idx=i) for i in range(config.num_hidden_layers)])
769
+
770
+
771
+ for idx in range(len(self.h)):
772
+ self.h[idx].mlp = self.mlp
773
+
774
+ self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
775
+
776
+ # Model parallel
777
+ self.model_parallel = False
778
+ self.device_map = None
779
+ self.gradient_checkpointing = False
780
+
781
+ # Initialize weights and apply final processing
782
+ self.post_init()
783
+
784
+ @add_start_docstrings(PARALLELIZE_DOCSTRING)
785
+ def parallelize(self, device_map=None):
786
+ # Check validity of device_map
787
+ warnings.warn(
788
+ "`GPT2Model.parallelize` is deprecated and will be removed in v5 of Transformers, you should load your"
789
+ " model with `device_map='balanced'` in the call to `from_pretrained`. You can also provide your own"
790
+ " `device_map` but it needs to be a dictionary module_name to device, so for instance {'h.0': 0, 'h.1': 1,"
791
+ " ...}",
792
+ FutureWarning,
793
+ )
794
+ self.device_map = (
795
+ get_device_map(len(self.h), range(torch.cuda.device_count())) if device_map is None else device_map
796
+ )
797
+ assert_device_map(self.device_map, len(self.h))
798
+ self.model_parallel = True
799
+ self.first_device = "cpu" if "cpu" in self.device_map.keys() else "cuda:" + str(min(self.device_map.keys()))
800
+ self.last_device = "cuda:" + str(max(self.device_map.keys()))
801
+ self.wte = self.wte.to(self.first_device)
802
+ self.wpe = self.wpe.to(self.first_device)
803
+ self.wln = self.wln.to(self.first_device)
804
+ # Load onto devices
805
+ for k, v in self.device_map.items():
806
+ for block in v:
807
+ cuda_device = "cuda:" + str(k)
808
+ self.h[block] = self.h[block].to(cuda_device)
809
+ # ln_f to last
810
+ self.ln_f = self.ln_f.to(self.last_device)
811
+
812
+ @add_start_docstrings(DEPARALLELIZE_DOCSTRING)
813
+ def deparallelize(self):
814
+ warnings.warn(
815
+ "Like `parallelize`, `deparallelize` is deprecated and will be removed in v5 of Transformers.",
816
+ FutureWarning,
817
+ )
818
+ self.model_parallel = False
819
+ self.device_map = None
820
+ self.first_device = "cpu"
821
+ self.last_device = "cpu"
822
+ self.wte = self.wte.to("cpu")
823
+ self.wpe = self.wpe.to("cpu")
824
+ self.wln = self.wln.to("cpu")
825
+ for index in range(len(self.h)):
826
+ self.h[index] = self.h[index].to("cpu")
827
+ self.ln_f = self.ln_f.to("cpu")
828
+ torch.cuda.empty_cache()
829
+
830
+ def get_input_embeddings(self):
831
+ return self.wte
832
+
833
+ def set_input_embeddings(self, new_embeddings):
834
+ self.wte = new_embeddings
835
+
836
+ def _prune_heads(self, heads_to_prune):
837
+ """
838
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer}
839
+ """
840
+ for layer, heads in heads_to_prune.items():
841
+ self.h[layer].attn.prune_heads(heads)
842
+
843
+ @add_start_docstrings_to_model_forward(GPT2_INPUTS_DOCSTRING)
844
+ @add_code_sample_docstrings(
845
+ checkpoint=_CHECKPOINT_FOR_DOC,
846
+ output_type=BaseModelOutputWithPastAndCrossAttentions,
847
+ config_class=_CONFIG_FOR_DOC,
848
+ )
849
+ def forward(
850
+ self,
851
+ input_ids: Optional[torch.LongTensor] = None,
852
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
853
+ attention_mask: Optional[torch.FloatTensor] = None,
854
+ token_type_ids: Optional[torch.LongTensor] = None,
855
+ position_ids: Optional[torch.LongTensor] = None,
856
+ head_mask: Optional[torch.FloatTensor] = None,
857
+ inputs_embeds: Optional[torch.FloatTensor] = None,
858
+ encoder_hidden_states: Optional[torch.Tensor] = None,
859
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
860
+ use_cache: Optional[bool] = None,
861
+ output_attentions: Optional[bool] = None,
862
+ output_hidden_states: Optional[bool] = None,
863
+ return_dict: Optional[bool] = None,
864
+ ) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]:
865
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
866
+ output_hidden_states = (
867
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
868
+ )
869
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
870
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
871
+
872
+ if input_ids is not None and inputs_embeds is not None:
873
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
874
+ elif input_ids is not None:
875
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
876
+ input_shape = input_ids.size()
877
+ input_ids = input_ids.view(-1, input_shape[-1])
878
+ batch_size = input_ids.shape[0]
879
+ elif inputs_embeds is not None:
880
+ input_shape = inputs_embeds.size()[:-1]
881
+ batch_size = inputs_embeds.shape[0]
882
+ else:
883
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
884
+
885
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
886
+
887
+ if token_type_ids is not None:
888
+ token_type_ids = token_type_ids.view(-1, input_shape[-1])
889
+ if position_ids is not None:
890
+ position_ids = position_ids.view(-1, input_shape[-1])
891
+
892
+ if past_key_values is None:
893
+ past_length = 0
894
+ past_key_values = tuple([None] * len(self.h))
895
+ else:
896
+ past_length = past_key_values[0][0].size(-2)
897
+ if position_ids is None:
898
+ position_ids = torch.arange(past_length, input_shape[-1] + past_length, dtype=torch.long, device=device)
899
+ position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])
900
+
901
+ # GPT2Attention mask.
902
+ if attention_mask is not None:
903
+ if batch_size <= 0:
904
+ raise ValueError("batch_size has to be defined and > 0")
905
+ attention_mask = attention_mask.view(batch_size, -1)
906
+ # We create a 3D attention mask from a 2D tensor mask.
907
+ # Sizes are [batch_size, 1, 1, to_seq_length]
908
+ # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
909
+ # this attention mask is more simple than the triangular masking of causal attention
910
+ # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
911
+ attention_mask = attention_mask[:, None, None, :]
912
+
913
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
914
+ # masked positions, this operation will create a tensor which is 0.0 for
915
+ # positions we want to attend and the dtype's smallest value for masked positions.
916
+ # Since we are adding it to the raw scores before the softmax, this is
917
+ # effectively the same as removing these entirely.
918
+ attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility
919
+ attention_mask = (1.0 - attention_mask) * torch.finfo(self.dtype).min
920
+
921
+ # If a 2D or 3D attention mask is provided for the cross-attention
922
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
923
+ if self.config.add_cross_attention and encoder_hidden_states is not None:
924
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
925
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
926
+ if encoder_attention_mask is None:
927
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
928
+ encoder_attention_mask = self.invert_attention_mask(encoder_attention_mask)
929
+ else:
930
+ encoder_attention_mask = None
931
+
932
+ # Prepare head mask if needed
933
+ # 1.0 in head_mask indicate we keep the head
934
+ # attention_probs has shape bsz x n_heads x N x N
935
+ # head_mask has shape n_layer x batch x n_heads x N x N
936
+ head_mask = self.get_head_mask(head_mask, self.config.n_layer)
937
+
938
+ if inputs_embeds is None:
939
+ inputs_embeds = self.wte(input_ids)
940
+ position_embeds = self.wpe(input_ids)
941
+ hidden_states = inputs_embeds + position_embeds
942
+ hidden_states = self.wln(hidden_states)
943
+
944
+ if token_type_ids is not None:
945
+ token_type_embeds = self.wte(token_type_ids)
946
+ hidden_states = hidden_states + token_type_embeds
947
+
948
+ hidden_states = self.drop(hidden_states)
949
+
950
+ output_shape = (-1,) + input_shape[1:] + (hidden_states.size(-1),)
951
+
952
+ if self.gradient_checkpointing and self.training:
953
+ if use_cache:
954
+ logger.warning_once(
955
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
956
+ )
957
+ use_cache = False
958
+
959
+ presents = () if use_cache else None
960
+ all_self_attentions = () if output_attentions else None
961
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
962
+ all_hidden_states = () if output_hidden_states else None
963
+ for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
964
+ # Model parallel
965
+ if self.model_parallel:
966
+ torch.cuda.set_device(hidden_states.device)
967
+ # Ensure layer_past is on same device as hidden_states (might not be correct)
968
+ if layer_past is not None:
969
+ layer_past = tuple(past_state.to(hidden_states.device) for past_state in layer_past)
970
+ # Ensure that attention_mask is always on the same device as hidden_states
971
+ if attention_mask is not None:
972
+ attention_mask = attention_mask.to(hidden_states.device)
973
+ if isinstance(head_mask, torch.Tensor):
974
+ head_mask = head_mask.to(hidden_states.device)
975
+ if output_hidden_states:
976
+ all_hidden_states = all_hidden_states + (hidden_states,)
977
+
978
+ if self.gradient_checkpointing and self.training:
979
+
980
+ def create_custom_forward(module):
981
+ def custom_forward(*inputs):
982
+ # None for past_key_value
983
+ return module(*inputs, use_cache, output_attentions)
984
+
985
+ return custom_forward
986
+
987
+ outputs = torch.utils.checkpoint.checkpoint(
988
+ create_custom_forward(block),
989
+ hidden_states,
990
+ None,
991
+ attention_mask,
992
+ head_mask[i],
993
+ encoder_hidden_states,
994
+ encoder_attention_mask,
995
+ )
996
+ else:
997
+ outputs = block(
998
+ hidden_states,
999
+ layer_past=layer_past,
1000
+ attention_mask=attention_mask,
1001
+ head_mask=head_mask[i],
1002
+ encoder_hidden_states=encoder_hidden_states,
1003
+ encoder_attention_mask=encoder_attention_mask,
1004
+ use_cache=use_cache,
1005
+ output_attentions=output_attentions,
1006
+ )
1007
+
1008
+ hidden_states = outputs[0]
1009
+ if use_cache is True:
1010
+ presents = presents + (outputs[1],)
1011
+
1012
+ if output_attentions:
1013
+ all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
1014
+ if self.config.add_cross_attention:
1015
+ all_cross_attentions = all_cross_attentions + (outputs[3 if use_cache else 2],)
1016
+
1017
+ # Model Parallel: If it's the last layer for that device, put things on the next device
1018
+ if self.model_parallel:
1019
+ for k, v in self.device_map.items():
1020
+ if i == v[-1] and "cuda:" + str(k) != self.last_device:
1021
+ hidden_states = hidden_states.to("cuda:" + str(k + 1))
1022
+
1023
+ hidden_states = self.ln_f(hidden_states)
1024
+
1025
+ hidden_states = hidden_states.view(output_shape)
1026
+ # Add last hidden state
1027
+ if output_hidden_states:
1028
+ all_hidden_states = all_hidden_states + (hidden_states,)
1029
+
1030
+ if not return_dict:
1031
+ return tuple(
1032
+ v
1033
+ for v in [hidden_states, presents, all_hidden_states, all_self_attentions, all_cross_attentions]
1034
+ if v is not None
1035
+ )
1036
+
1037
+ return BaseModelOutputWithPastAndCrossAttentions(
1038
+ last_hidden_state=hidden_states,
1039
+ past_key_values=presents,
1040
+ hidden_states=all_hidden_states,
1041
+ attentions=all_self_attentions,
1042
+ cross_attentions=all_cross_attentions,
1043
+ )
1044
+
1045
+
1046
+ @add_start_docstrings(
1047
+ """
1048
+ The GPT2 Model transformer with a language modeling head on top (linear layer with weights tied to the input
1049
+ embeddings).
1050
+ """,
1051
+ GPT2_START_DOCSTRING,
1052
+ )
1053
+ class GPT2ALMHeadModel(GPT2APreTrainedModel):
1054
+ _tied_weights_keys = ["lm_head.weight"]
1055
+
1056
+ def __init__(self, config):
1057
+ super().__init__(config)
1058
+ self.transformer = GPT2AModel(config)
1059
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
1060
+
1061
+ # Model parallel
1062
+ self.model_parallel = False
1063
+ self.device_map = None
1064
+
1065
+ # Initialize weights and apply final processing
1066
+ self.post_init()
1067
+
1068
+ @add_start_docstrings(PARALLELIZE_DOCSTRING)
1069
+ def parallelize(self, device_map=None):
1070
+ warnings.warn(
1071
+ "`GPT2LMHeadModel.parallelize` is deprecated and will be removed in v5 of Transformers, you should load"
1072
+ " your model with `device_map='balanced'` in the call to `from_pretrained`. You can also provide your own"
1073
+ " `device_map` but it needs to be a dictionary module_name to device, so for instance {'transformer.h.0':"
1074
+ " 0, 'transformer.h.1': 1, ...}",
1075
+ FutureWarning,
1076
+ )
1077
+ self.device_map = (
1078
+ get_device_map(len(self.transformer.h), range(torch.cuda.device_count()))
1079
+ if device_map is None
1080
+ else device_map
1081
+ )
1082
+ assert_device_map(self.device_map, len(self.transformer.h))
1083
+ self.transformer.parallelize(self.device_map)
1084
+ self.lm_head = self.lm_head.to(self.transformer.first_device)
1085
+ self.model_parallel = True
1086
+
1087
+ @add_start_docstrings(DEPARALLELIZE_DOCSTRING)
1088
+ def deparallelize(self):
1089
+ warnings.warn(
1090
+ "Like `parallelize`, `deparallelize` is deprecated and will be removed in v5 of Transformers.",
1091
+ FutureWarning,
1092
+ )
1093
+ self.transformer.deparallelize()
1094
+ self.transformer = self.transformer.to("cpu")
1095
+ self.lm_head = self.lm_head.to("cpu")
1096
+ self.model_parallel = False
1097
+ torch.cuda.empty_cache()
1098
+
1099
+ def get_output_embeddings(self):
1100
+ return self.lm_head
1101
+
1102
+ def set_output_embeddings(self, new_embeddings):
1103
+ self.lm_head = new_embeddings
1104
+
1105
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
1106
+ token_type_ids = kwargs.get("token_type_ids", None)
1107
+ # only last token for inputs_ids if past is defined in kwargs
1108
+ if past_key_values:
1109
+ input_ids = input_ids[:, -1].unsqueeze(-1)
1110
+ if token_type_ids is not None:
1111
+ token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
1112
+
1113
+ attention_mask = kwargs.get("attention_mask", None)
1114
+ position_ids = kwargs.get("position_ids", None)
1115
+
1116
+ if attention_mask is not None and position_ids is None:
1117
+ # create position_ids on the fly for batch generation
1118
+ position_ids = attention_mask.long().cumsum(-1) - 1
1119
+ position_ids.masked_fill_(attention_mask == 0, 1)
1120
+ if past_key_values:
1121
+ position_ids = position_ids[:, -1].unsqueeze(-1)
1122
+ else:
1123
+ position_ids = None
1124
+
1125
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1126
+ if inputs_embeds is not None and past_key_values is None:
1127
+ model_inputs = {"inputs_embeds": inputs_embeds}
1128
+ else:
1129
+ model_inputs = {"input_ids": input_ids}
1130
+
1131
+ model_inputs.update(
1132
+ {
1133
+ "past_key_values": past_key_values,
1134
+ "use_cache": kwargs.get("use_cache"),
1135
+ "position_ids": position_ids,
1136
+ "attention_mask": attention_mask,
1137
+ "token_type_ids": token_type_ids,
1138
+ }
1139
+ )
1140
+ return model_inputs
1141
+
1142
+ @add_start_docstrings_to_model_forward(GPT2_INPUTS_DOCSTRING)
1143
+ @add_code_sample_docstrings(
1144
+ checkpoint=_CHECKPOINT_FOR_DOC,
1145
+ output_type=CausalLMOutputWithCrossAttentions,
1146
+ config_class=_CONFIG_FOR_DOC,
1147
+ )
1148
+ def forward(
1149
+ self,
1150
+ input_ids: Optional[torch.LongTensor] = None,
1151
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1152
+ attention_mask: Optional[torch.FloatTensor] = None,
1153
+ token_type_ids: Optional[torch.LongTensor] = None,
1154
+ position_ids: Optional[torch.LongTensor] = None,
1155
+ head_mask: Optional[torch.FloatTensor] = None,
1156
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1157
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1158
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
1159
+ labels: Optional[torch.LongTensor] = None,
1160
+ use_cache: Optional[bool] = None,
1161
+ output_attentions: Optional[bool] = None,
1162
+ output_hidden_states: Optional[bool] = None,
1163
+ return_dict: Optional[bool] = None,
1164
+ ) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
1165
+ r"""
1166
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1167
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
1168
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
1169
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
1170
+ """
1171
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1172
+
1173
+ transformer_outputs = self.transformer(
1174
+ input_ids,
1175
+ past_key_values=past_key_values,
1176
+ attention_mask=attention_mask,
1177
+ token_type_ids=token_type_ids,
1178
+ position_ids=position_ids,
1179
+ head_mask=head_mask,
1180
+ inputs_embeds=inputs_embeds,
1181
+ encoder_hidden_states=encoder_hidden_states,
1182
+ encoder_attention_mask=encoder_attention_mask,
1183
+ use_cache=use_cache,
1184
+ output_attentions=output_attentions,
1185
+ output_hidden_states=output_hidden_states,
1186
+ return_dict=return_dict,
1187
+ )
1188
+ hidden_states = transformer_outputs[0]
1189
+
1190
+ # Set device for model parallelism
1191
+ if self.model_parallel:
1192
+ torch.cuda.set_device(self.transformer.first_device)
1193
+ hidden_states = hidden_states.to(self.lm_head.weight.device)
1194
+
1195
+ lm_logits = self.lm_head(hidden_states)
1196
+
1197
+ loss = None
1198
+ if labels is not None:
1199
+ # move labels to correct device to enable model parallelism
1200
+ labels = labels.to(lm_logits.device)
1201
+ # Shift so that tokens < n predict n
1202
+ shift_logits = lm_logits[..., :-1, :].contiguous()
1203
+ shift_labels = labels[..., 1:].contiguous()
1204
+ # Flatten the tokens
1205
+ loss_fct = CrossEntropyLoss()
1206
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
1207
+
1208
+ if not return_dict:
1209
+ output = (lm_logits,) + transformer_outputs[1:]
1210
+ return ((loss,) + output) if loss is not None else output
1211
+
1212
+ return CausalLMOutputWithCrossAttentions(
1213
+ loss=loss,
1214
+ logits=lm_logits,
1215
+ past_key_values=transformer_outputs.past_key_values,
1216
+ hidden_states=transformer_outputs.hidden_states,
1217
+ attentions=transformer_outputs.attentions,
1218
+ cross_attentions=transformer_outputs.cross_attentions,
1219
+ )
1220
+
1221
+ @staticmethod
1222
+ def _reorder_cache(
1223
+ past_key_values: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor
1224
+ ) -> Tuple[Tuple[torch.Tensor]]:
1225
+ """
1226
+ This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
1227
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
1228
+ beam_idx at every generation step.
1229
+ """
1230
+ return tuple(
1231
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past)
1232
+ for layer_past in past_key_values
1233
+ )
1234
+
1235
+
1236
+ @add_start_docstrings(
1237
+ """
1238
+ The GPT2 Model transformer with a language modeling and a multiple-choice classification head on top e.g. for
1239
+ RocStories/SWAG tasks. The two heads are two linear layers. The language modeling head has its weights tied to the
1240
+ input embeddings, the classification head takes as input the input of a specified classification token index in the
1241
+ input sequence).
1242
+ """,
1243
+ GPT2_START_DOCSTRING,
1244
+ )
1245
+ class GPT2ADoubleHeadsModel(GPT2APreTrainedModel):
1246
+ _tied_weights_keys = ["lm_head.weight"]
1247
+
1248
+ def __init__(self, config):
1249
+ super().__init__(config)
1250
+ config.num_labels = 1
1251
+ self.transformer = GPT2AModel(config)
1252
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
1253
+ self.multiple_choice_head = SequenceSummary(config)
1254
+
1255
+ # Model parallel
1256
+ self.model_parallel = False
1257
+ self.device_map = None
1258
+
1259
+ # Initialize weights and apply final processing
1260
+ self.post_init()
1261
+
1262
+ @add_start_docstrings(PARALLELIZE_DOCSTRING)
1263
+ def parallelize(self, device_map=None):
1264
+ warnings.warn(
1265
+ "`GPT2DoubleHeadsModel.parallelize` is deprecated and will be removed in v5 of Transformers, you should"
1266
+ " load your model with `device_map='balanced'` in the call to `from_pretrained`. You can also provide your"
1267
+ " own `device_map` but it needs to be a dictionary module_name to device, so for instance"
1268
+ " {'transformer.h.0': 0, 'transformer.h.1': 1, ...}",
1269
+ FutureWarning,
1270
+ )
1271
+ self.device_map = (
1272
+ get_device_map(len(self.transformer.h), range(torch.cuda.device_count()))
1273
+ if device_map is None
1274
+ else device_map
1275
+ )
1276
+ assert_device_map(self.device_map, len(self.transformer.h))
1277
+ self.transformer.parallelize(self.device_map)
1278
+ self.lm_head = self.lm_head.to(self.transformer.first_device)
1279
+ self.multiple_choice_head = self.multiple_choice_head.to(self.transformer.first_device)
1280
+ self.model_parallel = True
1281
+
1282
+ @add_start_docstrings(DEPARALLELIZE_DOCSTRING)
1283
+ def deparallelize(self):
1284
+ warnings.warn(
1285
+ "Like `parallelize`, `deparallelize` is deprecated and will be removed in v5 of Transformers.",
1286
+ FutureWarning,
1287
+ )
1288
+ self.transformer.deparallelize()
1289
+ self.transformer = self.transformer.to("cpu")
1290
+ self.lm_head = self.lm_head.to("cpu")
1291
+ self.multiple_choice_head = self.multiple_choice_head.to("cpu")
1292
+ self.model_parallel = False
1293
+ torch.cuda.empty_cache()
1294
+
1295
+ def get_output_embeddings(self):
1296
+ return self.lm_head
1297
+
1298
+ def set_output_embeddings(self, new_embeddings):
1299
+ self.lm_head = new_embeddings
1300
+
1301
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, **kwargs):
1302
+ token_type_ids = kwargs.get("token_type_ids", None)
1303
+ # only last token for inputs_ids if past is defined in kwargs
1304
+ if past_key_values:
1305
+ input_ids = input_ids[:, -1].unsqueeze(-1)
1306
+ if token_type_ids is not None:
1307
+ token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
1308
+
1309
+ attention_mask = kwargs.get("attention_mask", None)
1310
+ position_ids = kwargs.get("position_ids", None)
1311
+
1312
+ if attention_mask is not None and position_ids is None:
1313
+ # create position_ids on the fly for batch generation
1314
+ position_ids = attention_mask.long().cumsum(-1) - 1
1315
+ position_ids.masked_fill_(attention_mask == 0, 1)
1316
+ if past_key_values:
1317
+ position_ids = position_ids[:, -1].unsqueeze(-1)
1318
+ else:
1319
+ position_ids = None
1320
+
1321
+ return {
1322
+ "input_ids": input_ids,
1323
+ "past_key_values": past_key_values,
1324
+ "use_cache": kwargs.get("use_cache"),
1325
+ "position_ids": position_ids,
1326
+ "attention_mask": attention_mask,
1327
+ "token_type_ids": token_type_ids,
1328
+ }
1329
+
1330
+ @add_start_docstrings_to_model_forward(GPT2_INPUTS_DOCSTRING)
1331
+ @replace_return_docstrings(output_type=GPT2ADoubleHeadsModelOutput, config_class=_CONFIG_FOR_DOC)
1332
+ def forward(
1333
+ self,
1334
+ input_ids: Optional[torch.LongTensor] = None,
1335
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1336
+ attention_mask: Optional[torch.FloatTensor] = None,
1337
+ token_type_ids: Optional[torch.LongTensor] = None,
1338
+ position_ids: Optional[torch.LongTensor] = None,
1339
+ head_mask: Optional[torch.FloatTensor] = None,
1340
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1341
+ mc_token_ids: Optional[torch.LongTensor] = None,
1342
+ labels: Optional[torch.LongTensor] = None,
1343
+ mc_labels: Optional[torch.LongTensor] = None,
1344
+ use_cache: Optional[bool] = None,
1345
+ output_attentions: Optional[bool] = None,
1346
+ output_hidden_states: Optional[bool] = None,
1347
+ return_dict: Optional[bool] = None,
1348
+ **kwargs,
1349
+ ) -> Union[Tuple, GPT2ADoubleHeadsModelOutput]:
1350
+ r"""
1351
+ mc_token_ids (`torch.LongTensor` of shape `(batch_size, num_choices)`, *optional*, default to index of the last token of the input):
1352
+ Index of the classification token in each input sequence. Selected in the range `[0, input_ids.size(-1) -
1353
+ 1]`.
1354
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1355
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
1356
+ `labels = input_ids`. Indices are selected in `[-100, 0, ..., config.vocab_size - 1]`. All labels set to
1357
+ `-100` are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size - 1]`
1358
+ mc_labels (`torch.LongTensor` of shape `(batch_size)`, *optional*):
1359
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]`
1360
+ where *num_choices* is the size of the second dimension of the input tensors. (see *input_ids* above)
1361
+
1362
+ Return:
1363
+
1364
+ Example:
1365
+
1366
+ ```python
1367
+ >>> import torch
1368
+ >>> from transformers import AutoTokenizer, GPT2DoubleHeadsModel
1369
+
1370
+ >>> tokenizer = AutoTokenizer.from_pretrained("gpt2")
1371
+ >>> model = GPT2DoubleHeadsModel.from_pretrained("gpt2")
1372
+
1373
+ >>> # Add a [CLS] to the vocabulary (we should train it also!)
1374
+ >>> num_added_tokens = tokenizer.add_special_tokens({"cls_token": "[CLS]"})
1375
+ >>> # Update the model embeddings with the new vocabulary size
1376
+ >>> embedding_layer = model.resize_token_embeddings(len(tokenizer))
1377
+
1378
+ >>> choices = ["Hello, my dog is cute [CLS]", "Hello, my cat is cute [CLS]"]
1379
+ >>> encoded_choices = [tokenizer.encode(s) for s in choices]
1380
+ >>> cls_token_location = [tokens.index(tokenizer.cls_token_id) for tokens in encoded_choices]
1381
+
1382
+ >>> input_ids = torch.tensor(encoded_choices).unsqueeze(0) # Batch size: 1, number of choices: 2
1383
+ >>> mc_token_ids = torch.tensor([cls_token_location]) # Batch size: 1
1384
+
1385
+ >>> outputs = model(input_ids, mc_token_ids=mc_token_ids)
1386
+ >>> lm_logits = outputs.logits
1387
+ >>> mc_logits = outputs.mc_logits
1388
+ ```"""
1389
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1390
+
1391
+ transformer_outputs = self.transformer(
1392
+ input_ids,
1393
+ past_key_values=past_key_values,
1394
+ attention_mask=attention_mask,
1395
+ token_type_ids=token_type_ids,
1396
+ position_ids=position_ids,
1397
+ head_mask=head_mask,
1398
+ inputs_embeds=inputs_embeds,
1399
+ use_cache=use_cache,
1400
+ output_attentions=output_attentions,
1401
+ output_hidden_states=output_hidden_states,
1402
+ return_dict=return_dict,
1403
+ )
1404
+
1405
+ hidden_states = transformer_outputs[0]
1406
+
1407
+ # Set device for model parallelism
1408
+ if self.model_parallel:
1409
+ torch.cuda.set_device(self.transformer.first_device)
1410
+ hidden_states = hidden_states.to(self.lm_head.weight.device)
1411
+
1412
+ lm_logits = self.lm_head(hidden_states)
1413
+ mc_logits = self.multiple_choice_head(hidden_states, mc_token_ids).squeeze(-1)
1414
+
1415
+ mc_loss = None
1416
+ if mc_labels is not None:
1417
+ loss_fct = CrossEntropyLoss()
1418
+ mc_loss = loss_fct(mc_logits.view(-1, mc_logits.size(-1)), mc_labels.view(-1))
1419
+ lm_loss = None
1420
+ if labels is not None:
1421
+ labels = labels.to(lm_logits.device)
1422
+ shift_logits = lm_logits[..., :-1, :].contiguous()
1423
+ shift_labels = labels[..., 1:].contiguous()
1424
+ loss_fct = CrossEntropyLoss()
1425
+ lm_loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
1426
+
1427
+ if not return_dict:
1428
+ output = (lm_logits, mc_logits) + transformer_outputs[1:]
1429
+ if mc_loss is not None:
1430
+ output = (mc_loss,) + output
1431
+ return ((lm_loss,) + output) if lm_loss is not None else output
1432
+
1433
+ return GPT2ADoubleHeadsModelOutput(
1434
+ loss=lm_loss,
1435
+ mc_loss=mc_loss,
1436
+ logits=lm_logits,
1437
+ mc_logits=mc_logits,
1438
+ past_key_values=transformer_outputs.past_key_values,
1439
+ hidden_states=transformer_outputs.hidden_states,
1440
+ attentions=transformer_outputs.attentions,
1441
+ )
1442
+
1443
+ @staticmethod
1444
+ def _reorder_cache(
1445
+ past_key_values: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor
1446
+ ) -> Tuple[Tuple[torch.Tensor]]:
1447
+ """
1448
+ This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
1449
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
1450
+ beam_idx at every generation step.
1451
+ """
1452
+ return tuple(
1453
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past)
1454
+ for layer_past in past_key_values
1455
+ )
1456
+
1457
+
1458
+ @add_start_docstrings(
1459
+ """
1460
+ The GPT2 Model transformer with a sequence classification head on top (linear layer).
1461
+
1462
+ [`GPT2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1463
+ (e.g. GPT-1) do.
1464
+
1465
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1466
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1467
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1468
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1469
+ each row of the batch).
1470
+ """,
1471
+ GPT2_START_DOCSTRING,
1472
+ )
1473
+ class GPT2AForSequenceClassification(GPT2APreTrainedModel):
1474
+ def __init__(self, config):
1475
+ super().__init__(config)
1476
+ self.num_labels = config.num_labels
1477
+ self.transformer = GPT2Model(config)
1478
+ self.score = nn.Linear(config.n_embd, self.num_labels, bias=False)
1479
+
1480
+ # Model parallel
1481
+ self.model_parallel = False
1482
+ self.device_map = None
1483
+
1484
+ # Initialize weights and apply final processing
1485
+ self.post_init()
1486
+
1487
+ @add_start_docstrings_to_model_forward(GPT2_INPUTS_DOCSTRING)
1488
+ @add_code_sample_docstrings(
1489
+ checkpoint="microsoft/DialogRPT-updown",
1490
+ output_type=SequenceClassifierOutputWithPast,
1491
+ config_class=_CONFIG_FOR_DOC,
1492
+ )
1493
+ def forward(
1494
+ self,
1495
+ input_ids: Optional[torch.LongTensor] = None,
1496
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1497
+ attention_mask: Optional[torch.FloatTensor] = None,
1498
+ token_type_ids: Optional[torch.LongTensor] = None,
1499
+ position_ids: Optional[torch.LongTensor] = None,
1500
+ head_mask: Optional[torch.FloatTensor] = None,
1501
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1502
+ labels: Optional[torch.LongTensor] = None,
1503
+ use_cache: Optional[bool] = None,
1504
+ output_attentions: Optional[bool] = None,
1505
+ output_hidden_states: Optional[bool] = None,
1506
+ return_dict: Optional[bool] = None,
1507
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1508
+ r"""
1509
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1510
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1511
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1512
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1513
+ """
1514
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1515
+
1516
+ transformer_outputs = self.transformer(
1517
+ input_ids,
1518
+ past_key_values=past_key_values,
1519
+ attention_mask=attention_mask,
1520
+ token_type_ids=token_type_ids,
1521
+ position_ids=position_ids,
1522
+ head_mask=head_mask,
1523
+ inputs_embeds=inputs_embeds,
1524
+ use_cache=use_cache,
1525
+ output_attentions=output_attentions,
1526
+ output_hidden_states=output_hidden_states,
1527
+ return_dict=return_dict,
1528
+ )
1529
+ hidden_states = transformer_outputs[0]
1530
+ logits = self.score(hidden_states)
1531
+
1532
+ if input_ids is not None:
1533
+ batch_size, sequence_length = input_ids.shape[:2]
1534
+ else:
1535
+ batch_size, sequence_length = inputs_embeds.shape[:2]
1536
+
1537
+ assert (
1538
+ self.config.pad_token_id is not None or batch_size == 1
1539
+ ), "Cannot handle batch sizes > 1 if no padding token is defined."
1540
+ if self.config.pad_token_id is None:
1541
+ sequence_lengths = -1
1542
+ else:
1543
+ if input_ids is not None:
1544
+ sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).long().argmax(-1) - 1).to(
1545
+ logits.device
1546
+ )
1547
+ else:
1548
+ sequence_lengths = -1
1549
+ logger.warning(
1550
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
1551
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
1552
+ )
1553
+
1554
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1555
+
1556
+ loss = None
1557
+ if labels is not None:
1558
+ if self.config.problem_type is None:
1559
+ if self.num_labels == 1:
1560
+ self.config.problem_type = "regression"
1561
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1562
+ self.config.problem_type = "single_label_classification"
1563
+ else:
1564
+ self.config.problem_type = "multi_label_classification"
1565
+
1566
+ if self.config.problem_type == "regression":
1567
+ loss_fct = MSELoss()
1568
+ if self.num_labels == 1:
1569
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1570
+ else:
1571
+ loss = loss_fct(pooled_logits, labels)
1572
+ elif self.config.problem_type == "single_label_classification":
1573
+ loss_fct = CrossEntropyLoss()
1574
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1575
+ elif self.config.problem_type == "multi_label_classification":
1576
+ loss_fct = BCEWithLogitsLoss()
1577
+ loss = loss_fct(pooled_logits, labels)
1578
+ if not return_dict:
1579
+ output = (pooled_logits,) + transformer_outputs[1:]
1580
+ return ((loss,) + output) if loss is not None else output
1581
+
1582
+ return SequenceClassifierOutputWithPast(
1583
+ loss=loss,
1584
+ logits=pooled_logits,
1585
+ past_key_values=transformer_outputs.past_key_values,
1586
+ hidden_states=transformer_outputs.hidden_states,
1587
+ attentions=transformer_outputs.attentions,
1588
+ )
1589
+
1590
+
1591
+ @add_start_docstrings(
1592
+ """
1593
+ GPT2 Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1594
+ Named-Entity-Recognition (NER) tasks.
1595
+ """,
1596
+ GPT2_START_DOCSTRING,
1597
+ )
1598
+ class GPT2AForTokenClassification(GPT2APreTrainedModel):
1599
+ def __init__(self, config):
1600
+ super().__init__(config)
1601
+ self.num_labels = config.num_labels
1602
+
1603
+ self.transformer = GPT2AModel(config)
1604
+ if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
1605
+ classifier_dropout = config.classifier_dropout
1606
+ elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
1607
+ classifier_dropout = config.hidden_dropout
1608
+ else:
1609
+ classifier_dropout = 0.1
1610
+ self.dropout = nn.Dropout(classifier_dropout)
1611
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1612
+
1613
+ # Model parallel
1614
+ self.model_parallel = False
1615
+ self.device_map = None
1616
+
1617
+ # Initialize weights and apply final processing
1618
+ self.post_init()
1619
+
1620
+ @add_start_docstrings_to_model_forward(GPT2_INPUTS_DOCSTRING)
1621
+ # fmt: off
1622
+ @add_code_sample_docstrings(
1623
+ checkpoint="brad1141/gpt2-finetuned-comp2",
1624
+ output_type=TokenClassifierOutput,
1625
+ config_class=_CONFIG_FOR_DOC,
1626
+ expected_loss=0.25,
1627
+ expected_output=["Lead", "Lead", "Lead", "Position", "Lead", "Lead", "Lead", "Lead", "Lead", "Lead", "Lead", "Lead"],
1628
+ )
1629
+ # fmt: on
1630
+ def forward(
1631
+ self,
1632
+ input_ids: Optional[torch.LongTensor] = None,
1633
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1634
+ attention_mask: Optional[torch.FloatTensor] = None,
1635
+ token_type_ids: Optional[torch.LongTensor] = None,
1636
+ position_ids: Optional[torch.LongTensor] = None,
1637
+ head_mask: Optional[torch.FloatTensor] = None,
1638
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1639
+ labels: Optional[torch.LongTensor] = None,
1640
+ use_cache: Optional[bool] = None,
1641
+ output_attentions: Optional[bool] = None,
1642
+ output_hidden_states: Optional[bool] = None,
1643
+ return_dict: Optional[bool] = None,
1644
+ ) -> Union[Tuple, TokenClassifierOutput]:
1645
+ r"""
1646
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1647
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1648
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1649
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1650
+ """
1651
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1652
+
1653
+ transformer_outputs = self.transformer(
1654
+ input_ids,
1655
+ past_key_values=past_key_values,
1656
+ attention_mask=attention_mask,
1657
+ token_type_ids=token_type_ids,
1658
+ position_ids=position_ids,
1659
+ head_mask=head_mask,
1660
+ inputs_embeds=inputs_embeds,
1661
+ use_cache=use_cache,
1662
+ output_attentions=output_attentions,
1663
+ output_hidden_states=output_hidden_states,
1664
+ return_dict=return_dict,
1665
+ )
1666
+
1667
+ hidden_states = transformer_outputs[0]
1668
+ hidden_states = self.dropout(hidden_states)
1669
+ logits = self.classifier(hidden_states)
1670
+
1671
+ loss = None
1672
+ if labels is not None:
1673
+ labels = labels.to(logits.device)
1674
+ loss_fct = CrossEntropyLoss()
1675
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1676
+
1677
+ if not return_dict:
1678
+ output = (logits,) + transformer_outputs[2:]
1679
+ return ((loss,) + output) if loss is not None else output
1680
+
1681
+ return TokenClassifierOutput(
1682
+ loss=loss,
1683
+ logits=logits,
1684
+ hidden_states=transformer_outputs.hidden_states,
1685
+ attentions=transformer_outputs.attentions,
1686
+ )
1687
+
1688
+
1689
+ @add_start_docstrings(
1690
+ """
1691
+ The GPT-2 Model transformer with a span classification head on top for extractive question-answering tasks like
1692
+ SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1693
+ """,
1694
+ GPT2_START_DOCSTRING,
1695
+ )
1696
+ class GPT2AForQuestionAnswering(GPT2APreTrainedModel):
1697
+ def __init__(self, config):
1698
+ super().__init__(config)
1699
+ self.num_labels = config.num_labels
1700
+ self.transformer = GPT2AModel(config)
1701
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1702
+
1703
+ # Model parallel
1704
+ self.model_parallel = False
1705
+ self.device_map = None
1706
+ self.gradient_checkpointing = False
1707
+
1708
+ # Initialize weights and apply final processing
1709
+ self.post_init()
1710
+
1711
+ @add_start_docstrings_to_model_forward(GPT2_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1712
+ @add_code_sample_docstrings(
1713
+ checkpoint=_CHECKPOINT_FOR_DOC,
1714
+ output_type=QuestionAnsweringModelOutput,
1715
+ config_class=_CONFIG_FOR_DOC,
1716
+ real_checkpoint=_CHECKPOINT_FOR_DOC,
1717
+ )
1718
+ def forward(
1719
+ self,
1720
+ input_ids: Optional[torch.LongTensor] = None,
1721
+ attention_mask: Optional[torch.FloatTensor] = None,
1722
+ token_type_ids: Optional[torch.LongTensor] = None,
1723
+ position_ids: Optional[torch.LongTensor] = None,
1724
+ head_mask: Optional[torch.FloatTensor] = None,
1725
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1726
+ start_positions: Optional[torch.LongTensor] = None,
1727
+ end_positions: Optional[torch.LongTensor] = None,
1728
+ output_attentions: Optional[bool] = None,
1729
+ output_hidden_states: Optional[bool] = None,
1730
+ return_dict: Optional[bool] = None,
1731
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1732
+ r"""
1733
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1734
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1735
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1736
+ are not taken into account for computing the loss.
1737
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1738
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1739
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1740
+ are not taken into account for computing the loss.
1741
+ """
1742
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1743
+
1744
+ outputs = self.transformer(
1745
+ input_ids,
1746
+ attention_mask=attention_mask,
1747
+ token_type_ids=token_type_ids,
1748
+ position_ids=position_ids,
1749
+ head_mask=head_mask,
1750
+ inputs_embeds=inputs_embeds,
1751
+ output_attentions=output_attentions,
1752
+ output_hidden_states=output_hidden_states,
1753
+ return_dict=return_dict,
1754
+ )
1755
+
1756
+ sequence_output = outputs[0]
1757
+
1758
+ logits = self.qa_outputs(sequence_output)
1759
+ start_logits, end_logits = logits.split(1, dim=-1)
1760
+ start_logits = start_logits.squeeze(-1).contiguous()
1761
+ end_logits = end_logits.squeeze(-1).contiguous()
1762
+
1763
+ total_loss = None
1764
+ if start_positions is not None and end_positions is not None:
1765
+ # If we are on multi-GPU, split add a dimension
1766
+ if len(start_positions.size()) > 1:
1767
+ start_positions = start_positions.squeeze(-1).to(start_logits.device)
1768
+ if len(end_positions.size()) > 1:
1769
+ end_positions = end_positions.squeeze(-1).to(end_logits.device)
1770
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1771
+ ignored_index = start_logits.size(1)
1772
+ start_positions = start_positions.clamp(0, ignored_index)
1773
+ end_positions = end_positions.clamp(0, ignored_index)
1774
+
1775
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1776
+ start_loss = loss_fct(start_logits, start_positions)
1777
+ end_loss = loss_fct(end_logits, end_positions)
1778
+ total_loss = (start_loss + end_loss) / 2
1779
+
1780
+ if not return_dict:
1781
+ output = (start_logits, end_logits) + outputs[2:]
1782
+ return ((total_loss,) + output) if total_loss is not None else output
1783
+
1784
+ return QuestionAnsweringModelOutput(
1785
+ loss=total_loss,
1786
+ start_logits=start_logits,
1787
+ end_logits=end_logits,
1788
+ hidden_states=outputs.hidden_states,
1789
+ attentions=outputs.attentions,
1790
+ )
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eda74e0186b8b4be6309e11d3a4d4b8894d5b2b8cb4c3ef85b9997931f7a9716
3
+ size 686576053