Neural network formulas: a cheat sheet · Activation functions

Softmax: from logits to probabilities

The function that turns a network’s raw scores into a probability distribution over K classes. We take it apart bone by bone: why the exponential, why only logit differences matter, what temperature does, how the Jacobian diag(s) − ssᵀ is built, why softmax is the gradient of a smooth maximum, and how to avoid NaN in code.

Javharbek Abdulatipov · 35 min read
$$\operatorname{softmax}(z)_i=s_i=\frac{e^{z_i}}{\sum_{j=1}^{K}e^{z_j}}$$

Why we need it

A classifier with $K$ classes ends with $K$ numbers — logits: for example, $(2,\,1,\,0)$ for “cat”, “dog”, “bird”. They are just scores: they can be negative, they do not add up to 1, and they do not tell how sure the model is. Softmax turns such a vector into a probability distribution: all numbers are positive, they sum to 1, and the order is preserved — a higher score means a higher probability.

Where it appears:

  • the output of a multi-class classifier — from logistic regression to ResNet and ViT: $\hat y=\operatorname{softmax}(Wx+b)$;
  • language models — at every step an LLM outputs logits for every token in its vocabulary (tens or hundreds of thousands), softmax turns them into the distribution of the next token, and temperature controls how bold the generation is;
  • attention in transformers — the weights $\operatorname{softmax}(QK^\top/\sqrt d)$ decide which tokens to look at;
  • mixture of experts (MoE) — the router distributes a token among experts through a softmax;
  • reinforcement learning — a Boltzmann policy picks action $a$ with probability proportional to $e^{Q(a)/T}$;
  • statistical physics — it is the Boltzmann–Gibbs distribution $p_i\propto e^{-E_i/(kT)}$; hence the word “temperature”.
The essentials in a minute

$s_i=e^{z_i}/\sum_j e^{z_j}$: the exponential makes every number positive and turns differences into ratios, and dividing by the sum normalizes. Softmax does not change when one constant is added to all logits (which is why code subtracts the maximum), its derivative is the matrix $\operatorname{diag}(s)-ss^\top$, and for two classes it coincides with the sigmoid of the logit difference.

Intuition: a vote with amplification

Think of the classes as candidates and of the logits as their scores. To get shares of the “vote”, the scores must be made positive and normalized. Simply dividing by the sum does not work: scores can be negative and the sum can be zero. The exponential solves both problems: $e^{z}$ is always positive, and a difference in scores becomes a ratio: every unit of advantage makes a candidate’s share $e\approx2.718$ times its rival’s.

Drag the tops of the logit bars on the left and watch the probabilities on the right. Then press “+1 to every logit”: the bars on the left rise, while nothing changes on the right.

Figure 1. Logits and probabilities. The logits $(2,\,1,\,0)$ give $(0.665,\,0.245,\,0.090)$, and the sum of exponentials is $11.11$. The ±1 buttons shift every logit — the probabilities stay put. The temperature slider: at $T=0.1$ the first class gets more than $0.9999$, at $T=10$ the distribution is almost uniform, $(0.367,\,0.332,\,0.301)$. The dashed line is the level $1/K$.
What to notice

The logits $(2,\,1,\,0)$ differ by one, while the probabilities differ by a factor of $e$: $0.665/0.245\approx0.245/0.090\approx2.718$. Softmax only looks at logit differences. The temperature $T$ divides the logits: for $T<1$ the differences grow and the distribution sharpens, for $T>1$ it flattens.

The formula, bone by bone

$$s_i=\operatorname{softmax}(z)_i=\frac{e^{z_i}}{\sum_{j=1}^{K}e^{z_j}},\qquad i=1,\dots,K$$
$z=(z_1,\dots,z_K)$
the vector of logits — raw outputs of the last layer, any real numbers;
$e^{z_i}$
the exponential: makes the number positive and turns logit differences into ratios;
$\sum_{j}e^{z_j}$
the normalizing sum (in physics, the partition function $Z$);
$s_i$
the probability of class $i$: $s_i\in(0,\,1)$ and $\sum_i s_i=1$.

