Module contents
Lesson 4 of 22Core 75 min

Activation functions: sigmoid, tanh, ReLU, GELU and relatives

Compare sigmoid, tanh, ReLU and its variants, SiLU and GELU through their shapes, derivatives, saturation and numerical behavior.

After this lesson you can

  • Derive derivatives of sigmoid, tanh, ReLU, SiLU and GELU, expressing them in terms of their outputs where possible.
  • Explain saturation and how σ'(z) ≤ 1/4 limits gradient flow in deep sigmoid networks.
  • Diagnose inactive ReLU neurons and reason about variants that mitigate the problem.
  • Derive GELU as x·Φ(x), its tanh approximation and its interpretation as an expected stochastic mask.
  • Choose an activation for an architecture and explain centered versus noncentered activations.

Before you start

The valve between layers

In the previous lesson’s MLP, affine layers without activations collapse into one. An activation does more than break that restriction: each of its derivatives multiplies the signal propagated backward. If a neuron receives a value far from the region where its output changes, it may transmit a tiny signal even when its output looks perfectly reasonable.

InteractiveA function and its slope
Activation f(z)f(z)
Derivative f′(z)f'(z) and small slope
  • Sigmoid
  • ReLU
  • Exact GELU
Thick strokes indicate ∣f′(z)∣≤ε|f'(z)|\le\varepsilon on a grid with spacing 0.04; horizontal dashed lines mark ±ε\pm\varepsilon. The sigmoid's slope never exceeds 0.25. This local criterion also detects isolated stationary points, which are not necessarily saturation regions. At zero, ReLU and Leaky ReLU have no ordinary derivative. For GELU the normal density is numerically integrated using Simpson's rule.
1.00
0.10
Sigmoidf(z) = 0.731; f′(z) = 0.197
ReLUf(z) = 1.000; f′(z) = 1.000
Exact GELUf(z) = 0.841; f′(z) = 1.083
Select activations and move the point. The threshold marks where derivative magnitude is small; compare values and slopes before discussing saturation.

A saturated function has a small slope in the region considered; observing a small output is insufficient. A small output can have a large slope, and a large output can have an almost zero slope. In many-layer networks, local derivatives combine with weight matrices: the complete gradient cannot be judged from one activation alone.

Sigmoid and tanh

The sigmoid activation is σ(z)=1/(1+e−z)\sigma(z)=1/(1+e^{-z}), with values between zero and one. Its derivative follows directly:

σ′(z)=e−z(1+e−z)2=σ(z)(1−σ(z))≤14.\sigma'(z)=\frac{e^{-z}}{(1+e^{-z})^2}=\sigma(z)(1-\sigma(z))\le\frac14.

The last inequality follows from p(1−p)=1/4−(p−1/2)2p(1-p)=1/4-(p-1/2)^2 for p∈(0,1)p\in(0,1). Equality occurs at p=1/2p=1/2, that is, z=0z=0. The slope approaches zero at both extremes. Sigmoid serves as a Bernoulli output probability or a gate, but a deep chain can multiply many small factors.

The tanh activation takes values between −1-1 and 11 and satisfies

tanh⁡z=2σ(2z)−1,ddztanh⁡z=1−tanh⁡2z.\tanh z=2\sigma(2z)-1,\qquad \frac{d}{dz}\tanh z=1-\tanh^2 z.

Its maximum slope is one at the origin and also approaches zero at the extremes. It is odd: if the input distribution is symmetric about zero and expectation exists, the output has zero mean. An arbitrary input does not guarantee that mean. Sigmoid output is positive, while tanh admits both signs; “centered” describes range and symmetry, not an automatic promise about each batch.

Saturation matters because of the chain rule. In a scalar chain hℓ=ϕ(wℓhℓ−1+bℓ)h_\ell=\phi(w_\ell h_{\ell-1}+b_\ell),

