common_utils.py 6.57 KB
Newer Older
1
2
import contextlib
import functools
3
import os
4
import random
5
6
import shutil
import tempfile
7
from distutils.util import strtobool
8
9

import numpy as np
10
import pytest
eellison's avatar
eellison committed
11
import torch
12
from PIL import Image
13
from torchvision import io
14

15
import __main__  # noqa: 401
16

17

18
19
20
21
22
23
24
25
26
27
28
29
def get_bool_env_var(name, *, exist_ok=False, default=False):
    value = os.getenv(name)
    if value is None:
        return default
    if exist_ok:
        return True
    return bool(strtobool(value))


IN_CIRCLE_CI = get_bool_env_var("CIRCLECI")
IN_RE_WORKER = get_bool_env_var("INSIDE_RE_WORKER", exist_ok=True)
IN_FBCODE = get_bool_env_var("IN_FBCODE_TORCHVISION")
30
CUDA_NOT_AVAILABLE_MSG = "CUDA device not available"
31
CIRCLECI_GPU_NO_CUDA_MSG = "We're in a CircleCI GPU machine, and this test doesn't need cuda."
32

33
34
35
36
37
38
39
40
41
42
43

@contextlib.contextmanager
def get_tmp_dir(src=None, **kwargs):
    tmp_dir = tempfile.mkdtemp(**kwargs)
    if src is not None:
        os.rmdir(tmp_dir)
        shutil.copytree(src, tmp_dir)
    try:
        yield tmp_dir
    finally:
        shutil.rmtree(tmp_dir)
eellison's avatar
eellison committed
44
45


46
47
48
49
50
def set_rng_seed(seed):
    torch.manual_seed(seed)
    random.seed(seed)


51
class MapNestedTensorObjectImpl:
eellison's avatar
eellison committed
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
    def __init__(self, tensor_map_fn):
        self.tensor_map_fn = tensor_map_fn

    def __call__(self, object):
        if isinstance(object, torch.Tensor):
            return self.tensor_map_fn(object)

        elif isinstance(object, dict):
            mapped_dict = {}
            for key, value in object.items():
                mapped_dict[self(key)] = self(value)
            return mapped_dict

        elif isinstance(object, (list, tuple)):
            mapped_iter = []
            for iter in object:
                mapped_iter.append(self(iter))
            return mapped_iter if not isinstance(object, tuple) else tuple(mapped_iter)

        else:
            return object


def map_nested_tensor_object(object, tensor_map_fn):
    impl = MapNestedTensorObjectImpl(tensor_map_fn)
    return impl(object)


80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
def is_iterable(obj):
    try:
        iter(obj)
        return True
    except TypeError:
        return False


@contextlib.contextmanager
def freeze_rng_state():
    rng_state = torch.get_rng_state()
    if torch.cuda.is_available():
        cuda_rng_state = torch.cuda.get_rng_state()
    yield
    if torch.cuda.is_available():
        torch.cuda.set_rng_state(cuda_rng_state)
    torch.set_rng_state(rng_state)
97
98


99
def cycle_over(objs):
100
    for idx, obj1 in enumerate(objs):
101
        for obj2 in objs[:idx] + objs[idx + 1 :]:
102
            yield obj1, obj2
103
104
105


def int_dtypes():
106
    return (torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64)
107
108
109


def float_dtypes():
110
    return (torch.float32, torch.float64)
111
112
113
114
115
116
117
118


@contextlib.contextmanager
def disable_console_output():
    with contextlib.ExitStack() as stack, open(os.devnull, "w") as devnull:
        stack.enter_context(contextlib.redirect_stdout(devnull))
        stack.enter_context(contextlib.redirect_stderr(devnull))
        yield
119
120


121
122
def cpu_and_gpu():
    import pytest  # noqa
123
124

    return ("cpu", pytest.param("cuda", marks=pytest.mark.needs_cuda))
125
126
127
128


def needs_cuda(test_func):
    import pytest  # noqa
129

130
    return pytest.mark.needs_cuda(test_func)
Nicolas Hug's avatar
Nicolas Hug committed
131
132
133
134
135


def _create_data(height=3, width=3, channels=3, device="cpu"):
    # TODO: When all relevant tests are ported to pytest, turn this into a module-level fixture
    tensor = torch.randint(0, 256, (channels, height, width), dtype=torch.uint8, device=device)
