This commit is contained in:
2025-12-16 09:23:53 +08:00
parent 19138d3cc1
commit 9e7efd0626
409 changed files with 272713 additions and 241 deletions
@@ -0,0 +1,404 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "f66f7a20",
"metadata": {
"origin_pos": 0
},
"source": [
"# 自定义层\n",
"\n",
"深度学习成功背后的一个因素是神经网络的灵活性:\n",
"我们可以用创造性的方式组合不同的层,从而设计出适用于各种任务的架构。\n",
"例如,研究人员发明了专门用于处理图像、文本、序列数据和执行动态规划的层。\n",
"有时我们会遇到或要自己发明一个现在在深度学习框架中还不存在的层。\n",
"在这些情况下,必须构建自定义层。本节将展示如何构建自定义层。\n",
"\n",
"## 不带参数的层\n",
"\n",
"首先,我们(**构造一个没有任何参数的自定义层**)。\n",
"回忆一下在 :numref:`sec_model_construction`对块的介绍,\n",
"这应该看起来很眼熟。\n",
"下面的`CenteredLayer`类要从其输入中减去均值。\n",
"要构建它,我们只需继承基础层类并实现前向传播功能。\n"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "cc3b353a",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T07:07:16.604374Z",
"iopub.status.busy": "2023-08-18T07:07:16.603752Z",
"iopub.status.idle": "2023-08-18T07:07:17.492480Z",
"shell.execute_reply": "2023-08-18T07:07:17.491482Z"
},
"origin_pos": 2,
"tab": [
"pytorch"
]
},
"outputs": [],
"source": [
"import torch\n",
"import torch.nn.functional as F\n",
"from torch import nn\n",
"\n",
"\n",
"class CenteredLayer(nn.Module):\n",
" def __init__(self):\n",
" super().__init__()\n",
"\n",
" def forward(self, X):\n",
" return X - X.mean()"
]
},
{
"cell_type": "markdown",
"id": "a3c321cf",
"metadata": {
"origin_pos": 5
},
"source": [
"让我们向该层提供一些数据,验证它是否能按预期工作。\n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "dec68045",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T07:07:17.497408Z",
"iopub.status.busy": "2023-08-18T07:07:17.497077Z",
"iopub.status.idle": "2023-08-18T07:07:17.508357Z",
"shell.execute_reply": "2023-08-18T07:07:17.507175Z"
},
"origin_pos": 7,
"tab": [
"pytorch"
]
},
"outputs": [
{
"data": {
"text/plain": [
"tensor([-2., -1., 0., 1., 2.])"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"layer = CenteredLayer()\n",
"layer(torch.FloatTensor([1, 2, 3, 4, 5]))"
]
},
{
"cell_type": "markdown",
"id": "9d38600d",
"metadata": {
"origin_pos": 10
},
"source": [
"现在,我们可以[**将层作为组件合并到更复杂的模型中**]。\n"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "1b903c3c",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T07:07:17.513247Z",
"iopub.status.busy": "2023-08-18T07:07:17.512547Z",
"iopub.status.idle": "2023-08-18T07:07:17.518968Z",
"shell.execute_reply": "2023-08-18T07:07:17.517886Z"
},
"origin_pos": 12,
"tab": [
"pytorch"
]
},
"outputs": [],
"source": [
"net = nn.Sequential(nn.Linear(8, 128), CenteredLayer())"
]
},
{
"cell_type": "markdown",
"id": "4c48076d",
"metadata": {
"origin_pos": 14
},
"source": [
"作为额外的健全性检查,我们可以在向该网络发送随机数据后,检查均值是否为0。\n",
"由于我们处理的是浮点数,因为存储精度的原因,我们仍然可能会看到一个非常小的非零数。\n"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "6ab302a0",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T07:07:17.523517Z",
"iopub.status.busy": "2023-08-18T07:07:17.523140Z",
"iopub.status.idle": "2023-08-18T07:07:17.534718Z",
"shell.execute_reply": "2023-08-18T07:07:17.533593Z"
},
"origin_pos": 16,
"tab": [
"pytorch"
]
},
"outputs": [
{
"data": {
"text/plain": [
"tensor(7.4506e-09, grad_fn=<MeanBackward0>)"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Y = net(torch.rand(4, 8))\n",
"Y.mean()"
]
},
{
"cell_type": "markdown",
"id": "ca107571",
"metadata": {
"origin_pos": 19
},
"source": [
"## [**带参数的层**]\n",
"\n",
"以上我们知道了如何定义简单的层,下面我们继续定义具有参数的层,\n",
"这些参数可以通过训练进行调整。\n",
"我们可以使用内置函数来创建参数,这些函数提供一些基本的管理功能。\n",
"比如管理访问、初始化、共享、保存和加载模型参数。\n",
"这样做的好处之一是:我们不需要为每个自定义层编写自定义的序列化程序。\n",
"\n",
"现在,让我们实现自定义版本的全连接层。\n",
"回想一下,该层需要两个参数,一个用于表示权重,另一个用于表示偏置项。\n",
"在此实现中,我们使用修正线性单元作为激活函数。\n",
"该层需要输入参数:`in_units`和`units`,分别表示输入数和输出数。\n"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "8c4a7999",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T07:07:17.539101Z",
"iopub.status.busy": "2023-08-18T07:07:17.538729Z",
"iopub.status.idle": "2023-08-18T07:07:17.546162Z",
"shell.execute_reply": "2023-08-18T07:07:17.545105Z"
},
"origin_pos": 21,
"tab": [
"pytorch"
]
},
"outputs": [],
"source": [
"class MyLinear(nn.Module):\n",
" def __init__(self, in_units, units):\n",
" super().__init__()\n",
" self.weight = nn.Parameter(torch.randn(in_units, units))\n",
" self.bias = nn.Parameter(torch.randn(units,))\n",
" def forward(self, X):\n",
" linear = torch.matmul(X, self.weight.data) + self.bias.data\n",
" return F.relu(linear)"
]
},
{
"cell_type": "markdown",
"id": "442183c6",
"metadata": {
"origin_pos": 25,
"tab": [
"pytorch"
]
},
"source": [
"接下来,我们实例化`MyLinear`类并访问其模型参数。\n"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "4490005a",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T07:07:17.550522Z",
"iopub.status.busy": "2023-08-18T07:07:17.550152Z",
"iopub.status.idle": "2023-08-18T07:07:17.558364Z",
"shell.execute_reply": "2023-08-18T07:07:17.557338Z"
},
"origin_pos": 28,
"tab": [
"pytorch"
]
},
"outputs": [
{
"data": {
"text/plain": [
"Parameter containing:\n",
"tensor([[ 0.1775, -1.4539, 0.3972],\n",
" [-0.1339, 0.5273, 1.3041],\n",
" [-0.3327, -0.2337, -0.6334],\n",
" [ 1.2076, -0.3937, 0.6851],\n",
" [-0.4716, 0.0894, -0.9195]], requires_grad=True)"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"linear = MyLinear(5, 3)\n",
"linear.weight"
]
},
{
"cell_type": "markdown",
"id": "7dcc8fd9",
"metadata": {
"origin_pos": 30
},
"source": [
"我们可以[**使用自定义层直接执行前向传播计算**]。\n"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "25f2aabf",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T07:07:17.562706Z",
"iopub.status.busy": "2023-08-18T07:07:17.562337Z",
"iopub.status.idle": "2023-08-18T07:07:17.570015Z",
"shell.execute_reply": "2023-08-18T07:07:17.568916Z"
},
"origin_pos": 32,
"tab": [
"pytorch"
]
},
"outputs": [
{
"data": {
"text/plain": [
"tensor([[0., 0., 0.],\n",
" [0., 0., 0.]])"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"linear(torch.rand(2, 5))"
]
},
{
"cell_type": "markdown",
"id": "c92ac1e0",
"metadata": {
"origin_pos": 35
},
"source": [
"我们还可以(**使用自定义层构建模型**),就像使用内置的全连接层一样使用自定义层。\n"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "fb2953e8",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T07:07:17.574378Z",
"iopub.status.busy": "2023-08-18T07:07:17.574000Z",
"iopub.status.idle": "2023-08-18T07:07:17.582792Z",
"shell.execute_reply": "2023-08-18T07:07:17.581735Z"
},
"origin_pos": 37,
"tab": [
"pytorch"
]
},
"outputs": [
{
"data": {
"text/plain": [
"tensor([[0.],\n",
" [0.]])"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"net = nn.Sequential(MyLinear(64, 8), MyLinear(8, 1))\n",
"net(torch.rand(2, 64))"
]
},
{
"cell_type": "markdown",
"id": "5a23d1ab",
"metadata": {
"origin_pos": 40
},
"source": [
"## 小结\n",
"\n",
"* 我们可以通过基本层类设计自定义层。这允许我们定义灵活的新层,其行为与深度学习框架中的任何现有层不同。\n",
"* 在自定义层定义完成后,我们就可以在任意环境和网络架构中调用该自定义层。\n",
"* 层可以有局部参数,这些参数可以通过内置函数创建。\n",
"\n",
"## 练习\n",
"\n",
"1. 设计一个接受输入并计算张量降维的层,它返回$y_k = \\sum_{i, j} W_{ijk} x_i x_j$。\n",
"1. 设计一个返回输入数据的傅立叶系数前半部分的层。\n"
]
},
{
"cell_type": "markdown",
"id": "2d5d22c2",
"metadata": {
"origin_pos": 42,
"tab": [
"pytorch"
]
},
"source": [
"[Discussions](https://discuss.d2l.ai/t/1835)\n"
]
}
],
"metadata": {
"language_info": {
"name": "python"
},
"required_libs": []
},
"nbformat": 4,
"nbformat_minor": 5
}
@@ -0,0 +1,103 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "59a11c8e",
"metadata": {
"origin_pos": 0
},
"source": [
"# 延后初始化\n",
":label:`sec_deferred_init`\n",
"\n",
"到目前为止,我们忽略了建立网络时需要做的以下这些事情:\n",
"\n",
"* 我们定义了网络架构,但没有指定输入维度。\n",
"* 我们添加层时没有指定前一层的输出维度。\n",
"* 我们在初始化参数时,甚至没有足够的信息来确定模型应该包含多少参数。\n",
"\n",
"有些读者可能会对我们的代码能运行感到惊讶。\n",
"毕竟,深度学习框架无法判断网络的输入维度是什么。\n",
"这里的诀窍是框架的*延后初始化*defers initialization),\n",
"即直到数据第一次通过模型传递时,框架才会动态地推断出每个层的大小。\n",
"\n",
"在以后,当使用卷积神经网络时,\n",
"由于输入维度(即图像的分辨率)将影响每个后续层的维数,\n",
"有了该技术将更加方便。\n",
"现在我们在编写代码时无须知道维度是什么就可以设置参数,\n",
"这种能力可以大大简化定义和修改模型的任务。\n",
"接下来,我们将更深入地研究初始化机制。\n",
"\n",
"## 实例化网络\n",
"\n",
"首先,让我们实例化一个多层感知机。\n"
]
},
{
"cell_type": "markdown",
"id": "1d75086b",
"metadata": {
"origin_pos": 3
},
"source": [
"此时,因为输入维数是未知的,所以网络不可能知道输入层权重的维数。\n",
"因此,框架尚未初始化任何参数,我们通过尝试访问以下参数进行确认。\n"
]
},
{
"cell_type": "markdown",
"id": "82b701e3",
"metadata": {
"origin_pos": 10
},
"source": [
"接下来让我们将数据通过网络,最终使框架初始化参数。\n"
]
},
{
"cell_type": "markdown",
"id": "094382a3",
"metadata": {
"origin_pos": 13
},
"source": [
"一旦我们知道输入维数是20,框架可以通过代入值20来识别第一层权重矩阵的形状。\n",
"识别出第一层的形状后,框架处理第二层,依此类推,直到所有形状都已知为止。\n",
"注意,在这种情况下,只有第一层需要延迟初始化,但是框架仍是按顺序初始化的。\n",
"等到知道了所有的参数形状,框架就可以初始化参数。\n",
"\n",
"## 小结\n",
"\n",
"* 延后初始化使框架能够自动推断参数形状,使修改模型架构变得容易,避免了一些常见的错误。\n",
"* 我们可以通过模型传递数据,使框架最终初始化参数。\n",
"\n",
"## 练习\n",
"\n",
"1. 如果指定了第一层的输入尺寸,但没有指定后续层的尺寸,会发生什么?是否立即进行初始化?\n",
"1. 如果指定了不匹配的维度会发生什么?\n",
"1. 如果输入具有不同的维度,需要做什么?提示:查看参数绑定的相关内容。\n"
]
},
{
"cell_type": "markdown",
"id": "7ed4b454",
"metadata": {
"origin_pos": 15,
"tab": [
"pytorch"
]
},
"source": [
"[Discussions](https://discuss.d2l.ai/t/5770)\n"
]
}
],
"metadata": {
"language_info": {
"name": "python"
},
"required_libs": []
},
"nbformat": 4,
"nbformat_minor": 5
}
@@ -0,0 +1,55 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "5cf9fbc8",
"metadata": {
"origin_pos": 0
},
"source": [
"# 深度学习计算\n",
":label:`chap_computation`\n",
"\n",
"除了庞大的数据集和强大的硬件,\n",
"优秀的软件工具在深度学习的快速发展中发挥了不可或缺的作用。\n",
"从2007年发布的开创性的Theano库开始,\n",
"灵活的开源工具使研究人员能够快速开发模型原型,\n",
"避免了我们使用标准组件时的重复工作,\n",
"同时仍然保持了我们进行底层修改的能力。\n",
"随着时间的推移,深度学习库已经演变成提供越来越粗糙的抽象。\n",
"就像半导体设计师从指定晶体管到逻辑电路再到编写代码一样,\n",
"神经网络研究人员已经从考虑单个人工神经元的行为转变为从层的角度构思网络,\n",
"通常在设计架构时考虑的是更粗糙的块(block)。\n",
"\n",
"之前我们已经介绍了一些基本的机器学习概念,\n",
"并慢慢介绍了功能齐全的深度学习模型。\n",
"在上一章中,我们从零开始实现了多层感知机的每个组件,\n",
"然后展示了如何利用高级API轻松地实现相同的模型。\n",
"为了易于学习,我们调用了深度学习库,但是跳过了它们工作的细节。\n",
"在本章中,我们将深入探索深度学习计算的关键组件,\n",
"即模型构建、参数访问与初始化、设计自定义层和块、将模型读写到磁盘,\n",
"以及利用GPU实现显著的加速。\n",
"这些知识将使读者从深度学习“基础用户”变为“高级用户”。\n",
"虽然本章不介绍任何新的模型或数据集,\n",
"但后面的高级模型章节在很大程度上依赖于本章的知识。\n",
"\n",
":begin_tab:toc\n",
" - [model-construction](model-construction.ipynb)\n",
" - [parameters](parameters.ipynb)\n",
" - [deferred-init](deferred-init.ipynb)\n",
" - [custom-layer](custom-layer.ipynb)\n",
" - [read-write](read-write.ipynb)\n",
" - [use-gpu](use-gpu.ipynb)\n",
":end_tab:\n"
]
}
],
"metadata": {
"language_info": {
"name": "python"
},
"required_libs": []
},
"nbformat": 4,
"nbformat_minor": 5
}
@@ -0,0 +1,646 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "1dca9252",
"metadata": {
"origin_pos": 0
},
"source": [
"# 层和块\n",
":label:`sec_model_construction`\n",
"\n",
"之前首次介绍神经网络时,我们关注的是具有单一输出的线性模型。\n",
"在这里,整个模型只有一个输出。\n",
"注意,单个神经网络\n",
"1)接受一些输入;\n",
"2)生成相应的标量输出;\n",
"3)具有一组相关 *参数*(parameters),更新这些参数可以优化某目标函数。\n",
"\n",
"然后,当考虑具有多个输出的网络时,\n",
"我们利用矢量化算法来描述整层神经元。\n",
"像单个神经元一样,层(1)接受一组输入,\n",
"2)生成相应的输出,\n",
"(3)由一组可调整参数描述。\n",
"当我们使用softmax回归时,一个单层本身就是模型。\n",
"然而,即使我们随后引入了多层感知机,我们仍然可以认为该模型保留了上面所说的基本架构。\n",
"\n",
"对于多层感知机而言,整个模型及其组成层都是这种架构。\n",
"整个模型接受原始输入(特征),生成输出(预测),\n",
"并包含一些参数(所有组成层的参数集合)。\n",
"同样,每个单独的层接收输入(由前一层提供),\n",
"生成输出(到下一层的输入),并且具有一组可调参数,\n",
"这些参数根据从下一层反向传播的信号进行更新。\n",
"\n",
"事实证明,研究讨论“比单个层大”但“比整个模型小”的组件更有价值。\n",
"例如,在计算机视觉中广泛流行的ResNet-152架构就有数百层,\n",
"这些层是由*层组*groups of layers)的重复模式组成。\n",
"这个ResNet架构赢得了2015年ImageNet和COCO计算机视觉比赛\n",
"的识别和检测任务 :cite:`He.Zhang.Ren.ea.2016`。\n",
"目前ResNet架构仍然是许多视觉任务的首选架构。\n",
"在其他的领域,如自然语言处理和语音,\n",
"层组以各种重复模式排列的类似架构现在也是普遍存在。\n",
"\n",
"为了实现这些复杂的网络,我们引入了神经网络*块*的概念。\n",
"*块*(block)可以描述单个层、由多个层组成的组件或整个模型本身。\n",
"使用块进行抽象的一个好处是可以将一些块组合成更大的组件,\n",
"这一过程通常是递归的,如 :numref:`fig_blocks`所示。\n",
"通过定义代码来按需生成任意复杂度的块,\n",
"我们可以通过简洁的代码实现复杂的神经网络。\n",
"\n",
"![多个层被组合成块,形成更大的模型](../img/blocks.svg)\n",
":label:`fig_blocks`\n",
"\n",
"从编程的角度来看,块由*类*class)表示。\n",
"它的任何子类都必须定义一个将其输入转换为输出的前向传播函数,\n",
"并且必须存储任何必需的参数。\n",
"注意,有些块不需要任何参数。\n",
"最后,为了计算梯度,块必须具有反向传播函数。\n",
"在定义我们自己的块时,由于自动微分(在 :numref:`sec_autograd` 中引入)\n",
"提供了一些后端实现,我们只需要考虑前向传播函数和必需的参数。\n",
"\n",
"在构造自定义块之前,(**我们先回顾一下多层感知机**)\n",
" :numref:`sec_mlp_concise` )的代码。\n",
"下面的代码生成一个网络,其中包含一个具有256个单元和ReLU激活函数的全连接隐藏层,\n",
"然后是一个具有10个隐藏单元且不带激活函数的全连接输出层。\n"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "9895e279",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T06:57:00.244437Z",
"iopub.status.busy": "2023-08-18T06:57:00.243813Z",
"iopub.status.idle": "2023-08-18T06:57:01.320999Z",
"shell.execute_reply": "2023-08-18T06:57:01.320186Z"
},
"origin_pos": 2,
"tab": [
"pytorch"
]
},
"outputs": [
{
"data": {
"text/plain": [
"tensor([[ 0.0343, 0.0264, 0.2505, -0.0243, 0.0945, 0.0012, -0.0141, 0.0666,\n",
" -0.0547, -0.0667],\n",
" [ 0.0772, -0.0274, 0.2638, -0.0191, 0.0394, -0.0324, 0.0102, 0.0707,\n",
" -0.1481, -0.1031]], grad_fn=<AddmmBackward0>)"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import torch\n",
"from torch import nn\n",
"from torch.nn import functional as F\n",
"\n",
"net = nn.Sequential(nn.Linear(20, 256), nn.ReLU(), nn.Linear(256, 10))\n",
"\n",
"X = torch.rand(2, 20)\n",
"net(X)"
]
},
{
"cell_type": "markdown",
"id": "be949c0e",
"metadata": {
"origin_pos": 6,
"tab": [
"pytorch"
]
},
"source": [
"在这个例子中,我们通过实例化`nn.Sequential`来构建我们的模型,\n",
"层的执行顺序是作为参数传递的。\n",
"简而言之,(**`nn.Sequential`定义了一种特殊的`Module`**)\n",
"即在PyTorch中表示一个块的类,\n",
"它维护了一个由`Module`组成的有序列表。\n",
"注意,两个全连接层都是`Linear`类的实例,\n",
"`Linear`类本身就是`Module`的子类。\n",
"另外,到目前为止,我们一直在通过`net(X)`调用我们的模型来获得模型的输出。\n",
"这实际上是`net.__call__(X)`的简写。\n",
"这个前向传播函数非常简单:\n",
"它将列表中的每个块连接在一起,将每个块的输出作为下一个块的输入。\n"
]
},
{
"cell_type": "markdown",
"id": "a3ce5ce8",
"metadata": {
"origin_pos": 9
},
"source": [
"## [**自定义块**]\n",
"\n",
"要想直观地了解块是如何工作的,最简单的方法就是自己实现一个。\n",
"在实现我们自定义块之前,我们简要总结一下每个块必须提供的基本功能。\n"
]
},
{
"cell_type": "markdown",
"id": "24ea84f7",
"metadata": {
"origin_pos": 11,
"tab": [
"pytorch"
]
},
"source": [
"1. 将输入数据作为其前向传播函数的参数。\n",
"1. 通过前向传播函数来生成输出。请注意,输出的形状可能与输入的形状不同。例如,我们上面模型中的第一个全连接的层接收一个20维的输入,但是返回一个维度为256的输出。\n",
"1. 计算其输出关于输入的梯度,可通过其反向传播函数进行访问。通常这是自动发生的。\n",
"1. 存储和访问前向传播计算所需的参数。\n",
"1. 根据需要初始化模型参数。\n"
]
},
{
"cell_type": "markdown",
"id": "572894df",
"metadata": {
"origin_pos": 12
},
"source": [
"在下面的代码片段中,我们从零开始编写一个块。\n",
"它包含一个多层感知机,其具有256个隐藏单元的隐藏层和一个10维输出层。\n",
"注意,下面的`MLP`类继承了表示块的类。\n",
"我们的实现只需要提供我们自己的构造函数(Python中的`__init__`函数)和前向传播函数。\n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "876df867",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T06:57:01.325541Z",
"iopub.status.busy": "2023-08-18T06:57:01.324828Z",
"iopub.status.idle": "2023-08-18T06:57:01.330411Z",
"shell.execute_reply": "2023-08-18T06:57:01.329591Z"
},
"origin_pos": 14,
"tab": [
"pytorch"
]
},
"outputs": [],
"source": [
"class MLP(nn.Module):\n",
" # 用模型参数声明层。这里,我们声明两个全连接的层\n",
" def __init__(self):\n",
" # 调用MLP的父类Module的构造函数来执行必要的初始化。\n",
" # 这样,在类实例化时也可以指定其他函数参数,例如模型参数params(稍后将介绍)\n",
" super().__init__()\n",
" self.hidden = nn.Linear(20, 256) # 隐藏层\n",
" self.out = nn.Linear(256, 10) # 输出层\n",
"\n",
" # 定义模型的前向传播,即如何根据输入X返回所需的模型输出\n",
" def forward(self, X):\n",
" # 注意,这里我们使用ReLU的函数版本,其在nn.functional模块中定义。\n",
" return self.out(F.relu(self.hidden(X)))"
]
},
{
"cell_type": "markdown",
"id": "8327a09c",
"metadata": {
"origin_pos": 17
},
"source": [
"我们首先看一下前向传播函数,它以`X`作为输入,\n",
"计算带有激活函数的隐藏表示,并输出其未规范化的输出值。\n",
"在这个`MLP`实现中,两个层都是实例变量。\n",
"要了解这为什么是合理的,可以想象实例化两个多层感知机(`net1`和`net2`),\n",
"并根据不同的数据对它们进行训练。\n",
"当然,我们希望它们学到两种不同的模型。\n",
"\n",
"接着我们[**实例化多层感知机的层,然后在每次调用前向传播函数时调用这些层**]。\n",
"注意一些关键细节:\n",
"首先,我们定制的`__init__`函数通过`super().__init__()`\n",
"调用父类的`__init__`函数,\n",
"省去了重复编写模版代码的痛苦。\n",
"然后,我们实例化两个全连接层,\n",
"分别为`self.hidden`和`self.out`。\n",
"注意,除非我们实现一个新的运算符,\n",
"否则我们不必担心反向传播函数或参数初始化,\n",
"系统将自动生成这些。\n",
"\n",
"我们来试一下这个函数:\n"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "f7a34ec3",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T06:57:01.334346Z",
"iopub.status.busy": "2023-08-18T06:57:01.333603Z",
"iopub.status.idle": "2023-08-18T06:57:01.340473Z",
"shell.execute_reply": "2023-08-18T06:57:01.339676Z"
},
"origin_pos": 19,
"tab": [
"pytorch"
]
},
"outputs": [
{
"data": {
"text/plain": [
"tensor([[ 0.0669, 0.2202, -0.0912, -0.0064, 0.1474, -0.0577, -0.3006, 0.1256,\n",
" -0.0280, 0.4040],\n",
" [ 0.0545, 0.2591, -0.0297, 0.1141, 0.1887, 0.0094, -0.2686, 0.0732,\n",
" -0.0135, 0.3865]], grad_fn=<AddmmBackward0>)"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"net = MLP()\n",
"net(X)"
]
},
{
"cell_type": "markdown",
"id": "37aaa7fc",
"metadata": {
"origin_pos": 21
},
"source": [
"块的一个主要优点是它的多功能性。\n",
"我们可以子类化块以创建层(如全连接层的类)、\n",
"整个模型(如上面的`MLP`类)或具有中等复杂度的各种组件。\n",
"我们在接下来的章节中充分利用了这种多功能性,\n",
"比如在处理卷积神经网络时。\n",
"\n",
"## [**顺序块**]\n",
"\n",
"现在我们可以更仔细地看看`Sequential`类是如何工作的,\n",
"回想一下`Sequential`的设计是为了把其他模块串起来。\n",
"为了构建我们自己的简化的`MySequential`\n",
"我们只需要定义两个关键函数:\n",
"\n",
"1. 一种将块逐个追加到列表中的函数;\n",
"1. 一种前向传播函数,用于将输入按追加块的顺序传递给块组成的“链条”。\n",
"\n",
"下面的`MySequential`类提供了与默认`Sequential`类相同的功能。\n"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "dd09709c",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T06:57:01.344392Z",
"iopub.status.busy": "2023-08-18T06:57:01.343695Z",
"iopub.status.idle": "2023-08-18T06:57:01.349458Z",
"shell.execute_reply": "2023-08-18T06:57:01.348481Z"
},
"origin_pos": 23,
"tab": [
"pytorch"
]
},
"outputs": [],
"source": [
"class MySequential(nn.Module):\n",
" def __init__(self, *args):\n",
" super().__init__()\n",
" for idx, module in enumerate(args):\n",
" # 这里,module是Module子类的一个实例。我们把它保存在'Module'类的成员\n",
" # 变量_modules中。_module的类型是OrderedDict\n",
" self._modules[str(idx)] = module\n",
"\n",
" def forward(self, X):\n",
" # OrderedDict保证了按照成员添加的顺序遍历它们\n",
" for block in self._modules.values():\n",
" X = block(X)\n",
" return X"
]
},
{
"cell_type": "markdown",
"id": "2a44d091",
"metadata": {
"origin_pos": 27,
"tab": [
"pytorch"
]
},
"source": [
"`__init__`函数将每个模块逐个添加到有序字典`_modules`中。\n",
"读者可能会好奇为什么每个`Module`都有一个`_modules`属性?\n",
"以及为什么我们使用它而不是自己定义一个Python列表?\n",
"简而言之,`_modules`的主要优点是:\n",
"在模块的参数初始化过程中,\n",
"系统知道在`_modules`字典中查找需要初始化参数的子块。\n"
]
},
{
"cell_type": "markdown",
"id": "0272bce5",
"metadata": {
"origin_pos": 29
},
"source": [
"当`MySequential`的前向传播函数被调用时,\n",
"每个添加的块都按照它们被添加的顺序执行。\n",
"现在可以使用我们的`MySequential`类重新实现多层感知机。\n"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "9672de9a",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T06:57:01.353302Z",
"iopub.status.busy": "2023-08-18T06:57:01.352727Z",
"iopub.status.idle": "2023-08-18T06:57:01.360268Z",
"shell.execute_reply": "2023-08-18T06:57:01.359462Z"
},
"origin_pos": 31,
"tab": [
"pytorch"
]
},
"outputs": [
{
"data": {
"text/plain": [
"tensor([[ 2.2759e-01, -4.7003e-02, 4.2846e-01, -1.2546e-01, 1.5296e-01,\n",
" 1.8972e-01, 9.7048e-02, 4.5479e-04, -3.7986e-02, 6.4842e-02],\n",
" [ 2.7825e-01, -9.7517e-02, 4.8541e-01, -2.4519e-01, -8.4580e-02,\n",
" 2.8538e-01, 3.6861e-02, 2.9411e-02, -1.0612e-01, 1.2620e-01]],\n",
" grad_fn=<AddmmBackward0>)"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"net = MySequential(nn.Linear(20, 256), nn.ReLU(), nn.Linear(256, 10))\n",
"net(X)"
]
},
{
"cell_type": "markdown",
"id": "189aa472",
"metadata": {
"origin_pos": 33
},
"source": [
"请注意,`MySequential`的用法与之前为`Sequential`类编写的代码相同\n",
"(如 :numref:`sec_mlp_concise` 中所述)。\n",
"\n",
"## [**在前向传播函数中执行代码**]\n",
"\n",
"`Sequential`类使模型构造变得简单,\n",
"允许我们组合新的架构,而不必定义自己的类。\n",
"然而,并不是所有的架构都是简单的顺序架构。\n",
"当需要更强的灵活性时,我们需要定义自己的块。\n",
"例如,我们可能希望在前向传播函数中执行Python的控制流。\n",
"此外,我们可能希望执行任意的数学运算,\n",
"而不是简单地依赖预定义的神经网络层。\n",
"\n",
"到目前为止,\n",
"我们网络中的所有操作都对网络的激活值及网络的参数起作用。\n",
"然而,有时我们可能希望合并既不是上一层的结果也不是可更新参数的项,\n",
"我们称之为*常数参数*constant parameter)。\n",
"例如,我们需要一个计算函数\n",
"$f(\\mathbf{x},\\mathbf{w}) = c \\cdot \\mathbf{w}^\\top \\mathbf{x}$的层,\n",
"其中$\\mathbf{x}$是输入,\n",
"$\\mathbf{w}$是参数,\n",
"$c$是某个在优化过程中没有更新的指定常量。\n",
"因此我们实现了一个`FixedHiddenMLP`类,如下所示:\n"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "9ad09596",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T06:57:01.364000Z",
"iopub.status.busy": "2023-08-18T06:57:01.363468Z",
"iopub.status.idle": "2023-08-18T06:57:01.369665Z",
"shell.execute_reply": "2023-08-18T06:57:01.368755Z"
},
"origin_pos": 35,
"tab": [
"pytorch"
]
},
"outputs": [],
"source": [
"class FixedHiddenMLP(nn.Module):\n",
" def __init__(self):\n",
" super().__init__()\n",
" # 不计算梯度的随机权重参数。因此其在训练期间保持不变\n",
" self.rand_weight = torch.rand((20, 20), requires_grad=False)\n",
" self.linear = nn.Linear(20, 20)\n",
"\n",
" def forward(self, X):\n",
" X = self.linear(X)\n",
" # 使用创建的常量参数以及relu和mm函数\n",
" X = F.relu(torch.mm(X, self.rand_weight) + 1)\n",
" # 复用全连接层。这相当于两个全连接层共享参数\n",
" X = self.linear(X)\n",
" # 控制流\n",
" while X.abs().sum() > 1:\n",
" X /= 2\n",
" return X.sum()"
]
},
{
"cell_type": "markdown",
"id": "06017344",
"metadata": {
"origin_pos": 38
},
"source": [
"在这个`FixedHiddenMLP`模型中,我们实现了一个隐藏层,\n",
"其权重(`self.rand_weight`)在实例化时被随机初始化,之后为常量。\n",
"这个权重不是一个模型参数,因此它永远不会被反向传播更新。\n",
"然后,神经网络将这个固定层的输出通过一个全连接层。\n",
"\n",
"注意,在返回输出之前,模型做了一些不寻常的事情:\n",
"它运行了一个while循环,在$L_1$范数大于$1$的条件下,\n",
"将输出向量除以$2$,直到它满足条件为止。\n",
"最后,模型返回了`X`中所有项的和。\n",
"注意,此操作可能不会常用于在任何实际任务中,\n",
"我们只展示如何将任意代码集成到神经网络计算的流程中。\n"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "00ebc567",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T06:57:01.373508Z",
"iopub.status.busy": "2023-08-18T06:57:01.372789Z",
"iopub.status.idle": "2023-08-18T06:57:01.380049Z",
"shell.execute_reply": "2023-08-18T06:57:01.379025Z"
},
"origin_pos": 40,
"tab": [
"pytorch"
]
},
"outputs": [
{
"data": {
"text/plain": [
"tensor(0.1862, grad_fn=<SumBackward0>)"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"net = FixedHiddenMLP()\n",
"net(X)"
]
},
{
"cell_type": "markdown",
"id": "80b18eb2",
"metadata": {
"origin_pos": 41
},
"source": [
"我们可以[**混合搭配各种组合块的方法**]。\n",
"在下面的例子中,我们以一些想到的方法嵌套块。\n"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "6ca3b399",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T06:57:01.384091Z",
"iopub.status.busy": "2023-08-18T06:57:01.383236Z",
"iopub.status.idle": "2023-08-18T06:57:01.394649Z",
"shell.execute_reply": "2023-08-18T06:57:01.393535Z"
},
"origin_pos": 43,
"tab": [
"pytorch"
]
},
"outputs": [
{
"data": {
"text/plain": [
"tensor(0.2183, grad_fn=<SumBackward0>)"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"class NestMLP(nn.Module):\n",
" def __init__(self):\n",
" super().__init__()\n",
" self.net = nn.Sequential(nn.Linear(20, 64), nn.ReLU(),\n",
" nn.Linear(64, 32), nn.ReLU())\n",
" self.linear = nn.Linear(32, 16)\n",
"\n",
" def forward(self, X):\n",
" return self.linear(self.net(X))\n",
"\n",
"chimera = nn.Sequential(NestMLP(), nn.Linear(16, 20), FixedHiddenMLP())\n",
"chimera(X)"
]
},
{
"cell_type": "markdown",
"id": "3b12e280",
"metadata": {
"origin_pos": 46
},
"source": [
"## 效率\n"
]
},
{
"cell_type": "markdown",
"id": "e26229d3",
"metadata": {
"origin_pos": 48,
"tab": [
"pytorch"
]
},
"source": [
"读者可能会开始担心操作效率的问题。\n",
"毕竟,我们在一个高性能的深度学习库中进行了大量的字典查找、\n",
"代码执行和许多其他的Python代码。\n",
"Python的问题[全局解释器锁](https://wiki.python.org/moin/GlobalInterpreterLock)\n",
"是众所周知的。\n",
"在深度学习环境中,我们担心速度极快的GPU可能要等到CPU运行Python代码后才能运行另一个作业。\n"
]
},
{
"cell_type": "markdown",
"id": "4fa617e6",
"metadata": {
"origin_pos": 51
},
"source": [
"## 小结\n",
"\n",
"* 一个块可以由许多层组成;一个块可以由许多块组成。\n",
"* 块可以包含代码。\n",
"* 块负责大量的内部处理,包括参数初始化和反向传播。\n",
"* 层和块的顺序连接由`Sequential`块处理。\n",
"\n",
"## 练习\n",
"\n",
"1. 如果将`MySequential`中存储块的方式更改为Python列表,会出现什么样的问题?\n",
"1. 实现一个块,它以两个块为参数,例如`net1`和`net2`,并返回前向传播中两个网络的串联输出。这也被称为平行块。\n",
"1. 假设我们想要连接同一网络的多个实例。实现一个函数,该函数生成同一个块的多个实例,并在此基础上构建更大的网络。\n"
]
},
{
"cell_type": "markdown",
"id": "c29846c8",
"metadata": {
"origin_pos": 53,
"tab": [
"pytorch"
]
},
"source": [
"[Discussions](https://discuss.d2l.ai/t/1827)\n"
]
}
],
"metadata": {
"language_info": {
"name": "python"
},
"required_libs": []
},
"nbformat": 4,
"nbformat_minor": 5
}
@@ -0,0 +1,896 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "b05be39e",
"metadata": {
"origin_pos": 0
},
"source": [
"# 参数管理\n",
"\n",
"在选择了架构并设置了超参数后,我们就进入了训练阶段。\n",
"此时,我们的目标是找到使损失函数最小化的模型参数值。\n",
"经过训练后,我们将需要使用这些参数来做出未来的预测。\n",
"此外,有时我们希望提取参数,以便在其他环境中复用它们,\n",
"将模型保存下来,以便它可以在其他软件中执行,\n",
"或者为了获得科学的理解而进行检查。\n",
"\n",
"之前的介绍中,我们只依靠深度学习框架来完成训练的工作,\n",
"而忽略了操作参数的具体细节。\n",
"本节,我们将介绍以下内容:\n",
"\n",
"* 访问参数,用于调试、诊断和可视化;\n",
"* 参数初始化;\n",
"* 在不同模型组件间共享参数。\n",
"\n",
"(**我们首先看一下具有单隐藏层的多层感知机。**)\n"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "ab7ef7a0",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T07:01:09.649068Z",
"iopub.status.busy": "2023-08-18T07:01:09.648305Z",
"iopub.status.idle": "2023-08-18T07:01:10.928992Z",
"shell.execute_reply": "2023-08-18T07:01:10.927959Z"
},
"origin_pos": 2,
"tab": [
"pytorch"
]
},
"outputs": [
{
"data": {
"text/plain": [
"tensor([[-0.0970],\n",
" [-0.0827]], grad_fn=<AddmmBackward0>)"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import torch\n",
"from torch import nn\n",
"\n",
"net = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 1))\n",
"X = torch.rand(size=(2, 4))\n",
"net(X)"
]
},
{
"cell_type": "markdown",
"id": "fa004a12",
"metadata": {
"origin_pos": 5
},
"source": [
"## [**参数访问**]\n",
"\n",
"我们从已有模型中访问参数。\n",
"当通过`Sequential`类定义模型时,\n",
"我们可以通过索引来访问模型的任意层。\n",
"这就像模型是一个列表一样,每层的参数都在其属性中。\n",
"如下所示,我们可以检查第二个全连接层的参数。\n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "5e2fff9a",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T07:01:10.933865Z",
"iopub.status.busy": "2023-08-18T07:01:10.933267Z",
"iopub.status.idle": "2023-08-18T07:01:10.939922Z",
"shell.execute_reply": "2023-08-18T07:01:10.938931Z"
},
"origin_pos": 7,
"tab": [
"pytorch"
]
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"OrderedDict([('weight', tensor([[-0.0427, -0.2939, -0.1894, 0.0220, -0.1709, -0.1522, -0.0334, -0.2263]])), ('bias', tensor([0.0887]))])\n"
]
}
],
"source": [
"print(net[2].state_dict())"
]
},
{
"cell_type": "markdown",
"id": "b77c779c",
"metadata": {
"origin_pos": 9
},
"source": [
"输出的结果告诉我们一些重要的事情:\n",
"首先,这个全连接层包含两个参数,分别是该层的权重和偏置。\n",
"两者都存储为单精度浮点数(float32)。\n",
"注意,参数名称允许唯一标识每个参数,即使在包含数百个层的网络中也是如此。\n",
"\n",
"### [**目标参数**]\n",
"\n",
"注意,每个参数都表示为参数类的一个实例。\n",
"要对参数执行任何操作,首先我们需要访问底层的数值。\n",
"有几种方法可以做到这一点。有些比较简单,而另一些则比较通用。\n",
"下面的代码从第二个全连接层(即第三个神经网络层)提取偏置,\n",
"提取后返回的是一个参数类实例,并进一步访问该参数的值。\n"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "d0682fff",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T07:01:10.945104Z",
"iopub.status.busy": "2023-08-18T07:01:10.944250Z",
"iopub.status.idle": "2023-08-18T07:01:10.951764Z",
"shell.execute_reply": "2023-08-18T07:01:10.950790Z"
},
"origin_pos": 11,
"tab": [
"pytorch"
]
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<class 'torch.nn.parameter.Parameter'>\n",
"Parameter containing:\n",
"tensor([0.0887], requires_grad=True)\n",
"tensor([0.0887])\n"
]
}
],
"source": [
"print(type(net[2].bias))\n",
"print(net[2].bias)\n",
"print(net[2].bias.data)"
]
},
{
"cell_type": "markdown",
"id": "b90565b1",
"metadata": {
"origin_pos": 14,
"tab": [
"pytorch"
]
},
"source": [
"参数是复合的对象,包含值、梯度和额外信息。\n",
"这就是我们需要显式参数值的原因。\n",
"除了值之外,我们还可以访问每个参数的梯度。\n",
"在上面这个网络中,由于我们还没有调用反向传播,所以参数的梯度处于初始状态。\n"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "3cf4d55b",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T07:01:10.956378Z",
"iopub.status.busy": "2023-08-18T07:01:10.955542Z",
"iopub.status.idle": "2023-08-18T07:01:10.961810Z",
"shell.execute_reply": "2023-08-18T07:01:10.960767Z"
},
"origin_pos": 16,
"tab": [
"pytorch"
]
},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"net[2].weight.grad == None"
]
},
{
"cell_type": "markdown",
"id": "01e647c1",
"metadata": {
"origin_pos": 17
},
"source": [
"### [**一次性访问所有参数**]\n",
"\n",
"当我们需要对所有参数执行操作时,逐个访问它们可能会很麻烦。\n",
"当我们处理更复杂的块(例如,嵌套块)时,情况可能会变得特别复杂,\n",
"因为我们需要递归整个树来提取每个子块的参数。\n",
"下面,我们将通过演示来比较访问第一个全连接层的参数和访问所有层。\n"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "916939ce",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T07:01:10.966725Z",
"iopub.status.busy": "2023-08-18T07:01:10.965969Z",
"iopub.status.idle": "2023-08-18T07:01:10.972600Z",
"shell.execute_reply": "2023-08-18T07:01:10.971655Z"
},
"origin_pos": 19,
"tab": [
"pytorch"
]
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"('weight', torch.Size([8, 4])) ('bias', torch.Size([8]))\n",
"('0.weight', torch.Size([8, 4])) ('0.bias', torch.Size([8])) ('2.weight', torch.Size([1, 8])) ('2.bias', torch.Size([1]))\n"
]
}
],
"source": [
"print(*[(name, param.shape) for name, param in net[0].named_parameters()])\n",
"print(*[(name, param.shape) for name, param in net.named_parameters()])"
]
},
{
"cell_type": "markdown",
"id": "c9cc1e2f",
"metadata": {
"origin_pos": 21
},
"source": [
"这为我们提供了另一种访问网络参数的方式,如下所示。\n"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "116207ef",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T07:01:10.977269Z",
"iopub.status.busy": "2023-08-18T07:01:10.976623Z",
"iopub.status.idle": "2023-08-18T07:01:10.983222Z",
"shell.execute_reply": "2023-08-18T07:01:10.982309Z"
},
"origin_pos": 23,
"tab": [
"pytorch"
]
},
"outputs": [
{
"data": {
"text/plain": [
"tensor([0.0887])"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"net.state_dict()['2.bias'].data"
]
},
{
"cell_type": "markdown",
"id": "f2ae2721",
"metadata": {
"origin_pos": 26
},
"source": [
"### [**从嵌套块收集参数**]\n",
"\n",
"让我们看看,如果我们将多个块相互嵌套,参数命名约定是如何工作的。\n",
"我们首先定义一个生成块的函数(可以说是“块工厂”),然后将这些块组合到更大的块中。\n"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "712e31fd",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T07:01:10.988088Z",
"iopub.status.busy": "2023-08-18T07:01:10.987352Z",
"iopub.status.idle": "2023-08-18T07:01:10.998245Z",
"shell.execute_reply": "2023-08-18T07:01:10.997197Z"
},
"origin_pos": 28,
"tab": [
"pytorch"
]
},
"outputs": [
{
"data": {
"text/plain": [
"tensor([[0.2596],\n",
" [0.2596]], grad_fn=<AddmmBackward0>)"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def block1():\n",
" return nn.Sequential(nn.Linear(4, 8), nn.ReLU(),\n",
" nn.Linear(8, 4), nn.ReLU())\n",
"\n",
"def block2():\n",
" net = nn.Sequential()\n",
" for i in range(4):\n",
" # 在这里嵌套\n",
" net.add_module(f'block {i}', block1())\n",
" return net\n",
"\n",
"rgnet = nn.Sequential(block2(), nn.Linear(4, 1))\n",
"rgnet(X)"
]
},
{
"cell_type": "markdown",
"id": "ac9958fb",
"metadata": {
"origin_pos": 31
},
"source": [
"[**设计了网络后,我们看看它是如何工作的。**]\n"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "c7d7717d",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T07:01:11.002889Z",
"iopub.status.busy": "2023-08-18T07:01:11.002264Z",
"iopub.status.idle": "2023-08-18T07:01:11.007643Z",
"shell.execute_reply": "2023-08-18T07:01:11.006464Z"
},
"origin_pos": 33,
"tab": [
"pytorch"
]
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Sequential(\n",
" (0): Sequential(\n",
" (block 0): Sequential(\n",
" (0): Linear(in_features=4, out_features=8, bias=True)\n",
" (1): ReLU()\n",
" (2): Linear(in_features=8, out_features=4, bias=True)\n",
" (3): ReLU()\n",
" )\n",
" (block 1): Sequential(\n",
" (0): Linear(in_features=4, out_features=8, bias=True)\n",
" (1): ReLU()\n",
" (2): Linear(in_features=8, out_features=4, bias=True)\n",
" (3): ReLU()\n",
" )\n",
" (block 2): Sequential(\n",
" (0): Linear(in_features=4, out_features=8, bias=True)\n",
" (1): ReLU()\n",
" (2): Linear(in_features=8, out_features=4, bias=True)\n",
" (3): ReLU()\n",
" )\n",
" (block 3): Sequential(\n",
" (0): Linear(in_features=4, out_features=8, bias=True)\n",
" (1): ReLU()\n",
" (2): Linear(in_features=8, out_features=4, bias=True)\n",
" (3): ReLU()\n",
" )\n",
" )\n",
" (1): Linear(in_features=4, out_features=1, bias=True)\n",
")\n"
]
}
],
"source": [
"print(rgnet)"
]
},
{
"cell_type": "markdown",
"id": "1c49f699",
"metadata": {
"origin_pos": 35
},
"source": [
"因为层是分层嵌套的,所以我们也可以像通过嵌套列表索引一样访问它们。\n",
"下面,我们访问第一个主要的块中、第二个子块的第一层的偏置项。\n"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "939ba4d3",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T07:01:11.012522Z",
"iopub.status.busy": "2023-08-18T07:01:11.011839Z",
"iopub.status.idle": "2023-08-18T07:01:11.018508Z",
"shell.execute_reply": "2023-08-18T07:01:11.017590Z"
},
"origin_pos": 37,
"tab": [
"pytorch"
]
},
"outputs": [
{
"data": {
"text/plain": [
"tensor([ 0.1999, -0.4073, -0.1200, -0.2033, -0.1573, 0.3546, -0.2141, -0.2483])"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"rgnet[0][1][0].bias.data"
]
},
{
"cell_type": "markdown",
"id": "0383b6a9",
"metadata": {
"origin_pos": 40
},
"source": [
"## 参数初始化\n",
"\n",
"知道了如何访问参数后,现在我们看看如何正确地初始化参数。\n",
"我们在 :numref:`sec_numerical_stability`中讨论了良好初始化的必要性。\n",
"深度学习框架提供默认随机初始化,\n",
"也允许我们创建自定义初始化方法,\n",
"满足我们通过其他规则实现初始化权重。\n"
]
},
{
"cell_type": "markdown",
"id": "0418f044",
"metadata": {
"origin_pos": 42,
"tab": [
"pytorch"
]
},
"source": [
"默认情况下,PyTorch会根据一个范围均匀地初始化权重和偏置矩阵,\n",
"这个范围是根据输入和输出维度计算出的。\n",
"PyTorch的`nn.init`模块提供了多种预置初始化方法。\n"
]
},
{
"cell_type": "markdown",
"id": "0b0b932a",
"metadata": {
"origin_pos": 45
},
"source": [
"### [**内置初始化**]\n",
"\n",
"让我们首先调用内置的初始化器。\n",
"下面的代码将所有权重参数初始化为标准差为0.01的高斯随机变量,\n",
"且将偏置参数设置为0。\n"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "2f00d5e7",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T07:01:11.023955Z",
"iopub.status.busy": "2023-08-18T07:01:11.023046Z",
"iopub.status.idle": "2023-08-18T07:01:11.033287Z",
"shell.execute_reply": "2023-08-18T07:01:11.032096Z"
},
"origin_pos": 47,
"tab": [
"pytorch"
]
},
"outputs": [
{
"data": {
"text/plain": [
"(tensor([-0.0214, -0.0015, -0.0100, -0.0058]), tensor(0.))"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def init_normal(m):\n",
" if type(m) == nn.Linear:\n",
" nn.init.normal_(m.weight, mean=0, std=0.01)\n",
" nn.init.zeros_(m.bias)\n",
"net.apply(init_normal)\n",
"net[0].weight.data[0], net[0].bias.data[0]"
]
},
{
"cell_type": "markdown",
"id": "753e540b",
"metadata": {
"origin_pos": 50
},
"source": [
"我们还可以将所有参数初始化为给定的常数,比如初始化为1。\n"
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "49ee306c",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T07:01:11.038321Z",
"iopub.status.busy": "2023-08-18T07:01:11.037607Z",
"iopub.status.idle": "2023-08-18T07:01:11.049009Z",
"shell.execute_reply": "2023-08-18T07:01:11.047793Z"
},
"origin_pos": 52,
"tab": [
"pytorch"
]
},
"outputs": [
{
"data": {
"text/plain": [
"(tensor([1., 1., 1., 1.]), tensor(0.))"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def init_constant(m):\n",
" if type(m) == nn.Linear:\n",
" nn.init.constant_(m.weight, 1)\n",
" nn.init.zeros_(m.bias)\n",
"net.apply(init_constant)\n",
"net[0].weight.data[0], net[0].bias.data[0]"
]
},
{
"cell_type": "markdown",
"id": "e086279d",
"metadata": {
"origin_pos": 55
},
"source": [
"我们还可以[**对某些块应用不同的初始化方法**]。\n",
"例如,下面我们使用Xavier初始化方法初始化第一个神经网络层,\n",
"然后将第三个神经网络层初始化为常量值42。\n"
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "1a90ffaa",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T07:01:11.054335Z",
"iopub.status.busy": "2023-08-18T07:01:11.053550Z",
"iopub.status.idle": "2023-08-18T07:01:11.063215Z",
"shell.execute_reply": "2023-08-18T07:01:11.062244Z"
},
"origin_pos": 57,
"tab": [
"pytorch"
]
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"tensor([ 0.5236, 0.0516, -0.3236, 0.3794])\n",
"tensor([[42., 42., 42., 42., 42., 42., 42., 42.]])\n"
]
}
],
"source": [
"def init_xavier(m):\n",
" if type(m) == nn.Linear:\n",
" nn.init.xavier_uniform_(m.weight)\n",
"def init_42(m):\n",
" if type(m) == nn.Linear:\n",
" nn.init.constant_(m.weight, 42)\n",
"\n",
"net[0].apply(init_xavier)\n",
"net[2].apply(init_42)\n",
"print(net[0].weight.data[0])\n",
"print(net[2].weight.data)"
]
},
{
"cell_type": "markdown",
"id": "581dcade",
"metadata": {
"origin_pos": 60
},
"source": [
"### [**自定义初始化**]\n",
"\n",
"有时,深度学习框架没有提供我们需要的初始化方法。\n",
"在下面的例子中,我们使用以下的分布为任意权重参数$w$定义初始化方法:\n",
"\n",
"$$\n",
"\\begin{aligned}\n",
" w \\sim \\begin{cases}\n",
" U(5, 10) & \\text{ 可能性 } \\frac{1}{4} \\\\\n",
" 0 & \\text{ 可能性 } \\frac{1}{2} \\\\\n",
" U(-10, -5) & \\text{ 可能性 } \\frac{1}{4}\n",
" \\end{cases}\n",
"\\end{aligned}\n",
"$$\n"
]
},
{
"cell_type": "markdown",
"id": "12502b7c",
"metadata": {
"origin_pos": 62,
"tab": [
"pytorch"
]
},
"source": [
"同样,我们实现了一个`my_init`函数来应用到`net`。\n"
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "9166f6e3",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T07:01:11.068164Z",
"iopub.status.busy": "2023-08-18T07:01:11.067460Z",
"iopub.status.idle": "2023-08-18T07:01:11.079228Z",
"shell.execute_reply": "2023-08-18T07:01:11.078069Z"
},
"origin_pos": 66,
"tab": [
"pytorch"
]
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Init weight torch.Size([8, 4])\n",
"Init weight torch.Size([1, 8])\n"
]
},
{
"data": {
"text/plain": [
"tensor([[5.4079, 9.3334, 5.0616, 8.3095],\n",
" [0.0000, 7.2788, -0.0000, -0.0000]], grad_fn=<SliceBackward0>)"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def my_init(m):\n",
" if type(m) == nn.Linear:\n",
" print(\"Init\", *[(name, param.shape)\n",
" for name, param in m.named_parameters()][0])\n",
" nn.init.uniform_(m.weight, -10, 10)\n",
" m.weight.data *= m.weight.data.abs() >= 5\n",
"\n",
"net.apply(my_init)\n",
"net[0].weight[:2]"
]
},
{
"cell_type": "markdown",
"id": "030a52c5",
"metadata": {
"origin_pos": 69
},
"source": [
"注意,我们始终可以直接设置参数。\n"
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "5b9af1f8",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T07:01:11.084158Z",
"iopub.status.busy": "2023-08-18T07:01:11.083416Z",
"iopub.status.idle": "2023-08-18T07:01:11.092672Z",
"shell.execute_reply": "2023-08-18T07:01:11.091537Z"
},
"origin_pos": 71,
"tab": [
"pytorch"
]
},
"outputs": [
{
"data": {
"text/plain": [
"tensor([42.0000, 10.3334, 6.0616, 9.3095])"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"net[0].weight.data[:] += 1\n",
"net[0].weight.data[0, 0] = 42\n",
"net[0].weight.data[0]"
]
},
{
"cell_type": "markdown",
"id": "a4144ff7",
"metadata": {
"origin_pos": 75
},
"source": [
"## [**参数绑定**]\n",
"\n",
"有时我们希望在多个层间共享参数:\n",
"我们可以定义一个稠密层,然后使用它的参数来设置另一个层的参数。\n"
]
},
{
"cell_type": "code",
"execution_count": 15,
"id": "69660fa7",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T07:01:11.097767Z",
"iopub.status.busy": "2023-08-18T07:01:11.096948Z",
"iopub.status.idle": "2023-08-18T07:01:11.108904Z",
"shell.execute_reply": "2023-08-18T07:01:11.107763Z"
},
"origin_pos": 77,
"tab": [
"pytorch"
]
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"tensor([True, True, True, True, True, True, True, True])\n",
"tensor([True, True, True, True, True, True, True, True])\n"
]
}
],
"source": [
"# 我们需要给共享层一个名称,以便可以引用它的参数\n",
"shared = nn.Linear(8, 8)\n",
"net = nn.Sequential(nn.Linear(4, 8), nn.ReLU(),\n",
" shared, nn.ReLU(),\n",
" shared, nn.ReLU(),\n",
" nn.Linear(8, 1))\n",
"net(X)\n",
"# 检查参数是否相同\n",
"print(net[2].weight.data[0] == net[4].weight.data[0])\n",
"net[2].weight.data[0, 0] = 100\n",
"# 确保它们实际上是同一个对象,而不只是有相同的值\n",
"print(net[2].weight.data[0] == net[4].weight.data[0])"
]
},
{
"cell_type": "markdown",
"id": "81dc2c3c",
"metadata": {
"origin_pos": 81,
"tab": [
"pytorch"
]
},
"source": [
"这个例子表明第三个和第五个神经网络层的参数是绑定的。\n",
"它们不仅值相等,而且由相同的张量表示。\n",
"因此,如果我们改变其中一个参数,另一个参数也会改变。\n",
"这里有一个问题:当参数绑定时,梯度会发生什么情况?\n",
"答案是由于模型参数包含梯度,因此在反向传播期间第二个隐藏层\n",
"(即第三个神经网络层)和第三个隐藏层(即第五个神经网络层)的梯度会加在一起。\n"
]
},
{
"cell_type": "markdown",
"id": "ef8e6259",
"metadata": {
"origin_pos": 82
},
"source": [
"## 小结\n",
"\n",
"* 我们有几种方法可以访问、初始化和绑定模型参数。\n",
"* 我们可以使用自定义初始化方法。\n",
"\n",
"## 练习\n",
"\n",
"1. 使用 :numref:`sec_model_construction` 中定义的`FancyMLP`模型,访问各个层的参数。\n",
"1. 查看初始化模块文档以了解不同的初始化方法。\n",
"1. 构建包含共享参数层的多层感知机并对其进行训练。在训练过程中,观察模型各层的参数和梯度。\n",
"1. 为什么共享参数是个好主意?\n"
]
},
{
"cell_type": "markdown",
"id": "ead65cf9",
"metadata": {
"origin_pos": 84,
"tab": [
"pytorch"
]
},
"source": [
"[Discussions](https://discuss.d2l.ai/t/1829)\n"
]
}
],
"metadata": {
"language_info": {
"name": "python"
},
"required_libs": []
},
"nbformat": 4,
"nbformat_minor": 5
}
@@ -0,0 +1,408 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "bec47e64",
"metadata": {
"origin_pos": 0
},
"source": [
"# 读写文件\n",
"\n",
"到目前为止,我们讨论了如何处理数据,\n",
"以及如何构建、训练和测试深度学习模型。\n",
"然而,有时我们希望保存训练的模型,\n",
"以备将来在各种环境中使用(比如在部署中进行预测)。\n",
"此外,当运行一个耗时较长的训练过程时,\n",
"最佳的做法是定期保存中间结果,\n",
"以确保在服务器电源被不小心断掉时,我们不会损失几天的计算结果。\n",
"因此,现在是时候学习如何加载和存储权重向量和整个模型了。\n",
"\n",
"## (**加载和保存张量**)\n",
"\n",
"对于单个张量,我们可以直接调用`load`和`save`函数分别读写它们。\n",
"这两个函数都要求我们提供一个名称,`save`要求将要保存的变量作为输入。\n"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "9b319fd3",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T06:56:42.668559Z",
"iopub.status.busy": "2023-08-18T06:56:42.667248Z",
"iopub.status.idle": "2023-08-18T06:56:43.728764Z",
"shell.execute_reply": "2023-08-18T06:56:43.727885Z"
},
"origin_pos": 2,
"tab": [
"pytorch"
]
},
"outputs": [],
"source": [
"import torch\n",
"from torch import nn\n",
"from torch.nn import functional as F\n",
"\n",
"x = torch.arange(4)\n",
"torch.save(x, 'x-file')"
]
},
{
"cell_type": "markdown",
"id": "e4f44ac7",
"metadata": {
"origin_pos": 5
},
"source": [
"我们现在可以将存储在文件中的数据读回内存。\n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "1ab53461",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T06:56:43.733002Z",
"iopub.status.busy": "2023-08-18T06:56:43.732347Z",
"iopub.status.idle": "2023-08-18T06:56:43.741208Z",
"shell.execute_reply": "2023-08-18T06:56:43.740416Z"
},
"origin_pos": 7,
"tab": [
"pytorch"
]
},
"outputs": [
{
"data": {
"text/plain": [
"tensor([0, 1, 2, 3])"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x2 = torch.load('x-file')\n",
"x2"
]
},
{
"cell_type": "markdown",
"id": "44d4a111",
"metadata": {
"origin_pos": 10
},
"source": [
"我们可以[**存储一个张量列表,然后把它们读回内存。**]\n"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "81027fe1",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T06:56:43.744676Z",
"iopub.status.busy": "2023-08-18T06:56:43.744140Z",
"iopub.status.idle": "2023-08-18T06:56:43.751376Z",
"shell.execute_reply": "2023-08-18T06:56:43.750630Z"
},
"origin_pos": 12,
"tab": [
"pytorch"
]
},
"outputs": [
{
"data": {
"text/plain": [
"(tensor([0, 1, 2, 3]), tensor([0., 0., 0., 0.]))"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y = torch.zeros(4)\n",
"torch.save([x, y],'x-files')\n",
"x2, y2 = torch.load('x-files')\n",
"(x2, y2)"
]
},
{
"cell_type": "markdown",
"id": "b060dd48",
"metadata": {
"origin_pos": 15
},
"source": [
"我们甚至可以(**写入或读取从字符串映射到张量的字典**)。\n",
"当我们要读取或写入模型中的所有权重时,这很方便。\n"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "fde1cb33",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T06:56:43.754777Z",
"iopub.status.busy": "2023-08-18T06:56:43.754313Z",
"iopub.status.idle": "2023-08-18T06:56:43.761150Z",
"shell.execute_reply": "2023-08-18T06:56:43.760369Z"
},
"origin_pos": 17,
"tab": [
"pytorch"
]
},
"outputs": [
{
"data": {
"text/plain": [
"{'x': tensor([0, 1, 2, 3]), 'y': tensor([0., 0., 0., 0.])}"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"mydict = {'x': x, 'y': y}\n",
"torch.save(mydict, 'mydict')\n",
"mydict2 = torch.load('mydict')\n",
"mydict2"
]
},
{
"cell_type": "markdown",
"id": "afa857bf",
"metadata": {
"origin_pos": 20
},
"source": [
"## [**加载和保存模型参数**]\n",
"\n",
"保存单个权重向量(或其他张量)确实有用,\n",
"但是如果我们想保存整个模型,并在以后加载它们,\n",
"单独保存每个向量则会变得很麻烦。\n",
"毕竟,我们可能有数百个参数散布在各处。\n",
"因此,深度学习框架提供了内置函数来保存和加载整个网络。\n",
"需要注意的一个重要细节是,这将保存模型的参数而不是保存整个模型。\n",
"例如,如果我们有一个3层多层感知机,我们需要单独指定架构。\n",
"因为模型本身可以包含任意代码,所以模型本身难以序列化。\n",
"因此,为了恢复模型,我们需要用代码生成架构,\n",
"然后从磁盘加载参数。\n",
"让我们从熟悉的多层感知机开始尝试一下。\n"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "2672b5c2",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T06:56:43.764609Z",
"iopub.status.busy": "2023-08-18T06:56:43.764090Z",
"iopub.status.idle": "2023-08-18T06:56:43.773070Z",
"shell.execute_reply": "2023-08-18T06:56:43.772277Z"
},
"origin_pos": 22,
"tab": [
"pytorch"
]
},
"outputs": [],
"source": [
"class MLP(nn.Module):\n",
" def __init__(self):\n",
" super().__init__()\n",
" self.hidden = nn.Linear(20, 256)\n",
" self.output = nn.Linear(256, 10)\n",
"\n",
" def forward(self, x):\n",
" return self.output(F.relu(self.hidden(x)))\n",
"\n",
"net = MLP()\n",
"X = torch.randn(size=(2, 20))\n",
"Y = net(X)"
]
},
{
"cell_type": "markdown",
"id": "697ceed0",
"metadata": {
"origin_pos": 25
},
"source": [
"接下来,我们[**将模型的参数存储在一个叫做“mlp.params”的文件中。**]\n"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "a53c1315",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T06:56:43.776452Z",
"iopub.status.busy": "2023-08-18T06:56:43.775942Z",
"iopub.status.idle": "2023-08-18T06:56:43.780387Z",
"shell.execute_reply": "2023-08-18T06:56:43.779636Z"
},
"origin_pos": 27,
"tab": [
"pytorch"
]
},
"outputs": [],
"source": [
"torch.save(net.state_dict(), 'mlp.params')"
]
},
{
"cell_type": "markdown",
"id": "b6df754a",
"metadata": {
"origin_pos": 30
},
"source": [
"为了恢复模型,我们[**实例化了原始多层感知机模型的一个备份。**]\n",
"这里我们不需要随机初始化模型参数,而是(**直接读取文件中存储的参数。**)\n"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "da5e1b3f",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T06:56:43.783850Z",
"iopub.status.busy": "2023-08-18T06:56:43.783240Z",
"iopub.status.idle": "2023-08-18T06:56:43.789905Z",
"shell.execute_reply": "2023-08-18T06:56:43.789164Z"
},
"origin_pos": 32,
"tab": [
"pytorch"
]
},
"outputs": [
{
"data": {
"text/plain": [
"MLP(\n",
" (hidden): Linear(in_features=20, out_features=256, bias=True)\n",
" (output): Linear(in_features=256, out_features=10, bias=True)\n",
")"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"clone = MLP()\n",
"clone.load_state_dict(torch.load('mlp.params'))\n",
"clone.eval()"
]
},
{
"cell_type": "markdown",
"id": "65076662",
"metadata": {
"origin_pos": 35
},
"source": [
"由于两个实例具有相同的模型参数,在输入相同的`X`时,\n",
"两个实例的计算结果应该相同。\n",
"让我们来验证一下。\n"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "a25ba1f1",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T06:56:43.793400Z",
"iopub.status.busy": "2023-08-18T06:56:43.792788Z",
"iopub.status.idle": "2023-08-18T06:56:43.798329Z",
"shell.execute_reply": "2023-08-18T06:56:43.797576Z"
},
"origin_pos": 37,
"tab": [
"pytorch"
]
},
"outputs": [
{
"data": {
"text/plain": [
"tensor([[True, True, True, True, True, True, True, True, True, True],\n",
" [True, True, True, True, True, True, True, True, True, True]])"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Y_clone = clone(X)\n",
"Y_clone == Y"
]
},
{
"cell_type": "markdown",
"id": "7a65b1e2",
"metadata": {
"origin_pos": 39
},
"source": [
"## 小结\n",
"\n",
"* `save`和`load`函数可用于张量对象的文件读写。\n",
"* 我们可以通过参数字典保存和加载网络的全部参数。\n",
"* 保存架构必须在代码中完成,而不是在参数中完成。\n",
"\n",
"## 练习\n",
"\n",
"1. 即使不需要将经过训练的模型部署到不同的设备上,存储模型参数还有什么实际的好处?\n",
"1. 假设我们只想复用网络的一部分,以将其合并到不同的网络架构中。比如想在一个新的网络中使用之前网络的前两层,该怎么做?\n",
"1. 如何同时保存网络架构和参数?需要对架构加上什么限制?\n"
]
},
{
"cell_type": "markdown",
"id": "d803f301",
"metadata": {
"origin_pos": 41,
"tab": [
"pytorch"
]
},
"source": [
"[Discussions](https://discuss.d2l.ai/t/1839)\n"
]
}
],
"metadata": {
"language_info": {
"name": "python"
},
"required_libs": []
},
"nbformat": 4,
"nbformat_minor": 5
}
@@ -0,0 +1,768 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "618fd23a",
"metadata": {
"origin_pos": 0
},
"source": [
"# GPU\n",
":label:`sec_use_gpu`\n",
"\n",
"在 :numref:`tab_intro_decade`中,\n",
"我们回顾了过去20年计算能力的快速增长。\n",
"简而言之,自2000年以来,GPU性能每十年增长1000倍。\n",
"\n",
"本节,我们将讨论如何利用这种计算性能进行研究。\n",
"首先是如何使用单个GPU,然后是如何使用多个GPU和多个服务器(具有多个GPU)。\n",
"\n",
"我们先看看如何使用单个NVIDIA GPU进行计算。\n",
"首先,确保至少安装了一个NVIDIA GPU。\n",
"然后,下载[NVIDIA驱动和CUDA](https://developer.nvidia.com/cuda-downloads)\n",
"并按照提示设置适当的路径。\n",
"当这些准备工作完成,就可以使用`nvidia-smi`命令来(**查看显卡信息。**)\n"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "369d9baa",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T06:58:06.499888Z",
"iopub.status.busy": "2023-08-18T06:58:06.499324Z",
"iopub.status.idle": "2023-08-18T06:58:06.859541Z",
"shell.execute_reply": "2023-08-18T06:58:06.858210Z"
},
"origin_pos": 1,
"tab": [
"pytorch"
]
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Fri Aug 18 06:58:06 2023 \r\n",
"+-----------------------------------------------------------------------------+\r\n",
"| NVIDIA-SMI 470.161.03 Driver Version: 470.161.03 CUDA Version: 11.7 |\r\n",
"|-------------------------------+----------------------+----------------------+\r\n",
"| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |\r\n",
"| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |\r\n",
"| | | MIG M. |\r\n",
"|===============================+======================+======================|\r\n",
"| 0 Tesla V100-SXM2... Off | 00000000:00:1B.0 Off | 0 |\r\n",
"| N/A 41C P0 42W / 300W | 0MiB / 16160MiB | 0% Default |\r\n",
"| | | N/A |\r\n",
"+-------------------------------+----------------------+----------------------+\r\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"| 1 Tesla V100-SXM2... Off | 00000000:00:1C.0 Off | 0 |\r\n",
"| N/A 44C P0 113W / 300W | 1456MiB / 16160MiB | 53% Default |\r\n",
"| | | N/A |\r\n",
"+-------------------------------+----------------------+----------------------+\r\n",
"| 2 Tesla V100-SXM2... Off | 00000000:00:1D.0 Off | 0 |\r\n",
"| N/A 43C P0 120W / 300W | 1358MiB / 16160MiB | 55% Default |\r\n",
"| | | N/A |\r\n",
"+-------------------------------+----------------------+----------------------+\r\n",
"| 3 Tesla V100-SXM2... Off | 00000000:00:1E.0 Off | 0 |\r\n",
"| N/A 42C P0 47W / 300W | 0MiB / 16160MiB | 0% Default |\r\n",
"| | | N/A |\r\n",
"+-------------------------------+----------------------+----------------------+\r\n",
" \r\n",
"+-----------------------------------------------------------------------------+\r\n",
"| Processes: |\r\n",
"| GPU GI CI PID Type Process name GPU Memory |\r\n",
"| ID ID Usage |\r\n",
"|=============================================================================|\r\n",
"+-----------------------------------------------------------------------------+\r\n"
]
}
],
"source": [
"!nvidia-smi"
]
},
{
"cell_type": "markdown",
"id": "23e1982b",
"metadata": {
"origin_pos": 3,
"tab": [
"pytorch"
]
},
"source": [
"在PyTorch中,每个数组都有一个设备(device),\n",
"我们通常将其称为环境(context)。\n",
"默认情况下,所有变量和相关的计算都分配给CPU。\n",
"有时环境可能是GPU。\n",
"当我们跨多个服务器部署作业时,事情会变得更加棘手。\n",
"通过智能地将数组分配给环境,\n",
"我们可以最大限度地减少在设备之间传输数据的时间。\n",
"例如,当在带有GPU的服务器上训练神经网络时,\n",
"我们通常希望模型的参数在GPU上。\n"
]
},
{
"cell_type": "markdown",
"id": "aeacf63c",
"metadata": {
"origin_pos": 5
},
"source": [
"要运行此部分中的程序,至少需要两个GPU。\n",
"注意,对大多数桌面计算机来说,这可能是奢侈的,但在云中很容易获得。\n",
"例如可以使用AWS EC2的多GPU实例。\n",
"本书的其他章节大都不需要多个GPU,\n",
"而本节只是为了展示数据如何在不同的设备之间传递。\n",
"\n",
"## [**计算设备**]\n",
"\n",
"我们可以指定用于存储和计算的设备,如CPU和GPU。\n",
"默认情况下,张量是在内存中创建的,然后使用CPU计算它。\n"
]
},
{
"cell_type": "markdown",
"id": "872e46f0",
"metadata": {
"origin_pos": 7,
"tab": [
"pytorch"
]
},
"source": [
"在PyTorch中,CPU和GPU可以用`torch.device('cpu')`\n",
"和`torch.device('cuda')`表示。\n",
"应该注意的是,`cpu`设备意味着所有物理CPU和内存,\n",
"这意味着PyTorch的计算将尝试使用所有CPU核心。\n",
"然而,`gpu`设备只代表一个卡和相应的显存。\n",
"如果有多个GPU,我们使用`torch.device(f'cuda:{i}')`\n",
"来表示第$i$块GPU$i$从0开始)。\n",
"另外,`cuda:0`和`cuda`是等价的。\n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "9f69ad46",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T06:58:06.865430Z",
"iopub.status.busy": "2023-08-18T06:58:06.864979Z",
"iopub.status.idle": "2023-08-18T06:58:07.970615Z",
"shell.execute_reply": "2023-08-18T06:58:07.969801Z"
},
"origin_pos": 10,
"tab": [
"pytorch"
]
},
"outputs": [
{
"data": {
"text/plain": [
"(device(type='cpu'), device(type='cuda'), device(type='cuda', index=1))"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import torch\n",
"from torch import nn\n",
"\n",
"torch.device('cpu'), torch.device('cuda'), torch.device('cuda:1')"
]
},
{
"cell_type": "markdown",
"id": "248784cc",
"metadata": {
"origin_pos": 13
},
"source": [
"我们可以(**查询可用gpu的数量。**)\n"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "c29151b0",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T06:58:07.974568Z",
"iopub.status.busy": "2023-08-18T06:58:07.973917Z",
"iopub.status.idle": "2023-08-18T06:58:07.979097Z",
"shell.execute_reply": "2023-08-18T06:58:07.978337Z"
},
"origin_pos": 15,
"tab": [
"pytorch"
]
},
"outputs": [
{
"data": {
"text/plain": [
"2"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"torch.cuda.device_count()"
]
},
{
"cell_type": "markdown",
"id": "6e1bc4a6",
"metadata": {
"origin_pos": 18
},
"source": [
"现在我们定义了两个方便的函数,\n",
"[**这两个函数允许我们在不存在所需所有GPU的情况下运行代码。**]\n"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "cda0ab76",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T06:58:07.983261Z",
"iopub.status.busy": "2023-08-18T06:58:07.982604Z",
"iopub.status.idle": "2023-08-18T06:58:07.990309Z",
"shell.execute_reply": "2023-08-18T06:58:07.989541Z"
},
"origin_pos": 20,
"tab": [
"pytorch"
]
},
"outputs": [
{
"data": {
"text/plain": [
"(device(type='cuda', index=0),\n",
" device(type='cpu'),\n",
" [device(type='cuda', index=0), device(type='cuda', index=1)])"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def try_gpu(i=0): #@save\n",
" \"\"\"如果存在,则返回gpu(i),否则返回cpu()\"\"\"\n",
" if torch.cuda.device_count() >= i + 1:\n",
" return torch.device(f'cuda:{i}')\n",
" return torch.device('cpu')\n",
"\n",
"def try_all_gpus(): #@save\n",
" \"\"\"返回所有可用的GPU,如果没有GPU,则返回[cpu(),]\"\"\"\n",
" devices = [torch.device(f'cuda:{i}')\n",
" for i in range(torch.cuda.device_count())]\n",
" return devices if devices else [torch.device('cpu')]\n",
"\n",
"try_gpu(), try_gpu(10), try_all_gpus()"
]
},
{
"cell_type": "markdown",
"id": "034b0d3b",
"metadata": {
"origin_pos": 23
},
"source": [
"## 张量与GPU\n",
"\n",
"我们可以[**查询张量所在的设备。**]\n",
"默认情况下,张量是在CPU上创建的。\n"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "f6ab0f26",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T06:58:07.994741Z",
"iopub.status.busy": "2023-08-18T06:58:07.994126Z",
"iopub.status.idle": "2023-08-18T06:58:07.999439Z",
"shell.execute_reply": "2023-08-18T06:58:07.998673Z"
},
"origin_pos": 25,
"tab": [
"pytorch"
]
},
"outputs": [
{
"data": {
"text/plain": [
"device(type='cpu')"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x = torch.tensor([1, 2, 3])\n",
"x.device"
]
},
{
"cell_type": "markdown",
"id": "f39b0efa",
"metadata": {
"origin_pos": 28
},
"source": [
"需要注意的是,无论何时我们要对多个项进行操作,\n",
"它们都必须在同一个设备上。\n",
"例如,如果我们对两个张量求和,\n",
"我们需要确保两个张量都位于同一个设备上,\n",
"否则框架将不知道在哪里存储结果,甚至不知道在哪里执行计算。\n",
"\n",
"### [**存储在GPU上**]\n",
"\n",
"有几种方法可以在GPU上存储张量。\n",
"例如,我们可以在创建张量时指定存储设备。接\n",
"下来,我们在第一个`gpu`上创建张量变量`X`。\n",
"在GPU上创建的张量只消耗这个GPU的显存。\n",
"我们可以使用`nvidia-smi`命令查看显存使用情况。\n",
"一般来说,我们需要确保不创建超过GPU显存限制的数据。\n"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "a67dbf2f",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T06:58:08.004162Z",
"iopub.status.busy": "2023-08-18T06:58:08.003541Z",
"iopub.status.idle": "2023-08-18T06:58:09.277879Z",
"shell.execute_reply": "2023-08-18T06:58:09.277008Z"
},
"origin_pos": 30,
"tab": [
"pytorch"
]
},
"outputs": [
{
"data": {
"text/plain": [
"tensor([[1., 1., 1.],\n",
" [1., 1., 1.]], device='cuda:0')"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X = torch.ones(2, 3, device=try_gpu())\n",
"X"
]
},
{
"cell_type": "markdown",
"id": "dd17f6d7",
"metadata": {
"origin_pos": 33
},
"source": [
"假设我们至少有两个GPU,下面的代码将在(**第二个GPU上创建一个随机张量。**)\n"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "7c0d4a84",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T06:58:09.282814Z",
"iopub.status.busy": "2023-08-18T06:58:09.282230Z",
"iopub.status.idle": "2023-08-18T06:58:10.279046Z",
"shell.execute_reply": "2023-08-18T06:58:10.278227Z"
},
"origin_pos": 35,
"tab": [
"pytorch"
]
},
"outputs": [
{
"data": {
"text/plain": [
"tensor([[0.4860, 0.1285, 0.0440],\n",
" [0.9743, 0.4159, 0.9979]], device='cuda:1')"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Y = torch.rand(2, 3, device=try_gpu(1))\n",
"Y"
]
},
{
"cell_type": "markdown",
"id": "71646fa2",
"metadata": {
"origin_pos": 38
},
"source": [
"### 复制\n",
"\n",
"如果我们[**要计算`X + Y`,我们需要决定在哪里执行这个操作**]。\n",
"例如,如 :numref:`fig_copyto`所示,\n",
"我们可以将`X`传输到第二个GPU并在那里执行操作。\n",
"*不要*简单地`X`加上`Y`,因为这会导致异常,\n",
"运行时引擎不知道该怎么做:它在同一设备上找不到数据会导致失败。\n",
"由于`Y`位于第二个GPU上,所以我们需要将`X`移到那里,\n",
"然后才能执行相加运算。\n",
"\n",
"![复制数据以在同一设备上执行操作](../img/copyto.svg)\n",
":label:`fig_copyto`\n"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "9e700cd2",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T06:58:10.284097Z",
"iopub.status.busy": "2023-08-18T06:58:10.283529Z",
"iopub.status.idle": "2023-08-18T06:58:10.290795Z",
"shell.execute_reply": "2023-08-18T06:58:10.290007Z"
},
"origin_pos": 40,
"tab": [
"pytorch"
]
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"tensor([[1., 1., 1.],\n",
" [1., 1., 1.]], device='cuda:0')\n",
"tensor([[1., 1., 1.],\n",
" [1., 1., 1.]], device='cuda:1')\n"
]
}
],
"source": [
"Z = X.cuda(1)\n",
"print(X)\n",
"print(Z)"
]
},
{
"cell_type": "markdown",
"id": "f57eab12",
"metadata": {
"origin_pos": 42
},
"source": [
"[**现在数据在同一个GPU上(`Z`和`Y`都在),我们可以将它们相加。**]\n"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "b2f04f35",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T06:58:10.295377Z",
"iopub.status.busy": "2023-08-18T06:58:10.294845Z",
"iopub.status.idle": "2023-08-18T06:58:10.301122Z",
"shell.execute_reply": "2023-08-18T06:58:10.300297Z"
},
"origin_pos": 43,
"tab": [
"pytorch"
]
},
"outputs": [
{
"data": {
"text/plain": [
"tensor([[1.4860, 1.1285, 1.0440],\n",
" [1.9743, 1.4159, 1.9979]], device='cuda:1')"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Y + Z"
]
},
{
"cell_type": "markdown",
"id": "9acbe573",
"metadata": {
"origin_pos": 45,
"tab": [
"pytorch"
]
},
"source": [
"假设变量`Z`已经存在于第二个GPU上。\n",
"如果我们还是调用`Z.cuda(1)`会发生什么?\n",
"它将返回`Z`,而不会复制并分配新内存。\n"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "d6b95aa1",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T06:58:10.305143Z",
"iopub.status.busy": "2023-08-18T06:58:10.304592Z",
"iopub.status.idle": "2023-08-18T06:58:10.309707Z",
"shell.execute_reply": "2023-08-18T06:58:10.308894Z"
},
"origin_pos": 48,
"tab": [
"pytorch"
]
},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Z.cuda(1) is Z"
]
},
{
"cell_type": "markdown",
"id": "35568455",
"metadata": {
"origin_pos": 50
},
"source": [
"### 旁注\n",
"\n",
"人们使用GPU来进行机器学习,因为单个GPU相对运行速度快。\n",
"但是在设备(CPU、GPU和其他机器)之间传输数据比计算慢得多。\n",
"这也使得并行化变得更加困难,因为我们必须等待数据被发送(或者接收),\n",
"然后才能继续进行更多的操作。\n",
"这就是为什么拷贝操作要格外小心。\n",
"根据经验,多个小操作比一个大操作糟糕得多。\n",
"此外,一次执行几个操作比代码中散布的许多单个操作要好得多。\n",
"如果一个设备必须等待另一个设备才能执行其他操作,\n",
"那么这样的操作可能会阻塞。\n",
"这有点像排队订购咖啡,而不像通过电话预先订购:\n",
"当客人到店的时候,咖啡已经准备好了。\n",
"\n",
"最后,当我们打印张量或将张量转换为NumPy格式时,\n",
"如果数据不在内存中,框架会首先将其复制到内存中,\n",
"这会导致额外的传输开销。\n",
"更糟糕的是,它现在受制于全局解释器锁,使得一切都得等待Python完成。\n",
"\n",
"## [**神经网络与GPU**]\n",
"\n",
"类似地,神经网络模型可以指定设备。\n",
"下面的代码将模型参数放在GPU上。\n"
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "587af904",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T06:58:10.313163Z",
"iopub.status.busy": "2023-08-18T06:58:10.312623Z",
"iopub.status.idle": "2023-08-18T06:58:10.336351Z",
"shell.execute_reply": "2023-08-18T06:58:10.335568Z"
},
"origin_pos": 52,
"tab": [
"pytorch"
]
},
"outputs": [],
"source": [
"net = nn.Sequential(nn.Linear(3, 1))\n",
"net = net.to(device=try_gpu())"
]
},
{
"cell_type": "markdown",
"id": "a834a04c",
"metadata": {
"origin_pos": 55
},
"source": [
"在接下来的几章中,\n",
"我们将看到更多关于如何在GPU上运行模型的例子,\n",
"因为它们将变得更加计算密集。\n",
"\n",
"当输入为GPU上的张量时,模型将在同一GPU上计算结果。\n"
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "955f7f67",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T06:58:10.340989Z",
"iopub.status.busy": "2023-08-18T06:58:10.340312Z",
"iopub.status.idle": "2023-08-18T06:58:10.930969Z",
"shell.execute_reply": "2023-08-18T06:58:10.930143Z"
},
"origin_pos": 56,
"tab": [
"pytorch"
]
},
"outputs": [
{
"data": {
"text/plain": [
"tensor([[-0.4275],\n",
" [-0.4275]], device='cuda:0', grad_fn=<AddmmBackward0>)"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"net(X)"
]
},
{
"cell_type": "markdown",
"id": "fb9f9aef",
"metadata": {
"origin_pos": 57
},
"source": [
"让我们(**确认模型参数存储在同一个GPU上。**)\n"
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "bd727993",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T06:58:10.935087Z",
"iopub.status.busy": "2023-08-18T06:58:10.934497Z",
"iopub.status.idle": "2023-08-18T06:58:10.939740Z",
"shell.execute_reply": "2023-08-18T06:58:10.938974Z"
},
"origin_pos": 59,
"tab": [
"pytorch"
]
},
"outputs": [
{
"data": {
"text/plain": [
"device(type='cuda', index=0)"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"net[0].weight.data.device"
]
},
{
"cell_type": "markdown",
"id": "cf1bf3b2",
"metadata": {
"origin_pos": 62
},
"source": [
"总之,只要所有的数据和参数都在同一个设备上,\n",
"我们就可以有效地学习模型。\n",
"在下面的章节中,我们将看到几个这样的例子。\n",
"\n",
"## 小结\n",
"\n",
"* 我们可以指定用于存储和计算的设备,例如CPU或GPU。默认情况下,数据在主内存中创建,然后使用CPU进行计算。\n",
"* 深度学习框架要求计算的所有输入数据都在同一设备上,无论是CPU还是GPU。\n",
"* 不经意地移动数据可能会显著降低性能。一个典型的错误如下:计算GPU上每个小批量的损失,并在命令行中将其报告给用户(或将其记录在NumPy `ndarray`中)时,将触发全局解释器锁,从而使所有GPU阻塞。最好是为GPU内部的日志分配内存,并且只移动较大的日志。\n",
"\n",
"## 练习\n",
"\n",
"1. 尝试一个计算量更大的任务,比如大矩阵的乘法,看看CPU和GPU之间的速度差异。再试一个计算量很小的任务呢?\n",
"1. 我们应该如何在GPU上读写模型参数?\n",
"1. 测量计算1000个$100 \\times 100$矩阵的矩阵乘法所需的时间,并记录输出矩阵的Frobenius范数,一次记录一个结果,而不是在GPU上保存日志并仅传输最终结果。\n",
"1. 测量同时在两个GPU上执行两个矩阵乘法与在一个GPU上按顺序执行两个矩阵乘法所需的时间。提示:应该看到近乎线性的缩放。\n"
]
},
{
"cell_type": "markdown",
"id": "0460f3be",
"metadata": {
"origin_pos": 64,
"tab": [
"pytorch"
]
},
"source": [
"[Discussions](https://discuss.d2l.ai/t/1841)\n"
]
}
],
"metadata": {
"language_info": {
"name": "python"
},
"required_libs": []
},
"nbformat": 4,
"nbformat_minor": 5
}