Backward C 函数
- 类torch.autograd.function.BackwardCFunction[源代码]
-
此类用于内部自动微分功能,勿使用。
- apply(*args)[源代码]
-
在进行反向传播时,此节点使用的应用方法
- apply_jvp(*args)[源代码]
-
在正向模式自动微分执行期间使用的方法
- mark_dirty(*args)
-
将给定的张量标记为在原地操作中被修改。
这应当最多调用一次,要么在
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)
-
将输出标记为不可微分。
这应在
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)
-
为将来调用
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)
-
保存给定的张量,以便将来调用
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(值)
-
设置是否将梯度张量进行具体化。默认值为
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