Skip to content

Commit

Permalink
Merge pull request #1923 from huggingface/yehuitang-Add-GhostNetV2
Browse files Browse the repository at this point in the history
ghostnetv2 cleanup
  • Loading branch information
rwightman authored Aug 20, 2023
2 parents 7c2728c + be4e0d8 commit e6aeb91
Showing 1 changed file with 114 additions and 11 deletions.
125 changes: 114 additions & 11 deletions timm/models/ghostnet.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
"""
An implementation of GhostNet Model as defined in:
An implementation of GhostNet & GhostNetV2 Models as defined in:
GhostNet: More Features from Cheap Operations. https://arxiv.org/abs/1911.11907
The train script of the model is similar to that of MobileNetV3
GhostNetV2: Enhance Cheap Operation with Long-Range Attention. https://proceedings.neurips.cc/paper_files/paper/2022/file/40b60852a4abdaa696b5a1a78da34635-Paper-Conference.pdf
The train script & code of models at:
Original model: https://github.com/huawei-noah/CV-backbones/tree/master/ghostnet_pytorch
Original model: https://github.com/huawei-noah/Efficient-AI-Backbones/blob/master/ghostnetv2_pytorch/model/ghostnetv2_torch.py
"""
import math
from functools import partial
Expand Down Expand Up @@ -33,7 +36,8 @@ def __init__(
ratio=2,
dw_size=3,
stride=1,
relu=True,
use_act=True,
act_layer=nn.ReLU,
):
super(GhostModule, self).__init__()
self.out_chs = out_chs
Expand All @@ -43,13 +47,13 @@ def __init__(
self.primary_conv = nn.Sequential(
nn.Conv2d(in_chs, init_chs, kernel_size, stride, kernel_size // 2, bias=False),
nn.BatchNorm2d(init_chs),
nn.ReLU(inplace=True) if relu else nn.Identity(),
act_layer(inplace=True) if use_act else nn.Identity(),
)

self.cheap_operation = nn.Sequential(
nn.Conv2d(init_chs, new_chs, dw_size, 1, dw_size//2, groups=init_chs, bias=False),
nn.BatchNorm2d(new_chs),
nn.ReLU(inplace=True) if relu else nn.Identity(),
act_layer(inplace=True) if use_act else nn.Identity(),
)

def forward(self, x):
Expand All @@ -59,6 +63,51 @@ def forward(self, x):
return out[:, :self.out_chs, :, :]


class GhostModuleV2(nn.Module):
def __init__(
self,
in_chs,
out_chs,
kernel_size=1,
ratio=2,
dw_size=3,
stride=1,
use_act=True,
act_layer=nn.ReLU,
):
super().__init__()
self.gate_fn = nn.Sigmoid()
self.out_chs = out_chs
init_chs = math.ceil(out_chs / ratio)
new_chs = init_chs * (ratio - 1)
self.primary_conv = nn.Sequential(
nn.Conv2d(in_chs, init_chs, kernel_size, stride, kernel_size // 2, bias=False),
nn.BatchNorm2d(init_chs),
act_layer(inplace=True) if use_act else nn.Identity(),
)
self.cheap_operation = nn.Sequential(
nn.Conv2d(init_chs, new_chs, dw_size, 1, dw_size // 2, groups=init_chs, bias=False),
nn.BatchNorm2d(new_chs),
act_layer(inplace=True) if use_act else nn.Identity(),
)
self.short_conv = nn.Sequential(
nn.Conv2d(in_chs, out_chs, kernel_size, stride, kernel_size // 2, bias=False),
nn.BatchNorm2d(out_chs),
nn.Conv2d(out_chs, out_chs, kernel_size=(1, 5), stride=1, padding=(0, 2), groups=out_chs, bias=False),
nn.BatchNorm2d(out_chs),
nn.Conv2d(out_chs, out_chs, kernel_size=(5, 1), stride=1, padding=(2, 0), groups=out_chs, bias=False),
nn.BatchNorm2d(out_chs),
)

def forward(self, x):
res = self.short_conv(F.avg_pool2d(x, kernel_size=2, stride=2))
x1 = self.primary_conv(x)
x2 = self.cheap_operation(x1)
out = torch.cat([x1, x2], dim=1)
return out[:, :self.out_chs, :, :] * F.interpolate(
self.gate_fn(res), size=(out.shape[-2], out.shape[-1]), mode='nearest')


class GhostBottleneck(nn.Module):
""" Ghost bottleneck w/ optional SE"""

Expand All @@ -71,13 +120,17 @@ def __init__(
stride=1,
act_layer=nn.ReLU,
se_ratio=0.,
mode='original',
):
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)
if mode == 'original':
self.ghost1 = GhostModule(in_chs, mid_chs, use_act=True, act_layer=act_layer)
else:
self.ghost1 = GhostModuleV2(in_chs, mid_chs, use_act=True, act_layer=act_layer)

# Depth-wise convolution
if self.stride > 1:
Expand All @@ -93,7 +146,7 @@ def __init__(
self.se = _SE_LAYER(mid_chs, rd_ratio=se_ratio) if has_se else None

# Point-wise linear projection
self.ghost2 = GhostModule(mid_chs, out_chs, relu=False)
self.ghost2 = GhostModule(mid_chs, out_chs, use_act=False)

# shortcut
if in_chs == out_chs and self.stride == 1:
Expand Down Expand Up @@ -140,6 +193,7 @@ def __init__(
output_stride=32,
global_pool='avg',
drop_rate=0.2,
version='v1',
):
super(GhostNet, self).__init__()
# setting of inverted residual blocks
Expand All @@ -160,17 +214,21 @@ def __init__(

# building inverted residual blocks
stages = nn.ModuleList([])
block = GhostBottleneck
stage_idx = 0
layer_idx = 0
net_stride = 2
for cfg in self.cfgs:
layers = []
s = 1
for k, exp_size, c, se_ratio, s in cfg:
out_chs = make_divisible(c * width, 4)
mid_chs = make_divisible(exp_size * width, 4)
layers.append(block(prev_chs, mid_chs, out_chs, k, s, se_ratio=se_ratio))
layer_kwargs = {}
if version == 'v2' and layer_idx > 1:
layer_kwargs['mode'] = 'attn'
layers.append(GhostBottleneck(prev_chs, mid_chs, out_chs, k, s, se_ratio=se_ratio, **layer_kwargs))
prev_chs = out_chs
layer_idx += 1
if s > 1:
net_stride *= 2
self.feature_info.append(dict(
Expand Down Expand Up @@ -246,6 +304,15 @@ def forward(self, x):
return x


def checkpoint_filter_fn(state_dict, model: nn.Module):
out_dict = {}
for k, v in state_dict.items():
if 'total' in k:
continue
out_dict[k] = v
return out_dict


def _create_ghostnet(variant, width=1.0, pretrained=False, **kwargs):
"""
Constructs a GhostNet model
Expand Down Expand Up @@ -285,6 +352,7 @@ def _create_ghostnet(variant, width=1.0, pretrained=False, **kwargs):
GhostNet,
variant,
pretrained,
pretrained_filter_fn=checkpoint_filter_fn,
feature_cfg=dict(flatten_sequential=True),
**model_kwargs,
)
Expand All @@ -293,7 +361,7 @@ def _create_ghostnet(variant, width=1.0, pretrained=False, **kwargs):
def _cfg(url='', **kwargs):
return {
'url': url, 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': (7, 7),
'crop_pct': 0.875, 'interpolation': 'bilinear',
'crop_pct': 0.875, 'interpolation': 'bicubic',
'mean': IMAGENET_DEFAULT_MEAN, 'std': IMAGENET_DEFAULT_STD,
'first_conv': 'conv_stem', 'classifier': 'classifier',
**kwargs
Expand All @@ -303,8 +371,22 @@ def _cfg(url='', **kwargs):
default_cfgs = generate_default_cfgs({
'ghostnet_050.untrained': _cfg(),
'ghostnet_100.in1k': _cfg(
url='https://github.com/huawei-noah/CV-backbones/releases/download/ghostnet_pth/ghostnet_1x.pth'),
hf_hub_id='timm/',
# url='https://github.com/huawei-noah/CV-backbones/releases/download/ghostnet_pth/ghostnet_1x.pth'
),
'ghostnet_130.untrained': _cfg(),
'ghostnetv2_100.in1k': _cfg(
hf_hub_id='timm/',
# url='https://github.com/huawei-noah/Efficient-AI-Backbones/releases/download/GhostNetV2/ck_ghostnetv2_10.pth.tar'
),
'ghostnetv2_130.in1k': _cfg(
hf_hub_id='timm/',
# url='https://github.com/huawei-noah/Efficient-AI-Backbones/releases/download/GhostNetV2/ck_ghostnetv2_13.pth.tar'
),
'ghostnetv2_160.in1k': _cfg(
hf_hub_id='timm/',
# url='https://github.com/huawei-noah/Efficient-AI-Backbones/releases/download/GhostNetV2/ck_ghostnetv2_16.pth.tar'
),
})


Expand All @@ -327,3 +409,24 @@ def ghostnet_130(pretrained=False, **kwargs) -> GhostNet:
""" GhostNet-1.3x """
model = _create_ghostnet('ghostnet_130', width=1.3, pretrained=pretrained, **kwargs)
return model


@register_model
def ghostnetv2_100(pretrained=False, **kwargs) -> GhostNet:
""" GhostNetV2-1.0x """
model = _create_ghostnet('ghostnetv2_100', width=1.0, pretrained=pretrained, version='v2', **kwargs)
return model


@register_model
def ghostnetv2_130(pretrained=False, **kwargs) -> GhostNet:
""" GhostNetV2-1.3x """
model = _create_ghostnet('ghostnetv2_130', width=1.3, pretrained=pretrained, version='v2', **kwargs)
return model


@register_model
def ghostnetv2_160(pretrained=False, **kwargs) -> GhostNet:
""" GhostNetV2-1.6x """
model = _create_ghostnet('ghostnetv2_160', width=1.6, pretrained=pretrained, version='v2', **kwargs)
return model

0 comments on commit e6aeb91

Please sign in to comment.