特殊的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 分钟前
Python爬虫零基础入门【第九章:实战项目教学·第13节】)动态站点“回到接口“:识别接口并用 Requests 重写(更稳)!
爬虫·python·python爬虫实战·python爬虫工程化实战·python爬虫零基础入门·动态站点·识别接口并requests重写
幸福的达哥27 分钟前
Python多线程、多进程、协程、锁、同步、异步的详解和应用
开发语言·python
m0_7066532339 分钟前
Python生成器(Generator)与Yield关键字:惰性求值之美
jvm·数据库·python
熬夜敲代码的小N40 分钟前
Python基础入门:环境配置全指南+核心语法解析
开发语言·python
嫂子开门我是_我哥40 分钟前
第十八节:项目实战2:简易通讯录(面向对象+文件持久化实现)
开发语言·python
乙酸氧铍1 小时前
手机使用 ZeroTermux 调用 python 编辑缩放图像
图像处理·python·智能手机·安卓·termux
逄逄不是胖胖1 小时前
《动手学深度学习》-52文本预处理实现
人工智能·pytorch·python·深度学习
MediaTea1 小时前
Python:_sentinel 命名约定
开发语言·python·sentinel
Pyeako1 小时前
opencv计算机视觉--图形透视(投影)变换&图形拼接
人工智能·python·opencv·计算机视觉·图片拼接·投影变换·图形透视变换
开发者小天1 小时前
python返回随机数
开发语言·python