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

太坑了

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

相关推荐
yaoh.wang1 天前
力扣(LeetCode) 13: 罗马数字转整数 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·跳槽
小鸡吃米…1 天前
Python PyQt6教程七-控件
数据库·python
1916zz1 天前
Extreme programing 方利喆 _ 江贤晟
python
长安牧笛1 天前
智能鞋柜—脚气终结者,内置温湿度传感器和紫外线灯,晚上回家,把鞋放进去,自动检测湿度,湿度超标就启动烘干+紫外线杀菌,第二天穿鞋干燥无异味。
python
weixin_457760001 天前
PIL库将图片位深度是1、8、32统一转换为24的方法
python
Lucky高1 天前
Pandas库入门
python·pandas
小鸡吃米…1 天前
Python PyQt6教程三-菜单与工具栏
开发语言·python
Jack电子实验室1 天前
【杭电HDU】校园网(DeepL/Srun)自动登录教程
python·嵌入式硬件·计算机网络·自动化
木头左1 天前
二值化近似计算在量化交易策略中降低遗忘门运算复杂度
python
Jelena157795857921 天前
Java爬虫淘宝拍立淘item_search_img拍接口示例代码
开发语言·python