\n",
" \n",
"

\n",
"\"\"\"\n",
"display(HTML(html_code))"
]
},
{
"cell_type": "markdown",
"id": "533fe238",
"metadata": {},
"source": [
"\n",
"\n",
"PyTorch's *Autograd* feature is part of what make PyTorch flexible and\n",
"fast for building machine learning projects. It allows for the rapid and\n",
"easy computation of multiple partial derivatives (also referred to as\n",
"*gradients)* over a complex computation. This operation is central to\n",
"backpropagation-based neural network learning.\n",
"\n",
"The power of autograd comes from the fact that it traces your\n",
"computation dynamically *at runtime,* meaning that if your model has\n",
"decision branches, or loops whose lengths are not known until runtime,\n",
"the computation will still be traced correctly, and you'll get correct\n",
"gradients to drive learning. This, combined with the fact that your\n",
"models are built in Python, offers far more flexibility than frameworks\n",
"that rely on static analysis of a more rigidly-structured model for\n",
"computing gradients.\n",
"\n",
"What Do We Need Autograd For?\n",
"-----------------------------\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A machine learning model is a *function*, with inputs and outputs. For\n",
"this discussion, we'll treat the inputs as an *i*-dimensional vector\n",
"$\\vec{x}$, with elements $x_{i}$. We can then express the model, *M*, as\n",
"a vector-valued function of the input: $\\vec{y} =\n",
"\\vec{M}(\\vec{x})$. (We treat the value of M's output as a vector because\n",
"in general, a model may have any number of outputs.)\n",
"\n",
"Since we'll mostly be discussing autograd in the context of training,\n",
"our output of interest will be the model's loss. The *loss function*\n",
"L($\\vec{y}$) = L($\\vec{M}$($\\vec{x}$)) is a single-valued scalar\n",
"function of the model's output. This function expresses how far off our\n",
"model's prediction was from a particular input's *ideal* output. *Note:\n",
"After this point, we will often omit the vector sign where it should be\n",
"contextually clear - e.g.,* $y$ instead of $\\vec y$.\n",
"\n",
"In training a model, we want to minimize the loss. In the idealized case\n",
"of a perfect model, that means adjusting its learning weights - that is,\n",
"the adjustable parameters of the function - such that loss is zero for\n",
"all inputs. In the real world, it means an iterative process of nudging\n",
"the learning weights until we see that we get a tolerable loss for a\n",
"wide variety of inputs.\n",
"\n",
"How do we decide how far and in which direction to nudge the weights? We\n",
"want to *minimize* the loss, which means making its first derivative\n",
"with respect to the input equal to 0:\n",
"$\\frac{\\partial L}{\\partial x} = 0$.\n",
"\n",
"Recall, though, that the loss is not *directly* derived from the input,\n",
"but a function of the model's output (which is a function of the input\n",
"directly), $\\frac{\\partial L}{\\partial x}$ =\n",
"$\\frac{\\partial {L({\\vec y})}}{\\partial x}$. By the chain rule of\n",
"differential calculus, we have\n",
"$\\frac{\\partial {L({\\vec y})}}{\\partial x}$ =\n",
"$\\frac{\\partial L}{\\partial y}\\frac{\\partial y}{\\partial x}$ =\n",
"$\\frac{\\partial L}{\\partial y}\\frac{\\partial M(x)}{\\partial x}$.\n",
"\n",
"$\\frac{\\partial M(x)}{\\partial x}$ is where things get complex. The\n",
"partial derivatives of the model's outputs with respect to its inputs,\n",
"if we were to expand the expression using the chain rule again, would\n",
"involve many local partial derivatives over every multiplied learning\n",
"weight, every activation function, and every other mathematical\n",
"transformation in the model. The full expression for each such partial\n",
"derivative is the sum of the products of the local gradient of *every\n",
"possible path* through the computation graph that ends with the variable\n",
"whose gradient we are trying to measure.\n",
"\n",
"In particular, the gradients over the learning weights are of interest\n",
"to us - they tell us *what direction to change each weight* to get the\n",
"loss function closer to zero.\n",
"\n",
"Since the number of such local derivatives (each corresponding to a\n",
"separate path through the model's computation graph) will tend to go up\n",
"exponentially with the depth of a neural network, so does the complexity\n",
"in computing them. This is where autograd comes in: It tracks the\n",
"history of every computation. Every computed tensor in your PyTorch\n",
"model carries a history of its input tensors and the function used to\n",
"create it. Combined with the fact that PyTorch functions meant to act on\n",
"tensors each have a built-in implementation for computing their own\n",
"derivatives, this greatly speeds the computation of the local\n",
"derivatives needed for learning.\n",
"\n",
"A Simple Example\n",
"================\n",
"\n",
"That was a lot of theory - but what does it look like to use autograd in\n",
"practice?\n",
"\n",
"Let's start with a straightforward example. First, we'll do some imports\n",
"to let us graph our results:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# %matplotlib inline\n",
"\n",
"import torch\n",
"\n",
"import matplotlib.pyplot as plt\n",
"import matplotlib.ticker as ticker\n",
"import math"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Next, we'll create an input tensor full of evenly spaced values on the\n",
"interval $[0, 2{\\pi}]$, and specify `requires_grad=True`. (Like most\n",
"functions that create tensors, `torch.linspace()` accepts an optional\n",
"`requires_grad` option.) Setting this flag means that in every\n",
"computation that follows, autograd will be accumulating the history of\n",
"the computation in the output tensors of that computation.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"a = torch.linspace(0., 2. * math.pi, steps=25, requires_grad=True)\n",
"print(a)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Next, we'll perform a computation, and plot its output in terms of its\n",
"inputs:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"b = torch.sin(a)\n",
"plt.plot(a.detach(), b.detach())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's have a closer look at the tensor `b`. When we print it, we see an\n",
"indicator that it is tracking its computation history:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"print(b)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This `grad_fn` gives us a hint that when we execute the backpropagation\n",
"step and compute gradients, we'll need to compute the derivative of\n",
"$\\sin(x)$ for all this tensor's inputs.\n",
"\n",
"Let's perform some more computations:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"c = 2 * b\n",
"print(c)\n",
"\n",
"d = c + 1\n",
"print(d)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Finally, let's compute a single-element output. When you call\n",
"`.backward()` on a tensor with no arguments, it expects the calling\n",
"tensor to contain only a single element, as is the case when computing a\n",
"loss function.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"out = d.sum()\n",
"print(out)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Each `grad_fn` stored with our tensors allows you to walk the\n",
"computation all the way back to its inputs with its `next_functions`\n",
"property. We can see below that drilling down on this property on `d`\n",
"shows us the gradient functions for all the prior tensors. Note that\n",
"`a.grad_fn` is reported as `None`, indicating that this was an input to\n",
"the function with no history of its own.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"print('d:')\n",
"print(d.grad_fn)\n",
"print(d.grad_fn.next_functions)\n",
"print(d.grad_fn.next_functions[0][0].next_functions)\n",
"print(d.grad_fn.next_functions[0][0].next_functions[0][0].next_functions)\n",
"print(d.grad_fn.next_functions[0][0].next_functions[0][0].next_functions[0][0].next_functions)\n",
"print('\\nc:')\n",
"print(c.grad_fn)\n",
"print('\\nb:')\n",
"print(b.grad_fn)\n",
"print('\\na:')\n",
"print(a.grad_fn)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"With all this machinery in place, how do we get derivatives out? You\n",
"call the `backward()` method on the output, and check the input's `grad`\n",
"property to inspect the gradients:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"out.backward()\n",
"print(a.grad)\n",
"plt.plot(a.detach(), a.grad.detach())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Recall the computation steps we took to get here:\n",
"\n",
"``` {.sourceCode .python}\n",
"a = torch.linspace(0., 2. * math.pi, steps=25, requires_grad=True)\n",
"b = torch.sin(a)\n",
"c = 2 * b\n",
"d = c + 1\n",
"out = d.sum()\n",
"```\n",
"\n",
"Adding a constant, as we did to compute `d`, does not change the\n",
"derivative. That leaves $c = 2 * b = 2 * \\sin(a)$, the derivative of\n",
"which should be $2 * \\cos(a)$. Looking at the graph above, that's just\n",
"what we see.\n",
"\n",
"Be aware that only *leaf nodes* of the computation have their gradients\n",
"computed. If you tried, for example, `print(c.grad)` you'd get back\n",
"`None`. In this simple example, only the input is a leaf node, so only\n",
"it has gradients computed.\n",
"\n",
"Autograd in Training\n",
"====================\n",
"\n",
"We've had a brief look at how autograd works, but how does it look when\n",
"it's used for its intended purpose? Let's define a small model and\n",
"examine how it changes after a single training batch. First, define a\n",
"few constants, our model, and some stand-ins for inputs and outputs:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"BATCH_SIZE = 16\n",
"DIM_IN = 1000\n",
"HIDDEN_SIZE = 100\n",
"DIM_OUT = 10\n",
"\n",
"class TinyModel(torch.nn.Module):\n",
"\n",
" def __init__(self):\n",
" super(TinyModel, self).__init__()\n",
" \n",
" self.layer1 = torch.nn.Linear(DIM_IN, HIDDEN_SIZE)\n",
" self.relu = torch.nn.ReLU()\n",
" self.layer2 = torch.nn.Linear(HIDDEN_SIZE, DIM_OUT)\n",
" \n",
" def forward(self, x):\n",
" x = self.layer1(x)\n",
" x = self.relu(x)\n",
" x = self.layer2(x)\n",
" return x\n",
" \n",
"some_input = torch.randn(BATCH_SIZE, DIM_IN, requires_grad=False)\n",
"ideal_output = torch.randn(BATCH_SIZE, DIM_OUT, requires_grad=False)\n",
"\n",
"model = TinyModel()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"One thing you might notice is that we never specify `requires_grad=True`\n",
"for the model's layers. Within a subclass of `torch.nn.Module`, it's\n",
"assumed that we want to track gradients on the layers' weights for\n",
"learning.\n",
"\n",
"If we look at the layers of the model, we can examine the values of the\n",
"weights, and verify that no gradients have been computed yet:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"print(model.layer2.weight[0][0:10]) # just a small slice\n",
"print(model.layer2.weight.grad)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's see how this changes when we run through one training batch. For a\n",
"loss function, we'll just use the square of the Euclidean distance\n",
"between our `prediction` and the `ideal_output`, and we'll use a basic\n",
"stochastic gradient descent optimizer.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"optimizer = torch.optim.SGD(model.parameters(), lr=0.001)\n",
"\n",
"prediction = model(some_input)\n",
"\n",
"loss = (ideal_output - prediction).pow(2).sum()\n",
"print(loss)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now, let's call `loss.backward()` and see what happens:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"loss.backward()\n",
"print(model.layer2.weight[0][0:10])\n",
"print(model.layer2.weight.grad[0][0:10])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can see that the gradients have been computed for each learning\n",
"weight, but the weights remain unchanged, because we haven't run the\n",
"optimizer yet. The optimizer is responsible for updating model weights\n",
"based on the computed gradients.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"optimizer.step()\n",
"print(model.layer2.weight[0][0:10])\n",
"print(model.layer2.weight.grad[0][0:10])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You should see that `layer2`'s weights have changed.\n",
"\n",
"One important thing about the process: After calling `optimizer.step()`,\n",
"you need to call `optimizer.zero_grad()`, or else every time you run\n",
"`loss.backward()`, the gradients on the learning weights will\n",
"accumulate:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"print(model.layer2.weight.grad[0][0:10])\n",
"\n",
"for i in range(0, 5):\n",
" prediction = model(some_input)\n",
" loss = (ideal_output - prediction).pow(2).sum()\n",
" loss.backward()\n",
" \n",
"print(model.layer2.weight.grad[0][0:10])\n",
"\n",
"optimizer.zero_grad(set_to_none=False)\n",
"\n",
"print(model.layer2.weight.grad[0][0:10])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"After running the cell above, you should see that after running\n",
"`loss.backward()` multiple times, the magnitudes of most of the\n",
"gradients will be much larger. Failing to zero the gradients before\n",
"running your next training batch will cause the gradients to blow up in\n",
"this manner, causing incorrect and unpredictable learning results.\n",
"\n",
"Turning Autograd Off and On\n",
"===========================\n",
"\n",
"There are situations where you will need fine-grained control over\n",
"whether autograd is enabled. There are multiple ways to do this,\n",
"depending on the situation.\n",
"\n",
"The simplest is to change the `requires_grad` flag on a tensor directly:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"a = torch.ones(2, 3, requires_grad=True)\n",
"print(a)\n",
"\n",
"b1 = 2 * a\n",
"print(b1)\n",
"\n",
"a.requires_grad = False\n",
"b2 = 2 * a\n",
"print(b2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In the cell above, we see that `b1` has a `grad_fn` (i.e., a traced\n",
"computation history), which is what we expect, since it was derived from\n",
"a tensor, `a`, that had autograd turned on. When we turn off autograd\n",
"explicitly with `a.requires_grad = False`, computation history is no\n",
"longer tracked, as we see when we compute `b2`.\n",
"\n",
"If you only need autograd turned off temporarily, a better way is to use\n",
"the `torch.no_grad()`:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"a = torch.ones(2, 3, requires_grad=True) * 2\n",
"b = torch.ones(2, 3, requires_grad=True) * 3\n",
"\n",
"c1 = a + b\n",
"print(c1)\n",
"\n",
"with torch.no_grad():\n",
" c2 = a + b\n",
"\n",
"print(c2)\n",
"\n",
"c3 = a * b\n",
"print(c3)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`torch.no_grad()` can also be used as a function or method decorator:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"def add_tensors1(x, y):\n",
" return x + y\n",
"\n",
"@torch.no_grad()\n",
"def add_tensors2(x, y):\n",
" return x + y\n",
"\n",
"\n",
"a = torch.ones(2, 3, requires_grad=True) * 2\n",
"b = torch.ones(2, 3, requires_grad=True) * 3\n",
"\n",
"c1 = add_tensors1(a, b)\n",
"print(c1)\n",
"\n",
"c2 = add_tensors2(a, b)\n",
"print(c2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There's a corresponding context manager, `torch.enable_grad()`, for\n",
"turning autograd on when it isn't already. It may also be used as a\n",
"decorator.\n",
"\n",
"Finally, you may have a tensor that requires gradient tracking, but you\n",
"want a copy that does not. For this we have the `Tensor` object's\n",
"`detach()` method - it creates a copy of the tensor that is *detached*\n",
"from the computation history:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"x = torch.rand(5, requires_grad=True)\n",
"y = x.detach()\n",
"\n",
"print(x)\n",
"print(y)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We did this above when we wanted to graph some of our tensors. This is\n",
"because `matplotlib` expects a NumPy array as input, and the implicit\n",
"conversion from a PyTorch tensor to a NumPy array is not enabled for\n",
"tensors with requires\\_grad=True. Making a detached copy lets us move\n",
"forward.\n",
"\n",
"Autograd and In-place Operations\n",
"================================\n",
"\n",
"In every example in this notebook so far, we've used variables to\n",
"capture the intermediate values of a computation. Autograd needs these\n",
"intermediate values to perform gradient computations. *For this reason,\n",
"you must be careful about using in-place operations when using\n",
"autograd.* Doing so can destroy information you need to compute\n",
"derivatives in the `backward()` call. PyTorch will even stop you if you\n",
"attempt an in-place operation on leaf variable that requires autograd,\n",
"as shown below.\n",
"\n",
"\n",
"

\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Autograd Profiler\n",
"=================\n",
"\n",
"Autograd tracks every step of your computation in detail. Such a\n",
"computation history, combined with timing information, would make a\n",
"handy profiler - and autograd has that feature baked in. Here's a quick\n",
"example usage:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"device = torch.device('cpu')\n",
"run_on_gpu = False\n",
"if torch.cuda.is_available():\n",
" device = torch.device('cuda')\n",
" run_on_gpu = True\n",
" \n",
"x = torch.randn(2, 3, requires_grad=True)\n",
"y = torch.rand(2, 3, requires_grad=True)\n",
"z = torch.ones(2, 3, requires_grad=True)\n",
"\n",
"with torch.autograd.profiler.profile(use_cuda=run_on_gpu) as prf:\n",
" for _ in range(1000):\n",
" z = (z / x) * y\n",
" \n",
"print(prf.key_averages().table(sort_by='self_cpu_time_total'))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The profiler can also label individual sub-blocks of code, break out the\n",
"data by input tensor shape, and export data as a Chrome tracing tools\n",
"file. For full details of the API, see the\n",
"[documentation](https://pytorch.org/docs/stable/autograd.html#profiler).\n",
"\n",
"Advanced Topic: More Autograd Detail and the High-Level API\n",
"===========================================================\n",
"\n",
"If you have a function with an n-dimensional input and m-dimensional\n",
"output, $\\vec{y}=f(\\vec{x})$, the complete gradient is a matrix of the\n",
"derivative of every output with respect to every input, called the\n",
"*Jacobian:*\n",
"\n",
"$$\\begin{aligned}\n",
"J\n",
"=\n",
"\\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",
"If you have a second function, $l=g\\left(\\vec{y}\\right)$ that takes\n",
"m-dimensional input (that is, the same dimensionality as the output\n",
"above), and returns a scalar output, you can express its gradients with\n",
"respect to $\\vec{y}$ as a column vector,\n",
"$v=\\left(\\begin{array}{ccc}\\frac{\\partial l}{\\partial y_{1}} & \\cdots & \\frac{\\partial l}{\\partial y_{m}}\\end{array}\\right)^{T}$\n",
"- which is really just a one-column Jacobian.\n",
"\n",
"More concretely, imagine the first function as your PyTorch model (with\n",
"potentially many inputs and many outputs) and the second function as a\n",
"loss function (with the model's output as input, and the loss value as\n",
"the scalar output).\n",
"\n",
"If we multiply the first function's Jacobian by the gradient of the\n",
"second function, and apply the chain rule, we get:\n",
"\n",
"$$\\begin{aligned}\n",
"J^{T}\\cdot v=\\left(\\begin{array}{ccc}\n",
"\\frac{\\partial y_{1}}{\\partial x_{1}} & \\cdots & \\frac{\\partial y_{m}}{\\partial x_{1}}\\\\\n",
"\\vdots & \\ddots & \\vdots\\\\\n",
"\\frac{\\partial y_{1}}{\\partial x_{n}} & \\cdots & \\frac{\\partial y_{m}}{\\partial x_{n}}\n",
"\\end{array}\\right)\\left(\\begin{array}{c}\n",
"\\frac{\\partial l}{\\partial y_{1}}\\\\\n",
"\\vdots\\\\\n",
"\\frac{\\partial l}{\\partial y_{m}}\n",
"\\end{array}\\right)=\\left(\\begin{array}{c}\n",
"\\frac{\\partial l}{\\partial x_{1}}\\\\\n",
"\\vdots\\\\\n",
"\\frac{\\partial l}{\\partial x_{n}}\n",
"\\end{array}\\right)\n",
"\\end{aligned}$$\n",
"\n",
"Note: You could also use the equivalent operation $v^{T}\\cdot J$, and\n",
"get back a row vector.\n",
"\n",
"The resulting column vector is the *gradient of the second function with\n",
"respect to the inputs of the first* - or in the case of our model and\n",
"loss function, the gradient of the loss with respect to the model\n",
"inputs.\n",
"\n",
"**\\`\\`torch.autograd\\`\\` is an engine for computing these products.**\n",
"This is how we accumulate the gradients over the learning weights during\n",
"the backward pass.\n",
"\n",
"For this reason, the `backward()` call can *also* take an optional\n",
"vector input. This vector represents a set of gradients over the tensor,\n",
"which are multiplied by the Jacobian of the autograd-traced tensor that\n",
"precedes it. Let's try a specific example with a small vector:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"x = torch.randn(3, requires_grad=True)\n",
"\n",
"y = x * 2\n",
"while y.data.norm() < 1000:\n",
" y = y * 2\n",
"\n",
"print(y)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If we tried to call `y.backward()` now, we'd get a runtime error and a\n",
"message that gradients can only be *implicitly* computed for scalar\n",
"outputs. For a multi-dimensional output, autograd expects us to provide\n",
"gradients for those three outputs that it can multiply into the\n",
"Jacobian:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"v = torch.tensor([0.1, 1.0, 0.0001], dtype=torch.float) # stand-in for gradients\n",
"y.backward(v)\n",
"\n",
"print(x.grad)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"(Note that the output gradients are all related to powers of two - which\n",
"we'd expect from a repeated doubling operation.)\n",
"\n",
"The High-Level API\n",
"==================\n",
"\n",
"There is an API on autograd that gives you direct access to important\n",
"differential matrix and vector operations. In particular, it allows you\n",
"to calculate the Jacobian and the *Hessian* matrices of a particular\n",
"function for particular inputs. (The Hessian is like the Jacobian, but\n",
"expresses all partial *second* derivatives.) It also provides methods\n",
"for taking vector products with these matrices.\n",
"\n",
"Let's take the Jacobian of a simple function, evaluated for a 2\n",
"single-element inputs:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"def exp_adder(x, y):\n",
" return 2 * x.exp() + 3 * y\n",
"\n",
"inputs = (torch.rand(1), torch.rand(1)) # arguments for the function\n",
"print(inputs)\n",
"torch.autograd.functional.jacobian(exp_adder, inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If you look closely, the first output should equal $2e^x$ (since the\n",
"derivative of $e^x$ is $e^x$), and the second value should be 3.\n",
"\n",
"You can, of course, do this with higher-order tensors:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"inputs = (torch.rand(3), torch.rand(3)) # arguments for the function\n",
"print(inputs)\n",
"torch.autograd.functional.jacobian(exp_adder, inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The `torch.autograd.functional.hessian()` method works identically\n",
"(assuming your function is twice differentiable), but returns a matrix\n",
"of all second derivatives.\n",
"\n",
"There is also a function to directly compute the vector-Jacobian\n",
"product, if you provide the vector:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"def do_some_doubling(x):\n",
" y = x * 2\n",
" while y.data.norm() < 1000:\n",
" y = y * 2\n",
" return y\n",
"\n",
"inputs = torch.randn(3)\n",
"my_gradients = torch.tensor([0.1, 1.0, 0.0001])\n",
"torch.autograd.functional.vjp(do_some_doubling, inputs, v=my_gradients)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The `torch.autograd.functional.jvp()` method performs the same matrix\n",
"multiplication as `vjp()` with the operands reversed. The `vhp()` and\n",
"`hvp()` methods do the same for a vector-Hessian product.\n",
"\n",
"For more information, including performance notes on the [docs for the\n",
"functional\n",
"API](https://pytorch.org/docs/stable/autograd.html#functional-higher-level-api)\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.14"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
The following code cell throws a runtime error. This is expected.

```
a = torch.linspace(0., 2. * math.pi, steps=25, requires_grad=True)\n",
"torch.sin_(a)
```

\n",
"