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
本页目录