深度学习计算

7501 字
19 分钟

当代码出Bug时,你需要重写逻辑;当人的情绪出Bug时,你只需要陪伴。

层和块

首先我们回顾一下多层感知机:

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)

nn.Sequential定义了一种特殊的 Module,在pytorch中,Module是一个很重要的概念。任何一个层和神经网络,都应该是一个Module的子类

在下面的代码中,我们从零开始实现上面使用 Sequential定义的 Module

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)))

顺序块

现在我们可以更好的理解Sequential类是如何工作的:

  1. 将块逐个追加到列表中的函数
  2. 前向传播函数,用于将输入按追加块的顺序传递给块组成的”链条”
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):
        # OrderedDict保证了按照成员添加的顺序遍历它们
        for block in self._modules.values():
            X = block(X)
        return X

灵活的计算

当Sequential这个类不能完全满足我们的需求的时候,我们可以使用继承Module类来自己构建神经网络。

优势:

  • __init__forward中可以做大量的自定义的计算

样例:

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()

混合搭配各种组合块的方法:

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)

参数管理

假设我们已经定义好我们的类了,我们如何访问模型中的参数?

首先我们以一个具有单隐藏层的多层感知机为例:

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))
net(X)

参数访问

Sequential就像是一个python列表,我们可以通过下标访问:

print(net[2].state_dict())

这里获得上述net中的 nn.Linear(8, 1))

输出:

OrderedDict([('weight', tensor([[-0.0427, -0.2939, -0.1894,  0.0220, -0.1709, -0.1522, -0.0334, -0.2263]])), ('bias', tensor([0.0887]))])

目标参数

print(type(net[2].bias))
print(net[2].bias)
print(net[2].bias.data)

输出:

<class 'torch.nn.parameter.Parameter'>
Parameter containing:
tensor([0.0887], requires_grad=True)
tensor([0.0887])

此时还没有反向传播:

net[2].weight.grad == None

输出:

True

一次性访问所有参数

print(*[(name, param.shape) for name, param in net[0].named_parameters()])
print(*[(name, param.shape) for name, param in net.named_parameters()])

输出:

('weight', torch.Size([8, 4])) ('bias', torch.Size([8]))
('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

从嵌套块收集参数

我们定义一个包含嵌套的网络:

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)
)

初始化参数

内置初始化

import torch.nn as nn

# 定义一个初始化函数,m 代表网络中的一个层(module)
def init_normal(m):
    # 检查当前层是否为全连接层 (Linear)
    if type(m) == nn.Linear:
        # 使用正态分布初始化权重 (weight)
        # mean=0: 均值为 0,std=0.01: 标准差为 0.01
        # 注意:带有下划线的函数(如 normal_)表示“原地操作”(in-place)
        nn.init.normal_(m.weight, mean=0, std=0.01)
  
        # 将偏置 (bias) 初始化为 0
        nn.init.zeros_(m.bias)

# 将定义好的初始化函数递归地应用到网络 net 的每一个子层上
net.apply(init_normal)

# 查看网络第一层 (net[0]) 的初始化结果
# 读取第一个权重的数值和第一个偏置的数值,用于验证初始化是否成功
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)

自定义初始化

有时,深度学习框架没有提供我们需要的初始化方法。 在下面的例子中,我们使用以下的分布为任意权重参数定义初始化方法:

w{U(5,10)可能性 140可能性 12U(10,5)可能性 14w \sim \left\{ \begin{aligned} &U(5, 10) && \text{可能性 } \frac{1}{4} \\ &0 && \text{可能性 } \frac{1}{2} \\ &U(-10, -5) && \text{可能性 } \frac{1}{4} \end{aligned} \right.
import torch.nn as nn

# 定义自定义初始化函数
def my_init(m):
    # 只针对全连接层 (Linear) 进行处理
    if type(m) == nn.Linear:
        # 打印当前层的初始化信息
        # m.named_parameters() 返回参数名和张量的迭代器
        # [0] 获取第一个参数(通常是 'weight'),* 用于解包元组进行打印
        print("Init", *[(name, param.shape)
                        for name, param in m.named_parameters()][0])
  
        # 步骤 1: 将权重初始化为 [-10, 10] 之间的均匀分布
        nn.init.uniform_(m.weight, -10, 10)
  
        # 步骤 2: 应用自定义掩码(逻辑过滤)
        # m.weight.data.abs() >= 5 会生成一个布尔张量(True/False)
        # 与原数据相乘时,True 视为 1.0,False 视为 0.0
        # 结果:保留绝对值大于等于 5 的权重,其余全部变为 0
        m.weight.data *= m.weight.data.abs() >= 5

# 将该初始化函数应用到整个网络 net 上
net.apply(my_init)

# 打印网络第一层的前两行权重权重,以验证“绝对值 < 5 的元素已置零”的效果
net[0].weight[:2]

我们也可以直接设置参数:

net[0].weight.data[:] += 1
net[0].weight.data[0, 0] = 42
net[0].weight.data[0]

参数绑定

有时我们希望在多个层间共享参数: 我们可以定义一个稠密层,然后使用它的参数来设置另一个层的参数。

# 我们需要给共享层一个名称,以便可以引用它的参数
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])

自定义层

自定义一个神经网络层和自定义一个网络其实没有本质区别,它们都是Module的子类:

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()

自定义层可以作为组件构建到更复杂的模型中:

net = nn.Sequential(nn.Linear(8, 128), CenteredLayer())

读写文件

加载保存张量

保存张量:

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')

存取张量列表:

y = torch.zeros(4)
torch.save([x, y],'x-files')
x2, y2 = torch.load('x-files')
(x2, y2)

张量字典:

mydict = {'x': x, 'y': y}
torch.save(mydict, 'mydict')
mydict2 = torch.load('mydict')
mydict2

加载保存模型参数

深度学习框架提供了内置函数来保存和加载整个网络。需要注意的是:这将保存模型的参数而不是保存整个模型。

为了恢复模型,我们需要用代码生成架构,然后从磁盘加载参数。以一个MLP为例:

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)

我们可以通过stae_dict(),来获取模型的所有参数并保存:

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)
)

GPU

安装好NVIDIA驱动和CUDA后,我们可以通过命令来查看GPU的状态:

!nvidia-smi

计算设备

在pytorch中,我们使用如下方式来指定计算设备:

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的数量:

torch.cuda.device_count()

我们可以定义两个方便的函数,在多GPU/无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()

张量与GPU

我们可以查询张量所在的设备。默认情况下,张量是在CPU上创建的:

1773914284936

无论何时我们要对多个项进行操作,它们都必须在同一个设备上。

有几种方法可以在GPU上存储张量:

  1. 在创建张量时指定存储设备:

    X = torch.ones(2, 3, device=try_gpu())
  2. 把张量复制到指定设备:

    Z = X.cuda(1)

神经网络与GPU

类似地,神经网络模型可以指定设备。下面的代码将模型参数放在GPU上:

net = nn.Sequential(nn.Linear(3, 1))
net = net.to(device=try_gpu())