Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

LABS · 09  /  ACTIVATIONS

The Bend.

Stack a hundred layers of pure linear algebra and you still get… a straight line. The bend — a non-linear activation on every neuron — is what lets a network learn curves. Slide a point along each one and read its gradient: where it's alive, and where it dies.

THE GIST · 20 SECONDS

An activation function adds non-linearity to each neuron — without it, deep layers collapse into one linear map. Its derivative is what backprop multiplies to learn, so a flat region means a dying gradient. Sigmoid/tanh saturate (slope → 0 at the edges); ReLU keeps a slope of 1 for x > 0; GELU is a smooth modern default.

  • Non-linearlets nets learn curves
  • Derivativewhat backprop uses
  • Saturateslope → 0 = no learning
  • ReLUslope 1, no vanish

Pick a function, then drag the x slider to move the point — the tangent's steepness is the gradient backprop would use there.

UNDER THE HOOD

What you just played, written down

The shape of an activation decides what a network can represent; the shape of its derivative decides whether the network can actually learn it.

Why activations matter — four ideas

  1. Linearity collapses. Stacking linear layers without a bend equals one linear layer — no matter the depth.
  2. The bend adds power. A non-linear activation lets layers combine into arbitrarily complex, curved functions.
  3. Backprop multiplies derivatives. Each layer's gradient carries the activation's slope, chained back through the network.
  4. Flat slope = no learning. Where the derivative is near zero (saturation), the gradient vanishes and those weights barely move.
THE ReLU REVOLUTION

Sigmoid's derivative peaks at just 0.25 and falls to ~0 at the edges — stack a few layers and the gradient dwindles. ReLU's derivative is a flat 1 for x > 0, so gradients pass through undimmed. That's a big reason deep nets became trainable.

The functions in code

import numpy as np

def sigmoid(x): return 1 / (1 + np.exp(-x))   # (0, 1)
def tanh(x):    return np.tanh(x)             # (-1, 1)
def relu(x):    return np.maximum(0, x)       # slope 1 for x>0
def leaky(x):   return np.where(x > 0, x, 0.1 * x)
def gelu(x):
    return 0.5 * x * (1 + np.tanh(
        np.sqrt(2/np.pi) * (x + 0.044715 * x**3)))

# derivatives are what backprop multiplies:
d_sigmoid = lambda x: (s := sigmoid(x)) * (1 - s)  # max 0.25
d_relu    = lambda x: (x > 0).astype(float)        # 1 or 0
SIGMOID f'ₘₐₓ0.25vanishes at edges
ReLU f' (x>0)1.0no saturation
DEAD ReLUs → LEAKY & GELU

ReLU's flat zero for x < 0 can leave neurons dead (always outputting 0). Leaky ReLU gives a small negative slope; GELU curves smoothly and became the Transformer default (BERT, GPT-2), while many newer LLMs use its gated relative, SwiGLU.

⚠ Softmax is different

Softmax isn't a per-neuron activation — it's applied across a whole output layer to produce a probability distribution. It's a normalizer for classification, not a hidden-layer bend.

↔ Picking one

ReLU is a safe default for hidden layers; GELU or SwiGLU for Transformers; sigmoid for a single probability output; tanh when you want zero-centered outputs. Rarely sigmoid/tanh in deep hidden layers.

★ Why it's everywhere

Every neuron in every neural network passes through one of these. The choice affects how fast — and how deep — a model can learn. It's a small function with an outsized impact.

STEP BY STEP

Activation functions, step by step

Where the bend sits in a layer, what it does to the gradient on the way back, and each function's values and slopes computed at the same few points, so the numbers the widget's meters show are on the page too.

One layer, forward and back

  1. Mix. The layer computes a pre-activation z = W·x + b, a purely linear step.
  2. Bend. It applies a = f(z) to each element. Without this step, two layers W₂(W₁x + b₁) + b₂ equal the single layer (W₂W₁)x + (W₂b₁ + b₂).
  3. Gate the gradient. On the way back, the gradient arriving at a is multiplied element by element by f′(z): a slope of 0 blocks it, a slope of 1 passes it unchanged.
  4. Compound with depth. The gradient reaching layer 1 carries one f′ factor, and one weight matrix, from every layer above it. Factors that sit below 1 shrink it geometrically.
# forward
z = W @ x + b
a = f(z)
# backward through the bend
dL_dz = dL_da * f_prime(z)

