Skip to content

Commit bc73aff

Browse files
pmeierpytorchmergebot
authored andcommitted
prepare removal of deprecated functionality in torch.testing (pytorch#87969)
_Redo of pytorch#86586 with all BC breaking changes granularly placed into separate commits._ --- Per title. Deprecation happened on Feb 25, 2022 in c6f1bbc, which made it into the 1.12 release. Since it is now 245 days later and the next release will be 1.14, the removals later in the stack comply with the [BC policy](https://github.com/pytorch/pytorch/wiki/PyTorch's-Python-Frontend-Backward-and-Forward-Compatibility-Policy#minimizing-the-disruption-of-bc-breaking-changes). Pull Request resolved: pytorch#87969 Approved by: https://github.com/mruberry
1 parent 0fc7de3 commit bc73aff

32 files changed

+198
-146
lines changed

caffe2/python/operator_test/_utils.py

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
"""
2+
This file only exists since `torch.testing.assert_allclose` is deprecated, but used extensively throughout the tests in
3+
this package. The replacement `torch.testing.assert_close` doesn't support one feature that is needed here: comparison
4+
between numpy arrays and torch tensors. See https://github.com/pytorch/pytorch/issues/61844 for the reasoning why this
5+
was removed.
6+
"""
7+
8+
import torch
9+
from typing import Tuple, Any, Optional
10+
11+
_DTYPE_PRECISIONS = {
12+
torch.float16: (1e-3, 1e-3),
13+
torch.float32: (1e-4, 1e-5),
14+
torch.float64: (1e-5, 1e-8),
15+
}
16+
17+
18+
def _get_default_rtol_and_atol(actual: torch.Tensor, expected: torch.Tensor) -> Tuple[float, float]:
19+
actual_rtol, actual_atol = _DTYPE_PRECISIONS.get(actual.dtype, (0.0, 0.0))
20+
expected_rtol, expected_atol = _DTYPE_PRECISIONS.get(expected.dtype, (0.0, 0.0))
21+
return max(actual_rtol, expected_rtol), max(actual_atol, expected_atol)
22+
23+
24+
def assert_allclose(
25+
actual: Any,
26+
expected: Any,
27+
rtol: Optional[float] = None,
28+
atol: Optional[float] = None,
29+
equal_nan: bool = True,
30+
msg: str = "",
31+
) -> None:
32+
if not isinstance(actual, torch.Tensor):
33+
actual = torch.tensor(actual)
34+
if not isinstance(expected, torch.Tensor):
35+
expected = torch.tensor(expected, dtype=actual.dtype)
36+
37+
if rtol is None and atol is None:
38+
rtol, atol = _get_default_rtol_and_atol(actual, expected)
39+
40+
torch.testing.assert_close(
41+
actual,
42+
expected,
43+
rtol=rtol,
44+
atol=atol,
45+
equal_nan=equal_nan,
46+
check_device=True,
47+
check_dtype=False,
48+
check_stride=False,
49+
msg=msg or None,
50+
)

caffe2/python/operator_test/layer_norm_op_test.py

+14-16
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818

1919
import unittest
2020

21+
from ._utils import assert_allclose
22+
2123

2224
def _layer_norm_ref(axis, epsilon, X):
2325
left = int(np.prod(X.shape[:axis]))
@@ -254,10 +256,9 @@ def test_layer_norm_op_c10_preallocated_outputs(
254256
actual_mean = self.ws.fetch_blob('mean')
255257
actual_std = self.ws.fetch_blob('std')
256258

257-
torch.testing.assert_allclose(
258-
expected_norm, actual_norm, rtol=1e-4, atol=1e-4)
259-
torch.testing.assert_allclose(expected_mean, actual_mean)
260-
torch.testing.assert_allclose(expected_std, actual_std)
259+
assert_allclose(expected_norm, actual_norm, rtol=1e-4, atol=1e-4)
260+
assert_allclose(expected_mean, actual_mean)
261+
assert_allclose(expected_std, actual_std)
261262

262263
@given(X=hu.tensor(min_dim=2),
263264
eps=st.floats(1e-5, 1e-3),
@@ -280,10 +281,9 @@ def test_layer_norm_op_pytorch(self, X, eps, elementwise_affine, gc, dc):
280281
actual_norm, actual_mean, actual_std = torch.ops._caffe2.LayerNorm(
281282
torch.tensor(X), None, None, axis, eps)
282283

283-
torch.testing.assert_allclose(
284-
expected_norm, actual_norm, rtol=1e-4, atol=1e-4)
285-
torch.testing.assert_allclose(expected_mean, actual_mean)
286-
torch.testing.assert_allclose(expected_std, actual_std)
284+
assert_allclose(expected_norm, actual_norm, rtol=1e-4, atol=1e-4)
285+
assert_allclose(expected_mean, actual_mean)
286+
assert_allclose(expected_std, actual_std)
287287

288288
# Test case is using workspace.has_cuda_support and not
289289
# workspace.has_gpu_support to exclude it from HIP because tensor interop
@@ -313,10 +313,9 @@ def test_layer_norm_op_pytorch_cuda(self, X, eps, elementwise_affine):
313313
actual_norm, actual_mean, actual_std = torch.ops._caffe2.LayerNorm(
314314
torch.tensor(X).cuda(), None, None, axis, eps)
315315

316-
torch.testing.assert_allclose(
317-
expected_norm, actual_norm.cpu(), rtol=1e-4, atol=1e-4)
318-
torch.testing.assert_allclose(expected_mean, actual_mean.cpu())
319-
torch.testing.assert_allclose(expected_std, actual_std.cpu())
316+
assert_allclose(expected_norm, actual_norm, rtol=1e-4, atol=1e-4)
317+
assert_allclose(expected_mean, actual_mean)
318+
assert_allclose(expected_std, actual_std)
320319

321320
@given(X=hu.tensor(min_dim=2),
322321
eps=st.floats(1e-5, 1e-3),
@@ -352,10 +351,9 @@ def jit_layer_norm(
352351
actual_norm, actual_mean, actual_std = jit_layer_norm(
353352
torch.tensor(X), None, None, axis, eps, elementwise_affine)
354353

355-
torch.testing.assert_allclose(
356-
expected_norm, actual_norm, rtol=1e-4, atol=1e-4)
357-
torch.testing.assert_allclose(expected_mean, actual_mean)
358-
torch.testing.assert_allclose(expected_std, actual_std)
354+
assert_allclose(expected_norm, actual_norm, rtol=1e-4, atol=1e-4)
355+
assert_allclose(expected_mean, actual_mean)
356+
assert_allclose(expected_std, actual_std)
359357

360358
@given(X=hu.tensor(min_dim=2), **hu.gcs)
361359
def test_layer_norm_brew_wrapper(self, X, gc, dc):

caffe2/python/operator_test/torch_integration_test.py

+34-32
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111
from hypothesis import given, settings
1212
from scipy.stats import norm
1313

14+
from ._utils import assert_allclose
15+
1416

1517
def generate_rois(roi_counts, im_dims):
1618
assert len(roi_counts) == len(im_dims)
@@ -172,7 +174,7 @@ def bbox_transform_ref():
172174
legacy_plus_one=True,
173175
)
174176

175-
torch.testing.assert_allclose(box_out, a)
177+
assert_allclose(box_out, a)
176178

177179
@given(
178180
roi_counts=st.lists(st.integers(0, 5), min_size=1, max_size=10),
@@ -268,7 +270,7 @@ def box_with_nms_limit_ref():
268270
)
269271

270272
for o, o_ref in zip(outputs, output_refs):
271-
torch.testing.assert_allclose(o, o_ref)
273+
assert_allclose(o, o_ref)
272274

273275
@given(
274276
dim_1=st.integers(min_value=10, max_value=10),
@@ -314,7 +316,7 @@ def sparse_to_dense_mask_ref(return_presence_mask=False):
314316
mask=mask,
315317
)
316318

317-
torch.testing.assert_allclose(output, a)
319+
assert_allclose(output, a)
318320

319321
# Testing return_presence_mask = True
320322
output, presence_mask = sparse_to_dense_mask_ref(return_presence_mask=True)
@@ -330,8 +332,8 @@ def sparse_to_dense_mask_ref(return_presence_mask=False):
330332
return_presence_mask=True,
331333
)
332334

333-
torch.testing.assert_allclose(output, a)
334-
torch.testing.assert_allclose(presence_mask, b)
335+
assert_allclose(output, a)
336+
assert_allclose(presence_mask, b)
335337

336338
@given(
337339
A=st.integers(min_value=4, max_value=4),
@@ -382,8 +384,8 @@ def generate_proposals_ref():
382384
1.0,
383385
legacy_plus_one=True,
384386
)
385-
torch.testing.assert_allclose(rois, a)
386-
torch.testing.assert_allclose(rois_probs, b)
387+
assert_allclose(rois, a)
388+
assert_allclose(rois_probs, b)
387389

388390
@given(
389391
bsz=st.integers(1, 5),
@@ -461,9 +463,9 @@ def inference_lstm_ref():
461463
a, b, c = torch.ops._caffe2.InferenceLSTM(
462464
lstm_in, num_layers, has_biases, batch_first, is_bidirectional
463465
)
464-
torch.testing.assert_allclose(output, a)
465-
torch.testing.assert_allclose(hidden, b)
466-
torch.testing.assert_allclose(cell, c)
466+
assert_allclose(output, a)
467+
assert_allclose(hidden, b)
468+
assert_allclose(cell, c)
467469

468470
# Test case is using workspace.has_cuda_support and not workspace.has_gpu_support
469471
# to exclude it from HIP because tensor interop doesn't work for HIP tensors yet
@@ -517,8 +519,8 @@ def generate_proposals_ref():
517519
1.0,
518520
legacy_plus_one=True,
519521
)
520-
torch.testing.assert_allclose(rois, a.cpu())
521-
torch.testing.assert_allclose(rois_probs, b.cpu())
522+
assert_allclose(rois, a.cpu())
523+
assert_allclose(rois_probs, b.cpu())
522524

523525
@given(
524526
N=st.integers(min_value=1, max_value=2),
@@ -567,7 +569,7 @@ def roi_align_ref(_feature, _rois):
567569
sampling_ratio=0,
568570
aligned=False,
569571
)
570-
torch.testing.assert_allclose(roi_feature_ref, roi_feature.cpu())
572+
assert_allclose(roi_feature_ref, roi_feature.cpu())
571573

572574
def test_roi_align_cpu(self):
573575
self._test_roi_align(device="cpu")
@@ -624,7 +626,7 @@ def roi_align_ref(_feature, _rois):
624626
sampling_ratio=0,
625627
aligned=False,
626628
)
627-
torch.testing.assert_allclose(roi_feature_ref, roi_feature.cpu())
629+
assert_allclose(roi_feature_ref, roi_feature.cpu())
628630

629631
def test_roi_align_rotated_cpu(self):
630632
self._test_roi_align_rotated(device="cpu")
@@ -674,9 +676,9 @@ def test_collect_and_distribute_fpn_rpn_proposals_op(self, roi_counts):
674676
rois_idx_restore_int32 = fpn_outputs[-1]
675677

676678
# [rois] + fpn_outputs should be equal to all_outputs
677-
torch.testing.assert_allclose(rois, all_outputs[0])
679+
assert_allclose(rois, all_outputs[0])
678680
for x, y in zip(fpn_outputs, all_outputs[1:]):
679-
torch.testing.assert_allclose(x, y)
681+
assert_allclose(x, y)
680682

681683
@given(X=hu.tensor(), fast_gelu=st.booleans())
682684
def _test_gelu_op(self, X, fast_gelu, device):
@@ -688,7 +690,7 @@ def _gelu_ref(_X):
688690

689691
rtol = 1e-3 if fast_gelu else 1e-4
690692
atol = 1e-5
691-
torch.testing.assert_allclose(
693+
assert_allclose(
692694
expected_output, actual_output.cpu(), rtol=rtol, atol=atol
693695
)
694696

@@ -719,7 +721,7 @@ def _lengths_ref(X, Y):
719721
torch.tensor(data), torch.tensor(lengths, dtype=torch.int32)
720722
)
721723

722-
torch.testing.assert_allclose(expected_output, actual_output.cpu())
724+
assert_allclose(expected_output, actual_output.cpu())
723725

724726
def _test_lengths_sum_op(self, device):
725727
self._test_lengths_op("LengthsSum", torch.ops._caffe2.LengthsSum, device)
@@ -775,7 +777,7 @@ def _resize_nearest_ref(X):
775777
height_scale=1.5,
776778
)
777779

778-
torch.testing.assert_allclose(expected_output, actual_output.cpu())
780+
assert_allclose(expected_output, actual_output.cpu())
779781

780782
def test_resize_nearest_op_cpu(self):
781783
return self._test_resize_nearest_op("cpu")
@@ -838,26 +840,26 @@ def _piecewise_linear_ref(X):
838840
binary_input,
839841
)
840842

