test_transforms_tensor.py 35 KB
Newer Older
1
import os
2
import sys
3
import warnings
4
5

import numpy as np
6
import PIL.Image
7
import pytest
8
import torch
Nicolas Hug's avatar
Nicolas Hug committed
9
from common_utils import (
10
11
    _assert_approx_equal_tensor_to_pil,
    _assert_equal_tensor_to_pil,
Nicolas Hug's avatar
Nicolas Hug committed
12
13
    _create_data,
    _create_data_batch,
14
    assert_equal,
15
    cpu_and_cuda,
16
17
18
    float_dtypes,
    get_tmp_dir,
    int_dtypes,
Nicolas Hug's avatar
Nicolas Hug committed
19
)
20
from torchvision import transforms as T
21
from torchvision.transforms import functional as F, InterpolationMode
22
from torchvision.transforms.autoaugment import _apply_op
23

24
25
26
27
28
29
NEAREST, NEAREST_EXACT, BILINEAR, BICUBIC = (
    InterpolationMode.NEAREST,
    InterpolationMode.NEAREST_EXACT,
    InterpolationMode.BILINEAR,
    InterpolationMode.BICUBIC,
)
30
31


32
33
34
35
36
37
def _test_transform_vs_scripted(transform, s_transform, tensor, msg=None):
    torch.manual_seed(12)
    out1 = transform(tensor)
    torch.manual_seed(12)
    out2 = s_transform(tensor)
    assert_equal(out1, out2, msg=msg)
38

39

40
41
42
def _test_transform_vs_scripted_on_batch(transform, s_transform, batch_tensors, msg=None):
    torch.manual_seed(12)
    transformed_batch = transform(batch_tensors)
43

44
45
    for i in range(len(batch_tensors)):
        img_tensor = batch_tensors[i, ...]
46
        torch.manual_seed(12)
47
48
        transformed_img = transform(img_tensor)
        assert_equal(transformed_img, transformed_batch[i, ...], msg=msg)
49

50
51
52
    torch.manual_seed(12)
    s_transformed_batch = s_transform(batch_tensors)
    assert_equal(transformed_batch, s_transformed_batch, msg=msg)
53
54


55
def _test_functional_op(f, device, channels=3, fn_kwargs=None, test_exact_match=True, **match_kwargs):
56
    fn_kwargs = fn_kwargs or {}
57

58
    tensor, pil_img = _create_data(height=10, width=10, channels=channels, device=device)
59
60
61
62
63
64
    transformed_tensor = f(tensor, **fn_kwargs)
    transformed_pil_img = f(pil_img, **fn_kwargs)
    if test_exact_match:
        _assert_equal_tensor_to_pil(transformed_tensor, transformed_pil_img, **match_kwargs)
    else:
        _assert_approx_equal_tensor_to_pil(transformed_tensor, transformed_pil_img, **match_kwargs)
vfdev's avatar
vfdev committed
65
66


vfdev's avatar
vfdev committed
67
def _test_class_op(transform_cls, device, channels=3, meth_kwargs=None, test_exact_match=True, **match_kwargs):
68
    meth_kwargs = meth_kwargs or {}
69

70
    # test for class interface
vfdev's avatar
vfdev committed
71
    f = transform_cls(**meth_kwargs)
72
    scripted_fn = torch.jit.script(f)
73

74
    tensor, pil_img = _create_data(26, 34, channels, device=device)
75
76
77
78
79
80
81
82
83
    # set seed to reproduce the same transformation for tensor and PIL image
    torch.manual_seed(12)
    transformed_tensor = f(tensor)
    torch.manual_seed(12)
    transformed_pil_img = f(pil_img)
    if test_exact_match:
        _assert_equal_tensor_to_pil(transformed_tensor, transformed_pil_img, **match_kwargs)
    else:
        _assert_approx_equal_tensor_to_pil(transformed_tensor.float(), transformed_pil_img, **match_kwargs)
84

85
86
87
88
    torch.manual_seed(12)
    transformed_tensor_script = scripted_fn(tensor)
    assert_equal(transformed_tensor, transformed_tensor_script)

89
    batch_tensors = _create_data_batch(height=23, width=34, channels=channels, num_samples=4, device=device)
90
91
92
    _test_transform_vs_scripted_on_batch(f, scripted_fn, batch_tensors)

    with get_tmp_dir() as tmp_dir:
vfdev's avatar
vfdev committed
93
        scripted_fn.save(os.path.join(tmp_dir, f"t_{transform_cls.__name__}.pt"))
94

95

96
97
98
def _test_op(func, method, device, channels=3, fn_kwargs=None, meth_kwargs=None, test_exact_match=True, **match_kwargs):
    _test_functional_op(func, device, channels, fn_kwargs, test_exact_match=test_exact_match, **match_kwargs)
    _test_class_op(method, device, channels, meth_kwargs, test_exact_match=test_exact_match, **match_kwargs)
99
100


101
102
def _test_fn_save_load(fn, tmpdir):
    scripted_fn = torch.jit.script(fn)
103
    p = os.path.join(tmpdir, f"t_op_list_{getattr(fn, '__name__', fn.__class__.__name__)}.pt")
104
105
106
107
    scripted_fn.save(p)
    _ = torch.jit.load(p)


