特殊的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

太坑了

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

相关推荐
shengli7221 分钟前
机器学习与人工智能
jvm·数据库·python
2301_765703149 分钟前
Python迭代器(Iterator)揭秘:for循环背后的故事
jvm·数据库·python
追风少年ii29 分钟前
多组学扩展---分子对接pyrosetta
python·数据分析·空间·单细胞
2301_821369611 小时前
使用Python进行图像识别:CNN卷积神经网络实战
jvm·数据库·python
m0_561359671 小时前
使用Kivy开发跨平台的移动应用
jvm·数据库·python
编程火箭车1 小时前
04.第一个 Python 程序:Hello World 从编写到运行全解析
python·python第一个程序·python入门报错解决·python新手教程·hello world 程序·python终端运行·pycharm运行代码
qq_423233902 小时前
如何用FastAPI构建高性能的现代API
jvm·数据库·python
疯狂踩坑人2 小时前
【Python版 2026 从零学Langchain 1.x】(二)结构化输出和工具调用
后端·python·langchain
HDO清风2 小时前
CASIA-HWDB2.x 数据集DGRL文件解析(python)
开发语言·人工智能·pytorch·python·目标检测·计算机视觉·restful
weixin_499771552 小时前
Python上下文管理器(with语句)的原理与实践
jvm·数据库·python