841-
torch.testing.assert_allclose(torch.tensor(expected_output), actual_output)
843+
assert_allclose(torch.tensor(expected_output), actual_output)
842844

843845
def test_alias_with_name_is_in_place(self):
844846
device = "cuda" if workspace.has_cuda_support else "cpu"
845847
x = torch.tensor([3., 42.]).to(device=device)
846848
y = torch.ops._caffe2.AliasWithName(x, "new_name")
847849
x[1] = 6
848-
torch.testing.assert_allclose(x, torch.tensor([3., 6.]).to(device=device))
850+
assert_allclose(x, torch.tensor([3., 6.]).to(device=device))
849851
# y should also change because y is alias of x
850-
torch.testing.assert_allclose(y, torch.tensor([3., 6.]).to(device=device))
852+
assert_allclose(y, torch.tensor([3., 6.]).to(device=device))
851853

852854
@unittest.skipIf(not workspace.has_cuda_support, "No cuda support")
853855
def test_copy_between_cpu_and_gpu(self):
854856
x_cpu_ref = torch.tensor([1., 2., 3.])
855857
x_gpu_ref = x_cpu_ref.to("cuda")
856858

857859
x_gpu = torch.ops._caffe2.CopyCPUToGPU(x_cpu_ref)
858-
torch.testing.assert_allclose(x_gpu, x_gpu_ref)
860+
assert_allclose(x_gpu, x_gpu_ref)
859861
x_cpu = torch.ops._caffe2.CopyGPUToCPU(x_gpu)
860-
torch.testing.assert_allclose(x_cpu, x_cpu_ref)
862+
assert_allclose(x_cpu, x_cpu_ref)
861863

