Skip to content

7.3 Activation Functions and Their Derivatives

A model with hidden layers, such as the MLP of Module system and basic layers in AI Engineering, and later recurrent cells and transformer blocks, computes a matrix product followed by an activation function at every layer. The autograd engine in The op library and gradcheck_all needs both halves of every activation: the function for the forward pass and its derivative for the backward pass. Get a derivative wrong and the model still trains, slowly and to a worse loss, with no error anywhere. Get the forward pass numerically careless and one large logit after a bad optimizer step turns the whole batch into NaN.

Concepts from other sections (12)

This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.

  • Product rule / quotient rule: (fg)′=f′g+fg′(fg)' = f'g + fg' and (f/g)′=(f′g−fg′)/g2(f/g)' = (f'g - fg')/g^2, the rules for differentiating a product or a ratio of two functions. Read more: Chapter 7: Calculus 1
  • Continuous function / continuity: ff is continuous at aa when lim⁡x→af(x)=f(a)\lim_{x \to a} f(x) = f(a), so the graph has no jump or hole there; many theorems of calculus, such as the intermediate value theorem, require it. Read more: Chapter 7: Calculus 1
  • chain rule: ddxf(g(x))=f′(g(x)) g′(x)\frac{d}{dx} f(g(x)) = f'(g(x))\, g'(x). Read more: 7.5 Calculus 1 Problem Set
  • Logistic regression: a model P(y=1∣x)=σ(w⋅x)P(y = 1 \mid x) = \sigma(w \cdot x) in which the log-odds are linear in the features. Read more: 13.8 Logistic regression (IRLS), ROC-AUC, calibration (ECE)
  • Standard normal: the distribution N(0,1)\mathcal{N}(0, 1) with density 12πe−z2/2\frac{1}{\sqrt{2\pi}} e^{-z^2/2}. Read more: 13.1 Random variables, expectation, variance, and normal draws by Box-Muller
  • Cumulative distribution function (CDF): F(x)=P(X≤x)F(x) = P(X \le x), defined for every random variable, discrete or continuous; it rises from 0 to 1, and for a continuous variable its derivative is the density. Read more: Chapter 13: Probability and Statistics
  • SwiGLU: a gated MLP, (Swish(xW)⊙xV)W2(\text{Swish}(xW) \odot xV)W_2, that replaced the ReLU feed-forward block. Read more: 5.3 Model landscape and lifecycle in AI Engineering
  • op library (F): the module of differentiable functions, each a NumPy forward plus one closed-form VJP joined by from_op. Read more: 6.3 The op library and gradcheck_all in AI Engineering
  • Gradcheck: a comparison of a hand-written gradient against central differences of ∑f(x)⊙g\sum f(x) \odot g. Read more: 3.3 Oracles, golden and differential tests, gradcheck as a test in Software Engineering
  • Automatic differentiation / autodiff: computing exact derivatives of a program by applying the chain rule to each primitive operation it executes, in forward mode (Jacobian-vector products) or reverse mode (vector-Jacobian products); it is how neural networks get their gradients, with no step size and no symbolic formula. Read more: Chapter 14: Matrix Calculus and Autodiff
  • BF16: a 16-bit float with float32’s sign and exponent and 7 mantissa bits; the top half of a rounded float32. Read more: 6.7 Safetensors for every dtype, atomic checkpoints, and the token stream in AI Engineering
  • subgradient: a valid gradient choice at a non-differentiable point, such as a tie in max pooling. Read more: 14.1 Conv layers and pooling on autograd in AI Engineering

This section derives each common activation and its derivative from the rules of calculus, writes them so that no input can overflow, and checks them against PyTorch at 1000 points from −40-40 to 4040. The finished code is course/solutions/python/tinyllm/num/activations.py, which provides sigmoid, tanh, relu, softplus, gelu_tanh, gelu_erf, and silu, each with its derivative d<name>. The contract is course/contracts/py/tinyllm/num/activations.pyi.

The derivatives rest on Derivatives and finite differences and the exponentials on Exponents, logs, and units of information. The exact GELU calls erf_series from Taylor series, the one piece of code you need from another section.

Learning objectives

  • Explain why a network needs a nonlinearity between linear layers.
  • Derive the derivatives of sigmoid, tanh, softplus, SiLU, and both GELUs from the exponential, quotient, chain, and product rules.
  • Evaluate sigmoid and softplus from e−∣x∣e^{-|x|} so that no finite input overflows, and keep full relative accuracy in the tails.
  • Distinguish the exact and tanh-approximate GELU and state the convention for relu′(0)\mathrm{relu}'(0).
  • Implement every activation so that it preserves the input’s shape and float32 or float64 dtype.

