What it is about: numbers need storage space
Every number in the model has to sit somewhere in memory. How much space it needs depends on the number format, often called dtype in code (from “data type”). The standard format Float32 uses 32 bits, i.e. 4 bytes per number. A model with 15 million parameters therefore already needs 60 million bytes, just for the weights.
Smaller formats with 16 or 8 bits save space and time but are less precise. Like a ruler with a coarser scale: instead of millimeters there are only centimeters. For many purposes that is perfectly fine, for some it isn't. This chapter shows where it pays off. For your first training run, Float32 is enough.
In training every number counts four times
During training, every weight gets companions:
- the gradient, the slope from the backward pass,
- and two running averages that the AdamW optimizer from the training chapter keeps per weight, the so-called moments.
Weight, gradient, two moments: four numbers at 4 bytes each makes 16 bytes per parameter. With 15 million parameters that is about 240 million bytes, roughly 229 MiB. And the activations are still missing: the intermediate results of the forward pass that have to be kept for the backward pass.
Activations: the hidden memory hog
For the backward pass, PyTorch needs many intermediate results from the forward pass. How many depends on batch size, text length, width and depth. With long texts, the attention table in particular grows a lot (every position with every other).
When memory gets tight: first shrink the microbatch (with gradient accumulation from chapter 19 the effective batch size stays the same), then check text length and model size.
How a decimal number is stored
Computers store decimal numbers similar to scientific notation like 1.5 × 10³. One part, the mantissa, holds the digits and determines how finely graded the number is. The other part, the exponent, determines the order of magnitude: how huge or tiny a number may become. The abbreviation FP stands for “floating point”.
The most important formats:
- FP32 (32 bits): the robust standard.
- FP16 (16 bits): half the space, but a small range; very large or very small numbers break quickly.
- BF16 (16 bits): the same range as FP32, but coarser grading. For neural networks usually the better 16-bit choice, because the range matters more than the last decimal place.
Large training runs now even use FP8 for many matrix multiplications, with sophisticated scaling factors (DeepSeek-V3). For just using a model, 4-bit formats are common too. That is specialist work for particular hardware, not a switch for your learning project.
Mixed precision: the best of both worlds
Mixed precision means: most calculations run in the smaller format, sensitive parts stay in Float32. With Adam, the classic setup also needs about 16 bytes per parameter, by the way: 2 for the 16-bit weights, 2 for the gradients, 4 for a Float32 safety copy of the weights and 8 for the two moments (ZeRO, Rajbhandari et al.). The savings are mainly in activations and computing time.
Our trainer deliberately starts in Float32: fewer sources of error, and it runs the same everywhere (CPU, Mac, NVIDIA). Mixed precision is a later extension.
with torch.autocast(device_type='cuda', dtype=torch.bfloat16):
logits = model(x)
loss = F.cross_entropy(logits.reshape(-1, V), y.reshape(-1))
loss.backward()That is what it would look like on a suitable NVIDIA card. With FP16 you also need a “gradient scaler” so tiny gradients don't vanish to zero. Don't just copy it untested! PyTorch AMP documentation.
Quantization: rounding numbers roughly
When you hear about “4-bit models”, quantization is usually meant: finished weights are rounded afterwards to very few levels to make them smaller. Roughly like saving a photo with fewer colors: much smaller, usually hardly worse, sometimes visibly worse.
Important: only the stored weights get smaller. It doesn't mean everything runs four times faster or that training happens in 4 bits. How much quality suffers depends on the method and the model; “four bits” alone says little about that.
Recomputing activations instead of storing them
One more trick: instead of keeping all intermediate results, you store only some and simply recompute the rest during the backward pass. Memory traded for computing time. That is called activation checkpointing, but it has nothing to do with the save games on disk.
from torch.utils.checkpoint import checkpoint
for block in model.blocks:
x = checkpoint(block, x, use_reentrant=False)For small models this usually costs more than it brings. Only use it once memory is demonstrably tight.
Measuring honestly
if device.type == 'cuda':
torch.cuda.reset_peak_memory_stats()
# A real forward/backward/optimizer step
print(torch.cuda.max_memory_allocated() / 2**20, 'MiB')Always measure a complete training step. A typical trap: the model fits easily into memory during the forward pass, and then crashes at the first optimizer step because AdamW only creates its moments then.
Optimizing step by step
First Float32 as the baseline. Then smaller microbatches with accumulation. Then maybe mixed precision. Each time, write down validation loss, speed and peak memory. A speedup that makes the result worse isn't a free improvement but a trade-off.
Key points
- Every number needs memory: Float32 4 bytes, BF16 2 bytes. Training with AdamW takes roughly 16 bytes per parameter, plus activations.
- Smaller formats save space and time but are coarser. BF16 is usually the best 16-bit choice for networks.
- Quantization rounds finished weights for use. Always measure a complete training step.