评价此页

torch.testing#

创建日期:2021年5月7日 | 最后更新:2025年6月10日

torch.testing.assert_close(actual, expected, *, allow_subclasses=True, rtol=None, atol=None, equal_nan=False, check_device=True, check_dtype=True, check_layout=True, check_stride=False, msg=None)[源码]#

断言 actual(实际值)和 expected(预期值)非常接近。

如果 actualexpected 是跨步(strided)、非量化、实数且有限的,则当以下条件满足时,认为它们是接近的:

actualexpectedatol+rtolexpected\lvert \text{actual} - \text{expected} \rvert \le \texttt{atol} + \texttt{rtol} \cdot \lvert \text{expected} \rvert

非有限值(-infinf)仅在它们相等时才被视为接近。当且仅当 equal_nanTrue 时,NaN 才被视为彼此相等。

此外,只有当它们具有相同的以下属性时,才被视为接近:

  • device(如果 check_deviceTrue),

  • dtype(如果 check_dtypeTrue),

  • layout(如果 check_layoutTrue),以及

  • 步长(stride,如果 check_strideTrue)。

如果 actualexpected 是元张量(meta tensor),则仅执行属性检查。

如果 actualexpected 是稀疏的(具有 COO、CSR、CSC、BSR 或 BSC 布局),则会对它们的跨步成员进行单独检查。索引(即 COO 的 indices,CSR 和 BSR 的 crow_indicescol_indices,或者 CSC 和 BSC 布局中对应的 ccol_indicesrow_indices)总是会被检查是否相等,而值则根据上述定义检查是否接近。

如果 actualexpected 是量化的,当它们具有相同的 qscheme()dequantize() 的结果根据上述定义接近时,它们被视为接近。

actualexpected 可以是 Tensor 或任何可以使用 torch.as_tensor() 构建 torch.Tensor 的张量或标量类对象。除 Python 标量外,输入类型必须直接相关。此外,actualexpected 可以是 Sequence(序列)或 Mapping(映射),在这种情况下,如果它们的结构匹配且所有元素根据上述定义均被视为接近,则它们被视为接近。

注意

Python 标量是类型关系要求的一个例外,因为它们的 type()(即 intfloatcomplex)等同于类张量对象的 dtype。因此,可以检查不同类型的 Python 标量,但这需要设置 check_dtype=False

参数:
  • actual (Any) – 实际输入。

  • expected (Any) – 预期输入。

  • allow_subclasses (bool) – 如果为 True(默认值),除 Python 标量外,允许直接相关类型的输入。否则要求类型完全相等。

  • rtol (Optional[float]) – 相对容差。如果指定了此参数,则必须同时指定 atol。如果省略,则根据下表选择基于 dtype 的默认值。

  • atol (Optional[float]) – 绝对容差。如果指定了此参数,则必须同时指定 rtol。如果省略,则根据下表选择基于 dtype 的默认值。

  • equal_nan (Union[bool, str]) – 如果为 True,两个 NaN 值将被视为相等。

  • check_device (bool) – 如果为 True(默认值),断言对应的张量位于相同的 device 上。如果禁用此检查,不同 device 上的张量在比较前会被移动到 CPU。

  • check_dtype (bool) – 如果为 True(默认值),断言对应的张量具有相同的 dtype。如果禁用此检查,不同 dtype 的张量在比较前会提升为公共的 dtype(根据 torch.promote_types())。

  • check_layout (bool) – 如果为 True(默认值),断言对应的张量具有相同的 layout。如果禁用此检查,不同 layout 的张量在比较前会转换为跨步张量。

  • check_stride (bool) – 如果为 True 且对应的张量是跨步的,断言它们具有相同的步长。

  • msg (Optional[Union[str, Callable[[str], str]]]) – 如果比较失败,可选的错误消息。也可以作为可调用对象传入,此时它将接收生成的错误消息并应返回新的消息。

抛出:

下表显示了不同 dtype 的默认 rtolatol。如果 dtype 不匹配,则取两者容差的最大值。

dtype

rtol

atol

float16

1e-3

1e-5

bfloat16

1.6e-2

1e-5

float32

1.3e-6

1e-5

float64

1e-7

1e-7

complex32

1e-3

1e-5

complex64

1.3e-6

1e-5

complex128

1e-7

1e-7

quint8

1.3e-6

1e-5

quint2x4

1.3e-6

1e-5

quint4x2

1.3e-6

1e-5

qint8

1.3e-6

1e-5

qint32

1.3e-6

1e-5

other

0.0

0.0

注意

assert_close() 具有高度可配置性,且默认设置严格。鼓励用户使用 partial() 函数以适应其使用场景。例如,如果需要相等性检查,可以定义一个默认对所有 dtype 使用零容差的 assert_equal

>>> import functools
>>> assert_equal = functools.partial(torch.testing.assert_close, rtol=0, atol=0)
>>> assert_equal(1e-9, 1e-10)
Traceback (most recent call last):
...
AssertionError: Scalars are not equal!

Expected 1e-10 but got 1e-09.
Absolute difference: 9.000000000000001e-10
Relative difference: 9.0

示例

