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.
| Aspect | Training | Inference |
|---|---|---|
| Main purpose | Learn or adapt model parameters | Use the learned model to process an input |
| Parameter updates | Usually performed through optimization | Normally not performed |
| Typical input | Batches of training examples | A prompt or other model input |
| Computation | Forward pass, loss calculation, backward pass, updates | Primarily forward computation and output selection |
| Output | Updated model parameters | Predictions, 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:
- Prepare the input. Combine relevant instructions, conversation history, retrieved context, and the user’s message according to the model’s expected input format.
- Tokenize. Convert text into token identifiers understood by the model.
- Run a forward pass. Compute output scores for possible next tokens based on the current sequence.
- Convert scores to probabilities. Apply an appropriate normalization, commonly softmax, to obtain a distribution over tokens.
- Decode. Choose the next token using greedy selection, sampling, or another method.
- Extend the sequence. Add the selected token to the generated context and continue.
- Stop. End when a designated stopping condition is met, such as an end-of-sequence token or a token limit.
- Detokenize. Convert the generated tokens into readable output.
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 with logit , the softmax function gives:
where 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 token | Illustrative probability |
|---|---|
cat | 0.50 |
dog | 0.30 |
bird | 0.15 |
fish | 0.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:
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 before applying softmax:
- 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 .
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 highest-scoring tokens and samples among them after renormalizing their probabilities.
With in the example, only cat and dog remain eligible. Their new probabilities become:
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 .
For the same example, with :
catcontributes 0.50.- Adding
dogbrings the cumulative probability to 0.80. birdandfishare 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
| Method | Selection rule | Main benefit | Main trade-off |
|---|---|---|---|
| Greedy | Pick highest-probability token | Simple, little sampling variation | Can get stuck in poor local choices |
| Temperature sampling | Reshape the distribution and sample | Control degree of variation | High settings can increase low-quality output |
| Top-k sampling | Sample among fixed number of leading tokens | Excludes very low-ranking candidates | Fixed count may be too narrow or too broad |
| Top-p sampling | Sample from a probability-mass nucleus | Adapts candidate count to uncertainty | Output still depends on threshold and distribution |
| Beam search | Maintain multiple candidate sequences | Useful for some sequence-generation tasks | More 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
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:
- The model emits an end-of-sequence or end-of-turn token recognized by the serving system.
- A configured maximum output-token limit is reached.
- A supported stop sequence or another application-defined stopping condition is met.
- 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:
| Measure | Meaning |
|---|---|
| Time to first token (TTFT) | Delay before the first generated token becomes available |
| Inter-token latency | Time between successive generated tokens |
| Tokens per second | Output-generation throughput for a request or system |
| End-to-end latency | Total delay until the requested output is complete |
| Throughput | Total work a service completes per unit time |
| Memory use | Memory 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:
- Fix the model version, prompt template, and decoding settings when comparing configurations.
- Use a representative test set rather than judging a method from a few examples.
- Record when outputs are truncated, malformed, or unsupported by evidence.
- Test both ordinary and difficult inputs, including long context and ambiguous prompts.
- Measure latency and cost along with response quality.
- 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.
14. Related concepts and learning path
The following articles establish the concepts behind this topic or explain where they are used:
- Large Language Models: Foundations and Capabilities introduces token prediction and the capabilities and limitations of LLMs.
- The Transformer Architecture explains the neural network components used by many modern LLMs.
- Attention, Self-Attention, and Multi-Head Attention explains how Transformer layers use token representations.
- LLM Pretraining, Fine-Tuning, and Alignment covers how model parameters and behavior are developed before inference.
- Prompt Engineering for AI Applications addresses instructions and input construction.
- Multimodal Artificial Intelligence expands the discussion beyond text-only input and output.
- AI Knowledge Map connects this article with the broader curriculum.
15. Further reading
- Hugging Face Transformers: Text generation strategies — practical decoding strategies and configuration concepts.
- Hugging Face Transformers: Generation configuration — documented generation parameters and stopping behavior.
- The Curious Case of Neural Text Degeneration — research introducing nucleus sampling and discussing text-generation degeneration.
- Attention Is All You Need — foundational Transformer architecture paper.
- Efficient Memory Management for Large Language Model Serving with PagedAttention — KV-cache management and LLM serving performance.
Related articles in
- AI Agents and Tool-Using Workflows — Learn agent goals, tool invocation, planning, state, permissions, and how to evaluate multi-step AI workflows.
- AI Development Tools: Git, Jupyter, and APIs — Learn how Git, Jupyter notebooks, Python environments, and APIs fit together in reproducible, secure artificial intelligence workflows.
- How AI Is Changing Theoretical Computer Science — AI is beginning to help researchers explore algorithms, mathematical structures, and formal proofs. Here is what it can do, what still needs human judgment, and why verification matters.