Read values without retaining the training graph
Inference or logging
PyTorch · Module
Returns a tensor disconnected from the current autograd graph. The result shares storage with the source, does not require gradients, and has no forward-mode AD gradients.
Calling detach returns a tensor that shares storage with the original but is disconnected from its backward computation graph. The returned tensor does not require gradients and does not retain forward-mode automatic-differentiation gradients, so later operations on it are not connected to the original history.
Tensor.detach()A new Tensor detached from the current graph; it shares storage with the original tensor and does not require gradients.
import torch
x = torch.tensor([1.0, 2.0], requires_grad=True)
y = (x * 2).sum()
z = y.detach()
print(z.requires_grad) # False
z[0] = 99.0
print(y.item())
Creates a tensor with autograd history, detaches a scalar result, and verifies that the detached tensor does not require gradients. The final mutation illustrates shared storage when the detached value is non-scalar.
Inference or logging
Gradient-isolated branches
Memory-conscious tensor handling
detach() returns a new tensor disconnected from the current computation graph. It does not require gradients, and it shares storage with the source tensor.
Follow-up: What happens if the detached tensor is modified in place? The source tensor observes the same storage mutation, which can also trigger correctness-check errors.
The returned tensor is not connected to the graph used to compute the original tensor, so subsequent operations on it cannot propagate gradients back through that history. It also has no forward-mode AD gradients.
Follow-up: How would you avoid shared-storage side effects? Use a separate copy after detaching, such as detach().clone(), when independent storage is required.
No. The result shares storage with the original tensor, even though it has independent autograd history. In-place changes made through either tensor are therefore visible through both.
Follow-up: Why might this matter in a correctness check? An in-place update can invalidate values saved for gradient computation and produce an error.
torch.Tensor.detach_torch.Tensor.clonetorch.Tensor.requires_grad_torch.no_grad