Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 4: Neural Network Foundations

Activation functions

P4.440 min●●○ IntermediateReviewed Dec 2, 2026

Why this matters for machine learning

Without a nonlinear activation, any stack of layers is one layer in disguise. The choice of activation also decides how large the gradient is when it travels back through many layers, so it decides how easily a deep network trains.

  • Backpropagation multiplies each gradient by the slope of the activation at that unit, so every local rule in the backward pass uses the slopes you meet here. (P4.8: Backpropagation: step by step with numbers)
  • Vanishing gradients come from many slopes below 1 multiplied together, which is exactly what stacked sigmoids do. (P4.16: Vanishing and exploding gradients)
  • Starting weights are chosen to suit the activation: the right size for a ReLU layer is not the right size for a tanh layer. (P4.12: Weight initialization)
  • The feed-forward part of a transformer block uses an activation, commonly GELU or SiLU in published models. (P7.7: The transformer block, coming soon)

Before this: Multi-layer perceptrons, The sigmoid, tanh and other squashing functions, The chain rule, Random variables

After this lesson you can

  • Explain why a network needs a nonlinearity between its layers, and why it must also have a useful slope
  • State the formula, range, slope, largest slope and flat regions of the step, sigmoid, tanh, ReLU, Leaky ReLU, softplus, ELU, GELU and SiLU, and compute values and slopes by hand
  • Explain saturation, vanishing gradients through stacked sigmoids, and dead ReLU units, and how Leaky ReLU, GELU and SiLU respond to them
  • Choose an activation for hidden layers and for the output layer, and say why softmax is not an ordinary activation

Why does a neural network put a small extra function after every layer, and why does the choice of that function decide how well a deep network trains? Without it, two layers are one matrix and ten are still one (P1.B6, P4.3). Put ReLU(z)=max⁡(0,z)\mathrm{ReLU}(z)=\max(0,z) between two layers and the single matrix can no longer stand in for the network: ReLU(3,−1,2)=(3,0,2)\mathrm{ReLU}(3,-1,2)=(3,0,2) gives (5,2)(5,2) with the matrices of P1.B6, not (5,1)(5,1).

That small step is an activation function. This lesson covers the common choices, what each does to the slope that training depends on, and how to choose.

What an activation function is

A neuron (P4.1) computes a weighted sum of its inputs plus a bias, z=w⋅x+bz=\mathbf{w}\cdot\mathbf{x}+b. Call zz the pre-activation. The neuron then passes zz through a fixed function ff and outputs a=f(z)a=f(z), its activation. For a whole layer, with the weights in a matrix W\mathbf{W} and the biases in b\mathbf{b}:

z=Wx+b,a=f(z).\mathbf{z}=\mathbf{W}\mathbf{x}+\mathbf{b},\qquad \mathbf{a}=f(\mathbf{z}).

The function ff is applied to each entry on its own: ai=f(zi)a_i=f(z_i). It has no weights to learn (one variant in this lesson has a learned slope, noted where it comes up), and the same ff is usually used for all the hidden units of a layer. The whole story of this lesson is the choice of ff.

Why a nonlinearity at all

The matrix example above is the general fact. A linear layer applies x↦Wx+b\mathbf{x}\mapsto\mathbf{W}\mathbf{x}+\mathbf{b}, and a second one gives W2(W1x+b1)+b2\mathbf{W}_2(\mathbf{W}_1\mathbf{x}+\mathbf{b}_1)+\mathbf{b}_2, which is one matrix W2W1\mathbf{W}_2\mathbf{W}_1 and one bias W2b1+b2\mathbf{W}_2\mathbf{b}_1+\mathbf{b}_2. Ten layers are still one (P1.B6). Hidden layers with a nonlinear ff between the matrices do not collapse, and P4.3 shows how such layers bend the plane until a hard task becomes separable. A network with only the linear steps could not even learn XOR (P4.2).

Two requirements follow, and the rest of the lesson keeps coming back to them:

  1. It must not be linear. Any straight-line f(z)=czf(z)=cz would let the layers collapse again.
  2. It needs a useful slope. Training moves each weight by the slope of the loss with respect to it (P1.C5), and the chain rule (P1.C3) multiplies in f′(z)f'(z) for every activation the signal passes. Where f′f' is 0 or tiny, the signal is cut.

