Artificial Intelligence • Generative AI and Language Models • 15 min read

LLM Inference, Decoding, and Sampling

LLM inference is the process of running a trained large language model on an input to produce predictions or generated output. For a text-generating model, inference usually involves turning the input into tokens, computing probabilities for the next token, selecting a token according to a decoding strategy, and repeating this process until generation stops.

The model’s learned parameters are normally held fixed during inference. The input, context, decoding configuration, and available computing resources determine how the model is used. A different decoding strategy can produce different text from the same underlying model without retraining it.

Start with an example: one prompt, several possible answers

Suppose a model sees the prompt “The capital of France is”. It computes scores for possible next tokens. A decoding rule decides whether to choose the highest-scoring token or sample among plausible alternatives. With a factual question, sampling can introduce errors; for creative writing, some variation can be useful. Decoding changes how predictions are selected, not what the model learned during training.

1. Training versus inference

Training and inference are distinct stages in the lifecycle of a language model.

AspectTrainingInference
Main purposeLearn or adapt model parametersUse the learned model to process an input
Parameter updatesUsually performed through optimizationNormally not performed
Typical inputBatches of training examplesA prompt or other model input
ComputationForward pass, loss calculation, backward pass, updatesPrimarily forward computation and output selection
OutputUpdated model parametersPredictions, token probabilities, or generated content

A model may be pretrained and then fine-tuned before it is deployed. Those procedures are covered in LLM Pretraining, Fine-Tuning, and Alignment. This article concentrates on what happens after a model is ready to generate responses.

2. The text-generation pipeline

A typical autoregressive LLM uses the following process:

  1. Prepare the input. Combine relevant instructions, conversation history, retrieved context, and the user’s message according to the model’s expected input format.
  2. Tokenize. Convert text into token identifiers understood by the model.
  3. Run a forward pass. Compute output scores for possible next tokens based on the current sequence.
  4. Convert scores to probabilities. Apply an appropriate normalization, commonly softmax, to obtain a distribution over tokens.
  5. Decode. Choose the next token using greedy selection, sampling, or another method.
  6. Extend the sequence. Add the selected token to the generated context and continue.
  7. Stop. End when a designated stopping condition is met, such as an end-of-sequence token or a token limit.
  8. Detokenize. Convert the generated tokens into readable output.
Autoregressive language-model inference pipeline, from prompt and tokenization to next-token probabilities, decoding, and repeated generation.
An autoregressive decoder generates output one token at a time. Implementations can reuse intermediate computations to avoid repeating unnecessary work.

Many models produce tokens that do not align with complete words. For example, a word may be represented as one token or several smaller units. Token generation is not the same as word generation.

3. From logits to token probabilities

At a generation step, a language model produces a numerical score, or logit, for each token in its vocabulary. A logit is not itself a probability.

For token ii with logit ziz_i, the softmax function gives:

pi=ezi∑j=1Vezj,p_i = \frac{e^{z_i}}{\sum_{j=1}^{V} e^{z_j}},

where VV is the number of possible tokens. The resulting probabilities are nonnegative and add up to one.

Consider a simplified distribution for the next token after a prompt:

Candidate tokenIllustrative probability
cat0.50
dog0.30
bird0.15
fish0.05

The model assigns the greatest probability to cat, but it does not imply that cat must always be selected. Selection depends on the decoder.

The example uses a four-token vocabulary only for illustration. Real models predict over much larger vocabularies.

4. Greedy decoding

Greedy decoding always selects the token with the highest probability at the current step:

xt=arg max⁡iP(i∣x<t).x_t = \operatorname*{arg\,max}_{i} P(i\mid x_{<t}).

For the example distribution, the greedy decoder selects cat.

Advantages: Greedy decoding is straightforward, reproducible under fixed model and execution conditions, and requires no random token selection.

Limitations: A locally highest-probability token does not guarantee the best complete sequence. Greedy decoding can also produce repetitive or overly predictable text. Furthermore, deterministic token selection does not guarantee identical results across every serving implementation or hardware configuration.

Greedy decoding is often useful when variation is unwanted, but it is not automatically the most accurate choice for every task.

5. Sampling: choosing according to probabilities

Sampling selects a token randomly according to a probability distribution rather than always choosing the highest-probability candidate.

For the four-token example, repeated independent samples would favor cat, but sometimes select dog, bird, or fish. This allows different continuations from the same prompt.

Sampling is not unrestricted randomness: the probabilities still reflect the model’s predictions, and additional controls can alter which tokens are eligible and how heavily they are favored.

5.1 Temperature

Temperature adjusts the sharpness of token probabilities. A common formulation divides logits by temperature TT before applying softmax:

PT(i)=ezi/T∑j=1Vezj/T,T>0.P_T(i)=\frac{e^{z_i/T}}{\sum_{j=1}^{V}e^{z_j/T}}, \qquad T>0.
  • Lower temperature concentrates probability on high-scoring tokens, generally reducing variation.
  • Higher temperature flattens the distribution, generally increasing variation.
  • Temperature 1 preserves the original softmax distribution when no other modifications apply.

