Accounting for GPU memory in training and serving, and why the parameter count misleads
"It fits in 24 GB" is a claim about a file, not about a workload. A model whose weights load comfortably can still die on the first request, because the thing that determines whether you survive is peak memory across a step or a batch of concurrent requests, and almost none of that peak is weights.
This is a worked accounting method rather than an optimisation guide. The optimisations are well covered elsewhere; what gets skipped is the arithmetic that tells you which optimisation you actually need.
Training: sixteen bytes per parameter before anything interesting happens
For a plain FP32 setup with Adam, each parameter is carried four times over:
| Component | Bytes per parameter |
|---|---|
| Weights (FP32) | 4 |
| Gradients (FP32) | 4 |
| Adam first moment | 4 |
| Adam second moment | 4 |
| Optimiser state total | 16 |
Sixteen bytes per parameter is the floor, and it is reached before a single activation is saved. A 7B model is therefore about 112 GB of training state on its own, which is why nobody trains a 7B model on one 80 GB card without sharding, and why the first question about any training OOM is which of the four copies you are still holding.
The part that varies, and therefore the part that actually causes the failure, is activation memory: the intermediate tensors the backward pass needs. It scales with batch size, sequence length and depth, and it is the term people forget because it does not appear in the model card.
Inference: the cache is the budget
With autograd off, gradients and optimiser state vanish. What replaces them in autoregressive serving is the KV cache, and the cache is where serving capacity is actually decided.
The per-token cost is worth deriving once, because it is the number you will reuse for every capacity question you ever answer:
bytes per token per layer = 2 (K and V) x kv_heads x head_dim x bytes_per_element
bytes per token = that x num_layers
Take a hypothetical 8B model with BF16 weights, 32 full-attention layers, 8 KV heads, head dimension 128, BF16 cache:
Weights: 8e9 x 2 bytes = 16e9 bytes. That is 16 GB decimal, or 14.90 GiB. Keeping GB and GiB distinct matters here, because the 7% gap between them is larger than the headroom people usually leave.
Per token per layer: 2 x 8 x 128 x 2 = 4,096 bytes = 4 KiB.
Per token: 4 KiB x 32 = 128 KiB.
Per 8,192-token sequence: 128 KiB x 8,192 = exactly 1.00 GiB.
Four concurrent such sequences, no block sharing: 14.90 + 4.00 = 18.90 GiB of raw payload.
That 18.90 GiB is before workspace, runtime overhead and allocator slack, and it is the number that decides whether the fifth concurrent request succeeds.
Two structural observations follow from the derivation. First, the cache cost is linear in concurrency and in context length, while weights are a fixed cost — so a serving fleet sized on weights alone has no model of its own capacity. Second, the grouped-query ratio is doing enormous work in that formula: eight KV heads instead of thirty-two is a 4x cut in the dominant term, which is why GQA shows up in essentially every model built to be served rather than benchmarked.
Note also what the arithmetic is: a logical requirement. A serving runtime that preallocates a cache pool will show you the pool, not your sequences, which means the useful metric in production is pool occupancy rather than process memory.
Allocated versus reserved, and the double-count that follows
The second common failure is not arithmetic but instrumentation. A caching allocator holds memory it is not currently using, so there are two different numbers and people add them.
In PyTorch's own words, memory_allocated returns "the current GPU memory occupied by tensors in bytes for a given device", while memory_reserved returns "the current GPU memory managed by the caching allocator in bytes". Those are different quantities: tensors versus pool. The documentation notes that allocated "is likely less than the amount shown in nvidia-smi since some unused memory can be held by the caching allocator and some context needs to be created on GPU" — three numbers, then, not two, once the driver's own view is included.
The docstrings do not spell out the containment relationship, but the allocator's snapshot model does: "The size of reserved memory is the sum of all Segments," segments hold blocks, and a block in use is marked allocated. Reserved is the pool; allocated is the occupied part of the pool. Summing them double-counts, and a dashboard that plots "total GPU memory used = allocated + reserved" is reporting a number that corresponds to nothing.
The cache-clearing call is similarly over-trusted. It "release[s] all unoccupied cached memory currently held by the caching allocator" — unoccupied is the whole limitation. It cannot free what live tensors hold, and the documentation is explicit about the ceiling on what it buys you: it "doesn't increase the amount of GPU memory available for PyTorch. However, it may help reduce fragmentation of GPU memory in certain cases." So the honest reason to call it is fragmentation, not capacity, and anything allocated outside the framework's allocator — a comms library, a custom kernel's workspace, the CUDA context itself — is outside its reach and outside both of its counters.
For peak figures, the framework tracks them separately and from program start: peak allocated and peak reserved are each available, and the peak statistics can be reset to re-baseline a measurement around a specific phase. Measuring a single training step or a single batch means resetting first, which is the step most ad-hoc measurements skip.
Matching the optimisation to the term
The reason the accounting is worth doing is that each lever moves a different term, and applying the wrong one wastes a week:
| Lever | Term it reduces | What it costs |
|---|---|---|
| Smaller microbatches | Activation memory per microbatch | Throughput; more steps for the same tokens |
| Activation checkpointing | Saved activations | Recomputation on the backward pass |
| Sharding (ZeRO / FSDP) | Per-GPU training state | Communication, and a harder failure surface |
| Quantisation | Weight or KV storage | Scales and metadata overhead; accuracy risk |
| Paged KV allocation | Allocation waste in the cache | Allocator complexity |
| Prefix sharing | Duplicated KV across requests | Only helps where prefixes genuinely repeat |
An activation-memory problem does not respond to quantising the weights. A concurrency-driven cache problem does not respond to activation checkpointing. Diagnosis first.
Failure modes
| Failure | Mechanism | Symptom |
|---|---|---|
| Sizing on checkpoint size | Weights are the fixed cost, not the peak | Fits on load, OOMs under load |
| GB read as GiB | 7% unit gap | Capacity plans that are short by exactly the gap |
| Summing allocated and reserved | Reserved contains allocated | Phantom usage; wrong scaling decisions |
| Trusting the cache-clearing call | Frees only unoccupied blocks | No capacity gained, time lost |
| Ignoring non-framework allocations | Outside the allocator's counters | Process memory exceeds both counters, unexplained |
| Measuring without resetting peaks | Peaks run from program start | Phase measurements contaminated by earlier phases |
| Capacity from a single-stream benchmark | Cache cost is linear in concurrency | Falls over at the concurrency the plan assumed |
Review checklist
Derive bytes-per-token for the exact model: KV heads, head dimension, layers, cache dtype. Keep the number; it answers every later capacity question.
State the serving target as a pair — context length and concurrent sequences — and compute weights + cache for it. A target that names only one of the two is not a target.
Check the units. Decimal or binary, consistently, with the choice written down.
For training, count bytes per parameter for the actual optimiser and precision rather than assuming the FP32 Adam figure. Mixed precision and 8-bit optimisers change it substantially.
Measure peak allocated and peak reserved separately, resetting peaks around the phase you care about, and never add them.
Reconcile the framework's numbers against the driver's view. The unexplained difference is your non-framework allocation, and it is real.
Identify which term dominates your peak before choosing a lever, and write the dominating term in the ticket.
For a serving fleet, report cache-pool occupancy rather than process memory, since a preallocated pool hides the thing you need to watch.
Related reading
An interactive simulator for continuous batching, chunked prefill and cache occupancy is the natural companion to this arithmetic: the derivation gives the budget, the simulator shows how a scheduler spends it. Work on compressing the cache attacks the dominant serving term directly and is worth reading with the per-token formula in hand, since compression ratios are only meaningful against a known baseline. Architectures that split prefill from decode across different hardware are, in effect, a response to the observation that the two phases have different memory profiles — a point the accounting above makes but does not act on.