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()方法中呼叫最多一次,且僅使用張量。所有打算在 backward 傳播中使用但不是 forward 函式的輸入或輸出的 tensor 都應使用
save_for_backward儲存(而不是直接儲存在ctx上),以防止梯度不正確和記憶體洩漏,並啟用已儲存 tensor hook 的應用。請參閱torch.autograd.graph.saved_tensors_hooks。有關更多詳細資訊,請參閱 擴充套件 torch.autograd。請注意,如果儲存用於反向傳播的中間張量(既不是
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]#
Save given tensors for a future call to
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]#
Set whether to materialize grad tensors. Default is
True.此方法只能從
setup_context()或forward()方法中呼叫。如果設定為
True,則未定義的 grad 張量將在呼叫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