評價此頁

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 教程