Let us walk through the cheat sheet’s running example — the logits $z=(2,\,1,\,0)$:

$$\begin{gathered}e^{2}\approx7.389,\quad e^{1}\approx2.718,\quad e^{0}=1,\quad\textstyle\sum\approx11.107\\ \Longrightarrow\;s\approx\Bigl(\frac{7.389}{11.107},\,\frac{2.718}{11.107},\,\frac{1}{11.107}\Bigr)=(0.665,\,0.245,\,0.090)\end{gathered}$$

Temperature

Logits are often divided by a number $T>0$, the temperature, before the softmax:

$$s_i(T)=\frac{e^{z_i/T}}{\sum_j e^{z_j/T}}$$

The table shows what temperature does to the same vector $(2,\,1,\,0)$:

$i$$z_i$$e^{z_i}$$s_i,\ T=1$$s_i,\ T=0.5$$s_i,\ T=2$
127.3890.6650.8670.506
212.7180.2450.1170.307
301.0000.0900.0160.186
Σ11.107111

Two limits explain the name. As $T\to0$ only the largest logit wins: softmax tends to the one-hot vector of the $\operatorname{argmax}$ (if the maximum is unique). As $T\to\infty$ the differences vanish and the distribution becomes uniform, $s_i\to1/K$. Softmax is a “soft” argmax: something between a hard choice and complete indifference.

About the name

Strictly speaking, softmax smoothly approximates not the max function but the one-hot argmax vector. The smooth maximum is log-sum-exp, and softmax is its gradient (see the section on LSE).

Properties

  • A distribution: $s_i>0$ and $\sum_i s_i=1$ for any logits. Exactly 0 or 1 never happens — only in the limit (and on a computer, through rounding).
  • Order-preserving: $z_i>z_j\iff s_i>s_j$, so $\operatorname{argmax}s=\operatorname{argmax}z$. To merely predict the class you can skip the softmax.
  • Ratios: $s_i/s_j=e^{z_i-z_j}$ — the logit difference is the logarithm of the probability ratio. Conversely, $z_i=\ln s_i+C$: logits are recovered from probabilities up to a common constant.
  • Shift invariance: $\operatorname{softmax}(z+c\mathbf 1)=\operatorname{softmax}(z)$ for any number $c$. Of $K$ logits only $K-1$ differences matter.
  • No scale invariance: $\operatorname{softmax}(az)$ is sharper for $a>1$ and flatter for $0<a<1$. This is the same temperature, $a=1/T$.
  • Competition: raising one logit increases its probability and decreases all the others — mass is redistributed, not created.
Why a shift changes nothing
$$\frac{e^{z_i+c}}{\sum_j e^{z_j+c}}=\frac{e^{c}\,e^{z_i}}{e^{c}\sum_j e^{z_j}}=\frac{e^{z_i}}{\sum_j e^{z_j}}$$

The factor $e^c$ cancels. This is exactly what lets code subtract $\max_j z_j$ from every logit: the result is the same, and the exponential no longer overflows.

Two classes are a sigmoid

$$\operatorname{softmax}(z_1,z_2)_1=\frac{e^{z_1}}{e^{z_1}+e^{z_2}}=\frac{1}{1+e^{-(z_1-z_2)}}=\sigma(z_1-z_2)$$

For two classes softmax is the sigmoid of the logit difference, which is why a binary classifier needs only one output. A similar formula holds for $K$ classes if we look at one class against all the others:

$$s_i=\sigma\Bigl(z_i-\ln\sum_{j\ne i}e^{z_j}\Bigr)$$

Every probability is a sigmoid of how far its logit is ahead of the “smooth maximum” of the rest. To check it, divide the numerator and the denominator of $s_i$ by $e^{z_i}$.

