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

太坑了

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

相关推荐
不吃鱼的小时喵12 分钟前
【Python】关于python多进程
python
喵手21 分钟前
Python爬虫零基础入门【第六章:增量、去重、断点续爬·第1节】增量采集:只抓新增/更新(新手也能做)!
爬虫·python·python爬虫实战·python爬虫工程化实战·python爬虫零基础入门·增量、去重·增量采集
万粉变现经纪人39 分钟前
如何解决 pip install pyodbc 报错 缺少 ‘cl.exe’ 或 ‘sql.h’(ODBC 头文件)问题
数据库·python·sql·网络协议·bug·ssl·pip
dazzle1 小时前
Python数据结构(五):队列详解
数据结构·python
翱翔的苍鹰1 小时前
完整的“RNN + jieba 中文情感分析”项目之一:需要添加添加 JWT 认证
人工智能·python·rnn
0思必得01 小时前
[Web自动化] 爬虫URL去重
运维·爬虫·python·selenium·自动化
Cherry的跨界思维1 小时前
【AI测试全栈:质量】40、数据平权之路:Python+Java+Vue全栈实战偏见检测与公平性测试
java·人工智能·python·机器学习·ai测试·ai全栈·ai测试全栈
wheelmouse77881 小时前
Python 装饰器函数(decoratots) 学习笔记
笔记·python·学习
老歌老听老掉牙1 小时前
差分进化算法深度解码:Scipy高效全局优化实战秘籍
python·算法·scipy
工程师老罗1 小时前
Pycharm下新建一个conda环境后,如何在该环境下安装包?
人工智能·python