torch.testing
- torch.testing.assert_close(actual, expected, *, allow_subclasses=True, rtol=None, atol=None, equal_nan=False, , , , ,
Asserts that actual and expected are close.
If actual and expected are strided, non-quantized, real-valued, and finite, they are considered close if
Non-finite values (-inf and inf) are only considered close if and only if they are equal. NaN’s are
only considered equal to each other if equal_nan is True.
In addition, they are only considered close if they have the same
device (if check_device is True),
dtype (if check_dtype is True),
layout (if check_layout is True), and
stride (if check_stride is ).
If either actual or expected is a meta tensor, only the attribute checks will be performed.
If actual and expected are sparse (either having COO, CSR, CSC, BSR, or BSC layout), their strided members are
checked individually. Indices, namely indices for COO, crow_indices and col_indices for CSR and BSR,
or ccol_indices and row_indices for CSC and BSC layouts, respectively,
are always checked for equality whereas the values are checked for closeness according to the definition above.
If actual and expected are quantized, they are considered close if they have the same
qscheme() and the result of dequantize() is close according to the
definition above.
actual and expected can be Tensor’s or any tensor-or-scalar-likes from which
torch.Tensor’s can be constructed with torch.as_tensor(). Except for Python scalars the input types
have to be directly related. In addition, actual and expected can be Sequence’s
or ’s in which case they are considered close if their structure matches and all
their elements are considered close according to the above definition.
actual (Any) – Actual input.
expected (Any) – Expected input.
allow_subclasses (bool) – If True (default) and except for Python scalars, inputs of directly related types
are allowed. Otherwise type equality is required.
rtol (Optional[float]) – Relative tolerance. If specified atol must also be specified. If omitted, default
values based on the dtype are selected with the below table.
atol (Optional) – Absolute tolerance. If specified must also be specified. If omitted, default values based on the are selected with the below table.
The following table displays the default rtol and atol for different dtype’s. In case of mismatching
dtype’s, the maximum of both tolerances is used.
|
|
|
|---|---|---|
|
|
>>> # tensor to tensor comparison
>>> expected = torch.tensor([1e0, 1e-1, 1e-2])
>>> actual = torch.acos(torch.cos(expected))
>>> torch.testing.assert_close(actual
>>> # scalar to scalar comparison
>>> import math
>>> expected = math.sqrt(2.0)
>>> actual = 2.0 / math.sqrt(2.0)
>>> torch.testing.assert_close(actual, expected
>>> # numpy array to numpy array comparison
>>> import numpy as np
>>> expected = np.array([1e0, 1e-1, 1e-2])
>>> actual = np.arccos(np.cos(expected))
>>>
>>> # sequence to sequence comparison
>>> import numpy as np
>>> # The types of the sequences do not have to match. They only have to have the same
>>> # length and their elements have to match.
>>> expected = [torch.tensor([1.0]), 2.0, np.array(3.0)]
>>> actual
>>> # mapping to mapping comparison
>>> from collections import OrderedDict
>>> import numpy as np
>>> foo = torch.tensor(1.0)
>>> bar = 2.0
>>> baz = np.array
>>> expected = torch.tensor([1.0, 2.0, 3.0])
>>> actual = expected.clone()
>>> # By default, directly related instances can be compared
>>> torch.testing.assert_close(torch.nn.Parameter(
:
:
>>> # NaN != NaN by default.
>>> expected = torch.tensor(float("Nan"))
>>> actual = expected.clone()
>>> torch.testing.assert_close(actual, expected)
Traceback (most recent call last):
...
AssertionError: Scalars are not close!
>>> expected = torch.tensor([1.0, 2.0, 3.0])
>>> actual = torch.tensor([1.0, 4.0, 5.0])
>>> # The default error message can be overwritten.
>>> torch.testing.assert_close(
:
:
Creates a tensor with the given shape, device, and dtype, and filled with
values uniformly drawn from [low, high).
If low or high are specified and are outside the range of the dtype’s representable
finite values then they are clamped to the lowest or highest representable finite value, respectively.
If None, then the following table describes the default values for low and high,
which depend on dtype.
|
|
|
|---|---|---|
boolean type |
|
shape (Tuple[int, ...]) – Single integer or a sequence of integers defining the shape of the output tensor.
dtype (torch.dtype) – The data type of the returned tensor.
device (Union[str, torch.device]) – The device of the returned tensor.
low (Optional[Number]) – Sets the lower limit (inclusive) of the given range. If a number is provided it is clamped to the least representable finite value of the given dtype. When (default), this value is determined based on the (see the table above). Default: .
>>> from torch.testing import make_tensor
>>> # Creates a float tensor with values in [-1, 1)
>>> make_tensor((3,), device="cpu", dtype=torch.float32, low=-1, high=1)
tensor([ 0.1205, 0.2282, -0.6380])
>>> # Creates a bool tensor on CUDA
Mappingrtoldtypecheck_device (bool) – If True (default), asserts that corresponding tensors are on the same
device. If this check is disabled, tensors on different
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
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.
msg (Optional[Union[str, Callable[[str], str]]]) – Optional error message to use in case a failure occurs during the comparison. Can also passed as callable in which case it will be called with the generated message and should return the new message.
ValueError – If no torch.Tensor can be constructed from an input.
ValueError – If only rtol or atol is specified.
AssertionError – If corresponding inputs are not Python scalars and are not directly related.
AssertionError – If allow_subclasses is False, but corresponding inputs are not Python scalars and have
different types.
AssertionError – If the inputs are Sequence’s, but their length does not match.
AssertionError – If the inputs are Mapping’s, but their set of keys do not match.
AssertionError – If corresponding tensors do not have the same shape.
AssertionError – If check_layout is True, but corresponding tensors do not have the same
layout.
AssertionError – If only one of corresponding tensors is quantized.
AssertionError – If corresponding tensors are quantized, but have different qscheme()’s.
AssertionError – If check_device is True, but corresponding tensors are not on the same
device.
AssertionError – If check_dtype is True, but corresponding tensors do not have the same dtype.
AssertionError – If check_stride is True, but corresponding strided tensors do not have the same stride.
AssertionError – If the values of corresponding tensors are not close according to the definition above.
1e-5
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
other |
|
|
unsigned integral type |
|
|
signed integral types |
|
|
floating types |
|
|
complex types |
|
|
NonedtypeNonehigh (Optional[Number]) –
Sets the upper limit (exclusive) of the given range. If a number is provided it is
clamped to the greatest representable finite value of the given dtype. When None (default) this value
is determined based on the dtype (see the table above). Default: None.
requires_grad (Optional[bool]) – If autograd should record operations on the returned tensor. Default: False.
noncontiguous (Optional[bool]) – If True, the returned tensor will be noncontiguous. This argument is
ignored if the constructed tensor has fewer than two elements. Mutually exclusive with memory_format.
exclude_zero (Optional[bool]) – If True then zeros are replaced with the dtype’s small positive value
depending on the dtype. For bool and integer types zero is replaced with one. For floating
point types it is replaced with the dtype’s smallest positive normal number (the “tiny” value of the
dtype’s finfo() object), and for complex types it is replaced with a complex number
whose real and imaginary parts are both the smallest positive normal number representable by the complex
type. Default False.
memory_format (Optional[torch.memory_format]) – The memory format of the returned tensor. Mutually exclusive
with noncontiguous.
ValueError – If requires_grad=True is passed for integral dtype
ValueError – If low >= high.
ValueError – If either low or high is nan.
ValueError – If both noncontiguous and memory_format are passed.
TypeError – If dtype isn’t supported by this function.