test_transforms_v2_consistency.py 50.3 KB
Newer Older
1
import enum
2
3
import importlib.machinery
import importlib.util
4
import inspect
5
import random
6
import re
7
from collections import defaultdict
8
from pathlib import Path
9

10
import numpy as np
11
import PIL.Image
12
import pytest
13
14

import torch
15
import torchvision.transforms.v2 as v2_transforms
16
from common_utils import (
17
    ArgsKwargs,
18
    assert_close,
19
20
21
22
23
    assert_equal,
    make_bounding_box,
    make_detection_mask,
    make_image,
    make_images,
24
    make_segmentation_mask,
25
)
26
from torch import nn
27
from torchvision import datapoints, transforms as legacy_transforms
28
from torchvision._utils import sequence_to_str
29

30
from torchvision.transforms import functional as legacy_F
31
32
33
from torchvision.transforms.v2 import functional as prototype_F
from torchvision.transforms.v2.functional import to_image_pil
from torchvision.transforms.v2.utils import query_spatial_size
34

35
DEFAULT_MAKE_IMAGES_KWARGS = dict(color_spaces=["RGB"], extra_dims=[(4,)])
36
37


38
39
40
41
42
43
44
45
46
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


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


68
69
70
71
# 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)

72
73
CONSISTENCY_CONFIGS = [
    ConsistencyConfig(
74
        v2_transforms.Normalize,
75
76
77
78
79
80
81
82
        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(
83
        v2_transforms.Resize,
84
85
        legacy_transforms.Resize,
        [
86
            NotScriptableArgsKwargs(32),
87
            ArgsKwargs([32]),
88
            ArgsKwargs((32, 29)),
89
90
            ArgsKwargs((31, 28), interpolation=v2_transforms.InterpolationMode.NEAREST),
            ArgsKwargs((33, 26), interpolation=v2_transforms.InterpolationMode.BICUBIC),
91
92
93
            ArgsKwargs((30, 27), interpolation=PIL.Image.NEAREST),
            ArgsKwargs((35, 29), interpolation=PIL.Image.BILINEAR),
            ArgsKwargs((34, 25), interpolation=PIL.Image.BICUBIC),
94
95
96
97
            NotScriptableArgsKwargs(31, max_size=32),
            ArgsKwargs([31], max_size=32),
            NotScriptableArgsKwargs(30, max_size=100),
            ArgsKwargs([31], max_size=32),
98
99
            ArgsKwargs((29, 32), antialias=False),
            ArgsKwargs((28, 31), antialias=True),
100
101
102
        ],
    ),
    ConsistencyConfig(
103
        v2_transforms.CenterCrop,
104
105
106
107
108
109
        legacy_transforms.CenterCrop,
        [
            ArgsKwargs(18),
            ArgsKwargs((18, 13)),
        ],
    ),
110
    ConsistencyConfig(
111
        v2_transforms.FiveCrop,
112
113
114
115
116
117
118
119
        legacy_transforms.FiveCrop,
        [
            ArgsKwargs(18),
            ArgsKwargs((18, 13)),
        ],
        make_images_kwargs=dict(DEFAULT_MAKE_IMAGES_KWARGS, sizes=[(20, 19)]),
    ),
    ConsistencyConfig(
120
        v2_transforms.TenCrop,
121
122
123
124
        legacy_transforms.TenCrop,
        [
            ArgsKwargs(18),
            ArgsKwargs((18, 13)),
125
            ArgsKwargs(18, vertical_flip=True),
126
127
128
129
        ],
        make_images_kwargs=dict(DEFAULT_MAKE_IMAGES_KWARGS, sizes=[(20, 19)]),
    ),
    ConsistencyConfig(
130
        v2_transforms.Pad,
131
132
        legacy_transforms.Pad,
        [
133
            NotScriptableArgsKwargs(3),
134
135
136
            ArgsKwargs([3]),
            ArgsKwargs([2, 3]),
            ArgsKwargs([3, 2, 1, 4]),
137
138
139
140
141
            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"),
142
143
        ],
    ),
144
145
    *[
        ConsistencyConfig(
146
            v2_transforms.LinearTransformation,
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
            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),
        ]
    ],
166
    ConsistencyConfig(
167
        v2_transforms.Grayscale,
168
169
170
171
172
        legacy_transforms.Grayscale,
        [
            ArgsKwargs(num_output_channels=1),
            ArgsKwargs(num_output_channels=3),
        ],
173
        make_images_kwargs=dict(DEFAULT_MAKE_IMAGES_KWARGS, color_spaces=["RGB", "GRAY"]),
174
175
        # Use default tolerances of `torch.testing.assert_close`
        closeness_kwargs=dict(rtol=None, atol=None),
176
    ),
177
    ConsistencyConfig(
178
        v2_transforms.ConvertDtype,
179
180
181
182
183
184
185
186
187
        legacy_transforms.ConvertImageDtype,
        [
            ArgsKwargs(torch.float16),
            ArgsKwargs(torch.bfloat16),
            ArgsKwargs(torch.float32),
            ArgsKwargs(torch.float64),
            ArgsKwargs(torch.uint8),
        ],
        supports_pil=False,
188
189
        # Use default tolerances of `torch.testing.assert_close`
        closeness_kwargs=dict(rtol=None, atol=None),
190
191
    ),
    ConsistencyConfig(
192
        v2_transforms.ToPILImage,
193
        legacy_transforms.ToPILImage,
194
        [NotScriptableArgsKwargs()],
195
196
        make_images_kwargs=dict(
            color_spaces=[
197
198
199
200
                "GRAY",
                "GRAY_ALPHA",
                "RGB",
                "RGBA",
201
202
203
204
205
206
            ],
            extra_dims=[()],
        ),
        supports_pil=False,
    ),
    ConsistencyConfig(
207
        v2_transforms.Lambda,
208
209
        legacy_transforms.Lambda,
        [
210
            NotScriptableArgsKwargs(lambda image: image / 2),
211
212
213
214
215
        ],
        # 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,
    ),
216
    ConsistencyConfig(
217
        v2_transforms.RandomHorizontalFlip,
218
219
220
221
222
223
224
        legacy_transforms.RandomHorizontalFlip,
        [
            ArgsKwargs(p=0),
            ArgsKwargs(p=1),
        ],
    ),
    ConsistencyConfig(
225
        v2_transforms.RandomVerticalFlip,
226
227
228
229
230
231
232
        legacy_transforms.RandomVerticalFlip,
        [
            ArgsKwargs(p=0),
            ArgsKwargs(p=1),
        ],
    ),
    ConsistencyConfig(
233
        v2_transforms.RandomEqualize,
234
235
236
237
238
239
240
241
        legacy_transforms.RandomEqualize,
        [
            ArgsKwargs(p=0),
            ArgsKwargs(p=1),
        ],
        make_images_kwargs=dict(DEFAULT_MAKE_IMAGES_KWARGS, dtypes=[torch.uint8]),
    ),
    ConsistencyConfig(
242
        v2_transforms.RandomInvert,
243
244
245
246
247
248
249
        legacy_transforms.RandomInvert,
        [
            ArgsKwargs(p=0),
            ArgsKwargs(p=1),
        ],
    ),
    ConsistencyConfig(
250
        v2_transforms.RandomPosterize,
251
252
253
254
255
256
257
258
259
        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(
260
        v2_transforms.RandomSolarize,
261
262
263
264
265
266
267
        legacy_transforms.RandomSolarize,
        [
            ArgsKwargs(p=0, threshold=0.5),
            ArgsKwargs(p=1, threshold=0.3),
            ArgsKwargs(p=1, threshold=0.99),
        ],
    ),
268
269
    *[
        ConsistencyConfig(
270
            v2_transforms.RandomAutocontrast,
271
272
273
274
275
276
277
278
279
280
            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))]
    ],
