Softmax turns a vector of real-valued scores (logits) into a probability distribution. It sits at the end of every language model, turning scores over the vocabulary into next-token probabilities, and inside every attention layer.
Implement softmax(x, axis=-1) with NumPy.
Requirements
- Works on arrays of any shape, normalizing along
axis. The output has the same shape asx. - Numerically stable:
softmax(np.array([1000.0, 1001.0]))must not returnnan. The naive formula overflows, because isinfin float64. - No Python loops over elements.
Hint
Softmax is invariant to shifting all the inputs by the same constant :
Pick so the largest exponent is . Then nothing can overflow. Look up the keepdims argument to make the shift broadcast correctly.