At very low temperatures, sampling approaches greedy selection if the highest logit is unique. In some APIs, a temperature setting of 0 is implemented as a special deterministic or near-deterministic decoding mode rather than evaluated directly in the formula, which is undefined at T=0T=0.

Temperature does not directly measure factuality or creativity. Raising it increases the diversity of possible token choices, which may or may not improve the answer.

5.2 Top-k sampling

Top-k sampling keeps only the kk highest-scoring tokens and samples among them after renormalizing their probabilities.

With k=2k=2 in the example, only cat and dog remain eligible. Their new probabilities become:

P(cat)=0.500.50+0.30=0.625,P(\text{cat})=\frac{0.50}{0.50+0.30}=0.625, P(dog)=0.300.50+0.30=0.375.P(\text{dog})=\frac{0.30}{0.50+0.30}=0.375.

Top-k uses a fixed number of candidates even when the model is very confident or very uncertain. This fixed cutoff is its main limitation.

5.3 Top-p (nucleus) sampling

Top-p sampling, also called nucleus sampling, sorts tokens by probability and keeps the smallest leading set whose cumulative probability reaches or exceeds a threshold pp.

For the same example, with p=0.80p=0.80:

  • cat contributes 0.50.
  • Adding dog brings the cumulative probability to 0.80.
  • bird and fish are excluded.

The retained tokens are renormalized before sampling. Unlike top-k, top-p can use different numbers of tokens at different generation steps.

Different implementations may handle exact threshold ties and boundary cases differently. Always check the decoding semantics of the model-serving library or API in use.

6. Comparing decoding methods

MethodSelection ruleMain benefitMain trade-off
GreedyPick highest-probability tokenSimple, little sampling variationCan get stuck in poor local choices
Temperature samplingReshape the distribution and sampleControl degree of variationHigh settings can increase low-quality output
Top-k samplingSample among fixed number of leading tokensExcludes very low-ranking candidatesFixed count may be too narrow or too broad
Top-p samplingSample from a probability-mass nucleusAdapts candidate count to uncertaintyOutput still depends on threshold and distribution
Beam searchMaintain multiple candidate sequencesUseful for some sequence-generation tasksMore computation; not always better for open-ended chat

These techniques are not always alternatives. Temperature can be combined with top-k or top-p, depending on the implementation. A decoding configuration is part of the complete system’s behavior, not a replacement for model quality or evaluation.

Beam search retains multiple partial sequences during generation. At each step it expands candidate continuations and keeps a selected number of the highest-scoring sequences, often with length-related adjustments.

Beam search can be useful in some constrained generation settings, but it increases computational work and can favor generic or repetitive text if the scoring design is unsuitable. It is less commonly the default for open-ended conversational generation than sampling-based methods.

7. A Python demonstration of decoding

The following NumPy example uses fixed logits to demonstrate how temperature and top-k sampling work. It does not call or train a real language model; it isolates the token-selection step so the behavior is easier to inspect.

import numpy as np

vocabulary = np.array(["cat", "dog", "bird", "fish"])
logits = np.log(np.array([0.50, 0.30, 0.15, 0.05]))
rng = np.random.default_rng(42)


def softmax(values):
    shifted = values - np.max(values)
    exp_values = np.exp(shifted)
    return exp_values / exp_values.sum()


def sample_with_temperature(values, temperature, generator):
    if temperature <= 0:
        raise ValueError("temperature must be positive")
    probabilities = softmax(values / temperature)
    index = generator.choice(len(values), p=probabilities)
    return vocabulary[index], probabilities


def sample_top_k(values, k, generator):
    if not 1 <= k <= len(values):
        raise ValueError("k must be between 1 and vocabulary size")

    candidate_ids = np.argsort(values)[-k:]
    candidate_probabilities = softmax(values[candidate_ids])
    chosen_id = generator.choice(candidate_ids, p=candidate_probabilities)
    return vocabulary[chosen_id]


print("Greedy:", vocabulary[np.argmax(logits)])

for temperature in (0.5, 1.0, 2.0):
    token, distribution = sample_with_temperature(
        logits, temperature, rng
    )
    print(f"Temperature {temperature}: {token}")
    print(np.round(distribution, 3))

print("Top-k sample (k=2):", sample_top_k(logits, 2, rng))

The exact sampled tokens depend on the random-number generator and its state. More importantly, the resulting probability distributions reveal what the decoding settings actually change. At lower temperatures, the largest probability becomes more dominant; at higher temperatures, the smaller probabilities increase.

Note: A seeded pseudo-random generator makes this demonstration reproducible within a compatible environment. Real LLM services can have additional sources of variability, including parallel execution and provider-level implementation changes.

8. The role of context during inference

A model predicts output based on the context made available to it. This can include:

  • System or developer instructions supplied by the application.
  • The current user request and relevant conversation history.
  • Retrieved documents or search results.
  • Tool outputs and structured data.
  • Already-generated output tokens.

