Inference Strategies and Text Generation
Development of text generation methods, exploring Greedy Search, Beam Search, Top-k sampling, Top-p (nucleus) sampling, and temperature.
This chapter details the fundamental mechanisms by which Large Language Models (LLMs) turn statistical probabilities into coherent text. Inference in autoregressive models involves predicting the next token () given a sequence of previous tokens ().
Although the model provides a probability distribution over the entire vocabulary (the logits), the choice of which token to select — the decoding strategy — determines the creativity, coherence, and quality of the generated text.
11.1 The Autoregressive Process
Before exploring the strategies, it is crucial to understand the data flow. The model receives a context, processes it through attention layers, and the final layer projects the hidden state to the vocabulary size. A softmax function converts these raw values (logits) into probabilities.
The decoding strategy steps in exactly after the logits are generated and before (or during) the final selection of the token.
The process continues until an end token, a length limit, or another stopping criterion. The context window limits how many tokens can take part in the computation; when the prompt and the generation exceed this limit, the system must truncate, summarize, or retrieve only the relevant information.
In terms of performance, separate prefill from decode. Prefill processes the prompt in parallel and fills the key-value cache. Decode generates tokens sequentially and reuses this cache. For this reason, time to first token and tokens per second measure distinct aspects of the experience.
11.2 Deterministic Methods
Deterministic methods always produce the same output for the same input, focusing on maximizing probability.
11.2.1 Greedy Search
The simplest strategy. At each step, the model selects the token with the highest absolute probability.
- Algorithm:
- Advantages: Computationally efficient; good for tasks that require exact answers (arithmetic, short translation).
- Disadvantages: Tends to generate repetitive and generic text. It suffers from “myopia”: it chooses the best token now, but may lead to a probabilistic “dead end” later.
# Simplified Greedy Search example
import torch
def greedy_decode(model, input_ids, max_length):
for _ in range(max_length):
outputs = model(input_ids)
next_token_logits = outputs.logits[:, -1, :]
# Selects the index with the highest value
next_token = torch.argmax(next_token_logits, dim=-1).unsqueeze(0)
input_ids = torch.cat([input_ids, next_token], dim=1)
return input_ids
11.2.2 Beam Search
Beam Search mitigates the myopia of Greedy Search by keeping the most probable sequences (where is num_beams) at each step, instead of just one.
- How it works:
- Generates the distribution for the next step.
- Considers all possible extensions of the current sequences.
- Computes the accumulated probability (score) of each path.
- Keeps only the top- sequences for the next step.
- Advantages: Generates more coherent and grammatically correct text than Greedy.
- Disadvantages: Computationally more expensive. It can still suffer from repetition in long texts.
Flow Diagram: Greedy vs Beam Search

11.3 Stochastic Methods (Sampling)
For creative text generation (chatbots, stories), maximizing probability is undesirable, since human language is not strictly predictable. Stochastic methods introduce controlled randomness.
11.3.1 Temperature
Temperature is a hyperparameter that scales the logits before the softmax is applied.
- (low temperature): Increases the difference between high and low logits. The distribution becomes “peaked”. The model becomes more confident and conservative.
- : The model’s original distribution.
- (high temperature): Flattens the distribution. Less probable tokens gain a chance of being chosen. It increases creativity, but also the risk of hallucination or incoherence.
11.3.2 Top-k Sampling
Instead of sampling from the whole vocabulary (which can have 50,000+ tokens), we limit sampling to the tokens with the highest probability.
- The vocabulary is sorted by probability.
- Only the top- tokens are kept.
- The remaining probability mass is zeroed out.
- The distribution is re-normalized.
- A token is sampled from this new distribution.
- Problem: is fixed. If the distribution is flat (many valid words), may cut off good options. If it is peaked (few valid words), may include nonsensical words.
11.3.3 Top-p (Nucleus) Sampling
Introduced to address the rigidity of Top-k. Instead of a fixed number of tokens, we select the smallest set of tokens whose cumulative probability exceeds a threshold (e.g., or ).
- Dynamics: The size of the candidate set () varies dynamically at each step.
- If the model is uncertain (flat distribution), many tokens are needed to add up to 90%, increasing variety.
- If the model is certain (peaked distribution), few tokens add up to 90%, reducing the risk of errors.
Visual Comparison: Top-k vs Top-p

11.4 Comparative Summary and Implementation
Most modern systems use a combination of these strategies (e.g., Top-k followed by Top-p, with adjusted temperature).
| Strategy | Deterministic? | Ideal Use Case | Main Risk |
|---|---|---|---|
| Greedy | Yes | Short, factual answers, math. | Repetition, lack of creativity. |
| Beam Search | Yes | Translation, text summarization. | Computational cost, repetition. |
| Temperature | No (if T 0) | Global control of “risk”. | High T: hallucination. Low T: repetition. |
| Top-k | No | Simple chatbots. | Arbitrary cutoff of valid words. |
| Top-p | No | Creative writing, human-like dialogue. | Unpredictability in technical contexts. |
11.4.1 Generation Configuration Example (Hugging Face Transformers)
# Typical configuration for a creative but coherent chatbot
generation_config = {
"max_new_tokens": 200,
"do_sample": True, # Enables stochastic methods
"temperature": 0.7, # Balance between focus and creativity
"top_k": 50, # Limits the long tail of improbable tokens
"top_p": 0.95, # Nucleus sampling for dynamic adaptation
"repetition_penalty": 1.2 # Penalizes repetition of already generated tokens
}
# model.generate(**inputs, **generation_config)
11.5 Stopping Criteria and Evaluation
A generation needs explicit conditions: end token, limit on new tokens, and, in structured applications, stop sequences. The limit should count only new tokens when the prompt length varies. Repetition penalties can help, but high values also distort names, code, and terms that need to reappear.
There is no universally best configuration. Compare strategies on the representative set for the application and measure correctness, diversity, latency, and the rate of invalid responses. For factual generation, verification against sources may matter more than any temperature adjustment.
Controlled experiment
Fix the prompt and seed, vary a single parameter at a time, and record the distribution before and after the filter. This makes visible whether the change came from temperature, top-, or top-.
Techniques such as speculative decoding use a smaller model to propose several tokens and the main model to verify them. When the proposals are frequently accepted, latency decreases without changing the final distribution produced by the main model.
11.6 Key-Value Cache
Without a cache, when generating token , the model would recompute the keys and values of the previous tokens in all layers. The KV cache stores these tensors. The new query is compared with the stored keys, and only the new key-value pair is appended.
For layers, KV heads, dimension , length , and bytes per element, an estimate for one batch item is
where the factor 2 represents keys and values. The formula explains why long contexts and concurrent batches put pressure on memory, and why GQA reduces the cache by decreasing .
The cache speeds up decoding, but does not remove its sequential dependency. It also must not be reused between incompatible prompts: positions, masks, and tokens must exactly match the stored prefix.
11.7 Quantization in Inference
To quantize is to represent weights or activations with fewer bits. An FP32 weight takes four bytes; in int8, roughly one byte, before scale metadata. In symmetric quantization, an interval centered on zero is mapped to integers. In asymmetric quantization, a zero point makes it possible to represent shifted intervals.
PTQ quantizes an already trained model using calibration; QAT simulates quantization during training to adapt the weights. Reducing bits saves memory and may speed up compatible kernels, but introduces rounding error. Sensitive layers may remain in higher precision.
Evaluate the system, not just the size
Compare perplexity or tasks, tokens per second, time to first token, and memory. A smaller file does not guarantee speedup if the hardware must dequantize values or lacks suitable kernels.