Sub topic 8
Estimating the memory a model needs
This chapter assumes you can read basic Python and know what parameters, tokens, and a context window are. Memory is usually the first hard limit you hit when you self-host an open-weight model. If the model does not fit in your GPU or system memory, nothing else about it matters. A quick estimate, made before you download anything, tells you which models are worth considering.
The three parts of the memory bill
A running model uses memory for three things:
- Weights. The learned numbers, one per parameter. This is usually the largest part.
- KV cache. The attention keys and values the model stores for every token already in the context, so it does not recompute them for each new token. It grows with context length and with the number of simultaneous requests.
- Overhead. Activation buffers, the runtime's own allocations, CUDA context, and memory fragmentation. Plan for roughly 10 to 20 percent on top of the other two.
Step 1: Weight memory
Weight memory is the parameter count times the bytes used per parameter. A model stored at 16 bits uses 2 bytes per parameter. At 8 bits it uses 1 byte, and at 4 bits it uses half a byte. Because a billion parameters at one byte each is about one gigabyte, the arithmetic is simple.
def weight_memory_gb(params_billion: float, bits_per_weight: int) -> float:
"""Memory for the weights alone, in GB (1 GB = 1e9 bytes)."""
return params_billion * bits_per_weight / 8
for bits in (16, 8, 4):
print(f"7B model at {bits}-bit: {weight_memory_gb(7, bits):.1f} GB")
# 7B model at 16-bit: 14.0 GB
# 7B model at 8-bit: 7.0 GB
# 7B model at 4-bit: 3.5 GBHalving the precision halves the weight memory. The next chapter covers what that costs in quality.
| Model size | 16-bit | 8-bit | 4-bit |
|---|---|---|---|
| 7B | 14 GB | 7 GB | 3.5 GB |
| 13B | 26 GB | 13 GB | 6.5 GB |
| 70B | 140 GB | 70 GB | 35 GB |
These figures are for weights only. A 7B model at 16-bit does not fit on a 16 GB GPU in practice, because the KV cache and overhead still need room.
Step 2: KV cache
During generation, each layer stores a key vector and a value vector for every token in the context. The per-token cost is:
2 (key and value) x layers x KV heads x head dimension x bytes per value
The total is that number times the tokens in context times the number of requests running at once.
The "KV heads" term matters. Older designs use one key/value head per attention head. Many newer models use grouped-query attention (GQA), which shares key/value heads across groups of attention heads. GQA shrinks the cache several times over. You can find layers, KV heads, and head dimension in the model's config.json on its download page. Look for fields such as num_hidden_layers, num_key_value_heads, and head_dim (or hidden size divided by the number of attention heads).
def kv_cache_gb(layers: int, kv_heads: int, head_dim: int, tokens: int,
batch: int = 1, bytes_per_value: int = 2) -> float:
"""KV cache size in GB for `batch` concurrent sequences of `tokens` tokens."""
per_token_bytes = 2 * layers * kv_heads * head_dim * bytes_per_value
return per_token_bytes * tokens * batch / 1e9
# A 7B-class model with 32 layers and head dimension 128, 16-bit cache.
print(f"No GQA (32 KV heads), 4096 tokens: {kv_cache_gb(32, 32, 128, 4096):.1f} GB")
print(f"GQA (8 KV heads), 4096 tokens: {kv_cache_gb(32, 8, 128, 4096):.1f} GB")
print(f"GQA, 8192 tokens, 8 requests: {kv_cache_gb(32, 8, 128, 8192, batch=8):.1f} GB")
# No GQA (32 KV heads), 4096 tokens: 2.1 GB
# GQA (8 KV heads), 4096 tokens: 0.5 GB
# GQA, 8192 tokens, 8 requests: 8.6 GBThe last line shows the usual trap. One short request barely registers, but eight long ones need more memory than the 4-bit weights do. The cache scales linearly with both context length and concurrency.
Step 3: Add overhead and compare
Combine the parts and apply a safety margin. A 20 percent margin is a reasonable starting point.
def total_memory_gb(params_billion: float, bits_per_weight: int,
layers: int, kv_heads: int, head_dim: int,
tokens: int, batch: int = 1,
overhead: float = 0.20) -> float:
weights = params_billion * bits_per_weight / 8
per_token_bytes = 2 * layers * kv_heads * head_dim * 2 # 16-bit cache
kv = per_token_bytes * tokens * batch / 1e9
return (weights + kv) * (1 + overhead)
for bits in (16, 8, 4):
gb = total_memory_gb(7, bits, layers=32, kv_heads=8, head_dim=128, tokens=4096)
print(f"7B at {bits}-bit, 4096 tokens, 1 request: about {gb:.1f} GB")
# 7B at 16-bit, 4096 tokens, 1 request: about 17.4 GB
# 7B at 8-bit, 4096 tokens, 1 request: about 9.0 GB
# 7B at 4-bit, 4096 tokens, 1 request: about 4.8 GBCompare the result with the memory you have:
- A consumer GPU with 8 GB fits the 4-bit and (barely) the 8-bit configuration above.
- A 24 GB GPU fits all three, with room for a longer context or a few concurrent requests.
- Laptops with unified memory share one pool between the CPU and GPU. The operating system and other applications take their share first, so budget well below the advertised total.
Edge cases that break the simple formula
- Mixture-of-experts (MoE) models. An MoE model activates only some of its parameters for each token, but all experts must be loaded. A model advertised as "47B total, 13B active" needs memory for 47B parameters. The active count affects speed, not the memory floor.
- Effective bits for quantized files. A "4-bit" file typically stores extra scale values, so the real average is closer to 4.5 to 5 bits per weight. Use the file size on disk as a check. The weights occupy about that much memory.
- Quantized KV cache. Some runtimes can store the cache at 8 bits, which halves the cache figure. Check that your runtime supports it, and measure quality if you enable it.
- GB versus GiB. This chapter uses 1 GB = 10^9 bytes. GPU specifications often use gibibytes (2^30 bytes), which are about 7 percent larger. When a plan is close to the limit, keep the units consistent.
- Parameter counts are rounded. "7B" may mean 6.7B or 7.6B. Read the exact count from the model card when the margin is thin.
- Training and fine-tuning need more. Gradients and optimizer state can multiply the weight memory several times. This chapter covers inference only.
- CPU offloading. Some runtimes place part of the model in system RAM when the GPU is full. The model then runs, but generation can slow by an order of magnitude, because data crosses the slower link on every token.
A quick workflow
- Read the parameter count, layer count, KV heads, and head dimension from the model card or
config.json. - Pick a precision that you can afford and that your evaluation set (a later chapter) shows is good enough.
- Decide on the maximum context length and the number of simultaneous requests you need.
- Compute weights, KV cache, and a 20 percent margin.
- Compare with available memory, then load the model and watch the real usage.
Exercise
A model has 13 billion parameters, 40 layers, 40 KV heads, and head dimension 128. You plan to run it at 8-bit weights with a 16-bit KV cache, a 2048-token context, and one request at a time. Estimate the weight memory and the KV cache memory (GB, decimal), and say whether the weights plus cache fit in a 16 GB GPU before adding overhead.
Show answer
Weights: 13 x 8 / 8 = 13 GB. KV cache per token: 2 x 40 x 40 x 128 x 2 bytes = 819,200 bytes. For 2048 tokens that is 819,200 x 2048 = 1,677,721,600 bytes, about 1.7 GB. The sum is about 14.7 GB, which is under 16 GB. With a 20 percent margin the total is about 17.7 GB, so it does not reliably fit. A 4-bit version (6.5 GB of weights, about 8.2 GB, or about 9.9 GB with margin) would fit.
Exercise
Why can a server that handles one request comfortably run out of memory when ten users connect, even though the model weights never change?
Show answer
The weights are loaded once and shared, but each concurrent request needs its own KV cache. The cache grows linearly with the number of requests and with context length, so ten long requests can need ten times the cache memory of one. Total memory must cover weights plus the cache for every active request.