GNGiseldo Neo and Alana NeoBooks
Language Models with Python11 / 16

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 (wtw_t) given a sequence of previous tokens (w1:t−1w_{1:t-1}).

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.

P(wt∣w1:t−1)=softmax(ht)P(w_t | w_{1:t-1}) = \text{softmax}(h_{t})

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.

The simplest strategy. At each step, the model selects the token with the highest absolute probability.

  • Algorithm: wt=argmax P(w∣w1:t−1)w_t = \text{argmax } P(w | w_{1:t-1})
  • 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

Beam Search mitigates the myopia of Greedy Search by keeping the kk most probable sequences (where kk is num_beams) at each step, instead of just one.

  • How it works:
    1. Generates the distribution for the next step.
    2. Considers all possible extensions of the kk current sequences.
    3. Computes the accumulated probability (score) of each path.
    4. Keeps only the top-kk 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.

Diagram

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.

Pi=exp⁡(zi/T)∑jexp⁡(zj/T)P_i = \frac{\exp(z_i / T)}{\sum_j \exp(z_j / T)}
  • T<1T < 1 (low temperature): Increases the difference between high and low logits. The distribution becomes “peaked”. The model becomes more confident and conservative.
  • T=1T = 1: The model’s original distribution.
  • T>1T > 1 (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 kk tokens with the highest probability.

  1. The vocabulary is sorted by probability.
  2. Only the top-kk tokens are kept.
  3. The remaining probability mass is zeroed out.
  4. The distribution is re-normalized.
  5. A token is sampled from this new distribution.
  • Problem: kk is fixed. If the distribution is flat (many valid words), kk may cut off good options. If it is peaked (few valid words), kk 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 pp (e.g., 0.90.9 or 90%90\%).

  • Dynamics: The size of the candidate set (kk) 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

Diagram

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

StrategyDeterministic?Ideal Use CaseMain Risk
GreedyYesShort, factual answers, math.Repetition, lack of creativity.
Beam SearchYesTranslation, text summarization.Computational cost, repetition.
TemperatureNo (if T ≠\neq 0)Global control of “risk”.High T: hallucination. Low T: repetition.
Top-kNoSimple chatbots.Arbitrary cutoff of valid words.
Top-pNoCreative 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-kk, or top-pp.

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 tt, the model would recompute the keys and values of the previous t−1t-1 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 LL layers, HkvH_{kv} KV heads, dimension dhd_h, length TT, and bb bytes per element, an estimate for one batch item is

bytes≈2LTHkvdhb,\text{bytes}\approx 2LTH_{kv}d_hb,

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 HkvH_{kv}.

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.