Skip to main content

Implement softmax so that it does not overflow on large inputs. For example, the logits 1, 2, 3 should give about 0.09, 0.24, 0.67, and the logits 1000, 1001, 1002 should give the same answer, not NaN.

Coding rounds · Intermediate 2

Short answer

Subtract the largest logit from every logit, exponentiate, then divide by the sum: np.exp(x - x.max()) over its sum. The shift does not change the result because it cancels in the ratio, but the largest exponent becomes zero, so nothing overflows. The cost is linear in the number of logits.

Deeper answer

First ask about the shape. A single vector is simple. A batch of shape (n, classes) needs the max and the sum along the last axis with keepdims=True, so each row is normalised by itself and not by the whole batch.

The steps are z = x - x.max(axis=-1, keepdims=True), then e = np.exp(z), then e / e.sum(axis=-1, keepdims=True). Softmax is unchanged when you add a constant to every logit, so subtracting the max is exact, not an approximation. After the shift the largest value is 0, every exponential is at most 1, and the sum is at least 1, so there is no overflow and no division by zero. Time and memory are linear in the input.

Test that each row sums to 1, that 1000, 1001, 1002 matches 1, 2, 3, and that equal logits give a uniform result. Interviewers watch for the naive np.exp(x) version, and for a missing axis on a batch. If the next step is a log, compute log-softmax directly as z minus the log of the sum.

What a strong answer covers

Answer it out loud in the mock interview about 2 min

Follow-ups to expect

Common mistakes

Learn it

Neural networks

Practice Coding rounds questions

More on this topic

Today's AI turns are used

Lessons, roadmaps, videos, practice cards and the code playground stay free with your account, with no limit.