108
@pytest.mark.parametrize("device", cpu_and_cuda())
109
@pytest.mark.parametrize(
110
111
    "func,method,fn_kwargs,match_kwargs",
    [
112
113
114
115
116
117
        (F.hflip, T.RandomHorizontalFlip, None, {}),
        (F.vflip, T.RandomVerticalFlip, None, {}),
        (F.invert, T.RandomInvert, None, {}),
        (F.posterize, T.RandomPosterize, {"bits": 4}, {}),
        (F.solarize, T.RandomSolarize, {"threshold": 192.0}, {}),
        (F.adjust_sharpness, T.RandomAdjustSharpness, {"sharpness_factor": 2.0}, {}),
118
119
120
121
122
123
124
125
        (
            F.autocontrast,
            T.RandomAutocontrast,
            None,
            {"test_exact_match": False, "agg_method": "max", "tol": (1 + 1e-5), "allowed_percentage_diff": 0.05},
        ),
        (F.equalize, T.RandomEqualize, None, {}),
    ],
126
)
127
@pytest.mark.parametrize("channels", [1, 3])
128
129
def test_random(func, method, device, channels, fn_kwargs, match_kwargs):
    _test_op(func, method, device, channels, fn_kwargs, fn_kwargs, **match_kwargs)
130

131

132
@pytest.mark.parametrize("seed", range(10))
133
@pytest.mark.parametrize("device", cpu_and_cuda())
134
@pytest.mark.parametrize("channels", [1, 3])
135
class TestColorJitter:
136
137
138
139
    @pytest.fixture(autouse=True)
    def set_random_seed(self, seed):
        torch.random.manual_seed(seed)

140
    @pytest.mark.parametrize("brightness", [0.1, 0.5, 1.0, 1.34, (0.3, 0.7), [0.4, 0.5]])
141
    def test_color_jitter_brightness(self, brightness, device, channels):
142
143
144
        tol = 1.0 + 1e-10
        meth_kwargs = {"brightness": brightness}
        _test_class_op(
145
146
147
148
149
150
151
            T.ColorJitter,
            meth_kwargs=meth_kwargs,
            test_exact_match=False,
            device=device,
            tol=tol,
            agg_method="max",
            channels=channels,
152
153
        )

154
    @pytest.mark.parametrize("contrast", [0.2, 0.5, 1.0, 1.5, (0.3, 0.7), [0.4, 0.5]])
155
    def test_color_jitter_contrast(self, contrast, device, channels):
156
157
158
        tol = 1.0 + 1e-10
        meth_kwargs = {"contrast": contrast}
        _test_class_op(
159
160
161
162
163
164
165
            T.ColorJitter,
            meth_kwargs=meth_kwargs,
            test_exact_match=False,
            device=device,
            tol=tol,
            agg_method="max",
            channels=channels,
166
167
        )

168
    @pytest.mark.parametrize("saturation", [0.5, 0.75, 1.0, 1.25, (0.3, 0.7), [0.3, 0.4]])
169
    def test_color_jitter_saturation(self, saturation, device, channels):
170
171
172
        tol = 1.0 + 1e-10
        meth_kwargs = {"saturation": saturation}
        _test_class_op(
173
174
175
176
177
178
179
            T.ColorJitter,
            meth_kwargs=meth_kwargs,
            test_exact_match=False,
            device=device,
            tol=tol,
            agg_method="max",
            channels=channels,
180
181
        )

182
    @pytest.mark.parametrize("hue", [0.2, 0.5, (-0.2, 0.3), [-0.4, 0.5]])
183
    def test_color_jitter_hue(self, hue, device, channels):
184
185
        meth_kwargs = {"hue": hue}
        _test_class_op(
186
187
188
189
190
191
192
            T.ColorJitter,
            meth_kwargs=meth_kwargs,
            test_exact_match=False,
            device=device,
            tol=16.1,
            agg_method="max",
            channels=channels,
193
194
        )

195
    def test_color_jitter_all(self, device, channels):
196
197
198
        # All 4 parameters together
        meth_kwargs = {"brightness": 0.2, "contrast": 0.2, "saturation": 0.2, "hue": 0.2}
        _test_class_op(
199
200
201
202
203
204
205
            T.ColorJitter,
            meth_kwargs=meth_kwargs,
            test_exact_match=False,
            device=device,
            tol=12.1,
            agg_method="max",
            channels=channels,
206
207
208
        )


209
@pytest.mark.parametrize("device", cpu_and_cuda())
210
211
@pytest.mark.parametrize("m", ["constant", "edge", "reflect", "symmetric"])
@pytest.mark.parametrize("mul", [1, -1])
212
213
214
215
def test_pad(m, mul, device):
    fill = 127 if m == "constant" else 0

    # Test functional.pad (PIL and Tensor) with padding as single int
216
    _test_functional_op(F.pad, fn_kwargs={"padding": mul * 2, "fill": fill, "padding_mode": m}, device=device)
217
    # Test functional.pad and transforms.Pad with padding as [int, ]
218
    fn_kwargs = meth_kwargs = {
219
        "padding": [mul * 2],
220
221
222
223
        "fill": fill,
        "padding_mode": m,
    }
    _test_op(F.pad, T.Pad, device=device, fn_kwargs=fn_kwargs, meth_kwargs=meth_kwargs)
224
225
    # Test functional.pad and transforms.Pad with padding as list
    fn_kwargs = meth_kwargs = {"padding": [mul * 4, 4], "fill": fill, "padding_mode": m}
226
    _test_op(F.pad, T.Pad, device=device, fn_kwargs=fn_kwargs, meth_kwargs=meth_kwargs)
227
228
    # Test functional.pad and transforms.Pad with padding as tuple
    fn_kwargs = meth_kwargs = {"padding": (mul * 2, 2, 2, mul * 2), "fill": fill, "padding_mode": m}
229
    _test_op(F.pad, T.Pad, device=device, fn_kwargs=fn_kwargs, meth_kwargs=meth_kwargs)
230
231


