{ "cells": [ { "cell_type": "markdown", "id": "b4873f83", "metadata": { "origin_pos": 0 }, "source": [ "# 自动微分\n", ":label:`sec_autograd`\n", "\n", "正如 :numref:`sec_calculus`中所说,求导是几乎所有深度学习优化算法的关键步骤。\n", "虽然求导的计算很简单,只需要一些基本的微积分。\n", "但对于复杂的模型,手工进行更新是一件很痛苦的事情(而且经常容易出错)。\n", "\n", "深度学习框架通过自动计算导数,即*自动微分*(automatic differentiation)来加快求导。\n", "实际中,根据设计好的模型,系统会构建一个*计算图*(computational graph),\n", "来跟踪计算是哪些数据通过哪些操作组合起来产生输出。\n", "自动微分使系统能够随后反向传播梯度。\n", "这里,*反向传播*(backpropagate)意味着跟踪整个计算图,填充关于每个参数的偏导数。\n", "\n", "## 一个简单的例子\n", "\n", "作为一个演示例子,(**假设我们想对函数$y=2\\mathbf{x}^{\\top}\\mathbf{x}$关于列向量$\\mathbf{x}$求导**)。\n", "首先,我们创建变量`x`并为其分配一个初始值。\n" ] }, { "cell_type": "code", "execution_count": 1, "id": "98cd8a9e", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T07:07:31.627945Z", "iopub.status.busy": "2023-08-18T07:07:31.627424Z", "iopub.status.idle": "2023-08-18T07:07:32.686372Z", "shell.execute_reply": "2023-08-18T07:07:32.685559Z" }, "origin_pos": 2, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "tensor([0., 1., 2., 3.])" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import torch\n", "\n", "x = torch.arange(4.0)\n", "x" ] }, { "cell_type": "markdown", "id": "ec430520", "metadata": { "origin_pos": 5 }, "source": [ "[**在我们计算$y$关于$\\mathbf{x}$的梯度之前,需要一个地方来存储梯度。**]\n", "重要的是,我们不会在每次对一个参数求导时都分配新的内存。\n", "因为我们经常会成千上万次地更新相同的参数,每次都分配新的内存可能很快就会将内存耗尽。\n", "注意,一个标量函数关于向量$\\mathbf{x}$的梯度是向量,并且与$\\mathbf{x}$具有相同的形状。\n" ] }, { "cell_type": "code", "execution_count": 2, "id": "e27a5df4", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T07:07:32.690633Z", "iopub.status.busy": "2023-08-18T07:07:32.689882Z", "iopub.status.idle": "2023-08-18T07:07:32.694159Z", "shell.execute_reply": "2023-08-18T07:07:32.693367Z" }, "origin_pos": 7, "tab": [ "pytorch" ] }, "outputs": [], "source": [ "x.requires_grad_(True) # 等价于x=torch.arange(4.0,requires_grad=True)\n", "x.grad # 默认值是None" ] }, { "cell_type": "markdown", "id": "bd993524", "metadata": { "origin_pos": 10 }, "source": [ "(**现在计算$y$。**)\n" ] }, { "cell_type": "code", "execution_count": 3, "id": "4c3f80b7", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T07:07:32.698006Z", "iopub.status.busy": "2023-08-18T07:07:32.697167Z", "iopub.status.idle": "2023-08-18T07:07:32.705385Z", "shell.execute_reply": "2023-08-18T07:07:32.704593Z" }, "origin_pos": 12, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "tensor(28., grad_fn=)" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "y = 2 * torch.dot(x, x)\n", "y" ] }, { "cell_type": "markdown", "id": "35523dbc", "metadata": { "origin_pos": 15 }, "source": [ "`x`是一个长度为4的向量,计算`x`和`x`的点积,得到了我们赋值给`y`的标量输出。\n", "接下来,[**通过调用反向传播函数来自动计算`y`关于`x`每个分量的梯度**],并打印这些梯度。\n" ] }, { "cell_type": "code", "execution_count": 4, "id": "a1c3a419", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T07:07:32.708698Z", "iopub.status.busy": "2023-08-18T07:07:32.708196Z", "iopub.status.idle": "2023-08-18T07:07:32.713924Z", "shell.execute_reply": "2023-08-18T07:07:32.713091Z" }, "origin_pos": 17, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "tensor([ 0., 4., 8., 12.])" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "y.backward()\n", "x.grad" ] }, { "cell_type": "markdown", "id": "dca6a271", "metadata": { "origin_pos": 20 }, "source": [ "函数$y=2\\mathbf{x}^{\\top}\\mathbf{x}$关于$\\mathbf{x}$的梯度应为$4\\mathbf{x}$。\n", "让我们快速验证这个梯度是否计算正确。\n" ] }, { "cell_type": "code", "execution_count": 5, "id": "b8493d0a", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T07:07:32.718858Z", "iopub.status.busy": "2023-08-18T07:07:32.718156Z", "iopub.status.idle": "2023-08-18T07:07:32.724091Z", "shell.execute_reply": "2023-08-18T07:07:32.723104Z" }, "origin_pos": 22, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "tensor([True, True, True, True])" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x.grad == 4 * x" ] }, { "cell_type": "markdown", "id": "2733c623", "metadata": { "origin_pos": 25 }, "source": [ "[**现在计算`x`的另一个函数。**]\n" ] }, { "cell_type": "code", "execution_count": 6, "id": "f2fcd392", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T07:07:32.729368Z", "iopub.status.busy": "2023-08-18T07:07:32.728433Z", "iopub.status.idle": "2023-08-18T07:07:32.736493Z", "shell.execute_reply": "2023-08-18T07:07:32.735715Z" }, "origin_pos": 27, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "tensor([1., 1., 1., 1.])" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 在默认情况下,PyTorch会累积梯度,我们需要清除之前的值\n", "x.grad.zero_()\n", "y = x.sum()\n", "y.backward()\n", "x.grad" ] }, { "cell_type": "markdown", "id": "58f4f459", "metadata": { "origin_pos": 30 }, "source": [ "## 非标量变量的反向传播\n", "\n", "当`y`不是标量时,向量`y`关于向量`x`的导数的最自然解释是一个矩阵。\n", "对于高阶和高维的`y`和`x`,求导的结果可以是一个高阶张量。\n", "\n", "然而,虽然这些更奇特的对象确实出现在高级机器学习中(包括[**深度学习中**]),\n", "但当调用向量的反向计算时,我们通常会试图计算一批训练样本中每个组成部分的损失函数的导数。\n", "这里(**,我们的目的不是计算微分矩阵,而是单独计算批量中每个样本的偏导数之和。**)\n" ] }, { "cell_type": "code", "execution_count": 7, "id": "f4e62a5d", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T07:07:32.740109Z", "iopub.status.busy": "2023-08-18T07:07:32.739419Z", "iopub.status.idle": "2023-08-18T07:07:32.745803Z", "shell.execute_reply": "2023-08-18T07:07:32.744893Z" }, "origin_pos": 32, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "tensor([0., 2., 4., 6.])" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 对非标量调用backward需要传入一个gradient参数,该参数指定微分函数关于self的梯度。\n", "# 本例只想求偏导数的和,所以传递一个1的梯度是合适的\n", "x.grad.zero_()\n", "y = x * x\n", "# 等价于y.backward(torch.ones(len(x)))\n", "y.sum().backward()\n", "x.grad" ] }, { "cell_type": "markdown", "id": "80f510c4", "metadata": { "origin_pos": 35 }, "source": [ "## 分离计算\n", "\n", "有时,我们希望[**将某些计算移动到记录的计算图之外**]。\n", "例如,假设`y`是作为`x`的函数计算的,而`z`则是作为`y`和`x`的函数计算的。\n", "想象一下,我们想计算`z`关于`x`的梯度,但由于某种原因,希望将`y`视为一个常数,\n", "并且只考虑到`x`在`y`被计算后发挥的作用。\n", "\n", "这里可以分离`y`来返回一个新变量`u`,该变量与`y`具有相同的值,\n", "但丢弃计算图中如何计算`y`的任何信息。\n", "换句话说,梯度不会向后流经`u`到`x`。\n", "因此,下面的反向传播函数计算`z=u*x`关于`x`的偏导数,同时将`u`作为常数处理,\n", "而不是`z=x*x*x`关于`x`的偏导数。\n" ] }, { "cell_type": "code", "execution_count": 8, "id": "8dab493d", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T07:07:32.749398Z", "iopub.status.busy": "2023-08-18T07:07:32.748759Z", "iopub.status.idle": "2023-08-18T07:07:32.755280Z", "shell.execute_reply": "2023-08-18T07:07:32.754543Z" }, "origin_pos": 37, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "tensor([True, True, True, True])" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x.grad.zero_()\n", "y = x * x\n", "u = y.detach()\n", "z = u * x\n", "\n", "z.sum().backward()\n", "x.grad == u" ] }, { "cell_type": "markdown", "id": "f8fe6f9c", "metadata": { "origin_pos": 40 }, "source": [ "由于记录了`y`的计算结果,我们可以随后在`y`上调用反向传播,\n", "得到`y=x*x`关于的`x`的导数,即`2*x`。\n" ] }, { "cell_type": "code", "execution_count": 9, "id": "271a9b3a", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T07:07:32.759344Z", "iopub.status.busy": "2023-08-18T07:07:32.758633Z", "iopub.status.idle": "2023-08-18T07:07:32.764663Z", "shell.execute_reply": "2023-08-18T07:07:32.763922Z" }, "origin_pos": 42, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "tensor([True, True, True, True])" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x.grad.zero_()\n", "y.sum().backward()\n", "x.grad == 2 * x" ] }, { "cell_type": "markdown", "id": "fd79d12f", "metadata": { "origin_pos": 45 }, "source": [ "## Python控制流的梯度计算\n", "\n", "使用自动微分的一个好处是:\n", "[**即使构建函数的计算图需要通过Python控制流(例如,条件、循环或任意函数调用),我们仍然可以计算得到的变量的梯度**]。\n", "在下面的代码中,`while`循环的迭代次数和`if`语句的结果都取决于输入`a`的值。\n" ] }, { "cell_type": "code", "execution_count": 10, "id": "6323b2ff", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T07:07:32.769249Z", "iopub.status.busy": "2023-08-18T07:07:32.768616Z", "iopub.status.idle": "2023-08-18T07:07:32.773175Z", "shell.execute_reply": "2023-08-18T07:07:32.772293Z" }, "origin_pos": 47, "tab": [ "pytorch" ] }, "outputs": [], "source": [ "def f(a):\n", " b = a * 2\n", " while b.norm() < 1000:\n", " b = b * 2\n", " if b.sum() > 0:\n", " c = b\n", " else:\n", " c = 100 * b\n", " return c" ] }, { "cell_type": "markdown", "id": "51aaf333", "metadata": { "origin_pos": 50 }, "source": [ "让我们计算梯度。\n" ] }, { "cell_type": "code", "execution_count": 11, "id": "7719d6b6", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T07:07:32.777740Z", "iopub.status.busy": "2023-08-18T07:07:32.777207Z", "iopub.status.idle": "2023-08-18T07:07:32.782254Z", "shell.execute_reply": "2023-08-18T07:07:32.781458Z" }, "origin_pos": 52, "tab": [ "pytorch" ] }, "outputs": [], "source": [ "a = torch.randn(size=(), requires_grad=True)\n", "d = f(a)\n", "d.backward()" ] }, { "cell_type": "markdown", "id": "816a1ac2", "metadata": { "origin_pos": 55 }, "source": [ "我们现在可以分析上面定义的`f`函数。\n", "请注意,它在其输入`a`中是分段线性的。\n", "换言之,对于任何`a`,存在某个常量标量`k`,使得`f(a)=k*a`,其中`k`的值取决于输入`a`,因此可以用`d/a`验证梯度是否正确。\n" ] }, { "cell_type": "code", "execution_count": 12, "id": "2595bdc0", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T07:07:32.785728Z", "iopub.status.busy": "2023-08-18T07:07:32.785179Z", "iopub.status.idle": "2023-08-18T07:07:32.790672Z", "shell.execute_reply": "2023-08-18T07:07:32.789892Z" }, "origin_pos": 57, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "tensor(True)" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a.grad == d / a" ] }, { "cell_type": "markdown", "id": "67fb5517", "metadata": { "origin_pos": 60 }, "source": [ "## 小结\n", "\n", "* 深度学习框架可以自动计算导数:我们首先将梯度附加到想要对其计算偏导数的变量上,然后记录目标值的计算,执行它的反向传播函数,并访问得到的梯度。\n", "\n", "## 练习\n", "\n", "1. 为什么计算二阶导数比一阶导数的开销要更大?\n", "1. 在运行反向传播函数之后,立即再次运行它,看看会发生什么。\n", "1. 在控制流的例子中,我们计算`d`关于`a`的导数,如果将变量`a`更改为随机向量或矩阵,会发生什么?\n", "1. 重新设计一个求控制流梯度的例子,运行并分析结果。\n", "1. 使$f(x)=\\sin(x)$,绘制$f(x)$和$\\frac{df(x)}{dx}$的图像,其中后者不使用$f'(x)=\\cos(x)$。\n" ] }, { "cell_type": "markdown", "id": "530f74f8", "metadata": { "origin_pos": 62, "tab": [ "pytorch" ] }, "source": [ "[Discussions](https://discuss.d2l.ai/t/1759)\n" ] } ], "metadata": { "language_info": { "name": "python" }, "required_libs": [] }, "nbformat": 4, "nbformat_minor": 5 }