AI Logic

Distributed Training and Memory Saving

Mixed Precision Training

Updated:

How mixed precision training works. Left: one training step that rounds the FP32 master weights to FP16, runs the forward and backward passes, multiplies the loss by S, divides the gradients by S, and then updates the FP32 weights. Top right: with 8× loss scaling, gradients between 2 to the −27 and 2 to the −24 fall into the range representable in FP16. Bottom right: the bit layouts of FP32, FP16, and BF16

Background and overview

Mixed precision training is a training method that holds and computes weights, activations, and gradients as 16-bit floating-point numbers (FP16), and performs only the weight update in 32 bits (FP32). Without losing accuracy, it roughly halves the memory used for training and can speed up training on GPUs with fast 16-bit arithmetic.

Deep learning training is usually done in FP32. Switching to FP16 halves the number of bits per value, so twice as many values fit in the same memory, and data transfers to and from memory are halved as well. On GPUs at the time of the paper, FP16 arithmetic was 2–8× faster than FP32. However, FP16 has a much narrower representable range, and simply substituting it causes small gradients to become 0 and weight updates to vanish, reducing accuracy.

In a 2018 paper (ICLR), Micikevicius et al. showed that combining the following three techniques allows training to reach the same accuracy as FP32 without changing hyperparameters.

  • FP32 master weights: keep an FP32 master copy of the weights and apply updates to it
  • Loss scaling: multiply the loss by SS before back-propagating so that small gradients do not become 0
  • FP32 accumulation: sum FP16 products in FP32 and then convert back to FP16

As an analogy, it is like writing small daily transactions in the narrow columns of a notepad (FP16), while recording the bank balance (FP32) without dropping any digits. The fine-grained calculations are done quickly, while small increments are not lost to rounding as they accumulate.

Theory

One training step of mixed precision training proceeds as follows (left of the figure above; Figure 1 and Section 3 of the paper).

  1. Round the FP32 master weights to FP16 to make a copy of the weights.
  2. Run the forward pass with FP16 weights and activations and compute the loss LL. Sums of products, such as matrix multiplications, are accumulated in FP32 and then converted back to FP16 for storage.
  3. Run backpropagation in FP16 starting from S⋅LS \cdot L, the loss multiplied by a factor SS.
  4. Divide the resulting gradients by SS to restore their original scale. If the gradients contain inf or NaN (overflow), skip this update.
  5. Update the FP32 master weights with the optimizer using the restored gradients.

Multiplying the loss by SS makes every gradient computed in backpropagation SS times larger as well, by the chain rule. The gradient with respect to the weights θ\boldsymbol{\theta} is

∇θ(S⋅L)=S⋅∇θL,g=1S ∇θ(S⋅L)\nabla_{\boldsymbol{\theta}} (S \cdot L) = S \cdot \nabla_{\boldsymbol{\theta}} L, \qquad \boldsymbol{g} = \frac{1}{S}\,\nabla_{\boldsymbol{\theta}} (S \cdot L)

and dividing by SS, as in the right-hand equation, recovers the original gradient g\boldsymbol{g}. No extra computation is needed during backpropagation. The division by SS is done before any other processing that uses the gradients, such as gradient clipping or Weight Decay. This way, their hyperparameters do not need to change from FP32 training.

In PyTorch's automatic mixed precision (torch.autocast and GradScaler), the model weights stay in FP32, and inside autocast each operation such as a matrix multiplication or convolution is cast to FP16 for computation. The model weights themselves play the role of the "FP32 master weights," so there is no need to make a copy yourself.

Why FP16 does not reduce accuracy

FP16 is a format with 1 sign bit, 5 exponent bits, and 10 mantissa bits, and the nonzero magnitudes it can represent range from about 2−242^{-24} to 65,50465{,}504 (right of the figure above). FP32 has 8 exponent bits and 23 mantissa bits, so it can represent a much wider range at much finer granularity. Each of the three techniques of mixed precision training addresses one of three problems that arise from this difference.

TechniqueProblem it preventsExample shown in the paper
FP32 master weightsUpdate values so small that they become 0; updates so small relative to the weights that adding them does not change the weightsIn a Mandarin speech recognition model, updating FP16 weights directly reduced accuracy by 80% relative
Loss scalingSmall gradients falling below 2−242^{-24} and becoming 0SSD diverged without loss scaling; with a factor of 8 it matched FP32 accuracy
FP32 accumulationRounding errors accumulating when sums of products are accumulated in FP16Some models did not reach FP32 training accuracy without FP32 accumulation

There are two reasons FP32 master weights are needed. One is that if an update value, the gradient multiplied by the learning rate, is smaller than 2−242^{-24}, it becomes 0 in FP16. In the paper's speech recognition model, about 5% of the weight gradients had exponents smaller than −24. The other is that if a weight is 2,048 or more times larger than the update value, the update is truncated when aligning the exponents during FP16 addition, so the weight does not change. This is because FP16 has only 10 mantissa bits. Adding in FP32 avoids both problems.

