Spaces:
Runtime error
Runtime error
Upload encoders/densenet.py
Browse files- encoders/densenet.py +146 -0
encoders/densenet.py
ADDED
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
""" Each encoder should have following attributes and methods and be inherited from `_base.EncoderMixin`
|
2 |
+
|
3 |
+
Attributes:
|
4 |
+
|
5 |
+
_out_channels (list of int): specify number of channels for each encoder feature tensor
|
6 |
+
_depth (int): specify number of stages in decoder (in other words number of downsampling operations)
|
7 |
+
_in_channels (int): default number of input channels in first Conv2d layer for encoder (usually 3)
|
8 |
+
|
9 |
+
Methods:
|
10 |
+
|
11 |
+
forward(self, x: torch.Tensor)
|
12 |
+
produce list of features of different spatial resolutions, each feature is a 4D torch.tensor of
|
13 |
+
shape NCHW (features should be sorted in descending order according to spatial resolution, starting
|
14 |
+
with resolution same as input `x` tensor).
|
15 |
+
|
16 |
+
Input: `x` with shape (1, 3, 64, 64)
|
17 |
+
Output: [f0, f1, f2, f3, f4, f5] - features with corresponding shapes
|
18 |
+
[(1, 3, 64, 64), (1, 64, 32, 32), (1, 128, 16, 16), (1, 256, 8, 8),
|
19 |
+
(1, 512, 4, 4), (1, 1024, 2, 2)] (C - dim may differ)
|
20 |
+
|
21 |
+
also should support number of features according to specified depth, e.g. if depth = 5,
|
22 |
+
number of feature tensors = 6 (one with same resolution as input and 5 downsampled),
|
23 |
+
depth = 3 -> number of feature tensors = 4 (one with same resolution as input and 3 downsampled).
|
24 |
+
"""
|
25 |
+
|
26 |
+
import re
|
27 |
+
import torch.nn as nn
|
28 |
+
|
29 |
+
from pretrainedmodels.models.torchvision_models import pretrained_settings
|
30 |
+
from torchvision.models.densenet import DenseNet
|
31 |
+
|
32 |
+
from ._base import EncoderMixin
|
33 |
+
|
34 |
+
|
35 |
+
class TransitionWithSkip(nn.Module):
|
36 |
+
|
37 |
+
def __init__(self, module):
|
38 |
+
super().__init__()
|
39 |
+
self.module = module
|
40 |
+
|
41 |
+
def forward(self, x):
|
42 |
+
for module in self.module:
|
43 |
+
x = module(x)
|
44 |
+
if isinstance(module, nn.ReLU):
|
45 |
+
skip = x
|
46 |
+
return x, skip
|
47 |
+
|
48 |
+
|
49 |
+
class DenseNetEncoder(DenseNet, EncoderMixin):
|
50 |
+
def __init__(self, out_channels, depth=5, **kwargs):
|
51 |
+
super().__init__(**kwargs)
|
52 |
+
self._out_channels = out_channels
|
53 |
+
self._depth = depth
|
54 |
+
self._in_channels = 3
|
55 |
+
del self.classifier
|
56 |
+
|
57 |
+
def make_dilated(self, stage_list, dilation_list):
|
58 |
+
raise ValueError("DenseNet encoders do not support dilated mode "
|
59 |
+
"due to pooling operation for downsampling!")
|
60 |
+
|
61 |
+
def get_stages(self):
|
62 |
+
return [
|
63 |
+
nn.Identity(),
|
64 |
+
nn.Sequential(self.features.conv0, self.features.norm0, self.features.relu0),
|
65 |
+
nn.Sequential(self.features.pool0, self.features.denseblock1,
|
66 |
+
TransitionWithSkip(self.features.transition1)),
|
67 |
+
nn.Sequential(self.features.denseblock2, TransitionWithSkip(self.features.transition2)),
|
68 |
+
nn.Sequential(self.features.denseblock3, TransitionWithSkip(self.features.transition3)),
|
69 |
+
nn.Sequential(self.features.denseblock4, self.features.norm5)
|
70 |
+
]
|
71 |
+
|
72 |
+
def forward(self, x):
|
73 |
+
|
74 |
+
stages = self.get_stages()
|
75 |
+
|
76 |
+
features = []
|
77 |
+
for i in range(self._depth + 1):
|
78 |
+
x = stages[i](x)
|
79 |
+
if isinstance(x, (list, tuple)):
|
80 |
+
x, skip = x
|
81 |
+
features.append(skip)
|
82 |
+
else:
|
83 |
+
features.append(x)
|
84 |
+
|
85 |
+
return features
|
86 |
+
|
87 |
+
def load_state_dict(self, state_dict):
|
88 |
+
pattern = re.compile(
|
89 |
+
r"^(.*denselayer\d+\.(?:norm|relu|conv))\.((?:[12])\.(?:weight|bias|running_mean|running_var))$"
|
90 |
+
)
|
91 |
+
for key in list(state_dict.keys()):
|
92 |
+
res = pattern.match(key)
|
93 |
+
if res:
|
94 |
+
new_key = res.group(1) + res.group(2)
|
95 |
+
state_dict[new_key] = state_dict[key]
|
96 |
+
del state_dict[key]
|
97 |
+
|
98 |
+
# remove linear
|
99 |
+
state_dict.pop("classifier.bias", None)
|
100 |
+
state_dict.pop("classifier.weight", None)
|
101 |
+
|
102 |
+
super().load_state_dict(state_dict)
|
103 |
+
|
104 |
+
|
105 |
+
densenet_encoders = {
|
106 |
+
"densenet121": {
|
107 |
+
"encoder": DenseNetEncoder,
|
108 |
+
"pretrained_settings": pretrained_settings["densenet121"],
|
109 |
+
"params": {
|
110 |
+
"out_channels": (3, 64, 256, 512, 1024, 1024),
|
111 |
+
"num_init_features": 64,
|
112 |
+
"growth_rate": 32,
|
113 |
+
"block_config": (6, 12, 24, 16),
|
114 |
+
},
|
115 |
+
},
|
116 |
+
"densenet169": {
|
117 |
+
"encoder": DenseNetEncoder,
|
118 |
+
"pretrained_settings": pretrained_settings["densenet169"],
|
119 |
+
"params": {
|
120 |
+
"out_channels": (3, 64, 256, 512, 1280, 1664),
|
121 |
+
"num_init_features": 64,
|
122 |
+
"growth_rate": 32,
|
123 |
+
"block_config": (6, 12, 32, 32),
|
124 |
+
},
|
125 |
+
},
|
126 |
+
"densenet201": {
|
127 |
+
"encoder": DenseNetEncoder,
|
128 |
+
"pretrained_settings": pretrained_settings["densenet201"],
|
129 |
+
"params": {
|
130 |
+
"out_channels": (3, 64, 256, 512, 1792, 1920),
|
131 |
+
"num_init_features": 64,
|
132 |
+
"growth_rate": 32,
|
133 |
+
"block_config": (6, 12, 48, 32),
|
134 |
+
},
|
135 |
+
},
|
136 |
+
"densenet161": {
|
137 |
+
"encoder": DenseNetEncoder,
|
138 |
+
"pretrained_settings": pretrained_settings["densenet161"],
|
139 |
+
"params": {
|
140 |
+
"out_channels": (3, 96, 384, 768, 2112, 2208),
|
141 |
+
"num_init_features": 96,
|
142 |
+
"growth_rate": 48,
|
143 |
+
"block_config": (6, 12, 36, 24),
|
144 |
+
},
|
145 |
+
},
|
146 |
+
}
|