InplaceFunction¶
- class torch.autograd.function.InplaceFunction(inplace=False)[source][source]¶
此类仅出于向后兼容性原因而存在。对于任何新的用例,请使用
Function
而不是此类。- static backward(ctx, *grad_outputs)[source]¶
定义使用反向模式自动微分对操作进行微分的公式。
所有子类都应覆盖此函数。(定义此函数等同于定义
vjp
函数。)它必须接受上下文
ctx
作为第一个参数,后跟与forward()
返回值一样多的输出(对于前向函数的非张量输出,将传入 None),并且它应返回与forward()
的输入一样多的张量。每个参数是相对于给定输出的梯度,每个返回值应是相对于相应输入的梯度。如果输入不是张量或是不需要梯度的张量,您可以只为该输入传递 None 作为梯度。上下文可用于检索在前向传播期间保存的张量。它还具有一个属性
ctx.needs_input_grad
,它是一个布尔值元组,表示每个输入是否需要梯度。例如,如果forward()
的第一个输入需要计算相对于输出的梯度,则backward()
将具有ctx.needs_input_grad[0] = True
。- 返回类型
- static forward(*args, **kwargs)[source]¶
定义自定义 autograd Function 的前向传播。
所有子类都应覆盖此函数。定义前向传播有两种方法
用法 1(组合前向传播和上下文)
@staticmethod def forward(ctx: Any, *args: Any, **kwargs: Any) -> Any: pass
它必须接受上下文 ctx 作为第一个参数,后跟任意数量的参数(张量或其他类型)。
有关更多详细信息,请参阅 组合或分离 forward() 和 setup_context()
用法 2(分离前向传播和上下文)
@staticmethod def forward(*args: Any, **kwargs: Any) -> Any: pass @staticmethod def setup_context(ctx: Any, inputs: Tuple[Any, ...], output: Any) -> None: pass
前向传播不再接受 ctx 参数。
相反,您还必须覆盖
torch.autograd.Function.setup_context()
静态方法来处理ctx
对象的设置。output
是前向传播的输出,inputs
是前向传播的输入的元组。有关更多详细信息,请参阅 扩展 torch.autograd
上下文可用于存储任意数据,这些数据随后可在反向传播期间检索。张量不应直接存储在 ctx 上(尽管当前为了向后兼容性而未强制执行此操作)。相反,张量应使用
ctx.save_for_backward()
保存(如果它们旨在在backward
(等效于vjp
)中使用),或者使用ctx.save_for_forward()
保存(如果它们旨在在jvp
中使用)。- 返回类型
- static jvp(ctx, *grad_inputs)[source]¶
定义使用前向模式自动微分对操作进行微分的公式。
所有子类都应覆盖此函数。它必须接受上下文
ctx
作为第一个参数,后跟与forward()
获取的输入一样多的输入(对于前向函数的非张量输入,将传入 None),并且它应返回与forward()
的输出一样多的张量。每个参数是相对于给定输入的梯度,每个返回值应是相对于相应输出的梯度。如果输出不是张量或者函数对于该输出不可微分,您可以只为该输入传递 None 作为梯度。您可以使用
ctx
对象将任何值从前向传播传递到此函数。- 返回类型
- 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()
的输入也不是输出的张量)被保存用于反向传播,则您的自定义 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]¶
保存给定的张量,以便将来调用
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
- static setup_context(ctx, inputs, output)[source]¶
定义 autograd.Function 的前向传播有两种方法。
或者
使用签名
forward(ctx, *args, **kwargs)
覆盖前向传播。setup_context
未被覆盖。为反向传播设置 ctx 在forward
内部进行。使用签名
forward(*args, **kwargs)
覆盖前向传播,并覆盖setup_context
。为反向传播设置 ctx 在setup_context
内部进行(而不是在forward
内部)
有关更多详细信息,请参阅
torch.autograd.Function.forward()
和 扩展 torch.autograd。- 返回类型
- static vjp(ctx, *grad_outputs)[source]¶
定义使用反向模式自动微分对操作进行微分的公式。
所有子类都应覆盖此函数。(定义此函数等同于定义
vjp
函数。)它必须接受上下文
ctx
作为第一个参数,后跟与forward()
返回值一样多的输出(对于前向函数的非张量输出,将传入 None),并且它应返回与forward()
的输入一样多的张量。每个参数是相对于给定输出的梯度,每个返回值应是相对于相应输入的梯度。如果输入不是张量或是不需要梯度的张量,您可以只为该输入传递 None 作为梯度。上下文可用于检索在前向传播期间保存的张量。它还具有一个属性
ctx.needs_input_grad
,它是一个布尔值元组,表示每个输入是否需要梯度。例如,如果forward()
的第一个输入需要计算相对于输出的梯度,则backward()
将具有ctx.needs_input_grad[0] = True
。- 返回类型
- static vmap(info, in_dims, *args)[source]¶
定义此 autograd.Function 在
torch.vmap()
下的行为。对于
torch.autograd.Function()
要支持torch.vmap()
,您必须覆盖此静态方法,或将generate_vmap_rule
设置为True
(您不能同时执行这两项操作)。如果您选择覆盖此静态方法:它必须接受
一个
info
对象作为第一个参数。info.batch_size
指定被 vmap 化的维度的尺寸,而info.randomness
是传递给torch.vmap()
的随机性选项。一个
in_dims
元组作为第二个参数。对于args
中的每个 arg,in_dims
都有一个对应的Optional[int]
。如果 arg 不是张量,或者 arg 未被 vmap 化,则为None
,否则,它是一个整数,指定张量的哪个维度正在被 vmap 化。*args
,它与forward()
的 args 相同。
vmap 静态方法的返回值是一个
(output, out_dims)
元组。与in_dims
类似,out_dims
应与output
具有相同的结构,并为每个输出包含一个out_dim
,以指定输出是否具有 vmap 化的维度以及它在哪个索引中。有关更多详细信息,请参阅 使用 autograd.Function 扩展 torch.func。