-
Notifications
You must be signed in to change notification settings - Fork 0
/
octave_unet.py
357 lines (253 loc) · 10.8 KB
/
octave_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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
import os
import torch
import torchvision
import torch.nn as nn
import torch.nn.functional as F
class OctaveConv(nn.Module):
"""Implementation of octave convolution operation which uses high and low frequency feature maps
https://arxiv.org/abs/1904.05049"""
def __init__(
self,
in_chn,
out_chn,
alphas=[0.5, 0.5],
padding=1,
kernel=3,
):
super(OctaveConv, self).__init__()
(self.alpha_in, self.alpha_out) = alphas
assert 1 > self.alpha_in >= 0 and 1 > self.alpha_out >= 0, \
'alphas values must be bound between 0 and 1, it could be 0 but not 1'
(self.htoh, self.htol, self.ltol, self.ltoh) = (None, None,
None, None)
self.htoh = nn.Conv2d(in_chn - int(self.alpha_in * in_chn),
out_chn - int(self.alpha_out * out_chn),
kernel, stride=1, padding=padding)
self.htol = (nn.Conv2d(in_chn - int(self.alpha_in * in_chn),
int(self.alpha_out * out_chn), kernel, stride=1,
padding=padding) if self.alpha_out > 0 else None)
self.ltol = (nn.Conv2d(int(self.alpha_in * in_chn),
int(self.alpha_out * out_chn), kernel, stride=1,
padding=padding) if self.alpha_out > 0
and self.alpha_in > 0 else None)
self.ltoh = (nn.Conv2d(int(self.alpha_in * in_chn), out_chn
- int(self.alpha_out * out_chn), kernel, stride=1,
padding=padding) if self.alpha_in > 0 else None)
def forward(self, x):
(high, low) = (x if isinstance(x, tuple) else (x, None))
if self.htoh is not None:
htoh = self.htoh(high)
if self.htol is not None:
htol = self.htol(F.avg_pool2d(high, 2, stride=2))
if self.ltol and low is not None:
ltol = self.ltol(low)
if self.ltoh and low is not None:
ltoh = F.interpolate(self.ltoh(low), scale_factor=2,
mode='nearest')
# if octave conv is being used as normal conv and both alpha are 0
if self.alpha_in is 0 and self.alpha_out is 0:
return (htoh, None)
# for first layer when there is no low freq map was given and both maps were created from input image
if low is None:
return (htoh, htol)
# this is for the last layer in the network when we dont want any low freq map output
if self.alpha_out == 0:
return (htoh.add_(ltoh), None)
# otherwise add feature maps and return both high and low freq maps
htoh.add_(ltoh)
ltol.add_(htol)
return (htoh, ltol)
class TransposeOctConv(nn.Module):
"""This is the implementation of Octave Transpose Conv from paper https://arxiv.org/abs/1906.12193"""
def __init__(
self,
in_chn,
out_chn,
alphas=[0.5, 0.5],
kernel=2,
):
super(TransposeOctConv, self).__init__()
(self.alpha_in, self.alpha_out) = alphas
assert 1 > self.alpha_in >= 0 and 1 > self.alpha_out >= 0, \
'alphas values must be bound between 0 and 1, it could be 0 but not 1'
self.htoh = nn.ConvTranspose2d(in_chn - int(self.alpha_in
* in_chn), out_chn - int(self.alpha_out * out_chn),
kernel, 2)
self.htol = (nn.ConvTranspose2d(in_chn - int(self.alpha_in
* in_chn), int(self.alpha_out * out_chn), kernel,
2) if self.alpha_out > 0 else None)
self.ltol = (nn.ConvTranspose2d(int(self.alpha_in * in_chn),
int(self.alpha_out * out_chn), kernel,
2) if self.alpha_out > 0 and self.alpha_in
> 0 else None)
self.ltoh = (nn.ConvTranspose2d(int(self.alpha_in * in_chn),
out_chn - int(self.alpha_out * out_chn), kernel,
2) if self.alpha_in > 0 else None)
def forward(self, x):
(high, low) = (x if isinstance(x, tuple) else (x, None))
if self.htoh is not None:
htoh = self.htoh(high)
if self.htol is not None:
htol = self.htol(F.avg_pool2d(high, 2, 2))
if self.ltol is not None and low is not None:
ltol = self.ltol(low)
if self.ltoh is not None and low is not None:
ltoh = F.interpolate(self.ltoh(low), scale_factor=2,
mode='nearest')
# it will behave as normal Transpose Conv operation
if self.alpha_in is 0 and self.alpha_out is 0:
return (htoh, None)
# case where we don't want a low frequency map as output
if self.alpha_out == 0:
return (htoh.add_(ltoh), None)
# otherwise add feature maps and return both high and low freq maps
htoh.add_(ltoh)
ltol.add_(htol)
return (htoh, ltol)
class OctaveBnAct(nn.Module):
'''This class applies OctaveConv-->BatchNorm-->ReLU operations on input'''
def __init__(
self,
in_chn,
out_chn,
alphas=[0.5, 0.5],
):
super(OctaveBnAct, self).__init__()
self.oct = OctaveConv(in_chn, out_chn, alphas)
self.bn1 = nn.BatchNorm2d(out_chn - int(alphas[1] * out_chn))
self.bn2 = (None if alphas[1]
is 0 else nn.BatchNorm2d(int(alphas[1] * out_chn)))
self.relu = nn.ReLU(inplace=True)
def forward(self, x):
(high, low) = self.oct(x)
high = self.relu(self.bn1(high))
if low is not None:
low = self.relu(self.bn2(low))
return (high, low)
class Encoder_block(nn.Module):
def __init__(
self,
input_chn,
output_chn,
alphas=[0.5, 0.5],
num_layers=2,
kernel=3,
padding=1,
last_block=False,
):
super(Encoder_block, self).__init__()
layers_chn = [input_chn, output_chn] + [output_chn for i in
range(num_layers)]
if len(alphas) == 4:
# means alphas for both blocks are given
alphas1 = alphas[0:2]
alphas2 = alphas[2:]
else:
# use same alphas for both blocks
(alphas1, alphas2) = (alphas, alphas)
self.pool = None
self.block1 = OctaveBnAct(layers_chn[0], layers_chn[1], alphas1)
self.block2 = OctaveBnAct(layers_chn[2], layers_chn[3], alphas2)
if last_block is False:
self.pool = nn.MaxPool2d(kernel_size=2, stride=2)
def forward(self, x):
x = self.block1(x)
x = self.block2(x)
if self.pool:
pool = (self.pool(x[0]), self.pool(x[1]))
# here both x and pool are tuples consisting of high and low freq maps
return (x, pool)
return (x, None)
class Decoder_block(nn.Module):
def __init__(
self,
input_chn,
output_chn,
alphas=[0.5, 0.5],
bilinear=False,
):
super(Decoder_block, self).__init__()
# upsample feature maps size using either way
if bilinear:
self.up = nn.Upsample(scale_factor=2, mode='bilinear')
else:
self.up = TransposeOctConv(input_chn, output_chn)
if len(alphas) == 4:
# means alphas for both blocks are given
alphas1 = alphas[0:2]
alphas2 = alphas[2:]
else:
# use same alphas for both blocks
(alphas1, alphas2) = (alphas, alphas)
# use two conv operation to process over upsample feature maps
self.block1 = OctaveBnAct(input_chn, output_chn, alphas1)
self.block2 = OctaveBnAct(output_chn, output_chn, alphas2)
def forward(self, x, encoder_feat):
x = self.up(x)
x = (F.relu(x[0]), F.relu(x[1]))
# concatenate high freq maps with corresponding encoder map
assert x[0].shape[1] == encoder_feat[0].shape[1], \
'High freq maps channels should be same'
high = torch.cat([x[0], encoder_feat[0]], dim=1)
# concatenate low freq maps with corresponding encoder map
if x[1] is not None and encoder_feat[1] is not None:
assert x[1].shape[1] == encoder_feat[1].shape[1], \
'Low freq maps channels should be same'
low = torch.cat([x[1], encoder_feat[1]], dim=1)
x = (high, low)
x = self.block1(x)
x = self.block2(x)
return x
class OctaveUnet(nn.Module):
""" This is Unet architecture implementation using Oactave and Transpose Ovctave Convolution from the paper https://arxiv.org/abs/1906.12193.
However, in the paper feature maps retain same spatial size by using octave conv after max pool operation, here feature maps size is reduceed
as per the Unet paper. """
def __init__(self, num_classes):
super(OctaveUnet, self).__init__()
self.blocks = nn.ModuleDict()
down_chn = [
3,
64,
128,
256,
512,
1024,
]
up_chn = down_chn[::-1]
# initial block which take in original image (only high freq map)
self.blocks.update({'down_block1': Encoder_block(down_chn[0],
down_chn[1], [0, 0.5, 0.5, 0.5])})
# rest of the encoder blocks
for i in range(1, 5):
if i == 4:
# this makes sure that max pooling is not applied to the last block of encoder side
self.blocks.update({'down_block' + str(i
+ 1): Encoder_block(down_chn[i],
down_chn[i + 1], last_block=True)})
else:
# max pooling should be applied to rest of the blocks on encoder side
self.blocks.update({'down_block' + str(i
+ 1): Encoder_block(down_chn[i],
down_chn[i + 1])})
# decoder blocks
for i in range(3):
self.blocks.update({'up_block' + str(i
+ 1): Decoder_block(up_chn[i], up_chn[i
+ 1])})
# final block of decoder only outputs high freq map
self.blocks.update({'up_block4': Decoder_block(up_chn[i + 1],
up_chn[i + 2], [0.5, 0.5, 0.5, 0])})
self.classifier = nn.Conv2d(64, num_classes, 1)
def forward(self, x):
# save the encoder blocks output
encoder_results = list()
# iterate over encoder blocks
for i in range(5):
(feat, x) = self.blocks['down_block' + str(i + 1)](x)
encoder_results.append([feat, x])
index = 3
for i in range(4):
feat = self.blocks['up_block' + str(i + 1)](feat,
encoder_results[index - i][0])
# classifier only gets the high freq map in the end
return self.classifier(feat[0])