crumb commited on
Commit
4697410
1 Parent(s): d22c8dd

Upload model

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