The reason loss scaling is needed is that many gradient values are skewed toward the small end, below the range representable in FP16. In the activation gradients the paper collected while training SSD (object detection), the upper part of FP16's representable range was almost unused, while many values fell below the smallest representable magnitude and became 0. Values smaller than 2−272^{-27} were irrelevant to training, whereas values in [2−27,2−24)[2^{-27}, 2^{-24}) needed to be preserved, and a factor of 8 (raising the exponent by 3) was enough.

The factor SS can be made large without harm as long as the maximum gradient multiplied by it does not exceed 65,504. Beyond that, values become inf or NaN, and updating with them corrupts the weights. The paper showed two approaches: choosing a fixed factor (values from 8 to 32K were used) and skipping the update whenever an overflow is detected. PyTorch's GradScaler adjusts this automatically.

  • The initial factor is 2162^{16}.
  • When inf/NaN appears, that update is skipped and the factor is multiplied by 0.5.
  • After 2,000 consecutive steps without inf/NaN, the factor is doubled.

FP32 accumulation treats operations differently depending on their type. For matrix multiplications (dot products), FP16 products are summed in FP32, and large reductions such as batch normalization statistics and softmax are computed in FP32. Element-wise operations (such as activation functions) are bound by memory transfer speed, so they can be computed in either FP16 or FP32.

Experimental results

In all experiments, the paper used the same hyperparameters as FP32 training and compared against mixed precision training (using Tensor Cores, which accumulate FP16 products in FP32).

TaskModelMetricFP32Mixed precision
ImageNet image classificationAlexNetTop-1 accuracy56.77%56.93%
ImageNet image classificationVGG-DTop-1 accuracy65.40%65.43%
ImageNet image classificationGoogLeNetTop-1 accuracy68.33%68.43%
ImageNet image classificationInception v3Top-1 accuracy73.85%74.13%
ImageNet image classificationResNet-50Top-1 accuracy75.92%76.04%
Object detection (Pascal VOC 2007)Faster R-CNNmAP69.1%69.7%
Object detection (Pascal VOC 2007)SSDmAP76.9%77.1%
Speech recognition (English, WSJ '92)Deep Speech 2Character error rate (lower is better)2.201.99
Speech recognition (Mandarin)Deep Speech 2Character error rate (lower is better)15.8215.01
  • Image classification: all six models reached about the same accuracy as FP32. Loss scaling was not needed for these models.
  • Object detection: without loss scaling, Faster R-CNN dropped to 68.6% and SSD diverged. The values in the table are with loss scaling.
  • Language modeling: without loss scaling, bigLSTM (an LSTM language model) began to diverge from FP32 at around 300,000 iterations; with a factor of 128 it matched FP32 perplexity.
  • Memory: the master weights increase weight memory by 50%, but the paper states that because activations, which account for most of training memory, become FP16, overall memory is roughly halved.

Results comparable to FP32 were also reported for translation (an LSTM model with attention) and image generation with DCGAN.

Practical considerations

When training in FP16, always combine it with loss scaling. Some models, such as image classifiers, do not need it, but others, such as SSD, diverge without it. In PyTorch, GradScaler automatically adjusts the factor and skips steps that overflow.

  • Unscale before any processing that uses the gradients. When using gradient clipping, call scaler.unscale_(optimizer) first. Clipping without it compares the norm of the SS-scaled gradients against the threshold.
  • Updates may be skipped early in training. GradScaler starts with a large factor and lowers it, so the first few steps have their updates skipped due to inf/NaN. According to the PyTorch documentation, afterward this happens only about once every few hundred to few thousand iterations.
  • BF16 does not need loss scaling. BF16 (bfloat16) has the same 8-bit exponent as FP32, so its representable range is almost the same as FP32's. In exchange, its mantissa has 7 bits, making it coarser than FP16. Kalamkar et al. (2019) reported that BF16 mixed precision training achieved the same results as FP32 without changing hyperparameters. Whether it is available depends on the GPU.
  • Some operations should stay in FP32. Large reductions, softmax, Layer Normalization, and the like are prone to error or overflow in FP16. PyTorch's autocast automatically runs such operations (softmax, layer_norm, sum, etc.) in FP32.
  • Whether it gets faster depends on the GPU. Speedups come when using GPUs that can compute FP16/BF16 quickly (such as those with Tensor Cores). The memory savings apply on any GPU.

Comparison with other methods

Mixed precision training is one of the methods for reducing the memory used in training. It differs from other distributed training methods in what it reduces and what it costs, and they can be combined.

MethodWhat it reducesWhat it costsCombination
Mixed precision trainingBit width of weights, activations, and gradients (32 → 16)Memory for the master weights, the effort of loss scalingCombined with almost every method
Gradient checkpointingActivations saved for the backward passComputation to redo the forward passOften used together for large models
ZeRO / FSDPWeights, gradients, and optimizer states duplicated on each GPUCommunication between GPUsDesigned with mixed precision training in mind
Pipeline parallelism / Tensor parallelismLayers or matrices held by one GPUCommunication and GPU idle timeUsually used together with mixed precision training
  • Try mixed precision training first. It requires few code changes and helps both memory and speed.
  • If memory is still insufficient, add gradient checkpointing when activations dominate, or ZeRO/FSDP when weights or optimizer states dominate.
  • On GPUs that support BF16, choosing BF16, which needs no loss scaling, saves effort.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision import datasets, transforms

"""
Image classification task on MNIST data (automatic mixed precision)
torch.autocast casts to FP16 per operation, and GradScaler performs loss scaling
"""

# Hyperparameters
batch_size = 64       # batch size
epochs = 5            # number of epochs
learning_rate = 1e-3  # learning rate
max_norm = 1.0        # gradient clipping threshold

device = torch.device('cuda')  # FP16 automatic mixed precision is used on the GPU

transform = transforms.Compose([
  transforms.ToTensor(),
  transforms.Normalize((0.1307,), (0.3081,))
])
train_dataset = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)

