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)