SeeingML
Modern AI & LLMs Guide 4 of 7 · tap to switch
✦ Interactive Visual Guide 9 min · 4 hands-on labs · Beginner friendly

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!

Interactive Lab 1: One-Word-at-a-Time Loop (Autoregressive)
Turn 1 of 5
Prompt So Far (Fed Into Model)Next Word About to Be Glued On
The corner cafe serves the bestNext pick: "espresso"
Top 4 Next-Word Chances (Out of ~100,000 Vocabulary Words)Green bar = picked & glued next
"espresso" ← Picked & glued next52%
"coffee" 28%
"croissants" 14%
"tea" 6%
Each turn adds 1 word, then feeds the longer sentence back in.
Turn 1: The model reads your 6-word prompt, scores ~100,000 possible next words, and picks "espresso" (52%) to glue onto the end.

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!

Interactive Lab 2: Reshaping Chances With Temperature (T = 0.0 to 2.0)
Nonsense Tail Risk: 0.4%
Active Prompt
"The corner cafe serves the best ___"
Tip: Click Roll 1 Sample Word several times at T = 0.0, then try T = 1.8 to feel the chaos!
Candidate Word & Raw Score (Logit)Chance After Dividing by T = 0.7
"espresso" (raw score 4.8)63.3%
"latte" (raw score 4.1)23.3%
"croissants" (raw score 3.5)9.9%
"matcha" (raw score 2.7)3.1%
"gravity" (raw score 0.9, nonsense tail!)0.2%
"purple" (raw score 0.6, nonsense tail!)0.2%
T = 0.7
0.0 (Strict)0.7 (Balanced)2.0 (Chaotic)
T = 0.7 (Natural Conversational Sweet Spot): balances lively variety across realistic cafe words ("espresso", "latte", "croissants", "matcha") while keeping nonsense tail words small (0.4%).

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!

Interactive Lab 3: Fixed Top-K (K = 3) vs. Adaptive Top-P (90% Nucleus)
Kept Pool: 3 of 6 words
Try this: Step 1: Look at how Fixed Top-K forces "Lyon" and "located" into the pool. Now click Adaptive Top-P (90%)!
Factual Prompt: "The capital of France is ___"
Cumulative Probability Bar (Running Sum)Kept Raw Mass: 98%
Paris
0%50%90% Top-P Goal100%
Fixed K = 3 keeps 3 words: 94% + 2.5% + 1.5% = 98% (even though "Paris" alone is already 94%!)
#1"Paris"raw 94%sum 94%kept 95.9%
#2"Lyon"raw 2.5%sum 96.5%kept 2.6%
#3"located"raw 1.5%sum 98%kept 1.5%
#4"famous"raw 1%sum 99%pruned
#5"banana"raw 0.5%sum 99.5%pruned
#6"purple"raw 0.5%sum 100%pruned
Why kept percentages rise: Once pruned words are tossed out, the remaining pool is rescaled proportionally so the surviving chances add back up to 100% before rolling.
Clunky! Fixed Top-K (K = 3) always forces 3 words into the dice roll even though "Paris" is 94% certain, keeping silly distractions like "Lyon" and "located" alive!

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:

  1. Confident Guessing (Hallucinations): Asked for a private figure or obscure citation it never saw, the model smoothly invents a plausible-sounding fake source.
  2. 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.
  3. People-Pleasing (Sycophancy): Nudged with a leading wrong question, models coached to sound polite can bend and agree with the mistake.
  4. 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!

