Switchable Normalization (SN) normalizes using a learned weighted mix of the means and variances of three methods: instance normalization, layer normalization, and batch normalization. Luo et al. proposed it in 2018, and it was published at ICLR 2019. How much of each normalizer to use is learned per layer by backpropagation, jointly with the network weights.
Networks traditionally use the same normalizer in every normalization layer. Yet the best choice differs by task: batch normalization for image classification, instance normalization for style transfer, layer normalization for RNNs. Different layers of the same network may also prefer different methods. SN lets the data decide which one to use instead of a human.
In the paper, ResNet-50 trained on ImageNet with 8 GPUs × 32 images reaches a top-1 accuracy of 76.9% (batch normalization 76.4%, group normalization 75.9%). With only 2 images per GPU it still keeps 75.6%, far above batch normalization, which drops to 65.3%.
In the figure at the top of the article, the upper part shows the range over which each of the three normalizers computes its mean and variance (blue cells), and the lower part shows the computation in one SN layer. In each sample's grid, rows are channels and columns are spatial positions.
How it is computed
Let an image tensor be "samples N × channels C × height H × width W", with values hncij. One SN layer computes the following in order (Section 2 and Section 2.1 of the paper).
Compute the mean and variance of instance normalization. For each sample and each channel, they are computed from H×W values (N×C pairs).
μin=HW1∑i,jhncij,σin2=HW1∑i,j(hncij−μin)2
Recompute the means and variances of layer normalization and batch normalization from the results of step 1. Layer normalization averages the step-1 statistics over channels, and batch normalization averages them over samples (Eq. (4)). Since the values need not be scanned again, the cost stays at O(NCHW), the same as other normalizers.
μln=C1∑c=1Cμin,σln2=C1∑c=1C(σin2+μin2)−μln2μbn=N1∑n=1Nμin,σbn2=N1∑n=1N(σin2+μin2)−μbn2
Compute the weights with softmax. The layer has λin,λln,λbn for the mean and a separate λin′,λln′,λbn′ for the variance; softmax turns each set into weights between 0 and 1 that sum to 1 (Eq. (5)). Each layer has 6 such weights, shared across all channels.
wk=∑z∈{in,ln,bn}eλzeλk,k∈{in,ln,bn}
Normalize with the weighted averages, then apply scale and shift. As in other normalizers, γ and β are per channel (Eq. (3)).
h^ncij=γ∑kwk′σk2+ϵhncij−∑kwkμk+β
During training, the network weights Θ and the 6 λ values, collectively Φ, are optimized together on the same training data with the same loss. Unlike neural architecture search such as DARTS, which splits data into training and validation sets and optimizes in two levels, SN learns in a single level. In the paper's ImageNet experiments, all λ were initialized to 1 (equal weight for the three).
SN adds only 6 learnable parameters per layer. That is tiny compared with the 2C parameters of γ and β, and it adds no hyperparameter to tune, unlike the number of groups in group normalization.
Why mixing helps
In the paper's experiments, the SN weights changed with the task and the batch size (Figure 1 (a) and Figure 4 of the paper; the weights are averaged over all SN layers in the network).
Backbones for image classification and object detection: mixed all three but favored batch normalization.
Box and mask heads in object detection: the weight of layer normalization became large.
Style transfer: chose instance normalization.
LSTM (the controller of ENAS): preferred layer normalization over group normalization.
Small batches: the weight of batch normalization decreased and that of layer normalization increased.
The paper explains this behavior as follows. Batch normalization acts as regularization because its statistics fluctuate from mini-batch to mini-batch, which helps generalization. Layer normalization, in contrast, constrains the filter magnitudes less and increases learning capacity. With small batches, the noise of batch normalization becomes too strong, so SN lowers its weight and compensates with layer normalization.
As an analogy, SN blends the opinions of three experts (batch normalization, layer normalization, and instance normalization) with a different allocation in each layer. No human sets the allocation; training adjusts it in whichever direction improves the result (the loss).
The paper also reports that when ResNet-50 is retrained several times with different training settings (optimizer, initialization, learning rate schedule), the learned weights are nearly identical for the same network, task, and batch size.
Experimental results
ImageNet image classification: top-1 accuracy of ResNet-50 (Table 2 of the paper). Settings are (number of GPUs, images per GPU), and the mean and variance are computed per GPU.
Setting
(8, 32)
(8, 16)
(8, 8)
(8, 4)
(8, 2)
(8, 1)
Batch normalization
76.4%
76.3%
75.2%
72.7%
65.3%
Did not converge
Group normalization
75.9%
75.8%
76.0%
75.8%
75.9%
75.5%
SN
76.9%
76.7%
76.7%
75.9%
75.6%
75.0%
SN beats batch normalization with large batches and by a wide margin with small ones, and is on par with or better than group normalization. At (8, 2) and (8, 1), however, group normalization is slightly ahead. With 1 image per GPU, instance normalization and batch normalization compute the same thing during training, so SN uses only instance normalization and layer normalization. At the same (8, 32), instance normalization reaches 71.6% and layer normalization 74.7%.
Kinetics video classification, 4 clips per GPU (Table 6)
top-1
72.1%
72.8%
73.3%
Detection and segmentation use ResNet-50 with FPN, and are compared against batch normalization with frozen statistics (detection) or statistics synchronized across GPUs (segmentation). The segmentation numbers are for single-scale inference.
Practical caveats
Because SN contains a batch normalization component, its computation differs between training and inference. The statistics of instance normalization and layer normalization are computed from the input at inference time too, but batch normalization uses values estimated from the training data. The paper uses "batch average": after training, the network is frozen, several mini-batches are fed through it, and their means and variances are averaged (on ImageNet, 76.90% with 50,000 images, 76.92% with the full training set, and 76.89% with a moving average). When implementing it yourself in PyTorch, make it switch with model.eval().
PyTorch has no built-in layer for it. Use the code released by the paper's authors (switchablenorms on GitHub), or write it yourself as in the implementation example below.
Also keep the following in mind.
With 1 image per GPU, the batch normalization component is meaningless. SN then mixes only instance normalization and layer normalization.
SN keeps three kinds of statistics but is designed so that computation barely increases. This is because the statistics of layer normalization and batch normalization are recomputed from those of instance normalization. The number of statistics, however, becomes 2C+2N+2NC (Table 1 of the paper).
In fully connected layers and LSTMs, instance normalization and layer normalization are identical, because there is no spatial axis. In the paper's LSTM experiments, batch normalization cannot be used either, so layer normalization and group normalization are mixed.
The weights are shared across all channels. The paper also gives preliminary results for a variant with separate weights for each group of channels and a variant that keeps only the normalizer with the largest weight after training (77.2% and 77.0% on ResNet-50).
Comparison with other normalization methods
Aspect
SN
Batch normalization
Layer normalization
Instance normalization
Group normalization
Range for mean and variance
Weighted mix of the three on the right
Batch × space of one channel
All channels × space of one sample
Space of one channel of one sample
Channel group × space of one sample
Sensitivity to batch size
Low (adjusted by the weights)
Yes
No
No
No
Training vs. inference
Computation differs
Computation differs
Same computation
Same computation
Same computation
Learnable parameters (per layer)
2C+6
2C
2C
2C
2C
Hyperparameters to tune
None
None (moving-average momentum)
None
None
Number of groups G
ImageNet accuracy (ResNet-50, (8, 32))
76.9%
76.4%
74.7%
71.6%
75.9%
Accuracies are from the SN paper (Table 2 and Section 4.1).
A rough guide for choosing:
CNNs with sufficiently large batches, where simple implementation matters: batch normalization.
CNNs with small batches (object detection, segmentation, video): group normalization or SN. Group normalization is built in and easy to use; SN leaves the per-task and per-layer preferences to training.
New tasks or networks where the best normalizer is unknown: use SN, and inspect the learned weights for hints about which normalizer each layer chose.
Transformers and RNNs: layer normalization or RMSNorm.
PyTorch example
▶Show code
python
import torch
import torch.nn as nn
class SwitchNorm2d(nn.Module):
"""Switchable Normalization following Eqs. (3)-(5) of the paper (for [N, C, H, W]).
For simplicity, batch normalization statistics for inference are kept as a moving average
(the paper recommends "batch average": feed mini-batches after training and average them).
"""
def __init__(self, num_features, eps=1e-5, momentum=0.1):
super().__init__()
self.eps, self.momentum = eps, momentum
self.weight = nn.Parameter(torch.ones(1, num_features, 1, 1)) # γ (per channel)
self.bias = nn.Parameter(torch.zeros(1, num_features, 1, 1)) # β (per channel)
# λ (for the mean) and λ' (for the variance), in the order in, ln, bn. Initialized to 1 in the paper's experiments
self.mean_weight = nn.Parameter(torch.ones(3))
self.var_weight = nn.Parameter(torch.ones(3))
self.register_buffer("running_mean", torch.zeros(1, num_features, 1, 1))
self.register_buffer("running_var", torch.ones(1, num_features, 1, 1))
def forward(self, x):
# 1. Instance normalization statistics: over H, W for each sample and channel
mean_in = x.mean(dim=(2, 3), keepdim=True) # [N, C, 1, 1]
var_in = x.var(dim=(2, 3), unbiased=False, keepdim=True)
temp = var_in + mean_in ** 2
# 2. Layer normalization statistics: average the IN statistics over channels (Eq. (4))
mean_ln = mean_in.mean(dim=1, keepdim=True) # [N, 1, 1, 1]
var_ln = temp.mean(dim=1, keepdim=True) - mean_ln ** 2
# 2. Batch normalization statistics: average the IN statistics over samples (Eq. (4))
if self.training:
mean_bn = mean_in.mean(dim=0, keepdim=True) # [1, C, 1, 1]
var_bn = temp.mean(dim=0, keepdim=True) - mean_bn ** 2
with torch.no_grad():
self.running_mean.lerp_(mean_bn, self.momentum)
self.running_var.lerp_(var_bn, self.momentum)
else:
mean_bn, var_bn = self.running_mean, self.running_var # in eval(), use statistics from training
# 3. Weights: softmax gives values in 0-1 that sum to 1 (Eq. (5)). Shared across all channels
w = torch.softmax(self.mean_weight, dim=0)
v = torch.softmax(self.var_weight, dim=0)
# 4. Normalize with the weighted averages and apply γ, β (Eq. (3))
mean = w[0] * mean_in + w[1] * mean_ln + w[2] * mean_bn
var = v[0] * var_in + v[1] * var_ln + v[2] * var_bn
x = (x - mean) / torch.sqrt(var + self.eps)
return x * self.weight + self.bias
block = nn.Sequential(
nn.Conv2d(3, 64, kernel_size=3, padding=1, bias=False),
SwitchNorm2d(64),
nn.ReLU(),
)
x = torch.randn(2, 3, 32, 32) # works with small batches
block.train(); y = block(x) # training: uses batch statistics
block.eval(); y = block(x) # inference: the BN component uses the recorded statistics
# After training, check which normalizer was chosen (order: in, ln, bn)
sn = block[1]
print(torch.softmax(sn.mean_weight, 0), torch.softmax(sn.var_weight, 0))
FAQ
Q. Do the SN weights settle on a single normalizer after training?
A.
Not necessarily. Because they are softmax weights, training usually ends with all three still mixed. Even in the paper's image classification, SN mixed all three while favoring batch normalization. If a single normalizer is desired, the paper presents a variant that keeps only the normalizer with the largest weight after training and fine-tunes (77.0% on ResNet-50, versus 76.9% with the mix kept).
Q. Why are there separate weights for the mean and the variance?
A.
Eq. (3) of the paper derives the mean weights wk and the variance weights wk′ from different λ. This allows the range over which the mean is subtracted and the range of the variance used for division to be chosen independently. As a result, each layer has 3×2=6 weights.
Q. Should I use SN or group normalization?
A.
For convenience, group normalization. It is built into PyTorch, and its computation is the same during training and inference. SN has a batch normalization component, so the inference statistics need handling, but in the paper it matched or beat group normalization on ImageNet, COCO, ADE20K, Cityscapes, and Kinetics. With very small batches of 1 to 2 images, group normalization is slightly ahead on ImageNet.