This lab shows how PyTorch autograd records operations on tensors and computes gradients. It covers requires_grad, grad_fn, .grad, backward(), torch.no_grad() and detach(). The sections below the notebook explain why each output looks the way it does, check the gradients by hand, fix the misleading parts of the notebook, and list the autograd errors you are most likely to run into.
How autograd works in one paragraph
Each time you run an operation on a tensor with requires_grad=True, PyTorch adds a node to a computation graph. The graph is built while your code runs, which is why it is called a dynamic graph. Calling backward() on a scalar result walks that graph in reverse, applies the chain rule, and stores the gradients in the .grad attribute of every leaf tensor that requires gradients. A leaf tensor is one you created directly rather than one produced by an operation. Training a neural network follows this pattern: the model parameters are leaf tensors, the loss is the scalar you call backward() on, and the optimizer reads .grad to update the parameters.
| Attribute | Meaning | Typical value in the notebook |
|---|---|---|
requires_grad | Whether operations on this tensor are recorded | False by default, True after requires_grad_() |
grad_fn | The backward node that created this tensor | None for leaf tensors, MulBackward0 or MeanBackward0 for results |
.grad | Accumulated gradient, filled in by backward() | None until backward() runs, and only on leaf tensors |
is_leaf | Whether the tensor was created by the user rather than by an operation | True for tensor1, False for output_tensor |
Running the lab as a plain Python script
The notebook targets Python 3 and any recent PyTorch release. Install the CPU build with pip install torch, or follow the selector on the PyTorch website if you need a CUDA build. The script below condenses the first half of the notebook. It uses torch.tensor with float values, which is the recommended constructor, and checks the gradient against a value calculated by hand.
import torch
x = torch.tensor([[1., 2., 3.],
[4., 5., 6.]], requires_grad=True) # leaf, tracked
w = torch.tensor([[7., 8., 9.],
[10., 11., 12.]]) # leaf, not tracked
y = (x * w).mean()
print(y) # tensor(36.1667, grad_fn=<MeanBackward0>)
print(x.is_leaf, y.is_leaf) # True False
y.backward()
print(x.grad)
# tensor([[1.1667, 1.3333, 1.5000],
# [1.6667, 1.8333, 2.0000]])
# d(mean(x*w))/dx = w / number_of_elements
print(torch.allclose(x.grad, w / x.numel())) # True
print(w.grad) # None, because w does not require gradCode language: PHP (php)
The gradient is w / 6 because mean divides the sum of six products by 6, and the derivative of x_i * w_i with respect to x_i is w_i. The same reasoning explains 0.25 in the second part of the notebook: (tensor_one + tensor_two).mean() averages four elements, so each element's derivative is 1/4.
Note: The number at the end of a backward node name, as in MeanBackward0 or MeanBackward1, depends on which overload of the operation ran and on the PyTorch version. Recent releases show MeanBackward0 for a full .mean(), while the notebook shows MeanBackward1. Neither changes the result.
grad_fn links to the whole graph, not only the last operation
The notebook says that the gradient function only contains the last operation. That is misleading. grad_fn is the last node of the graph, but each node keeps references to the nodes before it through next_functions, so autograd still has the complete history. That is why backward() can reach tensor1 through both the mean and the multiplication.
print(y.grad_fn)
# <MeanBackward0 object at 0x...>
print(y.grad_fn.next_functions)
# ((<MulBackward0 object at 0x...>, 0),)
print(y.grad_fn.next_functions[0][0].next_functions)
# ((<AccumulateGrad object at 0x...>, 0), (None, 0))Code language: CSS (css)
AccumulateGrad is the node that writes into x.grad. The None entry belongs to w. It does not require gradients, so the graph has no path back to it.
Gradients accumulate: the 0.5 in the detach example
In the last cells of the notebook, tensor_one.grad shows 0.5 after (tensor_one + detached_tensor).mean().backward(). That result does not mean the detached tensor contributed a gradient. The gradient of that expression with respect to tensor_one is 0.25 per element. The extra 0.25 is left over from the earlier final_tensor.backward() call, because backward() adds to .grad rather than replacing it.
a = torch.tensor([[1., 2.], [3., 4.]], requires_grad=True)
a.mean().backward()
print(a.grad) # all 0.25
a.mean().backward()
print(a.grad) # all 0.50, because the two calls were added together
a.grad = None # or a.grad.zero_()
a.mean().backward()
print(a.grad) # all 0.25 againCode language: PHP (php)
In a training loop, gradients are reset once per batch with optimizer.zero_grad() before loss.backward(). If you forget this step, each update uses the sum of gradients from every batch so far, and training usually diverges or behaves strangely.
Leaf tensors, non-leaf tensors and retain_grad
The notebook prints None for output_tensor.grad and final_tensor.grad. This is expected, because autograd fills .grad only for leaf tensors, which saves memory. Recent PyTorch versions also print a UserWarning when you read .grad on a non-leaf tensor. If you need an intermediate gradient for debugging, call retain_grad() before running backward().
x = torch.tensor([1., 2., 3.], requires_grad=True)
h = x * 2
h.retain_grad() # keep the gradient of this intermediate tensor
out = h.sum()
out.backward()
print(h.grad) # tensor([1., 1., 1.])
print(x.grad) # tensor([2., 2., 2.])Code language: PHP (php)
backward() without arguments works only on a scalar. For a tensor with more than one element, either reduce it first with sum() or mean(), or pass a gradient of the same shape, as in v.backward(torch.ones_like(v)).
Choosing how to turn off tracking
| Tool | What it does | Use it for |
|---|---|---|
torch.no_grad() | Results created inside the block do not record history. Leaf flags stay as they are. | Evaluation loops and manual weight updates |
torch.inference_mode() | Like no_grad but with lower overhead. Tensors created inside it cannot be used later in autograd. | Pure inference and serving |
tensor.detach() | Returns a tensor that shares the same data but is outside the graph | Logging, plotting, or stopping gradients through one branch |
requires_grad_(False) | Stops tracking a leaf tensor permanently | Freezing layers during fine-tuning |
torch.enable_grad() | Turns tracking back on inside a no_grad block | Rare cases such as computing a gradient during evaluation |
Note: model.eval() does not disable gradients. It only changes the behaviour of layers such as dropout and batch normalisation. For inference, use model.eval() together with torch.no_grad() or torch.inference_mode().
detach() shares storage with the original tensor, so an in-place change to the detached tensor also changes the original. Use t.detach().clone() when you need an independent copy. To convert a tracked tensor to NumPy, use t.detach().cpu().numpy().
Common autograd errors
| Error message (abridged) | Cause | Fix |
|---|---|---|
grad can be implicitly created only for scalar outputs | backward() was called on a tensor with more than one element | Reduce it with sum() or mean(), or pass gradient=torch.ones_like(t) |
element 0 of tensors does not require grad and does not have a grad_fn | No input in the graph had requires_grad=True, or the result was computed under no_grad | Set requires_grad=True on the leaf tensors and compute outside no_grad |
Trying to backward through the graph a second time | The graph's saved buffers are freed after the first backward() | Rebuild the graph by recomputing the forward pass, or pass retain_graph=True if you really need a second pass |
only Tensors of floating point and complex dtype can require gradients | torch.tensor([[1, 2]], requires_grad=True) creates an integer tensor | Use float literals such as 1. or pass dtype=torch.float32 |
a leaf Variable that requires grad is being used in an in-place operation | An in-place operation such as x += 1 was run on a tracked leaf | Wrap manual updates in torch.no_grad() or use an out-of-place operation |
Can't call numpy() on Tensor that requires grad | Converting a tracked tensor directly | Use t.detach().numpy() |
Corrections to the notebook
- The note that the gradient function "only contains the last operation" is misleading.
grad_fnis the last node, but it links to every earlier node throughnext_functions, so the full graph is kept. - The
0.5gradient in the detach example comes from accumulation with the earlierbackward()call. Resettensor_one.grad = Nonebefore that cell and you will see0.25, which is the actual gradient of that expression. - In the
torch.no_grad()cell, both lines are labelledrequires_grad for tensor =. The second line printstensor2.requires_grad. - The notebook mixes the legacy
torch.Tensor(...)constructor withtorch.tensor(...). Prefertorch.tensor(..., dtype=torch.float32)or float literals, becausetorch.tensorinfers and preserves the dtype. - Backward node names such as
MeanBackward1vary between PyTorch versions. Current releases showMeanBackward0for a full.mean().
Frequently asked questions
Why is .grad None after I call backward()?
.grad is filled in only for leaf tensors that have requires_grad=True. Intermediate results get None unless you call retain_grad() on them before backward(), and tensors that never required gradients always stay None.
Why do my gradients keep growing between iterations?
PyTorch adds new gradients to the existing .grad instead of overwriting it. Call optimizer.zero_grad(), or set param.grad = None, before each backward() call.
What is the difference between torch.no_grad() and detach()?
torch.no_grad() stops recording for every operation inside the block. detach() removes a single tensor from the graph and leaves recording on for everything else. The detached tensor shares memory with the original.
Should I use torch.no_grad() or torch.inference_mode() for inference?
Both prevent graph construction. inference_mode has lower overhead, but tensors created inside it cannot be used in autograd later, so use it only for pure inference and use no_grad everywhere else.
Can integer tensors require gradients?
No. Only floating-point and complex tensors can require gradients, so create inputs with float values or pass dtype=torch.float32.
Related tutorials
- More Machine Learning tutorials
- Lead Machine Learning Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path
- Staff MLOps Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals