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

太坑了

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

相关推荐
pluvium2711 分钟前
记对 xonsh shell 的使用, 脚本编写, 迁移及调优
linux·python·shell·xonsh
2401_8274999925 分钟前
python项目实战09-AI智能伴侣(ai_partner_5-6)
开发语言·python
PD我是你的真爱粉27 分钟前
MCP 协议详解:从架构、工作流到 Python 技术栈落地
开发语言·python·架构
ZhengEnCi31 分钟前
P2G-Python字符串方法完全指南-split、join、strip、replace的Python编程利器
python
是小蟹呀^1 小时前
【总结】LangChain中工具的使用
python·langchain·agent·tool
宝贝儿好1 小时前
【LLM】第二章:文本表示:词袋模型、小案例:基于文本的推荐系统(酒店推荐)
人工智能·python·深度学习·神经网络·自然语言处理·机器人·语音识别
王夏奇1 小时前
pythonUI界面弹窗设置的几种办法
python·ui
ZhengEnCi1 小时前
P2B-Python可迭代对象完全指南-从列表到生成器的Python编程利器
python
萌萌站起2 小时前
Vscode 中 python模块的导入问题
ide·vscode·python
是小蟹呀^2 小时前
【总结】提示词工程
python·llm·prompt·agent