AI State of the Art
SOTA/Inference & Optimization/26 min
Section 132

Inference memory optimisation: offloading weights and activations

Listen as a podcast →

First, do not conflate two different accounts

This is the most common confusion in the subject, and it has to be cleared up before anything else: training memory and inference memory are not counted the same way. They are not the same items, and they are not the same order of magnitude.

During trainingDuring inference
Model weightsyesyes
Gradientsyes, as much as the weightsno
Optimizer statesyes, and the largest itemno
Activations kept for the backward passyesno
Attention cachenoyes, and it grows with every token
Transient intermediate buffersyesyes, but small

The training account is covered in detail in ZeRO: four items, roughly 12 bytes per parameter in the standard setup, of which 8 for the AdamW optimizer alone, that is 84 GB for a 7-billion-parameter model, before a single activation is stored. Let us not repeat it here.

This page is about inference, where only three items remain, and where the item that grows without bound is a different one.

GPU memory decomposition tree. The Total GPU Memory box splits into two branches. On the left, Model States subdivides into Optimizer States, Gradients and Parameters. On the right, Residual States subdivides into Activation, Temporary Buffers and Unusable Fragment Memory.
Read this diagram with care: it is the training-memory tree. At inference, two of its branches vanish outright (optimizer states and gradients) and a branch missing from the drawing becomes dominant: the attention cache. The diagram remains useful for its right-hand branch, temporary buffers and memory lost to fragmentation, which exists in both regimes.Source : LLM Foundations, course notes by Yutu Yang

The three items at inference

1. The weights: large, but fixed

A 70-billion-parameter model in FP16 weighs 140 GB: 2 bytes per parameter × 70 × 10⁹. That number never moves during serving. It is a floor, paid once, whatever the number of requests.

