davda54 commited on
Commit
035792c
1 Parent(s): 5be7854

Upload with huggingface_hub

Browse files
__init__.py ADDED
File without changes
config.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "LtgBertForMaskedLM"
4
+ ],
5
+ "attention_probs_dropout_prob": 0.1,
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_ltgbert.LtgBertConfig",
8
+ "AutoModelForMaskedLM": "modeling_ltgbert.LtgBertForMaskedLM",
9
+ "AutoModelForSequenceClassification": "modeling_ltgbert.LtgBertForSequenceClassification"
10
+ },
11
+ "classifier_dropout": 0.2,
12
+ "hidden_dropout_prob": 0.1,
13
+ "hidden_size": 768,
14
+ "intermediate_size": 2048,
15
+ "layer_norm_eps": 1e-07,
16
+ "max_position_embeddings": 256,
17
+ "model_type": "ltgbert",
18
+ "num_attention_heads": 12,
19
+ "num_hidden_layers": 12,
20
+ "output_all_encoded_layers": true,
21
+ "pad_token_id": 3,
22
+ "position_bucket_size": 32,
23
+ "torch_dtype": "float32",
24
+ "transformers_version": "4.26.0",
25
+ "vocab_size": 16384
26
+ }
configuration_ltgbert.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Language Technology Group from University of Oslo and The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """ LTG-BERT configutation """
17
+
18
+
19
+ from transformers.configuration_utils import PretrainedConfig
20
+
21
+
22
+ LTG_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP = {
23
+ "bnc-bert-span": "https://huggingface.co/ltg/bnc-bert-span",
24
+ "bnc-bert-span-2x": "https://huggingface.co/ltg/bnc-bert-span-2x",
25
+ "bnc-bert-span-0.5x": "https://huggingface.co/ltg/bnc-bert-span-0.5x",
26
+ "bnc-bert-span-0.25x": "https://huggingface.co/ltg/bnc-bert-span-0.25x",
27
+ "bnc-bert-span-order": "https://huggingface.co/ltg/bnc-bert-span-order",
28
+ "bnc-bert-span-document": "https://huggingface.co/ltg/bnc-bert-span-document",
29
+ "bnc-bert-span-word": "https://huggingface.co/ltg/bnc-bert-span-word",
30
+ "bnc-bert-span-subword": "https://huggingface.co/ltg/bnc-bert-span-subword",
31
+
32
+ "norbert3-xs": "https://huggingface.co/ltg/norbert3-xs/config.json",
33
+ "norbert3-small": "https://huggingface.co/ltg/norbert3-small/config.json",
34
+ "norbert3-base": "https://huggingface.co/ltg/norbert3-base/config.json",
35
+ "norbert3-large": "https://huggingface.co/ltg/norbert3-large/config.json",
36
+
37
+ "norbert3-oversampled-base": "https://huggingface.co/ltg/norbert3-oversampled-base/config.json",
38
+ "norbert3-ncc-base": "https://huggingface.co/ltg/norbert3-ncc-base/config.json",
39
+ "norbert3-nak-base": "https://huggingface.co/ltg/norbert3-nak-base/config.json",
40
+ "norbert3-nb-base": "https://huggingface.co/ltg/norbert3-nb-base/config.json",
41
+ "norbert3-wiki-base": "https://huggingface.co/ltg/norbert3-wiki-base/config.json",
42
+ "norbert3-c4-base": "https://huggingface.co/ltg/norbert3-c4-base/config.json"
43
+ }
44
+
45
+
46
+ class LtgBertConfig(PretrainedConfig):
47
+ r"""
48
+ This is the configuration class to store the configuration of a [`LtgBertModel`]. It is used to
49
+ instantiate an LTG-BERT model according to the specified arguments, defining the model architecture.
50
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
51
+ documentation from [`PretrainedConfig`] for more information.
52
+ Args:
53
+ vocab_size (`int`, *optional*, defaults to 16384):
54
+ Vocabulary size of the LTG-BERT model. Defines the number of different tokens that can be represented by the
55
+ `inputs_ids` passed when calling [`LtgBertModel`].
56
+ hidden_size (`int`, *optional*, defaults to 768):
57
+ Dimensionality of the encoder layers and the pooler layer.
58
+ num_hidden_layers (`int`, *optional*, defaults to 12):
59
+ Number of hidden layers in the Transformer encoder.
60
+ num_attention_heads (`int`, *optional*, defaults to 12):
61
+ Number of attention heads for each attention layer in the Transformer encoder.
62
+ intermediate_size (`int`, *optional*, defaults to 2048):
63
+ Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
64
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
65
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
66
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
67
+ The dropout ratio for the attention probabilities.
68
+ max_position_embeddings (`int`, *optional*, defaults to 512):
69
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
70
+ just in case (e.g., 512 or 1024 or 2048).
71
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
72
+ The epsilon used by the layer normalization layers.
73
+ classifier_dropout (`float`, *optional*):
74
+ The dropout ratio for the classification head.
75
+ """
76
+ model_type = "ltgbert"
77
+ def __init__(
78
+ self,
79
+ vocab_size=16384,
80
+ attention_probs_dropout_prob=0.1,
81
+ hidden_dropout_prob=0.1,
82
+ hidden_size=768,
83
+ intermediate_size=2048,
84
+ max_position_embeddings=512,
85
+ position_bucket_size=32,
86
+ num_attention_heads=12,
87
+ num_hidden_layers=12,
88
+ layer_norm_eps=1.0e-7,
89
+ pad_token_id=4,
90
+ output_all_encoded_layers=True,
91
+ classifier_dropout=None,
92
+ **kwargs,
93
+ ):
94
+ super().__init__(pad_token_id=pad_token_id, **kwargs)
95
+
96
+ self.vocab_size = vocab_size
97
+ self.hidden_size = hidden_size
98
+ self.num_hidden_layers = num_hidden_layers
99
+ self.num_attention_heads = num_attention_heads
100
+ self.intermediate_size = intermediate_size
101
+ self.hidden_dropout_prob = hidden_dropout_prob
102
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
103
+ self.max_position_embeddings = max_position_embeddings
104
+ self.output_all_encoded_layers = output_all_encoded_layers
105
+ self.position_bucket_size = position_bucket_size
106
+ self.layer_norm_eps = layer_norm_eps
107
+ self.classifier_dropout = classifier_dropout
modeling_ltgbert.py ADDED
@@ -0,0 +1,830 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Language Technology Group from University of Oslo and The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """ PyTorch LTG-BERT model."""
17
+
18
+
19
+ import math
20
+ import copy
21
+ from typing import List, Optional, Tuple, Union
22
+
23
+ import torch
24
+ import torch.nn as nn
25
+ import torch.nn.functional as F
26
+ from torch.utils import checkpoint
27
+
28
+ from .configuration_ltgbert import LtgBertConfig
29
+ from transformers.modeling_utils import PreTrainedModel
30
+ from transformers.activations import gelu_new
31
+ from transformers.modeling_outputs import (
32
+ MaskedLMOutput,
33
+ MultipleChoiceModelOutput,
34
+ QuestionAnsweringModelOutput,
35
+ SequenceClassifierOutput,
36
+ TokenClassifierOutput,
37
+ BaseModelOutput
38
+ )
39
+ from transformers.pytorch_utils import softmax_backward_data
40
+ from transformers.utils import add_start_docstrings, add_start_docstrings_to_model_forward
41
+
42
+
43
+ _CHECKPOINT_FOR_DOC = "ltg/bnc-bert-span"
44
+ _CONFIG_FOR_DOC = "LtgBertConfig"
45
+
46
+
47
+ LTG_BERT_PRETRAINED_MODEL_ARCHIVE_LIST = [
48
+ "bnc-bert-span",
49
+ "bnc-bert-span-2x",
50
+ "bnc-bert-span-0.5x",
51
+ "bnc-bert-span-0.25x",
52
+ "bnc-bert-span-order",
53
+ "bnc-bert-span-document",
54
+ "bnc-bert-span-word",
55
+ "bnc-bert-span-subword",
56
+
57
+ "norbert3-xs",
58
+ "norbert3-small",
59
+ "norbert3-base",
60
+ "norbert3-large",
61
+
62
+ "norbert3-oversampled-base",
63
+ "norbert3-ncc-base",
64
+ "norbert3-nak-base",
65
+ "norbert3-nb-base",
66
+ "norbert3-wiki-base",
67
+ "norbert3-c4-base"
68
+ ]
69
+
70
+
71
+ class Encoder(nn.Module):
72
+ def __init__(self, config, activation_checkpointing=False):
73
+ super().__init__()
74
+ self.layers = nn.ModuleList([EncoderLayer(config) for _ in range(config.num_hidden_layers)])
75
+ self.norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
76
+
77
+ for i, layer in enumerate(self.layers):
78
+ layer.mlp.mlp[1].weight.data *= math.sqrt(1.0 / (2.0 * (1 + i)))
79
+ layer.mlp.mlp[-2].weight.data *= math.sqrt(1.0 / (2.0 * (1 + i)))
80
+
81
+ self.activation_checkpointing = activation_checkpointing
82
+
83
+ def forward(self, hidden_states, attention_mask, relative_embedding):
84
+ hidden_states, attention_probs = [hidden_states], []
85
+
86
+ for layer in self.layers:
87
+ if self.activation_checkpointing:
88
+ hidden_state, attention_p = checkpoint.checkpoint(layer, hidden_states[-1], attention_mask, relative_embedding)
89
+ else:
90
+ hidden_state, attention_p = layer(hidden_states[-1], attention_mask, relative_embedding)
91
+
92
+ hidden_states.append(hidden_state)
93
+ attention_probs.append(attention_p)
94
+
95
+ hidden_states[-1] = self.norm(hidden_states[-1])
96
+
97
+ return hidden_states, attention_probs
98
+
99
+
100
+ class MaskClassifier(nn.Module):
101
+ def __init__(self, config, subword_embedding):
102
+ super().__init__()
103
+ self.nonlinearity = nn.Sequential(
104
+ nn.Linear(config.hidden_size, config.hidden_size),
105
+ nn.GELU(),
106
+ nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False),
107
+ nn.Dropout(config.hidden_dropout_prob),
108
+ nn.Linear(subword_embedding.size(1), subword_embedding.size(0))
109
+ )
110
+ self.initialize(config.hidden_size, subword_embedding)
111
+
112
+ def initialize(self, hidden_size, embedding):
113
+ std = math.sqrt(2.0 / (5.0 * hidden_size))
114
+ nn.init.trunc_normal_(self.nonlinearity[0].weight, mean=0.0, std=std, a=-2*std, b=2*std)
115
+ self.nonlinearity[-1].weight = embedding
116
+ self.nonlinearity[0].bias.data.zero_()
117
+ self.nonlinearity[-1].bias.data.zero_()
118
+
119
+ def forward(self, x, masked_lm_labels=None):
120
+ if masked_lm_labels is not None:
121
+ x = torch.index_select(x.flatten(0, 1), 0, torch.nonzero(masked_lm_labels.flatten() != -100).squeeze())
122
+ x = self.nonlinearity(x) / 2
123
+ return x
124
+
125
+
126
+ class EncoderLayer(nn.Module):
127
+ def __init__(self, config):
128
+ super().__init__()
129
+ self.attention = Attention(config)
130
+ self.mlp = FeedForward(config)
131
+
132
+ def forward(self, x, padding_mask, relative_embedding):
133
+ attention_output, attention_probs = self.attention(x, padding_mask, relative_embedding)
134
+ x = x + attention_output
135
+ x = x + self.mlp(x)
136
+ return x, attention_probs
137
+
138
+
139
+ class GeGLU(nn.Module):
140
+ def forward(self, x):
141
+ x, gate = x.chunk(2, dim=-1)
142
+ x = x * gelu_new(gate)
143
+ return x
144
+
145
+
146
+ class FeedForward(nn.Module):
147
+ def __init__(self, config):
148
+ super().__init__()
149
+ self.mlp = nn.Sequential(
150
+ nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps, elementwise_affine=False),
151
+ nn.Linear(config.hidden_size, 2*config.intermediate_size, bias=False),
152
+ GeGLU(),
153
+ nn.LayerNorm(config.intermediate_size, eps=config.layer_norm_eps, elementwise_affine=False),
154
+ nn.Linear(config.intermediate_size, config.hidden_size, bias=False),
155
+ nn.Dropout(config.hidden_dropout_prob)
156
+ )
157
+ self.initialize(config.hidden_size)
158
+
159
+ def initialize(self, hidden_size):
160
+ std = math.sqrt(2.0 / (5.0 * hidden_size))
161
+ nn.init.trunc_normal_(self.mlp[1].weight, mean=0.0, std=std, a=-2*std, b=2*std)
162
+ nn.init.trunc_normal_(self.mlp[-2].weight, mean=0.0, std=std, a=-2*std, b=2*std)
163
+
164
+ def forward(self, x):
165
+ return self.mlp(x)
166
+
167
+
168
+ class MaskedSoftmax(torch.autograd.Function):
169
+ @staticmethod
170
+ def forward(self, x, mask, dim):
171
+ self.dim = dim
172
+ x.masked_fill_(mask, float('-inf'))
173
+ x = torch.softmax(x, self.dim)
174
+ x.masked_fill_(mask, 0.0)
175
+ self.save_for_backward(x)
176
+ return x
177
+
178
+ @staticmethod
179
+ def backward(self, grad_output):
180
+ output, = self.saved_tensors
181
+ input_grad = softmax_backward_data(self, grad_output, output, self.dim, output)
182
+ return input_grad, None, None
183
+
184
+
185
+ class Attention(nn.Module):
186
+ def __init__(self, config):
187
+ super().__init__()
188
+
189
+ self.config = config
190
+
191
+ if config.hidden_size % config.num_attention_heads != 0:
192
+ raise ValueError(f"The hidden size {config.hidden_size} is not a multiple of the number of attention heads {config.num_attention_heads}")
193
+
194
+ self.hidden_size = config.hidden_size
195
+ self.num_heads = config.num_attention_heads
196
+ self.head_size = config.hidden_size // config.num_attention_heads
197
+
198
+ self.in_proj_qk = nn.Linear(config.hidden_size, 2*config.hidden_size, bias=True)
199
+ self.in_proj_v = nn.Linear(config.hidden_size, config.hidden_size, bias=True)
200
+ self.out_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=True)
201
+
202
+ self.pre_layer_norm = nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False)
203
+ self.post_layer_norm = nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=True)
204
+
205
+ position_indices = torch.arange(config.max_position_embeddings, dtype=torch.long).unsqueeze(1) \
206
+ - torch.arange(config.max_position_embeddings, dtype=torch.long).unsqueeze(0)
207
+ position_indices = self.make_log_bucket_position(position_indices, config.position_bucket_size, config.max_position_embeddings)
208
+ position_indices = config.position_bucket_size - 1 + position_indices
209
+ self.register_buffer("position_indices", position_indices, persistent=True)
210
+
211
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
212
+ self.scale = 1.0 / math.sqrt(3 * self.head_size)
213
+ self.initialize()
214
+
215
+ def make_log_bucket_position(self, relative_pos, bucket_size, max_position):
216
+ sign = torch.sign(relative_pos)
217
+ mid = bucket_size // 2
218
+ abs_pos = torch.where((relative_pos < mid) & (relative_pos > -mid), mid - 1, torch.abs(relative_pos).clamp(max=max_position - 1))
219
+ log_pos = torch.ceil(torch.log(abs_pos / mid) / math.log((max_position-1) / mid) * (mid - 1)).int() + mid
220
+ bucket_pos = torch.where(abs_pos <= mid, relative_pos, log_pos * sign).long()
221
+ return bucket_pos
222
+
223
+ def initialize(self):
224
+ std = math.sqrt(2.0 / (5.0 * self.hidden_size))
225
+ nn.init.trunc_normal_(self.in_proj_qk.weight, mean=0.0, std=std, a=-2*std, b=2*std)
226
+ nn.init.trunc_normal_(self.in_proj_v.weight, mean=0.0, std=std, a=-2*std, b=2*std)
227
+ nn.init.trunc_normal_(self.out_proj.weight, mean=0.0, std=std, a=-2*std, b=2*std)
228
+ self.in_proj_qk.bias.data.zero_()
229
+ self.in_proj_v.bias.data.zero_()
230
+ self.out_proj.bias.data.zero_()
231
+
232
+ def compute_attention_scores(self, hidden_states, relative_embedding):
233
+ key_len, batch_size, _ = hidden_states.size()
234
+ query_len = key_len
235
+
236
+ if self.position_indices.size(0) < query_len:
237
+ position_indices = torch.arange(query_len, dtype=torch.long).unsqueeze(1) \
238
+ - torch.arange(query_len, dtype=torch.long).unsqueeze(0)
239
+ position_indices = self.make_log_bucket_position(position_indices, self.config.position_bucket_size, 256)
240
+ position_indices = self.config.position_bucket_size - 1 + position_indices
241
+ self.position_indices = position_indices.to(hidden_states.device)
242
+
243
+ hidden_states = self.pre_layer_norm(hidden_states)
244
+
245
+ query, key = self.in_proj_qk(hidden_states).chunk(2, dim=2) # shape: [T, B, D]
246
+ value = self.in_proj_v(hidden_states) # shape: [T, B, D]
247
+
248
+ query = query.reshape(query_len, batch_size * self.num_heads, self.head_size).transpose(0, 1)
249
+ key = key.reshape(key_len, batch_size * self.num_heads, self.head_size).transpose(0, 1)
250
+ value = value.view(key_len, batch_size * self.num_heads, self.head_size).transpose(0, 1)
251
+
252
+ attention_scores = torch.bmm(query, key.transpose(1, 2) * self.scale)
253
+
254
+ query_pos, key_pos = self.in_proj_qk(self.dropout(relative_embedding)).chunk(2, dim=-1) # shape: [2T-1, D]
255
+ query_pos = query_pos.view(-1, self.num_heads, self.head_size) # shape: [2T-1, H, D]
256
+ key_pos = key_pos.view(-1, self.num_heads, self.head_size) # shape: [2T-1, H, D]
257
+
258
+ query = query.view(batch_size, self.num_heads, query_len, self.head_size)
259
+ key = key.view(batch_size, self.num_heads, query_len, self.head_size)
260
+
261
+ attention_c_p = torch.einsum("bhqd,khd->bhqk", query, key_pos.squeeze(1) * self.scale)
262
+ attention_p_c = torch.einsum("bhkd,qhd->bhqk", key * self.scale, query_pos.squeeze(1))
263
+
264
+ position_indices = self.position_indices[:query_len, :key_len].expand(batch_size, self.num_heads, -1, -1)
265
+ attention_c_p = attention_c_p.gather(3, position_indices)
266
+ attention_p_c = attention_p_c.gather(2, position_indices)
267
+
268
+ attention_scores = attention_scores.view(batch_size, self.num_heads, query_len, key_len)
269
+ attention_scores.add_(attention_c_p)
270
+ attention_scores.add_(attention_p_c)
271
+
272
+ return attention_scores, value
273
+
274
+ def compute_output(self, attention_probs, value):
275
+ attention_probs = self.dropout(attention_probs)
276
+ context = torch.bmm(attention_probs.flatten(0, 1), value) # shape: [B*H, Q, D]
277
+ context = context.transpose(0, 1).reshape(context.size(1), -1, self.hidden_size) # shape: [Q, B, H*D]
278
+ context = self.out_proj(context)
279
+ context = self.post_layer_norm(context)
280
+ context = self.dropout(context)
281
+ return context
282
+
283
+ def forward(self, hidden_states, attention_mask, relative_embedding):
284
+ attention_scores, value = self.compute_attention_scores(hidden_states, relative_embedding)
285
+ attention_probs = MaskedSoftmax.apply(attention_scores, attention_mask, -1)
286
+ return self.compute_output(attention_probs, value), attention_probs.detach()
287
+
288
+
289
+ class Embedding(nn.Module):
290
+ def __init__(self, config):
291
+ super().__init__()
292
+ self.hidden_size = config.hidden_size
293
+
294
+ self.word_embedding = nn.Embedding(config.vocab_size, config.hidden_size)
295
+ self.word_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps, elementwise_affine=False)
296
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
297
+
298
+ self.mask_embedding = nn.Parameter(torch.randn(config.hidden_size))
299
+
300
+ self.relative_embedding = nn.Parameter(torch.empty(2 * config.position_bucket_size - 1, config.hidden_size))
301
+ self.relative_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
302
+
303
+ self.initialize()
304
+
305
+ def initialize(self):
306
+ std = math.sqrt(2.0 / (5.0 * self.hidden_size))
307
+ nn.init.trunc_normal_(self.relative_embedding, mean=0.0, std=std, a=-2*std, b=2*std)
308
+ nn.init.trunc_normal_(self.word_embedding.weight, mean=0.0, std=std, a=-2*std, b=2*std)
309
+
310
+ def forward(self, input_ids):
311
+ word_embedding = self.dropout(self.word_layer_norm(self.word_embedding(input_ids)))
312
+ relative_embeddings = self.relative_layer_norm(self.relative_embedding)
313
+
314
+ return word_embedding, relative_embeddings
315
+
316
+
317
+ #
318
+ # HuggingFace wrappers
319
+ #
320
+
321
+ class LtgBertPreTrainedModel(PreTrainedModel):
322
+ """
323
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
324
+ models.
325
+ """
326
+
327
+ config_class = LtgBertConfig
328
+ base_model_prefix = "bnc-bert"
329
+ supports_gradient_checkpointing = True
330
+
331
+ def _set_gradient_checkpointing(self, module, value=False):
332
+ if isinstance(module, Encoder):
333
+ module.activation_checkpointing = value
334
+
335
+ def _init_weights(self, _):
336
+ pass # everything is already initialized
337
+
338
+
339
+ LTG_BERT_START_DOCSTRING = r"""
340
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
341
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
342
+ etc.)
343
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
344
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
345
+ and behavior.
346
+ Parameters:
347
+ config ([`LtgBertConfig`]): Model configuration class with all the parameters of the model.
348
+ Initializing with a config file does not load the weights associated with the model, only the
349
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
350
+ """
351
+
352
+ LTG_BERT_INPUTS_DOCSTRING = r"""
353
+ Args:
354
+ input_ids (`torch.LongTensor` of shape `({0})`):
355
+ Indices of input sequence tokens in the vocabulary.
356
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
357
+ [`PreTrainedTokenizer.__call__`] for details.
358
+ [What are input IDs?](../glossary#input-ids)
359
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
360
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
361
+ - 1 for tokens that are **not masked**,
362
+ - 0 for tokens that are **masked**.
363
+ [What are attention masks?](../glossary#attention-mask)
364
+ output_hidden_states (`bool`, *optional*):
365
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
366
+ more detail.
367
+ output_attentions (`bool`, *optional*):
368
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
369
+ tensors for more detail.
370
+ return_dict (`bool`, *optional*):
371
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
372
+ """
373
+
374
+
375
+ @add_start_docstrings(
376
+ "The bare LTG-BERT transformer outputting raw hidden-states without any specific head on top.",
377
+ LTG_BERT_START_DOCSTRING,
378
+ )
379
+ class LtgBertModel(LtgBertPreTrainedModel):
380
+ def __init__(self, config, add_mlm_layer=False):
381
+ super().__init__(config)
382
+ self.config = config
383
+
384
+ self.embedding = Embedding(config)
385
+ self.transformer = Encoder(config, activation_checkpointing=False)
386
+
387
+ decoder_config = copy.deepcopy(config)
388
+ decoder_config.num_hidden_layers = 4
389
+ decoder_config.attention_probs_dropout_prob = 0.0
390
+ decoder_config.hidden_dropout_prob = 0.0
391
+
392
+ self.decoder = Encoder(decoder_config, activation_checkpointing=False)
393
+
394
+ if add_mlm_layer:
395
+ self.classifier = MaskClassifier(config, self.embedding.word_embedding.weight)
396
+ else:
397
+ self.classifier = None
398
+
399
+ def get_input_embeddings(self):
400
+ return self.embedding.word_embedding
401
+
402
+ def set_input_embeddings(self, value):
403
+ self.embedding.word_embedding = value
404
+
405
+ def get_contextualized_embeddings(
406
+ self,
407
+ input_ids: Optional[torch.Tensor] = None,
408
+ attention_mask: Optional[torch.Tensor] = None
409
+ ) -> List[torch.Tensor]:
410
+ if input_ids is not None:
411
+ input_shape = input_ids.size()
412
+ else:
413
+ raise ValueError("You have to specify input_ids")
414
+
415
+ batch_size, seq_length = input_shape
416
+ device = input_ids.device
417
+
418
+ if attention_mask is None:
419
+ attention_mask = input_ids == 4
420
+ else:
421
+ attention_mask = ~attention_mask.bool()
422
+ attention_mask = attention_mask | (input_ids == 4) # mask padding and [MASK] tokens
423
+ attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
424
+
425
+ static_embeddings, relative_embedding = self.embedding(input_ids.t())
426
+ contextualized_embeddings, attention_probs = self.transformer(static_embeddings, attention_mask, relative_embedding)
427
+ contextualized_embeddings = [e.transpose(0, 1) for e in contextualized_embeddings]
428
+ last_layer = contextualized_embeddings[-1]
429
+ contextualized_embeddings = [contextualized_embeddings[0]] + [
430
+ contextualized_embeddings[i] - contextualized_embeddings[i - 1]
431
+ for i in range(1, len(contextualized_embeddings))
432
+ ]
433
+ return last_layer, contextualized_embeddings, attention_probs, relative_embedding
434
+
435
+ @add_start_docstrings_to_model_forward(LTG_BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
436
+ def forward(
437
+ self,
438
+ input_ids: Optional[torch.Tensor] = None,
439
+ attention_mask: Optional[torch.Tensor] = None,
440
+ output_hidden_states: Optional[bool] = None,
441
+ output_attentions: Optional[bool] = None,
442
+ return_dict: Optional[bool] = None,
443
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutput]:
444
+
445
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
446
+ output_hidden_states = (
447
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
448
+ )
449
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
450
+
451
+ sequence_output, contextualized_embeddings, attention_probs, _ = self.get_contextualized_embeddings(input_ids, attention_mask)
452
+
453
+ if not return_dict:
454
+ return (
455
+ sequence_output,
456
+ *([contextualized_embeddings] if output_hidden_states else []),
457
+ *([attention_probs] if output_attentions else [])
458
+ )
459
+
460
+ return BaseModelOutput(
461
+ last_hidden_state=sequence_output,
462
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
463
+ attentions=attention_probs if output_attentions else None
464
+ )
465
+
466
+
467
+ @add_start_docstrings("""LTG-BERT model with a `language modeling` head on top.""", LTG_BERT_START_DOCSTRING)
468
+ class LtgBertForMaskedLM(LtgBertModel):
469
+ _keys_to_ignore_on_load_unexpected = ["head"]
470
+
471
+ def __init__(self, config):
472
+ super().__init__(config, add_mlm_layer=True)
473
+
474
+ def get_output_embeddings(self):
475
+ return self.classifier.nonlinearity[-1].weight
476
+
477
+ def set_output_embeddings(self, new_embeddings):
478
+ self.classifier.nonlinearity[-1].weight = new_embeddings
479
+
480
+ @add_start_docstrings_to_model_forward(LTG_BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
481
+ def forward(
482
+ self,
483
+ input_ids: Optional[torch.Tensor] = None,
484
+ attention_mask: Optional[torch.Tensor] = None,
485
+ output_hidden_states: Optional[bool] = None,
486
+ output_attentions: Optional[bool] = None,
487
+ return_dict: Optional[bool] = None,
488
+ labels: Optional[torch.LongTensor] = None,
489
+ ) -> Union[Tuple[torch.Tensor], MaskedLMOutput]:
490
+ r"""
491
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
492
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
493
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
494
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
495
+ """
496
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
497
+
498
+ sequence_output, contextualized_embeddings, attention_probs, relative_embedding = self.get_contextualized_embeddings(input_ids, attention_mask)
499
+
500
+ mask_embedding = self.embedding.mask_embedding
501
+ decoder_input = torch.where(input_ids.t().unsqueeze(-1) != 4, sequence_output.transpose(0, 1), mask_embedding)
502
+
503
+ if attention_mask is None:
504
+ attention_mask = torch.zeros(input_ids.size(0), input_ids.size(1), dtype=torch.bool, device=input_ids.device)
505
+ else:
506
+ attention_mask = ~attention_mask.bool()
507
+ attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
508
+ sequence_output, _ = self.decoder(decoder_input, attention_mask, relative_embedding)
509
+ subword_prediction = self.classifier(sequence_output[-1]).transpose(0, 1)
510
+
511
+ masked_lm_loss = None
512
+ if labels is not None:
513
+ masked_lm_loss = F.cross_entropy(subword_prediction.flatten(0, 1), labels.flatten())
514
+
515
+ if not return_dict:
516
+ output = (
517
+ subword_prediction,
518
+ *([contextualized_embeddings] if output_hidden_states else []),
519
+ *([attention_probs] if output_attentions else [])
520
+ )
521
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
522
+
523
+ return MaskedLMOutput(
524
+ loss=masked_lm_loss,
525
+ logits=subword_prediction,
526
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
527
+ attentions=attention_probs if output_attentions else None
528
+ )
529
+
530
+
531
+ class Classifier(nn.Module):
532
+ def __init__(self, config, num_labels: int):
533
+ super().__init__()
534
+
535
+ drop_out = getattr(config, "classifier_dropout", config.hidden_dropout_prob)
536
+
537
+ self.nonlinearity = nn.Sequential(
538
+ nn.Linear(config.hidden_size, config.hidden_size),
539
+ nn.GELU(),
540
+ nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False),
541
+ nn.Dropout(drop_out),
542
+ nn.Linear(config.hidden_size, num_labels)
543
+ )
544
+ self.initialize(config.hidden_size)
545
+
546
+ def initialize(self, hidden_size):
547
+ std = math.sqrt(2.0 / (5.0 * hidden_size))
548
+ nn.init.trunc_normal_(self.nonlinearity[0].weight, mean=0.0, std=std, a=-2*std, b=2*std)
549
+ nn.init.trunc_normal_(self.nonlinearity[-1].weight, mean=0.0, std=std, a=-2*std, b=2*std)
550
+ self.nonlinearity[0].bias.data.zero_()
551
+ self.nonlinearity[-1].bias.data.zero_()
552
+
553
+ def forward(self, x):
554
+ x = self.nonlinearity(x)
555
+ return x
556
+
557
+
558
+ @add_start_docstrings(
559
+ """
560
+ LTG-BERT model with a sequence classification/regression head on top (a linear layer on top of the pooled
561
+ output) e.g. for GLUE tasks.
562
+ """,
563
+ LTG_BERT_START_DOCSTRING,
564
+ )
565
+ class LtgBertForSequenceClassification(LtgBertModel):
566
+ _keys_to_ignore_on_load_unexpected = ["classifier"]
567
+ _keys_to_ignore_on_load_missing = ["head"]
568
+
569
+ def __init__(self, config):
570
+ super().__init__(config, add_mlm_layer=False)
571
+
572
+ self.num_labels = config.num_labels
573
+ self.head = Classifier(config, self.num_labels)
574
+
575
+ @add_start_docstrings_to_model_forward(LTG_BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
576
+ def forward(
577
+ self,
578
+ input_ids: Optional[torch.Tensor] = None,
579
+ attention_mask: Optional[torch.Tensor] = None,
580
+ output_attentions: Optional[bool] = None,
581
+ output_hidden_states: Optional[bool] = None,
582
+ return_dict: Optional[bool] = None,
583
+ labels: Optional[torch.LongTensor] = None,
584
+ ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
585
+ r"""
586
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
587
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
588
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
589
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
590
+ """
591
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
592
+
593
+ sequence_output, contextualized_embeddings, attention_probs, relative_embedding = self.get_contextualized_embeddings(input_ids, attention_mask)
594
+
595
+ if attention_mask is None:
596
+ attention_mask = torch.zeros(input_ids.size(0), input_ids.size(1), dtype=torch.bool, device=input_ids.device)
597
+ else:
598
+ attention_mask = ~attention_mask.bool()
599
+ attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
600
+ sequence_output, _ = self.decoder(sequence_output.transpose(0, 1), attention_mask, relative_embedding)
601
+ logits = self.head(sequence_output[-1][0, :, :])
602
+
603
+ loss = None
604
+ if labels is not None:
605
+ if self.config.problem_type is None:
606
+ if self.num_labels == 1:
607
+ self.config.problem_type = "regression"
608
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
609
+ self.config.problem_type = "single_label_classification"
610
+ else:
611
+ self.config.problem_type = "multi_label_classification"
612
+
613
+ if self.config.problem_type == "regression":
614
+ loss_fct = nn.MSELoss()
615
+ if self.num_labels == 1:
616
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
617
+ else:
618
+ loss = loss_fct(logits, labels)
619
+ elif self.config.problem_type == "single_label_classification":
620
+ loss_fct = nn.CrossEntropyLoss()
621
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
622
+ elif self.config.problem_type == "multi_label_classification":
623
+ loss_fct = nn.BCEWithLogitsLoss()
624
+ loss = loss_fct(logits, labels)
625
+
626
+ if not return_dict:
627
+ output = (
628
+ logits,
629
+ *([contextualized_embeddings] if output_hidden_states else []),
630
+ *([attention_probs] if output_attentions else [])
631
+ )
632
+ return ((loss,) + output) if loss is not None else output
633
+
634
+ return SequenceClassifierOutput(
635
+ loss=loss,
636
+ logits=logits,
637
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
638
+ attentions=attention_probs if output_attentions else None
639
+ )
640
+
641
+
642
+ @add_start_docstrings(
643
+ """
644
+ LTG-BERT model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
645
+ Named-Entity-Recognition (NER) tasks.
646
+ """,
647
+ LTG_BERT_START_DOCSTRING,
648
+ )
649
+ class LtgBertForTokenClassification(LtgBertModel):
650
+ _keys_to_ignore_on_load_unexpected = ["classifier"]
651
+ _keys_to_ignore_on_load_missing = ["head"]
652
+
653
+ def __init__(self, config):
654
+ super().__init__(config, add_mlm_layer=False)
655
+
656
+ self.num_labels = config.num_labels
657
+ self.head = Classifier(config, self.num_labels)
658
+
659
+ @add_start_docstrings_to_model_forward(LTG_BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
660
+ def forward(
661
+ self,
662
+ input_ids: Optional[torch.Tensor] = None,
663
+ attention_mask: Optional[torch.Tensor] = None,
664
+ token_type_ids: Optional[torch.Tensor] = None,
665
+ position_ids: Optional[torch.Tensor] = None,
666
+ output_attentions: Optional[bool] = None,
667
+ output_hidden_states: Optional[bool] = None,
668
+ return_dict: Optional[bool] = None,
669
+ labels: Optional[torch.LongTensor] = None,
670
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
671
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
672
+
673
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
674
+ logits = self.head(sequence_output)
675
+
676
+ loss = None
677
+ if labels is not None:
678
+ loss_fct = nn.CrossEntropyLoss()
679
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
680
+
681
+ if not return_dict:
682
+ output = (
683
+ logits,
684
+ *([contextualized_embeddings] if output_hidden_states else []),
685
+ *([attention_probs] if output_attentions else [])
686
+ )
687
+ return ((loss,) + output) if loss is not None else output
688
+
689
+ return TokenClassifierOutput(
690
+ loss=loss,
691
+ logits=logits,
692
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
693
+ attentions=attention_probs if output_attentions else None
694
+ )
695
+
696
+
697
+ @add_start_docstrings(
698
+ """
699
+ LTG-BERT model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
700
+ layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
701
+ """,
702
+ LTG_BERT_START_DOCSTRING,
703
+ )
704
+ class LtgBertForQuestionAnswering(LtgBertModel):
705
+ _keys_to_ignore_on_load_unexpected = ["classifier"]
706
+ _keys_to_ignore_on_load_missing = ["head"]
707
+
708
+ def __init__(self, config):
709
+ super().__init__(config, add_mlm_layer=False)
710
+
711
+ self.num_labels = config.num_labels
712
+ self.head = Classifier(config, self.num_labels)
713
+
714
+ @add_start_docstrings_to_model_forward(LTG_BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
715
+ def forward(
716
+ self,
717
+ input_ids: Optional[torch.Tensor] = None,
718
+ attention_mask: Optional[torch.Tensor] = None,
719
+ token_type_ids: Optional[torch.Tensor] = None,
720
+ position_ids: Optional[torch.Tensor] = None,
721
+ output_attentions: Optional[bool] = None,
722
+ output_hidden_states: Optional[bool] = None,
723
+ return_dict: Optional[bool] = None,
724
+ start_positions: Optional[torch.Tensor] = None,
725
+ end_positions: Optional[torch.Tensor] = None
726
+ ) -> Union[Tuple[torch.Tensor], QuestionAnsweringModelOutput]:
727
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
728
+
729
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
730
+ logits = self.head(sequence_output)
731
+
732
+ start_logits, end_logits = logits.split(1, dim=-1)
733
+ start_logits = start_logits.squeeze(-1).contiguous()
734
+ end_logits = end_logits.squeeze(-1).contiguous()
735
+
736
+ total_loss = None
737
+ if start_positions is not None and end_positions is not None:
738
+ # If we are on multi-GPU, split add a dimension
739
+ if len(start_positions.size()) > 1:
740
+ start_positions = start_positions.squeeze(-1)
741
+ if len(end_positions.size()) > 1:
742
+ end_positions = end_positions.squeeze(-1)
743
+
744
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
745
+ ignored_index = start_logits.size(1)
746
+ start_positions = start_positions.clamp(0, ignored_index)
747
+ end_positions = end_positions.clamp(0, ignored_index)
748
+
749
+ loss_fct = nn.CrossEntropyLoss(ignore_index=ignored_index)
750
+ start_loss = loss_fct(start_logits, start_positions)
751
+ end_loss = loss_fct(end_logits, end_positions)
752
+ total_loss = (start_loss + end_loss) / 2
753
+
754
+ if not return_dict:
755
+ output = (
756
+ start_logits,
757
+ end_logits,
758
+ *([contextualized_embeddings] if output_hidden_states else []),
759
+ *([attention_probs] if output_attentions else [])
760
+ )
761
+ return ((total_loss,) + output) if total_loss is not None else output
762
+
763
+ return QuestionAnsweringModelOutput(
764
+ loss=total_loss,
765
+ start_logits=start_logits,
766
+ end_logits=end_logits,
767
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
768
+ attentions=attention_probs if output_attentions else None
769
+ )
770
+
771
+
772
+ @add_start_docstrings(
773
+ """
774
+ LTG-BERT model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
775
+ softmax) e.g. for RocStories/SWAG tasks.
776
+ """,
777
+ LTG_BERT_START_DOCSTRING,
778
+ )
779
+ class LtgBertForMultipleChoice(LtgBertModel):
780
+ _keys_to_ignore_on_load_unexpected = ["classifier"]
781
+ _keys_to_ignore_on_load_missing = ["head"]
782
+
783
+ def __init__(self, config):
784
+ super().__init__(config, add_mlm_layer=False)
785
+
786
+ self.num_labels = getattr(config, "num_labels", 2)
787
+ self.head = Classifier(config, self.num_labels)
788
+
789
+ @add_start_docstrings_to_model_forward(LTG_BERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
790
+ def forward(
791
+ self,
792
+ input_ids: Optional[torch.Tensor] = None,
793
+ attention_mask: Optional[torch.Tensor] = None,
794
+ token_type_ids: Optional[torch.Tensor] = None,
795
+ position_ids: Optional[torch.Tensor] = None,
796
+ labels: Optional[torch.Tensor] = None,
797
+ output_attentions: Optional[bool] = None,
798
+ output_hidden_states: Optional[bool] = None,
799
+ return_dict: Optional[bool] = None
800
+ ) -> Union[Tuple[torch.Tensor], MultipleChoiceModelOutput]:
801
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
802
+ num_choices = input_ids.shape[1]
803
+
804
+ flat_input_ids = input_ids.view(-1, input_ids.size(-1))
805
+ flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
806
+
807
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(flat_input_ids, flat_attention_mask)
808
+ logits = self.head(sequence_output)
809
+ reshaped_logits = logits.view(-1, num_choices)
810
+
811
+ loss = None
812
+ if labels is not None:
813
+ loss_fct = nn.CrossEntropyLoss()
814
+ loss = loss_fct(reshaped_logits, labels)
815
+
816
+ if not return_dict:
817
+ output = (
818
+ reshaped_logits,
819
+ *([contextualized_embeddings] if output_hidden_states else []),
820
+ *([attention_probs] if output_attentions else [])
821
+ )
822
+ return ((loss,) + output) if loss is not None else output
823
+
824
+ return MultipleChoiceModelOutput(
825
+ loss=loss,
826
+ logits=reshaped_logits,
827
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
828
+ attentions=attention_probs if output_attentions else None
829
+ )
830
+
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9dacabc7b6ba72fe055b6b39279f42a4240e364f2affef3bd0d45d181a2f2780
3
+ size 24443
special_tokens_map.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "[BOS]",
3
+ "cls_token": "[CLS]",
4
+ "eos_token": "[EOS]",
5
+ "mask_token": "[MASK]",
6
+ "pad_token": "[PAD]",
7
+ "sep_token": "[SEP]",
8
+ "unk_token": "[UNK]"
9
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "model_max_length": 1000000000000000019884624838656,
3
+ "tokenizer_class": "PreTrainedTokenizerFast"
4
+ }