58 lines
1.6 KiB
Python
58 lines
1.6 KiB
Python
from mmcv.cnn import ConvModule, build_norm_layer
|
|
from torch import nn
|
|
|
|
|
|
class InvertedResidual(nn.Module):
|
|
|
|
def __init__(self,
|
|
inp,
|
|
oup,
|
|
stride,
|
|
expand_ratio,
|
|
dilation=1,
|
|
conv_cfg=None,
|
|
norm_cfg=dict(type='BN'),
|
|
act_cfg=dict(type='ReLU6')):
|
|
super(InvertedResidual, self).__init__()
|
|
self.stride = stride
|
|
assert stride in [1, 2]
|
|
|
|
hidden_dim = int(round(inp * expand_ratio))
|
|
self.use_res_connect = self.stride == 1 and inp == oup
|
|
|
|
layers = []
|
|
if expand_ratio != 1:
|
|
# pw
|
|
layers.append(
|
|
ConvModule(
|
|
inp,
|
|
hidden_dim,
|
|
kernel_size=1,
|
|
conv_cfg=conv_cfg,
|
|
norm_cfg=norm_cfg,
|
|
act_cfg=act_cfg))
|
|
layers.extend([
|
|
# dw
|
|
ConvModule(
|
|
hidden_dim,
|
|
hidden_dim,
|
|
kernel_size=3,
|
|
padding=dilation,
|
|
stride=stride,
|
|
dilation=dilation,
|
|
groups=hidden_dim,
|
|
conv_cfg=conv_cfg,
|
|
norm_cfg=norm_cfg,
|
|
act_cfg=act_cfg),
|
|
# pw-linear
|
|
nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),
|
|
build_norm_layer(norm_cfg, oup)[1],
|
|
])
|
|
self.conv = nn.Sequential(*layers)
|
|
|
|
def forward(self, x):
|
|
if self.use_res_connect:
|
|
return x + self.conv(x)
|
|
else:
|
|
return self.conv(x)
|