Modern AI & LLMs Guide 4 of 7 · tap to switch
LLM Temperature, Top-K & Top-P Sampling
See how next-token prediction turns logits into fluent prose, why Temperature reshapes probabilities, why Top-P beats Top-K, and why hallucinations happen.
When an AI assistant streams a crisp 40-line Python script or a heartfelt poem onto your screen, it does NOT plan the whole paragraph in advance like a human essayist.
Instead, it runs ONE gloriously simple loop, one word (or word-piece token) at a time: feed your prompt into the Transformer, score every word in its ~100,000-word vocabulary for what fits next, pick one winner, glue it onto the end of the sentence, and feed that slightly longer sentence straight back in! In machine learning, this one-word-at-a-time feedback loop is called autoregressive generation.
Click Glue Word & Predict Next below to step through five turns until the special <EOS> (End-of-Sequence, or “Stop / Done”) signal cleanly ends the sentence!
The Temperature Dial: from strict robot (T = 0.0) to wild chaos (T = 1.8)
Before an LLM picks its next word, it assigns every candidate a raw confidence score (called a logit, written z). Higher scores mean a better fit. A math step called Softmax then converts those raw scores into percentages that add up to 100%.
Open any AI playground or API and the very first dial you meet is Temperature (T). There is zero mystery behind it: right before Softmax turns raw scores into percentages, we simply divide every raw score by T (z / T). Dividing by a tiny T stretches the gap between scores so the #1 word dominates; dividing by a big T squashes scores closer together so weird tail words steal real chances.
Drag the Temperature Dial below from 0.0 up to 2.0, watch the two coral nonsense tail words ("gravity" and "purple"), and click Roll 1 Sample Word to experience each setting live!
Pruning the weird tail: why Top-P (Nucleus Sampling) beats Top-K
Even at a sensible temperature (T = 0.8), thousands of tiny 0.001% nonsense words sit out in the long tail of a 100,000-word vocabulary. Add 10,000 tiny chances together and sooner or later a bizarre word hijacks your sentence!
To slice off that garbage tail before rolling the weighted die, AI systems rely on one of two cutoff rules:
- Fixed Top-K (for example,
K = 3): Always keep a fixed number of top choices (like the top 3 words), even when 1 word is obviously right or 5 words are equally good. - Adaptive Top-P (for example,
P = 0.90, called Nucleus Sampling): Keep just enough top words so their probabilities add up to 90%, shrinking automatically to 1 word on factual prompts and widening to 5 words on open creative prompts!
Start in Fixed Top-K (K = 3) on the Factual Prompt below to spot the flaw, then flip to Adaptive Top-P (90%) and switch to Open Creative Prompt!
Why smart LLMs still slip up: four real-world failure modes
Once you realize an LLM is picking plausible next words from one shared stream of text (rather than looking up verified records in a database), four famous real-world quirks immediately make total sense:
- Confident Guessing (Hallucinations): Asked for a private figure or obscure citation it never saw, the model smoothly invents a plausible-sounding fake source.
- Lost in the Middle: Given a giant 60-page document, models reliably recall facts near the start and end while overlooking details buried halfway through.
- People-Pleasing (Sycophancy): Nudged with a leading wrong question, models coached to sound polite can bend and agree with the mistake.
- Hidden Instruction Tricks (Prompt Injection): Because your rules and outside webpage text enter the exact same word stream, a hidden command inside outside text can hijack the reply.
Click each failure mode below to inspect the mini-chat slip-up and toggle the engineering fix!
See Temperature Softmax, Perplexity, Nucleus Sampling & Speculative DecodingThesis / Reference
1. Temperature-Scaled Softmax & Autoregressive Factorization: A causal language model factorizes the joint probability of a token sequence via the chain rule of probability, sampling each token from temperature-scaled logits :
As , converges to a Dirac delta at (Greedy Decoding); as , converges to the uniform distribution .
2. Nucleus (Top-P) Sampling (Holtzman et al., 2020): Rather than fixing cardinality , Nucleus Sampling selects the smallest vocabulary prefix (sorted descending by probability) whose cumulative mass satisfies , then renormalizes strictly over .
3. Perplexity & Speculative Decoding: Language model quality is evaluated via Perplexity (interpretable as the model’s average “effective branching factor” per token). In production serving, Speculative Decoding (Leviathan et al., 2023) lets a tiny draft model guess 4 to 6 tokens ahead while the giant target LLM verifies ALL of them in ONE parallel forward pass, yielding 2× to 3× faster streaming with mathematically identical output distributions!
See Temperature + Top-P Nucleus Sampling in Pure PyTorchOptional Code
import torch
import torch.nn.functional as F
def sample_next_token(logits, temperature=0.7, top_p=0.90):
if temperature <= 0.0:
return torch.argmax(logits, dim=-1) # Greedy decoding
probs = F.softmax(logits / temperature, dim=-1)
sorted_probs, sorted_idx = torch.sort(probs, descending=True)
cum_probs = torch.cumsum(sorted_probs, dim=-1)
# Keep smallest prefix whose cumulative mass reaches top_p (always keep rank 0)
mask = (cum_probs - sorted_probs) > top_p
sorted_probs[mask] = 0.0
sorted_probs /= sorted_probs.sum(dim=-1, keepdim=True)
pick = torch.multinomial(sorted_probs, num_samples=1)
return sorted_idx.gather(-1, pick)Wait: why does an LLM actually ANSWER your question instead of finishing it like a webpage?
A raw pretrained Transformer trained purely on internet next-token prediction is NOT a helpful assistant yet: type “Explain gravity to a 10-year-old” and a raw base model might just print “Explain magnetism to a 10-year-old” like a list of homework prompts!
How do labs turn raw internet autocomplete into helpful, honest, reasoning assistants (and how can YOU customize an open 70B model on a single GPU)?
Next up: Fine-Tuning, LoRA & RLHF (Post-Training).
Quick Intuition Check
Four quick real-world scenarios. No scores, just test your intuition.
You are building a strict SQL / JSON extractor that must output reliable, reproducible syntax with zero creative surprises. What Temperature setting fits best?
Why does Adaptive Top-P (Nucleus Sampling, e.g., P = 0.90) generally beat Fixed Top-K (e.g., K = 3) across varied prompts?
While generating a reply one word at a time, an LLM knows when to finish because it predicts and picks a special learned End-of-Sequence (<EOS>) stop signal from its vocabulary.
Your chatbot answers questions about a 60-page uploaded PDF, yet keeps missing exact pricing rules sitting on page 31 while nailing page 1 and page 60. What known failure mode is this?
Common Questions
What does Temperature do in ChatGPT, Claude, or Gemini APIs?
What is the difference between Top-K and Top-P (Nucleus Sampling)?
How does an LLM know when to stop writing?
Why do Large Language Models hallucinate false facts confidently?
Should you change BOTH Temperature and Top-P at the same time?
Related Visual Guides
Transformer Architecture & KV Cache
Step inside the complete blueprint powering GPT, Claude, and Gemini: Pre-Norm blocks, RoPE positional encoding, Encoder vs. Decoder families, and KV Caching.
Probability Distributions (Normal, Binomial & CLT)
The recurring shapes behind real-world data: bell curves, click counts, arrival rates, waiting times, and the Central Limit Theorem.
LoRA Fine-Tuning, RLHF & DPO (Post-Training)
How raw internet autocomplete becomes a helpful, aligned assistant via SFT, RLHF/DPO, and verifiable reasoning RL, plus low-cost LoRA adaptation.
Written & illustrated by Muhammad Aashir Irshad · Updated December 2026 · Free open-access reference
Cite this guide in a paper, thesis, or course (BibTeX & APA)
@misc{irshad2026llmtextgeneration,
author = {Irshad, Muhammad Aashir},
title = {LLM Temperature, Top-K & Top-P Sampling: Interactive Visual Guide},
howpublished = {SeeingML},
year = {2026},
month = {dec},
url = {https://seeingml.com/learn/llm-text-generation/},
note = {Interactive visual guide}
} Irshad, M. A. (2026). LLM Temperature, Top-K & Top-P Sampling: Interactive Visual Guide. SeeingML. https://seeingml.com/learn/llm-text-generation/