Careers Post-AI
AI infrastructure and systems: all chapters

AI infrastructure and systemsPart 2: Inference serving

Chapter 5Inference fundamentals

30 min read, 1 lab, Intermediate

An 8-billion-parameter model on one GPU can answer a single user at roughly 100 tokens per second, then hit a wall at a few dozen users. The wall is the KV cache, not compute. This chapter shows you what happens inside one generated token, so you can predict that wall, size memory for concurrent users and explain why latency and throughput pull against each other.

After this chapter you can

  • Trace autoregressive decoding token by token and separate the prefill phase from the decode phase.
  • Calculate the KV cache size per token and per sequence for a real model.
  • Explain static, dynamic and continuous batching and why continuous batching won.
  • Predict how time to first token and tokens per second move as prompt length and concurrency grow.
  • Measure TTFT, per-request speed and aggregate throughput on a local model server.

One token at a time

A language model does not write a sentence. It produces a probability distribution over its vocabulary for the next token only. The serving loop picks one token from that distribution, appends it to the sequence and runs the model again. This is autoregressive decoding: each token waits for the last.

The consequence is that a 500-token answer means 500 sequential forward passes. You cannot compute token 300 before token 299 exists. Every trick in inference serving is a way of making those passes cheaper, sharing them across users or skipping some of them.

Here is the loop in plain Python with Hugging Face Transformers, with no cache, so you can see the waste:

naive_decode.py
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
 
name = "Qwen/Qwen2.5-0.5B-Instruct"
tok = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(name)
 
ids = tok("The capital of France is", return_tensors="pt").input_ids
for _ in range(20):
    logits = model(ids, use_cache=False).logits   # recomputes the whole sequence
    next_id = logits[0, -1].argmax()              # greedy: take the top token
    ids = torch.cat([ids, next_id.view(1, 1)], dim=1)
print(tok.decode(ids[0]))

Each iteration reprocesses every earlier token, so the total work grows with the square of the length. The KV cache, two sections down, removes that repetition.

Prefill and decode are different workloads

A request goes through two phases with opposite performance profiles. Recall from the chapter on GPUs and accelerators that a kernel is either compute-bound (limited by arithmetic) or memory-bound (limited by how fast bytes move from memory).

Prefill

  • Processes the whole prompt in one forward pass.
  • Thousands of tokens in parallel, large matrix multiplies.
  • Compute-bound: the GPU's FLOPs are busy.
  • Determines time to first token (TTFT).
  • Cost grows roughly linearly with prompt length (quadratic attention term on long prompts).

Decode

  • Produces one new token per sequence per step.
  • Tiny matrix-vector work per sequence.
  • Memory-bound: every step reads all weights plus the KV cache.
  • Determines inter-token latency and tokens per second.
  • Cost grows with output length and context length.

The decode bound is worth computing once. An 8B model in 16-bit weights is about 16 GB. If your GPU has 3.35 TB/s of memory bandwidth (an H100 SXM), reading the weights once takes about 4.8 ms, so one sequence cannot decode faster than about 200 tokens per second no matter how many FLOPs the chip has.

decode step time  >=  bytes read per step / memory bandwidth
                  ~=  16 GB / 3.35 TB/s  ~=  4.8 ms   ->  at most ~200 tokens/s for one stream

The good news hides in the same formula. A batch of 32 sequences reads the weights once per step too, so it produces 32 tokens for nearly the same 4.8 ms. That is why batching is the main lever in serving.

The KV cache

Attention needs, for every earlier token, two vectors per layer: a key and a value. Those vectors never change once computed. The KV cache stores them so each decode step computes keys and values for the one new token and reads the rest from memory.

The cache trades compute for memory, and the memory is large. The size per token depends only on the architecture:

KV bytes per token = 2 (K and V) x layers x kv_heads x head_dim x bytes_per_value

Two worked examples, both with 16-bit values:

ModelLayersKV headsHead dimKV per tokenOne 8k-token sequence
Llama 3.1 8B328128128 KiB1 GiB
Qwen2.5 0.5B2426412 KiB96 MiB

