test_transforms_v2_consistency.py 34.7 KB
Newer Older
1
2
import importlib.machinery
import importlib.util
3
import inspect
4
import random
5
import re
6
from pathlib import Path
7

8
import numpy as np
9
import PIL.Image
10
import pytest
11
12

import torch
13
import torchvision.transforms.v2 as v2_transforms
14
from common_utils import assert_close, assert_equal, set_rng_seed
15
from torch import nn
16
from torchvision import transforms as legacy_transforms, tv_tensors
17
from torchvision._utils import sequence_to_str
18

19
from torchvision.transforms import functional as legacy_F
20
from torchvision.transforms.v2 import functional as prototype_F
Nicolas Hug's avatar
Nicolas Hug committed
21
from torchvision.transforms.v2._utils import _get_fill, query_size
22
from torchvision.transforms.v2.functional import to_pil_image
23
24
25
26
27
28
29
30
from transforms_v2_legacy_utils import (
    ArgsKwargs,
    make_bounding_boxes,
    make_detection_mask,
    make_image,
    make_images,
    make_segmentation_mask,
)
31

32
DEFAULT_MAKE_IMAGES_KWARGS = dict(color_spaces=["RGB"], extra_dims=[(4,)])
33
34


Nicolas Hug's avatar
Nicolas Hug committed
35
36
37
38
39
40
@pytest.fixture(autouse=True)
def fix_rng_seed():
    set_rng_seed(0)
    yield


41
42
43
44
45
46
47
48
49
class NotScriptableArgsKwargs(ArgsKwargs):
    """
    This class is used to mark parameters that render the transform non-scriptable. They still work in eager mode and
    thus will be tested there, but will be skipped by the JIT tests.
    """

    pass


50
51
class ConsistencyConfig:
    def __init__(
52
53
54
        self,
        prototype_cls,
        legacy_cls,
55
56
        # If no args_kwargs is passed, only the signature will be checked
        args_kwargs=(),
57
58
59
        make_images_kwargs=None,
        supports_pil=True,
        removed_params=(),
60
        closeness_kwargs=None,
61
62
63
    ):
        self.prototype_cls = prototype_cls
        self.legacy_cls = legacy_cls
64
        self.args_kwargs = args_kwargs
65
66
        self.make_images_kwargs = make_images_kwargs or DEFAULT_MAKE_IMAGES_KWARGS
        self.supports_pil = supports_pil
67
        self.removed_params = removed_params
68
        self.closeness_kwargs = closeness_kwargs or dict(rtol=0, atol=0)
69
70


71
72
73
74
# These are here since both the prototype and legacy transform need to be constructed with the same random parameters
LINEAR_TRANSFORMATION_MEAN = torch.rand(36)
LINEAR_TRANSFORMATION_MATRIX = torch.rand([LINEAR_TRANSFORMATION_MEAN.numel()] * 2)