281
    ConsistencyConfig(
282
        v2_transforms.RandomAdjustSharpness,
283
284
285
        legacy_transforms.RandomAdjustSharpness,
        [
            ArgsKwargs(p=0, sharpness_factor=0.5),
286
            ArgsKwargs(p=1, sharpness_factor=0.2),
287
288
            ArgsKwargs(p=1, sharpness_factor=0.99),
        ],
289
        closeness_kwargs={"atol": 1e-6, "rtol": 1e-6},
290
291
    ),
    ConsistencyConfig(
292
        v2_transforms.RandomGrayscale,
293
294
295
296
297
        legacy_transforms.RandomGrayscale,
        [
            ArgsKwargs(p=0),
            ArgsKwargs(p=1),
        ],
298
299
300
        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),
301
302
    ),
    ConsistencyConfig(
303
        v2_transforms.RandomResizedCrop,
304
305
306
307
308
        legacy_transforms.RandomResizedCrop,
        [
            ArgsKwargs(16),
            ArgsKwargs(17, scale=(0.3, 0.7)),
            ArgsKwargs(25, ratio=(0.5, 1.5)),
309
310
            ArgsKwargs((31, 28), interpolation=v2_transforms.InterpolationMode.NEAREST),
            ArgsKwargs((33, 26), interpolation=v2_transforms.InterpolationMode.BICUBIC),
311
312
            ArgsKwargs((31, 28), interpolation=PIL.Image.NEAREST),
            ArgsKwargs((33, 26), interpolation=PIL.Image.BICUBIC),
313
314
315
316
317
            ArgsKwargs((29, 32), antialias=False),
            ArgsKwargs((28, 31), antialias=True),
        ],
    ),
    ConsistencyConfig(
318
        v2_transforms.RandomErasing,
319
320
321
322
323
324
325
326
327
328
329
330
331
        legacy_transforms.RandomErasing,
        [
            ArgsKwargs(p=0),
            ArgsKwargs(p=1),
            ArgsKwargs(p=1, scale=(0.3, 0.7)),
            ArgsKwargs(p=1, ratio=(0.5, 1.5)),
            ArgsKwargs(p=1, value=1),
            ArgsKwargs(p=1, value=(1, 2, 3)),
            ArgsKwargs(p=1, value="random"),
        ],
        supports_pil=False,
    ),
    ConsistencyConfig(
332
        v2_transforms.ColorJitter,
333
334
335
336
337
338
339
340
341
342
343
        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)),
344
            ArgsKwargs(brightness=0.1, contrast=0.4, saturation=0.5, hue=0.3),
345
        ],
346
        closeness_kwargs={"atol": 1e-5, "rtol": 1e-5},
347
    ),