Notice "KV heads" rather than attention heads. Modern models use grouped-query attention (GQA), where several query heads share one key/value head; Llama 3.1 8B has 32 query heads but only 8 KV heads, which cuts the cache by four. Read these numbers from a model's config.json (num_hidden_layers, num_key_value_heads, and head_dim or hidden_size / num_attention_heads).

Memory budgeting for concurrent sequences

Put the pieces together for an 8B model on a 24 GB card (an NVIDIA L4, for example).

GPU memory                                  24.0 GB
- weights (8B params x 2 bytes)            -16.0 GB
- activations, CUDA context, fragmentation  -2.0 GB   (approximate, engine dependent)
= available for KV cache                     ~6 GB
KV per token (Llama 3.1 8B, FP16)          128 KiB
=> total cached tokens                     ~46,000 tokens
=> concurrent 8k-token conversations         ~5
=> concurrent 2k-token conversations        ~22

That arithmetic explains three decisions you will make constantly. Quantizing the weights to 8 bits (covered in the chapter on model optimization) frees about 8 GB for cache, more than doubling concurrency. Capping max_model_len stops one huge request from reserving memory for a context nobody uses. And storing the cache itself in 8 bits halves the per-token cost again, at a small accuracy risk.

When the cache fills, an engine must either queue new requests or preempt running ones, evicting their cache and recomputing it later. Both show up to users as latency spikes, which is why serving engines expose cache utilisation as a first-class metric.

Sampling turns logits into text

The model outputs logits, one score per vocabulary entry. The sampler converts them to probabilities and picks a token. Sampling parameters change output quality and sometimes speed, and they are part of every API request.

ParameterWhat it doesTypical value
temperatureDivides logits before softmax. 0 means greedy (always the top token); higher flattens the distribution.0 for extraction, 0.7 for chat
top_pNucleus sampling: keep the smallest set of tokens whose probabilities sum to p.0.9 to 1.0
top_kKeep only the k most likely tokens.20 to 50, or off
max_tokensHard cap on output length. Bounds latency and cache use.Set it always
stopStrings that end generation early.Model and task specific
seedMakes sampling repeatable on the same engine and hardware.For tests

Static, dynamic and continuous batching

Batching runs several sequences through one forward pass. The question is when sequences may join and leave.

  1. Static batching

    Collect a fixed batch, run it until every sequence finishes, return all results. A batch with one 1,000-token answer and seven 20-token answers keeps seven slots idle for 980 steps. Fine for offline jobs, poor for chat.

  2. Dynamic batching

    Wait up to a short window (say 10 ms) or until the batch is full, then run it as a static batch. This is how classic model servers batch image classifiers. It helps arrival patterns but still holds every request hostage to the longest one in its batch.

  3. Continuous batching

    Schedule at the granularity of one decode step. After every step, finished sequences leave and waiting requests join, with their prefill mixed into the same step. Introduced by the Orca paper (OSDI 2022) as iteration-level scheduling, it is now the default in every serious LLM engine.

Continuous batching raised throughput on real workloads by large factors because GPU slots never sit idle waiting for a straggler. Its admission rule is the memory budget from the previous section: a request joins only if there is cache space for it.

Latency against throughput

Every serving system has two audiences. A user cares about TTFT (how long until text appears) and inter-token latency or ITL (the gap between tokens, the inverse of per-request tokens per second). The operator cares about aggregate throughput: total tokens per second per GPU, which sets cost per token.

ConcurrencyPer-request tokens/sAggregate tokens/sTTFT
1highestlowestlowest
8slightly lowerabout 6 to 7 times highera bit higher
64noticeably lowerhighest, flatteninghigher, queueing begins
Past KV capacitydropsflatgrows without bound

These shapes, not the exact numbers, are what you should expect; the lab gives you your own numbers. Throughput rises with batch size because decode is memory-bound, then flattens once compute saturates or the cache fills. Each new prefill also stalls the decode steps of everyone else in the batch, which is why engines split long prompts into chunks (chunked prefill) and interleave them with decode steps.

Streaming changes perceived latency

Because tokens arrive one at a time, servers stream them as they are produced. OpenAI-compatible servers use server-sent events (SSE): an HTTP response that stays open and emits data: lines.

