-
Notifications
You must be signed in to change notification settings - Fork 0
/
finetune_models.py
328 lines (259 loc) · 10.9 KB
/
finetune_models.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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
import argparse
import glob
import logging
import os
import random
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import CrossEntropyLoss, MSELoss, BCELoss, BCEWithLogitsLoss
from torch.autograd import Variable
from transformers import (BertConfig, BertModel, BertPreTrainedModel, BertForSequenceClassification)
####### Functionalities
class FocalLoss(nn.Module):
'''
Focal loss (https://github.com/clcarwin/focal_loss_pytorch/blob/master/focalloss.py)
'''
####### Models
class BertForSequenceClassificationFL(BertModel):
"""
Use focal loss to address imbalanced datasets.
Config:
- alpha, gamma: parameters for focal loss
"""
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.bert = BertModel(config)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
#self.aggregation = nn.Conv1d(in_channels=config.k, out_channels=1, kernel_size=1)
self.classifier = nn.Linear(config.hidden_size, self.config.num_labels)
self.alpha = config.alpha
self.gamma = config.gamma
self.init_weights()
def forward(
self,
input_ids=None,
epi_vec = None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
labels=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,
)
pooled_output = outputs[1]
pooled_output = self.dropout(torch.cat((pooled_output, epi_vec), dim=1))
logits = self.classifier(pooled_output)
outputs = (logits,) + outputs[2:] # add hidden states and attention if they are here
if labels is not None:
if self.num_labels == 1:
# We are doing regression
loss_fct = MSELoss()
loss = loss_fct(logits.view(-1), labels.view(-1))
else:
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
outputs = (loss,) + outputs
return outputs # (loss), logits, (hidden_states), (attentions)
class BertForSNPClassification(BertModel):
"""
BERT model that is built on the central token embedding, instead of [CLS].
More specifically, the classifier is built on the average of all tokens that cover the central nucleotide (i.e. the location of the SNP)
The model requires the k-mer length argument to determine which tokens to look at.
"""
def __init__(self, config):
super().__init__(config)
self.k = int(config.k)
self.num_labels = config.num_labels
self.bert = BertModel(config)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
#self.aggregation = nn.Conv1d(in_channels=config.k, out_channels=1, kernel_size=1)
self.classifier = nn.Linear(config.hidden_size, self.config.num_labels)
self.init_weights()
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
labels=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]
d = int(self.k /2)
sequence_output = sequence_output[:,(127-d):(127+d),:]
pooled_output = sequence_output.mean(axis=1)
pooled_output = self.dropout(pooled_output)
logits = self.classifier(pooled_output)
outputs = (logits,) + outputs[2:] # add hidden states and attention if they are here
if labels is not None:
if self.num_labels == 1:
# We are doing regression
loss_fct = MSELoss()
loss = loss_fct(logits.view(-1), labels.view(-1))
else:
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
outputs = (loss,) + outputs
return outputs # (loss), logits, (hidden_states), (attentions)
### Sub-BERTs: use only lower layer for the classification
class SubBertForSequenceClassification(BertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.pred_layer = config.pred_layer
self.num_labels = config.num_labels
self.bert = BertModel(config)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
self.classifier = nn.Linear(config.hidden_size, self.config.num_labels)
self.init_weights()
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
labels=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,
)
pooled_output = outputs[2][self.pred_layer][:,0,:] ## TXL: difference from the original BertForSequenceClassification
pooled_output = self.dropout(pooled_output)
logits = self.classifier(pooled_output)
outputs = (logits,) + outputs[2:] # add hidden states and attention if they are here
if labels is not None:
if self.num_labels == 1:
# We are doing regression
loss_fct = MSELoss()
loss = loss_fct(logits.view(-1), labels.view(-1))
else:
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
outputs = (loss,) + outputs
return outputs # (loss), logits, (hidden_states), (attentions)
class SubBertForSNPClassification(BertModel):
"""
BERT model that is built on the central token embedding, instead of [CLS].
More specifically, the classifier is built on the average of all tokens that cover the central nucleotide (i.e. the location of the SNP)
The model requires the k-mer length argument to determine which tokens to look at.
"""
def __init__(self, config):
super().__init__(config)
self.k = int(config.k)
self.pred_layer = config.pred_layer
self.num_labels = config.num_labels
self.bert = BertModel(config)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
#self.aggregation = nn.Conv1d(in_channels=config.k, out_channels=1, kernel_size=1)
self.classifier = nn.Linear(config.hidden_size, self.config.num_labels)
self.init_weights()
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
labels=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[2][self.pred_layer]
d = int(self.k /2)
sequence_output = sequence_output[:,(127-d):(127+d),:]
pooled_output = sequence_output.mean(axis=1)
pooled_output = self.dropout(pooled_output)
logits = self.classifier(pooled_output)
outputs = (logits,) + outputs[2:] # add hidden states and attention if they are here
if labels is not None:
if self.num_labels == 1:
# We are doing regression
loss_fct = MSELoss()
loss = loss_fct(logits.view(-1), labels.view(-1))
else:
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
outputs = (loss,) + outputs
return outputs # (loss), logits, (hidden_states), (attentions)
##########
class BertForMultilabelSequenceClassification(BertForSequenceClassification):
"""
BERT model with linear layer for multi-label classification
"""
def __init__(self, config, num_hidden_layer=768):
super().__init__(config)
self.bert = BertModel(config)
self.num_labels = config.num_labels
self.num_hidden_layer = num_hidden_layer
'''
### One-layer model
self.dropout = nn.Dropout(config.hidden_dropout_prob)
self.classifier = nn.Linear(config.hidden_size, self.num_labels)
'''
### Two-layer model
self.dropout0 = nn.Dropout(config.hidden_dropout_prob)
self.classifier0 = nn.Linear(config.hidden_size, num_hidden_layer)
self.relu = nn.ReLU()
self.dropout1 = nn.Dropout(config.hidden_dropout_prob)
self.classifier1 = nn.Linear(num_hidden_layer, self.num_labels)
#self.sigmoid = nn.Sigmoid()
self.init_weights()
def forward(self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, labels=None):
outputs = self.bert(input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask)
pooled_output = outputs[1]
'''
### One-layer model
pooled_output = self.dropout(pooled_output)
logits = self.classifier(pooled_output)
'''
### Two-layer model
pooled_output = self.dropout0(pooled_output)
classifier0_output = self.classifier0(pooled_output)
classifier0_output = self.relu(classifier0_output)
classifier0_output = self.dropout1(classifier0_output)
logits = self.classifier1(classifier0_output)
#output = self.sigmoid(logits)
output = logits
outputs = (output,) + outputs[2:]
if labels is not None:
if self.num_labels == 1:
loss_fct = MSELoss()
loss = loss_fct(output.view(-1), labels.view(-1))
else:
loss_fct = BCEWithLogitsLoss()
loss = loss_fct(output.view(self.num_labels,-1), labels.view(self.num_labels,-1))
outputs = (loss,) + outputs
return outputs