快捷方式

模型集成

创建于:2023 年 3 月 15 日 | 最后更新:2024 年 1 月 16 日 | 最后验证:2024 年 11 月 05 日

本教程演示了如何使用 torch.vmap 对模型集成进行向量化。

什么是模型集成?

模型集成将多个模型的预测结果组合在一起。传统上,这是通过分别在一些输入上运行每个模型,然后组合预测结果来完成的。但是,如果您运行的是具有相同架构的模型,则可以使用 torch.vmap 将它们组合在一起。vmap 是一种函数变换,可将函数映射到输入张量的维度上。它的用例之一是通过向量化消除 for 循环并加速它们。

让我们演示如何使用简单的 MLP 集成来做到这一点。

注意

本教程需要 PyTorch 2.0.0 或更高版本。

import torch
import torch.nn as nn
import torch.nn.functional as F
torch.manual_seed(0)

# Here's a simple MLP
class SimpleMLP(nn.Module):
    def __init__(self):
        super(SimpleMLP, self).__init__()
        self.fc1 = nn.Linear(784, 128)
        self.fc2 = nn.Linear(128, 128)
        self.fc3 = nn.Linear(128, 10)

    def forward(self, x):
        x = x.flatten(1)
        x = self.fc1(x)
        x = F.relu(x)
        x = self.fc2(x)
        x = F.relu(x)
        x = self.fc3(x)
        return x

让我们生成一批虚拟数据,并假设我们正在处理 MNIST 数据集。因此,虚拟图像为 28x28,我们有一个大小为 64 的小批量。此外,假设我们想要组合来自 10 个不同模型的预测。

device = 'cuda'
num_models = 10

data = torch.randn(100, 64, 1, 28, 28, device=device)
targets = torch.randint(10, (6400,), device=device)

models = [SimpleMLP().to(device) for _ in range(num_models)]

我们有几种生成预测的选择。也许我们想为每个模型提供不同随机化的小批量数据。或者,也许我们想通过每个模型运行相同的小批量数据(例如,如果我们正在测试不同模型初始化的效果)。

选项 1:每个模型使用不同的小批量

minibatches = data[:num_models]
predictions_diff_minibatch_loop = [model(minibatch) for model, minibatch in zip(models, minibatches)]

选项 2:使用相同的小批量

minibatch = data[0]
predictions2 = [model(minibatch) for model in models]

使用 vmap 对集成进行向量化

让我们使用 vmap 加速 for 循环。我们必须首先准备好模型以与 vmap 一起使用。

首先,通过堆叠每个参数将模型的state组合在一起。例如,model[i].fc1.weight 的形状为 [784, 128];我们将堆叠 10 个模型中每个模型的 .fc1.weight,以生成形状为 [10, 784, 128] 的大权重。

PyTorch 提供了 torch.func.stack_module_state 便利函数来执行此操作。

from torch.func import stack_module_state

params, buffers = stack_module_state(models)

接下来,我们需要定义一个函数来使用 vmap 遍历。该函数应在给定参数、缓冲区和输入的情况下,使用这些参数、缓冲区和输入运行模型。我们将使用 torch.func.functional_call 来帮助实现。

from torch.func import functional_call
import copy

# Construct a "stateless" version of one of the models. It is "stateless" in
# the sense that the parameters are meta Tensors and do not have storage.
base_model = copy.deepcopy(models[0])
base_model = base_model.to('meta')

def fmodel(params, buffers, x):
    return functional_call(base_model, (params, buffers), (x,))

选项 1:为每个模型使用不同的小批量获取预测。

默认情况下,vmap 将函数映射到传递给函数的**所有**输入的第一个维度。使用 stack_module_state 后,每个 params 和缓冲区都在前面增加了一个大小为“num_models”的维度,而 minibatches 有一个大小为“num_models”的维度。

print([p.size(0) for p in params.values()]) # show the leading 'num_models' dimension

assert minibatches.shape == (num_models, 64, 1, 28, 28) # verify minibatch has leading dimension of size 'num_models'

from torch import vmap

predictions1_vmap = vmap(fmodel)(params, buffers, minibatches)

# verify the ``vmap`` predictions match the
assert torch.allclose(predictions1_vmap, torch.stack(predictions_diff_minibatch_loop), atol=1e-3, rtol=1e-5)
[10, 10, 10, 10, 10, 10]

选项 2:使用相同的小批量数据获取预测。

vmap 具有 in_dims 参数,用于指定要映射的维度。通过使用 None,我们告诉 vmap 我们希望相同的小批量应用于所有 10 个模型。

predictions2_vmap = vmap(fmodel, in_dims=(0, 0, None))(params, buffers, minibatch)

assert torch.allclose(predictions2_vmap, torch.stack(predictions2), atol=1e-3, rtol=1e-5)

快速说明:可以被 vmap 转换的函数类型存在限制。最适合转换的函数是纯函数:输出仅由输入确定且没有副作用(例如突变)的函数。vmap 无法处理任意 Python 数据结构的突变,但它能够处理许多就地 PyTorch 操作。

性能

对性能数字感到好奇?以下是数字的外观。

from torch.utils.benchmark import Timer
without_vmap = Timer(
    stmt="[model(minibatch) for model, minibatch in zip(models, minibatches)]",
    globals=globals())
with_vmap = Timer(
    stmt="vmap(fmodel)(params, buffers, minibatches)",
    globals=globals())
print(f'Predictions without vmap {without_vmap.timeit(100)}')
print(f'Predictions with vmap {with_vmap.timeit(100)}')
Predictions without vmap <torch.utils.benchmark.utils.common.Measurement object at 0x7fc7149c5930>
[model(minibatch) for model, minibatch in zip(models, minibatches)]
  2.88 ms
  1 measurement, 100 runs , 1 thread
Predictions with vmap <torch.utils.benchmark.utils.common.Measurement object at 0x7fc7149c5cf0>
vmap(fmodel)(params, buffers, minibatches)
  905.20 us
  1 measurement, 100 runs , 1 thread

使用 vmap 获得了很大的加速!

一般来说,使用 vmap 进行向量化应该比在 for 循环中运行函数更快,并且与手动批处理具有竞争力。但是,也有一些例外情况,例如,如果我们没有为特定操作实现 vmap 规则,或者底层内核未针对旧硬件(GPU)进行优化。如果您看到任何这些情况,请通过在 GitHub 上打开 issue 告知我们。

脚本总运行时间: (0 分 0.939 秒)

Gallery generated by Sphinx-Gallery

文档

访问 PyTorch 的全面开发者文档

查看文档

教程

获取面向初学者和高级开发者的深度教程

查看教程

资源

查找开发资源并获得您的问题解答

查看资源