dual_level¶
- class 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 的详细步骤。