Figure 2. $s_1$ as a function of $z_1$ with $z_2=1$, $z_3=0$ fixed. The blue curve is a sigmoid shifted to the point $m=\ln(e^{1}+e^{0})\approx1.313$: at $z_1=2$ we get $\sigma(0.687)\approx0.665$. The orange and teal curves are $s_2$ and $s_3$: they decrease, handing their mass to the first class. Untick “There is a third class” and an ordinary sigmoid $\sigma(z_1-z_2)$ remains.

Geometry: the probability simplex

All distributions over $K$ classes form the probability simplex:

$$\Delta^{K-1}=\Bigl\{s\in\mathbb R^{K}:\ s_i\ge0,\ \textstyle\sum_i s_i=1\Bigr\}$$

For $K=3$ it is an equilateral triangle. The vertices are confident answers $(1,\,0,\,0)$, $(0,\,1,\,0)$, $(0,\,0,\,1)$, the centre is the uniform distribution $(\tfrac13,\,\tfrac13,\,\tfrac13)$, and a point inside is a “mixture” of the vertices with weights $s_i$ (barycentric coordinates).

Softmax maps the whole logit space $\mathbb R^K$ onto the interior of the simplex: the edges and vertices are out of reach. All points of the line $z+c\mathbf 1$ land on one point, so in essence softmax is a one-to-one correspondence between the $(K-1)$-dimensional space of logit differences and the interior of the simplex. The inverse map is the logarithm: $z=\ln s$ up to a shift.

Figure 3. A distribution over three classes is a point of the triangle; the shading shows which class wins and how confidently. Drag the black point: on the right are the same probabilities as bars, below are the logits that produce this point. The black dashed line is the path as the temperature changes: from the winning vertex ($T\to0$) to the centre ($T\to\infty$). The blue line is the path when only $z_1$ changes: from the opposite edge to vertex 1. At $z=(2,\,1,\,0)$ the centred logits are $(1,\,0,\,-1)$ and the entropy is $0.832$.
Entropy is the distance from the vertices

The entropy $H(s)=-\sum_i s_i\ln s_i$ measures uncertainty: it tends to 0 near the vertices and is largest at the centre, where it equals $\ln K$. For $(0.665,\,0.245,\,0.090)$ it is $0.832$, with a maximum of $\ln3\approx1.099$.

The derivative: the Jacobian matrix

Softmax has $K$ inputs and $K$ outputs, so its derivative is not a number but a $K\times K$ matrix: the entry $J_{ij}=\partial s_i/\partial z_j$ shows how the $i$-th probability responds to the $j$-th logit.

Derivation with the quotient rule

Let $S=\sum_k e^{z_k}$; then $\partial S/\partial z_j=e^{z_j}$. For $i=j$:

$$\frac{\partial s_i}{\partial z_i}=\frac{e^{z_i}S-e^{z_i}e^{z_i}}{S^{2}}=s_i-s_i^{2}=s_i(1-s_i)$$

For $i\ne j$ the numerator $e^{z_i}$ does not depend on $z_j$:

$$\frac{\partial s_i}{\partial z_j}=\frac{0\cdot S-e^{z_i}e^{z_j}}{S^{2}}=-s_is_j$$
Derivation through the logarithm (shorter)

$\ln s_i=z_i-\ln S$. The derivative of the log of a sum of exponentials is softmax again: $\partial\ln S/\partial z_j=e^{z_j}/S=s_j$. Hence

$$\frac{\partial\ln s_i}{\partial z_j}=\delta_{ij}-s_j\quad\Longrightarrow\quad\frac{\partial s_i}{\partial z_j}=s_i(\delta_{ij}-s_j)$$

Here $\delta_{ij}$ is the Kronecker delta: 1 if $i=j$ and 0 otherwise.

$$J=\frac{\partial s}{\partial z}=\operatorname{diag}(s)-s\,s^{\top},\qquad J_{ij}=\begin{cases}s_i(1-s_i),&i=j\\-s_is_j,&i\ne j\end{cases}$$

