前言
论文地址: https://arxiv.org/abs/1911.11907.
源码(pytorch):https://github.com/huawei-noah/CV-Backbones/tree/master/ghostnet_pytorch.
贡献:
1、提出了新型的轻量化网络模块 Ghost Module (GhostConv 和 Ghost bottleneck)
2、提出新型轻量化网络GhostNet
一、背景
由于硬件资源以及计算量的限制,在嵌入式设备当中部署卷积神经网络是很困难的。想要解决这个问题,就要想方设法的使网络模型更加的轻量化。现存的网络模型轻量化方法一般有两种:模型压缩和轻量化网络设计。
模型压缩:
- pruning connection: 减去一些不重要的神经元连接;
- channel pruning: 通道剪枝,减去一些无用的通道,以便加速运算;
- model quantization: 模型量化,在具有离散值的神经网络中对权重或激活函数进行压缩和计算加速;
- tensor decomposition: 张量分解,通过权重的冗余性和low-link来减少参数或计算;
- knowledge distillation: 知识蒸馏, 利用大模型来教小模型,提高小模型的性能
轻量化网络设计:
- Xception: depthwise conv operation
- MobileNet 系列: 深度可分离卷积 depthwise separable conv、inverted resdual block、AutoML technology
- ShuffleNet 系列: channel shuffle operation
尽管这些模型获得了良好的性能,但是feature map之间的相关性和冗余性一直没有得到很好的利用。
那么什么是feature map之间的相关性和冗余性呢?
如下图,作者在实验过程中将ResNet50的第一个残差组的feature map进行可视化,发现里面有三对feature map(如下图中的红绿蓝三对feature map)它们极其相似,作者认为这些feature map对之间是冗余的(相关的)。
作者考虑到这些feature map层中的冗余信息可能是一个成功模型的重要组成部分,正是因为这些冗余信息才能保证输入数据的全面理解,所以作者在设计轻量化模型的时候并没有试图去除这些冗余feature map,而是尝试使用更低成本的计算量来获取这些冗余feature map。
作者生动的将这些冗余的feature map称为 Ghost(幽灵) 。
其他两个前提知识:
-
Ghost feature maps 和 Intrinsic feature maps 是什么?
intrinsic feature maps 执行 linear operations 得到 ghost feature maps。
如上图,一部分是Intrinic,而另外一部分是可以由 intrinsic 通过cheap operations来生成的,因为本来就是由intrinsic feature maps 生成的,所以肯定会有很多的冗余信息,所以称其为 ghost feature maps。 -
Linear transformations 和 Cheap operations 是什么?
通读全文会发现到处都是Linear transformations和Cheap operations ,其实它们两者是等价的,即是 3x3的卷积,或者5x5的卷积。
ok,关于背景知识大概就是这些,下面继续学习Ghost的核心模块。
二、Ghost Module
这部分是本论文最创新最核心的模块。
先看看正常卷积模块是什么样的,如下图:
再看看我们的新型轻量卷积模块 Ghost Module:
第一步: 少量卷积(比如正常用32个卷积核,这里就用16个,从而减少一半的计算量)
第二步:cheap operations,如图中的Φ表示,从问题3中可知,Φ 是诸如3x3 或 5x5的卷积,并且是逐个特征图的进行卷积(Depth-wise convolutional)。
比较两种的FLOPs有:
可以看出,使用Ghost Module模块,FLOPs一般可以减少为原来的 1/s。
这里再科普一下:
FLOPs(floating point operations):可以用来衡量算法/模型的复杂度。
计算方式: F L O P s = C o u t ∗ H o u t ∗ W o u t ∗ C i n ∗ K ∗ K FLOPs = C_{out} * H_{out} * W_{out} * C_{in} * K * K FLOPs=Cout∗Hout∗Wout∗Cin∗K∗K
FLOPS(floating point operations per second):意指每秒浮点运算次数,理解为计算速度。是一个衡量硬件性能的指标。
最后再对比下 Depthwise Separate Conv(深度可分卷积) 和 Ghost Module(幻象模块):
- 深度可分卷积是用深度卷积处理每一个特征通道上的空间信息,然后用点卷积进行通道间的特征融合;
- 而幻象模块是用正常的卷积生成部分真实feature map,再用这些真实的feature map经过线性变换 (Cheap operations ) 得到幻象特征层(Ghost feature map),最终由真实特征层和幻象特征层组成完整特征层。
自己用pytorch实现(YOLOV5中):
class Conv(nn.Module):
def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True):
"""
Standard convolution conv+BN+act
:params c1: 输入的channel值
:params c2: 输出的channel值
:params k: 卷积的kernel_size
:params s: 卷积的stride
:params p: 卷积的padding 一般是None 可以通过autopad自行计算需要pad的padding数
:params g: 卷积的groups数 =1就是普通的卷积 >1就是深度可分离卷积
:params act: 激活函数类型 True就是SiLU()/Swish False就是不使用激活函数
类型是nn.Module就使用传进来的激活函数类型
"""
super(Conv, self).__init__()
self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False)
self.bn = nn.BatchNorm2d(c2)
# 激活函数自己选择
self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity())
def forward(self, x):
return self.act(self.bn(self.conv(x)))
def fuseforward(self, x):
"""
前向融合计算 减少推理时间????
"""
return self.act(self.conv(x))
class GhostConv(nn.Module):
# Ghost Convolution https://github.com/huawei-noah/ghostnet
def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups
super(GhostConv, self).__init__()
c_ = c2 // 2 # hidden channels
self.cv1 = Conv(c1, c_, k, s, None, g, act)
self.cv2 = Conv(c_, c_, 5, 1, None, c_, act) # 也可以改成3x3
def forward(self, x):
y = self.cv1(x)
return torch.cat([y, self.cv2(y)], 1)
三、Ghost Bottleneck
幻象瓶颈层是为轻量化网络模型而设计的类似残差块的结构。幻象瓶颈层由两个幻象模块组成。第一个幻象模块作为扩张层(expansion layer),用于增加通道数目,输出channle / 输入channel 我们称为扩张率(expansion ratio);第二个幻象模块用于减少通道数目,使其输入数据通道数匹配,进行shortcut。如上图,是论文中设计的两种幻象瓶颈层,左边的Stride=1,右边的Stride=2,对于stride=2的shortcut我在阅读源码时发现,并不是直接Identity连接,而是先经过一个DWConv + Conv,再进行shortcut连接的。
自己用pytorch实现(YOLOV5中):
class GhostBottleneck(nn.Module):
# Ghost Bottleneck https://github.com/huawei-noah/ghostnet
def __init__(self, c1, c2, k=3, s=1): # ch_in, ch_out, kernel, stride
super(GhostBottleneck, self).__init__()
c_ = c2 // 2
self.conv = nn.Sequential(GhostConv(c1, c_, 1, 1), # pw
DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw
GhostConv(c_, c2, 1, 1, act=False)) # pw-linear
self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False),
Conv(c1, c2, 1, 1, act=False)) if s == 2 else nn.Identity()
def forward(self, x):
return self.conv(x) + self.shortcut(x)
这个模块是即插即用的,很方便,所以大家都可以试试。
四、GhostNet
GhostNet采用的是MobileNetV3的网络结构,只是将其中的瓶颈层改成幻想瓶颈层Ghost Bottleneck。
具体网络结构如下:
官方代码(与我写的略有不同):
"""
Creates a GhostNet Model as defined in:
GhostNet: More Features from Cheap Operations By Kai Han, Yunhe Wang, Qi Tian, Jianyuan Guo, Chunjing Xu, Chang Xu.
https://arxiv.org/abs/1911.11907
Modified from https://github.com/d-li14/mobilenetv3.pytorch and https://github.com/rwightman/pytorch-image-models
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
def _make_divisible(v, divisor, min_value=None):
"""
This function is taken from the original tf repo.
It ensures that all layers have a channel number that is divisible by 8
It can be seen here:
https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
"""
if min_value is None:
min_value = divisor
new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
# Make sure that round down does not go down by more than 10%.
if new_v < 0.9 * v:
new_v += divisor
return new_v
def hard_sigmoid(x, inplace: bool = False):
if inplace:
return x.add_(3.).clamp_(0., 6.).div_(6.)
else:
return F.relu6(x + 3.) / 6.
class SqueezeExcite(nn.Module):
def __init__(self, in_chs, se_ratio=0.25, reduced_base_chs=None,
act_layer=nn.ReLU, gate_fn=hard_sigmoid, divisor=4, **_):
super(SqueezeExcite, self).__init__()
self.gate_fn = gate_fn
reduced_chs = _make_divisible((reduced_base_chs or in_chs) * se_ratio, divisor)
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.conv_reduce = nn.Conv2d(in_chs, reduced_chs, 1, bias=True)
self.act1 = act_layer(inplace=True)
self.conv_expand = nn.Conv2d(reduced_chs, in_chs, 1, bias=True)
def forward(self, x):
x_se = self.avg_pool(x)
x_se = self.conv_reduce(x_se)
x_se = self.act1(x_se)
x_se = self.conv_expand(x_se)
x = x * self.gate_fn(x_se)
return x
class ConvBnAct(nn.Module):
def __init__(self, in_chs, out_chs, kernel_size,
stride=1, act_layer=nn.ReLU):
super(ConvBnAct, self).__init__()
self.conv = nn.Conv2d(in_chs, out_chs, kernel_size, stride, kernel_size // 2, bias=False)
self.bn1 = nn.BatchNorm2d(out_chs)
self.act1 = act_layer(inplace=True)
def forward(self, x):
x = self.conv(x)
x = self.bn1(x)
x = self.act1(x)
return x
class GhostModule(nn.Module):
def __init__(self, inp, oup, kernel_size=1, ratio=2, dw_size=3, stride=1, relu=True):
super(GhostModule, self).__init__()
self.oup = oup
init_channels = math.ceil(oup / ratio)
new_channels = init_channels * (ratio - 1)
self.primary_conv = nn.Sequential(
nn.Conv2d(inp, init_channels, kernel_size, stride, kernel_size // 2, bias=False),
nn.BatchNorm2d(init_channels),
nn.ReLU(inplace=True) if relu else nn.Sequential(),
)
self.cheap_operation = nn.Sequential(
nn.Conv2d(init_channels, new_channels, dw_size, 1, dw_size // 2, groups=init_channels, bias=False),
nn.BatchNorm2d(new_channels),
nn.ReLU(inplace=True) if relu else nn.Sequential(),
)
def forward(self, x):
x1 = self.primary_conv(x)
x2 = self.cheap_operation(x1)
out = torch.cat([x1, x2], dim=1)
return out[:, :self.oup, :, :]
class GhostBottleneck(nn.Module):
""" Ghost bottleneck w/ optional SE"""
def __init__(self, in_chs, mid_chs, out_chs, dw_kernel_size=3,
stride=1, act_layer=nn.ReLU, se_ratio=0.):
super(GhostBottleneck, self).__init__()
has_se = se_ratio is not None and se_ratio > 0.
self.stride = stride
# Point-wise expansion
self.ghost1 = GhostModule(in_chs, mid_chs, relu=True)
# Depth-wise convolution
if self.stride > 1:
self.conv_dw = nn.Conv2d(mid_chs, mid_chs, dw_kernel_size, stride=stride,
padding=(dw_kernel_size - 1) // 2,
groups=mid_chs, bias=False)
self.bn_dw = nn.BatchNorm2d(mid_chs)
# Squeeze-and-excitation
if has_se:
self.se = SqueezeExcite(mid_chs, se_ratio=se_ratio)
else:
self.se = None
# Point-wise linear projection
self.ghost2 = GhostModule(mid_chs, out_chs, relu=False)
# shortcut
if (in_chs == out_chs and self.stride == 1):
self.shortcut = nn.Sequential()
else:
self.shortcut = nn.Sequential(
nn.Conv2d(in_chs, in_chs, dw_kernel_size, stride=stride,
padding=(dw_kernel_size - 1) // 2, groups=in_chs, bias=False),
nn.BatchNorm2d(in_chs),
nn.Conv2d(in_chs, out_chs, 1, stride=1, padding=0, bias=False),
nn.BatchNorm2d(out_chs),
)
def forward(self, x):
residual = x
# 1st ghost bottleneck
x = self.ghost1(x)
# Depth-wise convolution
if self.stride > 1:
x = self.conv_dw(x)
x = self.bn_dw(x)
# Squeeze-and-excitation
if self.se is not None:
x = self.se(x)
# 2nd ghost bottleneck
x = self.ghost2(x)
x += self.shortcut(residual)
return x
class GhostNet(nn.Module):
def __init__(self, cfgs, num_classes=1000, width=1.0, dropout=0.2):
super(GhostNet, self).__init__()
# width: 宽度因子
# setting of inverted residual blocks
self.cfgs = cfgs
self.dropout = dropout
# building first layer
output_channel = _make_divisible(16 * width, 4)
self.conv_stem = nn.Conv2d(3, output_channel, 3, 2, 1, bias=False)
self.bn1 = nn.BatchNorm2d(output_channel)
self.act1 = nn.ReLU(inplace=True)
input_channel = output_channel
# building inverted residual blocks
stages = []
block = GhostBottleneck
for cfg in self.cfgs:
layers = []
for k, exp_size, c, se_ratio, s in cfg:
output_channel = _make_divisible(c * width, 4)
hidden_channel = _make_divisible(exp_size * width, 4)
layers.append(block(input_channel, hidden_channel, output_channel, k, s,
se_ratio=se_ratio))
input_channel = output_channel
stages.append(nn.Sequential(*layers))
output_channel = _make_divisible(exp_size * width, 4)
stages.append(nn.Sequential(ConvBnAct(input_channel, output_channel, 1)))
input_channel = output_channel
self.blocks = nn.Sequential(*stages)
# building last several layers
output_channel = 1280
self.global_pool = nn.AdaptiveAvgPool2d((1, 1))
self.conv_head = nn.Conv2d(input_channel, output_channel, 1, 1, 0, bias=True)
self.act2 = nn.ReLU(inplace=True)
self.classifier = nn.Linear(output_channel, num_classes)
def forward(self, x):
x = self.conv_stem(x)
x = self.bn1(x)
x = self.act1(x)
x = self.blocks(x)
x = self.global_pool(x)
x = self.conv_head(x)
x = self.act2(x)
x = x.view(x.size(0), -1)
if self.dropout > 0.:
x = F.dropout(x, p=self.dropout, training=self.training)
x = self.classifier(x)
return x
def ghostnet(**kwargs):
"""
Constructs a GhostNet model
"""
cfgs = [
# k, t, c, SE, s
# stage1
[[3, 16, 16, 0, 1]],
# stage2
[[3, 48, 24, 0, 2]],
[[3, 72, 24, 0, 1]],
# stage3
[[5, 72, 40, 0.25, 2]],
[[5, 120, 40, 0.25, 1]],
# stage4
[[3, 240, 80, 0, 2]],
[[3, 200, 80, 0, 1],
[3, 184, 80, 0, 1],
[3, 184, 80, 0, 1],
[3, 480, 112, 0.25, 1],
[3, 672, 112, 0.25, 1]
],
# stage5
[[5, 672, 160, 0.25, 2]],
[[5, 960, 160, 0, 1],
[5, 960, 160, 0.25, 1],
[5, 960, 160, 0, 1],
[5, 960, 160, 0.25, 1]
]
]
return GhostNet(cfgs, **kwargs)
if __name__ == '__main__':
model = ghostnet()
model.eval()
print(model)
input = torch.randn(32, 3, 320, 256)
y = model(input)
print(y.size())
代码和ResNet很像,都是函数式的模块化开发,重点掌握Ghost Module和Ghost Bottleneck 两部分的代码就不会很难的,感兴趣的自己可以看看。