Slides · LLM foundations

Sampling parameters and the model landscape

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.

Diagram: Logits are divided by the temperature, then filtered by keeping the k highest tokens (top-k) or the smallest set whose cumulative...

top-k

top-p

Logits

Divide by temperature

Filter

Keep k highest tokens

Keep smallest set ≥ p
cumulative probability

Sample

Next token

Diagram summary: Logits are divided by the temperature, then filtered by keeping the k highest tokens (top-k) or the smallest set whose cumulative probability reaches p (top-p). One token is sampled from what remains.

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=exp⁡(zi/T)∑jexp⁡(zj/T)p_i = \frac{\exp(z_i / T)}{\sum_j \exp(z_j / T)}
SymbolMeaning
ziz_iLogit (raw score) for token ii
TTTemperature, a positive number
pip_iProbability of token ii after temperature
∑j\sum_jSum over all candidate tokens jj

Because every logit is divided by the same positive TT, the ranking never changes. Only the spread does.

Worked example

Worked example: logits 2.0, 1.0, 0.0

Illustrative numbers. At T=1T = 1: exp⁡(2)=7.389\exp(2) = 7.389, exp⁡(1)=2.718\exp(1) = 2.718, exp⁡(0)=1\exp(0) = 1, sum =11.107= 11.107, so the probabilities are 0.665, 0.245, 0.090.

TemperatureProbabilities (approx.)
0.50.87, 0.12, 0.02
1.00.67, 0.24, 0.09
2.00.51, 0.31, 0.19

At T=0.5T = 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.

Source1 The Curious Case of Neural Text Degeneration

Worked example

Why top-p adapts

Same p=0.9p = 0.9, two different situations.

Model isProbabilitiesTop-p (p=0.9p = 0.9) keepsTop-k (k=2k = 2) keeps
Sure0.97, 0.02, 0.011 token (0.97 already passes 0.9)2 tokens, including a 2% option
Unsure0.40, 0.35, 0.253 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

TaskLean towardWhy
Extraction, classification, SQL generationLow temperature (0 or near it)You want the most likely answer, repeatably
Brainstorming, marketing copyHigher temperature, or top-p below 1You want variety
Evaluating a prompt changeFixed settings across runsOtherwise 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_p and top_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.

Source2 Claude Sonnet 5.5 migration guide

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

Diagram: Server load changes how many requests are batched together.

Your request

Server batches it with
other requests

Batch size depends on load

Kernel picks a reduction
order by batch size

Floating-point sums differ slightly

A near-tie flips: different token

Different text for the same prompt

Diagram summary: Server load changes how many requests are batched together. Kernels that are not batch-invariant then add numbers in a different order, floating-point results shift slightly, and a close call between two tokens can flip, so the same prompt yields different text.

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.

Source3 Defeating Nondeterminism in LLM Inference

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.

Source3 Defeating Nondeterminism in LLM Inference

Process

What to do about it

  1. Do not promise bit-for-bit repeatability from an API because temperature is 0. A seed, if offered, is best effort unless documented otherwise.
  2. For audit or compliance, store the output that was produced and shown. Do not plan to regenerate it.
  3. Constrain output with a schema, validate it, and retry on failure.
  4. Compare with tolerance: the extracted fields, not the exact prose.
  5. 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

AspectOpen-weightAPI-only
AccessWeights published; you download and run themUsed through the provider’s API
ControlSelf-host, fine-tune, change the stackCannot change weights; the provider can change or retire the model
DataCan stay inside your infrastructureGoes to the provider, under its policies (some offer managed APIs in your own cloud region or account)
Cost shapeGPUs, serving and operationsPer-token billing, no infrastructure
QualityVaries by modelStrongest 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.

Sources4 Introducing Meta Llama 3: The most capable openly available LLM to date5 The Open Source AI Definition - 1.0

Diagram

A decision flow

Diagram: Data residency is the first question, since it can settle the choice alone.

yes

no

no

yes

yes

no

Must data stay inside
your infrastructure?

Open-weight, self-hosted

Do you have a team to run
GPUs and serving?

API-only model

Is the API too slow, costly
or not tunable enough?

Measure quality, cost per request
and p95 latency on your own data

Diagram summary: Data residency is the first question, since it can settle the choice alone. If data may leave, whether you can run GPUs and serving decides next, and cost, latency and tuning needs decide the rest. Either branch ends in the same step: measure on your own examples before committing.

Process

A measurement plan

  1. Pick criteria: quality on your task, cost at your volume, latency, data residency and compliance, and the operations team you have.
  2. Build a small evaluation set from real examples.
  3. Run both options on it with fixed sampling settings.
  4. Compare quality, cost per request and p95 latency.
  5. 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)O(n^2 \cdot 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.

Sources6 Context windows7 Attention Is All You Need8 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.

Sources9 Lost in the Middle: How Language Models Use Long Contexts6 Context windows

Compare

Big window versus retrieval

AspectStuff everything inRetrieve what is relevant
Cost per requestPays for every token each timePays for the selected passages
QualityRelevant text can sit in a weak middle positionPuts selected passages up front
Freshness and scaleResend the whole corpus on every request, and it may outgrow the windowUpdate 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)

  1. The Curious Case of Neural Text Degeneration (opens in a new tab)

    Ari Holtzman, Jan Buys, Li Du, Maxwell Forbes, et al.2019ICLR 2020Paper

    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.

  2. Claude Sonnet 5.5 migration guide (opens in a new tab)

    Anthropic2026Documentation

    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.

  3. Defeating Nondeterminism in LLM Inference (opens in a new tab)

    Horace He2025Article

    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).

  4. Introducing Meta Llama 3: The most capable openly available LLM to date (opens in a new tab)

    Meta AI2024Article

    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.

  5. The Open Source AI Definition - 1.0 (opens in a new tab)

    Open Source Initiative2024Specification

    Used for Open source AI requires more than released weights (data information and code too).

References

References & Sources (2 of 2)

  1. Context windows (opens in a new tab)

    Anthropic2026Documentation

    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.

  2. 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

    Used for Self-attention costs O(n^2 * d) per layer, so work grows with the square of sequence length.

  3. Mastering LLM Techniques: Inference Optimization (opens in a new tab)

    Shashank Verma, Neal Vaidya2023Article

    Used for The KV cache grows linearly with batch size and sequence length.

  4. 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

    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.