Properties of this matrix:

  • the diagonal $s_i(1-s_i)$ is exactly the derivative of the sigmoid: at most $\tfrac14$, largest at $s_i=\tfrac12$;
  • off the diagonal every entry is negative: raising one logit takes probability away from the others;
  • it is symmetric, and every row (and column) sums to 0: $J\mathbf 1=s-s\,(s^\top\mathbf 1)=0$. This is the derivative of $\sum_i s_i=1$, and the vector $\mathbf 1$ is the shift direction that changes nothing. Hence $J$ is singular;
  • it is positive semi-definite: $v^\top Jv=\sum_i s_iv_i^2-\bigl(\sum_i s_iv_i\bigr)^2$ is the variance of $v$ under the distribution $s$, and a variance is never negative;
  • it fades with confidence: when $s$ is close to a vertex of the simplex, every entry of $J$ is close to zero — saturation, as with the sigmoid.
Figure 4. On the left, the Jacobian at $z=(2,\,1,\,0)$: the diagonal $(0.223,\,0.185,\,0.082)$ is positive (red), the off-diagonal entries $-0.163$, $-0.060$, $-0.022$ are negative (blue); every column sums to 0, and the trace is $1-\sum s_i^2\approx0.4895$. On the right, the entries of the chosen column as functions of $z_j$: the diagonal one is the bell $s_j(1-s_j)$ peaking at $0.25$ where $s_j=0.5$; the others are negative “dips”.

A backward pass without the matrix

Backprop needs not $J$ itself but the product $J^\top g$, where $g=\partial L/\partial s$ comes from above. Thanks to the structure $\operatorname{diag}(s)-ss^\top$ it costs $O(K)$ operations instead of $O(K^2)$:

$$\frac{\partial L}{\partial z}=J^{\top}g=s\odot\bigl(g-\langle g,s\rangle\,\mathbf 1\bigr)$$

For an LLM vocabulary of $K\approx10^5$ tokens this is the difference between $10^5$ and $10^{10}$ numbers per position. Paired with cross-entropy it gets simpler still: $\partial L/\partial z=s-y$ (derived on the cross-entropy page).

The 3D picture: softmax over the logit plane

Fix $z_3=0$ — no loss of generality, since a shift can make any logit zero — and draw $s_1$ as a function of the two variables $z_1$ and $z_2$. The result is a “ramp”: the surface is close to 1 where $z_1$ exceeds both $z_2$ and zero, and close to 0 where the first class loses. Across the boundary it rises along a sigmoid — the one-against-all formula in action.

Figure 5. On the left, $s_k(z_1,z_2,0)$ in 3D (the surface can be rotated); the black point is $z=(2,\,1,\,0)$ with $s_1\approx0.665$. On the right, the logit plane: the shading shows the winning class and its confidence, the lines are the levels $0.1$, $0.5$, $0.9$ of the chosen function ($0.05$, $0.15$, $0.24$ for the derivative). The point can be dragged. Switch to $\partial s_1/\partial z_1$: it is a ridge of height $0.25$ along the line $s_1=0.5$.

The top view splits the logit plane into three regions. The boundaries are the sets of equal logits: the ray $z_1=z_2\ge0$ separates classes 1 and 2, the ray $z_1=0$, $z_2\le0$ separates classes 1 and 3, and the ray $z_2=0$, $z_1\le0$ separates classes 2 and 3. All three rays start at the origin, where $s=(\tfrac13,\,\tfrac13,\,\tfrac13)$.

Where the gradient flows

The surface $\partial s_1/\partial z_1=s_1(1-s_1)$ is almost flat and almost zero deep inside the class’s “own” and “foreign” regions. Gradient flows through softmax only where the model is in doubt — near the boundaries.

Log-sum-exp: a smooth maximum

Softmax has an “antiderivative” — the log-sum-exp function:

$$\operatorname{LSE}(z)=\ln\sum_{j=1}^{K}e^{z_j},\qquad\frac{\partial\operatorname{LSE}}{\partial z_i}=\frac{e^{z_i}}{\sum_j e^{z_j}}=s_i,\qquad\nabla\operatorname{LSE}(z)=\operatorname{softmax}(z)$$