75
76
CONSISTENCY_CONFIGS = [
    ConsistencyConfig(
77
        v2_transforms.Normalize,
78
79
80
81
82
83
84
85
        legacy_transforms.Normalize,
        [
            ArgsKwargs(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
        ],
        supports_pil=False,
        make_images_kwargs=dict(DEFAULT_MAKE_IMAGES_KWARGS, dtypes=[torch.float]),
    ),
    ConsistencyConfig(
86
        v2_transforms.CenterCrop,
87
88
89
90
91
92
        legacy_transforms.CenterCrop,
        [
            ArgsKwargs(18),
            ArgsKwargs((18, 13)),
        ],
    ),
93
    ConsistencyConfig(
94
        v2_transforms.FiveCrop,
95
96
97
98
99
100
101
102
        legacy_transforms.FiveCrop,
        [
            ArgsKwargs(18),
            ArgsKwargs((18, 13)),
        ],
        make_images_kwargs=dict(DEFAULT_MAKE_IMAGES_KWARGS, sizes=[(20, 19)]),
    ),
    ConsistencyConfig(
103
        v2_transforms.TenCrop,
104
105
106
107
        legacy_transforms.TenCrop,
        [
            ArgsKwargs(18),
            ArgsKwargs((18, 13)),
108
            ArgsKwargs(18, vertical_flip=True),
109
110
111
112
        ],
        make_images_kwargs=dict(DEFAULT_MAKE_IMAGES_KWARGS, sizes=[(20, 19)]),
    ),
    ConsistencyConfig(
113
        v2_transforms.Pad,
114
115
        legacy_transforms.Pad,
        [
116
            NotScriptableArgsKwargs(3),
117
118
119
            ArgsKwargs([3]),
            ArgsKwargs([2, 3]),
            ArgsKwargs([3, 2, 1, 4]),
120
121
122
123
124
            NotScriptableArgsKwargs(5, fill=1, padding_mode="constant"),
            ArgsKwargs([5], fill=1, padding_mode="constant"),
            NotScriptableArgsKwargs(5, padding_mode="edge"),
            NotScriptableArgsKwargs(5, padding_mode="reflect"),
            NotScriptableArgsKwargs(5, padding_mode="symmetric"),
125
126
        ],
    ),
127
128
    *[
        ConsistencyConfig(
129
            v2_transforms.LinearTransformation,
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
            legacy_transforms.LinearTransformation,
            [
                ArgsKwargs(LINEAR_TRANSFORMATION_MATRIX.to(matrix_dtype), LINEAR_TRANSFORMATION_MEAN.to(matrix_dtype)),
            ],
            # Make sure that the product of the height, width and number of channels matches the number of elements in
            # `LINEAR_TRANSFORMATION_MEAN`. For example 2 * 6 * 3 == 4 * 3 * 3 == 36.
            make_images_kwargs=dict(
                DEFAULT_MAKE_IMAGES_KWARGS, sizes=[(2, 6), (4, 3)], color_spaces=["RGB"], dtypes=[image_dtype]
            ),
            supports_pil=False,
        )
        for matrix_dtype, image_dtype in [
            (torch.float32, torch.float32),
            (torch.float64, torch.float64),
            (torch.float32, torch.uint8),
            (torch.float64, torch.float32),
            (torch.float32, torch.float64),
        ]
    ],
149
    ConsistencyConfig(
150
        v2_transforms.Grayscale,
151
152
153
154
155
        legacy_transforms.Grayscale,
        [
            ArgsKwargs(num_output_channels=1),
            ArgsKwargs(num_output_channels=3),
        ],
156
        make_images_kwargs=dict(DEFAULT_MAKE_IMAGES_KWARGS, color_spaces=["RGB", "GRAY"]),
157
158
        # Use default tolerances of `torch.testing.assert_close`
        closeness_kwargs=dict(rtol=None, atol=None),
159
    ),
160
    ConsistencyConfig(
161
        v2_transforms.ToPILImage,
162
        legacy_transforms.ToPILImage,
163
        [NotScriptableArgsKwargs()],
164
165
        make_images_kwargs=dict(
            color_spaces=[
166
167
168
169
                "GRAY",
                "GRAY_ALPHA",
                "RGB",
                "RGBA",
170
171
172
173
174
175
            ],
            extra_dims=[()],
        ),
        supports_pil=False,
    ),
    ConsistencyConfig(
176
        v2_transforms.Lambda,
177
178
        legacy_transforms.Lambda,
        [
179
            NotScriptableArgsKwargs(lambda image: image / 2),
180
181
182
183
184
        ],
        # Technically, this also supports PIL, but it is overkill to write a function here that supports tensor and PIL
        # images given that the transform does nothing but call it anyway.
        supports_pil=False,
    ),
185
    ConsistencyConfig(
186
        v2_transforms.RandomEqualize,
187
188
189
190
191
192
193
194
        legacy_transforms.RandomEqualize,
        [
            ArgsKwargs(p=0),
            ArgsKwargs(p=1),
        ],
        make_images_kwargs=dict(DEFAULT_MAKE_IMAGES_KWARGS, dtypes=[torch.uint8]),
    ),
    ConsistencyConfig(
195
        v2_transforms.RandomInvert,
196
197
198
199
200
201
202
        legacy_transforms.RandomInvert,
        [
            ArgsKwargs(p=0),
            ArgsKwargs(p=1),
        ],
    ),
    ConsistencyConfig(
203
        v2_transforms.RandomPosterize,
204
205
206
207
208
209
210
211
212
        legacy_transforms.RandomPosterize,
        [
            ArgsKwargs(p=0, bits=5),
            ArgsKwargs(p=1, bits=1),
            ArgsKwargs(p=1, bits=3),
        ],
        make_images_kwargs=dict(DEFAULT_MAKE_IMAGES_KWARGS, dtypes=[torch.uint8]),
    ),
    ConsistencyConfig(
213
        v2_transforms.RandomSolarize,
214
215
216
217
218
219
220
        legacy_transforms.RandomSolarize,
        [
            ArgsKwargs(p=0, threshold=0.5),
            ArgsKwargs(p=1, threshold=0.3),
            ArgsKwargs(p=1, threshold=0.99),
        ],
    ),
221
222
    *[
        ConsistencyConfig(
223
            v2_transforms.RandomAutocontrast,
224
225
226
227
228
229
230
231
232
233
            legacy_transforms.RandomAutocontrast,
            [
                ArgsKwargs(p=0),
                ArgsKwargs(p=1),
            ],
            make_images_kwargs=dict(DEFAULT_MAKE_IMAGES_KWARGS, dtypes=[dt]),
            closeness_kwargs=ckw,
        )
        for dt, ckw in [(torch.uint8, dict(atol=1, rtol=0)), (torch.float32, dict(rtol=None, atol=None))]
    ],
234
    ConsistencyConfig(
235
        v2_transforms.RandomAdjustSharpness,
236
237
238
        legacy_transforms.RandomAdjustSharpness,
        [
            ArgsKwargs(p=0, sharpness_factor=0.5),
239
            ArgsKwargs(p=1, sharpness_factor=0.2),
240
241
            ArgsKwargs(p=1, sharpness_factor=0.99),
        ],
242
        closeness_kwargs={"atol": 1e-6, "rtol": 1e-6},
243
244
    ),
    ConsistencyConfig(
245
        v2_transforms.RandomGrayscale,
246
247
248
249
250
        legacy_transforms.RandomGrayscale,
        [
            ArgsKwargs(p=0),
            ArgsKwargs(p=1),
        ],
251
252
253
        make_images_kwargs=dict(DEFAULT_MAKE_IMAGES_KWARGS, color_spaces=["RGB", "GRAY"]),
        # Use default tolerances of `torch.testing.assert_close`
        closeness_kwargs=dict(rtol=None, atol=None),
254
255
    ),
    ConsistencyConfig(
256
        v2_transforms.ColorJitter,
257
258
259
260
261
262
263
264
265
266
267
        legacy_transforms.ColorJitter,
        [
            ArgsKwargs(),
            ArgsKwargs(brightness=0.1),
            ArgsKwargs(brightness=(0.2, 0.3)),
            ArgsKwargs(contrast=0.4),
            ArgsKwargs(contrast=(0.5, 0.6)),
            ArgsKwargs(saturation=0.7),
            ArgsKwargs(saturation=(0.8, 0.9)),
            ArgsKwargs(hue=0.3),
            ArgsKwargs(hue=(-0.1, 0.2)),
268
            ArgsKwargs(brightness=0.1, contrast=0.4, saturation=0.5, hue=0.3),
269
        ],
270
        closeness_kwargs={"atol": 1e-5, "rtol": 1e-5},
271
272
    ),
    ConsistencyConfig(
273
        v2_transforms.GaussianBlur,
274
275
276
277
278
279
280
        legacy_transforms.GaussianBlur,
        [
            ArgsKwargs(kernel_size=3),
            ArgsKwargs(kernel_size=(1, 5)),
            ArgsKwargs(kernel_size=3, sigma=0.7),
            ArgsKwargs(kernel_size=5, sigma=(0.3, 1.4)),
        ],
281
        closeness_kwargs={"rtol": 1e-5, "atol": 1e-5},
282
283
    ),
    ConsistencyConfig(
284
        v2_transforms.RandomPerspective,
285
286
287
288
289
        legacy_transforms.RandomPerspective,
        [
            ArgsKwargs(p=0),
            ArgsKwargs(p=1),
            ArgsKwargs(p=1, distortion_scale=0.3),
290
            ArgsKwargs(p=1, distortion_scale=0.2, interpolation=v2_transforms.InterpolationMode.NEAREST),
291
            ArgsKwargs(p=1, distortion_scale=0.2, interpolation=PIL.Image.NEAREST),
292
293
294
            ArgsKwargs(p=1, distortion_scale=0.1, fill=1),
            ArgsKwargs(p=1, distortion_scale=0.4, fill=(1, 2, 3)),
        ],
295
        closeness_kwargs={"atol": None, "rtol": None},
296
    ),
297
    ConsistencyConfig(
298
        v2_transforms.PILToTensor,
299
300
301
        legacy_transforms.PILToTensor,
    ),
    ConsistencyConfig(
302
        v2_transforms.ToTensor,
303
304
305
        legacy_transforms.ToTensor,
    ),
    ConsistencyConfig(
306
        v2_transforms.Compose,
307
308
309
        legacy_transforms.Compose,
    ),
    ConsistencyConfig(
310
        v2_transforms.RandomApply,
311
312
313
        legacy_transforms.RandomApply,
    ),
    ConsistencyConfig(
314
        v2_transforms.RandomChoice,
315
316
317
        legacy_transforms.RandomChoice,
    ),
    ConsistencyConfig(
318
        v2_transforms.RandomOrder,
319
320
321
        legacy_transforms.RandomOrder,
    ),
    ConsistencyConfig(
322
        v2_transforms.AugMix,
323
324
325
        legacy_transforms.AugMix,
    ),
    ConsistencyConfig(
326
        v2_transforms.AutoAugment,
327
328
329
        legacy_transforms.AutoAugment,
    ),
    ConsistencyConfig(
330
        v2_transforms.RandAugment,
331
332
333
        legacy_transforms.RandAugment,
    ),
    ConsistencyConfig(
334
        v2_transforms.TrivialAugmentWide,
335
336
        legacy_transforms.TrivialAugmentWide,
    ),
337
338
339
]


340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
@pytest.mark.parametrize("config", CONSISTENCY_CONFIGS, ids=lambda config: config.legacy_cls.__name__)
def test_signature_consistency(config):
    legacy_params = dict(inspect.signature(config.legacy_cls).parameters)
    prototype_params = dict(inspect.signature(config.prototype_cls).parameters)

    for param in config.removed_params:
        legacy_params.pop(param, None)

    missing = legacy_params.keys() - prototype_params.keys()
    if missing:
        raise AssertionError(
            f"The prototype transform does not support the parameters "
            f"{sequence_to_str(sorted(missing), separate_last='and ')}, but the legacy transform does. "
            f"If that is intentional, e.g. pending deprecation, please add the parameters to the `removed_params` on "
            f"the `ConsistencyConfig`."
        )

    extra = prototype_params.keys() - legacy_params.keys()
358
359
360
361
362
363
    extra_without_default = {
        param
        for param in extra
        if prototype_params[param].default is inspect.Parameter.empty
        and prototype_params[param].kind not in {inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD}
    }
364
365
    if extra_without_default:
        raise AssertionError(
366
367
368
            f"The prototype transform requires the parameters "
            f"{sequence_to_str(sorted(extra_without_default), separate_last='and ')}, but the legacy transform does "
            f"not. Please add a default value."
369
370
        )

371
372
373
374
375
376
    legacy_signature = list(legacy_params.keys())
    # Since we made sure that we don't have any extra parameters without default above, we clamp the prototype signature
    # to the same number of parameters as the legacy one
    prototype_signature = list(prototype_params.keys())[: len(legacy_signature)]

    assert prototype_signature == legacy_signature
377
378


379
380
381
def check_call_consistency(
    prototype_transform, legacy_transform, images=None, supports_pil=True, closeness_kwargs=None
):
382
383
    if images is None:
        images = make_images(**DEFAULT_MAKE_IMAGES_KWARGS)
384

385
386
    closeness_kwargs = closeness_kwargs or dict()

387
388
    for image in images:
        image_repr = f"[{tuple(image.shape)}, {str(image.dtype).rsplit('.')[-1]}]"
389
390
391

        image_tensor = torch.Tensor(image)
        try:
392
            torch.manual_seed(0)
393
            output_legacy_tensor = legacy_transform(image_tensor)
394
395
        except Exception as exc:
            raise pytest.UsageError(
396
                f"Transforming a tensor image {image_repr} failed in the legacy transform with the "
397
                f"error above. This means that you need to specify the parameters passed to `make_images` through the "
398
399
400
401
                "`make_images_kwargs` of the `ConsistencyConfig`."
            ) from exc

        try:
402
            torch.manual_seed(0)
403
            output_prototype_tensor = prototype_transform(image_tensor)
404
405
        except Exception as exc:
            raise AssertionError(
406
                f"Transforming a tensor image with shape {image_repr} failed in the prototype transform with "
407
                f"the error above. This means there is a consistency bug either in `_get_params` or in the "
408
                f"`is_pure_tensor` path in `_transform`."
409
410
            ) from exc

411
        assert_close(
412
413
414
            output_prototype_tensor,
            output_legacy_tensor,
            msg=lambda msg: f"Tensor image consistency check failed with: \n\n{msg}",
415
            **closeness_kwargs,
416
417
418
        )

        try:
419
            torch.manual_seed(0)
420
            output_prototype_image = prototype_transform(image)
421
422
        except Exception as exc:
            raise AssertionError(
423
                f"Transforming a image tv_tensor with shape {image_repr} failed in the prototype transform with "
424
                f"the error above. This means there is a consistency bug either in `_get_params` or in the "
425
                f"`tv_tensors.Image` path in `_transform`."
426
427
            ) from exc

428
        assert_close(
429
            output_prototype_image,
430
            output_prototype_tensor,
431
            msg=lambda msg: f"Output for tv_tensor and tensor images is not equal: \n\n{msg}",
432
            **closeness_kwargs,
433
434
        )

435
        if image.ndim == 3 and supports_pil:
436
            image_pil = to_pil_image(image)
437

438
            try:
439
                torch.manual_seed(0)
440
                output_legacy_pil = legacy_transform(image_pil)
441
442
            except Exception as exc:
                raise pytest.UsageError(
443
                    f"Transforming a PIL image with shape {image_repr} failed in the legacy transform with the "
444
445
446
447
448
                    f"error above. If this transform does not support PIL images, set `supports_pil=False` on the "
                    "`ConsistencyConfig`. "
                ) from exc

            try:
449
                torch.manual_seed(0)
450
                output_prototype_pil = prototype_transform(image_pil)
451
452
            except Exception as exc:
                raise AssertionError(
453
                    f"Transforming a PIL image with shape {image_repr} failed in the prototype transform with "
454
455
456
457
                    f"the error above. This means there is a consistency bug either in `_get_params` or in the "
                    f"`PIL.Image.Image` path in `_transform`."
                ) from exc

458
            assert_close(
459
460
                output_prototype_pil,
                output_legacy_pil,
461
                msg=lambda msg: f"PIL image consistency check failed with: \n\n{msg}",
462
                **closeness_kwargs,
463
            )
464
465


466
@pytest.mark.parametrize(
467
468
    ("config", "args_kwargs"),
    [
469
470
471
        pytest.param(
            config, args_kwargs, id=f"{config.legacy_cls.__name__}-{idx:0{len(str(len(config.args_kwargs)))}d}"
        )
472
        for config in CONSISTENCY_CONFIGS
473
        for idx, args_kwargs in enumerate(config.args_kwargs)
474
    ],
475
)
476
@pytest.mark.filterwarnings("ignore")
477
def test_call_consistency(config, args_kwargs):
478
479
480
    args, kwargs = args_kwargs

    try:
481
        legacy_transform = config.legacy_cls(*args, **kwargs)
482
483
484
485
486
487
488
    except Exception as exc:
        raise pytest.UsageError(
            f"Initializing the legacy transform failed with the error above. "
            f"Please correct the `ArgsKwargs({args_kwargs})` in the `ConsistencyConfig`."
        ) from exc

    try:
489
        prototype_transform = config.prototype_cls(*args, **kwargs)
490
491
492
493
494
495
    except Exception as exc:
        raise AssertionError(
            "Initializing the prototype transform failed with the error above. "
            "This means there is a consistency bug in the constructor."
        ) from exc

496
497
498
499
500
    check_call_consistency(
        prototype_transform,
        legacy_transform,
        images=make_images(**config.make_images_kwargs),
        supports_pil=config.supports_pil,
501
        closeness_kwargs=config.closeness_kwargs,
502
503
504
    )


505
506
507
508
509
510
511
512
513
get_params_parametrization = pytest.mark.parametrize(
    ("config", "get_params_args_kwargs"),
    [
        pytest.param(
            next(config for config in CONSISTENCY_CONFIGS if config.prototype_cls is transform_cls),
            get_params_args_kwargs,
            id=transform_cls.__name__,
        )
        for transform_cls, get_params_args_kwargs in [
514
515
516
517
            (v2_transforms.ColorJitter, ArgsKwargs(brightness=None, contrast=None, saturation=None, hue=None)),
            (v2_transforms.GaussianBlur, ArgsKwargs(0.3, 1.4)),
            (v2_transforms.RandomPerspective, ArgsKwargs(23, 17, 0.5)),
            (v2_transforms.AutoAugment, ArgsKwargs(5)),
518
519
        ]
    ],
520
)
521
522


523
@get_params_parametrization
524
def test_get_params_alias(config, get_params_args_kwargs):
525
526
    assert config.prototype_cls.get_params is config.legacy_cls.get_params

527
528
529
530
531
    if not config.args_kwargs:
        return
    args, kwargs = config.args_kwargs[0]
    legacy_transform = config.legacy_cls(*args, **kwargs)
    prototype_transform = config.prototype_cls(*args, **kwargs)
532

533
534
535
    assert prototype_transform.get_params is legacy_transform.get_params


536
@get_params_parametrization
537
538
539
540
541
542
543
544
545
def test_get_params_jit(config, get_params_args_kwargs):
    get_params_args, get_params_kwargs = get_params_args_kwargs

    torch.jit.script(config.prototype_cls.get_params)(*get_params_args, **get_params_kwargs)

    if not config.args_kwargs:
        return
    args, kwargs = config.args_kwargs[0]
    transform = config.prototype_cls(*args, **kwargs)
546

547
    torch.jit.script(transform.get_params)(*get_params_args, **get_params_kwargs)
548
549


550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
@pytest.mark.parametrize(
    ("config", "args_kwargs"),
    [
        pytest.param(
            config, args_kwargs, id=f"{config.legacy_cls.__name__}-{idx:0{len(str(len(config.args_kwargs)))}d}"
        )
        for config in CONSISTENCY_CONFIGS
        for idx, args_kwargs in enumerate(config.args_kwargs)
        if not isinstance(args_kwargs, NotScriptableArgsKwargs)
    ],
)
def test_jit_consistency(config, args_kwargs):
    args, kwargs = args_kwargs

    prototype_transform_eager = config.prototype_cls(*args, **kwargs)
    legacy_transform_eager = config.legacy_cls(*args, **kwargs)

    legacy_transform_scripted = torch.jit.script(legacy_transform_eager)
    prototype_transform_scripted = torch.jit.script(prototype_transform_eager)

    for image in make_images(**config.make_images_kwargs):
        image = image.as_subclass(torch.Tensor)

        torch.manual_seed(0)
        output_legacy_scripted = legacy_transform_scripted(image)

        torch.manual_seed(0)
        output_prototype_scripted = prototype_transform_scripted(image)

        assert_close(output_prototype_scripted, output_legacy_scripted, **config.closeness_kwargs)


582
583
584
585
586
587
588
589
590
591
class TestContainerTransforms:
    """
    Since we are testing containers here, we also need some transforms to wrap. Thus, testing a container transform for
    consistency automatically tests the wrapped transforms consistency.

    Instead of complicated mocking or creating custom transforms just for these tests, here we use deterministic ones
    that were already tested for consistency above.
    """

    def test_compose(self):
592
        prototype_transform = v2_transforms.Compose(
593
            [
594
595
                v2_transforms.Resize(256),
                v2_transforms.CenterCrop(224),
596
597
598
599
600
601
602
603
604
            ]
        )
        legacy_transform = legacy_transforms.Compose(
            [
                legacy_transforms.Resize(256),
                legacy_transforms.CenterCrop(224),
            ]
        )

605
606
        # atol=1 due to Resize v2 is using native uint8 interpolate path for bilinear and nearest modes
        check_call_consistency(prototype_transform, legacy_transform, closeness_kwargs=dict(rtol=0, atol=1))
607
608

    @pytest.mark.parametrize("p", [0, 0.1, 0.5, 0.9, 1])
609
610
    @pytest.mark.parametrize("sequence_type", [list, nn.ModuleList])
    def test_random_apply(self, p, sequence_type):
611
        prototype_transform = v2_transforms.RandomApply(
612
613
            sequence_type(
                [
614
615
                    v2_transforms.Resize(256),
                    v2_transforms.CenterCrop(224),
616
617
                ]
            ),
618
619
620
            p=p,
        )
        legacy_transform = legacy_transforms.RandomApply(
621
622
623
624
625
626
            sequence_type(
                [
                    legacy_transforms.Resize(256),
                    legacy_transforms.CenterCrop(224),
                ]
            ),
627
628
629
            p=p,
        )

630
631
        # atol=1 due to Resize v2 is using native uint8 interpolate path for bilinear and nearest modes
        check_call_consistency(prototype_transform, legacy_transform, closeness_kwargs=dict(rtol=0, atol=1))
632

633
634
635
636
637
        if sequence_type is nn.ModuleList:
            # quick and dirty test that it is jit-scriptable
            scripted = torch.jit.script(prototype_transform)
            scripted(torch.rand(1, 3, 300, 300))

638
    # We can't test other values for `p` since the random parameter generation is different
639
640
    @pytest.mark.parametrize("probabilities", [(0, 1), (1, 0)])
    def test_random_choice(self, probabilities):
641
        prototype_transform = v2_transforms.RandomChoice(
642
            [
643
                v2_transforms.Resize(256),
644
645
                legacy_transforms.CenterCrop(224),
            ],
646
            p=probabilities,
647
648
649
650
651
652
        )
        legacy_transform = legacy_transforms.RandomChoice(
            [
                legacy_transforms.Resize(256),
                legacy_transforms.CenterCrop(224),
            ],
653
            p=probabilities,
654
655
        )

656
657
        # atol=1 due to Resize v2 is using native uint8 interpolate path for bilinear and nearest modes
        check_call_consistency(prototype_transform, legacy_transform, closeness_kwargs=dict(rtol=0, atol=1))
658
659


660
661
class TestToTensorTransforms:
    def test_pil_to_tensor(self):
662
        prototype_transform = v2_transforms.PILToTensor()
663
664
        legacy_transform = legacy_transforms.PILToTensor()

665
        for image in make_images(extra_dims=[()]):
666
            image_pil = to_pil_image(image)
667
668
669
670

            assert_equal(prototype_transform(image_pil), legacy_transform(image_pil))

    def test_to_tensor(self):
671
        with pytest.warns(UserWarning, match=re.escape("The transform `ToTensor()` is deprecated")):
672
            prototype_transform = v2_transforms.ToTensor()
673
674
        legacy_transform = legacy_transforms.ToTensor()

675
        for image in make_images(extra_dims=[()]):
676
            image_pil = to_pil_image(image)
677
678
679
680
            image_numpy = np.array(image_pil)

            assert_equal(prototype_transform(image_pil), legacy_transform(image_pil))
            assert_equal(prototype_transform(image_numpy), legacy_transform(image_numpy))
681
682


683
def import_transforms_from_references(reference):
684
685
686
687
688
689
690
691
692
693
    HERE = Path(__file__).parent
    PROJECT_ROOT = HERE.parent

    loader = importlib.machinery.SourceFileLoader(
        "transforms", str(PROJECT_ROOT / "references" / reference / "transforms.py")
    )
    spec = importlib.util.spec_from_loader("transforms", loader)
    module = importlib.util.module_from_spec(spec)
    loader.exec_module(module)
    return module
694
695
696


det_transforms = import_transforms_from_references("detection")
697
698
699


class TestRefDetTransforms:
700
    def make_tv_tensors(self, with_mask=True):
701
702
703
        size = (600, 800)
        num_objects = 22

704
705
706
        def make_label(extra_dims, categories):
            return torch.randint(categories, extra_dims, dtype=torch.int64)

707
        pil_image = to_pil_image(make_image(size=size, color_space="RGB"))
708
        target = {
709
            "boxes": make_bounding_boxes(canvas_size=size, format="XYXY", batch_dims=(num_objects,), dtype=torch.float),
710
711
712
713
714
715
716
            "labels": make_label(extra_dims=(num_objects,), categories=80),
        }
        if with_mask:
            target["masks"] = make_detection_mask(size=size, num_objects=num_objects, dtype=torch.long)

        yield (pil_image, target)

717
        tensor_image = torch.Tensor(make_image(size=size, color_space="RGB", dtype=torch.float32))
718
        target = {
719
            "boxes": make_bounding_boxes(canvas_size=size, format="XYXY", batch_dims=(num_objects,), dtype=torch.float),
720
721
722
723
724
725
726
            "labels": make_label(extra_dims=(num_objects,), categories=80),
        }
        if with_mask:
            target["masks"] = make_detection_mask(size=size, num_objects=num_objects, dtype=torch.long)

        yield (tensor_image, target)

727
        tv_tensor_image = make_image(size=size, color_space="RGB", dtype=torch.float32)
728
        target = {
729
            "boxes": make_bounding_boxes(canvas_size=size, format="XYXY", batch_dims=(num_objects,), dtype=torch.float),
730
731
732
733
734
            "labels": make_label(extra_dims=(num_objects,), categories=80),
        }
        if with_mask:
            target["masks"] = make_detection_mask(size=size, num_objects=num_objects, dtype=torch.long)

735
        yield (tv_tensor_image, target)
736
737
738
739

    @pytest.mark.parametrize(
        "t_ref, t, data_kwargs",
        [
740
            (det_transforms.RandomHorizontalFlip(p=1.0), v2_transforms.RandomHorizontalFlip(p=1.0), {}),
741
742
743
744
745
            (
                det_transforms.RandomIoUCrop(),
                v2_transforms.Compose(
                    [
                        v2_transforms.RandomIoUCrop(),
746
                        v2_transforms.SanitizeBoundingBoxes(labels_getter=lambda sample: sample[1]["labels"]),
747
748
749
750
                    ]
                ),
                {"with_mask": False},
            ),
751
            (det_transforms.RandomZoomOut(), v2_transforms.RandomZoomOut(), {"with_mask": False}),
752
            (det_transforms.ScaleJitter((1024, 1024)), v2_transforms.ScaleJitter((1024, 1024), antialias=True), {}),
753
754
755
756
            (
                det_transforms.RandomShortestSize(
                    min_size=(480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800), max_size=1333
                ),
757
                v2_transforms.RandomShortestSize(
758
759
760
761
762
763
764
                    min_size=(480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800), max_size=1333
                ),
                {},
            ),
        ],
    )
    def test_transform(self, t_ref, t, data_kwargs):
765
        for dp in self.make_tv_tensors(**data_kwargs):
766
767
768
769
770
771
772
773
774

            # We should use prototype transform first as reference transform performs inplace target update
            torch.manual_seed(12)
            output = t(dp)

            torch.manual_seed(12)
            expected_output = t_ref(*dp)

            assert_equal(expected_output, output)
775
776
777
778
779
780
781
782
783


seg_transforms = import_transforms_from_references("segmentation")


# We need this transform for two reasons:
# 1. transforms.RandomCrop uses a different scheme to pad images and masks of insufficient size than its name
#    counterpart in the detection references. Thus, we cannot use it with `pad_if_needed=True`
# 2. transforms.Pad only supports a fixed padding, but the segmentation datasets don't have a fixed image size.
784
class PadIfSmaller(v2_transforms.Transform):
785
786
787
    def __init__(self, size, fill=0):
        super().__init__()
        self.size = size
788
        self.fill = v2_transforms._geometry._setup_fill_arg(fill)
789
790

    def _get_params(self, sample):
Philip Meier's avatar
Philip Meier committed
791
        height, width = query_size(sample)
792
793
794
795
796
797
798
799
        padding = [0, 0, max(self.size - width, 0), max(self.size - height, 0)]
        needs_padding = any(padding)
        return dict(padding=padding, needs_padding=needs_padding)

    def _transform(self, inpt, params):
        if not params["needs_padding"]:
            return inpt

800
        fill = _get_fill(self.fill, type(inpt))
801
        return prototype_F.pad(inpt, padding=params["padding"], fill=fill)
802
803
804


class TestRefSegTransforms:
805
    def make_tv_tensors(self, supports_pil=True, image_dtype=torch.uint8):
806
        size = (256, 460)
807
808
809
810
        num_categories = 21

        conv_fns = []
        if supports_pil:
811
            conv_fns.append(to_pil_image)
812
813
814
        conv_fns.extend([torch.Tensor, lambda x: x])

        for conv_fn in conv_fns:
815
816
            tv_tensor_image = make_image(size=size, color_space="RGB", dtype=image_dtype)
            tv_tensor_mask = make_segmentation_mask(size=size, num_categories=num_categories, dtype=torch.uint8)
817

818
            dp = (conv_fn(tv_tensor_image), tv_tensor_mask)
819
            dp_ref = (
820
821
                to_pil_image(tv_tensor_image) if supports_pil else tv_tensor_image.as_subclass(torch.Tensor),
                to_pil_image(tv_tensor_mask),
822
823
824
825
826
827
828
829
830
            )

            yield dp, dp_ref

    def set_seed(self, seed=12):
        torch.manual_seed(seed)
        random.seed(seed)

    def check(self, t, t_ref, data_kwargs=None):
831
        for dp, dp_ref in self.make_tv_tensors(**data_kwargs or dict()):
832
833

            self.set_seed()
834
            actual = actual_image, actual_mask = t(dp)
835
836

            self.set_seed()
837
838
839
840
841
            expected_image, expected_mask = t_ref(*dp_ref)
            if isinstance(actual_image, torch.Tensor) and not isinstance(expected_image, torch.Tensor):
                expected_image = legacy_F.pil_to_tensor(expected_image)
            expected_mask = legacy_F.pil_to_tensor(expected_mask).squeeze(0)
            expected = (expected_image, expected_mask)
842

843
            assert_equal(actual, expected)
844
845
846
847
848
849

    @pytest.mark.parametrize(
        ("t_ref", "t", "data_kwargs"),
        [
            (
                seg_transforms.RandomHorizontalFlip(flip_prob=1.0),
850
                v2_transforms.RandomHorizontalFlip(p=1.0),
851
852
853
854
                dict(),
            ),
            (
                seg_transforms.RandomHorizontalFlip(flip_prob=0.0),
855
                v2_transforms.RandomHorizontalFlip(p=0.0),
856
857
858
859
                dict(),
            ),
            (
                seg_transforms.RandomCrop(size=480),
860
                v2_transforms.Compose(
861
                    [
862
                        PadIfSmaller(size=480, fill={tv_tensors.Mask: 255, "others": 0}),
863
                        v2_transforms.RandomCrop(size=480),
864
865
866
867
868
869
                    ]
                ),
                dict(),
            ),
            (
                seg_transforms.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
870
                v2_transforms.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
871
872
873
874
875
876
877
                dict(supports_pil=False, image_dtype=torch.float),
            ),
        ],
    )
    def test_common(self, t_ref, t, data_kwargs):
        self.check(t, t_ref, data_kwargs)

878
879
880
881
882
883
884
885
886
887
888
889

@pytest.mark.parametrize(
    ("legacy_dispatcher", "name_only_params"),
    [
        (legacy_F.get_dimensions, {}),
        (legacy_F.get_image_size, {}),
        (legacy_F.get_image_num_channels, {}),
        (legacy_F.to_tensor, {}),
        (legacy_F.pil_to_tensor, {}),
        (legacy_F.convert_image_dtype, {}),
        (legacy_F.to_pil_image, {}),
        (legacy_F.normalize, {}),
890
        (legacy_F.resize, {"interpolation"}),
891
892
893
        (legacy_F.pad, {"padding", "fill"}),
        (legacy_F.crop, {}),
        (legacy_F.center_crop, {}),
894
        (legacy_F.resized_crop, {"interpolation"}),
895
        (legacy_F.hflip, {}),
896
        (legacy_F.perspective, {"startpoints", "endpoints", "fill", "interpolation"}),
897
898
899
900
901
902
903
904
        (legacy_F.vflip, {}),
        (legacy_F.five_crop, {}),
        (legacy_F.ten_crop, {}),
        (legacy_F.adjust_brightness, {}),
        (legacy_F.adjust_contrast, {}),
        (legacy_F.adjust_saturation, {}),
        (legacy_F.adjust_hue, {}),
        (legacy_F.adjust_gamma, {}),
905
906
        (legacy_F.rotate, {"center", "fill", "interpolation"}),
        (legacy_F.affine, {"angle", "translate", "center", "fill", "interpolation"}),
907
908
909
910
911
912
913
914
915
916
917
        (legacy_F.to_grayscale, {}),
        (legacy_F.rgb_to_grayscale, {}),
        (legacy_F.to_tensor, {}),
        (legacy_F.erase, {}),
        (legacy_F.gaussian_blur, {}),
        (legacy_F.invert, {}),
        (legacy_F.posterize, {}),
        (legacy_F.solarize, {}),
        (legacy_F.adjust_sharpness, {}),
        (legacy_F.autocontrast, {}),
        (legacy_F.equalize, {}),
918
        (legacy_F.elastic_transform, {"fill", "interpolation"}),
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
    ],
)
def test_dispatcher_signature_consistency(legacy_dispatcher, name_only_params):
    legacy_signature = inspect.signature(legacy_dispatcher)
    legacy_params = list(legacy_signature.parameters.values())[1:]

    try:
        prototype_dispatcher = getattr(prototype_F, legacy_dispatcher.__name__)
    except AttributeError:
        raise AssertionError(
            f"Legacy dispatcher `F.{legacy_dispatcher.__name__}` has no prototype equivalent"
        ) from None

    prototype_signature = inspect.signature(prototype_dispatcher)
    prototype_params = list(prototype_signature.parameters.values())[1:]

    # Some dispatchers got extra parameters. This makes sure they have a default argument and thus are BC. We don't
    # need to check if parameters were added in the middle rather than at the end, since that will be caught by the
    # regular check below.
    prototype_params, new_prototype_params = (
        prototype_params[: len(legacy_params)],
        prototype_params[len(legacy_params) :],
    )
    for param in new_prototype_params:
        assert param.default is not param.empty

    # Some annotations were changed mostly to supersets of what was there before. Plus, some legacy dispatchers had no
    # annotations. In these cases we simply drop the annotation and default argument from the comparison
    for prototype_param, legacy_param in zip(prototype_params, legacy_params):
        if legacy_param.name in name_only_params:
            prototype_param._annotation = prototype_param._default = inspect.Parameter.empty
            legacy_param._annotation = legacy_param._default = inspect.Parameter.empty
        elif legacy_param.annotation is inspect.Parameter.empty:
            prototype_param._annotation = inspect.Parameter.empty

    assert prototype_params == legacy_params