Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch Mixed Precision Training (AMP)

PyTorch Mixed Precision Training (AMP)

Mixed precision training is one of the most important performance optimization techniques in deep learning. By using both FP32 (single precision) and FP16 (half precision) floating-point numbers for computation, it can significantly speed up training and reduce memory usage with almost no loss of model accuracy. This section introduces Automatic Mixed Precision (AMP) in PyTorch in detail.

Applicable versions:The code in this article is based on the PyTorch 1.6+ torch.cuda.amp API. PyTorch 2.4+ recommends using torch.amp.autocast and torch.amp.GradScaler, with basically the same usage; differences will be noted in the text.


1. Fundamentals of Mixed Precision Training

1.1 Why Mixed Precision Is Needed

Training deep learning models involves a large number of matrix operations. Traditional FP32 (32-bit floating point) computation has high precision but uses a lot of memory and is slow. FP16 (16-bit floating point) computation is fast and uses little memory, but has a smaller numeric range and is prone to gradient underflow.

The core idea of mixed precision training is: use FP32 for operations that require high precision and FP16 for operations that do not. This way you can enjoy the speed advantage of FP16 while avoiding precision issues.

The figure below shows the differences in bit layout among the three floating-point formats --Exponent bitsdetermine the numeric range,Mantissa bitsdetermine the precision:

Comparison of Bit Layouts of Floating-Point Formats Sign bit Exponent bits Mantissa bits FP32 32 bits S 1 Exponent 8 bits Mantissa 23 bits Range: +/-3.4 x 10^38 Precision: ~7 significant digits FP16 16 bits S Exp 5 bits Mantissa 10 bits Range: +/-65504 Precision: ~3.3 significant digits Warning: Few exponent bits, prone to overflow BF16 16 bits S Exponent 8 bits (same as FP32) Mantissa 7 bits Range: +/-3.4 x 10^38 Precision: ~2.4 significant digits OK: Same range as FP32 BF16 keeps the exponent bits of FP32 -> the same numeric range -> more stable training, usually without the need for GradScaler

1.2 Advantages of Mixed Precision

Pointer Improvement Description
Training Speed 2-3x speedup Depends on GPU Tensor Core support
Memory usage Reduced by about 50% Activations and intermediate results stored in FP16
Memory bandwidth Reduced by about 50% Smaller data size means less data transfer
Communication overhead Reduced by about 50% Gradient transfer volume halved in distributed training

1.3 How Tensor Core Acceleration Works

NVIDIA's Tensor Core is a hardware unit specialized for matrix operations. It can complete a 4x4 matrix multiply-accumulate operation (D = A x B + C) in a single clock cycle, which is the main source of FP16 training acceleration. Compared with ordinary CUDA cores that need multiple instructions to complete the same operation, Tensor Core compresses it into a single instruction.

GPUs that support Tensor Core include:

Consumer-grade RTX GPUs also support Tensor Core; models such as the RTX 3060 and above can all benefit from AMP acceleration.


2. Basic Usage of PyTorch AMP

2.1 autocast and GradScaler

PyTorch's AMP API mainly includes two core components:

The figure below shows the data flow of a complete training step with AMP:

AMP Single-Step Training Flow Input data FP32 autocast Forward propagation Automatically select FP16/FP32 Compute loss FP32 GradScaler Scale + backpropagation loss × scale_factor Unscale gradients + gradient clipping grad / scale_factor Optimizer update FP32 weights update Scaler Adjust scale autocast control -- automatic precision selection GradScaler control -- prevents gradient underflow FP32 weight update -- maintains precision Key point: weights are always stored and updated in FP32 and are only temporarily converted to FP16 during computation

2.2 Basic Usage Example

Example

import

torch

import

torch.

nn

as

nn

import

torch.

optim

as

optim

from

torch.

cuda

.

amp

import

autocast

,

GradScaler

Recommended style for PyTorch 2.4+:

from torch.amp import autocast, GradScaler

Check whether CUDA is available

device

=

torch.

device

(

"cuda"

if

torch.

cuda

.

is_available

(

)

else

"cpu"

)

print

(

f

"Using device: {device}"

)

if

torch.

cuda

.

is_available

(

)

:

   

print

(

f

"GPU: {torch.cuda.get_device_name(0)}"

)

   

print

