Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 6/ 160
01. LLM Fundamentals

Temperature and Top-p

Sampling controls that trade creativity for determinism, plus when to prefer greedy decoding.

BeginnerTemperature · Nucleus Sampling3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

Temperature decides how adventurous the model is when picking the next word, and top-p cuts off the silly options.

Think of it like…

Choosing a restaurant: temperature 0 always picks the top-rated one; a moderate temperature usually picks a highly rated place but sometimes surprises you; a high temperature picks almost at random. Top-p says "only consider the places that together cover 90 percent of my usual choices".

Where you’ve seen it

An invoice-extraction service sets temperature 0 and a JSON schema so the same PDF yields the same fields. The marketing team's tagline generator uses temperature 0.9 and top-p 0.95 to get ten different options per request. Using the extraction settings for taglines produces ten near-identical lines; using tagline settings for extraction occasionally invents a field value.

Words you’ll hear

Temperature
Divides logits before softmax; lower means more deterministic, higher more random.
Top-p (nucleus)
Sample only from the smallest token set whose cumulative probability ≥ p.
Top-k
Sample only from the k most probable tokens.
Greedy decoding
Always choose the highest-probability token (temperature 0).

Visual diagram

Loading interactive diagram

Theory & deep dive

What each knob does

Softmax turns logits z into probabilities proportional to exp(z/T). With T < 1 differences grow, so the best token dominates; with T > 1 they shrink and unlikely tokens get a real chance. T = 0 is implemented as argmax. Because the model's own distribution is already peaked on predictable text, temperature matters most where several continuations are plausible, such as open-ended writing.

Top-p and top-k truncate the tail so rare nonsense tokens can't be drawn. Top-k uses a fixed count, which is too wide when the model is confident and too narrow when it isn't; top-p adapts, keeping one token when the model is sure and many when it isn't. A common default is temperature around 0.7 with top-p 0.9 to 1.0; many providers advise altering one of the two, not both.

Same prompt, different settings

Prompt: "Name a fruit." Temperature 0 returns the same fruit every time. Temperature 1 returns a spread, mostly common fruits. Temperature 1.5 starts returning odd or malformed answers, which is why high values are rarely useful for factual work.

Key takeaway: Temperature reshapes probabilities; top-p and top-k remove the unlikely tail.

Choosing settings, and what temperature 0 doesn't guarantee

Use low temperature (0 to 0.3) for extraction, classification, SQL and code, where one correct answer exists; moderate (0.5 to 0.8) for chat and summarisation; higher for brainstorming, always with a human or filter in the loop. For best-of-n or self-consistency, sample several answers at moderate temperature and vote, which can raise accuracy on reasoning tasks.

Temperature 0 is not a guarantee of identical outputs. Floating-point non-associativity in batched GPU kernels, mixture-of-experts routing and server-side batching can change which token wins when two scores are nearly tied. Some APIs offer a seed for best-effort reproducibility. If you need exact repeatability, cache outputs by input hash rather than relying on the sampler. Some reasoning models fix or ignore these parameters entirely, so check the provider's documentation.

Majority vote for a hard question

Sample 5 answers at temperature 0.7, extract each final answer, and return the most common one. The diversity from temperature lets independent reasoning paths agree on the right answer more often than a single greedy path.

Key takeaway: Low for one right answer, higher for variety; cache if you need exact repeatability.

How it works, step by step

Step 1 of 4
Model

1. Get logits

The final layer outputs a score for each token in the vocabulary.

vocab-sized vector of logits
Key numbers at this step
Vocab
32K – 200K

When to use it & trade-offs

What it is

At each step an LLM produces a probability for every token in its vocabulary, then a sampler picks one. Temperature rescales the logits before softmax: below 1 sharpens the distribution toward the top choice, above 1 flattens it. Top-p (nucleus) sampling keeps only the smallest set of tokens whose probabilities add up to p and samples from those; top-k keeps the k most likely. Greedy decoding (temperature 0) always takes the single most likely token.

Why it matters: These settings are the main dial between predictable and varied output. Extraction, classification and code generation want low variance; brainstorming and creative writing want more. They also affect reliability: high temperature raises hallucination and format-error rates. Knowing what each parameter does, and that temperature 0 is still not perfectly deterministic in practice, avoids wasted tuning.

When to reach for it

  • Temperature 0 with a schema for data extraction
  • Moderate temperature for assistants and summaries
  • Higher temperature plus filtering for ideation

When to avoid or be careful

  • High temperature on factual or structured tasks
  • Tuning temperature and top-p together without measuring
  • Assuming temperature 0 guarantees identical outputs

Decoding strategies

Greedy (temperature 0)
Best for: Extraction, classification, structured output

Strengths: Most consistent; cheapest to reason about.

Watch out: Repetitive on open-ended text; not perfectly deterministic.

Temperature + top-p sampling
Best for: Chat, writing, brainstorming

Strengths: Varied but coherent output.

Watch out: Run-to-run differences; occasional errors.

Sample n and vote (self-consistency)
Best for: Reasoning problems with checkable answers

Strengths: Often improves accuracy.

Watch out: n times the cost.

Interview signals & numbers to know

When this topic comes up

  • “Why does the same prompt give different answers?”
  • “What does temperature do?”
  • “Top-p vs top-k”
  • Deterministic outputs
  • Self-consistency

Benchmarks & rules of thumb

0 -
temperature for greedy-like decoding
0.7 / 0.9 -
a common temperature / top-p starting point
p = 1.0 -
top-p that keeps every token

Common mistakes & follow-ups

Common interview mistakes

  • Raising temperature to fix a wrong answer; it adds randomness rather than knowledge.
  • Expecting byte-identical outputs at temperature 0 across batched or updated servers.
  • Setting both temperature and top-p aggressively low, producing repetitive text.

Likely interviewer follow-ups

  • What's the difference between top-p and top-k?
  • Is temperature 0 fully deterministic?
  • When would you sample several answers and vote?
Interview tip: State the rule of thumb (low for one right answer, higher for variety) and then mention that temperature 0 still isn't guaranteed deterministic. The caveat shows production experience.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Temperature and Top-p with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
KV Cache
Next topic
System Prompts