Overview
SiLU, also called Swish, gates each input by a factor the input itself decides. The factor is the sigmoid of the input, a number between 0 and 1. A large positive input has a factor near 1 and passes almost unchanged. A large negative input has a factor near 0 and is almost removed. Near zero the factor is about one half. The result looks like ReLU with the corner rounded off and a shallow dip below zero. The parameter controls how sharp the rounding is.
A short history
Dan Hendrycks and Kevin Gimpel mentioned the sigmoid linear unit in their 2016 GELU paper. Stefan Elfwing, Eiji Uchibe and Kenji Doya studied it for reinforcement learning in 2017. In the same year Prajit Ramachandran, Barret Zoph and Quoc Le found the same function through an automated search over activations and named it Swish. Their results showed it could replace ReLU in deep image models with a small gain in accuracy.
How it works
- Take the input that a layer has computed for one unit.
- Compute the gate , a number between 0 and 1.
- Multiply: the output is .
- During training, multiply the incoming gradient by .
Watch out for
- The output dips to about near when , so the function is not monotonic and outputs are not non-negative.
- It costs one exponential per element, more than ReLU. Mobile models sometimes use a piecewise-linear stand-in called hard swish for that reason.
- In the template is a fixed setting. The original Swish paper also tried learning it, which this small version does not do.
Use cases
When to use it
Modern convolutional networks such as EfficientNet, diffusion models, and the gate inside SwiGLU feed-forward blocks, where a smooth activation trains better than ReLU.
In industry
- Computer vision
- The EfficientNet family of image classifiers uses Swish throughout, and later YOLO detectors use SiLU in their convolution blocks.
- Image generation
- The U-Net denoisers in diffusion models use SiLU in their residual blocks and time embedding layers.
- Language models
- SiLU is the gating function inside the SwiGLU feed-forward blocks of several recent large language models.
Choosing it: what must hold
- A deep network with normalisation layers, where a smooth activation helps optimisation.
- Compute for a sigmoid per value, which costs more than ReLU.
- On mobile hardware, support for the function or a willingness to use the piecewise hard swish approximation.
When to choose something else
| If | Use instead |
|---|---|
| Latency or low precision arithmetic is the constraint | ReLU, or ReLU6 on mobile |
| The model is a transformer with a plain feed-forward block | GELU |
| You are building a gated feed-forward block | SwiGLU |
Math foundations
The sigmoid gate
Maps any number to the range 0 to 1. Here it decides what share of the input to keep.
The activation
The input scaled by its own gate. With this is SiLU. With general it is Swish.
Its slope
From the product rule, since the derivative of the sigmoid is . At the slope is exactly 0.5.
The two limits
A very large makes the gate a hard switch and recovers ReLU. A very small fixes the gate at one half and gives a linear function. SiLU sits between.
Symbols
- the input to the activation (one unit's pre-activation)
- sharpness of the gate,
betain the config, default 1 - the logistic sigmoid
- the gate value, sigmoid of beta times x
Worked by hand
Compute SiLU and its slope at with . Use .
The output is 0.7311 and the slope is 0.9277. ReLU would give 1 and 1, and GELU gives 0.8413, so SiLU is the gentlest of the three at this input.
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 SiLU
from config import SiLUConfig
act = SiLU(SiLUConfig(beta=1.0))
y = act.forward(np.array([-1.0, 0.0, 1.0])) # [-0.2689, 0.0, 0.7311]
dy = act.backward(np.array([-1.0, 0.0, 1.0])) # [0.0723, 0.5, 0.9277]Read the implementation (40 lines)
"""SiLU / Swish: f(x) = x * sigmoid(beta * x).
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 SiLUConfig
except ImportError: # run from the template's own folder
from config import SiLUConfig
def _sigmoid(x: np.ndarray) -> np.ndarray:
"""Logistic function 1 / (1 + exp(-x)), written so that large |x| cannot overflow."""
return np.exp(-np.logaddexp(0.0, -x))
class SiLU:
"""f(x) = x * sigmoid(beta * x)."""
def __init__(self, config: SiLUConfig | None = None) -> None:
self.config = config or SiLUConfig()
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)
return x * _sigmoid(self.config.beta * x)
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).
With s = sigmoid(beta * x): f'(x) = s + beta * x * s * (1 - s).
"""
x = np.asarray(x, dtype=float)
s = _sigmoid(self.config.beta * x)
local = s + self.config.beta * x * s * (1.0 - s)
return local if grad_output is None else local * np.asarray(grad_output, dtype=float)
__call__ = forward- Repository
- gitlab.com/designsbyduhart/solomon-templates/activation-silu
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Build SiLU(SiLUConfig(beta=1.0)) and find the minimum of forward on 2001 points between -5 and 5. Then repeat with beta of 0.1 and 10 and compare each curve with and with ReLU.
Check on learning
- As grows the curve approaches ReLU. What is lost and what is gained along the way?
A way to think about it
Track two things as rises: the width of the smooth region near zero and the depth of the negative dip. Both shrink toward ReLU's corner.
- GELU is well approximated by . What does that tell you about choosing between GELU and SiLU?
A way to think about it
That approximation is Swish with a particular . The two are members of one family with slightly different sharpness, so expect small differences.
- ReLU has zero slope for all negative inputs. SiLU has a small negative slope for inputs below about . Which is more likely to leave a unit stuck?
A way to think about it
A unit is stuck when it gets no gradient. Compare exactly zero with small and nonzero, and consider that SiLU's slope tends to zero only far out in the tail.
- Why might a quantised mobile model replace SiLU with a piecewise-linear imitation?
A way to think about it
Think about what an exponential costs in integer arithmetic, and how well straight segments can follow a curve whose interesting part is a narrow band.