如何在 PyTorch 中使用 autograd.gradcheck?
How to use autograd.gradcheck in PyTorch?
该文档不包含 gradcheck 的任何示例用例,它在哪里有用?
此处的文档中提供了一个示例用例:
https://pytorch.org/docs/master/notes/extending.html
You probably want to check if the backward method you implemented
actually computes the derivatives of your function. It is possible by
comparing with numerical approximations using small finite
differences:
from torch.autograd import gradcheck
# gradcheck takes a tuple of tensors as input, check if your gradient
# evaluated with these tensors are close enough to numerical
# approximations and returns True if they all verify this condition.
input = (torch.randn(20,20,dtype=torch.double,requires_grad=True), torch.randn(30,20,dtype=torch.double,requires_grad=True))
test = gradcheck(linear, input, eps=1e-6, atol=1e-4)
print(test)
正如上面引述的那样,gradcheck
函数的目的是验证自定义后向函数是否与梯度的数值近似一致。主要用例是当您实施自定义向后操作时。 在极少数情况下,您应该在 PyTorch 中实现自己的后向函数。这是因为 PyTorch 的 autograd 功能负责为绝大多数操作计算梯度。
最明显的例外是
你有一个函数不能表示为其他可微函数的有限组合(例如,如果你需要不完全的伽马函数,你可能想写你自己的前向和后向它使用了 numpy and/or 查找表)。
您希望加快计算一个特别复杂的表达式,在应用链式法则后可以大大简化梯度。
该文档不包含 gradcheck 的任何示例用例,它在哪里有用?
此处的文档中提供了一个示例用例:
https://pytorch.org/docs/master/notes/extending.html
You probably want to check if the backward method you implemented actually computes the derivatives of your function. It is possible by comparing with numerical approximations using small finite differences:
from torch.autograd import gradcheck # gradcheck takes a tuple of tensors as input, check if your gradient # evaluated with these tensors are close enough to numerical # approximations and returns True if they all verify this condition. input = (torch.randn(20,20,dtype=torch.double,requires_grad=True), torch.randn(30,20,dtype=torch.double,requires_grad=True)) test = gradcheck(linear, input, eps=1e-6, atol=1e-4) print(test)
正如上面引述的那样,gradcheck
函数的目的是验证自定义后向函数是否与梯度的数值近似一致。主要用例是当您实施自定义向后操作时。 在极少数情况下,您应该在 PyTorch 中实现自己的后向函数。这是因为 PyTorch 的 autograd 功能负责为绝大多数操作计算梯度。
最明显的例外是
你有一个函数不能表示为其他可微函数的有限组合(例如,如果你需要不完全的伽马函数,你可能想写你自己的前向和后向它使用了 numpy and/or 查找表)。
您希望加快计算一个特别复杂的表达式,在应用链式法则后可以大大简化梯度。