LSE is a smooth maximum: the largest exponential dominates the sum, and the logarithm returns almost its exponent. More precisely,

$$\max_j z_j\;\le\;\operatorname{LSE}(z)\;\le\;\max_j z_j+\ln K$$

The left inequality holds because a sum is at least its largest term, the right one because each of the $K$ terms is at most the largest. For $(2,\,1,\,0)$: $\operatorname{LSE}=\ln11.107\approx2.408$ — between $2$ and $2+\ln3\approx3.099$. With a temperature, $\operatorname{LSE}_T(z)=T\ln\sum_j e^{z_j/T}$, the gap shrinks to $T\ln K$: as $T\to0$ LSE becomes the ordinary maximum, and its gradient $\operatorname{softmax}(z/T)$ becomes the one-hot argmax vector.

Figure 6. Top: $\operatorname{LSE}_T(x,0)=T\ln(e^{x/T}+1)$ and $\max(x,0)$; the gap is at most $T\ln2$ and is largest at $x=0$. At $T=1$, $x=1$: $\operatorname{LSE}\approx1.3133$, the gap is $0.3133$. Bottom: the derivative in $x$ — it is $\sigma(x/T)$, the first component of $\operatorname{softmax}(x/T,\,0)$, a smooth step. Decrease $T$ and LSE hugs the broken line while softmax hugs the step.
Convexity of LSE and of cross-entropy

The Hessian of LSE is the derivative of softmax, i.e. the same Jacobian: $\nabla^2\operatorname{LSE}=\operatorname{diag}(s)-ss^\top$. It is positive semi-definite, so LSE is a convex function. Hence cross-entropy is convex in the logits: $-\ln s_y=\operatorname{LSE}(z)-z_y$ is a convex function minus a linear one.

Three formulas worth connecting

$\operatorname{softmax}=\nabla\operatorname{LSE}$; $\ln s_i=z_i-\operatorname{LSE}(z)$ (log-softmax); $\mathrm{CE}=\operatorname{LSE}(z)-z_y$. For the cheat sheet’s example: $2.408-2=0.408$. And for $K=2$, $z=(x,\,0)$, LSE becomes softplus $\ln(1+e^{x})$ — a smooth version of ReLU.

Softmax in training

The simplest model with a softmax is multinomial logistic (softmax) regression: $K$ linear functions give the logits, softmax gives the probabilities, and the loss is cross-entropy:

$$s=\operatorname{softmax}(Wx+b),\qquad L=-\ln s_y,\qquad\frac{\partial L}{\partial W}=(s-y)\,x^{\top},\qquad\frac{\partial L}{\partial b}=s-y$$

Here $y$ is the one-hot vector of the correct class. The whole Jacobian, paired with the logarithm, has collapsed into the difference “prediction − truth”.

Figure 7. Three classes of 30 points each. The model starts at $W=0$, $b=0$: every probability is $\tfrac13$, $\mathrm{CE}=\ln3\approx1.099$, accuracy $33.3\%$. Press “Play”: full-batch gradient descent with step $0.15$. After the very first step the accuracy is $94.4\%$; after 200 steps $\mathrm{CE}\approx0.181$ and the accuracy is $95.6\%$. The brightness of the shading is the model’s confidence; hover to see the probabilities at any point.
The boundaries are straight

The boundary between classes $i$ and $j$ is the set where $z_i=z_j$, that is $(w_i-w_j)^\top x+b_i-b_j=0$: a line (a hyperplane in general). Softmax does not make the model non-linear — it only turns scores into probabilities. Curved boundaries appear when a neural network computes the logits.

Softmax inside the transformer: attention

$$\operatorname{Attention}(Q,K,V)=\operatorname{softmax}\Bigl(\frac{QK^{\top}}{\sqrt{d}}\Bigr)V$$

