GPU sizing and memory math for serving a model
"How many GPUs do I need?" is the first question every team asks when they decide to self-host, and the answer is almost always found with arithmetic you can do on a whiteboard in ten minutes. You need four numbers: the bytes for the weights, the bytes per token of KV cache, how many tokens you need to hold at once, and the memory bandwidth of the GPU. This doc walks through the formulas and a worked example, using architecture numbers from a model's own config rather than anyone's benchmark.
Why it matters
GPUs are the most expensive line item in self-hosted AI, and both mistakes hurt. Undersize and you hit out-of-memory errors, preemptions and latency spikes at the first traffic peak. Oversize and you pay for idle silicon. Doing the math first also tells you which levers matter: whether quantization, a shorter context limit, or a model with grouped-query attention would let you drop a GPU.
How it works
1. Weights
weight_bytes ≈ num_parameters × bytes_per_parameter
Bytes per parameter: 2 for BF16 or FP16, 1 for FP8 or INT8, about 0.5 for 4-bit (plus a little for scales and zero points). So a 70B model is roughly 140 GB in BF16, 70 GB in FP8, and around 35 to 40 GB in 4-bit. For mixture-of-experts models, use total parameters for memory (all experts must be resident) but active parameters when estimating compute per token.
2. KV cache per token
From the model's config.json:
kv_bytes_per_token = 2 × num_hidden_layers × num_key_value_heads × head_dim × kv_bytes_per_element
head_dim = hidden_size / num_attention_heads (unless config gives head_dim)
Worked example for a Llama 3.1 70B style config (80 layers, 8 KV heads, head dimension 128) with a 16-bit cache:
2 × 80 × 8 × 128 × 2 = 327,680 bytes ≈ 320 KiB per token
With an FP8 KV cache, halve it to about 160 KiB.
3. Tokens you must hold at once
kv_tokens_needed = concurrent_sequences × average_tokens_per_sequence
kv_bytes_needed = kv_tokens_needed × kv_bytes_per_token
Use the average context (prompt plus generated so far) at peak, not the maximum, because paged KV caches allocate on demand. But keep headroom for the long tail.
4. Total memory
gpu_memory_needed ≈ weight_bytes + kv_bytes_needed + activation_and_runtime_overhead
Overhead (activations, CUDA graphs, framework buffers) is usually a modest slice; engines measure it at startup. A practical approach is to plan for the engine using around 90 percent of each GPU and to treat the remaining tenth as safety margin.
5. Decode speed ceiling
per_step_seconds ≈ (weight_bytes_per_gpu + kv_bytes_read_per_step_per_gpu) / gpu_memory_bandwidth
tokens_per_second_per_stream ≲ 1 / per_step_seconds
aggregate_tokens_per_second ≲ batch_size / per_step_seconds
This is an upper bound: real kernels reach only part of peak bandwidth, and communication between GPUs adds time. It still tells you whether a latency target is even possible on a given card. Read the bandwidth from the GPU vendor's spec sheet.
Rendering diagram…
Reference architecture
Worked sizing for a hypothetical internal assistant on a 70B-class model:
- Peak concurrency: 64 active streams.
- Average live context at peak: 6,000 tokens.
- KV in FP8: about 160 KiB per token.
- KV needed: 64 × 6,000 × 160 KiB ≈ 59 GiB.
- Weights in FP8: about 70 GB (roughly 65 GiB).
- Total before overhead: about 124 GiB, so at least two GPUs of the 80 GB class with tensor parallelism, and likely more if you want headroom for long-context outliers or higher concurrency.
Note what moved the needle: FP8 weights halved the weight bill, and FP8 KV halved the cache bill. In BF16 the same workload would need roughly double.
When one replica cannot meet throughput, add replicas behind a load balancer (data parallelism). When one replica cannot fit the model, split it across GPUs:
Rendering diagram…
Tensor parallelism splits each layer across GPUs and needs fast interconnect (NVLink-class) because it communicates every layer. Pipeline parallelism splits layers into stages and tolerates slower links, at the cost of pipeline bubbles. MoE models add expert parallelism.
Code
A small calculator that reads a Hugging Face config, so you never type these numbers by hand:
import json, sys
from huggingface_hub import hf_hub_download
def size(model_id: str, params_b: float, w_bytes: float, kv_bytes: float,
concurrency: int, avg_ctx: int, gpu_gib: float, util: float = 0.9):
cfg = json.load(open(hf_hub_download(model_id, "config.json")))
layers = cfg["num_hidden_layers"]
kv_heads = cfg.get("num_key_value_heads", cfg["num_attention_heads"])
head_dim = cfg.get("head_dim") or cfg["hidden_size"] // cfg["num_attention_heads"]
kv_per_tok = 2 * layers * kv_heads * head_dim * kv_bytes
weights = params_b * 1e9 * w_bytes
kv_total = concurrency * avg_ctx * kv_per_tok
gib = 1024 ** 3
need = (weights + kv_total) / gib
gpus = -(-need // (gpu_gib * util)) # ceiling division
print(f"KV per token: {kv_per_tok/1024:.0f} KiB")
print(f"weights {weights/gib:.1f} GiB + KV {kv_total/gib:.1f} GiB = {need:.1f} GiB")
print(f"minimum GPUs at {util:.0%} of {gpu_gib} GiB: {int(gpus)}")
if __name__ == "__main__":
size("Qwen/Qwen2.5-7B-Instruct", params_b=7.6, w_bytes=2, kv_bytes=2,
concurrency=32, avg_ctx=8000, gpu_gib=24)
Treat the result as a floor and confirm with the engine's own startup log, which reports the KV cache it actually allocated.
Trade-offs and pitfalls
- Parameter count is not memory. Two models with similar parameter counts can have very different KV costs because of layer count and KV heads. Always compute from the config.
- Maximum context is a trap. Sizing every sequence at the model's maximum context (often 128k) massively oversizes. Size for realistic averages and cap
max_model_len. - Interconnect matters for tensor parallelism. Splitting a model across GPUs without fast links can make it slower than a smaller model on one GPU.
- Bandwidth bounds are optimistic. Real throughput sits below the ceiling; use the formula to rule things out, and a load test to rule them in.
- Leave headroom. Running memory at the edge turns small traffic spikes into preemptions and tail latency.
- MoE changes the maths. Memory follows total parameters; per-token compute and bandwidth follow active parameters, which is why large MoE models can decode quickly once they fit.
Checklist
- I computed KV bytes per token from the real config, including KV heads and head dimension.
- I sized for peak concurrency times realistic average context, with headroom.
- I compared BF16, FP8 and 4-bit weight options and FP8 KV cache.
- I chose tensor parallel only within fast-interconnect groups.
- I checked the decode speed ceiling against my latency target.
- I validated the estimate against the engine's startup KV capacity log and a load test.