The problem is immediate: the most common datacentre card, an A100 GPU, tops out at 80 GB of video memory (VRAM, Video Random Access Memory, the graphics card's own working memory). 140 does not fit in 80.

2. The attention cache: small at first, then unbounded

The attention cache holds the keys and values already computed so they need not be recomputed at every token, see KV cache. This is the item that makes inference hard, because it grows with every token produced and every request served.

Let us compute it for a 70-billion-parameter model with 80 layers, sharing its keys and values across groups of heads so that the cache dimension per layer is 1,024, in FP16:

2×80×1024×2 bytes=327,680 bytes per token2 \times 80 \times 1024 \times 2\ \text{bytes} = 327{,}680\ \text{bytes per token}

The factors: the 2 on the left because there are two tensors, keys and values; the 80 is the number of layers, each with its own cache; the 1,024 is the cache dimension within one layer; the 2 bytes on the right is the cost of one FP16 number (16 bits ÷ 8). That is about 0.33 MB per token.

Over a 128,000-token context that comes to 128,000×0.33 MB≈42 GB128{,}000 \times 0.33\ \text{MB} \approx 42\ \text{GB}, for a single request. Set against 140 GB of weights: at long context, the cache stops being a detail and becomes comparable to the model itself.

3. Intermediate buffers: negligible, except by accident

Producing a token requires temporary arrays of numbers, allocated then discarded at once. The vLLM authors measure them on a 13-billion-parameter model served on a 40 GB A100: the weights take about 65 % of the card, the caches close to 30 %, and these transient buffers the small remainder. So they can be ignored, except in two cases: processing a very long prompt in one block, and memory lost to fragmentation, which is not doing useful work but is not available either.

Lever 1: shrink the weights

That is quantization: storing each parameter in fewer bits. The full argument is in Quantization: the concepts, with its variants in GPTQ and AWQ.

The arithmetic, in one line. A 4-bit parameter costs half a byte, so:

70×109×0.5 byte=35 GB70 \times 10^9 \times 0.5\ \text{byte} = 35\ \text{GB}

The 70-billion-parameter model fits on an 80 GB card, with 45 GB left over for caches, a good dozen long requests. You went from "impossible" to "comfortable" by changing a number format.

The side benefit is a double one: fewer bytes to stream out of memory, so faster as well, for the reason set out in Quantization: the concepts. This is the only technique on the page that wins on both counts at once. In exchange, it approximates the weights: it is the only lever here that touches output quality.

Lever 2: shrink the attention cache

Three techniques, all covered elsewhere, that compound.

  • Share keys and values across attention heads. Instead of every head having its own set, several heads share one. The cache is divided by the size of a group, a factor of 4 to 8 on current models. See Grouped-query attention. This is an architectural decision: it is made when the model is designed, not at deployment.
  • Quantize the cache itself. Moving keys and values from 16 to 8 bits halves this item. The 42 GB computed above falls to 21. Quality suffers little but it does suffer; the details are in KV cache.
  • Stop wasting reserved memory. This is not a reduction of the cache but the removal of the space wasted around it: see PagedAttention and vLLM. The authors measured 60 % to 80 % of cache memory lost in systems that reserved the worst case.

Lever 3: move memory elsewhere, offloading

This is the page's own subject, and the most widely misunderstood.

The principle

The idea is appealing. A computer has several memories of very different sizes and speeds: the graphics card's (fast, small), the machine's main memory (slow, large), the disk (very slow, vast). Offloading means keeping on the card only what is needed right now, and parking the rest in main memory, fetching it back on demand.

For a model that means keeping in main memory the layers whose turn it is not, and pulling each layer onto the card just before using it. The 70-billion-parameter model then runs on a 32 GB card, the 140 GB is split between card and main memory.

The image: instead of getting the elephant into the car, you cut it up and make round trips with the truck parked alongside.

Why it is slow, worked out in the open

And here is the reason, which is exactly the same bandwidth argument as everywhere in this part of the course, applied to a far narrower pipe.

  • An A100 GPU's own memory reads at roughly 2,000 GB/s.
  • The link between card and main memory, a 4th-generation PCIe bus in a 16-lane configuration (PCIe for Peripheral Component Interconnect Express, the standard for connecting expansion cards), carries roughly 32 GB/s.

The pipe to main memory is therefore about sixty times narrower than the pipe to the card's own memory. The consequence, for a fully offloaded 70-billion-parameter model: producing a single token requires pushing all 140 GB of weights across that bus.

140 GB32 GB/s≈4.4 seconds per token\frac{140\ \text{GB}}{32\ \text{GB/s}} \approx 4.4\ \text{seconds per token}

Four and a half seconds for one word. Against the 0.07 seconds the same read would have taken from the card's memory (140 ÷ 2,000). Full offloading does not degrade speed, it destroys it, by a factor of sixty, which is exactly the ratio of the two bandwidths. There is nothing else to understand: it is the ratio of the pipes.

Partial offloading scales pro rata. Keep 70 GB on the card and offload the other 70, and each token costs 70÷32≈2.270 \div 32 \approx 2.2 seconds of transfer, against 0.035 seconds for the half that stayed put. Time is almost entirely dictated by whatever was offloaded.

The rule to remember

Offloading trades memory for transfer time, at a rate dictated by the ratio of bandwidths, about 60 to 1 between main memory and the card's. It is therefore never an optimization: it is a last resort when the model does not otherwise fit. Before reaching for it, always try quantization, which shrinks the size without changing the pipe.

When it is defensible anyway

  • Running a model you could not run at all. Four seconds per token is not absurd for exploring a model on a personal machine. Zero tokens per second is worse.
  • Background processing, with no user waiting. With a thousand documents to summarize overnight, per-request latency is irrelevant and only total throughput matters.
  • Offloading optimizer states during training, which is a different and much better case: those states are used once per step, at update time, which leaves room to slide the transfers underneath the computation. That is covered in ZeRO.

That last point explains an asymmetry that often surprises people: offloading works well in training and badly in inference. The reason is not technical but rhythmic. In training, a step is long and transfers can hide behind computation. In inference decoding, each token is short and there is nothing to hide behind.

The training case: recomputation

For the record, and because the confusion is common: in training there is a fourth lever with no inference equivalent. You discard the forward pass's activations instead of keeping them, and recompute them when the backward pass needs them. You trade memory for computation, not for transfer. See Activation recomputation.

At inference that lever does not exist: there is no backward pass, hence no activation to keep.

How the levers stack

Here is the full reasoning for fitting a 70-billion-parameter model onto a single 80 GB card, with the figures.

StepWeightsCache available
Start, FP16140 GBdoes not fit
4-bit quantization35 GB45 GB
Cache shared across heads (already in the architecture)35 GB45 GB, but each request costs 4 to 8 times less
8-bit cache quantization35 GB45 GB, each request costs another half
Cache paging35 GBthe 45 GB are actually used, not reserved for nothing

The methodological point, more important than the numbers: these levers do not add, they multiply, and they do not act on the same item. Quantization acts on the weights, head sharing and cache quantization act on the cache, paging acts on the waste around it. Stacking two techniques aimed at the same item does not double the gain.

And none is free. Quantization approximates the weights. Cache quantization approximates the cache. Head sharing is an architectural choice you cannot make after the fact. Offloading costs a factor of sixty in speed. The only technique on this list that costs nothing at all is cache paging, because all it does is remove waste.

Recommendations by situation

SituationWhere to start
Inference, one card too small4-bit weight quantization, before anything else
Long-context inferencecheck the model's head sharing, then quantize the cache
Many concurrent requestscache paging and continuous batching
The model still does not fitoffloading, accepting the loss of speed
Fine-tuning on a small cardQLoRA and activation recomputation
Training across several cardsFSDP or ZeRO

What to take away

Three items at inference (weights, attention cache, transient buffers) not the four of training. The weights are large but fixed, and quantization cuts them fourfold without changing hardware. The cache is small at first but grows without bound with context length and request count, and it is what caps a server's throughput. As for offloading, it is not optimization but rescue: it buys space at the cost of a factor of sixty in speed, because it pushes the weights through a pipe sixty times narrower.

Check your understanding0 / 5

1. Why does the memory needed to serve a model have so little to do with the memory needed to train it?

2. What makes the attention cache the hard item of inference, given that it starts from zero on every request?

3. Among the page's levers, what sets weight quantization apart from all the others?

4. Offloading lets a 70 billion parameter model run on a 32 GB card. Why does the page refuse to call that an optimization?

5. Offloading works well during training (ZeRO) and badly at inference. Why the asymmetry?