Datasets:
Upload folder using huggingface_hub
Browse files- README.md +37 -0
- articles/continuous-batching-explained.md +49 -0
- articles/gpu-memory-for-70b.md +53 -0
- articles/inference-engineer-roadmap.md +47 -0
- articles/kv-cache-math.md +68 -0
- articles/llm-inference-interview-questions.md +44 -0
- articles/prefill-vs-decode.md +55 -0
- articles/quantization-for-serving.md +49 -0
- articles/speculative-decoding.md +52 -0
- articles/ttft-vs-tokens-per-second.md +47 -0
- articles/vllm-vs-sglang-vs-tensorrt-llm.md +59 -0
- calculator/README.md +44 -0
- calculator/kv_calc.py +67 -0
README.md
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: cc-by-4.0
|
| 3 |
+
language:
|
| 4 |
+
- en
|
| 5 |
+
pretty_name: LLM Inference Engineering Notes
|
| 6 |
+
tags:
|
| 7 |
+
- text
|
| 8 |
+
- llm-inference
|
| 9 |
+
- vllm
|
| 10 |
+
- sglang
|
| 11 |
+
- kv-cache
|
| 12 |
+
- quantization
|
| 13 |
+
task_categories:
|
| 14 |
+
- text-generation
|
| 15 |
+
size_categories:
|
| 16 |
+
- n<1K
|
| 17 |
+
---
|
| 18 |
+
|
| 19 |
+
# LLM Inference Engineering Notes
|
| 20 |
+
|
| 21 |
+
A small collection of technical notes (Markdown text) on serving large language models: KV-cache math, prefill vs decode, continuous batching, quantization, speculative decoding, GPU memory sizing, latency metrics, engine comparisons and interview prep. Includes a dependency-free KV-cache / GPU-memory calculator script. This is a notes collection, not a training dataset.
|
| 22 |
+
|
| 23 |
+
## Table of contents
|
| 24 |
+
|
| 25 |
+
- [Continuous batching explained with numbers](articles/continuous-batching-explained.md)
|
| 26 |
+
- [How much GPU memory do you need to serve a 70B model?](articles/gpu-memory-for-70b.md)
|
| 27 |
+
- [Inference engineer roadmap: skills, tools, and a 12-week plan](articles/inference-engineer-roadmap.md)
|
| 28 |
+
- [KV cache math](articles/kv-cache-math.md)
|
| 29 |
+
- [LLM inference interview questions with worked answers](articles/llm-inference-interview-questions.md)
|
| 30 |
+
- [Prefill vs decode](articles/prefill-vs-decode.md)
|
| 31 |
+
- [Quantization for serving: FP8, INT8, INT4 tradeoffs](articles/quantization-for-serving.md)
|
| 32 |
+
- [Speculative decoding: when it helps and when it doesn't](articles/speculative-decoding.md)
|
| 33 |
+
- [Time-to-first-token vs tokens-per-second: what to measure](articles/ttft-vs-tokens-per-second.md)
|
| 34 |
+
- [vLLM vs SGLang vs TensorRT-LLM: when to pick which](articles/vllm-vs-sglang-vs-tensorrt-llm.md)
|
| 35 |
+
- [KV cache calculator](calculator/kv_calc.py) ([README](calculator/README.md)) — interactive version: https://huggingface.co/spaces/inference-engineering-academy/llm-kv-cache-calculator
|
| 36 |
+
|
| 37 |
+
Made by Inference Engineering Academy (https://www.inference-engineering.xyz/), which has a free Foundations course on LLM inference.
|
articles/continuous-batching-explained.md
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Continuous batching explained with numbers
|
| 2 |
+
|
| 3 |
+
Continuous batching is the single biggest reason modern LLM servers get high throughput. Here is why, with arithmetic you can check.
|
| 4 |
+
|
| 5 |
+
## Why batch at all?
|
| 6 |
+
During decode, each step generates one token per sequence and must read all model weights from GPU memory. Take Llama 3.1 8B in BF16: about 16 GB of weights. On an H100 SXM with about 3.35 TB/s of HBM bandwidth, one weight read takes at least
|
| 7 |
+
|
| 8 |
+
16 GB / 3,350 GB/s = **~4.8 ms**.
|
| 9 |
+
|
| 10 |
+
At batch size 1, that is at most ~210 tokens/s. With 32 sequences in the batch, the same weight read serves 32 tokens, so the ceiling becomes ~6,700 tokens/s, minus the extra cost of reading each sequence's KV cache. Batching amortizes the weight read.
|
| 11 |
+
|
| 12 |
+
## The problem with static batching
|
| 13 |
+
Static batching groups requests and runs them until **all** are finished. Suppose a batch of 4 has output lengths of 50, 100, 200 and 1,000 tokens.
|
| 14 |
+
- The batch runs 1,000 steps.
|
| 15 |
+
- Useful token-steps: 50 + 100 + 200 + 1,000 = 1,350.
|
| 16 |
+
- Slots available: 4 x 1,000 = 4,000.
|
| 17 |
+
- Utilization: 1,350 / 4,000 = **34%**.
|
| 18 |
+
|
| 19 |
+
Worse, new requests wait in the queue for up to 1,000 steps (about 5 seconds at 4.8 ms/step), which wrecks time to first token.
|
| 20 |
+
|
| 21 |
+
## Continuous (iteration-level) batching
|
| 22 |
+
Introduced by Orca (OSDI 2022), continuous batching makes scheduling decisions at every decode step:
|
| 23 |
+
1. Sequences that emit an end token leave immediately.
|
| 24 |
+
2. Waiting requests are admitted into freed slots on the next step.
|
| 25 |
+
3. Their prefill is run (often in chunks) alongside ongoing decodes.
|
| 26 |
+
|
| 27 |
+
In the example above, as soon as the 50-token request finishes, a new request takes its slot. With a steady queue, slots stay close to 100% occupied, so throughput approaches the full batch ceiling, and queueing delay drops from "until the longest request ends" to "until any slot frees up".
|
| 28 |
+
|
| 29 |
+
## What limits the batch size: KV cache
|
| 30 |
+
Each running sequence holds a KV cache. For Llama 3.1 8B that is 128 KiB per token (2 x 32 layers x 8 KV heads x 128 dims x 2 bytes). On an 80 GB GPU at 90% utilization, after ~15 GiB of weights and ~2 GiB of overhead, about 50 GiB remains:
|
| 31 |
+
|
| 32 |
+
50 GiB / 128 KiB = ~410,000 tokens.
|
| 33 |
+
|
| 34 |
+
At an average of 2,000 tokens per sequence (prompt + output), that is ~200 concurrent sequences; at 8,192 tokens, ~50. This is why PagedAttention (allocating KV in small blocks on demand instead of reserving max length) matters: it lets the scheduler pack in sequences based on what they actually use.
|
| 35 |
+
|
| 36 |
+
## Chunked prefill
|
| 37 |
+
A new 8,000-token prompt can take tens of milliseconds to prefill. If it runs alone, every decoding sequence stalls for that time, which shows up as inter-token latency spikes. Chunked prefill splits the prompt into pieces (for example 512 or 2,048 tokens) and mixes each chunk with ongoing decode steps, smoothing latency.
|
| 38 |
+
|
| 39 |
+
## Tuning knobs (vLLM names)
|
| 40 |
+
- `--max-num-seqs`: upper limit on concurrent sequences.
|
| 41 |
+
- `--max-num-batched-tokens`: tokens processed per step, which bounds prefill chunk size.
|
| 42 |
+
- `--gpu-memory-utilization`: fraction of memory vLLM may use (KV cache gets what is left after weights).
|
| 43 |
+
- `--max-model-len`: maximum sequence length; lowering it does not shrink per-token KV but prevents one request from needing more cache than you can fit.
|
| 44 |
+
|
| 45 |
+
## Takeaway
|
| 46 |
+
Batching works because weights are shared across sequences; continuous batching works because it keeps the batch full. The KV cache, not compute, usually decides how full it can get.
|
| 47 |
+
|
| 48 |
+
---
|
| 49 |
+
*If you want to go deeper, the free Foundations course at [Inference Engineering Academy](https://www.inference-engineering.xyz/) covers these topics with browser labs. Disclosure: written by the academy team.*
|
articles/gpu-memory-for-70b.md
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# How much GPU memory do you need to serve a 70B model?
|
| 2 |
+
|
| 3 |
+
Short answer for Llama 3.1 70B: about **141 GB for BF16 weights alone**, so plan on 2 x 80 GB GPUs as the bare minimum and 4 x 80 GB for comfortable serving. With FP8 it squeezes onto one 80 GB GPU for light traffic; with 4-bit it fits on one 80 GB GPU (or two 48 GB GPUs) with useful KV space. Here is the full calculation so you can redo it for any model.
|
| 4 |
+
|
| 5 |
+
## Step 1: weights
|
| 6 |
+
Llama 3.1 70B has 70.6B parameters.
|
| 7 |
+
- BF16: 70.6B x 2 bytes = **141.2 GB** (131.5 GiB)
|
| 8 |
+
- FP8/INT8: 70.6B x 1 = **70.6 GB** (65.8 GiB)
|
| 9 |
+
- INT4: 70.6B x 0.5 = **35.3 GB**, plus a few percent for quantization scales
|
| 10 |
+
|
| 11 |
+
## Step 2: KV cache per token
|
| 12 |
+
From the model's config: 80 layers, 8 KV heads (grouped-query attention), head_dim 128.
|
| 13 |
+
|
| 14 |
+
KV per token = 2 x 80 x 8 x 128 x 2 bytes = 327,680 bytes = **320 KiB** (BF16), or 160 KiB with an FP8 KV cache.
|
| 15 |
+
|
| 16 |
+
Per sequence:
|
| 17 |
+
- 4,096 tokens: 1.25 GiB
|
| 18 |
+
- 8,192 tokens: 2.5 GiB
|
| 19 |
+
- 32,768 tokens: 10 GiB
|
| 20 |
+
- 128K tokens (the model's maximum, 131,072): 40 GiB
|
| 21 |
+
|
| 22 |
+
## Step 3: overhead
|
| 23 |
+
Engines reserve memory for activations, CUDA graphs, and the CUDA context. Budget roughly 1 to 3 GiB per GPU, and remember engines like vLLM only use a fraction you set (`--gpu-memory-utilization`, default 0.9).
|
| 24 |
+
|
| 25 |
+
## Step 4: put it together
|
| 26 |
+
Usable memory per 80 GB GPU at 0.9 utilization ~= 72 GB = 67 GiB, minus ~2 GiB overhead = ~65 GiB.
|
| 27 |
+
|
| 28 |
+
| Setup | Usable | Weights | Left for KV | Tokens of KV (BF16) | 8K-token sequences |
|
| 29 |
+
|---|---|---|---|---|---|
|
| 30 |
+
| 1 x 80 GB, BF16 | 65 GiB | 131.5 GiB | does not fit | - | - |
|
| 31 |
+
| 2 x 80 GB, BF16 | 130 GiB | 131.5 GiB | does not fit at 0.9 | - | - |
|
| 32 |
+
| 2 x 80 GB, BF16, util 0.95 | ~138 GiB | 131.5 GiB | ~6 GiB | ~20K | ~2 |
|
| 33 |
+
| 4 x 80 GB, BF16 | ~260 GiB | 131.5 GiB | ~129 GiB | ~420K | ~51 |
|
| 34 |
+
| 1 x 80 GB, FP8 weights + FP8 KV | ~65 GiB | 65.8 GiB | does not fit at 0.9 | - | - |
|
| 35 |
+
| 1 x 80 GB, INT4 weights | ~65 GiB | ~34 GiB | ~31 GiB | ~100K | ~12 |
|
| 36 |
+
|
| 37 |
+
(Numbers from the formulas above; "8K-token sequences" = KV left / 2.5 GiB.) The FP8 row shows why "70B in FP8 fits on one H100" is only just true: you need to raise utilization close to 1.0 and keep context short. A 141 GB H200 holds FP8 70B comfortably (~50 GiB left for KV at 0.9 utilization).
|
| 38 |
+
|
| 39 |
+
## Step 5: choose by workload
|
| 40 |
+
- **Few users, short prompts, budget-limited:** INT4 on one 80 GB GPU.
|
| 41 |
+
- **Production chat at moderate scale:** BF16 or FP8 with tensor parallelism across 4 GPUs, or FP8 on 2 GPUs.
|
| 42 |
+
- **Long context (32K+) for many users:** KV dominates; use FP8 KV cache, more GPUs, and prefix caching.
|
| 43 |
+
|
| 44 |
+
## Do it for any model
|
| 45 |
+
Read `config.json` and use:
|
| 46 |
+
- weights = params x bytes per param
|
| 47 |
+
- KV/token = 2 x num_hidden_layers x num_key_value_heads x (hidden_size / num_attention_heads) x bytes
|
| 48 |
+
- concurrent tokens = (usable memory - weights) / KV per token
|
| 49 |
+
|
| 50 |
+
Our zero-dependency calculator does this for you: [kv_calc.py](https://github.com/inference-engineering-academy/inference-engineering-notes).
|
| 51 |
+
|
| 52 |
+
---
|
| 53 |
+
*If you want to go deeper, the free Foundations course at [Inference Engineering Academy](https://www.inference-engineering.xyz/) covers these topics with browser labs. Disclosure: written by the academy team.*
|
articles/inference-engineer-roadmap.md
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Inference engineer roadmap: skills, tools, and a 12-week plan
|
| 2 |
+
|
| 3 |
+
"Inference engineer" is the person who makes a trained model cheap, fast, and reliable to serve. Training teams care about loss curves; inference teams care about time-to-first-token (TTFT), inter-token latency, throughput per GPU, and cost per million tokens. This roadmap lists what to learn, in what order, and a concrete 12-week plan.
|
| 4 |
+
|
| 5 |
+
## The core skills
|
| 6 |
+
|
| 7 |
+
**1. The math of a forward pass.** You should be able to estimate, without running anything, how many bytes and FLOPs a token costs. For a dense model, a forward pass costs roughly 2 x parameters FLOPs per token, and decode must read every weight once per step. That one fact explains most of serving performance.
|
| 8 |
+
|
| 9 |
+
**2. Memory: weights plus KV cache.** Weights are params x bytes (Llama 3.1 8B in FP16: 8.03B x 2 = ~16 GB). The KV cache is 2 x layers x kv_heads x head_dim x bytes per token (Llama 3.1 8B: 2 x 32 x 8 x 128 x 2 = 128 KiB per token). Sizing a deployment is mostly these two numbers.
|
| 10 |
+
|
| 11 |
+
**3. Prefill vs decode.** Prefill processes the whole prompt in parallel and is compute-bound. Decode generates one token per step per sequence and is memory-bandwidth-bound at small batch sizes. Batching, chunked prefill, and disaggregated serving all exist because of this split.
|
| 12 |
+
|
| 13 |
+
**4. Batching and scheduling.** Continuous (iteration-level) batching, introduced by Orca (OSDI 2022), lets new requests join a running batch every step. PagedAttention (vLLM, SOSP 2023) stores the KV cache in fixed-size blocks so memory is not wasted on padding.
|
| 14 |
+
|
| 15 |
+
**5. Quantization.** FP8, INT8, and 4-bit weight formats (AWQ, GPTQ) trade a little accuracy for less memory and bandwidth. Know which part is quantized (weights, activations, KV cache) and how to measure quality loss.
|
| 16 |
+
|
| 17 |
+
**6. Engines.** vLLM, SGLang, and TensorRT-LLM are the main open serving engines; NVIDIA Dynamo and similar systems orchestrate across many GPUs. Be able to deploy one, read its metrics, and tune it.
|
| 18 |
+
|
| 19 |
+
**7. GPU basics.** HBM bandwidth (H100 SXM: about 3.35 TB/s), tensor-core FLOPs, NVLink vs PCIe, and what tensor and pipeline parallelism cost in communication.
|
| 20 |
+
|
| 21 |
+
**8. Measurement.** Benchmarks that report TTFT, inter-token latency, and throughput at a fixed latency target, with realistic prompt/output length distributions.
|
| 22 |
+
|
| 23 |
+
## A 12-week plan (about 8 to 10 hours a week)
|
| 24 |
+
|
| 25 |
+
| Week | Focus | Deliverable |
|
| 26 |
+
|---|---|---|
|
| 27 |
+
| 1 | Transformer forward pass, FLOPs and bytes per token | A one-page estimate sheet for an 8B model |
|
| 28 |
+
| 2 | KV cache math, GQA vs MHA | A script that computes KV per token for any config.json |
|
| 29 |
+
| 3 | Prefill vs decode, roofline model | Plot measured decode tok/s vs batch size |
|
| 30 |
+
| 4 | Run vLLM locally or on a rented GPU | OpenAI-compatible endpoint serving an 8B model |
|
| 31 |
+
| 5 | Continuous batching and PagedAttention | Load test with 1, 8, 32, 64 concurrent users |
|
| 32 |
+
| 6 | Metrics: TTFT, ITL, throughput, goodput | A benchmark report with p50/p99 |
|
| 33 |
+
| 7 | Quantization: FP8, AWQ/GPTQ INT4 | Compare memory, speed, and an eval score |
|
| 34 |
+
| 8 | Prefix caching and SGLang | Measure TTFT with a shared system prompt |
|
| 35 |
+
| 9 | Speculative decoding | Measure acceptance rate and speedup on your workload |
|
| 36 |
+
| 10 | Multi-GPU: tensor parallelism | Serve a 70B model across 2 to 4 GPUs |
|
| 37 |
+
| 11 | TensorRT-LLM or Dynamo, disaggregated prefill/decode | Compare against your vLLM baseline |
|
| 38 |
+
| 12 | Capstone | A write-up: cost per million tokens for a defined SLA |
|
| 39 |
+
|
| 40 |
+
## Tips
|
| 41 |
+
|
| 42 |
+
- Always write the estimate before running the benchmark. If they disagree by more than 2x, find out why; that is where learning happens.
|
| 43 |
+
- Rent GPUs by the hour instead of buying; one week of experiments on a single 80 GB card is enough for weeks 4 to 9.
|
| 44 |
+
- Publish your benchmark reports. They double as a portfolio for inference roles.
|
| 45 |
+
|
| 46 |
+
---
|
| 47 |
+
*If you want to go deeper, the free Foundations course at [Inference Engineering Academy](https://www.inference-engineering.xyz/) covers these topics with browser labs. Disclosure: written by the academy team.*
|
articles/kv-cache-math.md
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: "KV cache math: why Llama 3.1 8B needs ~128 KB per token"
|
| 3 |
+
tags: llm, inference, gpu, machinelearning
|
| 4 |
+
---
|
| 5 |
+
|
| 6 |
+
If you serve LLMs, the KV cache, not the weights, usually decides how many users fit on one GPU. The good news is that its size is easy to calculate from `config.json`, and the calculation explains a lot of serving behaviour.
|
| 7 |
+
|
| 8 |
+
## What the KV cache stores
|
| 9 |
+
|
| 10 |
+
In every attention layer, each token produces a key vector and a value vector. During decoding, a new token's query has to attend over the keys and values of all earlier tokens. Because of the causal mask those earlier K/V vectors never change, so engines compute them once and keep them in GPU memory. That stored state is the KV cache. Without it, every decode step would recompute the whole prefix.
|
| 11 |
+
|
| 12 |
+
## The formula
|
| 13 |
+
|
| 14 |
+
```
|
| 15 |
+
bytes per token = 2 × num_layers × num_kv_heads × head_dim × bytes_per_element
|
| 16 |
+
```
|
| 17 |
+
|
| 18 |
+
- **2**: one key plus one value
|
| 19 |
+
- **num_layers**: `num_hidden_layers`
|
| 20 |
+
- **num_kv_heads**: `num_key_value_heads`. This is the number of *KV* heads, not query heads.
|
| 21 |
+
- **head_dim**: `head_dim`, or `hidden_size / num_attention_heads` if the field is missing
|
| 22 |
+
- **bytes_per_element**: 2 for BF16/FP16, 1 for FP8
|
| 23 |
+
|
| 24 |
+
## Llama 3.1 8B, worked out
|
| 25 |
+
|
| 26 |
+
From its config: 32 layers, 32 query heads, 8 KV heads (grouped-query attention), hidden size 4096, so head_dim = 4096 / 32 = 128. At BF16:
|
| 27 |
+
|
| 28 |
+
```
|
| 29 |
+
2 × 32 × 8 × 128 × 2 = 131,072 bytes = 128 KiB per token
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
Now scale it:
|
| 33 |
+
|
| 34 |
+
| Workload | KV cache |
|
| 35 |
+
|---|---|
|
| 36 |
+
| 1 request × 8,192 tokens | 1 GiB |
|
| 37 |
+
| 1 request × 131,072 tokens (full context) | 16 GiB |
|
| 38 |
+
| 32 requests × 8,192 tokens | 32 GiB |
|
| 39 |
+
|
| 40 |
+
The BF16 weights of the 8B model take about 16 GB (~15 GiB). **A single full-context request needs more memory for cache than the model needs for weights.** A model that "fits" on a 24 GB card can still go out of memory as soon as real traffic arrives.
|
| 41 |
+
|
| 42 |
+
## The most common mistake: using query heads
|
| 43 |
+
|
| 44 |
+
If you plug in 32 attention heads instead of 8 KV heads, you get 512 KiB per token, which is 4× too high. Grouped-query attention lets 4 query heads share each KV head, and that sharing is exactly why Llama 3 can offer long contexts. For Llama 3.1 70B (80 layers, 8 KV heads, head_dim 128) the same formula gives 320 KiB per token, about 40 GiB at full 128K context.
|
| 45 |
+
|
| 46 |
+
## What this means when you serve
|
| 47 |
+
|
| 48 |
+
1. **Concurrency budget.** Free memory after weights ÷ (bytes per token × average sequence length) ≈ how many requests you can hold at once. On an 80 GB GPU running the 8B model with roughly 60 GB left for cache, that's about 480K tokens in total: ~60 requests at 8K, but only 3 at full context.
|
| 49 |
+
2. **FP8 KV cache halves it.** At 1 byte per element you get 64 KiB per token. Engines like vLLM and SGLang support this; check quality on your own workload.
|
| 50 |
+
3. **Paging matters.** Engines that preallocate the maximum length waste most of this memory. PagedAttention (vLLM) and radix-tree caches (SGLang) allocate in blocks, so memory follows actual length.
|
| 51 |
+
4. **Decode speed falls with context.** Every decode step reads the whole cache for that sequence, so long contexts cost bandwidth as well as capacity.
|
| 52 |
+
|
| 53 |
+
## A quick calculator
|
| 54 |
+
|
| 55 |
+
```python
|
| 56 |
+
def kv_bytes_per_token(layers, kv_heads, head_dim, dtype_bytes=2):
|
| 57 |
+
return 2 * layers * kv_heads * head_dim * dtype_bytes
|
| 58 |
+
|
| 59 |
+
per_tok = kv_bytes_per_token(32, 8, 128) # Llama 3.1 8B
|
| 60 |
+
print(per_tok / 1024, "KiB/token") # 128.0
|
| 61 |
+
print(per_tok * 131072 / 2**30, "GiB @ 128K") # 16.0
|
| 62 |
+
```
|
| 63 |
+
|
| 64 |
+
Run this for any model before you choose a context length, a GPU, or `--max-num-seqs`.
|
| 65 |
+
|
| 66 |
+
---
|
| 67 |
+
|
| 68 |
+
*If you want to go deeper, the free Inference Engineering Foundations course at inference-engineering.xyz works through these numbers for Llama 3.1 8B with runnable NumPy code.*
|
articles/llm-inference-interview-questions.md
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LLM inference interview questions with worked answers
|
| 2 |
+
|
| 3 |
+
These questions come up in interviews for inference, ML infrastructure, and LLM platform roles. Each answer shows the reasoning, because interviewers care about the estimate more than the final number.
|
| 4 |
+
|
| 5 |
+
### 1. How big is the KV cache per token for Llama 3.1 8B?
|
| 6 |
+
Config: 32 layers, 8 KV heads (grouped-query attention), head_dim 128, FP16 (2 bytes).
|
| 7 |
+
KV per token = 2 (K and V) x 32 x 8 x 128 x 2 = 131,072 bytes = **128 KiB**.
|
| 8 |
+
An 8,192-token sequence therefore needs 128 KiB x 8,192 = 1 GiB.
|
| 9 |
+
|
| 10 |
+
### 2. Why is decode memory-bound?
|
| 11 |
+
At batch size 1, every generated token requires reading all weights from HBM. Llama 3.1 8B in FP16 is about 16 GB. On an H100 SXM (about 3.35 TB/s), the floor is 16 / 3,350 s = ~4.8 ms per token, so at most ~210 tokens/s, regardless of FLOPs. The compute needed (about 2 x 8B = 16 GFLOPs per token) takes well under 0.1 ms at the GPU's FP16 tensor throughput. Bandwidth, not compute, is the limit.
|
| 12 |
+
|
| 13 |
+
### 3. Then why does batching help?
|
| 14 |
+
The weights are read once per step and shared by every sequence in the batch. With 32 sequences, the same ~4.8 ms weight read produces 32 tokens. Throughput rises almost linearly until the KV-cache reads or compute become the bottleneck.
|
| 15 |
+
|
| 16 |
+
### 4. What is the difference between static and continuous batching?
|
| 17 |
+
Static batching waits until every sequence in the batch finishes, so short requests sit idle behind long ones. Continuous batching (Orca, OSDI 2022) schedules at each iteration: finished sequences leave and new ones join every step. This raises GPU utilization and lowers queueing delay.
|
| 18 |
+
|
| 19 |
+
### 5. What does PagedAttention solve?
|
| 20 |
+
Allocating a contiguous KV buffer for the maximum length wastes memory on sequences that end early. PagedAttention (vLLM) splits the KV cache into fixed-size blocks, like OS virtual memory pages, allocating on demand. The vLLM paper reports large reductions in KV-cache waste, which allows bigger batches.
|
| 21 |
+
|
| 22 |
+
### 6. Can a 70B model run on one 80 GB GPU?
|
| 23 |
+
In FP16: 70.6B x 2 bytes = 141 GB. No. In FP8: ~71 GB of weights leaves about 9 GB; after ~2 GB of runtime overhead that is ~7 GB of KV cache, or about 21,000 tokens at 320 KiB per token (7e9 / 327,680). Workable for low concurrency, but tight. In 4-bit: ~35 GB (plus some for scales), which fits with room for KV cache. In practice, FP16/BF16 70B is usually served with tensor parallelism on 2 to 4 GPUs (2 is very tight, 4 is comfortable).
|
| 24 |
+
|
| 25 |
+
### 7. What is TTFT and what drives it?
|
| 26 |
+
Time to first token = queueing time + prefill time (+ network). Prefill cost grows with prompt length, so long prompts and busy queues dominate. Prefix caching and chunked prefill help.
|
| 27 |
+
|
| 28 |
+
### 8. When does speculative decoding help?
|
| 29 |
+
When decode is memory-bound and the draft model's tokens are often accepted. If acceptance rate is a and you propose k tokens, the expected tokens per target step is (1 - a^(k+1)) / (1 - a) (Leviathan et al., 2023). With a = 0.8, k = 4: (1 - 0.328) / 0.2 = 3.36 tokens per step. At large batch sizes the GPU is already busy, so the gain shrinks or disappears.
|
| 30 |
+
|
| 31 |
+
### 9. How does tensor parallelism affect latency?
|
| 32 |
+
It splits each layer's matrices across GPUs, so each GPU reads fewer weight bytes per step, lowering per-token latency. It costs two all-reduces per layer, which is cheap over NVLink and expensive over PCIe.
|
| 33 |
+
|
| 34 |
+
### 10. What would you measure in a serving benchmark?
|
| 35 |
+
TTFT (p50/p99), inter-token latency (p50/p99), output tokens per second per GPU, and goodput: requests per second that meet the latency SLA. Use realistic input/output length distributions, not a single fixed length.
|
| 36 |
+
|
| 37 |
+
### 11. GQA vs MHA: why does it matter for serving?
|
| 38 |
+
Grouped-query attention shares each K/V head across several query heads. Llama 3.1 8B has 32 query heads but 8 KV heads, so its KV cache is 4x smaller than full multi-head attention would need. That means 4x more concurrent tokens in the same memory.
|
| 39 |
+
|
| 40 |
+
### 12. What does quantizing the KV cache to FP8 buy you?
|
| 41 |
+
It halves KV memory (128 KiB to 64 KiB per token for Llama 3.1 8B), so you fit about twice as many tokens in cache, which means larger batches or longer contexts. Check accuracy on long-context tasks, where errors can accumulate.
|
| 42 |
+
|
| 43 |
+
---
|
| 44 |
+
*If you want to go deeper, the free Foundations course at [Inference Engineering Academy](https://www.inference-engineering.xyz/) covers these topics with browser labs. Disclosure: written by the academy team.*
|
articles/prefill-vs-decode.md
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: "Prefill vs decode: why LLM inference is memory-bandwidth bound"
|
| 3 |
+
tags: llm, inference, gpu, performance
|
| 4 |
+
---
|
| 5 |
+
|
| 6 |
+
Ask why an LLM streams its answer at a steady ~100 tokens/s even on a GPU rated for nearly a petaFLOP, and you end up at one idea: generation has two phases with very different bottlenecks.
|
| 7 |
+
|
| 8 |
+
## Two phases
|
| 9 |
+
|
| 10 |
+
**Prefill** runs the whole prompt through the model in one forward pass. Every prompt token is processed in parallel, so each layer does matrix × matrix multiplications. Prefill fills the KV cache and produces the first output token, so it drives **time to first token (TTFT)**.
|
| 11 |
+
|
| 12 |
+
**Decode** then generates one token per step. Each step pushes a single new token (per sequence) through every layer and attends over the cached K/V. Decode drives **time per output token (TPOT)**, also called inter-token latency.
|
| 13 |
+
|
| 14 |
+
## Arithmetic intensity
|
| 15 |
+
|
| 16 |
+
A GPU is limited either by how fast it can compute (FLOP/s) or by how fast it can read memory (bytes/s). The ratio that decides which one applies is **arithmetic intensity**: FLOPs done per byte moved.
|
| 17 |
+
|
| 18 |
+
An H100 SXM offers roughly 989 TFLOP/s of dense BF16 and about 3.35 TB/s of HBM bandwidth. The break-even point (the "ridge" of the roofline) is about 989e12 / 3.35e12 ≈ **295 FLOPs per byte**. Below that, the work is memory-bound.
|
| 19 |
+
|
| 20 |
+
For a matrix multiply against a weight matrix, each BF16 weight (2 bytes) gets used for 2 FLOPs (multiply + add) per token in the batch:
|
| 21 |
+
|
| 22 |
+
- **Decode, batch 1:** ~2 FLOPs per 2 bytes ≈ **1 FLOP/byte**, far below 295. The GPU spends most of its time waiting for weights to arrive from HBM.
|
| 23 |
+
- **Prefill, 2,000-token prompt:** each weight is reused for 2,000 tokens, so ≈ **2,000 FLOPs/byte**, well above the ridge. That's compute-bound.
|
| 24 |
+
|
| 25 |
+
## Back-of-envelope decode speed
|
| 26 |
+
|
| 27 |
+
Llama 3.1 8B in BF16 is about 16 GB of weights. Every decode step has to read all of them at least once:
|
| 28 |
+
|
| 29 |
+
```
|
| 30 |
+
16 GB / 3.35 TB/s ≈ 4.8 ms per step → ≈ 200 tokens/s upper bound (batch 1)
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
Real numbers come in lower because of KV-cache reads, kernel overheads and imperfect bandwidth use. Notice that FLOPs never showed up in that estimate. **For single-stream decode, memory bandwidth sets the speed.**
|
| 34 |
+
|
| 35 |
+
## Why batching is the main lever
|
| 36 |
+
|
| 37 |
+
If 32 sequences decode together, the weights are read once per step and used 32 times. Intensity rises about 32×, so throughput rises almost linearly while per-step latency barely moves. That's why serving engines use **continuous batching**: they admit new requests into the running batch at every step instead of waiting for a whole batch to finish.
|
| 38 |
+
|
| 39 |
+
There's a catch. Weights are shared across the batch, but **KV cache is not**: each sequence reads its own cache on every step. As batch size and context grow, cache reads take over and decode stays memory-bound. This is why KV-cache size (128 KiB/token for Llama 3.1 8B in BF16) matters for speed as well as capacity.
|
| 40 |
+
|
| 41 |
+
## What follows from this
|
| 42 |
+
|
| 43 |
+
- **Quantizing weights speeds up decode** because there are fewer bytes to read. INT4/FP8 weights help decode more than they help prefill.
|
| 44 |
+
- **Speculative decoding** uses spare compute: a small draft model proposes several tokens and the big model checks them in one pass, which is more work per byte read.
|
| 45 |
+
- **Chunked prefill** splits long prompts into pieces so a big prefill doesn't stall everyone else's decode steps.
|
| 46 |
+
- **Prefill/decode disaggregation** (as in NVIDIA Dynamo, and supported by vLLM and SGLang) runs the two phases on separate GPU pools, because they want different hardware and different batch sizes.
|
| 47 |
+
- **Measure TTFT and TPOT separately.** A change that helps one often hurts the other.
|
| 48 |
+
|
| 49 |
+
## Summary
|
| 50 |
+
|
| 51 |
+
Prefill is a big parallel matrix multiply and is compute-bound. Decode reads every weight and the whole KV cache to produce one token, so it is memory-bandwidth-bound. Almost every serving optimization (batching, quantization, paging, speculation, disaggregation) is a way of getting more useful tokens out of each byte read from memory.
|
| 52 |
+
|
| 53 |
+
---
|
| 54 |
+
|
| 55 |
+
*If you'd like to work through these numbers yourself, the free Inference Engineering Foundations course at inference-engineering.xyz covers prefill, decode and the KV cache with runnable code.*
|
articles/quantization-for-serving.md
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Quantization for serving: FP8, INT8, INT4 tradeoffs
|
| 2 |
+
|
| 3 |
+
Quantization stores numbers in fewer bits. For serving, it does two things: it shrinks memory (more room for KV cache, fewer GPUs) and it cuts the bytes read per decode step (faster tokens when memory-bound). The question is always what you are quantizing and what it costs in quality.
|
| 4 |
+
|
| 5 |
+
## Three things you can quantize
|
| 6 |
+
1. **Weights only** (W4A16, W8A16): weights stored in 4 or 8 bits, dequantized to 16-bit for the matmul. Saves memory and bandwidth; compute stays 16-bit. Examples: AWQ, GPTQ.
|
| 7 |
+
2. **Weights and activations** (W8A8 in FP8 or INT8): matmuls run in 8-bit on tensor cores. Saves memory, bandwidth, and compute. Needs hardware support (FP8 tensor cores arrived with Hopper/Ada).
|
| 8 |
+
3. **KV cache** (FP8 KV): halves KV memory, so more concurrent tokens fit.
|
| 9 |
+
|
| 10 |
+
## The memory math (Llama 3.1 70B, 70.6B params)
|
| 11 |
+
| Format | Bytes/param | Weights |
|
| 12 |
+
|---|---|---|
|
| 13 |
+
| BF16 | 2 | 141 GB |
|
| 14 |
+
| FP8 / INT8 | 1 | 71 GB |
|
| 15 |
+
| INT4 | 0.5 (+ scales) | ~35 GB + a few % for scales |
|
| 16 |
+
|
| 17 |
+
So BF16 needs at least two 80 GB GPUs (and really four for useful KV space), FP8 just fits on one with little KV room, and INT4 fits on one with plenty of room.
|
| 18 |
+
|
| 19 |
+
## Speed: what to expect
|
| 20 |
+
At small batch sizes decode is bandwidth-bound, so halving weight bytes can approach ~2x faster decode in the ideal case, and 4-bit can approach ~4x vs 16-bit. Real gains are lower because of dequantization overhead, KV-cache reads, and kernels that are not perfectly efficient.
|
| 21 |
+
|
| 22 |
+
At large batch sizes decode becomes more compute-bound. Weight-only INT4 then helps less, and can even be slower than FP8 because the dequantize step adds work. W8A8 FP8 keeps helping because the matmuls themselves get faster on FP8 tensor cores.
|
| 23 |
+
|
| 24 |
+
Rule of thumb:
|
| 25 |
+
- **Low concurrency, latency-sensitive, or memory-starved:** weight-only INT4 (AWQ/GPTQ).
|
| 26 |
+
- **High throughput on Hopper or newer:** FP8 W8A8.
|
| 27 |
+
- **Older GPUs without FP8 (A100):** INT8 W8A8 (SmoothQuant-style) or INT4 weight-only.
|
| 28 |
+
|
| 29 |
+
## FP8 vs INT8
|
| 30 |
+
Both use 8 bits. INT8 is a uniform grid; FP8 (E4M3 for inference) has an exponent, giving more resolution near zero and a wider dynamic range. LLM activations have outliers, so FP8 usually needs less calibration effort than INT8 for the same quality. Many teams report near-baseline quality for FP8 on large models, but always verify on your own evals.
|
| 31 |
+
|
| 32 |
+
## Quality: how to check
|
| 33 |
+
- Run task evals you care about (your own test set first, then standard benchmarks such as MMLU or GSM8K).
|
| 34 |
+
- Check long-context and reasoning tasks separately; errors from quantized KV cache can accumulate over long sequences.
|
| 35 |
+
- Compare outputs on real prompts side by side; perplexity alone can hide regressions.
|
| 36 |
+
- Smaller models usually lose more quality from 4-bit than large ones.
|
| 37 |
+
|
| 38 |
+
## KV-cache quantization
|
| 39 |
+
For Llama 3.1 70B, KV per token is 2 x 80 layers x 8 KV heads x 128 x 2 bytes = 320 KiB in FP16, and 160 KiB in FP8. On a deployment with 40 GiB free for KV, that is about 131,000 tokens in FP16 vs about 262,000 in FP8, which roughly doubles how many long conversations you can serve at once.
|
| 40 |
+
|
| 41 |
+
## Practical checklist
|
| 42 |
+
1. Prefer a published, pre-quantized checkpoint from the model vendor or a trusted source.
|
| 43 |
+
2. Confirm your engine and GPU support the format with fast kernels (otherwise it may be slower than BF16).
|
| 44 |
+
3. Benchmark at your real concurrency, not just batch 1.
|
| 45 |
+
4. Run evals before and after; set a quality budget in advance.
|
| 46 |
+
5. Quantize the KV cache separately and test long contexts.
|
| 47 |
+
|
| 48 |
+
---
|
| 49 |
+
*If you want to go deeper, the free Foundations course at [Inference Engineering Academy](https://www.inference-engineering.xyz/) covers these topics with browser labs. Disclosure: written by the academy team.*
|
articles/speculative-decoding.md
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Speculative decoding: when it helps and when it doesn't
|
| 2 |
+
|
| 3 |
+
Speculative decoding speeds up generation without changing the output distribution. It works by guessing several tokens cheaply and verifying them all with one pass of the big model. It is not a free lunch, and knowing when it backfires matters as much as knowing how it works.
|
| 4 |
+
|
| 5 |
+
## How it works
|
| 6 |
+
1. A cheap **draft** proposes k tokens (a small model, extra heads like Medusa/EAGLE, or n-gram lookup from the prompt).
|
| 7 |
+
2. The **target** model processes all k proposals in one forward pass, the same cost profile as a short prefill.
|
| 8 |
+
3. Proposals are accepted left to right using a rejection-sampling rule (Leviathan et al., 2023; Chen et al., 2023) that guarantees the output follows the target model's distribution. At the first rejection, the target supplies a corrected token.
|
| 9 |
+
|
| 10 |
+
So each target pass yields between 1 and k + 1 tokens.
|
| 11 |
+
|
| 12 |
+
## Why it can be faster
|
| 13 |
+
At small batch sizes, a decode step is memory-bandwidth-bound: the GPU spends its time reading weights, not computing. Verifying 5 tokens costs nearly the same as generating 1, because the weights are read once either way. If several are accepted, you get several tokens for about the price of one.
|
| 14 |
+
|
| 15 |
+
## The expected speedup
|
| 16 |
+
If each draft token is accepted with probability a (assumed independent), the expected tokens per target pass with k drafts is
|
| 17 |
+
|
| 18 |
+
E = (1 - a^(k+1)) / (1 - a)
|
| 19 |
+
|
| 20 |
+
| a | k = 2 | k = 4 | k = 8 |
|
| 21 |
+
|---|---|---|---|
|
| 22 |
+
| 0.5 | 1.75 | 1.94 | 2.00 |
|
| 23 |
+
| 0.7 | 2.19 | 2.77 | 3.20 |
|
| 24 |
+
| 0.8 | 2.44 | 3.36 | 4.33 |
|
| 25 |
+
| 0.9 | 2.71 | 4.10 | 6.13 |
|
| 26 |
+
|
| 27 |
+
Example: a = 0.8, k = 4 gives (1 - 0.8^5) / 0.2 = (1 - 0.328) / 0.2 = 3.36.
|
| 28 |
+
|
| 29 |
+
Wall-clock speedup is lower than E, because each step also pays for the draft and for a verification pass that is slightly more expensive than a normal decode. If drafting costs c (relative to one target step) per draft token, a rough estimate is speedup = E / (1 + k x c + verification overhead).
|
| 30 |
+
|
| 31 |
+
## When it helps
|
| 32 |
+
- **Low concurrency, latency-sensitive traffic** (chat with few simultaneous users, coding assistants).
|
| 33 |
+
- **Predictable text:** code, structured output, summaries and edits that copy from the prompt. N-gram/prompt-lookup drafting is very effective when outputs repeat input text.
|
| 34 |
+
- **A well-matched draft:** same tokenizer, trained on similar data, or heads trained on the target (EAGLE-style), which raise a.
|
| 35 |
+
|
| 36 |
+
## When it doesn't
|
| 37 |
+
- **High batch sizes.** When the batch already fills the GPU, decode is closer to compute-bound and extra verification tokens are no longer nearly free. Many engines see speedups shrink toward zero, or become slowdowns, as concurrency rises.
|
| 38 |
+
- **Low acceptance:** creative writing at high temperature, or a draft that disagrees often. With a = 0.5, you never exceed 2 tokens per pass regardless of k.
|
| 39 |
+
- **Too large k:** gains saturate (see the table) while draft and verify costs keep growing.
|
| 40 |
+
- **Memory-tight deployments:** a draft model needs its own weights and KV cache, taking room from the batch.
|
| 41 |
+
|
| 42 |
+
## How to evaluate it
|
| 43 |
+
1. Measure acceptance rate on real prompts, not benchmarks.
|
| 44 |
+
2. Sweep k (2 to 6 is typical) and concurrency (1, 8, 32, 64).
|
| 45 |
+
3. Report inter-token latency and throughput at each point. Expect a crossover concurrency where speculation stops paying off.
|
| 46 |
+
4. Enable it only below that crossover, or use an engine that adapts automatically.
|
| 47 |
+
|
| 48 |
+
## Takeaway
|
| 49 |
+
Speculative decoding trades spare compute for fewer sequential steps. It shines when compute is idle (small batches) and drafts are accurate; it fades when the GPU is already busy.
|
| 50 |
+
|
| 51 |
+
---
|
| 52 |
+
*If you want to go deeper, the free Foundations course at [Inference Engineering Academy](https://www.inference-engineering.xyz/) covers these topics with browser labs. Disclosure: written by the academy team.*
|
articles/ttft-vs-tokens-per-second.md
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Time-to-first-token vs tokens-per-second: what to measure
|
| 2 |
+
|
| 3 |
+
"How fast is it?" has at least four different answers for an LLM server. Picking the wrong one leads to optimizing the wrong thing. Here are the metrics, what drives each, and how to measure them honestly.
|
| 4 |
+
|
| 5 |
+
## The metrics
|
| 6 |
+
**Time to first token (TTFT).** From request sent to first output token received. Equals network + queueing + prefill. This is what a chat user feels as "responsiveness".
|
| 7 |
+
|
| 8 |
+
**Inter-token latency (ITL), also called time per output token (TPOT).** Average gap between output tokens after the first. This is the perceived streaming speed. 1 / ITL is the per-user tokens per second.
|
| 9 |
+
|
| 10 |
+
**End-to-end latency.** TTFT + (output tokens - 1) x ITL. For a 500-token answer with TTFT 300 ms and ITL 25 ms: 0.3 + 499 x 0.025 = **12.8 s**.
|
| 11 |
+
|
| 12 |
+
**Throughput.** Total output tokens per second across all users, usually per GPU. This is what drives cost.
|
| 13 |
+
|
| 14 |
+
**Goodput.** Requests per second that meet your latency targets (for example TTFT p99 < 1 s and ITL p99 < 50 ms). The most useful single number for capacity planning, because throughput at unacceptable latency is worthless.
|
| 15 |
+
|
| 16 |
+
## What drives each
|
| 17 |
+
| Metric | Main drivers | Typical fixes |
|
| 18 |
+
|---|---|---|
|
| 19 |
+
| TTFT | prompt length, queue depth, prefill compute | prefix caching, chunked prefill, more replicas, disaggregated prefill |
|
| 20 |
+
| ITL | weight bytes per step, batch size, KV reads | quantization, tensor parallelism, speculative decoding (small batches) |
|
| 21 |
+
| Throughput | batch size, KV-cache capacity | continuous batching, FP8 KV cache, more memory |
|
| 22 |
+
|
| 23 |
+
## The core tradeoff
|
| 24 |
+
Bigger batches raise throughput but also raise ITL, because each step does more work. For a memory-bound decode on Llama 3.1 8B (BF16, ~16 GB of weights) on an H100 SXM (~3.35 TB/s), the weight read alone is ~4.8 ms per step. At batch 1 that is ~210 tok/s for one user. At batch 64 each step also reads 64 sequences' KV caches and does 64x the compute, so ITL might rise to, say, 15 to 25 ms (40 to 65 tok/s per user) while total throughput rises to thousands of tokens/s. The exact numbers depend on engine and context length; measure them.
|
| 25 |
+
|
| 26 |
+
Similarly, admitting a long prompt helps throughput but its prefill can stall decodes, spiking ITL for everyone else. Chunked prefill exists to manage this.
|
| 27 |
+
|
| 28 |
+
## Which metric for which product
|
| 29 |
+
- **Chat UI:** TTFT p99 under ~1 s and ITL fast enough to exceed reading speed. Reading runs at a few tokens per second, so ~20+ tok/s per user (ITL under ~50 ms) usually feels fast.
|
| 30 |
+
- **Agents and tool calls:** end-to-end latency, because nobody reads the stream; each step blocks the next.
|
| 31 |
+
- **Batch/offline jobs (evals, synthetic data):** throughput and cost per million tokens only.
|
| 32 |
+
- **Voice:** TTFT is critical; aim for a few hundred milliseconds.
|
| 33 |
+
|
| 34 |
+
## How to measure honestly
|
| 35 |
+
1. **Use realistic lengths.** Sample input/output lengths from production logs. A benchmark with 128-token prompts says little about a RAG app with 6,000-token prompts.
|
| 36 |
+
2. **Measure at the client,** with streaming on, so you include tokenization, queueing, and network.
|
| 37 |
+
3. **Report percentiles,** at least p50 and p99. Averages hide tail stalls.
|
| 38 |
+
4. **Sweep load.** Plot ITL p99 and TTFT p99 against request rate; find the knee where they blow up. Your capacity is just below it.
|
| 39 |
+
5. **Use an open-loop load generator** (requests arrive at a set rate, e.g. Poisson) rather than a fixed number of users who wait for replies, which hides queueing.
|
| 40 |
+
6. **Fix the output length** with `ignore_eos` or `max_tokens` when comparing engines, so one model does not "win" by writing shorter answers.
|
| 41 |
+
7. **Write down versions and flags.** Engines change fast.
|
| 42 |
+
|
| 43 |
+
## Cost from throughput
|
| 44 |
+
Cost per million output tokens = (GPU $/hour) / (tokens per second x 3,600) x 1,000,000. At $2.50/hour and 2,500 tok/s: 2.50 / 9,000,000 x 1,000,000 = **$0.28 per million tokens**, but only at the latency that throughput was measured at. Always state both.
|
| 45 |
+
|
| 46 |
+
---
|
| 47 |
+
*If you want to go deeper, the free Foundations course at [Inference Engineering Academy](https://www.inference-engineering.xyz/) covers these topics with browser labs. Disclosure: written by the academy team.*
|
articles/vllm-vs-sglang-vs-tensorrt-llm.md
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# vLLM vs SGLang vs TensorRT-LLM: when to pick which
|
| 2 |
+
|
| 3 |
+
All three are open-source LLM serving engines with continuous batching, tensor parallelism, quantization support, and OpenAI-compatible APIs. Their strengths differ, and all three ship new releases often, so treat this as a decision framework and benchmark on your own workload before committing.
|
| 4 |
+
|
| 5 |
+
## vLLM
|
| 6 |
+
**Origin:** UC Berkeley, now a large community project (Apache 2.0).
|
| 7 |
+
**Signature idea:** PagedAttention, which stores the KV cache in fixed-size blocks to avoid fragmentation and enable large batches.
|
| 8 |
+
**Strengths:**
|
| 9 |
+
- Broadest model coverage; new open models usually get vLLM support quickly.
|
| 10 |
+
- Runs on NVIDIA, AMD, and other accelerators.
|
| 11 |
+
- Simple to start: `vllm serve <model>` gives an OpenAI-compatible server.
|
| 12 |
+
- Prefix caching, chunked prefill, speculative decoding, LoRA serving, many quantization formats.
|
| 13 |
+
|
| 14 |
+
**Pick it when:** you want the safest default, need to serve many different models, or need non-NVIDIA hardware.
|
| 15 |
+
|
| 16 |
+
## SGLang
|
| 17 |
+
**Origin:** LMSYS / UC Berkeley researchers (Apache 2.0).
|
| 18 |
+
**Signature idea:** RadixAttention, which keeps KV cache for shared prefixes in a radix tree and reuses it automatically across requests. It also has a frontend language for structured, multi-call LLM programs.
|
| 19 |
+
**Strengths:**
|
| 20 |
+
- Excellent when many requests share prefixes: long system prompts, few-shot examples, multi-turn chat, agents, and tree-of-thought style branching.
|
| 21 |
+
- Fast constrained decoding (JSON schemas, regex).
|
| 22 |
+
- Strong performance on large mixture-of-experts models such as DeepSeek.
|
| 23 |
+
|
| 24 |
+
**Pick it when:** your traffic has heavy prefix reuse (agents, RAG with fixed templates, chat), or you rely on structured output.
|
| 25 |
+
|
| 26 |
+
## TensorRT-LLM
|
| 27 |
+
**Origin:** NVIDIA (Apache 2.0).
|
| 28 |
+
**Signature idea:** models built into optimized engines using NVIDIA's kernels, with in-flight batching, FP8 and FP4 paths on recent GPUs.
|
| 29 |
+
**Strengths:**
|
| 30 |
+
- Often the highest raw performance on NVIDIA hardware, especially with FP8 on Hopper and FP4 on Blackwell.
|
| 31 |
+
- Tight integration with Triton Inference Server and NVIDIA Dynamo.
|
| 32 |
+
|
| 33 |
+
**Costs:** NVIDIA-only; historically more setup (engine builds, version pinning), although newer releases have a PyTorch-based workflow that reduces this.
|
| 34 |
+
|
| 35 |
+
**Pick it when:** you are all-in on NVIDIA, serving a small number of models at high volume, and the last 10 to 30% of efficiency is worth engineering time.
|
| 36 |
+
|
| 37 |
+
## Decision table
|
| 38 |
+
|
| 39 |
+
| Situation | First choice |
|
| 40 |
+
|---|---|
|
| 41 |
+
| Prototype, many models, mixed hardware | vLLM |
|
| 42 |
+
| Agents, multi-turn chat, shared system prompts | SGLang |
|
| 43 |
+
| One model, huge volume, NVIDIA only | TensorRT-LLM |
|
| 44 |
+
| Structured JSON output at scale | SGLang (vLLM also supports it) |
|
| 45 |
+
| AMD GPUs | vLLM or SGLang |
|
| 46 |
+
|
| 47 |
+
## How to benchmark fairly
|
| 48 |
+
1. Use the same model weights and precision in each engine (for example BF16, or the same FP8 checkpoint).
|
| 49 |
+
2. Replay a realistic distribution of input and output lengths, ideally sampled from your logs.
|
| 50 |
+
3. Sweep concurrency (1, 8, 32, 128) and report TTFT p50/p99, inter-token latency p50/p99, and output tokens/s.
|
| 51 |
+
4. Compare at a fixed latency SLA ("max throughput with p99 ITL under 50 ms"), not at peak throughput alone.
|
| 52 |
+
5. Enable each engine's equivalent features (prefix caching, CUDA graphs) or disable them all.
|
| 53 |
+
6. Record versions. Results from six months ago are often out of date.
|
| 54 |
+
|
| 55 |
+
## A common pattern
|
| 56 |
+
Many teams start on vLLM, move prefix-heavy workloads to SGLang, and adopt TensorRT-LLM for their highest-volume model once the traffic shape is stable. Because all three expose an OpenAI-compatible API, switching is mostly an operations change, not an application rewrite.
|
| 57 |
+
|
| 58 |
+
---
|
| 59 |
+
*If you want to go deeper, the free Foundations course at [Inference Engineering Academy](https://www.inference-engineering.xyz/) covers these topics with browser labs. Disclosure: written by the academy team.*
|
calculator/README.md
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# kv_calc.py: KV-cache and GPU memory calculator
|
| 2 |
+
|
| 3 |
+
A single-file Python script (no dependencies) that answers: *will this model fit, and how many concurrent requests can I serve?*
|
| 4 |
+
|
| 5 |
+
## Formula
|
| 6 |
+
```
|
| 7 |
+
KV bytes per token = 2 (K and V) x layers x kv_heads x head_dim x bytes_per_element
|
| 8 |
+
weights bytes = params x bits / 8
|
| 9 |
+
```
|
| 10 |
+
Example, Llama 3.1 8B in FP16: 2 x 32 x 8 x 128 x 2 = 131,072 bytes = **128 KiB per token**, so an 8,192-token sequence holds 1 GiB of KV cache.
|
| 11 |
+
|
| 12 |
+
## Built-in models (from each model's public `config.json`)
|
| 13 |
+
| model | params | layers | kv_heads | head_dim | KV/token (FP16) |
|
| 14 |
+
|---|---|---|---|---|---|
|
| 15 |
+
| llama-3.1-8b | 8.03B | 32 | 8 | 128 | 128 KiB |
|
| 16 |
+
| llama-3.1-70b | 70.6B | 80 | 8 | 128 | 320 KiB |
|
| 17 |
+
| llama-3.1-405b | 405.9B | 126 | 8 | 128 | 504 KiB |
|
| 18 |
+
| mistral-7b-v0.1 | 7.24B | 32 | 8 | 128 | 128 KiB |
|
| 19 |
+
| qwen2.5-7b | 7.62B | 28 | 4 | 128 | 56 KiB |
|
| 20 |
+
| qwen2.5-72b | 72.7B | 80 | 8 | 128 | 320 KiB |
|
| 21 |
+
|
| 22 |
+
Any other model: pass `--params-b --layers --kv-heads --head-dim`.
|
| 23 |
+
|
| 24 |
+
## Usage
|
| 25 |
+
```
|
| 26 |
+
python3 kv_calc.py --list
|
| 27 |
+
python3 kv_calc.py --model llama-3.1-8b --ctx 8192 --batch 16 --gpu-gb 80
|
| 28 |
+
python3 kv_calc.py --model llama-3.1-70b --tp 4 --ctx 8192 --batch 32
|
| 29 |
+
python3 kv_calc.py --model llama-3.1-70b --wbits 4 --kvbits 8 --gpu-gb 80
|
| 30 |
+
```
|
| 31 |
+
Sample output (Llama 3.1 8B, one 80 GB GPU, 0.9 utilization):
|
| 32 |
+
```
|
| 33 |
+
KV cache per token : 128.0 KiB
|
| 34 |
+
Weights : 15.0 GiB (16-bit)
|
| 35 |
+
Left for KV : 50.1 GiB -> 410,404 tokens total
|
| 36 |
+
Max concurrent seqs at 8192 ctx: 50
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
## Caveats
|
| 40 |
+
- `--overhead-gib` (default 2 GiB per GPU) is a rough allowance for activations, CUDA graphs and context; real numbers depend on engine and settings.
|
| 41 |
+
- GPU sizes are vendor GB (1e9 bytes); outputs are GiB (2^30).
|
| 42 |
+
- Ignores sliding-window attention, MLA (DeepSeek) and prefix-cache sharing, which all reduce KV use.
|
| 43 |
+
|
| 44 |
+
Learn the reasoning behind these numbers in the free Foundations course at [Inference Engineering Academy](https://www.inference-engineering.xyz/).
|
calculator/kv_calc.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""KV-cache and GPU memory calculator for LLM serving. No dependencies.
|
| 3 |
+
Configs are taken from each model's public config.json on Hugging Face
|
| 4 |
+
(num_hidden_layers, num_key_value_heads, head_dim = hidden_size / num_attention_heads).
|
| 5 |
+
Usage:
|
| 6 |
+
python3 kv_calc.py --model llama-3.1-8b --ctx 8192 --batch 16 --wbits 16 --kvbits 16 --gpu-gb 80
|
| 7 |
+
python3 kv_calc.py --list
|
| 8 |
+
"""
|
| 9 |
+
import argparse
|
| 10 |
+
|
| 11 |
+
# name: (params_billion, layers, kv_heads, head_dim)
|
| 12 |
+
MODELS = {
|
| 13 |
+
"llama-3.1-8b": (8.03, 32, 8, 128),
|
| 14 |
+
"llama-3.1-70b": (70.6, 80, 8, 128),
|
| 15 |
+
"llama-3.1-405b": (405.9, 126, 8, 128),
|
| 16 |
+
"mistral-7b-v0.1": (7.24, 32, 8, 128),
|
| 17 |
+
"qwen2.5-7b": (7.62, 28, 4, 128),
|
| 18 |
+
"qwen2.5-72b": (72.7, 80, 8, 128),
|
| 19 |
+
}
|
| 20 |
+
GiB = 1024 ** 3
|
| 21 |
+
|
| 22 |
+
def kv_bytes_per_token(layers, kv_heads, head_dim, kvbits):
|
| 23 |
+
# 2 tensors (K and V) per layer
|
| 24 |
+
return 2 * layers * kv_heads * head_dim * kvbits / 8
|
| 25 |
+
|
| 26 |
+
def main():
|
| 27 |
+
p = argparse.ArgumentParser()
|
| 28 |
+
p.add_argument("--model", default="llama-3.1-8b")
|
| 29 |
+
p.add_argument("--layers", type=int); p.add_argument("--kv-heads", type=int)
|
| 30 |
+
p.add_argument("--head-dim", type=int); p.add_argument("--params-b", type=float)
|
| 31 |
+
p.add_argument("--ctx", type=int, default=8192, help="tokens per sequence (prompt+output)")
|
| 32 |
+
p.add_argument("--batch", type=int, default=1, help="concurrent sequences")
|
| 33 |
+
p.add_argument("--wbits", type=int, default=16, help="weight bits: 16, 8, 4")
|
| 34 |
+
p.add_argument("--kvbits", type=int, default=16, help="KV cache bits: 16 or 8")
|
| 35 |
+
p.add_argument("--gpu-gb", type=float, default=80, help="memory per GPU in GB (vendor GB = 1e9)")
|
| 36 |
+
p.add_argument("--tp", type=int, default=1, help="tensor-parallel GPUs")
|
| 37 |
+
p.add_argument("--util", type=float, default=0.9, help="fraction of memory usable (vLLM gpu_memory_utilization)")
|
| 38 |
+
p.add_argument("--overhead-gib", type=float, default=2.0, help="per-GPU activations/CUDA context guess")
|
| 39 |
+
p.add_argument("--list", action="store_true")
|
| 40 |
+
a = p.parse_args()
|
| 41 |
+
if a.list:
|
| 42 |
+
for k, v in MODELS.items():
|
| 43 |
+
print(f"{k:16s} params={v[0]}B layers={v[1]} kv_heads={v[2]} head_dim={v[3]}")
|
| 44 |
+
return
|
| 45 |
+
params, layers, kvh, hd = MODELS.get(a.model, (None,)*4)
|
| 46 |
+
params = a.params_b or params; layers = a.layers or layers
|
| 47 |
+
kvh = a.kv_heads or kvh; hd = a.head_dim or hd
|
| 48 |
+
if None in (params, layers, kvh, hd):
|
| 49 |
+
p.error("unknown model: pass --params-b --layers --kv-heads --head-dim")
|
| 50 |
+
per_tok = kv_bytes_per_token(layers, kvh, hd, a.kvbits)
|
| 51 |
+
weights = params * 1e9 * a.wbits / 8
|
| 52 |
+
kv_total = per_tok * a.ctx * a.batch
|
| 53 |
+
usable = a.gpu_gb * 1e9 * a.util * a.tp - a.overhead_gib * GiB * a.tp
|
| 54 |
+
free_for_kv = usable - weights
|
| 55 |
+
print(f"KV cache per token : {per_tok/1024:.1f} KiB")
|
| 56 |
+
print(f"KV per sequence : {per_tok*a.ctx/GiB:.2f} GiB at {a.ctx} tokens")
|
| 57 |
+
print(f"KV for batch {a.batch:<5} : {kv_total/GiB:.2f} GiB")
|
| 58 |
+
print(f"Weights : {weights/GiB:.1f} GiB ({a.wbits}-bit)")
|
| 59 |
+
print(f"Usable memory : {usable/GiB:.1f} GiB across {a.tp} GPU(s)")
|
| 60 |
+
if free_for_kv <= 0:
|
| 61 |
+
print("Weights do not fit. Use more GPUs (--tp) or lower --wbits."); return
|
| 62 |
+
print(f"Left for KV : {free_for_kv/GiB:.1f} GiB -> {int(free_for_kv/per_tok):,} tokens total")
|
| 63 |
+
print(f"Max concurrent seqs at {a.ctx} ctx: {int(free_for_kv/(per_tok*a.ctx))}")
|
| 64 |
+
print("FITS" if kv_total <= free_for_kv else "DOES NOT FIT at this batch/ctx")
|
| 65 |
+
|
| 66 |
+
if __name__ == "__main__":
|
| 67 |
+
main()
|