∂hL∂h0=∏ℓ=1Lwℓϕ′(zℓ).\frac{\partial h_L}{\partial h_0}=\prod_{\ell=1}^{L} w_\ell\phi'(z_\ell).

If every activation is sigmoid and ∣wℓ∣≤1\abs{w_\ell}\le1, the magnitude is at most (1/4)L(1/4)^L. Without that weight assumption the full product has no such bound: large weights can amplify it. Vector networks involve matrix products and their directions, not just one scalar.

InteractiveDerivatives through depth
  • Accumulated product
  • Last nonzero value

We compute hᵢ = φ(w hᵢ₋₁ + b) and its derivative as a product of w φ′ at each layer. The plot clips the logarithm to [−40, 20]; if a factor is exactly zero, the line ends because log₁₀(0) is not finite. At the origin, the derivative is taken as 0 for ReLU and 0.1 for Leaky ReLU. Weights can offset or amplify local derivatives, and ReLU preserves the gradient only with suitable weights and positive preactivations.

Activation
20
1.0
0.0
1.0
Final output0.6590
Last activation derivative0.2247
Total derivative+10^−13.04
Explore a scalar chain with shared weight and bias. For positive ReLU, try weight one and then a different weight; for sigmoid observe each factor's contribution to the total derivative.

ReLU and inactive neurons

ReLU is ReLU⁡(z)=max⁡(0,z)\relu(z)=\max(0,z). Its derivative is zero for z<0z<0 and one for z>0z>0; at z=0z=0 there is no ordinary derivative. The function is convex and any value of [0,1][0,1] is a valid subgradient there. Many implementations, including this lesson’s convention, choose zero. Exact zeros can occur in discrete computation, so the convention should be documented.

ReLU does not saturate above: on the positive half-line it retains slope one and requires only comparison with zero. On the negative side it produces exactly zero activation, which can create sparse representations. Neither slope one nor sparsity guarantees that a deep network preserves its gradient: weight products and activation patterns still matter.

A dead ReLU is a unit that stops activating for relevant inputs and receives no gradient through its branch. Seeing only zeros in one batch does not prove it remains inactive: other data or changes in preceding layers may move its preactivations. Nor does it guarantee all model parameters stop learning: other units and an output bias can still receive gradients.

InteractiveActive and inactive ReLUs during SGD
Each row is a neuron and each column a state, every 5 steps. The line marks the selected step.
  • Active in minibatch
  • Inactive in that minibatch
  • Inactive across dataset
Inactive fraction among 64 neurons
Training steps

A 1 → 64 → 1 network is trained to approximate sin(πx), with 128 fixed inputs between −1 and 1, batches of 16, mean squared loss divided by 2, and SGD. The displayed minibatch was used in the last step and evaluated after the update; at step 0 the first is shown. The gray curve includes the red units. Currently 4.7 % are inactive across the dataset.

For this first layer, with fixed inputs, SGD without momentum or regularization and zero derivative at the corner, a red neuron no longer updates its incoming weights or bias: it remains inactive on this dataset. A gray minibatch can become active again. This does not guarantee inactivity for inputs outside [−1, 1], or with other optimizers or learned inputs. The seed is 42 and changing controls repeats the same batch sequence.

0.3
0.0
200
Available step200
Inactive across dataset3 / 64
Inactive in minibatch4 / 64
Training loss0.0771
Change initial bias and learning rate. Distinguish minibatch inactivity from inactivity across the whole fixed dataset; the latter is absorbing only under the figure's stated assumptions.

To diagnose a real network, record each unit’s zero fraction over representative data and how it evolves; compare training and validation and inspect gradients and preactivation distributions. Adjusting initialization or learning rate and using nonzero negative slopes are possible interventions, not universal guarantees. Lu and colleagues analyze specific assumptions about depth and initialization; an inactive batch is not proof of permanent death.

Variants with and without negative-side slope

