python
import torch
import torch.nn as nn
def conv3x3(in_ch: int, out_ch: int, stride: int = 1) -> nn.Conv2d:
return nn.Conv2d(in_ch, out_ch, kernel_size=3, stride=stride, padding=1, bias=False)
# Fixup の基本ブロック(正規化層なし。論文の Figure 1 右と公式実装に合わせる)
class FixupBasicBlock(nn.Module):
def __init__(self, in_ch: int, out_ch: int, stride: int = 1, downsample: nn.Module | None = None):
super().__init__()
# 規則 3:畳み込み・活性化の前にスカラーのバイアス(0)、ブランチに乗数(1)
self.bias1a = nn.Parameter(torch.zeros(1))
self.conv1 = conv3x3(in_ch, out_ch, stride)
self.bias1b = nn.Parameter(torch.zeros(1))
self.relu = nn.ReLU(inplace=True)
self.bias2a = nn.Parameter(torch.zeros(1))
self.conv2 = conv3x3(out_ch, out_ch)
self.scale = nn.Parameter(torch.ones(1))
self.bias2b = nn.Parameter(torch.zeros(1))
self.downsample = downsample
def forward(self, x: torch.Tensor) -> torch.Tensor:
identity = x
out = self.conv1(x + self.bias1a)
out = self.relu(out + self.bias1b)
out = self.conv2(out + self.bias2a)
out = out * self.scale + self.bias2b
if self.downsample is not None:
# 公式実装と同じく、パラメーターのないショートカット:間引いてからチャンネルを 0 で埋めて 2 倍にする
identity = self.downsample(x + self.bias1a)
identity = torch.cat((identity, torch.zeros_like(identity)), 1)
return self.relu(out + identity)
def fixup_init(model: nn.Module, num_branches: int, m: int = 2) -> None:
"""L = num_branches(残差ブランチの数)、m = ブランチの中の層の数"""
for module in model.modules():
if isinstance(module, FixupBasicBlock):
# 規則 2:He の初期化を L^(-1/(2m-2)) 倍する(m = 2 なら L^(-1/2))
nn.init.kaiming_normal_(module.conv1.weight, mode="fan_out", nonlinearity="relu")
with torch.no_grad():
module.conv1.weight.mul_(num_branches ** (-1.0 / (2 * m - 2)))
# 規則 1:ブランチの最後の層は 0
nn.init.zeros_(module.conv2.weight)
elif isinstance(module, nn.Linear):
# 規則 1:分類層も 0
nn.init.zeros_(module.weight)
nn.init.zeros_(module.bias)
class FixupResNet(nn.Module):
def __init__(self, blocks_per_stage=(18, 18, 18), num_classes: int = 10): # ResNet-110 の形
super().__init__()
self.conv1 = conv3x3(3, 16) # ショートカットの経路:標準の初期化(PyTorch の既定)のまま
self.bias1 = nn.Parameter(torch.zeros(1))
self.relu = nn.ReLU(inplace=True)
layers, in_ch = [], 16
for stage, n in enumerate(blocks_per_stage):
out_ch = 16 * 2 ** stage
for i in range(n):
stride = 2 if (stage > 0 and i == 0) else 1
down = None
if stride != 1:
down = nn.AvgPool2d(1, stride=stride)
layers.append(FixupBasicBlock(in_ch, out_ch, stride, down))
in_ch = out_ch
self.layers = nn.Sequential(*layers)
self.pool = nn.AdaptiveAvgPool2d(1)
self.bias2 = nn.Parameter(torch.zeros(1))
self.fc = nn.Linear(in_ch, num_classes)
fixup_init(self, num_branches=sum(blocks_per_stage), m=2)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.relu(self.conv1(x) + self.bias1)
x = self.layers(x)
x = self.pool(x).flatten(1)
return self.fc(x + self.bias2)
model = FixupResNet()
x = torch.randn(8, 3, 32, 32)
with torch.no_grad():
print(model(x).abs().max().item()) # 分類層が 0 なので、初期化の直後の出力は 0
# 統計を持たないので、train() と eval() で出力は変わらない(Dropout を足した場合を除く)
model.train()