Prefill: processes the whole prompt in parallel; compute-bound; determines time to first token
Decode: generates one token at a time; memory-bandwidth-bound; determines tokens per second
Each new token attends to all previous tokens. The KV cache stores the keys and values of past tokens so they are not recomputed.
Decode is limited by how fast weights and KV cache stream from GPU memoryTTFT: time to first token: queueing + prefill
TPOT / ITL: time per output token / inter-token latency
End-to-end latency: TTFT + (output tokens x TPOT)
Throughput: total tokens per second across all requests
Goodput: requests per second that meet your latency SLOs
Batching raises throughput but can raise per-request latencyContinuous batching: add and remove requests from the running batch every step instead of waiting for a full batch
PagedAttention: stores KV cache in fixed-size blocks to avoid fragmentation (vLLM)
Prefix caching: reuse the KV cache for shared prompt prefixes such as system prompts
Quantization: lower-precision weights/KV cache for less memory and faster decode
Speculative decoding: a small draft model proposes tokens, the big model verifies them in parallel
Tensor parallelism: split each layer across GPUs to fit larger models
pip install vllm
vllm serve meta-llama/Llama-3.1-8B-Instruct \
--max-model-len 8192 \
--gpu-memory-utilization 0.90 \
--tensor-parallel-size 1 \
--enable-prefix-caching \
--port 8000
# OpenAI-compatible API at http://localhost:8000/v1
Gated models need HF_TOKEN set in the environment
--max-model-len: context length; lower it to free KV cache memory
--gpu-memory-utilization: fraction of GPU memory vLLM may use (default 0.9)
--tensor-parallel-size: number of GPUs to shard the model across
--max-num-seqs: max concurrent sequences per step
--quantization: e.g. awq, gptq, fp8
--dtype: auto, bfloat16, float16
--enable-prefix-caching: reuse shared prompt prefixes
Out-of-memory at startup? Lower --max-model-len or --max-num-seqs, quantize, or add GPUs with tensor parallelism.
from vllm import LLM, SamplingParams
llm = LLM(model="Qwen/Qwen2.5-7B-Instruct", max_model_len=8192)
params = SamplingParams(temperature=0.7, top_p=0.9, max_tokens=256)
outputs = llm.generate(["Explain KV cache simply."], params)
print(outputs[0].outputs[0].text)
# Chat format
llm.chat([{"role": "user", "content": "Hi"}], params)
Offline batch inference is the cheapest way to process large datasets
ollama pull llama3.1
ollama run llama3.1 "Summarize RAG in two lines"
ollama list
ollama ps # loaded models
ollama serve # API on http://localhost:11434
curl http://localhost:11434/api/chat -d '{
"model": "llama3.1",
"messages": [{"role": "user", "content": "Hello"}],
"stream": false
}'
# Modelfile: custom system prompt and parameters
# FROM llama3.1
# PARAMETER temperature 0.3
# SYSTEM You are a concise assistant.
ollama create my-assistant -f Modelfile
# OpenAI-compatible server
llama-server -m model-Q4_K_M.gguf -c 8192 -ngl 99 --port 8080
# Interactive / one-shot
llama-cli -m model-Q4_K_M.gguf -p "Hello" -n 128
# -ngl = layers offloaded to GPU -c = context size -t = CPU threads
Q8_0: near-lossless, about 1 byte per weight
Q5_K_M: high quality
Q4_K_M: best size/quality balance; the popular default
Q2/Q3: noticeable quality loss; only when memory is tight
pip install mlx-lm
mlx_lm.generate --model mlx-community/Llama-3.2-3B-Instruct-4bit \
--prompt "Hello" --max-tokens 100
mlx_lm.server --model mlx-community/Llama-3.2-3B-Instruct-4bit --port 8080
Unified memory on Macs lets you run models larger than most consumer GPUs
vLLM: general-purpose high-throughput serving; broad model support
SGLang: high performance, strong structured output and prefix reuse
TensorRT-LLM: maximum NVIDIA performance; more complex build and deploy
llama.cpp / Ollama: local, CPU or consumer GPU, GGUF models
MLX: Apple Silicon
Hosted APIs: no ops; pay per token
# SGLang
python -m sglang.launch_server --model-path Qwen/Qwen2.5-7B-Instruct --port 30000
Benchmark with YOUR prompt lengths and concurrency before deciding
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="not-needed")
resp = client.chat.completions.create(
model="meta-llama/Llama-3.1-8B-Instruct",
messages=[{"role": "user", "content": "Hello"}],
temperature=0.2,
max_tokens=200,
stream=True,
)
for chunk in resp:
print(chunk.choices[0].delta.content or "", end="")
# curl http://localhost:8000/v1/models (list served models)
Because vLLM, SGLang, llama.cpp, Ollama (/v1) and others speak this API, you can swap backends by changing base_url.
# Constrain output to a JSON schema (guided decoding)
client.chat.completions.create(
model=MODEL,
messages=[{"role": "user", "content": "Extract name and age: Ann, 31"}],
response_format={"type": "json_schema", "json_schema": {
"name": "person",
"schema": {"type": "object",
"properties": {"name": {"type": "string"},
"age": {"type": "integer"}},
"required": ["name", "age"]}}},
)
Guided decoding guarantees valid JSON; still validate the content
Weights = params x bytes_per_param
7B fp16 ~ 14 GB | int8 ~ 7 GB | 4-bit ~ 3.5-4 GB
KV cache per token = 2 x layers x kv_heads x head_dim x bytes
Llama 3.1 8B (32 layers, 8 KV heads, head_dim 128, fp16):
2 x 32 x 8 x 128 x 2 B = 131,072 B = 128 KiB per token
KV total = per_token x context_len x concurrent_sequences
e.g. 8k tokens x 32 seqs x 128 KiB ~ 32 GiB
Plan: weights + KV cache + activations/overhead (10-20%)
GQA (fewer KV heads) shrinks KV cache; KV cache quantization (fp8) halves it again
# vLLM benchmark script against a running server
vllm bench serve --model meta-llama/Llama-3.1-8B-Instruct \
--dataset-name random --random-input-len 1024 --random-output-len 256 \
--num-prompts 200 --request-rate 10
- Test at realistic concurrency and prompt/output lengths
- Report p50 and p95/p99 for TTFT and TPOT, not just averages
- Increase load until latency SLOs break to find capacity
- Autoscale on queue depth or GPU utilization; warm up new replicas (model load is slow)
- Put a gateway in front: auth, rate limits, request size limits, timeouts
- Enable prefix caching for long shared system prompts
- Set max_tokens and max context to bound cost per request
- Monitor TTFT, TPOT, queue depth, KV cache usage, GPU memory (Prometheus metrics)
- Keep a fallback model or hosted API for overflow and failures
- Pin engine and model versions; test upgrades with the same benchmark