Sign in

Mish

Mish activation

A smooth activation that multiplies each input by the tanh of its softplus, giving a ReLU-like curve with a small negative dip.

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

  1. Take the input xx that a layer has computed for one unit.
  2. Compute the softplus, ln⁡(1+ex)\ln(1 + e^{x}), a smooth positive version of max⁡(0,x)\max(0, x).
  3. Take the tanh of that. The result tt lies between 0 and 1.
  4. Multiply: the output is x⋅tx \cdot t.
  5. During training, multiply the incoming gradient by t+x (1−t2) σ(x)t + x\,(1 - t^{2})\,\sigma(x).

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 −0.31-0.31 near x=−1.19x = -1.19, so the function is not monotonic and outputs are not non-negative.
  • Computed naively, exe^{x} overflows for large xx. The template uses logaddexp for 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

IfUse instead
You want nearly the same shape at lower costSiLU (Swish)
Inference speed or mobile hardware is the constraintReLU
The model is a transformerGELU

Math foundations

  1. Softplus

    softplus⁡(x)=ln⁡ ⁣(1+ex)\operatorname{softplus}(x) = \ln\!\big(1 + e^{x}\big)

    A smooth curve that is close to 0 for very negative xx and close to xx for very positive xx. Its derivative is the sigmoid σ(x)\sigma(x).

  2. The activation

    Mish⁡(x)=xtanh⁡ ⁣(softplus⁡(x))\operatorname{Mish}(x) = x \tanh\!\big(\operatorname{softplus}(x)\big)

    The input scaled by a factor between 0 and 1. Compare SiLU, which scales by σ(x)\sigma(x), and GELU, which scales by the normal CDF.

  3. Its slope

    ddxMish⁡(x)=t+x (1−t2) σ(x),t=tanh⁡ ⁣(softplus⁡(x))\frac{d}{dx}\operatorname{Mish}(x) = t + x\,(1 - t^{2})\,\sigma(x), \qquad t = \tanh\!\big(\operatorname{softplus}(x)\big)

    From the product rule and the chain rule: the derivative of tanh is 1−tanh⁡21 - \tanh^{2} and the derivative of softplus is the sigmoid. This is what backward computes.

Symbols

xx
the input to the activation (one unit's pre-activation)
tt
the gating factor, tanh of softplus of x
σ(x)\sigma(x)
the logistic sigmoid, 1 / (1 + exp(-x))
ln⁡\ln
the natural logarithm

Worked by hand

Compute Mish and its slope at x=1x = 1. Use ln⁡(1+e)=1.3133\ln(1 + e) = 1.3133, tanh⁡(1.3133)=0.8651\tanh(1.3133) = 0.8651 and σ(1)=0.7311\sigma(1) = 0.7311.

Mish⁡(1)=1×0.8651=0.8651\operatorname{Mish}(1) = 1 \times 0.8651 = 0.8651
1−t2=1−0.7484=0.25161 - t^{2} = 1 - 0.7484 = 0.2516
Mish⁡′(1)=0.8651+1×0.2516×0.7311=1.0490\operatorname{Mish}'(1) = 0.8651 + 1 \times 0.2516 \times 0.7311 = 1.0490

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 input
Read 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

  1. Mish, SiLU and GELU all have the form xx 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 −3-3 and 2. Then ask how much of your pre-activation distribution falls in that band.

  2. The slope of Mish is negative for inputs below about −1.19-1.19. 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.

  3. Why does the template compute softplus with logaddexp rather than writing out the logarithm of one plus the exponential?
    A way to think about it

    Evaluate exe^{x} at x=1000x = 1000 in floating point. Then think about how ln⁡(e0+ex)\ln(e^{0} + e^{x}) can be rearranged so that only a negative exponent is ever taken.

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