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.
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 , with values between zero and one. Its derivative follows directly:
The last inequality follows from for . Equality occurs at , that is, . 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 and and satisfies
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 ,
If every activation is sigmoid and , the magnitude is at most . 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.
ReLU and inactive neurons
ReLU is . Its derivative is zero for and one for ; at there is no ordinary derivative. The function is convex and any value of 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.
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: for ; the derivative is on the negative side and one on the positive side. A convention is needed at zero.
- PReLU: returns if and if , and learns . Without constraints, need not remain in the previous interval; for the maximum-of-two-lines formula no longer describes that piecewise definition.
- ELU: if and if , with . Its negative-side slope is : 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 .
- 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: , with derivative . It can be negative on part of the negative side: SiLU is not monotone over all . The Swish family 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, for and for , 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 be the cumulative distribution function of the standard normal, with density . Exact GELU, introduced by Hendrycks and Gimpel, is
The derivative follows from the product rule and . Since is negative for , GELU is not monotone over the entire real line either. If , then and . This interprets the deterministic function as an average, not an instruction to sample a mask on every forward pass.
A common approximation uses
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.
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.
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))))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()]))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 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.
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))))npm run lab and open the connection link.Exercises
Step 1 of 3. What does differentiating the function give?
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):
passActivation changes both representation and local derivatives. Sigmoid and tanh saturate at the extremes; ReLU retains positive slope but can leave branches inactive; GELU is and has a distinct approximation. The total signal depends on the complete composition, including weights and data.