-
Notifications
You must be signed in to change notification settings - Fork 1
/
seq2seq.py
1534 lines (1371 loc) · 56.8 KB
/
seq2seq.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 argparse
import json
import math
import os
from typing import List
import torch
import torch.nn as nn
from accelerate import Accelerator
from torch.optim import AdamW
from torch.utils.data import DataLoader
from tqdm.auto import tqdm
from transformers import (
PreTrainedModel,
PreTrainedTokenizerBase,
get_scheduler,
set_seed,
)
from transformers.models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
import wandb
from constrained_generation import constrained_beam_search, unconstrained_beam_search
from dataset import get_dataloader, get_task_tags
from evaluate import (
evaluate_most_probable,
)
from load_model import find_end_turn_token, load_model
def gen_batch(iterable, n=1):
l = len(iterable)
for ndx in range(0, l, n):
yield iterable[ndx : min(ndx + n, l)]
def experiment_done(experiment_dir: str, test_tsvs: List[str]):
for test_tsv in test_tsvs:
test_name = os.path.splitext(os.path.basename(test_tsv))[0]
dir_name = os.path.basename(os.path.basedir(test_tsv))
if len(dir_name) > 0:
test_name = f"{dir_name}_{test_name}"
else:
test_name = f"{test_name}"
if not os.path.exists(os.path.join(experiment_dir, f"{test_name}.txt")):
return False
return True
def parse_args():
parser = argparse.ArgumentParser(
description="Finetune a transformers model on a text classification task"
)
parser.add_argument(
"--train_tsvs",
nargs="+",
type=str,
default=None,
help="A tsv file in conll format containing the sl training data.",
)
parser.add_argument(
"--dev_tsvs",
nargs="+",
type=str,
default=None,
help="A tsv file in conll format containing the sl training data.",
)
parser.add_argument(
"--test_tsvs",
nargs="+",
type=str,
default=None,
help="A tsv file in conll format containing the sl training data.",
)
parser.add_argument(
"--num_beams",
type=int,
default=1,
help="Number of beams to use for evaluation. This argument will be "
"passed to ``model.generate``, which is used during ``evaluate`` and ``predict``.",
)
parser.add_argument(
"--num_return_sequences",
type=int,
default=1,
help="Number of sequences to return. This argument will be "
"passed to ``model.generate``, which is used during ``predict``.",
)
parser.add_argument(
"--max_source_length",
type=int,
default=256,
help="The maximum total input sequence length after "
"tokenization.Sequences longer than this will be truncated, sequences shorter will be padded.",
)
parser.add_argument(
"--max_target_length",
type=int,
default=256,
help="The maximum total sequence length for target text after "
"tokenization. Sequences longer than this will be truncated, sequences shorter will be padded."
"during ``evaluate`` and ``predict``.",
)
parser.add_argument(
"--model_name_or_path",
type=str,
help="Path to pretrained model or model identifier from huggingface.co/models.",
required=True,
)
parser.add_argument(
"--per_device_train_batch_size",
type=int,
default=8,
help="Batch size (per device) for the training dataloader.",
)
parser.add_argument(
"--per_device_eval_batch_size",
type=int,
default=64,
help="Starting batch size (per device) for evaluation batch size finder. We will start with batch and "
"reduce it until the batch fits in memory.",
)
parser.add_argument(
"--learning_rate",
type=float,
default=1e-4,
help="Initial learning rate (after the potential warmup period) to use.",
)
parser.add_argument(
"--weight_decay", type=float, default=0.0, help="Weight decay to use."
)
parser.add_argument(
"--num_train_epochs",
type=int,
default=3,
help="Total number of training epochs to perform.",
)
parser.add_argument(
"--gradient_accumulation_steps",
type=int,
default=1,
help="Number of updates steps to accumulate before performing a backward/update pass.",
)
parser.add_argument(
"--optim",
type=str,
default="adamw",
help="The optimizer to use. Adafactor is recommended for training T5, mT5 and FLAN models. "
"AdamW is recommended for LoRA and decoder-only models. Adafactor requires fairseq, you can install it with "
"pip install fairseq.",
choices=["adamw", "adamw8bits", "adafactor", "deepspeed"],
)
parser.add_argument(
"--lr_scheduler_type",
type=str,
default="cosine",
help="The scheduler type to use.",
choices=[
"linear",
"cosine",
"cosine_with_restarts",
"polynomial",
"constant",
"constant_with_warmup",
],
)
parser.add_argument(
"--num_warmup_steps",
type=int,
default=500,
help="Number of steps for the warmup in the lr scheduler.",
)
parser.add_argument(
"--output_dir", type=str, required=True, help="Where to store the final model."
)
parser.add_argument(
"--seed", type=int, default=None, help="A seed for reproducible training."
)
parser.add_argument(
"--eval_every_epochs",
type=int,
default=1,
help="We will evaluate every X epochs. Set this to 0 to disable evaluation.",
)
parser.add_argument(
"--eval_every_steps",
type=int,
default=0,
help="We will evaluate every X steps. Set this to 0 to disable evaluation.",
)
parser.add_argument(
"--project_name",
type=str,
default="SeqLabeling_w_LLMs",
help="The project name to use for wandb.",
)
parser.add_argument(
"--use_lora",
action="store_true",
help="Use LoRA for efficient training. We will convert the model to 8-bit and use LoRA to train it. "
"You should be able to train large models in consumer-grade GPUs with this option.",
)
parser.add_argument(
"--lora_r",
type=int,
default=16,
help="The r parameter for LoRA. This is the number of bits to quantize the weights to.",
)
parser.add_argument(
"--lora_alpha",
type=int,
default=32,
help="The alpha parameter for LoRA. This is the learning rate multiplier for the quantized weights.",
)
parser.add_argument(
"--lora_dropout",
type=float,
default=0.05,
help="The dropout probability for LoRA. This is the probability of dropping a weight during training.",
)
parser.add_argument(
"--lora_target_modules",
type=str,
nargs="+",
default=["all"],
help="The modules to apply LoRA to. This is a comma-separated list of module names. "
"If not specified we will add LoRA to all the compatible layers.",
)
parser.add_argument(
"--constrained_generation",
action="store_true",
help="Use constrained generation. ",
)
parser.add_argument(
"--unconstrained_generation",
action="store_true",
help="Use unconstrained generation.",
)
parser.add_argument(
"--use_flash_attention",
action="store_true",
help="Weather to use flash attention ",
)
parser.add_argument(
"--trust_remote_code",
action="store_true",
help="Weather to use flash attention ",
)
parser.add_argument(
"--mixed_precision",
type=str,
default="no",
choices=["fp16", "bf16", "no"],
help="Whether to use mixed precision or not. Models such as mT5 are trained with bf16, if you set fp16 "
"the loss will probably end up being NaN due to conversion issues. Check how the model was trained "
"and set this flag accordingly.",
)
parser.add_argument(
"--quantization",
type=int,
default=None,
help="Whether to use '4' or '8' bit quantization. "
"Requires bitsandbytes library: https://github.com/TimDettmers/bitsandbytes",
)
parser.add_argument(
"--force_auto_device_map",
type=int,
default=None,
help="Whether to force the use of the auto device map. If set to True, the model will be split across "
"GPUs and CPU to fit the model in memory. If set to False, a full copy of the model will be loaded "
"into each GPU. Defaults to False.",
)
parser.add_argument(
"--local_rank",
type=int,
default=-1,
help="For distributed training: local_rank",
)
parser.add_argument(
"--add_labels_as_tokens",
action="store_true",
help="Add the labels as tokens to the tokenizer",
)
parser.add_argument(
"--add_labels_as_prompt",
action="store_true",
help="We will append the labels of the task at the start of the input sentence, usefull for multi-task",
)
parser.add_argument(
"--prompt",
type=str,
default=None,
help="The prompt to use for the task, "
"this is a text that will be appended to the start of the input sentence. "
"Useful for zero-shot inference.",
)
parser.add_argument(
"--source_lang",
type=str,
default=None,
help="The source language, this is useful if you want to use a machine translation model such as"
"m2m100 or nllb200. If set to None, we will ignore this parameter.",
)
parser.add_argument(
"--target_lang",
type=str,
default=None,
help="The target language, this is useful if you want to use a machine translation model such as"
"m2m100 or nllb200. If set to None, we will ignore this parameter.",
)
args = parser.parse_args()
os.makedirs(args.output_dir, exist_ok=True)
if args.train_tsvs is not None and args.dev_tsvs is None:
raise ValueError("You must specify a dev set if you specify a train set.")
if not args.constrained_generation and not args.unconstrained_generation:
raise ValueError(
"You must specify either constrained_generation or unconstrained_generation."
)
return args
def print_trainable_parameters(model):
"""
Prints the number of trainable parameters in the model.
"""
trainable_params = 0
all_param = 0
for _, param in model.named_parameters():
all_param += param.numel()
if param.requires_grad:
trainable_params += param.numel()
print(
f"\n---> Trainable params: {trainable_params} || all params: {all_param} || trainable%: {100 * trainable_params / all_param}\n"
)
return trainable_params, all_param, 100 * trainable_params / all_param
def get_dtype(accelerator: Accelerator):
if accelerator.state.mixed_precision == "bf16":
dtype = "bfloat16"
elif accelerator.state.mixed_precision == "fp16":
dtype = "float16"
else:
dtype = None
return dtype
def evaluate(
dataloader: DataLoader,
constrained_generation: bool,
accelerator: Accelerator,
model: PreTrainedModel,
tokenizer: PreTrainedTokenizerBase,
max_length: int,
num_beams: int,
num_return_sequences: int,
output_dir: str,
stage: str = "dev",
epoch: int = -1,
train_step: int = -1,
forced_bos_token: int = None,
):
if accelerator.is_local_main_process:
print(f"***** Evaluating {dataloader.dataset.file_path} *****")
if epoch != -1:
print(f" Epoch = {epoch}")
print(f" Train step = {train_step}")
print(f" Num examples = {len(dataloader.dataset)}")
print(
f" Gen kwargs = "
f"{{'constrained_generation' : {constrained_generation}, "
f"'num_return_sequences': {num_return_sequences}, "
f"'num_beams': {num_beams}, "
f"'max_length': {max_length}}}"
)
print()
os.makedirs(output_dir, exist_ok=True)
model.eval()
model_outputs_txt: List[List[str]] = []
gold_txt: List[str] = []
original_txt: List[str] = []
model_inputs_txt: List[str] = []
samples_seen: int = 0
eos_token_id = find_end_turn_token(tokenizer)
test_name = os.path.splitext(os.path.basename(dataloader.dataset.file_path))[0]
dir_name = os.path.basename(os.path.dirname(dataloader.dataset.file_path))
if len(dir_name) > 0:
test_name = f"{dir_name}_{test_name}"
else:
test_name = f"{test_name}"
if stage == "dev":
filename = f"{test_name}_epoch_{epoch}_step_{train_step}_{'constrained' if constrained_generation else 'unconstrained'}"
else:
filename = f"{test_name}_{'constrained' if constrained_generation else 'unconstrained'}"
if accelerator.is_local_main_process:
print(f"Writing predictions to {os.path.join(output_dir, f'{filename}.jsonl')}")
dtype = get_dtype(accelerator)
if dtype is not None:
dtype = torch.float16 if dtype == "float16" else torch.bfloat16
with open(os.path.join(output_dir, f"{filename}.jsonl"), "w", encoding="utf8") as f:
for step, batch in enumerate(
tqdm(
dataloader,
disable=not accelerator.is_local_main_process,
ascii=True,
desc=f"{test_name}",
)
):
if constrained_generation:
with torch.cuda.amp.autocast(enabled=dtype is not None, dtype=dtype):
generated_tokens = constrained_beam_search(
model_inputs=batch,
model=accelerator.unwrap_model(model),
start_labels_ids=dataloader.dataset.start_labels_ids,
end_labels_ids=dataloader.dataset.end_labels_ids,
start_labels_names=list(
range(len(dataloader.dataset.start_labels_ids))
),
end_labels_names=list(
range(len(dataloader.dataset.end_labels_ids))
),
pad_token_id=tokenizer.pad_token_id,
eos_token_id=eos_token_id,
max_length=max_length,
num_beams=num_beams,
num_return_sequences=num_return_sequences,
forced_bos_token_id=forced_bos_token,
)
# print(batch.labeled_sentence_ids)
# print(
# tokenizer.batch_decode(
# batch.labeled_sentence_ids,
# skip_special_tokens=False,
# clean_up_tokenization_spaces=False,
# )
# )
else:
with torch.cuda.amp.autocast(enabled=dtype is not None, dtype=dtype):
generated_tokens = unconstrained_beam_search(
model_inputs=batch,
model=accelerator.unwrap_model(model),
max_length=max_length,
num_beams=num_beams,
num_return_sequences=num_return_sequences,
forced_bos_token_id=forced_bos_token,
)
input_tokens = (
accelerator.gather(
accelerator.pad_across_processes(
batch.input_ids,
dim=1,
pad_index=tokenizer.pad_token_id,
pad_first=tokenizer.padding_side == "left",
)
)
.cpu()
.tolist()
)
generated_tokens = (
accelerator.gather(
accelerator.pad_across_processes(
generated_tokens,
dim=1,
pad_index=tokenizer.pad_token_id,
)
)
.cpu()
.tolist()
)
original_sentences = (
accelerator.gather(
accelerator.pad_across_processes(
batch.original_sentence_ids,
dim=1,
)
)
.cpu()
.tolist()
)
gold_tokens = (
accelerator.gather(
accelerator.pad_across_processes(
batch.labeled_sentence_ids,
dim=1,
pad_index=tokenizer.pad_token_id,
)
)
.cpu()
.tolist()
)
if accelerator.is_local_main_process:
if accelerator.num_processes > 1:
# Remove duplicated in last batch if we are in a distributed setting
if step == len(dataloader) - 1:
generated_tokens = generated_tokens[
: (len(dataloader.dataset) - samples_seen)
* num_return_sequences
]
gold_tokens = gold_tokens[
: (len(dataloader.dataset) - samples_seen)
]
original_sentences = original_sentences[
: (len(dataloader.dataset) - samples_seen)
]
input_tokens = input_tokens[
: (len(dataloader.dataset) - samples_seen)
]
else:
samples_seen += len(batch)
generated_tokens = list(
gen_batch(
tokenizer.batch_decode(
generated_tokens,
skip_special_tokens=True,
clean_up_tokenization_spaces=False,
),
n=num_return_sequences,
)
)
gold_tokens = tokenizer.batch_decode(
gold_tokens,
skip_special_tokens=True,
clean_up_tokenization_spaces=False,
)
# print(gold_tokens)
original_sentences = tokenizer.batch_decode(
original_sentences,
skip_special_tokens=True,
clean_up_tokenization_spaces=False,
)
input_tokens = tokenizer.batch_decode(
input_tokens,
skip_special_tokens=False,
clean_up_tokenization_spaces=False,
)
model_outputs_txt.extend(generated_tokens)
gold_txt.extend(gold_tokens)
original_txt.extend(original_sentences)
model_inputs_txt.extend(input_tokens)
for prediction, gold, orig, model_input_txt in zip(
generated_tokens, gold_tokens, original_sentences, input_tokens
):
print(
json.dumps(
{
"model_input": model_input_txt,
"input_sentence": orig,
"prediction": prediction,
"gold": gold,
},
ensure_ascii=False,
),
file=f,
)
if step % 100 == 0:
f.flush()
accelerator.wait_for_everyone()
# f1, f1_upperbound = (-1, -1)
f1 = -1
if accelerator.is_main_process:
f1 = evaluate_most_probable(
predictions=model_outputs_txt,
gold=gold_txt,
output_name=os.path.join(output_dir, f"{filename}"),
task_labels=dataloader.dataset.task_labels,
)
# f1_upperbound = evaluate_best_prediction(
# predictions=model_outputs_txt,
# gold=gold_txt,
# output_name=os.path.join(output_dir, f"{filename}.upperbound"),
# task_labels=dataloader.dataset.task_labels,
# )
if stage == "dev":
wandb.log(
{
f"Val/{test_name}/f1_{'constrained' if constrained_generation else 'unconstrained'}": f1,
# f"Val/{test_name}/f1_upperbound": f1_upperbound,
"epoch": epoch,
"step": train_step,
}
)
else:
wandb.log(
{
f"{test_name}/f1_{'constrained' if constrained_generation else 'unconstrained'}": f1,
# f"{test_name}/f1_upperbound": f1_upperbound,
}
)
print(
f"\n{test_name}\n"
f" -- f1_{'constrained' if constrained_generation else 'unconstrained'}: {f1}.\n"
# f" -- f1_upperbound: {f1_upperbound}\n"
)
return f1
def seq2seq(
train_tsvs: List[str],
dev_tsvs: List[str],
test_tsvs: List[str],
num_beams: int,
num_return_sequences: int,
max_source_length: int,
max_target_length: int,
model_name_or_path: str,
per_device_train_batch_size: int,
per_device_eval_batch_size: int,
learning_rate: int,
weight_decay: float,
num_train_epochs: int,
gradient_accumulation_steps: int,
optim: str,
lr_scheduler_type: str,
num_warmup_steps: int,
output_dir: str,
seed: int,
eval_every_epochs: int,
eval_every_steps: int,
project_name: str,
use_lora: bool,
lora_r: int,
lora_alpha: int,
lora_dropout: float,
lora_target_modules: List[str],
constrained_generation: bool,
unconstrained_generation: bool,
mixed_precision: str,
quantization: int,
local_rank: int,
add_labels_as_tokens: bool,
add_labels_as_prompt: bool,
force_auto_device_map: bool,
prompt: str,
source_lang: str,
target_lang: str,
use_flash_attention: bool,
trust_remote_code: bool,
):
# if experiment_done(experiment_dir=output_dir, test_tsvs=test_tsvs):
# print(f"Experiment {output_dir} already done, skipping.")
# return True
trust_remote_code = True # @todo Remove for release
if not constrained_generation:
print(
"WARNING!!! Constrained generation is disabled, are you sure you want to do this?\n"
"Use --constrained_generation to enable it."
)
if constrained_generation and unconstrained_generation:
print(
"We will use constrained generation and unconstrained generation. This means that we will run two "
"inference runs for each dataset. This is useful if you want to compare the performance of the model "
"with and without the constraints. If you don't want to run unconstrained generation, please remove "
"the --unconstrained_generation flag."
)
if quantization and train_tsvs is not None and not use_lora:
raise ValueError(
"Training with 8 bits or 4 bits quantization is only supported with LORA. If you want to train "
"in Int8, please add the flag --use_lora. You can only evaluate in 4/8 bits without LoRA."
)
if seed is not None:
set_seed(seed)
accelerator = Accelerator(mixed_precision=mixed_precision)
if accelerator.is_local_main_process:
wandb.init(
project=project_name,
name=f"{os.path.basename(output_dir)}",
resume=None,
config={
"max_source_length": max_source_length,
"max_target_length": max_source_length,
"per_device_eval_batch_size": 1,
"output_dir": output_dir,
"num_beams": num_beams,
"num_return_sequences": num_return_sequences,
"constrained_generation": constrained_generation,
"unconstrained_generation": unconstrained_generation,
"use_lora": use_lora,
"lora_r": lora_r,
"lora_alpha": lora_alpha,
"lora_dropout": lora_dropout,
"lora_target_modules": lora_target_modules,
"model_name_or_path": model_name_or_path,
"train_tsvs": train_tsvs,
"dev_tsvs": dev_tsvs,
"test_tsvs": test_tsvs,
"numGPU": accelerator.num_processes,
"quantization": quantization,
},
)
if (
train_tsvs is not None
): # Do not overwrite the wandb run train info if we are just evaluating
wandb.config.per_device_train_batch_size = per_device_train_batch_size
wandb.config.gradient_accumulation_steps = gradient_accumulation_steps
wandb.config.learning_rate = learning_rate
wandb.config.weight_decay = weight_decay
wandb.config.lr_scheduler_type = lr_scheduler_type
wandb.config.num_warmup_steps = num_warmup_steps
wandb.config.seed = seed
wandb.config.eval_every_epochs = eval_every_epochs
wandb.config.eval_every_steps = eval_every_steps
wandb.config.Mixed_precision = accelerator.mixed_precision
wandb.config.num_train_epochs = num_train_epochs
if train_tsvs is not None:
if accelerator.is_local_main_process:
print(f"Loading model from {model_name_or_path}")
start_labels, end_labels = [], []
for train_tsv in train_tsvs:
sl, el = get_task_tags(train_tsv)
start_labels.extend(sl)
end_labels.extend(el)
if use_lora and add_labels_as_tokens:
extended_model_path = os.path.join(output_dir, "extended_model")
if accelerator.is_local_main_process:
print(
f"Using LoRA and add_labels_as_tokens, we will create a new model extending the original one with the "
f"labels as tokens. It will be saved in {extended_model_path}."
)
model, tokenizer, model_type = load_model(
inference=True,
model_weights_name_or_path=model_name_or_path,
use_lora=False,
quantization=None,
add_labels_as_tokens=add_labels_as_tokens,
labels=start_labels + end_labels,
use_flash_attention=use_flash_attention,
trust_remote_code=trust_remote_code,
torch_dtype=get_dtype(accelerator),
)
model.save_pretrained(extended_model_path)
tokenizer.save_pretrained(extended_model_path)
model_name_or_path = extended_model_path
model, tokenizer, model_type = load_model(
inference=False,
model_weights_name_or_path=model_name_or_path,
use_lora=use_lora,
lora_r=lora_r,
lora_alpha=lora_alpha,
lora_dropout=lora_dropout,
lora_target_modules=lora_target_modules,
quantization=quantization,
add_labels_as_tokens=add_labels_as_tokens,
labels=start_labels + end_labels,
force_auto_device_map=force_auto_device_map,
use_gradient_checkpointing=quantization is not None or use_lora,
use_flash_attention=use_flash_attention,
trust_remote_code=trust_remote_code,
torch_dtype=get_dtype(accelerator),
)
if accelerator.is_local_main_process:
print("Model loaded!")
if source_lang:
try:
_ = tokenizer.lang_code_to_id[source_lang]
except KeyError:
raise KeyError(
f"Language {source_lang} not found in tokenizer. "
f"Available languages: {tokenizer.lang_code_to_id.keys()}"
)
tokenizer.src_lang = source_lang
if target_lang:
try:
forced_bos_token = tokenizer.lang_code_to_id[target_lang]
except KeyError:
raise KeyError(
f"Language {target_lang} not found in tokenizer. "
f"Available languages: {tokenizer.lang_code_to_id.keys()}"
)
tokenizer.tgt_lang = target_lang
else:
forced_bos_token = None
trainable_params, all_param, percent_trainable = print_trainable_parameters(
model
)
if accelerator.is_local_main_process:
wandb.config.trainable_params = trainable_params
wandb.config.all_param = all_param
wandb.config.percent_trainable = percent_trainable
if accelerator.is_local_main_process:
print(f"Loading training dataset from {train_tsvs}")
train_dataloader = get_dataloader(
tokenizer=tokenizer,
filenames=train_tsvs,
batch_size=per_device_train_batch_size,
max_source_len=max_source_length,
max_target_len=max_target_length,
is_encoder_decoder=model_type == "seq2seq",
train=True,
input_prompt=None if prompt is None else prompt,
num_workers=min(os.cpu_count(), 8),
add_labels_as_context=add_labels_as_prompt,
verbosity=accelerator.is_local_main_process,
)
val_dataloaders = []
if accelerator.is_local_main_process:
print(
f"Found {len(dev_tsvs)} validation datasets, we will average their scores for best model selection."
)
for dev_tsv in dev_tsvs:
if accelerator.is_local_main_process:
print(f"Loading validation dataset from {dev_tsv}")
val_dataloaders.append(
get_dataloader(
tokenizer=tokenizer,
filenames=[dev_tsv],
batch_size=per_device_eval_batch_size,
max_source_len=max_source_length,
max_target_len=max_target_length,
is_encoder_decoder=model_type == "seq2seq",
train=False,
input_prompt=None if prompt is None else prompt,
num_workers=min(os.cpu_count(), 8),
add_labels_as_context=add_labels_as_prompt,
verbosity=accelerator.is_local_main_process,
)
)
num_update_steps_per_epoch = math.ceil(
len(train_dataloader)
/ gradient_accumulation_steps
/ accelerator.num_processes
)
max_train_steps = num_train_epochs * num_update_steps_per_epoch
total_batch_size = (
per_device_train_batch_size
* accelerator.num_processes
* gradient_accumulation_steps
)
if accelerator.is_local_main_process:
wandb.config.total_batch_size = total_batch_size
wandb.config.max_train_steps = max_train_steps
no_decay = ["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": 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,
},
]
if optim.lower() == "adamw8bits":
import bitsandbytes as bnb
optimizer = bnb.optim.PagedAdam8bit(
optimizer_grouped_parameters,
lr=learning_rate,
betas=(0.9, 0.995),
)
elif optim.lower() == "adamw":
optimizer = AdamW(optimizer_grouped_parameters, lr=learning_rate, eps=1e-7)
elif optim.lower() == "adafactor":
try:
from fairseq.optim.adafactor import Adafactor
except ImportError:
raise ImportError(
"Please install fairseq to use Adafactor optimizer: "
"https://github.com/facebookresearch/fairseq#requirements-and-installation\n"
"You can run: pip install fairseq"
)
optimizer = Adafactor(
params=optimizer_grouped_parameters,
scale_parameter=False,
relative_step=False,
warmup_init=False,
lr=learning_rate,
clip_threshold=1.0,
# weight_decay=args.weight_decay,
)
elif optim.lower() == "deepspeed":
from accelerate.utils import DummyOptim
kwargs = {
"optimizer": {
"params": {
"lr": learning_rate,
"betas": (0.9, 0.999),
"eps": 1e-8,
"weight_decay": weight_decay,
}
},
"scheduler": {
"params": {
"warmup_min_lr": 0.0,
"warmup_max_lr": learning_rate,
"warmup_num_steps": num_warmup_steps,
"warmup_type": "linear",
"total_num_steps": max_train_steps,
}
},
}
optimizer = DummyOptim(
params=optimizer_grouped_parameters,
lr=learning_rate,
weight_decay=weight_decay,
kwargs=kwargs,
)
else:
raise ValueError(