Skip to content

← Activations step 8 of 9

Easy Primitives

Implement Softmax

Softmax turns a vector of scores, often called logits, into probabilities. Each score is exponentiated and divided by the sum of all those exponentials:

softmax(x)[i] = exp(x[i]) / sum(exp(x))

For [1.0, 2.0, 3.0], the result is approximately [0.090031, 0.244728, 0.665241]. The largest input gets the largest probability. Equal inputs get equal probabilities; four equal scores each get 0.25.

Subtract the maximum first

Direct exponentiation can overflow for large positive scores. Subtracting the same constant from every score leaves the mathematical probabilities unchanged. Choose the maximum so the largest shifted score is zero:

shifted = x - max(x)
weights = exp(shifted)
probabilities = weights / sum(weights)

For [1000.0, 1001.0, 1002.0], the shifted scores are [-2.0, -1.0, 0.0]. Their largest exponential is one, so this avoids the overflow in exp(1002). The probabilities match those for [1.0, 2.0, 3.0], up to floating-point error.

Your task

Implement softmax(x) for a nonempty one-dimensional tensor of finite floating-point scores. Return a vector of the same shape, normalized across the whole vector. Use basic reductions and arithmetic; do not call torch.softmax, torch.nn.functional.softmax or jax.nn.softmax.

The result should sum to approximately one. Extremely small probabilities can round to zero, so do not assume every floating-point result is strictly positive. NaN and infinite inputs are outside this exercise's contract.

The explorer below lets you change temperature. This exercise uses the ordinary formula at temperature one, with no additional temperature argument.

Loading visualization…