POST /v1/chat/completions HTTP/1.1
Content-Type: application/json
 
{"model": "qwen", "stream": true, "messages": [{"role": "user", "content": "Hi"}]}
data: {"choices":[{"delta":{"content":"Hello"}}]}
data: {"choices":[{"delta":{"content":" there"}}]}
data: [DONE]

Streaming does not make generation faster. It makes TTFT the latency a person feels, since reading speed (around 5 to 10 tokens per second) is slower than most decode speeds. Proxies and load balancers must be configured not to buffer these responses, or users see nothing until the end.

Key terms

Autoregressive decoding
Generating text one token at a time, feeding each output token back in as input for the next step.
Prefill
The first forward pass over the whole prompt; compute-bound and the main driver of time to first token.
Decode
The repeated one-token-per-step phase; memory-bandwidth-bound and the driver of tokens per second.
KV cache
Stored attention keys and values for every earlier token, so each decode step only computes the newest token.
Grouped-query attention
An architecture where several query heads share one key/value head, shrinking the KV cache.
Continuous batching
Scheduling at every decode step so sequences join and leave the running batch independently.
TTFT
Time to first token: from request arrival to the first streamed output token.
ITL
Inter-token latency: the average gap between streamed tokens for one request.
Preemption
Evicting a running sequence's KV cache when memory runs out, to recompute or swap it back later.
Lab

Measure TTFT and tokens per second on your own machine

Intermediate, 60 min

Goal: serve a small open model locally, measure TTFT and tokens per second across prompt lengths and concurrency levels, and plot the curves.

You need: macOS or Linux (Windows: use WSL2), 8 GB RAM, Python 3.10+, and llama.cpp. Install llama.cpp with brew install llama.cpp on macOS or Linux Homebrew, or build it from source following the repository README. Then pip install openai matplotlib. If you prefer Ollama, the same script works against its OpenAI-compatible endpoint.

  1. Start llama-server with a 0.5B model. The -hf flag downloads a GGUF file from Hugging Face on first run. Four parallel slots let up to four requests decode together, and they share the 16,384-token context.
llama-server -hf Qwen/Qwen2.5-0.5B-Instruct-GGUF:Q4_K_M \
  --host 127.0.0.1 --port 8080 -np 4 -c 16384 --metrics

Wait for a log line saying the server is listening, then confirm it is ready (expect {"status":"ok"}):

curl -s http://127.0.0.1:8080/health

Ollama alternative: run OLLAMA_NUM_PARALLEL=4 ollama serve in one terminal and ollama pull qwen2.5:0.5b in another, then use base URL http://127.0.0.1:11434/v1 and model qwen2.5:0.5b below.

  1. Save the measurement script. It streams each response, records when the first content chunk arrives (TTFT) and counts chunks as an approximation of tokens.
measure.py
import asyncio, time, json, sys
from openai import AsyncOpenAI
 
BASE = sys.argv[1] if len(sys.argv) > 1 else "http://127.0.0.1:8080/v1"
MODEL = sys.argv[2] if len(sys.argv) > 2 else "qwen"
client = AsyncOpenAI(base_url=BASE, api_key="none")
FILLER = "The quick brown fox jumps over the lazy dog. "  # about 10 tokens
 
