17/25
Part 4 of 6 · A stable softmaxLearn

Subtract the largest score first, and the answer doesn't change

The fix is to shift the scores before the exponential.

Step
scores100010011002
minus the max-2-10
e to the power0.140.371.00the largest is exactly 1
divide by the sum0.090.240.67the sum is 1.50

Subtract the largest score from every score. Now the largest exponent is e0=1e^0 = 1, so nothing overflows. The sum is at least 1, so nothing divides by zero.

And the answer doesn't change, because softmax doesn't change when you subtract the same number from every input:

softmax(s)j=esj∑kesk=esj−m∑kesk−m\text{softmax}(s)_j = \frac{e^{s_j}}{\sum_k e^{s_k}} = \frac{e^{s_j - m}}{\sum_k e^{s_k - m}}

Here ss is one row of scores and mm is any number. Subtracting mm divides the top and the bottom by the same eme^m. Pick m=max⁡kskm = \max_k s_k, the largest score.

Here it is for one row of scores:

def shifted(s):
    e = np.exp(s - s.max())
    return e / e.sum()


print(shifted(big))
print(shifted(big - 1000))
[0.09003057 0.24472847 0.66524096]
[0.09003057 0.24472847 0.66524096]

The same weights for 1000, 1001, 1002 as for 0, 1, 2. Only the differences between the scores matter.