esc
  • WorkflowsPages
  • Case studiesPages
  • Machine Learning FoundationsLearn
  • AI EngineeringLearn
  • AI Guardrails & Red TeamingLearn
  • UI/UXLearn
  • Design SystemsLearn
  • Production System DesignLearn
  • AI papersPages
  • Interview KitPages
  • Book a callContact
Let’s talk

I’ll build the agent for it.

Implement Temperature, Top-K and Top-P Over Logits

How temperature, top-k and top-p reshape a model's next-token scores, with a 30-line Python sketch you can run, for your AI interview.

In short

Divide the raw scores (logits) by temperature, turn them into chances with softmax, keep the top k tokens, then keep the smallest group whose chances reach top-p. Renormalise what is left and draw one token. The whole thing fits in about 30 lines of plain Python.

11 min readIntermediateCommon · estimateFacts checked 27 November 2026

Say it out loud

Read it once, then say it without looking. Start with the short one; use the long one when they ask you to go deeper.

A model scores every possible next token. I divide those scores by temperature, turn them into chances with softmax, then keep the top k tokens and the smallest group that reaches top-p. I renormalise what is left and draw one token. In code it is about 30 lines of plain Python, and I test it with a fixed draw so the result repeats.

What is sampling over logits, in plain words?

A language model reads your text, then scores every token it knows for what should come next. A token is a chunk of text, often a word or part of one. The raw scores are called logits. Sampling means picking one token from those scores, and the three settings in this answer control how that pick is made.

Here is an everyday picture. A claims adjuster chooses the next phrase for a settlement letter from a shortlist, each phrase with a score from past files. She can make her picks sharper, drop the weakest phrases, or stop once the phrases she has cover most of the cases. Those are the three moves.

A real case: a CI review bot, which is a program that checks each code change before it merges, writes a JSON verdict. JSON is a small structured text record. The verdict has a severity field, and the label must be one of a few words, so the sampler has to stay predictable.

Two words will come up. A draw means picking one token at random, with each token's chance as its weight. Renormalise means scaling the remaining chances back up so they add up to one again.

Key words

Logit
The raw score a model gives each possible next token, before it becomes a chance.
Softmax
A formula that turns scores into positive chances that add up to one.
Temperature
A number that divides the scores, making the top token stronger or weaker.
Top-k
Keep only the k most likely tokens and drop the rest.
Top-p
Keep the smallest group of likely tokens whose chances add up to at least p.

How do the three settings change the chances?

Every setting works on the same list of scores, in the order this sketch uses: temperature, then softmax, then the two cuts, then one draw. Libraries may use a different order, so check the one you use.

The order the sampler runs in

Logits

one raw score per token

Temperature

divide each score by temperature

Softmax

scores become chances

Cut the tail

Top-k

keep the k best tokens

Top-p

keep until chances reach p

Draw one token

renormalised, then one draw

  1. 1Raw scores go into temperature, which divides each one by T.
  2. 2The divided scores go into softmax, which turns them into chances.
  3. 3The chances go into the cut step.
  4. 4After top-k, top-p keeps the smallest group that reaches p.
  5. 5The kept chances are renormalised and one token is drawn.
Temperature reshapes the scores first, and softmax turns them into chances. Top-k and top-p cut the list, and the kept chances are renormalised before one token is drawn.

Temperature is a division. Dividing the logits by a number under one makes the gaps between them bigger, so the top token takes more of the chances. Dividing by a number above one shrinks the gaps, and the list flattens. Top-k counts tokens, while top-p counts probability mass, so the number of tokens kept grows and shrinks with how sure the model is.

  • “Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.”

    OpenAI

  • “produces a softer probability distribution over classes.”

    Hinton and co-authors, on softening a softmax with temperature

  • “truncating the unreliable tail”

    Holtzman and co-authors, on nucleus sampling

Here is the whole thing in 30 lines of standard-library Python. The logits are made up, for a CI bot that has just reached its severity field.

Python
# A CI review bot writes a JSON verdict. After "severity": " it picks the next token. Logits are made up.
import math
LOGITS = {"low": 2.1, "medium": 1.4, "high": 0.9, "critical": -0.5, "none": -1.2}
def filter_probs(logits, temperature=1.0, top_k=None, top_p=None):
    scaled = {t: z / temperature for t, z in logits.items()}  # temperature divides the logits
    top = max(scaled.values())  # subtracting the max stops exp() overflowing
    exps = {t: math.exp(z - top) for t, z in scaled.items()}
    ranked = sorted(((t, e / sum(exps.values())) for t, e in exps.items()), key=lambda kv: kv[1], reverse=True)
    if top_k is not None:
        ranked = ranked[:top_k]  # keep the k most likely tokens
        ranked = [(t, p / sum(q for _, q in ranked)) for t, p in ranked]  # renormalise before top-p
    if top_p is not None:
        kept, mass = [], 0.0
        for token, p in ranked:  # keep tokens until their chances reach top_p
            kept.append((token, p)); mass += p
            if mass >= top_p: break
        ranked = kept
    return {t: p / sum(q for _, q in ranked) for t, p in ranked}  # renormalise the survivors
