python
import math
import torch
import torch.nn as nn
"""
Ghost モジュールと Ghost ボトルネックを、論文の式 2・3、図 2(b)・図 3 のとおりに組む。
SE の位置とストライド 2 のショートカットの中身は、論文の参照実装(huawei-noah/ghostnet、timm)に合わせた。
torchvision には GhostNet の組み込みはない。
"""
class GhostModule(nn.Module):
def __init__(self, c_in, c_out, k=1, s=2, d=3, relu=True):
super().__init__()
self.c_out = c_out
m = math.ceil(c_out / s) # 本来の特徴マップの数 m = n / s
act = nn.ReLU(inplace=True) if relu else nn.Identity()
self.primary = nn.Sequential( # 主の畳み込み(GhostNet では 1×1)
nn.Conv2d(c_in, m, k, 1, k // 2, bias=False), nn.BatchNorm2d(m), act
)
self.cheap = nn.Sequential( # 安い線形変換:d×d の深さ方向の畳み込み(s − 1 個ずつ)
nn.Conv2d(m, m * (s - 1), d, 1, d // 2, groups=m, bias=False), nn.BatchNorm2d(m * (s - 1)), act
)
def forward(self, x):
y1 = self.primary(x) # 本来の特徴マップ(恒等写像でそのまま残す)
y2 = self.cheap(y1) # ゴーストの特徴マップ
return torch.cat([y1, y2], dim=1)[:, : self.c_out]
class SE(nn.Module):
def __init__(self, ch, ratio=0.25):
super().__init__()
mid = max(8, int(ch * ratio))
self.fc = nn.Sequential(
nn.AdaptiveAvgPool2d(1), nn.Conv2d(ch, mid, 1), nn.ReLU(inplace=True), nn.Conv2d(mid, ch, 1), nn.Hardsigmoid()
)
def forward(self, x):
return x * self.fc(x)
class GhostBottleneck(nn.Module):
def __init__(self, c_in, c_exp, c_out, stride=1, use_se=False):
super().__init__()
self.ghost1 = GhostModule(c_in, c_exp, relu=True) # 広げる(BN・ReLU)
self.dw = (nn.Sequential( # ストライド 2 のときだけ深さ方向の畳み込み
nn.Conv2d(c_exp, c_exp, 3, stride, 1, groups=c_exp, bias=False), nn.BatchNorm2d(c_exp)
) if stride == 2 else nn.Identity())
self.se = SE(c_exp) if use_se else nn.Identity()
self.ghost2 = GhostModule(c_exp, c_out, relu=False) # 狭める(BN のみ、ReLU なし)
if stride == 1 and c_in == c_out:
self.shortcut = nn.Identity()
else: # 縮小の層(参照実装の形)
self.shortcut = nn.Sequential(
nn.Conv2d(c_in, c_in, 3, stride, 1, groups=c_in, bias=False), nn.BatchNorm2d(c_in),
nn.Conv2d(c_in, c_out, 1, bias=False), nn.BatchNorm2d(c_out),
)
def forward(self, x):
out = self.ghost2(self.se(self.dw(self.ghost1(x))))
return out + self.shortcut(x)
# 論文の表 1 の 1 行(入力 28×28×40、拡張 120、出力 40、SE あり、ストライド 1)
block = GhostBottleneck(40, 120, 40, stride=1, use_se=True)
block.eval() # BN は学習中に貯めた平均と分散を使う
with torch.no_grad():
print(block(torch.randn(1, 40, 28, 28)).shape) # torch.Size([1, 40, 28, 28])
down = GhostBottleneck(40, 240, 80, stride=2) # 表 1 の縮小するブロック
print(down(torch.randn(2, 40, 28, 28)).shape) # torch.Size([2, 80, 14, 14])