Topic: ml-fundamentals · deep dive

Activation functions

The nonlinearity between two linear maps, judged by its slope: saturation in sigmoid and tanh, dead units in the ReLU family, the smooth ReLUs (GELU, SiLU), the gated units every current LLM uses (SwiGLU) with the 2/3 width rule, and softmax at the output. Curves computed in your browser and checked against PyTorch; dead units and three released models measured offline. Data as of October 2026. Reading: 25 min, plus 5 in closed details.

An activation function is the elementwise nonlinearity between two linear maps, and what decides how well a network trains is its slope: backpropagation multiplies every unit's gradient by it, so a slope near 0 (saturation) or exactly 0 (a dead unit) stops learning. Since 2020, language models replace the single function with a gate: a second projection of the same input that sets each unit's slope, token by token (SwiGLU).

You need: backpropagation and a feed-forward block. Where the activation sits in one training step, and what a whole network of each does to the variance, is step 2 of the Reading tab of Topic: ml-fundamentals; the block around the activation is on The transformer from zero; normalisation and initialisation are on Normalisation and initialisation.

pre-activation
the number a unit computes before the activation: one entry of xW + b
saturation
inputs where the slope is close to 0, so almost no gradient flows back
dead unit
a ReLU unit whose input is negative on every example: output 0, gradient 0, nothing pulls it back
gated unit (GLU)
two projections of the same input multiplied elementwise, one passed through an activation
logit
a raw output score before softmax or sigmoid

Each activation (dark line) and its slope (blue): where the slope is low, the gradient fades

Red: slope exactly 0, no gradient at all. Grey: slope below 0.01, saturated. Dashed line: slope 1, where the gradient passes unchanged. All curves computed in your browser from PyTorch's definitions (src/recompute.py checks them).

In one screen

In 2026 the answer for hidden layers of a language model is a gated unit, almost always SwiGLU; GELU survives in vision transformers and older encoders; the ReLU family in convolutional networks and a few efficiency-minded LLMs; sigmoid and tanh only inside gates and at outputs.

FamilyMembersWhere it lives nowWhat goes wrong
Saturatingsigmoid, tanhgates (LSTM, GRU), binary outputsslope near 0 on both sides: gradients vanish through many layers (below)
RectifiedReLU, leaky ReLU, PReLU, ELU, SELU, squared ReLUconvolutional networks; OPT (ReLU), Nemotron-4 (squared ReLU); SELU in self-normalising fully connected networksReLU units can die: zero output and zero gradient on every input (measured below)
Smooth rectifiersGELU (exact or tanh form), SiLU (Swish), MishBERT, GPT-2, GPT-3, ViT; Mish in object detectorsseveral "GELU"s that are not interchangeable in a trained checkpoint (below)
GatedGLU, bilinear, ReGLU, GEGLU, SwiGLUthe feed-forward block of nearly every LLM since PaLM and Llamaa third weight matrix: the hidden width is cut to keep the parameter count (the 2/3 rule)
Outputsigmoid, softmax, none (linear)the last layer, chosen by the taskmust match the loss, which in PyTorch usually wants the raw logits (below)

Linked, not rebuilt, on the root: "one batch through five networks" (step 2 of its Reading tab), the Training lab (six activations swapped live) and Defaults across models (twenty-one models from AlexNet to Kimi K2). Here: every function with its derivative in the Activation atlas; three released models in Inside real models.

Why a nonlinearity, and what it must be

Non-linear, or the stack collapses: W2(W1x) = (W2W1)x, one linear map however many layers there are. Fig. 1 shows what the nonlinearity buys on the smallest problem a linear map cannot solve: two classes laid out like XOR, and a layer of two ReLU units that folds the plane they lie on.

  1. Two classes that no line separates. 60 points in four clusters: class A around (0, 0) and (1, 1), class B around (0, 1) and (1, 0). Any straight line on the plane leaves at least one cluster on the wrong side.
  2. A linear model is a plane, here a flat one. The least-squares fit y = ax1 + bx2 + c predicts between 0.47 and 0.53 for every point; cut at 0.5 it gets 53% right, a coin toss. More linear layers give another plane.
  3. One ReLU unit folds the plane once. h1 = ReLU(x1 + x2) is flat at 0 on one side of the line x1 + x2 = 0 and rises on the other: one crease, where its slope jumps from 0 to 1.
  4. A second unit folds along another line. h2 = ReLU(x1 + x2 − 1) creases along x1 + x2 = 1, the line through both B clusters.
  5. Their difference lifts one class. y = h1 − 2h2 carries both creases: it rises to 1 along the B line and falls back towards 0 at both A corners. Every A point ends at most 0.27, every B point at least 0.65.
  6. Now a flat cut separates them. The plane y = 0.5 has every B above and every A below: 100% right. Drop the two ReLUs from the same weights and y = 2 − x1 − x2, a plane again, at 75%.

