_comparison.py 61 KB

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