双级 ¶
- 类 torch.autograd.forward_ad.dual_level[source][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
请参阅前向模式的 AD 教程,以获取如何使用此 API 的详细步骤。