python
import torch
import torch.nn as nn
def make_model(widths=(64, 128, 256), num_classes=10):
layers, c_in = [], 3
for w in widths:
layers += [nn.Conv2d(c_in, w, 3, padding=1, bias=False), nn.BatchNorm2d(w), nn.ReLU()]
c_in = w
layers += [nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(c_in, num_classes)]
return nn.Sequential(*layers)
model = make_model()
for m in model.modules():
if isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 0.5) # 論文では γ の初期値を 0.5 にした
# 1. 学習:損失に λ Σ|γ| を足す(式 (1))。|γ| の劣勾配 λ·sign(γ) を勾配に足せばよい
def add_l1_on_bn(model, lam=1e-4):
for m in model.modules():
if isinstance(m, nn.BatchNorm2d):
m.weight.grad.add_(lam * torch.sign(m.weight.detach()))
opt = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9, weight_decay=1e-4)
x, y = torch.randn(8, 3, 32, 32), torch.randint(0, 10, (8,))
model.train()
loss = nn.functional.cross_entropy(model(x), y)
opt.zero_grad()
loss.backward()
add_l1_on_bn(model, lam=1e-4) # ふつうの勾配のあとに、γ の罰則の分を足す
opt.step()
# 2. しきい値:すべての BN の γ をまとめて、消す割合のパーセンタイルを求める
def global_threshold(model, ratio=0.5):
gammas = torch.cat([m.weight.detach().abs() for m in model.modules() if isinstance(m, nn.BatchNorm2d)])
return torch.quantile(gammas, ratio)
# 3. 消す:γ がしきい値以上のチャネルだけを残した、細いモデルを作る
@torch.no_grad()
def slim(model, ratio=0.5, min_keep=1):
th = global_threshold(model, ratio)
mods = list(model)
new_layers, keep_prev = [], torch.arange(3) # 入力の 3 チャネルはすべて残す
for i, m in enumerate(mods):
if isinstance(m, nn.Conv2d):
bn = mods[i + 1]
keep = (bn.weight.abs() >= th).nonzero().flatten()
if len(keep) < min_keep: # 層が丸ごと消えないようにする
keep = bn.weight.abs().topk(min_keep).indices.sort().values
conv = nn.Conv2d(len(keep_prev), len(keep), m.kernel_size, m.stride, m.padding, bias=False)
conv.weight.copy_(m.weight[keep][:, keep_prev]) # 出ていく側と入ってくる側の両方を消す
new_bn = nn.BatchNorm2d(len(keep))
for name in ["weight", "bias", "running_mean", "running_var"]:
getattr(new_bn, name).copy_(getattr(bn, name)[keep])
new_layers += [conv, new_bn]
keep_prev = keep
elif isinstance(m, nn.Linear):
fc = nn.Linear(len(keep_prev), m.out_features)
fc.weight.copy_(m.weight[:, keep_prev])
fc.bias.copy_(m.bias)
new_layers.append(fc)
elif not isinstance(m, nn.BatchNorm2d):
new_layers.append(m)
return nn.Sequential(*new_layers)
small = slim(model, ratio=0.5)
print([m.out_channels for m in small if isinstance(m, nn.Conv2d)]) # 層ごとに残る数は自動で決まる
small.eval()
print(small(torch.randn(1, 3, 32, 32)).shape) # torch.Size([1, 10])
# 4. このあと small.train() にして学習し直す(罰則なし)