A linear layer computes y=Wx+by = Wx + b. Two in a row compute W2(W1x+b1)+b2=(W2W1)x+(W2b1+b2)W_2(W_1 x + b_1) + b_2 = (W_2 W_1)x + (W_2 b_1 + b_2): again one linear layer, so depth would add nothing. Inserting a nonlinear ff between them, W2f(W1x+b1)+b2W_2 f(W_1 x + b_1) + b_2, breaks the collapse, and with enough hidden units such networks can approximate any continuous function on a bounded set. Every ff below is applied elementwise: the input xx is a float32 or float64 array, the output has the same shape, and output ii depends only on input ii. Training needs each activation’s derivative, which the chain rule multiplies into every gradient.

The logistic sigmoid σ(x)=11+e−x\sigma(x) = \frac{1}{1 + e^{-x}} squashes the line into (0,1)(0, 1): σ(0)=12\sigma(0) = \frac12, σ(x)→1\sigma(x) \to 1 as x→∞x \to \infty, σ(x)→0\sigma(x) \to 0 as x→−∞x \to -\infty, and σ(−x)=1−σ(x)\sigma(-x) = 1 - \sigma(x). It turns a score into a probability, as in the LSTM gates of LSTM and in logistic regression in Logistic regression, ROC-AUC, and calibration. Its derivative follows from the chain rule on (1+e−x)−1(1 + e^{-x})^{-1}:

σ′(x)=e−x(1+e−x)2=11+e−x⋅e−x1+e−x=σ(x) σ(−x)=σ(x)(1−σ(x)).\sigma'(x) = \frac{e^{-x}}{(1 + e^{-x})^2} = \frac{1}{1 + e^{-x}} \cdot \frac{e^{-x}}{1 + e^{-x}} = \sigma(x)\,\sigma(-x) = \sigma(x)(1 - \sigma(x)) .

The hyperbolic tangent, tanh⁡x=ex−e−xex+e−x\tanh x = \frac{e^x - e^{-x}}{e^x + e^{-x}}, is a rescaled sigmoid, tanh⁡x=2σ(2x)−1\tanh x = 2\sigma(2x) - 1, with range (−1,1)(-1, 1). By the quotient rule, tanh⁡′x=1−tanh⁡2x\tanh' x = 1 - \tanh^2 x.

The formulas are easy. Evaluating them safely in floating point takes two more ideas.

For x=−1000x = -1000, e−x=e1000e^{-x} = e^{1000} overflows to inf. The value 1/(1+∞)=01/(1 + \infty) = 0 happens to be right, but the overflow raises a floating-point warning (an error under np.errstate(over="raise")), and the same pattern elsewhere produces $\infty / \infty = $ NaN. The fix uses only z=e−∣x∣∈(0,1]z = e^{-|x|} \in (0, 1], which can never overflow:

