评价此页

dual_level#

class torch.autograd.forward_ad.dual_level[source]#

正向 AD 的上下文管理器,所有正向 AD 计算都必须发生在 dual_level 上下文内。

注意

dual_level 上下文会适当地进入和退出双层,以控制当前的正向 AD 层级,该层级被此 API 中的其他函数默认使用。

目前我们不打算支持嵌套的 dual_level 上下文,因此只支持一个正向 AD 层级。要计算更高阶的正向梯度,可以使用 torch.func.jvp()

示例

>>> x = torch.tensor([1])
>>> x_t = torch.tensor([1])
>>> with dual_level():
...     inp = make_dual(x, x_t)
...     # Do computations with inp
...     out = your_fn(inp)
...     _, grad = unpack_dual(out)
>>> grad is None
False
>>> # After exiting the level, the grad is deleted
>>> _, grad_after = unpack_dual(out)
>>> grad is None
True

有关如何使用此 API 的详细步骤,请参阅前向模式 AD 教程