Deep learning in practice · lesson 12 of 13
Parts in this lesson
Awith torch.autocast(device, dtype=torch.float16):run the big multiplications inside this block in 16 bits
Bscaler = torch.amp.GradScaler("cuda")scales the loss up before backward() so small float16 gradients don't become 0
Ctorch.finfo(torch.float16)a type's largest number, smallest number and precision
DFlopCounterMode(display=False)counts the FLOPs of everything run inside it

Hardware, speed and mixed precision

Last updated

Training is mostly multiplying matrices, and how fast that goes decides what you can afford to try. This lesson measures your computer's speed, counts the work a model needs in FLOPs, and looks at the numbers themselves: float32 against the 16-bit float16 and bfloat16, which are faster and smaller but coarser. Automatic mixed precision gets the speed without the coarseness, and the wrong way shows what goes wrong when you skip its safeguards.

By the end of this lesson you can

  • Measure matrix-multiply speed, and say how batch size changes the time per epoch
  • Count a model's FLOPs by hand and with PyTorch's counter
  • Compare float32, float16 and bfloat16 by range and precision
  • Train with autocast, and say when a GradScaler is needed

GPUs and parallel multiply–adds

Multiplying two n×n matrices makes n2 numbers, and each one is a dot product of n multiplies and n adds:

FLOPs=2n3

In words: a FLOP is one floating-point operation, an add or a multiply, and a matrix product needs 2n3 of them. For n=2048 that's 17 billion. The good news is that all n2 dot products are independent, so they can be done at the same time. A CPU has a handful of cores, each doing several multiply–adds at once; a GPU has thousands of simpler cores built to do nothing else, which is why it trains networks many times faster.

This script measures your computer. Lines starting with ~ are timings; yours will be different:

"""How fast this computer multiplies matrices, and what the batch size does to an epoch's time.

Lines starting with ~ are timings: yours will be different."""
import time

import torch
from sklearn.datasets import load_digits
from torch import nn
from torch.nn import functional as F

device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
print("device:", device)


def timed(fn, repeat=5):
    fn()                                            # once to warm up
    if device == "cuda":
        torch.cuda.synchronize()                    # GPU work runs in the background: wait for it
    start = time.perf_counter()
    for _ in range(repeat):
        fn()
    if device == "cuda":
        torch.cuda.synchronize()
    return (time.perf_counter() - start) / repeat


for n in (256, 1024, 2048):
    a, b = torch.randn(n, n, device=device), torch.randn(n, n, device=device)
    seconds = timed(lambda: a @ b)
    flops = 2 * n**3                                # n*n results, each n multiplies and n adds
    print(f"~ {n} x {n} matrix product: {flops / 1e9:.2f} billion FLOPs in {seconds * 1000:.2f} ms,"
          f" {flops / seconds / 1e9:.0f} GFLOP/s")

X, y = load_digits(return_X_y=True)
X, y = torch.tensor(X / 16, dtype=torch.float32, device=device), torch.tensor(y, device=device)
for batch in (8, 64, 512):
    torch.manual_seed(0)
    model = nn.Sequential(nn.Linear(64, 512), nn.ReLU(), nn.Linear(512, 10)).to(device)
    optimizer = torch.optim.SGD(model.parameters(), lr=0.1)

    def epoch():
        for idx in torch.randperm(len(X), device=device).split(batch):
            loss = F.cross_entropy(model(X[idx]), y[idx])
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()

    print(f"~ batch size {batch:3}: {len(X) // batch + (len(X) % batch > 0):3} steps per epoch, {timed(epoch, 3) * 1000:.0f} ms per epoch")
Terminal, in ml-local/7-12
(.venv) $ python speed.py
device: cpu
~ 256 x 256 matrix product: 0.03 billion FLOPs in 0.08 ms, 444 GFLOP/s
~ 1024 x 1024 matrix product: 2.15 billion FLOPs in 4.28 ms, 502 GFLOP/s
~ 2048 x 2048 matrix product: 17.18 billion FLOPs in 34.00 ms, 505 GFLOP/s
~ batch size   8: 225 steps per epoch, 90 ms per epoch
~ batch size  64:  29 steps per epoch, 20 ms per epoch
~ batch size 512:   4 steps per epoch, 5 ms per epoch