(

f

"BF16 supported: {torch.cuda.is_bf16_supported()}"

)

---- Model Definition -------------------------------------

class

SimpleModel

(

nn.

Module

)

:

   

def

init

(

self

)

:

       

super

(

)

.

init

(

)

       

self

.

net

=

nn.

Sequential

(

            nn.

Linear

(

128

,

256

)

,

            nn.

ReLU

(

)

,

            nn.

Linear

(

256

,

256

)

,

            nn.

ReLU

(

)

,

            nn.

Linear

(

256

,

10

)

       

)

   

def

forward

(

self

,

x

)

:

       

return

self

.

net

(

x

)

model

=

SimpleModel

(

)

.

to

(

device

)

Loss function and optimizer

criterion

=

nn.

CrossEntropyLoss

(

)

optimizer

=

optim.

Adam

(

model.

parameters

(

)

,

lr

=

1e-3

)

---- Key Components of Mixed Precision Training ----------------------

GradScaler: scales the loss to avoid FP16 gradient underflow

scaler

=

GradScaler

(

)

Training loop

def

train_epoch_amp

(

model

,

loader

,

criterion

,

optimizer

,

scaler

,

device

)

:

    model.

train

(

)

    total_loss

=

0

    correct

=

0

    total

=

0

   

for

inputs

,

labels

in

loader:

        inputs

=

inputs.

to

(

device

,

non_blocking

=

True

)

        labels

=

labels.

to

(

device

,

non_blocking

=

True

)

        optimizer.

zero_grad

(

)

       

---- Core: using the autocast context manager ---------------

       

Operations inside the autocast region automatically use FP16

       

Precision-sensitive operations (such as softmax and loss) automatically fall back to FP32

       

with

autocast

(

device_type

=

'cuda'

)

:

            outputs

=

model

(

inputs

)

            loss

=

criterion

(

outputs

,

labels

)

       

---- Backpropagation with scaler -------------------

       

1. Scale the loss (multiply by scale_factor)

       

2. Backpropagation (computed on the amplified gradients)

       

3. scaler.step internally unscales the gradients and checks for Inf/NaN

        scaler.

scale

(

loss

)

.

backward

(

)

       

Update parameters

        scaler.

step

(

optimizer

)

       

Update the scaler's scaling factor

        scaler.

update

(

)

       

Statistics

        total_loss +

=

loss.

item

(

)

size

(

0

)

        _

,

predicted

=

outputs.

max

(

1

)

        correct +

=

predicted.

eq

(

labels

)

.

sum

(

)

.

item

(

)

        total +

=

labels.

size

(

0

)

   

return

total_loss / total

,

correct / total

Simulated data

train_loader

=

[

   

(

torch.

randn

(

32

,

128

)

,

torch.

randint

(

0

,

10

,

(

32

,

)

)

)

for

_

in

range

(

10

)

]

Start training

for

epoch

in

range

(

3

)

:

    loss

,

acc

=

train_epoch_amp

(

        model

,

train_loader

,

criterion

,

optimizer

,

scaler

,

device

   

)

   

print

(

f

"Epoch {epoch+1}: Loss={loss:.4f}, Acc={acc:.4f}"

)

print

(

"Mixed precision training complete!"

)

API migration tip:PyTorch 2.4 marks torch.cuda.amp.autocast as deprecated and recommends using torch.amp.autocast('cuda'). The two are used in exactly the same way; only the import path differs.

2.3 Choosing Between BF16 and FP16

Modern GPUs support two half-precision formats; their core difference lies in the allocation strategy of exponent and mantissa bits:

Format Exponent bits Mantissa bits Numeric range Precision Applicable scenarios
FP16 5 bits 10 bits ±65504 Higher (~3.3 bits) Needs compatibility with older GPUs (V100/RTX 20 series)
BF16 8 bits 7 bits ±3.4×10³⁸ Lower (~2.4 bits) Pursues stability (A100/RTX 30 series and above)

Selection advice: if the hardware supports BF16, prefer BF16. Its numeric range is exactly the same as FP32, so overflow problems almost never occur during training, and no GradScaler is needed.

Example

---- BF16 Style (PyTorch 1.10+) ----------------------------

BF16 does not need GradScaler because its numeric range is the same as FP32

from

torch.

cuda

.

amp

import

autocast

Method 1: specify dtype in autocast

with

autocast

