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:
Substituting the first into the second:
This is just . The product is itself a matrix, so all depth collapses into one layer. Adding more layers without activations changes nothing.
An activation function is applied element-wise after each linear step:
Because is non-linear, 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 :
The shape is intuitive: it looks like a smooth step from to . For large positive inputs it saturates near ; for large negative inputs it saturates near . Its derivative can be written in terms of the function itself:
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 , where . At larger input magnitudes the gradient collapses rapidly:
In a 10-layer network, gradients at the first layer are multiplied together through each backward step. With a maximum per-layer factor of , the gradient arriving at layer 1 is at most : 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 rather than . 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 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 :
Its derivative is:
Two improvements over sigmoid:
Zero-centered outputs. Tanh outputs average to rather than . 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 , four times larger than sigmoid's maximum of . In a network of the same depth, gradients survive several more layers before vanishing.
Example. For an input of :
- , gradient
- , gradient
For this moderate input sigmoid actually wins; the difference shows at initialization, where inputs cluster near zero and tanh's gradient of is far stronger than sigmoid's .
Tanh was the preferred hidden-layer activation through the 1990s and into the 2000s. But it still saturates for large : 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:
Its output is for positive inputs and for negative inputs. The derivative is equally simple:
At the derivative is undefined, but this single point has no practical effect and is conventionally set to .
Why ReLU solved the vanishing gradient problem. A neuron whose pre-activation is positive passes its gradient through multiplied by exactly . In a network of ten active ReLU layers, the gradient arrives at layer 1 multiplied by . 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 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 . 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 occasionally caused instabilities.
GELU (Gaussian Error Linear Unit) weights the input by the probability that a standard normal variable is less than it:
where 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 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 . 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
| Setting | Recommended | Reason |
|---|---|---|
| General hidden layers | ReLU | Fast, no vanishing gradient for active neurons |
| Transformer hidden layers | GELU | Smooth, no dead neurons, standard in practice |
| Binary classification output | Sigmoid | Output in , probability interpretation |
| Multi-class output | Softmax | Generalizes sigmoid to classes |
| Recurrent hidden state | Tanh | Zero-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.