Sign in

ReLU

Rectified Linear Unit

An activation that keeps positive inputs unchanged and sets negative inputs to zero, optionally capped from above.

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

  1. Take the input xx that a layer has computed for one unit.
  2. Return xx if it is positive, otherwise return 0.
  3. If max_value is set to cc, also clip the result so it never exceeds cc.
  4. During training, pass the gradient through unchanged where 0<x0 < x (and x<cx < c 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

IfUse instead
Many units die during trainingLeaky ReLU or PReLU
The model is a transformerGELU, or SwiGLU for a gated block
You want a smooth activation in a deep convolutional networkSiLU (Swish)

Math foundations

  1. The activation

    ReLU⁡(x)=max⁡(0,x)\operatorname{ReLU}(x) = \max(0, x)

    The larger of zero and the input. It is two straight lines joined at the origin, so it is piecewise linear.

  2. Its slope

    ddxReLU⁡(x)={1,x>00,x≤0\frac{d}{dx}\operatorname{ReLU}(x) = \begin{cases} 1, & x > 0 \\ 0, & x \le 0 \end{cases}

    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.

  3. The capped form

    ReLU⁡c(x)=min⁡ ⁣(max⁡(0,x),  c)\operatorname{ReLU}_c(x) = \min\!\big(\max(0, x),\; c\big)

    Clips the output to the range from 0 to cc. With c=6c = 6 this is ReLU6. A bounded range is easier to represent with a few bits.

  4. Slope of the capped form

    ddxReLU⁡c(x)={1,0<x<c0,otherwise\frac{d}{dx}\operatorname{ReLU}_c(x) = \begin{cases} 1, & 0 < x < c \\ 0, & \text{otherwise} \end{cases}

    The gradient passes only in the open band between the two corners. Both flat regions block it.

Symbols

xx
the input to the activation (one unit's pre-activation)
cc
the optional upper cap; max_value in the config, no cap by default

Worked by hand

Apply ReLU with a cap of c=6c = 6 to the inputs −1.5-1.5, 0.50.5 and 77.

ReLU⁡6(−1.5)=min⁡(max⁡(0,−1.5),6)=0\operatorname{ReLU}_6(-1.5) = \min(\max(0, -1.5), 6) = 0
ReLU⁡6(0.5)=min⁡(max⁡(0,0.5),6)=0.5\operatorname{ReLU}_6(0.5) = \min(\max(0, 0.5), 6) = 0.5
ReLU⁡6(7)=min⁡(max⁡(0,7),6)=6\operatorname{ReLU}_6(7) = \min(\max(0, 7), 6) = 6
slopes: 0,  1,  0\text{slopes: } 0, \; 1, \; 0

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

  1. 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.

  2. 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.

  3. 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.

  4. 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.