ReLU variants modify the negative side:

  • Leaky ReLU: max⁡(z,az)\max(z,az) for 0<a<10<a<1; the derivative is aa on the negative side and one on the positive side. A convention is needed at zero.
  • PReLU: returns zz if z>0z>0 and azaz if z≤0z\le0, and learns aa. Without constraints, aa need not remain in the previous interval; for a>1a>1 the maximum-of-two-lines formula no longer describes that piecewise definition.
  • ELU: zz if z>0z>0 and a(ez−1)a(e^z-1) if z≤0z\le0, with a>0a>0. Its negative-side slope is aezae^z: it avoids an exactly flat negative region, but can be very small far from the origin. At zero the one-sided derivatives agree only if a=1a=1.
  • SELU: multiplies a parameterized ELU by a scaling factor. Its self-normalization analysis depends on assumptions about initialization, architecture and distribution; it does not justify removing any normalization from any network. See Self-Normalizing Neural Networks.
  • SiLU or Swish with parameter one: zσ(z)z\sigma(z), with derivative σ(z)+zσ(z)(1−σ(z))\sigma(z)+z\sigma(z)(1-\sigma(z)). It can be negative on part of the negative side: SiLU is not monotone over all R\R. The Swish family zσ(βz)z\sigma(\beta z) was studied through activation-function search by Ramachandran and colleagues; its result depends on architecture and task.

Leaky ReLU and PReLU with nonzero negative-side slope permit a nonzero local signal for negative inputs. This does not prevent every gradient problem or imply that the neuron will learn something useful. The choice also depends on numerical stability, hardware, initialization and the model to reproduce.

In SELU, SELU⁡(z)=λz\operatorname{SELU}(z)=\lambda z for z>0z>0 and λα(ez−1)\lambda\alpha(e^z-1) for z≤0z\le0, with positive constants fixed by architecture design. The original work analyzes mean and variance propagation under specific conditions; correlations, residual connections or different initialization can change that behavior. Activation mean and variance also do not alone determine all gradient behavior.

As a starting point for a new architecture, ReLU is a simple option in MLPs and CNNs, while GELU and SiLU are smooth alternatives whose cost and behavior should be measured on the task. There is no universal winner: Glorot and colleagues study rectifiers in specific networks, and the Swish paper compares specific architectures. Among transformers, BERT uses GELU; other families use different activations or gated products. When loading existing weights, preserve the exact function and implementation variant and check the loss before changing it.

GELU as an expectation

Let Φ\Phi be the cumulative distribution function of the standard normal, with density φ(z)=e−z2/2/2π\varphi(z)=e^{-z^2/2}/\sqrt{2\pi}. Exact GELU, introduced by Hendrycks and Gimpel, is

GELU⁡(z)=zΦ(z),GELU⁡′(z)=Φ(z)+zφ(z).\operatorname{GELU}(z)=z\Phi(z),\qquad \operatorname{GELU}'(z)=\Phi(z)+z\varphi(z).

The derivative follows from the product rule and Φ′=φ\Phi'=\varphi. Since zφ(z)z\varphi(z) is negative for z<0z<0, GELU is not monotone over the entire real line either. If M∣z∼Bern⁡(Φ(z))M\mid z\sim\Bern(\Phi(z)), then E[zM∣z]=zΦ(z)\E[zM\mid z]=z\Phi(z) and Var⁡(zM∣z)=z2Φ(z)(1−Φ(z))\Var(zM\mid z)=z^2\Phi(z)(1-\Phi(z)). This interprets the deterministic function as an average, not an instruction to sample a mask on every forward pass.

A common approximation uses

GELU⁡tanh⁡(z)=z2[1+tanh⁡ ⁣(2π (z+0.044715z3))].\operatorname{GELU}_{\tanh}(z)=\frac z2\left[1+\tanh\!\left(\sqrt{\frac2\pi}\,(z+0.044715z^3)\right)\right].