(

device_type

=

'cuda'

,

dtype

=

torch.

bfloat16

)

:

    outputs

=

model

(

inputs

)

    loss

=

criterion

(

outputs

,

labels

)

Method 2: enable BF16 globally by default (if the hardware supports it)

torch.backends.cuda.matmul.allow_bf16_reduced_precision = True

torch.backends.cudnn.allow_bf16_reduced_precision = True

---- Check Hardware Support --------------------------------

print

(

f

"Hardware supports BF16: {torch.cuda.is_bf16_supported()}"

)

print

(

f

"Current matmul allows BF16: {torch.backends.cuda.matmul.allow_bf16}"

)

print

(

f

"Current cuDNN allows BF16: {torch.backends.cudnn.allow_bf16}"

)

---- Complete BF16 Training Example (no GradScaler needed) ----------

scaler_bf16

=

None

 

BF16 does not need a scaler

for

inputs

,

labels

in

train_loader:

    inputs

,

labels

=

inputs.

to

(

device

)

,

labels.

to

(

device

)

    optimizer.

zero_grad

(

)

   

with

autocast

(

device_type

=

'cuda'

,

dtype

=

torch.

bfloat16

)

:

        outputs

=

model

(

inputs

)

        loss

=

criterion

(

outputs

,

labels

)

   

Direct backpropagation, no scaler needed

    loss.

backward

(

)

    optimizer.

step

(

)


3. Advanced Techniques and Optimizations

3.1 Dynamic Loss Scaling

The core mechanism of GradScaler isdynamic loss scaling--- it automatically adjusts the scaling factor according to the training state, preventing gradient underflow while gradually reducing the scale when training is stable to minimize precision loss:

Dynamic Loss Scaling Scale × Loss Backpropagation Gradients contain Inf / NaN? Is Reduce scale × backoff (default 0.5) Skip this update No Unscale + update parameters Consecutive successes +1 Consecutive successes >= growth_interval? (default 2000 steps) Increase scale x growth growth_factor default 2.0 - backoff_factor default 0.5 - dynamically balances precision and stability

GradScaler automatically manages the feedback loop above; you only need to fine-tune its behavior through parameters:

Example

from

torch.

cuda

.

amp

import

GradScaler

Custom GradScaler Parameters

scaler

=

GradScaler

(

    init_scale

=

2

**

16

,

       

Initial scaling factor, default 65536

    growth_factor

=

2.0

,

     

Scaling factor growth multiplier, default 2.0

    backoff_factor

=

0.5

,

     

Scaling factor backoff multiplier, default 0.5

    growth_interval

=

2000

,

   

Number of consecutive successful steps before growth

    enabled

=

True

           

Whether to enable (can be toggled dynamically)

)

Workflow:

1. Initial scale = 65536

2. If a step produces Inf/NaN -> scale x 0.5 (reduced) and skip that step

3. If 2000 consecutive steps have no Inf/NaN -> scale x 2.0 (increased)

4. Always seek the largest usable scale within a safe range

Check the current scaling factor

print

(

f

"Current scaling factor: {scaler.get_scale()}"

)

Check whether the scaler considers the previous step successful

print

(

f

"Recently successful: {scaler._found_inf.item() == 0}"

)

3.2 AMP in Gradient Accumulation

Gradient accumulation is used to simulate a larger batch size with limited memory. When using AMP, note that the loss of each sub-batch must be divided by the number of accumulation steps, otherwise the final gradients will be amplified:

Example

---- Gradient Accumulation + Mixed Precision ------------------------

accumulation_steps

=

8

scaler

=

GradScaler

(

)

model.

train

(

)

for

batch_idx

,

(

inputs

,

labels

)

in

enumerate

(

train_loader

)

:

    inputs

,

labels

=

inputs.

to

(

device

)

,

labels.

to

(

device

)

   

with

autocast

(

device_type

=

'cuda'

)

:

        outputs

=

model

(

inputs

)

       

Key point: divide each sub-batch's loss by the number of accumulation steps

       

This way the accumulated gradients are equivalent to the average gradients of a large batch

        loss

=

criterion

(

outputs

,

labels

)

/ accumulation_steps

   

Accumulate the scaled gradients (note: do not zero them here)

    scaler.

scale

(

loss

)

.

backward

(

)

   

Update parameters once every accumulation_steps batches

   