Points drawn by src/mk_fold.py (four clusters of 15, standard deviation 0.12, seed 0) illustrative; the weights are set by hand to make the folds visible, and a trained network finds its own. Every number in the steps is computed from those points.

  • Not a polynomial, the exact condition for a one-hidden-layer network to approximate any continuous function (Leshno et al. 1993, below). x2 alone would not do; squared ReLU, max(0, x)2, is piecewise and is not a polynomial, so it qualifies.
  • Differentiable almost everywhere is enough for gradient descent: ReLU has no derivative at exactly 0 and frameworks simply pick one (PyTorch's autograd uses 0 there; this page's derivatives agree with autograd everywhere else, src/recompute.py).

Everything else is a trade between four properties: slope near 1 over a wide range (gradients survive depth), outputs centred on zero (updates do not zig-zag), cheap to compute, and smooth (the optimiser sees a smooth surface). No function has all four.

The universal approximation condition, quoted (Leshno, Lin, Pinkus and Schocken 1993)

"A standard multilayer feedforward network with a locally bounded piecewise continuous activation function can approximate any continuous function to any degree of accuracy if and only if the network's activation function is not a polynomial" (Leshno, Lin, Pinkus and Schocken 1993).

Saturation: sigmoid and tanh

ActivationFormulaRangeLargest slopeGood atTrouble
Sigmoid σ1 / (1 + e−x)(0, 1)0.25, at x = 0an output read as a probability; a gate that opens between 0 and 1saturates on both sides; outputs always positive, not zero-centred
Tanhtanh x = 2σ(2x) − 1(−1, 1)1, at x = 0zero-centred: outputs, and so the next layer's updates, can have either signstill saturates: slope below 0.01 once |x| > 3.0 derived

Backpropagation multiplies the gradient by the activation's slope at every unit of every layer. A sigmoid's slope is at most 0.25, so even at its best a gradient shrinks by 4 per layer, and in a saturated unit the slope is close to 0: below 0.01 once |x| > 4.6 derived from σ(1 − σ) = 0.01. On the root's "one batch through five networks", the first layer of the 16-layer sigmoid network receives a gradient about 2 billion times smaller than the last (step 2 of the Reading tab of Topic: ml-fundamentals). Tanh is a rescaled sigmoid (the identity above) with four times the slope at 0, which is why it was preferred for hidden layers before ReLU.

Predict, then press: the figure holds the 3,072 real pre-activations of one token in one GPT-2 block. Which function passes the least gradient back through them: sigmoid (slope never above 0.25), tanh, ReLU, GELU or SiLU? Then multiply the inputs by 3, as happens when a layer's inputs grow without normalisation, and see which ones change.

The answer, in numbers (src/slope_numbers.mjs)
On these inputsMean |slope|Slope exactly 0Below 0.01Below 0.01 at × 3
Sigmoid0.1910%0%22.4%
Tanh0.5120%0.7%44.9%
ReLU0.11288.8%88.8%88.8%
GELU (tanh form)0.1980%2.7%43.9%
SiLU0.2100%3.6%8.8%

ReLU passes the least: its mean slope, 0.112, is the share of positive inputs, and it does not move with scale, because only signs matter. Sigmoid never saturates here but caps every unit at 0.25. GELU's few "below 0.01" units at × 1 sit at the bottom of its dip (x near −0.75, where the slope crosses 0), not in a flat tail.

