评价此页

torch.autograd.function.FunctionCtx.mark_non_differentiable#

FunctionCtx.mark_non_differentiable(*args)[源代码]#

将输出标记为不可微分。

此方法最多应调用一次,在 setup_context()forward() 方法中,并且所有参数都应为张量输出。

这将把输出标记为不需要梯度,从而提高反向传播计算的效率。你仍然需要在 backward() 中接受每个输出的梯度,但它始终是一个与相应输出形状相同的零张量。

此功能用于例如从排序返回的索引。请参阅示例:
>>> class Func(Function):
>>>     @staticmethod
>>>     def forward(ctx, x):
>>>         sorted, idx = x.sort()
>>>         ctx.mark_non_differentiable(idx)
>>>         ctx.save_for_backward(x, idx)
>>>         return sorted, idx
>>>
>>>     @staticmethod
>>>     @once_differentiable
>>>     def backward(ctx, g1, g2):  # still need to accept g2
>>>         x, idx = ctx.saved_tensors
>>>         grad_input = torch.zeros_like(x)
>>>         grad_input.index_add_(0, idx, g1)
>>>         return grad_input