python
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
MobileOne のブロック(論文の図 3 と公式実装 apple/ml-mobileone の考え方どおりの小さな実装)。
1 つの「層」は、k 本の conv+BN、(カーネルが 1 より大きいとき)1×1 conv+BN、(形が同じとき)BN だけの枝を足して ReLU。
ブロックは「深さ方向の 3×3 の層」と「1×1 の層」の 2 つ。reparameterize() で各層が 1 つの畳み込みになる。
"""
def fuse(conv_weight, bn):
"""BN を前の畳み込みにまとめる:W = W'·γ/σ、b = β − μγ/σ(畳み込みはバイアスなし)"""
std = (bn.running_var + bn.eps).sqrt()
return conv_weight * (bn.weight / std).reshape(-1, 1, 1, 1), bn.bias - bn.running_mean * bn.weight / std
class MobileOneLayer(nn.Module):
def __init__(self, in_ch, out_ch, kernel_size, stride=1, groups=1, k=1):
super().__init__()
pad = kernel_size // 2
self.in_ch, self.groups, self.kernel_size = in_ch, groups, kernel_size
conv_bn = lambda ks, p: nn.Sequential(nn.Conv2d(in_ch, out_ch, ks, stride, p, groups=groups, bias=False), nn.BatchNorm2d(out_ch))
self.branches = nn.ModuleList([conv_bn(kernel_size, pad) for _ in range(k)]) # 同じ形の枝を k 本
self.scale = conv_bn(1, 0) if kernel_size > 1 else None # 1×1 の枝
self.skip = nn.BatchNorm2d(in_ch) if (in_ch == out_ch and stride == 1) else None # 恒等写像の枝
self.fused = None
def forward(self, x):
if self.fused is not None: # 推論時:畳み込み 1 回と ReLU
return F.relu(self.fused(x))
y = sum(b(x) for b in self.branches)
if self.scale is not None:
y = y + self.scale(x)
if self.skip is not None:
y = y + self.skip(x)
return F.relu(y)
@torch.no_grad()
def reparameterize(self):
K = self.kernel_size
pairs = [fuse(b[0].weight, b[1]) for b in self.branches]
if self.scale is not None:
w, b = fuse(self.scale[0].weight, self.scale[1])
pairs.append((F.pad(w, [K // 2] * 4), b)) # 1×1 の重みを 0 で囲んで K×K に
if self.skip is not None:
per_group = self.in_ch // self.groups
eye = torch.zeros(self.in_ch, per_group, K, K)
for i in range(self.in_ch):
eye[i, i % per_group, K // 2, K // 2] = 1.0 # 恒等写像:同じチャネルの中央だけ 1
pairs.append(fuse(eye, self.skip))
c = self.branches[0][0]
self.fused = nn.Conv2d(c.in_channels, c.out_channels, K, c.stride, K // 2, groups=c.groups, bias=True)
self.fused.weight.copy_(sum(w for w, _ in pairs)) # すべての枝の重みを足す
self.fused.bias.copy_(sum(b for _, b in pairs)) # すべての枝のバイアスを足す
self.branches, self.scale, self.skip = None, None, None # 学習時の枝は捨てる
def mobileone_block(in_ch, out_ch, stride=1, k=4):
"""深さ方向の 3×3 の層 → 1×1 の層(MobileOne-S0 は k=4)"""
return nn.Sequential(
MobileOneLayer(in_ch, in_ch, 3, stride, groups=in_ch, k=k),
MobileOneLayer(in_ch, out_ch, 1, 1, groups=1, k=k),
)
block = mobileone_block(48, 48)
block.train()
block(torch.randn(8, 48, 28, 28)) # 学習で BN の平均と分散を貯める(ここでは 1 回だけ)
block.eval() # 変換は推論時の BN で行う
x = torch.randn(2, 48, 28, 28)
with torch.no_grad():
before = block(x)
for layer in block:
layer.reparameterize()
after = block(x)
print(torch.allclose(before, after, atol=1e-5)) # True:変換の前後で出力が一致する