-
Notifications
You must be signed in to change notification settings - Fork 0
/
pretrainer_gcvae.py
1951 lines (1775 loc) · 104 KB
/
pretrainer_gcvae.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 16 16:16:17 2022
@author: ifeanyi.ezukwoke
"""
#importing the libraries
seed_val = seed_trn = 42
import torch
from torch import nn
import torch.nn.functional as F
from torch.nn import CrossEntropyLoss
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.layers.experimental.preprocessing import TextVectorization
from features import foi, ic, num, obj, ct, triplets, cl_features, x_n
import numpy as np
import os
import re
import time
import random
import datetime
from rouge import Rouge
#import dependencies
from itertools import chain
#import required libraries
import os #operating system utils
import pandas as pd #data manipulation package
import numpy as np #numerical operation package
import nltk
import pickle
import re
import glob
import langid
import shutil
from sklearn.manifold import TSNE
from tqdm import tqdm, trange
from sklearn.mixture import GaussianMixture
from sklearn.utils.class_weight import compute_sample_weight #for using sample weight...
from os.path import join
from collections import Counter
from multiprocessing.dummy import Pool as ThreadPool
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
# from Similarity import similarity as sm
from collections import Counter, defaultdict
from sklearn.preprocessing import StandardScaler
from nltk.tokenize import RegexpTokenizer
from nltk.stem.snowball import FrenchStemmer, PorterStemmer, ItalianStemmer
#--------transformer utils -------------------------------------------------------
import gc
from torch.utils.tensorboard import SummaryWriter
#from pytorchtools import EarlyStopping
import torch.nn.init as init
from torch.utils.data import Dataset, random_split
# from transformers import (WEIGHTS_NAME, CONFIG_NAME,
# AutoTokenizer, AutoModelForCausalLM, AutoConfig,
# GPT2Tokenizer, GPT2LMHeadModel, GPT2Config, GPT2Model, #GPT Model
# BertTokenizer, EncoderDecoderModel, EncoderDecoderConfig, BertConfig, #Bert Model #---
# RobertaTokenizer, RobertaForCausalLM, RobertaConfig, RobertaConfig, RobertaForMaskedLM, #Roberta Model #---
# XLNetTokenizer, XLNetLMHeadModel, XLNetConfig, #XLNET Model
# XLMTokenizer, XLMWithLMHeadModel, XLMConfig, #XLM Model
# TransfoXLTokenizer, TransfoXLLMHeadModel, TransfoXLConfig, #TransfoXL Model
# OpenAIGPTTokenizer, OpenAIGPTLMHeadModel, OpenAIGPTConfig, #OpenAIGPTT Model
# BartTokenizer, BartForConditionalGeneration, BartConfig, #---
# T5Tokenizer, T5ForConditionalGeneration, T5Config,
# )
from pytorch_transformers import (WEIGHTS_NAME, AdamW, WarmupLinearSchedule,
BertConfig, BertForLatentConnector, BertTokenizer,
GPT2Config, GPT2ForLatentConnector, GPT2Tokenizer,
OpenAIGPTConfig, OpenAIGPTLMHeadModel, OpenAIGPTTokenizer,
RobertaConfig, RobertaForMaskedLM, RobertaTokenizer)
from transformers import AdamW, get_linear_schedule_with_warmup
from torch.utils.data import Dataset, DataLoader, random_split, RandomSampler, SequentialSampler, DistributedSampler
from transformers import pipeline, set_seed
torch.manual_seed(seed_trn)
#---VAE model------------------------------------
# from vae_pretrainer import VAE
from modules import VAEGCVAE
#---bleu evaluation------------------------------------
from bert_score import score as bert_score
from nltk.translate.bleu_score import sentence_bleu
from nltk.translate.bleu_score import SmoothingFunction
from nltk.translate import ribes_score, meteor_score
#--LESE eveluation
from LESE import LESE
#--- logging
import logging
import argparse
logging.basicConfig(format="", level=logging.INFO)
logging.getLogger().setLevel(logging.INFO)
logger = logging.getLogger(__name__)
#----utils functions
from utils import (weight_init, calc_iwnll, calc_rec, calc_mi, calc_au,
frange_cycle_linear, frange_cycle_zero_linear)
#--
os.environ['CUDA_LAUNCH_BLOCKING'] = "1"
#---clear cache
gc.collect()
torch.cuda.empty_cache()
#-- set root path
path = os.getcwd()
#%% Preprocessing...
class Mergefeatures(object):
def __init__(self, string):
super(Mergefeatures, self).__init__()
self.string = string
return
def concat(self):
'''Concatenate along the horizontal axis
'''
z = ','.join(y.strip('[]') for y in self.string)
z = [x.strip().strip("''") for x in z.split(',')]
z = ' '.join(x for x in z if not x == 'nan' if not x == ' ' if not x == '')
z = [x for x in z.split(' ')]
return z
def prepretreat(x, stopword = None, threshold = None):
'''Docstring
Parameters
----------
x : string type
word/sentence string.
threshold : TYPE, optional
threshold for cutting words. The default is None.
Returns
-------
list
list of pretreated words.
'''
if not threshold:
threshold = 3
else:
threshold = threshold
if not stopword:
with open(join(path, 'stopwords.txt'), 'r+', encoding="utf8") as st: #note that you need to define path in the function
stopwords = set([x for x in st.read().split()])
else:
stopwords = stopword
txt = ','.join(list(set([re.sub(r'[^\w+]', '', x.lower()) for x in set(''.join(str([str(ii).strip() for ii in x])).split())])))
txt = ' '.join(x for x in txt.split(',') if x not in stopwords if not len(x) < threshold if not any(z.isdigit() for z in x)) #remove stowords etc
return ' '.join(re.sub('\[^a-zA-Z0-9\n\.]', ' ', x) for x in txt.split(' ') if not len(x) < threshold if not any(z.isdigit() for z in x)) #remove special characters from string
#%% Training function
class PIDControl():
"""PID controller for functions with Lagrangian hyper-parameters"""
def __init__(self):
"""define them out of loop"""
self.I_k1 = 0.0
self.W_k1 = 0.0
self.e_k1 = 0.0
def _Kp_fun(self, Err, scale = 1):
return 1.0/(1.0 + float(scale)*torch.exp(Err))
def pid(self, exp_KL, kl_loss, Kp = 0.001, Ki = -0.001):
#Kp = 0.001, Ki = -0.001 <-- Try this if results are unsatisfactory.
"""
position PID algorithm
Input: kl_loss
return: weight for KL loss, beta
"""
self.exp_KL = exp_KL
error_k = torch.tensor(self.exp_KL - kl_loss, requires_grad = False)
## comput U as the control factor
Pk = Kp * self._Kp_fun(error_k)
Ik = self.I_k1 + Ki * error_k
## window up for integrator
if self.W_k1 < 0 and self.W_k1 > 1:
Ik = self.I_k1
Wk = Pk + Ik
self.W_k1 = Wk
self.I_k1 = Ik
self.e_k1 = error_k
## min and max value
if Wk > 1:
Wk = 1.0
if Wk < 0:
Wk = 0.0
return Wk
def gcvae_loss(latent_code, loss_rec, loss_kl, args):
#-- utility functions ...
def compute_kernel(x, y):
if len(x.size()) > 2:
x, y = x[-1, :, :], y[-1, :, :]
x, y = x[:, :args.latent_dim], y[:, :args.latent_dim]
x_size, y_size = x.size(0), y.size(0)
dim = x.size(1)
x = x.unsqueeze(1) # (x_size, 1, dim)
y = y.unsqueeze(0) # (1, y_size, dim)
tiled_x = x.expand(x_size, y_size, dim)
tiled_y = y.expand(x_size, y_size, dim)
kernel_input = (tiled_x - tiled_y).pow(2).mean(2)/float(dim)
return torch.exp(-kernel_input) # (x_size, y_size)
def compute_mmd(x, y):
x_kernel = compute_kernel(x, x)
y_kernel = compute_kernel(y, y)
xy_kernel = compute_kernel(x, y)
mmd = x_kernel.mean() + y_kernel.mean() - 2*xy_kernel.mean()
return mmd
def z_mahalanobis_fn(z, diag:bool = True, psd = True)->float:
'''
Parameters
----------
z : numpy array
latent array/code.
diag : bool, optional
Diagonal of the covariance matrix. The default is False.
Returns
-------
float
mahalanobis mean of the latent vector.
'''
if len(z.size()) > 2:
z = z[-1, :, :] #--covert [1, N, M] --> [N, M]
z = z[:, :args.latent_dim]
m = lambda z: z - z.mean(axis = 0) #mean of vectors
z_m = m(z) #mean centered data
# logger.info(f'shape of z_m: {z_m.shape}')
len_z = len(z_m)-1
len_z = 1 if len_z == 0 else len_z
#check if matrix entries are
if not psd:
cov = 1/(len_z)*torch.matmul(z_m.T, z_m)
cov = torch.eye(cov.shape[0]) if cov[0][0] == 0.0 else cov
diag_cov = torch.diag(torch.diag(cov))
diag_cov = torch.eye(diag_cov.shape[0]) if diag_cov[0][0] == 0.0 else diag_cov
else:
cov = 1/(len_z)*torch.matmul(z_m.T, z_m)
cov = torch.eye(cov.shape[0]) if cov[0][0] == 0.0 else cov
cov = torch.where(cov < 0, 0, cov)
diag_cov = torch.diag(torch.diag(cov))
diag_cov = torch.eye(diag_cov.shape[0]) if diag_cov[0][0] == 0.0 else diag_cov
diag_cov = torch.where(diag_cov < 0, 0, diag_cov)
# logger.info(f'shape of cov: {cov.shape}')
# logger.info(f'shape of diag_cov: {diag_cov.shape}')
if not diag:
inv_cov = torch.linalg.inv(cov.cpu()).to(args.device) #inverse of a full covariance matrix
else:
inv_cov = torch.linalg.inv(diag_cov.cpu()).to(args.device) #inverse of diagonal covariance matrix
# logger.info(f'shape of inv_cov: {inv_cov.shape}')
trans_x = torch.matmul(torch.matmul(z_m, inv_cov), z_m.T)
mah_mat_mean = trans_x.diagonal().mean() #torch.diagonal()
return mah_mat_mean
def z_mahalanobis_gcvae(z, diag:bool = True, psd = False)->float:
'''Reproducing Kernel Hilbert Space (RKHS)
Mahalanobis distance
Parameters
----------
z : numpy array
latent array/code.
diag : bool, optional
Diagonal of the covariance matrix. The default is False.
psd: bool, optional
is matrix is not positive semi definite
Returns
-------
float
mahalanobis mean of the latent vector.
'''
if len(z.size()) > 2:
z = z[-1, :, :] #--covert [1, N, M] --> [N, M]
z = z[:, :args.latent_dim]
m = lambda z: z - z.mean(axis = 0) #mean of vectors
z_m = m(z) #mean centered data
#check if matrix entries are
if not psd:
cov = 1/(len(z)-1)*torch.matmul(z_m.T, z_m)
diag_cov = torch.diag(torch.diag(cov))
else:
cov = 1/(len(z)-1)*torch.matmul(z_m.T, z_m)
cov = torch.where(cov < 0, 0, cov)
diag_cov = torch.diag(torch.diag(cov))
diag_cov = torch.where(diag_cov < 0, 0, diag_cov)
if not diag:
inv_cov = torch.linalg.inv(cov) #inverse of a full covariance matrix
else:
inv_cov = torch.linalg.inv(diag_cov) #inverse of diagonal covariance matrix
z_sample = torch.randn(z.size(), dtype = torch.float32)
mah_gcvae = inv_cov * compute_mmd(z_sample, z) #-- compute MMD
mah_gcvae_mean = mah_gcvae.diagonal().mean()
return mah_gcvae_mean
#--MMD
def mmd(z):
z_sample = torch.randn(z.size(), dtype = torch.float32).to(args.device)
return compute_mmd(z_sample, z)
#--Mahalanobis
def z_mahalanobis(z):
return z_mahalanobis_fn(z)
#--Mahalanobis GCVAE
def z_mah_gcvae(z):
return z_mahalanobis_gcvae(z)
#--define latent space using logits
z = latent_code
#--Maximum Mean Discrepancy (MMD)
if args.mmd_type == 'mmd':
mmd_fn = mmd
#-- Mahalanobolis distance
elif args.mmd_type == 'mah':
mmd_fn = z_mahalanobis
#-- Expectation of 'Mah'
elif args.mmd_type == 'mah_gcvae':
mmd_fn = z_mah_gcvae
#-- compute variational losses..
#select parameters...
if args.vae_model_name.lower() == 'vae':
alpha, beta, gamma = -1, 1, 0
mmd_xy = 0
elif args.vae_model_name == 'betavae':
alpha, beta, gamma = -1, args.beta, 0
mmd_xy = 0
elif args.vae_model_name.lower() == 'controlvae':
alpha = 0
beta = PIDControl().pid(args.init_kld, loss_kl)
gamma = 0
mmd_xy = 0
elif args.vae_model_name.lower() == 'infovae':
alpha, beta = 0, 0
gamma = args.gamma
mmd_xy = mmd_fn(z)
elif args.vae_model_name.lower() == 'gcvae':
mmd_xy = mmd_fn(z)
alpha = PIDControl().pid(args.init_bce, loss_rec) #reconstruction weight --> cross entropy weight
beta = PIDControl().pid(args.init_kld, loss_kl) #weight on KL-divergence --> Kullback-Leibler divergence.
gamma = PIDControl().pid(args.init_mmd, mmd_xy) #weight if correlation measure.
else:
return ValueError(f'Unknown loss type: {args.vae_model_name}')
#--
loss = (1-alpha-beta)*loss_rec + beta*loss_kl + gamma*mmd_xy
return loss, loss_rec, loss_kl, alpha, beta, gamma
def _rotate_checkpoints(args, checkpoint_prefix = 'checkpoint', use_mtime = False):
if not args.save_total_limit:
return
if args.save_total_limit <= 0:
return
# Check if we should delete older checkpoint(s)
output_dir = os.path.abspath(args.output_dir)
checkpoints = [output_dir]
if os.path.isdir(output_dir):
checkpoints = list(os.path.join(output_dir, n) for n in os.listdir(output_dir))
if args.local_rank not in [-1, 0]:
checkpoints = [checkpoint for checkpoint in checkpoints if torch.distributed.get_rank() == int(checkpoint.split('-')[-1])]
checkpoints.sort(key=lambda x: int(x.split('-')[-1]) if len(x.split('-')) > 1 else 0)
if len(checkpoints) > args.save_total_limit:
logger.info("Deleting older checkpoint [{}] due to args.save_total_limit".format(checkpoints[0]))
shutil.rmtree(checkpoints[0])
def filter_fdr_frm_generated_text(txt, stp_sstech):
stp_sstech_join = ' '.join(stp_sstech).split(' ')
ai_br = txt.split(' ') #original
ai_br_lwr = txt.lower().split(' ')
index_zer = len(stp_sstech[0].split(' ')) - 1 # the scaler -1 indicates count starting with zero
ai_pair = []
st_pair = []
len_ai_pair, len_stp_sstech_pair = len(ai_br_lwr), len(stp_sstech_join)
#N-grams in ai_br (i.e AI generated FAs)
for i in range(len_ai_pair - index_zer):
pair_ai = ''
for j in range(index_zer + 1):
if (i + j) < len_ai_pair:
pair_ai += ai_br_lwr[i + j] + ' '
ai_pair.append(pair_ai.strip())
# N-grams in stp_sstech_join (i.e ground truth FAs- from all possible
# combinations of Step-type + Substep technique)
for i in range(len_stp_sstech_pair - index_zer):
pair_st = ''
for j in range(index_zer + 1):
if (i + j) < len_stp_sstech_pair:
pair_st += stp_sstech_join[i + j] + ' '
st_pair.append(pair_st.strip())
#filter here
count = 0
for i in ai_pair:
if not i in st_pair:
count += 1
else:
break
ai_pair_filt = ' '.join(ai_br[count:])
return ai_pair_filt
#%% clustering utils
def GMMClustering(code, nc_trials = 30):
lowest_bic = np.infty
bic = []
n_components_range = range(1, nc_trials)
cv_types = ['spherical', 'tied', 'diag', 'full']
for cv_type in cv_types:
for n_components in n_components_range:
# Fit a Gaussian mixture with EM
gmm = GaussianMixture(n_components = n_components, covariance_type = cv_type)
gmm.fit(code)
bic.append(gmm.bic(code))
if bic[-1] < lowest_bic:
lowest_bic = bic[-1]
best_gmm = gmm
c_label = best_gmm.predict(code)
return c_label, bic
#%% Making the tokens and weight initialization...
def mask_tokens(inputs, tokenizer, args):
""" Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original. """
labels = inputs.clone()
# We sample a few tokens in each sequence for masked-LM training (with probability args.mlm_probability defaults to 0.15 in Bert/RoBERTa)
masked_indices = torch.bernoulli(torch.full(labels.shape, args.mlm_probability)).to(torch.uint8)
labels[masked_indices == 1] = -1 # We only compute loss on masked tokens
# 80% of the time, we replace masked input tokens with tokenizer.mask_token ([MASK])
indices_replaced = torch.bernoulli(torch.full(labels.shape, 0.8)).to(torch.uint8) & masked_indices
inputs[indices_replaced] = tokenizer.convert_tokens_to_ids(tokenizer.mask_token)
# 10% of the time, we replace masked input tokens with random word
indices_random = torch.bernoulli(torch.full(labels.shape, 0.5)).to(torch.uint8) & masked_indices & ~indices_replaced
indices_random = indices_random.to(args.device)
random_words = torch.randint(len(tokenizer), labels.shape, dtype = torch.long)
inputs[indices_random] = random_words[indices_random].to(args.device)
# The rest of the time (10% of the time) we keep the masked input tokens unchanged
return inputs, labels
def weights_init_rondom(model):
model = model.module if hasattr(model, 'module') else model # Take care of distributed/parallel training
model_state_dict = model.state_dict()
for key in model_state_dict:
if 'encoder' in key:
init.normal_(model_state_dict[key].data)
def evaluate_generation_from_gpt2(model, decoder_tokenizer, args):
context_tokens = decoder_tokenizer.encode('<BOS>')
with torch.no_grad():
out = sample_sequence(
model=model,
context=context_tokens,
length=args.max_seq_length, # Chunyuan: Fix length; or use <EOS> to complete a sentence
temperature=args.temperature,
top_k=args.top_k,
top_p=args.top_p,
device=args.device,
decoder_tokenizer = decoder_tokenizer,
max_seq_length = args.max_seq_length
)
text = decoder_tokenizer.decode(out[0,:].tolist(), clean_up_tokenization_spaces=True)
text = text.split()[1:-1]
text = ' '.join(text) + '\n'
return text
def evaluate_generation_fromp_prior(model_vae, decoder_tokenizer, args):
loc = torch.zeros([args.nz]).to(args.device)
scale = torch.ones([args.nz]).to(args.device)
prior = torch.distributions.normal.Normal(loc, scale)
context_tokens = decoder_tokenizer.encode('<BOS>')
with torch.no_grad():
latent_z = prior.sample()
# pdb.set_trace()
past = model_vae.decoder.linear(latent_z.unsqueeze(0))
# pdb.set_trace()
out = sample_sequence_conditional(
model=model_vae.decoder,
context=context_tokens,
past=past,
length=args.max_seq_length, # Chunyuan: Fix length; or use <EOS> to complete a sentence
temperature=args.temperature,
top_k=args.top_k,
top_p=args.top_p,
device=args.device,
decoder_tokenizer = decoder_tokenizer,
max_seq_length = args.max_seq_length
)
text = decoder_tokenizer.decode(out[0,:].tolist(), clean_up_tokenization_spaces=True)
text = text.split()[1:-1]
text = ' '.join(text) + '\n'
return text
def save_checkpoint(model, optimizer, global_step, tokenizer_enc, tokenizer_dec, args):
# Create output directory if needed
# Save model checkpoint
args.output_encoder_dir = os.path.join(args.output_dir, 'checkpoint-encoder-{}'.format(global_step))
args.output_decoder_dir = os.path.join(args.output_dir, 'checkpoint-decoder-{}'.format(global_step))
args.output_full_dir = os.path.join(args.output_dir, 'checkpoint-full-{}'.format(global_step))
if not os.path.exists(args.output_encoder_dir) and args.local_rank in [-1, 0]:
os.makedirs(args.output_encoder_dir)
if not os.path.exists(args.output_decoder_dir) and args.local_rank in [-1, 0]:
os.makedirs(args.output_decoder_dir)
#--
logger.info(" Saving encoder model checkpoint to %s", args.output_encoder_dir)
logger.info(" Saving decoder model checkpoint to %s", args.output_decoder_dir)
# #-- savingoptimizer and scheduler
# torch.save(optimizer.state_dict(), os.path.join(args.output_dir, "optimizer.pt"))
# torch.save(scheduler.state_dict(), os.path.join(args.output_dir, "scheduler.pt"))
# Save a trained model, configuration and tokenizer using `save_pretrained()`.
# They can then be reloaded using `from_pretrained()`
model_encoder_to_save = model.module.encoder if hasattr(model, 'module') else model.encoder # Take care of distributed/parallel training
model_decoder_to_save = model.module.decoder if hasattr(model, 'module') else model.decoder # Take care of distributed/parallel training
logger.info(" Saving encoder and decoder tokenizers")
tokenizer_enc.save_pretrained(args.output_encoder_dir)
tokenizer_dec.save_pretrained(args.output_decoder_dir)
# Good practice: save your training arguments together with the trained model
model_encoder_to_save.save_pretrained(args.output_encoder_dir)
torch.save(args, os.path.join(args.output_encoder_dir, 'training_encoder_args.bin'))
model_decoder_to_save.save_pretrained(args.output_decoder_dir)
torch.save(args, os.path.join(args.output_decoder_dir, 'training_decoder_args.bin'))
# save the full model and optmizer into a checkpoint
model_to_save = model.module if hasattr(model, 'module') else model # Take care of distributed/parallel training
checkpoint = {
'iter': global_step,
'model_state_dict': model_to_save.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'beta': model_to_save.args.beta,
'args': args
}
if not os.path.exists(args.output_full_dir) and args.local_rank in [-1, 0]:
os.makedirs(args.output_full_dir)
logger.info(" Start saving full model checkpoint to %s", args.output_full_dir)
torch.save(checkpoint, os.path.join(args.output_full_dir, 'training.bin'))
logger.info(" Saving full checkpoint to %s", args.output_full_dir)
def load_checkpoint(args, MODEL_CLASSES):
#--load directory of checkpoints
files_outdir = os.listdir(args.output_dir)
global_step = files_outdir[-1].split('-')[-1]
output_encoder_dir = os.path.join(args.output_dir, 'checkpoint-encoder-{}'.format(global_step))
output_decoder_dir = os.path.join(args.output_dir, 'checkpoint-decoder-{}'.format(global_step))
output_full_dir = os.path.join(args.output_dir, 'checkpoint-full-{}'.format(global_step))
checkpoints = [ [output_encoder_dir, output_decoder_dir] ]
logger.info(" Evaluate the following checkpoints: %s", checkpoints)
# Load a trained Encoder model and vocabulary
#---------Encoder
config_class_enc, model_class_enc, tokenizer_class_enc = MODEL_CLASSES[args.model_type_enc]
#encoder tokenization...load from checkpoint
tokenizer_enc = tokenizer_class_enc.from_pretrained(output_encoder_dir) #Tokenization
# config_enc = config_class_enc.from_pretrained(args.config_name_enc if args.config_name_enc else args.model_name_or_path_enc)
model_enc = model_class_enc.from_pretrained(output_encoder_dir,
latent_size = args.latent_size) #Encoder LM class
model_enc.to(args.device)
if args.block_size <= 0:
args.block_size = tokenizer_enc.max_len_single_sentence # Our input block size will be the max possible for the model
args.block_size = min(args.block_size, tokenizer_enc.max_len_single_sentence)
# Load a trained Decoder model and vocabulary
#---------Decoder
config_class_dec, model_class_dec, tokenizer_class_dec = MODEL_CLASSES[args.model_type_dec]
#decoder tokenization...
tokenizer_dec = tokenizer_class_dec.from_pretrained(output_decoder_dir) #Tokenization
# config_dec = config_class_dec.from_pretrained(args.config_name_dec if args.config_name_dec else args.model_name_or_path_dec)
model_dec = model_class_dec.from_pretrained(output_decoder_dir,
latent_size = args.latent_size) #Decoder LM class
model_dec.to(args.device)
if args.block_size <= 0:
args.block_size = tokenizer_dec.max_len_single_sentence # Our input block size will be the max possible for the model
args.block_size = min(args.block_size, tokenizer_dec.max_len_single_sentence) #check this if 'RuntimeError: The size of tensor a (1025) must match the size of tensor b (1024) at non-singleton dimension 3'
#--Adding special tokens to GPTx
special_tokens_dict = {'pad_token': '<PAD>', 'bos_token': '<BOS>', 'eos_token': '<EOS>'}
num_added_toks = tokenizer_dec.add_special_tokens(special_tokens_dict)
logger.info(' We have added', num_added_toks, 'tokens to GPTx')
model_dec.resize_token_embeddings(len(tokenizer_dec)) # Notice: resize_token_embeddings expect to receive the full size of the new vocabulary, i.e. the length of the tokenizer.
assert tokenizer_dec.pad_token == '<PAD>'
# Load full VAE (BERT/RoBERTa/BART <-> GPTx) model
checkpoint = torch.load(os.path.join(output_full_dir, 'training.bin'))
model = VAEGCVAE(model_enc, model_dec, tokenizer_enc, tokenizer_dec, args)
model.load_state_dict(checkpoint['model_state_dict'])
logger.info("Pre-trained Opti-style model is successfully loaded")
model.to(args.device)
return (tokenizer_enc, model_enc, tokenizer_dec, model_dec, model)
def top_k_top_p_filtering(logits, top_k = 0, top_p = 0.0, filter_value = -float('Inf')):
""" Filter a distribution of logits using top-k and/or nucleus (top-p) filtering
Args:
logits: logits distribution shape (vocabulary size)
top_k > 0: keep only top k tokens with highest probability (top-k filtering).
top_p > 0.0: keep the top tokens with cumulative probability >= top_p (nucleus filtering).
Nucleus filtering is described in Holtzman et al. (http://arxiv.org/abs/1904.09751)
From: https://gist.github.com/thomwolf/1a5a29f6962089e871b94cbd09daf317
"""
assert logits.dim() == 1 # batch size 1 for now - could be updated for more but the code would be less clear
top_k = min(top_k, logits.size(-1)) # Safety check
if top_k > 0:
# Remove all tokens with a probability less than the last token of the top-k
indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
logits[indices_to_remove] = filter_value
if top_p > 0.0:
sorted_logits, sorted_indices = torch.sort(logits, descending=True)
cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
# Remove tokens with cumulative probability above the threshold
sorted_indices_to_remove = cumulative_probs > top_p
# Shift the indices to the right to keep also the first token above the threshold
sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
sorted_indices_to_remove[..., 0] = 0
indices_to_remove = sorted_indices[sorted_indices_to_remove]
logits[indices_to_remove] = filter_value
return logits
def sample_sequence(model, length, context, num_samples = 1, temperature = 1, top_k = 0, top_p= 0.0, is_xlnet = False, device = 'cpu'):
context = torch.tensor(context, dtype=torch.long, device=device)
context = context.unsqueeze(0).repeat(num_samples, 1)
generated = context
with torch.no_grad():
for _ in trange(length):
inputs = {'input_ids': generated}
if is_xlnet:
# XLNet is a direct (predict same token, not next token) and bi-directional model by default
# => need one additional dummy token in the input (will be masked), attention mask and target mapping (see model docstring)
input_ids = torch.cat((generated, torch.zeros((1, 1), dtype=torch.long, device=device)), dim=1)
perm_mask = torch.zeros((1, input_ids.shape[1], input_ids.shape[1]), dtype=torch.float, device=device)
perm_mask[:, :, -1] = 1.0 # Previous tokens don't see last token
target_mapping = torch.zeros((1, 1, input_ids.shape[1]), dtype=torch.float, device=device)
target_mapping[0, 0, -1] = 1.0 # predict last token
inputs = {'input_ids': input_ids, 'perm_mask': perm_mask, 'target_mapping': target_mapping}
outputs = model(**inputs) # Note: we could also use 'past' with GPT-2/Transfo-XL/XLNet (cached hidden-states)
next_token_logits = outputs[0][0, -1, :] / temperature
filtered_logits = top_k_top_p_filtering(next_token_logits, top_k=top_k, top_p=top_p)
next_token = torch.multinomial(F.softmax(filtered_logits, dim=-1), num_samples=1)
generated = torch.cat((generated, next_token.unsqueeze(0)), dim=1)
return generated
def sample_sequence_conditional(model, length, context, past = None, num_samples = 1, temperature = 1, top_k = 0, top_p = 0.0, device = 'cpu', decoder_tokenizer = None, max_seq_length = -1):
context = torch.tensor(context, dtype = torch.long, device = device)
context = context.unsqueeze(0).repeat(num_samples, 1)
generated = context
gen_seq_length = 0
with torch.no_grad():
while True:
inputs = {'input_ids': generated, 'past': past}
outputs = model(**inputs) # Note: we could also use 'past' with GPT-2/Transfo-XL/XLNet (cached hidden-states)
next_token_logits = outputs[0][0, -1, :] / temperature
filtered_logits = top_k_top_p_filtering(next_token_logits, top_k = top_k, top_p = top_p)
next_token = torch.multinomial(F.softmax(filtered_logits, dim=-1), num_samples=1)
generated = torch.cat((generated, next_token.unsqueeze(0)), dim=1)
gen_seq_length += 1
# pdb.set_trace()
if next_token.unsqueeze(0)[0,0].item() == decoder_tokenizer.encode('<EOS>')[0]:
break
if max_seq_length>0 and gen_seq_length>max_seq_length:
break
return generated
def latent_code_from_text(text, tokenizer_encoder, model_vae, args):
tokenized1 = tokenizer_encoder.encode(text)
tokenized1 = [101] + tokenized1 + [102]
coded1 = torch.Tensor([tokenized1])
coded1 = torch.Tensor.long(coded1)
with torch.no_grad():
x0 = coded1
x0 = x0.to(args.device)
pooled_hidden_fea = model_vae.encoder(x0, attention_mask=(x0 > 0).float())[1]
mean, logvar = model_vae.encoder.linear(pooled_hidden_fea).chunk(2, -1)
latent_z = mean.squeeze(1)
coded_length = len(tokenized1)
return latent_z, coded_length
def latent_code_to_text(latent_z, tokenizer_decoder, model_vae, args):
past = latent_z
context_tokens = tokenizer_decoder.encode('<BOS>')
length = 128 # maximum length, but not used
out = sample_sequence_conditional(
model = model_vae.decoder,
context = context_tokens,
past = past,
length = length, # Chunyuan: Fix length; or use <EOS> to complete a sentence
temperature = args.temperature,
top_k = args.top_k, #must be integer
top_p = args.top_p,
device = args.device,
decoder_tokenizer = tokenizer_decoder
)
text_x1 = tokenizer_decoder.decode(out[0,:].tolist(),
clean_up_tokenization_spaces = True,
skip_special_tokens = True)
text_x1 = text_x1.split()[1:-1]
text_x1 = ' '.join(text_x1)
return text_x1
def interpolate(model, tokenizer_encoder, tokenizer_decoder, args):
# and then in the main function
latent_z1, coded_length1 = latent_code_from_text(args.sent_source, tokenizer_encoder, model, args)
latent_z2, coded_length2 = latent_code_from_text(args.sent_target, tokenizer_encoder, model, args)
#--
if args.num_interpolation_steps > 1:
result = defaultdict(str)
num_steps = args.num_interpolation_steps + 1
for step in range(num_steps+1):
latent_z = latent_z1 + (latent_z2 - latent_z1) * step * 1.0/num_steps
text_interpolate = latent_code_to_text(latent_z, tokenizer_decoder, model, args)
result[step] = text_interpolate
logger.info(f'Interpolation step {step}: {text_interpolate}')
else:
num_steps = 1
latent_z = latent_z1 + (latent_z2 - latent_z1) * 1.0/num_steps
text_interpolate = latent_code_to_text(latent_z, tokenizer_decoder, model, args)
result = text_interpolate
logger.info(f'Interpolation step {num_steps}: {result}')
return result, latent_z
#%% Evaluation function
def evaluate(args, eval_dataset, model, tokenizer = None, tokenizer_enc = None, tokenizer_dec = None, prefix=""):
eval_output_dir = args.eval_dir
tokenizer = tokenizer if tokenizer != None else None
tokenizer_enc = tokenizer_enc if tokenizer_enc != None else None
tokenizer_dec = tokenizer_dec if tokenizer_dec != None else None
if not os.path.exists(eval_output_dir) and args.local_rank in [-1, 0]:
os.makedirs(eval_output_dir)
args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu)
# Note that DistributedSampler samples randomly
eval_sampler = SequentialSampler(eval_dataset) if args.local_rank == -1 else DistributedSampler(eval_dataset)
eval_dataloader = DataLoader(eval_dataset, sampler = eval_sampler, batch_size = args.eval_batch_size)
# multi-gpu eval
if args.n_gpu > 1 and not isinstance(model, torch.nn.DataParallel):
model = torch.nn.DataParallel(model)
# Evaluation!
logger.info(f"\n ***** Running evaluation {prefix} *****")
logger.info(f" Num examples = {len(eval_dataset)}")
logger.info(f" Batch size = {args.eval_batch_size}")
eval_loss, perplexity = 0.0, 0.0
kl_loss, reconstr = 0.0, 0.0
nb_eval_steps = 0
model.eval()
for batch in tqdm(eval_dataloader, desc = "Evaluating"):
batch = tuple(t.to(args.device) for t in batch)
#No optimization during evaluation. i.e mini-batch gradient descent not needed.
with torch.no_grad():
if args.encoder_decoder_sep:
tokenized_text0, tokenized_text1, tokenized_text_lengths = batch #returns encoder_tokens, decoder_tokens, _
inputs, labels = mask_tokens(tokenized_text0, tokenizer_enc, args) if args.mlm else (tokenized_text0, tokenized_text1)
labels = tokenized_text1
# tokenized_text1 = tokenized_text1.to(args.device)
inputs = inputs.to(args.device)
labels = labels.to(args.device)
else:
inputs = {
'input_ids': batch[0],
'labels': batch[0],
'attention_mask': batch[1],
}
#varying beta...
model.args.fb_mode = 1
if args.use_deterministic_connect:
model.args.fb_mode = 2
# loss_rec, loss_kl, loss = model(inputs, labels) #VAE LLM
loss_rec, loss_kl, latent_z = model(inputs, labels) #VAE LLM throws reconstruction, KL-divergence and Latent code
loss, loss_rec, loss_kl, alpha, beta, gamma = gcvae_loss(latent_z, loss_rec, loss_kl, args)
#------
if args.n_gpu > 1:
loss_rec = loss_rec.mean()
loss_kl = loss_kl.mean()
loss = loss.mean()
#--compute averages...
avg_tmp_eval_loss = loss.mean().item() #average batch evaluation loss
avg_templ_ppl =torch.exp(torch.tensor(avg_tmp_eval_loss).to(args.device)) #average batch perplexity
avg_templ_rec = loss_rec.mean().item() #average reconstruction loss
avg_templ_kl = loss_kl.mean().item() #average KL loss
eval_loss += avg_tmp_eval_loss #total inreamental loss
perplexity += avg_templ_ppl #perplexity
kl_loss += avg_templ_kl #kl divergence
reconstr += avg_templ_rec #reconstruction loss
nb_eval_steps += 1
#--
eval_loss /= nb_eval_steps
perplexity /= nb_eval_steps
kl_loss /= nb_eval_steps
reconstr /= nb_eval_steps
#---
output_eval_file = os.path.join(eval_output_dir, "eval_results.txt")
if not args.encoder_decoder_sep:
if not os.path.exists(output_eval_file):
with open(output_eval_file, "w+") as writer:
logger.info(" ***** Eval loss results *****")
writer.write(" ***** Eval loss results *****\n")
writer.write(f"Evaluation loss: {eval_loss} PPL: {perplexity}\n")
else:
with open(output_eval_file, "a+") as writer:
writer.write(f"Evaluation loss: {eval_loss} PPL: {perplexity}\n")
else:
if not os.path.exists(output_eval_file):
with open(output_eval_file, "w+") as writer:
logger.info(" ***** Eval loss results *****")
writer.write(" ***** Eval loss results *****\n")
writer.write(f"Evaluation loss: {eval_loss} PPL: {perplexity} KL: {kl_loss} RECONSTRUCTION: {reconstr}\n")
else:
with open(output_eval_file, "a+") as writer:
writer.write(f"Evaluation loss: {eval_loss} PPL: {perplexity} KL: {kl_loss} RECONSTRUCTION: {reconstr}\n")
writer.close()
return eval_loss, perplexity
#%% Defining the training loop
def train(args, train_dataset, eval_dataset, model, tokenizer = None, tokenizer_enc = None, tokenizer_dec = None):
tokenizer = tokenizer if tokenizer != None else None
tokenizer_enc = tokenizer_enc if tokenizer_enc != None else None
tokenizer_dec = tokenizer_dec if tokenizer_dec != None else None
""" Train the model """
if args.local_rank in [-1, 0]:
tb_writer = SummaryWriter()
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)
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
# Prepare optimizer and schedule (linear warmup and decay)
no_decay = ["bias", "LayerNorm.bias", "LayerNorm.weight"]
optimizer_grouped_parameters = [
{'params': [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], 'weight_decay': args.weight_decay},
{'params': [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}
]
optimizer = AdamW(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')))
#--> numeric precision
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)
# 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) set local_rank = -1 for Non-distributed training
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)
# Train!
logger.info(" ***** Running training *****")
logger.info(f" Num examples = {len(train_dataset)}")
logger.info(f" Num Epochs = {args.num_train_epochs}")
logger.info(f" Instantaneous batch size per GPU = {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),)
logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
logger.info(f" Total optimization steps = {t_total}")
global_step = 0
epochs_trained = 0
steps_trained_in_current_epoch = 0
# Check if continuing training from a checkpoint
if os.path.exists(args.model_name_or_path):
# set global_step to gobal_step of last saved checkpoint from model path
try:
global_step = int(args.model_name_or_path.split('-')[-1].split('/')[0])
epochs_trained = global_step // (len(train_dataloader) // args.gradient_accumulation_steps)
steps_trained_in_current_epoch = global_step % (len(train_dataloader) // args.gradient_accumulation_steps)
logger.info(" Continuing training from checkpoint, will skip to saved global_step")
logger.info(" Continuing training from epoch %d", epochs_trained)
logger.info(" Continuing training from global step %d", global_step)
logger.info(" Will skip the first %d steps in the first epoch", steps_trained_in_current_epoch)
except ValueError:
global_step = 0
logger.info(" Start fine-tuning...")
avg_tr_loss, avg_eval_loss, avg_ppl = [], [], []
avg_kl, avg_alpha, avg_beta, avg_gamma, avg_rec = [], [], [], [], []
tr_loss, logging_loss = 0.0, 0.0
tr_kl_loss, tr_alpha, tr_beta, tr_gamma, tr_loss_rec = 0.0, 0.0, 0.0, 0.0, 0.0
model.zero_grad()
train_iterator = trange(epochs_trained, int(args.num_train_epochs), desc = "Epoch", disable = args.local_rank not in [-1, 0])
set_seed(args.seed) # Added here for reproducibility (even between python 2 and 3)
#-------
n_iter = int(args.num_train_epochs) * len(train_dataloader)
beta_t_list = frange_cycle_zero_linear(n_iter,
start = 0.0,
stop = args.beta,
n_cycle = 1,
ratio_increase = args.ratio_increase,
ratio_zero = args.ratio_zero)
#-------
for epoch in train_iterator:
epoch_iterator = tqdm(train_dataloader, desc="Iteration", disable = args.local_rank not in [-1, 0])
for step, batch in enumerate(epoch_iterator):
# Skip past any already trained steps if resuming training
if steps_trained_in_current_epoch > 0:
steps_trained_in_current_epoch -= 1
continue
#begin training
model.train()
batch = tuple(t.to(args.device) for t in batch)
if args.encoder_decoder_sep:
tokenized_text0, tokenized_text1, tokenized_text_lengths = batch #returns encoder_tokens, decoder_tokens, _
inputs, labels = mask_tokens(tokenized_text0, tokenizer_enc, args) if args.mlm else (tokenized_text0, tokenized_text1) #the label is the encoding of GPTx
labels = tokenized_text1 #the label is the encoding of GPTx
inputs = inputs.to(args.device)
labels = labels.to(args.device)
else:
#--from using Failure Analysis dataset without masking...
inputs = {
'input_ids': batch[0],
'labels': batch[0],
'attention_mask': batch[1],
}
#varying beta...
model.args.fb_mode = 1
if args.use_deterministic_connect:
model.args.fb_mode = 2
# loss_rec, loss_kl, loss = model(inputs, labels) #VAE LLM
loss_rec, loss_kl, latent_z = model(inputs, labels) #VAE LLM throws reconstruction, KL-divergence and Latent code
loss, loss_rec, loss_kl, alpha, beta, gamma = gcvae_loss(latent_z, loss_rec, loss_kl, args)
#------