232
@pytest.mark.parametrize("device", cpu_and_cuda())
233
234
235
def test_crop(device):
    fn_kwargs = {"top": 2, "left": 3, "height": 4, "width": 5}
    # Test transforms.RandomCrop with size and padding as tuple
236
237
238
239
240
241
    meth_kwargs = {
        "size": (4, 5),
        "padding": (4, 4),
        "pad_if_needed": True,
    }
    _test_op(F.crop, T.RandomCrop, device=device, fn_kwargs=fn_kwargs, meth_kwargs=meth_kwargs)
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259

    # Test transforms.functional.crop including outside the image area
    fn_kwargs = {"top": -2, "left": 3, "height": 4, "width": 5}  # top
    _test_functional_op(F.crop, fn_kwargs=fn_kwargs, device=device)

    fn_kwargs = {"top": 1, "left": -3, "height": 4, "width": 5}  # left
    _test_functional_op(F.crop, fn_kwargs=fn_kwargs, device=device)

    fn_kwargs = {"top": 7, "left": 3, "height": 4, "width": 5}  # bottom
    _test_functional_op(F.crop, fn_kwargs=fn_kwargs, device=device)

    fn_kwargs = {"top": 3, "left": 8, "height": 4, "width": 5}  # right
    _test_functional_op(F.crop, fn_kwargs=fn_kwargs, device=device)

    fn_kwargs = {"top": -3, "left": -3, "height": 15, "width": 15}  # all
    _test_functional_op(F.crop, fn_kwargs=fn_kwargs, device=device)


260
@pytest.mark.parametrize("device", cpu_and_cuda())
261
262
263
264
265
266
267
268
269
@pytest.mark.parametrize(
    "padding_config",
    [
        {"padding_mode": "constant", "fill": 0},
        {"padding_mode": "constant", "fill": 10},
        {"padding_mode": "edge"},
        {"padding_mode": "reflect"},
    ],
)
270
271
272
273
@pytest.mark.parametrize("pad_if_needed", [True, False])
@pytest.mark.parametrize("padding", [[5], [5, 4], [1, 2, 3, 4]])
@pytest.mark.parametrize("size", [5, [5], [6, 6]])
def test_random_crop(size, padding, pad_if_needed, padding_config, device):
274
275
    config = dict(padding_config)
    config["size"] = size
276
277
    config["padding"] = padding
    config["pad_if_needed"] = pad_if_needed
278
    _test_class_op(T.RandomCrop, device, meth_kwargs=config)
279
280


281
282
283
284
285
def test_random_crop_save_load(tmpdir):
    fn = T.RandomCrop(32, [4], pad_if_needed=True)
    _test_fn_save_load(fn, tmpdir)


286
@pytest.mark.parametrize("device", cpu_and_cuda())
287
def test_center_crop(device, tmpdir):
288
    fn_kwargs = {"output_size": (4, 5)}
289
    meth_kwargs = {"size": (4, 5)}
290
    _test_op(F.center_crop, T.CenterCrop, device=device, fn_kwargs=fn_kwargs, meth_kwargs=meth_kwargs)
291
    fn_kwargs = {"output_size": (5,)}
292
    meth_kwargs = {"size": (5,)}
293
    _test_op(F.center_crop, T.CenterCrop, device=device, fn_kwargs=fn_kwargs, meth_kwargs=meth_kwargs)
294
295
296
297
298
299
300
    tensor = torch.randint(0, 256, (3, 10, 10), dtype=torch.uint8, device=device)
    # Test torchscript of transforms.CenterCrop with size as int
    f = T.CenterCrop(size=5)
    scripted_fn = torch.jit.script(f)
    scripted_fn(tensor)

    # Test torchscript of transforms.CenterCrop with size as [int, ]
301
    f = T.CenterCrop(size=[5])
302
303
304
305
306
307
308
309
    scripted_fn = torch.jit.script(f)
    scripted_fn(tensor)

    # Test torchscript of transforms.CenterCrop with size as tuple
    f = T.CenterCrop(size=(6, 6))
    scripted_fn = torch.jit.script(f)
    scripted_fn(tensor)

310
311
312
313

def test_center_crop_save_load(tmpdir):
    fn = T.CenterCrop(size=[5])
    _test_fn_save_load(fn, tmpdir)
314
315


316
@pytest.mark.parametrize("device", cpu_and_cuda())
317
318
319
320
321
322
323
324
325
@pytest.mark.parametrize(
    "fn, method, out_length",
    [
        # test_five_crop
        (F.five_crop, T.FiveCrop, 5),
        # test_ten_crop
        (F.ten_crop, T.TenCrop, 10),
    ],
)
326
@pytest.mark.parametrize("size", [(5,), [5], (4, 5), [4, 5]])
327
def test_x_crop(fn, method, out_length, size, device):
328
    meth_kwargs = fn_kwargs = {"size": size}
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
    scripted_fn = torch.jit.script(fn)

    tensor, pil_img = _create_data(height=20, width=20, device=device)
    transformed_t_list = fn(tensor, **fn_kwargs)
    transformed_p_list = fn(pil_img, **fn_kwargs)
    assert len(transformed_t_list) == len(transformed_p_list)
    assert len(transformed_t_list) == out_length
    for transformed_tensor, transformed_pil_img in zip(transformed_t_list, transformed_p_list):
        _assert_equal_tensor_to_pil(transformed_tensor, transformed_pil_img)

    transformed_t_list_script = scripted_fn(tensor.detach().clone(), **fn_kwargs)
    assert len(transformed_t_list) == len(transformed_t_list_script)
    assert len(transformed_t_list_script) == out_length
    for transformed_tensor, transformed_tensor_script in zip(transformed_t_list, transformed_t_list_script):
        assert_equal(transformed_tensor, transformed_tensor_script)

    # test for class interface
    fn = method(**meth_kwargs)
    scripted_fn = torch.jit.script(fn)
    output = scripted_fn(tensor)
    assert len(output) == len(transformed_t_list_script)

    # test on batch of tensors
    batch_tensors = _create_data_batch(height=23, width=34, channels=3, num_samples=4, device=device)
    torch.manual_seed(12)
    transformed_batch_list = fn(batch_tensors)

    for i in range(len(batch_tensors)):
        img_tensor = batch_tensors[i, ...]
        torch.manual_seed(12)
        transformed_img_list = fn(img_tensor)
        for transformed_img, transformed_batch in zip(transformed_img_list, transformed_batch_list):
            assert_equal(transformed_img, transformed_batch[i, ...])


