Top level container for Callgrind results collected by Timer.
Manipulation is generally done using the FunctionCounts class, which is obtained by calling CallgrindStats.stats(…). Several convenience methods are provided as well; the most significant is CallgrindStats.as_standardized().
Strip library names and some prefixes from function strings.
When comparing two different sets of instruction counts, on stumbling block can be path prefixes. Callgrind includes the full filepath when reporting a function (as it should). However, this can cause issues when diffing profiles. If a key component such as Python or PyTorch was built in separate locations in the two profiles, which can result in something resembling:
Stripping prefixes can ameliorate this issue by regularizing the strings and causing better cancellation of equivilent call sites when diffing.
Returns the total number of instructions executed.
See FunctionCounts.denoise() for an explation of the denoise arg.
Diff two sets of counts.
One common reason to collect instruction counts is to determine the the effect that a particular change will have on the number of instructions needed to perform some unit of work. If a change increases that number, the next logical question is “why”. This generally involves looking at what part if the code increased in instruction count. This function automates that process so that one can easily diff counts on both an inclusive and exclusive basis. The subtract_baselines argument allows one to disable baseline correction, though in most cases it shouldn’t matter as the baselines are expected to more or less cancel out.
Returns detailed function counts.
Conceptually, the FunctionCounts returned can be thought of as a tuple of (count, path_and_function_name) tuples.
inclusive matches the semantics of callgrind. If True, the counts include instructions executed by children. inclusive=True is useful for identifying hot spots in code; inclusive=False is useful for reducing noise when diffing counts from two different runs. (See CallgrindStats.delta(…) for more details)


Strip library names and some prefixes from function strings.
When comparing two different sets of instruction counts, on stumbling block can be path prefixes. Callgrind includes the full filepath when reporting a function (as it should). However, this can cause issues when diffing profiles. If a key component such as Python or PyTorch was built in separate locations in the two profiles, which can result in something resembling:
Stripping prefixes can ameliorate this issue by regularizing the strings and causing better cancellation of equivilent call sites when diffing.


Returns the total number of instructions executed.
See FunctionCounts.denoise() for an explation of the denoise arg.


Diff two sets of counts.
One common reason to collect instruction counts is to determine the the effect that a particular change will have on the number of instructions needed to perform some unit of work. If a change increases that number, the next logical question is “why”. This generally involves looking at what part if the code increased in instruction count. This function automates that process so that one can easily diff counts on both an inclusive and exclusive basis. The subtract_baselines argument allows one to disable baseline correction, though in most cases it shouldn’t matter as the baselines are expected to more or less cancel out.


Returns detailed function counts.
Conceptually, the FunctionCounts returned can be thought of as a tuple of (count, path_and_function_name) tuples.
inclusive matches the semantics of callgrind. If True, the counts include instructions executed by children. inclusive=True is useful for identifying hot spots in code; inclusive=False is useful for reducing noise when diffing counts from two different runs. (See CallgrindStats.delta(…) for more details)


Container for manipulating Callgrind results.
Remove known noisy instructions.
Several instructions in the CPython interpreter are rather noisy. These instructions involve unicode to dictionary lookups which Python uses to map variable names. FunctionCounts is generally a content agnostic container, however this is sufficiently important for obtaining reliable results to warrant an exception.
Keep only the elements where filter_fn applied to function name returns True.
Apply map_fn to all of the function names.
This can be used to regularize function names (e.g. stripping irrelevant parts of the file path), coalesce entries by mapping multiple functions to the same name (in which case the counts are added together), etc.


Remove known noisy instructions.
Several instructions in the CPython interpreter are rather noisy. These instructions involve unicode to dictionary lookups which Python uses to map variable names. FunctionCounts is generally a content agnostic container, however this is sufficiently important for obtaining reliable results to warrant an exception.


Keep only the elements where filter_fn applied to function name returns True.


Apply map_fn to all of the function names.
This can be used to regularize function names (e.g. stripping irrelevant parts of the file path), coalesce entries by mapping multiple functions to the same name (in which case the counts are added together), etc.


The result of a Timer measurement.
This class stores one or more measurements of a given statement. It is serializable and provides several convenience methods (including a detailed __repr__) for downstream consumers.
Convenience method for merging replicates.
Merge will extrapolate times to number_per_run=1 and will not transfer any metadata. (Since it might differ between replicates)
Approximate significant figure estimate.
This property is intended to give a convenient way to estimate the precision of a measurement. It only uses the interquartile region to estimate statistics to try to mitigate skew from the tails, and uses a static z value of 1.645 since it is not expected to be used for small values of n, so z can approximate t.
The significant figure estimation used in conjunction with the trim_sigfig method to provide a more human interpretable data summary. __repr__ does not use this method; it simply displays raw values. Significant figure estimation is intended for Compare.


Convenience method for merging replicates.
Merge will extrapolate times to number_per_run=1 and will not transfer any metadata. (Since it might differ between replicates)


Approximate significant figure estimate.
This property is intended to give a convenient way to estimate the precision of a measurement. It only uses the interquartile region to estimate statistics to try to mitigate skew from the tails, and uses a static z value of 1.645 since it is not expected to be used for small values of n, so z can approximate t.
The significant figure estimation used in conjunction with the trim_sigfig method to provide a more human interpretable data summary. __repr__ does not use this method; it simply displays raw values. Significant figure estimation is intended for Compare.


Helper class for measuring execution time of PyTorch statements.
For a full tutorial on how to use this class, see: https://pytorch.org/tutorials/recipes/recipes/benchmark.html
The PyTorch Timer is based on timeit.Timer (and in fact uses timeit.Timer internally), but with several key differences:
Timer will perform warmups (important as some elements of PyTorch are lazily initialized), set threadpool size so that comparisons are apples-to-apples, and synchronize asynchronous CUDA functions when necessary.
When measuring code, and particularly complex kernels / models, run-to-run variation is a significant confounding factor. It is expected that all measurements should include replicates to quantify noise and allow median computation, which is more robust than mean. To that effect, this class deviates from the timeit API by conceptually merging timeit.Timer.repeat and timeit.Timer.autorange. (Exact algorithms are discussed in method docstrings.) The timeit method is replicated for cases where an adaptive strategy is not desired.
When defining a Timer, one can optionally specify label, sub_label, description, and env. (Defined later) These fields are included in the representation of result object and by the Compare class to group and display results for comparison.
In addition to wall times, Timer can run a statement under Callgrind and report instructions executed.
Directly analogous to timeit.Timer constructor arguments:
stmt, setup, timer, globals
PyTorch Timer specific constructor arguments:
label, sub_label, description, env, num_threads
sub_label –
Provide supplemental information to disambiguate measurements with identical stmt or label. For instance, in our example above sub_label might be “float” or “int”, so that it is easy to differentiate: “ReLU(x + 1): (float)”
”ReLU(x + 1): (int)” when printing Measurements or summarizing using Compare.
description –
String to distinguish measurements with identical label and sub_label. The principal use of description is to signal to Compare the columns of data. For instance one might set it based on the input size to create a table of the form:
using Compare. It is also included when printing a Measurement.
Measure many replicates while keeping timer overhead to a minimum.
At a high level, blocked_autorange executes the following pseudo-code:
Note the variable block_size in the inner loop. The choice of block size is important to measurement quality, and must balance two competing objectives:
blocked_autorange sets block_size by running a warmup period, increasing block size until timer overhead is less than 0.1% of the overall computation. This value is then used for the main measurement loop.
A Measurement object that contains measured runtimes and repetition counts, and can be used to compute statistics. (mean, median, etc.)
Collect instruction counts using Callgrind.
Unlike wall times, instruction counts are deterministic (modulo non-determinism in the program itself and small amounts of jitter from the Python interpreter.) This makes them ideal for detailed performance analysis. This method runs stmt in a separate process so that Valgrind can instrument the program. Performance is severely degraded due to the instrumentation, howevever this is ameliorated by the fact that a small number of iterations is generally sufficient to obtain good measurements.
In order to to use this method valgrind, callgrind_control, and callgrind_annotate must be installed.
Because there is a process boundary between the caller (this process) and the stmt execution, globals cannot contain arbitrary in-memory data structures. (Unlike timing methods) Instead, globals are restricted to builtins, nn.Modules’s, and TorchScripted functions/modules to reduce the surprise factor from serialization and subsequent deserialization. The GlobalsBridge class provides more detail on this subject. Take particular care with nn.Modules: they rely on pickle and you may need to add an import to setup for them to transfer properly.
By default, a profile for an empty statement will be collected and cached to indicate how many instructions are from the Python loop which drives stmt.
A CallgrindStats object which provides instruction counts and some basic facilities for analyzing and manipulating results.
Mirrors the semantics of timeit.Timer.timeit().
Execute the main statement (stmt) number times. https://docs.python.org/3/library/timeit.html#timeit.Timer.timeit


Measure many replicates while keeping timer overhead to a minimum.
At a high level, blocked_autorange executes the following pseudo-code:
Note the variable block_size in the inner loop. The choice of block size is important to measurement quality, and must balance two competing objectives:
blocked_autorange sets block_size by running a warmup period, increasing block size until timer overhead is less than 0.1% of the overall computation. This value is then used for the main measurement loop.
A Measurement object that contains measured runtimes and repetition counts, and can be used to compute statistics. (mean, median, etc.)


Collect instruction counts using Callgrind.
Unlike wall times, instruction counts are deterministic (modulo non-determinism in the program itself and small amounts of jitter from the Python interpreter.) This makes them ideal for detailed performance analysis. This method runs stmt in a separate process so that Valgrind can instrument the program. Performance is severely degraded due to the instrumentation, howevever this is ameliorated by the fact that a small number of iterations is generally sufficient to obtain good measurements.
In order to to use this method valgrind, callgrind_control, and callgrind_annotate must be installed.
Because there is a process boundary between the caller (this process) and the stmt execution, globals cannot contain arbitrary in-memory data structures. (Unlike timing methods) Instead, globals are restricted to builtins, nn.Modules’s, and TorchScripted functions/modules to reduce the surprise factor from serialization and subsequent deserialization. The GlobalsBridge class provides more detail on this subject. Take particular care with nn.Modules: they rely on pickle and you may need to add an import to setup for them to transfer properly.
By default, a profile for an empty statement will be collected and cached to indicate how many instructions are from the Python loop which drives stmt.
A CallgrindStats object which provides instruction counts and some basic facilities for analyzing and manipulating results.


