python
import torch
import torch.nn as nn
# SkipInit の残差ブロック(事前活性化型の Wide-ResNet の基本ブロックから BN を除いたもの)
class SkipInitBlock(nn.Module):
def __init__(self, in_ch: int, out_ch: int, stride: int = 1):
super().__init__()
self.relu = nn.ReLU()
# Regularized SkipInit では畳み込みにバイアスを付ける(bias=True)
self.conv1 = nn.Conv2d(in_ch, out_ch, 3, stride=stride, padding=1, bias=True)
self.conv2 = nn.Conv2d(out_ch, out_ch, 3, padding=1, bias=True)
# SkipInit:枝の最後に掛ける学習するスカラー。0 で初期化する
self.alpha = nn.Parameter(torch.zeros(()))
self.shortcut = None
if stride != 1 or in_ch != out_ch:
# 形が変わるブロックだけ 1×1 畳み込みのショートカット(ほかは恒等写像)
self.shortcut = nn.Conv2d(in_ch, out_ch, 1, stride=stride, bias=True)
for conv in (self.conv1, self.conv2):
nn.init.kaiming_normal_(conv.weight, nonlinearity="relu") # He の初期化
nn.init.zeros_(conv.bias)
def forward(self, x: torch.Tensor) -> torch.Tensor:
out = self.relu(x)
identity = x if self.shortcut is None else self.shortcut(out)
out = self.conv1(out)
out = self.conv2(self.relu(out))
return identity + self.alpha * out # x_{l+1} = x_l + α f_l(x_l)
class SkipInitWRN(nn.Module):
def __init__(self, blocks_per_stage: int = 2, widen: int = 2, num_classes: int = 10, drop: float = 0.6):
super().__init__()
widths = [16 * widen, 32 * widen, 64 * widen]
self.stem = nn.Conv2d(3, 16, 3, padding=1)
layers, in_ch = [], 16
for stage, w in enumerate(widths):
for i in range(blocks_per_stage):
stride = 2 if (stage > 0 and i == 0) else 1
layers.append(SkipInitBlock(in_ch, w, stride))
in_ch = w
self.blocks = nn.Sequential(*layers)
self.head = nn.Sequential(
nn.ReLU(), nn.AdaptiveAvgPool2d(1), nn.Flatten(),
nn.Dropout(drop), # Regularized SkipInit:ソフトマックスの直前に Dropout を1つ
nn.Linear(in_ch, num_classes),
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.head(self.blocks(self.stem(x)))
model = SkipInitWRN(blocks_per_stage=166) # 6n+4 = 1,000 層の n-2 Wide-ResNet に相当する深さ
x = torch.randn(4, 3, 32, 32)
model.eval() # Dropout を止める。正規化層がないので、それ以外は train() と eval() で同じ
with torch.no_grad():
print(model(x).shape) # torch.Size([4, 10])
block = model.blocks[1] # 形が変わらないブロック(ショートカットが恒等写像)
h = torch.randn(4, 32, 32, 32)
print(torch.equal(block(h), h)) # True:α = 0 なので、初期化の直後のブロックは恒等写像