trainer_callback.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
  1. # Copyright 2020-present the HuggingFace Inc. team.
  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. """
  15. Callbacks to use with the Trainer class and customize the training loop.
  16. """
  17. import dataclasses
  18. import json
  19. import math
  20. from dataclasses import dataclass
  21. from typing import Optional, Union
  22. import numpy as np
  23. from tqdm.auto import tqdm
  24. from .trainer_utils import HPSearchBackend, IntervalStrategy, SaveStrategy, has_length
  25. from .training_args import TrainingArguments
  26. from .utils import logging
  27. logger = logging.get_logger(__name__)
  28. @dataclass
  29. class TrainerState:
  30. """
  31. A class containing the [`Trainer`] inner state that will be saved along the model and optimizer when checkpointing
  32. and passed to the [`TrainerCallback`].
  33. <Tip>
  34. In all this class, one step is to be understood as one update step. When using gradient accumulation, one update
  35. step may require several forward and backward passes: if you use `gradient_accumulation_steps=n`, then one update
  36. step requires going through *n* batches.
  37. </Tip>
  38. Args:
  39. epoch (`float`, *optional*):
  40. Only set during training, will represent the epoch the training is at (the decimal part being the
  41. percentage of the current epoch completed).
  42. global_step (`int`, *optional*, defaults to 0):
  43. During training, represents the number of update steps completed.
  44. max_steps (`int`, *optional*, defaults to 0):
  45. The number of update steps to do during the current training.
  46. logging_steps (`int`, *optional*, defaults to 500):
  47. Log every X updates steps
  48. eval_steps (`int`, *optional*):
  49. Run an evaluation every X steps.
  50. save_steps (`int`, *optional*, defaults to 500):
  51. Save checkpoint every X updates steps.
  52. train_batch_size (`int`, *optional*):
  53. The batch size for the training dataloader. Only needed when
  54. `auto_find_batch_size` has been used.
  55. num_input_tokens_seen (`int`, *optional*, defaults to 0):
  56. When tracking the inputs tokens, the number of tokens seen during training (number of input tokens, not the
  57. number of prediction tokens).
  58. total_flos (`float`, *optional*, defaults to 0):
  59. The total number of floating operations done by the model since the beginning of training (stored as floats
  60. to avoid overflow).
  61. log_history (`list[dict[str, float]]`, *optional*):
  62. The list of logs done since the beginning of training.
  63. best_metric (`float`, *optional*):
  64. When tracking the best model, the value of the best metric encountered so far.
  65. best_global_step (`int`, *optional*):
  66. When tracking the best model, the step at which the best metric was encountered.
  67. Used for setting `best_model_checkpoint`.
  68. best_model_checkpoint (`str`, *optional*):
  69. When tracking the best model, the value of the name of the checkpoint for the best model encountered so
  70. far.
  71. is_local_process_zero (`bool`, *optional*, defaults to `True`):
  72. Whether or not this process is the local (e.g., on one machine if training in a distributed fashion on
  73. several machines) main process.
  74. is_world_process_zero (`bool`, *optional*, defaults to `True`):
  75. Whether or not this process is the global main process (when training in a distributed fashion on several
  76. machines, this is only going to be `True` for one process).
  77. is_hyper_param_search (`bool`, *optional*, defaults to `False`):
  78. Whether we are in the process of a hyper parameter search using Trainer.hyperparameter_search. This will
  79. impact the way data will be logged in TensorBoard.
  80. stateful_callbacks (`list[StatefulTrainerCallback]`, *optional*):
  81. Callbacks attached to the `Trainer` that should have their states be saved or restored.
  82. Relevant callbacks should implement a `state` and `from_state` function.
  83. """
  84. epoch: Optional[float] = None
  85. global_step: int = 0
  86. max_steps: int = 0
  87. logging_steps: int = 500
  88. eval_steps: int = 500
  89. save_steps: int = 500
  90. train_batch_size: Optional[int] = None
  91. num_train_epochs: int = 0
  92. num_input_tokens_seen: int = 0
  93. total_flos: float = 0
  94. log_history: list[dict[str, float]] = None
  95. best_metric: Optional[float] = None
  96. best_global_step: Optional[int] = None
  97. best_model_checkpoint: Optional[str] = None
  98. is_local_process_zero: bool = True
  99. is_world_process_zero: bool = True
  100. is_hyper_param_search: bool = False
  101. trial_name: Optional[str] = None
  102. trial_params: Optional[dict[str, Union[str, float, int, bool]]] = None
  103. stateful_callbacks: Optional[list["TrainerCallback"]] = None
  104. def __post_init__(self):
  105. if self.log_history is None:
  106. self.log_history = []
  107. if self.stateful_callbacks is None:
  108. self.stateful_callbacks = {}
  109. elif isinstance(self.stateful_callbacks, dict):
  110. # We are loading the callbacks in from the state file, no need to process them
  111. pass
  112. else:
  113. # Saveable callbacks get stored as dict of kwargs
  114. stateful_callbacks = {}
  115. for callback in self.stateful_callbacks:
  116. if not isinstance(callback, (ExportableState)):
  117. raise TypeError(
  118. f"All callbacks passed to be saved must inherit `ExportableState`, but received {type(callback)}"
  119. )
  120. name = callback.__class__.__name__
  121. if name in stateful_callbacks:
  122. # We can have multiple versions of the same callback
  123. # if so, we store them as a list of states to restore
  124. if not isinstance(stateful_callbacks[name], list):
  125. stateful_callbacks[name] = [stateful_callbacks[name]]
  126. stateful_callbacks[name].append(callback.state())
  127. else:
  128. stateful_callbacks[name] = callback.state()
  129. self.stateful_callbacks = stateful_callbacks
  130. def save_to_json(self, json_path: str):
  131. """Save the content of this instance in JSON format inside `json_path`."""
  132. json_string = json.dumps(dataclasses.asdict(self), indent=2, sort_keys=True) + "\n"
  133. with open(json_path, "w", encoding="utf-8") as f:
  134. f.write(json_string)
  135. @classmethod
  136. def load_from_json(cls, json_path: str):
  137. """Create an instance from the content of `json_path`."""
  138. with open(json_path, encoding="utf-8") as f:
  139. text = f.read()
  140. return cls(**json.loads(text))
  141. def compute_steps(self, args, max_steps):
  142. """
  143. Calculates and stores the absolute value for logging,
  144. eval, and save steps based on if it was a proportion
  145. or not.
  146. """
  147. for step_kind in ("logging", "eval", "save"):
  148. num_steps = getattr(args, f"{step_kind}_steps")
  149. if num_steps is not None:
  150. if num_steps < 1:
  151. num_steps = math.ceil(max_steps * num_steps)
  152. setattr(self, f"{step_kind}_steps", num_steps)
  153. def init_training_references(self, trainer, max_steps, num_train_epochs, trial):
  154. """
  155. Stores the initial training references needed in `self`
  156. """
  157. if trainer.hp_name is not None and trainer._trial is not None:
  158. # use self._trial because the SigOpt/Optuna hpo only call `_hp_search_setup(trial)` instead of passing trial
  159. # parameter to Train when using DDP.
  160. self.trial_name = trainer.hp_name(trainer._trial)
  161. self.trial_params = None
  162. if trial is not None:
  163. from transformers.integrations import hp_params
  164. assignments = trial.assignments if trainer.hp_search_backend == HPSearchBackend.SIGOPT else trial
  165. self.trial_params = hp_params(assignments)
  166. self.max_steps = max_steps
  167. self.num_train_epochs = num_train_epochs
  168. self.is_local_process_zero = trainer.is_local_process_zero()
  169. self.is_world_process_zero = trainer.is_world_process_zero()
  170. class ExportableState:
  171. """
  172. A class for objects that include the ability to have its state
  173. be saved during `Trainer._save_checkpoint` and loaded back in during
  174. `Trainer._load_from_checkpoint`.
  175. These must implement a `state` function that gets called during the respective
  176. Trainer function call. It should only include parameters and attributes needed to
  177. recreate the state at a particular time, to avoid utilizing pickle/maintain standard
  178. file IO writing.
  179. Example:
  180. ```python
  181. class EarlyStoppingCallback(TrainerCallback, ExportableState):
  182. def __init__(self, early_stopping_patience: int = 1, early_stopping_threshold: Optional[float] = 0.0):
  183. self.early_stopping_patience = early_stopping_patience
  184. self.early_stopping_threshold = early_stopping_threshold
  185. # early_stopping_patience_counter denotes the number of times validation metrics failed to improve.
  186. self.early_stopping_patience_counter = 0
  187. def state(self) -> dict:
  188. return {
  189. "args": {
  190. "early_stopping_patience": self.early_stopping_patience,
  191. "early_stopping_threshold": self.early_stopping_threshold,
  192. },
  193. "attributes": {
  194. "early_stopping_patience_counter": self.early_stopping_patience_counter,
  195. }
  196. }
  197. ```"""
  198. def state(self) -> dict:
  199. raise NotImplementedError("You must implement a `state` function to utilize this class.")
  200. @classmethod
  201. def from_state(cls, state):
  202. instance = cls(**state["args"])
  203. for k, v in state["attributes"].items():
  204. setattr(instance, k, v)
  205. return instance
  206. @dataclass
  207. class TrainerControl(ExportableState):
  208. """
  209. A class that handles the [`Trainer`] control flow. This class is used by the [`TrainerCallback`] to activate some
  210. switches in the training loop.
  211. Args:
  212. should_training_stop (`bool`, *optional*, defaults to `False`):
  213. Whether or not the training should be interrupted.
  214. If `True`, this variable will not be set back to `False`. The training will just stop.
  215. should_epoch_stop (`bool`, *optional*, defaults to `False`):
  216. Whether or not the current epoch should be interrupted.
  217. If `True`, this variable will be set back to `False` at the beginning of the next epoch.
  218. should_save (`bool`, *optional*, defaults to `False`):
  219. Whether or not the model should be saved at this step.
  220. If `True`, this variable will be set back to `False` at the beginning of the next step.
  221. should_evaluate (`bool`, *optional*, defaults to `False`):
  222. Whether or not the model should be evaluated at this step.
  223. If `True`, this variable will be set back to `False` at the beginning of the next step.
  224. should_log (`bool`, *optional*, defaults to `False`):
  225. Whether or not the logs should be reported at this step.
  226. If `True`, this variable will be set back to `False` at the beginning of the next step.
  227. """
  228. should_training_stop: bool = False
  229. should_epoch_stop: bool = False
  230. should_save: bool = False
  231. should_evaluate: bool = False
  232. should_log: bool = False
  233. def _new_training(self):
  234. """Internal method that resets the variable for a new training."""
  235. self.should_training_stop = False
  236. def _new_epoch(self):
  237. """Internal method that resets the variable for a new epoch."""
  238. self.should_epoch_stop = False
  239. def _new_step(self):
  240. """Internal method that resets the variable for a new step."""
  241. self.should_save = False
  242. self.should_evaluate = False
  243. self.should_log = False
  244. def state(self) -> dict:
  245. return {
  246. "args": {
  247. "should_training_stop": self.should_training_stop,
  248. "should_epoch_stop": self.should_epoch_stop,
  249. "should_save": self.should_save,
  250. "should_evaluate": self.should_evaluate,
  251. "should_log": self.should_log,
  252. },
  253. "attributes": {},
  254. }
  255. class TrainerCallback:
  256. # no-format
  257. """
  258. A class for objects that will inspect the state of the training loop at some events and take some decisions. At
  259. each of those events the following arguments are available:
  260. Args:
  261. args ([`TrainingArguments`]):
  262. The training arguments used to instantiate the [`Trainer`].
  263. state ([`TrainerState`]):
  264. The current state of the [`Trainer`].
  265. control ([`TrainerControl`]):
  266. The object that is returned to the [`Trainer`] and can be used to make some decisions.
  267. model ([`PreTrainedModel`] or `torch.nn.Module`):
  268. The model being trained.
  269. tokenizer ([`PreTrainedTokenizer`]):
  270. The tokenizer used for encoding the data. This is deprecated in favour of `processing_class`.
  271. processing_class ([`PreTrainedTokenizer` or `BaseImageProcessor` or `ProcessorMixin` or `FeatureExtractionMixin`]):
  272. The processing class used for encoding the data. Can be a tokenizer, a processor, an image processor or a feature extractor.
  273. optimizer (`torch.optim.Optimizer`):
  274. The optimizer used for the training steps.
  275. lr_scheduler (`torch.optim.lr_scheduler.LambdaLR`):
  276. The scheduler used for setting the learning rate.
  277. train_dataloader (`torch.utils.data.DataLoader`, *optional*):
  278. The current dataloader used for training.
  279. eval_dataloader (`torch.utils.data.DataLoader`, *optional*):
  280. The current dataloader used for evaluation.
  281. metrics (`dict[str, float]`):
  282. The metrics computed by the last evaluation phase.
  283. Those are only accessible in the event `on_evaluate`.
  284. logs (`dict[str, float]`):
  285. The values to log.
  286. Those are only accessible in the event `on_log`.
  287. The `control` object is the only one that can be changed by the callback, in which case the event that changes it
  288. should return the modified version.
  289. The argument `args`, `state` and `control` are positionals for all events, all the others are grouped in `kwargs`.
  290. You can unpack the ones you need in the signature of the event using them. As an example, see the code of the
  291. simple [`~transformers.PrinterCallback`].
  292. Example:
  293. ```python
  294. class PrinterCallback(TrainerCallback):
  295. def on_log(self, args, state, control, logs=None, **kwargs):
  296. _ = logs.pop("total_flos", None)
  297. if state.is_local_process_zero:
  298. print(logs)
  299. ```"""
  300. def on_init_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs):
  301. """
  302. Event called at the end of the initialization of the [`Trainer`].
  303. """
  304. pass
  305. def on_train_begin(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs):
  306. """
  307. Event called at the beginning of training.
  308. """
  309. pass
  310. def on_train_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs):
  311. """
  312. Event called at the end of training.
  313. """
  314. pass
  315. def on_epoch_begin(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs):
  316. """
  317. Event called at the beginning of an epoch.
  318. """
  319. pass
  320. def on_epoch_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs):
  321. """
  322. Event called at the end of an epoch.
  323. """
  324. pass
  325. def on_step_begin(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs):
  326. """
  327. Event called at the beginning of a training step. If using gradient accumulation, one training step might take
  328. several inputs.
  329. """
  330. pass
  331. def on_pre_optimizer_step(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs):
  332. """
  333. Event called before the optimizer step but after gradient clipping. Useful for monitoring gradients.
  334. """
  335. pass
  336. def on_optimizer_step(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs):
  337. """
  338. Event called after the optimizer step but before gradients are zeroed out. Useful for monitoring gradients.
  339. """
  340. pass
  341. def on_substep_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs):
  342. """
  343. Event called at the end of an substep during gradient accumulation.
  344. """
  345. pass
  346. def on_step_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs):
  347. """
  348. Event called at the end of a training step. If using gradient accumulation, one training step might take
  349. several inputs.
  350. """
  351. pass
  352. def on_evaluate(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs):
  353. """
  354. Event called after an evaluation phase.
  355. """
  356. pass
  357. def on_predict(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, metrics, **kwargs):
  358. """
  359. Event called after a successful prediction.
  360. """
  361. pass
  362. def on_save(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs):
  363. """
  364. Event called after a checkpoint save.
  365. """
  366. pass
  367. def on_log(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs):
  368. """
  369. Event called after logging the last logs.
  370. """
  371. pass
  372. def on_prediction_step(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs):
  373. """
  374. Event called after a prediction step.
  375. """
  376. pass
  377. class CallbackHandler(TrainerCallback):
  378. """Internal class that just calls the list of callbacks in order."""
  379. def __init__(self, callbacks, model, processing_class, optimizer, lr_scheduler):
  380. self.callbacks = []
  381. for cb in callbacks:
  382. self.add_callback(cb)
  383. self.model = model
  384. self.processing_class = processing_class
  385. self.optimizer = optimizer
  386. self.lr_scheduler = lr_scheduler
  387. self.train_dataloader = None
  388. self.eval_dataloader = None
  389. if not any(isinstance(cb, DefaultFlowCallback) for cb in self.callbacks):
  390. logger.warning(
  391. "The Trainer will not work properly if you don't have a `DefaultFlowCallback` in its callbacks. You\n"
  392. + "should add one before training with `trainer.add_callback(DefaultFlowCallback). The current list of"
  393. + "callbacks is\n:"
  394. + self.callback_list
  395. )
  396. def add_callback(self, callback):
  397. cb = callback() if isinstance(callback, type) else callback
  398. cb_class = callback if isinstance(callback, type) else callback.__class__
  399. if cb_class in [c.__class__ for c in self.callbacks]:
  400. logger.warning(
  401. f"You are adding a {cb_class} to the callbacks of this Trainer, but there is already one. The current"
  402. + "list of callbacks is\n:"
  403. + self.callback_list
  404. )
  405. self.callbacks.append(cb)
  406. def pop_callback(self, callback):
  407. if isinstance(callback, type):
  408. for cb in self.callbacks:
  409. if isinstance(cb, callback):
  410. self.callbacks.remove(cb)
  411. return cb
  412. else:
  413. for cb in self.callbacks:
  414. if cb == callback:
  415. self.callbacks.remove(cb)
  416. return cb
  417. def remove_callback(self, callback):
  418. if isinstance(callback, type):
  419. for cb in self.callbacks:
  420. if isinstance(cb, callback):
  421. self.callbacks.remove(cb)
  422. return
  423. else:
  424. self.callbacks.remove(callback)
  425. @property
  426. def callback_list(self):
  427. return "\n".join(cb.__class__.__name__ for cb in self.callbacks)
  428. def on_init_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl):
  429. return self.call_event("on_init_end", args, state, control)
  430. def on_train_begin(self, args: TrainingArguments, state: TrainerState, control: TrainerControl):
  431. control.should_training_stop = False
  432. return self.call_event("on_train_begin", args, state, control)
  433. def on_train_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl):
  434. return self.call_event("on_train_end", args, state, control)
  435. def on_epoch_begin(self, args: TrainingArguments, state: TrainerState, control: TrainerControl):
  436. control.should_epoch_stop = False
  437. return self.call_event("on_epoch_begin", args, state, control)
  438. def on_epoch_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl):
  439. return self.call_event("on_epoch_end", args, state, control)
  440. def on_step_begin(self, args: TrainingArguments, state: TrainerState, control: TrainerControl):
  441. control.should_log = False
  442. control.should_evaluate = False
  443. control.should_save = False
  444. return self.call_event("on_step_begin", args, state, control)
  445. def on_pre_optimizer_step(self, args: TrainingArguments, state: TrainerState, control: TrainerControl):
  446. return self.call_event("on_pre_optimizer_step", args, state, control)
  447. def on_optimizer_step(self, args: TrainingArguments, state: TrainerState, control: TrainerControl):
  448. return self.call_event("on_optimizer_step", args, state, control)
  449. def on_substep_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl):
  450. return self.call_event("on_substep_end", args, state, control)
  451. def on_step_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl):
  452. return self.call_event("on_step_end", args, state, control)
  453. def on_evaluate(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, metrics):
  454. control.should_evaluate = False
  455. return self.call_event("on_evaluate", args, state, control, metrics=metrics)
  456. def on_predict(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, metrics):
  457. return self.call_event("on_predict", args, state, control, metrics=metrics)
  458. def on_save(self, args: TrainingArguments, state: TrainerState, control: TrainerControl):
  459. control.should_save = False
  460. return self.call_event("on_save", args, state, control)
  461. def on_log(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, logs):
  462. control.should_log = False
  463. return self.call_event("on_log", args, state, control, logs=logs)
  464. def on_prediction_step(self, args: TrainingArguments, state: TrainerState, control: TrainerControl):
  465. return self.call_event("on_prediction_step", args, state, control)
  466. def call_event(self, event, args, state, control, **kwargs):
  467. for callback in self.callbacks:
  468. result = getattr(callback, event)(
  469. args,
  470. state,
  471. control,
  472. model=self.model,
  473. processing_class=self.processing_class,
  474. optimizer=self.optimizer,
  475. lr_scheduler=self.lr_scheduler,
  476. train_dataloader=self.train_dataloader,
  477. eval_dataloader=self.eval_dataloader,
  478. **kwargs,
  479. )
  480. # A Callback can skip the return of `control` if it doesn't change it.
  481. if result is not None:
  482. control = result
  483. return control
  484. class DefaultFlowCallback(TrainerCallback):
  485. """
  486. A [`TrainerCallback`] that handles the default flow of the training loop for logs, evaluation and checkpoints.
  487. """
  488. def on_step_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs):
  489. # Log
  490. if state.global_step == 1 and args.logging_first_step:
  491. control.should_log = True
  492. if args.logging_strategy == IntervalStrategy.STEPS and state.global_step % state.logging_steps == 0:
  493. control.should_log = True
  494. # Evaluate
  495. if (
  496. args.eval_strategy == IntervalStrategy.STEPS
  497. and state.global_step % state.eval_steps == 0
  498. and args.eval_delay <= state.global_step
  499. ):
  500. control.should_evaluate = True
  501. # Save
  502. if (
  503. args.save_strategy == SaveStrategy.STEPS
  504. and state.save_steps > 0
  505. and state.global_step % state.save_steps == 0
  506. ):
  507. control.should_save = True
  508. # End training
  509. if state.global_step >= state.max_steps:
  510. control.should_training_stop = True
  511. # Save the model at the end if we have a save strategy
  512. if args.save_strategy == SaveStrategy.STEPS:
  513. control.should_save = True
  514. return control
  515. def on_epoch_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs):
  516. # Log
  517. if args.logging_strategy == IntervalStrategy.EPOCH:
  518. control.should_log = True
  519. # Evaluate
  520. if args.eval_strategy == IntervalStrategy.EPOCH and args.eval_delay <= state.epoch:
  521. control.should_evaluate = True
  522. # Save
  523. if args.save_strategy == SaveStrategy.EPOCH:
  524. control.should_save = True
  525. return control
  526. class ProgressCallback(TrainerCallback):
  527. """
  528. A [`TrainerCallback`] that displays the progress of training or evaluation.
  529. You can modify `max_str_len` to control how long strings are truncated when logging.
  530. """
  531. def __init__(self, max_str_len: int = 100):
  532. """
  533. Initialize the callback with optional max_str_len parameter to control string truncation length.
  534. Args:
  535. max_str_len (`int`):
  536. Maximum length of strings to display in logs.
  537. Longer strings will be truncated with a message.
  538. """
  539. self.training_bar = None
  540. self.prediction_bar = None
  541. self.max_str_len = max_str_len
  542. def on_train_begin(self, args, state, control, **kwargs):
  543. if state.is_world_process_zero:
  544. self.training_bar = tqdm(total=state.max_steps, dynamic_ncols=True)
  545. self.current_step = 0
  546. def on_step_end(self, args, state, control, **kwargs):
  547. if state.is_world_process_zero:
  548. self.training_bar.update(state.global_step - self.current_step)
  549. self.current_step = state.global_step
  550. def on_prediction_step(self, args, state, control, eval_dataloader=None, **kwargs):
  551. if state.is_world_process_zero and has_length(eval_dataloader):
  552. if self.prediction_bar is None:
  553. self.prediction_bar = tqdm(
  554. total=len(eval_dataloader), leave=self.training_bar is None, dynamic_ncols=True
  555. )
  556. self.prediction_bar.update(1)
  557. def on_evaluate(self, args, state, control, **kwargs):
  558. if state.is_world_process_zero:
  559. if self.prediction_bar is not None:
  560. self.prediction_bar.close()
  561. self.prediction_bar = None
  562. def on_predict(self, args, state, control, **kwargs):
  563. if state.is_world_process_zero:
  564. if self.prediction_bar is not None:
  565. self.prediction_bar.close()
  566. self.prediction_bar = None
  567. def on_log(self, args, state, control, logs=None, **kwargs):
  568. if state.is_world_process_zero and self.training_bar is not None:
  569. # make a shallow copy of logs so we can mutate the fields copied
  570. # but avoid doing any value pickling.
  571. shallow_logs = {}
  572. for k, v in logs.items():
  573. if isinstance(v, str) and len(v) > self.max_str_len:
  574. shallow_logs[k] = (
  575. f"[String too long to display, length: {len(v)} > {self.max_str_len}. "
  576. "Consider increasing `max_str_len` if needed.]"
  577. )
  578. else:
  579. shallow_logs[k] = v
  580. _ = shallow_logs.pop("total_flos", None)
  581. # round numbers so that it looks better in console
  582. if "epoch" in shallow_logs:
  583. shallow_logs["epoch"] = round(shallow_logs["epoch"], 2)
  584. self.training_bar.write(str(shallow_logs))
  585. def on_train_end(self, args, state, control, **kwargs):
  586. if state.is_world_process_zero:
  587. self.training_bar.close()
  588. self.training_bar = None
  589. class PrinterCallback(TrainerCallback):
  590. """
  591. A bare [`TrainerCallback`] that just prints the logs.
  592. """
  593. def on_log(self, args, state, control, logs=None, **kwargs):
  594. _ = logs.pop("total_flos", None)
  595. if state.is_local_process_zero:
  596. print(logs)
  597. class EarlyStoppingCallback(TrainerCallback, ExportableState):
  598. """
  599. A [`TrainerCallback`] that handles early stopping.
  600. Args:
  601. early_stopping_patience (`int`):
  602. Use with `metric_for_best_model` to stop training when the specified metric worsens for
  603. `early_stopping_patience` evaluation calls.
  604. early_stopping_threshold(`float`, *optional*):
  605. Use with TrainingArguments `metric_for_best_model` and `early_stopping_patience` to denote how much the
  606. specified metric must improve to satisfy early stopping conditions. `
  607. This callback depends on [`TrainingArguments`] argument *load_best_model_at_end* functionality to set best_metric
  608. in [`TrainerState`]. Note that if the [`TrainingArguments`] argument *save_steps* differs from *eval_steps*, the
  609. early stopping will not occur until the next save step.
  610. """
  611. def __init__(self, early_stopping_patience: int = 1, early_stopping_threshold: Optional[float] = 0.0):
  612. self.early_stopping_patience = early_stopping_patience
  613. self.early_stopping_threshold = early_stopping_threshold
  614. # early_stopping_patience_counter denotes the number of times validation metrics failed to improve.
  615. self.early_stopping_patience_counter = 0
  616. def check_metric_value(self, args, state, control, metric_value):
  617. # best_metric is set by code for load_best_model
  618. operator = np.greater if args.greater_is_better else np.less
  619. if state.best_metric is None or (
  620. operator(metric_value, state.best_metric)
  621. and abs(metric_value - state.best_metric) > self.early_stopping_threshold
  622. ):
  623. self.early_stopping_patience_counter = 0
  624. else:
  625. self.early_stopping_patience_counter += 1
  626. def on_train_begin(self, args, state, control, **kwargs):
  627. if not args.load_best_model_at_end:
  628. logger.warning(
  629. "Using EarlyStoppingCallback without load_best_model_at_end=True. "
  630. "Once training is finished, the best model will not be loaded automatically."
  631. )
  632. assert args.metric_for_best_model is not None, (
  633. "EarlyStoppingCallback requires metric_for_best_model to be defined"
  634. )
  635. assert args.eval_strategy != IntervalStrategy.NO, (
  636. "EarlyStoppingCallback requires IntervalStrategy of steps or epoch"
  637. )
  638. def on_evaluate(self, args, state, control, metrics, **kwargs):
  639. metric_to_check = args.metric_for_best_model
  640. if not metric_to_check.startswith("eval_"):
  641. metric_to_check = f"eval_{metric_to_check}"
  642. metric_value = metrics.get(metric_to_check)
  643. if metric_value is None:
  644. logger.warning(
  645. f"early stopping required metric_for_best_model, but did not find {metric_to_check} so early stopping"
  646. " is disabled"
  647. )
  648. return
  649. self.check_metric_value(args, state, control, metric_value)
  650. if self.early_stopping_patience_counter >= self.early_stopping_patience:
  651. control.should_training_stop = True
  652. def state(self) -> dict:
  653. return {
  654. "args": {
  655. "early_stopping_patience": self.early_stopping_patience,
  656. "early_stopping_threshold": self.early_stopping_threshold,
  657. },
  658. "attributes": {
  659. "early_stopping_patience_counter": self.early_stopping_patience_counter,
  660. },
  661. }