Course
AI · Module 01: How LLMs Work Under the HoodTutorial 3 of 21
AI Course·~1.5 hrs

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.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

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?"

1. RAW LOGITS200k unnormalizedscores z_i ∈ (-∞, +∞)2. TEMP SCALEz_i / TT<1 sharpens · T>1 flattens3. SOFTMAXexp(z_i/T) / Σ expProbabilities sum = 1.04. TOP-K / TOP-PPrune low-prob tailRenormalize nucleus5. SAMPLEWeighted rollEmit next token!
Figure: An LLM never outputs "text" directly — it outputs 200,000 raw logits, shapes them with Temperature & Top-P, and rolls a weighted die.

Here is the exact math that converts those raw scores into a chosen word:

  1. Raw Logits (z_i): Unnormalized real numbers from (-∞, +∞), e.g., "WHERE": 6.2, "ORDER": 4.8, "BANANA": -0.4.
  2. Temperature Scaling (z_i / T): Divide every logit by temperature before Softmax:
    • T < 1.0 (e.g. 0.2): Stretches gaps between top logits → sharpens the winner toward 99% confidence.
    • T = 0.0 (Greedy Decoding): Picks argmax(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!
  3. Softmax: Applies p_i = exp(z_i / T) / Σ exp(z_j / T) so all 200,000 probabilities are positive and sum to 1.0 (100%).
  4. 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:

Interactive Softmax, Temperature & Top-P Sampling Lab
Drag sliders to reshape next-token probabilities in real time: p_i = softmax(logit_i / T)
Task Prompt:
Prompt → SELECT user_id, email FROM users [NEXT TOKEN?]
Temperature (T)0.70
0.0 (Deterministic)0.7 (Balanced)1.8 (Chaotic)
Top-P Nucleus Cutoff0.90 (2/6 tokens active)
0.10 (Ultra-strict)0.90 (Safe nucleus)1.00 (Keep risky tail)
WHERElogit=6.2· Standard filter clause
88.1%
ORDERlogit=4.8· Sorting clause
11.9%
LIMITlogit=4.1· Row cap clause
PRUNED BY TOP-P (raw 4.1%)0.0%
JOINlogit=3.3· Table join
PRUNED BY TOP-P (raw 1.3%)0.0%
GROUPlogit=2.1· Valid only with aggregates
PRUNED BY TOP-P (raw 0.2%)0.0%
BANANAlogit=-0.4· Syntax-breaking hallucination!
PRUNED BY TOP-P (raw 0.0%)0.0%
Click "Roll 12×" at T=0.0 vs T=1.5 to watch hallucinations appear!

Try this 15-second experiment in the lab above:

  1. Select SQL Query Generation, set Temperature = 1.65 and Top-P = 1.00, and click Roll 12× — watch "BANANA" or "GROUP" sneak into your SQL query!
  2. Now keep Temperature = 1.65 or drop it to 0.20 and slide Top-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 temperature OR top_p, not both aggressively at the same time. Set temperature to match your task determinism and leave top_p at 1.0 (or 0.95 when T >= 0.8).

WorkloadRecommended temperatureRecommended top_pWhy
JSON Extraction, SQL, Tool Calling, Classification0.01.0One wrong bracket or column name breaks downstream code
RAG Q&A, Code Generation, Technical Summaries0.0 – 0.20.95 – 1.0High factual fidelity while avoiding repetitive loops
Conversational Chatbots & Customer Support0.4 – 0.60.95Natural phrasing without inventing fake refund policies
Brainstorming, Ad Copy, Story Ideation0.8 – 1.00.90 – 0.95Explores 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!

  1. 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 by 0.0001 — enough to flip two tied logits (4.8001 vs 4.8000)!
  2. 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:

Tracing a Hallucination Snowball vs. Grounded Abstention
Interactive LLM Pipeline Tracer · Step 1 of 3 (1. Ungrounded Prompt Hits Knowledge Gap)
Wire Telemetry:in=18 tokout=1 tokcost=$0.00005
1→# ❌ Ungrounded prompt forces guessing:
2→ask("What is BigOSlate's enterprise SLA penalty %?")
3# ✅ Grounded prompt + explicit abstention rule + logprobs:
4ask(context=PRICING_DOC, rule="If absent, output UNKNOWN", logprobs=True)
Top Next-Token Probabilities (Flat Entropy = Guessing!)MAX PROB = 19%!
"10%" (p=0.19)  |  "99.9%" (p=0.17)  |  "5%" (p=0.14)  |  "25%" (p=0.11)
What's Happening: The model has never seen an enterprise SLA doc in its weights. Notice the flat probability distribution (top token is only 19%!) — the model is rolling dice!

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:

SDK:
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)

  1. Passing Both temperature=0.0 AND top_p=0.3 to Anthropic's Newer Models: Recent Claude 4+ endpoints return a 400 invalid_request_error if you specify both temperature and top_p in the same call! Pick temperature and omit top_p unless specifically running nucleus experiments.
  2. Leaving Default temperature=1.0 on SQL / JSON Pipelines: Many SDKs default to temperature=1.0! Everything passes your 5 manual tests on localhost — then at 10,000 daily production requests, a 0.5% tail token fires 50 times a day, emitting invalid JSON keys or hallucinated column names. Explicitly set temperature=0.0 on every structured pipeline.
  3. 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

Q1.Mathematically, what does lowering `temperature` from `1.0` down to `0.1` do before Softmax runs?
Q2.Why is `top_p` (Nucleus Sampling) generally preferred over a fixed `top_k` cutoff for open-ended text?
Q3.Why can setting `temperature=0` on a cloud LLM API still occasionally return slightly different phrasing across runs?
Q4.If a classifier returns `logprob = -0.02` for the token `'BILLING'`, what is its linear probability `exp(-0.02)`?

Keep Exploring: Related Lessons & Tools

All Courses →