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()
方法中调用,并且只能使用张量。所有打算在反向传播中使用张量都应使用
save_for_backward
保存(而不是直接保存在ctx
上),以防止不正确的梯度和内存泄漏,并启用保存张量钩子的应用。有关更多详细信息,请参阅torch.autograd.graph.saved_tensors_hooks
。请参阅 扩展 torch.autograd 以获取更多详细信息。请注意,如果保存了中间张量(非
forward()
的输入或输出的张量),则自定义函数可能不支持二次反向传播。不支持二次反向传播的自定义函数应使用@once_differentiable
装饰其backward()
方法,以便执行二次反向传播时会引发错误。如果您想支持二次反向传播,可以根据反向传播期间的输入重新计算中间值,或者将中间值作为自定义函数的输出返回。有关更多详细信息,请参阅 二次反向传播教程。在
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]#
保存给定的张量以供将来调用
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]#
设置是否实例化 grad 张量。默认值为
True
。这应仅从
setup_context()
或forward()
方法中调用。如果为
True
,则在调用backward()
和jvp()
方法之前,未定义的 grad 张量将被扩展为全零张量。示例
>>> 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