Worked example: values and slopes

  1. Collapse. Layers 2x + 1 and then 3h − 4 compose to 3(2x + 1) − 4 = 6x − 1: still a straight line.
  2. Sigmoid. f(0) = 0.5 and f(2) = 0.881; the slope is 0.25 at 0, 0.105 at 2 and 0.0066 at 5. At the widget's starting point, x = 1.5, it reads f = 0.818 and f′ = 0.149.
  3. tanh. f(2) = 0.964; the slope is 1 at 0 but 0.071 at 2. Zero-centered, and saturating just the same.
  4. ReLU and leaky ReLU. ReLU gives f(2) = 2 with slope 1 and f(−2) = 0 with slope 0. With this page's leak of 0.1, f(−2) = −0.2 and the slope stays 0.1.
  5. GELU, x·Φ(x). f(2) = 1.954 and f(−2) = −0.046; the slope is 0.5 at 0 and 1.085 at 2, so it can exceed 1. Its lowest output is −0.170, near x = −0.75.
  6. Ten layers deep. At best, sigmoid multiplies the gradient by 0.25¹⁰ ≈ 9.5 × 10⁻⁷; at x = 2 on every layer, 0.105¹⁰ ≈ 1.6 × 10⁻¹⁰. An active ReLU path multiplies it by 1¹⁰ = 1.

⚠ Match the initialization

The slope only helps if pre-activations stay in its useful range. Use He initialization with ReLU-family activations (weight variance 2/fan_in, a standard deviation of 0.0625 for 512 inputs) and Xavier with tanh or sigmoid. A learning rate that drives biases strongly negative is the usual cause of dead ReLUs.

↔ Exact vs approximate GELU

The code above uses the tanh approximation, which stays within 0.0005 of the exact x·Φ(x) on [−6, 6]. Libraries offer both; use whichever a pretrained model was trained with, since swapping them shifts every layer's output slightly.

★ In production

ReLU is still common in convolutional nets such as ResNet. BERT and GPT-2 use GELU. Llama uses SwiGLU: one projection passes through SiLU, x·σ(x), and gates a second, so the feed-forward block holds three matrices, and Llama shrinks its hidden width (11,008 for a 4,096-wide model) to keep the parameter count in line.

THE PICTURE

The picture: the gradient passing back through four bends

sigmoid, best case: each bend multiplies the gradient by f′ = 0.25 z1 0.0039 z2 0.0156 z3 0.0625 z4 0.25 loss 1 ReLU, every unit active: f′ = 1 passes it through unchanged z1 1 z2 1 z3 1 z4 1 loss 1 ReLU, but z3 < 0 for this input: f′ = 0 blocks everything below z1 0 z2 0 z3 0 z4 1 loss 1 4 layers back: sigmoid keeps 0.39% of the gradient, active ReLU 100%
Four layers with every weight set to 1, so only the bends act. Going backward, each layer multiplies the gradient by f′(z) at its own pre-activation. Sigmoid’s best case still divides it by 4 per layer. An active ReLU passes it untouched. A ReLU whose input is negative zeroes it, and nothing below that unit learns from this example. Real weights add their own factor at every step, which is why initialization matters as much as the choice of function.
TRADE-OFFS

Cost and trade-offs of each activation

Here Time is the forward work per element and Space is what the backward pass needs kept from the forward one.

CaseTimeSpaceWhy
ReLUOne comparisonOnly which inputs were positiveCheapest, and an active unit passes the gradient at 1. A unit stuck below zero passes nothing.
Leaky ReLUA comparison and a multiplySame as ReLUNever fully dead: the left slope is the leak (0.1 on this page; PyTorch defaults to 0.01). One more setting to choose.
SigmoidAn exp, an add and a divideIts output, since σ′ = σ(1 − σ)Slope at most 0.25, so it shrinks every gradient it touches. Right for a single probability at the output.
tanhAbout the same as sigmoidIts output, since tanh′ = 1 − tanh²Zero-centred with a peak slope of 1, but it saturates just as hard at the edges.
GELU (tanh form)A cube, a tanh and several multipliesIts inputThe costliest per element, smooth everywhere, and its slope can pass 1 (1.085 at x = 2).
SwiGLUA whole extra matrix multiplyBoth projections and the SiLU inputNot an elementwise swap: the feed-forward block goes from two matrices to three.

