-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathunet.py
executable file
·277 lines (245 loc) · 8.23 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
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
from functools import partial
from typing import Callable, List, Tuple
import torch as th
import torch.nn.functional as F
from torch import nn
class Block(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
conv_layer: Callable,
residual: bool,
kernel_size: int = 3,
):
super().__init__()
self.residual = residual
self.conv1 = conv_layer(
in_channels, out_channels, kernel_size=kernel_size, padding="same"
)
self.conv2 = conv_layer(
out_channels, out_channels, kernel_size=kernel_size, padding="same"
)
self.res_conv = None
if self.residual:
self.res_conv = conv_layer(
in_channels,
out_channels,
kernel_size=1,
padding="same",
)
def forward(self, x: th.Tensor) -> th.Tensor:
if self.residual:
res = self.res_conv(x)
x = F.relu(self.conv1(x), inplace=True)
x = F.relu(self.conv2(x) + res, inplace=True)
else:
x = F.relu(self.conv1(x), inplace=True)
x = F.relu(self.conv2(x), inplace=True)
return x
class Encoder(nn.Module):
def __init__(
self,
planes: Tuple[int],
conv_layer: Callable,
pool_layer: Callable,
residual: bool,
kernel_size: int,
):
super().__init__()
self.blocks = nn.ModuleList(
[
Block(
in_planes, out_planes, conv_layer, residual, kernel_size=kernel_size
)
for in_planes, out_planes in zip(planes[:-1], planes[1:])
]
)
self.pool_layer = pool_layer
def forward(self, x: th.Tensor) -> List[th.Tensor]:
feats = []
for block in self.blocks:
x = block(x)
feats.append(x)
x = self.pool_layer(x)
return feats
class Decoder(nn.Module):
def __init__(
self,
planes: Tuple[int],
conv_layer: Callable,
interp_layer: Callable,
residual: bool,
kernel_size: int,
):
super().__init__()
self.first_block = conv_layer(
planes[0], planes[1], kernel_size=3, padding="same"
)
self.blocks = nn.ModuleList(
[
Block(
2 * in_planes,
out_planes,
conv_layer,
residual,
kernel_size=kernel_size,
)
for in_planes, out_planes in zip(planes[1:-1], planes[2:])
]
)
self.interp_layer = interp_layer
@staticmethod
def center_crop(x: th.Tensor, shape: th.Size) -> th.Tensor:
assert x.shape[:2] == shape[:2], f"Found {x.shape} and {shape}"
shape_dif = tuple(xs - s for xs, s in zip(x.shape, shape))
slicing = tuple(
slice(d - d // 2, xs - d // 2) for xs, d in zip(x.shape, shape_dif)
)
return x[slicing]
def forward(self, x: th.Tensor, encoder_features: List[th.Tensor]) -> th.Tensor:
x = self.first_block(x)
for feats, block in zip(encoder_features, self.blocks):
x = self.interp_layer(x, scale_factor=2)
feats = self.center_crop(feats, x.shape)
x = th.cat((x, feats), dim=1)
x = block(x)
return x
class UNet(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
planes: Tuple[int] = (32, 64, 128, 256),
conv_layer: Callable = nn.Conv2d,
resize_output: bool = True,
kernel_size: int = 3,
residual: bool = False,
):
super().__init__()
if conv_layer == nn.Conv2d:
pool_layer = partial(F.max_pool2d, kernel_size=2)
self.interp_layer = partial(
F.interpolate, mode="bilinear", align_corners=False
)
elif conv_layer == nn.Conv3d:
pool_layer = partial(F.max_pool3d, kernel_size=2)
self.interp_layer = partial(
F.interpolate, mode="trilinear", align_corners=False
)
else:
raise NotImplementedError
self._resize_output = resize_output
self.encoder = Encoder(
(in_channels,) + planes,
conv_layer=conv_layer,
pool_layer=pool_layer,
residual=residual,
kernel_size=kernel_size,
)
self.decoder = Decoder(
planes[::-1],
conv_layer=conv_layer,
interp_layer=self.interp_layer,
residual=residual,
kernel_size=kernel_size,
)
self.head = conv_layer(planes[0], out_channels, kernel_size=1)
self.init_weights()
def forward(self, x):
shape = x.shape[2:]
encoder_feats = self.encoder(x)
out = self.decoder(encoder_feats[-1], encoder_feats[:-1][::-1])
out = self.head(out)
if self._resize_output:
out = self.interp_layer(out, size=shape)
return out
def init_weights(self):
for m in self.modules():
if isinstance(m, (nn.Conv2d, nn.Conv3d)):
nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")
class EdgeDecoder(Decoder):
def __init__(
self,
planes: Tuple[int],
conv_layer: Callable,
interp_layer: Callable,
residual: bool,
kernel_size: int,
):
super().__init__(
planes, conv_layer, interp_layer, residual, kernel_size=kernel_size
)
self.edge_blocks = nn.ModuleList(
[conv_layer(n_planes, 1, kernel_size=1) for n_planes in planes[1:-1]]
)
def forward(
self,
x: th.Tensor,
encoder_features: List[th.Tensor],
) -> Tuple[th.Tensor, List[th.Tensor]]:
x = self.first_block(x)
edges = []
for feats, block, edge_block in zip(
encoder_features, self.blocks, self.edge_blocks
):
edges.append(edge_block(x))
x = self.interp_layer(x, scale_factor=2)
feats = self.center_crop(feats, x.shape)
x = th.cat((x, feats), dim=1)
x = block(x)
return x, edges
class EdgeUNet(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
planes: Tuple[int] = (32, 64, 128, 256),
conv_layer: Callable = nn.Conv2d,
resize_output: bool = True,
residual: bool = False,
kernel_size: int = 3,
) -> None:
super().__init__()
if conv_layer == nn.Conv2d:
pool_layer = partial(F.max_pool2d, kernel_size=2)
self.interp_layer = partial(
F.interpolate, mode="bilinear", align_corners=False
)
elif conv_layer == nn.Conv3d:
pool_layer = partial(F.max_pool3d, kernel_size=2)
self.interp_layer = partial(
F.interpolate, mode="trilinear", align_corners=False
)
else:
raise NotImplementedError
self._resize_output = resize_output
self.encoder = Encoder(
(in_channels,) + planes,
conv_layer=conv_layer,
pool_layer=pool_layer,
residual=residual,
kernel_size=kernel_size,
)
self.decoder = EdgeDecoder(
planes[::-1],
conv_layer=conv_layer,
interp_layer=self.interp_layer,
residual=residual,
kernel_size=kernel_size,
)
self.head = conv_layer(planes[0], out_channels, kernel_size=1)
self.init_weights()
def forward(self, x):
shape = x.shape[2:]
encoder_feats = self.encoder(x)
out, edges = self.decoder(encoder_feats[-1], encoder_feats[:-1][::-1])
out = self.head(out)
if self._resize_output:
edges = [self.interp_layer(e, size=shape) for e in edges]
out = self.interp_layer(out, size=shape)
return out, edges
def init_weights(self):
for m in self.modules():
if isinstance(m, (nn.Conv2d, nn.Conv3d)):
nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")