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

太坑了

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

相关推荐
Csvn7 小时前
🌟 LangChain 30 天保姆级教程 · Day 13|OutputParser 进阶!让 AI 输出自动转为结构化对象,并支持自动重试!
python·langchain
cch89188 小时前
Python主流框架全解析
开发语言·python
sg_knight8 小时前
设计模式实战:状态模式(State)
python·ui·设计模式·状态模式·state
好运的阿财8 小时前
process 工具与子agent管理机制详解
网络·人工智能·python·程序人生·ai编程
龙文浩_8 小时前
AI中NLP的文本张量表示方法在自然语言处理中的演进与应用
人工智能·pytorch·深度学习·神经网络·自然语言处理
张張4088 小时前
(域格)环境搭建和编译
c语言·开发语言·python·ai
weixin_423533998 小时前
【Windows11离线安装anaconda、python、vscode】
开发语言·vscode·python
Ricky111zzz9 小时前
leetcode学python记录1
python·算法·leetcode·职场和发展
小白学大数据9 小时前
Selenium+Python 爬虫:动态加载头条问答爬取
爬虫·python·selenium
Hui Baby9 小时前
springboot读取配置文件
后端·python·flask