出错问题:
RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.FloatTensor [8]], which is output 0 of SelectBackward, is at version 2; expected version 1 instead. Hint: enable anomaly detection to find the operation that failed to compute its gradient, with torch.autograd.set_detect_anomaly(True).
出错原因:
对于需要求导的变量,不能用inplace操作赋值。inplace操作指的是在赋值操作中,同时改变需求导变量原本数值的操作。比如:
seq_hidden[0][0] = seq_hidden[0][0] + seq_hidden[0][1]
这个就不行,这个操作既读取了seq_hidden[0][0]的值用于计算,又更新seq_hidden[0][0]的值作为结果
解决办法:
创建一个和seq_hidden的shape一样的空tensor,这样跟 seq_hidden无关了,然后赋值的操作就不是inplace操作了
比如:at_hidden = torch.ones((seq_hidden.size()[0],seq_hidden.size()[1],hidden_size))
注意:千万不能直接 at_hidden = seq_hidden ,这样at_hidden就变成了需要求导的变量seq_hidden的引用。之前对at_hidden 的修改还是inplace操作。