364
@pytest.mark.parametrize("method", ["FiveCrop", "TenCrop"])
365
366
367
def test_x_crop_save_load(method, tmpdir):
    fn = getattr(T, method)(size=[5])
    _test_fn_save_load(fn, tmpdir)
368
369
370


class TestResize:
371
    @pytest.mark.parametrize("size", [32, 34, 35, 36, 38])
372
373
374
    def test_resize_int(self, size):
        # TODO: Minimal check for bug-fix, improve this later
        x = torch.rand(3, 32, 46)
375
        t = T.Resize(size=size, antialias=True)
376
377
378
379
380
381
382
        y = t(x)
        # If size is an int, smaller edge of the image will be matched to this number.
        # i.e, if height > width, then image will be rescaled to (size * height / width, size).
        assert isinstance(y, torch.Tensor)
        assert y.shape[1] == size
        assert y.shape[2] == int(size * 46 / 32)

383
    @pytest.mark.parametrize("device", cpu_and_cuda())
384
    @pytest.mark.parametrize("dt", [None, torch.float32, torch.float64])
385
    @pytest.mark.parametrize("size", [[32], [32, 32], (32, 32), [34, 35]])
386
    @pytest.mark.parametrize("max_size", [None, 35, 1000])
387
    @pytest.mark.parametrize("interpolation", [BILINEAR, BICUBIC, NEAREST, NEAREST_EXACT])
388
389
390
391
392
393
394
395
    def test_resize_scripted(self, dt, size, max_size, interpolation, device):
        tensor, _ = _create_data(height=34, width=36, device=device)
        batch_tensors = torch.randint(0, 256, size=(4, 3, 44, 56), dtype=torch.uint8, device=device)

        if dt is not None:
            # This is a trivial cast to float of uint8 data to test all cases
            tensor = tensor.to(dt)
        if max_size is not None and len(size) != 1:
396
            pytest.skip("Size should be an int or a sequence of length 1 if max_size is specified")
397

398
        transform = T.Resize(size=size, interpolation=interpolation, max_size=max_size, antialias=True)
399
400
401
402
        s_transform = torch.jit.script(transform)
        _test_transform_vs_scripted(transform, s_transform, tensor)
        _test_transform_vs_scripted_on_batch(transform, s_transform, batch_tensors)

403
    def test_resize_save_load(self, tmpdir):
404
        fn = T.Resize(size=[32], antialias=True)
405
        _test_fn_save_load(fn, tmpdir)
406

407
    @pytest.mark.parametrize("device", cpu_and_cuda())
408
409
    @pytest.mark.parametrize("scale", [(0.7, 1.2), [0.7, 1.2]])
    @pytest.mark.parametrize("ratio", [(0.75, 1.333), [0.75, 1.333]])
410
    @pytest.mark.parametrize("size", [(32,), [44], [32], [32, 32], (32, 32), [44, 55]])
411
    @pytest.mark.parametrize("interpolation", [NEAREST, BILINEAR, BICUBIC, NEAREST_EXACT])
412
413
414
    @pytest.mark.parametrize("antialias", [None, True, False])
    def test_resized_crop(self, scale, ratio, size, interpolation, antialias, device):

415
416
        if antialias and interpolation in {NEAREST, NEAREST_EXACT}:
            pytest.skip(f"Can not resize if interpolation mode is {interpolation} and antialias=True")
417

418
419
        tensor = torch.randint(0, 256, size=(3, 44, 56), dtype=torch.uint8, device=device)
        batch_tensors = torch.randint(0, 256, size=(4, 3, 44, 56), dtype=torch.uint8, device=device)
420
421
422
        transform = T.RandomResizedCrop(
            size=size, scale=scale, ratio=ratio, interpolation=interpolation, antialias=antialias
        )
423
424
425
426
        s_transform = torch.jit.script(transform)
        _test_transform_vs_scripted(transform, s_transform, tensor)
        _test_transform_vs_scripted_on_batch(transform, s_transform, batch_tensors)

427
    def test_resized_crop_save_load(self, tmpdir):
428
        fn = T.RandomResizedCrop(size=[32], antialias=True)
429
        _test_fn_save_load(fn, tmpdir)
430

431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
    def test_antialias_default_warning(self):

        img = torch.randint(0, 256, size=(3, 44, 56), dtype=torch.uint8)

        match = "The default value of the antialias"
        with pytest.warns(UserWarning, match=match):
            T.Resize((20, 20))(img)
        with pytest.warns(UserWarning, match=match):
            T.RandomResizedCrop((20, 20))(img)

        # For modes that aren't bicubic or bilinear, don't throw a warning
        with warnings.catch_warnings():
            warnings.simplefilter("error")
            T.Resize((20, 20), interpolation=NEAREST)(img)
            T.RandomResizedCrop((20, 20), interpolation=NEAREST)(img)

447

