liljacharlotte commited on
Commit
9bcd371
·
1 Parent(s): 5ea3b5f

Upload 2 files

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