Interactive Lab 4: Four Real-World LLM Slip-Ups (Mini-Chat Demos)
Broken Default
Mini-Chat Demo: Fake Sources & Numbers
UserWhat is the exact 2024 refund policy and citation code in Northstar Bakery's private staff handbook?
AI Failure: Confidently Invented Source
Sure! According to Section 4.2 of the 2024 Northstar Staff Handbook (Doc #NB-884), full cash refunds are allowed within 45 days.
Completely made up! Section 4.2, Doc #NB-884, and the 45-day rule do not exist.
Why It HappensNext-token generation optimizes plausible phrasing, NOT checking a verified database. When asked for private numbers or obscure citations, the model smoothly predicts realistic-sounding fake facts.
Plain-English Engineering FixConnect an open-book document lookup so the model reads real pages first, explicitly allow "I do not know" answers, and add a fact-check step for citations or numbers.
Viewing broken default for 1. Confident Guessing (Hallucination). Click "Apply Fix →" inside the chat to see the guardrail in action!
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 (x1,…,xn)(x_1, \dots, x_n) via the chain rule of probability, sampling each token from temperature-scaled logits zt∈R∣V∣\mathbf{z}_t \in \mathbb{R}^{|V|}:

P(x1,…,xn)=∏t=1nP(xt∣x<t),PT(v∣x<t)=exp⁡(zt,v/T)∑j=1∣V∣exp⁡(zt,j/T)P(x_1, \dots, x_n) = \prod_{t=1}^{n} P(x_t \mid x_{<t}), \qquad P_T(v \mid x_{<t}) = \frac{\exp(z_{t,v} / T)}{\sum_{j=1}^{|V|} \exp(z_{t,j} / T)}

As T→0+T \to 0^+, PTP_T converges to a Dirac delta at arg⁡max⁡vzt,v\arg\max_v z_{t,v} (Greedy Decoding); as T→∞T \to \infty, PTP_T converges to the uniform distribution 1/∣V∣1/|V|.

2. Nucleus (Top-P) Sampling (Holtzman et al., 2020): Rather than fixing cardinality KK, Nucleus Sampling selects the smallest vocabulary prefix V(p)V^{(p)} (sorted descending by probability) whose cumulative mass satisfies ∑v∈V(p)P(v∣x<t)≥p\sum_{v \in V^{(p)}} P(v \mid x_{<t}) \ge p, then renormalizes strictly over V(p)V^{(p)}.

3. Perplexity & Speculative Decoding: Language model quality is evaluated via Perplexity PPL⁡=exp⁡ ⁣(−1n∑t=1nln⁡P(xt∣x<t))\operatorname{PPL} = \exp\!\left(-\frac{1}{n}\sum_{t=1}^{n} \ln P(x_t \mid x_{<t})\right) (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
python
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).

✓ Self-Check

Quick Intuition Check

Four quick real-world scenarios. No scores, just test your intuition.

1

You are building a strict SQL / JSON extractor that must output reliable, reproducible syntax with zero creative surprises. What Temperature setting fits best?

Pick an option first, or peek anytime
2

Why does Adaptive Top-P (Nucleus Sampling, e.g., P = 0.90) generally beat Fixed Top-K (e.g., K = 3) across varied prompts?

Pick an option first, or peek anytime
3

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.

Pick an option first, or peek anytime
4

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?

Pick an option first, or peek anytime
Quick Reference

Common Questions

What does Temperature do in ChatGPT, Claude, or Gemini APIs?
Temperature T divides the model's raw output logits (z / T) right before Softmax. Low temperature (0.0 to 0.3) sharpens probabilities onto the single safest answer (best for code, JSON, and facts), medium temperature (0.7) adds lively natural variety, and high temperature (> 1.5) flattens probabilities so bizarre tail words get sampled.
What is the difference between Top-K and Top-P (Nucleus Sampling)?
Top-K always keeps a fixed number K of top tokens regardless of confidence, which either keeps junk words on obvious factual questions or cuts off good words on creative prompts. Top-P (Holtzman et al., 2020) keeps the smallest dynamic set of top words whose cumulative probability reaches P (e.g., 90%), adapting automatically to confidence.
How does an LLM know when to stop writing?
The vocabulary includes a special End-of-Sequence (<EOS> or <|eot_id|>) token learned during training. Whenever the model predicts and samples <EOS> as the next token, the generation loop halts cleanly.
Why do Large Language Models hallucinate false facts confidently?
Base next-token training optimizes linguistic plausibility rather than looking up verified records in a database. When asked about obscure facts or private data outside its memory, the model smoothly outputs the highest-probability plausible-sounding continuation unless grounded by RAG or search tools.
Should you change BOTH Temperature and Top-P at the same time?
Most LLM API docs recommend tuning one primary dial at a time: for factual/code tasks set temperature = 0 (or 0.2) with default top_p = 1.0, and for creative writing pair moderate temperature (~0.7 to 0.9) with top_p = 0.90 to clip the nonsense tail.

Written & illustrated by Muhammad Aashir Irshad · Updated December 2026 · Free open-access reference

https://seeingml.com/learn/llm-text-generation/ Open GitHub issue Suggest an edit
Cite this guide in a paper, thesis, or course (BibTeX & APA)
BibTeX
@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}
}
APA

Irshad, M. A. (2026). LLM Temperature, Top-K & Top-P Sampling: Interactive Visual Guide. SeeingML. https://seeingml.com/learn/llm-text-generation/