def pick(dist, draw):  # walk the running total until it passes the random draw
    cumulative = 0.0
    for token, p in dist.items():
        cumulative += p
        if draw < cumulative:
            return token
    return token
for label, settings in [("plain", {}), ("temperature 0.5", {"temperature": 0.5}),
                        ("top_k 2", {"top_k": 2}), ("top_p 0.8", {"top_p": 0.8})]:
    dist = filter_probs(LOGITS, **settings)
    shown = ", ".join(f"{t} {p:.2f}" for t, p in dist.items())
    print(f"{label}: {shown} | draw 0.6 picks {pick(dist, 0.6)}")

Output

plain: low 0.52, medium 0.26, high 0.16, critical 0.04, none 0.02 | draw 0.6 picks medium
temperature 0.5: low 0.74, medium 0.18, high 0.07, critical 0.00, none 0.00 | draw 0.6 picks low
top_k 2: low 0.67, medium 0.33 | draw 0.6 picks low
top_p 0.8: low 0.56, medium 0.28, high 0.17 | draw 0.6 picks medium

Read the output. At temperature 0.5 the top token jumps from 52% to 74%, and the bottom two fall to under 1%. Top-k 2 keeps low and medium and renormalises them to 67% and 33%. Top-p 0.8 keeps three tokens, because low and medium reach only 78%, so high joins them. The draw of 0.6 is fixed in the script so the output repeats.

Two cuts on the same five chances

Five chances (plain)

low 52%, medium 26%, rest 22%

Keep two tokens

renormalised: 67% and 33%

Keep three tokens

renormalised, about 56%, 28%, 17%

Top-k picks low

draw 0.6 lands on low

Top-p picks medium

draw 0.6 lands on medium

  1. 1Top-k keeps the two most likely tokens, then renormalises them.
  2. 2Top-p keeps three, because low and medium reach only 78%.
  3. 3A draw of 0.6 lands on low in the top-k case.
  4. 4The same draw lands on medium in the top-p case.
The same five chances, cut two ways. Top-k keeps two tokens and top-p keeps three, so the same draw lands on different words.

The OpenAI docs say: "We generally recommend altering this or top_p but not both." So in production, pick one of temperature or top-p and tune that one.

What edge cases break a sampler?

  • Temperature of zero

    Dividing by zero fails. Take the top token instead. Always picking the top token is called greedy decoding. Hugging Face describes greedy search as selecting the next most likely token at each step. The 30-line sketch leaves this check out to stay short, so add an if-check before the divide in real code.

  • Top-k bigger than the vocabulary

    Slicing keeps everything, so it is harmless. Still check that k is a whole number above zero, since a bad config value should fail loudly.

  • Chances that stop adding to one

    After any cut, divide by the new total. Skipping this means the draw runs past the end of the list, and the last token is picked by mistake.

  • Ties in the scores

    Two tokens with the same score keep the order the sort gives them. Write a test that fixes that order, so results repeat.

Tip

Asked to write it, say the three parts in order: scale, cut, renormalise. Then name the edge cases: temperature of zero, top-k bigger than the vocabulary, and top-p of one, which keeps everything.

What does the interviewer want to hear?

A strong answer covers

  • The order: temperature, softmax, top-k, top-p, renormalise, draw.
  • Temperature divides the logits: below one sharpens, above one flattens.
  • Top-k counts tokens; top-p counts probability mass.
  • Renormalise after every cut, so the chances add up to one again.
  • Edge cases: temperature zero, k too big, p of one.
  • A fixed draw in the test, so the output repeats.

Common traps

  • Trap"Top-k and top-p do the same job."

    BetterThey differ. Top-k fixes a count of tokens. Top-p fixes a share of the chances, so the count moves with how sure the model is.

  • Trap"Temperature 0 is just a very small number, so divide by it."

    BetterDividing by zero fails. Treat temperature zero as its own case and take the top token.

  • Trap"Once I cut the list, the chances still add up to one."

    BetterThey don't. Divide by what is left, or the draw runs past the end and the last token is picked by mistake.

Can you spot the bug?

Spot the bug

A teammate's sampler keeps two tokens. Which line hands back the kept chances without dividing by their total?

Quick check

A CI review bot writes a severity field. Which setting keeps that label most predictable?

Can you answer these from memory?

Flash cards · tap a card to flip it

1 / 6

What will they ask next?

  1. Q022What are logits, and what does softmax do?11 min
  2. Q010What does temperature control?10 min
  3. Q011What is top-k sampling?11 min
  4. Q012What is top-p (nucleus) sampling?10 min
  5. Q013Greedy vs beam search vs sampling?12 min
  6. Q146How do you pick top-k?11 min

Learn it in depth

Last updated on 27 November 2026

Shipping a bot that writes structured output?

I design and build AI agents, including the sampling settings and checks around them. Book a short call and tell me what your bot outputs and how wrong it is allowed to be.