generic.py 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159
  1. # Copyright 2022 The HuggingFace Team. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """
  15. Generic utilities
  16. """
  17. import inspect
  18. import json
  19. import os
  20. import tempfile
  21. import warnings
  22. from collections import OrderedDict, UserDict, defaultdict
  23. from collections.abc import Iterable, MutableMapping
  24. from contextlib import AbstractContextManager, ExitStack, contextmanager
  25. from dataclasses import dataclass, fields, is_dataclass
  26. from enum import Enum
  27. from functools import partial, wraps
  28. from typing import Any, Callable, Optional, TypedDict
  29. import numpy as np
  30. from ..utils import logging
  31. from .import_utils import (
  32. is_flax_available,
  33. is_mlx_available,
  34. is_tf_available,
  35. is_torch_available,
  36. is_torch_fx_proxy,
  37. requires,
  38. )
  39. _CAN_RECORD_REGISTRY = {}
  40. logger = logging.get_logger(__name__)
  41. if is_torch_available():
  42. # required for @can_return_tuple decorator to work with torchdynamo
  43. import torch
  44. from ..model_debugging_utils import model_addition_debugger_context
  45. # vendored from distutils.util
  46. def strtobool(val):
  47. """Convert a string representation of truth to true (1) or false (0).
  48. True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values are 'n', 'no', 'f', 'false', 'off', and '0'.
  49. Raises ValueError if 'val' is anything else.
  50. """
  51. val = val.lower()
  52. if val in {"y", "yes", "t", "true", "on", "1"}:
  53. return 1
  54. if val in {"n", "no", "f", "false", "off", "0"}:
  55. return 0
  56. raise ValueError(f"invalid truth value {val!r}")
  57. def infer_framework_from_repr(x):
  58. """
  59. Tries to guess the framework of an object `x` from its repr (brittle but will help in `is_tensor` to try the
  60. frameworks in a smart order, without the need to import the frameworks).
  61. """
  62. representation = str(type(x))
  63. if representation.startswith("<class 'torch."):
  64. return "pt"
  65. elif representation.startswith("<class 'tensorflow."):
  66. return "tf"
  67. elif representation.startswith("<class 'jax"):
  68. return "jax"
  69. elif representation.startswith("<class 'numpy."):
  70. return "np"
  71. elif representation.startswith("<class 'mlx."):
  72. return "mlx"
  73. def _get_frameworks_and_test_func(x):
  74. """
  75. Returns an (ordered since we are in Python 3.7+) dictionary framework to test function, which places the framework
  76. we can guess from the repr first, then Numpy, then the others.
  77. """
  78. framework_to_test = {
  79. "pt": is_torch_tensor,
  80. "tf": is_tf_tensor,
  81. "jax": is_jax_tensor,
  82. "np": is_numpy_array,
  83. "mlx": is_mlx_array,
  84. }
  85. preferred_framework = infer_framework_from_repr(x)
  86. # We will test this one first, then numpy, then the others.
  87. frameworks = [] if preferred_framework is None else [preferred_framework]
  88. if preferred_framework != "np":
  89. frameworks.append("np")
  90. frameworks.extend([f for f in framework_to_test if f not in [preferred_framework, "np"]])
  91. return {f: framework_to_test[f] for f in frameworks}
  92. def is_tensor(x):
  93. """
  94. Tests if `x` is a `torch.Tensor`, `tf.Tensor`, `jaxlib.xla_extension.DeviceArray`, `np.ndarray` or `mlx.array`
  95. in the order defined by `infer_framework_from_repr`
  96. """
  97. # This gives us a smart order to test the frameworks with the corresponding tests.
  98. framework_to_test_func = _get_frameworks_and_test_func(x)
  99. for test_func in framework_to_test_func.values():
  100. if test_func(x):
  101. return True
  102. # Tracers
  103. if is_torch_fx_proxy(x):
  104. return True
  105. if is_flax_available():
  106. from jax.core import Tracer
  107. if isinstance(x, Tracer):
  108. return True
  109. return False
  110. def _is_numpy(x):
  111. return isinstance(x, np.ndarray)
  112. def is_numpy_array(x):
  113. """
  114. Tests if `x` is a numpy array or not.
  115. """
  116. return _is_numpy(x)
  117. def _is_torch(x):
  118. import torch
  119. return isinstance(x, torch.Tensor)
  120. def is_torch_tensor(x):
  121. """
  122. Tests if `x` is a torch tensor or not. Safe to call even if torch is not installed.
  123. """
  124. return False if not is_torch_available() else _is_torch(x)
  125. def _is_torch_device(x):
  126. import torch
  127. return isinstance(x, torch.device)
  128. def is_torch_device(x):
  129. """
  130. Tests if `x` is a torch device or not. Safe to call even if torch is not installed.
  131. """
  132. return False if not is_torch_available() else _is_torch_device(x)
  133. def _is_torch_dtype(x):
  134. import torch
  135. if isinstance(x, str):
  136. if hasattr(torch, x):
  137. x = getattr(torch, x)
  138. else:
  139. return False
  140. return isinstance(x, torch.dtype)
  141. def is_torch_dtype(x):
  142. """
  143. Tests if `x` is a torch dtype or not. Safe to call even if torch is not installed.
  144. """
  145. return False if not is_torch_available() else _is_torch_dtype(x)
  146. def _is_tensorflow(x):
  147. import tensorflow as tf
  148. return isinstance(x, tf.Tensor)
  149. def is_tf_tensor(x):
  150. """
  151. Tests if `x` is a tensorflow tensor or not. Safe to call even if tensorflow is not installed.
  152. """
  153. return False if not is_tf_available() else _is_tensorflow(x)
  154. def _is_tf_symbolic_tensor(x):
  155. import tensorflow as tf
  156. # the `is_symbolic_tensor` predicate is only available starting with TF 2.14
  157. if hasattr(tf, "is_symbolic_tensor"):
  158. return tf.is_symbolic_tensor(x)
  159. return isinstance(x, tf.Tensor)
  160. def is_tf_symbolic_tensor(x):
  161. """
  162. Tests if `x` is a tensorflow symbolic tensor or not (ie. not eager). Safe to call even if tensorflow is not
  163. installed.
  164. """
  165. return False if not is_tf_available() else _is_tf_symbolic_tensor(x)
  166. def _is_jax(x):
  167. import jax.numpy as jnp # noqa: F811
  168. return isinstance(x, jnp.ndarray)
  169. def is_jax_tensor(x):
  170. """
  171. Tests if `x` is a Jax tensor or not. Safe to call even if jax is not installed.
  172. """
  173. return False if not is_flax_available() else _is_jax(x)
  174. def _is_mlx(x):
  175. import mlx.core as mx
  176. return isinstance(x, mx.array)
  177. def is_mlx_array(x):
  178. """
  179. Tests if `x` is a mlx array or not. Safe to call even when mlx is not installed.
  180. """
  181. return False if not is_mlx_available() else _is_mlx(x)
  182. def to_py_obj(obj):
  183. """
  184. Convert a TensorFlow tensor, PyTorch tensor, Numpy array or python list to a python list.
  185. """
  186. if isinstance(obj, (int, float)):
  187. return obj
  188. elif isinstance(obj, (dict, UserDict)):
  189. return {k: to_py_obj(v) for k, v in obj.items()}
  190. elif isinstance(obj, (list, tuple)):
  191. try:
  192. arr = np.array(obj)
  193. if np.issubdtype(arr.dtype, np.integer) or np.issubdtype(arr.dtype, np.floating):
  194. return arr.tolist()
  195. except Exception:
  196. pass
  197. return [to_py_obj(o) for o in obj]
  198. framework_to_py_obj = {
  199. "pt": lambda obj: obj.tolist(),
  200. "tf": lambda obj: obj.numpy().tolist(),
  201. "jax": lambda obj: np.asarray(obj).tolist(),
  202. "np": lambda obj: obj.tolist(),
  203. }
  204. # This gives us a smart order to test the frameworks with the corresponding tests.
  205. framework_to_test_func = _get_frameworks_and_test_func(obj)
  206. for framework, test_func in framework_to_test_func.items():
  207. if test_func(obj):
  208. return framework_to_py_obj[framework](obj)
  209. # tolist also works on 0d np arrays
  210. if isinstance(obj, np.number):
  211. return obj.tolist()
  212. else:
  213. return obj
  214. def to_numpy(obj):
  215. """
  216. Convert a TensorFlow tensor, PyTorch tensor, Numpy array or python list to a Numpy array.
  217. """
  218. framework_to_numpy = {
  219. "pt": lambda obj: obj.detach().cpu().numpy(),
  220. "tf": lambda obj: obj.numpy(),
  221. "jax": lambda obj: np.asarray(obj),
  222. "np": lambda obj: obj,
  223. }
  224. if isinstance(obj, (dict, UserDict)):
  225. return {k: to_numpy(v) for k, v in obj.items()}
  226. elif isinstance(obj, (list, tuple)):
  227. return np.array(obj)
  228. # This gives us a smart order to test the frameworks with the corresponding tests.
  229. framework_to_test_func = _get_frameworks_and_test_func(obj)
  230. for framework, test_func in framework_to_test_func.items():
  231. if test_func(obj):
  232. return framework_to_numpy[framework](obj)
  233. return obj
  234. class ModelOutput(OrderedDict):
  235. """
  236. Base class for all model outputs as dataclass. Has a `__getitem__` that allows indexing by integer or slice (like a
  237. tuple) or strings (like a dictionary) that will ignore the `None` attributes. Otherwise behaves like a regular
  238. python dictionary.
  239. <Tip warning={true}>
  240. You can't unpack a `ModelOutput` directly. Use the [`~utils.ModelOutput.to_tuple`] method to convert it to a tuple
  241. before.
  242. </Tip>
  243. """
  244. def __init_subclass__(cls) -> None:
  245. """Register subclasses as pytree nodes.
  246. This is necessary to synchronize gradients when using `torch.nn.parallel.DistributedDataParallel` with
  247. `static_graph=True` with modules that output `ModelOutput` subclasses.
  248. """
  249. if is_torch_available():
  250. from torch.utils._pytree import register_pytree_node
  251. register_pytree_node(
  252. cls,
  253. _model_output_flatten,
  254. partial(_model_output_unflatten, output_type=cls),
  255. serialized_type_name=f"{cls.__module__}.{cls.__name__}",
  256. )
  257. def __init__(self, *args, **kwargs):
  258. super().__init__(*args, **kwargs)
  259. # Subclasses of ModelOutput must use the @dataclass decorator
  260. # This check is done in __init__ because the @dataclass decorator operates after __init_subclass__
  261. # issubclass() would return True for issubclass(ModelOutput, ModelOutput) when False is needed
  262. # Just need to check that the current class is not ModelOutput
  263. is_modeloutput_subclass = self.__class__ != ModelOutput
  264. if is_modeloutput_subclass and not is_dataclass(self):
  265. raise TypeError(
  266. f"{self.__module__}.{self.__class__.__name__} is not a dataclass."
  267. " This is a subclass of ModelOutput and so must use the @dataclass decorator."
  268. )
  269. def __post_init__(self):
  270. """Check the ModelOutput dataclass.
  271. Only occurs if @dataclass decorator has been used.
  272. """
  273. class_fields = fields(self)
  274. # Safety and consistency checks
  275. if not len(class_fields):
  276. raise ValueError(f"{self.__class__.__name__} has no fields.")
  277. if not all(field.default is None for field in class_fields[1:]):
  278. raise ValueError(f"{self.__class__.__name__} should not have more than one required field.")
  279. first_field = getattr(self, class_fields[0].name)
  280. other_fields_are_none = all(getattr(self, field.name) is None for field in class_fields[1:])
  281. if other_fields_are_none and not is_tensor(first_field):
  282. if isinstance(first_field, dict):
  283. iterator = first_field.items()
  284. first_field_iterator = True
  285. else:
  286. try:
  287. iterator = iter(first_field)
  288. first_field_iterator = True
  289. except TypeError:
  290. first_field_iterator = False
  291. # if we provided an iterator as first field and the iterator is a (key, value) iterator
  292. # set the associated fields
  293. if first_field_iterator:
  294. # reset first field to None
  295. setattr(self, class_fields[0].name, None)
  296. for idx, element in enumerate(iterator):
  297. if not isinstance(element, (list, tuple)) or len(element) != 2 or not isinstance(element[0], str):
  298. if idx == 0:
  299. # If we do not have an iterator of key/values, set it as attribute
  300. self[class_fields[0].name] = first_field
  301. else:
  302. # If we have a mixed iterator, raise an error
  303. raise ValueError(
  304. f"Cannot set key/value for {element}. It needs to be a tuple (key, value)."
  305. )
  306. break
  307. setattr(self, element[0], element[1])
  308. if element[1] is not None:
  309. self[element[0]] = element[1]
  310. elif first_field is not None:
  311. self[class_fields[0].name] = first_field
  312. else:
  313. for field in class_fields:
  314. v = getattr(self, field.name)
  315. if v is not None:
  316. self[field.name] = v
  317. def __delitem__(self, *args, **kwargs):
  318. raise Exception(f"You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.")
  319. def setdefault(self, *args, **kwargs):
  320. raise Exception(f"You cannot use ``setdefault`` on a {self.__class__.__name__} instance.")
  321. def pop(self, *args, **kwargs):
  322. raise Exception(f"You cannot use ``pop`` on a {self.__class__.__name__} instance.")
  323. def update(self, *args, **kwargs):
  324. raise Exception(f"You cannot use ``update`` on a {self.__class__.__name__} instance.")
  325. def __getitem__(self, k):
  326. if isinstance(k, str):
  327. inner_dict = dict(self.items())
  328. return inner_dict[k]
  329. else:
  330. return self.to_tuple()[k]
  331. def __setattr__(self, name, value):
  332. if name in self.keys() and value is not None:
  333. # Don't call self.__setitem__ to avoid recursion errors
  334. super().__setitem__(name, value)
  335. super().__setattr__(name, value)
  336. def __setitem__(self, key, value):
  337. # Will raise a KeyException if needed
  338. super().__setitem__(key, value)
  339. # Don't call self.__setattr__ to avoid recursion errors
  340. super().__setattr__(key, value)
  341. def __reduce__(self):
  342. if not is_dataclass(self):
  343. return super().__reduce__()
  344. callable, _args, *remaining = super().__reduce__()
  345. args = tuple(getattr(self, field.name) for field in fields(self))
  346. return callable, args, *remaining
  347. def to_tuple(self) -> tuple:
  348. """
  349. Convert self to a tuple containing all the attributes/keys that are not `None`.
  350. """
  351. return tuple(self[k] for k in self.keys())
  352. if is_torch_available():
  353. import torch.utils._pytree as _torch_pytree
  354. def _model_output_flatten(output: ModelOutput) -> tuple[list[Any], "_torch_pytree.Context"]:
  355. return list(output.values()), list(output.keys())
  356. def _model_output_unflatten(
  357. values: Iterable[Any],
  358. context: "_torch_pytree.Context",
  359. output_type=None,
  360. ) -> ModelOutput:
  361. return output_type(**dict(zip(context, values)))
  362. _torch_pytree.register_pytree_node(
  363. ModelOutput,
  364. _model_output_flatten,
  365. partial(_model_output_unflatten, output_type=ModelOutput),
  366. serialized_type_name=f"{ModelOutput.__module__}.{ModelOutput.__name__}",
  367. )
  368. class ExplicitEnum(str, Enum):
  369. """
  370. Enum with more explicit error message for missing values.
  371. """
  372. @classmethod
  373. def _missing_(cls, value):
  374. raise ValueError(
  375. f"{value} is not a valid {cls.__name__}, please select one of {list(cls._value2member_map_.keys())}"
  376. )
  377. class PaddingStrategy(ExplicitEnum):
  378. """
  379. Possible values for the `padding` argument in [`PreTrainedTokenizerBase.__call__`]. Useful for tab-completion in an
  380. IDE.
  381. """
  382. LONGEST = "longest"
  383. MAX_LENGTH = "max_length"
  384. DO_NOT_PAD = "do_not_pad"
  385. class TensorType(ExplicitEnum):
  386. """
  387. Possible values for the `return_tensors` argument in [`PreTrainedTokenizerBase.__call__`]. Useful for
  388. tab-completion in an IDE.
  389. """
  390. PYTORCH = "pt"
  391. TENSORFLOW = "tf"
  392. NUMPY = "np"
  393. JAX = "jax"
  394. MLX = "mlx"
  395. class ContextManagers:
  396. """
  397. Wrapper for `contextlib.ExitStack` which enters a collection of context managers. Adaptation of `ContextManagers`
  398. in the `fastcore` library.
  399. """
  400. def __init__(self, context_managers: list[AbstractContextManager]):
  401. self.context_managers = context_managers
  402. self.stack = ExitStack()
  403. def __enter__(self):
  404. for context_manager in self.context_managers:
  405. self.stack.enter_context(context_manager)
  406. def __exit__(self, *args, **kwargs):
  407. self.stack.__exit__(*args, **kwargs)
  408. def can_return_loss(model_class):
  409. """
  410. Check if a given model can return loss.
  411. Args:
  412. model_class (`type`): The class of the model.
  413. """
  414. framework = infer_framework(model_class)
  415. if framework == "tf":
  416. signature = inspect.signature(model_class.call) # TensorFlow models
  417. elif framework == "pt":
  418. signature = inspect.signature(model_class.forward) # PyTorch models
  419. else:
  420. signature = inspect.signature(model_class.__call__) # Flax models
  421. for p in signature.parameters:
  422. if p == "return_loss" and signature.parameters[p].default is True:
  423. return True
  424. return False
  425. def find_labels(model_class):
  426. """
  427. Find the labels used by a given model.
  428. Args:
  429. model_class (`type`): The class of the model.
  430. """
  431. model_name = model_class.__name__
  432. framework = infer_framework(model_class)
  433. if framework == "tf":
  434. signature = inspect.signature(model_class.call) # TensorFlow models
  435. elif framework == "pt":
  436. signature = inspect.signature(model_class.forward) # PyTorch models
  437. else:
  438. signature = inspect.signature(model_class.__call__) # Flax models
  439. if "QuestionAnswering" in model_name:
  440. return [p for p in signature.parameters if "label" in p or p in ("start_positions", "end_positions")]
  441. else:
  442. return [p for p in signature.parameters if "label" in p]
  443. def flatten_dict(d: MutableMapping, parent_key: str = "", delimiter: str = "."):
  444. """Flatten a nested dict into a single level dict."""
  445. def _flatten_dict(d, parent_key="", delimiter="."):
  446. for k, v in d.items():
  447. key = str(parent_key) + delimiter + str(k) if parent_key else k
  448. if v and isinstance(v, MutableMapping):
  449. yield from flatten_dict(v, key, delimiter=delimiter).items()
  450. else:
  451. yield key, v
  452. return dict(_flatten_dict(d, parent_key, delimiter))
  453. @contextmanager
  454. def working_or_temp_dir(working_dir, use_temp_dir: bool = False):
  455. if use_temp_dir:
  456. with tempfile.TemporaryDirectory() as tmp_dir:
  457. yield tmp_dir
  458. else:
  459. yield working_dir
  460. def transpose(array, axes=None):
  461. """
  462. Framework-agnostic version of `numpy.transpose` that will work on torch/TensorFlow/Jax tensors as well as NumPy
  463. arrays.
  464. """
  465. if is_numpy_array(array):
  466. return np.transpose(array, axes=axes)
  467. elif is_torch_tensor(array):
  468. return array.T if axes is None else array.permute(*axes)
  469. elif is_tf_tensor(array):
  470. import tensorflow as tf
  471. return tf.transpose(array, perm=axes)
  472. elif is_jax_tensor(array):
  473. import jax.numpy as jnp
  474. return jnp.transpose(array, axes=axes)
  475. else:
  476. raise ValueError(f"Type not supported for transpose: {type(array)}.")
  477. def reshape(array, newshape):
  478. """
  479. Framework-agnostic version of `numpy.reshape` that will work on torch/TensorFlow/Jax tensors as well as NumPy
  480. arrays.
  481. """
  482. if is_numpy_array(array):
  483. return np.reshape(array, newshape)
  484. elif is_torch_tensor(array):
  485. return array.reshape(*newshape)
  486. elif is_tf_tensor(array):
  487. import tensorflow as tf
  488. return tf.reshape(array, newshape)
  489. elif is_jax_tensor(array):
  490. import jax.numpy as jnp
  491. return jnp.reshape(array, newshape)
  492. else:
  493. raise ValueError(f"Type not supported for reshape: {type(array)}.")
  494. def squeeze(array, axis=None):
  495. """
  496. Framework-agnostic version of `numpy.squeeze` that will work on torch/TensorFlow/Jax tensors as well as NumPy
  497. arrays.
  498. """
  499. if is_numpy_array(array):
  500. return np.squeeze(array, axis=axis)
  501. elif is_torch_tensor(array):
  502. return array.squeeze() if axis is None else array.squeeze(dim=axis)
  503. elif is_tf_tensor(array):
  504. import tensorflow as tf
  505. return tf.squeeze(array, axis=axis)
  506. elif is_jax_tensor(array):
  507. import jax.numpy as jnp
  508. return jnp.squeeze(array, axis=axis)
  509. else:
  510. raise ValueError(f"Type not supported for squeeze: {type(array)}.")
  511. def expand_dims(array, axis):
  512. """
  513. Framework-agnostic version of `numpy.expand_dims` that will work on torch/TensorFlow/Jax tensors as well as NumPy
  514. arrays.
  515. """
  516. if is_numpy_array(array):
  517. return np.expand_dims(array, axis)
  518. elif is_torch_tensor(array):
  519. return array.unsqueeze(dim=axis)
  520. elif is_tf_tensor(array):
  521. import tensorflow as tf
  522. return tf.expand_dims(array, axis=axis)
  523. elif is_jax_tensor(array):
  524. import jax.numpy as jnp
  525. return jnp.expand_dims(array, axis=axis)
  526. else:
  527. raise ValueError(f"Type not supported for expand_dims: {type(array)}.")
  528. def tensor_size(array):
  529. """
  530. Framework-agnostic version of `numpy.size` that will work on torch/TensorFlow/Jax tensors as well as NumPy arrays.
  531. """
  532. if is_numpy_array(array):
  533. return np.size(array)
  534. elif is_torch_tensor(array):
  535. return array.numel()
  536. elif is_tf_tensor(array):
  537. import tensorflow as tf
  538. return tf.size(array)
  539. elif is_jax_tensor(array):
  540. return array.size
  541. else:
  542. raise ValueError(f"Type not supported for tensor_size: {type(array)}.")
  543. def infer_framework(model_class):
  544. """
  545. Infers the framework of a given model without using isinstance(), because we cannot guarantee that the relevant
  546. classes are imported or available.
  547. """
  548. for base_class in inspect.getmro(model_class):
  549. module = base_class.__module__
  550. name = base_class.__name__
  551. if module.startswith("tensorflow") or module.startswith("keras") or name == "TFPreTrainedModel":
  552. return "tf"
  553. elif module.startswith("torch") or name == "PreTrainedModel":
  554. return "pt"
  555. elif module.startswith("flax") or module.startswith("jax") or name == "FlaxPreTrainedModel":
  556. return "flax"
  557. raise TypeError(f"Could not infer framework from class {model_class}.")
  558. def torch_int(x):
  559. """
  560. Casts an input to a torch int64 tensor if we are in a tracing context, otherwise to a Python int.
  561. """
  562. if not is_torch_available():
  563. return int(x)
  564. import torch
  565. return x.to(torch.int64) if torch.jit.is_tracing() and isinstance(x, torch.Tensor) else int(x)
  566. def torch_float(x):
  567. """
  568. Casts an input to a torch float32 tensor if we are in a tracing context, otherwise to a Python float.
  569. """
  570. if not is_torch_available():
  571. return int(x)
  572. import torch
  573. return x.to(torch.float32) if torch.jit.is_tracing() and isinstance(x, torch.Tensor) else int(x)
  574. def filter_out_non_signature_kwargs(extra: Optional[list] = None):
  575. """
  576. Decorator to filter out named arguments that are not in the function signature.
  577. This decorator ensures that only the keyword arguments that match the function's signature, or are specified in the
  578. `extra` list, are passed to the function. Any additional keyword arguments are filtered out and a warning is issued.
  579. Parameters:
  580. extra (`Optional[list]`, *optional*):
  581. A list of extra keyword argument names that are allowed even if they are not in the function's signature.
  582. Returns:
  583. Callable:
  584. A decorator that wraps the function and filters out invalid keyword arguments.
  585. Example usage:
  586. ```python
  587. @filter_out_non_signature_kwargs(extra=["allowed_extra_arg"])
  588. def my_function(arg1, arg2, **kwargs):
  589. print(arg1, arg2, kwargs)
  590. my_function(arg1=1, arg2=2, allowed_extra_arg=3, invalid_arg=4)
  591. # This will print: 1 2 {"allowed_extra_arg": 3}
  592. # And issue a warning: "The following named arguments are not valid for `my_function` and were ignored: 'invalid_arg'"
  593. ```
  594. """
  595. extra = extra or []
  596. extra_params_to_pass = set(extra)
  597. def decorator(func):
  598. sig = inspect.signature(func)
  599. function_named_args = set(sig.parameters.keys())
  600. valid_kwargs_to_pass = function_named_args.union(extra_params_to_pass)
  601. # Required for better warning message
  602. is_instance_method = "self" in function_named_args
  603. is_class_method = "cls" in function_named_args
  604. # Mark function as decorated
  605. func._filter_out_non_signature_kwargs = True
  606. @wraps(func)
  607. def wrapper(*args, **kwargs):
  608. valid_kwargs = {}
  609. invalid_kwargs = {}
  610. for k, v in kwargs.items():
  611. if k in valid_kwargs_to_pass:
  612. valid_kwargs[k] = v
  613. else:
  614. invalid_kwargs[k] = v
  615. if invalid_kwargs:
  616. invalid_kwargs_names = [f"'{k}'" for k in invalid_kwargs]
  617. invalid_kwargs_names = ", ".join(invalid_kwargs_names)
  618. # Get the class name for better warning message
  619. if is_instance_method:
  620. cls_prefix = args[0].__class__.__name__ + "."
  621. elif is_class_method:
  622. cls_prefix = args[0].__name__ + "."
  623. else:
  624. cls_prefix = ""
  625. warnings.warn(
  626. f"The following named arguments are not valid for `{cls_prefix}{func.__name__}`"
  627. f" and were ignored: {invalid_kwargs_names}",
  628. UserWarning,
  629. stacklevel=2,
  630. )
  631. return func(*args, **valid_kwargs)
  632. return wrapper
  633. return decorator
  634. class TransformersKwargs(TypedDict, total=False):
  635. """
  636. Keyword arguments to be passed to the forward pass of a `PreTrainedModel`.
  637. Attributes:
  638. num_items_in_batch (`Optional[torch.Tensor]`, *optional*):
  639. Number of items in the batch. It is recommended to pass it when you are doing gradient accumulation.
  640. output_hidden_states (`Optional[bool]`, *optional*):
  641. Most of the models support outputting all hidden states computed during the forward pass.
  642. output_attentions (`Optional[bool]`, *optional*):
  643. Turn this on to return the intermediary attention scores.
  644. output_router_logits (`Optional[bool]`, *optional*):
  645. For MoE models, this allows returning the router logits to compute the loss.
  646. cu_seq_lens_q (`torch.LongTensor`, *optional*)
  647. Gets cumulative sequence length for query state.
  648. cu_seq_lens_k (`torch.LongTensor`, *optional*)
  649. Gets cumulative sequence length for key state.
  650. max_length_q (`int`, *optional*):
  651. Maximum sequence length for query state.
  652. max_length_k (`int`, *optional*):
  653. Maximum sequence length for key state.
  654. """
  655. num_items_in_batch: Optional["torch.Tensor"]
  656. output_hidden_states: Optional[bool]
  657. output_attentions: Optional[bool]
  658. output_router_logits: Optional[bool]
  659. cu_seq_lens_q: Optional["torch.LongTensor"]
  660. cu_seq_lens_k: Optional["torch.LongTensor"]
  661. max_length_q: Optional[int]
  662. max_length_k: Optional[int]
  663. def is_timm_config_dict(config_dict: dict[str, Any]) -> bool:
  664. """Checks whether a config dict is a timm config dict."""
  665. return "pretrained_cfg" in config_dict
  666. def is_timm_local_checkpoint(pretrained_model_path: str) -> bool:
  667. """
  668. Checks whether a checkpoint is a timm model checkpoint.
  669. """
  670. if pretrained_model_path is None:
  671. return False
  672. # in case it's Path, not str
  673. pretrained_model_path = str(pretrained_model_path)
  674. is_file = os.path.isfile(pretrained_model_path)
  675. is_dir = os.path.isdir(pretrained_model_path)
  676. # pretrained_model_path is a file
  677. if is_file and pretrained_model_path.endswith(".json"):
  678. with open(pretrained_model_path) as f:
  679. config_dict = json.load(f)
  680. return is_timm_config_dict(config_dict)
  681. # pretrained_model_path is a directory with a config.json
  682. if is_dir and os.path.exists(os.path.join(pretrained_model_path, "config.json")):
  683. with open(os.path.join(pretrained_model_path, "config.json")) as f:
  684. config_dict = json.load(f)
  685. return is_timm_config_dict(config_dict)
  686. return False
  687. def set_attribute_for_modules(module: "torch.nn.Module", key: str, value: Any):
  688. """
  689. Set a value to a module and all submodules.
  690. """
  691. setattr(module, key, value)
  692. for submodule in module.children():
  693. set_attribute_for_modules(submodule, key, value)
  694. def del_attribute_from_modules(module: "torch.nn.Module", key: str):
  695. """
  696. Delete a value from a module and all submodules.
  697. """
  698. # because we might remove it previously in case it's a shared module, e.g. activation function
  699. if hasattr(module, key):
  700. delattr(module, key)
  701. for submodule in module.children():
  702. del_attribute_from_modules(submodule, key)
  703. def can_return_tuple(func):
  704. """
  705. Decorator to wrap model method, to call output.to_tuple() if return_dict=False passed as a kwarg or
  706. use_return_dict=False is set in the config.
  707. Note:
  708. output.to_tuple() convert output to tuple skipping all `None` values.
  709. """
  710. @wraps(func)
  711. def wrapper(self, *args, **kwargs):
  712. return_dict = self.config.return_dict if hasattr(self, "config") else True
  713. return_dict_passed = kwargs.pop("return_dict", return_dict)
  714. if return_dict_passed is not None:
  715. return_dict = return_dict_passed
  716. output = func(self, *args, **kwargs)
  717. if not return_dict and not isinstance(output, tuple):
  718. output = output.to_tuple()
  719. return output
  720. return wrapper
  721. # if is_torch_available():
  722. # @torch._dynamo.disable
  723. @dataclass
  724. @requires(backends=("torch",))
  725. class OutputRecorder:
  726. """
  727. Configuration for recording outputs from a model via hooks.
  728. Attributes:
  729. target_class (Type): The class (e.g., nn.Module) to which the hook will be attached.
  730. index (Optional[int]): If the output is a tuple/list, optionally record only at a specific index.
  731. layer_name (Optional[str]): Name of the submodule to target (if needed), e.g., "transformer.layer.3.attn".
  732. class_name (Optional[str]): Name of the class to which the hook will be attached. Could be the suffix of class name in some cases.
  733. """
  734. target_class: "type[torch.nn.Module]"
  735. index: int = 0
  736. layer_name: Optional[str] = None
  737. class_name: Optional[str] = None
  738. def check_model_inputs(tie_last_hidden_states=True):
  739. """
  740. Decorator to intercept specific layer outputs without using hooks.
  741. Compatible with torch.compile (Dynamo tracing).
  742. Args:
  743. tie_last_hidden_states (`bool`, *optional*, defaults to `True`):
  744. Whether to overwrite `out.hidden_states[-1]` with the `out.last_hidden_state`.
  745. This is true for all language models and should be toggled off only if
  746. `out.hidden_states[-1]` has to be the hidden state before last layer norm, which
  747. is needed for some vision models (e.g. CLIP, SigLIP)
  748. """
  749. def wrapped_fn(func):
  750. @wraps(func)
  751. def wrapper(self, *args, **kwargs):
  752. use_cache = (
  753. kwargs["use_cache"] if kwargs.get("use_cache") is not None else getattr(self.config, "use_cache", None)
  754. )
  755. if use_cache is not None:
  756. if getattr(self, "gradient_checkpointing", False) and self.training and use_cache:
  757. logger.warning_once(
  758. "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
  759. )
  760. use_cache = False
  761. kwargs["use_cache"] = use_cache
  762. return_dict = kwargs.pop("return_dict", None)
  763. if return_dict is None:
  764. return_dict = getattr(self.config, "return_dict", True)
  765. all_args = kwargs.copy()
  766. if "kwargs" in all_args:
  767. for k, v in all_args["kwargs"].items():
  768. all_args[k] = v
  769. capture_flags = _CAN_RECORD_REGISTRY.get(str(self.__class__), {}) # there is a weak ref for executorch
  770. recordable_keys = {
  771. f"output_{k}": all_args.get(
  772. f"output_{k}",
  773. getattr(
  774. self.config,
  775. f"output_{k}",
  776. all_args.get("output_attentions", getattr(self.config, "output_attentions", False)),
  777. ),
  778. )
  779. for k in capture_flags
  780. }
  781. # We let cross attentions to be saved separately because some models add `cross-attn` layer
  782. # when certain condtions are met. Let's output cross attention if attentions are requested (for BC)
  783. if "output_attentions" in recordable_keys:
  784. recordable_keys["output_cross_attentions"] = recordable_keys["output_attentions"]
  785. collected_outputs = defaultdict(tuple)
  786. monkey_patched_layers = []
  787. # Check attention implementation is properly set for capturing attention outputs
  788. if recordable_keys.get("output_attentions", False):
  789. supported_attn = ["eager", "eager_paged", "flex_attention"]
  790. config_attn = getattr(self.config, "_attn_implementation", None)
  791. sub_configs = [getattr(self.config, key, None) for key in self.config.sub_configs]
  792. sub_configs_attn = [
  793. getattr(config, "_attn_implementation", None) for config in sub_configs if config is not None
  794. ]
  795. if config_attn not in supported_attn or any(attn not in supported_attn for attn in sub_configs_attn):
  796. warnings.warn(
  797. f"`output_attentions=True` is not supported with `attn_implementation` other than {supported_attn}. "
  798. "Please use `model.set_attn_implementation('eager')` to enable capturing attention outputs.",
  799. UserWarning,
  800. )
  801. def make_capture_wrapper(module, orig_forward, key, index):
  802. @wraps(orig_forward)
  803. def wrapped_forward(*args, **kwargs):
  804. if key == "hidden_states" and len(collected_outputs[key]) == 0:
  805. collected_outputs[key] += (args[0],)
  806. if kwargs.get("debug_io", False):
  807. with model_addition_debugger_context(
  808. module, kwargs.get("debug_io_dir", "~/model_debug"), kwargs.get("prune_layers")
  809. ):
  810. output = orig_forward(*args, **kwargs)
  811. else:
  812. output = orig_forward(*args, **kwargs)
  813. if not isinstance(output, tuple):
  814. collected_outputs[key] += (output,)
  815. elif output[index] is not None:
  816. if key not in collected_outputs:
  817. collected_outputs[key] = (output[index],)
  818. else:
  819. collected_outputs[key] += (output[index],)
  820. return output
  821. return wrapped_forward
  822. if any(recordable_keys.values()):
  823. capture_tasks = []
  824. for key, layer_specs in capture_flags.items():
  825. if not recordable_keys.get(f"output_{key}", False):
  826. continue
  827. if not isinstance(layer_specs, list):
  828. layer_specs = [layer_specs]
  829. for specs in layer_specs:
  830. if not isinstance(specs, OutputRecorder):
  831. index = 0 if "hidden_states" in key else 1
  832. class_name = None if not isinstance(specs, str) else specs
  833. target_class = specs if not isinstance(specs, str) else None
  834. specs = OutputRecorder(target_class=target_class, index=index, class_name=class_name)
  835. capture_tasks.append((key, specs))
  836. for name, module in self.named_modules():
  837. for key, specs in capture_tasks:
  838. # The second check is for multimodals where only backbone layer suffix is available
  839. if (specs.target_class is not None and isinstance(module, specs.target_class)) or (
  840. specs.class_name is not None and name.endswith(specs.class_name)
  841. ):
  842. if specs.layer_name is not None and specs.layer_name not in name:
  843. continue
  844. # Monkey patch forward
  845. original_forward = module.forward
  846. module.forward = make_capture_wrapper(module, original_forward, key, specs.index)
  847. monkey_patched_layers.append((module, original_forward))
  848. try:
  849. outputs = func(self, *args, **kwargs)
  850. except TypeError as original_exception:
  851. # If we get a TypeError, it's possible that the model is not receiving the recordable kwargs correctly.
  852. # Get a TypeError even after removing the recordable kwargs -> re-raise the original exception
  853. # Otherwise -> we're probably missing `**kwargs` in the decorated function
  854. kwargs_without_recordable = {k: v for k, v in kwargs.items() if k not in recordable_keys}
  855. try:
  856. outputs = func(self, *args, **kwargs_without_recordable)
  857. except TypeError:
  858. raise original_exception
  859. raise TypeError(
  860. "Missing `**kwargs` in the signature of the `@check_model_inputs`-decorated function "
  861. f"({func.__qualname__})"
  862. )
  863. # Restore original forward methods
  864. for module, original_forward in monkey_patched_layers:
  865. module.forward = original_forward
  866. # Inject collected outputs into model output
  867. for key in collected_outputs:
  868. if key == "hidden_states":
  869. if not tie_last_hidden_states:
  870. pass
  871. elif hasattr(outputs, "vision_hidden_states"):
  872. collected_outputs[key] = collected_outputs[key][:-1]
  873. collected_outputs[key] += (outputs.vision_hidden_states,)
  874. elif hasattr(outputs, "last_hidden_state"):
  875. collected_outputs[key] = collected_outputs[key][:-1]
  876. collected_outputs[key] += (outputs.last_hidden_state,)
  877. outputs[key] = collected_outputs[key]
  878. elif key == "attentions":
  879. if isinstance(capture_flags[key], list) and len(capture_flags[key]) == 2:
  880. outputs[key] = collected_outputs[key][0::2]
  881. outputs["cross_" + key] = collected_outputs[key][1::2]
  882. else:
  883. outputs[key] = collected_outputs[key]
  884. else:
  885. outputs[key] = collected_outputs[key]
  886. if return_dict is False:
  887. outputs = outputs.to_tuple()
  888. return outputs
  889. return wrapper
  890. return wrapped_fn
  891. class GeneralInterface(MutableMapping):
  892. """
  893. Dict-like object keeping track of a class-wide mapping, as well as a local one. Allows to have library-wide
  894. modifications though the class mapping, as well as local modifications in a single file with the local mapping.
  895. """
  896. # Class instance object, so that a call to `register` can be reflected into all other files correctly, even if
  897. # a new instance is created (in order to locally override a given function)
  898. _global_mapping = {}
  899. def __init__(self):
  900. self._local_mapping = {}
  901. def __getitem__(self, key):
  902. # First check if instance has a local override
  903. if key in self._local_mapping:
  904. return self._local_mapping[key]
  905. return self._global_mapping[key]
  906. def __setitem__(self, key, value):
  907. # Allow local update of the default functions without impacting other instances
  908. self._local_mapping.update({key: value})
  909. def __delitem__(self, key):
  910. del self._local_mapping[key]
  911. def __iter__(self):
  912. # Ensure we use all keys, with the overwritten ones on top
  913. return iter({**self._global_mapping, **self._local_mapping})
  914. def __len__(self):
  915. return len(self._global_mapping.keys() | self._local_mapping.keys())
  916. @classmethod
  917. def register(cls, key: str, value: Callable):
  918. cls._global_mapping.update({key: value})
  919. def valid_keys(self) -> list[str]:
  920. return list(self.keys())