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

太坑了

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

相关推荐
540_5407 分钟前
ADVANCE Day32
人工智能·python·机器学习
STLearner12 分钟前
AAAI 2026 | 图基础模型(GFM)&文本属性图(TAG)高分论文
人工智能·python·深度学习·神经网络·机器学习·数据挖掘·图论
小北方城市网28 分钟前
Python + 前后端全栈进阶课程(共 10 节|完整版递进式|从技术深化→项目落地→就业进阶,无缝衔接基础课)
大数据·开发语言·网络·python·数据库架构
nvd111 小时前
故障排查:Pytest Asyncio Event Loop Closed 错误
python
deephub1 小时前
Lux 上手指南:让 AI 直接操作你的电脑
人工智能·python·大语言模型·agent
Channing Lewis1 小时前
Python读取excel转成html,并且复制excel中单元格的颜色(字体或填充)
python·html·excel
小钟不想敲代码1 小时前
Python(一)
开发语言·python
大佬,救命!!!1 小时前
对算子shape相关的属性值自动化处理
python·算法·自动化·学习笔记·算子·用例脚本·算子形状
WoY20201 小时前
本地PyCharm配置远程服务器上的python环境
服务器·python·pycharm
tzjly1 小时前
JSON数据一键导入SQL Server
python