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