【发布时间】:2021-10-08 19:41:00
【问题描述】:
我正在寻找一种很好的方法来覆盖 nn.Module 中的反向操作,例如:
class LayerWithCustomGrad(nn.Module):
def __init__(self):
super(LayerWithCustomGrad, self).__init__()
self.weights = nn.Parameter(torch.randn(200))
def forward(self,x):
return x * self.weights
def backward(self,grad_of_c): # This gets called during loss.backward()
# grad_of_c comes from the gradient of b*23
grad_of_a = some_operation(grad_of_c)
# perform extra computation
# and more computation
self.weights.grad = another_operation(grad_of_a,grad_of_c)
return grad_of_a # and the grad of parameter "a" will receive this
layer = LayerWithCustomGrad()
a = nn.Parameter(torch.randn(200),requires_grad=True)
b = layer(a)
c = b*23
我从事的一些项目包含具有不可微分函数的层,如果有一些方法可以连接两个损坏的图形和/或修改已经存在的图形的梯度,我会喜欢它。
如果在张量流中有一种可能的方法,那也很棒
【问题讨论】:
-
看来您采取了正确的方法。究竟是什么问题?
-
所以基本上用 forward 你执行 x -> 操作 -> more_operation -> 结果。向后 grad_of_result -> 到 grad_of_more_operation 等等。目标是劫持 grad_of_more_operation 并在 loss.backward() 期间进行“操作”之前对其进行修改