python
import torch
import torch.nn as nn
import torch.nn.functional as F
# オクターブ畳み込み:PyTorch に組み込みはないので、論文の式 4 のとおりに書く
# Y^H = f(X^H; W^{H→H}) + upsample(f(X^L; W^{L→H}), 2)
# Y^L = f(X^L; W^{L→L}) + f(pool(X^H, 2); W^{H→L})
# alpha_in = 0 なら最初の層(入力は通常の特徴マップ)、alpha_out = 0 なら最後の層(出力を 1 つに戻す)
class OctConv2d(nn.Module):
def __init__(self, in_ch, out_ch, kernel_size=3, alpha_in=0.5, alpha_out=0.5, padding=1):
super().__init__()
lin, lout = int(alpha_in * in_ch), int(alpha_out * out_ch) # 低周波のチャネル数
hin, hout = in_ch - lin, out_ch - lout # 高周波のチャネル数
conv = lambda i, o: nn.Conv2d(i, o, kernel_size, padding=padding, bias=False) if i > 0 and o > 0 else None
self.hh, self.hl = conv(hin, hout), conv(hin, lout)
self.lh, self.ll = conv(lin, hout), conv(lin, lout)
def forward(self, x):
xh, xl = x if isinstance(x, tuple) else (x, None)
yh = self.hh(xh) if self.hh else None
yl = self.hl(F.avg_pool2d(xh, 2)) if self.hl else None # 高 → 低:平均プーリングしてから畳み込む
if xl is not None:
if self.lh: # 低 → 高:畳み込んでから 2 倍にする
up = F.interpolate(self.lh(xl), scale_factor=2, mode="nearest")
yh = up if yh is None else yh + up
if self.ll:
yl = self.ll(xl) if yl is None else yl + self.ll(xl)
return yh if yl is None else (yh, yl)
x = torch.randn(1, 64, 56, 56) # 縦横は偶数にする
first = OctConv2d(64, 64, alpha_in=0.0, alpha_out=0.5) # 通常の特徴マップを 2 つに分ける
middle = OctConv2d(64, 64, alpha_in=0.5, alpha_out=0.5)
last = OctConv2d(64, 64, alpha_in=0.5, alpha_out=0.0) # 1 つに戻す
xh, xl = first(x)
print(xh.shape, xl.shape) # torch.Size([1, 32, 56, 56]) torch.Size([1, 32, 28, 28])
xh, xl = middle((xh, xl))
print(last((xh, xl)).shape) # torch.Size([1, 64, 56, 56])
# 重みの数は通常の畳み込みと同じ
count = lambda m: sum(p.numel() for p in m.parameters())
print(count(middle), count(nn.Conv2d(64, 64, 3, bias=False))) # 36864 36864
# 計算量の比(論文の付録 B):1 - 3/4 * alpha * (2 - alpha)
for a in (0.125, 0.25, 0.5, 0.75):
print(a, round(1 - 0.75 * a * (2 - a), 2)) # 0.82 0.67 0.44 0.3