快捷方式

torch.vmap

创建日期:2020 年 10 月 26 日 | 最后更新:2021 年 9 月 01 日 | 最后验证:未验证

本教程介绍了 torch.vmap,一个用于 PyTorch 操作的自动向量化工具。torch.vmap 是一个原型功能,目前无法处理许多用例;但是,我们希望收集其用例以改进设计。如果您正在考虑使用 torch.vmap 或认为它在某些方面会非常有用,请通过 https://github.com/pytorch/pytorch/issues/42368 联系我们。

那么,什么是 vmap?

vmap 是一个高阶函数。它接受一个函数 func,并返回一个新函数,该函数将 func 映射到输入数据的某个维度上。它在很大程度上受到了 JAX 的 vmap 的启发。

语义上,vmap 将“映射”推入由 func 调用的 PyTorch 操作中,有效地向量化了这些操作。

import torch
# NB: vmap is only available on nightly builds of PyTorch.
# You can download one at pytorch.org if you're interested in testing it out.
from torch import vmap

vmap 的第一个用例是使处理代码中的批处理维度变得更容易。可以编写一个对单个样本运行的函数 func,然后使用 vmap(func) 将其提升为一个可以处理批量样本的函数。但是,func 受制于许多限制:

  • 它必须是函数式的(不能在其中修改 Python 数据结构),就地 (in-place) PyTorch 操作除外。

  • 批量样本必须以张量形式提供。这意味着 vmap 本身无法处理变长序列。

使用 vmap 的一个例子是计算批处理的点积。PyTorch 没有提供批处理的 torch.dot API;与其徒劳地查阅文档,不如使用 vmap 构建一个新函数。

torch.dot                            # [D], [D] -> []
batched_dot = torch.vmap(torch.dot)  # [N, D], [N, D] -> [N]
x, y = torch.randn(2, 5), torch.randn(2, 5)
batched_dot(x, y)

vmap 有助于隐藏批处理维度,从而简化模型编写体验。

batch_size, feature_size = 3, 5
weights = torch.randn(feature_size, requires_grad=True)

# Note that model doesn't work with a batch of feature vectors because
# torch.dot must take 1D tensors. It's pretty easy to rewrite this
# to use `torch.matmul` instead, but if we didn't want to do that or if
# the code is more complicated (e.g., does some advanced indexing
# shenanigins), we can simply call `vmap`. `vmap` batches over ALL
# inputs, unless otherwise specified (with the in_dims argument,
# please see the documentation for more details).
def model(feature_vec):
    # Very simple linear model with activation
    return feature_vec.dot(weights).relu()

examples = torch.randn(batch_size, feature_size)
result = torch.vmap(model)(examples)
expected = torch.stack([model(example) for example in examples.unbind()])
assert torch.allclose(result, expected)

vmap 还可以帮助向量化之前难以或无法进行批量处理的计算。这引出了我们的第二个用例:批处理梯度计算。

PyTorch 的 autograd 引擎计算 vjps(向量-雅可比乘积)。使用 vmap,我们可以计算(批处理向量)- 雅可比乘积。

一个例子是计算完整的雅可比矩阵(这也可应用于计算完整的 Hessian 矩阵)。对于函数 f: R^N -> R^N 计算完整的雅可比矩阵通常需要调用 autograd.grad N 次,雅可比的每一行调用一次。

# Setup
N = 5
def f(x):
    return x ** 2

x = torch.randn(N, requires_grad=True)
y = f(x)
basis_vectors = torch.eye(N)

# Sequential approach
jacobian_rows = [torch.autograd.grad(y, x, v, retain_graph=True)[0]
                 for v in basis_vectors.unbind()]
jacobian = torch.stack(jacobian_rows)

# Using `vmap`, we can vectorize the whole computation, computing the
# Jacobian in a single call to `autograd.grad`.
def get_vjp(v):
    return torch.autograd.grad(y, x, v)[0]

jacobian_vmap = vmap(get_vjp)(basis_vectors)
assert torch.allclose(jacobian_vmap, jacobian)

vmap 的第三个主要用例是计算逐样本梯度 (per-sample-gradients)。这是 vmap 原型目前无法高性能处理的功能。我们不确定计算逐样本梯度的 API 应该是什么样子,如果您有想法,请在 https://github.com/pytorch/pytorch/issues/7786 中评论。

def model(sample, weight):
    # do something...
    return torch.dot(sample, weight)

def grad_sample(sample):
    return torch.autograd.functional.vjp(lambda weight: model(sample), weight)[1]

# The following doesn't actually work in the vmap prototype. But it
# could be an API for computing per-sample-gradients.

# batch_of_samples = torch.randn(64, 5)
# vmap(grad_sample)(batch_of_samples)

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

Gallery 由 Sphinx-Gallery 生成


评价本教程

© 版权所有 2024, PyTorch.

使用 Sphinx 构建,主题由 Read the Docs 提供。

文档

查阅 PyTorch 的全面开发者文档

查看文档

教程

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

查看教程

资源

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

查看资源