Skip to content
Deep learning Foundation 24 min read

Activation functions

The activation function is the only nonlinear thing in an MLP, so it decides what a deep network can represent and, through its derivative, whether gradients survive the trip back through the layers. The field moved from sigmoid and tanh to ReLU, then to smooth ReLU-like curves (GELU, SiLU) and finally to gated units (SwiGLU) inside today's LLMs. Each step fixed a specific, measurable problem.

10,000 ft

Without a nonlinearity, depth is worthless (neurons and MLPs). With a badly chosen one, depth is untrainable: the derivative \(\phi'\) multiplies the gradient at every layer of backpropagation, so a function whose slope is usually small makes the gradient vanish. The switch from sigmoid to ReLU around 2010–2012 was one of the three or four changes (with GPUs, big labelled datasets and dropout) that made the 2012 deep learning breakthrough possible. In 2026 the choice is mostly settled by architecture: ReLU in many convolutional nets, GELU in BERT-style encoders and vision transformers, gated SwiGLU or GeGLU in the feed-forward layers of most large language models (the transformer block). Knowing why lets you read new architectures and debug dead or exploding networks.

2,000 ft

Four families, each fixing the previous one's flaw:

How activation functions evolved
How activation functions evolved. Saturating sigmoid, tanh (1980s–2000s), Piecewise linear ReLU, leaky ReLU, PReLU (2010–), Smooth, ReLU-like ELU, SELU, GELU, SiLU (2015–), Gated GLU, SwiGLU, GeGLU (2016; LLMs 2020–), slope ≤ 0.25 kills gradients in deep stacks, dead units, kink at 0, non-zero mean, multiplicative interactions beat a fixed curveHow activation functions evolved. Saturating sigmoid, tanh (1980s–2000s), Piecewise linear ReLU, leaky ReLU, PReLU (2010–), Smooth, ReLU-like ELU, SELU, GELU, SiLU (2015–), Gated GLU, SwiGLU, GeGLU (2016; LLMs 2020–), slope ≤ 0.25 kills gradients in deep stacks, dead units, kink at 0, non-zero mean, multiplicative interactions beat a fixed curve

  • Sigmoid / tanh squash to a bounded range; their slope is small except near 0, so deep stacks lose gradient.
  • ReLU \(\max(0, x)\) has slope exactly 1 for positive inputs, is nearly free to compute and makes activations sparse; but units can die.
  • GELU / SiLU are smooth versions of ReLU that let small negative values through; they train slightly better in transformers.
  • Gated units compute \(\phi(\mathbf{x}W) \odot (\mathbf{x}V)\): one branch decides how much of the other to let through.

Ground level

What an activation has to do

Four jobs, in order of importance:

  1. Be nonlinear, and not a polynomial, or the network cannot approximate arbitrary functions (the Leshno et al. theorem on the MLP page).
  2. Pass gradient. Backprop multiplies by \(\phi'(z)\) at every layer. If \(\phi'\) is small over most of the inputs the layer actually sees, gradients shrink geometrically with depth.
  3. Keep the signal's statistics stable. If activations have a large non-zero mean, or their variance changes from layer to layer, later layers see shifted, rescaled inputs. Initialisation and normalisation manage this, but the activation sets the constants.
  4. Be cheap. It runs on every element of every hidden layer, forward and backward. A max is far cheaper than an exp, although on modern accelerators elementwise ops are usually limited by memory bandwidth rather than arithmetic, so smooth functions cost less than you might expect (kernels).

Sigmoid and tanh: the saturating era

The logistic sigmoid \(\sigma(x) = 1/(1 + e^{-x})\) was the natural first choice: it is a smooth version of the perceptron's step, its output reads as a probability, and it was loosely motivated by neuron firing rates. Its derivative is \(\sigma'(x) = \sigma(x)(1 - \sigma(x))\), which peaks at 0.25 at \(x = 0\) and is below 0.01 once \(|x| > 4.6\).

Two problems follow.

  • Vanishing gradients. Even in the best case each sigmoid layer multiplies the gradient by at most 0.25 (backpropagation), and for units pushed into saturation the factor is effectively zero.
  • Non-zero-centred outputs. Sigmoid outputs are always positive, so for a unit fed by sigmoid units, the gradient on every incoming weight \(\partial L/\partial w_i = \delta \cdot h_i\) has the same sign as \(\delta\). All the weights must move up together or down together, which makes gradient descent zig-zag. LeCun et al.'s Efficient BackProp (1998) made this argument and recommended tanh.

