forked from PaddlePaddle/PaddleNLP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtraining_args.py
2150 lines (1941 loc) · 112 KB
/
training_args.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
# Copyright 2020-present the HuggingFace Inc. team.
# Copyright 2020 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# This file is modified from
# https://github.com/huggingface/transformers/blob/main/src/transformers/training_args.py
import contextlib
import json
import math
import os
import sys
import types
import warnings
from dataclasses import asdict, dataclass, field
from enum import Enum
from typing import Any, Dict, List, Optional
import paddle
import paddle.distributed as dist
from paddle.distributed import fleet
from ..utils.log import logger
from .trainer_utils import (
IntervalStrategy,
OptimizerNames,
SchedulerType,
ShardingOption,
split_parallel_config,
)
try:
from paddle.distributed import in_auto_parallel_align_mode
except Exception:
def in_auto_parallel_align_mode():
"""
hack for paddlenlp develop branch.
"""
return False
__all__ = [
"default_logdir",
"TrainingArguments",
]
def default_logdir() -> str:
"""
Same default
"""
import socket
from datetime import datetime
current_time = datetime.now().strftime("%b%d_%H-%M-%S")
return os.path.join("runs", current_time + "_" + socket.gethostname())
@dataclass
class TrainingArguments:
"""
TrainingArguments is the subset of the arguments we use in our example scripts **which relate to the training loop
itself**.
Using [`PdArgumentParser`] we can turn this class into
[argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the
command line.
Parameters:
output_dir (`str`):
The output directory where the model predictions and checkpoints will be written.
overwrite_output_dir (`bool`, *optional*, defaults to `False`):
If `True`, overwrite the content of the output directory. Use this to continue training if `output_dir`
points to a checkpoint directory.
do_train (`bool`, *optional*, defaults to `False`):
Whether to run training or not. This argument is not directly used by [`Trainer`], it's intended to be used
by your training/evaluation scripts instead. See the [example
scripts](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/examples) for more details.
do_eval (`bool`, *optional*):
Whether to run evaluation on the validation set or not. Will be set to `True` if `evaluation_strategy` is
different from `"no"`. This argument is not directly used by [`Trainer`], it's intended to be used by your
training/evaluation scripts instead. See the [example
scripts](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/examples) for more details.
do_predict (`bool`, *optional*, defaults to `False`):
Whether to run predictions on the test set or not. This argument is not directly used by [`Trainer`], it's
intended to be used by your training/evaluation scripts instead. See the [example
scripts](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/examples) for more details.
do_export (`bool`, *optional*, defaults to `False`):
Whether to export inference model or not. This argument is not directly used by [`Trainer`], it's
intended to be used by your training/evaluation scripts instead.
evaluation_strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"no"`):
The evaluation strategy to adopt during training. Possible values are:
- `"no"`: No evaluation is done during training.
- `"steps"`: Evaluation is done (and logged) every `eval_steps`.
- `"epoch"`: Evaluation is done at the end of each epoch.
prediction_loss_only (`bool`, *optional*, defaults to `False`):
When performing evaluation and generating predictions, only returns the loss.
per_device_train_batch_size (`int`, *optional*, defaults to 8):
The batch size per GPU core/CPU for training.
per_device_eval_batch_size (`int`, *optional*, defaults to 8):
The batch size per GPU core/CPU for evaluation.
gradient_accumulation_steps (`int`, *optional*, defaults to 1):
Number of updates steps to accumulate the gradients for, before performing a backward/update pass.
<Tip warning={true}>
When using gradient accumulation, one step is counted as one step with backward pass. Therefore, logging,
evaluation, save will be conducted every `gradient_accumulation_steps * xxx_step` training examples.
</Tip>
eval_accumulation_steps (`int`, *optional*):
Number of predictions steps to accumulate the output tensors for, before moving the results to the CPU. If
left unset, the whole predictions are accumulated on GPU/TPU before being moved to the CPU (faster but
requires more memory).
learning_rate (`float`, *optional*, defaults to 5e-5):
The initial learning rate for [`AdamW`] optimizer.
weight_decay (`float`, *optional*, defaults to 0):
The weight decay to apply (if not zero) to all layers except all bias and LayerNorm weights in [`AdamW`]
optimizer.
adam_beta1 (`float`, *optional*, defaults to 0.9):
The beta1 hyperparameter for the [`AdamW`] optimizer.
adam_beta2 (`float`, *optional*, defaults to 0.999):
The beta2 hyperparameter for the [`AdamW`] optimizer.
adam_epsilon (`float`, *optional*, defaults to 1e-8):
The epsilon hyperparameter for the [`AdamW`] optimizer.
max_grad_norm (`float`, *optional*, defaults to 1.0):
Maximum gradient norm (for gradient clipping).
num_train_epochs(`float`, *optional*, defaults to 1.0):
Total number of training epochs to perform (if not an integer, will perform the decimal part percents of
the last epoch before stopping training).
max_steps (`int`, *optional*, defaults to -1):
If set to a positive number, the total number of training steps to perform. Overrides `num_train_epochs`.
In case of using a finite iterable dataset the training may stop before reaching the set number of steps
when all data is exhausted
lr_scheduler_type (`str` or [`SchedulerType`], *optional*, defaults to `"linear"`):
The scheduler type to use. See the documentation of [`SchedulerType`] for all possible values.
warmup_ratio (`float`, *optional*, defaults to 0.0):
Ratio of total training steps used for a linear warmup from 0 to `learning_rate`.
warmup_steps (`int`, *optional*, defaults to 0):
Number of steps used for a linear warmup from 0 to `learning_rate`. Overrides any effect of `warmup_ratio`.
num_cycles (`float`, *optional*, defaults to 0.5):
The number of waves in the cosine scheduler.
lr_end (`float`, *optional*, defaults to 1e-7):
The end LR used in the polynomial scheduler.
power (`float`, *optional*, defaults to 1.0):
The power factor used in the polynomial scheduler.
log_on_each_node (`bool`, *optional*, defaults to `True`):
In multinode distributed training, whether to log using `log_level` once per node, or only on the main
node.
logging_dir (`str`, *optional*):
log directory. Will default to *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***.
logging_strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"steps"`):
The logging strategy to adopt during training. Possible values are:
- `"no"`: No logging is done during training.
- `"epoch"`: Logging is done at the end of each epoch.
- `"steps"`: Logging is done every `logging_steps`.
logging_first_step (`bool`, *optional*, defaults to `False`):
Whether to log and evaluate the first `global_step` or not.
logging_steps (`int`, *optional*, defaults to 500):
Number of update steps between two logs if `logging_strategy="steps"`.
save_strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"steps"`):
The checkpoint save strategy to adopt during training. Possible values are:
- `"no"`: No save is done during training.
- `"epoch"`: Save is done at the end of each epoch.
- `"steps"`: Save is done every `save_steps`.
save_steps (`int`, *optional*, defaults to 500):
Number of updates steps before two checkpoint saves if `save_strategy="steps"`.
save_total_limit (`int`, *optional*):
If a value is passed, will limit the total amount of checkpoints. Deletes the older checkpoints in
`output_dir`.
save_on_each_node (`bool`, *optional*, defaults to `False`):
When doing multi-node distributed training, whether to save models and checkpoints on each node, or only on
the main one.
This should not be activated when the different nodes use the same storage as the files will be saved with
the same names for each node.
no_cuda (`bool`, *optional*, defaults to `False`):
Whether to not use CUDA even when it is available or not.
seed (`int`, *optional*, defaults to 42):
Random seed that will be set at the beginning of training. To ensure reproducibility across runs, use the
[`~Trainer.model_init`] function to instantiate the model if it has some randomly initialized parameters.
fp16 (`bool`, *optional*, defaults to `False`):
Whether to use fp16 16-bit (mixed) precision training instead of 32-bit training.
fp16_opt_level (`str`, *optional*, defaults to 'O1'):
For `fp16` training, AMP optimization level selected in ['O0', 'O1', 'O2']. See details at
https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/api/paddle/amp/auto_cast_cn.html
amp_custom_black_list (`List[str]`, *optional*, defaults to `None`):
The custom black_list. The set of ops that support fp16/bf16 calculation and are considered numerically-dangerous
and whose effects may also be observed in downstream ops. These ops will not be converted to fp16/bf16.
amp_custom_white_list (`List[str]`, *optional*, defaults to `None`):
The custom white_list. It’s the set of ops that support fp16/bf16 calculation and are considered numerically-safe and
performance-critical. These ops will be converted to fp16/bf16.
amp_master_grad (`bool`, *optional*, defaults to `False`):
For amp opt level=’O2’, whether to use float32 weight gradients
for calculations such as gradient clipping, weight decay, and weight updates. If master_grad is enabled,
the weight gradients will be float32 dtype after the backpropagation. Default is False, there is only float16 weight gradients.
Note: only support model parallel and pipeline parallel for now !!!
sharding (`str`, *optional*, defaults to ``):
Whether or not to use Paddle Sharding Data Parallel training (in distributed training
only). The base option should be `stage1`, `stage2` or `stage3` and you can add
CPU-offload to `stage2` or `stage3` like this: `stage2 offload` or `stage3 offload`.
Each stage means:
stage1 : optimizer state segmentation
stage2 : optimizer state + gradient segmentation
stage3 : parameter + gradient + optimizer state segmentation
offload : offload parameters to cpu
sharding_parallel_degree (`int`, *optional*, defaults to `-1`)
Sharding parameter in certain cards group. For example, aussume we use 2 machines each with 8 cards,
then set sharding_parallel_degree=8, sharding will only communication inside machine.
default -1 means sharding parameters between all workers.
sharding_parallel_mesh_dimension (`str`, *optional*, defaults to `dp`)
Specifies the name of the dimension in a multi-dimensional parallelism mesh that is responsible for sharding.
default `dp` for default parallelism mesh.
tensor_parallel_degree (`int`, *optional*, defaults to `-1`)
Tensor parallelism is parallel technique proposed in (https://arxiv.org/pdf/2104.04473.pdf see 2.3 Tensor Model Parallelism).
This technique splits one transformer layer into multi-cards (For examples, tensor_parallel_degree=4, will split a layer to 4-parts)
tensor_parallel_degree means split the transformer layer to how many parts.
default -1 for not use tensor parallel, Suggest tensor_parallel_degree<=8 for better proformance.
Note, this need model support in source code, currently GPT/BLOOM/LLAMA/BLOOM/CLM/CHATGLM is supported.
pipeline_parallel_degree (`int`, *optional*, defaults to `-1`)
Pipeline parallelism is parallel technique proposed in (https://arxiv.org/pdf/2104.04473.pdf see 2.2 Pipeline Model Parallelism).
Pipeline parallelism assigns multi-transformer layers to different cards, the micro batch data stream passed between cards like pipelines.
pipeline_parallel_degree means split all transformer layers to how many stages.
default -1 for not use pipeline parallel.
Note. this need model support in source code, see llama modeling_pp.py file
sep_parallel_degree (`int`, *optional*, defaults to `-1`)(
The paddle sequence parallel strategy. It can reduce the GPU memory of activation to 1/sep, and it is orthogonal to
data parallel, sharding stage1, tensor parallel and pipeline parallel strategy.
)
context_parallel_degree (`int`, *optional*, defaults to `-1`)(
Context parallelism is a parallel method that segments training data in the sequence dimension.
This method uses Ring FlashAttention to ensure the correctness of the Attention result after segmentation. The complete attention score is obtained through ring communication and iterative updates.
)
data_parallel_config (`str`, *optional*)(
Some additional configs which affect data parallel performance, we provide some option to config it.
following config is support:
enable_allreduce_avg_in_gradinent_scale, it replace `allreduce_sum + scale` pattern with `allreduce_avg` when scale gradient in data_parallel, which improve the performance. ONLY supported for auto mode now.
gradient_sync_after_accumulate, move gradient sync operations from backward into optimizer step when gradient accumulate enabling, which reduce the sync times to improve performance, but will increase the memory usage. ONLY supported for auto mode now.
tensor_parallel_config (`str`, *optional*)(
Some additional configs which affect model parallel performance, we provide some option to config it.
following config is support:
enable_mp_async_allreduce, it supports all_reduce(dx) overlap with matmul(dw) in ColumnParallelLinear backward when it set True, which can accelerate model parallel performance.
enable_mp_skip_c_identity, it supports skip c_identity in ColumnParallelLinear and RowParallelLinear. It only works when set mp_async_allreduce is True. It can accelerate model parallel further.
enable_mp_fused_linear_param_grad_add, it supports fused_linear_param_grad_add in ColumnParallelLinear (cuda >= 11.6). It only works when mp_async_allreduce is true. It can accelerate model parallel further.
enable_sp_async_reduce_scatter, it supports async reduce_scatter in ColumnSequenceParallelLinear. It only works when set sp_async_reduce_scatter is True. It can accelerate sequence parallel further.
enable_delay_scale_loss, accumulate gradients until optimizer step, all gradients div by accumute step. instead of div accumute step on loss directly.
sync_param, in optimizer step, use broadcast to sync parameters those attr 'is_distributed' is False.
sync_grad, in optimizer step, use broadcast to sync gradients those attr 'is_distributed' is False.
sync_moment, in optimizer step, use broadcast to sync momentums those attr 'is_distributed' is False.
pipeline_parallel_config (`str`, *optional*)(
Some additional config it highly affect the useage of pipeline parallel, we provide some option to config it.
following config is support:
disable_p2p_cache_shape, if you max sequence length is varying, please set disable_p2p_cache_shape.
disable_partial_send_recv, optmize send speed for tensor parallel.
enable_delay_scale_loss, accumulate gradients until optimizer step, all gradients div by inner pipeline accumute step. instead of div accumute step on loss directly.
enable_dp_comm_overlap, fuse data parallel gradient communication.
enable_sharding_comm_overlap, fuse sharding stage 1 parallel gradient communication.
enable_release_grads, reduce peak memory usage by releasing gradients after each iteration. The creation of gradients will be postponed until backward propagation of the next iteration.
enable_overlap_p2p_comm, overlap p2p communication with computation.
enable_clear_every_step_cache, clear every step cache for pipeline parallel.
disable_non_batch_p2p_comm, disable batched send/recv in pipeline parallel mode.
sharding_parallel_config (`str`, *optional*)(
Some additional config it highly affect the useage of sharding parallel, we provide some option to config it.
following config is support:
enable_stage1_tensor_fusion, fuse small tensors into big tensor chunks to accelerate communications, may increase memory occupation
enable_stage1_overlap, fuse small tensors into big tensor chunks to accelerate communications and do communication overlap with backward computation, may harm the backward speed
enable_stage2_overlap, overlap stage2 NCCL communication with computation. There are some constraints for the overlap, such as the logging_step should be bigger than 1 for broadcast overlap and no other sync could be called during the training for broadcast overlap.
enable_stage1_broadcast_overlap, overlap stage1 V1 broadcast with next step forward computation. There are some constraints for the overlap, such as the logging_step should be bigger than 1 for broadcast overlap forward compute and no other sync could be called during the training for broadcast overlap.
enable_stage1_allgather_overlap, overlap stage1 V2 allgather with next step forward computation. There are some constraints for the overlap, such as the logging_step should be bigger than 1 for allgather overlap forward compute and no other sync could be called during the training for allgather overlap.
disable_stage1_reduce_avg, replace reduce_avg with original reduce_sum+scale in stage1, which can be used for accuracy verification.
enable_release_grads, reduce peak memory usage by releasing gradients after each iteration. The creation of gradients will be postponed until backward propagation of the next iteration.
recompute (`bool`, *optional*, defaults to `False`):
Recompute the forward pass to calculate gradients. Used for saving memory.
Only support for networks with transformer blocks.
scale_loss (`float`, *optional*, defaults to 32768):
The value of initial scale_loss for fp16. (default: 32768)
local_rank (`int`, *optional*, defaults to -1):
Rank of the process during distributed training.
dataloader_drop_last (`bool`, *optional*, defaults to `False`):
Whether to drop the last incomplete batch (if the length of the dataset is not divisible by the batch size)
or not.
eval_steps (`int`, *optional*):
Number of update steps between two evaluations if `evaluation_strategy="steps"`. Will default to the same
value as `logging_steps` if not set.
max_evaluate_steps (`int`, *optional*, defaults to -1):
If set to a positive number, the total number of evaluation steps to perform.
dataloader_num_workers (`int`, *optional*, defaults to 0):
Number of subprocesses to use for data loading. 0 means that the data will be loaded in the
main process.
past_index (`int`, *optional*, defaults to -1):
Some models like TransformerXL or XLNet can make use of the past hidden states for their predictions.
If this argument is set to a positive int, the `Trainer` will use the corresponding output (usually index 2) as
the past state and feed it to the model at the next training step under the keyword argument `mems`.
run_name (`str`, *optional*):
A descriptor for the run. Typically used for logging.
disable_tqdm (`bool`, *optional*):
Whether or not to disable the tqdm progress bars and table of metrics. Will default to `True` if the logging
level is set to warn or lower (default), `False` otherwise.
remove_unused_columns (`bool`, *optional*, defaults to `True`):
If using `datasets.Dataset` datasets, whether or not to automatically remove the columns unused by the
model forward method.
label_names (`List[str]`, *optional*):
The list of keys in your dictionary of inputs that correspond to the labels.
Will eventually default to `["labels"]` except if the model used is one of the `XxxForQuestionAnswering` in
which case it will default to `["start_positions", "end_positions"]`.
load_best_model_at_end (`bool`, *optional*, defaults to `False`):
Whether or not to load the best model found during training at the end of training.
<Tip>
When set to `True`, the parameters `save_strategy` needs to be the same as `eval_strategy`, and in the case
it is "steps", `save_steps` must be a round multiple of `eval_steps`.
</Tip>
metric_for_best_model (`str`, *optional*):
Use in conjunction with `load_best_model_at_end` to specify the metric to use to compare two different
models. Must be the name of a metric returned by the evaluation with or without the prefix `"eval_"`. Will
default to `"loss"` if unspecified and `load_best_model_at_end=True` (to use the evaluation loss).
If you set this value, `greater_is_better` will default to `True`. Don't forget to set it to `False` if
your metric is better when lower.
greater_is_better (`bool`, *optional*):
Use in conjunction with `load_best_model_at_end` and `metric_for_best_model` to specify if better models
should have a greater metric or not. Will default to:
- `True` if `metric_for_best_model` is set to a value that isn't `"loss"` or `"eval_loss"`.
- `False` if `metric_for_best_model` is not set, or set to `"loss"` or `"eval_loss"`.
ignore_data_skip (`bool`, *optional*, defaults to `False`):
When resuming training, whether or not to skip the epochs and batches to get the data loading at the same
stage as in the previous training. If set to `True`, the training will begin faster (as that skipping step
can take a long time) but will not yield the same results as the interrupted training would have.
optim (`str` or [`training_args.OptimizerNames`], *optional*, defaults to `"adamw"`):
The optimizer to use: adamw, or adafactor.
length_column_name (`str`, *optional*, defaults to `"length"`):
Column name for precomputed lengths. If the column exists, grouping by length will use these values rather
than computing them on train startup. Ignored unless `group_by_length` is `True` and the dataset is an
instance of `Dataset`.
report_to (`str` or `List[str]`, *optional*, defaults to `"visualdl"`):
The list of integrations to report the results and logs to.
Supported platforms are `"visualdl"`/`"wandb"`/`"tensorboard"`.
`"none"` for no integrations.
ddp_find_unused_parameters (`bool`, *optional*):
When using distributed training, the value of the flag `find_unused_parameters` passed to
`paddle.DataParallel`. Will default to `False` if recompute is used, `True` otherwise.
wandb_api_key (`str`, *optional*):
Weights & Biases (WandB) API key(s) for authentication with the WandB service.
resume_from_checkpoint (`str`, *optional*):
The path to a folder with a valid checkpoint for your model. This argument is not directly used by
[`Trainer`], it's intended to be used by your training/evaluation scripts instead. See the [example
scripts](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/examples) for more details.
auto_parallel_resume_form_hybrid_parallel (`bool`, *optional*):
Wether hybrid paralle checkpoints be loaded in auto parallel mode.
flatten_param_grads (`bool`, *optional*):
Whether use flatten_param_grads method in optimizer, only used on NPU devices. Default is `False`.
skip_profile_timer (`bool`, *optional*):
Whether skip profile timer, timer will record time usage of forward/ backward/ step, etc.
distributed_dataloader (`bool`, *optional*):
Whether to use distributed dataloader. Default is `False`.
release_grads (`bool`, *optional*):
Whether to release gradients during training. Default is `False`.
"""
output_dir: str = field(
metadata={"help": "The output directory where the model predictions and checkpoints will be written."},
)
overwrite_output_dir: bool = field(
default=False,
metadata={
"help": (
"Overwrite the content of the output directory. "
"Use this to continue training if output_dir points to a checkpoint directory."
)
},
)
do_train: bool = field(default=False, metadata={"help": "Whether to run training."})
do_eval: bool = field(default=False, metadata={"help": "Whether to run eval on the dev set."})
do_predict: bool = field(default=False, metadata={"help": "Whether to run predictions on the test set."})
do_export: bool = field(default=False, metadata={"help": "Whether to export infernece model."})
evaluation_strategy: IntervalStrategy = field(
default="no",
metadata={"help": "The evaluation strategy to use."},
)
prediction_loss_only: bool = field(
default=False,
metadata={"help": "When performing evaluation and predictions, only returns the loss."},
)
per_device_train_batch_size: int = field(default=8, metadata={"help": "Batch size per GPU core/CPU for training."})
per_device_eval_batch_size: int = field(
default=8, metadata={"help": "Batch size per GPU core/CPU for evaluation."}
)
gradient_accumulation_steps: int = field(
default=1,
metadata={"help": "Number of updates steps to accumulate before performing a backward/update pass."},
)
eval_accumulation_steps: Optional[int] = field(
default=None,
metadata={"help": "Number of predictions steps to accumulate before moving the tensors to the CPU."},
)
learning_rate: float = field(default=5e-5, metadata={"help": "The initial learning rate for AdamW."})
weight_decay: float = field(default=0.0, metadata={"help": "Weight decay for AdamW if we apply some."})
adam_beta1: float = field(default=0.9, metadata={"help": "Beta1 for AdamW optimizer"})
adam_beta2: float = field(default=0.999, metadata={"help": "Beta2 for AdamW optimizer"})
adam_epsilon: float = field(default=1e-8, metadata={"help": "Epsilon for AdamW optimizer."})
max_grad_norm: float = field(default=1.0, metadata={"help": "Max gradient norm."})
num_train_epochs: float = field(default=1.0, metadata={"help": "Total number of training epochs to perform."})
max_steps: int = field(
default=-1,
metadata={"help": "If > 0: set total number of training steps to perform. Override num_train_epochs."},
)
lr_scheduler_type: str = field(
default="linear",
metadata={"help": "The scheduler type to use. suppor linear, cosine, constant, constant_with_warmup"},
)
warmup_ratio: float = field(
default=0.0, metadata={"help": "Linear warmup over warmup_ratio fraction of total steps."}
)
warmup_steps: int = field(default=0, metadata={"help": "Linear warmup over warmup_steps."})
num_cycles: float = field(default=0.5, metadata={"help": "The number of waves in the cosine scheduler."})
lr_end: float = field(default=1e-7, metadata={"help": "The end LR in the polynomial scheduler."})
power: float = field(default=1.0, metadata={"help": "The power factor in the polynomial scheduler."})
log_on_each_node: bool = field(
default=True,
metadata={
"help": "When doing a multinode distributed training, whether to log once per node or just once on the main node."
},
)
logging_dir: Optional[str] = field(default=None, metadata={"help": "VisualDL log dir."})
output_signal_dir: Optional[str] = field(default=None, metadata={"help": "Asynchronous saving signal dir."})
logging_strategy: IntervalStrategy = field(
default="steps",
metadata={"help": "The logging strategy to use."},
)
logging_first_step: bool = field(default=False, metadata={"help": "Log the first global_step"})
logging_steps: int = field(default=500, metadata={"help": "Log every X updates steps."})
save_strategy: IntervalStrategy = field(
default="steps",
metadata={"help": "The checkpoint save strategy to use."},
)
save_steps: int = field(default=500, metadata={"help": "Save checkpoint every X updates steps."})
save_total_limit: Optional[int] = field(
default=None,
metadata={
"help": (
"Limit the total amount of checkpoints. "
"Deletes the older checkpoints in the output_dir. Default is unlimited checkpoints"
)
},
)
save_on_each_node: bool = field(
default=False,
metadata={
"help": "When doing multi-node distributed training, whether to save models and checkpoints on each node, or only on the main one"
},
)
no_cuda: bool = field(default=False, metadata={"help": "Do not use CUDA even when it is available"})
seed: int = field(default=42, metadata={"help": "Random seed that will be set at the beginning of training."})
bf16: bool = field(
default=False,
metadata={
"help": (
"Whether to use bf16 (mixed) precision instead of 32-bit. Requires Ampere or higher NVIDIA"
" architecture or using CPU (no_cuda). This is an experimental API and it may change."
)
},
)
fp16: bool = field(
default=False,
metadata={"help": "Whether to use fp16 (mixed) precision instead of 32-bit"},
)
fp16_opt_level: str = field(
default="O1",
metadata={
"help": (
"For fp16: AMP optimization level selected in ['O0', 'O1', and 'O2']. "
"See details at https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/api/paddle/amp/auto_cast_cn.html"
)
},
)
amp_master_grad: bool = field(
default=False,
metadata={
"help": "amp_master_grad (bool, optional) – For amp opt level=’O2’, whether to use float32 weight gradients "
" for calculations such as gradient clipping, weight decay, and weight updates. If master_grad is enabled,"
" the weight gradients will be float32 dtype after the backpropagation. Default is False, there is only float16 weight gradients."
"Note: only support model parallel and pipeline parallel for now !!!"
},
)
bf16_full_eval: bool = field(
default=False,
metadata={
"help": (
"Whether to use full bfloat16 evaluation instead of 32-bit. This is an experimental API and it may"
" change."
)
},
)
fp16_full_eval: bool = field(
default=False,
metadata={"help": "Whether to use full float16 evaluation instead of 32-bit"},
)
amp_custom_black_list: Optional[List[str]] = field(
default=None,
metadata={
"help": "The set of ops that support fp16/bf16 calculation and are considered numerically-dangerous and whose effects may also be observed in downstream ops."
},
)
amp_custom_white_list: Optional[List[str]] = field(
default=None,
metadata={
"help": "The the set of ops that support fp16/bf16 calculation and are considered numerically-safe and performance-critical. These ops will be converted to fp16/bf16."
},
)
sharding: str = field(
default="",
metadata={
"help": (
"Whether or not to use Paddle Sharding Data Parallel training (in distributed training"
" only). The base option should be `stage1`, `stage2` or `stage3` and you can add"
" CPU-offload to `stage2` or `stage3` like this: stage2 offload` or `stage3"
" offload`. "
)
},
)
sharding_degree: int = field( # Alias for sharding_parallel_degree
default=-1,
metadata={"help": ("@deprecated Please use sharding_parallel_degree. ")},
)
sharding_parallel_degree: int = field(
default=-1,
metadata={
"help": (
"Sharding parameter in certain cards group. For example, aussume we use 2 machines each with 8 cards, "
"then set sharding_degree=8, sharding will only communication inside machine. "
"default -1 means sharding parameters between all workers."
)
},
)
sharding_parallel_mesh_dimension: str = field(
default="dp",
metadata={
"help": (
"Specifies the name of the dimension in a multi-dimensional parallelism mesh that is responsible for sharding. "
"default `dp` for default parallelism mesh. "
)
},
)
sharding_comm_buffer_size_MB: int = field(
default=-1,
metadata={
"help": (
"Set the size of the fuse gradient in sharding communication. This option only takes effect when "
"the sharding option is turned on.The default value is -1, which means that the gradient size of "
"all communication fuses follows the default configuration, which is 256MB. "
)
},
)
save_sharded_model: bool = field(
default=False,
metadata={
"help": (
"When use sharding stage1 and set save_sharded_model True, each shanding rank only save part of the model. It reduce time to save the model."
)
},
)
load_sharded_model: bool = field(
default=False,
metadata={
"help": (
"When use sharding stage1 and set load_sharded_model True, it means loading the sharded model. The sharded model is saved when we set save_sharded_model True."
)
},
)
tensor_parallel_degree: int = field(
default=-1,
metadata={
"help": (
"Tensor parallelism is parallel technique proposed in (https://arxiv.org/pdf/2104.04473.pdf see 2.3 Tensor Model Parallelism). "
"This techique splits one transformer layer into multi-cards (For examples, tensor_parallel_degree=4, will split a layer to 4-parts) "
"tensor_parallel_degree means split the transformer layer to how many parts."
"default -1 for not use tensor parallel, Suggest tensor_parallel_degree<=8 for better proformance."
"Note, this need model support in source code, currently GPT/BLOOM/LLAMA/BLOOM/CLM/CHATGLM is supported. "
)
},
)
pipeline_parallel_degree: int = field(
default=-1,
metadata={
"help": (
"Pipeline parallelism is parallel technique proposed in (https://arxiv.org/pdf/2104.04473.pdf see 2.2 Pipeline Model Parallelism). "
"Pipeline parallelism assigns multi-transformer layers to different cards, the micro batch data stream passed between cards like pipelines."
"pipeline_parallel_degree means split all transformer layers to how many stages."
"default -1 for not use pipeline parallel."
"Note. this need model support in source code, see llama modeling_pp.py file"
)
},
)
sep_parallel_degree: int = field(
default=-1,
metadata={
"help": (
"The paddle sequence parallel strategy. It can reduce the GPU memory of activation to 1/sep, and it is orthogonal to "
"data parallel, sharding stage1, tensor parallel and pipeline parallel strategy. "
)
},
)
context_parallel_degree: int = field(
default=-1,
metadata={
"help": (
"The paddle context parallel strategy. It can reduce the GPU memory of activation to 1/cp, and it is orthogonal to "
"data parallel, sharding stage1, tensor parallel and pipeline parallel strategy. "
)
},
)
data_parallel_config: str = field(
default="",
metadata={
"help": (
"Some additional configs which affect data parallel performance, we provide some option to config it."
"following config is support:\n"
"enable_allreduce_avg_in_gradinent_scale, it replace `allreduce_sum + scale` pattern with `allreduce_avg` when scale gradient in data_parallel, which improve the performance. ONLY supported for auto mode now. \n"
"gradient_sync_after_accumulate, move gradient sync operations from backward into optimizer step when gradient accumulate enabling, which reduce the sync times to improve performance, but will increase the memory usage. ONLY supported for auto mode now. \n"
)
},
)
sequence_parallel_config: str = field(
default="",
metadata={
"help": (
"Some additional configs which affect sequence parallel performance, we provide some option to config it."
"following config is support:\n"
"enable_allreduce_avg_in_gradinent_scale, it replace `allreduce_sum + scale` pattern with `allreduce_avg` when scale gradient in sequence_parallel, which improve the performance. ONLY supported for auto mode now. \n"
)
},
)
tensor_parallel_config: str = field(
default="",
metadata={
"help": (
"Some additional configs which affect model parallel performance, we provide some option to config it."
"following config is support:\n"
"enable_mp_async_allreduce, it supports all_reduce(dx) overlap with matmul(dw) in ColumnParallelLinear backward when it set True, which can accelerate model parallel performance. \n"
"enable_mp_skip_c_identity, it supports skip c_identity in ColumnParallelLinear and RowParallelLinear. It only works when set mp_async_allreduce is True. It can accelerate model parallel further.\n"
"enable_mp_fused_linear_param_grad_add, it supports fused_linear_param_grad_add in ColumnParallelLinear (cuda >= 11.6). It only works when mp_async_allreduce is true. It can accelerate model parallel further.\n"
"enable_sp_async_reduce_scatter, it supports async reduce_scatter in ColumnSequenceParallelLinear. It only works when set sp_async_reduce_scatter is True. It can accelerate sequence parallel further.\n"
"enable_delay_scale_loss, accumulate gradients until optimizer step, all gradients div by accumute step. instead of div accumute step on loss directly.\n"
"sync_param, in optimizer step, use broadcast to sync parameters those attr 'is_distributed' is False.\n"
"sync_grad, in optimizer step, use broadcast to sync gradients those attr 'is_distributed' is False.\n"
"sync_moment, in optimizer step, use broadcast to sync momentums those attr 'is_distributed' is False.\n"
)
},
)
pipeline_parallel_config: str = field(
default="",
metadata={
"help": (
"Some additional config it highly affect the useage of pipeline parallel, we provide some option to config it."
"following config is support:\n"
"disable_p2p_cache_shape, if you max sequence length is varying, please set disable_p2p_cache_shape. \n"
"disable_partial_send_recv, optmize send speed for tensor parallel.\n"
"enable_delay_scale_loss, accumulate gradients until optimizer step, all gradients div by inner pipeline accumute step. instead of div accumute step on loss directly.\n"
"enable_dp_comm_overlap, fuse data parallel gradient communication. \n"
"enable_sharding_comm_overlap, fuse sharding stage 1 parallel gradient communication. \n"
"enable_overlap_p2p_comm, overlap p2p communication with computation. \n"
"enable_clear_every_step_cache, clear every step cache for pipeline parallel. \n"
"disable_batch_p2p_comm, disable batched send/recv in pipeline parallel mode. \n"
"enable_split_backward, only can be used in StaticGraph-AutoParallel! split the `backward` program into `backward_b` and `backward_w` to decrease the bubble in VPP pipeline mode when `acc_step == pp_degree`. it increase the memory! \n"
)
},
)
sharding_parallel_config: str = field(
default="",
metadata={
"help": (
"Some additional config it highly affect the useage of sharding parallel, we provide some option to config it."
"following config is support: \n"
"enable_stage1_tensor_fusion, fuse small tensors into big tensor chunks to accelerate communications, may increase memory occupation\n"
"enable_stage1_overlap, fuse small tensors into big tensor chunks to accelerate communications and do communication overlap with backward computation, may harm the backward speed\n"
"disable_stage1_reduce_avg, replace reduce_avg with original reduce_sum+scale in stage1, which can be used for accuracy verification.\n"
"enable_stage2_overlap, overlap stage2 NCCL communication with computation. There are some constraints for the overlap, such as the logging_step should be bigger than 1 for broadcast overlap and no other sync could be called during the training for broadcast overlap\n"
"enable_stage1_broadcast_overlap, overlap stage1 V1 broadcast with next step forward computation. There are some constraints for the overlap, such as the logging_step should be bigger than 1 for broadcast overlap forward compute and no other sync could be called during the training for broadcast overlap.\n"
"enable_stage1_allgather_overlap, overlap stage1 V2 allgather with next step forward computation. There are some constraints for the overlap, such as the logging_step should be bigger than 1 for allgather overlap forward compute and no other sync could be called during the training for allgather overlap."
)
},
)
hybrid_parallel_topo_order: str = field(
default=None,
metadata={
"help": (
"In hybrid parallelism, the order of communication groups may affect efficiency.\n"
"Following options are supported:\n"
"- pp_first. the topo order is dp, pp, sharding, mp \n"
"- sharding_first. the topo order is dp, sharding, pp, mp \n"
"Defalut is None, for pp_first"
)
},
)
recompute: bool = field(
default=False,
metadata={
"help": "Recompute the forward pass to calculate gradients. Used for saving memory. "
"Only support for networks with transformer blocks."
},
)
scale_loss: float = field(default=2**15, metadata={"help": "The value of initial scale_loss for fp16."})
minimum_eval_times: int = field(
default=None,
metadata={
"help": "If under eval_steps, the valid time is less then minimum_eval_times, the config of override eval_steps."
},
)
local_rank: int = field(default=-1, metadata={"help": "For distributed training: local_rank"})
dataloader_drop_last: bool = field(
default=False, metadata={"help": "Drop the last incomplete batch if it is not divisible by the batch size."}
)
eval_steps: int = field(default=None, metadata={"help": "Run an evaluation every X steps."})
max_evaluate_steps: int = field(
default=-1, metadata={"help": "If set to a positive number, the total number of evaluation steps to perform."}
)
dataloader_num_workers: int = field(
default=0,
metadata={
"help": "Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
},
)
past_index: int = field(
default=-1,
metadata={"help": "If >=0, uses the corresponding part of the output as the past state for next step."},
)
run_name: Optional[str] = field(default=None, metadata={"help": "An optional descriptor for the run."})
device: Optional[str] = field(default="gpu", metadata={"help": "select cpu, gpu, xpu, npu devices."})
disable_tqdm: Optional[bool] = field(
default=None, metadata={"help": "Whether or not to disable the tqdm progress bars."}
)
remove_unused_columns: Optional[bool] = field(
default=True, metadata={"help": "Remove columns not required by the model when using an nlp.Dataset."}
)
label_names: Optional[List[str]] = field(
default=None, metadata={"help": "The list of keys in your dictionary of inputs that correspond to the labels."}
)
load_best_model_at_end: Optional[bool] = field(
default=False,
metadata={"help": "Whether or not to load the best model found during training at the end of training."},
)
metric_for_best_model: Optional[str] = field(
default=None, metadata={"help": "The metric to use to compare two different models."}
)
greater_is_better: Optional[bool] = field(
default=None, metadata={"help": "Whether the `metric_for_best_model` should be maximized or not."}
)
ignore_data_skip: bool = field(
default=False,
metadata={
"help": "When resuming training, whether or not to skip the first epochs and batches to get to the same training data."
},
)
optim: str = field(
default="adamw",
metadata={"help": "The optimizer to use."},
)
report_to: Optional[List[str]] = field(
default=None, metadata={"help": "The list of integrations to report the results and logs to."}
)
ddp_find_unused_parameters: Optional[bool] = field(
default=None,
metadata={
"help": (
"When using distributed training, the value of the flag `find_unused_parameters` passed to "
"`DataParallel`."
)
},
)
wandb_api_key: Optional[str] = field(
default=None,
metadata={"help": "Weights & Biases (WandB) API key(s) for authentication with the WandB service."},
)
resume_from_checkpoint: Optional[str] = field(
default=None,
metadata={"help": "The path to a folder with a valid checkpoint for your model."},
)
auto_parallel_resume_form_hybrid_parallel: Optional[bool] = field(
default=False,
metadata={"help": "Wether hybrid paralle checkpoints be loaded in auto parallel mode."},
)
skip_memory_metrics: bool = field(
default=True, metadata={"help": "Whether or not to skip adding of memory profiler reports to metrics."}
)
flatten_param_grads: Optional[bool] = field(
default=False,
metadata={"help": "Whether use flatten_param_grads method in optimizer, only used on NPU devices."},
)
lazy_data_processing: Optional[bool] = field(
default=True,
metadata={"help": "Whether use lazy data processing."},
)
use_async_save: Optional[bool] = field(
default=False,
metadata={"help": "Whether to use async_save instead of paddle.save."},
)
ordered_save_group_size: int = field(
default=0,
metadata={
"help": "Select ordered_save_group_size to save checkpoint in ordered. if ordered_save_group_size=0, not used ordered save"
},
)
skip_profile_timer: Optional[bool] = field(
default=True,
metadata={"help": "enable framework timer, will output timeline informatoin in logging and visualdl."},
)
distributed_dataloader: Optional[bool] = field(
default=False, metadata={"help": "Whether to use distributed dataloader."}
)
unified_checkpoint: Optional[bool] = field(
default=False,
metadata={"help": "Whether to unify hybrid parallel checkpoint."},
)
to_static: Optional[bool] = field(
default=False,
metadata={"help": ("Whether to train model under static mode by jit.to_static or distributed.to_static.")},
)
unified_checkpoint_config: Optional[str] = field(
default="",
metadata={
"help": (
"Configs to unify hybrid parallel checkpoint.\n"
"Following options are supports:\n"
"- skip_save_model_weight: do not save model weights when the masters weight exist\n"
"- master_weight_compatible: 1. if the master weights exist, only load when needed\n"
" 2. if master weights does not exist, convert model weights to master weights when needed\n"
"- remove_master_weight: same with `master_weight_compatible`, use in checkpoint quantization.\n"
"- async_save: enable asynchronous saving checkpoints to disk\n"
"- enable_all_options: enable all optimization configurations\n"
)
},
)
ckpt_quant_stage: str = field(
default="O0",
metadata={"help": "checkpoint quantization stage."},
)
ignore_load_lr_and_optim: Optional[bool] = field(
default=False,
metadata={"help": "whether to ignore load optimizer and scheduler."},
)
ignore_save_lr_and_optim: Optional[bool] = field(
default=False,
metadata={"help": "whether to ignore save optimizer and scheduler."},
)
force_reshard_pp: Optional[bool] = field(
default=False,
metadata={"help": "reshard pp even if pp degree in the model and pp degree in script match"},
)
enable_auto_parallel: Optional[bool] = field(
default=False,
metadata={"help": "whether to run distributed training in auto parallel mode"},
)
use_expert_parallel: Optional[bool] = field(
default=False,
metadata={"help": "Enable MoE (Mixture of Experts) expert parallel training"},
)
expert_max_capacity: Optional[int] = field(
default=pow(2, 32),
metadata={"help": "Enable MoE (Mixture of Experts) expert max token capacity"},
)
expert_min_capacity: Optional[int] = field(
default=1,
metadata={"help": "Enable MoE (Mixture of Experts) expert min token capacity"},
)
release_grads: Optional[bool] = field(
default=False, metadata={"help": "Whether to release gradients during training. Default is `False`."}
)
skip_data_intervals: Optional[List[List[int]]] = field(
default=None,
metadata={"help": "The intervals to skip, pass start global step and end global step at each interval"},
)
offload_optim: Optional[bool] = field(
default=False,
metadata={"help": "Offload optimizer after optimizer.step()"},
)
def __post_init__(self):
if in_auto_parallel_align_mode():
self.max_grad_norm = 0.0
os.environ["FLAGS_max_inplace_grad_add"] = "65536"
os.environ["FLAGS_embedding_deterministic"] = "1"
os.environ["FLAGS_cudnn_deterministic"] = "1"
env_local_rank = int(os.environ.get("PADDLE_RANK_IN_NODE", -1))
if env_local_rank != -1 and env_local_rank != self.local_rank and paddle.distributed.get_world_size() > 1:
self.local_rank = env_local_rank
# NOTE(gongenlei): new add, disable sharding when we have only single gpu
if paddle.distributed.get_world_size() <= 1:
self.sharding = ""
self.sharding_degree = -1
self.sharding_parallel_degree = -1
self.tensor_parallel_degree = -1
self.pipeline_parallel_degree = -1
# convert to int
self.log_level = -1
self.log_level_replica = -1
# expand paths, if not os.makedirs("~/bar") will make directory
# in the current directory instead of the actual home
if self.output_dir is not None:
self.output_dir = os.path.expanduser(self.output_dir)
if self.logging_dir is None and self.output_dir is not None:
self.logging_dir = os.path.join(self.output_dir, default_logdir())
if self.logging_dir is not None:
self.logging_dir = os.path.expanduser(self.logging_dir)
if self.output_signal_dir is None and self.output_dir is not None:
self.output_signal_dir = self.output_dir
if self.output_signal_dir is not None:
self.output_signal_dir = os.path.expanduser(self.output_signal_dir)
if self.disable_tqdm is None:
self.disable_tqdm = False # logger.getEffectiveLevel() > logging.WARN
self.evaluation_strategy = IntervalStrategy(self.evaluation_strategy)
self.logging_strategy = IntervalStrategy(self.logging_strategy)
self.save_strategy = IntervalStrategy(self.save_strategy)
self.lr_scheduler_type = SchedulerType(self.lr_scheduler_type)
if self.do_eval is False and self.evaluation_strategy != IntervalStrategy.NO:
self.do_eval = True
if self.do_eval and self.evaluation_strategy == IntervalStrategy.NO:
logger.warning(
"evaluation_strategy reset to IntervalStrategy.STEPS for do_eval is True. you can also set evaluation_strategy='epoch'."
)
self.evaluation_strategy = IntervalStrategy.STEPS
# eval_steps has to be defined and non-zero, fallbacks to logging_steps if the latter is non-zero
if self.evaluation_strategy == IntervalStrategy.STEPS and (self.eval_steps is None or self.eval_steps == 0):
if self.logging_steps > 0:
logger.info(f"using `logging_steps` to initialize `eval_steps` to {self.logging_steps}")
self.eval_steps = self.logging_steps
else:
raise ValueError(
f"evaluation strategy {self.evaluation_strategy} requires either non-zero --eval_steps or --logging_steps"
)
# logging_steps must be non-zero for logging_strategy that is other than 'no'
if self.logging_strategy == IntervalStrategy.STEPS and self.logging_steps == 0:
raise ValueError(f"logging strategy {self.logging_strategy} requires non-zero --logging_steps")
# Sanity checks for load_best_model_at_end: we require save and eval strategies to be compatible.
if self.load_best_model_at_end:
if self.evaluation_strategy != self.save_strategy:
raise ValueError(
"--load_best_model_at_end requires the save and eval strategy to match, but found\n- Evaluation "
f"strategy: {self.evaluation_strategy}\n- Save strategy: {self.save_strategy}"
)
if self.evaluation_strategy == IntervalStrategy.STEPS and self.save_steps % self.eval_steps != 0:
raise ValueError(
"--load_best_model_at_end requires the saving steps to be a round multiple of the evaluation "
f"steps, but found {self.save_steps}, which is not a round multiple of {self.eval_steps}."