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

太坑了

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

相关推荐
羡鱼饼饼9 分钟前
pytorch深度学习—RNN-循环神经网络
pytorch·rnn·深度学习
cdg==吃蛋糕12 分钟前
selenium 使用方法
开发语言·python
Y1nhl1 小时前
力扣_二叉树的BFS_python版本
python·算法·leetcode·职场和发展·宽度优先
Q_Q5110082852 小时前
python的婚纱影楼管理系统
开发语言·spring boot·python·django·flask·node.js·php
若兰幽竹2 小时前
【从零开始编写数据库:基于Python语言实现数据库ToyDB的ACID特性】
数据库·python
xiaocainiao8812 小时前
Python 实战:构建 Git 自动化助手
git·python·自动化
nightunderblackcat2 小时前
新手向:使用Python将多种图像格式统一转换为JPG
开发语言·python
engchina3 小时前
Python PDF处理库深度对比:PyMuPDF、pypdfium2、pdfplumber、pdfminer的关系与区别
开发语言·python·pdf
Lo-Y-eH3 小时前
Openpyxl:Python操作Excel的利器
python·excel
DAWN_T173 小时前
Transforms
pytorch·python·机器学习·jupyter·pycharm