Where does training memory go?

Introduction

Project introduction

Where does training memory go?

A model that easily fits on a GPU for answering questions can run out of memory the moment you try to train it. Training keeps much more than the weights. It also keeps a gradient for every weight, the optimizer's running averages, and the intermediate results of the forward pass that the backward pass needs.

Each of these has a size you can work out in advance from a few numbers, namely how many parameters there are, how many bytes each number takes, the batch size and the sequence length. Once you can count the bytes, you can see which trick will help and by how much.

Four kinds of memory

Weights, gradients and optimizer state are the model states. They depend only on the parameter count. Adam with mixed precision needs 16 bytes per parameter, so a 7 billion parameter model needs about 112 GB before it sees any data.

Activations are the tensors kept from the forward pass. They grow with the batch and the sequence length, so a long batch can run out of memory even when the model states fit. In this project you predict each kind, then cut it, using checkpointing for activations, fewer bytes per weight for the weights, and LoRA for the gradients and optimizer state.

Where training memory goes

batch 256
weights
grads
Adam
activations
4.2M parameters, float32 Adam86.15 MB
Measureevery saved tensor
Checkpointkeep fewer activations
Quantizefewer bytes per weight
LoRAtrain a small adapter

What you will build

01

A memory count

Bytes for model states and for the activations of a transformer layer.

02

A checkpoint plan

Decide which layer inputs to keep and what to rebuild during backward.

03

Smaller weights and updates

Int8 weights with absmax scales, and the size of a LoRA fine-tune.

Start with the model states

Count the bytes of weights, gradients and optimizer state for any setup.

Continue to Problem 1