Fitting training into memory
9 min read
Where the memory goes
- Weights. Parameters times bytes per parameter, as Setting up your environment showed.
- Gradients. One value per trainable weight.
- Optimiser state. The Adam optimiser keeps two running values per trainable weight, usually in 32-bit.
- Activations. The intermediate results of the forward pass, kept so the backward pass can use them. They grow with batch size and sequence length.
The first three depend on how many weights you train. The fourth depends on the data you feed in. That split tells you which lever to pull: if the weights and optimiser dominate, train fewer weights. If the activations dominate, shrink the batch or the sequence, or recompute.
Estimate it in code
The program below estimates memory for a 7 billion parameter model with 32 layers and a width of 4,096, in four setups. It rests on rough rules: 16 bytes per trainable weight for weights, gradients and Adam state in the common mixed-precision setup, about 34 bytes per token per unit of width per layer for stored activations in 16-bit without recomputation, and about 2 for each layer when you recompute. It leaves out the attention scores, fragmentation and framework overhead. Use it to compare options and not to promise that something fits.
params = 7e9
layers, width = 32, 4096
lora_trainable = 4_194_304
sequence = 1024
def gigabytes(value):
return value / 1e9
def activations(batch, recompute):
per_layer = (2 if recompute else 34) * sequence * batch * width
extra = 34 * sequence * batch * width if recompute else 0
return per_layer * layers + extra
def estimate(name, trainable, batch, recompute):
if trainable == params:
state = 16 * params
else:
state = 2 * params + 16 * trainable
total = state + activations(batch, recompute)
print(f"{name:34} state {gigabytes(state):6.1f} activations {gigabytes(activations(batch, recompute)):5.1f} total {gigabytes(total):6.1f} GB")
estimate("full fine-tuning, batch 8", params, 8, False)
estimate("LoRA, batch 8", lora_trainable, 8, False)
estimate("LoRA, batch 8, recompute", lora_trainable, 8, True)
estimate("LoRA, batch 2, recompute", lora_trainable, 2, True)It prints:
full fine-tuning, batch 8 state 112.0 activations 36.5 total 148.5 GB
LoRA, batch 8 state 14.1 activations 36.5 total 50.6 GB
LoRA, batch 8, recompute state 14.1 activations 3.3 total 17.4 GB
LoRA, batch 2, recompute state 14.1 activations 0.8 total 14.9 GBFull fine-tuning needs more than 100 GB for weights and optimiser state alone, which no single consumer card has. Switching to LoRA drops the state to about 14 GB, which is mainly the frozen 16-bit weights. The activations at batch 8 still take about 36 GB, so the total does not fit a 24 GB card. Recomputing activations cuts them to about 3 GB and the total to 17.4 GB, which fits under 24 GB. A batch of 2 lowers the total to 14.9 GB and leaves more room for longer sequences. Quantising the frozen weights, covered in Quantisation and QLoRA, would lower the state again.
The levers, one at a time
Train fewer weights. An adapter removes most of the gradient and optimiser memory. It is the biggest single saving for large models.
Lower the batch size, and accumulate. A smaller per-device batch reduces activations in proportion. Gradient accumulation keeps the effective batch size, as Batch size, epochs and steps showed, at the price of speed.
Shorten the sequences. Activations grow with sequence length. Check the length distribution of your examples, and set a maximum that keeps the answer. Truncating can cut off the answer or the evidence, so inspect examples after tokenisation.
Gradient checkpointing. The framework stores only some of the activations and recomputes the rest during the backward pass. It saves a lot of memory and costs extra compute, often something like a quarter more time. Use the documented option and measure the change.
Mixed precision. Using 16-bit numbers for most of the arithmetic halves the activation memory and speeds up training on suitable hardware. Support and numeric behaviour depend on the chip and the framework. Watch for a loss that becomes nan, and compare with a known good run.
Reading an out-of-memory error
An out-of-memory error says an allocation failed. It does not always mean the weights alone are too large. Check, in this order:
- Is something else using the GPU?
- Does the failure come at the first step, which points to weights and state, or after many steps, which points to one long batch?
- What is the longest sequence in the failing batch?
- Restart a small run after changing one setting, and note the memory it reaches.
The Transformers GPU training guide lists the options and how to enable them.
| Saves | Costs | |
|---|---|---|
| Adapter (LoRA) | Gradients and optimiser state | May fall short on large shifts |
| Smaller batch | Activations | More steps, or accumulation |
| Shorter sequences | Activations | May cut off the answer |
| Gradient checkpointing | Activations | Extra compute time |
| Mixed precision | Weights and activations | Needs hardware support, and care with nan |
Which setting saves the most memory first?
A training run fails with out of memory.
Activations dominate memory at large batch sizes, so cut them first.
What does gradient checkpointing trade?
It lowers memory use.
Some values are recomputed in the backward pass instead of stored.
Why does LoRA help memory?
Full tuning does not fit on your GPU.
Optimiser state for billions of weights is large. LoRA trains millions instead.
Your reading position is saved
0 of 36 complete
Lesson complete
Fitting training into memory
Up next