Skip to content
ImagineWorld

Inference

node_idnode-book_llm-systems-engineering_module-06-inference
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num6
chapter_titleInference
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Inference is the process by which a static set of learned weights becomes a responsive generator capable of answering questions and continuing unfinished passages. Understanding how this works requires a careful look at what happens during a single forward pass, how the probability distribution at the output is converted into an actual token, and how that token then feeds back into the model to produce the next one. Each of these steps involves choices that dramatically affect the character, quality, and cost of the generated output. This module completes the mechanics of generation, finishing with the moment the final token is emitted.

Summarizing the process up to this point, when a user submits a prompt to a trained language model, the text is first converted into a sequence of token IDs by the tokenizer. Those IDs are looked up in the embedding matrix to produce a sequence of vectors, each representing the starting point for one token position. The sequence then moves through the full stack of transformer layers, where self-attention and feed-forward sublayers progressively refine the representation at every position. At the final layer, each position holds a vector that summarizes everything the model has inferred about that location in the sequence, conditioned on all the tokens that came before it.

To convert these final-layer vectors into a prediction, the model applies a linear projection known as the language modeling head. This projection maps each position’s vector onto a space whose dimension equals the vocabulary size, producing a raw score called a logit for every possible next token. The softmax function then transforms those logits into a proper probability distribution, assigning a value between zero and one to each token in the vocabulary such that the values sum to one. At the final position in the input, this distribution represents the model’s belief about what token should come next.

flowchart LR
    P["Prompt<br/>&quot;The cat sat&quot;"] --> TK[Tokenizer]
    TK --> TR
    subgraph TR[Transformer]
        direction TB
        L1[Layer 1] ~~~ L2[Layer 2] ~~~ LN[Layer N]
    end
    TR --> LM[LM head] --> SM[Softmax]
    SM --> D[Probability over vocabulary — final position]
Tokenondownquietlytherestill
Probability0.620.230.100.030.02

Figure 1-11. From Prompt to Probability Distribution Over the Vocabulary

This forward pass produces a probability distribution over possible next tokens. The model has no preference mechanism of its own for deciding which token to emit. That decision belongs to the decoding strategy, which is the separate layer of logic that sits between the probability distribution and the actual output token. Two systems built on exactly the same model weights can produce very different generations depending on how this decoding layer is configured, a fact that makes inference behavior as much a matter of policy as of trained capability.

The simplest decoding strategy is greedy decoding, which always selects the token with the highest probability at each step. Greedy decoding is fast and deterministic, and it often produces acceptable output for short, constrained generations such as classification labels or direct factual answers.

Its weakness becomes apparent on longer or more open-ended outputs, where it tends to fall into repetitive loops and produces bland text that exhibits low linguistic diversity (Holtzman et al., 2020).

Beam search offers a more sophisticated alternative. It maintains several candidate sequences in parallel at each step, known as beams, extending each by the most promising continuations and returning the sequence with the highest overall probability at the end of generation. Beam search was originally developed for directed generation tasks such as machine translation, where there is a relatively well-defined correct output for each input. In open-ended generation, however, beam search tends to produce text that is grammatically polished but often repetitive, because high-probability sequences in language models do not correspond to the diverse, surprising phrasings that human writers produce (Holtzman et al., 2020).

Sampling methods take a fundamentally different approach by drawing tokens stochastically from the distribution. Where greedy decoding and beam search look for high-probability sequences, sampling methods accept randomness as part of generation to improve diversity. Pure sampling draws directly from the full distribution, which preserves diversity at the cost of sometimes selecting low-probability tokens that derail coherence. Top-k sampling, introduced by Fan et al. (2018), restricts the draw to the kk most probable tokens at each step, discarding the long tail of unlikely candidates before sampling. This reduces the chance of incoherent selections while retaining useful variability. Nucleus sampling, also called top-p sampling, refines the idea further by truncating the distribution at a cumulative probability threshold pp and sampling from the smallest set of tokens whose combined probability exceeds that threshold (Holtzman et al., 2020). Because the size of this nucleus expands and contracts based on the shape of the distribution at each step, nucleus sampling adapts to the model’s confidence in a way that a fixed kk cannot. The authors of the nucleus sampling paper argued that the tail of a modern language model’s distribution is systematically unreliable, and that truncating it is essential for drawing coherent, human-like text from an otherwise capable model (Holtzman et al., 2020).

Temperature and Controlling Output Behavior

Section titled “Temperature and Controlling Output Behavior”

