Sign in

GELU

Gaussian Error Linear Unit

An activation that multiplies each input by the probability that a standard normal value falls below it.

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

  1. Take the input xx that a layer has computed for one unit.
  2. Look up Φ(x)\Phi(x), the chance that a standard normal draw is smaller than xx. It runs from 0 to 1.
  3. Multiply: the output is x⋅Φ(x)x \cdot \Phi(x).
  4. During training, pass gradients back through the slope Φ(x)+x φ(x)\Phi(x) + x\,\varphi(x), which is smooth everywhere.

Watch out for

  • The output dips slightly below zero (about −0.17-0.17 near x=−0.75x = -0.75), 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 5×10−45 \times 10^{-4}, 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

IfUse instead
The model is small or latency-bound, or runs on hardware without a fast error functionReLU
You are building a gated feed-forward block as in recent large language modelsSwiGLU or GeGLU
You want a smooth curve without the error functionSiLU (Swish)

Math foundations

  1. The standard normal CDF

    Φ(x)=12[1+erf⁡ ⁣(x2)]\Phi(x) = \frac{1}{2}\left[1 + \operatorname{erf}\!\left(\frac{x}{\sqrt{2}}\right)\right]

    The share of a standard normal distribution that lies below xx. It is 0.5 at zero, close to 1 for large positive xx and close to 0 for large negative xx.

  2. The activation

    GELU⁡(x)=x Φ(x)\operatorname{GELU}(x) = x \, \Phi(x)

    The input scaled by that share. Compare ReLU, which scales by exactly 0 or 1.

  3. Its slope

    ddxGELU⁡(x)=Φ(x)+x φ(x),φ(x)=12πe−x2/2\frac{d}{dx}\operatorname{GELU}(x) = \Phi(x) + x\,\varphi(x), \qquad \varphi(x) = \frac{1}{\sqrt{2\pi}} e^{-x^{2}/2}

    From the product rule, since the derivative of Φ\Phi is the normal density φ\varphi. This is the factor backpropagation multiplies by.

  4. The tanh approximation

    GELU⁡(x)≈x2[1+tanh⁡ ⁣(2π (x+0.044715 x3))]\operatorname{GELU}(x) \approx \frac{x}{2}\left[1 + \tanh\!\left(\sqrt{\tfrac{2}{\pi}}\,\big(x + 0.044715\,x^{3}\big)\right)\right]

    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

xx
the input to the activation (one unit's pre-activation)
Φ(x)\Phi(x)
standard normal cumulative distribution function
φ(x)\varphi(x)
standard normal density
erf⁡\operatorname{erf}
the error function

Worked by hand

Compute GELU at x=1x = 1 by hand. The normal table gives Φ(1)=0.8413\Phi(1) = 0.8413 and the density is φ(1)=0.2420\varphi(1) = 0.2420.

GELU⁡(1)=1×0.8413=0.8413\operatorname{GELU}(1) = 1 \times 0.8413 = 0.8413
GELU⁡′(1)=0.8413+1×0.2420=1.0833\operatorname{GELU}'(1) = 0.8413 + 1 \times 0.2420 = 1.0833

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 input
Read 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

  1. 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.

  2. 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 Φ(x)+xφ(x)\Phi(x) + x\varphi(x). It is about 1.13 near x=1.4x = 1.4. Then consider what normalisation layers and residual paths do to repeated factors of that size.

  3. 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 Φ(5)\Phi(5). The two curves are indistinguishable far from zero, so the difference lives in how often pre-activations land near zero.

  4. 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.