Layer Normalization
What It Does
LayerNorm normalizes all features within each sample.
Given a 2D input matrix:
- Rows = batch samples
- Columns = features
LayerNorm normalizes each row (sample) independently across all features.


How It Works
For each sample in the batch:
- Compute mean and variance across features:
- Normalize:
- Scale and shift (learnable parameters):
Code Example
import torch.nn as nn
model = nn.Sequential(
nn.Linear(64, 128),
nn.LayerNorm(128), # Normalize across 128 features for each sample
nn.ReLU(),
nn.Linear(128, 10)
)Advantages
- Works with any batch size (even batch size = 1)
- Same behavior in training and inference
- Better for RNNs and Transformers
- No dependency on batch statistics
- More stable for small batches
Disadvantages
- Less regularization effect than BatchNorm
- May not work as well for CNNs as BatchNorm