Hidden layers and the output layer

A network has hidden layers (between input and output) and an output layer. Hidden activations are chosen to make training work. The output activation is chosen to match what the answer must look like, and a later section treats it. Everything before that section is about hidden units.

The step: the first idea, and why it fails

The perceptron of P4.1 used the step (or threshold) function: output 1 if z≥0z\ge0 and 0 otherwise. Its range is {0,1}\{0,1\}. It gives a clean yes or no, and it is where the idea of a neuron “firing” comes from.

Its slope is the trouble. For z≠0z\ne0 the curve is flat, so the slope is 0, and at z=0z=0 it jumps, so there is no slope (P1.C1). A small nudge to a weight changes zz a little and the output not at all, so the loss does not change and the gradient is 0. Gradient descent has no direction to follow. The perceptron rule of P4.2 trains a single threshold unit by a different update that does not use a gradient, and it does not extend directly to hidden layers. That is why networks trained by backpropagation use a smooth curve in its place, such as the sigmoid, which is the step with its jump rounded off (P1.A5).

Sigmoid and tanh: saturating curves

P1.A5 built both. In short: σ(z)=11+e−z\sigma(z)=\frac{1}{1+\mathrm{e}^{-z}} has range (0,1)(0,1), equals 0.50.5 at 00, and tanh⁡(z)\tanh(z) has range (−1,1)(-1,1) and equals 00 at 00. The two are one curve scaled and shifted: tanh⁡(z)=2σ(2z)−1\tanh(z)=2\sigma(2z)-1. This lesson adds their slopes.

Slopes. From P1.C2, σ′(z)=σ(z) (1−σ(z))\sigma'(z)=\sigma(z)\,(1-\sigma(z)) and tanh⁡′(z)=1−tanh⁡2(z)\tanh'(z)=1-\tanh^2(z). The largest slope is at z=0z=0:

  • σ′(0)=0.5×0.5=14\sigma'(0)=0.5\times0.5=\frac14, so σ′≤14\sigma'\le\frac14 everywhere;
  • tanh⁡′(0)=1−0=1\tanh'(0)=1-0=1, so tanh⁡′≤1\tanh'\le1 everywhere.

(Differentiating tanh⁡(z)=2σ(2z)−1\tanh(z)=2\sigma(2z)-1 gives tanh⁡′(z)=4 σ′(2z)\tanh'(z)=4\,\sigma'(2z), which agrees: 4×14=14\times\frac14=1.)

Saturation. For large ∣z∣|z| the curves are flat: σ′(±6)≈0.0025\sigma'(\pm6)\approx0.0025 and tanh⁡′(±2)≈0.07\tanh'(\pm2)\approx0.07. A unit in that region passes almost no gradient back. This is saturation, and it matters twice. A saturated unit is stuck, because changing its weights barely changes its output. And the slopes multiply along a path of layers (P1.C3):

  • ten sigmoid layers each at their best slope give at most 0.2510≈9.5×10−70.25^{10}\approx9.5\times10^{-7} (the bound P1.A5 and P1.C3 quote, with the weights ignored);
  • tanh does better near 0, with a best slope of 1, but it still saturates.

The effect is vanishing gradients. P4.16 treats it in full, and a widget below shows it.

Zero-centred or not. The sigmoid’s outputs are all positive. The next layer’s weights then see only positive inputs aia_i, and the gradient for weight wiw_i is (gradient at the unit) × ai\times\,a_i. All of a unit’s incoming weights get gradients with the same sign, so in one step they all increase or all decrease together, which makes for a zig-zag path to the best weights. This is one reason often given for preferring tanh, whose outputs are centred on 0, in hidden layers (P1.A5). Other tools reduce the problem too, such as normalization (P4.19).

Cost. Both need an exponential per entry, which is slower than the comparison ReLU needs. In a large layer, the matrix product usually costs much more than the activation.

ReLU: the workhorse

The rectified linear unit is ReLU(z)=max⁡(0,z)\mathrm{ReLU}(z)=\max(0,z): negative inputs become 0, and positive inputs pass unchanged (P1.A1). Its range is [0,∞)[0,\infty).

