Sign in

Softmax

Softmax function (normalised exponential)

A function that turns a vector of scores into positive numbers that sum to 1, so they can be read as probabilities over classes.

Overview

A classifier produces one score per class. Softmax converts those scores into a probability for each class. It exponentiates every score, which makes them all positive and widens the gaps between them, and then divides by the total so the results sum to 1. Only differences between scores matter: adding the same number to every score changes nothing. The temperature divides the scores first. A high temperature evens the probabilities out and a low one concentrates them on the top score.

A short history

The formula is the Boltzmann distribution of statistical physics from the 1860s, and it appeared in choice theory through R. Duncan Luce's 1959 work. Statisticians used it in multinomial logistic regression. John Bridle gave it the name softmax around 1989 when he proposed it as the output layer of neural network classifiers, so that outputs could be read as probabilities and trained by maximum likelihood.

How it works

  1. Take a vector of scores xx along the chosen axis and divide each by the temperature TT.
  2. Subtract the largest score from all of them. The result is unchanged, and the largest exponent becomes e0=1e^{0} = 1, so nothing overflows.
  3. Exponentiate each shifted score.
  4. Divide each by the sum of all of them. The outputs are positive and sum to 1.
  5. In backward, combine the upstream gradient gg with the outputs as s⊙(g−⟨g,s⟩)/Ts \odot (g - \langle g, s\rangle)/T, which avoids building the full Jacobian.

Watch out for

  • Exponentiating raw scores overflows for values in the hundreds. Always shift by the maximum first, as the template does.
  • The outputs depend on each other. Raising one score lowers every other probability, so the derivative is a full matrix, not one number per element.
  • Taking the log of softmax outputs loses precision when a probability rounds to zero. Losses should use log-softmax on the scores directly.
  • A high probability is not a calibrated confidence. Softmax will assign nearly all the mass to some class even for inputs unlike anything seen in training.
  • Applying it along the wrong axis normalises across the batch instead of across classes, and nothing raises an error.

Use cases

When to use it

The last step of a multi-class classifier, attention weights in transformers, and anywhere a set of scores must become a distribution over exclusive choices.

In industry

Language models
A language model applies softmax over its whole vocabulary at each step to get a probability for every possible next token.
Image classification
Classifiers that sort a photo into one of many categories end in a softmax, and the largest probability gives the predicted label.
Attention in transformers
Attention layers apply softmax to similarity scores so that the weights each position places on the others are positive and sum to 1.

Choosing it: what must hold

  • Classes that are mutually exclusive: exactly one is correct for each example.
  • A loss that works from the raw scores, such as cross-entropy, for numerical stability.
  • A number of classes small enough to score all of them on every training step.

When to choose something else

IfUse instead
Several labels can be true at onceSigmoid on each output with binary cross-entropy
There are millions of classes or itemsSampled softmax
You only need the top class at inference, not probabilitiesTake the largest raw score and skip the softmax

Math foundations

  1. The function

    si=exi/T∑j=1nexj/Ts_i = \frac{e^{x_i / T}}{\sum_{j=1}^{n} e^{x_j / T}}

    Each score is exponentiated and divided by the total. Every sis_i is positive and they sum to 1.

  2. Only differences matter

    softmax⁡(x+c 1)=softmax⁡(x)\operatorname{softmax}(x + c\,\mathbf{1}) = \operatorname{softmax}(x)

    A constant added to every score cancels between numerator and denominator. Choosing c=−max⁡jxjc = -\max_j x_j gives the stable form the template computes.

  3. The Jacobian

    ∂si∂xj=1T si (δij−sj)\frac{\partial s_i}{\partial x_j} = \frac{1}{T}\, s_i\,\big(\delta_{ij} - s_j\big)

    Raising score jj raises its own probability (the case i=ji = j) and lowers every other one. In matrix form it is (diag⁡(s)−ss⊤)/T(\operatorname{diag}(s) - s s^{\top})/T, which jacobian returns.

  4. Backpropagation without the matrix

    ∂L∂x=1T  s⊙(g−⟨g,s⟩),g=∂L∂s\frac{\partial \mathcal{L}}{\partial x} = \frac{1}{T}\; s \odot \big(g - \langle g, s \rangle\big), \qquad g = \frac{\partial \mathcal{L}}{\partial s}

    Multiplying the transposed Jacobian by the upstream gradient gg simplifies to this. It costs nn operations instead of n2n^{2}. The entries always sum to zero.

  5. With cross-entropy the gradient collapses

    ∂∂xi(−ln⁡sy)=si−1[i=y](T=1)\frac{\partial}{\partial x_i}\big(-\ln s_y\big) = s_i - \mathbf{1}[i = y] \qquad (T = 1)

    For the loss −ln⁡sy-\ln s_y with true class yy, the gradient on the scores is predicted minus target. This is why softmax and cross-entropy are implemented as one unit.

Symbols

xix_i
the score (logit) for class i
sis_i
the output probability for class i
nn
the number of classes along the axis
TT
the temperature, temperature in the config, default 1
δij\delta_{ij}
1 when i equals j, otherwise 0
1\mathbf{1}
the vector of ones; with a bracket, the indicator that is 1 when the condition holds
gg
the gradient of the loss with respect to the outputs, grad_output
⟨g,s⟩\langle g, s \rangle
the dot product of g and s
L\mathcal{L}
the loss being minimised
yy
the index of the true class

Worked by hand

Compute the softmax of the scores (2,1,0)(2, 1, 0) with T=1T = 1. Use e2=7.389e^{2} = 7.389 and e1=2.718e^{1} = 2.718.

