Education › Inference › Stage 2: LLM inference fundamentals

The life of an inference request

Tokens, weights and the request lifecycle; prefill versus decode and their very different compute patterns.

Beginner ~30 min read Module 3 of 15

To operate an inference service you need a precise picture of what happens between a request arriving and the last token streaming out. This lesson follows one request through tokenization, queueing, prefill, the decode loop and streaming, explains what model weights are and where they sit, and shows why prefill and decode stress the hardware in opposite ways. Almost every later topic, from batching to disaggregation, is built on that difference.

After this module you can
  • Explain tokens and why every cost, limit and speed is measured in them
  • Trace a request through tokenize, queue, prefill, decode, stream and stop
  • Contrast prefill (compute-bound) with decode (memory-bound)
  • Relate prompt length and output length to latency and cost
  • Name the sampling and stop parameters that change how long a request runs

Tokens and weights

Models do not read characters or words; they read tokens, chunks of text from a fixed vocabulary learned by a tokenizer. Common words are often one token, rarer words split into several, and code, other languages and numbers can take many more. As a loose rule of thumb, English prose averages around three-quarters of a word per token, but it varies by tokenizer, so always count with the model's own tokenizer.

Everything in inference is measured in tokens: the context window (maximum prompt plus output), prices, rate limits, throughput (tokens per second) and memory (KV cache per token). A request has input tokens (the prompt, including system prompt, history, retrieved documents and tool results) and output tokens (what the model generates).

The weights are the model's learned parameters: large matrices for every layer. A model with 8 billion parameters in BF16 is about 16 GB of numbers that must sit in GPU memory and be read for every forward pass. Weights are fixed during inference; what changes per request is the token sequence and the per-request KV cache built from it.

The request lifecycle

  1. Receive and tokenize. The server applies the model's chat template to the messages and converts the text to token IDs on the CPU.
  2. Queue. The scheduler admits the request when there is room: KV-cache memory and a slot in the running batch. Time spent here is pure waiting.
  3. Prefill. The model processes all prompt tokens in one forward pass, builds the KV cache for them, and produces the first output token.
  4. Decode loop. One forward pass per new token: read the weights, attend over the KV cache, pick the next token, append its keys and values to the cache.
  5. Stream. Each new token is detokenized and sent to the client as it is produced.
  6. Stop. The loop ends at an end-of-sequence token, a stop string, or the max-tokens limit; the KV cache is freed.
requestadmitfirst tokenwriteread, appendstream tokensClientTokenize + queuewaitingPrefillcompute-boundDecode loopmemory-boundKV cachegrows per token
One request's journey: queue wait and the compute-bound prefill make up time to first token; the memory-bound decode loop sets streaming speed.
The decode loop in pseudocode
python
tokens = tokenize(apply_chat_template(messages))
kv_cache, logits = model.prefill(tokens)          # one pass over the whole prompt
output = []
while len(output) < max_tokens:
    next_id = sample(logits, temperature=0.7, top_p=0.9)
    if next_id == EOS or hits_stop_string(output, next_id):
        break
    output.append(next_id)
    stream(detokenize(next_id))
    logits = model.decode_step(next_id, kv_cache)  # one pass per new token

Prefill versus decode

Prefill handles hundreds or thousands of prompt tokens at once. Each weight read from memory is used for every prompt token, so the work is large matrix-matrix multiplication and the GPU's Tensor Cores are the limit: prefill is compute-bound. Its duration grows with prompt length, and it decides the time to first token.

Decode produces one token per request per step. Each step reads every weight but does very little arithmetic with it, so the GPU waits on memory: decode is memory-bandwidth-bound. Its duration grows with output length, and it decides the gap between streamed tokens. Batching many requests' decode steps together is what turns this wasteful pattern into efficient throughput.

PrefillDecode
Tokens per passWhole promptOne per request
BottleneckCompute (Tensor Cores)Memory bandwidth
Scales withInput lengthOutput length
User feels it asTime to first tokenStreaming speed
Helped byMore compute, prefix cachingBatching, faster memory, smaller weights
Tip

A RAG app with 6,000-token prompts and 200-token answers is prefill-heavy; a writing assistant with short prompts and 2,000-token answers is decode-heavy. Profile your real input and output length distribution before tuning anything.

Parameters that change the work

  • max_tokens caps output length and therefore worst-case decode time and KV-cache use. Always set it.
  • Stop sequences end generation early when a delimiter appears, saving tokens.
  • temperature and top_p change which token is sampled, not the cost per token; but they can change how long answers run.
  • n (several completions per prompt) shares one prefill but multiplies decode work.
  • Structured output constrains tokens to a schema; engines implement it efficiently, but it adds per-step overhead.
  • Long system prompts are paid in prefill on every request unless the engine caches the shared prefix.
Hands-on practice

Watch prefill and decode separately

  1. Count tokens for a short prompt, a 2,000-word document and a block of code with the tokenizer of any open model (for example via the transformers library) and note tokens per word.
  2. Start any OpenAI-compatible engine (vLLM is fine) with a small model.
  3. Send a request with a 50-token prompt and max_tokens 500 using streaming, and record the time to the first token and the total time.
  4. Repeat with a 4,000-token prompt and max_tokens 50. Which phase dominated each request?
  5. Compute time per output token for each run as (total time minus time to first token) divided by output tokens minus one.
  6. Write down which of your real workloads look like the first run and which like the second.
Cheat sheet

The life of an inference request — at a glance

Main things to focus on

  • Everything is counted in tokens: context, cost, throughput, memory.
  • Lifecycle: tokenize, queue, prefill, decode loop, stream, stop.
  • Prefill is compute-bound and sets time to first token.
  • Decode is memory-bound and sets streaming speed.
  • Input length drives prefill cost; output length drives decode cost.
  • Always set max_tokens.

Formulas

latency ~ queue + prefill(input) + (output - 1) x TPOTEnd-to-end request time
TTFT ~ queue + prefillTime until the first token
prefill FLOPs ~ 2 x params x input_tokensCompute for the prompt, ignoring attention
decode bytes per step ~ weights + KV readWhy decode is bandwidth-bound

Request parameters

max_tokensCap output length and worst-case cost
stop: ["###"]End generation on a delimiter
temperature / top_pSampling randomness, not cost per token
nSeveral completions: one prefill, n decodes
stream: trueSend tokens as they are generated

Vocabulary

TokenUnit of text from the tokenizer's vocabulary
Context windowMaximum input plus output tokens
Chat templateHow messages are formatted into one token sequence
EOSEnd-of-sequence token that stops generation
Input / output tokensPrompt tokens vs generated tokens; priced and timed differently
LogitsScores over the vocabulary from which the next token is sampled

Common pitfalls

  • Estimating tokens from word counts for code or non-English text.
  • No max_tokens, so one runaway request holds cache and capacity.
  • Tuning for decode speed when the workload is dominated by long prompts.
  • Re-sending huge, unchanging system prompts without prefix caching.
  • Reporting only total latency, hiding whether prefill or decode is the problem.
Quiz

Check your understanding

5 questions · 4 to pass · answers are explained as you go. Your best score is saved on this device only.

Progress and quiz scores are saved in this browser only. Back up or restore on the hub.

Was this lesson useful? Tell me what to improve →