Its slope is 0 for z<0z<0 and 1 for z>0z>0. For a unit that is on, the signal passes back unchanged by the activation, with no extra factor of 14\frac14 (P1.C3). A unit that is off blocks the signal. Backprop (P4.8) treats it as a gate: gradient times 1 or times 0.

The corner. At exactly z=0z=0 the curve has a corner, so there is no true slope (P1.C5). Software picks a convention. PyTorch’s ReLU gives slope 0 at z=0z=0 (the code below confirms it), and P4.8 uses the same. Once a unit has a nonzero bias and real-valued inputs, zz is rarely exactly 0, so the choice seldom matters in training.

Not linear, only piecewise linear. ReLU is made of two straight pieces, yet it is not a straight line, and that bend is what the opening example used. Where it is flat on the left, it is exactly 0. If zz were a standard Gaussian number, half of the outputs would be exactly 0, because P(Z≤0)=12P(Z\le0)=\frac12 (P1.D2). Many exact zeros is called sparse activation.

The cost: dead units. A unit whose zz is negative for every input in the training data has slope 0 everywhere that matters. It outputs 0, gets zero gradient, and its weights stop changing, so it can stay off. This is a dead ReLU. A tiny example: a unit with w=1w=1 and b=−3b=-3 sees inputs 0.50.5, 11 and 22. Then z=−2.5z=-2.5, −2-2 and −1-1, and the outputs are all 0. Whatever gradient arrives from above is multiplied by 0, so ∂L/∂w=0\partial L/\partial w=0 and ∂L/∂b=0\partial L/\partial b=0. Nothing in the gradient pushes bb back up. How a unit gets there varies (a large update step, a poor start, or a shift in the data), and how often it happens depends on the learning rate, the initialization (P4.12) and the data. It is a known risk, not a certainty. The code below runs this example.

Leaky ReLU, PReLU and ELU: keep some slope on the left

Leaky ReLU replaces the flat left half with a small slope α\alpha (often 0.010.01): f(z)=zf(z)=z for z>0z>0 and f(z)=αzf(z)=\alpha z otherwise. The slope is 11 or α\alpha, and is not 0 when α>0\alpha>0, so a unit that is off still gets a small gradient. In the dead-unit example above, with a gradient of −1-1 arriving for each of the three inputs, a ReLU unit gets ∂L/∂b=0\partial L/\partial b=0 and a Leaky ReLU unit with α=0.01\alpha=0.01 gets ∂L/∂b=−0.03\partial L/\partial b=-0.03, a small push to turn back on (the code below confirms it). The idea was used for acoustic models by Maas, Hannun and Ng (2013). PReLU (He et al., 2015) makes α\alpha a learned parameter, trained by gradient descent like a weight.

ELU (Clevert, Unterthiner and Hochreiter, 2015) is f(z)=zf(z)=z for z>0z>0 and f(z)=α (ez−1)f(z)=\alpha\,(\mathrm{e}^{z}-1) for z≤0z\le0, with α=1\alpha=1 in this lesson. For negative zz it curves smoothly down towards −α-\alpha, so it saturates on the left. With α=1\alpha=1 its slope is 1 on both sides of 0, so it has no corner. It is in the widget but is not covered further.

Softplus: a smooth ReLU

Softplus is f(z)=ln⁡(1+ez)f(z)=\ln(1+\mathrm{e}^{z}). It has no corner, is always positive, and is close to 00 for very negative zz and close to zz for large positive zz. Its value at 0 is ln⁡2≈0.693\ln2\approx0.693 (not 0, so it is a little above ReLU). Its slope is σ(z)\sigma(z): the sigmoid is the slope of the softplus. (P1.C8 uses it as a smooth ReLU.) Because σ(z)<1\sigma(z)<1 for every zz, its slope is below 1 everywhere, so it is a poorer carrier of gradients than ReLU. It is often used when a smooth positive output is needed, more than as a hidden activation.

GELU and SiLU: smooth, self-gated

Both multiply the input by a smooth gate that runs from 0 to 1:

GELU(z)=z Φ(z),SiLU(z)=z σ(z).\begin{aligned} \mathrm{GELU}(z)&=z\,\Phi(z),\\ \mathrm{SiLU}(z)&=z\,\sigma(z). \end{aligned}

