forked from qubvel-org/segmentation_models.pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecoder.py
108 lines (90 loc) · 2.97 KB
/
decoder.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
import torch
import torch.nn as nn
from typing import Any, Dict, List, Optional, Union
from segmentation_models_pytorch.base import modules
class TransposeX2(nn.Sequential):
def __init__(
self,
in_channels: int,
out_channels: int,
use_norm: Union[bool, str, Dict[str, Any]] = "batchnorm",
):
super().__init__()
layers = [
nn.ConvTranspose2d(
in_channels, out_channels, kernel_size=4, stride=2, padding=1
),
nn.ReLU(inplace=True),
]
if use_norm != "identity":
if isinstance(use_norm, dict):
if use_norm.get("type") != "identity":
layers.insert(1, modules.get_norm_layer(use_norm, out_channels))
else:
layers.insert(1, modules.get_norm_layer(use_norm, out_channels))
super().__init__(*layers)
class DecoderBlock(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
use_norm: Union[bool, str, Dict[str, Any]] = True,
):
super().__init__()
self.block = nn.Sequential(
modules.Conv2dReLU(
in_channels,
in_channels // 4,
kernel_size=1,
use_norm=use_norm,
),
TransposeX2(
in_channels // 4, in_channels // 4, use_norm=use_norm
),
modules.Conv2dReLU(
in_channels // 4,
out_channels,
kernel_size=1,
use_norm=use_norm,
),
)
def forward(
self, x: torch.Tensor, skip: Optional[torch.Tensor] = None
) -> torch.Tensor:
x = self.block(x)
if skip is not None:
x = x + skip
return x
class LinknetDecoder(nn.Module):
def __init__(
self,
encoder_channels: List[int],
prefinal_channels: int = 32,
n_blocks: int = 5,
use_norm: Union[bool, str, Dict[str, Any]] = True,
):
super().__init__()
# remove first skip
encoder_channels = encoder_channels[1:]
# reverse channels to start from head of encoder
encoder_channels = encoder_channels[::-1]
channels = list(encoder_channels) + [prefinal_channels]
self.blocks = nn.ModuleList(
[
DecoderBlock(
channels[i],
channels[i + 1],
use_norm=use_norm,
)
for i in range(n_blocks)
]
)
def forward(self, features: List[torch.Tensor]) -> torch.Tensor:
features = features[1:] # remove first skip
features = features[::-1] # reverse channels to start from head of encoder
x = features[0]
skips = features[1:]
for i, decoder_block in enumerate(self.blocks):
skip = skips[i] if i < len(skips) else None
x = decoder_block(x, skip)
return x