test_transforms_v2_refactored.py 97 KB
Newer Older
1
import contextlib
2
import decimal
3
import inspect
Philip Meier's avatar
Philip Meier committed
4
import math
5
import pickle
6
import re
7
from pathlib import Path
8
9
10
11
12
13
14
15
16
17
18
19
20
from unittest import mock

import numpy as np
import PIL.Image
import pytest

import torch
import torchvision.transforms.v2 as transforms
from common_utils import (
    assert_equal,
    assert_no_warnings,
    cache,
    cpu_and_cuda,
21
    freeze_rng_state,
22
    ignore_jit_no_profile_information_warning,
23
    make_bounding_boxes,
24
25
    make_detection_mask,
    make_image,
26
27
    make_image_pil,
    make_image_tensor,
28
29
    make_segmentation_mask,
    make_video,
30
    make_video_tensor,
31
    needs_cuda,
Nicolas Hug's avatar
Nicolas Hug committed
32
    set_rng_seed,
33
)
34
35

from torch import nn
36
from torch.testing import assert_close
37
from torch.utils._pytree import tree_map
38
from torch.utils.data import DataLoader, default_collate
39
from torchvision import datapoints
Philip Meier's avatar
Philip Meier committed
40
41

from torchvision.transforms._functional_tensor import _max_value as get_max_value
42
43
from torchvision.transforms.functional import pil_modes_mapping
from torchvision.transforms.v2 import functional as F
44
from torchvision.transforms.v2.functional._utils import _get_kernel, _register_kernel_internal
45
46


Nicolas Hug's avatar
Nicolas Hug committed
47
48
49
50
51
52
@pytest.fixture(autouse=True)
def fix_rng_seed():
    set_rng_seed(0)
    yield


53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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")

70
71
72
73
    with freeze_rng_state():
        actual = kernel(input_cuda, *args, **kwargs)
    with freeze_rng_state():
        expected = kernel(input_cpu, *args, **kwargs)
74
75
76
77
78

    assert_close(actual, expected, check_device=False, rtol=rtol, atol=atol)


@cache
79
def _script(obj):
80
    try:
81
        return torch.jit.script(obj)
82
    except Exception as error:
83
84
        name = getattr(obj, "__name__", obj.__class__.__name__)
        raise AssertionError(f"Trying to `torch.jit.script` '{name}' raised the error above.") from error
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


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,
141
    expect_same_dtype=True,
142
143
144
145
146
147
148
149
150
151
152
153
    **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

154
155
    if expect_same_dtype:
        assert output.dtype == input.dtype
156
157
158
159
160
161
162
163
164
165
166
167
    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))