Φ(z)\Phi(z) is the cumulative distribution function of a standard Gaussian (P1.D2), the probability that a standard Gaussian number is at most zz. So GELU is “zz times the probability that a Gaussian number lands below it”. For z=0.5z=0.5, Φ(0.5)=0.6915\Phi(0.5)=0.6915 and GELU(0.5)=0.5×0.6915=0.346\mathrm{GELU}(0.5)=0.5\times0.6915=0.346. SiLU uses the sigmoid as its gate: σ(0.5)=0.6225\sigma(0.5)=0.6225 and SiLU(0.5)=0.311\mathrm{SiLU}(0.5)=0.311. For large positive zz the gate is near 1 and the output is near zz, like ReLU. For large negative zz the gate is near 0 and the output is near 0.

Their slopes are GELU′(z)=Φ(z)+z φ(z)\mathrm{GELU}'(z)=\Phi(z)+z\,\varphi(z), with φ\varphi the Gaussian density, and SiLU′(z)=σ(z) (1+z (1−σ(z)))\mathrm{SiLU}'(z)=\sigma(z)\,(1+z\,(1-\sigma(z))). Three things set them apart from ReLU:

  • Smooth. No corner anywhere, so there is no convention to pick.
  • Not monotonic. They dip below 0 and come back. GELU has its lowest value, about −0.170-0.170, near z=−0.75z=-0.75. SiLU has its lowest value, about −0.278-0.278, near z=−1.28z=-1.28. To the left of the dip the slope is negative.
  • Slope can exceed 1. The largest slope is about 1.1291.129 for GELU (near z=1.41z=1.41) and about 1.1001.100 for SiLU (near z=2.40z=2.40).

Names. The two curves are close but different. Hendrycks and Gimpel (2016) introduced GELU, z Φ(z)z\,\Phi(z), and also discussed z σ(z)z\,\sigma(z), which they called the SiLU (sigmoid linear unit). Elfwing, Uchibe and Doya (first posted in 2017) used the same function as a sigmoid-weighted linear unit for reinforcement learning. Ramachandran, Zoph and Le (2017) found it again by an automated search and called it Swish, defined with a parameter as z σ(βz)z\,\sigma(\beta z); with β=1\beta=1 it is the SiLU. PyTorch calls the β=1\beta=1 version SiLU, and the names are often used for the same curve.

Go deeper The tanh form of GELU, and a cheaper stand-in

Computing Φ\Phi needs the error function erf\mathrm{erf}, since Φ(z)=12(1+erf(z/2))\Phi(z)=\frac12\bigl(1+\mathrm{erf}(z/\sqrt2)\bigr). An approximation that uses only tanh⁡\tanh is

GELU(z)≈z2 (1+tanh⁡u),\mathrm{GELU}(z)\approx\tfrac{z}{2}\,(1+\tanh u),

with uu given by

u=2π (z+0.044715 z3).u=\sqrt{\tfrac{2}{\pi}}\,\bigl(z+0.044715\,z^3\bigr).

It is given in the GELU paper and is available in PyTorch as approximate="tanh". Running the check on a fine grid from −6-6 to 66 shows the two differ by at most about 0.00050.0005. At z=0.5z=0.5 the exact value is 0.345730.34573 and the approximation is 0.345710.34571. The same paper also notes z σ(1.702 z)z\,\sigma(1.702\,z) as a rougher approximation, and that one is off by up to about 0.020.02 on the same grid. Which version a trained model used matters if you want to reproduce its numbers exactly.

A table of numbers to check by hand

Every entry below was computed with code and rounded to three decimals. In the first three tables each cell shows the value and then the slope, as ff/f′f'; the last two tables give them in separate columns. Check one with your own calculator, for example σ(−0.5)=1/(1+e0.5)=0.378\sigma(-0.5)=1/(1+\mathrm{e}^{0.5})=0.378 and σ′(−0.5)=0.378×0.622=0.235\sigma'(-0.5)=0.378\times0.622=0.235.

The sigmoid and tanh:

zzσ\sigmatanh
−20.119/0.105−0.964/0.071
−0.50.378/0.235−0.462/0.786
00.500/0.2500.000/1.000
0.50.622/0.2350.462/0.786
20.881/0.1050.964/0.071

ReLU and Leaky ReLU (α=0.01\alpha=0.01). At z=0z=0 the slopes shown are the PyTorch values (0 for ReLU, α\alpha for Leaky ReLU):

