The starter code had softmax and test cases already written, which honestly helped a lot.
Start by clarifying the input shape and whether logits are 1D or batched, then walk through the algorithm step-by-step while writing clean NumPy code. Emphasize numerical stability and vectorization, and discuss trade-offs like sorting cost and handling edge cases.
Pro tip: Mention that you subtract the max logit before softmax to avoid overflow, and use np.cumsum on sorted probabilities to find the cutoff efficiently. Also note that top-p sampling is often used with temperature scaling, so you might apply temperature before softmax.
Ask about input dimensions (1D vs. batched), dtype, and whether p is a scalar or per-example. Discuss handling of p=0, p=1, and ties in probabilities.
Subtract the maximum logit before exponentiating, then normalize to get probabilities. This prevents overflow and underflow.
Sort probabilities in descending order, compute cumulative sum, and find the smallest set where cumsum >= p. Use np.searchsorted or boolean masking to identify the cutoff index.
Create a mask for the nucleus, set probabilities outside to zero, and renormalize the remaining probabilities to sum to 1.
Use np.random.choice with the renormalized probabilities to sample an index, then map back to the original token ID if needed.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.