torch.autograd provides classes and functions implementing automatic differentiation of arbitrary scalar valued functions.
It requires minimal changes to the existing code - you only need to declare Tensor s
for which gradients should be computed with the requires_grad=True keyword.
As of now, we only support autograd for floating point Tensor types (
half, float, double and bfloat16) and complex Tensor types (cfloat, cdouble).
Namedtuple returned by unpack_dual() containing the primal and tangent components of the dual tensor.
Functional higher level API
This section contains the higher level API for the autograd that builds on the basic API above
and allows you to compute jacobians, hessians, etc.
This API works with user-provided functions that take only Tensors as input and return
only Tensors.
If your function takes other arguments that are not Tensors or Tensors that don’t have requires_grad set,
you can use a lambda to capture them.
For example, for a function f that takes three inputs, a Tensor for which we want the jacobian, another
tensor that should be considered constant and a boolean flag as f(input,constant,flag=flag)
you can use it as functional.jacobian(lambdax:f(x,constant,flag=flag),input).
Compute the dot product between the scalar function's Hessian and a vector v at a specified point.
Locally disabling gradient computation
See Locally disabling gradient computation for more information on the differences
between no-grad and inference mode as well as other related mechanisms that
may be confused with the two. Also see Locally disabling gradient computation
for a list of functions that can be used to locally disable gradients.
If param’s memory is non-overlapping and dense, .grad is
created with strides matching param (thus matching param’s
layout).
Otherwise, .grad is created with rowmajor-contiguous strides.
If param already has a non-sparse .grad attribute:
If create_graph=False, backward() accumulates into .grad
in-place, which preserves its strides.
If create_graph=True, backward() replaces .grad with a
new tensor .grad+newgrad, which attempts (but does not guarantee)
matching the preexisting .grad’s strides.
The default behavior (letting .grads be None before the first
backward(), such that their layout is created according to 1 or 2,
and retained over time according to 3 or 4) is recommended for best performance.
Calls to model.zero_grad() or optimizer.zero_grad() will not affect .grad
layouts.
In fact, resetting all .grads to None before each
accumulation phase, e.g.:
such that they’re recreated according to 1 or 2 every time,
is a valid alternative to model.zero_grad() or optimizer.zero_grad()
that may improve performance for some networks.
Manual gradient layouts
If you need manual control over .grad’s strides,
assign param.grad= a zeroed tensor with desired strides
before the first backward(), and never reset it to None.
3 guarantees your layout is preserved as long as create_graph=False.
4 indicates your layout is likely preserved even if create_graph=True.
In-place operations on Tensors
Supporting in-place operations in autograd is a hard matter, and we discourage
their use in most cases. Autograd’s aggressive buffer freeing and reuse makes
it very efficient and there are very few occasions when in-place operations
actually lower memory usage by any significant amount. Unless you’re operating
under heavy memory pressure, you might never need to use them.
In-place correctness checks
All Tensor s keep track of in-place operations applied to them, and
if the implementation detects that a tensor was saved for backward in one of
the functions, but it was modified in-place afterwards, an error will be raised
once backward pass is started. This ensures that if you’re using in-place
functions and not seeing any errors, you can be sure that the computed
gradients are correct.
Variable (deprecated)
Tensor autograd functions
torch.Tensor.grad
This attribute is None by default and becomes a Tensor the first time a call to backward() computes gradients for self.
torch.Tensor.requires_grad
Is True if gradients need to be computed for this Tensor, False otherwise.
torch.Tensor.is_leaf
All Tensors that have requires_grad which is False will be leaf Tensors by convention.
torch.Tensor.backward([gradient, ...])
Computes the gradient of current tensor wrt graph leaves.
torch.Tensor.detach
Returns a new Tensor, detached from the current graph.
torch.Tensor.detach_
Detaches the Tensor from the graph that created it, making it a leaf.
Registers a backward hook that runs after grad accumulation.
torch.Tensor.retain_grad()
Enables this Tensor to have their grad populated during backward().
Function
classtorch.autograd.Function(*args, **kwargs)
Base class to create custom autograd.Function.
To create a custom autograd.Function, subclass this class and implement
the forward() and backward() static methods. Then, to use your custom
op in the forward pass, call the class method apply. Do not call
forward() directly.
To ensure correctness and best performance, make sure you are calling the
correct methods on ctx and validating your backward function using
torch.autograd.gradcheck().
Check gradients computed via small finite differences against analytical gradients wrt tensors in inputs that are of floating point or complex type and with requires_grad=True.
Check gradients of gradients computed via small finite differences against analytical gradients wrt tensors in inputs and grad_outputs that are of floating point or complex type and with requires_grad=True.
Autograd includes a profiler that lets you inspect the cost of different
operators inside your model - both on the CPU and GPU. There are three modes
implemented at the moment - CPU-only using profile.
nvprof based (registers both CPU and GPU activity) using
emit_nvtx.
and vtune profiler based using
emit_itt.
Context manager that manages autograd profiler state and holds a summary of results.
Under the hood it just records events of functions being executed in C++ and
exposes those events to Python. You can wrap any code into it and it will
only report runtime of PyTorch functions.
Note: profiler is thread local and is automatically propagated into the async tasks
Parameters:
enabled (bool, optional) – Setting this to False makes this context manager a no-op.
use_device () – Enables timing of device events.
Adds approximately 4us of overhead to each tensor operation when use cuda.
The valid devices options are ‘cuda’, ‘xpu’, ‘mtia’ and ‘privateuseone’.
Context-manager that enables anomaly detection for the autograd engine.
This does two things:
Running the forward pass with detection enabled will allow the backward
pass to print the traceback of the forward operation that created the failing
backward function.
If check_nan is True, any backward computation that generates “nan”
value will raise an error. Default True.
Context-manager that sets the anomaly detection for the autograd engine on or off.
set_detect_anomaly will enable or disable the autograd anomaly detection
based on its argument mode.
It can be used as a context-manager or as a function.
See detect_anomaly above for details of the anomaly detection behaviour.
Parameters:
mode () – Flag whether to enable anomaly detection (),
or disable ().
Context-manager that controls the gradient layout policy enforcement.
Autograd graph
Autograd exposes methods that allow one to inspect the graph and interpose behavior during
the backward pass.
The grad_fn attribute of a torch.Tensor holds a torch.autograd.graph.Node
if the tensor is the output of a operation that was recorded by autograd (i.e., grad_mode is
enabled and at least one of the inputs required gradients), or None otherwise.
Update autograd metadata tracking whether the given Tensor was modified in place.
Some operations need intermediary results to be saved during the forward pass
in order to execute the backward pass.
These intermediary results are saved as attributes on the grad_fn and can be accessed.
For example:
You can also define how these saved tensors should be packed / unpacked using hooks.
A common application is to trade compute for memory by saving those intermediary results
to disk or to CPU instead of leaving them on the GPU. This is especially useful if you
notice your model fits on GPU during evaluation, but not training.
When writing a pack_hook that keeps its input tensor, call .detach() on it first
to avoid a reference cycle when the saved tensor is a graph output; see
Hooks for saved tensors for details.
Context-manager that sets a pair of pack / unpack hooks for saved tensors.
Use this context-manager to define how intermediary results of an operation
should be packed before saving, and unpacked on retrieval.
In that context, the pack_hook function will be called every time an
operation saves a tensor for backward (this includes intermediary results
saved using
save_for_backward() but
also those recorded by a PyTorch-defined operation). The output of
pack_hook is then stored in the computation graph instead of the
original tensor.
The unpack_hook is called when the saved tensor needs to be accessed,
namely when executing or
. It takes as argument the object
returned by and should return a tensor which has the same
content as the original tensor (passed as input to the corresponding
).
Context manager under which tensors saved by the forward pass will be stored on cpu, then retrieved for backward.
When performing operations within this context manager, intermediary
results saved in the graph during the forward pass will be moved to CPU,
then copied back to the original device when needed for the backward pass.
If the graph was already on CPU, no tensor copy is performed.
Use this context-manager to trade compute for GPU memory usage (e.g.
when your model doesn’t fit in GPU memory during training).
Under the "all" mode, the hook will be called after gradients with respect to every tensor in
tensors have been computed. If a tensor is in but
is not part of the graph, or if a tensor is not needed to compute the gradients
for any specified for the current or call,
this tensor will be ignored and the hook will not wait for its gradient to be
computed.
Context-manager that registers a hook called on each autograd Node created within it.
In that context, hook is called once for every autograd graph node
created by operations on tensors that require grad, with the freshly
created torch.autograd.graph.Node as its only argument. The
intended use is to record the node, stash entries in node.metadata,
or register backward hooks on it via
register_hook() and
.
Context manager under which mutating tensors saved for backward is allowed.
Under this context manager, tensors saved for backward are cloned on mutation,
so the original version can still be used during backward. Normally, mutating a tensor
saved for backward will result in an error raised when it’s used during backward.
To ensure the correct behavior, both the forward and backward should be run under
the same context manager.
Returns:
An _AllowMutationOnSavedContext object storing the state managed by this
context manager. This object can be useful for debugging purposes. The state
managed by the context manager is automatically cleared upon exiting.
Context-manager that sets the activation memory budget for the region of
a compiled forward traced under it.
Under torch.compile(), the min-cut partitioner chooses which
activations to save versus recompute in the backward pass to stay under a
memory budget. budget is a ratio in [0,1]: 0.0 corresponds to
the activation memory from applying activation checkpointing to the full
region, and corresponds to the activation memory from the default
runtime-optimized strategy. So would result in a strategy that saves
40% of the activations compared to the default strategy. It solves a 0-1
knapsack to find the minimum recompute necessary to stay below the budget.
This overrides the global
for the annotated region.
Control behavior when autograd detects a stale non-capturing stream during
CUDA graph capture.
During CUDA graph capture, autograd nodes may reference a stale stream
that is not part of the capture. With the flag disabled (the
process-initial state), autograd raises a RuntimeError when the stale
stream is the default stream (stream 0), because this case always
invalidates the capture: cudaStreamWaitEvent on the default stream
pulls a non-capturing stream into the graph. For non-default stale streams
the stream reference is left unchanged; the capture will succeed if the
user has joined the stream into the capture (e.g. via
capture_stream.wait_stream(stale_stream)) and will otherwise fail with
a CUDA runtime error.
When enabled=True, any stale non-capturing stream (default or
non-default) is automatically overridden with the producer’s capturing
stream, allowing the capture to proceed. This is a process-global setting
and is not thread-local.
The flag also governs the end-of-backward sync between each leaf’s stream
and the caller’s current stream. A leaf whose incoming gradients are all
undefined (e.g. patterns that compute certain gradients out of band and
return from autograd) cannot be reconciled by the override, so
when exactly one of the two streams is capturing, that sync would cross
the capture boundary: with the flag enabled the sync is skipped (work on
a non-capturing stream is not part of the capture, so the ordering has no
effect on it); with the flag disabled a is raised.
record_shapes (bool, optional) – If shapes recording is set, information
about input dimensions will be collected. This allows one to see which
dimensions have been used under the hood and further group by them
using prof.key_averages(group_by_input_shape=True). Please note that
shape recording might skew your profiling data. It is recommended to
use separate runs with and without shape recording to validate the timing.
Most likely the skew will be negligible for bottom most events (in a case
of nested function calls). But for higher level functions the total
self cpu time might be artificially increased because of the shape
collection.
with_flops (bool, optional) – If with_flops is set, the profiler will estimate
the FLOPs (floating point operations) value using the operator’s input shape.
This allows one to estimate the hardware performance. Currently,
this option only works for the matrix multiplication and 2D convolution operators.
record module hierarchy (including function names)
corresponding to the callstack of the op. e.g. If module A’s forward call’s
module B’s forward which contains an aten::add op,
then aten::add’s module hierarchy is A.B
use_kineto (bool, optional) – experimental, enable profiling with Kineto profiler.
use_cpu (bool, optional) – profile CPU events; setting to False requires
use_kineto=True and can be used to lower the overhead for GPU-only profiling.
experimental_config (_ExperimentalConfig) – A set of experimental options
used by profiler libraries like Kineto. Note, backward compatibility is not guaranteed.
acc_events (bool) – Enable the accumulation of FunctionEvents across multiple profiling cycles
post_processing_timeout_s (float) – Optional timeout in seconds for post-processing profiler
results. In this context, post-processing happens after the profiling itself has finished.
If specified, event parsing will stop after this duration and return partial results. Useful
for handling large traces that may take too long to process.
Example
>>> x=torch.randn((1,1),requires_grad=True)>>> withtorch.autograd.profiler.profile()asprof:>>> for_inrange(100):# any normal python code, really!>>> y=x**2>>> y.backward()>>> # NOTE: some columns were removed for brevity>>> print(prof.key_averages().table(sort_by="self_cpu_time_total"))----------------------------------- --------------- --------------- ---------------Name Self CPU total CPU time avg Number of Calls----------------------------------- --------------- --------------- ---------------mul 32.048ms 32.048ms 200pow 27.041ms 27.041ms 200PowBackward0 9.727ms 55.483ms 100torch::autograd::AccumulateGrad 9.148ms 9.148ms 100torch::autograd::GraphRoot 691.816us 691.816us 100----------------------------------- --------------- --------------- ---------------
Unfortunately, there’s no way to force nvprof to flush the data it collected
to disk, so for CUDA profiling one has to use this context manager to annotate
nvprof traces and wait for the process to exit before inspecting them.
Then, either NVIDIA Visual Profiler (nvvp) can be used to visualize the timeline, or
torch.autograd.profiler.load_nvprof() can load the results for inspection
e.g. in Python REPL.
Parameters:
enabled (bool, optional) – Setting enabled=False makes this context manager a no-op.
Default: True.
record_shapes (bool, optional) – If record_shapes=True, the nvtx range wrapping
each autograd op will append information about the sizes of Tensor arguments received
by that op, in the following format:
[[arg0.size(0),arg0.size(1),...],[arg1.size(0),arg1.size(1),...],...]
Non-tensor arguments will be represented by [].
Arguments will be listed in the order they are received by the backend op.
Please note that this order may not match the order in which those arguments were passed
on the Python side. Also note that shape recording may increase the overhead of nvtx range creation.
Default: False
Example
>>> withtorch.cuda.profiler.profile():... model(x)# Warmup CUDA memory allocator and profiler... withtorch.autograd.profiler.emit_nvtx():... model(x)
Forward-backward correlation
When viewing a profile created using emit_nvtx in the Nvidia Visual Profiler,
correlating each backward-pass op with the corresponding forward-pass op can be difficult.
To ease this task, emit_nvtx appends sequence number information to the ranges it
generates.
During the forward pass, each function range is decorated with seq=<N>. seq is a running
counter, incremented each time a new backward Function object is created and stashed for backward.
Thus, the seq=<N> annotation associated with each forward function range tells you that
if a backward Function object is created by this forward function,
the backward object will receive sequence number N.
During the backward pass, the top-level range wrapping each C++ backward Function’s
apply() call is decorated with stashedseq=<M>. M is the sequence number that
the backward object was created with. By comparing stashedseq numbers in backward with seq
numbers in forward, you can track down which forward op created each backward Function.
Any functions executed during the backward pass are also decorated with seq=<N>. During
default backward (with create_graph=False) this information is irrelevant, and in fact,
N may simply be 0 for all such functions. Only the top-level ranges associated with
backward Function objects’ apply() methods are useful, as a way to correlate these Function
objects with the earlier forward pass.
Double-backward
If, on the other hand, a backward pass with create_graph=True is underway (in other words,
if you are setting up for a double-backward), each function’s execution during backward
is given a nonzero, useful seq=<N>. Those functions may themselves create Function objects
to be executed later during double-backward, just as the original functions in the forward pass did.
The relationship between backward and double-backward is conceptually the same as the relationship
between forward and backward: The functions still emit current-sequence-number-tagged ranges,
the Function objects they create still stash those sequence numbers, and during the eventual
double-backward, the Function objects’ apply() ranges are still tagged with stashedseq
numbers, which can be compared to seq numbers from the backward pass.
The Instrumentation and Tracing Technology (ITT) API enables your application to generate and
control the collection of trace data during its execution across different Intel tools.
This context manager is to annotate Intel(R) VTune Profiling trace. With help of this context manager,
you will be able to see labeled ranges in Intel(R) VTune Profiler GUI.
Parameters:
enabled (bool, optional) – Setting enabled=False makes this context manager a no-op.
Default: True.
record_shapes (bool, optional) – If record_shapes=True, the itt range wrapping
each autograd op will append information about the sizes of Tensor arguments received
by that op, in the following format:
[[arg0.size(0),arg0.size(1),...],[arg1.size(0),arg1.size(1),...],...]
Non-tensor arguments will be represented by [].
Arguments will be listed in the order they are received by the backend op.
Please note that this order may not match the order in which those arguments were passed
on the Python side. Also note that shape recording may increase the overhead of itt range creation.
Default: False
pin_memory (bool) – If True tensors will be saved to CPU pinned memory
during packing and copied to GPU asynchronously during both
packing and unpacking.
Defaults to False.
Also see Use pinned memory buffers.
Example:
>>> a=torch.randn(5,requires_grad=True,device="cuda")>>> b=torch.randn(5,requires_grad=True,device="cuda")>>> c=torch.randn(5,requires_grad=True,device="cuda")>>>>>> deff(a,b,c):... prod_1=a*b# a and b are saved on GPU... withtorch.autograd.graph.save_on_cpu():... prod_2=prod_1*c# prod_1 and c are saved on CPU... y=prod_2*a# prod_2 and a are saved on GPU... returny>>>>>> y=f(a,b,c)>>> dela,b,c# for illustration only>>> # the content of a, b, and prod_2 are still alive on GPU>>> # the content of prod_1 and c only live on CPU>>> y.sum().backward()# all CPU tensors are moved back to GPU, for backward>>> # all intermediary tensors are released (deleted) after the call to backward
>>> message="saved tensors default hooks are disabled">>> withtorch.autograd.graph.disable_saved_tensors_hooks(message):... # Raises RuntimeError: saved tensors default hooks are disabled... withtorch.autograd.graph.save_on_cpu():... pass
tensors
inputs
.backward()
.grad()
After every non-ignored tensor’s gradient has been computed, fn will be
called with those gradients. None will be passed for tensors that did not
have their gradients computed.
Under the "any" mode, the hook will be called after the first gradient
with respect to a tensor in tensors has been computed. The hook
will be called with that gradient as its argument.
The hook should not modify its arguments.
This function returns a handle with a method handle.remove() that removes the hook.
The node is passed to the hook only once it is fully populated: its
next_functions are wired, all outputs’ metadata are bound, and the
tensors saved for backward (_saved_*) have been stored, so a hook
that inspects the node sees its complete state.
The hook should have the following signature:
hook(node:torch.autograd.graph.Node)->None
The registration is thread-local and propagates like other autograd
thread-local state: it is active on autograd engine worker threads, so
nodes created during backward (e.g. with create_graph=True or inside
checkpoint recomputation) also fire the hook.
When nesting this context-manager, every active hook is called for each
node, in registration order (outermost context-manager first). Creating
a new autograd node from inside a hook raises an error; hooks must only
observe the node they are given.
One motivating use case is attributing work done during backward to the
forward region that created the graph, by capturing state at node
creation time and restoring it around the node’s backward execution:
>>> defcreation_hook(node):... # ``current_region()``/``enter_region()`` are user-defined and... # stand in for whatever thread-local state you want to restore... # while this node runs in backward.... region=current_region()... node.register_prehook(lambdagO:enter_region(region))... node.register_hook(lambdagI,gO:enter_region(None))>>>>>> withtorch.autograd.graph.node_creation_hook(creation_hook):... loss=model(inputs)
Example:
>>> a=torch.ones(5,requires_grad=True)>>> withtorch.autograd.graph.node_creation_hook(lambdanode:print(node)):... b=a*2<AccumulateGrad object at ...><MulBackward0 object at ...>
>>> withtorch.autograd.graph.region_activation_memory_budget(0.0):... x=layer(x)# recompute this region's activations in backward
None
RuntimeError
Parameters:
enabled (bool) – If True, override stale non-capturing streams with
the producer’s capturing stream during CUDA graph capture, and
skip end-of-backward leaf syncs that would cross the capture
boundary. If False (the process-initial state), raise an error
when the stale stream is the default stream (stream 0) or when a
leaf sync would cross the capture boundary; other stale streams
are left unchanged.