rhysjones commited on
Commit
f2bac03
1 Parent(s): 3158c84

Upload folder using huggingface_hub

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