def fuse_bn(W, bn):
"""Fold inference-mode batch normalization into a bias-free conv."""
scale = bn.weight / torch.sqrt(bn.running_var + bn.eps)
return W * scale.reshape(-1, 1, 1, 1), bn.bias - bn.running_mean * scale
@torch.no_grad()
def fuse_block(blk):
c = blk.conv3.weight.shape[0]
W3, b3 = fuse_bn(blk.conv3.weight, blk.bn3)
W1, b1 = fuse_bn(F.pad(blk.conv1.weight, (1, 1, 1, 1)), blk.bn1)
I = torch.zeros_like(W3) # On the device of the block
I[torch.arange(c), torch.arange(c), 1, 1] = 1.0
W0, b0 = fuse_bn(I, blk.bn0)
fused = nn.Conv2d(c, c, kernel_size=3, padding=1, device=W3.device)
fused.weight.copy_(W3 + W1 + W0)
fused.bias.copy_(b3 + b1 + b0)
return fused