\(\tanh(x) = 2\sigma(2x) - 1\) is a rescaled sigmoid: output in \((-1, 1)\), zero-centred, slope 1 at the origin, derivative \(1 - \tanh^2(x)\). It fixed the centring problem and quadrupled the peak slope, but it still saturates. Tanh remained the default for hidden layers until about 2010, and both functions are still everywhere as gates: the sigmoid in LSTM and GRU gates (RNNs and LSTMs), the GLU gate, and binary output heads, where a bounded output is exactly what you want.

ReLU: the switch that unlocked depth

The rectified linear unit \(\operatorname{ReLU}(x) = \max(0, x)\) has derivative 1 for \(x > 0\) and 0 for \(x < 0\). Nair and Hinton (2010) used it in restricted Boltzmann machines; Glorot, Bordes and Bengio (2011) showed deep rectifier networks trained well without unsupervised pre-training; and AlexNet (Krizhevsky, Sutskever and Hinton, 2012) reported that a four-layer convolutional network with ReLUs reached 25% training error on CIFAR-10 six times faster than the same network with tanh units.

Why it works:

  • No saturation on the active side. A gradient passing through an active ReLU is multiplied by exactly 1. Depth no longer means geometric shrinkage from the activation itself.
  • Sparsity. With zero-mean inputs about half the units output exactly zero, so each input activates a sparse subset of features, which tends to make representations more disentangled.
  • Positive homogeneity. \(\operatorname{ReLU}(ax) = a\operatorname{ReLU}(x)\) for \(a > 0\). Scaling the input scales the output, so the variance analysis behind He initialisation holds exactly at every scale.
  • Cost. A comparison and a select.

And what it breaks:

  • Dead units. A unit whose pre-activation is negative for every input gets zero gradient forever (the worked example showed one switched off for a single input). A too-large learning rate that knocks a bias strongly negative can kill a sizeable fraction of a layer. Lu et al. (2019) analyse how initialisation affects the probability of the whole network dying.
  • The kink at 0. The derivative jumps from 0 to 1, which makes the loss surface less smooth. It is rarely a practical problem, but smooth variants optimise slightly better at scale.
  • Non-zero mean. Outputs are non-negative, mean \(\approx 0.40\) for standard normal inputs, so the zig-zag argument partly returns; normalisation layers absorb it.

Dead ReLUs are a symptom, not a disease

If many units are dead at initialisation, your initialisation or input scaling is wrong. If they die during training, your learning rate is probably too high. Check the fraction of units that are zero for an entire batch, per layer, as Karpathy demonstrates in makemore part 3; fix the cause before swapping the activation.

The ReLU family: leaky, parametric, exponential

  • Leaky ReLU (Maas, Hannun and Ng, 2013): \(\max(\alpha x, x)\) with a small \(\alpha\) such as 0.01. Negative inputs keep a small gradient, so units cannot fully die.
  • PReLU (He et al., 2015): the same, with \(\alpha\) learned per channel. It was part of the first network reported to beat human-level error on ImageNet classification.
  • ELU (Clevert, Unterthiner and Hochreiter, 2015): \(x\) for \(x > 0\), \(\alpha(e^x - 1)\) otherwise. Smooth-ish, saturates gently to \(-\alpha\) for very negative inputs, which pushes the mean activation towards zero.
  • SELU (Klambauer et al., 2017): a scaled ELU, \(\lambda x\) or \(\lambda\alpha(e^x - 1)\) with \(\lambda \approx 1.0507\) and \(\alpha \approx 1.6733\), constants chosen so that mean 0, variance 1 is an attracting fixed point of the layer map. With the right initialisation (variance \(1/n\)) the network normalises itself without normalisation layers. Elegant, but fragile to architecture changes, and little used today.
  • Maxout (Goodfellow et al., 2013) takes the maximum of several linear functions; it generalises ReLU at the cost of several times the parameters.

GELU: a ReLU that weighs its input by how large it is

The Gaussian error linear unit (Hendrycks and Gimpel, 2016) is