Each row of $\operatorname{softmax}(\cdot)$ is how one token spreads its attention over the tokens of the sequence (itself included), with weights summing to 1. Dividing by $\sqrt d$ is a temperature: the dot product of $d$-dimensional vectors with independent zero-mean, unit-variance components has variance $d$. Without the scaling the attention logits are large, softmax saturates to nearly one-hot, and the Jacobian — and with it the gradients — nearly vanishes.

Temperature in text generation

A language model draws the next token from $\operatorname{softmax}(z/T)$. As $T\to0$ (greedy decoding) the most likely token is taken; with $T<1$ the text is more predictable, with $T>1$ more diverse and riskier. A temperature $T>1$ also appears in knowledge distillation (Hinton et al., 2015): the teacher’s “soft” probabilities carry more information than one-hot labels.

Where the name comes from

The formula came from statistical physics: the Boltzmann–Gibbs distribution $p_i\propto e^{-E_i/(kT)}$ gives the probability of a state with energy $E_i$ at temperature $T$; a logit plays the role of minus the energy. The word “softmax” was coined by John Bridle in 1990, when describing a probabilistic interpretation of network outputs. In econometrics the same model is called the multinomial logit.

In code: stability, log-softmax and PyTorch

The naive formula breaks on large logits: $e^{1000}\approx2\cdot10^{434}$ fits in neither float32 nor float64 and becomes infinity, which then gives $\infty/\infty=\text{NaN}$. In float32 (and in bfloat16, which has the same exponent range) the limit is closer: $e^{x}$ overflows already for $x>88.72$ (the largest float32 is $\approx3.4\cdot10^{38}$). On very negative logits the trouble is the opposite: the exponentials underflow to zero, giving $0/0$.

Figure 8. The logits $(2+c,\,1+c,\,c)$ for $c$ from $-800$ to $800$; the correct answer is always $(0.665,\,0.245,\,0.090)$. In float32 the naive formula is right only for $-99\le c\le86$: at $c=87$ the number $e^{89}$ does not fit in float32 and the result is NaN; at $c\le-106$ every exponential is zero, $0/0$; and in between, subnormal numbers lose precision — at $c=-105$ the output is a confident but false $(1,\,0,\,0)$. float64 has more room ($-741\le c\le707$), but a limit as well. With the maximum subtracted the answer is right everywhere.

The cure is shift invariance: subtract $m=\max_j z_j$. The largest exponent becomes 0, $e^0=1$, and the denominator lies between 1 and $K$ — no overflow, no division by zero:

$$s_i=\frac{e^{z_i-m}}{\sum_j e^{z_j-m}},\qquad\ln s_i=(z_i-m)-\ln\sum_j e^{z_j-m}$$
pythonimport numpy as np
np.set_printoptions(precision=3)

def softmax(z, axis=-1, T=1.0):
    """Stable softmax: subtract the maximum, the result does not change."""
    z = np.asarray(z, dtype=float) / T
    z = z - z.max(axis=axis, keepdims=True)
    e = np.exp(z)
    return e / e.sum(axis=axis, keepdims=True)

def log_softmax(z, axis=-1):
    # log s_i = z_i − logsumexp(z): no log(0) even for tiny probabilities
    z = np.asarray(z, dtype=float)
    m = z.max(axis=axis, keepdims=True)
    return z - m - np.log(np.exp(z - m).sum(axis=axis, keepdims=True))

def softmax_backward(s, g):
    # J^T g = s * (g − <g, s>): O(K) instead of a K×K matrix
    return s * (g - (g * s).sum(axis=-1, keepdims=True))

z = np.array([2.0, 1.0, 0.0])
print(softmax(z))            # [0.665 0.245 0.09 ]
print(softmax(z + 1000))     # [0.665 0.245 0.09 ] — the shift does not matter
print(softmax(z, T=0.5))     # [0.867 0.117 0.016] — sharper
print(log_softmax([0.0, -800.0]))  # [   0. -800.], while np.log(softmax(...)) gives -inf
pythonimport torch
import torch.nn.functional as F

