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

太坑了

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

相关推荐
mantch1 天前
个人 LLM 接口服务项目:一个简洁的 AI 入口
人工智能·python·llm
weixin_445054721 天前
力扣热题51
c++·python·算法·leetcode
朱朱没烦恼yeye1 天前
java基础学习
java·python·学习
databook1 天前
数据可视化五大黄金原则:让你的图表“会说话”
python·数据分析·数据可视化
ai_top_trends1 天前
2026 年度工作计划 PPT 模板与 AI 生成方法详解
人工智能·python·powerpoint
智航GIS1 天前
9.4 Word 自动化
python·自动化·word
2501_941809141 天前
面向多活架构与数据地域隔离的互联网系统设计思考与多语言工程实现实践分享记录
java·开发语言·python
aloha_7891 天前
agent智能体学习(尚硅谷,小智医疗)
人工智能·spring boot·python·学习·java-ee
亿牛云爬虫专家1 天前
Worker越简单,系统越稳定:从单机到集群
爬虫·python·集群·爬虫代理·单机·代理ip·worker
smj2302_796826521 天前
解决leetcode第3801题合并有序列表的最小成本
数据结构·python·算法·leetcode