Temperature is a scalar parameter applied to the logits before the softmax is computed. Dividing the logits by a temperature value below one sharpens the distribution, concentrating probability mass on the most likely tokens and making the model’s output more deterministic. Dividing by a value above 1 flattens the distribution, spreading probability more evenly and encouraging greater diversity in the sampled tokens. A temperature of exactly 1 leaves the original distribution unchanged. In practice, temperatures between roughly 0.7 and 1.0 are common for open-ended generation, while lower values such as 0.2 are used when precise, consistent output is needed. Temperature as a control on generation diversity traces back to early work on sampling from stochastic neural networks (Ackley et al., 1985) and has been applied extensively in modern text generation to shape stylistic properties of output (Ficler & Goldberg, 2017).

When combined with nucleus sampling, lowering the temperature effectively narrows the nucleus by concentrating mass on fewer candidates, which compounds the truncation effect. Raising the temperature has the opposite consequence, pushing more probability into the tail and making the nucleus expand. Teams tuning generation behavior usually adjust these parameters together and observe the joint effect on output quality.

lse-fig-1-12-temperature-distribution.png

Figure 1-12. Effect of Temperature on the Token Probability Distribution

Repetition penalties address a different failure mode. Trained language models sometimes fall into loops in which the same phrase or sentence is generated over and over, particularly under greedy or low-temperature decoding. A repetition penalty modifies the logits of tokens that have already appeared in the generated sequence, reducing their probability so that the model is less likely to select them again. Related techniques such as presence and frequency penalties offer finer control over how strongly recent tokens are discouraged. These interventions are heuristic in character, and excessive penalties can produce unnatural output by forcing the model away from words that are legitimately appropriate to repeat.

The broader point is that the same set of trained weights can produce very different output depending on how the decoding layer is configured. Two users sending identical prompts to identical models can receive dramatically different responses if one uses greedy decoding at low temperature while the other uses nucleus sampling at a higher temperature. Understanding inference behavior therefore requires attention to the trained model as well as to the full set of generation parameters applied at serving time.

Transformer-based language models generate one token at a time because each new prediction depends on every token that came before it, including tokens the model itself has just produced. Once a token is sampled from the distribution at the final position, it is appended to the existing sequence and fed back into the model as input for the next forward pass. The updated sequence produces a new distribution at its new final position, from which the next token is drawn, and the cycle continues until an end-of-sequence token is emitted or a length limit is reached. This pattern is called auto-regressive generation, because each output is regressed on the model’s own prior outputs.

The sequential nature of this loop has important implications for latency and cost. Generating 100 tokens requires 100 forward passes through the model, and there is no way to generate token n+1n+1 before token nn has been produced, because the latter is an input to the former. Unlike training, where many sequences can be processed in parallel, open-ended generation is inherently serial at the token level. This serial dependency means that the time to produce a response scales linearly with the number of tokens emitted, and the per-token latency of the model sets a hard lower bound on how quickly any response can be delivered (Pope et al., 2023).

Naively, each forward pass during generation would require recomputing the attention keys and values for every token in the sequence, including tokens that have not changed since the previous step. Because of the causal structure of attention in decoder-only transformers, the key and value vectors for earlier positions are in fact identical across successive decoding steps. Production systems exploit this by storing those vectors in a data structure called the key-value cache, or KV cache, which persists across forward passes and grows by one entry per token as generation proceeds (Pope et al., 2023). Without the KV cache, the cost of each decoding step would grow with the length of the generated sequence. With it, the incremental cost of producing one additional token remains roughly constant with respect to past computation, and dominated instead by the need to load the model’s weights from memory at each step.

Even with caching, the KV cache itself becomes a significant consumer of memory during long generations. Its size grows with the sequence length and with the cached dimensions accumulated across all the model’s layers. For long contexts and large models, the memory footprint of the cache can rival or exceed that of the model weights themselves, which is why efficient KV cache management has become a central concern in production inference systems (Pope et al., 2023).

Finally, the autoregressive loop creates a feedback property that shapes the character of generated output. Because every sampled token becomes part of the context for all subsequent tokens, a single odd or incorrect selection early in the sequence can steer the rest of the generation down an unhelpful path. The model cannot revise earlier choices once they have been made, and there is no mechanism in standard decoding for backtracking when a mistake becomes apparent. This is part of why the seemingly small choices made at the decoding layer, such as temperature or nucleus size, have such outsized effects on what a trained model actually produces in practice.

This book includes additional resources to support and continue your AI journey. Scan the QR code below (or go to ashford-publishing.com/materials) and enter the book code found at the back of this book.