带有修改导数的 Pytorch

Pytorch with Modified Derivatives

我正在重写 TRACX2 model,这是一种递归神经网络的变体,用于在连续语音或文本的分词上下文中训练编码。原代码作者用Numpy手动编写网络,而我想用Pytorch优化。然而,他们实现了他们称之为“温度”和“fahlman 偏移量”的东西:

这显然不是他们的激活函数之一 tanh(x) 的实际导数,但他们使用了这个导数。我将如何在 Pytorch 中实施此修改?

基本上,您可以像这样添加一个 backward hook

a = Variable(torch.randn(2,2), requires_grad=True)
m = nn.Linear(2,1)
m(a).mean().backward()
print(a.grad) 
# shows a 2x2 tensor of non-zero values
temperature = 0.3
fahlmanOffset = .1

def hook(module, grad_input, grad_output):
    # Use custom gradient output
    return grad_output * temperature + fahlmanOffset

m.register_backward_hook(hook)

a.grad.zero_()
m(a).mean().backward()
print(a.grad)
# shows a 2x2 tensor with modified gradient

(由 this answer 提供)