特殊的bug:element 0 of tensors does not require grad and does not have a grad_fn

很多帖子都说了,设置requires_grad_()就行。

但是我这次遇到的不一样,设置了都不行。

我是这种情况,在前面设置了torch.no_grad():,又在这个的作用域下进行了requires_grad_(),这是不起作用的。

简单版:

py 复制代码
with torch.no_grad():
            model.eval()
            pos_embed = model(homo_data.x, homo_data.edge_index)
						....            
            pos_embed.requires_grad_()# 不起作用
            ....

这样子直接看,傻瓜都不会犯错。而我这个就比较隐蔽了。。。

我的:

py 复制代码
# file1.py
with torch.no_grad():
    pos_embed = model(homo_data.x, homo_data.edge_index)
    ...
    fun_A(pos_embed)
    ...
# file2.py
def fun_A(x):
    ...
    fun_B(x)
    ...
# file3.py
def fun_B(x):
	...
  x.requires_grad_() # 由于x是在torch.no_grad中传过来的,所以不起作用
  ...

就这样一直会报错element 0 of tensors does not require grad and does not have a grad_fn

太坑了

大家引以为鉴,看看出现这个情况没。

相关推荐
少林码僧5 小时前
2.31 机器学习神器项目实战:如何在真实项目中应用XGBoost等算法
人工智能·python·算法·机器学习·ai·数据挖掘
智航GIS5 小时前
10.4 Selenium:Web 自动化测试框架
前端·python·selenium·测试工具
jarreyer5 小时前
摄像头相关记录
python
宝贝儿好5 小时前
【强化学习】第六章:无模型控制:在轨MC控制、在轨时序差分学习(Sarsa)、离轨学习(Q-learning)
人工智能·python·深度学习·学习·机器学习·机器人
大、男人5 小时前
python之asynccontextmanager学习
开发语言·python·学习
默默前行的虫虫6 小时前
nicegui文件上传归纳
python
一个没有本领的人7 小时前
UIU-Net运行记录
python
国强_dev7 小时前
Python 的“非直接原因”报错
开发语言·python
副露のmagic7 小时前
更弱智的算法学习 day24
python·学习·算法
廖圣平7 小时前
从零开始,福袋直播间脚本研究【三】《多进程执行selenium》
python·selenium·测试工具