Numerically Stable Softmax From Scratch
Difficulty: Medium · Concept: Activation Functions — Auxiliary Functions
Unlike sigmoid, softmax operates on a whole vector at once, turning raw scores ("logits") into a probability distribution that sums to 1 — the standard output layer for multi-class classification, and exactly what turns an LLM's raw next-token scores into a probability distribution over the vocabulary.
Your task: implement softmax(z) for a list of real numbers. The naive formula above overflows for large inputs — math.exp(1000) raises OverflowError in plain Python — so your implementation needs to be numerically stable: it must return correct results even when every value in z is large.
Next: Softmax Gradient (Vector-Jacobian Product) (a harder variant)