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

太坑了

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

相关推荐
啃火龙果的兔子14 小时前
如何使用python开发小游戏
开发语言·python·pygame
爱学习的uu14 小时前
大模型学习1——各类模型接入langchain,模型调用,记忆管理,工具调用
人工智能·python·深度学习·学习·算法·机器学习·langchain
wa的一声哭了14 小时前
赋范空间 赋范空间的完备性
python·线性代数·算法·机器学习·数学建模·矩阵·django
郝学胜-神的一滴15 小时前
Python面向对象编程:解耦、多态与魔法艺术
java·开发语言·c++·python·设计模式·软件工程
AI云原生15 小时前
如何解决 pip install 代理报错 SOCKS5 握手失败 ReadTimeoutError 问题
网络·爬虫·python·网络协议·tcp/ip·scikit-learn·pip
Easonmax15 小时前
从0到1:Qwen-1.8B-Chat 在昇腾Atlas 800T A2上的部署与实战指南前言
人工智能·pytorch·深度学习
cnxy1881 天前
围棋对弈Python程序开发完整指南:步骤4 - 提子逻辑和劫争规则实现
开发语言·python·机器学习
TheSumSt1 天前
Python丨课程笔记Part3:语法进阶部分(控制结构与基础数据结构)
数据结构·笔记·python
ha_lydms1 天前
5、Spark函数_s/t
java·大数据·python·spark·数据处理·maxcompute·spark 函数
电商API&Tina1 天前
跨境电商 API 对接指南:亚马逊 + 速卖通接口调用全流程
大数据·服务器·数据库·python·算法·json·图搜索算法