1.层和块
块(block)可以描述单个层、由多个层组成的组件或整个模型本身。使用块进行抽象的一个好处是可以将一些块组合成更大的组件, 这一过程通常是递归的, 通过定义代码来按需生成任意复杂度的块, 我们可以通过简洁的代码实现复杂的神经网络。
从编程的角度来看,块由类(class)表示。 它的任何子类都必须定义一个将其输入转换为输出的前向传播函数, 并且必须存储任何必需的参数。 注意,有些块不需要任何参数。 最后,为了计算梯度,块必须具有反向传播函数。 在定义我们自己的块时,由于自动微分提供了一些后端实现,我们只需要考虑前向传播函数和必需的参数。
下面的代码生成一个网络,其中包含一个具有256个单元和ReLU激活函数的全连接隐藏层, 然后是一个具有10个隐藏单元且不带激活函数的全连接输出层。
import torch
from torch import nn
from torch.nn import functional as F
net = nn.Sequential(nn.Linear(20, 256), nn.ReLU(), nn.Linear(256, 10))
X = torch.rand(2, 20)
net(X)
tensor([[ 0.0343, 0.0264, 0.2505, -0.0243, 0.0945, 0.0012, -0.0141, 0.0666, -0.0547, -0.0667], [ 0.0772, -0.0274, 0.2638, -0.0191, 0.0394, -0.0324, 0.0102, 0.0707, -0.1481, -0.1031]], grad_fn=<AddmmBackward0>)
1.1自定义块
我们简要总结一下每个块必须提供的基本功能。
-
将输入数据作为其前向传播函数的参数。
-
通过前向传播函数来生成输出。请注意,输出的形状可能与输入的形状不同。例如,我们上面模型中的第一个全连接的层接收一个20维的输入,但是返回一个维度为256的输出。
-
计算其输出关于输入的梯度,可通过其反向传播函数进行访问。通常这是自动发生的。
-
存储和访问前向传播计算所需的参数。
-
根据需要初始化模型参数。
下面我们自己定义了一个块,他是一个具有256层隐藏层和10输出层的多层感知机
class MLP(nn.Module):
# 用模型参数声明层。这里,我们声明两个全连接的层
def __init__(self):
# 调用MLP的父类Module的构造函数来执行必要的初始化。
# 这样,在类实例化时也可以指定其他函数参数,例如模型参数params(稍后将介绍)
super().__init__()
self.hidden = nn.Linear(20, 256) # 隐藏层
self.out = nn.Linear(256, 10) # 输出层
# 定义模型的前向传播,即如何根据输入X返回所需的模型输出
def forward(self, X):
# 注意,这里我们使用ReLU的函数版本,其在nn.functional模块中定义。
return self.out(F.relu(self.hidden(X)))
我们写的
__init__
函数通过super().__init__()
调用父类的__init__
函数, 省去了重复编写模版代码,然后实例化了两个全连层分别为self.hidden
和self.out
。然后定义了前向传播返回输出。
1.2顺序块
现在我们可以更仔细地看看Sequential
类是如何工作的, 回想一下Sequential
的设计是为了把其他模块串起来。 为了构建我们自己的简化的MySequential
, 我们只需要定义两个关键函数:
-
一种将块逐个追加到列表中的函数;
-
一种前向传播函数,用于将输入按追加块的顺序传递给块组成的“链条”。
下面的MySequential
类提供了与默认Sequential
类相同的功能。
class MySequential(nn.Module):
def __init__(self, *args):
super().__init__()
for idx, module in enumerate(args):
# 这里,module是Module子类的一个实例。我们把它保存在'Module'类的成员
# 变量_modules中。_module的类型是OrderedDict
self._modules[str(idx)] = module
def forward(self, X):
for block in self._modules.values():
X = block(X)
return X
__init__
函数将每个模块逐个添加到有序字典_modules
中._modules
的主要优点是: 在模块的参数初始化过程中, 系统知道在_modules
字典中查找需要初始化参数的子块。当
MySequential
的前向传播函数被调用时, 每个添加的块都按照它们被添加的顺序执行。
net = MySequential(nn.Linear(20, 256), nn.ReLU(), nn.Linear(256, 10))
net(X)
tensor([[ 2.2759e-01, -4.7003e-02, 4.2846e-01, -1.2546e-01, 1.5296e-01, 1.8972e-01, 9.7048e-02, 4.5479e-04, -3.7986e-02, 6.4842e-02], [ 2.7825e-01, -9.7517e-02, 4.8541e-01, -2.4519e-01, -8.4580e-02, 2.8538e-01, 3.6861e-02, 2.9411e-02, -1.0612e-01, 1.2620e-01]], grad_fn=<AddmmBackward0>)
1.3在前向传播函数中执行代码
有时我们可能希望合并既不是上一层的结果也不是可更新参数的项, 我们称之为常数参数(constant parameter)。 例如,我们需要一个计算函数 𝑓(𝑥,𝑤)=𝑐⋅𝑤⊤𝑥的层, 其中𝑥是输入, 𝑤是参数, 𝑐是某个在优化过程中没有更新的指定常量。 因此我们实现了一个FixedHiddenMLP
类。
class FixedHiddenMLP(nn.Module):
def __init__(self):
super().__init__()
# 不计算梯度的随机权重参数。因此其在训练期间保持不变
self.rand_weight = torch.rand((20, 20), requires_grad=False)
self.linear = nn.Linear(20, 20)
def forward(self, X):
X = self.linear(X)
# 使用创建的常量参数以及relu和mm函数
X = F.relu(torch.mm(X, self.rand_weight) + 1)
# 复用全连接层。这相当于两个全连接层共享参数
X = self.linear(X)
# 控制流
while X.abs().sum() > 1:
X /= 2
return X.sum()
我们实现了一个隐藏层, 其权重(self.rand_weight
)在实例化时被随机初始化,之后为常量。 这个权重不是一个模型参数,因此它永远不会被反向传播更新。 然后,神经网络将这个固定层的输出通过一个全连接层。
我们可以混合搭配各种组合块的方法。 在下面的例子中,我们以一些想到的方法嵌套块。
class NestMLP(nn.Module):
def __init__(self):
super().__init__()
self.net = nn.Sequential(nn.Linear(20, 64), nn.ReLU(),
nn.Linear(64, 32), nn.ReLU())
self.linear = nn.Linear(32, 16)
def forward(self, X):
return self.linear(self.net(X))
chimera = nn.Sequential(NestMLP(), nn.Linear(16, 20), FixedHiddenMLP())
chimera(X)
tensor(0.2183, grad_fn=<SumBackward0>)
2.参数管理
在之前学习的训练中我们往往忽略了参数的具体操作和细节,以下具体说明:
-
访问参数,用于调试、诊断和可视化;
-
参数初始化;
-
在不同模型组件间共享参数。
以一个具有单隐藏层的多层感知机为例
import torch from torch import nn net = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 1)) X = torch.rand(size=(2, 4))
2.1 参数访问
通过Sequential
类定义模型时, 我们可以通过索引来访问模型的任意层。例如访问第二个全连接层的参数。
print(net[2].state_dict())
OrderedDict([('weight', tensor([[-0.0427, -0.2939, -0.1894, 0.0220, -0.1709, -0.1522, -0.0334, -0.2263]])), ('bias', tensor([0.0887]))])
通过输出结果可以看到,这个全连接层包含两个参数,分别为权重和偏置。
2.1.1目标参数
要对参数执行操作,我们需要访问所需要的参数数值。
print(type(net[2].bias))
print(net[2].bias)
print(net[2].bias.data)
net[2].weight.grad == None
- 第一行代码打印出第三个层的偏置项的数据类型
<class 'torch.nn.parameter.Parameter'>- 第二行代码打印出第三个层的偏置项的值和梯度信息
tensor([0.0887], requires_grad=True)- 第三行代码仅仅打印了张量的数据部分,而不包括其他属性。
tensor([0.0887])- 第四行代码可以让我们访问每个参数的梯度信息
True
2.1.2一次性访问所有参数
当我们需要对所有参数执行操作时,逐个访问它们可能会很麻烦。下面,我们将通过演示来比较访问第一个全连接层的参数和访问所有层。
print(*[(name, param.shape) for name, param in net.named_parameters()])
named_parameters()
方法用于遍历神经网络模型的所有参数,并返回参数的名称以及对应的参数值。这里通过列表推导式将参数名称和形状组成的元组收集起来,然后通过print(*...)
打印出来。('0.weight', torch.Size([8, 4])) ('0.bias', torch.Size([8])) ('2.weight', torch.Size([1, 8])) ('2.bias', torch.Size([1]))
根据这个输出结果为我们提供了另一种访问方式,例如访问第三层的偏置。
net.state_dict()['2.bias'].data
2.1.3从嵌套快收集参数
如果我们将多个块相互嵌套,参数命名约定是如何工作的。 我们首先定义一个生成块的函数(可以说是“块工厂”),然后将这些块组合到更大的块中。
def block1():
return nn.Sequential(nn.Linear(4, 8), nn.ReLU(),
nn.Linear(8, 4), nn.ReLU())
def block2():
net = nn.Sequential()
for i in range(4):
# 在这里嵌套
net.add_module(f'block {i}', block1())
return net
rgnet = nn.Sequential(block2(), nn.Linear(4, 1))
print(rgnet)
运行结果:
Sequential( (0): Sequential( (block 0): Sequential( (0): Linear(in_features=4, out_features=8, bias=True) (1): ReLU() (2): Linear(in_features=8, out_features=4, bias=True) (3): ReLU() ) (block 1): Sequential( (0): Linear(in_features=4, out_features=8, bias=True) (1): ReLU() (2): Linear(in_features=8, out_features=4, bias=True) (3): ReLU() ) (block 2): Sequential( (0): Linear(in_features=4, out_features=8, bias=True) (1): ReLU() (2): Linear(in_features=8, out_features=4, bias=True) (3): ReLU() ) (block 3): Sequential( (0): Linear(in_features=4, out_features=8, bias=True) (1): ReLU() (2): Linear(in_features=8, out_features=4, bias=True) (3): ReLU() ) ) (1): Linear(in_features=4, out_features=1, bias=True) )
我们可以看出它是如何工作的,因为层是分层嵌套的,所以我们也可以像通过嵌套列表索引一样访问它们。 下面,我们访问第一个主要的块中、第二个子块的第一层的偏置项。
rgnet[0][1][0].bias.data
运行结果: tensor([ 0.1999, -0.4073, -0.1200, -0.2033, -0.1573, 0.3546, -0.2141, -0.2483])
2.2参数初始化
知道了如何访问参数后,现在我们就需要了解如何正确的对参数进行初始化,在深度学习框架中,默认提供了随机初始化,我们也可以通过自建初始化方法,满足一些特殊的规则的初始化。
2.2.1内置初始化
我们首先调用内置的初始化器。
权重初始化为标准差为0.01的高斯随机变量,且将偏置参数设置为0。
def init_normal(m):
if type(m) == nn.Linear:
nn.init.normal_(m.weight, mean=0, std=0.01)
nn.init.zeros_(m.bias)
net.apply(init_normal)
net[0].weight.data[0], net[0].bias.data[0]
我们还可以将所有参数初始化为给定的常数,比如初始化为1。
def init_constant(m):
if type(m) == nn.Linear:
nn.init.constant_(m.weight, 1)
nn.init.zeros_(m.bias)
net.apply(init_constant)
net[0].weight.data[0], net[0].bias.data[0]
使用Xavier初始化方法初始化第一个神经网络层, 然后将第三个神经网络层初始化为常量值42。
def init_xavier(m):
if type(m) == nn.Linear:
nn.init.xavier_uniform_(m.weight)
def init_42(m):
if type(m) == nn.Linear:
nn.init.constant_(m.weight, 42)
net[0].apply(init_xavier)
net[2].apply(init_42)
print(net[0].weight.data[0])
print(net[2].weight.data)
2.3自定义初始化
def my_init(m):
if type(m) == nn.Linear:
print("Init", *[(name, param.shape)
for name, param in m.named_parameters()][0])
nn.init.uniform_(m.weight, -10, 10)
m.weight.data *= m.weight.data.abs() >= 5
net.apply(my_init)
net[0].weight[:2]
tensor([[5.4079, 9.3334, 5.0616, 8.3095], [0.0000, 7.2788, -0.0000, -0.0000]], grad_fn=<SliceBackward0>)
我们始终可以直接设置参数。
net[0].weight.data[:] += 1
net[0].weight.data[0, 0] = 42
net[0].weight.data[0]
tensor([42.0000, 10.3334, 6.0616, 9.3095])
2.4参数绑定
有时我们希望在多个层间共享参数: 我们可以定义一个稠密层,然后使用它的参数来设置另一个层的参数。
# 我们需要给共享层一个名称,以便可以引用它的参数
shared = nn.Linear(8, 8)
net = nn.Sequential(nn.Linear(4, 8), nn.ReLU(),
shared, nn.ReLU(),
shared, nn.ReLU(),
nn.Linear(8, 1))
net(X)
# 检查参数是否相同
print(net[2].weight.data[0] == net[4].weight.data[0])
net[2].weight.data[0, 0] = 100
# 确保它们实际上是同一个对象,而不只是有相同的值
print(net[2].weight.data[0] == net[4].weight.data[0])
tensor([True, True, True, True, True, True, True, True]) tensor([True, True, True, True, True, True, True, True])
这个例子表明第三个和第五个神经网络层的参数是绑定的。它们不仅值相等,而且由相同的张量表示。 因此,如果我们改变其中一个参数,另一个参数也会改变。由于模型参数包含梯度,因此在反向传播期间第二个隐藏层和第三个隐藏层的梯度会加在一起。
3.自定义层
深度学习成功背后的一个因素是神经网络的灵活性: 我们可以用创造性的方式组合不同的层,从而设计出适用于各种任务的架构。
3.1不带参数的层
下面的CenteredLayer
类要从其输入中减去均值。 要构建它,我们只需继承基础层类并实现前向传播功能。
import torch
import torch.nn.functional as F
from torch import nn
class CenteredLayer(nn.Module):
def __init__(self):
super().__init__()
def forward(self, X):
return X - X.mean()
我们通过调用这个层看看能否正常工作。
layer = CenteredLayer()
layer(torch.FloatTensor([1, 2, 3, 4, 5]))
tensor([-2., -1., 0., 1., 2.])
3.2带参数的层
我们可以使用内置函数来创建参数,这些函数提供一些基本的管理功能。 比如管理访问、初始化、共享、保存和加载模型参数。 这样做的好处之一是:我们不需要为每个自定义层编写自定义的序列化程序。
正如之前所用到的全连接层,通常有两个参数,权重和偏置。我们使用relu作为激活函数,该层需要两个参数,in_units
和units
,分别表示输入数和输出数。
class MyLinear(nn.Module):
def __init__(self, in_units, units):
super().__init__()
self.weight = nn.Parameter(torch.randn(in_units, units))
self.bias = nn.Parameter(torch.randn(units,))
def forward(self, X):
linear = torch.matmul(X, self.weight.data) + self.bias.data
return F.relu(linear)
接下来我们实例化层并访问参数
linear = MyLinear(5, 3)
linear.weight
Parameter containing: tensor([[ 0.1775, -1.4539, 0.3972], [-0.1339, 0.5273, 1.3041], [-0.3327, -0.2337, -0.6334], [ 1.2076, -0.3937, 0.6851], [-0.4716, 0.0894, -0.9195]], requires_grad=True)
利用自定义层进行前向传播
linear(torch.rand(2, 5))
tensor([[0.0984, 0.5687, 2.8316],[2.2558, 0.0000, 1.8880]])
3.3小结
- 通过自定义层我们可以灵活的定义新层。
- 我们可以在任意环境和网络构架中调用该层。
4.读写文件
有时我们希望保存训练的模型, 以备将来在各种环境中使用。 此外,当运行一个耗时较长的训练过程时, 最佳的做法是定期保存中间结果, 以确保在服务器电源被不小心断掉时,我们不会损失几天的计算结果。 下面将学习如何加载和存储权重向量和整个模型。
4.1加载和保存张量
对于单个张量,我们可以直接调用load
和save
函数分别读写它们。 这两个函数都要求我们提供一个名称,save
要求将要保存的变量作为输入。
import torch
from torch import nn
from torch.nn import functional as F
x = torch.arange(4)
torch.save(x, 'x-file')
我们现在可以将存储在文件中的数据读回内存。
x2 = torch.load('x-file')
x2
tensor([0, 1, 2, 3])
我们可以存储一个张量列表,然后把它们读回内存。
y = torch.zeros(4)
torch.save([x, y],'x-files')
x2, y2 = torch.load('x-files')
(x2, y2)
(tensor([0, 1, 2, 3]), tensor([0., 0., 0., 0.]))
我们也以写入或读取从字符串映射到张量的字典。
mydict = {'x': x, 'y': y}
torch.save(mydict, 'mydict')
mydict2 = torch.load('mydict')
mydict2
{'x': tensor([0, 1, 2, 3]), 'y': tensor([0., 0., 0., 0.])}
4.2 加载和保存模型参数
保存单个参数固然可以,但是如果我们想保存整个模型就很麻烦,因为我们可能有数百个参数散布在各处,一个一个保存就很耗费时间。因此,深度学习框架为我们提供了内置函数来保存和加载整个网络。注意这保存的是模型的参数而不是整个模型。为了恢复模型,我们需要用代码生成架构, 然后从磁盘加载参数。
以多层感知机开始尝试。
class MLP(nn.Module):
def __init__(self):
super().__init__()
self.hidden = nn.Linear(20, 256)
self.output = nn.Linear(256, 10)
def forward(self, x):
return self.output(F.relu(self.hidden(x)))
net = MLP()
X = torch.randn(size=(2, 20))
Y = net(X)
接下来我们将模型的参数保存到“mlp.params”的文件中。
torch.save(net.state_dict(), 'mlp.params')
为了恢复模型,我们实例化了一个同原始多层感知机模型一样的一个模型。 这里我们直接读取文件中存储的参数。
clone = MLP()
clone.load_state_dict(torch.load('mlp.params'))
clone.eval()
MLP( (hidden): Linear(in_features=20, out_features=256, bias=True) (output): Linear(in_features=256, out_features=10, bias=True) )
由于两个实例具有相同的模型参数,在输入相同的X
时, 两个实例的计算结果应该相同。
Y_clone = clone(X)
Y_clone == Y
tensor([[True, True, True, True, True, True, True, True, True, True], [True, True, True, True, True, True, True, True, True, True]])
5.GPU
5.1.计算设备
我们可以指定用于存储和计算的设备,如CPU和GPU。 默认情况下,张量是在内存中创建的,然后使用CPU计算它。
在PyTorch中,CPU和GPU可以用torch.device('cpu')
和torch.device('cuda')
表示。 应该注意的是,cpu
设备意味着所有物理CPU和内存, 这意味着PyTorch的计算将尝试使用所有CPU核心。 然而,gpu
设备只代表一个卡和相应的显存。 如果有多个GPU,我们使用torch.device(f'cuda:{i}')
来表示第𝑖块GPU(𝑖从0开始)。 另外,cuda:0
和cuda
是等价的。
import torch
from torch import nn
torch.device('cpu'), torch.device('cuda'), torch.device('cuda:1')
(device(type='cpu'), device(type='cuda'), device(type='cuda', index=1))
现在我们定义了两个方便的函数, 这两个函数允许我们在不存在所需所有GPU的情况下运行代码。
def try_gpu(i=0): #@save
"""如果存在,则返回gpu(i),否则返回cpu()"""
if torch.cuda.device_count() >= i + 1:
return torch.device(f'cuda:{i}')
return torch.device('cpu')
def try_all_gpus(): #@save
"""返回所有可用的GPU,如果没有GPU,则返回[cpu(),]"""
devices = [torch.device(f'cuda:{i}')
for i in range(torch.cuda.device_count())]
return devices if devices else [torch.device('cpu')]
try_gpu(), try_gpu(10), try_all_gpus()
(device(type='cuda', index=0), device(type='cpu'), [device(type='cuda', index=0), device(type='cuda', index=1)])
5.2 张量与GPU
默认情况下,张量是创建在CPU上的,需要注意的是,如果我们需要对多个项进行操作,他们必须要同一个设备上。
5.2.1 存储在GPU上
有几种方法可以在GPU上存储张量。 例如,我们可以在创建张量时指定存储设备。 在GPU上创建的张量只消耗这个GPU的显存。 我们可以使用nvidia-smi
命令查看显存使用情况。 一般来说,我们需要确保不创建超过GPU显存限制的数据。
X = torch.ones(2, 3, device=try_gpu())
X
tensor([[1., 1., 1.], [1., 1., 1.]], device='cuda:0')
假设我们至少有两个GPU,下面的代码将在第二个GPU上创建一个随机张量。
Y = torch.rand(2, 3, device=try_gpu(1))
Y
tensor([[0.4860, 0.1285, 0.0440], [0.9743, 0.4159, 0.9979]], device='cuda:1')
5.3.复制
如果我们要计算X + Y
,我们需要决定在哪里执行这个操作。 例如,如 图5.6.1所示, 我们可以将X
传输到第二个GPU并在那里执行操作。 由于Y
位于第二个GPU上,所以我们需要将X
移到那里, 然后才能执行相加运算。
Z = X.cuda(1)
print(X)
print(Z)
tensor([[1., 1., 1.], [1., 1., 1.]], device='cuda:0') tensor([[1., 1., 1.], [1., 1., 1.]], device='cuda:1')
现在Z和Y在同一个GPU上,我们可以将他们相加。
5.4 神经网络与GPU
类似地,神经网络模型可以指定设备。 下面的代码将模型参数放在GPU上。
net = nn.Sequential(nn.Linear(3, 1))
net = net.to(device=try_gpu())
当输入为GPU上的张量时,模型将在同一GPU上计算结果。
net(X) tensor([[-0.4275], [-0.4275]], device='cuda:0', grad_fn=<AddmmBackward0>)
让我们确认模型参数存储在同一个GPU上。
net[0].weight.data.device
device(type='cuda', index=0)