AI Wiki中文/EN

GELU and SiLU: gates, dips and approximations

GELU 与 SiLU

Derive gate moments, locate negative stationary points and test the derivative of a GELU approximation.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A smooth gate can dip below zero

ReLU keeps a positive input and discards a negative one. GELU and SiLU instead multiply the input by a smooth weight between zero and one. Negative inputs are partly retained, but very negative inputs receive very small weights. The resulting functions dip below zero and then rise: they are smooth, yet not monotone.

This matters when interpreting a local derivative. A negative derivative is not necessarily a coding error; it can be part of the chosen activation. Conversely, “smooth” does not mean “nonzero derivative everywhere.” Each function has a stationary point on its negative side.

Hendrycks and Gimpel’s GELU paper, fixed v 5, Section 2 defines Gaussian weighting and approximations. Elfwing, Uchibe and Doya, fixed v 3, Section 2.2 defines SiLU and its derivative-based companion dSiLU. Start with sigmoid and tanh and Gaussian distributions.

The expected gate is deterministic

Let Φ and φ denote the standard normal CDF and density. Let σ be the logistic sigmoid. For a fixed real input x, introduce a hypothetical Bernoulli gate M with success probability Φ(x):

G(x)=xΦ(x),S(x)=xσ(x),E[xM∣x]=G(x),Var⁡(xM∣x)=x2Φ(x)(1−Φ(x)).G(x)=x\Phi(x),\qquad S(x)=x\sigma(x),\qquad \mathbb E[xM\mid x]=G(x),\qquad \operatorname{Var}(xM\mid x)=x^2\Phi(x)(1-\Phi(x)).

G is standard GELU and S is SiLU. The gate is a way to motivate GELU, not a requirement to draw random numbers during its usual evaluation. The expectation follows by enumerating M=1 and M=0. Since M²=M, the second moment is x²Φ(x), and subtracting the squared mean gives the variance.

The deterministic mean cannot generally replace the gate inside every downstream nonlinear function. At x=−1, the expected squared gated output is about 0.158655, but squaring the deterministic GELU output gives about 0.025171. The difference is the gate variance. Expectation commutes with affine operations; it does not generally commute with squaring or a whole nonlinear network. The paper’s motivation should not be turned into a claim that ordinary GELU exactly averages every randomized network.

Different curves, different stationary points

The product rule gives:

G′(x)=Φ(x)+xϕ(x),S′(x)=σ(x)+xσ(x)(1−σ(x)).G'(x)=\Phi(x)+x\phi(x),\qquad S'(x)=\sigma(x)+x\sigma(x)(1-\sigma(x)).

Both functions are zero at the origin with slope 1/2. Away from zero they differ. GELU’s derivative crosses zero near−0.751792, with value about−0.169971; SiLU’s crossing is near−1.278465, with value about−0.278465. Our code brackets and locates these crossings.

For GELU, differentiating again gives G″(x)=(2−x²)φ(x), positive on[−1,0]. The sign change of G′ across that bracket therefore identifies a unique local minimum there. For SiLU, S′=0 is equivalent to 1+eˣ+x=0. Its left side is strictly increasing, negative at−2 and positive at−1, so there is exactly one root; the derivative changes from negative to positive. These arguments support the numerical root checks without treating a plot as proof.

An approximation has its own derivative

A common GELU approximation is:

G~(x)=x2(1+tanh⁡u(x)),u(x)=2/π(x+0.044715x3),G~′(x)=1+tanh⁡u2+x2(1−tanh⁡2u)u′(x).\widetilde G(x)=\frac x2\bigl(1+\tanh u(x)\bigr),\qquad u(x)=\sqrt{2/\pi}(x+0.044715x^3),\qquad \widetilde G'(x)=\frac{1+\tanh u}{2}+\frac x2(1-\tanh^2u)u'(x).

Here u′(x)=√(2/π)(1+3·0.044715x²). If the forward pass uses this approximation, its analytic backward pass should differentiate this expression. Reusing the exact-CDF GELU derivative makes the pair mathematically inconsistent, even if the numerical discrepancy is small.

Locate stationary points and measure an approximation

The complete Python 3.12 program evaluates standard GELU, SiLU and the tanh approximation, returning both value and derivative. The normal CDF uses erfc to avoid cancellation in the negative tail. These remain floating-point evaluations of exact mathematical definitions.

from math import exp, erfc, sqrt, pi, tanh, isfinite


def smooth_unit(x, kind):
    if type(x) not in (int,float) or not isfinite(x) or abs(x)>100:
        raise ValueError('finite input in [-100,100] required')
    if kind=='gelu':
        cdf=erfc(-x/sqrt(2))/2;density=exp(-x*x/2)/sqrt(2*pi)
        return x*cdf,cdf+x*density
    if kind=='silu':
        e=exp(-abs(x));p=1/(1+e) if x>=0 else e/(1+e)
        return x*p,p+x*e/(1+e)**2
    if kind=='gelu_tanh':
        c=sqrt(2/pi);u=c*(x+0.044715*x**3);t=tanh(u)
        e=exp(-2*abs(u));dt=4*e/(1+e)**2
        return x*(1+t)/2,(1+t)/2+x*dt*c*(1+3*0.044715*x*x)/2
    raise ValueError('unknown activation')


