Generate a sequence with temperature, top-k, top-p and fixed random draws

A real decoding loop chains several steps: scale logits by temperature, softmax, cut with top-k, cut with top-p, renormalize, then draw a token. Giving the random numbers as input makes the whole loop testable.

The toy model is a table: logit_table has shape (V, V) and row t holds the next-token logits after token t.

Write sample_sequence(logit_table, start, uniforms, temperature, top_k, top_p, eos). Starting from current = start, for each u in uniforms (each 0 <= u < 1):
1. z = logit_table[current]. If temperature == 0, pick argmax(z) (lowest index on ties) and skip to step 6.
2. p = softmax(z / temperature), computed stably.
3. If top_k > 0, keep only the top_k largest p (ties: lower index ranks higher); set the rest to 0.
4. Sort the surviving tokens by p descending (ties: lower index first) and keep the shortest prefix whose cumulative sum is >= top_p (compare with a 1e-12 slack). Set the rest to 0.
5. Renormalize the kept p to sum 1. Walk tokens in increasing vocabulary index, accumulating kept p, and pick the first token where the running sum exceeds u. If rounding leaves none, pick the highest kept index.
6. Append the token. If it equals eos, stop. Otherwise set current to it.
Return the list of generated tokens (not including start).

Signaturedef sample_sequence(logit_table, start, uniforms, temperature, top_k, top_p, eos)

Example

if temperature is 0 the result is the greedy path, one token per uniform, stopping early at eos.

Understand the idea

A real decoding loop chains several steps for each new token: scale logits by temperature, softmax, keep the top k, keep the smallest set whose mass reaches top_p, renormalise, then draw. Supplying the random numbers u makes the draw repeatable. The draw walks tokens in vocabulary order, adding probabilities, and picks the first token where the running sum passes u. Worked example: logits [2, 1, 0], temperature 1. Softmax = [0.6652, 0.2447, 0.0900]. top_k = 2 keeps the first two. top_p = 0.8: sorted cumulative 0.6652 is below 0.8, adding 0.2447 gives 0.9099, so both stay. Renormalise: [0.7311, 0.2689, 0]. With u = 0.75, the running sum 0.7311 does not exceed 0.75, then 1.0 does, so token 1 is chosen. Rules: temperature 0 means greedy argmax; ties in ranking go to the lower index; compare cumulative mass with a 1e-12 slack; after picking, stop if it is eos, else the token becomes the next row of the table. Skipping the renormalise step makes large u values fall off the end. This is how sampling works in every chat model's generate loop.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: greedysample_sequence(_L, 0, _u, 0, 0, 1.0, 5)
  • Sample 2: plain samplingsample_sequence(_L, 1, _u, 1.0, 0, 1.0, -1)