BackwardCFunction#
- class torch.autograd.function.BackwardCFunction[source]#
此类用于内部 autograd 工作。请勿使用。
- 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
- mark_non_differentiable(*args)[source]#
将输出标记为不可微分。
此方法应在
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
- save_for_backward(*tensors)[source]#
为未来的
backward()
调用保存给定的张量。save_for_backward
应在setup_context()
或forward()
方法中调用最多一次,且仅使用张量。所有打算在 backward 传播中使用但不是 forward 函数的输入或输出的 tensor 都应使用
save_for_backward
保存(而不是直接保存在ctx
上),以防止梯度不正确和内存泄漏,并启用已保存 tensor hook 的应用。请参阅torch.autograd.graph.saved_tensors_hooks
。有关更多详细信息,请参阅 扩展 torch.autograd。请注意,如果保存用于反向传播的中间张量(既不是
forward()
的输入也不是输出的张量),则自定义 Function 可能不支持二次反向传播。不支持二次反向传播的自定义 Function 应使用@once_differentiable
装饰其backward()
方法,以便执行二次反向传播时会引发错误。如果您想支持二次反向传播,可以通过在反向传播期间根据输入重新计算中间值,或者将中间值作为自定义 Function 的输出返回。有关更多详细信息,请参阅 二次反向传播教程。在
backward()
中,可以通过saved_tensors
属性访问已保存的张量。在将它们返回给用户之前,会进行检查以确保它们未被用于任何修改其内容的就地操作。参数也可以是
None
。这不会执行任何操作。有关如何使用此方法的更多详细信息,请参阅 扩展 torch.autograd。
示例
>>> class Func(Function): >>> @staticmethod >>> def forward(ctx, x: torch.Tensor, y: torch.Tensor, z: int): >>> w = x * z >>> out = x * y + y * z + w * y >>> ctx.save_for_backward(x, y, w, out) >>> ctx.z = z # z is not a tensor >>> return out >>> >>> @staticmethod >>> @once_differentiable >>> def backward(ctx, grad_out): >>> x, y, w, out = ctx.saved_tensors >>> z = ctx.z >>> gx = grad_out * (y + y * z) >>> gy = grad_out * (x + z + w) >>> gz = None >>> return gx, gy, gz >>> >>> a = torch.tensor(1., requires_grad=True, dtype=torch.double) >>> b = torch.tensor(2., requires_grad=True, dtype=torch.double) >>> c = 4 >>> d = Func.apply(a, b, c)
- save_for_forward(*tensors)[source]#
Save given tensors for a future call to
jvp()
.save_for_forward
应在setup_context()
或forward()
方法中调用最多一次,且所有参数都应为张量。在
jvp()
中,可以通过saved_tensors
属性访问已保存的对象。参数也可以是
None
。这不会执行任何操作。有关如何使用此方法的更多详细信息,请参阅 扩展 torch.autograd。
示例
>>> class Func(torch.autograd.Function): >>> @staticmethod >>> def forward(ctx, x: torch.Tensor, y: torch.Tensor, z: int): >>> ctx.save_for_backward(x, y) >>> ctx.save_for_forward(x, y) >>> ctx.z = z >>> return x * y * z >>> >>> @staticmethod >>> def jvp(ctx, x_t, y_t, _): >>> x, y = ctx.saved_tensors >>> z = ctx.z >>> return z * (y * x_t + x * y_t) >>> >>> @staticmethod >>> def vjp(ctx, grad_out): >>> x, y = ctx.saved_tensors >>> z = ctx.z >>> return z * grad_out * y, z * grad_out * x, None >>> >>> a = torch.tensor(1., requires_grad=True, dtype=torch.double) >>> t = torch.tensor(1., dtype=torch.double) >>> b = torch.tensor(2., requires_grad=True, dtype=torch.double) >>> c = 4 >>> >>> with fwAD.dual_level(): >>> a_dual = fwAD.make_dual(a, t) >>> d = Func.apply(a_dual, b, c)
- set_materialize_grads(value)[source]#
Set whether to materialize grad tensors. Default is
True
.此方法只能从
setup_context()
或forward()
方法中调用。如果设置为
True
,则未定义的 grad 张量将在调用backward()
和jvp()
方法之前扩展为全零张量。示例
>>> class SimpleFunc(Function): >>> @staticmethod >>> def forward(ctx, x): >>> return x.clone(), x.clone() >>> >>> @staticmethod >>> @once_differentiable >>> def backward(ctx, g1, g2): >>> return g1 + g2 # No check for None necessary >>> >>> # We modify SimpleFunc to handle non-materialized grad outputs >>> class Func(Function): >>> @staticmethod >>> def forward(ctx, x): >>> ctx.set_materialize_grads(False) >>> ctx.save_for_backward(x) >>> return x.clone(), x.clone() >>> >>> @staticmethod >>> @once_differentiable >>> def backward(ctx, g1, g2): >>> x, = ctx.saved_tensors >>> grad_input = torch.zeros_like(x) >>> if g1 is not None: # We must check for None now >>> grad_input += g1 >>> if g2 is not None: >>> grad_input += g2 >>> return grad_input >>> >>> a = torch.tensor(1., requires_grad=True) >>> b, _ = Func.apply(a) # induces g2 to be undefined