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