python コピー
import torch
import torch.nn as nn
import torch.nn.functional as F
# CondConv:PyTorch に組み込みはないので、論文の式どおりに書く
# alpha = Sigmoid(GlobalAveragePool(x) R)
# Output(x) = (alpha_1 W_1 + ... + alpha_n W_n) * x (活性化関数は層の外でかける)
class CondConv2d(nn.Module):
def __init__(self, in_ch, out_ch, kernel_size, stride=1, padding=0, num_experts=8):
super().__init__()
self.out_ch, self.stride, self.padding = out_ch, stride, padding
# 専門家カーネル:形は (n, out_ch, in_ch, k, k)。それぞれが元の畳み込みのカーネルと同じ形
self.weight = nn.Parameter(torch.empty(num_experts, out_ch, in_ch, kernel_size, kernel_size))
for w in self.weight:
nn.init.kaiming_normal_(w, nonlinearity="relu")
self.routing = nn.Linear(in_ch, num_experts) # ルーティングの全結合 R
def routing_weights(self, x):
return torch.sigmoid(self.routing(x.mean(dim=(2, 3)))) # (B, n)。それぞれ 0〜1
def forward(self, x):
b, c, h, w = x.shape
alpha = self.routing_weights(x)
# 入力ごとにカーネルを混ぜる:(B, out_ch, in_ch, k, k)
kernels = torch.einsum("bn,noikl->boikl", alpha, self.weight)
# 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:]),
stride=self.stride, padding=self.padding, groups=b)
return y.reshape(b, self.out_ch, *y.shape[-2:])
layer = CondConv2d(32, 64, kernel_size=3, padding=1, num_experts=4)
x = torch.randn(2, 32, 28, 28)
y = layer(x)
print(y.shape) # torch.Size([2, 64, 28, 28])
# 混合エキスパートの形(専門家ごとに畳み込んでから重み付きで足す)と同じ結果になることを確かめる
with torch.no_grad():
alpha = layer.routing_weights(x) # (2, 4)
y_moe = sum(alpha[:, i, None, None, None] * F.conv2d(x, layer.weight[i], padding=1) for i in range(4))
print(torch.allclose(y, y_moe, atol=1e-4)) # True
# 層として使うとき:通常の畳み込みと同じく、あとにバッチ正規化と活性化関数を置く
block = nn.Sequential(CondConv2d(32, 64, 3, padding=1), nn.BatchNorm2d(64), nn.ReLU())
block.eval() # BatchNorm があるので、推論では eval() にして学習時の統計を使う
print(block(x).shape) # torch.Size([2, 64, 28, 28])