BackwardCFunction¶
- class torch.autograd.function.BackwardCFunction[source][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
。请注意,如果中间张量(既不是
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]¶
设置是否具体化梯度张量。默认值为
True
。此方法只能从
setup_context()
或forward()
方法中调用。如果为
True
,未定义的梯度张量在调用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