Sub topic 8
Estimating the memory a model needs
This chapter assumes you can read basic Python and know what a parameter count is. You should also know that an open-weight model is a set of downloadable weight files. Memory is the first hard limit you hit when you run one yourself, so you can estimate it before you download anything.
The weights come first
Every parameter is a number stored in a fixed number of bits. The memory for the weights is the parameter count times the bytes per parameter. A byte is 8 bits, so divide the bits by 8.
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 memory. A 7B model at 16-bit needs 14 GB for weights. The same model at 4-bit needs 3.5 GB. The next chapter covers how lower precision is achieved and what it costs in quality.
Weights are not the whole bill
The number above is a floor. Three more items share the same memory:
- KV cache. The model stores intermediate values for every token already in the context, so it does not recompute them. The cache grows with context length and with the number of requests served at once.
- Runtime overhead. The serving software, GPU libraries, and temporary buffers use memory too.
- Headroom. Running at 100% of memory leaves no room for a longer prompt or a second user.
A rough planning rule is to add 20 to 30 percent to the weight figure for short contexts and a single user. Add more for long contexts or many concurrent requests. Treat this as a starting estimate and confirm it by loading the model on your hardware.
| Item | Grows with |
|---|---|
| Weights | Parameter count and bits per weight |
| KV cache | Context length and concurrent requests |
| Overhead | Serving software and settings |
Worked example
You want to run a 7B model at 8-bit on a GPU with 16 GB of memory.
- Weights: 7 × 8 / 8 = 7.0 GB.
- Add about 30% for cache and overhead: 7.0 × 1.3 ≈ 9.1 GB.
- Compare with 16 GB. It fits, with room for longer prompts.
Now try a 70B model at 16-bit. The weights alone are 140 GB. That does not fit on any single common GPU, so you would need several GPUs, a lower precision, or a smaller model.
Common errors
- Using the parameter count in billions as gigabytes. That is only correct at 8 bits per weight.
- Forgetting the KV cache and then running out of memory with long prompts.
- Mixing up GB and GiB. The small difference matters when you are near the limit.
Exercise
A 13B model is stored at 4 bits per weight. How much memory do the weights need, and what total do you plan for if you add 30% for cache and overhead?
Show answer
Weights: 13 × 4 / 8 = 6.5 GB. With 30% added: 6.5 × 1.3 ≈ 8.45 GB, so plan for about 8.5 GB.