one of the variables needed for gradient computation has been modified by an inplace operation:
发布日期:2021-07-01 03:06:28
浏览次数:2
分类:技术文章
本文共 1360 字,大约阅读时间需要 4 分钟。
今天跑网络在进行loss.backward()的时候,出现了如下错误:
one of the variables needed for gradient computation has been modified by an inplace operation: [torch.FloatTensor [2, 64]], which is output 0 of ViewBackward, is at version 21;
expected version 20 instead. Hint: enable anomaly detection to find the operation that failed to compute its gradient, with torch.autograd.set_detect_anomaly(True).
我们先来看看错误是什么吧,就是说一个需要计算梯度的变量被原地置换了,网络希望是根据第20版的variable计算梯度,但拿到的却是第21版的,根据提示添加torch.autograd.set_detect_anomaly(True)仍然会报错
贴一下我的网络与问题相关的结构:
input_decoder = self.Decoder_init_input.repeat(batch_size, 1).unsqueeze(1)for i in range(total_len): _, _ = self.Decoder(input_decoder, hidden_decoder) input_decoder[index,:,:]= data[index,:]
不用管其他参数,只要看input_decoder就行,这里input_decoder每次循环不仅作为输入,每次loop的第二步还要改变其值,再进入下一次循环
这种做法在我们看来很合理,但是网络是不能接受的,你每次都在原地改变一个变量,那让torch如何去回溯这个变量的梯度呢?
所以,正确的做法应该是使用不同的变量去存储每次的结果,或者说,每次输入self.Decoder()的不应该都是同一个input_decoder,最简单的方式就是进行如下改动:
input_decoder = self.Decoder_init_input.repeat(batch_size, 1).unsqueeze(1)input_decoder_collector = [input_decoder]for i in range(total_len): _, _ = self.Decoder(input_decoder_collector[i], hidden_decoder) temp=input_decoder_collector[i].clone() temp[index,:,:]= data[index,:] input_decoder_collector.append(temp)
这样的话网络就可以回溯到每次循环所输入的input_decoder了,当然会占用更多的内存,可能还有更加巧妙地修改方式,对此有见解的大佬欢迎评论区交流指教呀(๑•̀ㅂ•́)و✧~
转载地址:https://meteorrain.blog.csdn.net/article/details/112319489 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
第一次来,支持一个
[***.219.124.196]2024年04月10日 03时15分17秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
vs中动态DLL与静态LIB工程中加入版本信息的方法
2019-05-01
大数据分析技术与应用一站式学习(值得收藏)_v20200418
2019-05-01
Qt 在windows下的串口读写
2019-05-01
SpringApplication执行流程
2019-05-01
自定义Starter
2019-05-01
分布式事务原理探究(一)
2019-05-01
spring cloud consul 应用的多实例名的解决
2019-05-01
人工智能为什么这么火?看看安防江湖30年血战就知道了
2019-05-01
“前端智能为安防产生新的数据价值”
2019-05-01
(8)CMake入门笔记--CMake语法
2019-05-01
头文件中 #ifndef---#define---#endif的作用
2019-05-01
Ant内置任务之whichresource
2019-05-01
Ant内置任务之symlink
2019-05-01
jface databinding:部分实现POJO对象的监测
2019-05-01
深入理解python--线程、进程与协程(1)
2019-05-01
Java--流重点总结初稿
2019-05-01
Html2Servlet--Html代码转换为Servlet小程序
2019-05-01
ImageView scaleType
2019-05-01
字符串的排序
2019-05-01