Turn logits into probabilities without overflowing
A model outputs one raw score (a logit) per token in its vocabulary. Softmax turns those scores into probabilities that add up to 1. Temperature T divides the logits before softmax: T below 1 makes the top token more likely, T above 1 flattens the odds.
Write softmax(logits, temperature=1.0) that returns a NumPy array of probabilities.
The catch: logits like 1000 overflow exp(). Subtract the largest logit before exponentiating. It does not change the answer, but it stops inf and nan.
def softmax(logits, temperature=1.0)Example
softmax([2.0, 1.0, 0.1]) is about [0.659, 0.242, 0.099].
Understand the idea
Softmax turns raw scores into probabilities: bigger score, bigger share, and all shares add up to 1. Think of splitting a cake by votes, where each vote is first made exponential. Temperature T is applied first by dividing every logit by T. Small T exaggerates gaps, large T shrinks them. The overflow problem: exp(1000) is inf in floating point. Subtracting the largest logit from every logit fixes this, because softmax does not change when you shift all inputs by the same number. Worked example, logits [2, 1, 0], T = 1: subtract max 2 to get [0, -1, -2], exponentiate to [1, 0.368, 0.135], sum is 1.503, so probabilities are about [0.665, 0.245, 0.090]. With T = 2 the scaled logits are [1, 0.5, 0] and the result flattens to about [0.506, 0.307, 0.186]. Rule: z = logits / T, z = z - max(z), p = exp(z) / sum(exp(z)). Every LLM sampler uses exactly this before drawing the next token.