The computer that made this output, using only its CPU, did about 500 billion FLOPs a second (500 GFLOP/s) once the matrices were big enough to keep every core busy. A current GPU does tens of trillions. Two habits for timing on a GPU: run once first to warm up, and call torch.cuda.synchronize() before reading the clock, because PyTorch hands GPU work over and carries on without waiting for it.

Batch size and memory

The same script's last lines train for one epoch with three batch sizes. With batches of 8 it takes 225 steps and about 90 ms; with 512, 4 steps and about 5 ms. Each step has a fixed cost (launching operations, the optimiser's update), and big batches give the hardware big matrices to work on, so they use it better.

So why not always use huge batches?

  • Memory. The weights take the same memory whatever the batch size, but backpropagation keeps every layer's outputs for the backward pass, and those grow with the batch. Too big, and a GPU runs out of memory: a CUDA out of memory error. Halve the batch until it fits.
  • Fewer steps. An epoch of 4 steps updates the weights 4 times. Big batches need a larger learning rate, often with warm-up (lesson 7.4), to make the same progress per epoch.
  • Less noise. The noise of small batches helps a little against overfitting (lesson 3.6).

A common choice is the largest batch that fits comfortably, from 32 to a few hundred, with the learning rate tuned for it.

Counting FLOPs

Counting the work in advance tells you how long training will take, and whether a bigger model is affordable. A Linear layer does one multiply and one add per weight per example, so for a whole network:

forward FLOPs≈2×batch×weights

PyTorch can count instead of estimating:

"""Counting the work: FLOPs for one batch, counted by PyTorch and worked out by hand, and memory for the weights."""
import torch
from torch import nn
from torch.utils.flop_counter import FlopCounterMode

model = nn.Sequential(nn.Linear(64, 128), nn.ReLU(), nn.Linear(128, 10))
n_params = sum(p.numel() for p in model.parameters())
weights = 64 * 128 + 128 * 10                       # the multiply-adds per example are one per weight
batch = 32
x = torch.randn(batch, 64)

with FlopCounterMode(display=False) as forward:
    out = model(x)
with FlopCounterMode(display=False) as backward:
    out.sum().backward()

print(f"parameters: {n_params:,} ({weights:,} weights, {n_params - weights} biases)")
print(f"forward,  counted: {forward.get_total_flops():,} FLOPs;  by hand, 2 x batch x weights = {2 * batch * weights:,}")
print(f"backward, counted: {backward.get_total_flops():,} FLOPs")
print(f"forward + backward: {(forward.get_total_flops() + backward.get_total_flops()) / (2 * batch * weights):.2f} times the forward pass")
for name, size in (("float32", 4), ("float16", 2)):
    print(f"weights in {name}: {n_params * size:,} bytes")
Terminal, in ml-local/7-12
(.venv) $ python flops.py
parameters: 9,610 (9,472 weights, 138 biases)
forward,  counted: 606,208 FLOPs;  by hand, 2 x batch x weights = 606,208
backward, counted: 688,128 FLOPs
forward + backward: 2.14 times the forward pass
weights in float32: 38,440 bytes
weights in float16: 19,220 bytes

The forward pass is exactly 2×32×9,472=606,208 FLOPs, as the formula says (the biases and ReLU are too few to count). The backward pass works out two things for each layer: the gradient of its weights and the gradient of its input, each as much work as the forward pass. Here it's 688,128 FLOPs, not twice the forward pass, because nothing needs the gradient of the input images, so the first layer skips that half. In a deep network the first layer is a small part of the whole, and training costs about 3 times the forward pass, which gives a handy rule:

training FLOPs≈6×parameters×training examples seen

In words: 2 for the forward pass and 4 for the backward, per parameter, per example, per epoch. A model with 10 million parameters trained for 10 epochs on 60,000 images needs about 6×107×6×105=3.6×1013 FLOPs; at 500 GFLOP/s, at best about 70 seconds. Real training reaches only part of that peak speed, but the estimate tells you whether to expect minutes or months.

The weights need 4 bytes each in float32: 38,440 bytes here. In 16 bits, half that, which is where the next step starts.

float32, float16, bfloat16

A floating-point number is stored in three parts: a sign bit, an exponent that says roughly how big it is, and a fraction that holds its digits:

x=(−1)sign×2exponent−bias×1.fraction

