-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathmodeling_bert.py
53 lines (42 loc) · 2.28 KB
/
modeling_bert.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
from transformers import BertPreTrainedModel,BertForTokenClassification
import torch
import torch.nn as nn
from torch.nn import CrossEntropyLoss, KLDivLoss
class BERTForTokenClassification_v2(BertForTokenClassification):
def forward(self, input_ids=None, attention_mask=None, token_type_ids=None,
position_ids=None, head_mask=None, inputs_embeds=None, labels=None, label_mask=None):
outputs = self.bert(input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds)
sequence_output = outputs[0]
sequence_output = self.dropout(sequence_output)
logits = self.classifier(sequence_output)
outputs = (logits,sequence_output) + outputs[2:] # add hidden states and attention if they are here
if labels is not None:
# Only keep active parts of the loss
if attention_mask is not None or label_mask is not None:
active_loss = True
if attention_mask is not None:
active_loss = attention_mask.view(-1) == 1
if label_mask is not None:
active_loss = active_loss & label_mask.view(-1)
active_logits = logits.view(-1, self.num_labels)[active_loss]
if labels.shape == logits.shape:
loss_fct = KLDivLoss()
if attention_mask is not None or label_mask is not None:
active_labels = labels.view(-1, self.num_labels)[active_loss]
loss = loss_fct(active_logits, active_labels)
else:
loss = loss_fct(logits, labels)
else:
loss_fct = CrossEntropyLoss()
if attention_mask is not None or label_mask is not None:
active_labels = labels.view(-1)[active_loss]
loss = loss_fct(active_logits, active_labels)
else:
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
outputs = (loss,) + outputs
return outputs # (loss), scores, (hidden_states), (attentions)