training_args.py 155 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099
  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 io
  16. import json
  17. import math
  18. import os
  19. import warnings
  20. from dataclasses import asdict, dataclass, field, fields
  21. from datetime import timedelta
  22. from enum import Enum
  23. from pathlib import Path
  24. from typing import Any, Dict, List, Optional, Union
  25. from huggingface_hub import get_full_repo_name
  26. from packaging import version
  27. from .debug_utils import DebugOption
  28. from .trainer_utils import (
  29. EvaluationStrategy,
  30. FSDPOption,
  31. HubStrategy,
  32. IntervalStrategy,
  33. SchedulerType,
  34. )
  35. from .utils import (
  36. ACCELERATE_MIN_VERSION,
  37. ExplicitEnum,
  38. cached_property,
  39. is_accelerate_available,
  40. is_ipex_available,
  41. is_safetensors_available,
  42. is_sagemaker_dp_enabled,
  43. is_sagemaker_mp_enabled,
  44. is_torch_available,
  45. is_torch_bf16_cpu_available,
  46. is_torch_bf16_gpu_available,
  47. is_torch_mlu_available,
  48. is_torch_mps_available,
  49. is_torch_musa_available,
  50. is_torch_neuroncore_available,
  51. is_torch_npu_available,
  52. is_torch_tf32_available,
  53. is_torch_xla_available,
  54. is_torch_xpu_available,
  55. logging,
  56. requires_backends,
  57. )
  58. from .utils.generic import strtobool
  59. from .utils.import_utils import is_optimum_neuron_available
  60. logger = logging.get_logger(__name__)
  61. log_levels = logging.get_log_levels_dict().copy()
  62. trainer_log_levels = dict(**log_levels, passive=-1)
  63. if is_torch_available():
  64. import torch
  65. import torch.distributed as dist
  66. from .pytorch_utils import is_torch_greater_or_equal_than_2_0
  67. if is_accelerate_available():
  68. from accelerate.state import AcceleratorState, PartialState
  69. from accelerate.utils import DistributedType
  70. from .trainer_pt_utils import AcceleratorConfig
  71. if is_torch_xla_available():
  72. import torch_xla.core.xla_model as xm
  73. if is_torch_neuroncore_available(check_device=False):
  74. # torchrun support
  75. # https://github.com/pytorch/xla/pull/3609
  76. if os.environ.get("TORCHELASTIC_RUN_ID"):
  77. if is_optimum_neuron_available():
  78. logger.info(
  79. "Make sure that you are performing the training with the NeuronTrainer from optimum[neuron], this "
  80. "will fail otherwise."
  81. )
  82. else:
  83. logger.warning(
  84. "Please use the NeuronTrainer from optimum[neuron] instead of the Transformers library to perform "
  85. "training on AWS Trainium instances. More information here: "
  86. "https://github.com/huggingface/optimum-neuron"
  87. )
  88. import torch_xla.distributed.xla_backend as xbn
  89. if not isinstance(dist.group.WORLD, xbn.ProcessGroupXla):
  90. dist.init_process_group(backend="xla")
  91. if not isinstance(dist.group.WORLD, xbn.ProcessGroupXla):
  92. raise AssertionError("Failed to initialize torch.distributed process group using XLA backend.")
  93. if is_sagemaker_mp_enabled():
  94. import smdistributed.modelparallel.torch as smp
  95. smp.init()
  96. def default_logdir() -> str:
  97. """
  98. Same default as PyTorch
  99. """
  100. import socket
  101. from datetime import datetime
  102. current_time = datetime.now().strftime("%b%d_%H-%M-%S")
  103. return os.path.join("runs", current_time + "_" + socket.gethostname())
  104. def get_int_from_env(env_keys, default):
  105. """Returns the first positive env value found in the `env_keys` list or the default."""
  106. for e in env_keys:
  107. val = int(os.environ.get(e, -1))
  108. if val >= 0:
  109. return val
  110. return default
  111. def get_xla_device_type(device: "torch.device") -> Optional[str]:
  112. """
  113. Returns the xla device type (CPU|GPU|TPU) or None if the device is a non-xla device.
  114. """
  115. if is_torch_xla_available():
  116. if device.type == "cpu":
  117. return "CPU"
  118. return xm.xla_real_devices([device])[0].split(":")[0]
  119. return None
  120. class OptimizerNames(ExplicitEnum):
  121. """
  122. Stores the acceptable string identifiers for optimizers.
  123. """
  124. ADAMW_HF = "adamw_hf"
  125. ADAMW_TORCH = "adamw_torch"
  126. ADAMW_TORCH_FUSED = "adamw_torch_fused"
  127. ADAMW_TORCH_XLA = "adamw_torch_xla"
  128. ADAMW_TORCH_NPU_FUSED = "adamw_torch_npu_fused"
  129. ADAMW_APEX_FUSED = "adamw_apex_fused"
  130. ADAFACTOR = "adafactor"
  131. ADAMW_ANYPRECISION = "adamw_anyprecision"
  132. ADAMW_TORCH_4BIT = "adamw_torch_4bit"
  133. ADEMAMIX = "ademamix"
  134. SGD = "sgd"
  135. ADAGRAD = "adagrad"
  136. ADAMW_BNB = "adamw_bnb_8bit"
  137. ADAMW_8BIT = "adamw_8bit" # just an alias for adamw_bnb_8bit
  138. ADEMAMIX_8BIT = "ademamix_8bit"
  139. LION_8BIT = "lion_8bit"
  140. LION = "lion_32bit"
  141. PAGED_ADAMW = "paged_adamw_32bit"
  142. PAGED_ADAMW_8BIT = "paged_adamw_8bit"
  143. PAGED_ADEMAMIX = "paged_ademamix_32bit"
  144. PAGED_ADEMAMIX_8BIT = "paged_ademamix_8bit"
  145. PAGED_LION = "paged_lion_32bit"
  146. PAGED_LION_8BIT = "paged_lion_8bit"
  147. RMSPROP = "rmsprop"
  148. RMSPROP_BNB = "rmsprop_bnb"
  149. RMSPROP_8BIT = "rmsprop_bnb_8bit"
  150. RMSPROP_32BIT = "rmsprop_bnb_32bit"
  151. GALORE_ADAMW = "galore_adamw"
  152. GALORE_ADAMW_8BIT = "galore_adamw_8bit"
  153. GALORE_ADAFACTOR = "galore_adafactor"
  154. GALORE_ADAMW_LAYERWISE = "galore_adamw_layerwise"
  155. GALORE_ADAMW_8BIT_LAYERWISE = "galore_adamw_8bit_layerwise"
  156. GALORE_ADAFACTOR_LAYERWISE = "galore_adafactor_layerwise"
  157. LOMO = "lomo"
  158. ADALOMO = "adalomo"
  159. GROKADAMW = "grokadamw"
  160. SCHEDULE_FREE_ADAMW = "schedule_free_adamw"
  161. SCHEDULE_FREE_SGD = "schedule_free_sgd"
  162. # Sometimes users will pass in a `str` repr of a dict in the CLI
  163. # We need to track what fields those can be. Each time a new arg
  164. # has a dict type, it must be added to this list.
  165. # Important: These should be typed with Optional[Union[dict,str,...]]
  166. _VALID_DICT_FIELDS = [
  167. "accelerator_config",
  168. "fsdp_config",
  169. "deepspeed",
  170. "gradient_checkpointing_kwargs",
  171. "lr_scheduler_kwargs",
  172. ]
  173. def _convert_str_dict(passed_value: dict):
  174. "Safely checks that a passed value is a dictionary and converts any string values to their appropriate types."
  175. for key, value in passed_value.items():
  176. if isinstance(value, dict):
  177. passed_value[key] = _convert_str_dict(value)
  178. elif isinstance(value, str):
  179. # First check for bool and convert
  180. if value.lower() in ("true", "false"):
  181. passed_value[key] = value.lower() == "true"
  182. # Check for digit
  183. elif value.isdigit():
  184. passed_value[key] = int(value)
  185. elif value.replace(".", "", 1).isdigit():
  186. passed_value[key] = float(value)
  187. return passed_value
  188. # TODO: `TrainingArguments` users rely on it being fully mutable. In the future see if we can narrow this to a few keys: https://github.com/huggingface/transformers/pull/25903
  189. @dataclass
  190. class TrainingArguments:
  191. """
  192. TrainingArguments is the subset of the arguments we use in our example scripts **which relate to the training loop
  193. itself**.
  194. Using [`HfArgumentParser`] we can turn this class into
  195. [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the
  196. command line.
  197. Parameters:
  198. output_dir (`str`):
  199. The output directory where the model predictions and checkpoints will be written.
  200. overwrite_output_dir (`bool`, *optional*, defaults to `False`):
  201. If `True`, overwrite the content of the output directory. Use this to continue training if `output_dir`
  202. points to a checkpoint directory.
  203. do_train (`bool`, *optional*, defaults to `False`):
  204. Whether to run training or not. This argument is not directly used by [`Trainer`], it's intended to be used
  205. by your training/evaluation scripts instead. See the [example
  206. scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details.
  207. do_eval (`bool`, *optional*):
  208. Whether to run evaluation on the validation set or not. Will be set to `True` if `eval_strategy` is
  209. different from `"no"`. This argument is not directly used by [`Trainer`], it's intended to be used by your
  210. training/evaluation scripts instead. See the [example
  211. scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details.
  212. do_predict (`bool`, *optional*, defaults to `False`):
  213. Whether to run predictions on the test set or not. This argument is not directly used by [`Trainer`], it's
  214. intended to be used by your training/evaluation scripts instead. See the [example
  215. scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details.
  216. eval_strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"no"`):
  217. The evaluation strategy to adopt during training. Possible values are:
  218. - `"no"`: No evaluation is done during training.
  219. - `"steps"`: Evaluation is done (and logged) every `eval_steps`.
  220. - `"epoch"`: Evaluation is done at the end of each epoch.
  221. prediction_loss_only (`bool`, *optional*, defaults to `False`):
  222. When performing evaluation and generating predictions, only returns the loss.
  223. per_device_train_batch_size (`int`, *optional*, defaults to 8):
  224. The batch size per GPU/XPU/TPU/MPS/NPU core/CPU for training.
  225. per_device_eval_batch_size (`int`, *optional*, defaults to 8):
  226. The batch size per GPU/XPU/TPU/MPS/NPU core/CPU for evaluation.
  227. gradient_accumulation_steps (`int`, *optional*, defaults to 1):
  228. Number of updates steps to accumulate the gradients for, before performing a backward/update pass.
  229. <Tip warning={true}>
  230. When using gradient accumulation, one step is counted as one step with backward pass. Therefore, logging,
  231. evaluation, save will be conducted every `gradient_accumulation_steps * xxx_step` training examples.
  232. </Tip>
  233. eval_accumulation_steps (`int`, *optional*):
  234. Number of predictions steps to accumulate the output tensors for, before moving the results to the CPU. If
  235. left unset, the whole predictions are accumulated on GPU/NPU/TPU before being moved to the CPU (faster but
  236. requires more memory).
  237. eval_delay (`float`, *optional*):
  238. Number of epochs or steps to wait for before the first evaluation can be performed, depending on the
  239. eval_strategy.
  240. torch_empty_cache_steps (`int`, *optional*):
  241. Number of steps to wait before calling `torch.<device>.empty_cache()`. If left unset or set to None, cache will not be emptied.
  242. <Tip>
  243. 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).
  244. </Tip>
  245. learning_rate (`float`, *optional*, defaults to 5e-5):
  246. The initial learning rate for [`AdamW`] optimizer.
  247. weight_decay (`float`, *optional*, defaults to 0):
  248. The weight decay to apply (if not zero) to all layers except all bias and LayerNorm weights in [`AdamW`]
  249. optimizer.
  250. adam_beta1 (`float`, *optional*, defaults to 0.9):
  251. The beta1 hyperparameter for the [`AdamW`] optimizer.
  252. adam_beta2 (`float`, *optional*, defaults to 0.999):
  253. The beta2 hyperparameter for the [`AdamW`] optimizer.
  254. adam_epsilon (`float`, *optional*, defaults to 1e-8):
  255. The epsilon hyperparameter for the [`AdamW`] optimizer.
  256. max_grad_norm (`float`, *optional*, defaults to 1.0):
  257. Maximum gradient norm (for gradient clipping).
  258. num_train_epochs(`float`, *optional*, defaults to 3.0):
  259. Total number of training epochs to perform (if not an integer, will perform the decimal part percents of
  260. the last epoch before stopping training).
  261. max_steps (`int`, *optional*, defaults to -1):
  262. If set to a positive number, the total number of training steps to perform. Overrides `num_train_epochs`.
  263. For a finite dataset, training is reiterated through the dataset (if all data is exhausted) until
  264. `max_steps` is reached.
  265. lr_scheduler_type (`str` or [`SchedulerType`], *optional*, defaults to `"linear"`):
  266. The scheduler type to use. See the documentation of [`SchedulerType`] for all possible values.
  267. lr_scheduler_kwargs ('dict', *optional*, defaults to {}):
  268. The extra arguments for the lr_scheduler. See the documentation of each scheduler for possible values.
  269. warmup_ratio (`float`, *optional*, defaults to 0.0):
  270. Ratio of total training steps used for a linear warmup from 0 to `learning_rate`.
  271. warmup_steps (`int`, *optional*, defaults to 0):
  272. Number of steps used for a linear warmup from 0 to `learning_rate`. Overrides any effect of `warmup_ratio`.
  273. log_level (`str`, *optional*, defaults to `passive`):
  274. Logger log level to use on the main process. Possible choices are the log levels as strings: 'debug',
  275. 'info', 'warning', 'error' and 'critical', plus a 'passive' level which doesn't set anything and keeps the
  276. current log level for the Transformers library (which will be `"warning"` by default).
  277. log_level_replica (`str`, *optional*, defaults to `"warning"`):
  278. Logger log level to use on replicas. Same choices as `log_level`"
  279. log_on_each_node (`bool`, *optional*, defaults to `True`):
  280. In multinode distributed training, whether to log using `log_level` once per node, or only on the main
  281. node.
  282. logging_dir (`str`, *optional*):
  283. [TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to
  284. *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***.
  285. logging_strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"steps"`):
  286. The logging strategy to adopt during training. Possible values are:
  287. - `"no"`: No logging is done during training.
  288. - `"epoch"`: Logging is done at the end of each epoch.
  289. - `"steps"`: Logging is done every `logging_steps`.
  290. logging_first_step (`bool`, *optional*, defaults to `False`):
  291. Whether to log the first `global_step` or not.
  292. logging_steps (`int` or `float`, *optional*, defaults to 500):
  293. Number of update steps between two logs if `logging_strategy="steps"`. Should be an integer or a float in
  294. range `[0,1)`. If smaller than 1, will be interpreted as ratio of total training steps.
  295. logging_nan_inf_filter (`bool`, *optional*, defaults to `True`):
  296. Whether to filter `nan` and `inf` losses for logging. If set to `True` the loss of every step that is `nan`
  297. or `inf` is filtered and the average loss of the current logging window is taken instead.
  298. <Tip>
  299. `logging_nan_inf_filter` only influences the logging of loss values, it does not change the behavior the
  300. gradient is computed or applied to the model.
  301. </Tip>
  302. save_strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"steps"`):
  303. The checkpoint save strategy to adopt during training. Possible values are:
  304. - `"no"`: No save is done during training.
  305. - `"epoch"`: Save is done at the end of each epoch.
  306. - `"steps"`: Save is done every `save_steps`.
  307. If `"epoch"` or `"steps"` is chosen, saving will also be performed at the
  308. very end of training, always.
  309. save_steps (`int` or `float`, *optional*, defaults to 500):
  310. Number of updates steps before two checkpoint saves if `save_strategy="steps"`. Should be an integer or a
  311. float in range `[0,1)`. If smaller than 1, will be interpreted as ratio of total training steps.
  312. save_total_limit (`int`, *optional*):
  313. If a value is passed, will limit the total amount of checkpoints. Deletes the older checkpoints in
  314. `output_dir`. When `load_best_model_at_end` is enabled, the "best" checkpoint according to
  315. `metric_for_best_model` will always be retained in addition to the most recent ones. For example, for
  316. `save_total_limit=5` and `load_best_model_at_end`, the four last checkpoints will always be retained
  317. alongside the best model. When `save_total_limit=1` and `load_best_model_at_end`, it is possible that two
  318. checkpoints are saved: the last one and the best one (if they are different).
  319. save_safetensors (`bool`, *optional*, defaults to `True`):
  320. Use [safetensors](https://huggingface.co/docs/safetensors) saving and loading for state dicts instead of
  321. default `torch.load` and `torch.save`.
  322. save_on_each_node (`bool`, *optional*, defaults to `False`):
  323. When doing multi-node distributed training, whether to save models and checkpoints on each node, or only on
  324. the main one.
  325. This should not be activated when the different nodes use the same storage as the files will be saved with
  326. the same names for each node.
  327. save_only_model (`bool`, *optional*, defaults to `False`):
  328. When checkpointing, whether to only save the model, or also the optimizer, scheduler & rng state.
  329. Note that when this is true, you won't be able to resume training from checkpoint.
  330. This enables you to save storage by not storing the optimizer, scheduler & rng state.
  331. You can only load the model using `from_pretrained` with this option set to `True`.
  332. restore_callback_states_from_checkpoint (`bool`, *optional*, defaults to `False`):
  333. Whether to restore the callback states from the checkpoint. If `True`, will override
  334. callbacks passed to the `Trainer` if they exist in the checkpoint."
  335. use_cpu (`bool`, *optional*, defaults to `False`):
  336. Whether or not to use cpu. If set to False, we will use cuda or mps device if available.
  337. seed (`int`, *optional*, defaults to 42):
  338. Random seed that will be set at the beginning of training. To ensure reproducibility across runs, use the
  339. [`~Trainer.model_init`] function to instantiate the model if it has some randomly initialized parameters.
  340. data_seed (`int`, *optional*):
  341. Random seed to be used with data samplers. If not set, random generators for data sampling will use the
  342. same seed as `seed`. This can be used to ensure reproducibility of data sampling, independent of the model
  343. seed.
  344. jit_mode_eval (`bool`, *optional*, defaults to `False`):
  345. Whether or not to use PyTorch jit trace for inference.
  346. use_ipex (`bool`, *optional*, defaults to `False`):
  347. Use Intel extension for PyTorch when it is available. [IPEX
  348. installation](https://github.com/intel/intel-extension-for-pytorch).
  349. bf16 (`bool`, *optional*, defaults to `False`):
  350. Whether to use bf16 16-bit (mixed) precision training instead of 32-bit training. Requires Ampere or higher
  351. NVIDIA architecture or using CPU (use_cpu) or Ascend NPU. This is an experimental API and it may change.
  352. fp16 (`bool`, *optional*, defaults to `False`):
  353. Whether to use fp16 16-bit (mixed) precision training instead of 32-bit training.
  354. fp16_opt_level (`str`, *optional*, defaults to 'O1'):
  355. For `fp16` training, Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']. See details on
  356. the [Apex documentation](https://nvidia.github.io/apex/amp).
  357. fp16_backend (`str`, *optional*, defaults to `"auto"`):
  358. This argument is deprecated. Use `half_precision_backend` instead.
  359. half_precision_backend (`str`, *optional*, defaults to `"auto"`):
  360. The backend to use for mixed precision training. Must be one of `"auto", "apex", "cpu_amp"`. `"auto"` will
  361. use CPU/CUDA AMP or APEX depending on the PyTorch version detected, while the other choices will force the
  362. requested backend.
  363. bf16_full_eval (`bool`, *optional*, defaults to `False`):
  364. Whether to use full bfloat16 evaluation instead of 32-bit. This will be faster and save memory but can harm
  365. metric values. This is an experimental API and it may change.
  366. fp16_full_eval (`bool`, *optional*, defaults to `False`):
  367. Whether to use full float16 evaluation instead of 32-bit. This will be faster and save memory but can harm
  368. metric values.
  369. tf32 (`bool`, *optional*):
  370. Whether to enable the TF32 mode, available in Ampere and newer GPU architectures. The default value depends
  371. on PyTorch's version default of `torch.backends.cuda.matmul.allow_tf32`. For more details please refer to
  372. the [TF32](https://huggingface.co/docs/transformers/perf_train_gpu_one#tf32) documentation. This is an
  373. experimental API and it may change.
  374. local_rank (`int`, *optional*, defaults to -1):
  375. Rank of the process during distributed training.
  376. ddp_backend (`str`, *optional*):
  377. The backend to use for distributed training. Must be one of `"nccl"`, `"mpi"`, `"ccl"`, `"gloo"`, `"hccl"`.
  378. tpu_num_cores (`int`, *optional*):
  379. When training on TPU, the number of TPU cores (automatically passed by launcher script).
  380. dataloader_drop_last (`bool`, *optional*, defaults to `False`):
  381. Whether to drop the last incomplete batch (if the length of the dataset is not divisible by the batch size)
  382. or not.
  383. eval_steps (`int` or `float`, *optional*):
  384. Number of update steps between two evaluations if `eval_strategy="steps"`. Will default to the same
  385. value as `logging_steps` if not set. Should be an integer or a float in range `[0,1)`. If smaller than 1,
  386. will be interpreted as ratio of total training steps.
  387. dataloader_num_workers (`int`, *optional*, defaults to 0):
  388. Number of subprocesses to use for data loading (PyTorch only). 0 means that the data will be loaded in the
  389. main process.
  390. past_index (`int`, *optional*, defaults to -1):
  391. Some models like [TransformerXL](../model_doc/transformerxl) or [XLNet](../model_doc/xlnet) can make use of
  392. the past hidden states for their predictions. If this argument is set to a positive int, the `Trainer` will
  393. use the corresponding output (usually index 2) as the past state and feed it to the model at the next
  394. training step under the keyword argument `mems`.
  395. run_name (`str`, *optional*, defaults to `output_dir`):
  396. A descriptor for the run. Typically used for [wandb](https://www.wandb.com/),
  397. [mlflow](https://www.mlflow.org/) and [comet](https://www.comet.com/site) logging. If not specified, will
  398. be the same as `output_dir`.
  399. disable_tqdm (`bool`, *optional*):
  400. Whether or not to disable the tqdm progress bars and table of metrics produced by
  401. [`~notebook.NotebookTrainingTracker`] in Jupyter Notebooks. Will default to `True` if the logging level is
  402. set to warn or lower (default), `False` otherwise.
  403. remove_unused_columns (`bool`, *optional*, defaults to `True`):
  404. Whether or not to automatically remove the columns unused by the model forward method.
  405. label_names (`List[str]`, *optional*):
  406. The list of keys in your dictionary of inputs that correspond to the labels.
  407. Will eventually default to the list of argument names accepted by the model that contain the word "label",
  408. except if the model used is one of the `XxxForQuestionAnswering` in which case it will also include the
  409. `["start_positions", "end_positions"]` keys.
  410. load_best_model_at_end (`bool`, *optional*, defaults to `False`):
  411. Whether or not to load the best model found during training at the end of training. When this option is
  412. enabled, the best checkpoint will always be saved. See
  413. [`save_total_limit`](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments.save_total_limit)
  414. for more.
  415. <Tip>
  416. When set to `True`, the parameters `save_strategy` needs to be the same as `eval_strategy`, and in
  417. the case it is "steps", `save_steps` must be a round multiple of `eval_steps`.
  418. </Tip>
  419. metric_for_best_model (`str`, *optional*):
  420. Use in conjunction with `load_best_model_at_end` to specify the metric to use to compare two different
  421. models. Must be the name of a metric returned by the evaluation with or without the prefix `"eval_"`. Will
  422. default to `"loss"` if unspecified and `load_best_model_at_end=True` (to use the evaluation loss).
  423. If you set this value, `greater_is_better` will default to `True`. Don't forget to set it to `False` if
  424. your metric is better when lower.
  425. greater_is_better (`bool`, *optional*):
  426. Use in conjunction with `load_best_model_at_end` and `metric_for_best_model` to specify if better models
  427. should have a greater metric or not. Will default to:
  428. - `True` if `metric_for_best_model` is set to a value that doesn't end in `"loss"`.
  429. - `False` if `metric_for_best_model` is not set, or set to a value that ends in `"loss"`.
  430. ignore_data_skip (`bool`, *optional*, defaults to `False`):
  431. When resuming training, whether or not to skip the epochs and batches to get the data loading at the same
  432. stage as in the previous training. If set to `True`, the training will begin faster (as that skipping step
  433. can take a long time) but will not yield the same results as the interrupted training would have.
  434. fsdp (`bool`, `str` or list of [`~trainer_utils.FSDPOption`], *optional*, defaults to `''`):
  435. Use PyTorch Distributed Parallel Training (in distributed training only).
  436. A list of options along the following:
  437. - `"full_shard"`: Shard parameters, gradients and optimizer states.
  438. - `"shard_grad_op"`: Shard optimizer states and gradients.
  439. - `"hybrid_shard"`: Apply `FULL_SHARD` within a node, and replicate parameters across nodes.
  440. - `"hybrid_shard_zero2"`: Apply `SHARD_GRAD_OP` within a node, and replicate parameters across nodes.
  441. - `"offload"`: Offload parameters and gradients to CPUs (only compatible with `"full_shard"` and
  442. `"shard_grad_op"`).
  443. - `"auto_wrap"`: Automatically recursively wrap layers with FSDP using `default_auto_wrap_policy`.
  444. fsdp_config (`str` or `dict`, *optional*):
  445. Config to be used with fsdp (Pytorch Distributed Parallel Training). The value is either a location of
  446. fsdp json config file (e.g., `fsdp_config.json`) or an already loaded json file as `dict`.
  447. A List of config and its options:
  448. - min_num_params (`int`, *optional*, defaults to `0`):
  449. FSDP's minimum number of parameters for Default Auto Wrapping. (useful only when `fsdp` field is
  450. passed).
  451. - transformer_layer_cls_to_wrap (`List[str]`, *optional*):
  452. List of transformer layer class names (case-sensitive) to wrap, e.g, `BertLayer`, `GPTJBlock`,
  453. `T5Block` .... (useful only when `fsdp` flag is passed).
  454. - backward_prefetch (`str`, *optional*)
  455. FSDP's backward prefetch mode. Controls when to prefetch next set of parameters (useful only when
  456. `fsdp` field is passed).
  457. A list of options along the following:
  458. - `"backward_pre"` : Prefetches the next set of parameters before the current set of parameter's
  459. gradient
  460. computation.
  461. - `"backward_post"` : This prefetches the next set of parameters after the current set of
  462. parameter’s
  463. gradient computation.
  464. - forward_prefetch (`bool`, *optional*, defaults to `False`)
  465. FSDP's forward prefetch mode (useful only when `fsdp` field is passed).
  466. If `"True"`, then FSDP explicitly prefetches the next upcoming all-gather while executing in the
  467. forward pass.
  468. - limit_all_gathers (`bool`, *optional*, defaults to `False`)
  469. FSDP's limit_all_gathers (useful only when `fsdp` field is passed).
  470. If `"True"`, FSDP explicitly synchronizes the CPU thread to prevent too many in-flight
  471. all-gathers.
  472. - use_orig_params (`bool`, *optional*, defaults to `True`)
  473. If `"True"`, allows non-uniform `requires_grad` during init, which means support for interspersed
  474. frozen and trainable paramteres. Useful in cases such as parameter-efficient fine-tuning. Please
  475. refer this
  476. [blog](https://dev-discuss.pytorch.org/t/rethinking-pytorch-fully-sharded-data-parallel-fsdp-from-first-principles/1019
  477. - sync_module_states (`bool`, *optional*, defaults to `True`)
  478. If `"True"`, each individually wrapped FSDP unit will broadcast module parameters from rank 0 to
  479. ensure they are the same across all ranks after initialization
  480. - cpu_ram_efficient_loading (`bool`, *optional*, defaults to `False`)
  481. If `"True"`, only the first process loads the pretrained model checkpoint while all other processes
  482. have empty weights. When this setting as `"True"`, `sync_module_states` also must to be `"True"`,
  483. otherwise all the processes except the main process would have random weights leading to unexpected
  484. behaviour during training.
  485. - activation_checkpointing (`bool`, *optional*, defaults to `False`):
  486. If `"True"`, activation checkpointing is a technique to reduce memory usage by clearing activations of
  487. certain layers and recomputing them during a backward pass. Effectively, this trades extra
  488. computation time for reduced memory usage.
  489. - xla (`bool`, *optional*, defaults to `False`):
  490. Whether to use PyTorch/XLA Fully Sharded Data Parallel Training. This is an experimental feature
  491. and its API may evolve in the future.
  492. - xla_fsdp_settings (`dict`, *optional*)
  493. The value is a dictionary which stores the XLA FSDP wrapping parameters.
  494. For a complete list of options, please see [here](
  495. https://github.com/pytorch/xla/blob/master/torch_xla/distributed/fsdp/xla_fully_sharded_data_parallel.py).
  496. - xla_fsdp_grad_ckpt (`bool`, *optional*, defaults to `False`):
  497. Will use gradient checkpointing over each nested XLA FSDP wrapped layer. This setting can only be
  498. used when the xla flag is set to true, and an auto wrapping policy is specified through
  499. fsdp_min_num_params or fsdp_transformer_layer_cls_to_wrap.
  500. deepspeed (`str` or `dict`, *optional*):
  501. Use [Deepspeed](https://github.com/microsoft/deepspeed). This is an experimental feature and its API may
  502. evolve in the future. The value is either the location of DeepSpeed json config file (e.g.,
  503. `ds_config.json`) or an already loaded json file as a `dict`"
  504. <Tip warning={true}>
  505. If enabling any Zero-init, make sure that your model is not initialized until
  506. *after* initializing the `TrainingArguments`, else it will not be applied.
  507. </Tip>
  508. accelerator_config (`str`, `dict`, or `AcceleratorConfig`, *optional*):
  509. Config to be used with the internal `Accelerator` implementation. The value is either a location of
  510. accelerator json config file (e.g., `accelerator_config.json`), an already loaded json file as `dict`,
  511. or an instance of [`~trainer_pt_utils.AcceleratorConfig`].
  512. A list of config and its options:
  513. - split_batches (`bool`, *optional*, defaults to `False`):
  514. Whether or not the accelerator should split the batches yielded by the dataloaders across the devices. If
  515. `True` the actual batch size used will be the same on any kind of distributed processes, but it must be a
  516. round multiple of the `num_processes` you are using. If `False`, actual batch size used will be the one set
  517. in your script multiplied by the number of processes.
  518. - dispatch_batches (`bool`, *optional*):
  519. If set to `True`, the dataloader prepared by the Accelerator is only iterated through on the main process
  520. and then the batches are split and broadcast to each process. Will default to `True` for `DataLoader` whose
  521. underlying dataset is an `IterableDataset`, `False` otherwise.
  522. - even_batches (`bool`, *optional*, defaults to `True`):
  523. If set to `True`, in cases where the total batch size across all processes does not exactly divide the
  524. dataset, samples at the start of the dataset will be duplicated so the batch can be divided equally among
  525. all workers.
  526. - use_seedable_sampler (`bool`, *optional*, defaults to `True`):
  527. Whether or not use a fully seedable random sampler ([`accelerate.data_loader.SeedableRandomSampler`]). Ensures
  528. training results are fully reproducable using a different sampling technique. While seed-to-seed results
  529. may differ, on average the differences are neglible when using multiple different seeds to compare. Should
  530. also be ran with [`~utils.set_seed`] for the best results.
  531. - use_configured_state (`bool`, *optional*, defaults to `False`):
  532. Whether or not to use a pre-configured `AcceleratorState` or `PartialState` defined before calling `TrainingArguments`.
  533. If `True`, an `Accelerator` or `PartialState` must be initialized. Note that by doing so, this could lead to issues
  534. with hyperparameter tuning.
  535. label_smoothing_factor (`float`, *optional*, defaults to 0.0):
  536. The label smoothing factor to use. Zero means no label smoothing, otherwise the underlying onehot-encoded
  537. labels are changed from 0s and 1s to `label_smoothing_factor/num_labels` and `1 - label_smoothing_factor +
  538. label_smoothing_factor/num_labels` respectively.
  539. debug (`str` or list of [`~debug_utils.DebugOption`], *optional*, defaults to `""`):
  540. Enable one or more debug features. This is an experimental feature.
  541. Possible options are:
  542. - `"underflow_overflow"`: detects overflow in model's input/outputs and reports the last frames that led to
  543. the event
  544. - `"tpu_metrics_debug"`: print debug metrics on TPU
  545. The options should be separated by whitespaces.
  546. optim (`str` or [`training_args.OptimizerNames`], *optional*, defaults to `"adamw_torch"`):
  547. The optimizer to use, such as "adamw_hf", "adamw_torch", "adamw_torch_fused", "adamw_apex_fused", "adamw_anyprecision",
  548. "adafactor". See `OptimizerNames` in [training_args.py](https://github.com/huggingface/transformers/blob/main/src/transformers/training_args.py)
  549. for a full list of optimizers.
  550. optim_args (`str`, *optional*):
  551. Optional arguments that are supplied to optimizers such as AnyPrecisionAdamW, AdEMAMix, and GaLore.
  552. group_by_length (`bool`, *optional*, defaults to `False`):
  553. Whether or not to group together samples of roughly the same length in the training dataset (to minimize
  554. padding applied and be more efficient). Only useful if applying dynamic padding.
  555. length_column_name (`str`, *optional*, defaults to `"length"`):
  556. Column name for precomputed lengths. If the column exists, grouping by length will use these values rather
  557. than computing them on train startup. Ignored unless `group_by_length` is `True` and the dataset is an
  558. instance of `Dataset`.
  559. report_to (`str` or `List[str]`, *optional*, defaults to `"all"`):
  560. The list of integrations to report the results and logs to. Supported platforms are `"azure_ml"`,
  561. `"clearml"`, `"codecarbon"`, `"comet_ml"`, `"dagshub"`, `"dvclive"`, `"flyte"`, `"mlflow"`, `"neptune"`,
  562. `"tensorboard"`, and `"wandb"`. Use `"all"` to report to all integrations installed, `"none"` for no
  563. integrations.
  564. ddp_find_unused_parameters (`bool`, *optional*):
  565. When using distributed training, the value of the flag `find_unused_parameters` passed to
  566. `DistributedDataParallel`. Will default to `False` if gradient checkpointing is used, `True` otherwise.
  567. ddp_bucket_cap_mb (`int`, *optional*):
  568. When using distributed training, the value of the flag `bucket_cap_mb` passed to `DistributedDataParallel`.
  569. ddp_broadcast_buffers (`bool`, *optional*):
  570. When using distributed training, the value of the flag `broadcast_buffers` passed to
  571. `DistributedDataParallel`. Will default to `False` if gradient checkpointing is used, `True` otherwise.
  572. dataloader_pin_memory (`bool`, *optional*, defaults to `True`):
  573. Whether you want to pin memory in data loaders or not. Will default to `True`.
  574. dataloader_persistent_workers (`bool`, *optional*, defaults to `False`):
  575. If True, the data loader will not shut down the worker processes after a dataset has been consumed once.
  576. This allows to maintain the workers Dataset instances alive. Can potentially speed up training, but will
  577. increase RAM usage. Will default to `False`.
  578. dataloader_prefetch_factor (`int`, *optional*):
  579. Number of batches loaded in advance by each worker.
  580. 2 means there will be a total of 2 * num_workers batches prefetched across all workers.
  581. skip_memory_metrics (`bool`, *optional*, defaults to `True`):
  582. Whether to skip adding of memory profiler reports to metrics. This is skipped by default because it slows
  583. down the training and evaluation speed.
  584. push_to_hub (`bool`, *optional*, defaults to `False`):
  585. Whether or not to push the model to the Hub every time the model is saved. If this is activated,
  586. `output_dir` will begin a git directory synced with the repo (determined by `hub_model_id`) and the content
  587. will be pushed each time a save is triggered (depending on your `save_strategy`). Calling
  588. [`~Trainer.save_model`] will also trigger a push.
  589. <Tip warning={true}>
  590. If `output_dir` exists, it needs to be a local clone of the repository to which the [`Trainer`] will be
  591. pushed.
  592. </Tip>
  593. resume_from_checkpoint (`str`, *optional*):
  594. The path to a folder with a valid checkpoint for your model. This argument is not directly used by
  595. [`Trainer`], it's intended to be used by your training/evaluation scripts instead. See the [example
  596. scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details.
  597. hub_model_id (`str`, *optional*):
  598. The name of the repository to keep in sync with the local *output_dir*. It can be a simple model ID in
  599. which case the model will be pushed in your namespace. Otherwise it should be the whole repository name,
  600. for instance `"user_name/model"`, which allows you to push to an organization you are a member of with
  601. `"organization_name/model"`. Will default to `user_name/output_dir_name` with *output_dir_name* being the
  602. name of `output_dir`.
  603. Will default to the name of `output_dir`.
  604. hub_strategy (`str` or [`~trainer_utils.HubStrategy`], *optional*, defaults to `"every_save"`):
  605. Defines the scope of what is pushed to the Hub and when. Possible values are:
  606. - `"end"`: push the model, its configuration, the processing class e.g. tokenizer (if passed along to the [`Trainer`]) and a
  607. draft of a model card when the [`~Trainer.save_model`] method is called.
  608. - `"every_save"`: push the model, its configuration, the processing class e.g. tokenizer (if passed along to the [`Trainer`]) and
  609. a draft of a model card each time there is a model save. The pushes are asynchronous to not block
  610. training, and in case the save are very frequent, a new push is only attempted if the previous one is
  611. finished. A last push is made with the final model at the end of training.
  612. - `"checkpoint"`: like `"every_save"` but the latest checkpoint is also pushed in a subfolder named
  613. last-checkpoint, allowing you to resume training easily with
  614. `trainer.train(resume_from_checkpoint="last-checkpoint")`.
  615. - `"all_checkpoints"`: like `"checkpoint"` but all checkpoints are pushed like they appear in the output
  616. folder (so you will get one checkpoint folder per folder in your final repository)
  617. hub_token (`str`, *optional*):
  618. The token to use to push the model to the Hub. Will default to the token in the cache folder obtained with
  619. `huggingface-cli login`.
  620. hub_private_repo (`bool`, *optional*, defaults to `False`):
  621. If True, the Hub repo will be set to private.
  622. hub_always_push (`bool`, *optional*, defaults to `False`):
  623. Unless this is `True`, the `Trainer` will skip pushing a checkpoint when the previous push is not finished.
  624. gradient_checkpointing (`bool`, *optional*, defaults to `False`):
  625. If True, use gradient checkpointing to save memory at the expense of slower backward pass.
  626. gradient_checkpointing_kwargs (`dict`, *optional*, defaults to `None`):
  627. Key word arguments to be passed to the `gradient_checkpointing_enable` method.
  628. include_inputs_for_metrics (`bool`, *optional*, defaults to `False`):
  629. This argument is deprecated. Use `include_for_metrics` instead, e.g, `include_for_metrics = ["inputs"]`.
  630. include_for_metrics (`List[str]`, *optional*, defaults to `[]`):
  631. Include additional data in the `compute_metrics` function if needed for metrics computation.
  632. Possible options to add to `include_for_metrics` list:
  633. - `"inputs"`: Input data passed to the model, intended for calculating input dependent metrics.
  634. - `"loss"`: Loss values computed during evaluation, intended for calculating loss dependent metrics.
  635. eval_do_concat_batches (`bool`, *optional*, defaults to `True`):
  636. Whether to recursively concat inputs/losses/labels/predictions across batches. If `False`,
  637. will instead store them as lists, with each batch kept separate.
  638. auto_find_batch_size (`bool`, *optional*, defaults to `False`)
  639. Whether to find a batch size that will fit into memory automatically through exponential decay, avoiding
  640. CUDA Out-of-Memory errors. Requires accelerate to be installed (`pip install accelerate`)
  641. full_determinism (`bool`, *optional*, defaults to `False`)
  642. If `True`, [`enable_full_determinism`] is called instead of [`set_seed`] to ensure reproducible results in
  643. distributed training. Important: this will negatively impact the performance, so only use it for debugging.
  644. torchdynamo (`str`, *optional*):
  645. If set, the backend compiler for TorchDynamo. Possible choices are `"eager"`, `"aot_eager"`, `"inductor"`,
  646. `"nvfuser"`, `"aot_nvfuser"`, `"aot_cudagraphs"`, `"ofi"`, `"fx2trt"`, `"onnxrt"` and `"ipex"`.
  647. ray_scope (`str`, *optional*, defaults to `"last"`):
  648. The scope to use when doing hyperparameter search with Ray. By default, `"last"` will be used. Ray will
  649. then use the last checkpoint of all trials, compare those, and select the best one. However, other options
  650. are also available. See the [Ray documentation](
  651. https://docs.ray.io/en/latest/tune/api_docs/analysis.html#ray.tune.ExperimentAnalysis.get_best_trial) for
  652. more options.
  653. ddp_timeout (`int`, *optional*, defaults to 1800):
  654. The timeout for `torch.distributed.init_process_group` calls, used to avoid GPU socket timeouts when
  655. performing slow operations in distributed runnings. Please refer the [PyTorch documentation]
  656. (https://pytorch.org/docs/stable/distributed.html#torch.distributed.init_process_group) for more
  657. information.
  658. use_mps_device (`bool`, *optional*, defaults to `False`):
  659. This argument is deprecated.`mps` device will be used if it is available similar to `cuda` device.
  660. torch_compile (`bool`, *optional*, defaults to `False`):
  661. Whether or not to compile the model using PyTorch 2.0
  662. [`torch.compile`](https://pytorch.org/get-started/pytorch-2.0/).
  663. This will use the best defaults for the [`torch.compile`
  664. API](https://pytorch.org/docs/stable/generated/torch.compile.html?highlight=torch+compile#torch.compile).
  665. You can customize the defaults with the argument `torch_compile_backend` and `torch_compile_mode` but we
  666. don't guarantee any of them will work as the support is progressively rolled in in PyTorch.
  667. This flag and the whole compile API is experimental and subject to change in future releases.
  668. torch_compile_backend (`str`, *optional*):
  669. The backend to use in `torch.compile`. If set to any value, `torch_compile` will be set to `True`.
  670. Refer to the PyTorch doc for possible values and note that they may change across PyTorch versions.
  671. This flag is experimental and subject to change in future releases.
  672. torch_compile_mode (`str`, *optional*):
  673. The mode to use in `torch.compile`. If set to any value, `torch_compile` will be set to `True`.
  674. Refer to the PyTorch doc for possible values and note that they may change across PyTorch versions.
  675. This flag is experimental and subject to change in future releases.
  676. split_batches (`bool`, *optional*):
  677. Whether or not the accelerator should split the batches yielded by the dataloaders across the devices
  678. during distributed training. If
  679. set to `True`, the actual batch size used will be the same on any kind of distributed processes, but it
  680. must be a
  681. round multiple of the number of processes you are using (such as GPUs).
  682. include_tokens_per_second (`bool`, *optional*):
  683. Whether or not to compute the number of tokens per second per device for training speed metrics.
  684. This will iterate over the entire training dataloader once beforehand,
  685. and will slow down the entire process.
  686. include_num_input_tokens_seen (`bool`, *optional*):
  687. Whether or not to track the number of input tokens seen throughout training.
  688. May be slower in distributed training as gather operations must be called.
  689. neftune_noise_alpha (`Optional[float]`):
  690. If not `None`, this will activate NEFTune noise embeddings. This can drastically improve model performance
  691. for instruction fine-tuning. Check out the [original paper](https://arxiv.org/abs/2310.05914) and the
  692. [original code](https://github.com/neelsjain/NEFTune). Support transformers `PreTrainedModel` and also
  693. `PeftModel` from peft. The original paper used values in the range [5.0, 15.0].
  694. optim_target_modules (`Union[str, List[str]]`, *optional*):
  695. The target modules to optimize, i.e. the module names that you would like to train, right now this is used only for GaLore algorithm
  696. https://arxiv.org/abs/2403.03507
  697. See: https://github.com/jiaweizzhao/GaLore for more details. You need to make sure to pass a valid GaloRe
  698. optimizer, e.g. one of: "galore_adamw", "galore_adamw_8bit", "galore_adafactor" and make sure that the target modules are `nn.Linear` modules
  699. only.
  700. batch_eval_metrics (`Optional[bool]`, defaults to `False`):
  701. If set to `True`, evaluation will call compute_metrics at the end of each batch to accumulate statistics
  702. rather than saving all eval logits in memory. When set to `True`, you must pass a compute_metrics function
  703. that takes a boolean argument `compute_result`, which when passed `True`, will trigger the final global
  704. summary statistics from the batch-level summary statistics you've accumulated over the evaluation set.
  705. eval_on_start (`bool`, *optional*, defaults to `False`):
  706. Whether to perform a evaluation step (sanity check) before the training to ensure the validation steps works correctly.
  707. eval_use_gather_object (`bool`, *optional*, defaults to `False`):
  708. 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.
  709. use_liger_kernel (`bool`, *optional*, defaults to `False`):
  710. Whether enable [Liger](https://github.com/linkedin/Liger-Kernel) Kernel for LLM model training.
  711. It can effectively increase multi-GPU training throughput by ~20% and reduces memory usage by ~60%, works out of the box with
  712. flash attention, PyTorch FSDP, and Microsoft DeepSpeed. Currently, it supports llama, mistral, mixtral and gemma models.
  713. """
  714. framework = "pt"
  715. output_dir: str = field(
  716. metadata={"help": "The output directory where the model predictions and checkpoints will be written."},
  717. )
  718. overwrite_output_dir: bool = field(
  719. default=False,
  720. metadata={
  721. "help": (
  722. "Overwrite the content of the output directory. "
  723. "Use this to continue training if output_dir points to a checkpoint directory."
  724. )
  725. },
  726. )
  727. do_train: bool = field(default=False, metadata={"help": "Whether to run training."})
  728. do_eval: bool = field(default=False, metadata={"help": "Whether to run eval on the dev set."})
  729. do_predict: bool = field(default=False, metadata={"help": "Whether to run predictions on the test set."})
  730. eval_strategy: Union[IntervalStrategy, str] = field(
  731. default="no",
  732. metadata={"help": "The evaluation strategy to use."},
  733. )
  734. prediction_loss_only: bool = field(
  735. default=False,
  736. metadata={"help": "When performing evaluation and predictions, only returns the loss."},
  737. )
  738. per_device_train_batch_size: int = field(
  739. default=8, metadata={"help": "Batch size per GPU/TPU/MPS/NPU core/CPU for training."}
  740. )
  741. per_device_eval_batch_size: int = field(
  742. default=8, metadata={"help": "Batch size per GPU/TPU/MPS/NPU core/CPU for evaluation."}
  743. )
  744. per_gpu_train_batch_size: Optional[int] = field(
  745. default=None,
  746. metadata={
  747. "help": (
  748. "Deprecated, the use of `--per_device_train_batch_size` is preferred. "
  749. "Batch size per GPU/TPU core/CPU for training."
  750. )
  751. },
  752. )
  753. per_gpu_eval_batch_size: Optional[int] = field(
  754. default=None,
  755. metadata={
  756. "help": (
  757. "Deprecated, the use of `--per_device_eval_batch_size` is preferred. "
  758. "Batch size per GPU/TPU core/CPU for evaluation."
  759. )
  760. },
  761. )
  762. gradient_accumulation_steps: int = field(
  763. default=1,
  764. metadata={"help": "Number of updates steps to accumulate before performing a backward/update pass."},
  765. )
  766. eval_accumulation_steps: Optional[int] = field(
  767. default=None,
  768. metadata={"help": "Number of predictions steps to accumulate before moving the tensors to the CPU."},
  769. )
  770. eval_delay: Optional[float] = field(
  771. default=0,
  772. metadata={
  773. "help": (
  774. "Number of epochs or steps to wait for before the first evaluation can be performed, depending on the"
  775. " eval_strategy."
  776. )
  777. },
  778. )
  779. torch_empty_cache_steps: Optional[int] = field(
  780. default=None,
  781. metadata={
  782. "help": "Number of steps to wait before calling `torch.<device>.empty_cache()`."
  783. "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)."
  784. "If left unset or set to None, cache will not be emptied."
  785. },
  786. )
  787. learning_rate: float = field(default=5e-5, metadata={"help": "The initial learning rate for AdamW."})
  788. weight_decay: float = field(default=0.0, metadata={"help": "Weight decay for AdamW if we apply some."})
  789. adam_beta1: float = field(default=0.9, metadata={"help": "Beta1 for AdamW optimizer"})
  790. adam_beta2: float = field(default=0.999, metadata={"help": "Beta2 for AdamW optimizer"})
  791. adam_epsilon: float = field(default=1e-8, metadata={"help": "Epsilon for AdamW optimizer."})
  792. max_grad_norm: float = field(default=1.0, metadata={"help": "Max gradient norm."})
  793. num_train_epochs: float = field(default=3.0, metadata={"help": "Total number of training epochs to perform."})
  794. max_steps: int = field(
  795. default=-1,
  796. metadata={"help": "If > 0: set total number of training steps to perform. Override num_train_epochs."},
  797. )
  798. lr_scheduler_type: Union[SchedulerType, str] = field(
  799. default="linear",
  800. metadata={"help": "The scheduler type to use."},
  801. )
  802. lr_scheduler_kwargs: Optional[Union[dict, str]] = field(
  803. default_factory=dict,
  804. metadata={
  805. "help": (
  806. "Extra parameters for the lr_scheduler such as {'num_cycles': 1} for the cosine with hard restarts."
  807. )
  808. },
  809. )
  810. warmup_ratio: float = field(
  811. default=0.0, metadata={"help": "Linear warmup over warmup_ratio fraction of total steps."}
  812. )
  813. warmup_steps: int = field(default=0, metadata={"help": "Linear warmup over warmup_steps."})
  814. log_level: Optional[str] = field(
  815. default="passive",
  816. metadata={
  817. "help": (
  818. "Logger log level to use on the main node. Possible choices are the log levels as strings: 'debug',"
  819. " 'info', 'warning', 'error' and 'critical', plus a 'passive' level which doesn't set anything and"
  820. " lets the application set the level. Defaults to 'passive'."
  821. ),
  822. "choices": trainer_log_levels.keys(),
  823. },
  824. )
  825. log_level_replica: Optional[str] = field(
  826. default="warning",
  827. metadata={
  828. "help": "Logger log level to use on replica nodes. Same choices and defaults as ``log_level``",
  829. "choices": trainer_log_levels.keys(),
  830. },
  831. )
  832. log_on_each_node: bool = field(
  833. default=True,
  834. metadata={
  835. "help": (
  836. "When doing a multinode distributed training, whether to log once per node or just once on the main"
  837. " node."
  838. )
  839. },
  840. )
  841. logging_dir: Optional[str] = field(default=None, metadata={"help": "Tensorboard log dir."})
  842. logging_strategy: Union[IntervalStrategy, str] = field(
  843. default="steps",
  844. metadata={"help": "The logging strategy to use."},
  845. )
  846. logging_first_step: bool = field(default=False, metadata={"help": "Log the first global_step"})
  847. logging_steps: float = field(
  848. default=500,
  849. metadata={
  850. "help": (
  851. "Log every X updates steps. Should be an integer or a float in range `[0,1)`. "
  852. "If smaller than 1, will be interpreted as ratio of total training steps."
  853. )
  854. },
  855. )
  856. logging_nan_inf_filter: bool = field(default=True, metadata={"help": "Filter nan and inf losses for logging."})
  857. save_strategy: Union[IntervalStrategy, str] = field(
  858. default="steps",
  859. metadata={"help": "The checkpoint save strategy to use."},
  860. )
  861. save_steps: float = field(
  862. default=500,
  863. metadata={
  864. "help": (
  865. "Save checkpoint every X updates steps. Should be an integer or a float in range `[0,1)`. "
  866. "If smaller than 1, will be interpreted as ratio of total training steps."
  867. )
  868. },
  869. )
  870. save_total_limit: Optional[int] = field(
  871. default=None,
  872. metadata={
  873. "help": (
  874. "If a value is passed, will limit the total amount of checkpoints. Deletes the older checkpoints in"
  875. " `output_dir`. When `load_best_model_at_end` is enabled, the 'best' checkpoint according to"
  876. " `metric_for_best_model` will always be retained in addition to the most recent ones. For example,"
  877. " for `save_total_limit=5` and `load_best_model_at_end=True`, the four last checkpoints will always be"
  878. " retained alongside the best model. When `save_total_limit=1` and `load_best_model_at_end=True`,"
  879. " it is possible that two checkpoints are saved: the last one and the best one (if they are different)."
  880. " Default is unlimited checkpoints"
  881. )
  882. },
  883. )
  884. save_safetensors: Optional[bool] = field(
  885. default=True,
  886. metadata={
  887. "help": "Use safetensors saving and loading for state dicts instead of default torch.load and torch.save."
  888. },
  889. )
  890. save_on_each_node: bool = field(
  891. default=False,
  892. metadata={
  893. "help": (
  894. "When doing multi-node distributed training, whether to save models and checkpoints on each node, or"
  895. " only on the main one"
  896. )
  897. },
  898. )
  899. save_only_model: bool = field(
  900. default=False,
  901. metadata={
  902. "help": (
  903. "When checkpointing, whether to only save the model, or also the optimizer, scheduler & rng state."
  904. "Note that when this is true, you won't be able to resume training from checkpoint."
  905. "This enables you to save storage by not storing the optimizer, scheduler & rng state."
  906. "You can only load the model using from_pretrained with this option set to True."
  907. )
  908. },
  909. )
  910. restore_callback_states_from_checkpoint: bool = field(
  911. default=False,
  912. metadata={
  913. "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."
  914. },
  915. )
  916. no_cuda: bool = field(
  917. default=False,
  918. metadata={"help": "This argument is deprecated. It will be removed in version 5.0 of 🤗 Transformers."},
  919. )
  920. use_cpu: bool = field(
  921. default=False,
  922. metadata={
  923. "help": " Whether or not to use cpu. If set to False, we will use cuda/tpu/mps/npu device if available."
  924. },
  925. )
  926. use_mps_device: bool = field(
  927. default=False,
  928. metadata={
  929. "help": "This argument is deprecated. `mps` device will be used if available similar to `cuda` device."
  930. " It will be removed in version 5.0 of 🤗 Transformers"
  931. },
  932. )
  933. seed: int = field(default=42, metadata={"help": "Random seed that will be set at the beginning of training."})
  934. data_seed: Optional[int] = field(default=None, metadata={"help": "Random seed to be used with data samplers."})
  935. jit_mode_eval: bool = field(
  936. default=False, metadata={"help": "Whether or not to use PyTorch jit trace for inference"}
  937. )
  938. use_ipex: bool = field(
  939. default=False,
  940. metadata={
  941. "help": (
  942. "Use Intel extension for PyTorch when it is available, installation:"
  943. " 'https://github.com/intel/intel-extension-for-pytorch'"
  944. )
  945. },
  946. )
  947. bf16: bool = field(
  948. default=False,
  949. metadata={
  950. "help": (
  951. "Whether to use bf16 (mixed) precision instead of 32-bit. Requires Ampere or higher NVIDIA"
  952. " architecture or using CPU (use_cpu) or Ascend NPU. This is an experimental API and it may change."
  953. )
  954. },
  955. )
  956. fp16: bool = field(
  957. default=False,
  958. metadata={"help": "Whether to use fp16 (mixed) precision instead of 32-bit"},
  959. )
  960. fp16_opt_level: str = field(
  961. default="O1",
  962. metadata={
  963. "help": (
  964. "For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']. "
  965. "See details at https://nvidia.github.io/apex/amp.html"
  966. )
  967. },
  968. )
  969. half_precision_backend: str = field(
  970. default="auto",
  971. metadata={
  972. "help": "The backend to be used for half precision.",
  973. "choices": ["auto", "apex", "cpu_amp"],
  974. },
  975. )
  976. bf16_full_eval: bool = field(
  977. default=False,
  978. metadata={
  979. "help": (
  980. "Whether to use full bfloat16 evaluation instead of 32-bit. This is an experimental API and it may"
  981. " change."
  982. )
  983. },
  984. )
  985. fp16_full_eval: bool = field(
  986. default=False,
  987. metadata={"help": "Whether to use full float16 evaluation instead of 32-bit"},
  988. )
  989. tf32: Optional[bool] = field(
  990. default=None,
  991. metadata={
  992. "help": (
  993. "Whether to enable tf32 mode, available in Ampere and newer GPU architectures. This is an experimental"
  994. " API and it may change."
  995. )
  996. },
  997. )
  998. local_rank: int = field(default=-1, metadata={"help": "For distributed training: local_rank"})
  999. ddp_backend: Optional[str] = field(
  1000. default=None,
  1001. metadata={
  1002. "help": "The backend to be used for distributed training",
  1003. "choices": ["nccl", "gloo", "mpi", "ccl", "hccl", "cncl", "mccl"],
  1004. },
  1005. )
  1006. tpu_num_cores: Optional[int] = field(
  1007. default=None, metadata={"help": "TPU: Number of TPU cores (automatically passed by launcher script)"}
  1008. )
  1009. tpu_metrics_debug: bool = field(
  1010. default=False,
  1011. metadata={
  1012. "help": (
  1013. "Deprecated, the use of `--debug tpu_metrics_debug` is preferred. TPU: Whether to print debug metrics"
  1014. )
  1015. },
  1016. )
  1017. debug: Union[str, List[DebugOption]] = field(
  1018. default="",
  1019. metadata={
  1020. "help": (
  1021. "Whether or not to enable debug mode. Current options: "
  1022. "`underflow_overflow` (Detect underflow and overflow in activations and weights), "
  1023. "`tpu_metrics_debug` (print debug metrics on TPU)."
  1024. )
  1025. },
  1026. )
  1027. dataloader_drop_last: bool = field(
  1028. default=False, metadata={"help": "Drop the last incomplete batch if it is not divisible by the batch size."}
  1029. )
  1030. eval_steps: Optional[float] = field(
  1031. default=None,
  1032. metadata={
  1033. "help": (
  1034. "Run an evaluation every X steps. Should be an integer or a float in range `[0,1)`. "
  1035. "If smaller than 1, will be interpreted as ratio of total training steps."
  1036. )
  1037. },
  1038. )
  1039. dataloader_num_workers: int = field(
  1040. default=0,
  1041. metadata={
  1042. "help": (
  1043. "Number of subprocesses to use for data loading (PyTorch only). 0 means that the data will be loaded"
  1044. " in the main process."
  1045. )
  1046. },
  1047. )
  1048. dataloader_prefetch_factor: Optional[int] = field(
  1049. default=None if not is_torch_available() or is_torch_greater_or_equal_than_2_0 else 2,
  1050. metadata={
  1051. "help": (
  1052. "Number of batches loaded in advance by each worker. "
  1053. "2 means there will be a total of 2 * num_workers batches prefetched across all workers. "
  1054. "Default is 2 for PyTorch < 2.0.0 and otherwise None."
  1055. )
  1056. },
  1057. )
  1058. past_index: int = field(
  1059. default=-1,
  1060. metadata={"help": "If >=0, uses the corresponding part of the output as the past state for next step."},
  1061. )
  1062. run_name: Optional[str] = field(
  1063. default=None,
  1064. metadata={"help": "An optional descriptor for the run. Notably used for wandb, mlflow and comet logging."},
  1065. )
  1066. disable_tqdm: Optional[bool] = field(
  1067. default=None, metadata={"help": "Whether or not to disable the tqdm progress bars."}
  1068. )
  1069. remove_unused_columns: Optional[bool] = field(
  1070. default=True, metadata={"help": "Remove columns not required by the model when using an nlp.Dataset."}
  1071. )
  1072. label_names: Optional[List[str]] = field(
  1073. default=None, metadata={"help": "The list of keys in your dictionary of inputs that correspond to the labels."}
  1074. )
  1075. load_best_model_at_end: Optional[bool] = field(
  1076. default=False,
  1077. metadata={
  1078. "help": (
  1079. "Whether or not to load the best model found during training at the end of training. When this option"
  1080. " is enabled, the best checkpoint will always be saved. See `save_total_limit` for more."
  1081. )
  1082. },
  1083. )
  1084. metric_for_best_model: Optional[str] = field(
  1085. default=None, metadata={"help": "The metric to use to compare two different models."}
  1086. )
  1087. greater_is_better: Optional[bool] = field(
  1088. default=None, metadata={"help": "Whether the `metric_for_best_model` should be maximized or not."}
  1089. )
  1090. ignore_data_skip: bool = field(
  1091. default=False,
  1092. metadata={
  1093. "help": (
  1094. "When resuming training, whether or not to skip the first epochs and batches to get to the same"
  1095. " training data."
  1096. )
  1097. },
  1098. )
  1099. fsdp: Optional[Union[List[FSDPOption], str]] = field(
  1100. default="",
  1101. metadata={
  1102. "help": (
  1103. "Whether or not to use PyTorch Fully Sharded Data Parallel (FSDP) training (in distributed training"
  1104. " only). The base option should be `full_shard`, `shard_grad_op` or `no_shard` and you can add"
  1105. " CPU-offload to `full_shard` or `shard_grad_op` like this: full_shard offload` or `shard_grad_op"
  1106. " offload`. You can add auto-wrap to `full_shard` or `shard_grad_op` with the same syntax: full_shard"
  1107. " auto_wrap` or `shard_grad_op auto_wrap`."
  1108. ),
  1109. },
  1110. )
  1111. fsdp_min_num_params: int = field(
  1112. default=0,
  1113. metadata={
  1114. "help": (
  1115. "This parameter is deprecated. FSDP's minimum number of parameters for Default Auto Wrapping. (useful"
  1116. " only when `fsdp` field is passed)."
  1117. )
  1118. },
  1119. )
  1120. fsdp_config: Optional[Union[dict, str]] = field(
  1121. default=None,
  1122. metadata={
  1123. "help": (
  1124. "Config to be used with FSDP (Pytorch Fully Sharded Data Parallel). The value is either a "
  1125. "fsdp json config file (e.g., `fsdp_config.json`) or an already loaded json file as `dict`."
  1126. )
  1127. },
  1128. )
  1129. fsdp_transformer_layer_cls_to_wrap: Optional[str] = field(
  1130. default=None,
  1131. metadata={
  1132. "help": (
  1133. "This parameter is deprecated. Transformer layer class name (case-sensitive) to wrap, e.g,"
  1134. " `BertLayer`, `GPTJBlock`, `T5Block` .... (useful only when `fsdp` flag is passed)."
  1135. )
  1136. },
  1137. )
  1138. accelerator_config: Optional[Union[dict, str]] = field(
  1139. default=None,
  1140. metadata={
  1141. "help": (
  1142. "Config to be used with the internal Accelerator object initializtion. The value is either a "
  1143. "accelerator json config file (e.g., `accelerator_config.json`) or an already loaded json file as `dict`."
  1144. )
  1145. },
  1146. )
  1147. deepspeed: Optional[Union[dict, str]] = field(
  1148. default=None,
  1149. metadata={
  1150. "help": (
  1151. "Enable deepspeed and pass the path to deepspeed json config file (e.g. `ds_config.json`) or an already"
  1152. " loaded json file as a dict"
  1153. )
  1154. },
  1155. )
  1156. label_smoothing_factor: float = field(
  1157. default=0.0, metadata={"help": "The label smoothing epsilon to apply (zero means no label smoothing)."}
  1158. )
  1159. default_optim = "adamw_torch"
  1160. # XXX: enable when pytorch==2.0.1 comes out - we want to give it time to get all the bugs sorted out
  1161. # if is_torch_available() and version.parse(version.parse(torch.__version__).base_version) >= version.parse("2.1.0"):
  1162. # default_optim = "adamw_torch_fused"
  1163. # and update the doc above to:
  1164. # optim (`str` or [`training_args.OptimizerNames`], *optional*, defaults to `"adamw_torch_fused"` (for torch<2.1.0 `"adamw_torch"`):
  1165. optim: Union[OptimizerNames, str] = field(
  1166. default=default_optim,
  1167. metadata={"help": "The optimizer to use."},
  1168. )
  1169. optim_args: Optional[str] = field(default=None, metadata={"help": "Optional arguments to supply to optimizer."})
  1170. adafactor: bool = field(default=False, metadata={"help": "Whether or not to replace AdamW by Adafactor."})
  1171. group_by_length: bool = field(
  1172. default=False,
  1173. metadata={"help": "Whether or not to group samples of roughly the same length together when batching."},
  1174. )
  1175. length_column_name: Optional[str] = field(
  1176. default="length",
  1177. metadata={"help": "Column name with precomputed lengths to use when grouping by length."},
  1178. )
  1179. report_to: Union[None, str, List[str]] = field(
  1180. default=None, metadata={"help": "The list of integrations to report the results and logs to."}
  1181. )
  1182. ddp_find_unused_parameters: Optional[bool] = field(
  1183. default=None,
  1184. metadata={
  1185. "help": (
  1186. "When using distributed training, the value of the flag `find_unused_parameters` passed to "
  1187. "`DistributedDataParallel`."
  1188. )
  1189. },
  1190. )
  1191. ddp_bucket_cap_mb: Optional[int] = field(
  1192. default=None,
  1193. metadata={
  1194. "help": (
  1195. "When using distributed training, the value of the flag `bucket_cap_mb` passed to "
  1196. "`DistributedDataParallel`."
  1197. )
  1198. },
  1199. )
  1200. ddp_broadcast_buffers: Optional[bool] = field(
  1201. default=None,
  1202. metadata={
  1203. "help": (
  1204. "When using distributed training, the value of the flag `broadcast_buffers` passed to "
  1205. "`DistributedDataParallel`."
  1206. )
  1207. },
  1208. )
  1209. dataloader_pin_memory: bool = field(
  1210. default=True, metadata={"help": "Whether or not to pin memory for DataLoader."}
  1211. )
  1212. dataloader_persistent_workers: bool = field(
  1213. default=False,
  1214. metadata={
  1215. "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."
  1216. },
  1217. )
  1218. skip_memory_metrics: bool = field(
  1219. default=True, metadata={"help": "Whether or not to skip adding of memory profiler reports to metrics."}
  1220. )
  1221. use_legacy_prediction_loop: bool = field(
  1222. default=False, metadata={"help": "Whether or not to use the legacy prediction_loop in the Trainer."}
  1223. )
  1224. push_to_hub: bool = field(
  1225. default=False, metadata={"help": "Whether or not to upload the trained model to the model hub after training."}
  1226. )
  1227. resume_from_checkpoint: Optional[str] = field(
  1228. default=None,
  1229. metadata={"help": "The path to a folder with a valid checkpoint for your model."},
  1230. )
  1231. hub_model_id: Optional[str] = field(
  1232. default=None, metadata={"help": "The name of the repository to keep in sync with the local `output_dir`."}
  1233. )
  1234. hub_strategy: Union[HubStrategy, str] = field(
  1235. default="every_save",
  1236. metadata={"help": "The hub strategy to use when `--push_to_hub` is activated."},
  1237. )
  1238. hub_token: Optional[str] = field(default=None, metadata={"help": "The token to use to push to the Model Hub."})
  1239. hub_private_repo: bool = field(default=False, metadata={"help": "Whether the model repository is private or not."})
  1240. hub_always_push: bool = field(
  1241. default=False,
  1242. metadata={"help": "Unless `True`, the Trainer will skip pushes if the previous one wasn't finished yet."},
  1243. )
  1244. gradient_checkpointing: bool = field(
  1245. default=False,
  1246. metadata={
  1247. "help": "If True, use gradient checkpointing to save memory at the expense of slower backward pass."
  1248. },
  1249. )
  1250. gradient_checkpointing_kwargs: Optional[Union[dict, str]] = field(
  1251. default=None,
  1252. metadata={
  1253. "help": "Gradient checkpointing key word arguments such as `use_reentrant`. Will be passed to `torch.utils.checkpoint.checkpoint` through `model.gradient_checkpointing_enable`."
  1254. },
  1255. )
  1256. include_inputs_for_metrics: bool = field(
  1257. default=False,
  1258. metadata={
  1259. "help": "This argument is deprecated and will be removed in version 5 of 🤗 Transformers. Use `include_for_metrics` instead."
  1260. },
  1261. )
  1262. include_for_metrics: List[str] = field(
  1263. default_factory=list,
  1264. metadata={
  1265. "help": "List of strings to specify additional data to include in the `compute_metrics` function."
  1266. "Options: 'inputs', 'loss'."
  1267. },
  1268. )
  1269. eval_do_concat_batches: bool = field(
  1270. default=True,
  1271. metadata={
  1272. "help": "Whether to recursively concat inputs/losses/labels/predictions across batches. If `False`, will instead store them as lists, with each batch kept separate."
  1273. },
  1274. )
  1275. # Deprecated arguments
  1276. fp16_backend: str = field(
  1277. default="auto",
  1278. metadata={
  1279. "help": "Deprecated. Use half_precision_backend instead",
  1280. "choices": ["auto", "apex", "cpu_amp"],
  1281. },
  1282. )
  1283. evaluation_strategy: Union[IntervalStrategy, str] = field(
  1284. default=None,
  1285. metadata={"help": "Deprecated. Use `eval_strategy` instead"},
  1286. )
  1287. push_to_hub_model_id: Optional[str] = field(
  1288. default=None, metadata={"help": "The name of the repository to which push the `Trainer`."}
  1289. )
  1290. push_to_hub_organization: Optional[str] = field(
  1291. default=None, metadata={"help": "The name of the organization in with to which push the `Trainer`."}
  1292. )
  1293. push_to_hub_token: Optional[str] = field(
  1294. default=None, metadata={"help": "The token to use to push to the Model Hub."}
  1295. )
  1296. _n_gpu: int = field(init=False, repr=False, default=-1)
  1297. mp_parameters: str = field(
  1298. default="",
  1299. metadata={"help": "Used by the SageMaker launcher to send mp-specific args. Ignored in Trainer"},
  1300. )
  1301. auto_find_batch_size: bool = field(
  1302. default=False,
  1303. metadata={
  1304. "help": (
  1305. "Whether to automatically decrease the batch size in half and rerun the training loop again each time"
  1306. " a CUDA Out-of-Memory was reached"
  1307. )
  1308. },
  1309. )
  1310. full_determinism: bool = field(
  1311. default=False,
  1312. metadata={
  1313. "help": (
  1314. "Whether to call enable_full_determinism instead of set_seed for reproducibility in distributed"
  1315. " training. Important: this will negatively impact the performance, so only use it for debugging."
  1316. )
  1317. },
  1318. )
  1319. torchdynamo: Optional[str] = field(
  1320. default=None,
  1321. metadata={
  1322. "help": "This argument is deprecated, use `--torch_compile_backend` instead.",
  1323. },
  1324. )
  1325. ray_scope: Optional[str] = field(
  1326. default="last",
  1327. metadata={
  1328. "help": (
  1329. 'The scope to use when doing hyperparameter search with Ray. By default, `"last"` will be used. Ray'
  1330. " will then use the last checkpoint of all trials, compare those, and select the best one. However,"
  1331. " other options are also available. See the Ray documentation"
  1332. " (https://docs.ray.io/en/latest/tune/api_docs/analysis.html"
  1333. "#ray.tune.ExperimentAnalysis.get_best_trial)"
  1334. " for more options."
  1335. )
  1336. },
  1337. )
  1338. ddp_timeout: Optional[int] = field(
  1339. default=1800,
  1340. metadata={
  1341. "help": "Overrides the default timeout for distributed training (value should be given in seconds)."
  1342. },
  1343. )
  1344. torch_compile: bool = field(
  1345. default=False, metadata={"help": "If set to `True`, the model will be wrapped in `torch.compile`."}
  1346. )
  1347. torch_compile_backend: Optional[str] = field(
  1348. default=None,
  1349. metadata={
  1350. "help": "Which backend to use with `torch.compile`, passing one will trigger a model compilation.",
  1351. },
  1352. )
  1353. torch_compile_mode: Optional[str] = field(
  1354. default=None,
  1355. metadata={
  1356. "help": "Which mode to use with `torch.compile`, passing one will trigger a model compilation.",
  1357. },
  1358. )
  1359. dispatch_batches: Optional[bool] = field(
  1360. default=None,
  1361. metadata={"help": "Deprecated. Pass {'dispatch_batches':VALUE} to `accelerator_config`."},
  1362. )
  1363. split_batches: Optional[bool] = field(
  1364. default=None,
  1365. metadata={"help": "Deprecated. Pass {'split_batches':True} to `accelerator_config`."},
  1366. )
  1367. include_tokens_per_second: Optional[bool] = field(
  1368. default=False,
  1369. metadata={"help": "If set to `True`, the speed metrics will include `tgs` (tokens per second per device)."},
  1370. )
  1371. include_num_input_tokens_seen: Optional[bool] = field(
  1372. default=False,
  1373. metadata={
  1374. "help": "If set to `True`, will track the number of input tokens seen throughout training. (May be slower in distributed training)"
  1375. },
  1376. )
  1377. neftune_noise_alpha: Optional[float] = field(
  1378. default=None,
  1379. metadata={
  1380. "help": "Activates neftune noise embeddings into the model. NEFTune has been proven to drastically improve model performances for instrcution fine-tuning. Check out the original paper here: https://arxiv.org/abs/2310.05914 and the original code here: https://github.com/neelsjain/NEFTune. Only supported for `PreTrainedModel` and `PeftModel` classes."
  1381. },
  1382. )
  1383. optim_target_modules: Union[None, str, List[str]] = field(
  1384. default=None,
  1385. metadata={
  1386. "help": "Target modules for the optimizer defined in the `optim` argument. Only used for the GaLore optimizer at the moment."
  1387. },
  1388. )
  1389. batch_eval_metrics: bool = field(
  1390. default=False,
  1391. metadata={"help": "Break eval metrics calculation into batches to save memory."},
  1392. )
  1393. eval_on_start: bool = field(
  1394. default=False,
  1395. metadata={
  1396. "help": "Whether to run through the entire `evaluation` step at the very beginning of training as a sanity check."
  1397. },
  1398. )
  1399. use_liger_kernel: Optional[bool] = field(
  1400. default=False,
  1401. metadata={"help": "Whether or not to enable the Liger Kernel for model training."},
  1402. )
  1403. eval_use_gather_object: Optional[bool] = field(
  1404. default=False,
  1405. metadata={
  1406. "help": "Whether to run recursively gather object in a nested list/tuple/dictionary of objects from all devices."
  1407. },
  1408. )
  1409. average_tokens_across_devices: Optional[bool] = field(
  1410. default=False,
  1411. metadata={
  1412. "help": "Whether or not to average tokens across devices. If enabled, will use all_reduce to "
  1413. "synchronize num_tokens_in_batch for precise loss calculation. Reference: "
  1414. "https://github.com/huggingface/transformers/issues/34242"
  1415. },
  1416. )
  1417. def __post_init__(self):
  1418. # Parse in args that could be `dict` sent in from the CLI as a string
  1419. for field in _VALID_DICT_FIELDS:
  1420. passed_value = getattr(self, field)
  1421. # We only want to do this if the str starts with a bracket to indiciate a `dict`
  1422. # else its likely a filename if supported
  1423. if isinstance(passed_value, str) and passed_value.startswith("{"):
  1424. loaded_dict = json.loads(passed_value)
  1425. # Convert str values to types if applicable
  1426. loaded_dict = _convert_str_dict(loaded_dict)
  1427. setattr(self, field, loaded_dict)
  1428. # expand paths, if not os.makedirs("~/bar") will make directory
  1429. # in the current directory instead of the actual home
  1430. # see https://github.com/huggingface/transformers/issues/10628
  1431. if self.output_dir is not None:
  1432. self.output_dir = os.path.expanduser(self.output_dir)
  1433. if self.logging_dir is None and self.output_dir is not None:
  1434. self.logging_dir = os.path.join(self.output_dir, default_logdir())
  1435. if self.logging_dir is not None:
  1436. self.logging_dir = os.path.expanduser(self.logging_dir)
  1437. if self.disable_tqdm is None:
  1438. self.disable_tqdm = logger.getEffectiveLevel() > logging.WARN
  1439. if self.evaluation_strategy is not None:
  1440. warnings.warn(
  1441. "`evaluation_strategy` is deprecated and will be removed in version 4.46 of 🤗 Transformers. Use `eval_strategy` instead",
  1442. FutureWarning,
  1443. )
  1444. self.eval_strategy = self.evaluation_strategy
  1445. if isinstance(self.eval_strategy, EvaluationStrategy):
  1446. warnings.warn(
  1447. "using `EvaluationStrategy` for `eval_strategy` is deprecated and will be removed in version 5"
  1448. " of 🤗 Transformers. Use `IntervalStrategy` instead",
  1449. FutureWarning,
  1450. )
  1451. # Go back to the underlying string or we won't be able to instantiate `IntervalStrategy` on it.
  1452. self.eval_strategy = self.eval_strategy.value
  1453. if self.no_cuda:
  1454. warnings.warn(
  1455. "using `no_cuda` is deprecated and will be removed in version 5.0 of 🤗 Transformers. "
  1456. "Use `use_cpu` instead",
  1457. FutureWarning,
  1458. )
  1459. self.use_cpu = self.no_cuda
  1460. self.eval_strategy = IntervalStrategy(self.eval_strategy)
  1461. self.logging_strategy = IntervalStrategy(self.logging_strategy)
  1462. self.save_strategy = IntervalStrategy(self.save_strategy)
  1463. self.hub_strategy = HubStrategy(self.hub_strategy)
  1464. self.lr_scheduler_type = SchedulerType(self.lr_scheduler_type)
  1465. if self.do_eval is False and self.eval_strategy != IntervalStrategy.NO:
  1466. self.do_eval = True
  1467. if self.torch_empty_cache_steps is not None:
  1468. if not (isinstance(self.torch_empty_cache_steps, int) or self.torch_empty_cache_steps > 0):
  1469. raise ValueError(
  1470. f"`torch_empty_cache_steps` must be an integer bigger than 0, got {self.torch_empty_cache_steps}."
  1471. )
  1472. # eval_steps has to be defined and non-zero, fallbacks to logging_steps if the latter is non-zero
  1473. if self.eval_strategy == IntervalStrategy.STEPS and (self.eval_steps is None or self.eval_steps == 0):
  1474. if self.logging_steps > 0:
  1475. logger.info(f"using `logging_steps` to initialize `eval_steps` to {self.logging_steps}")
  1476. self.eval_steps = self.logging_steps
  1477. else:
  1478. raise ValueError(
  1479. f"evaluation strategy {self.eval_strategy} requires either non-zero --eval_steps or"
  1480. " --logging_steps"
  1481. )
  1482. # logging_steps must be non-zero for logging_strategy that is other than 'no'
  1483. if self.logging_strategy == IntervalStrategy.STEPS and self.logging_steps == 0:
  1484. raise ValueError(f"logging strategy {self.logging_strategy} requires non-zero --logging_steps")
  1485. if self.logging_strategy == IntervalStrategy.STEPS and self.logging_steps > 1:
  1486. if self.logging_steps != int(self.logging_steps):
  1487. raise ValueError(f"--logging_steps must be an integer if bigger than 1: {self.logging_steps}")
  1488. self.logging_steps = int(self.logging_steps)
  1489. if self.eval_strategy == IntervalStrategy.STEPS and self.eval_steps > 1:
  1490. if self.eval_steps != int(self.eval_steps):
  1491. raise ValueError(f"--eval_steps must be an integer if bigger than 1: {self.eval_steps}")
  1492. self.eval_steps = int(self.eval_steps)
  1493. if self.save_strategy == IntervalStrategy.STEPS and self.save_steps > 1:
  1494. if self.save_steps != int(self.save_steps):
  1495. raise ValueError(f"--save_steps must be an integer if bigger than 1: {self.save_steps}")
  1496. self.save_steps = int(self.save_steps)
  1497. # Sanity checks for load_best_model_at_end: we require save and eval strategies to be compatible.
  1498. if self.load_best_model_at_end:
  1499. if self.eval_strategy != self.save_strategy:
  1500. raise ValueError(
  1501. "--load_best_model_at_end requires the save and eval strategy to match, but found\n- Evaluation "
  1502. f"strategy: {self.eval_strategy}\n- Save strategy: {self.save_strategy}"
  1503. )
  1504. if self.eval_strategy == IntervalStrategy.STEPS and self.save_steps % self.eval_steps != 0:
  1505. if self.eval_steps < 1 or self.save_steps < 1:
  1506. if not (self.eval_steps < 1 and self.save_steps < 1):
  1507. raise ValueError(
  1508. "--load_best_model_at_end requires the saving steps to be a multiple of the evaluation "
  1509. "steps, which cannot get guaranteed when mixing ratio and absolute steps for save_steps "
  1510. f"{self.save_steps} and eval_steps {self.eval_steps}."
  1511. )
  1512. # Work around floating point precision issues
  1513. LARGE_MULTIPLIER = 1_000_000
  1514. if (self.save_steps * LARGE_MULTIPLIER) % (self.eval_steps * LARGE_MULTIPLIER) != 0:
  1515. raise ValueError(
  1516. "--load_best_model_at_end requires the saving steps to be a multiple of the evaluation "
  1517. f"steps, but found {self.save_steps}, which is not a multiple of {self.eval_steps}."
  1518. )
  1519. raise ValueError(
  1520. "--load_best_model_at_end requires the saving steps to be a round multiple of the evaluation "
  1521. f"steps, but found {self.save_steps}, which is not a round multiple of {self.eval_steps}."
  1522. )
  1523. safetensors_available = is_safetensors_available()
  1524. if self.save_safetensors and not safetensors_available:
  1525. raise ValueError(f"--save_safetensors={self.save_safetensors} requires safetensors to be installed!")
  1526. if not self.save_safetensors and safetensors_available:
  1527. logger.info(
  1528. f"Found safetensors installation, but --save_safetensors={self.save_safetensors}. "
  1529. f"Safetensors should be a preferred weights saving format due to security and performance reasons. "
  1530. f"If your model cannot be saved by safetensors please feel free to open an issue at "
  1531. f"https://github.com/huggingface/safetensors!"
  1532. )
  1533. if (
  1534. self.load_best_model_at_end or self.lr_scheduler_type == SchedulerType.REDUCE_ON_PLATEAU
  1535. ) and self.metric_for_best_model is None:
  1536. self.metric_for_best_model = "loss"
  1537. if self.greater_is_better is None and self.metric_for_best_model is not None:
  1538. self.greater_is_better = not (self.metric_for_best_model.endswith("loss"))
  1539. if self.run_name is None:
  1540. self.run_name = self.output_dir
  1541. if self.framework == "pt" and is_torch_available():
  1542. if self.fp16_backend and self.fp16_backend != "auto":
  1543. warnings.warn(
  1544. "`fp16_backend` is deprecated and will be removed in version 5 of 🤗 Transformers. Use"
  1545. " `half_precision_backend` instead",
  1546. FutureWarning,
  1547. )
  1548. self.half_precision_backend = self.fp16_backend
  1549. if self.bf16 or self.bf16_full_eval:
  1550. if self.use_cpu and not is_torch_bf16_cpu_available() and not is_torch_xla_available():
  1551. # cpu
  1552. raise ValueError("Your setup doesn't support bf16/(cpu, tpu, neuroncore). You need torch>=1.10")
  1553. elif not self.use_cpu:
  1554. if torch.cuda.is_available() and not is_torch_bf16_gpu_available():
  1555. # gpu
  1556. raise ValueError(
  1557. "Your setup doesn't support bf16/gpu. You need torch>=1.10, using Ampere GPU with cuda>=11.0"
  1558. )
  1559. elif not is_torch_xpu_available():
  1560. # xpu
  1561. from .pytorch_utils import is_torch_greater_or_equal_than_1_12
  1562. if not is_torch_greater_or_equal_than_1_12:
  1563. raise ValueError(
  1564. "Your setup doesn't support bf16/xpu. You need torch>=1.12, using Intel XPU/GPU with IPEX installed"
  1565. )
  1566. if self.fp16 and self.bf16:
  1567. raise ValueError("At most one of fp16 and bf16 can be True, but not both")
  1568. if self.fp16_full_eval and self.bf16_full_eval:
  1569. raise ValueError("At most one of fp16 and bf16 can be True for full eval, but not both")
  1570. if self.bf16:
  1571. if self.half_precision_backend == "apex":
  1572. raise ValueError(" `--half_precision_backend apex`: GPU bf16 is not supported by apex.")
  1573. if self.lr_scheduler_type == SchedulerType.REDUCE_ON_PLATEAU:
  1574. if self.eval_strategy == IntervalStrategy.NO:
  1575. raise ValueError("lr_scheduler_type reduce_lr_on_plateau requires an eval strategy")
  1576. if not is_torch_available():
  1577. raise ValueError("lr_scheduler_type reduce_lr_on_plateau requires torch>=0.2.0")
  1578. self.optim = OptimizerNames(self.optim)
  1579. if self.adafactor:
  1580. warnings.warn(
  1581. "`--adafactor` is deprecated and will be removed in version 5 of 🤗 Transformers. Use `--optim"
  1582. " adafactor` instead",
  1583. FutureWarning,
  1584. )
  1585. self.optim = OptimizerNames.ADAFACTOR
  1586. if self.optim == OptimizerNames.ADAMW_TORCH_FUSED and is_torch_available():
  1587. if version.parse(version.parse(torch.__version__).base_version) < version.parse("2.0.0"):
  1588. raise ValueError("--optim adamw_torch_fused requires PyTorch 2.0 or higher")
  1589. # there is a bug in fp16/AMP in pt-2.0.0
  1590. if version.parse(version.parse(torch.__version__).base_version) == version.parse("2.0.0") and self.fp16:
  1591. raise ValueError("--optim adamw_torch_fused with --fp16 requires PyTorch>2.0")
  1592. # We need to setup the accelerator config here *before* the first call to `self.device`
  1593. if is_accelerate_available():
  1594. if not isinstance(self.accelerator_config, (AcceleratorConfig)):
  1595. if self.accelerator_config is None:
  1596. self.accelerator_config = AcceleratorConfig()
  1597. elif isinstance(self.accelerator_config, dict):
  1598. self.accelerator_config = AcceleratorConfig(**self.accelerator_config)
  1599. # Check that a user didn't pass in the class instantiator
  1600. # such as `accelerator_config = AcceleratorConfig`
  1601. elif isinstance(self.accelerator_config, type):
  1602. raise NotImplementedError(
  1603. "Tried passing in a callable to `accelerator_config`, but this is not supported. "
  1604. "Please pass in a fully constructed `AcceleratorConfig` object instead."
  1605. )
  1606. else:
  1607. self.accelerator_config = AcceleratorConfig.from_json_file(self.accelerator_config)
  1608. if self.dispatch_batches is not None:
  1609. warnings.warn(
  1610. "Using `--dispatch_batches` is deprecated and will be removed in version 4.41 of 🤗 Transformers. Use"
  1611. " `--accelerator_config {'dispatch_batches':VALUE} instead",
  1612. FutureWarning,
  1613. )
  1614. self.accelerator_config.dispatch_batches = self.dispatch_batches
  1615. if self.split_batches is not None:
  1616. warnings.warn(
  1617. "Using `--split_batches` is deprecated and will be removed in version 4.41 of 🤗 Transformers. Use"
  1618. " `--accelerator_config {'split_batches':VALUE} instead",
  1619. FutureWarning,
  1620. )
  1621. self.accelerator_config.split_batches = self.split_batches
  1622. # Initialize device before we proceed
  1623. if self.framework == "pt" and is_torch_available():
  1624. self.device
  1625. # Disable average tokens when using single device
  1626. if self.average_tokens_across_devices:
  1627. try:
  1628. if self.world_size == 1:
  1629. logger.warning(
  1630. "average_tokens_across_devices is set to True but it is invalid when world size is"
  1631. "1. Turn it to False automatically."
  1632. )
  1633. self.average_tokens_across_devices = False
  1634. except ImportError as e:
  1635. logger.warning(f"Can not specify world size due to {e}. Turn average_tokens_across_devices to False.")
  1636. self.average_tokens_across_devices = False
  1637. if self.torchdynamo is not None:
  1638. warnings.warn(
  1639. "`torchdynamo` is deprecated and will be removed in version 5 of 🤗 Transformers. Use"
  1640. " `torch_compile_backend` instead",
  1641. FutureWarning,
  1642. )
  1643. self.torch_compile_backend = self.torchdynamo
  1644. if (self.torch_compile_mode is not None or self.torch_compile_backend is not None) and not self.torch_compile:
  1645. self.torch_compile = True
  1646. if self.torch_compile and self.torch_compile_backend is None:
  1647. self.torch_compile_backend = "inductor"
  1648. # accelerate integration for torch compile
  1649. if self.torch_compile:
  1650. # set env vars for accelerate
  1651. prefix = "ACCELERATE_DYNAMO_"
  1652. os.environ[prefix + "BACKEND"] = self.torch_compile_backend
  1653. if self.torch_compile_mode is not None:
  1654. os.environ[prefix + "MODE"] = self.torch_compile_mode
  1655. if self.framework == "pt" and is_torch_available() and self.torch_compile:
  1656. if is_torch_tf32_available():
  1657. if self.tf32 is None and not self.fp16 or self.bf16:
  1658. logger.info(
  1659. "Setting TF32 in CUDA backends to speedup torch compile, you won't see any improvement"
  1660. " otherwise."
  1661. )
  1662. torch.backends.cuda.matmul.allow_tf32 = True
  1663. torch.backends.cudnn.allow_tf32 = True
  1664. else:
  1665. logger.warning(
  1666. "The speedups for torchdynamo mostly come wih GPU Ampere or higher and which is not detected here."
  1667. )
  1668. if self.framework == "pt" and is_torch_available() and self.tf32 is not None:
  1669. if self.tf32:
  1670. if is_torch_tf32_available():
  1671. torch.backends.cuda.matmul.allow_tf32 = True
  1672. torch.backends.cudnn.allow_tf32 = True
  1673. else:
  1674. raise ValueError("--tf32 requires Ampere or a newer GPU arch, cuda>=11 and torch>=1.7")
  1675. else:
  1676. if is_torch_tf32_available():
  1677. torch.backends.cuda.matmul.allow_tf32 = False
  1678. torch.backends.cudnn.allow_tf32 = False
  1679. # no need to assert on else
  1680. # if training args is specified, it will override the one specified in the accelerate config
  1681. if self.half_precision_backend != "apex":
  1682. mixed_precision_dtype = os.environ.get("ACCELERATE_MIXED_PRECISION", "no")
  1683. if self.fp16:
  1684. mixed_precision_dtype = "fp16"
  1685. elif self.bf16:
  1686. mixed_precision_dtype = "bf16"
  1687. os.environ["ACCELERATE_MIXED_PRECISION"] = mixed_precision_dtype
  1688. if self.report_to is None:
  1689. logger.info(
  1690. "The default value for the training argument `--report_to` will change in v5 (from all installed "
  1691. "integrations to none). In v5, you will need to use `--report_to all` to get the same behavior as "
  1692. "now. You should start updating your code and make this info disappear :-)."
  1693. )
  1694. self.report_to = "all"
  1695. if self.report_to == "all" or self.report_to == ["all"]:
  1696. # Import at runtime to avoid a circular import.
  1697. from .integrations import get_available_reporting_integrations
  1698. self.report_to = get_available_reporting_integrations()
  1699. if "codecarbon" in self.report_to and torch.version.hip:
  1700. logger.warning(
  1701. "When using the Trainer, CodeCarbonCallback requires the `codecarbon` package, which is not compatible with AMD ROCm (https://github.com/mlco2/codecarbon/pull/490). Automatically disabling the codecarbon callback. Reference: https://huggingface.co/docs/transformers/v4.39.3/en/main_classes/trainer#transformers.TrainingArguments.report_to."
  1702. )
  1703. self.report_to.remove("codecarbon")
  1704. elif self.report_to == "none" or self.report_to == ["none"]:
  1705. self.report_to = []
  1706. elif not isinstance(self.report_to, list):
  1707. self.report_to = [self.report_to]
  1708. if self.warmup_ratio < 0 or self.warmup_ratio > 1:
  1709. raise ValueError("warmup_ratio must lie in range [0,1]")
  1710. elif self.warmup_ratio > 0 and self.warmup_steps > 0:
  1711. logger.info(
  1712. "Both warmup_ratio and warmup_steps given, warmup_steps will override any effect of warmup_ratio"
  1713. " during training"
  1714. )
  1715. if not isinstance(self.warmup_steps, int) or self.warmup_steps < 0:
  1716. raise ValueError("warmup_steps must be of type int and must be 0 or a positive integer.")
  1717. if isinstance(self.fsdp, bool):
  1718. self.fsdp = [FSDPOption.FULL_SHARD] if self.fsdp else ""
  1719. if isinstance(self.fsdp, str):
  1720. self.fsdp = [FSDPOption(s) for s in self.fsdp.split()]
  1721. if self.fsdp == [FSDPOption.OFFLOAD]:
  1722. raise ValueError(
  1723. "`--fsdp offload` can't work on its own. It needs to be added to `--fsdp full_shard` or "
  1724. '`--fsdp shard_grad_op`. For example, `--fsdp "full_shard offload"`.'
  1725. )
  1726. elif FSDPOption.FULL_SHARD in self.fsdp and FSDPOption.SHARD_GRAD_OP in self.fsdp:
  1727. raise ValueError("`--fsdp full_shard` is not compatible with `--fsdp shard_grad_op`.")
  1728. if self.gradient_checkpointing and (
  1729. FSDPOption.FULL_SHARD in self.fsdp or FSDPOption.HYBRID_SHARD in self.fsdp
  1730. ):
  1731. logger.warning(
  1732. "When using FSDP full shard, instead of using `gradient_checkpointing` in TrainingArguments, please"
  1733. " use `activation_checkpointing` in `fsdp_config`. The former introduces a redundant AllGather"
  1734. " operation in backward pass. Reference: https://github.com/huggingface/transformers/issues/30404"
  1735. )
  1736. if self.fsdp_config is None:
  1737. self.fsdp_config = {}
  1738. if isinstance(self.fsdp_config, str):
  1739. if len(self.fsdp) == 0:
  1740. warnings.warn("`--fsdp_config` is useful only when `--fsdp` is specified.")
  1741. with io.open(self.fsdp_config, "r", encoding="utf-8") as f:
  1742. self.fsdp_config = json.load(f)
  1743. for k in list(self.fsdp_config.keys()):
  1744. if k.startswith("fsdp_"):
  1745. v = self.fsdp_config.pop(k)
  1746. self.fsdp_config[k[5:]] = v
  1747. if self.fsdp_min_num_params > 0:
  1748. warnings.warn("using `--fsdp_min_num_params` is deprecated. Use fsdp_config instead ", FutureWarning)
  1749. self.fsdp_config["min_num_params"] = max(self.fsdp_config.get("min_num_params", 0), self.fsdp_min_num_params)
  1750. # if fsdp_config["transformer_layer_cls_to_wrap"] is specified as a string, convert it to a list with a single object
  1751. if isinstance(self.fsdp_config.get("transformer_layer_cls_to_wrap", None), str):
  1752. self.fsdp_config["transformer_layer_cls_to_wrap"] = [self.fsdp_config["transformer_layer_cls_to_wrap"]]
  1753. if self.fsdp_transformer_layer_cls_to_wrap is not None:
  1754. warnings.warn(
  1755. "using `--fsdp_transformer_layer_cls_to_wrap` is deprecated. Use fsdp_config instead ", FutureWarning
  1756. )
  1757. self.fsdp_config["transformer_layer_cls_to_wrap"] = self.fsdp_config.get(
  1758. "transformer_layer_cls_to_wrap", []
  1759. ) + [self.fsdp_transformer_layer_cls_to_wrap]
  1760. if len(self.fsdp) == 0 and self.fsdp_config["min_num_params"] > 0:
  1761. warnings.warn("`min_num_params` is useful only when `--fsdp` is specified.")
  1762. if len(self.fsdp) == 0 and self.fsdp_config.get("transformer_layer_cls_to_wrap", None) is not None:
  1763. warnings.warn("`transformer_layer_cls_to_wrap` is useful only when `--fsdp` is specified.")
  1764. if (
  1765. len(self.fsdp) > 0
  1766. and self.fsdp_config["min_num_params"] > 0
  1767. and self.fsdp_config.get("transformer_layer_cls_to_wrap", None) is not None
  1768. ):
  1769. raise ValueError("`min_num_params` and `transformer_layer_cls_to_wrap` are mutually exclusive.")
  1770. self.fsdp_config["xla"] = self.fsdp_config.get("xla", False)
  1771. self.fsdp_config["xla_fsdp_v2"] = self.fsdp_config.get("xla_fsdp_v2", False)
  1772. self.fsdp_config["xla_fsdp_grad_ckpt"] = self.fsdp_config.get("xla_fsdp_grad_ckpt", False)
  1773. if self.fsdp_config["xla"]:
  1774. if len(self.fsdp) > 0:
  1775. # store XLA fsdp configuration parameters into a dictionary
  1776. # Copy the config to avoid modifying the original config (which may be used for JSON serialization)
  1777. self.xla_fsdp_config = self.fsdp_config.get("xla_fsdp_settings", {}).copy()
  1778. # apply appropriate string to torch.dtype conversions for parameters
  1779. if "compute_dtype" in self.xla_fsdp_config:
  1780. self.xla_fsdp_config["compute_dtype"] = getattr(torch, self.xla_fsdp_config["compute_dtype"])
  1781. if "buffer_dtype" in self.xla_fsdp_config:
  1782. self.xla_fsdp_config["buffer_dtype"] = getattr(torch, self.xla_fsdp_config["buffer_dtype"])
  1783. else:
  1784. warnings.warn("XLA FSDP can be used only when `--fsdp` is specified.")
  1785. else:
  1786. if self.fsdp_config["xla_fsdp_grad_ckpt"]:
  1787. warnings.warn("`--xla_fsdp_grad_ckpt` is useful only when `--xla` is set to true.")
  1788. # accelerate integration for FSDP
  1789. if len(self.fsdp) > 0 and not self.fsdp_config["xla"]:
  1790. os.environ["ACCELERATE_USE_FSDP"] = "true"
  1791. from accelerate.utils.constants import (
  1792. FSDP_AUTO_WRAP_POLICY,
  1793. FSDP_SHARDING_STRATEGY,
  1794. )
  1795. prefix = "FSDP_"
  1796. for fsdp_option in self.fsdp:
  1797. if fsdp_option.upper() in FSDP_SHARDING_STRATEGY:
  1798. # set environment variable for FSDP sharding strategy
  1799. os.environ[f"{prefix}SHARDING_STRATEGY"] = str(
  1800. FSDP_SHARDING_STRATEGY.index(fsdp_option.upper()) + 1
  1801. )
  1802. elif fsdp_option == FSDPOption.OFFLOAD:
  1803. os.environ[f"{prefix}OFFLOAD_PARAMS"] = "true"
  1804. elif fsdp_option == FSDPOption.AUTO_WRAP:
  1805. os.environ[f"{prefix}AUTO_WRAP_POLICY"] = FSDP_AUTO_WRAP_POLICY[0]
  1806. if self.fsdp_config["min_num_params"] > 0:
  1807. os.environ[f"{prefix}MIN_NUM_PARAMS"] = str(self.fsdp_config["min_num_params"])
  1808. os.environ[f"{prefix}AUTO_WRAP_POLICY"] = FSDP_AUTO_WRAP_POLICY[1]
  1809. elif self.fsdp_config.get("transformer_layer_cls_to_wrap", None) is not None:
  1810. os.environ[f"{prefix}TRANSFORMER_CLS_TO_WRAP"] = ",".join(
  1811. self.fsdp_config["transformer_layer_cls_to_wrap"]
  1812. )
  1813. prefetch_policy = self.fsdp_config.get("backward_prefetch", "NO_PREFETCH")
  1814. os.environ[f"{prefix}BACKWARD_PREFETCH"] = prefetch_policy.upper()
  1815. os.environ[f"{prefix}FORWARD_PREFETCH"] = str(self.fsdp_config.get("forward_prefetch", "false")).lower()
  1816. sync_module_states = str(self.fsdp_config.get("sync_module_states", "true")).lower()
  1817. cpu_ram_efficient_loading = str(self.fsdp_config.get("cpu_ram_efficient_loading", "false")).lower()
  1818. if sync_module_states == "false" and cpu_ram_efficient_loading == "true":
  1819. # In this case, all the processes except the main process would have random weights leading
  1820. # to unexpected behaviour during training, thus throwing error here to prevent it.
  1821. raise ValueError('`sync_module_states` must be `"True"` if `cpu_ram_efficient_loading` is `"True"`')
  1822. os.environ[f"{prefix}SYNC_MODULE_STATES"] = sync_module_states
  1823. os.environ[f"{prefix}CPU_RAM_EFFICIENT_LOADING"] = cpu_ram_efficient_loading
  1824. os.environ[f"{prefix}USE_ORIG_PARAMS"] = str(self.fsdp_config.get("use_orig_params", "true")).lower()
  1825. if self.tpu_metrics_debug:
  1826. warnings.warn(
  1827. "using `--tpu_metrics_debug` is deprecated and will be removed in version 5 of 🤗 Transformers. Use"
  1828. " `--debug tpu_metrics_debug` instead",
  1829. FutureWarning,
  1830. )
  1831. if self.debug is None:
  1832. self.debug = " tpu_metrics_debug"
  1833. else:
  1834. self.debug += " tpu_metrics_debug"
  1835. self.tpu_metrics_debug = False
  1836. if isinstance(self.debug, str):
  1837. self.debug = [DebugOption(s) for s in self.debug.split()]
  1838. elif self.debug is None:
  1839. self.debug = []
  1840. self.deepspeed_plugin = None
  1841. if self.deepspeed:
  1842. # - must be run very last in arg parsing, since it will use a lot of these settings.
  1843. # - must be run before the model is created.
  1844. if not is_accelerate_available():
  1845. raise ValueError(
  1846. f"--deepspeed requires Accelerate to be installed: `pip install 'accelerate>={ACCELERATE_MIN_VERSION}'`."
  1847. )
  1848. from transformers.integrations.deepspeed import HfTrainerDeepSpeedConfig
  1849. # will be used later by the Trainer
  1850. # note: leave self.deepspeed unmodified in case a user relies on it not to be modified)
  1851. self.hf_deepspeed_config = HfTrainerDeepSpeedConfig(self.deepspeed)
  1852. self.hf_deepspeed_config.trainer_config_process(self)
  1853. # Accelerate DeepSpeed Plugin
  1854. from accelerate.utils import DeepSpeedPlugin
  1855. os.environ["ACCELERATE_USE_DEEPSPEED"] = "true"
  1856. self.deepspeed_plugin = DeepSpeedPlugin(hf_ds_config=self.hf_deepspeed_config)
  1857. elif strtobool(os.environ.get("ACCELERATE_USE_DEEPSPEED", "false")):
  1858. # Accelerate DeepSpeed Plugin
  1859. from accelerate.utils import DeepSpeedPlugin
  1860. self.deepspeed_plugin = DeepSpeedPlugin()
  1861. mixed_precision = os.environ.get("ACCELERATE_MIXED_PRECISION", "no")
  1862. self.deepspeed_plugin.set_mixed_precision(mixed_precision)
  1863. self.deepspeed_plugin.set_deepspeed_weakref()
  1864. if self.use_cpu:
  1865. self.dataloader_pin_memory = False
  1866. if (
  1867. (not is_torch_available() or is_torch_greater_or_equal_than_2_0)
  1868. and self.dataloader_num_workers == 0
  1869. and self.dataloader_prefetch_factor is not None
  1870. ):
  1871. raise ValueError(
  1872. "--dataloader_prefetch_factor can only be set when data is loaded in a different process, i.e."
  1873. " when --dataloader_num_workers > 1."
  1874. )
  1875. if self.push_to_hub_token is not None:
  1876. warnings.warn(
  1877. "`--push_to_hub_token` is deprecated and will be removed in version 5 of 🤗 Transformers. Use "
  1878. "`--hub_token` instead.",
  1879. FutureWarning,
  1880. )
  1881. self.hub_token = self.push_to_hub_token
  1882. if self.push_to_hub_model_id is not None:
  1883. self.hub_model_id = get_full_repo_name(
  1884. self.push_to_hub_model_id, organization=self.push_to_hub_organization, token=self.hub_token
  1885. )
  1886. if self.push_to_hub_organization is not None:
  1887. warnings.warn(
  1888. "`--push_to_hub_model_id` and `--push_to_hub_organization` are deprecated and will be removed in "
  1889. "version 5 of 🤗 Transformers. Use `--hub_model_id` instead and pass the full repo name to this "
  1890. f"argument (in this case {self.hub_model_id}).",
  1891. FutureWarning,
  1892. )
  1893. else:
  1894. warnings.warn(
  1895. "`--push_to_hub_model_id` is deprecated and will be removed in version 5 of 🤗 Transformers. Use "
  1896. "`--hub_model_id` instead and pass the full repo name to this argument (in this case "
  1897. f"{self.hub_model_id}).",
  1898. FutureWarning,
  1899. )
  1900. elif self.push_to_hub_organization is not None:
  1901. self.hub_model_id = f"{self.push_to_hub_organization}/{Path(self.output_dir).name}"
  1902. warnings.warn(
  1903. "`--push_to_hub_organization` is deprecated and will be removed in version 5 of 🤗 Transformers. Use "
  1904. "`--hub_model_id` instead and pass the full repo name to this argument (in this case "
  1905. f"{self.hub_model_id}).",
  1906. FutureWarning,
  1907. )
  1908. if self.eval_use_gather_object and not is_accelerate_available("0.30.0"):
  1909. raise ValueError(
  1910. "--eval_use_gather_object requires Accelerate to be version of `accelerate` > 0.30.0."
  1911. "This is not supported and we recommend you to update your version."
  1912. )
  1913. if self.data_seed is not None:
  1914. if not is_accelerate_available("1.1.0"):
  1915. raise NotImplementedError(
  1916. "data_seed requires Accelerate version `accelerate` >= 1.1.0. "
  1917. "This is not supported and we recommend you to update your version."
  1918. )
  1919. if self.include_inputs_for_metrics:
  1920. logger.warning(
  1921. "Using `include_inputs_for_metrics` is deprecated and will be removed in version 5 of 🤗 Transformers. Please use `include_for_metrics` list argument instead."
  1922. )
  1923. self.include_for_metrics.append("inputs")
  1924. def __str__(self):
  1925. self_as_dict = asdict(self)
  1926. # Remove deprecated arguments. That code should be removed once
  1927. # those deprecated arguments are removed from TrainingArguments. (TODO: v5)
  1928. del self_as_dict["per_gpu_train_batch_size"]
  1929. del self_as_dict["per_gpu_eval_batch_size"]
  1930. self_as_dict = {k: f"<{k.upper()}>" if k.endswith("_token") else v for k, v in self_as_dict.items()}
  1931. attrs_as_str = [f"{k}={v},\n" for k, v in sorted(self_as_dict.items())]
  1932. return f"{self.__class__.__name__}(\n{''.join(attrs_as_str)})"
  1933. __repr__ = __str__
  1934. @property
  1935. def train_batch_size(self) -> int:
  1936. """
  1937. The actual batch size for training (may differ from `per_gpu_train_batch_size` in distributed training).
  1938. """
  1939. if self.per_gpu_train_batch_size:
  1940. logger.warning(
  1941. "Using deprecated `--per_gpu_train_batch_size` argument which will be removed in a future "
  1942. "version. Using `--per_device_train_batch_size` is preferred."
  1943. )
  1944. per_device_batch_size = self.per_gpu_train_batch_size or self.per_device_train_batch_size
  1945. train_batch_size = per_device_batch_size * max(1, self.n_gpu)
  1946. return train_batch_size
  1947. @property
  1948. def eval_batch_size(self) -> int:
  1949. """
  1950. The actual batch size for evaluation (may differ from `per_gpu_eval_batch_size` in distributed training).
  1951. """
  1952. if self.per_gpu_eval_batch_size:
  1953. logger.warning(
  1954. "Using deprecated `--per_gpu_eval_batch_size` argument which will be removed in a future "
  1955. "version. Using `--per_device_eval_batch_size` is preferred."
  1956. )
  1957. per_device_batch_size = self.per_gpu_eval_batch_size or self.per_device_eval_batch_size
  1958. eval_batch_size = per_device_batch_size * max(1, self.n_gpu)
  1959. return eval_batch_size
  1960. @property
  1961. def ddp_timeout_delta(self) -> timedelta:
  1962. """
  1963. The actual timeout for torch.distributed.init_process_group since it expects a timedelta variable.
  1964. """
  1965. return timedelta(seconds=self.ddp_timeout)
  1966. @cached_property
  1967. def _setup_devices(self) -> "torch.device":
  1968. requires_backends(self, ["torch"])
  1969. logger.info("PyTorch: setting up devices")
  1970. if not is_sagemaker_mp_enabled():
  1971. if not is_accelerate_available():
  1972. raise ImportError(
  1973. f"Using the `Trainer` with `PyTorch` requires `accelerate>={ACCELERATE_MIN_VERSION}`: "
  1974. "Please run `pip install transformers[torch]` or `pip install 'accelerate>={ACCELERATE_MIN_VERSION}'`"
  1975. )
  1976. # We delay the init of `PartialState` to the end for clarity
  1977. accelerator_state_kwargs = {"enabled": True, "use_configured_state": False}
  1978. if isinstance(self.accelerator_config, AcceleratorConfig):
  1979. accelerator_state_kwargs["use_configured_state"] = self.accelerator_config.pop(
  1980. "use_configured_state", False
  1981. )
  1982. if accelerator_state_kwargs["use_configured_state"]:
  1983. if PartialState._shared_state == {}:
  1984. raise ValueError(
  1985. "Passing `'use_configured_state':True` to the AcceleratorConfig requires a pre-configured "
  1986. "`AcceleratorState` or `PartialState` to be defined before calling `TrainingArguments`. "
  1987. )
  1988. # We rely on `PartialState` to yell if there's issues here (which it will)
  1989. self.distributed_state = PartialState(cpu=self.use_cpu)
  1990. if self.deepspeed and self.distributed_state.distributed_type != DistributedType.DEEPSPEED:
  1991. raise RuntimeError(
  1992. "Tried to use an already configured `Accelerator` or `PartialState` that was not initialized for DeepSpeed, "
  1993. "but also passed in a `deepspeed` configuration to the `TrainingArguments`. Please set "
  1994. "`use_configured_state:False` instead or setup your `Accelerator` or `PartialState` properly."
  1995. )
  1996. else:
  1997. AcceleratorState._reset_state(reset_partial_state=True)
  1998. self.distributed_state = None
  1999. if not self.use_ipex and "ACCELERATE_USE_IPEX" not in os.environ:
  2000. os.environ["ACCELERATE_USE_IPEX"] = "false"
  2001. self._n_gpu = 1
  2002. if self.use_cpu or strtobool(os.environ.get("ACCELERATE_USE_CPU", "False")):
  2003. accelerator_state_kwargs["cpu"] = True
  2004. accelerator_state_kwargs["backend"] = self.ddp_backend
  2005. self._n_gpu = 0
  2006. elif is_sagemaker_mp_enabled():
  2007. accelerator_state_kwargs["enabled"] = False
  2008. local_rank = smp.local_rank()
  2009. device = torch.device("cuda", local_rank)
  2010. torch.cuda.set_device(device)
  2011. elif is_sagemaker_dp_enabled():
  2012. accelerator_state_kwargs["_use_sagemaker_dp"] = True
  2013. elif self.deepspeed:
  2014. accelerator_state_kwargs["use_deepspeed"] = True
  2015. accelerator_state_kwargs["timeout"] = timedelta(seconds=self.ddp_timeout)
  2016. else:
  2017. accelerator_state_kwargs["backend"] = self.ddp_backend
  2018. accelerator_state_kwargs["timeout"] = timedelta(seconds=self.ddp_timeout)
  2019. # Now we pop everything
  2020. if accelerator_state_kwargs.pop("enabled", False) and not accelerator_state_kwargs.pop(
  2021. "use_configured_state", False
  2022. ):
  2023. # We need to patch this env var when enabling to detect deepspeed
  2024. use_deepspeed = accelerator_state_kwargs.pop("use_deepspeed", False)
  2025. if use_deepspeed:
  2026. os.environ["ACCELERATE_USE_DEEPSPEED"] = "true"
  2027. self.distributed_state = PartialState(**accelerator_state_kwargs)
  2028. if use_deepspeed:
  2029. del os.environ["ACCELERATE_USE_DEEPSPEED"]
  2030. if not is_sagemaker_mp_enabled():
  2031. device = self.distributed_state.device
  2032. self.local_rank = self.distributed_state.local_process_index
  2033. if dist.is_available() and dist.is_initialized() and self.parallel_mode != ParallelMode.DISTRIBUTED:
  2034. logger.warning(
  2035. "torch.distributed process group is initialized, but parallel_mode != ParallelMode.DISTRIBUTED. "
  2036. "In order to use Torch DDP, launch your script with `python -m torch.distributed.launch"
  2037. )
  2038. if is_torch_xla_available():
  2039. device = self.distributed_state.device
  2040. self._n_gpu = 0
  2041. elif is_sagemaker_dp_enabled() or is_sagemaker_mp_enabled():
  2042. # Already set _n_gpu
  2043. pass
  2044. elif self.distributed_state.distributed_type == DistributedType.NO:
  2045. if self.use_mps_device:
  2046. warnings.warn(
  2047. "`use_mps_device` is deprecated and will be removed in version 5.0 of 🤗 Transformers. "
  2048. "`mps` device will be used by default if available similar to the way `cuda` device is used."
  2049. "Therefore, no action from user is required. "
  2050. )
  2051. if device.type != "mps":
  2052. raise ValueError(
  2053. "Either you do not have an MPS-enabled device on this machine or MacOS version is not 12.3+ "
  2054. "or current PyTorch install was not built with MPS enabled."
  2055. )
  2056. if self.use_cpu:
  2057. device = torch.device("cpu")
  2058. elif is_torch_mps_available():
  2059. device = torch.device("mps")
  2060. elif is_torch_xpu_available():
  2061. if not is_ipex_available() and not is_accelerate_available("0.32.0.dev"):
  2062. raise ImportError("Using the XPU PyTorch backend requires `accelerate>=0.32.0.dev`")
  2063. device = torch.device("xpu:0")
  2064. torch.xpu.set_device(device)
  2065. elif is_torch_mlu_available():
  2066. device = torch.device("mlu:0")
  2067. torch.mlu.set_device(device)
  2068. elif is_torch_musa_available():
  2069. device = torch.device("musa:0")
  2070. torch.musa.set_device(device)
  2071. elif is_torch_npu_available():
  2072. device = torch.device("npu:0")
  2073. torch.npu.set_device(device)
  2074. else:
  2075. # if n_gpu is > 1 we'll use nn.DataParallel.
  2076. # If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0`
  2077. # Explicitly set CUDA to the first (index 0) CUDA device, otherwise `set_device` will
  2078. # trigger an error that a device index is missing. Index 0 takes into account the
  2079. # GPUs available in the environment, so `CUDA_VISIBLE_DEVICES=1,2` with `cuda:0`
  2080. # will use the first GPU in that env, i.e. GPU#1
  2081. device = torch.device(
  2082. "cuda:0" if torch.cuda.is_available() else os.environ.get("ACCELERATE_TORCH_DEVICE", "cpu")
  2083. )
  2084. # Sometimes the line in the postinit has not been run before we end up here, so just checking we're not at
  2085. # the default value.
  2086. self._n_gpu = torch.cuda.device_count()
  2087. if device.type == "cuda":
  2088. torch.cuda.set_device(device)
  2089. return device
  2090. @property
  2091. def device(self) -> "torch.device":
  2092. """
  2093. The device used by this process.
  2094. """
  2095. requires_backends(self, ["torch"])
  2096. return self._setup_devices
  2097. @property
  2098. def n_gpu(self):
  2099. """
  2100. The number of GPUs used by this process.
  2101. Note:
  2102. This will only be greater than one when you have multiple GPUs available but are not using distributed
  2103. training. For distributed training, it will always be 1.
  2104. """
  2105. requires_backends(self, ["torch"])
  2106. # Make sure `self._n_gpu` is properly setup.
  2107. if not hasattr(self, "_n_gpu"):
  2108. _ = self._setup_devices
  2109. return self._n_gpu
  2110. @property
  2111. def parallel_mode(self):
  2112. """
  2113. The current mode used for parallelism if multiple GPUs/TPU cores are available. One of:
  2114. - `ParallelMode.NOT_PARALLEL`: no parallelism (CPU or one GPU).
  2115. - `ParallelMode.NOT_DISTRIBUTED`: several GPUs in one single process (uses `torch.nn.DataParallel`).
  2116. - `ParallelMode.DISTRIBUTED`: several GPUs, each having its own process (uses
  2117. `torch.nn.DistributedDataParallel`).
  2118. - `ParallelMode.TPU`: several TPU cores.
  2119. """
  2120. requires_backends(self, ["torch"])
  2121. if is_torch_xla_available():
  2122. return ParallelMode.TPU
  2123. elif is_sagemaker_mp_enabled():
  2124. return ParallelMode.SAGEMAKER_MODEL_PARALLEL
  2125. elif is_sagemaker_dp_enabled():
  2126. return ParallelMode.SAGEMAKER_DATA_PARALLEL
  2127. elif (
  2128. self.distributed_state is not None and self.distributed_state.distributed_type != DistributedType.NO
  2129. ) or (self.distributed_state is None and self.local_rank != -1):
  2130. return ParallelMode.DISTRIBUTED
  2131. elif self.n_gpu > 1:
  2132. return ParallelMode.NOT_DISTRIBUTED
  2133. else:
  2134. return ParallelMode.NOT_PARALLEL
  2135. @property
  2136. def world_size(self):
  2137. """
  2138. The number of processes used in parallel.
  2139. """
  2140. requires_backends(self, ["torch"])
  2141. if self.distributed_state is not None:
  2142. return self.distributed_state.num_processes
  2143. elif is_sagemaker_mp_enabled():
  2144. return smp.dp_size() if not smp.state.cfg.prescaled_batch else smp.rdp_size()
  2145. return 1
  2146. @property
  2147. def process_index(self):
  2148. """
  2149. The index of the current process used.
  2150. """
  2151. requires_backends(self, ["torch"])
  2152. if self.distributed_state is not None:
  2153. return self.distributed_state.process_index
  2154. elif is_sagemaker_mp_enabled():
  2155. return smp.dp_rank() if not smp.state.cfg.prescaled_batch else smp.rdp_rank()
  2156. return 0
  2157. @property
  2158. def local_process_index(self):
  2159. """
  2160. The index of the local process used.
  2161. """
  2162. requires_backends(self, ["torch"])
  2163. if self.distributed_state is not None:
  2164. return self.distributed_state.local_process_index
  2165. elif is_sagemaker_mp_enabled():
  2166. return smp.local_rank()
  2167. return 0
  2168. @property
  2169. def should_log(self):
  2170. """
  2171. Whether or not the current process should produce log.
  2172. """
  2173. if self.log_on_each_node:
  2174. return self.local_process_index == 0
  2175. else:
  2176. if is_sagemaker_mp_enabled():
  2177. return smp.rank() == 0
  2178. else:
  2179. return self.process_index == 0
  2180. @property
  2181. def should_save(self):
  2182. """
  2183. Whether or not the current process should write to disk, e.g., to save models and checkpoints.
  2184. """
  2185. if self.save_on_each_node:
  2186. return self.local_process_index == 0
  2187. else:
  2188. if is_sagemaker_mp_enabled():
  2189. return smp.rank() == 0
  2190. else:
  2191. return self.process_index == 0
  2192. def get_process_log_level(self):
  2193. """
  2194. Returns the log level to be used depending on whether this process is the main process of node 0, main process
  2195. of node non-0, or a non-main process.
  2196. For the main process the log level defaults to the logging level set (`logging.WARNING` if you didn't do
  2197. anything) unless overridden by `log_level` argument.
  2198. For the replica processes the log level defaults to `logging.WARNING` unless overridden by `log_level_replica`
  2199. argument.
  2200. The choice between the main and replica process settings is made according to the return value of `should_log`.
  2201. """
  2202. # convert to int
  2203. log_level = trainer_log_levels[self.log_level]
  2204. log_level_replica = trainer_log_levels[self.log_level_replica]
  2205. log_level_main_node = logging.get_verbosity() if log_level == -1 else log_level
  2206. log_level_replica_node = logging.get_verbosity() if log_level_replica == -1 else log_level_replica
  2207. return log_level_main_node if self.should_log else log_level_replica_node
  2208. @property
  2209. def place_model_on_device(self):
  2210. """
  2211. Can be subclassed and overridden for some specific integrations.
  2212. """
  2213. return not is_sagemaker_mp_enabled()
  2214. @property
  2215. def _no_sync_in_gradient_accumulation(self):
  2216. """
  2217. Whether or not to use no_sync for the gradients when doing gradient accumulation.
  2218. """
  2219. return not (
  2220. self.deepspeed or is_sagemaker_dp_enabled() or is_sagemaker_mp_enabled() or is_torch_neuroncore_available()
  2221. )
  2222. @contextlib.contextmanager
  2223. def main_process_first(self, local=True, desc="work"):
  2224. """
  2225. A context manager for torch distributed environment where on needs to do something on the main process, while
  2226. blocking replicas, and when it's finished releasing the replicas.
  2227. One such use is for `datasets`'s `map` feature which to be efficient should be run once on the main process,
  2228. which upon completion saves a cached version of results and which then automatically gets loaded by the
  2229. replicas.
  2230. Args:
  2231. local (`bool`, *optional*, defaults to `True`):
  2232. if `True` first means process of rank 0 of each node if `False` first means process of rank 0 of node
  2233. rank 0 In multi-node environment with a shared filesystem you most likely will want to use
  2234. `local=False` so that only the main process of the first node will do the processing. If however, the
  2235. filesystem is not shared, then the main process of each node will need to do the processing, which is
  2236. the default behavior.
  2237. desc (`str`, *optional*, defaults to `"work"`):
  2238. a work description to be used in debug logs
  2239. """
  2240. if is_torch_available() and self.world_size > 1:
  2241. main_process_desc = "main local process" if local else "main process"
  2242. if self.distributed_state is not None:
  2243. is_main_process = (
  2244. self.distributed_state.is_local_main_process if local else self.distributed_state.is_main_process
  2245. )
  2246. elif is_sagemaker_mp_enabled():
  2247. is_main_process = smp.rank() == 0
  2248. try:
  2249. if not is_main_process:
  2250. # tell all replicas to wait
  2251. logger.debug(f"{self.process_index}: waiting for the {main_process_desc} to perform {desc}")
  2252. if is_torch_xla_available():
  2253. xm.rendezvous(desc)
  2254. else:
  2255. dist.barrier()
  2256. yield
  2257. finally:
  2258. if is_main_process:
  2259. # the wait is over
  2260. logger.debug(f"{self.process_index}: {main_process_desc} completed {desc}, releasing all replicas")
  2261. if is_torch_xla_available():
  2262. xm.rendezvous(desc)
  2263. else:
  2264. dist.barrier()
  2265. else:
  2266. yield
  2267. def get_warmup_steps(self, num_training_steps: int):
  2268. """
  2269. Get number of steps used for a linear warmup.
  2270. """
  2271. warmup_steps = (
  2272. self.warmup_steps if self.warmup_steps > 0 else math.ceil(num_training_steps * self.warmup_ratio)
  2273. )
  2274. return warmup_steps
  2275. def _dict_torch_dtype_to_str(self, d: Dict[str, Any]) -> None:
  2276. """
  2277. Checks whether the passed dictionary and its nested dicts have a *torch_dtype* key and if it's not None,
  2278. converts torch.dtype to a string of just the type. For example, `torch.float32` get converted into *"float32"*
  2279. string, which can then be stored in the json format.
  2280. """
  2281. if d.get("torch_dtype", None) is not None and not isinstance(d["torch_dtype"], str):
  2282. d["torch_dtype"] = str(d["torch_dtype"]).split(".")[1]
  2283. for value in d.values():
  2284. if isinstance(value, dict):
  2285. self._dict_torch_dtype_to_str(value)
  2286. def to_dict(self):
  2287. """
  2288. Serializes this instance while replace `Enum` by their values (for JSON serialization support). It obfuscates
  2289. the token values by removing their value.
  2290. """
  2291. # filter out fields that are defined as field(init=False)
  2292. d = {field.name: getattr(self, field.name) for field in fields(self) if field.init}
  2293. for k, v in d.items():
  2294. if isinstance(v, Enum):
  2295. d[k] = v.value
  2296. if isinstance(v, list) and len(v) > 0 and isinstance(v[0], Enum):
  2297. d[k] = [x.value for x in v]
  2298. if k.endswith("_token"):
  2299. d[k] = f"<{k.upper()}>"
  2300. # Handle the accelerator_config if passed
  2301. if is_accelerate_available() and isinstance(v, AcceleratorConfig):
  2302. d[k] = v.to_dict()
  2303. self._dict_torch_dtype_to_str(d)
  2304. return d
  2305. def to_json_string(self):
  2306. """
  2307. Serializes this instance to a JSON string.
  2308. """
  2309. return json.dumps(self.to_dict(), indent=2)
  2310. def to_sanitized_dict(self) -> Dict[str, Any]:
  2311. """
  2312. Sanitized serialization to use with TensorBoard’s hparams
  2313. """
  2314. d = self.to_dict()
  2315. d = {**d, **{"train_batch_size": self.train_batch_size, "eval_batch_size": self.eval_batch_size}}
  2316. valid_types = [bool, int, float, str]
  2317. if is_torch_available():
  2318. valid_types.append(torch.Tensor)
  2319. return {k: v if type(v) in valid_types else str(v) for k, v in d.items()}
  2320. # The following methods are there to simplify the instantiation of `TrainingArguments`
  2321. def set_training(
  2322. self,
  2323. learning_rate: float = 5e-5,
  2324. batch_size: int = 8,
  2325. weight_decay: float = 0,
  2326. num_epochs: float = 3,
  2327. max_steps: int = -1,
  2328. gradient_accumulation_steps: int = 1,
  2329. seed: int = 42,
  2330. gradient_checkpointing: bool = False,
  2331. ):
  2332. """
  2333. A method that regroups all basic arguments linked to the training.
  2334. <Tip>
  2335. Calling this method will automatically set `self.do_train` to `True`.
  2336. </Tip>
  2337. Args:
  2338. learning_rate (`float`, *optional*, defaults to 5e-5):
  2339. The initial learning rate for the optimizer.
  2340. batch_size (`int` *optional*, defaults to 8):
  2341. The batch size per device (GPU/TPU core/CPU...) used for training.
  2342. weight_decay (`float`, *optional*, defaults to 0):
  2343. The weight decay to apply (if not zero) to all layers except all bias and LayerNorm weights in the
  2344. optimizer.
  2345. num_train_epochs(`float`, *optional*, defaults to 3.0):
  2346. Total number of training epochs to perform (if not an integer, will perform the decimal part percents
  2347. of the last epoch before stopping training).
  2348. max_steps (`int`, *optional*, defaults to -1):
  2349. If set to a positive number, the total number of training steps to perform. Overrides `num_train_epochs`.
  2350. For a finite dataset, training is reiterated through the dataset (if all data is exhausted) until
  2351. `max_steps` is reached.
  2352. gradient_accumulation_steps (`int`, *optional*, defaults to 1):
  2353. Number of updates steps to accumulate the gradients for, before performing a backward/update pass.
  2354. <Tip warning={true}>
  2355. When using gradient accumulation, one step is counted as one step with backward pass. Therefore,
  2356. logging, evaluation, save will be conducted every `gradient_accumulation_steps * xxx_step` training
  2357. examples.
  2358. </Tip>
  2359. seed (`int`, *optional*, defaults to 42):
  2360. Random seed that will be set at the beginning of training. To ensure reproducibility across runs, use
  2361. the [`~Trainer.model_init`] function to instantiate the model if it has some randomly initialized
  2362. parameters.
  2363. gradient_checkpointing (`bool`, *optional*, defaults to `False`):
  2364. If True, use gradient checkpointing to save memory at the expense of slower backward pass.
  2365. Example:
  2366. ```py
  2367. >>> from transformers import TrainingArguments
  2368. >>> args = TrainingArguments("working_dir")
  2369. >>> args = args.set_training(learning_rate=1e-4, batch_size=32)
  2370. >>> args.learning_rate
  2371. 1e-4
  2372. ```
  2373. """
  2374. self.do_train = True
  2375. self.learning_rate = learning_rate
  2376. self.per_device_train_batch_size = batch_size
  2377. self.weight_decay = weight_decay
  2378. self.num_train_epochs = num_epochs
  2379. self.max_steps = max_steps
  2380. self.gradient_accumulation_steps = gradient_accumulation_steps
  2381. self.seed = seed
  2382. self.gradient_checkpointing = gradient_checkpointing
  2383. return self
  2384. def set_evaluate(
  2385. self,
  2386. strategy: Union[str, IntervalStrategy] = "no",
  2387. steps: int = 500,
  2388. batch_size: int = 8,
  2389. accumulation_steps: Optional[int] = None,
  2390. delay: Optional[float] = None,
  2391. loss_only: bool = False,
  2392. jit_mode: bool = False,
  2393. ):
  2394. """
  2395. A method that regroups all arguments linked to evaluation.
  2396. Args:
  2397. strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"no"`):
  2398. The evaluation strategy to adopt during training. Possible values are:
  2399. - `"no"`: No evaluation is done during training.
  2400. - `"steps"`: Evaluation is done (and logged) every `steps`.
  2401. - `"epoch"`: Evaluation is done at the end of each epoch.
  2402. Setting a `strategy` different from `"no"` will set `self.do_eval` to `True`.
  2403. steps (`int`, *optional*, defaults to 500):
  2404. Number of update steps between two evaluations if `strategy="steps"`.
  2405. batch_size (`int` *optional*, defaults to 8):
  2406. The batch size per device (GPU/TPU core/CPU...) used for evaluation.
  2407. accumulation_steps (`int`, *optional*):
  2408. Number of predictions steps to accumulate the output tensors for, before moving the results to the CPU.
  2409. If left unset, the whole predictions are accumulated on GPU/TPU before being moved to the CPU (faster
  2410. but requires more memory).
  2411. delay (`float`, *optional*):
  2412. Number of epochs or steps to wait for before the first evaluation can be performed, depending on the
  2413. eval_strategy.
  2414. loss_only (`bool`, *optional*, defaults to `False`):
  2415. Ignores all outputs except the loss.
  2416. jit_mode (`bool`, *optional*):
  2417. Whether or not to use PyTorch jit trace for inference.
  2418. Example:
  2419. ```py
  2420. >>> from transformers import TrainingArguments
  2421. >>> args = TrainingArguments("working_dir")
  2422. >>> args = args.set_evaluate(strategy="steps", steps=100)
  2423. >>> args.eval_steps
  2424. 100
  2425. ```
  2426. """
  2427. self.eval_strategy = IntervalStrategy(strategy)
  2428. if self.eval_strategy == IntervalStrategy.STEPS and steps == 0:
  2429. raise ValueError("Setting `strategy` as 'steps' requires a positive value for `steps`.")
  2430. self.do_eval = self.eval_strategy != IntervalStrategy.NO
  2431. self.eval_steps = steps
  2432. self.per_device_eval_batch_size = batch_size
  2433. self.eval_accumulation_steps = accumulation_steps
  2434. self.eval_delay = delay
  2435. self.prediction_loss_only = loss_only
  2436. self.jit_mode_eval = jit_mode
  2437. return self
  2438. def set_testing(
  2439. self,
  2440. batch_size: int = 8,
  2441. loss_only: bool = False,
  2442. jit_mode: bool = False,
  2443. ):
  2444. """
  2445. A method that regroups all basic arguments linked to testing on a held-out dataset.
  2446. <Tip>
  2447. Calling this method will automatically set `self.do_predict` to `True`.
  2448. </Tip>
  2449. Args:
  2450. batch_size (`int` *optional*, defaults to 8):
  2451. The batch size per device (GPU/TPU core/CPU...) used for testing.
  2452. loss_only (`bool`, *optional*, defaults to `False`):
  2453. Ignores all outputs except the loss.
  2454. jit_mode (`bool`, *optional*):
  2455. Whether or not to use PyTorch jit trace for inference.
  2456. Example:
  2457. ```py
  2458. >>> from transformers import TrainingArguments
  2459. >>> args = TrainingArguments("working_dir")
  2460. >>> args = args.set_testing(batch_size=32)
  2461. >>> args.per_device_eval_batch_size
  2462. 32
  2463. ```
  2464. """
  2465. self.do_predict = True
  2466. self.per_device_eval_batch_size = batch_size
  2467. self.prediction_loss_only = loss_only
  2468. self.jit_mode_eval = jit_mode
  2469. return self
  2470. def set_save(
  2471. self,
  2472. strategy: Union[str, IntervalStrategy] = "steps",
  2473. steps: int = 500,
  2474. total_limit: Optional[int] = None,
  2475. on_each_node: bool = False,
  2476. ):
  2477. """
  2478. A method that regroups all arguments linked to checkpoint saving.
  2479. Args:
  2480. strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"steps"`):
  2481. The checkpoint save strategy to adopt during training. Possible values are:
  2482. - `"no"`: No save is done during training.
  2483. - `"epoch"`: Save is done at the end of each epoch.
  2484. - `"steps"`: Save is done every `save_steps`.
  2485. steps (`int`, *optional*, defaults to 500):
  2486. Number of updates steps before two checkpoint saves if `strategy="steps"`.
  2487. total_limit (`int`, *optional*):
  2488. If a value is passed, will limit the total amount of checkpoints. Deletes the older checkpoints in
  2489. `output_dir`.
  2490. on_each_node (`bool`, *optional*, defaults to `False`):
  2491. When doing multi-node distributed training, whether to save models and checkpoints on each node, or
  2492. only on the main one.
  2493. This should not be activated when the different nodes use the same storage as the files will be saved
  2494. with the same names for each node.
  2495. Example:
  2496. ```py
  2497. >>> from transformers import TrainingArguments
  2498. >>> args = TrainingArguments("working_dir")
  2499. >>> args = args.set_save(strategy="steps", steps=100)
  2500. >>> args.save_steps
  2501. 100
  2502. ```
  2503. """
  2504. self.save_strategy = IntervalStrategy(strategy)
  2505. if self.save_strategy == IntervalStrategy.STEPS and steps == 0:
  2506. raise ValueError("Setting `strategy` as 'steps' requires a positive value for `steps`.")
  2507. self.save_steps = steps
  2508. self.save_total_limit = total_limit
  2509. self.save_on_each_node = on_each_node
  2510. return self
  2511. def set_logging(
  2512. self,
  2513. strategy: Union[str, IntervalStrategy] = "steps",
  2514. steps: int = 500,
  2515. report_to: Union[str, List[str]] = "none",
  2516. level: str = "passive",
  2517. first_step: bool = False,
  2518. nan_inf_filter: bool = False,
  2519. on_each_node: bool = False,
  2520. replica_level: str = "passive",
  2521. ):
  2522. """
  2523. A method that regroups all arguments linked to logging.
  2524. Args:
  2525. strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"steps"`):
  2526. The logging strategy to adopt during training. Possible values are:
  2527. - `"no"`: No logging is done during training.
  2528. - `"epoch"`: Logging is done at the end of each epoch.
  2529. - `"steps"`: Logging is done every `logging_steps`.
  2530. steps (`int`, *optional*, defaults to 500):
  2531. Number of update steps between two logs if `strategy="steps"`.
  2532. level (`str`, *optional*, defaults to `"passive"`):
  2533. Logger log level to use on the main process. Possible choices are the log levels as strings: `"debug"`,
  2534. `"info"`, `"warning"`, `"error"` and `"critical"`, plus a `"passive"` level which doesn't set anything
  2535. and lets the application set the level.
  2536. report_to (`str` or `List[str]`, *optional*, defaults to `"all"`):
  2537. The list of integrations to report the results and logs to. Supported platforms are `"azure_ml"`,
  2538. `"clearml"`, `"codecarbon"`, `"comet_ml"`, `"dagshub"`, `"dvclive"`, `"flyte"`, `"mlflow"`,
  2539. `"neptune"`, `"tensorboard"`, and `"wandb"`. Use `"all"` to report to all integrations installed,
  2540. `"none"` for no integrations.
  2541. first_step (`bool`, *optional*, defaults to `False`):
  2542. Whether to log and evaluate the first `global_step` or not.
  2543. nan_inf_filter (`bool`, *optional*, defaults to `True`):
  2544. Whether to filter `nan` and `inf` losses for logging. If set to `True` the loss of every step that is
  2545. `nan` or `inf` is filtered and the average loss of the current logging window is taken instead.
  2546. <Tip>
  2547. `nan_inf_filter` only influences the logging of loss values, it does not change the behavior the
  2548. gradient is computed or applied to the model.
  2549. </Tip>
  2550. on_each_node (`bool`, *optional*, defaults to `True`):
  2551. In multinode distributed training, whether to log using `log_level` once per node, or only on the main
  2552. node.
  2553. replica_level (`str`, *optional*, defaults to `"passive"`):
  2554. Logger log level to use on replicas. Same choices as `log_level`
  2555. Example:
  2556. ```py
  2557. >>> from transformers import TrainingArguments
  2558. >>> args = TrainingArguments("working_dir")
  2559. >>> args = args.set_logging(strategy="steps", steps=100)
  2560. >>> args.logging_steps
  2561. 100
  2562. ```
  2563. """
  2564. self.logging_strategy = IntervalStrategy(strategy)
  2565. if self.logging_strategy == IntervalStrategy.STEPS and steps == 0:
  2566. raise ValueError("Setting `strategy` as 'steps' requires a positive value for `steps`.")
  2567. self.logging_steps = steps
  2568. self.report_to = report_to
  2569. self.log_level = level
  2570. self.logging_first_step = first_step
  2571. self.logging_nan_inf_filter = nan_inf_filter
  2572. self.log_on_each_node = on_each_node
  2573. self.log_level_replica = replica_level
  2574. return self
  2575. def set_push_to_hub(
  2576. self,
  2577. model_id: str,
  2578. strategy: Union[str, HubStrategy] = "every_save",
  2579. token: Optional[str] = None,
  2580. private_repo: bool = False,
  2581. always_push: bool = False,
  2582. ):
  2583. """
  2584. A method that regroups all arguments linked to synchronizing checkpoints with the Hub.
  2585. <Tip>
  2586. Calling this method will set `self.push_to_hub` to `True`, which means the `output_dir` will begin a git
  2587. directory synced with the repo (determined by `model_id`) and the content will be pushed each time a save is
  2588. triggered (depending on your `self.save_strategy`). Calling [`~Trainer.save_model`] will also trigger a push.
  2589. </Tip>
  2590. Args:
  2591. model_id (`str`):
  2592. The name of the repository to keep in sync with the local *output_dir*. It can be a simple model ID in
  2593. which case the model will be pushed in your namespace. Otherwise it should be the whole repository
  2594. name, for instance `"user_name/model"`, which allows you to push to an organization you are a member of
  2595. with `"organization_name/model"`.
  2596. strategy (`str` or [`~trainer_utils.HubStrategy`], *optional*, defaults to `"every_save"`):
  2597. Defines the scope of what is pushed to the Hub and when. Possible values are:
  2598. - `"end"`: push the model, its configuration, the processing_class e.g. tokenizer (if passed along to the [`Trainer`]) and a
  2599. draft of a model card when the [`~Trainer.save_model`] method is called.
  2600. - `"every_save"`: push the model, its configuration, the processing_class e.g. tokenizer (if passed along to the [`Trainer`])
  2601. and
  2602. a draft of a model card each time there is a model save. The pushes are asynchronous to not block
  2603. training, and in case the save are very frequent, a new push is only attempted if the previous one is
  2604. finished. A last push is made with the final model at the end of training.
  2605. - `"checkpoint"`: like `"every_save"` but the latest checkpoint is also pushed in a subfolder named
  2606. last-checkpoint, allowing you to resume training easily with
  2607. `trainer.train(resume_from_checkpoint="last-checkpoint")`.
  2608. - `"all_checkpoints"`: like `"checkpoint"` but all checkpoints are pushed like they appear in the
  2609. output
  2610. folder (so you will get one checkpoint folder per folder in your final repository)
  2611. token (`str`, *optional*):
  2612. The token to use to push the model to the Hub. Will default to the token in the cache folder obtained
  2613. with `huggingface-cli login`.
  2614. private_repo (`bool`, *optional*, defaults to `False`):
  2615. If True, the Hub repo will be set to private.
  2616. always_push (`bool`, *optional*, defaults to `False`):
  2617. Unless this is `True`, the `Trainer` will skip pushing a checkpoint when the previous push is not
  2618. finished.
  2619. Example:
  2620. ```py
  2621. >>> from transformers import TrainingArguments
  2622. >>> args = TrainingArguments("working_dir")
  2623. >>> args = args.set_push_to_hub("me/awesome-model")
  2624. >>> args.hub_model_id
  2625. 'me/awesome-model'
  2626. ```
  2627. """
  2628. self.push_to_hub = True
  2629. self.hub_model_id = model_id
  2630. self.hub_strategy = HubStrategy(strategy)
  2631. self.hub_token = token
  2632. self.hub_private_repo = private_repo
  2633. self.hub_always_push = always_push
  2634. return self
  2635. def set_optimizer(
  2636. self,
  2637. name: Union[str, OptimizerNames] = "adamw_torch",
  2638. learning_rate: float = 5e-5,
  2639. weight_decay: float = 0,
  2640. beta1: float = 0.9,
  2641. beta2: float = 0.999,
  2642. epsilon: float = 1e-8,
  2643. args: Optional[str] = None,
  2644. ):
  2645. """
  2646. A method that regroups all arguments linked to the optimizer and its hyperparameters.
  2647. Args:
  2648. name (`str` or [`training_args.OptimizerNames`], *optional*, defaults to `"adamw_torch"`):
  2649. The optimizer to use: `"adamw_hf"`, `"adamw_torch"`, `"adamw_torch_fused"`, `"adamw_apex_fused"`,
  2650. `"adamw_anyprecision"` or `"adafactor"`.
  2651. learning_rate (`float`, *optional*, defaults to 5e-5):
  2652. The initial learning rate.
  2653. weight_decay (`float`, *optional*, defaults to 0):
  2654. The weight decay to apply (if not zero) to all layers except all bias and LayerNorm weights.
  2655. beta1 (`float`, *optional*, defaults to 0.9):
  2656. The beta1 hyperparameter for the adam optimizer or its variants.
  2657. beta2 (`float`, *optional*, defaults to 0.999):
  2658. The beta2 hyperparameter for the adam optimizer or its variants.
  2659. epsilon (`float`, *optional*, defaults to 1e-8):
  2660. The epsilon hyperparameter for the adam optimizer or its variants.
  2661. args (`str`, *optional*):
  2662. Optional arguments that are supplied to AnyPrecisionAdamW (only useful when
  2663. `optim="adamw_anyprecision"`).
  2664. Example:
  2665. ```py
  2666. >>> from transformers import TrainingArguments
  2667. >>> args = TrainingArguments("working_dir")
  2668. >>> args = args.set_optimizer(name="adamw_torch", beta1=0.8)
  2669. >>> args.optim
  2670. 'adamw_torch'
  2671. ```
  2672. """
  2673. self.optim = OptimizerNames(name)
  2674. self.learning_rate = learning_rate
  2675. self.weight_decay = weight_decay
  2676. self.adam_beta1 = beta1
  2677. self.adam_beta2 = beta2
  2678. self.adam_epsilon = epsilon
  2679. self.optim_args = args
  2680. return self
  2681. def set_lr_scheduler(
  2682. self,
  2683. name: Union[str, SchedulerType] = "linear",
  2684. num_epochs: float = 3.0,
  2685. max_steps: int = -1,
  2686. warmup_ratio: float = 0,
  2687. warmup_steps: int = 0,
  2688. ):
  2689. """
  2690. A method that regroups all arguments linked to the learning rate scheduler and its hyperparameters.
  2691. Args:
  2692. name (`str` or [`SchedulerType`], *optional*, defaults to `"linear"`):
  2693. The scheduler type to use. See the documentation of [`SchedulerType`] for all possible values.
  2694. num_epochs(`float`, *optional*, defaults to 3.0):
  2695. Total number of training epochs to perform (if not an integer, will perform the decimal part percents
  2696. of the last epoch before stopping training).
  2697. max_steps (`int`, *optional*, defaults to -1):
  2698. If set to a positive number, the total number of training steps to perform. Overrides `num_train_epochs`.
  2699. For a finite dataset, training is reiterated through the dataset (if all data is exhausted) until
  2700. `max_steps` is reached.
  2701. warmup_ratio (`float`, *optional*, defaults to 0.0):
  2702. Ratio of total training steps used for a linear warmup from 0 to `learning_rate`.
  2703. warmup_steps (`int`, *optional*, defaults to 0):
  2704. Number of steps used for a linear warmup from 0 to `learning_rate`. Overrides any effect of
  2705. `warmup_ratio`.
  2706. Example:
  2707. ```py
  2708. >>> from transformers import TrainingArguments
  2709. >>> args = TrainingArguments("working_dir")
  2710. >>> args = args.set_lr_scheduler(name="cosine", warmup_ratio=0.05)
  2711. >>> args.warmup_ratio
  2712. 0.05
  2713. ```
  2714. """
  2715. self.lr_scheduler_type = SchedulerType(name)
  2716. self.num_train_epochs = num_epochs
  2717. self.max_steps = max_steps
  2718. self.warmup_ratio = warmup_ratio
  2719. self.warmup_steps = warmup_steps
  2720. return self
  2721. def set_dataloader(
  2722. self,
  2723. train_batch_size: int = 8,
  2724. eval_batch_size: int = 8,
  2725. drop_last: bool = False,
  2726. num_workers: int = 0,
  2727. pin_memory: bool = True,
  2728. persistent_workers: bool = False,
  2729. prefetch_factor: Optional[int] = None,
  2730. auto_find_batch_size: bool = False,
  2731. ignore_data_skip: bool = False,
  2732. sampler_seed: Optional[int] = None,
  2733. ):
  2734. """
  2735. A method that regroups all arguments linked to the dataloaders creation.
  2736. Args:
  2737. drop_last (`bool`, *optional*, defaults to `False`):
  2738. Whether to drop the last incomplete batch (if the length of the dataset is not divisible by the batch
  2739. size) or not.
  2740. num_workers (`int`, *optional*, defaults to 0):
  2741. Number of subprocesses to use for data loading (PyTorch only). 0 means that the data will be loaded in
  2742. the main process.
  2743. pin_memory (`bool`, *optional*, defaults to `True`):
  2744. Whether you want to pin memory in data loaders or not. Will default to `True`.
  2745. persistent_workers (`bool`, *optional*, defaults to `False`):
  2746. If True, the data loader will not shut down the worker processes after a dataset has been consumed
  2747. once. This allows to maintain the workers Dataset instances alive. Can potentially speed up training,
  2748. but will increase RAM usage. Will default to `False`.
  2749. prefetch_factor (`int`, *optional*):
  2750. Number of batches loaded in advance by each worker.
  2751. 2 means there will be a total of 2 * num_workers batches prefetched across all workers.
  2752. auto_find_batch_size (`bool`, *optional*, defaults to `False`)
  2753. Whether to find a batch size that will fit into memory automatically through exponential decay,
  2754. avoiding CUDA Out-of-Memory errors. Requires accelerate to be installed (`pip install accelerate`)
  2755. ignore_data_skip (`bool`, *optional*, defaults to `False`):
  2756. When resuming training, whether or not to skip the epochs and batches to get the data loading at the
  2757. same stage as in the previous training. If set to `True`, the training will begin faster (as that
  2758. skipping step can take a long time) but will not yield the same results as the interrupted training
  2759. would have.
  2760. sampler_seed (`int`, *optional*):
  2761. Random seed to be used with data samplers. If not set, random generators for data sampling will use the
  2762. same seed as `self.seed`. This can be used to ensure reproducibility of data sampling, independent of
  2763. the model seed.
  2764. Example:
  2765. ```py
  2766. >>> from transformers import TrainingArguments
  2767. >>> args = TrainingArguments("working_dir")
  2768. >>> args = args.set_dataloader(train_batch_size=16, eval_batch_size=64)
  2769. >>> args.per_device_train_batch_size
  2770. 16
  2771. ```
  2772. """
  2773. self.per_device_train_batch_size = train_batch_size
  2774. self.per_device_eval_batch_size = eval_batch_size
  2775. self.dataloader_drop_last = drop_last
  2776. self.dataloader_num_workers = num_workers
  2777. self.dataloader_pin_memory = pin_memory
  2778. self.dataloader_persistent_workers = persistent_workers
  2779. self.dataloader_prefetch_factor = prefetch_factor
  2780. self.auto_find_batch_size = auto_find_batch_size
  2781. self.ignore_data_skip = ignore_data_skip
  2782. self.data_seed = sampler_seed
  2783. return self
  2784. class ParallelMode(Enum):
  2785. NOT_PARALLEL = "not_parallel"
  2786. NOT_DISTRIBUTED = "not_distributed"
  2787. DISTRIBUTED = "distributed"
  2788. SAGEMAKER_MODEL_PARALLEL = "sagemaker_model_parallel"
  2789. SAGEMAKER_DATA_PARALLEL = "sagemaker_data_parallel"
  2790. TPU = "tpu"