MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

PyTorch Lab – 6 – Pytorch Autograd With Variables

This lab uses PyTorch autograd to calculate gradients through a single multiplication, result = var * w1, using the older torch.autograd.Variable wrapper. Below you'll find what each cell does and the correct gradients on a clean run (w1.grad = 9, var.grad = 3). It also explains why the notebook shows 18 and 6, gives the same lab rewritten for current PyTorch, and covers the errors that come up most often with backward().


What the notebook demonstrates

Autograd is PyTorch's automatic differentiation engine. When a tensor has requires_grad=True, PyTorch records every operation applied to it in a computation graph. Calling .backward() on a scalar result walks that graph in reverse and stores the derivative of the result with respect to each leaf tensor in that tensor's .grad attribute.

The example above builds a tiny graph: var = 9, w1 = 3, and result_var = var * w1 = 27. The derivatives are simple: d(result)/d(w1) = var = 9 and d(result)/d(var) = w1 = 3. w2 is created but never used in any operation, so it never receives a gradient.

The markdown note in the notebook is correct: Variable(...) returns an ordinary torch.Tensor. Since PyTorch 0.4, Variable and Tensor have been merged. Tensors now carry requires_grad, .grad and grad_fn themselves, and Variable survives only as a deprecated compatibility wrapper.

Expected results on a clean run

If you restart the kernel and run every cell once, top to bottom, you should get these outputs:

CellOutputWhy
vartensor([9.])A plain float tensor. Gradients are off by default.
var.requires_gradFalseTensors don't track gradients unless you ask them to.
var.requires_grad_()tensor([9.], requires_grad=True)The trailing underscore means the change is made in place.
result_vartensor([27.], grad_fn=<MulBackward0>)grad_fn records the operation that produced the tensor.
result_var.requires_gradTrueThe result needs gradients because at least one input does.
w1.gradtensor([9.])d(var*w1)/d(w1) = var = 9
var.gradtensor([3.])d(var*w1)/d(var) = w1 = 3
w2.gradNone (nothing is displayed)w2 is not part of the graph.

Why the notebook shows 18 and 6

The saved notebook shows w1.grad = tensor([18.]) and var.grad = tensor([6.]), which are exactly double the correct values. The execution counters explain why. They jump from 44 to 50, so the cells that build the graph and call backward() were run twice.

PyTorch accumulates gradients: each backward() call adds to whatever is already stored in .grad instead of replacing it. The first run stored 9 and 3. The second run, on a freshly built result_var, added another 9 and 3.

result_var = var * w1
result_var.backward()
print(w1.grad)   # tensor([9.])

result_var = var * w1   # rebuild the graph
result_var.backward()
print(w1.grad)   # tensor([18.])  <- accumulated

# Reset before the next backward pass
w1.grad = None          # or w1.grad.zero_()
var.grad = NoneCode language: PHP (php)

Note: Accumulation is intentional. It lets you add up gradients across several mini-batches. In a training loop, call optimizer.zero_grad() (or set each .grad to None) once per step so gradients from different steps don't mix.

The same lab in current PyTorch

In new code, don't use Variable or the legacy torch.FloatTensor constructor. Use torch.tensor with a float value and set requires_grad directly. Install PyTorch with pip install torch (and pip install notebook if you want to run it in Jupyter). Recent PyTorch releases need a newer Python than the 3.7 kernel recorded in the notebook.

import torch

x = torch.tensor([9.0])
print(x.requires_grad)        # False
x.requires_grad_()            # turn on gradient tracking in place

w1 = torch.tensor([3.0], requires_grad=True)
w2 = torch.tensor([7.0], requires_grad=True)

y = x * w1
print(y)                      # tensor([27.], grad_fn=<MulBackward0>)
print(y.requires_grad)        # True

y.backward()                  # y has one element, so no gradient argument is needed

print(w1.grad)                # tensor([9.])
print(x.grad)                 # tensor([3.])
print(w2.grad)                # NoneCode language: PHP (php)

Each line does the same thing as the original notebook. The only differences are the constructor and the absence of the wrapper. .backward() without arguments works here only because y contains a single element.

Extending the lab: putting w2 to use

To see the chain rule at work, add w2 to the graph. For z = x * w1 * w2, each input's gradient is the product of the other two values.

import torch

x  = torch.tensor([9.0], requires_grad=True)
w1 = torch.tensor([3.0], requires_grad=True)
w2 = torch.tensor([7.0], requires_grad=True)

