Overview
Mish belongs to the same family as SiLU and GELU: the input is multiplied by a smooth factor between 0 and 1 that depends on the input itself. Here the factor is built in two stages. Softplus turns the input into a positive number, and tanh squashes that number into the range 0 to 1. For large positive inputs the factor is close to 1, so the input passes almost whole. For large negative inputs it is close to 0. In between, the curve is smooth and dips slightly below zero.
A short history
Diganta Misra proposed Mish in 2019 as a smooth, self-gated activation in the same family as Swish. The name is not an acronym. In his experiments it gave small accuracy gains over ReLU and Swish on image classification. It became widely known in 2020 when YOLOv4 adopted it in its backbone.
How it works
- Take the input that a layer has computed for one unit.
- Compute the softplus, , a smooth positive version of .
- Take the tanh of that. The result lies between 0 and 1.
- Multiply: the output is .
- During training, multiply the incoming gradient by .
Watch out for
- It needs an exponential, a logarithm and a tanh per element, so it is noticeably slower than ReLU and somewhat slower than SiLU.
- The output dips to about near , so the function is not monotonic and outputs are not non-negative.
- Computed naively, overflows for large . The template uses
logaddexpfor the softplus, and a hand-written version needs the same care.
Use cases
When to use it
Convolutional vision models, object detectors in particular, where a smooth activation with a small negative region has been found to train better than ReLU.
In industry
- Object detection
- YOLOv4 uses Mish in its CSPDarknet53 backbone for real time detection of objects in images and video.
- Image classification
- Practitioners training convolutional classifiers swap ReLU for Mish to gain a small amount of accuracy when training time is not the limit.
- Medical imaging
- Research groups training segmentation networks on scans test Mish as a drop-in replacement where a smoother activation helps optimisation.
Choosing it: what must hold
- A deep convolutional network where a small accuracy gain justifies a slower activation.
- Compute and memory to spare: Mish needs an exponential, a logarithm and a tanh per value.
- Time to compare against ReLU or SiLU on your own data, since the gain is not guaranteed.
When to choose something else
| If | Use instead |
|---|---|
| You want nearly the same shape at lower cost | SiLU (Swish) |
| Inference speed or mobile hardware is the constraint | ReLU |
| The model is a transformer | GELU |
Math foundations
Softplus
A smooth curve that is close to 0 for very negative and close to for very positive . Its derivative is the sigmoid .
The activation
The input scaled by a factor between 0 and 1. Compare SiLU, which scales by , and GELU, which scales by the normal CDF.
Its slope
From the product rule and the chain rule: the derivative of tanh is and the derivative of softplus is the sigmoid. This is what
backwardcomputes.
Symbols
- the input to the activation (one unit's pre-activation)
- the gating factor, tanh of softplus of x
- the logistic sigmoid, 1 / (1 + exp(-x))
- the natural logarithm
Worked by hand
Compute Mish and its slope at . Use , and .
The output is 0.8651 and the slope is 1.0490. GELU gives 0.8413 at the same input and SiLU gives 0.7311, so Mish sits closest to the identity.
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 Mish
act = Mish()
y = act.forward(np.array([-1.0, 0.0, 1.0])) # [-0.3034, 0.0, 0.8651]
dy = act.backward(np.array([-1.0, 0.0, 1.0])) # gradient with respect to the inputRead the implementation (40 lines)
"""Mish: f(x) = x * tanh(softplus(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 MishConfig
except ImportError: # run from the template's own folder
from config import MishConfig
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 Mish:
"""f(x) = x * tanh(log(1 + exp(x)))."""
def __init__(self, config: MishConfig | None = None) -> None:
self.config = config or MishConfig()
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 * np.tanh(np.logaddexp(0.0, x)) # logaddexp(0, x) is softplus without overflow
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 t = tanh(softplus(x)): f'(x) = t + x * (1 - t^2) * sigmoid(x), because softplus' = sigmoid.
"""
x = np.asarray(x, dtype=float)
t = np.tanh(np.logaddexp(0.0, x))
local = t + x * (1.0 - t**2) * _sigmoid(x)
return local if grad_output is None else local * np.asarray(grad_output, dtype=float)
__call__ = forward- Repository
- gitlab.com/designsbyduhart/solomon-templates/activation-mish
- Needs
- Python 3.10 and NumPy
- Tests
- 7, run with
python3 -m unittest -v
Practice
Build Mish() and evaluate forward on 2001 points between -5 and 5. Find the minimum value and where it occurs. Check backward against a finite difference there, and confirm the slope is zero at the minimum.
Check on learning
- Mish, SiLU and GELU all have the form times a factor between 0 and 1. What would you compare to decide whether the choice among them matters for your model?
A way to think about it
Plot the three factors. They differ mostly for inputs between about and 2. Then ask how much of your pre-activation distribution falls in that band.
- The slope of Mish is negative for inputs below about . What does a negative slope do to the gradient passed back through that unit?
A way to think about it
It flips the sign. Consider whether that is a problem or simply another direction the optimiser can use, given that the size is small.
- Why does the template compute softplus with
logaddexprather than writing out the logarithm of one plus the exponential?A way to think about it
Evaluate at in floating point. Then think about how can be rearranged so that only a negative exponent is ever taken.
- On a phone-sized model, Mish improves accuracy by 0.2 points but slows inference by 15 percent. How would you decide?
A way to think about it
Set the accuracy gain against the latency budget, and check whether the gain is larger than the spread between random seeds.