zzReLULeaky
−20.000/0.000−0.020/0.010
−0.50.000/0.000−0.005/0.010
00.000/0.0000.000/0.010
0.50.500/1.0000.500/1.000
22.000/1.0002.000/1.000

Softplus and ELU (α=1\alpha=1):

zzSoftplusELU
−20.127/0.119−0.865/0.135
−0.50.474/0.378−0.393/0.607
00.693/0.5000.000/1.000
0.50.974/0.6220.500/1.000
22.127/0.8812.000/1.000

GELU:

zzGELUGELU′
−2−0.046−0.085
−0.5−0.1540.133
00.0000.500
0.50.3460.867
21.9541.085

and SiLU:

zzSiLUSiLU′
−2−0.238−0.091
−0.5−0.1890.260
00.0000.500
0.50.3110.740
21.7621.091

Things to notice: the sigmoid and tanh slopes fall off on both sides; ReLU and Leaky ReLU slopes are 1 from z=0.5z=0.5 on; the softplus slope is the sigmoid column; the GELU and SiLU slopes are negative at z=−2z=-2 and above 1 at z=2z=2.

See the curves and their slopes

In the widget, blue is the function and orange is its slope. Choose up to three activations, and move zz to read f(z)f(z) and f′(z)f'(z) for each.

Press a name to add or remove it. At most three show at once, so choosing a fourth drops the oldest.

−4−3−2−11234−11234z
  • Sigmoid (solid line, circle): f(0.5) = 0.622, f′(0.5) = 0.235
  • ReLU (dashed line, square): f(0.5) = 0.5, f′(0.5) = 1

Each chosen activation has its own line style and marker (solid and circle, dashed and square, dotted and triangle). The vertical line marks z. The step jumps at 0, so its slope is 0 wherever it exists and the orange line lies along the axis. Leaky ReLU uses slope 0.01 and ELU uses α = 1.

Activation functions and their slopes. Blue is the function and orange is its slope, on one set of axes with z from −4 to 4. Press a name to add or remove it (up to three at a time), and move the slider to read f(z) and f′(z). Try Sigmoid and ReLU at z = 3.

Things to try:

  1. Choose Sigmoid and tanh. The orange peaks at z=0z=0 are 0.250.25 and 11, and both slopes are close to 0 at z=4z=4: saturation.
  2. Choose ReLU. Move zz across 0: the orange slope jumps from 0 to 1, and the blue curve has a corner.
  3. Choose GELU and SiLU. Both dip below 0 for moderate negative zz and their orange curves rise above 1 before settling at 1.
  4. Choose Step. The blue curve jumps at 0, and the orange slope is 0 on both sides, lying along the axis. Nothing for gradient descent to use.

A summary of the properties

ActivationRangeLargest slope; flat where
Step{0,1}\{0,1\}0; flat
Sigmoid(0,1)(0,1)14\frac14; both tails
tanh(−1,1)(-1,1)1; both tails
ReLU[0,∞)[0,\infty)1; z<0z<0
Leaky ReLUall reals1; none (α\alpha on the left)
Softplus(0,∞)(0,\infty)below 1; left tail
ELU(−α,∞)(-\alpha,\infty)1; left tail
GELU[−0.170,∞)[-0.170,\infty)about 1.13; left tail
SiLU[−0.278,∞)[-0.278,\infty)about 1.10; left tail

“Tail” means large ∣z∣|z|, where the curve is nearly flat; “left” is large negative zz. The sigmoid and tanh have both. Their largest slope is at z=0z=0.

What the choice does to a network

Two experiments on the same made-up data show the effects. The data are 80 points in the plane: 40 in a disc around the origin (circles) and 40 in a ring around that disc (squares). A straight line cannot separate them.

The network has two hidden layers of 8 units with the chosen activation and a sigmoid output unit. Plain gradient descent (learning rate 1) trains it from the same starting weights, whatever activation you choose. Drag the slider to see the boundary (where the network’s probability is 0.5), the loss and how many of the 80 points are on the right side. Under the plane, the bars show a second experiment: a deeper stack of 6 hidden layers of 8 units, before any training, and the size of the gradient of the loss in each of its 7 layers (layer 1 is next to the input).

loss after 500 steps: < 0.001
points on the right side: 80 of 80

