forked from Rajeevveera24/pytorch-copy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_comparison.py
1580 lines (1370 loc) · 61.7 KB
/
_comparison.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# mypy: allow-untyped-defs
import abc
import cmath
import collections.abc
import contextlib
from typing import (
Any,
Callable,
Collection,
Dict,
List,
NoReturn,
Optional,
Sequence,
Tuple,
Type,
Union,
)
from typing_extensions import deprecated
import torch
try:
import numpy as np
HAS_NUMPY = True
except ModuleNotFoundError:
HAS_NUMPY = False
np = None # type: ignore[assignment]
class ErrorMeta(Exception):
"""Internal testing exception that makes that carries error metadata."""
def __init__(
self, type: Type[Exception], msg: str, *, id: Tuple[Any, ...] = ()
) -> None:
super().__init__(
"If you are a user and see this message during normal operation "
"please file an issue at https://github.com/pytorch/pytorch/issues. "
"If you are a developer and working on the comparison functions, please `raise ErrorMeta.to_error()` "
"for user facing errors."
)
self.type = type
self.msg = msg
self.id = id
def to_error(
self, msg: Optional[Union[str, Callable[[str], str]]] = None
) -> Exception:
if not isinstance(msg, str):
generated_msg = self.msg
if self.id:
generated_msg += f"\n\nThe failure occurred for item {''.join(str([item]) for item in self.id)}"
msg = msg(generated_msg) if callable(msg) else generated_msg
return self.type(msg)
# Some analysis of tolerance by logging tests from test_torch.py can be found in
# https://github.com/pytorch/pytorch/pull/32538.
# {dtype: (rtol, atol)}
_DTYPE_PRECISIONS = {
torch.float16: (0.001, 1e-5),
torch.bfloat16: (0.016, 1e-5),
torch.float32: (1.3e-6, 1e-5),
torch.float64: (1e-7, 1e-7),
torch.complex32: (0.001, 1e-5),
torch.complex64: (1.3e-6, 1e-5),
torch.complex128: (1e-7, 1e-7),
}
# The default tolerances of torch.float32 are used for quantized dtypes, because quantized tensors are compared in
# their dequantized and floating point representation. For more details see `TensorLikePair._compare_quantized_values`
_DTYPE_PRECISIONS.update(
dict.fromkeys(
(torch.quint8, torch.quint2x4, torch.quint4x2, torch.qint8, torch.qint32),
_DTYPE_PRECISIONS[torch.float32],
)
)
def default_tolerances(
*inputs: Union[torch.Tensor, torch.dtype],
dtype_precisions: Optional[Dict[torch.dtype, Tuple[float, float]]] = None,
) -> Tuple[float, float]:
"""Returns the default absolute and relative testing tolerances for a set of inputs based on the dtype.
See :func:`assert_close` for a table of the default tolerance for each dtype.
Returns:
(Tuple[float, float]): Loosest tolerances of all input dtypes.
"""
dtypes = []
for input in inputs:
if isinstance(input, torch.Tensor):
dtypes.append(input.dtype)
elif isinstance(input, torch.dtype):
dtypes.append(input)
else:
raise TypeError(
f"Expected a torch.Tensor or a torch.dtype, but got {type(input)} instead."
)
dtype_precisions = dtype_precisions or _DTYPE_PRECISIONS
rtols, atols = zip(*[dtype_precisions.get(dtype, (0.0, 0.0)) for dtype in dtypes])
return max(rtols), max(atols)
def get_tolerances(
*inputs: Union[torch.Tensor, torch.dtype],
rtol: Optional[float],
atol: Optional[float],
id: Tuple[Any, ...] = (),
) -> Tuple[float, float]:
"""Gets absolute and relative to be used for numeric comparisons.
If both ``rtol`` and ``atol`` are specified, this is a no-op. If both are not specified, the return value of
:func:`default_tolerances` is used.
Raises:
ErrorMeta: With :class:`ValueError`, if only ``rtol`` or ``atol`` is specified.
Returns:
(Tuple[float, float]): Valid absolute and relative tolerances.
"""
if (rtol is None) ^ (atol is None):
# We require both tolerance to be omitted or specified, because specifying only one might lead to surprising
# results. Imagine setting atol=0.0 and the tensors still match because rtol>0.0.
raise ErrorMeta(
ValueError,
f"Both 'rtol' and 'atol' must be either specified or omitted, "
f"but got no {'rtol' if rtol is None else 'atol'}.",
id=id,
)
elif rtol is not None and atol is not None:
return rtol, atol
else:
return default_tolerances(*inputs)
def _make_mismatch_msg(
*,
default_identifier: str,
identifier: Optional[Union[str, Callable[[str], str]]] = None,
extra: Optional[str] = None,
abs_diff: float,
abs_diff_idx: Optional[Union[int, Tuple[int, ...]]] = None,
atol: float,
rel_diff: float,
rel_diff_idx: Optional[Union[int, Tuple[int, ...]]] = None,
rtol: float,
) -> str:
"""Makes a mismatch error message for numeric values.
Args:
default_identifier (str): Default description of the compared values, e.g. "Tensor-likes".
identifier (Optional[Union[str, Callable[[str], str]]]): Optional identifier that overrides
``default_identifier``. Can be passed as callable in which case it will be called with
``default_identifier`` to create the description at runtime.
extra (Optional[str]): Extra information to be placed after the message header and the mismatch statistics.
abs_diff (float): Absolute difference.
abs_diff_idx (Optional[Union[int, Tuple[int, ...]]]): Optional index of the absolute difference.
atol (float): Allowed absolute tolerance. Will only be added to mismatch statistics if it or ``rtol`` are
``> 0``.
rel_diff (float): Relative difference.
rel_diff_idx (Optional[Union[int, Tuple[int, ...]]]): Optional index of the relative difference.
rtol (float): Allowed relative tolerance. Will only be added to mismatch statistics if it or ``atol`` are
``> 0``.
"""
equality = rtol == 0 and atol == 0
def make_diff_msg(
*,
type: str,
diff: float,
idx: Optional[Union[int, Tuple[int, ...]]],
tol: float,
) -> str:
if idx is None:
msg = f"{type.title()} difference: {diff}"
else:
msg = f"Greatest {type} difference: {diff} at index {idx}"
if not equality:
msg += f" (up to {tol} allowed)"
return msg + "\n"
if identifier is None:
identifier = default_identifier
elif callable(identifier):
identifier = identifier(default_identifier)
msg = f"{identifier} are not {'equal' if equality else 'close'}!\n\n"
if extra:
msg += f"{extra.strip()}\n"
msg += make_diff_msg(type="absolute", diff=abs_diff, idx=abs_diff_idx, tol=atol)
msg += make_diff_msg(type="relative", diff=rel_diff, idx=rel_diff_idx, tol=rtol)
return msg.strip()
def make_scalar_mismatch_msg(
actual: Union[bool, int, float, complex],
expected: Union[bool, int, float, complex],
*,
rtol: float,
atol: float,
identifier: Optional[Union[str, Callable[[str], str]]] = None,
) -> str:
"""Makes a mismatch error message for scalars.
Args:
actual (Union[bool, int, float, complex]): Actual scalar.
expected (Union[bool, int, float, complex]): Expected scalar.
rtol (float): Relative tolerance.
atol (float): Absolute tolerance.
identifier (Optional[Union[str, Callable[[str], str]]]): Optional description for the scalars. Can be passed
as callable in which case it will be called by the default value to create the description at runtime.
Defaults to "Scalars".
"""
abs_diff = abs(actual - expected)
rel_diff = float("inf") if expected == 0 else abs_diff / abs(expected)
return _make_mismatch_msg(
default_identifier="Scalars",
identifier=identifier,
extra=f"Expected {expected} but got {actual}.",
abs_diff=abs_diff,
atol=atol,
rel_diff=rel_diff,
rtol=rtol,
)
def make_tensor_mismatch_msg(
actual: torch.Tensor,
expected: torch.Tensor,
matches: torch.Tensor,
*,
rtol: float,
atol: float,
identifier: Optional[Union[str, Callable[[str], str]]] = None,
):
"""Makes a mismatch error message for tensors.
Args:
actual (torch.Tensor): Actual tensor.
expected (torch.Tensor): Expected tensor.
matches (torch.Tensor): Boolean mask of the same shape as ``actual`` and ``expected`` that indicates the
location of matches.
rtol (float): Relative tolerance.
atol (float): Absolute tolerance.
identifier (Optional[Union[str, Callable[[str], str]]]): Optional description for the tensors. Can be passed
as callable in which case it will be called by the default value to create the description at runtime.
Defaults to "Tensor-likes".
"""
def unravel_flat_index(flat_index: int) -> Tuple[int, ...]:
if not matches.shape:
return ()
inverse_index = []
for size in matches.shape[::-1]:
div, mod = divmod(flat_index, size)
flat_index = div
inverse_index.append(mod)
return tuple(inverse_index[::-1])
number_of_elements = matches.numel()
total_mismatches = number_of_elements - int(torch.sum(matches))
extra = (
f"Mismatched elements: {total_mismatches} / {number_of_elements} "
f"({total_mismatches / number_of_elements:.1%})"
)
actual_flat = actual.flatten()
expected_flat = expected.flatten()
matches_flat = matches.flatten()
if not actual.dtype.is_floating_point and not actual.dtype.is_complex:
# TODO: Instead of always upcasting to int64, it would be sufficient to cast to the next higher dtype to avoid
# overflow
actual_flat = actual_flat.to(torch.int64)
expected_flat = expected_flat.to(torch.int64)
abs_diff = torch.abs(actual_flat - expected_flat)
# Ensure that only mismatches are used for the max_abs_diff computation
abs_diff[matches_flat] = 0
max_abs_diff, max_abs_diff_flat_idx = torch.max(abs_diff, 0)
rel_diff = abs_diff / torch.abs(expected_flat)
# Ensure that only mismatches are used for the max_rel_diff computation
rel_diff[matches_flat] = 0
max_rel_diff, max_rel_diff_flat_idx = torch.max(rel_diff, 0)
return _make_mismatch_msg(
default_identifier="Tensor-likes",
identifier=identifier,
extra=extra,
abs_diff=max_abs_diff.item(),
abs_diff_idx=unravel_flat_index(int(max_abs_diff_flat_idx)),
atol=atol,
rel_diff=max_rel_diff.item(),
rel_diff_idx=unravel_flat_index(int(max_rel_diff_flat_idx)),
rtol=rtol,
)
class UnsupportedInputs(Exception): # noqa: B903
"""Exception to be raised during the construction of a :class:`Pair` in case it doesn't support the inputs."""
class Pair(abc.ABC):
"""ABC for all comparison pairs to be used in conjunction with :func:`assert_equal`.
Each subclass needs to overwrite :meth:`Pair.compare` that performs the actual comparison.
Each pair receives **all** options, so select the ones applicable for the subclass and forward the rest to the
super class. Raising an :class:`UnsupportedInputs` during constructions indicates that the pair is not able to
handle the inputs and the next pair type will be tried.
All other errors should be raised as :class:`ErrorMeta`. After the instantiation, :meth:`Pair._make_error_meta` can
be used to automatically handle overwriting the message with a user supplied one and id handling.
"""
def __init__(
self,
actual: Any,
expected: Any,
*,
id: Tuple[Any, ...] = (),
**unknown_parameters: Any,
) -> None:
self.actual = actual
self.expected = expected
self.id = id
self._unknown_parameters = unknown_parameters
@staticmethod
def _inputs_not_supported() -> NoReturn:
raise UnsupportedInputs
@staticmethod
def _check_inputs_isinstance(*inputs: Any, cls: Union[Type, Tuple[Type, ...]]):
"""Checks if all inputs are instances of a given class and raise :class:`UnsupportedInputs` otherwise."""
if not all(isinstance(input, cls) for input in inputs):
Pair._inputs_not_supported()
def _fail(
self, type: Type[Exception], msg: str, *, id: Tuple[Any, ...] = ()
) -> NoReturn:
"""Raises an :class:`ErrorMeta` from a given exception type and message and the stored id.
.. warning::
If you use this before the ``super().__init__(...)`` call in the constructor, you have to pass the ``id``
explicitly.
"""
raise ErrorMeta(type, msg, id=self.id if not id and hasattr(self, "id") else id)
@abc.abstractmethod
def compare(self) -> None:
"""Compares the inputs and raises an :class`ErrorMeta` in case they mismatch."""
def extra_repr(self) -> Sequence[Union[str, Tuple[str, Any]]]:
"""Returns extra information that will be included in the representation.
Should be overwritten by all subclasses that use additional options. The representation of the object will only
be surfaced in case we encounter an unexpected error and thus should help debug the issue. Can be a sequence of
key-value-pairs or attribute names.
"""
return []
def __repr__(self) -> str:
head = f"{type(self).__name__}("
tail = ")"
body = [
f" {name}={value!s},"
for name, value in [
("id", self.id),
("actual", self.actual),
("expected", self.expected),
*[
(extra, getattr(self, extra)) if isinstance(extra, str) else extra
for extra in self.extra_repr()
],
]
]
return "\n".join((head, *body, *tail))
class ObjectPair(Pair):
"""Pair for any type of inputs that will be compared with the `==` operator.
.. note::
Since this will instantiate for any kind of inputs, it should only be used as fallback after all other pairs
couldn't handle the inputs.
"""
def compare(self) -> None:
try:
equal = self.actual == self.expected
except Exception as error:
# We are not using `self._raise_error_meta` here since we need the exception chaining
raise ErrorMeta(
ValueError,
f"{self.actual} == {self.expected} failed with:\n{error}.",
id=self.id,
) from error
if not equal:
self._fail(AssertionError, f"{self.actual} != {self.expected}")
class NonePair(Pair):
"""Pair for ``None`` inputs."""
def __init__(self, actual: Any, expected: Any, **other_parameters: Any) -> None:
if not (actual is None or expected is None):
self._inputs_not_supported()
super().__init__(actual, expected, **other_parameters)
def compare(self) -> None:
if not (self.actual is None and self.expected is None):
self._fail(
AssertionError, f"None mismatch: {self.actual} is not {self.expected}"
)
class BooleanPair(Pair):
"""Pair for :class:`bool` inputs.
.. note::
If ``numpy`` is available, also handles :class:`numpy.bool_` inputs.
"""
def __init__(
self,
actual: Any,
expected: Any,
*,
id: Tuple[Any, ...],
**other_parameters: Any,
) -> None:
actual, expected = self._process_inputs(actual, expected, id=id)
super().__init__(actual, expected, **other_parameters)
@property
def _supported_types(self) -> Tuple[Type, ...]:
cls: List[Type] = [bool]
if HAS_NUMPY:
cls.append(np.bool_)
return tuple(cls)
def _process_inputs(
self, actual: Any, expected: Any, *, id: Tuple[Any, ...]
) -> Tuple[bool, bool]:
self._check_inputs_isinstance(actual, expected, cls=self._supported_types)
actual, expected = (
self._to_bool(bool_like, id=id) for bool_like in (actual, expected)
)
return actual, expected
def _to_bool(self, bool_like: Any, *, id: Tuple[Any, ...]) -> bool:
if isinstance(bool_like, bool):
return bool_like
elif isinstance(bool_like, np.bool_):
return bool_like.item()
else:
raise ErrorMeta(
TypeError, f"Unknown boolean type {type(bool_like)}.", id=id
)
def compare(self) -> None:
if self.actual is not self.expected:
self._fail(
AssertionError,
f"Booleans mismatch: {self.actual} is not {self.expected}",
)
class NumberPair(Pair):
"""Pair for Python number (:class:`int`, :class:`float`, and :class:`complex`) inputs.
.. note::
If ``numpy`` is available, also handles :class:`numpy.number` inputs.
Kwargs:
rtol (Optional[float]): Relative tolerance. If specified ``atol`` must also be specified. If omitted, default
values based on the type are selected with the below table.
atol (Optional[float]): Absolute tolerance. If specified ``rtol`` must also be specified. If omitted, default
values based on the type are selected with the below table.
equal_nan (bool): If ``True``, two ``NaN`` values are considered equal. Defaults to ``False``.
check_dtype (bool): If ``True``, the type of the inputs will be checked for equality. Defaults to ``False``.
The following table displays correspondence between Python number type and the ``torch.dtype``'s. See
:func:`assert_close` for the corresponding tolerances.
+------------------+-------------------------------+
| ``type`` | corresponding ``torch.dtype`` |
+==================+===============================+
| :class:`int` | :attr:`~torch.int64` |
+------------------+-------------------------------+
| :class:`float` | :attr:`~torch.float64` |
+------------------+-------------------------------+
| :class:`complex` | :attr:`~torch.complex64` |
+------------------+-------------------------------+
"""
_TYPE_TO_DTYPE = {
int: torch.int64,
float: torch.float64,
complex: torch.complex128,
}
_NUMBER_TYPES = tuple(_TYPE_TO_DTYPE.keys())
def __init__(
self,
actual: Any,
expected: Any,
*,
id: Tuple[Any, ...] = (),
rtol: Optional[float] = None,
atol: Optional[float] = None,
equal_nan: bool = False,
check_dtype: bool = False,
**other_parameters: Any,
) -> None:
actual, expected = self._process_inputs(actual, expected, id=id)
super().__init__(actual, expected, id=id, **other_parameters)
self.rtol, self.atol = get_tolerances(
*[self._TYPE_TO_DTYPE[type(input)] for input in (actual, expected)],
rtol=rtol,
atol=atol,
id=id,
)
self.equal_nan = equal_nan
self.check_dtype = check_dtype
@property
def _supported_types(self) -> Tuple[Type, ...]:
cls = list(self._NUMBER_TYPES)
if HAS_NUMPY:
cls.append(np.number)
return tuple(cls)
def _process_inputs(
self, actual: Any, expected: Any, *, id: Tuple[Any, ...]
) -> Tuple[Union[int, float, complex], Union[int, float, complex]]:
self._check_inputs_isinstance(actual, expected, cls=self._supported_types)
actual, expected = (
self._to_number(number_like, id=id) for number_like in (actual, expected)
)
return actual, expected
def _to_number(
self, number_like: Any, *, id: Tuple[Any, ...]
) -> Union[int, float, complex]:
if HAS_NUMPY and isinstance(number_like, np.number):
return number_like.item()
elif isinstance(number_like, self._NUMBER_TYPES):
return number_like # type: ignore[return-value]
else:
raise ErrorMeta(
TypeError, f"Unknown number type {type(number_like)}.", id=id
)
def compare(self) -> None:
if self.check_dtype and type(self.actual) is not type(self.expected):
self._fail(
AssertionError,
f"The (d)types do not match: {type(self.actual)} != {type(self.expected)}.",
)
if self.actual == self.expected:
return
if self.equal_nan and cmath.isnan(self.actual) and cmath.isnan(self.expected):
return
abs_diff = abs(self.actual - self.expected)
tolerance = self.atol + self.rtol * abs(self.expected)
if cmath.isfinite(abs_diff) and abs_diff <= tolerance:
return
self._fail(
AssertionError,
make_scalar_mismatch_msg(
self.actual, self.expected, rtol=self.rtol, atol=self.atol
),
)
def extra_repr(self) -> Sequence[str]:
return (
"rtol",
"atol",
"equal_nan",
"check_dtype",
)
class TensorLikePair(Pair):
"""Pair for :class:`torch.Tensor`-like inputs.
Kwargs:
allow_subclasses (bool):
rtol (Optional[float]): Relative tolerance. If specified ``atol`` must also be specified. If omitted, default
values based on the type are selected. See :func:assert_close: for details.
atol (Optional[float]): Absolute tolerance. If specified ``rtol`` must also be specified. If omitted, default
values based on the type are selected. See :func:assert_close: for details.
equal_nan (bool): If ``True``, two ``NaN`` values are considered equal. Defaults to ``False``.
check_device (bool): If ``True`` (default), asserts that corresponding tensors are on the same
:attr:`~torch.Tensor.device`. If this check is disabled, tensors on different
:attr:`~torch.Tensor.device`'s are moved to the CPU before being compared.
check_dtype (bool): If ``True`` (default), asserts that corresponding tensors have the same ``dtype``. If this
check is disabled, tensors with different ``dtype``'s are promoted to a common ``dtype`` (according to
:func:`torch.promote_types`) before being compared.
check_layout (bool): If ``True`` (default), asserts that corresponding tensors have the same ``layout``. If this
check is disabled, tensors with different ``layout``'s are converted to strided tensors before being
compared.
check_stride (bool): If ``True`` and corresponding tensors are strided, asserts that they have the same stride.
"""
def __init__(
self,
actual: Any,
expected: Any,
*,
id: Tuple[Any, ...] = (),
allow_subclasses: bool = True,
rtol: Optional[float] = None,
atol: Optional[float] = None,
equal_nan: bool = False,
check_device: bool = True,
check_dtype: bool = True,
check_layout: bool = True,
check_stride: bool = False,
**other_parameters: Any,
):
actual, expected = self._process_inputs(
actual, expected, id=id, allow_subclasses=allow_subclasses
)
super().__init__(actual, expected, id=id, **other_parameters)
self.rtol, self.atol = get_tolerances(
actual, expected, rtol=rtol, atol=atol, id=self.id
)
self.equal_nan = equal_nan
self.check_device = check_device
self.check_dtype = check_dtype
self.check_layout = check_layout
self.check_stride = check_stride
def _process_inputs(
self, actual: Any, expected: Any, *, id: Tuple[Any, ...], allow_subclasses: bool
) -> Tuple[torch.Tensor, torch.Tensor]:
directly_related = isinstance(actual, type(expected)) or isinstance(
expected, type(actual)
)
if not directly_related:
self._inputs_not_supported()
if not allow_subclasses and type(actual) is not type(expected):
self._inputs_not_supported()
actual, expected = (self._to_tensor(input) for input in (actual, expected))
for tensor in (actual, expected):
self._check_supported(tensor, id=id)
return actual, expected
def _to_tensor(self, tensor_like: Any) -> torch.Tensor:
if isinstance(tensor_like, torch.Tensor):
return tensor_like
try:
return torch.as_tensor(tensor_like)
except Exception:
self._inputs_not_supported()
def _check_supported(self, tensor: torch.Tensor, *, id: Tuple[Any, ...]) -> None:
if tensor.layout not in {
torch.strided,
torch.jagged,
torch.sparse_coo,
torch.sparse_csr,
torch.sparse_csc,
torch.sparse_bsr,
torch.sparse_bsc,
}:
raise ErrorMeta(
ValueError, f"Unsupported tensor layout {tensor.layout}", id=id
)
def compare(self) -> None:
actual, expected = self.actual, self.expected
self._compare_attributes(actual, expected)
if any(input.device.type == "meta" for input in (actual, expected)):
return
actual, expected = self._equalize_attributes(actual, expected)
self._compare_values(actual, expected)
def _compare_attributes(
self,
actual: torch.Tensor,
expected: torch.Tensor,
) -> None:
"""Checks if the attributes of two tensors match.
Always checks
- the :attr:`~torch.Tensor.shape`,
- whether both inputs are quantized or not,
- and if they use the same quantization scheme.
Checks for
- :attr:`~torch.Tensor.layout`,
- :meth:`~torch.Tensor.stride`,
- :attr:`~torch.Tensor.device`, and
- :attr:`~torch.Tensor.dtype`
are optional and can be disabled through the corresponding ``check_*`` flag during construction of the pair.
"""
def raise_mismatch_error(
attribute_name: str, actual_value: Any, expected_value: Any
) -> NoReturn:
self._fail(
AssertionError,
f"The values for attribute '{attribute_name}' do not match: {actual_value} != {expected_value}.",
)
if actual.shape != expected.shape:
raise_mismatch_error("shape", actual.shape, expected.shape)
if actual.is_quantized != expected.is_quantized:
raise_mismatch_error(
"is_quantized", actual.is_quantized, expected.is_quantized
)
elif actual.is_quantized and actual.qscheme() != expected.qscheme():
raise_mismatch_error("qscheme()", actual.qscheme(), expected.qscheme())
if actual.layout != expected.layout:
if self.check_layout:
raise_mismatch_error("layout", actual.layout, expected.layout)
elif (
actual.layout == torch.strided
and self.check_stride
and actual.stride() != expected.stride()
):
raise_mismatch_error("stride()", actual.stride(), expected.stride())
if self.check_device and actual.device != expected.device:
raise_mismatch_error("device", actual.device, expected.device)
if self.check_dtype and actual.dtype != expected.dtype:
raise_mismatch_error("dtype", actual.dtype, expected.dtype)
def _equalize_attributes(
self, actual: torch.Tensor, expected: torch.Tensor
) -> Tuple[torch.Tensor, torch.Tensor]:
"""Equalizes some attributes of two tensors for value comparison.
If ``actual`` and ``expected`` are ...
- ... not on the same :attr:`~torch.Tensor.device`, they are moved CPU memory.
- ... not of the same ``dtype``, they are promoted to a common ``dtype`` (according to
:func:`torch.promote_types`).
- ... not of the same ``layout``, they are converted to strided tensors.
Args:
actual (Tensor): Actual tensor.
expected (Tensor): Expected tensor.
Returns:
(Tuple[Tensor, Tensor]): Equalized tensors.
"""
# The comparison logic uses operators currently not supported by the MPS backends.
# See https://github.com/pytorch/pytorch/issues/77144 for details.
# TODO: Remove this conversion as soon as all operations are supported natively by the MPS backend
if actual.is_mps or expected.is_mps: # type: ignore[attr-defined]
actual = actual.cpu()
expected = expected.cpu()
if actual.device != expected.device:
actual = actual.cpu()
expected = expected.cpu()
if actual.dtype != expected.dtype:
actual_dtype = actual.dtype
expected_dtype = expected.dtype
# For uint64, this is not sound in general, which is why promote_types doesn't
# allow it, but for easy testing, we're unlikely to get confused
# by large uint64 overflowing into negative int64
if actual_dtype in [torch.uint64, torch.uint32, torch.uint16]:
actual_dtype = torch.int64
if expected_dtype in [torch.uint64, torch.uint32, torch.uint16]:
expected_dtype = torch.int64
dtype = torch.promote_types(actual_dtype, expected_dtype)
actual = actual.to(dtype)
expected = expected.to(dtype)
if actual.layout != expected.layout:
# These checks are needed, since Tensor.to_dense() fails on tensors that are already strided
actual = actual.to_dense() if actual.layout != torch.strided else actual
expected = (
expected.to_dense() if expected.layout != torch.strided else expected
)
return actual, expected
def _compare_values(self, actual: torch.Tensor, expected: torch.Tensor) -> None:
if actual.is_quantized:
compare_fn = self._compare_quantized_values
elif actual.is_sparse:
compare_fn = self._compare_sparse_coo_values
elif actual.layout in {
torch.sparse_csr,
torch.sparse_csc,
torch.sparse_bsr,
torch.sparse_bsc,
}:
compare_fn = self._compare_sparse_compressed_values
elif actual.layout == torch.jagged:
actual, expected = actual.values(), expected.values()
compare_fn = self._compare_regular_values_close
else:
compare_fn = self._compare_regular_values_close
compare_fn(
actual, expected, rtol=self.rtol, atol=self.atol, equal_nan=self.equal_nan
)
def _compare_quantized_values(
self,
actual: torch.Tensor,
expected: torch.Tensor,
*,
rtol: float,
atol: float,
equal_nan: bool,
) -> None:
"""Compares quantized tensors by comparing the :meth:`~torch.Tensor.dequantize`'d variants for closeness.
.. note::
A detailed discussion about why only the dequantized variant is checked for closeness rather than checking
the individual quantization parameters for closeness and the integer representation for equality can be
found in https://github.com/pytorch/pytorch/issues/68548.
"""
return self._compare_regular_values_close(
actual.dequantize(),
expected.dequantize(),
rtol=rtol,
atol=atol,
equal_nan=equal_nan,
identifier=lambda default_identifier: f"Quantized {default_identifier.lower()}",
)
def _compare_sparse_coo_values(
self,
actual: torch.Tensor,
expected: torch.Tensor,
*,
rtol: float,
atol: float,
equal_nan: bool,
) -> None:
"""Compares sparse COO tensors by comparing
- the number of sparse dimensions,
- the number of non-zero elements (nnz) for equality,
- the indices for equality, and
- the values for closeness.
"""
if actual.sparse_dim() != expected.sparse_dim():
self._fail(
AssertionError,
(
f"The number of sparse dimensions in sparse COO tensors does not match: "
f"{actual.sparse_dim()} != {expected.sparse_dim()}"
),
)
if actual._nnz() != expected._nnz():
self._fail(
AssertionError,
(
f"The number of specified values in sparse COO tensors does not match: "
f"{actual._nnz()} != {expected._nnz()}"
),
)
self._compare_regular_values_equal(
actual._indices(),
expected._indices(),
identifier="Sparse COO indices",
)
self._compare_regular_values_close(
actual._values(),
expected._values(),
rtol=rtol,
atol=atol,
equal_nan=equal_nan,
identifier="Sparse COO values",
)
def _compare_sparse_compressed_values(
self,
actual: torch.Tensor,
expected: torch.Tensor,
*,
rtol: float,
atol: float,
equal_nan: bool,
) -> None:
"""Compares sparse compressed tensors by comparing
- the number of non-zero elements (nnz) for equality,
- the plain indices for equality,
- the compressed indices for equality, and
- the values for closeness.
"""
format_name, compressed_indices_method, plain_indices_method = {
torch.sparse_csr: (
"CSR",
torch.Tensor.crow_indices,
torch.Tensor.col_indices,
),
torch.sparse_csc: (
"CSC",
torch.Tensor.ccol_indices,
torch.Tensor.row_indices,
),
torch.sparse_bsr: (
"BSR",
torch.Tensor.crow_indices,
torch.Tensor.col_indices,
),
torch.sparse_bsc: (
"BSC",
torch.Tensor.ccol_indices,
torch.Tensor.row_indices,
),
}[actual.layout]
if actual._nnz() != expected._nnz():
self._fail(
AssertionError,
(
f"The number of specified values in sparse {format_name} tensors does not match: "
f"{actual._nnz()} != {expected._nnz()}"
),
)
# Compressed and plain indices in the CSR / CSC / BSR / BSC sparse formates can be `torch.int32` _or_
# `torch.int64`. While the same dtype is enforced for the compressed and plain indices of a single tensor, it
# can be different between two tensors. Thus, we need to convert them to the same dtype, or the comparison will
# fail.
actual_compressed_indices = compressed_indices_method(actual)
expected_compressed_indices = compressed_indices_method(expected)
indices_dtype = torch.promote_types(
actual_compressed_indices.dtype, expected_compressed_indices.dtype
)
self._compare_regular_values_equal(
actual_compressed_indices.to(indices_dtype),
expected_compressed_indices.to(indices_dtype),
identifier=f"Sparse {format_name} {compressed_indices_method.__name__}",
)
self._compare_regular_values_equal(
plain_indices_method(actual).to(indices_dtype),
plain_indices_method(expected).to(indices_dtype),
identifier=f"Sparse {format_name} {plain_indices_method.__name__}",
)
self._compare_regular_values_close(
actual.values(),
expected.values(),
rtol=rtol,
atol=atol,
equal_nan=equal_nan,
identifier=f"Sparse {format_name} values",
)
def _compare_regular_values_equal(
self,
actual: torch.Tensor,
expected: torch.Tensor,
*,