348
349
    *[
        ConsistencyConfig(
350
            v2_transforms.ElasticTransform,
351
352
353
354
355
356
357
            legacy_transforms.ElasticTransform,
            [
                ArgsKwargs(),
                ArgsKwargs(alpha=20.0),
                ArgsKwargs(alpha=(15.3, 27.2)),
                ArgsKwargs(sigma=3.0),
                ArgsKwargs(sigma=(2.5, 3.9)),
358
359
                ArgsKwargs(interpolation=v2_transforms.InterpolationMode.NEAREST),
                ArgsKwargs(interpolation=v2_transforms.InterpolationMode.BICUBIC),
360
361
                ArgsKwargs(interpolation=PIL.Image.NEAREST),
                ArgsKwargs(interpolation=PIL.Image.BICUBIC),
362
363
364
365
366
367
368
369
370
371
                ArgsKwargs(fill=1),
            ],
            # ElasticTransform needs larger images to avoid the needed internal padding being larger than the actual image
            make_images_kwargs=dict(DEFAULT_MAKE_IMAGES_KWARGS, sizes=[(163, 163), (72, 333), (313, 95)], dtypes=[dt]),
            # We updated gaussian blur kernel generation with a faster and numerically more stable version
            # This brings float32 accumulation visible in elastic transform -> we need to relax consistency tolerance
            closeness_kwargs=ckw,
        )
        for dt, ckw in [(torch.uint8, {"rtol": 1e-1, "atol": 1}), (torch.float32, {"rtol": 1e-2, "atol": 1e-3})]
    ],
372
    ConsistencyConfig(
373
        v2_transforms.GaussianBlur,
374
375
376
377
378
379
380
        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)),
        ],
381
        closeness_kwargs={"rtol": 1e-5, "atol": 1e-5},
382
383
    ),
    ConsistencyConfig(
384
        v2_transforms.RandomAffine,
385
386
387
388
389
390
391
392
393
394
        legacy_transforms.RandomAffine,
        [
            ArgsKwargs(degrees=30.0),
            ArgsKwargs(degrees=(-20.0, 10.0)),
            ArgsKwargs(degrees=0.0, translate=(0.4, 0.6)),
            ArgsKwargs(degrees=0.0, scale=(0.3, 0.8)),
            ArgsKwargs(degrees=0.0, shear=13),
            ArgsKwargs(degrees=0.0, shear=(8, 17)),
            ArgsKwargs(degrees=0.0, shear=(4, 5, 4, 13)),
            ArgsKwargs(degrees=(-20.0, 10.0), translate=(0.4, 0.6), scale=(0.3, 0.8), shear=(4, 5, 4, 13)),
395
            ArgsKwargs(degrees=30.0, interpolation=v2_transforms.InterpolationMode.NEAREST),
396
            ArgsKwargs(degrees=30.0, interpolation=PIL.Image.NEAREST),
397
398
399
400
            ArgsKwargs(degrees=30.0, fill=1),
            ArgsKwargs(degrees=30.0, fill=(2, 3, 4)),
            ArgsKwargs(degrees=30.0, center=(0, 0)),
        ],
401
        removed_params=["fillcolor", "resample"],
402
403
    ),
    ConsistencyConfig(
404
        v2_transforms.RandomCrop,
405
406
407
408
        legacy_transforms.RandomCrop,
        [
            ArgsKwargs(12),
            ArgsKwargs((15, 17)),
409
410
            NotScriptableArgsKwargs(11, padding=1),
            ArgsKwargs(11, padding=[1]),
411
412
413
414
            ArgsKwargs((8, 13), padding=(2, 3)),
            ArgsKwargs((14, 9), padding=(0, 2, 1, 0)),
            ArgsKwargs(36, pad_if_needed=True),
            ArgsKwargs((7, 8), fill=1),
415
            NotScriptableArgsKwargs(5, fill=(1, 2, 3)),
416
            ArgsKwargs(12),
417
            NotScriptableArgsKwargs(15, padding=2, padding_mode="edge"),
418
419
420
421
422
423
            ArgsKwargs(17, padding=(1, 0), padding_mode="reflect"),
            ArgsKwargs(8, padding=(3, 0, 0, 1), padding_mode="symmetric"),
        ],
        make_images_kwargs=dict(DEFAULT_MAKE_IMAGES_KWARGS, sizes=[(26, 26), (18, 33), (29, 22)]),
    ),
    ConsistencyConfig(
424
        v2_transforms.RandomPerspective,
425
426
427
428
429
        legacy_transforms.RandomPerspective,
        [
            ArgsKwargs(p=0),
            ArgsKwargs(p=1),
            ArgsKwargs(p=1, distortion_scale=0.3),
430
            ArgsKwargs(p=1, distortion_scale=0.2, interpolation=v2_transforms.InterpolationMode.NEAREST),
431
            ArgsKwargs(p=1, distortion_scale=0.2, interpolation=PIL.Image.NEAREST),
432
433
434
            ArgsKwargs(p=1, distortion_scale=0.1, fill=1),
            ArgsKwargs(p=1, distortion_scale=0.4, fill=(1, 2, 3)),
        ],
435
        closeness_kwargs={"atol": None, "rtol": None},
436
437
    ),
    ConsistencyConfig(
438
        v2_transforms.RandomRotation,
439
440
441
442
        legacy_transforms.RandomRotation,
        [
            ArgsKwargs(degrees=30.0),
            ArgsKwargs(degrees=(-20.0, 10.0)),
443
            ArgsKwargs(degrees=30.0, interpolation=v2_transforms.InterpolationMode.BILINEAR),
444
            ArgsKwargs(degrees=30.0, interpolation=PIL.Image.BILINEAR),
445
446
447
448
449
            ArgsKwargs(degrees=30.0, expand=True),
            ArgsKwargs(degrees=30.0, center=(0, 0)),
            ArgsKwargs(degrees=30.0, fill=1),
            ArgsKwargs(degrees=30.0, fill=(1, 2, 3)),
        ],
450
        removed_params=["resample"],
451
    ),