In words: the exponent picks a power of 2, and the fraction says where between that power and the next one the number lies. More exponent bits reach bigger and smaller numbers; more fraction bits store each number more exactly. The bias (127 for float32) lets the exponent be negative without a sign bit of its own. PyTorch has two 16-bit formats, which split their bits differently:

"""float32, float16 and bfloat16: their ranges, their precision, and the same numbers stored in each."""
import struct

import torch

TYPES = {"float32": torch.float32, "float16": torch.float16, "bfloat16": torch.bfloat16}

print(f"{'':9} {'bits':>4} {'largest':>10} {'smallest normal':>16} {'gap after 1':>12}")
for name, t in TYPES.items():
    info = torch.finfo(t)
    print(f"{name:9} {info.bits:4} {info.max:10.3g} {info.tiny:16.3g} {info.eps:12.3g}")

print()
for value in (0.1, 1 / 3, 300.0, 70000.0, 1e-8):
    stored = [torch.tensor(value, dtype=t).item() for t in TYPES.values()]
    print(f"{value:<12.6g} stored as: " + "  ".join(f"{n} {s:.8g}" for n, s in zip(TYPES, stored)))
print("300 squared:", "  ".join(f"{n} {(torch.tensor(300.0, dtype=t) ** 2).item():g}" for n, t in TYPES.items()))

# the bits of 0.1 in each format: sign | exponent | fraction
bits32 = format(struct.unpack(">I", struct.pack(">f", 0.1))[0], "032b")
bits16 = format(struct.unpack(">H", struct.pack(">e", 0.1))[0], "016b")
bitsbf = format(torch.tensor(0.1, dtype=torch.bfloat16).view(torch.int16).item() & 0xFFFF, "016b")
print()
print("0.1 in bits (sign | exponent | fraction):")
print(f"  float32   {bits32[0]} | {bits32[1:9]} | {bits32[9:]}")
print(f"  float16   {bits16[0]} | {bits16[1:6]} | {bits16[6:]}")
print(f"  bfloat16  {bitsbf[0]} | {bitsbf[1:9]} | {bitsbf[9:]}")
Terminal, in ml-local/7-12
(.venv) $ python floats.py
          bits    largest  smallest normal  gap after 1
float32     32    3.4e+38         1.18e-38     1.19e-07
float16     16   6.55e+04          6.1e-05     0.000977
bfloat16    16   3.39e+38         1.18e-38      0.00781

0.1          stored as: float32 0.1  float16 0.099975586  bfloat16 0.10009766
0.333333     stored as: float32 0.33333334  float16 0.33325195  bfloat16 0.33398438
300          stored as: float32 300  float16 300  bfloat16 300
70000        stored as: float32 70000  float16 inf  bfloat16 70144
1e-08        stored as: float32 9.9999999e-09  float16 0  bfloat16 1.0011718e-08
300 squared: float32 90000  float16 inf  bfloat16 90112

0.1 in bits (sign | exponent | fraction):
  float32   0 | 01111011 | 10011001100110011001101
  float16   0 | 01011 | 1001100110
  bfloat16  0 | 01111011 | 1001101
Bit layoutsthe same number, 0.1, in three formats
float32001111011100110011001100110011011 sign · 8 exponent · 23 fraction bitsfloat1600101110011001101 sign · 5 exponent · 10 fraction bitsbfloat1600111101110011011 sign · 8 exponent · 7 fraction bitssignexponentfraction
numberfloat32float16bfloat16
0.10.0999755860.10009766
0.333333340.333251950.33398438
300300300
70000inf70144
9.9999999e-0901.0011718e-08
largest3.4e+386.55e+043.39e+38
gap after 11.19e-070.0009770.00781

0.1 is stored as 0.1 in float32, 0.099975586 in float16 and 0.10009766 in bfloat16. More exponent bits reach bigger and smaller numbers; more fraction bits store each one more exactly. bfloat16 keeps float32's 8 exponent bits and gives up fraction bits; float16 does the opposite.

  • float32: 8 exponent bits, 23 fraction bits. Huge range, about 7 digits. The default.
  • float16: 5 exponent bits, 10 fraction bits. About 3 digits, and a small range: nothing above 65,504, so 70,000 and 3002 become inf; and nothing smaller than about 6×10−8, so 10−8 becomes 0. (Below the smallest normal number, 6.1×10−5, it keeps going with fewer digits down to 6×10−8.)
  • bfloat16 ("brain float", from Google): float32's 8 exponent bits, only 7 fraction bits. The same range as float32, so nothing overflows, but only 2 to 3 digits: 70,000 is stored as 70,144, and the gap after 1 is 0.0078.

