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

太坑了

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

相关推荐
Storynone23 分钟前
【Day29】LeetCode:62. 不同路径,63. 不同路径 II,343. 整数拆分,96. 不同的二叉搜索树
python·算法·leetcode
chushiyunen28 分钟前
python语法-继承、方法命名、单例等
开发语言·python
咚咚王者28 分钟前
人工智能之语言领域 自然语言处理 第十八章 Python NLP生态
人工智能·python·自然语言处理
码路飞30 分钟前
AI 写的代码越来越多,但你敢直接上线吗?我的多模型交叉 Review 方案
python·openai
MgArcher31 分钟前
Python 入门核心考点:数据类型与变量全解
python
m0_6625779735 分钟前
自动化机器学习(AutoML)库TPOT使用指南
jvm·数据库·python
q_354888515340 分钟前
计算机毕业设计源码:Python动漫智能推荐与可视化分析系统 Django框架 协同过滤推荐算法 可视化 数据分析 大数据 大模型(建议收藏)✅
python·scrapy·数据分析·django·课程设计·旅游·推荐算法
与虾牵手40 分钟前
写了 8 年 Python 转 Rust,我被所有权机制折磨了整整一周
python
sqyno1sky1 小时前
机器学习模型部署:将模型转化为Web API
jvm·数据库·python
何政@1 小时前
通过python 快速完成ai 构建
人工智能·python·ai·大模型·love l