R330 · Infrastructure for agents at scale › Inference providers and serving reliability

The checkpoint size is not the budget: accounting for GPU memory in training and serving

Read the original

Authors Pallavi Ahuja

inference-servingkv-cachegpu-memorycapacity-planningtraining-infrastructuremeasurement

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:

ComponentBytes per parameter
Weights (FP32)4
Gradients (FP32)4
Adam first moment4
Adam second moment4
Optimiser state total16

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:

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:

LeverTerm it reducesWhat it costs
Smaller microbatchesActivation memory per microbatchThroughput; more steps for the same tokens
Activation checkpointingSaved activationsRecomputation on the backward pass
Sharding (ZeRO / FSDP)Per-GPU training stateCommunication, and a harder failure surface
QuantisationWeight or KV storageScales and metadata overhead; accuracy risk
Paged KV allocationAllocation waste in the cacheAllocator complexity
Prefix sharingDuplicated KV across requestsOnly 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

FailureMechanismSymptom
Sizing on checkpoint sizeWeights are the fixed cost, not the peakFits on load, OOMs under load
GB read as GiB7% unit gapCapacity plans that are short by exactly the gap
Summing allocated and reservedReserved contains allocatedPhantom usage; wrong scaling decisions
Trusting the cache-clearing callFrees only unoccupied blocksNo capacity gained, time lost
Ignoring non-framework allocationsOutside the allocator's countersProcess memory exceeds both counters, unexplained
Measuring without resetting peaksPeaks run from program startPhase measurements contaminated by earlier phases
Capacity from a single-stream benchmarkCache cost is linear in concurrencyFalls over at the concurrency the plan assumed

Review checklist

  1. Derive bytes-per-token for the exact model: KV heads, head dimension, layers, cache dtype. Keep the number; it answers every later capacity question.

  2. 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.

  3. Check the units. Decimal or binary, consistently, with the choice written down.

  4. 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.

  5. Measure peak allocated and peak reserved separately, resetting peaks around the phase you care about, and never add them.

  6. Reconcile the framework's numbers against the driver's view. The unexplained difference is your non-framework allocation, and it is real.

  7. Identify which term dominates your peak before choosing a lever, and write the dominating term in the ticket.

  8. For a serving fleet, report cache-pool occupancy rather than process memory, since a preallocated pool hides the thing you need to watch.

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.

Part of the Research notes on nowucca.com. Figures and claims are the source's own unless the summary says otherwise.