Mirrors the semantics of timeit.Timer.timeit().
Execute the main statement (stmt) number times. https://docs.python.org/3/library/timeit.html#timeit.Timer.timeit


torch.utils.bottleneck is a tool that can be used as an initial step for debugging bottlenecks in your program. It summarizes runs of your script with the Python profiler and PyTorch’s autograd profiler.
Run it on the command line with
where [args] are any number of arguments to script.py, or run python -m torch.utils.bottleneck -h for more usage instructions.
Warning
Because your script will be profiled, please ensure that it exits in a finite amount of time.
Warning
Due to the asynchronous nature of CUDA kernels, when running against CUDA code, the cProfile output and CPU-mode autograd profilers may not show correct timings: the reported CPU time reports the amount of time used to launch the kernels but does not include the time the kernel spent executing on a GPU unless the operation does a synchronize. Ops that do synchronize appear to be extremely expensive under regular CPU-mode profilers. In these case where timings are incorrect, the CUDA-mode autograd profiler may be helpful.
Note
To decide which (CPU-only-mode or CUDA-mode) autograd profiler output to look at, you should first check if your script is CPU-bound (“CPU total time is much greater than CUDA total time”). If it is CPU-bound, looking at the results of the CPU-mode autograd profiler will help. If on the other hand your script spends most of its time executing on the GPU, then it makes sense to start looking for responsible CUDA operators in the output of the CUDA-mode autograd profiler.
Of course the reality is much more complicated and your script might not be in one of those two extremes depending on the part of the model you’re evaluating. If the profiler outputs don’t help, you could try looking at the result of torch.autograd.profiler.emit_nvtx() with nvprof. However, please take into account that the NVTX overhead is very high and often gives a heavily skewed timeline.
Warning
If you are profiling CUDA code, the first profiler that bottleneck runs (cProfile) will include the CUDA startup time (CUDA buffer allocation cost) in its time reporting. This should not matter if your bottlenecks result in code much slower than the CUDA startup time.
For more complicated uses of the profilers (like in a multi-GPU case), please see https://docs.python.org/3/library/profile.html or torch.autograd.profiler.profile() for more information.


Note
Checkpointing is implemented by rerunning a forward-pass segment for each checkpointed segment during backward. This can cause persistent states like the RNG state to be advanced than they would without checkpointing. By default, checkpointing includes logic to juggle the RNG state such that checkpointed passes making use of RNG (through dropout for example) have deterministic output as compared to non-checkpointed passes. The logic to stash and restore RNG states can incur a moderate performance hit depending on the runtime of checkpointed operations. If deterministic output compared to non-checkpointed passes is not required, supply preserve_rng_state=False to checkpoint or checkpoint_sequential to omit stashing and restoring the RNG state during each checkpoint.
The stashing logic saves and restores the RNG state for the current device and the device of all cuda Tensor arguments to the run_fn. However, the logic has no way to anticipate if the user will move Tensors to a new device within the run_fn itself. Therefore, if you move Tensors to a new device (“new” meaning not belonging to the set of [current device + devices of Tensor arguments]) within run_fn, deterministic output compared to non-checkpointed passes is never guaranteed.
Checkpoint a model or part of the model
Checkpointing works by trading compute for memory. Rather than storing all intermediate activations of the entire computation graph for computing backward, the checkpointed part does not save intermediate activations, and instead recomputes them in backward pass. It can be applied on any part of a model.
Specifically, in the forward pass, function will run in torch.no_grad() manner, i.e., not storing the intermediate activations. Instead, the forward pass saves the inputs tuple and the function parameter. In the backwards pass, the saved inputs and function is retrieved, and the forward pass is computed on function again, now tracking the intermediate activations, and then the gradients are calculated using these activation values.
Warning
Checkpointing doesn’t work with torch.autograd.grad(), but only with torch.autograd.backward().
Warning
If function invocation during backward does anything different than the one during forward, e.g., due to some global variable, the checkpointed version won’t be equivalent, and unfortunately it can’t be detected.
Warning
If checkpointed segment contains tensors detached from the computational graph by detach() or torch.no_grad(), the backward pass will raise an error. This is because checkpoint makes all the outputs require gradients which causes issues when a tensor is defined to have no gradient in the model. To circumvent this, detach the tensors outside of the checkpoint function.
Output of running function on *args
A helper function for checkpointing sequential models.
Sequential models execute a list of modules/functions in order (sequentially). Therefore, we can divide such a model in various segments and checkpoint each segment. All segments except the last will run in torch.no_grad() manner, i.e., not storing the intermediate activations. The inputs of each checkpointed segment will be saved for re-running the segment in the backward pass.
See checkpoint() on how checkpointing works.
Warning
Checkpointing doesn’t work with torch.autograd.grad(), but only with torch.autograd.backward().
Output of running functions sequentially on *inputs


Checkpoint a model or part of the model
Checkpointing works by trading compute for memory. Rather than storing all intermediate activations of the entire computation graph for computing backward, the checkpointed part does not save intermediate activations, and instead recomputes them in backward pass. It can be applied on any part of a model.
Specifically, in the forward pass, function will run in torch.no_grad() manner, i.e., not storing the intermediate activations. Instead, the forward pass saves the inputs tuple and the function parameter. In the backwards pass, the saved inputs and function is retrieved, and the forward pass is computed on function again, now tracking the intermediate activations, and then the gradients are calculated using these activation values.
Warning
Checkpointing doesn’t work with torch.autograd.grad(), but only with torch.autograd.backward().
Warning
If function invocation during backward does anything different than the one during forward, e.g., due to some global variable, the checkpointed version won’t be equivalent, and unfortunately it can’t be detected.
Warning
If checkpointed segment contains tensors detached from the computational graph by detach() or torch.no_grad(), the backward pass will raise an error. This is because checkpoint makes all the outputs require gradients which causes issues when a tensor is defined to have no gradient in the model. To circumvent this, detach the tensors outside of the checkpoint function.
Output of running function on *args


A helper function for checkpointing sequential models.
Sequential models execute a list of modules/functions in order (sequentially). Therefore, we can divide such a model in various segments and checkpoint each segment. All segments except the last will run in torch.no_grad() manner, i.e., not storing the intermediate activations. The inputs of each checkpointed segment will be saved for re-running the segment in the backward pass.
See checkpoint() on how checkpointing works.
Warning
Checkpointing doesn’t work with torch.autograd.grad(), but only with torch.autograd.backward().
Output of running functions sequentially on *inputs


Creates a setuptools.Extension for C++.
Convenience method that creates a setuptools.Extension with the bare minimum (but often sufficient) arguments to build a C++ extension.
All arguments are forwarded to the setuptools.Extension constructor.
Creates a setuptools.Extension for CUDA/C++.
Convenience method that creates a setuptools.Extension with the bare minimum (but often sufficient) arguments to build a CUDA/C++ extension. This includes the CUDA include path, library path and runtime library.
All arguments are forwarded to the setuptools.Extension constructor.
Compute capabilities:
By default the extension will be compiled to run on all archs of the cards visible during the building process of the extension, plus PTX. If down the road a new card is installed the extension may need to be recompiled. If a visible card has a compute capability (CC) that’s newer than the newest version for which your nvcc can build fully-compiled binaries, Pytorch will make nvcc fall back to building kernels with the newest version of PTX your nvcc does support (see below for details on PTX).
You can override the default behavior using TORCH_CUDA_ARCH_LIST to explicitly specify which CCs you want the extension to support:
TORCH_CUDA_ARCH_LIST=”6.1 8.6” python build_my_extension.py TORCH_CUDA_ARCH_LIST=”5.2 6.0 6.1 7.0 7.5 8.0 8.6+PTX” python build_my_extension.py
The +PTX option causes extension kernel binaries to include PTX instructions for the specified CC. PTX is an intermediate representation that allows kernels to runtime-compile for any CC >= the specified CC (for example, 8.6+PTX generates PTX that can runtime-compile for any GPU with CC >= 8.6). This improves your binary’s forward compatibility. However, relying on older PTX to provide forward compat by runtime-compiling for newer CCs can modestly reduce performance on those newer CCs. If you know exact CC(s) of the GPUs you want to target, you’re always better off specifying them individually. For example, if you want your extension to run on 8.0 and 8.6, “8.0+PTX” would work functionally because it includes PTX that can runtime-compile for 8.6, but “8.0 8.6” would be better.
Note that while it’s possible to include all supported archs, the more archs get included the slower the building process will be, as it will build a separate kernel image for each arch.
A custom setuptools build extension .
This setuptools.build_ext subclass takes care of passing the minimum required compiler flags (e.g. -std=c++14) as well as mixed C++/CUDA compilation (and support for CUDA files in general).
When using BuildExtension, it is allowed to supply a dictionary for extra_compile_args (rather than the usual list) that maps from languages (cxx or nvcc) to a list of additional compiler flags to supply to the compiler. This makes it possible to supply different flags to the C++ and CUDA compiler during mixed compilation.
use_ninja (bool): If use_ninja is True (default), then we attempt to build using the Ninja backend. Ninja greatly speeds up compilation compared to the standard setuptools.build_ext. Fallbacks to the standard distutils backend if Ninja is not available.
Note
By default, the Ninja backend uses #CPUS + 2 workers to build the extension. This may use up too many resources on some systems. One can control the number of workers by setting the MAX_JOBS environment variable to a non-negative number.
Loads a PyTorch C++ extension just-in-time (JIT).
To load an extension, a Ninja build file is emitted, which is used to compile the given sources into a dynamic library. This library is subsequently loaded into the current Python process as a module and returned from this function, ready for use.
By default, the directory to which the build file is emitted and the resulting library compiled to is <tmp>/torch_extensions/<name>, where <tmp> is the temporary folder on the current platform and <name> the name of the extension. This location can be overridden in two ways. First, if the TORCH_EXTENSIONS_DIR environment variable is set, it replaces <tmp>/torch_extensions and all extensions will be compiled into subfolders of this directory. Second, if the build_directory argument to this function is supplied, it overrides the entire path, i.e. the library will be compiled into that folder directly.
To compile the sources, the default system compiler (c++) is used, which can be overridden by setting the CXX environment variable. To pass additional arguments to the compilation process, extra_cflags or extra_ldflags can be provided. For example, to compile your extension with optimizations, pass extra_cflags=['-O3']. You can also use extra_cflags to pass further include directories.
CUDA support with mixed compilation is provided. Simply pass CUDA source files (.cu or .cuh) along with other sources. Such files will be detected and compiled with nvcc rather than the C++ compiler. This includes passing the CUDA lib64 directory as a library directory, and linking cudart. You can pass additional flags to nvcc via extra_cuda_cflags, just like with extra_cflags for C++. Various heuristics for finding the CUDA install directory are used, which usually work fine. If not, setting the CUDA_HOME environment variable is the safest option.
Returns the loaded PyTorch extension as a Python module.
Returns nothing. (The shared library is loaded into the process as a side effect.)
Return the path to the executable. (On Windows, TORCH_LIB_PATH is added to the PATH environment variable as a side effect.)
If is_python_module is True
Loads a PyTorch C++ extension just-in-time (JIT) from string sources.
This function behaves exactly like load(), but takes its sources as strings rather than filenames. These strings are stored to files in the build directory, after which the behavior of load_inline() is identical to load().
See the tests for good examples of using this function.
Sources may omit two required parts of a typical non-inline C++ extension: the necessary header includes, as well as the (pybind11) binding code. More precisely, strings passed to cpp_sources are first concatenated into a single .cpp file. This file is then prepended with #include
<torch/extension.h>.
Furthermore, if the functions argument is supplied, bindings will be automatically generated for each function specified. functions can either be a list of function names, or a dictionary mapping from function names to docstrings. If a list is given, the name of each function is used as its docstring.
The sources in cuda_sources are concatenated into a separate .cu file and prepended with torch/types.h, cuda.h and cuda_runtime.h includes. The .cpp and .cu files are compiled separately, but ultimately linked into a single library. Note that no bindings are generated for functions in cuda_sources per se. To bind to a CUDA kernel, you must create a C++ function that calls it, and either declare or define this C++ function in one of the cpp_sources (and include its name in functions).
See load() for a description of arguments omitted below.
Note
By default, the Ninja backend uses #CPUS + 2 workers to build the extension. This may use up too many resources on some systems. One can control the number of workers by setting the MAX_JOBS environment variable to a non-negative number.
Get the include paths required to build a C++ or CUDA extension.
cuda – If True, includes CUDA-specific include paths.
A list of include path strings.
Verifies that the given compiler is ABI-compatible with PyTorch.
compiler (str) – The compiler executable name to check (e.g. g++). Must be executable in a shell process.
False if the compiler is (likely) ABI-incompatible with PyTorch, else True.
Raises RuntimeError if ninja build system is not available on the system, does nothing otherwise.
Returns True if the ninja build system is available on the system, False otherwise.