Its value differs from exact GELU. When reproducing a checkpoint use the variant expected by its implementation: PyTorch documents both. GELU appears, for example, in BERT; not all transformers use the same activation.

InteractiveGELU as a mask average

For each xx, take Bj(x)=1[Uj<Φ(x)]B_j(x)=\mathbf{1}[U_j<\Phi(x)] with UjU_j uniform on [0,1)[0,1). Each mask is Bernoulli with probability Φ(x)\Phi(x) and the mean of xBj(x)xB_j(x) estimates xΦ(x)x\Phi(x).

A random mean and its expectation
  • GELU
  • Mean of masks
  • Tanh approximation

The same uniform draws are reused at every x, so estimates at different points are correlated. Increasing N keeps the previous sequence; the error of a realization need not decrease at every step.

Error of the tanh approximation

On the 401-point grid over [−5, 5], the maximum absolute error is 0.000473. The plot multiplies it by 1000: its maximum is 0.473, at x = 2.700.

The maximum is searched only on the grid; this does not prove the continuous maximum. To draw Φ\Phi, the normal density is numerically integrated using 64 Simpson subintervals.

1.0
32
Probability Φ(x)\Phi(x)84.13 %
Active masks28 / 32
Mean of xBxB0.8750
Computed GELU0.8413
Theoretical standard error0.0646
Seed2026
Increase Bernoulli samples and compare their average with GELU. The figure also compares the tanh formula; the maximum is measured on the stated grid, not the entire real line.

Lab: derivatives and propagation

First implement six functions and their derivatives. SciPy’s CDF avoids a manual normal approximation; form expit evaluates sigmoid stably. The chosen derivative at zero for ReLU is zero and for Leaky ReLU it is the negative-side slope. Finite differences for functions with corners should be tested away from them.

[ ]Six activations and derivativesBrowser
import numpy as np
from scipy.special import expit, ndtr

def activation(z, name):
    z = np.asarray(z, dtype=float)
    s = expit(z)
    if name == 'sigmoid': return s, s*(1-s)
    if name == 'tanh':
        h = np.tanh(z)
        return h, 1-h*h
    if name == 'relu': return np.maximum(z, 0), (z > 0).astype(float)
    if name == 'leaky': return np.where(z > 0, z, 0.1*z), np.where(z > 0, 1., 0.1)
    if name == 'silu': return z*s, s + z*s*(1-s)
    if name == 'gelu':
        density = np.exp(-z*z/2) / np.sqrt(2*np.pi)
        return z*ndtr(z), ndtr(z) + z*density
    raise ValueError(name)

names = ['sigmoid', 'tanh', 'relu', 'leaky', 'silu', 'gelu']
x = np.array([-2.3, -0.7, 0.4, 1.8])
eps = 1e-5
for name in names:
    value, derivative = activation(x, name)
    finite = (activation(x+eps, name)[0] - activation(x-eps, name)[0]) / (2*eps)
    print(name, 'error máximo diferencias finitas', float(np.max(np.abs(derivative-finite))))
[ ]GELU at one and approximation on a gridBrowser
one = 1.0
exact = one * ndtr(one)
approx = one/2 * (1 + np.tanh(np.sqrt(2/np.pi) * (one + 0.044715*one**3)))
grid = np.linspace(-5, 5, 10001)
approx_grid = grid/2 * (1 + np.tanh(np.sqrt(2/np.pi) * (grid + 0.044715*grid**3)))
err = np.abs(grid*ndtr(grid) - approx_grid)
print('GELU(1), tanh, diferencia', exact, approx, abs(exact-approx))
print('máximo en malla [-5,5]', float(err.max()), 'en', float(grid[err.argmax()]))
[ ]Twenty layers with the same set of weightsBrowser
rng = np.random.default_rng(17)
batch, width, layers = 256, 64, 20
X = rng.normal(size=(batch, width))
weights = [rng.normal(size=(width, width)) * np.sqrt(2/width) for _ in range(layers)]
for name in names:
    h = X.copy()
    stats = []
    for W in weights:
        z = h @ W
        h, derivative = activation(z, name)
        inactive_units = np.mean(np.all(z <= 0, axis=0)) if name == 'relu' else np.nan
        stats.append((h.std(), np.mean(np.abs(derivative) < 0.01), inactive_units))
    print(name, 'desviación primera/última', np.round([stats[0][0], stats[-1][0]], 4),
          'fracción pendiente pequeña primera/última', np.round([stats[0][1], stats[-1][1]], 4))
    if name == 'relu':
        print('ReLU: unidades inactivas en todo el lote, primera/última', np.round([stats[0][2], stats[-1][2]], 4))

