liljacharlotte commited on
Commit
5f6271c
·
verified ·
1 Parent(s): 2abab41

Upload modeling_norbert.py

Browse files
Files changed (1) hide show
  1. modeling_norbert.py +615 -0
modeling_norbert.py ADDED
@@ -0,0 +1,615 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.modeling_outputs import (
12
+ MaskedLMOutput,
13
+ MultipleChoiceModelOutput,
14
+ QuestionAnsweringModelOutput,
15
+ SequenceClassifierOutput,
16
+ TokenClassifierOutput,
17
+ BaseModelOutput
18
+ )
19
+
20
+
21
+ class Encoder(nn.Module):
22
+ def __init__(self, config, activation_checkpointing=False):
23
+ super().__init__()
24
+ self.layers = nn.ModuleList([EncoderLayer(config) for _ in range(config.num_hidden_layers)])
25
+ self.activation_checkpointing = activation_checkpointing
26
+
27
+ def forward(self, hidden_states, attention_mask, relative_embedding):
28
+ hidden_states, attention_probs = [hidden_states], []
29
+
30
+ for layer in self.layers:
31
+ if self.activation_checkpointing:
32
+ hidden_state, attention_p = checkpoint.checkpoint(layer, hidden_states[-1], attention_mask, relative_embedding)
33
+ else:
34
+ hidden_state, attention_p = layer(hidden_states[-1], attention_mask, relative_embedding)
35
+
36
+ hidden_states.append(hidden_state)
37
+ attention_probs.append(attention_p)
38
+
39
+ return hidden_states, attention_probs
40
+
41
+
42
+ class MaskClassifier(nn.Module):
43
+ def __init__(self, config, subword_embedding):
44
+ super().__init__()
45
+ self.nonlinearity = nn.Sequential(
46
+ nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False),
47
+ nn.Linear(config.hidden_size, config.hidden_size),
48
+ nn.GELU(),
49
+ nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False),
50
+ nn.Dropout(config.hidden_dropout_prob),
51
+ nn.Linear(subword_embedding.size(1), subword_embedding.size(0))
52
+ )
53
+
54
+ def forward(self, x, masked_lm_labels=None):
55
+ if masked_lm_labels is not None:
56
+ x = torch.index_select(x.flatten(0, 1), 0, torch.nonzero(masked_lm_labels.flatten() != -100).squeeze())
57
+ x = self.nonlinearity(x)
58
+ return x
59
+
60
+
61
+ class EncoderLayer(nn.Module):
62
+ def __init__(self, config):
63
+ super().__init__()
64
+ self.attention = Attention(config)
65
+ self.mlp = FeedForward(config)
66
+
67
+ def forward(self, x, padding_mask, relative_embedding):
68
+ attention_output, attention_probs = self.attention(x, padding_mask, relative_embedding)
69
+ x = x + attention_output
70
+ x = x + self.mlp(x)
71
+ return x, attention_probs
72
+
73
+
74
+ class GeGLU(nn.Module):
75
+ def forward(self, x):
76
+ x, gate = x.chunk(2, dim=-1)
77
+ x = x * F.gelu(gate, approximate="tanh")
78
+ return x
79
+
80
+
81
+ class FeedForward(nn.Module):
82
+ def __init__(self, config):
83
+ super().__init__()
84
+ self.mlp = nn.Sequential(
85
+ nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps, elementwise_affine=False),
86
+ nn.Linear(config.hidden_size, 2*config.intermediate_size, bias=False),
87
+ GeGLU(),
88
+ nn.LayerNorm(config.intermediate_size, eps=config.layer_norm_eps, elementwise_affine=False),
89
+ nn.Linear(config.intermediate_size, config.hidden_size, bias=False),
90
+ nn.Dropout(config.hidden_dropout_prob)
91
+ )
92
+
93
+ def forward(self, x):
94
+ return self.mlp(x)
95
+
96
+
97
+ class Attention(nn.Module):
98
+ def __init__(self, config):
99
+ super().__init__()
100
+
101
+ self.config = config
102
+
103
+ if config.hidden_size % config.num_attention_heads != 0:
104
+ raise ValueError(f"The hidden size {config.hidden_size} is not a multiple of the number of attention heads {config.num_attention_heads}")
105
+
106
+ self.hidden_size = config.hidden_size
107
+ self.num_heads = config.num_attention_heads
108
+ self.head_size = config.hidden_size // config.num_attention_heads
109
+
110
+ self.in_proj_qk = nn.Linear(config.hidden_size, 2*config.hidden_size, bias=True)
111
+ self.in_proj_v = nn.Linear(config.hidden_size, config.hidden_size, bias=True)
112
+ self.out_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=True)
113
+
114
+ self.pre_layer_norm = nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False)
115
+ self.post_layer_norm = nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=True)
116
+
117
+ self.position_indices = None
118
+
119
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
120
+ self.scale = 1.0 / math.sqrt(3 * self.head_size)
121
+
122
+ def make_log_bucket_position(self, relative_pos, bucket_size, max_position):
123
+ sign = torch.sign(relative_pos)
124
+ mid = bucket_size // 2
125
+ abs_pos = torch.where((relative_pos < mid) & (relative_pos > -mid), mid - 1, torch.abs(relative_pos).clamp(max=max_position - 1))
126
+ log_pos = torch.ceil(torch.log(abs_pos / mid) / math.log((max_position-1) / mid) * (mid - 1)).int() + mid
127
+ bucket_pos = torch.where(abs_pos <= mid, relative_pos, log_pos * sign).long()
128
+ return bucket_pos
129
+
130
+ def forward(self, hidden_states, attention_mask, relative_embedding):
131
+ batch_size, key_len, _ = hidden_states.size()
132
+ query_len = key_len
133
+
134
+ # Recompute position_indices at the beginning or if sequence length exceeds the precomputed size
135
+ if self.position_indices is None or self.position_indices.size(0) < query_len:
136
+ self.position_indices = torch.arange(query_len, dtype=torch.long).unsqueeze(1) \
137
+ - torch.arange(query_len, dtype=torch.long).unsqueeze(0)
138
+ self.position_indices = self.make_log_bucket_position(self.position_indices, self.config.position_bucket_size, 512)
139
+ self.position_indices = self.config.position_bucket_size - 1 + self.position_indices
140
+ if self.position_indices.device != hidden_states.device:
141
+ self.position_indices = self.position_indices.to(hidden_states.device)
142
+
143
+ # Pre-LN and project query/key/value.
144
+ hidden_states = self.pre_layer_norm(hidden_states) # shape: [B, T, D]
145
+ query, key = self.in_proj_qk(hidden_states).chunk(2, dim=-1) # shape: [B, T, D]
146
+ value = self.in_proj_v(hidden_states) # shape: [B, T, D]
147
+
148
+ # Reshape to [B, num_heads, T, head_size]
149
+ query = query.view(batch_size, query_len, self.num_heads, self.head_size).transpose(1, 2) # shape: [B, num_heads, T_q, head_size]
150
+ key = key.view(batch_size, key_len, self.num_heads, self.head_size).permute(0, 2, 3, 1) # shape: [B, num_heads, head_size, T_k]
151
+ value = value.view(batch_size, key_len, self.num_heads, self.head_size).transpose(1, 2) # shape: [B, num_heads, T_k, head_size]
152
+
153
+ # Compute relative positional contributions
154
+ pos = self.in_proj_qk(self.dropout(relative_embedding)) # shape: [2*position_bucket_size - 1, 2D]
155
+ query_pos, key_pos = pos.view(-1, self.num_heads, 2*self.head_size).chunk(2, dim=2) # shape: [2*position_bucket_size - 1, num_heads, head_size]
156
+ query_pos = query_pos.transpose(0, 1) # shape: [num_heads, 2*position_bucket_size - 1, head_size]
157
+ key_pos = key_pos.permute(1, 2, 0) # shape: [num_heads, head_size, 2*position_bucket_size - 1]
158
+
159
+ # Scale the keys
160
+ key = key * self.scale
161
+ key_pos = key_pos * self.scale
162
+
163
+ # Compute standard content-to-content attention scores
164
+ attention_c_to_c = torch.matmul(query, key) # shape: [B, num_heads, T_q, T_k]
165
+
166
+ # Compute content-to-position and position-to-content attention scores
167
+ position_indices = self.position_indices[:query_len, :key_len].expand(batch_size, self.num_heads, -1, -1) # shape: [B, num_heads, T_q, T_k]
168
+ attention_c_to_p = torch.matmul(query, key_pos.unsqueeze(0)) # shape: [B, num_heads, T_q, 2*position_bucket_size - 1]
169
+ attention_p_to_c = torch.matmul(query_pos.unsqueeze(0), key) # shape: [B, num_heads, 2*position_bucket_size - 1, T_k]
170
+ attention_c_to_p = attention_c_to_p.gather(3, position_indices) # shape: [B, num_heads, T_q, T_k]
171
+ attention_p_to_c = attention_p_to_c.gather(2, position_indices) # shape: [B, num_heads, T_q, T_k]
172
+
173
+ # Full attention score
174
+ attention_scores = attention_c_to_c + attention_c_to_p + attention_p_to_c # shape: [B, num_heads, T_q, T_k]
175
+
176
+ # Masked softmax
177
+ attention_scores = attention_scores.masked_fill(attention_mask, float('-inf')) # shape: [B, num_heads, T_q, T_k]
178
+ attention_probs = F.softmax(attention_scores, dim=-1) # shape: [B, num_heads, T_q, T_k]
179
+
180
+ # Collect the weighted-averaged values
181
+ attention_probs = self.dropout(attention_probs) # shape: [B, num_heads, T_q, T_k]
182
+ output = torch.matmul(attention_probs, value) # shape: [B, num_heads, T_q, head_size]
183
+ output = output.transpose(1, 2).flatten(2, 3) # shape: [B, T_q, D]
184
+ output = self.out_proj(output)
185
+ output = self.post_layer_norm(output)
186
+ output = self.dropout(output)
187
+
188
+ return output, attention_probs.detach()
189
+
190
+
191
+ class Embedding(nn.Module):
192
+ def __init__(self, config):
193
+ super().__init__()
194
+ self.hidden_size = config.hidden_size
195
+
196
+ self.word_embedding = nn.Embedding(config.vocab_size, config.hidden_size)
197
+ self.word_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps, elementwise_affine=False)
198
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
199
+
200
+ self.relative_embedding = nn.Parameter(torch.empty(2 * config.position_bucket_size - 1, config.hidden_size))
201
+ self.relative_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
202
+
203
+ def forward(self, input_ids):
204
+ word_embedding = self.dropout(self.word_layer_norm(self.word_embedding(input_ids)))
205
+ relative_embeddings = self.relative_layer_norm(self.relative_embedding)
206
+ return word_embedding, relative_embeddings
207
+
208
+
209
+ #
210
+ # HuggingFace wrappers
211
+ #
212
+
213
+ class NorbertPreTrainedModel(PreTrainedModel):
214
+ config_class = NorbertConfig
215
+ base_model_prefix = "norbert3"
216
+ supports_gradient_checkpointing = True
217
+ _tied_weights_keys = {}
218
+ _keys_to_ignore_on_load_unexpected = [r".*position_indices.*"]
219
+
220
+ def _set_gradient_checkpointing(self, module, value=False):
221
+ if isinstance(module, Encoder):
222
+ module.activation_checkpointing = value
223
+
224
+ def _init_weights(self, module):
225
+ std = math.sqrt(2.0 / (5.0 * self.hidden_size))
226
+
227
+ if isinstance(module, nn.Linear) or isinstance(module, nn.Embedding):
228
+ nn.init.trunc_normal_(module.weight, mean=0.0, std=std, a=-2*std, b=2*std)
229
+ elif isinstance(module, nn.LayerNorm) and module.weight is not None:
230
+ nn.init.ones_(module.weight)
231
+ if hasattr(module, "bias") and module.bias is not None:
232
+ nn.init.zeros_(module.bias)
233
+
234
+
235
+ class NorbertModel(NorbertPreTrainedModel):
236
+ def __init__(self, config, add_mlm_layer=False, gradient_checkpointing=False, **kwargs):
237
+ super().__init__(config, **kwargs)
238
+ self.config = config
239
+ self.hidden_size = config.hidden_size
240
+
241
+ self.embedding = Embedding(config)
242
+ self.transformer = Encoder(config, activation_checkpointing=gradient_checkpointing)
243
+ self.classifier = MaskClassifier(config, self.embedding.word_embedding.weight) if add_mlm_layer else None
244
+
245
+ self.post_init()
246
+
247
+ def get_input_embeddings(self):
248
+ return self.embedding.word_embedding
249
+
250
+ def set_input_embeddings(self, value):
251
+ self.embedding.word_embedding = value
252
+
253
+ def get_contextualized_embeddings(
254
+ self,
255
+ input_ids: Optional[torch.Tensor] = None,
256
+ attention_mask: Optional[torch.Tensor] = None
257
+ ) -> List[torch.Tensor]:
258
+ if input_ids is not None:
259
+ input_shape = input_ids.size()
260
+ else:
261
+ raise ValueError("You have to specify input_ids")
262
+
263
+ batch_size, seq_length = input_shape
264
+ device = input_ids.device
265
+
266
+ if attention_mask is None:
267
+ attention_mask = torch.zeros(batch_size, seq_length, dtype=torch.bool, device=device)
268
+ else:
269
+ attention_mask = ~attention_mask.bool()
270
+ attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
271
+
272
+ static_embeddings, relative_embedding = self.embedding(input_ids)
273
+ contextualized_embeddings, attention_probs = self.transformer(static_embeddings, attention_mask, relative_embedding)
274
+ last_layer = contextualized_embeddings[-1]
275
+ contextualized_embeddings = [contextualized_embeddings[0]] + [
276
+ contextualized_embeddings[i] - contextualized_embeddings[i - 1]
277
+ for i in range(1, len(contextualized_embeddings))
278
+ ]
279
+ return last_layer, contextualized_embeddings, attention_probs
280
+
281
+ def forward(
282
+ self,
283
+ input_ids: Optional[torch.Tensor] = None,
284
+ attention_mask: Optional[torch.Tensor] = None,
285
+ token_type_ids: Optional[torch.Tensor] = None,
286
+ position_ids: Optional[torch.Tensor] = None,
287
+ output_hidden_states: Optional[bool] = None,
288
+ output_attentions: Optional[bool] = None,
289
+ return_dict: Optional[bool] = None,
290
+ **kwargs
291
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutput]:
292
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
293
+
294
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
295
+
296
+ if not return_dict:
297
+ return (
298
+ sequence_output,
299
+ *([contextualized_embeddings] if output_hidden_states else []),
300
+ *([attention_probs] if output_attentions else [])
301
+ )
302
+
303
+ return BaseModelOutput(
304
+ last_hidden_state=sequence_output,
305
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
306
+ attentions=attention_probs if output_attentions else None
307
+ )
308
+
309
+
310
+ class NorbertForMaskedLM(NorbertModel):
311
+ _keys_to_ignore_on_load_unexpected = ["head", r".*position_indices.*"]
312
+ _tied_weights_keys = {"classifier.nonlinearity.5.weight": "embedding.word_embedding.weight"}
313
+
314
+ def __init__(self, config, **kwargs):
315
+ super().__init__(config, add_mlm_layer=True, **kwargs)
316
+ self.post_init()
317
+
318
+ def get_output_embeddings(self):
319
+ return self.classifier.nonlinearity[-1]
320
+
321
+ def set_output_embeddings(self, new_embeddings):
322
+ self.classifier.nonlinearity[-1] = new_embeddings
323
+
324
+ def forward(
325
+ self,
326
+ input_ids: Optional[torch.Tensor] = None,
327
+ attention_mask: Optional[torch.Tensor] = None,
328
+ token_type_ids: Optional[torch.Tensor] = None,
329
+ position_ids: Optional[torch.Tensor] = None,
330
+ output_hidden_states: Optional[bool] = None,
331
+ output_attentions: Optional[bool] = None,
332
+ return_dict: Optional[bool] = None,
333
+ labels: Optional[torch.LongTensor] = None,
334
+ **kwargs
335
+ ) -> Union[Tuple[torch.Tensor], MaskedLMOutput]:
336
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
337
+
338
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
339
+ subword_prediction = self.classifier(sequence_output)
340
+ subword_prediction[:, :, :106+1] = float("-inf")
341
+
342
+ masked_lm_loss = None
343
+ if labels is not None:
344
+ masked_lm_loss = F.cross_entropy(subword_prediction.flatten(0, 1), labels.flatten())
345
+
346
+ if not return_dict:
347
+ output = (
348
+ subword_prediction,
349
+ *([contextualized_embeddings] if output_hidden_states else []),
350
+ *([attention_probs] if output_attentions else [])
351
+ )
352
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
353
+
354
+ return MaskedLMOutput(
355
+ loss=masked_lm_loss,
356
+ logits=subword_prediction,
357
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
358
+ attentions=attention_probs if output_attentions else None
359
+ )
360
+
361
+
362
+ class Classifier(nn.Module):
363
+ def __init__(self, config, num_labels: int):
364
+ super().__init__()
365
+
366
+ drop_out = getattr(config, "cls_dropout", None)
367
+ drop_out = config.hidden_dropout_prob if drop_out is None else drop_out
368
+
369
+ self.nonlinearity = nn.Sequential(
370
+ nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False),
371
+ nn.Linear(config.hidden_size, config.hidden_size),
372
+ nn.GELU(),
373
+ nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False),
374
+ nn.Dropout(drop_out),
375
+ nn.Linear(config.hidden_size, num_labels)
376
+ )
377
+
378
+ def forward(self, x):
379
+ x = self.nonlinearity(x)
380
+ return x
381
+
382
+
383
+ class NorbertForSequenceClassification(NorbertModel):
384
+ _keys_to_ignore_on_load_unexpected = ["classifier", r".*position_indices.*"]
385
+
386
+ def __init__(self, config, **kwargs):
387
+ super().__init__(config, add_mlm_layer=False, **kwargs)
388
+
389
+ self.num_labels = config.num_labels
390
+ self.head = Classifier(config, self.num_labels)
391
+ self.post_init()
392
+
393
+ def forward(
394
+ self,
395
+ input_ids: Optional[torch.Tensor] = None,
396
+ attention_mask: Optional[torch.Tensor] = None,
397
+ token_type_ids: Optional[torch.Tensor] = None,
398
+ position_ids: Optional[torch.Tensor] = None,
399
+ output_attentions: Optional[bool] = None,
400
+ output_hidden_states: Optional[bool] = None,
401
+ return_dict: Optional[bool] = None,
402
+ labels: Optional[torch.LongTensor] = None,
403
+ **kwargs
404
+ ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
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
+ logits = self.head(sequence_output[:, 0, :])
409
+
410
+ loss = None
411
+ if labels is not None:
412
+ if self.config.problem_type is None:
413
+ if self.num_labels == 1:
414
+ self.config.problem_type = "regression"
415
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
416
+ self.config.problem_type = "single_label_classification"
417
+ else:
418
+ self.config.problem_type = "multi_label_classification"
419
+
420
+ if self.config.problem_type == "regression":
421
+ loss_fct = nn.MSELoss()
422
+ if self.num_labels == 1:
423
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
424
+ else:
425
+ loss = loss_fct(logits, labels)
426
+ elif self.config.problem_type == "single_label_classification":
427
+ loss_fct = nn.CrossEntropyLoss()
428
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
429
+ elif self.config.problem_type == "multi_label_classification":
430
+ loss_fct = nn.BCEWithLogitsLoss()
431
+ loss = loss_fct(logits, labels)
432
+
433
+ if not return_dict:
434
+ output = (
435
+ logits,
436
+ *([contextualized_embeddings] if output_hidden_states else []),
437
+ *([attention_probs] if output_attentions else [])
438
+ )
439
+ return ((loss,) + output) if loss is not None else output
440
+
441
+ return SequenceClassifierOutput(
442
+ loss=loss,
443
+ logits=logits,
444
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
445
+ attentions=attention_probs if output_attentions else None
446
+ )
447
+
448
+
449
+ class NorbertForTokenClassification(NorbertModel):
450
+ _keys_to_ignore_on_load_unexpected = ["classifier", r".*position_indices.*"]
451
+
452
+ def __init__(self, config, **kwargs):
453
+ super().__init__(config, add_mlm_layer=False, **kwargs)
454
+
455
+ self.num_labels = config.num_labels
456
+ self.head = Classifier(config, self.num_labels)
457
+ self.post_init()
458
+
459
+ def forward(
460
+ self,
461
+ input_ids: Optional[torch.Tensor] = None,
462
+ attention_mask: Optional[torch.Tensor] = None,
463
+ token_type_ids: Optional[torch.Tensor] = None,
464
+ position_ids: Optional[torch.Tensor] = None,
465
+ output_attentions: Optional[bool] = None,
466
+ output_hidden_states: Optional[bool] = None,
467
+ return_dict: Optional[bool] = None,
468
+ labels: Optional[torch.LongTensor] = None,
469
+ **kwargs
470
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
471
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
472
+
473
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
474
+ logits = self.head(sequence_output)
475
+
476
+ loss = None
477
+ if labels is not None:
478
+ loss_fct = nn.CrossEntropyLoss()
479
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
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 TokenClassifierOutput(
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 NorbertForQuestionAnswering(NorbertModel):
498
+ _keys_to_ignore_on_load_unexpected = ["classifier", r".*position_indices.*"]
499
+
500
+ def __init__(self, config, **kwargs):
501
+ super().__init__(config, add_mlm_layer=False, **kwargs)
502
+
503
+ self.num_labels = config.num_labels
504
+ self.head = Classifier(config, self.num_labels)
505
+ self.post_init()
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
+ start_positions: Optional[torch.Tensor] = None,
517
+ end_positions: Optional[torch.Tensor] = None,
518
+ **kwargs
519
+ ) -> Union[Tuple[torch.Tensor], QuestionAnsweringModelOutput]:
520
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
521
+
522
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
523
+ logits = self.head(sequence_output)
524
+
525
+ start_logits, end_logits = logits.split(1, dim=-1)
526
+ start_logits = start_logits.squeeze(-1).contiguous()
527
+ end_logits = end_logits.squeeze(-1).contiguous()
528
+
529
+ total_loss = None
530
+ if start_positions is not None and end_positions is not None:
531
+ # If we are on multi-GPU, split add a dimension
532
+ if len(start_positions.size()) > 1:
533
+ start_positions = start_positions.squeeze(-1)
534
+ if len(end_positions.size()) > 1:
535
+ end_positions = end_positions.squeeze(-1)
536
+
537
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
538
+ ignored_index = start_logits.size(1)
539
+ start_positions = start_positions.clamp(0, ignored_index)
540
+ end_positions = end_positions.clamp(0, ignored_index)
541
+
542
+ loss_fct = nn.CrossEntropyLoss(ignore_index=ignored_index)
543
+ start_loss = loss_fct(start_logits, start_positions)
544
+ end_loss = loss_fct(end_logits, end_positions)
545
+ total_loss = (start_loss + end_loss) / 2
546
+
547
+ if not return_dict:
548
+ output = (
549
+ start_logits,
550
+ end_logits,
551
+ *([contextualized_embeddings] if output_hidden_states else []),
552
+ *([attention_probs] if output_attentions else [])
553
+ )
554
+ return ((total_loss,) + output) if total_loss is not None else output
555
+
556
+ return QuestionAnsweringModelOutput(
557
+ loss=total_loss,
558
+ start_logits=start_logits,
559
+ end_logits=end_logits,
560
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
561
+ attentions=attention_probs if output_attentions else None
562
+ )
563
+
564
+
565
+ class NorbertForMultipleChoice(NorbertModel):
566
+ _keys_to_ignore_on_load_unexpected = ["classifier", r".*position_indices.*"]
567
+
568
+ def __init__(self, config, **kwargs):
569
+ super().__init__(config, add_mlm_layer=False, **kwargs)
570
+
571
+ self.num_labels = getattr(config, "num_labels", 2)
572
+ self.head = Classifier(config, self.num_labels)
573
+ self.post_init()
574
+
575
+ def forward(
576
+ self,
577
+ input_ids: Optional[torch.Tensor] = None,
578
+ attention_mask: Optional[torch.Tensor] = None,
579
+ token_type_ids: Optional[torch.Tensor] = None,
580
+ position_ids: Optional[torch.Tensor] = None,
581
+ labels: Optional[torch.Tensor] = None,
582
+ output_attentions: Optional[bool] = None,
583
+ output_hidden_states: Optional[bool] = None,
584
+ return_dict: Optional[bool] = None,
585
+ **kwargs
586
+ ) -> Union[Tuple[torch.Tensor], MultipleChoiceModelOutput]:
587
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
588
+ num_choices = input_ids.shape[1]
589
+
590
+ flat_input_ids = input_ids.view(-1, input_ids.size(-1))
591
+ flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
592
+
593
+ sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(flat_input_ids, flat_attention_mask)
594
+ logits = self.head(sequence_output)
595
+ reshaped_logits = logits.view(-1, num_choices)
596
+
597
+ loss = None
598
+ if labels is not None:
599
+ loss_fct = nn.CrossEntropyLoss()
600
+ loss = loss_fct(reshaped_logits, labels)
601
+
602
+ if not return_dict:
603
+ output = (
604
+ reshaped_logits,
605
+ *([contextualized_embeddings] if output_hidden_states else []),
606
+ *([attention_probs] if output_attentions else [])
607
+ )
608
+ return ((loss,) + output) if loss is not None else output
609
+
610
+ return MultipleChoiceModelOutput(
611
+ loss=loss,
612
+ logits=reshaped_logits,
613
+ hidden_states=contextualized_embeddings if output_hidden_states else None,
614
+ attentions=attention_probs if output_attentions else None
615
+ )