DylanJHJ commited on
Commit
b37d977
1 Parent(s): 9c9af7b

upload model

Browse files
Files changed (1) hide show
  1. README.md +118 -0
README.md CHANGED
@@ -1,3 +1,121 @@
1
  ---
2
  license: apache-2.0
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: apache-2.0
3
  ---
4
+
5
+ ```python
6
+ import torch
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+ from torch.nn import CrossEntropyLoss, KLDivLoss
10
+ from transformers.modeling_outputs import TokenClassifierOutput
11
+ from transformers import BertModel, BertPreTrainedModel
12
+
13
+ class BertForHighlightPrediction(BertPreTrainedModel):
14
+ _keys_to_ignore_on_load_unexpected = [r"pooler"]
15
+
16
+ def __init__(self, config, **model_kwargs):
17
+ super().__init__(config)
18
+ # self.model_args = model_kargs["model_args"]
19
+ self.num_labels = config.num_labels
20
+ self.bert = BertModel(config, add_pooling_layer=False)
21
+ classifier_dropout = (
22
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
23
+ )
24
+ self.dropout = nn.Dropout(classifier_dropout)
25
+ self.tokens_clf = nn.Linear(config.hidden_size, config.num_labels)
26
+
27
+ self.tau = model_kwargs.pop('tau', 1)
28
+ self.gamma = model_kwargs.pop('gamma', 1)
29
+ self.soft_labeling = model_kwargs.pop('soft_labeling', False)
30
+
31
+ self.init_weights()
32
+ self.softmax = nn.Softmax(dim=-1)
33
+
34
+ def forward(self,
35
+ input_ids=None,
36
+ probs=None, # soft-labeling
37
+ attention_mask=None,
38
+ token_type_ids=None,
39
+ position_ids=None,
40
+ head_mask=None,
41
+ inputs_embeds=None,
42
+ labels=None,
43
+ output_attentions=None,
44
+ output_hidden_states=None,
45
+ return_dict=None,):
46
+
47
+ outputs = self.bert(
48
+ input_ids,
49
+ attention_mask=attention_mask,
50
+ token_type_ids=token_type_ids,
51
+ position_ids=position_ids,
52
+ head_mask=head_mask,
53
+ inputs_embeds=inputs_embeds,
54
+ output_attentions=output_attentions,
55
+ output_hidden_states=output_hidden_states,
56
+ return_dict=return_dict,
57
+ )
58
+
59
+ tokens_output = outputs[0]
60
+ highlight_logits = self.tokens_clf(self.dropout(tokens_output))
61
+
62
+ loss = None
63
+ if labels is not None:
64
+ loss_fct = CrossEntropyLoss()
65
+ active_loss = attention_mask.view(-1) == 1
66
+ active_logits = highlight_logits.view(-1, self.num_labels)
67
+ active_labels = torch.where(
68
+ active_loss,
69
+ labels.view(-1),
70
+ torch.tensor(loss_fct.ignore_index).type_as(labels)
71
+ )
72
+ loss_ce = loss_fct(active_logits, active_labels)
73
+
74
+ loss_kl = 0
75
+ if self.soft_labeling:
76
+ loss_fct = KLDivLoss(reduction='sum')
77
+ active_mask = (attention_mask * token_type_ids).view(-1, 1) # BL 1
78
+ n_active = (active_mask == 1).sum()
79
+ active_mask = active_mask.repeat(1, 2) # BL 2
80
+ input_logp = F.log_softmax(active_logits / self.tau, -1) # BL 2
81
+ target_p = torch.cat(( (1-probs).view(-1, 1), probs.view(-1, 1)), -1) # BL 2
82
+
83
+ loss_kl = loss_fct(input_logp, target_p * active_mask) / n_active
84
+
85
+ loss = self.gamma * loss_ce + (1-self.gamma) * loss_kl
86
+
87
+ # print("Loss:\n")
88
+ # print(loss)
89
+ # print(loss_kl)
90
+ # print(loss_ce)
91
+
92
+ return TokenClassifierOutput(
93
+ loss=loss,
94
+ logits=highlight_logits,
95
+ hidden_states=outputs.hidden_states,
96
+ attentions=outputs.attentions,
97
+ )
98
+ @torch.no_grad()
99
+ def inference(self, outputs):
100
+
101
+ with torch.no_grad():
102
+ outputs = self.forward(**batch_inputs)
103
+ probabilities = self.softmax(self.tokens_clf(outputs.hidden_states[-1]))
104
+ predictions = torch.argmax(probabilities, dim=-1)
105
+
106
+ # active filtering
107
+ active_tokens = batch_inputs['attention_mask'] == 1
108
+ active_predictions = torch.where(
109
+ active_tokens,
110
+ predictions,
111
+ torch.tensor(-1).type_as(predictions)
112
+ )
113
+
114
+ outputs = {
115
+ "probabilities": probabilities[:, :, 1].detach(), # shape: (batch, length)
116
+ "active_predictions": predictions.detach(),
117
+ "active_tokens": active_tokens,
118
+ }
119
+
120
+ return outputs
121
+ ```