The line is the loss at every step (the top of the box is the largest loss on it), and the dot marks the step on the slider.

Gradient size in each layer of a deeper stack

6 hidden layers of 8 units, at their starting weights. Each bar is the root-mean-square gradient of one layer's weights, on a log scale from 10⁻⁷ to 1. Layer 1 is next to the input and layer 7 is the output layer.

  • Layer 1 1.9×10−3
  • Layer 2 9.1×10−4
  • Layer 3 9.3×10−4
  • Layer 4 1.2×10−3
  • Layer 5 2.5×10−3
  • Layer 6 2.1×10−3
  • Layer 7 2.9×10−3

The output layer's gradient is about 1.5 times the gradient in layer 1.

Made-up data: 40 circles in a disc and 40 squares in a ring. Plain gradient descent, learning rate 1, Glorot-uniform start. Other starts and weight scales (P4.12) change the numbers. The line is where the network's probability is 0.5. In Lite Mode, Play jumps to the last step.

The same task and the same starting weights with a different activation in the hidden layers. Choose an activation, then press Play or drag the slider to see the decision boundary, the loss and the number of correctly classified points after N steps. Orange bars show the gradient size in each layer of a deeper network. Try Sigmoid, then ReLU, then Step.

What the fixed start and fixed data give (running the same code in NumPy reproduces every number):

  • Step. The loss stays near 0.670.67 after 500 steps and only 45 of the 80 points are correct. The hidden layers get a gradient of exactly 0, so only the output weights move, on top of fixed random step features. 45 of 80 is 56 percent, near the 50 percent of guessing.
  • Sigmoid. The loss is 0.3840.384 after 500 steps and 72 points are correct. It is still falling, but its loss is still 0.6840.684 after 200 steps, when every activation except the step is below 0.010.01. The slow start of the sigmoid in the small network is not itself measured as a vanishing gradient; the deeper stack shows the mechanism. In the deeper stack, the gradient in the output layer is about 47,000 times the gradient in layer 1, and the first layers receive almost nothing.
  • tanh, ReLU, Leaky ReLU, ELU, GELU, SiLU. All reach 80 of 80 points correct by 100 steps, with a loss under 0.020.02. In the deeper stack the output-layer gradient is between 0.9 and 2.3 times the layer-1 gradient (tanh 0.9, ReLU 1.5, Leaky 1.6, SiLU 1.9, ELU 2.1, GELU 2.3).
  • Softplus. It also ends with 80 of 80 correct, but its loss is 0.970.97 at step 50, above its starting loss of 0.730.73, and the deeper stack shows a ratio of about 540. Its slope is σ(z)\sigma(z), below 1 everywhere, so slopes multiply down a path as for the sigmoid, though less severely.

These numbers belong to one start, one learning rate (1) and one kind of starting weights (Glorot-uniform). A different scale of starting weights changes the picture a lot, which is the subject of P4.12, and the matter of long chains of slopes is the subject of P4.16. The robust lesson is the direction: slopes well below 1 shrink the gradient with depth, and slopes of 0 remove it.

Output activations are a different choice

The last layer’s activation follows the form of the answer, not the training behaviour of the hidden layers:

  • A real number (regression, P3.A2): no activation, or the identity. A sigmoid output would limit the answer to (0,1)(0,1).
  • One probability (binary classification): a sigmoid, as in logistic regression (P3.A7). The loss is then binary cross-entropy (P4.6). This is what the tiny network above uses.
  • Several classes: softmax (P3.A8), which turns a vector of scores into probabilities that add to 1.
  • A positive number: a softplus or an exponential is often used.

Softmax is not an elementwise activation. Every other function here takes ziz_i and returns aia_i from that one number. Softmax gives ai=ezi/∑jezja_i=\mathrm{e}^{z_i}/\sum_j\mathrm{e}^{z_j}, so each output depends on all the scores. Changing one entry changes every output. It is an output-layer tool and is not used as a hidden activation in the sense of this lesson.

Which one should I use?

