gpt4 book ai didi

pytorch - 如何在 PyTorch 中使用 autograd.gradcheck?

转载 作者:行者123 更新时间:2023-12-02 08:00:45 29 4
gpt4 key购买 nike

该文档不包含 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 功能负责计算绝大多数操作的梯度。

最明显的异常(exception)是
  • 您有一个函数不能表示为其他可微函数的有限组合(例如,如果您需要不完整的 gamma 函数,您可能需要编写自己的使用 numpy 和/或查找表的前向和后向函数)。
  • 您希望加快一个特别复杂的表达式的计算速度,在应用链式法则后可以大大简化其梯度。
  • 关于pytorch - 如何在 PyTorch 中使用 autograd.gradcheck?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57627406/

    29 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com