forked from lhoyer/DAFormer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
daformer_head.py
184 lines (165 loc) · 6.43 KB
/
daformer_head.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
# ---------------------------------------------------------------
# Copyright (c) 2021-2022 ETH Zurich, Lukas Hoyer. All rights reserved.
# Licensed under the Apache License, Version 2.0
# ---------------------------------------------------------------
import torch
import torch.nn as nn
from mmcv.cnn import ConvModule, DepthwiseSeparableConvModule
from mmseg.models.decode_heads.isa_head import ISALayer
from mmseg.ops import resize
from ..builder import HEADS
from .aspp_head import ASPPModule
from .decode_head import BaseDecodeHead
from .segformer_head import MLP
from .sep_aspp_head import DepthwiseSeparableASPPModule
class ASPPWrapper(nn.Module):
def __init__(self,
in_channels,
channels,
sep,
dilations,
pool,
norm_cfg,
act_cfg,
align_corners,
context_cfg=None):
super(ASPPWrapper, self).__init__()
assert isinstance(dilations, (list, tuple))
self.dilations = dilations
self.align_corners = align_corners
if pool:
self.image_pool = nn.Sequential(
nn.AdaptiveAvgPool2d(1),
ConvModule(
in_channels,
channels,
1,
norm_cfg=norm_cfg,
act_cfg=act_cfg))
else:
self.image_pool = None
if context_cfg is not None:
self.context_layer = build_layer(in_channels, channels,
**context_cfg)
else:
self.context_layer = None
ASPP = {True: DepthwiseSeparableASPPModule, False: ASPPModule}[sep]
self.aspp_modules = ASPP(
dilations=dilations,
in_channels=in_channels,
channels=channels,
norm_cfg=norm_cfg,
conv_cfg=None,
act_cfg=act_cfg)
self.bottleneck = ConvModule(
(len(dilations) + int(pool) + int(bool(context_cfg))) * channels,
channels,
kernel_size=3,
padding=1,
norm_cfg=norm_cfg,
act_cfg=act_cfg)
def forward(self, x):
"""Forward function."""
aspp_outs = []
if self.image_pool is not None:
aspp_outs.append(
resize(
self.image_pool(x),
size=x.size()[2:],
mode='bilinear',
align_corners=self.align_corners))
if self.context_layer is not None:
aspp_outs.append(self.context_layer(x))
aspp_outs.extend(self.aspp_modules(x))
aspp_outs = torch.cat(aspp_outs, dim=1)
output = self.bottleneck(aspp_outs)
return output
def build_layer(in_channels, out_channels, type, **kwargs):
if type == 'id':
return nn.Identity()
elif type == 'mlp':
return MLP(input_dim=in_channels, embed_dim=out_channels)
elif type == 'sep_conv':
return DepthwiseSeparableConvModule(
in_channels=in_channels,
out_channels=out_channels,
padding=kwargs['kernel_size'] // 2,
**kwargs)
elif type == 'conv':
return ConvModule(
in_channels=in_channels,
out_channels=out_channels,
padding=kwargs['kernel_size'] // 2,
**kwargs)
elif type == 'aspp':
return ASPPWrapper(
in_channels=in_channels, channels=out_channels, **kwargs)
elif type == 'rawconv_and_aspp':
kernel_size = kwargs.pop('kernel_size')
return nn.Sequential(
nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
padding=kernel_size // 2),
ASPPWrapper(
in_channels=out_channels, channels=out_channels, **kwargs))
elif type == 'isa':
return ISALayer(
in_channels=in_channels, channels=out_channels, **kwargs)
else:
raise NotImplementedError(type)
@HEADS.register_module()
class DAFormerHead(BaseDecodeHead):
def __init__(self, **kwargs):
super(DAFormerHead, self).__init__(
input_transform='multiple_select', **kwargs)
assert not self.align_corners
decoder_params = kwargs['decoder_params']
embed_dims = decoder_params['embed_dims']
if isinstance(embed_dims, int):
embed_dims = [embed_dims] * len(self.in_index)
embed_cfg = decoder_params['embed_cfg']
embed_neck_cfg = decoder_params['embed_neck_cfg']
if embed_neck_cfg == 'same_as_embed_cfg':
embed_neck_cfg = embed_cfg
fusion_cfg = decoder_params['fusion_cfg']
for cfg in [embed_cfg, embed_neck_cfg, fusion_cfg]:
if cfg is not None and 'aspp' in cfg['type']:
cfg['align_corners'] = self.align_corners
self.embed_layers = {}
for i, in_channels, embed_dim in zip(self.in_index, self.in_channels,
embed_dims):
if i == self.in_index[-1]:
self.embed_layers[str(i)] = build_layer(
in_channels, embed_dim, **embed_neck_cfg)
else:
self.embed_layers[str(i)] = build_layer(
in_channels, embed_dim, **embed_cfg)
self.embed_layers = nn.ModuleDict(self.embed_layers)
self.fuse_layer = build_layer(
sum(embed_dims), self.channels, **fusion_cfg)
def forward(self, inputs):
x = inputs
n, _, h, w = x[-1].shape
# for f in x:
# mmcv.print_log(f'{f.shape}', 'mmseg')
os_size = x[0].size()[2:]
_c = {}
for i in self.in_index:
# mmcv.print_log(f'{i}: {x[i].shape}', 'mmseg')
_c[i] = self.embed_layers[str(i)](x[i])
if _c[i].dim() == 3:
_c[i] = _c[i].permute(0, 2, 1).contiguous()\
.reshape(n, -1, x[i].shape[2], x[i].shape[3])
# mmcv.print_log(f'_c{i}: {_c[i].shape}', 'mmseg')
if _c[i].size()[2:] != os_size:
# mmcv.print_log(f'resize {i}', 'mmseg')
_c[i] = resize(
_c[i],
size=os_size,
mode='bilinear',
align_corners=self.align_corners)
x = self.fuse_layer(torch.cat(list(_c.values()), dim=1))
x = self.cls_seg(x)
return x