-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathresizer.py
76 lines (58 loc) · 2.36 KB
/
resizer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
from omegaconf import DictConfig
import torch.nn as nn
import torch.nn.functional as F
from functools import partial
class ResBlock(nn.Module):
def __init__(self, channel_size: int, negative_slope: float = 0.2):
super().__init__()
self.block = nn.Sequential(
nn.Conv2d(channel_size, channel_size, kernel_size=3, padding=1,
bias=False),
nn.BatchNorm2d(channel_size),
nn.LeakyReLU(negative_slope, inplace=True),
nn.Conv2d(channel_size, channel_size, kernel_size=3, padding=1,
bias=False),
nn.BatchNorm2d(channel_size)
)
def forward(self, x):
return x + self.block(x)
class Resizer(nn.Module):
def __init__(self, cfg: DictConfig):
super().__init__()
self.interpolate_mode = cfg.resizer.interpolate_mode
self.scale_factor = cfg.data.image_size / cfg.data.resizer_image_size
n = cfg.resizer.num_kernels
r = cfg.resizer.num_resblocks
slope = cfg.resizer.negative_slope
self.module1 = nn.Sequential(
nn.Conv2d(cfg.resizer.in_channels, n, kernel_size=7, padding=3),
nn.LeakyReLU(slope, inplace=True),
nn.Conv2d(n, n, kernel_size=1),
nn.LeakyReLU(slope, inplace=True),
nn.BatchNorm2d(n)
)
resblocks = []
for i in range(r):
resblocks.append(ResBlock(n, slope))
self.resblocks = nn.Sequential(*resblocks)
self.module3 = nn.Sequential(
nn.Conv2d(n, n, kernel_size=3, padding=1, bias=False),
nn.BatchNorm2d(n)
)
self.module4 = nn.Conv2d(n, cfg.resizer.out_channels, kernel_size=7,
padding=3)
self.interpolate = partial(F.interpolate,
scale_factor=self.scale_factor,
mode=self.interpolate_mode,
align_corners=False,
recompute_scale_factor=False)
def forward(self, x):
residual = self.interpolate(x)
out = self.module1(x)
out_residual = self.interpolate(out)
out = self.resblocks(out_residual)
out = self.module3(out)
out = out + out_residual
out = self.module4(out)
out = out + residual
return out