ELLMEngineering Large
Language Models
Download PDF

Chapter 01

The Model and the System

On this page

A decoder-only language model maps integer token IDs to vocabulary logits. Serving adds a sampling loop and persistent attention state. This chapter follows the tensors through one request and calculates the storage required by its weights and cache.

Specify the forward interface

Let B be batch size, S input length, D hidden width, and V vocabulary size. Tokenization produces an integer tensor input_ids[B,S]. An embedding table E[V,D] maps those IDs to X[B,S,D]. Transformer layers preserve the hidden width while mixing information across allowed positions. A final normalization and vocabulary projection produce logits.

Operation Input Output
Embedding lookup IDs [B,S], table [V,D] Hidden states [B,S,D]
Transformer stack Hidden states, positions, attention mask Hidden states [B,S,D]
Vocabulary projection Hidden states, matrix [D,V] Logits [B,S,V]
Next-token selection Last-position logits [B,V] Selected IDs [B,1]
One request through prefill and the next decode call. Shapes omit the batch axis. Prefill emits the first token distribution; feeding that selected token grows the retained KV prefix by one.
Open full diagram ↗

One request through prefill and the next decode call. Shapes omit the batch axis. Prefill emits the first token distribution; feeding that selected token grows the retained KV prefix by one.

For an unpadded prompt, its last position supplies the first generated-token distribution. With unequal padded inputs, gather the last valid position for each sequence according to the runtime's padding convention. Using the last array column indiscriminately can select logits for padding.

The full [B,S,V] logit tensor is useful for training but often unnecessary for prefill in serving. With B=1, S=2048, and V=32768, it contains 67,108,864 values: 128 MiB at two bytes per value. Projecting only the final hidden position reduces the output tensor to 64 KiB. The transformer still processes the prompt positions needed to build context and cache.

Convert logits into a selected token

The model returns scores, not token IDs. For positive temperature T, divide logits by T and apply softmax. A numerically stable implementation subtracts the maximum score before exponentiation:

2026-10-12T12:02:54.803762 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

z is the vocabulary-logit vector; T controls the sampling distribution.

For logits [2,1,0] at T=1, the probabilities are approximately [0.6652,0.2447,0.0900]. Greedy selection returns the first token. Categorical sampling can return any of the three. Top-k and top-p filtering remove candidates and renormalize the remaining mass; they therefore change the distribution. Greedy decoding should use an explicit argmax branch rather than division by zero at T=0.

Example status: Runnable Python reference; computes a stable distribution without external dependencies.

import math

logits = [2.0, 1.0, 0.0]
temperature = 1.0
peak = max(logits)
weights = [math.exp((z - peak) / temperature) for z in logits]
probabilities = [w / sum(weights) for w in weights]
assert abs(sum(probabilities) - 1.0) < 1e-12
assert max(range(len(logits)), key=logits.__getitem__) == 0

A token probability is conditional on the encoded prefix. It does not measure whether a complete answer is factually correct. The numerical interface supports likelihood evaluation; source verification or execution of generated code requires additional computation outside this forward pass.

Prefill and decode use different tensor shapes

Prefill processes all S prompt positions together under a causal mask. Position t can read positions through t, but cannot read later ones. This builds attention keys and values for the prompt and yields the first output distribution. Decode then processes a selected token at its next position, attending to the cached prefix and appending its own keys and values.

Example status: Explanatory pseudocode; forward and select_token are runtime-specific interfaces, and the loop illustrates one unbatched request.

logits, cache = forward(prompt_ids, positions=0..S-1)
output = []
for step in range(max_new_tokens):
    token = select_token(logits.last_valid_position)
    output.append(token)
    if token == EOS or step + 1 == max_new_tokens:
        break
    logits, cache = forward([token], positions=[S + step], cache=cache)

Producing N tokens uses one prefill and N-1 single-token forward calls in this loop. The first selected token comes from prefill. The last selected token need not be forwarded unless generation continues or its state is required later. Off-by-one mistakes here distort latency accounting and cache-length estimates.

