-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUNet.py
234 lines (210 loc) · 10 KB
/
UNet.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
import torch
import torch.nn as nn
from torch.nn import init
import functools
from torch.optim import lr_scheduler
###############################################################################
# In this file, we define all the helper functions for generator. To be specific, according to the paper, there is two way to implement the generator:
# 1. Latent code z is injected injected into the input layer.
# 2. Latent code z is injected injected into every intermediate layer in the encoder.
###############################################################################
class G_Unet_add_input(nn.Module):
def __init__(self, input_nc, output_nc, nz, num_downs, ngf=64,
norm_layer=None, nl_layer=None, use_dropout=False,
upsample='basic'):
super(G_Unet_add_input, self).__init__()
self.nz = nz
max_nchn = 8
# construct unet structure
unet_block = UnetBlock(ngf * max_nchn, ngf * max_nchn, ngf * max_nchn,
innermost=True, norm_layer=norm_layer, nl_layer=nl_layer, upsample=upsample)
for i in range(num_downs - 5):
unet_block = UnetBlock(ngf * max_nchn, ngf * max_nchn, ngf * max_nchn, unet_block,
norm_layer=norm_layer, nl_layer=nl_layer, use_dropout=use_dropout, upsample=upsample)
unet_block = UnetBlock(ngf * 4, ngf * 4, ngf * max_nchn, unet_block,
norm_layer=norm_layer, nl_layer=nl_layer, upsample=upsample)
unet_block = UnetBlock(ngf * 2, ngf * 2, ngf * 4, unet_block,
norm_layer=norm_layer, nl_layer=nl_layer, upsample=upsample)
unet_block = UnetBlock(ngf, ngf, ngf * 2, unet_block,
norm_layer=norm_layer, nl_layer=nl_layer, upsample=upsample)
unet_block = UnetBlock(input_nc + nz, output_nc, ngf, unet_block,
outermost=True, norm_layer=norm_layer, nl_layer=nl_layer, upsample=upsample)
self.model = unet_block
def forward(self, x, z=None):
if self.nz > 0:
z_img = z.view(z.size(0), z.size(1), 1, 1).expand(
z.size(0), z.size(1), x.size(2), x.size(3))
x_with_z = torch.cat([x, z_img], 1)
else:
x_with_z = x # no z
return self.model(x_with_z)
def upsampleLayer(inplanes, outplanes, upsample='basic', padding_type='zero'):
# padding_type = 'zero'
if upsample == 'basic':
upconv = [nn.ConvTranspose2d(
inplanes, outplanes, kernel_size=4, stride=2, padding=1)]
elif upsample == 'bilinear':
upconv = [nn.Upsample(scale_factor=2, mode='bilinear'),
nn.ReflectionPad2d(1),
nn.Conv2d(inplanes, outplanes, kernel_size=3, stride=1, padding=0)]
else:
raise NotImplementedError(
'upsample layer [%s] not implemented' % upsample)
return upconv
# Defines the submodule with skip connection.
# X -------------------identity---------------------- X
# |-- downsampling -- |submodule| -- upsampling --|
class UnetBlock(nn.Module):
def __init__(self, input_nc, outer_nc, inner_nc,
submodule=None, outermost=False, innermost=False,
norm_layer=None, nl_layer=None, use_dropout=False, upsample='basic', padding_type='zero'):
super(UnetBlock, self).__init__()
self.outermost = outermost
p = 0
downconv = []
if padding_type == 'reflect':
downconv += [nn.ReflectionPad2d(1)]
elif padding_type == 'replicate':
downconv += [nn.ReplicationPad2d(1)]
elif padding_type == 'zero':
p = 1
else:
raise NotImplementedError(
'padding [%s] is not implemented' % padding_type)
downconv += [nn.Conv2d(input_nc, inner_nc,
kernel_size=4, stride=2, padding=p)]
# downsample is different from upsample
downrelu = nn.LeakyReLU(0.2, True)
downnorm = norm_layer(inner_nc) if norm_layer is not None else None
uprelu = nl_layer()
upnorm = norm_layer(outer_nc) if norm_layer is not None else None
if outermost:
upconv = upsampleLayer(
inner_nc * 2, outer_nc, upsample=upsample, padding_type=padding_type)
down = downconv
up = [uprelu] + upconv + [nn.Tanh()]
model = down + [submodule] + up
elif innermost:
upconv = upsampleLayer(
inner_nc, outer_nc, upsample=upsample, padding_type=padding_type)
down = [downrelu] + downconv
up = [uprelu] + upconv
if upnorm is not None:
up += [upnorm]
model = down + up
else:
upconv = upsampleLayer(
inner_nc * 2, outer_nc, upsample=upsample, padding_type=padding_type)
down = [downrelu] + downconv
if downnorm is not None:
down += [downnorm]
up = [uprelu] + upconv
if upnorm is not None:
up += [upnorm]
if use_dropout:
model = down + [submodule] + up + [nn.Dropout(0.5)]
else:
model = down + [submodule] + up
self.model = nn.Sequential(*model)
def forward(self, x):
if self.outermost:
return self.model(x)
else:
return torch.cat([self.model(x), x], 1)
# Defines the Unet generator.
# |num_downs|: number of downsamplings in UNet. For example,
# if |num_downs| == 7, image of size 128x128 will become of size 1x1
# at the bottleneck
class G_Unet_add_all(nn.Module):
def __init__(self, input_nc, output_nc, nz, num_downs, ngf=64,
norm_layer=None, nl_layer=None, use_dropout=False, upsample='basic'):
super(G_Unet_add_all, self).__init__()
self.nz = nz
# construct unet structure
unet_block = UnetBlock_with_z(ngf * 8, ngf * 8, ngf * 8, nz, None, innermost=True,
norm_layer=norm_layer, nl_layer=nl_layer, upsample=upsample)
unet_block = UnetBlock_with_z(ngf * 8, ngf * 8, ngf * 8, nz, unet_block,
norm_layer=norm_layer, nl_layer=nl_layer, use_dropout=use_dropout, upsample=upsample)
for i in range(num_downs - 6):
unet_block = UnetBlock_with_z(ngf * 8, ngf * 8, ngf * 8, nz, unet_block,
norm_layer=norm_layer, nl_layer=nl_layer, use_dropout=use_dropout, upsample=upsample)
unet_block = UnetBlock_with_z(ngf * 4, ngf * 4, ngf * 8, nz, unet_block,
norm_layer=norm_layer, nl_layer=nl_layer, upsample=upsample)
unet_block = UnetBlock_with_z(ngf * 2, ngf * 2, ngf * 4, nz, unet_block,
norm_layer=norm_layer, nl_layer=nl_layer, upsample=upsample)
unet_block = UnetBlock_with_z(
ngf, ngf, ngf * 2, nz, unet_block, norm_layer=norm_layer, nl_layer=nl_layer, upsample=upsample)
unet_block = UnetBlock_with_z(input_nc, output_nc, ngf, nz, unet_block,
outermost=True, norm_layer=norm_layer, nl_layer=nl_layer, upsample=upsample)
self.model = unet_block
def forward(self, x, z):
return self.model(x, z)
class UnetBlock_with_z(nn.Module):
def __init__(self, input_nc, outer_nc, inner_nc, nz=0,
submodule=None, outermost=False, innermost=False,
norm_layer=None, nl_layer=None, use_dropout=False, upsample='basic', padding_type='zero'):
super(UnetBlock_with_z, self).__init__()
p = 0
downconv = []
if padding_type == 'reflect':
downconv += [nn.ReflectionPad2d(1)]
elif padding_type == 'replicate':
downconv += [nn.ReplicationPad2d(1)]
elif padding_type == 'zero':
p = 1
else:
raise NotImplementedError(
'padding [%s] is not implemented' % padding_type)
self.outermost = outermost
self.innermost = innermost
self.nz = nz
input_nc = input_nc + nz
downconv += [nn.Conv2d(input_nc, inner_nc,
kernel_size=4, stride=2, padding=p)]
# downsample is different from upsample
downrelu = nn.LeakyReLU(0.2, True)
uprelu = nl_layer()
if outermost:
upconv = upsampleLayer(
inner_nc * 2, outer_nc, upsample=upsample, padding_type=padding_type)
down = downconv
up = [uprelu] + upconv + [nn.Tanh()]
elif innermost:
upconv = upsampleLayer(
inner_nc, outer_nc, upsample=upsample, padding_type=padding_type)
down = [downrelu] + downconv
up = [uprelu] + upconv
if norm_layer is not None:
up += [norm_layer(outer_nc)]
else:
upconv = upsampleLayer(
inner_nc * 2, outer_nc, upsample=upsample, padding_type=padding_type)
down = [downrelu] + downconv
if norm_layer is not None:
down += [norm_layer(inner_nc)]
up = [uprelu] + upconv
if norm_layer is not None:
up += [norm_layer(outer_nc)]
if use_dropout:
up += [nn.Dropout(0.5)]
self.down = nn.Sequential(*down)
self.submodule = submodule
self.up = nn.Sequential(*up)
def forward(self, x, z):
# print(x.size())
if self.nz > 0:
z_img = z.view(z.size(0), z.size(1), 1, 1).expand(z.size(0), z.size(1), x.size(2), x.size(3))
x_and_z = torch.cat([x, z_img], 1)
else:
x_and_z = x
if self.outermost:
x1 = self.down(x_and_z)
x2 = self.submodule(x1, z)
return self.up(x2)
elif self.innermost:
x1 = self.up(self.down(x_and_z))
return torch.cat([x1, x], 1)
else:
x1 = self.down(x_and_z)
x2 = self.submodule(x1, z)
return torch.cat([self.up(x2), x], 1)