In PyTorch 2.14, what does torch.utils.checkpoint do when use_reentrant is omitted, and why pass use_reentrant=False?
answer
- two implementations behind one flag
- omitted means a warning and the old path
- reentrant forward runs under no_grad
- some input must require grad
- context_fn only on the new path
basics
~10 sIn PyTorch 2.14, omitting use_reentrant warns and falls back to the reentrant variant. Pass use_reentrant=False: it handles frozen inputs, keyword arguments, nested inputs and torch.autograd.grad, stops recomputing early, and enables selective checkpointing.
solid answer
~40 s`torch.utils.checkpoint.checkpoint` has two implementations. In 2.14.1 the argument defaults to `None`, which warns that it should be passed and then sets `use_reentrant=True` — the docstring says omitting it would raise from 2.9, but the shipped code still warns and falls back. The reentrant variant runs the region's forward under `no_grad` and needs at least one *input* that requires grad; with frozen embeddings feeding adapter-tuned blocks it warns "None of the inputs have requires_grad=True" and the blocks' trainable weights get no gradients. It also rejects keyword arguments, breaks `torch.autograd.grad` and always recomputes the whole function. `use_reentrant=False` records the graph, has none of those limits, stops recomputing once the needed tensors exist, and is the only path for `context_fn` (selective checkpointing), `debug` and `determinism_check`.
code
python · 14 linesimport torch
from torch.utils.checkpoint import checkpoint
class Decoder(torch.nn.Module):
def __init__(self, blocks):
super().__init__()
self.blocks = torch.nn.ModuleList(blocks)
def forward(self, h):
for block in self.blocks:
# explicit: no warning, and frozen-embedding inputs still train the adapters
h = checkpoint(block, h, use_reentrant=False)
return hgo deeper
Recall that checkpoint has two implementations chosen by use_reentrant, and that use_reentrant=False is the recommended one to pass explicitly.
Explain what 2.14 does when the argument is omitted and list the reentrant variant's limits: inputs needing grad, no keyword arguments, no autograd.grad.
Diagnose adapter weights that never train behind a reentrant checkpoint with frozen inputs, and choose selective checkpointing or host offload per layer from a profile.
Set a codebase rule that every checkpoint call passes use_reentrant explicitly, so a future release that turns the warning into an error breaks nothing.
## Two implementations behind one argument `torch.utils.checkpoint.checkpoint(function, *args, use_reentrant=...)` does not keep the intermediate activations of `function` for backward; it recomputes them when backward needs them. Why that trade pays off is a concept question of its own — here the subject is the API. PyTorch ships two implementations, selected by `use_reentrant`: - **Reentrant** (`use_reentrant=True`): the original. It runs `function` under `torch.no_grad()` during the forward, and during backward re-runs the whole function with grad enabled and calls back into autograd from inside a backward pass — hence "reentrant". - **Non-reentrant** (`use_reentrant=False`): built on saved-tensor hooks. It records the autograd graph during the forward, drops the saved tensors, and recomputes them on demand. The documentation recommends `use_reentrant=False`. ## What happens when the argument is omitted In PyTorch 2.14.1 the parameter defaults to `None`. When it is `None`, `checkpoint` emits a warning that it should be passed explicitly — the message says calls without it will raise starting in 2.9 — and then sets `use_reentrant = True`. The docstring repeats the "will raise" plan, but the shipped code still warns and falls back to the reentrant variant. Code that relies on the default therefore runs the older implementation with all its limits. `checkpoint_sequential` follows the same pattern. ## Where the two differ | Behaviour | Reentrant (`True`) | Non-reentrant (`False`) | |---|---|---| | Recompute in backward | The whole function, every time | Stops once the needed tensors exist (`early_stop`, default `True`) | | Inputs that need grad | At least one input and output must require grad, or the region gets no gradients | No such requirement | | Backward API | Only `torch.autograd.backward` without `inputs`; `torch.autograd.grad` raises | All forms | | Keyword arguments to `function` | Rejected with a `ValueError` | Supported | | Tensors inside lists, dicts or custom objects | Not treated as autograd inputs | Tracked | | Detached tensors inside the region | Backward raises | Supported | | `context_fn`, `debug`, `determinism_check` | Not available | Available | ## The frozen-input trap Consider fine-tuning a 7B code model with low-rank adapters: the embeddings and base weights are frozen, the small adapter matrices inside each decoder block are trainable, and every block is wrapped in a reentrant checkpoint. 1. The embedding output does not require grad, because the embedding is frozen. 2. The reentrant checkpoint is an autograd function whose output requires grad only if one of its tensor *inputs* does. The adapter weights are not inputs to the call — they are captured inside `function`. 3. The first block's output therefore does not require grad, so neither does the next block's input, and the pattern repeats through the stack. 4. PyTorch warns "None of the inputs have requires_grad=True. Gradients will be None". The adapters inside the checkpointed blocks never receive gradients; if no trainable layer sits outside them, backward fails because the loss does not require grad. Passing `use_reentrant=False` fixes it: the non-reentrant variant records the graph through the block, so gradients reach the adapters whatever the input's `requires_grad`. ## What only the non-reentrant variant unlocks - **Selective checkpointing.** `context_fn=functools.partial(create_selective_checkpoint_contexts, policy_fn)` lets a policy return a `CheckpointPolicy` for each op: `MUST_SAVE` / `PREFER_SAVE` to keep an output, `MUST_RECOMPUTE` / `PREFER_RECOMPUTE` to drop it, and `MUST_CPU_OFFLOAD` / `PREFER_CPU_OFFLOAD` to keep it in host memory. - **`determinism_check`** (default `"default"`) compares the shapes, dtypes and devices of recomputed tensors with the originals and raises a `CheckpointError` on a mismatch. - **`debug=True`** adds a trace of the operators run in the forward and in the recomputation to that error. ## Offloading instead of recomputing `torch.autograd.graph.save_on_cpu(pin_memory=False)` is a context manager that moves tensors saved for backward to host memory during the forward and copies them back for backward. With `pin_memory=True` the host copies use pinned memory and the transfers run asynchronously. It spends host-device bandwidth instead of recompute; whether that is cheaper depends on the link and the layer, and the profiler is where you find out.
- How do you keep some ops' outputs instead of recomputing all of them?Use selective checkpointing, which needs `use_reentrant=False`: pass `context_fn=functools.partial(create_selective_checkpoint_contexts, policy_fn)`, where `policy_fn` returns a `CheckpointPolicy` per op — for example `MUST_SAVE` for expensive matrix multiplications and `PREFER_RECOMPUTE` for cheap pointwise ops. A policy that recomputes everything is plain checkpointing.
- What does torch.autograd.graph.save_on_cpu change, and what is its pin_memory default?Inside the context, tensors saved for backward move to host memory during the forward and are copied back to the device for backward. `pin_memory` defaults to `False`; with `True` the copies go through pinned host memory and run asynchronously. It trades device memory for host-device transfers rather than recompute.
- A checkpointed block raises a CheckpointError about recomputed tensors with different metadata. What does it mean?With `use_reentrant=False`, the default `determinism_check` compares shapes, dtypes and devices of recomputed tensors against the originals. A mismatch means the recompute took a different path — global state or an input changed between forward and backward. Pass `debug=True` to see the operators run in both passes.
- Omitting use_reentrant raises an exception in PyTorch 2.14.
- Omitting use_reentrant selects the non-reentrant variant.
- Both variants always recompute the whole checkpointed function.
- The reentrant variant works fine with torch.autograd.grad.
- Frozen inputs are harmless to the reentrant variant if the weights need grad.
- save_on_cpu pins host memory by default.
Assumes PyTorch 2.14.1: omitting use_reentrant still warns and falls back to the reentrant variant, although the docstring says 2.9 would raise.