The same set of matrices allows comparison for this realization, not determination of the best initialization for each activation. Threshold 0.010.01 operationally defines “small slope” in this measurement; for ReLU it counts example-neuron pairs with negative or zero preactivation, while for smooth functions it does not mean permanent death. The additional readout counts neurons inactive for this entire batch, a different question that also does not establish inactivity for all future inputs. Activation deviation is not the gradient norm: it measures another property.

The next cell compares values and derivatives of all six functions with PyTorch on CPU, using exact GELU. It runs locally because PyTorch is unavailable in the browser.

[ ]Compare with PyTorch autogradLocal GPU
import numpy as np
import torch
import torch.nn.functional as F
from scipy.special import expit, ndtr

z_np = np.array([-2.3, -0.7, 0.4, 1.8], dtype=np.float64)
s = expit(z_np)
phi = np.exp(-z_np**2/2) / np.sqrt(2*np.pi)
reference = {
    'sigmoid': (s, s*(1-s)),
    'tanh': (np.tanh(z_np), 1-np.tanh(z_np)**2),
    'relu': (np.maximum(z_np, 0), (z_np > 0).astype(float)),
    'leaky': (np.where(z_np > 0, z_np, 0.1*z_np), np.where(z_np > 0, 1., 0.1)),
    'silu': (z_np*s, s + z_np*s*(1-s)),
    'gelu': (z_np*ndtr(z_np), ndtr(z_np) + z_np*phi),
}
functions = {'sigmoid': torch.sigmoid, 'tanh': torch.tanh, 'relu': F.relu,
             'leaky': lambda q: F.leaky_relu(q, negative_slope=0.1),
             'silu': F.silu, 'gelu': lambda q: F.gelu(q, approximate='none')}
for name, fn in functions.items():
    z = torch.tensor(z_np, requires_grad=True)
    out = fn(z)
    out.sum().backward()
    expected, derivative = reference[name]
    print(name, 'error valor y derivada', float(np.max(np.abs(out.detach().numpy()-expected))),
          float(np.max(np.abs(z.grad.numpy()-derivative))))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofThe maximum slope
Prove: Show that σ′(z) = σ(z)(1 − σ(z)) and does not exceed 1/4.
0
Let σ(z)=1/(1+e^(−z)) for real z.

Step 1 of 3. What does differentiating the function give?

NumericTwo GELUs at z=1
Calculate the absolute difference between exact GELU and the lesson's tanh approximation at z=1.
QuizWhat has stopped?
A hidden ReLU layer produces negative preactivations for every example in a batch. Under the zero-derivative convention, what follows for that step?
CodeGELU and its derivative
Implement gelu_and_grad(x) with the normal CDF expressed using scipy.special.erf. Accept a NumPy array and return the exact value and derivative.
import numpy as np
from scipy.special import erf

def gelu_and_grad(x):
  pass
Shift+Enter to run
Key idea

Activation changes both representation and local derivatives. Sigmoid and tanh saturate at the extremes; ReLU retains positive slope but can leave branches inactive; GELU is zΦ(z)z\Phi(z) and has a distinct approximation. The total signal depends on the complete composition, including weights and data.