Загрузка
_infer_device_typerun_fncudaDefaultDeviceTyperun_fnrun_fncheckpoint may also be called without a function to produce a decorator. This
keeps checkpoint configuration separate from the keyword arguments passed to the
checkpointed function:
checkpointed_fn = checkpoint(use_reentrant=False, preserve_rng_state=False)(fn)
out = checkpointed_fn(*args, **kwargs)
Checkpoint a model or part of the model.
Activation checkpointing is a technique that trades compute for memory.
By default, tensors computed during the forward pass are kept alive until
they are used in gradient computations in the backward pass. To reduce this
memory usage, tensors produced in the passed function are not kept
alive until the backward pass. Instead, any passed tensors in args
are kept alive, and the unsaved tensors are recomputed by re-invoking
function in the backward pass as needed for gradient computation.
Activation checkpointing can be applied to any part of a model – this is
sometimes described as “checkpointing” that part of the model.
There are currently two checkpointing implementations available, determined
by the use_reentrant parameter. It is recommended that you use
use_reentrant=False. Please refer the note below for a discussion of
their differences.
Checkpoint a sequential model to save memory.
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 not store the intermediate activations. The inputs of each checkpointed segment will be saved for re-running the segment in the backward pass.
functions – A torch.nn.Sequential or the list of modules or
functions (comprising the model) to run sequentially.
segments – Number of chunks to create in the model
input – A Tensor that is input to functions
preserve_rng_state (bool, optional) – Omit stashing and restoring
the RNG state during each checkpoint.
Default: True
use_reentrant (bool) – specify whether to use the activation checkpoint variant that requires reentrant autograd. This parameter should be passed explicitly. In version 2.5 we will raise an exception if is not passed. If , will use an implementation that does not require reentrant autograd. This allows to support additional functionality, such as working as expected with and support for keyword arguments input into the checkpointed function.
>>> model = nn.Sequential(...)
>>> input_var = checkpoint_sequential(model, chunks, input_var)
Context manager that sets whether checkpoint should print additional debug
information when running. See the debug flag for
checkpoint() for more information. Note that
when set, this context manager overrides the value of debug passed to
checkpoint. To defer to the local setting, pass None to this context.
enabled (bool) – Whether checkpoint should print debug information. Default is ‘None’.
Enum for specifying the policy for checkpointing during backpropagation.
The following policies are supported:
{MUST,PREFER}_SAVE: The operation’s output will be saved during the forward
pass and will not be recomputed during the backward pass
{MUST,PREFER}_RECOMPUTE: The operation’s output will not be saved during the
forward pass and will be recomputed during the backward pass
{MUST,PREFER}_CPU_OFFLOAD: The operation’s output will be saved during the
forward pass, offloaded to CPU, and reloaded to GPU during the backward pass
Use MUST_* over PREFER_* to indicate that the policy should not be overridden
by other subsystems like torch.compile.
Context passed to policy function during selective checkpointing.
This class is used to pass relevant metadata to the policy function during selective checkpointing.
The policy function is only called during the forward pass. During
recomputation, cached values are retrieved by index, so is_recompute
is deprecated and always False.
>>>
>>> def policy_fn(ctx, op, *args, **kwargs):
>>> print(ctx.op_output)
>>>
>>> context_fn = functools.partial(create_selective_checkpoint_contexts, policy_fn)
>>>
>>> out = torch.utils.checkpoint.checkpoint(
>>> fn, x, y,
>>> use_reentrant=False,
>>> context_fn=context_fn,
>>> )
Helper to avoid recomputing certain ops during activation checkpointing.
Use this with torch.utils.checkpoint.checkpoint to control which operations are recomputed during the backward pass.
policy_fn_or_list (Callable or List) –
If a policy function is provided, it should accept a
SelectiveCheckpointContext, the OpOverload, args and
kwargs to the op, and return a CheckpointPolicy enum value
indicating whether the execution of the op should be recomputed or not.
If a list of operations is provided, it is equivalent to a policy returning CheckpointPolicy.MUST_SAVE for the specified operations and CheckpointPolicy.PREFER_RECOMPUTE for all other operations.
allow_cache_entry_mutation (bool, optional) – By default, an error is raised if any tensors cached by selective activation checkpoint are mutated in order to ensure correctness. If set to True, this check is disabled.
A tuple of two context managers.
>>> import functools
>>>
>>> x = torch.rand(10, 10, requires_grad=True)
>>> y = torch.rand(10, 10, requires_grad=True)
>>>
Any checkpointed regions encountered by backward under the same instance of this context manager will trigger recompute at most once, even if there are multiple calls to backward.
Backward calls under the same instance of this context manager must execute over non-overlapping regions of the backward graph even if retain_graph=True. In particular, any two backward call cannot use the same saved activation for gradient computation.
Controls whether checkpoint should stop recomputation early.
By default, non-reentrant checkpoint stops recomputation as soon as it has computed all needed Tensors. This context manager can be used to disable that feature if it is problematic for your specific application.
This context manager only needs to be active when forward is run. It does not need to be active during backward.
Example:
>>> message = "saved tensors default hooks are disabled"
>>> with set_checkpoint_early_stop(False):
... # Any checkpoint under this context manager will respect this
... # context manager, even if its backward is performed outside.
... out = checkpoint(fn, inputs)
...
>>> out.backward()
Sets random number generator states for the specified devices.
devices – Device ids to set states for.
states – States to set.
device_type – device_type of the devices to set states for. Default
is the device returned by a call to DefaultDeviceType.get_device_type(),
which is cuda if not changed by calling DefaultDeviceType::set_device_type().
function – describes what to run in the forward pass of the model or
part of the model. It should also know how to handle the inputs
passed as the tuple. For example, in LSTM, if user passes
(activation, hidden), function should correctly use the
first input as activation and the second input as hidden.
If omitted, checkpoint returns a decorator that can be used to
wrap a function before passing user arguments.
args – tuple containing inputs to the function
preserve_rng_state (bool, optional) – Omit stashing and restoring
the RNG state during each checkpoint. Note that under torch.compile,
this flag doesn’t take effect and we always preserve RNG state.
Default: True
use_reentrant (bool) – specify whether to use the activation checkpoint variant that
requires reentrant autograd. This parameter should be passed
explicitly. In version 2.9 we will raise an exception if
use_reentrant is not passed. If use_reentrant=False,
checkpoint will use an implementation that does not require
reentrant autograd. This allows checkpoint to support additional
functionality, such as working as expected with
torch.autograd.grad and support for keyword arguments input into
the checkpointed function.
context_fn (Callable, optional) – A callable returning a tuple of two
context managers. The function and its recomputation will be run
under the first and second context managers respectively.
This argument is only supported if use_reentrant=False.
determinism_check (str, optional) – A string specifying the determinism
check to perform. By default it is set to "default" which
compares the shapes, dtypes, and devices of the recomputed tensors
against those the saved tensors. To turn off this check, specify
"none". Currently these are the only two supported values.
Please open an issue if you would like to see more determinism
checks. This argument is only supported if use_reentrant=False,
if use_reentrant=True, the determinism check is always disabled.
debug (bool, optional) – If True, error messages will also include
a trace of the operators ran during the original forward computation
as well as the recomputation. This argument is only supported if
use_reentrant=False.
early_stop (bool, optional) – If True, non-reentrant checkpoint stops
recomputation as soon as it has computed all needed Tensors. This
argument is ignored if use_reentrant=True. Can be overridden
globally using set_checkpoint_early_stop() context manager.
Default: True.
respect_saved_tensors_hooks (bool, optional) – Whether tensors that
selective activation checkpointing (SAC) saves are routed through
the surrounding user
torch.autograd.graph.saved_tensors_hooks() (e.g.
torch.autograd.graph.save_on_cpu()). Such tensors are held
outside the autograd graph, so historically these hooks did not see
them; a future release will make checkpoint honor the hooks by
default. Until then the default (None) keeps the legacy behavior
and emits a FutureWarning when a user hook is in scope; pass
True to opt in or False to keep the legacy behavior without
the warning. Has no effect without SAC (plain checkpoint recomputes
rather than saves) or when . This argument is
only supported if .
Output of running function on *args, or a decorator
when function is omitted.
>>> # Direct call: checkpoint the function immediately.
>>> out = torch.utils.checkpoint.checkpoint(
... fn, *args, use_reentrant=False, **kwargs
... )
>>> # Decorator/curried form: configure once, then call.
>>> checkpointed_fn = torch.utils.checkpoint.checkpoint(
... use_reentrant=False,
... preserve_rng_state=False,
... )(fn)
>>> out = checkpointed_fn(*args, **kwargs)
>>> # The same decorator can be applied directly to a function or method.
>>> @torch.utils.checkpoint.checkpoint(use_reentrant=False)
... def fn(*args, **kwargs):
... ...
>>> out = fn(*args, **kwargs)
use_reentrantuse_reentrant=Falsecheckpointcheckpointtorch.autograd.gradOutput of running functions sequentially on *inputs
use_reentrant=Trueuse_reentrant=False