A custom setuptools build extension .
This setuptools.build_ext subclass takes care of passing the minimum required compiler flags (e.g. -std=c++14) as well as mixed C++/CUDA compilation (and support for CUDA files in general).
When using BuildExtension, it is allowed to supply a dictionary for extra_compile_args (rather than the usual list) that maps from languages (cxx or nvcc) to a list of additional compiler flags to supply to the compiler. This makes it possible to supply different flags to the C++ and CUDA compiler during mixed compilation.
use_ninja (bool): If use_ninja is True (default), then we attempt to build using the Ninja backend. Ninja greatly speeds up compilation compared to the standard setuptools.build_ext. Fallbacks to the standard distutils backend if Ninja is not available.
Note
By default, the Ninja backend uses #CPUS + 2 workers to build the extension. This may use up too many resources on some systems. One can control the number of workers by setting the MAX_JOBS environment variable to a non-negative number.


Verifies that the given compiler is ABI-compatible with PyTorch.
compiler (str) – The compiler executable name to check (e.g. g++). Must be executable in a shell process.
False if the compiler is (likely) ABI-incompatible with PyTorch, else True.


Creates a setuptools.Extension for C++.
Convenience method that creates a setuptools.Extension with the bare minimum (but often sufficient) arguments to build a C++ extension.
All arguments are forwarded to the setuptools.Extension constructor.


Creates a setuptools.Extension for CUDA/C++.
Convenience method that creates a setuptools.Extension with the bare minimum (but often sufficient) arguments to build a CUDA/C++ extension. This includes the CUDA include path, library path and runtime library.
All arguments are forwarded to the setuptools.Extension constructor.
Compute capabilities:
By default the extension will be compiled to run on all archs of the cards visible during the building process of the extension, plus PTX. If down the road a new card is installed the extension may need to be recompiled. If a visible card has a compute capability (CC) that’s newer than the newest version for which your nvcc can build fully-compiled binaries, Pytorch will make nvcc fall back to building kernels with the newest version of PTX your nvcc does support (see below for details on PTX).
You can override the default behavior using TORCH_CUDA_ARCH_LIST to explicitly specify which CCs you want the extension to support:
TORCH_CUDA_ARCH_LIST=”6.1 8.6” python build_my_extension.py TORCH_CUDA_ARCH_LIST=”5.2 6.0 6.1 7.0 7.5 8.0 8.6+PTX” python build_my_extension.py
The +PTX option causes extension kernel binaries to include PTX instructions for the specified CC. PTX is an intermediate representation that allows kernels to runtime-compile for any CC >= the specified CC (for example, 8.6+PTX generates PTX that can runtime-compile for any GPU with CC >= 8.6). This improves your binary’s forward compatibility. However, relying on older PTX to provide forward compat by runtime-compiling for newer CCs can modestly reduce performance on those newer CCs. If you know exact CC(s) of the GPUs you want to target, you’re always better off specifying them individually. For example, if you want your extension to run on 8.0 and 8.6, “8.0+PTX” would work functionally because it includes PTX that can runtime-compile for 8.6, but “8.0 8.6” would be better.
Note that while it’s possible to include all supported archs, the more archs get included the slower the building process will be, as it will build a separate kernel image for each arch.


Get the include paths required to build a C++ or CUDA extension.
cuda – If True, includes CUDA-specific include paths.
A list of include path strings.


Returns True if the ninja build system is available on the system, False otherwise.


Loads a PyTorch C++ extension just-in-time (JIT).
To load an extension, a Ninja build file is emitted, which is used to compile the given sources into a dynamic library. This library is subsequently loaded into the current Python process as a module and returned from this function, ready for use.
By default, the directory to which the build file is emitted and the resulting library compiled to is <tmp>/torch_extensions/<name>, where <tmp> is the temporary folder on the current platform and <name> the name of the extension. This location can be overridden in two ways. First, if the TORCH_EXTENSIONS_DIR environment variable is set, it replaces <tmp>/torch_extensions and all extensions will be compiled into subfolders of this directory. Second, if the build_directory argument to this function is supplied, it overrides the entire path, i.e. the library will be compiled into that folder directly.
To compile the sources, the default system compiler (c++) is used, which can be overridden by setting the CXX environment variable. To pass additional arguments to the compilation process, extra_cflags or extra_ldflags can be provided. For example, to compile your extension with optimizations, pass extra_cflags=['-O3']. You can also use extra_cflags to pass further include directories.
CUDA support with mixed compilation is provided. Simply pass CUDA source files (.cu or .cuh) along with other sources. Such files will be detected and compiled with nvcc rather than the C++ compiler. This includes passing the CUDA lib64 directory as a library directory, and linking cudart. You can pass additional flags to nvcc via extra_cuda_cflags, just like with extra_cflags for C++. Various heuristics for finding the CUDA install directory are used, which usually work fine. If not, setting the CUDA_HOME environment variable is the safest option.
Returns the loaded PyTorch extension as a Python module.
Returns nothing. (The shared library is loaded into the process as a side effect.)
Return the path to the executable. (On Windows, TORCH_LIB_PATH is added to the PATH environment variable as a side effect.)
If is_python_module is True


Loads a PyTorch C++ extension just-in-time (JIT) from string sources.
This function behaves exactly like load(), but takes its sources as strings rather than filenames. These strings are stored to files in the build directory, after which the behavior of load_inline() is identical to load().
See the tests for good examples of using this function.
Sources may omit two required parts of a typical non-inline C++ extension: the necessary header includes, as well as the (pybind11) binding code. More precisely, strings passed to cpp_sources are first concatenated into a single .cpp file. This file is then prepended with #include
<torch/extension.h>.
Furthermore, if the functions argument is supplied, bindings will be automatically generated for each function specified. functions can either be a list of function names, or a dictionary mapping from function names to docstrings. If a list is given, the name of each function is used as its docstring.
The sources in cuda_sources are concatenated into a separate .cu file and prepended with torch/types.h, cuda.h and cuda_runtime.h includes. The .cpp and .cu files are compiled separately, but ultimately linked into a single library. Note that no bindings are generated for functions in cuda_sources per se. To bind to a CUDA kernel, you must create a C++ function that calls it, and either declare or define this C++ function in one of the cpp_sources (and include its name in functions).
See load() for a description of arguments omitted below.
Note
By default, the Ninja backend uses #CPUS + 2 workers to build the extension. This may use up too many resources on some systems. One can control the number of workers by setting the MAX_JOBS environment variable to a non-negative number.


Raises RuntimeError if ninja build system is not available on the system, does nothing otherwise.


