generic.py 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  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. from __future__ import annotations
  18. import inspect
  19. import json
  20. import os
  21. import re
  22. import warnings
  23. from collections import OrderedDict, UserDict
  24. from collections.abc import Callable, Iterable, MutableMapping
  25. from contextlib import AbstractContextManager, ExitStack, nullcontext
  26. from dataclasses import fields, is_dataclass
  27. from enum import Enum
  28. from functools import partial, wraps
  29. from typing import TYPE_CHECKING, Any, TypedDict
  30. import numpy as np
  31. from ..utils import logging
  32. from .import_utils import is_mlx_available, is_torch_available, is_torch_fx_proxy
  33. if TYPE_CHECKING:
  34. import torch
  35. from torch import nn
  36. logger = logging.get_logger(__name__)
  37. _is_torch_available = False
  38. if is_torch_available():
  39. _is_torch_available = True
  40. _registered_model_output_types: set[type[Any]] = set()
  41. def _register_model_output_pytree_node(output_type: type[ModelOutput]) -> None:
  42. if not _is_torch_available or output_type in _registered_model_output_types:
  43. return
  44. import torch.utils._pytree as torch_pytree
  45. torch_pytree.register_pytree_node(
  46. output_type,
  47. _model_output_flatten,
  48. partial(_model_output_unflatten, output_type=output_type),
  49. serialized_type_name=f"{output_type.__module__}.{output_type.__name__}",
  50. )
  51. _registered_model_output_types.add(output_type)
  52. # required for @can_return_tuple decorator to work with torchdynamo
  53. _is_mlx_available = False
  54. if is_mlx_available():
  55. _is_mlx_available = True
  56. # vendored from distutils.util
  57. def strtobool(val) -> int:
  58. """Convert a string representation of truth to true (1) or false (0).
  59. True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values are 'n', 'no', 'f', 'false', 'off', and '0'.
  60. Raises ValueError if 'val' is anything else.
  61. """
  62. val = val.lower()
  63. if val in {"y", "yes", "t", "true", "on", "1"}:
  64. return 1
  65. if val in {"n", "no", "f", "false", "off", "0"}:
  66. return 0
  67. raise ValueError(f"invalid truth value {val!r}")
  68. def infer_framework_from_repr(x) -> str | None:
  69. """
  70. Tries to guess the framework of an object `x` from its repr (brittle but will help in `is_tensor` to try the
  71. frameworks in a smart order, without the need to import the frameworks).
  72. """
  73. representation = str(type(x))
  74. if representation.startswith("<class 'torch."):
  75. return "pt"
  76. elif representation.startswith("<class 'numpy."):
  77. return "np"
  78. elif representation.startswith("<class 'mlx."):
  79. return "mlx"
  80. def _get_frameworks_and_test_func(x):
  81. """
  82. Returns an (ordered since we are in Python 3.7+) dictionary framework to test function, which places the framework
  83. we can guess from the repr first, then Numpy, then the others.
  84. """
  85. framework_to_test = {
  86. "pt": is_torch_tensor,
  87. "np": is_numpy_array,
  88. "mlx": is_mlx_array,
  89. }
  90. preferred_framework = infer_framework_from_repr(x)
  91. # We will test this one first, then numpy, then the others.
  92. frameworks = [] if preferred_framework is None else [preferred_framework]
  93. if preferred_framework != "np":
  94. frameworks.append("np")
  95. frameworks.extend([f for f in framework_to_test if f not in [preferred_framework, "np"]])
  96. return {f: framework_to_test[f] for f in frameworks}
  97. def is_tensor(x) -> bool:
  98. """
  99. Tests if `x` is a `torch.Tensor`, `np.ndarray` or `mlx.array` in the order defined by `infer_framework_from_repr`
  100. """
  101. # This gives us a smart order to test the frameworks with the corresponding tests.
  102. framework_to_test_func = _get_frameworks_and_test_func(x)
  103. for test_func in framework_to_test_func.values():
  104. if test_func(x):
  105. return True
  106. # Tracers
  107. if is_torch_fx_proxy(x):
  108. return True
  109. return False
  110. def is_numpy_array(x) -> bool:
  111. """
  112. Tests if `x` is a numpy array or not.
  113. """
  114. return isinstance(x, np.ndarray)
  115. def is_torch_tensor(x) -> bool:
  116. """
  117. Tests if `x` is a torch tensor or not. Safe to call even if torch is not installed.
  118. """
  119. if not _is_torch_available:
  120. return False
  121. import torch
  122. return isinstance(x, torch.Tensor)
  123. def is_torch_device(x) -> bool:
  124. """
  125. Tests if `x` is a torch device or not. Safe to call even if torch is not installed.
  126. """
  127. if not _is_torch_available:
  128. return False
  129. import torch
  130. return isinstance(x, torch.device)
  131. def is_torch_dtype(x) -> bool:
  132. """
  133. Tests if `x` is a torch dtype or not. Safe to call even if torch is not installed.
  134. """
  135. if not _is_torch_available:
  136. return False
  137. import torch
  138. if isinstance(x, str):
  139. if hasattr(torch, x):
  140. x = getattr(torch, x)
  141. else:
  142. return False
  143. return isinstance(x, torch.dtype)
  144. def _is_tensor_or_array_like(value):
  145. """
  146. Check if a value is array-like (includes ragged arrays)
  147. """
  148. if is_numpy_array(value):
  149. return True
  150. if is_torch_tensor(value):
  151. return True
  152. if isinstance(value, (int, float, bool, np.number)):
  153. return True
  154. if isinstance(value, (list, tuple)):
  155. if len(value) == 0:
  156. # consider empty list or nested list as array-like
  157. return True
  158. return _is_tensor_or_array_like(value[0])
  159. return False
  160. def maybe_autocast(
  161. device_type: str,
  162. dtype: torch.dtype | None = None,
  163. enabled: bool = True,
  164. cache_enabled: bool | None = None,
  165. ):
  166. """
  167. Context manager that only autocasts if:
  168. - `autocast` is already enabled in this context
  169. - Or this call to `maybe_autocast` has `enabled=True`
  170. This prevents `autocast` being added to the graph when it is effectively a no-op.
  171. Which makes graph splitting in `torch.compile` more flexible as it removes the
  172. requirement that partition IDs be monotonically increasing.
  173. """
  174. if not _is_torch_available:
  175. raise ImportError("`maybe_autocast` requires PyTorch to be installed.")
  176. import torch
  177. if device_type == "meta":
  178. return nullcontext()
  179. if torch.is_autocast_enabled(device_type) or enabled:
  180. return torch.autocast(device_type, dtype=dtype, enabled=enabled, cache_enabled=cache_enabled)
  181. else:
  182. return nullcontext()
  183. def _is_mlx(x):
  184. import mlx.core as mx
  185. return isinstance(x, mx.array)
  186. def is_mlx_array(x) -> bool:
  187. """
  188. Tests if `x` is a mlx array or not. Safe to call even when mlx is not installed.
  189. """
  190. return False if not _is_mlx_available else _is_mlx(x)
  191. def is_flash_attention_requested(
  192. config=None, requested_attention_implementation: str | None = None, version: int | None = None
  193. ) -> bool:
  194. """
  195. Checks whether some flavor of flash attention is requested or not. Optionally, checks for a specific version of
  196. flash attention.
  197. This is checked against one of the two arguments, i.e. either the `config` or the directly passed value
  198. `requested_attention_implementation`. Otherwise, an error will be raised (ambiguity).
  199. The different versions of flash attention are usually
  200. - Implementations based on the original flash attention repo: https://github.com/Dao-AILab/flash-attention
  201. - Kernels implementations such as: https://huggingface.co/kernels-community/vllm-flash-attn3
  202. """
  203. if config is not None and requested_attention_implementation is not None:
  204. raise ValueError(
  205. "Requested attention implementation is ambiguous: "
  206. "Please pass either the config or the name of the attention implementation, not both."
  207. )
  208. if config is not None:
  209. checked_attention_implementation = config._attn_implementation
  210. else:
  211. checked_attention_implementation = requested_attention_implementation
  212. # theoretically can happen, equivalent to default implementation (sdpa/eager)
  213. if checked_attention_implementation is None:
  214. return False
  215. # If a specific version is requested, look for a pattern of type "flash...{version}"
  216. if version is not None:
  217. return re.match(r".*flash.*" + str(version), checked_attention_implementation) is not None
  218. # Otherwise, just check "flash" is in the attention implementation
  219. return "flash" in checked_attention_implementation
  220. def to_py_obj(obj):
  221. """
  222. Convert a PyTorch tensor, Numpy array or python list to a python list.
  223. """
  224. if isinstance(obj, (int, float)):
  225. return obj
  226. elif isinstance(obj, (dict, UserDict)):
  227. return {k: to_py_obj(v) for k, v in obj.items()}
  228. elif isinstance(obj, (list, tuple)):
  229. # Only convert directly if all elements are numeric scalars
  230. if all(isinstance(x, (int, float, np.number)) for x in obj):
  231. return list(obj)
  232. # Otherwise recurse element-wise
  233. return [to_py_obj(o) for o in obj]
  234. framework_to_py_obj = {
  235. "pt": lambda obj: obj.tolist(),
  236. "np": lambda obj: obj.tolist(),
  237. }
  238. # This gives us a smart order to test the frameworks with the corresponding tests.
  239. framework_to_test_func = _get_frameworks_and_test_func(obj)
  240. for framework, test_func in framework_to_test_func.items():
  241. if test_func(obj):
  242. return framework_to_py_obj[framework](obj)
  243. # tolist also works on 0d np arrays
  244. if isinstance(obj, np.number):
  245. return obj.tolist()
  246. else:
  247. return obj
  248. def to_numpy(obj):
  249. """
  250. Convert a PyTorch tensor, Numpy array or python list to a Numpy array.
  251. """
  252. framework_to_numpy = {
  253. "pt": lambda obj: obj.detach().cpu().numpy(),
  254. "np": lambda obj: obj,
  255. }
  256. if isinstance(obj, (dict, UserDict)):
  257. return {k: to_numpy(v) for k, v in obj.items()}
  258. elif isinstance(obj, (list, tuple)):
  259. return np.array(obj)
  260. # This gives us a smart order to test the frameworks with the corresponding tests.
  261. framework_to_test_func = _get_frameworks_and_test_func(obj)
  262. for framework, test_func in framework_to_test_func.items():
  263. if test_func(obj):
  264. return framework_to_numpy[framework](obj)
  265. return obj
  266. def safe_load_json_file(json_file: str):
  267. "A helper to load safe config files and raise a proper error message if it wasn't serialized correctly"
  268. try:
  269. with open(json_file, encoding="utf-8") as reader:
  270. text = reader.read()
  271. config_dict = json.loads(text)
  272. except json.JSONDecodeError:
  273. raise OSError(f"It looks like the config file at '{json_file}' is not a valid JSON file.")
  274. return config_dict
  275. class ModelOutput(OrderedDict):
  276. """
  277. Base class for all model outputs as dataclass. Has a `__getitem__` that allows indexing by integer or slice (like a
  278. tuple) or strings (like a dictionary) that will ignore the `None` attributes. Otherwise behaves like a regular
  279. python dictionary.
  280. <Tip warning={true}>
  281. You can't unpack a `ModelOutput` directly. Use the [`~utils.ModelOutput.to_tuple`] method to convert it to a tuple
  282. before.
  283. </Tip>
  284. """
  285. def __init_subclass__(cls) -> None:
  286. """Register subclasses as pytree nodes.
  287. This is necessary to synchronize gradients when using `torch.nn.parallel.DistributedDataParallel` with
  288. `static_graph=True` with modules that output `ModelOutput` subclasses.
  289. """
  290. _register_model_output_pytree_node(cls)
  291. def __init__(self, *args, **kwargs):
  292. super().__init__(*args, **kwargs)
  293. _register_model_output_pytree_node(type(self))
  294. # Subclasses of ModelOutput must use the @dataclass decorator
  295. # This check is done in __init__ because the @dataclass decorator operates after __init_subclass__
  296. # issubclass() would return True for issubclass(ModelOutput, ModelOutput) when False is needed
  297. # Just need to check that the current class is not ModelOutput
  298. is_modeloutput_subclass = self.__class__ != ModelOutput
  299. if is_modeloutput_subclass and not is_dataclass(self):
  300. raise TypeError(
  301. f"{self.__module__}.{self.__class__.__name__} is not a dataclass."
  302. " This is a subclass of ModelOutput and so must use the @dataclass decorator."
  303. )
  304. def __post_init__(self):
  305. """Check the ModelOutput dataclass.
  306. Only occurs if @dataclass decorator has been used.
  307. """
  308. _register_model_output_pytree_node(type(self))
  309. class_fields = fields(self)
  310. # Safety and consistency checks
  311. if not len(class_fields):
  312. raise ValueError(f"{self.__class__.__name__} has no fields.")
  313. if not all(field.default is None for field in class_fields[1:]):
  314. raise ValueError(f"{self.__class__.__name__} should not have more than one required field.")
  315. first_field = getattr(self, class_fields[0].name)
  316. other_fields_are_none = all(getattr(self, field.name) is None for field in class_fields[1:])
  317. if other_fields_are_none and not is_tensor(first_field):
  318. if isinstance(first_field, dict):
  319. iterator = first_field.items()
  320. first_field_iterator = True
  321. else:
  322. try:
  323. iterator = iter(first_field)
  324. first_field_iterator = True
  325. except TypeError:
  326. first_field_iterator = False
  327. # if we provided an iterator as first field and the iterator is a (key, value) iterator
  328. # set the associated fields
  329. if first_field_iterator:
  330. # reset first field to None and remove it from the internal dictionary
  331. setattr(self, class_fields[0].name, None)
  332. super().__delitem__(class_fields[0].name)
  333. for idx, element in enumerate(iterator):
  334. if not isinstance(element, (list, tuple)) or len(element) != 2 or not isinstance(element[0], str):
  335. if idx == 0:
  336. # If we do not have an iterator of key/values, set it as attribute
  337. self[class_fields[0].name] = first_field
  338. else:
  339. # If we have a mixed iterator, raise an error
  340. raise ValueError(
  341. f"Cannot set key/value for {element}. It needs to be a tuple (key, value)."
  342. )
  343. break
  344. setattr(self, element[0], element[1])
  345. if element[1] is not None:
  346. self[element[0]] = element[1]
  347. elif first_field is not None:
  348. self[class_fields[0].name] = first_field
  349. else:
  350. for field in class_fields:
  351. v = getattr(self, field.name)
  352. if v is not None:
  353. self[field.name] = v
  354. def __delitem__(self, *args, **kwargs):
  355. raise Exception(f"You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.")
  356. def setdefault(self, *args, **kwargs):
  357. raise Exception(f"You cannot use ``setdefault`` on a {self.__class__.__name__} instance.")
  358. def pop(self, *args, **kwargs):
  359. raise Exception(f"You cannot use ``pop`` on a {self.__class__.__name__} instance.")
  360. def update(self, *args, **kwargs):
  361. raise Exception(f"You cannot use ``update`` on a {self.__class__.__name__} instance.")
  362. def __getitem__(self, k):
  363. if isinstance(k, str):
  364. inner_dict = dict(self.items())
  365. return inner_dict[k]
  366. else:
  367. return self.to_tuple()[k]
  368. def __setattr__(self, name, value):
  369. field_names = {field.name for field in fields(self)}
  370. if name in field_names and value is not None:
  371. # Don't call self.__setitem__ to avoid recursion errors
  372. super().__setitem__(name, value)
  373. super().__setattr__(name, value)
  374. def __setitem__(self, key, value):
  375. # Will raise a KeyException if needed
  376. super().__setitem__(key, value)
  377. # Don't call self.__setattr__ to avoid recursion errors
  378. super().__setattr__(key, value)
  379. def __reduce__(self):
  380. if not is_dataclass(self):
  381. return super().__reduce__()
  382. callable, _args, *remaining = super().__reduce__()
  383. args = tuple(getattr(self, field.name) for field in fields(self))
  384. return callable, args, *remaining
  385. def to_tuple(self) -> tuple:
  386. """
  387. Convert self to a tuple containing all the attributes/keys that are not `None`.
  388. """
  389. return tuple(self[k] for k in self.keys())
  390. def _model_output_flatten(output: ModelOutput) -> tuple[list[Any], list[str]]:
  391. return list(output.values()), list(output.keys())
  392. def _model_output_unflatten(
  393. values: Iterable[Any],
  394. context: list[str],
  395. output_type: type[ModelOutput] | None = None,
  396. ) -> ModelOutput:
  397. return output_type(**dict(zip(context, values)))
  398. class ExplicitEnum(str, Enum):
  399. """
  400. Enum with more explicit error message for missing values.
  401. """
  402. @classmethod
  403. def _missing_(cls, value):
  404. raise ValueError(
  405. f"{value} is not a valid {cls.__name__}, please select one of {list(cls._value2member_map_.keys())}"
  406. )
  407. class PaddingStrategy(ExplicitEnum):
  408. """
  409. Possible values for the `padding` argument in [`PreTrainedTokenizerBase.__call__`]. Useful for tab-completion in an
  410. IDE.
  411. """
  412. LONGEST = "longest"
  413. MAX_LENGTH = "max_length"
  414. DO_NOT_PAD = "do_not_pad"
  415. class TensorType(ExplicitEnum):
  416. """
  417. Possible values for the `return_tensors` argument in [`PreTrainedTokenizerBase.__call__`]. Useful for
  418. tab-completion in an IDE.
  419. """
  420. PYTORCH = "pt"
  421. NUMPY = "np"
  422. MLX = "mlx"
  423. class ContextManagers:
  424. """
  425. Wrapper for `contextlib.ExitStack` which enters a collection of context managers. Adaptation of `ContextManagers`
  426. in the `fastcore` library.
  427. """
  428. def __init__(self, context_managers: list[AbstractContextManager]):
  429. self.context_managers = context_managers
  430. self.stack = ExitStack()
  431. def __enter__(self):
  432. for context_manager in self.context_managers:
  433. self.stack.enter_context(context_manager)
  434. def __exit__(self, *args, **kwargs):
  435. self.stack.__exit__(*args, **kwargs)
  436. def can_return_loss(model_class):
  437. """
  438. Check if a given model can return loss.
  439. Args:
  440. model_class (`type`): The class of the model.
  441. """
  442. signature = inspect.signature(model_class.forward)
  443. for p in signature.parameters:
  444. if p == "return_loss" and signature.parameters[p].default is True:
  445. return True
  446. return False
  447. def find_labels(model_class):
  448. """
  449. Find the labels used by a given model.
  450. Args:
  451. model_class (`type`): The class of the model.
  452. """
  453. model_name = model_class.__name__
  454. signature = inspect.signature(model_class.forward)
  455. if "QuestionAnswering" in model_name:
  456. return [p for p in signature.parameters if "label" in p or p in ("start_positions", "end_positions")]
  457. else:
  458. return [p for p in signature.parameters if "label" in p]
  459. def flatten_dict(d: MutableMapping, parent_key: str = "", delimiter: str = "."):
  460. """Flatten a nested dict into a single level dict."""
  461. def _flatten_dict(d, parent_key="", delimiter="."):
  462. for k, v in d.items():
  463. key = str(parent_key) + delimiter + str(k) if parent_key else k
  464. if v and isinstance(v, MutableMapping):
  465. yield from flatten_dict(v, key, delimiter=delimiter).items()
  466. else:
  467. yield key, v
  468. return dict(_flatten_dict(d, parent_key, delimiter))
  469. def transpose(array, axes=None):
  470. """
  471. Framework-agnostic version of transpose operation.
  472. """
  473. if is_numpy_array(array):
  474. return np.transpose(array, axes=axes)
  475. elif is_torch_tensor(array):
  476. return array.T if axes is None else array.permute(*axes)
  477. else:
  478. raise ValueError(f"Type not supported for transpose: {type(array)}.")
  479. def reshape(array, newshape):
  480. """
  481. Framework-agnostic version of reshape operation.
  482. """
  483. if is_numpy_array(array):
  484. return np.reshape(array, newshape)
  485. elif is_torch_tensor(array):
  486. return array.reshape(*newshape)
  487. else:
  488. raise ValueError(f"Type not supported for reshape: {type(array)}.")
  489. def squeeze(array, axis=None):
  490. """
  491. Framework-agnostic version of squeeze operation.
  492. """
  493. if is_numpy_array(array):
  494. return np.squeeze(array, axis=axis)
  495. elif is_torch_tensor(array):
  496. return array.squeeze() if axis is None else array.squeeze(dim=axis)
  497. else:
  498. raise ValueError(f"Type not supported for squeeze: {type(array)}.")
  499. def expand_dims(array, axis):
  500. """
  501. Framework-agnostic version of expand_dims operation.
  502. """
  503. if is_numpy_array(array):
  504. return np.expand_dims(array, axis)
  505. elif is_torch_tensor(array):
  506. return array.unsqueeze(dim=axis)
  507. else:
  508. raise ValueError(f"Type not supported for expand_dims: {type(array)}.")
  509. def tensor_size(array):
  510. """
  511. Framework-agnostic version of size operation.
  512. """
  513. if is_numpy_array(array):
  514. return np.size(array)
  515. elif is_torch_tensor(array):
  516. return array.numel()
  517. else:
  518. raise ValueError(f"Type not supported for tensor_size: {type(array)}.")
  519. def torch_int(x):
  520. """
  521. Casts an input to a torch int64 tensor if we are in a tracing context, otherwise to a Python int.
  522. """
  523. if not _is_torch_available:
  524. return int(x)
  525. import torch
  526. return x.to(torch.int64) if torch.jit.is_tracing() and isinstance(x, torch.Tensor) else int(x)
  527. def torch_float(x):
  528. """
  529. Casts an input to a torch float32 tensor if we are in a tracing context, otherwise to a Python float.
  530. """
  531. if not _is_torch_available:
  532. return int(x)
  533. import torch
  534. return x.to(torch.float32) if torch.jit.is_tracing() and isinstance(x, torch.Tensor) else int(x)
  535. def filter_out_non_signature_kwargs(extra: list | None = None):
  536. """
  537. Decorator to filter out named arguments that are not in the function signature.
  538. This decorator ensures that only the keyword arguments that match the function's signature, or are specified in the
  539. `extra` list, are passed to the function. Any additional keyword arguments are filtered out and a warning is issued.
  540. Parameters:
  541. extra (`Optional[list]`, *optional*):
  542. A list of extra keyword argument names that are allowed even if they are not in the function's signature.
  543. Returns:
  544. Callable:
  545. A decorator that wraps the function and filters out invalid keyword arguments.
  546. Example usage:
  547. ```python
  548. @filter_out_non_signature_kwargs(extra=["allowed_extra_arg"])
  549. def my_function(arg1, arg2, **kwargs):
  550. print(arg1, arg2, kwargs)
  551. my_function(arg1=1, arg2=2, allowed_extra_arg=3, invalid_arg=4)
  552. # This will print: 1 2 {"allowed_extra_arg": 3}
  553. # And issue a warning: "The following named arguments are not valid for `my_function` and were ignored: 'invalid_arg'"
  554. ```
  555. """
  556. extra = extra or []
  557. extra_params_to_pass = set(extra)
  558. def decorator(func):
  559. sig = inspect.signature(func)
  560. function_named_args = set(sig.parameters.keys())
  561. valid_kwargs_to_pass = function_named_args.union(extra_params_to_pass)
  562. # Required for better warning message
  563. is_instance_method = "self" in function_named_args
  564. is_class_method = "cls" in function_named_args
  565. # Mark function as decorated
  566. func._filter_out_non_signature_kwargs = True
  567. @wraps(func)
  568. def wrapper(*args, **kwargs):
  569. valid_kwargs = {}
  570. invalid_kwargs = {}
  571. for k, v in kwargs.items():
  572. if k in valid_kwargs_to_pass:
  573. valid_kwargs[k] = v
  574. else:
  575. invalid_kwargs[k] = v
  576. if invalid_kwargs:
  577. invalid_kwargs_names = [f"'{k}'" for k in invalid_kwargs]
  578. invalid_kwargs_names = ", ".join(invalid_kwargs_names)
  579. # Get the class name for better warning message
  580. if is_instance_method:
  581. cls_prefix = args[0].__class__.__name__ + "."
  582. elif is_class_method:
  583. cls_prefix = args[0].__name__ + "."
  584. else:
  585. cls_prefix = ""
  586. warnings.warn(
  587. f"The following named arguments are not valid for `{cls_prefix}{func.__name__}`"
  588. f" and were ignored: {invalid_kwargs_names}",
  589. UserWarning,
  590. stacklevel=2,
  591. )
  592. return func(*args, **valid_kwargs)
  593. return wrapper
  594. return decorator
  595. class TransformersKwargs(TypedDict, total=False):
  596. """
  597. Keyword arguments to be passed to the forward pass of a `PreTrainedModel`.
  598. Attributes:
  599. num_items_in_batch (`Optional[torch.Tensor]`, *optional*):
  600. Number of items in the batch. It is recommended to pass it when you are doing gradient accumulation.
  601. output_hidden_states (`Optional[bool]`, *optional*):
  602. Most of the models support outputting all hidden states computed during the forward pass.
  603. output_attentions (`Optional[bool]`, *optional*):
  604. Turn this on to return the intermediary attention scores.
  605. output_router_logits (`Optional[bool]`, *optional*):
  606. For MoE models, this allows returning the router logits to compute the loss.
  607. cu_seq_lens_q (`torch.LongTensor`, *optional*)
  608. Gets cumulative sequence length for query state.
  609. cu_seq_lens_k (`torch.LongTensor`, *optional*)
  610. Gets cumulative sequence length for key state.
  611. max_length_q (`int`, *optional*):
  612. Maximum sequence length for query state.
  613. max_length_k (`int`, *optional*):
  614. Maximum sequence length for key state.
  615. position_ids (`torch.LongTensor`, *optional*)
  616. Indices of positions of each input sequence tokens.
  617. is_causal (`bool`, *optional*)
  618. Can be set to False to enable bi-directional attention, i.e. use decoder Attention modules as encoders.
  619. """
  620. num_items_in_batch: torch.Tensor | None
  621. output_hidden_states: bool | None
  622. output_attentions: bool | None
  623. output_router_logits: bool | None
  624. cu_seq_lens_q: torch.LongTensor | None
  625. cu_seq_lens_k: torch.LongTensor | None
  626. max_length_q: int | None
  627. max_length_k: int | None
  628. position_ids: torch.LongTensor | None
  629. is_causal: bool | None
  630. def is_timm_config_dict(config_dict: dict[str, Any]) -> bool:
  631. """Checks whether a config dict is a timm config dict."""
  632. return "pretrained_cfg" in config_dict
  633. def is_timm_local_checkpoint(pretrained_model_path: str) -> bool:
  634. """
  635. Checks whether a checkpoint is a timm model checkpoint.
  636. """
  637. if pretrained_model_path is None:
  638. return False
  639. # in case it's Path, not str
  640. pretrained_model_path = str(pretrained_model_path)
  641. is_file = os.path.isfile(pretrained_model_path)
  642. is_dir = os.path.isdir(pretrained_model_path)
  643. # pretrained_model_path is a file
  644. if is_file and pretrained_model_path.endswith(".json"):
  645. with open(pretrained_model_path) as f:
  646. config_dict = json.load(f)
  647. return is_timm_config_dict(config_dict)
  648. # pretrained_model_path is a directory with a config.json
  649. if is_dir and os.path.exists(os.path.join(pretrained_model_path, "config.json")):
  650. with open(os.path.join(pretrained_model_path, "config.json")) as f:
  651. config_dict = json.load(f)
  652. return is_timm_config_dict(config_dict)
  653. return False
  654. def set_attribute_for_modules(module: nn.Module, key: str, value: Any):
  655. """
  656. Set a value to a module and all submodules.
  657. """
  658. setattr(module, key, value)
  659. for submodule in module.children():
  660. set_attribute_for_modules(submodule, key, value)
  661. def del_attribute_from_modules(module: nn.Module, key: str):
  662. """
  663. Delete a value from a module and all submodules.
  664. """
  665. # because we might remove it previously in case it's a shared module, e.g. activation function
  666. if hasattr(module, key):
  667. delattr(module, key)
  668. for submodule in module.children():
  669. del_attribute_from_modules(submodule, key)
  670. def can_return_tuple(func):
  671. """
  672. Decorator to wrap model method, to call output.to_tuple() if return_dict=False passed as a kwarg or
  673. return_dict=False is set in the config.
  674. Note:
  675. output.to_tuple() convert output to tuple skipping all `None` values.
  676. """
  677. @wraps(func)
  678. def wrapper(self, *args, **kwargs):
  679. return_dict = self.config.return_dict if hasattr(self, "config") else True
  680. return_dict_passed = kwargs.pop("return_dict", return_dict)
  681. if return_dict_passed is not None:
  682. return_dict = return_dict_passed
  683. output = func(self, *args, **kwargs)
  684. if not return_dict and not isinstance(output, tuple):
  685. output = output.to_tuple()
  686. return output
  687. return wrapper
  688. def merge_with_config_defaults(func):
  689. """
  690. Decorator using config field (if they exist) as default value for some args and kwargs. Precedence is always
  691. given to the args/kwargs that are explicitly passed.
  692. """
  693. @wraps(func)
  694. def wrapper(self, *args, **kwargs):
  695. args_with_config_defaults = [
  696. "use_cache",
  697. "vision_feature_layer",
  698. "vision_feature_select_strategy",
  699. "vision_aspect_ratio",
  700. ]
  701. for arg_name in args_with_config_defaults:
  702. arg_index = None
  703. if arg_name in func.__code__.co_varnames:
  704. arg_index = func.__code__.co_varnames.index(arg_name) - 1 # -1 for self
  705. if arg_index is not None and len(args) > arg_index and args[arg_index] is not None:
  706. arg_value = args[arg_index]
  707. elif kwargs.get(arg_name) is not None:
  708. arg_value = kwargs[arg_name]
  709. else:
  710. arg_value = getattr(self.config, arg_name, None)
  711. if arg_value is not None:
  712. # Arg-specific handling
  713. if arg_name == "use_cache":
  714. if getattr(self, "gradient_checkpointing", False) and self.training and arg_value:
  715. logger.warning_once(
  716. "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
  717. )
  718. arg_value = False
  719. elif arg_name == "vision_feature_select_strategy":
  720. valid_strategies = ["default", "full"]
  721. if arg_value not in valid_strategies:
  722. raise ValueError(
  723. f"`Unexpected select feature strategy: {arg_value}. Please select from {valid_strategies}."
  724. )
  725. if arg_index is not None and len(args) > arg_index:
  726. args = list(args)
  727. args[arg_index] = arg_value
  728. args = tuple(args)
  729. else:
  730. kwargs[arg_name] = arg_value
  731. # Maybe temporarily overwrite config value to create the correct mask - kwarg takes precedence
  732. is_causal = kwargs.get("is_causal", getattr(self.config, "is_causal", None))
  733. if is_causal is not None:
  734. is_causal_in_config = hasattr(self.config, "is_causal")
  735. if is_causal_in_config:
  736. is_causal_original_value = self.config.is_causal
  737. # Set it to both config and kwargs (it's needed in both, and can come from only 1 of the sources)
  738. self.config.is_causal = is_causal
  739. kwargs["is_causal"] = is_causal
  740. # Call the original forward with the updated kwargs/config
  741. try:
  742. if kwargs.get("debug_io", False):
  743. from ..model_debugging_utils import model_addition_debugger_context
  744. with model_addition_debugger_context(
  745. self, kwargs.get("debug_io_dir", "model_debug"), kwargs.get("prune_layers")
  746. ):
  747. output = func(self, *args, **kwargs)
  748. else:
  749. output = func(self, *args, **kwargs)
  750. # Restore original config value
  751. finally:
  752. if is_causal is not None:
  753. if is_causal_in_config:
  754. self.config.is_causal = is_causal_original_value
  755. else:
  756. del self.config.is_causal
  757. return output
  758. return wrapper
  759. # bc for check_model_inputs:
  760. def check_model_inputs(func):
  761. logger.warning_once("The `check_model_inputs` decorator is deprecated in favor of `merge_with_config_defaults`.")
  762. return merge_with_config_defaults(func)
  763. class GeneralInterface(MutableMapping):
  764. """
  765. Dict-like object keeping track of a class-wide mapping, as well as a local one. Allows to have library-wide
  766. modifications through the class mapping, as well as local modifications in a single file with the local mapping.
  767. """
  768. # Class instance object, so that a call to `register` can be reflected into all other files correctly, even if
  769. # a new instance is created (in order to locally override a given function)
  770. _global_mapping = {}
  771. def __init__(self):
  772. self._local_mapping = {}
  773. def __getitem__(self, key):
  774. # First check if instance has a local override
  775. if key in self._local_mapping:
  776. return self._local_mapping[key]
  777. return self._global_mapping[key]
  778. def __setitem__(self, key, value):
  779. # Allow local update of the default functions without impacting other instances
  780. self._local_mapping.update({key: value})
  781. def __delitem__(self, key):
  782. del self._local_mapping[key]
  783. def __iter__(self):
  784. # Ensure we use all keys, with the overwritten ones on top
  785. return iter({**self._global_mapping, **self._local_mapping})
  786. def __len__(self):
  787. return len(self._global_mapping.keys() | self._local_mapping.keys())
  788. @classmethod
  789. def register(cls, key: str, value: Callable):
  790. cls._global_mapping.update({key: value})
  791. def valid_keys(self) -> list[str]:
  792. return list(self.keys())