-
Notifications
You must be signed in to change notification settings - Fork 84
/
convolutions.py
214 lines (188 loc) · 7.42 KB
/
convolutions.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
from collections import OrderedDict
from functools import partial
import torch
import torch.nn as nn
import torch.nn.functional as F
class ConvBlock(nn.Module):
"""2D convolution followed by
- an optional normalisation (batch norm or instance norm)
- an optional activation (ReLU, LeakyReLU, or tanh)
"""
def __init__(
self,
in_channels,
out_channels=None,
kernel_size=3,
stride=1,
norm='bn',
activation='relu',
bias=False,
transpose=False,
):
super().__init__()
out_channels = out_channels or in_channels
padding = int((kernel_size - 1) / 2)
self.conv = nn.Conv2d if not transpose else partial(nn.ConvTranspose2d, output_padding=1)
self.conv = self.conv(in_channels, out_channels, kernel_size, stride, padding=padding, bias=bias)
if norm == 'bn':
self.norm = nn.BatchNorm2d(out_channels)
elif norm == 'in':
self.norm = nn.InstanceNorm2d(out_channels)
elif norm == 'none':
self.norm = None
else:
raise ValueError('Invalid norm {}'.format(norm))
if activation == 'relu':
self.activation = nn.ReLU(inplace=True)
elif activation == 'lrelu':
self.activation = nn.LeakyReLU(0.1, inplace=True)
elif activation == 'elu':
self.activation = nn.ELU(inplace=True)
elif activation == 'tanh':
self.activation = nn.Tanh(inplace=True)
elif activation == 'none':
self.activation = None
else:
raise ValueError('Invalid activation {}'.format(activation))
def forward(self, x):
x = self.conv(x)
if self.norm:
x = self.norm(x)
if self.activation:
x = self.activation(x)
return x
class Bottleneck(nn.Module):
"""
Defines a bottleneck module with a residual connection
"""
def __init__(
self,
in_channels,
out_channels=None,
kernel_size=3,
dilation=1,
groups=1,
upsample=False,
downsample=False,
dropout=0.0,
):
super().__init__()
self._downsample = downsample
bottleneck_channels = int(in_channels / 2)
out_channels = out_channels or in_channels
padding_size = ((kernel_size - 1) * dilation + 1) // 2
# Define the main conv operation
assert dilation == 1
if upsample:
assert not downsample, 'downsample and upsample not possible simultaneously.'
bottleneck_conv = nn.ConvTranspose2d(
bottleneck_channels,
bottleneck_channels,
kernel_size=kernel_size,
bias=False,
dilation=1,
stride=2,
output_padding=padding_size,
padding=padding_size,
groups=groups,
)
elif downsample:
bottleneck_conv = nn.Conv2d(
bottleneck_channels,
bottleneck_channels,
kernel_size=kernel_size,
bias=False,
dilation=dilation,
stride=2,
padding=padding_size,
groups=groups,
)
else:
bottleneck_conv = nn.Conv2d(
bottleneck_channels,
bottleneck_channels,
kernel_size=kernel_size,
bias=False,
dilation=dilation,
padding=padding_size,
groups=groups,
)
self.layers = nn.Sequential(
OrderedDict(
[
# First projection with 1x1 kernel
('conv_down_project', nn.Conv2d(in_channels, bottleneck_channels, kernel_size=1, bias=False)),
('abn_down_project', nn.Sequential(nn.BatchNorm2d(bottleneck_channels),
nn.ReLU(inplace=True))),
# Second conv block
('conv', bottleneck_conv),
('abn', nn.Sequential(nn.BatchNorm2d(bottleneck_channels), nn.ReLU(inplace=True))),
# Final projection with 1x1 kernel
('conv_up_project', nn.Conv2d(bottleneck_channels, out_channels, kernel_size=1, bias=False)),
('abn_up_project', nn.Sequential(nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True))),
# Regulariser
('dropout', nn.Dropout2d(p=dropout)),
]
)
)
if out_channels == in_channels and not downsample and not upsample:
self.projection = None
else:
projection = OrderedDict()
if upsample:
projection.update({'upsample_skip_proj': Interpolate(scale_factor=2)})
elif downsample:
projection.update({'upsample_skip_proj': nn.MaxPool2d(kernel_size=2, stride=2)})
projection.update(
{
'conv_skip_proj': nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False),
'bn_skip_proj': nn.BatchNorm2d(out_channels),
}
)
self.projection = nn.Sequential(projection)
# pylint: disable=arguments-differ
def forward(self, *args):
(x,) = args
x_residual = self.layers(x)
if self.projection is not None:
if self._downsample:
# pad h/w dimensions if they are odd to prevent shape mismatch with residual layer
x = nn.functional.pad(x, (0, x.shape[-1] % 2, 0, x.shape[-2] % 2), value=0)
return x_residual + self.projection(x)
return x_residual + x
class Interpolate(nn.Module):
def __init__(self, scale_factor: int = 2):
super().__init__()
self._interpolate = nn.functional.interpolate
self._scale_factor = scale_factor
# pylint: disable=arguments-differ
def forward(self, x):
return self._interpolate(x, scale_factor=self._scale_factor, mode='bilinear', align_corners=False)
class UpsamplingConcat(nn.Module):
def __init__(self, in_channels, out_channels, scale_factor=2):
super().__init__()
self.upsample = nn.Upsample(scale_factor=scale_factor, mode='bilinear', align_corners=False)
self.conv = nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1, bias=False),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True),
nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1, bias=False),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True),
)
def forward(self, x_to_upsample, x):
x_to_upsample = self.upsample(x_to_upsample)
x_to_upsample = torch.cat([x, x_to_upsample], dim=1)
return self.conv(x_to_upsample)
class UpsamplingAdd(nn.Module):
def __init__(self, in_channels, out_channels, scale_factor=2):
super().__init__()
self.upsample_layer = nn.Sequential(
nn.Upsample(scale_factor=scale_factor, mode='bilinear', align_corners=False),
nn.Conv2d(in_channels, out_channels, kernel_size=1, padding=0, bias=False),
nn.BatchNorm2d(out_channels),
)
def forward(self, x, x_skip):
x = self.upsample_layer(x)
return x + x_skip