Part III / Inference Engineering

One request, two phases

The transformer call looks like one operation from an API. The serving engine sees two different workloads: read the prompt in parallel, then generate one token per active sequence.

12
Prefill

Process prompt tokens and create their KV cache.

Decode

Generate new tokens iteratively using the cache.

User clock

Queueing, TTFT, inter-token latency, and total completion.

Read the brief, then speak

A lawyer first reads a case file, then answers questions one sentence at a time. Reading is parallelizable: many pages can be scanned and related at once. Speaking is sequential: the next word depends on what has already been said. LLM inference has the same asymmetry.

Mental model

Prefill is prompt ingestion. Decode is autoregressive generation. They run the same model weights with different shapes, bottlenecks, and latency consequences.

Tokenization converts text and tool schemas into token IDs. The request waits for admission. During prefill, the model processes the prompt tokens, computes attention and feed-forward layers, and stores key/value vectors for each layer. The final prompt position produces logits for the first generated token. During decode, the sampled token becomes the next input, the model computes one new position, appends its K and V to the cache, samples again, and repeats.

A tool-using turn is several inference requests

Concrete example

The incident-reasoning engine starts with 2,000 tokens of system instructions, tool schemas, alert context, and recent history. It generates a 35-token topology call. The tool returns 900 tokens. The engine then generates a telemetry call, receives another result, and finally writes a diagnosis.

Each model turn has a prompt and decode phase. If the runtime cannot reuse the prior prefix, the second turn prefills the original 2,000 tokens, the first action, and the 900-token tool result. Prefix or session caching can reuse earlier KV state when the model, tokens, positions, and relevant runtime assumptions match. The growing transcript increases both prefill work and KV memory.

An agent's "18-second answer" spans queueing, several prefills, several decode segments, network serialization, tool execution, and orchestration. Output token speed describes only one segment. Instrument the critical path by phase.

Queue time
Arrival until the scheduler admits the request.
TTFT
Time to first token: queueing, tokenization, prefill, and first sampling step.
ITL / TPOT
Inter-token latency or time per output token after generation starts.
E2E latency
Arrival to completed response, including generated length and external work.

The shapes differ

Prefill exposes many token positions at once. Matrix multiplications have larger dimensions, making it easier to use GPU compute units efficiently. Attention still has substantial memory traffic, especially at long context, but prefill is commonly described as more compute-bound than single-token decode.

Decode processes one new token per sequence. For a single request, matrix-vector-like operations repeatedly read large model weights to produce a small amount of new work. That low arithmetic intensity often makes decode memory-bandwidth-bound. Batching several active sequences turns the operation into a wider matrix multiplication and reuses each weight load across more tokens, moving the workload toward better compute utilization.

PhaseTokens processed per sequenceTypical sensitivityUser-facing metric
PrefillAll uncached prompt tokensPrompt length, batching, compute, attention IOTTFT
DecodeOne new token per iterationWeight bandwidth, active batch, KV readsITL / TPOT
Tool gapNo model tokensExternal service latency and orchestrationEnd-to-end task time

The words "compute-bound" and "memory-bound" are workload and hardware statements, not model identities. A phase can change regimes with sequence length, batch size, quantization, kernel, parallelism, and accelerator. The next chapter builds the arithmetic needed to say which resource sets the floor.

Sampling is part of inference semantics

The model produces logits. A serving stack may apply temperature, top-k, top-p, repetition controls, logit biases, structured-output constraints, and a random-number generator before selecting a token. Greedy decoding chooses the highest logit. Sampling draws from a transformed distribution. These settings change both behavior and workload: generated length, tool-call diversity, speculative acceptance, and rollout exploration.

For RL rollouts, record decoding parameters and random seeds where reproducibility allows. Two policies compared under different temperatures are not a clean policy comparison. For production, deterministic settings can simplify debugging but may reduce useful diversity. Choose decoding settings from the task contract.

Inference contract

Model weights alone do not identify a policy deployment. Tokenizer, prompt template, tool grammar, numerical precision, sampling configuration, runtime, and stopping rules all influence observable behavior.

Misconception: tokens per second is latency

Output token rate describes the stream after generation starts. A system can have excellent decode rate and terrible TTFT from queueing or long prefill. Users experience the sequence of waits, not one aggregate number.

Measure the workload distribution

Collect prompt length, generated length, cached-prefix fraction, tool-turn count, concurrency, arrival burstiness, and SLO class. Report medians and tails. A benchmark with 128-token prompts and 128-token outputs says little about an agent that sends 32,000-token transcripts and generates 20-token tool calls. A throughput number without a workload shape is not portable.

Separate user-in-loop work from background work. An interactive investigation may prioritize TTFT and ITL. An overnight best-of-eight rollout job may accept higher per-request latency to maximize tokens per GPU hour. One runtime can expose different scheduling policies along the latency-throughput frontier.

References