amroadel1 commited on
Commit
4274db8
1 Parent(s): b5c7d1d

Upload 2 files

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