Skip to the content

fatehi.devx2Learning

Deep learning

Softmax

Raise e to every score and divide by the total: positive numbers that add up to 1 and keep the order of the scores; only the gaps between scores count.

Wherever a model chooses, whether the next token, an answer letter or the positions attention reads, a softmax turns its scores into probabilities, and its properties decide how the model can be trained and read.

From scores to probabilities

Many models end by choosing among options: which word comes next, which object is in a picture, which answer is right. Usually the model does not produce the choice directly. It gives each option a score, a single number, and then turns the scores into probabilities. The function that does this second step, almost everywhere in machine learning, is the softmax. This page builds it up from a small example, then explains its behaviour and how it is used to train a model.

Take three options with the scores 2, 1 and −1. Scores like these, called logits, can be any real numbers, negative ones included, and they add up to nothing in particular. To read them as probabilities we need three things: every value must be positive, the values must add up to 1, and an option with a higher score must keep a higher probability. The softmax gets all three in two moves. First it raises the number e ≈ 2.718 to the power of each score (the exponential): e2 ≈ 7.39, e1 ≈ 2.72, e−1 ≈ 0.37. Every result is positive, and the order is kept. Then it divides each result by their sum, 10.48, which makes them add up to 1: the probabilities are about 0.705, 0.259 and 0.035.

Why the exponential, and not some other way of making numbers positive? Because it turns differences into ratios. Since ea+b = ea · eb, an option whose score is one point higher than another’s is about 2.7 times as likely, two points higher about 7.4 times, five points higher about 148 times, whatever the scores themselves are. In the example, the first option’s lead of 1 over the second makes it 2.7 times as likely, and its lead of 3 over the third makes it about 20 times as likely. Two consequences follow. Adding the same number to every score changes nothing, so a score means nothing on its own; only its distance from the others counts. And a lead of a few points is enough for one option to take nearly all the probability.

How sharply the probability gathers on the top option can be controlled by dividing every score by a number called the temperature before the softmax. A temperature below 1 stretches the gaps, so the top option takes more; a temperature above 1 shrinks them, so the probabilities move towards being equal. Language models use this when they generate text: a low temperature makes them pick the likeliest token almost every time, a high one makes their choices more varied. The figure shows the effect on five options.

Five scores, one for each option A to E, and their softmax at a temperature T moving between 0.25 and 4. At low T nearly all the probability goes to A; at high T the five come close to 1/5 each. The order never changes.

When one option takes almost everything, the softmax is said to saturate. Its output then hardly moves when a score changes a little. That matters because models are trained by small changes: gradient descent nudges the scores in the direction that improves the probabilities, and if the probabilities hardly respond, learning through the softmax slows down or stops. Networks that compute many scores at once guard against this by keeping their scores from growing too large.

The softmax also tells us how to train a model to choose well. When the right option is known, we want its probability to be large, which is the same as wanting minus the logarithm of its probability to be small. That quantity is the cross-entropy. It is a loss function: a single number that measures how wrong the model is, and that training makes as small as it can. It works remarkably well with the softmax: the logarithm undoes the exponential, so even a model that is badly wrong gets a strong, steady signal to improve, as the section on cross-entropy shows.

Because choosing among options is so common, the softmax appears in many places: at the output of a classifier, where it turns the scores of the classes into probabilities; at the output of a language model, where it turns a score for every token of the vocabulary into the probabilities of the next token (tokens and embeddings); inside attention, where it turns scores into weights that say how much each position should read from every other; and in many other models that must spread one unit of weight over several options.

The definition

Now the same thing in symbols. The softmax takes a list of K scores, one per option, and returns a list of K probabilities, one per option. Write the scores z1, …, zK; the probability it gives option i is

pi=softmax(z)i=ezi∑j=1Kezj

z is the list of the K scores, zi the score of option i, pi its probability, and j runs over all options. Raise e to the score zi of option i, and divide by the same quantity summed over all K options: every pi is positive and together they add up to 1. To review the powers of e: exponentials and logarithms; for what makes a list of numbers a distribution: probability.