At the heart of PyTorch data loading utility is the torch.utils.data.DataLoader class. It represents a Python iterable over a dataset, with support for
These options are configured by the constructor arguments of a DataLoader, which has signature:
The sections below describe in details the effects and usages of these options.
The most important argument of DataLoader constructor is dataset, which indicates a dataset object to load data from. PyTorch supports two different types of datasets:
A map-style dataset is one that implements the __getitem__() and __len__() protocols, and represents a map from (possibly non-integral) indices/keys to data samples.
For example, such a dataset, when accessed with dataset[idx], could read the idx-th image and its corresponding label from a folder on the disk.
See Dataset for more details.
An iterable-style dataset is an instance of a subclass of IterableDataset that implements the __iter__() protocol, and represents an iterable over data samples. This type of datasets is particularly suitable for cases where random reads are expensive or even improbable, and where the batch size depends on the fetched data.
For example, such a dataset, when called iter(dataset), could return a stream of data reading from a database, a remote server, or even logs generated in real time.
See IterableDataset for more details.
Note
When using an IterableDataset with multi-process data loading. The same dataset object is replicated on each worker process, and thus the replicas must be configured differently to avoid duplicated data. See IterableDataset documentations for how to achieve this.
For iterable-style datasets, data loading order is entirely controlled by the user-defined iterable. This allows easier implementations of chunk-reading and dynamic batch size (e.g., by yielding a batched sample at each time).
The rest of this section concerns the case with map-style datasets. torch.utils.data.Sampler classes are used to specify the sequence of indices/keys used in data loading. They represent iterable objects over the indices to datasets. E.g., in the common case with stochastic gradient decent (SGD), a Sampler could randomly permute a list of indices and yield each one at a time, or yield a small number of them for mini-batch SGD.
A sequential or shuffled sampler will be automatically constructed based on the shuffle argument to a DataLoader. Alternatively, users may use the sampler argument to specify a custom Sampler object that at each time yields the next index/key to fetch.
A custom Sampler that yields a list of batch indices at a time can be passed as the batch_sampler argument. Automatic batching can also be enabled via batch_size and drop_last arguments. See the next section for more details on this.
Note
Neither sampler nor batch_sampler is compatible with iterable-style datasets, since such datasets have no notion of a key or an index.
DataLoader supports automatically collating individual fetched data samples into batches via arguments batch_size, drop_last, and batch_sampler.
This is the most common case, and corresponds to fetching a minibatch of data and collating them into batched samples, i.e., containing Tensors with one dimension being the batch dimension (usually the first).
When batch_size (default 1) is not None, the data loader yields batched samples instead of individual samples. batch_size and drop_last arguments are used to specify how the data loader obtains batches of dataset keys. For map-style datasets, users can alternatively specify batch_sampler, which yields a list of keys at a time.
Note
The batch_size and drop_last arguments essentially are used to construct a batch_sampler from sampler. For map-style datasets, the sampler is either provided by user or constructed based on the shuffle argument. For iterable-style datasets, the sampler is a dummy infinite one. See this section on more details on samplers.
Note
When fetching from iterable-style datasets with multi-processing, the drop_last argument drops the last non-full batch of each worker’s dataset replica.
After fetching a list of samples using the indices from sampler, the function passed as the collate_fn argument is used to collate lists of samples into batches.
In this case, loading from a map-style dataset is roughly equivalent with:
and loading from an iterable-style dataset is roughly equivalent with:
A custom collate_fn can be used to customize collation, e.g., padding sequential data to max length of a batch. See this section on more about collate_fn.
In certain cases, users may want to handle batching manually in dataset code, or simply load individual samples. For example, it could be cheaper to directly load batched data (e.g., bulk reads from a database or reading continuous chunks of memory), or the batch size is data dependent, or the program is designed to work on individual samples. Under these scenarios, it’s likely better to not use automatic batching (where collate_fn is used to collate the samples), but let the data loader directly return each member of the dataset object.
When both batch_size and batch_sampler are None (default value for batch_sampler is already None), automatic batching is disabled. Each sample obtained from the dataset is processed with the function passed as the collate_fn argument.
When automatic batching is disabled, the default collate_fn simply converts NumPy arrays into PyTorch Tensors, and keeps everything else untouched.
In this case, loading from a map-style dataset is roughly equivalent with:
and loading from an iterable-style dataset is roughly equivalent with:
See this section on more about collate_fn.
The use of collate_fn is slightly different when automatic batching is enabled or disabled.
When automatic batching is disabled, collate_fn is called with each individual data sample, and the output is yielded from the data loader iterator. In this case, the default collate_fn simply converts NumPy arrays in PyTorch tensors.
When automatic batching is enabled, collate_fn is called with a list of data samples at each time. It is expected to collate the input samples into a batch for yielding from the data loader iterator. The rest of this section describes behavior of the default collate_fn in this case.
For instance, if each data sample consists of a 3-channel image and an integral class label, i.e., each element of the dataset returns a tuple (image, class_index), the default collate_fn collates a list of such tuples into a single tuple of a batched image tensor and a batched class label Tensor. In particular, the default collate_fn has the following properties:
Users may use customized collate_fn to achieve custom batching, e.g., collating along a dimension other than the first, padding sequences of various lengths, or adding support for custom data types.
A DataLoader uses single-process data loading by default.
Within a Python process, the Global Interpreter Lock (GIL) prevents true fully parallelizing Python code across threads. To avoid blocking computation code with data loading, PyTorch provides an easy switch to perform multi-process data loading by simply setting the argument num_workers to a positive integer.
In this mode, data fetching is done in the same process a DataLoader is initialized. Therefore, data loading may block computing. However, this mode may be preferred when resource(s) used for sharing data among processes (e.g., shared memory, file descriptors) is limited, or when the entire dataset is small and can be loaded entirely in memory. Additionally, single-process loading often shows more readable error traces and thus is useful for debugging.
Setting the argument num_workers as a positive integer will turn on multi-process data loading with the specified number of loader worker processes.
In this mode, each time an iterator of a DataLoader is created (e.g., when you call enumerate(dataloader)), num_workers worker processes are created. At this point, the dataset, collate_fn, and worker_init_fn are passed to each worker, where they are used to initialize, and fetch data. This means that dataset access together with its internal IO, transforms (including collate_fn) runs in the worker process.
torch.utils.data.get_worker_info() returns various useful information in a worker process (including the worker id, dataset replica, initial seed, etc.), and returns None in main process. Users may use this function in dataset code and/or worker_init_fn to individually configure each dataset replica, and to determine whether the code is running in a worker process. For example, this can be particularly helpful in sharding the dataset.
For map-style datasets, the main process generates the indices using sampler and sends them to the workers. So any shuffle randomization is done in the main process which guides loading by assigning indices to load.
For iterable-style datasets, since each worker process gets a replica of the dataset object, naive multi-process loading will often result in duplicated data. Using torch.utils.data.get_worker_info() and/or worker_init_fn, users may configure each replica independently. (See IterableDataset documentations for how to achieve this. ) For similar reasons, in multi-process loading, the drop_last argument drops the last non-full batch of each worker’s iterable-style dataset replica.
Workers are shut down once the end of the iteration is reached, or when the iterator becomes garbage collected.
Warning
It is generally not recommended to return CUDA tensors in multi-process loading because of many subtleties in using CUDA and sharing CUDA tensors in multiprocessing (see CUDA in multiprocessing). Instead, we recommend using automatic memory pinning (i.e., setting pin_memory=True), which enables fast data transfer to CUDA-enabled GPUs.
Since workers rely on Python multiprocessing, worker launch behavior is different on Windows compared to Unix.
This separate serialization means that you should take two steps to ensure you are compatible with Windows while using multi-process data loading:
By default, each worker will have its PyTorch seed set to base_seed + worker_id, where base_seed is a long generated by main process using its RNG (thereby, consuming a RNG state mandatorily). However, seeds for other libraries may be duplicated upon initializing workers (e.g., NumPy), causing each worker to return identical random numbers. (See this section in FAQ.).
In worker_init_fn, you may access the PyTorch seed set for each worker with either torch.utils.data.get_worker_info().seed or torch.initial_seed(), and use it to seed other libraries before data loading.
Host to GPU copies are much faster when they originate from pinned (page-locked) memory. See Use pinned memory buffers for more details on when and how to use pinned memory generally.
For data loading, passing pin_memory=True to a DataLoader will automatically put the fetched data Tensors in pinned memory, and thus enables faster data transfer to CUDA-enabled GPUs.
The default memory pinning logic only recognizes Tensors and maps and iterables containing Tensors. By default, if the pinning logic sees a batch that is a custom type (which will occur if you have a collate_fn that returns a custom batch type), or if each element of your batch is a custom type, the pinning logic will not recognize them, and it will return that batch (or those elements) without pinning the memory. To enable memory pinning for custom batch or data type(s), define a pin_memory() method on your custom type(s).
See the example below.
Example:
Data loader. Combines a dataset and a sampler, and provides an iterable over the given dataset.
The DataLoader supports both map-style and iterable-style datasets with single- or multi-process loading, customizing loading order and optional automatic batching (collation) and memory pinning.
See torch.utils.data documentation page for more details.
Warning
If the spawn start method is used, worker_init_fn cannot be an unpicklable object, e.g., a lambda function. See Multiprocessing best practices on more details related to multiprocessing in PyTorch.
Warning
len(dataloader) heuristic is based on the length of the sampler used. When dataset is an IterableDataset, it instead returns an estimate based on len(dataset) / batch_size, with proper rounding depending on drop_last, regardless of multi-process loading configurations. This represents the best guess PyTorch can make because PyTorch trusts user dataset code in correctly handling multi-process loading to avoid duplicate data.
However, if sharding results in multiple workers having incomplete last batches, this estimate can still be inaccurate, because (1) an otherwise complete batch can be broken into multiple ones and (2) more than one batch worth of samples can be dropped when drop_last is set. Unfortunately, PyTorch can not detect such cases in general.
See Dataset Types for more details on these two types of datasets and how IterableDataset interacts with Multi-process data loading.
Warning
See Reproducibility, and My data loader workers return identical random numbers, and Randomness in multi-process data loading notes for random seed related questions.
An abstract class representing a Dataset.
All datasets that represent a map from keys to data samples should subclass it. All subclasses should overwrite __getitem__(), supporting fetching a data sample for a given key. Subclasses could also optionally overwrite __len__(), which is expected to return the size of the dataset by many Sampler implementations and the default options of DataLoader.
Note
DataLoader by default constructs a index sampler that yields integral indices. To make it work with a map-style dataset with non-integral indices/keys, a custom sampler must be provided.
An iterable Dataset.
All datasets that represent an iterable of data samples should subclass it. Such form of datasets is particularly useful when data come from a stream.
All subclasses should overwrite __iter__(), which would return an iterator of samples in this dataset.
When a subclass is used with DataLoader, each item in the dataset will be yielded from the DataLoader iterator. When num_workers > 0, each worker process will have a different copy of the dataset object, so it is often desired to configure each copy independently to avoid having duplicate data returned from the workers. get_worker_info(), when called in a worker process, returns information about the worker. It can be used in either the dataset’s __iter__() method or the DataLoader ‘s worker_init_fn option to modify each copy’s behavior.
Example 1: splitting workload across all workers in __iter__():
Example 2: splitting workload across all workers using worker_init_fn:
Dataset wrapping tensors.
Each sample will be retrieved by indexing tensors along the first dimension.
*tensors (Tensor) – tensors that have the same size of the first dimension.
Dataset as a concatenation of multiple datasets.
This class is useful to assemble different existing datasets.
datasets (sequence) – List of datasets to be concatenated
Dataset for chainning multiple IterableDataset s.
This class is useful to assemble different existing dataset streams. The chainning operation is done on-the-fly, so concatenating large-scale datasets with this class will be efficient.
datasets (iterable of IterableDataset) – datasets to be chained together
Dataset shuffled from the original dataset.
This class is useful to shuffle an existing instance of an IterableDataset. The buffer with buffer_size is filled with the items from the dataset first. Then, each item will be yielded from the buffer by reservoir sampling via iterator.
buffer_size is required to be larger than 0. For buffer_size == 1, the dataset is not shuffled. In order to fully shuffle the whole dataset, buffer_size is required to be greater than or equal to the size of dataset.
When it is used with DataLoader, each item in the dataset will be yielded from the DataLoader iterator. And, the method to set up a random seed is different based on num_workers.
For single-process mode (num_workers == 0), the random seed is required to be set before the DataLoader in the main process.
For multi-process mode (num_workers > 0), the random seed is set by a callable function in each worker.
Subset of a dataset at specified indices.
Returns the information about the current DataLoader iterator worker process.
When called in a worker, this returns an object guaranteed to have the following attributes:
When called in the main process, this returns None.
Note
When used in a worker_init_fn passed over to DataLoader, this method can be useful to set up each worker process differently, for instance, using worker_id to configure the dataset object to only read a specific fraction of a sharded dataset, or use seed to seed other libraries used in dataset code (e.g., NumPy).
Randomly split a dataset into non-overlapping new datasets of given lengths. Optionally fix the generator for reproducible results, e.g.:
Base class for all Samplers.
Every Sampler subclass has to provide an __iter__() method, providing a way to iterate over indices of dataset elements, and a __len__() method that returns the length of the returned iterators.
Note
The __len__() method isn’t strictly required by DataLoader, but is expected in any calculation involving the length of a DataLoader.
Samples elements sequentially, always in the same order.
data_source (Dataset) – dataset to sample from
Samples elements randomly. If without replacement, then sample from a shuffled dataset. If with replacement, then user can specify num_samples to draw.
Samples elements randomly from a given list of indices, without replacement.
Samples elements from [0,..,len(weights)-1] with given probabilities (weights).
Wraps another sampler to yield a mini-batch of indices.
Sampler that restricts data loading to a subset of the dataset.
It is especially useful in conjunction with torch.nn.parallel.DistributedDataParallel. In such a case, each process can pass a DistributedSampler instance as a DataLoader sampler, and load a subset of the original dataset that is exclusive to it.
Note
Dataset is assumed to be of constant size.
Warning
In distributed mode, calling the set_epoch() method at the beginning of each epoch before creating the DataLoader iterator is necessary to make shuffling work properly across multiple epochs. Otherwise, the same ordering will be always used.
Example:


