Equations · Bridle (1990) named it; used by every classifier and attention layer since

The softmax formula, explained

Softmax turns KK arbitrary scores (logits) into a probability distribution over KK options.

softmax⁡(z)i=ezi∑j=1Kezj\operatorname{softmax}(\mathbf{z})_i = \frac{e^{z_i}}{\sum_{j=1}^{K} e^{z_j}}

Open in the decoder →

Term by term

  1. z\mathbf{z}

    The vector of scores (logits), one per class. Any real numbers.

  2. softmax⁡(z)i\operatorname{softmax}(\mathbf{z})_i

    The ii-th entry of the output: the probability given to class ii.

  3. ezie^{z_i}

    Exponentiating makes every score positive and stretches the gaps between them.

  4. ∑j=1Kezj\sum_{j=1}^{K} e^{z_j}

    The total over all KK classes. Dividing by it makes the outputs sum to 1.

A small worked example

For z=(1,2,3)\mathbf{z} = (1, 2, 3): ez≈(2.72,7.39,20.09)e^{\mathbf{z}} \approx (2.72, 7.39, 20.09), total 30.1930.19, so softmax⁡(z)≈(0.09,0.24,0.67)\operatorname{softmax}(\mathbf{z}) \approx (0.09, 0.24, 0.67). Adding 100 to every score gives the same answer, which is why code subtracts the largest score first.

In code

import numpy as np

def softmax(z):
    e = np.exp(z - z.max())   # subtracting the max avoids overflow
    return e / e.sum()

Every symbol in it

x∈Rd\mathbf{x} \in \mathbb{R}^{d}Bold lowercase (vector)softmax⁡(z)i=ezi∑jezj\operatorname{softmax}(\mathbf{z})_i = \frac{e^{z_i}}{\sum_j e^{z_j}}Softmaxxi,  Wq,  pθ,  dmodelx_i,\; W_q,\; p_\theta,\; d_{\text{model}}Subscript (index or label)ex=exp⁡(x)e^{x} = \exp(x)Exponential∑i=1Nxi\sum_{i=1}^{N} x_iSummation

Other equations