Before you start: three words#
| Word | Plain meaning |
|---|---|
| Elementwise | Applied to each number on its own, with no mixing between numbers. |
| Sigmoid | 1 / (1 + e^-x): squashes any number into the range 0 to 1. Large negative → near 0, large positive → near 1. |
| Gate | A value between 0 and 1 (or a soft version of it) that decides how much of another value passes through. |
1. What is it?#
An activation function is a simple non-linear function applied to every number in a tensor separately. It usually has no parameters and never mixes numbers together.
ReLU(x) = max(0, x)
GELU(x) = x · Φ(x) Φ = the standard normal cumulative distribution
SiLU(x) = x · sigmoid(x) also called Swish
SwiGLU(x, y) = SiLU(x) · y a *gated* form: two inputs, one controls the otherA worked number for each, at x = 0.5:
ReLU(0.5) = 0.5
SiLU(0.5) = 0.5 × sigmoid(0.5) = 0.5 × 0.622 = 0.311
GELU(0.5) = 0.5 × Φ(0.5) = 0.5 × 0.691 = 0.3462. Why does it exist?#
To break linearity, so that stacking layers achieves something (10.d). Beyond that, the specific choice affects how well a model trains and, for us, how much the kernel costs.
For inference the practical questions are: how expensive is it, can it be fused into a neighbouring operation, and does its range of values cause trouble at low precision?
3. Simple analogy#
A dimmer switch versus an on/off switch.
ReLU is a hard switch: below zero nothing passes; above zero everything passes. Simple and fast, but everything below zero is thrown away.
GELU and SiLU are dimmers: near zero they let a fraction through, smoothly. Slightly more expensive, and in practice better for transformers because small signals are not destroyed.
Gated forms (SwiGLU) add a second control: one signal decides how much of another passes — like a valve whose opening is itself computed from the data.
4. Tiny example#
package main
import (
"fmt"
"math"
)
func relu(x float64) float64 { return math.Max(0, x) }
func sigmoid(x float64) float64 { return 1 / (1 + math.Exp(-x)) }
func silu(x float64) float64 { return x * sigmoid(x) }
func geluExact(x float64) float64 {
return 0.5 * x * (1 + math.Erf(x/math.Sqrt2))
}
func geluTanh(x float64) float64 {
return 0.5 * x * (1 + math.Tanh(math.Sqrt(2/math.Pi)*(x+0.044715*x*x*x)))
}
func main() {
xs := []float64{-2.0, -0.5, 0.0, 0.5, 2.0}
fns := []struct {
name string
f func(float64) float64
}{{"relu", relu}, {"silu", silu}, {"gelu", geluExact}, {"gelu~", geluTanh}}
fmt.Printf("%-6s", "x")
for _, x := range xs {
fmt.Printf(" %7.3f", x)
}
fmt.Println()
for _, fn := range fns {
fmt.Printf("%-6s", fn.name)
for _, x := range xs {
fmt.Printf(" %7.3f", fn.f(x))
}
fmt.Println()
}
// The largest gap between exact GELU and its tanh approximation on [-5, 5].
worst, at := 0.0, 0.0
for x := -5.0; x <= 5.0; x += 0.001 {
if d := math.Abs(geluExact(x) - geluTanh(x)); d > worst {
worst, at = d, x
}
}
fmt.Printf("max |gelu - gelu~| on [-5,5] = %.1e at x = %.2f\n", worst, at)
}Output:
x -2.000 -0.500 0.000 0.500 2.000
relu 0.000 0.000 0.000 0.500 2.000
silu -0.238 -0.189 0.000 0.311 1.762
gelu -0.046 -0.154 0.000 0.346 1.954
gelu~ -0.045 -0.154 0.000 0.346 1.955
max |gelu - gelu~| on [-5,5] = 4.7e-04 at x = 2.70Three things to notice:
- SiLU and GELU go slightly negative for small negative inputs instead of clipping to zero. That smooth dip is part of why they train better than ReLU.
- They are different functions. At
x = -2, SiLU gives −0.238 and GELU −0.046. A model must be served with exactly the activation it was trained with. - The tanh approximation of GELU (
gelu~) differs from the exact one by at most about 0.0005. Small, but not zero — see section 5.
5. Technical explanation#
What models actually use#
| Model family | Feed-forward activation |
|---|---|
| BERT, GPT-2, GPT-3 | GELU |
| Llama 1–4, Mistral, Qwen 2–3, DeepSeek V2/V3 | SiLU in SwiGLU form |
| PaLM, Gemma 1–3 | GeGLU (GELU-gated; Gemma uses the tanh-approximated GELU) |
| gpt-oss (OpenAI, 2025) | a SwiGLU variant with clamped inputs, for stability |
| Older CNNs | ReLU |
Current language models almost all use a gated form. The feed-forward block becomes
down( act(gate(x)) * up(x) )with three matrices instead of two and d_ff ≈ 8d/3 to keep the parameter count similar (10.d).
Mixture-of-experts models use the same gated block inside every expert (14.g).
What it costs#
ReLU: 1 comparison ~1 operation
SiLU: 1 exp, 1 divide, 1 multiply ~10–20 operations
GELU exact: 1 erf ~20–40 operations
GELU tanh approx: 1 tanh, a few multiplies ~15–25 operationsThat sounds like a big difference, but all of these are memory-bound anyway. For a
(B, S, d_ff) tensor at 16 bits (2 bytes) per number:
bytes moved = 2·B·S·d_ff (read) + 2·B·S·d_ff (write) = 4 bytes per element
FLOPs ≈ 20 per element (SiLU)
arithmetic intensity = 20 / 4 = 5 FLOP/byte
an H100's "ridge point" is ~300 FLOP/byte (989 TFLOP/s ÷ 3.35 TB/s, 2.f)At 5 FLOP/byte the arithmetic units are nearly idle, waiting for memory. So an unfused activation costs one full read and write of the tensor whichever function it is. The choice of activation is nearly free; the choice to fuse it is not.
Fused into the end (“epilogue”) of the preceding matmul, the activation costs almost nothing: the values are already sitting in registers (section 6).
Exact GELU versus the tanh approximation#
exact: gelu(x) = 0.5 · x · (1 + erf(x / √2))
approximation: gelu(x) ≈ 0.5 · x · (1 + tanh(√(2/π) · (x + 0.044715·x³)))The maximum gap is about 5 × 10⁻⁴, as measured above. The approximation was faster on hardware
without a fast erf. They are not bit-identical, so a model trained with one and served with
the other sees a tiny shift in its numbers. Usually harmless; occasionally the explanation for “my
ported model scores slightly differently”. PyTorch exposes both: gelu(x, approximate="tanh").
Low-precision considerations#
FP16 largest value ≈ 65,504 BF16 largest value ≈ 3.4 × 10^38 (10.k)Activations after a large up-projection can be big. SiLU and GELU are close to the identity for
large positive inputs, so they do not amplify — but the product in SwiGLU (act * up) can. In
FP16 that occasionally overflows to infinity. Fixes: compute in BF16 (huge range, now the default
for serving), compute the gate in FP32, or clamp the inputs (as gpt-oss does). Large activation
outliers are also what make activation quantization hard (13.d).
6. Under the hood#
In a fused kernel the activation lives in the matmul’s epilogue:
... tensor cores accumulate the matmul result in on-chip storage ...
epilogue:
acc = acc * scale + bias # on chip
acc = silu(acc) # on chip — effectively FREE
store acc to HBM # the only memory trafficCompare with the unfused version:
matmul kernel: write the result to HBM
activation kernel: read it from HBM, compute, write it back
→ two extra trips over the whole tensorFor a (2048, 14336) tensor at 16 bits, that is 2 × 59 MB = 118 MB of avoidable traffic per
matrix per layer — several gigabytes over a whole prefill. This is why torch.compile, TensorRT
and every serious engine fuse epilogues (11.h, 13.j).
7. Performance implications#
- An unfused activation costs a full memory round trip. Fuse it.
- The specific function barely matters for speed once fused.
- Gated activations add an elementwise multiply and a third matrix, but the matrices are smaller, so the total cost is about the same.
- Merging gate and up into one matmul (concatenating their weights) turns two matmuls into
one larger, more efficient one; the epilogue splits the result and applies
silu(gate) * up.
8. Production implications#
- Check that your engine fuses activations. In an Nsight kernel list (6.d), a standalone
siluoract_and_mulkernel between matmuls is common and acceptable when it fuses the gate multiply; a separate kernel for every elementwise step is performance left on the table. - Match the activation exactly to the model’s config (
hidden_actinconfig.json). GELU exact versus tanh, or SiLU versus GELU, silently shifts outputs. - Watch for overflow in FP16 SwiGLU. BF16 avoids it.
9. Common mistakes#
Substituting GELU for SiLU, or exact for tanh. Numerically different; quality shifts.
Leaving activations unfused. A common 5–15% loss.
Assuming activations are compute-bound. They are bandwidth-bound.
Forgetting SwiGLU has three matrices when counting parameters or FLOPs.
10. Hands-on exercise#
A. Plot them. Plot ReLU, GELU (exact and tanh), and SiLU on [−5, 5], and the gap between the two GELUs. Does the largest gap match the program’s answer?
B. Measure fusion. In PyTorch, time y = x @ W; z = F.silu(y) as two operations against the
same code under torch.compile. Report the speedup and explain it in bytes moved.
C. Overflow hunt. Build FP16 tensors on which SwiGLU overflows to infinity. At what input sizes does it happen? Repeat in BF16 and explain the difference.
D. Wrong activation. Take a small open model that uses SiLU, swap in GELU, and measure the change in perplexity on a small text sample.
11. Interview questions#
- Why do neural networks need activation functions?
- What is SwiGLU and why do current LLMs use it?
- Is the choice of activation a significant performance decision? Explain.
- What does fusing an activation into a matmul save, and how much?
- Why might FP16 SwiGLU overflow, and what would you do about it?
- What is the difference between exact and tanh-approximated GELU, and when does it matter?
12. Further reading#
- [ESTABLISHED] Shazeer, “GLU Variants Improve Transformer” (2020).
- [ESTABLISHED] Hendrycks & Gimpel, “Gaussian Error Linear Units (GELUs)” (2016).
- [REFERENCE] PyTorch
torch.nn.functional.gelu— theapproximateargument. - [REFERENCE] gpt-oss model card — the clamped SwiGLU variant.