在用pytorch手写实现lstm时遇到
参考
https://zhuanlan.zhihu.com/p/38475183
https://www.youtube.com/watch?v=MswxJw-8PvE
可知原因主要出现在了计算图中inplace错误
我手动实现的graph memory network。该模型类似于LSTM
一开始是直接在模型里定义的ht
class GMN(nn.Module):
def __init__(self, input_size, adj,K=3):
super(GMN,self).__init__()
self.input_size = input_size
...
# 初始化隐藏状态和细胞状态
self.h=nn.Parameter(torch.randn(12, input_size),requires_grad=True).cuda().float()
def forward(self, x):
h=self.h.detach()
f1=x*h
f2=self.forget_gate(f1)
f=nn.Sigmoid()(f2)
...
#省略其他门控
t1=f*g
t2=t1*self_h
t3=t2+i
self.h=t3
return self.h
因为在forward函数里面,遗忘门ft、输入门it以及输出门gt等都是根据ht-1(也就是self.h)计算而来
而再最后模型会根据ft、it、gt等更新ht,并return ht。这可能引起计算题混乱
我最后的解决方法是在forward里面指定:h=self.h.detach()
然后用h而不是self.h去计算ft、it、gt
此外注意,在等式左右尽量不要用相同的变量名