862864
def test_index_hash_op(self):
863865
data = np.random.randint(low=0, high=1000, size=(4, 4, 4))
@@ -873,7 +875,7 @@ def _index_hash_ref(X):
873875
torch.tensor(data), seed=0, modulo=100
874876
)
875877

876-
torch.testing.assert_allclose(expected_output, actual_output.cpu())
878+
assert_allclose(expected_output, actual_output.cpu())
877879

878880
def test_bucketize_op(self):
879881
data = np.random.rand(8, 10).astype(np.float32) * 1000
@@ -889,7 +891,7 @@ def _bucketize_ref(X):
889891

890892
expected_output = _bucketize_ref(data)
891893
actual_output = torch.ops._caffe2.Bucketize(torch.tensor(data), boundaries)
892-
torch.testing.assert_allclose(expected_output, actual_output.cpu())
894+
assert_allclose(expected_output, actual_output.cpu())
893895

894896
@given(X=hu.tensor(), eps=st.floats(min_value=1e-4, max_value=1e-2))
895897
def test_logit(self, X, eps):
@@ -901,7 +903,7 @@ def ref(X, eps):
901903

902904
expected_output = ref(X, eps)
903905
actual_output = torch.ops._caffe2.Logit(torch.tensor(X), eps)
904-
torch.testing.assert_allclose(expected_output, actual_output.cpu())
906+
assert_allclose(expected_output, actual_output.cpu())
905907

