Slides · LLM foundations
Sampling parameters and the model landscape
1 / 28
Sampling parameters and the model landscape
Why the same prompt gives different answers, how to steer it, and how to choose a model without guessing.
By the end you can:
- explain temperature, top-k and top-p,
- choose sampling settings for a task,
- explain why temperature 0 is not a guarantee,
- compare open-weight and API-only models,
- explain why a bigger context window is a trade-off.
Concept
The puzzle: three answers in ten minutes
- A customer asks the same question three times. The bot says yes, then no, then yes.
- Is the model broken? No. Choosing the next token involves a decision, and you control how it is made.
- Then a second question: keep this model, or try another one?
Diagram
Where sampling sits
The model outputs logits. Decoding is how you turn them into one token.
Order matters: reshape first, filter second, draw last.
Concept
Greedy decoding and temperature
- Greedy decoding always takes the highest-probability token.
- Temperature divides the logits before softmax.
- Higher temperature: flatter distribution, more randomness.
- Lower temperature: sharper distribution. Near 0, sampling approaches greedy.
Mental model: a confidence dial on the model’s own ranking. It does not make the model smarter or more creative; it changes how often a less likely token is picked.
Math
The temperature formula
pi=∑jexp(zj/T)exp(zi/T)| Symbol | Meaning |
|---|---|
| zi | Logit (raw score) for token i |
| T | Temperature, a positive number |
| pi | Probability of token i after temperature |
| ∑j | Sum over all candidate tokens j |
Because every logit is divided by the same positive T, the ranking never changes. Only the spread does.
Worked example
Worked example: logits 2.0, 1.0, 0.0
Illustrative numbers. At T=1: exp(2)=7.389, exp(1)=2.718, exp(0)=1, sum =11.107, so the probabilities are 0.665, 0.245, 0.090.
| Temperature | Probabilities (approx.) |
|---|---|
| 0.5 | 0.87, 0.12, 0.02 |
| 1.0 | 0.67, 0.24, 0.09 |
| 2.0 | 0.51, 0.31, 0.19 |
At T=0.5 the same logits become 4, 2, 0, which gives 0.867, 0.117, 0.016. Lower temperature piles probability onto the top token. Higher temperature spreads it out.
Concept
Filters: top-k and top-p
- Top-k keeps the k highest-probability tokens, then samples among them.
- Top-p (nucleus sampling) keeps the smallest set whose cumulative probability reaches p, then samples among them.
- The idea behind top-p: cut the unreliable low-probability tail while keeping enough variety.
Libraries can apply both filters together; the diagram shows them as alternatives for clarity. Think of bouncers at a door. Top-k admits a fixed number. Top-p admits candidates until their combined probability is high enough.
Worked example
Why top-p adapts
Same p=0.9, two different situations.
| Model is | Probabilities | Top-p (p=0.9) keeps | Top-k (k=2) keeps |
|---|---|---|---|
| Sure | 0.97, 0.02, 0.01 | 1 token (0.97 already passes 0.9) | 2 tokens, including a 2% option |
| Unsure | 0.40, 0.35, 0.25 | 3 tokens (0.40, 0.75, then 1.00) | 2 tokens, dropping a 25% option |
Top-k cuts the same count in both cases. Top-p lets the cutoff follow the shape of the distribution. That is what “adaptive” means.
Check yourself
Check: temperature and top-p
Logits 2.0, 1.0 and 0.0 give probabilities 0.67, 0.24 and 0.09 at temperature 1.0. You lower the temperature to 0.3. What happens to the lowest-probability token (logit 0.0), and does the ranking change?
Answer
Its probability falls, to about 0.001 (the scaled logits become 6.7, 3.3 and 0, and the top token takes about 0.964). The ranking does not change, because dividing all logits by the same positive number keeps their order. Only the spread changes.
Compare
Choosing settings by task
| Task | Lean toward | Why |
|---|---|---|
| Extraction, classification, SQL generation | Low temperature (0 or near it) | You want the most likely answer, repeatably |
| Brainstorming, marketing copy | Higher temperature, or top-p below 1 | You want variety |
| Evaluating a prompt change | Fixed settings across runs | Otherwise you cannot tell noise from effect |
The cost of low temperature is less variety. The cost of high temperature is more off-target output.
Concept
Two cautions
- Change one knob at a time. Temperature and top-p both reshape the same distribution, so their effects overlap. Change one, measure, then decide.
- Check your provider. Some current models do not let you set these. Anthropic’s Claude Sonnet 5.5 migration guide says to remove
temperature,top_pandtop_k, because sampling parameters return an error on that model (checked 2026-10-22). - Treat sampling controls as model-specific and read the docs for the model you call.
Check yourself
Check: pick the settings
Pick settings for (a) a product tagline and (b) pulling a phone number out of text. Justify each.
Answer
(a) Tagline: higher temperature, or top-p below 1, because variety is the goal and you can pick the best candidate. (b) Extraction: temperature 0 or near it, because you want the most likely answer repeatably. In both cases, change one parameter at a time and fix settings when comparing prompts.
Concept
Temperature 0 is not a guarantee
- In theory, temperature 0 is greedy decoding, so it should be repeatable.
- In practice, hosted inference often returns different text for the same prompt.
- A common explanation blames floating-point math and parallel threads. That is only part of the story.
Diagram
Why it varies: load changes the math
Floating-point addition is not associative, so order changes the result. For a fixed batch, the forward pass is run-to-run deterministic. Your answer depends on who else is on the server.
Worked example
Evidence: 1,000 completions
- With batch-invariant kernels, 1,000 completions of the same prompt came out identical (Thinking Machines Lab, 2025-09-10).
- With the default kernels, the same test produced 80 unique completions out of 1,000 at temperature 0 (Qwen3-235B-A22B-Instruct-2507).
- The cost comes from a separate benchmark in the same post: one GPU, Qwen3-8B, 1,000 sequences of about 90 to 110 output tokens. Default vLLM took 26 seconds, unoptimized deterministic vLLM took 55 seconds, and with an improved attention kernel it took 42 seconds. The author says this is not heavily optimized.
So exact repeatability is possible, but it is an engineering and performance decision, not a free setting.
Process
What to do about it
- Do not promise bit-for-bit repeatability from an API because temperature is 0. A seed, if offered, is best effort unless documented otherwise.
- For audit or compliance, store the output that was produced and shown. Do not plan to regenerate it.
- Constrain output with a schema, validate it, and retry on failure.
- Compare with tolerance: the extracted fields, not the exact prose.
- Need exact repeatability and control the stack? Self-host with batch-invariant kernels, and accept the speed cost.
Check yourself
Check: temperature 0
A compliance team sets temperature 0 and says the model’s answers can be regenerated later for auditors. What is wrong, and what do you build instead?
Answer
Temperature 0 is greedy in principle, but hosted inference can still vary with batching and load, so regeneration may not match. Store the exact output that was shown, validate it against a schema, and compare fields with tolerance.
Compare
Open-weight versus API-only
| Aspect | Open-weight | API-only |
|---|---|---|
| Access | Weights published; you download and run them | Used through the provider’s API |
| Control | Self-host, fine-tune, change the stack | Cannot change weights; the provider can change or retire the model |
| Data | Can stay inside your infrastructure | Goes to the provider, under its policies (some offer managed APIs in your own cloud region or account) |
| Cost shape | GPUs, serving and operations | Per-token billing, no infrastructure |
| Quality | Varies by model | Strongest models are often here |
Example: Meta released Llama 3 8B and 70B (pretrained and instruction-tuned) for download on 2024-04-18. Licenses vary and “open-weight” is not the same as open source: the Open Source Initiative’s definition requires more than the weights, such as data information and code. Read the license.
Sources[4] Introducing Meta Llama 3: The most capable openly available LLM to date[5] The Open Source AI Definition - 1.0
Diagram
A decision flow
Process
A measurement plan
- Pick criteria: quality on your task, cost at your volume, latency, data residency and compliance, and the operations team you have.
- Build a small evaluation set from real examples.
- Run both options on it with fixed sampling settings.
- Compare quality, cost per request and p95 latency.
- Decide, and write down what would make you revisit it.
Neither option is better by default.
Check yourself
Check: 50,000 requests a day
You must choose between a small open-weight model and a frontier API for summarising 50,000 documents a day. Name three criteria and how you would measure.
Answer
Example criteria: summary quality on a sample of your own documents, cost per request at 50,000 a day (API tokens versus GPU and operations cost), and p95 latency. Also consider data residency. Run both on the same evaluation set and compare. The answer comes from the numbers, not from which model is bigger.
Concept
Context windows are not free
- You are billed on tokens in and out, so a longer prompt costs more on every request.
- Everything in the request counts toward the window: system prompt, messages, tool results and definitions, and the model’s own output.
- Self-attention does work that grows with the square of the sequence length (the original Transformer paper lists O(n2⋅d) per layer), and the KV cache grows linearly with sequence length (and batch size). See How LLMs work. Providers optimize this, so measure the cost you actually see instead of assuming a formula.
Sources[6] Context windows[7] Attention Is All You Need[8] Mastering LLM Techniques: Inference Optimization
Concept
More context can mean worse answers
- Liu et al. (2023) found performance is often highest when the relevant information is at the start or end of a long input, and lower when it is in the middle.
- Anthropic’s docs say more context is not automatically better: as token count grows, accuracy and recall degrade, so curating what goes in matters as much as how much fits.
Practical rule: put what matters where the model uses it best, and send less.
Sources[9] Lost in the Middle: How Language Models Use Long Contexts[6] Context windows
Compare
Big window versus retrieval
| Aspect | Stuff everything in | Retrieve what is relevant |
|---|---|---|
| Cost per request | Pays for every token each time | Pays for the selected passages |
| Quality | Relevant text can sit in a weak middle position | Puts selected passages up front |
| Freshness and scale | Resend the whole corpus on every request, and it may outgrow the window | Update the index incrementally and fetch only what is needed |
A 1M-token window does not remove the need for retrieval. More context is not better recall, and it costs more. Retrieval-augmented generation is the subject of later modules.
Check yourself
Check: the interview question
“Why not just use a 1M-token context window instead of RAG?” Give two reasons.
Answer
Cost: you pay for the tokens on every request. Quality: models can use the middle of a long input worse. Also, the corpus may outgrow the window, and retrieval lets you update the index incrementally and control what the model sees.
Summary
Recap
- Temperature reshapes the distribution; top-k and top-p filter it; top-p adapts to how peaked it is.
- Pick low temperature for extraction and classification, higher for generative work, fixed settings when evaluating. Change one knob at a time.
- Temperature 0 is greedy in principle, not guaranteed identical in practice. Store outputs, validate, compare with tolerance.
- Some models do not accept sampling parameters; check the docs.
- Open-weight: control and data locality, plus an operations burden. API-only: convenience and often frontier quality, less control. Measure on your own data.
- A bigger context window costs money and can lower quality. It does not replace retrieval.
References
References & Sources (1 of 2)
The Curious Case of Neural Text Degeneration (opens in a new tab)
Ari Holtzman, Jan Buys, Li Du, Maxwell Forbes, et al.2019ICLR 2020Paper
arXiv 1904.09751 (opens in a new tab)https://arxiv.org/abs/1904.09751
Used for Top-p (nucleus) sampling keeps the smallest set of top-probability tokens whose combined probability passes a threshold, and removes the unreliable low-probability tail.
Claude Sonnet 5.5 migration guide (opens in a new tab)
Anthropic2026Documentation
https://platform.claude.com/docs/en/models/sonnet-5-5/migration-guide
Used for Sampling controls are model-specific: the Claude Sonnet 5.5 guide says temperature, top_p and top_k return an error and should be removed.
Defeating Nondeterminism in LLM Inference (opens in a new tab)
Horace He2025Article
https://thinkingmachines.ai/blog/defeating-nondeterminism-in-llm-inference/
Used for Temperature 0 is not enough for repeatable output: kernels are not batch-invariant, so results depend on server load; batch-invariant kernels made 1,000 completions identical, at a speed cost (26 s default, 55 s deterministic, 42 s with an improved kernel in a separate Qwen-3-8B benchmark).
Introducing Meta Llama 3: The most capable openly available LLM to date (opens in a new tab)
Meta AI2024Article
https://ai.meta.com/blog/meta-llama-3/
Used for Example of an openly available model family: Meta released Llama 3 8B and 70B (pretrained and instruction-tuned) for download in April 2024.
The Open Source AI Definition - 1.0 (opens in a new tab)
Open Source Initiative2024Specification
https://opensource.org/ai/open-source-ai-definition
Used for Open source AI requires more than released weights (data information and code too).
References
References & Sources (2 of 2)
Context windows (opens in a new tab)
Anthropic2026Documentation
https://platform.claude.com/docs/en/build-with-claude/context-windows
Used for A larger context window is not automatically better: accuracy and recall degrade as token count grows, and everything in the request counts toward the window.
Attention Is All You Need (opens in a new tab)
Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, et al.2017Advances in Neural Information Processing Systems 30 (NIPS 2017)Paper
arXiv 1706.03762 (opens in a new tab)https://arxiv.org/abs/1706.03762
Used for Self-attention costs O(n^2 * d) per layer, so work grows with the square of sequence length.
Mastering LLM Techniques: Inference Optimization (opens in a new tab)
Shashank Verma, Neal Vaidya2023Article
https://developer.nvidia.com/blog/mastering-llm-techniques-inference-optimization/
Used for The KV cache grows linearly with batch size and sequence length.
Lost in the Middle: How Language Models Use Long Contexts (opens in a new tab)
Nelson F. Liu, Kevin Lin, John Hewitt, Ashwin Paranjape, et al.2023Transactions of the Association for Computational Linguistics (TACL)Paper
arXiv 2307.03172 (opens in a new tab)https://arxiv.org/abs/2307.03172
Used for Models use long inputs unevenly: performance is often highest when relevant information is at the start or end and lower when it is in the middle.
Keys: ← → move, Home End first and last, F full screen.