Every quantity in the formula has a job you have already seen. The top, ezi, is the positive number made from option i’s score. The bottom is the same quantity summed over all options; dividing by it is what makes the probabilities add up to 1. The bottom is shared by every option, so the probabilities compare to each other exactly as their exponentials do.

The name is Bridle’s (1990). It is a soft version of picking the maximum: the hard rule “give 1 to the top option and 0 to all the others” jumps abruptly when two scores swap places, while the softmax shares the probability smoothly and changes smoothly with the scores, which is what training by small steps needs.

Only the gaps count

Add the same number to every score and nothing changes. With the scores 2, 1 and −1 the probabilities are 0.705, 0.259 and 0.035; with 12, 11 and 9 they are exactly the same. The reason is in the formula: adding a constant c to every score multiplies the top and the bottom of the fraction by the same ec, which cancels. What is left depends only on the gaps between the scores:

softmax(z+c)=softmax(z),pipj=ezi−zj

pi and pj are the probabilities of options i and j, z the scores and c any number. Shifting all the scores z by the same amount c leaves the probabilities as they are. Option i is e to the power of its lead over option j times as likely as j, the ratios worked out in the examples above. Logits therefore have no meaningful zero, and a program may subtract the largest score from all of them before computing, which is what keeps the computation safe (below).

The same number is added to all three scores, up to 2.5 and down to −2, and the probabilities do not move: only the gaps between the scores, 1 and 2 here, reach the softmax.

Two practical lessons follow. A single score means nothing on its own, so asking whether a logit is “high” only makes sense in comparison with the other options’ logits. And a program is free to subtract any number from all the scores before computing; subtracting the largest one is what keeps the computation safe, as the section on log-probabilities shows.

The case of two options is worth seeing on its own, because so many models make exactly one yes-or-no decision: is this e-mail spam, does this patient have the disease. With only two options there is only one gap, z1 − z2, and the softmax’s first probability becomes

p1=11+e−(z1−z2)

p1 is the probability of option 1 when there are two options, with scores z1 and z2. Divide the top and the bottom of the softmax’s fraction for option 1 by ez1: what is left depends only on the gap z1 − z2. A gap of 0 gives 1/2, a large positive gap gives nearly 1, a large negative gap nearly 0.

The logistic function: the probability of option 1 against the gap between the two scores. It passes through 1/2 at a gap of 0, rises fastest there, and flattens towards 0 and 1 on either side.

This S-shaped function is the logistic function, also called the sigmoid, and it is the function with which binary classifiers end, from logistic regression to large neural networks that answer yes or no. They are written with a single score instead of two, but that score plays the role of the gap: a sigmoid on one score is a softmax over two options in disguise, and everything on this page applies to it.

Temperature and saturation

Dividing every score by a positive number T, the temperature, before the softmax scales every gap by 1/T, and the gaps are all that matter:

pi(T)=softmax(z/T)i

To apply a temperature T, divide every score z by T first, then take the softmax as usual; pi(T) is the probability of option i at that temperature.

Dividing by T divides every gap between scores by T too, and the gaps are all the softmax looks at. Take the page’s scores 2, 1 and −1, which give the probabilities 0.71, 0.26 and 0.04:

  • at T = 0.5 the scores become 4, 2 and −2: the gaps double, and the probabilities sharpen to 0.88, 0.12 and 0.00;
  • at T = 2 they become 1, 0.5 and −0.5: the gaps halve, and the probabilities even out to 0.55, 0.33 and 0.12;
  • at T = 10 they become 0.2, 0.1 and −0.1: the gaps almost vanish, and the probabilities, 0.38, 0.34 and 0.28, are nearly equal.

Pushed to the extremes: as T approaches 0 the top option takes all the probability, as if one simply picked the highest score; as T grows without limit every option approaches the same share, 1/K for K options. In between the order of the options never changes: the option with the highest score always has the highest probability.

Language models use the temperature when they generate text. At T = 1 they sample the next token from the softmax as it is; at a low temperature, say 0.2, the gaps are five times larger and the likeliest token is chosen almost every time, which makes the text predictable; at a temperature above 1 unlikely tokens get a real chance, which makes it varied and, past a point, incoherent. The figure at the top of the page shows the probabilities moving with T.

