Skip to main content
LearnMLAcademy
Advanced10 min read

Initialization, Normalization and Stable Gradients

Prevent vanishing gradients with He initialization and Layer Normalization, with tensor walkthroughs, gradient calculations, and PyTorch practice.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

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.

L1
L2
L3
L4
L5
L6

Well-scaled start

The signal stays in a useful range through the network.

L1
L2
L3
L4
L5
L6

Weights too large

The signal grows and may produce unstable values.

L1
L2
L3
L4
L5
L6
Conceptual illustration. Real activation distributions depend on the inputs, architecture, activation functions and the sampled weights.

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

All hidden weights identicalSmall random hidden weightsw = 0w = 0w = 0inputoutputsame output → same gradient → same featurew = .08w = −.03w = .11inputoutputdifferent outputs → different gradients → different features
Read left to right: if hidden neurons start with identical incoming weights, they remain copies under ordinary gradient updates. Randomness breaks that symmetry; variance scaling then keeps the random values from being too weak or too strong.

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

σ = √(2 / (fanin + fanout))
Draw each weight from a zero-centred normal distribution with this standard deviation.

Xavier uniform

a = √(6 / (fanin + fanout))
Draw each weight uniformly between −a and +a.

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

σ = √(2 / fanin)
For a ReLU layer, draw weights from a zero-centred normal distribution with variance 2/fan-in, or standard deviation √(2/fan-in).

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.

SituationStarting initializerReason
ReLU or Leaky ReLU hidden layersHe/KaimingAccounts for the signal loss caused when ReLU sets negative values to zero.
Tanh hidden layersXavier/GlorotBalances fan-in and fan-out to keep forward and backward variance useful.
Sigmoid hidden layersXavier/Glorot, with careBetter scaled than arbitrary random values, but deep sigmoid networks can still saturate and vanish.
SELU self-normalizing networkLeCun-normal-style recipeUse the activation, initializer and architecture conditions together; ordinary dropout breaks the intended behaviour.
Pretrained modelKeep pretrained weightsReinitializing 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

∂Loss/∂wearly = (∂Loss/∂aL) × … × (∂a2/∂a1) × (∂a1/∂wearly)
Each factor describes how one stage changes the next. The product can become tiny or enormous even when no individual factor looks extreme.

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 + β

μ is the selected group’s mean, σ² its variance, ε a tiny stability constant, γ the learned scale and β the learned shift.

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

one statistics group
x11
x12
x13
x14
x21
x22
x23
x24
x31
x32
x33
x34
x41
x42
x43
x44
rows: examplescolumns: features/channels

Layer Normalization

features within one example/token

one statistics group
x11
x12
x13
x14
x21
x22
x23
x24
x31
x32
x33
x34
x41
x42
x43
x44
rows: examplescolumns: features/channels

Instance Normalization

one channel inside one image

one statistics group
x11
x12
x13
x14
x21
x22
x23
x24
x31
x32
x33
x34
x41
x42
x43
x44
rows: examplescolumns: features/channels

Group Normalization

a group of channels inside one image

one statistics group
x11
x12
x13
x14
x21
x22
x23
x24
x31
x32
x33
x34
x41
x42
x43
x44
rows: examplescolumns: features/channels
Real convolution tensors also contain height and width, and framework APIs specify exact axes. The coloured selection gives the core intuition: BatchNorm depends on other examples in the mini-batch; LayerNorm, InstanceNorm and GroupNorm calculate statistics within each example.
SituationGood starting methodWhy
CNN with moderate/large batchesBatchNormPer-channel batch statistics are well established and efficient.
CNN with batches of 1–4 imagesGroupNormIts statistics do not depend on other batch examples.
Transformer or token representationLayerNorm or architecture-specified RMSNormStatistics are computed within each token/example, so sequence batches can vary.
Neural style transferInstanceNormPer-image, per-channel normalization reduces instance-specific contrast information.
Existing tested architectureFollow its normalization placementChanging 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.

batch values → μB, σ²B → normalized values
→

model.eval()

Use saved running mean and variance

One production example should not depend on whichever examples happen to arrive beside it.

new value + running μ, σ² → normalized value
Calling 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.

stable_cnn.py
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

SymptomPossible causeWhat to inspect or change
Every hidden neuron learns the same featureIdentical hidden weightsUse the framework’s random initializer or an activation-aware Xavier/He scheme
Early layers have near-zero gradient normsVanishing gradients, saturation or a disconnected graphInspect per-layer norms; check activations, initialization, residual paths and graph connectivity
Loss suddenly becomes NaNExploding gradients, excessive learning rate or invalid dataLog activation/gradient norms; lower the rate; validate inputs; clip only as a guard after diagnosis
BatchNorm validation is unstableModel left in training mode or poor running statisticsCall model.eval(); confirm representative training batches and restored running buffers
BatchNorm fails with batches of one or twoBatch statistics are too noisy or undefined for the chosen shapeUse GroupNorm/LayerNorm or increase the effective batch size
A pretrained model suddenly performs poorlyBackbone was reinitialized or normalization statistics were mishandledLoad 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.

Continue Learning

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Initialization, Normalization and Stable Gradients"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Summary / Key Takeaways

  • Initialization sets parameter scales before learning begins.
  • Too-large values can explode signals; too-small values can erase them.
  • Xavier suits symmetric activations; He suits ReLU-like layers.
  • Normalization stabilizes activation statistics.
  • BatchNorm behaves differently in training and evaluation modes.
  • Monitor activations and gradients throughout training.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5conceptual
Why not initialize every weight to the same value?
Question 2 of 5practical selection
Which initialization is designed for ReLU-like layers?
Question 3 of 5debugging/diagnostic
What symptom suggests weights are initialized much too large?
Question 4 of 5interpretation
How does BatchNorm behave differently during evaluation?
Question 5 of 5debugging/diagnostic
What should be inspected in addition to the loss?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1Why not initialize every weight to the same value?▼

Correct Answer: Units remain symmetric and learn the same feature

Identical units receive identical gradients, so they fail to specialize.

2Which initialization is designed for ReLU-like layers?▼

Correct Answer: He initialization

He scaling accounts for ReLU discarding roughly half the signal and helps preserve variance.

3What symptom suggests weights are initialized much too large?▼

Correct Answer: Exploding activations or non-finite loss

Large repeated transformations can amplify values and gradients until they overflow.

4How does BatchNorm behave differently during evaluation?▼

Correct Answer: It uses stored running statistics rather than current-batch updates

Evaluation must be deterministic and use training-time running estimates.

5What should be inspected in addition to the loss?▼

Correct Answer: Activation and gradient distributions

Signal and gradient statistics reveal vanishing, explosion, saturation, and normalization problems directly.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Optional Learning Resources

These resources may complement the lesson. They are optional and are not required to use ML Academy.

As an Amazon Associate I earn from qualifying purchases. Other links are identified separately when they are not affiliate links.

Next