Skip to main content

Given a vector of logits, sample one token id using a temperature and top-p (nucleus) sampling. For example, if the probabilities after temperature are 0.5, 0.3, 0.15 and 0.05 and top-p is 0.7, only the first two tokens can be chosen, with probabilities 0.625 and 0.375.

Coding rounds · Intermediate 3

Short answer

Divide the logits by the temperature and apply a stable softmax. Sort the probabilities from high to low, take the cumulative sum, and keep the smallest set of tokens whose total reaches p, including the token that crosses it. Renormalise the kept probabilities and sample one. The sort makes it O(V log V).

Deeper answer

Clarify first: logits is a vector of vocabulary size V for one position. Temperature must be above 0, so treat a temperature of 0 as a special case that returns the argmax. Top-p is between 0 and 1, and 1 means no filtering.

The steps: probs = softmax(logits / temperature), with the max subtracted first for stability. Then order = np.argsort(-probs), cum = np.cumsum(probs[order]), and cutoff = np.searchsorted(cum, top_p) + 1 gives the number of tokens to keep, which includes the one that crosses the threshold. Keep order[:cutoff], divide their probabilities by their sum, and draw with rng.choice(kept, p=kept_probs).

Explain the effect. A temperature below 1 sharpens the distribution and above 1 flattens it. Top-p then removes the long tail of unlikely tokens, and the number kept changes with how confident the model is. Test that at least one token is always kept, that top-p of 1 keeps everything, and that sampled frequencies match the renormalised probabilities. Interviewers watch for dropping the crossing token, which can leave nothing, for no renormalisation, and for temperature applied after the softmax.

What a strong answer covers

Answer it out loud in the mock interview about 3 min

Follow-ups to expect

Common mistakes

Learn it

How a model picks its next word: temperature, top-p and top-k

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.