Wraps another sampler to yield a mini-batch of indices.


Dataset shuffled from the original dataset.
This class is useful to shuffle an existing instance of an IterableDataset. The buffer with buffer_size is filled with the items from the dataset first. Then, each item will be yielded from the buffer by reservoir sampling via iterator.
buffer_size is required to be larger than 0. For buffer_size == 1, the dataset is not shuffled. In order to fully shuffle the whole dataset, buffer_size is required to be greater than or equal to the size of dataset.
When it is used with DataLoader, each item in the dataset will be yielded from the DataLoader iterator. And, the method to set up a random seed is different based on num_workers.
For single-process mode (num_workers == 0), the random seed is required to be set before the DataLoader in the main process.
For multi-process mode (num_workers > 0), the random seed is set by a callable function in each worker.


Dataset for chainning multiple IterableDataset s.
This class is useful to assemble different existing dataset streams. The chainning operation is done on-the-fly, so concatenating large-scale datasets with this class will be efficient.
datasets (iterable of IterableDataset) – datasets to be chained together


Dataset as a concatenation of multiple datasets.
This class is useful to assemble different existing datasets.
datasets (sequence) – List of datasets to be concatenated


Data loader. Combines a dataset and a sampler, and provides an iterable over the given dataset.
The DataLoader supports both map-style and iterable-style datasets with single- or multi-process loading, customizing loading order and optional automatic batching (collation) and memory pinning.
See torch.utils.data documentation page for more details.
Warning
If the spawn start method is used, worker_init_fn cannot be an unpicklable object, e.g., a lambda function. See Multiprocessing best practices on more details related to multiprocessing in PyTorch.
Warning
len(dataloader) heuristic is based on the length of the sampler used. When dataset is an IterableDataset, it instead returns an estimate based on len(dataset) / batch_size, with proper rounding depending on drop_last, regardless of multi-process loading configurations. This represents the best guess PyTorch can make because PyTorch trusts user dataset code in correctly handling multi-process loading to avoid duplicate data.
However, if sharding results in multiple workers having incomplete last batches, this estimate can still be inaccurate, because (1) an otherwise complete batch can be broken into multiple ones and (2) more than one batch worth of samples can be dropped when drop_last is set. Unfortunately, PyTorch can not detect such cases in general.
See Dataset Types for more details on these two types of datasets and how IterableDataset interacts with Multi-process data loading.
Warning
See Reproducibility, and My data loader workers return identical random numbers, and Randomness in multi-process data loading notes for random seed related questions.


An abstract class representing a Dataset.
All datasets that represent a map from keys to data samples should subclass it. All subclasses should overwrite __getitem__(), supporting fetching a data sample for a given key. Subclasses could also optionally overwrite __len__(), which is expected to return the size of the dataset by many Sampler implementations and the default options of DataLoader.
Note
DataLoader by default constructs a index sampler that yields integral indices. To make it work with a map-style dataset with non-integral indices/keys, a custom sampler must be provided.


Sampler that restricts data loading to a subset of the dataset.
It is especially useful in conjunction with torch.nn.parallel.DistributedDataParallel. In such a case, each process can pass a DistributedSampler instance as a DataLoader sampler, and load a subset of the original dataset that is exclusive to it.
Note
Dataset is assumed to be of constant size.
Warning
In distributed mode, calling the set_epoch() method at the beginning of each epoch before creating the DataLoader iterator is necessary to make shuffling work properly across multiple epochs. Otherwise, the same ordering will be always used.
Example:


Returns the information about the current DataLoader iterator worker process.
When called in a worker, this returns an object guaranteed to have the following attributes:
When called in the main process, this returns None.
Note
When used in a worker_init_fn passed over to DataLoader, this method can be useful to set up each worker process differently, for instance, using worker_id to configure the dataset object to only read a specific fraction of a sharded dataset, or use seed to seed other libraries used in dataset code (e.g., NumPy).


An iterable Dataset.
All datasets that represent an iterable of data samples should subclass it. Such form of datasets is particularly useful when data come from a stream.
All subclasses should overwrite __iter__(), which would return an iterator of samples in this dataset.
When a subclass is used with DataLoader, each item in the dataset will be yielded from the DataLoader iterator. When num_workers > 0, each worker process will have a different copy of the dataset object, so it is often desired to configure each copy independently to avoid having duplicate data returned from the workers. get_worker_info(), when called in a worker process, returns information about the worker. It can be used in either the dataset’s __iter__() method or the DataLoader ‘s worker_init_fn option to modify each copy’s behavior.
Example 1: splitting workload across all workers in __iter__():
Example 2: splitting workload across all workers using worker_init_fn:


Samples elements randomly. If without replacement, then sample from a shuffled dataset. If with replacement, then user can specify num_samples to draw.


Randomly split a dataset into non-overlapping new datasets of given lengths. Optionally fix the generator for reproducible results, e.g.:


Base class for all Samplers.
Every Sampler subclass has to provide an __iter__() method, providing a way to iterate over indices of dataset elements, and a __len__() method that returns the length of the returned iterators.
Note
The __len__() method isn’t strictly required by DataLoader, but is expected in any calculation involving the length of a DataLoader.


Samples elements sequentially, always in the same order.
data_source (Dataset) – dataset to sample from


Subset of a dataset at specified indices.


Samples elements randomly from a given list of indices, without replacement.


Dataset wrapping tensors.
Each sample will be retrieved by indexing tensors along the first dimension.
*tensors (Tensor) – tensors that have the same size of the first dimension.


Samples elements from [0,..,len(weights)-1] with given probabilities (weights).


Decodes a DLPack to a tensor.
dlpack – a PyCapsule object with the dltensor
The tensor will share the memory with the object represented in the dlpack. Note that each dlpack can only be consumed once.
Returns a DLPack representing the tensor.
tensor – a tensor to be exported
The dlpack shares the tensors memory. Note that each dlpack can only be consumed once.


Decodes a DLPack to a tensor.
dlpack – a PyCapsule object with the dltensor
The tensor will share the memory with the object represented in the dlpack. Note that each dlpack can only be consumed once.


Returns a DLPack representing the tensor.
tensor – a tensor to be exported
The dlpack shares the tensors memory. Note that each dlpack can only be consumed once.


Warning
This API is in beta and may change in the near future.
Torch mobile supports torch.mobile_optimizer.optimize_for_mobile utility to run a list of optimization pass with modules in eval mode. The method takes the following parameters: a torch.jit.ScriptModule object, a blocklisting optimization set and a preserved method list
optimize_for_mobile will also invoke freeze_module pass which only preserves forward method. If you have other method to that needed to be preserved, add them into the preserved method list and pass into the method.
A new optimized torch script module


