torch.amp provides convenience methods for mixed precision,
where some operations use the torch.float32 (float) datatype and other operations
use lower precision floating point datatype (lower_precision_fp): torch.float16 (half) or torch.bfloat16. Some ops, like linear layers and convolutions,
are much faster in . Other ops, like reductions, often require the dynamic
range of . Mixed precision tries to match each op to its appropriate datatype.
Return a bool indicating if autocast is available on device_type.
Parameters:
device_type (str) – Device type to use. Possible values are: ‘cuda’, ‘cpu’, ‘mtia’, ‘maia’, ‘xpu’, and so on.
The type is the same as the type attribute of a torch.device.
Thus, you may obtain the device type of a tensor using Tensor.device.type.
Instances of autocast serve as context managers or decorators that
allow regions of your script to run in mixed precision.
In these regions, ops run in an op-specific dtype chosen by autocast
to improve performance while maintaining accuracy.
See the Autocast Op Reference for details.
When entering an autocast-enabled region, Tensors may be any type.
You should not call or on your model(s) or inputs when using autocasting.
Create a helper decorator for backward methods of custom autograd functions.
Autograd functions are subclasses of torch.autograd.Function.
Ensures that backward executes with the same autocast state as forward.
See the example page for more detail.
See torch.autocast.
torch.cpu.amp.autocast(args...) is deprecated. Please use torch.amp.autocast("cpu",args...) instead.
Gradient Scaling
If the forward pass for a particular op has float16 inputs, the backward pass for
that op will produce float16 gradients.
Gradient values with small magnitudes may not be representable in float16.
These values will flush to zero (“underflow”), so the update for the corresponding parameters will be lost.
To prevent underflow, “gradient scaling” multiplies the network’s loss(es) by a scale factor and
invokes a backward pass on the scaled loss(es). Gradients flowing backward through the network are
then scaled by the same factor. In other words, gradient values have a larger magnitude,
so they don’t flush to zero.
Each parameter’s gradient (.grad attribute) should be unscaled before the optimizer
updates the parameters, so the scale factor does not interfere with the learning rate.
See torch.amp.GradScaler.
torch.cpu.amp.GradScaler(args...) is deprecated. Please use instead.
Autocast Op Reference
Op Eligibility
Ops that run in float64 or non-floating-point dtypes are not eligible, and will
run in these types whether or not autocast is enabled.
Only out-of-place ops and Tensor methods are eligible.
In-place variants and calls that explicitly supply an out=... Tensor
are allowed in autocast-enabled regions, but won’t go through autocasting.
For example, in an autocast-enabled region a.addmm(b,c) can autocast,
but a.addmm_(b,c) and a.addmm(b,c,out=d) cannot.
For best performance and stability, prefer out-of-place ops in autocast-enabled
regions.
Ops called with an explicit dtype=... argument are not eligible,
and will produce output that respects the dtype argument.
CUDA Op-Specific Behavior
The following lists describe the behavior of eligible ops in autocast-enabled regions.
These ops always go through autocasting whether they are invoked as part of a torch.nn.Module,
as a function, or as a torch.Tensor method. If functions are exposed in multiple namespaces,
they go through autocasting regardless of the namespace.
Ops not listed below do not go through autocasting. They run in the type
defined by their inputs. However, autocasting may still change the type
in which unlisted ops run if they’re downstream from autocasted ops.
If an op is unlisted, we assume it’s numerically stable in float16.
If you believe an unlisted op is numerically unstable in float16,
please file an issue.
CUDA Ops that can autocast to float16
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
XPU Op-Specific Behavior (Experimental)
The following lists describe the behavior of eligible ops in autocast-enabled regions.
These ops always go through autocasting whether they are invoked as part of a torch.nn.Module,
as a function, or as a torch.Tensor method. If functions are exposed in multiple namespaces,
they go through autocasting regardless of the namespace.
Ops not listed below do not go through autocasting. They run in the type
defined by their inputs. However, autocasting may still change the type
in which unlisted ops run if they’re downstream from autocasted ops.
If an op is unlisted, we assume it’s numerically stable in float16.
If you believe an unlisted op is numerically unstable in float16,
please file an issue.
XPU Ops that can autocast to float16
CPU Op-Specific Behavior
The following lists describe the behavior of eligible ops in autocast-enabled regions.
These ops always go through autocasting whether they are invoked as part of a torch.nn.Module,
as a function, or as a torch.Tensor method. If functions are exposed in multiple namespaces,
they go through autocasting regardless of the namespace.
Ops not listed below do not go through autocasting. They run in the type
defined by their inputs. However, autocasting may still change the type
in which unlisted ops run if they’re downstream from autocasted ops.
If an op is unlisted, we assume it’s numerically stable in bfloat16.
If you believe an unlisted op is numerically unstable in bfloat16,
please file an issue. float16 shares the lists of bfloat16.
half()
bfloat16()
autocast should wrap only the forward pass(es) of your network, including the loss
computation(s). Backward passes under autocast are not recommended.
Backward ops run in the same type that autocast used for corresponding forward ops.
Example for CUDA Devices:
# Creates model and optimizer in default precisionmodel=Net().cuda()optimizer=optim.SGD(model.parameters(),...)forinput,targetindata:optimizer.zero_grad()# Enables autocasting for the forward pass (model + loss)withtorch.autocast(device_type="cuda"):output=model(input)loss=loss_fn(output,target)# Exits the context manager before backward()loss.backward()optimizer.step()
See the Automatic Mixed Precision examples for usage (along with gradient scaling)
in more complex scenarios (e.g., gradient penalty, multiple models/losses, custom autograd functions).
autocast can also be used as a decorator, e.g., on the forward method of your model:
Floating-point Tensors produced in an autocast-enabled region may be float16.
After returning to an autocast-disabled region, using them with floating-point
Tensors of different dtypes may cause type mismatch errors. If so, cast the Tensor(s)
produced in the autocast region back to float32 (or other dtype if desired).
If a Tensor from the autocast region is already float32, the cast is a no-op,
and incurs no additional overhead.
CUDA Example:
# Creates some tensors in default dtype (here assumed to be float32)a_float32=torch.rand((8,8),device="cuda")b_float32=torch.rand((8,8),device="cuda")c_float32=torch.rand((8,8),device="cuda")d_float32=torch.rand((8,8),device="cuda")withtorch.autocast(device_type="cuda"):# torch.mm is on autocast's list of ops that should run in float16.# Inputs are float32, but the op runs in float16 and produces float16 output.# No manual casts are required.e_float16=torch.mm(a_float32,b_float32)# Also handles mixed input typesf_float16=torch.mm(d_float32,e_float16)# After exiting autocast, calls f_float16.float() to use with d_float32g_float32=torch.mm(d_float32,f_float16.float())
CPU Training Example:
# Creates model and optimizer in default precisionmodel=Net()optimizer=optim.SGD(model.parameters(),...)forepochinepochs:forinput,targetindata:optimizer.zero_grad()# Runs the forward pass with autocasting.withtorch.autocast(device_type="cpu",dtype=torch.bfloat16):output=model(input)loss=loss_fn(output,target)loss.backward()optimizer.step()
CPU Inference Example:
# Creates model in default precisionmodel=Net().eval()withtorch.autocast(device_type="cpu",dtype=torch.bfloat16):forinputindata:# Runs the forward pass with autocasting.output=model(input)
CPU Inference Example with Jit Trace:
classTestModel(nn.Module):def__init__(self,input_size,num_classes):super().__init__()self.fc1=nn.Linear(input_size,num_classes)defforward(self,x):returnself.fc1(x)input_size=2num_classes=2model=TestModel(input_size,num_classes).eval()# For now, we suggest to disable the Jit Autocast Pass,# As the issue: https://github.com/pytorch/pytorch/issues/75956torch._C._jit_set_autocast_mode(False)withtorch.cpu.amp.autocast(cache_enabled=False):model=torch.jit.trace(model,torch.randn(1,input_size))model=torch.jit.freeze(model)# Models Runfor_inrange(3):model(torch.randn(1,input_size))
Type mismatch errors in an autocast-enabled region are a bug; if this is what you observe,
please file an issue.
autocast(enabled=False) subregions can be nested in autocast-enabled regions.
Locally disabling autocast can be useful, for example, if you want to force a subregion
to run in a particular dtype. Disabling autocast gives you explicit control over
the execution type. In the subregion, inputs from the surrounding region
should be cast to dtype before use:
# Creates some tensors in default dtype (here assumed to be float32)a_float32=torch.rand((8,8),device="cuda")b_float32=torch.rand((8,8),device="cuda")c_float32=torch.rand((8,8),device="cuda")d_float32=torch.rand((8,8),device="cuda")withtorch.autocast(device_type="cuda"):e_float16=torch.mm(a_float32,b_float32)withtorch.autocast(device_type="cuda",enabled=False):# Calls e_float16.float() to ensure float32 execution# (necessary because e_float16 was created in an autocasted region)f_float32=torch.mm(c_float32,e_float16.float())# No manual casts are required when re-entering the autocast-enabled region.# torch.mm again runs in float16 and produces float16 output, regardless of input types.g_float16=torch.mm(d_float32,f_float32)
device_type (str, required) – Device type to use. Possible values are: ‘cuda’, ‘cpu’, ‘mtia’, ‘maia’, ‘xpu’, and ‘hpu’.
The type is the same as the type attribute of a torch.device.
Thus, you may obtain the device type of a tensor using Tensor.device.type.
enabled (bool, optional) – Whether autocasting should be enabled in the region.
Default: True
dtype (torch_dtype, optional) – Data type for ops run in autocast. It uses the default value
(torch.float16 for CUDA and torch.bfloat16 for CPU), given by
get_autocast_dtype(), if dtype is None.
Default: None
cache_enabled (bool, optional) – Whether the weight cache inside autocast should be enabled.
Default: True
device_type (str) – Device type to use. ‘cuda’, ‘cpu’, ‘mtia’, ‘maia’, ‘xpu’ and so on.
The type is the same as the type attribute of a torch.device.
Thus, you may obtain the device type of a tensor using Tensor.device.type.
cast_inputs (torch.dtype or None, optional, default=None) – If not None,
when forward runs in an autocast-enabled region, casts incoming
floating-point Tensors to the target dtype (non-floating-point Tensors are not affected),
then executes forward with autocast disabled.
If None, forward’s internal ops execute with the current autocast state.
device_type (str) – Device type to use. ‘cuda’, ‘cpu’, ‘mtia’, ‘maia’, ‘xpu’ and so on.
The type is the same as the type attribute of a torch.device.
Thus, you may obtain the device type of a tensor using Tensor.device.type.
These ops don’t require a particular dtype for stability, but take multiple inputs
and require that the inputs’ dtypes match. If all of the inputs are
float16, the op runs in float16. If any of the inputs is float32,
autocast casts all inputs to float32 and runs the op in float32.
Some ops not listed here (e.g., binary ops like add) natively promote
inputs without autocasting’s intervention. If inputs are a mixture of float16
and float32, these ops run in float32 and produce float32 output,
regardless of whether autocast is enabled.
Prefer binary_cross_entropy_with_logits over binary_cross_entropy
The backward passes of torch.nn.functional.binary_cross_entropy() (and torch.nn.BCELoss, which wraps it)
can produce gradients that aren’t representable in float16. In autocast-enabled regions, the forward input
may be float16, which means the backward gradient must be representable in float16 (autocasting float16
forward inputs to float32 doesn’t help, because that cast must be reversed in backward).
Therefore, binary_cross_entropy and BCELoss raise an error in autocast-enabled regions.
These ops don’t require a particular dtype for stability, but take multiple inputs
and require that the inputs’ dtypes match. If all of the inputs are
float16, the op runs in float16. If any of the inputs is float32,
autocast casts all inputs to float32 and runs the op in float32.
Some ops not listed here (e.g., binary ops like add) natively promote
inputs without autocasting’s intervention. If inputs are a mixture of float16
and float32, these ops run in float32 and produce float32 output,
regardless of whether autocast is enabled.
These ops don’t require a particular dtype for stability, but take multiple inputs
and require that the inputs’ dtypes match. If all of the inputs are
bfloat16, the op runs in bfloat16. If any of the inputs is float32,
autocast casts all inputs to float32 and runs the op in float32.
cat,
stack,
index_copy
Some ops not listed here (e.g., binary ops like add) natively promote
inputs without autocasting’s intervention. If inputs are a mixture of bfloat16
and float32, these ops run in float32 and produce float32 output,
regardless of whether autocast is enabled.