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

太坑了

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

相关推荐
飞鸟真人10 分钟前
关于python -m http.server的一些安全问题
python·安全·http
tjjucheng16 分钟前
小程序定制开发哪家性价比高
python
No0d1es27 分钟前
2025年12月 GESP CCF编程能力等级认证Python六级真题
python·青少年编程·gesp·ccf·六级
亮子AI1 小时前
【Python】比较两个cli库:Click vs Typer
开发语言·python
CappuccinoRose1 小时前
流计算概述
python·flink·流计算·数据流·pyflink
Dragon水魅1 小时前
Fandom Wiki 网站爬取文本信息踩坑实录
爬虫·python
Darkershadow1 小时前
蓝牙学习之unprovision beacon
python·学习·ble
小龙在山东1 小时前
基于 plumbum 跨平台执行Shell脚本
python
一条咸鱼_SaltyFish2 小时前
[Day10] contract-management初期开发避坑指南:合同模块 DDD 架构规划的教训与调整
开发语言·经验分享·微服务·架构·bug·开源软件·ai编程
CCPC不拿奖不改名2 小时前
python基础:python语言中的函数与模块+面试习题
开发语言·python·面试·职场和发展·蓝桥杯