452
    ConsistencyConfig(
453
        v2_transforms.PILToTensor,
454
455
456
        legacy_transforms.PILToTensor,
    ),
    ConsistencyConfig(
457
        v2_transforms.ToTensor,
458
459
460
        legacy_transforms.ToTensor,
    ),
    ConsistencyConfig(
461
        v2_transforms.Compose,
462
463
464
        legacy_transforms.Compose,
    ),
    ConsistencyConfig(
465
        v2_transforms.RandomApply,
466
467
468
        legacy_transforms.RandomApply,
    ),
    ConsistencyConfig(
469
        v2_transforms.RandomChoice,
470
471
472
        legacy_transforms.RandomChoice,
    ),
    ConsistencyConfig(
473
        v2_transforms.RandomOrder,
474
475
476
        legacy_transforms.RandomOrder,
    ),
    ConsistencyConfig(
477
        v2_transforms.AugMix,
478
479
480
        legacy_transforms.AugMix,
    ),
    ConsistencyConfig(
481
        v2_transforms.AutoAugment,
482
483
484
        legacy_transforms.AutoAugment,
    ),
    ConsistencyConfig(
485
        v2_transforms.RandAugment,
486
487
488
        legacy_transforms.RandAugment,
    ),
    ConsistencyConfig(
489
        v2_transforms.TrivialAugmentWide,
490
491
        legacy_transforms.TrivialAugmentWide,
    ),
492
493
494
]


495
496
def test_automatic_coverage():
    available = {
497
498
        name
        for name, obj in legacy_transforms.__dict__.items()
499
        if not name.startswith("_") and isinstance(obj, type) and not issubclass(obj, enum.Enum)
500
501
    }

502
    checked = {config.legacy_cls.__name__ for config in CONSISTENCY_CONFIGS}
503

504
    missing = available - checked
505
506
507
508
509
510
511
    if missing:
        raise AssertionError(
            f"The prototype transformations {sequence_to_str(sorted(missing), separate_last='and ')} "
            f"are not checked for consistency although a legacy counterpart exists."
        )


512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
@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()
530
531
532
533
534
535
    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}
    }
536
537
    if extra_without_default:
        raise AssertionError(
538
539
540
            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."
541
542
        )

543
544
545
    legacy_kinds = {name: param.kind for name, param in legacy_params.items()}
    prototype_kinds = {name: prototype_params[name].kind for name in legacy_kinds.keys()}
    assert prototype_kinds == legacy_kinds
546
547


548
549
550
def check_call_consistency(
    prototype_transform, legacy_transform, images=None, supports_pil=True, closeness_kwargs=None
):
551
552
    if images is None:
        images = make_images(**DEFAULT_MAKE_IMAGES_KWARGS)
553

554
555
    closeness_kwargs = closeness_kwargs or dict()

556
557
    for image in images:
        image_repr = f"[{tuple(image.shape)}, {str(image.dtype).rsplit('.')[-1]}]"
558
559
560

        image_tensor = torch.Tensor(image)
        try:
561
            torch.manual_seed(0)
562
            output_legacy_tensor = legacy_transform(image_tensor)
563
564
        except Exception as exc:
            raise pytest.UsageError(
565
                f"Transforming a tensor image {image_repr} failed in the legacy transform with the "
566
                f"error above. This means that you need to specify the parameters passed to `make_images` through the "
567
568
569
570
                "`make_images_kwargs` of the `ConsistencyConfig`."
            ) from exc

        try:
571
            torch.manual_seed(0)
572
            output_prototype_tensor = prototype_transform(image_tensor)
573
574
        except Exception as exc:
            raise AssertionError(
575
                f"Transforming a tensor image with shape {image_repr} failed in the prototype transform with "
576
577
                f"the error above. This means there is a consistency bug either in `_get_params` or in the "
                f"`is_simple_tensor` path in `_transform`."
578
579
            ) from exc

580
        assert_close(
581
582
583
            output_prototype_tensor,
            output_legacy_tensor,
            msg=lambda msg: f"Tensor image consistency check failed with: \n\n{msg}",
584
            **closeness_kwargs,
585
586
587
        )

        try:
588
            torch.manual_seed(0)
589
            output_prototype_image = prototype_transform(image)
590
591
        except Exception as exc:
            raise AssertionError(
592
                f"Transforming a image datapoint with shape {image_repr} failed in the prototype transform with "
593
                f"the error above. This means there is a consistency bug either in `_get_params` or in the "
594
                f"`datapoints.Image` path in `_transform`."
595
596
            ) from exc

597
        assert_close(
598
            output_prototype_image,
599
            output_prototype_tensor,
600
            msg=lambda msg: f"Output for datapoint and tensor images is not equal: \n\n{msg}",
601
            **closeness_kwargs,
602
603
        )

604
605
606
        if image.ndim == 3 and supports_pil:
            image_pil = to_image_pil(image)

607
            try:
608
                torch.manual_seed(0)
609
                output_legacy_pil = legacy_transform(image_pil)
610
611
            except Exception as exc:
                raise pytest.UsageError(
612
                    f"Transforming a PIL image with shape {image_repr} failed in the legacy transform with the "
613
614
615
616
617
                    f"error above. If this transform does not support PIL images, set `supports_pil=False` on the "
                    "`ConsistencyConfig`. "
                ) from exc

            try:
618
                torch.manual_seed(0)
619
                output_prototype_pil = prototype_transform(image_pil)
