128 KiB Per Token: The GPU Memory Math for Serving an 8B Model

Llama 3.1 8B's weights fit in 16 GB. One 128K-token request needs another 17. The KV cache formula, worked for four models, from config.json alone.


An 80 GB GPU split into 16.1 GB of Llama 3.1 8B weights, about 4 GB of overhead, a 51.9 GB KV cache budget and 10% held back; the KV budget holds three requests at 128K tokens or forty-eight requests at 8K tokens

Llama 3.1 8B’s weights take 16.1 GB in bf16. One request at its full 128K-token context needs another 17.2 GB. The model is smaller than a single conversation with it.

That second number is the KV cache, and it’s the one that decides how many users a GPU can serve. Most capacity conversations get stuck on the first number because it’s printed on the model card. The second you have to work out, and it takes four values from config.json and one multiplication.

Two things live in GPU memory

The weights are fixed. Parameter count times bytes per parameter: 2 bytes in bf16, 1 in fp8, about half a byte at 4-bit. They’re loaded once and shared by every request.

The KV cache grows with traffic. When a transformer processes a token, every layer computes a key vector and a value vector for it, and attention for every later token in that sequence needs to read them. Recomputing them each step would make generation quadratic, so the server keeps them in GPU memory for as long as the request is alive. More tokens in flight, more memory.

The formula:

KV bytes per token = 2 × layers × kv_heads × head_dim × bytes_per_element

The 2 is one key plus one value. head_dim is hidden_size / num_attention_heads. For Llama 3.1 8B (config.json): 2 × 32 layers × 8 KV heads × 128 × 2 bytes = 131,072 bytes. 128 KiB for every token of every live request.

Four models, worked

This script computes both numbers from config values only. As a check on the parameter formula, it reproduces the exact parameter counts Hugging Face reports for the safetensors files: 8,030,261,248 for Llama 3.1 8B and 7,615,616,512 for Qwen2.5-7B.

"""GPU memory math for serving an LLM: weights + KV cache, from config.json values alone."""

# Values copied from each model's config.json on Hugging Face.
MODELS = {
    # name: (layers, heads, kv_heads, hidden, intermediate, vocab, qkv_bias)
    "Llama-2-7B":     (32, 32, 32, 4096, 11008, 32000, False),
    "Llama-3.1-8B":   (32, 32, 8, 4096, 14336, 128256, False),
    "Qwen2.5-7B":     (28, 28, 4, 3584, 18944, 152064, True),
    "Llama-3.1-70B":  (80, 64, 8, 8192, 28672, 128256, False),
}
GB = 1e9


def params(layers, heads, kv_heads, hidden, inter, vocab, qkv_bias):
    head_dim = hidden // heads
    kv_dim = kv_heads * head_dim
    attn = hidden * hidden + 2 * hidden * kv_dim + hidden * hidden   # q, k, v, o projections
    if qkv_bias:
        attn += hidden + 2 * kv_dim
    mlp = 3 * hidden * inter                                         # gate, up, down
    norms = 2 * hidden
    return 2 * vocab * hidden + layers * (attn + mlp + norms) + hidden  # embed + lm_head + layers + final norm


def kv_bytes_per_token(layers, heads, kv_heads, hidden, bytes_per_elem=2):
    head_dim = hidden // heads
    return 2 * layers * kv_heads * head_dim * bytes_per_elem          # 2 = one K and one V


print(f"{'model':<14} {'params':>8} {'bf16 weights':>13} {'int4 weights':>13} {'KV/token':>9} {'KV @8K':>8} {'KV @128K':>9}")
for name, cfg in MODELS.items():
    p = params(*cfg)
    kv = kv_bytes_per_token(*cfg[:4])
    print(f"{name:<14} {p/1e9:>7.2f}B {p*2/GB:>11.1f}GB {p*0.5/GB:>11.1f}GB "
          f"{kv/1024:>6.0f}KiB {kv*8192/GB:>6.2f}GB {kv*131072/GB:>7.1f}GB")
model            params  bf16 weights  int4 weights  KV/token   KV @8K  KV @128K
Llama-2-7B        6.74B        13.5GB         3.4GB    512KiB   4.29GB    68.7GB
Llama-3.1-8B      8.03B        16.1GB         4.0GB    128KiB   1.07GB    17.2GB
Qwen2.5-7B        7.62B        15.2GB         3.8GB     56KiB   0.47GB     7.5GB
Llama-3.1-70B    70.55B       141.1GB        35.3GB    320KiB   2.68GB    42.9GB

The 128K column is hypothetical for two of them: Llama 2’s config declares 4,096 positions and Qwen2.5-7B’s declares 32,768. It’s there to show what each design would cost at the same length.

Three things stand out.

The weights column barely varies between the 7B and 8B models. The KV column varies by 9×. Llama 2 7B, Llama 3.1 8B and Qwen2.5-7B are within 2.6 GB of each other in weights. Per token of KV cache they range from 512 KiB down to 56 KiB. If you’re sizing a fleet by “parameters”, you’re sizing by the number that matters least once requests get long.