z = torch.tensor([2.0, 1.0, 0.0], requires_grad=True)
s = F.softmax(z, dim=-1)          # tensor([0.6652, 0.2447, 0.0900])
s[0].backward()                   # the first row of the Jacobian
print(z.grad)                     # tensor([ 0.2227, -0.1628, -0.0599])

# For training you do not need a separate softmax:
logits = torch.randn(4, 3)        # a batch: 4 examples, 3 classes
target = torch.tensor([0, 2, 1, 0])
loss = F.cross_entropy(logits, target)   # log_softmax + NLL inside
log_p = F.log_softmax(logits, dim=-1)    # if you need log-probabilities
The rule

If a logarithm follows, do not compute $\ln(\operatorname{softmax}(z))$ in two steps: a small probability rounds to 0 and you get $-\infty$. Use log_softmax or a loss on logits directly: F.cross_entropy / nn.CrossEntropyLoss in PyTorch, from_logits=True in Keras.

Common mistakes

  1. A softmax before nn.CrossEntropyLoss. This loss expects logits and applies log-softmax itself. A double softmax squeezes the probabilities: for three classes the second softmax never exceeds $e/(e+2)\approx0.576$, the loss cannot drop below $0.551$, and the gradients are distorted.
  2. The wrong axis. For a batch of shape $(N,K)$ normalize over classes (dim=-1), not over examples (dim=0). No exception is raised — the model simply learns nonsense.
  3. A naive exponential without subtracting the maximum — NaN on large logits, especially in mixed precision: in float16 $e^{x}$ overflows already for $x>11.09$.
  4. Softmax for multi-label. If an object can carry several labels at once (a cat and a dog in a photo), the classes do not compete — use a sigmoid on every output and BCE.
  5. A softmax probability as a guarantee. $s_{\max}=0.99$ does not mean “right 99% of the time”: deep networks are often overconfident. Calibration is a separate task; the simplest method is temperature scaling, fitting a single $T$ on validation data.
  6. Comparing logits of different examples. Logits are defined up to a shift, so “a logit of 5 for one example is more than 3 for another” means nothing. Compare probabilities, or logit differences within one example.
  • Sigmoid: $\operatorname{softmax}(z_1,z_2)_1=\sigma(z_1-z_2)$, and the Jacobian’s diagonal $s_i(1-s_i)$ is the derivative of the sigmoid.
  • Cross-entropy: softmax’s natural partner; together they give the gradient $s-y$, and $\mathrm{CE}=\operatorname{LSE}(z)-z_y$.
  • BCE: the two-class special case of cross-entropy, where softmax reduces to the sigmoid.
  • Focal Loss: multiplies $-\ln p_t$ by $(1-p_t)^\gamma$, where $p_t$ is the softmax probability of the correct class.
  • ReLU: softplus $\ln(1+e^{x})=\operatorname{LSE}(x,0)$ is a smooth version of $\max(x,0)$.

Summary

1) $s_i=e^{z_i}/\sum_je^{z_j}$ turns any logits into a distribution over $K$ classes and preserves their order. 2) Only logit differences matter: $s_i/s_j=e^{z_i-z_j}$, and a shift changes nothing — hence the stable formula that subtracts the maximum. 3) Temperature controls sharpness: $T\to0$ gives argmax, $T\to\infty$ the uniform distribution. 4) The Jacobian $\operatorname{diag}(s)-ss^\top$ is symmetric, singular and fades with confidence; the backward pass costs $O(K)$. 5) Softmax is the gradient of the smooth maximum LSE, and paired with cross-entropy it gives the gradient $s-y$.

Check yourself

1. The logits $(2,\,1,\,0)$ give $s\approx(0.665,\,0.245,\,0.090)$. What do $(102,\,101,\,100)$ give?
2. What happens to $\operatorname{softmax}(z/T)$ as $T\to0$?
3. What is $\operatorname{softmax}(z_1,z_2)_1$?
4. What is the sum of the entries of any column of the softmax Jacobian?
5. Why does a stable softmax subtract $\max_j z_j$?