前言:
RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.cuda.FloatTensor [2, 512, 32, 32]], which is output 0 of ReluBackward0, is at version 1; expected version 0 instead. Hint: the backtrace further above shows the operation that failed to compute its gradient. The variable in question was changed in there or anywhere later. Good luck!
博主宰debug Swin Transformer for Semantic Segmentaion这个个代码的时候,出现这个错误,即使在代码中加入:
torch.autograd.set_detect_anomaly(True)
loss_batch,loss = self.loss(pred, self.mask) # 计算loss
loss.backward() # 误差反向传播
self.optimizer.step() # 更新参数
仍然无法定位所在的具体位置。
一、分析
[torch.cuda.FloatTensor [2, 512, 32, 32]],,可以根据特征图的大小大致定位到应该是解码器中出了问题,因为在编码器中没有出现过这样的特征图。
在这个文件中找到,ConvModule这个函数
可以清楚的看到如果不指定inplace,则默认为True,我这边直接写改源码,让其变为False
这样以来,可以照顾到所有使用这个函数的卷积,
,
但是错误依旧没有解决,,,
二、错误解决
博主检查了所有的卷积后面的激活函数,发现原地操作都已经去掉了。但是错误还在,于是接着向下找与[torch.cuda.FloatTensor [2, 512, 32, 32]]相关的操作,发现“+=””这个操作,终于发现了。
将语句:
laterals[i - 1] += resize(laterals[i],size=prev_shape,mode='bilinear',align_corners=self.align_corners)
改为:
laterals[i - 1] = laterals[i - 1] + resize(laterals[i],size=prev_shape,mode='bilinear',align_corners=self.align_corners)
既可以解决所有的问题,goodlock