Within one attention layer, queries have shape [B,H_q,S,d_h] during prefill and [B,H_q,1,d_h] during single-token decode. Cached keys and values each have shape [B,H_kv,C,d_h], where C is the retained prefix length. Grouped-query attention uses fewer KV heads than query heads and maps groups of queries to shared KV heads. The next transformer chapter derives these operations.

Account for persistent and temporary memory

Weights persist across requests. Token IDs, activations, and KV state belong to request execution. A dense model with P parameters stored at b_w bytes each requires P*b_w bytes for parameter payload, before allocator overhead, quantization metadata, temporary workspace, and request state. A 7-billion-parameter model at two bytes per parameter requires 14 GB, approximately 13.04 GiB.

For L layers and uniform cached lengths, the KV payload is:

2026-10-12T12:02:54.820719 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

The factor two counts keys and values; b_kv is bytes per stored scalar.

With L=32, B=1, C=4096, H_kv=8, d_h=128, and b_kv=2, this is 536,870,912 bytes, or 512 MiB. Chapter 5 generalizes this per-request calculation to different retention and head-sharing policies; Chapter 6 combines it with concurrent requests and workspace. Paged allocation, unequal sequence lengths, sliding windows, and sharding change the actual worker allocation; the formula describes a fully retained, unsharded payload.

Caching avoids recomputing old keys and values. It does not remove the need for each new query to attend to the retained keys. For full attention, that part of decode work grows with C. Weights can stay fixed while long sequences exhaust memory or increase per-token latency.

Training changes the execution contract

Training supplies known tokens and shifted targets so many next-token predictions can run in parallel. It computes cross entropy at selected target positions, backpropagates through the forward graph, and updates weights. Inference performs forward computation with fixed weights and ordinarily retains no gradient graph. Training also requires gradients, optimizer state, and backward activations; inference weight storage alone cannot predict training memory.

A cache is valid only for the computation that produced it: weights, adapter, token prefix, positions, and attention semantics must remain compatible. Changing an early prompt token can change later hidden states and their KV entries. Prefix-cache reuse therefore needs an exact compatible prefix, not semantic similarity between two prompts.

At the application boundary, log the tokenized length and generation settings alongside the model/tokenizer revision. A chat template inserts role and boundary tokens before the forward pass; retrieval contributes additional input tokens; a tool call is generated output interpreted by a dispatcher. These operations affect the actual sequence and control flow, but none substitutes for the numerical forward function.

Transformer architecture does not require autoregressive generation

A transformer specifies how vectors interact. The training objective and sampling procedure specify what those vectors represent and how output is generated. A causal language decoder predicts the next discrete token. A masked language denoiser predicts corrupted positions. A diffusion transformer can process noisy continuous image latents, and a flow-matching model can predict a velocity field over those latents. Their attention masks, output heads, and reusable state differ.

Part VII's “Diffusion Transformers, Flow Matching, and Parallel Generation” chapter develops diffusion transformers and flow matching before returning to discrete text denoising. For now, keep the three choices separate: representation, network architecture, and generation procedure. The tokenizer and transformer chapters next derive the autoregressive path used throughout the serving chapters.

Exercises and worked answers

  1. How much storage does [2,1024,32768] require at two bytes per logit? 134,217,728 bytes, or 128 MiB. Selecting only the final valid position before projection reduces the output to [2,32768], or 128 KiB.
  2. How many single-token forward calls follow prefill to emit 20 tokens in the shown loop? Nineteen. Prefill provides the first distribution; the final token is not forwarded.
  3. What happens to the example KV payload when context doubles? It grows from 512 MiB to 1 GiB per request, assuming every position remains cached.
  4. Can a changed system prompt reuse all previously cached KV? Only the unchanged compatible prefix can be reused. Later entries may depend on the changed token through attention.
  5. Does replacing a causal mask with bidirectional attention turn a pretrained decoder into a diffusion model? No. The corruption objective, output interpretation, and generation schedule also require appropriate training and implementation.