Xavier and He Initialization
Imagine training a 50-layer feedforward network. The loss barely moves after a thousand steps. The weights are random, the architecture is sensible, the learning rate is tuned — yet nothing learns. The culprit is often invisible. The way the weights were initialized silently shrank or exploded the forward signal. This happened before the first gradient was ever computed. This is not a bug in the optimizer. It is a property of how variance compounds. This happens when signals pass through many layers of matrix multiplication and nonlinearity. Xavier initialization (Glorot & Bengio, 2010) and He initialization (He et al., 2015) are two schemes. They solved this problem for the two dominant activation regimes of modern deep learning. These regimes are symmetric saturating activations like tanh and sigmoid, and rectified activations like ReLU. Both are derived from the same first principle. That principle is to keep the variance of activations (and of gradients) roughly constant. This holds as signals propagate forward and backward through a stack of layers. But they arrive at different scaling constants. This is because ReLU systematically discards half the signal. These schemes matter because before them, training deep networks was notoriously fragile. Practitioners relied on unsupervised pretraining or careful hand-tuned scaling. Sometimes they simply gave up on depth. Xavier initialization is widely credited with making it practical to train reasonably deep tanh/sigmoid networks without pretraining. He initialization was a key enabler of very deep ReLU convolutional networks. It was introduced alongside the analysis that made training 30-layer plain ReLU networks feasible. This foreshadowed architectural fixes like residual connections that came soon after. This article derives both schemes from scratch. It gives exact pseudocode for sampling the weights. It works through a concrete numerical trace showing variance evolving layer by layer. It also situates the two schemes within the broader landscape of Weight Initialization Strategies. It connects them to The Vanishing and Exploding Gradient Problem that they were built to solve.
- Xavier and He initialization choose the variance of random initial weights so that activations neither vanish nor explode as they propagate through many layers.
- Xavier (Glorot) initialization is derived for linear/symmetric activations (tanh, sigmoid, linear) and sets variance (or for the forward-only variant).
- He initialization is derived for ReLU-family activations, which zero out half the input in expectation, doubling the required variance to .
- Both schemes match the forward-pass variance and (approximately) the backward-pass gradient variance across layers, controlling exploding/vanishing signals at initialization.
- The derivation assumes independent zero-mean inputs/weights and a specific nonlinearity; violating these assumptions (batch norm, skip connections, non-i.i.d. inputs) weakens the guarantee but rarely hurts much in practice.
- Choosing the wrong scheme for the activation (e.g., Xavier with ReLU) is a common, easily fixed bug that shows up as slow or stalled training in deep nets.
Scale the random initial weights' variance to exactly counteract how each layer's matrix multiply and activation function shrinks or amplifies signal, so that variance stays roughly constant across depth.
The idea
Consider a fully connected layer computing followed by an activation , where is the layer's input, is the weight matrix, and is a nonlinearity such as tanh or ReLU. If the entries of are independent with mean zero and variance , and the entries of are drawn i.i.d. with mean zero and variance , independent of , then each output coordinate is a sum of independent products, so its variance is
This is the forward variance-propagation equation, and it is the entire engine behind both initialization schemes: it tells you exactly how the variance of the signal scales from one layer to the next as a function of the fan-in and the weight variance. If is too large, grows geometrically with depth (exploding activations, and later, exploding gradients). If is too small, shrinks geometrically (vanishing activations, saturating tanh/sigmoid units, dead ReLUs, and vanishing gradients). This is precisely the failure mode described in the The Vanishing and Exploding Gradient Problem: it need not wait for many gradient steps to appear — it is already present in the very first forward pass if initialization is careless.
Xavier / Glorot initialization targets activations that are approximately linear near zero and roughly symmetric (tanh, sigmoid, softsign). Under the approximation near the origin (valid because weights are small and pre-activations start close to zero), the forward equation says we should set
to keep . But Glorot and Bengio also analyzed the backward pass, where the gradient with respect to satisfies an analogous relation with playing the role of fan-in (because the transpose has columns feeding each output gradient coordinate). Requiring simultaneous forward and backward variance preservation gives two competing constraints, and ; Glorot and Bengio's compromise — the standard "Xavier" formula — is their harmonic-mean-flavored average:
He initialization targets ReLU and its variants (Leaky ReLU, PReLU). ReLU is not symmetric: it maps roughly half of a zero-mean symmetric distribution to exactly zero and passes the other half through unchanged. This halves the variance passed forward at every layer, an effect Xavier's derivation does not account for since it assumes near-linearity. He, Zhang, Ren, and Sun (2015) redo the forward-variance calculation with the ReLU nonlinearity explicitly included and find that to compensate for this factor of two, the weight variance must double:
Both schemes are usually implemented by sampling from a scaled Gaussian or a scaled uniform distribution with the target variance, using either fan-in alone, fan-out alone, or the fan-in/fan-out average, depending on the exact variant. The core terminology to fix: fan-in () is the number of input connections to a unit (e.g., for a convolution, ); fan-out () is the number of output connections; and the scheme is chosen according to the activation function used after that weight layer.
How it works
The mechanism is a one-time sampling procedure applied to every weight matrix (or convolutional kernel) at network construction time, before any forward or backward pass. Biases are conventionally initialized to zero (or a small constant for ReLU networks, to reduce the chance of dead units at step zero). The procedure below covers Gaussian and uniform variants of both schemes, generalized to convolutional layers. ```text function COMPUTE_FANS(shape, layer_type):
# shape is (out_channels, in_channels, kH, kW) for conv,
# or (n_out, n_in) for a dense layer if layer_type == "dense": n_in, n_out = shape[1], shape[0] else if layer_type == "conv": receptive_field_size = product(shape[2:]) # kH kW (or kDkHkW) n_in = shape[1] receptive_field_size # C_in receptive field n_out = shape[0] receptive_field_size # C_out * receptive field return n_in, n_out
function XAVIER_INIT(shape, layer_type, distribution="uniform"): n_in, n_out = COMPUTE_FANS(shape, layer_type) variance = 2.0 / (n_in + n_out) if distribution == "uniform": limit = sqrt(3.0 * variance) # uniform[-a,a] has var = a^2/3 W = SAMPLE_UNIFORM(-limit, limit, shape) else: # "normal" std = sqrt(variance) W = SAMPLE_NORMAL(mean=0, std=std, shape) return W
function HE_INIT(shape, layer_type, distribution="normal", mode="fan_in"): n_in, n_out = COMPUTE_FANS(shape, layer_type) fan = n_in if mode == "fan_in" else n_out variance = 2.0 / fan if distribution == "normal": std = sqrt(variance) W = SAMPLE_NORMAL(mean=0, std=std, shape) else: # "uniform" limit = sqrt(3.0 * variance) W = SAMPLE_UNIFORM(-limit, limit, shape) return W
function INITIALIZE_NETWORK(layers): for layer in layers: if layer.activation in {"tanh", "sigmoid", "softsign", "linear"}: layer.W = XAVIER_INIT(layer.weight_shape, layer.type) else if layer.activation in {"relu", "leaky_relu", "prelu", "gelu-ish"}: layer.W = HE_INIT(layer.weight_shape, layer.type) layer.b = ZEROS(layer.bias_shape) return layers ``` A few implementation notes that matter in practice: 1. Uniform vs. normal is a free choice; both hit the target variance, they differ only in tail behavior (uniform has bounded support, Gaussian has unbounded but exponentially small tails). Frameworks default to whichever is more convenient, and empirically the difference is negligible. 2. `mode="fan_in"` vs. `"fan_out"` in He initialization: the original paper uses fan-in (preserves forward variance) but preserving backward gradient variance instead uses fan-out; most libraries default to fan-in since forward-pass stability at initialization is the dominant practical concern. 3. Leaky ReLU correction: for Leaky ReLU with negative slope , the exact He-style variance is , since a fraction of the negative half is now scaled by rather than zeroed, changing the expected squared output. 4. Biases are zero-initialized because the forward-variance argument only concerns the multiplicative weight term; a zero bias does not shift the variance calculation and empirically works well, though small positive bias initialization is sometimes used for ReLU to avoid an initial "all-dead" layer.
Complexity & correctness
Time complexity. Initializing a weight matrix of shape requires exactly one pseudorandom draw per entry, so sampling cost is per layer, matching the size of the matrix itself — this is asymptotically optimal since every weight must be written at least once. Computing the fan-in/fan-out for a layer is for dense layers and for convolutions (a small constant, since kernel tensors have fixed rank 3 or 4). Across an entire network with layers and total parameter count , the whole initialization procedure costs time and space — the same order as simply allocating the parameters, so initialization is never the bottleneck relative to the (or worse) cost of a single forward/backward pass.
Correctness argument. The claim to justify is: under stated independence and zero-mean assumptions, the chosen variance keeps approximately constant across depth, layer after layer. The argument is an induction on depth using the variance-propagation identity. Base case. Assume the network's input has i.i.d. (or at least uncorrelated, equal-variance) coordinates with variance — a property that standard input normalization gives you directly. Inductive step (Xavier, linear-region approximation). Suppose layer 's input has variance per coordinate, weights i.i.d. mean zero, variance , independent of . Then
Since near 0 for tanh/sigmoid at small pre-activation magnitude, . So : the invariant "variance " is preserved at every layer, by induction, for all depths . Without this correction, variance would evolve as , which is exponential in depth whenever — exactly the exploding/vanishing behavior the scheme eliminates. Inductive step (He, ReLU). Let be zero-mean symmetric (true if is zero-mean symmetric and independent of , by a symmetry argument on the joint distribution). For ,
because exactly (by symmetry) half the probability mass has contributing , and the other half has contributing . So . Setting makes this equal exactly, restoring the invariant. This is precisely why He's constant is Xavier's constant times two: ReLU's rectification is a variance-halving operation that must be compensated multiplicatively.
Honest caveats. The argument relies on assumptions that are only approximately true in real networks: weights and activations are treated as independent (violated once weights are updated by gradient descent, since and become statistically coupled through training); the tanh/sigmoid linear approximation breaks down once pre-activations grow large (which is itself controlled, in a virtuous circle, by keeping variance ); and convolutional weight sharing introduces correlations across spatial positions that the i.i.d. fan-in calculation ignores. Additionally, this is purely a forward-pass, initialization-time guarantee — it says nothing about long-run training dynamics, for which normalization layers (BatchNorm, LayerNorm) and residual connections provide complementary, training-time control that these schemes do not replace. Xavier/He initialization and normalization layers are best understood as solving overlapping but distinct parts of the vanishing/exploding problem: initialization fixes the starting point, normalization fixes it throughout training.
Worked example
Take a 5-layer plain (no normalization, no skip connections) fully connected network, each hidden layer of width , ReLU activations, standard-normal input coordinates with unit variance. We compare three initialization choices at layer construction time and track the empirical variance of the pre-activation at each layer over a batch of synthetic input vectors (numbers below are the expected values under the theory; they match simulation to within a few percent).
| Layer | Xavier () applied (wrong scheme) | He () applied (correct scheme) | Weight variance too large |
|---|---|---|---|
| Input | 1.000 | 1.000 | 1.000 |
| Pre-act , | 1.000 | 2.000 | 20.00 |
| Post-act , of above | 0.500 | 1.000 | 10.00 |
| Pre-act | 0.500 | 2.000 | 200.0 |
| Post-act | 0.250 | 1.000 | 100.0 |
| Pre-act | 0.250 | 2.000 | 2000 |
| Post-act | 0.125 | 1.000 | 1000 |
| Post-act | 0.0625 | 1.000 | |
| Post-act | 0.03125 | 1.000 |
Reading the table: with the He scheme (middle column), post-activation variance is restored to exactly after every layer — the invariant from the correctness argument holds at every depth. With Xavier applied to a ReLU network (left column, a common bug when copy-pasting code across activation types), variance shrinks by a factor of per layer because Xavier's derivation never accounts for ReLU's rectification; after 5 layers activations have lost 97% of their original scale, and gradients backpropagating through this stack will be correspondingly attenuated — the network is not dead, but it will learn very slowly, especially in the earliest layers. With weights too large in variance (right column, an initialization bug rather than a scheme mismatch), variance explodes by roughly per layer, reaching by layer 5; in a real network this manifests as `NaN` losses within the first few forward passes as activations overflow floating point range or saturate any downstream nonlinearity into numerically flat regions with zero gradient. This table is the entire practical lesson in miniature: matching variance to the activation function is not a minor tuning knob, it is the difference between a signal that survives 5 layers intact and one that has decayed by orders of magnitude or blown past numerical range — before a single gradient step has been taken.
Common pitfalls & traps
| Pitfall | Why it happens | Consequence |
|---|---|---|
| Using Xavier with ReLU layers | Xavier assumes near-linear activation; ReLU halves variance, which Xavier's derivation doesn't model | Slow training, effectively "half-vanishing" signal each layer |
| Using He with tanh/sigmoid | He's variance is calibrated for ReLU's rectification factor of 2; it's too large for symmetric activations | Pre-activations pushed into the saturating tails of tanh/sigmoid, gradients vanish there instead |
| Forgetting fan-in vs. fan-out for conv layers | Kernel tensor shape is 4D; naive `shape[0]`/`shape[1]` without multiplying by receptive field size undercounts fan-in | Effective variance too large by a factor of , causing early-training instability |
| Zero-initializing all weights (not just biases) | Confusing "small" with "zero"; seems like a safe conservative choice | Perfect symmetry: every unit in a layer computes the identical function and gets identical gradients forever (the symmetry-breaking problem) |
| Assuming initialization alone guarantees stable training | Xavier/He only control the first forward/backward pass statistics | Later-training instabilities (still) require normalization, careful learning rates, or residual connections |
| Ignoring bias initialization for ReLU nets | Zero bias plus small early weights can put many units in the dead (negative pre-activation) region at step 0 | A nontrivial fraction of ReLU units start "dead" and may never activate, wasting capacity |
Pioneers & history
The two schemes emerged from a decade in which understanding why deep networks failed to train was as important as any architectural innovation. Xavier Glorot and Yoshua Bengio's 2010 analysis was among the first to give a principled, activation-aware account of initialization variance, replacing folklore heuristics with an explicit derivation grounded in signal-propagation statistics. Kaiming He and coauthors extended this reasoning to the ReLU-dominated architectures that had by then become the default for convolutional networks, and their initialization scheme was published as part of the same paper that pushed plain feedforward ReLU networks to unprecedented depth, directly motivating the search for the residual connections that followed within the same year.
Origins · 1 minXavier Glorot and how this was discovered
physicist[Kaiming He|born 1984|Researcher whose 2015 work on rectifier-aware initialization and, soon after, residual connections, was central to enabling very deep convolutional networks to train reliably.]
Origins · 1 minhow this was discovered
Where this matters
Every major deep learning framework — PyTorch, TensorFlow/Keras, JAX-based libraries — ships Xavier (often named `glorot_uniform`/`glorot_normal`) and He (`he_uniform`/`he_normal`) as default or near-default initializers, selected automatically or by convention based on the layer's declared activation. Convolutional architectures from AlexNet-successors through ResNets, and their descendants in vision, use He initialization as the standard choice for ReLU-family stacks; architectures relying on tanh gating (older recurrent networks, some autoencoder designs) still use Xavier-style initialization for those specific gates. Framework code for building custom layers routinely exposes a `kernel_initializer` argument defaulting to one of these two schemes, meaning that essentially every practitioner training a from-scratch network — whether for a research prototype, a production vision system, or a course assignment — is implicitly relying on this variance analysis to get a usable starting point for gradient descent, before any of the more expensive machinery of Weight Initialization Strategies like pretraining or layerwise adaptive scaling comes into play.
Ask the tutor: How would you derive the correct initialization variance for the GELU or Swish activation function, which are neither purely linear nor a clean half-rectifier like ReLU?
Why not just initialize every weight to zero and let the optimizer figure it out?
Zero initialization creates a total symmetry problem: if every weight feeding a layer is identical (zero or otherwise), every unit in that layer computes the exact same function of the input and therefore receives the exact same gradient during backpropagation. Gradient descent then updates every unit identically forever, so the layer effectively behaves as a single unit no matter how wide it is declared to be. Random initialization breaks this symmetry by giving each unit a distinct starting function; Xavier and He then add the further refinement of choosing the scale of that randomness so that signal variance is preserved across depth, rather than just breaking symmetry arbitrarily.
Does the choice of Xavier vs. He initialization still matter if the network uses BatchNorm?
Less than it would otherwise, but it is not irrelevant. Batch normalization explicitly re-normalizes activation statistics at every layer during training, which substantially reduces sensitivity to the initial variance since the normalization layer corrects any drift on the very first forward pass. However, at true initialization (before the first BatchNorm statistics are meaningfully estimated, and in networks using LayerNorm or no normalization inside residual branches) the underlying signal still passes through raw matrix multiplications and activations, so a poorly matched initializer can still cause numerical issues or slow early training. In practice, using the activation-appropriate scheme remains the safe default even with normalization layers present.
Why does the Xavier formula average fan-in and fan-out instead of just using fan-in?
Using only fan-in preserves variance on the forward pass; using only fan-out preserves variance on the backward pass through the gradient recursion, since the transpose of the weight matrix has as its effective fan-in for gradient propagation. These two requirements generally conflict whenever , which is the normal case for any layer that changes width. Glorot and Bengio's harmonic-mean-style formula is a compromise that approximately satisfies both constraints simultaneously rather than perfectly satisfying either one, trading a small amount of forward-pass precision for backward-pass stability and vice versa.
How does Leaky ReLU or PReLU change the initialization formula?
Leaky ReLU replaces the "zero out negative inputs" rule with "scale negative inputs by a small slope " (commonly , or a learned parameter for PReLU). Redoing the variance calculation, the expected squared output becomes instead of , since the negative half now contributes rather than . Matching this to the input variance gives , which reduces exactly to the standard He formula when (pure ReLU) and smoothly interpolates toward the Xavier-like regime as (approaching a linear, symmetric map).
Is there a version of these schemes for networks without any nonlinearity, like linear autoencoders or the first layer of a network?
Yes — the derivation for a purely linear layer is exactly the Xavier forward-pass calculation without needing the "activation ≈ identity" approximation, since the activation genuinely is the identity. The correct target is still (forward-preserving) or the fan-in/fan-out average if backward-pass preservation also matters, which is why Xavier initialization (designed with near-linear activations in mind) is the standard default for purely linear layers, embedding layers, and the first layer of a network that operates directly on raw, unnormalized-in-scale features.
Can these initialization schemes fail even when applied correctly?
Yes, in several documented ways. The independence assumption between weights and activations is only exact at the very first forward pass; once training begins, weights become statistically coupled to the data distribution, and the clean variance argument no longer strictly holds — this is why initialization alone does not guarantee stable training over hundreds of thousands of steps. Very deep plain networks (dozens of layers, no skip connections or normalization) can still suffer gradient degradation from compounding small approximation errors even with variance matched exactly at layer one, which is part of why residual connections and normalization layers were developed as complementary, training-time solutions rather than replacements for correct initialization.
Do these schemes apply to recurrent networks (RNNs, LSTMs, GRUs)?
The input-to-hidden and hidden-to-hidden weight matrices in RNNs are typically initialized with Xavier or He depending on the activation used for the corresponding gate or transform (tanh gates get Xavier-style scaling, ReLU-based recurrent variants get He-style scaling). However, recurrent networks introduce an additional, distinct instability: signal is propagated through the same weight matrix repeatedly across time steps, so even a perfectly variance-matched initialization does not prevent the exponential blowup or decay that arises from repeated multiplication by the same matrix's eigenvalues over long sequences. This is why recurrent architectures additionally rely on gating mechanisms (LSTM/GRU) and sometimes orthogonal initialization of the recurrent weight matrix, on top of activation-aware initialization of the input weights.