136
137
138
139
140
141
    data = tensor.permute(1, 2, 0).contiguous().cpu().numpy()
    mode = "RGB"
    if channels == 1:
        mode = "L"
        data = data[..., 0]
    pil_img = Image.fromarray(data, mode=mode)
Nicolas Hug's avatar
Nicolas Hug committed
142
143
144
145
146
    return tensor, pil_img


def _create_data_batch(height=3, width=3, channels=3, num_samples=4, device="cpu"):
    # TODO: When all relevant tests are ported to pytest, turn this into a module-level fixture
147
    batch_tensor = torch.randint(0, 256, (num_samples, channels, height, width), dtype=torch.uint8, device=device)
Nicolas Hug's avatar
Nicolas Hug committed
148
149
150
    return batch_tensor


151
assert_equal = functools.partial(torch.testing.assert_close, rtol=0, atol=1e-6)
152
153


154
155
156
157
158
159
160
161
162
163
164
165
def get_list_of_videos(tmpdir, num_videos=5, sizes=None, fps=None):
    names = []
    for i in range(num_videos):
        if sizes is None:
            size = 5 * (i + 1)
        else:
            size = sizes[i]
        if fps is None:
            f = 5
        else:
            f = fps[i]
        data = torch.randint(0, 256, (size, 300, 400, 3), dtype=torch.uint8)
166
        name = os.path.join(tmpdir, f"{i}.mp4")
167
168
169
170
171
172
        names.append(name)
        io.write_video(name, data, fps=f)

    return names


Nicolas Hug's avatar
Nicolas Hug committed
173
174
175
176
177
178
def _assert_equal_tensor_to_pil(tensor, pil_image, msg=None):
    np_pil_image = np.array(pil_image)
    if np_pil_image.ndim == 2:
        np_pil_image = np_pil_image[:, :, None]
    pil_tensor = torch.as_tensor(np_pil_image.transpose((2, 0, 1)))
    if msg is None:
179
        msg = f"tensor:\n{tensor} \ndid not equal PIL tensor:\n{pil_tensor}"
180
    assert_equal(tensor.cpu(), pil_tensor, msg=msg)
Nicolas Hug's avatar
Nicolas Hug committed
181
182


183
184
185
def _assert_approx_equal_tensor_to_pil(
    tensor, pil_image, tol=1e-5, msg=None, agg_method="mean", allowed_percentage_diff=None
):
Nicolas Hug's avatar
Nicolas Hug committed
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
    # TODO: we could just merge this into _assert_equal_tensor_to_pil
    np_pil_image = np.array(pil_image)
    if np_pil_image.ndim == 2:
        np_pil_image = np_pil_image[:, :, None]
    pil_tensor = torch.as_tensor(np_pil_image.transpose((2, 0, 1))).to(tensor)

    if allowed_percentage_diff is not None:
        # Assert that less than a given %age of pixels are different
        assert (tensor != pil_tensor).to(torch.float).mean() <= allowed_percentage_diff

    # error value can be mean absolute error, max abs error
    # Convert to float to avoid underflow when computing absolute difference
    tensor = tensor.to(torch.float)
    pil_tensor = pil_tensor.to(torch.float)
    err = getattr(torch, agg_method)(torch.abs(tensor - pil_tensor)).item()
    assert err < tol


def _test_fn_on_batch(batch_tensors, fn, scripted_fn_atol=1e-8, **fn_kwargs):
    transformed_batch = fn(batch_tensors, **fn_kwargs)
    for i in range(len(batch_tensors)):
        img_tensor = batch_tensors[i, ...]
        transformed_img = fn(img_tensor, **fn_kwargs)
        assert_equal(transformed_img, transformed_batch[i, ...])

    if scripted_fn_atol >= 0:
        scripted_fn = torch.jit.script(fn)
        # scriptable function test
        s_transformed_batch = scripted_fn(batch_tensors, **fn_kwargs)
        torch.testing.assert_close(transformed_batch, s_transformed_batch, rtol=1e-5, atol=scripted_fn_atol)
216
217
218
219


def run_on_env_var(name, *, skip_reason=None, exist_ok=False, default=False):
    return pytest.mark.skipif(not get_bool_env_var(name, exist_ok=exist_ok, default=default), reason=skip_reason)