python コピー
import torch
import torch.nn as nn
import torch.nn.functional as F
# 動的畳み込み:PyTorch に組み込みはないので、論文の式 1・3 と図 3 のとおりに書く
# z = FC(ReLU(FC(GlobalAveragePool(x)))) 1 つ目の全結合で次元を 1/4 に縮める
# pi = softmax(z / tau) 合計が 1
# y = (sum_k pi_k W_k) * x + sum_k pi_k b_k このあとにバッチ正規化と ReLU
class DynamicConv2d(nn.Module):
def __init__(self, in_ch, out_ch, kernel_size, stride=1, padding=0, K=4, reduction=4, tau=30.0):
super().__init__()
self.out_ch, self.stride, self.padding, self.tau = out_ch, stride, padding, tau
self.weight = nn.Parameter(torch.empty(K, out_ch, in_ch, kernel_size, kernel_size))
for w in self.weight:
nn.init.kaiming_normal_(w, nonlinearity="relu")
self.bias = nn.Parameter(torch.zeros(K, out_ch))
hidden = max(in_ch // reduction, 4)
self.attention = nn.Sequential(nn.Linear(in_ch, hidden), nn.ReLU(), nn.Linear(hidden, K))
def attention_weights(self, x):
z = self.attention(x.mean(dim=(2, 3))) # (B, K)
return F.softmax(z / self.tau, dim=1) # 合計が 1。tau が大きいほど均等に近い
def forward(self, x):
b, c, h, w = x.shape
pi = self.attention_weights(x)
kernels = torch.einsum("bk,koihw->boihw", pi, self.weight) # (B, out_ch, in_ch, k, k)
biases = pi @ self.bias # (B, out_ch)。バイアスも同じ重みで足す
# B 個の入力を 1 つにまとめ、groups=B で「入力ごとに別のカーネル」を 1 回の畳み込みで計算する
y = F.conv2d(x.reshape(1, b * c, h, w), kernels.reshape(b * self.out_ch, c, *kernels.shape[-2:]),
biases.reshape(-1), stride=self.stride, padding=self.padding, groups=b)
return y.reshape(b, self.out_ch, *y.shape[-2:])
# 温度を最初の 10 エポックで 30 から 1 へ直線的に下げる(論文の「温度を下げていく学習」)
def set_temperature(model, epoch, start=30.0, end=1.0, anneal_epochs=10):
t = end if epoch >= anneal_epochs else start + (end - start) * epoch / anneal_epochs
for m in model.modules():
if isinstance(m, DynamicConv2d):
m.tau = t
block = nn.Sequential(DynamicConv2d(32, 64, 3, padding=1), nn.BatchNorm2d(64), nn.ReLU())
x = torch.randn(2, 32, 28, 28)
for epoch in range(3):
set_temperature(block, epoch)
block.train()
y = block(x) # 学習の処理(損失・逆伝播)は省略
print(y.shape) # torch.Size([2, 64, 28, 28])
block.eval() # BatchNorm があるので、推論では eval() にして学習時の統計を使う
with torch.no_grad():
print(block[0].attention_weights(x).sum(dim=1)) # tensor([1., 1.])