620
621
            except Exception as exc:
                raise AssertionError(
622
                    f"Transforming a PIL image with shape {image_repr} failed in the prototype transform with "
623
624
625
626
                    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

627
            assert_close(
628
629
                output_prototype_pil,
                output_legacy_pil,
630
                msg=lambda msg: f"PIL image consistency check failed with: \n\n{msg}",
631
                **closeness_kwargs,
632
            )
633
634


635
@pytest.mark.parametrize(
636
637
    ("config", "args_kwargs"),
    [
638
639
640
        pytest.param(
            config, args_kwargs, id=f"{config.legacy_cls.__name__}-{idx:0{len(str(len(config.args_kwargs)))}d}"
        )
641
        for config in CONSISTENCY_CONFIGS
642
        for idx, args_kwargs in enumerate(config.args_kwargs)
643
    ],
644
)
645
@pytest.mark.filterwarnings("ignore")
646
def test_call_consistency(config, args_kwargs):
647
648
649
    args, kwargs = args_kwargs

    try:
650
        legacy_transform = config.legacy_cls(*args, **kwargs)
651
652
653
654
655
656
657
    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:
658
        prototype_transform = config.prototype_cls(*args, **kwargs)
659
660
661
662
663
664
    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

665
666
667
668
669
    check_call_consistency(
        prototype_transform,
        legacy_transform,
        images=make_images(**config.make_images_kwargs),
        supports_pil=config.supports_pil,
670
        closeness_kwargs=config.closeness_kwargs,
671
672
673
    )


674
675
676
677
678
679
680
681
682
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 [
683
684
685
686
687
            (v2_transforms.RandomResizedCrop, ArgsKwargs(make_image(), scale=[0.3, 0.7], ratio=[0.5, 1.5])),
            (v2_transforms.RandomErasing, ArgsKwargs(make_image(), scale=(0.3, 0.7), ratio=(0.5, 1.5))),
            (v2_transforms.ColorJitter, ArgsKwargs(brightness=None, contrast=None, saturation=None, hue=None)),
            (v2_transforms.ElasticTransform, ArgsKwargs(alpha=[15.3, 27.2], sigma=[2.5, 3.9], size=[17, 31])),
            (v2_transforms.GaussianBlur, ArgsKwargs(0.3, 1.4)),
688
            (
689
                v2_transforms.RandomAffine,
690
691
                ArgsKwargs(degrees=[-20.0, 10.0], translate=None, scale_ranges=None, shears=None, img_size=[15, 29]),
            ),
692
693
694
695
            (v2_transforms.RandomCrop, ArgsKwargs(make_image(size=(61, 47)), output_size=(19, 25))),
            (v2_transforms.RandomPerspective, ArgsKwargs(23, 17, 0.5)),
            (v2_transforms.RandomRotation, ArgsKwargs(degrees=[-20.0, 10.0])),
            (v2_transforms.AutoAugment, ArgsKwargs(5)),
696
697
        ]
    ],
698
)
699
700


701
@get_params_parametrization
702
def test_get_params_alias(config, get_params_args_kwargs):
703
704
    assert config.prototype_cls.get_params is config.legacy_cls.get_params

705
706
707
708
709
    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)
710

711
712
713
    assert prototype_transform.get_params is legacy_transform.get_params


714
@get_params_parametrization
715
716
717
718
719
720
721
722
723
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)
724

725
    torch.jit.script(transform.get_params)(*get_params_args, **get_params_kwargs)
726
727


728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
@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)


760
761
762
763
764
765
766
767
768
769
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):
770
        prototype_transform = v2_transforms.Compose(
771
            [
772
773
                v2_transforms.Resize(256),
                v2_transforms.CenterCrop(224),
774
775
776
777
778
779
780
781
782
            ]
        )
        legacy_transform = legacy_transforms.Compose(
            [
                legacy_transforms.Resize(256),
                legacy_transforms.CenterCrop(224),
            ]
        )

783
        check_call_consistency(prototype_transform, legacy_transform)
784
785

    @pytest.mark.parametrize("p", [0, 0.1, 0.5, 0.9, 1])
786
787
    @pytest.mark.parametrize("sequence_type", [list, nn.ModuleList])
    def test_random_apply(self, p, sequence_type):
788
        prototype_transform = v2_transforms.RandomApply(
789
790
            sequence_type(
                [
791
792
                    v2_transforms.Resize(256),
                    v2_transforms.CenterCrop(224),
793
794
                ]
            ),
795
796
797
            p=p,
        )
        legacy_transform = legacy_transforms.RandomApply(
798
799
800
801
802
803
            sequence_type(
                [
                    legacy_transforms.Resize(256),
                    legacy_transforms.CenterCrop(224),
                ]
            ),
804
805
806
            p=p,
        )

807
        check_call_consistency(prototype_transform, legacy_transform)
808

809
810
811
812
813
        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))

814
    # We can't test other values for `p` since the random parameter generation is different
815
816
    @pytest.mark.parametrize("probabilities", [(0, 1), (1, 0)])
    def test_random_choice(self, probabilities):
817
        prototype_transform = v2_transforms.RandomChoice(
818
            [
819
                v2_transforms.Resize(256),
820
821
                legacy_transforms.CenterCrop(224),
            ],
822
            probabilities=probabilities,
823
824
825
826
827
828
        )
        legacy_transform = legacy_transforms.RandomChoice(
            [
                legacy_transforms.Resize(256),
                legacy_transforms.CenterCrop(224),
            ],
829
            p=probabilities,
830
831
        )

832
        check_call_consistency(prototype_transform, legacy_transform)
833
834


