Four lines of arithmetic with three ways to get it wrong: dividing by a temperature of zero, exponentiating without subtracting the maximum, and applying the filters in an order that changes the result. The implementation, the verification against the analytic distribution, and the overflow that is one logit away.
Implement sampling from a model's logits with temperature, top-k and top-p. What are the numerical traps?
Four lines of arithmetic with three ways to get it wrong: dividing by a temperature of zero, exponentiating without subtracting the maximum, and applying the filters in an order that changes the result. The implementation, the verification against the analytic distribution, and the overflow that is one logit away.
Updated Sep 2026 · Grounded in real AI infrastructure interview loops and written to a senior-engineer editorial bar, with every number worked and every diagram hand-built.
The concepts behind this question
Ranked by how closely each one overlaps this question's topic, so the first card is the thing to read if the answer above moved too fast.
Scored on the max subtraction for stability, on temperature zero handled as greedy rather than by division, on the order of temperature then top-k then softmax then top-p, and on verifying empirically against the analytic softmax.
No comments yet — be the first to share your approach.
