esenergun commited on
Commit
d0d2ecc
1 Parent(s): dbabb90

Upload model

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