-
-
Notifications
You must be signed in to change notification settings - Fork 274
Expand file tree
/
Copy pathhub.py
More file actions
388 lines (323 loc) · 13.9 KB
/
Copy pathhub.py
File metadata and controls
388 lines (323 loc) · 13.9 KB
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
from os import path
import torch
import PIL
from nunif.utils import pil_io
from .model_dir import MODEL_DIR
from .download_models import main as download_main
from .utils import Waifu2x
MODEL_TYPES = {
# default models.
"art": path.join(MODEL_DIR, "swin_unet", "art"),
"art_scan": path.join(MODEL_DIR, "swin_unet", "art_scan"),
"photo": path.join(MODEL_DIR, "swin_unet", "photo"),
# arch
"swin_unet/art": path.join(MODEL_DIR, "swin_unet", "art"),
"swin_unet/art_scan": path.join(MODEL_DIR, "swin_unet", "art_scan"),
"swin_unet/photo": path.join(MODEL_DIR, "swin_unet", "photo"),
"cunet/art": path.join(MODEL_DIR, "cunet", "art"),
"upconv_7/art": path.join(MODEL_DIR, "upconv_7", "art"),
"upconv_7/photo": path.join(MODEL_DIR, "upconv_7", "photo"),
}
NO_4X_MODELS = {"cunet/art", "upconv_7/art", "upconv_7/photo"}
METHODS = [
"noise", "scale", "noise_scale",
"scale2x", "noise_scale2x",
"scale4x", "noise_scale4x"
]
class Waifu2xImageModel():
def __init__(self, model_type, method=None, noise_level=-1,
device_ids=[-1], tile_size=None, batch_size=None, keep_alpha=True, amp=True):
self.model_type = model_type
self.tile_size = tile_size
self.batch_size = batch_size
self.keep_alpha = keep_alpha
self.amp = amp
if model_type not in MODEL_TYPES:
raise ValueError(f"model_type: choose from {list(MODEL_TYPES.keys())}")
if method is not None and method not in METHODS:
raise ValueError(f"method: choose from {METHODS}")
if method is not None and method.startswith("noise") and noise_level not in {0, 1, 2, 3}:
raise ValueError("noise_level: choose from [0, 1, 2, 3]")
self.ctx = Waifu2x(MODEL_TYPES[model_type], device_ids)
if method is not None:
method = self.normalize_method(method, noise_level)
self.ctx.load_model(method, noise_level)
self.set_mode(method, noise_level)
else:
self.method = None
self.noise_level = None
self.ctx.load_model_all(load_4x=(model_type not in NO_4X_MODELS))
def set_mode(self, method, noise_level=-1):
method = self.normalize_method(method, noise_level)
if self.model_type in NO_4X_MODELS and method in {"scale4x", "noise_scale4x"}:
raise ValueError(f"method: {self.model_type} does not support {method}")
if (method in {"noise", "noise_scale4x", "noise_scale", "noise_scale2x"} and
noise_level not in {0, 1, 2, 3}):
raise ValueError("noise_level: choose from (0, 1, 2, 3)")
self.method = method
self.noise_level = noise_level
def compile(self):
self.ctx.compile()
return self
def to(self, device):
self.ctx = self.ctx.to(device)
return self
def cuda(self):
return self.to("cuda")
def cpu(self):
return self.to("cpu")
def half(self):
self.ctx.half()
return self
def float(self):
self.ctx.float()
return self
@property
def is_half(self):
return self.ctx.is_half
@property
def device(self):
return self.ctx.device
def convert(self, input_filepath, output_filepath, tta=False, format="png", **kwargs):
im, meta = pil_io.load_image(input_filepath, keep_alpha=self.keep_alpha)
new_im = self.infer_pil(im, tta=tta, **kwargs)
pil_io.save_image(new_im, output_filepath, meta=meta, format=format)
def infer_file(self, filepath, tta=False, output_type="pil", **kwargs):
im, meta = pil_io.load_image(filepath, keep_alpha=self.keep_alpha)
return self.infer_pil(im, tta=tta, output_type=output_type, **kwargs)
def infer_pil(self, pil_image, tta=False, output_type="pil", **kwargs):
if self.keep_alpha:
rgb, alpha = pil_io.to_tensor(pil_image, return_alpha=self.keep_alpha)
else:
rgb = pil_io.to_tensor(pil_image, return_alpha=self.keep_alpha)
alpha = None
rgb = rgb.to(self.device)
if self.is_half:
rgb = rgb.half()
if alpha is not None:
alpha = alpha.to(self.device)
if self.is_half:
alpha = alpha.half()
return self.infer_tensor(rgb, alpha, tta=tta, output_type=output_type, **kwargs)
def infer_tensor(self, rgb, alpha=None, tta=False, output_type="pil", **kwargs):
method = kwargs.get("method", self.method)
noise_level = kwargs.get("noise_level", self.noise_level)
if method is None:
raise ValueError(("method is None. Call `model.set_mode(method, noise_level)`"
" or use method and noise_level kwargs"))
with torch.inference_mode():
rgb, alpha = self.ctx.convert(
rgb, alpha, method, noise_level,
tile_size=self.tile_size, batch_size=self.batch_size,
tta=tta, enable_amp=self.amp)
if output_type == "tensor":
return (rgb, alpha)
else:
return pil_io.to_image(rgb, alpha)
def infer(self, x, tta=False, output_type="pil", **kwargs):
if isinstance(x, str):
return self.infer_file(x, tta=tta, output_type=output_type, **kwargs)
if isinstance(x, PIL.Image.Image):
return self.infer_pil(x, tta=tta, output_type=output_type, **kwargs)
elif torch.is_tensor(x):
return self.infer_tensor(x, tta=tta, output_type=output_type, **kwargs)
else:
raise ValueError("Unsupported input format")
def __call__(self, x, tta=False, output_type="pil", **kwargs):
return self.infer(x, tta=tta, output_type=output_type, **kwargs)
@staticmethod
def normalize_method(method, noise_level):
if method is None:
return None
if method == "scale2x":
method = "scale"
if method == "noise_scale2x":
method = "noise_scale"
if method == "scale" and noise_level >= 0:
method = "noise_scale"
if method == "scale4x" and noise_level >= 0:
method = "noise_scale4x"
return method
def waifu2x(model_type="art",
method=None, noise_level=-1,
device_ids=[-1], tile_size=None, batch_size=None, keep_alpha=True, amp=True,
**kwargs):
download_main()
return Waifu2xImageModel(
model_type=model_type,
method=method, noise_level=noise_level,
device_ids=device_ids, tile_size=tile_size, batch_size=batch_size,
keep_alpha=keep_alpha, amp=amp)
def _test():
import os
import argparse
import threading
ROOT_DIR = path.join(path.dirname(__file__), "..")
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--input", "-i", type=str, required=True,
help="input file")
parser.add_argument("--output", "-o", type=str, required=True,
help="output directory")
args = parser.parse_args()
os.makedirs(args.output, exist_ok=True)
im = PIL.Image.open(args.input)
# model_type
for model_type in MODEL_TYPES.keys():
for method in ("scale2x", "scale4x"):
if method == "scale4x" and model_type in NO_4X_MODELS:
continue
# Load a model with fixed method and noise_level
model = torch.hub.load(
ROOT_DIR, "waifu2x", keep_alpha=True,
model_type=model_type, method=method, noise_level=3,
source="local", trust_repo=True)
model = model.to("cuda")
out = model(im)
out.save(path.join(args.output, f"{model_type.replace('/', '-')}_{method}.png"))
# Load all method and noise_level models
lock = threading.RLock()
model = torch.hub.load(
ROOT_DIR, "waifu2x", keep_alpha=True,
model_type="art_scan",
source="local", trust_repo=True).to("cuda")
for noise_level in (0, 1, 2, 3):
with lock: # model.set_mode -> model.infer block is not thread-safe, so lock
# Select method and noise_level
model.set_mode("scale", noise_level)
out = model(im)
out.save(path.join(args.output, f"noise_scale_{noise_level}.png"))
for noise_level in (0, 1, 2, 3):
out = model(im, method="noise", noise_level=noise_level)
out.save(path.join(args.output, f"noise_{noise_level}.png"))
def _test_device_memory():
from time import time
ROOT_DIR = path.join(path.dirname(__file__), "..")
model = torch.hub.load(
ROOT_DIR, "waifu2x", model_type="art",
source="local", trust_repo=True)
# load model to gpu memory
t = time()
model = model.cuda()
print("* load", round(time() - t, 4))
print(torch.cuda.memory_summary())
# release gpu memory
t = time()
model = model.cpu()
torch.cuda.empty_cache()
print("* release", round(time() - t, 4))
print(torch.cuda.memory_summary())
# reload model to gpu memory
t = time()
model = model.cuda()
print("* reload", round(time() - t, 4))
print(torch.cuda.memory_summary())
def _test_tensor_input():
import argparse
import torchvision.transforms.functional as TF
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--input", "-i", type=str, required=True,
help="input file")
args = parser.parse_args()
im = PIL.Image.open(args.input)
x = TF.to_tensor(im)
ROOT_DIR = path.join(path.dirname(__file__), "..")
model = torch.hub.load(
ROOT_DIR, "waifu2x", model_type="art", method="scale", noise_level=3, amp=True,
source="local", trust_repo=True)
model = model.cuda()
gt = model.infer(x.cuda())
for device in ("cpu", "cuda"):
model = model.to(device)
for tensor in (x.cuda(), x.cpu(), x.half().cuda(), x.half().cpu()):
ret = model.infer(tensor.float().to(model.device))
mean_diff = (TF.to_tensor(gt) - TF.to_tensor(ret)).abs().mean()
print(model.device, tensor.dtype, tensor.device, mean_diff)
model = torch.hub.load(
ROOT_DIR, "waifu2x", model_type="art", method="scale", noise_level=3, amp=False,
source="local", trust_repo=True)
model = model.cuda().half()
for tensor in (x.cuda(), x.cuda().half()):
ret = model.infer(tensor.to(model.device).half())
mean_diff = (TF.to_tensor(gt) - TF.to_tensor(ret)).abs().mean()
print(model.device, tensor.dtype, tensor.device, mean_diff)
def _test_amp():
import argparse
from time import time
import torchvision.transforms.functional as TF
ROOT_DIR = path.join(path.dirname(__file__), "..")
LOOP_N = 10
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--input", "-i", type=str, required=True,
help="input file")
args = parser.parse_args()
im = PIL.Image.open(args.input)
# AMP=True
model = torch.hub.load(
ROOT_DIR, "waifu2x", model_type="art", method="scale", noise_level=3,
source="local", trust_repo=True).cuda()
t = time()
for i in range(LOOP_N):
amp_t_im = model(im)
print("amp=True", round((time() - t) / LOOP_N, 4), "sec / image")
# AMP=False
model = torch.hub.load(
ROOT_DIR, "waifu2x", model_type="art", method="scale", noise_level=3, amp=False,
source="local", trust_repo=True).cuda()
t = time()
for i in range(LOOP_N):
amp_f_im = model(im)
print("amp=False", round((time() - t) / LOOP_N, 4), "sec / image")
# AMP=False, manual setting float16
# NOTE: `torch.set_default_dtype(torch.float16)` does not work when `torch.hub.load`
if False:
torch.set_default_dtype(torch.float16)
model = model.half()
t = time()
for i in range(LOOP_N):
amp_f_half_im = model(im)
print("amp=False half()", round((time() - t) / LOOP_N, 4), "sec / image")
def image_diff(a, b):
return (TF.to_tensor(a) - TF.to_tensor(b)).abs().mean()
print("image_diff(amp=True, amp=False)", image_diff(amp_t_im, amp_f_im))
print("image_diff(amp=True, amp=False half())", image_diff(amp_t_im, amp_f_half_im))
def _test_half():
import argparse
import torchvision.transforms.functional as TF
ROOT_DIR = path.join(path.dirname(__file__), "..")
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--input", "-i", type=str, required=True,
help="input file")
args = parser.parse_args()
im = PIL.Image.open(args.input)
model = torch.hub.load(
ROOT_DIR, "waifu2x", model_type="art", method="scale", noise_level=3, amp=False,
source="local", trust_repo=True).cuda()
ret = model(im)
model = model.half()
ret_half = model(im)
print((TF.to_tensor(ret) - TF.to_tensor(ret_half)).abs().mean())
def _test_alias():
import argparse
import torchvision.transforms.functional as TF
ROOT_DIR = path.join(path.dirname(__file__), "..")
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--input", "-i", type=str, required=True,
help="input file")
args = parser.parse_args()
im = PIL.Image.open(args.input)
model1 = torch.hub.load(
ROOT_DIR, "waifu2x", model_type="art", method="scale", noise_level=3, amp=False,
source="local", trust_repo=True).cuda()
ret1 = model1(im)
model2 = torch.hub.load(
ROOT_DIR, "superresolution", model_type="art", method="scale", noise_level=3, amp=False,
source="local", trust_repo=True).cuda()
ret2 = model2(im)
print((TF.to_tensor(ret1) - TF.to_tensor(ret2)).abs().sum())
if __name__ == "__main__":
_test()
# _test_device_memory()
# _test_tensor_input()
# _test_amp()
# _test_half()
# _test_alias()