def stationary(kind):
    if kind not in ('gelu','silu'):raise ValueError('exact-definition activation required')
    lo,hi=(-1.0,0.0) if kind=='gelu' else (-2.0,-1.0)
    for _ in range(60):
        mid=(lo+hi)/2
        if smooth_unit(mid,kind)[1]<0:lo=mid
        else:hi=mid
    x=(lo+hi)/2
    return x,smooth_unit(x,kind)[0]


if __name__=='__main__':
    for kind in ('gelu','silu'):
        x,value=stationary(kind)
        print(kind,'bracketed stationary x/value:',f'{x:.9f}',f'{value:.9f}')
    grid=[i/100 for i in range(-500,501)]
    error=max(abs(smooth_unit(x,'gelu')[0]-smooth_unit(x,'gelu_tanh')[0]) for x in grid)
    print('tanh approximation maximum value error on 1001-point [-5,5] grid:',f'{error:.9f}')
    x=-1;p=erfc(-x/sqrt(2))/2
    print('random gate: E[(xM)^2], (E[xM])^2, variance:',*[f'{v:.9f}' for v in (x*x*p,(x*p)**2,x*x*p*(1-p))])

Actual output:

gelu bracketed stationary x/value: -0.751791525 -0.169971207
silu bracketed stationary x/value: -1.278464543 -0.278464543
tanh approximation maximum value error on 1001-point [-5,5] grid: 0.000473235
random gate: E[(xM)^2], (E[xM])^2, variance: 0.158655254 0.025171490 0.133483764

Bisection performs 60 bracket updates. The approximation comparison uses exactly 1001 equally spaced points on[−5,5]. Its maximum is a sampled statistic, not a proved uniform bound on the interval or the real line. Relative errors near zero can be misleading, so the program reports absolute value error.

Each scalar evaluation has constant operation count, but special functions cost more than a comparison. The root search has fixed 60-step cost and the grid sweep has linear cost in grid size. Tests compare known values, finite differences for all three derivatives, stationary-point residuals and the exact two-outcome moment identity.

A favorable scalar curve is not a benchmark

A slightly different activation changes outputs, gradients and often appropriate initialization. Compare trained models using the same data split and evaluation budget; the graph of a scalar function cannot establish a task-level ranking. This program does not reproduce either paper’s image, language, speech or reinforcement-learning experiments.

GELU and SiLU are unbounded above and approach zero from below in the negative tail. Their derivatives can be negative or exceed 1, so treating either as a monotone probability transform is wrong. The multiplicative weights are probabilities in the mathematical construction; the activation outputs are not class probabilities.

The tanh approximation may round its negative tail to zero sooner than the erfc implementation. Different kernels and number formats can produce different tail behavior. Record the chosen approximation when reproducing a model, especially if comparing gradients or exported inference results.

Which equality survives the nonlinear operation?

  1. Does ordinary deterministic GELU sample the gate M each time?

Answer 1: No. It computes the expected gated input xΦ(x).

  1. What is E[(xM)²]−(E[xM])² for this Bernoulli gate?

Answer 2: x²Φ(x)(1−Φ(x)), the conditional variance at fixed x.

  1. Which derivative matches a forward implementation using the tanh GELU approximation?

Answer 3: The derivative of that approximation, including u′, rather than the exact-CDF derivative.

  1. Does the program’s 1001-point maximum prove a uniform approximation bound?

Answer 4: No. Points between grid samples and outside the sampled interval need separate control.

Keep the version and the function explicit

GELU’s first arXiv submission was 2016-06-27; the version read here is v 5 dated 2023-06-06. The SiLU paper was first submitted 2017-02-10; we use v 3 dated 2017-11-02. A later manuscript’s wording is not evidence of naming priority in an earlier year. In the SiLU paper, dSiLU is a separate activation whose forward value is the SiLU derivative, not just a label for a software backward pass.

This chapter adds the gate-moment counterexample, bracket arguments, approximation derivative and numerical audit to the broader activation overview. The calculations are original; source code, figures and empirical tables were not copied. Next inspect how these outputs enter a forward pass.

Make a prediction, then check

What separates the expected square of a gated input from its squared mean?

Choose one answer

Learning objectives

  • Distinguish a deterministic expected gate from its random counterpart.
  • Differentiate an approximation and interpret a sampled error audit.

Prerequisites & connections

Explore related knowledge →

References

  1. Gaussian Error Linear Units (GELUs)
    Dan Hendrycks; Kevin Gimpel · 2016
  2. Sigmoid-Weighted Linear Units for Neural Network Function Approximation in Reinforcement Learning
    Stefan Elfwing; Eiji Uchibe; Kenji Doya · 2017

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-06 · Codex single-agent authored technical review: cited primary-source scope, explicit assumptions, original calculations and counterexamples, runnable tests and bilingual review; not independent human or second-agent review.

  • Single-agent authored technical review: bounded primary-source locations, assumptions, original derivations, exact/literal references and matching bilingual equations/examples/exercises. Not independent human or second-agent review.
  • Four focused CPython3.12.4 tests passed per chapter. Rectifier update paths, smooth-gate moments/stationary points, batch intermediates and weighted Bernoulli optima are checked against literal references, analytic identities and finite differences. Forward-pass example uses pinned NumPy1.26.4; other examples use the standard library.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.