-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmodels.py
executable file
·536 lines (482 loc) · 20.4 KB
/
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
import os
import torch
import logging
from torch import nn
from torch.nn import CrossEntropyLoss, MSELoss
from transformers import (
AutoConfig,
AutoModel,
AutoTokenizer,
RobertaModel,
BertModel,
BertPreTrainedModel,
RobertaConfig,
RobertaForSequenceClassification,
XLMRobertaForSequenceClassification
)
class NegEntropy(object):
def __call__(self, outputs):
probs = torch.softmax(outputs, dim=1)
return torch.mean(torch.sum(probs.log()*probs, dim=1))
class RobertaClassificationHead(nn.Module):
"""Head for sentence-level classification tasks."""
def __init__(self, config):
super().__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 = features[:, 0, :] # take <s> token (equiv. to [CLS])
x = self.dropout(x)
x = self.dense(x)
x = torch.tanh(x)
x = self.dropout(x)
x = self.out_proj(x)
return x
class BertClassificationHead(nn.Module):
"""Head for sentence-level classification tasks."""
def __init__(self, config):
super().__init__()
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 = features[:, 0, :] # take <s> token (equiv. to [CLS])
x = self.dropout(x)
x = self.out_proj(x)
return x
class SequenceClassificationFp16(BertPreTrainedModel):
r"""
https://github.com/huggingface/transformers/blob/master/transformers/modeling_bert.py#L1122
"""
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
if config.model_type == 'bert':
self.bert = BertModel(config)
self.classifier = BertClassificationHead(config)
if config.secondary_num_labels is not None:
temp_num_labels = config.num_labels
config.num_labels = config.secondary_num_labels
self.sec_classifier = BertClassificationHead(config)
config.num_labels = temp_num_labels
self.secondary_num_labels=config.secondary_num_labels
elif config.model_type == 'xlm-roberta':
self.roberta = RobertaModel(config)
self.classifier = RobertaClassificationHead(config)
if config.secondary_num_labels is not None:
temp_num_labels = config.num_labels
config.num_labels = config.secondary_num_labels
self.sec_classifier = RobertaClassificationHead(config)
config.num_labels = temp_num_labels
self.secondary_num_labels=config.secondary_num_labels
else:
raise NotImplementedError()
self.config = config
self.init_weights()
@torch.cuda.amp.autocast()
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
labels=None,
output_attentions=None,
output_hidden_states=None,
conf_penalty=None,
marginal_entropy=None,
sec_classifier=None,
conf_coef=1
):
if self.config.model_type == "bert":
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,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
)
elif self.config.model_type == "xlm-roberta":
outputs = self.roberta(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
)
sequence_output = outputs[0]
num_of_label = self.num_labels
if sec_classifier is None:
logits = self.classifier(sequence_output)
else:
num_of_label = self.secondary_num_labels
logits = self.sec_classifier(sequence_output)
loss = None
per_sample_loss = None
if labels is not None:
if num_of_label == 1:
# We are doing regression
loss_fct = MSELoss()
loss = loss_fct(logits.view(-1), labels.view(-1))
else:
loss_fct = CrossEntropyLoss()
per_sample_loss_fct = CrossEntropyLoss(reduction='none')
loss = loss_fct(logits.view(-1, num_of_label), labels.view(-1))
per_sample_loss = per_sample_loss_fct(logits.view(-1, num_of_label), labels.view(-1))
if conf_penalty is not None:
if loss is None:
loss = 0
neg_entropy_loss_func = NegEntropy()
loss = loss + conf_coef*neg_entropy_loss_func(logits)
per_sample_loss = per_sample_loss + neg_entropy_loss_func(logits)
if marginal_entropy is not None:
if loss is None:
loss = 0
neg_entropy_loss_func = NegEntropy()
loss = loss - neg_entropy_loss_func(torch.mean(logits, dim=0, keepdim=True)) # neg_entropy_loss_func(logits.mean(axis=0))
return loss, (per_sample_loss, logits, sequence_output)
class SequenceClassification(BertPreTrainedModel):
r"""
https://github.com/huggingface/transformers/blob/master/transformers/modeling_bert.py#L1122
"""
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
if config.model_type == 'bert':
self.bert = BertModel(config)
self.classifier = BertClassificationHead(config)
if config.secondary_num_labels is not None:
temp_num_labels = config.num_labels
config.num_labels = config.secondary_num_labels
self.sec_classifier = BertClassificationHead(config)
config.num_labels = temp_num_labels
self.secondary_num_labels=config.secondary_num_labels
elif config.model_type == 'xlm-roberta':
self.roberta = RobertaModel(config)
self.classifier = RobertaClassificationHead(config)
if config.secondary_num_labels is not None:
temp_num_labels = config.num_labels
config.num_labels = config.secondary_num_labels
self.sec_classifier = RobertaClassificationHead(config)
config.num_labels = temp_num_labels
self.secondary_num_labels=config.secondary_num_labels
else:
raise NotImplementedError()
self.config = config
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,
output_attentions=None,
output_hidden_states=None,
conf_penalty=None,
marginal_entropy=None,
sec_classifier=None,
conf_coef=1
):
if self.config.model_type == "bert":
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,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
)
elif self.config.model_type == "xlm-roberta":
outputs = self.roberta(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
)
sequence_output = outputs[0]
num_of_label = self.num_labels
if sec_classifier is None:
logits = self.classifier(sequence_output)
else:
num_of_label = self.secondary_num_labels
logits = self.sec_classifier(sequence_output)
loss = None
per_sample_loss = None
if labels is not None:
if num_of_label == 1:
# We are doing regression
loss_fct = MSELoss()
loss = loss_fct(logits.view(-1), labels.view(-1))
else:
loss_fct = CrossEntropyLoss()
per_sample_loss_fct = CrossEntropyLoss(reduction='none')
loss = loss_fct(logits.view(-1, num_of_label), labels.view(-1))
per_sample_loss = per_sample_loss_fct(logits.view(-1, num_of_label), labels.view(-1))
if conf_penalty is not None:
probs = logits.softmax(-1)
if loss is None:
loss = 0
neg_entropy_loss_func = NegEntropy()
loss = loss + conf_coef*neg_entropy_loss_func(probs)
#per_sample_loss = per_sample_loss + neg_entropy_loss_func(logits)
if marginal_entropy is not None:
if conf_penalty is None:
probs = logits.softmax(-1)
if loss is None:
loss = 0
neg_entropy_loss_func = NegEntropy()
loss = loss - neg_entropy_loss_func(torch.mean(probs, dim=0, keepdim=True)) # neg_entropy_loss_func(logits.mean(axis=0))
return loss, (per_sample_loss, logits, sequence_output)
class TokenClassificationFp16(BertPreTrainedModel):
r"""
https://github.com/huggingface/transformers/blob/master/transformers/modeling_bert.py#L1122
"""
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
if config.model_type == 'bert':
self.bert = BertModel(config)
elif config.model_type == 'xlm-roberta':
self.roberta = RobertaModel(config)
else:
raise NotImplementedError()
self.dropout = nn.Dropout(config.hidden_dropout_prob)
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
self.config = config
self.init_weights()
@torch.cuda.amp.autocast()
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
labels=None,
output_attentions=None,
output_hidden_states=None,
conf_penalty=None,
):
if self.config.model_type == "bert":
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,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
)
elif self.config.model_type == "xlm-roberta":
outputs = self.roberta(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
)
sequence_output = outputs[0]
sequence_output = self.dropout(sequence_output)
logits = self.classifier(sequence_output)
if labels is not None:
loss_fct = CrossEntropyLoss()
neg_entropy_loss_func = NegEntropy()
loss_fct_token = CrossEntropyLoss(reduction='none')
# Only keep active parts of the loss
if attention_mask is not None:
active_loss = attention_mask.view(-1) == 1
active_logits = logits.view(-1, self.num_labels)[active_loss]
active_labels = labels.view(-1)[active_loss]
loss = loss_fct(active_logits, active_labels)
if conf_penalty is not None:
loss = loss + neg_entropy_loss_func(active_logits)
per_token_loss = loss_fct_token(logits.view(-1, self.num_labels), labels.view(-1))
else:
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
if conf_penalty is not None:
loss = loss - neg_entropy_loss_func(logits.view(-1, self.num_labels))
per_token_loss = loss_fct_token(logits.view(-1, self.num_labels), labels.view(-1))
else:
return None, ([None], logits, sequence_output)
return loss, (per_token_loss, logits, sequence_output)
class TokenClassification(BertPreTrainedModel):
r"""
https://github.com/huggingface/transformers/blob/master/transformers/modeling_bert.py#L1122
"""
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
if config.model_type == 'bert':
self.bert = BertModel(config)
elif config.model_type == 'xlm-roberta':
self.roberta = RobertaModel(config)
else:
raise NotImplementedError()
self.dropout = nn.Dropout(config.hidden_dropout_prob)
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
self.config = config
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,
output_attentions=None,
output_hidden_states=None,
conf_penalty=None,
):
if self.config.model_type == "bert":
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,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
)
elif self.config.model_type == "xlm-roberta":
outputs = self.roberta(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
)
sequence_output = outputs[0]
sequence_output = self.dropout(sequence_output)
logits = self.classifier(sequence_output)
if labels is not None:
loss_fct = CrossEntropyLoss()
neg_entropy_loss_func = NegEntropy()
loss_fct_token = CrossEntropyLoss(reduction='none')
# Only keep active parts of the loss
if attention_mask is not None:
active_loss = attention_mask.view(-1) == 1
active_logits = logits.view(-1, self.num_labels)[active_loss]
active_labels = labels.view(-1)[active_loss]
loss = loss_fct(active_logits, active_labels)
if conf_penalty is not None:
loss = loss + neg_entropy_loss_func(active_logits)
per_token_loss = loss_fct_token(logits.view(-1, self.num_labels), labels.view(-1))
else:
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
if conf_penalty is not None:
loss = loss + neg_entropy_loss_func(logits.view(-1, self.num_labels))
per_token_loss = loss_fct_token(logits.view(-1, self.num_labels), labels.view(-1))
else:
return None, ([None], logits, sequence_output)
return loss, (per_token_loss, logits, sequence_output)
def load_model(
task_name,
config_name,
tokenizer_name,
model_name_or_path,
num_labels,
model_type,
logger=None,
do_lower_case=False,
cache_dir=None,
is_fp16=False,
verbose=True,
secondary_num_labels=None
):
if logger is None:
logger = logging.getLogger(__name__)
if verbose:
logger.info("Loading config ...")
config = AutoConfig.from_pretrained(
config_name if config_name else model_name_or_path,
num_labels=num_labels,
finetuning_task=task_name,
cache_dir=None,
)
config.secondary_num_labels = secondary_num_labels
# print("model_type : %s, config.model_type : %s" % (model_type, config.model_type))
try:
assert model_type == config.model_type
except:
assert model_type.split("-")[0] == config.model_type
if verbose:
logger.info("Loading tokenizer ...")
tokenizer = AutoTokenizer.from_pretrained(
pretrained_model_name_or_path = tokenizer_name if tokenizer_name else model_name_or_path,
do_lower_case=do_lower_case,
cache_dir=cache_dir,
)
if verbose:
logger.info("Loading model ...")
model = get_model_class(task_name, is_fp16).from_pretrained(
pretrained_model_name_or_path = model_name_or_path,
from_tf=False,
config=config,
cache_dir=cache_dir,
)
# Check if saved optimizer or scheduler states exist
optimizer = None
scheduler = None
if os.path.isfile(os.path.join(model_name_or_path, "optimizer.pt")) and os.path.isfile(
os.path.join(model_name_or_path, "scheduler.pt")
):
optimizer.load_state_dict(torch.load(os.path.join(model_name_or_path, "optimizer.pt")))
scheduler.load_state_dict(torch.load(os.path.join(model_name_or_path, "scheduler.pt")))
return config, tokenizer, model, optimizer, scheduler
def save_model(exp_dir, args, global_step, model, tokenizer, optimizer=None, scheduler=None, logger=None, prefix=""):
if logger is None:
logger = logging.getLogger(__name__)
checkpoints = os.path.join(exp_dir, "checkpoints")
output_dir = os.path.join(checkpoints, "{}_checkpoint-{}".format(prefix, global_step))
if not os.path.exists(output_dir):
os.makedirs(output_dir)
model_to_save = (
model.module if hasattr(model, "module") else model
) # Take care of distributed/parallel training
model_to_save.save_pretrained(output_dir)
tokenizer.save_pretrained(output_dir)
torch.save(args, os.path.join(output_dir, "training_args.bin"))
# logger.info("Saving model checkpoint to %s", output_dir)
if optimizer is not None:
logger.info("Saving optimizer states to %s", output_dir)
# torch.save(optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt"))
if scheduler is not None:
logger.info("Saving scheduler states to %s", output_dir)
# torch.save(scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt"))
def get_model_class(task_name, is_fp16):
key = task_name+"_fp16" if is_fp16 else task_name
model_dict = {
"xnli": SequenceClassification,
"pawsx": SequenceClassification,
"xnli_fp16": SequenceClassificationFp16,
"pawsx_fp16": SequenceClassificationFp16
}
return model_dict[key]