Overview
ReLU is a one-way valve. A positive input passes through untouched and a negative input is replaced by zero. That single bend is enough to make a stack of layers nonlinear, and it is as cheap as an activation can be: one comparison. Because the slope on the positive side is exactly 1, gradients pass back through active units without shrinking. The price is that an inactive unit passes back nothing. With the optional cap, outputs above max_value are clipped, which gives ReLU6 when the cap is 6.
A short history
The rectifier appeared in Kunihiko Fukushima's work on visual pattern recognition around 1969. Vinod Nair and Geoffrey Hinton showed in 2010 that rectified units improve restricted Boltzmann machines, and Xavier Glorot, Antoine Bordes and Yoshua Bengio showed in 2011 that they let deep networks train without pretraining. AlexNet used ReLU in 2012 and trained several times faster than with tanh, after which it became the default activation.
How it works
- Take the input that a layer has computed for one unit.
- Return if it is positive, otherwise return 0.
- If
max_valueis set to , also clip the result so it never exceeds . - During training, pass the gradient through unchanged where (and when capped), and block it everywhere else.
Watch out for
- A unit whose inputs are negative for every example has zero gradient and stops learning. This dying ReLU problem is made worse by a high learning rate or a large negative bias.
- Outputs are never negative, so the mean activation is positive. That shifts the inputs of the next layer unless a normalisation layer corrects it.
- The slope is undefined at exactly zero. The template uses 0 there, and at the cap, and other libraries may differ, which shows up in gradient checks placed on the corner.
- With a cap, large inputs also get zero gradient, so a unit can die on the high side as well.
Use cases
When to use it
The default for convolutional and plain feed-forward networks, where speed and simplicity matter. Use the cap of 6 for models that will be quantised to low-precision integers.
In industry
- Computer vision
- Convolutional networks such as ResNet, used for image classification and detection, apply ReLU after almost every convolution.
- Mobile and embedded
- MobileNet uses ReLU6, a ReLU capped at 6, so activations stay in a range that survives low precision arithmetic on phones.
- Recommendation and ads
- The feed-forward towers of click prediction and recommendation models use ReLU because it is cheap at very high request volumes.
Choosing it: what must hold
- Sensible weight initialisation, such as He initialisation, so that units do not start in the dead region.
- A learning rate low enough that large updates do not push many units permanently negative.
- Tolerance for outputs that are never negative, usually handled with batch or layer normalisation.
When to choose something else
| If | Use instead |
|---|---|
| Many units die during training | Leaky ReLU or PReLU |
| The model is a transformer | GELU, or SwiGLU for a gated block |
| You want a smooth activation in a deep convolutional network | SiLU (Swish) |
Math foundations
The activation
The larger of zero and the input. It is two straight lines joined at the origin, so it is piecewise linear.
Its slope
The factor backpropagation multiplies by. A slope of exactly 1 neither shrinks nor grows the gradient through active units. The value 0 at the corner is a convention.
The capped form
Clips the output to the range from 0 to . With this is ReLU6. A bounded range is easier to represent with a few bits.
Slope of the capped form
The gradient passes only in the open band between the two corners. Both flat regions block it.
Symbols
- the input to the activation (one unit's pre-activation)
- the optional upper cap;
max_valuein the config, no cap by default
Worked by hand
Apply ReLU with a cap of to the inputs , and .
Only the middle input is in the active band, so only it passes a gradient. Without the cap the third input would give 7 with slope 1.
Visual example
Loading the example.
Try this
- Move across the curve and read the output and the slope together.
- Find where the slope is close to zero: a unit there has stopped learning.
Code sample
import numpy as np
from impl import ReLU
from config import ReLUConfig
act = ReLU(ReLUConfig())
y = act.forward(np.array([-2.0, 0.0, 3.0])) # [0.0, 0.0, 3.0]
dy = act.backward(np.array([-2.0, 0.0, 3.0])) # [0.0, 0.0, 1.0]
relu6 = ReLU(ReLUConfig(max_value=6.0)) # output clipped to [0, 6]Read the implementation (40 lines)
"""ReLU: rectified linear unit, f(x) = max(0, x), optionally capped from above.
NumPy only. `forward` computes the activation, `backward` the gradient with respect to the input.
"""
from __future__ import annotations
import numpy as np
try:
from .config import ReLUConfig
except ImportError: # run from the template's own folder
from config import ReLUConfig
class ReLU:
"""f(x) = max(0, x), or min(max(0, x), max_value) when a cap is set."""
def __init__(self, config: ReLUConfig | None = None) -> None:
self.config = config or ReLUConfig()
def forward(self, x: np.ndarray) -> np.ndarray:
"""Apply the activation element by element. x: any shape. Returns the same shape."""
x = np.asarray(x, dtype=float)
y = np.maximum(x, 0.0)
if self.config.max_value is not None:
y = np.minimum(y, self.config.max_value)
return y
def backward(self, x: np.ndarray, grad_output: np.ndarray | None = None) -> np.ndarray:
"""d f / d x at x, times `grad_output` when given (the chain rule step of backpropagation).
The gradient is 1 where 0 < x (and x < max_value when a cap is set), and 0 elsewhere, kinks included.
"""
x = np.asarray(x, dtype=float)
active = x > 0
if self.config.max_value is not None:
active &= x < self.config.max_value
local = active.astype(float)
return local if grad_output is None else local * np.asarray(grad_output, dtype=float)
__call__ = forward- Repository
- gitlab.com/designsbyduhart/solomon-templates/activation-relu
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Build ReLU(ReLUConfig()) and ReLU(ReLUConfig(max_value=6.0)). Run forward and backward on 13 points from -3 to 9 and list where the two differ. Then draw 1000 standard normal inputs and report what share of them get zero gradient.
Check on learning
- A network trains well, then after a learning-rate spike a third of its units output zero for every input. What happened, and why do they not recover?
A way to think about it
A large step can push a unit's bias so negative that no input activates it. Then look at the slope formula for negative inputs.
- ReLU is made of two straight lines. How can a network of such units approximate a smooth curve?
A way to think about it
Each unit contributes one bend at a place its weights choose. Sketch what the sum of several shifted and scaled bends looks like.
- About half of standard normal inputs to ReLU are negative. Is having half the units output zero a waste?
A way to think about it
Different inputs switch off different units, so each example uses its own sub-network. Sparse outputs can also be cheap to store. Compare that with a unit that is off for every input.
- Why does a cap of 6 help when weights and activations are stored in 8 bits?
A way to think about it
Eight bits give 256 levels. Spread them over a range of 0 to 6, then over a range of 0 to 1000, and compare the step between neighbouring levels.