835
836
class TestToTensorTransforms:
    def test_pil_to_tensor(self):
837
        prototype_transform = v2_transforms.PILToTensor()
838
839
        legacy_transform = legacy_transforms.PILToTensor()

840
841
842
843
844
845
        for image in make_images(extra_dims=[()]):
            image_pil = to_image_pil(image)

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

    def test_to_tensor(self):
846
        with pytest.warns(UserWarning, match=re.escape("The transform `ToTensor()` is deprecated")):
847
            prototype_transform = v2_transforms.ToTensor()
848
849
        legacy_transform = legacy_transforms.ToTensor()

850
851
852
853
854
855
        for image in make_images(extra_dims=[()]):
            image_pil = to_image_pil(image)
            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))
856
857
858
859
860
861
862
863


class TestAATransforms:
    @pytest.mark.parametrize(
        "inpt",
        [
            torch.randint(0, 256, size=(1, 3, 256, 256), dtype=torch.uint8),
            PIL.Image.new("RGB", (256, 256), 123),
864
            datapoints.Image(torch.randint(0, 256, size=(1, 3, 256, 256), dtype=torch.uint8)),
865
866
867
868
        ],
    )
    @pytest.mark.parametrize(
        "interpolation",
869
        [
870
871
            v2_transforms.InterpolationMode.NEAREST,
            v2_transforms.InterpolationMode.BILINEAR,
872
873
            PIL.Image.NEAREST,
        ],
874
875
876
    )
    def test_randaug(self, inpt, interpolation, mocker):
        t_ref = legacy_transforms.RandAugment(interpolation=interpolation, num_ops=1)
877
        t = v2_transforms.RandAugment(interpolation=interpolation, num_ops=1)
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898

        le = len(t._AUGMENTATION_SPACE)
        keys = list(t._AUGMENTATION_SPACE.keys())
        randint_values = []
        for i in range(le):
            # Stable API, op_index random call
            randint_values.append(i)
            # Stable API, if signed there is another random call
            if t._AUGMENTATION_SPACE[keys[i]][1]:
                randint_values.append(0)
            # New API, _get_random_item
            randint_values.append(i)
        randint_values = iter(randint_values)

        mocker.patch("torch.randint", side_effect=lambda *arg, **kwargs: torch.tensor(next(randint_values)))
        mocker.patch("torch.rand", return_value=1.0)

        for i in range(le):
            expected_output = t_ref(inpt)
            output = t(inpt)

899
            assert_close(expected_output, output, atol=1, rtol=0.1)
900
901
902
903
904
905

    @pytest.mark.parametrize(
        "inpt",
        [
            torch.randint(0, 256, size=(1, 3, 256, 256), dtype=torch.uint8),
            PIL.Image.new("RGB", (256, 256), 123),
906
            datapoints.Image(torch.randint(0, 256, size=(1, 3, 256, 256), dtype=torch.uint8)),
907
908
909
910
        ],
    )
    @pytest.mark.parametrize(
        "interpolation",
911
        [
912
913
            v2_transforms.InterpolationMode.NEAREST,
            v2_transforms.InterpolationMode.BILINEAR,
914
915
            PIL.Image.NEAREST,
        ],
916
917
918
    )
    def test_trivial_aug(self, inpt, interpolation, mocker):
        t_ref = legacy_transforms.TrivialAugmentWide(interpolation=interpolation)
919
        t = v2_transforms.TrivialAugmentWide(interpolation=interpolation)
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

        le = len(t._AUGMENTATION_SPACE)
        keys = list(t._AUGMENTATION_SPACE.keys())
        randint_values = []
        for i in range(le):
            # Stable API, op_index random call
            randint_values.append(i)
            key = keys[i]
            # Stable API, random magnitude
            aug_op = t._AUGMENTATION_SPACE[key]
            magnitudes = aug_op[0](2, 0, 0)
            if magnitudes is not None:
                randint_values.append(5)
            # Stable API, if signed there is another random call
            if aug_op[1]:
                randint_values.append(0)
            # New API, _get_random_item
            randint_values.append(i)
            # New API, random magnitude
            if magnitudes is not None:
                randint_values.append(5)

        randint_values = iter(randint_values)

        mocker.patch("torch.randint", side_effect=lambda *arg, **kwargs: torch.tensor(next(randint_values)))
        mocker.patch("torch.rand", return_value=1.0)

        for _ in range(le):
            expected_output = t_ref(inpt)
            output = t(inpt)

951
            assert_close(expected_output, output, atol=1, rtol=0.1)
952
953
954
955
956
957

    @pytest.mark.parametrize(
        "inpt",
        [
            torch.randint(0, 256, size=(1, 3, 256, 256), dtype=torch.uint8),
            PIL.Image.new("RGB", (256, 256), 123),
958
            datapoints.Image(torch.randint(0, 256, size=(1, 3, 256, 256), dtype=torch.uint8)),
959
960
961
962
        ],
    )
    @pytest.mark.parametrize(
        "interpolation",
963
        [
964
965
            v2_transforms.InterpolationMode.NEAREST,
            v2_transforms.InterpolationMode.BILINEAR,
966
967
            PIL.Image.NEAREST,
        ],
968
969
970
971
    )
    def test_augmix(self, inpt, interpolation, mocker):
        t_ref = legacy_transforms.AugMix(interpolation=interpolation, mixture_width=1, chain_depth=1)
        t_ref._sample_dirichlet = lambda t: t.softmax(dim=-1)