e2+e1+e0=7.389+2.718+1=11.107e^{2} + e^{1} + e^{0} = 7.389 + 2.718 + 1 = 11.107
s=(7.38911.107,  2.71811.107,  111.107)=(0.6652,  0.2447,  0.0900)s = \left(\tfrac{7.389}{11.107},\; \tfrac{2.718}{11.107},\; \tfrac{1}{11.107}\right) = (0.6652,\; 0.2447,\; 0.0900)
∂s1∂x1=0.6652×(1−0.6652)=0.2227\frac{\partial s_1}{\partial x_1} = 0.6652 \times (1 - 0.6652) = 0.2227
∂s1∂x2=−0.6652×0.2447=−0.1628\frac{\partial s_1}{\partial x_2} = -0.6652 \times 0.2447 = -0.1628

The probabilities are 0.6652, 0.2447 and 0.0900, which sum to 1 up to rounding. Each one-point gap in score is a factor of ee in probability.

Visual example

Loading the example.

Try this

  • Raise one score: the others lose share even though they did not change.
  • Lower the temperature and the largest score takes almost everything.

Code sample

import numpy as np
from impl import Softmax
from config import SoftmaxConfig

act = Softmax(SoftmaxConfig(axis=-1, temperature=1.0))
logits = np.array([[2.0, 1.0, 0.1]])
p = act.forward(logits)                           # [[0.659, 0.2424, 0.0986]], each row sums to 1
dx = act.backward(logits, np.array([[1.0, 0.0, 0.0]]))   # gradient of p[0, 0] with respect to the logits
Read the implementation (47 lines)
"""Softmax: f(x)_i = exp(x_i / T) / sum_j exp(x_j / T) along one axis.

NumPy only. `forward` computes the probabilities, `backward` the gradient with respect to the input given the
gradient with respect to the output, and `jacobian` the full matrix of partial derivatives for one vector.
"""
from __future__ import annotations

import numpy as np

try:
    from .config import SoftmaxConfig
except ImportError:  # run from the template's own folder
    from config import SoftmaxConfig

class Softmax:
    """Maps scores to probabilities that are positive and sum to 1 along `axis`."""

    def __init__(self, config: SoftmaxConfig | None = None) -> None:
        self.config = config or SoftmaxConfig()

    def forward(self, x: np.ndarray) -> np.ndarray:
        """Softmax of x along the configured axis. x: any shape with at least one axis. Returns the same shape."""
        x = np.asarray(x, dtype=float) / self.config.temperature
        shifted = x - x.max(axis=self.config.axis, keepdims=True)  # the largest exponent is exp(0) = 1
        e = np.exp(shifted)
        return e / e.sum(axis=self.config.axis, keepdims=True)

    def backward(self, x: np.ndarray, grad_output: np.ndarray) -> np.ndarray:
        """Gradient of a scalar loss with respect to x, given `grad_output` = d loss / d softmax(x).

        x, grad_output: same shape. Returns that shape. Uses J^T g = s * (g - sum(g * s)) / T, which avoids
        building the Jacobian.
        """
        s = self.forward(x)
        g = np.asarray(grad_output, dtype=float)
        inner = (g * s).sum(axis=self.config.axis, keepdims=True)
        return s * (g - inner) / self.config.temperature

    def jacobian(self, x: np.ndarray) -> np.ndarray:
        """Matrix J[i, j] = d f_i / d x_j for one score vector. x: (n,). Returns (n, n)."""
        x = np.asarray(x, dtype=float)
        if x.ndim != 1:
            raise ValueError(f"jacobian takes one vector of shape (n,), got shape {x.shape}")
        s = Softmax(SoftmaxConfig(axis=-1, temperature=self.config.temperature)).forward(x)
        return (np.diag(s) - np.outer(s, s)) / self.config.temperature

    __call__ = forward
Repository
gitlab.com/designsbyduhart/solomon-templates/activation-softmax
Needs
Python 3.10 and NumPy
Tests
8, run with python3 -m unittest -v

Practice

Build Softmax(SoftmaxConfig(axis=-1, temperature=1.0)) and run forward on the scores 2, 1, 0 and on 1002, 1001, 1000. Confirm both give the same output. Then check that backward with a random grad_output equals jacobian(x).T @ grad_output.

Check on learning

  1. Adding 1000 to every score leaves the output unchanged. What does that say about how many free numbers a softmax over nn classes really has?
    A way to think about it

    One direction in score space has no effect. Count the dimensions that remain, and relate that to probabilities having to sum to 1.

  2. With scores (2,1,0)(2, 1, 0), predict what happens to the three probabilities at T=0.1T = 0.1 and at T=10T = 10 before computing them.
    A way to think about it

    Dividing by TT scales the gaps between scores. Large gaps push toward one-hot, small gaps toward uniform. Then verify with the template.

  3. The entries of the gradient with respect to the scores always sum to zero. Why must that be true?
    A way to think about it

    Use the shift invariance. If moving all scores together cannot change the loss, the directional derivative along the all-ones vector is zero.

  4. A model outputs 0.99 for one class on an image of random noise. Is the model 99 percent sure? What does softmax guarantee and what does it not?
    A way to think about it

    Softmax guarantees the outputs sum to 1, nothing more. It has no way to say none of the above, and a large score gap can arise far from the training data.

  5. Why does subtracting the maximum before exponentiating fix overflow but not change the answer?
    A way to think about it

    After the shift the largest exponent is exactly 0 and the rest are negative. Underflow to zero in a small term is harmless, overflow to infinity is not.