Half the bits means half the memory, and modern GPUs multiply 16-bit numbers several times faster than 32-bit ones. The cost is precision, and for float16 range.

Automatic mixed precision

Mixed precision (Micikevicius and others, 2018) uses 16 bits where it's safe and fast, mostly the matrix multiplications, and float32 where precision matters: the weights themselves, the loss, sums over many numbers. torch.autocast decides which operation gets which, inside a with block:

"""Automatic mixed precision: the same training in float32, and with autocast doing the big multiplications in 16 bits.

On an NVIDIA GPU this uses float16 with a GradScaler; on a CPU, bfloat16, which needs no scaler."""
import torch
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from torch import nn
from torch.nn import functional as F

device = "cuda" if torch.cuda.is_available() else "cpu"
low = torch.float16 if device == "cuda" else torch.bfloat16
print("device:", device, "  16-bit type:", low)

X, y = load_digits(return_X_y=True)
X_train, X_val, y_train, y_val = train_test_split(X / 16, y, test_size=500, stratify=y, random_state=0)
X_train, X_val = (torch.tensor(a, dtype=torch.float32, device=device) for a in (X_train, X_val))
y_train, y_val = (torch.tensor(a, device=device) for a in (y_train, y_val))

for use_amp in (False, True):
    torch.manual_seed(0)
    model = nn.Sequential(nn.Linear(64, 256), nn.ReLU(), nn.Linear(256, 10)).to(device)
    optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
    scaler = torch.amp.GradScaler(device, enabled=use_amp and low == torch.float16)
    for epoch in range(15):
        for idx in torch.randperm(len(X_train), device=device).split(32):
            with torch.autocast(device, dtype=low, enabled=use_amp):
                logits = model(X_train[idx])            # Linear layers run in 16 bits under autocast
                loss = F.cross_entropy(logits, y_train[idx])
            optimizer.zero_grad()
            scaler.scale(loss).backward()              # with the scaler off, this is just loss.backward()
            scaler.step(optimizer)
            scaler.update()
    with torch.no_grad():
        accuracy = (model(X_val).argmax(1) == y_val).float().mean().item()
    print(f"{'autocast' if use_amp else 'float32 ':8}: validation accuracy {accuracy:.3f};"
          f" logits {logits.dtype}, loss {loss.dtype}, weights {model[0].weight.dtype}")
Terminal, in ml-local/7-12
(.venv) $ python amp.py
device: cpu   16-bit type: torch.bfloat16
float32 : validation accuracy 0.962; logits torch.float32, loss torch.float32, weights torch.float32
autocast: validation accuracy 0.964; logits torch.bfloat16, loss torch.float32, weights torch.float32

Inside autocast, the Linear layers produced bfloat16 logits, but the loss came out in float32 (autocast runs cross_entropy in float32), and the weights stayed float32 throughout. Validation accuracy was 96.2% without autocast and 96.4% with it: no loss of quality. The script doesn't time the two runs: the speed-up comes from GPUs with fast 16-bit hardware, where it can be large, and on a CPU there may be none.

The script picks float16 on an NVIDIA GPU and bfloat16 on a CPU. float16 needs one more piece, a GradScaler, because of its small range:

  1. Multiply the loss by a big number, 65,536 to start, before backward(). Every gradient is multiplied by the same number, which lifts the tiny ones above float16's floor.
  2. Before the optimiser's step, divide the gradients back down, in float32.
  3. If any gradient became inf or nan, skip that step and halve the scale. If 2,000 steps go by without trouble, double it.

bfloat16 has float32's range, so it needs no scaler: GradScaler(enabled=False) turns it into a pass-through, which is how the script uses one loop for both.

Wrong way: plain float16 training

Why not just convert the whole model with model.half() and train? Two things go wrong, and mixed precision exists to stop both:

"""The wrong way: plain float16 training, without loss scaling and without float32 weights."""
import copy

import torch
from sklearn.datasets import load_digits
from torch import nn
from torch.nn import functional as F

X, y = load_digits(return_X_y=True)
X, y = torch.tensor(X / 16, dtype=torch.float32), torch.tensor(y)

