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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 |
+
|
18 |
+
from collections import OrderedDict
|
19 |
+
from typing import Any, List, Mapping, Optional
|
20 |
+
|
21 |
+
from transformers import PreTrainedTokenizer, TensorType, is_torch_available
|
22 |
+
from transformers.configuration_utils import PretrainedConfig
|
23 |
+
from transformers.onnx import OnnxConfigWithPast, PatchingSpec
|
24 |
+
from transformers.utils import logging
|
25 |
+
|
26 |
+
|
27 |
+
logger = logging.get_logger(__name__)
|
28 |
+
|
29 |
+
|
30 |
+
class GPT2Config(PretrainedConfig):
|
31 |
+
"""
|
32 |
+
This is the configuration class to store the configuration of a [`GPT2Model`] or a [`TFGPT2Model`]. It is used to
|
33 |
+
instantiate a GPT-2 model according to the specified arguments, defining the model architecture. Instantiating a
|
34 |
+
configuration with the defaults will yield a similar configuration to that of the GPT-2
|
35 |
+
[openai-community/gpt2](https://huggingface.co/openai-community/gpt2) architecture.
|
36 |
+
|
37 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
38 |
+
documentation from [`PretrainedConfig`] for more information.
|
39 |
+
|
40 |
+
|
41 |
+
Args:
|
42 |
+
vocab_size (`int`, *optional*, defaults to 50257):
|
43 |
+
Vocabulary size of the GPT-2 model. Defines the number of different tokens that can be represented by the
|
44 |
+
`inputs_ids` passed when calling [`GPT2Model`] or [`TFGPT2Model`].
|
45 |
+
n_positions (`int`, *optional*, defaults to 1024):
|
46 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
47 |
+
just in case (e.g., 512 or 1024 or 2048).
|
48 |
+
n_embd (`int`, *optional*, defaults to 768):
|
49 |
+
Dimensionality of the embeddings and hidden states.
|
50 |
+
n_layer (`int`, *optional*, defaults to 12):
|
51 |
+
Number of hidden layers in the Transformer encoder.
|
52 |
+
n_head (`int`, *optional*, defaults to 12):
|
53 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
54 |
+
n_inner (`int`, *optional*):
|
55 |
+
Dimensionality of the inner feed-forward layers. `None` will set it to 4 times n_embd
|
56 |
+
activation_function (`str`, *optional*, defaults to `"gelu_new"`):
|
57 |
+
Activation function, to be selected in the list `["relu", "silu", "gelu", "tanh", "gelu_new"]`.
|
58 |
+
resid_pdrop (`float`, *optional*, defaults to 0.1):
|
59 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
60 |
+
embd_pdrop (`float`, *optional*, defaults to 0.1):
|
61 |
+
The dropout ratio for the embeddings.
|
62 |
+
attn_pdrop (`float`, *optional*, defaults to 0.1):
|
63 |
+
The dropout ratio for the attention.
|
64 |
+
layer_norm_epsilon (`float`, *optional*, defaults to 1e-05):
|
65 |
+
The epsilon to use in the layer normalization layers.
|
66 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
67 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
68 |
+
summary_type (`string`, *optional*, defaults to `"cls_index"`):
|
69 |
+
Argument used when doing sequence summary, used in the models [`GPT2DoubleHeadsModel`] and
|
70 |
+
[`TFGPT2DoubleHeadsModel`].
|
71 |
+
|
72 |
+
Has to be one of the following options:
|
73 |
+
|
74 |
+
- `"last"`: Take the last token hidden state (like XLNet).
|
75 |
+
- `"first"`: Take the first token hidden state (like BERT).
|
76 |
+
- `"mean"`: Take the mean of all tokens hidden states.
|
77 |
+
- `"cls_index"`: Supply a Tensor of classification token position (like GPT/GPT-2).
|
78 |
+
- `"attn"`: Not implemented now, use multi-head attention.
|
79 |
+
summary_use_proj (`bool`, *optional*, defaults to `True`):
|
80 |
+
Argument used when doing sequence summary, used in the models [`GPT2DoubleHeadsModel`] and
|
81 |
+
[`TFGPT2DoubleHeadsModel`].
|
82 |
+
|
83 |
+
Whether or not to add a projection after the vector extraction.
|
84 |
+
summary_activation (`str`, *optional*):
|
85 |
+
Argument used when doing sequence summary. Used in for the multiple choice head in
|
86 |
+
[`GPT2DoubleHeadsModel`].
|
87 |
+
|
88 |
+
Pass `"tanh"` for a tanh activation to the output, any other value will result in no activation.
|
89 |
+
summary_proj_to_labels (`bool`, *optional*, defaults to `True`):
|
90 |
+
Argument used when doing sequence summary, used in the models [`GPT2DoubleHeadsModel`] and
|
91 |
+
[`TFGPT2DoubleHeadsModel`].
|
92 |
+
|
93 |
+
Whether the projection outputs should have `config.num_labels` or `config.hidden_size` classes.
|
94 |
+
summary_first_dropout (`float`, *optional*, defaults to 0.1):
|
95 |
+
Argument used when doing sequence summary, used in the models [`GPT2DoubleHeadsModel`] and
|
96 |
+
[`TFGPT2DoubleHeadsModel`].
|
97 |
+
|
98 |
+
The dropout ratio to be used after the projection and activation.
|
99 |
+
scale_attn_weights (`bool`, *optional*, defaults to `True`):
|
100 |
+
Scale attention weights by dividing by sqrt(hidden_size)..
|
101 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
102 |
+
Whether or not the model should return the last key/values attentions (not used by all models).
|
103 |
+
bos_token_id (`int`, *optional*, defaults to 50256):
|
104 |
+
Id of the beginning of sentence token in the vocabulary.
|
105 |
+
eos_token_id (`int`, *optional*, defaults to 50256):
|
106 |
+
Id of the end of sentence token in the vocabulary.
|
107 |
+
scale_attn_by_inverse_layer_idx (`bool`, *optional*, defaults to `False`):
|
108 |
+
Whether to additionally scale attention weights by `1 / layer_idx + 1`.
|
109 |
+
reorder_and_upcast_attn (`bool`, *optional*, defaults to `False`):
|
110 |
+
Whether to scale keys (K) prior to computing attention (dot-product) and upcast attention
|
111 |
+
dot-product/softmax to float() when training with mixed precision.
|
112 |
+
|
113 |
+
Example:
|
114 |
+
|
115 |
+
```python
|
116 |
+
>>> from transformers import GPT2Config, GPT2Model
|
117 |
+
|
118 |
+
>>> # Initializing a GPT2 configuration
|
119 |
+
>>> configuration = GPT2Config()
|
120 |
+
|
121 |
+
>>> # Initializing a model (with random weights) from the configuration
|
122 |
+
>>> model = GPT2Model(configuration)
|
123 |
+
|
124 |
+
>>> # Accessing the model configuration
|
125 |
+
>>> configuration = model.config
|
126 |
+
```"""
|
127 |
+
|
128 |
+
model_type = "gpt2"
|
129 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
130 |
+
attribute_map = {
|
131 |
+
"hidden_size": "n_embd",
|
132 |
+
"max_position_embeddings": "n_positions",
|
133 |
+
"num_attention_heads": "n_head",
|
134 |
+
"num_hidden_layers": "n_layer",
|
135 |
+
}
|
136 |
+
|
137 |
+
def __init__(
|
138 |
+
self,
|
139 |
+
vocab_size=50258,
|
140 |
+
n_positions=1024,
|
141 |
+
n_embd=768,
|
142 |
+
n_layer=12,
|
143 |
+
n_head=12,
|
144 |
+
n_inner=None,
|
145 |
+
activation_function="gelu_new",
|
146 |
+
resid_pdrop=0.1,
|
147 |
+
embd_pdrop=0.1,
|
148 |
+
attn_pdrop=0.1,
|
149 |
+
layer_norm_epsilon=1e-5,
|
150 |
+
initializer_range=0.02,
|
151 |
+
summary_type="cls_index",
|
152 |
+
summary_use_proj=True,
|
153 |
+
summary_activation=None,
|
154 |
+
summary_proj_to_labels=True,
|
155 |
+
summary_first_dropout=0.1,
|
156 |
+
scale_attn_weights=True,
|
157 |
+
use_cache=True,
|
158 |
+
bos_token_id=50256,
|
159 |
+
eos_token_id=50256,
|
160 |
+
scale_attn_by_inverse_layer_idx=False,
|
161 |
+
reorder_and_upcast_attn=False,
|
162 |
+
**kwargs,
|
163 |
+
):
|
164 |
+
self.vocab_size = vocab_size
|
165 |
+
self.n_positions = n_positions
|
166 |
+
self.n_embd = n_embd
|
167 |
+
self.n_layer = n_layer
|
168 |
+
self.n_head = n_head
|
169 |
+
self.n_inner = n_inner
|
170 |
+
self.activation_function = activation_function
|
171 |
+
self.resid_pdrop = resid_pdrop
|
172 |
+
self.embd_pdrop = embd_pdrop
|
173 |
+
self.attn_pdrop = attn_pdrop
|
174 |
+
self.layer_norm_epsilon = layer_norm_epsilon
|
175 |
+
self.initializer_range = initializer_range
|
176 |
+
self.summary_type = summary_type
|
177 |
+
self.summary_use_proj = summary_use_proj
|
178 |
+
self.summary_activation = summary_activation
|
179 |
+
self.summary_first_dropout = summary_first_dropout
|
180 |
+
self.summary_proj_to_labels = summary_proj_to_labels
|
181 |
+
self.scale_attn_weights = scale_attn_weights
|
182 |
+
self.use_cache = use_cache
|
183 |
+
self.scale_attn_by_inverse_layer_idx = scale_attn_by_inverse_layer_idx
|
184 |
+
self.reorder_and_upcast_attn = reorder_and_upcast_attn
|
185 |
+
|
186 |
+
self.bos_token_id = bos_token_id
|
187 |
+
self.eos_token_id = eos_token_id
|
188 |
+
|
189 |
+
super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
|
190 |
+
|
191 |
+
|
192 |
+
class GPT2OnnxConfig(OnnxConfigWithPast):
|
193 |
+
def __init__(
|
194 |
+
self,
|
195 |
+
config: PretrainedConfig,
|
196 |
+
task: str = "default",
|
197 |
+
patching_specs: List[PatchingSpec] = None,
|
198 |
+
use_past: bool = False,
|
199 |
+
):
|
200 |
+
super().__init__(config, task=task, patching_specs=patching_specs, use_past=use_past)
|
201 |
+
if not getattr(self._config, "pad_token_id", None):
|
202 |
+
# TODO: how to do that better?
|
203 |
+
self._config.pad_token_id = 0
|
204 |
+
|
205 |
+
@property
|
206 |
+
def inputs(self) -> Mapping[str, Mapping[int, str]]:
|
207 |
+
common_inputs = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}})
|
208 |
+
if self.use_past:
|
209 |
+
self.fill_with_past_key_values_(common_inputs, direction="inputs")
|
210 |
+
common_inputs["attention_mask"] = {0: "batch", 1: "past_sequence + sequence"}
|
211 |
+
else:
|
212 |
+
common_inputs["attention_mask"] = {0: "batch", 1: "sequence"}
|
213 |
+
|
214 |
+
return common_inputs
|
215 |
+
|
216 |
+
@property
|
217 |
+
def num_layers(self) -> int:
|
218 |
+
return self._config.n_layer
|
219 |
+
|
220 |
+
@property
|
221 |
+
def num_attention_heads(self) -> int:
|
222 |
+
return self._config.n_head
|
223 |
+
|
224 |
+
def generate_dummy_inputs(
|
225 |
+
self,
|
226 |
+
tokenizer: PreTrainedTokenizer,
|
227 |
+
batch_size: int = -1,
|
228 |
+
seq_length: int = -1,
|
229 |
+
is_pair: bool = False,
|
230 |
+
framework: Optional[TensorType] = None,
|
231 |
+
) -> Mapping[str, Any]:
|
232 |
+
common_inputs = super(OnnxConfigWithPast, self).generate_dummy_inputs(
|
233 |
+
tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
|
234 |
+
)
|
235 |
+
|
236 |
+
# We need to order the input in the way they appears in the forward()
|
237 |
+
ordered_inputs = OrderedDict({"input_ids": common_inputs["input_ids"]})
|
238 |
+
|
239 |
+
# Need to add the past_keys
|
240 |
+
if self.use_past:
|
241 |
+
if not is_torch_available():
|
242 |
+
raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
|
243 |
+
else:
|
244 |
+
import torch
|
245 |
+
|
246 |
+
batch, seqlen = common_inputs["input_ids"].shape
|
247 |
+
# Not using the same length for past_key_values
|
248 |
+
past_key_values_length = seqlen + 2
|
249 |
+
past_shape = (
|
250 |
+
batch,
|
251 |
+
self.num_attention_heads,
|
252 |
+
past_key_values_length,
|
253 |
+
self._config.hidden_size // self.num_attention_heads,
|
254 |
+
)
|
255 |
+
ordered_inputs["past_key_values"] = [
|
256 |
+
(torch.zeros(past_shape), torch.zeros(past_shape)) for _ in range(self.num_layers)
|
257 |
+
]
|
258 |
+
|
259 |
+
ordered_inputs["attention_mask"] = common_inputs["attention_mask"]
|
260 |
+
if self.use_past:
|
261 |
+
mask_dtype = ordered_inputs["attention_mask"].dtype
|
262 |
+
ordered_inputs["attention_mask"] = torch.cat(
|
263 |
+
[ordered_inputs["attention_mask"], torch.ones(batch, past_key_values_length, dtype=mask_dtype)], dim=1
|
264 |
+
)
|
265 |
+
|
266 |
+
return ordered_inputs
|
267 |
+
|
268 |
+
@property
|
269 |
+
def default_onnx_opset(self) -> int:
|
270 |
+
return 13
|
271 |
+
|
272 |
+
class GPT2VisionConfig(PretrainedConfig):
|
273 |
+
model_type = "gptvision"
|
274 |
+
|
275 |
+
def __init__(self, **kwargs):
|
276 |
+
super().__init__(**kwargs)
|
277 |
+
self.gpt2_config = GPT2Config(**kwargs)
|
278 |
+
|
279 |
+
|