448
449
450
451
452
453
454
455
456
457
def _test_random_affine_helper(device, **kwargs):
    tensor = torch.randint(0, 256, size=(3, 44, 56), dtype=torch.uint8, device=device)
    batch_tensors = torch.randint(0, 256, size=(4, 3, 44, 56), dtype=torch.uint8, device=device)
    transform = T.RandomAffine(**kwargs)
    s_transform = torch.jit.script(transform)

    _test_transform_vs_scripted(transform, s_transform, tensor)
    _test_transform_vs_scripted_on_batch(transform, s_transform, batch_tensors)


458
459
460
def test_random_affine_save_load(tmpdir):
    fn = T.RandomAffine(degrees=45.0)
    _test_fn_save_load(fn, tmpdir)
461
462


463
@pytest.mark.parametrize("device", cpu_and_cuda())
464
465
@pytest.mark.parametrize("interpolation", [NEAREST, BILINEAR])
@pytest.mark.parametrize("shear", [15, 10.0, (5.0, 10.0), [-15, 15], [-10.0, 10.0, -11.0, 11.0]])
466
467
468
469
def test_random_affine_shear(device, interpolation, shear):
    _test_random_affine_helper(device, degrees=0.0, interpolation=interpolation, shear=shear)


470
@pytest.mark.parametrize("device", cpu_and_cuda())
471
472
@pytest.mark.parametrize("interpolation", [NEAREST, BILINEAR])
@pytest.mark.parametrize("scale", [(0.7, 1.2), [0.7, 1.2]])
473
474
475
476
def test_random_affine_scale(device, interpolation, scale):
    _test_random_affine_helper(device, degrees=0.0, interpolation=interpolation, scale=scale)


477
@pytest.mark.parametrize("device", cpu_and_cuda())
478
479
@pytest.mark.parametrize("interpolation", [NEAREST, BILINEAR])
@pytest.mark.parametrize("translate", [(0.1, 0.2), [0.2, 0.1]])
480
481
482
483
def test_random_affine_translate(device, interpolation, translate):
    _test_random_affine_helper(device, degrees=0.0, interpolation=interpolation, translate=translate)


484
@pytest.mark.parametrize("device", cpu_and_cuda())
485
486
@pytest.mark.parametrize("interpolation", [NEAREST, BILINEAR])
@pytest.mark.parametrize("degrees", [45, 35.0, (-45, 45), [-90.0, 90.0]])
487
488
489
490
def test_random_affine_degrees(device, interpolation, degrees):
    _test_random_affine_helper(device, degrees=degrees, interpolation=interpolation)


491
@pytest.mark.parametrize("device", cpu_and_cuda())
492
@pytest.mark.parametrize("interpolation", [NEAREST, BILINEAR])
493
@pytest.mark.parametrize("fill", [85, (10, -10, 10), 0.7, [0.0, 0.0, 0.0], [1], 1])
494
495
496
497
def test_random_affine_fill(device, interpolation, fill):
    _test_random_affine_helper(device, degrees=0.0, interpolation=interpolation, fill=fill)


498
@pytest.mark.parametrize("device", cpu_and_cuda())
499
500
501
502
@pytest.mark.parametrize("center", [(0, 0), [10, 10], None, (56, 44)])
@pytest.mark.parametrize("expand", [True, False])
@pytest.mark.parametrize("degrees", [45, 35.0, (-45, 45), [-90.0, 90.0]])
@pytest.mark.parametrize("interpolation", [NEAREST, BILINEAR])
503
@pytest.mark.parametrize("fill", [85, (10, -10, 10), 0.7, [0.0, 0.0, 0.0], [1], 1])
504
505
506
507
def test_random_rotate(device, center, expand, degrees, interpolation, fill):
    tensor = torch.randint(0, 256, size=(3, 44, 56), dtype=torch.uint8, device=device)
    batch_tensors = torch.randint(0, 256, size=(4, 3, 44, 56), dtype=torch.uint8, device=device)

508
    transform = T.RandomRotation(degrees=degrees, interpolation=interpolation, expand=expand, center=center, fill=fill)
509
510
511
512
513
514
    s_transform = torch.jit.script(transform)

    _test_transform_vs_scripted(transform, s_transform, tensor)
    _test_transform_vs_scripted_on_batch(transform, s_transform, batch_tensors)


515
516
517
def test_random_rotate_save_load(tmpdir):
    fn = T.RandomRotation(degrees=45.0)
    _test_fn_save_load(fn, tmpdir)
518
519


520
@pytest.mark.parametrize("device", cpu_and_cuda())
521
522
@pytest.mark.parametrize("distortion_scale", np.linspace(0.1, 1.0, num=20))
@pytest.mark.parametrize("interpolation", [NEAREST, BILINEAR])
523
@pytest.mark.parametrize("fill", [85, (10, -10, 10), 0.7, [0.0, 0.0, 0.0], [1], 1])
524
525
526
527
def test_random_perspective(device, distortion_scale, interpolation, fill):
    tensor = torch.randint(0, 256, size=(3, 44, 56), dtype=torch.uint8, device=device)
    batch_tensors = torch.randint(0, 256, size=(4, 3, 44, 56), dtype=torch.uint8, device=device)

528
    transform = T.RandomPerspective(distortion_scale=distortion_scale, interpolation=interpolation, fill=fill)
529
530
531
532
533
534
    s_transform = torch.jit.script(transform)

    _test_transform_vs_scripted(transform, s_transform, tensor)
    _test_transform_vs_scripted_on_batch(transform, s_transform, batch_tensors)


535
536
537
def test_random_perspective_save_load(tmpdir):
    fn = T.RandomPerspective()
    _test_fn_save_load(fn, tmpdir)