The difference is the kv_heads column. Llama 2 7B gives every one of its 32 attention heads its own key and value. Llama 3.1 8B shares each key-value head between four query heads (8 KV heads for 32 query heads), and Qwen2.5-7B shares each one across seven. That’s grouped-query attention, from Ainslie et al., 2023, and its whole point is this table: near multi-head quality with a fraction of the cache. When you compare two models for serving, compare num_key_value_heads before you compare benchmarks.

4-bit weights don’t fix long context. Llama 3.1 70B quantized to 4-bit fits its weights into 35.3 GB, which tempts people onto a single 80 GB card. One request at 128K then needs 42.9 GB of KV cache. Weight quantization doesn’t touch the cache: it stays at its own precision (bf16 by default) unless you separately turn on KV cache quantization, which at fp8 halves it.

How many users fit on one GPU

Now subtract. On an 80 GB card, cap usage at 90% (a little under vLLM’s current --gpu-memory-utilization default of 0.92, to leave room for spikes), take off the weights, and assume about 4 GB for activations and CUDA graphs. That 4 GB is my assumption, not a measurement; your serving stack will report its own.

print("\nHow many concurrent sequences fit on one 80 GB GPU? (Llama-3.1-8B, bf16)")
cfg = MODELS["Llama-3.1-8B"]
weights = params(*cfg) * 2
kv = kv_bytes_per_token(*cfg[:4])
budget = 80 * GB * 0.90 - weights - 4 * GB   # 90% utilisation cap, ~4 GB for activations and CUDA graphs
print(f"  KV budget after weights and overhead: {budget/GB:.1f} GB = {budget/kv:,.0f} tokens")
for ctx in (2048, 8192, 32768, 131072):
    print(f"  every request at {ctx:>7,} tokens -> {budget/(kv*ctx):6.1f} concurrent sequences")
How many concurrent sequences fit on one 80 GB GPU? (Llama-3.1-8B, bf16)
  KV budget after weights and overhead: 51.9 GB = 396,267 tokens
  every request at   2,048 tokens ->  193.5 concurrent sequences
  every request at   8,192 tokens ->   48.4 concurrent sequences
  every request at  32,768 tokens ->   12.1 concurrent sequences
  every request at 131,072 tokens ->    3.0 concurrent sequences

The same GPU, the same model, and the answer to “how many users?” runs from 193 down to 3. Context length isn’t a feature toggle. It’s a capacity decision, which is why --max-model-len belongs in your capacity plan and not just your product spec (more on that flag in practice).

And this is already the good case, because it assumes the server only reserves memory for tokens that exist. Early serving systems reserved a contiguous block for each request’s maximum length up front, so a request capped at 8K that used 500 tokens still held 8K worth of cache. vLLM’s PagedAttention fixed that by allocating the cache in small fixed-size blocks, the same trick an operating system uses for virtual memory, and the paper reports 2 to 4× higher throughput at the same latency against the systems it compared. If your serving stack still pre-allocates per request, divide every number above by how much of the maximum your requests actually use.

Check your numbers against the server

vLLM prints its own version of this calculation at startup, after it has measured the real overhead:

GPU KV cache size: 643,232 tokens
Maximum concurrency for 40,960 tokens per request: 15.70x

(That example is from the vLLM parallelism docs, for a different model and GPU layout.) The first line is the token budget I computed above. The second is the budget divided by --max-model-len. Do the arithmetic before you deploy, then compare it with what the server logs. If they disagree by more than a few percent, either your config values are wrong or something else is holding GPU memory, and you want to know which before the first long-context customer finds out for you.

The economics follow straight from this. Concurrency is what you’re selling, the KV cache is what limits it, and GPU utilization tells you very little about either. One formula, four numbers from config.json:

users per GPU ≈ (0.9 × GPU memory − weights − overhead) ÷ (KV bytes per token × context length)

Frequently asked questions

How much GPU memory does an LLM need?

Two things, added together. The weights: parameter count times bytes per parameter, so an 8-billion-parameter model needs about 16 GB in bf16 and 4 GB at 4-bit. And the KV cache: for every token of every request in flight, each layer stores a key and a value vector. For Llama 3.1 8B that's 128 KiB per token, so one request at its full 128K context needs 17.2 GB on top of the weights.

How do you calculate KV cache size?

KV bytes per token = 2 × number of layers × number of key-value heads × head dimension × bytes per element. The 2 is one key and one value. Multiply by the context length for one sequence, then by the number of concurrent sequences. All four numbers are in the model's config.json: num_hidden_layers, num_key_value_heads, and hidden_size divided by num_attention_heads for the head dimension.

Does quantizing a model to 4-bit reduce the KV cache?

No. Weight quantization shrinks the weights only. The KV cache is stored at its own precision, usually bf16, unless you separately enable KV cache quantization (for example an fp8 KV cache, which halves it). For long-context serving, the KV cache is often larger than the quantized weights, so 4-bit weights alone can leave you with the same concurrency problem.

Comments