All formulas

Machine learning building blocks

GELU (tanh approximation)

ml.gelu-tanhAlso called gelu tanh, gelu approximate, gelu new, approximate gelu

GELU⁡tanh⁡(x)=x2(1+tanh⁡(2π(x+0.044715x3)))\operatorname{GELU}_{\tanh}(x) = \frac{x}{2}\left(1 + \tanh\left(\sqrt{\frac{2}{\pi}}\left(x + 0.044715x^{3}\right)\right)\right)

The tanh approximation of GELU, torch.nn.GELU(approximate='tanh') and the form used in many transformer codebases. The exact erf form is ml.gelu.

Notation

xx

input

x ∈ ℝ

GELU⁡tanh⁡(x)\operatorname{GELU}_{\tanh}(x)

Result: the activation

scalar

Worked examples

Each result is solved exactly and confirmed by two independent computations.

  1. Given

    x=0x = 0

    Result

    GELU⁡tanh⁡(x)=0\displaystyle \operatorname{GELU}_{\tanh}(x) = 0
  2. Given

    x=1x = 1

    Result

    GELU⁡tanh⁡(x)=tanh⁡(2089432200000π)2+12\displaystyle \operatorname{GELU}_{\tanh}(x) = \frac{\tanh{\left(\frac{208943 \sqrt{2}}{200000 \sqrt{\pi}} \right)}}{2} + \frac{1}{2}

    ≈ 0.841191990608

  3. Given

    x=−1x = -1

    Result

    GELU⁡tanh⁡(x)=−12+tanh⁡(2089432200000π)2\displaystyle \operatorname{GELU}_{\tanh}(x) = - \frac{1}{2} + \frac{\tanh{\left(\frac{208943 \sqrt{2}}{200000 \sqrt{\pi}} \right)}}{2}

    ≈ -0.158808009392

  4. Given

    x=2x = 2

    Result

    GELU⁡tanh⁡(x)=tanh⁡(58943225000π)+1\displaystyle \operatorname{GELU}_{\tanh}(x) = \tanh{\left(\frac{58943 \sqrt{2}}{25000 \sqrt{\pi}} \right)} + 1

    ≈ 1.95459769409

Common mistakes

  • Computes the exact erf form

    The result is x Φ(x), the exact GELU, where the tanh approximation is specified.

    Fix: Use the tanh formula, or torch.nn.GELU(approximate='tanh').

Source

  • Hendrycks and Gimpel 2016

    Hendrycks, Dan; Gimpel, Kevin. Gaussian Error Linear Units (GELUs). arXiv:1606.08415, 2016.

    arxiv.org