\[ \operatorname{GELU}(x) = x\,\Phi(x), \]

where \(\Phi\) is the standard normal cumulative distribution function. It comes from a stochastic thought experiment: multiply the input by a random mask \(m \sim \operatorname{Bernoulli}(\Phi(x))\), so that larger inputs are more likely to be kept, and take the expectation, \(\mathbb{E}[m x] = x\Phi(x)\). Unlike ReLU, which gates by the sign of \(x\), GELU gates by how large \(x\) is relative to other inputs.

GELU(x) = x·Φ(x)Φ(x): keep-probabilityReLU (dashed)minimum −0.170 at x ≈ −0.75 03−41
GELU is the input times the probability that a standard normal falls below it. For large positive x it is ReLU; for large negative x it is 0; in between it lets small negative values through and is smooth everywhere.

Three properties matter in practice. It is smooth, with a continuous derivative \(\Phi(x) + x\varphi(x)\) (where \(\varphi\) is the normal density), so the loss surface has no kinks. It is non-monotone: it dips to a minimum of about \(-0.17\) at \(x \approx -0.75\), so small negative inputs carry (signed) information and receive gradient. And it is ReLU-like at scale, so most of ReLU's good properties survive. A common approximation, used in the original BERT and GPT-2 code, is \(0.5x\big(1 + \tanh\big(\sqrt{2/\pi}\,(x + 0.044715x^3)\big)\big)\); PyTorch exposes it as nn.GELU(approximate="tanh"). GELU became the default in BERT (Devlin et al., 2018), the GPT series and vision transformers.

SiLU / Swish: the self-gated input

\(\operatorname{SiLU}(x) = x\,\sigma(x)\) replaces GELU's normal CDF with the logistic sigmoid; the two curves are very close (GELU \(\approx x\sigma(1.702x)\)). It was named SiLU in the GELU paper, used for reinforcement learning by Elfwing, Uchibe and Doya (2017), and rediscovered as Swish, \(x\sigma(\beta x)\), by Ramachandran, Zoph and Le (2017) through an automated search over activation functions, which found that simple "self-gated" functions of this form consistently beat ReLU on deep models. Its minimum is about \(-0.278\) at \(x \approx -1.28\). As an activation by itself SiLU is common in efficient convolutional networks; its larger role today is as the gate inside SwiGLU.

Gated linear units: let one projection decide for the other

Dauphin et al. (2016) introduced the gated linear unit for convolutional language models:

\[ \operatorname{GLU}(\mathbf{x}) = (\mathbf{x}W + \mathbf{b}) \odot \sigma(\mathbf{x}V + \mathbf{c}). \]

Two linear projections of the same input; one passes through a sigmoid and acts as a soft, input-dependent switch on the other. Shazeer (2020) tried swapping the gate's nonlinearity inside a transformer's feed-forward block, \(\operatorname{FFN}(\mathbf{x}) = \big(\phi(\mathbf{x}W_1) \odot \mathbf{x}W_3\big)W_2\), and found that SwiGLU ($\phi = $ SiLU) and GeGLU ($\phi = $ GELU) gave the best perplexity among the variants tested in his T5 experiments, at equal parameter count. The paper's conclusion is famously modest: it offers "no explanation" for why these architectures seem to work, attributing their success "to divine benevolence".

The more mechanical explanation is that gating gives the layer multiplicative interactions: each hidden unit computes a product of two learned linear functions of the input, a quadratic form, before any further nonlinearity. A plain MLP has to approximate such products with many piecewise-linear pieces. Because a gated FFN has three weight matrices instead of two, the hidden width is cut to about \(\tfrac{8}{3}d\) to keep the parameter count equal (see the parameter question on the MLP page). PaLM (2022) and LLaMA (2023) adopted SwiGLU, and as of 2026 gated FFNs are the norm in large open-weight language models (the Gemma family uses GeGLU).

A SwiGLU feed-forward block
A SwiGLU feed-forward block. token vector x (d), gate branch x W₁  (d → h), value branch x W₃  (d → h), SiLU, elementwise ×, x W₂ (h → d) h ≈ 8d/3A SwiGLU feed-forward block. token vector x (d), gate branch x W₁  (d → h), value branch x W₃  (d → h), SiLU, elementwise ×, x W₂ (h → d) h ≈ 8d/3