Moved to torch.hub.
Loads the Torch serialized object at the given URL.
If downloaded file is a zip file, it will be automatically decompressed.
If the object is already present in model_dir, it’s deserialized and returned. The default value of model_dir is <hub_dir>/checkpoints where hub_dir is the directory returned by get_dir().


Loads the Torch serialized object at the given URL.
If downloaded file is a zip file, it will be automatically decompressed.
If the object is already present in model_dir, it’s deserialized and returned. The default value of model_dir is <hub_dir>/checkpoints where hub_dir is the directory returned by get_dir().


Before going further, more details on TensorBoard can be found at https://www.tensorflow.org/tensorboard/
Once you’ve installed TensorBoard, these utilities let you log PyTorch models and metrics into a directory for visualization within the TensorBoard UI. Scalars, images, histograms, graphs, and embedding visualizations are all supported for PyTorch models and tensors as well as Caffe2 nets and blobs.
The SummaryWriter class is your main entry to log data for consumption and visualization by TensorBoard. For example:
This can then be visualized with TensorBoard, which should be installable and runnable with:
Lots of information can be logged for one experiment. To avoid cluttering the UI and have better result clustering, we can group plots by naming them hierarchically. For example, “Loss/train” and “Loss/test” will be grouped together, while “Accuracy/train” and “Accuracy/test” will be grouped separately in the TensorBoard interface.
Expected result:
Writes entries directly to event files in the log_dir to be consumed by TensorBoard.
The SummaryWriter class provides a high-level API to create an event file in a given directory and add summaries and events to it. The class updates the file contents asynchronously. This allows a training program to call methods to add data to the file directly from the training loop, without slowing down training.
Creates a SummaryWriter that will write out events and summaries to the event file.
Examples:
Add scalar data to summary.
Examples:
Expected result:
Adds many scalar data to summary.
Examples:
Expected result:
Add histogram to summary.
Examples:
Expected result:
Add image data to summary.
Note that this requires the pillow package.
img_tensor: Default is (3,H,W)(3, H, W) . You can use torchvision.utils.make_grid() to convert a batch of tensor into 3xHxW format or call add_images and let us do the job. Tensor with (1,H,W)(1, H, W) , (H,W)(H, W) , (H,W,3)(H, W, 3)  is also suitable as long as corresponding dataformats argument is passed, e.g. CHW, HWC, HW.
Examples:
Expected result:
Add batched image data to summary.
Note that this requires the pillow package.
img_tensor: Default is (N,3,H,W)(N, 3, H, W) . If dataformats is specified, other shape will be accepted. e.g. NCHW or NHWC.
Examples:
Expected result:
Render matplotlib figure into an image and add it to summary.
Note that this requires the matplotlib package.
Add video data to summary.
Note that this requires the moviepy package.
vid_tensor: (N,T,C,H,W)(N, T, C, H, W) . The values should lie in [0, 255] for type uint8 or [0, 1] for type float.
Add audio data to summary.
snd_tensor: (1,L)(1, L) . The values should lie between [-1, 1].
Add text data to summary.
Examples:
Add graph data to summary.
Add embedding projector data to summary.
mat: (N,D)(N, D) , where N is number of data and D is feature dimension
label_img: (N,C,H,W)(N, C, H, W)
Examples:
Adds precision recall curve. Plotting a precision-recall curve lets you understand your model’s performance under different threshold settings. With this function, you provide the ground truth labeling (T/F) and prediction confidence (usually the output of your model) for each target. The TensorBoard UI will let you choose the threshold interactively.
Examples:
Create special chart by collecting charts tags in ‘scalars’. Note that this function can only be called once for each SummaryWriter() object. Because it only provides metadata to tensorboard, the function can be called before or after the training loop.
layout (dict) – {categoryName: charts}, where charts is also a dictionary {chartName: ListOfProperties}. The first element in ListOfProperties is the chart’s type (one of Multiline or Margin) and the second element should be a list containing the tags you have used in add_scalar function, which will be collected into the new chart.
Examples:
Add meshes or 3D point clouds to TensorBoard. The visualization is based on Three.js, so it allows users to interact with the rendered object. Besides the basic definitions such as vertices, faces, users can further provide camera parameter, lighting condition, etc. Please check https://threejs.org/docs/index.html#manual/en/introduction/Creating-a-scene for advanced usage.
vertices: (B,N,3)(B, N, 3) . (batch, number_of_vertices, channels)
colors: (B,N,3)(B, N, 3) . The values should lie in [0, 255] for type uint8 or [0, 1] for type float.
faces: (B,N,3)(B, N, 3) . The values should lie in [0, number_of_vertices] for type uint8.
Examples:
Add a set of hyperparameters to be compared in TensorBoard.
Examples:
Expected result:
Flushes the event file to disk. Call this method to make sure that all pending events have been written to disk.


Writes entries directly to event files in the log_dir to be consumed by TensorBoard.
The SummaryWriter class provides a high-level API to create an event file in a given directory and add summaries and events to it. The class updates the file contents asynchronously. This allows a training program to call methods to add data to the file directly from the training loop, without slowing down training.
Creates a SummaryWriter that will write out events and summaries to the event file.
Examples:
Add scalar data to summary.
Examples:
Expected result:
Adds many scalar data to summary.
Examples:
Expected result:
Add histogram to summary.
Examples:
Expected result:
Add image data to summary.
Note that this requires the pillow package.
img_tensor: Default is (3,H,W)(3, H, W) . You can use torchvision.utils.make_grid() to convert a batch of tensor into 3xHxW format or call add_images and let us do the job. Tensor with (1,H,W)(1, H, W) , (H,W)(H, W) , (H,W,3)(H, W, 3)  is also suitable as long as corresponding dataformats argument is passed, e.g. CHW, HWC, HW.
Examples:
Expected result:
Add batched image data to summary.
Note that this requires the pillow package.
img_tensor: Default is (N,3,H,W)(N, 3, H, W) . If dataformats is specified, other shape will be accepted. e.g. NCHW or NHWC.
Examples:
Expected result:
Render matplotlib figure into an image and add it to summary.
Note that this requires the matplotlib package.
Add video data to summary.
Note that this requires the moviepy package.
vid_tensor: (N,T,C,H,W)(N, T, C, H, W) . The values should lie in [0, 255] for type uint8 or [0, 1] for type float.
Add audio data to summary.
snd_tensor: (1,L)(1, L) . The values should lie between [-1, 1].
Add text data to summary.
Examples:
Add graph data to summary.
Add embedding projector data to summary.
mat: (N,D)(N, D) , where N is number of data and D is feature dimension
label_img: (N,C,H,W)(N, C, H, W)
Examples:
Adds precision recall curve. Plotting a precision-recall curve lets you understand your model’s performance under different threshold settings. With this function, you provide the ground truth labeling (T/F) and prediction confidence (usually the output of your model) for each target. The TensorBoard UI will let you choose the threshold interactively.
Examples:
Create special chart by collecting charts tags in ‘scalars’. Note that this function can only be called once for each SummaryWriter() object. Because it only provides metadata to tensorboard, the function can be called before or after the training loop.
layout (dict) – {categoryName: charts}, where charts is also a dictionary {chartName: ListOfProperties}. The first element in ListOfProperties is the chart’s type (one of Multiline or Margin) and the second element should be a list containing the tags you have used in add_scalar function, which will be collected into the new chart.
Examples:
Add meshes or 3D point clouds to TensorBoard. The visualization is based on Three.js, so it allows users to interact with the rendered object. Besides the basic definitions such as vertices, faces, users can further provide camera parameter, lighting condition, etc. Please check https://threejs.org/docs/index.html#manual/en/introduction/Creating-a-scene for advanced usage.
vertices: (B,N,3)(B, N, 3) . (batch, number_of_vertices, channels)
colors: (B,N,3)(B, N, 3) . The values should lie in [0, 255] for type uint8 or [0, 1] for type float.
faces: (B,N,3)(B, N, 3) . The values should lie in [0, number_of_vertices] for type uint8.
Examples:
Add a set of hyperparameters to be compared in TensorBoard.
Examples:
Expected result:
Flushes the event file to disk. Call this method to make sure that all pending events have been written to disk.


Add audio data to summary.
snd_tensor: (1,L)(1, L) . The values should lie between [-1, 1].


Create special chart by collecting charts tags in ‘scalars’. Note that this function can only be called once for each SummaryWriter() object. Because it only provides metadata to tensorboard, the function can be called before or after the training loop.
layout (dict) – {categoryName: charts}, where charts is also a dictionary {chartName: ListOfProperties}. The first element in ListOfProperties is the chart’s type (one of Multiline or Margin) and the second element should be a list containing the tags you have used in add_scalar function, which will be collected into the new chart.
Examples:


Add embedding projector data to summary.
mat: (N,D)(N, D) , where N is number of data and D is feature dimension
label_img: (N,C,H,W)(N, C, H, W)
Examples:


Render matplotlib figure into an image and add it to summary.
Note that this requires the matplotlib package.


Add histogram to summary.
Examples:
Expected result:


Add a set of hyperparameters to be compared in TensorBoard.
Examples:
Expected result:


Add image data to summary.
Note that this requires the pillow package.
img_tensor: Default is (3,H,W)(3, H, W) . You can use torchvision.utils.make_grid() to convert a batch of tensor into 3xHxW format or call add_images and let us do the job. Tensor with (1,H,W)(1, H, W) , (H,W)(H, W) , (H,W,3)(H, W, 3)  is also suitable as long as corresponding dataformats argument is passed, e.g. CHW, HWC, HW.
Examples:
Expected result:


Add batched image data to summary.
Note that this requires the pillow package.
img_tensor: Default is (N,3,H,W)(N, 3, H, W) . If dataformats is specified, other shape will be accepted. e.g. NCHW or NHWC.
Examples:
Expected result:


Add meshes or 3D point clouds to TensorBoard. The visualization is based on Three.js, so it allows users to interact with the rendered object. Besides the basic definitions such as vertices, faces, users can further provide camera parameter, lighting condition, etc. Please check https://threejs.org/docs/index.html#manual/en/introduction/Creating-a-scene for advanced usage.
vertices: (B,N,3)(B, N, 3) . (batch, number_of_vertices, channels)
colors: (B,N,3)(B, N, 3) . The values should lie in [0, 255] for type uint8 or [0, 1] for type float.
faces: (B,N,3)(B, N, 3) . The values should lie in [0, number_of_vertices] for type uint8.
Examples:


