{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# For tips on running notebooks in Google Colab, see\n",
    "# https://docs.pytorch.org/tutorials/beginner/colab\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[Learn the Basics](intro.html) \\|\\|\n",
    "[Quickstart](quickstart_tutorial.html) \\|\\|\n",
    "[Tensors](tensorqs_tutorial.html) \\|\\| [Datasets &\n",
    "DataLoaders](data_tutorial.html) \\|\\|\n",
    "[Transforms](transforms_tutorial.html) \\|\\| [Build\n",
    "Model](buildmodel_tutorial.html) \\|\\| **Autograd** \\|\\|\n",
    "[Optimization](optimization_tutorial.html) \\|\\| [Save & Load\n",
    "Model](saveloadrun_tutorial.html)\n",
    "\n",
    "# Automatic Differentiation with `torch.autograd`\n",
    "\n",
    "When training neural networks, the most frequently used algorithm is\n",
    "**back propagation**. In this algorithm, parameters (model weights) are\n",
    "adjusted according to the **gradient** of the loss function with respect\n",
    "to the given parameter.\n",
    "\n",
    "To compute those gradients, PyTorch has a built-in differentiation\n",
    "engine called `torch.autograd`. It supports automatic computation of\n",
    "gradient for any computational graph.\n",
    "\n",
    "Consider the simplest one-layer neural network, with input `x`,\n",
    "parameters `w` and `b`, and some loss function. It can be defined in\n",
    "PyTorch in the following manner:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "\n",
    "x = torch.ones(5)  # input tensor\n",
    "y = torch.zeros(3)  # expected output\n",
    "w = torch.randn(5, 3, requires_grad=True)\n",
    "b = torch.randn(3, requires_grad=True)\n",
    "z = torch.matmul(x, w)+b\n",
    "loss = torch.nn.functional.binary_cross_entropy_with_logits(z, y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Tensors, Functions and Computational graph\n",
    "\n",
    "This code defines the following **computational graph**:\n",
    "\n",
    "![/\\_static/img/basics/comp-graph.png](https://pytorch.org/tutorials/_static/img/basics/comp-graph.png)\n",
    "\n",
    "In this network, `w` and `b` are **parameters**, which we need to\n",
    "optimize. Thus, we need to be able to compute the gradients of loss\n",
    "function with respect to those variables. In order to do that, we set\n",
    "the `requires_grad` property of those tensors.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"background-color: #54c7ec; color: #fff; font-weight: 700; padding-left: 10px; padding-top: 5px; padding-bottom: 5px\"><strong>NOTE:</strong></div>\n",
    "\n",
    "<div style=\"background-color: #f3f4f7; padding-left: 10px; padding-top: 10px; padding-bottom: 10px; padding-right: 10px\">\n",
    "\n",
    "<p>You can set the value of <code>requires_grad</code> when creating atensor, or later by using <code>x.requires_grad_(True)</code> method.</p>\n",
    "\n",
    "</div>\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A function that we apply to tensors to construct computational graph is\n",
    "in fact an object of class `Function`. This object knows how to compute\n",
    "the function in the *forward* direction, and also how to compute its\n",
    "derivative during the *backward propagation* step. A reference to the\n",
    "backward propagation function is stored in `grad_fn` property of a\n",
    "tensor. You can find more information of `Function` [in the\n",
    "documentation](https://pytorch.org/docs/stable/autograd.html#function).\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "print(f\"Gradient function for z = {z.grad_fn}\")\n",
    "print(f\"Gradient function for loss = {loss.grad_fn}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Computing Gradients\n",
    "\n",
    "To optimize weights of parameters in the neural network, we need to\n",
    "compute the derivatives of our loss function with respect to parameters,\n",
    "namely, we need $\\frac{\\partial loss}{\\partial w}$ and\n",
    "$\\frac{\\partial loss}{\\partial b}$ under some fixed values of `x` and\n",
    "`y`. To compute those derivatives, we call `loss.backward()`, and then\n",
    "retrieve the values from `w.grad` and `b.grad`:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "loss.backward()\n",
    "print(w.grad)\n",
    "print(b.grad)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"background-color: #54c7ec; color: #fff; font-weight: 700; padding-left: 10px; padding-top: 5px; padding-bottom: 5px\"><strong>NOTE:</strong></div>\n",
    "\n",
    "<div style=\"background-color: #f3f4f7; padding-left: 10px; padding-top: 10px; padding-bottom: 10px; padding-right: 10px\">\n",
    "\n",
    "<ul>\n",
    "<li>We can only obtain the <code>grad</code> properties for the leafnodes of the computational graph, which have <code>requires_grad</code> propertyset to <code>True</code>. For all other nodes in our graph, gradients will not beavailable.- We can only perform gradient calculations using<code>backward</code> once on a given graph, for performance reasons. If we needto do several <code>backward</code> calls on the same graph, we need to pass<code>retain_graph=True</code> to the <code>backward</code> call.</li>\n",
    "</ul>\n",
    "```\n",
    "\n",
    "</div>\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Disabling Gradient Tracking\n",
    "\n",
    "By default, all tensors with `requires_grad=True` are tracking their\n",
    "computational history and support gradient computation. However, there\n",
    "are some cases when we do not need to do that, for example, when we have\n",
    "trained the model and just want to apply it to some input data, i.e. we\n",
    "only want to do *forward* computations through the network. We can stop\n",
    "tracking computations by surrounding our computation code with\n",
    "`torch.no_grad()` block:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "z = torch.matmul(x, w)+b\n",
    "print(z.requires_grad)\n",
    "\n",
    "with torch.no_grad():\n",
    "    z = torch.matmul(x, w)+b\n",
    "print(z.requires_grad)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Another way to achieve the same result is to use the `detach()` method\n",
    "on the tensor:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "z = torch.matmul(x, w)+b\n",
    "z_det = z.detach()\n",
    "print(z_det.requires_grad)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There are reasons you might want to disable gradient tracking:\n",
    "\n",
    ":   -   To mark some parameters in your neural network as **frozen\n",
    "        parameters**.\n",
    "    -   To **speed up computations** when you are only doing forward\n",
    "        pass, because computations on tensors that do not track\n",
    "        gradients would be more efficient.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# More on Computational Graphs\n",
    "\n",
    "Conceptually, autograd keeps a record of data (tensors) and all executed\n",
    "operations (along with the resulting new tensors) in a directed acyclic\n",
    "graph (DAG) consisting of\n",
    "[Function](https://pytorch.org/docs/stable/autograd.html#torch.autograd.Function)\n",
    "objects. In this DAG, leaves are the input tensors, roots are the output\n",
    "tensors. By tracing this graph from roots to leaves, you can\n",
    "automatically compute the gradients using the chain rule.\n",
    "\n",
    "In a forward pass, autograd does two things simultaneously:\n",
    "\n",
    "-   run the requested operation to compute a resulting tensor\n",
    "-   maintain the operation's *gradient function* in the DAG.\n",
    "\n",
    "The backward pass kicks off when `.backward()` is called on the DAG\n",
    "root. `autograd` then:\n",
    "\n",
    "-   computes the gradients from each `.grad_fn`,\n",
    "-   accumulates them in the respective tensor's `.grad` attribute\n",
    "-   using the chain rule, propagates all the way to the leaf tensors.\n",
    "\n",
    "<div style=\"background-color: #54c7ec; color: #fff; font-weight: 700; padding-left: 10px; padding-top: 5px; padding-bottom: 5px\"><strong>NOTE:</strong></div>\n",
    "\n",
    "<div style=\"background-color: #f3f4f7; padding-left: 10px; padding-top: 10px; padding-bottom: 10px; padding-right: 10px\">\n",
    "\n",
    "<p>An important thing to note is that the graph is recreated from scratch; after each<code>.backward()</code> call, autograd starts populating a new graph. This isexactly what allows you to use control flow statements in your model;you can change the shape, size and operations at every iteration ifneeded.</p>\n",
    "\n",
    "</div>\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Optional Reading: Tensor Gradients and Jacobian Products\n",
    "\n",
    "In many cases, we have a scalar loss function, and we need to compute\n",
    "the gradient with respect to some parameters. However, there are cases\n",
    "when the output function is an arbitrary tensor. In this case, PyTorch\n",
    "allows you to compute so-called **Jacobian product**, and not the actual\n",
    "gradient.\n",
    "\n",
    "For a vector function $\\vec{y}=f(\\vec{x})$, where\n",
    "$\\vec{x}=\\langle x_1,\\dots,x_n\\rangle$ and\n",
    "$\\vec{y}=\\langle y_1,\\dots,y_m\\rangle$, a gradient of $\\vec{y}$ with\n",
    "respect to $\\vec{x}$ is given by **Jacobian matrix**:\n",
    "\n",
    "$$\\begin{aligned}\n",
    "J=\\left(\\begin{array}{ccc}\n",
    "   \\frac{\\partial y_{1}}{\\partial x_{1}} & \\cdots & \\frac{\\partial y_{1}}{\\partial x_{n}}\\\\\n",
    "   \\vdots & \\ddots & \\vdots\\\\\n",
    "   \\frac{\\partial y_{m}}{\\partial x_{1}} & \\cdots & \\frac{\\partial y_{m}}{\\partial x_{n}}\n",
    "   \\end{array}\\right)\n",
    "\\end{aligned}$$\n",
    "\n",
    "Instead of computing the Jacobian matrix itself, PyTorch allows you to\n",
    "compute **Jacobian Product** $v^T\\cdot J$ for a given input vector\n",
    "$v=(v_1 \\dots v_m)$. This is achieved by calling `backward` with $v$ as\n",
    "an argument. The size of $v$ should be the same as the size of the\n",
    "original tensor, with respect to which we want to compute the product:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "inp = torch.eye(4, 5, requires_grad=True)\n",
    "out = (inp+1).pow(2).t()\n",
    "out.backward(torch.ones_like(out), retain_graph=True)\n",
    "print(f\"First call\\n{inp.grad}\")\n",
    "out.backward(torch.ones_like(out), retain_graph=True)\n",
    "print(f\"\\nSecond call\\n{inp.grad}\")\n",
    "inp.grad.zero_()\n",
    "out.backward(torch.ones_like(out), retain_graph=True)\n",
    "print(f\"\\nCall after zeroing gradients\\n{inp.grad}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Notice that when we call `backward` for the second time with the same\n",
    "argument, the value of the gradient is different. This happens because\n",
    "when doing `backward` propagation, PyTorch **accumulates the\n",
    "gradients**, i.e. the value of computed gradients is added to the `grad`\n",
    "property of all leaf nodes of computational graph. If you want to\n",
    "compute the proper gradients, you need to zero out the `grad` property\n",
    "before. In real-life training an *optimizer* helps us to do this.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"background-color: #54c7ec; color: #fff; font-weight: 700; padding-left: 10px; padding-top: 5px; padding-bottom: 5px\"><strong>NOTE:</strong></div>\n",
    "\n",
    "<div style=\"background-color: #f3f4f7; padding-left: 10px; padding-top: 10px; padding-bottom: 10px; padding-right: 10px\">\n",
    "\n",
    "<p>Previously we were calling <code>backward()</code> function withoutparameters. This is essentially equivalent to calling<code>backward(torch.tensor(1.0))</code>, which is a useful way to compute thegradients in case of a scalar-valued function, such as loss duringneural network training.</p>\n",
    "\n",
    "</div>\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "------------------------------------------------------------------------\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Further Reading\n",
    "\n",
    "-   [Autograd\n",
    "    Mechanics](https://pytorch.org/docs/stable/notes/autograd.html)\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