Softmax, softplus and the rest

  • Softmax is an activation over a vector, \(\operatorname{softmax}(\mathbf{z})_i = e^{z_i}/\sum_j e^{z_j}\), used for categorical outputs and for attention weights (attention). Its temperature controls sharpness (decoding).
  • Softplus \(\log(1 + e^x)\) is a smooth ReLU whose derivative is the sigmoid; it is used where an output must be positive (a variance, a rate).
  • Squared ReLU \(\operatorname{ReLU}(x)^2\) was found by the Primer architecture search (So et al., 2021) to help transformer language models; it shows up in some efficiency-focused models.
  • Mish \(x\tanh(\operatorname{softplus}(x))\) is another smooth self-gated curve, popular in some object detectors.

What to use, as of 2026

Situation Default Why
Hidden layers of an MLP or CNN, from scratch ReLU (with He initialisation) cheap, robust, exact variance theory
Transformer encoders, ViTs GELU the convention since BERT; smooth
LLM feed-forward blocks SwiGLU (or GeGLU) better loss per parameter in published ablations
Gates (LSTM, GLU, attention gating) sigmoid bounded in \((0, 1)\)
Bounded hidden state (RNNs) tanh zero-centred, bounded
Outputs identity / sigmoid / softmax matched to the loss (MLP heads)

The differences between ReLU, GELU and SiLU in a well-normalised network are usually small, a few tenths of a percent or a small perplexity gain. Initialisation, normalisation and learning rate matter far more. Change activations last.

History

From firing rates to gates

1943–1958: the McCulloch–Pitts neuron and Rosenblatt's perceptron use a hard threshold. 1980s: backpropagation needs a derivative, so the threshold is smoothed into the sigmoid (Rumelhart, Hinton and Williams, 1986); tanh follows. 1991–1994: the vanishing-gradient problem is identified (Hochreiter; Bengio et al.). 1998: LeCun et al.'s Efficient BackProp recommends a scaled tanh. 2010–2011: ReLU succeeds in RBMs (Nair and Hinton) and deep supervised nets (Glorot, Bordes and Bengio). 2012: AlexNet makes ReLU standard. 2013–2017: leaky ReLU, PReLU, maxout, ELU, SELU. 2016: GELU and SiLU (Hendrycks and Gimpel); GLU (Dauphin et al.). 2017: Swish found by automated search. 2018: BERT adopts GELU. 2020: Shazeer's GLU variants; 2022–2023: PaLM and LLaMA make SwiGLU the LLM default.

First principles

Why must it be nonlinear and non-polynomial? Composition of affine maps is affine; composition of polynomials of bounded degree stays in a finite-dimensional space. Only a non-polynomial nonlinearity makes the function class dense (the MLP page).