Adds precision recall curve. Plotting a precision-recall curve lets you understand your model’s performance under different threshold settings. With this function, you provide the ground truth labeling (T/F) and prediction confidence (usually the output of your model) for each target. The TensorBoard UI will let you choose the threshold interactively.
Examples:


Add scalar data to summary.
Examples:
Expected result:


Adds many scalar data to summary.
Examples:
Expected result:


Add video data to summary.
Note that this requires the moviepy package.
vid_tensor: (N,T,C,H,W)(N, T, C, H, W) . The values should lie in [0, 255] for type uint8 or [0, 1] for type float.


Flushes the event file to disk. Call this method to make sure that all pending events have been written to disk.


Creates a SummaryWriter that will write out events and summaries to the event file.
Examples:


Generates a Vandermonde matrix.
The columns of the output matrix are elementwise powers of the input vector x(N−1),x(N−2),...,x0x^{(N-1)}, x^{(N-2)}, ..., x^0 . If increasing is True, the order of the columns is reversed x0,x1,...,x(N−1)x^0, x^1, ..., x^{(N-1)} . Such a matrix with a geometric progression in each row is named for Alexandre-Theophile Vandermonde.
Vandermonde matrix. If increasing is False, the first column is x(N−1)x^{(N-1)} , the second x(N−2)x^{(N-2)}  and so forth. If increasing is True, the columns are x0,x1,...,x(N−1)x^0, x^1, ..., x^{(N-1)} .
Tensor
Example:


Returns the variance of all elements in the input tensor.
If unbiased is False, then the variance will be calculated via the biased estimator. Otherwise, Bessel’s correction will be used.
Example:
Returns the variance of each row of the input tensor in the given dimension dim.
If keepdim is True, the output tensor is of the same size as input except in the dimension(s) dim where it is of size 1. Otherwise, dim is squeezed (see torch.squeeze()), resulting in the output tensor having 1 (or len(dim)) fewer dimension(s).
If unbiased is False, then the variance will be calculated via the biased estimator. Otherwise, Bessel’s correction will be used.
out (Tensor, optional) – the output tensor.
Example:


Returns the variance and mean of all elements in the input tensor.
If unbiased is False, then the variance will be calculated via the biased estimator. Otherwise, Bessel’s correction will be used.
Example:
Returns the variance and mean of each row of the input tensor in the given dimension dim.
If keepdim is True, the output tensor is of the same size as input except in the dimension(s) dim where it is of size 1. Otherwise, dim is squeezed (see torch.squeeze()), resulting in the output tensor having 1 (or len(dim)) fewer dimension(s).
If unbiased is False, then the variance will be calculated via the biased estimator. Otherwise, Bessel’s correction will be used.
Example:


Computes the dot product of two 1D tensors. The vdot(a, b) function handles complex numbers differently than dot(a, b). If the first argument is complex, the complex conjugate of the first argument is used for the calculation of the dot product.
Note
Unlike NumPy’s vdot, torch.vdot intentionally only supports computing the dot product of two 1D tensors with the same number of elements.
out (Tensor, optional) – the output tensor.
Example:


Returns a view of input as a complex tensor. For an input complex tensor of size m1,m2,…,mi,2m1, m2, \dots, mi, 2 , this function returns a new complex tensor of size m1,m2,…,mim1, m2, \dots, mi  where the last dimension of the input tensor is expected to represent the real and imaginary components of complex numbers.
Warning
view_as_complex() is only supported for tensors with torch.dtype torch.float64 and torch.float32. The input is expected to have the last dimension of size 2. In addition, the tensor must have a stride of 1 for its last dimension. The strides of all other dimensions must be even numbers.
input (Tensor) – the input tensor.


Returns a view of input as a real tensor. For an input complex tensor of size m1,m2,…,mim1, m2, \dots, mi , this function returns a new real tensor of size m1,m2,…,mi,2m1, m2, \dots, mi, 2 , where the last dimension of size 2 represents the real and imaginary components of complex numbers.
Warning
view_as_real() is only supported for tensors with complex dtypes.
input (Tensor) – the input tensor.


Stack tensors in sequence vertically (row wise).
This is equivalent to concatenation along the first axis after all 1-D tensors have been reshaped by torch.atleast_2d().
tensors (sequence of Tensors) – sequence of tensors to concatenate
out (Tensor, optional) – the output tensor.
Example:


Return a tensor of elements selected from either x or y, depending on condition.
The operation is defined as:
Note
The tensors condition, x, y must be broadcastable.
Note
Currently valid scalar and tensor combination are 1. Scalar of floating dtype and torch.double 2. Scalar of integral dtype and torch.long 3. Scalar of complex dtype and torch.complex128
A tensor of shape equal to the broadcasted shape of condition, x, y
Tensor
Example:
torch.where(condition) is identical to torch.nonzero(condition, as_tuple=True).
Note
See also torch.nonzero().


Computes input * log(other) with the following cases.
Similar to SciPy’s scipy.special.xlogy.
Note
At least one of input or other must be a tensor.
out (Tensor, optional) – the output tensor.
Example:


Returns a tensor filled with the scalar value 0, with the shape defined by the variable argument size.
size (int...) – a sequence of integers defining the shape of the output tensor. Can be a variable number of arguments or a collection like a list or tuple.
Example:


Returns a tensor filled with the scalar value 0, with the same size as input. torch.zeros_like(input) is equivalent to torch.zeros(input.size(), dtype=input.dtype, layout=input.layout, device=input.device).
Warning
As of 0.4, this function does not support an out keyword. As an alternative, the old torch.zeros_like(input, out=output) is equivalent to torch.zeros(input.size(), out=output).
input (Tensor) – the size of input will determine size of the output tensor.
Example:


A wrapper around Python’s assert which is symbolically traceable.


Raises an HTTPException for the given status code or WSGI application.
If a status code is given, it will be looked up in the list of exceptions and will raise that exception. If passed a WSGI application, it will wrap it in a proxy WSGI exception and raise that:
NoReturn


When passed a dict of code -> exception items it can be used as callable that raises exceptions. If the first argument to the callable is an integer it will be looked up in the mapping, if it’s a WSGI application it will be raised in a proxy exception.
The rest of the arguments are forwarded to the exception constructor.
None


An Accept object is just a list subclass for lists of (value, quality) tuples. It is automatically sorted by specificity and quality.
All Accept objects work similar to a list but provide extra functionality for working with the data. Containment checks are normalized to the rules of that header:
To get the quality for an item you can use normal item lookup:
Changed in version 1.0.0: Accept internal values are no longer ordered alphabetically for equal quality tags. Instead the initial order is preserved.
Changed in version 0.5: Accept objects are forced immutable now.
The best match as value.
Returns the best match from a list of possible matches based on the specificity and quality of the client. If two items have the same quality and specificity, the one is returned that comes first.
Get the position of an entry or return -1.
key – The key to be looked up.
Get the position of an entry or raise ValueError.
key – The key to be looked up.
Changed in version 0.5: This used to raise IndexError, which was inconsistent with the list API.
Returns the quality of the key.
New in version 0.6: In previous versions you had to use the item-lookup syntax (eg: obj[key] instead of obj.quality(key))
Convert the header set into an HTTP header string.
Iterate over all values.


Returns the best match from a list of possible matches based on the specificity and quality of the client. If two items have the same quality and specificity, the one is returned that comes first.


Get the position of an entry or return -1.
key – The key to be looked up.


Get the position of an entry or raise ValueError.
key – The key to be looked up.
Changed in version 0.5: This used to raise IndexError, which was inconsistent with the list API.


Returns the quality of the key.
New in version 0.6: In previous versions you had to use the item-lookup syntax (eg: obj[key] instead of obj.quality(key))


Convert the header set into an HTTP header string.


Matches one of the items provided. Items can either be Python identifiers or strings:
None


Redirects to the same URL but with a slash appended. The behavior of this function is undefined if the path ends with a slash already.
Response


Represents an Authorization header sent by the client.
This is returned by parse_authorization_header(). It can be useful to create the object manually to pass to the test Client.
Changed in version 0.5: This object became immutable.
If the server sent a qop-header in the WWW-Authenticate header, the client has to provide this value for HTTP digest auth. See the RFC for more details.
The nonce count value transmitted by clients if a qop-header is also transmitted. HTTP digest auth only.
The nonce the server sent for digest auth, sent back by the client. A nonce should be unique for every 401 response for HTTP digest auth.
The opaque header from the server returned unchanged by the client. It is recommended that this string be base64 or hexadecimal data. Digest auth only.
When the authentication type is basic this is the password transmitted by the client, else None.
Indicates what “quality of protection” the client has applied to the message for HTTP digest auth. Note that this is a single token, not a quoted list of alternatives as in WWW-Authenticate.
This is the server realm sent back for HTTP digest auth.
A string of 32 hex digits computed as defined in RFC 2617, which proves that the user knows a password. Digest auth only.
Convert to a string value for an Authorization header.
New in version 2.0: Added to support passing authorization to the test client.
The URI from Request-URI of the Request-Line; duplicated because proxies are allowed to change the Request-Line in transit. HTTP digest auth only.
The username transmitted. This is set for both basic and digest auth all the time.


Convert to a string value for an Authorization header.
New in version 2.0: Added to support passing authorization to the test client.


