-
Notifications
You must be signed in to change notification settings - Fork 2
/
run_span_swa.py
1605 lines (1458 loc) · 75.1 KB
/
run_span_swa.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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import re
import sys
import time
import json
import glob
import random
import logging
import itertools
from pathlib import Path
from argparse import ArgumentParser, Namespace
from tqdm import tqdm
import copy
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler,DistributedSampler
import numpy as np
# datasets
from transformers.data import DataProcessor
from torch.cuda.amp import autocast as ac
# models
import transformers
from transformers import WEIGHTS_NAME
from transformers import (
BertConfig,
BertTokenizer,
BertPreTrainedModel,
BertModel,
)
from transformers.modeling_outputs import TokenClassifierOutput
from nezha.modeling_nezha import NeZhaModel, NeZhaPreTrainedModel,NeZhaConfig
from nezha.modeling_nezha import relative_position_encoding
# from roformer import RoFormerModel,RoFormerConfig,RoFormerPreTrainedModel
# trainer & training arguments
from transformers import AdamW, get_linear_schedule_with_warmup
from lamb import Lamb
# metrics
from seqeval.metrics.sequence_labeling import (
accuracy_score,
classification_report,
performance_measure,
f1_score, precision_score, recall_score,
get_entities
)
from evaluate import score
from utils import LABEL_MEANING_MAP, MEANING_LABEL_MAP, get_ner_tags
class BertConfigSpanV2(BertConfig):
def __init__(self,
max_span_length=10,
width_embedding_dim=150,
**kwargs,
):
super().__init__(**kwargs)
self.max_span_length = max_span_length
self.width_embedding_dim = width_embedding_dim
class NeZhaConfigSpanV2(NeZhaConfig):
def __init__(self,
max_span_length=10,
width_embedding_dim=150,
**kwargs,
):
super().__init__(**kwargs)
self.max_span_length = max_span_length
self.width_embedding_dim = width_embedding_dim
# class RoformerConfigSpanV2(RoFormerConfig):
#
# def __init__(self,
# max_span_length=10,
# width_embedding_dim=150,
# **kwargs,
# ):
# super().__init__(**kwargs)
# self.max_span_length = max_span_length
# self.width_embedding_dim = width_embedding_dim
def batched_index_select(input, index):
batch_size, sequence_length, hidden_size = input.size()
batch_size, num_spans = index.size()
index_onehot = torch.FloatTensor(
batch_size, num_spans, sequence_length).to(input.device)
index_onehot.zero_()
index_onehot.scatter_(2, index.unsqueeze(2), 1)
output = torch.bmm(index_onehot, input)
return output
class LabelSmoothingCE(nn.Module):
def __init__(self, eps=0.1, reduction='mean', ignore_index=-100):
super().__init__()
self.eps = eps
self.reduction = reduction
self.ignore_index = ignore_index
def forward(self, input, target):
c = input.size()[-1]
log_preds = F.log_softmax(input, dim=-1)
if self.reduction == 'sum':
loss = -log_preds.sum()
else:
loss = -log_preds.sum(dim=-1)
if self.reduction == 'mean':
loss = loss.mean()
loss_1 = loss * self.eps / c
loss_2 = F.nll_loss(log_preds, target, reduction=self.reduction, ignore_index=self.ignore_index)
return loss_1 + (1 - self.eps) * loss_2
class FocalLoss(nn.Module):
"""
Softmax and sigmoid focal loss
"""
def __init__(self, activation_type='softmax', reduction='mean',
gamma=2.0, alpha=0.25, epsilon=1.e-9):
super(FocalLoss, self).__init__()
self.gamma = gamma
self.alpha = alpha
self.epsilon = epsilon
self.activation_type = activation_type
self.reduction = reduction
def forward(self, input, target):
"""
Args:
logits: pretrain_model's output, shape of [batch_size, num_cls]
target: ground truth labels, shape of [batch_size]
Returns:
shape of [batch_size]
"""
if self.activation_type == 'softmax':
num_labels = input.size(-1)
idx = target.view(-1, 1).long()
one_hot_key = torch.zeros(idx.size(0), num_labels, dtype=torch.float32, device=idx.device)
one_hot_key = one_hot_key.scatter_(1, idx, 1)
logits = F.softmax(input, dim=-1)
loss = -self.alpha * one_hot_key * torch.pow((1 - logits), self.gamma) * (logits + self.epsilon).log()
loss = loss.sum(1)
elif self.activation_type == 'sigmoid':
multi_hot_key = target
logits = F.sigmoid(input)
zero_hot_key = 1 - multi_hot_key
loss = -self.alpha * multi_hot_key * torch.pow((1 - logits), self.gamma) * (logits + self.epsilon).log()
loss += -(1 - self.alpha) * zero_hot_key * torch.pow(logits, self.gamma) * (1 - logits + self.epsilon).log()
if self.reduction == "mean":
loss = loss.mean()
elif self.reduction == "none":
pass
return loss
class SpanV2(nn.Module):
def __init__(self, hidden_size, num_labels, max_span_length, width_embedding_dim):
super(SpanV2, self).__init__()
self.width_embedding = nn.Embedding(max_span_length + 1, width_embedding_dim)
self.classifier = nn.Sequential(
nn.Linear(hidden_size * 2 + width_embedding_dim, hidden_size),
nn.ReLU(),
nn.Linear(hidden_size, num_labels),
)
def forward(self, hidden_states, spans):
spans_start = spans[:, :, 0].view(spans.size(0), -1)
spans_start_embedding = batched_index_select(hidden_states, spans_start)
spans_end = spans[:, :, 1].view(spans.size(0), -1)
spans_end_embedding = batched_index_select(hidden_states, spans_end)
spans_width = spans[:, :, 2].view(spans.size(0), -1)
spans_width_embedding = self.width_embedding(spans_width)
spans_embedding = torch.cat([
spans_start_embedding,
spans_end_embedding,
spans_width_embedding
], dim=-1) # (batch_size, num_spans, num_features)
logits = self.classifier(spans_embedding)
return logits
@staticmethod
def decode_batch(
batch, # (batch_size, num_spans, num_labels)
spans, # (batch_size, num_spans, 3)
span_mask, # (batch_size, num_spans)
is_logits: bool=True,
):
decodeds = []
if is_logits:
labels = batch.argmax(dim=-1)
else:
labels = batch
for labels_, spans_, span_mask_ in zip(labels, spans, span_mask):
span_mask_ = span_mask_ == 1.
labels_ = labels_[span_mask_].cpu().numpy().tolist()
spans_ = spans_[span_mask_].cpu().numpy().tolist()
decoded_ = []
for t, s in zip(labels_, spans_):
decoded_.append([t, s[0] - 1, s[1] - 1])
decodeds.append(decoded_)
return decodeds
class SpanV2Loss(nn.Module):
def __init__(self):
super().__init__()
self.loss_fct = None
if args.loss_type == "ce":
self.loss_fct = nn.CrossEntropyLoss(reduction='none')
elif args.loss_type == "lsr":
self.loss_fct = LabelSmoothingCE(eps=args.label_smooth_eps, reduction='none')
elif args.loss_type == "focal":
self.loss_fct = FocalLoss(reduction='none',
gamma=args.focal_gamma, alpha=args.focal_alpha) # TODO:
def forward(self,
logits=None, # (batch_size, num_spans, num_labels)
label=None, # (batch_size, num_spans)
mask=None, # (batch_size, num_spans)
):
num_labels = logits.size(-1)
loss_mask = mask.view(-1) == 1
loss = self.loss_fct(logits.view(-1, num_labels), label.view(-1))
loss = loss[loss_mask].mean()
return loss
def forward(
cls,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
spans=None, # (batch_size, num_spans, 3)
span_mask=None, # (batch_size, num_spans)
label=None, # (batch_size, num_spans)
input_len=None, # (batch_size)
sent_start=None, # (batch_size)
sent_end=None, # (batch_size)
head_mask=None,
inputs_embeds=None,
output_attentions=None,
output_hidden_states=None,
return_dict=True,
):
return_dict = return_dict if return_dict is not None else cls.config.use_return_dict
outputs = cls.base_model(
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,
return_dict=return_dict,
)
sequence_output = outputs[0]
if not cls.config.do_mdp:
sequence_output = cls.dropout(sequence_output)
logits = cls.span(sequence_output, spans) # (batch_size, num_spans, num_labels)
total_loss = None
if label is not None:
loss_fct = SpanV2Loss()
total_loss = loss_fct(logits, label, span_mask)
if not return_dict:
output = (logits,) + outputs[2:]
return ((total_loss,) + output) if total_loss is not None else output
return TokenClassifierOutput(
loss=total_loss,
logits=logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
def compute_kl_loss(p, q, pad_mask=None):
batch_size, num_spans, num_labels = p.size()
if pad_mask is None:
pad_mask = torch.ones(batch_size, num_spans, dtype=torch.bool, device=p.device)
pad_mask = pad_mask.unsqueeze(-1).expand(batch_size, num_spans, num_labels)
p_loss = F.kl_div(F.log_softmax(p, dim=-1), F.softmax(q, dim=-1), reduction='none')
q_loss = F.kl_div(F.log_softmax(q, dim=-1), F.softmax(p, dim=-1), reduction='none')
# pad_mask is for seq-level tasks
p_loss.masked_fill_(pad_mask, 0.)
q_loss.masked_fill_(pad_mask, 0.)
# You can choose whether to use function "sum" and "mean" depending on your task
p_loss = p_loss.mean()
q_loss = q_loss.mean()
loss = (p_loss + q_loss) / 2
return loss
def forward_rdrop(cls, alpha, **kwargs):
outputs1 = forward(cls, **kwargs)
if outputs1.loss is None or alpha <= 0.: return outputs1
outputs2 = forward(cls, **kwargs)
rdrop_loss = compute_kl_loss(
outputs1["logits"], outputs2["logits"],
kwargs["span_mask"] == 0)
total_loss = (outputs1["loss"] + outputs2["loss"]) / 2. + alpha * rdrop_loss
return TokenClassifierOutput(
loss=total_loss,
logits=outputs1["logits"],
hidden_states=outputs1.hidden_states,
attentions=outputs1.attentions,
)
class BertSpanV2ForNer(BertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.bert = BertModel(config)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
self.span = SpanV2(config.hidden_size, config.num_labels,
config.max_span_length, config.width_embedding_dim)
self.init_weights()
def forward(self, **kwargs):
if args.rdrop_alpha is not None:
return forward_rdrop(self, args.rdrop_alpha, **kwargs)
return forward(self, **kwargs)
class MultiSampleDropoutSpanV2(nn.Module):
'''
# multisample dropout (wut): https://arxiv.org/abs/1905.09788
'''
def __init__(self, config, mdp_k=5, mdp_p=0.2):
super().__init__()
self.K = mdp_k
self.dropout = nn.Dropout(mdp_p)
self.classifier = SpanV2(config.hidden_size, config.num_labels,
config.max_span_length, config.width_embedding_dim)
def forward(self, sequence_output, spans):
for i in range(self.K):
if i == 0:
logits = self.classifier(self.dropout(sequence_output),spans)
else:
logits += self.classifier(self.dropout(sequence_output),spans)
logits = logits / self.K
return logits
class NeZhaSpanV2ForNer(NeZhaPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.bert = NeZhaModel(config)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
if config.do_mdp:
self.span = MultiSampleDropoutSpanV2(config)
else:
self.span = SpanV2(config.hidden_size, config.num_labels,
config.max_span_length, config.width_embedding_dim)
self.init_weights()
def forward(self, **kwargs):
if args.rdrop_alpha is not None:
return forward_rdrop(self, args.rdrop_alpha, **kwargs)
return forward(self, **kwargs)
# class RoformerSpanV2ForNer(RoFormerPreTrainedModel):
#
# def __init__(self, config):
# super().__init__(config)
#
# self.roformer = RoFormerModel(config)
# self.dropout = nn.Dropout(config.hidden_dropout_prob)
# self.span = SpanV2(config.hidden_size, config.num_labels,
# config.max_span_length, config.width_embedding_dim)
# self.init_weights()
#
# def forward(self, **kwargs):
# if args.rdrop_alpha is not None:
# return forward_rdrop(self, args.rdrop_alpha, **kwargs)
# return forward(self, **kwargs)
class NerArgumentParser(ArgumentParser):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def parse_args_from_json(self, json_file):
data = json.loads(Path(json_file).read_text())
return Namespace(**data)
def save_args_to_json(self, json_file, args):
Path(json_file).write_text(json.dumps(vars(args), indent=4))
def build_arguments(self):
# Required parameters
self.add_argument("--version", default=None, type=str, required=True,
help="Version of training model.")
self.add_argument("--device", default=None, type=str, required=False,
help="Device for training.")
self.add_argument("--n_gpu", default=1, type=int, required=False,
help="Device for training.")
self.add_argument("--task_name", default="ner", type=str, required=False,
help="The name of the task to train selected in the list: ")
self.add_argument("--dataset_name", default="cail_ner", type=str, required=False,
help="The name of the dataset for the task")
self.add_argument("--data_dir", default=None, type=str, required=True,
help="The input data dir. Should contain the training files for the CoNLL-2003 NER task.", )
self.add_argument("--train_file", default=None, type=str, required=True)
self.add_argument("--dev_file", default=None, type=str, required=True)
self.add_argument("--test_file", default=None, type=str, required=True)
self.add_argument("--model_type", default=None, type=str, required=True,
help="Model type selected in the list: ")
self.add_argument("--model_name_or_path", default=None, type=str, required=True,
help="Path to pre-trained model or shortcut name selected in the list: " )
self.add_argument("--output_dir", default="output/", type=str, required=False,
help="The output directory where the model predictions and checkpoints will be written.", )
self.add_argument("--max_span_length", default=50, type=int)
self.add_argument("--width_embedding_dim", default=128, type=int)
self.add_argument("--optimizer", default="adamw", type=str)
# self.add_argument("--context_window", default=0, type=int)
self.add_argument("--augment_context_aware_p", default=None, type=float)
self.add_argument("--augment_entity_replace_p", default=None, type=float)
self.add_argument("--rdrop_alpha", default=None, type=float)
self.add_argument("--vat_alpha", default=None, type=float)
# Other parameters
self.add_argument('--scheme', default='IOB2', type=str,
choices=['IOB2', 'IOBES'])
self.add_argument('--loss_type', default='ce', type=str,
choices=['lsr', 'focal', 'ce'])
self.add_argument('--label_smooth_eps', default=0.1, type=float)
self.add_argument('--focal_gamma', default=2.0, type=float)
self.add_argument('--focal_alpha', default=0.25, type=float)
self.add_argument("--config_name", default="", type=str,
help="Pretrained config name or path if not the same as model_name")
self.add_argument("--tokenizer_name", default="", type=str,
help="Pretrained tokenizer name or path if not the same as model_name", )
self.add_argument("--cache_dir", default="cache/", type=str,
help="Where do you want to store the pre-trained models downloaded from s3", )
self.add_argument("--train_max_seq_length", default=128, type=int,
help="The maximum total input sequence length after tokenization. Sequences longer "
"than this will be truncated, sequences shorter will be padded.", )
self.add_argument("--eval_max_seq_length", default=512, type=int,
help="The maximum total input sequence length after tokenization. Sequences longer "
"than this will be truncated, sequences shorter will be padded.", )
self.add_argument("--do_train", action="store_true",
help="Whether to run training.")
self.add_argument("--do_eval", action="store_true",
help="Whether to run eval on the dev set.")
self.add_argument("--do_predict", action="store_true",
help="Whether to run predictions on the test set.")
self.add_argument("--evaluate_during_training", action="store_true",
help="Whether to run evaluation during training at each logging step.", )
self.add_argument("--evaluate_each_epoch", action="store_true",
help="Whether to run evaluation during training at each epoch, `--logging_step` will be ignored", )
self.add_argument("--do_lower_case", action="store_true",
help="Set this flag if you are using an uncased model.")
# adversarial training
self.add_argument("--do_fgm", action="store_true",
help="Whether to adversarial training.")
self.add_argument('--fgm_epsilon', default=1.0, type=float,
help="Epsilon for adversarial.")
self.add_argument('--fgm_name', default='word_embeddings', type=str,
help="name for adversarial layer.")
self.add_argument("--per_gpu_train_batch_size", default=8, type=int,
help="Batch size per GPU/CPU for training.")
self.add_argument("--per_gpu_eval_batch_size", default=8, type=int,
help="Batch size per GPU/CPU for evaluation.")
self.add_argument("--gradient_accumulation_steps", type=int, default=1,
help="Number of updates steps to accumulate before performing a backward/update pass.", )
self.add_argument("--learning_rate", default=5e-5, type=float,
help="The initial learning rate for Adam.")
self.add_argument("--other_learning_rate", default=5e-5, type=float,
help="The initial learning rate for crf and linear layer.")
self.add_argument("--weight_decay", default=0.01, type=float,
help="Weight decay if we apply some.")
self.add_argument("--adam_epsilon", default=1e-8, type=float,
help="Epsilon for Adam optimizer.")
self.add_argument("--max_grad_norm", default=1.0, type=float,
help="Max gradient norm.")
self.add_argument("--num_train_epochs", default=3.0, type=float,
help="Total number of training epochs to perform.")
self.add_argument("--max_steps", default=-1, type=int,
help="If > 0: set total number of training steps to perform. Override num_train_epochs.", )
self.add_argument("--warmup_proportion", default=0.1, type=float,
help="Proportion of training to perform linear learning rate warmup for,E.g., 0.1 = 10% of training.")
self.add_argument("--logging_steps", type=int, default=50, help="Log every X updates steps.")
self.add_argument("--save_steps", type=int, default=50, help="Save checkpoint every X updates steps.")
self.add_argument("--save_best_checkpoints", action="store_true", help="Save best checkpoint each `--logging_steps`, `--save_step` will be ignore")
self.add_argument("--eval_all_checkpoints", action="store_true", help="Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number", )
self.add_argument("--predict_checkpoints", type=int, default=0,
help="predict checkpoints starting with the same prefix as model_name ending and ending with step number")
self.add_argument("--no_cuda", action="store_true", help="Avoid using CUDA when available")
self.add_argument("--overwrite_output_dir", action="store_true",
help="Overwrite the content of the output directory")
self.add_argument("--seed", type=int, default=42, help="random seed for initialization")
self.add_argument("--fp16", action="store_true",
help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit", )
self.add_argument("--fp16_opt_level", type=str, default="O1",
help="For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']."
"See details at https://nvidia.github.io/apex/amp.html", )
self.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
self.add_argument("--do_swa", action="store_true")
self.add_argument("--swa_start", type=int, default=1)
self.add_argument("--swa_type", type=str, default='weight',choices=['weight', 'avg'])
self.add_argument("--do_pgd", action="store_true")
self.add_argument("--pgd_k", type=int, default=3)
self.add_argument("--do_mdp", action="store_true")
return self
class NerProcessor(DataProcessor):
def get_train_examples(self, data_dir, data_file):
"""Gets a collection of :class:`InputExample` for the train set."""
return list(self._create_examples(data_dir, data_file, 'train'))
def get_dev_examples(self, data_dir, data_file):
"""Gets a collection of :class:`InputExample` for the dev set."""
return list(self._create_examples(data_dir, data_file, 'dev'))
def get_test_examples(self, data_dir, data_file):
"""Gets a collection of :class:`InputExample` for the test set."""
return list(self._create_examples(data_dir, data_file, 'test'))
@property
def label2id(self):
return {label: i for i, label in enumerate(self.get_labels())}
@property
def id2label(self):
return {i: label for i, label in enumerate(self.get_labels())}
def get_labels(self):
"""Gets the list of labels for this data set."""
raise NotImplementedError()
def _create_examples(self, data_dir, data_file, mode):
raise NotImplementedError()
class CailNerProcessor(NerProcessor):
def get_labels(self):
return [
"O", # "X", "O", "[START]", "[END]",
] + list(LABEL_MEANING_MAP.keys())
def _create_examples(self, data_dir, data_file, mode):
data_path = os.path.join(data_dir, data_file)
with open(data_path, encoding="utf-8") as f:
lines = [json.loads(line) for line in f.readlines()]
for sentence_counter, line in enumerate(lines):
sentence = (
sentence_counter,
{
"id": f"{mode}-{str(line['id'])}",
"tokens": list(line["text"]),
"entities": line.get("entities", None)
if mode in ["train", "dev"] else None,
"sent_start": line["sent_start"],
"sent_end": line["sent_end"],
}
)
yield sentence
class NerDataset(torch.utils.data.Dataset):
def __init__(self, examples, process_pipline=[]):
super().__init__()
self.examples = examples
self.process_pipline = process_pipline
def __getitem__(self, index):
# get example
example = self.examples[index]
# preprocessing
for proc in self.process_pipline:
if proc is None: continue
example = proc(example)
# convert to features
return example
def __len__(self):
return len(self.examples)
@staticmethod
def collate_fn(batch):
max_len = max([b["input_len"] for b in batch])[0].item()
collated = dict()
for k in ["input_ids", "token_type_ids", "attention_mask", "input_len", "sent_start", "sent_end"]:
t = torch.cat([b[k] for b in batch], dim=0)
if k not in ["input_len", "sent_start", "sent_end"]:
t = t[:, :max_len] # dynamic batch
collated[k] = t
for k in ["spans", "span_mask", "label"]:
if batch[0][k] is None:
collated[k] = None
continue
t = pad_sequence([b[k][0] for b in batch], batch_first=True)
collated[k] = t
return collated
class AugmentContextAware:
def __init__(self, p):
self.p = p
self.augment_entity_meanings = [
"物品价值", "被盗货币", "盗窃获利",
"受害人", "犯罪嫌疑人"
]
def __call__(self, example):
id_ = example[1]["id"]
tokens = example[1]["tokens"]
entities = example[1]["entities"]
sent_start = example[1]["sent_start"]
sent_end = example[1]["sent_end"]
random.shuffle(entities)
for entity_type, entity_start, entity_end, entity_text in entities:
if LABEL_MEANING_MAP[entity_type] in self.augment_entity_meanings:
if random.random() > self.p: continue
if any([tk == "[MASK]" for tk in tokens[entity_start: entity_end + 1]]):
continue
for i in range(entity_start, entity_end + 1):
tokens[i] = "[MASK]"
example[1]["tokens"] = tokens
return example
class AugmentEntityReplace:
def __init__(self, p, examples):
self.p = p
self.wordType_entityTypes_map = {
"姓名": ["受害人", "犯罪嫌疑人", ],
"价值": ["物品价值", "被盗货币", "盗窃获利", ],
}
self.entityType_wordType_map = dict()
for word_type, entity_types in self.wordType_entityTypes_map.items():
for entity_type in entity_types:
self.entityType_wordType_map[entity_type] = word_type
self.wordType_words_map = {
"姓名": set(),
"价值": set(),
}
for example in examples:
for entity_type, entity_start, entity_end, entity_text in example[1]["entities"]:
meaning = LABEL_MEANING_MAP[entity_type]
if meaning not in self.entityType_wordType_map:
continue
self.wordType_words_map[self.entityType_wordType_map[meaning]] \
.add(entity_text)
self.wordType_words_map = {k: list(v) for k, v in self.wordType_words_map.items()}
def __call__(self, example):
id_ = example[1]["id"]
tokens = example[1]["tokens"]
entities = example[1]["entities"]
sent_start = example[1]["sent_start"]
sent_end = example[1]["sent_end"]
text = "".join(tokens)
entities = sorted(entities, key=lambda x: x[0])
for i, (entity_type, entity_start, entity_end, entity_text) in enumerate(entities):
if random.random() > self.p: continue
meaning = LABEL_MEANING_MAP[entity_type]
if meaning not in self.entityType_wordType_map:
continue
entity_text_new = random.choice(self.wordType_words_map[self.entityType_wordType_map[meaning]])
len_diff = len(entity_text_new) - len(entity_text)
text = text[: entity_start] + entity_text_new + text[entity_end + 1:]
entity_start, entity_end = entity_start, entity_start + len(entity_text_new) - 1
entities[i] = [entity_type, entity_start, entity_end, text[entity_start: entity_end + 1]]
# 调整其他实体位置
adjust_pos = lambda x: x if x <= entity_start else x + len_diff
for j, (l, s, e, t) in enumerate(entities):
s, e = adjust_pos(s), adjust_pos(e)
t = text[s: e + 1]
entities[j] = [l, s, e, t]
example[1]["tokens"] = list(text)
example[1]["entities"] = entities
example[1]["sent_start"] = sent_start
example[1]["sent_end"] = sent_start + len(text)
return example
# TODO:
class ReDataMasking:
def __init__(self):
self.nc_reobj = re.compile("(现金)?(人民币)?[0-9]+(.[0-9]+)?余?元(现金)?(人民币)?")
def __call__(self, example):
...
class Example2Feature:
def __init__(self, tokenizer, label2id, max_seq_length, max_span_length):
self.tokenizer = tokenizer
self.label2id = label2id
self.max_seq_length = max_seq_length
self.max_span_length = max_span_length
def __call__(self, example):
return self._convert_example_to_feature(example)
def _encode_span(self, max_length, input_len, sent_start, sent_end):
spans = []; span_mask = []
for i in range(sent_start, sent_end):
for j in range(i, min(min(max_length, sent_end), i + self.max_span_length)):
spans.append([i, j, j - i + 1])
span_mask.append(0 if i >= input_len else 1)
spans = torch.tensor([spans]) # (1, num_spans, 3)
span_mask = torch.tensor([span_mask]) # (1, num_spans)
return spans, span_mask
def _encode_label(self, entities, spans):
tag_o = self.label2id["O"]
entities = {(b + 1, e + 1): self.label2id[t] for t, b, e, _ in entities}
label = [entities.get((b, e), tag_o) for b, e, l in spans[0]]
label = torch.tensor([label]) # (1, num_spans)
return label
def _convert_example_to_feature(self, example):
id_ = example[1]["id"]
tokens = example[1]["tokens"]
entities = example[1]["entities"]
sent_start = example[1]["sent_start"]
sent_end = example[1]["sent_end"]
# encode input
inputs = self.tokenizer.encode_plus(
text=tokens,
text_pair=None,
add_special_tokens=True,
padding="max_length",
truncation="longest_first",
max_length=self.max_seq_length,
is_split_into_words=True,
return_tensors="pt",
)
inputs["input_len"] = inputs["attention_mask"].sum(dim=1) # for special tokens
input_len = inputs["input_len"].item()
inputs["spans"], inputs["span_mask"] = self._encode_span(
input_len, input_len, sent_start, sent_end) # dynamic batch
inputs["sent_start"] = torch.tensor([sent_start])
inputs["sent_end"] = torch.tensor([sent_end])
if entities is None:
inputs["label"] = None
return inputs
# encode label
inputs["label"] = self._encode_label(entities,
inputs["spans"].cpu().numpy().tolist())
return inputs
class FGM():
def __init__(self, model, emb_name, epsilon=1.0):
# emb_name这个参数要换成你模型中embedding的参数名
self.model = model
self.epsilon = epsilon
self.emb_name = emb_name
self.backup = {}
def attack(self):
for name, param in self.model.named_parameters():
if param.requires_grad and self.emb_name in name:
self.backup[name] = param.data.clone()
norm = torch.norm(param.grad)
if norm != 0 and not torch.isnan(norm):
r_at = self.epsilon * param.grad / norm
param.data.add_(r_at)
def restore(self):
for name, param in self.model.named_parameters():
if param.requires_grad and self.emb_name in name:
assert name in self.backup
param.data = self.backup[name]
self.backup = {}
class PGD:
def __init__(self, model, eps=1., alpha=0.3):
self.model = (
model.module if hasattr(model, "module") else model
)
self.eps = eps
self.alpha = alpha
self.emb_backup = {}
self.grad_backup = {}
def attack(self, emb_name='word_embeddings', is_first_attack=False):
for name, param in self.model.named_parameters():
if param.requires_grad and emb_name in name:
if is_first_attack:
self.emb_backup[name] = param.data.clone()
norm = torch.norm(param.grad)
if norm != 0 and not torch.isnan(norm):
r_at = self.alpha * param.grad / norm
param.data.add_(r_at)
param.data = self.project(name, param.data)
def restore(self, emb_name='word_embeddings'):
for name, param in self.model.named_parameters():
if param.requires_grad and emb_name in name:
assert name in self.emb_backup
param.data = self.emb_backup[name]
self.emb_backup = {}
def project(self, param_name, param_data):
r = param_data - self.emb_backup[param_name]
if torch.norm(r) > self.eps:
r = self.eps * r / torch.norm(r)
return self.emb_backup[param_name] + r
def backup_grad(self):
for name, param in self.model.named_parameters():
if param.requires_grad and param.grad is not None:
self.grad_backup[name] = param.grad.clone()
def restore_grad(self):
for name, param in self.model.named_parameters():
if param.requires_grad and param.grad is not None:
param.grad = self.grad_backup[name]
def get_model_path_list(base_dir):
"""
从文件夹中获取 model.pt 的路径
"""
model_lists = []
for root, dirs, files in os.walk(base_dir):
for _file in files:
if 'pytorch_model.bin' == _file:
model_lists.append(os.path.join(root, _file))
model_lists = [x for x in model_lists if 'checkpoint-' in x and 'swa' not in x]
model_lists = sorted(model_lists,
key=lambda x: int(x.split('/')[-2].split('-')[-1]))
print(model_lists)
return model_lists
def swa(model, model_dir, swa_type='weight',swa_start=1):
"""
swa 滑动平均模型,一般在训练平稳阶段再使用 SWA
"""
model_path_list = get_model_path_list(model_dir)
# assert 1 <= swa_start < len(model_path_list) - 1, \
# f'Using swa, swa start should smaller than {len(model_path_list) - 1} and bigger than 0'
swa_model = copy.deepcopy(model)
swa_n = 0.
with torch.no_grad():
for _ckpt in model_path_list[swa_start:]:
logger.info(f'Load model from {_ckpt}')
model.load_state_dict(torch.load(_ckpt, map_location=torch.device('cpu')))
tmp_para_dict = dict(model.named_parameters())
alpha = 1. / (swa_n + 1.)
for name, para in swa_model.named_parameters():
para.copy_(tmp_para_dict[name].data.clone() * alpha + para.data.clone() * (1. - alpha))
swa_n += 1
# use 100000 to represent swa to avoid clash
swa_model_dir = os.path.join(model_dir, f'checkpoint-swa-{swa_type}')
if not os.path.exists(swa_model_dir):
os.mkdir(swa_model_dir)
logger.info(f'Save swa model in: {swa_model_dir}')
swa_model_path = os.path.join(swa_model_dir, 'pytorch_model.bin')
torch.save(swa_model.state_dict(), swa_model_path)
return swa_model
def seed_everything(seed=None, reproducibility=True):
'''
init random seed for random functions in numpy, torch, cuda and cudnn
Args:
seed (int): random seed
reproducibility (bool): Whether to require reproducibility
'''
if seed is None:
seed = int(_select_seed_randomly())
random.seed(seed)
np.random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
if reproducibility:
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
else:
torch.backends.cudnn.benchmark = True
torch.backends.cudnn.deterministic = False
def init_logger(name, log_file='', log_file_level=logging.NOTSET):
'''
初始化logger
'''
log_format = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
datefmt='%m/%d/%Y %H:%M:%S')
logger = logging.getLogger(name)
logger.setLevel(logging.INFO)
console_handler = logging.StreamHandler()
console_handler.setFormatter(log_format)
logger.handlers = [console_handler]
if log_file and log_file != '':
file_handler = logging.FileHandler(log_file)
file_handler.setLevel(log_file_level)
logger.addHandler(file_handler)
return logger
def train(args, model, processor, tokenizer):
""" Train the model """
train_dataset = load_dataset(args, processor, tokenizer, data_type='train')
args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu)
train_sampler = RandomSampler(train_dataset) if args.local_rank == -1 else DistributedSampler(train_dataset)
train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=args.train_batch_size,
collate_fn=NerDataset.collate_fn)
if args.max_steps > 0:
t_total = args.max_steps
args.num_train_epochs = args.max_steps // (len(train_dataloader) // args.gradient_accumulation_steps) + 1
else:
t_total = len(train_dataloader) // args.gradient_accumulation_steps * args.num_train_epochs
if args.evaluate_each_epoch:
args.logging_steps = args.save_steps = int(t_total // args.num_train_epochs)
# Prepare optimizer and schedule (linear warmup and decay)
no_decay = ["bias", "LayerNorm.weight"]
bert_param_optimizer = list(model.roformer.named_parameters()) if 'roformer' in args.model_type else list(model.bert.named_parameters())
bert_param_optimizer_ids = [id(p) for n, p in bert_param_optimizer]
other_param_optimizer = [(n, p) for n, p in model.named_parameters() if id(p) not in bert_param_optimizer_ids]
optimizer_grouped_parameters = [
{'params': [p for n, p in bert_param_optimizer if not any(nd in n for nd in no_decay)],
'weight_decay': args.weight_decay, 'lr': args.learning_rate},
{'params': [p for n, p in bert_param_optimizer if any(nd in n for nd in no_decay)],
'weight_decay': 0.0, 'lr': args.learning_rate},
{'params': [p for n, p in other_param_optimizer],
'weight_decay': args.weight_decay, 'lr': args.other_learning_rate}
]
args.warmup_steps = int(t_total * args.warmup_proportion)
if args.optimizer == "adamw":
optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon)
elif args.optimizer == "lamb":
optimizer = Lamb(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon)
scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=args.warmup_steps,
num_training_steps=t_total)
# Check if saved optimizer or scheduler states exist
if os.path.isfile(os.path.join(args.model_name_or_path, "optimizer.pt")) and os.path.isfile(
os.path.join(args.model_name_or_path, "scheduler.pt")):
# Load in optimizer and scheduler states
optimizer.load_state_dict(torch.load(os.path.join(args.model_name_or_path, "optimizer.pt")))
scheduler.load_state_dict(torch.load(os.path.join(args.model_name_or_path, "scheduler.pt")))
if args.fp16:
try:
from apex import amp
except ImportError:
raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use fp16 training.")
model, optimizer = amp.initialize(model, optimizer, opt_level=args.fp16_opt_level)
scaler = torch.cuda.amp.GradScaler()
# multi-gpu training (should be after apex fp16 initialization)
if args.n_gpu > 1:
model = torch.nn.DataParallel(model)
# Distributed training (should be after apex fp16 initialization)
if args.local_rank != -1:
model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank],
output_device=args.local_rank,
find_unused_parameters=True)
if args.do_fgm:
fgm = FGM(model, emb_name=args.fgm_name, epsilon=args.fgm_epsilon)
if args.do_pgd:
pgd = PGD(model=model)
# Train!
logger.info("***** Running training *****")
logger.info(" Num examples = %d", len(train_dataset))
logger.info(" Num Epochs = %d", args.num_train_epochs)
logger.info(" Instantaneous batch size per GPU = %d", args.per_gpu_train_batch_size)
logger.info(" Total train batch size (w. parallel, distributed & accumulation) = %d",
args.train_batch_size
* args.gradient_accumulation_steps
* (torch.distributed.get_world_size() if args.local_rank != -1 else 1),