Equations · Hendrycks and Gimpel, “Gaussian Error Linear Units (GELUs)” (2016)

The GELU activation formula, explained

A smooth version of ReLU, used in BERT, GPT-2 and many Transformers since. Each input is multiplied by the probability that a standard normal variable is below it: large positive inputs pass almost unchanged, large negative ones are nearly zeroed, and the region around 0 is curved rather than kinked.

GELU⁡(x)=x Φ(x)≈0.5x(1+tanh⁡[2/π(x+0.044715x3)])\operatorname{GELU}(x) = x\,\Phi(x) \approx 0.5x\left(1 + \tanh\left[\sqrt{2/\pi}\left(x + 0.044715x^3\right)\right]\right)

Open in the decoder →

Term by term

  1. xx

    One pre-activation value. GELU is applied elementwise, so for a vector or tensor it acts on each entry separately.

  2. Φ(x)\Phi(x)

    The cumulative distribution function of the standard normal N(0,1)\mathcal{N}(0, 1): the probability P(X≤x)P(X \le x). It rises smoothly from 0 to 1, passing 0.50.5 at x=0x = 0. A capital Φ\Phi almost always means this CDF.

  3. x Φ(x)x\,\Phi(x)

    The input, scaled by a weight between 0 and 1 that depends on the input itself. ReLU uses a hard weight instead: 1 if x>0x > 0, else 0.

  4. tanh⁡[2/π(x+0.044715x3)]\tanh\left[\sqrt{2/\pi}\left(x + 0.044715x^3\right)\right]

    A fast approximation of 2Φ(x)−12\Phi(x) - 1 given in the paper. Some libraries use it (PyTorch's approximate="tanh"); others compute Φ\Phi exactly with the error function. The two differ by less than 0.0010.001.

A small worked example

At x=1x = 1: Φ(1)≈0.841\Phi(1) \approx 0.841, so GELU⁡(1)≈0.841\operatorname{GELU}(1) \approx 0.841; the tanh form gives 0.5×1.682≈0.8410.5 \times 1.682 \approx 0.841 too. At x=−1x = -1: −1×0.159=−0.159-1 \times 0.159 = -0.159. ReLU would give 11 and 00. GELU is slightly negative for negative inputs, with a minimum of about −0.17-0.17 near x=−0.75x = -0.75.

In code

import torch
import torch.nn.functional as F

x = torch.tensor([-1.0, 0.0, 1.0])
F.gelu(x)                       # exact: x * Phi(x)
F.gelu(x, approximate="tanh")   # the tanh approximation
x * 0.5 * (1 + torch.erf(x / 2**0.5))   # the same thing by hand

Every symbol in it

y=Wx+by = Wx + bItalic letters (variables)qϕ(z∣x)q_\phi(z \mid x)PhiN(μ,σ2)\mathcal{N}(\mu, \sigma^2)Normal distributionp(x),  q(z)p(\mathbf{x}), \; q(\mathbf{z})Probability p(x)tanh⁡(x)\tanh(x)Hyperbolic tangentdk\sqrt{d_k}Square rootπθ(a∣s)\pi_\theta(a \mid s)Pix2,  βt,  WQx^2,\; \beta^t,\; W^QSuperscript (power or label)

Other equations