Std. Inf.TN-03
DepartmentDivision of Technical Notes
Form 300-NSoftmax, by hand
Sheet03 / 03
Date
[DD MMM YYYY]
Reading time
12 min
Level
Maths
Last checked
✓ [DD MMM YYYY]
Goes with D1 // Standard Deviation // Placeholder post

The softmax function, worked by hand

In short

Softmax turns a list of raw scores into probabilities that add up to 1. It takes three moves: raise e to the power of each score, add the results, then divide each one by the total. This note works one example by hand, then shows the same steps in a few lines of code.

The problem

At the end of each step, a language model gives a score to every token it knows. These scores are called logits raw, unscaled scores: any number, including negative ones. Logits are not probabilities. They do not add up to anything in particular. We need a fixed procedure that turns them into probabilities without changing their order.[1]

Softmax does not change the order of the scores. It changes what they mean.

The formula

For a list of n scores, written z, the probability for score number i is:

EQ 01 // SoftmaxDisplay maths
softmax⁡(z)i=ezi∑j=1nezj\operatorname{softmax}(z)_i = \frac{e^{z_i}}{\sum_{j=1}^{n} e^{z_j}}
Plainly
Raise e to the power of one score. Divide by the same thing done to every score, added up.

The number e is about 2.718.*1 Raising it to a power always gives a positive result, so every probability is above zero. Dividing by the total makes them add up to exactly 1.

Worked by hand

Take three scores. A calculator is enough.

  1. Write down the scores: 2.0, 1.0, 0.1.
  2. Raise e to each one: 7.389, 2.718, 1.105.
  3. Add them up: 7.389 + 2.718 + 1.105 = 11.212.
  4. Divide each by the total: 0.659, 0.242, 0.099.
  5. Check the result. The three numbers add up to 1.000, and the order has not changed.
Fig. 01 // Softmax, step by step01 / 03
Step 1 // Start with the scores
#z1
2.0
#z2
1.0
#z3
0.1
Raw scores. They add up to 3.1.
Fig. 01
Three scores in, three probabilities out. The largest score still wins.

In code

The same procedure, in Python.

Listing 01 // softmax.py
import math

def softmax(scores):
  exps = [math.exp(z) for z in scores]
  total = sum(exps)
  return [x / total for x in exps]

print(softmax([2.0, 1.0, 0.1]))
# ≈ [0.659, 0.242, 0.099]

In practice, libraries subtract the largest score from every score first. This keeps the numbers small enough to compute safely and gives the same answer.[2]

Sources

  1. [1][Reference placeholder — author, title, year] ↩
  2. [2][Reference placeholder — library documentation] ↩
▶
Watch the video
D1
Thumbnail // D1
Standard Deviation // D1[D1 working title]Coming soon

Corrections

No corrections yet.