Xavier initialization: a forward–backward compromise
Xavier 初始化
Derive the fan-based variance, distinguish it from standard deviation and exactly audit unequal forward/backward multipliers.
xavier-initializationTwo directions ask for different scales
A dense layer with two inputs and six outputs adds two weighted terms for each forward output. In reverse, each input gradient can add six weighted terms. A weight scale that preserves a typical forward variance need not preserve a typical backward variance. Xavier initialization makes a compromise between these two counts.
The rule is also called Glorot initialization. Glorot and Bengio,2010, Section 4.2.1 derives a normalized initialization in a linearized regime. D2L, Section 5.4.2.2 explains the variance calculation. This chapter makes the compromise explicit with an exactly enumerable two-input, six-output example.
Read parameter initialization and expectation and variance first. The formulas concern an initialization distribution and specified independence assumptions, not a guarantee about every finite sampled matrix.
Count terms in the forward and backward sums
Let a dense weight matrix have n_out rows and n_in columns. Assume zero biases; independent, zero-mean weights with variance v; and independent zero-mean inputs of variance q, independent of those weights. For a linear layer:
The last equality additionally assumes output-gradient components are zero mean with variance r and independent of the weights and each other. These assumptions are useful at initialization but generally not exact throughout training. For nonlinear layers, the derivative of the activation also enters; the original analysis approximates a symmetric activation with slope 1 near zero.
To derive the forward equality, expand the squared sum. Cross terms vanish under the assumptions, while each remaining product has second moment vq. Preserving q asks for v=1/n_in. Applying the same argument backward asks for v=1/n_out. When widths differ, these demands cannot both be met by one variance.
A compromise, not two simultaneous equalities
Xavier sets:
A uniform variable on[−a,a] has variance a²/3, which yields this bound. The standard deviation is √v, not v. A zero-mean Gaussian with variance v matches this second-moment calculation but has different tails; the original normalized uniform rule is the one implemented here.
The forward and backward variance multipliers are:
For n_in=2 and n_out=6, v=1/4, standard deviation 1/2 and uniform bound√3/2. The forward multiplier is 1/2 and the backward multiplier 3/2. Their arithmetic mean is 1; neither individual multiplier is 1. Equal fan counts are the special case where both match 1.
This derivation preserves scalar variance in a model of random signals. It does not make every singular value equal to 1, preserve all vector norms or guarantee well-conditioned optimization. A random matrix can have the requested entry variance and still shrink some directions much more than others.
Separate sampling from an exact moment audit
The complete Python 3.12 program creates a 6×2 uniform weight matrix with a local pseudorandom generator. It also enumerates a separate sign-valued distribution to check the predicted forward and backward moments exactly.
from fractions import Fraction as F
from itertools import product
from math import sqrt
from random import Random
def xavier_parameters(fan_in, fan_out):
if any(type(n) is not int or not 1<=n<=64 for n in (fan_in,fan_out)):
raise ValueError('integer fans from 1 to 64 required')
variance=F(2,fan_in+fan_out)
return variance,sqrt(float(variance)),sqrt(3*float(variance))
def initialize(fan_in, fan_out, seed):
_,_,bound=xavier_parameters(fan_in,fan_out)
if type(seed) is not int or not 0<=seed<=1000000:raise ValueError('bounded integer seed required')
rng=Random(seed)
return [[rng.uniform(-bound,bound) for _ in range(fan_in)] for _ in range(fan_out)]
def exact_sign_variance(terms, scale):
if type(terms) is not int or not 1<=terms<=8:raise ValueError('one to eight terms required')
if type(scale) not in (int,F) or not 0<=scale<=4:raise ValueError('bounded rational scale required')
values=[F(scale)*sum(signs) for signs in product((-1,1),repeat=terms)]
mean=sum(values)/len(values)
return sum((v-mean)**2 for v in values)/len(values)
if __name__=='__main__':
variance,std,bound=xavier_parameters(2,6)
print('fan_in2/fan_out6: variance',variance,'std',f'{std:.9f}','uniform bound',f'{bound:.9f}')
print('exact sign-law forward/backward variances:',exact_sign_variance(2,F(1,2)),exact_sign_variance(6,F(1,2)))
weights=initialize(2,6,7)
print('uniform matrix shape:',len(weights),len(weights[0]),'first row:',*[f'{v:.9f}' for v in weights[0]])
print('same seed reproduces matrix:',weights==initialize(2,6,7))
Actual output:
fan_in2/fan_out6: variance 1/4 std 0.500000000 uniform bound 0.866025404
exact sign-law forward/backward variances: 1/2 3/2
uniform matrix shape: 6 2 first row: -0.305130602 -0.604746970
same seed reproduces matrix: True
For the exact audit, each weight is independently±1/2 and each input is independently±1. Their products are independent±1/2 values, so it suffices to enumerate the product signs. A two-term sum has variance 1/2; a six-term sum has variance 3/2. Independent sign-valued output gradients give the same six-term backward calculation. This sign law shares variance 1/4 with the Xavier distribution but is not the uniform sampler above.
A 12-entry uniform draw will not usually have sample mean exactly zero or sample variance exactly 1/4. The tests therefore check the sampler’s bounds, shape and reproducibility, and use exhaustive sums to check the moment identities. They do not force one random draw to equal its population moments.
Generating weights takes O(n_in·n_out) time and storage. The sign audit costs O(k 2ᵏ) arithmetic and O(2ᵏ) storage for k terms, capped at 8. Exhaustive enumeration is a tiny teaching reference, not a scalable initialization routine.
The activation and matrix layout matter
ReLU does not satisfy the slope 1 linearized model on both sides. He initialization accounts for the rectifier’s effect on second moments. Replacing an activation or adding a gain changes the intended scale; copying a formula without its assumptions can produce the wrong distribution.
Our matrix uses output-by-input layout and column-vector multiplication. Frameworks may store weights differently or apply a transpose internally. A correct fan count describes actual connections, not whichever array axis happens to come first. Convolution, grouped operations and shared parameters need their own connectivity accounting.
Zero-mean weight initialization does not imply every later activation has zero mean. Learned correlations, nonzero biases and saturation can invalidate the simple factorization. Monitor actual signal and gradient distributions; an initialization rule is a starting condition, not a promise that these moments remain fixed during learning.
Which number is the variance?
- For fans 2 and 6, what are the Xavier variance and standard deviation?
Answer 1: Variance 1/4 and standard deviation 1/2.
- What uniform half-width gives that variance?
Answer 2: √3/2, since the variance of U[−a,a] is a²/3.
- Does this setting preserve both forward and backward scalar variance?
Answer 3: No. Their multipliers are 1/2 and 3/2; only their arithmetic mean equals 1.
- Why is the sign-valued exact audit not a test that the sampler generates uniform weights?
Answer 4: It checks a moment identity using a different distribution with the same variance. Sampling law, bounds and reproducibility require separate checks.
The original rule names a particular approximation
The 2010 AISTATS paper appears in PMLR 9:249–256. Its analysis states a linearized regime, independent weights and comparable input variances before proposing the compromise and uniform distribution. Conference dates and repository-export dates should not be conflated into an invented publication day.
The sampler and exact sign audit here are original. No empirical results from the paper are reproduced. Continue to He initialization for rectifiers and vanishing gradients for directional effects that a scalar variance average cannot settle.
Make a prediction, then check
For fan_in2 and fan_out6, what are the forward/backward variance multipliers?
Learning objectives
- Derive distinct fan-in and fan-out variance constraints.
- Separate population moments from a finite sampled matrix.
Prerequisites & connections
Explore related knowledge →References
- Understanding the difficulty of training deep feedforward neural networks
Xavier Glorot; Yoshua Bengio · 2010 - Numerical Stability and Initialization — Dive into Deep Learning 1.0.3
D2L authors · 2023
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex single-agent authored technical review: cited primary-source scope, explicit assumptions, original calculations and counterexamples, runnable tests and bilingual review; not independent human or second-agent review.
- Single-agent authored technical review: bounded primary-source locations, assumptions, original derivations, exact/literal references and matching bilingual equations/examples/exercises. Not independent human or second-agent review.
- Four focused CPython3.12.4 tests passed per chapter. Symmetry trajectories, exact sign-law moments, initializer sampling and directional Jacobian products are checked against literal references, analytic identities and finite differences. All four examples use the standard library.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- Understanding the difficulty of training deep feedforward neural networks · Section4.2.1 printed253–254, assumptions and equations4–16, normalized uniform rule and unequal-width compromise.
- Numerical Stability and Initialization — Dive into Deep Learning 1.0.3 · Section5.4.2.2, no-nonlinearity sum and independent zero-mean input/weight setup.
Related topics