AI Logic

Normalization

Instance Normalization

Updated:

Comparison of the ranges over which Batch Normalization and Instance Normalization pool the mean and variance. In each sample's grid, rows are channels and columns are spatial positions. Batch Normalization (left) pools one channel across all samples; Instance Normalization (right) pools only one channel of one sample. Below: the computation flow of Instance Normalization, which is the same at training and inference time

What Is Instance Normalization?

Instance Normalization normalizes one channel of one image (instance) using a mean and variance computed only over its H×WH \times W spatial positions. Ulyanov, Vedaldi, and Lempitsky proposed it in 2016 for generator networks that perform fast image style transfer. The paper also calls it "contrast normalization."

The change consists of just two points: replacing Batch Normalization in the generator with Instance Normalization, and applying the same computation unchanged at inference time. The paper reports that this alone raises the image quality of single-pass style transfer to the level of methods that run optimization for several minutes.

The figure at the top of the article compares the ranges (blue cells) over which Batch Normalization and Instance Normalization pool the mean and variance. In each sample's grid, rows are channels and columns are spatial positions. Batch Normalization pools one channel across all samples in the batch, whereas Instance Normalization pools only one channel of one sample.

Computation Steps

Let the input be a tensor of shape "batch TT × channels CC × width WW × height HH," and let xtijkx_{tijk} be the value of the tt-th image at channel ii and position (j,k)(j, k) (the paper's notation). Instance Normalization computes the following in order (Eq. (3) in the paper).

  1. Compute the mean per image and per channel. Only the H×WH \times W values of one channel of one image are used. Other images in the batch are not used. μti=1HW∑l=1W∑m=1Hxtilm\mu_{ti} = \frac{1}{HW} \sum_{l=1}^{W} \sum_{m=1}^{H} x_{tilm}
  2. Compute the variance over the same range. σti2=1HW∑l=1W∑m=1H(xtilm−μti)2\sigma_{ti}^2 = \frac{1}{HW} \sum_{l=1}^{W} \sum_{m=1}^{H} \left(x_{tilm} - \mu_{ti}\right)^2
  3. Subtract the mean and divide by the standard deviation. ϵ\epsilon is a small value that prevents division by zero. ytijk=xtijk−μtiσti2+ϵy_{tijk} = \frac{x_{tijk} - \mu_{ti}}{\sqrt{\sigma_{ti}^2 + \epsilon}}

Eq. (3) in the paper does not include a learnable scale γ\gamma and shift β\beta as in Batch Normalization. PyTorch's nn.InstanceNorm2d also has no γ\gamma or β\beta by default (affine=False).

The only difference from Batch Normalization is the range over which the mean and variance are pooled (Eqs. (2) and (3) in the paper).

MethodAxes pooled for mean/varianceValues per statisticNumber of statistic sets
Batch NormalizationT,H,WT, H, WT×H×WT \times H \times WCC
Instance NormalizationH,WH, WH×WH \times WT×CT \times C

Setting the number of groups in Group Normalization equal to the number of channels (one channel per group) yields the same computation as Instance Normalization.

Why It Works for Style Transfer

The paper starts from the observation that the result of style transfer should hardly depend on the contrast of the content image. Style transfer keeps the shapes of the content image while copying the colors and brushstrokes of the style image (such as a painting). Because the loss function is designed to match the contrast of the output to that of the style image, the output contrast is determined by the style image even when the contrast of the content image is lowered (Figure 2 in the paper).

In other words, the generator needs to discard the contrast information of the content image. However, per-image contrast normalization (dividing values by the sum over the same image and channel, as in Eq. (1) in the paper) is a highly nonlinear function that is hard to learn by stacking convolutions and ReLU.

The original generator contained Batch Normalization, but because Batch Normalization computes the mean and variance over the whole batch, it cannot remove contrast differences between individual images. The paper therefore replaced it with Instance Normalization, which normalizes each image separately, building contrast normalization directly into the network architecture. The paper states that this prevents instance-specific mean and covariance shift and simplifies learning.

As an analogy, it is like adjusting bright and dark photos to the same brightness and contrast before starting to paint, and only then adding brushstrokes. The network can focus on transferring style without worrying about differences in brightness.

A key point is to keep using Instance Normalization at inference time. Batch Normalization switches to the running averages from training at inference and acts as a plain linear transform. That loses the ability to normalize the contrast of the single image being processed.

Experimental Results

The paper's experiments are qualitative comparisons of generated images. No numerical evaluation is reported.

  • Problem with the original method: In the authors' earlier fast style transfer (Ulyanov et al. 2016), adding more training data actually degraded quality; training on 16 images gave better results than training on thousands. In particular, zero padding before convolutions caused artifacts at image borders, which persisted even with improved padding. The best results were obtained by training on few images and stopping early.
  • Effect of the replacement: In both generator architectures (the one from Ulyanov et al. 2016 and the residual-block one from Johnson et al. 2016), replacing Batch Normalization with Instance Normalization and retraining with the same hyperparameters greatly improved image quality (Figure 5 in the paper). Figure 3 in the paper shows the results with zero padding, improved padding, and zero padding plus Instance Normalization side by side.
  • Speed: The paper states that the results match the quality of the iterative optimization method of Gatys et al. and can be obtained in real time on a typical GPU.

On the other hand, Instance Normalization is at a disadvantage in tasks where contrast or brightness itself is a useful cue, such as image classification. The Group Normalization paper (Wu & He 2018) reports the following results for ResNet-50 trained on ImageNet (32 images per GPU, validation error).

Batch NormalizationLayer NormalizationGroup NormalizationInstance Normalization
Error23.6%25.3%24.1%28.4%
Difference from Batch Normalization—+1.7+0.5+4.8

The same paper notes that Instance Normalization and Layer Normalization are effective for training generative models such as GANs, but have limited success in visual recognition.

Practical Considerations

PyTorch's nn.InstanceNorm2d has no γ\gamma or β\beta by default (affine=False) and no running averages (track_running_stats=False). When replacing Batch Normalization (nn.BatchNorm2d defaults both to True), omitting these arguments removes the learnable scale and shift. Specify affine=True if per-channel γ\gamma and β\beta are needed.

With track_running_stats=True, the computation changes under model.eval(). Running averages of the mean and variance are recorded during training, and those values are used for normalization at inference. This differs from the paper's idea of normalizing each image individually at inference time as well. With the default False, the statistics of the input itself are used in both train() and eval().

Also keep the following in mind.

  • Contrast and brightness information is removed. Because the mean and variance are equalized per image and per channel, it is unsuitable for tasks where that information is needed for the answer (such as image classification).
  • Statistics become unstable in layers with small spatial size. The mean and variance are computed from only H×WH \times W values, so the smaller the feature map, the fewer the values. At 1×11 \times 1, every value becomes 0 after subtracting the mean, which is meaningless.
  • It is unaffected by batch size. The computation is the same even with a batch of 1, making it convenient for generation that processes one image at a time and for tasks with large images.

Comparison with Other Normalization Methods

AspectInstance NormalizationBatch NormalizationLayer NormalizationGroup Normalization
Range pooled for mean/varianceOne channel's spatial positions in one sampleOne channel across batch × spaceAll channels × space in one sampleA channel group × space in one sample
Affected by batch sizeNoYesNoNo
Training vs. inferenceSame computation (PyTorch default)Different (running averages)Same computationSame computation
Per-image contrastRemovedPreservedEqualized across all channelsEqualized per group
ImageNet error (ResNet-50, batch 32)28.4%23.6%25.3%24.1%

Rough guidelines for choosing:

  • Style transfer or image generation where the contrast or color bias of the input should be removed: Instance Normalization.
  • Image classification with CNNs and a sufficiently large batch: Batch Normalization.
  • CNNs with small batches (object detection, segmentation, etc.): Group Normalization.
  • Transformers and RNNs: Layer Normalization or RMSNorm.

PyTorch example

Show code
python
import torch
import torch.nn as nn

x = torch.randn(4, 64, 32, 32)                # [N, C, H, W]

# Default: no γ/β (affine=False), no running averages (track_running_stats=False)
inorm = nn.InstanceNorm2d(64)
print(sum(p.numel() for p in inorm.parameters()))   # 0 (no learnable parameters)

# Specify affine=True to get per-channel γ/β
inorm_affine = nn.InstanceNorm2d(64, affine=True)

# Computation as in Eq. (3) of the paper: mean and variance over H, W per sample and per channel
def instance_norm(x, eps=1e-5):
    mean = x.mean(dim=(2, 3), keepdim=True)
    var = x.var(dim=(2, 3), unbiased=False, keepdim=True)   # biased variance (divide by n)
    return (x - mean) / torch.sqrt(var + eps)

print(torch.allclose(instance_norm(x), inorm(x), atol=1e-5))   # True

# By default, training and inference compute the same thing (statistics of the input itself)
inorm.train(); y_train = inorm(x)
inorm.eval();  y_eval = inorm(x)
print(torch.allclose(y_train, y_eval))   # True

# With track_running_stats=True, eval() normalizes with running averages from training (computation changes)
inorm_rs = nn.InstanceNorm2d(64, track_running_stats=True)
inorm_rs.train(); _ = inorm_rs(x)          # update running averages
inorm_rs.eval();  y_rs = inorm_rs(x)
print(torch.allclose(y_rs, y_train))       # False

# Use in a style transfer generator (in place of Batch Normalization)
block = nn.Sequential(
    nn.Conv2d(3, 32, kernel_size=9, padding=4),
    nn.InstanceNorm2d(32, affine=True),
    nn.ReLU(),
)
print(block(torch.randn(1, 3, 256, 256)).shape)   # works even with batch size 1

FAQ

Q. How does Instance Normalization differ from Layer Normalization?
A.

They pool the mean and variance over different ranges. Layer Normalization computes one set of statistics over all channels and positions of a sample, whereas Instance Normalization computes separate statistics for each channel. As a result, Instance Normalization also removes per-channel differences in brightness and contrast. In addition, in PyTorch, Layer Normalization has element-wise γ and β by default, while Instance Normalization does not.

Q. Can it be used with a batch size of 1?
A.

Yes. Because the mean and variance are computed within a single image, the computation is the same regardless of batch size. The problem of noisy statistics with small batches, as in Batch Normalization, does not occur.

Q. Does model.eval() change the computation at inference?
A.

Not with PyTorch's default (track_running_stats=False). Both training and inference normalize with the statistics of the input itself. Only with track_running_stats=True does eval() switch to the running averages from training. The paper emphasizes normalizing each image individually at inference time as well.

References

  1. D. Ulyanov, A. Vedaldi, and V. Lempitsky, "Instance Normalization: The Missing Ingredient for Fast Stylization," arXiv:1607.08022, 2016.
  2. D. Ulyanov, A. Vedaldi, and V. Lempitsky, "Improved Texture Networks: Maximizing Quality and Diversity in Feed-forward Stylization and Texture Synthesis," CVPR, 2017.
  3. Y. Wu and K. He, "Group Normalization," ECCV, 2018.
  4. PyTorch Documentation, "torch.nn.InstanceNorm2d."