• 文档 >
  • 自动微分包 - torch.autograd >
  • torch.autograd.function.FunctionCtx.mark_dirty
快捷键

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

© 版权所有 PyTorch 贡献者。

使用 Sphinx 构建,主题由 Read the Docs 提供。

文档

访问 PyTorch 的全面开发者文档

查看文档

教程

深入了解初学者和高级开发者的教程

查看教程

资源

查找开发资源并获得您的疑问解答

查看资源