538
539


540
@pytest.mark.parametrize("device", cpu_and_cuda())
541
542
543
544
@pytest.mark.parametrize(
    "Klass, meth_kwargs",
    [(T.Grayscale, {"num_output_channels": 1}), (T.Grayscale, {"num_output_channels": 3}), (T.RandomGrayscale, {})],
)
545
546
def test_to_grayscale(device, Klass, meth_kwargs):
    tol = 1.0 + 1e-10
547
    _test_class_op(Klass, meth_kwargs=meth_kwargs, test_exact_match=False, device=device, tol=tol, agg_method="max")
548
549


550
@pytest.mark.parametrize("device", cpu_and_cuda())
551
552
@pytest.mark.parametrize("in_dtype", int_dtypes() + float_dtypes())
@pytest.mark.parametrize("out_dtype", int_dtypes() + float_dtypes())
553
554
555
556
557
558
559
560
561
562
def test_convert_image_dtype(device, in_dtype, out_dtype):
    tensor, _ = _create_data(26, 34, device=device)
    batch_tensors = torch.rand(4, 3, 44, 56, device=device)

    in_tensor = tensor.to(in_dtype)
    in_batch_tensors = batch_tensors.to(in_dtype)

    fn = T.ConvertImageDtype(dtype=out_dtype)
    scripted_fn = torch.jit.script(fn)

563
564
565
    if (in_dtype == torch.float32 and out_dtype in (torch.int32, torch.int64)) or (
        in_dtype == torch.float64 and out_dtype == torch.int64
    ):
566
567
568
569
570
571
572
573
574
575
        with pytest.raises(RuntimeError, match=r"cannot be performed safely"):
            _test_transform_vs_scripted(fn, scripted_fn, in_tensor)
        with pytest.raises(RuntimeError, match=r"cannot be performed safely"):
            _test_transform_vs_scripted_on_batch(fn, scripted_fn, in_batch_tensors)
        return

    _test_transform_vs_scripted(fn, scripted_fn, in_tensor)
    _test_transform_vs_scripted_on_batch(fn, scripted_fn, in_batch_tensors)


576
def test_convert_image_dtype_save_load(tmpdir):
577
    fn = T.ConvertImageDtype(dtype=torch.uint8)
578
    _test_fn_save_load(fn, tmpdir)
579
580


581
@pytest.mark.parametrize("device", cpu_and_cuda())
582
@pytest.mark.parametrize("policy", [policy for policy in T.AutoAugmentPolicy])
583
@pytest.mark.parametrize("fill", [None, 85, (10, -10, 10), 0.7, [0.0, 0.0, 0.0], [1], 1])
584
585
586
587
588
589
590
591
592
593
594
def test_autoaugment(device, policy, fill):
    tensor = torch.randint(0, 256, size=(3, 44, 56), dtype=torch.uint8, device=device)
    batch_tensors = torch.randint(0, 256, size=(4, 3, 44, 56), dtype=torch.uint8, device=device)

    transform = T.AutoAugment(policy=policy, fill=fill)
    s_transform = torch.jit.script(transform)
    for _ in range(25):
        _test_transform_vs_scripted(transform, s_transform, tensor)
        _test_transform_vs_scripted_on_batch(transform, s_transform, batch_tensors)


595
@pytest.mark.parametrize("device", cpu_and_cuda())
596
597
@pytest.mark.parametrize("num_ops", [1, 2, 3])
@pytest.mark.parametrize("magnitude", [7, 9, 11])
598
@pytest.mark.parametrize("fill", [None, 85, (10, -10, 10), 0.7, [0.0, 0.0, 0.0], [1], 1])
599
600
601
602
603
604
605
606
607
608
609
def test_randaugment(device, num_ops, magnitude, fill):
    tensor = torch.randint(0, 256, size=(3, 44, 56), dtype=torch.uint8, device=device)
    batch_tensors = torch.randint(0, 256, size=(4, 3, 44, 56), dtype=torch.uint8, device=device)

    transform = T.RandAugment(num_ops=num_ops, magnitude=magnitude, fill=fill)
    s_transform = torch.jit.script(transform)
    for _ in range(25):
        _test_transform_vs_scripted(transform, s_transform, tensor)
        _test_transform_vs_scripted_on_batch(transform, s_transform, batch_tensors)


610
@pytest.mark.parametrize("device", cpu_and_cuda())
611
@pytest.mark.parametrize("fill", [None, 85, (10, -10, 10), 0.7, [0.0, 0.0, 0.0], [1], 1])
612
613
614
615
616
617
618
619
620
621
622
def test_trivialaugmentwide(device, fill):
    tensor = torch.randint(0, 256, size=(3, 44, 56), dtype=torch.uint8, device=device)
    batch_tensors = torch.randint(0, 256, size=(4, 3, 44, 56), dtype=torch.uint8, device=device)

    transform = T.TrivialAugmentWide(fill=fill)
    s_transform = torch.jit.script(transform)
    for _ in range(25):
        _test_transform_vs_scripted(transform, s_transform, tensor)
        _test_transform_vs_scripted_on_batch(transform, s_transform, batch_tensors)


