Skip to content
Building Blocks

Activation Functions

From sigmoid to ReLU: the non-linear operations that make depth meaningful, and why each replaced what came before.

The Training section covered the machinery of learning: measuring error, propagating gradients, updating weights. This section turns to the building blocks that go inside the network itself. The first and most fundamental is the activation function.

Why Non-Linearity Is Required

Without activation functions, a network of any depth is equivalent to a single linear transformation. To see why, consider two linear layers stacked without any non-linearity:

h=W1x+b1y=W2h+b2\mathbf{h} = \mathbf{W}_1 \mathbf{x} + \mathbf{b}_1 \qquad \mathbf{y} = \mathbf{W}_2 \mathbf{h} + \mathbf{b}_2

Substituting the first into the second:

y=W2(W1x+b1)+b2=(W2W1)⏟Wx+(W2b1+b2)⏟b\mathbf{y} = \mathbf{W}_2 (\mathbf{W}_1 \mathbf{x} + \mathbf{b}_1) + \mathbf{b}_2 = \underbrace{(\mathbf{W}_2 \mathbf{W}_1)}_{\mathbf{W}} \mathbf{x} + \underbrace{(\mathbf{W}_2 \mathbf{b}_1 + \mathbf{b}_2)}_{\mathbf{b}}

This is just y=Wx+b\mathbf{y} = \mathbf{W}\mathbf{x} + \mathbf{b}. The product W2W1\mathbf{W}_2\mathbf{W}_1 is itself a matrix, so all depth collapses into one layer. Adding more layers without activations changes nothing.

An activation function σ\sigma is applied element-wise after each linear step:

h=σ(W1x+b1)\mathbf{h} = \sigma(\mathbf{W}_1 \mathbf{x} + \mathbf{b}_1)

Because σ\sigma is non-linear, W2σ(W1x+b1)\mathbf{W}_2 \sigma(\mathbf{W}_1 \mathbf{x} + \mathbf{b}_1) cannot be collapsed into a single matrix multiplication. Each additional layer genuinely extends what the network can represent. The theoretical justification is the universal approximation theorem: a network with at least one hidden layer using a non-linear activation can approximate any continuous function to arbitrary precision, given enough neurons.

The history of activation functions is a history of finding and fixing failure modes. Each generation solved the problems of the one before.

Sigmoid

The sigmoid function was the first widely used activation. It compresses any real input into the interval (0,1)(0, 1):

σ(x)=11+e−x\sigma(x) = \frac{1}{1 + e^{-x}}

The shape is intuitive: it looks like a smooth step from 00 to 11. For large positive inputs it saturates near 11; for large negative inputs it saturates near 00. Its derivative can be written in terms of the function itself:

σ′(x)=σ(x) (1−σ(x))\sigma'(x) = \sigma(x)\,(1 - \sigma(x))

The appeal in early neural networks was clear: the output is bounded and differentiable everywhere, which felt like a clean proxy for a neuron either "firing" or not.

The vanishing gradient problem. The maximum gradient occurs at x=0x = 0, where σ′(0)=0.5×0.5=0.25\sigma'(0) = 0.5 \times 0.5 = 0.25. At larger input magnitudes the gradient collapses rapidly:

σ′(5)≈0.993×0.007≈0.007\sigma'(5) \approx 0.993 \times 0.007 \approx 0.007

In a 10-layer network, gradients at the first layer are multiplied together through each backward step. With a maximum per-layer factor of 0.250.25, the gradient arriving at layer 1 is at most 0.2510≈10−60.25^{10} \approx 10^{-6}: effectively zero. Early layers learn nothing. This is the vanishing gradient problem, and it made training deep networks with sigmoid nearly impossible.

Offset outputs. Sigmoid outputs are always positive, centered around 0.50.5 rather than 00. When the input to the next layer is always positive, the gradients with respect to the weights all have the same sign, forcing a zig-zagging path during optimization rather than a straight descent toward the minimum.

Sigmoid is still the right choice in one specific role: the output layer of a binary classifier, where a prediction in (0,1)(0, 1) is a valid probability. For hidden layers it was superseded almost immediately once a better option was found.

Tanh

Hyperbolic tangent emerged as a direct response to sigmoid's offset problem. It maps inputs to (−1,1)(-1, 1):

tanh⁡(x)=ex−e−xex+e−x=2σ(2x)−1\tanh(x) = \frac{e^x - e^{-x}}{e^x + e^{-x}} = 2\sigma(2x) - 1

Its derivative is:

tanh⁡′(x)=1−tanh⁡2(x)\tanh'(x) = 1 - \tanh^2(x)

Two improvements over sigmoid:

Zero-centered outputs. Tanh outputs average to 00 rather than 0.50.5. The next layer receives inputs that mix positive and negative values, and its gradients no longer all have the same sign. Optimization follows a cleaner path.

Stronger gradient. The maximum gradient is tanh⁡′(0)=1\tanh'(0) = 1, four times larger than sigmoid's maximum of 0.250.25. In a network of the same depth, gradients survive several more layers before vanishing.

Example. For an input of x=2x = 2:

  • tanh⁡(2)≈0.964\tanh(2) \approx 0.964, gradient ≈1−0.9642=0.071\approx 1 - 0.964^2 = 0.071
  • σ(2)≈0.880\sigma(2) \approx 0.880, gradient ≈0.880×0.120=0.106\approx 0.880 \times 0.120 = 0.106

For this moderate input sigmoid actually wins; the difference shows at initialization, where inputs cluster near zero and tanh's gradient of 11 is far stronger than sigmoid's 0.250.25.