Per element, the differences barely matter. In a Llama-style block 4,096 wide with a hidden size of 11,008, the activation does a few operations on each of 11,008 hidden values per token, while the three matrix multiplies do 2 × 3 × 4,096 × 11,008 ≈ 270 million floating-point operations. The same arithmetic explains the odd width: three 4,096 × 11,008 matrices hold 135.3 million weights, against 134.2 million for the classic two matrices at four times the width (16,384). So pick an activation for what it does to the gradient, not for its speed.

WATCH FOR

Common mistakes with activations

  • A ReLU on the output layer

    A regression head that ends in ReLU can never predict a negative number, and once its pre-activation drops below zero it gets no gradient to climb back. Leave the last layer linear for real-valued targets, and use sigmoid or softmax only when the output really is a probability.

  • Squashing twice before the loss

    PyTorch’s CrossEntropyLoss and BCEWithLogitsLoss take raw scores (logits) and apply softmax or sigmoid inside, in a numerically stable form. Add your own softmax or sigmoid first and the model trains on a doubly squashed signal with weaker gradients, usually without any error message.

  • Writing sigmoid and its log naively

    In float32, exp overflows past about 88.7, so 1 / (1 + exp(-x)) at x = −100 computes exp(100) = inf. The result, 0, is fine. Its log is −inf, and the loss becomes inf or NaN. Use the library’s logsigmoid, or a loss that takes logits.

  • Feeding sigmoid outputs to the next layer

    Sigmoid outputs are always positive. For one example, every weight into the next neuron then gets a gradient with the same sign (the neuron’s error times a positive input), so those weights can only all rise or all fall together, and updates zig-zag. tanh is zero-centred, one reason it trained better as a hidden activation.

  • Gradient-checking across ReLU’s kink

    A finite-difference check at x = 0.0001 with a step of 0.001 straddles zero: (relu(0.0011) − relu(−0.0009)) / 0.002 = 0.55, while backprop correctly says 1. The check looks broken when the code is fine. Test at inputs well away from 0, and expect a few such mismatches on any ReLU network.

QUICK CHECK

Did it stick?

See every answer, with the reasoning
  1. Why does a neural network need a non-linear activation function?

    Answer: Because without it, stacked linear layers collapse into a single linear map — Composing linear functions gives another linear function, so any depth of purely-linear layers can only represent a straight-line relationship. A non-linear activation between layers is what lets the network model curves.

  2. What is the vanishing-gradient problem?

    Answer: Saturating activations have near-zero derivatives at the extremes, so gradients shrink toward zero through deep networks — Sigmoid and tanh flatten out for large |x|, so their derivative is nearly zero there. Multiplying many such small derivatives during backprop drives the gradient to ~0, and early layers stop learning.

  3. What is ReLU’s derivative for a positive input?

    Answer: exactly 1 — ReLU is f(x)=max(0,x), so for x>0 its slope is a flat 1 — gradients pass through undiminished, which is a key reason ReLU made deep networks trainable. For x<0 the derivative is 0.

FAQ

Activations, answered

What is an activation function?

A non-linear function applied to each neuron's output. Without it, stacked layers collapse into a single linear map, so the network could only learn straight lines. The bend is what enables deep networks to model curves.

Why does its derivative matter?

Backprop multiplies gradients layer by layer, including the activation's derivative. A near-zero derivative shrinks the gradient as it flows back — early layers stop learning.

What is the vanishing-gradient problem?

Saturating activations (sigmoid, tanh) flatten at the extremes, so their derivative is ~0 there. Multiplying many tiny derivatives through a deep net drives the gradient to zero, stalling training.

Why did ReLU win?

Its derivative is a flat 1 for positive inputs, so gradients pass undiminished, and it's cheap to compute — making much deeper networks trainable. Leaky ReLU and GELU patch its dead-neuron weakness.

What is GELU?

A smooth activation that acts like ReLU for large inputs but curves gently near zero and allows small negatives. It's the activation in BERT and GPT-2/GPT-3; many newer LLMs, such as Llama, use SwiGLU, a gated relative built on SiLU.

RESULT

—

Next → chain these derivatives backward through a network, layer by layer, and you're doing backpropagation — how a model actually learns.

Finished this one? 0 / 61 Labs done
NextThe Loss Landscape Next on the “Training a network” ladder · rung 3 of 7

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Labs