906908
def test_percentile(self):
907909
original_values = np.array([[3.0, 5.0, 3], [5.0, 1.0, 6.0]]).astype(np.float32)
@@ -926,7 +928,7 @@ def _percentile_ref(original_values, value_to_pct, lengths):
926928
torch.tensor(value_to_pct),
927929
torch.tensor(lengths),
928930
)
929-
torch.testing.assert_allclose(expected_output, actual_output.cpu())
931+
assert_allclose(expected_output, actual_output.cpu())
930932

931933
def test_batch_bucket_one_hot_op(self):
932934
data = np.array([[2, 3], [4, 1], [2, 5]]).astype(np.float32)
@@ -947,7 +949,7 @@ def _batch_bucket_one_hot_ref(data, lengths, boundaries):
947949
actual_output = torch.ops._caffe2.BatchBucketOneHot(
948950
torch.tensor(data), torch.tensor(lengths), torch.tensor(boundaries)
949951
)
950-
torch.testing.assert_allclose(expected_output, actual_output.cpu())
952+
assert_allclose(expected_output, actual_output.cpu())
951953

952954
def test_gather_ranges_to_dense_op(self):
953955
data = np.array([1, 2, 3, 4, 5, 6, 7, 8])
@@ -1033,8 +1035,8 @@ def _merge_id_lists(lengths, values):
10331035
torch.tensor(values[1]),
10341036
]
10351037
)
1036-
torch.testing.assert_allclose(expected_merged_lengths, output_merged_lengths)
1037-
torch.testing.assert_allclose(expected_merged_values, output_merged_values)
1038+
assert_allclose(expected_merged_lengths, output_merged_lengths)
1039+
assert_allclose(expected_merged_values, output_merged_values)
10381040