Tanh was the preferred hidden-layer activation through the 1990s and into the 2000s. But it still saturates for large ∣x∣|x|: both tails have near-zero gradients, and the vanishing gradient problem returns for any network deep enough that pre-activations drift away from zero.

ReLU

The breakthrough came in 2010–2011 when researchers demonstrated that Rectified Linear Unit allowed networks ten or more layers deep to train effectively for the first time:

ReLU(x)=max⁡(0, x)\text{ReLU}(x) = \max(0,\, x)

Its output is xx for positive inputs and 00 for negative inputs. The derivative is equally simple:

ReLU′(x)={1x>00x<0\text{ReLU}'(x) = \begin{cases} 1 & x > 0 \\ 0 & x < 0 \end{cases}

At x=0x = 0 the derivative is undefined, but this single point has no practical effect and is conventionally set to 00.

Why ReLU solved the vanishing gradient problem. A neuron whose pre-activation is positive passes its gradient through multiplied by exactly 11. In a network of ten active ReLU layers, the gradient arrives at layer 1 multiplied by 110=11^{10} = 1. There is no exponential decay. The gradient signal that reaches early layers is the same order of magnitude as the gradient at the output, and training proceeds at every depth.

Speed. Computing max⁡(0,x)\max(0, x) is a single comparison, with no exponentials. Networks using ReLU train significantly faster per step than those using sigmoid or tanh.

The dying ReLU problem. The simplicity of ReLU has one cost. If a neuron's pre-activation is always negative — because a large weight update pushed it into that region — its gradient is permanently 00. The optimizer can never move it back. The neuron "dies" and stops contributing to the network. In practice this is rarely a serious problem with good initialization and a reasonable learning rate, but it is the known failure mode of ReLU.

ReLU became the default activation for hidden layers in deep networks and remained so through the deep learning revolution of the 2010s.

Modern Variants

ReLU's hard zero for negative inputs is convenient but crude. Several smooth approximations were developed for large models where the dying neuron problem was more of a concern, and where the slight roughness of ReLU at x=0x = 0 occasionally caused instabilities.

GELU (Gaussian Error Linear Unit) weights the input by the probability that a standard normal variable is less than it:

GELU(x)=x⋅Φ(x)\text{GELU}(x) = x \cdot \Phi(x)

where Φ\Phi is the standard normal CDF. Unlike ReLU, GELU is differentiable everywhere. For large positive inputs it behaves like the identity; for large negative inputs it decays smoothly to 00 rather than clamping abruptly. It also allows small negative outputs for inputs slightly below zero, rather than zeroing them entirely. This means no neuron can fully die: even a negative pre-activation produces a small non-zero gradient.

GELU is the standard activation in BERT, GPT-2, and the transformer feed-forward networks covered in the Transformer Block article.

SiLU (Sigmoid Linear Unit, also called Swish) is defined as x⋅σ(x)x \cdot \sigma(x). It shares GELU's key properties: smooth, non-monotone for negative inputs, and no hard cutoff to zero. SiLU is used in EfficientNet and LLaMA.

Both are plug-in replacements for ReLU. Any architecture using ReLU can switch to GELU or SiLU without structural changes.

Choosing an Activation

SettingRecommendedReason
General hidden layersReLUFast, no vanishing gradient for active neurons
Transformer hidden layersGELUSmooth, no dead neurons, standard in practice
Binary classification outputSigmoidOutput in (0,1)(0, 1), probability interpretation
Multi-class outputSoftmaxGeneralizes sigmoid to KK classes
Recurrent hidden stateTanhZero-centered, beneficial for sequence dynamics

The default for any new hidden layer is ReLU unless there is a specific reason to use something else. For transformers, GELU is the established convention.

In Code

import torch
import torch.nn.functional as F

# Sigmoid — maps to (0, 1), max gradient 0.25 at x=0
x1 = torch.tensor([-2.0, 0.0, 2.0], requires_grad=True)
y1 = torch.sigmoid(x1)
y1.sum().backward()          # sum() so that backward() starts from a scalar: x.grad = dy/dx
print(y1)        # tensor([0.1192, 0.5000, 0.8808])
print(x1.grad)   # tensor([0.1050, 0.2500, 0.1050])  —  peaks at 0.25

# Tanh — maps to (-1, 1), zero-centered, max gradient 1.0 at x=0
x2 = torch.tensor([-2.0, 0.0, 2.0], requires_grad=True)
y2 = torch.tanh(x2)
y2.sum().backward()
print(y2)        # tensor([-0.9640,  0.0000,  0.9640])
print(x2.grad)   # tensor([0.0707, 1.0000, 0.0707])  —  peaks at 1.0

# ReLU — gradient 1 for positive inputs, 0 for negative ones (dying ReLU risk)
x3 = torch.tensor([-2.0, -1.0, 0.0, 1.0, 2.0], requires_grad=True)
y3 = F.relu(x3)
y3.sum().backward()
print(y3)        # tensor([0., 0., 0., 1., 2.])
print(x3.grad)   # tensor([0., 0., 0., 1., 1.])  —  zero for every negative input

# GELU — x·Φ(x), smooth and non-monotone for x < 0, no dead neurons
x4 = torch.tensor([-2.0, 0.0, 2.0])
print(F.gelu(x4))   # tensor([-0.0455,  0.0000,  1.9545])

Activation functions introduce the non-linearity that makes depth meaningful. Without them, no amount of additional layers extends the network's expressive power. The history from sigmoid to tanh to ReLU is a history of removing obstacles to gradient flow: first fixing offset outputs, then fixing the saturation ceiling, then eliminating the vanishing gradient problem for active neurons entirely. The next article examines the linear operations that activation functions are always paired with: the weight matrices and bias vectors that form the neurons themselves.