torch.autograd.function.FunctionCtx.mark_dirty¶
- FunctionCtx.mark_dirty(*args)[source][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