training_args.py 159 KB

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