Practice, not a theorem:

  • ReLU is a common default for the hidden layers of MLPs and convolutional networks. It is simple and trains well, with He initialization (P4.12).
  • Leaky ReLU or ELU are options to try when many ReLU units are dead.
  • GELU and SiLU are common in transformers and in many recent models (P7.7). Some recent decoder models use a gated feed-forward layer built from SiLU, called SwiGLU (P10.C1).
  • Sigmoid and tanh are mostly kept for places where a bounded number is needed: probabilities at the output, and the gates and cell values in a recurrent cell such as the LSTM (P6.7).
  • Step is the original perceptron activation (P4.1). It still appears as a final yes or no threshold on a probability, but not as a hidden activation trained by gradient descent.

Differences between ReLU, GELU and SiLU are often smaller than those from the learning rate, the initialization and the normalization, and published comparisons depend on the task. When you copy an architecture, copy its activation too.

Depth: three ways to see it

Intuition

Think of each activation as a gate at the exit of a neuron. The step is a door that is shut or open. The sigmoid opens smoothly, but its tails barely react. ReLU is a one-way valve: it passes positive values unchanged and blocks the rest. Leaky ReLU is a valve with a pinhole. GELU and SiLU open gradually near 0, with a slight dip on the negative side. Training works by feeling how each gate responds to a small change, so a gate that does not respond (slope 0) gives training nothing to feel.

Math

For a layer, z=Wx+b\mathbf{z}=\mathbf{W}\mathbf{x}+\mathbf{b} and a=f(z)\mathbf{a}=f(\mathbf{z}) entry by entry. In backprop (P4.8), if δa\delta_a is the gradient arriving at aa, then the gradient at zz is δz=δa f′(z)\delta_z=\delta_a\,f'(z).

σ′=σ(1−σ),tanh⁡′=1−tanh⁡2,softplus′=σ,SiLU′=σ (1+z (1−σ)),GELU′(z)=Φ(z)+z φ(z).\begin{aligned} \sigma'&=\sigma(1-\sigma),\\ \tanh'&=1-\tanh^2,\\ \mathrm{softplus}'&=\sigma,\\ \mathrm{SiLU}'&=\sigma\,(1+z\,(1-\sigma)),\\ \mathrm{GELU}'(z)&=\Phi(z)+z\,\varphi(z). \end{aligned}ReLU′(z)={1z>00z<0\mathrm{ReLU}'(z)=\begin{cases}1&z>0\\0&z<0\end{cases}

Through nn sigmoid layers the slope factors alone multiply to at most (1/4)n(1/4)^n, and 0.2510≈9.5×10−70.25^{10}\approx9.5\times10^{-7}. The weights also enter every factor (P1.C3).

Code

import torch
import torch.nn.functional as F

z = torch.tensor([-2.0, -0.5, 0.0, 0.5, 2.0], requires_grad=True)
for name, fn in [("ReLU", torch.relu), ("GELU", F.gelu), ("SiLU", F.silu)]:
    z.grad = None
    fn(z).sum().backward()      # sum, so z.grad holds f'(z)
    print(name, z.grad.numpy().round(3))

Output from a local run with PyTorch 2.9.1:

ReLU [0. 0. 0. 1. 1.]
GELU [-0.085  0.133  0.5    0.867  1.085]
SiLU [-0.091  0.26   0.5    0.74   1.091]

The ReLU slope at z=0z=0 is 0, the convention above. In a model you would use torch.nn.ReLU(), torch.nn.LeakyReLU(0.01), torch.nn.GELU() or torch.nn.SiLU().

Try it in Python

The first cell compares the slopes of five activations with a numerical slope, and the second runs the dead-unit example. Both use NumPy only.

Slopes of five activations

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

A dead unit and a leaky one

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Common mistakes

Quiz

Check your understanding

  1. A network has ten layers, each computing Wx+b\mathbf{W}\mathbf{x}+\mathbf{b} with no activation between them. What can it represent?

  2. Why can a network of step-function hidden units not be trained with gradient descent?

  3. A sigmoid unit has z=0z=0. By what factor, at most, does it scale the gradient passing back through it?

  4. A ReLU unit has z<0z<0 for every training example and the loss gradient arriving at it is nonzero. What does the unit pass back to its weights, and what does Leaky ReLU with α=0.01\alpha=0.01 do differently?

  5. You build a network to output the probability that an email is spam. Which function should turn the output score into a probability?

