評價此頁

torch.autograd.function.FunctionCtx.mark_dirty#

FunctionCtx.mark_dirty(*args)[source]#

將給定張量標記為在就地操作中已修改。

此函式最多應呼叫一次,可以在 setup_context()forward() 方法中呼叫,並且所有引數都應該是輸入。

在呼叫 forward() 時,任何被原地修改的張量都應傳遞給此函式,以確保我們的檢查正確性。函式是在修改之前還是之後呼叫並不重要。

示例:
>>> class Inplace(Function):
>>>     @staticmethod
>>>     def forward(ctx, x):
>>>         x_npy = x.numpy() # x_npy shares storage with x
>>>         x_npy += 1
>>>         ctx.mark_dirty(x)
>>>         return x
>>>
>>>     @staticmethod
>>>     @once_differentiable
>>>     def backward(ctx, grad_output):
>>>         return grad_output
>>>
>>> a = torch.tensor(1., requires_grad=True, dtype=torch.double).clone()
>>> b = a * a
>>> Inplace.apply(a)  # This would lead to wrong gradients!
>>>                   # but the engine would not know unless we mark_dirty
>>> b.backward() # RuntimeError: one of the variables needed for gradient
>>>              # computation has been modified by an inplace operation