# Create the model weights in FP32 (they serve as the master weights)
model = nn.Sequential(
  nn.Flatten(),
  nn.Linear(28 * 28, 256), nn.ReLU(),
  nn.Linear(256, 10)
).to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)

# Loss scaling. Defaults: init_scale=2**16, growth_factor=2.0, backoff_factor=0.5, growth_interval=2000
scaler = torch.amp.GradScaler('cuda')

for epoch in range(epochs):
  model.train()
  for images, labels in train_loader:
    images, labels = images.to(device), labels.to(device)
    optimizer.zero_grad()

    # Run only the forward pass and loss inside autocast (matmuls become FP16; softmax and the like become FP32)
    with torch.autocast(device_type='cuda', dtype=torch.float16):
      outputs = model(images)
      loss = criterion(outputs, labels)

    # Multiply the loss by S, then back-propagate (call backward outside autocast)
    scaler.scale(loss).backward()

    # Before gradient clipping, divide the gradients by S to restore their original scale
    scaler.unscale_(optimizer)
    torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm)

    # Skip the update if the gradients contain inf/NaN; otherwise call optimizer.step()
    scaler.step(optimizer)
    # Set the scale for the next step (×0.5 on inf/NaN, ×2 after 2000 consecutive steps without them)
    scaler.update()
  print(f"epoch {epoch + 1}: loss {loss.item():.4f}, scale {scaler.get_scale():.0f}")

# Inference can also run inside autocast (no gradients, so GradScaler is not needed)
model.eval()
with torch.no_grad(), torch.autocast(device_type='cuda', dtype=torch.float16):
  images, labels = next(iter(train_loader))
  preds = model(images.to(device)).argmax(dim=1)

# With BF16: set dtype=torch.bfloat16 and do not use GradScaler
# with torch.autocast(device_type='cuda', dtype=torch.bfloat16):
#   loss = criterion(model(images), labels)
# loss.backward(); optimizer.step()

FAQ

Q. Can mixed precision training be less accurate than FP32?
A.

In the original paper, accuracy was about the same as FP32 across image classification, object detection, speech recognition, translation, language modeling, and image generation. However, that is when all three techniques are used: FP32 master weights, loss scaling, and FP32 accumulation. For example, SSD diverged without loss scaling.

Q. How should the loss scaling factor $S$ be chosen?
A.

With PyTorch's GradScaler, it is chosen automatically. It starts at 2162^{16}, halves when the gradients contain inf/NaN, and doubles after 2,000 consecutive steps without them. If fixing it, choose a fairly large value such that the maximum gradient multiplied by it does not exceed FP16's maximum of 65,504. The original paper used values in the range of 8 to 32K.

Q. Should I use FP16 or BF16?
A.

If the GPU supports BF16, BF16 is the easier choice. Its exponent has the same 8 bits as FP32, so its range is wide and loss scaling is unnecessary. In exchange, its mantissa has only 7 bits, fewer than FP16's 10, so values are coarser. On GPUs that do not support BF16, use FP16 with loss scaling.

References

  1. Micikevicius, P., Narang, S., Alben, J., Diamos, G., Elsen, E., Garcia, D., Ginsburg, B., Houston, M., Kuchaiev, O., Venkatesh, G., & Wu, H. (2018). Mixed Precision Training. ICLR 2018.
  2. Kalamkar, D., Mudigere, D., Mellempudi, N., et al. (2019). A Study of BFLOAT16 for Deep Learning Training. arXiv:1905.12322.
  3. PyTorch Documentation, "Automatic Mixed Precision package - torch.amp."
  4. PyTorch Documentation, "Automatic Mixed Precision examples."