The context window is the model’s supported capacity for input and, depending on the architecture and provider, generated tokens as well. When the available context is too long, an application must manage the input through truncation, summarization, retrieval, or another strategy.

A larger context window does not guarantee that every detail will be used correctly. Context quality, ordering, relevance, and prompt construction influence the result.

Prefill refers to the initial computation over the provided prompt tokens in many autoregressive serving systems. Decode then refers to producing new tokens, often step by step. These are two computational phases of inference, distinct from the general meaning of decoding strategy as a token-selection rule.

9. Stopping generation and controlling output length

Generation usually ends when one of the following occurs:

  1. The model emits an end-of-sequence or end-of-turn token recognized by the serving system.
  2. A configured maximum output-token limit is reached.
  3. A supported stop sequence or another application-defined stopping condition is met.
  4. The serving system terminates generation due to a resource, safety, or runtime condition.

A token limit constrains output length but does not guarantee a complete answer. If generation is cut off mid-response, the application should handle that condition rather than assuming the output is finished.

Structured-output generation may also use constrained decoding, validators, or schema-aware generation mechanisms. These are application or serving techniques layered on top of the model’s token predictions.

10. Inference performance and cost

Generating a response requires computation, memory, and data movement. Important performance measures include:

MeasureMeaning
Time to first token (TTFT)Delay before the first generated token becomes available
Inter-token latencyTime between successive generated tokens
Tokens per secondOutput-generation throughput for a request or system
End-to-end latencyTotal delay until the requested output is complete
ThroughputTotal work a service completes per unit time
Memory useMemory required for model weights, intermediate states, and cached attention data

Performance depends on model architecture, size, hardware, numerical precision, input length, output length, concurrency, and the inference implementation.

10.1 KV caching

In a Transformer decoder, attention uses keys and values derived from earlier tokens. A key-value (KV) cache stores these intermediate representations so the model does not need to recompute all prior key and value projections for each generated token.

This can significantly reduce repeated work during autoregressive decoding, but the cache consumes memory that generally grows with context length and the number of concurrent sequences. Cache behavior differs across architectures, especially models with different attention configurations.

10.2 Batching and continuous batching

Batching groups multiple inputs for processing. In serving systems, continuous batching can dynamically add or remove requests as their generation progresses. This improves resource utilization under many workloads, but scheduling and memory-management trade-offs remain.

10.3 Quantization

Quantization represents some model values with lower numerical precision, such as reduced-bit weights. It can reduce memory requirements and improve some inference workloads. Quantization can also introduce approximation error, and performance benefits depend on software and hardware support.

These subjects are part of AI Application Architecture in the wider learning map.

11. Prompt settings versus decoding settings

A common engineering mistake is to treat prompts and decoding controls as if they perform the same function.

Prompt design specifies the task, context, requirements, and desired output characteristics. Decoding controls determine how token predictions are turned into a particular sequence.

For example:

  • A prompt can ask for a JSON object with specified fields.
  • Low-temperature sampling may reduce variation but does not guarantee valid JSON.
  • Schema validation or constrained generation can improve structural compliance.
  • Reliable factual answers still require suitable evidence, evaluation, and handling of uncertainty.

Changing sampling parameters cannot compensate for missing knowledge or poorly defined requirements. Conversely, even a well-written prompt does not eliminate the effects of model limitations or system-level execution.

12. Reliability, reproducibility, and evaluation

LLM outputs should be evaluated for the task they are intended to perform. Relevant dimensions include factual accuracy, relevance, instruction following, completeness, consistency, latency, cost, and safety.

Useful practices include:

  1. Fix the model version, prompt template, and decoding settings when comparing configurations.
  2. Use a representative test set rather than judging a method from a few examples.
  3. Record when outputs are truncated, malformed, or unsupported by evidence.
  4. Test both ordinary and difficult inputs, including long context and ambiguous prompts.
  5. Measure latency and cost along with response quality.
  6. Re-evaluate after model, serving, or prompt changes.

Deterministic-looking generation is not the same as correctness. Greedy selection can produce a stable false statement; random sampling can sometimes produce a correct one. Accuracy must be assessed against appropriate references and task requirements.

13. Common misconceptions

“The model searches its training data for the next sentence.” In ordinary autoregressive inference, the model computes token predictions from its learned parameters and context. Retrieval from external material is a separate mechanism that an application may integrate.

“Temperature changes how much the model knows.” Temperature changes selection probabilities during decoding. It does not alter the model’s learned knowledge or weights.

“A lower temperature guarantees truth.” Lower temperature generally reduces variation, not factual error.

“Top-p is the probability of a token being correct.” The top-p threshold controls cumulative candidate probability mass. It does not represent an accuracy guarantee.

“Generating 100 tokens takes the same time as generating 10.” Output length usually affects decoding time and resource consumption, although batching, caching, and implementation details complicate the relationship.

“Inference is just one forward pass.” A single-token prediction involves a forward computation, but autoregressive text generation commonly requires many successive decoding steps.

The following articles establish the concepts behind this topic or explain where they are used:

15. Further reading

Related articles in

Image preview

Fit