Activation Functions
The previous lesson showed that without an activation a deep network collapses into one linear layer. Any nonlinear function would break the collapse, so why do frameworks ship a dozen of them? Because the activation also decides how gradients flow backwards. Each layer multiplies the incoming gradient by , so an activation whose slope is tiny over most of its range starves the layers below it of signal, and one whose slope is exactly zero can switch neurons off for good.
This lesson implements the common activations and their derivatives in NumPy, measures saturation and dead units on a real layer, and checks the implementations against torch.nn.functional. The shapes, the history and the derivations of these functions are in Activation Functions in the Mathematics track; here we care about what they do inside a network.
The functions and their slopes
With and the standard normal CDF:
| Name | Range | ||
|---|---|---|---|
| sigmoid | , at most | ||
| tanh | , at most | ||
| ReLU | for , for | ||
| Leaky ReLU | if , else | or (often ) | |
| ELU | if , else | or | |
| GELU | about | ||
| SiLU (Swish) | about |
ReLU is not differentiable at 0; frameworks simply use . GELU is often computed with a tanh approximation, , which is what the original GPT-2 code used.
The figure shows the key difference. Sigmoid and tanh flatten out on both sides: for their slopes are below 0.05 and 0.01. ReLU and its smooth cousins GELU and SiLU keep slope 1 for large positive inputs, so the gradient passes through unchanged. GELU and SiLU are smooth, are slightly negative for negative inputs and have a small dip below zero in the derivative.
Softmax is different: it is not applied elementwise but to a whole vector, and it is used as the output of a classifier rather than inside a network:
Subtracting the maximum changes nothing mathematically and prevents from overflowing (overflow and softmax). The next lesson pairs it with its loss.
All of them in NumPy
The table at five points, the derivatives, a check of every derivative against a central difference, the size of the GELU approximation error, and a stable softmax:
import numpy as np
from scipy.special import erf
sigmoid = lambda x: 1 / (1 + np.exp(-x))
acts = { # name: (f, f')
"sigmoid": (sigmoid, lambda x: sigmoid(x) * (1 - sigmoid(x))),
"tanh": (np.tanh, lambda x: 1 - np.tanh(x) ** 2),
"relu": (lambda x: np.maximum(0, x), 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, 0.01)),
"elu": (lambda x: np.where(x > 0, x, np.expm1(x)), lambda x: np.where(x > 0, 1.0, np.exp(x))),
"gelu": (lambda x: x * 0.5 * (1 + erf(x / np.sqrt(2))),
lambda x: 0.5 * (1 + erf(x / np.sqrt(2))) + x * np.exp(-x ** 2 / 2) / np.sqrt(2 * np.pi)),
"silu": (lambda x: x * sigmoid(x), lambda x: sigmoid(x) * (1 + x * (1 - sigmoid(x)))),
}
xs = np.array([-3.0, -1.0, 0.0, 1.0, 3.0])
print("x " + "".join(f"{v:>8.1f}" for v in xs))
for name, (f, df) in acts.items():
print(f"{name:8s} " + "".join(f"{v:8.4f}" for v in f(xs)))
print("derivatives")
for name, (f, df) in acts.items():
print(f"{name:8s} " + "".join(f"{v:8.4f}" for v in df(xs)))
# check every derivative against a central difference (away from the kink at 0)
grid = np.linspace(-4, 4, 801); grid = grid[np.abs(grid) > 1e-3]
h = 1e-6
worst = max(float(np.abs((f(grid + h) - f(grid - h)) / (2 * h) - df(grid)).max()) for f, df in acts.values())
print("largest derivative error:", f"{worst:.1e}")
gelu_tanh = lambda x: 0.5 * x * (1 + np.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 * x ** 3)))
print("max |gelu - gelu_tanh| on [-4, 4]:", f"{float(np.abs(acts['gelu'][0](grid) - gelu_tanh(grid)).max()):.5f}")
def softmax(z):
e = np.exp(z - z.max(axis=-1, keepdims=True)) # shift: same result, no overflow
return e / e.sum(axis=-1, keepdims=True)
z = np.array([2.0, 1.0, 0.1])
print("softmax", np.round(softmax(z), 4).tolist(), " sum", round(float(softmax(z).sum()), 6))
print("softmax(z + 100) equal:", bool(np.allclose(softmax(z + 100), softmax(z))))x -3.0 -1.0 0.0 1.0 3.0
sigmoid 0.0474 0.2689 0.5000 0.7311 0.9526
tanh -0.9951 -0.7616 0.0000 0.7616 0.9951
relu 0.0000 0.0000 0.0000 1.0000 3.0000
leaky -0.0300 -0.0100 0.0000 1.0000 3.0000
elu -0.9502 -0.6321 0.0000 1.0000 3.0000
gelu -0.0040 -0.1587 0.0000 0.8413 2.9960
silu -0.1423 -0.2689 0.0000 0.7311 2.8577
derivatives
sigmoid 0.0452 0.1966 0.2500 0.1966 0.0452
tanh 0.0099 0.4200 1.0000 0.4200 0.0099
relu 0.0000 0.0000 0.0000 1.0000 1.0000
leaky 0.0100 0.0100 0.0100 1.0000 1.0000
elu 0.0498 0.3679 1.0000 1.0000 1.0000
gelu -0.0119 -0.0833 0.5000 1.0833 1.0119
silu -0.0881 0.0723 0.5000 0.9277 1.0881
largest derivative error: 5.7e-10
max |gelu - gelu_tanh| on [-4, 4]: 0.00047
softmax [0.659, 0.2424, 0.0986] sum 1.0
softmax(z + 100) equal: True
Read the derivative rows at . Sigmoid passes on 0.0452 of the gradient and tanh only 0.0099, while ReLU, Leaky ReLU and ELU pass 1 for positive inputs. Even at its best () a sigmoid passes 0.25, so a chain of ten sigmoid layers multiplies the gradient by at most ; this is the classic vanishing gradient problem. GELU at has slope , which ReLU (slope 0) would not have. The tanh approximation of GELU differs from the exact form by at most 0.00047 on , which is why both are used interchangeably, though a model must be run with the variant it was trained with. Softmax gives probabilities 0.659, 0.2424, 0.0986 that sum to 1, unchanged when 100 is added to every logit.
Saturation and dead units on a real layer
The derivatives above are about single numbers. In a network, what matters is where the pre-activations of a layer actually fall on real data. The example feeds the 1797 Digits images into a layer of 100 units, first with raw pixels 0 to 16 and then scaled to , and counts the sigmoid units whose slope is below 0.01. Then it does the same for ReLU after an update has pushed all biases down by 1, 2 or 3, and counts dead units: units whose output is 0 for every one of the 1797 inputs. A dead unit receives zero gradient on every example, so gradient descent can never revive it.
import numpy as np
from sklearn.datasets import load_digits
X, y = load_digits(return_X_y=True) # 1797 x 64, raw pixels 0..16
rng = np.random.default_rng(0)
W = rng.normal(0, np.sqrt(1 / 64), (64, 100)) # 100 sigmoid units, weights ~ N(0, 1/64)
sig = lambda a: 1 / (1 + np.exp(-a))
for name, Xin in [("raw 0..16", X), ("scaled 0..1", X / 16)]:
s = sig(Xin @ W)
d = s * (1 - s)
print(f"sigmoid, inputs {name:11s}: mean |pre-act| {float(np.abs(Xin @ W).mean()):6.2f}, "
f"saturated (f' < 0.01): {float((d < 0.01).mean()):.3f}, mean f' {float(d.mean()):.4f}")
# dead ReLUs: a unit that outputs 0 for every training input gets no gradient at all
Xs = X / 16
W = rng.normal(0, np.sqrt(2 / 64), (64, 100)) # He init for ReLU
for shift in [0.0, -1.0, -2.0, -3.0]:
A = Xs @ W + shift # biases pushed down by an update
dead = (A <= 0).all(axis=0)
print(f"bias {shift:4.1f}: zero outputs {float((A <= 0).mean()):.3f}, dead units {int(dead.sum()):3d}/100, "
f"units with a gradient: ReLU {100 - int(dead.sum()):3d}, Leaky ReLU 100")sigmoid, inputs raw 0..16 : mean |pre-act| 6.05, saturated (f' < 0.01): 0.532, mean f' 0.0532
sigmoid, inputs scaled 0..1: mean |pre-act| 0.38, saturated (f' < 0.01): 0.000, mean f' 0.2371
bias 0.0: zero outputs 0.474, dead units 2/100, units with a gradient: ReLU 98, Leaky ReLU 100
bias -1.0: zero outputs 0.940, dead units 37/100, units with a gradient: ReLU 63, Leaky ReLU 100
bias -2.0: zero outputs 0.999, dead units 95/100, units with a gradient: ReLU 5, Leaky ReLU 100
bias -3.0: zero outputs 1.000, dead units 100/100, units with a gradient: ReLU 0, Leaky ReLU 100
With raw pixels the pre-activations have mean magnitude 6.05 and 53.2 % of the sigmoid outputs are saturated; the average slope is 0.0532. Scaling the inputs to brings the mean magnitude to 0.38, no unit saturates and the average slope is 0.2371, near the maximum of 0.25. Input scaling is an activation issue as much as an optimisation one.
For ReLU, even the freshly initialised layer has 2 dead units out of 100: their random weights happen to be negative on the pixels that are ever bright, so they output 0 for all 1797 images. Lowering the biases by 1 kills 37 units and by 2 kills 95; at 3 the whole layer is dead. A learning rate that is too high can do exactly this in a single step, and the loss then stops improving for no visible reason. Leaky ReLU keeps slope on the negative side, so all 100 units still receive a gradient and can recover. ELU, GELU and SiLU also have nonzero slope for moderately negative inputs.
Checked against PyTorch
The torch.nn.functional versions (also available as modules such as nn.GELU() for nn.Sequential) should give the same values, and autograd's slopes should match the numerical derivatives. A recorded example, float64, on 1200 points in :
import numpy as np
import torch
import torch.nn.functional as F
from scipy.special import erf
sig = lambda x: 1 / (1 + np.exp(-x))
mine = {
"sigmoid": (sig, torch.sigmoid),
"tanh": (np.tanh, torch.tanh),
"relu": (lambda x: np.maximum(0, x), F.relu),
"leaky_relu": (lambda x: np.where(x > 0, x, 0.01 * x), lambda t: F.leaky_relu(t, 0.01)),
"elu": (lambda x: np.where(x > 0, x, np.expm1(x)), F.elu),
"gelu": (lambda x: x * 0.5 * (1 + erf(x / np.sqrt(2))), F.gelu),
"gelu_tanh": (lambda x: 0.5 * x * (1 + np.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 * x ** 3))),
lambda t: F.gelu(t, approximate="tanh")),
"silu": (lambda x: x * sig(x), F.silu),
}
x = np.linspace(-6, 6, 1201)
x = x[np.abs(x) > 1e-3] # keep away from the kink at 0
for name, (f_np, f_t) in mine.items():
t = torch.tensor(x, requires_grad=True) # float64
out = f_t(t)
out.sum().backward() # d out_i / d x_i, elementwise
h = 1e-6
num = (f_np(x + h) - f_np(x - h)) / (2 * h)
print(f"{name:10s} value match: {bool(np.allclose(out.detach().numpy(), f_np(x), atol=1e-12))} "
f"slope match: {bool(np.allclose(t.grad.numpy(), num, atol=1e-6))}")
z = torch.tensor([[2.0, 1.0, 0.1]], dtype=torch.float64)
print("F.softmax:", [round(v, 4) for v in F.softmax(z, dim=1)[0].tolist()],
" log_softmax:", [round(v, 4) for v in F.log_softmax(z, dim=1)[0].tolist()])
print("nn modules:", torch.nn.GELU(), torch.nn.LeakyReLU(0.01), torch.nn.SiLU())sigmoid value match: True slope match: True
tanh value match: True slope match: True
relu value match: True slope match: True
leaky_relu value match: True slope match: True
elu value match: True slope match: True
gelu value match: True slope match: True
gelu_tanh value match: True slope match: True
silu value match: True slope match: True
F.softmax: [0.659, 0.2424, 0.0986] log_softmax: [-0.417, -1.417, -2.317]
nn modules: GELU(approximate='none') LeakyReLU(negative_slope=0.01) SiLU()
Every value and every slope matches. Note the defaults: F.gelu is the exact erf form (approximate='none'), and F.leaky_relu uses slope 0.01 unless you pass another. The softmax probabilities are the same three numbers as in NumPy, and F.log_softmax returns their logarithms, computed stably (the next lesson explains why you want it).
Which one where
| Where | Usual choice | Why |
|---|---|---|
| Hidden layers of MLPs and CNNs | ReLU | cheap, slope 1 for positive inputs, works with He initialisation |
| Transformers | GELU (BERT, GPT-2) or SiLU inside SwiGLU (LLaMA-style) | smooth, small negative region, empirically a little better |
| When many ReLUs die | Leaky ReLU or ELU | nonzero slope for negative inputs |
| Gates in LSTMs, GRUs, attention-style gating | sigmoid | an output in means "how much to let through" |
| Recurrent state, bounded outputs | tanh | zero-centred and bounded in |
| Output layer | none, sigmoid or softmax, chosen by the task | see output layers and losses |
Sigmoid and tanh are no longer used as the main hidden activation of deep feed-forward networks: they saturate, and sigmoid's outputs are all positive, which biases the gradients of the next layer's weights in one direction.
Pitfalls
- Unscaled inputs into saturating units. The 53.2 % saturation above came from nothing but raw pixel values. Standardise or rescale inputs before the first layer.
- Applying softmax or sigmoid twice. PyTorch's classification losses take logits and apply the output function themselves. An extra softmax in the model still trains, badly, without an error.
- Mismatched GELU variants. Loading weights trained with the tanh approximation into a model that uses the exact form shifts every activation a little; numbers stop matching the reference implementation.
- Diagnosing dead ReLUs by the loss alone. Count units whose output is zero on a whole batch (as in the example) or watch the fraction of zero activations per layer; lower the learning rate, check the initialisation or switch to Leaky ReLU when it climbs.
- In-place activations on tensors autograd still needs.
nn.ReLU(inplace=True)saves memory by overwriting its input; if an earlier operation saved that tensor for its own backward pass,backward()raises an error about a tensor modified by an in-place operation.
Practice
- Verify from the table that at using the printed values.
Answer
, so , the printed . Tanh is a shifted and rescaled sigmoid, which is why its maximum slope is .
- In the dead-unit example, why can a unit with a negative bias still be alive while a unit with bias 0 is dead?
Answer
Whether a unit is dead depends on over all inputs, not on alone. Digits pixels are non-negative, so a unit whose weights are negative on every pixel that is ever bright has for all images even with ; a unit with large positive weights on common pixels stays positive for some images even after the bias drops by 1.
- Write the derivative of Leaky ReLU with in one NumPy line, and say what PyTorch module to use.
Answer
np.where(x > 0, 1.0, 0.2); in PyTorch nn.LeakyReLU(negative_slope=0.2) or F.leaky_relu(x, 0.2).
- Ten sigmoid layers in a row: what is the best case for the factor the activations alone apply to the gradient, and what is it at in every layer?
Answer
Best case ; at it is . The weights also multiply in, but no weight scale fixes a factor this small without making the forward pass explode.
Test yourself
What is the largest value the derivative of the sigmoid can take?
- 1
- 0.5
- 0.25
- It is unbounded
A ReLU unit outputs 0 for every input in the training set. What happens to its incoming weights during training?
- They grow until the unit fires again
- They receive zero gradient and stop changing (a dead unit)
- Weight decay is turned off for them
- They are reinitialised automatically
Which default does torch.nn.functional.gelu use?
- The tanh approximation
- The exact form with the error function
- A sigmoid approximation
- Leaky ReLU
Why is softmax subtracted by before exponentiating?
- To make the probabilities sum to 1
- To avoid overflow; the result is mathematically unchanged
- To make the largest probability exactly 1
- To turn logits into log-probabilities
Feeding raw Digits pixels (0 to 16) into a sigmoid layer saturated about half of the units. What is the simplest fix?
- Use a larger learning rate
- Scale the inputs, for example to
- Add more sigmoid layers
- Use softmax instead