Spaces:
Runtime error
Runtime error
release training codes and config files.
Browse files- README.md +8 -6
- basicsr/archs/codeformer_arch.py +5 -1
- basicsr/data/data_util.py +87 -0
- basicsr/data/ffhq_blind_joint_dataset.py +327 -0
- basicsr/data/paired_image_dataset.py +101 -0
- basicsr/models/base_model.py +322 -0
- basicsr/models/codeformer_idx_model.py +216 -0
- basicsr/models/codeformer_joint_model.py +346 -0
- basicsr/models/codeformer_model.py +332 -0
- basicsr/models/sr_model.py +209 -0
- basicsr/models/vqgan_model.py +285 -0
- docs/history_changelog.md +1 -0
- docs/train.md +32 -0
- docs/train_CN.md +32 -0
- options/CodeFormer_colorization.yml +137 -0
- options/CodeFormer_inpainting.yml +151 -0
- options/CodeFormer_stage2.yml +137 -0
- options/CodeFormer_stage3.yml +164 -0
- options/VQGAN_512_ds32_nearest_stage1.yml +136 -0
- scripts/generate_latent_gt.py +67 -0
- scripts/inference_vqgan.py +59 -0
README.md
CHANGED
@@ -20,8 +20,9 @@ S-Lab, Nanyang Technological University
|
|
20 |
|
21 |
:star: If CodeFormer is helpful to your images or projects, please help star this repo. Thanks! :hugs:
|
22 |
|
23 |
-
|
24 |
### Update
|
|
|
25 |
- **2023.04.09**: Add features of inpainting and colorization for cropped and aligned face images.
|
26 |
- **2023.02.10**: Include `dlib` as a new face detector option, it produces more accurate face identity.
|
27 |
- **2022.10.05**: Support video input `--input_path [YOUR_VIDEO.mp4]`. Try it to enhance your videos! :clapper:
|
@@ -30,7 +31,7 @@ S-Lab, Nanyang Technological University
|
|
30 |
- [**More**](docs/history_changelog.md)
|
31 |
|
32 |
### TODO
|
33 |
-
- [
|
34 |
- [x] Add checkpoint and script for face inpainting
|
35 |
- [x] Add checkpoint and script for face colorization
|
36 |
- [x] ~~Add background image enhancement~~
|
@@ -77,13 +78,13 @@ conda install -c conda-forge dlib (only for face detection or cropping with dlib
|
|
77 |
### Quick Inference
|
78 |
|
79 |
#### Download Pre-trained Models:
|
80 |
-
Download the facelib and dlib pretrained models from [[Releases](https://github.com/sczhou/CodeFormer/releases) | [Google Drive](https://drive.google.com/drive/folders/1b_3qwrzY_kTQh0-SnBoGBgOrJ_PLZSKm?usp=sharing) | [OneDrive](https://entuedu-my.sharepoint.com/:f:/g/personal/s200094_e_ntu_edu_sg/EvDxR7FcAbZMp_MA9ouq7aQB8XTppMb3-T0uGZ_2anI2mg?e=DXsJFo)] to the `weights/facelib` folder. You can manually download the pretrained models OR download by running the following command:
|
81 |
```
|
82 |
python scripts/download_pretrained_models.py facelib
|
83 |
python scripts/download_pretrained_models.py dlib (only for dlib face detector)
|
84 |
```
|
85 |
|
86 |
-
Download the CodeFormer pretrained models from [[Releases](https://github.com/sczhou/CodeFormer/releases) | [Google Drive](https://drive.google.com/drive/folders/1CNNByjHDFt0b95q54yMVp6Ifo5iuU6QS?usp=sharing) | [OneDrive](https://entuedu-my.sharepoint.com/:f:/g/personal/s200094_e_ntu_edu_sg/EoKFj4wo8cdIn2-TY2IV6CYBhZ0pIG4kUOeHdPR_A5nlbg?e=AO8UN9)] to the `weights/CodeFormer` folder. You can manually download the pretrained models OR download by running the following command:
|
87 |
```
|
88 |
python scripts/download_pretrained_models.py CodeFormer
|
89 |
```
|
@@ -141,7 +142,8 @@ python inference_colorization.py --input_path [image folder]|[image path]
|
|
141 |
# (check out the examples in inputs/masked_faces)
|
142 |
python inference_inpainting.py --input_path [image folder]|[image path]
|
143 |
```
|
144 |
-
|
|
|
145 |
|
146 |
### Citation
|
147 |
If our work is useful for your research, please consider citing:
|
@@ -162,4 +164,4 @@ This project is licensed under <a rel="license" href="https://github.com/sczhou/
|
|
162 |
This project is based on [BasicSR](https://github.com/XPixelGroup/BasicSR). Some codes are brought from [Unleashing Transformers](https://github.com/samb-t/unleashing-transformers), [YOLOv5-face](https://github.com/deepcam-cn/yolov5-face), and [FaceXLib](https://github.com/xinntao/facexlib). We also adopt [Real-ESRGAN](https://github.com/xinntao/Real-ESRGAN) to support background image enhancement. Thanks for their awesome works.
|
163 |
|
164 |
### Contact
|
165 |
-
If you have any questions, please feel free to reach me out at `[email protected]`.
|
|
|
20 |
|
21 |
:star: If CodeFormer is helpful to your images or projects, please help star this repo. Thanks! :hugs:
|
22 |
|
23 |
+
|
24 |
### Update
|
25 |
+
- **2023.04.19**: :whale: Training codes and config files are public available now.
|
26 |
- **2023.04.09**: Add features of inpainting and colorization for cropped and aligned face images.
|
27 |
- **2023.02.10**: Include `dlib` as a new face detector option, it produces more accurate face identity.
|
28 |
- **2022.10.05**: Support video input `--input_path [YOUR_VIDEO.mp4]`. Try it to enhance your videos! :clapper:
|
|
|
31 |
- [**More**](docs/history_changelog.md)
|
32 |
|
33 |
### TODO
|
34 |
+
- [x] Add training code and config files
|
35 |
- [x] Add checkpoint and script for face inpainting
|
36 |
- [x] Add checkpoint and script for face colorization
|
37 |
- [x] ~~Add background image enhancement~~
|
|
|
78 |
### Quick Inference
|
79 |
|
80 |
#### Download Pre-trained Models:
|
81 |
+
Download the facelib and dlib pretrained models from [[Releases](https://github.com/sczhou/CodeFormer/releases/tag/v0.1.0) | [Google Drive](https://drive.google.com/drive/folders/1b_3qwrzY_kTQh0-SnBoGBgOrJ_PLZSKm?usp=sharing) | [OneDrive](https://entuedu-my.sharepoint.com/:f:/g/personal/s200094_e_ntu_edu_sg/EvDxR7FcAbZMp_MA9ouq7aQB8XTppMb3-T0uGZ_2anI2mg?e=DXsJFo)] to the `weights/facelib` folder. You can manually download the pretrained models OR download by running the following command:
|
82 |
```
|
83 |
python scripts/download_pretrained_models.py facelib
|
84 |
python scripts/download_pretrained_models.py dlib (only for dlib face detector)
|
85 |
```
|
86 |
|
87 |
+
Download the CodeFormer pretrained models from [[Releases](https://github.com/sczhou/CodeFormer/releases/tag/v0.1.0) | [Google Drive](https://drive.google.com/drive/folders/1CNNByjHDFt0b95q54yMVp6Ifo5iuU6QS?usp=sharing) | [OneDrive](https://entuedu-my.sharepoint.com/:f:/g/personal/s200094_e_ntu_edu_sg/EoKFj4wo8cdIn2-TY2IV6CYBhZ0pIG4kUOeHdPR_A5nlbg?e=AO8UN9)] to the `weights/CodeFormer` folder. You can manually download the pretrained models OR download by running the following command:
|
88 |
```
|
89 |
python scripts/download_pretrained_models.py CodeFormer
|
90 |
```
|
|
|
142 |
# (check out the examples in inputs/masked_faces)
|
143 |
python inference_inpainting.py --input_path [image folder]|[image path]
|
144 |
```
|
145 |
+
#### Training:
|
146 |
+
You can find training commands in training documents: [English](docs/train.md) **|** [简体中文](docs/train_CN.md).
|
147 |
|
148 |
### Citation
|
149 |
If our work is useful for your research, please consider citing:
|
|
|
164 |
This project is based on [BasicSR](https://github.com/XPixelGroup/BasicSR). Some codes are brought from [Unleashing Transformers](https://github.com/samb-t/unleashing-transformers), [YOLOv5-face](https://github.com/deepcam-cn/yolov5-face), and [FaceXLib](https://github.com/xinntao/facexlib). We also adopt [Real-ESRGAN](https://github.com/xinntao/Real-ESRGAN) to support background image enhancement. Thanks for their awesome works.
|
165 |
|
166 |
### Contact
|
167 |
+
If you have any questions, please feel free to reach me out at `[email protected]`.
|
basicsr/archs/codeformer_arch.py
CHANGED
@@ -162,9 +162,13 @@ class CodeFormer(VQAutoEncoder):
|
|
162 |
def __init__(self, dim_embd=512, n_head=8, n_layers=9,
|
163 |
codebook_size=1024, latent_size=256,
|
164 |
connect_list=['32', '64', '128', '256'],
|
165 |
-
fix_modules=['quantize','generator']):
|
166 |
super(CodeFormer, self).__init__(512, 64, [1, 2, 2, 4, 4, 8], 'nearest',2, [16], codebook_size)
|
167 |
|
|
|
|
|
|
|
|
|
168 |
if fix_modules is not None:
|
169 |
for module in fix_modules:
|
170 |
for param in getattr(self, module).parameters():
|
|
|
162 |
def __init__(self, dim_embd=512, n_head=8, n_layers=9,
|
163 |
codebook_size=1024, latent_size=256,
|
164 |
connect_list=['32', '64', '128', '256'],
|
165 |
+
fix_modules=['quantize','generator'], vqgan_path=None):
|
166 |
super(CodeFormer, self).__init__(512, 64, [1, 2, 2, 4, 4, 8], 'nearest',2, [16], codebook_size)
|
167 |
|
168 |
+
if vqgan_path is not None:
|
169 |
+
self.load_state_dict(
|
170 |
+
torch.load(vqgan_path, map_location='cpu')['params_ema'])
|
171 |
+
|
172 |
if fix_modules is not None:
|
173 |
for module in fix_modules:
|
174 |
for param in getattr(self, module).parameters():
|
basicsr/data/data_util.py
CHANGED
@@ -1,7 +1,9 @@
|
|
1 |
import cv2
|
|
|
2 |
import numpy as np
|
3 |
import torch
|
4 |
from os import path as osp
|
|
|
5 |
from torch.nn import functional as F
|
6 |
|
7 |
from basicsr.data.transforms import mod_crop
|
@@ -303,3 +305,88 @@ def duf_downsample(x, kernel_size=13, scale=4):
|
|
303 |
if squeeze_flag:
|
304 |
x = x.squeeze(0)
|
305 |
return x
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import cv2
|
2 |
+
import math
|
3 |
import numpy as np
|
4 |
import torch
|
5 |
from os import path as osp
|
6 |
+
from PIL import Image, ImageDraw
|
7 |
from torch.nn import functional as F
|
8 |
|
9 |
from basicsr.data.transforms import mod_crop
|
|
|
305 |
if squeeze_flag:
|
306 |
x = x.squeeze(0)
|
307 |
return x
|
308 |
+
|
309 |
+
|
310 |
+
def brush_stroke_mask(img, color=(255,255,255)):
|
311 |
+
min_num_vertex = 8
|
312 |
+
max_num_vertex = 28
|
313 |
+
mean_angle = 2*math.pi / 5
|
314 |
+
angle_range = 2*math.pi / 12
|
315 |
+
# training large mask ratio (training setting)
|
316 |
+
min_width = 30
|
317 |
+
max_width = 70
|
318 |
+
# very large mask ratio (test setting and refine after 200k)
|
319 |
+
# min_width = 80
|
320 |
+
# max_width = 120
|
321 |
+
def generate_mask(H, W, img=None):
|
322 |
+
average_radius = math.sqrt(H*H+W*W) / 8
|
323 |
+
mask = Image.new('RGB', (W, H), 0)
|
324 |
+
if img is not None: mask = img # Image.fromarray(img)
|
325 |
+
|
326 |
+
for _ in range(np.random.randint(1, 4)):
|
327 |
+
num_vertex = np.random.randint(min_num_vertex, max_num_vertex)
|
328 |
+
angle_min = mean_angle - np.random.uniform(0, angle_range)
|
329 |
+
angle_max = mean_angle + np.random.uniform(0, angle_range)
|
330 |
+
angles = []
|
331 |
+
vertex = []
|
332 |
+
for i in range(num_vertex):
|
333 |
+
if i % 2 == 0:
|
334 |
+
angles.append(2*math.pi - np.random.uniform(angle_min, angle_max))
|
335 |
+
else:
|
336 |
+
angles.append(np.random.uniform(angle_min, angle_max))
|
337 |
+
|
338 |
+
h, w = mask.size
|
339 |
+
vertex.append((int(np.random.randint(0, w)), int(np.random.randint(0, h))))
|
340 |
+
for i in range(num_vertex):
|
341 |
+
r = np.clip(
|
342 |
+
np.random.normal(loc=average_radius, scale=average_radius//2),
|
343 |
+
0, 2*average_radius)
|
344 |
+
new_x = np.clip(vertex[-1][0] + r * math.cos(angles[i]), 0, w)
|
345 |
+
new_y = np.clip(vertex[-1][1] + r * math.sin(angles[i]), 0, h)
|
346 |
+
vertex.append((int(new_x), int(new_y)))
|
347 |
+
|
348 |
+
draw = ImageDraw.Draw(mask)
|
349 |
+
width = int(np.random.uniform(min_width, max_width))
|
350 |
+
draw.line(vertex, fill=color, width=width)
|
351 |
+
for v in vertex:
|
352 |
+
draw.ellipse((v[0] - width//2,
|
353 |
+
v[1] - width//2,
|
354 |
+
v[0] + width//2,
|
355 |
+
v[1] + width//2),
|
356 |
+
fill=color)
|
357 |
+
|
358 |
+
return mask
|
359 |
+
|
360 |
+
width, height = img.size
|
361 |
+
mask = generate_mask(height, width, img)
|
362 |
+
return mask
|
363 |
+
|
364 |
+
|
365 |
+
def random_ff_mask(shape, max_angle = 10, max_len = 100, max_width = 70, times = 10):
|
366 |
+
"""Generate a random free form mask with configuration.
|
367 |
+
Args:
|
368 |
+
config: Config should have configuration including IMG_SHAPES,
|
369 |
+
VERTICAL_MARGIN, HEIGHT, HORIZONTAL_MARGIN, WIDTH.
|
370 |
+
Returns:
|
371 |
+
tuple: (top, left, height, width)
|
372 |
+
Link:
|
373 |
+
https://github.com/csqiangwen/DeepFillv2_Pytorch/blob/master/train_dataset.py
|
374 |
+
"""
|
375 |
+
height = shape[0]
|
376 |
+
width = shape[1]
|
377 |
+
mask = np.zeros((height, width), np.float32)
|
378 |
+
times = np.random.randint(times-5, times)
|
379 |
+
for i in range(times):
|
380 |
+
start_x = np.random.randint(width)
|
381 |
+
start_y = np.random.randint(height)
|
382 |
+
for j in range(1 + np.random.randint(5)):
|
383 |
+
angle = 0.01 + np.random.randint(max_angle)
|
384 |
+
if i % 2 == 0:
|
385 |
+
angle = 2 * 3.1415926 - angle
|
386 |
+
length = 10 + np.random.randint(max_len-20, max_len)
|
387 |
+
brush_w = 5 + np.random.randint(max_width-30, max_width)
|
388 |
+
end_x = (start_x + length * np.sin(angle)).astype(np.int32)
|
389 |
+
end_y = (start_y + length * np.cos(angle)).astype(np.int32)
|
390 |
+
cv2.line(mask, (start_y, start_x), (end_y, end_x), 1.0, brush_w)
|
391 |
+
start_x, start_y = end_x, end_y
|
392 |
+
return mask.astype(np.float32)
|
basicsr/data/ffhq_blind_joint_dataset.py
ADDED
@@ -0,0 +1,327 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import cv2
|
2 |
+
import math
|
3 |
+
import random
|
4 |
+
import numpy as np
|
5 |
+
import os.path as osp
|
6 |
+
from scipy.io import loadmat
|
7 |
+
from PIL import Image, ImageDraw
|
8 |
+
import torch
|
9 |
+
import torch.utils.data as data
|
10 |
+
from torchvision.transforms.functional import (adjust_brightness, adjust_contrast,
|
11 |
+
adjust_hue, adjust_saturation, normalize)
|
12 |
+
from basicsr.data import gaussian_kernels as gaussian_kernels
|
13 |
+
from basicsr.data.data_util import paths_from_folder
|
14 |
+
from basicsr.data.transforms import augment, img_rotate
|
15 |
+
from basicsr.metrics.psnr_ssim import calculate_psnr
|
16 |
+
from basicsr.utils import FileClient, get_root_logger, imfrombytes, img2tensor
|
17 |
+
from basicsr.utils.matlab_functions import imresize
|
18 |
+
from basicsr.utils.registry import DATASET_REGISTRY
|
19 |
+
|
20 |
+
@DATASET_REGISTRY.register()
|
21 |
+
class FFHQBlindJointDataset(data.Dataset):
|
22 |
+
|
23 |
+
def __init__(self, opt):
|
24 |
+
super(FFHQBlindJointDataset, self).__init__()
|
25 |
+
logger = get_root_logger()
|
26 |
+
self.opt = opt
|
27 |
+
# file client (io backend)
|
28 |
+
self.file_client = None
|
29 |
+
self.io_backend_opt = opt['io_backend']
|
30 |
+
|
31 |
+
self.gt_folder = opt['dataroot_gt']
|
32 |
+
self.gt_size = opt.get('gt_size', 512)
|
33 |
+
self.in_size = opt.get('in_size', 512)
|
34 |
+
assert self.gt_size >= self.in_size, 'Wrong setting.'
|
35 |
+
|
36 |
+
self.mean = opt.get('mean', [0.5, 0.5, 0.5])
|
37 |
+
self.std = opt.get('std', [0.5, 0.5, 0.5])
|
38 |
+
|
39 |
+
self.component_path = opt.get('component_path', None)
|
40 |
+
self.latent_gt_path = opt.get('latent_gt_path', None)
|
41 |
+
|
42 |
+
if self.component_path is not None:
|
43 |
+
self.crop_components = True
|
44 |
+
self.components_dict = torch.load(self.component_path)
|
45 |
+
self.eye_enlarge_ratio = opt.get('eye_enlarge_ratio', 1.4)
|
46 |
+
self.nose_enlarge_ratio = opt.get('nose_enlarge_ratio', 1.1)
|
47 |
+
self.mouth_enlarge_ratio = opt.get('mouth_enlarge_ratio', 1.3)
|
48 |
+
else:
|
49 |
+
self.crop_components = False
|
50 |
+
|
51 |
+
if self.latent_gt_path is not None:
|
52 |
+
self.load_latent_gt = True
|
53 |
+
self.latent_gt_dict = torch.load(self.latent_gt_path)
|
54 |
+
else:
|
55 |
+
self.load_latent_gt = False
|
56 |
+
|
57 |
+
if self.io_backend_opt['type'] == 'lmdb':
|
58 |
+
self.io_backend_opt['db_paths'] = self.gt_folder
|
59 |
+
if not self.gt_folder.endswith('.lmdb'):
|
60 |
+
raise ValueError("'dataroot_gt' should end with '.lmdb', "f'but received {self.gt_folder}')
|
61 |
+
with open(osp.join(self.gt_folder, 'meta_info.txt')) as fin:
|
62 |
+
self.paths = [line.split('.')[0] for line in fin]
|
63 |
+
else:
|
64 |
+
self.paths = paths_from_folder(self.gt_folder)
|
65 |
+
|
66 |
+
# perform corrupt
|
67 |
+
self.use_corrupt = opt.get('use_corrupt', True)
|
68 |
+
self.use_motion_kernel = False
|
69 |
+
# self.use_motion_kernel = opt.get('use_motion_kernel', True)
|
70 |
+
|
71 |
+
if self.use_motion_kernel:
|
72 |
+
self.motion_kernel_prob = opt.get('motion_kernel_prob', 0.001)
|
73 |
+
motion_kernel_path = opt.get('motion_kernel_path', 'basicsr/data/motion-blur-kernels-32.pth')
|
74 |
+
self.motion_kernels = torch.load(motion_kernel_path)
|
75 |
+
|
76 |
+
if self.use_corrupt:
|
77 |
+
# degradation configurations
|
78 |
+
self.blur_kernel_size = self.opt['blur_kernel_size']
|
79 |
+
self.kernel_list = self.opt['kernel_list']
|
80 |
+
self.kernel_prob = self.opt['kernel_prob']
|
81 |
+
# Small degradation
|
82 |
+
self.blur_sigma = self.opt['blur_sigma']
|
83 |
+
self.downsample_range = self.opt['downsample_range']
|
84 |
+
self.noise_range = self.opt['noise_range']
|
85 |
+
self.jpeg_range = self.opt['jpeg_range']
|
86 |
+
# Large degradation
|
87 |
+
self.blur_sigma_large = self.opt['blur_sigma_large']
|
88 |
+
self.downsample_range_large = self.opt['downsample_range_large']
|
89 |
+
self.noise_range_large = self.opt['noise_range_large']
|
90 |
+
self.jpeg_range_large = self.opt['jpeg_range_large']
|
91 |
+
|
92 |
+
# print
|
93 |
+
logger.info(f'Blur: blur_kernel_size {self.blur_kernel_size}, sigma: [{", ".join(map(str, self.blur_sigma))}]')
|
94 |
+
logger.info(f'Downsample: downsample_range [{", ".join(map(str, self.downsample_range))}]')
|
95 |
+
logger.info(f'Noise: [{", ".join(map(str, self.noise_range))}]')
|
96 |
+
logger.info(f'JPEG compression: [{", ".join(map(str, self.jpeg_range))}]')
|
97 |
+
|
98 |
+
# color jitter
|
99 |
+
self.color_jitter_prob = opt.get('color_jitter_prob', None)
|
100 |
+
self.color_jitter_pt_prob = opt.get('color_jitter_pt_prob', None)
|
101 |
+
self.color_jitter_shift = opt.get('color_jitter_shift', 20)
|
102 |
+
if self.color_jitter_prob is not None:
|
103 |
+
logger.info(f'Use random color jitter. Prob: {self.color_jitter_prob}, shift: {self.color_jitter_shift}')
|
104 |
+
|
105 |
+
# to gray
|
106 |
+
self.gray_prob = opt.get('gray_prob', 0.0)
|
107 |
+
if self.gray_prob is not None:
|
108 |
+
logger.info(f'Use random gray. Prob: {self.gray_prob}')
|
109 |
+
self.color_jitter_shift /= 255.
|
110 |
+
|
111 |
+
@staticmethod
|
112 |
+
def color_jitter(img, shift):
|
113 |
+
"""jitter color: randomly jitter the RGB values, in numpy formats"""
|
114 |
+
jitter_val = np.random.uniform(-shift, shift, 3).astype(np.float32)
|
115 |
+
img = img + jitter_val
|
116 |
+
img = np.clip(img, 0, 1)
|
117 |
+
return img
|
118 |
+
|
119 |
+
@staticmethod
|
120 |
+
def color_jitter_pt(img, brightness, contrast, saturation, hue):
|
121 |
+
"""jitter color: randomly jitter the brightness, contrast, saturation, and hue, in torch Tensor formats"""
|
122 |
+
fn_idx = torch.randperm(4)
|
123 |
+
for fn_id in fn_idx:
|
124 |
+
if fn_id == 0 and brightness is not None:
|
125 |
+
brightness_factor = torch.tensor(1.0).uniform_(brightness[0], brightness[1]).item()
|
126 |
+
img = adjust_brightness(img, brightness_factor)
|
127 |
+
|
128 |
+
if fn_id == 1 and contrast is not None:
|
129 |
+
contrast_factor = torch.tensor(1.0).uniform_(contrast[0], contrast[1]).item()
|
130 |
+
img = adjust_contrast(img, contrast_factor)
|
131 |
+
|
132 |
+
if fn_id == 2 and saturation is not None:
|
133 |
+
saturation_factor = torch.tensor(1.0).uniform_(saturation[0], saturation[1]).item()
|
134 |
+
img = adjust_saturation(img, saturation_factor)
|
135 |
+
|
136 |
+
if fn_id == 3 and hue is not None:
|
137 |
+
hue_factor = torch.tensor(1.0).uniform_(hue[0], hue[1]).item()
|
138 |
+
img = adjust_hue(img, hue_factor)
|
139 |
+
return img
|
140 |
+
|
141 |
+
|
142 |
+
def get_component_locations(self, name, status):
|
143 |
+
components_bbox = self.components_dict[name]
|
144 |
+
if status[0]: # hflip
|
145 |
+
# exchange right and left eye
|
146 |
+
tmp = components_bbox['left_eye']
|
147 |
+
components_bbox['left_eye'] = components_bbox['right_eye']
|
148 |
+
components_bbox['right_eye'] = tmp
|
149 |
+
# modify the width coordinate
|
150 |
+
components_bbox['left_eye'][0] = self.gt_size - components_bbox['left_eye'][0]
|
151 |
+
components_bbox['right_eye'][0] = self.gt_size - components_bbox['right_eye'][0]
|
152 |
+
components_bbox['nose'][0] = self.gt_size - components_bbox['nose'][0]
|
153 |
+
components_bbox['mouth'][0] = self.gt_size - components_bbox['mouth'][0]
|
154 |
+
|
155 |
+
locations_gt = {}
|
156 |
+
locations_in = {}
|
157 |
+
for part in ['left_eye', 'right_eye', 'nose', 'mouth']:
|
158 |
+
mean = components_bbox[part][0:2]
|
159 |
+
half_len = components_bbox[part][2]
|
160 |
+
if 'eye' in part:
|
161 |
+
half_len *= self.eye_enlarge_ratio
|
162 |
+
elif part == 'nose':
|
163 |
+
half_len *= self.nose_enlarge_ratio
|
164 |
+
elif part == 'mouth':
|
165 |
+
half_len *= self.mouth_enlarge_ratio
|
166 |
+
loc = np.hstack((mean - half_len + 1, mean + half_len))
|
167 |
+
loc = torch.from_numpy(loc).float()
|
168 |
+
locations_gt[part] = loc
|
169 |
+
loc_in = loc/(self.gt_size//self.in_size)
|
170 |
+
locations_in[part] = loc_in
|
171 |
+
return locations_gt, locations_in
|
172 |
+
|
173 |
+
|
174 |
+
def __getitem__(self, index):
|
175 |
+
if self.file_client is None:
|
176 |
+
self.file_client = FileClient(self.io_backend_opt.pop('type'), **self.io_backend_opt)
|
177 |
+
|
178 |
+
# load gt image
|
179 |
+
gt_path = self.paths[index]
|
180 |
+
name = osp.basename(gt_path)[:-4]
|
181 |
+
img_bytes = self.file_client.get(gt_path)
|
182 |
+
img_gt = imfrombytes(img_bytes, float32=True)
|
183 |
+
|
184 |
+
# random horizontal flip
|
185 |
+
img_gt, status = augment(img_gt, hflip=self.opt['use_hflip'], rotation=False, return_status=True)
|
186 |
+
|
187 |
+
if self.load_latent_gt:
|
188 |
+
if status[0]:
|
189 |
+
latent_gt = self.latent_gt_dict['hflip'][name]
|
190 |
+
else:
|
191 |
+
latent_gt = self.latent_gt_dict['orig'][name]
|
192 |
+
|
193 |
+
if self.crop_components:
|
194 |
+
locations_gt, locations_in = self.get_component_locations(name, status)
|
195 |
+
|
196 |
+
# generate in image
|
197 |
+
img_in = img_gt
|
198 |
+
if self.use_corrupt:
|
199 |
+
# motion blur
|
200 |
+
if self.use_motion_kernel and random.random() < self.motion_kernel_prob:
|
201 |
+
m_i = random.randint(0,31)
|
202 |
+
k = self.motion_kernels[f'{m_i:02d}']
|
203 |
+
img_in = cv2.filter2D(img_in,-1,k)
|
204 |
+
|
205 |
+
# gaussian blur
|
206 |
+
kernel = gaussian_kernels.random_mixed_kernels(
|
207 |
+
self.kernel_list,
|
208 |
+
self.kernel_prob,
|
209 |
+
self.blur_kernel_size,
|
210 |
+
self.blur_sigma,
|
211 |
+
self.blur_sigma,
|
212 |
+
[-math.pi, math.pi],
|
213 |
+
noise_range=None)
|
214 |
+
img_in = cv2.filter2D(img_in, -1, kernel)
|
215 |
+
|
216 |
+
# downsample
|
217 |
+
scale = np.random.uniform(self.downsample_range[0], self.downsample_range[1])
|
218 |
+
img_in = cv2.resize(img_in, (int(self.gt_size // scale), int(self.gt_size // scale)), interpolation=cv2.INTER_LINEAR)
|
219 |
+
|
220 |
+
# noise
|
221 |
+
if self.noise_range is not None:
|
222 |
+
noise_sigma = np.random.uniform(self.noise_range[0] / 255., self.noise_range[1] / 255.)
|
223 |
+
noise = np.float32(np.random.randn(*(img_in.shape))) * noise_sigma
|
224 |
+
img_in = img_in + noise
|
225 |
+
img_in = np.clip(img_in, 0, 1)
|
226 |
+
|
227 |
+
# jpeg
|
228 |
+
if self.jpeg_range is not None:
|
229 |
+
jpeg_p = np.random.uniform(self.jpeg_range[0], self.jpeg_range[1])
|
230 |
+
encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), jpeg_p]
|
231 |
+
_, encimg = cv2.imencode('.jpg', img_in * 255., encode_param)
|
232 |
+
img_in = np.float32(cv2.imdecode(encimg, 1)) / 255.
|
233 |
+
|
234 |
+
# resize to in_size
|
235 |
+
img_in = cv2.resize(img_in, (self.in_size, self.in_size), interpolation=cv2.INTER_LINEAR)
|
236 |
+
|
237 |
+
|
238 |
+
# generate in_large with large degradation
|
239 |
+
img_in_large = img_gt
|
240 |
+
|
241 |
+
if self.use_corrupt:
|
242 |
+
# motion blur
|
243 |
+
if self.use_motion_kernel and random.random() < self.motion_kernel_prob:
|
244 |
+
m_i = random.randint(0,31)
|
245 |
+
k = self.motion_kernels[f'{m_i:02d}']
|
246 |
+
img_in_large = cv2.filter2D(img_in_large,-1,k)
|
247 |
+
|
248 |
+
# gaussian blur
|
249 |
+
kernel = gaussian_kernels.random_mixed_kernels(
|
250 |
+
self.kernel_list,
|
251 |
+
self.kernel_prob,
|
252 |
+
self.blur_kernel_size,
|
253 |
+
self.blur_sigma_large,
|
254 |
+
self.blur_sigma_large,
|
255 |
+
[-math.pi, math.pi],
|
256 |
+
noise_range=None)
|
257 |
+
img_in_large = cv2.filter2D(img_in_large, -1, kernel)
|
258 |
+
|
259 |
+
# downsample
|
260 |
+
scale = np.random.uniform(self.downsample_range_large[0], self.downsample_range_large[1])
|
261 |
+
img_in_large = cv2.resize(img_in_large, (int(self.gt_size // scale), int(self.gt_size // scale)), interpolation=cv2.INTER_LINEAR)
|
262 |
+
|
263 |
+
# noise
|
264 |
+
if self.noise_range_large is not None:
|
265 |
+
noise_sigma = np.random.uniform(self.noise_range_large[0] / 255., self.noise_range_large[1] / 255.)
|
266 |
+
noise = np.float32(np.random.randn(*(img_in_large.shape))) * noise_sigma
|
267 |
+
img_in_large = img_in_large + noise
|
268 |
+
img_in_large = np.clip(img_in_large, 0, 1)
|
269 |
+
|
270 |
+
# jpeg
|
271 |
+
if self.jpeg_range_large is not None:
|
272 |
+
jpeg_p = np.random.uniform(self.jpeg_range_large[0], self.jpeg_range_large[1])
|
273 |
+
encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), jpeg_p]
|
274 |
+
_, encimg = cv2.imencode('.jpg', img_in_large * 255., encode_param)
|
275 |
+
img_in_large = np.float32(cv2.imdecode(encimg, 1)) / 255.
|
276 |
+
|
277 |
+
# resize to in_size
|
278 |
+
img_in_large = cv2.resize(img_in_large, (self.in_size, self.in_size), interpolation=cv2.INTER_LINEAR)
|
279 |
+
|
280 |
+
|
281 |
+
# random color jitter (only for lq)
|
282 |
+
if self.color_jitter_prob is not None and (np.random.uniform() < self.color_jitter_prob):
|
283 |
+
img_in = self.color_jitter(img_in, self.color_jitter_shift)
|
284 |
+
img_in_large = self.color_jitter(img_in_large, self.color_jitter_shift)
|
285 |
+
# random to gray (only for lq)
|
286 |
+
if self.gray_prob and np.random.uniform() < self.gray_prob:
|
287 |
+
img_in = cv2.cvtColor(img_in, cv2.COLOR_BGR2GRAY)
|
288 |
+
img_in = np.tile(img_in[:, :, None], [1, 1, 3])
|
289 |
+
img_in_large = cv2.cvtColor(img_in_large, cv2.COLOR_BGR2GRAY)
|
290 |
+
img_in_large = np.tile(img_in_large[:, :, None], [1, 1, 3])
|
291 |
+
|
292 |
+
# BGR to RGB, HWC to CHW, numpy to tensor
|
293 |
+
img_in, img_in_large, img_gt = img2tensor([img_in, img_in_large, img_gt], bgr2rgb=True, float32=True)
|
294 |
+
|
295 |
+
# random color jitter (pytorch version) (only for lq)
|
296 |
+
if self.color_jitter_pt_prob is not None and (np.random.uniform() < self.color_jitter_pt_prob):
|
297 |
+
brightness = self.opt.get('brightness', (0.5, 1.5))
|
298 |
+
contrast = self.opt.get('contrast', (0.5, 1.5))
|
299 |
+
saturation = self.opt.get('saturation', (0, 1.5))
|
300 |
+
hue = self.opt.get('hue', (-0.1, 0.1))
|
301 |
+
img_in = self.color_jitter_pt(img_in, brightness, contrast, saturation, hue)
|
302 |
+
img_in_large = self.color_jitter_pt(img_in_large, brightness, contrast, saturation, hue)
|
303 |
+
|
304 |
+
# round and clip
|
305 |
+
img_in = np.clip((img_in * 255.0).round(), 0, 255) / 255.
|
306 |
+
img_in_large = np.clip((img_in_large * 255.0).round(), 0, 255) / 255.
|
307 |
+
|
308 |
+
# Set vgg range_norm=True if use the normalization here
|
309 |
+
# normalize
|
310 |
+
normalize(img_in, self.mean, self.std, inplace=True)
|
311 |
+
normalize(img_in_large, self.mean, self.std, inplace=True)
|
312 |
+
normalize(img_gt, self.mean, self.std, inplace=True)
|
313 |
+
|
314 |
+
return_dict = {'in': img_in, 'in_large_de': img_in_large, 'gt': img_gt, 'gt_path': gt_path}
|
315 |
+
|
316 |
+
if self.crop_components:
|
317 |
+
return_dict['locations_in'] = locations_in
|
318 |
+
return_dict['locations_gt'] = locations_gt
|
319 |
+
|
320 |
+
if self.load_latent_gt:
|
321 |
+
return_dict['latent_gt'] = latent_gt
|
322 |
+
|
323 |
+
return return_dict
|
324 |
+
|
325 |
+
|
326 |
+
def __len__(self):
|
327 |
+
return len(self.paths)
|
basicsr/data/paired_image_dataset.py
ADDED
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from torch.utils import data as data
|
2 |
+
from torchvision.transforms.functional import normalize
|
3 |
+
|
4 |
+
from basicsr.data.data_util import paired_paths_from_folder, paired_paths_from_lmdb, paired_paths_from_meta_info_file
|
5 |
+
from basicsr.data.transforms import augment, paired_random_crop
|
6 |
+
from basicsr.utils import FileClient, imfrombytes, img2tensor
|
7 |
+
from basicsr.utils.registry import DATASET_REGISTRY
|
8 |
+
|
9 |
+
|
10 |
+
@DATASET_REGISTRY.register()
|
11 |
+
class PairedImageDataset(data.Dataset):
|
12 |
+
"""Paired image dataset for image restoration.
|
13 |
+
|
14 |
+
Read LQ (Low Quality, e.g. LR (Low Resolution), blurry, noisy, etc) and
|
15 |
+
GT image pairs.
|
16 |
+
|
17 |
+
There are three modes:
|
18 |
+
1. 'lmdb': Use lmdb files.
|
19 |
+
If opt['io_backend'] == lmdb.
|
20 |
+
2. 'meta_info_file': Use meta information file to generate paths.
|
21 |
+
If opt['io_backend'] != lmdb and opt['meta_info_file'] is not None.
|
22 |
+
3. 'folder': Scan folders to generate paths.
|
23 |
+
The rest.
|
24 |
+
|
25 |
+
Args:
|
26 |
+
opt (dict): Config for train datasets. It contains the following keys:
|
27 |
+
dataroot_gt (str): Data root path for gt.
|
28 |
+
dataroot_lq (str): Data root path for lq.
|
29 |
+
meta_info_file (str): Path for meta information file.
|
30 |
+
io_backend (dict): IO backend type and other kwarg.
|
31 |
+
filename_tmpl (str): Template for each filename. Note that the
|
32 |
+
template excludes the file extension. Default: '{}'.
|
33 |
+
gt_size (int): Cropped patched size for gt patches.
|
34 |
+
use_flip (bool): Use horizontal flips.
|
35 |
+
use_rot (bool): Use rotation (use vertical flip and transposing h
|
36 |
+
and w for implementation).
|
37 |
+
|
38 |
+
scale (bool): Scale, which will be added automatically.
|
39 |
+
phase (str): 'train' or 'val'.
|
40 |
+
"""
|
41 |
+
|
42 |
+
def __init__(self, opt):
|
43 |
+
super(PairedImageDataset, self).__init__()
|
44 |
+
self.opt = opt
|
45 |
+
# file client (io backend)
|
46 |
+
self.file_client = None
|
47 |
+
self.io_backend_opt = opt['io_backend']
|
48 |
+
self.mean = opt['mean'] if 'mean' in opt else None
|
49 |
+
self.std = opt['std'] if 'std' in opt else None
|
50 |
+
|
51 |
+
self.gt_folder, self.lq_folder = opt['dataroot_gt'], opt['dataroot_lq']
|
52 |
+
if 'filename_tmpl' in opt:
|
53 |
+
self.filename_tmpl = opt['filename_tmpl']
|
54 |
+
else:
|
55 |
+
self.filename_tmpl = '{}'
|
56 |
+
|
57 |
+
if self.io_backend_opt['type'] == 'lmdb':
|
58 |
+
self.io_backend_opt['db_paths'] = [self.lq_folder, self.gt_folder]
|
59 |
+
self.io_backend_opt['client_keys'] = ['lq', 'gt']
|
60 |
+
self.paths = paired_paths_from_lmdb([self.lq_folder, self.gt_folder], ['lq', 'gt'])
|
61 |
+
elif 'meta_info_file' in self.opt and self.opt['meta_info_file'] is not None:
|
62 |
+
self.paths = paired_paths_from_meta_info_file([self.lq_folder, self.gt_folder], ['lq', 'gt'],
|
63 |
+
self.opt['meta_info_file'], self.filename_tmpl)
|
64 |
+
else:
|
65 |
+
self.paths = paired_paths_from_folder([self.lq_folder, self.gt_folder], ['lq', 'gt'], self.filename_tmpl)
|
66 |
+
|
67 |
+
def __getitem__(self, index):
|
68 |
+
if self.file_client is None:
|
69 |
+
self.file_client = FileClient(self.io_backend_opt.pop('type'), **self.io_backend_opt)
|
70 |
+
|
71 |
+
scale = self.opt['scale']
|
72 |
+
|
73 |
+
# Load gt and lq images. Dimension order: HWC; channel order: BGR;
|
74 |
+
# image range: [0, 1], float32.
|
75 |
+
gt_path = self.paths[index]['gt_path']
|
76 |
+
img_bytes = self.file_client.get(gt_path, 'gt')
|
77 |
+
img_gt = imfrombytes(img_bytes, float32=True)
|
78 |
+
lq_path = self.paths[index]['lq_path']
|
79 |
+
img_bytes = self.file_client.get(lq_path, 'lq')
|
80 |
+
img_lq = imfrombytes(img_bytes, float32=True)
|
81 |
+
|
82 |
+
# augmentation for training
|
83 |
+
if self.opt['phase'] == 'train':
|
84 |
+
gt_size = self.opt['gt_size']
|
85 |
+
# random crop
|
86 |
+
img_gt, img_lq = paired_random_crop(img_gt, img_lq, gt_size, scale, gt_path)
|
87 |
+
# flip, rotation
|
88 |
+
img_gt, img_lq = augment([img_gt, img_lq], self.opt['use_flip'], self.opt['use_rot'])
|
89 |
+
|
90 |
+
# TODO: color space transform
|
91 |
+
# BGR to RGB, HWC to CHW, numpy to tensor
|
92 |
+
img_gt, img_lq = img2tensor([img_gt, img_lq], bgr2rgb=True, float32=True)
|
93 |
+
# normalize
|
94 |
+
if self.mean is not None or self.std is not None:
|
95 |
+
normalize(img_lq, self.mean, self.std, inplace=True)
|
96 |
+
normalize(img_gt, self.mean, self.std, inplace=True)
|
97 |
+
|
98 |
+
return {'lq': img_lq, 'gt': img_gt, 'lq_path': lq_path, 'gt_path': gt_path}
|
99 |
+
|
100 |
+
def __len__(self):
|
101 |
+
return len(self.paths)
|
basicsr/models/base_model.py
ADDED
@@ -0,0 +1,322 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import logging
|
2 |
+
import os
|
3 |
+
import torch
|
4 |
+
from collections import OrderedDict
|
5 |
+
from copy import deepcopy
|
6 |
+
from torch.nn.parallel import DataParallel, DistributedDataParallel
|
7 |
+
|
8 |
+
from basicsr.models import lr_scheduler as lr_scheduler
|
9 |
+
from basicsr.utils.dist_util import master_only
|
10 |
+
|
11 |
+
logger = logging.getLogger('basicsr')
|
12 |
+
|
13 |
+
|
14 |
+
class BaseModel():
|
15 |
+
"""Base model."""
|
16 |
+
|
17 |
+
def __init__(self, opt):
|
18 |
+
self.opt = opt
|
19 |
+
self.device = torch.device('cuda' if opt['num_gpu'] != 0 else 'cpu')
|
20 |
+
self.is_train = opt['is_train']
|
21 |
+
self.schedulers = []
|
22 |
+
self.optimizers = []
|
23 |
+
|
24 |
+
def feed_data(self, data):
|
25 |
+
pass
|
26 |
+
|
27 |
+
def optimize_parameters(self):
|
28 |
+
pass
|
29 |
+
|
30 |
+
def get_current_visuals(self):
|
31 |
+
pass
|
32 |
+
|
33 |
+
def save(self, epoch, current_iter):
|
34 |
+
"""Save networks and training state."""
|
35 |
+
pass
|
36 |
+
|
37 |
+
def validation(self, dataloader, current_iter, tb_logger, save_img=False):
|
38 |
+
"""Validation function.
|
39 |
+
|
40 |
+
Args:
|
41 |
+
dataloader (torch.utils.data.DataLoader): Validation dataloader.
|
42 |
+
current_iter (int): Current iteration.
|
43 |
+
tb_logger (tensorboard logger): Tensorboard logger.
|
44 |
+
save_img (bool): Whether to save images. Default: False.
|
45 |
+
"""
|
46 |
+
if self.opt['dist']:
|
47 |
+
self.dist_validation(dataloader, current_iter, tb_logger, save_img)
|
48 |
+
else:
|
49 |
+
self.nondist_validation(dataloader, current_iter, tb_logger, save_img)
|
50 |
+
|
51 |
+
def model_ema(self, decay=0.999):
|
52 |
+
net_g = self.get_bare_model(self.net_g)
|
53 |
+
|
54 |
+
net_g_params = dict(net_g.named_parameters())
|
55 |
+
net_g_ema_params = dict(self.net_g_ema.named_parameters())
|
56 |
+
|
57 |
+
for k in net_g_ema_params.keys():
|
58 |
+
net_g_ema_params[k].data.mul_(decay).add_(net_g_params[k].data, alpha=1 - decay)
|
59 |
+
|
60 |
+
def get_current_log(self):
|
61 |
+
return self.log_dict
|
62 |
+
|
63 |
+
def model_to_device(self, net):
|
64 |
+
"""Model to device. It also warps models with DistributedDataParallel
|
65 |
+
or DataParallel.
|
66 |
+
|
67 |
+
Args:
|
68 |
+
net (nn.Module)
|
69 |
+
"""
|
70 |
+
net = net.to(self.device)
|
71 |
+
if self.opt['dist']:
|
72 |
+
find_unused_parameters = self.opt.get('find_unused_parameters', False)
|
73 |
+
net = DistributedDataParallel(
|
74 |
+
net, device_ids=[torch.cuda.current_device()], find_unused_parameters=find_unused_parameters)
|
75 |
+
elif self.opt['num_gpu'] > 1:
|
76 |
+
net = DataParallel(net)
|
77 |
+
return net
|
78 |
+
|
79 |
+
def get_optimizer(self, optim_type, params, lr, **kwargs):
|
80 |
+
if optim_type == 'Adam':
|
81 |
+
optimizer = torch.optim.Adam(params, lr, **kwargs)
|
82 |
+
else:
|
83 |
+
raise NotImplementedError(f'optimizer {optim_type} is not supperted yet.')
|
84 |
+
return optimizer
|
85 |
+
|
86 |
+
def setup_schedulers(self):
|
87 |
+
"""Set up schedulers."""
|
88 |
+
train_opt = self.opt['train']
|
89 |
+
scheduler_type = train_opt['scheduler'].pop('type')
|
90 |
+
if scheduler_type in ['MultiStepLR', 'MultiStepRestartLR']:
|
91 |
+
for optimizer in self.optimizers:
|
92 |
+
self.schedulers.append(lr_scheduler.MultiStepRestartLR(optimizer, **train_opt['scheduler']))
|
93 |
+
elif scheduler_type == 'CosineAnnealingRestartLR':
|
94 |
+
for optimizer in self.optimizers:
|
95 |
+
self.schedulers.append(lr_scheduler.CosineAnnealingRestartLR(optimizer, **train_opt['scheduler']))
|
96 |
+
else:
|
97 |
+
raise NotImplementedError(f'Scheduler {scheduler_type} is not implemented yet.')
|
98 |
+
|
99 |
+
def get_bare_model(self, net):
|
100 |
+
"""Get bare model, especially under wrapping with
|
101 |
+
DistributedDataParallel or DataParallel.
|
102 |
+
"""
|
103 |
+
if isinstance(net, (DataParallel, DistributedDataParallel)):
|
104 |
+
net = net.module
|
105 |
+
return net
|
106 |
+
|
107 |
+
@master_only
|
108 |
+
def print_network(self, net):
|
109 |
+
"""Print the str and parameter number of a network.
|
110 |
+
|
111 |
+
Args:
|
112 |
+
net (nn.Module)
|
113 |
+
"""
|
114 |
+
if isinstance(net, (DataParallel, DistributedDataParallel)):
|
115 |
+
net_cls_str = (f'{net.__class__.__name__} - ' f'{net.module.__class__.__name__}')
|
116 |
+
else:
|
117 |
+
net_cls_str = f'{net.__class__.__name__}'
|
118 |
+
|
119 |
+
net = self.get_bare_model(net)
|
120 |
+
net_str = str(net)
|
121 |
+
net_params = sum(map(lambda x: x.numel(), net.parameters()))
|
122 |
+
|
123 |
+
logger.info(f'Network: {net_cls_str}, with parameters: {net_params:,d}')
|
124 |
+
logger.info(net_str)
|
125 |
+
|
126 |
+
def _set_lr(self, lr_groups_l):
|
127 |
+
"""Set learning rate for warmup.
|
128 |
+
|
129 |
+
Args:
|
130 |
+
lr_groups_l (list): List for lr_groups, each for an optimizer.
|
131 |
+
"""
|
132 |
+
for optimizer, lr_groups in zip(self.optimizers, lr_groups_l):
|
133 |
+
for param_group, lr in zip(optimizer.param_groups, lr_groups):
|
134 |
+
param_group['lr'] = lr
|
135 |
+
|
136 |
+
def _get_init_lr(self):
|
137 |
+
"""Get the initial lr, which is set by the scheduler.
|
138 |
+
"""
|
139 |
+
init_lr_groups_l = []
|
140 |
+
for optimizer in self.optimizers:
|
141 |
+
init_lr_groups_l.append([v['initial_lr'] for v in optimizer.param_groups])
|
142 |
+
return init_lr_groups_l
|
143 |
+
|
144 |
+
def update_learning_rate(self, current_iter, warmup_iter=-1):
|
145 |
+
"""Update learning rate.
|
146 |
+
|
147 |
+
Args:
|
148 |
+
current_iter (int): Current iteration.
|
149 |
+
warmup_iter (int): Warmup iter numbers. -1 for no warmup.
|
150 |
+
Default: -1.
|
151 |
+
"""
|
152 |
+
if current_iter > 1:
|
153 |
+
for scheduler in self.schedulers:
|
154 |
+
scheduler.step()
|
155 |
+
# set up warm-up learning rate
|
156 |
+
if current_iter < warmup_iter:
|
157 |
+
# get initial lr for each group
|
158 |
+
init_lr_g_l = self._get_init_lr()
|
159 |
+
# modify warming-up learning rates
|
160 |
+
# currently only support linearly warm up
|
161 |
+
warm_up_lr_l = []
|
162 |
+
for init_lr_g in init_lr_g_l:
|
163 |
+
warm_up_lr_l.append([v / warmup_iter * current_iter for v in init_lr_g])
|
164 |
+
# set learning rate
|
165 |
+
self._set_lr(warm_up_lr_l)
|
166 |
+
|
167 |
+
def get_current_learning_rate(self):
|
168 |
+
return [param_group['lr'] for param_group in self.optimizers[0].param_groups]
|
169 |
+
|
170 |
+
@master_only
|
171 |
+
def save_network(self, net, net_label, current_iter, param_key='params'):
|
172 |
+
"""Save networks.
|
173 |
+
|
174 |
+
Args:
|
175 |
+
net (nn.Module | list[nn.Module]): Network(s) to be saved.
|
176 |
+
net_label (str): Network label.
|
177 |
+
current_iter (int): Current iter number.
|
178 |
+
param_key (str | list[str]): The parameter key(s) to save network.
|
179 |
+
Default: 'params'.
|
180 |
+
"""
|
181 |
+
if current_iter == -1:
|
182 |
+
current_iter = 'latest'
|
183 |
+
save_filename = f'{net_label}_{current_iter}.pth'
|
184 |
+
save_path = os.path.join(self.opt['path']['models'], save_filename)
|
185 |
+
|
186 |
+
net = net if isinstance(net, list) else [net]
|
187 |
+
param_key = param_key if isinstance(param_key, list) else [param_key]
|
188 |
+
assert len(net) == len(param_key), 'The lengths of net and param_key should be the same.'
|
189 |
+
|
190 |
+
save_dict = {}
|
191 |
+
for net_, param_key_ in zip(net, param_key):
|
192 |
+
net_ = self.get_bare_model(net_)
|
193 |
+
state_dict = net_.state_dict()
|
194 |
+
for key, param in state_dict.items():
|
195 |
+
if key.startswith('module.'): # remove unnecessary 'module.'
|
196 |
+
key = key[7:]
|
197 |
+
state_dict[key] = param.cpu()
|
198 |
+
save_dict[param_key_] = state_dict
|
199 |
+
|
200 |
+
torch.save(save_dict, save_path)
|
201 |
+
|
202 |
+
def _print_different_keys_loading(self, crt_net, load_net, strict=True):
|
203 |
+
"""Print keys with differnet name or different size when loading models.
|
204 |
+
|
205 |
+
1. Print keys with differnet names.
|
206 |
+
2. If strict=False, print the same key but with different tensor size.
|
207 |
+
It also ignore these keys with different sizes (not load).
|
208 |
+
|
209 |
+
Args:
|
210 |
+
crt_net (torch model): Current network.
|
211 |
+
load_net (dict): Loaded network.
|
212 |
+
strict (bool): Whether strictly loaded. Default: True.
|
213 |
+
"""
|
214 |
+
crt_net = self.get_bare_model(crt_net)
|
215 |
+
crt_net = crt_net.state_dict()
|
216 |
+
crt_net_keys = set(crt_net.keys())
|
217 |
+
load_net_keys = set(load_net.keys())
|
218 |
+
|
219 |
+
if crt_net_keys != load_net_keys:
|
220 |
+
logger.warning('Current net - loaded net:')
|
221 |
+
for v in sorted(list(crt_net_keys - load_net_keys)):
|
222 |
+
logger.warning(f' {v}')
|
223 |
+
logger.warning('Loaded net - current net:')
|
224 |
+
for v in sorted(list(load_net_keys - crt_net_keys)):
|
225 |
+
logger.warning(f' {v}')
|
226 |
+
|
227 |
+
# check the size for the same keys
|
228 |
+
if not strict:
|
229 |
+
common_keys = crt_net_keys & load_net_keys
|
230 |
+
for k in common_keys:
|
231 |
+
if crt_net[k].size() != load_net[k].size():
|
232 |
+
logger.warning(f'Size different, ignore [{k}]: crt_net: '
|
233 |
+
f'{crt_net[k].shape}; load_net: {load_net[k].shape}')
|
234 |
+
load_net[k + '.ignore'] = load_net.pop(k)
|
235 |
+
|
236 |
+
def load_network(self, net, load_path, strict=True, param_key='params'):
|
237 |
+
"""Load network.
|
238 |
+
|
239 |
+
Args:
|
240 |
+
load_path (str): The path of networks to be loaded.
|
241 |
+
net (nn.Module): Network.
|
242 |
+
strict (bool): Whether strictly loaded.
|
243 |
+
param_key (str): The parameter key of loaded network. If set to
|
244 |
+
None, use the root 'path'.
|
245 |
+
Default: 'params'.
|
246 |
+
"""
|
247 |
+
net = self.get_bare_model(net)
|
248 |
+
logger.info(f'Loading {net.__class__.__name__} model from {load_path}.')
|
249 |
+
load_net = torch.load(load_path, map_location=lambda storage, loc: storage)
|
250 |
+
if param_key is not None:
|
251 |
+
if param_key not in load_net and 'params' in load_net:
|
252 |
+
param_key = 'params'
|
253 |
+
logger.info('Loading: params_ema does not exist, use params.')
|
254 |
+
load_net = load_net[param_key]
|
255 |
+
# remove unnecessary 'module.'
|
256 |
+
for k, v in deepcopy(load_net).items():
|
257 |
+
if k.startswith('module.'):
|
258 |
+
load_net[k[7:]] = v
|
259 |
+
load_net.pop(k)
|
260 |
+
self._print_different_keys_loading(net, load_net, strict)
|
261 |
+
net.load_state_dict(load_net, strict=strict)
|
262 |
+
|
263 |
+
@master_only
|
264 |
+
def save_training_state(self, epoch, current_iter):
|
265 |
+
"""Save training states during training, which will be used for
|
266 |
+
resuming.
|
267 |
+
|
268 |
+
Args:
|
269 |
+
epoch (int): Current epoch.
|
270 |
+
current_iter (int): Current iteration.
|
271 |
+
"""
|
272 |
+
if current_iter != -1:
|
273 |
+
state = {'epoch': epoch, 'iter': current_iter, 'optimizers': [], 'schedulers': []}
|
274 |
+
for o in self.optimizers:
|
275 |
+
state['optimizers'].append(o.state_dict())
|
276 |
+
for s in self.schedulers:
|
277 |
+
state['schedulers'].append(s.state_dict())
|
278 |
+
save_filename = f'{current_iter}.state'
|
279 |
+
save_path = os.path.join(self.opt['path']['training_states'], save_filename)
|
280 |
+
torch.save(state, save_path)
|
281 |
+
|
282 |
+
def resume_training(self, resume_state):
|
283 |
+
"""Reload the optimizers and schedulers for resumed training.
|
284 |
+
|
285 |
+
Args:
|
286 |
+
resume_state (dict): Resume state.
|
287 |
+
"""
|
288 |
+
resume_optimizers = resume_state['optimizers']
|
289 |
+
resume_schedulers = resume_state['schedulers']
|
290 |
+
assert len(resume_optimizers) == len(self.optimizers), 'Wrong lengths of optimizers'
|
291 |
+
assert len(resume_schedulers) == len(self.schedulers), 'Wrong lengths of schedulers'
|
292 |
+
for i, o in enumerate(resume_optimizers):
|
293 |
+
self.optimizers[i].load_state_dict(o)
|
294 |
+
for i, s in enumerate(resume_schedulers):
|
295 |
+
self.schedulers[i].load_state_dict(s)
|
296 |
+
|
297 |
+
def reduce_loss_dict(self, loss_dict):
|
298 |
+
"""reduce loss dict.
|
299 |
+
|
300 |
+
In distributed training, it averages the losses among different GPUs .
|
301 |
+
|
302 |
+
Args:
|
303 |
+
loss_dict (OrderedDict): Loss dict.
|
304 |
+
"""
|
305 |
+
with torch.no_grad():
|
306 |
+
if self.opt['dist']:
|
307 |
+
keys = []
|
308 |
+
losses = []
|
309 |
+
for name, value in loss_dict.items():
|
310 |
+
keys.append(name)
|
311 |
+
losses.append(value)
|
312 |
+
losses = torch.stack(losses, 0)
|
313 |
+
torch.distributed.reduce(losses, dst=0)
|
314 |
+
if self.opt['rank'] == 0:
|
315 |
+
losses /= self.opt['world_size']
|
316 |
+
loss_dict = {key: loss for key, loss in zip(keys, losses)}
|
317 |
+
|
318 |
+
log_dict = OrderedDict()
|
319 |
+
for name, value in loss_dict.items():
|
320 |
+
log_dict[name] = value.mean().item()
|
321 |
+
|
322 |
+
return log_dict
|
basicsr/models/codeformer_idx_model.py
ADDED
@@ -0,0 +1,216 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from collections import OrderedDict
|
3 |
+
from os import path as osp
|
4 |
+
from tqdm import tqdm
|
5 |
+
|
6 |
+
from basicsr.archs import build_network
|
7 |
+
from basicsr.metrics import calculate_metric
|
8 |
+
from basicsr.utils import get_root_logger, imwrite, tensor2img
|
9 |
+
from basicsr.utils.registry import MODEL_REGISTRY
|
10 |
+
import torch.nn.functional as F
|
11 |
+
from .sr_model import SRModel
|
12 |
+
|
13 |
+
|
14 |
+
@MODEL_REGISTRY.register()
|
15 |
+
class CodeFormerIdxModel(SRModel):
|
16 |
+
def feed_data(self, data):
|
17 |
+
self.gt = data['gt'].to(self.device)
|
18 |
+
self.input = data['in'].to(self.device)
|
19 |
+
self.b = self.gt.shape[0]
|
20 |
+
|
21 |
+
if 'latent_gt' in data:
|
22 |
+
self.idx_gt = data['latent_gt'].to(self.device)
|
23 |
+
self.idx_gt = self.idx_gt.view(self.b, -1)
|
24 |
+
else:
|
25 |
+
self.idx_gt = None
|
26 |
+
|
27 |
+
def init_training_settings(self):
|
28 |
+
logger = get_root_logger()
|
29 |
+
train_opt = self.opt['train']
|
30 |
+
|
31 |
+
self.ema_decay = train_opt.get('ema_decay', 0)
|
32 |
+
if self.ema_decay > 0:
|
33 |
+
logger.info(f'Use Exponential Moving Average with decay: {self.ema_decay}')
|
34 |
+
# define network net_g with Exponential Moving Average (EMA)
|
35 |
+
# net_g_ema is used only for testing on one GPU and saving
|
36 |
+
# There is no need to wrap with DistributedDataParallel
|
37 |
+
self.net_g_ema = build_network(self.opt['network_g']).to(self.device)
|
38 |
+
# load pretrained model
|
39 |
+
load_path = self.opt['path'].get('pretrain_network_g', None)
|
40 |
+
if load_path is not None:
|
41 |
+
self.load_network(self.net_g_ema, load_path, self.opt['path'].get('strict_load_g', True), 'params_ema')
|
42 |
+
else:
|
43 |
+
self.model_ema(0) # copy net_g weight
|
44 |
+
self.net_g_ema.eval()
|
45 |
+
|
46 |
+
if self.opt.get('network_vqgan', None) is not None and self.opt['datasets'].get('latent_gt_path') is None:
|
47 |
+
self.hq_vqgan_fix = build_network(self.opt['network_vqgan']).to(self.device)
|
48 |
+
self.hq_vqgan_fix.eval()
|
49 |
+
self.generate_idx_gt = True
|
50 |
+
for param in self.hq_vqgan_fix.parameters():
|
51 |
+
param.requires_grad = False
|
52 |
+
else:
|
53 |
+
self.generate_idx_gt = False
|
54 |
+
|
55 |
+
self.hq_feat_loss = train_opt.get('use_hq_feat_loss', True)
|
56 |
+
self.feat_loss_weight = train_opt.get('feat_loss_weight', 1.0)
|
57 |
+
self.cross_entropy_loss = train_opt.get('cross_entropy_loss', True)
|
58 |
+
self.entropy_loss_weight = train_opt.get('entropy_loss_weight', 0.5)
|
59 |
+
|
60 |
+
self.net_g.train()
|
61 |
+
|
62 |
+
# set up optimizers and schedulers
|
63 |
+
self.setup_optimizers()
|
64 |
+
self.setup_schedulers()
|
65 |
+
|
66 |
+
|
67 |
+
def setup_optimizers(self):
|
68 |
+
train_opt = self.opt['train']
|
69 |
+
# optimizer g
|
70 |
+
optim_params_g = []
|
71 |
+
for k, v in self.net_g.named_parameters():
|
72 |
+
if v.requires_grad:
|
73 |
+
optim_params_g.append(v)
|
74 |
+
else:
|
75 |
+
logger = get_root_logger()
|
76 |
+
logger.warning(f'Params {k} will not be optimized.')
|
77 |
+
optim_type = train_opt['optim_g'].pop('type')
|
78 |
+
self.optimizer_g = self.get_optimizer(optim_type, optim_params_g, **train_opt['optim_g'])
|
79 |
+
self.optimizers.append(self.optimizer_g)
|
80 |
+
|
81 |
+
|
82 |
+
def optimize_parameters(self, current_iter):
|
83 |
+
logger = get_root_logger()
|
84 |
+
# optimize net_g
|
85 |
+
self.optimizer_g.zero_grad()
|
86 |
+
|
87 |
+
if self.generate_idx_gt:
|
88 |
+
x = self.hq_vqgan_fix.encoder(self.gt)
|
89 |
+
_, _, quant_stats = self.hq_vqgan_fix.quantize(x)
|
90 |
+
min_encoding_indices = quant_stats['min_encoding_indices']
|
91 |
+
self.idx_gt = min_encoding_indices.view(self.b, -1)
|
92 |
+
|
93 |
+
if self.hq_feat_loss:
|
94 |
+
# quant_feats
|
95 |
+
quant_feat_gt = self.net_g.module.quantize.get_codebook_feat(self.idx_gt, shape=[self.b,16,16,256])
|
96 |
+
|
97 |
+
logits, lq_feat = self.net_g(self.input, w=0, code_only=True)
|
98 |
+
|
99 |
+
l_g_total = 0
|
100 |
+
loss_dict = OrderedDict()
|
101 |
+
# hq_feat_loss
|
102 |
+
if self.hq_feat_loss: # codebook loss
|
103 |
+
l_feat_encoder = torch.mean((quant_feat_gt.detach()-lq_feat)**2) * self.feat_loss_weight
|
104 |
+
l_g_total += l_feat_encoder
|
105 |
+
loss_dict['l_feat_encoder'] = l_feat_encoder
|
106 |
+
|
107 |
+
# cross_entropy_loss
|
108 |
+
if self.cross_entropy_loss:
|
109 |
+
# b(hw)n -> bn(hw)
|
110 |
+
cross_entropy_loss = F.cross_entropy(logits.permute(0, 2, 1), self.idx_gt) * self.entropy_loss_weight
|
111 |
+
l_g_total += cross_entropy_loss
|
112 |
+
loss_dict['cross_entropy_loss'] = cross_entropy_loss
|
113 |
+
|
114 |
+
l_g_total.backward()
|
115 |
+
self.optimizer_g.step()
|
116 |
+
|
117 |
+
if self.ema_decay > 0:
|
118 |
+
self.model_ema(decay=self.ema_decay)
|
119 |
+
|
120 |
+
self.log_dict = self.reduce_loss_dict(loss_dict)
|
121 |
+
|
122 |
+
|
123 |
+
def test(self):
|
124 |
+
with torch.no_grad():
|
125 |
+
if hasattr(self, 'net_g_ema'):
|
126 |
+
self.net_g_ema.eval()
|
127 |
+
self.output, _, _ = self.net_g_ema(self.input, w=0)
|
128 |
+
else:
|
129 |
+
logger = get_root_logger()
|
130 |
+
logger.warning('Do not have self.net_g_ema, use self.net_g.')
|
131 |
+
self.net_g.eval()
|
132 |
+
self.output, _, _ = self.net_g(self.input, w=0)
|
133 |
+
self.net_g.train()
|
134 |
+
|
135 |
+
|
136 |
+
def dist_validation(self, dataloader, current_iter, tb_logger, save_img):
|
137 |
+
if self.opt['rank'] == 0:
|
138 |
+
self.nondist_validation(dataloader, current_iter, tb_logger, save_img)
|
139 |
+
|
140 |
+
|
141 |
+
def nondist_validation(self, dataloader, current_iter, tb_logger, save_img):
|
142 |
+
dataset_name = dataloader.dataset.opt['name']
|
143 |
+
with_metrics = self.opt['val'].get('metrics') is not None
|
144 |
+
if with_metrics:
|
145 |
+
self.metric_results = {metric: 0 for metric in self.opt['val']['metrics'].keys()}
|
146 |
+
pbar = tqdm(total=len(dataloader), unit='image')
|
147 |
+
|
148 |
+
for idx, val_data in enumerate(dataloader):
|
149 |
+
img_name = osp.splitext(osp.basename(val_data['lq_path'][0]))[0]
|
150 |
+
self.feed_data(val_data)
|
151 |
+
self.test()
|
152 |
+
|
153 |
+
visuals = self.get_current_visuals()
|
154 |
+
sr_img = tensor2img([visuals['result']])
|
155 |
+
if 'gt' in visuals:
|
156 |
+
gt_img = tensor2img([visuals['gt']])
|
157 |
+
del self.gt
|
158 |
+
|
159 |
+
# tentative for out of GPU memory
|
160 |
+
del self.lq
|
161 |
+
del self.output
|
162 |
+
torch.cuda.empty_cache()
|
163 |
+
|
164 |
+
if save_img:
|
165 |
+
if self.opt['is_train']:
|
166 |
+
save_img_path = osp.join(self.opt['path']['visualization'], img_name,
|
167 |
+
f'{img_name}_{current_iter}.png')
|
168 |
+
else:
|
169 |
+
if self.opt['val']['suffix']:
|
170 |
+
save_img_path = osp.join(self.opt['path']['visualization'], dataset_name,
|
171 |
+
f'{img_name}_{self.opt["val"]["suffix"]}.png')
|
172 |
+
else:
|
173 |
+
save_img_path = osp.join(self.opt['path']['visualization'], dataset_name,
|
174 |
+
f'{img_name}_{self.opt["name"]}.png')
|
175 |
+
imwrite(sr_img, save_img_path)
|
176 |
+
|
177 |
+
if with_metrics:
|
178 |
+
# calculate metrics
|
179 |
+
for name, opt_ in self.opt['val']['metrics'].items():
|
180 |
+
metric_data = dict(img1=sr_img, img2=gt_img)
|
181 |
+
self.metric_results[name] += calculate_metric(metric_data, opt_)
|
182 |
+
pbar.update(1)
|
183 |
+
pbar.set_description(f'Test {img_name}')
|
184 |
+
pbar.close()
|
185 |
+
|
186 |
+
if with_metrics:
|
187 |
+
for metric in self.metric_results.keys():
|
188 |
+
self.metric_results[metric] /= (idx + 1)
|
189 |
+
|
190 |
+
self._log_validation_metric_values(current_iter, dataset_name, tb_logger)
|
191 |
+
|
192 |
+
|
193 |
+
def _log_validation_metric_values(self, current_iter, dataset_name, tb_logger):
|
194 |
+
log_str = f'Validation {dataset_name}\n'
|
195 |
+
for metric, value in self.metric_results.items():
|
196 |
+
log_str += f'\t # {metric}: {value:.4f}\n'
|
197 |
+
logger = get_root_logger()
|
198 |
+
logger.info(log_str)
|
199 |
+
if tb_logger:
|
200 |
+
for metric, value in self.metric_results.items():
|
201 |
+
tb_logger.add_scalar(f'metrics/{metric}', value, current_iter)
|
202 |
+
|
203 |
+
|
204 |
+
def get_current_visuals(self):
|
205 |
+
out_dict = OrderedDict()
|
206 |
+
out_dict['gt'] = self.gt.detach().cpu()
|
207 |
+
out_dict['result'] = self.output.detach().cpu()
|
208 |
+
return out_dict
|
209 |
+
|
210 |
+
|
211 |
+
def save(self, epoch, current_iter):
|
212 |
+
if self.ema_decay > 0:
|
213 |
+
self.save_network([self.net_g, self.net_g_ema], 'net_g', current_iter, param_key=['params', 'params_ema'])
|
214 |
+
else:
|
215 |
+
self.save_network(self.net_g, 'net_g', current_iter)
|
216 |
+
self.save_training_state(epoch, current_iter)
|
basicsr/models/codeformer_joint_model.py
ADDED
@@ -0,0 +1,346 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from collections import OrderedDict
|
3 |
+
from os import path as osp
|
4 |
+
from tqdm import tqdm
|
5 |
+
|
6 |
+
|
7 |
+
from basicsr.archs import build_network
|
8 |
+
from basicsr.losses import build_loss
|
9 |
+
from basicsr.metrics import calculate_metric
|
10 |
+
from basicsr.utils import get_root_logger, imwrite, tensor2img
|
11 |
+
from basicsr.utils.registry import MODEL_REGISTRY
|
12 |
+
import torch.nn.functional as F
|
13 |
+
from .sr_model import SRModel
|
14 |
+
|
15 |
+
|
16 |
+
@MODEL_REGISTRY.register()
|
17 |
+
class CodeFormerJointModel(SRModel):
|
18 |
+
def feed_data(self, data):
|
19 |
+
self.gt = data['gt'].to(self.device)
|
20 |
+
self.input = data['in'].to(self.device)
|
21 |
+
self.input_large_de = data['in_large_de'].to(self.device)
|
22 |
+
self.b = self.gt.shape[0]
|
23 |
+
|
24 |
+
if 'latent_gt' in data:
|
25 |
+
self.idx_gt = data['latent_gt'].to(self.device)
|
26 |
+
self.idx_gt = self.idx_gt.view(self.b, -1)
|
27 |
+
else:
|
28 |
+
self.idx_gt = None
|
29 |
+
|
30 |
+
def init_training_settings(self):
|
31 |
+
logger = get_root_logger()
|
32 |
+
train_opt = self.opt['train']
|
33 |
+
|
34 |
+
self.ema_decay = train_opt.get('ema_decay', 0)
|
35 |
+
if self.ema_decay > 0:
|
36 |
+
logger.info(f'Use Exponential Moving Average with decay: {self.ema_decay}')
|
37 |
+
# define network net_g with Exponential Moving Average (EMA)
|
38 |
+
# net_g_ema is used only for testing on one GPU and saving
|
39 |
+
# There is no need to wrap with DistributedDataParallel
|
40 |
+
self.net_g_ema = build_network(self.opt['network_g']).to(self.device)
|
41 |
+
# load pretrained model
|
42 |
+
load_path = self.opt['path'].get('pretrain_network_g', None)
|
43 |
+
if load_path is not None:
|
44 |
+
self.load_network(self.net_g_ema, load_path, self.opt['path'].get('strict_load_g', True), 'params_ema')
|
45 |
+
else:
|
46 |
+
self.model_ema(0) # copy net_g weight
|
47 |
+
self.net_g_ema.eval()
|
48 |
+
|
49 |
+
if self.opt.get('network_vqgan', None) is not None and self.opt['datasets'].get('latent_gt_path') is None:
|
50 |
+
self.hq_vqgan_fix = build_network(self.opt['network_vqgan']).to(self.device)
|
51 |
+
self.hq_vqgan_fix.eval()
|
52 |
+
self.generate_idx_gt = True
|
53 |
+
for param in self.hq_vqgan_fix.parameters():
|
54 |
+
param.requires_grad = False
|
55 |
+
else:
|
56 |
+
self.generate_idx_gt = False
|
57 |
+
|
58 |
+
self.hq_feat_loss = train_opt.get('use_hq_feat_loss', True)
|
59 |
+
self.feat_loss_weight = train_opt.get('feat_loss_weight', 1.0)
|
60 |
+
self.cross_entropy_loss = train_opt.get('cross_entropy_loss', True)
|
61 |
+
self.entropy_loss_weight = train_opt.get('entropy_loss_weight', 0.5)
|
62 |
+
self.scale_adaptive_gan_weight = train_opt.get('scale_adaptive_gan_weight', 0.8)
|
63 |
+
|
64 |
+
# define network net_d
|
65 |
+
self.net_d = build_network(self.opt['network_d'])
|
66 |
+
self.net_d = self.model_to_device(self.net_d)
|
67 |
+
self.print_network(self.net_d)
|
68 |
+
|
69 |
+
# load pretrained models
|
70 |
+
load_path = self.opt['path'].get('pretrain_network_d', None)
|
71 |
+
if load_path is not None:
|
72 |
+
self.load_network(self.net_d, load_path, self.opt['path'].get('strict_load_d', True))
|
73 |
+
|
74 |
+
self.net_g.train()
|
75 |
+
self.net_d.train()
|
76 |
+
|
77 |
+
# define losses
|
78 |
+
if train_opt.get('pixel_opt'):
|
79 |
+
self.cri_pix = build_loss(train_opt['pixel_opt']).to(self.device)
|
80 |
+
else:
|
81 |
+
self.cri_pix = None
|
82 |
+
|
83 |
+
if train_opt.get('perceptual_opt'):
|
84 |
+
self.cri_perceptual = build_loss(train_opt['perceptual_opt']).to(self.device)
|
85 |
+
else:
|
86 |
+
self.cri_perceptual = None
|
87 |
+
|
88 |
+
if train_opt.get('gan_opt'):
|
89 |
+
self.cri_gan = build_loss(train_opt['gan_opt']).to(self.device)
|
90 |
+
|
91 |
+
|
92 |
+
self.fix_generator = train_opt.get('fix_generator', True)
|
93 |
+
logger.info(f'fix_generator: {self.fix_generator}')
|
94 |
+
|
95 |
+
self.net_g_start_iter = train_opt.get('net_g_start_iter', 0)
|
96 |
+
self.net_d_iters = train_opt.get('net_d_iters', 1)
|
97 |
+
self.net_d_start_iter = train_opt.get('net_d_start_iter', 0)
|
98 |
+
|
99 |
+
# set up optimizers and schedulers
|
100 |
+
self.setup_optimizers()
|
101 |
+
self.setup_schedulers()
|
102 |
+
|
103 |
+
def calculate_adaptive_weight(self, recon_loss, g_loss, last_layer, disc_weight_max):
|
104 |
+
recon_grads = torch.autograd.grad(recon_loss, last_layer, retain_graph=True)[0]
|
105 |
+
g_grads = torch.autograd.grad(g_loss, last_layer, retain_graph=True)[0]
|
106 |
+
|
107 |
+
d_weight = torch.norm(recon_grads) / (torch.norm(g_grads) + 1e-4)
|
108 |
+
d_weight = torch.clamp(d_weight, 0.0, disc_weight_max).detach()
|
109 |
+
return d_weight
|
110 |
+
|
111 |
+
def setup_optimizers(self):
|
112 |
+
train_opt = self.opt['train']
|
113 |
+
# optimizer g
|
114 |
+
optim_params_g = []
|
115 |
+
for k, v in self.net_g.named_parameters():
|
116 |
+
if v.requires_grad:
|
117 |
+
optim_params_g.append(v)
|
118 |
+
else:
|
119 |
+
logger = get_root_logger()
|
120 |
+
logger.warning(f'Params {k} will not be optimized.')
|
121 |
+
optim_type = train_opt['optim_g'].pop('type')
|
122 |
+
self.optimizer_g = self.get_optimizer(optim_type, optim_params_g, **train_opt['optim_g'])
|
123 |
+
self.optimizers.append(self.optimizer_g)
|
124 |
+
# optimizer d
|
125 |
+
optim_type = train_opt['optim_d'].pop('type')
|
126 |
+
self.optimizer_d = self.get_optimizer(optim_type, self.net_d.parameters(), **train_opt['optim_d'])
|
127 |
+
self.optimizers.append(self.optimizer_d)
|
128 |
+
|
129 |
+
def gray_resize_for_identity(self, out, size=128):
|
130 |
+
out_gray = (0.2989 * out[:, 0, :, :] + 0.5870 * out[:, 1, :, :] + 0.1140 * out[:, 2, :, :])
|
131 |
+
out_gray = out_gray.unsqueeze(1)
|
132 |
+
out_gray = F.interpolate(out_gray, (size, size), mode='bilinear', align_corners=False)
|
133 |
+
return out_gray
|
134 |
+
|
135 |
+
def optimize_parameters(self, current_iter):
|
136 |
+
logger = get_root_logger()
|
137 |
+
# optimize net_g
|
138 |
+
for p in self.net_d.parameters():
|
139 |
+
p.requires_grad = False
|
140 |
+
|
141 |
+
self.optimizer_g.zero_grad()
|
142 |
+
|
143 |
+
if self.generate_idx_gt:
|
144 |
+
x = self.hq_vqgan_fix.encoder(self.gt)
|
145 |
+
output, _, quant_stats = self.hq_vqgan_fix.quantize(x)
|
146 |
+
min_encoding_indices = quant_stats['min_encoding_indices']
|
147 |
+
self.idx_gt = min_encoding_indices.view(self.b, -1)
|
148 |
+
|
149 |
+
if current_iter <= 40000: # small degradation
|
150 |
+
small_per_n = 1
|
151 |
+
w = 1
|
152 |
+
elif current_iter <= 80000: # small degradation
|
153 |
+
small_per_n = 1
|
154 |
+
w = 1.3
|
155 |
+
elif current_iter <= 120000: # large degradation
|
156 |
+
small_per_n = 120000
|
157 |
+
w = 0
|
158 |
+
else: # mixed degradation
|
159 |
+
small_per_n = 15
|
160 |
+
w = 1.3
|
161 |
+
|
162 |
+
if current_iter % small_per_n == 0:
|
163 |
+
self.output, logits, lq_feat = self.net_g(self.input, w=w, detach_16=True)
|
164 |
+
large_de = False
|
165 |
+
else:
|
166 |
+
logits, lq_feat = self.net_g(self.input_large_de, code_only=True)
|
167 |
+
large_de = True
|
168 |
+
|
169 |
+
if self.hq_feat_loss:
|
170 |
+
# quant_feats
|
171 |
+
quant_feat_gt = self.net_g.module.quantize.get_codebook_feat(self.idx_gt, shape=[self.b,16,16,256])
|
172 |
+
|
173 |
+
l_g_total = 0
|
174 |
+
loss_dict = OrderedDict()
|
175 |
+
if current_iter % self.net_d_iters == 0 and current_iter > self.net_g_start_iter:
|
176 |
+
# hq_feat_loss
|
177 |
+
if not 'transformer' in self.opt['network_g']['fix_modules']:
|
178 |
+
if self.hq_feat_loss: # codebook loss
|
179 |
+
l_feat_encoder = torch.mean((quant_feat_gt.detach()-lq_feat)**2) * self.feat_loss_weight
|
180 |
+
l_g_total += l_feat_encoder
|
181 |
+
loss_dict['l_feat_encoder'] = l_feat_encoder
|
182 |
+
|
183 |
+
# cross_entropy_loss
|
184 |
+
if self.cross_entropy_loss:
|
185 |
+
# b(hw)n -> bn(hw)
|
186 |
+
cross_entropy_loss = F.cross_entropy(logits.permute(0, 2, 1), self.idx_gt) * self.entropy_loss_weight
|
187 |
+
l_g_total += cross_entropy_loss
|
188 |
+
loss_dict['cross_entropy_loss'] = cross_entropy_loss
|
189 |
+
|
190 |
+
# pixel loss
|
191 |
+
if not large_de: # when large degradation don't need image-level loss
|
192 |
+
if self.cri_pix:
|
193 |
+
l_g_pix = self.cri_pix(self.output, self.gt)
|
194 |
+
l_g_total += l_g_pix
|
195 |
+
loss_dict['l_g_pix'] = l_g_pix
|
196 |
+
|
197 |
+
# perceptual loss
|
198 |
+
if self.cri_perceptual:
|
199 |
+
l_g_percep = self.cri_perceptual(self.output, self.gt)
|
200 |
+
l_g_total += l_g_percep
|
201 |
+
loss_dict['l_g_percep'] = l_g_percep
|
202 |
+
|
203 |
+
# gan loss
|
204 |
+
if current_iter > self.net_d_start_iter:
|
205 |
+
fake_g_pred = self.net_d(self.output)
|
206 |
+
l_g_gan = self.cri_gan(fake_g_pred, True, is_disc=False)
|
207 |
+
recon_loss = l_g_pix + l_g_percep
|
208 |
+
if not self.fix_generator:
|
209 |
+
last_layer = self.net_g.module.generator.blocks[-1].weight
|
210 |
+
d_weight = self.calculate_adaptive_weight(recon_loss, l_g_gan, last_layer, disc_weight_max=1.0)
|
211 |
+
else:
|
212 |
+
largest_fuse_size = self.opt['network_g']['connect_list'][-1]
|
213 |
+
last_layer = self.net_g.module.fuse_convs_dict[largest_fuse_size].shift[-1].weight
|
214 |
+
d_weight = self.calculate_adaptive_weight(recon_loss, l_g_gan, last_layer, disc_weight_max=1.0)
|
215 |
+
|
216 |
+
d_weight *= self.scale_adaptive_gan_weight # 0.8
|
217 |
+
loss_dict['d_weight'] = d_weight
|
218 |
+
l_g_total += d_weight * l_g_gan
|
219 |
+
loss_dict['l_g_gan'] = d_weight * l_g_gan
|
220 |
+
|
221 |
+
l_g_total.backward()
|
222 |
+
self.optimizer_g.step()
|
223 |
+
|
224 |
+
if self.ema_decay > 0:
|
225 |
+
self.model_ema(decay=self.ema_decay)
|
226 |
+
|
227 |
+
# optimize net_d
|
228 |
+
if not large_de:
|
229 |
+
if current_iter > self.net_d_start_iter:
|
230 |
+
for p in self.net_d.parameters():
|
231 |
+
p.requires_grad = True
|
232 |
+
|
233 |
+
self.optimizer_d.zero_grad()
|
234 |
+
# real
|
235 |
+
real_d_pred = self.net_d(self.gt)
|
236 |
+
l_d_real = self.cri_gan(real_d_pred, True, is_disc=True)
|
237 |
+
loss_dict['l_d_real'] = l_d_real
|
238 |
+
loss_dict['out_d_real'] = torch.mean(real_d_pred.detach())
|
239 |
+
l_d_real.backward()
|
240 |
+
# fake
|
241 |
+
fake_d_pred = self.net_d(self.output.detach())
|
242 |
+
l_d_fake = self.cri_gan(fake_d_pred, False, is_disc=True)
|
243 |
+
loss_dict['l_d_fake'] = l_d_fake
|
244 |
+
loss_dict['out_d_fake'] = torch.mean(fake_d_pred.detach())
|
245 |
+
l_d_fake.backward()
|
246 |
+
|
247 |
+
self.optimizer_d.step()
|
248 |
+
|
249 |
+
self.log_dict = self.reduce_loss_dict(loss_dict)
|
250 |
+
|
251 |
+
|
252 |
+
def test(self):
|
253 |
+
with torch.no_grad():
|
254 |
+
if hasattr(self, 'net_g_ema'):
|
255 |
+
self.net_g_ema.eval()
|
256 |
+
self.output, _, _ = self.net_g_ema(self.input, w=1)
|
257 |
+
else:
|
258 |
+
logger = get_root_logger()
|
259 |
+
logger.warning('Do not have self.net_g_ema, use self.net_g.')
|
260 |
+
self.net_g.eval()
|
261 |
+
self.output, _, _ = self.net_g(self.input, w=1)
|
262 |
+
self.net_g.train()
|
263 |
+
|
264 |
+
|
265 |
+
def dist_validation(self, dataloader, current_iter, tb_logger, save_img):
|
266 |
+
if self.opt['rank'] == 0:
|
267 |
+
self.nondist_validation(dataloader, current_iter, tb_logger, save_img)
|
268 |
+
|
269 |
+
|
270 |
+
def nondist_validation(self, dataloader, current_iter, tb_logger, save_img):
|
271 |
+
dataset_name = dataloader.dataset.opt['name']
|
272 |
+
with_metrics = self.opt['val'].get('metrics') is not None
|
273 |
+
if with_metrics:
|
274 |
+
self.metric_results = {metric: 0 for metric in self.opt['val']['metrics'].keys()}
|
275 |
+
pbar = tqdm(total=len(dataloader), unit='image')
|
276 |
+
|
277 |
+
for idx, val_data in enumerate(dataloader):
|
278 |
+
img_name = osp.splitext(osp.basename(val_data['lq_path'][0]))[0]
|
279 |
+
self.feed_data(val_data)
|
280 |
+
self.test()
|
281 |
+
|
282 |
+
visuals = self.get_current_visuals()
|
283 |
+
sr_img = tensor2img([visuals['result']])
|
284 |
+
if 'gt' in visuals:
|
285 |
+
gt_img = tensor2img([visuals['gt']])
|
286 |
+
del self.gt
|
287 |
+
|
288 |
+
# tentative for out of GPU memory
|
289 |
+
del self.lq
|
290 |
+
del self.output
|
291 |
+
torch.cuda.empty_cache()
|
292 |
+
|
293 |
+
if save_img:
|
294 |
+
if self.opt['is_train']:
|
295 |
+
save_img_path = osp.join(self.opt['path']['visualization'], img_name,
|
296 |
+
f'{img_name}_{current_iter}.png')
|
297 |
+
else:
|
298 |
+
if self.opt['val']['suffix']:
|
299 |
+
save_img_path = osp.join(self.opt['path']['visualization'], dataset_name,
|
300 |
+
f'{img_name}_{self.opt["val"]["suffix"]}.png')
|
301 |
+
else:
|
302 |
+
save_img_path = osp.join(self.opt['path']['visualization'], dataset_name,
|
303 |
+
f'{img_name}_{self.opt["name"]}.png')
|
304 |
+
imwrite(sr_img, save_img_path)
|
305 |
+
|
306 |
+
if with_metrics:
|
307 |
+
# calculate metrics
|
308 |
+
for name, opt_ in self.opt['val']['metrics'].items():
|
309 |
+
metric_data = dict(img1=sr_img, img2=gt_img)
|
310 |
+
self.metric_results[name] += calculate_metric(metric_data, opt_)
|
311 |
+
pbar.update(1)
|
312 |
+
pbar.set_description(f'Test {img_name}')
|
313 |
+
pbar.close()
|
314 |
+
|
315 |
+
if with_metrics:
|
316 |
+
for metric in self.metric_results.keys():
|
317 |
+
self.metric_results[metric] /= (idx + 1)
|
318 |
+
|
319 |
+
self._log_validation_metric_values(current_iter, dataset_name, tb_logger)
|
320 |
+
|
321 |
+
|
322 |
+
def _log_validation_metric_values(self, current_iter, dataset_name, tb_logger):
|
323 |
+
log_str = f'Validation {dataset_name}\n'
|
324 |
+
for metric, value in self.metric_results.items():
|
325 |
+
log_str += f'\t # {metric}: {value:.4f}\n'
|
326 |
+
logger = get_root_logger()
|
327 |
+
logger.info(log_str)
|
328 |
+
if tb_logger:
|
329 |
+
for metric, value in self.metric_results.items():
|
330 |
+
tb_logger.add_scalar(f'metrics/{metric}', value, current_iter)
|
331 |
+
|
332 |
+
|
333 |
+
def get_current_visuals(self):
|
334 |
+
out_dict = OrderedDict()
|
335 |
+
out_dict['gt'] = self.gt.detach().cpu()
|
336 |
+
out_dict['result'] = self.output.detach().cpu()
|
337 |
+
return out_dict
|
338 |
+
|
339 |
+
|
340 |
+
def save(self, epoch, current_iter):
|
341 |
+
if self.ema_decay > 0:
|
342 |
+
self.save_network([self.net_g, self.net_g_ema], 'net_g', current_iter, param_key=['params', 'params_ema'])
|
343 |
+
else:
|
344 |
+
self.save_network(self.net_g, 'net_g', current_iter)
|
345 |
+
self.save_network(self.net_d, 'net_d', current_iter)
|
346 |
+
self.save_training_state(epoch, current_iter)
|
basicsr/models/codeformer_model.py
ADDED
@@ -0,0 +1,332 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from collections import OrderedDict
|
3 |
+
from os import path as osp
|
4 |
+
from tqdm import tqdm
|
5 |
+
|
6 |
+
from basicsr.archs import build_network
|
7 |
+
from basicsr.losses import build_loss
|
8 |
+
from basicsr.metrics import calculate_metric
|
9 |
+
from basicsr.utils import get_root_logger, imwrite, tensor2img
|
10 |
+
from basicsr.utils.registry import MODEL_REGISTRY
|
11 |
+
import torch.nn.functional as F
|
12 |
+
from .sr_model import SRModel
|
13 |
+
|
14 |
+
|
15 |
+
@MODEL_REGISTRY.register()
|
16 |
+
class CodeFormerModel(SRModel):
|
17 |
+
def feed_data(self, data):
|
18 |
+
self.gt = data['gt'].to(self.device)
|
19 |
+
self.input = data['in'].to(self.device)
|
20 |
+
self.b = self.gt.shape[0]
|
21 |
+
|
22 |
+
if 'latent_gt' in data:
|
23 |
+
self.idx_gt = data['latent_gt'].to(self.device)
|
24 |
+
self.idx_gt = self.idx_gt.view(self.b, -1)
|
25 |
+
else:
|
26 |
+
self.idx_gt = None
|
27 |
+
|
28 |
+
def init_training_settings(self):
|
29 |
+
logger = get_root_logger()
|
30 |
+
train_opt = self.opt['train']
|
31 |
+
|
32 |
+
self.ema_decay = train_opt.get('ema_decay', 0)
|
33 |
+
if self.ema_decay > 0:
|
34 |
+
logger.info(f'Use Exponential Moving Average with decay: {self.ema_decay}')
|
35 |
+
# define network net_g with Exponential Moving Average (EMA)
|
36 |
+
# net_g_ema is used only for testing on one GPU and saving
|
37 |
+
# There is no need to wrap with DistributedDataParallel
|
38 |
+
self.net_g_ema = build_network(self.opt['network_g']).to(self.device)
|
39 |
+
# load pretrained model
|
40 |
+
load_path = self.opt['path'].get('pretrain_network_g', None)
|
41 |
+
if load_path is not None:
|
42 |
+
self.load_network(self.net_g_ema, load_path, self.opt['path'].get('strict_load_g', True), 'params_ema')
|
43 |
+
else:
|
44 |
+
self.model_ema(0) # copy net_g weight
|
45 |
+
self.net_g_ema.eval()
|
46 |
+
|
47 |
+
if self.opt.get('network_vqgan', None) is not None and self.opt['datasets'].get('latent_gt_path') is None:
|
48 |
+
self.hq_vqgan_fix = build_network(self.opt['network_vqgan']).to(self.device)
|
49 |
+
self.hq_vqgan_fix.eval()
|
50 |
+
self.generate_idx_gt = True
|
51 |
+
for param in self.hq_vqgan_fix.parameters():
|
52 |
+
param.requires_grad = False
|
53 |
+
else:
|
54 |
+
self.generate_idx_gt = False
|
55 |
+
|
56 |
+
self.hq_feat_loss = train_opt.get('use_hq_feat_loss', True)
|
57 |
+
self.feat_loss_weight = train_opt.get('feat_loss_weight', 1.0)
|
58 |
+
self.cross_entropy_loss = train_opt.get('cross_entropy_loss', True)
|
59 |
+
self.entropy_loss_weight = train_opt.get('entropy_loss_weight', 0.5)
|
60 |
+
self.fidelity_weight = train_opt.get('fidelity_weight', 1.0)
|
61 |
+
self.scale_adaptive_gan_weight = train_opt.get('scale_adaptive_gan_weight', 0.8)
|
62 |
+
|
63 |
+
|
64 |
+
self.net_g.train()
|
65 |
+
# define network net_d
|
66 |
+
if self.fidelity_weight > 0:
|
67 |
+
self.net_d = build_network(self.opt['network_d'])
|
68 |
+
self.net_d = self.model_to_device(self.net_d)
|
69 |
+
self.print_network(self.net_d)
|
70 |
+
|
71 |
+
# load pretrained models
|
72 |
+
load_path = self.opt['path'].get('pretrain_network_d', None)
|
73 |
+
if load_path is not None:
|
74 |
+
self.load_network(self.net_d, load_path, self.opt['path'].get('strict_load_d', True))
|
75 |
+
|
76 |
+
self.net_d.train()
|
77 |
+
|
78 |
+
# define losses
|
79 |
+
if train_opt.get('pixel_opt'):
|
80 |
+
self.cri_pix = build_loss(train_opt['pixel_opt']).to(self.device)
|
81 |
+
else:
|
82 |
+
self.cri_pix = None
|
83 |
+
|
84 |
+
if train_opt.get('perceptual_opt'):
|
85 |
+
self.cri_perceptual = build_loss(train_opt['perceptual_opt']).to(self.device)
|
86 |
+
else:
|
87 |
+
self.cri_perceptual = None
|
88 |
+
|
89 |
+
if train_opt.get('gan_opt'):
|
90 |
+
self.cri_gan = build_loss(train_opt['gan_opt']).to(self.device)
|
91 |
+
|
92 |
+
|
93 |
+
self.fix_generator = train_opt.get('fix_generator', True)
|
94 |
+
logger.info(f'fix_generator: {self.fix_generator}')
|
95 |
+
|
96 |
+
self.net_g_start_iter = train_opt.get('net_g_start_iter', 0)
|
97 |
+
self.net_d_iters = train_opt.get('net_d_iters', 1)
|
98 |
+
self.net_d_start_iter = train_opt.get('net_d_start_iter', 0)
|
99 |
+
|
100 |
+
# set up optimizers and schedulers
|
101 |
+
self.setup_optimizers()
|
102 |
+
self.setup_schedulers()
|
103 |
+
|
104 |
+
def calculate_adaptive_weight(self, recon_loss, g_loss, last_layer, disc_weight_max):
|
105 |
+
recon_grads = torch.autograd.grad(recon_loss, last_layer, retain_graph=True)[0]
|
106 |
+
g_grads = torch.autograd.grad(g_loss, last_layer, retain_graph=True)[0]
|
107 |
+
|
108 |
+
d_weight = torch.norm(recon_grads) / (torch.norm(g_grads) + 1e-4)
|
109 |
+
d_weight = torch.clamp(d_weight, 0.0, disc_weight_max).detach()
|
110 |
+
return d_weight
|
111 |
+
|
112 |
+
def setup_optimizers(self):
|
113 |
+
train_opt = self.opt['train']
|
114 |
+
# optimizer g
|
115 |
+
optim_params_g = []
|
116 |
+
for k, v in self.net_g.named_parameters():
|
117 |
+
if v.requires_grad:
|
118 |
+
optim_params_g.append(v)
|
119 |
+
else:
|
120 |
+
logger = get_root_logger()
|
121 |
+
logger.warning(f'Params {k} will not be optimized.')
|
122 |
+
optim_type = train_opt['optim_g'].pop('type')
|
123 |
+
self.optimizer_g = self.get_optimizer(optim_type, optim_params_g, **train_opt['optim_g'])
|
124 |
+
self.optimizers.append(self.optimizer_g)
|
125 |
+
# optimizer d
|
126 |
+
if self.fidelity_weight > 0:
|
127 |
+
optim_type = train_opt['optim_d'].pop('type')
|
128 |
+
self.optimizer_d = self.get_optimizer(optim_type, self.net_d.parameters(), **train_opt['optim_d'])
|
129 |
+
self.optimizers.append(self.optimizer_d)
|
130 |
+
|
131 |
+
def gray_resize_for_identity(self, out, size=128):
|
132 |
+
out_gray = (0.2989 * out[:, 0, :, :] + 0.5870 * out[:, 1, :, :] + 0.1140 * out[:, 2, :, :])
|
133 |
+
out_gray = out_gray.unsqueeze(1)
|
134 |
+
out_gray = F.interpolate(out_gray, (size, size), mode='bilinear', align_corners=False)
|
135 |
+
return out_gray
|
136 |
+
|
137 |
+
def optimize_parameters(self, current_iter):
|
138 |
+
logger = get_root_logger()
|
139 |
+
# optimize net_g
|
140 |
+
for p in self.net_d.parameters():
|
141 |
+
p.requires_grad = False
|
142 |
+
|
143 |
+
self.optimizer_g.zero_grad()
|
144 |
+
|
145 |
+
if self.generate_idx_gt:
|
146 |
+
x = self.hq_vqgan_fix.encoder(self.gt)
|
147 |
+
output, _, quant_stats = self.hq_vqgan_fix.quantize(x)
|
148 |
+
min_encoding_indices = quant_stats['min_encoding_indices']
|
149 |
+
self.idx_gt = min_encoding_indices.view(self.b, -1)
|
150 |
+
|
151 |
+
if self.fidelity_weight > 0:
|
152 |
+
self.output, logits, lq_feat = self.net_g(self.input, w=self.fidelity_weight, detach_16=True)
|
153 |
+
else:
|
154 |
+
logits, lq_feat = self.net_g(self.input, w=0, code_only=True)
|
155 |
+
|
156 |
+
if self.hq_feat_loss:
|
157 |
+
# quant_feats
|
158 |
+
quant_feat_gt = self.net_g.module.quantize.get_codebook_feat(self.idx_gt, shape=[self.b,16,16,256])
|
159 |
+
|
160 |
+
l_g_total = 0
|
161 |
+
loss_dict = OrderedDict()
|
162 |
+
if current_iter % self.net_d_iters == 0 and current_iter > self.net_g_start_iter:
|
163 |
+
# hq_feat_loss
|
164 |
+
if self.hq_feat_loss: # codebook loss
|
165 |
+
l_feat_encoder = torch.mean((quant_feat_gt.detach()-lq_feat)**2) * self.feat_loss_weight
|
166 |
+
l_g_total += l_feat_encoder
|
167 |
+
loss_dict['l_feat_encoder'] = l_feat_encoder
|
168 |
+
|
169 |
+
# cross_entropy_loss
|
170 |
+
if self.cross_entropy_loss:
|
171 |
+
# b(hw)n -> bn(hw)
|
172 |
+
cross_entropy_loss = F.cross_entropy(logits.permute(0, 2, 1), self.idx_gt) * self.entropy_loss_weight
|
173 |
+
l_g_total += cross_entropy_loss
|
174 |
+
loss_dict['cross_entropy_loss'] = cross_entropy_loss
|
175 |
+
|
176 |
+
if self.fidelity_weight > 0: # when fidelity_weight == 0 don't need image-level loss
|
177 |
+
# pixel loss
|
178 |
+
if self.cri_pix:
|
179 |
+
l_g_pix = self.cri_pix(self.output, self.gt)
|
180 |
+
l_g_total += l_g_pix
|
181 |
+
loss_dict['l_g_pix'] = l_g_pix
|
182 |
+
|
183 |
+
# perceptual loss
|
184 |
+
if self.cri_perceptual:
|
185 |
+
l_g_percep = self.cri_perceptual(self.output, self.gt)
|
186 |
+
l_g_total += l_g_percep
|
187 |
+
loss_dict['l_g_percep'] = l_g_percep
|
188 |
+
|
189 |
+
# gan loss
|
190 |
+
if current_iter > self.net_d_start_iter:
|
191 |
+
fake_g_pred = self.net_d(self.output)
|
192 |
+
l_g_gan = self.cri_gan(fake_g_pred, True, is_disc=False)
|
193 |
+
recon_loss = l_g_pix + l_g_percep
|
194 |
+
if not self.fix_generator:
|
195 |
+
last_layer = self.net_g.module.generator.blocks[-1].weight
|
196 |
+
d_weight = self.calculate_adaptive_weight(recon_loss, l_g_gan, last_layer, disc_weight_max=1.0)
|
197 |
+
else:
|
198 |
+
largest_fuse_size = self.opt['network_g']['connect_list'][-1]
|
199 |
+
last_layer = self.net_g.module.fuse_convs_dict[largest_fuse_size].shift[-1].weight
|
200 |
+
d_weight = self.calculate_adaptive_weight(recon_loss, l_g_gan, last_layer, disc_weight_max=1.0)
|
201 |
+
|
202 |
+
d_weight *= self.scale_adaptive_gan_weight # 0.8
|
203 |
+
loss_dict['d_weight'] = d_weight
|
204 |
+
l_g_total += d_weight * l_g_gan
|
205 |
+
loss_dict['l_g_gan'] = d_weight * l_g_gan
|
206 |
+
|
207 |
+
l_g_total.backward()
|
208 |
+
self.optimizer_g.step()
|
209 |
+
|
210 |
+
if self.ema_decay > 0:
|
211 |
+
self.model_ema(decay=self.ema_decay)
|
212 |
+
|
213 |
+
# optimize net_d
|
214 |
+
if current_iter > self.net_d_start_iter and self.fidelity_weight > 0:
|
215 |
+
for p in self.net_d.parameters():
|
216 |
+
p.requires_grad = True
|
217 |
+
|
218 |
+
self.optimizer_d.zero_grad()
|
219 |
+
# real
|
220 |
+
real_d_pred = self.net_d(self.gt)
|
221 |
+
l_d_real = self.cri_gan(real_d_pred, True, is_disc=True)
|
222 |
+
loss_dict['l_d_real'] = l_d_real
|
223 |
+
loss_dict['out_d_real'] = torch.mean(real_d_pred.detach())
|
224 |
+
l_d_real.backward()
|
225 |
+
# fake
|
226 |
+
fake_d_pred = self.net_d(self.output.detach())
|
227 |
+
l_d_fake = self.cri_gan(fake_d_pred, False, is_disc=True)
|
228 |
+
loss_dict['l_d_fake'] = l_d_fake
|
229 |
+
loss_dict['out_d_fake'] = torch.mean(fake_d_pred.detach())
|
230 |
+
l_d_fake.backward()
|
231 |
+
|
232 |
+
self.optimizer_d.step()
|
233 |
+
|
234 |
+
self.log_dict = self.reduce_loss_dict(loss_dict)
|
235 |
+
|
236 |
+
|
237 |
+
def test(self):
|
238 |
+
with torch.no_grad():
|
239 |
+
if hasattr(self, 'net_g_ema'):
|
240 |
+
self.net_g_ema.eval()
|
241 |
+
self.output, _, _ = self.net_g_ema(self.input, w=self.fidelity_weight)
|
242 |
+
else:
|
243 |
+
logger = get_root_logger()
|
244 |
+
logger.warning('Do not have self.net_g_ema, use self.net_g.')
|
245 |
+
self.net_g.eval()
|
246 |
+
self.output, _, _ = self.net_g(self.input, w=self.fidelity_weight)
|
247 |
+
self.net_g.train()
|
248 |
+
|
249 |
+
|
250 |
+
def dist_validation(self, dataloader, current_iter, tb_logger, save_img):
|
251 |
+
if self.opt['rank'] == 0:
|
252 |
+
self.nondist_validation(dataloader, current_iter, tb_logger, save_img)
|
253 |
+
|
254 |
+
|
255 |
+
def nondist_validation(self, dataloader, current_iter, tb_logger, save_img):
|
256 |
+
dataset_name = dataloader.dataset.opt['name']
|
257 |
+
with_metrics = self.opt['val'].get('metrics') is not None
|
258 |
+
if with_metrics:
|
259 |
+
self.metric_results = {metric: 0 for metric in self.opt['val']['metrics'].keys()}
|
260 |
+
pbar = tqdm(total=len(dataloader), unit='image')
|
261 |
+
|
262 |
+
for idx, val_data in enumerate(dataloader):
|
263 |
+
img_name = osp.splitext(osp.basename(val_data['lq_path'][0]))[0]
|
264 |
+
self.feed_data(val_data)
|
265 |
+
self.test()
|
266 |
+
|
267 |
+
visuals = self.get_current_visuals()
|
268 |
+
sr_img = tensor2img([visuals['result']])
|
269 |
+
if 'gt' in visuals:
|
270 |
+
gt_img = tensor2img([visuals['gt']])
|
271 |
+
del self.gt
|
272 |
+
|
273 |
+
# tentative for out of GPU memory
|
274 |
+
del self.lq
|
275 |
+
del self.output
|
276 |
+
torch.cuda.empty_cache()
|
277 |
+
|
278 |
+
if save_img:
|
279 |
+
if self.opt['is_train']:
|
280 |
+
save_img_path = osp.join(self.opt['path']['visualization'], img_name,
|
281 |
+
f'{img_name}_{current_iter}.png')
|
282 |
+
else:
|
283 |
+
if self.opt['val']['suffix']:
|
284 |
+
save_img_path = osp.join(self.opt['path']['visualization'], dataset_name,
|
285 |
+
f'{img_name}_{self.opt["val"]["suffix"]}.png')
|
286 |
+
else:
|
287 |
+
save_img_path = osp.join(self.opt['path']['visualization'], dataset_name,
|
288 |
+
f'{img_name}_{self.opt["name"]}.png')
|
289 |
+
imwrite(sr_img, save_img_path)
|
290 |
+
|
291 |
+
if with_metrics:
|
292 |
+
# calculate metrics
|
293 |
+
for name, opt_ in self.opt['val']['metrics'].items():
|
294 |
+
metric_data = dict(img1=sr_img, img2=gt_img)
|
295 |
+
self.metric_results[name] += calculate_metric(metric_data, opt_)
|
296 |
+
pbar.update(1)
|
297 |
+
pbar.set_description(f'Test {img_name}')
|
298 |
+
pbar.close()
|
299 |
+
|
300 |
+
if with_metrics:
|
301 |
+
for metric in self.metric_results.keys():
|
302 |
+
self.metric_results[metric] /= (idx + 1)
|
303 |
+
|
304 |
+
self._log_validation_metric_values(current_iter, dataset_name, tb_logger)
|
305 |
+
|
306 |
+
|
307 |
+
def _log_validation_metric_values(self, current_iter, dataset_name, tb_logger):
|
308 |
+
log_str = f'Validation {dataset_name}\n'
|
309 |
+
for metric, value in self.metric_results.items():
|
310 |
+
log_str += f'\t # {metric}: {value:.4f}\n'
|
311 |
+
logger = get_root_logger()
|
312 |
+
logger.info(log_str)
|
313 |
+
if tb_logger:
|
314 |
+
for metric, value in self.metric_results.items():
|
315 |
+
tb_logger.add_scalar(f'metrics/{metric}', value, current_iter)
|
316 |
+
|
317 |
+
|
318 |
+
def get_current_visuals(self):
|
319 |
+
out_dict = OrderedDict()
|
320 |
+
out_dict['gt'] = self.gt.detach().cpu()
|
321 |
+
out_dict['result'] = self.output.detach().cpu()
|
322 |
+
return out_dict
|
323 |
+
|
324 |
+
|
325 |
+
def save(self, epoch, current_iter):
|
326 |
+
if self.ema_decay > 0:
|
327 |
+
self.save_network([self.net_g, self.net_g_ema], 'net_g', current_iter, param_key=['params', 'params_ema'])
|
328 |
+
else:
|
329 |
+
self.save_network(self.net_g, 'net_g', current_iter)
|
330 |
+
if self.fidelity_weight > 0:
|
331 |
+
self.save_network(self.net_d, 'net_d', current_iter)
|
332 |
+
self.save_training_state(epoch, current_iter)
|
basicsr/models/sr_model.py
ADDED
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from collections import OrderedDict
|
3 |
+
from os import path as osp
|
4 |
+
from tqdm import tqdm
|
5 |
+
|
6 |
+
from basicsr.archs import build_network
|
7 |
+
from basicsr.losses import build_loss
|
8 |
+
from basicsr.metrics import calculate_metric
|
9 |
+
from basicsr.utils import get_root_logger, imwrite, tensor2img
|
10 |
+
from basicsr.utils.registry import MODEL_REGISTRY
|
11 |
+
from .base_model import BaseModel
|
12 |
+
|
13 |
+
@MODEL_REGISTRY.register()
|
14 |
+
class SRModel(BaseModel):
|
15 |
+
"""Base SR model for single image super-resolution."""
|
16 |
+
|
17 |
+
def __init__(self, opt):
|
18 |
+
super(SRModel, self).__init__(opt)
|
19 |
+
|
20 |
+
# define network
|
21 |
+
self.net_g = build_network(opt['network_g'])
|
22 |
+
self.net_g = self.model_to_device(self.net_g)
|
23 |
+
self.print_network(self.net_g)
|
24 |
+
|
25 |
+
# load pretrained models
|
26 |
+
load_path = self.opt['path'].get('pretrain_network_g', None)
|
27 |
+
if load_path is not None:
|
28 |
+
param_key = self.opt['path'].get('param_key_g', 'params')
|
29 |
+
self.load_network(self.net_g, load_path, self.opt['path'].get('strict_load_g', True), param_key)
|
30 |
+
|
31 |
+
if self.is_train:
|
32 |
+
self.init_training_settings()
|
33 |
+
|
34 |
+
def init_training_settings(self):
|
35 |
+
self.net_g.train()
|
36 |
+
train_opt = self.opt['train']
|
37 |
+
|
38 |
+
self.ema_decay = train_opt.get('ema_decay', 0)
|
39 |
+
if self.ema_decay > 0:
|
40 |
+
logger = get_root_logger()
|
41 |
+
logger.info(f'Use Exponential Moving Average with decay: {self.ema_decay}')
|
42 |
+
# define network net_g with Exponential Moving Average (EMA)
|
43 |
+
# net_g_ema is used only for testing on one GPU and saving
|
44 |
+
# There is no need to wrap with DistributedDataParallel
|
45 |
+
self.net_g_ema = build_network(self.opt['network_g']).to(self.device)
|
46 |
+
# load pretrained model
|
47 |
+
load_path = self.opt['path'].get('pretrain_network_g', None)
|
48 |
+
if load_path is not None:
|
49 |
+
self.load_network(self.net_g_ema, load_path, self.opt['path'].get('strict_load_g', True), 'params_ema')
|
50 |
+
else:
|
51 |
+
self.model_ema(0) # copy net_g weight
|
52 |
+
self.net_g_ema.eval()
|
53 |
+
|
54 |
+
# define losses
|
55 |
+
if train_opt.get('pixel_opt'):
|
56 |
+
self.cri_pix = build_loss(train_opt['pixel_opt']).to(self.device)
|
57 |
+
else:
|
58 |
+
self.cri_pix = None
|
59 |
+
|
60 |
+
if train_opt.get('perceptual_opt'):
|
61 |
+
self.cri_perceptual = build_loss(train_opt['perceptual_opt']).to(self.device)
|
62 |
+
else:
|
63 |
+
self.cri_perceptual = None
|
64 |
+
|
65 |
+
if self.cri_pix is None and self.cri_perceptual is None:
|
66 |
+
raise ValueError('Both pixel and perceptual losses are None.')
|
67 |
+
|
68 |
+
# set up optimizers and schedulers
|
69 |
+
self.setup_optimizers()
|
70 |
+
self.setup_schedulers()
|
71 |
+
|
72 |
+
def setup_optimizers(self):
|
73 |
+
train_opt = self.opt['train']
|
74 |
+
optim_params = []
|
75 |
+
for k, v in self.net_g.named_parameters():
|
76 |
+
if v.requires_grad:
|
77 |
+
optim_params.append(v)
|
78 |
+
else:
|
79 |
+
logger = get_root_logger()
|
80 |
+
logger.warning(f'Params {k} will not be optimized.')
|
81 |
+
|
82 |
+
optim_type = train_opt['optim_g'].pop('type')
|
83 |
+
self.optimizer_g = self.get_optimizer(optim_type, optim_params, **train_opt['optim_g'])
|
84 |
+
self.optimizers.append(self.optimizer_g)
|
85 |
+
|
86 |
+
def feed_data(self, data):
|
87 |
+
self.lq = data['lq'].to(self.device)
|
88 |
+
if 'gt' in data:
|
89 |
+
self.gt = data['gt'].to(self.device)
|
90 |
+
|
91 |
+
def optimize_parameters(self, current_iter):
|
92 |
+
self.optimizer_g.zero_grad()
|
93 |
+
self.output = self.net_g(self.lq)
|
94 |
+
|
95 |
+
l_total = 0
|
96 |
+
loss_dict = OrderedDict()
|
97 |
+
# pixel loss
|
98 |
+
if self.cri_pix:
|
99 |
+
l_pix = self.cri_pix(self.output, self.gt)
|
100 |
+
l_total += l_pix
|
101 |
+
loss_dict['l_pix'] = l_pix
|
102 |
+
# perceptual loss
|
103 |
+
if self.cri_perceptual:
|
104 |
+
l_percep, l_style = self.cri_perceptual(self.output, self.gt)
|
105 |
+
if l_percep is not None:
|
106 |
+
l_total += l_percep
|
107 |
+
loss_dict['l_percep'] = l_percep
|
108 |
+
if l_style is not None:
|
109 |
+
l_total += l_style
|
110 |
+
loss_dict['l_style'] = l_style
|
111 |
+
|
112 |
+
l_total.backward()
|
113 |
+
self.optimizer_g.step()
|
114 |
+
|
115 |
+
self.log_dict = self.reduce_loss_dict(loss_dict)
|
116 |
+
|
117 |
+
if self.ema_decay > 0:
|
118 |
+
self.model_ema(decay=self.ema_decay)
|
119 |
+
|
120 |
+
def test(self):
|
121 |
+
if hasattr(self, 'ema_decay'):
|
122 |
+
self.net_g_ema.eval()
|
123 |
+
with torch.no_grad():
|
124 |
+
self.output = self.net_g_ema(self.lq)
|
125 |
+
else:
|
126 |
+
self.net_g.eval()
|
127 |
+
with torch.no_grad():
|
128 |
+
self.output = self.net_g(self.lq)
|
129 |
+
self.net_g.train()
|
130 |
+
|
131 |
+
def dist_validation(self, dataloader, current_iter, tb_logger, save_img):
|
132 |
+
if self.opt['rank'] == 0:
|
133 |
+
self.nondist_validation(dataloader, current_iter, tb_logger, save_img)
|
134 |
+
|
135 |
+
def nondist_validation(self, dataloader, current_iter, tb_logger, save_img):
|
136 |
+
dataset_name = dataloader.dataset.opt['name']
|
137 |
+
with_metrics = self.opt['val'].get('metrics') is not None
|
138 |
+
if with_metrics:
|
139 |
+
self.metric_results = {metric: 0 for metric in self.opt['val']['metrics'].keys()}
|
140 |
+
pbar = tqdm(total=len(dataloader), unit='image')
|
141 |
+
|
142 |
+
for idx, val_data in enumerate(dataloader):
|
143 |
+
img_name = osp.splitext(osp.basename(val_data['lq_path'][0]))[0]
|
144 |
+
self.feed_data(val_data)
|
145 |
+
self.test()
|
146 |
+
|
147 |
+
visuals = self.get_current_visuals()
|
148 |
+
sr_img = tensor2img([visuals['result']])
|
149 |
+
if 'gt' in visuals:
|
150 |
+
gt_img = tensor2img([visuals['gt']])
|
151 |
+
del self.gt
|
152 |
+
|
153 |
+
# tentative for out of GPU memory
|
154 |
+
del self.lq
|
155 |
+
del self.output
|
156 |
+
torch.cuda.empty_cache()
|
157 |
+
|
158 |
+
if save_img:
|
159 |
+
if self.opt['is_train']:
|
160 |
+
save_img_path = osp.join(self.opt['path']['visualization'], img_name,
|
161 |
+
f'{img_name}_{current_iter}.png')
|
162 |
+
else:
|
163 |
+
if self.opt['val']['suffix']:
|
164 |
+
save_img_path = osp.join(self.opt['path']['visualization'], dataset_name,
|
165 |
+
f'{img_name}_{self.opt["val"]["suffix"]}.png')
|
166 |
+
else:
|
167 |
+
save_img_path = osp.join(self.opt['path']['visualization'], dataset_name,
|
168 |
+
f'{img_name}_{self.opt["name"]}.png')
|
169 |
+
imwrite(sr_img, save_img_path)
|
170 |
+
|
171 |
+
if with_metrics:
|
172 |
+
# calculate metrics
|
173 |
+
for name, opt_ in self.opt['val']['metrics'].items():
|
174 |
+
metric_data = dict(img1=sr_img, img2=gt_img)
|
175 |
+
self.metric_results[name] += calculate_metric(metric_data, opt_)
|
176 |
+
pbar.update(1)
|
177 |
+
pbar.set_description(f'Test {img_name}')
|
178 |
+
pbar.close()
|
179 |
+
|
180 |
+
if with_metrics:
|
181 |
+
for metric in self.metric_results.keys():
|
182 |
+
self.metric_results[metric] /= (idx + 1)
|
183 |
+
|
184 |
+
self._log_validation_metric_values(current_iter, dataset_name, tb_logger)
|
185 |
+
|
186 |
+
def _log_validation_metric_values(self, current_iter, dataset_name, tb_logger):
|
187 |
+
log_str = f'Validation {dataset_name}\n'
|
188 |
+
for metric, value in self.metric_results.items():
|
189 |
+
log_str += f'\t # {metric}: {value:.4f}\n'
|
190 |
+
logger = get_root_logger()
|
191 |
+
logger.info(log_str)
|
192 |
+
if tb_logger:
|
193 |
+
for metric, value in self.metric_results.items():
|
194 |
+
tb_logger.add_scalar(f'metrics/{metric}', value, current_iter)
|
195 |
+
|
196 |
+
def get_current_visuals(self):
|
197 |
+
out_dict = OrderedDict()
|
198 |
+
out_dict['lq'] = self.lq.detach().cpu()
|
199 |
+
out_dict['result'] = self.output.detach().cpu()
|
200 |
+
if hasattr(self, 'gt'):
|
201 |
+
out_dict['gt'] = self.gt.detach().cpu()
|
202 |
+
return out_dict
|
203 |
+
|
204 |
+
def save(self, epoch, current_iter):
|
205 |
+
if hasattr(self, 'ema_decay'):
|
206 |
+
self.save_network([self.net_g, self.net_g_ema], 'net_g', current_iter, param_key=['params', 'params_ema'])
|
207 |
+
else:
|
208 |
+
self.save_network(self.net_g, 'net_g', current_iter)
|
209 |
+
self.save_training_state(epoch, current_iter)
|
basicsr/models/vqgan_model.py
ADDED
@@ -0,0 +1,285 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from collections import OrderedDict
|
3 |
+
from os import path as osp
|
4 |
+
from tqdm import tqdm
|
5 |
+
|
6 |
+
from basicsr.archs import build_network
|
7 |
+
from basicsr.losses import build_loss
|
8 |
+
from basicsr.metrics import calculate_metric
|
9 |
+
from basicsr.utils import get_root_logger, imwrite, tensor2img
|
10 |
+
from basicsr.utils.registry import MODEL_REGISTRY
|
11 |
+
import torch.nn.functional as F
|
12 |
+
from .sr_model import SRModel
|
13 |
+
|
14 |
+
|
15 |
+
@MODEL_REGISTRY.register()
|
16 |
+
class VQGANModel(SRModel):
|
17 |
+
def feed_data(self, data):
|
18 |
+
self.gt = data['gt'].to(self.device)
|
19 |
+
self.b = self.gt.shape[0]
|
20 |
+
|
21 |
+
|
22 |
+
def init_training_settings(self):
|
23 |
+
logger = get_root_logger()
|
24 |
+
train_opt = self.opt['train']
|
25 |
+
|
26 |
+
self.ema_decay = train_opt.get('ema_decay', 0)
|
27 |
+
if self.ema_decay > 0:
|
28 |
+
logger.info(f'Use Exponential Moving Average with decay: {self.ema_decay}')
|
29 |
+
# define network net_g with Exponential Moving Average (EMA)
|
30 |
+
# net_g_ema is used only for testing on one GPU and saving
|
31 |
+
# There is no need to wrap with DistributedDataParallel
|
32 |
+
self.net_g_ema = build_network(self.opt['network_g']).to(self.device)
|
33 |
+
# load pretrained model
|
34 |
+
load_path = self.opt['path'].get('pretrain_network_g', None)
|
35 |
+
if load_path is not None:
|
36 |
+
self.load_network(self.net_g_ema, load_path, self.opt['path'].get('strict_load_g', True), 'params_ema')
|
37 |
+
else:
|
38 |
+
self.model_ema(0) # copy net_g weight
|
39 |
+
self.net_g_ema.eval()
|
40 |
+
|
41 |
+
# define network net_d
|
42 |
+
self.net_d = build_network(self.opt['network_d'])
|
43 |
+
self.net_d = self.model_to_device(self.net_d)
|
44 |
+
self.print_network(self.net_d)
|
45 |
+
|
46 |
+
# load pretrained models
|
47 |
+
load_path = self.opt['path'].get('pretrain_network_d', None)
|
48 |
+
if load_path is not None:
|
49 |
+
self.load_network(self.net_d, load_path, self.opt['path'].get('strict_load_d', True))
|
50 |
+
|
51 |
+
self.net_g.train()
|
52 |
+
self.net_d.train()
|
53 |
+
|
54 |
+
# define losses
|
55 |
+
if train_opt.get('pixel_opt'):
|
56 |
+
self.cri_pix = build_loss(train_opt['pixel_opt']).to(self.device)
|
57 |
+
else:
|
58 |
+
self.cri_pix = None
|
59 |
+
|
60 |
+
if train_opt.get('perceptual_opt'):
|
61 |
+
self.cri_perceptual = build_loss(train_opt['perceptual_opt']).to(self.device)
|
62 |
+
else:
|
63 |
+
self.cri_perceptual = None
|
64 |
+
|
65 |
+
if train_opt.get('gan_opt'):
|
66 |
+
self.cri_gan = build_loss(train_opt['gan_opt']).to(self.device)
|
67 |
+
|
68 |
+
if train_opt.get('codebook_opt'):
|
69 |
+
self.l_weight_codebook = train_opt['codebook_opt'].get('loss_weight', 1.0)
|
70 |
+
else:
|
71 |
+
self.l_weight_codebook = 1.0
|
72 |
+
|
73 |
+
self.vqgan_quantizer = self.opt['network_g']['quantizer']
|
74 |
+
logger.info(f'vqgan_quantizer: {self.vqgan_quantizer}')
|
75 |
+
|
76 |
+
self.net_g_start_iter = train_opt.get('net_g_start_iter', 0)
|
77 |
+
self.net_d_iters = train_opt.get('net_d_iters', 1)
|
78 |
+
self.net_d_start_iter = train_opt.get('net_d_start_iter', 0)
|
79 |
+
self.disc_weight = train_opt.get('disc_weight', 0.8)
|
80 |
+
|
81 |
+
# set up optimizers and schedulers
|
82 |
+
self.setup_optimizers()
|
83 |
+
self.setup_schedulers()
|
84 |
+
|
85 |
+
def calculate_adaptive_weight(self, recon_loss, g_loss, last_layer, disc_weight_max):
|
86 |
+
recon_grads = torch.autograd.grad(recon_loss, last_layer, retain_graph=True)[0]
|
87 |
+
g_grads = torch.autograd.grad(g_loss, last_layer, retain_graph=True)[0]
|
88 |
+
|
89 |
+
d_weight = torch.norm(recon_grads) / (torch.norm(g_grads) + 1e-4)
|
90 |
+
d_weight = torch.clamp(d_weight, 0.0, disc_weight_max).detach()
|
91 |
+
return d_weight
|
92 |
+
|
93 |
+
def adopt_weight(self, weight, global_step, threshold=0, value=0.):
|
94 |
+
if global_step < threshold:
|
95 |
+
weight = value
|
96 |
+
return weight
|
97 |
+
|
98 |
+
def setup_optimizers(self):
|
99 |
+
train_opt = self.opt['train']
|
100 |
+
# optimizer g
|
101 |
+
optim_params_g = []
|
102 |
+
for k, v in self.net_g.named_parameters():
|
103 |
+
if v.requires_grad:
|
104 |
+
optim_params_g.append(v)
|
105 |
+
else:
|
106 |
+
logger = get_root_logger()
|
107 |
+
logger.warning(f'Params {k} will not be optimized.')
|
108 |
+
optim_type = train_opt['optim_g'].pop('type')
|
109 |
+
self.optimizer_g = self.get_optimizer(optim_type, optim_params_g, **train_opt['optim_g'])
|
110 |
+
self.optimizers.append(self.optimizer_g)
|
111 |
+
# optimizer d
|
112 |
+
optim_type = train_opt['optim_d'].pop('type')
|
113 |
+
self.optimizer_d = self.get_optimizer(optim_type, self.net_d.parameters(), **train_opt['optim_d'])
|
114 |
+
self.optimizers.append(self.optimizer_d)
|
115 |
+
|
116 |
+
|
117 |
+
def optimize_parameters(self, current_iter):
|
118 |
+
logger = get_root_logger()
|
119 |
+
loss_dict = OrderedDict()
|
120 |
+
if self.opt['network_g']['quantizer'] == 'gumbel':
|
121 |
+
self.net_g.module.quantize.temperature = max(1/16, ((-1/160000) * current_iter) + 1)
|
122 |
+
if current_iter%1000 == 0:
|
123 |
+
logger.info(f'temperature: {self.net_g.module.quantize.temperature}')
|
124 |
+
|
125 |
+
# optimize net_g
|
126 |
+
for p in self.net_d.parameters():
|
127 |
+
p.requires_grad = False
|
128 |
+
|
129 |
+
self.optimizer_g.zero_grad()
|
130 |
+
self.output, l_codebook, quant_stats = self.net_g(self.gt)
|
131 |
+
|
132 |
+
l_codebook = l_codebook*self.l_weight_codebook
|
133 |
+
|
134 |
+
l_g_total = 0
|
135 |
+
if current_iter % self.net_d_iters == 0 and current_iter > self.net_g_start_iter:
|
136 |
+
# pixel loss
|
137 |
+
if self.cri_pix:
|
138 |
+
l_g_pix = self.cri_pix(self.output, self.gt)
|
139 |
+
l_g_total += l_g_pix
|
140 |
+
loss_dict['l_g_pix'] = l_g_pix
|
141 |
+
# perceptual loss
|
142 |
+
if self.cri_perceptual:
|
143 |
+
l_g_percep = self.cri_perceptual(self.output, self.gt)
|
144 |
+
l_g_total += l_g_percep
|
145 |
+
loss_dict['l_g_percep'] = l_g_percep
|
146 |
+
|
147 |
+
# gan loss
|
148 |
+
if current_iter > self.net_d_start_iter:
|
149 |
+
# fake_g_pred = self.net_d(self.output_1024)
|
150 |
+
fake_g_pred = self.net_d(self.output)
|
151 |
+
l_g_gan = self.cri_gan(fake_g_pred, True, is_disc=False)
|
152 |
+
recon_loss = l_g_total
|
153 |
+
last_layer = self.net_g.module.generator.blocks[-1].weight
|
154 |
+
d_weight = self.calculate_adaptive_weight(recon_loss, l_g_gan, last_layer, disc_weight_max=1.0)
|
155 |
+
d_weight *= self.adopt_weight(1, current_iter, self.net_d_start_iter)
|
156 |
+
d_weight *= self.disc_weight # tamming setting 0.8
|
157 |
+
l_g_total += d_weight * l_g_gan
|
158 |
+
loss_dict['l_g_gan'] = d_weight * l_g_gan
|
159 |
+
|
160 |
+
l_g_total += l_codebook
|
161 |
+
loss_dict['l_codebook'] = l_codebook
|
162 |
+
|
163 |
+
l_g_total.backward()
|
164 |
+
self.optimizer_g.step()
|
165 |
+
|
166 |
+
# optimize net_d
|
167 |
+
if current_iter > self.net_d_start_iter:
|
168 |
+
for p in self.net_d.parameters():
|
169 |
+
p.requires_grad = True
|
170 |
+
|
171 |
+
self.optimizer_d.zero_grad()
|
172 |
+
# real
|
173 |
+
real_d_pred = self.net_d(self.gt)
|
174 |
+
l_d_real = self.cri_gan(real_d_pred, True, is_disc=True)
|
175 |
+
loss_dict['l_d_real'] = l_d_real
|
176 |
+
loss_dict['out_d_real'] = torch.mean(real_d_pred.detach())
|
177 |
+
l_d_real.backward()
|
178 |
+
# fake
|
179 |
+
fake_d_pred = self.net_d(self.output.detach())
|
180 |
+
l_d_fake = self.cri_gan(fake_d_pred, False, is_disc=True)
|
181 |
+
loss_dict['l_d_fake'] = l_d_fake
|
182 |
+
loss_dict['out_d_fake'] = torch.mean(fake_d_pred.detach())
|
183 |
+
l_d_fake.backward()
|
184 |
+
self.optimizer_d.step()
|
185 |
+
|
186 |
+
self.log_dict = self.reduce_loss_dict(loss_dict)
|
187 |
+
|
188 |
+
if self.ema_decay > 0:
|
189 |
+
self.model_ema(decay=self.ema_decay)
|
190 |
+
|
191 |
+
|
192 |
+
def test(self):
|
193 |
+
with torch.no_grad():
|
194 |
+
if hasattr(self, 'net_g_ema'):
|
195 |
+
self.net_g_ema.eval()
|
196 |
+
self.output, _, _ = self.net_g_ema(self.gt)
|
197 |
+
else:
|
198 |
+
logger = get_root_logger()
|
199 |
+
logger.warning('Do not have self.net_g_ema, use self.net_g.')
|
200 |
+
self.net_g.eval()
|
201 |
+
self.output, _, _ = self.net_g(self.gt)
|
202 |
+
self.net_g.train()
|
203 |
+
|
204 |
+
|
205 |
+
def dist_validation(self, dataloader, current_iter, tb_logger, save_img):
|
206 |
+
if self.opt['rank'] == 0:
|
207 |
+
self.nondist_validation(dataloader, current_iter, tb_logger, save_img)
|
208 |
+
|
209 |
+
|
210 |
+
def nondist_validation(self, dataloader, current_iter, tb_logger, save_img):
|
211 |
+
dataset_name = dataloader.dataset.opt['name']
|
212 |
+
with_metrics = self.opt['val'].get('metrics') is not None
|
213 |
+
if with_metrics:
|
214 |
+
self.metric_results = {metric: 0 for metric in self.opt['val']['metrics'].keys()}
|
215 |
+
pbar = tqdm(total=len(dataloader), unit='image')
|
216 |
+
|
217 |
+
for idx, val_data in enumerate(dataloader):
|
218 |
+
img_name = osp.splitext(osp.basename(val_data['lq_path'][0]))[0]
|
219 |
+
self.feed_data(val_data)
|
220 |
+
self.test()
|
221 |
+
|
222 |
+
visuals = self.get_current_visuals()
|
223 |
+
sr_img = tensor2img([visuals['result']])
|
224 |
+
if 'gt' in visuals:
|
225 |
+
gt_img = tensor2img([visuals['gt']])
|
226 |
+
del self.gt
|
227 |
+
|
228 |
+
# tentative for out of GPU memory
|
229 |
+
del self.lq
|
230 |
+
del self.output
|
231 |
+
torch.cuda.empty_cache()
|
232 |
+
|
233 |
+
if save_img:
|
234 |
+
if self.opt['is_train']:
|
235 |
+
save_img_path = osp.join(self.opt['path']['visualization'], img_name,
|
236 |
+
f'{img_name}_{current_iter}.png')
|
237 |
+
else:
|
238 |
+
if self.opt['val']['suffix']:
|
239 |
+
save_img_path = osp.join(self.opt['path']['visualization'], dataset_name,
|
240 |
+
f'{img_name}_{self.opt["val"]["suffix"]}.png')
|
241 |
+
else:
|
242 |
+
save_img_path = osp.join(self.opt['path']['visualization'], dataset_name,
|
243 |
+
f'{img_name}_{self.opt["name"]}.png')
|
244 |
+
imwrite(sr_img, save_img_path)
|
245 |
+
|
246 |
+
if with_metrics:
|
247 |
+
# calculate metrics
|
248 |
+
for name, opt_ in self.opt['val']['metrics'].items():
|
249 |
+
metric_data = dict(img1=sr_img, img2=gt_img)
|
250 |
+
self.metric_results[name] += calculate_metric(metric_data, opt_)
|
251 |
+
pbar.update(1)
|
252 |
+
pbar.set_description(f'Test {img_name}')
|
253 |
+
pbar.close()
|
254 |
+
|
255 |
+
if with_metrics:
|
256 |
+
for metric in self.metric_results.keys():
|
257 |
+
self.metric_results[metric] /= (idx + 1)
|
258 |
+
|
259 |
+
self._log_validation_metric_values(current_iter, dataset_name, tb_logger)
|
260 |
+
|
261 |
+
|
262 |
+
def _log_validation_metric_values(self, current_iter, dataset_name, tb_logger):
|
263 |
+
log_str = f'Validation {dataset_name}\n'
|
264 |
+
for metric, value in self.metric_results.items():
|
265 |
+
log_str += f'\t # {metric}: {value:.4f}\n'
|
266 |
+
logger = get_root_logger()
|
267 |
+
logger.info(log_str)
|
268 |
+
if tb_logger:
|
269 |
+
for metric, value in self.metric_results.items():
|
270 |
+
tb_logger.add_scalar(f'metrics/{metric}', value, current_iter)
|
271 |
+
|
272 |
+
|
273 |
+
def get_current_visuals(self):
|
274 |
+
out_dict = OrderedDict()
|
275 |
+
out_dict['gt'] = self.gt.detach().cpu()
|
276 |
+
out_dict['result'] = self.output.detach().cpu()
|
277 |
+
return out_dict
|
278 |
+
|
279 |
+
def save(self, epoch, current_iter):
|
280 |
+
if self.ema_decay > 0:
|
281 |
+
self.save_network([self.net_g, self.net_g_ema], 'net_g', current_iter, param_key=['params', 'params_ema'])
|
282 |
+
else:
|
283 |
+
self.save_network(self.net_g, 'net_g', current_iter)
|
284 |
+
self.save_network(self.net_d, 'net_d', current_iter)
|
285 |
+
self.save_training_state(epoch, current_iter)
|
docs/history_changelog.md
CHANGED
@@ -1,5 +1,6 @@
|
|
1 |
# History of Changelog
|
2 |
|
|
|
3 |
- **2023.04.09**: Add features of inpainting and colorization for cropped face images.
|
4 |
- **2023.02.10**: Include `dlib` as a new face detector option, it produces more accurate face identity.
|
5 |
- **2022.10.05**: Support video input `--input_path [YOUR_VIDEO.mp4]`. Try it to enhance your videos! :clapper:
|
|
|
1 |
# History of Changelog
|
2 |
|
3 |
+
- **2023.04.19**: :whale: Training codes and config files are public available now.
|
4 |
- **2023.04.09**: Add features of inpainting and colorization for cropped face images.
|
5 |
- **2023.02.10**: Include `dlib` as a new face detector option, it produces more accurate face identity.
|
6 |
- **2022.10.05**: Support video input `--input_path [YOUR_VIDEO.mp4]`. Try it to enhance your videos! :clapper:
|
docs/train.md
ADDED
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# :milky_way: Training Procedures
|
2 |
+
[English](train.md) **|** [简体中文](train_CN.md)
|
3 |
+
## Preparing Dataset
|
4 |
+
|
5 |
+
- Download training dataset: [FFHQ](https://github.com/NVlabs/ffhq-dataset)
|
6 |
+
|
7 |
+
---
|
8 |
+
|
9 |
+
## Training
|
10 |
+
|
11 |
+
#### 👾 Stage I - VQGAN
|
12 |
+
- Training VQGAN:
|
13 |
+
> python -m torch.distributed.launch --nproc_per_node=8 --master_port=4321 basicsr/train.py -opt options/VQGAN_512_ds32_nearest_stage1.yml --launcher pytorch
|
14 |
+
|
15 |
+
- After VQGAN training, you can pre-calculate code sequence for the training dataset to speed up the later training stages:
|
16 |
+
> python scripts/generate_latent_gt.py
|
17 |
+
|
18 |
+
- If you don't require training your own VQGAN, you can find pre-trained VQGAN and the corresponding code sequence in the folder of Releases v0.1.0: https://github.com/sczhou/CodeFormer/releases/tag/v0.1.0
|
19 |
+
|
20 |
+
#### 🚀 Stage II - CodeFormer (w=0)
|
21 |
+
- Training Code Sequence Prediction Module:
|
22 |
+
> python -m torch.distributed.launch --nproc_per_node=8 --master_port=4322 basicsr/train.py -opt options/CodeFormer_stage2.yml --launcher pytorch
|
23 |
+
|
24 |
+
#### 🛸 Stage III - CodeFormer (w=1)
|
25 |
+
- Training Controllable Module:
|
26 |
+
> python -m torch.distributed.launch --nproc_per_node=8 --master_port=4323 basicsr/train.py -opt options/CodeFormer_stage3.yml --launcher pytorch
|
27 |
+
|
28 |
+
- Pre-trained CodeFormer can be found in the folder of Releases v0.1.0: https://github.com/sczhou/CodeFormer/releases/tag/v0.1.0
|
29 |
+
|
30 |
+
---
|
31 |
+
|
32 |
+
:whale: The project was built using the framework [BasicSR](https://github.com/XPixelGroup/BasicSR). For detailed information on training, resuming, and other related topics, please refer to the documentation: https://github.com/XPixelGroup/BasicSR/blob/master/docs/TrainTest.md
|
docs/train_CN.md
ADDED
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# :milky_way: 训练文档
|
2 |
+
[English](train.md) **|** [简体中文](train_CN.md)
|
3 |
+
|
4 |
+
## 准备数据集
|
5 |
+
- 下载训练数据集: [FFHQ](https://github.com/NVlabs/ffhq-dataset)
|
6 |
+
|
7 |
+
---
|
8 |
+
|
9 |
+
## 训练
|
10 |
+
|
11 |
+
#### 👾 阶段 I - VQGAN
|
12 |
+
- 训练VQGAN:
|
13 |
+
> python -m torch.distributed.launch --nproc_per_node=8 --master_port=4321 basicsr/train.py -opt options/VQGAN_512_ds32_nearest_stage1.yml --launcher pytorch
|
14 |
+
|
15 |
+
- 训练完VQGAN后,可以通过下面代码预先获得训练数据集的密码本序列,从而加速后面阶段的训练过程:
|
16 |
+
> python scripts/generate_latent_gt.py
|
17 |
+
|
18 |
+
- 如果你不需要训练自己的VQGAN,可以在Release v0.1.0文档中找到预训练的VQGAN和对应的密码本序列: https://github.com/sczhou/CodeFormer/releases/tag/v0.1.0
|
19 |
+
|
20 |
+
#### 🚀 阶段 II - CodeFormer (w=0)
|
21 |
+
- 训练密码本训练预测模块:
|
22 |
+
> python -m torch.distributed.launch --nproc_per_node=8 --master_port=4322 basicsr/train.py -opt options/CodeFormer_stage2.yml --launcher pytorch
|
23 |
+
|
24 |
+
#### 🛸 阶段 III - CodeFormer (w=1)
|
25 |
+
- 训练可调模块:
|
26 |
+
> python -m torch.distributed.launch --nproc_per_node=8 --master_port=4323 basicsr/train.py -opt options/CodeFormer_stage3.yml --launcher pytorch
|
27 |
+
|
28 |
+
- 预训练CodeFormer模型可以在Releases v0.1.0文档里下载: https://github.com/sczhou/CodeFormer/releases/tag/v0.1.0
|
29 |
+
|
30 |
+
---
|
31 |
+
|
32 |
+
:whale: 该项目是基于[BasicSR](https://github.com/XPixelGroup/BasicSR)框架搭建,有关训练、Resume等详细介绍可以查看文档: https://github.com/XPixelGroup/BasicSR/blob/master/docs/TrainTest_CN.md
|
options/CodeFormer_colorization.yml
ADDED
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# general settings
|
2 |
+
name: CodeFormer_colorization
|
3 |
+
model_type: CodeFormerIdxModel
|
4 |
+
num_gpu: 8
|
5 |
+
manual_seed: 0
|
6 |
+
|
7 |
+
# dataset and data loader settings
|
8 |
+
datasets:
|
9 |
+
train:
|
10 |
+
name: FFHQ
|
11 |
+
type: FFHQBlindDataset
|
12 |
+
dataroot_gt: datasets/ffhq/ffhq_512
|
13 |
+
filename_tmpl: '{}'
|
14 |
+
io_backend:
|
15 |
+
type: disk
|
16 |
+
|
17 |
+
in_size: 512
|
18 |
+
gt_size: 512
|
19 |
+
mean: [0.5, 0.5, 0.5]
|
20 |
+
std: [0.5, 0.5, 0.5]
|
21 |
+
use_hflip: true
|
22 |
+
use_corrupt: true
|
23 |
+
latent_gt_path: ~
|
24 |
+
|
25 |
+
# large degradation in stageII
|
26 |
+
blur_kernel_size: 41
|
27 |
+
use_motion_kernel: false
|
28 |
+
motion_kernel_prob: 0.001
|
29 |
+
kernel_list: ['iso', 'aniso']
|
30 |
+
kernel_prob: [0.5, 0.5]
|
31 |
+
blur_sigma: [1, 15]
|
32 |
+
downsample_range: [4, 30]
|
33 |
+
noise_range: [0, 20]
|
34 |
+
jpeg_range: [30, 80]
|
35 |
+
|
36 |
+
# color jitter and gray
|
37 |
+
color_jitter_prob: 0.3
|
38 |
+
color_jitter_shift: 20
|
39 |
+
color_jitter_pt_prob: 0.3
|
40 |
+
gray_prob: 0.01
|
41 |
+
|
42 |
+
latent_gt_path: './experiments/pretrained_models/VQGAN/latent_gt_code1024.pth'
|
43 |
+
|
44 |
+
# data loader
|
45 |
+
num_worker_per_gpu: 2
|
46 |
+
batch_size_per_gpu: 4
|
47 |
+
dataset_enlarge_ratio: 100
|
48 |
+
prefetch_mode: ~
|
49 |
+
|
50 |
+
# val:
|
51 |
+
# name: CelebA-HQ-512
|
52 |
+
# type: PairedImageDataset
|
53 |
+
# dataroot_lq: datasets/faces/validation/lq
|
54 |
+
# dataroot_gt: datasets/faces/validation/gt
|
55 |
+
# io_backend:
|
56 |
+
# type: disk
|
57 |
+
# mean: [0.5, 0.5, 0.5]
|
58 |
+
# std: [0.5, 0.5, 0.5]
|
59 |
+
# scale: 1
|
60 |
+
|
61 |
+
# network structures
|
62 |
+
network_g:
|
63 |
+
type: CodeFormer
|
64 |
+
dim_embd: 512
|
65 |
+
n_head: 8
|
66 |
+
n_layers: 9
|
67 |
+
codebook_size: 1024
|
68 |
+
connect_list: ['32', '64', '128', '256']
|
69 |
+
fix_modules: ['quantize','generator']
|
70 |
+
vqgan_path: './experiments/pretrained_models/vqgan/vqgan_code1024.pth' # pretrained VQGAN
|
71 |
+
|
72 |
+
# path
|
73 |
+
path:
|
74 |
+
pretrain_network_g: ~
|
75 |
+
param_key_g: params_ema
|
76 |
+
strict_load_g: false
|
77 |
+
pretrain_network_d: ~
|
78 |
+
strict_load_d: true
|
79 |
+
resume_state: ~
|
80 |
+
|
81 |
+
# base_lr(4.5e-6)*bach_size(4)
|
82 |
+
train:
|
83 |
+
use_hq_feat_loss: true
|
84 |
+
feat_loss_weight: 1.0
|
85 |
+
cross_entropy_loss: true
|
86 |
+
entropy_loss_weight: 0.5
|
87 |
+
fidelity_weight: 0
|
88 |
+
|
89 |
+
optim_g:
|
90 |
+
type: Adam
|
91 |
+
lr: !!float 1e-4
|
92 |
+
weight_decay: 0
|
93 |
+
betas: [0.9, 0.99]
|
94 |
+
|
95 |
+
scheduler:
|
96 |
+
type: MultiStepLR
|
97 |
+
milestones: [400000, 450000]
|
98 |
+
gamma: 0.5
|
99 |
+
|
100 |
+
total_iter: 500000
|
101 |
+
|
102 |
+
warmup_iter: -1 # no warm up
|
103 |
+
ema_decay: 0.995
|
104 |
+
|
105 |
+
use_adaptive_weight: true
|
106 |
+
|
107 |
+
net_g_start_iter: 0
|
108 |
+
net_d_iters: 1
|
109 |
+
net_d_start_iter: 0
|
110 |
+
manual_seed: 0
|
111 |
+
|
112 |
+
# validation settings
|
113 |
+
val:
|
114 |
+
val_freq: !!float 5e10 # no validation
|
115 |
+
save_img: true
|
116 |
+
|
117 |
+
metrics:
|
118 |
+
psnr: # metric name, can be arbitrary
|
119 |
+
type: calculate_psnr
|
120 |
+
crop_border: 4
|
121 |
+
test_y_channel: false
|
122 |
+
|
123 |
+
# logging settings
|
124 |
+
logger:
|
125 |
+
print_freq: 100
|
126 |
+
save_checkpoint_freq: !!float 1e4
|
127 |
+
use_tb_logger: true
|
128 |
+
wandb:
|
129 |
+
project: ~
|
130 |
+
resume_id: ~
|
131 |
+
|
132 |
+
# dist training settings
|
133 |
+
dist_params:
|
134 |
+
backend: nccl
|
135 |
+
port: 29419
|
136 |
+
|
137 |
+
find_unused_parameters: true
|
options/CodeFormer_inpainting.yml
ADDED
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# general settings
|
2 |
+
name: CodeFormer_inpainting
|
3 |
+
model_type: CodeFormerModel
|
4 |
+
num_gpu: 4
|
5 |
+
manual_seed: 0
|
6 |
+
|
7 |
+
# dataset and data loader settings
|
8 |
+
datasets:
|
9 |
+
train:
|
10 |
+
name: FFHQ
|
11 |
+
type: FFHQBlindDataset
|
12 |
+
dataroot_gt: datasets/ffhq/ffhq_512
|
13 |
+
filename_tmpl: '{}'
|
14 |
+
io_backend:
|
15 |
+
type: disk
|
16 |
+
|
17 |
+
in_size: 512
|
18 |
+
gt_size: 512
|
19 |
+
mean: [0.5, 0.5, 0.5]
|
20 |
+
std: [0.5, 0.5, 0.5]
|
21 |
+
use_hflip: true
|
22 |
+
use_corrupt: false
|
23 |
+
gen_inpaint_mask: true
|
24 |
+
|
25 |
+
|
26 |
+
latent_gt_path: './experiments/pretrained_models/VQGAN/latent_gt_code1024.pth'
|
27 |
+
|
28 |
+
# data loader
|
29 |
+
num_worker_per_gpu: 2
|
30 |
+
batch_size_per_gpu: 3
|
31 |
+
dataset_enlarge_ratio: 100
|
32 |
+
prefetch_mode: ~
|
33 |
+
|
34 |
+
# val:
|
35 |
+
# name: CelebA-HQ-512
|
36 |
+
# type: PairedImageDataset
|
37 |
+
# dataroot_lq: datasets/faces/validation/lq
|
38 |
+
# dataroot_gt: datasets/faces/validation/gt
|
39 |
+
# io_backend:
|
40 |
+
# type: disk
|
41 |
+
# mean: [0.5, 0.5, 0.5]
|
42 |
+
# std: [0.5, 0.5, 0.5]
|
43 |
+
# scale: 1
|
44 |
+
|
45 |
+
# network structures
|
46 |
+
network_g:
|
47 |
+
type: CodeFormer
|
48 |
+
dim_embd: 512
|
49 |
+
n_head: 8
|
50 |
+
n_layers: 9
|
51 |
+
codebook_size: 1024
|
52 |
+
connect_list: ['32', '64', '128']
|
53 |
+
fix_modules: ['quantize','generator']
|
54 |
+
vqgan_path: './experiments/pretrained_models/vqgan/vqgan_code1024.pth' # pretrained VQGAN
|
55 |
+
|
56 |
+
network_d:
|
57 |
+
type: VQGANDiscriminator
|
58 |
+
nc: 3
|
59 |
+
ndf: 64
|
60 |
+
n_layers: 4
|
61 |
+
model_path: ~
|
62 |
+
|
63 |
+
# path
|
64 |
+
path:
|
65 |
+
pretrain_network_g: ~
|
66 |
+
param_key_g: params_ema
|
67 |
+
strict_load_g: true
|
68 |
+
pretrain_network_d: ~
|
69 |
+
strict_load_d: true
|
70 |
+
resume_state: ~
|
71 |
+
|
72 |
+
# base_lr(4.5e-6)*bach_size(4)
|
73 |
+
train:
|
74 |
+
use_hq_feat_loss: true
|
75 |
+
feat_loss_weight: 1.0
|
76 |
+
cross_entropy_loss: true
|
77 |
+
entropy_loss_weight: 0.5
|
78 |
+
scale_adaptive_gan_weight: 0.1
|
79 |
+
fidelity_weight: 1.0
|
80 |
+
|
81 |
+
optim_g:
|
82 |
+
type: Adam
|
83 |
+
lr: !!float 7e-5
|
84 |
+
weight_decay: 0
|
85 |
+
betas: [0.9, 0.99]
|
86 |
+
optim_d:
|
87 |
+
type: Adam
|
88 |
+
lr: !!float 7e-5
|
89 |
+
weight_decay: 0
|
90 |
+
betas: [0.9, 0.99]
|
91 |
+
|
92 |
+
scheduler:
|
93 |
+
type: MultiStepLR
|
94 |
+
milestones: [250000, 300000]
|
95 |
+
gamma: 0.5
|
96 |
+
|
97 |
+
total_iter: 300000
|
98 |
+
|
99 |
+
warmup_iter: -1 # no warm up
|
100 |
+
ema_decay: 0.997
|
101 |
+
|
102 |
+
pixel_opt:
|
103 |
+
type: L1Loss
|
104 |
+
loss_weight: 1.0
|
105 |
+
reduction: mean
|
106 |
+
|
107 |
+
perceptual_opt:
|
108 |
+
type: LPIPSLoss
|
109 |
+
loss_weight: 1.0
|
110 |
+
use_input_norm: true
|
111 |
+
range_norm: true
|
112 |
+
|
113 |
+
gan_opt:
|
114 |
+
type: GANLoss
|
115 |
+
gan_type: hinge
|
116 |
+
loss_weight: !!float 1.0 # adaptive_weighting
|
117 |
+
|
118 |
+
|
119 |
+
use_adaptive_weight: true
|
120 |
+
|
121 |
+
net_g_start_iter: 0
|
122 |
+
net_d_iters: 1
|
123 |
+
net_d_start_iter: 296001
|
124 |
+
manual_seed: 0
|
125 |
+
|
126 |
+
# validation settings
|
127 |
+
val:
|
128 |
+
val_freq: !!float 5e10 # no validation
|
129 |
+
save_img: true
|
130 |
+
|
131 |
+
metrics:
|
132 |
+
psnr: # metric name, can be arbitrary
|
133 |
+
type: calculate_psnr
|
134 |
+
crop_border: 4
|
135 |
+
test_y_channel: false
|
136 |
+
|
137 |
+
# logging settings
|
138 |
+
logger:
|
139 |
+
print_freq: 100
|
140 |
+
save_checkpoint_freq: !!float 1e4
|
141 |
+
use_tb_logger: true
|
142 |
+
wandb:
|
143 |
+
project: ~
|
144 |
+
resume_id: ~
|
145 |
+
|
146 |
+
# dist training settings
|
147 |
+
dist_params:
|
148 |
+
backend: nccl
|
149 |
+
port: 29420
|
150 |
+
|
151 |
+
find_unused_parameters: true
|
options/CodeFormer_stage2.yml
ADDED
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# general settings
|
2 |
+
name: CodeFormer_stage2
|
3 |
+
model_type: CodeFormerIdxModel
|
4 |
+
num_gpu: 8
|
5 |
+
manual_seed: 0
|
6 |
+
|
7 |
+
# dataset and data loader settings
|
8 |
+
datasets:
|
9 |
+
train:
|
10 |
+
name: FFHQ
|
11 |
+
type: FFHQBlindDataset
|
12 |
+
dataroot_gt: datasets/ffhq/ffhq_512
|
13 |
+
filename_tmpl: '{}'
|
14 |
+
io_backend:
|
15 |
+
type: disk
|
16 |
+
|
17 |
+
in_size: 512
|
18 |
+
gt_size: 512
|
19 |
+
mean: [0.5, 0.5, 0.5]
|
20 |
+
std: [0.5, 0.5, 0.5]
|
21 |
+
use_hflip: true
|
22 |
+
use_corrupt: true
|
23 |
+
latent_gt_path: ~
|
24 |
+
|
25 |
+
# large degradation in stageII
|
26 |
+
blur_kernel_size: 41
|
27 |
+
use_motion_kernel: false
|
28 |
+
motion_kernel_prob: 0.001
|
29 |
+
kernel_list: ['iso', 'aniso']
|
30 |
+
kernel_prob: [0.5, 0.5]
|
31 |
+
blur_sigma: [1, 15]
|
32 |
+
downsample_range: [4, 30]
|
33 |
+
noise_range: [0, 20]
|
34 |
+
jpeg_range: [30, 80]
|
35 |
+
|
36 |
+
latent_gt_path: './experiments/pretrained_models/VQGAN/latent_gt_code1024.pth'
|
37 |
+
|
38 |
+
# data loader
|
39 |
+
num_worker_per_gpu: 2
|
40 |
+
batch_size_per_gpu: 4
|
41 |
+
dataset_enlarge_ratio: 100
|
42 |
+
prefetch_mode: ~
|
43 |
+
|
44 |
+
# val:
|
45 |
+
# name: CelebA-HQ-512
|
46 |
+
# type: PairedImageDataset
|
47 |
+
# dataroot_lq: datasets/faces/validation/lq
|
48 |
+
# dataroot_gt: datasets/faces/validation/gt
|
49 |
+
# io_backend:
|
50 |
+
# type: disk
|
51 |
+
# mean: [0.5, 0.5, 0.5]
|
52 |
+
# std: [0.5, 0.5, 0.5]
|
53 |
+
# scale: 1
|
54 |
+
|
55 |
+
# network structures
|
56 |
+
network_g:
|
57 |
+
type: CodeFormer
|
58 |
+
dim_embd: 512
|
59 |
+
n_head: 8
|
60 |
+
n_layers: 9
|
61 |
+
codebook_size: 1024
|
62 |
+
connect_list: ['32', '64', '128', '256']
|
63 |
+
fix_modules: ['quantize','generator']
|
64 |
+
vqgan_path: './experiments/pretrained_models/vqgan/vqgan_code1024.pth' # pretrained VQGAN
|
65 |
+
|
66 |
+
# path
|
67 |
+
path:
|
68 |
+
pretrain_network_g: ~
|
69 |
+
param_key_g: params_ema
|
70 |
+
strict_load_g: false
|
71 |
+
pretrain_network_d: ~
|
72 |
+
strict_load_d: true
|
73 |
+
resume_state: ~
|
74 |
+
|
75 |
+
# base_lr(4.5e-6)*bach_size(4)
|
76 |
+
train:
|
77 |
+
use_hq_feat_loss: true
|
78 |
+
feat_loss_weight: 1.0
|
79 |
+
cross_entropy_loss: true
|
80 |
+
entropy_loss_weight: 0.5
|
81 |
+
fidelity_weight: 0
|
82 |
+
|
83 |
+
optim_g:
|
84 |
+
type: Adam
|
85 |
+
lr: !!float 1e-4
|
86 |
+
weight_decay: 0
|
87 |
+
betas: [0.9, 0.99]
|
88 |
+
|
89 |
+
scheduler:
|
90 |
+
type: MultiStepLR
|
91 |
+
milestones: [400000, 450000]
|
92 |
+
gamma: 0.5
|
93 |
+
|
94 |
+
# scheduler:
|
95 |
+
# type: CosineAnnealingRestartLR
|
96 |
+
# periods: [500000]
|
97 |
+
# restart_weights: [1]
|
98 |
+
# eta_min: !!float 2e-5 # no lr reduce in official vqgan code
|
99 |
+
|
100 |
+
total_iter: 500000
|
101 |
+
|
102 |
+
warmup_iter: -1 # no warm up
|
103 |
+
ema_decay: 0.995
|
104 |
+
|
105 |
+
use_adaptive_weight: true
|
106 |
+
|
107 |
+
net_g_start_iter: 0
|
108 |
+
net_d_iters: 1
|
109 |
+
net_d_start_iter: 0
|
110 |
+
manual_seed: 0
|
111 |
+
|
112 |
+
# validation settings
|
113 |
+
val:
|
114 |
+
val_freq: !!float 5e10 # no validation
|
115 |
+
save_img: true
|
116 |
+
|
117 |
+
metrics:
|
118 |
+
psnr: # metric name, can be arbitrary
|
119 |
+
type: calculate_psnr
|
120 |
+
crop_border: 4
|
121 |
+
test_y_channel: false
|
122 |
+
|
123 |
+
# logging settings
|
124 |
+
logger:
|
125 |
+
print_freq: 100
|
126 |
+
save_checkpoint_freq: !!float 1e4
|
127 |
+
use_tb_logger: true
|
128 |
+
wandb:
|
129 |
+
project: ~
|
130 |
+
resume_id: ~
|
131 |
+
|
132 |
+
# dist training settings
|
133 |
+
dist_params:
|
134 |
+
backend: nccl
|
135 |
+
port: 29412
|
136 |
+
|
137 |
+
find_unused_parameters: true
|
options/CodeFormer_stage3.yml
ADDED
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# general settings
|
2 |
+
name: CodeFormer_stage3
|
3 |
+
model_type: CodeFormerJointModel
|
4 |
+
num_gpu: 8
|
5 |
+
manual_seed: 0
|
6 |
+
|
7 |
+
# dataset and data loader settings
|
8 |
+
datasets:
|
9 |
+
train:
|
10 |
+
name: FFHQ
|
11 |
+
type: FFHQBlindJointDataset
|
12 |
+
dataroot_gt: datasets/ffhq/ffhq_512
|
13 |
+
filename_tmpl: '{}'
|
14 |
+
io_backend:
|
15 |
+
type: disk
|
16 |
+
|
17 |
+
in_size: 512
|
18 |
+
gt_size: 512
|
19 |
+
mean: [0.5, 0.5, 0.5]
|
20 |
+
std: [0.5, 0.5, 0.5]
|
21 |
+
use_hflip: true
|
22 |
+
use_corrupt: true
|
23 |
+
latent_gt_path: ~
|
24 |
+
|
25 |
+
blur_kernel_size: 41
|
26 |
+
use_motion_kernel: false
|
27 |
+
motion_kernel_prob: 0.001
|
28 |
+
kernel_list: ['iso', 'aniso']
|
29 |
+
kernel_prob: [0.5, 0.5]
|
30 |
+
# small degradation in stageIII
|
31 |
+
blur_sigma: [0.1, 10]
|
32 |
+
downsample_range: [1, 12]
|
33 |
+
noise_range: [0, 15]
|
34 |
+
jpeg_range: [60, 100]
|
35 |
+
# large degradation in stageII
|
36 |
+
blur_sigma_large: [1, 15]
|
37 |
+
downsample_range_large: [4, 30]
|
38 |
+
noise_range_large: [0, 20]
|
39 |
+
jpeg_range_large: [30, 80]
|
40 |
+
|
41 |
+
|
42 |
+
latent_gt_path: './experiments/pretrained_models/VQGAN/latent_gt_code1024.pth'
|
43 |
+
|
44 |
+
# data loader
|
45 |
+
num_worker_per_gpu: 1
|
46 |
+
batch_size_per_gpu: 3
|
47 |
+
dataset_enlarge_ratio: 100
|
48 |
+
prefetch_mode: ~
|
49 |
+
|
50 |
+
# val:
|
51 |
+
# name: CelebA-HQ-512
|
52 |
+
# type: PairedImageDataset
|
53 |
+
# dataroot_lq: datasets/faces/validation/lq
|
54 |
+
# dataroot_gt: datasets/faces/validation/gt
|
55 |
+
# io_backend:
|
56 |
+
# type: disk
|
57 |
+
# mean: [0.5, 0.5, 0.5]
|
58 |
+
# std: [0.5, 0.5, 0.5]
|
59 |
+
# scale: 1
|
60 |
+
|
61 |
+
# network structures
|
62 |
+
network_g:
|
63 |
+
type: CodeFormer
|
64 |
+
dim_embd: 512
|
65 |
+
n_head: 8
|
66 |
+
n_layers: 9
|
67 |
+
codebook_size: 1024
|
68 |
+
connect_list: ['32', '64', '128', '256']
|
69 |
+
fix_modules: ['quantize','generator']
|
70 |
+
|
71 |
+
network_d:
|
72 |
+
type: VQGANDiscriminator
|
73 |
+
nc: 3
|
74 |
+
ndf: 64
|
75 |
+
n_layers: 4
|
76 |
+
|
77 |
+
# path
|
78 |
+
path:
|
79 |
+
pretrain_network_g: './experiments/pretrained_models/CodeFormer_stage2/net_g_latest.pth' # pretrained G model in StageII
|
80 |
+
param_key_g: params_ema
|
81 |
+
strict_load_g: true
|
82 |
+
pretrain_network_d: './experiments/pretrained_models/CodeFormer_stage2/net_d_latest.pth' # pretrained D model in StageII
|
83 |
+
resume_state: ~
|
84 |
+
|
85 |
+
# base_lr(4.5e-6)*bach_size(4)
|
86 |
+
train:
|
87 |
+
use_hq_feat_loss: true
|
88 |
+
feat_loss_weight: 1.0
|
89 |
+
cross_entropy_loss: true
|
90 |
+
entropy_loss_weight: 0.5
|
91 |
+
scale_adaptive_gan_weight: 0.1
|
92 |
+
|
93 |
+
optim_g:
|
94 |
+
type: Adam
|
95 |
+
lr: !!float 5e-5
|
96 |
+
weight_decay: 0
|
97 |
+
betas: [0.9, 0.99]
|
98 |
+
optim_d:
|
99 |
+
type: Adam
|
100 |
+
lr: !!float 5e-5
|
101 |
+
weight_decay: 0
|
102 |
+
betas: [0.9, 0.99]
|
103 |
+
|
104 |
+
scheduler:
|
105 |
+
type: CosineAnnealingRestartLR
|
106 |
+
periods: [150000]
|
107 |
+
restart_weights: [1]
|
108 |
+
eta_min: !!float 2e-5
|
109 |
+
|
110 |
+
|
111 |
+
total_iter: 150000
|
112 |
+
|
113 |
+
warmup_iter: -1 # no warm up
|
114 |
+
ema_decay: 0.997
|
115 |
+
|
116 |
+
pixel_opt:
|
117 |
+
type: L1Loss
|
118 |
+
loss_weight: 1.0
|
119 |
+
reduction: mean
|
120 |
+
|
121 |
+
perceptual_opt:
|
122 |
+
type: LPIPSLoss
|
123 |
+
loss_weight: 1.0
|
124 |
+
use_input_norm: true
|
125 |
+
range_norm: true
|
126 |
+
|
127 |
+
gan_opt:
|
128 |
+
type: GANLoss
|
129 |
+
gan_type: hinge
|
130 |
+
loss_weight: !!float 1.0 # adaptive_weighting
|
131 |
+
|
132 |
+
use_adaptive_weight: true
|
133 |
+
|
134 |
+
net_g_start_iter: 0
|
135 |
+
net_d_iters: 1
|
136 |
+
net_d_start_iter: 5001
|
137 |
+
manual_seed: 0
|
138 |
+
|
139 |
+
# validation settings
|
140 |
+
val:
|
141 |
+
val_freq: !!float 5e10 # no validation
|
142 |
+
save_img: true
|
143 |
+
|
144 |
+
metrics:
|
145 |
+
psnr: # metric name, can be arbitrary
|
146 |
+
type: calculate_psnr
|
147 |
+
crop_border: 4
|
148 |
+
test_y_channel: false
|
149 |
+
|
150 |
+
# logging settings
|
151 |
+
logger:
|
152 |
+
print_freq: 100
|
153 |
+
save_checkpoint_freq: !!float 5e3
|
154 |
+
use_tb_logger: true
|
155 |
+
wandb:
|
156 |
+
project: ~
|
157 |
+
resume_id: ~
|
158 |
+
|
159 |
+
# dist training settings
|
160 |
+
dist_params:
|
161 |
+
backend: nccl
|
162 |
+
port: 29413
|
163 |
+
|
164 |
+
find_unused_parameters: true
|
options/VQGAN_512_ds32_nearest_stage1.yml
ADDED
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# general settings
|
2 |
+
name: VQGAN-512-ds32-nearest-stage1
|
3 |
+
model_type: VQGANModel
|
4 |
+
num_gpu: 8
|
5 |
+
manual_seed: 0
|
6 |
+
|
7 |
+
# dataset and data loader settings
|
8 |
+
datasets:
|
9 |
+
train:
|
10 |
+
name: FFHQ
|
11 |
+
type: FFHQBlindDataset
|
12 |
+
dataroot_gt: datasets/ffhq/ffhq_512
|
13 |
+
filename_tmpl: '{}'
|
14 |
+
io_backend:
|
15 |
+
type: disk
|
16 |
+
|
17 |
+
in_size: 512
|
18 |
+
gt_size: 512
|
19 |
+
mean: [0.5, 0.5, 0.5]
|
20 |
+
std: [0.5, 0.5, 0.5]
|
21 |
+
use_hflip: true
|
22 |
+
use_corrupt: false # for VQGAN
|
23 |
+
|
24 |
+
# data loader
|
25 |
+
num_worker_per_gpu: 2
|
26 |
+
batch_size_per_gpu: 4
|
27 |
+
dataset_enlarge_ratio: 100
|
28 |
+
|
29 |
+
prefetch_mode: cpu
|
30 |
+
num_prefetch_queue: 4
|
31 |
+
|
32 |
+
# val:
|
33 |
+
# name: CelebA-HQ-512
|
34 |
+
# type: PairedImageDataset
|
35 |
+
# dataroot_lq: datasets/faces/validation/gt
|
36 |
+
# dataroot_gt: datasets/faces/validation/gt
|
37 |
+
# io_backend:
|
38 |
+
# type: disk
|
39 |
+
# mean: [0.5, 0.5, 0.5]
|
40 |
+
# std: [0.5, 0.5, 0.5]
|
41 |
+
# scale: 1
|
42 |
+
|
43 |
+
# network structures
|
44 |
+
network_g:
|
45 |
+
type: VQAutoEncoder
|
46 |
+
img_size: 512
|
47 |
+
nf: 64
|
48 |
+
ch_mult: [1, 2, 2, 4, 4, 8]
|
49 |
+
quantizer: 'nearest'
|
50 |
+
codebook_size: 1024
|
51 |
+
|
52 |
+
network_d:
|
53 |
+
type: VQGANDiscriminator
|
54 |
+
nc: 3
|
55 |
+
ndf: 64
|
56 |
+
|
57 |
+
# path
|
58 |
+
path:
|
59 |
+
pretrain_network_g: ~
|
60 |
+
param_key_g: params_ema
|
61 |
+
strict_load_g: true
|
62 |
+
pretrain_network_d: ~
|
63 |
+
strict_load_d: true
|
64 |
+
resume_state: ~
|
65 |
+
|
66 |
+
# base_lr(4.5e-6)*bach_size(4)
|
67 |
+
train:
|
68 |
+
optim_g:
|
69 |
+
type: Adam
|
70 |
+
lr: !!float 7e-5
|
71 |
+
weight_decay: 0
|
72 |
+
betas: [0.9, 0.99]
|
73 |
+
optim_d:
|
74 |
+
type: Adam
|
75 |
+
lr: !!float 7e-5
|
76 |
+
weight_decay: 0
|
77 |
+
betas: [0.9, 0.99]
|
78 |
+
|
79 |
+
scheduler:
|
80 |
+
type: CosineAnnealingRestartLR
|
81 |
+
periods: [1600000]
|
82 |
+
restart_weights: [1]
|
83 |
+
eta_min: !!float 6e-5 # no lr reduce in official vqgan code
|
84 |
+
|
85 |
+
total_iter: 1600000
|
86 |
+
|
87 |
+
warmup_iter: -1 # no warm up
|
88 |
+
ema_decay: 0.995 # GFPGAN: 0.5**(32 / (10 * 1000) == 0.998; Unleashing: 0.995
|
89 |
+
|
90 |
+
pixel_opt:
|
91 |
+
type: L1Loss
|
92 |
+
loss_weight: 1.0
|
93 |
+
reduction: mean
|
94 |
+
|
95 |
+
perceptual_opt:
|
96 |
+
type: LPIPSLoss
|
97 |
+
loss_weight: 1.0
|
98 |
+
use_input_norm: true
|
99 |
+
range_norm: true
|
100 |
+
|
101 |
+
gan_opt:
|
102 |
+
type: GANLoss
|
103 |
+
gan_type: hinge
|
104 |
+
loss_weight: !!float 1.0 # adaptive_weighting
|
105 |
+
|
106 |
+
net_g_start_iter: 0
|
107 |
+
net_d_iters: 1
|
108 |
+
net_d_start_iter: 30001
|
109 |
+
manual_seed: 0
|
110 |
+
|
111 |
+
# validation settings
|
112 |
+
val:
|
113 |
+
val_freq: !!float 5e10 # no validation
|
114 |
+
save_img: true
|
115 |
+
|
116 |
+
metrics:
|
117 |
+
psnr: # metric name, can be arbitrary
|
118 |
+
type: calculate_psnr
|
119 |
+
crop_border: 4
|
120 |
+
test_y_channel: false
|
121 |
+
|
122 |
+
# logging settings
|
123 |
+
logger:
|
124 |
+
print_freq: 100
|
125 |
+
save_checkpoint_freq: !!float 1e4
|
126 |
+
use_tb_logger: true
|
127 |
+
wandb:
|
128 |
+
project: ~
|
129 |
+
resume_id: ~
|
130 |
+
|
131 |
+
# dist training settings
|
132 |
+
dist_params:
|
133 |
+
backend: nccl
|
134 |
+
port: 29411
|
135 |
+
|
136 |
+
find_unused_parameters: true
|
scripts/generate_latent_gt.py
ADDED
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import glob
|
3 |
+
import numpy as np
|
4 |
+
import os
|
5 |
+
import cv2
|
6 |
+
import torch
|
7 |
+
from torchvision.transforms.functional import normalize
|
8 |
+
from basicsr.utils import imwrite, img2tensor, tensor2img
|
9 |
+
|
10 |
+
from basicsr.utils.registry import ARCH_REGISTRY
|
11 |
+
|
12 |
+
if __name__ == '__main__':
|
13 |
+
parser = argparse.ArgumentParser()
|
14 |
+
parser.add_argument('-i', '--test_path', type=str, default='datasets/ffhq/ffhq_512')
|
15 |
+
parser.add_argument('-o', '--save_root', type=str, default='./experiments/pretrained_models/vqgan')
|
16 |
+
parser.add_argument('--codebook_size', type=int, default=1024)
|
17 |
+
parser.add_argument('--ckpt_path', type=str, default='./experiments/pretrained_models/vqgan/net_g.pth')
|
18 |
+
args = parser.parse_args()
|
19 |
+
|
20 |
+
if args.save_root.endswith('/'): # solve when path ends with /
|
21 |
+
args.save_root = args.save_root[:-1]
|
22 |
+
dir_name = os.path.abspath(args.save_root)
|
23 |
+
os.makedirs(dir_name, exist_ok=True)
|
24 |
+
|
25 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
26 |
+
test_path = args.test_path
|
27 |
+
save_root = args.save_root
|
28 |
+
ckpt_path = args.ckpt_path
|
29 |
+
codebook_size = args.codebook_size
|
30 |
+
|
31 |
+
vqgan = ARCH_REGISTRY.get('VQAutoEncoder')(512, 64, [1, 2, 2, 4, 4, 8], 'nearest',
|
32 |
+
codebook_size=codebook_size).to(device)
|
33 |
+
checkpoint = torch.load(ckpt_path)['params_ema']
|
34 |
+
|
35 |
+
vqgan.load_state_dict(checkpoint)
|
36 |
+
vqgan.eval()
|
37 |
+
|
38 |
+
sum_latent = np.zeros((codebook_size)).astype('float64')
|
39 |
+
size_latent = 16
|
40 |
+
latent = {}
|
41 |
+
latent['orig'] = {}
|
42 |
+
latent['hflip'] = {}
|
43 |
+
for i in ['orig', 'hflip']:
|
44 |
+
# for i in ['hflip']:
|
45 |
+
for img_path in sorted(glob.glob(os.path.join(test_path, '*.[jp][pn]g'))):
|
46 |
+
img_name = os.path.basename(img_path)
|
47 |
+
img = cv2.imread(img_path)
|
48 |
+
if i == 'hflip':
|
49 |
+
cv2.flip(img, 1, img)
|
50 |
+
img = img2tensor(img / 255., bgr2rgb=True, float32=True)
|
51 |
+
normalize(img, (0.5, 0.5, 0.5), (0.5, 0.5, 0.5), inplace=True)
|
52 |
+
img = img.unsqueeze(0).to(device)
|
53 |
+
with torch.no_grad():
|
54 |
+
# output = net(img)[0]
|
55 |
+
x, feat_dict = vqgan.encoder(img, True)
|
56 |
+
x, _, log = vqgan.quantize(x)
|
57 |
+
# del output
|
58 |
+
torch.cuda.empty_cache()
|
59 |
+
|
60 |
+
min_encoding_indices = log['min_encoding_indices']
|
61 |
+
min_encoding_indices = min_encoding_indices.view(size_latent,size_latent)
|
62 |
+
latent[i][img_name[:-4]] = min_encoding_indices.cpu().numpy()
|
63 |
+
print(img_name, latent[i][img_name[:-4]].shape)
|
64 |
+
|
65 |
+
latent_save_path = os.path.join(save_root, f'latent_gt_code{codebook_size}.pth')
|
66 |
+
torch.save(latent, latent_save_path)
|
67 |
+
print(f'\nLatent GT code are saved in {save_root}')
|
scripts/inference_vqgan.py
ADDED
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import glob
|
3 |
+
import numpy as np
|
4 |
+
import os
|
5 |
+
import cv2
|
6 |
+
import torch
|
7 |
+
from torchvision.transforms.functional import normalize
|
8 |
+
from basicsr.utils import imwrite, img2tensor, tensor2img
|
9 |
+
|
10 |
+
from basicsr.utils.registry import ARCH_REGISTRY
|
11 |
+
|
12 |
+
if __name__ == '__main__':
|
13 |
+
parser = argparse.ArgumentParser()
|
14 |
+
parser.add_argument('-i', '--test_path', type=str, default='datasets/ffhq/ffhq_512')
|
15 |
+
parser.add_argument('-o', '--save_root', type=str, default='./results/vqgan_rec')
|
16 |
+
parser.add_argument('--codebook_size', type=int, default=1024)
|
17 |
+
parser.add_argument('--ckpt_path', type=str, default='./experiments/pretrained_models/vqgan/net_g.pth')
|
18 |
+
args = parser.parse_args()
|
19 |
+
|
20 |
+
if args.save_root.endswith('/'): # solve when path ends with /
|
21 |
+
args.save_root = args.save_root[:-1]
|
22 |
+
dir_name = os.path.abspath(args.save_root)
|
23 |
+
os.makedirs(dir_name, exist_ok=True)
|
24 |
+
|
25 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
26 |
+
test_path = args.test_path
|
27 |
+
save_root = args.save_root
|
28 |
+
ckpt_path = args.ckpt_path
|
29 |
+
codebook_size = args.codebook_size
|
30 |
+
|
31 |
+
vqgan = ARCH_REGISTRY.get('VQAutoEncoder')(512, 64, [1, 2, 2, 4, 4, 8], 'nearest',
|
32 |
+
codebook_size=codebook_size).to(device)
|
33 |
+
checkpoint = torch.load(ckpt_path)['params_ema']
|
34 |
+
|
35 |
+
vqgan.load_state_dict(checkpoint)
|
36 |
+
vqgan.eval()
|
37 |
+
|
38 |
+
for img_path in sorted(glob.glob(os.path.join(test_path, '*.[jp][pn]g'))):
|
39 |
+
img_name = os.path.basename(img_path)
|
40 |
+
print(img_name)
|
41 |
+
img = cv2.imread(img_path)
|
42 |
+
img = img2tensor(img / 255., bgr2rgb=True, float32=True)
|
43 |
+
normalize(img, (0.5, 0.5, 0.5), (0.5, 0.5, 0.5), inplace=True)
|
44 |
+
img = img.unsqueeze(0).to(device)
|
45 |
+
with torch.no_grad():
|
46 |
+
output = vqgan(img)[0]
|
47 |
+
output = tensor2img(output, min_max=[-1,1])
|
48 |
+
img = tensor2img(img, min_max=[-1,1])
|
49 |
+
restored_img = np.concatenate([img, output], axis=1)
|
50 |
+
restored_img = output
|
51 |
+
del output
|
52 |
+
torch.cuda.empty_cache()
|
53 |
+
|
54 |
+
path = os.path.splitext(os.path.join(save_root, img_name))[0]
|
55 |
+
save_path = f'{path}.png'
|
56 |
+
imwrite(restored_img, save_path)
|
57 |
+
|
58 |
+
print(f'\nAll results are saved in {save_root}')
|
59 |
+
|