BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Sampling and decoding14 of 17 in topic

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

HardSampling and decoding Pro
Asked atAnthropicCohereDeepMindOpenAI

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).

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

Example 1

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

Constraints

  • logit_table has shape (V, V)
  • Python 3 with NumPy. Code runs in your browser.
  • Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1

Use np.argsort(-p, kind='stable') for both cuts.

Hint 2

Keep a boolean keep mask, then do q = p * keep / (p * keep).sum() and np.cumsum(q) for the draw.

Common mistakes
  • Skipping the renormalization, as the buggy version does, leaves a cumulative sum below 1, so large uniforms fall off the end and always land on the last kept token, biasing the output.
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.

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.

Topics
Sampling and decoding
Companies4
  • Anthropic the topic appears in interview reports Coding Exercises & ML System Design: Real AI Interview Questions (landedjobs)
  • Cohere a candidate reported this question Cohere Machine Learning Engineer Interview Questions | Screna AI
  • DeepMind the topic appears in interview reports AI Engineering Interview Questions Company Wise (Outcome School)
  • OpenAI the topic appears in interview reports Coding Exercises & ML System Design: Real AI Interview Questions (landedjobs)

From public interview reports and guides. Not affiliated with or endorsed by these companies.

Similar questions
  • Decode with beam searchHard
  • Decode under a finite-state grammarHard
  • Keep the nucleus: top-p filteringMedium
  • Apply repetition, frequency and presence penalties to logitsMedium
All Sampling and decoding problems
Report
425 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
import numpy as np
​
def sample_sequence(logit_table, start, uniforms, temperature, top_k, top_p, eos):
# your code here
pass
​
sample_sequence(_L, 0, _u, 0, 0, 1.0, 5)

This case uses generated data, so it runs as written. Press + to add your own case.

Run checks these cases in your browser, no sign-in needed. Submit checks the full hidden test set with Pro.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS