torch.autograd.function.FunctionCtx.save_for_backward¶
- FunctionCtx.save_for_backward(*tensors)[原始碼][原始碼]¶
儲存給定的 tensors,以便未來呼叫
backward()
。save_for_backward
應該最多被呼叫一次,無論是在setup_context()
或forward()
方法中,且只能使用於 tensors。所有打算在 backward pass 中使用的 tensors 應該使用
save_for_backward
儲存(而不是直接儲存在ctx
上),以防止不正確的梯度和記憶體洩漏,並啟用已儲存 tensor hooks 的應用。請參閱torch.autograd.graph.saved_tensors_hooks
。請注意,如果中間 tensors (既不是
forward()
的輸入也不是輸出) 被儲存以用於 backward,您的自定義 Function 可能不支持 double backward。 不支持 double backward 的自定義 Functions 應該使用@once_differentiable
來裝飾它們的backward()
方法,以便執行 double backward 時會引發錯誤。 如果您想支持 double backward,您可以重新計算 backward 期間基於輸入的中間變數,或將中間變數作為自定義 Function 的輸出返回。 有關更多詳細信息,請參閱double backward 教學。在
backward()
中,可以通過saved_tensors
屬性存取已儲存的 tensors。 在將它們返回給使用者之前,會進行檢查以確保它們沒有在任何修改其內容的 in-place 操作中使用。參數也可以是
None
。 這是一個空操作 (no-op)。有關如何使用此方法的更多詳細訊息,請參閱擴展 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)