623
@pytest.mark.parametrize("device", cpu_and_cuda())
624
@pytest.mark.parametrize("fill", [None, 85, (10, -10, 10), 0.7, [0.0, 0.0, 0.0], [1], 1])
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
def test_augmix(device, fill):
    tensor = torch.randint(0, 256, size=(3, 44, 56), dtype=torch.uint8, device=device)
    batch_tensors = torch.randint(0, 256, size=(4, 3, 44, 56), dtype=torch.uint8, device=device)

    class DeterministicAugMix(T.AugMix):
        def _sample_dirichlet(self, params: torch.Tensor) -> torch.Tensor:
            # patch the method to ensure that the order of rand calls doesn't affect the outcome
            return params.softmax(dim=-1)

    transform = DeterministicAugMix(fill=fill)
    s_transform = torch.jit.script(transform)
    for _ in range(25):
        _test_transform_vs_scripted(transform, s_transform, tensor)
        _test_transform_vs_scripted_on_batch(transform, s_transform, batch_tensors)


@pytest.mark.parametrize("augmentation", [T.AutoAugment, T.RandAugment, T.TrivialAugmentWide, T.AugMix])
642
643
644
def test_autoaugment_save_load(augmentation, tmpdir):
    fn = augmentation()
    _test_fn_save_load(fn, tmpdir)
645
646


647
648
649
650
651
652
653
654
655
656
657
658
659
@pytest.mark.parametrize("interpolation", [F.InterpolationMode.NEAREST, F.InterpolationMode.BILINEAR])
@pytest.mark.parametrize("mode", ["X", "Y"])
def test_autoaugment__op_apply_shear(interpolation, mode):
    # We check that torchvision's implementation of shear is equivalent
    # to official CIFAR10 autoaugment implementation:
    # https://github.com/tensorflow/models/blob/885fda091c46c59d6c7bb5c7e760935eacc229da/research/autoaugment/augmentation_transforms.py#L273-L290
    image_size = 32

    def shear(pil_img, level, mode, resample):
        if mode == "X":
            matrix = (1, level, 0, 0, 1, 0)
        elif mode == "Y":
            matrix = (1, 0, 0, level, 1, 0)
660
        return pil_img.transform((image_size, image_size), PIL.Image.AFFINE, matrix, resample=resample)
661
662
663
664

    t_img, pil_img = _create_data(image_size, image_size)

    resample_pil = {
665
666
        F.InterpolationMode.NEAREST: PIL.Image.NEAREST,
        F.InterpolationMode.BILINEAR: PIL.Image.BILINEAR,
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
    }[interpolation]

    level = 0.3
    expected_out = shear(pil_img, level, mode=mode, resample=resample_pil)

    # Check pil output vs expected pil
    out = _apply_op(pil_img, op_name=f"Shear{mode}", magnitude=level, interpolation=interpolation, fill=0)
    assert out == expected_out

    if interpolation == F.InterpolationMode.BILINEAR:
        # We skip bilinear mode for tensors as
        # affine transformation results are not exactly the same
        # between tensors and pil images
        # MAE as around 1.40
        # Max Abs error can be 163 or 170
        return

    # Check tensor output vs expected pil
    out = _apply_op(t_img, op_name=f"Shear{mode}", magnitude=level, interpolation=interpolation, fill=0)
    _assert_approx_equal_tensor_to_pil(out, expected_out)


689
@pytest.mark.parametrize("device", cpu_and_cuda())
690
@pytest.mark.parametrize(
691
    "config",
692
693
694
695
696
697
698
699
700
701
702
    [
        {},
        {"value": 1},
        {"value": 0.2},
        {"value": "random"},
        {"value": (1, 1, 1)},
        {"value": (0.2, 0.2, 0.2)},
        {"value": [1, 1, 1]},
        {"value": [0.2, 0.2, 0.2]},
        {"value": "random", "ratio": (0.1, 0.2)},
    ],
703
704
705
706
707
708
709
710
711
712
713
)
def test_random_erasing(device, config):
    tensor, _ = _create_data(24, 32, channels=3, device=device)
    batch_tensors = torch.rand(4, 3, 44, 56, device=device)

    fn = T.RandomErasing(**config)
    scripted_fn = torch.jit.script(fn)
    _test_transform_vs_scripted(fn, scripted_fn, tensor)
    _test_transform_vs_scripted_on_batch(fn, scripted_fn, batch_tensors)


714
def test_random_erasing_save_load(tmpdir):
715
    fn = T.RandomErasing(value=0.2)
716
    _test_fn_save_load(fn, tmpdir)
717
718
719
720
721
722
723
724
725
726


def test_random_erasing_with_invalid_data():
    img = torch.rand(3, 60, 60)
    # Test Set 0: invalid value
    random_erasing = T.RandomErasing(value=(0.1, 0.2, 0.3, 0.4), p=1.0)
    with pytest.raises(ValueError, match="If value is a sequence, it should have either a single value or 3"):
        random_erasing(img)


727
@pytest.mark.parametrize("device", cpu_and_cuda())
728
def test_normalize(device, tmpdir):
729
730
731
732
733
734
735
736
737
738
739
740
741
742
    fn = T.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
    tensor, _ = _create_data(26, 34, device=device)

    with pytest.raises(TypeError, match="Input tensor should be a float tensor"):
        fn(tensor)

    batch_tensors = torch.rand(4, 3, 44, 56, device=device)
    tensor = tensor.to(dtype=torch.float32) / 255.0
    # test for class interface
    scripted_fn = torch.jit.script(fn)

    _test_transform_vs_scripted(fn, scripted_fn, tensor)
    _test_transform_vs_scripted_on_batch(fn, scripted_fn, batch_tensors)

743
    scripted_fn.save(os.path.join(tmpdir, "t_norm.pt"))
744
745


