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

太坑了

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

相关推荐
dudly13 分钟前
Python类的力量:第五篇:魔法方法与协议——让类拥有Python的“超能力”
开发语言·python
攻城狮7号1 小时前
Python爬虫第21节- 基础图形验证码识别实战
开发语言·爬虫·python·图形验证码识别
侃山1 小时前
pytorch nn.RNN demo
pytorch·rnn·深度学习
Francek Chen1 小时前
【现代深度学习技术】注意力机制07:Transformer
人工智能·pytorch·深度学习·神经网络·transformer
kpl_201 小时前
Python基础
开发语言·python
%d%d21 小时前
undefined reference to CPUAllocatorSingleton::instance
bug
啥都鼓捣的小yao2 小时前
课程11. 计算机视觉、自编码器和生成对抗网络 (GAN)
人工智能·python·深度学习·神经网络·算法·生成对抗网络·计算机视觉
dhxhsgrx6 小时前
PYTHON训练营DAY25
java·开发语言·python
伊织code8 小时前
PyTorch API 5 - 全分片数据并行、流水线并行、概率分布
pytorch·python·ai·api·-·5