-
Notifications
You must be signed in to change notification settings - Fork 7k
/
test_transforms_v2.py
5785 lines (4695 loc) · 234 KB
/
test_transforms_v2.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
import contextlib
import decimal
import functools
import inspect
import itertools
import math
import pickle
import random
import re
import sys
from copy import deepcopy
from pathlib import Path
from unittest import mock
import numpy as np
import PIL.Image
import pytest
import torch
import torchvision.ops
import torchvision.transforms.v2 as transforms
from common_utils import (
assert_equal,
cache,
cpu_and_cuda,
freeze_rng_state,
ignore_jit_no_profile_information_warning,
make_bounding_boxes,
make_detection_masks,
make_image,
make_image_pil,
make_image_tensor,
make_segmentation_mask,
make_video,
make_video_tensor,
needs_cuda,
set_rng_seed,
)
from torch import nn
from torch.testing import assert_close
from torch.utils._pytree import tree_flatten, tree_map
from torch.utils.data import DataLoader, default_collate
from torchvision import tv_tensors
from torchvision.ops.boxes import box_iou
from torchvision.transforms._functional_tensor import _max_value as get_max_value
from torchvision.transforms.functional import pil_modes_mapping, to_pil_image
from torchvision.transforms.v2 import functional as F
from torchvision.transforms.v2._utils import check_type, is_pure_tensor
from torchvision.transforms.v2.functional._geometry import _get_perspective_coeffs
from torchvision.transforms.v2.functional._utils import _get_kernel, _register_kernel_internal
# turns all warnings into errors for this module
pytestmark = pytest.mark.filterwarnings("error")
@pytest.fixture(autouse=True)
def fix_rng_seed():
set_rng_seed(0)
yield
def _to_tolerances(maybe_tolerance_dict):
if not isinstance(maybe_tolerance_dict, dict):
return dict(rtol=None, atol=None)
tolerances = dict(rtol=0, atol=0)
tolerances.update(maybe_tolerance_dict)
return tolerances
def _check_kernel_cuda_vs_cpu(kernel, input, *args, rtol, atol, **kwargs):
"""Checks if the kernel produces closes results for inputs on GPU and CPU."""
if input.device.type != "cuda":
return
input_cuda = input.as_subclass(torch.Tensor)
input_cpu = input_cuda.to("cpu")
with freeze_rng_state():
actual = kernel(input_cuda, *args, **kwargs)
with freeze_rng_state():
expected = kernel(input_cpu, *args, **kwargs)
assert_close(actual, expected, check_device=False, rtol=rtol, atol=atol)
@cache
def _script(obj):
try:
return torch.jit.script(obj)
except Exception as error:
name = getattr(obj, "__name__", obj.__class__.__name__)
raise AssertionError(f"Trying to `torch.jit.script` '{name}' raised the error above.") from error
def _check_kernel_scripted_vs_eager(kernel, input, *args, rtol, atol, **kwargs):
"""Checks if the kernel is scriptable and if the scripted output is close to the eager one."""
if input.device.type != "cpu":
return
kernel_scripted = _script(kernel)
input = input.as_subclass(torch.Tensor)
with ignore_jit_no_profile_information_warning():
actual = kernel_scripted(input, *args, **kwargs)
expected = kernel(input, *args, **kwargs)
assert_close(actual, expected, rtol=rtol, atol=atol)
def _check_kernel_batched_vs_unbatched(kernel, input, *args, rtol, atol, **kwargs):
"""Checks if the kernel produces close results for batched and unbatched inputs."""
unbatched_input = input.as_subclass(torch.Tensor)
for batch_dims in [(2,), (2, 1)]:
repeats = [*batch_dims, *[1] * input.ndim]
actual = kernel(unbatched_input.repeat(repeats), *args, **kwargs)
expected = kernel(unbatched_input, *args, **kwargs)
# We can't directly call `.repeat()` on the output, since some kernel also return some additional metadata
if isinstance(expected, torch.Tensor):
expected = expected.repeat(repeats)
else:
tensor, *metadata = expected
expected = (tensor.repeat(repeats), *metadata)
assert_close(actual, expected, rtol=rtol, atol=atol)
for degenerate_batch_dims in [(0,), (5, 0), (0, 5)]:
degenerate_batched_input = torch.empty(
degenerate_batch_dims + input.shape, dtype=input.dtype, device=input.device
)
output = kernel(degenerate_batched_input, *args, **kwargs)
# Most kernels just return a tensor, but some also return some additional metadata
if not isinstance(output, torch.Tensor):
output, *_ = output
assert output.shape[: -input.ndim] == degenerate_batch_dims
def check_kernel(
kernel,
input,
*args,
check_cuda_vs_cpu=True,
check_scripted_vs_eager=True,
check_batched_vs_unbatched=True,
**kwargs,
):
initial_input_version = input._version
output = kernel(input.as_subclass(torch.Tensor), *args, **kwargs)
# Most kernels just return a tensor, but some also return some additional metadata
if not isinstance(output, torch.Tensor):
output, *_ = output
# check that no inplace operation happened
assert input._version == initial_input_version
if kernel not in {F.to_dtype_image, F.to_dtype_video}:
assert output.dtype == input.dtype
assert output.device == input.device
if check_cuda_vs_cpu:
_check_kernel_cuda_vs_cpu(kernel, input, *args, **kwargs, **_to_tolerances(check_cuda_vs_cpu))
if check_scripted_vs_eager:
_check_kernel_scripted_vs_eager(kernel, input, *args, **kwargs, **_to_tolerances(check_scripted_vs_eager))
if check_batched_vs_unbatched:
_check_kernel_batched_vs_unbatched(kernel, input, *args, **kwargs, **_to_tolerances(check_batched_vs_unbatched))
def _check_functional_scripted_smoke(functional, input, *args, **kwargs):
"""Checks if the functional can be scripted and the scripted version can be called without error."""
if not isinstance(input, tv_tensors.Image):
return
functional_scripted = _script(functional)
with ignore_jit_no_profile_information_warning():
functional_scripted(input.as_subclass(torch.Tensor), *args, **kwargs)
def check_functional(functional, input, *args, check_scripted_smoke=True, **kwargs):
unknown_input = object()
with pytest.raises(TypeError, match=re.escape(str(type(unknown_input)))):
functional(unknown_input, *args, **kwargs)
with mock.patch("torch._C._log_api_usage_once", wraps=torch._C._log_api_usage_once) as spy:
output = functional(input, *args, **kwargs)
spy.assert_any_call(f"{functional.__module__}.{functional.__name__}")
assert isinstance(output, type(input))
if isinstance(input, tv_tensors.BoundingBoxes) and functional is not F.convert_bounding_box_format:
assert output.format == input.format
if check_scripted_smoke:
_check_functional_scripted_smoke(functional, input, *args, **kwargs)
def check_functional_kernel_signature_match(functional, *, kernel, input_type):
"""Checks if the signature of the functional matches the kernel signature."""
functional_params = list(inspect.signature(functional).parameters.values())[1:]
kernel_params = list(inspect.signature(kernel).parameters.values())[1:]
if issubclass(input_type, tv_tensors.TVTensor):
# We filter out metadata that is implicitly passed to the functional through the input tv_tensor, but has to be
# explicitly passed to the kernel.
explicit_metadata = {
tv_tensors.BoundingBoxes: {"format", "canvas_size"},
}
kernel_params = [param for param in kernel_params if param.name not in explicit_metadata.get(input_type, set())]
functional_params = iter(functional_params)
for functional_param, kernel_param in zip(functional_params, kernel_params):
try:
# In general, the functional parameters are a superset of the kernel parameters. Thus, we filter out
# functional parameters that have no kernel equivalent while keeping the order intact.
while functional_param.name != kernel_param.name:
functional_param = next(functional_params)
except StopIteration:
raise AssertionError(
f"Parameter `{kernel_param.name}` of kernel `{kernel.__name__}` "
f"has no corresponding parameter on the functional `{functional.__name__}`."
) from None
if issubclass(input_type, PIL.Image.Image):
# PIL kernels often have more correct annotations, since they are not limited by JIT. Thus, we don't check
# them in the first place.
functional_param._annotation = kernel_param._annotation = inspect.Parameter.empty
assert functional_param == kernel_param
def _check_transform_v1_compatibility(transform, input, *, rtol, atol):
"""If the transform defines the ``_v1_transform_cls`` attribute, checks if the transform has a public, static
``get_params`` method that is the v1 equivalent, the output is close to v1, is scriptable, and the scripted version
can be called without error."""
if not (type(input) is torch.Tensor or isinstance(input, PIL.Image.Image)):
return
v1_transform_cls = transform._v1_transform_cls
if v1_transform_cls is None:
return
if hasattr(v1_transform_cls, "get_params"):
assert type(transform).get_params is v1_transform_cls.get_params
v1_transform = v1_transform_cls(**transform._extract_params_for_v1_transform())
with freeze_rng_state():
output_v2 = transform(input)
with freeze_rng_state():
output_v1 = v1_transform(input)
assert_close(F.to_image(output_v2), F.to_image(output_v1), rtol=rtol, atol=atol)
if isinstance(input, PIL.Image.Image):
return
_script(v1_transform)(input)
def _make_transform_sample(transform, *, image_or_video, adapter):
device = image_or_video.device if isinstance(image_or_video, torch.Tensor) else "cpu"
size = F.get_size(image_or_video)
input = dict(
image_or_video=image_or_video,
image_tv_tensor=make_image(size, device=device),
video_tv_tensor=make_video(size, device=device),
image_pil=make_image_pil(size),
bounding_boxes_xyxy=make_bounding_boxes(size, format=tv_tensors.BoundingBoxFormat.XYXY, device=device),
bounding_boxes_xywh=make_bounding_boxes(size, format=tv_tensors.BoundingBoxFormat.XYWH, device=device),
bounding_boxes_cxcywh=make_bounding_boxes(size, format=tv_tensors.BoundingBoxFormat.CXCYWH, device=device),
bounding_boxes_degenerate_xyxy=tv_tensors.BoundingBoxes(
[
[0, 0, 0, 0], # no height or width
[0, 0, 0, 1], # no height
[0, 0, 1, 0], # no width
[2, 0, 1, 1], # x1 > x2, y1 < y2
[0, 2, 1, 1], # x1 < x2, y1 > y2
[2, 2, 1, 1], # x1 > x2, y1 > y2
],
format=tv_tensors.BoundingBoxFormat.XYXY,
canvas_size=size,
device=device,
),
bounding_boxes_degenerate_xywh=tv_tensors.BoundingBoxes(
[
[0, 0, 0, 0], # no height or width
[0, 0, 0, 1], # no height
[0, 0, 1, 0], # no width
[0, 0, 1, -1], # negative height
[0, 0, -1, 1], # negative width
[0, 0, -1, -1], # negative height and width
],
format=tv_tensors.BoundingBoxFormat.XYWH,
canvas_size=size,
device=device,
),
bounding_boxes_degenerate_cxcywh=tv_tensors.BoundingBoxes(
[
[0, 0, 0, 0], # no height or width
[0, 0, 0, 1], # no height
[0, 0, 1, 0], # no width
[0, 0, 1, -1], # negative height
[0, 0, -1, 1], # negative width
[0, 0, -1, -1], # negative height and width
],
format=tv_tensors.BoundingBoxFormat.CXCYWH,
canvas_size=size,
device=device,
),
detection_mask=make_detection_masks(size, device=device),
segmentation_mask=make_segmentation_mask(size, device=device),
int=0,
float=0.0,
bool=True,
none=None,
str="str",
path=Path.cwd(),
object=object(),
tensor=torch.empty(5),
array=np.empty(5),
)
if adapter is not None:
input = adapter(transform, input, device)
return input
def _check_transform_sample_input_smoke(transform, input, *, adapter):
# This is a bunch of input / output convention checks, using a big sample with different parts as input.
if not check_type(input, (is_pure_tensor, PIL.Image.Image, tv_tensors.Image, tv_tensors.Video)):
return
sample = _make_transform_sample(
# adapter might change transform inplace
transform=transform if adapter is None else deepcopy(transform),
image_or_video=input,
adapter=adapter,
)
for container_type in [dict, list, tuple]:
if container_type is dict:
input = sample
else:
input = container_type(sample.values())
input_flat, input_spec = tree_flatten(input)
with freeze_rng_state():
torch.manual_seed(0)
output = transform(input)
output_flat, output_spec = tree_flatten(output)
assert output_spec == input_spec
for output_item, input_item, should_be_transformed in zip(
output_flat, input_flat, transforms.Transform()._needs_transform_list(input_flat)
):
if should_be_transformed:
assert type(output_item) is type(input_item)
else:
assert output_item is input_item
# Enforce that the transform does not turn a degenerate bounding box, e.g. marked by RandomIoUCrop (or any other
# future transform that does this), back into a valid one.
for degenerate_bounding_boxes in (
bounding_box
for name, bounding_box in sample.items()
if "degenerate" in name and isinstance(bounding_box, tv_tensors.BoundingBoxes)
):
sample = dict(
boxes=degenerate_bounding_boxes,
labels=torch.randint(10, (degenerate_bounding_boxes.shape[0],), device=degenerate_bounding_boxes.device),
)
assert transforms.SanitizeBoundingBoxes()(sample)["boxes"].shape == (0, 4)
def check_transform(transform, input, check_v1_compatibility=True, check_sample_input=True):
pickle.loads(pickle.dumps(transform))
output = transform(input)
assert isinstance(output, type(input))
if isinstance(input, tv_tensors.BoundingBoxes) and not isinstance(transform, transforms.ConvertBoundingBoxFormat):
assert output.format == input.format
if check_sample_input:
_check_transform_sample_input_smoke(
transform, input, adapter=check_sample_input if callable(check_sample_input) else None
)
if check_v1_compatibility:
_check_transform_v1_compatibility(transform, input, **_to_tolerances(check_v1_compatibility))
return output
def transform_cls_to_functional(transform_cls, **transform_specific_kwargs):
def wrapper(input, *args, **kwargs):
transform = transform_cls(*args, **transform_specific_kwargs, **kwargs)
return transform(input)
wrapper.__name__ = transform_cls.__name__
return wrapper
def param_value_parametrization(**kwargs):
"""Helper function to turn
@pytest.mark.parametrize(
("param", "value"),
("a", 1),
("a", 2),
("a", 3),
("b", -1.0)
("b", 1.0)
)
into
@param_value_parametrization(a=[1, 2, 3], b=[-1.0, 1.0])
"""
return pytest.mark.parametrize(
("param", "value"),
[(param, value) for param, values in kwargs.items() for value in values],
)
def adapt_fill(value, *, dtype):
"""Adapt fill values in the range [0.0, 1.0] to the value range of the dtype"""
if value is None:
return value
max_value = get_max_value(dtype)
value_type = float if dtype.is_floating_point else int
if isinstance(value, (int, float)):
return value_type(value * max_value)
elif isinstance(value, (list, tuple)):
return type(value)(value_type(v * max_value) for v in value)
else:
raise ValueError(f"fill should be an int or float, or a list or tuple of the former, but got '{value}'.")
EXHAUSTIVE_TYPE_FILLS = [
None,
1,
0.5,
[1],
[0.2],
(0,),
(0.7,),
[1, 0, 1],
[0.1, 0.2, 0.3],
(0, 1, 0),
(0.9, 0.234, 0.314),
]
CORRECTNESS_FILLS = [
v for v in EXHAUSTIVE_TYPE_FILLS if v is None or isinstance(v, float) or (isinstance(v, list) and len(v) > 1)
]
# We cannot use `list(transforms.InterpolationMode)` here, since it includes some PIL-only ones as well
INTERPOLATION_MODES = [
transforms.InterpolationMode.NEAREST,
transforms.InterpolationMode.NEAREST_EXACT,
transforms.InterpolationMode.BILINEAR,
transforms.InterpolationMode.BICUBIC,
]
def reference_affine_bounding_boxes_helper(bounding_boxes, *, affine_matrix, new_canvas_size=None, clamp=True):
format = bounding_boxes.format
canvas_size = new_canvas_size or bounding_boxes.canvas_size
def affine_bounding_boxes(bounding_boxes):
dtype = bounding_boxes.dtype
device = bounding_boxes.device
# Go to float before converting to prevent precision loss in case of CXCYWH -> XYXY and W or H is 1
input_xyxy = F.convert_bounding_box_format(
bounding_boxes.to(dtype=torch.float64, device="cpu", copy=True),
old_format=format,
new_format=tv_tensors.BoundingBoxFormat.XYXY,
inplace=True,
)
x1, y1, x2, y2 = input_xyxy.squeeze(0).tolist()
points = np.array(
[
[x1, y1, 1.0],
[x2, y1, 1.0],
[x1, y2, 1.0],
[x2, y2, 1.0],
]
)
transformed_points = np.matmul(points, affine_matrix.astype(points.dtype).T)
output_xyxy = torch.Tensor(
[
float(np.min(transformed_points[:, 0])),
float(np.min(transformed_points[:, 1])),
float(np.max(transformed_points[:, 0])),
float(np.max(transformed_points[:, 1])),
]
)
output = F.convert_bounding_box_format(
output_xyxy, old_format=tv_tensors.BoundingBoxFormat.XYXY, new_format=format
)
if clamp:
# It is important to clamp before casting, especially for CXCYWH format, dtype=int64
output = F.clamp_bounding_boxes(
output,
format=format,
canvas_size=canvas_size,
)
else:
# We leave the bounding box as float64 so the caller gets the full precision to perform any additional
# operation
dtype = output.dtype
return output.to(dtype=dtype, device=device)
return tv_tensors.BoundingBoxes(
torch.cat([affine_bounding_boxes(b) for b in bounding_boxes.reshape(-1, 4).unbind()], dim=0).reshape(
bounding_boxes.shape
),
format=format,
canvas_size=canvas_size,
)
class TestResize:
INPUT_SIZE = (17, 11)
OUTPUT_SIZES = [17, [17], (17,), [12, 13], (12, 13)]
def _make_max_size_kwarg(self, *, use_max_size, size):
if use_max_size:
if not (isinstance(size, int) or len(size) == 1):
# This would result in an `ValueError`
return None
max_size = (size if isinstance(size, int) else size[0]) + 1
else:
max_size = None
return dict(max_size=max_size)
def _compute_output_size(self, *, input_size, size, max_size):
if not (isinstance(size, int) or len(size) == 1):
return tuple(size)
if not isinstance(size, int):
size = size[0]
old_height, old_width = input_size
ratio = old_width / old_height
if ratio > 1:
new_height = size
new_width = int(ratio * new_height)
else:
new_width = size
new_height = int(new_width / ratio)
if max_size is not None and max(new_height, new_width) > max_size:
# Need to recompute the aspect ratio, since it might have changed due to rounding
ratio = new_width / new_height
if ratio > 1:
new_width = max_size
new_height = int(new_width / ratio)
else:
new_height = max_size
new_width = int(new_height * ratio)
return new_height, new_width
@pytest.mark.parametrize("size", OUTPUT_SIZES)
@pytest.mark.parametrize("interpolation", INTERPOLATION_MODES)
@pytest.mark.parametrize("use_max_size", [True, False])
@pytest.mark.parametrize("antialias", [True, False])
@pytest.mark.parametrize("dtype", [torch.float32, torch.uint8])
@pytest.mark.parametrize("device", cpu_and_cuda())
def test_kernel_image(self, size, interpolation, use_max_size, antialias, dtype, device):
if not (max_size_kwarg := self._make_max_size_kwarg(use_max_size=use_max_size, size=size)):
return
# In contrast to CPU, there is no native `InterpolationMode.BICUBIC` implementation for uint8 images on CUDA.
# Internally, it uses the float path. Thus, we need to test with an enormous tolerance here to account for that.
atol = 30 if (interpolation is transforms.InterpolationMode.BICUBIC and dtype is torch.uint8) else 1
check_cuda_vs_cpu_tolerances = dict(rtol=0, atol=atol / 255 if dtype.is_floating_point else atol)
check_kernel(
F.resize_image,
make_image(self.INPUT_SIZE, dtype=dtype, device=device),
size=size,
interpolation=interpolation,
**max_size_kwarg,
antialias=antialias,
check_cuda_vs_cpu=check_cuda_vs_cpu_tolerances,
check_scripted_vs_eager=not isinstance(size, int),
)
@pytest.mark.parametrize("format", list(tv_tensors.BoundingBoxFormat))
@pytest.mark.parametrize("size", OUTPUT_SIZES)
@pytest.mark.parametrize("use_max_size", [True, False])
@pytest.mark.parametrize("dtype", [torch.float32, torch.int64])
@pytest.mark.parametrize("device", cpu_and_cuda())
def test_kernel_bounding_boxes(self, format, size, use_max_size, dtype, device):
if not (max_size_kwarg := self._make_max_size_kwarg(use_max_size=use_max_size, size=size)):
return
bounding_boxes = make_bounding_boxes(
format=format,
canvas_size=self.INPUT_SIZE,
dtype=dtype,
device=device,
)
check_kernel(
F.resize_bounding_boxes,
bounding_boxes,
canvas_size=bounding_boxes.canvas_size,
size=size,
**max_size_kwarg,
check_scripted_vs_eager=not isinstance(size, int),
)
@pytest.mark.parametrize("make_mask", [make_segmentation_mask, make_detection_masks])
def test_kernel_mask(self, make_mask):
check_kernel(F.resize_mask, make_mask(self.INPUT_SIZE), size=self.OUTPUT_SIZES[-1])
def test_kernel_video(self):
check_kernel(F.resize_video, make_video(self.INPUT_SIZE), size=self.OUTPUT_SIZES[-1], antialias=True)
@pytest.mark.parametrize("size", OUTPUT_SIZES)
@pytest.mark.parametrize(
"make_input",
[make_image_tensor, make_image_pil, make_image, make_bounding_boxes, make_segmentation_mask, make_video],
)
def test_functional(self, size, make_input):
check_functional(
F.resize,
make_input(self.INPUT_SIZE),
size=size,
antialias=True,
check_scripted_smoke=not isinstance(size, int),
)
@pytest.mark.parametrize(
("kernel", "input_type"),
[
(F.resize_image, torch.Tensor),
(F._resize_image_pil, PIL.Image.Image),
(F.resize_image, tv_tensors.Image),
(F.resize_bounding_boxes, tv_tensors.BoundingBoxes),
(F.resize_mask, tv_tensors.Mask),
(F.resize_video, tv_tensors.Video),
],
)
def test_functional_signature(self, kernel, input_type):
check_functional_kernel_signature_match(F.resize, kernel=kernel, input_type=input_type)
@pytest.mark.parametrize("size", OUTPUT_SIZES)
@pytest.mark.parametrize("device", cpu_and_cuda())
@pytest.mark.parametrize(
"make_input",
[
make_image_tensor,
make_image_pil,
make_image,
make_bounding_boxes,
make_segmentation_mask,
make_detection_masks,
make_video,
],
)
def test_transform(self, size, device, make_input):
check_transform(
transforms.Resize(size=size, antialias=True),
make_input(self.INPUT_SIZE, device=device),
# atol=1 due to Resize v2 is using native uint8 interpolate path for bilinear and nearest modes
check_v1_compatibility=dict(rtol=0, atol=1),
)
def _check_output_size(self, input, output, *, size, max_size):
assert tuple(F.get_size(output)) == self._compute_output_size(
input_size=F.get_size(input), size=size, max_size=max_size
)
@pytest.mark.parametrize("size", OUTPUT_SIZES)
# `InterpolationMode.NEAREST` is modeled after the buggy `INTER_NEAREST` interpolation of CV2.
# The PIL equivalent of `InterpolationMode.NEAREST` is `InterpolationMode.NEAREST_EXACT`
@pytest.mark.parametrize("interpolation", set(INTERPOLATION_MODES) - {transforms.InterpolationMode.NEAREST})
@pytest.mark.parametrize("use_max_size", [True, False])
@pytest.mark.parametrize("fn", [F.resize, transform_cls_to_functional(transforms.Resize)])
def test_image_correctness(self, size, interpolation, use_max_size, fn):
if not (max_size_kwarg := self._make_max_size_kwarg(use_max_size=use_max_size, size=size)):
return
image = make_image(self.INPUT_SIZE, dtype=torch.uint8)
actual = fn(image, size=size, interpolation=interpolation, **max_size_kwarg, antialias=True)
expected = F.to_image(F.resize(F.to_pil_image(image), size=size, interpolation=interpolation, **max_size_kwarg))
self._check_output_size(image, actual, size=size, **max_size_kwarg)
torch.testing.assert_close(actual, expected, atol=1, rtol=0)
def _reference_resize_bounding_boxes(self, bounding_boxes, *, size, max_size=None):
old_height, old_width = bounding_boxes.canvas_size
new_height, new_width = self._compute_output_size(
input_size=bounding_boxes.canvas_size, size=size, max_size=max_size
)
if (old_height, old_width) == (new_height, new_width):
return bounding_boxes
affine_matrix = np.array(
[
[new_width / old_width, 0, 0],
[0, new_height / old_height, 0],
],
)
return reference_affine_bounding_boxes_helper(
bounding_boxes,
affine_matrix=affine_matrix,
new_canvas_size=(new_height, new_width),
)
@pytest.mark.parametrize("format", list(tv_tensors.BoundingBoxFormat))
@pytest.mark.parametrize("size", OUTPUT_SIZES)
@pytest.mark.parametrize("use_max_size", [True, False])
@pytest.mark.parametrize("fn", [F.resize, transform_cls_to_functional(transforms.Resize)])
def test_bounding_boxes_correctness(self, format, size, use_max_size, fn):
if not (max_size_kwarg := self._make_max_size_kwarg(use_max_size=use_max_size, size=size)):
return
bounding_boxes = make_bounding_boxes(format=format, canvas_size=self.INPUT_SIZE)
actual = fn(bounding_boxes, size=size, **max_size_kwarg)
expected = self._reference_resize_bounding_boxes(bounding_boxes, size=size, **max_size_kwarg)
self._check_output_size(bounding_boxes, actual, size=size, **max_size_kwarg)
torch.testing.assert_close(actual, expected)
@pytest.mark.parametrize("interpolation", set(transforms.InterpolationMode) - set(INTERPOLATION_MODES))
@pytest.mark.parametrize(
"make_input",
[make_image_tensor, make_image_pil, make_image, make_video],
)
def test_pil_interpolation_compat_smoke(self, interpolation, make_input):
input = make_input(self.INPUT_SIZE)
with (
contextlib.nullcontext()
if isinstance(input, PIL.Image.Image)
# This error is triggered in PyTorch core
else pytest.raises(NotImplementedError, match=f"got {interpolation.value.lower()}")
):
F.resize(
input,
size=self.OUTPUT_SIZES[0],
interpolation=interpolation,
)
def test_functional_pil_antialias_warning(self):
with pytest.warns(UserWarning, match="Anti-alias option is always applied for PIL Image input"):
F.resize(make_image_pil(self.INPUT_SIZE), size=self.OUTPUT_SIZES[0], antialias=False)
@pytest.mark.parametrize("size", OUTPUT_SIZES)
@pytest.mark.parametrize(
"make_input",
[
make_image_tensor,
make_image_pil,
make_image,
make_bounding_boxes,
make_segmentation_mask,
make_detection_masks,
make_video,
],
)
def test_max_size_error(self, size, make_input):
if isinstance(size, int) or len(size) == 1:
max_size = (size if isinstance(size, int) else size[0]) - 1
match = "must be strictly greater than the requested size"
else:
# value can be anything other than None
max_size = -1
match = "size should be an int or a sequence of length 1"
with pytest.raises(ValueError, match=match):
F.resize(make_input(self.INPUT_SIZE), size=size, max_size=max_size, antialias=True)
@pytest.mark.parametrize("interpolation", INTERPOLATION_MODES)
@pytest.mark.parametrize(
"make_input",
[make_image_tensor, make_image_pil, make_image, make_video],
)
def test_interpolation_int(self, interpolation, make_input):
input = make_input(self.INPUT_SIZE)
# `InterpolationMode.NEAREST_EXACT` has no proper corresponding integer equivalent. Internally, we map it to
# `0` to be the same as `InterpolationMode.NEAREST` for PIL. However, for the tensor backend there is a
# difference and thus we don't test it here.
if isinstance(input, torch.Tensor) and interpolation is transforms.InterpolationMode.NEAREST_EXACT:
return
expected = F.resize(input, size=self.OUTPUT_SIZES[0], interpolation=interpolation, antialias=True)
actual = F.resize(
input, size=self.OUTPUT_SIZES[0], interpolation=pil_modes_mapping[interpolation], antialias=True
)
assert_equal(actual, expected)
def test_transform_unknown_size_error(self):
with pytest.raises(ValueError, match="size can either be an integer or a sequence of one or two integers"):
transforms.Resize(size=object())
@pytest.mark.parametrize(
"size", [min(INPUT_SIZE), [min(INPUT_SIZE)], (min(INPUT_SIZE),), list(INPUT_SIZE), tuple(INPUT_SIZE)]
)
@pytest.mark.parametrize(
"make_input",
[
make_image_tensor,
make_image_pil,
make_image,
make_bounding_boxes,
make_segmentation_mask,
make_detection_masks,
make_video,
],
)
def test_noop(self, size, make_input):
input = make_input(self.INPUT_SIZE)
output = F.resize(input, size=F.get_size(input), antialias=True)
# This identity check is not a requirement. It is here to avoid breaking the behavior by accident. If there
# is a good reason to break this, feel free to downgrade to an equality check.
if isinstance(input, tv_tensors.TVTensor):
# We can't test identity directly, since that checks for the identity of the Python object. Since all
# tv_tensors unwrap before a kernel and wrap again afterwards, the Python object changes. Thus, we check
# that the underlying storage is the same
assert output.data_ptr() == input.data_ptr()
else:
assert output is input
@pytest.mark.parametrize(
"make_input",
[
make_image_tensor,
make_image_pil,
make_image,
make_bounding_boxes,
make_segmentation_mask,
make_detection_masks,
make_video,
],
)
def test_no_regression_5405(self, make_input):
# Checks that `max_size` is not ignored if `size == small_edge_size`
# See https://github.com/pytorch/vision/issues/5405
input = make_input(self.INPUT_SIZE)
size = min(F.get_size(input))
max_size = size + 1
output = F.resize(input, size=size, max_size=max_size, antialias=True)
assert max(F.get_size(output)) == max_size
def _make_image(self, *args, batch_dims=(), memory_format=torch.contiguous_format, **kwargs):
# torch.channels_last memory_format is only available for 4D tensors, i.e. (B, C, H, W). However, images coming
# from PIL or our own I/O functions do not have a batch dimensions and are thus 3D, i.e. (C, H, W). Still, the
# layout of the data in memory is channels last. To emulate this when a 3D input is requested here, we create
# the image as 4D and create a view with the right shape afterwards. With this the layout in memory is channels
# last although PyTorch doesn't recognizes it as such.
emulate_channels_last = memory_format is torch.channels_last and len(batch_dims) != 1
image = make_image(
*args,
batch_dims=(math.prod(batch_dims),) if emulate_channels_last else batch_dims,
memory_format=memory_format,
**kwargs,
)
if emulate_channels_last:
image = tv_tensors.wrap(image.view(*batch_dims, *image.shape[-3:]), like=image)
return image
def _check_stride(self, image, *, memory_format):
C, H, W = F.get_dimensions(image)
if memory_format is torch.contiguous_format:
expected_stride = (H * W, W, 1)
elif memory_format is torch.channels_last:
expected_stride = (1, W * C, C)
else:
raise ValueError(f"Unknown memory_format: {memory_format}")
assert image.stride() == expected_stride
# TODO: We can remove this test and related torchvision workaround
# once we fixed related pytorch issue: https://github.com/pytorch/pytorch/issues/68430
@pytest.mark.parametrize("interpolation", INTERPOLATION_MODES)
@pytest.mark.parametrize("antialias", [True, False])
@pytest.mark.parametrize("memory_format", [torch.contiguous_format, torch.channels_last])
@pytest.mark.parametrize("dtype", [torch.uint8, torch.float32])
@pytest.mark.parametrize("device", cpu_and_cuda())
def test_kernel_image_memory_format_consistency(self, interpolation, antialias, memory_format, dtype, device):
size = self.OUTPUT_SIZES[0]
input = self._make_image(self.INPUT_SIZE, dtype=dtype, device=device, memory_format=memory_format)
# Smoke test to make sure we aren't starting with wrong assumptions
self._check_stride(input, memory_format=memory_format)
output = F.resize_image(input, size=size, interpolation=interpolation, antialias=antialias)
self._check_stride(output, memory_format=memory_format)
def test_float16_no_rounding(self):
# Make sure Resize() doesn't round float16 images
# Non-regression test for https://github.com/pytorch/vision/issues/7667
input = make_image_tensor(self.INPUT_SIZE, dtype=torch.float16)
output = F.resize_image(input, size=self.OUTPUT_SIZES[0], antialias=True)
assert output.dtype is torch.float16
assert (output.round() - output).abs().sum() > 0
class TestHorizontalFlip:
@pytest.mark.parametrize("dtype", [torch.float32, torch.uint8])
@pytest.mark.parametrize("device", cpu_and_cuda())
def test_kernel_image(self, dtype, device):
check_kernel(F.horizontal_flip_image, make_image(dtype=dtype, device=device))
@pytest.mark.parametrize("format", list(tv_tensors.BoundingBoxFormat))
@pytest.mark.parametrize("dtype", [torch.float32, torch.int64])
@pytest.mark.parametrize("device", cpu_and_cuda())
def test_kernel_bounding_boxes(self, format, dtype, device):
bounding_boxes = make_bounding_boxes(format=format, dtype=dtype, device=device)
check_kernel(
F.horizontal_flip_bounding_boxes,
bounding_boxes,
format=format,
canvas_size=bounding_boxes.canvas_size,
)
@pytest.mark.parametrize("make_mask", [make_segmentation_mask, make_detection_masks])
def test_kernel_mask(self, make_mask):
check_kernel(F.horizontal_flip_mask, make_mask())
def test_kernel_video(self):
check_kernel(F.horizontal_flip_video, make_video())
@pytest.mark.parametrize(
"make_input",
[make_image_tensor, make_image_pil, make_image, make_bounding_boxes, make_segmentation_mask, make_video],
)
def test_functional(self, make_input):
check_functional(F.horizontal_flip, make_input())
@pytest.mark.parametrize(
("kernel", "input_type"),
[
(F.horizontal_flip_image, torch.Tensor),
(F._horizontal_flip_image_pil, PIL.Image.Image),
(F.horizontal_flip_image, tv_tensors.Image),
(F.horizontal_flip_bounding_boxes, tv_tensors.BoundingBoxes),
(F.horizontal_flip_mask, tv_tensors.Mask),
(F.horizontal_flip_video, tv_tensors.Video),
],
)
def test_functional_signature(self, kernel, input_type):
check_functional_kernel_signature_match(F.horizontal_flip, kernel=kernel, input_type=input_type)
@pytest.mark.parametrize(
"make_input",
[make_image_tensor, make_image_pil, make_image, make_bounding_boxes, make_segmentation_mask, make_video],
)
@pytest.mark.parametrize("device", cpu_and_cuda())
def test_transform(self, make_input, device):
check_transform(transforms.RandomHorizontalFlip(p=1), make_input(device=device))