Why does the derivative's size matter so much? Backprop's recursion multiplies by \(\operatorname{diag}(\phi'(\mathbf{z}))\) at every layer. If we keep the forward signal at unit variance with the right initialisation, the gradient's variance changes by a factor

\[ \chi = \frac{\mathbb{E}[\phi'(z)^2]}{\mathbb{E}[\phi(z)^2]}, \qquad z \sim \mathcal{N}(0, 1), \]

per layer (derived in the maths). Over \(L\) layers the gradient norm scales like \(\chi^{L/2}\). For the sigmoid \(\chi = 0.153\): after 30 layers, \(0.153^{15} \approx 6 \times 10^{-13}\). For ReLU, \(\chi = 1\) exactly, because \(\mathbb{E}[\operatorname{ReLU}(z)^2] = \mathbb{E}[\operatorname{ReLU}'(z)^2] = \tfrac12\). This single number explains most of the history above, and the code in Build it measures it in a real 30-layer network.

Why does positive homogeneity help? For ReLU, \(\mathbb{E}[\phi(\sqrt{q}z)^2] = q/2\) for any variance \(q\), so the right weight scale does not depend on the signal's current scale. For GELU and SiLU the curve is ReLU-like for large inputs but different near 0, so a weight scale that is exactly right at variance 1 is slightly wrong at other variances and the signal drifts. The measured run below shows exactly this; normalisation layers make it moot in practice.

Why smoothness? A smooth \(\phi\) gives a loss whose gradient changes continuously, which helps gradient methods with momentum and adaptive step sizes behave predictably, and gives second-order information that is not zero almost everywhere. It also means small negative pre-activations still receive gradient, so no unit is permanently dead.

Why gating? A gate turns an additive model into a multiplicative one. \(\phi(\mathbf{x}^\top\mathbf{w})(\mathbf{x}^\top\mathbf{v})\) can represent "feature A matters only when feature B is present" directly, while a plain MLP has to synthesise the product from many hinges. The same principle shows up in LSTM gates, attention (a softmax-weighted product) and mixture-of-experts routers (mixture of experts).

The maths

Definitions and derivatives (\(\sigma\) logistic sigmoid, \(\Phi\) and \(\varphi\) standard normal CDF and density):

Name \(\phi(x)\) \(\phi'(x)\) Range \(\phi'(0)\)
sigmoid \(\dfrac{1}{1 + e^{-x}}\) \(\sigma(x)(1 - \sigma(x))\) \((0, 1)\) 0.25
tanh \(\dfrac{e^x - e^{-x}}{e^x + e^{-x}}\) \(1 - \tanh^2 x\) \((-1, 1)\) 1
ReLU \(\max(0, x)\) \([x > 0]\) \([0, \infty)\) 0 (by convention)
leaky ReLU \(\max(\alpha x, x)\) \(1\) or \(\alpha\) \(\mathbb{R}\) \(\alpha\) or 1
ELU \(x\) or \(\alpha(e^x - 1)\) \(1\) or \(\alpha e^x\) \((-\alpha, \infty)\) 1 if \(\alpha = 1\)
GELU \(x\Phi(x)\) \(\Phi(x) + x\varphi(x)\) \([\approx -0.17, \infty)\) 0.5
SiLU \(x\sigma(x)\) \(\sigma(x)\big(1 + x(1 - \sigma(x))\big)\) \([\approx -0.28, \infty)\) 0.5
softplus \(\log(1 + e^x)\) \(\sigma(x)\) \((0, \infty)\) 0.5
Derivations of the sigmoid, tanh and SiLU derivatives

Sigmoid. \(\sigma(x) = (1 + e^{-x})^{-1}\), so \(\sigma'(x) = e^{-x}(1 + e^{-x})^{-2} = \sigma(x)\cdot\frac{e^{-x}}{1 + e^{-x}} = \sigma(x)(1 - \sigma(x))\). The maximum of \(p(1 - p)\) is at \(p = \tfrac12\), i.e. \(x = 0\), value \(\tfrac14\).

Tanh. \(\tanh x = 2\sigma(2x) - 1\), so \(\tanh'(x) = 4\sigma'(2x) = 4\sigma(2x)(1 - \sigma(2x))\). With \(\sigma(2x) = (1 + \tanh x)/2\) this is \((1 + \tanh x)(1 - \tanh x) = 1 - \tanh^2 x\).

SiLU. Product rule: \(\frac{d}{dx}x\sigma(x) = \sigma(x) + x\sigma(x)(1 - \sigma(x)) = \sigma(x)(1 + x(1 - \sigma(x)))\). Setting it to zero gives the minimum where \(1 + x(1 - \sigma(x)) = 0\), numerically \(x \approx -1.278\).

GELU. \(\frac{d}{dx}x\Phi(x) = \Phi(x) + x\varphi(x)\); the minimum solves \(\Phi(x) = -x\varphi(x)\), numerically \(x \approx -0.752\), \(\operatorname{GELU} \approx -0.170\).

Signal propagation: where χ comes from

Consider a wide layer \(z_j^{(\ell+1)} = \sum_{i=1}^{n} W_{ji}\,\phi(z_i^{(\ell)})\) with independent weights \(W_{ji} \sim \mathcal{N}(0, \sigma_w^2)\) and pre-activations \(z_i^{(\ell)} \sim \mathcal{N}(0, q)\) (the mean-field, infinite-width approximation).

Forward. \(\operatorname{Var}(z^{(\ell+1)}) = n\sigma_w^2\,\mathbb{E}[\phi(z)^2]\). Choosing \(\sigma_w^2 = 1/(n\,\mathbb{E}[\phi(z)^2])\) makes \(q = 1\) a fixed point. For ReLU, \(\mathbb{E}[\phi^2] = q/2\), giving \(\sigma_w^2 = 2/n\): He initialisation.

Backward. \(\partial L/\partial z_i^{(\ell)} = \phi'(z_i^{(\ell)})\sum_j W_{ji}\,\partial L/\partial z_j^{(\ell+1)}\), so (treating the backward weights as independent of the forward activations, the standard approximation)

\[ \operatorname{Var}\Big(\frac{\partial L}{\partial z^{(\ell)}}\Big) = n\sigma_w^2\,\mathbb{E}[\phi'(z)^2]\,\operatorname{Var}\Big(\frac{\partial L}{\partial z^{(\ell+1)}}\Big) = \underbrace{\frac{\mathbb{E}[\phi'(z)^2]}{\mathbb{E}[\phi(z)^2]}}_{\chi}\,\operatorname{Var}\Big(\frac{\partial L}{\partial z^{(\ell+1)}}\Big). \]

Over \(L\) layers the gradient variance scales as \(\chi^L\) and its norm as \(\chi^{L/2}\). Stable training at depth needs \(\chi \approx 1\). Schoenholz et al. (2016) and Poole et al. (2016) develop this "edge of chaos" theory fully, including correlations between inputs; the initialisation page builds on it.

Gaussian moments for the common activations (inputs \(z \sim \mathcal{N}(0,1)\), from the first snippet below): ReLU \(\mathbb{E}[\phi] = 1/\sqrt{2\pi} \approx 0.399\), \(\mathbb{E}[\phi^2] = 0.5\), \(\mathbb{E}[\phi'^2] = 0.5\); tanh \(0\), \(0.395\), \(0.464\); GELU \(0.283\), \(0.426\), \(0.456\); SiLU \(0.207\), \(0.356\), \(0.380\); sigmoid \(0.5\), \(0.294\), \(0.045\).

SELU's constants solve two equations: with \(z \sim \mathcal{N}(0, 1)\), \(\mathbb{E}[\operatorname{SELU}(z)] = 0\) and \(\mathbb{E}[\operatorname{SELU}(z)^2] = 1\), giving \(\alpha \approx 1.6733\) and \(\lambda \approx 1.0507\) (Klambauer et al., 2017, prove the fixed point is attracting).

Gated FFN. \(\operatorname{SwiGLU}(\mathbf{x}) = \big(\operatorname{SiLU}(\mathbf{x}W_1) \odot \mathbf{x}W_3\big)W_2\), \(W_1, W_3 \in \mathbb{R}^{d \times h}\), \(W_2 \in \mathbb{R}^{h \times d}\); \(3dh\) parameters, equal to a plain \(d \to 4d \to d\) MLP's \(8d^2\) when \(h = \tfrac{8}{3}d\).

Build it

First, the statistics that decide everything: for standard-normal pre-activations, each activation's mean, second moment, mean squared slope, fraction of zero gradients and minimum.

import numpy as np
from math import erf, sqrt, pi
Phi = np.vectorize(lambda x: 0.5 * (1 + erf(x / sqrt(2))))
sig = lambda x: 1 / (1 + np.exp(-x))
acts = {   # name: (f, f')
    "sigmoid": (sig, lambda x: sig(x) * (1 - sig(x))),
    "tanh":    (np.tanh, lambda x: 1 - np.tanh(x) ** 2),
    "ReLU":    (lambda x: np.maximum(x, 0), lambda x: (x > 0) * 1.0),
    "leaky":   (lambda x: np.where(x > 0, x, 0.01 * x), lambda x: np.where(x > 0, 1, 0.01)),
    "GELU":    (lambda x: x * Phi(x),
                lambda x: Phi(x) + x * np.exp(-x**2 / 2) / sqrt(2 * pi)),
    "SiLU":    (lambda x: x * sig(x), lambda x: sig(x) * (1 + x * (1 - sig(x)))),
}
z = np.random.default_rng(0).standard_normal(200_000)     # pre-activations ~ N(0, 1)
grid = np.linspace(-6, 6, 120_001)
print(f"{'':8} {'E[f]':>6} {'E[f^2]':>7} {'E[f_^2]':>8} {'f_ = 0':>7}   minimum")
for name, (f, df) in acts.items():
    a, g, fg = f(z), df(z), f(grid)
    i = fg.argmin()                                        # interior minimum = non-monotone
    low = f"{fg[i]:.3f} at x = {grid[i]:.2f}" if 0 < i < len(grid) - 1 else "none (monotone)"
    print(f"{name:8} {a.mean():6.3f} {np.mean(a**2):7.3f} {np.mean(g**2):8.3f} "
          f"{np.mean(g == 0):7.1%}   {low}")
           E[f]  E[f^2]  E[f_^2]  f_ = 0   minimum
sigmoid   0.500   0.294    0.045    0.0%   none (monotone)
tanh      0.000   0.395    0.464    0.0%   none (monotone)
ReLU      0.400   0.501    0.500   50.0%   none (monotone)
leaky     0.396   0.501    0.500    0.0%   none (monotone)
GELU      0.283   0.426    0.456    0.0%   -0.170 at x = -0.75
SiLU      0.207   0.356    0.380    0.0%   -0.278 at x = -1.28

(f_ is the derivative \(\phi'\).) Now the experiment the theory predicts: a 30-layer, 256-wide MLP per activation, each initialised so the forward variance starts at 1. Send a random gradient down from the top and measure how much of it reaches the bottom, against the prediction \(\chi^{L/2}\).

import numpy as np
from math import erf, sqrt, pi
erfv = np.vectorize(erf)
sig = lambda x: 1 / (1 + np.exp(-x))
acts = {   # name: (f, f')
    "sigmoid": (sig, lambda x: sig(x) * (1 - sig(x))),
    "tanh":    (np.tanh, lambda x: 1 - np.tanh(x) ** 2),
    "ReLU":    (lambda x: np.maximum(x, 0), lambda x: (x > 0) * 1.0),
    "GELU":    (lambda x: 0.5 * x * (1 + erfv(x / sqrt(2))),
                lambda x: 0.5 * (1 + erfv(x / sqrt(2))) + x * np.exp(-x**2 / 2) / sqrt(2 * pi)),
    "SiLU":    (lambda x: x * sig(x), lambda x: sig(x) * (1 + x * (1 - sig(x)))),
}
rng = np.random.default_rng(0)
z = rng.standard_normal(100_000)
n, L, B = 256, 30, 128
print(f"{'':8} {'chi':>6} {'chi^(L/2)':>10} {'measured':>9} {'std(z_L)':>9}")
for name, (f, df) in acts.items():
    m2, g2 = np.mean(f(z)**2), np.mean(df(z)**2)
    chi = g2 / m2                                 # backward variance gain per layer
    sw = 1 / np.sqrt(n * m2)                       # init that keeps Var(pre-activation) = 1
    Ws = [rng.normal(0, sw, (n, n)) for _ in range(L)]
    h, zs = rng.standard_normal((B, n)), []
    for W in Ws:                                   # forward: z = f(h_prev) W
        zs.append(h); h = f(h) @ W
    g = rng.standard_normal((B, n)); top = np.linalg.norm(g)
    for W, zp in zip(reversed(Ws), reversed(zs)):  # backward through the same layers
        g = (g @ W.T) * df(zp)
    print(f"{name:8} {chi:6.3f} {chi ** (L/2):10.1e} {np.linalg.norm(g)/top:9.1e} {zs[-1].std():9.2f}")
            chi  chi^(L/2)  measured  std(z_L)
sigmoid   0.153    5.9e-13   5.5e-13      1.09
tanh      1.178    1.2e+01   1.1e+01      1.01
ReLU      0.999    9.9e-01   9.8e-01      1.01
GELU      1.076    3.0e+00   7.3e+00      2.76
SiLU      1.069    2.7e+00   4.1e+01     11.35

Read the table row by row. The sigmoid network loses twelve orders of magnitude of gradient, exactly as \(\chi^{15}\) predicts: its bottom layers cannot learn. ReLU keeps the gradient at 0.98 of its size through 30 layers and the forward signal at unit scale. Tanh grows the gradient modestly (it operates in its curved region, where the slope-to-output ratio is above 1). GELU and SiLU match the prediction less well because their forward signal drifts upwards (std(z_L) 2.8 and 11.4): they are not homogeneous, so the weight scale that is right at variance 1 is too large once the signal grows and they start to behave like ReLU. That drift is one reason transformers pair them with normalisation layers (initialisation and normalisation).

Things to try

  • Increase L to 100. Which activations still pass gradient? Then initialise ReLU with sw = 1/sqrt(n) (the "LeCun" scale, ignoring the factor 2) and watch both the forward signal and the gradient shrink by about \(\sqrt{2}\) per layer.
  • Add leaky ReLU with \(\alpha = 0.2\). Print the weight scale the code picks, sw * sqrt(n), and check it against PyTorch's calculate_gain("leaky_relu", 0.2) \(= \sqrt{2/(1 + \alpha^2)}\). Then explain why its \(\chi\) is exactly 1, like ReLU's.
  • Train the spiral MLP from backpropagation with ReLU, tanh and SiLU and five hidden layers; plot loss curves. Then count, per layer, the units that are zero for every training example.
  • Implement SwiGLU in NumPy with \(d = 6\), \(h = 16\), and check its parameter count against a \(6 \to 24 \to 6\) MLP.
  • Find SELU's constants yourself: solve \(\mathbb{E}[\operatorname{SELU}(z)] = 0\), \(\mathbb{E}[\operatorname{SELU}(z)^2] = 1\) for \((\alpha, \lambda)\) with Monte Carlo and a root finder.

Check yourself

What is the maximum slope of the sigmoid, and what does that imply for a 10-layer sigmoid network?

0.25, at \(x = 0\). Ignoring the weights, the gradient reaching the first layer is multiplied by at most \(0.25^{10} \approx 10^{-6}\); in practice saturation makes it worse.

Why does a non-zero-centred activation make gradient descent zig-zag?

For a unit fed by activations \(h_i \ge 0\), \(\partial L/\partial w_i = \delta h_i\) has the same sign for every \(i\). In one update all its incoming weights must increase together or decrease together, so reaching a target where some go up and some go down takes a zig-zag path.

Why does ReLU have χ = 1 exactly, and what initialisation does that imply?

For \(z \sim \mathcal{N}(0, q)\), \(\mathbb{E}[\operatorname{ReLU}(z)^2] = q/2\) and \(\mathbb{E}[\operatorname{ReLU}'(z)^2] = P(z > 0) = 1/2\). With the forward variance held at 1 (by \(\sigma_w^2 = 2/n\), He initialisation), the backward gain \(n\sigma_w^2 \cdot \tfrac12 = 1\).

A colleague reports that 40% of the units in layer 3 of their ReLU network output zero for every example in the training set. What do you check?

These are dead units. Check the learning rate (too high is the usual cause), the initialisation and input scaling (are pre-activations mostly negative from the start?), and whether biases have drifted strongly negative. Remedies: lower learning rate or warm-up, proper He initialisation, normalisation before the activation, or leaky ReLU/GELU.

Explain GELU as an expected value. How does it differ from ReLU in what it gates on?

Multiply \(x\) by a mask \(m \sim \operatorname{Bernoulli}(\Phi(x))\); \(\mathbb{E}[mx] = x\Phi(x)\). ReLU keeps \(x\) if and only if \(x > 0\), gating on the sign; GELU keeps \(x\) with a probability that rises smoothly with \(x\), so slightly negative inputs pass partially and the function is smooth.

Why do LLM feed-forward blocks use a hidden width of about 8d/3 with SwiGLU instead of 4d?

SwiGLU has three weight matrices (\(W_1, W_3\) of \(d \times h\) and \(W_2\) of \(h \times d\)), so \(3dh\) parameters. Setting \(3dh = 8d^2\), the count of a plain \(4d\) MLP, gives \(h = 8d/3\): equal parameters and compute, so comparisons are fair.

Hard: why might a smooth activation like GELU optimise better than ReLU in a very large transformer, even though both pass gradient well?

Several reasons stack. The loss is smoother (continuous gradient), which suits momentum and adaptive optimisers with large learning rates; small negative pre-activations still get gradient, so no unit is permanently dead even after aggressive updates; and the non-monotone dip gives each unit a little more expressive freedom. None of these is decisive alone, and the measured gains are modest, which is why the choice is usually made by convention plus ablation, not theory.

Go deeper

Papers

Videos and lectures

Articles and documentation

Courses and books

  • Understanding Deep Learning — Simon Prince. Chapter 3 on ReLU networks as piecewise-linear functions, and the activation discussion in chapter 7.

Where this leads