The other side of large gaps is saturation. To see it, ask how much a probability changes when a score changes a little: that is the softmax’s slope, its derivative.

∂pi∂zj=pi([i=j]−pj)

The change of probability pi per unit change of score zj is pi times ([i = j] − pj), where [i = j] is 1 when i and j are the same option and 0 otherwise. Every slope is a product of probabilities, and at most 1/4 in size. When one option holds nearly all the probability, each product has a factor close to 0 (either a tiny p or 1 − p for the top option), so every slope is close to 0. To review: derivatives.

Saturation, watched. With two options the softmax depends only on the gap between their scores. As the gap grows the top option’s probability climbs towards 1 and flattens, and the slope beside it, how much the probability still responds to a change of score, shrinks from its largest value, 1/4, to almost nothing: a model in this state hardly learns through its softmax.

This is saturation in exact terms: with large gaps, a small change of any score no longer changes the probabilities, and a learning signal passed back through the softmax by the chain rule fades away. A network that computes its scores as dot products of long vectors is especially exposed, because such scores grow with the length of the vectors; attention, for example, divides its scores by the square root of that length before its softmax.

Keeping a softmax out of saturation

Saturation is not always a problem. A model that gives the right answer a probability of 0.999 is saturated and should be: there is nothing left to learn from that example. The trouble comes in two situations: when a model is confidently wrong, so that the signal it needs is the one that has faded; and when a softmax sits inside a network, as in attention, where a saturated softmax stops the layers below it from learning at all. Deep learning has gathered a set of remedies, each acting at a different point.

Pair it with the right loss. The most important remedy is not to train through the probabilities themselves but through their logarithm, with the cross-entropy. Its slope with respect to the right option’s score is py − 1, which stays close to −1 however wrong the model is, so a confidently wrong output softmax still learns quickly. This is why output layers almost always compute a log-softmax and a cross-entropy together.

Keep the scores small. Saturation comes from large gaps between scores, so most other remedies keep the scores from growing large. Scores computed as dot products of long vectors grow with the vectors’ length, so attention divides them by the square root of that length. Normalisation layers rescale the vectors that go into the scores; some models also normalise the queries and keys of attention themselves, which bounds the scores directly. Some models cap the scores smoothly, passing them through a function such as c·tanh(z/c) that leaves small scores almost unchanged but never lets one exceed c (logit soft-capping, used for example in Google’s Gemma 2). And small random weights at the start (weight initialisation) mean that training begins with modest scores and an unsaturated softmax.

Do not ask for certainty. The cross-entropy never stops asking for more. Take two options, the right one and a wrong one. With a gap of 4.6 between their scores the right one gets probability 0.99 and the loss is 0.01; with a gap of 6.9 it gets 0.999 and the loss is 0.001. The loss reaches 0 only when the probability reaches 1, which needs an infinite gap, so training keeps pushing the right score up and the others down, example after example, and the scores grow until the softmax saturates.

Label smoothing removes the reason to push. Instead of asking for probability 1 on the right option, the training target asks for a little less, say 0.9, and gives the remaining 0.1 to the other options. Now the loss is smallest at a finite gap. The smoothed loss is −(0.9 ln p + 0.1 ln(1 − p)), the cross-entropy against the target 0.9 and 0.1, and it is smallest exactly when the model’s probability p equals the target, 0.9; beyond that the second term grows faster than the first shrinks, so pushing harder makes the loss larger again. With two options, the probability of the right one is the logistic function of the gap g, 1/(1 + e−g). Setting it to 0.9 gives e−g = 1/9, so g = ln 9 ≈ 2.2: a moderate gap is all the target asks for. The scores settle at a moderate size instead of growing for ever.

A second, simpler trick watches the overall level of the scores rather than their gaps. Since adding the same number to every score changes no probability, the scores can drift upwards or downwards together without anyone noticing, until they are large enough to cause trouble in the computation. A small extra term in the loss, the square of the log-sum-exp (sometimes called a z-loss), pulls that common level back towards zero. It changes nothing about which option wins or by how much; it only keeps the numbers in a comfortable range. Both tricks are forms of regularisation: they change what training aims for, a little, to keep the model well behaved.

