Shortcuts

N-Bit Precision (Intermediate)

Audience: Users looking to scale larger models or take advantage of optimized accelerators.


What is Mixed Precision?

PyTorch, like most deep learning frameworks, trains on 32-bit floating-point (FP32) arithmetic by default. However, many deep learning models do not require this to reach complete accuracy. By conducting operations in half-precision format while keeping minimum information in single-precision to maintain as much information as possible in crucial areas of the network, mixed precision training delivers significant computational speedup. Switching to mixed precision has resulted in considerable training speedups since the introduction of Tensor Cores in the Volta and Turing architectures. It combines FP32 and lower-bit floating-points (such as FP16) to reduce memory footprint and increase performance during model training and evaluation. It accomplishes this by recognizing the steps that require complete accuracy and employing a 32-bit floating-point for those steps only, while using a 16-bit floating-point for the rest. When compared to complete precision training, mixed precision training delivers all of these benefits while ensuring that no task-specific accuracy is lost. [2].

Note

In some cases, it is essential to remain in FP32 for numerical stability, so keep this in mind when using mixed precision. For example, when running scatter operations during the forward (such as torchpoint3d), computation must remain in FP32.

Warning

Do not cast anything to other dtypes manually using torch.autocast or tensor.half() when using native precision because this can bring instability.

class LitModel(LightningModule):
    def training_step(self, batch, batch_idx):
        outs = self(batch)

        a_float32 = torch.rand((8, 8), device=self.device, dtype=self.dtype)
        b_float32 = torch.rand((8, 4), device=self.device, dtype=self.dtype)

        # casting to float16 manually
        with torch.autocast(device_type=self.device.type):
            c_float16 = torch.mm(a_float32, b_float32)
            target = self.layer(c_float16.flatten()[None])

        # here outs is of type float32 and target is of type float16
        loss = torch.mm(target @ outs).float()
        return loss


trainer = Trainer(accelerator="gpu", devices=1, precision=32)

FP16 Mixed Precision

In most cases, mixed precision uses FP16. Supported PyTorch operations automatically run in FP16, saving memory and improving throughput on the supported accelerators.

Note

When using TPUs, setting precision=16 will enable bfloat16, the only supported half precision type on TPUs.

Trainer(accelerator="gpu", devices=1, precision=16)

PyTorch Native

PyTorch 1.6 release introduced mixed precision functionality into their core as the AMP package, torch.cuda.amp. It is more flexible and intuitive compared to NVIDIA APEX. Since computation happens in FP16, there is a chance of numerical instability during training. This is handled internally by a dynamic grad scaler which skips invalid steps and adjusts the scaler to ensure subsequent steps fall within a finite range. For more information see the autocast docs. Lightning uses native amp by default with precision=16|"bf16". You can also set it using:

Trainer(precision=16, amp_backend="native")

NVIDIA APEX

Warning

We strongly recommend using the above native mixed precision rather than NVIDIA APEX unless you require more refined control.

NVIDIA APEX offers additional flexibility in setting mixed precision. This can be useful when trying out different precision configurations, such as keeping most of your weights in FP16 and running computation in FP16.

Trainer(accelerator="gpu", devices=1, amp_backend="apex", precision=16)

Set the NVIDIA optimization level via the precision plugin.

from pytorch_lightning.plugins import ApexMixedPrecisionPlugin


apex_plugin = ApexMixedPrecisionPlugin(amp_level="O3")
Trainer(accelerator="gpu", devices=1, precision=16, plugins=[apex_plugin])

BFloat16 Mixed Precision

Warning

BFloat16 is also experimental and may not provide significant speedups or memory improvements, offering better numerical stability.

Do note for GPUs, the most significant benefits require Ampere based GPUs, such as A100s or 3090s.

BFloat16 Mixed precision is similar to FP16 mixed precision, however, it maintains more of the “dynamic range” that FP32 offers. This means it is able to improve numerical stability than FP16 mixed precision. For more information, see this TPU performance blogpost.

Under the hood, we use torch.autocast with the dtype set to bfloat16, with no gradient scaling.

Trainer(accelerator="gpu", devices=1, precision="bf16")

It is also possible to use BFloat16 mixed precision on the CPU, relying on MKLDNN under the hood.

Trainer(precision="bf16")

8-bit Optimizer

It is possible to further reduce the precision using third-party libraries like bitsandbytes. Although, Lightning doesn’t support it out of the box yet but you can still use it by configuring it in your LightningModule and setting Trainer(precision=32).

import bitsandbytes as bnb

# in your LightningModule, return the 8-bit optimizer
def configure_optimizers(self):
    return bnb.optim.Adam8bit(model.parameters(), lr=0.001, betas=(0.9, 0.995))

© Copyright Copyright (c) 2018-2022, Lightning AI et al... Revision f4fcad36.

Built with Sphinx using a theme provided by Read the Docs.
Read the Docs v: latest
Versions
latest
stable
1.8.3post1
1.8.3.post0
1.8.3
1.8.2
1.8.1
1.8.0.post1
1.8.0
1.7.7
1.7.6
1.7.5
1.7.4
1.7.3
1.7.2
1.7.1
1.7.0
1.6.5
1.6.4
1.6.3
1.6.2
1.6.1
1.6.0
1.5.10
1.5.9
1.5.8
1.5.7
1.5.6
1.5.5
1.5.4
1.5.3
1.5.2
1.5.1
1.5.0
1.4.9
1.4.8
1.4.7
1.4.6
1.4.5
1.4.4
1.4.3
1.4.2
1.4.1
1.4.0
1.3.8
1.3.7
1.3.6
1.3.5
1.3.4
1.3.3
1.3.2
1.3.1
1.3.0
1.2.10
1.2.8
1.2.7
1.2.6
1.2.5
1.2.4
1.2.3
1.2.2
1.2.1
1.2.0
1.1.8
1.1.7
1.1.6
1.1.5
1.1.4
1.1.3
1.1.2
1.1.1
1.1.0
1.0.8
1.0.7
1.0.6
1.0.5
1.0.4
1.0.3
1.0.2
1.0.1
1.0.0
0.10.0
0.9.0
0.8.5
0.8.4
0.8.3
0.8.2
0.8.1
0.8.0
0.7.6
0.7.5
0.7.4
0.7.3
0.7.2
0.7.1
0.7.0
0.6.0
0.5.3
0.4.9
Downloads
html
On Read the Docs
Project Home
Builds

Free document hosting provided by Read the Docs.