Where the memory goes when you serve a large language model
A field guide to GPU memory in LLM serving: weights, quantization metadata, mixture-of-experts residency, KV cache, attention intermediates and prefix reuse, with a working capacity calculator.
Consolidates and expands five notes first published in Issues 001–002 on November 7, 2026. See the archive record.
A model that loads is not a model that serves. Most capacity surprises in LLM deployments happen in the gap between those two states: the weights fit, the health check passes, and then the first afternoon of real traffic, with long documents and long answers, exhausts the memory that was left over.
This guide walks through that memory in the order an operator meets it. First the weights, including what quantization and mixture-of-experts labels do and do not change. Then the request state that grows with every token, which is where most of the confusion lives. Then two techniques that change the accounting, FlashAttention and prefix caching, and what they actually remove. The last section connects the result to something that matters on the facility side: how much power each concurrent conversation ends up carrying.
All of the arithmetic below can be reproduced, and the calculator near the end lets you substitute your own model dimensions.
Two ledgers: what is stored, and what grows
It helps to keep two ledgers from the start.
The first is resident state that does not depend on traffic: model weights, quantization metadata, runtime buffers and any copies the deployment keeps. It is paid once per replica.
The second is state that grows with requests: the attention key/value cache for every token a live conversation keeps, plus temporary workspace that scales with sequence length and batch. It is paid per request, per token, and it changes minute by minute.
Most sizing mistakes come from answering a question in the second ledger with a number from the first. “The model is 4-bit, so it fits” is a statement about weights. “It can hold forty conversations” is a statement about the cache. Neither implies the other.
Weights: what a bit-width label actually buys
Storage arithmetic, metadata included
For an illustrative dense model with seven billion parameters, 16-bit weights occupy 14 billion bytes before anything else. Four-bit payloads occupy 3.5 billion bytes. That is the headline everyone quotes. It is not the whole representation.
Group-wise quantization stores scaling information alongside the low-bit values. Take a hypothetical layout in which each group of 128 four-bit weights carries one two-byte scale and one two-byte zero point. This is a storage example, not the exact packing of any particular method or runtime.
metadata bytes per parameter = 4 / 128 = 0.03125
total bytes = 7,000,000,000 × (0.5 + 0.03125) = 3,718,750,000
| Item | Illustrative storage |
|---|---|
| 16-bit weights | 14.000 GB |
| Four-bit weight payload | 3.500 GB |
| Assumed group metadata | 0.219 GB |
| Combined four-bit representation | 3.719 GB |
| KV cache and working memory | Separate budget |
Metadata adds 6.25% to the four-bit payload under these assumptions. Padding, layers left unquantized, file headers and implementation-specific packing can add more. To estimate a real checkpoint, inspect its actual group layout rather than relying on the label.
Three separate questions a quantized release must answer
AWQ describes activation-aware, low-bit, weight-only quantization [6]. GPTQ develops post-training quantization using approximate second-order information [7]. Both papers report results under their own experimental conditions. Neither establishes that every file carrying the same bit-width label preserves the behavior a particular application needs.
A quantized artifact therefore has to clear three separate checks before it replaces the original:
- Quality. Fix the tokenizer, prompting, decoding settings and test set, then compare against an identified reference. Look specifically at the failure modes the application cares about: code that must compile, structured output that must parse, numerical answers, or non-English text. Keep calibration data and evaluation data apart, or the result partly measures how well the method adapted to its own examples.
- Fit. Lower-precision weights shrink the first ledger. They do not shrink the second. Cache precision is configured separately, and Transformers documents several cache strategies independently of weight representation [5].
- Speed. A smaller representation only runs faster if the execution path supports it. Packing, dequantization cost, matrix shapes and kernel availability decide that. A four-bit file that loads is not evidence of a fourfold throughput gain.
The defensible claim after testing may be “it now fits”, “it admits more concurrent requests” or “it is faster on this workload”. Those are different achievements. Reporting only the one actually demonstrated is more useful than reporting all three by implication.
Mixture-of-experts: total parameters stay resident
Sparse models invite a specific mistake. Their specifications usually quote two numbers, and only one of them belongs in the memory ledger.
The Mixtral 8x7B paper describes eight feed-forward experts per layer, with routing that selects two for each token. It reports roughly 47 billion total parameters and 13 billion active parameters during inference [9]. At two bytes per parameter, those rounded figures give:
47 billion × 2 bytes ≈ 94 GB of total raw weight payload
13 billion × 2 bytes ≈ 26 GB corresponding to the active count
If the deployment keeps all experts resident, which is the ordinary case, the 94 GB figure is the starting point for weight memory. An illustrative 80 GB device cannot hold that raw payload before any cache is allocated. The 26 GB figure describes how much of the network a token passes through, not what must be stored. It also includes shared layers; do not multiply it by the expert count again.
| Planning question | Starting quantity | Additional evidence needed |
|---|---|---|
| Will resident weights fit? | Total stored parameters | Precision, packing, sharding, unquantized layers |
| How much work does one token select? | Active parameter path | Shared layers, routing, batch shape, kernels |
| Will the service meet latency? | Complete execution path | Expert dispatch, cross-device traffic, cache, queueing |
Switch Transformers, an earlier primary reference on sparse activation, uses top-one routing rather than Mixtral’s top-two and discusses the communication and load-balancing costs that routing brings [8]. Those costs show up in latency and memory alike: a batch rarely sends equal work to every expert, extra expert capacity to absorb that imbalance wastes computation and memory, and experts placed on different devices turn routing into network traffic [8]. A sparse-model capacity plan should state per-expert load, dispatch timing and whether a missing expert can trigger an offload transfer.
The KV cache: the ledger that grows with every token
The formula
During generation, a transformer keeps the key and value vectors for every token it has seen so that it does not recompute them on each step. For a decoder whose layers share the same attention shape:
KV bytes = 2 × layers × KV heads × head dimension × bytes per element × retained tokens
The factor of two covers keys and values. Retained tokens means the prompt plus whatever continuation attention keeps. The head count that matters is the number of KV heads, not query heads. Grouped-query attention lets several query heads share one key/value head [3], and modern models use it heavily. Plugging in the query-head count is the single most common way to overstate cache size.
Worked numbers from two published configurations
Qwen’s published configuration files supply concrete dimensions [1, 2]. These are deliberately pinned model revisions, chosen because their fields are public, not because they are the newest models. Both configurations disable sliding-window attention.
| Configuration field | Qwen2.5-7B-Instruct | Qwen2.5-32B-Instruct |
|---|---|---|
| Layers | 28 | 64 |
| Query heads | 28 | 40 |
| KV heads | 4 | 8 |
| Hidden size | 3,584 | 5,120 |
| Head dimension (hidden ÷ query heads) | 128 | 128 |
| Assumed cache bytes per element | 2 | 2 |
| KV bytes per retained token | 57,344 | 262,144 |
For the 7B configuration: 2 × 28 × 4 × 128 × 2 = 57,344 bytes per token. For the 32B: 2 × 64 × 8 × 128 × 2 = 262,144. Using query heads instead would inflate these by factors of seven and five.
The two-byte cache is an explicit assumption. A bfloat16 model configuration does not prove the serving engine stores its cache in that format; check the runtime setting.
| Retained tokens per request | 7B payload | 32B payload |
|---|---|---|
| 2,048 | 112 MiB | 512 MiB |
| 8,192 | 448 MiB | 2,048 MiB |
| 10,240 | 560 MiB | 2,560 MiB |
| 32,768 | 1,792 MiB | 8,192 MiB |
The reservation people forget: room to answer
Suppose a replica has 24 GiB left over for cache after weights and workspace. That is an illustrative remainder, not a claim about any device.
Prompts average 8,192 tokens, and the service promises answers up to 2,048 tokens. The cache must hold both, so each request needs room for 10,240 tokens.
| Admission basis | 7B ceiling | 32B ceiling |
|---|---|---|
| Prompt only (8,192 tokens) | 54 | 12 |
| Prompt + answer (10,240 tokens) | 43 | 9 |
The difference is not a rounding detail. A scheduler sized on prompt length alone will admit requests whose answers cannot finish. Depending on the engine, the result is preemption, recomputation or an error halfway through a reply.
Round to allocator blocks
Logical payload and allocated payload differ. PagedAttention manages the cache in fixed-size blocks and describes the unfilled positions in each sequence’s final block [4]. An estimate should name the block size alongside the model dimensions.
With 16-token blocks and 1,001 retained tokens per sequence, each unshared sequence occupies ceil(1,001 / 16) × 16 = 1,008 positions.
| Two-byte KV, 100 sequences of 1,001 tokens | Logical payload | Block-rounded | Final-block waste |
|---|---|---|---|
| Qwen2.5-7B | 5,474.2 MiB | 5,512.5 MiB | 38.3 MiB |
| Qwen2.5-32B | 25,025 MiB | 25,200 MiB | 175 MiB |
allocated = sum over sequences of ceil(retained tokens / block size) × block size × KV bytes per token
These figures still exclude allocator metadata and replication across devices. The point of PagedAttention is to recover memory that older allocators lost to fragmentation; it does not shrink the logical payload of a long sequence.
Before turning any of this into an admission limit, measure it. Record allocated cache blocks and memory as prompt length, answer length and concurrency vary, then compare the slope with the analytical estimate. Sliding windows, mixed layer types, cache compression, latent attention, offloading and sharded placement all change the formula, and a cache replicated across devices has a different per-device budget from a sharded one.
FlashAttention removes an intermediate, not the work
The attention computation itself produces a large temporary object: the matrix of scores between every query position and every key position. For one head over N positions it has N² entries.
At N = 8,192 with an illustrative two-byte entry:
8,192² × 2 = 134,217,728 bytes = 128 MiB per head
Across 32 heads materialized together, that is 4 GiB. At N = 16,384 it becomes 512 MiB per head and 16 GiB across 32 heads. Doubling sequence length quadruples this term.
FlashAttention restructures the computation into tiles and uses recomputation so that the full intermediate never has to be written to high-bandwidth memory [10]. The tiles still contribute to one exact softmax, which requires bookkeeping. A toy example shows why. Split three scores into blocks [0, 0] and [ln 2]. The unnormalized sums are 2 and 2, so the correct probabilities are [1/4, 1/4, 1/2]. Normalizing each block separately and concatenating would give [1/2, 1/2, 1], which sums to two. Real kernels add numerically stable rescaling on top of that coordination.
Three cautions keep the gain in proportion:
- The pairwise work remains. Removing a stored N-by-N object does not remove dense attention’s N² arithmetic. Long sequences stay expensive in time.
- Kernel speedups dilute at application level. If attention is 40% of elapsed time and a kernel halves it, total time becomes
0.6 + 0.4 / 2 = 0.8of the original: 1.25 times faster, not twice as fast. - “Exact” is a mathematical target, not bitwise identity. PyTorch’s scaled-dot-product-attention documentation notes backend-dependent numerical differences [11]. Check tolerances when changing kernels, precision or masks, and record which backend was actually selected.
Prefix caching: count what can really be skipped
Many applications send the same long instructions with every request. If the serving engine can keep the computed state for that shared prefix, later requests skip part of the prompt work.
The ideal count
Take 100 sequential requests that share an identical 2,000-token prefix followed by 500 unique tokens each.
without reuse: 100 × (2,000 + 500) = 250,000 prompt-token positions
with ideal reuse: 2,000 + (100 × 500) = 52,000
The saving is 198,000 positions, or 79.2%. That is skipped prompt computation for a constructed workload. It is not a latency figure, not a total-compute figure and not a price discount: the unique suffixes still attend to the cached prefix, and every answer still has to be generated.
The realistic count
vLLM’s documented design caches only full blocks and identifies them by hash, with eviction when memory is needed [12]. SGLang’s RadixAttention organizes reusable state as a radix tree and evicts unused nodes to admit running requests [13]. Both describe mechanisms for finding reusable state. Neither guarantees that a given request lands on a worker that still holds it.
If only 40 of the 99 follow-on requests find the prefix resident:
250,000 − (40 × 2,000) = 170,000 positions, a 32% reduction
Misses come from slightly different token sequences, eviction, configuration differences or routing to a worker without the state. Text that looks identical can tokenize differently in context.
Two rules before turning it on
- Respect tenant boundaries. vLLM documents a cache salt that separates reuse between requests with different salts [12]. A higher fleet-wide hit rate is not a reason to let one customer’s prompt state become a timing side channel for another.
- Measure at the execution boundary. An application can know that its text repeats without knowing whether the assigned worker holds a usable block. Report reused blocks, time to first token, completion time and memory pressure, cold and warm, broken down by request type.
Resident prefixes also occupy cache memory. Whether that reduces capacity depends on eviction policy: an evictable cache can give memory back to running requests, while a pinned one is a permanent deduction from the second ledger.
Calculator: how many conversations fit?
Enter a model’s attention dimensions and the memory left for cache after weights and workspace. The calculator applies the formula above, rounds each request to allocator blocks, and compares a prompt-only admission estimate with one that reserves room for the answer. Presets load the two Qwen2.5 configurations used in this guide.
It is an arithmetic tool. It does not know your runtime’s cache format, sharing, compression or replication, so treat its output as the question to test, not the answer.
From cache budget to power budget
Memory arithmetic eventually becomes an electricity question, because a facility pays for the hardware’s power whether that hardware holds one conversation or fifty.
Use deliberately simple, hypothetical numbers. Suppose one replica of the 32B configuration has 24 GiB of free cache, and its share of facility power, including cooling, is 1.5 kW. Compare two request profiles:
| Request profile | Retained tokens | Cache per request | Concurrent requests | Power per concurrent request |
|---|---|---|---|---|
| Long document + long answer | 10,240 | 2,560 MiB | 9 | ≈167 W |
| Short prompt + short answer | 2,560 | 640 MiB | 38 | ≈39 W |
The hardware and its power draw are identical. The context length chosen by the product team changes how much power each live conversation carries by a factor of more than four. That is one reason the same cluster can look efficient on a chat benchmark and expensive on a document-analysis workload, and why context limits are an infrastructure decision as much as a product one.
The calculation is crude. Accelerators do not draw a constant figure, idle power is lower than peak, and concurrency is not the only measure of useful work. It still points to the right conversation: when a team asks for longer context, the request should arrive with a cache estimate, and the cache estimate should arrive with a power estimate.
A checklist for the capacity review
- State weight memory from total stored parameters, with the actual precision and packing.
- Treat quality, fit and speed of a quantized artifact as three separate results.
- Compute cache per token from KV heads, and confirm the runtime’s cache precision.
- Size admission on prompt plus reserved answer, rounded to allocator blocks.
- Separate FlashAttention’s memory saving from its application-level time saving.
- Report prefix-cache hits at the worker, by tenant, cold and warm.
- Translate concurrency into power per live request before agreeing to longer context.
Sources and limitations
- Qwen2.5-7B-Instruct configuration, revision
a09a354: layer and head counts for the 7B worksheet. - Qwen2.5-32B-Instruct configuration, revision
5ede1c9: layer and head counts for the 32B worksheet. - GQA, version 3, §2.2: grouped query heads share key/value heads.
- PagedAttention, version 1, §§3–4: block allocation, fragmentation and sharing. No throughput figure from its evaluation is used.
- Transformers cache strategies, version 4.57.1: cache types and quantized cache as a separate decision from weight precision.
- AWQ, version 6, abstract: activation-aware low-bit weight-only quantization.
- GPTQ, version 2, §§3–4: approximate second-order post-training quantization.
- Switch Transformers, version 3, §§2.1–2.2 and 5: top-one routing, capacity and placement.
- Mixtral of Experts, version 1, abstract and §2: routing and rounded total/active parameter counts for Mixtral 8x7B.
- FlashAttention, version 2, §§2.2, 3.1 and Appendix B: tiling, recomputation and avoided intermediates.
- PyTorch scaled dot product attention, version 2.15: backend selection and numerical-difference notes.
- vLLM automatic prefix caching, version 0.20.1: block hashing, full-block note, cache salt and eviction.
- SGLang, version 2, §3 and Appendix A: radix-tree reuse and eviction of unused nodes.
Storage, cache, attention-matrix, prefix-reuse and power figures are original calculations from the stated assumptions. The 24 GiB cache budget and 1.5 kW power share are hypothetical. No hardware was benchmarked for this guide. It consolidates and expands five shorter field notes first published on November 7, 2026, whose addresses now redirect here.
Continue exploring
- The real cost of a useful token: utilization, service objectives, retries and the electricity bill
- Why an AI service feels slow: first tokens, queues, speculation and the multi-GPU tax
- How to read an AI benchmark: sample sizes, paired comparisons, latency tails and hidden workload mixes