-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtext2sql.py
2054 lines (1661 loc) · 81.4 KB
/
text2sql.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 json
import torch
import argparse
import torch.optim as optim
import transformers
import wandb
import torch.nn as nn
import math
from tqdm.auto import tqdm
from tokenizers import AddedToken
from accelerate import Accelerator
from sql_metadata import Parser
from preprocessing import sql_keywords, ops
from torch.utils.data import DataLoader
from transformers import AutoTokenizer, MT5ForConditionalGeneration, AutoModelForSeq2SeqLM
from mT5_grad_adv import MT5ForConditionalGenerationWithLP
from transformers.optimization import Adafactor
from transformers.trainer_utils import set_seed
from utils.spider_metric.evaluator import EvaluateTool
from utils.mschema2qa_metric.evaluator import MSchema2QAEvaluateTool
from utils.load_dataset import Text2SQLDataset, MSchema2QADataset, TAPMSchema2QADataset, TTMSchema2QADataset, Text2SQLWithLPDataset, Mschema2QAWithLPDataset, MultiMschema2QADataset
from utils.load_dataset import Text2SQLMultiPTDataset, Text2SQLDatasetWithMultiPT, Mschema2QAMultiPTDataset, Mschema2QADatasetWithMultiPT, LanguagePredictionDataset
from utils.load_dataset import ReconstructionDataset, Text2SQLWithReconDataset, Mschema2QAWithReconDataset
from utils.load_dataset import Text2SQLWithLpAndReconDataset, Mschema2QAWithLpAndReconDataset
from utils.load_dataset import Text2SQLDatasetWithTranslated, Mschema2QADatasetWithTranslated
from utils.text2sql_decoding_utils import decode_sqls
def list_of_strings(arg):
return arg.split(',')
def parse_option():
parser = argparse.ArgumentParser("command line arguments for fine-tuning pre-trained language model.")
parser.add_argument('--effective_batch_size', type = int, default = 8,
help = 'input batch size. Should be effective batch size!')
parser.add_argument('--gradient_accumulation_steps', type = int, default = 4,
help = 'perform gradient descent per "gradient_accumulation_step" steps.')
parser.add_argument('--learning_rate',type = float, default = 3e-5,
help = 'learning rate.')
parser.add_argument('--epochs', type = int, default = 50,
help = 'training epochs.')
parser.add_argument('--seed', type = int, default = 42,
help = 'random seed.')
parser.add_argument('--save_path', type = str, default = "models/text2sql",
help = 'save path of best fine-tuned text2sql model.')
parser.add_argument('--wandb_log', action="store_true", help="Enable for wandb logging")
parser.add_argument('--model_name_or_path', type = str, default = "t5-3b",
help =
'''
pre-trained model name.
options:
t5-base, https://huggingface.co/t5-base;
t5-large, https://huggingface.co/t5-large;
t5-3b, https://huggingface.co/t5-3b;
''')
parser.add_argument('--use_adafactor', action='store_true',
help = 'whether to use adafactor optimizer.')
parser.add_argument('--mode', type = str, default = "train",
help='train, eval or test.')
parser.add_argument('--train_filepath', type = str, default = "data/preprocessed_data/resdsql_train_spider.json",
help = 'file path of test2sql training set.')
parser.add_argument('--dev_filepath', type = str, default = "data/preprocessed_data/resdsql_dev.json",
help = 'file path of test2sql dev set.')
parser.add_argument('--original_dev_filepath', type = str, default = "data/spider/dev.json",
help = 'file path of the original dev set (for registing evaluator).')
parser.add_argument('--db_path', type = str, default = "database",
help = 'file path of database. ')
parser.add_argument('--preprocessed_dataset_path', type = str)
# Reconstruction dataset arguments
parser.add_argument("--reconstruction", action="store_true", help="Enable for training with reconstruction dataset")
parser.add_argument("--mask_rate", type=float, default=0.3)
parser.add_argument("--max_seq_length", type=int, default=512)
parser.add_argument("--reconstruction_loss_weight", type=float, default=0.5)
# Language prediction penalty arugments
parser.add_argument("--lp_penalty", action="store_true", help="Enable for training with language prediction penalty")
parser.add_argument("--lp_penalty_weight", type=float, default=0.33)
parser.add_argument("--lp_with_reconstruction", action="store_true", help="Enable for training with language prediction penalty and reconstruction dataset")
# Train with translated dataset + source labeled dataset
parser.add_argument("--labeled_with_translated", action="store_true", help="Enable for training with translated dataset + source labeled dataset")
parser.add_argument("--translated_dataset_path", type=str, default=None, help="Path of translated dataset. Only used for labeled_with_translated option.")
parser.add_argument('--num_beams', type = int, default = 8,
help = 'beam size in model.generate() function.')
parser.add_argument('--num_return_sequences', type = int, default = 8,
help = 'the number of returned sequences in model.generate() function (num_return_sequences <= num_beams).')
parser.add_argument("--output", type = str, default = "predicted_sql.txt",
help = "save file of the predicted sqls.")
parser.add_argument("--local_rank", type=int)
parser.add_argument("--dataset_type", type=str, choices=["spider", "mschema2qa"], default="spider")
parser.add_argument("--dataset_lang", type=str, default="en")
parser.add_argument("--mschema2qa_translate_train", action="store_true", help="Enable for translated train set of mschema2qa")
parser.add_argument("--mschema2qa_TAP", action="store_true", help="Enable for translated TAP of mschema2qa")
parser.add_argument("--multilingual_training", action="store_true", help="Enable for multilingual training. By enable this, we will save model from epoch 0.")
parser.add_argument("--multilingual_pt", action="store_true", help="Enable for multilingual pretraining")
parser.add_argument("--multi_pt_dataset_path_list", type=list_of_strings, help="Path of synthesized dataset for multilingual pretraining")
parser.add_argument("--cpt_weight", type=float, default=1.0, help="Weight given to loss for multilingual pretraining")
opt = parser.parse_args()
return opt
def _train(opt):
set_seed(opt.seed)
accelerator = Accelerator(
gradient_accumulation_steps=opt.gradient_accumulation_steps,
)
is_local_main_process = accelerator.is_local_main_process
if is_local_main_process:
print(opt)
if opt.wandb_log and is_local_main_process:
wandb.init(
project="ZX_seq2seq",
name=f"{opt.model_name_or_path}",
)
text2sql_tokenizer = AutoTokenizer.from_pretrained(
opt.model_name_or_path,
add_prefix_space = True
)
if isinstance(text2sql_tokenizer, AutoTokenizer):
text2sql_tokenizer.add_tokens([AddedToken(" <="), AddedToken(" <")])
# Compute batch size per gpu, by considering number of gpus and gradient accumulation steps.
opt.batch_size = opt.effective_batch_size // opt.gradient_accumulation_steps // torch.cuda.device_count()
assert opt.effective_batch_size == opt.batch_size * opt.gradient_accumulation_steps * torch.cuda.device_count()
if is_local_main_process:
print(f"batch size per gpu: {opt.batch_size}")
print(f"gradient accumulation steps: {opt.gradient_accumulation_steps}")
print(f"number of gpus: {torch.cuda.device_count()}")
print(f"effective batch size: {opt.effective_batch_size}")
if opt.dataset_type == "spider":
train_dataset = Text2SQLDataset(
dir_ = opt.train_filepath,
mode = "train"
)
elif opt.dataset_type == "mschema2qa":
if opt.mschema2qa_translate_train:
train_dataset = TTMSchema2QADataset(
dir_ = opt.train_filepath,
mode = "train",
)
elif opt.mschema2qa_TAP:
train_dataset = TAPMSchema2QADataset(
dir_ = opt.train_filepath,
mode = "train",
)
elif opt.multilingual_training:
train_dataset = MultiMschema2QADataset(
dir_ = opt.train_filepath,
mode = "train",
)
else:
train_dataset = MSchema2QADataset(
dir_ = opt.train_filepath,
data_lang = opt.dataset_lang,
mode = "train",
)
train_dataloader = DataLoader(
train_dataset,
batch_size = opt.batch_size,
shuffle = True,
collate_fn = lambda x: x,
drop_last = True
)
model_class = MT5ForConditionalGeneration if "mt5" in opt.model_name_or_path else AutoModelForSeq2SeqLM
if is_local_main_process:
print("initializing text2sql model.")
# initialize model
model = model_class.from_pretrained(opt.model_name_or_path)
model.resize_token_embeddings(len(text2sql_tokenizer))
device = accelerator.device
num_warmup_steps = int(0.1*opt.epochs*len(train_dataset)/opt.effective_batch_size) # Changed from opt.batch_size to opt.effective_batch_size
# total training steps
num_training_steps = int(opt.epochs*len(train_dataset)/opt.effective_batch_size) # Changed from opt.batch_size to opt.effective_batch_size
if opt.use_adafactor:
if is_local_main_process:
print("Let's use Adafactor!")
optimizer = Adafactor(
model.parameters(),
lr=opt.learning_rate,
scale_parameter=False,
relative_step=False,
clip_threshold = 1.0,
warmup_init=False
)
else:
if is_local_main_process:
print("Let's use AdamW!")
optimizer = optim.AdamW(
model.parameters(),
lr = opt.learning_rate
)
scheduler = transformers.get_cosine_schedule_with_warmup(
optimizer,
num_warmup_steps = num_warmup_steps,
num_training_steps = num_training_steps
)
model, optimizer, train_dataloader, scheduler = accelerator.prepare(
model, optimizer, train_dataloader, scheduler
)
train_step = 0
for epoch in range(opt.epochs):
# Training
if is_local_main_process:
print(f"This is epoch {epoch+1}.")
model.train()
train_pbar = tqdm(train_dataloader, disable=not is_local_main_process, desc="Training..")
for batch in train_pbar:
with accelerator.accumulate(model):
train_step += 1
batch_inputs = [data[0] for data in batch]
batch_sqls = [data[1] for data in batch]
tokenized_inputs = text2sql_tokenizer(
batch_inputs,
padding = "max_length",
return_tensors = "pt",
max_length = 512,
truncation = True
)
with text2sql_tokenizer.as_target_tokenizer():
tokenized_outputs = text2sql_tokenizer(
batch_sqls,
padding = "max_length",
return_tensors = 'pt',
max_length = 256,
truncation = True
)
encoder_input_ids = tokenized_inputs["input_ids"]
encoder_input_attention_mask = tokenized_inputs["attention_mask"]
decoder_labels = tokenized_outputs["input_ids"]
decoder_labels[decoder_labels == text2sql_tokenizer.pad_token_id] = -100
decoder_attention_mask = tokenized_outputs["attention_mask"]
if torch.cuda.is_available():
encoder_input_ids = encoder_input_ids.to(device)
encoder_input_attention_mask = encoder_input_attention_mask.to(device)
decoder_labels = decoder_labels.to(device)
decoder_attention_mask = tokenized_outputs["attention_mask"]
model_outputs = model(
input_ids = encoder_input_ids,
attention_mask = encoder_input_attention_mask,
labels = decoder_labels,
decoder_attention_mask = decoder_attention_mask,
return_dict = True
)
loss = model_outputs["loss"]
accelerator.backward(loss)
if opt.wandb_log and is_local_main_process:
wandb.log({"train loss": loss.item(), "train lr": optimizer.state_dict()['param_groups'][0]['lr']}, step=train_step)
elif not opt.wandb_log and is_local_main_process:
print(f"At {train_step} training step, loss = {loss.mean().item()}.")
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
optimizer.step()
scheduler.step()
optimizer.zero_grad()
if is_local_main_process:
print(f"At {train_step} training step, save a checkpoint.")
os.makedirs(opt.save_path, exist_ok = True)
accelerator.wait_for_everyone()
unwrapped_model = accelerator.unwrap_model(model)
if is_local_main_process:
if opt.multilingual_training or epoch>=30:
save_directory = os.path.join(opt.save_path, "checkpoint-{}".format(train_step))
unwrapped_model.save_pretrained(save_directory = save_directory)
print(f"Checkpoint saved at {save_directory}.")
text2sql_tokenizer.save_pretrained(save_directory = save_directory)
wandb.finish()
def _train_with_multilingual_pt(opt):
set_seed(opt.seed)
accelerator = Accelerator(
gradient_accumulation_steps=opt.gradient_accumulation_steps,
)
is_local_main_process = accelerator.is_local_main_process
if is_local_main_process:
print(opt)
if opt.wandb_log and is_local_main_process:
wandb.init(
project="ZX_seq2seq",
name=f"{opt.model_name_or_path}",
)
text2sql_tokenizer = AutoTokenizer.from_pretrained(
opt.model_name_or_path,
add_prefix_space = True
)
if isinstance(text2sql_tokenizer, AutoTokenizer):
text2sql_tokenizer.add_tokens([AddedToken(" <="), AddedToken(" <")])
# Compute batch size per gpu, by considering number of gpus and gradient accumulation steps.
opt.batch_size = opt.effective_batch_size // opt.gradient_accumulation_steps // torch.cuda.device_count()
assert opt.effective_batch_size == opt.batch_size * opt.gradient_accumulation_steps * torch.cuda.device_count()
if is_local_main_process:
print(f"batch size per gpu: {opt.batch_size}")
print(f"gradient accumulation steps: {opt.gradient_accumulation_steps}")
print(f"number of gpus: {torch.cuda.device_count()}")
print(f"effective batch size: {opt.effective_batch_size}")
if opt.dataset_type == "spider":
train_dataset = Text2SQLDataset(
dir_ = opt.train_filepath,
mode = "train"
)
train_multipt_dataset = Text2SQLMultiPTDataset(
synthesized_dataset_paths = opt.multi_pt_dataset_path_list
)
train_with_multipt_dataset = Text2SQLDatasetWithMultiPT(
text2sql_dataset = train_dataset,
multi_pt_dataset = train_multipt_dataset,
)
elif opt.dataset_type == "mschema2qa":
train_dataset = MSchema2QADataset(
dir_ = opt.train_filepath,
data_lang = opt.dataset_lang,
mode = "train",
)
train_multipt_dataset = Mschema2QAMultiPTDataset(
synthesized_dataset_paths = opt.multi_pt_dataset_path_list
)
train_with_multipt_dataset = Mschema2QADatasetWithMultiPT(
mschema2qa_dataset= train_dataset,
multi_pt_dataset = train_multipt_dataset,
)
train_dataloader = DataLoader(
train_with_multipt_dataset,
batch_size = opt.batch_size,
shuffle = True,
collate_fn = lambda x: x,
drop_last = True
)
model_class = MT5ForConditionalGeneration if "mt5" in opt.model_name_or_path else AutoModelForSeq2SeqLM
if is_local_main_process:
print("initializing text2sql model.")
# initialize model
model = model_class.from_pretrained(opt.model_name_or_path)
model.resize_token_embeddings(len(text2sql_tokenizer))
device = accelerator.device
# TODO: remove this!
if is_local_main_process:
print(f"train_dataset length: {len(train_dataset)}")
# warm up steps (10% training step)
num_warmup_steps = int(0.1*opt.epochs*len(train_dataset)/opt.effective_batch_size) # Changed from opt.batch_size to opt.effective_batch_size
# total training steps
num_training_steps = int(opt.epochs*len(train_dataset)/opt.effective_batch_size) # Changed from opt.batch_size to opt.effective_batch_size
if opt.use_adafactor:
if is_local_main_process:
print("Let's use Adafactor!")
optimizer = Adafactor(
model.parameters(),
lr=opt.learning_rate,
scale_parameter=False,
relative_step=False,
clip_threshold = 1.0,
warmup_init=False
)
else:
if is_local_main_process:
print("Let's use AdamW!")
optimizer = optim.AdamW(
model.parameters(),
lr = opt.learning_rate
)
scheduler = transformers.get_cosine_schedule_with_warmup(
optimizer,
num_warmup_steps = num_warmup_steps,
num_training_steps = num_training_steps
)
model, optimizer, train_dataloader, scheduler = accelerator.prepare(
model, optimizer, train_dataloader, scheduler
)
train_step = 0
for epoch in range(opt.epochs):
# Training
if is_local_main_process:
print(f"This is epoch {epoch+1}.")
model.train()
train_pbar = tqdm(train_dataloader, disable=not is_local_main_process, desc="Training..")
for batch in train_pbar:
with accelerator.accumulate(model):
train_step += 1
batch_inputs = [data[0] for data in batch]
batch_sqls = [data[1] for data in batch]
if opt.dataset_type == "spider":
batch_cpt_inputs = [data[4] for data in batch]
batch_cpt_outputs = [data[5] for data in batch]
elif opt.dataset_type == "mschema2qa":
batch_cpt_inputs = [data[2] for data in batch]
batch_cpt_outputs = [data[3] for data in batch]
tokenized_inputs = text2sql_tokenizer(
batch_inputs,
padding = "max_length",
return_tensors = "pt",
max_length = 512,
truncation = True
)
tokenized_cpt_inputs = text2sql_tokenizer(
batch_cpt_inputs,
padding = "max_length",
return_tensors = "pt",
max_length = 512,
truncation = True
)
if "bart" in opt.model_name_or_path:
tokenized_outputs = text2sql_tokenizer(
batch_sqls,
padding = "max_length",
return_tensors = 'pt',
max_length = 256,
truncation = True
)
tokenized_cpt_outputs = text2sql_tokenizer(
batch_cpt_outputs,
padding = "max_length",
return_tensors = 'pt',
max_length = 256,
truncation = True
)
else:
with text2sql_tokenizer.as_target_tokenizer():
tokenized_outputs = text2sql_tokenizer(
batch_sqls,
padding = "max_length",
return_tensors = 'pt',
max_length = 256,
truncation = True
)
tokenized_cpt_outputs = text2sql_tokenizer(
batch_cpt_outputs,
padding = "max_length",
return_tensors = 'pt',
max_length = 256,
truncation = True
)
encoder_input_ids = tokenized_inputs["input_ids"]
encoder_input_attention_mask = tokenized_inputs["attention_mask"]
decoder_labels = tokenized_outputs["input_ids"]
decoder_labels[decoder_labels == text2sql_tokenizer.pad_token_id] = -100
decoder_attention_mask = tokenized_outputs["attention_mask"]
if torch.cuda.is_available():
encoder_input_ids = encoder_input_ids.to(device)
encoder_input_attention_mask = encoder_input_attention_mask.to(device)
decoder_labels = decoder_labels.to(device)
decoder_attention_mask = decoder_attention_mask.to(device)
model_outputs = model(
input_ids = encoder_input_ids,
attention_mask = encoder_input_attention_mask,
labels = decoder_labels,
decoder_attention_mask = decoder_attention_mask,
return_dict = True
)
loss_text2sql = model_outputs["loss"]
# cross-lingual pretraining loss
cpt_encoder_input_ids = tokenized_cpt_inputs["input_ids"]
cpt_encoder_input_attention_mask = tokenized_cpt_inputs["attention_mask"]
cpt_decoder_labels = tokenized_cpt_outputs["input_ids"]
cpt_decoder_labels[cpt_decoder_labels == text2sql_tokenizer.pad_token_id] = -100
cpt_decoder_attention_mask = tokenized_cpt_outputs["attention_mask"]
if torch.cuda.is_available():
cpt_encoder_input_ids = cpt_encoder_input_ids.to(device)
cpt_encoder_input_attention_mask = cpt_encoder_input_attention_mask.to(device)
cpt_decoder_labels = cpt_decoder_labels.to(device)
cpt_decoder_attention_mask = cpt_decoder_attention_mask.to(device)
model_cpt_outputs = model(
input_ids = cpt_encoder_input_ids,
attention_mask = cpt_encoder_input_attention_mask,
labels = cpt_decoder_labels,
decoder_attention_mask = cpt_decoder_attention_mask,
return_dict = True
)
loss_cpt = model_cpt_outputs["loss"]
loss = loss_text2sql + opt.cpt_weight * loss_cpt
accelerator.backward(loss)
if opt.wandb_log and is_local_main_process:
wandb.log({"train loss": loss.item(), "train lr": optimizer.state_dict()['param_groups'][0]['lr']}, step=train_step)
elif not opt.wandb_log and is_local_main_process:
print(f"At {train_step} training step, loss = {loss.mean().item()}.")
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
optimizer.step()
scheduler.step()
optimizer.zero_grad()
if is_local_main_process:
print(f"At {train_step} training step, save a checkpoint.")
os.makedirs(opt.save_path, exist_ok = True)
accelerator.wait_for_everyone()
unwrapped_model = accelerator.unwrap_model(model)
if opt.dataset_type == "mschema2qa":
if is_local_main_process and epoch>=30:
save_directory = os.path.join(opt.save_path, "checkpoint-{}".format(train_step))
unwrapped_model.save_pretrained(save_directory = save_directory)
print(f"Checkpoint saved at {save_directory}.")
text2sql_tokenizer.save_pretrained(save_directory = save_directory)
else:
if is_local_main_process and epoch>=30:
# Without pretraining, We only save model from epoch 30 - till it reaches top performance on source language (also save space either)
save_directory = os.path.join(opt.save_path, "checkpoint-{}".format(train_step))
unwrapped_model.save_pretrained(save_directory = save_directory)
print(f"Checkpoint saved at {save_directory}.")
text2sql_tokenizer.save_pretrained(save_directory = save_directory)
wandb.finish()
def _train_with_lp_penalty(opt):
set_seed(opt.seed)
accelerator = Accelerator(
gradient_accumulation_steps=opt.gradient_accumulation_steps,
)
is_local_main_process = accelerator.is_local_main_process
if is_local_main_process:
print(opt)
if opt.wandb_log and is_local_main_process:
wandb.init(
project="ZX_seq2seq",
name=f"{opt.model_name_or_path}",
)
text2sql_tokenizer = AutoTokenizer.from_pretrained(
opt.model_name_or_path,
add_prefix_space = True
)
if isinstance(text2sql_tokenizer, AutoTokenizer):
text2sql_tokenizer.add_tokens([AddedToken(" <="), AddedToken(" <")])
# Compute batch size per gpu, by considering number of gpus and gradient accumulation steps.
opt.batch_size = opt.effective_batch_size // opt.gradient_accumulation_steps // torch.cuda.device_count()
assert opt.effective_batch_size == opt.batch_size * opt.gradient_accumulation_steps * torch.cuda.device_count()
if is_local_main_process:
print(f"batch size per gpu: {opt.batch_size}")
print(f"gradient accumulation steps: {opt.gradient_accumulation_steps}")
print(f"number of gpus: {torch.cuda.device_count()}")
print(f"effective batch size: {opt.effective_batch_size}")
if opt.dataset_type == "spider":
train_dataset = Text2SQLDataset(
dir_ = opt.train_filepath,
mode = "train"
)
train_lp_dataset = LanguagePredictionDataset(
langs= ["en", "zh", "vi"]
)
multitask_train_dataset = Text2SQLWithLPDataset(
text2sql_dataset = train_dataset,
lp_dataset = train_lp_dataset,
)
elif opt.dataset_type == "mschema2qa":
train_dataset = MSchema2QADataset(
dir_ = opt.train_filepath,
data_lang = opt.dataset_lang,
mode = "train",
)
train_lp_dataset = LanguagePredictionDataset(
langs= ["en", "ar", "de", "es", "fa", "fi", "it", "ja", "pl", "tr", "zh"]
)
multitask_train_dataset = Mschema2QAWithLPDataset(
mschema2qa_dataset= train_dataset,
lp_dataset = train_lp_dataset,
)
train_dataloader = DataLoader(
multitask_train_dataset,
batch_size = opt.batch_size,
shuffle = True,
collate_fn = lambda x: x,
drop_last = True
)
model_class = MT5ForConditionalGenerationWithLP if "mt5" in opt.model_name_or_path else AutoModelForSeq2SeqLM
num_langs=3 if opt.dataset_type == "spider" else 11
if is_local_main_process:
print("initializing text2sql model.")
# initialize model
model = model_class.from_pretrained(opt.model_name_or_path, num_langs)
model.resize_token_embeddings(len(text2sql_tokenizer))
device = accelerator.device
# TODO: remove this!
if is_local_main_process:
print(f"train_dataset length: {len(train_dataset)}")
# warm up steps (10% training step)
num_warmup_steps = int(0.1*opt.epochs*len(train_dataset)/opt.effective_batch_size) # Changed from opt.batch_size to opt.effective_batch_size
# total training steps
num_training_steps = int(opt.epochs*len(train_dataset)/opt.effective_batch_size) # Changed from opt.batch_size to opt.effective_batch_size
if opt.use_adafactor:
if is_local_main_process:
print("Let's use Adafactor!")
optimizer = Adafactor(
model.parameters(),
lr=opt.learning_rate,
scale_parameter=False,
relative_step=False,
clip_threshold = 1.0,
warmup_init=False
)
else:
if is_local_main_process:
print("Let's use AdamW!")
optimizer = optim.AdamW(
model.parameters(),
lr = opt.learning_rate
)
scheduler = transformers.get_cosine_schedule_with_warmup(
optimizer,
num_warmup_steps = num_warmup_steps,
num_training_steps = num_training_steps
)
model_decoder_start_token_id = model.config.decoder_start_token_id
model, optimizer, train_dataloader, scheduler = accelerator.prepare(
model, optimizer, train_dataloader, scheduler
)
train_step = 0
for epoch in range(opt.epochs):
# Training
if is_local_main_process:
print(f"This is epoch {epoch+1}.")
model.train()
train_pbar = tqdm(train_dataloader, disable=not is_local_main_process, desc="Training..")
for batch in train_pbar:
with accelerator.accumulate(model):
train_step += 1
grad_reverse_lambda = 2/(1+math.exp(-1*40*(train_step/num_training_steps)))-1
batch_inputs = [data[0] for data in batch]
batch_sqls = [data[1] for data in batch]
if opt.dataset_type == "spider":
batch_lp_inputs = [data[4] for data in batch]
batch_lp_labels = [data[5] for data in batch]
elif opt.dataset_type == "mschema2qa":
batch_lp_inputs = [data[2] for data in batch]
batch_lp_labels = [data[3] for data in batch]
tokenized_inputs = text2sql_tokenizer(
batch_inputs,
padding = "max_length",
return_tensors = "pt",
max_length = 512,
truncation = True
)
tokenized_lp_inputs = text2sql_tokenizer(
batch_lp_inputs,
padding = "max_length",
return_tensors = "pt",
max_length = 512,
truncation = True
)
if "bart" in opt.model_name_or_path:
tokenized_outputs = text2sql_tokenizer(
batch_sqls,
padding = "max_length",
return_tensors = 'pt',
max_length = 256,
truncation = True
)
else:
with text2sql_tokenizer.as_target_tokenizer():
tokenized_outputs = text2sql_tokenizer(
batch_sqls,
padding = "max_length",
return_tensors = 'pt',
max_length = 256,
truncation = True
)
encoder_input_ids = tokenized_inputs["input_ids"]
encoder_input_attention_mask = tokenized_inputs["attention_mask"]
decoder_labels = tokenized_outputs["input_ids"]
decoder_labels[decoder_labels == text2sql_tokenizer.pad_token_id] = -100
decoder_attention_mask = tokenized_outputs["attention_mask"]
if torch.cuda.is_available():
encoder_input_ids = encoder_input_ids.to(device)
encoder_input_attention_mask = encoder_input_attention_mask.to(device)
decoder_labels = decoder_labels.to(device)
decoder_attention_mask = decoder_attention_mask.to(device)
model_outputs = model(
input_ids = encoder_input_ids,
attention_mask = encoder_input_attention_mask,
labels = decoder_labels,
decoder_attention_mask = decoder_attention_mask,
return_dict = True
)
loss_text2sql = model_outputs["loss"]
# Language prediction loss
lp_input_ids = tokenized_lp_inputs["input_ids"]
lp_attention_mask = tokenized_lp_inputs["attention_mask"]
if torch.cuda.is_available():
lp_input_ids = lp_input_ids.to(device)
lp_attention_mask = lp_attention_mask.to(device)
lp_labels = torch.tensor(batch_lp_labels).to(device)
model_lp_outputs = model(
input_ids = lp_input_ids,
attention_mask = lp_attention_mask,
labels=lp_labels,
task_id=1,
grad_reverse_lambda=grad_reverse_lambda
)
loss_lp = model_lp_outputs["loss"]
loss = loss_text2sql + opt.lp_penalty_weight*loss_lp
accelerator.backward(loss)
if opt.wandb_log and is_local_main_process:
wandb.log({"train loss": loss.item(), "train lr": optimizer.state_dict()['param_groups'][0]['lr']}, step=train_step)
elif not opt.wandb_log and is_local_main_process:
print(f"At {train_step} training step, loss = {loss.mean().item()}.")
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
optimizer.step()
scheduler.step()
optimizer.zero_grad()
if is_local_main_process:
print(f"At {train_step} training step, save a checkpoint.")
os.makedirs(opt.save_path, exist_ok = True)
accelerator.wait_for_everyone()
unwrapped_model = accelerator.unwrap_model(model)
if opt.dataset_type == "mschema2qa":
if is_local_main_process and epoch>=30:
save_directory = os.path.join(opt.save_path, "checkpoint-{}".format(train_step))
unwrapped_model.save_pretrained(save_directory = save_directory)
print(f"Checkpoint saved at {save_directory}.")
text2sql_tokenizer.save_pretrained(save_directory = save_directory)
else:
if is_local_main_process and epoch>=30:
# Without pretraining, We only save model from epoch 30, since model with earlier epoch produced invalid sql, resulting in massive evaluation time
save_directory = os.path.join(opt.save_path, "checkpoint-{}".format(train_step))
unwrapped_model.save_pretrained(save_directory = save_directory)
print(f"Checkpoint saved at {save_directory}.")
text2sql_tokenizer.save_pretrained(save_directory = save_directory)
wandb.finish()
def _train_with_reconstruction(opt):
set_seed(opt.seed)
accelerator = Accelerator(
gradient_accumulation_steps=opt.gradient_accumulation_steps,
)
is_local_main_process = accelerator.is_local_main_process
if is_local_main_process:
print(opt)
if opt.wandb_log and is_local_main_process:
wandb.init(
project="ZX_seq2seq",
name=f"{opt.model_name_or_path}_with_reconstruction",
)
text2sql_tokenizer = AutoTokenizer.from_pretrained(
opt.model_name_or_path,
add_prefix_space = True
)
if isinstance(text2sql_tokenizer, AutoTokenizer):
text2sql_tokenizer.add_tokens([AddedToken(" <="), AddedToken(" <")])
special_tokens_dict = {'additional_special_tokens': ["<mask>"]}
text2sql_tokenizer.add_special_tokens(special_tokens_dict)
# Compute batch size per gpu, by considering number of gpus and gradient accumulation steps.
opt.batch_size = opt.effective_batch_size // opt.gradient_accumulation_steps // torch.cuda.device_count()
assert opt.effective_batch_size == opt.batch_size * opt.gradient_accumulation_steps * torch.cuda.device_count()
if is_local_main_process:
print(f"batch size per gpu: {opt.batch_size}")
print(f"gradient accumulation steps: {opt.gradient_accumulation_steps}")
print(f"number of gpus: {torch.cuda.device_count()}")
print(f"effective batch size: {opt.effective_batch_size}")
if opt.dataset_type == "spider":
train_dataset = Text2SQLDataset(
dir_ = opt.train_filepath,
mode = "train"
)
train_recon_dataset = ReconstructionDataset(
langs= ["en", "zh", "vi"],
tokenizer=text2sql_tokenizer,
max_seq_length=opt.max_seq_length,
mask_rate=opt.mask_rate
)
multitask_train_dataset = Text2SQLWithReconDataset(
text2sql_dataset = train_dataset,
reconstruction_dataset = train_recon_dataset,
)
elif opt.dataset_type == "mschema2qa":
train_dataset = MSchema2QADataset(
dir_ = opt.train_filepath,
data_lang = opt.dataset_lang,
mode = "train",
)
train_recon_dataset = ReconstructionDataset(
langs= ["en", "ar", "de", "es", "fa", "fi", "it", "ja", "pl", "tr", "zh"],
tokenizer=text2sql_tokenizer,
max_seq_length=opt.max_seq_length,
mask_rate=opt.mask_rate
)
multitask_train_dataset = Mschema2QAWithReconDataset(
mschema2qa_dataset= train_dataset,
reconstruction_dataset = train_recon_dataset,
)
train_dataloader = DataLoader(
multitask_train_dataset,
batch_size = opt.batch_size,
shuffle = True,
collate_fn = lambda x: x,
drop_last = True
)
model_class = MT5ForConditionalGeneration if "mt5" in opt.model_name_or_path else AutoModelForSeq2SeqLM
if is_local_main_process:
print("initializing text2sql model.")
# initialize model
model = model_class.from_pretrained(opt.model_name_or_path)
model.resize_token_embeddings(len(text2sql_tokenizer))
device = accelerator.device
# TODO: remove this!
if is_local_main_process:
print(f"train_dataset length: {len(train_dataset)}")
# warm up steps (10% training step)
num_warmup_steps = int(0.1*opt.epochs*len(train_dataset)/opt.effective_batch_size) # Changed from opt.batch_size to opt.effective_batch_size
# total training steps
num_training_steps = int(opt.epochs*len(train_dataset)/opt.effective_batch_size) # Changed from opt.batch_size to opt.effective_batch_size
if opt.use_adafactor:
if is_local_main_process:
print("Let's use Adafactor!")
optimizer = Adafactor(
model.parameters(),
lr=opt.learning_rate,
scale_parameter=False,
relative_step=False,
clip_threshold = 1.0,
warmup_init=False
)
else:
if is_local_main_process:
print("Let's use AdamW!")
optimizer = optim.AdamW(
model.parameters(),
lr = opt.learning_rate
)
scheduler = transformers.get_cosine_schedule_with_warmup(
optimizer,
num_warmup_steps = num_warmup_steps,
num_training_steps = num_training_steps
)
model_decoder_start_token_id = model.config.decoder_start_token_id
model, optimizer, train_dataloader, scheduler = accelerator.prepare(
model, optimizer, train_dataloader, scheduler
)
train_step = 0
for epoch in range(opt.epochs):
# Training
if is_local_main_process:
print(f"This is epoch {epoch+1}.")
model.train()
train_pbar = tqdm(train_dataloader, disable=not is_local_main_process, desc="Training..")