快捷方式

InplaceFunction

class torch.autograd.function.InplaceFunction(inplace=False)[source][source]

此类仅用于向后兼容。对于任何新用例,请使用 Function 代替此项。

static backward(ctx, *grad_outputs)[source]

定义使用反向模式自动微分来计算操作导数的公式。

所有子类都应覆盖此函数。(定义此函数等同于定义 vjp 函数。)

它必须接受一个上下文 ctx 作为第一个参数,后跟与 forward() 返回的输出数量相同的参数(forward 函数的非张量输出将传入 None),并且它应该返回与 forward() 输入数量相同的张量。每个参数是相对于给定输出的梯度,每个返回值应该是相对于相应输入的梯度。如果输入不是张量或是不需要梯度的张量,您可以直接传入 None 作为该输入的梯度。

上下文可用于检索前向传播期间保存的张量。它还有一个属性 ctx.needs_input_grad,它是一个布尔值元组,表示每个输入是否需要梯度。例如,如果 forward() 的第一个输入需要计算相对于输出的梯度,则 backward() 将具有 ctx.needs_input_grad[0] = True

返回类型

任意

static forward(*args, **kwargs)[source]

定义自定义 autograd 函数的前向传播。

所有子类都应覆盖此函数。定义 forward 有两种方式

用法 1(合并 forward 和 ctx)

@staticmethod
def forward(ctx: Any, *args: Any, **kwargs: Any) -> Any:
    pass

用法 2(分开 forward 和 ctx)

@staticmethod
def forward(*args: Any, **kwargs: Any) -> Any:
    pass

@staticmethod
def setup_context(ctx: Any, inputs: Tuple[Any, ...], output: Any) -> None:
    pass
  • forward 不再接受 ctx 参数。

  • 相反,您还必须覆盖 torch.autograd.Function.setup_context() 静态方法来处理 ctx 对象的设置。output 是 forward 的输出,inputs 是 forward 输入的元组。

  • 有关更多详细信息,请参阅 扩展 torch.autograd

上下文可用于存储可在反向传播期间检索的任意数据。张量不应直接存储在 ctx 上(尽管为了向后兼容目前并未强制执行此规则)。相反,如果张量用于 backward(等同于 vjp),应使用 ctx.save_for_backward() 保存;如果用于 jvp,应使用 ctx.save_for_forward() 保存。

返回类型

任意

static jvp(ctx, *grad_inputs)[source]

定义使用前向模式自动微分来计算操作导数的公式。

所有子类都应覆盖此函数。它必须接受一个上下文 ctx 作为第一个参数,后跟与 forward() 输入数量相同的参数(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 上),以防止梯度错误和内存泄漏,并启用 saved tensor hooks 的应用。参阅 torch.autograd.graph.saved_tensors_hooks

请注意,如果中间张量(即 forward() 的输入和输出之外的张量)被保存用于反向传播,您的自定义 Function 可能不支持二次反向传播(double backward)。不支持二次反向传播的自定义 Functions 应使用 @once_differentiable 装饰器装饰其 backward() 方法,以便执行二次反向传播时引发错误。如果您想支持二次反向传播,可以在 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 的前向传播有两种方式。

或者

  1. 使用 forward(ctx, *args, **kwargs) 签名覆盖 forward。不覆盖 setup_context。为反向传播设置 ctxforward 内部进行。

  2. 使用 forward(*args, **kwargs) 签名覆盖 forward 并覆盖 setup_context。为反向传播设置 ctxsetup_context 内部进行(而不是在 forward 内部)

有关更多详细信息,请参阅 torch.autograd.Function.forward()扩展 torch.autograd

返回类型

任意

static vjp(ctx, *grad_outputs)[source]

定义使用反向模式自动微分来计算操作导数的公式。

所有子类都应覆盖此函数。(定义此函数等同于定义 vjp 函数。)

它必须接受一个上下文 ctx 作为第一个参数,后跟与 forward() 返回的输出数量相同的参数(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() 的 randomness 选项。

  • 一个 in_dims 元组作为第二个参数。对于 args 中的每个 arg,in_dims 都有一个对应的 Optional[int]`. 如果 arg 不是张量或没有进行 vmap 操作,则为 `None`;否则,它是一个整数,指定正在对张量的哪个维度进行 vmap 操作。

  • *args,与传递给 forward() 的参数相同。

vmap 静态方法的返回是一个 (output, out_dims) 元组。与 in_dims 类似,out_dims 应与 output 具有相同的结构,并且对于每个输出包含一个 out_dim,指定输出是否具有 vmap 维度以及其索引位置。

有关更多详细信息,请参阅 使用 autograd.Function 扩展 torch.func

文档

查阅 PyTorch 的全面开发者文档

查看文档

教程

获取面向初学者和高级开发者的深度教程

查看教程

资源

查找开发资源并获得问题解答

查看资源