training_args.py 137 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829
  1. # Copyright 2020 The HuggingFace Team. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import contextlib
  15. import json
  16. import math
  17. import os
  18. import warnings
  19. from dataclasses import asdict, dataclass, field, fields
  20. from datetime import timedelta
  21. from enum import Enum
  22. from functools import cached_property
  23. from typing import Any
  24. from .debug_utils import DebugOption
  25. from .trainer_utils import (
  26. FSDPOption,
  27. HubStrategy,
  28. IntervalStrategy,
  29. SaveStrategy,
  30. SchedulerType,
  31. )
  32. from .utils import (
  33. ACCELERATE_MIN_VERSION,
  34. ExplicitEnum,
  35. is_accelerate_available,
  36. is_sagemaker_dp_enabled,
  37. is_sagemaker_mp_enabled,
  38. is_torch_available,
  39. is_torch_bf16_gpu_available,
  40. is_torch_cuda_available,
  41. is_torch_hpu_available,
  42. is_torch_mlu_available,
  43. is_torch_mps_available,
  44. is_torch_musa_available,
  45. is_torch_neuron_available,
  46. is_torch_neuroncore_available,
  47. is_torch_npu_available,
  48. is_torch_tf32_available,
  49. is_torch_xla_available,
  50. is_torch_xpu_available,
  51. logging,
  52. requires_backends,
  53. )
  54. from .utils.generic import strtobool
  55. from .utils.import_utils import enable_tf32, is_optimum_neuron_available
  56. logger = logging.get_logger(__name__)
  57. log_levels = logging.get_log_levels_dict().copy()
  58. trainer_log_levels = dict(**log_levels, passive=-1)
  59. if is_torch_available():
  60. import torch
  61. import torch.distributed as dist
  62. if is_accelerate_available():
  63. from accelerate.state import AcceleratorState, PartialState
  64. from accelerate.utils import DistributedType
  65. from .trainer_pt_utils import AcceleratorConfig
  66. if is_accelerate_available("1.10.1"):
  67. from accelerate.parallelism_config import ParallelismConfig
  68. else:
  69. ParallelismConfig = Any
  70. if is_torch_xla_available():
  71. import torch_xla.core.xla_model as xm
  72. if is_torch_neuroncore_available(check_device=False):
  73. # torchrun support
  74. # https://github.com/pytorch/xla/pull/3609
  75. if os.environ.get("TORCHELASTIC_RUN_ID"):
  76. if is_optimum_neuron_available():
  77. logger.info(
  78. "Make sure that you are performing the training with the NeuronTrainer from optimum[neuron], this "
  79. "will fail otherwise."
  80. )
  81. else:
  82. logger.warning(
  83. "Please use the NeuronTrainer from optimum[neuron] instead of the Transformers library to perform "
  84. "training on AWS Trainium instances. More information here: "
  85. "https://github.com/huggingface/optimum-neuron"
  86. )
  87. import torch_xla.distributed.xla_backend as xbn
  88. if not isinstance(dist.group.WORLD, xbn.ProcessGroupXla):
  89. dist.init_process_group(backend="xla")
  90. if not isinstance(dist.group.WORLD, xbn.ProcessGroupXla):
  91. raise AssertionError("Failed to initialize torch.distributed process group using XLA backend.")
  92. if is_sagemaker_mp_enabled():
  93. import smdistributed.modelparallel.torch as smp
  94. smp.init()
  95. class OptimizerNames(ExplicitEnum):
  96. """
  97. Stores the acceptable string identifiers for optimizers.
  98. """
  99. ADAMW_TORCH = "adamw_torch"
  100. ADAMW_TORCH_FUSED = "adamw_torch_fused"
  101. ADAMW_TORCH_XLA = "adamw_torch_xla"
  102. ADAMW_TORCH_NPU_FUSED = "adamw_torch_npu_fused"
  103. ADAMW_APEX_FUSED = "adamw_apex_fused"
  104. ADAFACTOR = "adafactor"
  105. ADAMW_ANYPRECISION = "adamw_anyprecision"
  106. ADAMW_TORCH_4BIT = "adamw_torch_4bit"
  107. ADAMW_TORCH_8BIT = "adamw_torch_8bit"
  108. ADEMAMIX = "ademamix"
  109. SGD = "sgd"
  110. ADAGRAD = "adagrad"
  111. ADAMW_BNB = "adamw_bnb_8bit"
  112. ADAMW_8BIT = "adamw_8bit" # just an alias for adamw_bnb_8bit
  113. ADEMAMIX_8BIT = "ademamix_8bit"
  114. LION_8BIT = "lion_8bit"
  115. LION = "lion_32bit"
  116. PAGED_ADAMW = "paged_adamw_32bit"
  117. PAGED_ADAMW_8BIT = "paged_adamw_8bit"
  118. PAGED_ADEMAMIX = "paged_ademamix_32bit"
  119. PAGED_ADEMAMIX_8BIT = "paged_ademamix_8bit"
  120. PAGED_LION = "paged_lion_32bit"
  121. PAGED_LION_8BIT = "paged_lion_8bit"
  122. RMSPROP = "rmsprop"
  123. RMSPROP_BNB = "rmsprop_bnb"
  124. RMSPROP_8BIT = "rmsprop_bnb_8bit"
  125. RMSPROP_32BIT = "rmsprop_bnb_32bit"
  126. GALORE_ADAMW = "galore_adamw"
  127. GALORE_ADAMW_8BIT = "galore_adamw_8bit"
  128. GALORE_ADAFACTOR = "galore_adafactor"
  129. GALORE_ADAMW_LAYERWISE = "galore_adamw_layerwise"
  130. GALORE_ADAMW_8BIT_LAYERWISE = "galore_adamw_8bit_layerwise"
  131. GALORE_ADAFACTOR_LAYERWISE = "galore_adafactor_layerwise"
  132. LOMO = "lomo"
  133. ADALOMO = "adalomo"
  134. GROKADAMW = "grokadamw"
  135. SCHEDULE_FREE_RADAM = "schedule_free_radam"
  136. SCHEDULE_FREE_ADAMW = "schedule_free_adamw"
  137. SCHEDULE_FREE_SGD = "schedule_free_sgd"
  138. APOLLO_ADAMW = "apollo_adamw"
  139. APOLLO_ADAMW_LAYERWISE = "apollo_adamw_layerwise"
  140. STABLE_ADAMW = "stable_adamw"
  141. def _convert_str_dict(passed_value: dict):
  142. "Safely checks that a passed value is a dictionary and converts any string values to their appropriate types."
  143. for key, value in passed_value.items():
  144. if isinstance(value, dict):
  145. passed_value[key] = _convert_str_dict(value)
  146. elif isinstance(value, str):
  147. # First check for bool and convert
  148. if value.lower() in ("true", "false"):
  149. passed_value[key] = value.lower() == "true"
  150. # Check for digit
  151. elif value.isdigit():
  152. passed_value[key] = int(value)
  153. elif value.replace(".", "", 1).isdigit():
  154. passed_value[key] = float(value)
  155. return passed_value
  156. @dataclass
  157. class TrainingArguments:
  158. """
  159. Configuration class for controlling all aspects of model training with the Trainer.
  160. TrainingArguments centralizes all hyperparameters, optimization settings, logging preferences, and infrastructure choices needed for training.
  161. [`HfArgumentParser`] can turn this class into
  162. [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the
  163. command line.
  164. Parameters:
  165. output_dir (`str`, *optional*, defaults to `"trainer_output"`):
  166. The output directory where the model predictions and checkpoints will be written.
  167. > Training Duration and Batch Size
  168. per_device_train_batch_size (`int`, *optional*, defaults to 8):
  169. The batch size *per device*. The **global batch size** is computed as:
  170. `per_device_train_batch_size * number_of_devices` in multi-GPU or distributed setups.
  171. num_train_epochs(`float`, *optional*, defaults to 3.0):
  172. Total number of training epochs to perform (if not an integer, will perform the decimal part percents of
  173. the last epoch before stopping training).
  174. max_steps (`int`, *optional*, defaults to -1):
  175. Overrides `num_train_epochs`. If set to a positive number, the total number of training steps to perform.
  176. For a finite dataset, training is reiterated through the dataset (if all data is exhausted) until
  177. `max_steps` is reached.
  178. > Learning Rate & Scheduler
  179. learning_rate (`float`, *optional*, defaults to 5e-5):
  180. The initial learning rate for the optimizer. This is typically the peak learning rate when using a scheduler with warmup.
  181. lr_scheduler_type (`str` or [`SchedulerType`], *optional*, defaults to `"linear"`):
  182. The learning rate scheduler type to use. See [`SchedulerType`] for all possible values. Common choices:
  183. - "linear" = [`get_linear_schedule_with_warmup`]
  184. - "cosine" = [`get_cosine_schedule_with_warmup`]
  185. - "constant" = [`get_constant_schedule`]
  186. - "constant_with_warmup" = [`get_constant_schedule_with_warmup`]
  187. lr_scheduler_kwargs (`dict` or `str`, *optional*, defaults to `None`):
  188. The extra arguments for the lr_scheduler. See the documentation of each scheduler for possible values.
  189. warmup_steps (`int` or `float`, *optional*, defaults to 0):
  190. Number of steps for a linear warmup from 0 to `learning_rate`. Warmup helps stabilize training in the initial phase. Can be:
  191. - An integer: exact number of warmup steps
  192. - A float in range [0, 1): interpreted as ratio of total training steps
  193. > Optimizer
  194. optim (`str` or [`training_args.OptimizerNames`], *optional*, defaults to `"adamw_torch"` (for torch>=2.8 `"adamw_torch_fused"`)):
  195. The optimizer to use. Common options:
  196. - `"adamw_torch"`: PyTorch's AdamW (recommended default)
  197. - `"adamw_torch_fused"`: Fused AdamW kernel
  198. - `"adamw_hf"`: HuggingFace's AdamW implementation
  199. - `"sgd"`: Stochastic Gradient Descent with momentum
  200. - `"adafactor"`: Memory-efficient optimizer for large models
  201. - `"adamw_8bit"`: 8-bit AdamW (requires bitsandbytes)
  202. See [`OptimizerNames`] for the complete list.
  203. optim_args (`str`, *optional*):
  204. Optional arguments that are supplied to optimizers such as AnyPrecisionAdamW, AdEMAMix, and GaLore.
  205. weight_decay (`float`, *optional*, defaults to 0):
  206. Weight decay coefficient applied by the optimizer (not the loss function). Adds L2
  207. regularization to prevent overfitting by penalizing large weights. Automatically
  208. excluded from bias and LayerNorm parameters. Typical values: 0.01 (standard), 0.1
  209. (stronger regularization), 0.0 (no regularization).
  210. adam_beta1 (`float`, *optional*, defaults to 0.9):
  211. The exponential decay rate for the first moment estimates (momentum) in Adam-based
  212. optimizers. Controls how much history of gradients to retain.
  213. adam_beta2 (`float`, *optional*, defaults to 0.999):
  214. The exponential decay rate for the second moment estimates (variance) in Adam-based
  215. optimizers. Controls adaptive learning rate scaling.
  216. adam_epsilon (`float`, *optional*, defaults to 1e-8):
  217. Epsilon value for numerical stability in Adam-based optimizers. Prevents division by
  218. zero in the denominator of the update rule.
  219. optim_target_modules (`Union[str, list[str]]`, *optional*):
  220. The target modules to optimize, i.e. the module names that you would like to train.
  221. Currently used for the [GaLore algorithm](https://huggingface.co/papers/2403.03507) and [APOLLO algorithm](https://huggingface.co/papers/2412.05270).
  222. See [GaLore implementation](https://github.com/jiaweizzhao/GaLore) and [APOLLO implementation](https://github.com/zhuhanqing/APOLLO) for more details.
  223. You need to make sure to pass a valid GaLore or APOLLO optimizer, e.g., one of: "apollo_adamw", "galore_adamw", "galore_adamw_8bit", "galore_adafactor" and make sure that the target modules are `nn.Linear` modules only.
  224. > Regularization & Training Stability
  225. gradient_accumulation_steps (`int`, *optional*, defaults to 1):
  226. Number of update steps to accumulate gradients before performing a backward/update pass.
  227. Simulates larger batch sizes without additional memory. Effective batch size =
  228. `per_device_train_batch_size × num_devices × gradient_accumulation_steps`.
  229. > [!TIP]
  230. > When using gradient accumulation, one "step" is counted as one step with a backward pass. Therefore, logging, evaluation, and saving will occur every `gradient_accumulation_steps × xxx_step` training examples.
  231. average_tokens_across_devices (`bool`, *optional*, defaults to `True`):
  232. Whether or not to average tokens across devices. If enabled, will use all_reduce to synchronize
  233. num_tokens_in_batch for precise loss calculation. Reference:
  234. https://github.com/huggingface/transformers/issues/34242
  235. max_grad_norm (`float`, *optional*, defaults to 1.0):
  236. Maximum gradient norm for gradient clipping. Applied after backward pass, before
  237. optimizer step. Prevents gradient explosion by scaling down gradients when their global
  238. norm exceeds this threshold. Set to 0 to disable clipping. Typical values:
  239. 1.0 (standard), 0.5 (more conservative), 5.0 (less aggressive).
  240. label_smoothing_factor (`float`, *optional*, defaults to 0.0):
  241. Label smoothing factor to prevent overconfidence. Replaces hard 0/1 targets with soft
  242. targets: 0 becomes `ε/num_labels` and 1 becomes `1 - ε + ε/num_labels`, where
  243. ε = `label_smoothing_factor`. Zero means no smoothing. Typical range: 0.0 to 0.1.
  244. > Mixed Precision Training
  245. bf16 (`bool`, *optional*, defaults to `False`):
  246. Enable bfloat16 (BF16) mixed precision training
  247. Generally preferred over FP16 due to better numerical stability and no loss scaling required.
  248. fp16 (`bool`, *optional*, defaults to `False`):
  249. Enable float16 (FP16) mixed precision training.
  250. Consider using BF16 instead if your hardware supports it.
  251. bf16_full_eval (`bool`, *optional*, defaults to `False`):
  252. Use full BF16 precision for evaluation (not just mixed precision). Faster and saves
  253. memory but may affect metric values slightly. Only applies during evaluation.
  254. fp16_full_eval (`bool`, *optional*, defaults to `False`):
  255. Use full FP16 precision for evaluation (not just mixed precision). Faster and saves
  256. memory but may affect metric values slightly. Only applies during evaluation.
  257. tf32 (`bool`, *optional*):
  258. Enable TensorFloat-32 (TF32) mode on Ampere and newer GPUs. TF32 uses 19-bit precision
  259. for matrix multiplications (instead of FP32's 23-bit), providing up to 8x speedup with
  260. negligible accuracy loss. Default depends on PyTorch version. See
  261. [TF32 docs](https://huggingface.co/docs/transformers/perf_train_gpu_one#tf32).
  262. > Gradient Checkpointing
  263. gradient_checkpointing (`bool`, *optional*, defaults to `False`):
  264. Enable gradient checkpointing to trade compute for memory. Reduces memory usage by
  265. clearing activations during forward pass and recomputing them during backward pass.
  266. Enables training larger models or batch sizes at the cost of ~20% slower training.
  267. gradient_checkpointing_kwargs (`dict`, *optional*, defaults to `None`):
  268. Keyword arguments passed to `gradient_checkpointing_enable()`.
  269. > Compilation
  270. torch_compile (`bool`, *optional*, defaults to `False`):
  271. Compile the model using PyTorch 2.0's `torch.compile()` for faster training. Can provide
  272. 20-50% speedup with no code changes. Uses default compilation settings unless
  273. `torch_compile_backend` or `torch_compile_mode` are specified.
  274. torch_compile_backend (`str`, *optional*):
  275. Backend for `torch.compile()`. If set, automatically enables `torch_compile`. Options
  276. include `"inductor"` (default), `"aot_eager"`, `"cudagraphs"`. Backends vary by PyTorch
  277. version - see PyTorch docs for available options.
  278. torch_compile_mode (`str`, *optional*):
  279. Compilation mode for `torch.compile()`. If set, automatically enables `torch_compile`.
  280. Options: `"default"`, `"reduce-overhead"` (minimize Python overhead), `"max-autotune"`
  281. (aggressive optimization, slower compile time).
  282. > Kernels
  283. use_liger_kernel (`bool`, *optional*, defaults to `False`):
  284. Enable [Liger Kernel](https://github.com/linkedin/Liger-Kernel) optimizations. Increases
  285. multi-GPU throughput by ~20% and reduces memory usage by ~60%. Works with Flash Attention,
  286. FSDP, and DeepSpeed. Currently supports Llama, Mistral, Mixtral, and Gemma models.
  287. liger_kernel_config (`Optional[dict]`, *optional*):
  288. Configuration for Liger Kernel. Passed as kwargs to `_apply_liger_kernel_to_instance()`.
  289. Options typically include: `"rope"`, `"swiglu"`, `"cross_entropy"`,
  290. `"fused_linear_cross_entropy"`, `"rms_norm"`. If `None`, uses default configuration.
  291. > Additional Optimizations
  292. use_cache (`bool`, *optional*, defaults to `False`):
  293. Whether or not to enable cache for the model. For training, this is usually not needed apart from some PEFT methods that uses `past_key_values`.
  294. neftune_noise_alpha (`Optional[float]`):
  295. If not `None`, this will activate NEFTune noise embeddings. This can drastically improve model performance
  296. for instruction fine-tuning. Check out the [original paper](https://huggingface.co/papers/2310.05914) and the
  297. [original code](https://github.com/neelsjain/NEFTune). Support transformers `PreTrainedModel` and also
  298. `PeftModel` from peft. The original paper used values in the range [5.0, 15.0].
  299. torch_empty_cache_steps (`int`, *optional*):
  300. Number of steps to wait before calling `torch.<device>.empty_cache()`. If left unset or set to None, cache will not be emptied.
  301. This can help avoid CUDA out-of-memory errors by lowering peak VRAM usage at a cost of about [10% slower performance](https://github.com/huggingface/transformers/issues/31372).
  302. auto_find_batch_size (`bool`, *optional*, defaults to `False`)
  303. Whether to find a batch size that will fit into memory automatically through exponential decay, avoiding
  304. CUDA Out-of-Memory errors.
  305. > Logging & Monitoring Training
  306. logging_strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"steps"`):
  307. The logging strategy to adopt during training. Possible values are:
  308. - `"no"`: No logging is done during training.
  309. - `"epoch"`: Logging is done at the end of each epoch.
  310. - `"steps"`: Logging is done every `logging_steps`.
  311. logging_steps (`int` or `float`, *optional*, defaults to 500):
  312. Number of update steps between two logs if `logging_strategy="steps"`. Should be an integer or a float in
  313. range `[0,1)`. If smaller than 1, will be interpreted as ratio of total training steps.
  314. logging_first_step (`bool`, *optional*, defaults to `False`):
  315. Whether to log the first `global_step` or not.
  316. log_on_each_node (`bool`, *optional*, defaults to `True`):
  317. In multinode distributed training, whether to log using `log_level` once per node, or only on the main
  318. node.
  319. logging_nan_inf_filter (`bool`, *optional*, defaults to `True`):
  320. Filter out NaN and Inf losses when logging. If `True`, replaces NaN/Inf losses with the
  321. average of recent valid losses. Does not affect gradient computation, only logging.
  322. include_num_input_tokens_seen (`Optional[Union[str, bool]]`, *optional*, defaults to "no"):
  323. Whether to track the number of input tokens seen. Must be one of ["all", "non_padding", "no"] or a boolean value which map to "all" or "no".
  324. May be slower in distributed training as gather operations must be called.
  325. > Logging
  326. log_level (`str`, *optional*, defaults to `passive`):
  327. Logging level for the main process. Options: `"debug"`, `"info"`, `"warning"`, `"error"`,
  328. `"critical"`, or `"passive"` (doesn't change the current Transformers logging level,
  329. which defaults to `"warning"`)
  330. log_level_replica (`str`, *optional*, defaults to `"warning"`):
  331. Logging level for replica processes in distributed training. Same options as `log_level`.
  332. disable_tqdm (`bool`, *optional*):
  333. Disable tqdm progress bars. Defaults to `True` if `log_level` is warning or lower, `False` otherwise.
  334. > Experiment Tracking Integration
  335. report_to (`str` or `list[str]`, *optional*, defaults to `"none"`):
  336. The list of integrations to report the results and logs to. Supported platforms are `"azure_ml"`,
  337. `"clearml"`, `"codecarbon"`, `"comet_ml"`, `"dagshub"`, `"dvclive"`, `"flyte"`, `"mlflow"`, `"swanlab"`,
  338. `"tensorboard"`, `"trackio"` and `"wandb"`. Use `"all"` to report to all integrations installed, `"none"`
  339. for no integrations.
  340. run_name (`str`, *optional*):
  341. A descriptor for the run. Typically used for [trackio](https://github.com/gradio-app/trackio),
  342. [wandb](https://www.wandb.com/), [mlflow](https://www.mlflow.org/), [comet](https://www.comet.com/site) and
  343. [swanlab](https://swanlab.cn) logging.
  344. project (`str`, *optional*, defaults to `"huggingface"`):
  345. The name of the project to use for logging. Currently, only used by Trackio.
  346. trackio_space_id (`str` or `None`, *optional*, defaults to `"trackio"`):
  347. The Hugging Face Space ID to deploy to when using Trackio. Should be a complete Space name like
  348. `'username/reponame'` or `'orgname/reponame'`, or just `'reponame'` in which case the Space will be
  349. created in the currently-logged-in Hugging Face user's namespace. If `None`, will log to a local directory.
  350. Note that this Space will be public unless you set `hub_private_repo=True` or your organization's default
  351. is to create private Spaces."
  352. > Evaluation
  353. eval_strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"no"`):
  354. When to run evaluation. Options:
  355. - `"no"`: No evaluation during training
  356. - `"steps"`: Evaluate every `eval_steps`
  357. - `"epoch"`: Evaluate at the end of each epoch
  358. eval_steps (`int` or `float`, *optional*):
  359. Number of update steps between two evaluations if `eval_strategy="steps"`. Will default to the same
  360. value as `logging_steps` if not set. Should be an integer or a float in range `[0,1)`. If smaller than 1,
  361. will be interpreted as ratio of total training steps.
  362. eval_delay (`float`, *optional*):
  363. Number of epochs or steps to wait for before the first evaluation can be performed, depending on the
  364. eval_strategy.
  365. per_device_eval_batch_size (`int`, *optional*, defaults to 8):
  366. The batch size per device accelerator core/CPU for evaluation.
  367. prediction_loss_only (`bool`, *optional*, defaults to `False`):
  368. When performing evaluation and generating predictions, only returns the loss.
  369. eval_on_start (`bool`, *optional*, defaults to `False`):
  370. Whether to perform a evaluation step (sanity check) before the training to ensure the validation steps works correctly.
  371. eval_do_concat_batches (`bool`, *optional*, defaults to `True`):
  372. Whether to recursively concat inputs/losses/labels/predictions across batches. If `False`,
  373. will instead store them as lists, with each batch kept separate.
  374. eval_use_gather_object (`bool`, *optional*, defaults to `False`):
  375. Whether to run recursively gather object in a nested list/tuple/dictionary of objects from all devices. This should only be enabled if users are not just returning tensors, and this is actively discouraged by PyTorch.
  376. This is useful when the labels structure is non standard, like in computer vision tasks.
  377. eval_accumulation_steps (`int`, *optional*):
  378. Number of predictions steps to accumulate the output tensors for, before moving the results to the CPU. If
  379. left unset, the whole predictions are accumulated on the device accelerator before being moved to the CPU (faster but
  380. requires more memory).
  381. > Metrics Computation
  382. include_for_metrics (`list[str]`, *optional*, defaults to `[]`):
  383. Include additional data in the `compute_metrics` function if needed for metrics computation.
  384. Possible options to add to `include_for_metrics` list:
  385. - `"inputs"`: Input data passed to the model, intended for calculating input dependent metrics.
  386. - `"loss"`: Loss values computed during evaluation, intended for calculating loss dependent metrics.
  387. batch_eval_metrics (`bool`, *optional*, defaults to `False`):
  388. If set to `True`, evaluation will call compute_metrics at the end of each batch to accumulate statistics
  389. rather than saving all eval logits in memory. When set to `True`, you must pass a compute_metrics function
  390. that takes a boolean argument `compute_result`, which when passed `True`, will trigger the final global
  391. summary statistics from the batch-level summary statistics you've accumulated over the evaluation set.
  392. > Checkpointing & Saving
  393. save_only_model (`bool`, *optional*, defaults to `False`):
  394. Save only model weights, not optimizer/scheduler/RNG state. Significantly reduces
  395. checkpoint size but prevents resuming training from the checkpoint. Use when you only
  396. need the trained model for inference, not continued training.
  397. You can only load the model using `from_pretrained` with this option set to `True`.
  398. save_strategy (`str` or [`~trainer_utils.SaveStrategy`], *optional*, defaults to `"steps"`):
  399. The checkpoint save strategy to adopt during training. Possible values are:
  400. - `"no"`: No save is done during training.
  401. - `"epoch"`: Save is done at the end of each epoch.
  402. - `"steps"`: Save is done every `save_steps`.
  403. - `"best"`: Save is done whenever a new `best_metric` is achieved.
  404. save_steps (`int` or `float`, *optional*, defaults to 500):
  405. Number of updates steps before two checkpoint saves if `save_strategy="steps"`. Should be an integer or a
  406. float in range `[0,1)`. If smaller than 1, will be interpreted as ratio of total training steps.
  407. save_on_each_node (`bool`, *optional*, defaults to `False`):
  408. When doing multi-node distributed training, whether to save models and checkpoints on each node, or only on
  409. the main one.
  410. This should not be activated when the different nodes use the same storage as the files will be saved with
  411. the same names for each node.
  412. save_total_limit (`int`, *optional*):
  413. Maximum number of checkpoints to keep. Deletes older checkpoints in `output_dir`. When
  414. `load_best_model_at_end=True`, the best checkpoint is always retained plus the most
  415. recent ones. For example, `save_total_limit=5` keeps the 4 most recent plus the best
  416. enable_jit_checkpoint (`bool`, *optional*, defaults to `False`):
  417. Enable Just-In-Time checkpointing on SIGTERM signal for graceful termination on
  418. preemptible workloads. **Important**: Configure your orchestrator's graceful shutdown
  419. period to allow sufficient time. For Kubernetes, set `terminationGracePeriodSeconds`
  420. (default 30s is usually insufficient). For Slurm, use `--signal=USR1@<seconds>`.
  421. Required grace period ≥ longest iteration time + checkpoint save time.
  422. > Hugging Face Hub Integration
  423. push_to_hub (`bool`, *optional*, defaults to `False`):
  424. Whether or not to push the model to the Hub every time the model is saved. If this is activated,
  425. `output_dir` will begin a git directory synced with the repo (determined by `hub_model_id`) and the content
  426. will be pushed each time a save is triggered (depending on your `save_strategy`). Calling
  427. [`~Trainer.save_model`] will also trigger a push.
  428. hub_token (`str`, *optional*):
  429. The token to use to push the model to the Hub. Will default to the token in the cache folder obtained with
  430. `hf auth login`.
  431. hub_private_repo (`bool`, *optional*):
  432. Whether to make the repo private. If `None` (default), the repo will be public unless the organization's
  433. default is private. This value is ignored if the repo already exists. If reporting to Trackio with
  434. deployment to Hugging Face Spaces enabled, the same logic determines whether the Space is private.
  435. hub_model_id (`str`, *optional*):
  436. The name of the repository to keep in sync with the local *output_dir*. It can be a simple model ID in
  437. which case the model will be pushed in your namespace. Otherwise it should be the whole repository name,
  438. for instance `"user_name/model"`, which allows you to push to an organization you are a member of with
  439. `"organization_name/model"`. Will default to `user_name/output_dir_name` with *output_dir_name* being the
  440. name of `output_dir`.
  441. hub_strategy (`str` or [`~trainer_utils.HubStrategy`], *optional*, defaults to `"every_save"`):
  442. Defines what and when to push to Hub. Options:
  443. - `"end"`: Push only at the end of training
  444. - `"every_save"`: Push on each save (async to not block training)
  445. - `"checkpoint"`: Like `"every_save"` plus push latest checkpoint to `"last-checkpoint"` subfolder for easy resuming
  446. - `"all_checkpoints"`: Push all checkpoints as they appear
  447. hub_always_push (`bool`, *optional*, defaults to `False`):
  448. Unless this is `True`, the `Trainer` will skip pushing a checkpoint when the previous push is not finished.
  449. hub_revision (`str`, *optional*):
  450. The revision to use when pushing to the Hub. Can be a branch name, a tag, or a commit hash.
  451. > Best Model Tracking
  452. load_best_model_at_end (`bool`, *optional*, defaults to `False`):
  453. Load the best checkpoint at the end of training. Requires `eval_strategy` to be set.
  454. When enabled, the best checkpoint is always saved (see `save_total_limit`).
  455. <Tip>
  456. When `True`, `save_strategy` must match `eval_strategy` (unless `save_strategy` is `"best"`), and if using `"steps"`,
  457. `save_steps` must be a multiple of `eval_steps`.
  458. </Tip>
  459. metric_for_best_model (`str`, *optional*):
  460. Metric to use for comparing models when `load_best_model_at_end=True`. Must be a metric
  461. name returned by evaluation, with or without the `"eval_"` prefix. Defaults to `"loss"`.
  462. If you set this, `greater_is_better` will default to `True` unless the name ends with
  463. `"loss"`. Examples: `"accuracy"`, `"f1"`, `"eval_bleu"`.
  464. greater_is_better (`bool`, *optional*):
  465. Whether higher metric values are better. Defaults based on `metric_for_best_model`:
  466. `True` if the metric name doesn't end in `"loss"`, `False` otherwise.
  467. > Resuming Training
  468. ignore_data_skip (`bool`, *optional*, defaults to `False`):
  469. When resuming training, skip fast-forwarding through the dataset to reach the previous
  470. state. If `True`, training starts from the beginning of the dataset (faster resume but
  471. results won't match interrupted training). If `False`, skips seen data (slower resume
  472. but exact continuation).
  473. restore_callback_states_from_checkpoint (`bool`, *optional*, defaults to `False`):
  474. Restore callback states from checkpoint when resuming. If `True`, will override callbacks
  475. passed to Trainer if they exist in the checkpoint.
  476. > Reproducibility
  477. full_determinism (`bool`, *optional*, defaults to `False`)
  478. If `True`, [`enable_full_determinism`] is called instead of [`set_seed`] to ensure reproducible results in
  479. distributed training. Important: this will negatively impact the performance, so only use it for debugging.
  480. seed (`int`, *optional*, defaults to 42):
  481. Random seed that will be set at the beginning of training. To ensure reproducibility across runs, use the
  482. [`~Trainer.model_init`] function to instantiate the model if it has some randomly initialized parameters.
  483. data_seed (`int`, *optional*):
  484. Random seed to be used with data samplers. If not set, random generators for data sampling will use the
  485. same seed as `seed`. This can be used to ensure reproducibility of data sampling, independent of the model
  486. seed.
  487. > Hardware Configuration
  488. use_cpu (`bool`, *optional*, defaults to `False`):
  489. Whether or not to use cpu. If set to False, we will use the available torch device/backend.
  490. > Accelerate Configuration
  491. accelerator_config (`str`, `dict`, or `AcceleratorConfig`, *optional*):
  492. Configuration for the internal Accelerate integration. Can be:
  493. - Path to JSON config file: `"accelerator_config.json"`
  494. - Dictionary with config options
  495. - `AcceleratorConfig` instance
  496. Key options:
  497. - `split_batches` (`bool`, defaults to `False`): Whether to split batches across devices.
  498. If `True`, actual batch size is the same on all devices (total must be divisible by
  499. num_processes). If `False`, each device gets the specified batch size.
  500. - `dispatch_batches` (`bool`): If `True`, only main process iterates through dataloader
  501. and dispatches batches to devices. Defaults to `True` for `IterableDataset`, `False`
  502. otherwise.
  503. - `even_batches` (`bool`, defaults to `True`): Duplicate samples from dataset start to
  504. ensure all workers get equal batch sizes.
  505. - `use_seedable_sampler` (`bool`, defaults to `True`): Use fully seedable random sampler
  506. for reproducibility.
  507. - `use_configured_state` (`bool`, defaults to `False`): Use pre-initialized
  508. `AcceleratorState`/`PartialState` instead of creating new one. May cause issues with
  509. hyperparameter tuning.
  510. parallelism_config (`ParallelismConfig`, *optional*):
  511. Parallelism configuration for the training run. Requires Accelerate `1.10.1`
  512. > Dataloader
  513. dataloader_drop_last (`bool`, *optional*, defaults to `False`):
  514. Whether to drop the last incomplete batch (if the length of the dataset is not divisible by the batch size)
  515. or not.
  516. dataloader_num_workers (`int`, *optional*, defaults to 0):
  517. Number of subprocesses to use for data loading (PyTorch only). 0 means that the data will be loaded in the
  518. main process.
  519. dataloader_pin_memory (`bool`, *optional*, defaults to `True`):
  520. Whether you want to pin memory in data loaders or not. Will default to `True`.
  521. dataloader_persistent_workers (`bool`, *optional*, defaults to `False`):
  522. If True, the data loader will not shut down the worker processes after a dataset has been consumed once.
  523. This allows to maintain the workers Dataset instances alive. Can potentially speed up training, but will
  524. increase RAM usage. Will default to `False`.
  525. dataloader_prefetch_factor (`int`, *optional*):
  526. Number of batches loaded in advance by each worker.
  527. 2 means there will be a total of 2 * num_workers batches prefetched across all workers.
  528. remove_unused_columns (`bool`, *optional*, defaults to `True`):
  529. Whether or not to automatically remove the columns unused by the model forward method.
  530. label_names (`list[str]`, *optional*):
  531. The list of keys in your dictionary of inputs that correspond to the labels.
  532. Will eventually default to the list of argument names accepted by the model that contain the word "label",
  533. except if the model used is one of the `XxxForQuestionAnswering` in which case it will also include the
  534. `["start_positions", "end_positions"]` keys.
  535. You should only specify `label_names` if you're using custom label names or if your model's `forward` consumes multiple label tensors (e.g., extractive QA).
  536. train_sampling_strategy (`str`, *optional*, defaults to `"random"`):
  537. The sampler to use for the training dataloader. Possible values are:
  538. - `"random"`: Uses `RandomSampler` (default).
  539. - `"sequential"`: Uses `SequentialSampler`.
  540. - `"group_by_length"`: Uses `LengthGroupedSampler` to group samples of roughly the same length
  541. together (to minimize padding and be more efficient).
  542. Note: When using an `IterableDataset`, this argument is ignored.
  543. length_column_name (`str`, *optional*, defaults to `"length"`):
  544. Column name for precomputed lengths. If the column exists, grouping by length will use these values rather
  545. than computing them on train startup. Ignored unless `train_sampling_strategy` is `"group_by_length"` and the dataset
  546. is an instance of `Dataset`.
  547. > DDP (DistributedDataParallel)
  548. ddp_find_unused_parameters (`bool`, *optional*):
  549. When using distributed training, the value of the flag `find_unused_parameters` passed to
  550. `DistributedDataParallel`. Will default to `False` if gradient checkpointing is used, `True` otherwise.
  551. ddp_bucket_cap_mb (`int`, *optional*):
  552. When using distributed training, the value of the flag `bucket_cap_mb` passed to `DistributedDataParallel`.
  553. ddp_broadcast_buffers (`bool`, *optional*):
  554. When using distributed training, the value of the flag `broadcast_buffers` passed to
  555. `DistributedDataParallel`. Will default to `False` if gradient checkpointing is used, `True` otherwise.
  556. ddp_backend (`str`, *optional*):
  557. The backend to use for distributed training. Must be one of `"nccl"`, `"mpi"`, `"xccl"`, `"gloo"`, `"hccl"`.
  558. ddp_timeout (`int`, *optional*, defaults to 1800):
  559. The timeout for `torch.distributed.init_process_group` calls, used to avoid GPU socket timeouts when
  560. performing slow operations in distributed runnings. Please refer to the [PyTorch documentation](https://pytorch.org/docs/stable/distributed.html#torch.distributed.init_process_group) for more
  561. information.
  562. > FSDP (Fully Sharded Data Parallel)
  563. fsdp (`bool`, `str` or list of [`~trainer_utils.FSDPOption`], *optional*, defaults to `None`):
  564. Enable PyTorch Fully Sharded Data Parallel (FSDP) for distributed training. Options:
  565. - `"full_shard"`: Shard parameters, gradients, and optimizer states (most memory efficient)
  566. - `"shard_grad_op"`: Shard only optimizer states and gradients (ZeRO-2)
  567. - `"hybrid_shard"`: Full shard within nodes, replicate across nodes
  568. - `"hybrid_shard_zero2"`: Shard gradients/optimizer within nodes, replicate across nodes
  569. - `"offload"`: Offload parameters and gradients to CPU (only with `"full_shard"` or
  570. `"shard_grad_op"`)
  571. - `"auto_wrap"`: Automatically wrap layers using `default_auto_wrap_policy`
  572. fsdp_config (`str` or `dict`, *optional*):
  573. Config to be used with fsdp (Pytorch Distributed Parallel Training). The value is either a location of
  574. fsdp json config file (e.g., `fsdp_config.json`) or an already loaded json file as `dict`.
  575. A List of config and its options:
  576. - fsdp_version (`int`, *optional*, defaults to `1`):
  577. The version of FSDP to use. Defaults to 1.
  578. - min_num_params (`int`, *optional*, defaults to `0`):
  579. FSDP's minimum number of parameters for Default Auto Wrapping. (useful only when `fsdp` field is
  580. passed).
  581. - transformer_layer_cls_to_wrap (`list[str]`, *optional*):
  582. List of transformer layer class names (case-sensitive) to wrap, e.g, `BertLayer`, `GPTJBlock`,
  583. `T5Block` .... (useful only when `fsdp` flag is passed).
  584. - backward_prefetch (`str`, *optional*)
  585. FSDP's backward prefetch mode. Controls when to prefetch next set of parameters (useful only when
  586. `fsdp` field is passed).
  587. A list of options along the following:
  588. - `"backward_pre"` : Prefetches the next set of parameters before the current set of parameter's
  589. gradient computation.
  590. - `"backward_post"` : This prefetches the next set of parameters after the current set of
  591. parameter's gradient computation.
  592. - forward_prefetch (`bool`, *optional*, defaults to `False`)
  593. FSDP's forward prefetch mode (useful only when `fsdp` field is passed).
  594. If `"True"`, then FSDP explicitly prefetches the next upcoming all-gather while executing in the
  595. forward pass.
  596. - limit_all_gathers (`bool`, *optional*, defaults to `False`)
  597. FSDP's limit_all_gathers (useful only when `fsdp` field is passed).
  598. If `"True"`, FSDP explicitly synchronizes the CPU thread to prevent too many in-flight
  599. all-gathers.
  600. - use_orig_params (`bool`, *optional*, defaults to `True`)
  601. If `"True"`, allows non-uniform `requires_grad` during init, which means support for interspersed
  602. frozen and trainable parameters. Useful in cases such as parameter-efficient fine-tuning. Please
  603. refer this
  604. [blog](https://dev-discuss.pytorch.org/t/rethinking-pytorch-fully-sharded-data-parallel-fsdp-from-first-principles/1019
  605. - sync_module_states (`bool`, *optional*, defaults to `True`)
  606. If `"True"`, each individually wrapped FSDP unit will broadcast module parameters from rank 0 to
  607. ensure they are the same across all ranks after initialization
  608. - cpu_ram_efficient_loading (`bool`, *optional*, defaults to `False`)
  609. If `"True"`, only the first process loads the pretrained model checkpoint while all other processes
  610. have empty weights. When this setting as `"True"`, `sync_module_states` also must to be `"True"`,
  611. otherwise all the processes except the main process would have random weights leading to unexpected
  612. behaviour during training.
  613. - activation_checkpointing (`bool`, *optional*, defaults to `False`):
  614. If `"True"`, activation checkpointing is a technique to reduce memory usage by clearing activations of
  615. certain layers and recomputing them during a backward pass. Effectively, this trades extra
  616. computation time for reduced memory usage.
  617. - xla (`bool`, *optional*, defaults to `False`):
  618. Whether to use PyTorch/XLA Fully Sharded Data Parallel Training. This is an experimental feature
  619. and its API may evolve in the future.
  620. - xla_fsdp_settings (`dict`, *optional*)
  621. The value is a dictionary which stores the XLA FSDP wrapping parameters.
  622. For a complete list of options, please see [here](
  623. https://github.com/pytorch/xla/blob/master/torch_xla/distributed/fsdp/xla_fully_sharded_data_parallel.py).
  624. - xla_fsdp_grad_ckpt (`bool`, *optional*, defaults to `False`):
  625. Will use gradient checkpointing over each nested XLA FSDP wrapped layer. This setting can only be
  626. used when the xla flag is set to true, and an auto wrapping policy is specified through
  627. fsdp_min_num_params or fsdp_transformer_layer_cls_to_wrap.
  628. > DeepSpeed
  629. deepspeed (`str` or `dict`, *optional*):
  630. Enable [DeepSpeed](https://github.com/deepspeedai/DeepSpeed) integration. Value is either:
  631. - Path to DeepSpeed JSON config file: `"ds_config.json"`
  632. - Loaded config as dictionary
  633. > [!TIP]
  634. > If using ZeRO initialization, instantiate your model *after* initializing
  635. `TrainingArguments`, otherwise ZeRO won't be applied.
  636. > Debugging & Profiling (Experimental)
  637. debug (`str` or list of [`~debug_utils.DebugOption`], *optional*, defaults to `""`):
  638. Enable one or more debug features. This is an experimental feature.
  639. Possible options are:
  640. - "underflow_overflow": detects overflow in model's input/outputs and reports the last frames that led to
  641. the event
  642. - "tpu_metrics_debug": print debug metrics on TPU
  643. skip_memory_metrics (`bool`, *optional*, defaults to `True`):
  644. Whether to skip adding of memory profiler reports to metrics. This is skipped by default because it slows
  645. down the training and evaluation speed.
  646. > External Script Flags (not used by Trainer)
  647. do_train (`bool`, *optional*, defaults to `False`):
  648. Whether to run training or not. This argument is not directly used by [`Trainer`], it's intended to be used
  649. by your training/evaluation scripts instead. See the [example
  650. scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details.
  651. do_eval (`bool`, *optional*):
  652. Whether to run evaluation on the validation set or not. Will be set to `True` if `eval_strategy` is
  653. different from `"no"`. This argument is not directly used by [`Trainer`], it's intended to be used by your
  654. training/evaluation scripts instead. See the [example
  655. scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details.
  656. do_predict (`bool`, *optional*, defaults to `False`):
  657. Whether to run predictions on the test set or not. This argument is not directly used by [`Trainer`], it's
  658. intended to be used by your training/evaluation scripts instead. See the [example
  659. scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details.
  660. resume_from_checkpoint (`str`, *optional*):
  661. The path to a folder with a valid checkpoint for your model. This argument is not directly used by
  662. [`Trainer`], it's intended to be used by your training/evaluation scripts instead. See the [example
  663. scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details.
  664. """
  665. # Fields that accept dict values via CLI as JSON strings (e.g., '{"key": "value"}').
  666. # Any new dict-typed arg must be added here and typed as `dict | str | None`.
  667. _VALID_DICT_FIELDS = [
  668. "accelerator_config",
  669. "fsdp_config",
  670. "deepspeed",
  671. "gradient_checkpointing_kwargs",
  672. "lr_scheduler_kwargs",
  673. ]
  674. # --- Output ---
  675. output_dir: str | None = field(
  676. default=None,
  677. metadata={"help": "The output directory where the model predictions and checkpoints will be written."},
  678. )
  679. # --- Training Duration and Batch Size ---
  680. per_device_train_batch_size: int = field(default=8, metadata={"help": "The batch size per device for training."})
  681. num_train_epochs: float = field(default=3.0, metadata={"help": "Total number of training epochs to perform."})
  682. max_steps: int = field(
  683. default=-1,
  684. metadata={
  685. "help": "Overrides `num_train_epochs`. If set to a positive number, the total number of training steps to perform."
  686. },
  687. )
  688. # --- Learning Rate & Scheduler ---
  689. learning_rate: float = field(default=5e-5, metadata={"help": "The initial learning rate for the optimizer."})
  690. lr_scheduler_type: SchedulerType | str = field(
  691. default="linear",
  692. metadata={"help": "The learning rate scheduler type to use. See `SchedulerType` for all possible values."},
  693. )
  694. lr_scheduler_kwargs: dict | str | None = field(
  695. default=None,
  696. metadata={
  697. "help": "The extra arguments for the lr_scheduler. See the documentation of each scheduler for possible values."
  698. },
  699. )
  700. warmup_steps: float = field(
  701. default=0,
  702. metadata={
  703. "help": "Number of steps for a linear warmup from 0 to `learning_rate`. Can be an integer (exact steps) or a float in [0, 1) (ratio of total steps)."
  704. },
  705. )
  706. # --- Optimizer ---
  707. default_optim = "adamw_torch"
  708. if is_torch_available():
  709. from .pytorch_utils import is_torch_greater_or_equal_than_2_8
  710. if is_torch_greater_or_equal_than_2_8:
  711. default_optim = "adamw_torch_fused"
  712. optim: OptimizerNames | str = field(
  713. default=default_optim,
  714. metadata={"help": "The optimizer to use. See `OptimizerNames` for the complete list."},
  715. )
  716. optim_args: str | None = field(
  717. default=None,
  718. metadata={
  719. "help": "Optional arguments supplied to optimizers such as AnyPrecisionAdamW, AdEMAMix, and GaLore."
  720. },
  721. )
  722. weight_decay: float = field(
  723. default=0.0,
  724. metadata={
  725. "help": "Weight decay coefficient applied by the optimizer. Automatically excluded from bias and LayerNorm parameters."
  726. },
  727. )
  728. adam_beta1: float = field(
  729. default=0.9,
  730. metadata={
  731. "help": "The exponential decay rate for the first moment estimates (momentum) in Adam-based optimizers."
  732. },
  733. )
  734. adam_beta2: float = field(
  735. default=0.999,
  736. metadata={
  737. "help": "The exponential decay rate for the second moment estimates (variance) in Adam-based optimizers."
  738. },
  739. )
  740. adam_epsilon: float = field(
  741. default=1e-8, metadata={"help": "Epsilon value for numerical stability in Adam-based optimizers."}
  742. )
  743. optim_target_modules: None | str | list[str] = field(
  744. default=None,
  745. metadata={"help": "The target modules to optimize. Currently used for the GaLore and APOLLO algorithms."},
  746. )
  747. # --- Regularization & Training Stability ---
  748. gradient_accumulation_steps: int = field(
  749. default=1,
  750. metadata={
  751. "help": (
  752. "Number of update steps to accumulate gradients before performing a backward/update pass."
  753. " Effective batch size = per_device_train_batch_size * num_devices * gradient_accumulation_steps."
  754. )
  755. },
  756. )
  757. average_tokens_across_devices: bool = field(
  758. default=True,
  759. metadata={
  760. "help": "Whether or not to average tokens across devices. If enabled, will use all_reduce to "
  761. "synchronize num_tokens_in_batch for precise loss calculation. Reference: "
  762. "https://github.com/huggingface/transformers/issues/34242"
  763. },
  764. )
  765. max_grad_norm: float = field(
  766. default=1.0, metadata={"help": "Maximum gradient norm for gradient clipping. Set to 0 to disable."}
  767. )
  768. label_smoothing_factor: float = field(
  769. default=0.0, metadata={"help": "Label smoothing factor to prevent overconfidence. Zero means no smoothing."}
  770. )
  771. # --- Mixed Precision ---
  772. bf16: bool = field(
  773. default=False,
  774. metadata={
  775. "help": "Enable bfloat16 (BF16) mixed precision training. Generally preferred over FP16 due to better numerical stability."
  776. },
  777. )
  778. fp16: bool = field(
  779. default=False,
  780. metadata={
  781. "help": "Enable float16 (FP16) mixed precision training. Consider using BF16 instead if your hardware supports it."
  782. },
  783. )
  784. bf16_full_eval: bool = field(
  785. default=False,
  786. metadata={
  787. "help": "Use full BF16 precision for evaluation (not just mixed precision). Faster and saves memory."
  788. },
  789. )
  790. fp16_full_eval: bool = field(
  791. default=False,
  792. metadata={
  793. "help": "Use full FP16 precision for evaluation (not just mixed precision). Faster and saves memory."
  794. },
  795. )
  796. tf32: bool | None = field(
  797. default=None,
  798. metadata={
  799. "help": "Enable TF32 mode on Ampere and newer GPUs. Provides up to 8x speedup with negligible accuracy loss."
  800. },
  801. )
  802. # --- Gradient Checkpointing ---
  803. gradient_checkpointing: bool = field(
  804. default=False,
  805. metadata={
  806. "help": "Enable gradient checkpointing to trade compute for memory. Reduces memory at the cost of ~20%% slower training."
  807. },
  808. )
  809. gradient_checkpointing_kwargs: dict[str, Any] | str | None = field(
  810. default=None,
  811. metadata={"help": "Keyword arguments passed to `gradient_checkpointing_enable()`."},
  812. )
  813. # --- Compilation ---
  814. torch_compile: bool = field(
  815. default=False, metadata={"help": "Compile the model using `torch.compile()` for faster training."}
  816. )
  817. torch_compile_backend: str | None = field(
  818. default=None,
  819. metadata={
  820. "help": "Backend for `torch.compile()`. If set, automatically enables `torch_compile`.",
  821. },
  822. )
  823. torch_compile_mode: str | None = field(
  824. default=None,
  825. metadata={
  826. "help": "Compilation mode for `torch.compile()`. If set, automatically enables `torch_compile`.",
  827. },
  828. )
  829. # --- Kernels ---
  830. use_liger_kernel: bool = field(
  831. default=False,
  832. metadata={
  833. "help": "Enable Liger Kernel optimizations. Increases throughput by ~20%% and reduces memory by ~60%%."
  834. },
  835. )
  836. liger_kernel_config: dict[str, bool] | None = field(
  837. default=None,
  838. metadata={
  839. "help": "Configuration for Liger Kernel. Passed as kwargs to `_apply_liger_kernel_to_instance()`. If None, uses default configuration."
  840. },
  841. )
  842. # --- Additional Optimizations ---
  843. use_cache: bool = field(
  844. default=False,
  845. metadata={
  846. "help": "Whether or not to use cache for the model For training, this is usually not needed apart from some PEFT methods that uses `past_key_values`."
  847. },
  848. )
  849. neftune_noise_alpha: float | None = field(
  850. default=None,
  851. metadata={
  852. "help": "If not None, activates NEFTune noise embeddings. Can drastically improve performance for instruction fine-tuning. Typical range: [5.0, 15.0]."
  853. },
  854. )
  855. torch_empty_cache_steps: int | None = field(
  856. default=None,
  857. metadata={
  858. "help": "Number of steps to wait before calling `torch.<device>.empty_cache()`. Helps avoid CUDA OOM at a cost of ~10%% slower performance. If None, cache will not be emptied."
  859. },
  860. )
  861. auto_find_batch_size: bool = field(
  862. default=False,
  863. metadata={
  864. "help": "Whether to find a batch size that will fit into memory automatically through exponential decay, avoiding CUDA Out-of-Memory errors."
  865. },
  866. )
  867. # --- Logging & Monitoring ---
  868. logging_strategy: IntervalStrategy | str = field(
  869. default="steps",
  870. metadata={"help": "The logging strategy to adopt during training. Options: 'no', 'epoch', 'steps'."},
  871. )
  872. logging_steps: float = field(
  873. default=500,
  874. metadata={
  875. "help": (
  876. "Log every X updates steps. Should be an integer or a float in range `[0,1)`. "
  877. "If smaller than 1, will be interpreted as ratio of total training steps."
  878. )
  879. },
  880. )
  881. logging_first_step: bool = field(
  882. default=False, metadata={"help": "Whether to log the first `global_step` or not."}
  883. )
  884. log_on_each_node: bool = field(
  885. default=True,
  886. metadata={
  887. "help": (
  888. "When doing a multinode distributed training, whether to log once per node or just once on the main"
  889. " node."
  890. )
  891. },
  892. )
  893. logging_nan_inf_filter: bool = field(
  894. default=True,
  895. metadata={
  896. "help": "Filter out NaN and Inf losses when logging. Does not affect gradient computation, only logging."
  897. },
  898. )
  899. include_num_input_tokens_seen: str | bool = field(
  900. default="no",
  901. metadata={
  902. "help": (
  903. "Whether to track the number of input tokens seen. "
  904. "Must be one of [`all`, `non_padding`, `no`] or a boolean value which map to `all` or `no`"
  905. )
  906. },
  907. )
  908. # --- Log Levels ---
  909. log_level: str = field(
  910. default="passive",
  911. metadata={
  912. "help": "Logging level for the main process. Options: 'debug', 'info', 'warning', 'error', 'critical', 'passive'.",
  913. "choices": trainer_log_levels.keys(),
  914. },
  915. )
  916. log_level_replica: str = field(
  917. default="warning",
  918. metadata={
  919. "help": "Logging level for replica processes in distributed training. Same options as `log_level`.",
  920. "choices": trainer_log_levels.keys(),
  921. },
  922. )
  923. disable_tqdm: bool | None = field(
  924. default=None,
  925. metadata={"help": "Disable tqdm progress bars. Defaults to True if log_level is warning or lower."},
  926. )
  927. # --- Experiment Tracking ---
  928. report_to: None | str | list[str] = field(
  929. default="none",
  930. metadata={
  931. "help": "The list of integrations to report the results and logs to. Use 'all' for all installed integrations, 'none' for no integrations."
  932. },
  933. )
  934. run_name: str | None = field(
  935. default=None,
  936. metadata={
  937. "help": (
  938. "An optional descriptor for the run. Notably used for trackio, wandb, mlflow comet and swanlab "
  939. "logging."
  940. )
  941. },
  942. )
  943. project: str = field(
  944. default="huggingface",
  945. metadata={"help": "The name of the project to use for logging. Currently, only used by Trackio."},
  946. )
  947. trackio_space_id: str | None = field(
  948. default="trackio",
  949. metadata={
  950. "help": "The Hugging Face Space ID to deploy to when using Trackio. Should be a complete Space name like "
  951. "'username/reponame' or 'orgname/reponame', or just 'reponame' in which case the Space will be created in "
  952. "the currently-logged-in Hugging Face user's namespace. If `None`, will log to a local directory. Note "
  953. "that this Space will be public unless you set `hub_private_repo=True` or your organization's "
  954. "default is to create private Spaces."
  955. },
  956. )
  957. # --- Evaluation ---
  958. eval_strategy: IntervalStrategy | str = field(
  959. default="no",
  960. metadata={"help": "When to run evaluation. Options: 'no', 'steps', 'epoch'."},
  961. )
  962. eval_steps: float | None = field(
  963. default=None,
  964. metadata={
  965. "help": (
  966. "Number of update steps between evaluations if `eval_strategy='steps'`. Defaults to `logging_steps` if not set."
  967. " Should be an integer or a float in range `[0,1)`. If smaller than 1, will be interpreted as ratio of total training steps."
  968. )
  969. },
  970. )
  971. eval_delay: float = field(
  972. default=0,
  973. metadata={
  974. "help": (
  975. "Number of epochs or steps to wait for before the first evaluation can be performed, depending on the"
  976. " eval_strategy."
  977. )
  978. },
  979. )
  980. per_device_eval_batch_size: int = field(
  981. default=8, metadata={"help": "The batch size per device (GPU/TPU core/CPU) for evaluation."}
  982. )
  983. prediction_loss_only: bool = field(
  984. default=False,
  985. metadata={"help": "When performing evaluation and generating predictions, only returns the loss."},
  986. )
  987. eval_on_start: bool = field(
  988. default=False,
  989. metadata={
  990. "help": "Whether to run through the entire `evaluation` step at the very beginning of training as a sanity check."
  991. },
  992. )
  993. eval_do_concat_batches: bool = field(
  994. default=True,
  995. metadata={
  996. "help": "Whether to recursively concat inputs/losses/labels/predictions across batches. If `False`, will instead store them as lists, with each batch kept separate."
  997. },
  998. )
  999. eval_use_gather_object: bool = field(
  1000. default=False,
  1001. metadata={
  1002. "help": "Whether to run recursively gather object in a nested list/tuple/dictionary of objects from all devices."
  1003. },
  1004. )
  1005. eval_accumulation_steps: int | None = field(
  1006. default=None,
  1007. metadata={
  1008. "help": "Number of predictions steps to accumulate the output tensors for, before moving the results to the CPU. If unset, predictions are accumulated on the accelerator before being moved to the CPU."
  1009. },
  1010. )
  1011. # --- Metrics ---
  1012. include_for_metrics: list[str] = field(
  1013. default_factory=list,
  1014. metadata={"help": "Include additional data in the `compute_metrics` function. Options: 'inputs', 'loss'."},
  1015. )
  1016. batch_eval_metrics: bool = field(
  1017. default=False,
  1018. metadata={"help": "Break eval metrics calculation into batches to save memory."},
  1019. )
  1020. # --- Checkpointing & Saving ---
  1021. save_only_model: bool = field(
  1022. default=False,
  1023. metadata={
  1024. "help": "Save only model weights, not optimizer/scheduler/RNG state. Prevents resuming training from checkpoint."
  1025. },
  1026. )
  1027. save_strategy: SaveStrategy | str = field(
  1028. default="steps",
  1029. metadata={
  1030. "help": "The checkpoint save strategy to adopt during training. Options: 'no', 'epoch', 'steps', 'best'."
  1031. },
  1032. )
  1033. save_steps: float = field(
  1034. default=500,
  1035. metadata={
  1036. "help": (
  1037. "Save checkpoint every X updates steps. Should be an integer or a float in range `[0,1)`. "
  1038. "If smaller than 1, will be interpreted as ratio of total training steps."
  1039. )
  1040. },
  1041. )
  1042. save_on_each_node: bool = field(
  1043. default=False,
  1044. metadata={
  1045. "help": (
  1046. "When doing multi-node distributed training, whether to save models and checkpoints on each node, or"
  1047. " only on the main one"
  1048. )
  1049. },
  1050. )
  1051. save_total_limit: int | None = field(
  1052. default=None,
  1053. metadata={
  1054. "help": "Maximum number of checkpoints to keep. Deletes older checkpoints in `output_dir`. The best checkpoint is always retained when `load_best_model_at_end=True`."
  1055. },
  1056. )
  1057. enable_jit_checkpoint: bool = field(
  1058. default=False,
  1059. metadata={
  1060. "help": "Enable JIT checkpointing on SIGTERM signal for graceful termination on preemptible workloads. Configure your orchestrator's graceful shutdown period accordingly."
  1061. },
  1062. )
  1063. # --- Hub Integration ---
  1064. push_to_hub: bool = field(
  1065. default=False, metadata={"help": "Whether or not to push the model to the Hub every time the model is saved."}
  1066. )
  1067. hub_token: str | None = field(
  1068. default=None,
  1069. metadata={
  1070. "help": "The token to use to push the model to the Hub. Defaults to the token from `hf auth login`."
  1071. },
  1072. )
  1073. hub_private_repo: bool | None = field(
  1074. default=None,
  1075. metadata={
  1076. "help": "Whether to make the repo private. If `None` (default), the repo will be public unless the "
  1077. "organization's default is private. This value is ignored if the repo already exists. If reporting to "
  1078. "Trackio with deployment to Hugging Face Spaces enabled, the same logic determines whether the Space is "
  1079. "private."
  1080. },
  1081. )
  1082. hub_model_id: str | None = field(
  1083. default=None, metadata={"help": "The name of the repository to keep in sync with the local `output_dir`."}
  1084. )
  1085. hub_strategy: HubStrategy | str = field(
  1086. default="every_save",
  1087. metadata={
  1088. "help": "Defines what and when to push to Hub. Options: 'end', 'every_save', 'checkpoint', 'all_checkpoints'."
  1089. },
  1090. )
  1091. hub_always_push: bool = field(
  1092. default=False,
  1093. metadata={"help": "Unless `True`, the Trainer will skip pushes if the previous one wasn't finished yet."},
  1094. )
  1095. hub_revision: str | None = field(
  1096. default=None,
  1097. metadata={
  1098. "help": "The revision to use when pushing to the Hub. Can be a branch name, a tag, or a commit hash."
  1099. },
  1100. )
  1101. # --- Best Model Tracking ---
  1102. load_best_model_at_end: bool = field(
  1103. default=False,
  1104. metadata={"help": "Load the best checkpoint at the end of training. Requires `eval_strategy` to be set."},
  1105. )
  1106. metric_for_best_model: str | None = field(
  1107. default=None,
  1108. metadata={
  1109. "help": "Metric to use for comparing models when `load_best_model_at_end=True`. Defaults to 'loss'."
  1110. },
  1111. )
  1112. greater_is_better: bool | None = field(
  1113. default=None,
  1114. metadata={"help": "Whether higher metric values are better. Defaults based on `metric_for_best_model`."},
  1115. )
  1116. # --- Resuming Training ---
  1117. ignore_data_skip: bool = field(
  1118. default=False,
  1119. metadata={
  1120. "help": "When resuming training, skip fast-forwarding through the dataset to reach the previous state. If True, training starts from the beginning of the dataset."
  1121. },
  1122. )
  1123. restore_callback_states_from_checkpoint: bool = field(
  1124. default=False,
  1125. metadata={
  1126. "help": "Whether to restore the callback states from the checkpoint. If `True`, will override callbacks passed to the `Trainer` if they exist in the checkpoint."
  1127. },
  1128. )
  1129. # --- Reproducibility ---
  1130. full_determinism: bool = field(
  1131. default=False,
  1132. metadata={
  1133. "help": (
  1134. "Whether to call enable_full_determinism instead of set_seed for reproducibility in distributed"
  1135. " training. Important: this will negatively impact the performance, so only use it for debugging."
  1136. )
  1137. },
  1138. )
  1139. seed: int = field(default=42, metadata={"help": "Random seed that will be set at the beginning of training."})
  1140. data_seed: int | None = field(
  1141. default=None,
  1142. metadata={"help": "Random seed to be used with data samplers. If not set, uses the same seed as `seed`."},
  1143. )
  1144. # --- Hardware ---
  1145. use_cpu: bool = field(
  1146. default=False,
  1147. metadata={
  1148. "help": "Whether or not to use cpu. If set to False, we will use the available torch device/backend."
  1149. },
  1150. )
  1151. # --- Accelerate ---
  1152. accelerator_config: dict | str | None = field(
  1153. default=None,
  1154. metadata={
  1155. "help": "Configuration for the internal Accelerate integration. Can be a path to a JSON config file or a dict."
  1156. },
  1157. )
  1158. parallelism_config: ParallelismConfig | None = field(
  1159. default=None,
  1160. metadata={"help": "Parallelism configuration for the training run. Requires Accelerate `1.10.1`."},
  1161. )
  1162. # --- Dataloader ---
  1163. dataloader_drop_last: bool = field(
  1164. default=False, metadata={"help": "Drop the last incomplete batch if it is not divisible by the batch size."}
  1165. )
  1166. dataloader_num_workers: int = field(
  1167. default=0,
  1168. metadata={
  1169. "help": (
  1170. "Number of subprocesses to use for data loading (PyTorch only). 0 means that the data will be loaded"
  1171. " in the main process."
  1172. )
  1173. },
  1174. )
  1175. dataloader_pin_memory: bool = field(
  1176. default=True, metadata={"help": "Whether or not to pin memory for DataLoader."}
  1177. )
  1178. dataloader_persistent_workers: bool = field(
  1179. default=False,
  1180. metadata={
  1181. "help": "If True, the data loader will not shut down the worker processes after a dataset has been consumed once. This allows to maintain the workers Dataset instances alive. Can potentially speed up training, but will increase RAM usage."
  1182. },
  1183. )
  1184. dataloader_prefetch_factor: int | None = field(
  1185. default=None,
  1186. metadata={
  1187. "help": (
  1188. "Number of batches loaded in advance by each worker. "
  1189. "2 means there will be a total of 2 * num_workers batches prefetched across all workers. "
  1190. )
  1191. },
  1192. )
  1193. remove_unused_columns: bool = field(
  1194. default=True,
  1195. metadata={"help": "Whether or not to automatically remove the columns unused by the model forward method."},
  1196. )
  1197. label_names: list[str] | None = field(
  1198. default=None, metadata={"help": "The list of keys in your dictionary of inputs that correspond to the labels."}
  1199. )
  1200. train_sampling_strategy: str = field(
  1201. default="random",
  1202. metadata={
  1203. "help": "Sampler for training: 'random' (default), 'sequential', or 'group_by_length'.",
  1204. "choices": ["random", "sequential", "group_by_length"],
  1205. },
  1206. )
  1207. length_column_name: str = field(
  1208. default="length",
  1209. metadata={
  1210. "help": "Column name for precomputed lengths. Ignored unless `train_sampling_strategy` is 'group_by_length'."
  1211. },
  1212. )
  1213. # --- DDP ---
  1214. ddp_find_unused_parameters: bool | None = field(
  1215. default=None,
  1216. metadata={
  1217. "help": (
  1218. "When using distributed training, the value of the flag `find_unused_parameters` passed to "
  1219. "`DistributedDataParallel`."
  1220. )
  1221. },
  1222. )
  1223. ddp_bucket_cap_mb: int | None = field(
  1224. default=None,
  1225. metadata={
  1226. "help": (
  1227. "When using distributed training, the value of the flag `bucket_cap_mb` passed to "
  1228. "`DistributedDataParallel`."
  1229. )
  1230. },
  1231. )
  1232. ddp_broadcast_buffers: bool | None = field(
  1233. default=None,
  1234. metadata={
  1235. "help": (
  1236. "When using distributed training, the value of the flag `broadcast_buffers` passed to "
  1237. "`DistributedDataParallel`."
  1238. )
  1239. },
  1240. )
  1241. ddp_backend: str | None = field(
  1242. default=None,
  1243. metadata={
  1244. "help": "The backend to use for distributed training. Must be one of 'nccl', 'mpi', 'xccl', 'gloo', 'hccl'.",
  1245. "choices": ["nccl", "gloo", "mpi", "xccl", "hccl", "cncl", "mccl"],
  1246. },
  1247. )
  1248. ddp_timeout: int = field(
  1249. default=1800,
  1250. metadata={"help": "The timeout for `torch.distributed.init_process_group` calls (in seconds)."},
  1251. )
  1252. # --- FSDP ---
  1253. fsdp: list[FSDPOption] | str | None = field(
  1254. default=None,
  1255. metadata={
  1256. "help": "Enable PyTorch FSDP for distributed training. Options: 'full_shard', 'shard_grad_op', 'hybrid_shard', 'hybrid_shard_zero2', 'offload', 'auto_wrap'.",
  1257. },
  1258. )
  1259. fsdp_config: dict[str, Any] | str | None = field(
  1260. default=None,
  1261. metadata={
  1262. "help": (
  1263. "Config to be used with FSDP (Pytorch Fully Sharded Data Parallel). The value is either a "
  1264. "fsdp json config file (e.g., `fsdp_config.json`) or an already loaded json file as `dict`."
  1265. )
  1266. },
  1267. )
  1268. # --- DeepSpeed ---
  1269. deepspeed: dict | str | None = field(
  1270. default=None,
  1271. metadata={"help": "Enable DeepSpeed integration. Value is a path to a JSON config file or a dict."},
  1272. )
  1273. # --- Debugging ---
  1274. debug: str | list[DebugOption] = field(
  1275. default="",
  1276. metadata={
  1277. "help": "Enable one or more debug features. Options: 'underflow_overflow' (detect overflow in model I/O), 'tpu_metrics_debug' (print TPU metrics)."
  1278. },
  1279. )
  1280. skip_memory_metrics: bool = field(
  1281. default=True,
  1282. metadata={
  1283. "help": "Whether to skip adding memory profiler reports to metrics. Skipped by default because it slows down training."
  1284. },
  1285. )
  1286. # --- External Script Flags ---
  1287. do_train: bool = field(
  1288. default=False,
  1289. metadata={
  1290. "help": "Whether to run training. Not directly used by Trainer; intended for training/evaluation scripts."
  1291. },
  1292. )
  1293. do_eval: bool = field(
  1294. default=False,
  1295. metadata={
  1296. "help": "Whether to run evaluation. Not directly used by Trainer; intended for training/evaluation scripts."
  1297. },
  1298. )
  1299. do_predict: bool = field(
  1300. default=False,
  1301. metadata={
  1302. "help": "Whether to run predictions on the test set. Not directly used by Trainer; intended for training/evaluation scripts."
  1303. },
  1304. )
  1305. resume_from_checkpoint: str | None = field(
  1306. default=None,
  1307. metadata={
  1308. "help": "Path to a folder with a valid checkpoint for your model. Not directly used by Trainer; intended for training/evaluation scripts."
  1309. },
  1310. )
  1311. # --- Deprecated / Internal ---
  1312. warmup_ratio: float | None = field(
  1313. default=None,
  1314. metadata={
  1315. "help": "This argument is deprecated and will be removed in v5.2. Use `warmup_steps` instead as it also works with float values."
  1316. },
  1317. )
  1318. logging_dir: str | None = field(
  1319. default=None,
  1320. metadata={
  1321. "help": "Deprecated and will be removed in v5.2. Set env var `TENSORBOARD_LOGGING_DIR` instead. TensorBoard log directory."
  1322. },
  1323. )
  1324. local_rank: int = field(
  1325. default=-1,
  1326. metadata={
  1327. "help": "When using torch.distributed.launch (Deprecated), it will pass `local_rank` in the script, so we need this for the parser. To get the local rank, prefer using the property `local_process_index`"
  1328. },
  1329. )
  1330. def __post_init__(self):
  1331. # ── 1. Defaults & Normalization ──
  1332. if self.output_dir is None:
  1333. self.output_dir = "trainer_output"
  1334. logger.info(
  1335. "No output directory specified, defaulting to 'trainer_output'. "
  1336. "To change this behavior, specify --output_dir when creating TrainingArguments."
  1337. )
  1338. # Parse JSON string dict args from CLI (e.g., '{"key": "value"}').
  1339. # Only parses strings starting with '{'; other strings are treated as file paths.
  1340. for valid_field in self._VALID_DICT_FIELDS:
  1341. passed_value = getattr(self, valid_field)
  1342. if isinstance(passed_value, str) and passed_value.startswith("{"):
  1343. loaded_dict = json.loads(passed_value)
  1344. loaded_dict = _convert_str_dict(loaded_dict)
  1345. setattr(self, valid_field, loaded_dict)
  1346. # Expand ~ in paths so os.makedirs works correctly (#10628)
  1347. if self.output_dir is not None:
  1348. self.output_dir = os.path.expanduser(self.output_dir)
  1349. if self.disable_tqdm is None:
  1350. self.disable_tqdm = logger.getEffectiveLevel() > logging.WARN
  1351. if self.warmup_ratio is not None:
  1352. logger.warning("warmup_ratio is deprecated and will be removed in v5.2. Use `warmup_steps` instead.")
  1353. self.warmup_steps = self.warmup_ratio
  1354. if self.logging_dir is not None:
  1355. logger.warning(
  1356. "`logging_dir` is deprecated and will be removed in v5.2. Please set `TENSORBOARD_LOGGING_DIR` instead."
  1357. )
  1358. if isinstance(self.include_num_input_tokens_seen, bool):
  1359. self.include_num_input_tokens_seen = "all" if self.include_num_input_tokens_seen else "no"
  1360. # ── 2. Enum / Type Conversions ──
  1361. self.eval_strategy = IntervalStrategy(self.eval_strategy)
  1362. self.logging_strategy = IntervalStrategy(self.logging_strategy)
  1363. self.save_strategy = SaveStrategy(self.save_strategy)
  1364. self.hub_strategy = HubStrategy(self.hub_strategy)
  1365. self.lr_scheduler_type = SchedulerType(self.lr_scheduler_type)
  1366. self.optim = OptimizerNames(self.optim)
  1367. if isinstance(self.debug, str):
  1368. self.debug = [DebugOption(s) for s in self.debug.split()]
  1369. elif self.debug is None:
  1370. self.debug = []
  1371. # ── 3. Auto-derived Values ──
  1372. if self.do_eval is False and self.eval_strategy != IntervalStrategy.NO:
  1373. self.do_eval = True
  1374. # Fall back to logging_steps if eval_steps is unset
  1375. if self.eval_strategy == IntervalStrategy.STEPS and (self.eval_steps is None or self.eval_steps == 0):
  1376. if self.logging_steps > 0:
  1377. logger.info(f"using `logging_steps` to initialize `eval_steps` to {self.logging_steps}")
  1378. self.eval_steps = self.logging_steps
  1379. else:
  1380. raise ValueError(
  1381. f"evaluation strategy {self.eval_strategy} requires either non-zero --eval_steps or"
  1382. " --logging_steps"
  1383. )
  1384. if (
  1385. self.load_best_model_at_end
  1386. or self.lr_scheduler_type == SchedulerType.REDUCE_ON_PLATEAU
  1387. or self.lr_scheduler_type == SchedulerType.GREEDY
  1388. ) and self.metric_for_best_model is None:
  1389. self.metric_for_best_model = "loss"
  1390. if self.greater_is_better is None and self.metric_for_best_model is not None:
  1391. self.greater_is_better = not self.metric_for_best_model.endswith("loss")
  1392. if self.report_to == "all" or self.report_to == ["all"]:
  1393. from .integrations import get_available_reporting_integrations
  1394. self.report_to = get_available_reporting_integrations()
  1395. elif self.report_to == "none" or self.report_to == ["none"]:
  1396. self.report_to = []
  1397. elif not isinstance(self.report_to, list):
  1398. self.report_to = [self.report_to]
  1399. # Auto-enable Kubeflow integration when running inside a Kubeflow TrainJob
  1400. from .integrations import is_kubeflow_available
  1401. if is_kubeflow_available() and "kubeflow" not in self.report_to:
  1402. self.report_to = list(self.report_to) + ["kubeflow"]
  1403. # ── 4. Validation ──
  1404. self._validate_args()
  1405. # ── 5. Mixed Precision ──
  1406. # Read from env first; DeepSpeed may override this later
  1407. self.mixed_precision = os.environ.get("ACCELERATE_MIXED_PRECISION", "no")
  1408. if self.fp16:
  1409. self.mixed_precision = "fp16"
  1410. elif self.bf16:
  1411. self.mixed_precision = "bf16"
  1412. # ── 6. Torch Compile ──
  1413. if (self.torch_compile_mode is not None or self.torch_compile_backend is not None) and not self.torch_compile:
  1414. self.torch_compile = True
  1415. if self.torch_compile and self.torch_compile_backend is None:
  1416. if not self.use_cpu and is_torch_hpu_available():
  1417. self.torch_compile_backend = "hpu_backend"
  1418. else:
  1419. self.torch_compile_backend = "inductor"
  1420. if self.torch_compile:
  1421. # TODO: remove env var fallback once minimum accelerate >= 1.2.0
  1422. if not is_accelerate_available("1.2.0"):
  1423. os.environ["ACCELERATE_DYNAMO_BACKEND"] = self.torch_compile_backend
  1424. if self.torch_compile_mode is not None:
  1425. os.environ["ACCELERATE_DYNAMO_MODE"] = self.torch_compile_mode
  1426. # ── 7. Accelerator Config (must come before self.device) ──
  1427. if is_accelerate_available():
  1428. if not isinstance(self.accelerator_config, AcceleratorConfig):
  1429. if self.accelerator_config is None:
  1430. self.accelerator_config = AcceleratorConfig()
  1431. elif isinstance(self.accelerator_config, dict):
  1432. self.accelerator_config = AcceleratorConfig(**self.accelerator_config)
  1433. # Reject uninstantiated class (e.g. AcceleratorConfig instead of AcceleratorConfig())
  1434. elif isinstance(self.accelerator_config, type):
  1435. raise NotImplementedError(
  1436. "Tried passing in a callable to `accelerator_config`, but this is not supported. "
  1437. "Please pass in a fully constructed `AcceleratorConfig` object instead."
  1438. )
  1439. else:
  1440. self.accelerator_config = AcceleratorConfig.from_json_file(self.accelerator_config)
  1441. if self.accelerator_config.split_batches:
  1442. logger.info(
  1443. "Using `split_batches=True` in `accelerator_config` will override the `per_device_train_batch_size` "
  1444. "Batches will be split across all processes equally when using `split_batches=True`."
  1445. )
  1446. # ── 8. Device Init ──
  1447. if is_torch_available():
  1448. self.device
  1449. # ── 9. TF32 ──
  1450. if is_torch_available() and self.torch_compile:
  1451. if is_torch_tf32_available():
  1452. if self.tf32 is None and not self.fp16 or self.bf16:
  1453. device_str = "MUSA" if is_torch_musa_available() else "CUDA"
  1454. logger.info(
  1455. f"Setting TF32 in {device_str} backends to speedup torch compile, you won't see any improvement"
  1456. " otherwise."
  1457. )
  1458. enable_tf32(True)
  1459. else:
  1460. logger.warning(
  1461. "The speedups for torchdynamo mostly come with GPU Ampere or higher and which is not detected here."
  1462. )
  1463. if is_torch_available() and self.tf32 is not None:
  1464. if self.tf32:
  1465. if is_torch_tf32_available():
  1466. enable_tf32(True)
  1467. else:
  1468. raise ValueError("--tf32 requires Ampere or a newer GPU arch, cuda>=11 and torch>=1.7")
  1469. else:
  1470. if is_torch_tf32_available():
  1471. enable_tf32(False)
  1472. # TF32 not available, nothing to disable
  1473. # ── 10. Hardware Overrides ──
  1474. if self.use_cpu:
  1475. self.dataloader_pin_memory = False
  1476. # ── 11. FSDP ──
  1477. # Store args only (not the plugin itself) to avoid pickle issues
  1478. self.fsdp_plugin_args = self._process_fsdp_args()
  1479. # ── 12. DeepSpeed (must be last) ──
  1480. self.deepspeed_plugin = None
  1481. if self.deepspeed:
  1482. from transformers.integrations.deepspeed import HfTrainerDeepSpeedConfig
  1483. # Leave self.deepspeed unmodified; users may rely on the original value
  1484. self.hf_deepspeed_config = HfTrainerDeepSpeedConfig(self.deepspeed)
  1485. self.hf_deepspeed_config.trainer_config_process(self)
  1486. from accelerate.utils import DeepSpeedPlugin
  1487. self.deepspeed_plugin = DeepSpeedPlugin(hf_ds_config=self.hf_deepspeed_config)
  1488. elif strtobool(os.environ.get("ACCELERATE_USE_DEEPSPEED", "false")):
  1489. from accelerate.utils import DeepSpeedPlugin
  1490. self.deepspeed_plugin = DeepSpeedPlugin()
  1491. self.deepspeed_plugin.set_mixed_precision(self.mixed_precision)
  1492. self.deepspeed_plugin.set_deepspeed_weakref()
  1493. def _validate_args(self):
  1494. """Validate argument combinations and value constraints."""
  1495. if self.torch_empty_cache_steps is not None:
  1496. if not (isinstance(self.torch_empty_cache_steps, int) and self.torch_empty_cache_steps > 0):
  1497. raise ValueError(
  1498. f"`torch_empty_cache_steps` must be an integer bigger than 0, got {self.torch_empty_cache_steps}."
  1499. )
  1500. # logging_steps must be non-zero when logging_strategy="steps"
  1501. if self.logging_strategy == IntervalStrategy.STEPS and self.logging_steps == 0:
  1502. raise ValueError(f"logging strategy {self.logging_strategy} requires non-zero --logging_steps")
  1503. if self.logging_strategy == IntervalStrategy.STEPS and self.logging_steps > 1:
  1504. if self.logging_steps != int(self.logging_steps):
  1505. raise ValueError(f"--logging_steps must be an integer if bigger than 1: {self.logging_steps}")
  1506. self.logging_steps = int(self.logging_steps)
  1507. if self.eval_strategy == IntervalStrategy.STEPS and self.eval_steps > 1:
  1508. if self.eval_steps != int(self.eval_steps):
  1509. raise ValueError(f"--eval_steps must be an integer if bigger than 1: {self.eval_steps}")
  1510. self.eval_steps = int(self.eval_steps)
  1511. if self.save_strategy == SaveStrategy.STEPS and self.save_steps > 1:
  1512. if self.save_steps != int(self.save_steps):
  1513. raise ValueError(f"--save_steps must be an integer if bigger than 1: {self.save_steps}")
  1514. self.save_steps = int(self.save_steps)
  1515. # load_best_model_at_end requires compatible save and eval strategies
  1516. if self.load_best_model_at_end and self.save_strategy != SaveStrategy.BEST:
  1517. if self.eval_strategy != self.save_strategy:
  1518. raise ValueError(
  1519. '--load_best_model_at_end requires the save and eval strategy to match, except when --save_strategy="best", but found\n- Evaluation '
  1520. f"strategy: {self.eval_strategy}\n- Save strategy: {self.save_strategy}"
  1521. )
  1522. if self.eval_strategy == IntervalStrategy.STEPS and self.save_steps % self.eval_steps != 0:
  1523. if self.eval_steps < 1 or self.save_steps < 1:
  1524. if not (self.eval_steps < 1 and self.save_steps < 1):
  1525. raise ValueError(
  1526. "--load_best_model_at_end requires the saving steps to be a multiple of the evaluation "
  1527. "steps, which cannot get guaranteed when mixing ratio and absolute steps for save_steps "
  1528. f"{self.save_steps} and eval_steps {self.eval_steps}."
  1529. )
  1530. # Use integer arithmetic to avoid floating point precision issues
  1531. LARGE_MULTIPLIER = 1_000_000
  1532. if (self.save_steps * LARGE_MULTIPLIER) % (self.eval_steps * LARGE_MULTIPLIER) != 0:
  1533. raise ValueError(
  1534. "--load_best_model_at_end requires the saving steps to be a multiple of the evaluation "
  1535. f"steps, but found {self.save_steps}, which is not a multiple of {self.eval_steps}."
  1536. )
  1537. else:
  1538. raise ValueError(
  1539. "--load_best_model_at_end requires the saving steps to be a round multiple of the evaluation "
  1540. f"steps, but found {self.save_steps}, which is not a round multiple of {self.eval_steps}."
  1541. )
  1542. if is_torch_available():
  1543. if self.bf16 or self.bf16_full_eval:
  1544. if not self.use_cpu and not is_torch_bf16_gpu_available() and not is_torch_xla_available():
  1545. error_message = "Your setup doesn't support bf16/gpu. You need to assign use_cpu if you want to train the model on CPU."
  1546. if is_torch_cuda_available():
  1547. error_message += " You need Ampere+ GPU with cuda>=11.0."
  1548. raise ValueError(error_message)
  1549. if self.fp16 and self.bf16:
  1550. raise ValueError("At most one of fp16 and bf16 can be True, but not both")
  1551. if self.fp16_full_eval and self.bf16_full_eval:
  1552. raise ValueError("At most one of fp16 and bf16 can be True for full eval, but not both")
  1553. if self.lr_scheduler_type == SchedulerType.REDUCE_ON_PLATEAU:
  1554. if self.eval_strategy == IntervalStrategy.NO:
  1555. raise ValueError("lr_scheduler_type reduce_lr_on_plateau requires an eval strategy")
  1556. if not is_torch_available():
  1557. raise ValueError("lr_scheduler_type reduce_lr_on_plateau requires torch>=0.2.0")
  1558. if self.lr_scheduler_type == SchedulerType.GREEDY:
  1559. if self.eval_strategy == IntervalStrategy.NO:
  1560. raise ValueError("lr_scheduler_type greedy requires an eval strategy")
  1561. if self.warmup_steps < 0:
  1562. raise ValueError("warmup_steps must be an integer or a float")
  1563. if self.dataloader_num_workers == 0 and self.dataloader_prefetch_factor is not None:
  1564. raise ValueError(
  1565. "--dataloader_prefetch_factor can only be set when data is loaded in a different process, i.e."
  1566. " when --dataloader_num_workers > 0."
  1567. )
  1568. def __str__(self):
  1569. self_as_dict = asdict(self)
  1570. self_as_dict = {k: f"<{k.upper()}>" if k.endswith("_token") else v for k, v in self_as_dict.items()}
  1571. attrs_as_str = [f"{k}={v},\n" for k, v in sorted(self_as_dict.items())]
  1572. return f"{self.__class__.__name__}(\n{''.join(attrs_as_str)})"
  1573. __repr__ = __str__
  1574. @property
  1575. def train_batch_size(self) -> int:
  1576. """
  1577. The actual batch size for training.
  1578. """
  1579. train_batch_size = self.per_device_train_batch_size * max(1, self.n_gpu)
  1580. return train_batch_size
  1581. @property
  1582. def eval_batch_size(self) -> int:
  1583. """
  1584. The actual batch size for evaluation.
  1585. """
  1586. eval_batch_size = self.per_device_eval_batch_size * max(1, self.n_gpu)
  1587. return eval_batch_size
  1588. @property
  1589. def ddp_timeout_delta(self) -> timedelta:
  1590. """
  1591. The actual timeout for torch.distributed.init_process_group since it expects a timedelta variable.
  1592. """
  1593. return timedelta(seconds=self.ddp_timeout)
  1594. @cached_property
  1595. def _setup_devices(self) -> "torch.device":
  1596. requires_backends(self, ["torch"])
  1597. logger.info("PyTorch: setting up devices")
  1598. if not is_sagemaker_mp_enabled():
  1599. if not is_accelerate_available():
  1600. raise ImportError(
  1601. f"Using the `Trainer` with `PyTorch` requires `accelerate>={ACCELERATE_MIN_VERSION}`: "
  1602. f"Please run `pip install transformers[torch]` or `pip install 'accelerate>={ACCELERATE_MIN_VERSION}'`"
  1603. )
  1604. # Build kwargs for PartialState; actual init happens below
  1605. accelerator_state_kwargs: dict[str, Any] = {"enabled": True, "use_configured_state": False}
  1606. if isinstance(self.accelerator_config, AcceleratorConfig):
  1607. accelerator_state_kwargs["use_configured_state"] = self.accelerator_config.pop(
  1608. "use_configured_state", False
  1609. )
  1610. if accelerator_state_kwargs["use_configured_state"]:
  1611. if PartialState._shared_state == {}:
  1612. raise ValueError(
  1613. "Passing `'use_configured_state':True` to the AcceleratorConfig requires a pre-configured "
  1614. "`AcceleratorState` or `PartialState` to be defined before calling `TrainingArguments`. "
  1615. )
  1616. self.distributed_state = PartialState(cpu=self.use_cpu)
  1617. if self.deepspeed and self.distributed_state.distributed_type != DistributedType.DEEPSPEED:
  1618. raise RuntimeError(
  1619. "Tried to use an already configured `Accelerator` or `PartialState` that was not initialized for DeepSpeed, "
  1620. "but also passed in a `deepspeed` configuration to the `TrainingArguments`. Please set "
  1621. "`use_configured_state:False` instead or setup your `Accelerator` or `PartialState` properly."
  1622. )
  1623. else:
  1624. AcceleratorState._reset_state(reset_partial_state=True)
  1625. self.distributed_state = None
  1626. self._n_gpu = 1
  1627. if self.use_cpu or strtobool(os.environ.get("ACCELERATE_USE_CPU", "False")):
  1628. accelerator_state_kwargs["cpu"] = True
  1629. accelerator_state_kwargs["backend"] = self.ddp_backend
  1630. self._n_gpu = 0
  1631. elif is_sagemaker_mp_enabled():
  1632. accelerator_state_kwargs["enabled"] = False
  1633. device = torch.device("cuda", smp.local_rank())
  1634. torch.cuda.set_device(device)
  1635. elif is_sagemaker_dp_enabled():
  1636. accelerator_state_kwargs["_use_sagemaker_dp"] = True
  1637. elif self.deepspeed:
  1638. accelerator_state_kwargs["use_deepspeed"] = True
  1639. accelerator_state_kwargs["timeout"] = timedelta(seconds=self.ddp_timeout)
  1640. else:
  1641. accelerator_state_kwargs["backend"] = self.ddp_backend
  1642. accelerator_state_kwargs["timeout"] = timedelta(seconds=self.ddp_timeout)
  1643. # Initialize PartialState with the accumulated kwargs
  1644. if accelerator_state_kwargs.pop("enabled", False) and not accelerator_state_kwargs.pop(
  1645. "use_configured_state", False
  1646. ):
  1647. # Temporarily set env var so Accelerate detects DeepSpeed
  1648. use_deepspeed = accelerator_state_kwargs.pop("use_deepspeed", False)
  1649. if use_deepspeed:
  1650. os.environ["ACCELERATE_USE_DEEPSPEED"] = "true"
  1651. self.distributed_state = PartialState(**accelerator_state_kwargs)
  1652. if use_deepspeed:
  1653. del os.environ["ACCELERATE_USE_DEEPSPEED"]
  1654. if not is_sagemaker_mp_enabled():
  1655. device = self.distributed_state.device
  1656. if dist.is_available() and dist.is_initialized() and self.parallel_mode != ParallelMode.DISTRIBUTED:
  1657. logger.warning(
  1658. "torch.distributed process group is initialized, but parallel_mode != ParallelMode.DISTRIBUTED. "
  1659. "In order to use Torch DDP, launch your script with `python -m torch.distributed.launch"
  1660. )
  1661. if is_torch_xla_available():
  1662. device = self.distributed_state.device
  1663. self._n_gpu = 0
  1664. elif is_sagemaker_dp_enabled() or is_sagemaker_mp_enabled():
  1665. pass # _n_gpu already set above
  1666. elif self.distributed_state.distributed_type == DistributedType.NO:
  1667. if self.use_cpu:
  1668. device = torch.device("cpu")
  1669. elif is_torch_mps_available():
  1670. device = torch.device("mps")
  1671. elif is_torch_xpu_available():
  1672. device = torch.device("xpu:0")
  1673. torch.xpu.set_device(device)
  1674. elif is_torch_mlu_available():
  1675. device = torch.device("mlu:0")
  1676. torch.mlu.set_device(device)
  1677. elif is_torch_musa_available():
  1678. device = torch.device("musa:0")
  1679. torch.musa.set_device(device)
  1680. elif is_torch_npu_available():
  1681. device = torch.device("npu:0")
  1682. torch.npu.set_device(device)
  1683. elif is_torch_hpu_available():
  1684. device = torch.device("hpu:0")
  1685. torch.hpu.set_device(device)
  1686. elif is_torch_neuron_available():
  1687. device = torch.device("neuron:0")
  1688. torch.neuron.set_device(device)
  1689. else:
  1690. # Default to cuda:0 (respects CUDA_VISIBLE_DEVICES); nn.DataParallel handles n_gpu > 1
  1691. device = torch.device(
  1692. "cuda:0" if torch.cuda.is_available() else os.environ.get("ACCELERATE_TORCH_DEVICE", "cpu")
  1693. )
  1694. # _n_gpu may not have been set yet if _setup_devices is called early
  1695. self._n_gpu = torch.cuda.device_count()
  1696. if device.type == "cuda":
  1697. torch.cuda.set_device(device)
  1698. return device
  1699. @property
  1700. def device(self) -> "torch.device":
  1701. """
  1702. The device used by this process.
  1703. """
  1704. requires_backends(self, ["torch"])
  1705. return self._setup_devices
  1706. @property
  1707. def n_gpu(self):
  1708. """
  1709. The number of GPUs used by this process.
  1710. Note:
  1711. This will only be greater than one when you have multiple GPUs available but are not using distributed
  1712. training. For distributed training, it will always be 1.
  1713. """
  1714. requires_backends(self, ["torch"])
  1715. # Ensure _setup_devices has been called
  1716. if not hasattr(self, "_n_gpu"):
  1717. _ = self._setup_devices
  1718. return self._n_gpu
  1719. @property
  1720. def parallel_mode(self):
  1721. """
  1722. The current mode used for parallelism if multiple GPUs/TPU cores are available. One of:
  1723. - `ParallelMode.NOT_PARALLEL`: no parallelism (CPU or one GPU).
  1724. - `ParallelMode.NOT_DISTRIBUTED`: several GPUs in one single process (uses `torch.nn.DataParallel`).
  1725. - `ParallelMode.DISTRIBUTED`: several GPUs, each having its own process (uses
  1726. `torch.nn.DistributedDataParallel`).
  1727. - `ParallelMode.TPU`: several TPU cores.
  1728. """
  1729. requires_backends(self, ["torch"])
  1730. if is_torch_xla_available():
  1731. return ParallelMode.TPU
  1732. elif is_sagemaker_mp_enabled():
  1733. return ParallelMode.SAGEMAKER_MODEL_PARALLEL
  1734. elif is_sagemaker_dp_enabled():
  1735. return ParallelMode.SAGEMAKER_DATA_PARALLEL
  1736. elif self.distributed_state is not None and self.distributed_state.distributed_type != DistributedType.NO:
  1737. return ParallelMode.DISTRIBUTED
  1738. elif self.n_gpu > 1:
  1739. return ParallelMode.NOT_DISTRIBUTED
  1740. else:
  1741. return ParallelMode.NOT_PARALLEL
  1742. @property
  1743. def world_size(self):
  1744. """
  1745. The number of processes used in parallel.
  1746. """
  1747. requires_backends(self, ["torch"])
  1748. if self.distributed_state is not None:
  1749. return self.distributed_state.num_processes
  1750. elif is_sagemaker_mp_enabled():
  1751. return smp.dp_size() if not smp.state.cfg.prescaled_batch else smp.rdp_size()
  1752. return 1
  1753. @property
  1754. def process_index(self):
  1755. """
  1756. The index of the current process used.
  1757. """
  1758. requires_backends(self, ["torch"])
  1759. if self.distributed_state is not None:
  1760. return self.distributed_state.process_index
  1761. elif is_sagemaker_mp_enabled():
  1762. return smp.dp_rank() if not smp.state.cfg.prescaled_batch else smp.rdp_rank()
  1763. return 0
  1764. @property
  1765. def local_process_index(self):
  1766. """
  1767. The index of the local process used.
  1768. """
  1769. requires_backends(self, ["torch"])
  1770. if self.distributed_state is not None:
  1771. return self.distributed_state.local_process_index
  1772. elif is_sagemaker_mp_enabled():
  1773. return smp.local_rank()
  1774. return 0
  1775. @property
  1776. def should_log(self):
  1777. """
  1778. Whether or not the current process should produce log.
  1779. """
  1780. if self.log_on_each_node:
  1781. return self.local_process_index == 0
  1782. else:
  1783. if is_sagemaker_mp_enabled():
  1784. return smp.rank() == 0
  1785. else:
  1786. return self.process_index == 0
  1787. @property
  1788. def should_save(self):
  1789. """
  1790. Whether or not the current process should write to disk, e.g., to save models and checkpoints.
  1791. """
  1792. if self.save_on_each_node:
  1793. return self.local_process_index == 0
  1794. else:
  1795. if is_sagemaker_mp_enabled():
  1796. return smp.rank() == 0
  1797. else:
  1798. return self.process_index == 0
  1799. def get_process_log_level(self):
  1800. """
  1801. Returns the log level to be used depending on whether this process is the main process of node 0, main process
  1802. of node non-0, or a non-main process.
  1803. For the main process the log level defaults to the logging level set (`logging.WARNING` if you didn't do
  1804. anything) unless overridden by `log_level` argument.
  1805. For the replica processes the log level defaults to `logging.WARNING` unless overridden by `log_level_replica`
  1806. argument.
  1807. The choice between the main and replica process settings is made according to the return value of `should_log`.
  1808. """
  1809. # convert to int
  1810. log_level = trainer_log_levels[self.log_level]
  1811. log_level_replica = trainer_log_levels[self.log_level_replica]
  1812. log_level_main_node = logging.get_verbosity() if log_level == -1 else log_level
  1813. log_level_replica_node = logging.get_verbosity() if log_level_replica == -1 else log_level_replica
  1814. return log_level_main_node if self.should_log else log_level_replica_node
  1815. @property
  1816. def place_model_on_device(self) -> bool | None:
  1817. """
  1818. Can be subclassed and overridden for some specific integrations.
  1819. """
  1820. return None
  1821. @property
  1822. def _no_sync_in_gradient_accumulation(self):
  1823. """
  1824. Whether or not to use no_sync for the gradients when doing gradient accumulation.
  1825. """
  1826. return not (
  1827. self.deepspeed or is_sagemaker_dp_enabled() or is_sagemaker_mp_enabled() or is_torch_neuroncore_available()
  1828. )
  1829. @contextlib.contextmanager
  1830. def main_process_first(self, local=True, desc="work"):
  1831. """
  1832. A context manager for torch distributed environment where on needs to do something on the main process, while
  1833. blocking replicas, and when it's finished releasing the replicas.
  1834. One such use is for `datasets`'s `map` feature which to be efficient should be run once on the main process,
  1835. which upon completion saves a cached version of results and which then automatically gets loaded by the
  1836. replicas.
  1837. Args:
  1838. local (`bool`, *optional*, defaults to `True`):
  1839. if `True` first means process of rank 0 of each node if `False` first means process of rank 0 of node
  1840. rank 0 In multi-node environment with a shared filesystem you most likely will want to use
  1841. `local=False` so that only the main process of the first node will do the processing. If however, the
  1842. filesystem is not shared, then the main process of each node will need to do the processing, which is
  1843. the default behavior.
  1844. desc (`str`, *optional*, defaults to `"work"`):
  1845. a work description to be used in debug logs
  1846. """
  1847. if is_torch_available() and self.world_size > 1:
  1848. main_process_desc = "main local process" if local else "main process"
  1849. if self.distributed_state is not None:
  1850. is_main_process = (
  1851. self.distributed_state.is_local_main_process if local else self.distributed_state.is_main_process
  1852. )
  1853. elif is_sagemaker_mp_enabled():
  1854. is_main_process = smp.rank() == 0
  1855. try:
  1856. if not is_main_process:
  1857. # tell all replicas to wait
  1858. logger.debug(f"{self.process_index}: waiting for the {main_process_desc} to perform {desc}")
  1859. if is_torch_xla_available():
  1860. xm.rendezvous(desc)
  1861. else:
  1862. dist.barrier()
  1863. yield
  1864. finally:
  1865. if is_main_process:
  1866. # the wait is over
  1867. logger.debug(f"{self.process_index}: {main_process_desc} completed {desc}, releasing all replicas")
  1868. if is_torch_xla_available():
  1869. xm.rendezvous(desc)
  1870. else:
  1871. dist.barrier()
  1872. else:
  1873. yield
  1874. def get_warmup_steps(self, num_training_steps: int):
  1875. """
  1876. Get number of steps used for a linear warmup.
  1877. """
  1878. warmup_steps = (
  1879. int(self.warmup_steps) if self.warmup_steps >= 1 else math.ceil(num_training_steps * self.warmup_steps)
  1880. )
  1881. return warmup_steps
  1882. def _dict_dtype_to_str(self, d: dict[str, Any]) -> None:
  1883. """
  1884. Checks whether the passed dictionary and its nested dicts have a *dtype* key and if it's not None,
  1885. converts torch.dtype to a string of just the type. For example, `torch.float32` get converted into *"float32"*
  1886. string, which can then be stored in the json format.
  1887. """
  1888. if d.get("dtype") is not None and not isinstance(d["dtype"], str):
  1889. d["dtype"] = str(d["dtype"]).split(".")[1]
  1890. for value in d.values():
  1891. if isinstance(value, dict):
  1892. self._dict_dtype_to_str(value)
  1893. def to_dict(self):
  1894. """
  1895. Serializes this instance while replace `Enum` by their values (for JSON serialization support). It obfuscates
  1896. the token values by removing their value.
  1897. """
  1898. # Exclude non-init fields (they aren't user-facing config)
  1899. d = {field.name: getattr(self, field.name) for field in fields(self) if field.init}
  1900. for k, v in d.items():
  1901. if isinstance(v, Enum):
  1902. d[k] = v.value
  1903. if isinstance(v, list) and len(v) > 0 and isinstance(v[0], Enum):
  1904. d[k] = [x.value for x in v]
  1905. if k.endswith("_token"):
  1906. d[k] = f"<{k.upper()}>"
  1907. # Serialize AcceleratorConfig to dict
  1908. if is_accelerate_available() and isinstance(v, AcceleratorConfig):
  1909. d[k] = v.to_dict()
  1910. # Serialize quantization_config if nested inside model_init_kwargs
  1911. if k == "model_init_kwargs" and isinstance(v, dict) and "quantization_config" in v:
  1912. quantization_config = v.get("quantization_config")
  1913. if quantization_config and not isinstance(quantization_config, dict):
  1914. d[k]["quantization_config"] = quantization_config.to_dict()
  1915. if k == "parallelism_config" and v is not None:
  1916. d[k] = v.to_json()
  1917. self._dict_dtype_to_str(d)
  1918. return d
  1919. def to_json_string(self):
  1920. """
  1921. Serializes this instance to a JSON string.
  1922. """
  1923. return json.dumps(self.to_dict(), indent=2)
  1924. def to_sanitized_dict(self) -> dict[str, Any]:
  1925. """
  1926. Sanitized serialization to use with TensorBoard's hparams
  1927. """
  1928. d = self.to_dict()
  1929. d = {**d, "train_batch_size": self.train_batch_size, "eval_batch_size": self.eval_batch_size}
  1930. valid_types = [bool, int, float, str]
  1931. if is_torch_available():
  1932. valid_types.append(torch.Tensor)
  1933. return {k: v if type(v) in valid_types else str(v) for k, v in d.items()}
  1934. # Convenience setters for grouped configuration
  1935. def set_training(
  1936. self,
  1937. learning_rate: float = 5e-5,
  1938. batch_size: int = 8,
  1939. weight_decay: float = 0,
  1940. num_epochs: float = 3,
  1941. max_steps: int = -1,
  1942. gradient_accumulation_steps: int = 1,
  1943. seed: int = 42,
  1944. gradient_checkpointing: bool = False,
  1945. ):
  1946. """
  1947. A method that regroups all basic arguments linked to the training.
  1948. <Tip>
  1949. Calling this method will automatically set `self.do_train` to `True`.
  1950. </Tip>
  1951. Args:
  1952. learning_rate (`float`, *optional*, defaults to 5e-5):
  1953. The initial learning rate for the optimizer.
  1954. batch_size (`int` *optional*, defaults to 8):
  1955. The batch size per device (GPU/TPU core/CPU...) used for training.
  1956. weight_decay (`float`, *optional*, defaults to 0):
  1957. The weight decay to apply (if not zero) to all layers except all bias and LayerNorm weights in the
  1958. optimizer.
  1959. num_train_epochs(`float`, *optional*, defaults to 3.0):
  1960. Total number of training epochs to perform (if not an integer, will perform the decimal part percents
  1961. of the last epoch before stopping training).
  1962. max_steps (`int`, *optional*, defaults to -1):
  1963. If set to a positive number, the total number of training steps to perform. Overrides `num_train_epochs`.
  1964. For a finite dataset, training is reiterated through the dataset (if all data is exhausted) until
  1965. `max_steps` is reached.
  1966. gradient_accumulation_steps (`int`, *optional*, defaults to 1):
  1967. Number of updates steps to accumulate the gradients for, before performing a backward/update pass.
  1968. <Tip warning={true}>
  1969. When using gradient accumulation, one step is counted as one step with backward pass. Therefore,
  1970. logging, evaluation, save will be conducted every `gradient_accumulation_steps * xxx_step` training
  1971. examples.
  1972. </Tip>
  1973. seed (`int`, *optional*, defaults to 42):
  1974. Random seed that will be set at the beginning of training. To ensure reproducibility across runs, use
  1975. the [`~Trainer.model_init`] function to instantiate the model if it has some randomly initialized
  1976. parameters.
  1977. gradient_checkpointing (`bool`, *optional*, defaults to `False`):
  1978. If True, use gradient checkpointing to save memory at the expense of slower backward pass.
  1979. Example:
  1980. ```py
  1981. >>> from transformers import TrainingArguments
  1982. >>> args = TrainingArguments("working_dir")
  1983. >>> args = args.set_training(learning_rate=1e-4, batch_size=32)
  1984. >>> args.learning_rate
  1985. 1e-4
  1986. ```
  1987. """
  1988. self.do_train = True
  1989. self.learning_rate = learning_rate
  1990. self.per_device_train_batch_size = batch_size
  1991. self.weight_decay = weight_decay
  1992. self.num_train_epochs = num_epochs
  1993. self.max_steps = max_steps
  1994. self.gradient_accumulation_steps = gradient_accumulation_steps
  1995. self.seed = seed
  1996. self.gradient_checkpointing = gradient_checkpointing
  1997. return self
  1998. def set_evaluate(
  1999. self,
  2000. strategy: str | IntervalStrategy = "no",
  2001. steps: int = 500,
  2002. batch_size: int = 8,
  2003. accumulation_steps: int | None = None,
  2004. delay: float | None = None,
  2005. loss_only: bool = False,
  2006. ):
  2007. """
  2008. A method that regroups all arguments linked to evaluation.
  2009. Args:
  2010. strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"no"`):
  2011. The evaluation strategy to adopt during training. Possible values are:
  2012. - `"no"`: No evaluation is done during training.
  2013. - `"steps"`: Evaluation is done (and logged) every `steps`.
  2014. - `"epoch"`: Evaluation is done at the end of each epoch.
  2015. Setting a `strategy` different from `"no"` will set `self.do_eval` to `True`.
  2016. steps (`int`, *optional*, defaults to 500):
  2017. Number of update steps between two evaluations if `strategy="steps"`.
  2018. batch_size (`int` *optional*, defaults to 8):
  2019. The batch size per device (GPU/TPU core/CPU...) used for evaluation.
  2020. accumulation_steps (`int`, *optional*):
  2021. Number of predictions steps to accumulate the output tensors for, before moving the results to the CPU.
  2022. If left unset, the whole predictions are accumulated on GPU/TPU before being moved to the CPU (faster
  2023. but requires more memory).
  2024. delay (`float`, *optional*):
  2025. Number of epochs or steps to wait for before the first evaluation can be performed, depending on the
  2026. eval_strategy.
  2027. loss_only (`bool`, *optional*, defaults to `False`):
  2028. Ignores all outputs except the loss.
  2029. Example:
  2030. ```py
  2031. >>> from transformers import TrainingArguments
  2032. >>> args = TrainingArguments("working_dir")
  2033. >>> args = args.set_evaluate(strategy="steps", steps=100)
  2034. >>> args.eval_steps
  2035. 100
  2036. ```
  2037. """
  2038. self.eval_strategy = IntervalStrategy(strategy)
  2039. if self.eval_strategy == IntervalStrategy.STEPS and steps == 0:
  2040. raise ValueError("Setting `strategy` as 'steps' requires a positive value for `steps`.")
  2041. self.do_eval = self.eval_strategy != IntervalStrategy.NO
  2042. self.eval_steps = steps
  2043. self.per_device_eval_batch_size = batch_size
  2044. self.eval_accumulation_steps = accumulation_steps
  2045. self.eval_delay = delay
  2046. self.prediction_loss_only = loss_only
  2047. return self
  2048. def set_testing(
  2049. self,
  2050. batch_size: int = 8,
  2051. loss_only: bool = False,
  2052. ):
  2053. """
  2054. A method that regroups all basic arguments linked to testing on a held-out dataset.
  2055. <Tip>
  2056. Calling this method will automatically set `self.do_predict` to `True`.
  2057. </Tip>
  2058. Args:
  2059. batch_size (`int` *optional*, defaults to 8):
  2060. The batch size per device (GPU/TPU core/CPU...) used for testing.
  2061. loss_only (`bool`, *optional*, defaults to `False`):
  2062. Ignores all outputs except the loss.
  2063. Example:
  2064. ```py
  2065. >>> from transformers import TrainingArguments
  2066. >>> args = TrainingArguments("working_dir")
  2067. >>> args = args.set_testing(batch_size=32)
  2068. >>> args.per_device_eval_batch_size
  2069. 32
  2070. ```
  2071. """
  2072. self.do_predict = True
  2073. self.per_device_eval_batch_size = batch_size
  2074. self.prediction_loss_only = loss_only
  2075. return self
  2076. def set_save(
  2077. self,
  2078. strategy: str | IntervalStrategy = "steps",
  2079. steps: int = 500,
  2080. total_limit: int | None = None,
  2081. on_each_node: bool = False,
  2082. ):
  2083. """
  2084. A method that regroups all arguments linked to checkpoint saving.
  2085. Args:
  2086. strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"steps"`):
  2087. The checkpoint save strategy to adopt during training. Possible values are:
  2088. - `"no"`: No save is done during training.
  2089. - `"epoch"`: Save is done at the end of each epoch.
  2090. - `"steps"`: Save is done every `save_steps`.
  2091. steps (`int`, *optional*, defaults to 500):
  2092. Number of updates steps before two checkpoint saves if `strategy="steps"`.
  2093. total_limit (`int`, *optional*):
  2094. If a value is passed, will limit the total amount of checkpoints. Deletes the older checkpoints in
  2095. `output_dir`.
  2096. on_each_node (`bool`, *optional*, defaults to `False`):
  2097. When doing multi-node distributed training, whether to save models and checkpoints on each node, or
  2098. only on the main one.
  2099. This should not be activated when the different nodes use the same storage as the files will be saved
  2100. with the same names for each node.
  2101. Example:
  2102. ```py
  2103. >>> from transformers import TrainingArguments
  2104. >>> args = TrainingArguments("working_dir")
  2105. >>> args = args.set_save(strategy="steps", steps=100)
  2106. >>> args.save_steps
  2107. 100
  2108. ```
  2109. """
  2110. self.save_strategy = SaveStrategy(strategy)
  2111. if self.save_strategy == SaveStrategy.STEPS and steps == 0:
  2112. raise ValueError("Setting `strategy` as 'steps' requires a positive value for `steps`.")
  2113. self.save_steps = steps
  2114. self.save_total_limit = total_limit
  2115. self.save_on_each_node = on_each_node
  2116. return self
  2117. def set_logging(
  2118. self,
  2119. strategy: str | IntervalStrategy = "steps",
  2120. steps: int = 500,
  2121. report_to: str | list[str] = "none",
  2122. level: str = "passive",
  2123. first_step: bool = False,
  2124. nan_inf_filter: bool = False,
  2125. on_each_node: bool = False,
  2126. replica_level: str = "passive",
  2127. ):
  2128. """
  2129. A method that regroups all arguments linked to logging.
  2130. Args:
  2131. strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"steps"`):
  2132. The logging strategy to adopt during training. Possible values are:
  2133. - `"no"`: No logging is done during training.
  2134. - `"epoch"`: Logging is done at the end of each epoch.
  2135. - `"steps"`: Logging is done every `logging_steps`.
  2136. steps (`int`, *optional*, defaults to 500):
  2137. Number of update steps between two logs if `strategy="steps"`.
  2138. level (`str`, *optional*, defaults to `"passive"`):
  2139. Logger log level to use on the main process. Possible choices are the log levels as strings: `"debug"`,
  2140. `"info"`, `"warning"`, `"error"` and `"critical"`, plus a `"passive"` level which doesn't set anything
  2141. and lets the application set the level.
  2142. report_to (`str` or `list[str]`, *optional*, defaults to `"none"`):
  2143. The list of integrations to report the results and logs to. Supported platforms are `"azure_ml"`,
  2144. `"clearml"`, `"codecarbon"`, `"comet_ml"`, `"dagshub"`, `"dvclive"`, `"flyte"`, `"mlflow"`,
  2145. `"swanlab"`, `"tensorboard"`, `"trackio"` and `"wandb"`. Use `"all"` to report to all integrations
  2146. installed, `"none"` for no integrations.
  2147. first_step (`bool`, *optional*, defaults to `False`):
  2148. Whether to log and evaluate the first `global_step` or not.
  2149. nan_inf_filter (`bool`, *optional*, defaults to `True`):
  2150. Whether to filter `nan` and `inf` losses for logging. If set to `True` the loss of every step that is
  2151. `nan` or `inf` is filtered and the average loss of the current logging window is taken instead.
  2152. <Tip>
  2153. `nan_inf_filter` only influences the logging of loss values, it does not change the behavior the
  2154. gradient is computed or applied to the model.
  2155. </Tip>
  2156. on_each_node (`bool`, *optional*, defaults to `True`):
  2157. In multinode distributed training, whether to log using `log_level` once per node, or only on the main
  2158. node.
  2159. replica_level (`str`, *optional*, defaults to `"passive"`):
  2160. Logger log level to use on replicas. Same choices as `log_level`
  2161. Example:
  2162. ```py
  2163. >>> from transformers import TrainingArguments
  2164. >>> args = TrainingArguments("working_dir")
  2165. >>> args = args.set_logging(strategy="steps", steps=100)
  2166. >>> args.logging_steps
  2167. 100
  2168. ```
  2169. """
  2170. self.logging_strategy = IntervalStrategy(strategy)
  2171. if self.logging_strategy == IntervalStrategy.STEPS and steps == 0:
  2172. raise ValueError("Setting `strategy` as 'steps' requires a positive value for `steps`.")
  2173. self.logging_steps = steps
  2174. self.report_to = report_to
  2175. self.log_level = level
  2176. self.logging_first_step = first_step
  2177. self.logging_nan_inf_filter = nan_inf_filter
  2178. self.log_on_each_node = on_each_node
  2179. self.log_level_replica = replica_level
  2180. return self
  2181. def set_push_to_hub(
  2182. self,
  2183. model_id: str,
  2184. strategy: str | HubStrategy = "every_save",
  2185. token: str | None = None,
  2186. private_repo: bool | None = None,
  2187. always_push: bool = False,
  2188. revision: str | None = None,
  2189. ):
  2190. """
  2191. A method that regroups all arguments linked to synchronizing checkpoints with the Hub.
  2192. <Tip>
  2193. Calling this method will set `self.push_to_hub` to `True`, which means the `output_dir` will begin a git
  2194. directory synced with the repo (determined by `model_id`) and the content will be pushed each time a save is
  2195. triggered (depending on your `self.save_strategy`). Calling [`~Trainer.save_model`] will also trigger a push.
  2196. </Tip>
  2197. Args:
  2198. model_id (`str`):
  2199. The name of the repository to keep in sync with the local *output_dir*. It can be a simple model ID in
  2200. which case the model will be pushed in your namespace. Otherwise it should be the whole repository
  2201. name, for instance `"user_name/model"`, which allows you to push to an organization you are a member of
  2202. with `"organization_name/model"`.
  2203. strategy (`str` or [`~trainer_utils.HubStrategy`], *optional*, defaults to `"every_save"`):
  2204. Defines the scope of what is pushed to the Hub and when. Possible values are:
  2205. - `"end"`: push the model, its configuration, the processing_class e.g. tokenizer (if passed along to the [`Trainer`]) and a
  2206. draft of a model card when the [`~Trainer.save_model`] method is called.
  2207. - `"every_save"`: push the model, its configuration, the processing_class e.g. tokenizer (if passed along to the [`Trainer`])
  2208. and
  2209. a draft of a model card each time there is a model save. The pushes are asynchronous to not block
  2210. training, and in case the save are very frequent, a new push is only attempted if the previous one is
  2211. finished. A last push is made with the final model at the end of training.
  2212. - `"checkpoint"`: like `"every_save"` but the latest checkpoint is also pushed in a subfolder named
  2213. last-checkpoint, allowing you to resume training easily with
  2214. `trainer.train(resume_from_checkpoint="last-checkpoint")`.
  2215. - `"all_checkpoints"`: like `"checkpoint"` but all checkpoints are pushed like they appear in the
  2216. output
  2217. folder (so you will get one checkpoint folder per folder in your final repository)
  2218. token (`str`, *optional*):
  2219. The token to use to push the model to the Hub. Will default to the token in the cache folder obtained
  2220. with `hf auth login`.
  2221. private_repo (`bool`, *optional*, defaults to `False`):
  2222. Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.
  2223. always_push (`bool`, *optional*, defaults to `False`):
  2224. Unless this is `True`, the `Trainer` will skip pushing a checkpoint when the previous push is not
  2225. finished.
  2226. revision (`str`, *optional*):
  2227. The revision to use when pushing to the Hub. Can be a branch name, a tag, or a commit hash.
  2228. Example:
  2229. ```py
  2230. >>> from transformers import TrainingArguments
  2231. >>> args = TrainingArguments("working_dir")
  2232. >>> args = args.set_push_to_hub("me/awesome-model")
  2233. >>> args.hub_model_id
  2234. 'me/awesome-model'
  2235. ```
  2236. """
  2237. self.push_to_hub = True
  2238. self.hub_model_id = model_id
  2239. self.hub_strategy = HubStrategy(strategy)
  2240. self.hub_token = token
  2241. self.hub_private_repo = private_repo
  2242. self.hub_always_push = always_push
  2243. self.hub_revision = revision
  2244. return self
  2245. def set_optimizer(
  2246. self,
  2247. name: str | OptimizerNames = "adamw_torch",
  2248. learning_rate: float = 5e-5,
  2249. weight_decay: float = 0,
  2250. beta1: float = 0.9,
  2251. beta2: float = 0.999,
  2252. epsilon: float = 1e-8,
  2253. args: str | None = None,
  2254. ):
  2255. """
  2256. A method that regroups all arguments linked to the optimizer and its hyperparameters.
  2257. Args:
  2258. name (`str` or [`training_args.OptimizerNames`], *optional*, defaults to `"adamw_torch"`):
  2259. The optimizer to use: `"adamw_torch"`, `"adamw_torch_fused"`, `"adamw_apex_fused"`,
  2260. `"adamw_anyprecision"` or `"adafactor"`.
  2261. learning_rate (`float`, *optional*, defaults to 5e-5):
  2262. The initial learning rate.
  2263. weight_decay (`float`, *optional*, defaults to 0):
  2264. The weight decay to apply (if not zero) to all layers except all bias and LayerNorm weights.
  2265. beta1 (`float`, *optional*, defaults to 0.9):
  2266. The beta1 hyperparameter for the adam optimizer or its variants.
  2267. beta2 (`float`, *optional*, defaults to 0.999):
  2268. The beta2 hyperparameter for the adam optimizer or its variants.
  2269. epsilon (`float`, *optional*, defaults to 1e-8):
  2270. The epsilon hyperparameter for the adam optimizer or its variants.
  2271. args (`str`, *optional*):
  2272. Optional arguments that are supplied to AnyPrecisionAdamW (only useful when
  2273. `optim="adamw_anyprecision"`).
  2274. Example:
  2275. ```py
  2276. >>> from transformers import TrainingArguments
  2277. >>> args = TrainingArguments("working_dir")
  2278. >>> args = args.set_optimizer(name="adamw_torch", beta1=0.8)
  2279. >>> args.optim
  2280. 'adamw_torch'
  2281. ```
  2282. """
  2283. self.optim = OptimizerNames(name)
  2284. self.learning_rate = learning_rate
  2285. self.weight_decay = weight_decay
  2286. self.adam_beta1 = beta1
  2287. self.adam_beta2 = beta2
  2288. self.adam_epsilon = epsilon
  2289. self.optim_args = args
  2290. return self
  2291. def set_lr_scheduler(
  2292. self,
  2293. name: str | SchedulerType = "linear",
  2294. num_epochs: float = 3.0,
  2295. max_steps: int = -1,
  2296. warmup_steps: float = 0,
  2297. warmup_ratio: float | None = None,
  2298. ):
  2299. """
  2300. A method that regroups all arguments linked to the learning rate scheduler and its hyperparameters.
  2301. Args:
  2302. name (`str` or [`SchedulerType`], *optional*, defaults to `"linear"`):
  2303. The scheduler type to use. See the documentation of [`SchedulerType`] for all possible values.
  2304. num_epochs(`float`, *optional*, defaults to 3.0):
  2305. Total number of training epochs to perform (if not an integer, will perform the decimal part percents
  2306. of the last epoch before stopping training).
  2307. max_steps (`int`, *optional*, defaults to -1):
  2308. If set to a positive number, the total number of training steps to perform. Overrides `num_train_epochs`.
  2309. For a finite dataset, training is reiterated through the dataset (if all data is exhausted) until
  2310. `max_steps` is reached.
  2311. warmup_steps (`float`, *optional*, defaults to 0):
  2312. Number of steps used for a linear warmup from 0 to `learning_rate`. Should be an integer or a float in range `[0,1)`.
  2313. If smaller than 1, will be interpreted as ratio of steps used for a linear warmup from 0 to `learning_rate`.
  2314. Example:
  2315. ```py
  2316. >>> from transformers import TrainingArguments
  2317. >>> args = TrainingArguments("working_dir")
  2318. >>> args = args.set_lr_scheduler(name="cosine", warmup_steps=0.05)
  2319. >>> args.warmup_steps
  2320. 0.05
  2321. ```
  2322. """
  2323. if warmup_ratio is not None:
  2324. logger.warning("warmup_ratio is deprecated and will be removed in v5.2 . Use `warmup_steps` instead.")
  2325. warmup_steps = warmup_ratio
  2326. self.lr_scheduler_type = SchedulerType(name)
  2327. self.num_train_epochs = num_epochs
  2328. self.max_steps = max_steps
  2329. self.warmup_steps = warmup_steps
  2330. return self
  2331. def set_dataloader(
  2332. self,
  2333. train_batch_size: int = 8,
  2334. eval_batch_size: int = 8,
  2335. drop_last: bool = False,
  2336. num_workers: int = 0,
  2337. pin_memory: bool = True,
  2338. persistent_workers: bool = False,
  2339. prefetch_factor: int | None = None,
  2340. auto_find_batch_size: bool = False,
  2341. ignore_data_skip: bool = False,
  2342. sampler_seed: int | None = None,
  2343. ):
  2344. """
  2345. A method that regroups all arguments linked to the dataloaders creation.
  2346. Args:
  2347. drop_last (`bool`, *optional*, defaults to `False`):
  2348. Whether to drop the last incomplete batch (if the length of the dataset is not divisible by the batch
  2349. size) or not.
  2350. num_workers (`int`, *optional*, defaults to 0):
  2351. Number of subprocesses to use for data loading (PyTorch only). 0 means that the data will be loaded in
  2352. the main process.
  2353. pin_memory (`bool`, *optional*, defaults to `True`):
  2354. Whether you want to pin memory in data loaders or not. Will default to `True`.
  2355. persistent_workers (`bool`, *optional*, defaults to `False`):
  2356. If True, the data loader will not shut down the worker processes after a dataset has been consumed
  2357. once. This allows to maintain the workers Dataset instances alive. Can potentially speed up training,
  2358. but will increase RAM usage. Will default to `False`.
  2359. prefetch_factor (`int`, *optional*):
  2360. Number of batches loaded in advance by each worker.
  2361. 2 means there will be a total of 2 * num_workers batches prefetched across all workers.
  2362. auto_find_batch_size (`bool`, *optional*, defaults to `False`)
  2363. Whether to find a batch size that will fit into memory automatically through exponential decay,
  2364. avoiding CUDA Out-of-Memory errors. Requires accelerate to be installed (`pip install accelerate`)
  2365. ignore_data_skip (`bool`, *optional*, defaults to `False`):
  2366. When resuming training, whether or not to skip the epochs and batches to get the data loading at the
  2367. same stage as in the previous training. If set to `True`, the training will begin faster (as that
  2368. skipping step can take a long time) but will not yield the same results as the interrupted training
  2369. would have.
  2370. sampler_seed (`int`, *optional*):
  2371. Random seed to be used with data samplers. If not set, random generators for data sampling will use the
  2372. same seed as `self.seed`. This can be used to ensure reproducibility of data sampling, independent of
  2373. the model seed.
  2374. Example:
  2375. ```py
  2376. >>> from transformers import TrainingArguments
  2377. >>> args = TrainingArguments("working_dir")
  2378. >>> args = args.set_dataloader(train_batch_size=16, eval_batch_size=64)
  2379. >>> args.per_device_train_batch_size
  2380. 16
  2381. ```
  2382. """
  2383. self.per_device_train_batch_size = train_batch_size
  2384. self.per_device_eval_batch_size = eval_batch_size
  2385. self.dataloader_drop_last = drop_last
  2386. self.dataloader_num_workers = num_workers
  2387. self.dataloader_pin_memory = pin_memory
  2388. self.dataloader_persistent_workers = persistent_workers
  2389. self.dataloader_prefetch_factor = prefetch_factor
  2390. self.auto_find_batch_size = auto_find_batch_size
  2391. self.ignore_data_skip = ignore_data_skip
  2392. self.data_seed = sampler_seed
  2393. return self
  2394. def _process_fsdp_args(self):
  2395. if not self.fsdp:
  2396. self.fsdp = []
  2397. elif self.fsdp is True:
  2398. self.fsdp = [FSDPOption.FULL_SHARD]
  2399. elif isinstance(self.fsdp, str):
  2400. self.fsdp = [FSDPOption(s) for s in self.fsdp.split()]
  2401. if self.fsdp == [FSDPOption.OFFLOAD]:
  2402. raise ValueError(
  2403. "`--fsdp offload` can't work on its own. It needs to be added to `--fsdp full_shard` or "
  2404. '`--fsdp shard_grad_op`. For example, `--fsdp "full_shard offload"`.'
  2405. )
  2406. elif FSDPOption.FULL_SHARD in self.fsdp and FSDPOption.SHARD_GRAD_OP in self.fsdp:
  2407. raise ValueError("`--fsdp full_shard` is not compatible with `--fsdp shard_grad_op`.")
  2408. if self.gradient_checkpointing and (
  2409. FSDPOption.FULL_SHARD in self.fsdp or FSDPOption.HYBRID_SHARD in self.fsdp
  2410. ):
  2411. logger.warning(
  2412. "When using FSDP full shard, instead of using `gradient_checkpointing` in TrainingArguments, please"
  2413. " use `activation_checkpointing` in `fsdp_config`. The former introduces a redundant AllGather"
  2414. " operation in backward pass. Reference: https://github.com/huggingface/transformers/issues/30404"
  2415. )
  2416. if self.fsdp_config is None:
  2417. self.fsdp_config = {}
  2418. if isinstance(self.fsdp_config, str):
  2419. if len(self.fsdp) == 0:
  2420. warnings.warn("`--fsdp_config` is useful only when `--fsdp` is specified.")
  2421. with open(self.fsdp_config, encoding="utf-8") as f:
  2422. self.fsdp_config = json.load(f)
  2423. if self.fsdp_config is not None and isinstance(self.fsdp_config, dict):
  2424. for k in list(self.fsdp_config.keys()):
  2425. if k.startswith("fsdp_"):
  2426. v = self.fsdp_config.pop(k)
  2427. self.fsdp_config[k[5:]] = v
  2428. self.fsdp_config["min_num_params"] = self.fsdp_config.get("min_num_params", 0)
  2429. # Normalize transformer_layer_cls_to_wrap from string to list
  2430. if isinstance(self.fsdp_config.get("transformer_layer_cls_to_wrap", None), str):
  2431. self.fsdp_config["transformer_layer_cls_to_wrap"] = [self.fsdp_config["transformer_layer_cls_to_wrap"]]
  2432. if len(self.fsdp) == 0 and self.fsdp_config["min_num_params"] > 0:
  2433. warnings.warn("`min_num_params` is useful only when `--fsdp` is specified.")
  2434. if len(self.fsdp) == 0 and self.fsdp_config.get("transformer_layer_cls_to_wrap", None) is not None:
  2435. warnings.warn("`transformer_layer_cls_to_wrap` is useful only when `--fsdp` is specified.")
  2436. if (
  2437. len(self.fsdp) > 0
  2438. and self.fsdp_config["min_num_params"] > 0
  2439. and self.fsdp_config.get("transformer_layer_cls_to_wrap", None) is not None
  2440. ):
  2441. raise ValueError("`min_num_params` and `transformer_layer_cls_to_wrap` are mutually exclusive.")
  2442. self.fsdp_config["xla"] = self.fsdp_config.get("xla", False)
  2443. self.fsdp_config["xla_fsdp_v2"] = self.fsdp_config.get("xla_fsdp_v2", False)
  2444. self.fsdp_config["xla_fsdp_grad_ckpt"] = self.fsdp_config.get("xla_fsdp_grad_ckpt", False)
  2445. if self.fsdp_config["xla"]:
  2446. if len(self.fsdp) > 0:
  2447. # Copy to avoid mutating the original (needed for JSON serialization)
  2448. self.xla_fsdp_config = self.fsdp_config.get("xla_fsdp_settings", {}).copy()
  2449. # Convert string dtype names to torch.dtype
  2450. if "compute_dtype" in self.xla_fsdp_config:
  2451. self.xla_fsdp_config["compute_dtype"] = getattr(torch, self.xla_fsdp_config["compute_dtype"])
  2452. if "buffer_dtype" in self.xla_fsdp_config:
  2453. self.xla_fsdp_config["buffer_dtype"] = getattr(torch, self.xla_fsdp_config["buffer_dtype"])
  2454. else:
  2455. warnings.warn("XLA FSDP can be used only when `--fsdp` is specified.")
  2456. else:
  2457. if self.fsdp_config["xla_fsdp_grad_ckpt"]:
  2458. warnings.warn("`--xla_fsdp_grad_ckpt` is useful only when `--xla` is set to true.")
  2459. # Build kwargs for Accelerate's FSDPPlugin
  2460. fsdp_plugin_args = None
  2461. if len(self.fsdp) > 0 and not self.fsdp_config["xla"]:
  2462. from accelerate.utils.constants import (
  2463. FSDP_AUTO_WRAP_POLICY,
  2464. FSDP_SHARDING_STRATEGY,
  2465. )
  2466. fsdp_plugin_args = {}
  2467. fsdp_sharding = None
  2468. for fsdp_option in self.fsdp:
  2469. if fsdp_option.upper() in FSDP_SHARDING_STRATEGY:
  2470. fsdp_sharding = fsdp_option
  2471. elif fsdp_option == FSDPOption.OFFLOAD:
  2472. fsdp_plugin_args["cpu_offload"] = True
  2473. elif fsdp_option == FSDPOption.AUTO_WRAP:
  2474. fsdp_plugin_args["auto_wrap_policy"] = FSDP_AUTO_WRAP_POLICY[0]
  2475. if self.fsdp_config["min_num_params"] > 0:
  2476. fsdp_plugin_args["min_num_params"] = self.fsdp_config["min_num_params"]
  2477. fsdp_plugin_args["auto_wrap_policy"] = FSDP_AUTO_WRAP_POLICY[1]
  2478. elif self.fsdp_config.get("transformer_layer_cls_to_wrap", None) is not None:
  2479. fsdp_plugin_args["transformer_cls_names_to_wrap"] = ",".join(
  2480. self.fsdp_config["transformer_layer_cls_to_wrap"]
  2481. )
  2482. fsdp_version = int(self.fsdp_config.get("version", 1))
  2483. fsdp_plugin_args["fsdp_version"] = fsdp_version
  2484. prefetch_policy = self.fsdp_config.get("backward_prefetch", "NO_PREFETCH")
  2485. if fsdp_version == 2:
  2486. # full_shard → True (reshard after forward), shard_grad_op → False
  2487. default_reshard = fsdp_sharding != "shard_grad_op" if fsdp_sharding else True
  2488. fsdp_plugin_args["reshard_after_forward"] = str_to_bool(
  2489. str(self.fsdp_config.get("reshard_after_forward", default_reshard)).lower()
  2490. )
  2491. else:
  2492. fsdp_plugin_args["forward_prefetch"] = str_to_bool(
  2493. str(self.fsdp_config.get("forward_prefetch", "false")).lower()
  2494. )
  2495. fsdp_plugin_args["backward_prefetch"] = prefetch_policy.upper()
  2496. # Pass sharding strategy as reshard_after_forward (accelerate converts it to ShardingStrategy)
  2497. default_reshard = fsdp_sharding.upper() if fsdp_sharding else "FULL_SHARD"
  2498. fsdp_plugin_args["reshard_after_forward"] = str(
  2499. self.fsdp_config.get("reshard_after_forward", default_reshard)
  2500. ).lower()
  2501. fsdp_plugin_args["use_orig_params"] = str_to_bool(
  2502. str(self.fsdp_config.get("use_orig_params", "true")).lower()
  2503. )
  2504. sync_module_states = str(self.fsdp_config.get("sync_module_states", "true")).lower()
  2505. cpu_ram_efficient_loading = str(self.fsdp_config.get("cpu_ram_efficient_loading", "false")).lower()
  2506. if sync_module_states == "false" and cpu_ram_efficient_loading == "true":
  2507. # Without sync, non-main processes would have random weights
  2508. raise ValueError('`sync_module_states` must be `"True"` if `cpu_ram_efficient_loading` is `"True"`')
  2509. # Set env var to suppress Accelerate warning and for transformers to read
  2510. fsdp_plugin_args["cpu_ram_efficient_loading"] = str_to_bool(cpu_ram_efficient_loading)
  2511. os.environ["FSDP_CPU_RAM_EFFICIENT_LOADING"] = cpu_ram_efficient_loading
  2512. fsdp_plugin_args["sync_module_states"] = str_to_bool(sync_module_states)
  2513. return fsdp_plugin_args
  2514. class ParallelMode(Enum):
  2515. NOT_PARALLEL = "not_parallel"
  2516. NOT_DISTRIBUTED = "not_distributed"
  2517. DISTRIBUTED = "distributed"
  2518. SAGEMAKER_MODEL_PARALLEL = "sagemaker_model_parallel"
  2519. SAGEMAKER_DATA_PARALLEL = "sagemaker_data_parallel"
  2520. TPU = "tpu"
  2521. def str_to_bool(value, to_bool: bool = True) -> int | bool:
  2522. """
  2523. Converts a string representation of truth to `True` (1) or `False` (0).
  2524. True values are `y`, `yes`, `t`, `true`, `on`, and `1`; False value are `n`, `no`, `f`, `false`, `off`, and `0`;
  2525. """
  2526. value = value.lower()
  2527. if value in ("y", "yes", "t", "true", "on", "1"):
  2528. return 1 if not to_bool else True
  2529. elif value in ("n", "no", "f", "false", "off", "0"):
  2530. return 0 if not to_bool else False
  2531. else:
  2532. raise ValueError(f"invalid truth value {value}")