>>> # tensor to tensor comparison
>>> expected = torch.tensor([1e0, 1e-1, 1e-2])
>>> actual = torch.acos(torch.cos(expected))
>>> torch.testing.assert_close(actual, expected)
>>> # 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))
>>> torch.testing.assert_close(actual, 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 = tuple(expected)
>>> torch.testing.assert_close(actual, expected)
>>> # mapping to mapping comparison
>>> from collections import OrderedDict
>>> import numpy as np
>>> foo = torch.tensor(1.0)
>>> bar = 2.0
>>> baz = np.array(3.0)
>>> # The types and a possible ordering of mappings do not have to match. They only
>>> # have to have the same set of keys and their elements have to match.
>>> expected = OrderedDict([("foo", foo), ("bar", bar), ("baz", baz)])
>>> actual = {"baz": baz, "bar": bar, "foo": foo}
>>> torch.testing.assert_close(actual, expected)
>>> 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(actual), expected)
>>> # This check can be made more strict with allow_subclasses=False
>>> torch.testing.assert_close(
...     torch.nn.Parameter(actual), expected, allow_subclasses=False
... )
Traceback (most recent call last):
...
TypeError: No comparison pair was able to handle inputs of type
<class 'torch.nn.parameter.Parameter'> and <class 'torch.Tensor'>.
>>> # If the inputs are not directly related, they are never considered close
>>> torch.testing.assert_close(actual.numpy(), expected)
Traceback (most recent call last):
...
TypeError: No comparison pair was able to handle inputs of type <class 'numpy.ndarray'>
and <class 'torch.Tensor'>.
>>> # Exceptions to these rules are Python scalars. They can be checked regardless of
>>> # their type if check_dtype=False.
>>> torch.testing.assert_close(1.0, 1, check_dtype=False)
>>> # 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 nan but got nan.
Absolute difference: nan (up to 1e-05 allowed)
Relative difference: nan (up to 1.3e-06 allowed)
>>> torch.testing.assert_close(actual, expected, equal_nan=True)
>>> 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(
...     actual, expected, msg="Argh, the tensors are not close!"
... )
Traceback (most recent call last):
...
AssertionError: Argh, the tensors are not close!
>>> # If msg is a callable, it can be used to augment the generated message with
>>> # extra information
>>> torch.testing.assert_close(
...     actual, expected, msg=lambda msg: f"Header\n\n{msg}\n\nFooter"
... )
Traceback (most recent call last):
...
AssertionError: Header

Tensor-likes are not close!

Mismatched elements: 2 / 3 (66.7%)
Greatest absolute difference: 2.0 at index (1,) (up to 1e-05 allowed)
Greatest relative difference: 1.0 at index (1,) (up to 1.3e-06 allowed)

Footer
torch.testing.make_tensor(*shape, dtype, device, low=None, high=None, requires_grad=False, noncontiguous=False, exclude_zero=False, memory_format=None)[源码]#

创建一个具有给定 shapedevicedtype 的张量,其值均匀地从 [low, high) 区间抽取。

如果指定了 lowhigh 且它们超出了该 dtype 可表示有限值的范围,则它们会分别被截断(clamp)到可表示的最小或最大有限值。如果为 None,则下表描述了依赖于 dtypelowhigh 的默认值。

dtype

low

high

布尔类型

0

2

无符号整型

0

10

有符号整型

-9

10

浮点类型

-9

9

复数类型

-9

9

参数:
  • shape (Tuple[int, ...]) – 单个整数或整数序列,定义输出张量的形状。

  • dtype (torch.dtype) – 返回张量的数据类型。

  • device (Union[str, torch.device]) – 返回张量的设备。

  • low (Optional[Number]) – 设置给定范围的下限(包含)。如果提供了数字,它会被截断到给定 dtype 的最小可表示有限值。当为 None(默认值)时,该值由 dtype 决定(见上表)。默认值:None

  • high (Optional[Number]) –

    设置给定范围的上限(不包含)。如果提供了数字,它会被截断到给定 dtype 的最大可表示有限值。当为 None(默认值)时,该值由 dtype 决定(见上表)。默认值:None

    2.1 版本弃用:对于浮点或复数类型,将 low==high 传递给 make_tensor() 在 2.1 版本中已被弃用,并将于 2.3 版本移除。请改用 torch.full()

  • requires_grad (Optional[bool]) – 是否让 autograd 记录对返回张量的操作。默认值:False

  • noncontiguous (Optional[bool]) – 如果为 True,返回的张量将是不连续的(noncontiguous)。如果构建的张量少于两个元素,此参数将被忽略。与 memory_format 互斥。

  • exclude_zero (Optional[bool]) – 如果为 True,则零将被根据 dtype 的小正数值替换。对于布尔和整数类型,零被替换为 1。对于浮点类型,它被替换为该 dtype 的最小正规格化数(dtypefinfo() 对象的 “tiny” 值),对于复数类型,它被替换为一个实部和虚部均为该复数类型可表示的最小正规格化数的复数。默认值:False

  • memory_format (Optional[torch.memory_format]) – 返回张量的内存格式。与 noncontiguous 互斥。

抛出:
  • ValueError – 如果为整型 dtype 传递了 requires_grad=True

  • ValueError – 如果 low >= high

  • ValueError – 如果 lowhighnan

  • ValueError – 如果同时传递了 noncontiguousmemory_format

  • TypeError – 如果此函数不支持 dtype

返回类型:

张量

示例

>>> 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
>>> make_tensor((2, 2), device="cuda", dtype=torch.bool)
tensor([[False, False],
        [False, True]], device='cuda:0')
torch.testing.assert_allclose(actual, expected, rtol=None, atol=None, equal_nan=True, msg='')[源码]#

警告

torch.testing.assert_allclose()1.12 版本起被弃用,并将于未来版本中移除。请改用 torch.testing.assert_close()。您可以在 此处 找到详细的升级指南。