torch.func 旋风之旅¶
什么是 torch.func?¶
torch.func,之前称为 functorch,是一个在 PyTorch 中实现类似 JAX 的可组合函数转换的库。
“函数转换”是一种高阶函数,它接受一个数值函数,并返回一个计算不同量的新函数。
torch.func 具有自动微分转换(
grad(f)
返回计算f
梯度的函数)、向量化/批处理转换(vmap(f)
返回在批量输入上计算f
的函数)等功能。这些函数转换可以任意组合。例如,组合
vmap(grad(f))
可以计算一种称为“逐样本梯度”的量,这是当前原生 PyTorch 无法高效计算的。
为何需要可组合函数转换?¶
目前在 PyTorch 中有一些难以实现的用例:- 计算逐样本梯度(或其他逐样本量)
在单台机器上运行模型集合
高效地对 MAML 内循环中的任务进行批处理
高效计算雅可比矩阵和 Hessian 矩阵
高效计算批量雅可比矩阵和 Hessian 矩阵
组合 vmap()
、grad()
、vjp()
和 jvp()
转换,使我们无需为每个用例设计单独的子系统即可实现上述功能。
有哪些转换?¶
grad()
(梯度计算)¶
grad(func)
是我们的梯度计算转换。它返回一个计算 func
梯度的新函数。它假定 func
返回一个单元素张量,并且默认计算 func
输出相对于第一个输入的梯度。
import torch
from torch.func import grad
x = torch.randn([])
cos_x = grad(lambda x: torch.sin(x))(x)
assert torch.allclose(cos_x, x.cos())
# Second-order gradients
neg_sin_x = grad(grad(lambda x: torch.sin(x)))(x)
assert torch.allclose(neg_sin_x, -x.sin())
vmap()
(自动向量化)¶
注意:vmap()
对可应用的代码有限制。更多详情,请参阅用户体验限制。
vmap(func)(*inputs)
是一种转换,它为 func
中的所有张量操作添加一个维度。vmap(func)
返回一个新函数,该函数将 func
应用于输入中每个张量的某个维度(默认:0)。
vmap 对于隐藏批量维度很有用:可以编写一个在单个示例上运行的函数 func,然后使用 vmap(func)
将其提升为可以处理批量示例的函数,从而带来更简单的建模体验
import torch
from torch.func import 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
assert feature_vec.dim() == 1
return feature_vec.dot(weights).relu()
examples = torch.randn(batch_size, feature_size)
result = vmap(model)(examples)
当与 grad()
组合时,vmap()
可用于计算逐样本梯度
from torch.func import vmap
batch_size, feature_size = 3, 5
def model(weights,feature_vec):
# Very simple linear model with activation
assert feature_vec.dim() == 1
return feature_vec.dot(weights).relu()
def compute_loss(weights, example, target):
y = model(weights, example)
return ((y - target) ** 2).mean() # MSELoss
weights = torch.randn(feature_size, requires_grad=True)
examples = torch.randn(batch_size, feature_size)
targets = torch.randn(batch_size)
inputs = (weights,examples, targets)
grad_weight_per_example = vmap(grad(compute_loss), in_dims=(None, 0, 0))(*inputs)
vjp()
(向量-雅可比积)¶
vjp()
转换将 func
应用于 inputs
,并返回一个新函数,该函数根据给定的 cotangents
张量计算向量-雅可比积 (vjp)。
from torch.func import vjp
inputs = torch.randn(3)
func = torch.sin
cotangents = (torch.randn(3),)
outputs, vjp_fn = vjp(func, inputs); vjps = vjp_fn(*cotangents)
jvp()
(雅可比-向量积)¶
jvp()
转换计算雅可比-向量积,也称为“前向模式 AD”。与大多数其他转换不同,它不是高阶函数,但它返回 func(inputs)
的输出以及 jvp。
from torch.func import jvp
x = torch.randn(5)
y = torch.randn(5)
f = lambda x, y: (x * y)
_, out_tangent = jvp(f, (x, y), (torch.ones(5), torch.ones(5)))
assert torch.allclose(out_tangent, x + y)
jacrev()
, jacfwd()
和 hessian()
¶
jacrev()
转换返回一个新函数,该函数接受 x
作为输入,并使用反向模式 AD 返回函数对 x
的雅可比矩阵。
from torch.func import jacrev
x = torch.randn(5)
jacobian = jacrev(torch.sin)(x)
expected = torch.diag(torch.cos(x))
assert torch.allclose(jacobian, expected)
jacrev()
可以与 vmap()
组合以生成批量雅可比矩阵
x = torch.randn(64, 5)
jacobian = vmap(jacrev(torch.sin))(x)
assert jacobian.shape == (64, 5, 5)
jacfwd()
是 jacrev 的直接替代品,它使用前向模式 AD 计算雅可比矩阵
from torch.func import jacfwd
x = torch.randn(5)
jacobian = jacfwd(torch.sin)(x)
expected = torch.diag(torch.cos(x))
assert torch.allclose(jacobian, expected)
jacrev()
与其自身或 jacfwd()
组合可以生成 Hessian 矩阵
def f(x):
return x.sin().sum()
x = torch.randn(5)
hessian0 = jacrev(jacrev(f))(x)
hessian1 = jacfwd(jacrev(f))(x)
hessian()
是一个结合了 jacfwd 和 jacrev 的便捷函数
from torch.func import hessian
def f(x):
return x.sin().sum()
x = torch.randn(5)
hess = hessian(f)(x)