_comparison.py 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639
  1. # mypy: allow-untyped-defs
  2. import abc
  3. import cmath
  4. import collections.abc
  5. import contextlib
  6. from collections.abc import Collection, Sequence
  7. from typing import Any, Callable, NoReturn, Optional, Union
  8. from typing_extensions import deprecated
  9. import torch
  10. try:
  11. import numpy as np
  12. HAS_NUMPY = True
  13. except ModuleNotFoundError:
  14. HAS_NUMPY = False
  15. np = None # type: ignore[assignment]
  16. class ErrorMeta(Exception):
  17. """Internal testing exception that makes that carries error metadata."""
  18. def __init__(
  19. self, type: type[Exception], msg: str, *, id: tuple[Any, ...] = ()
  20. ) -> None:
  21. super().__init__(
  22. "If you are a user and see this message during normal operation "
  23. "please file an issue at https://github.com/pytorch/pytorch/issues. "
  24. "If you are a developer and working on the comparison functions, please `raise ErrorMeta.to_error()` "
  25. "for user facing errors."
  26. )
  27. self.type = type
  28. self.msg = msg
  29. self.id = id
  30. def to_error(
  31. self, msg: Optional[Union[str, Callable[[str], str]]] = None
  32. ) -> Exception:
  33. if not isinstance(msg, str):
  34. generated_msg = self.msg
  35. if self.id:
  36. generated_msg += f"\n\nThe failure occurred for item {''.join(str([item]) for item in self.id)}"
  37. msg = msg(generated_msg) if callable(msg) else generated_msg
  38. return self.type(msg)
  39. # Some analysis of tolerance by logging tests from test_torch.py can be found in
  40. # https://github.com/pytorch/pytorch/pull/32538.
  41. # {dtype: (rtol, atol)}
  42. _DTYPE_PRECISIONS = {
  43. torch.float16: (0.001, 1e-5),
  44. torch.bfloat16: (0.016, 1e-5),
  45. torch.float32: (1.3e-6, 1e-5),
  46. torch.float64: (1e-7, 1e-7),
  47. torch.complex32: (0.001, 1e-5),
  48. torch.complex64: (1.3e-6, 1e-5),
  49. torch.complex128: (1e-7, 1e-7),
  50. }
  51. # The default tolerances of torch.float32 are used for quantized dtypes, because quantized tensors are compared in
  52. # their dequantized and floating point representation. For more details see `TensorLikePair._compare_quantized_values`
  53. _DTYPE_PRECISIONS.update(
  54. dict.fromkeys(
  55. (torch.quint8, torch.quint2x4, torch.quint4x2, torch.qint8, torch.qint32),
  56. _DTYPE_PRECISIONS[torch.float32],
  57. )
  58. )
  59. def default_tolerances(
  60. *inputs: Union[torch.Tensor, torch.dtype],
  61. dtype_precisions: Optional[dict[torch.dtype, tuple[float, float]]] = None,
  62. ) -> tuple[float, float]:
  63. """Returns the default absolute and relative testing tolerances for a set of inputs based on the dtype.
  64. See :func:`assert_close` for a table of the default tolerance for each dtype.
  65. Returns:
  66. (Tuple[float, float]): Loosest tolerances of all input dtypes.
  67. """
  68. dtypes = []
  69. for input in inputs:
  70. if isinstance(input, torch.Tensor):
  71. dtypes.append(input.dtype)
  72. elif isinstance(input, torch.dtype):
  73. dtypes.append(input)
  74. else:
  75. raise TypeError(
  76. f"Expected a torch.Tensor or a torch.dtype, but got {type(input)} instead."
  77. )
  78. dtype_precisions = dtype_precisions or _DTYPE_PRECISIONS
  79. rtols, atols = zip(*[dtype_precisions.get(dtype, (0.0, 0.0)) for dtype in dtypes])
  80. return max(rtols), max(atols)
  81. def get_tolerances(
  82. *inputs: Union[torch.Tensor, torch.dtype],
  83. rtol: Optional[float],
  84. atol: Optional[float],
  85. id: tuple[Any, ...] = (),
  86. ) -> tuple[float, float]:
  87. """Gets absolute and relative to be used for numeric comparisons.
  88. If both ``rtol`` and ``atol`` are specified, this is a no-op. If both are not specified, the return value of
  89. :func:`default_tolerances` is used.
  90. Raises:
  91. ErrorMeta: With :class:`ValueError`, if only ``rtol`` or ``atol`` is specified.
  92. Returns:
  93. (Tuple[float, float]): Valid absolute and relative tolerances.
  94. """
  95. if (rtol is None) ^ (atol is None):
  96. # We require both tolerance to be omitted or specified, because specifying only one might lead to surprising
  97. # results. Imagine setting atol=0.0 and the tensors still match because rtol>0.0.
  98. raise ErrorMeta(
  99. ValueError,
  100. f"Both 'rtol' and 'atol' must be either specified or omitted, "
  101. f"but got no {'rtol' if rtol is None else 'atol'}.",
  102. id=id,
  103. )
  104. elif rtol is not None and atol is not None:
  105. return rtol, atol
  106. else:
  107. return default_tolerances(*inputs)
  108. def _make_bitwise_mismatch_msg(
  109. *,
  110. default_identifier: str,
  111. identifier: Optional[Union[str, Callable[[str], str]]] = None,
  112. extra: Optional[str] = None,
  113. first_mismatch_idx: Optional[tuple[int]] = None,
  114. ):
  115. """Makes a mismatch error message for bitwise values.
  116. Args:
  117. default_identifier (str): Default description of the compared values, e.g. "Tensor-likes".
  118. identifier (Optional[Union[str, Callable[[str], str]]]): Optional identifier that overrides
  119. ``default_identifier``. Can be passed as callable in which case it will be called with
  120. ``default_identifier`` to create the description at runtime.
  121. extra (Optional[str]): Extra information to be placed after the message header and the mismatch statistics.
  122. first_mismatch_idx (Optional[tuple[int]]): the index of the first mismatch, for each dimension.
  123. """
  124. if identifier is None:
  125. identifier = default_identifier
  126. elif callable(identifier):
  127. identifier = identifier(default_identifier)
  128. msg = f"{identifier} are not 'equal'!\n\n"
  129. if extra:
  130. msg += f"{extra.strip()}\n"
  131. if first_mismatch_idx is not None:
  132. msg += f"The first mismatched element is at index {first_mismatch_idx}.\n"
  133. return msg.strip()
  134. def _make_mismatch_msg(
  135. *,
  136. default_identifier: str,
  137. identifier: Optional[Union[str, Callable[[str], str]]] = None,
  138. extra: Optional[str] = None,
  139. abs_diff: float,
  140. abs_diff_idx: Optional[Union[int, tuple[int, ...]]] = None,
  141. atol: float,
  142. rel_diff: float,
  143. rel_diff_idx: Optional[Union[int, tuple[int, ...]]] = None,
  144. rtol: float,
  145. ) -> str:
  146. """Makes a mismatch error message for numeric values.
  147. Args:
  148. default_identifier (str): Default description of the compared values, e.g. "Tensor-likes".
  149. identifier (Optional[Union[str, Callable[[str], str]]]): Optional identifier that overrides
  150. ``default_identifier``. Can be passed as callable in which case it will be called with
  151. ``default_identifier`` to create the description at runtime.
  152. extra (Optional[str]): Extra information to be placed after the message header and the mismatch statistics.
  153. abs_diff (float): Absolute difference.
  154. abs_diff_idx (Optional[Union[int, Tuple[int, ...]]]): Optional index of the absolute difference.
  155. atol (float): Allowed absolute tolerance. Will only be added to mismatch statistics if it or ``rtol`` are
  156. ``> 0``.
  157. rel_diff (float): Relative difference.
  158. rel_diff_idx (Optional[Union[int, Tuple[int, ...]]]): Optional index of the relative difference.
  159. rtol (float): Allowed relative tolerance. Will only be added to mismatch statistics if it or ``atol`` are
  160. ``> 0``.
  161. """
  162. equality = rtol == 0 and atol == 0
  163. def make_diff_msg(
  164. *,
  165. type: str,
  166. diff: float,
  167. idx: Optional[Union[int, tuple[int, ...]]],
  168. tol: float,
  169. ) -> str:
  170. if idx is None:
  171. msg = f"{type.title()} difference: {diff}"
  172. else:
  173. msg = f"Greatest {type} difference: {diff} at index {idx}"
  174. if not equality:
  175. msg += f" (up to {tol} allowed)"
  176. return msg + "\n"
  177. if identifier is None:
  178. identifier = default_identifier
  179. elif callable(identifier):
  180. identifier = identifier(default_identifier)
  181. msg = f"{identifier} are not {'equal' if equality else 'close'}!\n\n"
  182. if extra:
  183. msg += f"{extra.strip()}\n"
  184. msg += make_diff_msg(type="absolute", diff=abs_diff, idx=abs_diff_idx, tol=atol)
  185. msg += make_diff_msg(type="relative", diff=rel_diff, idx=rel_diff_idx, tol=rtol)
  186. return msg.strip()
  187. def make_scalar_mismatch_msg(
  188. actual: Union[bool, int, float, complex],
  189. expected: Union[bool, int, float, complex],
  190. *,
  191. rtol: float,
  192. atol: float,
  193. identifier: Optional[Union[str, Callable[[str], str]]] = None,
  194. ) -> str:
  195. """Makes a mismatch error message for scalars.
  196. Args:
  197. actual (Union[bool, int, float, complex]): Actual scalar.
  198. expected (Union[bool, int, float, complex]): Expected scalar.
  199. rtol (float): Relative tolerance.
  200. atol (float): Absolute tolerance.
  201. identifier (Optional[Union[str, Callable[[str], str]]]): Optional description for the scalars. Can be passed
  202. as callable in which case it will be called by the default value to create the description at runtime.
  203. Defaults to "Scalars".
  204. """
  205. abs_diff = abs(actual - expected)
  206. rel_diff = float("inf") if expected == 0 else abs_diff / abs(expected)
  207. return _make_mismatch_msg(
  208. default_identifier="Scalars",
  209. identifier=identifier,
  210. extra=f"Expected {expected} but got {actual}.",
  211. abs_diff=abs_diff,
  212. atol=atol,
  213. rel_diff=rel_diff,
  214. rtol=rtol,
  215. )
  216. def make_tensor_mismatch_msg(
  217. actual: torch.Tensor,
  218. expected: torch.Tensor,
  219. matches: torch.Tensor,
  220. *,
  221. rtol: float,
  222. atol: float,
  223. identifier: Optional[Union[str, Callable[[str], str]]] = None,
  224. ):
  225. """Makes a mismatch error message for tensors.
  226. Args:
  227. actual (torch.Tensor): Actual tensor.
  228. expected (torch.Tensor): Expected tensor.
  229. matches (torch.Tensor): Boolean mask of the same shape as ``actual`` and ``expected`` that indicates the
  230. location of matches.
  231. rtol (float): Relative tolerance.
  232. atol (float): Absolute tolerance.
  233. identifier (Optional[Union[str, Callable[[str], str]]]): Optional description for the tensors. Can be passed
  234. as callable in which case it will be called by the default value to create the description at runtime.
  235. Defaults to "Tensor-likes".
  236. """
  237. def unravel_flat_index(flat_index: int) -> tuple[int, ...]:
  238. if not matches.shape:
  239. return ()
  240. inverse_index = []
  241. for size in matches.shape[::-1]:
  242. div, mod = divmod(flat_index, size)
  243. flat_index = div
  244. inverse_index.append(mod)
  245. return tuple(inverse_index[::-1])
  246. number_of_elements = matches.numel()
  247. total_mismatches = number_of_elements - int(torch.sum(matches))
  248. extra = (
  249. f"Mismatched elements: {total_mismatches} / {number_of_elements} "
  250. f"({total_mismatches / number_of_elements:.1%})"
  251. )
  252. if actual.dtype.is_floating_point and actual.dtype.itemsize == 1:
  253. # skip checking for max_abs_diff and max_rel_diff for float8-like values
  254. first_mismatch_idx = tuple(torch.nonzero(~matches, as_tuple=False)[0].tolist())
  255. return _make_bitwise_mismatch_msg(
  256. default_identifier="Tensor-likes",
  257. identifier=identifier,
  258. extra=extra,
  259. first_mismatch_idx=first_mismatch_idx,
  260. )
  261. actual_flat = actual.flatten()
  262. expected_flat = expected.flatten()
  263. matches_flat = matches.flatten()
  264. if not actual.dtype.is_floating_point and not actual.dtype.is_complex:
  265. # TODO: Instead of always upcasting to int64, it would be sufficient to cast to the next higher dtype to avoid
  266. # overflow
  267. actual_flat = actual_flat.to(torch.int64)
  268. expected_flat = expected_flat.to(torch.int64)
  269. abs_diff = torch.abs(actual_flat - expected_flat)
  270. # Ensure that only mismatches are used for the max_abs_diff computation
  271. abs_diff[matches_flat] = 0
  272. max_abs_diff, max_abs_diff_flat_idx = torch.max(abs_diff, 0)
  273. rel_diff = abs_diff / torch.abs(expected_flat)
  274. # Ensure that only mismatches are used for the max_rel_diff computation
  275. rel_diff[matches_flat] = 0
  276. max_rel_diff, max_rel_diff_flat_idx = torch.max(rel_diff, 0)
  277. return _make_mismatch_msg(
  278. default_identifier="Tensor-likes",
  279. identifier=identifier,
  280. extra=extra,
  281. abs_diff=max_abs_diff.item(),
  282. abs_diff_idx=unravel_flat_index(int(max_abs_diff_flat_idx)),
  283. atol=atol,
  284. rel_diff=max_rel_diff.item(),
  285. rel_diff_idx=unravel_flat_index(int(max_rel_diff_flat_idx)),
  286. rtol=rtol,
  287. )
  288. class UnsupportedInputs(Exception): # noqa: B903
  289. """Exception to be raised during the construction of a :class:`Pair` in case it doesn't support the inputs."""
  290. class Pair(abc.ABC):
  291. """ABC for all comparison pairs to be used in conjunction with :func:`assert_equal`.
  292. Each subclass needs to overwrite :meth:`Pair.compare` that performs the actual comparison.
  293. Each pair receives **all** options, so select the ones applicable for the subclass and forward the rest to the
  294. super class. Raising an :class:`UnsupportedInputs` during constructions indicates that the pair is not able to
  295. handle the inputs and the next pair type will be tried.
  296. All other errors should be raised as :class:`ErrorMeta`. After the instantiation, :meth:`Pair._make_error_meta` can
  297. be used to automatically handle overwriting the message with a user supplied one and id handling.
  298. """
  299. def __init__(
  300. self,
  301. actual: Any,
  302. expected: Any,
  303. *,
  304. id: tuple[Any, ...] = (),
  305. **unknown_parameters: Any,
  306. ) -> None:
  307. self.actual = actual
  308. self.expected = expected
  309. self.id = id
  310. self._unknown_parameters = unknown_parameters
  311. @staticmethod
  312. def _inputs_not_supported() -> NoReturn:
  313. raise UnsupportedInputs
  314. @staticmethod
  315. def _check_inputs_isinstance(*inputs: Any, cls: Union[type, tuple[type, ...]]):
  316. """Checks if all inputs are instances of a given class and raise :class:`UnsupportedInputs` otherwise."""
  317. if not all(isinstance(input, cls) for input in inputs):
  318. Pair._inputs_not_supported()
  319. def _fail(
  320. self, type: type[Exception], msg: str, *, id: tuple[Any, ...] = ()
  321. ) -> NoReturn:
  322. """Raises an :class:`ErrorMeta` from a given exception type and message and the stored id.
  323. .. warning::
  324. If you use this before the ``super().__init__(...)`` call in the constructor, you have to pass the ``id``
  325. explicitly.
  326. """
  327. raise ErrorMeta(type, msg, id=self.id if not id and hasattr(self, "id") else id)
  328. @abc.abstractmethod
  329. def compare(self) -> None:
  330. """Compares the inputs and raises an :class`ErrorMeta` in case they mismatch."""
  331. def extra_repr(self) -> Sequence[Union[str, tuple[str, Any]]]:
  332. """Returns extra information that will be included in the representation.
  333. Should be overwritten by all subclasses that use additional options. The representation of the object will only
  334. be surfaced in case we encounter an unexpected error and thus should help debug the issue. Can be a sequence of
  335. key-value-pairs or attribute names.
  336. """
  337. return []
  338. def __repr__(self) -> str:
  339. head = f"{type(self).__name__}("
  340. tail = ")"
  341. body = [
  342. f" {name}={value!s},"
  343. for name, value in [
  344. ("id", self.id),
  345. ("actual", self.actual),
  346. ("expected", self.expected),
  347. *[
  348. (extra, getattr(self, extra)) if isinstance(extra, str) else extra
  349. for extra in self.extra_repr()
  350. ],
  351. ]
  352. ]
  353. return "\n".join((head, *body, *tail))
  354. class ObjectPair(Pair):
  355. """Pair for any type of inputs that will be compared with the `==` operator.
  356. .. note::
  357. Since this will instantiate for any kind of inputs, it should only be used as fallback after all other pairs
  358. couldn't handle the inputs.
  359. """
  360. def compare(self) -> None:
  361. try:
  362. equal = self.actual == self.expected
  363. except Exception as error:
  364. # We are not using `self._raise_error_meta` here since we need the exception chaining
  365. raise ErrorMeta(
  366. ValueError,
  367. f"{self.actual} == {self.expected} failed with:\n{error}.",
  368. id=self.id,
  369. ) from error
  370. if not equal:
  371. self._fail(AssertionError, f"{self.actual} != {self.expected}")
  372. class NonePair(Pair):
  373. """Pair for ``None`` inputs."""
  374. def __init__(self, actual: Any, expected: Any, **other_parameters: Any) -> None:
  375. if not (actual is None or expected is None):
  376. self._inputs_not_supported()
  377. super().__init__(actual, expected, **other_parameters)
  378. def compare(self) -> None:
  379. if not (self.actual is None and self.expected is None):
  380. self._fail(
  381. AssertionError, f"None mismatch: {self.actual} is not {self.expected}"
  382. )
  383. class BooleanPair(Pair):
  384. """Pair for :class:`bool` inputs.
  385. .. note::
  386. If ``numpy`` is available, also handles :class:`numpy.bool_` inputs.
  387. """
  388. def __init__(
  389. self,
  390. actual: Any,
  391. expected: Any,
  392. *,
  393. id: tuple[Any, ...],
  394. **other_parameters: Any,
  395. ) -> None:
  396. actual, expected = self._process_inputs(actual, expected, id=id)
  397. super().__init__(actual, expected, **other_parameters)
  398. @property
  399. def _supported_types(self) -> tuple[type, ...]:
  400. cls: list[type] = [bool]
  401. if HAS_NUMPY:
  402. cls.append(np.bool_)
  403. return tuple(cls)
  404. def _process_inputs(
  405. self, actual: Any, expected: Any, *, id: tuple[Any, ...]
  406. ) -> tuple[bool, bool]:
  407. self._check_inputs_isinstance(actual, expected, cls=self._supported_types)
  408. actual, expected = (
  409. self._to_bool(bool_like, id=id) for bool_like in (actual, expected)
  410. )
  411. return actual, expected
  412. def _to_bool(self, bool_like: Any, *, id: tuple[Any, ...]) -> bool:
  413. if isinstance(bool_like, bool):
  414. return bool_like
  415. elif isinstance(bool_like, np.bool_):
  416. return bool_like.item()
  417. else:
  418. raise ErrorMeta(
  419. TypeError, f"Unknown boolean type {type(bool_like)}.", id=id
  420. )
  421. def compare(self) -> None:
  422. if self.actual is not self.expected:
  423. self._fail(
  424. AssertionError,
  425. f"Booleans mismatch: {self.actual} is not {self.expected}",
  426. )
  427. class NumberPair(Pair):
  428. """Pair for Python number (:class:`int`, :class:`float`, and :class:`complex`) inputs.
  429. .. note::
  430. If ``numpy`` is available, also handles :class:`numpy.number` inputs.
  431. Kwargs:
  432. rtol (Optional[float]): Relative tolerance. If specified ``atol`` must also be specified. If omitted, default
  433. values based on the type are selected with the below table.
  434. atol (Optional[float]): Absolute tolerance. If specified ``rtol`` must also be specified. If omitted, default
  435. values based on the type are selected with the below table.
  436. equal_nan (bool): If ``True``, two ``NaN`` values are considered equal. Defaults to ``False``.
  437. check_dtype (bool): If ``True``, the type of the inputs will be checked for equality. Defaults to ``False``.
  438. The following table displays correspondence between Python number type and the ``torch.dtype``'s. See
  439. :func:`assert_close` for the corresponding tolerances.
  440. +------------------+-------------------------------+
  441. | ``type`` | corresponding ``torch.dtype`` |
  442. +==================+===============================+
  443. | :class:`int` | :attr:`~torch.int64` |
  444. +------------------+-------------------------------+
  445. | :class:`float` | :attr:`~torch.float64` |
  446. +------------------+-------------------------------+
  447. | :class:`complex` | :attr:`~torch.complex64` |
  448. +------------------+-------------------------------+
  449. """
  450. _TYPE_TO_DTYPE = {
  451. int: torch.int64,
  452. float: torch.float64,
  453. complex: torch.complex128,
  454. }
  455. _NUMBER_TYPES = tuple(_TYPE_TO_DTYPE.keys())
  456. def __init__(
  457. self,
  458. actual: Any,
  459. expected: Any,
  460. *,
  461. id: tuple[Any, ...] = (),
  462. rtol: Optional[float] = None,
  463. atol: Optional[float] = None,
  464. equal_nan: bool = False,
  465. check_dtype: bool = False,
  466. **other_parameters: Any,
  467. ) -> None:
  468. actual, expected = self._process_inputs(actual, expected, id=id)
  469. super().__init__(actual, expected, id=id, **other_parameters)
  470. self.rtol, self.atol = get_tolerances(
  471. *[self._TYPE_TO_DTYPE[type(input)] for input in (actual, expected)],
  472. rtol=rtol,
  473. atol=atol,
  474. id=id,
  475. )
  476. self.equal_nan = equal_nan
  477. self.check_dtype = check_dtype
  478. @property
  479. def _supported_types(self) -> tuple[type, ...]:
  480. cls = list(self._NUMBER_TYPES)
  481. if HAS_NUMPY:
  482. cls.append(np.number)
  483. return tuple(cls)
  484. def _process_inputs(
  485. self, actual: Any, expected: Any, *, id: tuple[Any, ...]
  486. ) -> tuple[Union[int, float, complex], Union[int, float, complex]]:
  487. self._check_inputs_isinstance(actual, expected, cls=self._supported_types)
  488. actual, expected = (
  489. self._to_number(number_like, id=id) for number_like in (actual, expected)
  490. )
  491. return actual, expected
  492. def _to_number(
  493. self, number_like: Any, *, id: tuple[Any, ...]
  494. ) -> Union[int, float, complex]:
  495. if HAS_NUMPY and isinstance(number_like, np.number):
  496. return number_like.item()
  497. elif isinstance(number_like, self._NUMBER_TYPES):
  498. return number_like # type: ignore[return-value]
  499. else:
  500. raise ErrorMeta(
  501. TypeError, f"Unknown number type {type(number_like)}.", id=id
  502. )
  503. def compare(self) -> None:
  504. if self.check_dtype and type(self.actual) is not type(self.expected):
  505. self._fail(
  506. AssertionError,
  507. f"The (d)types do not match: {type(self.actual)} != {type(self.expected)}.",
  508. )
  509. if self.actual == self.expected:
  510. return
  511. if self.equal_nan and cmath.isnan(self.actual) and cmath.isnan(self.expected):
  512. return
  513. abs_diff = abs(self.actual - self.expected)
  514. tolerance = self.atol + self.rtol * abs(self.expected)
  515. if cmath.isfinite(abs_diff) and abs_diff <= tolerance:
  516. return
  517. self._fail(
  518. AssertionError,
  519. make_scalar_mismatch_msg(
  520. self.actual, self.expected, rtol=self.rtol, atol=self.atol
  521. ),
  522. )
  523. def extra_repr(self) -> Sequence[str]:
  524. return (
  525. "rtol",
  526. "atol",
  527. "equal_nan",
  528. "check_dtype",
  529. )
  530. class TensorLikePair(Pair):
  531. """Pair for :class:`torch.Tensor`-like inputs.
  532. Kwargs:
  533. allow_subclasses (bool):
  534. rtol (Optional[float]): Relative tolerance. If specified ``atol`` must also be specified. If omitted, default
  535. values based on the type are selected. See :func:assert_close: for details.
  536. atol (Optional[float]): Absolute tolerance. If specified ``rtol`` must also be specified. If omitted, default
  537. values based on the type are selected. See :func:assert_close: for details.
  538. equal_nan (bool): If ``True``, two ``NaN`` values are considered equal. Defaults to ``False``.
  539. check_device (bool): If ``True`` (default), asserts that corresponding tensors are on the same
  540. :attr:`~torch.Tensor.device`. If this check is disabled, tensors on different
  541. :attr:`~torch.Tensor.device`'s are moved to the CPU before being compared.
  542. check_dtype (bool): If ``True`` (default), asserts that corresponding tensors have the same ``dtype``. If this
  543. check is disabled, tensors with different ``dtype``'s are promoted to a common ``dtype`` (according to
  544. :func:`torch.promote_types`) before being compared.
  545. check_layout (bool): If ``True`` (default), asserts that corresponding tensors have the same ``layout``. If this
  546. check is disabled, tensors with different ``layout``'s are converted to strided tensors before being
  547. compared.
  548. check_stride (bool): If ``True`` and corresponding tensors are strided, asserts that they have the same stride.
  549. """
  550. def __init__(
  551. self,
  552. actual: Any,
  553. expected: Any,
  554. *,
  555. id: tuple[Any, ...] = (),
  556. allow_subclasses: bool = True,
  557. rtol: Optional[float] = None,
  558. atol: Optional[float] = None,
  559. equal_nan: bool = False,
  560. check_device: bool = True,
  561. check_dtype: bool = True,
  562. check_layout: bool = True,
  563. check_stride: bool = False,
  564. **other_parameters: Any,
  565. ):
  566. actual, expected = self._process_inputs(
  567. actual, expected, id=id, allow_subclasses=allow_subclasses
  568. )
  569. super().__init__(actual, expected, id=id, **other_parameters)
  570. self.rtol, self.atol = get_tolerances(
  571. actual, expected, rtol=rtol, atol=atol, id=self.id
  572. )
  573. self.equal_nan = equal_nan
  574. self.check_device = check_device
  575. self.check_dtype = check_dtype
  576. self.check_layout = check_layout
  577. self.check_stride = check_stride
  578. def _process_inputs(
  579. self, actual: Any, expected: Any, *, id: tuple[Any, ...], allow_subclasses: bool
  580. ) -> tuple[torch.Tensor, torch.Tensor]:
  581. directly_related = isinstance(actual, type(expected)) or isinstance(
  582. expected, type(actual)
  583. )
  584. if not directly_related:
  585. self._inputs_not_supported()
  586. if not allow_subclasses and type(actual) is not type(expected):
  587. self._inputs_not_supported()
  588. actual, expected = (self._to_tensor(input) for input in (actual, expected))
  589. for tensor in (actual, expected):
  590. self._check_supported(tensor, id=id)
  591. return actual, expected
  592. def _to_tensor(self, tensor_like: Any) -> torch.Tensor:
  593. if isinstance(tensor_like, torch.Tensor):
  594. return tensor_like
  595. try:
  596. return torch.as_tensor(tensor_like)
  597. except Exception:
  598. self._inputs_not_supported()
  599. def _check_supported(self, tensor: torch.Tensor, *, id: tuple[Any, ...]) -> None:
  600. if tensor.layout not in {
  601. torch.strided,
  602. torch.jagged,
  603. torch.sparse_coo,
  604. torch.sparse_csr,
  605. torch.sparse_csc,
  606. torch.sparse_bsr,
  607. torch.sparse_bsc,
  608. }:
  609. raise ErrorMeta(
  610. ValueError, f"Unsupported tensor layout {tensor.layout}", id=id
  611. )
  612. def compare(self) -> None:
  613. actual, expected = self.actual, self.expected
  614. self._compare_attributes(actual, expected)
  615. if any(input.device.type == "meta" for input in (actual, expected)):
  616. return
  617. actual, expected = self._equalize_attributes(actual, expected)
  618. self._compare_values(actual, expected)
  619. def _compare_attributes(
  620. self,
  621. actual: torch.Tensor,
  622. expected: torch.Tensor,
  623. ) -> None:
  624. """Checks if the attributes of two tensors match.
  625. Always checks
  626. - the :attr:`~torch.Tensor.shape`,
  627. - whether both inputs are quantized or not,
  628. - and if they use the same quantization scheme.
  629. Checks for
  630. - :attr:`~torch.Tensor.layout`,
  631. - :meth:`~torch.Tensor.stride`,
  632. - :attr:`~torch.Tensor.device`, and
  633. - :attr:`~torch.Tensor.dtype`
  634. are optional and can be disabled through the corresponding ``check_*`` flag during construction of the pair.
  635. """
  636. def raise_mismatch_error(
  637. attribute_name: str, actual_value: Any, expected_value: Any
  638. ) -> NoReturn:
  639. self._fail(
  640. AssertionError,
  641. f"The values for attribute '{attribute_name}' do not match: {actual_value} != {expected_value}.",
  642. )
  643. if actual.shape != expected.shape:
  644. raise_mismatch_error("shape", actual.shape, expected.shape)
  645. if actual.is_quantized != expected.is_quantized:
  646. raise_mismatch_error(
  647. "is_quantized", actual.is_quantized, expected.is_quantized
  648. )
  649. elif actual.is_quantized and actual.qscheme() != expected.qscheme():
  650. raise_mismatch_error("qscheme()", actual.qscheme(), expected.qscheme())
  651. if actual.layout != expected.layout:
  652. if self.check_layout:
  653. raise_mismatch_error("layout", actual.layout, expected.layout)
  654. elif (
  655. actual.layout == torch.strided
  656. and self.check_stride
  657. and actual.stride() != expected.stride()
  658. ):
  659. raise_mismatch_error("stride()", actual.stride(), expected.stride())
  660. if self.check_device and actual.device != expected.device:
  661. raise_mismatch_error("device", actual.device, expected.device)
  662. if self.check_dtype and actual.dtype != expected.dtype:
  663. raise_mismatch_error("dtype", actual.dtype, expected.dtype)
  664. def _equalize_attributes(
  665. self, actual: torch.Tensor, expected: torch.Tensor
  666. ) -> tuple[torch.Tensor, torch.Tensor]:
  667. """Equalizes some attributes of two tensors for value comparison.
  668. If ``actual`` and ``expected`` are ...
  669. - ... not on the same :attr:`~torch.Tensor.device`, they are moved CPU memory.
  670. - ... not of the same ``dtype``, they are promoted to a common ``dtype`` (according to
  671. :func:`torch.promote_types`).
  672. - ... not of the same ``layout``, they are converted to strided tensors.
  673. Args:
  674. actual (Tensor): Actual tensor.
  675. expected (Tensor): Expected tensor.
  676. Returns:
  677. (Tuple[Tensor, Tensor]): Equalized tensors.
  678. """
  679. # The comparison logic uses operators currently not supported by the MPS backends.
  680. # See https://github.com/pytorch/pytorch/issues/77144 for details.
  681. # TODO: Remove this conversion as soon as all operations are supported natively by the MPS backend
  682. if actual.is_mps or expected.is_mps: # type: ignore[attr-defined]
  683. actual = actual.cpu()
  684. expected = expected.cpu()
  685. if actual.device != expected.device:
  686. actual = actual.cpu()
  687. expected = expected.cpu()
  688. if actual.dtype != expected.dtype:
  689. actual_dtype = actual.dtype
  690. expected_dtype = expected.dtype
  691. # For uint64, this is not sound in general, which is why promote_types doesn't
  692. # allow it, but for easy testing, we're unlikely to get confused
  693. # by large uint64 overflowing into negative int64
  694. if actual_dtype in [torch.uint64, torch.uint32, torch.uint16]:
  695. actual_dtype = torch.int64
  696. if expected_dtype in [torch.uint64, torch.uint32, torch.uint16]:
  697. expected_dtype = torch.int64
  698. dtype = torch.promote_types(actual_dtype, expected_dtype)
  699. actual = actual.to(dtype)
  700. expected = expected.to(dtype)
  701. if actual.layout != expected.layout:
  702. # These checks are needed, since Tensor.to_dense() fails on tensors that are already strided
  703. actual = actual.to_dense() if actual.layout != torch.strided else actual
  704. expected = (
  705. expected.to_dense() if expected.layout != torch.strided else expected
  706. )
  707. return actual, expected
  708. def _compare_values(self, actual: torch.Tensor, expected: torch.Tensor) -> None:
  709. if actual.is_quantized:
  710. compare_fn = self._compare_quantized_values
  711. elif actual.is_sparse:
  712. compare_fn = self._compare_sparse_coo_values
  713. elif actual.layout in {
  714. torch.sparse_csr,
  715. torch.sparse_csc,
  716. torch.sparse_bsr,
  717. torch.sparse_bsc,
  718. }:
  719. compare_fn = self._compare_sparse_compressed_values
  720. elif actual.layout == torch.jagged:
  721. actual, expected = actual.values(), expected.values()
  722. compare_fn = self._compare_regular_values_close
  723. elif actual.dtype.is_floating_point and actual.dtype.itemsize == 1:
  724. def bitwise_comp(
  725. actual: torch.Tensor,
  726. expected: torch.Tensor,
  727. *,
  728. rtol: float,
  729. atol: float,
  730. equal_nan: bool,
  731. identifier: Optional[Union[str, Callable[[str], str]]] = None,
  732. ) -> None:
  733. if rtol != 0.0 or atol != 0.0:
  734. raise ErrorMeta(
  735. AssertionError,
  736. f"Rtol={rtol} and atol={atol} are not supported for bitwise comparison of low"
  737. " dimensional floats. Please use rtol=0.0 and atol=0.0.",
  738. )
  739. return self._compare_regular_values_close(
  740. actual,
  741. expected,
  742. rtol=rtol,
  743. atol=atol,
  744. equal_nan=equal_nan,
  745. identifier=identifier,
  746. )
  747. compare_fn = bitwise_comp
  748. else:
  749. compare_fn = self._compare_regular_values_close
  750. compare_fn(
  751. actual, expected, rtol=self.rtol, atol=self.atol, equal_nan=self.equal_nan
  752. )
  753. def _compare_quantized_values(
  754. self,
  755. actual: torch.Tensor,
  756. expected: torch.Tensor,
  757. *,
  758. rtol: float,
  759. atol: float,
  760. equal_nan: bool,
  761. ) -> None:
  762. """Compares quantized tensors by comparing the :meth:`~torch.Tensor.dequantize`'d variants for closeness.
  763. .. note::
  764. A detailed discussion about why only the dequantized variant is checked for closeness rather than checking
  765. the individual quantization parameters for closeness and the integer representation for equality can be
  766. found in https://github.com/pytorch/pytorch/issues/68548.
  767. """
  768. return self._compare_regular_values_close(
  769. actual.dequantize(),
  770. expected.dequantize(),
  771. rtol=rtol,
  772. atol=atol,
  773. equal_nan=equal_nan,
  774. identifier=lambda default_identifier: f"Quantized {default_identifier.lower()}",
  775. )
  776. def _compare_sparse_coo_values(
  777. self,
  778. actual: torch.Tensor,
  779. expected: torch.Tensor,
  780. *,
  781. rtol: float,
  782. atol: float,
  783. equal_nan: bool,
  784. ) -> None:
  785. """Compares sparse COO tensors by comparing
  786. - the number of sparse dimensions,
  787. - the number of non-zero elements (nnz) for equality,
  788. - the indices for equality, and
  789. - the values for closeness.
  790. """
  791. if actual.sparse_dim() != expected.sparse_dim():
  792. self._fail(
  793. AssertionError,
  794. (
  795. f"The number of sparse dimensions in sparse COO tensors does not match: "
  796. f"{actual.sparse_dim()} != {expected.sparse_dim()}"
  797. ),
  798. )
  799. if actual._nnz() != expected._nnz():
  800. self._fail(
  801. AssertionError,
  802. (
  803. f"The number of specified values in sparse COO tensors does not match: "
  804. f"{actual._nnz()} != {expected._nnz()}"
  805. ),
  806. )
  807. self._compare_regular_values_equal(
  808. actual._indices(),
  809. expected._indices(),
  810. identifier="Sparse COO indices",
  811. )
  812. self._compare_regular_values_close(
  813. actual._values(),
  814. expected._values(),
  815. rtol=rtol,
  816. atol=atol,
  817. equal_nan=equal_nan,
  818. identifier="Sparse COO values",
  819. )
  820. def _compare_sparse_compressed_values(
  821. self,
  822. actual: torch.Tensor,
  823. expected: torch.Tensor,
  824. *,
  825. rtol: float,
  826. atol: float,
  827. equal_nan: bool,
  828. ) -> None:
  829. """Compares sparse compressed tensors by comparing
  830. - the number of non-zero elements (nnz) for equality,
  831. - the plain indices for equality,
  832. - the compressed indices for equality, and
  833. - the values for closeness.
  834. """
  835. format_name, compressed_indices_method, plain_indices_method = {
  836. torch.sparse_csr: (
  837. "CSR",
  838. torch.Tensor.crow_indices,
  839. torch.Tensor.col_indices,
  840. ),
  841. torch.sparse_csc: (
  842. "CSC",
  843. torch.Tensor.ccol_indices,
  844. torch.Tensor.row_indices,
  845. ),
  846. torch.sparse_bsr: (
  847. "BSR",
  848. torch.Tensor.crow_indices,
  849. torch.Tensor.col_indices,
  850. ),
  851. torch.sparse_bsc: (
  852. "BSC",
  853. torch.Tensor.ccol_indices,
  854. torch.Tensor.row_indices,
  855. ),
  856. }[actual.layout]
  857. if actual._nnz() != expected._nnz():
  858. self._fail(
  859. AssertionError,
  860. (
  861. f"The number of specified values in sparse {format_name} tensors does not match: "
  862. f"{actual._nnz()} != {expected._nnz()}"
  863. ),
  864. )
  865. # Compressed and plain indices in the CSR / CSC / BSR / BSC sparse formats can be `torch.int32` _or_
  866. # `torch.int64`. While the same dtype is enforced for the compressed and plain indices of a single tensor, it
  867. # can be different between two tensors. Thus, we need to convert them to the same dtype, or the comparison will
  868. # fail.
  869. actual_compressed_indices = compressed_indices_method(actual)
  870. expected_compressed_indices = compressed_indices_method(expected)
  871. indices_dtype = torch.promote_types(
  872. actual_compressed_indices.dtype, expected_compressed_indices.dtype
  873. )
  874. self._compare_regular_values_equal(
  875. actual_compressed_indices.to(indices_dtype),
  876. expected_compressed_indices.to(indices_dtype),
  877. identifier=f"Sparse {format_name} {compressed_indices_method.__name__}",
  878. )
  879. self._compare_regular_values_equal(
  880. plain_indices_method(actual).to(indices_dtype),
  881. plain_indices_method(expected).to(indices_dtype),
  882. identifier=f"Sparse {format_name} {plain_indices_method.__name__}",
  883. )
  884. self._compare_regular_values_close(
  885. actual.values(),
  886. expected.values(),
  887. rtol=rtol,
  888. atol=atol,
  889. equal_nan=equal_nan,
  890. identifier=f"Sparse {format_name} values",
  891. )
  892. def _compare_regular_values_equal(
  893. self,
  894. actual: torch.Tensor,
  895. expected: torch.Tensor,
  896. *,
  897. equal_nan: bool = False,
  898. identifier: Optional[Union[str, Callable[[str], str]]] = None,
  899. ) -> None:
  900. """Checks if the values of two tensors are equal."""
  901. self._compare_regular_values_close(
  902. actual, expected, rtol=0, atol=0, equal_nan=equal_nan, identifier=identifier
  903. )
  904. def _compare_regular_values_close(
  905. self,
  906. actual: torch.Tensor,
  907. expected: torch.Tensor,
  908. *,
  909. rtol: float,
  910. atol: float,
  911. equal_nan: bool,
  912. identifier: Optional[Union[str, Callable[[str], str]]] = None,
  913. ) -> None:
  914. """Checks if the values of two tensors are close up to a desired tolerance."""
  915. matches = torch.isclose(
  916. actual, expected, rtol=rtol, atol=atol, equal_nan=equal_nan
  917. )
  918. if torch.all(matches):
  919. return
  920. if actual.shape == torch.Size([]):
  921. msg = make_scalar_mismatch_msg(
  922. actual.item(),
  923. expected.item(),
  924. rtol=rtol,
  925. atol=atol,
  926. identifier=identifier,
  927. )
  928. else:
  929. msg = make_tensor_mismatch_msg(
  930. actual, expected, matches, rtol=rtol, atol=atol, identifier=identifier
  931. )
  932. self._fail(AssertionError, msg)
  933. def extra_repr(self) -> Sequence[str]:
  934. return (
  935. "rtol",
  936. "atol",
  937. "equal_nan",
  938. "check_device",
  939. "check_dtype",
  940. "check_layout",
  941. "check_stride",
  942. )
  943. def originate_pairs(
  944. actual: Any,
  945. expected: Any,
  946. *,
  947. pair_types: Sequence[type[Pair]],
  948. sequence_types: tuple[type, ...] = (collections.abc.Sequence,),
  949. mapping_types: tuple[type, ...] = (collections.abc.Mapping,),
  950. id: tuple[Any, ...] = (),
  951. **options: Any,
  952. ) -> list[Pair]:
  953. """Originates pairs from the individual inputs.
  954. ``actual`` and ``expected`` can be possibly nested :class:`~collections.abc.Sequence`'s or
  955. :class:`~collections.abc.Mapping`'s. In this case the pairs are originated by recursing through them.
  956. Args:
  957. actual (Any): Actual input.
  958. expected (Any): Expected input.
  959. pair_types (Sequence[Type[Pair]]): Sequence of pair types that will be tried to construct with the inputs.
  960. First successful pair will be used.
  961. sequence_types (Tuple[Type, ...]): Optional types treated as sequences that will be checked elementwise.
  962. mapping_types (Tuple[Type, ...]): Optional types treated as mappings that will be checked elementwise.
  963. id (Tuple[Any, ...]): Optional id of a pair that will be included in an error message.
  964. **options (Any): Options passed to each pair during construction.
  965. Raises:
  966. ErrorMeta: With :class`AssertionError`, if the inputs are :class:`~collections.abc.Sequence`'s, but their
  967. length does not match.
  968. ErrorMeta: With :class`AssertionError`, if the inputs are :class:`~collections.abc.Mapping`'s, but their set of
  969. keys do not match.
  970. ErrorMeta: With :class`TypeError`, if no pair is able to handle the inputs.
  971. ErrorMeta: With any expected exception that happens during the construction of a pair.
  972. Returns:
  973. (List[Pair]): Originated pairs.
  974. """
  975. # We explicitly exclude str's here since they are self-referential and would cause an infinite recursion loop:
  976. # "a" == "a"[0][0]...
  977. if (
  978. isinstance(actual, sequence_types)
  979. and not isinstance(actual, str)
  980. and isinstance(expected, sequence_types)
  981. and not isinstance(expected, str)
  982. ):
  983. actual_len = len(actual) # type: ignore[arg-type]
  984. expected_len = len(expected) # type: ignore[arg-type]
  985. if actual_len != expected_len:
  986. raise ErrorMeta(
  987. AssertionError,
  988. f"The length of the sequences mismatch: {actual_len} != {expected_len}",
  989. id=id,
  990. )
  991. pairs = []
  992. for idx in range(actual_len):
  993. pairs.extend(
  994. originate_pairs(
  995. actual[idx], # type: ignore[index]
  996. expected[idx], # type: ignore[index]
  997. pair_types=pair_types,
  998. sequence_types=sequence_types,
  999. mapping_types=mapping_types,
  1000. id=(*id, idx),
  1001. **options,
  1002. )
  1003. )
  1004. return pairs
  1005. elif isinstance(actual, mapping_types) and isinstance(expected, mapping_types):
  1006. actual_keys = set(actual.keys()) # type: ignore[attr-defined]
  1007. expected_keys = set(expected.keys()) # type: ignore[attr-defined]
  1008. if actual_keys != expected_keys:
  1009. missing_keys = expected_keys - actual_keys
  1010. additional_keys = actual_keys - expected_keys
  1011. raise ErrorMeta(
  1012. AssertionError,
  1013. (
  1014. f"The keys of the mappings do not match:\n"
  1015. f"Missing keys in the actual mapping: {sorted(missing_keys)}\n"
  1016. f"Additional keys in the actual mapping: {sorted(additional_keys)}"
  1017. ),
  1018. id=id,
  1019. )
  1020. keys: Collection = actual_keys
  1021. # Since the origination aborts after the first failure, we try to be deterministic
  1022. with contextlib.suppress(Exception):
  1023. keys = sorted(keys)
  1024. pairs = []
  1025. for key in keys:
  1026. pairs.extend(
  1027. originate_pairs(
  1028. actual[key], # type: ignore[index]
  1029. expected[key], # type: ignore[index]
  1030. pair_types=pair_types,
  1031. sequence_types=sequence_types,
  1032. mapping_types=mapping_types,
  1033. id=(*id, key),
  1034. **options,
  1035. )
  1036. )
  1037. return pairs
  1038. else:
  1039. for pair_type in pair_types:
  1040. try:
  1041. return [pair_type(actual, expected, id=id, **options)]
  1042. # Raising an `UnsupportedInputs` during origination indicates that the pair type is not able to handle the
  1043. # inputs. Thus, we try the next pair type.
  1044. except UnsupportedInputs:
  1045. continue
  1046. # Raising an `ErrorMeta` during origination is the orderly way to abort and so we simply re-raise it. This
  1047. # is only in a separate branch, because the one below would also except it.
  1048. except ErrorMeta:
  1049. raise
  1050. # Raising any other exception during origination is unexpected and will give some extra information about
  1051. # what happened. If applicable, the exception should be expected in the future.
  1052. except Exception as error:
  1053. raise RuntimeError(
  1054. f"Originating a {pair_type.__name__}() at item {''.join(str([item]) for item in id)} with\n\n"
  1055. f"{type(actual).__name__}(): {actual}\n\n"
  1056. f"and\n\n"
  1057. f"{type(expected).__name__}(): {expected}\n\n"
  1058. f"resulted in the unexpected exception above. "
  1059. f"If you are a user and see this message during normal operation "
  1060. "please file an issue at https://github.com/pytorch/pytorch/issues. "
  1061. "If you are a developer and working on the comparison functions, "
  1062. "please except the previous error and raise an expressive `ErrorMeta` instead."
  1063. ) from error
  1064. else:
  1065. raise ErrorMeta(
  1066. TypeError,
  1067. f"No comparison pair was able to handle inputs of type {type(actual)} and {type(expected)}.",
  1068. id=id,
  1069. )
  1070. def not_close_error_metas(
  1071. actual: Any,
  1072. expected: Any,
  1073. *,
  1074. pair_types: Sequence[type[Pair]] = (ObjectPair,),
  1075. sequence_types: tuple[type, ...] = (collections.abc.Sequence,),
  1076. mapping_types: tuple[type, ...] = (collections.abc.Mapping,),
  1077. **options: Any,
  1078. ) -> list[ErrorMeta]:
  1079. """Asserts that inputs are equal.
  1080. ``actual`` and ``expected`` can be possibly nested :class:`~collections.abc.Sequence`'s or
  1081. :class:`~collections.abc.Mapping`'s. In this case the comparison happens elementwise by recursing through them.
  1082. Args:
  1083. actual (Any): Actual input.
  1084. expected (Any): Expected input.
  1085. pair_types (Sequence[Type[Pair]]): Sequence of :class:`Pair` types that will be tried to construct with the
  1086. inputs. First successful pair will be used. Defaults to only using :class:`ObjectPair`.
  1087. sequence_types (Tuple[Type, ...]): Optional types treated as sequences that will be checked elementwise.
  1088. mapping_types (Tuple[Type, ...]): Optional types treated as mappings that will be checked elementwise.
  1089. **options (Any): Options passed to each pair during construction.
  1090. """
  1091. # Hide this function from `pytest`'s traceback
  1092. __tracebackhide__ = True
  1093. try:
  1094. pairs = originate_pairs(
  1095. actual,
  1096. expected,
  1097. pair_types=pair_types,
  1098. sequence_types=sequence_types,
  1099. mapping_types=mapping_types,
  1100. **options,
  1101. )
  1102. except ErrorMeta as error_meta:
  1103. # Explicitly raising from None to hide the internal traceback
  1104. raise error_meta.to_error() from None # noqa: RSE102
  1105. error_metas: list[ErrorMeta] = []
  1106. for pair in pairs:
  1107. try:
  1108. pair.compare()
  1109. except ErrorMeta as error_meta:
  1110. error_metas.append(error_meta)
  1111. # Raising any exception besides `ErrorMeta` while comparing is unexpected and will give some extra information
  1112. # about what happened. If applicable, the exception should be expected in the future.
  1113. except Exception as error:
  1114. raise RuntimeError(
  1115. f"Comparing\n\n"
  1116. f"{pair}\n\n"
  1117. f"resulted in the unexpected exception above. "
  1118. f"If you are a user and see this message during normal operation "
  1119. "please file an issue at https://github.com/pytorch/pytorch/issues. "
  1120. "If you are a developer and working on the comparison functions, "
  1121. "please except the previous error and raise an expressive `ErrorMeta` instead."
  1122. ) from error
  1123. # [ErrorMeta Cycles]
  1124. # ErrorMeta objects in this list capture
  1125. # tracebacks that refer to the frame of this function.
  1126. # The local variable `error_metas` refers to the error meta
  1127. # objects, creating a reference cycle. Frames in the traceback
  1128. # would not get freed until cycle collection, leaking cuda memory in tests.
  1129. # We break the cycle by removing the reference to the error_meta objects
  1130. # from this frame as it returns.
  1131. error_metas = [error_metas]
  1132. return error_metas.pop()
  1133. def assert_close(
  1134. actual: Any,
  1135. expected: Any,
  1136. *,
  1137. allow_subclasses: bool = True,
  1138. rtol: Optional[float] = None,
  1139. atol: Optional[float] = None,
  1140. equal_nan: bool = False,
  1141. check_device: bool = True,
  1142. check_dtype: bool = True,
  1143. check_layout: bool = True,
  1144. check_stride: bool = False,
  1145. msg: Optional[Union[str, Callable[[str], str]]] = None,
  1146. ):
  1147. r"""Asserts that ``actual`` and ``expected`` are close.
  1148. If ``actual`` and ``expected`` are strided, non-quantized, real-valued, and finite, they are considered close if
  1149. .. math::
  1150. \lvert \text{actual} - \text{expected} \rvert \le \texttt{atol} + \texttt{rtol} \cdot \lvert \text{expected} \rvert
  1151. Non-finite values (``-inf`` and ``inf``) are only considered close if and only if they are equal. ``NaN``'s are
  1152. only considered equal to each other if ``equal_nan`` is ``True``.
  1153. In addition, they are only considered close if they have the same
  1154. - :attr:`~torch.Tensor.device` (if ``check_device`` is ``True``),
  1155. - ``dtype`` (if ``check_dtype`` is ``True``),
  1156. - ``layout`` (if ``check_layout`` is ``True``), and
  1157. - stride (if ``check_stride`` is ``True``).
  1158. If either ``actual`` or ``expected`` is a meta tensor, only the attribute checks will be performed.
  1159. If ``actual`` and ``expected`` are sparse (either having COO, CSR, CSC, BSR, or BSC layout), their strided members are
  1160. checked individually. Indices, namely ``indices`` for COO, ``crow_indices`` and ``col_indices`` for CSR and BSR,
  1161. or ``ccol_indices`` and ``row_indices`` for CSC and BSC layouts, respectively,
  1162. are always checked for equality whereas the values are checked for closeness according to the definition above.
  1163. If ``actual`` and ``expected`` are quantized, they are considered close if they have the same
  1164. :meth:`~torch.Tensor.qscheme` and the result of :meth:`~torch.Tensor.dequantize` is close according to the
  1165. definition above.
  1166. ``actual`` and ``expected`` can be :class:`~torch.Tensor`'s or any tensor-or-scalar-likes from which
  1167. :class:`torch.Tensor`'s can be constructed with :func:`torch.as_tensor`. Except for Python scalars the input types
  1168. have to be directly related. In addition, ``actual`` and ``expected`` can be :class:`~collections.abc.Sequence`'s
  1169. or :class:`~collections.abc.Mapping`'s in which case they are considered close if their structure matches and all
  1170. their elements are considered close according to the above definition.
  1171. .. note::
  1172. Python scalars are an exception to the type relation requirement, because their :func:`type`, i.e.
  1173. :class:`int`, :class:`float`, and :class:`complex`, is equivalent to the ``dtype`` of a tensor-like. Thus,
  1174. Python scalars of different types can be checked, but require ``check_dtype=False``.
  1175. Args:
  1176. actual (Any): Actual input.
  1177. expected (Any): Expected input.
  1178. allow_subclasses (bool): If ``True`` (default) and except for Python scalars, inputs of directly related types
  1179. are allowed. Otherwise type equality is required.
  1180. rtol (Optional[float]): Relative tolerance. If specified ``atol`` must also be specified. If omitted, default
  1181. values based on the :attr:`~torch.Tensor.dtype` are selected with the below table.
  1182. atol (Optional[float]): Absolute tolerance. If specified ``rtol`` must also be specified. If omitted, default
  1183. values based on the :attr:`~torch.Tensor.dtype` are selected with the below table.
  1184. equal_nan (Union[bool, str]): If ``True``, two ``NaN`` values will be considered equal.
  1185. check_device (bool): If ``True`` (default), asserts that corresponding tensors are on the same
  1186. :attr:`~torch.Tensor.device`. If this check is disabled, tensors on different
  1187. :attr:`~torch.Tensor.device`'s are moved to the CPU before being compared.
  1188. check_dtype (bool): If ``True`` (default), asserts that corresponding tensors have the same ``dtype``. If this
  1189. check is disabled, tensors with different ``dtype``'s are promoted to a common ``dtype`` (according to
  1190. :func:`torch.promote_types`) before being compared.
  1191. check_layout (bool): If ``True`` (default), asserts that corresponding tensors have the same ``layout``. If this
  1192. check is disabled, tensors with different ``layout``'s are converted to strided tensors before being
  1193. compared.
  1194. check_stride (bool): If ``True`` and corresponding tensors are strided, asserts that they have the same stride.
  1195. msg (Optional[Union[str, Callable[[str], str]]]): Optional error message to use in case a failure occurs during
  1196. the comparison. Can also passed as callable in which case it will be called with the generated message and
  1197. should return the new message.
  1198. Raises:
  1199. ValueError: If no :class:`torch.Tensor` can be constructed from an input.
  1200. ValueError: If only ``rtol`` or ``atol`` is specified.
  1201. AssertionError: If corresponding inputs are not Python scalars and are not directly related.
  1202. AssertionError: If ``allow_subclasses`` is ``False``, but corresponding inputs are not Python scalars and have
  1203. different types.
  1204. AssertionError: If the inputs are :class:`~collections.abc.Sequence`'s, but their length does not match.
  1205. AssertionError: If the inputs are :class:`~collections.abc.Mapping`'s, but their set of keys do not match.
  1206. AssertionError: If corresponding tensors do not have the same :attr:`~torch.Tensor.shape`.
  1207. AssertionError: If ``check_layout`` is ``True``, but corresponding tensors do not have the same
  1208. :attr:`~torch.Tensor.layout`.
  1209. AssertionError: If only one of corresponding tensors is quantized.
  1210. AssertionError: If corresponding tensors are quantized, but have different :meth:`~torch.Tensor.qscheme`'s.
  1211. AssertionError: If ``check_device`` is ``True``, but corresponding tensors are not on the same
  1212. :attr:`~torch.Tensor.device`.
  1213. AssertionError: If ``check_dtype`` is ``True``, but corresponding tensors do not have the same ``dtype``.
  1214. AssertionError: If ``check_stride`` is ``True``, but corresponding strided tensors do not have the same stride.
  1215. AssertionError: If the values of corresponding tensors are not close according to the definition above.
  1216. The following table displays the default ``rtol`` and ``atol`` for different ``dtype``'s. In case of mismatching
  1217. ``dtype``'s, the maximum of both tolerances is used.
  1218. +---------------------------+------------+----------+
  1219. | ``dtype`` | ``rtol`` | ``atol`` |
  1220. +===========================+============+==========+
  1221. | :attr:`~torch.float16` | ``1e-3`` | ``1e-5`` |
  1222. +---------------------------+------------+----------+
  1223. | :attr:`~torch.bfloat16` | ``1.6e-2`` | ``1e-5`` |
  1224. +---------------------------+------------+----------+
  1225. | :attr:`~torch.float32` | ``1.3e-6`` | ``1e-5`` |
  1226. +---------------------------+------------+----------+
  1227. | :attr:`~torch.float64` | ``1e-7`` | ``1e-7`` |
  1228. +---------------------------+------------+----------+
  1229. | :attr:`~torch.complex32` | ``1e-3`` | ``1e-5`` |
  1230. +---------------------------+------------+----------+
  1231. | :attr:`~torch.complex64` | ``1.3e-6`` | ``1e-5`` |
  1232. +---------------------------+------------+----------+
  1233. | :attr:`~torch.complex128` | ``1e-7`` | ``1e-7`` |
  1234. +---------------------------+------------+----------+
  1235. | :attr:`~torch.quint8` | ``1.3e-6`` | ``1e-5`` |
  1236. +---------------------------+------------+----------+
  1237. | :attr:`~torch.quint2x4` | ``1.3e-6`` | ``1e-5`` |
  1238. +---------------------------+------------+----------+
  1239. | :attr:`~torch.quint4x2` | ``1.3e-6`` | ``1e-5`` |
  1240. +---------------------------+------------+----------+
  1241. | :attr:`~torch.qint8` | ``1.3e-6`` | ``1e-5`` |
  1242. +---------------------------+------------+----------+
  1243. | :attr:`~torch.qint32` | ``1.3e-6`` | ``1e-5`` |
  1244. +---------------------------+------------+----------+
  1245. | other | ``0.0`` | ``0.0`` |
  1246. +---------------------------+------------+----------+
  1247. .. note::
  1248. :func:`~torch.testing.assert_close` is highly configurable with strict default settings. Users are encouraged
  1249. to :func:`~functools.partial` it to fit their use case. For example, if an equality check is needed, one might
  1250. define an ``assert_equal`` that uses zero tolerances for every ``dtype`` by default:
  1251. >>> import functools
  1252. >>> assert_equal = functools.partial(torch.testing.assert_close, rtol=0, atol=0)
  1253. >>> assert_equal(1e-9, 1e-10)
  1254. Traceback (most recent call last):
  1255. ...
  1256. AssertionError: Scalars are not equal!
  1257. <BLANKLINE>
  1258. Expected 1e-10 but got 1e-09.
  1259. Absolute difference: 9.000000000000001e-10
  1260. Relative difference: 9.0
  1261. Examples:
  1262. >>> # tensor to tensor comparison
  1263. >>> expected = torch.tensor([1e0, 1e-1, 1e-2])
  1264. >>> actual = torch.acos(torch.cos(expected))
  1265. >>> torch.testing.assert_close(actual, expected)
  1266. >>> # scalar to scalar comparison
  1267. >>> import math
  1268. >>> expected = math.sqrt(2.0)
  1269. >>> actual = 2.0 / math.sqrt(2.0)
  1270. >>> torch.testing.assert_close(actual, expected)
  1271. >>> # numpy array to numpy array comparison
  1272. >>> import numpy as np
  1273. >>> expected = np.array([1e0, 1e-1, 1e-2])
  1274. >>> actual = np.arccos(np.cos(expected))
  1275. >>> torch.testing.assert_close(actual, expected)
  1276. >>> # sequence to sequence comparison
  1277. >>> import numpy as np
  1278. >>> # The types of the sequences do not have to match. They only have to have the same
  1279. >>> # length and their elements have to match.
  1280. >>> expected = [torch.tensor([1.0]), 2.0, np.array(3.0)]
  1281. >>> actual = tuple(expected)
  1282. >>> torch.testing.assert_close(actual, expected)
  1283. >>> # mapping to mapping comparison
  1284. >>> from collections import OrderedDict
  1285. >>> import numpy as np
  1286. >>> foo = torch.tensor(1.0)
  1287. >>> bar = 2.0
  1288. >>> baz = np.array(3.0)
  1289. >>> # The types and a possible ordering of mappings do not have to match. They only
  1290. >>> # have to have the same set of keys and their elements have to match.
  1291. >>> expected = OrderedDict([("foo", foo), ("bar", bar), ("baz", baz)])
  1292. >>> actual = {"baz": baz, "bar": bar, "foo": foo}
  1293. >>> torch.testing.assert_close(actual, expected)
  1294. >>> expected = torch.tensor([1.0, 2.0, 3.0])
  1295. >>> actual = expected.clone()
  1296. >>> # By default, directly related instances can be compared
  1297. >>> torch.testing.assert_close(torch.nn.Parameter(actual), expected)
  1298. >>> # This check can be made more strict with allow_subclasses=False
  1299. >>> torch.testing.assert_close(
  1300. ... torch.nn.Parameter(actual), expected, allow_subclasses=False
  1301. ... )
  1302. Traceback (most recent call last):
  1303. ...
  1304. TypeError: No comparison pair was able to handle inputs of type
  1305. <class 'torch.nn.parameter.Parameter'> and <class 'torch.Tensor'>.
  1306. >>> # If the inputs are not directly related, they are never considered close
  1307. >>> torch.testing.assert_close(actual.numpy(), expected)
  1308. Traceback (most recent call last):
  1309. ...
  1310. TypeError: No comparison pair was able to handle inputs of type <class 'numpy.ndarray'>
  1311. and <class 'torch.Tensor'>.
  1312. >>> # Exceptions to these rules are Python scalars. They can be checked regardless of
  1313. >>> # their type if check_dtype=False.
  1314. >>> torch.testing.assert_close(1.0, 1, check_dtype=False)
  1315. >>> # NaN != NaN by default.
  1316. >>> expected = torch.tensor(float("Nan"))
  1317. >>> actual = expected.clone()
  1318. >>> torch.testing.assert_close(actual, expected)
  1319. Traceback (most recent call last):
  1320. ...
  1321. AssertionError: Scalars are not close!
  1322. <BLANKLINE>
  1323. Expected nan but got nan.
  1324. Absolute difference: nan (up to 1e-05 allowed)
  1325. Relative difference: nan (up to 1.3e-06 allowed)
  1326. >>> torch.testing.assert_close(actual, expected, equal_nan=True)
  1327. >>> expected = torch.tensor([1.0, 2.0, 3.0])
  1328. >>> actual = torch.tensor([1.0, 4.0, 5.0])
  1329. >>> # The default error message can be overwritten.
  1330. >>> torch.testing.assert_close(
  1331. ... actual, expected, msg="Argh, the tensors are not close!"
  1332. ... )
  1333. Traceback (most recent call last):
  1334. ...
  1335. AssertionError: Argh, the tensors are not close!
  1336. >>> # If msg is a callable, it can be used to augment the generated message with
  1337. >>> # extra information
  1338. >>> torch.testing.assert_close(
  1339. ... actual, expected, msg=lambda msg: f"Header\n\n{msg}\n\nFooter"
  1340. ... )
  1341. Traceback (most recent call last):
  1342. ...
  1343. AssertionError: Header
  1344. <BLANKLINE>
  1345. Tensor-likes are not close!
  1346. <BLANKLINE>
  1347. Mismatched elements: 2 / 3 (66.7%)
  1348. Greatest absolute difference: 2.0 at index (1,) (up to 1e-05 allowed)
  1349. Greatest relative difference: 1.0 at index (1,) (up to 1.3e-06 allowed)
  1350. <BLANKLINE>
  1351. Footer
  1352. """
  1353. # Hide this function from `pytest`'s traceback
  1354. __tracebackhide__ = True
  1355. error_metas = not_close_error_metas(
  1356. actual,
  1357. expected,
  1358. pair_types=(
  1359. NonePair,
  1360. BooleanPair,
  1361. NumberPair,
  1362. TensorLikePair,
  1363. ),
  1364. allow_subclasses=allow_subclasses,
  1365. rtol=rtol,
  1366. atol=atol,
  1367. equal_nan=equal_nan,
  1368. check_device=check_device,
  1369. check_dtype=check_dtype,
  1370. check_layout=check_layout,
  1371. check_stride=check_stride,
  1372. msg=msg,
  1373. )
  1374. if error_metas:
  1375. # TODO: compose all metas into one AssertionError
  1376. raise error_metas[0].to_error(msg)
  1377. @deprecated(
  1378. "`torch.testing.assert_allclose()` is deprecated since 1.12 and will be removed in a future release. "
  1379. "Please use `torch.testing.assert_close()` instead. "
  1380. "You can find detailed upgrade instructions in https://github.com/pytorch/pytorch/issues/61844.",
  1381. category=FutureWarning,
  1382. )
  1383. def assert_allclose(
  1384. actual: Any,
  1385. expected: Any,
  1386. rtol: Optional[float] = None,
  1387. atol: Optional[float] = None,
  1388. equal_nan: bool = True,
  1389. msg: str = "",
  1390. ) -> None:
  1391. """
  1392. .. warning::
  1393. :func:`torch.testing.assert_allclose` is deprecated since ``1.12`` and will be removed in a future release.
  1394. Please use :func:`torch.testing.assert_close` instead. You can find detailed upgrade instructions
  1395. `here <https://github.com/pytorch/pytorch/issues/61844>`_.
  1396. """
  1397. if not isinstance(actual, torch.Tensor):
  1398. actual = torch.tensor(actual)
  1399. if not isinstance(expected, torch.Tensor):
  1400. expected = torch.tensor(expected, dtype=actual.dtype)
  1401. if rtol is None and atol is None:
  1402. rtol, atol = default_tolerances(
  1403. actual,
  1404. expected,
  1405. dtype_precisions={
  1406. torch.float16: (1e-3, 1e-3),
  1407. torch.float32: (1e-4, 1e-5),
  1408. torch.float64: (1e-5, 1e-8),
  1409. },
  1410. )
  1411. torch.testing.assert_close(
  1412. actual,
  1413. expected,
  1414. rtol=rtol,
  1415. atol=atol,
  1416. equal_nan=equal_nan,
  1417. check_device=True,
  1418. check_dtype=False,
  1419. check_stride=False,
  1420. msg=msg or None,
  1421. )