if

(

batch_idx +

1

)

% accumulation_steps

==

0

:

        scaler.

step

(

optimizer

)

        scaler.

update

(

)

        optimizer.

zero_grad

(

)

---- Handling Gradients at the End When a Full Accumulation Cycle Is Not Complete ----------

remainder

=

len

(

train_loader

)

% accumulation_steps

if

remainder

!=

0

:

   

The accumulated gradients need to be rescaled by the actual number of steps

   

Simple approach: still perform the step; the gradients will be somewhat larger but the impact is usually small

    scaler.

step

(

optimizer

)

    scaler.

update

(

)

    optimizer.

zero_grad

(

)

3.3 AMP in Validation and Inference

AMP is also recommended during validation and inference. Since backpropagation and gradient scaling are not needed, the code is simpler:

Example

---- Using autocast During Inference -------------------------------

@

torch.

no_grad

(

)

def

inference_amp

(

model

,

inputs

,

device

)

:

    model.

eval

(

)

   

Inference uses FP16, no GradScaler needed

   

with

autocast

(

device_type

=

'cuda'

)

:

        outputs

=

model

(

inputs.

to

(

device

)

)

   

return

outputs

---- inference_mode is Faster than no_grad -------------------------

inference_mode disables more tracking overhead, suitable for pure inference

@

torch.

inference_mode

(

)

def

inference_fast

(

model

,

inputs

,

device

)

:

    model.

eval

(

)

   

with

autocast

(

device_type

=

'cuda'

)

:

        outputs

=

model

(

inputs.

to

(

device

)

)

   

return

outputs

---- Batch Inference Example ---------------------------------------

def

batch_inference

(

model

,

dataloader

,

device

)

:

    model.

eval

(

)

    all_outputs

=

[

]

   

with

torch.

inference_mode

(

)

:

       

for

inputs

in

dataloader:

           

with

autocast

(

device_type

=

'cuda'

)

:

                outputs

=

model

(

inputs.

to

(

device

)

)

            all_outputs.

append

(

outputs.

cpu

(

)

)

   

return

torch.

cat

(

all_outputs

,

dim

=

0

)


4. Common Problems and Solutions

4.1 Unstable Training

Problem Reason Solution
Loss becomes NaN / Inf Gradient overflow (scale too large or learning rate too high) Reduce the init_scale, add gradient clipping, and lower the learning rate
Loss does not decrease / oscillates Gradient underflow (scale too small, gradients truncated to 0) Increase the init_scale, check gradient statistics, and try BF16
Significant precision drop Some layers (such as LayerNorm and Softmax) are sensitive to FP16 Keep these layers in FP32 manually (see 4.2)
Unstable in the later stages of training Changes in the value range of model parameters cause a scale mismatch Increase the growth_intervalappropriately to make scale adjustment more conservative

4.2 Manually Controlling Precision

Some operations suffer significant precision loss under FP16 and need to be manually designated to use FP32. PyTorch's autocast already has built-in protection for these operations, but custom operations may need manual handling:

Example

---- Method 1: Wrap a Loss Function Forced to FP32 ------------------

class

FP32Loss

(

nn.

Module

)

:

   

"""A wrapper for a loss function that is forced to compute in FP32"""

   

def

init

(

self

,

base_criterion

)

:

       

super

(

)

.

init

(

)

       

self

.

base_criterion

=

base_criterion

   

def

forward

(

self

,

input

,

target

)

:

       

Explicitly convert to FP32 to escape the influence of autocast

       

return

self

.

base_criterion

(

input

.

float

(

)

,

target.

float

(

)

)

---- Method 2: Locally Disable autocast ----------------------------

with

autocast

(

device_type

=

'cuda'

)

:

    outputs

=

model

(

inputs

)

   

Temporarily disable autocast for precision-sensitive operations

   

with

autocast

(

enabled

=

False

)

:

        loss

=

criterion

(

outputs.

float

(

)

,

labels

)

---- Method 3: Keep Specific Layers in FP32 ------------------------

class

CustomModel

(

nn.

Module

)

:

   

def

init

(

self

)

:

       

super

(

)

.

init

(

)

       

self

.

features

=

nn.

Sequential