Why zero-centred matters. A unit's weight gradient is its input times one shared error term. If every input is positive (a sigmoid layer's output always is), every weight of that unit moves in the same direction at each step, so reaching a target that needs some weights up and others down takes a zig-zag. LeCun et al. recommend inputs with mean close to zero for this reason, and a scaled tanh, 1.7159 tanh(2x/3), for hidden units (Efficient BackProp, 1998, sections 4.3 and 4.4).

Where they still live. Inside gates, where a value between 0 and 1 is the point: the LSTM's forget, input and output gates are sigmoids and its cell candidate a tanh (Sequence models: the pre-transformer lineage); the gated units below move this idea into the feed-forward block. And at the output, for a binary or multilabel probability.

The same 3,072 pre-activations, five slopes: ReLU cuts nine units in ten to zero, tanh saturates only when the inputs grow

Input: GPT-2 small, layer 6, the token " cat" in "The cat sat on the mat because it was tired.": 3,072 pre-activations xW1 + b1, recorded by src/real_models.py, 88.8% of them negative, sorted from −4.24 to 2.57. GPT-2 was trained with GELU; the other four functions are applied to the same numbers illustrative, to compare slopes on one input, not to predict a model trained with them. Grey bars: slope below 0.01. Red ticks: slope exactly 0.

The ReLU family

ReLU, max(0, x), has slope exactly 1 for every positive input, so the gradient passes through any number of active layers unshrunk, and it costs one comparison. AlexNet made it the default: a four-layer convolutional network with ReLUs reached 25% training error on CIFAR-10 six times faster than the same network with tanh (Krizhevsky, Sutskever and Hinton 2012, section 3.1). Its variants each patch one weakness:

VariantFormula, for x ≤ 0 (all are x for x > 0 unless said)What it fixes, and its costSource
Leaky ReLUαx, α fixed (0.01 in the paper and PyTorch's default)a small gradient for negative inputs, so a unit cannot be stuck at zero gradient; one more hyperparameterMaas, Hannun and Ng 2013
PReLUax, a learned (per channel or shared), initialised at 0.25the network picks the slope; He initialisation was derived for it in the same paperHe et al. 2015
ELUα(ex − 1), α = 1a smooth negative side that saturates at −α, which pushes mean outputs towards zero (the paper's argument for faster learning); costs an exponentialClevert, Unterthiner and Hochreiter 2015
SELUλα(ex − 1), and λx for x > 0; λ ≈ 1.0507, α ≈ 1.6733constants chosen so that mean 0 and variance 1 is a fixed point of a layer with LeCun initialisation: the network normalises itself without BatchNorm, in fully connected networksKlambauer et al. 2017
Squared ReLU0, and x2 for x > 0found by Primer's search as "the most effective modification" to a Transformer's feed-forward block; used by Nemotron-4 15B and the Nemotron Mini and Minitron models (config relu2). Why it helps, read as a memory: squaring crushes weak matches, so a hidden unit's typical weight for an unrelated input falls from about d−1/2 to about d−1, and a layer reads about 2d2/3 random memories cleanly instead of 2d (the transformers-from-memory article)So et al. 2021, Nemotron-4 15B, config.json
Where ReLU came from (2010 and 2011)

It entered deep learning through restricted Boltzmann machines (Nair and Hinton 2010) and deep supervised networks (Glorot, Bordes and Bengio 2011, who stressed that it makes representations sparse: many units output exactly 0).

SELU's fixed point, reproduced (and ReLU's factor of 2)

For a standard normal input, this page's numerical integration gives E[SELU(z)] = 0.0000 and E[SELU(z)2] = 1.0000 reproduces Klambauer et al. independently; for ReLU, E[ReLU(z)2] = 0.5, the half that He initialisation's factor 2 puts back. Both are rows of the statistics table in the Activation atlas, beside PyTorch's calculate_gain.

Dead units, measured

A ReLU unit whose input is negative for every example outputs 0 everywhere and receives zero gradient, so nothing in backpropagation pushes it back: it is dead. A high learning rate or a large negative bias can kill many at once. The usual statement is that a dead unit "never recovers". That is exact only for a unit whose inputs cannot change (the first layer, fed fixed data); a dead unit deeper in the network can come back when the layers below it change, as the measured run below shows.

Predict, then watch: will dead units come back once they die? A real network, trained offline: a 64-128-128-128-10 network on 1,797 handwritten digits, He initialisation, SGD with momentum 0.9, 30 epochs. In Fig. 2 each column is one of the 384 hidden units, as tall as the share of the 1,797 images on which it is on; a flat red tile is dead (off on every image). Dots carry the signal from layer to layer, as dense as the share of live units in the layer they leave. Switch runs: the same network at learning rate 0.04, at 0.08, and at 0.08 with leaky ReLU.

  1. Before training. He initialisation and zero biases: every unit is on for roughly half of the images, and held-out accuracy is 9.2%, chance.
  2. Epochs 1 to 3: it learns. The training loss falls from 0.782 to 0.147 and held-out accuracy reaches 96.4%. No unit dies.
  3. Epochs 4 to 30: nothing dies at this rate. The loss keeps falling, to 0.0001; still 0 dead of 384, and 96.9% of the held-out digits right.

Measured with src/dead_relu_toy.py (PyTorch 2.14, CPU, seed 0 for these three runs). Data: scikit-learn's digits (UCI), pixels standardised, 1,437 images to train on and 360 held out; "dead" is judged on all 1,797. A leaky unit with negative input on every image is counted the same way (a red tile), though it still passes 1% of the gradient.

Across five seeds and ten learning rates (the chart, from the same script): up to a rate of 0.04 no ReLU unit dies; at 0.05 and 0.06 a handful die and the network still reaches 96 to 98% held-out accuracy; from 0.07 most runs lose a whole layer, after which every image produces the same output, the loss sits at ln 10 = 2.303 and accuracy at chance. With leaky ReLU nothing can go fully silent, so the same rates do not end in a dead network; they end in a loss that overflows to "not a number". The learning rate is the cause in both; the activation decides only whether the failure is silent or loud.

What to do about dead units
  • Check for them: count, over a batch or a held-out set, the units whose output is 0 on every example (the parent's When training goes wrong tab runs a network whose biases start at −3, so most ReLUs are off from the start, and shows the plateau that follows).
  • Lower the learning rate, warm it up, clip gradients: the runs above die only above a threshold rate.
  • Initialise for the activation (He for the ReLU family) and keep biases at 0, not negative.
  • Normalise before the activation, which keeps pre-activations centred, or switch to a variant with a negative side (leaky, ELU, GELU, SiLU). Neither removes the cause if the rate is too high.

In a released model. Dead units are not only a training accident. In OPT, whose feed-forward blocks use ReLU, "many neurons (more than 70% in some layers of the 66b model) are 'dead', i.e. they never activate on a large collection of diverse data", all of them in the first half of the network (Voita, Ferrando and Nalmpantis 2023). The Inside real models tab measures the same thing on OPT-125m over 283,287 tokens of WikiText-2:

Up to rate 0.04 nothing dies; from 0.07 ReLU runs collapse and leaky ReLU runs overflow

Smooth rectifiers: GELU, SiLU, Mish

ActivationFormulaLowest value derivedOriginUsed in
GELUx Φ(x), Φ the standard normal CDF−0.170 at x = −0.752Hendrycks and Gimpel 2016GPT-1, BERT, GPT-2, GPT-3, ViT (the parent's Defaults across models tab gives each source)
SiLU, also Swish-1x σ(x)−0.278 at x = −1.278named in the GELU paper and by Elfwing, Uchibe and Doya 2017; Swish, x σ(βx), by Ramachandran, Zoph and Le 2017the gate of SwiGLU, so every Llama-style model
Mishx tanh(softplus(x))−0.309 at x = −1.192Misra 2019object detectors such as YOLOv4; rare in language models

GELU's idea. Multiply the input by a random mask m ~ Bernoulli(Φ(x)): kept with a probability that grows with x. Its expected value is x Φ(x), so GELU is a deterministic version of a stochastic regulariser that blends ReLU (a mask of 0 or 1 set by the sign), dropout (a random 0) and zoneout (a random 1) (GELU paper, section 2). Unlike ReLU it is smooth, not monotone (a small dip below 0), and lets small negative inputs pass a small gradient.

Several GELUs. The paper gives two cheaper forms, and trained models use all three; a checkpoint must be run with the form it was trained with:

FormFormulaLargest gap from exact GELU on [−6, 6] derivedWho uses it
Exactx Φ(x) = ½x(1 + erf(x/√2))0BERT as configured in Hugging Face (gelu; the Google BERT code first used this form and later the tanh one, per the comments in Transformers' activations.py); PyTorch F.gelu
Tanh½x(1 + tanh[√(2/π)(x + 0.044715x3)])4.7 × 10−4GPT-2 (gelu_new), Gemma 3 (gelu_pytorch_tanh); PyTorch approximate='tanh'
Sigmoid ("QuickGELU")x σ(1.702x)0.020CLIP's released code (class QuickGELU)
Correction: SiLU is not "nearly identical" to GELU, and was not found by the search

The old version of this page said SiLU has a "nearly identical curve to GELU" and was "found by architecture search". The curves differ by up to 0.193 derived, max |SiLU − GELU| on [−6, 6], and SiLU's dip is 64% deeper (−0.278 against −0.170). The near-identity is GELU against x σ(1.702x): SiLU is that curve stretched 1.702 times along x (and rescaled). SiLU was not found by the search either (below).

Who found SiLU, and what Swish's search found (Ramachandran et al. 2017)

As for the search: x σ(x) was already in the GELU paper (as SiLU) and in Elfwing et al.; Ramachandran et al.'s automated search found the family x σ(βx), which they named Swish, and their paper says that with β = 1 "Swish is equivalent to the Sigmoid-weighted Linear Unit (SiL) of Elfwing et al." Their result is that replacing ReLU with Swish raised ImageNet top-1 accuracy by 0.9% for Mobile NASNet-A and 0.6% for Inception-ResNet-v2.

Overlay the curves in the Activation atlas.

Why the smooth ones win in transformers is not settled. The papers report empirical gains (GELU over ReLU and ELU on their benchmarks, Swish over ReLU on ImageNet and translation); the old page's "self-scaling" has no source beyond the Bernoulli motivation above. In Shazeer's controlled comparison (next section), GELU and Swish alone barely beat ReLU in pre-training perplexity (1.983 and 1.994 against 1.997 at 65,536 steps, with run-to-run spreads of 0.003 to 0.005) and were behind it at the end of training (1.679 and 1.683 against 1.677): the gain that stuck came from gating.

Gated units: GLU, ReGLU, GEGLU, SwiGLU

A gated linear unit computes two projections of the same input and multiplies them elementwise, one passed through a nonlinearity (Dauphin et al. 2016, for gated convolutional language models). Shazeer put the variants into the Transformer's feed-forward block, without biases (GLU Variants Improve Transformer, 2020, equation 6):

FFNSwiGLU(x) = (SiLU(xW) ⊙ xV) W2
x
one token's vector, width d
W, V
the gate and up projections, d × h each (in Llama's code w1 and w3, in Hugging Face gate_proj and up_proj)
W2
the down projection, h × d
⊙
elementwise product
VariantGate function on xWSource
GLUsigmoid σDauphin et al. 2016
Bilinearnone (identity): still nonlinear, a product of two linear mapsDauphin et al., attributed to Mnih and Hinton 2007
ReGLUReLUShazeer 2020
GEGLUGELUShazeer 2020; T5 v1.1, Gemma (tanh GELU)
SwiGLUSiLU (Swish with β = 1)Shazeer 2020; PaLM, Llama, Mistral, Qwen, DeepSeek, SmolLM and most open LLMs since

What the gate does to the gradient. With g = xW and u = xV, the hidden unit is h = SiLU(g) u, so ∂h/∂u = SiLU(g): the slope of the linear path is not a fixed function of its own input but is set, token by token, by a second projection of the same input. That is the old page's "learned adaptive slope", and the only mechanism the formula itself shows. Its other claims for gated units ("very expressive, stable training, balanced mean/variance") are unconfirmed: the paper that introduced them offers none, and says so: "We offer no explanation as to why these architectures seem to work; we attribute their success, as all else, to divine benevolence."

A positive output for two unrelated reasons. SiLU of a negative gate is small but negative, never below about −0.278 (at g ≈ −1.28), so when gate and value are both negative their product is positive, at most about 0.278 × |u|. This double-negative quadrant usually adds a faint echo of a unit's negative pole to its positive one; in Qwen3-32B it is the whole top of the activation list for about 4% of neurons, a companion paper counts about a third of all activations there in Qwen3.6-35B-A3B, and ablating those activations raised most benchmarks but lowered some reasoning ones, a cost nobody has explained yet (Neural Networks Are Already Clean, from one team's audits).

Predict, then watch: with the same parameter budget, will the gated block leave more hidden values near zero than the GELU block, or fewer? One real token, " cat" in "The cat sat on the mat because it was tired.", through two real feed-forward blocks: GPT-2 small's (layer 6, a plain GELU block of width 4d) and SmolLM2-135M's (layer 15, a SwiGLU block of width 8d/3). In Fig. 3 each vector is a row of signed bars (up positive, down negative) and each weight matrix a glass plate drawn to scale, d tall and its hidden width wide: both blocks cost 8d2 parameters. Switch blocks; in the SwiGLU block, try another gate function on the same pre-activations.

  1. The input. One token, " cat", as GPT-2 small's sixth block sees it after LayerNorm: 768 numbers (the first 24 drawn).
  2. Up projection. A 768 × 3,072 matrix (plus a bias) widens it four times: 2.36 million multiply-adds. 88.8% of the 3,072 pre-activations are negative.
  3. GELU. Every negative pre-activation is squashed into GELU's dip, between −0.17 and 0, while positive ones pass almost unchanged. Only 5.5% of the hidden values are near zero by the 0.1 × rms test, yet 88.8% are small negatives: GELU leaves few exact zeros.
  4. Down projection. A 3,072 × 768 matrix brings it back to width d, the block's output added to the residual stream. Two matrices, 8d2 = 4.72 million parameters.

Vectors recorded with forward hooks by src/real_models.py (float32, stored as 16-bit integers with one scale per vector); the GELU and the gate products are recomputed in your browser from the stored pre-activations. The figure draws the first 32 hidden units; the percentages are over the whole vector. "Near zero" means |h| below 0.1 times the root mean square of that token's hidden vector. Gate functions other than SiLU are applied to SmolLM2's own gate pre-activations, which were trained for SiLU: illustrative, to show what each gate passes, not how a model trained with it would behave; the last step then shows the output the model computed with SiLU.

The answer (on this token)

More. GPT-2's GELU block leaves 5.5% of its 3,072 hidden values below 0.1 × rms, and 88.8% of them negative but small (inside GELU's dip); SmolLM2's SwiGLU block leaves 24.2% of its 1,536 below 0.1 × rms, and 50.7% negative, because the sign of each product comes from u. The gate shuts units multiplicatively, without the exact zeros of ReLU. One token each: the Inside real models tab gives the same measures over 283 thousand tokens and every layer.

Shazeer's results. All variants matched for parameters and computation, on T5's span-filling pre-training (the base model, d = 768) and then fine-tuned once on a mixture of GLUE, SuperGLUE and SQuAD. Lower log-perplexity is better; at 65,536 steps the bracket is the standard deviation over runs of the same model.

Read with the noise in mind: at 65,536 steps GEGLU (1.942 ± 0.004) and SwiGLU (1.944 ± 0.010) are indistinguishable, and both are about 0.05 below ReLU (1.997 ± 0.005), ten times the spread derived. The fine-tuning scores come from one run each and the paper calls them "noisy"; the spread T5 measured for the GLUE average was 0.235. Every gated variant beat every ungated one in pre-training perplexity, at both lengths derived from Table 1.

Why gating won. On this evidence PaLM (2022) and then Llama (2023) replaced ReLU and GELU with SwiGLU, accepting a third matrix, and nearly every open model since did the same; the root's Defaults across models tab shows the switch year by year. A later line of work goes the other way for inference speed: replacing SiLU and GELU with ReLU in a pre-trained Llama or Falcon and fine-tuning briefly brings back exact zeros that a server can skip (Mirzadeh et al. 2023, "ReLU Strikes Back").

What PaLM and Llama said when they adopted it (quoted)

PaLM: "they have been shown to significantly increase quality compared to standard ReLU, GeLU, or Swish activations (Shazeer, 2020). Note that this does require three matrix multiplications in the MLP rather than two" (Chowdhery et al. 2022, section 2). Llama: "We replace the ReLU non-linearity by the SwiGLU activation function ... We use a dimension of 2/3 4d instead of 4d as in PaLM" (Touvron et al. 2023, section 2.2).

Every gated variant beats every ungated one in pre-training perplexity

The 2/3 rule, and who follows it

A plain feed-forward block with hidden width 4d has two matrices: 2 · d · 4d = 8d2 parameters, and as many multiply-adds per token. A gated block has three: 3dh. Matching them gives h = 8d/3 = ⅔ · 4d. Shazeer did exactly this: "we reduce the hidden layer to dff = 2048" from 3,072 at d = 768 (2 × 768 × 3,072 = 3 × 768 × 2,048 = 4,718,592). Llama's code applies the same rule, then an optional multiplier, then rounds up to a hardware-friendly multiple:

h = m · ⌈ int(f · int(2 · 4d / 3)) / m ⌉
f
ffn_dim_multiplier (none in Llama 1)
m
multiple_of; both from meta-llama/llama, model.py and the per-model values in llama-models, sku_list.py

"Relative size" is 3h / 8d for a gated block (2h / 8d for a plain one): its parameters against a plain 4d block's. Every "rule gives" cell reproduces the released config.json independently (src/recompute.py). The parent's Defaults across models tab lists the FFN width of twenty-one models; this table adds the rule that produces it.

Correction: "usually shrunk to 2/3 · 4d" is one convention among several

PaLM uses SwiGLU with "dff always 4 × dmodel" (PaLM, section 2), so its feed-forward blocks are 1.5 times the size of a plain block; Gemma 3 keeps 4d or more with GeGLU; most of the Llama 3 family multiplies the 2/3 width by 1.2 to 1.5. Only Llama 1, Llama 3.2 3B and SmolLM2 in the table sit at (or within 1% of) the matched size. What survives everywhere is the habit of quoting the width relative to d, so always count three matrices.

Inside real models

The page's Inside real models tab measures every feed-forward hidden unit of three released models on the same 283,000-odd tokens of WikiText-2 (Wikipedia articles), layer by layer. Three findings:

So "sparse activations" means different things: exact zeros that a server can skip in a ReLU model, mostly small values in a GELU or SwiGLU model. The published numbers it checks: Voita et al. on dead neurons in OPT (qualitatively, on less data and the smallest model), and Mirzadeh et al.'s "all layers exhibit sparsity exceeding 90%" for OPT 6.7B (OPT-125m: ).

Mostly small is not the same as removable. In Qwen3.6-35B-A3B, a SwiGLU mixture of experts, keeping only the strongest 7.8% of routed activations moved web-text loss only from 1.886 to 1.940, but reasoning collapsed into loops until a light fine-tune, which the authors tie to the double-negative quadrant above (the companion paper of Neural Networks Are Already Clean). Weak activations are cheap for loss, not for reasoning; test a sparsification on a reasoning task, not on perplexity alone.

The output layer, and softmax as an activation

The last layer's activation is chosen by what the output has to be, and it must agree with the loss (the loss for each is on Loss functions). In PyTorch the loss usually applies the output activation itself, so the network should end with the raw scores (logits):

The output isOutput activationPyTorch loss, fed what
any real number (regression)none (linear)MSELoss, HuberLoss, on the value
a positive number (a rate, a variance)softplus or expPoissonNLLLoss(log_input=True) on the log rate; GaussianNLLLoss on a softplus variance
a value in a fixed rangetanh, then rescalefor example continuous actions in DDPG: "The final output layer of the actor was a tanh layer, to bound the actions" (Lillicrap et al. 2015)
yes or nosigmoidBCEWithLogitsLoss, on the logit
several yes/no labels at onceone sigmoid per labelBCEWithLogitsLoss, on the logits
one class out of KsoftmaxCrossEntropyLoss, on the logits
the next tokensoftmax over the vocabularycross entropy on the logits in training; at generation the logits are divided by a temperature and filtered (top-k, top-p, min-p)

Softmax, in four facts. (1) Adding a constant to every logit changes nothing, softmax(z + c) = softmax(z), which is why every implementation subtracts the largest logit before exponentiating (without it, e1000 overflows). (2) With two classes it is the sigmoid: softmax([x, 0])1 = σ(x) checked to 10−15, so a binary sigmoid output is a two-class softmax with one logit fixed at 0. (3) Its derivative, ∂pi/∂zj = pi(δij − pj), goes to zero as one probability approaches 1: a softmax saturates like a sigmoid, which is why it is paired with a log in the loss (cross entropy's gradient on the logits is simply p − y). (4) A temperature T, softmax(z/T), sharpens (T < 1) or flattens (T > 1) the distribution without changing the order; try it on a real model's logits in the Sampler lab of Sampling and Decoding. Softmax also normalises attention scores (Attention Is All You Need) and mixture-of-experts router scores.

Correction: with a large vocabulary, the cost is the projection, not the softmax (the numbers)

The old page called softmax "expensive for very large K". The exponentials are cheap; what grows with the vocabulary V is the output projection that produces the logits: d · V multiply-adds per token against V exponentials. For Qwen2.5-0.5B (d = 896, V = 151,936, config.json) that is 136 million multiply-adds against 152 thousand exponentials, 896 times more derived; and in training the logits themselves take memory: a batch of 8 sequences of 4,096 tokens holds 8 × 4,096 × 151,936 = 5.0 billion logits, 19.9 GB in 32-bit floats derived. Sampled and hierarchical softmaxes, and fused or chunked cross-entropy kernels, target these two costs.

Common mistakes, nine of them (each with its fix)
Applying softmax (or sigmoid) before a loss that applies it again
CrossEntropyLoss expects "the unnormalized logits for each class" (PyTorch docs); a softmax in front of it squashes the scores twice, so training still runs but the gradients are wrong and confidence is capped. End the network with logits and put the softmax only where probabilities are read.
Sigmoid followed by BCELoss instead of BCEWithLogitsLoss
The combined loss "is more numerically stable than using a plain Sigmoid followed by a BCELoss as, by combining the operations into one layer, we take advantage of the log-sum-exp trick for numerical stability" (PyTorch docs). A saturated sigmoid rounds to exactly 0 or 1, and the log of that is infinite.
A ReLU or sigmoid on a regression output
A ReLU output can never predict a negative value and receives no gradient when it outputs 0; a sigmoid caps it at 1. Regression outputs are linear unless the target's range is known (then softplus for positive values, tanh for a bounded range).
Running a checkpoint with a different GELU
GPT-2 runs with the tanh form, CLIP with x σ(1.702x), BERT's Hugging Face configs with the exact form. The tanh form is within 4.7 × 10−4 of exact; the sigmoid form is off by up to 0.020 per unit, which compounds over layers. Use the activation string in the model's config (gelu, gelu_new, gelu_pytorch_tanh, quick_gelu).
Treating SiLU and GELU as the same function
They differ by up to 0.19 (above). Swapping one for the other in a trained model changes its outputs; in a model trained from scratch either works.
Counting a SwiGLU block as two matrices
It has three, so its parameters are 3dh. A width quoted as "4d" means a block 1.5 times the size of a plain 4d one (PaLM, Gemma 3); "2.69d" means the matched size (the 2/3 rule).
An initialisation that does not match the activation
Xavier was derived for sigmoid and tanh, He for the ReLU family, LeCun's 1/n for SELU; the wrong one shrinks or grows the signal at every layer. The parent's thread 2 ("keep the variance constant", in the Reading tab of Topic: ml-fundamentals) shows each mismatch, and the Activation atlas table gives the variance-preserving gain of every function here; the details are on Normalisation and initialisation.
Expecting exact zeros from a SwiGLU model
SiLU is never exactly 0 for a nonzero input, so a SwiGLU block has small values, not zeros; tricks that skip zero rows (built for ReLU models such as OPT) need a threshold or a ReLU fine-tune first (Mirzadeh et al. 2023). See the Inside real models tab.
Blaming the activation for a learning rate that is too high
In the runs above, ReLU networks die and leaky ReLU networks overflow at the same learning rates. Swapping the activation changes the symptom; lowering or warming up the rate removes the cause. The parent's When training goes wrong tab goes from symptom to cause.