10391041
def test_learning_rate(self):
10401042
base_lr = 0.05
@@ -1097,7 +1099,7 @@ def test_pack_segments(self):
10971099
packed_tensor, _ = torch.ops._caffe2.PackSegments(lengths, s)
10981100
self.assertEqual(packed_tensor.numpy().shape, (2, 2, 3, 3))
10991101
unpacked_tensor = torch.ops._caffe2.UnpackSegments(lengths, packed_tensor)
1100-
torch.testing.assert_allclose(s, unpacked_tensor)
1102+
assert_allclose(s, unpacked_tensor)
11011103

11021104

11031105
if __name__ == "__main__":

docs/source/fx.rst

+2-2
Original file line numberDiff line numberDiff line change
@@ -1039,7 +1039,7 @@ Miscellanea
10391039
traced.eval()
10401040

10411041
x = torch.randn(5, 3)
1042-
torch.testing.assert_allclose(traced(x), x)
1042+
torch.testing.assert_close(traced(x), x)
10431043
"""
10441044
AssertionError: Tensor-likes are not close!
10451045

@@ -1071,7 +1071,7 @@ Miscellanea
10711071
traced.eval()
10721072

10731073
x = torch.randn(5, 3)
1074-
torch.testing.assert_allclose(traced(x), x)
1074+
torch.testing.assert_close(traced(x), x)
10751075

10761076
- Because of this difference, consider marking modules that interact with the ``training`` flag dynamically as leaf modules.
10771077

0 commit comments

Comments
 (0)