TExcelTAD

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 ϕ′(z)\phi'(z), 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 σ(x)=1/(1+e−x)\sigma(x) = 1/(1 + e^{-x}) and Φ\Phi the standard normal CDF:

Name f(x)f(x) f′(x)f'(x) Range
sigmoid σ(x)\sigma(x) σ(x)(1−σ(x))\sigma(x)(1 - \sigma(x)), at most 0.250.25 (0,1)(0, 1)
tanh tanh⁡x\tanh x 1−tanh⁡2x1 - \tanh^2 x, at most 11 (−1,1)(-1, 1)
ReLU max⁡(0,x)\max(0, x) 00 for x<0x < 0, 11 for x>0x > 0 [0,∞)[0, \infty)
Leaky ReLU xx if x>0x > 0, else αx\alpha x 11 or α\alpha (often α=0.01\alpha = 0.01) R\mathbb{R}
ELU xx if x>0x > 0, else ex−1e^x - 1 11 or exe^x (−1,∞)(-1, \infty)
GELU xΦ(x)x \Phi(x) Φ(x)+xφ(x)\Phi(x) + x \varphi(x) about (−0.17,∞)(-0.17, \infty)
SiLU (Swish) xσ(x)x \sigma(x) σ(x)(1+x(1−σ(x)))\sigma(x)(1 + x(1 - \sigma(x))) about (−0.28,∞)(-0.28, \infty)

ReLU is not differentiable at 0; frameworks simply use f′(0)=0f'(0) = 0. GELU is often computed with a tanh approximation, 0.5x(1+tanh⁡(2/π(x+0.044715x3)))0.5x\left(1 + \tanh\left(\sqrt{2/\pi}(x + 0.044715x^3)\right)\right), which is what the original GPT-2 code used.

-1 0 1 2 3 -3 -2 -1 0 1 2 3 values f(x) x 0 0.5 1 -3 -2 -1 0 1 2 3 derivatives f'(x) x sigmoid tanh ReLU GELU

The figure shows the key difference. Sigmoid and tanh flatten out on both sides: for ∣x∣>3\lvert x \rvert > 3 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:

softmax⁡(z)i=ezi∑jezj=ezi−m∑jezj−m,m=max⁡jzj\operatorname{softmax}(z)_i = \frac{e^{z_i}}{\sum_j e^{z_j}} = \frac{e^{z_i - m}}{\sum_j e^{z_j - m}}, \qquad m = \max_j z_j

Subtracting the maximum changes nothing mathematically and prevents eze^{z} 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:

python · try it yourself
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 x=±3x = \pm 3. 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 (x=0x = 0) a sigmoid passes 0.25, so a chain of ten sigmoid layers multiplies the gradient by at most 0.2510≈10−60.25^{10} \approx 10^{-6}; this is the classic vanishing gradient problem. GELU at x=−1x = -1 has slope −0.0833-0.0833, which ReLU (slope 0) would not have. The tanh approximation of GELU differs from the exact form by at most 0.00047 on [−4,4][-4, 4], 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 z=XW+bz = XW + b 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 [0,1][0, 1], 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.

python · try it yourself
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 [0,1][0, 1] 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 α\alpha 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 [−6,6][-6, 6]:

python · try it yourself
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 (0,1)(0, 1) means "how much to let through"
Recurrent state, bounded outputs tanh zero-centred and bounded in (−1,1)(-1, 1)
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

  1. Verify from the table that tanh⁡(x)=2σ(2x)−1\tanh(x) = 2\sigma(2x) - 1 at x=1x = 1 using the printed values.
Answer

σ(2)=1/(1+e−2)≈0.8808\sigma(2) = 1/(1 + e^{-2}) \approx 0.8808, so 2⋅0.8808−1=0.76162 \cdot 0.8808 - 1 = 0.7616, the printed tanh⁡1\tanh 1. Tanh is a shifted and rescaled sigmoid, which is why its maximum slope is 4⋅0.25=14 \cdot 0.25 = 1.

  1. 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 z=x⊤w+bz = x^\top w + b over all inputs, not on bb alone. Digits pixels are non-negative, so a unit whose weights are negative on every pixel that is ever bright has z≤0z \le 0 for all images even with b=0b = 0; a unit with large positive weights on common pixels stays positive for some images even after the bias drops by 1.

  1. Write the derivative of Leaky ReLU with α=0.2\alpha = 0.2 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).

  1. 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 x=3x = 3 in every layer?
Answer

Best case 0.2510≈9.5×10−70.25^{10} \approx 9.5 \times 10^{-7}; at x=3x = 3 it is 0.045210≈3.6×10−140.0452^{10} \approx 3.6 \times 10^{-14}. 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. 1
  2. 0.5
  3. 0.25
  4. It is unbounded

A ReLU unit outputs 0 for every input in the training set. What happens to its incoming weights during training?

  1. They grow until the unit fires again
  2. They receive zero gradient and stop changing (a dead unit)
  3. Weight decay is turned off for them
  4. They are reinitialised automatically

Which default does torch.nn.functional.gelu use?

  1. The tanh approximation
  2. The exact form xΦ(x)x \Phi(x) with the error function
  3. A sigmoid approximation xσ(1.702x)x \sigma(1.702x)
  4. Leaky ReLU

Why is softmax subtracted by max⁡jzj\max_j z_j before exponentiating?

  1. To make the probabilities sum to 1
  2. To avoid overflow; the result is mathematically unchanged
  3. To make the largest probability exactly 1
  4. 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?

  1. Use a larger learning rate
  2. Scale the inputs, for example to [0,1][0, 1]
  3. Add more sigmoid layers
  4. Use softmax instead