972
        t = v2_transforms.AugMix(interpolation=interpolation, mixture_width=1, chain_depth=1)
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
        t._sample_dirichlet = lambda t: t.softmax(dim=-1)

        le = len(t._AUGMENTATION_SPACE)
        keys = list(t._AUGMENTATION_SPACE.keys())
        randint_values = []
        for i in range(le):
            # Stable API, op_index random call
            randint_values.append(i)
            key = keys[i]
            # Stable API, random magnitude
            aug_op = t._AUGMENTATION_SPACE[key]
            magnitudes = aug_op[0](2, 0, 0)
            if magnitudes is not None:
                randint_values.append(5)
            # Stable API, if signed there is another random call
            if aug_op[1]:
                randint_values.append(0)
            # New API, _get_random_item
            randint_values.append(i)
            # New API, random magnitude
            if magnitudes is not None:
                randint_values.append(5)

        randint_values = iter(randint_values)

        mocker.patch("torch.randint", side_effect=lambda *arg, **kwargs: torch.tensor(next(randint_values)))
        mocker.patch("torch.rand", return_value=1.0)

        expected_output = t_ref(inpt)
        output = t(inpt)

        assert_equal(expected_output, output)

    @pytest.mark.parametrize(
        "inpt",
        [
            torch.randint(0, 256, size=(1, 3, 256, 256), dtype=torch.uint8),
            PIL.Image.new("RGB", (256, 256), 123),
1011
            datapoints.Image(torch.randint(0, 256, size=(1, 3, 256, 256), dtype=torch.uint8)),
1012
1013
1014
1015
        ],
    )
    @pytest.mark.parametrize(
        "interpolation",
1016
        [
1017
1018
            v2_transforms.InterpolationMode.NEAREST,
            v2_transforms.InterpolationMode.BILINEAR,
1019
1020
            PIL.Image.NEAREST,
        ],
1021
1022
1023
1024
    )
    def test_aa(self, inpt, interpolation):
        aa_policy = legacy_transforms.AutoAugmentPolicy("imagenet")
        t_ref = legacy_transforms.AutoAugment(aa_policy, interpolation=interpolation)
1025
        t = v2_transforms.AutoAugment(aa_policy, interpolation=interpolation)
1026
1027
1028
1029
1030
1031
1032
1033

        torch.manual_seed(12)
        expected_output = t_ref(inpt)

        torch.manual_seed(12)
        output = t(inpt)

        assert_equal(expected_output, output)
1034
1035


1036
def import_transforms_from_references(reference):
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
    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
1047
1048
1049


det_transforms = import_transforms_from_references("detection")
1050
1051
1052
1053
1054
1055
1056


class TestRefDetTransforms:
    def make_datapoints(self, with_mask=True):
        size = (600, 800)
        num_objects = 22

1057
1058
1059
        def make_label(extra_dims, categories):
            return torch.randint(categories, extra_dims, dtype=torch.int64)

1060
        pil_image = to_image_pil(make_image(size=size, color_space="RGB"))
