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: and , the rules for differentiating a product or a ratio of two functions. Read more: Chapter 7: Calculus 1
- Continuous function / continuity: is continuous at when , 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: . Read more: 7.5 Calculus 1 Problem Set
- Logistic regression: a model 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 with density . Read more: 13.1 Random variables, expectation, variance, and normal draws by Box-Muller
- Cumulative distribution function (CDF): , 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, , 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 byfrom_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 . 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 to . 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 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 .
- Implement every activation so that it preserves the input’s shape and float32 or float64 dtype.
Why a nonlinearity
Section titled “Why a nonlinearity”A linear layer computes . Two in a row compute : again one linear layer, so depth would add nothing. Inserting a nonlinear between them, , breaks the collapse, and with enough hidden units such networks can approximate any continuous function on a bounded set. Every below is applied elementwise: the input is a float32 or float64 array, the output has the same shape, and output depends only on input . Training needs each activation’s derivative, which the chain rule multiplies into every gradient.
Sigmoid and tanh
Section titled “Sigmoid and tanh”The logistic sigmoid squashes the line into : , as , as , and . 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 :
The hyperbolic tangent, , is a rescaled sigmoid, , with range . By the quotient rule, .
The formulas are easy. Evaluating them safely in floating point takes two more ideas.
Evaluating without overflow
Section titled “Evaluating without overflow”For , overflows to inf. The value 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 , which can never overflow:
The second line is the first with numerator and denominator multiplied by .
Relative accuracy in the tails
Section titled “Relative accuracy in the tails”. Computed as with , the subtraction leaves only the last few bits of , and the result is : three correct digits. never subtracts and keeps all sixteen. Tiny derivatives matter because the chain rule multiplies them into other factors.
ReLU and softplus
Section titled “ReLU and softplus”is the identity for positive inputs and zero otherwise; its derivative is 1 for and 0 for . At 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.
is a smooth relu: about for large , about for very negative . Its derivative is . Computed naively, overflows, and gives exactly 0 because rounds to 1. The stable form splits off the large part and uses log1p, which computes accurately for tiny :
GELU, exact and approximate
Section titled “GELU, exact and approximate”The Gaussian error linear unit weights its input by the probability that a standard normal variable is below it. With the standard normal CDF, its density (note ), and :
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:
Its derivative needs the product rule and the chain rule: , with . The two GELUs are different functions, differing by up to (near ), so a checkpoint trained with one must be served with the same one. For , is already exactly, while would overflow for ( in float32), so is clamped to inside . Likewise underflows to 0 beyond , and inside it is clamped there.
, 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,
Forgetting the product rule and writing alone is the classic bug: it is right at and wrong everywhere else.
Identities and dtypes
Section titled “Identities and dtypes”A few identities give an independent check of signs and symmetry at any point: ; ; and for in , . Each of the last group is times something that adds to 1 at , or for softplus, . These hold for every .
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.
Working it by hand
Section titled “Working it by hand”At , with , every function and most derivatives can be computed on paper:
| Function | Computation | Value | Derivative | Value |
|---|---|---|---|---|
| sigmoid | 0.7310586 | 0.1966119 | ||
| tanh | 0.7615942 | 0.4199743 | ||
| relu | 1 | 1 | ||
| softplus | 1.3132617 | 0.7310586 | ||
| silu | 0.7310586 | 0.9276705 | ||
| gelu (erf) | 0.8413447 | 1.0833155 | ||
| gelu (tanh) | , | 0.8411920 | (formula above) |
The exact and approximate GELU differ by here.
Designing the interface
Section titled “Designing the interface”Each activation comes with its derivative:
def sigmoid(x: ArrayLike) -> NDArray: ... # and dsigmoiddef tanh(x: ArrayLike) -> NDArray: ... # and dtanhdef 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_tanhdef gelu_erf(x: ArrayLike) -> NDArray: ... # and dgelu_erf, through erf_series (M02.1)def silu(x: ArrayLike) -> NDArray: ... # and dsiluEvery 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.
Building it step by step
Section titled “Building it step by step”Seven decisions shape the implementation.
- 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. - Build sigmoid from . The only exponential that cannot overflow for every finite is . Both (for ) and (for ) are then bounded, warning-free expressions.
- Write derivatives without subtracting from 1. is a product of two accurately computed numbers; subtracts a number close to 1 and loses the tail. The same idea gives .
- Compute softplus by splitting off the large part. , and the second term is
log1pof a number in : no overflow, and full accuracy when is tiny. Its derivative is exactly , so it reusessigmoid. - Settle ReLU’s kink by convention. , strict, so the value at 0 is 0, matching PyTorch.
- Clamp inside the tanh-GELU. is exactly in float64 once , so clamping to inside changes no result and removes the overflow of . The outer is not clamped: it multiplies and must keep its true value.
- Compute the exact GELU in float64. 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 squares , so is clamped to there, beyond which 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 , not only for the half where they are selected: with , both and are. The naive np.where(x >= 0, 1/(1+np.exp(-x)), ...) would still compute np.exp(-x) for 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 , softplus returns , all digits correct, where would round 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) * duBeyond the clamp, th is exactly , so and the second term is whatever du is; the derivative is then exactly 1 (for ) or 0 (for ), as it should be. Writing t(0.5) * x first also keeps 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 phiERF_TERMS = 160 is the series length that Taylor series shows is enough for 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 : , the table’s value. At , (its underflows to 0, quietly), so dsilu is exactly 1. The full solution is in activations.py.
Why this design
Section titled “Why this design”Every function is 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 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 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 , which subtracts from 1 in the tails: is computed as exactly 0 instead of about . PyTorch uses the same formula, and the golden comparison is against PyTorch, so matching it is the right choice here.
What can go wrong
Section titled “What can go wrong”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 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, and must be correct to 14 digits, because tiny gradients still multiply other factors. No finite input may overflow: 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 .
These are the mistakes that break those checks:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
| exponentials that can overflow: , , an unclamped | overflow warnings, inf, or NaN at | only is ever exponentiated; is clamped inside and inside |
| subtracting from 1 in the tails: , | three correct digits at ; | sigmoid(x) * sigmoid(-x) and log1p |
| gradients differ from PyTorch’s exactly at zeros | (x > 0), strict | |
| using the tanh approximation for the exact GELU (or the reverse) | off at ; a loaded checkpoint drifts | two separate functions, gelu_erf through erf_series and gelu_tanh through np.tanh |
| forgetting the product rule: , without the term | right at 0, wrong everywhere else | dsilu has the term; dgelu_tanh has both product-rule terms |
| promoting float32 to float64 | a float64 array where the kernel expects float32 | _arr keeps float32; constants built with x.dtype.type; erf path casts back |
| dropping the square in | instead of 0.420 | t.dtype.type(1) - t * t |
| a wrong GELU constant (0.0447 for 0.044715) | the 6th digit of every GELU | GELU_A = 0.044715 |
| subtracting the log1p term in softplus | np.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.
Where this leads
Section titled “Where this leads”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 . 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 ; and Elementwise kernels in C ports SiLU to C as tl_silu_mul_f32, checked against this Python.
Further reading
Section titled “Further reading”- 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 above a threshold (default 20) instead of computing the log, trading for speed. erfin libm anderffon GPUs (glibcsysdeps/ieee754/dbl-64/s_erf.c): minimax rational approximations accurate to a few ulps everywhere.- llama.cpp
ggml_siluandggml_gelu(ggml/src/ggml-cpu/vec.h): lookup tables for f16 GELU and vectorized SiLU.
Key terms
Section titled “Key terms”- activation function: a nonlinear function applied elementwise between linear layers.
- sigmoid: , mapping the real line into , with .
- softplus: , a smooth relu whose derivative is .
- GELU: , the input weighted by the standard normal CDF; its tanh approximation is a different function.
- SiLU (swish): , the gate inside SwiGLU.
- relative accuracy: the number of correct significant digits, which subtraction of nearly equal numbers destroys.
- log1p: a library function computing accurately for tiny .
Summary
Section titled “Summary”- 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: , the quotient or chain rule, and the product rule, giving , , , , and .
- Overflow is avoided, not silenced: never overflows, so sigmoid and softplus are written in terms of it, and every function is finite and warning-free at in float32 and float64.
- Writing as instead of keeps full relative accuracy in the tails.
- The two GELUs are different functions (they differ in the fourth digit at ), and by convention: match the checkpoint you load.
Review questions
Section titled “Review questions”-
Why does
sigmoiduse in both branches ofnp.where, rather than in one and in the other?Answer
np.whereevaluates both branch expressions for every element before choosing. With in one branch and in the other, one of them overflows for every large even though its result is discarded, raising a warning (or an error undernp.errstate(over="raise")). is at most 1 for every input, so neither branch can overflow. -
and are equal on paper. Why does the solution use the second?
Answer
At , , and is a subtraction of two numbers that agree in 13 digits: only about 3 correct digits survive. with is computed directly to full relative precision, and multiplying two accurate numbers loses nothing.
-
In
gelu_tanh, is clamped inside but not in the outer factor. What would clamping the outer do?Answer
For , to float precision. Clamping the outer factor would return for every , 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 , which is already .
-
Why is defined as 0, when the derivative does not exist there?
Answer
Any value in 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
dreluuses the strict comparisonx > 0. -
Why does
gelu_erfconvert to float64 and back, whilegelu_tanhstays in the input dtype?Answer
gelu_tanhuses onlynp.tanhand a few multiplications, which are accurate in either dtype and must match a float32 C kernel operation for operation.gelu_erfcallserf_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.