\n",
"\n",
"

\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",
"\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": [
"You can set the value of `requires_grad`

when creating atensor, or later by using `x.requires_grad_(True)`

method.

\n",
"\n",
"

\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Disabling Gradient Tracking\n",
"===========================\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",
"\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",
"- \n",
"
- We can only obtain the
`grad`

properties for the leafnodes of the computational graph, which have`requires_grad`

propertyset to`True`

. For all other nodes in our graph, gradients will not beavailable.- We can only perform gradient calculations using`backward`

once on a given graph, for performance reasons. If we needto do several`backward`

calls on the same graph, we need to pass`retain_graph=True`

to the`backward`

call. \n",
"

\n",
"\n",
"

\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Optional Reading: Tensor Gradients and Jacobian Products\n",
"========================================================\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": [
"An important thing to note is that the graph is recreated from scratch; after each`.backward()`

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.

\n",
"\n",
"

\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"------------------------------------------------------------------------\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Further Reading\n",
"===============\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.10.12"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Previously we were calling `backward()`

function withoutparameters. This is essentially equivalent to calling`backward(torch.tensor(1.0))`

, which is a useful way to compute thegradients in case of a scalar-valued function, such as loss duringneural network training.