Superclass of URL and BytesURL.
Create new instance of _URLTuple(scheme, netloc, path, query, fragment)
Works exactly like host but will return a result that is restricted to ASCII. If it finds a netloc that is not ASCII it will attempt to idna decode it. This is useful for socket operations when the URL might include internationalized characters.
The authentication part in the URL if available, None otherwise.
Decodes the netloc part into a string.
str
Decodes the query part of the URL. Ths is a shortcut for calling url_decode() on the query argument. The arguments and keyword arguments are forwarded to url_decode() unchanged.
ds.MultiDict[str, str]
Encodes the netloc part to an ASCII safe URL as bytes.
str
Returns a tuple with the location of the file in the form (server, location). If the netloc is empty in the URL or points to localhost, it’s represented as None.
The pathformat by default is autodetection but needs to be set when working with URLs of a specific system. The supported values are 'windows' when working with Windows or DOS paths and 'posix' when working with posix paths.
If the URL does not point to a local file, the server and location are both represented as None.
pathformat (Optional[str]) – The expected format of the path component. Currently 'windows' and 'posix' are supported. Defaults to None which is autodetect.
Tuple[Optional[str], Optional[str]]
The host part of the URL if available, otherwise None. The host is either the hostname or the IP address mentioned in the URL. It will not contain the port.
Joins this URL with another one. This is just a convenience function for calling into url_join() and then parsing the return value again.
werkzeug.urls.BaseURL
The password if it was part of the URL, None otherwise. This undergoes URL decoding and will always be a string.
The port in the URL as an integer if it was present, None otherwise. This does not fill in default ports.
The password if it was part of the URL, None otherwise. Unlike password this one is not being decoded.
The username if it was part of the URL, None otherwise. Unlike username this one is not being decoded.
Return an URL with the same values, except for those parameters given new values by whichever keyword arguments are specified.
kwargs (Any) –
werkzeug.urls.BaseURL
Returns a URL tuple that holds a IRI. This will try to decode as much information as possible in the URL without losing information similar to how a web browser does it for the URL bar.
It’s usually more interesting to directly call uri_to_iri() which will return a string.
werkzeug.urls.BaseURL
Returns a BytesURL tuple that holds a URI. This will encode all the information in the URL properly to ASCII using the rules a web browser would follow.
It’s usually more interesting to directly call iri_to_uri() which will return a string.
werkzeug.urls.BaseURL
Returns a URL string or bytes depending on the type of the information stored. This is just a convenience function for calling url_unparse() for this URL.
str
The username if it was part of the URL, None otherwise. This undergoes URL decoding and will always be a string.


Decodes the netloc part into a string.
str


Decodes the query part of the URL. Ths is a shortcut for calling url_decode() on the query argument. The arguments and keyword arguments are forwarded to url_decode() unchanged.
ds.MultiDict[str, str]


Encodes the netloc part to an ASCII safe URL as bytes.
str


Returns a tuple with the location of the file in the form (server, location). If the netloc is empty in the URL or points to localhost, it’s represented as None.
The pathformat by default is autodetection but needs to be set when working with URLs of a specific system. The supported values are 'windows' when working with Windows or DOS paths and 'posix' when working with posix paths.
If the URL does not point to a local file, the server and location are both represented as None.
pathformat (Optional[str]) – The expected format of the path component. Currently 'windows' and 'posix' are supported. Defaults to None which is autodetect.
Tuple[Optional[str], Optional[str]]


Joins this URL with another one. This is just a convenience function for calling into url_join() and then parsing the return value again.
werkzeug.urls.BaseURL


Return an URL with the same values, except for those parameters given new values by whichever keyword arguments are specified.
kwargs (Any) –
werkzeug.urls.BaseURL


Returns a URL tuple that holds a IRI. This will try to decode as much information as possible in the URL without losing information similar to how a web browser does it for the URL bar.
It’s usually more interesting to directly call uri_to_iri() which will return a string.
werkzeug.urls.BaseURL


Returns a BytesURL tuple that holds a URI. This will encode all the information in the URL properly to ASCII using the rules a web browser would follow.
It’s usually more interesting to directly call iri_to_uri() which will return a string.
werkzeug.urls.BaseURL


Returns a URL string or bytes depending on the type of the information stored. This is just a convenience function for calling url_unparse() for this URL.
str


Bind the arguments provided into a dict. When passed a function, a tuple of arguments and a dict of keyword arguments bind_arguments returns a dict of names as the function would see it. This can be useful to implement a cache decorator that uses the function arguments to build the cache key based on the values of the arguments.
a dict of bound keyword arguments.
Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use Signature.bind() instead.


The warning used by Werkzeug to signal a broken filesystem. Will only be used once per runtime.


Represents a parsed URL in bytes.
Create new instance of _URLTuple(scheme, netloc, path, query, fragment)
Decodes the URL to a tuple made out of strings. The charset is only being used for the path, query and fragment.
werkzeug.urls.URL
Returns the netloc unchanged as bytes.
bytes


Decodes the URL to a tuple made out of strings. The charset is only being used for the path, query and fragment.
werkzeug.urls.URL


Returns the netloc unchanged as bytes.
bytes


A property() that is only evaluated once. Subsequent access returns the cached value. Setting the property sets the cached value. Deleting the property clears the cached value, accessing it again will evaluate it again.
The class must have a __dict__ for this to work.
Changed in version 2.0: del obj.name clears the cached value.
None


If all other deployment methods do not work, CGI will work for sure. CGI is supported by all major servers but usually has a less-than-optimal performance.
This is also the way you can use a Werkzeug application on Google’s AppEngine, there however the execution does happen in a CGI-like environment. The application’s performance is unaffected because of that.
First you need to create the CGI application file. Let’s call it yourapplication.cgi:
Usually there are two ways to configure the server. Either just copy the .cgi into a cgi-bin (and use mod_rewrite or something similar to rewrite the URL) or let the server point to the file directly.
In Apache for example you can put something like this into the config:
For more information consult the documentation of your webserver.


Like Accept but with normalization for charsets.


Check a password against a given salted and hashed password value. In order to support unsalted legacy passwords this method supports plain text passwords, md5 and sha1 hashes (both salted and unsalted).
Returns True if the password matched, False otherwise.
bool


This class allows you to send requests to a wrapped application.
The use_cookies parameter indicates whether cookies should be stored and sent for subsequent requests. This is True by default, but passing False will disable this behaviour.
If you want to request some subdomain of your application you may set allow_subdomain_redirects to True as if not no external redirects are allowed.
Changed in version 2.0: response_wrapper is always a subclass of :class:TestResponse.
Changed in version 0.5: Added the use_cookies parameter.
None
Sets a cookie in the client’s cookie jar. The server name is required and has to match the one that is also passed to the open call.
None
Deletes a cookie in the test client.
None
Generate an environ dict from the given arguments, make a request to the application using it, and return the response.
werkzeug.test.TestResponse
Changed in version 2.0: as_tuple is deprecated and will be removed in Werkzeug 2.1. Use TestResponse.request and request.environ instead.
Changed in version 2.0: The request input stream is closed when calling response.close(). Input streams for redirects are automatically closed.
Changed in version 0.5: If a dict is provided as file in the dict for the data parameter the content type has to be called content_type instead of mimetype. This change was made for consistency with werkzeug.FileWrapper.
Changed in version 0.5: Added the follow_redirects parameter.
Call open() with method set to GET.
werkzeug.test.TestResponse
Call open() with method set to POST.
werkzeug.test.TestResponse
Call open() with method set to PUT.
werkzeug.test.TestResponse
Call open() with method set to DELETE.
werkzeug.test.TestResponse
Call open() with method set to PATCH.
werkzeug.test.TestResponse
Call open() with method set to OPTIONS.
werkzeug.test.TestResponse
Call open() with method set to HEAD.
werkzeug.test.TestResponse
Call open() with method set to TRACE.
werkzeug.test.TestResponse


Call open() with method set to DELETE.
werkzeug.test.TestResponse


Deletes a cookie in the test client.
None


Call open() with method set to GET.
werkzeug.test.TestResponse


Call open() with method set to HEAD.
werkzeug.test.TestResponse


Generate an environ dict from the given arguments, make a request to the application using it, and return the response.
werkzeug.test.TestResponse
Changed in version 2.0: as_tuple is deprecated and will be removed in Werkzeug 2.1. Use TestResponse.request and request.environ instead.
Changed in version 2.0: The request input stream is closed when calling response.close(). Input streams for redirects are automatically closed.
Changed in version 0.5: If a dict is provided as file in the dict for the data parameter the content type has to be called content_type instead of mimetype. This change was made for consistency with werkzeug.FileWrapper.
Changed in version 0.5: Added the follow_redirects parameter.


Call open() with method set to OPTIONS.
werkzeug.test.TestResponse


Call open() with method set to PATCH.
werkzeug.test.TestResponse


Call open() with method set to POST.
werkzeug.test.TestResponse


Call open() with method set to PUT.
werkzeug.test.TestResponse


Sets a cookie in the client’s cookie jar. The server name is required and has to match the one that is also passed to the open call.
None


Call open() with method set to TRACE.
werkzeug.test.TestResponse


The WSGI specification requires that all middlewares and gateways respect the close callback of the iterable returned by the application. Because it is useful to add another close action to a returned iterable and adding a custom iterable is a boring task this class can be used for that:
If there is just one close function it can be passed instead of the list.
A closing iterator is not needed if the application uses response objects and finishes the processing if the response is started:
None


A read only MultiDict that you can pass multiple MultiDict instances as sequence and it will combine the return values of all wrapped dicts:
This works for all read operations and will raise a TypeError for methods that usually change data which isn’t possible.
From Werkzeug 0.3 onwards, the KeyError raised by this class is also a subclass of the BadRequest HTTP exception and will render a page for a 400 BAD REQUEST if caught in a catch-all for HTTP exceptions.


Represents the content range header.
New in version 0.7.
The length of the range or None.
Simple method to update the ranges.
The start point of the range or None.
The stop point of the range (non-inclusive) or None. Can only be None if also start is None.
The units to use, usually “bytes”
Sets the units to None which indicates that the header should no longer be used.


Sets the units to None which indicates that the header should no longer be used.


Format a datetime object or timestamp into an RFC 2822 date string for Set-Cookie expires.
Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use http_date() instead.
expires (Optional[Union[datetime.datetime, datetime.date, int, float, time.struct_time]]) –
str


Create a new WSGI environ dict based on the values passed. The first parameter should be the path of the request which defaults to ‘/’. The second one can either be an absolute path (in that case the host is localhost:80) or a full path to the request with scheme, netloc port and the path to the script.
This accepts the same arguments as the EnvironBuilder constructor.
Changed in version 0.5: This function is now a thin wrapper over EnvironBuilder which was added in 0.5. The headers, environ_base, environ_overrides and charset parameters were added.
WSGIEnvironment