Nicolas Hug's avatar
Nicolas Hug committed
168
169
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."""
170
171
172
    if not isinstance(input, datapoints.Image):
        return

Nicolas Hug's avatar
Nicolas Hug committed
173
    functional_scripted = _script(functional)
174
    with ignore_jit_no_profile_information_warning():
Nicolas Hug's avatar
Nicolas Hug committed
175
        functional_scripted(input.as_subclass(torch.Tensor), *args, **kwargs)
176
177


Nicolas Hug's avatar
Nicolas Hug committed
178
def check_functional(functional, input, *args, check_scripted_smoke=True, **kwargs):
179
    unknown_input = object()
180
    with pytest.raises(TypeError, match=re.escape(str(type(unknown_input)))):
Nicolas Hug's avatar
Nicolas Hug committed
181
        functional(unknown_input, *args, **kwargs)
182

183
    with mock.patch("torch._C._log_api_usage_once", wraps=torch._C._log_api_usage_once) as spy:
Nicolas Hug's avatar
Nicolas Hug committed
184
        output = functional(input, *args, **kwargs)
185

Nicolas Hug's avatar
Nicolas Hug committed
186
        spy.assert_any_call(f"{functional.__module__}.{functional.__name__}")
187

188
189
190
191
192
    assert isinstance(output, type(input))

    if isinstance(input, datapoints.BoundingBoxes):
        assert output.format == input.format

193
    if check_scripted_smoke:
Nicolas Hug's avatar
Nicolas Hug committed
194
        _check_functional_scripted_smoke(functional, input, *args, **kwargs)
195
196


Nicolas Hug's avatar
Nicolas Hug committed
197
198
199
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:]
200
    kernel_params = list(inspect.signature(kernel).parameters.values())[1:]
201

202
    if issubclass(input_type, datapoints.Datapoint):
Nicolas Hug's avatar
Nicolas Hug committed
203
        # We filter out metadata that is implicitly passed to the functional through the input datapoint, but has to be
204
        # explicitly passed to the kernel.
205
206
207
208
        explicit_metadata = {
            datapoints.BoundingBoxes: {"format", "canvas_size"},
        }
        kernel_params = [param for param in kernel_params if param.name not in explicit_metadata.get(input_type, set())]
209

Nicolas Hug's avatar
Nicolas Hug committed
210
211
    functional_params = iter(functional_params)
    for functional_param, kernel_param in zip(functional_params, kernel_params):
212
        try:
Nicolas Hug's avatar
Nicolas Hug committed
213
214
215
216
            # 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)
217
218
219
        except StopIteration:
            raise AssertionError(
                f"Parameter `{kernel_param.name}` of kernel `{kernel.__name__}` "
Nicolas Hug's avatar
Nicolas Hug committed
220
                f"has no corresponding parameter on the functional `{functional.__name__}`."
221
222
223
224
225
            ) 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.
Nicolas Hug's avatar
Nicolas Hug committed
226
            functional_param._annotation = kernel_param._annotation = inspect.Parameter.empty
227

Nicolas Hug's avatar
Nicolas Hug committed
228
        assert functional_param == kernel_param
229
230
231
232
233


def _check_transform_v1_compatibility(transform, input):
    """If the transform defines the ``_v1_transform_cls`` attribute, checks if the transform has a public, static
    ``get_params`` method, is scriptable, and the scripted version can be called without error."""
234
    if transform._v1_transform_cls is None:
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
        return

    if type(input) is not torch.Tensor:
        return

    if hasattr(transform._v1_transform_cls, "get_params"):
        assert type(transform).get_params is transform._v1_transform_cls.get_params

    scripted_transform = _script(transform)
    with ignore_jit_no_profile_information_warning():
        scripted_transform(input)


def check_transform(transform_cls, input, *args, **kwargs):
    transform = transform_cls(*args, **kwargs)

251
252
    pickle.loads(pickle.dumps(transform))

253
254
255
    output = transform(input)
    assert isinstance(output, type(input))

256
    if isinstance(input, datapoints.BoundingBoxes):
257
258
259
260
261
        assert output.format == input.format

    _check_transform_v1_compatibility(transform, input)


262
def transform_cls_to_functional(transform_cls, **transform_specific_kwargs):
263
    def wrapper(input, *args, **kwargs):
264
        transform = transform_cls(*args, **transform_specific_kwargs, **kwargs)
265
266
267
268
269
270
271
        return transform(input)

    wrapper.__name__ = transform_cls.__name__

    return wrapper


Philip Meier's avatar
Philip Meier committed
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
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)

    if isinstance(value, (int, float)):
        return type(value)(value * max_value)
    elif isinstance(value, (list, tuple)):
        return type(value)(type(v)(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)
]


327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
# 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,
]


@contextlib.contextmanager
def assert_warns_antialias_default_value():
    with pytest.warns(UserWarning, match="The default value of the antialias parameter of all the resizing transforms"):
        yield


Philip Meier's avatar
Philip Meier committed
342
def reference_affine_bounding_boxes_helper(bounding_boxes, *, format, canvas_size, affine_matrix):
343
    def transform(bbox):
344
345
346
347
        # Go to float before converting to prevent precision loss in case of CXCYWH -> XYXY and W or H is 1
        in_dtype = bbox.dtype
        if not torch.is_floating_point(bbox):
            bbox = bbox.float()
Nicolas Hug's avatar
Nicolas Hug committed
348
        bbox_xyxy = F.convert_bounding_box_format(
349
            bbox.as_subclass(torch.Tensor),
350
            old_format=format,
351
352
353
354
355
356
357
358
359
360
361
            new_format=datapoints.BoundingBoxFormat.XYXY,
            inplace=True,
        )
        points = np.array(
            [
                [bbox_xyxy[0].item(), bbox_xyxy[1].item(), 1.0],
                [bbox_xyxy[2].item(), bbox_xyxy[1].item(), 1.0],
                [bbox_xyxy[0].item(), bbox_xyxy[3].item(), 1.0],
                [bbox_xyxy[2].item(), bbox_xyxy[3].item(), 1.0],
            ]
        )
362
        transformed_points = np.matmul(points, affine_matrix.T)
363
364
365
366
367
368
369
370
371
        out_bbox = torch.tensor(
            [
                np.min(transformed_points[:, 0]).item(),
                np.min(transformed_points[:, 1]).item(),
                np.max(transformed_points[:, 0]).item(),
                np.max(transformed_points[:, 1]).item(),
            ],
            dtype=bbox_xyxy.dtype,
        )
Nicolas Hug's avatar
Nicolas Hug committed
372
        out_bbox = F.convert_bounding_box_format(
373
            out_bbox, old_format=datapoints.BoundingBoxFormat.XYXY, new_format=format, inplace=True
374
375
        )
        # It is important to clamp before casting, especially for CXCYWH format, dtype=int64
Philip Meier's avatar
Philip Meier committed
376
        out_bbox = F.clamp_bounding_boxes(out_bbox, format=format, canvas_size=canvas_size)
377
378
379
        out_bbox = out_bbox.to(dtype=in_dtype)
        return out_bbox

380
    return torch.stack([transform(b) for b in bounding_boxes.reshape(-1, 4).unbind()]).reshape(bounding_boxes.shape)
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


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_tensor(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 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(
443
            F.resize_image,
444
            make_image(self.INPUT_SIZE, dtype=dtype, device=device),
445
446
447
448
449
450
451
452
453
454
455
456
457
            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(datapoints.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())
458
    def test_kernel_bounding_boxes(self, format, size, use_max_size, dtype, device):
459
460
461
        if not (max_size_kwarg := self._make_max_size_kwarg(use_max_size=use_max_size, size=size)):
            return

462
        bounding_boxes = make_bounding_boxes(
463
            format=format,
Philip Meier's avatar
Philip Meier committed
464
            canvas_size=self.INPUT_SIZE,
465
466
            dtype=dtype,
            device=device,
Philip Meier's avatar
Philip Meier committed
467
        )
468
        check_kernel(
469
470
            F.resize_bounding_boxes,
            bounding_boxes,
Philip Meier's avatar
Philip Meier committed
471
            canvas_size=bounding_boxes.canvas_size,
472
473
474
475
476
            size=size,
            **max_size_kwarg,
            check_scripted_vs_eager=not isinstance(size, int),
        )

477
478
479
    @pytest.mark.parametrize("make_mask", [make_segmentation_mask, make_detection_mask])
    def test_kernel_mask(self, make_mask):
        check_kernel(F.resize_mask, make_mask(self.INPUT_SIZE), size=self.OUTPUT_SIZES[-1])
480
481

    def test_kernel_video(self):
482
        check_kernel(F.resize_video, make_video(self.INPUT_SIZE), size=self.OUTPUT_SIZES[-1], antialias=True)
483
484
485

    @pytest.mark.parametrize("size", OUTPUT_SIZES)
    @pytest.mark.parametrize(
Philip Meier's avatar
Philip Meier committed
486
        "make_input",
487
        [make_image_tensor, make_image_pil, make_image, make_bounding_boxes, make_segmentation_mask, make_video],
488
    )
Nicolas Hug's avatar
Nicolas Hug committed
489
490
    def test_functional(self, size, make_input):
        check_functional(
491
            F.resize,
492
            make_input(self.INPUT_SIZE),
493
494
495
496
497
498
            size=size,
            antialias=True,
            check_scripted_smoke=not isinstance(size, int),
        )

    @pytest.mark.parametrize(
499
        ("kernel", "input_type"),
500
        [
501
502
503
            (F.resize_image, torch.Tensor),
            (F._resize_image_pil, PIL.Image.Image),
            (F.resize_image, datapoints.Image),
504
            (F.resize_bounding_boxes, datapoints.BoundingBoxes),
505
506
            (F.resize_mask, datapoints.Mask),
            (F.resize_video, datapoints.Video),
507
508
        ],
    )
Nicolas Hug's avatar
Nicolas Hug committed
509
510
    def test_functional_signature(self, kernel, input_type):
        check_functional_kernel_signature_match(F.resize, kernel=kernel, input_type=input_type)
511
512
513
514

    @pytest.mark.parametrize("size", OUTPUT_SIZES)
    @pytest.mark.parametrize("device", cpu_and_cuda())
    @pytest.mark.parametrize(
515
516
517
518
519
        "make_input",
        [
            make_image_tensor,
            make_image_pil,
            make_image,
520
            make_bounding_boxes,
521
522
523
524
            make_segmentation_mask,
            make_detection_mask,
            make_video,
        ],
525
    )
526
527
    def test_transform(self, size, device, make_input):
        check_transform(transforms.Resize, make_input(self.INPUT_SIZE, device=device), size=size, antialias=True)
528
529

    def _check_output_size(self, input, output, *, size, max_size):
Philip Meier's avatar
Philip Meier committed
530
531
        assert tuple(F.get_size(output)) == self._compute_output_size(
            input_size=F.get_size(input), size=size, max_size=max_size
532
533
534
535
536
537
538
539
540
541
542
543
        )

    @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

544
        image = make_image(self.INPUT_SIZE, dtype=torch.uint8)
545
546

        actual = fn(image, size=size, interpolation=interpolation, **max_size_kwarg, antialias=True)
547
        expected = F.to_image(F.resize(F.to_pil_image(image), size=size, interpolation=interpolation, **max_size_kwarg))
548
549
550
551

        self._check_output_size(image, actual, size=size, **max_size_kwarg)
        torch.testing.assert_close(actual, expected, atol=1, rtol=0)

552
    def _reference_resize_bounding_boxes(self, bounding_boxes, *, size, max_size=None):
Philip Meier's avatar
Philip Meier committed
553
        old_height, old_width = bounding_boxes.canvas_size
554
        new_height, new_width = self._compute_output_size(
Philip Meier's avatar
Philip Meier committed
555
            input_size=bounding_boxes.canvas_size, size=size, max_size=max_size
556
557
558
        )

        if (old_height, old_width) == (new_height, new_width):
559
            return bounding_boxes
560
561
562
563
564
565

        affine_matrix = np.array(
            [
                [new_width / old_width, 0, 0],
                [0, new_height / old_height, 0],
            ],
566
            dtype="float64" if bounding_boxes.dtype == torch.float64 else "float32",
567
568
        )

569
570
571
        expected_bboxes = reference_affine_bounding_boxes_helper(
            bounding_boxes,
            format=bounding_boxes.format,
Philip Meier's avatar
Philip Meier committed
572
            canvas_size=(new_height, new_width),
573
574
            affine_matrix=affine_matrix,
        )
575
        return datapoints.wrap(expected_bboxes, like=bounding_boxes, canvas_size=(new_height, new_width))
576
577
578
579
580

    @pytest.mark.parametrize("format", list(datapoints.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)])
581
    def test_bounding_boxes_correctness(self, format, size, use_max_size, fn):
582
583
584
        if not (max_size_kwarg := self._make_max_size_kwarg(use_max_size=use_max_size, size=size)):
            return

585
        bounding_boxes = make_bounding_boxes(format=format, canvas_size=self.INPUT_SIZE)
586

587
588
        actual = fn(bounding_boxes, size=size, **max_size_kwarg)
        expected = self._reference_resize_bounding_boxes(bounding_boxes, size=size, **max_size_kwarg)
589

590
        self._check_output_size(bounding_boxes, actual, size=size, **max_size_kwarg)
591
592
593
594
        torch.testing.assert_close(actual, expected)

    @pytest.mark.parametrize("interpolation", set(transforms.InterpolationMode) - set(INTERPOLATION_MODES))
    @pytest.mark.parametrize(
595
596
        "make_input",
        [make_image_tensor, make_image_pil, make_image, make_video],
597
    )
598
599
    def test_pil_interpolation_compat_smoke(self, interpolation, make_input):
        input = make_input(self.INPUT_SIZE)
600
601
602
603
604
605
606
607
608
609
610
611
612

        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,
            )

Nicolas Hug's avatar
Nicolas Hug committed
613
    def test_functional_pil_antialias_warning(self):
614
        with pytest.warns(UserWarning, match="Anti-alias option is always applied for PIL Image input"):
615
            F.resize(make_image_pil(self.INPUT_SIZE), size=self.OUTPUT_SIZES[0], antialias=False)
616
617
618

    @pytest.mark.parametrize("size", OUTPUT_SIZES)
    @pytest.mark.parametrize(
619
620
621
622
623
        "make_input",
        [
            make_image_tensor,
            make_image_pil,
            make_image,
624
            make_bounding_boxes,
625
626
627
628
            make_segmentation_mask,
            make_detection_mask,
            make_video,
        ],
629
    )
630
    def test_max_size_error(self, size, make_input):
631
632
633
634
635
636
637
638
639
        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):
640
            F.resize(make_input(self.INPUT_SIZE), size=size, max_size=max_size, antialias=True)
641
642
643

    @pytest.mark.parametrize("interpolation", INTERPOLATION_MODES)
    @pytest.mark.parametrize(
644
645
        "make_input",
        [make_image_tensor, make_image, make_video],
646
    )
647
    def test_antialias_warning(self, interpolation, make_input):
648
649
650
651
652
        with (
            assert_warns_antialias_default_value()
            if interpolation in {transforms.InterpolationMode.BILINEAR, transforms.InterpolationMode.BICUBIC}
            else assert_no_warnings()
        ):
Philip Meier's avatar
Philip Meier committed
653
            F.resize(
654
                make_input(self.INPUT_SIZE),
Philip Meier's avatar
Philip Meier committed
655
656
657
                size=self.OUTPUT_SIZES[0],
                interpolation=interpolation,
            )
658
659
660

    @pytest.mark.parametrize("interpolation", INTERPOLATION_MODES)
    @pytest.mark.parametrize(
661
662
        "make_input",
        [make_image_tensor, make_image_pil, make_image, make_video],
663
    )
664
665
666
    def test_interpolation_int(self, interpolation, make_input):
        input = make_input(self.INPUT_SIZE)

667
668
669
        # `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.
670
        if isinstance(input, torch.Tensor) and interpolation is transforms.InterpolationMode.NEAREST_EXACT:
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
            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 list or tuple 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(
688
689
690
691
692
        "make_input",
        [
            make_image_tensor,
            make_image_pil,
            make_image,
693
            make_bounding_boxes,
694
695
696
697
            make_segmentation_mask,
            make_detection_mask,
            make_video,
        ],
698
    )
699
700
    def test_noop(self, size, make_input):
        input = make_input(self.INPUT_SIZE)
701

Philip Meier's avatar
Philip Meier committed
702
        output = F.resize(input, size=F.get_size(input), antialias=True)
703
704
705

        # 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.
706
        if isinstance(input, datapoints.Datapoint):
707
708
709
710
711
712
713
714
            # We can't test identity directly, since that checks for the identity of the Python object. Since all
            # datapoints 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(
715
716
717
718
719
        "make_input",
        [
            make_image_tensor,
            make_image_pil,
            make_image,
720
            make_bounding_boxes,
721
722
723
724
            make_segmentation_mask,
            make_detection_mask,
            make_video,
        ],
725
    )
726
    def test_no_regression_5405(self, make_input):
727
728
729
        # Checks that `max_size` is not ignored if `size == small_edge_size`
        # See https://github.com/pytorch/vision/issues/5405

730
        input = make_input(self.INPUT_SIZE)
731

Philip Meier's avatar
Philip Meier committed
732
        size = min(F.get_size(input))
733
734
735
        max_size = size + 1
        output = F.resize(input, size=size, max_size=max_size, antialias=True)

Philip Meier's avatar
Philip Meier committed
736
        assert max(F.get_size(output)) == max_size
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
    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 = datapoints.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])

        assert output.dtype is torch.float16
        assert (output.round() - output).abs().sum() > 0

798
799
800
801
802

class TestHorizontalFlip:
    @pytest.mark.parametrize("dtype", [torch.float32, torch.uint8])
    @pytest.mark.parametrize("device", cpu_and_cuda())
    def test_kernel_image_tensor(self, dtype, device):
803
        check_kernel(F.horizontal_flip_image, make_image(dtype=dtype, device=device))
804
805
806
807

    @pytest.mark.parametrize("format", list(datapoints.BoundingBoxFormat))
    @pytest.mark.parametrize("dtype", [torch.float32, torch.int64])
    @pytest.mark.parametrize("device", cpu_and_cuda())
808
    def test_kernel_bounding_boxes(self, format, dtype, device):
809
        bounding_boxes = make_bounding_boxes(format=format, dtype=dtype, device=device)
810
        check_kernel(
811
812
            F.horizontal_flip_bounding_boxes,
            bounding_boxes,
813
            format=format,
Philip Meier's avatar
Philip Meier committed
814
            canvas_size=bounding_boxes.canvas_size,
815
816
        )

817
818
819
    @pytest.mark.parametrize("make_mask", [make_segmentation_mask, make_detection_mask])
    def test_kernel_mask(self, make_mask):
        check_kernel(F.horizontal_flip_mask, make_mask())
820
821

    def test_kernel_video(self):
822
        check_kernel(F.horizontal_flip_video, make_video())
823
824

    @pytest.mark.parametrize(
Philip Meier's avatar
Philip Meier committed
825
        "make_input",
826
        [make_image_tensor, make_image_pil, make_image, make_bounding_boxes, make_segmentation_mask, make_video],
827
    )
Nicolas Hug's avatar
Nicolas Hug committed
828
829
    def test_functional(self, make_input):
        check_functional(F.horizontal_flip, make_input())
830
831

    @pytest.mark.parametrize(
832
        ("kernel", "input_type"),
833
        [
834
835
836
            (F.horizontal_flip_image, torch.Tensor),
            (F._horizontal_flip_image_pil, PIL.Image.Image),
            (F.horizontal_flip_image, datapoints.Image),
837
            (F.horizontal_flip_bounding_boxes, datapoints.BoundingBoxes),
838
839
            (F.horizontal_flip_mask, datapoints.Mask),
            (F.horizontal_flip_video, datapoints.Video),
840
841
        ],
    )
Nicolas Hug's avatar
Nicolas Hug committed
842
843
    def test_functional_signature(self, kernel, input_type):
        check_functional_kernel_signature_match(F.horizontal_flip, kernel=kernel, input_type=input_type)
844
845

    @pytest.mark.parametrize(
846
        "make_input",
847
        [make_image_tensor, make_image_pil, make_image, make_bounding_boxes, make_segmentation_mask, make_video],
848
849
    )
    @pytest.mark.parametrize("device", cpu_and_cuda())
850
851
    def test_transform(self, make_input, device):
        check_transform(transforms.RandomHorizontalFlip, make_input(device=device), p=1)
852
853
854
855
856

    @pytest.mark.parametrize(
        "fn", [F.horizontal_flip, transform_cls_to_functional(transforms.RandomHorizontalFlip, p=1)]
    )
    def test_image_correctness(self, fn):
857
        image = make_image(dtype=torch.uint8, device="cpu")
858
859

        actual = fn(image)
860
        expected = F.to_image(F.horizontal_flip(F.to_pil_image(image)))
861
862
863

        torch.testing.assert_close(actual, expected)

864
    def _reference_horizontal_flip_bounding_boxes(self, bounding_boxes):
865
866
        affine_matrix = np.array(
            [
Philip Meier's avatar
Philip Meier committed
867
                [-1, 0, bounding_boxes.canvas_size[1]],
868
869
                [0, 1, 0],
            ],
870
            dtype="float64" if bounding_boxes.dtype == torch.float64 else "float32",
871
872
        )

873
874
875
        expected_bboxes = reference_affine_bounding_boxes_helper(
            bounding_boxes,
            format=bounding_boxes.format,
Philip Meier's avatar
Philip Meier committed
876
            canvas_size=bounding_boxes.canvas_size,
877
878
879
            affine_matrix=affine_matrix,
        )

880
        return datapoints.wrap(expected_bboxes, like=bounding_boxes)
881
882
883
884
885

    @pytest.mark.parametrize("format", list(datapoints.BoundingBoxFormat))
    @pytest.mark.parametrize(
        "fn", [F.horizontal_flip, transform_cls_to_functional(transforms.RandomHorizontalFlip, p=1)]
    )
886
    def test_bounding_boxes_correctness(self, format, fn):
887
        bounding_boxes = make_bounding_boxes(format=format)
888

889
890
        actual = fn(bounding_boxes)
        expected = self._reference_horizontal_flip_bounding_boxes(bounding_boxes)
891
892
893
894

        torch.testing.assert_close(actual, expected)

    @pytest.mark.parametrize(
895
        "make_input",
896
        [make_image_tensor, make_image_pil, make_image, make_bounding_boxes, make_segmentation_mask, make_video],
897
898
    )
    @pytest.mark.parametrize("device", cpu_and_cuda())
899
900
    def test_transform_noop(self, make_input, device):
        input = make_input(device=device)
901
902
903
904
905
906

        transform = transforms.RandomHorizontalFlip(p=0)

        output = transform(input)

        assert_equal(output, input)
Philip Meier's avatar
Philip Meier committed
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


class TestAffine:
    _EXHAUSTIVE_TYPE_AFFINE_KWARGS = dict(
        # float, int
        angle=[-10.9, 18],
        # two-list of float, two-list of int, two-tuple of float, two-tuple of int
        translate=[[6.3, -0.6], [1, -3], (16.6, -6.6), (-2, 4)],
        # float
        scale=[0.5],
        # float, int,
        # one-list of float, one-list of int, one-tuple of float, one-tuple of int
        # two-list of float, two-list of int, two-tuple of float, two-tuple of int
        shear=[35.6, 38, [-37.7], [-23], (5.3,), (-52,), [5.4, 21.8], [-47, 51], (-11.2, 36.7), (8, -53)],
        # None
        # two-list of float, two-list of int, two-tuple of float, two-tuple of int
        center=[None, [1.2, 4.9], [-3, 1], (2.5, -4.7), (3, 2)],
    )
    # The special case for shear makes sure we pick a value that is supported while JIT scripting
    _MINIMAL_AFFINE_KWARGS = {
        k: vs[0] if k != "shear" else next(v for v in vs if isinstance(v, list))
        for k, vs in _EXHAUSTIVE_TYPE_AFFINE_KWARGS.items()
    }
    _CORRECTNESS_AFFINE_KWARGS = {
        k: [v for v in vs if v is None or isinstance(v, float) or (isinstance(v, list) and len(v) > 1)]
        for k, vs in _EXHAUSTIVE_TYPE_AFFINE_KWARGS.items()
    }

    _EXHAUSTIVE_TYPE_TRANSFORM_AFFINE_RANGES = dict(
        degrees=[30, (-15, 20)],
        translate=[None, (0.5, 0.5)],
        scale=[None, (0.75, 1.25)],
        shear=[None, (12, 30, -17, 5), 10, (-5, 12)],
    )
    _CORRECTNESS_TRANSFORM_AFFINE_RANGES = {
        k: next(v for v in vs if v is not None) for k, vs in _EXHAUSTIVE_TYPE_TRANSFORM_AFFINE_RANGES.items()
    }

    def _check_kernel(self, kernel, input, *args, **kwargs):
        kwargs_ = self._MINIMAL_AFFINE_KWARGS.copy()
        kwargs_.update(kwargs)
        check_kernel(kernel, input, *args, **kwargs_)

Philip Meier's avatar
Philip Meier committed
950
951
952
953
954
955
956
    @param_value_parametrization(
        angle=_EXHAUSTIVE_TYPE_AFFINE_KWARGS["angle"],
        translate=_EXHAUSTIVE_TYPE_AFFINE_KWARGS["translate"],
        shear=_EXHAUSTIVE_TYPE_AFFINE_KWARGS["shear"],
        center=_EXHAUSTIVE_TYPE_AFFINE_KWARGS["center"],
        interpolation=[transforms.InterpolationMode.NEAREST, transforms.InterpolationMode.BILINEAR],
        fill=EXHAUSTIVE_TYPE_FILLS,
Philip Meier's avatar
Philip Meier committed
957
958
959
960
961
    )
    @pytest.mark.parametrize("dtype", [torch.float32, torch.uint8])
    @pytest.mark.parametrize("device", cpu_and_cuda())
    def test_kernel_image_tensor(self, param, value, dtype, device):
        if param == "fill":
Philip Meier's avatar
Philip Meier committed
962
            value = adapt_fill(value, dtype=dtype)
Philip Meier's avatar
Philip Meier committed
963
        self._check_kernel(
964
            F.affine_image,
965
            make_image(dtype=dtype, device=device),
Philip Meier's avatar
Philip Meier committed
966
967
968
969
970
971
972
            **{param: value},
            check_scripted_vs_eager=not (param in {"shear", "fill"} and isinstance(value, (int, float))),
            check_cuda_vs_cpu=dict(atol=1, rtol=0)
            if dtype is torch.uint8 and param == "interpolation" and value is transforms.InterpolationMode.BILINEAR
            else True,
        )

Philip Meier's avatar
Philip Meier committed
973
974
975
976
977
    @param_value_parametrization(
        angle=_EXHAUSTIVE_TYPE_AFFINE_KWARGS["angle"],
        translate=_EXHAUSTIVE_TYPE_AFFINE_KWARGS["translate"],
        shear=_EXHAUSTIVE_TYPE_AFFINE_KWARGS["shear"],
        center=_EXHAUSTIVE_TYPE_AFFINE_KWARGS["center"],
Philip Meier's avatar
Philip Meier committed
978
979
980
981
    )
    @pytest.mark.parametrize("format", list(datapoints.BoundingBoxFormat))
    @pytest.mark.parametrize("dtype", [torch.float32, torch.int64])
    @pytest.mark.parametrize("device", cpu_and_cuda())
982
    def test_kernel_bounding_boxes(self, param, value, format, dtype, device):
983
        bounding_boxes = make_bounding_boxes(format=format, dtype=dtype, device=device)
Philip Meier's avatar
Philip Meier committed
984
        self._check_kernel(
985
986
            F.affine_bounding_boxes,
            bounding_boxes,
Philip Meier's avatar
Philip Meier committed
987
            format=format,
Philip Meier's avatar
Philip Meier committed
988
            canvas_size=bounding_boxes.canvas_size,
Philip Meier's avatar
Philip Meier committed
989
990
991
992
            **{param: value},
            check_scripted_vs_eager=not (param == "shear" and isinstance(value, (int, float))),
        )

993
994
995
    @pytest.mark.parametrize("make_mask", [make_segmentation_mask, make_detection_mask])
    def test_kernel_mask(self, make_mask):
        self._check_kernel(F.affine_mask, make_mask())
Philip Meier's avatar
Philip Meier committed
996
997

    def test_kernel_video(self):
998
        self._check_kernel(F.affine_video, make_video())
Philip Meier's avatar
Philip Meier committed
999
1000

    @pytest.mark.parametrize(
Philip Meier's avatar
Philip Meier committed
1001
        "make_input",
1002
        [make_image_tensor, make_image_pil, make_image, make_bounding_boxes, make_segmentation_mask, make_video],
Philip Meier's avatar
Philip Meier committed
1003
    )
Nicolas Hug's avatar
Nicolas Hug committed
1004
1005
    def test_functional(self, make_input):
        check_functional(F.affine, make_input(), **self._MINIMAL_AFFINE_KWARGS)
Philip Meier's avatar
Philip Meier committed
1006
1007

    @pytest.mark.parametrize(
1008
        ("kernel", "input_type"),
Philip Meier's avatar
Philip Meier committed
1009
        [
1010
1011
1012
            (F.affine_image, torch.Tensor),
            (F._affine_image_pil, PIL.Image.Image),
            (F.affine_image, datapoints.Image),
1013
            (F.affine_bounding_boxes, datapoints.BoundingBoxes),
1014
1015
            (F.affine_mask, datapoints.Mask),
            (F.affine_video, datapoints.Video),
Philip Meier's avatar
Philip Meier committed
1016
1017
        ],
    )
Nicolas Hug's avatar
Nicolas Hug committed
1018
1019
    def test_functional_signature(self, kernel, input_type):
        check_functional_kernel_signature_match(F.affine, kernel=kernel, input_type=input_type)
Philip Meier's avatar
Philip Meier committed
1020
1021

    @pytest.mark.parametrize(
1022
        "make_input",
1023
        [make_image_tensor, make_image_pil, make_image, make_bounding_boxes, make_segmentation_mask, make_video],
Philip Meier's avatar
Philip Meier committed
1024
1025
    )
    @pytest.mark.parametrize("device", cpu_and_cuda())
1026
1027
    def test_transform(self, make_input, device):
        input = make_input(device=device)
Philip Meier's avatar
Philip Meier committed
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038

        check_transform(transforms.RandomAffine, input, **self._CORRECTNESS_TRANSFORM_AFFINE_RANGES)

    @pytest.mark.parametrize("angle", _CORRECTNESS_AFFINE_KWARGS["angle"])
    @pytest.mark.parametrize("translate", _CORRECTNESS_AFFINE_KWARGS["translate"])
    @pytest.mark.parametrize("scale", _CORRECTNESS_AFFINE_KWARGS["scale"])
    @pytest.mark.parametrize("shear", _CORRECTNESS_AFFINE_KWARGS["shear"])
    @pytest.mark.parametrize("center", _CORRECTNESS_AFFINE_KWARGS["center"])
    @pytest.mark.parametrize(
        "interpolation", [transforms.InterpolationMode.NEAREST, transforms.InterpolationMode.BILINEAR]
    )
Philip Meier's avatar
Philip Meier committed
1039
    @pytest.mark.parametrize("fill", CORRECTNESS_FILLS)
Philip Meier's avatar
Philip Meier committed
1040
    def test_functional_image_correctness(self, angle, translate, scale, shear, center, interpolation, fill):
1041
        image = make_image(dtype=torch.uint8, device="cpu")
Philip Meier's avatar
Philip Meier committed
1042

Philip Meier's avatar
Philip Meier committed
1043
        fill = adapt_fill(fill, dtype=torch.uint8)
Philip Meier's avatar
Philip Meier committed
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054

        actual = F.affine(
            image,
            angle=angle,
            translate=translate,
            scale=scale,
            shear=shear,
            center=center,
            interpolation=interpolation,
            fill=fill,
        )
1055
        expected = F.to_image(
Philip Meier's avatar
Philip Meier committed
1056
            F.affine(
1057
                F.to_pil_image(image),
Philip Meier's avatar
Philip Meier committed
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
                angle=angle,
                translate=translate,
                scale=scale,
                shear=shear,
                center=center,
                interpolation=interpolation,
                fill=fill,
            )
        )

        mae = (actual.float() - expected.float()).abs().mean()
        assert mae < 2 if interpolation is transforms.InterpolationMode.NEAREST else 8

    @pytest.mark.parametrize("center", _CORRECTNESS_AFFINE_KWARGS["center"])
    @pytest.mark.parametrize(
        "interpolation", [transforms.InterpolationMode.NEAREST, transforms.InterpolationMode.BILINEAR]
    )
Philip Meier's avatar
Philip Meier committed
1075
    @pytest.mark.parametrize("fill", CORRECTNESS_FILLS)
Philip Meier's avatar
Philip Meier committed
1076
1077
    @pytest.mark.parametrize("seed", list(range(5)))
    def test_transform_image_correctness(self, center, interpolation, fill, seed):
1078
        image = make_image(dtype=torch.uint8, device="cpu")
Philip Meier's avatar
Philip Meier committed
1079

Philip Meier's avatar
Philip Meier committed
1080
        fill = adapt_fill(fill, dtype=torch.uint8)
Philip Meier's avatar
Philip Meier committed
1081
1082
1083
1084
1085
1086
1087
1088
1089

        transform = transforms.RandomAffine(
            **self._CORRECTNESS_TRANSFORM_AFFINE_RANGES, center=center, interpolation=interpolation, fill=fill
        )

        torch.manual_seed(seed)
        actual = transform(image)

        torch.manual_seed(seed)
1090
        expected = F.to_image(transform(F.to_pil_image(image)))
Philip Meier's avatar
Philip Meier committed
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116

        mae = (actual.float() - expected.float()).abs().mean()
        assert mae < 2 if interpolation is transforms.InterpolationMode.NEAREST else 8

    def _compute_affine_matrix(self, *, angle, translate, scale, shear, center):
        rot = math.radians(angle)
        cx, cy = center
        tx, ty = translate
        sx, sy = [math.radians(s) for s in ([shear, 0.0] if isinstance(shear, (int, float)) else shear)]

        c_matrix = np.array([[1, 0, cx], [0, 1, cy], [0, 0, 1]])
        t_matrix = np.array([[1, 0, tx], [0, 1, ty], [0, 0, 1]])
        c_matrix_inv = np.linalg.inv(c_matrix)
        rs_matrix = np.array(
            [
                [scale * math.cos(rot), -scale * math.sin(rot), 0],
                [scale * math.sin(rot), scale * math.cos(rot), 0],
                [0, 0, 1],
            ]
        )
        shear_x_matrix = np.array([[1, -math.tan(sx), 0], [0, 1, 0], [0, 0, 1]])
        shear_y_matrix = np.array([[1, 0, 0], [-math.tan(sy), 1, 0], [0, 0, 1]])
        rss_matrix = np.matmul(rs_matrix, np.matmul(shear_y_matrix, shear_x_matrix))
        true_matrix = np.matmul(t_matrix, np.matmul(c_matrix, np.matmul(rss_matrix, c_matrix_inv)))
        return true_matrix

1117
    def _reference_affine_bounding_boxes(self, bounding_boxes, *, angle, translate, scale, shear, center):
Philip Meier's avatar
Philip Meier committed
1118
        if center is None:
Philip Meier's avatar
Philip Meier committed
1119
            center = [s * 0.5 for s in bounding_boxes.canvas_size[::-1]]
Philip Meier's avatar
Philip Meier committed
1120
1121
1122
1123
1124
1125

        affine_matrix = self._compute_affine_matrix(
            angle=angle, translate=translate, scale=scale, shear=shear, center=center
        )
        affine_matrix = affine_matrix[:2, :]

1126
1127
1128
        expected_bboxes = reference_affine_bounding_boxes_helper(
            bounding_boxes,
            format=bounding_boxes.format,
Philip Meier's avatar
Philip Meier committed
1129
            canvas_size=bounding_boxes.canvas_size,
Philip Meier's avatar
Philip Meier committed
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
            affine_matrix=affine_matrix,
        )

        return expected_bboxes

    @pytest.mark.parametrize("format", list(datapoints.BoundingBoxFormat))
    @pytest.mark.parametrize("angle", _CORRECTNESS_AFFINE_KWARGS["angle"])
    @pytest.mark.parametrize("translate", _CORRECTNESS_AFFINE_KWARGS["translate"])
    @pytest.mark.parametrize("scale", _CORRECTNESS_AFFINE_KWARGS["scale"])
    @pytest.mark.parametrize("shear", _CORRECTNESS_AFFINE_KWARGS["shear"])
    @pytest.mark.parametrize("center", _CORRECTNESS_AFFINE_KWARGS["center"])
1141
    def test_functional_bounding_boxes_correctness(self, format, angle, translate, scale, shear, center):
1142
        bounding_boxes = make_bounding_boxes(format=format)
Philip Meier's avatar
Philip Meier committed
1143
1144

        actual = F.affine(
1145
            bounding_boxes,
Philip Meier's avatar
Philip Meier committed
1146
1147
1148
1149
1150
1151
            angle=angle,
            translate=translate,
            scale=scale,
            shear=shear,
            center=center,
        )
1152
1153
        expected = self._reference_affine_bounding_boxes(
            bounding_boxes,
Philip Meier's avatar
Philip Meier committed
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
            angle=angle,
            translate=translate,
            scale=scale,
            shear=shear,
            center=center,
        )

        torch.testing.assert_close(actual, expected)

    @pytest.mark.parametrize("format", list(datapoints.BoundingBoxFormat))
    @pytest.mark.parametrize("center", _CORRECTNESS_AFFINE_KWARGS["center"])
    @pytest.mark.parametrize("seed", list(range(5)))
1166
    def test_transform_bounding_boxes_correctness(self, format, center, seed):
1167
        bounding_boxes = make_bounding_boxes(format=format)
Philip Meier's avatar
Philip Meier committed
1168
1169
1170
1171

        transform = transforms.RandomAffine(**self._CORRECTNESS_TRANSFORM_AFFINE_RANGES, center=center)

        torch.manual_seed(seed)
1172
        params = transform._get_params([bounding_boxes])
Philip Meier's avatar
Philip Meier committed
1173
1174

        torch.manual_seed(seed)
1175
        actual = transform(bounding_boxes)
Philip Meier's avatar
Philip Meier committed
1176

1177
        expected = self._reference_affine_bounding_boxes(bounding_boxes, **params, center=center)
Philip Meier's avatar
Philip Meier committed
1178
1179
1180
1181
1182
1183
1184
1185
1186

        torch.testing.assert_close(actual, expected)

    @pytest.mark.parametrize("degrees", _EXHAUSTIVE_TYPE_TRANSFORM_AFFINE_RANGES["degrees"])
    @pytest.mark.parametrize("translate", _EXHAUSTIVE_TYPE_TRANSFORM_AFFINE_RANGES["translate"])
    @pytest.mark.parametrize("scale", _EXHAUSTIVE_TYPE_TRANSFORM_AFFINE_RANGES["scale"])
    @pytest.mark.parametrize("shear", _EXHAUSTIVE_TYPE_TRANSFORM_AFFINE_RANGES["shear"])
    @pytest.mark.parametrize("seed", list(range(10)))
    def test_transform_get_params_bounds(self, degrees, translate, scale, shear, seed):
1187
        image = make_image()
Philip Meier's avatar
Philip Meier committed
1188
        height, width = F.get_size(image)
Philip Meier's avatar
Philip Meier committed
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261

        transform = transforms.RandomAffine(degrees=degrees, translate=translate, scale=scale, shear=shear)

        torch.manual_seed(seed)
        params = transform._get_params([image])

        if isinstance(degrees, (int, float)):
            assert -degrees <= params["angle"] <= degrees
        else:
            assert degrees[0] <= params["angle"] <= degrees[1]

        if translate is not None:
            width_max = int(round(translate[0] * width))
            height_max = int(round(translate[1] * height))
            assert -width_max <= params["translate"][0] <= width_max
            assert -height_max <= params["translate"][1] <= height_max
        else:
            assert params["translate"] == (0, 0)

        if scale is not None:
            assert scale[0] <= params["scale"] <= scale[1]
        else:
            assert params["scale"] == 1.0

        if shear is not None:
            if isinstance(shear, (int, float)):
                assert -shear <= params["shear"][0] <= shear
                assert params["shear"][1] == 0.0
            elif len(shear) == 2:
                assert shear[0] <= params["shear"][0] <= shear[1]
                assert params["shear"][1] == 0.0
            elif len(shear) == 4:
                assert shear[0] <= params["shear"][0] <= shear[1]
                assert shear[2] <= params["shear"][1] <= shear[3]
        else:
            assert params["shear"] == (0, 0)

    @pytest.mark.parametrize("param", ["degrees", "translate", "scale", "shear", "center"])
    @pytest.mark.parametrize("value", [0, [0], [0, 0, 0]])
    def test_transform_sequence_len_errors(self, param, value):
        if param in {"degrees", "shear"} and not isinstance(value, list):
            return

        kwargs = {param: value}
        if param != "degrees":
            kwargs["degrees"] = 0

        with pytest.raises(
            ValueError if isinstance(value, list) else TypeError, match=f"{param} should be a sequence of length 2"
        ):
            transforms.RandomAffine(**kwargs)

    def test_transform_negative_degrees_error(self):
        with pytest.raises(ValueError, match="If degrees is a single number, it must be positive"):
            transforms.RandomAffine(degrees=-1)

    @pytest.mark.parametrize("translate", [[-1, 0], [2, 0], [-1, 2]])
    def test_transform_translate_range_error(self, translate):
        with pytest.raises(ValueError, match="translation values should be between 0 and 1"):
            transforms.RandomAffine(degrees=0, translate=translate)

    @pytest.mark.parametrize("scale", [[-1, 0], [0, -1], [-1, -1]])
    def test_transform_scale_range_error(self, scale):
        with pytest.raises(ValueError, match="scale values should be positive"):
            transforms.RandomAffine(degrees=0, scale=scale)

    def test_transform_negative_shear_error(self):
        with pytest.raises(ValueError, match="If shear is a single number, it must be positive"):
            transforms.RandomAffine(degrees=0, shear=-1)

    def test_transform_unknown_fill_error(self):
        with pytest.raises(TypeError, match="Got inappropriate fill arg"):
            transforms.RandomAffine(degrees=0, fill="fill")
Philip Meier's avatar
Philip Meier committed
1262
1263
1264
1265
1266
1267


class TestVerticalFlip:
    @pytest.mark.parametrize("dtype", [torch.float32, torch.uint8])
    @pytest.mark.parametrize("device", cpu_and_cuda())
    def test_kernel_image_tensor(self, dtype, device):
1268
        check_kernel(F.vertical_flip_image, make_image(dtype=dtype, device=device))
Philip Meier's avatar
Philip Meier committed
1269
1270
1271
1272

    @pytest.mark.parametrize("format", list(datapoints.BoundingBoxFormat))
    @pytest.mark.parametrize("dtype", [torch.float32, torch.int64])
    @pytest.mark.parametrize("device", cpu_and_cuda())
1273
    def test_kernel_bounding_boxes(self, format, dtype, device):
1274
        bounding_boxes = make_bounding_boxes(format=format, dtype=dtype, device=device)
Philip Meier's avatar
Philip Meier committed
1275
        check_kernel(
1276
1277
            F.vertical_flip_bounding_boxes,
            bounding_boxes,
Philip Meier's avatar
Philip Meier committed
1278
            format=format,
Philip Meier's avatar
Philip Meier committed
1279
            canvas_size=bounding_boxes.canvas_size,
Philip Meier's avatar
Philip Meier committed
1280
1281
        )

1282
1283
1284
    @pytest.mark.parametrize("make_mask", [make_segmentation_mask, make_detection_mask])
    def test_kernel_mask(self, make_mask):
        check_kernel(F.vertical_flip_mask, make_mask())
Philip Meier's avatar
Philip Meier committed
1285
1286

    def test_kernel_video(self):
1287
        check_kernel(F.vertical_flip_video, make_video())
Philip Meier's avatar
Philip Meier committed
1288
1289

    @pytest.mark.parametrize(
Philip Meier's avatar
Philip Meier committed
1290
        "make_input",
1291
        [make_image_tensor, make_image_pil, make_image, make_bounding_boxes, make_segmentation_mask, make_video],
Philip Meier's avatar
Philip Meier committed
1292
    )
Nicolas Hug's avatar
Nicolas Hug committed
1293
1294
    def test_functional(self, make_input):
        check_functional(F.vertical_flip, make_input())
Philip Meier's avatar
Philip Meier committed
1295
1296

    @pytest.mark.parametrize(
1297
        ("kernel", "input_type"),
Philip Meier's avatar
Philip Meier committed
1298
        [
1299
1300
1301
            (F.vertical_flip_image, torch.Tensor),
            (F._vertical_flip_image_pil, PIL.Image.Image),
            (F.vertical_flip_image, datapoints.Image),
1302
            (F.vertical_flip_bounding_boxes, datapoints.BoundingBoxes),
1303
1304
            (F.vertical_flip_mask, datapoints.Mask),
            (F.vertical_flip_video, datapoints.Video),
Philip Meier's avatar
Philip Meier committed
1305
1306
        ],
    )
Nicolas Hug's avatar
Nicolas Hug committed
1307
1308
    def test_functional_signature(self, kernel, input_type):
        check_functional_kernel_signature_match(F.vertical_flip, kernel=kernel, input_type=input_type)
Philip Meier's avatar
Philip Meier committed
1309
1310

    @pytest.mark.parametrize(
1311
        "make_input",
1312
        [make_image_tensor, make_image_pil, make_image, make_bounding_boxes, make_segmentation_mask, make_video],
Philip Meier's avatar
Philip Meier committed
1313
1314
    )
    @pytest.mark.parametrize("device", cpu_and_cuda())
1315
1316
    def test_transform(self, make_input, device):
        check_transform(transforms.RandomVerticalFlip, make_input(device=device), p=1)
Philip Meier's avatar
Philip Meier committed
1317
1318
1319

    @pytest.mark.parametrize("fn", [F.vertical_flip, transform_cls_to_functional(transforms.RandomVerticalFlip, p=1)])
    def test_image_correctness(self, fn):
1320
        image = make_image(dtype=torch.uint8, device="cpu")
Philip Meier's avatar
Philip Meier committed
1321
1322

        actual = fn(image)
1323
        expected = F.to_image(F.vertical_flip(F.to_pil_image(image)))
Philip Meier's avatar
Philip Meier committed
1324
1325
1326

        torch.testing.assert_close(actual, expected)

1327
    def _reference_vertical_flip_bounding_boxes(self, bounding_boxes):
Philip Meier's avatar
Philip Meier committed
1328
1329
1330
        affine_matrix = np.array(
            [
                [1, 0, 0],
Philip Meier's avatar
Philip Meier committed
1331
                [0, -1, bounding_boxes.canvas_size[0]],
Philip Meier's avatar
Philip Meier committed
1332
            ],
1333
            dtype="float64" if bounding_boxes.dtype == torch.float64 else "float32",
Philip Meier's avatar
Philip Meier committed
1334
1335
        )

1336
1337
1338
        expected_bboxes = reference_affine_bounding_boxes_helper(
            bounding_boxes,
            format=bounding_boxes.format,
Philip Meier's avatar
Philip Meier committed
1339
            canvas_size=bounding_boxes.canvas_size,
Philip Meier's avatar
Philip Meier committed
1340
1341
1342
            affine_matrix=affine_matrix,
        )

1343
        return datapoints.wrap(expected_bboxes, like=bounding_boxes)
Philip Meier's avatar
Philip Meier committed
1344
1345
1346

    @pytest.mark.parametrize("format", list(datapoints.BoundingBoxFormat))
    @pytest.mark.parametrize("fn", [F.vertical_flip, transform_cls_to_functional(transforms.RandomVerticalFlip, p=1)])
1347
    def test_bounding_boxes_correctness(self, format, fn):
1348
        bounding_boxes = make_bounding_boxes(format=format)
Philip Meier's avatar
Philip Meier committed
1349

1350
1351
        actual = fn(bounding_boxes)
        expected = self._reference_vertical_flip_bounding_boxes(bounding_boxes)
Philip Meier's avatar
Philip Meier committed
1352
1353
1354
1355

        torch.testing.assert_close(actual, expected)

    @pytest.mark.parametrize(
1356
        "make_input",
1357
        [make_image_tensor, make_image_pil, make_image, make_bounding_boxes, make_segmentation_mask, make_video],
Philip Meier's avatar
Philip Meier committed
1358
1359
    )
    @pytest.mark.parametrize("device", cpu_and_cuda())
1360
1361
    def test_transform_noop(self, make_input, device):
        input = make_input(device=device)
Philip Meier's avatar
Philip Meier committed
1362
1363
1364
1365
1366
1367

        transform = transforms.RandomVerticalFlip(p=0)

        output = transform(input)

        assert_equal(output, input)
Philip Meier's avatar
Philip Meier committed
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402


class TestRotate:
    _EXHAUSTIVE_TYPE_AFFINE_KWARGS = dict(
        # float, int
        angle=[-10.9, 18],
        # None
        # two-list of float, two-list of int, two-tuple of float, two-tuple of int
        center=[None, [1.2, 4.9], [-3, 1], (2.5, -4.7), (3, 2)],
    )
    _MINIMAL_AFFINE_KWARGS = {k: vs[0] for k, vs in _EXHAUSTIVE_TYPE_AFFINE_KWARGS.items()}
    _CORRECTNESS_AFFINE_KWARGS = {
        k: [v for v in vs if v is None or isinstance(v, float) or isinstance(v, list)]
        for k, vs in _EXHAUSTIVE_TYPE_AFFINE_KWARGS.items()
    }

    _EXHAUSTIVE_TYPE_TRANSFORM_AFFINE_RANGES = dict(
        degrees=[30, (-15, 20)],
    )
    _CORRECTNESS_TRANSFORM_AFFINE_RANGES = {k: vs[0] for k, vs in _EXHAUSTIVE_TYPE_TRANSFORM_AFFINE_RANGES.items()}

    @param_value_parametrization(
        angle=_EXHAUSTIVE_TYPE_AFFINE_KWARGS["angle"],
        interpolation=[transforms.InterpolationMode.NEAREST, transforms.InterpolationMode.BILINEAR],
        expand=[False, True],
        center=_EXHAUSTIVE_TYPE_AFFINE_KWARGS["center"],
        fill=EXHAUSTIVE_TYPE_FILLS,
    )
    @pytest.mark.parametrize("dtype", [torch.float32, torch.uint8])
    @pytest.mark.parametrize("device", cpu_and_cuda())
    def test_kernel_image_tensor(self, param, value, dtype, device):
        kwargs = {param: value}
        if param != "angle":
            kwargs["angle"] = self._MINIMAL_AFFINE_KWARGS["angle"]
        check_kernel(
1403
            F.rotate_image,
1404
            make_image(dtype=dtype, device=device),
Philip Meier's avatar
Philip Meier committed
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
            **kwargs,
            check_scripted_vs_eager=not (param == "fill" and isinstance(value, (int, float))),
        )

    @param_value_parametrization(
        angle=_EXHAUSTIVE_TYPE_AFFINE_KWARGS["angle"],
        expand=[False, True],
        center=_EXHAUSTIVE_TYPE_AFFINE_KWARGS["center"],
    )
    @pytest.mark.parametrize("format", list(datapoints.BoundingBoxFormat))
    @pytest.mark.parametrize("dtype", [torch.float32, torch.uint8])
    @pytest.mark.parametrize("device", cpu_and_cuda())
1417
    def test_kernel_bounding_boxes(self, param, value, format, dtype, device):
Philip Meier's avatar
Philip Meier committed
1418
1419
1420
1421
        kwargs = {param: value}
        if param != "angle":
            kwargs["angle"] = self._MINIMAL_AFFINE_KWARGS["angle"]

1422
        bounding_boxes = make_bounding_boxes(format=format, dtype=dtype, device=device)
Philip Meier's avatar
Philip Meier committed
1423
1424

        check_kernel(
1425
1426
            F.rotate_bounding_boxes,
            bounding_boxes,
Philip Meier's avatar
Philip Meier committed
1427
            format=format,
Philip Meier's avatar
Philip Meier committed
1428
            canvas_size=bounding_boxes.canvas_size,
Philip Meier's avatar
Philip Meier committed
1429
1430
1431
            **kwargs,
        )

1432
1433
1434
    @pytest.mark.parametrize("make_mask", [make_segmentation_mask, make_detection_mask])
    def test_kernel_mask(self, make_mask):
        check_kernel(F.rotate_mask, make_mask(), **self._MINIMAL_AFFINE_KWARGS)
Philip Meier's avatar
Philip Meier committed
1435
1436

    def test_kernel_video(self):
1437
        check_kernel(F.rotate_video, make_video(), **self._MINIMAL_AFFINE_KWARGS)
Philip Meier's avatar
Philip Meier committed
1438
1439

    @pytest.mark.parametrize(
Philip Meier's avatar
Philip Meier committed
1440
        "make_input",
1441
        [make_image_tensor, make_image_pil, make_image, make_bounding_boxes, make_segmentation_mask, make_video],
Philip Meier's avatar
Philip Meier committed
1442
    )
Nicolas Hug's avatar
Nicolas Hug committed
1443
1444
    def test_functional(self, make_input):
        check_functional(F.rotate, make_input(), **self._MINIMAL_AFFINE_KWARGS)
Philip Meier's avatar
Philip Meier committed
1445
1446

    @pytest.mark.parametrize(
1447
        ("kernel", "input_type"),
Philip Meier's avatar
Philip Meier committed
1448
        [
1449
1450
1451
            (F.rotate_image, torch.Tensor),
            (F._rotate_image_pil, PIL.Image.Image),
            (F.rotate_image, datapoints.Image),
1452
            (F.rotate_bounding_boxes, datapoints.BoundingBoxes),
1453
1454
            (F.rotate_mask, datapoints.Mask),
            (F.rotate_video, datapoints.Video),
Philip Meier's avatar
Philip Meier committed
1455
1456
        ],
    )
Nicolas Hug's avatar
Nicolas Hug committed
1457
1458
    def test_functional_signature(self, kernel, input_type):
        check_functional_kernel_signature_match(F.rotate, kernel=kernel, input_type=input_type)
Philip Meier's avatar
Philip Meier committed
1459
1460

    @pytest.mark.parametrize(
1461
        "make_input",
1462
        [make_image_tensor, make_image_pil, make_image, make_bounding_boxes, make_segmentation_mask, make_video],
Philip Meier's avatar
Philip Meier committed
1463
1464
    )
    @pytest.mark.parametrize("device", cpu_and_cuda())
1465
1466
1467
1468
    def test_transform(self, make_input, device):
        check_transform(
            transforms.RandomRotation, make_input(device=device), **self._CORRECTNESS_TRANSFORM_AFFINE_RANGES
        )
Philip Meier's avatar
Philip Meier committed
1469
1470
1471
1472
1473
1474
1475
1476
1477

    @pytest.mark.parametrize("angle", _CORRECTNESS_AFFINE_KWARGS["angle"])
    @pytest.mark.parametrize("center", _CORRECTNESS_AFFINE_KWARGS["center"])
    @pytest.mark.parametrize(
        "interpolation", [transforms.InterpolationMode.NEAREST, transforms.InterpolationMode.BILINEAR]
    )
    @pytest.mark.parametrize("expand", [False, True])
    @pytest.mark.parametrize("fill", CORRECTNESS_FILLS)
    def test_functional_image_correctness(self, angle, center, interpolation, expand, fill):
1478
        image = make_image(dtype=torch.uint8, device="cpu")
Philip Meier's avatar
Philip Meier committed
1479
1480
1481
1482

        fill = adapt_fill(fill, dtype=torch.uint8)

        actual = F.rotate(image, angle=angle, center=center, interpolation=interpolation, expand=expand, fill=fill)
1483
        expected = F.to_image(
Philip Meier's avatar
Philip Meier committed
1484
            F.rotate(
1485
                F.to_pil_image(image), angle=angle, center=center, interpolation=interpolation, expand=expand, fill=fill
Philip Meier's avatar
Philip Meier committed
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
            )
        )

        mae = (actual.float() - expected.float()).abs().mean()
        assert mae < 1 if interpolation is transforms.InterpolationMode.NEAREST else 6

    @pytest.mark.parametrize("center", _CORRECTNESS_AFFINE_KWARGS["center"])
    @pytest.mark.parametrize(
        "interpolation", [transforms.InterpolationMode.NEAREST, transforms.InterpolationMode.BILINEAR]
    )
    @pytest.mark.parametrize("expand", [False, True])
    @pytest.mark.parametrize("fill", CORRECTNESS_FILLS)
    @pytest.mark.parametrize("seed", list(range(5)))
    def test_transform_image_correctness(self, center, interpolation, expand, fill, seed):
1500
        image = make_image(dtype=torch.uint8, device="cpu")
Philip Meier's avatar
Philip Meier committed
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515

        fill = adapt_fill(fill, dtype=torch.uint8)

        transform = transforms.RandomRotation(
            **self._CORRECTNESS_TRANSFORM_AFFINE_RANGES,
            center=center,
            interpolation=interpolation,
            expand=expand,
            fill=fill,
        )

        torch.manual_seed(seed)
        actual = transform(image)

        torch.manual_seed(seed)
1516
        expected = F.to_image(transform(F.to_pil_image(image)))
Philip Meier's avatar
Philip Meier committed
1517
1518
1519
1520

        mae = (actual.float() - expected.float()).abs().mean()
        assert mae < 1 if interpolation is transforms.InterpolationMode.NEAREST else 6

1521
    def _reference_rotate_bounding_boxes(self, bounding_boxes, *, angle, expand, center):
Philip Meier's avatar
Philip Meier committed
1522
1523
1524
1525
1526
        # FIXME
        if expand:
            raise ValueError("This reference currently does not support expand=True")

        if center is None:
Philip Meier's avatar
Philip Meier committed
1527
            center = [s * 0.5 for s in bounding_boxes.canvas_size[::-1]]
Philip Meier's avatar
Philip Meier committed
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537

        a = np.cos(angle * np.pi / 180.0)
        b = np.sin(angle * np.pi / 180.0)
        cx = center[0]
        cy = center[1]
        affine_matrix = np.array(
            [
                [a, b, cx - cx * a - b * cy],
                [-b, a, cy + cx * b - a * cy],
            ],
1538
            dtype="float64" if bounding_boxes.dtype == torch.float64 else "float32",
Philip Meier's avatar
Philip Meier committed
1539
1540
        )

1541
1542
1543
        expected_bboxes = reference_affine_bounding_boxes_helper(
            bounding_boxes,
            format=bounding_boxes.format,
Philip Meier's avatar
Philip Meier committed
1544
            canvas_size=bounding_boxes.canvas_size,
Philip Meier's avatar
Philip Meier committed
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
            affine_matrix=affine_matrix,
        )

        return expected_bboxes

    @pytest.mark.parametrize("format", list(datapoints.BoundingBoxFormat))
    @pytest.mark.parametrize("angle", _CORRECTNESS_AFFINE_KWARGS["angle"])
    # TODO: add support for expand=True in the reference
    @pytest.mark.parametrize("expand", [False])
    @pytest.mark.parametrize("center", _CORRECTNESS_AFFINE_KWARGS["center"])
1555
    def test_functional_bounding_boxes_correctness(self, format, angle, expand, center):
1556
        bounding_boxes = make_bounding_boxes(format=format)
Philip Meier's avatar
Philip Meier committed
1557

1558
1559
        actual = F.rotate(bounding_boxes, angle=angle, expand=expand, center=center)
        expected = self._reference_rotate_bounding_boxes(bounding_boxes, angle=angle, expand=expand, center=center)
Philip Meier's avatar
Philip Meier committed
1560
1561
1562
1563
1564
1565
1566
1567

        torch.testing.assert_close(actual, expected)

    @pytest.mark.parametrize("format", list(datapoints.BoundingBoxFormat))
    # TODO: add support for expand=True in the reference
    @pytest.mark.parametrize("expand", [False])
    @pytest.mark.parametrize("center", _CORRECTNESS_AFFINE_KWARGS["center"])
    @pytest.mark.parametrize("seed", list(range(5)))
1568
    def test_transform_bounding_boxes_correctness(self, format, expand, center, seed):
1569
        bounding_boxes = make_bounding_boxes(format=format)
Philip Meier's avatar
Philip Meier committed
1570
1571
1572
1573

        transform = transforms.RandomRotation(**self._CORRECTNESS_TRANSFORM_AFFINE_RANGES, expand=expand, center=center)

        torch.manual_seed(seed)
1574
        params = transform._get_params([bounding_boxes])
Philip Meier's avatar
Philip Meier committed
1575
1576

        torch.manual_seed(seed)
1577
        actual = transform(bounding_boxes)
Philip Meier's avatar
Philip Meier committed
1578

1579
        expected = self._reference_rotate_bounding_boxes(bounding_boxes, **params, expand=expand, center=center)
Philip Meier's avatar
Philip Meier committed
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617

        torch.testing.assert_close(actual, expected)

    @pytest.mark.parametrize("degrees", _EXHAUSTIVE_TYPE_TRANSFORM_AFFINE_RANGES["degrees"])
    @pytest.mark.parametrize("seed", list(range(10)))
    def test_transform_get_params_bounds(self, degrees, seed):
        transform = transforms.RandomRotation(degrees=degrees)

        torch.manual_seed(seed)
        params = transform._get_params([])

        if isinstance(degrees, (int, float)):
            assert -degrees <= params["angle"] <= degrees
        else:
            assert degrees[0] <= params["angle"] <= degrees[1]

    @pytest.mark.parametrize("param", ["degrees", "center"])
    @pytest.mark.parametrize("value", [0, [0], [0, 0, 0]])
    def test_transform_sequence_len_errors(self, param, value):
        if param == "degrees" and not isinstance(value, list):
            return

        kwargs = {param: value}
        if param != "degrees":
            kwargs["degrees"] = 0

        with pytest.raises(
            ValueError if isinstance(value, list) else TypeError, match=f"{param} should be a sequence of length 2"
        ):
            transforms.RandomRotation(**kwargs)

    def test_transform_negative_degrees_error(self):
        with pytest.raises(ValueError, match="If degrees is a single number, it must be positive"):
            transforms.RandomAffine(degrees=-1)

    def test_transform_unknown_fill_error(self):
        with pytest.raises(TypeError, match="Got inappropriate fill arg"):
            transforms.RandomAffine(degrees=0, fill="fill")
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678


class TestCompose:
    class BuiltinTransform(transforms.Transform):
        def _transform(self, inpt, params):
            return inpt

    class PackedInputTransform(nn.Module):
        def forward(self, sample):
            assert len(sample) == 2
            return sample

    class UnpackedInputTransform(nn.Module):
        def forward(self, image, label):
            return image, label

    @pytest.mark.parametrize(
        "transform_clss",
        [
            [BuiltinTransform],
            [PackedInputTransform],
            [UnpackedInputTransform],
            [BuiltinTransform, BuiltinTransform],
            [PackedInputTransform, PackedInputTransform],
            [UnpackedInputTransform, UnpackedInputTransform],
            [BuiltinTransform, PackedInputTransform, BuiltinTransform],
            [BuiltinTransform, UnpackedInputTransform, BuiltinTransform],
            [PackedInputTransform, BuiltinTransform, PackedInputTransform],
            [UnpackedInputTransform, BuiltinTransform, UnpackedInputTransform],
        ],
    )
    @pytest.mark.parametrize("unpack", [True, False])
    def test_packed_unpacked(self, transform_clss, unpack):
        needs_packed_inputs = any(issubclass(cls, self.PackedInputTransform) for cls in transform_clss)
        needs_unpacked_inputs = any(issubclass(cls, self.UnpackedInputTransform) for cls in transform_clss)
        assert not (needs_packed_inputs and needs_unpacked_inputs)

        transform = transforms.Compose([cls() for cls in transform_clss])

        image = make_image()
        label = 3
        packed_input = (image, label)

        def call_transform():
            if unpack:
                return transform(*packed_input)
            else:
                return transform(packed_input)

        if needs_unpacked_inputs and not unpack:
            with pytest.raises(TypeError, match="missing 1 required positional argument"):
                call_transform()
        elif needs_packed_inputs and unpack:
            with pytest.raises(TypeError, match="takes 2 positional arguments but 3 were given"):
                call_transform()
        else:
            output = call_transform()

            assert isinstance(output, tuple) and len(output) == 2
            assert output[0] is image
            assert output[1] is label
1679
1680
1681
1682
1683
1684


class TestToDtype:
    @pytest.mark.parametrize(
        ("kernel", "make_input"),
        [
1685
1686
            (F.to_dtype_image, make_image_tensor),
            (F.to_dtype_image, make_image),
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
            (F.to_dtype_video, make_video),
        ],
    )
    @pytest.mark.parametrize("input_dtype", [torch.float32, torch.float64, torch.uint8])
    @pytest.mark.parametrize("output_dtype", [torch.float32, torch.float64, torch.uint8])
    @pytest.mark.parametrize("device", cpu_and_cuda())
    @pytest.mark.parametrize("scale", (True, False))
    def test_kernel(self, kernel, make_input, input_dtype, output_dtype, device, scale):
        check_kernel(
            kernel,
            make_input(dtype=input_dtype, device=device),
            expect_same_dtype=input_dtype is output_dtype,
            dtype=output_dtype,
            scale=scale,
        )

Philip Meier's avatar
Philip Meier committed
1703
    @pytest.mark.parametrize("make_input", [make_image_tensor, make_image, make_video])
1704
1705
1706
1707
    @pytest.mark.parametrize("input_dtype", [torch.float32, torch.float64, torch.uint8])
    @pytest.mark.parametrize("output_dtype", [torch.float32, torch.float64, torch.uint8])
    @pytest.mark.parametrize("device", cpu_and_cuda())
    @pytest.mark.parametrize("scale", (True, False))
Nicolas Hug's avatar
Nicolas Hug committed
1708
1709
    def test_functional(self, make_input, input_dtype, output_dtype, device, scale):
        check_functional(
1710
1711
1712
1713
1714
1715
1716
1717
            F.to_dtype,
            make_input(dtype=input_dtype, device=device),
            dtype=output_dtype,
            scale=scale,
        )

    @pytest.mark.parametrize(
        "make_input",
1718
        [make_image_tensor, make_image, make_bounding_boxes, make_segmentation_mask, make_video],
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
    )
    @pytest.mark.parametrize("input_dtype", [torch.float32, torch.float64, torch.uint8])
    @pytest.mark.parametrize("output_dtype", [torch.float32, torch.float64, torch.uint8])
    @pytest.mark.parametrize("device", cpu_and_cuda())
    @pytest.mark.parametrize("scale", (True, False))
    @pytest.mark.parametrize("as_dict", (True, False))
    def test_transform(self, make_input, input_dtype, output_dtype, device, scale, as_dict):
        input = make_input(dtype=input_dtype, device=device)
        if as_dict:
            output_dtype = {type(input): output_dtype}
        check_transform(transforms.ToDtype, input, dtype=output_dtype, scale=scale)

    def reference_convert_dtype_image_tensor(self, image, dtype=torch.float, scale=False):
        input_dtype = image.dtype
        output_dtype = dtype

        if not scale:
            return image.to(dtype)

        if output_dtype == input_dtype:
            return image

        def fn(value):
            if input_dtype.is_floating_point:
                if output_dtype.is_floating_point:
                    return value
                else:
                    return round(decimal.Decimal(value) * torch.iinfo(output_dtype).max)
            else:
                input_max_value = torch.iinfo(input_dtype).max

                if output_dtype.is_floating_point:
                    return float(decimal.Decimal(value) / input_max_value)
                else:
                    output_max_value = torch.iinfo(output_dtype).max

                    if input_max_value > output_max_value:
                        factor = (input_max_value + 1) // (output_max_value + 1)
                        return value / factor
                    else:
                        factor = (output_max_value + 1) // (input_max_value + 1)
                        return value * factor

        return torch.tensor(tree_map(fn, image.tolist()), dtype=dtype, device=image.device)

    @pytest.mark.parametrize("input_dtype", [torch.float32, torch.float64, torch.uint8])
    @pytest.mark.parametrize("output_dtype", [torch.float32, torch.float64, torch.uint8])
    @pytest.mark.parametrize("device", cpu_and_cuda())
    @pytest.mark.parametrize("scale", (True, False))
    def test_image_correctness(self, input_dtype, output_dtype, device, scale):
        if input_dtype.is_floating_point and output_dtype == torch.int64:
            pytest.xfail("float to int64 conversion is not supported")

        input = make_image(dtype=input_dtype, device=device)

        out = F.to_dtype(input, dtype=output_dtype, scale=scale)
        expected = self.reference_convert_dtype_image_tensor(input, dtype=output_dtype, scale=scale)

        if input_dtype.is_floating_point and not output_dtype.is_floating_point and scale:
            torch.testing.assert_close(out, expected, atol=1, rtol=0)
        else:
            torch.testing.assert_close(out, expected)

    def was_scaled(self, inpt):
        # this assumes the target dtype is float
        return inpt.max() <= 1

    def make_inpt_with_bbox_and_mask(self, make_input):
        H, W = 10, 10
        inpt_dtype = torch.uint8
        bbox_dtype = torch.float32
        mask_dtype = torch.bool
        sample = {
            "inpt": make_input(size=(H, W), dtype=inpt_dtype),
1793
            "bbox": make_bounding_boxes(canvas_size=(H, W), dtype=bbox_dtype),
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
            "mask": make_detection_mask(size=(H, W), dtype=mask_dtype),
        }

        return sample, inpt_dtype, bbox_dtype, mask_dtype

    @pytest.mark.parametrize("make_input", (make_image_tensor, make_image, make_video))
    @pytest.mark.parametrize("scale", (True, False))
    def test_dtype_not_a_dict(self, make_input, scale):
        # assert only inpt gets transformed when dtype isn't a dict

        sample, inpt_dtype, bbox_dtype, mask_dtype = self.make_inpt_with_bbox_and_mask(make_input)
        out = transforms.ToDtype(dtype=torch.float32, scale=scale)(sample)

        assert out["inpt"].dtype != inpt_dtype
        assert out["inpt"].dtype == torch.float32
        if scale:
            assert self.was_scaled(out["inpt"])
        else:
            assert not self.was_scaled(out["inpt"])
        assert out["bbox"].dtype == bbox_dtype
        assert out["mask"].dtype == mask_dtype

    @pytest.mark.parametrize("make_input", (make_image_tensor, make_image, make_video))
    def test_others_catch_all_and_none(self, make_input):
        # make sure "others" works as a catch-all and that None means no conversion

        sample, inpt_dtype, bbox_dtype, mask_dtype = self.make_inpt_with_bbox_and_mask(make_input)
        out = transforms.ToDtype(dtype={datapoints.Mask: torch.int64, "others": None})(sample)
        assert out["inpt"].dtype == inpt_dtype
        assert out["bbox"].dtype == bbox_dtype
        assert out["mask"].dtype != mask_dtype
        assert out["mask"].dtype == torch.int64

    @pytest.mark.parametrize("make_input", (make_image_tensor, make_image, make_video))
    def test_typical_use_case(self, make_input):
        # Typical use-case: want to convert dtype and scale for inpt and just dtype for masks.
        # This just makes sure we now have a decent API for this

        sample, inpt_dtype, bbox_dtype, mask_dtype = self.make_inpt_with_bbox_and_mask(make_input)
        out = transforms.ToDtype(
            dtype={type(sample["inpt"]): torch.float32, datapoints.Mask: torch.int64, "others": None}, scale=True
        )(sample)
        assert out["inpt"].dtype != inpt_dtype
        assert out["inpt"].dtype == torch.float32
        assert self.was_scaled(out["inpt"])
        assert out["bbox"].dtype == bbox_dtype
        assert out["mask"].dtype != mask_dtype
        assert out["mask"].dtype == torch.int64

    @pytest.mark.parametrize("make_input", (make_image_tensor, make_image, make_video))
    def test_errors_warnings(self, make_input):
        sample, inpt_dtype, bbox_dtype, mask_dtype = self.make_inpt_with_bbox_and_mask(make_input)

        with pytest.raises(ValueError, match="No dtype was specified for"):
            out = transforms.ToDtype(dtype={datapoints.Mask: torch.float32})(sample)
        with pytest.warns(UserWarning, match=re.escape("plain `torch.Tensor` will *not* be transformed")):
            transforms.ToDtype(dtype={torch.Tensor: torch.float32, datapoints.Image: torch.float32})
        with pytest.warns(UserWarning, match="no scaling will be done"):
            out = transforms.ToDtype(dtype={"others": None}, scale=True)(sample)
        assert out["inpt"].dtype == inpt_dtype
        assert out["bbox"].dtype == bbox_dtype
        assert out["mask"].dtype == mask_dtype
1856
1857


1858
1859
1860
1861
1862
1863
1864
class TestAdjustBrightness:
    _CORRECTNESS_BRIGHTNESS_FACTORS = [0.5, 0.0, 1.0, 5.0]
    _DEFAULT_BRIGHTNESS_FACTOR = _CORRECTNESS_BRIGHTNESS_FACTORS[0]

    @pytest.mark.parametrize(
        ("kernel", "make_input"),
        [
1865
            (F.adjust_brightness_image, make_image),
1866
1867
1868
1869
1870
1871
1872
1873
            (F.adjust_brightness_video, make_video),
        ],
    )
    @pytest.mark.parametrize("dtype", [torch.float32, torch.uint8])
    @pytest.mark.parametrize("device", cpu_and_cuda())
    def test_kernel(self, kernel, make_input, dtype, device):
        check_kernel(kernel, make_input(dtype=dtype, device=device), brightness_factor=self._DEFAULT_BRIGHTNESS_FACTOR)

Philip Meier's avatar
Philip Meier committed
1874
    @pytest.mark.parametrize("make_input", [make_image_tensor, make_image_pil, make_image, make_video])
Nicolas Hug's avatar
Nicolas Hug committed
1875
1876
    def test_functional(self, make_input):
        check_functional(F.adjust_brightness, make_input(), brightness_factor=self._DEFAULT_BRIGHTNESS_FACTOR)
1877
1878
1879
1880

    @pytest.mark.parametrize(
        ("kernel", "input_type"),
        [
1881
1882
1883
            (F.adjust_brightness_image, torch.Tensor),
            (F._adjust_brightness_image_pil, PIL.Image.Image),
            (F.adjust_brightness_image, datapoints.Image),
1884
1885
1886
            (F.adjust_brightness_video, datapoints.Video),
        ],
    )
Nicolas Hug's avatar
Nicolas Hug committed
1887
1888
    def test_functional_signature(self, kernel, input_type):
        check_functional_kernel_signature_match(F.adjust_brightness, kernel=kernel, input_type=input_type)
1889
1890
1891
1892
1893
1894

    @pytest.mark.parametrize("brightness_factor", _CORRECTNESS_BRIGHTNESS_FACTORS)
    def test_image_correctness(self, brightness_factor):
        image = make_image(dtype=torch.uint8, device="cpu")

        actual = F.adjust_brightness(image, brightness_factor=brightness_factor)
1895
        expected = F.to_image(F.adjust_brightness(F.to_pil_image(image), brightness_factor=brightness_factor))
1896
1897
1898
1899

        torch.testing.assert_close(actual, expected)


1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
class TestCutMixMixUp:
    class DummyDataset:
        def __init__(self, size, num_classes):
            self.size = size
            self.num_classes = num_classes
            assert size < num_classes

        def __getitem__(self, idx):
            img = torch.rand(3, 100, 100)
            label = idx  # This ensures all labels in a batch are unique and makes testing easier
            return img, label

        def __len__(self):
            return self.size

Nicolas Hug's avatar
Nicolas Hug committed
1915
    @pytest.mark.parametrize("T", [transforms.CutMix, transforms.MixUp])
1916
1917
1918
1919
1920
1921
1922
    def test_supported_input_structure(self, T):

        batch_size = 32
        num_classes = 100

        dataset = self.DummyDataset(size=batch_size, num_classes=num_classes)

1923
        cutmix_mixup = T(num_classes=num_classes)
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964

        dl = DataLoader(dataset, batch_size=batch_size)

        # Input sanity checks
        img, target = next(iter(dl))
        input_img_size = img.shape[-3:]
        assert isinstance(img, torch.Tensor) and isinstance(target, torch.Tensor)
        assert target.shape == (batch_size,)

        def check_output(img, target):
            assert img.shape == (batch_size, *input_img_size)
            assert target.shape == (batch_size, num_classes)
            torch.testing.assert_close(target.sum(axis=-1), torch.ones(batch_size))
            num_non_zero_labels = (target != 0).sum(axis=-1)
            assert (num_non_zero_labels == 2).all()

        # After Dataloader, as unpacked input
        img, target = next(iter(dl))
        assert target.shape == (batch_size,)
        img, target = cutmix_mixup(img, target)
        check_output(img, target)

        # After Dataloader, as packed input
        packed_from_dl = next(iter(dl))
        assert isinstance(packed_from_dl, list)
        img, target = cutmix_mixup(packed_from_dl)
        check_output(img, target)

        # As collation function. We expect default_collate to be used by users.
        def collate_fn_1(batch):
            return cutmix_mixup(default_collate(batch))

        def collate_fn_2(batch):
            return cutmix_mixup(*default_collate(batch))

        for collate_fn in (collate_fn_1, collate_fn_2):
            dl = DataLoader(dataset, batch_size=batch_size, collate_fn=collate_fn)
            img, target = next(iter(dl))
            check_output(img, target)

    @needs_cuda
Nicolas Hug's avatar
Nicolas Hug committed
1965
    @pytest.mark.parametrize("T", [transforms.CutMix, transforms.MixUp])
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
    def test_cpu_vs_gpu(self, T):
        num_classes = 10
        batch_size = 3
        H, W = 12, 12

        imgs = torch.rand(batch_size, 3, H, W)
        labels = torch.randint(0, num_classes, (batch_size,))
        cutmix_mixup = T(alpha=0.5, num_classes=num_classes)

        _check_kernel_cuda_vs_cpu(cutmix_mixup, imgs, labels, rtol=None, atol=None)

Nicolas Hug's avatar
Nicolas Hug committed
1977
    @pytest.mark.parametrize("T", [transforms.CutMix, transforms.MixUp])
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
    def test_error(self, T):

        num_classes = 10
        batch_size = 9

        imgs = torch.rand(batch_size, 3, 12, 12)
        cutmix_mixup = T(alpha=0.5, num_classes=num_classes)

        for input_with_bad_type in (
            F.to_pil_image(imgs[0]),
            datapoints.Mask(torch.rand(12, 12)),
Philip Meier's avatar
Philip Meier committed
1989
            datapoints.BoundingBoxes(torch.rand(2, 4), format="XYXY", canvas_size=12),
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
        ):
            with pytest.raises(ValueError, match="does not support PIL images, "):
                cutmix_mixup(input_with_bad_type)

        with pytest.raises(ValueError, match="Could not infer where the labels are"):
            cutmix_mixup({"img": imgs, "Nothing_else": 3})

        with pytest.raises(ValueError, match="labels tensor should be of shape"):
            # Note: the error message isn't ideal, but that's because the label heuristic found the img as the label
            # It's OK, it's an edge-case. The important thing is that this fails loudly instead of passing silently
            cutmix_mixup(imgs)

        with pytest.raises(ValueError, match="When using the default labels_getter"):
            cutmix_mixup(imgs, "not_a_tensor")

        with pytest.raises(ValueError, match="labels tensor should be of shape"):
            cutmix_mixup(imgs, torch.randint(0, 2, size=(2, 3)))

        with pytest.raises(ValueError, match="Expected a batched input with 4 dims"):
            cutmix_mixup(imgs[None, None], torch.randint(0, num_classes, size=(batch_size,)))

        with pytest.raises(ValueError, match="does not match the batch size of the labels"):
            cutmix_mixup(imgs, torch.randint(0, num_classes, size=(batch_size + 1,)))

        with pytest.raises(ValueError, match="labels tensor should be of shape"):
            # The purpose of this check is more about documenting the current
            # behaviour of what happens on a Compose(), rather than actually
            # asserting the expected behaviour. We may support Compose() in the
            # future, e.g. for 2 consecutive CutMix?
            labels = torch.randint(0, num_classes, size=(batch_size,))
            transforms.Compose([cutmix_mixup, cutmix_mixup])(imgs, labels)


@pytest.mark.parametrize("key", ("labels", "LABELS", "LaBeL", "SOME_WEIRD_KEY_THAT_HAS_LABeL_IN_IT"))
@pytest.mark.parametrize("sample_type", (tuple, list, dict))
def test_labels_getter_default_heuristic(key, sample_type):
    labels = torch.arange(10)
    sample = {key: labels, "another_key": "whatever"}
    if sample_type is not dict:
        sample = sample_type((None, sample, "whatever_again"))
    assert transforms._utils._find_labels_default_heuristic(sample) is labels

    if key.lower() != "labels":
        # If "labels" is in the dict (case-insensitive),
        # it takes precedence over other keys which would otherwise be a match
        d = {key: "something_else", "labels": labels}
        assert transforms._utils._find_labels_default_heuristic(d) is labels
2037
2038
2039
2040
2041
2042


class TestShapeGetters:
    @pytest.mark.parametrize(
        ("kernel", "make_input"),
        [
2043
2044
2045
            (F.get_dimensions_image, make_image_tensor),
            (F._get_dimensions_image_pil, make_image_pil),
            (F.get_dimensions_image, make_image),
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
            (F.get_dimensions_video, make_video),
        ],
    )
    def test_get_dimensions(self, kernel, make_input):
        size = (10, 10)
        color_space, num_channels = "RGB", 3

        input = make_input(size, color_space=color_space)

        assert kernel(input) == F.get_dimensions(input) == [num_channels, *size]

    @pytest.mark.parametrize(
        ("kernel", "make_input"),
        [
2060
2061
2062
            (F.get_num_channels_image, make_image_tensor),
            (F._get_num_channels_image_pil, make_image_pil),
            (F.get_num_channels_image, make_image),
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
            (F.get_num_channels_video, make_video),
        ],
    )
    def test_get_num_channels(self, kernel, make_input):
        color_space, num_channels = "RGB", 3

        input = make_input(color_space=color_space)

        assert kernel(input) == F.get_num_channels(input) == num_channels

    @pytest.mark.parametrize(
        ("kernel", "make_input"),
        [
2076
2077
2078
            (F.get_size_image, make_image_tensor),
            (F._get_size_image_pil, make_image_pil),
            (F.get_size_image, make_image),
2079
            (F.get_size_bounding_boxes, make_bounding_boxes),
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
            (F.get_size_mask, make_detection_mask),
            (F.get_size_mask, make_segmentation_mask),
            (F.get_size_video, make_video),
        ],
    )
    def test_get_size(self, kernel, make_input):
        size = (10, 10)

        input = make_input(size)

        assert kernel(input) == F.get_size(input) == list(size)

    @pytest.mark.parametrize(
        ("kernel", "make_input"),
        [
            (F.get_num_frames_video, make_video_tensor),
            (F.get_num_frames_video, make_video),
        ],
    )
    def test_get_num_frames(self, kernel, make_input):
        num_frames = 4

        input = make_input(num_frames=num_frames)

        assert kernel(input) == F.get_num_frames(input) == num_frames

    @pytest.mark.parametrize(
Nicolas Hug's avatar
Nicolas Hug committed
2107
        ("functional", "make_input"),
2108
        [
2109
            (F.get_dimensions, make_bounding_boxes),
2110
2111
            (F.get_dimensions, make_detection_mask),
            (F.get_dimensions, make_segmentation_mask),
2112
            (F.get_num_channels, make_bounding_boxes),
2113
2114
2115
2116
            (F.get_num_channels, make_detection_mask),
            (F.get_num_channels, make_segmentation_mask),
            (F.get_num_frames, make_image_pil),
            (F.get_num_frames, make_image),
2117
            (F.get_num_frames, make_bounding_boxes),
2118
2119
2120
2121
            (F.get_num_frames, make_detection_mask),
            (F.get_num_frames, make_segmentation_mask),
        ],
    )
Nicolas Hug's avatar
Nicolas Hug committed
2122
    def test_unsupported_types(self, functional, make_input):
2123
2124
2125
        input = make_input()

        with pytest.raises(TypeError, match=re.escape(str(type(input)))):
Nicolas Hug's avatar
Nicolas Hug committed
2126
            functional(input)
2127
2128
2129


class TestRegisterKernel:
Nicolas Hug's avatar
Nicolas Hug committed
2130
2131
    @pytest.mark.parametrize("functional", (F.resize, "resize"))
    def test_register_kernel(self, functional):
2132
2133
2134
2135
2136
        class CustomDatapoint(datapoints.Datapoint):
            pass

        kernel_was_called = False

Nicolas Hug's avatar
Nicolas Hug committed
2137
        @F.register_kernel(functional, CustomDatapoint)
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
        def new_resize(dp, *args, **kwargs):
            nonlocal kernel_was_called
            kernel_was_called = True
            return dp

        t = transforms.Resize(size=(224, 224), antialias=True)

        my_dp = CustomDatapoint(torch.rand(3, 10, 10))
        out = t(my_dp)
        assert out is my_dp
        assert kernel_was_called

        # Sanity check to make sure we didn't override the kernel of other types
        t(torch.rand(3, 10, 10)).shape == (3, 224, 224)
        t(datapoints.Image(torch.rand(3, 10, 10))).shape == (3, 224, 224)

2154
    def test_errors(self):
Nicolas Hug's avatar
Nicolas Hug committed
2155
        with pytest.raises(ValueError, match="Could not find functional with name"):
2156
2157
            F.register_kernel("bad_name", datapoints.Image)

Nicolas Hug's avatar
Nicolas Hug committed
2158
        with pytest.raises(ValueError, match="Kernels can only be registered on functionals"):
2159
2160
2161
2162
2163
            F.register_kernel(datapoints.Image, F.resize)

        with pytest.raises(ValueError, match="Kernels can only be registered for subclasses"):
            F.register_kernel(F.resize, object)

2164
        with pytest.raises(ValueError, match="cannot be registered for the builtin datapoint classes"):
2165
            F.register_kernel(F.resize, datapoints.Image)(F.resize_image)
2166

2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
        class CustomDatapoint(datapoints.Datapoint):
            pass

        def resize_custom_datapoint():
            pass

        F.register_kernel(F.resize, CustomDatapoint)(resize_custom_datapoint)

        with pytest.raises(ValueError, match="already has a kernel registered for type"):
            F.register_kernel(F.resize, CustomDatapoint)(resize_custom_datapoint)

2178
2179

class TestGetKernel:
Nicolas Hug's avatar
Nicolas Hug committed
2180
    # We are using F.resize as functional and the kernels below as proxy. Any other functional / kernels combination
2181
2182
    # would also be fine
    KERNELS = {
2183
2184
2185
        torch.Tensor: F.resize_image,
        PIL.Image.Image: F._resize_image_pil,
        datapoints.Image: F.resize_image,
2186
2187
2188
2189
2190
        datapoints.BoundingBoxes: F.resize_bounding_boxes,
        datapoints.Mask: F.resize_mask,
        datapoints.Video: F.resize_video,
    }

2191
2192
2193
2194
    @pytest.mark.parametrize("input_type", [str, int, object])
    def test_unsupported_types(self, input_type):
        with pytest.raises(TypeError, match="supports inputs of type"):
            _get_kernel(F.resize, input_type)
2195
2196
2197

    def test_exact_match(self):
        # We cannot use F.resize together with self.KERNELS mapping here directly here, since this is only the
Nicolas Hug's avatar
Nicolas Hug committed
2198
        # ideal wrapping. Practically, we have an intermediate wrapper layer. Thus, we create a new resize functional
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
        # here, register the kernels without wrapper, and check the exact matching afterwards.
        def resize_with_pure_kernels():
            pass

        for input_type, kernel in self.KERNELS.items():
            _register_kernel_internal(resize_with_pure_kernels, input_type, datapoint_wrapper=False)(kernel)

            assert _get_kernel(resize_with_pure_kernels, input_type) is kernel

    def test_builtin_datapoint_subclass(self):
        # We cannot use F.resize together with self.KERNELS mapping here directly here, since this is only the
Nicolas Hug's avatar
Nicolas Hug committed
2210
        # ideal wrapping. Practically, we have an intermediate wrapper layer. Thus, we create a new resize functional
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
        # here, register the kernels without wrapper, and check if subclasses of our builtin datapoints get dispatched
        # to the kernel of the corresponding superclass
        def resize_with_pure_kernels():
            pass

        class MyImage(datapoints.Image):
            pass

        class MyBoundingBoxes(datapoints.BoundingBoxes):
            pass

        class MyMask(datapoints.Mask):
            pass

        class MyVideo(datapoints.Video):
            pass

        for custom_datapoint_subclass in [
            MyImage,
            MyBoundingBoxes,
            MyMask,
            MyVideo,
        ]:
            builtin_datapoint_class = custom_datapoint_subclass.__mro__[1]
            builtin_datapoint_kernel = self.KERNELS[builtin_datapoint_class]
            _register_kernel_internal(resize_with_pure_kernels, builtin_datapoint_class, datapoint_wrapper=False)(
                builtin_datapoint_kernel
            )

            assert _get_kernel(resize_with_pure_kernels, custom_datapoint_subclass) is builtin_datapoint_kernel

    def test_datapoint_subclass(self):
        class MyDatapoint(datapoints.Datapoint):
            pass

2246
2247
        with pytest.raises(TypeError, match="supports inputs of type"):
            _get_kernel(F.resize, MyDatapoint)
2248
2249
2250
2251
2252
2253
2254

        def resize_my_datapoint():
            pass

        _register_kernel_internal(F.resize, MyDatapoint, datapoint_wrapper=False)(resize_my_datapoint)

        assert _get_kernel(F.resize, MyDatapoint) is resize_my_datapoint
2255

2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
    def test_pil_image_subclass(self):
        opened_image = PIL.Image.open(Path(__file__).parent / "assets" / "encode_jpeg" / "grace_hopper_517x606.jpg")
        loaded_image = opened_image.convert("RGB")

        # check the assumptions
        assert isinstance(opened_image, PIL.Image.Image)
        assert type(opened_image) is not PIL.Image.Image

        assert type(loaded_image) is PIL.Image.Image

        size = [17, 11]
        for image in [opened_image, loaded_image]:
            kernel = _get_kernel(F.resize, type(image))

            output = kernel(image, size=size)

            assert F.get_size(output) == size

2274
2275
2276
2277
2278
2279
2280

class TestPermuteChannels:
    _DEFAULT_PERMUTATION = [2, 0, 1]

    @pytest.mark.parametrize(
        ("kernel", "make_input"),
        [
2281
            (F.permute_channels_image, make_image_tensor),
2282
2283
            # FIXME
            # check_kernel does not support PIL kernel, but it should
2284
            (F.permute_channels_image, make_image),
2285
2286
2287
2288
2289
2290
2291
2292
            (F.permute_channels_video, make_video),
        ],
    )
    @pytest.mark.parametrize("dtype", [torch.float32, torch.uint8])
    @pytest.mark.parametrize("device", cpu_and_cuda())
    def test_kernel(self, kernel, make_input, dtype, device):
        check_kernel(kernel, make_input(dtype=dtype, device=device), permutation=self._DEFAULT_PERMUTATION)

Nicolas Hug's avatar
Nicolas Hug committed
2293
    @pytest.mark.parametrize("make_input", [make_image_tensor, make_image_pil, make_image, make_video])
Nicolas Hug's avatar
Nicolas Hug committed
2294
2295
    def test_functional(self, make_input):
        check_functional(F.permute_channels, make_input(), permutation=self._DEFAULT_PERMUTATION)
2296
2297
2298
2299

    @pytest.mark.parametrize(
        ("kernel", "input_type"),
        [
2300
2301
2302
            (F.permute_channels_image, torch.Tensor),
            (F._permute_channels_image_pil, PIL.Image.Image),
            (F.permute_channels_image, datapoints.Image),
2303
2304
2305
            (F.permute_channels_video, datapoints.Video),
        ],
    )
Nicolas Hug's avatar
Nicolas Hug committed
2306
2307
    def test_functional_signature(self, kernel, input_type):
        check_functional_kernel_signature_match(F.permute_channels, kernel=kernel, input_type=input_type)
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322

    def reference_image_correctness(self, image, permutation):
        channel_images = image.split(1, dim=-3)
        permuted_channel_images = [channel_images[channel_idx] for channel_idx in permutation]
        return datapoints.Image(torch.concat(permuted_channel_images, dim=-3))

    @pytest.mark.parametrize("permutation", [[2, 0, 1], [1, 2, 0], [2, 0, 1], [0, 1, 2]])
    @pytest.mark.parametrize("batch_dims", [(), (2,), (2, 1)])
    def test_image_correctness(self, permutation, batch_dims):
        image = make_image(batch_dims=batch_dims)

        actual = F.permute_channels(image, permutation=permutation)
        expected = self.reference_image_correctness(image, permutation=permutation)

        torch.testing.assert_close(actual, expected)
Philip Meier's avatar
Philip Meier committed
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344


class TestElastic:
    def _make_displacement(self, inpt):
        return torch.rand(
            1,
            *F.get_size(inpt),
            2,
            dtype=torch.float32,
            device=inpt.device if isinstance(inpt, torch.Tensor) else "cpu",
        )

    @param_value_parametrization(
        interpolation=[transforms.InterpolationMode.NEAREST, transforms.InterpolationMode.BILINEAR],
        fill=EXHAUSTIVE_TYPE_FILLS,
    )
    @pytest.mark.parametrize("dtype", [torch.float32, torch.uint8])
    @pytest.mark.parametrize("device", cpu_and_cuda())
    def test_kernel_image_tensor(self, param, value, dtype, device):
        image = make_image_tensor(dtype=dtype, device=device)

        check_kernel(
Philip Meier's avatar
Philip Meier committed
2345
            F.elastic_image,
Philip Meier's avatar
Philip Meier committed
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
            image,
            displacement=self._make_displacement(image),
            **{param: value},
            check_scripted_vs_eager=not (param == "fill" and isinstance(value, (int, float))),
        )

    @pytest.mark.parametrize("format", list(datapoints.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):
2356
        bounding_boxes = make_bounding_boxes(format=format, dtype=dtype, device=device)
Philip Meier's avatar
Philip Meier committed
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376

        check_kernel(
            F.elastic_bounding_boxes,
            bounding_boxes,
            format=bounding_boxes.format,
            canvas_size=bounding_boxes.canvas_size,
            displacement=self._make_displacement(bounding_boxes),
        )

    @pytest.mark.parametrize("make_mask", [make_segmentation_mask, make_detection_mask])
    def test_kernel_mask(self, make_mask):
        mask = make_mask()
        check_kernel(F.elastic_mask, mask, displacement=self._make_displacement(mask))

    def test_kernel_video(self):
        video = make_video()
        check_kernel(F.elastic_video, video, displacement=self._make_displacement(video))

    @pytest.mark.parametrize(
        "make_input",
2377
        [make_image_tensor, make_image_pil, make_image, make_bounding_boxes, make_segmentation_mask, make_video],
Philip Meier's avatar
Philip Meier committed
2378
2379
2380
2381
2382
2383
2384
2385
    )
    def test_functional(self, make_input):
        input = make_input()
        check_functional(F.elastic, input, displacement=self._make_displacement(input))

    @pytest.mark.parametrize(
        ("kernel", "input_type"),
        [
Philip Meier's avatar
Philip Meier committed
2386
2387
2388
            (F.elastic_image, torch.Tensor),
            (F._elastic_image_pil, PIL.Image.Image),
            (F.elastic_image, datapoints.Image),
Philip Meier's avatar
Philip Meier committed
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
            (F.elastic_bounding_boxes, datapoints.BoundingBoxes),
            (F.elastic_mask, datapoints.Mask),
            (F.elastic_video, datapoints.Video),
        ],
    )
    def test_functional_signature(self, kernel, input_type):
        check_functional_kernel_signature_match(F.elastic, kernel=kernel, input_type=input_type)

    @pytest.mark.parametrize(
        "make_input",
2399
        [make_image_tensor, make_image_pil, make_image, make_bounding_boxes, make_segmentation_mask, make_video],
Philip Meier's avatar
Philip Meier committed
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
    )
    def test_displacement_error(self, make_input):
        input = make_input()

        with pytest.raises(TypeError, match="displacement should be a Tensor"):
            F.elastic(input, displacement=None)

        with pytest.raises(ValueError, match="displacement shape should be"):
            F.elastic(input, displacement=torch.rand(F.get_size(input)))

    @pytest.mark.parametrize(
        "make_input",
2412
        [make_image_tensor, make_image_pil, make_image, make_bounding_boxes, make_segmentation_mask, make_video],
Philip Meier's avatar
Philip Meier committed
2413
2414
2415
2416
2417
2418
    )
    # ElasticTransform needs larger images to avoid the needed internal padding being larger than the actual image
    @pytest.mark.parametrize("size", [(163, 163), (72, 333), (313, 95)])
    @pytest.mark.parametrize("device", cpu_and_cuda())
    def test_transform(self, make_input, size, device):
        check_transform(transforms.ElasticTransform, make_input(size, device=device))
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428


class TestToPureTensor:
    def test_correctness(self):
        input = {
            "img": make_image(),
            "img_tensor": make_image_tensor(),
            "img_pil": make_image_pil(),
            "mask": make_detection_mask(),
            "video": make_video(),
2429
            "bbox": make_bounding_boxes(),
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
            "str": "str",
        }

        out = transforms.ToPureTensor()(input)

        for input_value, out_value in zip(input.values(), out.values()):
            if isinstance(input_value, datapoints.Datapoint):
                assert isinstance(out_value, torch.Tensor) and not isinstance(out_value, datapoints.Datapoint)
            else:
                assert isinstance(out_value, type(input_value))