AI State of the Art
Fundamentals/Machine Learning: The Basics/20 min
Section 8

Activation Functions: The Pinch of Non-Linearity

Listen as a podcast β†’

The problem: without them, a hundred layers equal one layer

A neural network layer does two things, in this order. First a matrix multiplication, which mixes the components of the input, each output becomes a weighted average of all the inputs, as explained in How to read the formulas. Then an activation function, applied slot by slot, with no mixing at all.

That second step looks decorative. It is indispensable, and the reason fits on one line: chaining two matrix multiplications, W2β‹…(W1β‹…x)W_2 \cdot (W_1 \cdot x), amounts to multiplying once by the single table Wβ€²=W2β‹…W1W' = W_2 \cdot W_1. Two purely linear layers stacked are therefore exactly equivalent to one, and so are a thousand of them. The full argument, biases included, is worked through in The perceptron.

Put differently: depth buys a network nothing until you slip in, between two layers, an operation no matrix can imitate. That is the job of the activation function, and all it has to be is non-linear, anything but a plain rescaling.

What an activation function is not

It mixes nothing. It takes one number and returns one number, regardless of its neighbours. If the input is a list of 4096 numbers, the same function is applied 4096 times in parallel.

It also almost never has a learned parameter: it is a fixed operation, chosen by whoever designed the architecture, not learned from data. One exception, at the end of this page: the multiplicative gates, which do carry weights.

Sigmoid and hyperbolic tangent: the generation that saturates

The sigmoid, written Οƒ\sigma, squashes any number into the range 0 to 1:

Οƒ(z)=11+eβˆ’z\sigma(z) = \frac{1}{1 + e^{-z}}

Here zz is the incoming number, ee is Euler's constant (about 2.718), and the negative exponent means that the larger zz gets, the tinier eβˆ’ze^{-z} becomes, so the closer the result creeps to 1. In one sentence: an S-shaped curve, flat on the left, flat on the right, rising in the middle.

The hyperbolic tangent, written tanh⁑\tanh, is the same curve recentred: it runs from βˆ’1-1 to +1+1 and passes through zero in the middle. That centring is a genuine advantage, negative values stay negative instead of all being crushed towards 0.

Both share one flaw, and it is a fatal one: saturation. When zz is very large or very small, the curve is nearly horizontal, so its slope is nearly zero. But that slope is precisely what tells the weights upstream which way to move. No slope, no instruction, no learning.

Stack a dozen saturating layers and those tiny slopes multiply together until they vanish outright: this is the vanishing gradient, the ailment that long made deep networks untrainable, and the one that gates in recurrent architectures work around, see LSTM and GRU.

ReLU: the crudeness that unlocked depth

ReLU stands for Rectified Linear Unit. "Rectified" in the electrical sense: the signal is straightened, everything negative is cut away.

ReLU(z)=max⁑(0;z)\text{ReLU}(z) = \max(0 ; z)

Where max⁑(0;z)\max(0 ; z) means "keep whichever of 0 and zz is larger". So: if the input is negative, the output is 0; if it is positive, the output is the input, untouched. Two straight pieces meeting at a sharp corner at zero.

It is almost crude, and that is what makes it powerful:

  • No saturation on the positive side. The slope there is exactly 1, forever. The learning signal crosses the layer without being dimmed. This single property is what makes very deep networks trainable.
  • Laughably cheap to compute. One comparison against zero, no exponential. Across billions of applications per request, that is not a detail.
  • It switches neurons off. A good share of the outputs are exactly zero, and a zero propagates nothing. The network specialises on its own, each neuron responding to only part of the input space.

One flaw remains, a direct consequence of the third point: the dead neuron. If a neuron ends up returning 0 for every possible input, its slope is zero everywhere, it never receives a correction again, and it is lost for good.

The variants: each one fixes the one before

FunctionWhat it changesThe flaw it fixes
Leaky ReLUa very shallow slope on the negative side instead of flat 0the dead neuron: a small slope keeps it reachable
ELU, exponential linear unitthe negative side is rounded, settling on a fixed negative valuethe harsh corner, and the fact that ReLU never outputs anything negative
GELU, Gaussian error linear unitthe corner is replaced by a smooth curvethe sharp kink at zero, where the slope jumps from 0 to 1 at once
SiLU, also called Swishzz multiplied by Οƒ(z)\sigma(z)the same smoothing as GELU, in a form that is simpler to compute

These four differ only in how they handle the neighbourhood of zero and the negative side. None of them changes the nature of the operation: one number in, one number out.

Compared curves of GELU, ReLU and ELU: ReLU forms a sharp kink at zero, ELU rounds the negative side towards a floor at -1, and GELU follows a smooth curve dipping slightly below zero before joining ReLU on the positive side.
Three ways of handling the neighbourhood of zero, plotted in the paper that introduced GELU. ReLU (orange) cuts off sharply at zero; ELU (green) rounds the negative side towards a floor value; GELU (blue) replaces the kink with a smooth curve that dips slightly below zero before joining ReLU on the positive side.Source : GELU paper (figure 1)
The original papers

