1.3 Temperature, Top-P, Logits & Why LLMs Hallucinate
Play with live Temperature and Top-P sliders to watch softmax probability bars reshape in real time, learn why even T=0 isn't 100% deterministic, and understand the math behind hallucinations.
1. From Final Hidden Vector to Next Token (The 5-Stage Funnel)
A common misconception is that an LLM "thinks up a whole paragraph" and then types it out. It doesn't! At every single decode step, the final Transformer layer outputs one raw score (logit) for every token in its ~200,000-token vocabulary — answering just one question: "Given the sequence so far, how plausible is each next token?"
Here is the exact math that converts those raw scores into a chosen word:
- Raw Logits (
z_i): Unnormalized real numbers from(-∞, +∞), e.g.,"WHERE": 6.2,"ORDER": 4.8,"BANANA": -0.4. - Temperature Scaling (
z_i / T): Divide every logit bytemperaturebefore Softmax:T < 1.0(e.g.0.2): Stretches gaps between top logits → sharpens the winner toward99%confidence.T = 0.0(Greedy Decoding): Picksargmax(z_i)directly — highest-scoring token wins every time.T > 1.0(e.g.1.4): Compresses gaps between logits → flattens the distribution so rare, risky tail tokens suddenly get a real chance to be rolled!
- Softmax: Applies
p_i = exp(z_i / T) / Σ exp(z_j / T)so all 200,000 probabilities are positive and sum to1.0(100%). - Top-K & Top-P (Nucleus) Pruning:
top_k = 40: Keeps only the 40 highest-probability tokens. (Weakness: 40 is too wide when 1 answer is obvious, and too narrow when 100 adjectives are equally great!)top_p = 0.90(Adaptive Nucleus): Sorts tokens from highest to lowest probability and keeps the smallest prefix whose probabilities sum to>= 90%, pruning the long tail of 199,990 bizarre tokens ("BANANA", syntax errors) and renormalizing the survivors!
2. Hands-On Lab: Reshape Probabilities & Watch Hallucinations Happen
Drag Temperature and Top-P below, switch between SQL Query Generation and Creative Product Copy, and click Roll 12× to see the exact moment syntax-breaking hallucinations sneak through:
Try this 15-second experiment in the lab above:
- Select SQL Query Generation, set
Temperature = 1.65andTop-P = 1.00, and click Roll 12× — watch"BANANA"or"GROUP"sneak into your SQL query! - Now keep
Temperature = 1.65or drop it to0.20and slideTop-P = 0.85— notice"BANANA"gets PRUNED BY TOP-P and can never be sampled!
3. Production Sampling Cheat Sheet (What Senior AI Engineers Set)
Golden API Rule: OpenAI and Anthropic docs explicitly advise tuning
temperatureORtop_p, not both aggressively at the same time. Settemperatureto match your task determinism and leavetop_pat1.0(or0.95whenT >= 0.8).
| Workload | Recommended temperature | Recommended top_p | Why |
|---|---|---|---|
| JSON Extraction, SQL, Tool Calling, Classification | 0.0 | 1.0 | One wrong bracket or column name breaks downstream code |
| RAG Q&A, Code Generation, Technical Summaries | 0.0 – 0.2 | 0.95 – 1.0 | High factual fidelity while avoiding repetitive loops |
| Conversational Chatbots & Customer Support | 0.4 – 0.6 | 0.95 | Natural phrasing without inventing fake refund policies |
| Brainstorming, Ad Copy, Story Ideation | 0.8 – 1.0 | 0.90 – 0.95 | Explores fresh vocabulary while top_p cuts gibberish tail |
(Note: Reasoning models like OpenAI o3/o4-mini or Claude Extended Thinking lock or manage temperature internally so their multi-step search trajectories stay calibrated.)
Surprising Fact: Why Even temperature = 0 Isn't 100% Identical Every Time!
Have you ever set temperature=0 (and even seed=42) and still seen 1 word flip once every 20 calls? That is not a bug in your code!
- GPU Floating-Point Non-Associativity: In IEEE-754 float16/bfloat16 math,
(a + b) + c != a + (b + c). Dynamic cloud batching groups your prompt with different neighbors depending on server load, changing matrix-reduction order by0.0001— enough to flip two tied logits (4.8001vs4.8000)! - Sparse Mixture-of-Experts (MoE) Routing: Frontier MoE models enforce per-expert capacity buffers across batches; if an expert queue is full under heavy traffic, a token routes to a backup expert.
Takeaway: Never write unit tests with assert llm_output == "exact string". Assert on parsed Pydantic/JSON schemas and semantic/rubric evals!
4. Why LLMs Hallucinate Mathematically (The Snowball Effect)
LLMs are trained via Next-Token Cross-Entropy Loss — they are rewarded for producing plausible-sounding continuations, not for saying "I don't know" (unless post-trained via RLHF to abstain).
Worse, once a single low-probability fabricated token slips into the output (say, inventing "RFC 9942"), autoregressive self-conditioning appends "RFC 9942" to the prompt for Step t+1! On the very next token, the model sees "According to RFC 9942," in its own context and dutifully invents a convincing title, author, and year to stay coherent!
5. Interactive Trace: Catching Low-Confidence Hallucinations with logprobs
Click Next to see how an ungrounded prompt snowballs into a confident hallucination — and how Grounding + Escape Hatches + logprobs stop it cold:
"10%" (p=0.19) | "99.9%" (p=0.17) | "5%" (p=0.14) | "25%" (p=0.11)
6. Production SDK Code: Deterministic Configs & Inspecting logprobs
Here is how to lock down sampling parameters for deterministic backend tasks — and inspect token-level logprobs (prob = math.exp(logprob)) for ultra-fast confidence routing:
import math
from openai import OpenAI
client = OpenAI()
# Classify a support ticket AND read exact mathematical confidence from logprobs!
resp = client.chat.completions.create(
model="gpt-4o-mini",
temperature=0.0,
max_tokens=3,
logprobs=True,
top_logprobs=3,
messages=[
{"role": "system", "content": "Classify ticket into ONE token: BILLING, BUG, or AUTH."},
{"role": "user", "content": "My 2FA TOTP code keeps saying invalid after reset."},
],
)
first_tok = resp.choices[0].logprobs.content[0]
confidence = math.exp(first_tok.logprob)
print(f"Label: {first_tok.token} | Confidence: {confidence:.1%}")
# If confidence < 80%, route to human triage or frontier reasoning model!7. What Breaks in Production (War Stories)
- Passing Both
temperature=0.0ANDtop_p=0.3to Anthropic's Newer Models: Recent Claude 4+ endpoints return a400 invalid_request_errorif you specify bothtemperatureandtop_pin the same call! Picktemperatureand omittop_punless specifically running nucleus experiments. - Leaving Default
temperature=1.0on SQL / JSON Pipelines: Many SDKs default totemperature=1.0! Everything passes your 5 manual tests on localhost — then at10,000daily production requests, a0.5%tail token fires 50 times a day, emitting invalid JSON keys or hallucinated column names. Explicitly settemperature=0.0on every structured pipeline. - No Abstention Path ("Forced Guessing"): If your system prompt says "Always answer the customer's question helpfully" without an explicit
"If not found in <context>, reply..."branch, you mathematically force the model to hallucinate whenever retrieval misses!
Module 1.3 Mastery Check — Sampling, Logits & Hallucinations
Keep Exploring: Related Lessons & Tools
All Courses →Compare two versions of text, source code, config files, or JSON payloads side-by-side using exact LCS diffing with recursive JSON key sorting and patch export.
Convert Unix epoch seconds/milliseconds to ISO-8601 and local timezones, and bulk-generate UUID v4, time-ordered UUID v7, and sortable ULIDs.