注意
点击此处下载完整的示例代码
Jacobians、Hessians、hvp、vhp 等:组合函数变换¶
创建于:2023 年 3 月 15 日 | 最后更新:2023 年 4 月 18 日 | 最后验证:2024 年 11 月 05 日
计算 Jacobian 或 Hessian 在许多非传统的深度学习模型中非常有用。使用 PyTorch 的常规自动微分 API(Tensor.backward()
、torch.autograd.grad
)有效地计算这些量非常困难(或令人讨厌)。PyTorch 的 受 JAX 启发的 函数变换 API 提供了有效计算各种高阶自动微分量的方法。
注意
本教程需要 PyTorch 2.0.0 或更高版本。
计算 Jacobian¶
import torch
import torch.nn.functional as F
from functools import partial
_ = torch.manual_seed(0)
让我们从一个我们想要计算 Jacobian 的函数开始。这是一个带有非线性激活的简单线性函数。
让我们添加一些虚拟数据:权重、偏置和特征向量 x。
D = 16
weight = torch.randn(D, D)
bias = torch.randn(D)
x = torch.randn(D) # feature vector
让我们将 predict
视为将输入 x
从 \(R^D \to R^D\) 映射的函数。PyTorch Autograd 计算向量-Jacobian 乘积。为了计算此 \(R^D \to R^D\) 函数的完整 Jacobian,我们将不得不通过每次使用不同的单位向量逐行计算。
def compute_jac(xp):
jacobian_rows = [torch.autograd.grad(predict(weight, bias, xp), xp, vec)[0]
for vec in unit_vectors]
return torch.stack(jacobian_rows)
xp = x.clone().requires_grad_()
unit_vectors = torch.eye(D)
jacobian = compute_jac(xp)
print(jacobian.shape)
print(jacobian[0]) # show first row
torch.Size([16, 16])
tensor([-0.5956, -0.6096, -0.1326, -0.2295, 0.4490, 0.3661, -0.1672, -1.1190,
0.1705, -0.6683, 0.1851, 0.1630, 0.0634, 0.6547, 0.5908, -0.1308])
我们可以使用 PyTorch 的 torch.vmap
函数变换来消除 for 循环并向量化计算,而不是逐行计算 Jacobian。我们不能直接将 vmap
应用于 torch.autograd.grad
;相反,PyTorch 提供了 torch.func.vjp
变换,该变换与 torch.vmap
组合
from torch.func import vmap, vjp
_, vjp_fn = vjp(partial(predict, weight, bias), x)
ft_jacobian, = vmap(vjp_fn)(unit_vectors)
# let's confirm both methods compute the same result
assert torch.allclose(ft_jacobian, jacobian)
在后面的教程中,反向模式 AD 和 vmap
的组合将为我们提供逐样本梯度。在本教程中,反向模式 AD 和 vmap
的组合为我们提供了 Jacobian 计算!vmap
和自动微分变换的各种组合可以为我们提供不同的有趣量。
PyTorch 提供了 torch.func.jacrev
作为执行 vmap-vjp
组合以计算 Jacobian 的便捷函数。jacrev
接受一个 argnums
参数,该参数说明我们希望计算关于哪个参数的 Jacobian。
from torch.func import jacrev
ft_jacobian = jacrev(predict, argnums=2)(weight, bias, x)
# Confirm by running the following:
assert torch.allclose(ft_jacobian, jacobian)
让我们比较两种计算 Jacobian 的方法的性能。函数变换版本快得多(并且输出越多,速度越快)。
总的来说,我们期望通过 vmap
进行向量化可以帮助消除开销并更好地利用您的硬件。
vmap
通过将外循环下推到函数的原始操作中来完成这种魔力,以获得更好的性能。
让我们快速创建一个函数来评估性能并处理微秒和毫秒测量值
def get_perf(first, first_descriptor, second, second_descriptor):
"""takes torch.benchmark objects and compares delta of second vs first."""
faster = second.times[0]
slower = first.times[0]
gain = (slower-faster)/slower
if gain < 0: gain *=-1
final_gain = gain*100
print(f" Performance delta: {final_gain:.4f} percent improvement with {second_descriptor} ")
然后运行性能比较
from torch.utils.benchmark import Timer
without_vmap = Timer(stmt="compute_jac(xp)", globals=globals())
with_vmap = Timer(stmt="jacrev(predict, argnums=2)(weight, bias, x)", globals=globals())
no_vmap_timer = without_vmap.timeit(500)
with_vmap_timer = with_vmap.timeit(500)
print(no_vmap_timer)
print(with_vmap_timer)
<torch.utils.benchmark.utils.common.Measurement object at 0x7fd07017b370>
compute_jac(xp)
3.06 ms
1 measurement, 500 runs , 1 thread
<torch.utils.benchmark.utils.common.Measurement object at 0x7fd05ca88340>
jacrev(predict, argnums=2)(weight, bias, x)
772.86 us
1 measurement, 500 runs , 1 thread
让我们使用我们的 get_perf
函数对上述内容进行相对性能比较
get_perf(no_vmap_timer, "without vmap", with_vmap_timer, "vmap")
Performance delta: 74.7730 percent improvement with vmap
此外,很容易翻转问题并说我们想要计算模型参数(权重、偏置)而不是输入的 Jacobian
# note the change in input via ``argnums`` parameters of 0,1 to map to weight and bias
ft_jac_weight, ft_jac_bias = jacrev(predict, argnums=(0, 1))(weight, bias, x)
反向模式 Jacobian (jacrev
) 与前向模式 Jacobian (jacfwd
)¶
我们提供两个 API 来计算 Jacobian:jacrev
和 jacfwd
jacrev
使用反向模式 AD。正如您在上面看到的,它是我们的vjp
和vmap
变换的组合。jacfwd
使用前向模式 AD。它实现为我们的jvp
和vmap
变换的组合。
jacfwd
和 jacrev
可以相互替代,但它们具有不同的性能特征。
作为一般经验法则,如果您要计算 \(R^N \to R^M\) 函数的 Jacobian,并且输出比输入多得多(例如,\(M > N\)),则首选 jacfwd
,否则使用 jacrev
。此规则有一些例外,但对此的非严格论证如下
在反向模式 AD 中,我们逐行计算 Jacobian,而在前向模式 AD(计算 Jacobian-向量乘积)中,我们逐列计算它。Jacobian 矩阵有 M 行和 N 列,因此如果它在一个方向上更高或更宽,我们可能更喜欢处理较少行或列的方法。
首先,让我们用比输出更多的输入进行基准测试
Din = 32
Dout = 2048
weight = torch.randn(Dout, Din)
bias = torch.randn(Dout)
x = torch.randn(Din)
# remember the general rule about taller vs wider... here we have a taller matrix:
print(weight.shape)
using_fwd = Timer(stmt="jacfwd(predict, argnums=2)(weight, bias, x)", globals=globals())
using_bwd = Timer(stmt="jacrev(predict, argnums=2)(weight, bias, x)", globals=globals())
jacfwd_timing = using_fwd.timeit(500)
jacrev_timing = using_bwd.timeit(500)
print(f'jacfwd time: {jacfwd_timing}')
print(f'jacrev time: {jacrev_timing}')
torch.Size([2048, 32])
jacfwd time: <torch.utils.benchmark.utils.common.Measurement object at 0x7fd07067c970>
jacfwd(predict, argnums=2)(weight, bias, x)
1.39 ms
1 measurement, 500 runs , 1 thread
jacrev time: <torch.utils.benchmark.utils.common.Measurement object at 0x7fd05c9e64a0>
jacrev(predict, argnums=2)(weight, bias, x)
7.97 ms
1 measurement, 500 runs , 1 thread
然后进行相对基准测试
get_perf(jacfwd_timing, "jacfwd", jacrev_timing, "jacrev", );
Performance delta: 472.0687 percent improvement with jacrev
现在反过来 - 比输入 (N) 更多的输出 (M)
Din = 2048
Dout = 32
weight = torch.randn(Dout, Din)
bias = torch.randn(Dout)
x = torch.randn(Din)
using_fwd = Timer(stmt="jacfwd(predict, argnums=2)(weight, bias, x)", globals=globals())
using_bwd = Timer(stmt="jacrev(predict, argnums=2)(weight, bias, x)", globals=globals())
jacfwd_timing = using_fwd.timeit(500)
jacrev_timing = using_bwd.timeit(500)
print(f'jacfwd time: {jacfwd_timing}')
print(f'jacrev time: {jacrev_timing}')
jacfwd time: <torch.utils.benchmark.utils.common.Measurement object at 0x7fd05ca73cd0>
jacfwd(predict, argnums=2)(weight, bias, x)
6.60 ms
1 measurement, 500 runs , 1 thread
jacrev time: <torch.utils.benchmark.utils.common.Measurement object at 0x7fd0a464fcd0>
jacrev(predict, argnums=2)(weight, bias, x)
882.64 us
1 measurement, 500 runs , 1 thread
以及相对性能比较
get_perf(jacrev_timing, "jacrev", jacfwd_timing, "jacfwd")
Performance delta: 647.2890 percent improvement with jacfwd
使用 functorch.hessian 进行 Hessian 计算¶
我们提供了一个便捷的 API 来计算 Hessian:torch.func.hessiani
。Hessian 是 Jacobian 的 Jacobian(或偏导数的偏导数,也称为二阶导数)。
这表明人们可以简单地组合 functorch Jacobian 变换来计算 Hessian。实际上,在底层,hessian(f)
只是 jacfwd(jacrev(f))
。
注意:为了提高性能:根据您的模型,您可能还想使用 jacfwd(jacfwd(f))
或 jacrev(jacrev(f))
来计算 Hessian,利用上面关于更宽与更高矩阵的经验法则。
from torch.func import hessian
# lets reduce the size in order not to overwhelm Colab. Hessians require
# significant memory:
Din = 512
Dout = 32
weight = torch.randn(Dout, Din)
bias = torch.randn(Dout)
x = torch.randn(Din)
hess_api = hessian(predict, argnums=2)(weight, bias, x)
hess_fwdfwd = jacfwd(jacfwd(predict, argnums=2), argnums=2)(weight, bias, x)
hess_revrev = jacrev(jacrev(predict, argnums=2), argnums=2)(weight, bias, x)
让我们验证无论使用 Hessian API 还是使用 jacfwd(jacfwd())
,我们都得到相同的结果。
True
批量 Jacobian 和批量 Hessian¶
在上面的示例中,我们一直在使用单个特征向量进行操作。在某些情况下,您可能想要获取一批输出相对于一批输入的 Jacobian。也就是说,给定形状为 (B, N)
的一批输入和一个从 \(R^N \to R^M\) 的函数,我们想要一个形状为 (B, M, N)
的 Jacobian。
最简单的方法是使用 vmap
batch_size = 64
Din = 31
Dout = 33
weight = torch.randn(Dout, Din)
print(f"weight shape = {weight.shape}")
bias = torch.randn(Dout)
x = torch.randn(batch_size, Din)
compute_batch_jacobian = vmap(jacrev(predict, argnums=2), in_dims=(None, None, 0))
batch_jacobian0 = compute_batch_jacobian(weight, bias, x)
weight shape = torch.Size([33, 31])
如果您有一个从 (B, N) -> (B, M) 的函数,并且确定每个输入都产生独立的输出,那么有时也可以在不使用 vmap
的情况下通过对输出求和然后计算该函数的 Jacobian 来完成此操作
def predict_with_output_summed(weight, bias, x):
return predict(weight, bias, x).sum(0)
batch_jacobian1 = jacrev(predict_with_output_summed, argnums=2)(weight, bias, x).movedim(1, 0)
assert torch.allclose(batch_jacobian0, batch_jacobian1)
如果您有一个从 \(R^N \to R^M\) 的函数但输入是批量的,则将 vmap
与 jacrev
组合以计算批量 Jacobian
最后,可以类似地计算批量 Hessian。最容易考虑它们的方法是使用 vmap
来批量处理 Hessian 计算,但在某些情况下,求和技巧也有效。
compute_batch_hessian = vmap(hessian(predict, argnums=2), in_dims=(None, None, 0))
batch_hess = compute_batch_hessian(weight, bias, x)
batch_hess.shape
torch.Size([64, 33, 31, 31])
计算 Hessian-向量乘积¶
计算 Hessian-向量乘积 (hvp) 的朴素方法是物化完整的 Hessian 并执行与向量的点积。我们可以做得更好:事实证明,我们不需要物化完整的 Hessian 就可以做到这一点。我们将介绍两种(多种)不同的策略来计算 Hessian-向量乘积: - 组合反向模式 AD 和反向模式 AD - 组合反向模式 AD 和前向模式 AD
组合反向模式 AD 和前向模式 AD(而不是反向模式和反向模式)通常是计算 hvp 的更节省内存的方法,因为前向模式 AD 不需要构建 Autograd 图并保存中间值以进行反向传播
以下是一些示例用法。
def f(x):
return x.sin().sum()
x = torch.randn(2048)
tangent = torch.randn(2048)
result = hvp(f, (x,), (tangent,))
如果 PyTorch 前向 AD 没有涵盖您的操作,那么我们可以改为组合反向模式 AD 和反向模式 AD
脚本的总运行时间: (0 分 11.637 秒)