BackwardCFunction¶
- class torch.autograd.function.BackwardCFunction[原始碼][原始碼]¶
此類別用於內部 autograd 工作。 請勿使用。
- mark_dirty(*args)[原始碼]¶
標記給定的張量為原地 (in-place) 運算中已修改的張量。
此方法應最多呼叫一次,無論是在
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
上),以防止不正確的梯度和記憶體洩漏,並啟用已儲存張量 Hook 的應用。 請參閱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)[原始碼]¶
儲存給定的張量,以供將來呼叫
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)[原始碼]¶
設定是否實體化梯度張量。預設值為
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