Turn the temperature up when the soft information matters. When one network is trained to imitate another (knowledge distillation), the teacher’s probabilities are taken at a high temperature, so that the small probabilities on the wrong options, which carry much of what the teacher knows, are not flattened to zero.

Working with log-probabilities

Models, and the libraries they are built with, rarely work with probabilities directly. They work with their logarithms, log-probabilities. There are two reasons, and both come from the size of the numbers involved.

The first is that useful probabilities can be extremely small. A language model gives a probability to every token of a vocabulary of a hundred thousand tokens or more, and most of them are tiny: one in a million, one in a trillion, or far less. A computer stores numbers with limited precision (floating point), and in the common 32-bit format anything below about 10−45 becomes exactly 0. The second is that probabilities get multiplied: the probability of a whole sentence is the product of the probabilities of its tokens, and a product of a hundred numbers like 0.1 is 10−100, already too small for that format. The logarithm solves both problems at once. Here the logarithm is the natural one, written ln, to base e, the inverse of the exponential; only the figure below uses base 10, so that its steps are factors of ten. It turns a tiny number into a moderate negative one (the natural logarithm of one in a trillion is about −27.6), and it turns products into sums, which never underflow. The figure shows the first effect.

One probability shrinks from 1 to one in a trillion and grows back. On the plain axis (above) it is pressed against 0 almost all the time: 0.001 and 0.000000001 look the same. On the logarithmic axis (below) every factor of ten is one equal step, so a tiny probability is a clear, moderate negative number: one in a trillion is −12.

For the softmax, taking the logarithm also makes the formula simpler. Since pi = ezi divided by the sum, and the logarithm turns a division into a subtraction, the log-probability of option i is its score minus one number shared by all options:

lnpi=zi−LSE(z),LSE(z)=ln∑jezj=m+ln∑jezj−m

j runs over all options, and m is the largest score. Read the left part first: the log-probability of option i, ln pi, is its score zi minus LSE(z). LSE, short for log-sum-exp, is exactly what its name says: raise e to every score, sum, and take the logarithm. It is the same for every option, so the log-probabilities are just the scores shifted down by one common amount. The right part shows how LSE is computed safely: m is the largest score; taking it out in front leaves only powers of e that are at most 1, and changes nothing else.

Take the example from the start of the page, the scores 2, 1 and −1. The sum of their exponentials is 10.48, and its logarithm is LSE ≈ 2.35. The log-probabilities are therefore 2 − 2.35 = −0.35, 1 − 2.35 = −1.35 and −1 − 2.35 = −3.35; raising e to them gives back the probabilities 0.705, 0.259 and 0.035. No division was needed, and nothing small was ever stored.

What kind of number is LSE? It behaves like a softened maximum of the scores. It is always a little larger than the largest score, never by more than the logarithm of the number of options, and it is furthest above it when several scores are close to the top. When one score is far ahead, LSE is almost exactly that score, and the top option’s log-probability is almost exactly 0, that is, its probability is almost 1. The animation shows LSE following the largest of three scores.

Log-sum-exp is a smooth maximum. Score C moves from −3 to 5 and back while A stays at 2 and B at 0. The log-sum-exp (gold) always lies a little above the largest score (dashed): when C is far below A it is almost exactly 2, when C and A are equal it is highest above them, and once C leads it follows C. With K options it is never more than ln K above the largest score.

Taking out the largest score is not a detail. Suppose two scores are 1000 and 999. Computing e1000 directly overflows: in the 32-bit format, ex is already infinity above x ≈ 88.7. With m = 1000 taken out first, only e0 = 1 and e−1 ≈ 0.37 are needed, and LSE = 1000 + ln 1.37 ≈ 1000.31. Every serious implementation of the softmax and its logarithm works this way.

A few options out of many

Sometimes only a few of the options matter, for example when a model with a large vocabulary is asked to answer with one of the letters A to E. The probabilities within such a set S of options are a softmax over the scores of S alone:

p(c∣c∈S)=ezc∑c′∈Sezc′

S is the set of allowed options, c one of them, zc its score, and p(c ∣ c ∈ S) its probability given that the answer is in S. Given that the answer is one of the options in S, option c gets e to its score divided by the same summed over S only; the rest of the vocabulary drops out. This is a conditional probability. The probability on S as a whole, before this rescaling, says whether the model meant to choose among these options at all: if it put most of its probability elsewhere, the choice within S means little (answering a multiple-choice question).

Twelve tokens of a vocabulary with their probabilities (teal, and the five answer letters in gold). Keeping only the letters and dividing by their total, the letters keep their order and their ratios to each other, and now add up to 1: the softmax over the five letters’ scores alone.

Why does this work? Within the set, the bottom of every fraction loses the same terms, the exponentials of all the other options, so the letters keep their ratios to each other and are simply rescaled to add up to 1. This is a conditional probability: the probability of each letter, given that the answer is one of the letters (probability). It is the standard way to read a model’s choice among a few options without letting it write free text.

Cross-entropy, and why the logarithm matters

Finally, training. Suppose the right option is known, call it y, and the model should learn to give it a high probability. The natural goal is to make py large; the standard way to say this is to make the following loss small:

L=−lnpy=LSE(z)−zy,∂L∂zi=pi−[i=y]

z are the scores, pi the probability of option i, LSE(z) the log-sum-exp of the scores, and [i = y] is 1 for the right option and 0 for the others. The loss L is minus the log-probability of the right option y: near 0 when the model is sure and right, large when it gives y little probability. Its slope with respect to each score zi is the predicted probability pi, minus 1 for the right option. A step of gradient descent raises the right score by an amount proportional to 1 − py and lowers every other score in proportion to its probability. The slope follows from the chain rule.

Think of what this loss does on one example. If the model gives the right option a probability of 0.9, the loss is −ln 0.9 ≈ 0.11, small; at 0.5 it is 0.69; at 0.01 it is 4.6, large. The loss is 0 only for a model that is certain and right, and it grows without bound as the model becomes certain and wrong. Averaged over many examples, it is the cross-entropy between the right answers and the model’s probabilities.

Why the logarithm matters. As the probability of the right option grows from 0.02 to 0.98, the cross-entropy (left) falls smoothly, and the push it gives the right option’s score (gold bar) is strongest when the model is most wrong. The slope of the probability itself (teal bar) is weak at both ends: a loss built on the probability alone would hardly move a model that is confidently wrong.

Compare this with the slopes of the softmax itself. The slope of py with respect to its own score is py(1 − py), which is close to 0 when the model is confidently wrong (py near 0): a loss built on py directly would hardly move such a model. The logarithm cancels the exponential, and the cross-entropy’s slope for the right option stays near −1 however wrong the model is. This is why the softmax and the cross-entropy are used together almost everywhere. Language models, for example, are pretrained with this loss at every position of a text: the right option is the token that actually comes next, and the softmax runs over the whole vocabulary.

Test yourself

  1. Two options have logits 3 and 1. What probabilities does the softmax give them?

    About 0.881 and 0.119. Only the gap of 2 counts, so the first option is e2 ≈ 7.4 times as likely as the second; with two options this is the logistic function, 1 / (1 + e−2) ≈ 0.881.

  2. What happens to a softmax’s probabilities if 10 is added to every score? And if every score is multiplied by 10?

    Adding 10 changes nothing, because only the gaps between scores count. Multiplying by 10 multiplies every gap by 10, which is the same as a temperature of 1/10: the order stays the same, but the top option takes nearly all the probability, and the softmax saturates, so its slopes become nearly 0.

  3. Why are models trained to make −ln p of the right option small, rather than simply to make p large?

    Because p itself stops responding when the model is confidently wrong: the slope of py with respect to its own score is py(1 − py), close to 0 when py is close to 0, so training would barely move such a model. The logarithm undoes the exponential: the cross-entropy’s slope is py − 1, close to −1 in that case, the strongest push exactly where it is needed.

Where it leads

Kept in this browser only, never sent.