torch.backends
torch.backends controls the behavior of various backends that PyTorch supports.
These backends include:
torch.backends.cputorch.backends.cudatorch.backends.cudnntorch.backends.cusparselttorch.backends.mha
torch.backends controls the behavior of various backends that PyTorch supports.
These backends include:
torch.backends.cpu
torch.backends.cuda
torch.backends.cudnn
torch.backends.cusparselt
torch.backends.mha
torch.backends.mps
torch.backends.mkl
torch.backends.mkldnn
torch.backends.nnpack
torch.backends.openmp
torch.backends.opt_einsum
torch.backends.python_native
torch.backends.xeon
Return cpu capability as a string value.
Possible values: - “DEFAULT” - “VSX” - “Z VECTOR” - “NO AVX” - “AVX2” - “AVX512” - “SVE256”
Return whether PyTorch is built with CUDA support.
Note that this doesn’t necessarily mean CUDA is available; just that if this PyTorch binary were run on a machine with working CUDA drivers and devices, we would be able to use it.
A bool that controls whether TensorFloat-32 tensor cores may be used in matrix
multiplications on Ampere or newer GPUs. allow_tf32 is going to be deprecated. See TensorFloat-32 (TF32) on Ampere (and later) devices.
A bool that controls whether reduced precision reductions (e.g.,
with fp16 accumulation type) are allowed with fp16 GEMMs.
For tuple assignment and split-k behavior, see
Reduced Precision Reduction in FP16 GEMMs.
A readonly bool that reports whether split-K heuristics may be used
for fp16 GEMMs when dispatching to cuBLASLt. For how this value is
controlled, see
Reduced Precision Reduction in FP16 GEMMs.
A bool that controls whether supported grouped GEMMs prefer the
cuBLASLt backend.
A bool that controls whether reduced precision reductions are
allowed with bf16 GEMMs.
For tuple assignment and split-k behavior, see
Reduced Precision Reduction in BF16 GEMMs.
A readonly bool that reports whether split-K heuristics may be used
for bf16 GEMMs when dispatching to cuBLASLt. For how this value is
controlled, see
Reduced Precision Reduction in BF16 GEMMs.
cufft_plan_cache contains the cuFFT plan caches for each CUDA device.
Query a specific device i’s cache via torch.backends.cuda.cufft_plan_cache[i].
A readonly int that shows the number of plans currently in a cuFFT plan cache.
Override the library PyTorch uses for BLAS operations. Choose between cuBLAS, cuBLASLt, and CK [ROCm-only].
When PyTorch runs a CUDA BLAS operation it defaults to cuBLAS even if both cuBLAS and cuBLASLt are available.
For PyTorch built for ROCm, hipBLAS, hipBLASLt, and CK may offer different performance.
This flag (a str) allows overriding which BLAS library to use.
If “cublas” is set then cuBLAS will be used wherever possible.
Query or set the cuBLAS workspace size in bytes.
When called with no arguments, returns the current workspace size. When called with a size argument, sets the workspace size and returns the new value. Setting the workspace size will take precedence over the CUBLAS_WORKSPACE_CONFIG environment variable. Changes take effect lazily: only handles used after the change get new workspaces.
size (int, optional) – workspace size in bytes. Must be non-negative.
the current (or newly set) workspace size in bytes.
Query or set the cuBLASLt workspace size in bytes.
When called with no arguments, returns the current workspace size. When called with a size argument, sets the workspace size and returns the new value. Setting the workspace size will take precedence over the CUBLASLT_WORKSPACE_SIZE environment variable. Changes take effect lazily: only handles used after the change get new workspaces.
size (int, optional) – workspace size in bytes. Must be non-negative.
the current (or newly set) workspace size in bytes.
Query or set the BLAS workspace size for a given backend.
Convenience wrapper that dispatches to cublas_workspace_size() or
cublaslt_workspace_size() depending on the backend.
When backend is None the current is
used. is resolved to the platform’s default backend (cuBLAS
on NVIDIA, potentially hipBLASLt on supported ROCm architectures).
[ROCm-only] Override the backend PyTorch uses in ROCm environments for Flash Attention. Choose between AOTriton and CK
When Flash Attention is enabled and desired, PyTorch defaults to using AOTriton as the backend.
This flag (a str) allows users to override this backend to use composable_kernel
If “default” is set then the default backend will be used wherever possible. Currently AOTriton.
If “aotriton” is set then AOTriton will be used wherever possible.
If is set then CK will be used wherever possible.
Returns whether composable_kernel may be used as the backend for scaled-dot-product-attention.
Override the heuristic PyTorch uses to choose between cuSOLVER and MAGMA for CUDA linear algebra operations.
When PyTorch runs a CUDA linear algebra operation it often uses the cuSOLVER or MAGMA libraries,
and if both are available it decides which to use with a heuristic.
This flag (a str) allows overriding those heuristics.
If “cusolver” is set then cuSOLVER will be used wherever possible.
If “magma” is set then MAGMA will be used wherever possible.
If (the default) is set then heuristics will be used to pick between cuSOLVER and MAGMA if both are available.
Returns whether flash scaled dot product attention is enabled or not.
Enables or disables memory efficient scaled dot product attention.
Returns whether memory efficient scaled dot product attention is enabled or not.
Enables or disables flash scaled dot product attention.
Returns whether math scaled dot product attention is enabled or not.
Enables or disables math scaled dot product attention.
Returns whether fp16/bf16 reduction in math scaled dot product attention is enabled or not.
Enables or disables fp16/bf16 reduction in math scaled dot product attention.
Returns whether cuDNN scaled dot product attention is enabled or not.
Enables or disables cuDNN scaled dot product attention.
Check if PyTorch was built with FlashAttention for scaled_dot_product_attention.
True if FlashAttention is built and available; otherwise, False.
Check if FlashAttention can be utilized in scaled_dot_product_attention.
params (_SDPAParams) – An instance of SDPAParams containing the tensors for query, key, value, an optional attention mask, dropout rate, and a flag indicating if the attention is causal.
debug (bool) – Whether to logging.warn debug information as to why FlashAttention could not be run. Defaults to False.
Check if efficient_attention can be utilized in scaled_dot_product_attention.
params (_SDPAParams) – An instance of SDPAParams containing the tensors for query, key, value, an optional attention mask, dropout rate, and a flag indicating if the attention is causal.
debug (bool) – Whether to logging.warn with information as to why efficient_attention could not be run. Defaults to False.
Check if cudnn_attention can be utilized in scaled_dot_product_attention.
params (_SDPAParams) – An instance of SDPAParams containing the tensors for query, key, value, an optional attention mask, dropout rate, and a flag indicating if the attention is causal.
debug (bool) – Whether to logging.warn with information as to why cuDNN attention could not be run. Defaults to False.
This context manager can be used to temporarily enable or disable any of the three backends for scaled dot product attention. Upon exiting the context manager, the previous state of the flags will be restored.
Return the version of cuDNN.
Return a bool indicating if CUDNN is currently available.
A bool that controls whether cuDNN is enabled.
A bool that controls where TensorFloat-32 tensor cores may be used in cuDNN
convolutions on Ampere or newer GPUs. allow_tf32 is going to be deprecated. See TensorFloat-32 (TF32) on Ampere (and later) devices.
A bool that, if True, causes cuDNN to only use deterministic convolution algorithms.
See also torch.are_deterministic_algorithms_enabled() and
torch.use_deterministic_algorithms().
A bool that, if True, causes cuDNN to benchmark multiple convolution algorithms
and select the fastest.
A int that specifies the maximum number of cuDNN convolution algorithms to try when
torch.backends.cudnn.benchmark is True. Set benchmark_limit to zero to try every
available algorithm. Note that this setting only affects convolutions dispatched via the
cuDNN v8 API.
Return the version of cuSPARSELt
int | None
Return a bool indicating if cuSPARSELt is currently available.
int | None
Returns whether fast path for TransformerEncoder and MultiHeadAttention
is enabled, or True if jit is scripting.
Sets whether fast path is enabled
A bool that, if True, causes MIOpen to use Immediate Mode
(https://rocm.docs.amd.com/projects/MIOpen/en/latest/how-to/find-and-immediate.html).
Return a bool indicating if MPS is currently available.
Return whether PyTorch is built with MPS support.
Note that this doesn’t necessarily mean MPS is available; just that if this PyTorch binary were run on a machine with working MPS drivers and devices, we would be able to use it.
Return GPU core count.
According to the documentation, one core is comprised of 16 Execution Units. One execution Unit has 8 ALUs. And one ALU can run 24 threads, i.e. one core is capable of executing 3072 threads concurrently.
Return Metal device name
Return a bool indicating whether MPS is running on MacOS 13 or newer.
Return a bool indicating whether MPS is running on given MacOS or newer.
Return whether PyTorch is built with MKL support.
On-demand oneMKL verbosing functionality.
To make it easier to debug performance issues, oneMKL can dump verbose messages containing execution information like duration while executing the kernel. The verbosing functionality can be invoked via an environment variable named MKL_VERBOSE. However, this methodology dumps messages in all steps. Those are a large amount of verbose messages. Moreover, for investigating the performance issues, generally taking verbose messages for one single iteration is enough. This on-demand verbosing functionality makes it possible to control scope for verbose message dumping. In the following example, verbose messages will be dumped out for the second inference only.
import torch
model(data)
with torch.backends.mkl.verbose(torch.backends.mkl.VERBOSE_ON):
model(data)
level – Verbose level
- VERBOSE_OFF: Disable verbosing
- VERBOSE_ON: Enable verbosing
On-demand oneDNN (former MKL-DNN) verbosing functionality.
To make it easier to debug performance issues, oneDNN can dump verbose messages containing information like kernel size, input data size and execution duration while executing the kernel. The verbosing functionality can be invoked via an environment variable named DNNL_VERBOSE. However, this methodology dumps messages in all steps. Those are a large amount of verbose messages. Moreover, for investigating the performance issues, generally taking verbose messages for one single iteration is enough. This on-demand verbosing functionality makes it possible to control scope for verbose message dumping. In the following example, verbose messages will be dumped out for the second inference only.
import torch
model(data)
with torch.backends.mkldnn.verbose(torch.backends.mkldnn.VERBOSE_ON):
model(data)
level – Verbose level
- VERBOSE_OFF: Disable verbosing
- VERBOSE_ON: Enable verbosing
- VERBOSE_ON_CREATION: Enable verbosing, including oneDNN kernel creation
Return whether PyTorch is built with NNPACK support.
Context manager for setting if nnpack is enabled globally
Set if nnpack is enabled globally
Return whether PyTorch is built with OpenMP support.
Return whether PyTorch is built with KleidiAI support.
Return a bool indicating if opt_einsum is currently available.
You must install opt-einsum in order for torch to automatically optimize einsum. To
make opt-einsum available, you can install it along with torch: pip install torch[opt-einsum]
or by itself: pip install opt-einsum. If the package is installed, torch will import
it automatically and use it accordingly. Use this function to check whether opt-einsum
was installed and properly imported by torch.
Return the opt_einsum package if opt_einsum is currently available, else None.
A bool that controls whether opt_einsum is enabled (True by default). If so,
torch.einsum will use opt_einsum (https://optimized-einsum.readthedocs.io/en/stable/path_finding.html)
if available to calculate an optimal path of contraction for faster performance.
If opt_einsum is not available, torch.einsum will fall back to the default contraction path of left to right.
A str that specifies which strategies to try when torch.backends.opt_einsum.enabled
is True. By default, torch.einsum will try the “auto” strategy, but the “greedy” and “optimal”
strategies are also supported. Note that the “optimal” strategy is factorial on the number of
inputs as it tries all possible paths. See more details in opt_einsum’s docs
(https://optimized-einsum.readthedocs.io/en/stable/path_finding.html).
The torch.backends.python_native module provides user control over native operators implemented in python
via. DSLs (Domain Specific Languages) that are defined in torch._native. This allows users to selectively
enable or disable high-performance implementations from various DSLs like Triton and CuteDSL.
Get list of operations registered by a specific DSL.
dsl_name (str) – Name of the DSL to query (e.g., ‘triton’, ‘cutedsl’).
Sorted list of operation names registered by the DSL.
Example:
ops = torch.backends.python_native.get_dsl_operations("triton")
print(ops) # ['triton_to_mxfp8_dim0', ...]
Disable specific operations across all DSLs.
*op_symbols (str) – Names of operations to disable.
Example:
# Disable scaled matrix multiply across all DSLs
torch.backends.python_native.disable_operations
Re-enable specific operations across all DSLs.
*op_symbols (str) – Names of operations to re-enable.
Example:
# Re-enable previously disabled operations
torch.backends.python_native.enable_operations
Disable operations at specific dispatch keys.
*dispatch_keys (str) – Dispatch keys to disable (e.g., ‘CUDA’, ‘CPU’).
Example:
# Disable all native operations on CUDA
torch.backends.python_native.disable_dispatch_keys
Re-enable operations at specific dispatch keys.
*dispatch_keys (str) – Dispatch keys to re-enable (e.g., ‘CUDA’, ‘CPU’).
Example:
# Re-enable native operations on CUDA
torch.backends.python_native.enable_dispatch_keys
Context manager to temporarily disable operations.
*op_symbols (str) – Names of operations to temporarily disable.
Example:
with torch.backends.python_native.operations_disabled
A list of str containing the names of DSLs that are available at runtime.
This is a subset of all_dsls that have their runtime dependencies satisfied.
For each registered DSL (e.g., triton, cutedsl), auto-populated controller modules are available:
Each DSL controller (e.g., torch.backends.python_native.triton) provides the following properties:
Property | Type | Description |
|---|---|---|
import torch.backends.python_native as pn
# Query available DSLs
print(pn.available_dsls) # ['triton', 'cutedsl']
# Disable all Triton operations
pn.triton.enabled = False
# Temporarily disable CuteDSL operations
with pn.cutedsl.disabled():
result
Parse the command line options.
@retval ArgumentParser
A int that controls the capacity of a cuFFT plan cache.
Clears a cuFFT plan cache.
If “cublaslt” is set then cuBLASLt will be used wherever possible.
If “ck” is set then CK will be used wherever possible.
If “default” (the default) is set then heuristics will be used to pick between the other options.
When no input is given, this function returns the currently preferred library.
User may use the environment variable TORCH_BLAS_PREFER_CUBLASLT=1 to set the preferred library to cuBLASLt globally. This flag only sets the initial value of the preferred library and the preferred library may still be overridden by this function call later in your script.
Note: When a library is preferred other libraries may still be used if the preferred library doesn’t implement the operation(s) called. This flag may achieve better performance if PyTorch’s library selection is incorrect for your application’s inputs.
_BlasBackend
Defaultsize (int, optional) – workspace size in bytes. Must be non-negative. When omitted the current size is returned without modification.
backend (str | torch._C._BlasBackend, optional) – which backend’s
workspace to query/set. Accepts the same strings as
preferred_blas_library() (e.g. "cublas", "cublaslt").
the current (or newly set) workspace size in bytes.
RuntimeError – if the resolved backend is CK (no workspace concept).
When no input is given, this function returns the currently preferred library.
User may use the environment variable TORCH_ROCM_FA_PREFER_CK=1 to set the preferred library to CK globally.
Note: When a library is preferred other libraries may still be used if the preferred library doesn’t implement the operation(s) called. This flag may achieve better performance if PyTorch’s library selection is incorrect for your application’s inputs.
_ROCmFABackend
When no input is given, this function returns the currently preferred library.
User may use the environment variable TORCH_LINALG_PREFER_CUSOLVER=1 to set the preferred library to cuSOLVER globally. This flag only sets the initial value of the preferred library and the preferred library may still be overridden by this function call later in your script.
Note: When a library is preferred other libraries may still be used if the preferred library doesn’t implement the operation(s) called. This flag may achieve better performance if PyTorch’s heuristic library selection is incorrect for your application’s inputs.
Currently supported linalg operators:
_LinalgBackend
True if FlashAttention can be used with the given parameters; otherwise, False.
True if efficient_attention can be used with the given parameters; otherwise, False.
True if cuDNN can be used with the given parameters; otherwise, False.
name
|
The name of the DSL |
|
| Whether the DSL’s runtime dependencies are available |
|
| Controls whether all operations from this DSL are enabled. Setting to |
|
| The version of the DSL runtime, if available. Returns |
Each DSL controller provides the following methods:
disable() Disable all operations from this DSL.
enable() Re-enable all operations from this DSL.
disabled() Context manager that temporarily disables all operations from this DSL. Operations are automatically re-enabled when exiting the context.
Example::
with torch.backends.python_native.triton.disabled():
# Triton operations are disabled here
result = model(input)
# Triton operations restored here