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

太坑了

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

相关推荐
IAUTOMOBILE3 小时前
Python 流程控制与函数定义:从调试现场到工程实践
java·前端·python
TT_44194 小时前
python程序实现图片截图溯源功能
开发语言·python
小陈的进阶之路5 小时前
logging 日志模块笔记
python
cqbelt5 小时前
Python 并发编程实战学习笔记
笔记·python·学习
智算菩萨6 小时前
【论文复现】Applied Intelligence 2025:Auto-PU正例无标签学习的自动化实现与GPT-5.4辅助编程实战
论文阅读·python·gpt·学习·自动化·复现
小陈工6 小时前
2026年3月31日技术资讯洞察:AI智能体安全、异步编程突破与Python运行时演进
开发语言·jvm·数据库·人工智能·python·安全·oracle
亚林瓜子7 小时前
AWS EB使用自定义镜像
云计算·bug·aws·ami·fix·eb·al2023
老李的勺子7 小时前
Agent 记忆失效的 5 种方式:完整排查复盘
python·llm
Leo655357 小时前
动态透视报表 + 查询接口 + Excel导出
开发语言·windows·python
清水白石0087 小时前
pytest Fixture 设计实战指南:作用域、依赖链、自动清理与测试资源高效复用
python·pytest