{"id":47571,"date":"2026-11-23T22:06:08","date_gmt":"2026-11-23T22:06:08","guid":{"rendered":"https:\/\/www.devopsschool.com\/blog\/?p=47571"},"modified":"2026-11-23T22:06:08","modified_gmt":"2026-11-23T22:06:08","slug":"pytorch-lab-6-pytorch-autograd-with-variables","status":"publish","type":"post","link":"https:\/\/www.devopsschool.com\/blog\/pytorch-lab-6-pytorch-autograd-with-variables\/","title":{"rendered":"PyTorch Lab &#8211; 6 &#8211; Pytorch Autograd With Variables"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">This lab uses PyTorch autograd to calculate gradients through a single multiplication, <code>result = var * w1<\/code>, using the older <code>torch.autograd.Variable<\/code> wrapper. Below you&#039;ll find what each cell does and the correct gradients on a clean run (<code>w1.grad = 9<\/code>, <code>var.grad = 3<\/code>). 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 <code>backward()<\/code>.<\/p>\n\n\n\n<script src=\"https:\/\/gist.github.com\/devops-school\/30167dc1dea213ef4fbad4afd2c0c480.js\"><\/script>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">What the notebook demonstrates<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Autograd is PyTorch&#039;s automatic differentiation engine. When a tensor has <code>requires_grad=True<\/code>, PyTorch records every operation applied to it in a computation graph. Calling <code>.backward()<\/code> 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&#039;s <code>.grad<\/code> attribute.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The example above builds a tiny graph: <code>var = 9<\/code>, <code>w1 = 3<\/code>, and <code>result_var = var * w1 = 27<\/code>. The derivatives are simple: d(result)\/d(w1) = var = 9 and d(result)\/d(var) = w1 = 3. <code>w2<\/code> is created but never used in any operation, so it never receives a gradient.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The markdown note in the notebook is correct: <code>Variable(...)<\/code> returns an ordinary <code>torch.Tensor<\/code>. Since PyTorch 0.4, <code>Variable<\/code> and <code>Tensor<\/code> have been merged. Tensors now carry <code>requires_grad<\/code>, <code>.grad<\/code> and <code>grad_fn<\/code> themselves, and <code>Variable<\/code> survives only as a deprecated compatibility wrapper.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Expected results on a clean run<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">If you restart the kernel and run every cell once, top to bottom, you should get these outputs:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Cell<\/th><th>Output<\/th><th>Why<\/th><\/tr><\/thead><tbody><tr><td><code>var<\/code><\/td><td><code>tensor([9.])<\/code><\/td><td>A plain float tensor. Gradients are off by default.<\/td><\/tr><tr><td><code>var.requires_grad<\/code><\/td><td><code>False<\/code><\/td><td>Tensors don&#039;t track gradients unless you ask them to.<\/td><\/tr><tr><td><code>var.requires_grad_()<\/code><\/td><td><code>tensor([9.], requires_grad=True)<\/code><\/td><td>The trailing underscore means the change is made in place.<\/td><\/tr><tr><td><code>result_var<\/code><\/td><td><code>tensor([27.], grad_fn=&lt;MulBackward0&gt;)<\/code><\/td><td><code>grad_fn<\/code> records the operation that produced the tensor.<\/td><\/tr><tr><td><code>result_var.requires_grad<\/code><\/td><td><code>True<\/code><\/td><td>The result needs gradients because at least one input does.<\/td><\/tr><tr><td><code>w1.grad<\/code><\/td><td><code>tensor([9.])<\/code><\/td><td>d(var*w1)\/d(w1) = var = 9<\/td><\/tr><tr><td><code>var.grad<\/code><\/td><td><code>tensor([3.])<\/code><\/td><td>d(var*w1)\/d(var) = w1 = 3<\/td><\/tr><tr><td><code>w2.grad<\/code><\/td><td><code>None<\/code> (nothing is displayed)<\/td><td><code>w2<\/code> is not part of the graph.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Why the notebook shows 18 and 6<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The saved notebook shows <code>w1.grad = tensor([18.])<\/code> and <code>var.grad = tensor([6.])<\/code>, 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 <code>backward()<\/code> were run twice.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">PyTorch <strong>accumulates<\/strong> gradients: each <code>backward()<\/code> call adds to whatever is already stored in <code>.grad<\/code> instead of replacing it. The first run stored 9 and 3. The second run, on a freshly built <code>result_var<\/code>, added another 9 and 3.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">result_var = <span class=\"hljs-keyword\">var<\/span> * w1\nresult_var.backward()\n<span class=\"hljs-keyword\">print<\/span>(w1.grad)   <span class=\"hljs-comment\"># tensor(&#91;9.])<\/span>\n\nresult_var = <span class=\"hljs-keyword\">var<\/span> * w1   <span class=\"hljs-comment\"># rebuild the graph<\/span>\nresult_var.backward()\n<span class=\"hljs-keyword\">print<\/span>(w1.grad)   <span class=\"hljs-comment\"># tensor(&#91;18.])  &lt;- accumulated<\/span>\n\n<span class=\"hljs-comment\"># Reset before the next backward pass<\/span>\nw1.grad = None          <span class=\"hljs-comment\"># or w1.grad.zero_()<\/span>\n<span class=\"hljs-keyword\">var<\/span>.grad = None<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> Accumulation is intentional. It lets you add up gradients across several mini-batches. In a training loop, call <code>optimizer.zero_grad()<\/code> (or set each <code>.grad<\/code> to <code>None<\/code>) once per step so gradients from different steps don&#039;t mix.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">The same lab in current PyTorch<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In new code, don&#039;t use <code>Variable<\/code> or the legacy <code>torch.FloatTensor<\/code> constructor. Use <code>torch.tensor<\/code> with a float value and set <code>requires_grad<\/code> directly. Install PyTorch with <code>pip install torch<\/code> (and <code>pip install notebook<\/code> if you want to run it in Jupyter). Recent PyTorch releases need a newer Python than the 3.7 kernel recorded in the notebook.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">import torch\n\nx = torch.tensor(&#91;<span class=\"hljs-number\">9.0<\/span>])\n<span class=\"hljs-keyword\">print<\/span>(x.requires_grad)        <span class=\"hljs-comment\"># False<\/span>\nx.requires_grad_()            <span class=\"hljs-comment\"># turn on gradient tracking in place<\/span>\n\nw1 = torch.tensor(&#91;<span class=\"hljs-number\">3.0<\/span>], requires_grad=<span class=\"hljs-keyword\">True<\/span>)\nw2 = torch.tensor(&#91;<span class=\"hljs-number\">7.0<\/span>], requires_grad=<span class=\"hljs-keyword\">True<\/span>)\n\ny = x * w1\n<span class=\"hljs-keyword\">print<\/span>(y)                      <span class=\"hljs-comment\"># tensor(&#91;27.], grad_fn=&lt;MulBackward0&gt;)<\/span>\n<span class=\"hljs-keyword\">print<\/span>(y.requires_grad)        <span class=\"hljs-comment\"># True<\/span>\n\ny.backward()                  <span class=\"hljs-comment\"># y has one element, so no gradient argument is needed<\/span>\n\n<span class=\"hljs-keyword\">print<\/span>(w1.grad)                <span class=\"hljs-comment\"># tensor(&#91;9.])<\/span>\n<span class=\"hljs-keyword\">print<\/span>(x.grad)                 <span class=\"hljs-comment\"># tensor(&#91;3.])<\/span>\n<span class=\"hljs-keyword\">print<\/span>(w2.grad)                <span class=\"hljs-comment\"># None<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">Each line does the same thing as the original notebook. The only differences are the constructor and the absence of the wrapper. <code>.backward()<\/code> without arguments works here only because <code>y<\/code> contains a single element.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Extending the lab: putting w2 to use<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">To see the chain rule at work, add <code>w2<\/code> to the graph. For <code>z = x * w1 * w2<\/code>, each input&#039;s gradient is the product of the other two values.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">import torch\n\nx  = torch.tensor(&#91;<span class=\"hljs-number\">9.0<\/span>], requires_grad=<span class=\"hljs-keyword\">True<\/span>)\nw1 = torch.tensor(&#91;<span class=\"hljs-number\">3.0<\/span>], requires_grad=<span class=\"hljs-keyword\">True<\/span>)\nw2 = torch.tensor(&#91;<span class=\"hljs-number\">7.0<\/span>], requires_grad=<span class=\"hljs-keyword\">True<\/span>)\n\nh = x * w1          <span class=\"hljs-comment\"># 27, an intermediate (non-leaf) tensor<\/span>\nz = h * w2          <span class=\"hljs-comment\"># 189<\/span>\nz.backward()\n\n<span class=\"hljs-keyword\">print<\/span>(z)            <span class=\"hljs-comment\"># tensor(&#91;189.], grad_fn=&lt;MulBackward0&gt;)<\/span>\n<span class=\"hljs-keyword\">print<\/span>(x.grad)       <span class=\"hljs-comment\"># tensor(&#91;21.])  = w1 * w2<\/span>\n<span class=\"hljs-keyword\">print<\/span>(w1.grad)      <span class=\"hljs-comment\"># tensor(&#91;63.])  = x * w2<\/span>\n<span class=\"hljs-keyword\">print<\/span>(w2.grad)      <span class=\"hljs-comment\"># tensor(&#91;27.])  = x * w1<\/span>\n<span class=\"hljs-keyword\">print<\/span>(h.is_leaf)    <span class=\"hljs-comment\"># False, so h.grad is None unless you call h.retain_grad() before backward()<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">Common errors and fixes<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Error or symptom<\/th><th>Cause<\/th><th>Fix<\/th><\/tr><\/thead><tbody><tr><td><code>RuntimeError: Trying to backward through the graph a second time<\/code><\/td><td>PyTorch frees the graph after <code>backward()<\/code>, and you called it again on the same result.<\/td><td>Rebuild the result before calling <code>backward()<\/code> again, or use <code>backward(retain_graph=True)<\/code> if you really need a second pass.<\/td><\/tr><tr><td><code>RuntimeError: grad can be implicitly created only for scalar outputs<\/code><\/td><td>You called <code>backward()<\/code> on a tensor with more than one element.<\/td><td>Reduce it first, for example <code>y.sum().backward()<\/code>, or pass a matching <code>gradient=<\/code> tensor.<\/td><\/tr><tr><td><code>RuntimeError: Only Tensors of floating point and complex dtype can require gradients<\/code><\/td><td>You set <code>requires_grad<\/code> on an integer tensor such as <code>torch.tensor([9])<\/code>.<\/td><td>Use a float value (<code>9.0<\/code>) or <code>dtype=torch.float32<\/code>.<\/td><\/tr><tr><td><code>RuntimeError: a leaf Variable that requires grad is being used in an in-place operation<\/code><\/td><td>You updated a weight in place, such as <code>w1 -= 0.1 * w1.grad<\/code>, while autograd was recording.<\/td><td>Make the update inside <code>with torch.no_grad():<\/code>, or use an optimizer.<\/td><\/tr><tr><td><code>.grad<\/code> is <code>None<\/code><\/td><td>The tensor is not part of the graph, or it is a non-leaf tensor.<\/td><td>Check that it feeds into the output. For intermediate tensors, call <code>.retain_grad()<\/code> before <code>backward()<\/code>.<\/td><\/tr><tr><td>Gradients keep growing<\/td><td>Gradients accumulate across <code>backward()<\/code> calls.<\/td><td>Zero them every step with <code>optimizer.zero_grad()<\/code> or by setting <code>.grad = None<\/code>.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Best practices<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use plain tensors with <code>requires_grad=True<\/code>. Treat <code>Variable<\/code> as legacy code you may still come across in old tutorials.<\/li>\n\n\n<li>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.<\/li>\n\n\n<li>Wrap inference and manual weight updates in <code>torch.no_grad()<\/code> (or <code>torch.inference_mode()<\/code> for inference) to save memory and avoid accidental graph building.<\/li>\n\n\n<li>Use <code>tensor.detach()<\/code> when you need a value without its gradient history, for example for logging or plotting.<\/li>\n\n\n<li>Clear gradients once per training step, before the next <code>backward()<\/code> call.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Frequently asked questions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Is torch.autograd.Variable deprecated?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. Since PyTorch 0.4, <code>Variable<\/code> and <code>Tensor<\/code> have been merged, and <code>Variable(t)<\/code> simply returns a tensor. New code should use <code>torch.tensor(..., requires_grad=True)<\/code> directly.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is the difference between requires_grad=True and requires_grad_()?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><code>requires_grad=True<\/code> turns on gradient tracking when you create the tensor. <code>requires_grad_()<\/code> turns it on in place for a tensor that already exists. Both mark a leaf tensor so that autograd stores its gradient in <code>.grad<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why does my gradient double every time I run backward()?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">PyTorch adds each new gradient to the value already stored in <code>.grad<\/code> instead of replacing it. Reset it with <code>optimizer.zero_grad()<\/code>, <code>tensor.grad.zero_()<\/code> or <code>tensor.grad = None<\/code> before each new backward pass.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why is w2.grad None in this lab?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><code>w2<\/code> is never used to compute <code>result_var<\/code>, so it isn&#039;t part of the computation graph and receives no gradient. Gradients only reach leaf tensors that contribute to the output.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What does grad_fn=&lt;MulBackward0&gt; mean?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">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 <code>grad_fn=None<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Related tutorials<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/category\/artificial-intelligence\/machine-learning\/\">More Machine Learning tutorials<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/senior-machine-learning-scientist-role-blueprint-responsibilities-skills-kpis-and-career-path\/\">Senior Machine Learning Scientist: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/staff-mlops-engineer-role-blueprint-responsibilities-skills-kpis-and-career-path\/\">Staff MLOps Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>This lab uses PyTorch autograd to calculate gradients through a single multiplication, result = var * w1, using the older torch.autograd.Variable wrapper. Below you&#039;ll find what each&#8230; <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"","sticky":false,"template":"","format":"standard","meta":{"_joinchat":[],"footnotes":""},"categories":[6512],"tags":[7364],"class_list":["post-47571","post","type-post","status-publish","format-standard","hentry","category-machine-learning","tag-pytorch"],"_links":{"self":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/47571","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/comments?post=47571"}],"version-history":[{"count":2,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/47571\/revisions"}],"predecessor-version":[{"id":80170,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/47571\/revisions\/80170"}],"wp:attachment":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/media?parent=47571"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/categories?post=47571"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/tags?post=47571"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}