Sampling and Decoding
Decoding is how a language model turns its scores into text, one token at a time. At each step the model gives a probability to every token in its vocabulary, and a decoding strategy chooses one: always the most likely (greedy decoding), or a random draw (sampling), shaped by temperature, top-k and top-p. The same model can sound careful or creative, repetitive or chaotic, depending only on these settings.
This lesson completes the chapter's checkpoint: run a small open model locally, inspect its tokenizer, and generate text with different temperatures.
Decoding Strategies
| Setting | Description |
|---|---|
| Greedy | It is used to always pick the most likely token; the same output every time |
| Sampling | It is used to draw a token at random, in proportion to its probability |
| Temperature | Divides the scores before softmax: below 1 sharpens the choice, above 1 flattens it |
| Top-k | It is used to sample only from the k most likely tokens |
| Top-p (nucleus) | It is used to sample only from the smallest set of tokens whose probabilities add up to p |
| Max new tokens | It is used to stop generation after a set number of tokens |
| Stop token | Generation also stops when the model writes its end-of-turn token |
Example: How the Settings Change the Odds
The programs in this chapter need pip install torch transformers. They use SmolLM2-135M, a small open language model from Hugging Face (Apache 2.0 license, about 270 MB), which runs on an ordinary laptop. The first run downloads it; the download and loading messages are left out of the output shown.
This program takes the real scores SmolLM2-135M gives for the word after "My favorite subject at school is" and applies each setting.
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM2-135M")
model = AutoModelForCausalLM.from_pretrained("HuggingFaceTB/SmolLM2-135M")
model.eval()
ids = tokenizer("My favorite subject at school is", return_tensors="pt").input_ids
with torch.no_grad():
logits = model(ids).logits[0, -1].float() # raw scores for all 49,152 tokens
def top5(probs):
top = probs.topk(5)
return " ".join(f"{tokenizer.decode(i).strip()} {p:.1%}" for p, i in zip(top.values, top.indices))
for t in [0.5, 1.0, 2.0]: # temperature divides the scores before softmax
probs = (logits / t).softmax(dim=0)
print(f"temperature {t}: {top5(probs)}")
probs = logits.softmax(dim=0)
sorted_p, order = probs.sort(descending=True)
print("\nTop-k = 50 keeps 50 tokens, which hold", f"{sorted_p[:50].sum():.1%}", "of the probability")
keep = int((sorted_p.cumsum(0) < 0.9).sum()) + 1 # top-p: smallest set that reaches 90%
print(f"Top-p = 0.9 keeps the {keep} most likely tokens")
print("Greedy decoding always picks:", repr(tokenizer.decode(order[0])))temperature 0.5: math 41.7% history 22.3% science 9.3% the 7.2% music 2.4%
temperature 1.0: math 8.0% history 5.9% science 3.8% the 3.3% music 1.9%
temperature 2.0: math 0.4% history 0.3% science 0.3% the 0.3% music 0.2%
Top-k = 50 keeps 50 tokens, which hold 50.2% of the probability
Top-p = 0.9 keeps the 1851 most likely tokens
Greedy decoding always picks: ' math'Explanation:
- At temperature 1.0 the probabilities are the model's own: "math" 8.0%, "history" 5.9%, "science" 3.8%. They are low because thousands of other tokens each get a little probability.
- At temperature 0.5, the scores are doubled before softmax, so the top choices take over: "math" jumps to 41.7%. Lower temperature means more predictable text.
- At temperature 2.0, the scores are halved, and the distribution becomes almost flat: "math" falls to 0.4%. Higher temperature means more surprising, and soon nonsensical, text.
- Top-k = 50 keeps only the 50 most likely tokens, which hold 50.2% of the probability here, and throws away a long tail of unlikely ones.
- Top-p = 0.9 keeps the smallest set that reaches 90%, which here is 1,851 tokens, because this question has many reasonable answers. For a question with one clear answer, top-p would keep only a few. That flexibility is why top-p is popular.
- Greedy decoding always picks "math".
Example: The Checkpoint
This program loads the instruct model, inspects its tokenizer, and asks for a science fair slogan at temperature 0 (greedy), 0.7 and 1.5, with two random seeds each.
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
name = "HuggingFaceTB/SmolLM2-135M-Instruct"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(name)
model.eval()
# 1. Inspect the tokenizer
print("Model:", name, f"({sum(p.numel() for p in model.parameters()):,} parameters)")
print("Vocabulary:", f"{len(tokenizer):,} tokens | end-of-turn token:", tokenizer.eos_token)
messages = [{"role": "user", "content": "Write a one-sentence slogan for a school science fair."}]
ids = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt", return_dict=True)["input_ids"]
print("Prompt with chat template:", ids.shape[1], "tokens")
print("Last 8 tokens:", tokenizer.convert_ids_to_tokens(ids[0, -8:]))
# 2. Generate with different temperatures
def generate(temperature, seed):
torch.manual_seed(seed) # the same seed gives the same sample
settings = dict(do_sample=False) if temperature == 0 else dict(do_sample=True, temperature=temperature, top_p=0.95)
out = model.generate(ids, max_new_tokens=30, pad_token_id=tokenizer.eos_token_id, **settings)
return tokenizer.decode(out[0, ids.shape[1]:], skip_special_tokens=True).strip().split("\n")[0]
for temperature in [0, 0.7, 1.5]:
print(f"\ntemperature {temperature}:")
for seed in [1, 2]:
print(f" seed {seed}: {generate(temperature, seed)}")Model: HuggingFaceTB/SmolLM2-135M-Instruct (134,515,008 parameters)
Vocabulary: 49,152 tokens | end-of-turn token: <|im_end|>
Prompt with chat template: 42 tokens
Last 8 tokens: ['Ġfair', '.', '<|im_end|>', 'Ċ', '<|im_start|>', 'ass', 'istant', 'Ċ']
temperature 0:
seed 1: "Discover the wonders of the natural world through hands-on experiments and innovative teaching methods."
seed 2: "Discover the wonders of the natural world through hands-on experiments and innovative teaching methods."
temperature 0.7:
seed 1: "Innovative, Engaging, and Exclusive: A School Science Fair Award for Science Fair Winners"
seed 2: "Discover the world of science through interactive experiments and innovative thinking."
temperature 1.5:
seed 1: "At www.tricky_ease.org @tricky-ease, the goal remains the highest achievable teaching standard: the
seed 2: To foster curiosity and inspire student wonder, we'll craft a clever yet meaningful slogan for a school science fair that sparks a spark of wonder. Our sloganExplanation:
- The tokenizer: 49,152 tokens, and
<|im_end|>is the token that ends the assistant's turn, so generation stops there. With the chat template, the short request becomes 42 tokens; the last 8 show the end of the user message and the start of the assistant's turn.Ċis how this tokenizer shows a new line. - Temperature 0 (greedy) gives the same slogan for both seeds, because there is no randomness. It is sensible, if not really about a fair.
- Temperature 0.7 gives two different, reasonable slogans. This range (about 0.6 to 0.8) is a common default for writing that should vary but stay on topic.
- Temperature 1.5 drifts: seed 1 invents a web address, and seed 2 talks about writing a slogan instead of writing one. Unlikely tokens get picked, and each odd choice makes the next one odder.
torch.manual_seed()makes sampling repeatable: the same seed, settings and model give the same text on the same machine.max_new_tokens=30cuts the longer replies off mid-sentence.
The checkpoint is complete: the model runs locally, its tokenizer is inspected, and the effect of temperature is clear.
Choosing Settings
| Task | Typical settings |
|---|---|
| Facts, extraction, classification, code | Temperature 0 to 0.3 |
| Everyday chat and explanations | Temperature about 0.7, top-p 0.9 to 0.95 |
| Brainstorming, stories, slogans | Temperature 0.8 to 1.0, sometimes higher |
| Repeated text | Raise temperature slightly, or use a repetition penalty |
Hosted model APIs expose the same settings; see "Temperature and Randomness". Some newer reasoning models fix or ignore temperature, so check each model's documentation.
Common Mistakes
Expecting the same answer twice with sampling. Sampling is random by design; set a seed for repeatable tests or use temperature 0.
Using very high temperature for "creativity". Above about 1.2, text quickly becomes incoherent, as the 1.5 samples show.
Setting both a tiny top-k and a high temperature. The settings interact; change one at a time and look at real samples.
Forgetting max_new_tokens. Without a limit or a stop token, generation can run long and cost more.
Interview Corner
What does temperature do?
It divides the logits before softmax: values below 1 make the distribution sharper and the output more predictable, values above 1 make it flatter and more random. Temperature 0 is treated as greedy decoding.
What is the difference between top-k and top-p sampling?
Top-k always keeps a fixed number of the most likely tokens; top-p keeps the smallest set whose probabilities add up to p, so it keeps few tokens when the model is confident and many when it is not.
Practice
Exercise: top-k vs top-p. In the checkpoint program, replace top_p=0.95 with top_k=5 and run temperature 1.5 again. Does limiting to 5 tokens keep the slogans on topic?
Check your understanding:
- Why did both seeds give the same slogan at temperature 0?
- What happened to the probability of "math" as temperature went from 0.5 to 2.0?
- Why did top-p 0.9 keep 1,851 tokens for this prompt?
Key Takeaways
Quick reference
| Need | Code |
|---|---|
| Greedy | model.generate(ids, do_sample=False, max_new_tokens=30) |
| Sampling | model.generate(ids, do_sample=True, temperature=0.7, top_p=0.95) |
| Top-k | model.generate(ids, do_sample=True, top_k=50) |
| Repeatable samples | torch.manual_seed(1) |
| Temperature by hand | (logits / t).softmax(dim=0) |
| Inspect tokens | tokenizer.convert_ids_to_tokens(ids[0]) |
Was this tutorial helpful?