σ(x)={11+zx≥0z1+zx<0\sigma(x) = \begin{cases} \frac{1}{1 + z} & x \ge 0 \\ \frac{z}{1 + z} & x < 0 \end{cases}

The second line is the first with numerator and denominator multiplied by exe^{x}.

σ′(30)=9.3576×10−14\sigma'(30) = 9.3576 \times 10^{-14}. Computed as s(1−s)s(1 - s) with s=σ(30)=1−9.36×10−14s = \sigma(30) = 1 - 9.36 \times 10^{-14}, the subtraction 1−s1 - s leaves only the last few bits of ss, and the result is 9.348×10−149.348 \times 10^{-14}: three correct digits. σ(30)σ(−30)\sigma(30)\sigma(-30) never subtracts and keeps all sixteen. Tiny derivatives matter because the chain rule multiplies them into other factors.

relu(x)=max⁡(x,0)\mathrm{relu}(x) = \max(x, 0) is the identity for positive inputs and zero otherwise; its derivative is 1 for x>0x > 0 and 0 for x<0x < 0. At x=0x = 0 the graph has a corner and no derivative exists. Frameworks pick a value: PyTorch uses 0, and so does this book, because a gradient that differs from the framework’s exactly at zeros makes gradients disagree with any checkpoint’s training history there.

softplus(x)=ln⁡(1+ex)\mathrm{softplus}(x) = \ln(1 + e^x) is a smooth relu: about xx for large xx, about exe^x for very negative xx. Its derivative is ex1+ex=σ(x)\frac{e^x}{1 + e^x} = \sigma(x). Computed naively, ln⁡(1+e1000)\ln(1 + e^{1000}) overflows, and ln⁡(1+e−40)\ln(1 + e^{-40}) gives exactly 0 because 1+4.2×10−181 + 4.2 \times 10^{-18} rounds to 1. The stable form splits off the large part and uses log1p, which computes ln⁡(1+u)\ln(1 + u) accurately for tiny uu:

softplus(x)=max⁡(x,0)+log1p⁡ ⁣(e−∣x∣).\mathrm{softplus}(x) = \max(x, 0) + \operatorname{log1p}\!\left(e^{-|x|}\right) .

The Gaussian error linear unit weights its input by the probability that a standard normal variable is below it. With Φ(x)=12(1+erf⁡(x/2))\Phi(x) = \frac{1}{2}\left(1 + \operatorname{erf}(x/\sqrt 2)\right) the standard normal CDF, φ(x)=12πe−x2/2\varphi(x) = \frac{1}{\sqrt{2\pi}} e^{-x^2/2} its density (note Φ′=φ\Phi' = \varphi), and erf⁡(z)=2π∫0ze−t2 dt\operatorname{erf}(z) = \frac{2}{\sqrt\pi}\int_0^z e^{-t^2}\,dt:

gelu(x)=x Φ(x)=x2(1+erf⁡x2),gelu′(x)=Φ(x)+x φ(x)\mathrm{gelu}(x) = x\,\Phi(x) = \frac{x}{2}\left(1 + \operatorname{erf}\frac{x}{\sqrt 2}\right), \qquad \mathrm{gelu}'(x) = \Phi(x) + x\,\varphi(x)

by the product rule. The solution’s gelu_erf computes erf with erf_series. Before erf was fast on GPUs, GPT-2 and BERT used a tanh approximation:

gelutanh⁡(x)=x2(1+tanh⁡u),u=2/π (x+0.044715 x3).\mathrm{gelu}_{\tanh}(x) = \frac{x}{2}\left(1 + \tanh u\right), \quad u = \sqrt{2/\pi}\,(x + 0.044715\, x^3) .

Its derivative needs the product rule and the chain rule: 12(1+tanh⁡u)+x2(1−tanh⁡2u) u′\frac12(1 + \tanh u) + \frac{x}{2}(1 - \tanh^2 u)\,u', with u′=2/π(1+3⋅0.044715 x2)u' = \sqrt{2/\pi}(1 + 3 \cdot 0.044715\, x^2). The two GELUs are different functions, differing by up to 4.7×10−44.7 \times 10^{-4} (near x=2.7x = 2.7), so a checkpoint trained with one must be served with the same one. For ∣x∣>10|x| > 10, tanh⁡u\tanh u is already ±1\pm 1 exactly, while x3x^3 would overflow for ∣x∣>10102|x| > 10^{102} (7×10127 \times 10^{12} in float32), so xx is clamped to [−10,10][-10, 10] inside uu. Likewise φ\varphi underflows to 0 beyond ∣x∣=40|x| = 40, and x2x^2 inside it is clamped there.

silu(x)=x σ(x)\mathrm{silu}(x) = x\,\sigma(x), also called swish, is the gate inside SwiGLU, the MLP of Llama-family models covered in Gated MLPs: SwiGLU and GeGLU. By the product rule,

silu′(x)=σ(x)+x σ(x)(1−σ(x))=σ(x)(1+x σ(−x)).\mathrm{silu}'(x) = \sigma(x) + x\,\sigma(x)(1 - \sigma(x)) = \sigma(x)\left(1 + x\,\sigma(-x)\right) .

Forgetting the product rule and writing σ(x)\sigma(x) alone is the classic bug: it is right at x=0x = 0 and wrong everywhere else.

A few identities give an independent check of signs and symmetry at any point: σ(x)+σ(−x)=1\sigma(x) + \sigma(-x) = 1; tanh⁡x=2σ(2x)−1\tanh x = 2\sigma(2x) - 1; and for ff in {softplus,silu,gelu,gelutanh⁡}\{\mathrm{softplus}, \mathrm{silu}, \mathrm{gelu}, \mathrm{gelu}_{\tanh}\}, f(x)−f(−x)=xf(x) - f(-x) = x. Each of the last group is xx times something that adds to 1 at ±x\pm x, or for softplus, ln⁡1+ex1+e−x=ln⁡ex\ln\frac{1 + e^x}{1 + e^{-x}} = \ln e^x. These hold for every xx.

Dtypes deserve the same care as values. A float32 tensor stays float32 and a float64 tensor stays float64: promoting silently doubles memory and breaks the bit-for-bit comparisons with the C kernels later in AI Engineering. Integer input is computed in float64. The GELU with erf is computed in float64 internally and cast back.

At x=1x = 1, with e−1=0.3678794e^{-1} = 0.3678794, every function and most derivatives can be computed on paper:

FunctionComputationValueDerivativeValue
sigmoid1/1.36787941 / 1.36787940.73105860.7310586×0.26894140.7310586 \times 0.26894140.1966119
tanh2σ(2)−12\sigma(2) - 10.76159421−0.761594221 - 0.7615942^20.4199743
relumax⁡(1,0)\max(1, 0)1x>0x > 01
softplusln⁡(1+2.7182818)\ln(1 + 2.7182818)1.3132617σ(1)\sigma(1)0.7310586
silu1×0.73105861 \times 0.73105860.73105860.7310586×(1+0.2689414)0.7310586 \times (1 + 0.2689414)0.9276705
gelu (erf)1×Φ(1)1 \times \Phi(1)0.8413447Φ(1)+φ(1)=0.8413447+0.2419707\Phi(1) + \varphi(1) = 0.8413447 + 0.24197071.0833155
gelu (tanh)u=0.7978846×1.044715=0.8335620u = 0.7978846 \times 1.044715 = 0.8335620, 12(1+tanh⁡u)=12(1+0.6823840)\frac12(1 + \tanh u) = \frac12(1 + 0.6823840)0.8411920(formula above)

The exact and approximate GELU differ by 1.5×10−41.5 \times 10^{-4} here.

Each activation comes with its derivative:

def sigmoid(x: ArrayLike) -> NDArray: ... # and dsigmoid
def tanh(x: ArrayLike) -> NDArray: ... # and dtanh
def relu(x: ArrayLike) -> NDArray: ... # and drelu (0 at x = 0)
def softplus(x: ArrayLike) -> NDArray: ... # and dsoftplus (= sigmoid)
def gelu_tanh(x: ArrayLike) -> NDArray: ... # and dgelu_tanh
def gelu_erf(x: ArrayLike) -> NDArray: ... # and dgelu_erf, through erf_series (M02.1)
def silu(x: ArrayLike) -> NDArray: ... # and dsilu

Every function keeps the shape and the float32 or float64 dtype of its input, returns finite values for finite inputs, and emits no overflow, invalid, or divide warning.

Seven decisions shape the implementation.

  1. Fix the dtype once, at the door. float32 stays float32, float64 stays float64, anything else becomes float64. One helper does this, and every constant afterwards is built in the input’s dtype (x.dtype.type(1)) so that no scalar silently promotes the array.
  2. Build sigmoid from e−∣x∣e^{-|x|}. The only exponential that cannot overflow for every finite xx is z=e−∣x∣∈(0,1]z = e^{-|x|} \in (0, 1]. Both 11+z\frac{1}{1+z} (for x≥0x \ge 0) and z1+z\frac{z}{1+z} (for x<0x < 0) are then bounded, warning-free expressions.
  3. Write derivatives without subtracting from 1. σ′=σ(x)σ(−x)\sigma' = \sigma(x)\sigma(-x) is a product of two accurately computed numbers; σ(1−σ)\sigma(1 - \sigma) subtracts a number close to 1 and loses the tail. The same idea gives silu′=σ(x)(1+xσ(−x))\mathrm{silu}' = \sigma(x)(1 + x\sigma(-x)).
  4. Compute softplus by splitting off the large part. ln⁡(1+ex)=max⁡(x,0)+ln⁡(1+e−∣x∣)\ln(1 + e^x) = \max(x, 0) + \ln(1 + e^{-|x|}), and the second term is log1p of a number in (0,1](0, 1]: no overflow, and full accuracy when e−∣x∣e^{-|x|} is tiny. Its derivative is exactly σ\sigma, so it reuses sigmoid.
  5. Settle ReLU’s kink by convention. relu′(x)=[x>0]\mathrm{relu}'(x) = [x > 0], strict, so the value at 0 is 0, matching PyTorch.
  6. Clamp inside the tanh-GELU. tanh⁡u\tanh u is exactly ±1\pm1 in float64 once ∣x∣>10|x| > 10, so clamping xx to [−10,10][-10, 10] inside uu changes no result and removes the overflow of x3x^3. The outer xx is not clamped: it multiplies 12(1+tanh⁡u)\tfrac12(1 + \tanh u) and must keep its true value.
  7. Compute the exact GELU in float64. Φ\Phi comes from erf_series, which works in float64; computing in float64 and casting back once gives float32 callers a correctly rounded result rather than float32 rounding inside the series. The density φ\varphi squares xx, so xx is clamped to [−40,40][-40, 40] there, beyond which e−x2/2e^{-x^2/2} is 0 anyway.

The dtype helper and sigmoid come first:

def _arr(x: ArrayLike) -> NDArray:
"""x as a float array: float32 and float64 keep their dtype."""
a = np.asarray(x)
if a.dtype in (np.float32, np.float64):
return a
return a.astype(np.float64) # ints, bools, float16 compute in float64
def sigmoid(x: ArrayLike) -> NDArray:
x = _arr(x)
# exp(-|x|) is in (0, 1]: it can never overflow. For x >= 0 that is
# 1 / (1 + e^-x); for x < 0 multiply top and bottom by e^x.
z = np.exp(-np.abs(x))
one = x.dtype.type(1) # a 1 of the input's dtype: no promotion
return np.where(x >= 0, one / (one + z), z / (one + z))
def dsigmoid(x: ArrayLike) -> NDArray:
x = _arr(x)
# s(x)(1 - s(x)) = s(x) s(-x). The second form never subtracts from 1,
# so dsigmoid(30) keeps its relative accuracy instead of 1e-3.
return sigmoid(x) * sigmoid(-x)

np.where evaluates both branches on every element and then picks one. That is why both branches must be safe for all xx, not only for the half where they are selected: with z∈(0,1]z \in (0, 1], both 1/(1+z)1/(1+z) and z/(1+z)z/(1+z) are. The naive np.where(x >= 0, 1/(1+np.exp(-x)), ...) would still compute np.exp(-x) for x=−1000x = -1000 and warn.

Tanh, ReLU, and softplus are short:

def dtanh(x: ArrayLike) -> NDArray:
t = np.tanh(_arr(x)) # np.tanh is already overflow-safe
return t.dtype.type(1) - t * t # 1 - tanh^2
def drelu(x: ArrayLike) -> NDArray:
x = _arr(x)
return (x > 0).astype(x.dtype) # strict: the derivative at the kink is 0
def softplus(x: ArrayLike) -> NDArray:
x = _arr(x)
# max(x, 0) carries the large part; log1p(e^-|x|) is in (0, ln 2] and accurate when tiny
return np.maximum(x, x.dtype.type(0)) + np.log1p(np.exp(-np.abs(x)))
def dsoftplus(x: ArrayLike) -> NDArray:
return sigmoid(x) # d/dx log(1 + e^x) = e^x / (1 + e^x)

For x=−40x = -40, softplus returns 0+log1p⁡(4.25×10−18)=4.25×10−180 + \operatorname{log1p}(4.25 \times 10^{-18}) = 4.25 \times 10^{-18}, all digits correct, where ln⁡(1+e−40)\ln(1 + e^{-40}) would round 1+4.25×10−181 + 4.25 \times 10^{-18} to 1 and return 0.

The tanh-GELU applies the clamp in one helper:

def _gelu_u(x: NDArray) -> NDArray:
"""sqrt(2/pi) (x + 0.044715 x^3) with x clamped to [-10, 10]: tanh is
already +-1 there (u(10) = 43.6), and x^3 would overflow for |x| > 1e102
(|x| > 7e12 in float32)."""
t = x.dtype.type
xc = np.clip(x, t(-GELU_CLAMP), t(GELU_CLAMP))
return t(GELU_C) * (xc + t(GELU_A) * xc * xc * xc)
def gelu_tanh(x: ArrayLike) -> NDArray:
x = _arr(x)
t = x.dtype.type
return t(0.5) * x * (t(1) + np.tanh(_gelu_u(x))) # unclamped outer x
def dgelu_tanh(x: ArrayLike) -> NDArray:
x = _arr(x)
t = x.dtype.type
xc = np.clip(x, t(-GELU_CLAMP), t(GELU_CLAMP))
th = np.tanh(_gelu_u(x))
du = t(GELU_C) * (t(1) + t(3 * GELU_A) * xc * xc) # u'(x), on the clamped x
# product rule on 0.5 x (1 + tanh u), with tanh' = 1 - tanh^2
return t(0.5) * (t(1) + th) + t(0.5) * x * (t(1) - th * th) * du

Beyond the clamp, th is exactly ±1\pm 1, so 1−th2=01 - \text{th}^2 = 0 and the second term is 00 whatever du is; the derivative is then exactly 1 (for x>10x > 10) or 0 (for x<−10x < -10), as it should be. Writing t(0.5) * x first also keeps 12x⋅2\tfrac12 x \cdot 2 finite at the largest float, where x * 2 would overflow.

The exact GELU works in float64 and casts back once:

def _phi_cdf(x: NDArray) -> NDArray:
"""Phi(x) = (1 + erf(x / sqrt 2)) / 2 in float64."""
return 0.5 * (1.0 + erf_series(x.astype(np.float64) / math.sqrt(2.0), ERF_TERMS))
def gelu_erf(x: ArrayLike) -> NDArray:
x = _arr(x)
return (x.astype(np.float64) * _phi_cdf(x)).astype(x.dtype) # one cast back at the end
def dgelu_erf(x: ArrayLike) -> NDArray:
x = _arr(x)
xd = x.astype(np.float64)
xc = np.clip(xd, -PDF_CLAMP, PDF_CLAMP) # xd * xd overflows for |x| > 1e154
pdf = np.exp(-0.5 * xc * xc) / math.sqrt(2.0 * math.pi)
return (_phi_cdf(x) + xd * pdf).astype(x.dtype) # Phi + x phi

ERF_TERMS = 160 is the series length that Taylor series shows is enough for 3×10−153 \times 10^{-15} accuracy on the whole line.

SiLU closes the set:

def silu(x: ArrayLike) -> NDArray:
x = _arr(x)
return x * sigmoid(x)
def dsilu(x: ArrayLike) -> NDArray:
x = _arr(x)
# d/dx [x s(x)] = s(x) + x s(x) (1 - s(x)) = s(x) (1 + x s(-x))
return sigmoid(x) * (x.dtype.type(1) + x * sigmoid(-x))

At x=1x = 1: σ(1)(1+1⋅σ(−1))=0.7310586×1.2689414=0.9276705\sigma(1)(1 + 1 \cdot \sigma(-1)) = 0.7310586 \times 1.2689414 = 0.9276705, the table’s value. At x=1030x = 10^{30}, σ(−x)=0\sigma(-x) = 0 (its zz underflows to 0, quietly), so dsilu is exactly 1. The full solution is in activations.py.

Every function is O(n)O(n) elementwise work. sigmoid computes one exponential per element and both np.where branches; gelu_erf is the expensive one, a 160-term series per element, which is acceptable for a reference implementation and is exactly why production code uses minimax erf.

np.where with safe branches beats masking. Boolean indexing (out[x >= 0] = ...) also avoids computing the wrong branch, but costs copies and more code, and is easy to get wrong for 0-d inputs. With z=e−∣x∣z = e^{-|x|} both branches are safe everywhere, so the simple form is correct.

Clamping beats np.errstate. Suppressing overflow warnings would hide the problem but still produce inf intermediates, which turn into NaN the moment they meet a 0 (for example ∞⋅0\infty \cdot 0 in the derivative). Clamping where the result is already saturated changes nothing numerically and produces no inf at all.

Only the erf path uses float64. Running everything in float64 would break the float32 comparisons with the C kernels and double memory; running erf_series in float32 would lose accuracy in a 160-term sum. The solution promotes only where the algorithm needs it and casts back once.

One tradeoff is accepted knowingly. dtanh uses 1−tanh⁡21 - \tanh^2, which subtracts from 1 in the tails: tanh⁡′(20)\tanh'(20) is computed as exactly 0 instead of about 1.7×10−171.7 \times 10^{-17}. PyTorch uses the same formula, and the golden comparison is against PyTorch, so matching it is the right choice here.

A correct solution reproduces the hand-worked table at 1 for sigmoid, tanh, relu, softplus, and SiLU, plus both GELUs and the exact GELU’s derivative, which shows the two GELUs are not interchangeable. Each function and derivative must match PyTorch autograd at 1000 points in [−40,40][-40, 40] to float64 tolerances, because the op library is checked against PyTorch forward and backward. Each smooth derivative must also pass the frozen central-difference gradcheck, which shows the derivative belongs to its function and not just to a formula; relu’s derivative is checked the same way away from 0. The identities must hold at 500 seeded points, catching sign and symmetry slips. In the tails, σ′(±30)\sigma'(\pm 30) and softplus(−40)\mathrm{softplus}(-40) must be correct to 14 digits, because tiny gradients still multiply other factors. No finite input may overflow: ±1030\pm 10^{30} and the largest float, in float32 and float64, with warnings raised as errors, because one bad logit must not become NaN. float32 stays float32, shapes are kept, integers become float64, and relu′(0)=0\mathrm{relu}'(0) = 0.

These are the mistakes that break those checks:

PitfallSymptomHow the solution avoids it
exponentials that can overflow: 1/(1+e−x)1/(1 + e^{-x}), ln⁡(1+ex)\ln(1 + e^x), an unclamped x3x^3overflow warnings, inf, or NaN at x=±1000x = \pm 1000only e−∣x∣e^{-\lvert x\rvert} is ever exponentiated; xx is clamped inside uu and inside φ\varphi
subtracting from 1 in the tails: σ(1−σ)\sigma(1 - \sigma), ln⁡(1+e−40)\ln(1 + e^{-40})three correct digits at x=30x = 30; softplus(−40)=0\mathrm{softplus}(-40) = 0sigmoid(x) * sigmoid(-x) and log1p
relu′(0)=1\mathrm{relu}'(0) = 1gradients differ from PyTorch’s exactly at zeros(x > 0), strict
using the tanh approximation for the exact GELU (or the reverse)1.5×10−41.5 \times 10^{-4} off at x=1x = 1; a loaded checkpoint driftstwo separate functions, gelu_erf through erf_series and gelu_tanh through np.tanh
forgetting the product rule: silu′=σ\mathrm{silu}' = \sigma, gelutanh⁡′\mathrm{gelu}_{\tanh}' without the tanh⁡′\tanh' termright at 0, wrong everywhere elsedsilu has the xσ(−x)x\sigma(-x) term; dgelu_tanh has both product-rule terms
promoting float32 to float64a float64 array where the kernel expects float32_arr keeps float32; constants built with x.dtype.type; erf path casts back
dropping the square in 1−tanh⁡21 - \tanh^2tanh⁡′(1)=0.238\tanh'(1) = 0.238 instead of 0.420t.dtype.type(1) - t * t
a wrong GELU constant (0.0447 for 0.044715)the 6th digit of every GELUGELU_A = 0.044715
subtracting the log1p term in softplussoftplus(1)=0.687\mathrm{softplus}(1) = 0.687np.maximum(x, 0) + np.log1p(...)

Warning: A missing product-rule term does not crash training. The model learns, just worse, so a derivative bug can survive for a long time unless something like gradcheck compares it against the function.

Dual numbers and forward-mode autodiff computes the same derivatives by forward-mode automatic differentiation, and its tests compare them with these closed forms to 10−1510^{-15}. In AI Engineering, The op library and gradcheck_all wraps them as the elementwise ops of tinyllm.F, forward and backward; LSTM uses sigmoid for the input, forget, and output gates and tanh for the cell; Gated MLPs: SwiGLU and GeGLU computes SwiGLU =silu(xW)⊙xV= \mathrm{silu}(xW) \odot xV; and Elementwise kernels in C ports SiLU to C as tl_silu_mul_f32, checked against this Python.

  • OpenStax, Calculus Volume 1 (free), sections 3.3 to 3.6 (derivative rules, the chain rule) and 3.9 (exponential and logarithm).
  • Hendrycks and Gimpel, “Gaussian Error Linear Units” (2016).
  • Ramachandran, Zoph, and Le, “Searching for Activation Functions” (2017): SiLU, also called swish.
  • PyTorch torch.nn.functional (aten/src/ATen/native/Activation.cpp, cuda/ActivationGeluKernel.cu): fused CUDA kernels, autocast to bf16, in-place variants.
  • PyTorch F.softplus(beta, threshold) (aten/src/ATen/native/cpu/Activation.cpp): returns xx above a threshold (default 20) instead of computing the log, trading 2×10−92 \times 10^{-9} for speed.
  • erf in libm and erff on GPUs (glibc sysdeps/ieee754/dbl-64/s_erf.c): minimax rational approximations accurate to a few ulps everywhere.
  • llama.cpp ggml_silu and ggml_gelu (ggml/src/ggml-cpu/vec.h): lookup tables for f16 GELU and vectorized SiLU.
  • activation function: a nonlinear function applied elementwise between linear layers.
  • sigmoid: σ(x)=11+e−x\sigma(x) = \frac{1}{1 + e^{-x}}, mapping the real line into (0,1)(0, 1), with σ′=σ(x)σ(−x)\sigma' = \sigma(x)\sigma(-x).
  • softplus: ln⁡(1+ex)\ln(1 + e^x), a smooth relu whose derivative is σ\sigma.
  • GELU: x Φ(x)x\,\Phi(x), the input weighted by the standard normal CDF; its tanh approximation is a different function.
  • SiLU (swish): x σ(x)x\,\sigma(x), the gate inside SwiGLU.
  • relative accuracy: the number of correct significant digits, which subtraction of nearly equal numbers destroys.
  • log1p: a library function computing ln⁡(1+u)\ln(1 + u) accurately for tiny uu.
  • An activation is a nonlinear function applied elementwise between linear layers; without one, any stack of layers is a single matrix. Training needs each one’s derivative, which the chain rule multiplies into every gradient.
  • The derivatives come from three rules: (ex)′=ex(e^x)' = e^x, the quotient or chain rule, and the product rule, giving σ′=σ(x)σ(−x)\sigma' = \sigma(x)\sigma(-x), tanh⁡′=1−tanh⁡2\tanh' = 1 - \tanh^2, softplus′=σ\mathrm{softplus}' = \sigma, silu′=σ(x)(1+xσ(−x))\mathrm{silu}' = \sigma(x)(1 + x\sigma(-x)), and gelu′=Φ+xφ\mathrm{gelu}' = \Phi + x\varphi.
  • Overflow is avoided, not silenced: e−∣x∣e^{-|x|} never overflows, so sigmoid and softplus are written in terms of it, and every function is finite and warning-free at x=±1030x = \pm 10^{30} in float32 and float64.
  • Writing σ′\sigma' as σ(x)σ(−x)\sigma(x)\sigma(-x) instead of σ(1−σ)\sigma(1 - \sigma) keeps full relative accuracy in the tails.
  • The two GELUs are different functions (they differ in the fourth digit at x=1x = 1), and relu′(0)=0\mathrm{relu}'(0) = 0 by convention: match the checkpoint you load.
  1. Why does sigmoid use e−∣x∣e^{-|x|} in both branches of np.where, rather than e−xe^{-x} in one and exe^{x} in the other?

    Answer

    np.where evaluates both branch expressions for every element before choosing. With e−xe^{-x} in one branch and exe^{x} in the other, one of them overflows for every large ∣x∣|x| even though its result is discarded, raising a warning (or an error under np.errstate(over="raise")). e−∣x∣e^{-|x|} is at most 1 for every input, so neither branch can overflow.

  2. σ(x)(1−σ(x))\sigma(x)(1 - \sigma(x)) and σ(x)σ(−x)\sigma(x)\sigma(-x) are equal on paper. Why does the solution use the second?

    Answer

    At x=30x = 30, σ(x)=1−9.36×10−14\sigma(x) = 1 - 9.36 \times 10^{-14}, and 1−σ(x)1 - \sigma(x) is a subtraction of two numbers that agree in 13 digits: only about 3 correct digits survive. σ(−30)=z/(1+z)\sigma(-30) = z/(1+z) with z=e−30z = e^{-30} is computed directly to full relative precision, and multiplying two accurate numbers loses nothing.

  3. In gelu_tanh, xx is clamped inside uu but not in the outer factor. What would clamping the outer xx do?

    Answer

    For x>10x > 10, gelu(x)=x\mathrm{gelu}(x) = x to float precision. Clamping the outer factor would return 1010 for every x>10x > 10, a function that saturates instead of growing linearly, with derivative 0 instead of 1. The clamp is safe only where its effect is invisible: inside tanh⁡u\tanh u, which is already ±1\pm 1.

  4. Why is relu′(0)\mathrm{relu}'(0) defined as 0, when the derivative does not exist there?

    Answer

    Any value in [0,1][0, 1] is a valid subgradient, so the choice is a convention. Exact zeros are common in practice (padding, relu of a relu, quantized inputs), and the gradients there must match the framework the checkpoint and the reference implementation use. PyTorch uses 0, so drelu uses the strict comparison x > 0.

  5. Why does gelu_erf convert to float64 and back, while gelu_tanh stays in the input dtype?

    Answer

    gelu_tanh uses only np.tanh and a few multiplications, which are accurate in either dtype and must match a float32 C kernel operation for operation. gelu_erf calls erf_series, a long sum whose accuracy depends on float64 intermediates; computing it in float32 would add many float32 roundings. Promoting for the computation and casting once at the end gives a float32 result that is the float64 answer correctly rounded, while the output dtype still matches the input.