h = x * w1          # 27, an intermediate (non-leaf) tensor
z = h * w2          # 189
z.backward()

print(z)            # tensor([189.], grad_fn=<MulBackward0>)
print(x.grad)       # tensor([21.])  = w1 * w2
print(w1.grad)      # tensor([63.])  = x * w2
print(w2.grad)      # tensor([27.])  = x * w1
print(h.is_leaf)    # False, so h.grad is None unless you call h.retain_grad() before backward()Code language: PHP (php)

Common errors and fixes

Error or symptomCauseFix
RuntimeError: Trying to backward through the graph a second timePyTorch frees the graph after backward(), and you called it again on the same result.Rebuild the result before calling backward() again, or use backward(retain_graph=True) if you really need a second pass.
RuntimeError: grad can be implicitly created only for scalar outputsYou called backward() on a tensor with more than one element.Reduce it first, for example y.sum().backward(), or pass a matching gradient= tensor.
RuntimeError: Only Tensors of floating point and complex dtype can require gradientsYou set requires_grad on an integer tensor such as torch.tensor([9]).Use a float value (9.0) or dtype=torch.float32.
RuntimeError: a leaf Variable that requires grad is being used in an in-place operationYou updated a weight in place, such as w1 -= 0.1 * w1.grad, while autograd was recording.Make the update inside with torch.no_grad():, or use an optimizer.
.grad is NoneThe tensor is not part of the graph, or it is a non-leaf tensor.Check that it feeds into the output. For intermediate tensors, call .retain_grad() before backward().
Gradients keep growingGradients accumulate across backward() calls.Zero them every step with optimizer.zero_grad() or by setting .grad = None.

Best practices

  • Use plain tensors with requires_grad=True. Treat Variable as legacy code you may still come across in old tutorials.
  • Restart the kernel and run all cells before trusting notebook output. Cells run out of order can silently double gradients, as happened in this notebook.
  • Wrap inference and manual weight updates in torch.no_grad() (or torch.inference_mode() for inference) to save memory and avoid accidental graph building.
  • Use tensor.detach() when you need a value without its gradient history, for example for logging or plotting.
  • Clear gradients once per training step, before the next backward() call.

Frequently asked questions

Is torch.autograd.Variable deprecated?

Yes. Since PyTorch 0.4, Variable and Tensor have been merged, and Variable(t) simply returns a tensor. New code should use torch.tensor(..., requires_grad=True) directly.

What is the difference between requires_grad=True and requires_grad_()?

requires_grad=True turns on gradient tracking when you create the tensor. requires_grad_() turns it on in place for a tensor that already exists. Both mark a leaf tensor so that autograd stores its gradient in .grad.

Why does my gradient double every time I run backward()?

PyTorch adds each new gradient to the value already stored in .grad instead of replacing it. Reset it with optimizer.zero_grad(), tensor.grad.zero_() or tensor.grad = None before each new backward pass.

Why is w2.grad None in this lab?

w2 is never used to compute result_var, so it isn't part of the computation graph and receives no gradient. Gradients only reach leaf tensors that contribute to the output.

What does grad_fn=<MulBackward0> mean?

It names the backward function autograd recorded for the operation that created the tensor, which here is multiplication. Tensors you create yourself (leaf tensors) have grad_fn=None.

Related tutorials

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
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.

Related Posts

PyTorch Lab – 9 – Pytorch CUDA Semantics

This lab covers how PyTorch builds a computation graph on the fly as tensor operations run, and how that graph behaves when tensors and models are on…

Read More

PyTorch Lab – 8 – Pytorch Install And Setup Tensorflow Hidden Layer

This lab sets up HiddenLayer, a small Python library that draws neural network graphs and plots training metrics, along with the Graphviz bindings it uses to render…

Read More

PyTorch Lab – 7 – Pytorch CUDA Semantics

This page covers a PyTorch lab notebook that fits a linear regression model with autograd and manual gradient descent. The title mentions CUDA, but the notebook above…

Read More

PyTorch Lab – 5 – Pytorch AutogradIntro

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…

Read More

PyTorch Lab – 3 – Pytorch Conversions Between PyTorch And NumPy

This lab shows how to convert data between PyTorch tensors and NumPy arrays using tensor.numpy(), torch.from_numpy(), torch.as_tensor() and torch.tensor(). The main point is memory: the first three…

Read More

PyTorch Lab -4 – Pytorch CUDA Semantics

This lab covers how PyTorch places tensors on GPUs: device objects, the current device, moving tensors between the CPU and GPUs, and how the CUDA caching allocator…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x