特殊的bug:element 0 of tensors does not require grad and does not have a grad_fn

发布时间 2023-12-26 11:11:13作者: ZephyrYin

很多帖子都说了,设置requires_grad_()就行。
但是我这次遇到的不一样,设置了都不行。

我是这种情况,在前面设置了torch.no_grad():,又在这个的作用域下进行了requires_grad_(),这是不起作用的。

简单版:

with torch.no_grad():
            model.eval()
            pos_embed = model(homo_data.x, homo_data.edge_index)
						....            
            pos_embed.requires_grad_()# 不起作用
            ....

这样子直接看,傻瓜都不会犯错。而我这个就比较隐蔽了。。。
我的:

# 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

太坑了

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