Exercises

  1. Compute σ(1)\sigma(1) and σ′(1)\sigma'(1), then tanh⁡′(1)\tanh'(1), to three decimals.
    Show answerσ(1)=0.731\sigma(1)=0.731, so σ′(1)=0.731×0.269=0.197\sigma'(1)=0.731\times0.269=0.197. tanh⁡(1)=0.7616\tanh(1)=0.7616, so tanh⁡′(1)=1−0.76162=0.420\tanh'(1)=1-0.7616^2=0.420.
  2. A gradient of 22 arrives at a ReLU unit whose input is z=−0.3z=-0.3. What gradient does it pass to zz? What if the input were z=0.3z=0.3? What about a Leaky ReLU with α=0.01\alpha=0.01 at z=−0.3z=-0.3?
    Show answerFor z=−0.3z=-0.3 the ReLU slope is 0, so 2×0=02\times0=0. For z=0.3z=0.3 the slope is 1, so 2×1=22\times1=2. The Leaky ReLU at z=−0.3z=-0.3 passes 2×0.01=0.022\times0.01=0.02.
  3. Compute SiLU(2)\mathrm{SiLU}(2) and GELU(−2)\mathrm{GELU}(-2) from their definitions, given σ(2)=0.8808\sigma(2)=0.8808 and Φ(−2)=0.0228\Phi(-2)=0.0228.
    Show answerSiLU(2)=2×0.8808=1.762\mathrm{SiLU}(2)=2\times0.8808=1.762. GELU(−2)=−2×0.0228=−0.046\mathrm{GELU}(-2)=-2\times0.0228=-0.046.
  4. Ten sigmoid layers are stacked and each is at its steepest point, z=0z=0. Ignoring the weights, by what factor does a gradient shrink between layer 10 and layer 1? What if each were a tanh unit at z=0z=0?
    Show answerFor the sigmoid, 0.2510≈9.5×10−70.25^{10}\approx9.5\times10^{-7}. For tanh at z=0z=0 the slope is 1, so the factor from the slopes is 110=11^{10}=1. Real units are rarely all at z=0z=0, so tanh also shrinks the gradient once some units saturate, and the weights also scale it.
  5. Show with one pair of numbers that ReLU is not a linear function, and say what the “not linear” property buys a network.
    Show answerReLU(2)+ReLU(−5)=2\mathrm{ReLU}(2)+\mathrm{ReLU}(-5)=2, but ReLU(2+(−5))=ReLU(−3)=0\mathrm{ReLU}(2+(-5))=\mathrm{ReLU}(-3)=0, so it fails f(a+b)=f(a)+f(b)f(a+b)=f(a)+f(b). A network with it between layers does not collapse into one matrix, so extra layers add power.

Next: P4.5 writes the forward pass in matrix form, with the shapes of a whole batch flowing through the layers. P4.6 covers the loss functions that go after the output activation, and P4.8 shows how the slopes in this lesson enter backpropagation.

Key takeaways

  • A layer computes z=Wx+b\mathbf{z}=\mathbf{W}\mathbf{x}+\mathbf{b} and then applies an activation function to each entry. Without it, two layers are one matrix and ten are still one; a nonlinear step is what lets depth add power.
  • Training needs the activation's slope. The step has slope 0 wherever it has a slope, so gradient descent has nothing to follow. The sigmoid has σ′≤14\sigma'\le\frac14 and tanh has tanh⁡′≤1\tanh'\le1, and both go flat for large ∣z∣|z| (saturation).
  • ReLU is max⁡(0,z)\max(0,z): slope 1 for z>0z>0 and 0 for z<0z<0 (PyTorch uses 0 at exactly 0). It is cheap and does not saturate for positive zz, but a unit that is off for every input gets no gradient and can stay off (a dead unit). Leaky ReLU keeps a small slope there.
  • GELU z Φ(z)z\,\Phi(z) and SiLU z σ(z)z\,\sigma(z) are smooth, slightly negative for moderate negative zz and close to ReLU for large ∣z∣|z|. Softplus ln⁡(1+ez)\ln(1+\mathrm{e}^z) is a smooth ReLU whose slope is the sigmoid.
  • Hidden layers need a nonlinearity with a useful slope; the output layer's activation follows the target: none for a real number, sigmoid for one probability, softmax (which is not elementwise) for several. ReLU is a common default for hidden layers, and GELU and SiLU are common in transformers.
Found a mistake? Tell us