快捷方式

torch.func.vmap

torch.func.vmap(func, in_dims=0, out_dims=0, randomness='error', *, chunk_size=None)[来源]

vmap 是向量化映射;vmap(func) 返回一个新的函数,该函数将 func 映射到输入张量的某个维度上。在语义上,vmap 将映射操作推送到由 func 调用的 PyTorch 操作中,从而有效地向量化这些操作。

vmap 对于处理批量维度非常有用:可以编写一个在单个样本上运行的函数 func,然后使用 vmap(func) 将其提升为可以接受批量样本的函数。vmap 还可以与 autograd 结合使用,计算批量梯度。

注意

torch.vmap()torch.func.vmap() 的别名,为了方便起见。你可以使用其中任何一个。

参数
  • func (function) – 一个接受一个或多个参数的 Python 函数。必须返回一个或多个 Tensor。

  • in_dims (int嵌套结构) – 指定输入张量的哪个维度应被映射。 in_dims 的结构应与输入张量类似。如果特定输入的 in_dim 为 None,则表明没有映射维度。默认值:0。

  • out_dims (intTuple[int]) – 指定映射维度应出现在输出张量的哪个位置。如果 out_dims 是一个 Tuple,则应包含与每个输出对应的元素。默认值:0。

  • randomness (str) – 指定此 vmap 中的随机性在不同批次之间是相同还是不同。如果是 ‘different’,则每个批次的随机性将不同。如果是 ‘same’,则随机性在不同批次之间将相同。如果是 ‘error’,则调用任何随机函数将报错。默认值:‘error’。警告:此标志仅适用于 PyTorch 的随机操作,不适用于 Python 的 random 模块或 numpy 的随机性。

  • chunk_size (Noneint) – 如果为 None(默认值),则对输入应用单个 vmap。如果不为 None,则每次计算 chunk_size 个样本的 vmap。注意,chunk_size=1 等同于通过 for 循环计算 vmap。如果你在计算 vmap 时遇到内存问题,请尝试使用非 None 的 chunk_size。

返回值

返回一个新的“批量化”函数。它接受与 func 相同的输入,不同之处在于每个输入在由 in_dims 指定的索引处多了一个维度。它返回与 func 相同的输出,不同之处在于每个输出在由 out_dims 指定的索引处多了一个维度。

返回类型

Callable

使用 vmap() 的一个例子是计算批量点积。PyTorch 没有提供批量化的 torch.dot API;无需在文档中徒劳地翻找,可以使用 vmap() 来构造一个新的函数。

>>> torch.dot                            # [D], [D] -> []
>>> batched_dot = torch.func.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)
>>>
>>> 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)

vmap() 还可以帮助向量化之前难以或不可能批量计算的操作。一个例子是高阶梯度计算。PyTorch 的 autograd 引擎计算 vjp(向量-雅可比积)。计算某个函数 f: R^N -> R^N 的完整雅可比矩阵通常需要调用 N 次 autograd.grad,每次计算一行雅可比矩阵。使用 vmap(),我们可以向量化整个计算过程,在一次调用 autograd.grad 中计算整个雅可比矩阵。

>>> # Setup
>>> N = 5
>>> f = lambda x: x ** 2
>>> x = torch.randn(N, requires_grad=True)
>>> y = f(x)
>>> I_N = torch.eye(N)
>>>
>>> # Sequential approach
>>> jacobian_rows = [torch.autograd.grad(y, x, v, retain_graph=True)[0]
>>>                  for v in I_N.unbind()]
>>> jacobian = torch.stack(jacobian_rows)
>>>
>>> # vectorized gradient computation
>>> def get_vjp(v):
>>>     return torch.autograd.grad(y, x, v)
>>> jacobian = torch.vmap(get_vjp)(I_N)

vmap() 还可以嵌套使用,生成具有多个批量维度的输出

>>> torch.dot                            # [D], [D] -> []
>>> batched_dot = torch.vmap(torch.vmap(torch.dot))  # [N1, N0, D], [N1, N0, D] -> [N1, N0]
>>> x, y = torch.randn(2, 3, 5), torch.randn(2, 3, 5)
>>> batched_dot(x, y) # tensor of size [2, 3]

如果输入不是沿第一个维度进行批量化,in_dims 指定了每个输入进行批量化的维度,例如

>>> torch.dot                            # [N], [N] -> []
>>> batched_dot = torch.vmap(torch.dot, in_dims=1)  # [N, D], [N, D] -> [D]
>>> x, y = torch.randn(2, 5), torch.randn(2, 5)
>>> batched_dot(x, y)   # output is [5] instead of [2] if batched along the 0th dimension

如果存在多个输入,且每个输入沿不同维度进行批量化,则 in_dims 必须是一个元组,其中包含每个输入的批量维度,例如

>>> torch.dot                            # [D], [D] -> []
>>> batched_dot = torch.vmap(torch.dot, in_dims=(0, None))  # [N, D], [D] -> [N]
>>> x, y = torch.randn(2, 5), torch.randn(5)
>>> batched_dot(x, y) # second arg doesn't have a batch dim because in_dim[1] was None

如果输入是 Python 结构,in_dims 必须是包含与输入形状匹配的结构的元组

>>> f = lambda dict: torch.dot(dict['x'], dict['y'])
>>> x, y = torch.randn(2, 5), torch.randn(5)
>>> input = {'x': x, 'y': y}
>>> batched_dot = torch.vmap(f, in_dims=({'x': 0, 'y': None},))
>>> batched_dot(input)

默认情况下,输出是沿第一个维度进行批量化。但是,可以通过使用 out_dims 将其沿任何维度进行批量化

>>> f = lambda x: x ** 2
>>> x = torch.randn(2, 5)
>>> batched_pow = torch.vmap(f, out_dims=1)
>>> batched_pow(x) # [5, 2]

对于任何使用 kwargs 的函数,返回的函数不会对 kwargs 进行批量化,但会接受 kwargs

>>> x = torch.randn([2, 5])
>>> def fn(x, scale=4.):
>>>   return x * scale
>>>
>>> batched_pow = torch.vmap(fn)
>>> assert torch.allclose(batched_pow(x), x * 4)
>>> batched_pow(x, scale=x) # scale is not batched, output has shape [2, 2, 5]

注意

vmap 不提供通用的自动批处理,也不能直接处理变长序列。

文档

访问 PyTorch 的全面开发者文档

查看文档

教程

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

查看教程

资源

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

查看资源