-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
273 lines (227 loc) · 9.67 KB
/
utils.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
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils.parametrizations import spectral_norm as SpectralNorm
import functools
from torch.nn import Parameter as P
def MDmin(x_batch, lidc=False):
batch_size = x_batch.shape[0]
s = 1e6 * torch.ones(batch_size).to(x_batch.device)
for ii in range(batch_size):
for jj in range(batch_size):
if ii != jj:
s[ii] = min(s[ii],torch.abs(x_batch[ii] - x_batch[jj]).mean())
if lidc:
s_full = s[:,None,None,None,None].repeat((1,1,16,16,16))
else:
s_full = s[:,None,None,None,None].repeat((1,1,8,16,16))
return torch.cat((x_batch,s_full),dim=1), s
class Conv3_1d(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=(3,3,3,3), stride=(1, 1, 1, 1),
padding=(0, 1, 1, 1), dilation=(1, 1, 1, 1), bias=True):
super().__init__()
t = kernel_size[0]
d = (kernel_size[1] + kernel_size[2] + kernel_size[3])//2
self.in_channels = in_channels
self.out_channels = out_channels
#Hidden size estimation to get a number of parameter similar to the 3d case
self.hidden_size = int((t*d**2*in_channels*out_channels)/(d**2*in_channels+t*out_channels))
self.conv3d = nn.Conv3d(in_channels, self.hidden_size, kernel_size[1:], stride[1:], padding[1:], bias=bias)
self.conv1d = nn.Conv1d(self.hidden_size, out_channels, kernel_size[0], stride[0], padding[0], bias=bias)
def forward(self, x):
#3D convolution
b, t, c, d1, d2, d3 = x.size()
x = x.view(b*t, c, d1, d2, d3)
x = F.relu(self.conv3d(x))
#1D convolution
c, dr1, dr2, dr3 = x.size(1), x.size(2), x.size(3), x.size(4)
x = x.view(b, t, c, dr1, dr2, dr3)
x = x.permute(0, 3, 4, 5, 2, 1).contiguous()
x = x.view(b*dr1*dr2*dr3, c, t)
x = self.conv1d(x)
#Final output
out_c, out_t = x.size(1), x.size(2)
x = x.view(b, dr1, dr2, dr3, out_c, out_t)
x = x.permute(0, 4, 5, 1, 2, 3).contiguous()
return x.squeeze()
################# BigGAN ######################
def snconv3d(in_channels, out_channels, kernel_size=3, stride=1, padding=1, dilation=1, bias=True):
return SpectralNorm(nn.Conv3d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size,
stride=stride, padding=padding, dilation=dilation, bias=bias))
def snlinear(in_features, out_features):
return SpectralNorm(nn.Linear(in_features=in_features, out_features=out_features))
class Attention(nn.Module):
def __init__(self, ch):
super(Attention, self).__init__()
# Channel multiplier
self.ch = ch
self.ch_ = self.ch//8
self.f = snconv3d(self.ch, self.ch_, kernel_size=1, padding=0, bias=False)
self.g = snconv3d(self.ch, self.ch_, kernel_size=1, padding=0, bias=False)
self.h = snconv3d(self.ch, self.ch_, kernel_size=1, padding=0, bias=False)
self.v = snconv3d(self.ch_, self.ch, kernel_size=1, padding=0, bias=False)
self.gamma = P(torch.tensor(0.), requires_grad=True)
def forward(self, x, y=None):
# Apply convs
f = self.f(x)
g = F.max_pool3d(self.g(x), [2,2,2], stride=2)
f = f.view(-1, self.ch_, x.shape[2] * x.shape[3] * x.shape[4])
g = g.view(-1, self.ch_, x.shape[2] * x.shape[3] * x.shape[4]//8)
beta = F.softmax(torch.bmm(f.permute(0,2,1), g), -1)
h = F.max_pool3d(self.h(x), [2,2,2], stride=2)
h = h.view(-1, self.ch_, x.shape[2] * x.shape[3] * x.shape[4]//8)
o = self.v(torch.bmm(h, beta.permute(0,2,1)).view(-1, self.ch_, x.shape[2], x.shape[3], x.shape[4]))
return self.gamma * o + x
class GBlock(nn.Module):
def __init__(self, in_channels, out_channels, upsample=None, channel_ratio=4):
super(GBlock, self).__init__()
self.in_channels, self.out_channels = in_channels, out_channels
self.hidden_channels = self.in_channels // channel_ratio
# Conv layers
self.conv1 = snconv3d(self.in_channels, self.hidden_channels,
kernel_size=1, padding=0)
self.conv2 = snconv3d(self.hidden_channels, self.hidden_channels)
self.conv3 = snconv3d(self.hidden_channels, self.hidden_channels)
self.conv4 = snconv3d(self.hidden_channels, self.out_channels,
kernel_size=1, padding=0)
# Batchnorm layers
self.bn1 = nn.BatchNorm3d(self.in_channels)
self.bn2 = nn.BatchNorm3d(self.hidden_channels)
self.bn3 = nn.BatchNorm3d(self.hidden_channels)
self.bn4 = nn.BatchNorm3d(self.hidden_channels)
# upsample layers
self.upsample = upsample
self.activation = nn.ReLU(inplace=True)
def forward(self, x):
# Project down to channel ratio
h = self.conv1(self.activation(self.bn1(x)))
# Apply next BN-ReLU
h = self.activation(self.bn2(h))
if self.in_channels != self.out_channels:
x = x[:, :self.out_channels]
# Upsample both h and x at this point
if self.upsample:
h = self.upsample(h)
x = self.upsample(x)
# 3x3 convs
h = self.conv2(h)
h = self.conv3(self.activation(self.bn3(h)))
# Final 1x1 conv
h = self.conv4(self.activation(self.bn4(h)))
return h + x
class DBlock(nn.Module):
def __init__(self, in_channels, out_channels, wide=True, preactivation=True,
downsample=None, channel_ratio=4):
super(DBlock, self).__init__()
self.in_channels, self.out_channels = in_channels, out_channels
# If using wide D (as in SA-GAN and BigGAN), change the channel pattern
self.hidden_channels = self.out_channels // channel_ratio
self.preactivation = preactivation
self.activation = nn.ReLU(inplace=True)
self.downsample = downsample
# Conv layers
self.conv1 = snconv3d(self.in_channels, self.hidden_channels,
kernel_size=1, padding=0)
self.conv2 = snconv3d(self.hidden_channels, self.hidden_channels)
self.conv3 = snconv3d(self.hidden_channels, self.hidden_channels)
self.conv4 = snconv3d(self.hidden_channels, self.out_channels,
kernel_size=1, padding=0)
self.learnable_sc = True if (in_channels != out_channels) else False
if self.learnable_sc:
self.conv_sc = snconv3d(in_channels, out_channels - in_channels,
kernel_size=1, padding=0)
def shortcut(self, x):
if self.downsample:
x = self.downsample(x)
if self.learnable_sc:
x = torch.cat([x, self.conv_sc(x)], 1)
return x
def forward(self, x):
# 1x1 bottleneck conv
h = self.conv1(F.relu(x))
# 3x3 convs
h = self.conv2(self.activation(h))
h = self.conv3(self.activation(h))
# relu before downsample
h = self.activation(h)
# downsample
if self.downsample:
h = self.downsample(h)
# final 1x1 conv
h = self.conv4(h)
return h + self.shortcut(x)
################### 3D-ResNet #######################
def conv3x3x3(in_planes, out_planes, stride=1, dilation=1):
# 3x3x3 convolution with padding
return nn.Conv3d(
in_planes,
out_planes,
kernel_size=3,
dilation=dilation,
stride=stride,
padding=dilation,
bias=False)
def downsample_basic_block(x, planes, stride, no_cuda=False):
out = F.avg_pool3d(x, kernel_size=1, stride=stride)
zero_pads = torch.Tensor(
out.size(0), planes - out.size(1), out.size(2), out.size(3),
out.size(4)).zero_()
if not no_cuda:
if isinstance(out.data, torch.cuda.FloatTensor):
zero_pads = zero_pads.cuda()
out = Variable(torch.cat([out.data, zero_pads], dim=1))
return out
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3x3(inplanes, planes, stride=stride, dilation=dilation)
self.bn1 = nn.BatchNorm3d(planes)
self.relu = nn.ReLU(inplace=True)
self.conv2 = conv3x3x3(planes, planes, dilation=dilation)
self.bn2 = nn.BatchNorm3d(planes)
self.downsample = downsample
self.stride = stride
self.dilation = dilation
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv3d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm3d(planes)
self.conv2 = nn.Conv3d(
planes, planes, kernel_size=3, stride=stride, dilation=dilation, padding=dilation, bias=False)
self.bn2 = nn.BatchNorm3d(planes)
self.conv3 = nn.Conv3d(planes, planes * 4, kernel_size=1, bias=False)
self.bn3 = nn.BatchNorm3d(planes * 4)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
self.dilation = dilation
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out