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

AI and LLM interview question Q474, Coding and practical. Intermediate, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/implement-temperature-top-k-and-top-p-over-logits

## Say it in 30 seconds

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.

## Say it in 2 minutes

A language model scores every token it knows before it picks the next one. Those raw scores are logits. Sampling turns them into chances and draws one token. Three settings shape that draw: temperature, top-k and top-p. I can write all three in about 30 lines of standard Python, and I can test them with a fixed draw so the result repeats.

In this sketch the order is fixed. First I divide each logit by the temperature. Then softmax turns the scores into chances that add up to one. Top-k keeps the k most likely tokens. Top-p keeps the smallest group whose chances reach p. Because the cuts remove some chances, I renormalise what is left before the draw.

Take a CI review bot that writes a severity field. Its label must be one of a few words, so I'd use a low temperature, then test it on past cases. In my example at temperature 0.5, the top label jumps from 52 percent to 74 percent, and the rare labels fall below one percent.

The edge cases are where candidates slip. A temperature of zero needs its own rule, because dividing by zero fails, so I take the top token instead. After any cut, the chances must be renormalised. And OpenAI's docs advise changing temperature or top-p, not both.

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

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

*Diagram, The order the sampler runs in: 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.*
1. Raw scores go into temperature, which divides each one by T.
2. The divided scores go into softmax, which turns them into chances.
3. The chances go into the cut step.
4. After top-k, top-p keeps the smallest group that reaches p.
5. The kept chances are renormalised and 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:

```text
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.

*Diagram, Two cuts on the same five chances: 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.*
1. Top-k keeps the two most likely tokens, then renormalises them.
2. Top-p keeps three, because low and medium reach only 78%.
3. A draw of 0.6 lands on low in the top-k case.
4. The same draw lands on medium in the top-p case.

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." Better: They 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." Better: Dividing 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." Better: They 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?

A. scaled = {t: z / temperature for t, z in logits.items()}
B. ranked = ranked[:top_k]
C. return {t: p for t, p in ranked}
D. top = max(scaled.values())

**Answer:** C. The cut above it is fine: it keeps the two best tokens. This return hands back the kept chances as they are, without dividing by their total, so they add up to less than one.

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

A. Raise temperature to 1.4 for more variety
B. Lower temperature to 0.2 and leave top-p unset
C. Set top-k to 1000 so nothing is cut
D. Raise top-p to 1.0 so every token stays in play

**Answer:** B. Low temperature gives the top label more of the chances, so the bot picks it more often. Raising temperature adds variety. A top-k of 1000 drops only the long tail of tiny chances, and a top-p of 1.0 keeps every token in play.

## Can you answer these from memory?

**Flash cards**

- **What order does the sampler run in?** Temperature, softmax, top-k, top-p, renormalise, then one draw.
- **What does temperature do to the logits?** It divides them. Below 1 sharpens the top token, above 1 flattens the list.
- **What does top-k keep?** The k most likely tokens. The rest are dropped.
- **What does top-p keep?** The smallest group of likely tokens whose chances reach p.
- **Why renormalise after a cut?** The kept chances must add up to one again before the draw.
- **What about temperature zero?** Dividing by zero fails. Take the top token instead (greedy).

## Likely follow-up questions

- Q022 What are logits, and what does softmax do? https://designervenkat.online/interview/ai/what-are-logits-and-what-does-softmax-do
- Q010 What does temperature control? https://designervenkat.online/interview/ai/what-does-temperature-control
- Q011 What is top-k sampling? https://designervenkat.online/interview/ai/what-is-top-k-sampling
- Q012 What is top-p (nucleus) sampling? https://designervenkat.online/interview/ai/what-is-top-p-nucleus-sampling
- Q013 Greedy vs beam search vs sampling? https://designervenkat.online/interview/ai/greedy-vs-beam-search-vs-sampling
- Q146 How do you pick top-k? https://designervenkat.online/interview/ai/how-do-you-pick-top-k

## Learn it in depth

- [Sampling Parameters](https://designervenkat.online/learn/ai-engineering/sampling-parameters)