# 1. Gradients too small for float16. Train a model well in float32, then work out one
#    gradient in float32 and again in float16, with and without scaling the loss first.
torch.manual_seed(0)
model = nn.Sequential(nn.Linear(64, 256), nn.ReLU(), nn.Linear(256, 256), nn.ReLU(), nn.Linear(256, 10))
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
for epoch in range(20):
    for idx in torch.randperm(len(X)).split(32):
        loss = F.cross_entropy(model(X[idx]), y[idx])
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
xb, yb = X[:256], y[:256]
model.zero_grad()
F.cross_entropy(model(xb), yb).backward()
g32 = torch.cat([p.grad.flatten() for p in model.parameters()])
print(f"float32 gradient: {(g32 != 0).sum().item():,} of {g32.numel():,} numbers are not 0;"
      f" {((g32 != 0) & (g32.abs() < 6e-8)).sum().item():,} of those are smaller than float16's smallest number")
half = copy.deepcopy(model).half()
for scale in (1, 65536):
    half.zero_grad()
    (F.cross_entropy(half(xb.half()).float(), yb) * scale).backward()
    g16 = torch.cat([p.grad.float().flatten() for p in half.parameters()]) / scale
    lost = ((g16 == 0) & (g32 != 0)).sum().item()
    print(f"float16, loss x {scale:5}: {lost:3} gradient numbers became 0, {torch.isinf(g16).sum().item()} became inf")

# 2. Weights too coarse for small updates. Train from scratch with the weights themselves
#    stored in 16 bits, and count the first layer's weights that never changed.
print()
for dtype in (torch.float32, torch.float16, torch.bfloat16):
    torch.manual_seed(0)
    model = nn.Sequential(nn.Linear(64, 256), nn.ReLU(), nn.Linear(256, 10)).to(dtype)
    start = model[0].weight.detach().clone()
    optimizer = torch.optim.SGD(model.parameters(), lr=0.001)
    for epoch in range(10):
        for idx in torch.randperm(len(X)).split(32):
            loss = F.cross_entropy(model(X[idx].to(dtype)).float(), y[idx])
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
    with torch.no_grad():
        accuracy = (model(X.to(dtype)).argmax(1) == y).float().mean().item()
        unchanged = (model[0].weight == start).float().mean().item()
    print(f"weights in {str(dtype)[6:]:8}: {unchanged:.1%} of the first layer's weights never changed; accuracy {accuracy:.3f}")
Terminal, in ml-local/7-12
(.venv) $ python fp16_wrong.py
float32 gradient: 60,440 of 85,002 numbers are not 0; 479 of those are smaller than float16's smallest number
float16, loss x     1: 425 gradient numbers became 0, 0 became inf
float16, loss x 65536:   0 gradient numbers became 0, 0 became inf

weights in float32 : 11.9% of the first layer's weights never changed; accuracy 0.214
weights in float16 : 81.7% of the first layer's weights never changed; accuracy 0.149
weights in bfloat16: 97.8% of the first layer's weights never changed; accuracy 0.066

Gradients underflow. In a well-trained model many gradients are tiny. Of the 60,440 non-zero gradient numbers here, 479 are smaller than anything float16 can hold, and computed in float16, 425 of them became exactly 0: those weights get no update at all. Multiply the loss by 65,536 first, as a GradScaler does, and none are lost, with none overflowing either. Here it's under 1% of the gradient; in bigger models, with more layers multiplying small numbers, it can be most of it.

Small updates vanish. Store the weights themselves in 16 bits and train from scratch with a learning rate of 0.001. A weight near 0.1 in float16 can only change in steps of about 0.00006 (bfloat16: 0.0005), and an update η×gradient smaller than half a step rounds back to the same weight. After 10 epochs, 81.7% of the first layer's float16 weights, and 97.8% of the bfloat16 ones, never changed. In float32 only 11.9% never changed, and those are weights from pixels that are blank in every image, so their gradient is always 0. Accuracy follows: 21.4% in float32 after this short, slow run, 14.9% in float16, 6.6% in bfloat16.

This is why autocast keeps the weights in float32 and converts copies for each multiplication, and why float16 comes with a GradScaler. Use torch.autocast and, for float16, a GradScaler, rather than .half().

Check what you learned

About how many FLOPs does one forward pass of a batch of 100 take through a network with 50,000 weights?
Why does float16 training need a GradScaler but bfloat16 doesn’t?
Under torch.autocast, what type are the model’s weights?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Machine Learning