-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmodel.py
219 lines (177 loc) · 9.97 KB
/
model.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
from pytorch_transformers import BertPreTrainedModel, RobertaConfig, \
ROBERTA_PRETRAINED_MODEL_ARCHIVE_MAP, RobertaModel
from pytorch_transformers.modeling_roberta import RobertaClassificationHead
from torch.nn import CrossEntropyLoss, BCEWithLogitsLoss
import torch
import torch.nn as nn
from torch.nn.utils.rnn import pad_sequence
class RobertaForRR(BertPreTrainedModel):
config_class = RobertaConfig
pretrained_model_archive_map = ROBERTA_PRETRAINED_MODEL_ARCHIVE_MAP
base_model_prefix = "roberta"
def __init__(self, config):
super(RobertaForRR, self).__init__(config)
self.num_labels = config.num_labels
self.roberta = RobertaModel(config)
self.classifier = RobertaClassificationHead(config)
self.apply(self.init_weights)
def forward(self, input_ids, token_type_ids=None, attention_mask=None, labels=None, position_ids=None,
head_mask=None):
outputs = self.roberta(input_ids, position_ids=position_ids, token_type_ids=token_type_ids,
attention_mask=attention_mask, head_mask=head_mask)
sequence_output = outputs[0]
logits = self.classifier(sequence_output)
outputs = (logits,) + outputs[2:]
if labels is not None:
loss_fct = CrossEntropyLoss()
qa_loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
outputs = (qa_loss,) + outputs
return outputs # qa_loss, logits, (hidden_states), (attentions)
class RobertaForRRWithNodeLoss(BertPreTrainedModel):
config_class = RobertaConfig
pretrained_model_archive_map = ROBERTA_PRETRAINED_MODEL_ARCHIVE_MAP
base_model_prefix = "roberta"
def __init__(self, config):
super(RobertaForRRWithNodeLoss, self).__init__(config)
self.num_labels = config.num_labels
self.roberta = RobertaModel(config)
self.classifier = RobertaClassificationHead(config)
self.naf_layer = nn.Linear(config.hidden_size, config.hidden_size)
self.classifier_node = NodeClassificationHead(config)
self.apply(self.init_weights)
def forward(self, input_ids, token_type_ids=None, attention_mask=None, proof_offset=None, node_label=None, labels=None,
position_ids=None, head_mask=None):
outputs = self.roberta(input_ids, position_ids=position_ids, token_type_ids=token_type_ids,
attention_mask=attention_mask, head_mask=head_mask)
sequence_output = outputs[0]
cls_output = sequence_output[:, 0, :]
naf_output = self.naf_layer(cls_output)
logits = self.classifier(sequence_output)
max_node_length = node_label.shape[1]
batch_size = node_label.shape[0]
embedding_dim = sequence_output.shape[2]
batch_node_embedding = torch.zeros((batch_size, max_node_length, embedding_dim)).to("cuda")
for batch_index in range(batch_size):
prev_index = 1
sample_node_embedding = None
count = 0
for offset in proof_offset[batch_index]:
if offset == 0:
break
else:
rf_embedding = torch.mean(sequence_output[batch_index, prev_index:(offset+1), :], dim=0).unsqueeze(0)
prev_index = offset+1
count += 1
if sample_node_embedding is None:
sample_node_embedding = rf_embedding
else:
sample_node_embedding = torch.cat((sample_node_embedding, rf_embedding), dim=0)
# Add the NAF output at the end
sample_node_embedding = torch.cat((sample_node_embedding, naf_output[batch_index].unsqueeze(0)), dim=0)
# Append 0s at the end (these will be ignored for loss)
sample_node_embedding = torch.cat((sample_node_embedding, torch.zeros((max_node_length-count-1, embedding_dim)).to("cuda")), dim=0)
batch_node_embedding[batch_index, :, :] = sample_node_embedding
node_logits = self.classifier_node(batch_node_embedding)
outputs = (logits, node_logits) + outputs[2:]
if labels is not None:
loss_fct = CrossEntropyLoss()
qa_loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
node_loss = loss_fct(node_logits.view(-1, self.num_labels), node_label.view(-1))
total_loss = qa_loss + node_loss
outputs = (total_loss, qa_loss, node_loss) + outputs
return outputs # (total_loss), qa_loss, node_loss, logits, node_logits, (hidden_states), (attentions)
class NodeClassificationHead(nn.Module):
"""Head for sentence-level classification tasks."""
def __init__(self, config):
super(NodeClassificationHead, self).__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
def forward(self, features, **kwargs):
x = self.dropout(features)
x = self.dense(x)
x = torch.tanh(x)
x = self.dropout(x)
x = self.out_proj(x)
return x
class EdgeClassificationHead(nn.Module):
"""Head for sentence-level classification tasks."""
def __init__(self, config):
super(EdgeClassificationHead, self).__init__()
self.dense = nn.Linear(3*config.hidden_size, config.hidden_size)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
def forward(self, features, **kwargs):
x = self.dropout(features)
x = self.dense(x)
x = torch.tanh(x)
x = self.dropout(x)
x = self.out_proj(x)
return x
class RobertaForRRWithNodeEdgeLoss(BertPreTrainedModel):
config_class = RobertaConfig
pretrained_model_archive_map = ROBERTA_PRETRAINED_MODEL_ARCHIVE_MAP
base_model_prefix = "roberta"
def __init__(self, config):
super(RobertaForRRWithNodeEdgeLoss, self).__init__(config)
self.num_labels = config.num_labels
self.num_labels_edge = 2
self.roberta = RobertaModel(config)
self.naf_layer = nn.Linear(config.hidden_size, config.hidden_size)
self.classifier = RobertaClassificationHead(config)
self.classifier_node = NodeClassificationHead(config)
self.classifier_edge = EdgeClassificationHead(config)
self.apply(self.init_weights)
def forward(self, input_ids, token_type_ids=None, attention_mask=None, proof_offset=None, node_label=None,
edge_label=None, labels=None, position_ids=None, head_mask=None):
outputs = self.roberta(input_ids, position_ids=position_ids, token_type_ids=token_type_ids,
attention_mask=attention_mask, head_mask=head_mask)
sequence_output = outputs[0]
cls_output = sequence_output[:, 0, :]
naf_output = self.naf_layer(cls_output)
logits = self.classifier(sequence_output)
max_node_length = node_label.shape[1]
max_edge_length = edge_label.shape[1]
batch_size = node_label.shape[0]
embedding_dim = sequence_output.shape[2]
batch_node_embedding = torch.zeros((batch_size, max_node_length, embedding_dim)).to("cuda")
batch_edge_embedding = torch.zeros((batch_size, max_edge_length, 3*embedding_dim)).to("cuda")
for batch_index in range(batch_size):
prev_index = 1
sample_node_embedding = None
count = 0
for offset in proof_offset[batch_index]:
if offset == 0:
break
else:
rf_embedding = torch.mean(sequence_output[batch_index, prev_index:(offset+1), :], dim=0).unsqueeze(0)
prev_index = offset+1
count += 1
if sample_node_embedding is None:
sample_node_embedding = rf_embedding
else:
sample_node_embedding = torch.cat((sample_node_embedding, rf_embedding), dim=0)
# Add the NAF output at the end
sample_node_embedding = torch.cat((sample_node_embedding, naf_output[batch_index].unsqueeze(0)), dim=0)
repeat1 = sample_node_embedding.unsqueeze(0).repeat(len(sample_node_embedding), 1, 1)
repeat2 = sample_node_embedding.unsqueeze(1).repeat(1, len(sample_node_embedding), 1)
sample_edge_embedding = torch.cat((repeat1, repeat2, (repeat1-repeat2)), dim=2)
sample_edge_embedding = sample_edge_embedding.view(-1, sample_edge_embedding.shape[-1])
# Append 0s at the end (these will be ignored for loss)
sample_node_embedding = torch.cat((sample_node_embedding,
torch.zeros((max_node_length-count-1, embedding_dim)).to("cuda")), dim=0)
sample_edge_embedding = torch.cat((sample_edge_embedding,
torch.zeros((max_edge_length-len(sample_edge_embedding), 3*embedding_dim)).to("cuda")), dim=0)
batch_node_embedding[batch_index, :, :] = sample_node_embedding
batch_edge_embedding[batch_index, :, :] = sample_edge_embedding
node_logits = self.classifier_node(batch_node_embedding)
edge_logits = self.classifier_edge(batch_edge_embedding)
outputs = (logits, node_logits, edge_logits) + outputs[2:]
if labels is not None:
loss_fct = CrossEntropyLoss()
qa_loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
node_loss = loss_fct(node_logits.view(-1, self.num_labels), node_label.view(-1))
edge_loss = loss_fct(edge_logits.view(-1, self.num_labels_edge), edge_label.view(-1))
total_loss = qa_loss + node_loss + edge_loss
outputs = (total_loss, qa_loss, node_loss, edge_loss) + outputs
return outputs # (total_loss), qa_loss, node_loss, edge_loss, logits, node_logits, edge_logits, (hidden_states), (attentions)