TExcelTAD
Home › Math for Deep Learning & LLMs › Activation Functions

Activation Functions

Without a nonlinearity, a stack of linear layers collapses into a single linear map: W2(W1x)=(W2W1)xW_2(W_1\mathbf{x}) = (W_2W_1)\mathbf{x}. The activation function between layers is what lets depth build complicated functions. Its shape also decides how gradients flow backward, which is why the field moved from sigmoids to ReLU and then to smooth variants such as GELU and SwiGLU.

The common activations

Name ϕ(z)\phi(z) ϕ′(z)\phi'(z) Range
sigmoid 11+e−z\frac{1}{1 + e^{-z}} ϕ(1−ϕ)\phi(1 - \phi), at most 0.250.25 (0,1)(0, 1)
tanh ez−e−zez+e−z\frac{e^z - e^{-z}}{e^z + e^{-z}} 1−ϕ21 - \phi^2, at most 1 (−1,1)(-1, 1)
ReLU max⁡(0,z)\max(0, z) 0 for z<0z < 0, 1 for z>0z > 0 [0,∞)[0, \infty)
leaky ReLU max⁡(αz,z)\max(\alpha z, z) α\alpha or 1 R\mathbb{R}
GELU z Φ(z)z\,\Phi(z) smooth, slightly negative for z<0z < 0 about [−0.17,∞)[-0.17, \infty)
SiLU / swish z σ(z)z\,\sigma(z) smooth about [−0.28,∞)[-0.28, \infty)

Φ\Phi is the standard normal CDF. GELU weights the input by the probability that a standard Gaussian falls below it; it is the default in BERT and GPT-2. SiLU is used inside SwiGLU, the feed-forward block of Llama-style models.

python · try it yourself
import numpy as np
from math import erf

z = np.array([-3.0, -1.0, -0.5, 0.0, 0.5, 1.0, 3.0])
sig = 1 / (1 + np.exp(-z))
gelu = z * 0.5 * (1 + np.array([erf(v / np.sqrt(2)) for v in z]))
print("z      ", z)
print("sigmoid", np.round(sig, 3))
print("tanh   ", np.round(np.tanh(z), 3))
print("relu   ", np.maximum(0, z))
print("gelu   ", np.round(gelu, 3))
print("silu   ", np.round(z * sig, 3))
z       [-3.  -1.  -0.5  0.   0.5  1.   3. ]
sigmoid [0.047 0.269 0.378 0.5   0.622 0.731 0.953]
tanh    [-0.995 -0.762 -0.462  0.     0.462  0.762  0.995]
relu    [0.  0.  0.  0.  0.5 1.  3. ]
gelu    [-0.004 -0.159 -0.154  0.     0.346  0.841  2.996]
silu    [-0.142 -0.269 -0.189  0.     0.311  0.731  2.858]

Saturation and vanishing gradients

The sigmoid's derivative is at most 0.250.25, and nearly 0 when ∣z∣\lvert z \rvert is large. Backpropagation multiplies one such factor per layer, so through 10 sigmoid layers the gradient shrinks by at least 0.2510≈10−60.25^{10} \approx 10^{-6} (Vanishing Gradients). ReLU's derivative is exactly 1 for positive inputs, which is why it made deep networks trainable. Its weakness is the dying ReLU: a unit whose input is always negative gets zero gradient and never recovers; leaky ReLU and GELU keep a small gradient there.

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
def grad_through(act_grad, depth=10, n=100000):
    z = rng.normal(size=(depth, n))                  # pre-activations, roughly standard normal
    return np.mean(np.prod(act_grad(z), axis=0))
sig = lambda z: 1 / (1 + np.exp(-z))
print(f"sigmoid: mean gradient factor through 10 layers {grad_through(lambda z: sig(z) * (1 - sig(z))):.2e}")
print(f"tanh:    {grad_through(lambda z: 1 - np.tanh(z)**2):.2e}")
print(f"relu:    {grad_through(lambda z: (z > 0).astype(float)):.2e}  (each path is 0 or 1)")
sigmoid: mean gradient factor through 10 layers 1.42e-07
tanh:    6.73e-03
relu:    9.80e-04  (each path is 0 or 1)

ReLU's average looks small too, but for a different reason: each unit passes the gradient unchanged or blocks it, and with proper initialization the surviving paths keep the signal's size.

Gated activations

GLU variants multiply two linear projections, one passed through an activation: SwiGLU⁡(x)=SiLU⁡(Wx)⊙(Vx)\operatorname{SwiGLU}(\mathbf{x}) = \operatorname{SiLU}(W\mathbf{x}) \odot (V\mathbf{x}). The multiplicative gate lets the network switch features on and off smoothly and consistently improves transformer quality for the same compute.

Output activations

The last layer's activation is chosen by the output distribution, not for gradient flow: identity for regression, sigmoid for a binary probability, softmax for classes (Maximum Likelihood and Cross-Entropy).

In software

  • nn.ReLU, nn.GELU(approximate="tanh"), nn.SiLU, nn.Tanh, F.softmax.
  • The tanh approximation of GELU, 0.5z(1+tanh⁡(2/π(z+0.044715z3)))0.5z(1 + \tanh(\sqrt{2/\pi}(z + 0.044715z^3))), was used in GPT-2 for speed.
  • Activations are elementwise, so they are memory-bound on GPUs and usually fused into the preceding matrix multiply.

Exercises

Exercise 1: Collapse without activations

Two linear layers W1∈R100×10W_1 \in \mathbb{R}^{100 \times 10} and W2∈R1×100W_2 \in \mathbb{R}^{1 \times 100} without an activation equal one linear layer of what shape?

Answer

1×101 \times 10.

Solution

W2W1W_2W_1 is (1×100)(100×10)=1×10(1 \times 100)(100 \times 10) = 1 \times 10. The 1000 extra parameters add nothing to what the model can represent.

Exercise 2: Sigmoid derivative maximum

Show that σ′(z)≤0.25\sigma'(z) \le 0.25.

Answer

σ′(z)=σ(1−σ)\sigma'(z) = \sigma(1 - \sigma), maximized at σ=0.5\sigma = 0.5.

Solution

u(1−u)u(1 - u) for u∈(0,1)u \in (0, 1) is a downward parabola with peak at u=0.5u = 0.5, value 0.250.25, reached at z=0z = 0.

Exercise 3: GELU minimum (code)

Find numerically where GELU attains its minimum and the value there.

Answer

Near z≈−0.75z \approx -0.75, with value about −0.17-0.17.

Solution
python · try it yourself
import numpy as np
from math import erf
z = np.linspace(-3, 0, 30001)
g = z * 0.5 * (1 + np.vectorize(erf)(z / np.sqrt(2)))
i = np.argmin(g)
print(round(z[i], 3), round(g[i], 4))
-0.752 -0.17

Test yourself

Why do networks need nonlinear activations?

  1. To make training faster
  2. A stack of linear layers is just one linear map
  3. To keep weights positive
  4. To normalize the outputs

The derivative of ReLU for a positive input is…

  1. 0
  2. 0.25
  3. 1
  4. the input itself

A 'dead' ReLU unit is one that…

  1. outputs very large values
  2. always receives negative input and so gets zero gradient
  3. has been pruned
  4. uses a sigmoid