1061
        target = {
1062
            "boxes": make_bounding_box(spatial_size=size, format="XYXY", extra_dims=(num_objects,), dtype=torch.float),
1063
1064
1065
1066
1067
1068
1069
            "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)

1070
        tensor_image = torch.Tensor(make_image(size=size, color_space="RGB"))
1071
        target = {
1072
            "boxes": make_bounding_box(spatial_size=size, format="XYXY", extra_dims=(num_objects,), dtype=torch.float),
1073
1074
1075
1076
1077
1078
1079
            "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)

1080
        datapoint_image = make_image(size=size, color_space="RGB")
1081
        target = {
1082
            "boxes": make_bounding_box(spatial_size=size, format="XYXY", extra_dims=(num_objects,), dtype=torch.float),
1083
1084
1085
1086
1087
            "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)

1088
        yield (datapoint_image, target)
1089
1090
1091
1092

    @pytest.mark.parametrize(
        "t_ref, t, data_kwargs",
        [
1093
            (det_transforms.RandomHorizontalFlip(p=1.0), v2_transforms.RandomHorizontalFlip(p=1.0), {}),
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
            (
                det_transforms.RandomIoUCrop(),
                v2_transforms.Compose(
                    [
                        v2_transforms.RandomIoUCrop(),
                        v2_transforms.SanitizeBoundingBoxes(labels_getter=lambda sample: sample[1]["labels"]),
                    ]
                ),
                {"with_mask": False},
            ),
1104
1105
            (det_transforms.RandomZoomOut(), v2_transforms.RandomZoomOut(), {"with_mask": False}),
            (det_transforms.ScaleJitter((1024, 1024)), v2_transforms.ScaleJitter((1024, 1024)), {}),
1106
1107
1108
1109
            (
                det_transforms.RandomShortestSize(
                    min_size=(480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800), max_size=1333
                ),
1110
                v2_transforms.RandomShortestSize(
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
                    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):
        for dp in self.make_datapoints(**data_kwargs):

            # 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)
1128
1129
1130
1131
1132
1133
1134
1135
1136


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.
1137
class PadIfSmaller(v2_transforms.Transform):
1138
1139
1140
    def __init__(self, size, fill=0):
        super().__init__()
        self.size = size
1141
        self.fill = v2_transforms._geometry._setup_fill_arg(fill)
1142
1143

    def _get_params(self, sample):
1144
        height, width = query_spatial_size(sample)
1145
1146
1147
1148
1149
1150
1151
1152
1153
        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

        fill = self.fill[type(inpt)]
1154
        return prototype_F.pad(inpt, padding=params["padding"], fill=fill)
1155
1156
1157
1158


class TestRefSegTransforms:
    def make_datapoints(self, supports_pil=True, image_dtype=torch.uint8):
1159
        size = (256, 460)
1160
1161
1162
1163
1164
1165
1166
1167
        num_categories = 21

        conv_fns = []
        if supports_pil:
            conv_fns.append(to_image_pil)
        conv_fns.extend([torch.Tensor, lambda x: x])

        for conv_fn in conv_fns:
1168
            datapoint_image = make_image(size=size, color_space="RGB", dtype=image_dtype)
1169
            datapoint_mask = make_segmentation_mask(size=size, num_categories=num_categories, dtype=torch.uint8)
1170

1171
            dp = (conv_fn(datapoint_image), datapoint_mask)
1172
            dp_ref = (
1173
1174
                to_image_pil(datapoint_image) if supports_pil else datapoint_image.as_subclass(torch.Tensor),
                to_image_pil(datapoint_mask),
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
            )

            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):
        for dp, dp_ref in self.make_datapoints(**data_kwargs or dict()):

            self.set_seed()
1187
            actual = actual_image, actual_mask = t(dp)
1188
1189

            self.set_seed()
1190
1191
1192
1193
1194
            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)
1195

1196
            assert_equal(actual, expected)
1197
1198
1199
1200
1201
1202

    @pytest.mark.parametrize(
        ("t_ref", "t", "data_kwargs"),
        [
            (
                seg_transforms.RandomHorizontalFlip(flip_prob=1.0),
1203
                v2_transforms.RandomHorizontalFlip(p=1.0),
1204
1205
1206
1207
                dict(),
            ),
            (
                seg_transforms.RandomHorizontalFlip(flip_prob=0.0),
1208
                v2_transforms.RandomHorizontalFlip(p=0.0),
1209
1210
1211
1212
                dict(),
            ),
            (
                seg_transforms.RandomCrop(size=480),
1213
                v2_transforms.Compose(
1214
                    [
1215
                        PadIfSmaller(size=480, fill=defaultdict(lambda: 0, {datapoints.Mask: 255})),
1216
                        v2_transforms.RandomCrop(size=480),
1217
1218
1219
1220
1221
1222
                    ]
                ),
                dict(),
            ),
            (
                seg_transforms.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
1223
                v2_transforms.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
1224
1225
1226
1227
1228
1229
1230
1231
                dict(supports_pil=False, image_dtype=torch.float),
            ),
        ],
    )
    def test_common(self, t_ref, t, data_kwargs):
        self.check(t, t_ref, data_kwargs)

    def check_resize(self, mocker, t_ref, t):
1232
        mock = mocker.patch("torchvision.transforms.v2._geometry.F.resize")
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
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
        mock_ref = mocker.patch("torchvision.transforms.functional.resize")

        for dp, dp_ref in self.make_datapoints():
            mock.reset_mock()
            mock_ref.reset_mock()

            self.set_seed()
            t(dp)
            assert mock.call_count == 2
            assert all(
                actual is expected
                for actual, expected in zip([call_args[0][0] for call_args in mock.call_args_list], dp)
            )

            self.set_seed()
            t_ref(*dp_ref)
            assert mock_ref.call_count == 2
            assert all(
                actual is expected
                for actual, expected in zip([call_args[0][0] for call_args in mock_ref.call_args_list], dp_ref)
            )

            for args_kwargs, args_kwargs_ref in zip(mock.call_args_list, mock_ref.call_args_list):
                assert args_kwargs[0][1] == [args_kwargs_ref[0][1]]

    def test_random_resize_train(self, mocker):
        base_size = 520
        min_size = base_size // 2
        max_size = base_size * 2

        randint = torch.randint

        def patched_randint(a, b, *other_args, **kwargs):
            if kwargs or len(other_args) > 1 or other_args[0] != ():
                return randint(a, b, *other_args, **kwargs)

            return random.randint(a, b)

        # We are patching torch.randint -> random.randint here, because we can't patch the modules that are not imported
        # normally
1273
        t = v2_transforms.RandomResize(min_size=min_size, max_size=max_size, antialias=True)
1274
        mocker.patch(
1275
            "torchvision.transforms.v2._geometry.torch.randint",
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
            new=patched_randint,
        )

        t_ref = seg_transforms.RandomResize(min_size=min_size, max_size=max_size)

        self.check_resize(mocker, t_ref, t)

    def test_random_resize_eval(self, mocker):
        torch.manual_seed(0)
        base_size = 520

1287
        t = v2_transforms.Resize(size=base_size, antialias=True)
1288
1289
1290
1291

        t_ref = seg_transforms.RandomResize(min_size=base_size, max_size=base_size)

        self.check_resize(mocker, t_ref, t)
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304


@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, {}),
1305
        (legacy_F.resize, {"interpolation"}),
1306
1307
1308
        (legacy_F.pad, {"padding", "fill"}),
        (legacy_F.crop, {}),
        (legacy_F.center_crop, {}),
1309
        (legacy_F.resized_crop, {"interpolation"}),
1310
        (legacy_F.hflip, {}),
1311
        (legacy_F.perspective, {"startpoints", "endpoints", "fill", "interpolation"}),
1312
1313
1314
1315
1316
1317
1318
1319
        (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, {}),
1320
1321
        (legacy_F.rotate, {"center", "fill", "interpolation"}),
        (legacy_F.affine, {"angle", "translate", "center", "fill", "interpolation"}),
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
        (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, {}),
1333
        (legacy_F.elastic_transform, {"fill", "interpolation"}),
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
    ],
)
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