egilron commited on
Commit
9300203
1 Parent(s): 1e946ad

Upload NorbertForTokenClassification

Browse files
Files changed (4) hide show
  1. config.json +43 -0
  2. configuration_norbert.py +34 -0
  3. model.safetensors +3 -0
  4. modeling_norbert.py +663 -0
config.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/home/egil/gits_wsl/SANT_FinalStage/models/01191518_tsa-bin_NorBERT_3_large_final/best_model",
3
+ "architectures": [
4
+ "NorbertForTokenClassification"
5
+ ],
6
+ "attention_probs_dropout_prob": 0.1,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_norbert.NorbertConfig",
9
+ "AutoModel": "ltg/norbert3-large--modeling_norbert.NorbertModel",
10
+ "AutoModelForMaskedLM": "ltg/norbert3-large--modeling_norbert.NorbertForMaskedLM",
11
+ "AutoModelForMultipleChoice": "ltg/norbert3-large--modeling_norbert.NorbertForMultipleChoice",
12
+ "AutoModelForQuestionAnswering": "ltg/norbert3-large--modeling_norbert.NorbertForQuestionAnswering",
13
+ "AutoModelForSequenceClassification": "ltg/norbert3-large--modeling_norbert.NorbertForSequenceClassification",
14
+ "AutoModelForTokenClassification": "modeling_norbert.NorbertForTokenClassification"
15
+ },
16
+ "finetuning_task": "01191518_tsa-bin_norbert_3_large",
17
+ "hidden_dropout_prob": 0.1,
18
+ "hidden_size": 1024,
19
+ "id2label": {
20
+ "0": "O",
21
+ "1": "B-targ-Negative",
22
+ "2": "I-targ-Negative",
23
+ "3": "B-targ-Positive",
24
+ "4": "I-targ-Positive"
25
+ },
26
+ "intermediate_size": 2730,
27
+ "label2id": {
28
+ "B-targ-Negative": 1,
29
+ "B-targ-Positive": 3,
30
+ "I-targ-Negative": 2,
31
+ "I-targ-Positive": 4,
32
+ "O": 0
33
+ },
34
+ "layer_norm_eps": 1e-07,
35
+ "max_position_embeddings": 512,
36
+ "num_attention_heads": 16,
37
+ "num_hidden_layers": 24,
38
+ "output_all_encoded_layers": true,
39
+ "position_bucket_size": 32,
40
+ "torch_dtype": "float32",
41
+ "transformers_version": "4.36.2",
42
+ "vocab_size": 50000
43
+ }
configuration_norbert.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers.configuration_utils import PretrainedConfig
2
+
3
+
4
+ class NorbertConfig(PretrainedConfig):
5
+ """Configuration class to store the configuration of a `NorbertModel`.
6
+ """
7
+ def __init__(
8
+ self,
9
+ vocab_size=50000,
10
+ attention_probs_dropout_prob=0.1,
11
+ hidden_dropout_prob=0.1,
12
+ hidden_size=768,
13
+ intermediate_size=2048,
14
+ max_position_embeddings=512,
15
+ position_bucket_size=32,
16
+ num_attention_heads=12,
17
+ num_hidden_layers=12,
18
+ layer_norm_eps=1.0e-7,
19
+ output_all_encoded_layers=True,
20
+ **kwargs,
21
+ ):
22
+ super().__init__(**kwargs)
23
+
24
+ self.vocab_size = vocab_size
25
+ self.hidden_size = hidden_size
26
+ self.num_hidden_layers = num_hidden_layers
27
+ self.num_attention_heads = num_attention_heads
28
+ self.intermediate_size = intermediate_size
29
+ self.hidden_dropout_prob = hidden_dropout_prob
30
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
31
+ self.max_position_embeddings = max_position_embeddings
32
+ self.output_all_encoded_layers = output_all_encoded_layers
33
+ self.position_bucket_size = position_bucket_size
34
+ self.layer_norm_eps = layer_norm_eps
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:34d6858b4ee469060f5d0c1210b48db2baf3c574dcedfa626361d8a286b649de
3
+ size 1468002116
modeling_norbert.py ADDED
@@ -0,0 +1,663 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from typing import List, Optional, Tuple, Union
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ from torch.utils import checkpoint
8
+
9
+ from .configuration_norbert import NorbertConfig
10
+ from transformers.modeling_utils import PreTrainedModel
11
+ from transformers.activations import gelu_new
12
+ from transformers.modeling_outputs import (
13
+ MaskedLMOutput,
14
+ MultipleChoiceModelOutput,
15
+ QuestionAnsweringModelOutput,
16
+ SequenceClassifierOutput,
17
+ TokenClassifierOutput,
18
+ BaseModelOutput
19
+ )
20
+ from transformers.pytorch_utils import softmax_backward_data
21
+
22
+
23
+ class Encoder(nn.Module):
24
+ def __init__(self, config, activation_checkpointing=False):
25
+ super().__init__()
26
+ self.layers = nn.ModuleList([EncoderLayer(config) for _ in range(config.num_hidden_layers)])
27
+
28
+ for i, layer in enumerate(self.layers):
29
+ layer.mlp.mlp[1].weight.data *= math.sqrt(1.0 / (2.0 * (1 + i)))
30
+ layer.mlp.mlp[-2].weight.data *= math.sqrt(1.0 / (2.0 * (1 + i)))
31
+
32
+ self.activation_checkpointing = activation_checkpointing
33
+
34
+ def forward(self, hidden_states, attention_mask, relative_embedding):
35
+ hidden_states, attention_probs = [hidden_states], []
36
+
37
+ for layer in self.layers:
38
+ if self.activation_checkpointing:
39
+ hidden_state, attention_p = checkpoint.checkpoint(layer, hidden_states[-1], attention_mask, relative_embedding)
40
+ else:
41
+ hidden_state, attention_p = layer(hidden_states[-1], attention_mask, relative_embedding)
42
+
43
+ hidden_states.append(hidden_state)
44
+ attention_probs.append(attention_p)
45
+
46
+ return hidden_states, attention_probs
47
+
48
+
49
+ class MaskClassifier(nn.Module):
50
+ def __init__(self, config, subword_embedding):
51
+ super().__init__()
52
+ self.nonlinearity = nn.Sequential(
53
+ nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False),
54
+ nn.Linear(config.hidden_size, config.hidden_size),
55
+ nn.GELU(),
56
+ nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False),
57
+ nn.Dropout(config.hidden_dropout_prob),
58
+ nn.Linear(subword_embedding.size(1), subword_embedding.size(0))
59
+ )
60
+ self.initialize(config.hidden_size, subword_embedding)
61
+
62
+ def initialize(self, hidden_size, embedding):
63
+ std = math.sqrt(2.0 / (5.0 * hidden_size))
64
+ nn.init.trunc_normal_(self.nonlinearity[1].weight, mean=0.0, std=std, a=-2*std, b=2*std)
65
+ self.nonlinearity[-1].weight = embedding
66
+ self.nonlinearity[1].bias.data.zero_()
67
+ self.nonlinearity[-1].bias.data.zero_()
68
+
69
+ def forward(self, x, masked_lm_labels=None):
70
+ if masked_lm_labels is not None:
71
+ x = torch.index_select(x.flatten(0, 1), 0, torch.nonzero(masked_lm_labels.flatten() != -100).squeeze())
72
+ x = self.nonlinearity(x)
73
+ return x
74
+
75
+
76
+ class EncoderLayer(nn.Module):
77
+ def __init__(self, config):
78
+ super().__init__()
79
+ self.attention = Attention(config)
80
+ self.mlp = FeedForward(config)
81
+
82
+ def forward(self, x, padding_mask, relative_embedding):
83
+ attention_output, attention_probs = self.attention(x, padding_mask, relative_embedding)
84
+ x = x + attention_output
85
+ x = x + self.mlp(x)
86
+ return x, attention_probs
87
+
88
+
89
+ class GeGLU(nn.Module):
90
+ def forward(self, x):
91
+ x, gate = x.chunk(2, dim=-1)
92
+ x = x * gelu_new(gate)
93
+ return x
94
+
95
+
96
+ class FeedForward(nn.Module):
97
+ def __init__(self, config):
98
+ super().__init__()
99
+ self.mlp = nn.Sequential(
100
+ nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps, elementwise_affine=False),
101
+ nn.Linear(config.hidden_size, 2*config.intermediate_size, bias=False),
102
+ GeGLU(),
103
+ nn.LayerNorm(config.intermediate_size, eps=config.layer_norm_eps, elementwise_affine=False),
104
+ nn.Linear(config.intermediate_size, config.hidden_size, bias=False),
105
+ nn.Dropout(config.hidden_dropout_prob)
106
+ )
107
+ self.initialize(config.hidden_size)
108
+
109
+ def initialize(self, hidden_size):
110
+ std = math.sqrt(2.0 / (5.0 * hidden_size))
111
+ nn.init.trunc_normal_(self.mlp[1].weight, mean=0.0, std=std, a=-2*std, b=2*std)
112
+ nn.init.trunc_normal_(self.mlp[-2].weight, mean=0.0, std=std, a=-2*std, b=2*std)
113
+
114
+ def forward(self, x):
115
+ return self.mlp(x)
116
+
117
+
118
+ class MaskedSoftmax(torch.autograd.Function):
119
+ @staticmethod
120
+ def forward(self, x, mask, dim):
121
+ self.dim = dim
122
+ x.masked_fill_(mask, float('-inf'))
123
+ x = torch.softmax(x, self.dim)
124
+ x.masked_fill_(mask, 0.0)
125
+ self.save_for_backward(x)
126
+ return x
127
+
128
+ @staticmethod
129
+ def backward(self, grad_output):
130
+ output, = self.saved_tensors
131
+ input_grad = softmax_backward_data(self, grad_output, output, self.dim, output)
132
+ return input_grad, None, None
133
+
134
+
135
+ class Attention(nn.Module):
136
+ def __init__(self, config):
137
+ super().__init__()
138
+
139
+ self.config = config
140
+
141
+ if config.hidden_size % config.num_attention_heads != 0:
142
+ raise ValueError(f"The hidden size {config.hidden_size} is not a multiple of the number of attention heads {config.num_attention_heads}")
143
+
144
+ self.hidden_size = config.hidden_size
145
+ self.num_heads = config.num_attention_heads
146
+ self.head_size = config.hidden_size // config.num_attention_heads
147
+
148
+ self.in_proj_qk = nn.Linear(config.hidden_size, 2*config.hidden_size, bias=True)
149
+ self.in_proj_v = nn.Linear(config.hidden_size, config.hidden_size, bias=True)
150
+ self.out_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=True)
151
+
152
+ self.pre_layer_norm = nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False)
153
+ self.post_layer_norm = nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=True)
154
+
155
+ position_indices = torch.arange(config.max_position_embeddings, dtype=torch.long).unsqueeze(1) \
156
+ - torch.arange(config.max_position_embeddings, dtype=torch.long).unsqueeze(0)
157
+ position_indices = self.make_log_bucket_position(position_indices, config.position_bucket_size, config.max_position_embeddings)
158
+ position_indices = config.position_bucket_size - 1 + position_indices
159
+ self.register_buffer("position_indices", position_indices, persistent=True)
160
+
161
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
162
+ self.scale = 1.0 / math.sqrt(3 * self.head_size)
163
+ self.initialize()
164
+
165
+ def make_log_bucket_position(self, relative_pos, bucket_size, max_position):
166
+ sign = torch.sign(relative_pos)
167
+ mid = bucket_size // 2
168
+ abs_pos = torch.where((relative_pos < mid) & (relative_pos > -mid), mid - 1, torch.abs(relative_pos).clamp(max=max_position - 1))
169
+ log_pos = torch.ceil(torch.log(abs_pos / mid) / math.log((max_position-1) / mid) * (mid - 1)).int() + mid
170
+ bucket_pos = torch.where(abs_pos <= mid, relative_pos, log_pos * sign).long()
171
+ return bucket_pos
172
+
173
+ def initialize(self):
174
+ std = math.sqrt(2.0 / (5.0 * self.hidden_size))
175
+ nn.init.trunc_normal_(self.in_proj_qk.weight, mean=0.0, std=std, a=-2*std, b=2*std)
176
+ nn.init.trunc_normal_(self.in_proj_v.weight, mean=0.0, std=std, a=-2*std, b=2*std)
177
+ nn.init.trunc_normal_(self.out_proj.weight, mean=0.0, std=std, a=-2*std, b=2*std)
178
+ self.in_proj_qk.bias.data.zero_()
179
+ self.in_proj_v.bias.data.zero_()
180
+ self.out_proj.bias.data.zero_()
181
+
182
+ def compute_attention_scores(self, hidden_states, relative_embedding):
183
+ key_len, batch_size, _ = hidden_states.size()
184
+ query_len = key_len
185
+
186
+ if self.position_indices.size(0) < query_len:
187
+ position_indices = torch.arange(query_len, dtype=torch.long).unsqueeze(1) \
188
+ - torch.arange(query_len, dtype=torch.long).unsqueeze(0)
189
+ position_indices = self.make_log_bucket_position(position_indices, self.position_bucket_size, 512)
190
+ position_indices = self.position_bucket_size - 1 + position_indices
191
+ self.position_indices = position_indices.to(hidden_states.device)
192
+
193
+ hidden_states = self.pre_layer_norm(hidden_states)
194
+
195
+ query, key = self.in_proj_qk(hidden_states).chunk(2, dim=2) # shape: [T, B, D]
196
+ value = self.in_proj_v(hidden_states) # shape: [T, B, D]
197
+
198
+ query = query.reshape(query_len, batch_size * self.num_heads, self.head_size).transpose(0, 1)
199
+ key = key.reshape(key_len, batch_size * self.num_heads, self.head_size).transpose(0, 1)
200
+ value = value.view(key_len, batch_size * self.num_heads, self.head_size).transpose(0, 1)
201
+
202
+ attention_scores = torch.bmm(query, key.transpose(1, 2) * self.scale)
203
+
204
+ pos = self.in_proj_qk(self.dropout(relative_embedding)) # shape: [2T-1, 2D]
205
+ query_pos, key_pos = pos.view(-1, self.num_heads, 2*self.head_size).chunk(2, dim=2)
206
+ query = query.view(batch_size, self.num_heads, query_len, self.head_size)
207
+ key = key.view(batch_size, self.num_heads, query_len, self.head_size)
208
+
209
+ attention_c_p = torch.einsum("bhqd,khd->bhqk", query, key_pos.squeeze(1) * self.scale)
210
+ attention_p_c = torch.einsum("bhkd,qhd->bhqk", key * self.scale, query_pos.squeeze(1))
211
+
212
+ position_indices = self.position_indices[:query_len, :key_len].expand(batch_size, self.num_heads, -1, -1)
213
+ attention_c_p = attention_c_p.gather(3, position_indices)
214
+ attention_p_c = attention_p_c.gather(2, position_indices)
215
+
216
+ attention_scores = attention_scores.view(batch_size, self.num_heads, query_len, key_len)
217
+ attention_scores.add_(attention_c_p)
218
+ attention_scores.add_(attention_p_c)
219
+
220
+ return attention_scores, value
221
+
222
+ def compute_output(self, attention_probs, value):
223
+ attention_probs = self.dropout(attention_probs)
224
+ context = torch.bmm(attention_probs.flatten(0, 1), value) # shape: [B*H, Q, D]
225
+ context = context.transpose(0, 1).reshape(context.size(1), -1, self.hidden_size) # shape: [Q, B, H*D]
226
+ context = self.out_proj(context)
227
+ context = self.post_layer_norm(context)
228
+ context = self.dropout(context)
229
+ return context
230
+
231
+ def forward(self, hidden_states, attention_mask, relative_embedding):
232
+ attention_scores, value = self.compute_attention_scores(hidden_states, relative_embedding)
233
+ attention_probs = MaskedSoftmax.apply(attention_scores, attention_mask, -1)
234
+ return self.compute_output(attention_probs, value), attention_probs.detach()
235
+
236
+
237
+ class Embedding(nn.Module):
238
+ def __init__(self, config):
239
+ super().__init__()
240
+ self.hidden_size = config.hidden_size
241
+
242
+ self.word_embedding = nn.Embedding(config.vocab_size, config.hidden_size)
243
+ self.word_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps, elementwise_affine=False)
244
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
245
+
246
+ self.relative_embedding = nn.Parameter(torch.empty(2 * config.position_bucket_size - 1, config.hidden_size))
247
+ self.relative_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
248
+
249
+ self.initialize()
250
+
251
+ def initialize(self):
252
+ std = math.sqrt(2.0 / (5.0 * self.hidden_size))
253
+ nn.init.trunc_normal_(self.relative_embedding, mean=0.0, std=std, a=-2*std, b=2*std)
254
+ nn.init.trunc_normal_(self.word_embedding.weight, mean=0.0, std=std, a=-2*std, b=2*std)
255
+
256
+ def forward(self, input_ids):
257
+ word_embedding = self.dropout(self.word_layer_norm(self.word_embedding(input_ids)))
258
+ relative_embeddings = self.relative_layer_norm(self.relative_embedding)
259
+ return word_embedding, relative_embeddings
260
+
261
+
262
+ #
263
+ # HuggingFace wrappers
264
+ #
265
+
266
+ class NorbertPreTrainedModel(PreTrainedModel):
267
+ config_class = NorbertConfig
268
+ base_model_prefix = "norbert3"
269
+ supports_gradient_checkpointing = True
270
+
271
+ def _set_gradient_checkpointing(self, module, value=False):
272
+ if isinstance(module, Encoder):
273
+ module.activation_checkpointing = value
274
+
275
+ def _init_weights(self, module):
276
+ pass # everything is already initialized
277
+
278
+
279
+ class NorbertModel(NorbertPreTrainedModel):
280
+ def __init__(self, config, add_mlm_layer=False, gradient_checkpointing=False, **kwargs):
281
+ super().__init__(config, **kwargs)
282
+ self.config = config
283
+
284
+ self.embedding = Embedding(config)
285
+ self.transformer = Encoder(config, activation_checkpointing=gradient_checkpointing)
286
+ self.classifier = MaskClassifier(config, self.embedding.word_embedding.weight) if add_mlm_layer else None
287
+
288
+ def get_input_embeddings(self):
289
+ return self.embedding.word_embedding
290
+
291
+ def set_input_embeddings(self, value):
292
+ self.embedding.word_embedding = value
293
+
294
+ def get_contextualized_embeddings(
295
+ self,
296
+ input_ids: Optional[torch.Tensor] = None,
297
+ attention_mask: Optional[torch.Tensor] = None
298
+ ) -> List[torch.Tensor]:
299
+ if input_ids is not None:
300
+ input_shape = input_ids.size()
301
+ else:
302
+ raise ValueError("You have to specify input_ids")
303
+
304
+ batch_size, seq_length = input_shape
305
+ device = input_ids.device
306
+
307
+ if attention_mask is None:
308
+ attention_mask = torch.zeros(batch_size, seq_length, dtype=torch.bool, device=device)
309
+ else:
310
+ attention_mask = ~attention_mask.bool()
311
+ attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
312
+
313
+ static_embeddings, relative_embedding = self.embedding(input_ids.t())
314
+ contextualized_embeddings, attention_probs = self.transformer(static_embeddings, attention_mask, relative_embedding)
315
+ contextualized_embeddings = [e.transpose(0, 1) for e in contextualized_embeddings]
316
+ last_layer = contextualized_embeddings[-1]
317
+ contextualized_embeddings = [contextualized_embeddings[0]] + [
318
+ contextualized_embeddings[i] - contextualized_embeddings[i - 1]
319
+ for i in range(1, len(contextualized_embeddings))
320
+ ]
321
+ return last_layer, contextualized_embeddings, attention_probs
322
+
323
+ def forward(
324
+ self,
325
+ input_ids: Optional[torch.Tensor] = None,
326
+ attention_mask: Optional[torch.Tensor] = None,
327
+ token_type_ids: Optional[torch.Tensor] = None,
328
+ position_ids: Optional[torch.Tensor] = None,
329
+ output_hidden_states: Optional[bool] = None,
330
+ output_attentions: Optional[bool] = None,
331
+ return_dict: Optional[bool] = None,
332
+ **kwargs
333
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutput]:
334
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
335
+
336
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
337
+
338
+ if not return_dict:
339
+ return (
340
+ sequence_output,
341
+ *([contextualized_embeddings] if output_hidden_states else []),
342
+ *([attention_probs] if output_attentions else [])
343
+ )
344
+
345
+ return BaseModelOutput(
346
+ last_hidden_state=sequence_output,
347
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
348
+ attentions=attention_probs if output_attentions else None
349
+ )
350
+
351
+
352
+ class NorbertForMaskedLM(NorbertModel):
353
+ _keys_to_ignore_on_load_unexpected = ["head"]
354
+
355
+ def __init__(self, config, **kwargs):
356
+ super().__init__(config, add_mlm_layer=True, **kwargs)
357
+
358
+ def get_output_embeddings(self):
359
+ return self.classifier.nonlinearity[-1].weight
360
+
361
+ def set_output_embeddings(self, new_embeddings):
362
+ self.classifier.nonlinearity[-1].weight = new_embeddings
363
+
364
+ def forward(
365
+ self,
366
+ input_ids: Optional[torch.Tensor] = None,
367
+ attention_mask: Optional[torch.Tensor] = None,
368
+ token_type_ids: Optional[torch.Tensor] = None,
369
+ position_ids: Optional[torch.Tensor] = None,
370
+ output_hidden_states: Optional[bool] = None,
371
+ output_attentions: Optional[bool] = None,
372
+ return_dict: Optional[bool] = None,
373
+ labels: Optional[torch.LongTensor] = None,
374
+ **kwargs
375
+ ) -> Union[Tuple[torch.Tensor], MaskedLMOutput]:
376
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
377
+
378
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
379
+ subword_prediction = self.classifier(sequence_output)
380
+ subword_prediction[:, :, :106+1] = float("-inf")
381
+
382
+ masked_lm_loss = None
383
+ if labels is not None:
384
+ masked_lm_loss = F.cross_entropy(subword_prediction.flatten(0, 1), labels.flatten())
385
+
386
+ if not return_dict:
387
+ output = (
388
+ subword_prediction,
389
+ *([contextualized_embeddings] if output_hidden_states else []),
390
+ *([attention_probs] if output_attentions else [])
391
+ )
392
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
393
+
394
+ return MaskedLMOutput(
395
+ loss=masked_lm_loss,
396
+ logits=subword_prediction,
397
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
398
+ attentions=attention_probs if output_attentions else None
399
+ )
400
+
401
+
402
+ class Classifier(nn.Module):
403
+ def __init__(self, config, num_labels: int):
404
+ super().__init__()
405
+
406
+ drop_out = getattr(config, "cls_dropout", None)
407
+ drop_out = config.hidden_dropout_prob if drop_out is None else drop_out
408
+
409
+ self.nonlinearity = nn.Sequential(
410
+ nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False),
411
+ nn.Linear(config.hidden_size, config.hidden_size),
412
+ nn.GELU(),
413
+ nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False),
414
+ nn.Dropout(drop_out),
415
+ nn.Linear(config.hidden_size, num_labels)
416
+ )
417
+ self.initialize(config.hidden_size)
418
+
419
+ def initialize(self, hidden_size):
420
+ std = math.sqrt(2.0 / (5.0 * hidden_size))
421
+ nn.init.trunc_normal_(self.nonlinearity[1].weight, mean=0.0, std=std, a=-2*std, b=2*std)
422
+ nn.init.trunc_normal_(self.nonlinearity[-1].weight, mean=0.0, std=std, a=-2*std, b=2*std)
423
+ self.nonlinearity[1].bias.data.zero_()
424
+ self.nonlinearity[-1].bias.data.zero_()
425
+
426
+ def forward(self, x):
427
+ x = self.nonlinearity(x)
428
+ return x
429
+
430
+
431
+ class NorbertForSequenceClassification(NorbertModel):
432
+ _keys_to_ignore_on_load_unexpected = ["classifier"]
433
+ _keys_to_ignore_on_load_missing = ["head"]
434
+
435
+ def __init__(self, config, **kwargs):
436
+ super().__init__(config, add_mlm_layer=False, **kwargs)
437
+
438
+ self.num_labels = config.num_labels
439
+ self.head = Classifier(config, self.num_labels)
440
+
441
+ def forward(
442
+ self,
443
+ input_ids: Optional[torch.Tensor] = None,
444
+ attention_mask: Optional[torch.Tensor] = None,
445
+ token_type_ids: Optional[torch.Tensor] = None,
446
+ position_ids: Optional[torch.Tensor] = None,
447
+ output_attentions: Optional[bool] = None,
448
+ output_hidden_states: Optional[bool] = None,
449
+ return_dict: Optional[bool] = None,
450
+ labels: Optional[torch.LongTensor] = None,
451
+ **kwargs
452
+ ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
453
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
454
+
455
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
456
+ logits = self.head(sequence_output[:, 0, :])
457
+
458
+ loss = None
459
+ if labels is not None:
460
+ if self.config.problem_type is None:
461
+ if self.num_labels == 1:
462
+ self.config.problem_type = "regression"
463
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
464
+ self.config.problem_type = "single_label_classification"
465
+ else:
466
+ self.config.problem_type = "multi_label_classification"
467
+
468
+ if self.config.problem_type == "regression":
469
+ loss_fct = nn.MSELoss()
470
+ if self.num_labels == 1:
471
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
472
+ else:
473
+ loss = loss_fct(logits, labels)
474
+ elif self.config.problem_type == "single_label_classification":
475
+ loss_fct = nn.CrossEntropyLoss()
476
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
477
+ elif self.config.problem_type == "multi_label_classification":
478
+ loss_fct = nn.BCEWithLogitsLoss()
479
+ loss = loss_fct(logits, labels)
480
+
481
+ if not return_dict:
482
+ output = (
483
+ logits,
484
+ *([contextualized_embeddings] if output_hidden_states else []),
485
+ *([attention_probs] if output_attentions else [])
486
+ )
487
+ return ((loss,) + output) if loss is not None else output
488
+
489
+ return SequenceClassifierOutput(
490
+ loss=loss,
491
+ logits=logits,
492
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
493
+ attentions=attention_probs if output_attentions else None
494
+ )
495
+
496
+
497
+ class NorbertForTokenClassification(NorbertModel):
498
+ _keys_to_ignore_on_load_unexpected = ["classifier"]
499
+ _keys_to_ignore_on_load_missing = ["head"]
500
+
501
+ def __init__(self, config, **kwargs):
502
+ super().__init__(config, add_mlm_layer=False, **kwargs)
503
+
504
+ self.num_labels = config.num_labels
505
+ self.head = Classifier(config, self.num_labels)
506
+
507
+ def forward(
508
+ self,
509
+ input_ids: Optional[torch.Tensor] = None,
510
+ attention_mask: Optional[torch.Tensor] = None,
511
+ token_type_ids: Optional[torch.Tensor] = None,
512
+ position_ids: Optional[torch.Tensor] = None,
513
+ output_attentions: Optional[bool] = None,
514
+ output_hidden_states: Optional[bool] = None,
515
+ return_dict: Optional[bool] = None,
516
+ labels: Optional[torch.LongTensor] = None,
517
+ **kwargs
518
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
519
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
520
+
521
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
522
+ logits = self.head(sequence_output)
523
+
524
+ loss = None
525
+ if labels is not None:
526
+ loss_fct = nn.CrossEntropyLoss()
527
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
528
+
529
+ if not return_dict:
530
+ output = (
531
+ logits,
532
+ *([contextualized_embeddings] if output_hidden_states else []),
533
+ *([attention_probs] if output_attentions else [])
534
+ )
535
+ return ((loss,) + output) if loss is not None else output
536
+
537
+ return TokenClassifierOutput(
538
+ loss=loss,
539
+ logits=logits,
540
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
541
+ attentions=attention_probs if output_attentions else None
542
+ )
543
+
544
+
545
+ class NorbertForQuestionAnswering(NorbertModel):
546
+ _keys_to_ignore_on_load_unexpected = ["classifier"]
547
+ _keys_to_ignore_on_load_missing = ["head"]
548
+
549
+ def __init__(self, config, **kwargs):
550
+ super().__init__(config, add_mlm_layer=False, **kwargs)
551
+
552
+ self.num_labels = config.num_labels
553
+ self.head = Classifier(config, self.num_labels)
554
+
555
+ def forward(
556
+ self,
557
+ input_ids: Optional[torch.Tensor] = None,
558
+ attention_mask: Optional[torch.Tensor] = None,
559
+ token_type_ids: Optional[torch.Tensor] = None,
560
+ position_ids: Optional[torch.Tensor] = None,
561
+ output_attentions: Optional[bool] = None,
562
+ output_hidden_states: Optional[bool] = None,
563
+ return_dict: Optional[bool] = None,
564
+ start_positions: Optional[torch.Tensor] = None,
565
+ end_positions: Optional[torch.Tensor] = None,
566
+ **kwargs
567
+ ) -> Union[Tuple[torch.Tensor], QuestionAnsweringModelOutput]:
568
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
569
+
570
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
571
+ logits = self.head(sequence_output)
572
+
573
+ start_logits, end_logits = logits.split(1, dim=-1)
574
+ start_logits = start_logits.squeeze(-1).contiguous()
575
+ end_logits = end_logits.squeeze(-1).contiguous()
576
+
577
+ total_loss = None
578
+ if start_positions is not None and end_positions is not None:
579
+ # If we are on multi-GPU, split add a dimension
580
+ if len(start_positions.size()) > 1:
581
+ start_positions = start_positions.squeeze(-1)
582
+ if len(end_positions.size()) > 1:
583
+ end_positions = end_positions.squeeze(-1)
584
+
585
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
586
+ ignored_index = start_logits.size(1)
587
+ start_positions = start_positions.clamp(0, ignored_index)
588
+ end_positions = end_positions.clamp(0, ignored_index)
589
+
590
+ loss_fct = nn.CrossEntropyLoss(ignore_index=ignored_index)
591
+ start_loss = loss_fct(start_logits, start_positions)
592
+ end_loss = loss_fct(end_logits, end_positions)
593
+ total_loss = (start_loss + end_loss) / 2
594
+
595
+ if not return_dict:
596
+ output = (
597
+ start_logits,
598
+ end_logits,
599
+ *([contextualized_embeddings] if output_hidden_states else []),
600
+ *([attention_probs] if output_attentions else [])
601
+ )
602
+ return ((total_loss,) + output) if total_loss is not None else output
603
+
604
+ return QuestionAnsweringModelOutput(
605
+ loss=total_loss,
606
+ start_logits=start_logits,
607
+ end_logits=end_logits,
608
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
609
+ attentions=attention_probs if output_attentions else None
610
+ )
611
+
612
+
613
+ class NorbertForMultipleChoice(NorbertModel):
614
+ _keys_to_ignore_on_load_unexpected = ["classifier"]
615
+ _keys_to_ignore_on_load_missing = ["head"]
616
+
617
+ def __init__(self, config, **kwargs):
618
+ super().__init__(config, add_mlm_layer=False, **kwargs)
619
+
620
+ self.num_labels = getattr(config, "num_labels", 2)
621
+ self.head = Classifier(config, self.num_labels)
622
+
623
+ def forward(
624
+ self,
625
+ input_ids: Optional[torch.Tensor] = None,
626
+ attention_mask: Optional[torch.Tensor] = None,
627
+ token_type_ids: Optional[torch.Tensor] = None,
628
+ position_ids: Optional[torch.Tensor] = None,
629
+ labels: Optional[torch.Tensor] = None,
630
+ output_attentions: Optional[bool] = None,
631
+ output_hidden_states: Optional[bool] = None,
632
+ return_dict: Optional[bool] = None,
633
+ **kwargs
634
+ ) -> Union[Tuple[torch.Tensor], MultipleChoiceModelOutput]:
635
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
636
+ num_choices = input_ids.shape[1]
637
+
638
+ flat_input_ids = input_ids.view(-1, input_ids.size(-1))
639
+ flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
640
+
641
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(flat_input_ids, flat_attention_mask)
642
+ logits = self.head(sequence_output)
643
+ reshaped_logits = logits.view(-1, num_choices)
644
+
645
+ loss = None
646
+ if labels is not None:
647
+ loss_fct = nn.CrossEntropyLoss()
648
+ loss = loss_fct(reshaped_logits, labels)
649
+
650
+ if not return_dict:
651
+ output = (
652
+ reshaped_logits,
653
+ *([contextualized_embeddings] if output_hidden_states else []),
654
+ *([attention_probs] if output_attentions else [])
655
+ )
656
+ return ((loss,) + output) if loss is not None else output
657
+
658
+ return MultipleChoiceModelOutput(
659
+ loss=loss,
660
+ logits=reshaped_logits,
661
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
662
+ attentions=attention_probs if output_attentions else None
663
+ )