(

            nn.

Conv2d

(

3

,

64

,

3

,

padding

=

1

)

,

            nn.

BatchNorm2d

(

64

)

,

 

BN is sensitive to precision

            nn.

ReLU

(

)

,

            nn.

Conv2d

(

64

,

128

,

3

,

padding

=

1

)

,

            nn.

BatchNorm2d

(

128

)

,

            nn.

ReLU

(

)

,

       

)

       

self

.

classifier

=

nn.

Linear

(

128

,

10

)

   

def

forward

(

self

,

x

)

:

        x

=

self

.

features

[

0

]

(

x

)

         

Conv: FP16 (controlled by autocast)

        x

=

self

.

features

[

1

]

(

x.

float

(

)

)

 

BN: forced to FP32

        x

=

self

.

features

[

2

]

(

x

)

         

ReLU: FP16

        x

=

self

.

features

[

3

]

(

x

)

        x

=

self

.

features

[

4

]

(

x.

float

(

)

)

 

BN: forced to FP32

        x

=

self

.

features

[

5

]

(

x

)

        x

=

x.

mean

(

dim

=

[

2

,

3

]

)

           

Global Average Pooling

        x

=

self

.

classifier

(

x

)

       

return

x

Tip:PyTorch's autocast automatically keeps the following operations in FP32: softmax, log_softmax, cross_entropy, layer_norm, batch_norm, etc. Usually only custom operators need manual handling.

4.3 Gradient Clipping with AMP

Gradient clipping must be performed after scaler.step() and before scaler.unscale_() . This is because clipping needs to act on thereal gradient valuesrather than the scaled gradients:

Example

---- Correct Order of Gradient Clipping ----------------------------

for

inputs

,

labels

in

train_loader:

    inputs

,

labels

=

inputs.

to

(

device

)

,

labels.

to

(

device

)

    optimizer.

zero_grad

(

)

   

with

autocast

(

device_type

=

'cuda'

)

:

        outputs

=

model

(

inputs

)

        loss

=

criterion

(

outputs

,

labels

)

   

Step 1: Scale the loss and backpropagate

    scaler.

scale

(

loss

)

.

backward

(

)

   

Step 2: Unscale the gradients (restore them from the scaled value to the real value)

   

        must be called before clipping and step

    scaler.

unscale_

(

optimizer

)

   

Step 3: Clip the real gradients

    torch.

nn

.

utils

.

clip_grad_norm_

(

model.

parameters

(

)

,

max_norm

=

1.0

)

   

Step 4: Update parameters (internally checks whether gradients contain Inf/NaN)

    scaler.

step

(

optimizer

)

   

Step 5: Update the scaling factor

    scaler.

update

(

)

---- Common Mistake: Clipping Without unscale_ First ----------------

Wrong! What is clipped is the amplified gradient, and the threshold will be disturbed by the scale

scaler.scale(loss).backward()

torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0) # <- wrong

scaler.step(optimizer)


5. Performance Comparison and Best Practices

5.1 Performance Benchmarking

Example

import

time

def

benchmark_training

(

model

,

train_loader

,

device

,

use_amp

=

True

,

                       dtype

=

torch.

float16

,

num_iterations

=

100

)

:

   

"""Compare the training speed of FP32 and AMP"""

    model

=

model.

to

(

device

)

    criterion

=

nn.

CrossEntropyLoss

(

)

    optimizer

=

optim.

Adam

(

model.

parameters

(

)

,

lr

=

1e-3

)

    scaler

=

GradScaler

(

enabled

=

use_amp

and

dtype

==

torch.

float16

)

   

---- Warm-up (first 10 steps not timed) -----------------------

   

for

i

,

(

inputs

,

labels

)

in

enumerate

(

train_loader

)

:

       

if

i

=

10

:

           

break

        inputs

,

labels

=

inputs.

to

(

device

)

,

labels.

to

(

device

)

        optimizer.

zero_grad

(

)

       

if

use_amp:

           

with

autocast

(

device_type

=

'cuda'

,

dtype

=

dtype

)

:

                outputs

=

model

(

inputs

)

                loss

=

criterion

(

outputs

,

labels

)

            scaler.

scale

(

loss

)

.

backward

(

)

            scaler.

step

(

optimizer

)

            scaler.

update

(

)

       

else

:

            outputs

=

model

(

inputs

)

            loss

=

criterion

(

outputs

,

labels

)

            loss.

backward

(

)

            optimizer.

