跳到正文

第 12 课 · Memory, Speed and Quantization

Llama Memory Requirements: Weights and KV Cache

Estimate how much RAM or GPU memory a Llama model needs: weight size by number format, the KV cache that grows with context and runtime overhead.

Memory is the first wall you hit with local models. Three things use it: the weights, the KV cache that grows with the context, and runtime overhead. This lesson shows how to estimate each one so you can choose hardware and settings with fewer surprises.

Weights

Each parameter is stored in some number format.

Format Bits per weight About, for 8B parameters
32-bit float 32 32 GB
16-bit (bf16 or fp16) 16 16 GB
8-bit about 8 about 8 GB
4-bit family about 4 to 5 about 4 to 5 GB

The formula is parameters × bits / 8 bytes. Here 1 GB means one billion bytes. llama.cpp's quantization documentation gives examples for Llama 3.1: the 8B model goes from 32.1 GB to 4.9 GB in Q4_K_M, the 70B from 280.9 GB to 43.1 GB, and the 405B from 1,625.1 GB to 249.1 GB. It also says that memory and disk needs are currently the same, because models are loaded fully into memory. (Some runtimes can map files from disk, but speed suffers badly if memory is too small.)

The KV cache

To avoid recomputing earlier tokens, the model stores keys and values for each token in each layer. This is the KV cache. It grows linearly with the number of tokens in context and with the number of parallel conversations. See the KV cache for inference for how it works.

A formula:

2 × layers × tokens × kv_heads × head_size × bytes_per_value

The values come from the model's configuration file (config.json). The example below uses 32 layers, 8 key-value heads and a head size of 128, which is the shape of Llama 3.1 8B. Confirm these numbers in the file of your own model. Llama 3.1 uses grouped-query attention, which has fewer key-value heads than attention heads and so makes the cache much smaller.

Python KV cache size for different context lengths

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

(This uses binary units: 1 GiB is 1,073,741,824 bytes.) With these settings, 128K tokens need about 16 GiB for the cache alone. That is why a huge advertised context window may be impractical on your machine.

Shrinking the cache

  • Use a smaller context. This is often the biggest and easiest saving.
  • Quantize the cache. Ollama's OLLAMA_KV_CACHE_TYPE offers f16 (default), q8_0 (about half the memory, with very little quality loss according to its FAQ) and q4_0 (about a quarter of the memory, with more noticeable loss at larger contexts). Other runtimes have their own options.
  • Limit parallel requests. Each one needs room for its own context.

llama.cpp's function-calling documentation warns that extreme cache quantization can badly hurt tool calling, so test it.

Overhead and headroom

The runtime, the graphics driver, the operating system and your other apps need memory too. Leave headroom. As a planning habit, do not fill more than about 80 to 90 percent of a device. This is a rule of thumb, not a law.

A complete estimate

Python Does this setup fit?

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The overhead number is a guess. The cache shape applies only to an 8B model of this kind. Use the model's own configuration for other sizes. For mixture-of-experts models, count the total parameters.

CPU RAM, GPU memory and unified memory

  • GPU memory (VRAM) is fast but limited.
  • System RAM is usually larger, but CPU inference is slower.
  • Unified memory (as on Apple silicon) is shared by CPU and GPU, so the whole pool matters, minus what the system needs.

If part of a model lands on the CPU, expect a clear slowdown.

Reading the numbers from a model

Open the config.json file of a downloaded model. Look for the number of hidden layers, the number of attention heads, the number of key-value heads and the hidden size. The head size is often listed directly, or you can compute it as the hidden size divided by the number of attention heads. Check which definition your model uses before you rely on it. Then put the values into the calculator above.

Runtimes also print their own memory estimates at startup. Compare your calculation with that report. If they differ a lot, you probably used a wrong value, a different cache data type or forgot that several request slots were configured.

Planning for growth

When you plan hardware, think about your next step, not only today's. Longer chats, bigger documents and more users all increase the cache. A larger model or a higher quantization level increases the weights. Write down the numbers for your likely next configuration and check whether the same machine could handle it.

Then verify by measurement. Load the model with your real settings, send long inputs from several clients at once and watch memory use with your system's monitoring tool or the GPU vendor's tool.

When it still does not fit. If your estimate is above your memory, change one thing: a smaller context, fewer parallel slots, a quantized cache, a lower weight level or a smaller model. Then calculate again and retest quality before you decide.

Keep your notes. Record each configuration you try, with the estimate and the measured peak memory. Over time, this table shows how far your estimates are from reality on your own hardware.

Common mistakes

Do not plan memory from the download size alone. A model that loads can still run out of memory when the conversation grows or when a second user arrives.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What happens to the KV cache when you double the context length?

    The cache grows linearly with the number of tokens.
  2. 2. About how large are 8 billion weights at 16 bits?

    8 billion times 2 bytes is 16 billion bytes.
  3. 3. Which parameter count matters for memory in a mixture-of-experts model?

    All experts must be stored.
  4. 4. Eight users each have their own long context. What follows?

    Weights are shared, but each sequence needs cache (some runtimes can share identical beginnings).

Summary

  • Memory is weights plus KV cache plus overhead.
  • Weights are about parameters times bits divided by 8.
  • The cache grows with context length and parallel users.
  • Read real values from the model configuration and leave headroom.

Next: Quantization and GGUF

你的学习进度保存在此浏览器中,无需账号。