Gaussian Error Linear Units (GELUs) introduces GELU.

Searching for Activation Functions presents Swish, found by automated search over combinations of elementary functions rather than designed by hand.

Multiplicative gates: SwiGLU and its family

Recent language models do something else. Instead of applying a function to a single result, the layer computes two results from the same input, applies the activation to only one of them, and then multiplies them element-wise, slot by slot, no mixing, the operation written βŠ™\odot.

SwiGLU(x)=(SiLU(xβ‹…W1))βŠ™(xβ‹…W2)\text{SwiGLU}(x) = \bigl(\text{SiLU}(x \cdot W_1)\bigr) \odot (x \cdot W_2)

Every symbol: xx is the layer's input, a value computed on the text at hand. W1W_1 and W2W_2 are two distinct weight tables, two learned parameters, frozen once training ends. The βŠ™\odot is the element-wise product.

In one sentence: one branch decides how far the tap opens, the other decides what flows through it, and the result is the product of the two. The name GLU comes from Gated Linear Unit, and the Swi- prefix says that the activation used on the control branch is Swish.

The appeal: how much gets through depends on the input itself, slot by slot. An ordinary activation always filters the same way; a gate filters differently according to context. The cost: two weight tables are needed where a classic layer asked for one, so implementations shrink the layer's width to keep the parameter count comparable.

The reference paper

GLU Variants Improve Transformer compares these gates against the classic activations inside a transformer and proposes SwiGLU. That is where its adoption across most of today's large open models comes from.

Softmax: the special case

Softmax is nearly always filed under activation functions. That is misleading: its role is entirely different. It is not a hidden-layer non-linearity, it is a converter from scores to probabilities.

First, a word of vocabulary: a logit is a raw score, exactly as the network produces it, before any conversion. It has no unit, no bounds, and can be negative. Comparing two logits is meaningful; reading one in isolation is not.

softmax(z)i=eziβˆ‘jezj\text{softmax}(z)_i = \frac{e^{z_i}}{\sum_j e^{z_j}}

Every symbol: zz is the list of logits, ziz_i is the logit of candidate number ii, the exponential ezie^{z_i} makes it positive whatever its sign, and the denominator βˆ‘jezj\sum_j e^{z_j} adds up those exponentials across all candidates. In one sentence: every score is made positive, then each is divided by their total, so the results become slices of one cake.

What softmax guarantees, which is exactly what it is asked for:

  • Every number coming out is positive. The exponential takes care of that.
  • They sum to 1. Dividing by the total takes care of that. So they can be read as probabilities.
  • It is monotonic, meaning it preserves order: the largest logit yields the largest probability. One important practical consequence, softmax never changes the ranking. A model that only wants the winning candidate, its arg⁑max⁑\arg\max, gets the same answer with or without softmax. Softmax earns its keep only when you actually want probabilities: to sample a word at random among the plausible ones, or to measure an error during training, see Loss functions.

Its role in attention

This is where the reader meets it most often, and it is not to produce an output word. In the attention mechanism, the model computes for each token a relevance score towards each of the others. Softmax turns that list of scores into an attention distribution: positive weights summing to 1, in other words an attention budget spent in full.

That constraint is the heart of the mechanism. Since the total is fixed, giving more attention to one token necessarily takes it away from the others. Attention is a zero-sum game, and softmax is what makes it one. The details are in Self-attention.

Which one shows up where

Place in the modelUsual functionWhat is asked of it
Hidden layer of a recent language modelSwiGLU, or GELUdo not saturate, filter according to context
Hidden layer of a vision networkReLU and its variantsdo not saturate, be very cheap to compute
Recurrent cell (LSTM, GRU)sigmoid for the gates, tanh⁑\tanh for the contentsan output between 0 and 1, readable as how far a tap is open
Output of a multi-class classifiersoftmaxprobabilities that sum to 1
Output of a yes/no classifiersigmoidone single probability between 0 and 1
Inside the attention mechanismsoftmaxa fixed attention budget to divide up
Output of a regression, predicting a numbernonedo not cap the predicted value

Why it matters

The choice of activation function turns up often in product announcements, because it is an easy way in: the formula is short and a variant is easy to propose. The question worth asking stays the one this page has been asking throughout: which flaw of the previous function does this one fix, and at what computational cost? A variant that brings neither brings nothing.

Check your understanding0 / 5

1. Why is a hundred-layer network worth nothing without activation functions?

2. What is sigmoid saturation, and why is it a fatal flaw?

3. What is a dead neuron with ReLU?

4. A model only wants the highest-scoring word (the argmax). Does applying softmax before choosing change the winner?

5. In the attention mechanism, what does softmax guarantee?