Overview
ReLU makes a hard choice: keep the input if it is positive, drop it if it is not. GELU makes the same choice softly. It asks how unusual the input is compared with ordinary noise and keeps that share of it. A large positive input passes almost whole, a large negative one is almost removed, and an input near zero is kept about halfway. Because the choice is gradual, the curve has no corner and its slope never jumps.
A short history
Dan Hendrycks and Kevin Gimpel proposed GELU in 2016 as a smooth alternative to ReLU, motivated by the idea of dropping an input at random with a chance that depends on its size. It drew little attention until BERT adopted it in 2018, followed by GPT-2 and the Vision Transformer. It has been the usual activation in transformer feed-forward blocks since.
How it works
- Take the input that a layer has computed for one unit.
- Look up , the chance that a standard normal draw is smaller than . It runs from 0 to 1.
- Multiply: the output is .
- During training, pass gradients back through the slope , which is smooth everywhere.
Watch out for
- The output dips slightly below zero (about near ), so it is not monotonic. Code that assumes non-negative activations will be wrong.
- The exact form needs the error function. Some frameworks default to a tanh approximation that differs by up to about , which matters when you compare outputs across libraries.
- It costs more to compute than ReLU. On very small or latency-bound models that can be the deciding factor.
Use cases
When to use it
Building transformer feed-forward blocks, or any deep network where a smooth slope near zero trains better than ReLU's corner. It is the default in BERT, GPT-2 and ViT.
In industry
- Search and language
- Encoder models in the BERT family, used to rank search results and classify text, use GELU in every feed-forward block.
- Computer vision
- Vision Transformers for image classification and detection use GELU where convolutional networks used ReLU.
- Speech
- Transformer speech recognisers such as wav2vec 2.0 and Whisper use GELU in their encoder layers.
Choosing it: what must hold
- A deep network, usually a transformer, trained with normalisation and residual connections.
- Enough compute that an activation slightly costlier than ReLU does not matter.
- If you load pretrained weights, the same GELU variant (exact or tanh) the weights were trained with.
When to choose something else
| If | Use instead |
|---|---|
| The model is small or latency-bound, or runs on hardware without a fast error function | ReLU |
| You are building a gated feed-forward block as in recent large language models | SwiGLU or GeGLU |
| You want a smooth curve without the error function | SiLU (Swish) |
Math foundations
The standard normal CDF
The share of a standard normal distribution that lies below . It is 0.5 at zero, close to 1 for large positive and close to 0 for large negative .
The activation
The input scaled by that share. Compare ReLU, which scales by exactly 0 or 1.
Its slope
From the product rule, since the derivative of is the normal density . This is the factor backpropagation multiplies by.
The tanh approximation
Used by the original BERT and GPT-2 code because it avoids the error function. Close to the exact curve, not equal to it.
Symbols
- the input to the activation (one unit's pre-activation)
- standard normal cumulative distribution function
- standard normal density
- the error function
Worked by hand
Compute GELU at by hand. The normal table gives and the density is .
The output is 0.8413, a little under the input, and the slope is slightly above 1. ReLU would give exactly 1 and 1.
Visual example
Loading the example.
Try this
- Move across the curve and read the output and the slope together.
- Find where the slope is close to zero: a unit there has stopped learning.
Code sample
import numpy as np
from impl import GELU
from config import GELUConfig
act = GELU(GELUConfig(approximate="none"))
y = act.forward(np.array([-1.0, 0.0, 1.0])) # [-0.1587, 0.0, 0.8413]
dy = act.backward(np.array([-1.0, 0.0, 1.0])) # gradient with respect to the inputRead the implementation (48 lines)
"""GELU: Gaussian error linear unit, f(x) = x * Phi(x).
NumPy only. `forward` computes the activation, `backward` the gradient with respect to the input, so the
template drops into a hand-written network or serves as a reference to test a framework's GELU against.
"""
from __future__ import annotations
import math
import numpy as np
try:
from .config import GELUConfig
except ImportError: # run from the template's own folder
from config import GELUConfig
_SQRT_2 = math.sqrt(2.0)
_SQRT_2_OVER_PI = math.sqrt(2.0 / math.pi)
_INV_SQRT_2PI = 1.0 / math.sqrt(2.0 * math.pi)
_erf = np.vectorize(math.erf, otypes=[float])
class GELU:
"""f(x) = x * Phi(x), where Phi is the standard normal CDF."""
def __init__(self, config: GELUConfig | None = None) -> None:
self.config = config or GELUConfig()
def forward(self, x: np.ndarray) -> np.ndarray:
x = np.asarray(x, dtype=float)
if self.config.approximate == "tanh":
return 0.5 * x * (1.0 + np.tanh(_SQRT_2_OVER_PI * (x + 0.044715 * x**3)))
return 0.5 * x * (1.0 + _erf(x / _SQRT_2))
def backward(self, x: np.ndarray, grad_output: np.ndarray | None = None) -> np.ndarray:
"""d f / d x at x, times `grad_output` when given (the chain rule step of backpropagation)."""
x = np.asarray(x, dtype=float)
if self.config.approximate == "tanh":
inner = _SQRT_2_OVER_PI * (x + 0.044715 * x**3)
t = np.tanh(inner)
local = 0.5 * (1.0 + t) + 0.5 * x * (1.0 - t**2) * _SQRT_2_OVER_PI * (1.0 + 3 * 0.044715 * x**2)
else:
cdf = 0.5 * (1.0 + _erf(x / _SQRT_2))
pdf = _INV_SQRT_2PI * np.exp(-0.5 * x**2)
local = cdf + x * pdf
return local if grad_output is None else local * np.asarray(grad_output, dtype=float)
__call__ = forward- Repository
- gitlab.com/designsbyduhart/solomon-templates/activation-gelu
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Using the template, evaluate GELU with approximate set to none and to tanh on 1001 points between -5 and 5. Find where the two differ most and by how much, then check the analytic backward against a finite difference at that point.
Check on learning
- GELU is negative for some negative inputs but ReLU never is. What could a network do with a small negative output that it cannot do with a zero?
A way to think about it
Think about the gradient. Where ReLU outputs zero its slope is also zero, so the unit cannot recover. Compare with GELU's slope at the same input.
- Why does the product rule give a slope above 1 for some positive inputs, and does that risk exploding gradients in a deep stack?
A way to think about it
Find the maximum of . It is about 1.13 near . Then consider what normalisation layers and residual paths do to repeated factors of that size.
- If your inputs to GELU were all in the range 5 to 10, would switching to ReLU change the model's behaviour? What does that tell you about where the choice of activation matters?
A way to think about it
Evaluate . The two curves are indistinguishable far from zero, so the difference lives in how often pre-activations land near zero.
- A colleague reports that the same weights give slightly different outputs in two frameworks. How would you test whether the GELU variant is the cause?
A way to think about it
Compare the exact and tanh forms on the actual pre-activations, and see whether the size of the gap matches what you observe at the output.