-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathverif_interp_bicubic.py
309 lines (254 loc) · 13.1 KB
/
verif_interp_bicubic.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
from pathlib import Path
import numpy as np
import PIL.Image
import torch
import torch.utils.benchmark as benchmark
import fire
def pth_downsample(img, mode, size, aa=True, ac=False):
align_corners = ac
if mode == "nearest":
align_corners = None
out = torch.nn.functional.interpolate(
img, size=size,
mode=mode,
align_corners=align_corners,
antialias=aa,
)
return out
def pth_downsample_force_float(img, mode, size, aa=True, ac=False):
align_corners = ac
if mode == "nearest":
align_corners = None
out = torch.nn.functional.interpolate(
img.float(), size=size,
mode=mode,
align_corners=align_corners,
antialias=aa,
)
if out.dtype in (torch.uint8, torch.int8, torch.int32, torch.long):
out = out.round().clamp(0, 255)
return out.to(img.dtype)
def store_expected(tensor, output, output_path, seed, mf, c, dtype, size, mode, osize, aa, ac, non_contig):
if not output_path.exists():
output_path.mkdir(parents=True)
bs = len(tensor)
filepath = output_path / f"{seed}_{bs}_{mf}_{c}_{dtype}_{size[0]}_{size[1]}_{mode}_{osize[0]}_{osize[1]}_{aa}_{ac}_{non_contig}.pt"
torch.save(
{"input": tensor, "output": output, "torch_version": torch.__version__},
filepath
)
def get_expected(tensor, output_path, seed, mf, c, dtype, size, mode, osize, aa, ac, non_contig):
bs = len(tensor)
filepath = output_path / f"{seed}_{bs}_{mf}_{c}_{dtype}_{size[0]}_{size[1]}_{mode}_{osize[0]}_{osize[1]}_{aa}_{ac}_{non_contig}.pt"
obj = torch.load(filepath)
inpt = obj["input"]
torch.testing.assert_close(inpt, tensor)
return obj["output"]
if not hasattr(PIL.Image, "Resampling"):
resampling_map = {
"bilinear": PIL.Image.BILINEAR,
"nearest": PIL.Image.NEAREST,
"bicubic": PIL.Image.BICUBIC,
}
else:
resampling_map = {
"bilinear": PIL.Image.Resampling.BILINEAR,
"nearest": PIL.Image.Resampling.NEAREST,
"bicubic": PIL.Image.Resampling.BICUBIC,
}
def test_consistency_or_record(
expected_pil, tensor, c, size, mf, dtype, mode, osize, aa, ac, is_ref, output_path, seed,
exact_match=True,
record_path={torch.float32: "native", torch.uint8: "native"},
non_contig=False,
):
# Tested op -> output
if is_ref:
if non_contig is not False:
assert tensor.ndim == 4, tensor.ndim
if mf == "channels_first":
tensor = tensor.contiguous()
elif mf == "channels_last":
tensor = tensor.contiguous(memory_format=torch.channels_last)
else:
raise RuntimeError(
"Unknown mf:", mf, " | ",
c, size, mf, dtype, mode, osize, aa, ac, is_ref, output_path, seed
)
# When there is no reference code, we can use float32 intermediate dtype
code_path = record_path.get(dtype, "force_float")
if code_path == "native":
print("take 'native' code path", end=" ")
output = pth_downsample(tensor, mode, osize, aa, ac)
elif code_path == "force_float":
print("take 'force_float' code path", end=" ")
output = pth_downsample_force_float(tensor, mode, osize, aa, ac)
else:
raise ValueError(f"Unknown value for record_path on {code_path}, record_path={record_path}")
else:
output = pth_downsample(tensor, mode, osize, aa, ac)
# Expected result:
if is_ref:
if output is not None:
print(" -> store output")
store_expected(tensor, output, output_path, seed, mf, c, dtype, size, mode, osize, aa, ac, non_contig)
else:
print("")
return
print(" -> get expected from file")
expected_ten = get_expected(tensor, output_path, seed, mf, c, dtype, size, mode, osize, aa, ac, non_contig)
print("---")
if not ac and expected_pil is not None:
abs_diff = torch.abs(expected_pil.float() - output.float())
mae = torch.mean(abs_diff)
max_abs_err = torch.max(abs_diff)
if mode == "bilinear":
assert mae.item() < 1.0, mae.item()
assert max_abs_err.item() < 1.0 + 1e-5, max_abs_err.item()
elif mode == "bicubic":
assert mae.item() < 1.0, mae.item()
assert max_abs_err.item() < 1.0 + 1e-5, max_abs_err.item()
else:
raise ValueError(f"Unknown mode '{mode}'")
expected_mf = torch.channels_last if expected_ten.is_contiguous(memory_format=torch.channels_last) else torch.contiguous_format
output_mf = torch.channels_last if output.is_contiguous(memory_format=torch.channels_last) else torch.contiguous_format
assert expected_mf == output_mf, (expected_mf, output_mf)
abs_diff = torch.abs(expected_ten.float() - output.float())
mae = torch.mean(abs_diff)
max_abs_err = torch.max(abs_diff)
if mode == "bilinear":
if exact_match:
torch.testing.assert_close(expected_ten, output)
else:
assert mae.item() < 1.0, mae.item()
max_abs_err_tol = 2.0
m = abs_diff > 1.5
assert max_abs_err.item() < max_abs_err_tol + 1e-5, \
(max_abs_err.item(), expected_ten.float()[m], output.float()[m])
elif mode == "bicubic":
if exact_match:
torch.testing.assert_close(expected_ten, output)
else:
assert mae.item() < 10.0, mae.item()
max_abs_err_tol = 2.0
m = abs_diff > 1.5
assert max_abs_err.item() < max_abs_err_tol + 1e-5, \
(max_abs_err.item(), expected_ten.float()[m], output.float()[m])
else:
raise ValueError(f"Unknown mode '{mode}'")
def main(output_path: str, is_ref: bool = False):
output_path = Path(output_path)
if is_ref and output_path.exists():
raise RuntimeError("Please provide non-exising folder if --is_ref flag is used")
# for batch_size in [1, 5]:
for batch_size in [1,]:
# for non_contig in [False, "sliced", "restrided"]:
for non_contig in [False, ]:
for ac in [True, False]:
for mf in ["channels_last", "channels_first", ]:
for c, dtype in [
(1, torch.uint8),
# (2, torch.uint8),
(3, torch.uint8),
(4, torch.uint8),
(5, torch.uint8),
# (1, torch.float32),
# (2, torch.float32),
# (3, torch.float32),
# (4, torch.float32),
# (5, torch.float32),
]:
for size in [256, (256, 299), (299, 321)]:
if isinstance(size, int):
size = [size, size]
if non_contig is not False:
if non_contig == "sliced":
size = [size[0] + 50, size[1] + 50]
elif non_contig == "restrided":
size = [size[0] * 2, size[1] * 2]
else:
raise ValueError("Unknown non_contig value '{non_contig}'")
minimal_osize_aa_mode_set = [
(32, True, "bicubic"),
(32, False, "bicubic"),
((35, 38), True, "bicubic"),
((35, 38), False, "bicubic"),
((323, 327), True, "bicubic"),
((323, 327), False, "bicubic"),
]
if not (batch_size > 1 or non_contig is not False):
minimal_osize_aa_mode_set += [
(224, True, "bicubic"),
(224, False, "bicubic"),
((227, 231), True, "bicubic"),
((227, 231), False, "bicubic"),
(320, True, "bicubic"),
(320, False, "bicubic"),
]
for osize, aa, mode in minimal_osize_aa_mode_set:
if isinstance(osize, int):
osize = [osize, osize + 1]
print("batch_size/non_contig/mf/size/dtype/c/osize/aa/mode/ac : ", batch_size, non_contig, mf, size, dtype, c, osize, aa, mode, ac, end=" ")
seed = 115
torch.manual_seed(seed)
if dtype == torch.bool:
tensor = torch.randint(0, 2, size=(c, size[0], size[1]), dtype=dtype)
elif dtype == torch.complex64:
real = torch.randint(0, 256, size=(c, size[0], size[1]), dtype=torch.float32)
imag = torch.randint(0, 256, size=(c, size[0], size[1]), dtype=torch.float32)
tensor = torch.complex(real, imag)
elif dtype == torch.int8:
tensor = torch.randint(-127, 127, size=(c, size[0], size[1]), dtype=dtype)
else:
tensor = torch.randint(0, 256, size=(c, size[0], size[1]), dtype=dtype)
if non_contig is not False:
if non_contig == "sliced":
tensor = tensor[:, 25:-25, 25:-25]
elif non_contig == "restrided":
tensor = tensor[:, ::2, ::2]
else:
raise ValueError("Unknown non_contig value '{non_contig}'")
expected_pil = None
if dtype == torch.uint8 and c == 3 and aa:
np_array = tensor.clone().permute(1, 2, 0).contiguous().numpy()
pil_img = PIL.Image.fromarray(np_array)
pil_img = pil_img.resize(osize[::-1], resample=resampling_map[mode])
expected_pil = torch.from_numpy(np.asarray(pil_img)).clone().permute(2, 0, 1).contiguous()
memory_format = torch.channels_last if mf == "channels_last" else torch.contiguous_format
if batch_size == 1:
tensor = tensor[None, ...].contiguous(memory_format=memory_format)
else:
new_shape = (batch_size, ) + tensor.shape
tensor = tensor[None, ...].expand(new_shape).contiguous(memory_format=memory_format)
print(".", end=" ")
record_path = {torch.float32: "native", torch.uint8: "force_float"}
test_consistency_or_record(
expected_pil, tensor, c, size, mf, dtype, mode, osize, aa, ac, is_ref, output_path, seed,
exact_match=False, non_contig=non_contig, record_path=record_path
)
if batch_size == 1:
# Check specifically squeeze/unsqueeze on batch dimension
# There is an inconsistency with interpolate on output mem format
# if input is unsqueezed 3D CL tensor, output is 4D CF tensor
tensor = tensor[0, ...]
tensor = tensor[None, ...]
print("..", end=" ")
# We override record_path as native code path for uint8 is buggy for nightly before
# https://github.com/pytorch/pytorch/pull/100258
record_path = {torch.float32: "native", torch.uint8: "force_float"}
test_consistency_or_record(
expected_pil, tensor, c, size, mf, dtype, mode, osize, aa, ac, is_ref, output_path / "sq_unsq", seed,
exact_match=False, record_path=record_path,
non_contig=non_contig
)
if __name__ == "__main__":
import os
if not ("OMP_NUM_THREADS" in os.environ):
torch.set_num_threads(1)
print("")
print(f"Torch version: {torch.__version__}")
print(f"Torch config: {torch.__config__.show()}")
print(f"Num threads: {torch.get_num_threads()}")
print("")
print("PIL version: ", PIL.__version__)
fire.Fire(main)