async def one(prompt_words, max_tokens=128):
    prompt = FILLER * (prompt_words // 9) + "\nSummarise the text above in a long paragraph."
    t0 = time.perf_counter(); first = None; n = 0
    stream = await client.chat.completions.create(
        model=MODEL, stream=True, max_tokens=max_tokens, temperature=0,
        messages=[{"role": "user", "content": prompt}])
    async for chunk in stream:
        if chunk.choices and chunk.choices[0].delta.content:
            n += 1
            if first is None:
                first = time.perf_counter()
    end = time.perf_counter()
    decode_tps = (n - 1) / (end - first) if n > 1 else 0.0
    return {"ttft": first - t0, "tokens": n, "decode_tps": decode_tps, "total": end - t0}
 
async def run(prompt_words, concurrency):
    t0 = time.perf_counter()
    rs = await asyncio.gather(*[one(prompt_words) for _ in range(concurrency)])
    wall = time.perf_counter() - t0
    return {"prompt_words": prompt_words, "concurrency": concurrency,
            "ttft_avg": sum(r["ttft"] for r in rs) / len(rs),
            "decode_tps_avg": sum(r["decode_tps"] for r in rs) / len(rs),
            "aggregate_tps": sum(r["tokens"] for r in rs) / wall}
 
async def main():
    await one(50)  # warm-up, not recorded
    results = []
    for words in [50, 500, 1500, 3000]:
        results.append(await run(words, 1))
    for c in [1, 2, 4, 8]:
        results.append(await run(300, c))
    for r in results:
        print(r)
    json.dump(results, open("results.json", "w"), indent=2)
 
asyncio.run(main())
  1. Run it. On an Apple M-series laptop expect TTFT well under a second for short prompts, rising with prompt length, and per-request decode speeds in the tens to low hundreds of tokens per second for this tiny model. Your numbers will differ; the shapes are what matter.
python measure.py http://127.0.0.1:8080/v1 qwen
  1. Plot the two experiments.
plot.py
import json
import matplotlib.pyplot as plt
 
rs = json.load(open("results.json"))
pl = [r for r in rs if r["concurrency"] == 1 and r["prompt_words"] != 300]
cc = [r for r in rs if r["prompt_words"] == 300]
 
fig, (a, b) = plt.subplots(1, 2, figsize=(11, 4))
a.plot([r["prompt_words"] for r in pl], [r["ttft_avg"] for r in pl], marker="o")
a.set(xlabel="Prompt length (words)", ylabel="TTFT (s)", title="Prefill cost")
b.plot([r["concurrency"] for r in cc], [r["decode_tps_avg"] for r in cc], marker="o", label="per request")
b.plot([r["concurrency"] for r in cc], [r["aggregate_tps"] for r in cc], marker="s", label="aggregate")
b.set(xlabel="Concurrent requests", ylabel="tokens/s", title="Latency vs throughput")
b.legend(); fig.tight_layout(); fig.savefig("inference_curves.png", dpi=150)
  1. Look at the server's own view while a run is in progress. With --metrics enabled, llama-server exposes Prometheus metrics; llamacpp:requests_processing and llamacpp:requests_deferred show running and queued requests.
curl -s http://127.0.0.1:8080/metrics | grep -E "requests_(processing|deferred)"

Check your work: inference_curves.png shows TTFT rising with prompt length, and aggregate tokens per second rising with concurrency while per-request speed falls. At concurrency 8 with 4 slots you should see requests_deferred above zero during the run and a jump in average TTFT, because half the requests queue.

Stretch: restart the server with -np 1 and -np 8 and rerun the concurrency sweep. Then compute the KV cache size for 16,384 tokens of Qwen2.5 0.5B with the formula above, and compare it with the memory figures llama-server prints at startup.

Check yourself

A team doubles their GPU's FLOPs but keeps the same memory bandwidth. Single-user tokens per second for an 8B model barely changes. Why?

Llama 3.1 8B uses 128 KiB of FP16 KV cache per token. Roughly how much cache do 10 concurrent 4,000-token conversations need?

Under static batching, a batch holds one request generating 1,000 tokens and seven generating 20. What does continuous batching change?

Users report that chat responses appear all at once after a long pause, even though the model server streams tokens. What is the most likely cause?

Why does aggregate tokens per second keep rising as concurrency grows from 1 to 8 on a GPU, while per-request speed drops only slightly?

Recap

  • Decoding is autoregressive: one forward pass per output token, strictly in order.
  • Prefill is compute-bound and sets TTFT; decode is memory-bound and sets tokens per second.
  • The KV cache costs 2 x layers x KV heads x head dim x bytes per token, and it caps concurrency.
  • Continuous batching schedules every step, so GPU slots never wait on a straggler.
  • Bigger batches raise throughput and cost per token falls, but per-request latency rises and queues form at the cache limit.
  • Streaming makes TTFT the latency users feel, as long as nothing in the path buffers it.

Go deeper