python
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
RepVGG のブロック(論文の式 1〜4 どおりの小さな実装)。
学習時は 3×3 畳み込み+BN、1×1 畳み込み+BN、BN だけ(恒等写像)の 3 本を足して ReLU。
学習のあとに reparameterize() を呼ぶと、1 つの 3×3 畳み込み(バイアスつき)に置き換わる。
"""
def fuse_bn(kernel, bn):
"""BN を前の畳み込みにまとめる(式 3):W' = γ/σ · W、b' = β − μγ/σ"""
std = (bn.running_var + bn.eps).sqrt()
t = (bn.weight / std).reshape(-1, 1, 1, 1)
return kernel * t, bn.bias - bn.running_mean * bn.weight / std
class RepVGGBlock(nn.Module):
def __init__(self, in_ch, out_ch, stride=1, groups=1):
super().__init__()
self.in_ch, self.groups = in_ch, groups
self.conv3 = nn.Conv2d(in_ch, out_ch, 3, stride, padding=1, groups=groups, bias=False)
self.bn3 = nn.BatchNorm2d(out_ch)
self.conv1 = nn.Conv2d(in_ch, out_ch, 1, stride, padding=0, groups=groups, bias=False) # パディングは 3×3 より 1 少ない
self.bn1 = nn.BatchNorm2d(out_ch)
# 恒等写像の枝は、入力と出力の形が同じとき(ストライド 1・チャネル数が同じ)だけ
self.bn_id = nn.BatchNorm2d(in_ch) if (in_ch == out_ch and stride == 1) else None
self.fused = None
def forward(self, x):
if self.fused is not None: # 推論時:3×3 畳み込み 1 回と ReLU
return F.relu(self.fused(x))
y = self.bn3(self.conv3(x)) + self.bn1(self.conv1(x))
if self.bn_id is not None:
y = y + self.bn_id(x)
return F.relu(y)
@torch.no_grad()
def reparameterize(self):
k3, b3 = fuse_bn(self.conv3.weight, self.bn3)
k1, b1 = fuse_bn(self.conv1.weight, self.bn1)
k = k3 + F.pad(k1, [1, 1, 1, 1]) # 1×1 の重みを 0 で囲んで 3×3 の中央に置く
b = b3 + b1
if self.bn_id is not None:
# 恒等写像 = 単位行列を重みにした畳み込み(同じチャネルの中央だけ 1)
per_group = self.in_ch // self.groups
eye = torch.zeros_like(k3)
for i in range(self.in_ch):
eye[i, i % per_group, 1, 1] = 1.0
kid, bid = fuse_bn(eye, self.bn_id)
k, b = k + kid, b + bid
c = self.conv3
self.fused = nn.Conv2d(c.in_channels, c.out_channels, 3, c.stride, padding=1, groups=c.groups, bias=True)
self.fused.weight.copy_(k)
self.fused.bias.copy_(b)
for name in ["conv3", "bn3", "conv1", "bn1", "bn_id"]:
setattr(self, name, None) # 学習時の枝は捨てる
block = RepVGGBlock(16, 16)
block.train()
block(torch.randn(8, 16, 32, 32)) # 学習で BN の平均と分散を貯める(ここでは 1 回だけ)
block.eval() # 変換は推論時の BN(貯めた平均と分散)で行う
x = torch.randn(2, 16, 32, 32)
with torch.no_grad():
before = block(x)
block.reparameterize()
after = block(x)
print(torch.allclose(before, after, atol=1e-5)) # True:変換の前後で出力が一致する