This repository has been archived by the owner on May 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
semi_sup_train.py
2103 lines (1856 loc) · 98.1 KB
/
semi_sup_train.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 copy
import json
import torch
import pickle
import random
import hashlib
import subprocess
import numpy as np
from tensorboardX import SummaryWriter
from collections import OrderedDict
from train import export_logit, evaluate, training_loop
from unsup_utils import select_samples_with_GMM, select_data_from_logit, unsupervised_sample_selection
from utils_ner import select_and_write_data, write_conll_data, select_and_write_source_data, read_from_path, read_examples_from_file
from model import load_model, save_model_checkpoint
from load_examples import load_and_cache_examples
from lm_augmentation import augment_data
def create_aug_data(args, external_dataset_address, langs, model, tokenizer, labels, mode, top_k, pad_token_label_id, logger):
logger.info("[::] Lang = {}, Mode = {} data prediction.".format(langs, mode))
logger.info("--"*10)
if external_dataset_address is not None:
for dt in external_dataset_address:
logger.info("Dataset info {}, dataset length {}".format(
dt,
len(
read_from_path(
dt.split(";")[0],
encoding=dt.split(";")[1]
)
)
))
temp_train_data_percentage = args.train_data_percentage
args.train_data_percentage = 100
loss_dict, logit_dict, _, _, _= export_logit(
args,
model, tokenizer, labels,
pad_token_label_id, mode=mode, external_data=external_dataset_address,
prefix="", langs = langs, logger=logger, debug=0
)
args.train_data_percentage = temp_train_data_percentage
external_files = []
for dict_key in loss_dict.keys():
logger.info("{} Distillation".format(dict_key))
logger.info("--"*10)
temp_top_k = args.top_k
args.top_k = args.top_k if top_k is None else top_k
indices, gmm_model = data_distillation(
args,
dict_key,
pseudo_loss_dict=loss_dict,
logit_dict=logit_dict,
mode="train",
logger=logger,
debug=0
)
args.top_k = temp_top_k
total_indexes = indices
address, indices = select_and_write_data(
dict_key,
args.output_dir,
total_indexes,
loss_dict,
labels,
logger=logger,
postfix = str(random.randint(0,10000000))
)
external_files.append(address)
return external_files
def create_file_name(file_name1, file_name2, logger):
new_name = file_name1 + "__" + file_name2
if len(new_name) > 50:
temp = new_name
logger.info("File name size exceeds 50 length, using hash instead")
new_name = hashlib.sha256(new_name.encode('utf-8')).hexdigest()
logger.info("[sha256_hashing]:: {} : {} ".format(temp, new_name))
return new_name
def merge_two_dataset(file_info_1, file_info_2, output_dir, logger):
address1, encoding1, lang1 = file_info_1.split(";")[0], file_info_1.split(";")[1], file_info_1.split(";")[2]
address2, encoding2, lang2 = file_info_2.split(";")[0], file_info_2.split(";")[1], file_info_2.split(";")[2]
if encoding1 != encoding2:
encoding1 = "latin-1"
encoding2 = "latin-1"
assert lang1 == lang2
file_name1 = os.path.split(address1)[-1]
file_name2 = os.path.split(address2)[-1]
new_name = create_file_name(file_name1, file_name2, logger)
full_path = os.path.join(output_dir, new_name)
assert os.path.exists(full_path) == False
subprocess.check_output("touch {}".format(full_path), shell=True)
subprocess.check_output("cat {} >> {}".format(address1, full_path), shell=True)
subprocess.check_output("echo \"\n\" >> {}".format(full_path), shell=True)
subprocess.check_output("cat {} >> {}".format(address2, full_path), shell=True)
new_file_info = full_path+";"+encoding1+";"+lang1
return new_file_info
def partial_single_self_training(
args, MODEL_CLASSES,
model, tokenizer,
labels, pad_token_label_id, num_labels,
is_GMM_selection=0,
logger=None,
):
best_dev_scores = None
test_scores_in_best_src_dev = None
logger.info("Dev Evaluation")
logger.info("--"*10)
dev_scores = evaluate(
args,
model, tokenizer, labels,
pad_token_label_id, "dev",
prefix="", langs = args.tgt_lang,
logger=logger
)
logger.info("Test Evaluation")
logger.info("--"*10)
test_scores = evaluate(
args,
model, tokenizer, labels,
pad_token_label_id, "test",
prefix="", langs = args.tgt_lang,
logger=logger
)
backup_overwrite_cache = args.overwrite_cache
args.overwrite_cache = True
logger.info("Source Train Data Loading")
logger.info("--"*10)
train_dataset = OrderedDict()
# source dataset load
train_dataset, guids = load_and_cache_examples(
args, tokenizer, labels, pad_token_label_id,
mode="train", langs=args.src_lang, logger=logger
)
datasets = []
if "self_src" in args.aug_desc.split(";"):
if args.train_data_percentage == 100:
logger.warning("[***] :: train_data_percentage is 100 and we are augmenting source dataset...!!!!")
logger.info("Pseudo Source Train Dataset Creation Process Started ...")
logger.info("=="*10)
src_train_dataset = create_aug_data(
args, external_dataset_address=None,
langs=args.src_lang,
model=model, tokenizer=tokenizer, labels=labels,
mode="train", top_k=args.top_k,
pad_token_label_id=pad_token_label_id,
logger=logger
)
datasets += src_train_dataset
if "self_tgt" in args.aug_desc.split(";"):
logger.info("Pseudo Target Train Dataset Creation Process Started ...")
logger.info("=="*10)
tgt_train_datasets = create_aug_data(
args, external_dataset_address=None,
langs=args.tgt_lang,
model=model, tokenizer=tokenizer, labels=labels,
mode="train", top_k=100,
pad_token_label_id=pad_token_label_id,
logger=logger
)
datasets += tgt_train_datasets
if "src_aug" in args.aug_desc.split(";"):
logger.info("Pseudo Augmented Source Dataset Creation Process Started ...")
logger.info("=="*10)
src_aug_datasets = create_aug_data(
args, external_dataset_address=args.external_data,
langs=args.src_lang,
model=model, tokenizer=tokenizer, labels=labels,
mode="aug", top_k=args.top_k,
pad_token_label_id=pad_token_label_id,
logger=logger
)
datasets += src_aug_datasets
if "tgt_aug" in args.aug_desc.split(";"):
logger.info("Pseudo Augmented Target Dataset Creation Process Started ...")
logger.info("=="*10)
tgt_aug_datasets = create_aug_data(
args, external_dataset_address=args.external_data,
langs=args.tgt_lang,
model=model, tokenizer=tokenizer, labels=labels,
mode="aug", top_k=args.top_k,
pad_token_label_id=pad_token_label_id,
logger=logger
)
datasets += tgt_aug_datasets
total_sent_len = 0
if args.merge_datasets:
for idx, dataset in enumerate(datasets):
total_sent_len = len(read_from_path(dataset.split(";")[0], encoding=dataset.split(";")[1]))
if idx == 0:
continue
logger.info("Merging Dataset {} ({}) and {} ({})".format(
datasets[idx-1], len(read_from_path(datasets[idx-1].split(";")[0], encoding=datasets[idx-1].split(";")[1])),
datasets[idx], len(read_from_path(datasets[idx].split(";")[0], encoding=datasets[idx].split(";")[1]))))
datasets[idx] = merge_two_dataset(datasets[idx-1], datasets[idx], args.output_dir, logger)
logger.info("New Dataset address {} ({})".format(
datasets[idx], len(read_from_path(datasets[idx].split(";")[0], encoding=datasets[idx].split(";")[1]))))
datasets = [datasets[-1]]
try:
found_sent_len = len(read_from_path(datasets[0].split(";")[0], encoding=datasets[0].split(";")[1]))
assert total_sent_len == found_sent_len
except:
logger.info("Total Number of sentence {}, found {}".format(total_sent_len, found_sent_len))
logger.info("[::] Creating Tensor of Training Datasets...")
temp_train_data_percentage = args.train_data_percentage
args.train_data_percentage = 100
for dataset in datasets:
logger.info("Dataset Name : {}".format(dataset))
tensor_dataset, _ = load_and_cache_examples(
args, tokenizer, labels, pad_token_label_id, external_data=[dataset],
mode="aug", langs=dataset.split(";")[-1], logger=logger
)
for k, v in tensor_dataset.items():
assert k not in train_dataset
train_dataset[k] = v
args.train_data_percentage = temp_train_data_percentage
args.overwrite_cache = backup_overwrite_cache
tot_sample = 0
for k, v in train_dataset.items():
tot_sample += len(v)
logger.info("TRAINING IS STARTING ...")
logger.info("=="*10)
if tot_sample > 0:
if args.semi_sup_max_steps == 0:
args.max_steps = tot_sample*3//(args.per_gpu_train_batch_size * args.gradient_accumulation_steps)
else:
args.max_steps = args.semi_sup_max_steps
args.warmup_steps = (args.max_steps*10)//100
global_step, tr_loss, IsUpdated, best_dev_scores, test_scores_in_best_src_dev = training_loop(
args, train_dataset,
model, tokenizer, labels, pad_token_label_id,
logger=logger,
prev_best_dev_scores = best_dev_scores,
prev_test_scores_in_best_src_dev=test_scores_in_best_src_dev
)
logger.info("TRAINING DONE FOR [::] {}".format(args.external_data))
else:
logger.info("TRAINING POSTPONED DUE TO INSUFFICIENT SAMPLES [::]")
# def partial_single_self_training(
# args, MODEL_CLASSES,
# model, tokenizer,
# labels, pad_token_label_id, num_labels,
# is_GMM_selection=0,
# logger=None,
# ):
# best_dev_scores = None
# test_scores_in_best_src_dev = None
# logger.info("Dev Evaluation")
# logger.info("--"*10)
# dev_scores = evaluate(
# args,
# model, tokenizer, labels,
# pad_token_label_id, "dev",
# prefix="", langs = args.tgt_lang,
# logger=logger
# )
# logger.info("Test Evaluation")
# logger.info("--"*10)
# test_scores = evaluate(
# args,
# model, tokenizer, labels,
# pad_token_label_id, "test",
# prefix="", langs = args.tgt_lang,
# logger=logger
# )
# backup_overwrite_cache = args.overwrite_cache
# args.overwrite_cache = True
# logger.info("Source Train Data Loading")
# logger.info("--"*10)
# # source dataset load
# train_dataset, _ = load_and_cache_examples(
# args, tokenizer, labels, pad_token_label_id,
# mode="train", langs=args.src_lang, logger=logger
# )
# if "self_tgt" in args.aug_desc.split(";"):
# logger.info("Original Target Train Prediction")
# logger.info("--"*10)
# temp_train_data_percentage = args.train_data_percentage
# args.train_data_percentage = 100
# loss_dict, logit_dict, _, _, _= export_logit(
# args,
# model, tokenizer, labels,
# pad_token_label_id, args.aug_mode,
# prefix="", langs = args.tgt_lang, logger=logger, debug=0
# )
# args.train_data_percentage = temp_train_data_percentage
# logger.info("Original Target Train Distillation")
# logger.info("--"*10)
# external_files = []
# for dict_key in loss_dict.keys():
# temp_top_k = args.top_k
# args.top_k = 100
# indices, gmm_model = data_distillation(
# args,
# dict_key,
# pseudo_loss_dict=loss_dict,
# logit_dict=logit_dict,
# mode="train",
# logger=logger,
# debug=0
# )
# args.top_k = temp_top_k
# total_indexes = indices
# address, indices = select_and_write_data(
# dict_key,
# args.output_dir,
# total_indexes,
# loss_dict,
# labels,
# logger=logger,
# postfix = str(random.randint(0,10000000))
# )
# external_files.append(address)
# logger.info("Target Train Pseudo Data Loading")
# logger.info("--"*10)
# # target pseudo language dataset
# temp_train_data_percentage = args.train_data_percentage
# args.train_data_percentage = 100
# target_dataset, _ = load_and_cache_examples(
# args, tokenizer, labels, pad_token_label_id, external_data=external_files,
# mode="aug", langs=args.tgt_lang, logger=logger
# )
# args.train_data_percentage = temp_train_data_percentage
# logger.info("Accumulating Target Train Pseudo Data to Training Datasets ...")
# for k, v in target_dataset.items():
# assert k not in train_dataset
# train_dataset[k] = v
# langs = "None"
# if "src_aug" in args.aug_desc.split(";"):
# langs = args.src_lang
# if "tgt_aug" in args.aug_desc.split(";"):
# if langs == "None" or langs == "":
# langs = args.tgt_lang
# else:
# langs = langs + ";" + args.tgt_lang
# logger.info("Source {} and/or Target {} Augmented data prediction : langs flag {}...".format(args.src_lang, args.tgt_lang, langs))
# logger.info("--"*10)
# temp_train_data_percentage = args.train_data_percentage
# args.train_data_percentage = 100
# loss_dict, logit_dict, _, _, _= export_logit(
# args,
# model, tokenizer, labels,
# pad_token_label_id, "aug", external_data=args.external_data,
# prefix="", langs = langs, logger=logger, debug=0
# )
# args.train_data_percentage = temp_train_data_percentage
# for dict_key in loss_dict.keys():
# logger.info("{} Distillation".format(dict_key))
# logger.info("--"*10)
# indices, gmm_model = data_distillation(
# args,
# dict_key,
# pseudo_loss_dict=loss_dict,
# logit_dict=logit_dict,
# mode="train",
# logger=logger,
# debug=0
# )
# total_indexes = indices
# address, indices = select_and_write_data(
# dict_key,
# args.output_dir,
# total_indexes,
# loss_dict,
# labels,
# logger=logger,
# postfix = str(random.randint(0,10000000))
# )
# lang = dict_key.split(";")[-1]
# logger.info("{} Data Loading".format(dict_key))
# logger.info("--"*10)
# temp_train_data_percentage = args.train_data_percentage
# args.train_data_percentage = 100
# aug_dataset, _ = load_and_cache_examples(
# args, tokenizer, labels, pad_token_label_id, external_data=[address],
# mode="aug", langs=lang, logger=logger
# )
# args.train_data_percentage = temp_train_data_percentage
# logger.info("Accumulating {} Pseudo Data to Training Datasets".format(dict_key))
# logger.info("--"*10)
# for k, v in aug_dataset.items():
# assert k not in train_dataset
# train_dataset[k] = v
# args.overwrite_cache = backup_overwrite_cache
# tot_sample = 0
# for k, v in train_dataset.items():
# tot_sample += len(v)
# logger.info("TRAINING IS STARTING ...")
# logger.info("=="*10)
# if tot_sample > 0:
# if args.semi_sup_max_steps == 0:
# args.max_steps = tot_sample*3//(args.per_gpu_train_batch_size * args.gradient_accumulation_steps)
# else:
# args.max_steps = args.semi_sup_max_steps
# args.warmup_steps = (args.max_steps*10)//100
# global_step, tr_loss, IsUpdated, best_dev_scores, test_scores_in_best_src_dev = training_loop(
# args, train_dataset,
# model, tokenizer, labels, pad_token_label_id,
# logger=logger,
# prev_best_dev_scores = best_dev_scores,
# prev_test_scores_in_best_src_dev=test_scores_in_best_src_dev
# )
# logger.info("TRAINING DONE FOR [::] {}".format(args.external_data))
# else:
# logger.info("TRAINING POSTPONED DUE TO INSUFFICIENT SAMPLES [::]")
def classical_self_training(
args, MODEL_CLASSES,
model, tokenizer,
labels, pad_token_label_id, num_labels,
is_GMM_selection=0,
logger=None
):
IsUpdated = True
best_dev_scores = None
test_scores_in_best_src_dev = None
total_cnt = 0
random.seed(args.seed)
total_indexes = None
while IsUpdated:
###################
# evaluate the score of the best model
###################
dev_scores = evaluate(
args,
model, tokenizer, labels,
pad_token_label_id, "dev",
prefix="", langs = args.tgt_lang,
logger=logger
)
test_scores = evaluate(
args,
model, tokenizer, labels,
pad_token_label_id, "test",
prefix="", langs = args.tgt_lang,
logger=logger
)
###################
# extract logit/loss etc. info from the model with respect to dataset.
###################
loss_dict, logit_dict, _, _, _= export_logit(
args,
model, tokenizer, labels,
pad_token_label_id, args.aug_mode,
prefix="", langs = args.tgt_lang, logger=logger
)
external_files = []
for dict_key in loss_dict.keys():
indexes = select_data_from_logit(
args,
dict_key,
logit_dict,
loss_dict,
path=args.output_dir,
bin_increment=.01,
top_k=args.top_k,
noise_threshold=0,
min_length_restriction=-10,
max_length_restriction=1500000,
mode="train",
logger=logger,
debug=0,
isGMM=0
)
total_indexes = indexes if total_indexes is None else list(set(total_indexes+indexes))
address, indices = select_and_write_data(
dict_key,
args.output_dir,
total_indexes,
loss_dict,
labels,
logger=logger,
postfix = str(random.randint(0,10000000))
)
external_files.append(address)
args.external_data = external_files
backup_overwrite_cache = args.overwrite_cache
args.overwrite_cache = True
train_dataset, _ = load_and_cache_examples(
args, tokenizer, labels, pad_token_label_id,
mode="aug", langs=args.tgt_lang, logger=logger
)
args.overwrite_cache = backup_overwrite_cache
tot_sample = 0
for k, v in train_dataset.items():
tot_sample += len(v)
if tot_sample > 0:
if args.semi_sup_max_steps == 0:
args.max_steps = tot_sample*6//(args.per_gpu_train_batch_size * args.gradient_accumulation_steps)
else:
args.max_steps = args.semi_sup_max_steps
args.warmup_steps = (args.max_steps*10)//100
global_step, tr_loss, IsUpdated, best_dev_scores, test_scores_in_best_src_dev = training_loop(
args, train_dataset,
model, tokenizer, labels, pad_token_label_id,
logger=logger,
prev_best_dev_scores = best_dev_scores,
prev_test_scores_in_best_src_dev=test_scores_in_best_src_dev
)
logger.info("TRAINING DONE FOR [::] {}".format(args.external_data))
else:
logger.info("TRAINING POSTPONED DUE TO INSUFFICIENT SAMPLES [::]")
IsUpdated = False
def pseudo_self_training(
args, MODEL_CLASSES,
model, tokenizer,
labels, pad_token_label_id, num_labels,
is_GMM_selection=0,
logger=None
):
IsUpdated = True
best_dev_scores = None
test_scores_in_best_src_dev = None
total_cnt = 0
random.seed(args.seed)
while IsUpdated:
###################
# load best model
###################
config, tokenizer, model = load_model(
args.model_type, MODEL_CLASSES,
args.best_dev_model, args.best_dev_config, args.tokenizer_name,
num_labels, args.cache_dir, args.do_lower_case, args.device
)
###################
# evaluate the score of the best model
###################
dev_scores = evaluate(
args,
model, tokenizer, labels,
pad_token_label_id, "dev",
prefix="", langs = args.tgt_lang,
logger=logger
)
test_scores = evaluate(
args,
model, tokenizer, labels,
pad_token_label_id, "test",
prefix="", langs = args.tgt_lang,
logger=logger
)
###################
# extract logit/loss etc. info from the model with respect to dataset.
###################
loss_dict, logit_dict, _, _, _ = export_logit(
args,
model, tokenizer, labels,
pad_token_label_id, args.aug_mode,
prefix="", langs = args.tgt_lang, logger=logger
)
###################
# Create dataset
###################
external_files = []
for dict_key in loss_dict.keys():
if is_GMM_selection == 0:
indexes = np.array(list(range(len(loss_dict[dict_key]))))
address, indices = select_and_write_data(
dict_key,
args.output_dir,
indexes,
loss_dict,
labels,
logger=logger,
postfix = str(random.randint(0,10000000))
)
external_files.append(address)
else:
# rng = []
# val = 0.0
# while val <= 1:
# val += .05
# rng.append(val)
# rng = args.posterior_threshold
# for posterior_threshold in rng:
# args.posterior_threshold = [posterior_threshold]
indexes, _ = select_samples_with_GMM(
args=args,
dict_key=dict_key,
loss_dict=loss_dict,
path=args.output_dir,
bin_increment=.01,
noise_threshold=args.noise_threshold,
min_length_restriction=args.min_length_restriction,
max_length_restriction=args.max_length_restriction,
mode=args.aug_mode,
logger=logger,
debug=0
)
address, indices = select_and_write_data(
dict_key,
args.output_dir,
indexes,
loss_dict,
labels,
logger=logger,
postfix = str(random.randint(0,10000000)) + "." + str(round(args.posterior_threshold[0], 2))
)
external_files.append(address)
###################
# Train
###################
for external_file in external_files:
args.external_data = [external_file]
logger.info("NEW TRAINING LOOP [::]")
logger.info("="*20)
logger.info("="*20)
logger.info("TRAINING MODEL ON [::] {}".format(args.external_data))
backup_overwrite_cache = args.overwrite_cache
args.overwrite_cache = True
train_dataset, _ = load_and_cache_examples(
args, tokenizer, labels, pad_token_label_id,
mode="aug", langs=args.tgt_lang, logger=logger
)
args.overwrite_cache = backup_overwrite_cache
tot_sample = 0
for k, v in train_dataset.items():
tot_sample += len(v)
if tot_sample > 0:
if args.semi_sup_max_steps == 0:
args.max_steps = tot_sample*3//(args.per_gpu_train_batch_size * args.gradient_accumulation_steps)
else:
args.max_steps = args.semi_sup_max_steps
args.warmup_steps = (args.max_steps*10)//100
global_step, tr_loss, IsUpdated, best_dev_scores, test_scores_in_best_src_dev = training_loop(
args, train_dataset,
model, tokenizer, labels, pad_token_label_id,
logger=logger,
prev_best_dev_scores = best_dev_scores,
prev_test_scores_in_best_src_dev=test_scores_in_best_src_dev
)
logger.info("TRAINING DONE FOR [::] {}".format(args.external_data))
else:
logger.info("TRAINING POSTPONED DUE TO INSUFFICIENT SAMPLES [::]")
if is_GMM_selection == 1:
IsUpdated = False
def select_theta(args, MODEL_CLASSES, num_labels, theta, retrain=0, logger=None):
if retrain == 0:
model_name_or_path = os.path.join(theta, "pytorch_model.bin")
config_name = os.path.join(theta, "config.json")
elif retrain == 1:
model_name_or_path = "bert-base-multilingual-cased"
config_name = "bert-base-multilingual-cased"
else:
raise NotImplementedError()
config, tokenizer, model = load_model(
args.model_type, MODEL_CLASSES,
model_name_or_path, config_name, args.tokenizer_name,
num_labels, args.cache_dir, args.do_lower_case, args.device
)
if retrain == 1:
save_address = save_model_checkpoint(
args, None, None,
model,
logger=logger,
overwrite_address = theta
)
return config, tokenizer, model
def retrieve_sentences_with_idx(data, intersect_indices):
sentences = read_from_path(data[1].split(";")[0], encoding=data[1].split(";")[1])
indices = data[2]
assert len(sentences) == len(indices)
intersect_sentences = []
for index, sentence in zip(indices, sentences):
if index in intersect_indices:
intersect_sentences.append(sentence)
return intersect_sentences
def combine_file_name(k_file_info, j_file_info):
root_address = os.path.split(k_file_info)[0]
k_file_name = os.path.split(k_file_info)[1].split(";")[0]
j_file_name = os.path.split(j_file_info)[1].split(";")[0]
assert k_file_info.split(";")[1] == j_file_info.split(";")[1]
assert k_file_info.split(";")[2] == j_file_info.split(";")[2]
prefix_name = k_file_name
postfix_name = ""
idx = -1
for __i, (k_content, j_content) in enumerate(zip(k_file_name.split("."), j_file_name.split("."))):
if k_content != j_content:
idx = __i
break
assert idx != -1
for __i, j_content in enumerate(j_file_name.split(".")):
if __i >= idx:
postfix_name = postfix_name + "." + j_content
file_name = prefix_name + "._._." + postfix_name
# print(k_file_name)
# print(j_file_name)
# print(file_name)
full_file_name = os.path.join(root_address, file_name)
full_file_info = full_file_name+'.int' + ';' + k_file_info.split(";")[1] + ';' + k_file_info.split(";")[2]
return full_file_info
def get_intersected_dataset_from_indices(kdata, jdata, logger=None):
kindices = kdata[2]
jindices = jdata[2]
intersect_indices = [ index for index in kindices if index in jindices ]
logger.info("Original data size kdata = {}, jdata = {}, k_data \intersect j_data = {} ".format(len(kindices), len(jindices), len(intersect_indices)))
# print(intersect_indices)
k_intersect_sentence = retrieve_sentences_with_idx(kdata, intersect_indices)
j_intersect_sentence = retrieve_sentences_with_idx(jdata, intersect_indices)
assert len(k_intersect_sentence) == len(j_intersect_sentence)
intersected_sentences_with_lables = []
for k_sent_info, j_sent_info in zip(k_intersect_sentence, j_intersect_sentence):
flag = 1
for k_w, j_w in zip(k_sent_info, j_sent_info):
# print(k_w[0], j_w[0] )
assert k_w[0] == j_w[0]
if k_w[-1] != j_w[-1]:
flag = 0
break
if flag:
intersected_sentences_with_lables.append(k_sent_info)
logger.info("{} and {} dataset is INTERSECTING ...".format(kdata[1], jdata[1]))
full_file_info = combine_file_name(kdata[1], jdata[1])
logger.info("intersected file name {}".format(full_file_info))
file_info = write_conll_data(full_file_info, intersected_sentences_with_lables, logger=logger)
return file_info, intersect_indices
def get_unioned_dataset_from_indices(kdata, jdata, logger=None):
kindices = kdata[2]
jindices = jdata[2]
intersect_indices = [ index for index in kindices if index in jindices ]
logger.info("Original data size kdata = {}, jdata = {}, k_data \intersect j_data = {} ".format(len(kindices), len(jindices), len(intersect_indices)))
# print(intersect_indices)
k_intersect_sentence = retrieve_sentences_with_idx(kdata, intersect_indices)
j_intersect_sentence = retrieve_sentences_with_idx(jdata, intersect_indices)
assert len(k_intersect_sentence) == len(j_intersect_sentence)
sentences_with_lables = []
for k_sent_info, j_sent_info in zip(k_intersect_sentence, j_intersect_sentence):
flag = 1
for k_w, j_w in zip(k_sent_info, j_sent_info):
# print(k_w[0], j_w[0] )
assert k_w[0] == j_w[0]
if k_w[-1] != j_w[-1]:
flag = 0
break
if flag:
sentences_with_lables.append(k_sent_info)
# print(len(sentences_with_lables))
k_not_intersected, j_not_intersected = [], []
for index in kindices:
if index not in intersect_indices:
k_not_intersected.append(index)
for index in jindices:
if index not in intersect_indices:
j_not_intersected.append(index)
k_not_intersect_sentence = retrieve_sentences_with_idx(kdata, k_not_intersected)
j_not_intersect_sentence = retrieve_sentences_with_idx(jdata, j_not_intersected)
for k_sent_info in k_not_intersect_sentence:
sentences_with_lables.append(k_sent_info)
for j_sent_info in j_not_intersect_sentence:
sentences_with_lables.append(j_sent_info)
logger.info("k_not_intersected {}, j_not_intersected {}, intersect_indices {}, total indices {}"
.format(len(k_not_intersect_sentence), len(j_not_intersect_sentence), len(intersect_indices), len(sentences_with_lables)))
logger.info("{} and {} dataset is UNIONED ...".format(kdata[1], jdata[1]))
full_file_info = combine_file_name(kdata[1], jdata[1])
logger.info("UNIONED file name {}".format(full_file_info))
file_info = write_conll_data(full_file_info, sentences_with_lables, logger=logger)
unioned_indices = intersect_indices + k_not_intersected + j_not_intersected
return file_info, unioned_indices
def unsupervised_augmentation(args, data_address_list, logger=None):
address, output_aug_sentences = augment_data(
dataset_list=data_address_list,
output_dir=args.output_dir,
aug_type="successive_max",
only_ner_aug=0,
topk=1,
aug_per=15,
num_of_aug=5,
seed=1234,
logger=logger,
is_small_name=1,
debug=0
)
return address, output_aug_sentences
def supervised_augmentation(args, X_src_p, logger=None):
X_src_p_p_ss_mx, output_aug_sentences_ = unsupervised_augmentation(args, X_src_p, logger)
X_src_p_p_per_tkn, output_aug_sentences__ = augment_data(
dataset_list=X_src_p,
output_dir=args.output_dir,
aug_type="per_token",
only_ner_aug=1,
topk=3,
aug_per=15,
num_of_aug=5,
seed=1234,
logger=logger,
is_small_name=1,
debug=0
)
X_src_p_p = X_src_p_p_ss_mx + X_src_p_p_per_tkn
return X_src_p_p
def augmentation_lable_post_processing(
args, X_src_p_p, theta,
num_labels, MODEL_CLASSES, labels, pad_token_label_id,
post_tag, logger=None
):
orig_X_src_p_p = {}
for address in X_src_p_p:
orig_X_src_p_p[address] = read_from_path(address.split(";")[0], encoding=address.split(";")[1])
config, tokenizer, model = select_theta(args, MODEL_CLASSES, num_labels, theta, logger=logger)
temp = args.overwrite_cache
args.overwrite_cache=True
eval_dataset, _ = load_and_cache_examples(
args, tokenizer, labels, pad_token_label_id,
mode="aug", langs=args.aug_lang, logger=logger,
external_data=X_src_p_p
)
args.overwrite_cache = temp
test_scores = evaluate(
args,
model, tokenizer, labels,
pad_token_label_id, "aug",
prefix="",
langs = args.aug_lang,
logger=logger,
eval_dataset=eval_dataset
)
new_aug_dataset_address = []
for k, v in test_scores.items():
predictions = v[1]
assert k in orig_X_src_p_p
orig_label = orig_X_src_p_p[k]
assert len(orig_label) == len(predictions)
current_lang = k.split(";")[-1]
all_new_sentence_info = []
for pred, orig in zip(predictions, orig_label):
assert len(pred) == len(orig)
# print("pred : ", pred)
# print("orig : ", orig)
new_labels = []
for p, o in zip(pred, orig):
if current_lang in args.aug_label_propagate:
new_labels.append(o[-1])
if new_labels[-1] == "X":
new_labels[-1] = p
else:
new_labels.append(p)
# print("new_label : ", new_labels)
new_sent_info = [ [w[0], w[1], l] for w, l in zip(orig, new_labels)]
# print("new_sent_info : ", new_sent_info)
# break
all_new_sentence_info.append(new_sent_info)
file_info = k.split(";")[0] + ".prd.mrg." + post_tag + ";" + k.split(";")[1] + ";" + k.split(";")[2]
file_info = write_conll_data(file_info, all_new_sentence_info, logger=logger)
new_aug_dataset_address.append(file_info)
return new_aug_dataset_address
def get_training_dataset(
args, semi_sup_epoch_idx,
all_X_src_p_p, all_X_src_p,
all_X_tgt_p_p, all_X_tgt_p
):
external_training_data_address_list = []
if args.retrain or (args.partial_train_in_semi_sup_epochs and semi_sup_epoch_idx==0):
for dataset in args.train:
lang = dataset.split(";")[-1]
if lang == args.src_lang:
external_training_data_address_list.append(dataset)
if args.partial_train_in_semi_sup_epochs == 0 or \
(semi_sup_epoch_idx > 0 and semi_sup_epoch_idx < (args.max_semi_sup_epoch-1) ):
for dataset in all_X_src_p:
external_training_data_address_list.append(dataset)
for dataset in all_X_src_p_p:
external_training_data_address_list.append(dataset)
for dataset in all_X_tgt_p:
external_training_data_address_list.append(dataset)
for dataset in all_X_tgt_p_p:
external_training_data_address_list.append(dataset)
else:
if semi_sup_epoch_idx == 0:
for dataset in all_X_src_p:
external_training_data_address_list.append(dataset)
for dataset in all_X_src_p_p:
external_training_data_address_list.append(dataset)
elif semi_sup_epoch_idx == (args.max_semi_sup_epoch-1):
for dataset in all_X_tgt_p:
external_training_data_address_list.append(dataset)
for dataset in all_X_tgt_p_p:
external_training_data_address_list.append(dataset)
return external_training_data_address_list
def data_distillation(
args,
dict_key,
pseudo_loss_dict=None,
logit_dict=None,
mode="train",
logger=None,
debug=0
):
gmm_model= None
if args.data_distil_type =='gmm':
logger.info("applying GMM on {} data ...".format(dict_key))
indices, gmm_model = select_samples_with_GMM(
args,
dict_key,
pseudo_loss_dict,
path=args.output_dir,
bin_increment=.01,
noise_threshold=0,
min_length_restriction=-10,
max_length_restriction=1000000,
mode=mode,
logger=logger,
debug=debug
)
elif args.data_distil_type =='top_k':
logger.info("Selecting topk : {} \% confident data from {} ...".format(args.top_k, dict_key))
indices = select_data_from_logit(
args,
dict_key,
logit_dict,