step

(

)

   

---- Formal Test ----------------------------------------------

    torch.

cuda

.

synchronize

(

)

    start

=

time

.

time

(

)

   

for

i

,

(

inputs

,

labels

)

in

enumerate

(

train_loader

)

:

       

if

i

=

num_iterations:

           

break

        inputs

,

labels

=

inputs.

to

(

device

)

,

labels.

to

(

device

)

        optimizer.

zero_grad

(

)

       

if

use_amp:

           

with

autocast

(

device_type

=

'cuda'

,

dtype

=

dtype

)

:

                outputs

=

model

(

inputs

)

                loss

=

criterion

(

outputs

,

labels

)

            scaler.

scale

(

loss

)

.

backward

(

)

            scaler.

step

(

optimizer

)

            scaler.

update

(

)

       

else

:

            outputs

=

model

(

inputs

)

            loss

=

criterion

(

outputs

,

labels

)

            loss.

backward

(

)

            optimizer.

step

(

)

    torch.

cuda

.

synchronize

(

)

    elapsed

=

time

.

time

(

)

   

return

elapsed / num_iterations

---- Run the Comparison -------------------------------------------

model

=

SimpleModel

(

)

fp32_time

=

benchmark_training

(

model

,

train_loader

,

device

,

use_amp

=

False

)

fp16_time

=

benchmark_training

(

model

,

train_loader

,

device

,

use_amp

=

True

,

dtype

=

torch.

float16

)

print

(

f

"FP32 average time: {fp32_time*1000:.2f} ms/batch"

)

print

(

f

"FP16 average time: {fp16_time*1000:.2f} ms/batch"

)

print

(

f

"Speedup: {fp32_time / fp16_time:.2f}x"

)

If BF16 is supported, test that too

if

torch.

cuda

.

is_bf16_supported

(

)

:

    bf16_time

=

benchmark_training

(

        model

,

train_loader

,

device

,

use_amp

=

True

,

dtype

=

torch.

bfloat16

   

)

   

print

(

f

"BF16 average time: {bf16_time*1000:.2f} ms/batch"

)

   

print

(

f

"BF16 speedup: {fp32_time / bf16_time:.2f}x"

)

5.2 Memory Usage Comparison

Example

def

compare_memory

(

model_class

,

train_loader

,

device

)

:

   

"""Compare the memory usage of FP32 and AMP"""

   

def

reset

(

)

:

        torch.

cuda

.

empty_cache

(

)

        torch.

cuda

.

reset_peak_memory_stats

(

)

   

---- FP32 Memory Test ---------------------------------------

    reset

(

)

    model_fp32

=

model_class

(

)

.

to

(

device

)

    optimizer_fp32

=

optim.

Adam

(

model_fp32.

parameters

(

)

)

   

for

inputs

,

labels

in

list

(

train_loader

)

[

:

5

]

:

        inputs

,

labels

=

inputs.

to

(

device

)

,

labels.

to

(

device

)

        optimizer_fp32.

zero_grad

(

)

        outputs

=

model_fp32

(

inputs

)

        loss

=

nn.

CrossEntropyLoss

(

)

(

outputs

,

labels

)

        loss.

backward

(

)

        optimizer_fp32.

step

(

)

    fp32_peak

=

torch.

cuda

.

max_memory_allocated

(

)

/

1024

**

2

   

---- AMP Memory Test ----------------------------------------

    reset

(

)

    model_amp

=

model_class

(

)

.

to

(

device

)

    optimizer_amp

=

optim.

Adam

(

model_amp.

parameters

(

)

)

    scaler

=

GradScaler

(

)

   

for

inputs

,

labels

in

list

(

train_loader

)

[

:

5

]

:

        inputs

,

labels

=

inputs.

to

(

device

)

,

labels.

to

(

device

)

        optimizer_amp.

zero_grad

(

)

       

with

autocast

(

device_type

=

'cuda'

)

:

            outputs

=

model_amp

(

inputs

)

            loss

=

nn.

CrossEntropyLoss

(

)

(

outputs

,

labels

)

        scaler.

scale

(

loss

)

.

backward

(

)

        scaler.

step

(

optimizer_amp

)

        scaler.

update

(

)

    amp_peak

=

torch.

cuda

.

max_memory_allocated

(

)

/

1024

**

2

   

print

