trainer_pt_utils.py 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406
  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. Torch utilities for the Trainer class.
  16. """
  17. import copy
  18. import datetime
  19. import io
  20. import json
  21. import math
  22. import os
  23. import re
  24. import sys
  25. import warnings
  26. from collections.abc import Iterator, Mapping
  27. from contextlib import contextmanager
  28. from dataclasses import dataclass, field
  29. from itertools import chain
  30. from logging import StreamHandler
  31. from typing import Any, Optional, Union
  32. import numpy as np
  33. import torch
  34. import torch.distributed as dist
  35. from torch import nn
  36. from torch.utils.data import Dataset, IterableDataset, RandomSampler, Sampler
  37. from torch.utils.data.distributed import DistributedSampler
  38. from .integrations.deepspeed import is_deepspeed_zero3_enabled
  39. from .tokenization_utils_base import BatchEncoding
  40. from .utils import (
  41. is_sagemaker_mp_enabled,
  42. is_torch_available,
  43. is_torch_xla_available,
  44. is_training_run_on_sagemaker,
  45. logging,
  46. )
  47. if is_training_run_on_sagemaker():
  48. logging.add_handler(StreamHandler(sys.stdout))
  49. if is_torch_xla_available():
  50. import torch_xla.runtime as xr
  51. if is_torch_available():
  52. from torch.optim.lr_scheduler import LRScheduler
  53. logger = logging.get_logger(__name__)
  54. def get_dataloader_sampler(dataloader):
  55. if hasattr(dataloader, "batch_sampler") and dataloader.batch_sampler is not None:
  56. return get_dataloader_sampler(dataloader.batch_sampler)
  57. elif hasattr(dataloader, "sampler"):
  58. return dataloader.sampler
  59. def atleast_1d(tensor_or_array: Union[torch.Tensor, np.ndarray]):
  60. if isinstance(tensor_or_array, torch.Tensor):
  61. if hasattr(torch, "atleast_1d"):
  62. tensor_or_array = torch.atleast_1d(tensor_or_array)
  63. elif tensor_or_array.ndim < 1:
  64. tensor_or_array = tensor_or_array[None]
  65. else:
  66. tensor_or_array = np.atleast_1d(tensor_or_array)
  67. return tensor_or_array
  68. def torch_pad_and_concatenate(tensor1, tensor2, padding_index=-100):
  69. """Concatenates `tensor1` and `tensor2` on first axis, applying padding on the second if necessary."""
  70. tensor1 = atleast_1d(tensor1)
  71. tensor2 = atleast_1d(tensor2)
  72. if len(tensor1.shape) == 1 or tensor1.shape[1] == tensor2.shape[1]:
  73. return torch.cat((tensor1, tensor2), dim=0)
  74. # Let's figure out the new shape
  75. new_shape = (tensor1.shape[0] + tensor2.shape[0], max(tensor1.shape[1], tensor2.shape[1])) + tensor1.shape[2:]
  76. # Now let's fill the result tensor
  77. result = tensor1.new_full(new_shape, padding_index)
  78. result[: tensor1.shape[0], : tensor1.shape[1]] = tensor1
  79. result[tensor1.shape[0] :, : tensor2.shape[1]] = tensor2
  80. return result
  81. def numpy_pad_and_concatenate(array1, array2, padding_index=-100):
  82. """Concatenates `array1` and `array2` on first axis, applying padding on the second if necessary."""
  83. array1 = atleast_1d(array1)
  84. array2 = atleast_1d(array2)
  85. if len(array1.shape) == 1 or array1.shape[1] == array2.shape[1]:
  86. return np.concatenate((array1, array2), axis=0)
  87. # Let's figure out the new shape
  88. new_shape = (array1.shape[0] + array2.shape[0], max(array1.shape[1], array2.shape[1])) + array1.shape[2:]
  89. # Now let's fill the result tensor
  90. result = np.full_like(array1, padding_index, shape=new_shape)
  91. result[: array1.shape[0], : array1.shape[1]] = array1
  92. result[array1.shape[0] :, : array2.shape[1]] = array2
  93. return result
  94. def nested_concat(tensors, new_tensors, padding_index=-100):
  95. """
  96. Concat the `new_tensors` to `tensors` on the first dim and pad them on the second if needed. Works for tensors or
  97. nested list/tuples/dict of tensors.
  98. """
  99. if not (isinstance(tensors, torch.Tensor) and isinstance(new_tensors, torch.Tensor)):
  100. assert type(tensors) is type(new_tensors), (
  101. f"Expected `tensors` and `new_tensors` to have the same type but found {type(tensors)} and {type(new_tensors)}."
  102. )
  103. if isinstance(tensors, (list, tuple)):
  104. return type(tensors)(nested_concat(t, n, padding_index=padding_index) for t, n in zip(tensors, new_tensors))
  105. elif isinstance(tensors, torch.Tensor):
  106. return torch_pad_and_concatenate(tensors, new_tensors, padding_index=padding_index)
  107. elif isinstance(tensors, Mapping):
  108. return type(tensors)(
  109. {k: nested_concat(t, new_tensors[k], padding_index=padding_index) for k, t in tensors.items()}
  110. )
  111. elif isinstance(tensors, np.ndarray):
  112. return numpy_pad_and_concatenate(tensors, new_tensors, padding_index=padding_index)
  113. else:
  114. raise TypeError(f"Unsupported type for concatenation: got {type(tensors)}")
  115. def find_batch_size(tensors):
  116. """
  117. Find the first dimension of a tensor in a nested list/tuple/dict of tensors.
  118. """
  119. if isinstance(tensors, (list, tuple)):
  120. for t in tensors:
  121. result = find_batch_size(t)
  122. if result is not None:
  123. return result
  124. elif isinstance(tensors, Mapping):
  125. for value in tensors.values():
  126. result = find_batch_size(value)
  127. if result is not None:
  128. return result
  129. elif isinstance(tensors, (torch.Tensor, np.ndarray)):
  130. return tensors.shape[0] if len(tensors.shape) >= 1 else None
  131. def nested_numpify(tensors):
  132. "Numpify `tensors` (even if it's a nested list/tuple/dict of tensors)."
  133. if isinstance(tensors, (list, tuple)):
  134. return type(tensors)(nested_numpify(t) for t in tensors)
  135. if isinstance(tensors, Mapping):
  136. return type(tensors)({k: nested_numpify(t) for k, t in tensors.items()})
  137. t = tensors.cpu()
  138. if t.dtype == torch.bfloat16:
  139. # As of Numpy 1.21.4, NumPy does not support bfloat16 (see
  140. # https://github.com/numpy/numpy/blob/a47ecdea856986cd60eabbd53265c2ca5916ad5d/doc/source/user/basics.types.rst ).
  141. # Until Numpy adds bfloat16, we must convert float32.
  142. t = t.to(torch.float32)
  143. return t.numpy()
  144. def nested_detach(tensors):
  145. "Detach `tensors` (even if it's a nested list/tuple/dict of tensors)."
  146. if isinstance(tensors, (list, tuple)):
  147. return type(tensors)(nested_detach(t) for t in tensors)
  148. elif isinstance(tensors, Mapping):
  149. return type(tensors)({k: nested_detach(t) for k, t in tensors.items()})
  150. return tensors.detach() if isinstance(tensors, torch.Tensor) else tensors
  151. def nested_xla_mesh_reduce(tensors, name):
  152. if is_torch_xla_available():
  153. import torch_xla.core.xla_model as xm
  154. if isinstance(tensors, (list, tuple)):
  155. return type(tensors)(nested_xla_mesh_reduce(t, f"{name}_{i}") for i, t in enumerate(tensors))
  156. if isinstance(tensors, Mapping):
  157. return type(tensors)(
  158. {k: nested_xla_mesh_reduce(t, f"{name}_{i}") for i, (k, t) in enumerate(tensors.items())}
  159. )
  160. tensors = atleast_1d(tensors)
  161. return xm.mesh_reduce(name, tensors, torch.cat)
  162. else:
  163. raise ImportError("Torch xla must be installed to use `nested_xla_mesh_reduce`")
  164. def distributed_concat(tensor: Any, num_total_examples: Optional[int] = None) -> Any:
  165. try:
  166. if isinstance(tensor, (tuple, list)):
  167. return type(tensor)(distributed_concat(t, num_total_examples) for t in tensor)
  168. if isinstance(tensor, Mapping):
  169. return type(tensor)({k: distributed_concat(t, num_total_examples) for k, t in tensor.items()})
  170. tensor = atleast_1d(tensor).contiguous()
  171. output_tensors = [tensor.clone() for _ in range(dist.get_world_size())]
  172. dist.all_gather(output_tensors, tensor)
  173. concat = torch.cat(output_tensors, dim=0)
  174. # truncate the dummy elements added by SequentialDistributedSampler
  175. if num_total_examples is not None:
  176. concat = concat[:num_total_examples]
  177. return concat
  178. except AssertionError:
  179. raise AssertionError("Not currently using distributed training")
  180. def distributed_broadcast_scalars(
  181. scalars: list[Union[int, float]],
  182. num_total_examples: Optional[int] = None,
  183. device: Optional[torch.device] = torch.device("cuda"),
  184. ) -> torch.Tensor:
  185. try:
  186. tensorized_scalar = torch.tensor(scalars, device=device)
  187. output_tensors = [tensorized_scalar.clone() for _ in range(dist.get_world_size())]
  188. dist.all_gather(output_tensors, tensorized_scalar)
  189. concat = torch.cat(output_tensors, dim=0)
  190. # truncate the dummy elements added by SequentialDistributedSampler
  191. if num_total_examples is not None:
  192. concat = concat[:num_total_examples]
  193. return concat
  194. except AssertionError:
  195. raise AssertionError("Not currently using distributed training")
  196. def reissue_pt_warnings(caught_warnings):
  197. # Reissue warnings
  198. if len(caught_warnings) > 1:
  199. for w in caught_warnings:
  200. if w.category is not UserWarning:
  201. warnings.warn(w.message, w.category)
  202. @contextmanager
  203. def torch_distributed_zero_first(local_rank: int):
  204. """
  205. Decorator to make all processes in distributed training wait for each local_master to do something.
  206. Args:
  207. local_rank (`int`): The rank of the local process.
  208. """
  209. if local_rank not in [-1, 0]:
  210. dist.barrier()
  211. yield
  212. if local_rank == 0:
  213. dist.barrier()
  214. class DistributedSamplerWithLoop(DistributedSampler):
  215. """
  216. Like a torch.utils.data.distributed.DistributedSampler` but loops at the end back to the beginning of the shuffled
  217. samples to make each process have a round multiple of batch_size samples.
  218. Args:
  219. dataset (`torch.utils.data.Dataset`):
  220. Dataset used for sampling.
  221. batch_size (`int`):
  222. The batch size used with this sampler
  223. kwargs (`dict[str, Any]`, *optional*):
  224. All other keyword arguments passed to `DistributedSampler`.
  225. """
  226. def __init__(self, dataset, batch_size, **kwargs):
  227. super().__init__(dataset, **kwargs)
  228. self.batch_size = batch_size
  229. def __iter__(self):
  230. indices = list(super().__iter__())
  231. remainder = 0 if len(indices) % self.batch_size == 0 else self.batch_size - len(indices) % self.batch_size
  232. # DistributedSampler already added samples from the beginning to make the number of samples a round multiple
  233. # of the world size, so we skip those.
  234. start_remainder = 1 if self.rank < len(self.dataset) % self.num_replicas else 0
  235. indices += indices[start_remainder : start_remainder + remainder]
  236. return iter(indices)
  237. class EvalLoopContainer:
  238. """
  239. Container to store intermediate results of evaluation loop.
  240. Args:
  241. do_nested_concat (`bool`, *optional*, defaults to `True`):
  242. If set to `True`, each iteration will recursively concatenate a new object containing tensors to
  243. the existing stored tensors, provided that the structure of the existing object and the new one
  244. are identical. If set to `False`, all newly added tensors will be stored in a list.
  245. padding_index (`int`, *optional*, defaults to -100):
  246. Value used to pad tensors of different shapes when `do_nested_concat=True`.
  247. """
  248. def __init__(self, do_nested_concat: bool = True, padding_index: int = -100):
  249. self.do_nested_concat = do_nested_concat
  250. self.padding_index = padding_index
  251. self.tensors = None
  252. self.arrays = None
  253. def add(self, tensors) -> None:
  254. """Add tensors to the stored objects. If `do_nested_concat=True`, the tensors will be concatenated recursively."""
  255. if self.tensors is None:
  256. self.tensors = tensors if self.do_nested_concat else [tensors]
  257. elif self.do_nested_concat:
  258. self.tensors = nested_concat(self.tensors, tensors, padding_index=self.padding_index)
  259. else:
  260. self.tensors.append(tensors)
  261. def to_cpu_and_numpy(self) -> None:
  262. """Move tensors in stored objects to CPU and convert them to numpy arrays."""
  263. # Check if we have something to add, if not just return
  264. if self.tensors is None:
  265. return
  266. new_arrays = nested_numpify(self.tensors)
  267. if self.arrays is None:
  268. self.arrays = new_arrays
  269. elif self.do_nested_concat:
  270. self.arrays = nested_concat(self.arrays, new_arrays, padding_index=self.padding_index)
  271. else:
  272. self.arrays.extend(new_arrays)
  273. # reset device tensors after adding to cpu
  274. self.tensors = None
  275. def get_arrays(self):
  276. """Returns the numpified and moved to CPU stored objects."""
  277. self.to_cpu_and_numpy()
  278. return self.arrays
  279. class SequentialDistributedSampler(Sampler):
  280. """
  281. Distributed Sampler that subsamples indices sequentially, making it easier to collate all results at the end.
  282. Even though we only use this sampler for eval and predict (no training), which means that the model params won't
  283. have to be synced (i.e. will not hang for synchronization even if varied number of forward passes), we still add
  284. extra samples to the sampler to make it evenly divisible (like in `DistributedSampler`) to make it easy to `gather`
  285. or `reduce` resulting tensors at the end of the loop.
  286. """
  287. def __init__(self, dataset, num_replicas=None, rank=None, batch_size=None):
  288. warnings.warn(
  289. "SequentialDistributedSampler is deprecated and will be removed in v5 of Transformers.",
  290. FutureWarning,
  291. )
  292. if num_replicas is None:
  293. if not dist.is_available():
  294. raise RuntimeError("Requires distributed package to be available")
  295. num_replicas = dist.get_world_size()
  296. if rank is None:
  297. if not dist.is_available():
  298. raise RuntimeError("Requires distributed package to be available")
  299. rank = dist.get_rank()
  300. self.dataset = dataset
  301. self.num_replicas = num_replicas
  302. self.rank = rank
  303. num_samples = len(self.dataset)
  304. # Add extra samples to make num_samples a multiple of batch_size if passed
  305. if batch_size is not None:
  306. self.num_samples = int(math.ceil(num_samples / (batch_size * num_replicas))) * batch_size
  307. else:
  308. self.num_samples = int(math.ceil(num_samples / num_replicas))
  309. self.total_size = self.num_samples * self.num_replicas
  310. self.batch_size = batch_size
  311. def __iter__(self):
  312. indices = list(range(len(self.dataset)))
  313. # add extra samples to make it evenly divisible
  314. indices += indices[: (self.total_size - len(indices))]
  315. assert len(indices) == self.total_size, (
  316. f"Indices length {len(indices)} and total size {self.total_size} mismatched"
  317. )
  318. # subsample
  319. indices = indices[self.rank * self.num_samples : (self.rank + 1) * self.num_samples]
  320. assert len(indices) == self.num_samples, (
  321. f"Indices length {len(indices)} and sample number {self.num_samples} mismatched"
  322. )
  323. return iter(indices)
  324. def __len__(self):
  325. return self.num_samples
  326. def get_tpu_sampler(dataset: torch.utils.data.Dataset, batch_size: int):
  327. if xr.world_size() <= 1:
  328. return RandomSampler(dataset)
  329. return DistributedSampler(dataset, num_replicas=xr.world_size(), rank=xr.global_ordinal())
  330. def nested_new_like(arrays, num_samples, padding_index=-100):
  331. """Create the same nested structure as `arrays` with a first dimension always at `num_samples`."""
  332. if isinstance(arrays, (list, tuple)):
  333. return type(arrays)(nested_new_like(x, num_samples) for x in arrays)
  334. return np.full_like(arrays, padding_index, shape=(num_samples, *arrays.shape[1:]))
  335. def expand_like(arrays, new_seq_length, padding_index=-100):
  336. """Expand the `arrays` so that the second dimension grows to `new_seq_length`. Uses `padding_index` for padding."""
  337. result = np.full_like(arrays, padding_index, shape=(arrays.shape[0], new_seq_length) + arrays.shape[2:])
  338. result[:, : arrays.shape[1]] = arrays
  339. return result
  340. def nested_truncate(tensors, limit):
  341. "Truncate `tensors` at `limit` (even if it's a nested list/tuple/dict of tensors)."
  342. if isinstance(tensors, (list, tuple)):
  343. return type(tensors)(nested_truncate(t, limit) for t in tensors)
  344. if isinstance(tensors, Mapping):
  345. return type(tensors)({k: nested_truncate(t, limit) for k, t in tensors.items()})
  346. return tensors[:limit]
  347. class DistributedTensorGatherer:
  348. """
  349. A class responsible for properly gathering tensors (or nested list/tuple of tensors) on the CPU by chunks.
  350. If our dataset has 16 samples with a batch size of 2 on 3 processes and we gather then transfer on CPU at every
  351. step, our sampler will generate the following indices:
  352. `[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0, 1]`
  353. to get something of size a multiple of 3 (so that each process gets the same dataset length). Then process 0, 1 and
  354. 2 will be responsible of making predictions for the following samples:
  355. - P0: `[0, 1, 2, 3, 4, 5]`
  356. - P1: `[6, 7, 8, 9, 10, 11]`
  357. - P2: `[12, 13, 14, 15, 0, 1]`
  358. The first batch treated on each process will be:
  359. - P0: `[0, 1]`
  360. - P1: `[6, 7]`
  361. - P2: `[12, 13]`
  362. So if we gather at the end of the first batch, we will get a tensor (nested list/tuple of tensor) corresponding to
  363. the following indices:
  364. `[0, 1, 6, 7, 12, 13]`
  365. If we directly concatenate our results without taking any precautions, the user will then get the predictions for
  366. the indices in this order at the end of the prediction loop:
  367. `[0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11, 0, 1]`
  368. For some reason, that's not going to roll their boat. This class is there to solve that problem.
  369. Args:
  370. world_size (`int`):
  371. The number of processes used in the distributed training.
  372. num_samples (`int`):
  373. The number of samples in our dataset.
  374. make_multiple_of (`int`, *optional*):
  375. If passed, the class assumes the datasets passed to each process are made to be a multiple of this argument
  376. (by adding samples).
  377. padding_index (`int`, *optional*, defaults to -100):
  378. The padding index to use if the arrays don't all have the same sequence length.
  379. """
  380. def __init__(self, world_size, num_samples, make_multiple_of=None, padding_index=-100):
  381. warnings.warn(
  382. "DistributedTensorGatherer is deprecated and will be removed in v5 of Transformers.",
  383. FutureWarning,
  384. )
  385. self.world_size = world_size
  386. self.num_samples = num_samples
  387. total_size = world_size if make_multiple_of is None else world_size * make_multiple_of
  388. self.total_samples = int(np.ceil(num_samples / total_size)) * total_size
  389. self.process_length = self.total_samples // world_size
  390. self._storage = None
  391. self._offsets = None
  392. self.padding_index = padding_index
  393. def add_arrays(self, arrays):
  394. """
  395. Add `arrays` to the internal storage, Will initialize the storage to the full size at the first arrays passed
  396. so that if we're bound to get an OOM, it happens at the beginning.
  397. """
  398. if arrays is None:
  399. return
  400. if self._storage is None:
  401. self._storage = nested_new_like(arrays, self.total_samples, padding_index=self.padding_index)
  402. self._offsets = list(range(0, self.total_samples, self.process_length))
  403. slice_len, self._storage = self._nested_set_tensors(self._storage, arrays)
  404. for i in range(self.world_size):
  405. self._offsets[i] += slice_len
  406. def _nested_set_tensors(self, storage, arrays):
  407. if isinstance(arrays, (list, tuple)):
  408. result = [self._nested_set_tensors(x, y) for x, y in zip(storage, arrays)]
  409. return result[0][0], type(arrays)(r[1] for r in result)
  410. assert arrays.shape[0] % self.world_size == 0, (
  411. f"Arrays passed should all have a first dimension multiple of {self.world_size}, found {arrays.shape[0]}."
  412. )
  413. slice_len = arrays.shape[0] // self.world_size
  414. for i in range(self.world_size):
  415. if len(arrays.shape) == 1:
  416. storage[self._offsets[i] : self._offsets[i] + slice_len] = arrays[i * slice_len : (i + 1) * slice_len]
  417. else:
  418. # Expand the array on the fly if needed.
  419. if len(storage.shape) > 1 and storage.shape[1] < arrays.shape[1]:
  420. storage = expand_like(storage, arrays.shape[1], padding_index=self.padding_index)
  421. storage[self._offsets[i] : self._offsets[i] + slice_len, : arrays.shape[1]] = arrays[
  422. i * slice_len : (i + 1) * slice_len
  423. ]
  424. return slice_len, storage
  425. def finalize(self):
  426. """
  427. Return the properly gathered arrays and truncate to the number of samples (since the sampler added some extras
  428. to get each process a dataset of the same length).
  429. """
  430. if self._storage is None:
  431. return
  432. if self._offsets[0] != self.process_length:
  433. logger.warning("Not all data has been set. Are you sure you passed all values?")
  434. return nested_truncate(self._storage, self.num_samples)
  435. @dataclass
  436. class LabelSmoother:
  437. """
  438. Adds label-smoothing on a pre-computed output from a Transformers model.
  439. Args:
  440. epsilon (`float`, *optional*, defaults to 0.1):
  441. The label smoothing factor.
  442. ignore_index (`int`, *optional*, defaults to -100):
  443. The index in the labels to ignore when computing the loss.
  444. """
  445. epsilon: float = 0.1
  446. ignore_index: int = -100
  447. def __call__(self, model_output, labels, shift_labels=False):
  448. logits = model_output["logits"] if isinstance(model_output, dict) else model_output[0]
  449. if shift_labels:
  450. logits = logits[..., :-1, :].contiguous()
  451. labels = labels[..., 1:].contiguous()
  452. log_probs = -nn.functional.log_softmax(logits, dim=-1)
  453. if labels.dim() == log_probs.dim() - 1:
  454. labels = labels.unsqueeze(-1)
  455. padding_mask = labels.eq(self.ignore_index)
  456. # In case the ignore_index is -100, the gather will fail, so we replace labels by 0. The padding_mask
  457. # will ignore them in any case.
  458. labels = torch.clamp(labels, min=0)
  459. nll_loss = log_probs.gather(dim=-1, index=labels)
  460. # works for fp16 input tensor too, by internally upcasting it to fp32
  461. smoothed_loss = log_probs.sum(dim=-1, keepdim=True, dtype=torch.float32)
  462. nll_loss.masked_fill_(padding_mask, 0.0)
  463. smoothed_loss.masked_fill_(padding_mask, 0.0)
  464. # Take the mean over the label dimensions, then divide by the number of active elements (i.e. not-padded):
  465. num_active_elements = padding_mask.numel() - padding_mask.long().sum()
  466. nll_loss = nll_loss.sum() / num_active_elements
  467. smoothed_loss = smoothed_loss.sum() / (num_active_elements * log_probs.shape[-1])
  468. return (1 - self.epsilon) * nll_loss + self.epsilon * smoothed_loss
  469. def get_length_grouped_indices(lengths, batch_size, mega_batch_mult=None, generator=None):
  470. """
  471. Return a list of indices so that each slice of `batch_size` consecutive indices correspond to elements of similar
  472. lengths. To do this, the indices are:
  473. - randomly permuted
  474. - grouped in mega-batches of size `mega_batch_mult * batch_size`
  475. - sorted by length in each mega-batch
  476. The result is the concatenation of all mega-batches, with the batch of `batch_size` containing the element of
  477. maximum length placed first, so that an OOM happens sooner rather than later.
  478. """
  479. # Default for mega_batch_mult: 50 or the number to get 4 megabatches, whichever is smaller.
  480. if mega_batch_mult is None:
  481. mega_batch_mult = min(len(lengths) // (batch_size * 4), 50)
  482. # Just in case, for tiny datasets
  483. if mega_batch_mult == 0:
  484. mega_batch_mult = 1
  485. # We need to use torch for the random part as a distributed sampler will set the random seed for torch.
  486. indices = torch.randperm(len(lengths), generator=generator)
  487. megabatch_size = mega_batch_mult * batch_size
  488. megabatches = [indices[i : i + megabatch_size].tolist() for i in range(0, len(lengths), megabatch_size)]
  489. megabatches = [sorted(megabatch, key=lambda i: lengths[i], reverse=True) for megabatch in megabatches]
  490. # The rest is to get the biggest batch first.
  491. # Since each megabatch is sorted by descending length, the longest element is the first
  492. megabatch_maximums = [lengths[megabatch[0]] for megabatch in megabatches]
  493. max_idx = torch.argmax(torch.tensor(megabatch_maximums)).item()
  494. # Switch to put the longest element in first position
  495. megabatches[0][0], megabatches[max_idx][0] = megabatches[max_idx][0], megabatches[0][0]
  496. return [i for megabatch in megabatches for i in megabatch]
  497. class LengthGroupedSampler(Sampler):
  498. r"""
  499. Sampler that samples indices in a way that groups together features of the dataset of roughly the same length while
  500. keeping a bit of randomness.
  501. """
  502. def __init__(
  503. self,
  504. batch_size: int,
  505. dataset: Optional[Dataset] = None,
  506. lengths: Optional[list[int]] = None,
  507. model_input_name: Optional[str] = None,
  508. generator=None,
  509. ):
  510. if dataset is None and lengths is None:
  511. raise ValueError("One of dataset and lengths must be provided.")
  512. self.batch_size = batch_size
  513. if lengths is None:
  514. model_input_name = model_input_name if model_input_name is not None else "input_ids"
  515. if not isinstance(dataset[0], (dict, BatchEncoding)) or model_input_name not in dataset[0]:
  516. raise ValueError(
  517. "Can only automatically infer lengths for datasets whose items are dictionaries with an "
  518. f"'{model_input_name}' key."
  519. )
  520. lengths = [len(feature[model_input_name]) for feature in dataset]
  521. elif isinstance(lengths, torch.Tensor):
  522. logger.info(
  523. "If lengths is a torch.Tensor, LengthGroupedSampler will be slow. Converting lengths to list[int]..."
  524. )
  525. lengths = lengths.tolist()
  526. self.lengths = lengths
  527. self.generator = generator
  528. def __len__(self):
  529. return len(self.lengths)
  530. def __iter__(self):
  531. indices = get_length_grouped_indices(self.lengths, self.batch_size, generator=self.generator)
  532. return iter(indices)
  533. class DistributedLengthGroupedSampler(DistributedSampler):
  534. r"""
  535. Distributed Sampler that samples indices in a way that groups together features of the dataset of roughly the same
  536. length while keeping a bit of randomness.
  537. """
  538. # Copied and adapted from PyTorch DistributedSampler.
  539. def __init__(
  540. self,
  541. batch_size: int,
  542. dataset: Optional[Dataset] = None,
  543. num_replicas: Optional[int] = None,
  544. rank: Optional[int] = None,
  545. seed: int = 0,
  546. drop_last: bool = False,
  547. lengths: Optional[list[int]] = None,
  548. model_input_name: Optional[str] = None,
  549. ):
  550. if dataset is None and lengths is None:
  551. raise ValueError("One of dataset and lengths must be provided.")
  552. if num_replicas is None:
  553. if not dist.is_available():
  554. raise RuntimeError("Requires distributed package to be available")
  555. num_replicas = dist.get_world_size()
  556. if rank is None:
  557. if not dist.is_available():
  558. raise RuntimeError("Requires distributed package to be available")
  559. rank = dist.get_rank()
  560. self.batch_size = batch_size
  561. self.num_replicas = num_replicas
  562. self.rank = rank
  563. self.epoch = 0
  564. self.drop_last = drop_last
  565. if lengths is None:
  566. model_input_name = model_input_name if model_input_name is not None else "input_ids"
  567. if not isinstance(dataset[0], (dict, BatchEncoding)) or model_input_name not in dataset[0]:
  568. raise ValueError(
  569. "Can only automatically infer lengths for datasets whose items are dictionaries with an "
  570. f"'{model_input_name}' key."
  571. )
  572. lengths = [len(feature[model_input_name]) for feature in dataset]
  573. elif isinstance(lengths, torch.Tensor):
  574. logger.info(
  575. "If lengths is a torch.Tensor, DistributedLengthGroupedSampler will be slow. Converting lengths to"
  576. " list[int]..."
  577. )
  578. lengths = lengths.tolist()
  579. self.lengths = lengths
  580. # If the dataset length is evenly divisible by # of replicas, then there
  581. # is no need to drop any data, since the dataset will be split equally.
  582. if self.drop_last and len(self.lengths) % self.num_replicas != 0:
  583. # Split to nearest available length that is evenly divisible.
  584. # This is to ensure each rank receives the same amount of data when
  585. # using this Sampler.
  586. self.num_samples = math.ceil((len(self.lengths) - self.num_replicas) / self.num_replicas)
  587. else:
  588. self.num_samples = math.ceil(len(self.lengths) / self.num_replicas)
  589. self.total_size = self.num_samples * self.num_replicas
  590. self.seed = seed
  591. def __iter__(self) -> Iterator:
  592. # Deterministically shuffle based on epoch and seed
  593. g = torch.Generator()
  594. g.manual_seed(self.seed + self.epoch)
  595. indices = get_length_grouped_indices(self.lengths, self.batch_size, generator=g)
  596. if not self.drop_last:
  597. # add extra samples to make it evenly divisible
  598. indices += indices[: (self.total_size - len(indices))]
  599. else:
  600. # remove tail of data to make it evenly divisible
  601. indices = indices[: self.total_size]
  602. assert len(indices) == self.total_size
  603. # subsample
  604. indices = indices[self.rank : self.total_size : self.num_replicas]
  605. assert len(indices) == self.num_samples
  606. return iter(indices)
  607. class ShardSampler(Sampler):
  608. """
  609. Sampler that shards batches between several processes. Dispatches indices batch by batch: on 2 processes with batch
  610. size 4, the first two batches are `[0, 1, 2, 3, 4, 5, 6, 7]` and `[8, 9, 10, 11, 12, 13, 14, 15]`, which shard into
  611. `[0, 1, 2, 3]` and `[8, 9, 10, 11]` for GPU-0 and `[4, 5, 6, 7]` and `[12, 13, 14, 15]` for GPU-1.
  612. The sampler thus yields `[0, 1, 2, 3, 8, 9, 10, 11]` on GPU-0 and `[4, 5, 6, 7, 12, 13, 14, 15]` on GPU-1.
  613. """
  614. def __init__(
  615. self,
  616. dataset: Dataset,
  617. batch_size: int = 1,
  618. drop_last: bool = False,
  619. num_processes: int = 1,
  620. process_index: int = 0,
  621. ):
  622. self.dataset = dataset
  623. self.batch_size = batch_size
  624. self.drop_last = drop_last
  625. self.num_processes = num_processes
  626. self.process_index = process_index
  627. self.total_batch_size = total_batch_size = batch_size * num_processes
  628. num_batches = len(dataset) // total_batch_size if drop_last else math.ceil(len(dataset) / total_batch_size)
  629. self.total_num_samples = num_batches * total_batch_size
  630. def __iter__(self):
  631. indices = list(range(len(self.dataset)))
  632. # Add extra samples to make it evenly divisible. While loop is there in the edge case we have a tiny dataset
  633. # and it needs to be done several times.
  634. while len(indices) < self.total_num_samples:
  635. indices += indices[: (self.total_num_samples - len(indices))]
  636. result = []
  637. for batch_start in range(self.batch_size * self.process_index, self.total_num_samples, self.total_batch_size):
  638. result += indices[batch_start : batch_start + self.batch_size]
  639. return iter(result)
  640. def __len__(self):
  641. # Each shard only sees a fraction of total_num_samples.
  642. return self.total_num_samples // self.num_processes
  643. class IterableDatasetShard(IterableDataset):
  644. """
  645. Wraps a PyTorch `IterableDataset` to generate samples for one of the processes only. Instances of this class will
  646. always yield a number of samples that is a round multiple of the actual batch size (which is `batch_size x
  647. num_processes`). Depending on the value of the `drop_last` attribute, it will either stop the iteration at the
  648. first batch that would be too small or loop with indices from the beginning.
  649. On two processes with an iterable dataset yielding of `[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]` with a batch size of
  650. 2:
  651. - the shard on process 0 will yield `[0, 1, 4, 5, 8, 9]` so will see batches `[0, 1]`, `[4, 5]`, `[8, 9]`
  652. - the shard on process 1 will yield `[2, 3, 6, 7, 10, 11]` so will see batches `[2, 3]`, `[6, 7]`, `[10, 11]`
  653. <Tip warning={true}>
  654. If your IterableDataset implements some randomization that needs to be applied the same way on all processes
  655. (for instance, a shuffling), you should use a `torch.Generator` in a `generator` attribute of the `dataset` to
  656. generate your random numbers and call the [`~trainer_pt_utils.IterableDatasetShard.set_epoch`] method of this
  657. object. It will set the seed of this `generator` to `seed + epoch` on all processes before starting the
  658. iteration. Alternatively, you can also implement a `set_epoch()` method in your iterable dataset to deal with
  659. this.
  660. </Tip>
  661. Args:
  662. dataset (`torch.utils.data.IterableDataset`):
  663. The batch sampler to split in several shards.
  664. batch_size (`int`, *optional*, defaults to 1):
  665. The size of the batches per shard.
  666. drop_last (`bool`, *optional*, defaults to `False`):
  667. Whether or not to drop the last incomplete batch or complete the last batches by using the samples from the
  668. beginning.
  669. num_processes (`int`, *optional*, defaults to 1):
  670. The number of processes running concurrently.
  671. process_index (`int`, *optional*, defaults to 0):
  672. The index of the current process.
  673. seed (`int`, *optional*, defaults to 0):
  674. A random seed that will be used for the random number generation in
  675. [`~trainer_pt_utils.IterableDatasetShard.set_epoch`].
  676. """
  677. def __init__(
  678. self,
  679. dataset: IterableDataset,
  680. batch_size: int = 1,
  681. drop_last: bool = False,
  682. num_processes: int = 1,
  683. process_index: int = 0,
  684. seed: int = 0,
  685. ):
  686. self.dataset = dataset
  687. self.batch_size = batch_size
  688. self.drop_last = drop_last
  689. self.num_processes = num_processes
  690. self.process_index = process_index
  691. self.seed = seed
  692. self.epoch = 0
  693. self.num_examples = 0
  694. def set_epoch(self, epoch):
  695. self.epoch = epoch
  696. if hasattr(self.dataset, "set_epoch"):
  697. self.dataset.set_epoch(epoch)
  698. def __iter__(self):
  699. self.num_examples = 0
  700. if (
  701. not hasattr(self.dataset, "set_epoch")
  702. and hasattr(self.dataset, "generator")
  703. and isinstance(self.dataset.generator, torch.Generator)
  704. ):
  705. self.dataset.generator.manual_seed(self.seed + self.epoch)
  706. real_batch_size = self.batch_size * self.num_processes
  707. process_slice = range(self.process_index * self.batch_size, (self.process_index + 1) * self.batch_size)
  708. first_batch = None
  709. current_batch = []
  710. for element in self.dataset:
  711. self.num_examples += 1
  712. current_batch.append(element)
  713. # Wait to have a full batch before yielding elements.
  714. if len(current_batch) == real_batch_size:
  715. for i in process_slice:
  716. yield current_batch[i]
  717. if first_batch is None:
  718. first_batch = current_batch.copy()
  719. current_batch = []
  720. # Finished if drop_last is True, otherwise complete the last batch with elements from the beginning.
  721. if not self.drop_last and len(current_batch) > 0:
  722. if first_batch is None:
  723. first_batch = current_batch.copy()
  724. while len(current_batch) < real_batch_size:
  725. current_batch += first_batch
  726. for i in process_slice:
  727. yield current_batch[i]
  728. def __len__(self):
  729. # Will raise an error if the underlying dataset is not sized.
  730. if self.drop_last:
  731. return (len(self.dataset) // (self.batch_size * self.num_processes)) * self.batch_size
  732. else:
  733. return math.ceil(len(self.dataset) / (self.batch_size * self.num_processes)) * self.batch_size
  734. # In order to keep `trainer.py` compact and easy to understand, place any secondary PT Trainer
  735. # helper methods here
  736. def _get_learning_rate(self):
  737. if self.is_deepspeed_enabled:
  738. # with deepspeed's fp16 and dynamic loss scale enabled the optimizer/scheduler steps may
  739. # not run for the first few dozen steps while loss scale is too large, and thus during
  740. # that time `get_last_lr` will fail if called during that warm up stage, so work around it:
  741. try:
  742. last_lr = self.lr_scheduler.get_last_lr()[0]
  743. except AssertionError as e:
  744. if "need to call step" in str(e):
  745. logger.warning("tried to get lr value before scheduler/optimizer started stepping, returning lr=0")
  746. last_lr = 0
  747. else:
  748. raise
  749. else:
  750. if isinstance(self.lr_scheduler, torch.optim.lr_scheduler.ReduceLROnPlateau):
  751. last_lr = self.optimizer.param_groups[0]["lr"]
  752. else:
  753. last_lr = self.lr_scheduler.get_last_lr()[0]
  754. if torch.is_tensor(last_lr):
  755. last_lr = last_lr.item()
  756. return last_lr
  757. def _secs2timedelta(secs):
  758. """
  759. Convert seconds to hh:mm:ss.msec, msecs rounded to 2 decimal places.
  760. """
  761. msec = int(abs(secs - int(secs)) * 100)
  762. return f"{datetime.timedelta(seconds=int(secs))}.{msec:02d}"
  763. def metrics_format(metrics: dict[str, float]) -> dict[str, float]:
  764. """
  765. Reformat Trainer metrics values to a human-readable format.
  766. Args:
  767. metrics (`dict[str, float]`):
  768. The metrics returned from train/evaluate/predict
  769. Returns:
  770. metrics (`dict[str, float]`): The reformatted metrics
  771. """
  772. metrics_copy = metrics.copy()
  773. for k, v in metrics_copy.items():
  774. if "_mem_" in k:
  775. metrics_copy[k] = f"{v >> 20}MB"
  776. elif "_runtime" in k:
  777. metrics_copy[k] = _secs2timedelta(v)
  778. elif k == "total_flos":
  779. metrics_copy[k] = f"{int(v) >> 30}GF"
  780. elif isinstance(metrics_copy[k], float):
  781. metrics_copy[k] = round(v, 4)
  782. return metrics_copy
  783. def log_metrics(self, split, metrics):
  784. """
  785. Log metrics in a specially formatted way.
  786. Under distributed environment this is done only for a process with rank 0.
  787. Args:
  788. split (`str`):
  789. Mode/split name: one of `train`, `eval`, `test`
  790. metrics (`dict[str, float]`):
  791. The metrics returned from train/evaluate/predictmetrics: metrics dict
  792. Notes on memory reports:
  793. In order to get memory usage report you need to install `psutil`. You can do that with `pip install psutil`.
  794. Now when this method is run, you will see a report that will include:
  795. ```
  796. init_mem_cpu_alloc_delta = 1301MB
  797. init_mem_cpu_peaked_delta = 154MB
  798. init_mem_gpu_alloc_delta = 230MB
  799. init_mem_gpu_peaked_delta = 0MB
  800. train_mem_cpu_alloc_delta = 1345MB
  801. train_mem_cpu_peaked_delta = 0MB
  802. train_mem_gpu_alloc_delta = 693MB
  803. train_mem_gpu_peaked_delta = 7MB
  804. ```
  805. **Understanding the reports:**
  806. - the first segment, e.g., `train__`, tells you which stage the metrics are for. Reports starting with `init_`
  807. will be added to the first stage that gets run. So that if only evaluation is run, the memory usage for the
  808. `__init__` will be reported along with the `eval_` metrics.
  809. - the third segment, is either `cpu` or `gpu`, tells you whether it's the general RAM or the gpu0 memory
  810. metric.
  811. - `*_alloc_delta` - is the difference in the used/allocated memory counter between the end and the start of the
  812. stage - it can be negative if a function released more memory than it allocated.
  813. - `*_peaked_delta` - is any extra memory that was consumed and then freed - relative to the current allocated
  814. memory counter - it is never negative. When you look at the metrics of any stage you add up `alloc_delta` +
  815. `peaked_delta` and you know how much memory was needed to complete that stage.
  816. The reporting happens only for process of rank 0 and gpu 0 (if there is a gpu). Typically this is enough since the
  817. main process does the bulk of work, but it could be not quite so if model parallel is used and then other GPUs may
  818. use a different amount of gpu memory. This is also not the same under DataParallel where gpu0 may require much more
  819. memory than the rest since it stores the gradient and optimizer states for all participating GPUs. Perhaps in the
  820. future these reports will evolve to measure those too.
  821. The CPU RAM metric measures RSS (Resident Set Size) includes both the memory which is unique to the process and the
  822. memory shared with other processes. It is important to note that it does not include swapped out memory, so the
  823. reports could be imprecise.
  824. The CPU peak memory is measured using a sampling thread. Due to python's GIL it may miss some of the peak memory if
  825. that thread didn't get a chance to run when the highest memory was used. Therefore this report can be less than
  826. reality. Using `tracemalloc` would have reported the exact peak memory, but it doesn't report memory allocations
  827. outside of python. So if some C++ CUDA extension allocated its own memory it won't be reported. And therefore it
  828. was dropped in favor of the memory sampling approach, which reads the current process memory usage.
  829. The GPU allocated and peak memory reporting is done with `torch.cuda.memory_allocated()` and
  830. `torch.cuda.max_memory_allocated()`. This metric reports only "deltas" for pytorch-specific allocations, as
  831. `torch.cuda` memory management system doesn't track any memory allocated outside of pytorch. For example, the very
  832. first cuda call typically loads CUDA kernels, which may take from 0.5 to 2GB of GPU memory.
  833. Note that this tracker doesn't account for memory allocations outside of [`Trainer`]'s `__init__`, `train`,
  834. `evaluate` and `predict` calls.
  835. Because `evaluation` calls may happen during `train`, we can't handle nested invocations because
  836. `torch.cuda.max_memory_allocated` is a single counter, so if it gets reset by a nested eval call, `train`'s tracker
  837. will report incorrect info. If this [pytorch issue](https://github.com/pytorch/pytorch/issues/16266) gets resolved
  838. it will be possible to change this class to be re-entrant. Until then we will only track the outer level of
  839. `train`, `evaluate` and `predict` methods. Which means that if `eval` is called during `train`, it's the latter
  840. that will account for its memory usage and that of the former.
  841. This also means that if any other tool that is used along the [`Trainer`] calls
  842. `torch.cuda.reset_peak_memory_stats`, the gpu peak memory stats could be invalid. And the [`Trainer`] will disrupt
  843. the normal behavior of any such tools that rely on calling `torch.cuda.reset_peak_memory_stats` themselves.
  844. For best performance you may want to consider turning the memory profiling off for production runs.
  845. """
  846. if not self.is_world_process_zero():
  847. return
  848. print(f"***** {split} metrics *****")
  849. metrics_formatted = metrics_format(metrics)
  850. k_width = max(len(str(x)) for x in metrics_formatted)
  851. v_width = max(len(str(x)) for x in metrics_formatted.values())
  852. for key in sorted(metrics_formatted.keys()):
  853. print(f" {key: <{k_width}} = {metrics_formatted[key]:>{v_width}}")
  854. def save_metrics(self, split, metrics, combined=True):
  855. """
  856. Save metrics into a json file for that split, e.g. `train_results.json`.
  857. Under distributed environment this is done only for a process with rank 0.
  858. Args:
  859. split (`str`):
  860. Mode/split name: one of `train`, `eval`, `test`, `all`
  861. metrics (`dict[str, float]`):
  862. The metrics returned from train/evaluate/predict
  863. combined (`bool`, *optional*, defaults to `True`):
  864. Creates combined metrics by updating `all_results.json` with metrics of this call
  865. To understand the metrics please read the docstring of [`~Trainer.log_metrics`]. The only difference is that raw
  866. unformatted numbers are saved in the current method.
  867. """
  868. if not self.is_world_process_zero():
  869. return
  870. path = os.path.join(self.args.output_dir, f"{split}_results.json")
  871. with open(path, "w") as f:
  872. json.dump(metrics, f, indent=4, sort_keys=True)
  873. if combined:
  874. path = os.path.join(self.args.output_dir, "all_results.json")
  875. if os.path.exists(path):
  876. with open(path) as f:
  877. all_metrics = json.load(f)
  878. else:
  879. all_metrics = {}
  880. all_metrics.update(metrics)
  881. with open(path, "w") as f:
  882. json.dump(all_metrics, f, indent=4, sort_keys=True)
  883. def save_state(self):
  884. """
  885. Saves the Trainer state, since Trainer.save_model saves only the tokenizer with the model.
  886. Under distributed environment this is done only for a process with rank 0.
  887. """
  888. if not self.is_world_process_zero():
  889. return
  890. path = os.path.join(self.args.output_dir, "trainer_state.json")
  891. self.state.save_to_json(path)
  892. def get_model_param_count(model, trainable_only=False):
  893. """
  894. Calculate model's total param count. If trainable_only is True then count only those requiring grads.
  895. """
  896. if is_deepspeed_zero3_enabled():
  897. def numel(p):
  898. return p.ds_numel if hasattr(p, "ds_numel") else p.numel()
  899. else:
  900. def numel(p):
  901. return p.numel()
  902. return sum(numel(p) for p in model.parameters() if not trainable_only or p.requires_grad)
  903. def get_parameter_names(model, forbidden_layer_types, forbidden_layer_names=None):
  904. """
  905. Returns the names of the model parameters that are not inside a forbidden layer.
  906. """
  907. forbidden_layer_patterns = (
  908. [re.compile(pattern) for pattern in forbidden_layer_names] if forbidden_layer_names is not None else []
  909. )
  910. result = []
  911. for name, child in model.named_children():
  912. child_params = get_parameter_names(child, forbidden_layer_types, forbidden_layer_names)
  913. result += [
  914. f"{name}.{n}"
  915. for n in child_params
  916. if not isinstance(child, tuple(forbidden_layer_types))
  917. and not any(pattern.search(f"{name}.{n}".lower()) for pattern in forbidden_layer_patterns)
  918. ]
  919. # Add model specific parameters that are not in any child
  920. result += [
  921. k for k in model._parameters if not any(pattern.search(k.lower()) for pattern in forbidden_layer_patterns)
  922. ]
  923. return result
  924. def get_module_class_from_name(module, name):
  925. """
  926. Gets a class from a module by its name.
  927. Args:
  928. module (`torch.nn.Module`): The module to get the class from.
  929. name (`str`): The name of the class.
  930. """
  931. modules_children = list(module.children())
  932. if module.__class__.__name__ == name:
  933. return module.__class__
  934. elif len(modules_children) == 0:
  935. return
  936. else:
  937. for child_module in modules_children:
  938. module_class = get_module_class_from_name(child_module, name)
  939. if module_class is not None:
  940. return module_class
  941. def remove_dummy_checkpoint(is_main_process, output_dir, filenames):
  942. if is_main_process:
  943. for filename in filenames:
  944. file = os.path.join(output_dir, filename)
  945. if os.path.isfile(file):
  946. os.remove(file)
  947. if is_sagemaker_mp_enabled():
  948. import smdistributed.modelparallel.torch as smp
  949. @smp.step()
  950. def smp_forward_backward(model, inputs, gradient_accumulation_steps=1):
  951. outputs = model(**inputs)
  952. loss = outputs["loss"] if isinstance(outputs, dict) else outputs[0]
  953. loss /= gradient_accumulation_steps
  954. model.backward(loss)
  955. return loss
  956. @smp.step()
  957. def smp_forward_only(model, inputs):
  958. return model(**inputs)
  959. def smp_gather(tensor):
  960. if isinstance(tensor, (list, tuple)):
  961. return type(tensor)(smp_gather(t) for t in tensor)
  962. elif isinstance(tensor, dict):
  963. return type(tensor)({k: smp_gather(v) for k, v in tensor.items()})
  964. elif not isinstance(tensor, torch.Tensor):
  965. raise TypeError(
  966. f"Can't gather the values of type {type(tensor)}, only of nested list/tuple/dicts of tensors."
  967. )
  968. all_tensors = smp.allgather(tensor, smp.CommGroup.DP_GROUP)
  969. all_tensors = [atleast_1d(t) for t in all_tensors]
  970. return torch.cat([t.cpu() for t in all_tensors], dim=0)
  971. def smp_nested_concat(tensor):
  972. if isinstance(tensor, (list, tuple)):
  973. return type(tensor)(smp_nested_concat(t) for t in tensor)
  974. elif isinstance(tensor, dict):
  975. return type(tensor)({k: smp_nested_concat(v) for k, v in tensor.items()})
  976. # It doesn't seem possible to check here if `tensor` is a StepOutput because StepOutput lives in `smp.step`
  977. # which is also the name of the decorator so Python is confused.
  978. return tensor.detach().concat().cpu()
  979. @dataclass
  980. class AcceleratorConfig:
  981. """
  982. A subset of arguments relating to the underlying [`accelerate.Accelerator`]
  983. implementation utilized in the `Trainer` that can be customized.
  984. Mostly relating to data.
  985. Parameters:
  986. split_batches (`bool`, *optional*, defaults to `False`):
  987. Whether or not the accelerator should split the batches yielded by the dataloaders across the devices. If
  988. `True` the actual batch size used will be the same on any kind of distributed processes, but it must be a
  989. round multiple of the `num_processes` you are using. If `False`, actual batch size used will be the one set
  990. in your script multiplied by the number of processes.
  991. dispatch_batches (`bool`, *optional*):
  992. If set to `True`, the dataloader prepared by the Accelerator is only iterated through on the main process
  993. and then the batches are split and broadcast to each process. Will default to `True` for `DataLoader` whose
  994. underlying dataset is an `IterableDataset`, `False` otherwise.
  995. even_batches (`bool`, *optional*, defaults to `True`):
  996. If set to `True`, in cases where the total batch size across all processes does not exactly divide the
  997. dataset, samples at the start of the dataset will be duplicated so the batch can be divided equally among
  998. all workers.
  999. use_seedable_sampler (`bool`, *optional*, defaults to `True`):
  1000. Whether or not use a fully seedable random sampler ([`accelerate.data_loader.SeedableRandomSampler`]). Ensures
  1001. training results are fully reproducible using a different sampling technique. While seed-to-seed results
  1002. may differ, on average the differences are negligible when using multiple different seeds to compare. Should
  1003. also be ran with [`~utils.set_seed`] for the best results.
  1004. gradient_accumulation_kwargs (`dict`, *optional*):
  1005. Additional kwargs to configure gradient accumulation, see [`accelerate.utils.GradientAccumulationPlugin`].
  1006. Any of the following (optional) keys are acceptable:
  1007. num_steps (`int`): Will take precedence over [`~.TrainingArguments.gradient_accumulation_steps`] if
  1008. the latter is set to 1, otherwise an exception will be raised.
  1009. adjust_scheduler (`bool`): Whether to adjust the scheduler steps to account for [`~.TrainingArguments.gradient_accumulation_steps`].
  1010. The [`accelerate.utils.GradientAccumulationPlugin`] default is `True`.
  1011. sync_each_batch (`bool`): Whether to synchronize the gradients at each data batch.
  1012. The [`accelerate.utils.GradientAccumulationPlugin`] default is `False`.
  1013. non_blocking (`bool`, *optional*, defaults to `False`):
  1014. Whether to use non-blocking CUDA calls to help minimize synchronization during
  1015. distributed training with prepared `DataLoader` inputs being moved to device.
  1016. Best if used with `pin_memory=True` in the `TrainingArguments`.
  1017. use_configured_state (`bool*, *optional*, defaults to `False`):
  1018. Whether or not to use a pre-configured `AcceleratorState` or `PartialState` defined
  1019. before calling `TrainingArguments`. If `True`, an `Accelerator` or `PartialState`
  1020. must be initialized. May lead to issues using sweeps or hyperparameter tuning.
  1021. """
  1022. # Data related arguments
  1023. split_batches: bool = field(
  1024. default=False,
  1025. metadata={
  1026. "help": "Whether or not the accelerator should split the batches yielded by the dataloaders across the devices. If"
  1027. " `True` the actual batch size used will be the same on any kind of distributed processes, but it must be a"
  1028. " round multiple of the `num_processes` you are using. If `False`, actual batch size used will be the one set"
  1029. " in your script multiplied by the number of processes."
  1030. },
  1031. )
  1032. dispatch_batches: Optional[bool] = field(
  1033. default=None,
  1034. metadata={
  1035. "help": "If set to `True`, the dataloader prepared by the Accelerator is only iterated through on the main process"
  1036. " and then the batches are split and broadcast to each process. Will default to `True` for `DataLoader` whose"
  1037. " underlying dataset is an `IterableDataslet`, `False` otherwise."
  1038. },
  1039. )
  1040. even_batches: bool = field(
  1041. default=True,
  1042. metadata={
  1043. "help": "If set to `True`, in cases where the total batch size across all processes does not exactly divide the"
  1044. " dataset, samples at the start of the dataset will be duplicated so the batch can be divided equally among"
  1045. " all workers."
  1046. },
  1047. )
  1048. use_seedable_sampler: bool = field(
  1049. default=True,
  1050. metadata={
  1051. "help": "Whether or not use a fully seedable random sampler ([`accelerate.data_loader.SeedableRandomSampler`])."
  1052. "Ensures training results are fully reproducible using a different sampling technique. "
  1053. "While seed-to-seed results may differ, on average the differences are negligible when using"
  1054. "multiple different seeds to compare. Should also be ran with [`~utils.set_seed`] for the best results."
  1055. },
  1056. )
  1057. non_blocking: bool = field(
  1058. default=False,
  1059. metadata={
  1060. "help": "Whether to use non-blocking CUDA calls to help minimize synchronization during "
  1061. "distributed training with prepared `DataLoader` inputs being moved to device. "
  1062. "Best if used with `pin_memory=True` in the `TrainingArguments`. Requires accelerate "
  1063. "v0.30.0."
  1064. },
  1065. )
  1066. gradient_accumulation_kwargs: Optional[dict] = field(
  1067. default=None,
  1068. metadata={
  1069. "help": "Additional kwargs to configure gradient accumulation, see [`accelerate.utils.GradientAccumulationPlugin`]. "
  1070. "Any of the following (optional) keys are acceptable: "
  1071. " num_steps (`int`): Will take precedence over [`~.TrainingArguments.gradient_accumulation_steps`] if "
  1072. " the latter is set to 1, otherwise an exception will be raised. "
  1073. " adjust_scheduler (`bool`): Whether to adjust the scheduler steps to account for [`~.TrainingArguments.gradient_accumulation_steps`]. "
  1074. " The [`accelerate.utils.GradientAccumulationPlugin`] default is `True`. "
  1075. " sync_each_batch (`bool`): Whether to synchronize the gradients at each data batch. "
  1076. " The [`accelerate.utils.GradientAccumulationPlugin`] default is `False`."
  1077. },
  1078. )
  1079. use_configured_state: bool = field(
  1080. default=False,
  1081. metadata={
  1082. "help": "Whether or not to use a pre-configured `AcceleratorState` or `PartialState` defined before calling `TrainingArguments`."
  1083. "If `True`, an `Accelerator` or `PartialState` must be initialized. May lead to issues using sweeps or hyperparameter tuning."
  1084. },
  1085. )
  1086. @classmethod
  1087. def from_json_file(cls, json_file):
  1088. # Check if exists
  1089. open_file = io.open if os.path.exists(json_file) else open
  1090. with open_file(json_file, "r", encoding="utf-8") as f:
  1091. config_dict = json.load(f)
  1092. # Check for keys and load sensible defaults
  1093. extra_keys = sorted(key for key in config_dict if key not in cls.__dataclass_fields__)
  1094. if len(extra_keys) > 0:
  1095. raise ValueError(
  1096. f"The config file at {json_file} had unknown keys ({extra_keys}), please try upgrading your `transformers`"
  1097. " version or fix (and potentially remove these keys) from your config file."
  1098. )
  1099. return cls(**config_dict)
  1100. def to_dict(self):
  1101. return copy.deepcopy(self.__dict__)
  1102. def pop(self, key, default=None):
  1103. return self.__dict__.pop(key, default)
  1104. class LayerWiseDummyOptimizer(torch.optim.Optimizer):
  1105. """
  1106. For Layer-wise optimizers such as GaLoRE optimizer, the optimization
  1107. step is already done through the post gradient hooks. Therefore
  1108. the trick is to create a dummy optimizer that can take arbitrary
  1109. args and kwargs and return a no-op during training.
  1110. Initial idea from @hiyouga in LLaMA-Factory:
  1111. https://github.com/hiyouga/LLaMA-Factory/commit/8664262cde3919e10eaecbd66e8c5d356856362e#diff-ebe08ab14496dfb9e06075f0fdd36799ef6d1535cc4dd4715b74c4e3e06fe3ba
  1112. """
  1113. def __init__(self, optimizer_dict=None, **kwargs):
  1114. dummy_tensor = torch.randn(1, 1)
  1115. self.optimizer_dict = optimizer_dict
  1116. super().__init__([dummy_tensor], {"lr": kwargs.get("lr", 1e-03)})
  1117. def zero_grad(self, set_to_none: bool = True) -> None:
  1118. pass
  1119. def step(self, closure=None) -> Optional[float]:
  1120. pass
  1121. class LayerWiseDummyScheduler(LRScheduler):
  1122. """
  1123. For Layer-wise optimizers such as GaLoRE optimizer, the optimization and scheduling step
  1124. are already done through the post gradient hooks. Therefore
  1125. the trick is to create a dummy scheduler that can take arbitrary
  1126. args and kwargs and return a no-op during training.
  1127. """
  1128. def __init__(self, *args, **kwargs):
  1129. self.default_lr = kwargs["lr"]
  1130. optimizer = LayerWiseDummyOptimizer(**kwargs)
  1131. last_epoch = -1
  1132. super().__init__(optimizer, last_epoch)
  1133. def get_lr(self):
  1134. # default value
  1135. lrs = [self.default_lr]
  1136. # we take each lr in the parameters if they exist, assumes the optimizer to be the `LayerWiseDummyOptimizer`
  1137. if self.optimizer is not None:
  1138. param_wise_lrs = [
  1139. [group["lr"] for group in optim.param_groups] for optim in self.optimizer.optimizer_dict.values()
  1140. ]
  1141. lrs = list(chain(*param_wise_lrs))
  1142. return lrs
  1143. def _get_closed_form_lr(self):
  1144. return self.base_lrs
  1145. def set_rng_state_for_device(device_name, device_module, checkpoint_rng_state, is_distributed):
  1146. """Helper to set RNG state for a specific device type (CUDA, NPU, MLU, MUSA)"""
  1147. device_state_key = device_name.lower()
  1148. err_template = "Didn't manage to set back the RNG states of the {backend} because of the following error:\n {exception}\nThis won't yield the same results as if the training had not been interrupted."
  1149. try:
  1150. if is_distributed:
  1151. device_module.random.set_rng_state_all(checkpoint_rng_state[device_state_key])
  1152. else:
  1153. device_module.random.set_rng_state(checkpoint_rng_state[device_state_key])
  1154. except Exception as e:
  1155. # Log error if setting RNG state fails
  1156. logger.error(err_template.format(backend=device_name, exception=e))