k4tel commited on
Commit
c69ca3f
·
1 Parent(s): 81723aa
config.json CHANGED
@@ -67,7 +67,7 @@
67
  "pooler_type": "first_token_transform",
68
  "problem_type": "regression",
69
  "torch_dtype": "float32",
70
- "transformers_version": "4.19.3",
71
  "type_vocab_size": 2,
72
  "vocab_size": 119547
73
  }
 
67
  "pooler_type": "first_token_transform",
68
  "problem_type": "regression",
69
  "torch_dtype": "float32",
70
+ "transformers_version": "4.23.1",
71
  "type_vocab_size": 2,
72
  "vocab_size": 119547
73
  }
modeling_bert.py ADDED
@@ -0,0 +1,1889 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The Google AI Language Team Authors and The 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 BERT model."""
17
+
18
+
19
+ import math
20
+ import os
21
+ import warnings
22
+ from dataclasses import dataclass
23
+ from typing import List, Optional, Tuple, Union
24
+
25
+ import torch
26
+ import torch.utils.checkpoint
27
+ from torch import nn
28
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
29
+
30
+ from ...activations import ACT2FN
31
+ from ...modeling_outputs import (
32
+ BaseModelOutputWithPastAndCrossAttentions,
33
+ BaseModelOutputWithPoolingAndCrossAttentions,
34
+ CausalLMOutputWithCrossAttentions,
35
+ MaskedLMOutput,
36
+ MultipleChoiceModelOutput,
37
+ NextSentencePredictorOutput,
38
+ QuestionAnsweringModelOutput,
39
+ SequenceClassifierOutput,
40
+ TokenClassifierOutput,
41
+ )
42
+ from ...modeling_utils import PreTrainedModel
43
+ from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
44
+ from ...utils import (
45
+ ModelOutput,
46
+ add_code_sample_docstrings,
47
+ add_start_docstrings,
48
+ add_start_docstrings_to_model_forward,
49
+ logging,
50
+ replace_return_docstrings,
51
+ )
52
+ from .configuration_bert import BertConfig
53
+
54
+
55
+ logger = logging.get_logger(__name__)
56
+
57
+ _CHECKPOINT_FOR_DOC = "bert-base-uncased"
58
+ _CONFIG_FOR_DOC = "BertConfig"
59
+ _TOKENIZER_FOR_DOC = "BertTokenizer"
60
+
61
+ # TokenClassification docstring
62
+ _CHECKPOINT_FOR_TOKEN_CLASSIFICATION = "dbmdz/bert-large-cased-finetuned-conll03-english"
63
+ _TOKEN_CLASS_EXPECTED_OUTPUT = (
64
+ "['O', 'I-ORG', 'I-ORG', 'I-ORG', 'O', 'O', 'O', 'O', 'O', 'I-LOC', 'O', 'I-LOC', 'I-LOC'] "
65
+ )
66
+ _TOKEN_CLASS_EXPECTED_LOSS = 0.01
67
+
68
+ # QuestionAnswering docstring
69
+ _CHECKPOINT_FOR_QA = "deepset/bert-base-cased-squad2"
70
+ _QA_EXPECTED_OUTPUT = "'a nice puppet'"
71
+ _QA_EXPECTED_LOSS = 7.41
72
+ _QA_TARGET_START_INDEX = 14
73
+ _QA_TARGET_END_INDEX = 15
74
+
75
+ # SequenceClassification docstring
76
+ _CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION = "textattack/bert-base-uncased-yelp-polarity"
77
+ _SEQ_CLASS_EXPECTED_OUTPUT = "'LABEL_1'"
78
+ _SEQ_CLASS_EXPECTED_LOSS = 0.01
79
+
80
+
81
+ BERT_PRETRAINED_MODEL_ARCHIVE_LIST = [
82
+ "bert-base-uncased",
83
+ "bert-large-uncased",
84
+ "bert-base-cased",
85
+ "bert-large-cased",
86
+ "bert-base-multilingual-uncased",
87
+ "bert-base-multilingual-cased",
88
+ "bert-base-chinese",
89
+ "bert-base-german-cased",
90
+ "bert-large-uncased-whole-word-masking",
91
+ "bert-large-cased-whole-word-masking",
92
+ "bert-large-uncased-whole-word-masking-finetuned-squad",
93
+ "bert-large-cased-whole-word-masking-finetuned-squad",
94
+ "bert-base-cased-finetuned-mrpc",
95
+ "bert-base-german-dbmdz-cased",
96
+ "bert-base-german-dbmdz-uncased",
97
+ "cl-tohoku/bert-base-japanese",
98
+ "cl-tohoku/bert-base-japanese-whole-word-masking",
99
+ "cl-tohoku/bert-base-japanese-char",
100
+ "cl-tohoku/bert-base-japanese-char-whole-word-masking",
101
+ "TurkuNLP/bert-base-finnish-cased-v1",
102
+ "TurkuNLP/bert-base-finnish-uncased-v1",
103
+ "wietsedv/bert-base-dutch-cased",
104
+ # See all BERT models at https://huggingface.co/models?filter=bert
105
+ ]
106
+
107
+
108
+ def load_tf_weights_in_bert(model, config, tf_checkpoint_path):
109
+ """Load tf checkpoints in a pytorch model."""
110
+ try:
111
+ import re
112
+
113
+ import numpy as np
114
+ import tensorflow as tf
115
+ except ImportError:
116
+ logger.error(
117
+ "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
118
+ "https://www.tensorflow.org/install/ for installation instructions."
119
+ )
120
+ raise
121
+ tf_path = os.path.abspath(tf_checkpoint_path)
122
+ logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
123
+ # Load weights from TF model
124
+ init_vars = tf.train.list_variables(tf_path)
125
+ names = []
126
+ arrays = []
127
+ for name, shape in init_vars:
128
+ logger.info(f"Loading TF weight {name} with shape {shape}")
129
+ array = tf.train.load_variable(tf_path, name)
130
+ names.append(name)
131
+ arrays.append(array)
132
+
133
+ for name, array in zip(names, arrays):
134
+ name = name.split("/")
135
+ # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
136
+ # which are not required for using pretrained model
137
+ if any(
138
+ n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"]
139
+ for n in name
140
+ ):
141
+ logger.info(f"Skipping {'/'.join(name)}")
142
+ continue
143
+ pointer = model
144
+ for m_name in name:
145
+ if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
146
+ scope_names = re.split(r"_(\d+)", m_name)
147
+ else:
148
+ scope_names = [m_name]
149
+ if scope_names[0] == "kernel" or scope_names[0] == "gamma":
150
+ pointer = getattr(pointer, "weight")
151
+ elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
152
+ pointer = getattr(pointer, "bias")
153
+ elif scope_names[0] == "output_weights":
154
+ pointer = getattr(pointer, "weight")
155
+ elif scope_names[0] == "squad":
156
+ pointer = getattr(pointer, "classifier")
157
+ else:
158
+ try:
159
+ pointer = getattr(pointer, scope_names[0])
160
+ except AttributeError:
161
+ logger.info(f"Skipping {'/'.join(name)}")
162
+ continue
163
+ if len(scope_names) >= 2:
164
+ num = int(scope_names[1])
165
+ pointer = pointer[num]
166
+ if m_name[-11:] == "_embeddings":
167
+ pointer = getattr(pointer, "weight")
168
+ elif m_name == "kernel":
169
+ array = np.transpose(array)
170
+ try:
171
+ if pointer.shape != array.shape:
172
+ raise ValueError(f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched")
173
+ except AssertionError as e:
174
+ e.args += (pointer.shape, array.shape)
175
+ raise
176
+ logger.info(f"Initialize PyTorch weight {name}")
177
+ pointer.data = torch.from_numpy(array)
178
+ return model
179
+
180
+
181
+ class BertEmbeddings(nn.Module):
182
+ """Construct the embeddings from word, position and token_type embeddings."""
183
+
184
+ def __init__(self, config):
185
+ super().__init__()
186
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
187
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
188
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
189
+
190
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
191
+ # any TensorFlow checkpoint file
192
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
193
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
194
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
195
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
196
+ self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)))
197
+ self.register_buffer(
198
+ "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
199
+ )
200
+
201
+ def forward(
202
+ self,
203
+ input_ids: Optional[torch.LongTensor] = None,
204
+ token_type_ids: Optional[torch.LongTensor] = None,
205
+ position_ids: Optional[torch.LongTensor] = None,
206
+ inputs_embeds: Optional[torch.FloatTensor] = None,
207
+ past_key_values_length: int = 0,
208
+ ) -> torch.Tensor:
209
+ if input_ids is not None:
210
+ input_shape = input_ids.size()
211
+ else:
212
+ input_shape = inputs_embeds.size()[:-1]
213
+
214
+ seq_length = input_shape[1]
215
+
216
+ if position_ids is None:
217
+ position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
218
+
219
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
220
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
221
+ # issue #5664
222
+ if token_type_ids is None:
223
+ if hasattr(self, "token_type_ids"):
224
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
225
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
226
+ token_type_ids = buffered_token_type_ids_expanded
227
+ else:
228
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
229
+
230
+ if inputs_embeds is None:
231
+ inputs_embeds = self.word_embeddings(input_ids)
232
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
233
+
234
+ embeddings = inputs_embeds + token_type_embeddings
235
+ if self.position_embedding_type == "absolute":
236
+ position_embeddings = self.position_embeddings(position_ids)
237
+ embeddings += position_embeddings
238
+ embeddings = self.LayerNorm(embeddings)
239
+ embeddings = self.dropout(embeddings)
240
+ return embeddings
241
+
242
+
243
+ class BertSelfAttention(nn.Module):
244
+ def __init__(self, config, position_embedding_type=None):
245
+ super().__init__()
246
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
247
+ raise ValueError(
248
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
249
+ f"heads ({config.num_attention_heads})"
250
+ )
251
+
252
+ self.num_attention_heads = config.num_attention_heads
253
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
254
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
255
+
256
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
257
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
258
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
259
+
260
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
261
+ self.position_embedding_type = position_embedding_type or getattr(
262
+ config, "position_embedding_type", "absolute"
263
+ )
264
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
265
+ self.max_position_embeddings = config.max_position_embeddings
266
+ self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
267
+
268
+ self.is_decoder = config.is_decoder
269
+
270
+ def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
271
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
272
+ x = x.view(new_x_shape)
273
+ return x.permute(0, 2, 1, 3)
274
+
275
+ def forward(
276
+ self,
277
+ hidden_states: torch.Tensor,
278
+ attention_mask: Optional[torch.FloatTensor] = None,
279
+ head_mask: Optional[torch.FloatTensor] = None,
280
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
281
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
282
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
283
+ output_attentions: Optional[bool] = False,
284
+ ) -> Tuple[torch.Tensor]:
285
+ mixed_query_layer = self.query(hidden_states)
286
+
287
+ # If this is instantiated as a cross-attention module, the keys
288
+ # and values come from an encoder; the attention mask needs to be
289
+ # such that the encoder's padding tokens are not attended to.
290
+ is_cross_attention = encoder_hidden_states is not None
291
+
292
+ if is_cross_attention and past_key_value is not None:
293
+ # reuse k,v, cross_attentions
294
+ key_layer = past_key_value[0]
295
+ value_layer = past_key_value[1]
296
+ attention_mask = encoder_attention_mask
297
+ elif is_cross_attention:
298
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
299
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
300
+ attention_mask = encoder_attention_mask
301
+ elif past_key_value is not None:
302
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
303
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
304
+ key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
305
+ value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
306
+ else:
307
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
308
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
309
+
310
+ query_layer = self.transpose_for_scores(mixed_query_layer)
311
+
312
+ if self.is_decoder:
313
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
314
+ # Further calls to cross_attention layer can then reuse all cross-attention
315
+ # key/value_states (first "if" case)
316
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
317
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
318
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
319
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
320
+ past_key_value = (key_layer, value_layer)
321
+
322
+ # Take the dot product between "query" and "key" to get the raw attention scores.
323
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
324
+
325
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
326
+ seq_length = hidden_states.size()[1]
327
+ position_ids_l = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
328
+ position_ids_r = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
329
+ distance = position_ids_l - position_ids_r
330
+ positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
331
+ positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
332
+
333
+ if self.position_embedding_type == "relative_key":
334
+ relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
335
+ attention_scores = attention_scores + relative_position_scores
336
+ elif self.position_embedding_type == "relative_key_query":
337
+ relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
338
+ relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
339
+ attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
340
+
341
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
342
+ if attention_mask is not None:
343
+ # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
344
+ attention_scores = attention_scores + attention_mask
345
+
346
+ # Normalize the attention scores to probabilities.
347
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
348
+
349
+ # This is actually dropping out entire tokens to attend to, which might
350
+ # seem a bit unusual, but is taken from the original Transformer paper.
351
+ attention_probs = self.dropout(attention_probs)
352
+
353
+ # Mask heads if we want to
354
+ if head_mask is not None:
355
+ attention_probs = attention_probs * head_mask
356
+
357
+ context_layer = torch.matmul(attention_probs, value_layer)
358
+
359
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
360
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
361
+ context_layer = context_layer.view(new_context_layer_shape)
362
+
363
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
364
+
365
+ if self.is_decoder:
366
+ outputs = outputs + (past_key_value,)
367
+ return outputs
368
+
369
+
370
+ class BertSelfOutput(nn.Module):
371
+ def __init__(self, config):
372
+ super().__init__()
373
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
374
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
375
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
376
+
377
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
378
+ hidden_states = self.dense(hidden_states)
379
+ hidden_states = self.dropout(hidden_states)
380
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
381
+ return hidden_states
382
+
383
+
384
+ class BertAttention(nn.Module):
385
+ def __init__(self, config, position_embedding_type=None):
386
+ super().__init__()
387
+ self.self = BertSelfAttention(config, position_embedding_type=position_embedding_type)
388
+ self.output = BertSelfOutput(config)
389
+ self.pruned_heads = set()
390
+
391
+ def prune_heads(self, heads):
392
+ if len(heads) == 0:
393
+ return
394
+ heads, index = find_pruneable_heads_and_indices(
395
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
396
+ )
397
+
398
+ # Prune linear layers
399
+ self.self.query = prune_linear_layer(self.self.query, index)
400
+ self.self.key = prune_linear_layer(self.self.key, index)
401
+ self.self.value = prune_linear_layer(self.self.value, index)
402
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
403
+
404
+ # Update hyper params and store pruned heads
405
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
406
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
407
+ self.pruned_heads = self.pruned_heads.union(heads)
408
+
409
+ def forward(
410
+ self,
411
+ hidden_states: torch.Tensor,
412
+ attention_mask: Optional[torch.FloatTensor] = None,
413
+ head_mask: Optional[torch.FloatTensor] = None,
414
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
415
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
416
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
417
+ output_attentions: Optional[bool] = False,
418
+ ) -> Tuple[torch.Tensor]:
419
+ self_outputs = self.self(
420
+ hidden_states,
421
+ attention_mask,
422
+ head_mask,
423
+ encoder_hidden_states,
424
+ encoder_attention_mask,
425
+ past_key_value,
426
+ output_attentions,
427
+ )
428
+ attention_output = self.output(self_outputs[0], hidden_states)
429
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
430
+ return outputs
431
+
432
+
433
+ class BertIntermediate(nn.Module):
434
+ def __init__(self, config):
435
+ super().__init__()
436
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
437
+ if isinstance(config.hidden_act, str):
438
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
439
+ else:
440
+ self.intermediate_act_fn = config.hidden_act
441
+
442
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
443
+ hidden_states = self.dense(hidden_states)
444
+ hidden_states = self.intermediate_act_fn(hidden_states)
445
+ return hidden_states
446
+
447
+
448
+ class BertOutput(nn.Module):
449
+ def __init__(self, config):
450
+ super().__init__()
451
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
452
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
453
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
454
+
455
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
456
+ hidden_states = self.dense(hidden_states)
457
+ hidden_states = self.dropout(hidden_states)
458
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
459
+ return hidden_states
460
+
461
+
462
+ class BertLayer(nn.Module):
463
+ def __init__(self, config):
464
+ super().__init__()
465
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
466
+ self.seq_len_dim = 1
467
+ self.attention = BertAttention(config)
468
+ self.is_decoder = config.is_decoder
469
+ self.add_cross_attention = config.add_cross_attention
470
+ if self.add_cross_attention:
471
+ if not self.is_decoder:
472
+ raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
473
+ self.crossattention = BertAttention(config, position_embedding_type="absolute")
474
+ self.intermediate = BertIntermediate(config)
475
+ self.output = BertOutput(config)
476
+
477
+ def forward(
478
+ self,
479
+ hidden_states: torch.Tensor,
480
+ attention_mask: Optional[torch.FloatTensor] = None,
481
+ head_mask: Optional[torch.FloatTensor] = None,
482
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
483
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
484
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
485
+ output_attentions: Optional[bool] = False,
486
+ ) -> Tuple[torch.Tensor]:
487
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
488
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
489
+ self_attention_outputs = self.attention(
490
+ hidden_states,
491
+ attention_mask,
492
+ head_mask,
493
+ output_attentions=output_attentions,
494
+ past_key_value=self_attn_past_key_value,
495
+ )
496
+ attention_output = self_attention_outputs[0]
497
+
498
+ # if decoder, the last output is tuple of self-attn cache
499
+ if self.is_decoder:
500
+ outputs = self_attention_outputs[1:-1]
501
+ present_key_value = self_attention_outputs[-1]
502
+ else:
503
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
504
+
505
+ cross_attn_present_key_value = None
506
+ if self.is_decoder and encoder_hidden_states is not None:
507
+ if not hasattr(self, "crossattention"):
508
+ raise ValueError(
509
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
510
+ " by setting `config.add_cross_attention=True`"
511
+ )
512
+
513
+ # cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
514
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
515
+ cross_attention_outputs = self.crossattention(
516
+ attention_output,
517
+ attention_mask,
518
+ head_mask,
519
+ encoder_hidden_states,
520
+ encoder_attention_mask,
521
+ cross_attn_past_key_value,
522
+ output_attentions,
523
+ )
524
+ attention_output = cross_attention_outputs[0]
525
+ outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
526
+
527
+ # add cross-attn cache to positions 3,4 of present_key_value tuple
528
+ cross_attn_present_key_value = cross_attention_outputs[-1]
529
+ present_key_value = present_key_value + cross_attn_present_key_value
530
+
531
+ layer_output = apply_chunking_to_forward(
532
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
533
+ )
534
+ outputs = (layer_output,) + outputs
535
+
536
+ # if decoder, return the attn key/values as the last output
537
+ if self.is_decoder:
538
+ outputs = outputs + (present_key_value,)
539
+
540
+ return outputs
541
+
542
+ def feed_forward_chunk(self, attention_output):
543
+ intermediate_output = self.intermediate(attention_output)
544
+ layer_output = self.output(intermediate_output, attention_output)
545
+ return layer_output
546
+
547
+
548
+ class BertEncoder(nn.Module):
549
+ def __init__(self, config):
550
+ super().__init__()
551
+ self.config = config
552
+ self.layer = nn.ModuleList([BertLayer(config) for _ in range(config.num_hidden_layers)])
553
+ self.gradient_checkpointing = False
554
+
555
+ def forward(
556
+ self,
557
+ hidden_states: torch.Tensor,
558
+ attention_mask: Optional[torch.FloatTensor] = None,
559
+ head_mask: Optional[torch.FloatTensor] = None,
560
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
561
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
562
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
563
+ use_cache: Optional[bool] = None,
564
+ output_attentions: Optional[bool] = False,
565
+ output_hidden_states: Optional[bool] = False,
566
+ return_dict: Optional[bool] = True,
567
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
568
+ all_hidden_states = () if output_hidden_states else None
569
+ all_self_attentions = () if output_attentions else None
570
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
571
+
572
+ next_decoder_cache = () if use_cache else None
573
+ for i, layer_module in enumerate(self.layer):
574
+ if output_hidden_states:
575
+ all_hidden_states = all_hidden_states + (hidden_states,)
576
+
577
+ layer_head_mask = head_mask[i] if head_mask is not None else None
578
+ past_key_value = past_key_values[i] if past_key_values is not None else None
579
+
580
+ if self.gradient_checkpointing and self.training:
581
+
582
+ if use_cache:
583
+ logger.warning(
584
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
585
+ )
586
+ use_cache = False
587
+
588
+ def create_custom_forward(module):
589
+ def custom_forward(*inputs):
590
+ return module(*inputs, past_key_value, output_attentions)
591
+
592
+ return custom_forward
593
+
594
+ layer_outputs = torch.utils.checkpoint.checkpoint(
595
+ create_custom_forward(layer_module),
596
+ hidden_states,
597
+ attention_mask,
598
+ layer_head_mask,
599
+ encoder_hidden_states,
600
+ encoder_attention_mask,
601
+ )
602
+ else:
603
+ layer_outputs = layer_module(
604
+ hidden_states,
605
+ attention_mask,
606
+ layer_head_mask,
607
+ encoder_hidden_states,
608
+ encoder_attention_mask,
609
+ past_key_value,
610
+ output_attentions,
611
+ )
612
+
613
+ hidden_states = layer_outputs[0]
614
+ if use_cache:
615
+ next_decoder_cache += (layer_outputs[-1],)
616
+ if output_attentions:
617
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
618
+ if self.config.add_cross_attention:
619
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
620
+
621
+ if output_hidden_states:
622
+ all_hidden_states = all_hidden_states + (hidden_states,)
623
+
624
+ if not return_dict:
625
+ return tuple(
626
+ v
627
+ for v in [
628
+ hidden_states,
629
+ next_decoder_cache,
630
+ all_hidden_states,
631
+ all_self_attentions,
632
+ all_cross_attentions,
633
+ ]
634
+ if v is not None
635
+ )
636
+ return BaseModelOutputWithPastAndCrossAttentions(
637
+ last_hidden_state=hidden_states,
638
+ past_key_values=next_decoder_cache,
639
+ hidden_states=all_hidden_states,
640
+ attentions=all_self_attentions,
641
+ cross_attentions=all_cross_attentions,
642
+ )
643
+
644
+
645
+ class BertPooler(nn.Module):
646
+ def __init__(self, config):
647
+ super().__init__()
648
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
649
+ self.activation = nn.Tanh()
650
+
651
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
652
+ # We "pool" the model by simply taking the hidden state corresponding
653
+ # to the first token.
654
+ first_token_tensor = hidden_states[:, 0]
655
+ pooled_output = self.dense(first_token_tensor)
656
+ pooled_output = self.activation(pooled_output)
657
+ return pooled_output
658
+
659
+
660
+ class BertPredictionHeadTransform(nn.Module):
661
+ def __init__(self, config):
662
+ super().__init__()
663
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
664
+ if isinstance(config.hidden_act, str):
665
+ self.transform_act_fn = ACT2FN[config.hidden_act]
666
+ else:
667
+ self.transform_act_fn = config.hidden_act
668
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
669
+
670
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
671
+ hidden_states = self.dense(hidden_states)
672
+ hidden_states = self.transform_act_fn(hidden_states)
673
+ hidden_states = self.LayerNorm(hidden_states)
674
+ return hidden_states
675
+
676
+
677
+ class BertLMPredictionHead(nn.Module):
678
+ def __init__(self, config):
679
+ super().__init__()
680
+ self.transform = BertPredictionHeadTransform(config)
681
+
682
+ # The output weights are the same as the input embeddings, but there is
683
+ # an output-only bias for each token.
684
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
685
+
686
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
687
+
688
+ # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
689
+ self.decoder.bias = self.bias
690
+
691
+ def forward(self, hidden_states):
692
+ hidden_states = self.transform(hidden_states)
693
+ hidden_states = self.decoder(hidden_states)
694
+ return hidden_states
695
+
696
+
697
+ class BertOnlyMLMHead(nn.Module):
698
+ def __init__(self, config):
699
+ super().__init__()
700
+ self.predictions = BertLMPredictionHead(config)
701
+
702
+ def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
703
+ prediction_scores = self.predictions(sequence_output)
704
+ return prediction_scores
705
+
706
+
707
+ class BertOnlyNSPHead(nn.Module):
708
+ def __init__(self, config):
709
+ super().__init__()
710
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
711
+
712
+ def forward(self, pooled_output):
713
+ seq_relationship_score = self.seq_relationship(pooled_output)
714
+ return seq_relationship_score
715
+
716
+
717
+ class BertPreTrainingHeads(nn.Module):
718
+ def __init__(self, config):
719
+ super().__init__()
720
+ self.predictions = BertLMPredictionHead(config)
721
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
722
+
723
+ def forward(self, sequence_output, pooled_output):
724
+ prediction_scores = self.predictions(sequence_output)
725
+ seq_relationship_score = self.seq_relationship(pooled_output)
726
+ return prediction_scores, seq_relationship_score
727
+
728
+
729
+ class BertPreTrainedModel(PreTrainedModel):
730
+ """
731
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
732
+ models.
733
+ """
734
+
735
+ config_class = BertConfig
736
+ load_tf_weights = load_tf_weights_in_bert
737
+ base_model_prefix = "bert"
738
+ supports_gradient_checkpointing = True
739
+ _keys_to_ignore_on_load_missing = [r"position_ids"]
740
+
741
+ def _init_weights(self, module):
742
+ """Initialize the weights"""
743
+ if isinstance(module, nn.Linear):
744
+ # Slightly different from the TF version which uses truncated_normal for initialization
745
+ # cf https://github.com/pytorch/pytorch/pull/5617
746
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
747
+ if module.bias is not None:
748
+ module.bias.data.zero_()
749
+ elif isinstance(module, nn.Embedding):
750
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
751
+ if module.padding_idx is not None:
752
+ module.weight.data[module.padding_idx].zero_()
753
+ elif isinstance(module, nn.LayerNorm):
754
+ module.bias.data.zero_()
755
+ module.weight.data.fill_(1.0)
756
+
757
+ def _set_gradient_checkpointing(self, module, value=False):
758
+ if isinstance(module, BertEncoder):
759
+ module.gradient_checkpointing = value
760
+
761
+
762
+ @dataclass
763
+ class BertForPreTrainingOutput(ModelOutput):
764
+ """
765
+ Output type of [`BertForPreTraining`].
766
+
767
+ Args:
768
+ loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
769
+ Total loss as the sum of the masked language modeling loss and the next sequence prediction
770
+ (classification) loss.
771
+ prediction_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
772
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
773
+ seq_relationship_logits (`torch.FloatTensor` of shape `(batch_size, 2)`):
774
+ Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
775
+ before SoftMax).
776
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
777
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
778
+ shape `(batch_size, sequence_length, hidden_size)`.
779
+
780
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
781
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
782
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
783
+ sequence_length)`.
784
+
785
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
786
+ heads.
787
+ """
788
+
789
+ loss: Optional[torch.FloatTensor] = None
790
+ prediction_logits: torch.FloatTensor = None
791
+ seq_relationship_logits: torch.FloatTensor = None
792
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
793
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
794
+
795
+
796
+ BERT_START_DOCSTRING = r"""
797
+
798
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
799
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
800
+ etc.)
801
+
802
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
803
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
804
+ and behavior.
805
+
806
+ Parameters:
807
+ config ([`BertConfig`]): Model configuration class with all the parameters of the model.
808
+ Initializing with a config file does not load the weights associated with the model, only the
809
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
810
+ """
811
+
812
+ BERT_INPUTS_DOCSTRING = r"""
813
+ Args:
814
+ input_ids (`torch.LongTensor` of shape `({0})`):
815
+ Indices of input sequence tokens in the vocabulary.
816
+
817
+ Indices can be obtained using [`BertTokenizer`]. See [`PreTrainedTokenizer.encode`] and
818
+ [`PreTrainedTokenizer.__call__`] for details.
819
+
820
+ [What are input IDs?](../glossary#input-ids)
821
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
822
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
823
+
824
+ - 1 for tokens that are **not masked**,
825
+ - 0 for tokens that are **masked**.
826
+
827
+ [What are attention masks?](../glossary#attention-mask)
828
+ token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
829
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
830
+ 1]`:
831
+
832
+ - 0 corresponds to a *sentence A* token,
833
+ - 1 corresponds to a *sentence B* token.
834
+
835
+ [What are token type IDs?](../glossary#token-type-ids)
836
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
837
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
838
+ config.max_position_embeddings - 1]`.
839
+
840
+ [What are position IDs?](../glossary#position-ids)
841
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
842
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
843
+
844
+ - 1 indicates the head is **not masked**,
845
+ - 0 indicates the head is **masked**.
846
+
847
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
848
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
849
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
850
+ model's internal embedding lookup matrix.
851
+ output_attentions (`bool`, *optional*):
852
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
853
+ tensors for more detail.
854
+ output_hidden_states (`bool`, *optional*):
855
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
856
+ more detail.
857
+ return_dict (`bool`, *optional*):
858
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
859
+ """
860
+
861
+
862
+ @add_start_docstrings(
863
+ "The bare Bert Model transformer outputting raw hidden-states without any specific head on top.",
864
+ BERT_START_DOCSTRING,
865
+ )
866
+ class BertModel(BertPreTrainedModel):
867
+ """
868
+
869
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
870
+ cross-attention is added between the self-attention layers, following the architecture described in [Attention is
871
+ all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
872
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
873
+
874
+ To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
875
+ to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
876
+ `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
877
+ """
878
+
879
+ def __init__(self, config, add_pooling_layer=True):
880
+ super().__init__(config)
881
+ self.config = config
882
+
883
+ self.embeddings = BertEmbeddings(config)
884
+ self.encoder = BertEncoder(config)
885
+
886
+ self.pooler = BertPooler(config) if add_pooling_layer else None
887
+
888
+ # Initialize weights and apply final processing
889
+ self.post_init()
890
+
891
+ def get_input_embeddings(self):
892
+ return self.embeddings.word_embeddings
893
+
894
+ def set_input_embeddings(self, value):
895
+ self.embeddings.word_embeddings = value
896
+
897
+ def _prune_heads(self, heads_to_prune):
898
+ """
899
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
900
+ class PreTrainedModel
901
+ """
902
+ for layer, heads in heads_to_prune.items():
903
+ self.encoder.layer[layer].attention.prune_heads(heads)
904
+
905
+ @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
906
+ @add_code_sample_docstrings(
907
+ processor_class=_TOKENIZER_FOR_DOC,
908
+ checkpoint=_CHECKPOINT_FOR_DOC,
909
+ output_type=BaseModelOutputWithPoolingAndCrossAttentions,
910
+ config_class=_CONFIG_FOR_DOC,
911
+ )
912
+ def forward(
913
+ self,
914
+ input_ids: Optional[torch.Tensor] = None,
915
+ attention_mask: Optional[torch.Tensor] = None,
916
+ token_type_ids: Optional[torch.Tensor] = None,
917
+ position_ids: Optional[torch.Tensor] = None,
918
+ head_mask: Optional[torch.Tensor] = None,
919
+ inputs_embeds: Optional[torch.Tensor] = None,
920
+ encoder_hidden_states: Optional[torch.Tensor] = None,
921
+ encoder_attention_mask: Optional[torch.Tensor] = None,
922
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
923
+ use_cache: Optional[bool] = None,
924
+ output_attentions: Optional[bool] = None,
925
+ output_hidden_states: Optional[bool] = None,
926
+ return_dict: Optional[bool] = None,
927
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
928
+ r"""
929
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
930
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
931
+ the model is configured as a decoder.
932
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
933
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
934
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
935
+
936
+ - 1 for tokens that are **not masked**,
937
+ - 0 for tokens that are **masked**.
938
+ past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
939
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
940
+
941
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
942
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
943
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
944
+ use_cache (`bool`, *optional*):
945
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
946
+ `past_key_values`).
947
+ """
948
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
949
+ output_hidden_states = (
950
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
951
+ )
952
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
953
+
954
+ if self.config.is_decoder:
955
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
956
+ else:
957
+ use_cache = False
958
+
959
+ if input_ids is not None and inputs_embeds is not None:
960
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
961
+ elif input_ids is not None:
962
+ input_shape = input_ids.size()
963
+ elif inputs_embeds is not None:
964
+ input_shape = inputs_embeds.size()[:-1]
965
+ else:
966
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
967
+
968
+ batch_size, seq_length = input_shape
969
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
970
+
971
+ # past_key_values_length
972
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
973
+
974
+ if attention_mask is None:
975
+ attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
976
+
977
+ if token_type_ids is None:
978
+ if hasattr(self.embeddings, "token_type_ids"):
979
+ buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
980
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
981
+ token_type_ids = buffered_token_type_ids_expanded
982
+ else:
983
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
984
+
985
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
986
+ # ourselves in which case we just need to make it broadcastable to all heads.
987
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
988
+
989
+ # If a 2D or 3D attention mask is provided for the cross-attention
990
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
991
+ if self.config.is_decoder and encoder_hidden_states is not None:
992
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
993
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
994
+ if encoder_attention_mask is None:
995
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
996
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
997
+ else:
998
+ encoder_extended_attention_mask = None
999
+
1000
+ # Prepare head mask if needed
1001
+ # 1.0 in head_mask indicate we keep the head
1002
+ # attention_probs has shape bsz x n_heads x N x N
1003
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
1004
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
1005
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
1006
+
1007
+ embedding_output = self.embeddings(
1008
+ input_ids=input_ids,
1009
+ position_ids=position_ids,
1010
+ token_type_ids=token_type_ids,
1011
+ inputs_embeds=inputs_embeds,
1012
+ past_key_values_length=past_key_values_length,
1013
+ )
1014
+ encoder_outputs = self.encoder(
1015
+ embedding_output,
1016
+ attention_mask=extended_attention_mask,
1017
+ head_mask=head_mask,
1018
+ encoder_hidden_states=encoder_hidden_states,
1019
+ encoder_attention_mask=encoder_extended_attention_mask,
1020
+ past_key_values=past_key_values,
1021
+ use_cache=use_cache,
1022
+ output_attentions=output_attentions,
1023
+ output_hidden_states=output_hidden_states,
1024
+ return_dict=return_dict,
1025
+ )
1026
+ sequence_output = encoder_outputs[0]
1027
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
1028
+
1029
+ if not return_dict:
1030
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
1031
+
1032
+ return BaseModelOutputWithPoolingAndCrossAttentions(
1033
+ last_hidden_state=sequence_output,
1034
+ pooler_output=pooled_output,
1035
+ past_key_values=encoder_outputs.past_key_values,
1036
+ hidden_states=encoder_outputs.hidden_states,
1037
+ attentions=encoder_outputs.attentions,
1038
+ cross_attentions=encoder_outputs.cross_attentions,
1039
+ )
1040
+
1041
+
1042
+ @add_start_docstrings(
1043
+ """
1044
+ Bert Model with two heads on top as done during the pretraining: a `masked language modeling` head and a `next
1045
+ sentence prediction (classification)` head.
1046
+ """,
1047
+ BERT_START_DOCSTRING,
1048
+ )
1049
+ class BertForPreTraining(BertPreTrainedModel):
1050
+ def __init__(self, config):
1051
+ super().__init__(config)
1052
+
1053
+ self.bert = BertModel(config)
1054
+ self.cls = BertPreTrainingHeads(config)
1055
+
1056
+ # Initialize weights and apply final processing
1057
+ self.post_init()
1058
+
1059
+ def get_output_embeddings(self):
1060
+ return self.cls.predictions.decoder
1061
+
1062
+ def set_output_embeddings(self, new_embeddings):
1063
+ self.cls.predictions.decoder = new_embeddings
1064
+
1065
+ @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1066
+ @replace_return_docstrings(output_type=BertForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
1067
+ def forward(
1068
+ self,
1069
+ input_ids: Optional[torch.Tensor] = None,
1070
+ attention_mask: Optional[torch.Tensor] = None,
1071
+ token_type_ids: Optional[torch.Tensor] = None,
1072
+ position_ids: Optional[torch.Tensor] = None,
1073
+ head_mask: Optional[torch.Tensor] = None,
1074
+ inputs_embeds: Optional[torch.Tensor] = None,
1075
+ labels: Optional[torch.Tensor] = None,
1076
+ next_sentence_label: Optional[torch.Tensor] = None,
1077
+ output_attentions: Optional[bool] = None,
1078
+ output_hidden_states: Optional[bool] = None,
1079
+ return_dict: Optional[bool] = None,
1080
+ ) -> Union[Tuple[torch.Tensor], BertForPreTrainingOutput]:
1081
+ r"""
1082
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1083
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
1084
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked),
1085
+ the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1086
+ next_sentence_label (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1087
+ Labels for computing the next sequence prediction (classification) loss. Input should be a sequence
1088
+ pair (see `input_ids` docstring) Indices should be in `[0, 1]`:
1089
+
1090
+ - 0 indicates sequence B is a continuation of sequence A,
1091
+ - 1 indicates sequence B is a random sequence.
1092
+ kwargs (`Dict[str, any]`, optional, defaults to *{}*):
1093
+ Used to hide legacy arguments that have been deprecated.
1094
+
1095
+ Returns:
1096
+
1097
+ Example:
1098
+
1099
+ ```python
1100
+ >>> from transformers import BertTokenizer, BertForPreTraining
1101
+ >>> import torch
1102
+
1103
+ >>> tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
1104
+ >>> model = BertForPreTraining.from_pretrained("bert-base-uncased")
1105
+
1106
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
1107
+ >>> outputs = model(**inputs)
1108
+
1109
+ >>> prediction_logits = outputs.prediction_logits
1110
+ >>> seq_relationship_logits = outputs.seq_relationship_logits
1111
+ ```
1112
+ """
1113
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1114
+
1115
+ outputs = self.bert(
1116
+ input_ids,
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
+ output_attentions=output_attentions,
1123
+ output_hidden_states=output_hidden_states,
1124
+ return_dict=return_dict,
1125
+ )
1126
+
1127
+ sequence_output, pooled_output = outputs[:2]
1128
+ prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)
1129
+
1130
+ total_loss = None
1131
+ if labels is not None and next_sentence_label is not None:
1132
+ loss_fct = CrossEntropyLoss()
1133
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
1134
+ next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))
1135
+ total_loss = masked_lm_loss + next_sentence_loss
1136
+
1137
+ if not return_dict:
1138
+ output = (prediction_scores, seq_relationship_score) + outputs[2:]
1139
+ return ((total_loss,) + output) if total_loss is not None else output
1140
+
1141
+ return BertForPreTrainingOutput(
1142
+ loss=total_loss,
1143
+ prediction_logits=prediction_scores,
1144
+ seq_relationship_logits=seq_relationship_score,
1145
+ hidden_states=outputs.hidden_states,
1146
+ attentions=outputs.attentions,
1147
+ )
1148
+
1149
+
1150
+ @add_start_docstrings(
1151
+ """Bert Model with a `language modeling` head on top for CLM fine-tuning.""", BERT_START_DOCSTRING
1152
+ )
1153
+ class BertLMHeadModel(BertPreTrainedModel):
1154
+
1155
+ _keys_to_ignore_on_load_unexpected = [r"pooler"]
1156
+ _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"]
1157
+
1158
+ def __init__(self, config):
1159
+ super().__init__(config)
1160
+
1161
+ if not config.is_decoder:
1162
+ logger.warning("If you want to use `BertLMHeadModel` as a standalone, add `is_decoder=True.`")
1163
+
1164
+ self.bert = BertModel(config, add_pooling_layer=False)
1165
+ self.cls = BertOnlyMLMHead(config)
1166
+
1167
+ # Initialize weights and apply final processing
1168
+ self.post_init()
1169
+
1170
+ def get_output_embeddings(self):
1171
+ return self.cls.predictions.decoder
1172
+
1173
+ def set_output_embeddings(self, new_embeddings):
1174
+ self.cls.predictions.decoder = new_embeddings
1175
+
1176
+ @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1177
+ @add_code_sample_docstrings(
1178
+ processor_class=_TOKENIZER_FOR_DOC,
1179
+ checkpoint=_CHECKPOINT_FOR_DOC,
1180
+ output_type=CausalLMOutputWithCrossAttentions,
1181
+ config_class=_CONFIG_FOR_DOC,
1182
+ )
1183
+ def forward(
1184
+ self,
1185
+ input_ids: Optional[torch.Tensor] = None,
1186
+ attention_mask: Optional[torch.Tensor] = None,
1187
+ token_type_ids: Optional[torch.Tensor] = None,
1188
+ position_ids: Optional[torch.Tensor] = None,
1189
+ head_mask: Optional[torch.Tensor] = None,
1190
+ inputs_embeds: Optional[torch.Tensor] = None,
1191
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1192
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1193
+ labels: Optional[torch.Tensor] = None,
1194
+ past_key_values: Optional[List[torch.Tensor]] = None,
1195
+ use_cache: Optional[bool] = None,
1196
+ output_attentions: Optional[bool] = None,
1197
+ output_hidden_states: Optional[bool] = None,
1198
+ return_dict: Optional[bool] = None,
1199
+ ) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
1200
+ r"""
1201
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1202
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
1203
+ the model is configured as a decoder.
1204
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
1205
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
1206
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
1207
+
1208
+ - 1 for tokens that are **not masked**,
1209
+ - 0 for tokens that are **masked**.
1210
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1211
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
1212
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
1213
+ ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`
1214
+ past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
1215
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
1216
+
1217
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
1218
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
1219
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1220
+ use_cache (`bool`, *optional*):
1221
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1222
+ `past_key_values`).
1223
+ """
1224
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1225
+ if labels is not None:
1226
+ use_cache = False
1227
+
1228
+ outputs = self.bert(
1229
+ input_ids,
1230
+ attention_mask=attention_mask,
1231
+ token_type_ids=token_type_ids,
1232
+ position_ids=position_ids,
1233
+ head_mask=head_mask,
1234
+ inputs_embeds=inputs_embeds,
1235
+ encoder_hidden_states=encoder_hidden_states,
1236
+ encoder_attention_mask=encoder_attention_mask,
1237
+ past_key_values=past_key_values,
1238
+ use_cache=use_cache,
1239
+ output_attentions=output_attentions,
1240
+ output_hidden_states=output_hidden_states,
1241
+ return_dict=return_dict,
1242
+ )
1243
+
1244
+ sequence_output = outputs[0]
1245
+ prediction_scores = self.cls(sequence_output)
1246
+
1247
+ lm_loss = None
1248
+ if labels is not None:
1249
+ # we are doing next-token prediction; shift prediction scores and input ids by one
1250
+ shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()
1251
+ labels = labels[:, 1:].contiguous()
1252
+ loss_fct = CrossEntropyLoss()
1253
+ lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
1254
+
1255
+ if not return_dict:
1256
+ output = (prediction_scores,) + outputs[2:]
1257
+ return ((lm_loss,) + output) if lm_loss is not None else output
1258
+
1259
+ return CausalLMOutputWithCrossAttentions(
1260
+ loss=lm_loss,
1261
+ logits=prediction_scores,
1262
+ past_key_values=outputs.past_key_values,
1263
+ hidden_states=outputs.hidden_states,
1264
+ attentions=outputs.attentions,
1265
+ cross_attentions=outputs.cross_attentions,
1266
+ )
1267
+
1268
+ def prepare_inputs_for_generation(self, input_ids, past=None, attention_mask=None, **model_kwargs):
1269
+ input_shape = input_ids.shape
1270
+ # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
1271
+ if attention_mask is None:
1272
+ attention_mask = input_ids.new_ones(input_shape)
1273
+
1274
+ # cut decoder_input_ids if past is used
1275
+ if past is not None:
1276
+ input_ids = input_ids[:, -1:]
1277
+
1278
+ return {"input_ids": input_ids, "attention_mask": attention_mask, "past_key_values": past}
1279
+
1280
+ def _reorder_cache(self, past, beam_idx):
1281
+ reordered_past = ()
1282
+ for layer_past in past:
1283
+ reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
1284
+ return reordered_past
1285
+
1286
+
1287
+ @add_start_docstrings("""Bert Model with a `language modeling` head on top.""", BERT_START_DOCSTRING)
1288
+ class BertForMaskedLM(BertPreTrainedModel):
1289
+
1290
+ _keys_to_ignore_on_load_unexpected = [r"pooler"]
1291
+ _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"]
1292
+
1293
+ def __init__(self, config):
1294
+ super().__init__(config)
1295
+
1296
+ if config.is_decoder:
1297
+ logger.warning(
1298
+ "If you want to use `BertForMaskedLM` make sure `config.is_decoder=False` for "
1299
+ "bi-directional self-attention."
1300
+ )
1301
+
1302
+ self.bert = BertModel(config, add_pooling_layer=False)
1303
+ self.cls = BertOnlyMLMHead(config)
1304
+
1305
+ # Initialize weights and apply final processing
1306
+ self.post_init()
1307
+
1308
+ def get_output_embeddings(self):
1309
+ return self.cls.predictions.decoder
1310
+
1311
+ def set_output_embeddings(self, new_embeddings):
1312
+ self.cls.predictions.decoder = new_embeddings
1313
+
1314
+ @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1315
+ @add_code_sample_docstrings(
1316
+ processor_class=_TOKENIZER_FOR_DOC,
1317
+ checkpoint=_CHECKPOINT_FOR_DOC,
1318
+ output_type=MaskedLMOutput,
1319
+ config_class=_CONFIG_FOR_DOC,
1320
+ expected_output="'paris'",
1321
+ expected_loss=0.88,
1322
+ )
1323
+ def forward(
1324
+ self,
1325
+ input_ids: Optional[torch.Tensor] = None,
1326
+ attention_mask: Optional[torch.Tensor] = None,
1327
+ token_type_ids: Optional[torch.Tensor] = None,
1328
+ position_ids: Optional[torch.Tensor] = None,
1329
+ head_mask: Optional[torch.Tensor] = None,
1330
+ inputs_embeds: Optional[torch.Tensor] = None,
1331
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1332
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1333
+ labels: Optional[torch.Tensor] = None,
1334
+ output_attentions: Optional[bool] = None,
1335
+ output_hidden_states: Optional[bool] = None,
1336
+ return_dict: Optional[bool] = None,
1337
+ ) -> Union[Tuple[torch.Tensor], MaskedLMOutput]:
1338
+ r"""
1339
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1340
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
1341
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
1342
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1343
+ """
1344
+
1345
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1346
+
1347
+ outputs = self.bert(
1348
+ input_ids,
1349
+ attention_mask=attention_mask,
1350
+ token_type_ids=token_type_ids,
1351
+ position_ids=position_ids,
1352
+ head_mask=head_mask,
1353
+ inputs_embeds=inputs_embeds,
1354
+ encoder_hidden_states=encoder_hidden_states,
1355
+ encoder_attention_mask=encoder_attention_mask,
1356
+ output_attentions=output_attentions,
1357
+ output_hidden_states=output_hidden_states,
1358
+ return_dict=return_dict,
1359
+ )
1360
+
1361
+ sequence_output = outputs[0]
1362
+ prediction_scores = self.cls(sequence_output)
1363
+
1364
+ masked_lm_loss = None
1365
+ if labels is not None:
1366
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
1367
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
1368
+
1369
+ if not return_dict:
1370
+ output = (prediction_scores,) + outputs[2:]
1371
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1372
+
1373
+ return MaskedLMOutput(
1374
+ loss=masked_lm_loss,
1375
+ logits=prediction_scores,
1376
+ hidden_states=outputs.hidden_states,
1377
+ attentions=outputs.attentions,
1378
+ )
1379
+
1380
+ def prepare_inputs_for_generation(self, input_ids, attention_mask=None, **model_kwargs):
1381
+ input_shape = input_ids.shape
1382
+ effective_batch_size = input_shape[0]
1383
+
1384
+ # add a dummy token
1385
+ if self.config.pad_token_id is None:
1386
+ raise ValueError("The PAD token should be defined for generation")
1387
+
1388
+ attention_mask = torch.cat([attention_mask, attention_mask.new_zeros((attention_mask.shape[0], 1))], dim=-1)
1389
+ dummy_token = torch.full(
1390
+ (effective_batch_size, 1), self.config.pad_token_id, dtype=torch.long, device=input_ids.device
1391
+ )
1392
+ input_ids = torch.cat([input_ids, dummy_token], dim=1)
1393
+
1394
+ return {"input_ids": input_ids, "attention_mask": attention_mask}
1395
+
1396
+
1397
+ @add_start_docstrings(
1398
+ """Bert Model with a `next sentence prediction (classification)` head on top.""",
1399
+ BERT_START_DOCSTRING,
1400
+ )
1401
+ class BertForNextSentencePrediction(BertPreTrainedModel):
1402
+ def __init__(self, config):
1403
+ super().__init__(config)
1404
+
1405
+ self.bert = BertModel(config)
1406
+ self.cls = BertOnlyNSPHead(config)
1407
+
1408
+ # Initialize weights and apply final processing
1409
+ self.post_init()
1410
+
1411
+ @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1412
+ @replace_return_docstrings(output_type=NextSentencePredictorOutput, config_class=_CONFIG_FOR_DOC)
1413
+ def forward(
1414
+ self,
1415
+ input_ids: Optional[torch.Tensor] = None,
1416
+ attention_mask: Optional[torch.Tensor] = None,
1417
+ token_type_ids: Optional[torch.Tensor] = None,
1418
+ position_ids: Optional[torch.Tensor] = None,
1419
+ head_mask: Optional[torch.Tensor] = None,
1420
+ inputs_embeds: Optional[torch.Tensor] = None,
1421
+ labels: Optional[torch.Tensor] = None,
1422
+ output_attentions: Optional[bool] = None,
1423
+ output_hidden_states: Optional[bool] = None,
1424
+ return_dict: Optional[bool] = None,
1425
+ **kwargs,
1426
+ ) -> Union[Tuple[torch.Tensor], NextSentencePredictorOutput]:
1427
+ r"""
1428
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1429
+ Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
1430
+ (see `input_ids` docstring). Indices should be in `[0, 1]`:
1431
+
1432
+ - 0 indicates sequence B is a continuation of sequence A,
1433
+ - 1 indicates sequence B is a random sequence.
1434
+
1435
+ Returns:
1436
+
1437
+ Example:
1438
+
1439
+ ```python
1440
+ >>> from transformers import BertTokenizer, BertForNextSentencePrediction
1441
+ >>> import torch
1442
+
1443
+ >>> tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
1444
+ >>> model = BertForNextSentencePrediction.from_pretrained("bert-base-uncased")
1445
+
1446
+ >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
1447
+ >>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
1448
+ >>> encoding = tokenizer(prompt, next_sentence, return_tensors="pt")
1449
+
1450
+ >>> outputs = model(**encoding, labels=torch.LongTensor([1]))
1451
+ >>> logits = outputs.logits
1452
+ >>> assert logits[0, 0] < logits[0, 1] # next sentence was random
1453
+ ```
1454
+ """
1455
+
1456
+ if "next_sentence_label" in kwargs:
1457
+ warnings.warn(
1458
+ "The `next_sentence_label` argument is deprecated and will be removed in a future version, use"
1459
+ " `labels` instead.",
1460
+ FutureWarning,
1461
+ )
1462
+ labels = kwargs.pop("next_sentence_label")
1463
+
1464
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1465
+
1466
+ outputs = self.bert(
1467
+ input_ids,
1468
+ attention_mask=attention_mask,
1469
+ token_type_ids=token_type_ids,
1470
+ position_ids=position_ids,
1471
+ head_mask=head_mask,
1472
+ inputs_embeds=inputs_embeds,
1473
+ output_attentions=output_attentions,
1474
+ output_hidden_states=output_hidden_states,
1475
+ return_dict=return_dict,
1476
+ )
1477
+
1478
+ pooled_output = outputs[1]
1479
+
1480
+ seq_relationship_scores = self.cls(pooled_output)
1481
+
1482
+ next_sentence_loss = None
1483
+ if labels is not None:
1484
+ loss_fct = CrossEntropyLoss()
1485
+ next_sentence_loss = loss_fct(seq_relationship_scores.view(-1, 2), labels.view(-1))
1486
+
1487
+ if not return_dict:
1488
+ output = (seq_relationship_scores,) + outputs[2:]
1489
+ return ((next_sentence_loss,) + output) if next_sentence_loss is not None else output
1490
+
1491
+ return NextSentencePredictorOutput(
1492
+ loss=next_sentence_loss,
1493
+ logits=seq_relationship_scores,
1494
+ hidden_states=outputs.hidden_states,
1495
+ attentions=outputs.attentions,
1496
+ )
1497
+
1498
+
1499
+ @add_start_docstrings(
1500
+ """
1501
+ Bert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
1502
+ output) e.g. for GLUE tasks.
1503
+ """,
1504
+ BERT_START_DOCSTRING,
1505
+ )
1506
+ class BertForSequenceClassification(BertPreTrainedModel):
1507
+ def __init__(self, config):
1508
+ super().__init__(config)
1509
+ self.num_labels = config.num_labels
1510
+ self.config = config
1511
+
1512
+ self.bert = BertModel(config)
1513
+ classifier_dropout = (
1514
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1515
+ )
1516
+ self.dropout = nn.Dropout(classifier_dropout)
1517
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1518
+
1519
+ # Initialize weights and apply final processing
1520
+ self.post_init()
1521
+
1522
+ @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1523
+ @add_code_sample_docstrings(
1524
+ processor_class=_TOKENIZER_FOR_DOC,
1525
+ checkpoint=_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION,
1526
+ output_type=SequenceClassifierOutput,
1527
+ config_class=_CONFIG_FOR_DOC,
1528
+ expected_output=_SEQ_CLASS_EXPECTED_OUTPUT,
1529
+ expected_loss=_SEQ_CLASS_EXPECTED_LOSS,
1530
+ )
1531
+ def forward(
1532
+ self,
1533
+ input_ids: Optional[torch.Tensor] = None,
1534
+ attention_mask: Optional[torch.Tensor] = None,
1535
+ token_type_ids: Optional[torch.Tensor] = None,
1536
+ position_ids: Optional[torch.Tensor] = None,
1537
+ head_mask: Optional[torch.Tensor] = None,
1538
+ inputs_embeds: Optional[torch.Tensor] = None,
1539
+ labels: Optional[torch.Tensor] = None,
1540
+ output_attentions: Optional[bool] = None,
1541
+ output_hidden_states: Optional[bool] = None,
1542
+ return_dict: Optional[bool] = None,
1543
+ ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
1544
+ r"""
1545
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1546
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1547
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1548
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1549
+ """
1550
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1551
+
1552
+ outputs = self.bert(
1553
+ input_ids,
1554
+ attention_mask=attention_mask,
1555
+ token_type_ids=token_type_ids,
1556
+ position_ids=position_ids,
1557
+ head_mask=head_mask,
1558
+ inputs_embeds=inputs_embeds,
1559
+ output_attentions=output_attentions,
1560
+ output_hidden_states=output_hidden_states,
1561
+ return_dict=return_dict,
1562
+ )
1563
+
1564
+ pooled_output = outputs[1]
1565
+
1566
+ pooled_output = self.dropout(pooled_output)
1567
+ logits = self.classifier(pooled_output)
1568
+
1569
+ loss = None
1570
+ if labels is not None:
1571
+ if self.config.problem_type is None:
1572
+ if self.num_labels == 1:
1573
+ self.config.problem_type = "regression"
1574
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1575
+ self.config.problem_type = "single_label_classification"
1576
+ else:
1577
+ self.config.problem_type = "multi_label_classification"
1578
+
1579
+ if self.config.problem_type == "regression":
1580
+ loss_fct = MSELoss()
1581
+ if self.num_labels == 1:
1582
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1583
+ else:
1584
+ loss = loss_fct(logits, labels)
1585
+ elif self.config.problem_type == "single_label_classification":
1586
+ loss_fct = CrossEntropyLoss()
1587
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1588
+ elif self.config.problem_type == "multi_label_classification":
1589
+ loss_fct = BCEWithLogitsLoss()
1590
+ loss = loss_fct(logits, labels)
1591
+ if not return_dict:
1592
+ output = (logits,) + outputs[2:]
1593
+ return ((loss,) + output) if loss is not None else output
1594
+
1595
+ return SequenceClassifierOutput(
1596
+ loss=loss,
1597
+ logits=logits,
1598
+ hidden_states=outputs.hidden_states,
1599
+ attentions=outputs.attentions,
1600
+ )
1601
+
1602
+
1603
+ @add_start_docstrings(
1604
+ """
1605
+ Bert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
1606
+ softmax) e.g. for RocStories/SWAG tasks.
1607
+ """,
1608
+ BERT_START_DOCSTRING,
1609
+ )
1610
+ class BertForMultipleChoice(BertPreTrainedModel):
1611
+ def __init__(self, config):
1612
+ super().__init__(config)
1613
+
1614
+ self.bert = BertModel(config)
1615
+ classifier_dropout = (
1616
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1617
+ )
1618
+ self.dropout = nn.Dropout(classifier_dropout)
1619
+ self.classifier = nn.Linear(config.hidden_size, 1)
1620
+
1621
+ # Initialize weights and apply final processing
1622
+ self.post_init()
1623
+
1624
+ @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
1625
+ @add_code_sample_docstrings(
1626
+ processor_class=_TOKENIZER_FOR_DOC,
1627
+ checkpoint=_CHECKPOINT_FOR_DOC,
1628
+ output_type=MultipleChoiceModelOutput,
1629
+ config_class=_CONFIG_FOR_DOC,
1630
+ )
1631
+ def forward(
1632
+ self,
1633
+ input_ids: Optional[torch.Tensor] = None,
1634
+ attention_mask: Optional[torch.Tensor] = None,
1635
+ token_type_ids: Optional[torch.Tensor] = None,
1636
+ position_ids: Optional[torch.Tensor] = None,
1637
+ head_mask: Optional[torch.Tensor] = None,
1638
+ inputs_embeds: Optional[torch.Tensor] = None,
1639
+ labels: Optional[torch.Tensor] = None,
1640
+ output_attentions: Optional[bool] = None,
1641
+ output_hidden_states: Optional[bool] = None,
1642
+ return_dict: Optional[bool] = None,
1643
+ ) -> Union[Tuple[torch.Tensor], MultipleChoiceModelOutput]:
1644
+ r"""
1645
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1646
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
1647
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
1648
+ `input_ids` above)
1649
+ """
1650
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1651
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
1652
+
1653
+ input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
1654
+ attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
1655
+ token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
1656
+ position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
1657
+ inputs_embeds = (
1658
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
1659
+ if inputs_embeds is not None
1660
+ else None
1661
+ )
1662
+
1663
+ outputs = self.bert(
1664
+ input_ids,
1665
+ attention_mask=attention_mask,
1666
+ token_type_ids=token_type_ids,
1667
+ position_ids=position_ids,
1668
+ head_mask=head_mask,
1669
+ inputs_embeds=inputs_embeds,
1670
+ output_attentions=output_attentions,
1671
+ output_hidden_states=output_hidden_states,
1672
+ return_dict=return_dict,
1673
+ )
1674
+
1675
+ pooled_output = outputs[1]
1676
+
1677
+ pooled_output = self.dropout(pooled_output)
1678
+ logits = self.classifier(pooled_output)
1679
+ reshaped_logits = logits.view(-1, num_choices)
1680
+
1681
+ loss = None
1682
+ if labels is not None:
1683
+ loss_fct = CrossEntropyLoss()
1684
+ loss = loss_fct(reshaped_logits, labels)
1685
+
1686
+ if not return_dict:
1687
+ output = (reshaped_logits,) + outputs[2:]
1688
+ return ((loss,) + output) if loss is not None else output
1689
+
1690
+ return MultipleChoiceModelOutput(
1691
+ loss=loss,
1692
+ logits=reshaped_logits,
1693
+ hidden_states=outputs.hidden_states,
1694
+ attentions=outputs.attentions,
1695
+ )
1696
+
1697
+
1698
+ @add_start_docstrings(
1699
+ """
1700
+ Bert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1701
+ Named-Entity-Recognition (NER) tasks.
1702
+ """,
1703
+ BERT_START_DOCSTRING,
1704
+ )
1705
+ class BertForTokenClassification(BertPreTrainedModel):
1706
+
1707
+ _keys_to_ignore_on_load_unexpected = [r"pooler"]
1708
+
1709
+ def __init__(self, config):
1710
+ super().__init__(config)
1711
+ self.num_labels = config.num_labels
1712
+
1713
+ self.bert = BertModel(config, add_pooling_layer=False)
1714
+ classifier_dropout = (
1715
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1716
+ )
1717
+ self.dropout = nn.Dropout(classifier_dropout)
1718
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1719
+
1720
+ # Initialize weights and apply final processing
1721
+ self.post_init()
1722
+
1723
+ @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1724
+ @add_code_sample_docstrings(
1725
+ processor_class=_TOKENIZER_FOR_DOC,
1726
+ checkpoint=_CHECKPOINT_FOR_TOKEN_CLASSIFICATION,
1727
+ output_type=TokenClassifierOutput,
1728
+ config_class=_CONFIG_FOR_DOC,
1729
+ expected_output=_TOKEN_CLASS_EXPECTED_OUTPUT,
1730
+ expected_loss=_TOKEN_CLASS_EXPECTED_LOSS,
1731
+ )
1732
+ def forward(
1733
+ self,
1734
+ input_ids: Optional[torch.Tensor] = None,
1735
+ attention_mask: Optional[torch.Tensor] = None,
1736
+ token_type_ids: Optional[torch.Tensor] = None,
1737
+ position_ids: Optional[torch.Tensor] = None,
1738
+ head_mask: Optional[torch.Tensor] = None,
1739
+ inputs_embeds: Optional[torch.Tensor] = None,
1740
+ labels: Optional[torch.Tensor] = None,
1741
+ output_attentions: Optional[bool] = None,
1742
+ output_hidden_states: Optional[bool] = None,
1743
+ return_dict: Optional[bool] = None,
1744
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
1745
+ r"""
1746
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1747
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1748
+ """
1749
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1750
+
1751
+ outputs = self.bert(
1752
+ input_ids,
1753
+ attention_mask=attention_mask,
1754
+ token_type_ids=token_type_ids,
1755
+ position_ids=position_ids,
1756
+ head_mask=head_mask,
1757
+ inputs_embeds=inputs_embeds,
1758
+ output_attentions=output_attentions,
1759
+ output_hidden_states=output_hidden_states,
1760
+ return_dict=return_dict,
1761
+ )
1762
+
1763
+ sequence_output = outputs[0]
1764
+
1765
+ sequence_output = self.dropout(sequence_output)
1766
+ logits = self.classifier(sequence_output)
1767
+
1768
+ loss = None
1769
+ if labels is not None:
1770
+ loss_fct = CrossEntropyLoss()
1771
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1772
+
1773
+ if not return_dict:
1774
+ output = (logits,) + outputs[2:]
1775
+ return ((loss,) + output) if loss is not None else output
1776
+
1777
+ return TokenClassifierOutput(
1778
+ loss=loss,
1779
+ logits=logits,
1780
+ hidden_states=outputs.hidden_states,
1781
+ attentions=outputs.attentions,
1782
+ )
1783
+
1784
+
1785
+ @add_start_docstrings(
1786
+ """
1787
+ Bert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
1788
+ layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
1789
+ """,
1790
+ BERT_START_DOCSTRING,
1791
+ )
1792
+ class BertForQuestionAnswering(BertPreTrainedModel):
1793
+
1794
+ _keys_to_ignore_on_load_unexpected = [r"pooler"]
1795
+
1796
+ def __init__(self, config):
1797
+ super().__init__(config)
1798
+ self.num_labels = config.num_labels
1799
+
1800
+ self.bert = BertModel(config, add_pooling_layer=False)
1801
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
1802
+
1803
+ # Initialize weights and apply final processing
1804
+ self.post_init()
1805
+
1806
+ @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1807
+ @add_code_sample_docstrings(
1808
+ processor_class=_TOKENIZER_FOR_DOC,
1809
+ checkpoint=_CHECKPOINT_FOR_QA,
1810
+ output_type=QuestionAnsweringModelOutput,
1811
+ config_class=_CONFIG_FOR_DOC,
1812
+ qa_target_start_index=_QA_TARGET_START_INDEX,
1813
+ qa_target_end_index=_QA_TARGET_END_INDEX,
1814
+ expected_output=_QA_EXPECTED_OUTPUT,
1815
+ expected_loss=_QA_EXPECTED_LOSS,
1816
+ )
1817
+ def forward(
1818
+ self,
1819
+ input_ids: Optional[torch.Tensor] = None,
1820
+ attention_mask: Optional[torch.Tensor] = None,
1821
+ token_type_ids: Optional[torch.Tensor] = None,
1822
+ position_ids: Optional[torch.Tensor] = None,
1823
+ head_mask: Optional[torch.Tensor] = None,
1824
+ inputs_embeds: Optional[torch.Tensor] = None,
1825
+ start_positions: Optional[torch.Tensor] = None,
1826
+ end_positions: Optional[torch.Tensor] = None,
1827
+ output_attentions: Optional[bool] = None,
1828
+ output_hidden_states: Optional[bool] = None,
1829
+ return_dict: Optional[bool] = None,
1830
+ ) -> Union[Tuple[torch.Tensor], QuestionAnsweringModelOutput]:
1831
+ r"""
1832
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1833
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1834
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1835
+ are not taken into account for computing the loss.
1836
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1837
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1838
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1839
+ are not taken into account for computing the loss.
1840
+ """
1841
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1842
+
1843
+ outputs = self.bert(
1844
+ input_ids,
1845
+ attention_mask=attention_mask,
1846
+ token_type_ids=token_type_ids,
1847
+ position_ids=position_ids,
1848
+ head_mask=head_mask,
1849
+ inputs_embeds=inputs_embeds,
1850
+ output_attentions=output_attentions,
1851
+ output_hidden_states=output_hidden_states,
1852
+ return_dict=return_dict,
1853
+ )
1854
+
1855
+ sequence_output = outputs[0]
1856
+
1857
+ logits = self.qa_outputs(sequence_output)
1858
+ start_logits, end_logits = logits.split(1, dim=-1)
1859
+ start_logits = start_logits.squeeze(-1).contiguous()
1860
+ end_logits = end_logits.squeeze(-1).contiguous()
1861
+
1862
+ total_loss = None
1863
+ if start_positions is not None and end_positions is not None:
1864
+ # If we are on multi-GPU, split add a dimension
1865
+ if len(start_positions.size()) > 1:
1866
+ start_positions = start_positions.squeeze(-1)
1867
+ if len(end_positions.size()) > 1:
1868
+ end_positions = end_positions.squeeze(-1)
1869
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1870
+ ignored_index = start_logits.size(1)
1871
+ start_positions = start_positions.clamp(0, ignored_index)
1872
+ end_positions = end_positions.clamp(0, ignored_index)
1873
+
1874
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1875
+ start_loss = loss_fct(start_logits, start_positions)
1876
+ end_loss = loss_fct(end_logits, end_positions)
1877
+ total_loss = (start_loss + end_loss) / 2
1878
+
1879
+ if not return_dict:
1880
+ output = (start_logits, end_logits) + outputs[2:]
1881
+ return ((total_loss,) + output) if total_loss is not None else output
1882
+
1883
+ return QuestionAnsweringModelOutput(
1884
+ loss=total_loss,
1885
+ start_logits=start_logits,
1886
+ end_logits=end_logits,
1887
+ hidden_states=outputs.hidden_states,
1888
+ attentions=outputs.attentions,
1889
+ )
pytorch_model.bin CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:2318a9595339a6433d2e14cf18464ef105d8afe0f3ef4f8de87d4a67cac00dad
3
- size 711553257
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1b0009c9b8ad656d3545bc1d57b7a70c3165c8c5717b56a0a47a0c04cbaa979c
3
+ size 711553449
special_tokens_map.json CHANGED
@@ -1 +1,7 @@
1
- {"unk_token": "[UNK]", "sep_token": "[SEP]", "pad_token": "[PAD]", "cls_token": "[CLS]", "mask_token": "[MASK]"}
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": "[CLS]",
3
+ "mask_token": "[MASK]",
4
+ "pad_token": "[PAD]",
5
+ "sep_token": "[SEP]",
6
+ "unk_token": "[UNK]"
7
+ }
tokenizer_config.json CHANGED
@@ -1 +1,16 @@
1
- {"do_lower_case": false, "do_basic_tokenize": true, "never_split": null, "unk_token": "[UNK]", "sep_token": "[SEP]", "pad_token": "[PAD]", "cls_token": "[CLS]", "mask_token": "[MASK]", "tokenize_chinese_chars": true, "strip_accents": null, "model_max_length": 512, "special_tokens_map_file": null, "name_or_path": "bert-base-multilingual-cased", "tokenizer_class": "BertTokenizer"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": "[CLS]",
3
+ "do_basic_tokenize": true,
4
+ "do_lower_case": false,
5
+ "mask_token": "[MASK]",
6
+ "model_max_length": 512,
7
+ "name_or_path": "bert-base-multilingual-cased",
8
+ "never_split": null,
9
+ "pad_token": "[PAD]",
10
+ "sep_token": "[SEP]",
11
+ "special_tokens_map_file": null,
12
+ "strip_accents": null,
13
+ "tokenize_chinese_chars": true,
14
+ "tokenizer_class": "BertTokenizer",
15
+ "unk_token": "[UNK]"
16
+ }
training_args.bin CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:424d8be4348080dd8314a205ce18dabf2f417f06f96b38f28753c92b907ecbbd
3
- size 3247
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:de121b9d06acc600d54d91b722b4f14579844fb7b0d1d062ca644296e33f09cb
3
+ size 3439