(

f

"FP32 peak memory: {fp32_peak:.1f} MB"

)

   

print

(

f

"AMP peak memory: {amp_peak:.1f} MB"

)

   

print

(

f

"Memory saved: {(fp32_peak - amp_peak) / fp32_peak * 100:.1f}%"

)

compare_memory

(

SimpleModel

,

train_loader

,

device

)

5.3 Summary of Best Practices

Scenario Recommended configuration Reason
A100 / H100 / RTX 40 series BF16, no GradScaler needed Same numeric range as FP32, most stable
V100 / RTX 20 series FP16 + GradScaler Hardware does not support BF16, a scaler is needed to prevent overflow
RTX 30 series BF16 first, FP16 as an alternative The Ampere architecture supports BF16
Large model training (tight memory) AMP + gradient accumulation + gradient checkpointing Combining all three maximizes memory utilization
Inference deployment autocast + inference_mode No scaler needed, fastest inference

PyTorch 2.0+ has integrated AMP into torch.compile , which can automatically apply mixed precision optimization. When using torch.compile(model) , the compiler automatically determines which operations are suitable for FP16.


6. Combination with Other Optimization Techniques

6.1 AMP + torch.compile

Example

---- Combined Use with PyTorch 2.0+ -------------------------------

model

=

model.

to

(

device

)

Method 1: compile first, then train with AMP

torch.compile automatically fuses operators and optimizes memory access

model_compiled

=

torch.

compile

(

model

,

mode

=

"reduce-overhead"

)

scaler

=

GradScaler

(

)

for

inputs

,

labels

in

train_loader:

    inputs

,

labels

=

inputs.

to

(

device

)

,

labels.

to

(

device

)

    optimizer.

zero_grad

(

)

   

with

autocast

(

device_type

=

'cuda'

)

:

        outputs

=

model_compiled

(

inputs

)

        loss

=

criterion

(

outputs

,

labels

)

    scaler.

scale

(

loss

)

.

backward

(

)

    scaler.

step

(

optimizer

)

    scaler.

update

(

)

Method 2: enable TF32 (extra acceleration for Ampere+ architectures)

TF32 uses 19-bit precision, with speed close to FP16 and precision close to FP32

torch.

backends

.

cuda

.

matmul

.

allow_tf32

=

True

torch.

backends

.

cudnn

.

allow_tf32

=

True

torch.

backends

.

cudnn

.

benchmark

=

True

 

Accelerates convolution with fixed input sizes

6.2 AMP + Distributed Training

Example

---- Distributed Training + Mixed Precision --------------------------

import

torch.

distributed

as

dist

from

torch.

nn

.

parallel

import

DistributedDataParallel

as

DDP

def

setup

(

rank

,

world_size

)

:

    dist.

init_process_group

(

"nccl"

,

rank

=

rank

,

world_size

=

world_size

)

    torch.

cuda

.

set_device

(

rank

)

def

train_ddp_amp

(

rank

,

world_size

)

:

    setup

(

rank

,

world_size

)

    device

=

torch.

device

(

f

"cuda:{rank}"

)

    model

=

SimpleModel

(

)

.

to

(

device

)

    model

=

DDP

(

model

,

device_ids

=

[

rank

]

)

    optimizer

=

optim.

Adam

(

model.

parameters

(

)

,

lr

=

1e-3

)

    scaler

=

GradScaler

(

)

   

for

inputs

,

labels

in

train_loader:

        inputs

=

inputs.

to

(

device

,

non_blocking

=

True

)

        labels

=

labels.

to

(

device

,

non_blocking

=

True

)

        optimizer.

zero_grad

(

)

       

with

autocast

(

device_type

=

'cuda'

)

:

            outputs

=

model

(

inputs

)

            loss

=

criterion

(

outputs

,

labels

)

       

DDP automatically synchronizes gradients during backward

        scaler.

scale

(

loss

)

.

backward

(

)

       

Gradient clipping (unscale first)

        scaler.

unscale_

(

optimizer

)

        torch.

nn

.

utils

.

clip_grad_norm_

(

model.

parameters

(

)

,

max_norm

=

1.0

)

        scaler.

step

(

optimizer

)

        scaler.

update

(

)

    dist.

destroy_process_group

(

)


Summary

Mixed precision training is thestandard practice in deep learning training today.

Key points: