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

太坑了

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

相关推荐
cuber膜拜2 分钟前
Tenacity 原理与基本使用
服务器·网络·python·装饰器模式·tenacity
Myosotis5133 分钟前
作业 第三次
开发语言·python
cuber膜拜4 分钟前
PyBreaker 原理与基本使用
服务器·网络·python·pybreaker
学Linux的语莫6 分钟前
模型转为RKNN格式
python·深度学习·机器学习
Albert Edison12 分钟前
【Python】文件
android·服务器·python
沉睡的无敌雄狮14 分钟前
可编程数字人落地实践:某省广电用矩阵跃动API重构工作流(选题→政策图谱→方言音色→审稿水印),附Python调度代码
人工智能·python·重构·排序算法·kmeans
junior_Xin24 分钟前
Flask框架beginning4
python·flask
JaydenAI38 分钟前
[拆解LangChain执行引擎] PregelProtocol——定义了"LangChain执行体"最小功能集
python·langchain
qq_370773091 小时前
python实现人脸识别
开发语言·python·opencv
Liue612312311 小时前
胚胎显微图像检测与识别改进Grid-RCNN模型实现
python