746
@pytest.mark.parametrize("device", cpu_and_cuda())
747
def test_linear_transformation(device, tmpdir):
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
    c, h, w = 3, 24, 32

    tensor, _ = _create_data(h, w, channels=c, device=device)

    matrix = torch.rand(c * h * w, c * h * w, device=device)
    mean_vector = torch.rand(c * h * w, device=device)

    fn = T.LinearTransformation(matrix, mean_vector)
    scripted_fn = torch.jit.script(fn)

    _test_transform_vs_scripted(fn, scripted_fn, tensor)

    batch_tensors = torch.rand(4, c, h, w, device=device)
    # We skip some tests from _test_transform_vs_scripted_on_batch as
    # results for scripted and non-scripted transformations are not exactly the same
    torch.manual_seed(12)
    transformed_batch = fn(batch_tensors)
    torch.manual_seed(12)
    s_transformed_batch = scripted_fn(batch_tensors)
    assert_equal(transformed_batch, s_transformed_batch)

769
    scripted_fn.save(os.path.join(tmpdir, "t_norm.pt"))
770
771


772
@pytest.mark.parametrize("device", cpu_and_cuda())
773
774
775
def test_compose(device):
    tensor, _ = _create_data(26, 34, device=device)
    tensor = tensor.to(dtype=torch.float32) / 255.0
776
777
778
779
780
781
    transforms = T.Compose(
        [
            T.CenterCrop(10),
            T.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),
        ]
    )
782
783
784
785
786
787
788
    s_transforms = torch.nn.Sequential(*transforms.transforms)

    scripted_fn = torch.jit.script(s_transforms)
    torch.manual_seed(12)
    transformed_tensor = transforms(tensor)
    torch.manual_seed(12)
    transformed_tensor_script = scripted_fn(tensor)
789
    assert_equal(transformed_tensor, transformed_tensor_script, msg=f"{transforms}")
790

791
792
793
794
795
    t = T.Compose(
        [
            lambda x: x,
        ]
    )
796
    with pytest.raises(RuntimeError, match="cannot call a value of type 'Tensor'"):
797
798
799
        torch.jit.script(t)


800
@pytest.mark.parametrize("device", cpu_and_cuda())
801
802
803
804
def test_random_apply(device):
    tensor, _ = _create_data(26, 34, device=device)
    tensor = tensor.to(dtype=torch.float32) / 255.0

805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
    transforms = T.RandomApply(
        [
            T.RandomHorizontalFlip(),
            T.ColorJitter(),
        ],
        p=0.4,
    )
    s_transforms = T.RandomApply(
        torch.nn.ModuleList(
            [
                T.RandomHorizontalFlip(),
                T.ColorJitter(),
            ]
        ),
        p=0.4,
    )
821
822
823
824
825
826

    scripted_fn = torch.jit.script(s_transforms)
    torch.manual_seed(12)
    transformed_tensor = transforms(tensor)
    torch.manual_seed(12)
    transformed_tensor_script = scripted_fn(tensor)
827
    assert_equal(transformed_tensor, transformed_tensor_script, msg=f"{transforms}")
828
829
830
831

    if device == "cpu":
        # Can't check this twice, otherwise
        # "Can't redefine method: forward on class: __torch__.torchvision.transforms.transforms.RandomApply"
832
833
834
835
836
837
        transforms = T.RandomApply(
            [
                T.ColorJitter(),
            ],
            p=0.3,
        )
838
839
840
841
        with pytest.raises(RuntimeError, match="Module 'RandomApply' has no attribute 'transforms'"):
            torch.jit.script(transforms)


842
@pytest.mark.parametrize("device", cpu_and_cuda())
843
844
845
846
847
848
849
850
851
852
853
854
@pytest.mark.parametrize(
    "meth_kwargs",
    [
        {"kernel_size": 3, "sigma": 0.75},
        {"kernel_size": 23, "sigma": [0.1, 2.0]},
        {"kernel_size": 23, "sigma": (0.1, 2.0)},
        {"kernel_size": [3, 3], "sigma": (1.0, 1.0)},
        {"kernel_size": (3, 3), "sigma": (0.1, 2.0)},
        {"kernel_size": [23], "sigma": 0.75},
    ],
)
@pytest.mark.parametrize("channels", [1, 3])
855
def test_gaussian_blur(device, channels, meth_kwargs):
856
857
858
859
860
861
862
863
864
865
866
    if all(
        [
            device == "cuda",
            channels == 1,
            meth_kwargs["kernel_size"] in [23, [23]],
            torch.version.cuda == "11.3",
            sys.platform in ("win32", "cygwin"),
        ]
    ):
        pytest.skip("Fails on Windows, see https://github.com/pytorch/vision/issues/5464")

867
    tol = 1.0 + 1e-10
868
    torch.manual_seed(12)
869
    _test_class_op(
870
871
872
873
874
875
876
        T.GaussianBlur,
        meth_kwargs=meth_kwargs,
        channels=channels,
        test_exact_match=False,
        device=device,
        agg_method="max",
        tol=tol,
877
    )
878
879


880
@pytest.mark.parametrize("device", cpu_and_cuda())
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
@pytest.mark.parametrize(
    "fill",
    [
        1,
        1.0,
        [1],
        [1.0],
        (1,),
        (1.0,),
        [1, 2, 3],
        [1.0, 2.0, 3.0],
        (1, 2, 3),
        (1.0, 2.0, 3.0),
    ],
)
@pytest.mark.parametrize("channels", [1, 3])
def test_elastic_transform(device, channels, fill):
    if isinstance(fill, (list, tuple)) and len(fill) > 1 and channels == 1:
        # For this the test would correctly fail, since the number of channels in the image does not match `fill`.
        # Thus, this is not an issue in the transform, but rather a problem of parametrization that just gives the
        # product of `fill` and `channels`.
        return

    _test_class_op(
        T.ElasticTransform,
        meth_kwargs=dict(fill=fill),
        channels=channels,
        device=device,
    )