Papa Programmer
Lesson 21 of 36

Fitting training into memory

9 min read

Optional

Where the memory goes

  1. Weights. Parameters times bytes per parameter, as Setting up your environment showed.
  2. Gradients. One value per trainable weight.
  3. Optimiser state. The Adam optimiser keeps two running values per trainable weight, usually in 32-bit.
  4. 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.

python
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:

text
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 GB

Full 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:

  1. Is something else using the GPU?
  2. Does the failure come at the first step, which points to weights and state, or after many steps, which points to one long batch?
  3. What is the longest sequence in the failing batch?
  4. 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.

SavesCosts
Adapter (LoRA)Gradients and optimiser stateMay fall short on large shifts
Smaller batchActivationsMore steps, or accumulation
Shorter sequencesActivationsMay cut off the answer
Gradient checkpointingActivationsExtra compute time
Mixed precisionWeights and activationsNeeds hardware support, and care with nan
Memory levers
Four partsWeights, gradients, optimiser state and activations each take memory.
Start with the adapterTraining fewer weights removes the largest costs for big models.
Measure the restSmaller batches, shorter sequences and recompute each trade speed for memory.

Your reading position is saved

0%

0 of 36 complete

Contents

Learning tools