Deep Learning · Beginner Tutorial
Before a neural network learns its first example, its weights need sensible starting values. As data and gradients cross many layers, their numerical scale must also remain usable. This lesson shows why signals vanish or explode, how Xavier and He initialization set a safer starting scale, and how Batch, Layer, Instance and Group Normalization stabilize different groups of activations.
A Deep Network Must Carry Two Signals Safely
During the forward pass, numbers move from the input toward the prediction. During backpropagation, gradients move in the opposite direction so earlier weights can learn. Every layer multiplies, adds and transforms those numbers. If the scale repeatedly shrinks, useful information fades. If it repeatedly grows, values and updates become unstable.
Initialization controls the network’s starting scale before any training has occurred. Normalization controls selected activation scales while the network operates. Residual connections, suitable activations, optimizer settings and gradient clipping can also help, but they solve different parts of the stability problem.
What happens when a signal crosses many layers?
Bar height represents the relative size of activations. All three examples begin before learning.
Weights too small
The signal fades before it reaches the last layer.
The signal fades before it reaches the last layer.
Well-scaled start
The signal stays in a useful range through the network.
The signal stays in a useful range through the network.
Weights too large
The signal grows and may produce unstable values.
The signal grows and may produce unstable values.
Forward direction
Input → layer activations → prediction. We want useful variation to survive without values becoming enormous.
Backward direction
Loss → output gradients → earlier-layer gradients. We want the learning signal to reach early parameters at a usable scale.
Why Not Initialize Every Weight to Zero?
A bias can often start at zero, but setting every weight in a hidden layer to the same value creates a symmetry problem. Neurons with identical incoming weights produce identical outputs. They then receive identical gradients and remain identical after every update. Ten identical neurons behave like one repeated neuron instead of learning ten different features.
Why identical hidden weights fail to create different learners
Small random differences break that symmetry, but “random” is not enough. The distribution needs a scale related to the layer’s size and activation function. That is the purpose of variance-scaled initialization.
Fan-In, Fan-Out and Variance
A dense neuron combines several inputs. Fan-in is the number of values entering a neuron; fan-out is the number of neurons receiving outputs from that layer. If a neuron adds many independently weighted inputs, the output variance can grow with fan-in unless the weights become correspondingly smaller.
Mean
The centre of a group of values. Initial weight distributions are commonly centred near zero.
Variance
How spread out values are around their mean. Variance controls signal strength more directly than a vague “small random” description.
Standard deviation
The square root of variance. A normal initializer usually asks for this scale.
Xavier/Glorot Initialization for Balanced Signals
Xavier initialization chooses random weights whose scale depends on both fan-in and fan-out. Its aim is to keep forward activations and backward gradients at roughly comparable variance across layers. It is a common match for tanh and other roughly symmetric activations.
Xavier normal
Xavier uniform
Worked example: 4 inputs and 6 outputs
The layer shape supplies these two counts: every output neuron receives 4 input values, so fan-in = 4; the layer produces 6 output values, so fan-out = 6. They are architecture choices, not values learned during training.
Xavier normal scale
σ = √(2 / (4 + 6))
= √0.2
≈ 0.447
Xavier uniform range
a = √(6 / (4 + 6))
= √0.6
≈ 0.775
weights are sampled from [−0.775, +0.775]
Interpretation: this calculation does not assign every weight the value 0.447. It sets the spread of a random distribution. Each neuron receives different random values, but the overall scale is controlled.
He/Kaiming Initialization for ReLU Layers
ReLU turns every negative input into zero. At a roughly symmetric start, that removes about half of the activations. He initialization compensates by using a larger variance based mainly on fan-in, helping the surviving positive signal retain a useful scale.
He normal for ReLU
Use the same fan-in = 4
The 4 again comes from the number of inputs entering each neuron. ReLU is the developer's activation choice, so it determines why the He formula—not the Xavier formula—is used here.
σ = √(2 / 4)
= √0.5
≈ 0.707
Why larger than Xavier’s 0.447? ReLU discards negative outputs, so the initializer allows a larger starting spread to compensate. It still does not guarantee perfect stability: architecture depth, data scale, residual paths and optimizer settings continue to matter.
| Situation | Starting initializer | Reason |
|---|---|---|
| ReLU or Leaky ReLU hidden layers | He/Kaiming | Accounts for the signal loss caused when ReLU sets negative values to zero. |
| Tanh hidden layers | Xavier/Glorot | Balances fan-in and fan-out to keep forward and backward variance useful. |
| Sigmoid hidden layers | Xavier/Glorot, with care | Better scaled than arbitrary random values, but deep sigmoid networks can still saturate and vanish. |
| SELU self-normalizing network | LeCun-normal-style recipe | Use the activation, initializer and architecture conditions together; ordinary dropout breaks the intended behaviour. |
| Pretrained model | Keep pretrained weights | Reinitializing the backbone destroys the learned representation; initialize only new layers unless intentionally training from scratch. |
How Gradients Vanish or Explode
Backpropagation uses the chain rule, multiplying local derivatives along the path from the loss to an earlier layer. A single factor below 1 is not automatically a problem. The danger is repeated multiplication through many layers or time steps.
Chain-rule idea
Vanishing example
For teaching, suppose five successive local derivatives are each 0.5. A real network calculates each derivative from its current weights, activations and data.
0.5 × 0.5 × 0.5 × 0.5 × 0.5
= 0.5⁵
= 0.03125
Only about 3% of the original scale remains after five factors. Earlier layers receive very small updates.
Exploding example
Now suppose the five calculated local derivatives are each 1.5. The repeated multiplication reverses the effect.
1.5 × 1.5 × 1.5 × 1.5 × 1.5
= 1.5⁵
≈ 7.594
The scale becomes more than seven times larger after only five factors. Deeper products can grow dramatically.
Vanishing clues
Early-layer gradient norms near zero, unchanged early weights and loss that improves only in later layers.
Exploding clues
Large gradient norms, erratic loss, huge weight changes, infinities or NaNs.
Different remedies
Initialization, residual paths and suitable activations help flow; clipping limits explosions but does not restore vanished information.
Normalization Re-centres and Re-scales Activations
Even with a good initial scale, activations change as weights learn. A normalization layer selects a group of values, subtracts their mean, divides by their standard deviation, and then applies a learned scale and shift. The first two operations standardize; the learned γ and β allow the network to choose a useful range instead of being permanently forced to mean 0 and variance 1.
Normalization followed by learned scale and shift
x̂i = (xi − μ) / √(σ² + ε)
yi = γx̂i + β
Worked example: values [2, 4, 6, 8]
The four values are illustrative activations produced by an earlier layer. We temporarily ignore the tiny ε because the variance is safely above zero. The example uses γ = 2 and β = 0.5 as a possible learned state; frameworks usually initialize them to 1 and 0, then training changes them.
1. Mean
μ = (2 + 4 + 6 + 8) / 4 = 5
2. Variance
σ² = (9 + 1 + 1 + 9) / 4 = 5
3. Standardize
√5 ≈ 2.236
x̂ ≈ [−1.342, −0.447, 0.447, 1.342]
4. Learn scale and shift
if γ = 2 and β = 0.5:
y ≈ [−2.184, −0.394, 1.394, 3.184]
Interpretation: standardization creates a predictable centre and spread. γ = 2 stretches the standardized values and β = 0.5 moves them upward. Both can be learned by backpropagation.
Batch, Layer, Instance and Group Normalization
The mathematical operation is similar, but the methods choose different values for μ and σ². That choice determines whether the result depends on other examples in the mini-batch, which tensor dimensions are standardized, and which architectures the method naturally fits.
The formula is similar; the selected group of values is different
Each mini-grid represents a tensor with examples as rows and features or channels as columns. Coloured cells contribute to one mean and variance calculation.
Batch Normalization
same channel across examples and spatial positions
Layer Normalization
features within one example/token
Instance Normalization
one channel inside one image
Group Normalization
a group of channels inside one image
| Situation | Good starting method | Why |
|---|---|---|
| CNN with moderate/large batches | BatchNorm | Per-channel batch statistics are well established and efficient. |
| CNN with batches of 1–4 images | GroupNorm | Its statistics do not depend on other batch examples. |
| Transformer or token representation | LayerNorm or architecture-specified RMSNorm | Statistics are computed within each token/example, so sequence batches can vary. |
| Neural style transfer | InstanceNorm | Per-image, per-channel normalization reduces instance-specific contrast information. |
| Existing tested architecture | Follow its normalization placement | Changing pre-norm/post-norm or axes can alter optimization and checkpoint compatibility. |
BatchNorm behaves differently during training and inference
model.train()
Use this mini-batch’s mean and variance
Also update running averages that summarize training batches.
model.eval()
Use saved running mean and variance
One production example should not depend on whichever examples happen to arrive beside it.
torch.no_grad() does not switch BatchNorm to inference behaviour; call model.eval() as well.Implementing a Stable ReLU Network in PyTorch
The code below applies Kaiming initialization only to convolutional layers that are followed by ReLU. The final classifier produces logits and is not followed by ReLU, so it receives a separate Xavier initialization. BatchNorm stabilizes each feature channel during training, and evaluation mode makes validation use saved running statistics.
import torch
from torch import nn
class SmallCNN(nn.Module):
def __init__(self):
super().__init__()
self.features = nn.Sequential(
nn.Conv2d(3, 32, kernel_size=3, padding=1, bias=False),
nn.BatchNorm2d(32),
nn.ReLU(),
nn.Conv2d(32, 64, kernel_size=3, padding=1, bias=False),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.AdaptiveAvgPool2d(1),
)
self.classifier = nn.Linear(64, 10)
# These convolutional layers are each followed by ReLU.
for module in self.features.modules():
if isinstance(module, nn.Conv2d):
nn.init.kaiming_normal_(module.weight, mode="fan_in", nonlinearity="relu")
# The classifier emits logits; no ReLU follows it.
nn.init.xavier_uniform_(self.classifier.weight)
nn.init.zeros_(self.classifier.bias)
def forward(self, x):
x = self.features(x)
return self.classifier(x.flatten(1))
model = SmallCNN()
# Training: BatchNorm uses batch statistics and updates running values.
model.train()
train_logits = model(train_images)
# Validation/inference: use the saved running statistics.
model.eval()
with torch.no_grad():
validation_logits = model(validation_images)Where the dimensions come from
3 input channels come from RGB image data. 32 and 64 feature channels are developer-chosen model capacities. 10 outputs come from the dataset's ten classes. A 3 × 3 kernel and padding 1 are chosen to inspect a small neighbourhood while preserving height and width.
What PyTorch performs internally
kaiming_normal_ calculates fan-in for each ReLU-followed convolution. xavier_uniform_ separately initializes the final logits classifier because no ReLU follows it; keeping that layer's framework default would also be a reasonable deliberate choice. BatchNorm2d(32) keeps one learned γ and β for each of 32 channels. model.train() uses and updates batch statistics; model.eval() uses saved running statistics; no_grad() stops gradient recording but does not change BatchNorm mode.
For a tiny image batch
Replace nn.BatchNorm2d(32) with something like nn.GroupNorm(8, 32), provided the channel count is divisible by the number of groups. GroupNorm uses current-example statistics in both training and evaluation.
Diagnosing Unstable Signals and Gradients
| Symptom | Possible cause | What to inspect or change |
|---|---|---|
| Every hidden neuron learns the same feature | Identical hidden weights | Use the framework’s random initializer or an activation-aware Xavier/He scheme |
| Early layers have near-zero gradient norms | Vanishing gradients, saturation or a disconnected graph | Inspect per-layer norms; check activations, initialization, residual paths and graph connectivity |
| Loss suddenly becomes NaN | Exploding gradients, excessive learning rate or invalid data | Log activation/gradient norms; lower the rate; validate inputs; clip only as a guard after diagnosis |
| BatchNorm validation is unstable | Model left in training mode or poor running statistics | Call model.eval(); confirm representative training batches and restored running buffers |
| BatchNorm fails with batches of one or two | Batch statistics are too noisy or undefined for the chosen shape | Use GroupNorm/LayerNorm or increase the effective batch size |
| A pretrained model suddenly performs poorly | Backbone was reinitialized or normalization statistics were mishandled | Load the checkpoint before selective initialization; preserve or deliberately adapt normalization state |
Normalization is not a cure for bad input data.
Still scale raw inputs appropriately, validate labels, and inspect outliers. A normalization layer cannot repair corrupt values or data leakage.
Initialization does not choose the final solution.
It creates trainable starting conditions. Different seeds can still produce different outcomes, so important experiments should report variability.
The Essential Picture
- Random weights break symmetry; their scale determines whether early signals survive.
- Xavier/Glorot balances fan-in and fan-out and commonly fits tanh-like layers.
- He/Kaiming uses a ReLU-aware fan-in scale.
- Vanishing and exploding gradients arise from repeated chain-rule multiplication.
- Normalization standardizes selected activations, then learns a scale γ and shift β.
- BatchNorm depends on batch statistics during training; LayerNorm, InstanceNorm and GroupNorm use within-example groups.
- Stable training is a system property involving data scale, activation, initialization, architecture, normalization, optimizer and learning rate.